From 576cd5a836c050eadff58126443a4beebed87a39 Mon Sep 17 00:00:00 2001 From: Satont Date: Mon, 9 Mar 2026 12:37:51 +0300 Subject: [PATCH 1/4] refactor: use cf workers --- .env.example | 15 +- .gitignore | 2 + .../middleware-insertion-facade.js | 11 + .../bundle-ldhBcJ/middleware-loader.entry.ts | 134 + .wrangler/tmp/dev-FVjRI2/index.js | 32018 ++++++++++++++++ .wrangler/tmp/dev-FVjRI2/index.js.map | 8 + MIGRATION_PLAN.md | 315 + README.md | 183 +- bun.lock | 435 + drizzle.config.ts | 8 + drizzle/0000_init.sql | 50 + drizzle/meta/0000_snapshot.json | 360 + drizzle/meta/0001_snapshot.json | 398 + drizzle/meta/_journal.json | 20 + locales/en.json | 7 +- locales/ru.json | 4 + locales/uk.json | 4 + package.json | 40 + src/bot/commands/broadcast.command.ts | 48 + src/bot/commands/callback.handler.ts | 74 + src/bot/commands/change-channel-id.command.ts | 45 + src/bot/commands/follow.command.ts | 121 + src/bot/commands/follows.command.ts | 37 + src/bot/commands/index.ts | 7 + src/bot/commands/live.command.ts | 102 + src/bot/commands/start.command.ts | 28 + src/bot/helpers.ts | 184 + src/bot/index.ts | 71 + src/bot/storage.ts | 47 + src/bot/types.ts | 33 + src/db/connection.ts | 20 + src/db/index.ts | 3 + src/db/repositories/cloudflare-kv/index.ts | 1 + .../cloudflare-kv/session.kv.repository.ts | 38 + .../drizzle/channel.drizzle.repository.ts | 65 + .../drizzle/chat.drizzle.repository.ts | 104 + .../drizzle/follow.drizzle.repository.ts | 82 + src/db/repositories/drizzle/index.ts | 4 + .../drizzle/stream.drizzle.repository.ts | 60 + src/db/repositories/index.ts | 20 + .../channel.repository.interface.ts | 10 + .../interfaces/chat.repository.interface.ts | 9 + .../interfaces/follow.repository.interface.ts | 11 + src/db/repositories/interfaces/index.ts | 5 + .../session.repository.interface.ts | 6 + .../interfaces/stream.repository.interface.ts | 15 + src/db/repository.factory.ts | 44 + src/db/schema.ts | 108 + src/domain/mapper.ts | 63 + src/domain/models.ts | 174 + src/index.ts | 77 + src/services/eventsub.service.ts | 129 + src/services/i18n.service.ts | 84 + src/services/index.ts | 5 + src/services/notification.service.ts | 210 + src/services/telegram.service.ts | 163 + src/services/twitch.service.ts | 56 + src/types/env.ts | 21 + src/types/index.ts | 1 + src/utils/index.ts | 1 + src/utils/thumbnail.ts | 62 + src/webhooks/twitch.ts | 186 + tsconfig.json | 21 + wrangler.example.toml | 43 + 64 files changed, 36668 insertions(+), 42 deletions(-) create mode 100644 .wrangler/tmp/bundle-ldhBcJ/middleware-insertion-facade.js create mode 100644 .wrangler/tmp/bundle-ldhBcJ/middleware-loader.entry.ts create mode 100644 .wrangler/tmp/dev-FVjRI2/index.js create mode 100644 .wrangler/tmp/dev-FVjRI2/index.js.map create mode 100644 MIGRATION_PLAN.md create mode 100644 bun.lock create mode 100644 drizzle.config.ts create mode 100644 drizzle/0000_init.sql create mode 100644 drizzle/meta/0000_snapshot.json create mode 100644 drizzle/meta/0001_snapshot.json create mode 100644 drizzle/meta/_journal.json create mode 100644 package.json create mode 100644 src/bot/commands/broadcast.command.ts create mode 100644 src/bot/commands/callback.handler.ts create mode 100644 src/bot/commands/change-channel-id.command.ts create mode 100644 src/bot/commands/follow.command.ts create mode 100644 src/bot/commands/follows.command.ts create mode 100644 src/bot/commands/index.ts create mode 100644 src/bot/commands/live.command.ts create mode 100644 src/bot/commands/start.command.ts create mode 100644 src/bot/helpers.ts create mode 100644 src/bot/index.ts create mode 100644 src/bot/storage.ts create mode 100644 src/bot/types.ts create mode 100644 src/db/connection.ts create mode 100644 src/db/index.ts create mode 100644 src/db/repositories/cloudflare-kv/index.ts create mode 100644 src/db/repositories/cloudflare-kv/session.kv.repository.ts create mode 100644 src/db/repositories/drizzle/channel.drizzle.repository.ts create mode 100644 src/db/repositories/drizzle/chat.drizzle.repository.ts create mode 100644 src/db/repositories/drizzle/follow.drizzle.repository.ts create mode 100644 src/db/repositories/drizzle/index.ts create mode 100644 src/db/repositories/drizzle/stream.drizzle.repository.ts create mode 100644 src/db/repositories/index.ts create mode 100644 src/db/repositories/interfaces/channel.repository.interface.ts create mode 100644 src/db/repositories/interfaces/chat.repository.interface.ts create mode 100644 src/db/repositories/interfaces/follow.repository.interface.ts create mode 100644 src/db/repositories/interfaces/index.ts create mode 100644 src/db/repositories/interfaces/session.repository.interface.ts create mode 100644 src/db/repositories/interfaces/stream.repository.interface.ts create mode 100644 src/db/repository.factory.ts create mode 100644 src/db/schema.ts create mode 100644 src/domain/mapper.ts create mode 100644 src/domain/models.ts create mode 100644 src/index.ts create mode 100644 src/services/eventsub.service.ts create mode 100644 src/services/i18n.service.ts create mode 100644 src/services/index.ts create mode 100644 src/services/notification.service.ts create mode 100644 src/services/telegram.service.ts create mode 100644 src/services/twitch.service.ts create mode 100644 src/types/env.ts create mode 100644 src/types/index.ts create mode 100644 src/utils/index.ts create mode 100644 src/utils/thumbnail.ts create mode 100644 src/webhooks/twitch.ts create mode 100644 tsconfig.json create mode 100644 wrangler.example.toml diff --git a/.env.example b/.env.example index ddca089c..ad3d4ac1 100644 --- a/.env.example +++ b/.env.example @@ -1,8 +1,7 @@ -# twitch app data -TWITCH_CLIENTID= -TWITCH_CLIENTSECRET= -# telegram bot token -TELEGRAM_TOKEN= -# ids, separated by command -TELEGRAM_BOT_ADMINS= -DATABASE_URL=postgres://test:test@localhost:54326/test?sslmode= +# Environment variables template +TELEGRAM_TOKEN=your_telegram_bot_token +TWITCH_CLIENT_ID=your_twitch_client_id +TWITCH_CLIENT_SECRET=your_twitch_client_secret +TELEGRAM_BOT_ADMINS=123456789,987654321 +TWITCH_EVENTSUB_SECRET=your_random_secret_string +BASE_URL=https://your-worker.workers.dev diff --git a/.gitignore b/.gitignore index c03420e4..4ae3dc57 100644 --- a/.gitignore +++ b/.gitignore @@ -8,3 +8,5 @@ ent/**/* !ent/generate.go .vscode .DS_Store +wrangler.toml +node_modules diff --git a/.wrangler/tmp/bundle-ldhBcJ/middleware-insertion-facade.js b/.wrangler/tmp/bundle-ldhBcJ/middleware-insertion-facade.js new file mode 100644 index 00000000..ea2d7d47 --- /dev/null +++ b/.wrangler/tmp/bundle-ldhBcJ/middleware-insertion-facade.js @@ -0,0 +1,11 @@ + import worker, * as OTHER_EXPORTS from "/home/satont/Projects/twitch-notifier/src/index.ts"; + import * as __MIDDLEWARE_0__ from "/home/satont/Projects/twitch-notifier/node_modules/.pnpm/wrangler@4.71.0_@cloudflare+workers-types@4.20260307.1/node_modules/wrangler/templates/middleware/middleware-ensure-req-body-drained.ts"; +import * as __MIDDLEWARE_1__ from "/home/satont/Projects/twitch-notifier/node_modules/.pnpm/wrangler@4.71.0_@cloudflare+workers-types@4.20260307.1/node_modules/wrangler/templates/middleware/middleware-miniflare3-json-error.ts"; + + export * from "/home/satont/Projects/twitch-notifier/src/index.ts"; + const MIDDLEWARE_TEST_INJECT = "__INJECT_FOR_TESTING_WRANGLER_MIDDLEWARE__"; + export const __INTERNAL_WRANGLER_MIDDLEWARE__ = [ + + __MIDDLEWARE_0__.default,__MIDDLEWARE_1__.default + ] + export default worker; \ No newline at end of file diff --git a/.wrangler/tmp/bundle-ldhBcJ/middleware-loader.entry.ts b/.wrangler/tmp/bundle-ldhBcJ/middleware-loader.entry.ts new file mode 100644 index 00000000..1bfe275f --- /dev/null +++ b/.wrangler/tmp/bundle-ldhBcJ/middleware-loader.entry.ts @@ -0,0 +1,134 @@ +// This loads all middlewares exposed on the middleware object and then starts +// the invocation chain. The big idea is that we can add these to the middleware +// export dynamically through wrangler, or we can potentially let users directly +// add them as a sort of "plugin" system. + +import ENTRY, { __INTERNAL_WRANGLER_MIDDLEWARE__ } from "/home/satont/Projects/twitch-notifier/.wrangler/tmp/bundle-ldhBcJ/middleware-insertion-facade.js"; +import { __facade_invoke__, __facade_register__, Dispatcher } from "/home/satont/Projects/twitch-notifier/node_modules/.pnpm/wrangler@4.71.0_@cloudflare+workers-types@4.20260307.1/node_modules/wrangler/templates/middleware/common.ts"; +import type { WorkerEntrypointConstructor } from "/home/satont/Projects/twitch-notifier/.wrangler/tmp/bundle-ldhBcJ/middleware-insertion-facade.js"; + +// Preserve all the exports from the worker +export * from "/home/satont/Projects/twitch-notifier/.wrangler/tmp/bundle-ldhBcJ/middleware-insertion-facade.js"; + +class __Facade_ScheduledController__ implements ScheduledController { + readonly #noRetry: ScheduledController["noRetry"]; + + constructor( + readonly scheduledTime: number, + readonly cron: string, + noRetry: ScheduledController["noRetry"] + ) { + this.#noRetry = noRetry; + } + + noRetry() { + if (!(this instanceof __Facade_ScheduledController__)) { + throw new TypeError("Illegal invocation"); + } + // Need to call native method immediately in case uncaught error thrown + this.#noRetry(); + } +} + +function wrapExportedHandler(worker: ExportedHandler): ExportedHandler { + // If we don't have any middleware defined, just return the handler as is + if ( + __INTERNAL_WRANGLER_MIDDLEWARE__ === undefined || + __INTERNAL_WRANGLER_MIDDLEWARE__.length === 0 + ) { + return worker; + } + // Otherwise, register all middleware once + for (const middleware of __INTERNAL_WRANGLER_MIDDLEWARE__) { + __facade_register__(middleware); + } + + const fetchDispatcher: ExportedHandlerFetchHandler = function ( + request, + env, + ctx + ) { + if (worker.fetch === undefined) { + throw new Error("Handler does not export a fetch() function."); + } + return worker.fetch(request, env, ctx); + }; + + return { + ...worker, + fetch(request, env, ctx) { + const dispatcher: Dispatcher = function (type, init) { + if (type === "scheduled" && worker.scheduled !== undefined) { + const controller = new __Facade_ScheduledController__( + Date.now(), + init.cron ?? "", + () => {} + ); + return worker.scheduled(controller, env, ctx); + } + }; + return __facade_invoke__(request, env, ctx, dispatcher, fetchDispatcher); + }, + }; +} + +function wrapWorkerEntrypoint( + klass: WorkerEntrypointConstructor +): WorkerEntrypointConstructor { + // If we don't have any middleware defined, just return the handler as is + if ( + __INTERNAL_WRANGLER_MIDDLEWARE__ === undefined || + __INTERNAL_WRANGLER_MIDDLEWARE__.length === 0 + ) { + return klass; + } + // Otherwise, register all middleware once + for (const middleware of __INTERNAL_WRANGLER_MIDDLEWARE__) { + __facade_register__(middleware); + } + + // `extend`ing `klass` here so other RPC methods remain callable + return class extends klass { + #fetchDispatcher: ExportedHandlerFetchHandler> = ( + request, + env, + ctx + ) => { + this.env = env; + this.ctx = ctx; + if (super.fetch === undefined) { + throw new Error("Entrypoint class does not define a fetch() function."); + } + return super.fetch(request); + }; + + #dispatcher: Dispatcher = (type, init) => { + if (type === "scheduled" && super.scheduled !== undefined) { + const controller = new __Facade_ScheduledController__( + Date.now(), + init.cron ?? "", + () => {} + ); + return super.scheduled(controller); + } + }; + + fetch(request: Request) { + return __facade_invoke__( + request, + this.env, + this.ctx, + this.#dispatcher, + this.#fetchDispatcher + ); + } + }; +} + +let WRAPPED_ENTRY: ExportedHandler | WorkerEntrypointConstructor | undefined; +if (typeof ENTRY === "object") { + WRAPPED_ENTRY = wrapExportedHandler(ENTRY); +} else if (typeof ENTRY === "function") { + WRAPPED_ENTRY = wrapWorkerEntrypoint(ENTRY); +} +export default WRAPPED_ENTRY; diff --git a/.wrangler/tmp/dev-FVjRI2/index.js b/.wrangler/tmp/dev-FVjRI2/index.js new file mode 100644 index 00000000..8d15d671 --- /dev/null +++ b/.wrangler/tmp/dev-FVjRI2/index.js @@ -0,0 +1,32018 @@ +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __esm = (fn, res) => function __init() { + return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res; +}; +var __commonJS = (cb, mod) => function __require() { + return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; +}; +var __copyProps = (to, from, except2, desc2) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except2) + __defProp(to, key, { get: () => from[key], enumerable: !(desc2 = __getOwnPropDesc(from, key)) || desc2.enumerable }); + } + return to; +}; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); + +// node_modules/.pnpm/unenv@2.0.0-rc.24/node_modules/unenv/dist/runtime/_internal/utils.mjs +// @__NO_SIDE_EFFECTS__ +function createNotImplementedError(name) { + return new Error(`[unenv] ${name} is not implemented yet!`); +} +var init_utils = __esm({ + "node_modules/.pnpm/unenv@2.0.0-rc.24/node_modules/unenv/dist/runtime/_internal/utils.mjs"() { + init_modules_watch_stub(); + init_performance2(); + __name(createNotImplementedError, "createNotImplementedError"); + } +}); + +// node_modules/.pnpm/unenv@2.0.0-rc.24/node_modules/unenv/dist/runtime/node/internal/perf_hooks/performance.mjs +var _timeOrigin, _performanceNow, nodeTiming, PerformanceEntry, PerformanceMark, PerformanceMeasure, PerformanceResourceTiming, PerformanceObserverEntryList, Performance, PerformanceObserver, performance; +var init_performance = __esm({ + "node_modules/.pnpm/unenv@2.0.0-rc.24/node_modules/unenv/dist/runtime/node/internal/perf_hooks/performance.mjs"() { + init_modules_watch_stub(); + init_performance2(); + init_utils(); + _timeOrigin = globalThis.performance?.timeOrigin ?? Date.now(); + _performanceNow = globalThis.performance?.now ? globalThis.performance.now.bind(globalThis.performance) : () => Date.now() - _timeOrigin; + nodeTiming = { + name: "node", + entryType: "node", + startTime: 0, + duration: 0, + nodeStart: 0, + v8Start: 0, + bootstrapComplete: 0, + environment: 0, + loopStart: 0, + loopExit: 0, + idleTime: 0, + uvMetricsInfo: { + loopCount: 0, + events: 0, + eventsWaiting: 0 + }, + detail: void 0, + toJSON() { + return this; + } + }; + PerformanceEntry = class { + static { + __name(this, "PerformanceEntry"); + } + __unenv__ = true; + detail; + entryType = "event"; + name; + startTime; + constructor(name, options) { + this.name = name; + this.startTime = options?.startTime || _performanceNow(); + this.detail = options?.detail; + } + get duration() { + return _performanceNow() - this.startTime; + } + toJSON() { + return { + name: this.name, + entryType: this.entryType, + startTime: this.startTime, + duration: this.duration, + detail: this.detail + }; + } + }; + PerformanceMark = class PerformanceMark2 extends PerformanceEntry { + static { + __name(this, "PerformanceMark"); + } + entryType = "mark"; + constructor() { + super(...arguments); + } + get duration() { + return 0; + } + }; + PerformanceMeasure = class extends PerformanceEntry { + static { + __name(this, "PerformanceMeasure"); + } + entryType = "measure"; + }; + PerformanceResourceTiming = class extends PerformanceEntry { + static { + __name(this, "PerformanceResourceTiming"); + } + entryType = "resource"; + serverTiming = []; + connectEnd = 0; + connectStart = 0; + decodedBodySize = 0; + domainLookupEnd = 0; + domainLookupStart = 0; + encodedBodySize = 0; + fetchStart = 0; + initiatorType = ""; + name = ""; + nextHopProtocol = ""; + redirectEnd = 0; + redirectStart = 0; + requestStart = 0; + responseEnd = 0; + responseStart = 0; + secureConnectionStart = 0; + startTime = 0; + transferSize = 0; + workerStart = 0; + responseStatus = 0; + }; + PerformanceObserverEntryList = class { + static { + __name(this, "PerformanceObserverEntryList"); + } + __unenv__ = true; + getEntries() { + return []; + } + getEntriesByName(_name, _type) { + return []; + } + getEntriesByType(type) { + return []; + } + }; + Performance = class { + static { + __name(this, "Performance"); + } + __unenv__ = true; + timeOrigin = _timeOrigin; + eventCounts = /* @__PURE__ */ new Map(); + _entries = []; + _resourceTimingBufferSize = 0; + navigation = void 0; + timing = void 0; + timerify(_fn, _options) { + throw createNotImplementedError("Performance.timerify"); + } + get nodeTiming() { + return nodeTiming; + } + eventLoopUtilization() { + return {}; + } + markResourceTiming() { + return new PerformanceResourceTiming(""); + } + onresourcetimingbufferfull = null; + now() { + if (this.timeOrigin === _timeOrigin) { + return _performanceNow(); + } + return Date.now() - this.timeOrigin; + } + clearMarks(markName) { + this._entries = markName ? this._entries.filter((e) => e.name !== markName) : this._entries.filter((e) => e.entryType !== "mark"); + } + clearMeasures(measureName) { + this._entries = measureName ? this._entries.filter((e) => e.name !== measureName) : this._entries.filter((e) => e.entryType !== "measure"); + } + clearResourceTimings() { + this._entries = this._entries.filter((e) => e.entryType !== "resource" || e.entryType !== "navigation"); + } + getEntries() { + return this._entries; + } + getEntriesByName(name, type) { + return this._entries.filter((e) => e.name === name && (!type || e.entryType === type)); + } + getEntriesByType(type) { + return this._entries.filter((e) => e.entryType === type); + } + mark(name, options) { + const entry = new PerformanceMark(name, options); + this._entries.push(entry); + return entry; + } + measure(measureName, startOrMeasureOptions, endMark) { + let start; + let end; + if (typeof startOrMeasureOptions === "string") { + start = this.getEntriesByName(startOrMeasureOptions, "mark")[0]?.startTime; + end = this.getEntriesByName(endMark, "mark")[0]?.startTime; + } else { + start = Number.parseFloat(startOrMeasureOptions?.start) || this.now(); + end = Number.parseFloat(startOrMeasureOptions?.end) || this.now(); + } + const entry = new PerformanceMeasure(measureName, { + startTime: start, + detail: { + start, + end + } + }); + this._entries.push(entry); + return entry; + } + setResourceTimingBufferSize(maxSize) { + this._resourceTimingBufferSize = maxSize; + } + addEventListener(type, listener, options) { + throw createNotImplementedError("Performance.addEventListener"); + } + removeEventListener(type, listener, options) { + throw createNotImplementedError("Performance.removeEventListener"); + } + dispatchEvent(event) { + throw createNotImplementedError("Performance.dispatchEvent"); + } + toJSON() { + return this; + } + }; + PerformanceObserver = class { + static { + __name(this, "PerformanceObserver"); + } + __unenv__ = true; + static supportedEntryTypes = []; + _callback = null; + constructor(callback) { + this._callback = callback; + } + takeRecords() { + return []; + } + disconnect() { + throw createNotImplementedError("PerformanceObserver.disconnect"); + } + observe(options) { + throw createNotImplementedError("PerformanceObserver.observe"); + } + bind(fn) { + return fn; + } + runInAsyncScope(fn, thisArg, ...args) { + return fn.call(thisArg, ...args); + } + asyncId() { + return 0; + } + triggerAsyncId() { + return 0; + } + emitDestroy() { + return this; + } + }; + performance = globalThis.performance && "addEventListener" in globalThis.performance ? globalThis.performance : new Performance(); + } +}); + +// node_modules/.pnpm/unenv@2.0.0-rc.24/node_modules/unenv/dist/runtime/node/perf_hooks.mjs +var init_perf_hooks = __esm({ + "node_modules/.pnpm/unenv@2.0.0-rc.24/node_modules/unenv/dist/runtime/node/perf_hooks.mjs"() { + init_modules_watch_stub(); + init_performance2(); + init_performance(); + } +}); + +// node_modules/.pnpm/@cloudflare+unenv-preset@2.15.0_unenv@2.0.0-rc.24_workerd@1.20260301.1/node_modules/@cloudflare/unenv-preset/dist/runtime/polyfill/performance.mjs +var init_performance2 = __esm({ + "node_modules/.pnpm/@cloudflare+unenv-preset@2.15.0_unenv@2.0.0-rc.24_workerd@1.20260301.1/node_modules/@cloudflare/unenv-preset/dist/runtime/polyfill/performance.mjs"() { + init_perf_hooks(); + globalThis.performance = performance; + globalThis.Performance = Performance; + globalThis.PerformanceEntry = PerformanceEntry; + globalThis.PerformanceMark = PerformanceMark; + globalThis.PerformanceMeasure = PerformanceMeasure; + globalThis.PerformanceObserver = PerformanceObserver; + globalThis.PerformanceObserverEntryList = PerformanceObserverEntryList; + globalThis.PerformanceResourceTiming = PerformanceResourceTiming; + } +}); + +// wrangler-modules-watch:wrangler:modules-watch +var init_wrangler_modules_watch = __esm({ + "wrangler-modules-watch:wrangler:modules-watch"() { + init_modules_watch_stub(); + init_performance2(); + } +}); + +// node_modules/.pnpm/wrangler@4.71.0_@cloudflare+workers-types@4.20260307.1/node_modules/wrangler/templates/modules-watch-stub.js +var init_modules_watch_stub = __esm({ + "node_modules/.pnpm/wrangler@4.71.0_@cloudflare+workers-types@4.20260307.1/node_modules/wrangler/templates/modules-watch-stub.js"() { + init_wrangler_modules_watch(); + } +}); + +// node_modules/.pnpm/@d-fischer+detect-node@3.0.1/node_modules/@d-fischer/detect-node/browser.js +var require_browser = __commonJS({ + "node_modules/.pnpm/@d-fischer+detect-node@3.0.1/node_modules/@d-fischer/detect-node/browser.js"(exports, module) { + init_modules_watch_stub(); + init_performance2(); + module.exports.isNode = false; + } +}); + +// node_modules/.pnpm/retry@0.13.1/node_modules/retry/lib/retry_operation.js +var require_retry_operation = __commonJS({ + "node_modules/.pnpm/retry@0.13.1/node_modules/retry/lib/retry_operation.js"(exports, module) { + init_modules_watch_stub(); + init_performance2(); + function RetryOperation(timeouts, options) { + if (typeof options === "boolean") { + options = { forever: options }; + } + this._originalTimeouts = JSON.parse(JSON.stringify(timeouts)); + this._timeouts = timeouts; + this._options = options || {}; + this._maxRetryTime = options && options.maxRetryTime || Infinity; + this._fn = null; + this._errors = []; + this._attempts = 1; + this._operationTimeout = null; + this._operationTimeoutCb = null; + this._timeout = null; + this._operationStart = null; + this._timer = null; + if (this._options.forever) { + this._cachedTimeouts = this._timeouts.slice(0); + } + } + __name(RetryOperation, "RetryOperation"); + module.exports = RetryOperation; + RetryOperation.prototype.reset = function() { + this._attempts = 1; + this._timeouts = this._originalTimeouts.slice(0); + }; + RetryOperation.prototype.stop = function() { + if (this._timeout) { + clearTimeout(this._timeout); + } + if (this._timer) { + clearTimeout(this._timer); + } + this._timeouts = []; + this._cachedTimeouts = null; + }; + RetryOperation.prototype.retry = function(err) { + if (this._timeout) { + clearTimeout(this._timeout); + } + if (!err) { + return false; + } + var currentTime = (/* @__PURE__ */ new Date()).getTime(); + if (err && currentTime - this._operationStart >= this._maxRetryTime) { + this._errors.push(err); + this._errors.unshift(new Error("RetryOperation timeout occurred")); + return false; + } + this._errors.push(err); + var timeout = this._timeouts.shift(); + if (timeout === void 0) { + if (this._cachedTimeouts) { + this._errors.splice(0, this._errors.length - 1); + timeout = this._cachedTimeouts.slice(-1); + } else { + return false; + } + } + var self2 = this; + this._timer = setTimeout(function() { + self2._attempts++; + if (self2._operationTimeoutCb) { + self2._timeout = setTimeout(function() { + self2._operationTimeoutCb(self2._attempts); + }, self2._operationTimeout); + if (self2._options.unref) { + self2._timeout.unref(); + } + } + self2._fn(self2._attempts); + }, timeout); + if (this._options.unref) { + this._timer.unref(); + } + return true; + }; + RetryOperation.prototype.attempt = function(fn, timeoutOps) { + this._fn = fn; + if (timeoutOps) { + if (timeoutOps.timeout) { + this._operationTimeout = timeoutOps.timeout; + } + if (timeoutOps.cb) { + this._operationTimeoutCb = timeoutOps.cb; + } + } + var self2 = this; + if (this._operationTimeoutCb) { + this._timeout = setTimeout(function() { + self2._operationTimeoutCb(); + }, self2._operationTimeout); + } + this._operationStart = (/* @__PURE__ */ new Date()).getTime(); + this._fn(this._attempts); + }; + RetryOperation.prototype.try = function(fn) { + console.log("Using RetryOperation.try() is deprecated"); + this.attempt(fn); + }; + RetryOperation.prototype.start = function(fn) { + console.log("Using RetryOperation.start() is deprecated"); + this.attempt(fn); + }; + RetryOperation.prototype.start = RetryOperation.prototype.try; + RetryOperation.prototype.errors = function() { + return this._errors; + }; + RetryOperation.prototype.attempts = function() { + return this._attempts; + }; + RetryOperation.prototype.mainError = function() { + if (this._errors.length === 0) { + return null; + } + var counts = {}; + var mainError = null; + var mainErrorCount = 0; + for (var i = 0; i < this._errors.length; i++) { + var error = this._errors[i]; + var message = error.message; + var count2 = (counts[message] || 0) + 1; + counts[message] = count2; + if (count2 >= mainErrorCount) { + mainError = error; + mainErrorCount = count2; + } + } + return mainError; + }; + } +}); + +// node_modules/.pnpm/retry@0.13.1/node_modules/retry/lib/retry.js +var require_retry = __commonJS({ + "node_modules/.pnpm/retry@0.13.1/node_modules/retry/lib/retry.js"(exports) { + init_modules_watch_stub(); + init_performance2(); + var RetryOperation = require_retry_operation(); + exports.operation = function(options) { + var timeouts = exports.timeouts(options); + return new RetryOperation(timeouts, { + forever: options && (options.forever || options.retries === Infinity), + unref: options && options.unref, + maxRetryTime: options && options.maxRetryTime + }); + }; + exports.timeouts = function(options) { + if (options instanceof Array) { + return [].concat(options); + } + var opts = { + retries: 10, + factor: 2, + minTimeout: 1 * 1e3, + maxTimeout: Infinity, + randomize: false + }; + for (var key in options) { + opts[key] = options[key]; + } + if (opts.minTimeout > opts.maxTimeout) { + throw new Error("minTimeout is greater than maxTimeout"); + } + var timeouts = []; + for (var i = 0; i < opts.retries; i++) { + timeouts.push(this.createTimeout(i, opts)); + } + if (options && options.forever && !timeouts.length) { + timeouts.push(this.createTimeout(i, opts)); + } + timeouts.sort(function(a, b) { + return a - b; + }); + return timeouts; + }; + exports.createTimeout = function(attempt, opts) { + var random = opts.randomize ? Math.random() + 1 : 1; + var timeout = Math.round(random * Math.max(opts.minTimeout, 1) * Math.pow(opts.factor, attempt)); + timeout = Math.min(timeout, opts.maxTimeout); + return timeout; + }; + exports.wrap = function(obj, options, methods) { + if (options instanceof Array) { + methods = options; + options = null; + } + if (!methods) { + methods = []; + for (var key in obj) { + if (typeof obj[key] === "function") { + methods.push(key); + } + } + } + for (var i = 0; i < methods.length; i++) { + var method = methods[i]; + var original = obj[method]; + obj[method] = (/* @__PURE__ */ __name(function retryWrapper(original2) { + var op = exports.operation(options); + var args = Array.prototype.slice.call(arguments, 1); + var callback = args.pop(); + args.push(function(err) { + if (op.retry(err)) { + return; + } + if (err) { + arguments[0] = op.mainError(); + } + callback.apply(this, arguments); + }); + op.attempt(function() { + original2.apply(obj, args); + }); + }, "retryWrapper")).bind(obj, original); + obj[method].options = options; + } + }; + } +}); + +// node_modules/.pnpm/retry@0.13.1/node_modules/retry/index.js +var require_retry2 = __commonJS({ + "node_modules/.pnpm/retry@0.13.1/node_modules/retry/index.js"(exports, module) { + init_modules_watch_stub(); + init_performance2(); + module.exports = require_retry(); + } +}); + +// .wrangler/tmp/bundle-ldhBcJ/middleware-loader.entry.ts +init_modules_watch_stub(); +init_performance2(); + +// .wrangler/tmp/bundle-ldhBcJ/middleware-insertion-facade.js +init_modules_watch_stub(); +init_performance2(); + +// src/index.ts +init_modules_watch_stub(); +init_performance2(); + +// node_modules/.pnpm/hono@4.12.5/node_modules/hono/dist/index.js +init_modules_watch_stub(); +init_performance2(); + +// node_modules/.pnpm/hono@4.12.5/node_modules/hono/dist/hono.js +init_modules_watch_stub(); +init_performance2(); + +// node_modules/.pnpm/hono@4.12.5/node_modules/hono/dist/hono-base.js +init_modules_watch_stub(); +init_performance2(); + +// node_modules/.pnpm/hono@4.12.5/node_modules/hono/dist/compose.js +init_modules_watch_stub(); +init_performance2(); +var compose = /* @__PURE__ */ __name((middleware, onError, onNotFound) => { + return (context, next) => { + let index = -1; + return dispatch(0); + async function dispatch(i) { + if (i <= index) { + throw new Error("next() called multiple times"); + } + index = i; + let res; + let isError = false; + let handler; + if (middleware[i]) { + handler = middleware[i][0][0]; + context.req.routeIndex = i; + } else { + handler = i === middleware.length && next || void 0; + } + if (handler) { + try { + res = await handler(context, () => dispatch(i + 1)); + } catch (err) { + if (err instanceof Error && onError) { + context.error = err; + res = await onError(err, context); + isError = true; + } else { + throw err; + } + } + } else { + if (context.finalized === false && onNotFound) { + res = await onNotFound(context); + } + } + if (res && (context.finalized === false || isError)) { + context.res = res; + } + return context; + } + __name(dispatch, "dispatch"); + }; +}, "compose"); + +// node_modules/.pnpm/hono@4.12.5/node_modules/hono/dist/context.js +init_modules_watch_stub(); +init_performance2(); + +// node_modules/.pnpm/hono@4.12.5/node_modules/hono/dist/request.js +init_modules_watch_stub(); +init_performance2(); + +// node_modules/.pnpm/hono@4.12.5/node_modules/hono/dist/http-exception.js +init_modules_watch_stub(); +init_performance2(); + +// node_modules/.pnpm/hono@4.12.5/node_modules/hono/dist/request/constants.js +init_modules_watch_stub(); +init_performance2(); +var GET_MATCH_RESULT = /* @__PURE__ */ Symbol(); + +// node_modules/.pnpm/hono@4.12.5/node_modules/hono/dist/utils/body.js +init_modules_watch_stub(); +init_performance2(); +var parseBody = /* @__PURE__ */ __name(async (request, options = /* @__PURE__ */ Object.create(null)) => { + const { all = false, dot = false } = options; + const headers = request instanceof HonoRequest ? request.raw.headers : request.headers; + const contentType = headers.get("Content-Type"); + if (contentType?.startsWith("multipart/form-data") || contentType?.startsWith("application/x-www-form-urlencoded")) { + return parseFormData(request, { all, dot }); + } + return {}; +}, "parseBody"); +async function parseFormData(request, options) { + const formData = await request.formData(); + if (formData) { + return convertFormDataToBodyData(formData, options); + } + return {}; +} +__name(parseFormData, "parseFormData"); +function convertFormDataToBodyData(formData, options) { + const form = /* @__PURE__ */ Object.create(null); + formData.forEach((value, key) => { + const shouldParseAllValues = options.all || key.endsWith("[]"); + if (!shouldParseAllValues) { + form[key] = value; + } else { + handleParsingAllValues(form, key, value); + } + }); + if (options.dot) { + Object.entries(form).forEach(([key, value]) => { + const shouldParseDotValues = key.includes("."); + if (shouldParseDotValues) { + handleParsingNestedValues(form, key, value); + delete form[key]; + } + }); + } + return form; +} +__name(convertFormDataToBodyData, "convertFormDataToBodyData"); +var handleParsingAllValues = /* @__PURE__ */ __name((form, key, value) => { + if (form[key] !== void 0) { + if (Array.isArray(form[key])) { + ; + form[key].push(value); + } else { + form[key] = [form[key], value]; + } + } else { + if (!key.endsWith("[]")) { + form[key] = value; + } else { + form[key] = [value]; + } + } +}, "handleParsingAllValues"); +var handleParsingNestedValues = /* @__PURE__ */ __name((form, key, value) => { + let nestedForm = form; + const keys = key.split("."); + keys.forEach((key2, index) => { + if (index === keys.length - 1) { + nestedForm[key2] = value; + } else { + if (!nestedForm[key2] || typeof nestedForm[key2] !== "object" || Array.isArray(nestedForm[key2]) || nestedForm[key2] instanceof File) { + nestedForm[key2] = /* @__PURE__ */ Object.create(null); + } + nestedForm = nestedForm[key2]; + } + }); +}, "handleParsingNestedValues"); + +// node_modules/.pnpm/hono@4.12.5/node_modules/hono/dist/utils/url.js +init_modules_watch_stub(); +init_performance2(); +var splitPath = /* @__PURE__ */ __name((path) => { + const paths = path.split("/"); + if (paths[0] === "") { + paths.shift(); + } + return paths; +}, "splitPath"); +var splitRoutingPath = /* @__PURE__ */ __name((routePath) => { + const { groups, path } = extractGroupsFromPath(routePath); + const paths = splitPath(path); + return replaceGroupMarks(paths, groups); +}, "splitRoutingPath"); +var extractGroupsFromPath = /* @__PURE__ */ __name((path) => { + const groups = []; + path = path.replace(/\{[^}]+\}/g, (match3, index) => { + const mark = `@${index}`; + groups.push([mark, match3]); + return mark; + }); + return { groups, path }; +}, "extractGroupsFromPath"); +var replaceGroupMarks = /* @__PURE__ */ __name((paths, groups) => { + for (let i = groups.length - 1; i >= 0; i--) { + const [mark] = groups[i]; + for (let j = paths.length - 1; j >= 0; j--) { + if (paths[j].includes(mark)) { + paths[j] = paths[j].replace(mark, groups[i][1]); + break; + } + } + } + return paths; +}, "replaceGroupMarks"); +var patternCache = {}; +var getPattern = /* @__PURE__ */ __name((label, next) => { + if (label === "*") { + return "*"; + } + const match3 = label.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/); + if (match3) { + const cacheKey = `${label}#${next}`; + if (!patternCache[cacheKey]) { + if (match3[2]) { + patternCache[cacheKey] = next && next[0] !== ":" && next[0] !== "*" ? [cacheKey, match3[1], new RegExp(`^${match3[2]}(?=/${next})`)] : [label, match3[1], new RegExp(`^${match3[2]}$`)]; + } else { + patternCache[cacheKey] = [label, match3[1], true]; + } + } + return patternCache[cacheKey]; + } + return null; +}, "getPattern"); +var tryDecode = /* @__PURE__ */ __name((str2, decoder) => { + try { + return decoder(str2); + } catch { + return str2.replace(/(?:%[0-9A-Fa-f]{2})+/g, (match3) => { + try { + return decoder(match3); + } catch { + return match3; + } + }); + } +}, "tryDecode"); +var tryDecodeURI = /* @__PURE__ */ __name((str2) => tryDecode(str2, decodeURI), "tryDecodeURI"); +var getPath = /* @__PURE__ */ __name((request) => { + const url = request.url; + const start = url.indexOf("/", url.indexOf(":") + 4); + let i = start; + for (; i < url.length; i++) { + const charCode = url.charCodeAt(i); + if (charCode === 37) { + const queryIndex = url.indexOf("?", i); + const hashIndex = url.indexOf("#", i); + const end = queryIndex === -1 ? hashIndex === -1 ? void 0 : hashIndex : hashIndex === -1 ? queryIndex : Math.min(queryIndex, hashIndex); + const path = url.slice(start, end); + return tryDecodeURI(path.includes("%25") ? path.replace(/%25/g, "%2525") : path); + } else if (charCode === 63 || charCode === 35) { + break; + } + } + return url.slice(start, i); +}, "getPath"); +var getPathNoStrict = /* @__PURE__ */ __name((request) => { + const result = getPath(request); + return result.length > 1 && result.at(-1) === "/" ? result.slice(0, -1) : result; +}, "getPathNoStrict"); +var mergePath = /* @__PURE__ */ __name((base, sub, ...rest) => { + if (rest.length) { + sub = mergePath(sub, ...rest); + } + return `${base?.[0] === "/" ? "" : "/"}${base}${sub === "/" ? "" : `${base?.at(-1) === "/" ? "" : "/"}${sub?.[0] === "/" ? sub.slice(1) : sub}`}`; +}, "mergePath"); +var checkOptionalParameter = /* @__PURE__ */ __name((path) => { + if (path.charCodeAt(path.length - 1) !== 63 || !path.includes(":")) { + return null; + } + const segments = path.split("/"); + const results = []; + let basePath = ""; + segments.forEach((segment) => { + if (segment !== "" && !/\:/.test(segment)) { + basePath += "/" + segment; + } else if (/\:/.test(segment)) { + if (/\?/.test(segment)) { + if (results.length === 0 && basePath === "") { + results.push("/"); + } else { + results.push(basePath); + } + const optionalSegment = segment.replace("?", ""); + basePath += "/" + optionalSegment; + results.push(basePath); + } else { + basePath += "/" + segment; + } + } + }); + return results.filter((v, i, a) => a.indexOf(v) === i); +}, "checkOptionalParameter"); +var _decodeURI = /* @__PURE__ */ __name((value) => { + if (!/[%+]/.test(value)) { + return value; + } + if (value.indexOf("+") !== -1) { + value = value.replace(/\+/g, " "); + } + return value.indexOf("%") !== -1 ? tryDecode(value, decodeURIComponent_) : value; +}, "_decodeURI"); +var _getQueryParam = /* @__PURE__ */ __name((url, key, multiple) => { + let encoded; + if (!multiple && key && !/[%+]/.test(key)) { + let keyIndex2 = url.indexOf("?", 8); + if (keyIndex2 === -1) { + return void 0; + } + if (!url.startsWith(key, keyIndex2 + 1)) { + keyIndex2 = url.indexOf(`&${key}`, keyIndex2 + 1); + } + while (keyIndex2 !== -1) { + const trailingKeyCode = url.charCodeAt(keyIndex2 + key.length + 1); + if (trailingKeyCode === 61) { + const valueIndex = keyIndex2 + key.length + 2; + const endIndex = url.indexOf("&", valueIndex); + return _decodeURI(url.slice(valueIndex, endIndex === -1 ? void 0 : endIndex)); + } else if (trailingKeyCode == 38 || isNaN(trailingKeyCode)) { + return ""; + } + keyIndex2 = url.indexOf(`&${key}`, keyIndex2 + 1); + } + encoded = /[%+]/.test(url); + if (!encoded) { + return void 0; + } + } + const results = {}; + encoded ??= /[%+]/.test(url); + let keyIndex = url.indexOf("?", 8); + while (keyIndex !== -1) { + const nextKeyIndex = url.indexOf("&", keyIndex + 1); + let valueIndex = url.indexOf("=", keyIndex); + if (valueIndex > nextKeyIndex && nextKeyIndex !== -1) { + valueIndex = -1; + } + let name = url.slice( + keyIndex + 1, + valueIndex === -1 ? nextKeyIndex === -1 ? void 0 : nextKeyIndex : valueIndex + ); + if (encoded) { + name = _decodeURI(name); + } + keyIndex = nextKeyIndex; + if (name === "") { + continue; + } + let value; + if (valueIndex === -1) { + value = ""; + } else { + value = url.slice(valueIndex + 1, nextKeyIndex === -1 ? void 0 : nextKeyIndex); + if (encoded) { + value = _decodeURI(value); + } + } + if (multiple) { + if (!(results[name] && Array.isArray(results[name]))) { + results[name] = []; + } + ; + results[name].push(value); + } else { + results[name] ??= value; + } + } + return key ? results[key] : results; +}, "_getQueryParam"); +var getQueryParam = _getQueryParam; +var getQueryParams = /* @__PURE__ */ __name((url, key) => { + return _getQueryParam(url, key, true); +}, "getQueryParams"); +var decodeURIComponent_ = decodeURIComponent; + +// node_modules/.pnpm/hono@4.12.5/node_modules/hono/dist/request.js +var tryDecodeURIComponent = /* @__PURE__ */ __name((str2) => tryDecode(str2, decodeURIComponent_), "tryDecodeURIComponent"); +var HonoRequest = class { + static { + __name(this, "HonoRequest"); + } + /** + * `.raw` can get the raw Request object. + * + * @see {@link https://hono.dev/docs/api/request#raw} + * + * @example + * ```ts + * // For Cloudflare Workers + * app.post('/', async (c) => { + * const metadata = c.req.raw.cf?.hostMetadata? + * ... + * }) + * ``` + */ + raw; + #validatedData; + // Short name of validatedData + #matchResult; + routeIndex = 0; + /** + * `.path` can get the pathname of the request. + * + * @see {@link https://hono.dev/docs/api/request#path} + * + * @example + * ```ts + * app.get('/about/me', (c) => { + * const pathname = c.req.path // `/about/me` + * }) + * ``` + */ + path; + bodyCache = {}; + constructor(request, path = "/", matchResult = [[]]) { + this.raw = request; + this.path = path; + this.#matchResult = matchResult; + this.#validatedData = {}; + } + param(key) { + return key ? this.#getDecodedParam(key) : this.#getAllDecodedParams(); + } + #getDecodedParam(key) { + const paramKey = this.#matchResult[0][this.routeIndex][1][key]; + const param = this.#getParamValue(paramKey); + return param && /\%/.test(param) ? tryDecodeURIComponent(param) : param; + } + #getAllDecodedParams() { + const decoded = {}; + const keys = Object.keys(this.#matchResult[0][this.routeIndex][1]); + for (const key of keys) { + const value = this.#getParamValue(this.#matchResult[0][this.routeIndex][1][key]); + if (value !== void 0) { + decoded[key] = /\%/.test(value) ? tryDecodeURIComponent(value) : value; + } + } + return decoded; + } + #getParamValue(paramKey) { + return this.#matchResult[1] ? this.#matchResult[1][paramKey] : paramKey; + } + query(key) { + return getQueryParam(this.url, key); + } + queries(key) { + return getQueryParams(this.url, key); + } + header(name) { + if (name) { + return this.raw.headers.get(name) ?? void 0; + } + const headerData = {}; + this.raw.headers.forEach((value, key) => { + headerData[key] = value; + }); + return headerData; + } + async parseBody(options) { + return this.bodyCache.parsedBody ??= await parseBody(this, options); + } + #cachedBody = /* @__PURE__ */ __name((key) => { + const { bodyCache, raw: raw2 } = this; + const cachedBody = bodyCache[key]; + if (cachedBody) { + return cachedBody; + } + const anyCachedKey = Object.keys(bodyCache)[0]; + if (anyCachedKey) { + return bodyCache[anyCachedKey].then((body) => { + if (anyCachedKey === "json") { + body = JSON.stringify(body); + } + return new Response(body)[key](); + }); + } + return bodyCache[key] = raw2[key](); + }, "#cachedBody"); + /** + * `.json()` can parse Request body of type `application/json` + * + * @see {@link https://hono.dev/docs/api/request#json} + * + * @example + * ```ts + * app.post('/entry', async (c) => { + * const body = await c.req.json() + * }) + * ``` + */ + json() { + return this.#cachedBody("text").then((text2) => JSON.parse(text2)); + } + /** + * `.text()` can parse Request body of type `text/plain` + * + * @see {@link https://hono.dev/docs/api/request#text} + * + * @example + * ```ts + * app.post('/entry', async (c) => { + * const body = await c.req.text() + * }) + * ``` + */ + text() { + return this.#cachedBody("text"); + } + /** + * `.arrayBuffer()` parse Request body as an `ArrayBuffer` + * + * @see {@link https://hono.dev/docs/api/request#arraybuffer} + * + * @example + * ```ts + * app.post('/entry', async (c) => { + * const body = await c.req.arrayBuffer() + * }) + * ``` + */ + arrayBuffer() { + return this.#cachedBody("arrayBuffer"); + } + /** + * Parses the request body as a `Blob`. + * @example + * ```ts + * app.post('/entry', async (c) => { + * const body = await c.req.blob(); + * }); + * ``` + * @see https://hono.dev/docs/api/request#blob + */ + blob() { + return this.#cachedBody("blob"); + } + /** + * Parses the request body as `FormData`. + * @example + * ```ts + * app.post('/entry', async (c) => { + * const body = await c.req.formData(); + * }); + * ``` + * @see https://hono.dev/docs/api/request#formdata + */ + formData() { + return this.#cachedBody("formData"); + } + /** + * Adds validated data to the request. + * + * @param target - The target of the validation. + * @param data - The validated data to add. + */ + addValidatedData(target, data2) { + this.#validatedData[target] = data2; + } + valid(target) { + return this.#validatedData[target]; + } + /** + * `.url()` can get the request url strings. + * + * @see {@link https://hono.dev/docs/api/request#url} + * + * @example + * ```ts + * app.get('/about/me', (c) => { + * const url = c.req.url // `http://localhost:8787/about/me` + * ... + * }) + * ``` + */ + get url() { + return this.raw.url; + } + /** + * `.method()` can get the method name of the request. + * + * @see {@link https://hono.dev/docs/api/request#method} + * + * @example + * ```ts + * app.get('/about/me', (c) => { + * const method = c.req.method // `GET` + * }) + * ``` + */ + get method() { + return this.raw.method; + } + get [GET_MATCH_RESULT]() { + return this.#matchResult; + } + /** + * `.matchedRoutes()` can return a matched route in the handler + * + * @deprecated + * + * Use matchedRoutes helper defined in "hono/route" instead. + * + * @see {@link https://hono.dev/docs/api/request#matchedroutes} + * + * @example + * ```ts + * app.use('*', async function logger(c, next) { + * await next() + * c.req.matchedRoutes.forEach(({ handler, method, path }, i) => { + * const name = handler.name || (handler.length < 2 ? '[handler]' : '[middleware]') + * console.log( + * method, + * ' ', + * path, + * ' '.repeat(Math.max(10 - path.length, 0)), + * name, + * i === c.req.routeIndex ? '<- respond from here' : '' + * ) + * }) + * }) + * ``` + */ + get matchedRoutes() { + return this.#matchResult[0].map(([[, route]]) => route); + } + /** + * `routePath()` can retrieve the path registered within the handler + * + * @deprecated + * + * Use routePath helper defined in "hono/route" instead. + * + * @see {@link https://hono.dev/docs/api/request#routepath} + * + * @example + * ```ts + * app.get('/posts/:id', (c) => { + * return c.json({ path: c.req.routePath }) + * }) + * ``` + */ + get routePath() { + return this.#matchResult[0].map(([[, route]]) => route)[this.routeIndex].path; + } +}; + +// node_modules/.pnpm/hono@4.12.5/node_modules/hono/dist/utils/html.js +init_modules_watch_stub(); +init_performance2(); +var HtmlEscapedCallbackPhase = { + Stringify: 1, + BeforeStream: 2, + Stream: 3 +}; +var raw = /* @__PURE__ */ __name((value, callbacks) => { + const escapedString = new String(value); + escapedString.isEscaped = true; + escapedString.callbacks = callbacks; + return escapedString; +}, "raw"); +var resolveCallback = /* @__PURE__ */ __name(async (str2, phase, preserveCallbacks, context, buffer) => { + if (typeof str2 === "object" && !(str2 instanceof String)) { + if (!(str2 instanceof Promise)) { + str2 = str2.toString(); + } + if (str2 instanceof Promise) { + str2 = await str2; + } + } + const callbacks = str2.callbacks; + if (!callbacks?.length) { + return Promise.resolve(str2); + } + if (buffer) { + buffer[0] += str2; + } else { + buffer = [str2]; + } + const resStr = Promise.all(callbacks.map((c) => c({ phase, buffer, context }))).then( + (res) => Promise.all( + res.filter(Boolean).map((str22) => resolveCallback(str22, phase, false, context, buffer)) + ).then(() => buffer[0]) + ); + if (preserveCallbacks) { + return raw(await resStr, callbacks); + } else { + return resStr; + } +}, "resolveCallback"); + +// node_modules/.pnpm/hono@4.12.5/node_modules/hono/dist/context.js +var TEXT_PLAIN = "text/plain; charset=UTF-8"; +var setDefaultContentType = /* @__PURE__ */ __name((contentType, headers) => { + return { + "Content-Type": contentType, + ...headers + }; +}, "setDefaultContentType"); +var createResponseInstance = /* @__PURE__ */ __name((body, init2) => new Response(body, init2), "createResponseInstance"); +var Context = class { + static { + __name(this, "Context"); + } + #rawRequest; + #req; + /** + * `.env` can get bindings (environment variables, secrets, KV namespaces, D1 database, R2 bucket etc.) in Cloudflare Workers. + * + * @see {@link https://hono.dev/docs/api/context#env} + * + * @example + * ```ts + * // Environment object for Cloudflare Workers + * app.get('*', async c => { + * const counter = c.env.COUNTER + * }) + * ``` + */ + env = {}; + #var; + finalized = false; + /** + * `.error` can get the error object from the middleware if the Handler throws an error. + * + * @see {@link https://hono.dev/docs/api/context#error} + * + * @example + * ```ts + * app.use('*', async (c, next) => { + * await next() + * if (c.error) { + * // do something... + * } + * }) + * ``` + */ + error; + #status; + #executionCtx; + #res; + #layout; + #renderer; + #notFoundHandler; + #preparedHeaders; + #matchResult; + #path; + /** + * Creates an instance of the Context class. + * + * @param req - The Request object. + * @param options - Optional configuration options for the context. + */ + constructor(req, options) { + this.#rawRequest = req; + if (options) { + this.#executionCtx = options.executionCtx; + this.env = options.env; + this.#notFoundHandler = options.notFoundHandler; + this.#path = options.path; + this.#matchResult = options.matchResult; + } + } + /** + * `.req` is the instance of {@link HonoRequest}. + */ + get req() { + this.#req ??= new HonoRequest(this.#rawRequest, this.#path, this.#matchResult); + return this.#req; + } + /** + * @see {@link https://hono.dev/docs/api/context#event} + * The FetchEvent associated with the current request. + * + * @throws Will throw an error if the context does not have a FetchEvent. + */ + get event() { + if (this.#executionCtx && "respondWith" in this.#executionCtx) { + return this.#executionCtx; + } else { + throw Error("This context has no FetchEvent"); + } + } + /** + * @see {@link https://hono.dev/docs/api/context#executionctx} + * The ExecutionContext associated with the current request. + * + * @throws Will throw an error if the context does not have an ExecutionContext. + */ + get executionCtx() { + if (this.#executionCtx) { + return this.#executionCtx; + } else { + throw Error("This context has no ExecutionContext"); + } + } + /** + * @see {@link https://hono.dev/docs/api/context#res} + * The Response object for the current request. + */ + get res() { + return this.#res ||= createResponseInstance(null, { + headers: this.#preparedHeaders ??= new Headers() + }); + } + /** + * Sets the Response object for the current request. + * + * @param _res - The Response object to set. + */ + set res(_res) { + if (this.#res && _res) { + _res = createResponseInstance(_res.body, _res); + for (const [k, v] of this.#res.headers.entries()) { + if (k === "content-type") { + continue; + } + if (k === "set-cookie") { + const cookies = this.#res.headers.getSetCookie(); + _res.headers.delete("set-cookie"); + for (const cookie of cookies) { + _res.headers.append("set-cookie", cookie); + } + } else { + _res.headers.set(k, v); + } + } + } + this.#res = _res; + this.finalized = true; + } + /** + * `.render()` can create a response within a layout. + * + * @see {@link https://hono.dev/docs/api/context#render-setrenderer} + * + * @example + * ```ts + * app.get('/', (c) => { + * return c.render('Hello!') + * }) + * ``` + */ + render = /* @__PURE__ */ __name((...args) => { + this.#renderer ??= (content) => this.html(content); + return this.#renderer(...args); + }, "render"); + /** + * Sets the layout for the response. + * + * @param layout - The layout to set. + * @returns The layout function. + */ + setLayout = /* @__PURE__ */ __name((layout) => this.#layout = layout, "setLayout"); + /** + * Gets the current layout for the response. + * + * @returns The current layout function. + */ + getLayout = /* @__PURE__ */ __name(() => this.#layout, "getLayout"); + /** + * `.setRenderer()` can set the layout in the custom middleware. + * + * @see {@link https://hono.dev/docs/api/context#render-setrenderer} + * + * @example + * ```tsx + * app.use('*', async (c, next) => { + * c.setRenderer((content) => { + * return c.html( + * + * + *

{content}

+ * + * + * ) + * }) + * await next() + * }) + * ``` + */ + setRenderer = /* @__PURE__ */ __name((renderer) => { + this.#renderer = renderer; + }, "setRenderer"); + /** + * `.header()` can set headers. + * + * @see {@link https://hono.dev/docs/api/context#header} + * + * @example + * ```ts + * app.get('/welcome', (c) => { + * // Set headers + * c.header('X-Message', 'Hello!') + * c.header('Content-Type', 'text/plain') + * + * return c.body('Thank you for coming') + * }) + * ``` + */ + header = /* @__PURE__ */ __name((name, value, options) => { + if (this.finalized) { + this.#res = createResponseInstance(this.#res.body, this.#res); + } + const headers = this.#res ? this.#res.headers : this.#preparedHeaders ??= new Headers(); + if (value === void 0) { + headers.delete(name); + } else if (options?.append) { + headers.append(name, value); + } else { + headers.set(name, value); + } + }, "header"); + status = /* @__PURE__ */ __name((status) => { + this.#status = status; + }, "status"); + /** + * `.set()` can set the value specified by the key. + * + * @see {@link https://hono.dev/docs/api/context#set-get} + * + * @example + * ```ts + * app.use('*', async (c, next) => { + * c.set('message', 'Hono is hot!!') + * await next() + * }) + * ``` + */ + set = /* @__PURE__ */ __name((key, value) => { + this.#var ??= /* @__PURE__ */ new Map(); + this.#var.set(key, value); + }, "set"); + /** + * `.get()` can use the value specified by the key. + * + * @see {@link https://hono.dev/docs/api/context#set-get} + * + * @example + * ```ts + * app.get('/', (c) => { + * const message = c.get('message') + * return c.text(`The message is "${message}"`) + * }) + * ``` + */ + get = /* @__PURE__ */ __name((key) => { + return this.#var ? this.#var.get(key) : void 0; + }, "get"); + /** + * `.var` can access the value of a variable. + * + * @see {@link https://hono.dev/docs/api/context#var} + * + * @example + * ```ts + * const result = c.var.client.oneMethod() + * ``` + */ + // c.var.propName is a read-only + get var() { + if (!this.#var) { + return {}; + } + return Object.fromEntries(this.#var); + } + #newResponse(data2, arg, headers) { + const responseHeaders = this.#res ? new Headers(this.#res.headers) : this.#preparedHeaders ?? new Headers(); + if (typeof arg === "object" && "headers" in arg) { + const argHeaders = arg.headers instanceof Headers ? arg.headers : new Headers(arg.headers); + for (const [key, value] of argHeaders) { + if (key.toLowerCase() === "set-cookie") { + responseHeaders.append(key, value); + } else { + responseHeaders.set(key, value); + } + } + } + if (headers) { + for (const [k, v] of Object.entries(headers)) { + if (typeof v === "string") { + responseHeaders.set(k, v); + } else { + responseHeaders.delete(k); + for (const v2 of v) { + responseHeaders.append(k, v2); + } + } + } + } + const status = typeof arg === "number" ? arg : arg?.status ?? this.#status; + return createResponseInstance(data2, { status, headers: responseHeaders }); + } + newResponse = /* @__PURE__ */ __name((...args) => this.#newResponse(...args), "newResponse"); + /** + * `.body()` can return the HTTP response. + * You can set headers with `.header()` and set HTTP status code with `.status`. + * This can also be set in `.text()`, `.json()` and so on. + * + * @see {@link https://hono.dev/docs/api/context#body} + * + * @example + * ```ts + * app.get('/welcome', (c) => { + * // Set headers + * c.header('X-Message', 'Hello!') + * c.header('Content-Type', 'text/plain') + * // Set HTTP status code + * c.status(201) + * + * // Return the response body + * return c.body('Thank you for coming') + * }) + * ``` + */ + body = /* @__PURE__ */ __name((data2, arg, headers) => this.#newResponse(data2, arg, headers), "body"); + /** + * `.text()` can render text as `Content-Type:text/plain`. + * + * @see {@link https://hono.dev/docs/api/context#text} + * + * @example + * ```ts + * app.get('/say', (c) => { + * return c.text('Hello!') + * }) + * ``` + */ + text = /* @__PURE__ */ __name((text2, arg, headers) => { + return !this.#preparedHeaders && !this.#status && !arg && !headers && !this.finalized ? new Response(text2) : this.#newResponse( + text2, + arg, + setDefaultContentType(TEXT_PLAIN, headers) + ); + }, "text"); + /** + * `.json()` can render JSON as `Content-Type:application/json`. + * + * @see {@link https://hono.dev/docs/api/context#json} + * + * @example + * ```ts + * app.get('/api', (c) => { + * return c.json({ message: 'Hello!' }) + * }) + * ``` + */ + json = /* @__PURE__ */ __name((object, arg, headers) => { + return this.#newResponse( + JSON.stringify(object), + arg, + setDefaultContentType("application/json", headers) + ); + }, "json"); + html = /* @__PURE__ */ __name((html, arg, headers) => { + const res = /* @__PURE__ */ __name((html2) => this.#newResponse(html2, arg, setDefaultContentType("text/html; charset=UTF-8", headers)), "res"); + return typeof html === "object" ? resolveCallback(html, HtmlEscapedCallbackPhase.Stringify, false, {}).then(res) : res(html); + }, "html"); + /** + * `.redirect()` can Redirect, default status code is 302. + * + * @see {@link https://hono.dev/docs/api/context#redirect} + * + * @example + * ```ts + * app.get('/redirect', (c) => { + * return c.redirect('/') + * }) + * app.get('/redirect-permanently', (c) => { + * return c.redirect('/', 301) + * }) + * ``` + */ + redirect = /* @__PURE__ */ __name((location, status) => { + const locationString = String(location); + this.header( + "Location", + // Multibyes should be encoded + // eslint-disable-next-line no-control-regex + !/[^\x00-\xFF]/.test(locationString) ? locationString : encodeURI(locationString) + ); + return this.newResponse(null, status ?? 302); + }, "redirect"); + /** + * `.notFound()` can return the Not Found Response. + * + * @see {@link https://hono.dev/docs/api/context#notfound} + * + * @example + * ```ts + * app.get('/notfound', (c) => { + * return c.notFound() + * }) + * ``` + */ + notFound = /* @__PURE__ */ __name(() => { + this.#notFoundHandler ??= () => createResponseInstance(); + return this.#notFoundHandler(this); + }, "notFound"); +}; + +// node_modules/.pnpm/hono@4.12.5/node_modules/hono/dist/router.js +init_modules_watch_stub(); +init_performance2(); +var METHOD_NAME_ALL = "ALL"; +var METHOD_NAME_ALL_LOWERCASE = "all"; +var METHODS = ["get", "post", "put", "delete", "options", "patch"]; +var MESSAGE_MATCHER_IS_ALREADY_BUILT = "Can not add a route since the matcher is already built."; +var UnsupportedPathError = class extends Error { + static { + __name(this, "UnsupportedPathError"); + } +}; + +// node_modules/.pnpm/hono@4.12.5/node_modules/hono/dist/utils/constants.js +init_modules_watch_stub(); +init_performance2(); +var COMPOSED_HANDLER = "__COMPOSED_HANDLER"; + +// node_modules/.pnpm/hono@4.12.5/node_modules/hono/dist/hono-base.js +var notFoundHandler = /* @__PURE__ */ __name((c) => { + return c.text("404 Not Found", 404); +}, "notFoundHandler"); +var errorHandler = /* @__PURE__ */ __name((err, c) => { + if ("getResponse" in err) { + const res = err.getResponse(); + return c.newResponse(res.body, res); + } + console.error(err); + return c.text("Internal Server Error", 500); +}, "errorHandler"); +var Hono = class _Hono { + static { + __name(this, "_Hono"); + } + get; + post; + put; + delete; + options; + patch; + all; + on; + use; + /* + This class is like an abstract class and does not have a router. + To use it, inherit the class and implement router in the constructor. + */ + router; + getPath; + // Cannot use `#` because it requires visibility at JavaScript runtime. + _basePath = "/"; + #path = "/"; + routes = []; + constructor(options = {}) { + const allMethods = [...METHODS, METHOD_NAME_ALL_LOWERCASE]; + allMethods.forEach((method) => { + this[method] = (args1, ...args) => { + if (typeof args1 === "string") { + this.#path = args1; + } else { + this.#addRoute(method, this.#path, args1); + } + args.forEach((handler) => { + this.#addRoute(method, this.#path, handler); + }); + return this; + }; + }); + this.on = (method, path, ...handlers) => { + for (const p of [path].flat()) { + this.#path = p; + for (const m2 of [method].flat()) { + handlers.map((handler) => { + this.#addRoute(m2.toUpperCase(), this.#path, handler); + }); + } + } + return this; + }; + this.use = (arg1, ...handlers) => { + if (typeof arg1 === "string") { + this.#path = arg1; + } else { + this.#path = "*"; + handlers.unshift(arg1); + } + handlers.forEach((handler) => { + this.#addRoute(METHOD_NAME_ALL, this.#path, handler); + }); + return this; + }; + const { strict, ...optionsWithoutStrict } = options; + Object.assign(this, optionsWithoutStrict); + this.getPath = strict ?? true ? options.getPath ?? getPath : getPathNoStrict; + } + #clone() { + const clone = new _Hono({ + router: this.router, + getPath: this.getPath + }); + clone.errorHandler = this.errorHandler; + clone.#notFoundHandler = this.#notFoundHandler; + clone.routes = this.routes; + return clone; + } + #notFoundHandler = notFoundHandler; + // Cannot use `#` because it requires visibility at JavaScript runtime. + errorHandler = errorHandler; + /** + * `.route()` allows grouping other Hono instance in routes. + * + * @see {@link https://hono.dev/docs/api/routing#grouping} + * + * @param {string} path - base Path + * @param {Hono} app - other Hono instance + * @returns {Hono} routed Hono instance + * + * @example + * ```ts + * const app = new Hono() + * const app2 = new Hono() + * + * app2.get("/user", (c) => c.text("user")) + * app.route("/api", app2) // GET /api/user + * ``` + */ + route(path, app2) { + const subApp = this.basePath(path); + app2.routes.map((r) => { + let handler; + if (app2.errorHandler === errorHandler) { + handler = r.handler; + } else { + handler = /* @__PURE__ */ __name(async (c, next) => (await compose([], app2.errorHandler)(c, () => r.handler(c, next))).res, "handler"); + handler[COMPOSED_HANDLER] = r.handler; + } + subApp.#addRoute(r.method, r.path, handler); + }); + return this; + } + /** + * `.basePath()` allows base paths to be specified. + * + * @see {@link https://hono.dev/docs/api/routing#base-path} + * + * @param {string} path - base Path + * @returns {Hono} changed Hono instance + * + * @example + * ```ts + * const api = new Hono().basePath('/api') + * ``` + */ + basePath(path) { + const subApp = this.#clone(); + subApp._basePath = mergePath(this._basePath, path); + return subApp; + } + /** + * `.onError()` handles an error and returns a customized Response. + * + * @see {@link https://hono.dev/docs/api/hono#error-handling} + * + * @param {ErrorHandler} handler - request Handler for error + * @returns {Hono} changed Hono instance + * + * @example + * ```ts + * app.onError((err, c) => { + * console.error(`${err}`) + * return c.text('Custom Error Message', 500) + * }) + * ``` + */ + onError = /* @__PURE__ */ __name((handler) => { + this.errorHandler = handler; + return this; + }, "onError"); + /** + * `.notFound()` allows you to customize a Not Found Response. + * + * @see {@link https://hono.dev/docs/api/hono#not-found} + * + * @param {NotFoundHandler} handler - request handler for not-found + * @returns {Hono} changed Hono instance + * + * @example + * ```ts + * app.notFound((c) => { + * return c.text('Custom 404 Message', 404) + * }) + * ``` + */ + notFound = /* @__PURE__ */ __name((handler) => { + this.#notFoundHandler = handler; + return this; + }, "notFound"); + /** + * `.mount()` allows you to mount applications built with other frameworks into your Hono application. + * + * @see {@link https://hono.dev/docs/api/hono#mount} + * + * @param {string} path - base Path + * @param {Function} applicationHandler - other Request Handler + * @param {MountOptions} [options] - options of `.mount()` + * @returns {Hono} mounted Hono instance + * + * @example + * ```ts + * import { Router as IttyRouter } from 'itty-router' + * import { Hono } from 'hono' + * // Create itty-router application + * const ittyRouter = IttyRouter() + * // GET /itty-router/hello + * ittyRouter.get('/hello', () => new Response('Hello from itty-router')) + * + * const app = new Hono() + * app.mount('/itty-router', ittyRouter.handle) + * ``` + * + * @example + * ```ts + * const app = new Hono() + * // Send the request to another application without modification. + * app.mount('/app', anotherApp, { + * replaceRequest: (req) => req, + * }) + * ``` + */ + mount(path, applicationHandler, options) { + let replaceRequest; + let optionHandler; + if (options) { + if (typeof options === "function") { + optionHandler = options; + } else { + optionHandler = options.optionHandler; + if (options.replaceRequest === false) { + replaceRequest = /* @__PURE__ */ __name((request) => request, "replaceRequest"); + } else { + replaceRequest = options.replaceRequest; + } + } + } + const getOptions = optionHandler ? (c) => { + const options2 = optionHandler(c); + return Array.isArray(options2) ? options2 : [options2]; + } : (c) => { + let executionContext = void 0; + try { + executionContext = c.executionCtx; + } catch { + } + return [c.env, executionContext]; + }; + replaceRequest ||= (() => { + const mergedPath = mergePath(this._basePath, path); + const pathPrefixLength = mergedPath === "/" ? 0 : mergedPath.length; + return (request) => { + const url = new URL(request.url); + url.pathname = url.pathname.slice(pathPrefixLength) || "/"; + return new Request(url, request); + }; + })(); + const handler = /* @__PURE__ */ __name(async (c, next) => { + const res = await applicationHandler(replaceRequest(c.req.raw), ...getOptions(c)); + if (res) { + return res; + } + await next(); + }, "handler"); + this.#addRoute(METHOD_NAME_ALL, mergePath(path, "*"), handler); + return this; + } + #addRoute(method, path, handler) { + method = method.toUpperCase(); + path = mergePath(this._basePath, path); + const r = { basePath: this._basePath, path, method, handler }; + this.router.add(method, path, [handler, r]); + this.routes.push(r); + } + #handleError(err, c) { + if (err instanceof Error) { + return this.errorHandler(err, c); + } + throw err; + } + #dispatch(request, executionCtx, env, method) { + if (method === "HEAD") { + return (async () => new Response(null, await this.#dispatch(request, executionCtx, env, "GET")))(); + } + const path = this.getPath(request, { env }); + const matchResult = this.router.match(method, path); + const c = new Context(request, { + path, + matchResult, + env, + executionCtx, + notFoundHandler: this.#notFoundHandler + }); + if (matchResult[0].length === 1) { + let res; + try { + res = matchResult[0][0][0][0](c, async () => { + c.res = await this.#notFoundHandler(c); + }); + } catch (err) { + return this.#handleError(err, c); + } + return res instanceof Promise ? res.then( + (resolved) => resolved || (c.finalized ? c.res : this.#notFoundHandler(c)) + ).catch((err) => this.#handleError(err, c)) : res ?? this.#notFoundHandler(c); + } + const composed = compose(matchResult[0], this.errorHandler, this.#notFoundHandler); + return (async () => { + try { + const context = await composed(c); + if (!context.finalized) { + throw new Error( + "Context is not finalized. Did you forget to return a Response object or `await next()`?" + ); + } + return context.res; + } catch (err) { + return this.#handleError(err, c); + } + })(); + } + /** + * `.fetch()` will be entry point of your app. + * + * @see {@link https://hono.dev/docs/api/hono#fetch} + * + * @param {Request} request - request Object of request + * @param {Env} Env - env Object + * @param {ExecutionContext} - context of execution + * @returns {Response | Promise} response of request + * + */ + fetch = /* @__PURE__ */ __name((request, ...rest) => { + return this.#dispatch(request, rest[1], rest[0], request.method); + }, "fetch"); + /** + * `.request()` is a useful method for testing. + * You can pass a URL or pathname to send a GET request. + * app will return a Response object. + * ```ts + * test('GET /hello is ok', async () => { + * const res = await app.request('/hello') + * expect(res.status).toBe(200) + * }) + * ``` + * @see https://hono.dev/docs/api/hono#request + */ + request = /* @__PURE__ */ __name((input, requestInit, Env, executionCtx) => { + if (input instanceof Request) { + return this.fetch(requestInit ? new Request(input, requestInit) : input, Env, executionCtx); + } + input = input.toString(); + return this.fetch( + new Request( + /^https?:\/\//.test(input) ? input : `http://localhost${mergePath("/", input)}`, + requestInit + ), + Env, + executionCtx + ); + }, "request"); + /** + * `.fire()` automatically adds a global fetch event listener. + * This can be useful for environments that adhere to the Service Worker API, such as non-ES module Cloudflare Workers. + * @deprecated + * Use `fire` from `hono/service-worker` instead. + * ```ts + * import { Hono } from 'hono' + * import { fire } from 'hono/service-worker' + * + * const app = new Hono() + * // ... + * fire(app) + * ``` + * @see https://hono.dev/docs/api/hono#fire + * @see https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API + * @see https://developers.cloudflare.com/workers/reference/migrate-to-module-workers/ + */ + fire = /* @__PURE__ */ __name(() => { + addEventListener("fetch", (event) => { + event.respondWith(this.#dispatch(event.request, event, void 0, event.request.method)); + }); + }, "fire"); +}; + +// node_modules/.pnpm/hono@4.12.5/node_modules/hono/dist/router/reg-exp-router/index.js +init_modules_watch_stub(); +init_performance2(); + +// node_modules/.pnpm/hono@4.12.5/node_modules/hono/dist/router/reg-exp-router/router.js +init_modules_watch_stub(); +init_performance2(); + +// node_modules/.pnpm/hono@4.12.5/node_modules/hono/dist/router/reg-exp-router/matcher.js +init_modules_watch_stub(); +init_performance2(); +var emptyParam = []; +function match(method, path) { + const matchers = this.buildAllMatchers(); + const match22 = /* @__PURE__ */ __name(((method2, path2) => { + const matcher = matchers[method2] || matchers[METHOD_NAME_ALL]; + const staticMatch = matcher[2][path2]; + if (staticMatch) { + return staticMatch; + } + const match3 = path2.match(matcher[0]); + if (!match3) { + return [[], emptyParam]; + } + const index = match3.indexOf("", 1); + return [matcher[1][index], match3]; + }), "match2"); + this.match = match22; + return match22(method, path); +} +__name(match, "match"); + +// node_modules/.pnpm/hono@4.12.5/node_modules/hono/dist/router/reg-exp-router/node.js +init_modules_watch_stub(); +init_performance2(); +var LABEL_REG_EXP_STR = "[^/]+"; +var ONLY_WILDCARD_REG_EXP_STR = ".*"; +var TAIL_WILDCARD_REG_EXP_STR = "(?:|/.*)"; +var PATH_ERROR = /* @__PURE__ */ Symbol(); +var regExpMetaChars = new Set(".\\+*[^]$()"); +function compareKey(a, b) { + if (a.length === 1) { + return b.length === 1 ? a < b ? -1 : 1 : -1; + } + if (b.length === 1) { + return 1; + } + if (a === ONLY_WILDCARD_REG_EXP_STR || a === TAIL_WILDCARD_REG_EXP_STR) { + return 1; + } else if (b === ONLY_WILDCARD_REG_EXP_STR || b === TAIL_WILDCARD_REG_EXP_STR) { + return -1; + } + if (a === LABEL_REG_EXP_STR) { + return 1; + } else if (b === LABEL_REG_EXP_STR) { + return -1; + } + return a.length === b.length ? a < b ? -1 : 1 : b.length - a.length; +} +__name(compareKey, "compareKey"); +var Node = class _Node { + static { + __name(this, "_Node"); + } + #index; + #varIndex; + #children = /* @__PURE__ */ Object.create(null); + insert(tokens, index, paramMap, context, pathErrorCheckOnly) { + if (tokens.length === 0) { + if (this.#index !== void 0) { + throw PATH_ERROR; + } + if (pathErrorCheckOnly) { + return; + } + this.#index = index; + return; + } + const [token, ...restTokens] = tokens; + const pattern = token === "*" ? restTokens.length === 0 ? ["", "", ONLY_WILDCARD_REG_EXP_STR] : ["", "", LABEL_REG_EXP_STR] : token === "/*" ? ["", "", TAIL_WILDCARD_REG_EXP_STR] : token.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/); + let node; + if (pattern) { + const name = pattern[1]; + let regexpStr = pattern[2] || LABEL_REG_EXP_STR; + if (name && pattern[2]) { + if (regexpStr === ".*") { + throw PATH_ERROR; + } + regexpStr = regexpStr.replace(/^\((?!\?:)(?=[^)]+\)$)/, "(?:"); + if (/\((?!\?:)/.test(regexpStr)) { + throw PATH_ERROR; + } + } + node = this.#children[regexpStr]; + if (!node) { + if (Object.keys(this.#children).some( + (k) => k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR + )) { + throw PATH_ERROR; + } + if (pathErrorCheckOnly) { + return; + } + node = this.#children[regexpStr] = new _Node(); + if (name !== "") { + node.#varIndex = context.varIndex++; + } + } + if (!pathErrorCheckOnly && name !== "") { + paramMap.push([name, node.#varIndex]); + } + } else { + node = this.#children[token]; + if (!node) { + if (Object.keys(this.#children).some( + (k) => k.length > 1 && k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR + )) { + throw PATH_ERROR; + } + if (pathErrorCheckOnly) { + return; + } + node = this.#children[token] = new _Node(); + } + } + node.insert(restTokens, index, paramMap, context, pathErrorCheckOnly); + } + buildRegExpStr() { + const childKeys = Object.keys(this.#children).sort(compareKey); + const strList = childKeys.map((k) => { + const c = this.#children[k]; + return (typeof c.#varIndex === "number" ? `(${k})@${c.#varIndex}` : regExpMetaChars.has(k) ? `\\${k}` : k) + c.buildRegExpStr(); + }); + if (typeof this.#index === "number") { + strList.unshift(`#${this.#index}`); + } + if (strList.length === 0) { + return ""; + } + if (strList.length === 1) { + return strList[0]; + } + return "(?:" + strList.join("|") + ")"; + } +}; + +// node_modules/.pnpm/hono@4.12.5/node_modules/hono/dist/router/reg-exp-router/trie.js +init_modules_watch_stub(); +init_performance2(); +var Trie = class { + static { + __name(this, "Trie"); + } + #context = { varIndex: 0 }; + #root = new Node(); + insert(path, index, pathErrorCheckOnly) { + const paramAssoc = []; + const groups = []; + for (let i = 0; ; ) { + let replaced = false; + path = path.replace(/\{[^}]+\}/g, (m2) => { + const mark = `@\\${i}`; + groups[i] = [mark, m2]; + i++; + replaced = true; + return mark; + }); + if (!replaced) { + break; + } + } + const tokens = path.match(/(?::[^\/]+)|(?:\/\*$)|./g) || []; + for (let i = groups.length - 1; i >= 0; i--) { + const [mark] = groups[i]; + for (let j = tokens.length - 1; j >= 0; j--) { + if (tokens[j].indexOf(mark) !== -1) { + tokens[j] = tokens[j].replace(mark, groups[i][1]); + break; + } + } + } + this.#root.insert(tokens, index, paramAssoc, this.#context, pathErrorCheckOnly); + return paramAssoc; + } + buildRegExp() { + let regexp = this.#root.buildRegExpStr(); + if (regexp === "") { + return [/^$/, [], []]; + } + let captureIndex = 0; + const indexReplacementMap = []; + const paramReplacementMap = []; + regexp = regexp.replace(/#(\d+)|@(\d+)|\.\*\$/g, (_, handlerIndex, paramIndex) => { + if (handlerIndex !== void 0) { + indexReplacementMap[++captureIndex] = Number(handlerIndex); + return "$()"; + } + if (paramIndex !== void 0) { + paramReplacementMap[Number(paramIndex)] = ++captureIndex; + return ""; + } + return ""; + }); + return [new RegExp(`^${regexp}`), indexReplacementMap, paramReplacementMap]; + } +}; + +// node_modules/.pnpm/hono@4.12.5/node_modules/hono/dist/router/reg-exp-router/router.js +var nullMatcher = [/^$/, [], /* @__PURE__ */ Object.create(null)]; +var wildcardRegExpCache = /* @__PURE__ */ Object.create(null); +function buildWildcardRegExp(path) { + return wildcardRegExpCache[path] ??= new RegExp( + path === "*" ? "" : `^${path.replace( + /\/\*$|([.\\+*[^\]$()])/g, + (_, metaChar) => metaChar ? `\\${metaChar}` : "(?:|/.*)" + )}$` + ); +} +__name(buildWildcardRegExp, "buildWildcardRegExp"); +function clearWildcardRegExpCache() { + wildcardRegExpCache = /* @__PURE__ */ Object.create(null); +} +__name(clearWildcardRegExpCache, "clearWildcardRegExpCache"); +function buildMatcherFromPreprocessedRoutes(routes) { + const trie = new Trie(); + const handlerData = []; + if (routes.length === 0) { + return nullMatcher; + } + const routesWithStaticPathFlag = routes.map( + (route) => [!/\*|\/:/.test(route[0]), ...route] + ).sort( + ([isStaticA, pathA], [isStaticB, pathB]) => isStaticA ? 1 : isStaticB ? -1 : pathA.length - pathB.length + ); + const staticMap = /* @__PURE__ */ Object.create(null); + for (let i = 0, j = -1, len = routesWithStaticPathFlag.length; i < len; i++) { + const [pathErrorCheckOnly, path, handlers] = routesWithStaticPathFlag[i]; + if (pathErrorCheckOnly) { + staticMap[path] = [handlers.map(([h2]) => [h2, /* @__PURE__ */ Object.create(null)]), emptyParam]; + } else { + j++; + } + let paramAssoc; + try { + paramAssoc = trie.insert(path, j, pathErrorCheckOnly); + } catch (e) { + throw e === PATH_ERROR ? new UnsupportedPathError(path) : e; + } + if (pathErrorCheckOnly) { + continue; + } + handlerData[j] = handlers.map(([h2, paramCount]) => { + const paramIndexMap = /* @__PURE__ */ Object.create(null); + paramCount -= 1; + for (; paramCount >= 0; paramCount--) { + const [key, value] = paramAssoc[paramCount]; + paramIndexMap[key] = value; + } + return [h2, paramIndexMap]; + }); + } + const [regexp, indexReplacementMap, paramReplacementMap] = trie.buildRegExp(); + for (let i = 0, len = handlerData.length; i < len; i++) { + for (let j = 0, len2 = handlerData[i].length; j < len2; j++) { + const map = handlerData[i][j]?.[1]; + if (!map) { + continue; + } + const keys = Object.keys(map); + for (let k = 0, len3 = keys.length; k < len3; k++) { + map[keys[k]] = paramReplacementMap[map[keys[k]]]; + } + } + } + const handlerMap = []; + for (const i in indexReplacementMap) { + handlerMap[i] = handlerData[indexReplacementMap[i]]; + } + return [regexp, handlerMap, staticMap]; +} +__name(buildMatcherFromPreprocessedRoutes, "buildMatcherFromPreprocessedRoutes"); +function findMiddleware(middleware, path) { + if (!middleware) { + return void 0; + } + for (const k of Object.keys(middleware).sort((a, b) => b.length - a.length)) { + if (buildWildcardRegExp(k).test(path)) { + return [...middleware[k]]; + } + } + return void 0; +} +__name(findMiddleware, "findMiddleware"); +var RegExpRouter = class { + static { + __name(this, "RegExpRouter"); + } + name = "RegExpRouter"; + #middleware; + #routes; + constructor() { + this.#middleware = { [METHOD_NAME_ALL]: /* @__PURE__ */ Object.create(null) }; + this.#routes = { [METHOD_NAME_ALL]: /* @__PURE__ */ Object.create(null) }; + } + add(method, path, handler) { + const middleware = this.#middleware; + const routes = this.#routes; + if (!middleware || !routes) { + throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT); + } + if (!middleware[method]) { + ; + [middleware, routes].forEach((handlerMap) => { + handlerMap[method] = /* @__PURE__ */ Object.create(null); + Object.keys(handlerMap[METHOD_NAME_ALL]).forEach((p) => { + handlerMap[method][p] = [...handlerMap[METHOD_NAME_ALL][p]]; + }); + }); + } + if (path === "/*") { + path = "*"; + } + const paramCount = (path.match(/\/:/g) || []).length; + if (/\*$/.test(path)) { + const re = buildWildcardRegExp(path); + if (method === METHOD_NAME_ALL) { + Object.keys(middleware).forEach((m2) => { + middleware[m2][path] ||= findMiddleware(middleware[m2], path) || findMiddleware(middleware[METHOD_NAME_ALL], path) || []; + }); + } else { + middleware[method][path] ||= findMiddleware(middleware[method], path) || findMiddleware(middleware[METHOD_NAME_ALL], path) || []; + } + Object.keys(middleware).forEach((m2) => { + if (method === METHOD_NAME_ALL || method === m2) { + Object.keys(middleware[m2]).forEach((p) => { + re.test(p) && middleware[m2][p].push([handler, paramCount]); + }); + } + }); + Object.keys(routes).forEach((m2) => { + if (method === METHOD_NAME_ALL || method === m2) { + Object.keys(routes[m2]).forEach( + (p) => re.test(p) && routes[m2][p].push([handler, paramCount]) + ); + } + }); + return; + } + const paths = checkOptionalParameter(path) || [path]; + for (let i = 0, len = paths.length; i < len; i++) { + const path2 = paths[i]; + Object.keys(routes).forEach((m2) => { + if (method === METHOD_NAME_ALL || method === m2) { + routes[m2][path2] ||= [ + ...findMiddleware(middleware[m2], path2) || findMiddleware(middleware[METHOD_NAME_ALL], path2) || [] + ]; + routes[m2][path2].push([handler, paramCount - len + i + 1]); + } + }); + } + } + match = match; + buildAllMatchers() { + const matchers = /* @__PURE__ */ Object.create(null); + Object.keys(this.#routes).concat(Object.keys(this.#middleware)).forEach((method) => { + matchers[method] ||= this.#buildMatcher(method); + }); + this.#middleware = this.#routes = void 0; + clearWildcardRegExpCache(); + return matchers; + } + #buildMatcher(method) { + const routes = []; + let hasOwnRoute = method === METHOD_NAME_ALL; + [this.#middleware, this.#routes].forEach((r) => { + const ownRoute = r[method] ? Object.keys(r[method]).map((path) => [path, r[method][path]]) : []; + if (ownRoute.length !== 0) { + hasOwnRoute ||= true; + routes.push(...ownRoute); + } else if (method !== METHOD_NAME_ALL) { + routes.push( + ...Object.keys(r[METHOD_NAME_ALL]).map((path) => [path, r[METHOD_NAME_ALL][path]]) + ); + } + }); + if (!hasOwnRoute) { + return null; + } else { + return buildMatcherFromPreprocessedRoutes(routes); + } + } +}; + +// node_modules/.pnpm/hono@4.12.5/node_modules/hono/dist/router/reg-exp-router/prepared-router.js +init_modules_watch_stub(); +init_performance2(); + +// node_modules/.pnpm/hono@4.12.5/node_modules/hono/dist/router/smart-router/index.js +init_modules_watch_stub(); +init_performance2(); + +// node_modules/.pnpm/hono@4.12.5/node_modules/hono/dist/router/smart-router/router.js +init_modules_watch_stub(); +init_performance2(); +var SmartRouter = class { + static { + __name(this, "SmartRouter"); + } + name = "SmartRouter"; + #routers = []; + #routes = []; + constructor(init2) { + this.#routers = init2.routers; + } + add(method, path, handler) { + if (!this.#routes) { + throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT); + } + this.#routes.push([method, path, handler]); + } + match(method, path) { + if (!this.#routes) { + throw new Error("Fatal error"); + } + const routers = this.#routers; + const routes = this.#routes; + const len = routers.length; + let i = 0; + let res; + for (; i < len; i++) { + const router = routers[i]; + try { + for (let i2 = 0, len2 = routes.length; i2 < len2; i2++) { + router.add(...routes[i2]); + } + res = router.match(method, path); + } catch (e) { + if (e instanceof UnsupportedPathError) { + continue; + } + throw e; + } + this.match = router.match.bind(router); + this.#routers = [router]; + this.#routes = void 0; + break; + } + if (i === len) { + throw new Error("Fatal error"); + } + this.name = `SmartRouter + ${this.activeRouter.name}`; + return res; + } + get activeRouter() { + if (this.#routes || this.#routers.length !== 1) { + throw new Error("No active router has been determined yet."); + } + return this.#routers[0]; + } +}; + +// node_modules/.pnpm/hono@4.12.5/node_modules/hono/dist/router/trie-router/index.js +init_modules_watch_stub(); +init_performance2(); + +// node_modules/.pnpm/hono@4.12.5/node_modules/hono/dist/router/trie-router/router.js +init_modules_watch_stub(); +init_performance2(); + +// node_modules/.pnpm/hono@4.12.5/node_modules/hono/dist/router/trie-router/node.js +init_modules_watch_stub(); +init_performance2(); +var emptyParams = /* @__PURE__ */ Object.create(null); +var hasChildren = /* @__PURE__ */ __name((children) => { + for (const _ in children) { + return true; + } + return false; +}, "hasChildren"); +var Node2 = class _Node2 { + static { + __name(this, "_Node"); + } + #methods; + #children; + #patterns; + #order = 0; + #params = emptyParams; + constructor(method, handler, children) { + this.#children = children || /* @__PURE__ */ Object.create(null); + this.#methods = []; + if (method && handler) { + const m2 = /* @__PURE__ */ Object.create(null); + m2[method] = { handler, possibleKeys: [], score: 0 }; + this.#methods = [m2]; + } + this.#patterns = []; + } + insert(method, path, handler) { + this.#order = ++this.#order; + let curNode = this; + const parts = splitRoutingPath(path); + const possibleKeys = []; + for (let i = 0, len = parts.length; i < len; i++) { + const p = parts[i]; + const nextP = parts[i + 1]; + const pattern = getPattern(p, nextP); + const key = Array.isArray(pattern) ? pattern[0] : p; + if (key in curNode.#children) { + curNode = curNode.#children[key]; + if (pattern) { + possibleKeys.push(pattern[1]); + } + continue; + } + curNode.#children[key] = new _Node2(); + if (pattern) { + curNode.#patterns.push(pattern); + possibleKeys.push(pattern[1]); + } + curNode = curNode.#children[key]; + } + curNode.#methods.push({ + [method]: { + handler, + possibleKeys: possibleKeys.filter((v, i, a) => a.indexOf(v) === i), + score: this.#order + } + }); + return curNode; + } + #pushHandlerSets(handlerSets, node, method, nodeParams, params) { + for (let i = 0, len = node.#methods.length; i < len; i++) { + const m2 = node.#methods[i]; + const handlerSet = m2[method] || m2[METHOD_NAME_ALL]; + const processedSet = {}; + if (handlerSet !== void 0) { + handlerSet.params = /* @__PURE__ */ Object.create(null); + handlerSets.push(handlerSet); + if (nodeParams !== emptyParams || params && params !== emptyParams) { + for (let i2 = 0, len2 = handlerSet.possibleKeys.length; i2 < len2; i2++) { + const key = handlerSet.possibleKeys[i2]; + const processed = processedSet[handlerSet.score]; + handlerSet.params[key] = params?.[key] && !processed ? params[key] : nodeParams[key] ?? params?.[key]; + processedSet[handlerSet.score] = true; + } + } + } + } + } + search(method, path) { + const handlerSets = []; + this.#params = emptyParams; + const curNode = this; + let curNodes = [curNode]; + const parts = splitPath(path); + const curNodesQueue = []; + const len = parts.length; + let partOffsets = null; + for (let i = 0; i < len; i++) { + const part = parts[i]; + const isLast = i === len - 1; + const tempNodes = []; + for (let j = 0, len2 = curNodes.length; j < len2; j++) { + const node = curNodes[j]; + const nextNode = node.#children[part]; + if (nextNode) { + nextNode.#params = node.#params; + if (isLast) { + if (nextNode.#children["*"]) { + this.#pushHandlerSets(handlerSets, nextNode.#children["*"], method, node.#params); + } + this.#pushHandlerSets(handlerSets, nextNode, method, node.#params); + } else { + tempNodes.push(nextNode); + } + } + for (let k = 0, len3 = node.#patterns.length; k < len3; k++) { + const pattern = node.#patterns[k]; + const params = node.#params === emptyParams ? {} : { ...node.#params }; + if (pattern === "*") { + const astNode = node.#children["*"]; + if (astNode) { + this.#pushHandlerSets(handlerSets, astNode, method, node.#params); + astNode.#params = params; + tempNodes.push(astNode); + } + continue; + } + const [key, name, matcher] = pattern; + if (!part && !(matcher instanceof RegExp)) { + continue; + } + const child = node.#children[key]; + if (matcher instanceof RegExp) { + if (partOffsets === null) { + partOffsets = new Array(len); + let offset = path[0] === "/" ? 1 : 0; + for (let p = 0; p < len; p++) { + partOffsets[p] = offset; + offset += parts[p].length + 1; + } + } + const restPathString = path.substring(partOffsets[i]); + const m2 = matcher.exec(restPathString); + if (m2) { + params[name] = m2[0]; + this.#pushHandlerSets(handlerSets, child, method, node.#params, params); + if (hasChildren(child.#children)) { + child.#params = params; + const componentCount = m2[0].match(/\//)?.length ?? 0; + const targetCurNodes = curNodesQueue[componentCount] ||= []; + targetCurNodes.push(child); + } + continue; + } + } + if (matcher === true || matcher.test(part)) { + params[name] = part; + if (isLast) { + this.#pushHandlerSets(handlerSets, child, method, params, node.#params); + if (child.#children["*"]) { + this.#pushHandlerSets( + handlerSets, + child.#children["*"], + method, + params, + node.#params + ); + } + } else { + child.#params = params; + tempNodes.push(child); + } + } + } + } + const shifted = curNodesQueue.shift(); + curNodes = shifted ? tempNodes.concat(shifted) : tempNodes; + } + if (handlerSets.length > 1) { + handlerSets.sort((a, b) => { + return a.score - b.score; + }); + } + return [handlerSets.map(({ handler, params }) => [handler, params])]; + } +}; + +// node_modules/.pnpm/hono@4.12.5/node_modules/hono/dist/router/trie-router/router.js +var TrieRouter = class { + static { + __name(this, "TrieRouter"); + } + name = "TrieRouter"; + #node; + constructor() { + this.#node = new Node2(); + } + add(method, path, handler) { + const results = checkOptionalParameter(path); + if (results) { + for (let i = 0, len = results.length; i < len; i++) { + this.#node.insert(method, results[i], handler); + } + return; + } + this.#node.insert(method, path, handler); + } + match(method, path) { + return this.#node.search(method, path); + } +}; + +// node_modules/.pnpm/hono@4.12.5/node_modules/hono/dist/hono.js +var Hono2 = class extends Hono { + static { + __name(this, "Hono"); + } + /** + * Creates an instance of the Hono class. + * + * @param options - Optional configuration options for the Hono instance. + */ + constructor(options = {}) { + super(options); + this.router = options.router ?? new SmartRouter({ + routers: [new RegExpRouter(), new TrieRouter()] + }); + } +}; + +// node_modules/.pnpm/grammy@1.41.1/node_modules/grammy/out/web.mjs +init_modules_watch_stub(); +init_performance2(); +var filterQueryCache = /* @__PURE__ */ new Map(); +function matchFilter(filter) { + const queries = Array.isArray(filter) ? filter : [ + filter + ]; + const key = queries.join(","); + const predicate = filterQueryCache.get(key) ?? (() => { + const parsed = parse(queries); + const pred = compile(parsed); + filterQueryCache.set(key, pred); + return pred; + })(); + return (ctx) => predicate(ctx); +} +__name(matchFilter, "matchFilter"); +function parse(filter) { + return Array.isArray(filter) ? filter.map((q) => q.split(":")) : [ + filter.split(":") + ]; +} +__name(parse, "parse"); +function compile(parsed) { + const preprocessed = parsed.flatMap((q) => check(q, preprocess(q))); + const ltree = treeify(preprocessed); + const predicate = arborist(ltree); + return (ctx) => !!predicate(ctx.update, ctx); +} +__name(compile, "compile"); +function preprocess(filter) { + const valid = UPDATE_KEYS; + const expanded = [ + filter + ].flatMap((q) => { + const [l1, l2, l3] = q; + if (!(l1 in L1_SHORTCUTS)) return [ + q + ]; + if (!l1 && !l2 && !l3) return [ + q + ]; + const targets = L1_SHORTCUTS[l1]; + const expanded2 = targets.map((s2) => [ + s2, + l2, + l3 + ]); + if (l2 === void 0) return expanded2; + if (l2 in L2_SHORTCUTS && (l2 || l3)) return expanded2; + return expanded2.filter(([s2]) => !!valid[s2]?.[l2]); + }).flatMap((q) => { + const [l1, l2, l3] = q; + if (!(l2 in L2_SHORTCUTS)) return [ + q + ]; + if (!l2 && !l3) return [ + q + ]; + const targets = L2_SHORTCUTS[l2]; + const expanded2 = targets.map((s2) => [ + l1, + s2, + l3 + ]); + if (l3 === void 0) return expanded2; + return expanded2.filter(([, s2]) => !!valid[l1]?.[s2]?.[l3]); + }); + if (expanded.length === 0) { + throw new Error(`Shortcuts in '${filter.join(":")}' do not expand to any valid filter query`); + } + return expanded; +} +__name(preprocess, "preprocess"); +function check(original, preprocessed) { + if (preprocessed.length === 0) throw new Error("Empty filter query given"); + const errors = preprocessed.map(checkOne).filter((r) => r !== true); + if (errors.length === 0) return preprocessed; + else if (errors.length === 1) throw new Error(errors[0]); + else { + throw new Error(`Invalid filter query '${original.join(":")}'. There are ${errors.length} errors after expanding the contained shortcuts: ${errors.join("; ")}`); + } +} +__name(check, "check"); +function checkOne(filter) { + const [l1, l2, l3, ...n] = filter; + if (l1 === void 0) return "Empty filter query given"; + if (!(l1 in UPDATE_KEYS)) { + const permitted = Object.keys(UPDATE_KEYS); + return `Invalid L1 filter '${l1}' given in '${filter.join(":")}'. Permitted values are: ${permitted.map((k) => `'${k}'`).join(", ")}.`; + } + if (l2 === void 0) return true; + const l1Obj = UPDATE_KEYS[l1]; + if (!(l2 in l1Obj)) { + const permitted = Object.keys(l1Obj); + return `Invalid L2 filter '${l2}' given in '${filter.join(":")}'. Permitted values are: ${permitted.map((k) => `'${k}'`).join(", ")}.`; + } + if (l3 === void 0) return true; + const l2Obj = l1Obj[l2]; + if (!(l3 in l2Obj)) { + const permitted = Object.keys(l2Obj); + return `Invalid L3 filter '${l3}' given in '${filter.join(":")}'. ${permitted.length === 0 ? `No further filtering is possible after '${l1}:${l2}'.` : `Permitted values are: ${permitted.map((k) => `'${k}'`).join(", ")}.`}`; + } + if (n.length === 0) return true; + return `Cannot filter further than three levels, ':${n.join(":")}' is invalid!`; +} +__name(checkOne, "checkOne"); +function treeify(paths) { + const tree = {}; + for (const [l1, l2, l3] of paths) { + const subtree = tree[l1] ??= {}; + if (l2 !== void 0) { + const set = subtree[l2] ??= /* @__PURE__ */ new Set(); + if (l3 !== void 0) set.add(l3); + } + } + return tree; +} +__name(treeify, "treeify"); +function or(left, right) { + return (obj, ctx) => left(obj, ctx) || right(obj, ctx); +} +__name(or, "or"); +function concat(get2, test) { + return (obj, ctx) => { + const nextObj = get2(obj, ctx); + return nextObj && test(nextObj, ctx); + }; +} +__name(concat, "concat"); +function leaf(pred) { + return (obj, ctx) => pred(obj, ctx) != null; +} +__name(leaf, "leaf"); +function arborist(tree) { + const l1Predicates = Object.entries(tree).map(([l1, subtree]) => { + const l1Pred = /* @__PURE__ */ __name((obj) => obj[l1], "l1Pred"); + const l2Predicates = Object.entries(subtree).map(([l2, set]) => { + const l2Pred = /* @__PURE__ */ __name((obj) => obj[l2], "l2Pred"); + const l3Predicates = Array.from(set).map((l3) => { + const l3Pred = l3 === "me" ? (obj, ctx) => { + const me = ctx.me.id; + return testMaybeArray(obj, (u) => u.id === me); + } : (obj) => testMaybeArray(obj, (e) => e[l3] || e.type === l3); + return l3Pred; + }); + return l3Predicates.length === 0 ? leaf(l2Pred) : concat(l2Pred, l3Predicates.reduce(or)); + }); + return l2Predicates.length === 0 ? leaf(l1Pred) : concat(l1Pred, l2Predicates.reduce(or)); + }); + if (l1Predicates.length === 0) { + throw new Error("Cannot create filter function for empty query"); + } + return l1Predicates.reduce(or); +} +__name(arborist, "arborist"); +function testMaybeArray(t2, pred) { + const p = /* @__PURE__ */ __name((x) => x != null && pred(x), "p"); + return Array.isArray(t2) ? t2.some(p) : p(t2); +} +__name(testMaybeArray, "testMaybeArray"); +var ENTITY_KEYS = { + mention: {}, + hashtag: {}, + cashtag: {}, + bot_command: {}, + url: {}, + email: {}, + phone_number: {}, + bold: {}, + italic: {}, + underline: {}, + strikethrough: {}, + spoiler: {}, + blockquote: {}, + expandable_blockquote: {}, + code: {}, + pre: {}, + text_link: {}, + text_mention: {}, + custom_emoji: {} +}; +var USER_KEYS = { + me: {}, + is_bot: {}, + is_premium: {}, + added_to_attachment_menu: {} +}; +var FORWARD_ORIGIN_KEYS = { + user: {}, + hidden_user: {}, + chat: {}, + channel: {} +}; +var STICKER_KEYS = { + is_video: {}, + is_animated: {}, + premium_animation: {} +}; +var REACTION_KEYS = { + emoji: {}, + custom_emoji: {}, + paid: {} +}; +var GIFT_INFO_KEYS = { + can_be_upgraded: {}, + is_upgrade_separate: {}, + is_private: {} +}; +var COMMON_MESSAGE_KEYS = { + forward_origin: FORWARD_ORIGIN_KEYS, + is_topic_message: {}, + is_automatic_forward: {}, + business_connection_id: {}, + text: {}, + animation: {}, + audio: {}, + document: {}, + paid_media: {}, + photo: {}, + sticker: STICKER_KEYS, + story: {}, + video: {}, + video_note: {}, + voice: {}, + contact: {}, + dice: {}, + game: {}, + poll: {}, + venue: {}, + location: {}, + entities: ENTITY_KEYS, + caption_entities: ENTITY_KEYS, + caption: {}, + link_preview_options: { + url: {}, + prefer_small_media: {}, + prefer_large_media: {}, + show_above_text: {} + }, + effect_id: {}, + paid_star_count: {}, + has_media_spoiler: {}, + new_chat_title: {}, + new_chat_photo: {}, + delete_chat_photo: {}, + message_auto_delete_timer_changed: {}, + pinned_message: {}, + invoice: {}, + proximity_alert_triggered: {}, + chat_background_set: {}, + giveaway_created: {}, + giveaway: { + only_new_members: {}, + has_public_winners: {} + }, + giveaway_winners: { + only_new_members: {}, + was_refunded: {} + }, + giveaway_completed: {}, + gift: GIFT_INFO_KEYS, + gift_upgrade_sent: GIFT_INFO_KEYS, + unique_gift: { + transfer_star_count: {} + }, + paid_message_price_changed: {}, + video_chat_scheduled: {}, + video_chat_started: {}, + video_chat_ended: {}, + video_chat_participants_invited: {}, + web_app_data: {} +}; +var MESSAGE_KEYS = { + ...COMMON_MESSAGE_KEYS, + direct_messages_topic: {}, + chat_owner_left: { + new_owner: {} + }, + chat_owner_changd: {}, + new_chat_members: USER_KEYS, + left_chat_member: USER_KEYS, + group_chat_created: {}, + supergroup_chat_created: {}, + migrate_to_chat_id: {}, + migrate_from_chat_id: {}, + successful_payment: {}, + refunded_payment: {}, + users_shared: {}, + chat_shared: {}, + connected_website: {}, + write_access_allowed: {}, + passport_data: {}, + boost_added: {}, + forum_topic_created: { + is_name_implicit: {} + }, + forum_topic_edited: { + name: {}, + icon_custom_emoji_id: {} + }, + forum_topic_closed: {}, + forum_topic_reopened: {}, + general_forum_topic_hidden: {}, + general_forum_topic_unhidden: {}, + checklist: { + others_can_add_tasks: {}, + others_can_mark_tasks_as_done: {} + }, + checklist_tasks_done: {}, + checklist_tasks_added: {}, + suggested_post_info: {}, + suggested_post_approved: {}, + suggested_post_approval_failed: {}, + suggested_post_declined: {}, + suggested_post_paid: {}, + suggested_post_refunded: {}, + sender_boost_count: {} +}; +var CHANNEL_POST_KEYS = { + ...COMMON_MESSAGE_KEYS, + channel_chat_created: {}, + direct_message_price_changed: {}, + is_paid_post: {} +}; +var BUSINESS_CONNECTION_KEYS = { + can_reply: {}, + is_enabled: {} +}; +var MESSAGE_REACTION_KEYS = { + old_reaction: REACTION_KEYS, + new_reaction: REACTION_KEYS +}; +var MESSAGE_REACTION_COUNT_UPDATED_KEYS = { + reactions: REACTION_KEYS +}; +var CALLBACK_QUERY_KEYS = { + data: {}, + game_short_name: {} +}; +var CHAT_MEMBER_UPDATED_KEYS = { + from: USER_KEYS +}; +var UPDATE_KEYS = { + message: MESSAGE_KEYS, + edited_message: MESSAGE_KEYS, + channel_post: CHANNEL_POST_KEYS, + edited_channel_post: CHANNEL_POST_KEYS, + business_connection: BUSINESS_CONNECTION_KEYS, + business_message: MESSAGE_KEYS, + edited_business_message: MESSAGE_KEYS, + deleted_business_messages: {}, + inline_query: {}, + chosen_inline_result: {}, + callback_query: CALLBACK_QUERY_KEYS, + shipping_query: {}, + pre_checkout_query: {}, + poll: {}, + poll_answer: {}, + my_chat_member: CHAT_MEMBER_UPDATED_KEYS, + chat_member: CHAT_MEMBER_UPDATED_KEYS, + chat_join_request: {}, + message_reaction: MESSAGE_REACTION_KEYS, + message_reaction_count: MESSAGE_REACTION_COUNT_UPDATED_KEYS, + chat_boost: {}, + removed_chat_boost: {}, + purchased_paid_media: {} +}; +var L1_SHORTCUTS = { + "": [ + "message", + "channel_post" + ], + msg: [ + "message", + "channel_post" + ], + edit: [ + "edited_message", + "edited_channel_post" + ] +}; +var L2_SHORTCUTS = { + "": [ + "entities", + "caption_entities" + ], + media: [ + "photo", + "video" + ], + file: [ + "photo", + "animation", + "audio", + "document", + "video", + "video_note", + "voice", + "sticker" + ] +}; +var checker = { + filterQuery(filter) { + const pred = matchFilter(filter); + return (ctx) => pred(ctx); + }, + text(trigger) { + const hasText = checker.filterQuery([ + ":text", + ":caption" + ]); + const trg = triggerFn(trigger); + return (ctx) => { + if (!hasText(ctx)) return false; + const msg = ctx.message ?? ctx.channelPost; + const txt = msg.text ?? msg.caption; + return match2(ctx, txt, trg); + }; + }, + command(command) { + const hasEntities = checker.filterQuery(":entities:bot_command"); + const atCommands = /* @__PURE__ */ new Set(); + const noAtCommands = /* @__PURE__ */ new Set(); + toArray(command).forEach((cmd) => { + if (cmd.startsWith("/")) { + throw new Error(`Do not include '/' when registering command handlers (use '${cmd.substring(1)}' not '${cmd}')`); + } + const set = cmd.includes("@") ? atCommands : noAtCommands; + set.add(cmd); + }); + return (ctx) => { + if (!hasEntities(ctx)) return false; + const msg = ctx.message ?? ctx.channelPost; + const txt = msg.text ?? msg.caption; + return msg.entities.some((e) => { + if (e.type !== "bot_command") return false; + if (e.offset !== 0) return false; + const cmd = txt.substring(1, e.length); + if (noAtCommands.has(cmd) || atCommands.has(cmd)) { + ctx.match = txt.substring(cmd.length + 1).trimStart(); + return true; + } + const index = cmd.indexOf("@"); + if (index === -1) return false; + const atTarget = cmd.substring(index + 1).toLowerCase(); + const username = ctx.me.username.toLowerCase(); + if (atTarget !== username) return false; + const atCommand = cmd.substring(0, index); + if (noAtCommands.has(atCommand)) { + ctx.match = txt.substring(cmd.length + 1).trimStart(); + return true; + } + return false; + }); + }; + }, + reaction(reaction) { + const hasMessageReaction = checker.filterQuery("message_reaction"); + const normalized = typeof reaction === "string" ? [ + { + type: "emoji", + emoji: reaction + } + ] : (Array.isArray(reaction) ? reaction : [ + reaction + ]).map((emoji2) => typeof emoji2 === "string" ? { + type: "emoji", + emoji: emoji2 + } : emoji2); + const emoji = new Set(normalized.filter((r) => r.type === "emoji").map((r) => r.emoji)); + const customEmoji = new Set(normalized.filter((r) => r.type === "custom_emoji").map((r) => r.custom_emoji_id)); + const paid = normalized.some((r) => r.type === "paid"); + return (ctx) => { + if (!hasMessageReaction(ctx)) return false; + const { old_reaction, new_reaction } = ctx.messageReaction; + for (const reaction2 of new_reaction) { + let isOld = false; + if (reaction2.type === "emoji") { + for (const old of old_reaction) { + if (old.type !== "emoji") continue; + if (old.emoji === reaction2.emoji) { + isOld = true; + break; + } + } + } else if (reaction2.type === "custom_emoji") { + for (const old of old_reaction) { + if (old.type !== "custom_emoji") continue; + if (old.custom_emoji_id === reaction2.custom_emoji_id) { + isOld = true; + break; + } + } + } else if (reaction2.type === "paid") { + for (const old of old_reaction) { + if (old.type !== "paid") continue; + isOld = true; + break; + } + } else { + } + if (isOld) continue; + if (reaction2.type === "emoji") { + if (emoji.has(reaction2.emoji)) return true; + } else if (reaction2.type === "custom_emoji") { + if (customEmoji.has(reaction2.custom_emoji_id)) return true; + } else if (reaction2.type === "paid") { + if (paid) return true; + } else { + return true; + } + } + return false; + }; + }, + chatType(chatType) { + const set = new Set(toArray(chatType)); + return (ctx) => ctx.chat?.type !== void 0 && set.has(ctx.chat.type); + }, + callbackQuery(trigger) { + const hasCallbackQuery = checker.filterQuery("callback_query:data"); + const trg = triggerFn(trigger); + return (ctx) => hasCallbackQuery(ctx) && match2(ctx, ctx.callbackQuery.data, trg); + }, + gameQuery(trigger) { + const hasGameQuery = checker.filterQuery("callback_query:game_short_name"); + const trg = triggerFn(trigger); + return (ctx) => hasGameQuery(ctx) && match2(ctx, ctx.callbackQuery.game_short_name, trg); + }, + inlineQuery(trigger) { + const hasInlineQuery = checker.filterQuery("inline_query"); + const trg = triggerFn(trigger); + return (ctx) => hasInlineQuery(ctx) && match2(ctx, ctx.inlineQuery.query, trg); + }, + chosenInlineResult(trigger) { + const hasChosenInlineResult = checker.filterQuery("chosen_inline_result"); + const trg = triggerFn(trigger); + return (ctx) => hasChosenInlineResult(ctx) && match2(ctx, ctx.chosenInlineResult.result_id, trg); + }, + preCheckoutQuery(trigger) { + const hasPreCheckoutQuery = checker.filterQuery("pre_checkout_query"); + const trg = triggerFn(trigger); + return (ctx) => hasPreCheckoutQuery(ctx) && match2(ctx, ctx.preCheckoutQuery.invoice_payload, trg); + }, + shippingQuery(trigger) { + const hasShippingQuery = checker.filterQuery("shipping_query"); + const trg = triggerFn(trigger); + return (ctx) => hasShippingQuery(ctx) && match2(ctx, ctx.shippingQuery.invoice_payload, trg); + } +}; +var Context2 = class _Context { + static { + __name(this, "Context"); + } + update; + api; + me; + match; + constructor(update, api, me) { + this.update = update; + this.api = api; + this.me = me; + } + get message() { + return this.update.message; + } + get editedMessage() { + return this.update.edited_message; + } + get channelPost() { + return this.update.channel_post; + } + get editedChannelPost() { + return this.update.edited_channel_post; + } + get businessConnection() { + return this.update.business_connection; + } + get businessMessage() { + return this.update.business_message; + } + get editedBusinessMessage() { + return this.update.edited_business_message; + } + get deletedBusinessMessages() { + return this.update.deleted_business_messages; + } + get messageReaction() { + return this.update.message_reaction; + } + get messageReactionCount() { + return this.update.message_reaction_count; + } + get inlineQuery() { + return this.update.inline_query; + } + get chosenInlineResult() { + return this.update.chosen_inline_result; + } + get callbackQuery() { + return this.update.callback_query; + } + get shippingQuery() { + return this.update.shipping_query; + } + get preCheckoutQuery() { + return this.update.pre_checkout_query; + } + get poll() { + return this.update.poll; + } + get pollAnswer() { + return this.update.poll_answer; + } + get myChatMember() { + return this.update.my_chat_member; + } + get chatMember() { + return this.update.chat_member; + } + get chatJoinRequest() { + return this.update.chat_join_request; + } + get chatBoost() { + return this.update.chat_boost; + } + get removedChatBoost() { + return this.update.removed_chat_boost; + } + get purchasedPaidMedia() { + return this.update.purchased_paid_media; + } + get msg() { + return this.message ?? this.editedMessage ?? this.channelPost ?? this.editedChannelPost ?? this.businessMessage ?? this.editedBusinessMessage ?? this.callbackQuery?.message; + } + get chat() { + return (this.msg ?? this.deletedBusinessMessages ?? this.messageReaction ?? this.messageReactionCount ?? this.myChatMember ?? this.chatMember ?? this.chatJoinRequest ?? this.chatBoost ?? this.removedChatBoost)?.chat; + } + get senderChat() { + return this.msg?.sender_chat; + } + get from() { + return (this.businessConnection ?? this.messageReaction ?? (this.chatBoost?.boost ?? this.removedChatBoost)?.source)?.user ?? (this.callbackQuery ?? this.msg ?? this.inlineQuery ?? this.chosenInlineResult ?? this.shippingQuery ?? this.preCheckoutQuery ?? this.myChatMember ?? this.chatMember ?? this.chatJoinRequest ?? this.purchasedPaidMedia)?.from; + } + get msgId() { + return this.msg?.message_id ?? this.messageReaction?.message_id ?? this.messageReactionCount?.message_id; + } + get chatId() { + return this.chat?.id ?? this.businessConnection?.user_chat_id; + } + get inlineMessageId() { + return this.callbackQuery?.inline_message_id ?? this.chosenInlineResult?.inline_message_id; + } + get businessConnectionId() { + return this.msg?.business_connection_id ?? this.businessConnection?.id ?? this.deletedBusinessMessages?.business_connection_id; + } + entities(types) { + const message = this.msg; + if (message === void 0) return []; + const text2 = message.text ?? message.caption; + if (text2 === void 0) return []; + let entities = message.entities ?? message.caption_entities; + if (entities === void 0) return []; + if (types !== void 0) { + const filters = new Set(toArray(types)); + entities = entities.filter((entity) => filters.has(entity.type)); + } + return entities.map((entity) => ({ + ...entity, + text: text2.substring(entity.offset, entity.offset + entity.length) + })); + } + reactions() { + const emoji = []; + const emojiAdded = []; + const emojiKept = []; + const emojiRemoved = []; + const customEmoji = []; + const customEmojiAdded = []; + const customEmojiKept = []; + const customEmojiRemoved = []; + let paid = false; + let paidAdded = false; + const r = this.messageReaction; + if (r !== void 0) { + const { old_reaction, new_reaction } = r; + for (const reaction of new_reaction) { + if (reaction.type === "emoji") { + emoji.push(reaction.emoji); + } else if (reaction.type === "custom_emoji") { + customEmoji.push(reaction.custom_emoji_id); + } else if (reaction.type === "paid") { + paid = paidAdded = true; + } + } + for (const reaction of old_reaction) { + if (reaction.type === "emoji") { + emojiRemoved.push(reaction.emoji); + } else if (reaction.type === "custom_emoji") { + customEmojiRemoved.push(reaction.custom_emoji_id); + } else if (reaction.type === "paid") { + paidAdded = false; + } + } + emojiAdded.push(...emoji); + customEmojiAdded.push(...customEmoji); + for (let i = 0; i < emojiRemoved.length; i++) { + const len = emojiAdded.length; + if (len === 0) break; + const rem = emojiRemoved[i]; + for (let j = 0; j < len; j++) { + if (rem === emojiAdded[j]) { + emojiKept.push(rem); + emojiRemoved.splice(i, 1); + emojiAdded.splice(j, 1); + i--; + break; + } + } + } + for (let i = 0; i < customEmojiRemoved.length; i++) { + const len = customEmojiAdded.length; + if (len === 0) break; + const rem = customEmojiRemoved[i]; + for (let j = 0; j < len; j++) { + if (rem === customEmojiAdded[j]) { + customEmojiKept.push(rem); + customEmojiRemoved.splice(i, 1); + customEmojiAdded.splice(j, 1); + i--; + break; + } + } + } + } + return { + emoji, + emojiAdded, + emojiKept, + emojiRemoved, + customEmoji, + customEmojiAdded, + customEmojiKept, + customEmojiRemoved, + paid, + paidAdded + }; + } + static has = checker; + has(filter) { + return _Context.has.filterQuery(filter)(this); + } + hasText(trigger) { + return _Context.has.text(trigger)(this); + } + hasCommand(command) { + return _Context.has.command(command)(this); + } + hasReaction(reaction) { + return _Context.has.reaction(reaction)(this); + } + hasChatType(chatType) { + return _Context.has.chatType(chatType)(this); + } + hasCallbackQuery(trigger) { + return _Context.has.callbackQuery(trigger)(this); + } + hasGameQuery(trigger) { + return _Context.has.gameQuery(trigger)(this); + } + hasInlineQuery(trigger) { + return _Context.has.inlineQuery(trigger)(this); + } + hasChosenInlineResult(trigger) { + return _Context.has.chosenInlineResult(trigger)(this); + } + hasPreCheckoutQuery(trigger) { + return _Context.has.preCheckoutQuery(trigger)(this); + } + hasShippingQuery(trigger) { + return _Context.has.shippingQuery(trigger)(this); + } + reply(text2, other, signal) { + const msg = this.msg; + return this.api.sendMessage(orThrow(this.chatId, "sendMessage"), text2, { + business_connection_id: this.businessConnectionId, + ...msg?.is_topic_message ? { + message_thread_id: msg.message_thread_id + } : {}, + direct_messages_topic_id: msg?.direct_messages_topic?.topic_id, + ...other + }, signal); + } + replyWithDraft(text2, other, signal) { + const msg = this.msg; + return this.api.sendMessageDraft(orThrow(this.chatId, "sendMessageDraft"), this.update.update_id, text2, { + ...msg?.is_topic_message ? { + message_thread_id: msg?.message_thread_id + } : {}, + ...other + }, signal); + } + forwardMessage(chat_id, other, signal) { + const msg = this.msg; + return this.api.forwardMessage(chat_id, orThrow(this.chatId, "forwardMessage"), orThrow(this.msgId, "forwardMessage"), { + direct_messages_topic_id: msg?.direct_messages_topic?.topic_id, + ...other + }, signal); + } + forwardMessages(chat_id, message_ids, other, signal) { + const msg = this.msg; + return this.api.forwardMessages(chat_id, orThrow(this.chatId, "forwardMessages"), message_ids, { + direct_messages_topic_id: msg?.direct_messages_topic?.topic_id, + ...other + }, signal); + } + copyMessage(chat_id, other, signal) { + const msg = this.msg; + return this.api.copyMessage(chat_id, orThrow(this.chatId, "copyMessage"), orThrow(this.msgId, "copyMessage"), { + direct_messages_topic_id: msg?.direct_messages_topic?.topic_id, + ...other + }, signal); + } + copyMessages(chat_id, message_ids, other, signal) { + const msg = this.msg; + return this.api.copyMessages(chat_id, orThrow(this.chatId, "copyMessages"), message_ids, { + direct_messages_topic_id: msg?.direct_messages_topic?.topic_id, + ...other + }, signal); + } + replyWithPhoto(photo, other, signal) { + const msg = this.msg; + return this.api.sendPhoto(orThrow(this.chatId, "sendPhoto"), photo, { + business_connection_id: this.businessConnectionId, + ...msg?.is_topic_message ? { + message_thread_id: msg.message_thread_id + } : {}, + direct_messages_topic_id: msg?.direct_messages_topic?.topic_id, + ...other + }, signal); + } + replyWithAudio(audio, other, signal) { + const msg = this.msg; + return this.api.sendAudio(orThrow(this.chatId, "sendAudio"), audio, { + business_connection_id: this.businessConnectionId, + ...msg?.is_topic_message ? { + message_thread_id: msg.message_thread_id + } : {}, + direct_messages_topic_id: msg?.direct_messages_topic?.topic_id, + ...other + }, signal); + } + replyWithDocument(document1, other, signal) { + const msg = this.msg; + return this.api.sendDocument(orThrow(this.chatId, "sendDocument"), document1, { + business_connection_id: this.businessConnectionId, + ...msg?.is_topic_message ? { + message_thread_id: msg.message_thread_id + } : {}, + direct_messages_topic_id: msg?.direct_messages_topic?.topic_id, + ...other + }, signal); + } + replyWithVideo(video, other, signal) { + const msg = this.msg; + return this.api.sendVideo(orThrow(this.chatId, "sendVideo"), video, { + business_connection_id: this.businessConnectionId, + ...msg?.is_topic_message ? { + message_thread_id: msg.message_thread_id + } : {}, + direct_messages_topic_id: msg?.direct_messages_topic?.topic_id, + ...other + }, signal); + } + replyWithAnimation(animation, other, signal) { + const msg = this.msg; + return this.api.sendAnimation(orThrow(this.chatId, "sendAnimation"), animation, { + business_connection_id: this.businessConnectionId, + ...msg?.is_topic_message ? { + message_thread_id: msg.message_thread_id + } : {}, + direct_messages_topic_id: msg?.direct_messages_topic?.topic_id, + ...other + }, signal); + } + replyWithVoice(voice, other, signal) { + const msg = this.msg; + return this.api.sendVoice(orThrow(this.chatId, "sendVoice"), voice, { + business_connection_id: this.businessConnectionId, + ...msg?.is_topic_message ? { + message_thread_id: msg.message_thread_id + } : {}, + direct_messages_topic_id: msg?.direct_messages_topic?.topic_id, + ...other + }, signal); + } + replyWithVideoNote(video_note, other, signal) { + const msg = this.msg; + return this.api.sendVideoNote(orThrow(this.chatId, "sendVideoNote"), video_note, { + business_connection_id: this.businessConnectionId, + ...msg?.is_topic_message ? { + message_thread_id: msg.message_thread_id + } : {}, + direct_messages_topic_id: msg?.direct_messages_topic?.topic_id, + ...other + }, signal); + } + replyWithMediaGroup(media, other, signal) { + const msg = this.msg; + return this.api.sendMediaGroup(orThrow(this.chatId, "sendMediaGroup"), media, { + business_connection_id: this.businessConnectionId, + ...msg?.is_topic_message ? { + message_thread_id: msg.message_thread_id + } : {}, + direct_messages_topic_id: msg?.direct_messages_topic?.topic_id, + ...other + }, signal); + } + replyWithLocation(latitude, longitude, other, signal) { + const msg = this.msg; + return this.api.sendLocation(orThrow(this.chatId, "sendLocation"), latitude, longitude, { + business_connection_id: this.businessConnectionId, + ...msg?.is_topic_message ? { + message_thread_id: msg.message_thread_id + } : {}, + direct_messages_topic_id: msg?.direct_messages_topic?.topic_id, + ...other + }, signal); + } + editMessageLiveLocation(latitude, longitude, other, signal) { + const inlineId = this.inlineMessageId; + return inlineId !== void 0 ? this.api.editMessageLiveLocationInline(inlineId, latitude, longitude, { + business_connection_id: this.businessConnectionId, + ...other + }, signal) : this.api.editMessageLiveLocation(orThrow(this.chatId, "editMessageLiveLocation"), orThrow(this.msgId, "editMessageLiveLocation"), latitude, longitude, { + business_connection_id: this.businessConnectionId, + ...other + }, signal); + } + stopMessageLiveLocation(other, signal) { + const inlineId = this.inlineMessageId; + return inlineId !== void 0 ? this.api.stopMessageLiveLocationInline(inlineId, { + business_connection_id: this.businessConnectionId, + ...other + }, signal) : this.api.stopMessageLiveLocation(orThrow(this.chatId, "stopMessageLiveLocation"), orThrow(this.msgId, "stopMessageLiveLocation"), { + business_connection_id: this.businessConnectionId, + ...other + }, signal); + } + sendPaidMedia(star_count, media, other, signal) { + const msg = this.msg; + return this.api.sendPaidMedia(orThrow(this.chatId, "sendPaidMedia"), star_count, media, { + business_connection_id: this.businessConnectionId, + ...msg?.is_topic_message ? { + message_thread_id: msg.message_thread_id + } : {}, + direct_messages_topic_id: this.msg?.direct_messages_topic?.topic_id, + ...other + }, signal); + } + replyWithVenue(latitude, longitude, title2, address, other, signal) { + const msg = this.msg; + return this.api.sendVenue(orThrow(this.chatId, "sendVenue"), latitude, longitude, title2, address, { + business_connection_id: this.businessConnectionId, + ...msg?.is_topic_message ? { + message_thread_id: msg.message_thread_id + } : {}, + direct_messages_topic_id: msg?.direct_messages_topic?.topic_id, + ...other + }, signal); + } + replyWithContact(phone_number, first_name, other, signal) { + const msg = this.msg; + return this.api.sendContact(orThrow(this.chatId, "sendContact"), phone_number, first_name, { + business_connection_id: this.businessConnectionId, + ...msg?.is_topic_message ? { + message_thread_id: msg.message_thread_id + } : {}, + direct_messages_topic_id: msg?.direct_messages_topic?.topic_id, + ...other + }, signal); + } + replyWithPoll(question, options, other, signal) { + const msg = this.msg; + return this.api.sendPoll(orThrow(this.chatId, "sendPoll"), question, options, { + business_connection_id: this.businessConnectionId, + ...msg?.is_topic_message ? { + message_thread_id: msg.message_thread_id + } : {}, + ...other + }, signal); + } + replyWithChecklist(checklist, other, signal) { + return this.api.sendChecklist(orThrow(this.businessConnectionId, "sendChecklist"), orThrow(this.chatId, "sendChecklist"), checklist, other, signal); + } + editMessageChecklist(checklist, other, signal) { + const msg = orThrow(this.msg, "editMessageChecklist"); + const target = msg.checklist_tasks_done?.checklist_message ?? msg.checklist_tasks_added?.checklist_message ?? msg; + return this.api.editMessageChecklist(orThrow(this.businessConnectionId, "editMessageChecklist"), orThrow(target.chat.id, "editMessageChecklist"), orThrow(target.message_id, "editMessageChecklist"), checklist, other, signal); + } + replyWithDice(emoji, other, signal) { + const msg = this.msg; + return this.api.sendDice(orThrow(this.chatId, "sendDice"), emoji, { + business_connection_id: this.businessConnectionId, + ...msg?.is_topic_message ? { + message_thread_id: msg.message_thread_id + } : {}, + direct_messages_topic_id: msg?.direct_messages_topic?.topic_id, + ...other + }, signal); + } + replyWithChatAction(action, other, signal) { + const msg = this.msg; + return this.api.sendChatAction(orThrow(this.chatId, "sendChatAction"), action, { + business_connection_id: this.businessConnectionId, + message_thread_id: msg?.message_thread_id, + ...other + }, signal); + } + react(reaction, other, signal) { + return this.api.setMessageReaction(orThrow(this.chatId, "setMessageReaction"), orThrow(this.msgId, "setMessageReaction"), typeof reaction === "string" ? [ + { + type: "emoji", + emoji: reaction + } + ] : (Array.isArray(reaction) ? reaction : [ + reaction + ]).map((emoji) => typeof emoji === "string" ? { + type: "emoji", + emoji + } : emoji), other, signal); + } + getUserProfilePhotos(other, signal) { + return this.api.getUserProfilePhotos(orThrow(this.from, "getUserProfilePhotos").id, other, signal); + } + getUserProfileAudios(other, signal) { + return this.api.getUserProfileAudios(orThrow(this.from, "getUserProfileAudios").id, other, signal); + } + setUserEmojiStatus(other, signal) { + return this.api.setUserEmojiStatus(orThrow(this.from, "setUserEmojiStatus").id, other, signal); + } + getUserChatBoosts(chat_id, signal) { + return this.api.getUserChatBoosts(chat_id ?? orThrow(this.chatId, "getUserChatBoosts"), orThrow(this.from, "getUserChatBoosts").id, signal); + } + getUserGifts(other, signal) { + return this.api.getUserGifts(orThrow(this.from, "getUserGifts").id, other, signal); + } + getChatGifts(other, signal) { + return this.api.getChatGifts(orThrow(this.chatId, "getChatGifts"), other, signal); + } + getBusinessConnection(signal) { + return this.api.getBusinessConnection(orThrow(this.businessConnectionId, "getBusinessConnection"), signal); + } + getFile(signal) { + const m2 = orThrow(this.msg, "getFile"); + const file = m2.photo !== void 0 ? m2.photo[m2.photo.length - 1] : m2.animation ?? m2.audio ?? m2.document ?? m2.video ?? m2.video_note ?? m2.voice ?? m2.sticker; + return this.api.getFile(orThrow(file, "getFile").file_id, signal); + } + kickAuthor(...args) { + return this.banAuthor(...args); + } + banAuthor(other, signal) { + return this.api.banChatMember(orThrow(this.chatId, "banAuthor"), orThrow(this.from, "banAuthor").id, other, signal); + } + kickChatMember(...args) { + return this.banChatMember(...args); + } + banChatMember(user_id, other, signal) { + return this.api.banChatMember(orThrow(this.chatId, "banChatMember"), user_id, other, signal); + } + unbanChatMember(user_id, other, signal) { + return this.api.unbanChatMember(orThrow(this.chatId, "unbanChatMember"), user_id, other, signal); + } + restrictAuthor(permissions, other, signal) { + return this.api.restrictChatMember(orThrow(this.chatId, "restrictAuthor"), orThrow(this.from, "restrictAuthor").id, permissions, other, signal); + } + restrictChatMember(user_id, permissions, other, signal) { + return this.api.restrictChatMember(orThrow(this.chatId, "restrictChatMember"), user_id, permissions, other, signal); + } + promoteAuthor(other, signal) { + return this.api.promoteChatMember(orThrow(this.chatId, "promoteAuthor"), orThrow(this.from, "promoteAuthor").id, other, signal); + } + promoteChatMember(user_id, other, signal) { + return this.api.promoteChatMember(orThrow(this.chatId, "promoteChatMember"), user_id, other, signal); + } + setChatAdministratorAuthorCustomTitle(custom_title, signal) { + return this.api.setChatAdministratorCustomTitle(orThrow(this.chatId, "setChatAdministratorAuthorCustomTitle"), orThrow(this.from, "setChatAdministratorAuthorCustomTitle").id, custom_title, signal); + } + setChatAdministratorCustomTitle(user_id, custom_title, signal) { + return this.api.setChatAdministratorCustomTitle(orThrow(this.chatId, "setChatAdministratorCustomTitle"), user_id, custom_title, signal); + } + setAuthorTag(tag, signal) { + return this.api.setChatMemberTag(orThrow(this.chatId, "setChatMemberTag"), orThrow(this.from, "setChatMemberTag").id, tag, signal); + } + setChatMemberTag(user_id, tag, signal) { + return this.api.setChatMemberTag(orThrow(this.chatId, "setChatMemberTag"), user_id, tag, signal); + } + banChatSenderChat(sender_chat_id, signal) { + return this.api.banChatSenderChat(orThrow(this.chatId, "banChatSenderChat"), sender_chat_id, signal); + } + unbanChatSenderChat(sender_chat_id, signal) { + return this.api.unbanChatSenderChat(orThrow(this.chatId, "unbanChatSenderChat"), sender_chat_id, signal); + } + setChatPermissions(permissions, other, signal) { + return this.api.setChatPermissions(orThrow(this.chatId, "setChatPermissions"), permissions, other, signal); + } + exportChatInviteLink(signal) { + return this.api.exportChatInviteLink(orThrow(this.chatId, "exportChatInviteLink"), signal); + } + createChatInviteLink(other, signal) { + return this.api.createChatInviteLink(orThrow(this.chatId, "createChatInviteLink"), other, signal); + } + editChatInviteLink(invite_link, other, signal) { + return this.api.editChatInviteLink(orThrow(this.chatId, "editChatInviteLink"), invite_link, other, signal); + } + createChatSubscriptionInviteLink(subscription_period, subscription_price, other, signal) { + return this.api.createChatSubscriptionInviteLink(orThrow(this.chatId, "createChatSubscriptionInviteLink"), subscription_period, subscription_price, other, signal); + } + editChatSubscriptionInviteLink(invite_link, other, signal) { + return this.api.editChatSubscriptionInviteLink(orThrow(this.chatId, "editChatSubscriptionInviteLink"), invite_link, other, signal); + } + revokeChatInviteLink(invite_link, signal) { + return this.api.revokeChatInviteLink(orThrow(this.chatId, "editChatInviteLink"), invite_link, signal); + } + approveChatJoinRequest(user_id, signal) { + return this.api.approveChatJoinRequest(orThrow(this.chatId, "approveChatJoinRequest"), user_id, signal); + } + declineChatJoinRequest(user_id, signal) { + return this.api.declineChatJoinRequest(orThrow(this.chatId, "declineChatJoinRequest"), user_id, signal); + } + approveSuggestedPost(other, signal) { + return this.api.approveSuggestedPost(orThrow(this.chatId, "approveSuggestedPost"), orThrow(this.msgId, "approveSuggestedPost"), other, signal); + } + declineSuggestedPost(other, signal) { + return this.api.declineSuggestedPost(orThrow(this.chatId, "declineSuggestedPost"), orThrow(this.msgId, "declineSuggestedPost"), other, signal); + } + setChatPhoto(photo, signal) { + return this.api.setChatPhoto(orThrow(this.chatId, "setChatPhoto"), photo, signal); + } + deleteChatPhoto(signal) { + return this.api.deleteChatPhoto(orThrow(this.chatId, "deleteChatPhoto"), signal); + } + setChatTitle(title2, signal) { + return this.api.setChatTitle(orThrow(this.chatId, "setChatTitle"), title2, signal); + } + setChatDescription(description, signal) { + return this.api.setChatDescription(orThrow(this.chatId, "setChatDescription"), description, signal); + } + pinChatMessage(message_id, other, signal) { + return this.api.pinChatMessage(orThrow(this.chatId, "pinChatMessage"), message_id, { + business_connection_id: this.businessConnectionId, + ...other + }, signal); + } + unpinChatMessage(message_id, other, signal) { + return this.api.unpinChatMessage(orThrow(this.chatId, "unpinChatMessage"), message_id, { + business_connection_id: this.businessConnectionId, + ...other + }, signal); + } + unpinAllChatMessages(signal) { + return this.api.unpinAllChatMessages(orThrow(this.chatId, "unpinAllChatMessages"), signal); + } + leaveChat(signal) { + return this.api.leaveChat(orThrow(this.chatId, "leaveChat"), signal); + } + getChat(signal) { + return this.api.getChat(orThrow(this.chatId, "getChat"), signal); + } + getChatAdministrators(signal) { + return this.api.getChatAdministrators(orThrow(this.chatId, "getChatAdministrators"), signal); + } + getChatMembersCount(...args) { + return this.getChatMemberCount(...args); + } + getChatMemberCount(signal) { + return this.api.getChatMemberCount(orThrow(this.chatId, "getChatMemberCount"), signal); + } + getAuthor(signal) { + return this.api.getChatMember(orThrow(this.chatId, "getAuthor"), orThrow(this.from, "getAuthor").id, signal); + } + getChatMember(user_id, signal) { + return this.api.getChatMember(orThrow(this.chatId, "getChatMember"), user_id, signal); + } + setChatStickerSet(sticker_set_name, signal) { + return this.api.setChatStickerSet(orThrow(this.chatId, "setChatStickerSet"), sticker_set_name, signal); + } + deleteChatStickerSet(signal) { + return this.api.deleteChatStickerSet(orThrow(this.chatId, "deleteChatStickerSet"), signal); + } + createForumTopic(name, other, signal) { + return this.api.createForumTopic(orThrow(this.chatId, "createForumTopic"), name, other, signal); + } + editForumTopic(other, signal) { + const message = orThrow(this.msg, "editForumTopic"); + const thread = orThrow(message.message_thread_id, "editForumTopic"); + return this.api.editForumTopic(message.chat.id, thread, other, signal); + } + closeForumTopic(signal) { + const message = orThrow(this.msg, "closeForumTopic"); + const thread = orThrow(message.message_thread_id, "closeForumTopic"); + return this.api.closeForumTopic(message.chat.id, thread, signal); + } + reopenForumTopic(signal) { + const message = orThrow(this.msg, "reopenForumTopic"); + const thread = orThrow(message.message_thread_id, "reopenForumTopic"); + return this.api.reopenForumTopic(message.chat.id, thread, signal); + } + deleteForumTopic(signal) { + const message = orThrow(this.msg, "deleteForumTopic"); + const thread = orThrow(message.message_thread_id, "deleteForumTopic"); + return this.api.deleteForumTopic(message.chat.id, thread, signal); + } + unpinAllForumTopicMessages(signal) { + const message = orThrow(this.msg, "unpinAllForumTopicMessages"); + const thread = orThrow(message.message_thread_id, "unpinAllForumTopicMessages"); + return this.api.unpinAllForumTopicMessages(message.chat.id, thread, signal); + } + editGeneralForumTopic(name, signal) { + return this.api.editGeneralForumTopic(orThrow(this.chatId, "editGeneralForumTopic"), name, signal); + } + closeGeneralForumTopic(signal) { + return this.api.closeGeneralForumTopic(orThrow(this.chatId, "closeGeneralForumTopic"), signal); + } + reopenGeneralForumTopic(signal) { + return this.api.reopenGeneralForumTopic(orThrow(this.chatId, "reopenGeneralForumTopic"), signal); + } + hideGeneralForumTopic(signal) { + return this.api.hideGeneralForumTopic(orThrow(this.chatId, "hideGeneralForumTopic"), signal); + } + unhideGeneralForumTopic(signal) { + return this.api.unhideGeneralForumTopic(orThrow(this.chatId, "unhideGeneralForumTopic"), signal); + } + unpinAllGeneralForumTopicMessages(signal) { + return this.api.unpinAllGeneralForumTopicMessages(orThrow(this.chatId, "unpinAllGeneralForumTopicMessages"), signal); + } + answerCallbackQuery(other, signal) { + return this.api.answerCallbackQuery(orThrow(this.callbackQuery, "answerCallbackQuery").id, typeof other === "string" ? { + text: other + } : other, signal); + } + setChatMenuButton(other, signal) { + return this.api.setChatMenuButton(other, signal); + } + getChatMenuButton(other, signal) { + return this.api.getChatMenuButton(other, signal); + } + setMyDefaultAdministratorRights(other, signal) { + return this.api.setMyDefaultAdministratorRights(other, signal); + } + getMyDefaultAdministratorRights(other, signal) { + return this.api.getMyDefaultAdministratorRights(other, signal); + } + editMessageText(text2, other, signal) { + const inlineId = this.inlineMessageId; + return inlineId !== void 0 ? this.api.editMessageTextInline(inlineId, text2, { + business_connection_id: this.businessConnectionId, + ...other + }, signal) : this.api.editMessageText(orThrow(this.chatId, "editMessageText"), orThrow(this.msg?.message_id ?? this.messageReaction?.message_id ?? this.messageReactionCount?.message_id, "editMessageText"), text2, { + business_connection_id: this.businessConnectionId, + ...other + }, signal); + } + editMessageCaption(other, signal) { + const inlineId = this.inlineMessageId; + return inlineId !== void 0 ? this.api.editMessageCaptionInline(inlineId, { + business_connection_id: this.businessConnectionId, + ...other + }, signal) : this.api.editMessageCaption(orThrow(this.chatId, "editMessageCaption"), orThrow(this.msg?.message_id ?? this.messageReaction?.message_id ?? this.messageReactionCount?.message_id, "editMessageCaption"), { + business_connection_id: this.businessConnectionId, + ...other + }, signal); + } + editMessageMedia(media, other, signal) { + const inlineId = this.inlineMessageId; + return inlineId !== void 0 ? this.api.editMessageMediaInline(inlineId, media, { + business_connection_id: this.businessConnectionId, + ...other + }, signal) : this.api.editMessageMedia(orThrow(this.chatId, "editMessageMedia"), orThrow(this.msg?.message_id ?? this.messageReaction?.message_id ?? this.messageReactionCount?.message_id, "editMessageMedia"), media, { + business_connection_id: this.businessConnectionId, + ...other + }, signal); + } + editMessageReplyMarkup(other, signal) { + const inlineId = this.inlineMessageId; + return inlineId !== void 0 ? this.api.editMessageReplyMarkupInline(inlineId, { + business_connection_id: this.businessConnectionId, + ...other + }, signal) : this.api.editMessageReplyMarkup(orThrow(this.chatId, "editMessageReplyMarkup"), orThrow(this.msg?.message_id ?? this.messageReaction?.message_id ?? this.messageReactionCount?.message_id, "editMessageReplyMarkup"), { + business_connection_id: this.businessConnectionId, + ...other + }, signal); + } + stopPoll(other, signal) { + return this.api.stopPoll(orThrow(this.chatId, "stopPoll"), orThrow(this.msg?.message_id ?? this.messageReaction?.message_id ?? this.messageReactionCount?.message_id, "stopPoll"), { + business_connection_id: this.businessConnectionId, + ...other + }, signal); + } + deleteMessage(signal) { + return this.api.deleteMessage(orThrow(this.chatId, "deleteMessage"), orThrow(this.msg?.message_id ?? this.messageReaction?.message_id ?? this.messageReactionCount?.message_id, "deleteMessage"), signal); + } + deleteMessages(message_ids, signal) { + return this.api.deleteMessages(orThrow(this.chatId, "deleteMessages"), message_ids, signal); + } + deleteBusinessMessages(message_ids, signal) { + return this.api.deleteBusinessMessages(orThrow(this.businessConnectionId, "deleteBusinessMessages"), message_ids, signal); + } + setBusinessAccountName(first_name, other, signal) { + return this.api.setBusinessAccountName(orThrow(this.businessConnectionId, "setBusinessAccountName"), first_name, other, signal); + } + setBusinessAccountUsername(username, signal) { + return this.api.setBusinessAccountUsername(orThrow(this.businessConnectionId, "setBusinessAccountUsername"), username, signal); + } + setBusinessAccountBio(bio, signal) { + return this.api.setBusinessAccountBio(orThrow(this.businessConnectionId, "setBusinessAccountBio"), bio, signal); + } + setBusinessAccountProfilePhoto(photo, other, signal) { + return this.api.setBusinessAccountProfilePhoto(orThrow(this.businessConnectionId, "setBusinessAccountProfilePhoto"), photo, other, signal); + } + removeBusinessAccountProfilePhoto(other, signal) { + return this.api.removeBusinessAccountProfilePhoto(orThrow(this.businessConnectionId, "removeBusinessAccountProfilePhoto"), other, signal); + } + setBusinessAccountGiftSettings(show_gift_button, accepted_gift_types, signal) { + return this.api.setBusinessAccountGiftSettings(orThrow(this.businessConnectionId, "setBusinessAccountGiftSettings"), show_gift_button, accepted_gift_types, signal); + } + getBusinessAccountStarBalance(signal) { + return this.api.getBusinessAccountStarBalance(orThrow(this.businessConnectionId, "getBusinessAccountStarBalance"), signal); + } + transferBusinessAccountStars(star_count, signal) { + return this.api.transferBusinessAccountStars(orThrow(this.businessConnectionId, "transferBusinessAccountStars"), star_count, signal); + } + getBusinessAccountGifts(other, signal) { + return this.api.getBusinessAccountGifts(orThrow(this.businessConnectionId, "getBusinessAccountGifts"), other, signal); + } + convertGiftToStars(owned_gift_id, signal) { + return this.api.convertGiftToStars(orThrow(this.businessConnectionId, "convertGiftToStars"), owned_gift_id, signal); + } + upgradeGift(owned_gift_id, other, signal) { + return this.api.upgradeGift(orThrow(this.businessConnectionId, "upgradeGift"), owned_gift_id, other, signal); + } + transferGift(owned_gift_id, new_owner_chat_id, star_count, signal) { + return this.api.transferGift(orThrow(this.businessConnectionId, "transferGift"), owned_gift_id, new_owner_chat_id, star_count, signal); + } + postStory(content, active_period, other, signal) { + return this.api.postStory(orThrow(this.businessConnectionId, "postStory"), content, active_period, other, signal); + } + repostStory(active_period, other, signal) { + const story = orThrow(this.msg?.story, "repostStory"); + return this.api.repostStory(orThrow(this.businessConnectionId, "repostStory"), story.chat.id, story.id, active_period, other, signal); + } + editStory(story_id, content, other, signal) { + return this.api.editStory(orThrow(this.businessConnectionId, "editStory"), story_id, content, other, signal); + } + deleteStory(story_id, signal) { + return this.api.deleteStory(orThrow(this.businessConnectionId, "deleteStory"), story_id, signal); + } + replyWithSticker(sticker, other, signal) { + const msg = this.msg; + return this.api.sendSticker(orThrow(this.chatId, "sendSticker"), sticker, { + business_connection_id: this.businessConnectionId, + ...msg?.is_topic_message ? { + message_thread_id: msg.message_thread_id + } : {}, + direct_messages_topic_id: msg?.direct_messages_topic?.topic_id, + ...other + }, signal); + } + getCustomEmojiStickers(signal) { + return this.api.getCustomEmojiStickers((this.msg?.entities ?? []).filter((e) => e.type === "custom_emoji").map((e) => e.custom_emoji_id), signal); + } + replyWithGift(gift_id, other, signal) { + return this.api.sendGift(orThrow(this.from, "sendGift").id, gift_id, other, signal); + } + giftPremiumSubscription(month_count, star_count, other, signal) { + return this.api.giftPremiumSubscription(orThrow(this.from, "giftPremiumSubscription").id, month_count, star_count, other, signal); + } + replyWithGiftToChannel(gift_id, other, signal) { + return this.api.sendGiftToChannel(orThrow(this.chat, "sendGift").id, gift_id, other, signal); + } + answerInlineQuery(results, other, signal) { + return this.api.answerInlineQuery(orThrow(this.inlineQuery, "answerInlineQuery").id, results, other, signal); + } + savePreparedInlineMessage(result, other, signal) { + return this.api.savePreparedInlineMessage(orThrow(this.from, "savePreparedInlineMessage").id, result, other, signal); + } + replyWithInvoice(title2, description, payload, currency, prices, other, signal) { + const msg = this.msg; + return this.api.sendInvoice(orThrow(this.chatId, "sendInvoice"), title2, description, payload, currency, prices, { + ...msg?.is_topic_message ? { + message_thread_id: msg.message_thread_id + } : {}, + direct_messages_topic_id: msg?.direct_messages_topic?.topic_id, + ...other + }, signal); + } + answerShippingQuery(ok2, other, signal) { + return this.api.answerShippingQuery(orThrow(this.shippingQuery, "answerShippingQuery").id, ok2, other, signal); + } + answerPreCheckoutQuery(ok2, other, signal) { + return this.api.answerPreCheckoutQuery(orThrow(this.preCheckoutQuery, "answerPreCheckoutQuery").id, ok2, typeof other === "string" ? { + error_message: other + } : other, signal); + } + refundStarPayment(signal) { + return this.api.refundStarPayment(orThrow(this.from, "refundStarPayment").id, orThrow(this.msg?.successful_payment, "refundStarPayment").telegram_payment_charge_id, signal); + } + editUserStarSubscription(telegram_payment_charge_id, is_canceled, signal) { + return this.api.editUserStarSubscription(orThrow(this.from, "editUserStarSubscription").id, telegram_payment_charge_id, is_canceled, signal); + } + verifyUser(other, signal) { + return this.api.verifyUser(orThrow(this.from, "verifyUser").id, other, signal); + } + verifyChat(other, signal) { + return this.api.verifyChat(orThrow(this.chatId, "verifyChat"), other, signal); + } + removeUserVerification(signal) { + return this.api.removeUserVerification(orThrow(this.from, "removeUserVerification").id, signal); + } + removeChatVerification(signal) { + return this.api.removeChatVerification(orThrow(this.chatId, "removeChatVerification"), signal); + } + readBusinessMessage(signal) { + return this.api.readBusinessMessage(orThrow(this.businessConnectionId, "readBusinessMessage"), orThrow(this.chatId, "readBusinessMessage"), orThrow(this.msgId, "readBusinessMessage"), signal); + } + setPassportDataErrors(errors, signal) { + return this.api.setPassportDataErrors(orThrow(this.from, "setPassportDataErrors").id, errors, signal); + } + replyWithGame(game_short_name, other, signal) { + const msg = this.msg; + return this.api.sendGame(orThrow(this.chatId, "sendGame"), game_short_name, { + business_connection_id: this.businessConnectionId, + ...msg?.is_topic_message ? { + message_thread_id: msg.message_thread_id + } : {}, + ...other + }, signal); + } +}; +function orThrow(value, method) { + if (value === void 0) { + throw new Error(`Missing information for API call to ${method}`); + } + return value; +} +__name(orThrow, "orThrow"); +function triggerFn(trigger) { + return toArray(trigger).map((t2) => typeof t2 === "string" ? (txt) => txt === t2 ? t2 : null : (txt) => txt.match(t2)); +} +__name(triggerFn, "triggerFn"); +function match2(ctx, content, triggers) { + for (const t2 of triggers) { + const res = t2(content); + if (res) { + ctx.match = res; + return true; + } + } + return false; +} +__name(match2, "match"); +function toArray(e) { + return Array.isArray(e) ? e : [ + e + ]; +} +__name(toArray, "toArray"); +var BotError = class extends Error { + static { + __name(this, "BotError"); + } + error; + ctx; + constructor(error, ctx) { + super(generateBotErrorMessage(error)); + this.error = error; + this.ctx = ctx; + this.name = "BotError"; + if (error instanceof Error) this.stack = error.stack; + } +}; +function generateBotErrorMessage(error) { + let msg; + if (error instanceof Error) { + msg = `${error.name} in middleware: ${error.message}`; + } else { + const type = typeof error; + msg = `Non-error value of type ${type} thrown in middleware`; + switch (type) { + case "bigint": + case "boolean": + case "number": + case "symbol": + msg += `: ${error}`; + break; + case "string": + msg += `: ${String(error).substring(0, 50)}`; + break; + default: + msg += "!"; + break; + } + } + return msg; +} +__name(generateBotErrorMessage, "generateBotErrorMessage"); +function flatten(mw) { + return typeof mw === "function" ? mw : (ctx, next) => mw.middleware()(ctx, next); +} +__name(flatten, "flatten"); +function concat1(first, andThen) { + return async (ctx, next) => { + let nextCalled = false; + await first(ctx, async () => { + if (nextCalled) throw new Error("`next` already called before!"); + else nextCalled = true; + await andThen(ctx, next); + }); + }; +} +__name(concat1, "concat1"); +function pass(_ctx, next) { + return next(); +} +__name(pass, "pass"); +var leaf1 = /* @__PURE__ */ __name(() => Promise.resolve(), "leaf1"); +async function run(middleware, ctx) { + await middleware(ctx, leaf1); +} +__name(run, "run"); +var Composer = class _Composer { + static { + __name(this, "Composer"); + } + handler; + constructor(...middleware) { + this.handler = middleware.length === 0 ? pass : middleware.map(flatten).reduce(concat1); + } + middleware() { + return this.handler; + } + use(...middleware) { + const composer = new _Composer(...middleware); + this.handler = concat1(this.handler, flatten(composer)); + return composer; + } + on(filter, ...middleware) { + return this.filter(Context2.has.filterQuery(filter), ...middleware); + } + hears(trigger, ...middleware) { + return this.filter(Context2.has.text(trigger), ...middleware); + } + command(command, ...middleware) { + return this.filter(Context2.has.command(command), ...middleware); + } + reaction(reaction, ...middleware) { + return this.filter(Context2.has.reaction(reaction), ...middleware); + } + chatType(chatType, ...middleware) { + return this.filter(Context2.has.chatType(chatType), ...middleware); + } + callbackQuery(trigger, ...middleware) { + return this.filter(Context2.has.callbackQuery(trigger), ...middleware); + } + gameQuery(trigger, ...middleware) { + return this.filter(Context2.has.gameQuery(trigger), ...middleware); + } + inlineQuery(trigger, ...middleware) { + return this.filter(Context2.has.inlineQuery(trigger), ...middleware); + } + chosenInlineResult(resultId, ...middleware) { + return this.filter(Context2.has.chosenInlineResult(resultId), ...middleware); + } + preCheckoutQuery(trigger, ...middleware) { + return this.filter(Context2.has.preCheckoutQuery(trigger), ...middleware); + } + shippingQuery(trigger, ...middleware) { + return this.filter(Context2.has.shippingQuery(trigger), ...middleware); + } + filter(predicate, ...middleware) { + const composer = new _Composer(...middleware); + this.branch(predicate, composer, pass); + return composer; + } + drop(predicate, ...middleware) { + return this.filter(async (ctx) => !await predicate(ctx), ...middleware); + } + fork(...middleware) { + const composer = new _Composer(...middleware); + const fork = flatten(composer); + this.use((ctx, next) => Promise.all([ + next(), + run(fork, ctx) + ])); + return composer; + } + lazy(middlewareFactory) { + return this.use(async (ctx, next) => { + const middleware = await middlewareFactory(ctx); + const arr = Array.isArray(middleware) ? middleware : [ + middleware + ]; + await flatten(new _Composer(...arr))(ctx, next); + }); + } + route(router, routeHandlers, fallback = pass) { + return this.lazy(async (ctx) => { + const route = await router(ctx); + return (route === void 0 || !routeHandlers[route] ? fallback : routeHandlers[route]) ?? []; + }); + } + branch(predicate, trueMiddleware, falseMiddleware) { + return this.lazy(async (ctx) => await predicate(ctx) ? trueMiddleware : falseMiddleware); + } + errorBoundary(errorHandler2, ...middleware) { + const composer = new _Composer(...middleware); + const bound = flatten(composer); + this.use(async (ctx, next) => { + let nextCalled = false; + const cont = /* @__PURE__ */ __name(() => (nextCalled = true, Promise.resolve()), "cont"); + try { + await bound(ctx, cont); + } catch (err) { + nextCalled = false; + await errorHandler2(new BotError(err, ctx), cont); + } + if (nextCalled) await next(); + }); + return composer; + } +}; +var s = 1e3; +var m = s * 60; +var h = m * 60; +var d = h * 24; +var w = d * 7; +var y = d * 365.25; +var ms = /* @__PURE__ */ __name(function(val, options) { + options = options || {}; + var type = typeof val; + if (type === "string" && val.length > 0) { + return parse1(val); + } else if (type === "number" && isFinite(val)) { + return options.long ? fmtLong(val) : fmtShort(val); + } + throw new Error("val is not a non-empty string or a valid number. val=" + JSON.stringify(val)); +}, "ms"); +function parse1(str2) { + str2 = String(str2); + if (str2.length > 100) { + return; + } + var match3 = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(str2); + if (!match3) { + return; + } + var n = parseFloat(match3[1]); + var type = (match3[2] || "ms").toLowerCase(); + switch (type) { + case "years": + case "year": + case "yrs": + case "yr": + case "y": + return n * y; + case "weeks": + case "week": + case "w": + return n * w; + case "days": + case "day": + case "d": + return n * d; + case "hours": + case "hour": + case "hrs": + case "hr": + case "h": + return n * h; + case "minutes": + case "minute": + case "mins": + case "min": + case "m": + return n * m; + case "seconds": + case "second": + case "secs": + case "sec": + case "s": + return n * s; + case "milliseconds": + case "millisecond": + case "msecs": + case "msec": + case "ms": + return n; + default: + return void 0; + } +} +__name(parse1, "parse1"); +function fmtShort(ms2) { + var msAbs = Math.abs(ms2); + if (msAbs >= d) { + return Math.round(ms2 / d) + "d"; + } + if (msAbs >= h) { + return Math.round(ms2 / h) + "h"; + } + if (msAbs >= m) { + return Math.round(ms2 / m) + "m"; + } + if (msAbs >= s) { + return Math.round(ms2 / s) + "s"; + } + return ms2 + "ms"; +} +__name(fmtShort, "fmtShort"); +function fmtLong(ms2) { + var msAbs = Math.abs(ms2); + if (msAbs >= d) { + return plural(ms2, msAbs, d, "day"); + } + if (msAbs >= h) { + return plural(ms2, msAbs, h, "hour"); + } + if (msAbs >= m) { + return plural(ms2, msAbs, m, "minute"); + } + if (msAbs >= s) { + return plural(ms2, msAbs, s, "second"); + } + return ms2 + " ms"; +} +__name(fmtLong, "fmtLong"); +function plural(ms2, msAbs, n, name) { + var isPlural = msAbs >= n * 1.5; + return Math.round(ms2 / n) + " " + name + (isPlural ? "s" : ""); +} +__name(plural, "plural"); +function defaultSetTimout() { + throw new Error("setTimeout has not been defined"); +} +__name(defaultSetTimout, "defaultSetTimout"); +function defaultClearTimeout() { + throw new Error("clearTimeout has not been defined"); +} +__name(defaultClearTimeout, "defaultClearTimeout"); +var cachedSetTimeout = defaultSetTimout; +var cachedClearTimeout = defaultClearTimeout; +var globalContext; +if (typeof window !== "undefined") { + globalContext = window; +} else if (typeof self !== "undefined") { + globalContext = self; +} else { + globalContext = {}; +} +if (typeof globalContext.setTimeout === "function") { + cachedSetTimeout = setTimeout; +} +if (typeof globalContext.clearTimeout === "function") { + cachedClearTimeout = clearTimeout; +} +function runTimeout(fun) { + if (cachedSetTimeout === setTimeout) { + return setTimeout(fun, 0); + } + if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { + cachedSetTimeout = setTimeout; + return setTimeout(fun, 0); + } + try { + return cachedSetTimeout(fun, 0); + } catch (e) { + try { + return cachedSetTimeout.call(null, fun, 0); + } catch (e2) { + return cachedSetTimeout.call(this, fun, 0); + } + } +} +__name(runTimeout, "runTimeout"); +function runClearTimeout(marker) { + if (cachedClearTimeout === clearTimeout) { + return clearTimeout(marker); + } + if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { + cachedClearTimeout = clearTimeout; + return clearTimeout(marker); + } + try { + return cachedClearTimeout(marker); + } catch (e) { + try { + return cachedClearTimeout.call(null, marker); + } catch (e2) { + return cachedClearTimeout.call(this, marker); + } + } +} +__name(runClearTimeout, "runClearTimeout"); +var queue = []; +var draining = false; +var currentQueue; +var queueIndex = -1; +function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; + } + draining = false; + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; + } + if (queue.length) { + drainQueue(); + } +} +__name(cleanUpNextTick, "cleanUpNextTick"); +function drainQueue() { + if (draining) { + return; + } + var timeout = runTimeout(cleanUpNextTick); + draining = true; + var len = queue.length; + while (len) { + currentQueue = queue; + queue = []; + while (++queueIndex < len) { + if (currentQueue) { + currentQueue[queueIndex].run(); + } + } + queueIndex = -1; + len = queue.length; + } + currentQueue = null; + draining = false; + runClearTimeout(timeout); +} +__name(drainQueue, "drainQueue"); +function nextTick(fun) { + var args = new Array(arguments.length - 1); + if (arguments.length > 1) { + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + } + queue.push(new Item(fun, args)); + if (queue.length === 1 && !draining) { + runTimeout(drainQueue); + } +} +__name(nextTick, "nextTick"); +function Item(fun, array) { + this.fun = fun; + this.array = array; +} +__name(Item, "Item"); +Item.prototype.run = function() { + this.fun.apply(null, this.array); +}; +var title = "browser"; +var platform = "browser"; +var browser = true; +var argv = []; +var version = ""; +var versions = {}; +var release = {}; +var config = {}; +function noop() { +} +__name(noop, "noop"); +var on = noop; +var addListener = noop; +var once = noop; +var off = noop; +var removeListener = noop; +var removeAllListeners = noop; +var emit = noop; +function binding(name) { + throw new Error("process.binding is not supported"); +} +__name(binding, "binding"); +function cwd() { + return "/"; +} +__name(cwd, "cwd"); +function chdir(dir2) { + throw new Error("process.chdir is not supported"); +} +__name(chdir, "chdir"); +function umask() { + return 0; +} +__name(umask, "umask"); +var performance2 = globalContext.performance || {}; +var performanceNow = performance2.now || performance2.mozNow || performance2.msNow || performance2.oNow || performance2.webkitNow || function() { + return (/* @__PURE__ */ new Date()).getTime(); +}; +function hrtime(previousTimestamp) { + var clocktime = performanceNow.call(performance2) * 1e-3; + var seconds = Math.floor(clocktime); + var nanoseconds = Math.floor(clocktime % 1 * 1e9); + if (previousTimestamp) { + seconds = seconds - previousTimestamp[0]; + nanoseconds = nanoseconds - previousTimestamp[1]; + if (nanoseconds < 0) { + seconds--; + nanoseconds += 1e9; + } + } + return [ + seconds, + nanoseconds + ]; +} +__name(hrtime, "hrtime"); +var startTime = /* @__PURE__ */ new Date(); +function uptime() { + var currentTime = /* @__PURE__ */ new Date(); + var dif = currentTime - startTime; + return dif / 1e3; +} +__name(uptime, "uptime"); +var process2 = { + nextTick, + title, + browser, + env: { + NODE_ENV: "production" + }, + argv, + version, + versions, + on, + addListener, + once, + off, + removeListener, + removeAllListeners, + emit, + binding, + cwd, + chdir, + umask, + hrtime, + platform, + release, + config, + uptime +}; +function createCommonjsModule(fn, basedir, module) { + return module = { + path: basedir, + exports: {}, + require: /* @__PURE__ */ __name(function(path, base) { + return commonjsRequire(path, base === void 0 || base === null ? module.path : base); + }, "require") + }, fn(module, module.exports), module.exports; +} +__name(createCommonjsModule, "createCommonjsModule"); +function commonjsRequire() { + throw new Error("Dynamic requires are not currently supported by @rollup/plugin-commonjs"); +} +__name(commonjsRequire, "commonjsRequire"); +function setup(env) { + createDebug.debug = createDebug; + createDebug.default = createDebug; + createDebug.coerce = coerce; + createDebug.disable = disable; + createDebug.enable = enable; + createDebug.enabled = enabled; + createDebug.humanize = ms; + createDebug.destroy = destroy2; + Object.keys(env).forEach((key) => { + createDebug[key] = env[key]; + }); + createDebug.names = []; + createDebug.skips = []; + createDebug.formatters = {}; + function selectColor(namespace) { + let hash = 0; + for (let i = 0; i < namespace.length; i++) { + hash = (hash << 5) - hash + namespace.charCodeAt(i); + hash |= 0; + } + return createDebug.colors[Math.abs(hash) % createDebug.colors.length]; + } + __name(selectColor, "selectColor"); + createDebug.selectColor = selectColor; + function createDebug(namespace) { + let prevTime; + let enableOverride = null; + let namespacesCache; + let enabledCache; + function debug4(...args) { + if (!debug4.enabled) { + return; + } + const self2 = debug4; + const curr = Number(/* @__PURE__ */ new Date()); + const ms2 = curr - (prevTime || curr); + self2.diff = ms2; + self2.prev = prevTime; + self2.curr = curr; + prevTime = curr; + args[0] = createDebug.coerce(args[0]); + if (typeof args[0] !== "string") { + args.unshift("%O"); + } + let index = 0; + args[0] = args[0].replace(/%([a-zA-Z%])/g, (match3, format) => { + if (match3 === "%%") { + return "%"; + } + index++; + const formatter = createDebug.formatters[format]; + if (typeof formatter === "function") { + const val = args[index]; + match3 = formatter.call(self2, val); + args.splice(index, 1); + index--; + } + return match3; + }); + createDebug.formatArgs.call(self2, args); + const logFn = self2.log || createDebug.log; + logFn.apply(self2, args); + } + __name(debug4, "debug"); + debug4.namespace = namespace; + debug4.useColors = createDebug.useColors(); + debug4.color = createDebug.selectColor(namespace); + debug4.extend = extend; + debug4.destroy = createDebug.destroy; + Object.defineProperty(debug4, "enabled", { + enumerable: true, + configurable: false, + get: /* @__PURE__ */ __name(() => { + if (enableOverride !== null) { + return enableOverride; + } + if (namespacesCache !== createDebug.namespaces) { + namespacesCache = createDebug.namespaces; + enabledCache = createDebug.enabled(namespace); + } + return enabledCache; + }, "get"), + set: /* @__PURE__ */ __name((v) => { + enableOverride = v; + }, "set") + }); + if (typeof createDebug.init === "function") { + createDebug.init(debug4); + } + return debug4; + } + __name(createDebug, "createDebug"); + function extend(namespace, delimiter) { + const newDebug = createDebug(this.namespace + (typeof delimiter === "undefined" ? ":" : delimiter) + namespace); + newDebug.log = this.log; + return newDebug; + } + __name(extend, "extend"); + function enable(namespaces) { + createDebug.save(namespaces); + createDebug.namespaces = namespaces; + createDebug.names = []; + createDebug.skips = []; + const split = (typeof namespaces === "string" ? namespaces : "").trim().replace(/\s+/g, ",").split(",").filter(Boolean); + for (const ns of split) { + if (ns[0] === "-") { + createDebug.skips.push(ns.slice(1)); + } else { + createDebug.names.push(ns); + } + } + } + __name(enable, "enable"); + function matchesTemplate(search, template) { + let searchIndex = 0; + let templateIndex = 0; + let starIndex = -1; + let matchIndex = 0; + while (searchIndex < search.length) { + if (templateIndex < template.length && (template[templateIndex] === search[searchIndex] || template[templateIndex] === "*")) { + if (template[templateIndex] === "*") { + starIndex = templateIndex; + matchIndex = searchIndex; + templateIndex++; + } else { + searchIndex++; + templateIndex++; + } + } else if (starIndex !== -1) { + templateIndex = starIndex + 1; + matchIndex++; + searchIndex = matchIndex; + } else { + return false; + } + } + while (templateIndex < template.length && template[templateIndex] === "*") { + templateIndex++; + } + return templateIndex === template.length; + } + __name(matchesTemplate, "matchesTemplate"); + function disable() { + const namespaces = [ + ...createDebug.names, + ...createDebug.skips.map((namespace) => "-" + namespace) + ].join(","); + createDebug.enable(""); + return namespaces; + } + __name(disable, "disable"); + function enabled(name) { + for (const skip of createDebug.skips) { + if (matchesTemplate(name, skip)) { + return false; + } + } + for (const ns of createDebug.names) { + if (matchesTemplate(name, ns)) { + return true; + } + } + return false; + } + __name(enabled, "enabled"); + function coerce(val) { + if (val instanceof Error) { + return val.stack || val.message; + } + return val; + } + __name(coerce, "coerce"); + function destroy2() { + console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."); + } + __name(destroy2, "destroy2"); + createDebug.enable(createDebug.load()); + return createDebug; +} +__name(setup, "setup"); +var common = setup; +var browser$1 = createCommonjsModule(function(module, exports) { + exports.formatArgs = formatArgs2; + exports.save = save2; + exports.load = load2; + exports.useColors = useColors2; + exports.storage = localstorage(); + exports.destroy = /* @__PURE__ */ (() => { + let warned = false; + return () => { + if (!warned) { + warned = true; + console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."); + } + }; + })(); + exports.colors = [ + "#0000CC", + "#0000FF", + "#0033CC", + "#0033FF", + "#0066CC", + "#0066FF", + "#0099CC", + "#0099FF", + "#00CC00", + "#00CC33", + "#00CC66", + "#00CC99", + "#00CCCC", + "#00CCFF", + "#3300CC", + "#3300FF", + "#3333CC", + "#3333FF", + "#3366CC", + "#3366FF", + "#3399CC", + "#3399FF", + "#33CC00", + "#33CC33", + "#33CC66", + "#33CC99", + "#33CCCC", + "#33CCFF", + "#6600CC", + "#6600FF", + "#6633CC", + "#6633FF", + "#66CC00", + "#66CC33", + "#9900CC", + "#9900FF", + "#9933CC", + "#9933FF", + "#99CC00", + "#99CC33", + "#CC0000", + "#CC0033", + "#CC0066", + "#CC0099", + "#CC00CC", + "#CC00FF", + "#CC3300", + "#CC3333", + "#CC3366", + "#CC3399", + "#CC33CC", + "#CC33FF", + "#CC6600", + "#CC6633", + "#CC9900", + "#CC9933", + "#CCCC00", + "#CCCC33", + "#FF0000", + "#FF0033", + "#FF0066", + "#FF0099", + "#FF00CC", + "#FF00FF", + "#FF3300", + "#FF3333", + "#FF3366", + "#FF3399", + "#FF33CC", + "#FF33FF", + "#FF6600", + "#FF6633", + "#FF9900", + "#FF9933", + "#FFCC00", + "#FFCC33" + ]; + function useColors2() { + if (typeof window !== "undefined" && window.process && (window.process.type === "renderer" || window.process.__nwjs)) { + return true; + } + if (typeof navigator !== "undefined" && "Cloudflare-Workers" && "Cloudflare-Workers".toLowerCase().match(/(edge|trident)\/(\d+)/)) { + return false; + } + let m2; + return typeof document !== "undefined" && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance || typeof window !== "undefined" && window.console && (window.console.firebug || window.console.exception && window.console.table) || typeof navigator !== "undefined" && "Cloudflare-Workers" && (m2 = "Cloudflare-Workers".toLowerCase().match(/firefox\/(\d+)/)) && parseInt(m2[1], 10) >= 31 || typeof navigator !== "undefined" && "Cloudflare-Workers" && "Cloudflare-Workers".toLowerCase().match(/applewebkit\/(\d+)/); + } + __name(useColors2, "useColors2"); + function formatArgs2(args) { + args[0] = (this.useColors ? "%c" : "") + this.namespace + (this.useColors ? " %c" : " ") + args[0] + (this.useColors ? "%c " : " ") + "+" + module.exports.humanize(this.diff); + if (!this.useColors) { + return; + } + const c = "color: " + this.color; + args.splice(1, 0, c, "color: inherit"); + let index = 0; + let lastC = 0; + args[0].replace(/%[a-zA-Z%]/g, (match3) => { + if (match3 === "%%") { + return; + } + index++; + if (match3 === "%c") { + lastC = index; + } + }); + args.splice(lastC, 0, c); + } + __name(formatArgs2, "formatArgs2"); + exports.log = console.debug || console.log || (() => { + }); + function save2(namespaces) { + try { + if (namespaces) { + exports.storage.setItem("debug", namespaces); + } else { + exports.storage.removeItem("debug"); + } + } catch (error) { + } + } + __name(save2, "save2"); + function load2() { + let r; + try { + r = exports.storage.getItem("debug") || exports.storage.getItem("DEBUG"); + } catch (error) { + } + if (!r && typeof process2 !== "undefined" && "env" in process2) { + r = process2.env.DEBUG; + } + return r; + } + __name(load2, "load2"); + function localstorage() { + try { + return localStorage; + } catch (error) { + } + } + __name(localstorage, "localstorage"); + module.exports = common(exports); + const { formatters } = module.exports; + formatters.j = function(v) { + try { + return JSON.stringify(v); + } catch (error) { + return "[UnexpectedJSONParseError]: " + error.message; + } + }; +}); +browser$1.colors; +browser$1.destroy; +browser$1.formatArgs; +browser$1.load; +browser$1.log; +browser$1.save; +browser$1.storage; +browser$1.useColors; +var itrToStream = /* @__PURE__ */ __name((itr) => { + const it = itr[Symbol.asyncIterator](); + return new ReadableStream({ + async pull(controller) { + const chunk = await it.next(); + if (chunk.done) controller.close(); + else controller.enqueue(chunk.value); + } + }); +}, "itrToStream"); +var baseFetchConfig = /* @__PURE__ */ __name((_apiRoot) => ({}), "baseFetchConfig"); +var defaultAdapter = "cloudflare"; +var debug = browser$1("grammy:warn"); +var GrammyError = class extends Error { + static { + __name(this, "GrammyError"); + } + method; + payload; + ok; + error_code; + description; + parameters; + constructor(message, err, method, payload) { + super(`${message} (${err.error_code}: ${err.description})`); + this.method = method; + this.payload = payload; + this.ok = false; + this.name = "GrammyError"; + this.error_code = err.error_code; + this.description = err.description; + this.parameters = err.parameters ?? {}; + } +}; +function toGrammyError(err, method, payload) { + switch (err.error_code) { + case 401: + debug("Error 401 means that your bot token is wrong, talk to https://t.me/BotFather to check it."); + break; + case 409: + debug("Error 409 means that you are running your bot several times on long polling. Consider revoking the bot token if you believe that no other instance is running."); + break; + } + return new GrammyError(`Call to '${method}' failed!`, err, method, payload); +} +__name(toGrammyError, "toGrammyError"); +var HttpError = class extends Error { + static { + __name(this, "HttpError"); + } + error; + constructor(message, error) { + super(message); + this.error = error; + this.name = "HttpError"; + } +}; +function isTelegramError(err) { + return typeof err === "object" && err !== null && "status" in err && "statusText" in err; +} +__name(isTelegramError, "isTelegramError"); +function toHttpError(method, sensitiveLogs, err) { + let msg = `Network request for '${method}' failed!`; + if (isTelegramError(err)) msg += ` (${err.status}: ${err.statusText})`; + if (sensitiveLogs && err instanceof Error) msg += ` ${err.message}`; + return new HttpError(msg, err); +} +__name(toHttpError, "toHttpError"); +function checkWindows() { + const global = globalThis; + const os = global.Deno?.build?.os; + return typeof os === "string" ? os === "windows" : global.navigator?.platform?.startsWith("Win") ?? global.process?.platform?.startsWith("win") ?? false; +} +__name(checkWindows, "checkWindows"); +var isWindows = checkWindows(); +function assertPath(path) { + if (typeof path !== "string") { + throw new TypeError(`Path must be a string, received "${JSON.stringify(path)}"`); + } +} +__name(assertPath, "assertPath"); +function stripSuffix(name, suffix) { + if (suffix.length >= name.length) { + return name; + } + const lenDiff = name.length - suffix.length; + for (let i = suffix.length - 1; i >= 0; --i) { + if (name.charCodeAt(lenDiff + i) !== suffix.charCodeAt(i)) { + return name; + } + } + return name.slice(0, -suffix.length); +} +__name(stripSuffix, "stripSuffix"); +function lastPathSegment(path, isSep, start = 0) { + let matchedNonSeparator = false; + let end = path.length; + for (let i = path.length - 1; i >= start; --i) { + if (isSep(path.charCodeAt(i))) { + if (matchedNonSeparator) { + start = i + 1; + break; + } + } else if (!matchedNonSeparator) { + matchedNonSeparator = true; + end = i + 1; + } + } + return path.slice(start, end); +} +__name(lastPathSegment, "lastPathSegment"); +function assertArgs(path, suffix) { + assertPath(path); + if (path.length === 0) return path; + if (typeof suffix !== "string") { + throw new TypeError(`Suffix must be a string, received "${JSON.stringify(suffix)}"`); + } +} +__name(assertArgs, "assertArgs"); +function assertArg(url) { + url = url instanceof URL ? url : new URL(url); + if (url.protocol !== "file:") { + throw new TypeError(`URL must be a file URL: received "${url.protocol}"`); + } + return url; +} +__name(assertArg, "assertArg"); +function fromFileUrl(url) { + url = assertArg(url); + return decodeURIComponent(url.pathname.replace(/%(?![0-9A-Fa-f]{2})/g, "%25")); +} +__name(fromFileUrl, "fromFileUrl"); +function stripTrailingSeparators(segment, isSep) { + if (segment.length <= 1) { + return segment; + } + let end = segment.length; + for (let i = segment.length - 1; i > 0; i--) { + if (isSep(segment.charCodeAt(i))) { + end = i; + } else { + break; + } + } + return segment.slice(0, end); +} +__name(stripTrailingSeparators, "stripTrailingSeparators"); +function isPosixPathSeparator(code) { + return code === 47; +} +__name(isPosixPathSeparator, "isPosixPathSeparator"); +function basename(path, suffix = "") { + if (path instanceof URL) { + path = fromFileUrl(path); + } + assertArgs(path, suffix); + const lastSegment = lastPathSegment(path, isPosixPathSeparator); + const strippedSegment = stripTrailingSeparators(lastSegment, isPosixPathSeparator); + return suffix ? stripSuffix(strippedSegment, suffix) : strippedSegment; +} +__name(basename, "basename"); +function isPathSeparator(code) { + return code === 47 || code === 92; +} +__name(isPathSeparator, "isPathSeparator"); +function isWindowsDeviceRoot(code) { + return code >= 97 && code <= 122 || code >= 65 && code <= 90; +} +__name(isWindowsDeviceRoot, "isWindowsDeviceRoot"); +function fromFileUrl1(url) { + url = assertArg(url); + let path = decodeURIComponent(url.pathname.replace(/\//g, "\\").replace(/%(?![0-9A-Fa-f]{2})/g, "%25")).replace(/^\\*([A-Za-z]:)(\\|$)/, "$1\\"); + if (url.hostname !== "") { + path = `\\\\${url.hostname}${path}`; + } + return path; +} +__name(fromFileUrl1, "fromFileUrl1"); +function basename1(path, suffix = "") { + if (path instanceof URL) { + path = fromFileUrl1(path); + } + assertArgs(path, suffix); + let start = 0; + if (path.length >= 2) { + const drive = path.charCodeAt(0); + if (isWindowsDeviceRoot(drive)) { + if (path.charCodeAt(1) === 58) start = 2; + } + } + const lastSegment = lastPathSegment(path, isPathSeparator, start); + const strippedSegment = stripTrailingSeparators(lastSegment, isPathSeparator); + return suffix ? stripSuffix(strippedSegment, suffix) : strippedSegment; +} +__name(basename1, "basename1"); +function basename2(path, suffix = "") { + return isWindows ? basename1(path, suffix) : basename(path, suffix); +} +__name(basename2, "basename2"); +var InputFile = class { + static { + __name(this, "InputFile"); + } + consumed = false; + fileData; + filename; + constructor(file, filename) { + this.fileData = file; + filename ??= this.guessFilename(file); + this.filename = filename; + } + guessFilename(file) { + if (typeof file === "string") return basename2(file); + if (typeof file !== "object") return void 0; + if ("url" in file) return basename2(file.url); + if (!(file instanceof URL)) return void 0; + return basename2(file.pathname) || basename2(file.hostname); + } + toRaw() { + if (this.consumed) { + throw new Error("Cannot reuse InputFile data source!"); + } + const data2 = this.fileData; + if (data2 instanceof Blob) return data2.stream(); + if (data2 instanceof URL) return fetchFile(data2); + if ("url" in data2) return fetchFile(data2.url); + if (!(data2 instanceof Uint8Array)) this.consumed = true; + return data2; + } + toJSON() { + throw new Error("InputFile instances must be sent via grammY"); + } +}; +async function* fetchFile(url) { + const { body } = await fetch(url); + if (body === null) { + throw new Error(`Download failed, no response body from '${url}'`); + } + yield* body; +} +__name(fetchFile, "fetchFile"); +function requiresFormDataUpload(payload) { + return payload instanceof InputFile || typeof payload === "object" && payload !== null && Object.values(payload).some((v) => Array.isArray(v) ? v.some(requiresFormDataUpload) : v instanceof InputFile || requiresFormDataUpload(v)); +} +__name(requiresFormDataUpload, "requiresFormDataUpload"); +function str(value) { + return JSON.stringify(value, (_, v) => v ?? void 0); +} +__name(str, "str"); +function createJsonPayload(payload) { + return { + method: "POST", + headers: { + "content-type": "application/json", + connection: "keep-alive" + }, + body: str(payload) + }; +} +__name(createJsonPayload, "createJsonPayload"); +async function* protectItr(itr, onError) { + try { + yield* itr; + } catch (err) { + onError(err); + } +} +__name(protectItr, "protectItr"); +function createFormDataPayload(payload, onError) { + const boundary = createBoundary(); + const itr = payloadToMultipartItr(payload, boundary); + const safeItr = protectItr(itr, onError); + const stream = itrToStream(safeItr); + return { + method: "POST", + headers: { + "content-type": `multipart/form-data; boundary=${boundary}`, + connection: "keep-alive" + }, + body: stream + }; +} +__name(createFormDataPayload, "createFormDataPayload"); +function createBoundary() { + return "----------" + randomId(32); +} +__name(createBoundary, "createBoundary"); +function randomId(length = 16) { + return Array.from(Array(length)).map(() => Math.random().toString(36)[2] || 0).join(""); +} +__name(randomId, "randomId"); +var enc = new TextEncoder(); +async function* payloadToMultipartItr(payload, boundary) { + const files = collectFiles(payload); + yield enc.encode(`--${boundary}\r +`); + const separator = enc.encode(`\r +--${boundary}\r +`); + let first = true; + for (const [key, value] of Object.entries(payload)) { + if (value == null) continue; + if (!first) yield separator; + yield valuePart(key, value instanceof InputFile ? value.toJSON() : typeof value === "object" ? str(value) : value); + first = false; + } + for (const { id, origin, file } of files) { + if (!first) yield separator; + yield* filePart(id, origin, file); + first = false; + } + yield enc.encode(`\r +--${boundary}--\r +`); +} +__name(payloadToMultipartItr, "payloadToMultipartItr"); +function collectFiles(value) { + if (typeof value !== "object" || value === null) return []; + return Object.entries(value).flatMap(([k, v]) => { + if (Array.isArray(v)) return v.flatMap((p) => collectFiles(p)); + else if (v instanceof InputFile) { + const id = randomId(); + Object.assign(v, { + toJSON: /* @__PURE__ */ __name(() => `attach://${id}`, "toJSON") + }); + const origin = k === "media" && "type" in value && typeof value.type === "string" ? value.type : k; + return { + id, + origin, + file: v + }; + } else return collectFiles(v); + }); +} +__name(collectFiles, "collectFiles"); +function valuePart(key, value) { + return enc.encode(`content-disposition:form-data;name="${key}"\r +\r +${value}`); +} +__name(valuePart, "valuePart"); +async function* filePart(id, origin, input) { + const filename = input.filename || `${origin}.${getExt(origin)}`; + if (filename.includes("\r") || filename.includes("\n")) { + throw new Error(`File paths cannot contain carriage-return (\\r) or newline (\\n) characters! Filename for property '${origin}' was: +""" +${filename} +"""`); + } + yield enc.encode(`content-disposition:form-data;name="${id}";filename=${filename}\r +content-type:application/octet-stream\r +\r +`); + const data2 = await input.toRaw(); + if (data2 instanceof Uint8Array) yield data2; + else yield* data2; +} +__name(filePart, "filePart"); +function getExt(key) { + switch (key) { + case "certificate": + return "pem"; + case "photo": + case "thumbnail": + return "jpg"; + case "voice": + return "ogg"; + case "audio": + return "mp3"; + case "animation": + case "video": + case "video_note": + return "mp4"; + case "sticker": + return "webp"; + default: + return "dat"; + } +} +__name(getExt, "getExt"); +var debug1 = browser$1("grammy:core"); +function concatTransformer(prev, trans) { + return (method, payload, signal) => trans(prev, method, payload, signal); +} +__name(concatTransformer, "concatTransformer"); +var ApiClient = class { + static { + __name(this, "ApiClient"); + } + token; + webhookReplyEnvelope; + options; + fetch; + hasUsedWebhookReply; + installedTransformers; + constructor(token, options = {}, webhookReplyEnvelope = {}) { + this.token = token; + this.webhookReplyEnvelope = webhookReplyEnvelope; + this.hasUsedWebhookReply = false; + this.installedTransformers = []; + this.call = async (method, p, signal) => { + const payload = p ?? {}; + debug1(`Calling ${method}`); + if (signal !== void 0) validateSignal(method, payload, signal); + const opts = this.options; + const formDataRequired = requiresFormDataUpload(payload); + if (this.webhookReplyEnvelope.send !== void 0 && !this.hasUsedWebhookReply && !formDataRequired && opts.canUseWebhookReply(method)) { + this.hasUsedWebhookReply = true; + const config3 = createJsonPayload({ + ...payload, + method + }); + await this.webhookReplyEnvelope.send(config3.body); + return { + ok: true, + result: true + }; + } + const controller = createAbortControllerFromSignal(signal); + const timeout = createTimeout(controller, opts.timeoutSeconds, method); + const streamErr = createStreamError(controller); + const url = opts.buildUrl(opts.apiRoot, this.token, method, opts.environment); + const config2 = formDataRequired ? createFormDataPayload(payload, (err) => streamErr.catch(err)) : createJsonPayload(payload); + const sig = controller.signal; + const options2 = { + ...opts.baseFetchConfig, + signal: sig, + ...config2 + }; + const successPromise = this.fetch(url, options2).then((res) => res.json()); + const operations = [ + successPromise, + streamErr.promise, + timeout.promise + ]; + try { + return await Promise.race(operations); + } catch (error) { + throw toHttpError(method, opts.sensitiveLogs, error); + } finally { + if (timeout.handle !== void 0) clearTimeout(timeout.handle); + } + }; + const apiRoot = options.apiRoot ?? "https://api.telegram.org"; + const environment = options.environment ?? "prod"; + const { fetch: customFetch } = options; + const fetchFn = customFetch ?? fetch; + this.options = { + apiRoot, + environment, + buildUrl: options.buildUrl ?? defaultBuildUrl, + timeoutSeconds: options.timeoutSeconds ?? 500, + baseFetchConfig: { + ...baseFetchConfig(apiRoot), + ...options.baseFetchConfig + }, + canUseWebhookReply: options.canUseWebhookReply ?? (() => false), + sensitiveLogs: options.sensitiveLogs ?? false, + fetch: /* @__PURE__ */ __name((...args) => fetchFn(...args), "fetch") + }; + this.fetch = this.options.fetch; + if (this.options.apiRoot.endsWith("/")) { + throw new Error(`Remove the trailing '/' from the 'apiRoot' option (use '${this.options.apiRoot.substring(0, this.options.apiRoot.length - 1)}' instead of '${this.options.apiRoot}')`); + } + } + call; + use(...transformers) { + this.call = transformers.reduce(concatTransformer, this.call); + this.installedTransformers.push(...transformers); + return this; + } + async callApi(method, payload, signal) { + const data2 = await this.call(method, payload, signal); + if (data2.ok) return data2.result; + else throw toGrammyError(data2, method, payload); + } +}; +function createRawApi(token, options, webhookReplyEnvelope) { + const client = new ApiClient(token, options, webhookReplyEnvelope); + const proxyHandler = { + get(_, m2) { + return m2 === "toJSON" ? "__internal" : m2 === "getMe" || m2 === "getWebhookInfo" || m2 === "getForumTopicIconStickers" || m2 === "getAvailableGifts" || m2 === "logOut" || m2 === "close" || m2 === "getMyStarBalance" || m2 === "removeMyProfilePhoto" ? client.callApi.bind(client, m2, {}) : client.callApi.bind(client, m2); + }, + ...proxyMethods + }; + const raw2 = new Proxy({}, proxyHandler); + const installedTransformers = client.installedTransformers; + const api = { + raw: raw2, + installedTransformers, + use: /* @__PURE__ */ __name((...t2) => { + client.use(...t2); + return api; + }, "use") + }; + return api; +} +__name(createRawApi, "createRawApi"); +var defaultBuildUrl = /* @__PURE__ */ __name((root, token, method, env) => { + const prefix = env === "test" ? "test/" : ""; + return `${root}/bot${token}/${prefix}${method}`; +}, "defaultBuildUrl"); +var proxyMethods = { + set() { + return false; + }, + defineProperty() { + return false; + }, + deleteProperty() { + return false; + }, + ownKeys() { + return []; + } +}; +function createTimeout(controller, seconds, method) { + let handle = void 0; + const promise = new Promise((_, reject) => { + handle = setTimeout(() => { + const msg = `Request to '${method}' timed out after ${seconds} seconds`; + reject(new Error(msg)); + controller.abort(); + }, 1e3 * seconds); + }); + return { + promise, + handle + }; +} +__name(createTimeout, "createTimeout"); +function createStreamError(abortController) { + let onError = /* @__PURE__ */ __name((err) => { + throw err; + }, "onError"); + const promise = new Promise((_, reject) => { + onError = /* @__PURE__ */ __name((err) => { + reject(err); + abortController.abort(); + }, "onError"); + }); + return { + promise, + catch: onError + }; +} +__name(createStreamError, "createStreamError"); +function createAbortControllerFromSignal(signal) { + const abortController = new AbortController(); + if (signal === void 0) return abortController; + const sig = signal; + function abort() { + abortController.abort(); + sig.removeEventListener("abort", abort); + } + __name(abort, "abort"); + if (sig.aborted) abort(); + else sig.addEventListener("abort", abort); + return { + abort, + signal: abortController.signal + }; +} +__name(createAbortControllerFromSignal, "createAbortControllerFromSignal"); +function validateSignal(method, payload, signal) { + if (typeof signal?.addEventListener === "function") { + return; + } + let payload0 = JSON.stringify(payload); + if (payload0.length > 20) { + payload0 = payload0.substring(0, 16) + " ..."; + } + let payload1 = JSON.stringify(signal); + if (payload1.length > 20) { + payload1 = payload1.substring(0, 16) + " ..."; + } + throw new Error(`Incorrect abort signal instance found! You passed two payloads to '${method}' but you should merge the second one containing '${payload1}' into the first one containing '${payload0}'! If you are using context shortcuts, you may want to use a method on 'ctx.api' instead. + +If you want to prevent such mistakes in the future, consider using TypeScript. https://www.typescriptlang.org/`); +} +__name(validateSignal, "validateSignal"); +var Api = class { + static { + __name(this, "Api"); + } + token; + options; + raw; + config; + constructor(token, options, webhookReplyEnvelope) { + this.token = token; + this.options = options; + const { raw: raw2, use: use2, installedTransformers } = createRawApi(token, options, webhookReplyEnvelope); + this.raw = raw2; + this.config = { + use: use2, + installedTransformers: /* @__PURE__ */ __name(() => installedTransformers.slice(), "installedTransformers") + }; + } + getUpdates(other, signal) { + return this.raw.getUpdates({ + ...other + }, signal); + } + setWebhook(url, other, signal) { + return this.raw.setWebhook({ + url, + ...other + }, signal); + } + deleteWebhook(other, signal) { + return this.raw.deleteWebhook({ + ...other + }, signal); + } + getWebhookInfo(signal) { + return this.raw.getWebhookInfo(signal); + } + getMe(signal) { + return this.raw.getMe(signal); + } + logOut(signal) { + return this.raw.logOut(signal); + } + close(signal) { + return this.raw.close(signal); + } + sendMessage(chat_id, text2, other, signal) { + return this.raw.sendMessage({ + chat_id, + text: text2, + ...other + }, signal); + } + sendMessageDraft(chat_id, draft_id, text2, other, signal) { + return this.raw.sendMessageDraft({ + chat_id, + draft_id, + text: text2, + ...other + }, signal); + } + forwardMessage(chat_id, from_chat_id, message_id, other, signal) { + return this.raw.forwardMessage({ + chat_id, + from_chat_id, + message_id, + ...other + }, signal); + } + forwardMessages(chat_id, from_chat_id, message_ids, other, signal) { + return this.raw.forwardMessages({ + chat_id, + from_chat_id, + message_ids, + ...other + }, signal); + } + copyMessage(chat_id, from_chat_id, message_id, other, signal) { + return this.raw.copyMessage({ + chat_id, + from_chat_id, + message_id, + ...other + }, signal); + } + copyMessages(chat_id, from_chat_id, message_ids, other, signal) { + return this.raw.copyMessages({ + chat_id, + from_chat_id, + message_ids, + ...other + }, signal); + } + sendPhoto(chat_id, photo, other, signal) { + return this.raw.sendPhoto({ + chat_id, + photo, + ...other + }, signal); + } + sendAudio(chat_id, audio, other, signal) { + return this.raw.sendAudio({ + chat_id, + audio, + ...other + }, signal); + } + sendDocument(chat_id, document1, other, signal) { + return this.raw.sendDocument({ + chat_id, + document: document1, + ...other + }, signal); + } + sendVideo(chat_id, video, other, signal) { + return this.raw.sendVideo({ + chat_id, + video, + ...other + }, signal); + } + sendAnimation(chat_id, animation, other, signal) { + return this.raw.sendAnimation({ + chat_id, + animation, + ...other + }, signal); + } + sendVoice(chat_id, voice, other, signal) { + return this.raw.sendVoice({ + chat_id, + voice, + ...other + }, signal); + } + sendVideoNote(chat_id, video_note, other, signal) { + return this.raw.sendVideoNote({ + chat_id, + video_note, + ...other + }, signal); + } + sendMediaGroup(chat_id, media, other, signal) { + return this.raw.sendMediaGroup({ + chat_id, + media, + ...other + }, signal); + } + sendLocation(chat_id, latitude, longitude, other, signal) { + return this.raw.sendLocation({ + chat_id, + latitude, + longitude, + ...other + }, signal); + } + editMessageLiveLocation(chat_id, message_id, latitude, longitude, other, signal) { + return this.raw.editMessageLiveLocation({ + chat_id, + message_id, + latitude, + longitude, + ...other + }, signal); + } + editMessageLiveLocationInline(inline_message_id, latitude, longitude, other, signal) { + return this.raw.editMessageLiveLocation({ + inline_message_id, + latitude, + longitude, + ...other + }, signal); + } + stopMessageLiveLocation(chat_id, message_id, other, signal) { + return this.raw.stopMessageLiveLocation({ + chat_id, + message_id, + ...other + }, signal); + } + stopMessageLiveLocationInline(inline_message_id, other, signal) { + return this.raw.stopMessageLiveLocation({ + inline_message_id, + ...other + }, signal); + } + sendPaidMedia(chat_id, star_count, media, other, signal) { + return this.raw.sendPaidMedia({ + chat_id, + star_count, + media, + ...other + }, signal); + } + sendVenue(chat_id, latitude, longitude, title2, address, other, signal) { + return this.raw.sendVenue({ + chat_id, + latitude, + longitude, + title: title2, + address, + ...other + }, signal); + } + sendContact(chat_id, phone_number, first_name, other, signal) { + return this.raw.sendContact({ + chat_id, + phone_number, + first_name, + ...other + }, signal); + } + sendPoll(chat_id, question, options, other, signal) { + const opts = options.map((o) => typeof o === "string" ? { + text: o + } : o); + return this.raw.sendPoll({ + chat_id, + question, + options: opts, + ...other + }, signal); + } + sendChecklist(business_connection_id, chat_id, checklist, other, signal) { + return this.raw.sendChecklist({ + business_connection_id, + chat_id, + checklist, + ...other + }, signal); + } + editMessageChecklist(business_connection_id, chat_id, message_id, checklist, other, signal) { + return this.raw.editMessageChecklist({ + business_connection_id, + chat_id, + message_id, + checklist, + ...other + }, signal); + } + sendDice(chat_id, emoji, other, signal) { + return this.raw.sendDice({ + chat_id, + emoji, + ...other + }, signal); + } + setMessageReaction(chat_id, message_id, reaction, other, signal) { + return this.raw.setMessageReaction({ + chat_id, + message_id, + reaction, + ...other + }, signal); + } + sendChatAction(chat_id, action, other, signal) { + return this.raw.sendChatAction({ + chat_id, + action, + ...other + }, signal); + } + getUserProfilePhotos(user_id, other, signal) { + return this.raw.getUserProfilePhotos({ + user_id, + ...other + }, signal); + } + getUserProfileAudios(user_id, other, signal) { + return this.raw.getUserProfileAudios({ + user_id, + ...other + }, signal); + } + setUserEmojiStatus(user_id, other, signal) { + return this.raw.setUserEmojiStatus({ + user_id, + ...other + }, signal); + } + getUserChatBoosts(chat_id, user_id, signal) { + return this.raw.getUserChatBoosts({ + chat_id, + user_id + }, signal); + } + getUserGifts(user_id, other, signal) { + return this.raw.getUserGifts({ + user_id, + ...other + }, signal); + } + getChatGifts(chat_id, other, signal) { + return this.raw.getChatGifts({ + chat_id, + ...other + }, signal); + } + getBusinessConnection(business_connection_id, signal) { + return this.raw.getBusinessConnection({ + business_connection_id + }, signal); + } + getFile(file_id, signal) { + return this.raw.getFile({ + file_id + }, signal); + } + kickChatMember(...args) { + return this.banChatMember(...args); + } + banChatMember(chat_id, user_id, other, signal) { + return this.raw.banChatMember({ + chat_id, + user_id, + ...other + }, signal); + } + unbanChatMember(chat_id, user_id, other, signal) { + return this.raw.unbanChatMember({ + chat_id, + user_id, + ...other + }, signal); + } + restrictChatMember(chat_id, user_id, permissions, other, signal) { + return this.raw.restrictChatMember({ + chat_id, + user_id, + permissions, + ...other + }, signal); + } + promoteChatMember(chat_id, user_id, other, signal) { + return this.raw.promoteChatMember({ + chat_id, + user_id, + ...other + }, signal); + } + setChatAdministratorCustomTitle(chat_id, user_id, custom_title, signal) { + return this.raw.setChatAdministratorCustomTitle({ + chat_id, + user_id, + custom_title + }, signal); + } + setChatMemberTag(chat_id, user_id, tag, signal) { + return this.raw.setChatMemberTag({ + chat_id, + user_id, + tag + }, signal); + } + banChatSenderChat(chat_id, sender_chat_id, signal) { + return this.raw.banChatSenderChat({ + chat_id, + sender_chat_id + }, signal); + } + unbanChatSenderChat(chat_id, sender_chat_id, signal) { + return this.raw.unbanChatSenderChat({ + chat_id, + sender_chat_id + }, signal); + } + setChatPermissions(chat_id, permissions, other, signal) { + return this.raw.setChatPermissions({ + chat_id, + permissions, + ...other + }, signal); + } + exportChatInviteLink(chat_id, signal) { + return this.raw.exportChatInviteLink({ + chat_id + }, signal); + } + createChatInviteLink(chat_id, other, signal) { + return this.raw.createChatInviteLink({ + chat_id, + ...other + }, signal); + } + editChatInviteLink(chat_id, invite_link, other, signal) { + return this.raw.editChatInviteLink({ + chat_id, + invite_link, + ...other + }, signal); + } + createChatSubscriptionInviteLink(chat_id, subscription_period, subscription_price, other, signal) { + return this.raw.createChatSubscriptionInviteLink({ + chat_id, + subscription_period, + subscription_price, + ...other + }, signal); + } + editChatSubscriptionInviteLink(chat_id, invite_link, other, signal) { + return this.raw.editChatSubscriptionInviteLink({ + chat_id, + invite_link, + ...other + }, signal); + } + revokeChatInviteLink(chat_id, invite_link, signal) { + return this.raw.revokeChatInviteLink({ + chat_id, + invite_link + }, signal); + } + approveChatJoinRequest(chat_id, user_id, signal) { + return this.raw.approveChatJoinRequest({ + chat_id, + user_id + }, signal); + } + declineChatJoinRequest(chat_id, user_id, signal) { + return this.raw.declineChatJoinRequest({ + chat_id, + user_id + }, signal); + } + approveSuggestedPost(chat_id, message_id, other, signal) { + return this.raw.approveSuggestedPost({ + chat_id, + message_id, + ...other + }, signal); + } + declineSuggestedPost(chat_id, message_id, other, signal) { + return this.raw.declineSuggestedPost({ + chat_id, + message_id, + ...other + }, signal); + } + setChatPhoto(chat_id, photo, signal) { + return this.raw.setChatPhoto({ + chat_id, + photo + }, signal); + } + deleteChatPhoto(chat_id, signal) { + return this.raw.deleteChatPhoto({ + chat_id + }, signal); + } + setChatTitle(chat_id, title2, signal) { + return this.raw.setChatTitle({ + chat_id, + title: title2 + }, signal); + } + setChatDescription(chat_id, description, signal) { + return this.raw.setChatDescription({ + chat_id, + description + }, signal); + } + pinChatMessage(chat_id, message_id, other, signal) { + return this.raw.pinChatMessage({ + chat_id, + message_id, + ...other + }, signal); + } + unpinChatMessage(chat_id, message_id, other, signal) { + return this.raw.unpinChatMessage({ + chat_id, + message_id, + ...other + }, signal); + } + unpinAllChatMessages(chat_id, signal) { + return this.raw.unpinAllChatMessages({ + chat_id + }, signal); + } + leaveChat(chat_id, signal) { + return this.raw.leaveChat({ + chat_id + }, signal); + } + getChat(chat_id, signal) { + return this.raw.getChat({ + chat_id + }, signal); + } + getChatAdministrators(chat_id, signal) { + return this.raw.getChatAdministrators({ + chat_id + }, signal); + } + getChatMembersCount(...args) { + return this.getChatMemberCount(...args); + } + getChatMemberCount(chat_id, signal) { + return this.raw.getChatMemberCount({ + chat_id + }, signal); + } + getChatMember(chat_id, user_id, signal) { + return this.raw.getChatMember({ + chat_id, + user_id + }, signal); + } + setChatStickerSet(chat_id, sticker_set_name, signal) { + return this.raw.setChatStickerSet({ + chat_id, + sticker_set_name + }, signal); + } + deleteChatStickerSet(chat_id, signal) { + return this.raw.deleteChatStickerSet({ + chat_id + }, signal); + } + getForumTopicIconStickers(signal) { + return this.raw.getForumTopicIconStickers(signal); + } + createForumTopic(chat_id, name, other, signal) { + return this.raw.createForumTopic({ + chat_id, + name, + ...other + }, signal); + } + editForumTopic(chat_id, message_thread_id, other, signal) { + return this.raw.editForumTopic({ + chat_id, + message_thread_id, + ...other + }, signal); + } + closeForumTopic(chat_id, message_thread_id, signal) { + return this.raw.closeForumTopic({ + chat_id, + message_thread_id + }, signal); + } + reopenForumTopic(chat_id, message_thread_id, signal) { + return this.raw.reopenForumTopic({ + chat_id, + message_thread_id + }, signal); + } + deleteForumTopic(chat_id, message_thread_id, signal) { + return this.raw.deleteForumTopic({ + chat_id, + message_thread_id + }, signal); + } + unpinAllForumTopicMessages(chat_id, message_thread_id, signal) { + return this.raw.unpinAllForumTopicMessages({ + chat_id, + message_thread_id + }, signal); + } + editGeneralForumTopic(chat_id, name, signal) { + return this.raw.editGeneralForumTopic({ + chat_id, + name + }, signal); + } + closeGeneralForumTopic(chat_id, signal) { + return this.raw.closeGeneralForumTopic({ + chat_id + }, signal); + } + reopenGeneralForumTopic(chat_id, signal) { + return this.raw.reopenGeneralForumTopic({ + chat_id + }, signal); + } + hideGeneralForumTopic(chat_id, signal) { + return this.raw.hideGeneralForumTopic({ + chat_id + }, signal); + } + unhideGeneralForumTopic(chat_id, signal) { + return this.raw.unhideGeneralForumTopic({ + chat_id + }, signal); + } + unpinAllGeneralForumTopicMessages(chat_id, signal) { + return this.raw.unpinAllGeneralForumTopicMessages({ + chat_id + }, signal); + } + answerCallbackQuery(callback_query_id, other, signal) { + return this.raw.answerCallbackQuery({ + callback_query_id, + ...other + }, signal); + } + setMyName(name, other, signal) { + return this.raw.setMyName({ + name, + ...other + }, signal); + } + getMyName(other, signal) { + return this.raw.getMyName(other ?? {}, signal); + } + setMyCommands(commands, other, signal) { + return this.raw.setMyCommands({ + commands, + ...other + }, signal); + } + deleteMyCommands(other, signal) { + return this.raw.deleteMyCommands({ + ...other + }, signal); + } + getMyCommands(other, signal) { + return this.raw.getMyCommands({ + ...other + }, signal); + } + setMyDescription(description, other, signal) { + return this.raw.setMyDescription({ + description, + ...other + }, signal); + } + getMyDescription(other, signal) { + return this.raw.getMyDescription({ + ...other + }, signal); + } + setMyShortDescription(short_description, other, signal) { + return this.raw.setMyShortDescription({ + short_description, + ...other + }, signal); + } + getMyShortDescription(other, signal) { + return this.raw.getMyShortDescription({ + ...other + }, signal); + } + setMyProfilePhoto(photo, signal) { + return this.raw.setMyProfilePhoto({ + photo + }, signal); + } + removeMyProfilePhoto(signal) { + return this.raw.removeMyProfilePhoto(signal); + } + setChatMenuButton(other, signal) { + return this.raw.setChatMenuButton({ + ...other + }, signal); + } + getChatMenuButton(other, signal) { + return this.raw.getChatMenuButton({ + ...other + }, signal); + } + setMyDefaultAdministratorRights(other, signal) { + return this.raw.setMyDefaultAdministratorRights({ + ...other + }, signal); + } + getMyDefaultAdministratorRights(other, signal) { + return this.raw.getMyDefaultAdministratorRights({ + ...other + }, signal); + } + getMyStarBalance(signal) { + return this.raw.getMyStarBalance(signal); + } + editMessageText(chat_id, message_id, text2, other, signal) { + return this.raw.editMessageText({ + chat_id, + message_id, + text: text2, + ...other + }, signal); + } + editMessageTextInline(inline_message_id, text2, other, signal) { + return this.raw.editMessageText({ + inline_message_id, + text: text2, + ...other + }, signal); + } + editMessageCaption(chat_id, message_id, other, signal) { + return this.raw.editMessageCaption({ + chat_id, + message_id, + ...other + }, signal); + } + editMessageCaptionInline(inline_message_id, other, signal) { + return this.raw.editMessageCaption({ + inline_message_id, + ...other + }, signal); + } + editMessageMedia(chat_id, message_id, media, other, signal) { + return this.raw.editMessageMedia({ + chat_id, + message_id, + media, + ...other + }, signal); + } + editMessageMediaInline(inline_message_id, media, other, signal) { + return this.raw.editMessageMedia({ + inline_message_id, + media, + ...other + }, signal); + } + editMessageReplyMarkup(chat_id, message_id, other, signal) { + return this.raw.editMessageReplyMarkup({ + chat_id, + message_id, + ...other + }, signal); + } + editMessageReplyMarkupInline(inline_message_id, other, signal) { + return this.raw.editMessageReplyMarkup({ + inline_message_id, + ...other + }, signal); + } + stopPoll(chat_id, message_id, other, signal) { + return this.raw.stopPoll({ + chat_id, + message_id, + ...other + }, signal); + } + deleteMessage(chat_id, message_id, signal) { + return this.raw.deleteMessage({ + chat_id, + message_id + }, signal); + } + deleteMessages(chat_id, message_ids, signal) { + return this.raw.deleteMessages({ + chat_id, + message_ids + }, signal); + } + deleteBusinessMessages(business_connection_id, message_ids, signal) { + return this.raw.deleteBusinessMessages({ + business_connection_id, + message_ids + }, signal); + } + setBusinessAccountName(business_connection_id, first_name, other, signal) { + return this.raw.setBusinessAccountName({ + business_connection_id, + first_name, + ...other + }, signal); + } + setBusinessAccountUsername(business_connection_id, username, signal) { + return this.raw.setBusinessAccountUsername({ + business_connection_id, + username + }, signal); + } + setBusinessAccountBio(business_connection_id, bio, signal) { + return this.raw.setBusinessAccountBio({ + business_connection_id, + bio + }, signal); + } + setBusinessAccountProfilePhoto(business_connection_id, photo, other, signal) { + return this.raw.setBusinessAccountProfilePhoto({ + business_connection_id, + photo, + ...other + }, signal); + } + removeBusinessAccountProfilePhoto(business_connection_id, other, signal) { + return this.raw.removeBusinessAccountProfilePhoto({ + business_connection_id, + ...other + }, signal); + } + setBusinessAccountGiftSettings(business_connection_id, show_gift_button, accepted_gift_types, signal) { + return this.raw.setBusinessAccountGiftSettings({ + business_connection_id, + show_gift_button, + accepted_gift_types + }, signal); + } + getBusinessAccountStarBalance(business_connection_id, signal) { + return this.raw.getBusinessAccountStarBalance({ + business_connection_id + }, signal); + } + transferBusinessAccountStars(business_connection_id, star_count, signal) { + return this.raw.transferBusinessAccountStars({ + business_connection_id, + star_count + }, signal); + } + getBusinessAccountGifts(business_connection_id, other, signal) { + return this.raw.getBusinessAccountGifts({ + business_connection_id, + ...other + }, signal); + } + convertGiftToStars(business_connection_id, owned_gift_id, signal) { + return this.raw.convertGiftToStars({ + business_connection_id, + owned_gift_id + }, signal); + } + upgradeGift(business_connection_id, owned_gift_id, other, signal) { + return this.raw.upgradeGift({ + business_connection_id, + owned_gift_id, + ...other + }, signal); + } + transferGift(business_connection_id, owned_gift_id, new_owner_chat_id, star_count, signal) { + return this.raw.transferGift({ + business_connection_id, + owned_gift_id, + new_owner_chat_id, + star_count + }, signal); + } + postStory(business_connection_id, content, active_period, other, signal) { + return this.raw.postStory({ + business_connection_id, + content, + active_period, + ...other + }, signal); + } + repostStory(business_connection_id, from_chat_id, from_story_id, active_period, other, signal) { + return this.raw.repostStory({ + business_connection_id, + from_chat_id, + from_story_id, + active_period, + ...other + }, signal); + } + editStory(business_connection_id, story_id, content, other, signal) { + return this.raw.editStory({ + business_connection_id, + story_id, + content, + ...other + }, signal); + } + deleteStory(business_connection_id, story_id, signal) { + return this.raw.deleteStory({ + business_connection_id, + story_id + }, signal); + } + sendSticker(chat_id, sticker, other, signal) { + return this.raw.sendSticker({ + chat_id, + sticker, + ...other + }, signal); + } + getStickerSet(name, signal) { + return this.raw.getStickerSet({ + name + }, signal); + } + getCustomEmojiStickers(custom_emoji_ids, signal) { + return this.raw.getCustomEmojiStickers({ + custom_emoji_ids + }, signal); + } + uploadStickerFile(user_id, sticker_format, sticker, signal) { + return this.raw.uploadStickerFile({ + user_id, + sticker_format, + sticker + }, signal); + } + createNewStickerSet(user_id, name, title2, stickers, other, signal) { + return this.raw.createNewStickerSet({ + user_id, + name, + title: title2, + stickers, + ...other + }, signal); + } + addStickerToSet(user_id, name, sticker, signal) { + return this.raw.addStickerToSet({ + user_id, + name, + sticker + }, signal); + } + setStickerPositionInSet(sticker, position, signal) { + return this.raw.setStickerPositionInSet({ + sticker, + position + }, signal); + } + deleteStickerFromSet(sticker, signal) { + return this.raw.deleteStickerFromSet({ + sticker + }, signal); + } + replaceStickerInSet(user_id, name, old_sticker, sticker, signal) { + return this.raw.replaceStickerInSet({ + user_id, + name, + old_sticker, + sticker + }, signal); + } + setStickerEmojiList(sticker, emoji_list, signal) { + return this.raw.setStickerEmojiList({ + sticker, + emoji_list + }, signal); + } + setStickerKeywords(sticker, keywords, signal) { + return this.raw.setStickerKeywords({ + sticker, + keywords + }, signal); + } + setStickerMaskPosition(sticker, mask_position, signal) { + return this.raw.setStickerMaskPosition({ + sticker, + mask_position + }, signal); + } + setStickerSetTitle(name, title2, signal) { + return this.raw.setStickerSetTitle({ + name, + title: title2 + }, signal); + } + deleteStickerSet(name, signal) { + return this.raw.deleteStickerSet({ + name + }, signal); + } + setStickerSetThumbnail(name, user_id, thumbnail, format, signal) { + return this.raw.setStickerSetThumbnail({ + name, + user_id, + thumbnail, + format + }, signal); + } + setCustomEmojiStickerSetThumbnail(name, custom_emoji_id, signal) { + return this.raw.setCustomEmojiStickerSetThumbnail({ + name, + custom_emoji_id + }, signal); + } + getAvailableGifts(signal) { + return this.raw.getAvailableGifts(signal); + } + sendGift(user_id, gift_id, other, signal) { + return this.raw.sendGift({ + user_id, + gift_id, + ...other + }, signal); + } + giftPremiumSubscription(user_id, month_count, star_count, other, signal) { + return this.raw.giftPremiumSubscription({ + user_id, + month_count, + star_count, + ...other + }, signal); + } + sendGiftToChannel(chat_id, gift_id, other, signal) { + return this.raw.sendGift({ + chat_id, + gift_id, + ...other + }, signal); + } + answerInlineQuery(inline_query_id, results, other, signal) { + return this.raw.answerInlineQuery({ + inline_query_id, + results, + ...other + }, signal); + } + answerWebAppQuery(web_app_query_id, result, signal) { + return this.raw.answerWebAppQuery({ + web_app_query_id, + result + }, signal); + } + savePreparedInlineMessage(user_id, result, other, signal) { + return this.raw.savePreparedInlineMessage({ + user_id, + result, + ...other + }, signal); + } + sendInvoice(chat_id, title2, description, payload, currency, prices, other, signal) { + return this.raw.sendInvoice({ + chat_id, + title: title2, + description, + payload, + currency, + prices, + ...other + }, signal); + } + createInvoiceLink(title2, description, payload, provider_token, currency, prices, other, signal) { + return this.raw.createInvoiceLink({ + title: title2, + description, + payload, + provider_token, + currency, + prices, + ...other + }, signal); + } + answerShippingQuery(shipping_query_id, ok2, other, signal) { + return this.raw.answerShippingQuery({ + shipping_query_id, + ok: ok2, + ...other + }, signal); + } + answerPreCheckoutQuery(pre_checkout_query_id, ok2, other, signal) { + return this.raw.answerPreCheckoutQuery({ + pre_checkout_query_id, + ok: ok2, + ...other + }, signal); + } + getStarTransactions(other, signal) { + return this.raw.getStarTransactions({ + ...other + }, signal); + } + refundStarPayment(user_id, telegram_payment_charge_id, signal) { + return this.raw.refundStarPayment({ + user_id, + telegram_payment_charge_id + }, signal); + } + editUserStarSubscription(user_id, telegram_payment_charge_id, is_canceled, signal) { + return this.raw.editUserStarSubscription({ + user_id, + telegram_payment_charge_id, + is_canceled + }, signal); + } + verifyUser(user_id, other, signal) { + return this.raw.verifyUser({ + user_id, + ...other + }, signal); + } + verifyChat(chat_id, other, signal) { + return this.raw.verifyChat({ + chat_id, + ...other + }, signal); + } + removeUserVerification(user_id, signal) { + return this.raw.removeUserVerification({ + user_id + }, signal); + } + removeChatVerification(chat_id, signal) { + return this.raw.removeChatVerification({ + chat_id + }, signal); + } + readBusinessMessage(business_connection_id, chat_id, message_id, signal) { + return this.raw.readBusinessMessage({ + business_connection_id, + chat_id, + message_id + }, signal); + } + setPassportDataErrors(user_id, errors, signal) { + return this.raw.setPassportDataErrors({ + user_id, + errors + }, signal); + } + sendGame(chat_id, game_short_name, other, signal) { + return this.raw.sendGame({ + chat_id, + game_short_name, + ...other + }, signal); + } + setGameScore(chat_id, message_id, user_id, score, other, signal) { + return this.raw.setGameScore({ + chat_id, + message_id, + user_id, + score, + ...other + }, signal); + } + setGameScoreInline(inline_message_id, user_id, score, other, signal) { + return this.raw.setGameScore({ + inline_message_id, + user_id, + score, + ...other + }, signal); + } + getGameHighScores(chat_id, message_id, user_id, signal) { + return this.raw.getGameHighScores({ + chat_id, + message_id, + user_id + }, signal); + } + getGameHighScoresInline(inline_message_id, user_id, signal) { + return this.raw.getGameHighScores({ + inline_message_id, + user_id + }, signal); + } +}; +var debug2 = browser$1("grammy:bot"); +var debugWarn = browser$1("grammy:warn"); +var debugErr = browser$1("grammy:error"); +var DEFAULT_UPDATE_TYPES = [ + "message", + "edited_message", + "channel_post", + "edited_channel_post", + "business_connection", + "business_message", + "edited_business_message", + "deleted_business_messages", + "inline_query", + "chosen_inline_result", + "callback_query", + "shipping_query", + "pre_checkout_query", + "purchased_paid_media", + "poll", + "poll_answer", + "my_chat_member", + "chat_join_request", + "chat_boost", + "removed_chat_boost" +]; +var Bot = class extends Composer { + static { + __name(this, "Bot"); + } + token; + pollingRunning; + pollingAbortController; + lastTriedUpdateId; + api; + me; + mePromise; + clientConfig; + ContextConstructor; + observedUpdateTypes; + errorHandler; + constructor(token, config2) { + super(); + this.token = token; + this.pollingRunning = false; + this.lastTriedUpdateId = 0; + this.observedUpdateTypes = /* @__PURE__ */ new Set(); + this.errorHandler = async (err) => { + console.error("Error in middleware while handling update", err.ctx?.update?.update_id, err.error); + console.error("No error handler was set!"); + console.error("Set your own error handler with `bot.catch = ...`"); + if (this.pollingRunning) { + console.error("Stopping bot"); + await this.stop(); + } + throw err; + }; + if (!token) throw new Error("Empty token!"); + this.me = config2?.botInfo; + this.clientConfig = config2?.client; + this.ContextConstructor = config2?.ContextConstructor ?? Context2; + this.api = new Api(token, this.clientConfig); + } + set botInfo(botInfo) { + this.me = botInfo; + } + get botInfo() { + if (this.me === void 0) { + throw new Error("Bot information unavailable! Make sure to call `await bot.init()` before accessing `bot.botInfo`!"); + } + return this.me; + } + on(filter, ...middleware) { + for (const [u] of parse(filter).flatMap(preprocess)) { + this.observedUpdateTypes.add(u); + } + return super.on(filter, ...middleware); + } + reaction(reaction, ...middleware) { + this.observedUpdateTypes.add("message_reaction"); + return super.reaction(reaction, ...middleware); + } + isInited() { + return this.me !== void 0; + } + async init(signal) { + if (!this.isInited()) { + debug2("Initializing bot"); + this.mePromise ??= withRetries(() => this.api.getMe(signal), signal); + let me; + try { + me = await this.mePromise; + } finally { + this.mePromise = void 0; + } + if (this.me === void 0) this.me = me; + else debug2("Bot info was set by now, will not overwrite"); + } + debug2(`I am ${this.me.username}!`); + } + async handleUpdates(updates) { + for (const update of updates) { + this.lastTriedUpdateId = update.update_id; + try { + await this.handleUpdate(update); + } catch (err) { + if (err instanceof BotError) { + await this.errorHandler(err); + } else { + console.error("FATAL: grammY unable to handle:", err); + throw err; + } + } + } + } + async handleUpdate(update, webhookReplyEnvelope) { + if (this.me === void 0) { + throw new Error("Bot not initialized! Either call `await bot.init()`, or directly set the `botInfo` option in the `Bot` constructor to specify a known bot info object."); + } + debug2(`Processing update ${update.update_id}`); + const api = new Api(this.token, this.clientConfig, webhookReplyEnvelope); + const t2 = this.api.config.installedTransformers(); + if (t2.length > 0) api.config.use(...t2); + const ctx = new this.ContextConstructor(update, api, this.me); + try { + await run(this.middleware(), ctx); + } catch (err) { + debugErr(`Error in middleware for update ${update.update_id}`); + throw new BotError(err, ctx); + } + } + async start(options) { + const setup2 = []; + if (!this.isInited()) { + setup2.push(this.init(this.pollingAbortController?.signal)); + } + if (this.pollingRunning) { + await Promise.all(setup2); + debug2("Simple long polling already running!"); + return; + } + this.pollingRunning = true; + this.pollingAbortController = new AbortController(); + try { + setup2.push(withRetries(async () => { + await this.api.deleteWebhook({ + drop_pending_updates: options?.drop_pending_updates + }, this.pollingAbortController?.signal); + }, this.pollingAbortController?.signal)); + await Promise.all(setup2); + await options?.onStart?.(this.botInfo); + } catch (err) { + this.pollingRunning = false; + this.pollingAbortController = void 0; + throw err; + } + if (!this.pollingRunning) return; + validateAllowedUpdates(this.observedUpdateTypes, options?.allowed_updates); + this.use = noUseFunction; + debug2("Starting simple long polling"); + await this.loop(options); + debug2("Middleware is done running"); + } + async stop() { + if (this.pollingRunning) { + debug2("Stopping bot, saving update offset"); + this.pollingRunning = false; + this.pollingAbortController?.abort(); + const offset = this.lastTriedUpdateId + 1; + await this.api.getUpdates({ + offset, + limit: 1 + }).finally(() => this.pollingAbortController = void 0); + } else { + debug2("Bot is not running!"); + } + } + isRunning() { + return this.pollingRunning; + } + catch(errorHandler2) { + this.errorHandler = errorHandler2; + } + async loop(options) { + const limit = options?.limit; + const timeout = options?.timeout ?? 30; + let allowed_updates = options?.allowed_updates ?? []; + try { + while (this.pollingRunning) { + const updates = await this.fetchUpdates({ + limit, + timeout, + allowed_updates + }); + if (updates === void 0) break; + await this.handleUpdates(updates); + allowed_updates = void 0; + } + } finally { + this.pollingRunning = false; + } + } + async fetchUpdates({ limit, timeout, allowed_updates }) { + const offset = this.lastTriedUpdateId + 1; + let updates = void 0; + do { + try { + updates = await this.api.getUpdates({ + offset, + limit, + timeout, + allowed_updates + }, this.pollingAbortController?.signal); + } catch (error) { + await this.handlePollingError(error); + } + } while (updates === void 0 && this.pollingRunning); + return updates; + } + async handlePollingError(error) { + if (!this.pollingRunning) { + debug2("Pending getUpdates request cancelled"); + return; + } + let sleepSeconds = 3; + if (error instanceof GrammyError) { + debugErr(error.message); + if (error.error_code === 401 || error.error_code === 409) { + throw error; + } else if (error.error_code === 429) { + debugErr("Bot API server is closing."); + sleepSeconds = error.parameters.retry_after ?? sleepSeconds; + } + } else debugErr(error); + debugErr(`Call to getUpdates failed, retrying in ${sleepSeconds} seconds ...`); + await sleep(sleepSeconds); + } +}; +async function withRetries(task, signal) { + const INITIAL_DELAY = 50; + let lastDelay = 50; + async function handleError(error) { + let delay = false; + let strategy = "rethrow"; + if (error instanceof HttpError) { + delay = true; + strategy = "retry"; + } else if (error instanceof GrammyError) { + if (error.error_code >= 500) { + delay = true; + strategy = "retry"; + } else if (error.error_code === 429) { + const retryAfter = error.parameters.retry_after; + if (typeof retryAfter === "number") { + await sleep(retryAfter, signal); + lastDelay = INITIAL_DELAY; + } else { + delay = true; + } + strategy = "retry"; + } + } + if (delay) { + if (lastDelay !== 50) { + await sleep(lastDelay, signal); + } + const TWENTY_MINUTES = 20 * 60 * 1e3; + lastDelay = Math.min(TWENTY_MINUTES, 2 * lastDelay); + } + return strategy; + } + __name(handleError, "handleError"); + let result = { + ok: false + }; + while (!result.ok) { + try { + result = { + ok: true, + value: await task() + }; + } catch (error) { + debugErr(error); + const strategy = await handleError(error); + switch (strategy) { + case "retry": + continue; + case "rethrow": + throw error; + } + } + } + return result.value; +} +__name(withRetries, "withRetries"); +async function sleep(seconds, signal) { + let handle; + let reject; + function abort() { + reject?.(new Error("Aborted delay")); + if (handle !== void 0) clearTimeout(handle); + } + __name(abort, "abort"); + try { + await new Promise((res, rej) => { + reject = rej; + if (signal?.aborted) { + abort(); + return; + } + signal?.addEventListener("abort", abort); + handle = setTimeout(res, 1e3 * seconds); + }); + } finally { + signal?.removeEventListener("abort", abort); + } +} +__name(sleep, "sleep"); +function validateAllowedUpdates(updates, allowed = DEFAULT_UPDATE_TYPES) { + const impossible = Array.from(updates).filter((u) => !allowed.includes(u)); + if (impossible.length > 0) { + debugWarn(`You registered listeners for the following update types, but you did not specify them in \`allowed_updates\` so they may not be received: ${impossible.map((u) => `'${u}'`).join(", ")}`); + } +} +__name(validateAllowedUpdates, "validateAllowedUpdates"); +function noUseFunction() { + throw new Error(`It looks like you are registering more listeners on your bot from within other listeners! This means that every time your bot handles a message like this one, new listeners will be added. This list grows until your machine crashes, so grammY throws this error to tell you that you should probably do things a bit differently. If you're unsure how to resolve this problem, you can ask in the group chat: https://telegram.me/grammyjs + +On the other hand, if you actually know what you're doing and you do need to install further middleware while your bot is running, consider installing a composer instance on your bot, and in turn augment the composer after the fact. This way, you can circumvent this protection against memory leaks.`); +} +__name(noUseFunction, "noUseFunction"); +var ALL_UPDATE_TYPES = [ + ...DEFAULT_UPDATE_TYPES, + "chat_member", + "message_reaction", + "message_reaction_count" +]; +var ALL_CHAT_PERMISSIONS = { + can_send_messages: true, + can_send_audios: true, + can_send_documents: true, + can_send_photos: true, + can_send_videos: true, + can_send_video_notes: true, + can_send_voice_notes: true, + can_send_polls: true, + can_send_other_messages: true, + can_add_web_page_previews: true, + can_change_info: true, + can_invite_users: true, + can_edit_tag: true, + can_pin_messages: true, + can_manage_topics: true +}; +var API_CONSTANTS = { + DEFAULT_UPDATE_TYPES, + ALL_UPDATE_TYPES, + ALL_CHAT_PERMISSIONS +}; +Object.freeze(API_CONSTANTS); +var InlineKeyboard = class _InlineKeyboard { + static { + __name(this, "InlineKeyboard"); + } + inline_keyboard; + constructor(inline_keyboard = [ + [] + ]) { + this.inline_keyboard = inline_keyboard; + } + add(...buttons) { + this.inline_keyboard[this.inline_keyboard.length - 1]?.push(...buttons); + return this; + } + row(...buttons) { + this.inline_keyboard.push(buttons); + return this; + } + url(text2, url) { + return this.add(_InlineKeyboard.url(text2, url)); + } + static url(text2, url) { + return typeof text2 === "string" ? { + text: text2, + url + } : { + ...text2, + url + }; + } + text(text2, data2 = typeof text2 === "string" ? text2 : text2.text) { + return this.add(_InlineKeyboard.text(text2, data2)); + } + static text(text2, data2 = typeof text2 === "string" ? text2 : text2.text) { + return typeof text2 === "string" ? { + text: text2, + callback_data: data2 + } : { + ...text2, + callback_data: data2 + }; + } + webApp(text2, url) { + return this.add(_InlineKeyboard.webApp(text2, url)); + } + static webApp(text2, url) { + const web_app = typeof url === "string" ? { + url + } : url; + return typeof text2 === "string" ? { + text: text2, + web_app + } : { + ...text2, + web_app + }; + } + login(text2, loginUrl) { + return this.add(_InlineKeyboard.login(text2, loginUrl)); + } + static login(text2, loginUrl) { + const login_url = typeof loginUrl === "string" ? { + url: loginUrl + } : loginUrl; + return typeof text2 === "string" ? { + text: text2, + login_url + } : { + ...text2, + login_url + }; + } + switchInline(text2, query = "") { + return this.add(_InlineKeyboard.switchInline(text2, query)); + } + static switchInline(text2, query = "") { + return typeof text2 === "string" ? { + text: text2, + switch_inline_query: query + } : { + ...text2, + switch_inline_query: query + }; + } + switchInlineCurrent(text2, query = "") { + return this.add(_InlineKeyboard.switchInlineCurrent(text2, query)); + } + static switchInlineCurrent(text2, query = "") { + return typeof text2 === "string" ? { + text: text2, + switch_inline_query_current_chat: query + } : { + ...text2, + switch_inline_query_current_chat: query + }; + } + switchInlineChosen(text2, query = {}) { + return this.add(_InlineKeyboard.switchInlineChosen(text2, query)); + } + static switchInlineChosen(text2, query = {}) { + return typeof text2 === "string" ? { + text: text2, + switch_inline_query_chosen_chat: query + } : { + ...text2, + switch_inline_query_chosen_chat: query + }; + } + copyText(text2, copyText) { + return this.add(_InlineKeyboard.copyText(text2, copyText)); + } + static copyText(text2, copyText) { + const copy_text = typeof copyText === "string" ? { + text: copyText + } : copyText; + return typeof text2 === "string" ? { + text: text2, + copy_text + } : { + ...text2, + copy_text + }; + } + game(text2) { + return this.add(_InlineKeyboard.game(text2)); + } + static game(text2) { + const callback_game = {}; + return typeof text2 === "string" ? { + text: text2, + callback_game + } : { + ...text2, + callback_game + }; + } + pay(text2) { + return this.add(_InlineKeyboard.pay(text2)); + } + static pay(text2) { + return typeof text2 === "string" ? { + text: text2, + pay: true + } : { + ...text2, + pay: true + }; + } + style(style) { + const rows = this.inline_keyboard.length; + if (rows === 0) { + throw new Error("Need to add a button before applying a style!"); + } + const lastRow = this.inline_keyboard[rows - 1]; + const cols = lastRow.length; + if (cols === 0) { + throw new Error("Need to add a button before applying a style!"); + } + lastRow[cols - 1].style = style; + return this; + } + danger() { + return this.style("danger"); + } + success() { + return this.style("success"); + } + primary() { + return this.style("primary"); + } + icon(icon) { + const rows = this.inline_keyboard.length; + if (rows === 0) { + throw new Error("Need to add a button before adding an icon!"); + } + const lastRow = this.inline_keyboard[rows - 1]; + const cols = lastRow.length; + if (cols === 0) { + throw new Error("Need to add a button before adding an icon!"); + } + lastRow[cols - 1].icon_custom_emoji_id = icon; + return this; + } + toTransposed() { + const original = this.inline_keyboard; + const transposed = transpose(original); + return new _InlineKeyboard(transposed); + } + toFlowed(columns, options = {}) { + const original = this.inline_keyboard; + const flowed = reflow(original, columns, options); + return new _InlineKeyboard(flowed); + } + clone() { + return new _InlineKeyboard(this.inline_keyboard.map((row) => row.slice())); + } + append(...sources) { + for (const source of sources) { + const keyboard = _InlineKeyboard.from(source); + this.inline_keyboard.push(...keyboard.inline_keyboard.map((row) => row.slice())); + } + return this; + } + static from(source) { + if (source instanceof _InlineKeyboard) return source.clone(); + return new _InlineKeyboard(source.map((row) => row.slice())); + } +}; +function transpose(grid) { + const transposed = []; + for (let i = 0; i < grid.length; i++) { + const row = grid[i]; + for (let j = 0; j < row.length; j++) { + const button = row[j]; + (transposed[j] ??= []).push(button); + } + } + return transposed; +} +__name(transpose, "transpose"); +function reflow(grid, columns, { fillLastRow = false }) { + let first = columns; + if (fillLastRow) { + const buttonCount = grid.map((row) => row.length).reduce((a, b) => a + b, 0); + first = buttonCount % columns; + } + const reflowed = []; + for (const row of grid) { + for (const button of row) { + const at = Math.max(0, reflowed.length - 1); + const max = at === 0 ? first : columns; + let next = reflowed[at] ??= []; + if (next.length === max) { + next = []; + reflowed.push(next); + } + next.push(button); + } + } + return reflowed; +} +__name(reflow, "reflow"); +var debug3 = browser$1("grammy:session"); +function session(options = {}) { + return options.type === "multi" ? strictMultiSession(options) : strictSingleSession(options); +} +__name(session, "session"); +function strictSingleSession(options) { + const { initial, storage, getSessionKey, custom } = fillDefaults(options); + return async (ctx, next) => { + const propSession = new PropertySession(storage, ctx, "session", initial); + const key = await getSessionKey(ctx); + await propSession.init(key, { + custom, + lazy: false + }); + await next(); + await propSession.finish(); + }; +} +__name(strictSingleSession, "strictSingleSession"); +function strictMultiSession(options) { + const props = Object.keys(options).filter((k) => k !== "type"); + const defaults = Object.fromEntries(props.map((prop) => [ + prop, + fillDefaults(options[prop]) + ])); + return async (ctx, next) => { + ctx.session = {}; + const propSessions = await Promise.all(props.map(async (prop) => { + const { initial, storage, getSessionKey, custom } = defaults[prop]; + const s2 = new PropertySession(storage, ctx.session, prop, initial); + const key = await getSessionKey(ctx); + await s2.init(key, { + custom, + lazy: false + }); + return s2; + })); + await next(); + if (ctx.session == null) propSessions.forEach((s2) => s2.delete()); + await Promise.all(propSessions.map((s2) => s2.finish())); + }; +} +__name(strictMultiSession, "strictMultiSession"); +var PropertySession = class { + static { + __name(this, "PropertySession"); + } + storage; + obj; + prop; + initial; + key; + value; + promise; + fetching; + read; + wrote; + constructor(storage, obj, prop, initial) { + this.storage = storage; + this.obj = obj; + this.prop = prop; + this.initial = initial; + this.fetching = false; + this.read = false; + this.wrote = false; + } + load() { + if (this.key === void 0) { + return; + } + if (this.wrote) { + return; + } + if (this.promise === void 0) { + this.fetching = true; + this.promise = Promise.resolve(this.storage.read(this.key)).then((val) => { + this.fetching = false; + if (this.wrote) { + return this.value; + } + if (val !== void 0) { + this.value = val; + return val; + } + val = this.initial?.(); + if (val !== void 0) { + this.wrote = true; + this.value = val; + } + return val; + }); + } + return this.promise; + } + async init(key, opts) { + this.key = key; + if (!opts.lazy) await this.load(); + Object.defineProperty(this.obj, this.prop, { + enumerable: true, + get: /* @__PURE__ */ __name(() => { + if (key === void 0) { + const msg = undef("access", opts); + throw new Error(msg); + } + this.read = true; + if (!opts.lazy || this.wrote) return this.value; + this.load(); + return this.fetching ? this.promise : this.value; + }, "get"), + set: /* @__PURE__ */ __name((v) => { + if (key === void 0) { + const msg = undef("assign", opts); + throw new Error(msg); + } + this.wrote = true; + this.fetching = false; + this.value = v; + }, "set") + }); + } + delete() { + Object.assign(this.obj, { + [this.prop]: void 0 + }); + } + async finish() { + if (this.key !== void 0) { + if (this.read) await this.load(); + if (this.read || this.wrote) { + const value = await this.value; + if (value == null) await this.storage.delete(this.key); + else await this.storage.write(this.key, value); + } + } + } +}; +function fillDefaults(opts = {}) { + let { prefix = "", getSessionKey = defaultGetSessionKey, initial, storage } = opts; + if (storage == null) { + debug3("Storing session data in memory, all data will be lost when the bot restarts."); + storage = new MemorySessionStorage(); + } + const custom = getSessionKey !== defaultGetSessionKey; + return { + initial, + storage, + getSessionKey: /* @__PURE__ */ __name(async (ctx) => { + const key = await getSessionKey(ctx); + return key === void 0 ? void 0 : prefix + key; + }, "getSessionKey"), + custom + }; +} +__name(fillDefaults, "fillDefaults"); +function defaultGetSessionKey(ctx) { + return ctx.chatId?.toString(); +} +__name(defaultGetSessionKey, "defaultGetSessionKey"); +function undef(op, opts) { + const { lazy = false, custom } = opts; + const reason = custom ? "the custom `getSessionKey` function returned undefined for this update" : "this update does not belong to a chat, so the session key is undefined"; + return `Cannot ${op} ${lazy ? "lazy " : ""}session data because ${reason}!`; +} +__name(undef, "undef"); +var MemorySessionStorage = class { + static { + __name(this, "MemorySessionStorage"); + } + timeToLive; + storage; + constructor(timeToLive) { + this.timeToLive = timeToLive; + this.storage = /* @__PURE__ */ new Map(); + } + read(key) { + const value = this.storage.get(key); + if (value === void 0) return void 0; + if (value.expires !== void 0 && value.expires < Date.now()) { + this.delete(key); + return void 0; + } + return value.session; + } + readAll() { + return this.readAllValues(); + } + readAllKeys() { + return Array.from(this.storage.keys()); + } + readAllValues() { + return Array.from(this.storage.keys()).map((key) => this.read(key)).filter((value) => value !== void 0); + } + readAllEntries() { + return Array.from(this.storage.keys()).map((key) => [ + key, + this.read(key) + ]).filter((pair) => pair[1] !== void 0); + } + has(key) { + return this.storage.has(key); + } + write(key, value) { + this.storage.set(key, addExpiryDate(value, this.timeToLive)); + } + delete(key) { + this.storage.delete(key); + } +}; +function addExpiryDate(value, ttl) { + if (ttl !== void 0 && ttl < Infinity) { + const now = Date.now(); + return { + session: value, + expires: now + ttl + }; + } else { + return { + session: value + }; + } +} +__name(addExpiryDate, "addExpiryDate"); +var SECRET_HEADER = "X-Telegram-Bot-Api-Secret-Token"; +var SECRET_HEADER_LOWERCASE = SECRET_HEADER.toLowerCase(); +var WRONG_TOKEN_ERROR = "secret token is wrong"; +var ok = /* @__PURE__ */ __name(() => new Response(null, { + status: 200 +}), "ok"); +var okJson = /* @__PURE__ */ __name((json) => new Response(json, { + status: 200, + headers: { + "Content-Type": "application/json" + } +}), "okJson"); +var unauthorized = /* @__PURE__ */ __name(() => new Response('"unauthorized"', { + status: 401, + statusText: WRONG_TOKEN_ERROR +}), "unauthorized"); +var awsLambda = /* @__PURE__ */ __name((event, _context, callback) => ({ + get update() { + return JSON.parse(event.body ?? "{}"); + }, + header: event.headers[SECRET_HEADER], + end: /* @__PURE__ */ __name(() => callback(null, { + statusCode: 200 + }), "end"), + respond: /* @__PURE__ */ __name((json) => callback(null, { + statusCode: 200, + headers: { + "Content-Type": "application/json" + }, + body: json + }), "respond"), + unauthorized: /* @__PURE__ */ __name(() => callback(null, { + statusCode: 401 + }), "unauthorized") +}), "awsLambda"); +var awsLambdaAsync = /* @__PURE__ */ __name((event, _context) => { + let resolveResponse; + return { + get update() { + return JSON.parse(event.body ?? "{}"); + }, + header: event.headers[SECRET_HEADER], + end: /* @__PURE__ */ __name(() => resolveResponse({ + statusCode: 200 + }), "end"), + respond: /* @__PURE__ */ __name((json) => resolveResponse({ + statusCode: 200, + headers: { + "Content-Type": "application/json" + }, + body: json + }), "respond"), + unauthorized: /* @__PURE__ */ __name(() => resolveResponse({ + statusCode: 401 + }), "unauthorized"), + handlerReturn: new Promise((res) => resolveResponse = res) + }; +}, "awsLambdaAsync"); +var azure = /* @__PURE__ */ __name((context, request) => ({ + get update() { + return request.body; + }, + header: context.res?.headers?.[SECRET_HEADER], + end: /* @__PURE__ */ __name(() => context.res = { + status: 200, + body: "" + }, "end"), + respond: /* @__PURE__ */ __name((json) => { + context.res?.set?.("Content-Type", "application/json"); + context.res?.send?.(json); + }, "respond"), + unauthorized: /* @__PURE__ */ __name(() => { + context.res?.send?.(401, WRONG_TOKEN_ERROR); + }, "unauthorized") +}), "azure"); +var azureV4 = /* @__PURE__ */ __name((request) => { + let resolveResponse; + return { + get update() { + return request.json(); + }, + header: request.headers.get(SECRET_HEADER) || void 0, + end: /* @__PURE__ */ __name(() => resolveResponse({ + status: 204 + }), "end"), + respond: /* @__PURE__ */ __name((json) => resolveResponse({ + jsonBody: json + }), "respond"), + unauthorized: /* @__PURE__ */ __name(() => resolveResponse({ + status: 401, + body: WRONG_TOKEN_ERROR + }), "unauthorized"), + handlerReturn: new Promise((resolve) => resolveResponse = resolve) + }; +}, "azureV4"); +var bun = /* @__PURE__ */ __name((request) => { + let resolveResponse; + return { + get update() { + return request.json(); + }, + header: request.headers.get(SECRET_HEADER) || void 0, + end: /* @__PURE__ */ __name(() => { + resolveResponse(ok()); + }, "end"), + respond: /* @__PURE__ */ __name((json) => { + resolveResponse(okJson(json)); + }, "respond"), + unauthorized: /* @__PURE__ */ __name(() => { + resolveResponse(unauthorized()); + }, "unauthorized"), + handlerReturn: new Promise((res) => resolveResponse = res) + }; +}, "bun"); +var cloudflare = /* @__PURE__ */ __name((event) => { + let resolveResponse; + event.respondWith(new Promise((resolve) => { + resolveResponse = resolve; + })); + return { + get update() { + return event.request.json(); + }, + header: event.request.headers.get(SECRET_HEADER) || void 0, + end: /* @__PURE__ */ __name(() => { + resolveResponse(ok()); + }, "end"), + respond: /* @__PURE__ */ __name((json) => { + resolveResponse(okJson(json)); + }, "respond"), + unauthorized: /* @__PURE__ */ __name(() => { + resolveResponse(unauthorized()); + }, "unauthorized") + }; +}, "cloudflare"); +var cloudflareModule = /* @__PURE__ */ __name((request) => { + let resolveResponse; + return { + get update() { + return request.json(); + }, + header: request.headers.get(SECRET_HEADER) || void 0, + end: /* @__PURE__ */ __name(() => { + resolveResponse(ok()); + }, "end"), + respond: /* @__PURE__ */ __name((json) => { + resolveResponse(okJson(json)); + }, "respond"), + unauthorized: /* @__PURE__ */ __name(() => { + resolveResponse(unauthorized()); + }, "unauthorized"), + handlerReturn: new Promise((res) => resolveResponse = res) + }; +}, "cloudflareModule"); +var express = /* @__PURE__ */ __name((req, res) => ({ + get update() { + return req.body; + }, + header: req.header(SECRET_HEADER), + end: /* @__PURE__ */ __name(() => res.end(), "end"), + respond: /* @__PURE__ */ __name((json) => { + res.set("Content-Type", "application/json"); + res.send(json); + }, "respond"), + unauthorized: /* @__PURE__ */ __name(() => { + res.status(401).send(WRONG_TOKEN_ERROR); + }, "unauthorized") +}), "express"); +var fastify = /* @__PURE__ */ __name((request, reply) => ({ + get update() { + return request.body; + }, + header: request.headers[SECRET_HEADER_LOWERCASE], + end: /* @__PURE__ */ __name(() => reply.send(""), "end"), + respond: /* @__PURE__ */ __name((json) => reply.headers({ + "Content-Type": "application/json" + }).send(json), "respond"), + unauthorized: /* @__PURE__ */ __name(() => reply.code(401).send(WRONG_TOKEN_ERROR), "unauthorized") +}), "fastify"); +var hono = /* @__PURE__ */ __name((c) => { + let resolveResponse; + return { + get update() { + return c.req.json(); + }, + header: c.req.header(SECRET_HEADER), + end: /* @__PURE__ */ __name(() => { + resolveResponse(c.body("")); + }, "end"), + respond: /* @__PURE__ */ __name((json) => { + resolveResponse(c.json(json)); + }, "respond"), + unauthorized: /* @__PURE__ */ __name(() => { + c.status(401); + resolveResponse(c.body("")); + }, "unauthorized"), + handlerReturn: new Promise((res) => resolveResponse = res) + }; +}, "hono"); +var http = /* @__PURE__ */ __name((req, res) => { + const secretHeaderFromRequest = req.headers[SECRET_HEADER_LOWERCASE]; + return { + get update() { + return new Promise((resolve, reject) => { + const chunks = []; + req.on("data", (chunk) => chunks.push(chunk)).once("end", () => { + const raw2 = Buffer.concat(chunks).toString("utf-8"); + try { + resolve(JSON.parse(raw2)); + } catch (err) { + reject(err); + } + }).once("error", reject); + }); + }, + header: Array.isArray(secretHeaderFromRequest) ? secretHeaderFromRequest[0] : secretHeaderFromRequest, + end: /* @__PURE__ */ __name(() => res.end(), "end"), + respond: /* @__PURE__ */ __name((json) => res.writeHead(200, { + "Content-Type": "application/json" + }).end(json), "respond"), + unauthorized: /* @__PURE__ */ __name(() => res.writeHead(401).end(WRONG_TOKEN_ERROR), "unauthorized") + }; +}, "http"); +var koa = /* @__PURE__ */ __name((ctx) => ({ + get update() { + return ctx.request.body; + }, + header: ctx.get(SECRET_HEADER) || void 0, + end: /* @__PURE__ */ __name(() => { + ctx.body = ""; + }, "end"), + respond: /* @__PURE__ */ __name((json) => { + ctx.set("Content-Type", "application/json"); + ctx.response.body = json; + }, "respond"), + unauthorized: /* @__PURE__ */ __name(() => { + ctx.status = 401; + }, "unauthorized") +}), "koa"); +var nextJs = /* @__PURE__ */ __name((request, response) => ({ + get update() { + return request.body; + }, + header: request.headers[SECRET_HEADER_LOWERCASE], + end: /* @__PURE__ */ __name(() => response.end(), "end"), + respond: /* @__PURE__ */ __name((json) => response.status(200).json(json), "respond"), + unauthorized: /* @__PURE__ */ __name(() => response.status(401).send(WRONG_TOKEN_ERROR), "unauthorized") +}), "nextJs"); +var nhttp = /* @__PURE__ */ __name((rev) => ({ + get update() { + return rev.body; + }, + header: rev.headers.get(SECRET_HEADER) || void 0, + end: /* @__PURE__ */ __name(() => rev.response.sendStatus(200), "end"), + respond: /* @__PURE__ */ __name((json) => rev.response.status(200).send(json), "respond"), + unauthorized: /* @__PURE__ */ __name(() => rev.response.status(401).send(WRONG_TOKEN_ERROR), "unauthorized") +}), "nhttp"); +var oak = /* @__PURE__ */ __name((ctx) => ({ + get update() { + return ctx.request.body.json(); + }, + header: ctx.request.headers.get(SECRET_HEADER) || void 0, + end: /* @__PURE__ */ __name(() => { + ctx.response.status = 200; + }, "end"), + respond: /* @__PURE__ */ __name((json) => { + ctx.response.type = "json"; + ctx.response.body = json; + }, "respond"), + unauthorized: /* @__PURE__ */ __name(() => { + ctx.response.status = 401; + }, "unauthorized") +}), "oak"); +var serveHttp = /* @__PURE__ */ __name((requestEvent) => ({ + get update() { + return requestEvent.request.json(); + }, + header: requestEvent.request.headers.get(SECRET_HEADER) || void 0, + end: /* @__PURE__ */ __name(() => requestEvent.respondWith(ok()), "end"), + respond: /* @__PURE__ */ __name((json) => requestEvent.respondWith(okJson(json)), "respond"), + unauthorized: /* @__PURE__ */ __name(() => requestEvent.respondWith(unauthorized()), "unauthorized") +}), "serveHttp"); +var stdHttp = /* @__PURE__ */ __name((req) => { + let resolveResponse; + return { + get update() { + return req.json(); + }, + header: req.headers.get(SECRET_HEADER) || void 0, + end: /* @__PURE__ */ __name(() => { + if (resolveResponse) resolveResponse(ok()); + }, "end"), + respond: /* @__PURE__ */ __name((json) => { + if (resolveResponse) resolveResponse(okJson(json)); + }, "respond"), + unauthorized: /* @__PURE__ */ __name(() => { + if (resolveResponse) resolveResponse(unauthorized()); + }, "unauthorized"), + handlerReturn: new Promise((res) => resolveResponse = res) + }; +}, "stdHttp"); +var sveltekit = /* @__PURE__ */ __name(({ request }) => { + let resolveResponse; + return { + get update() { + return request.json(); + }, + header: request.headers.get(SECRET_HEADER) || void 0, + end: /* @__PURE__ */ __name(() => { + if (resolveResponse) resolveResponse(ok()); + }, "end"), + respond: /* @__PURE__ */ __name((json) => { + if (resolveResponse) resolveResponse(okJson(json)); + }, "respond"), + unauthorized: /* @__PURE__ */ __name(() => { + if (resolveResponse) resolveResponse(unauthorized()); + }, "unauthorized"), + handlerReturn: new Promise((res) => resolveResponse = res) + }; +}, "sveltekit"); +var worktop = /* @__PURE__ */ __name((req, res) => ({ + get update() { + return req.json(); + }, + header: req.headers.get(SECRET_HEADER) ?? void 0, + end: /* @__PURE__ */ __name(() => res.end(null), "end"), + respond: /* @__PURE__ */ __name((json) => res.send(200, json), "respond"), + unauthorized: /* @__PURE__ */ __name(() => res.send(401, WRONG_TOKEN_ERROR), "unauthorized") +}), "worktop"); +var elysia = /* @__PURE__ */ __name((ctx) => { + let resolveResponse; + return { + get update() { + return ctx.body; + }, + header: ctx.headers[SECRET_HEADER_LOWERCASE], + end() { + resolveResponse(""); + }, + respond(json) { + ctx.set.headers["content-type"] = "application/json"; + resolveResponse(json); + }, + unauthorized() { + ctx.set.status = 401; + resolveResponse(""); + }, + handlerReturn: new Promise((res) => resolveResponse = res) + }; +}, "elysia"); +var adapters = { + "aws-lambda": awsLambda, + "aws-lambda-async": awsLambdaAsync, + azure, + "azure-v4": azureV4, + bun, + cloudflare, + "cloudflare-mod": cloudflareModule, + elysia, + express, + fastify, + hono, + http, + https: http, + koa, + "next-js": nextJs, + nhttp, + oak, + serveHttp, + "std/http": stdHttp, + sveltekit, + worktop +}; +var debugErr1 = browser$1("grammy:error"); +var callbackAdapter = /* @__PURE__ */ __name((update, callback, header, unauthorized2 = () => callback('"unauthorized"')) => ({ + update: Promise.resolve(update), + respond: callback, + header, + unauthorized: unauthorized2 +}), "callbackAdapter"); +var adapters1 = { + ...adapters, + callback: callbackAdapter +}; +function compareSecretToken(header, token) { + if (token === void 0) { + return true; + } + if (header === void 0) { + return false; + } + const encoder = new TextEncoder(); + const headerBytes = encoder.encode(header); + const tokenBytes = encoder.encode(token); + if (headerBytes.length !== tokenBytes.length) { + return false; + } + let hasDifference = 0; + for (let i = 0; i < tokenBytes.length; i++) { + const headerByte = i < headerBytes.length ? headerBytes[i] : 0; + const tokenByte = tokenBytes[i]; + hasDifference |= headerByte ^ tokenByte; + } + return hasDifference === 0; +} +__name(compareSecretToken, "compareSecretToken"); +function webhookCallback(bot, adapter = defaultAdapter, onTimeout, timeoutMilliseconds, secretToken) { + if (bot.isRunning()) { + throw new Error("Bot is already running via long polling, the webhook setup won't receive any updates!"); + } else { + bot.start = () => { + throw new Error("You already started the bot via webhooks, calling `bot.start()` starts the bot with long polling and this will prevent your webhook setup from receiving any updates!"); + }; + } + const { onTimeout: timeout = "throw", timeoutMilliseconds: ms2 = 1e4, secretToken: token } = typeof onTimeout === "object" ? onTimeout : { + onTimeout, + timeoutMilliseconds, + secretToken + }; + let initialized = false; + const server = typeof adapter === "string" ? adapters1[adapter] : adapter; + return async (...args) => { + const handler = server(...args); + if (!initialized) { + await bot.init(); + initialized = true; + } + if (!compareSecretToken(handler.header, token)) { + await handler.unauthorized(); + return handler.handlerReturn; + } + let usedWebhookReply = false; + const webhookReplyEnvelope = { + async send(json) { + usedWebhookReply = true; + await handler.respond(json); + } + }; + await timeoutIfNecessary(bot.handleUpdate(await handler.update, webhookReplyEnvelope), typeof timeout === "function" ? () => timeout(...args) : timeout, ms2); + if (!usedWebhookReply) handler.end?.(); + return handler.handlerReturn; + }; +} +__name(webhookCallback, "webhookCallback"); +function timeoutIfNecessary(task, onTimeout, timeout) { + if (timeout === Infinity) return task; + return new Promise((resolve, reject) => { + const handle = setTimeout(() => { + debugErr1(`Request timed out after ${timeout} ms`); + if (onTimeout === "throw") { + reject(new Error(`Request timed out after ${timeout} ms`)); + } else { + if (typeof onTimeout === "function") onTimeout(); + resolve(); + } + const now = Date.now(); + task.finally(() => { + const diff = Date.now() - now; + debugErr1(`Request completed ${diff} ms after timeout!`); + }); + }, timeout); + task.then(resolve).catch(reject).finally(() => clearTimeout(handle)); + }); +} +__name(timeoutIfNecessary, "timeoutIfNecessary"); + +// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/d1/driver.js +init_modules_watch_stub(); +init_performance2(); + +// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/entity.js +init_modules_watch_stub(); +init_performance2(); +var entityKind = /* @__PURE__ */ Symbol.for("drizzle:entityKind"); +function is(value, type) { + if (!value || typeof value !== "object") { + return false; + } + if (value instanceof type) { + return true; + } + if (!Object.prototype.hasOwnProperty.call(type, entityKind)) { + throw new Error( + `Class "${type.name ?? ""}" doesn't look like a Drizzle entity. If this is incorrect and the class is provided by Drizzle, please report this as a bug.` + ); + } + let cls = Object.getPrototypeOf(value).constructor; + if (cls) { + while (cls) { + if (entityKind in cls && cls[entityKind] === type[entityKind]) { + return true; + } + cls = Object.getPrototypeOf(cls); + } + } + return false; +} +__name(is, "is"); + +// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/logger.js +init_modules_watch_stub(); +init_performance2(); +var ConsoleLogWriter = class { + static { + __name(this, "ConsoleLogWriter"); + } + static [entityKind] = "ConsoleLogWriter"; + write(message) { + console.log(message); + } +}; +var DefaultLogger = class { + static { + __name(this, "DefaultLogger"); + } + static [entityKind] = "DefaultLogger"; + writer; + constructor(config2) { + this.writer = config2?.writer ?? new ConsoleLogWriter(); + } + logQuery(query, params) { + const stringifiedParams = params.map((p) => { + try { + return JSON.stringify(p); + } catch { + return String(p); + } + }); + const paramsStr = stringifiedParams.length ? ` -- params: [${stringifiedParams.join(", ")}]` : ""; + this.writer.write(`Query: ${query}${paramsStr}`); + } +}; +var NoopLogger = class { + static { + __name(this, "NoopLogger"); + } + static [entityKind] = "NoopLogger"; + logQuery() { + } +}; + +// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/relations.js +init_modules_watch_stub(); +init_performance2(); + +// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/table.js +init_modules_watch_stub(); +init_performance2(); + +// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/table.utils.js +init_modules_watch_stub(); +init_performance2(); +var TableName = /* @__PURE__ */ Symbol.for("drizzle:Name"); + +// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/table.js +var Schema = /* @__PURE__ */ Symbol.for("drizzle:Schema"); +var Columns = /* @__PURE__ */ Symbol.for("drizzle:Columns"); +var ExtraConfigColumns = /* @__PURE__ */ Symbol.for("drizzle:ExtraConfigColumns"); +var OriginalName = /* @__PURE__ */ Symbol.for("drizzle:OriginalName"); +var BaseName = /* @__PURE__ */ Symbol.for("drizzle:BaseName"); +var IsAlias = /* @__PURE__ */ Symbol.for("drizzle:IsAlias"); +var ExtraConfigBuilder = /* @__PURE__ */ Symbol.for("drizzle:ExtraConfigBuilder"); +var IsDrizzleTable = /* @__PURE__ */ Symbol.for("drizzle:IsDrizzleTable"); +var Table = class { + static { + __name(this, "Table"); + } + static [entityKind] = "Table"; + /** @internal */ + static Symbol = { + Name: TableName, + Schema, + OriginalName, + Columns, + ExtraConfigColumns, + BaseName, + IsAlias, + ExtraConfigBuilder + }; + /** + * @internal + * Can be changed if the table is aliased. + */ + [TableName]; + /** + * @internal + * Used to store the original name of the table, before any aliasing. + */ + [OriginalName]; + /** @internal */ + [Schema]; + /** @internal */ + [Columns]; + /** @internal */ + [ExtraConfigColumns]; + /** + * @internal + * Used to store the table name before the transformation via the `tableCreator` functions. + */ + [BaseName]; + /** @internal */ + [IsAlias] = false; + /** @internal */ + [IsDrizzleTable] = true; + /** @internal */ + [ExtraConfigBuilder] = void 0; + constructor(name, schema, baseName) { + this[TableName] = this[OriginalName] = name; + this[Schema] = schema; + this[BaseName] = baseName; + } +}; +function getTableName(table) { + return table[TableName]; +} +__name(getTableName, "getTableName"); +function getTableUniqueName(table) { + return `${table[Schema] ?? "public"}.${table[TableName]}`; +} +__name(getTableUniqueName, "getTableUniqueName"); + +// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/column.js +init_modules_watch_stub(); +init_performance2(); +var Column = class { + static { + __name(this, "Column"); + } + constructor(table, config2) { + this.table = table; + this.config = config2; + this.name = config2.name; + this.keyAsName = config2.keyAsName; + this.notNull = config2.notNull; + this.default = config2.default; + this.defaultFn = config2.defaultFn; + this.onUpdateFn = config2.onUpdateFn; + this.hasDefault = config2.hasDefault; + this.primary = config2.primaryKey; + this.isUnique = config2.isUnique; + this.uniqueName = config2.uniqueName; + this.uniqueType = config2.uniqueType; + this.dataType = config2.dataType; + this.columnType = config2.columnType; + this.generated = config2.generated; + this.generatedIdentity = config2.generatedIdentity; + } + static [entityKind] = "Column"; + name; + keyAsName; + primary; + notNull; + default; + defaultFn; + onUpdateFn; + hasDefault; + isUnique; + uniqueName; + uniqueType; + dataType; + columnType; + enumValues = void 0; + generated = void 0; + generatedIdentity = void 0; + config; + mapFromDriverValue(value) { + return value; + } + mapToDriverValue(value) { + return value; + } + // ** @internal */ + shouldDisableInsert() { + return this.config.generated !== void 0 && this.config.generated.type !== "byDefault"; + } +}; + +// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/pg-core/primary-keys.js +init_modules_watch_stub(); +init_performance2(); + +// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/pg-core/table.js +init_modules_watch_stub(); +init_performance2(); + +// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/utils.js +init_modules_watch_stub(); +init_performance2(); + +// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/sql/sql.js +init_modules_watch_stub(); +init_performance2(); + +// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/pg-core/columns/enum.js +init_modules_watch_stub(); +init_performance2(); + +// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/pg-core/columns/common.js +init_modules_watch_stub(); +init_performance2(); + +// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/column-builder.js +init_modules_watch_stub(); +init_performance2(); +var ColumnBuilder = class { + static { + __name(this, "ColumnBuilder"); + } + static [entityKind] = "ColumnBuilder"; + config; + constructor(name, dataType, columnType) { + this.config = { + name, + keyAsName: name === "", + notNull: false, + default: void 0, + hasDefault: false, + primaryKey: false, + isUnique: false, + uniqueName: void 0, + uniqueType: void 0, + dataType, + columnType, + generated: void 0 + }; + } + /** + * Changes the data type of the column. Commonly used with `json` columns. Also, useful for branded types. + * + * @example + * ```ts + * const users = pgTable('users', { + * id: integer('id').$type().primaryKey(), + * details: json('details').$type().notNull(), + * }); + * ``` + */ + $type() { + return this; + } + /** + * Adds a `not null` clause to the column definition. + * + * Affects the `select` model of the table - columns *without* `not null` will be nullable on select. + */ + notNull() { + this.config.notNull = true; + return this; + } + /** + * Adds a `default ` clause to the column definition. + * + * Affects the `insert` model of the table - columns *with* `default` are optional on insert. + * + * If you need to set a dynamic default value, use {@link $defaultFn} instead. + */ + default(value) { + this.config.default = value; + this.config.hasDefault = true; + return this; + } + /** + * Adds a dynamic default value to the column. + * The function will be called when the row is inserted, and the returned value will be used as the column value. + * + * **Note:** This value does not affect the `drizzle-kit` behavior, it is only used at runtime in `drizzle-orm`. + */ + $defaultFn(fn) { + this.config.defaultFn = fn; + this.config.hasDefault = true; + return this; + } + /** + * Alias for {@link $defaultFn}. + */ + $default = this.$defaultFn; + /** + * Adds a dynamic update value to the column. + * The function will be called when the row is updated, and the returned value will be used as the column value if none is provided. + * If no `default` (or `$defaultFn`) value is provided, the function will be called when the row is inserted as well, and the returned value will be used as the column value. + * + * **Note:** This value does not affect the `drizzle-kit` behavior, it is only used at runtime in `drizzle-orm`. + */ + $onUpdateFn(fn) { + this.config.onUpdateFn = fn; + this.config.hasDefault = true; + return this; + } + /** + * Alias for {@link $onUpdateFn}. + */ + $onUpdate = this.$onUpdateFn; + /** + * Adds a `primary key` clause to the column definition. This implicitly makes the column `not null`. + * + * In SQLite, `integer primary key` implicitly makes the column auto-incrementing. + */ + primaryKey() { + this.config.primaryKey = true; + this.config.notNull = true; + return this; + } + /** @internal Sets the name of the column to the key within the table definition if a name was not given. */ + setName(name) { + if (this.config.name !== "") return; + this.config.name = name; + } +}; + +// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/pg-core/foreign-keys.js +init_modules_watch_stub(); +init_performance2(); +var ForeignKeyBuilder = class { + static { + __name(this, "ForeignKeyBuilder"); + } + static [entityKind] = "PgForeignKeyBuilder"; + /** @internal */ + reference; + /** @internal */ + _onUpdate = "no action"; + /** @internal */ + _onDelete = "no action"; + constructor(config2, actions) { + this.reference = () => { + const { name, columns, foreignColumns } = config2(); + return { name, columns, foreignTable: foreignColumns[0].table, foreignColumns }; + }; + if (actions) { + this._onUpdate = actions.onUpdate; + this._onDelete = actions.onDelete; + } + } + onUpdate(action) { + this._onUpdate = action === void 0 ? "no action" : action; + return this; + } + onDelete(action) { + this._onDelete = action === void 0 ? "no action" : action; + return this; + } + /** @internal */ + build(table) { + return new ForeignKey(table, this); + } +}; +var ForeignKey = class { + static { + __name(this, "ForeignKey"); + } + constructor(table, builder) { + this.table = table; + this.reference = builder.reference; + this.onUpdate = builder._onUpdate; + this.onDelete = builder._onDelete; + } + static [entityKind] = "PgForeignKey"; + reference; + onUpdate; + onDelete; + getName() { + const { name, columns, foreignColumns } = this.reference(); + const columnNames = columns.map((column) => column.name); + const foreignColumnNames = foreignColumns.map((column) => column.name); + const chunks = [ + this.table[TableName], + ...columnNames, + foreignColumns[0].table[TableName], + ...foreignColumnNames + ]; + return name ?? `${chunks.join("_")}_fk`; + } +}; + +// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/tracing-utils.js +init_modules_watch_stub(); +init_performance2(); +function iife(fn, ...args) { + return fn(...args); +} +__name(iife, "iife"); + +// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/pg-core/unique-constraint.js +init_modules_watch_stub(); +init_performance2(); +function uniqueKeyName(table, columns) { + return `${table[TableName]}_${columns.join("_")}_unique`; +} +__name(uniqueKeyName, "uniqueKeyName"); +var UniqueConstraintBuilder = class { + static { + __name(this, "UniqueConstraintBuilder"); + } + constructor(columns, name) { + this.name = name; + this.columns = columns; + } + static [entityKind] = "PgUniqueConstraintBuilder"; + /** @internal */ + columns; + /** @internal */ + nullsNotDistinctConfig = false; + nullsNotDistinct() { + this.nullsNotDistinctConfig = true; + return this; + } + /** @internal */ + build(table) { + return new UniqueConstraint(table, this.columns, this.nullsNotDistinctConfig, this.name); + } +}; +var UniqueOnConstraintBuilder = class { + static { + __name(this, "UniqueOnConstraintBuilder"); + } + static [entityKind] = "PgUniqueOnConstraintBuilder"; + /** @internal */ + name; + constructor(name) { + this.name = name; + } + on(...columns) { + return new UniqueConstraintBuilder(columns, this.name); + } +}; +var UniqueConstraint = class { + static { + __name(this, "UniqueConstraint"); + } + constructor(table, columns, nullsNotDistinct, name) { + this.table = table; + this.columns = columns; + this.name = name ?? uniqueKeyName(this.table, this.columns.map((column) => column.name)); + this.nullsNotDistinct = nullsNotDistinct; + } + static [entityKind] = "PgUniqueConstraint"; + columns; + name; + nullsNotDistinct = false; + getName() { + return this.name; + } +}; + +// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/pg-core/utils/array.js +init_modules_watch_stub(); +init_performance2(); +function parsePgArrayValue(arrayString, startFrom, inQuotes) { + for (let i = startFrom; i < arrayString.length; i++) { + const char = arrayString[i]; + if (char === "\\") { + i++; + continue; + } + if (char === '"') { + return [arrayString.slice(startFrom, i).replace(/\\/g, ""), i + 1]; + } + if (inQuotes) { + continue; + } + if (char === "," || char === "}") { + return [arrayString.slice(startFrom, i).replace(/\\/g, ""), i]; + } + } + return [arrayString.slice(startFrom).replace(/\\/g, ""), arrayString.length]; +} +__name(parsePgArrayValue, "parsePgArrayValue"); +function parsePgNestedArray(arrayString, startFrom = 0) { + const result = []; + let i = startFrom; + let lastCharIsComma = false; + while (i < arrayString.length) { + const char = arrayString[i]; + if (char === ",") { + if (lastCharIsComma || i === startFrom) { + result.push(""); + } + lastCharIsComma = true; + i++; + continue; + } + lastCharIsComma = false; + if (char === "\\") { + i += 2; + continue; + } + if (char === '"') { + const [value2, startFrom2] = parsePgArrayValue(arrayString, i + 1, true); + result.push(value2); + i = startFrom2; + continue; + } + if (char === "}") { + return [result, i + 1]; + } + if (char === "{") { + const [value2, startFrom2] = parsePgNestedArray(arrayString, i + 1); + result.push(value2); + i = startFrom2; + continue; + } + const [value, newStartFrom] = parsePgArrayValue(arrayString, i, false); + result.push(value); + i = newStartFrom; + } + return [result, i]; +} +__name(parsePgNestedArray, "parsePgNestedArray"); +function parsePgArray(arrayString) { + const [result] = parsePgNestedArray(arrayString, 1); + return result; +} +__name(parsePgArray, "parsePgArray"); +function makePgArray(array) { + return `{${array.map((item) => { + if (Array.isArray(item)) { + return makePgArray(item); + } + if (typeof item === "string") { + return `"${item.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`; + } + return `${item}`; + }).join(",")}}`; +} +__name(makePgArray, "makePgArray"); + +// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/pg-core/columns/common.js +var PgColumnBuilder = class extends ColumnBuilder { + static { + __name(this, "PgColumnBuilder"); + } + foreignKeyConfigs = []; + static [entityKind] = "PgColumnBuilder"; + array(size) { + return new PgArrayBuilder(this.config.name, this, size); + } + references(ref, actions = {}) { + this.foreignKeyConfigs.push({ ref, actions }); + return this; + } + unique(name, config2) { + this.config.isUnique = true; + this.config.uniqueName = name; + this.config.uniqueType = config2?.nulls; + return this; + } + generatedAlwaysAs(as) { + this.config.generated = { + as, + type: "always", + mode: "stored" + }; + return this; + } + /** @internal */ + buildForeignKeys(column, table) { + return this.foreignKeyConfigs.map(({ ref, actions }) => { + return iife( + (ref2, actions2) => { + const builder = new ForeignKeyBuilder(() => { + const foreignColumn = ref2(); + return { columns: [column], foreignColumns: [foreignColumn] }; + }); + if (actions2.onUpdate) { + builder.onUpdate(actions2.onUpdate); + } + if (actions2.onDelete) { + builder.onDelete(actions2.onDelete); + } + return builder.build(table); + }, + ref, + actions + ); + }); + } + /** @internal */ + buildExtraConfigColumn(table) { + return new ExtraConfigColumn(table, this.config); + } +}; +var PgColumn = class extends Column { + static { + __name(this, "PgColumn"); + } + constructor(table, config2) { + if (!config2.uniqueName) { + config2.uniqueName = uniqueKeyName(table, [config2.name]); + } + super(table, config2); + this.table = table; + } + static [entityKind] = "PgColumn"; +}; +var ExtraConfigColumn = class extends PgColumn { + static { + __name(this, "ExtraConfigColumn"); + } + static [entityKind] = "ExtraConfigColumn"; + getSQLType() { + return this.getSQLType(); + } + indexConfig = { + order: this.config.order ?? "asc", + nulls: this.config.nulls ?? "last", + opClass: this.config.opClass + }; + defaultConfig = { + order: "asc", + nulls: "last", + opClass: void 0 + }; + asc() { + this.indexConfig.order = "asc"; + return this; + } + desc() { + this.indexConfig.order = "desc"; + return this; + } + nullsFirst() { + this.indexConfig.nulls = "first"; + return this; + } + nullsLast() { + this.indexConfig.nulls = "last"; + return this; + } + /** + * ### PostgreSQL documentation quote + * + * > An operator class with optional parameters can be specified for each column of an index. + * The operator class identifies the operators to be used by the index for that column. + * For example, a B-tree index on four-byte integers would use the int4_ops class; + * this operator class includes comparison functions for four-byte integers. + * In practice the default operator class for the column's data type is usually sufficient. + * The main point of having operator classes is that for some data types, there could be more than one meaningful ordering. + * For example, we might want to sort a complex-number data type either by absolute value or by real part. + * We could do this by defining two operator classes for the data type and then selecting the proper class when creating an index. + * More information about operator classes check: + * + * ### Useful links + * https://www.postgresql.org/docs/current/sql-createindex.html + * + * https://www.postgresql.org/docs/current/indexes-opclass.html + * + * https://www.postgresql.org/docs/current/xindex.html + * + * ### Additional types + * If you have the `pg_vector` extension installed in your database, you can use the + * `vector_l2_ops`, `vector_ip_ops`, `vector_cosine_ops`, `vector_l1_ops`, `bit_hamming_ops`, `bit_jaccard_ops`, `halfvec_l2_ops`, `sparsevec_l2_ops` options, which are predefined types. + * + * **You can always specify any string you want in the operator class, in case Drizzle doesn't have it natively in its types** + * + * @param opClass + * @returns + */ + op(opClass) { + this.indexConfig.opClass = opClass; + return this; + } +}; +var IndexedColumn = class { + static { + __name(this, "IndexedColumn"); + } + static [entityKind] = "IndexedColumn"; + constructor(name, keyAsName, type, indexConfig) { + this.name = name; + this.keyAsName = keyAsName; + this.type = type; + this.indexConfig = indexConfig; + } + name; + keyAsName; + type; + indexConfig; +}; +var PgArrayBuilder = class extends PgColumnBuilder { + static { + __name(this, "PgArrayBuilder"); + } + static [entityKind] = "PgArrayBuilder"; + constructor(name, baseBuilder, size) { + super(name, "array", "PgArray"); + this.config.baseBuilder = baseBuilder; + this.config.size = size; + } + /** @internal */ + build(table) { + const baseColumn = this.config.baseBuilder.build(table); + return new PgArray( + table, + this.config, + baseColumn + ); + } +}; +var PgArray = class _PgArray extends PgColumn { + static { + __name(this, "PgArray"); + } + constructor(table, config2, baseColumn, range) { + super(table, config2); + this.baseColumn = baseColumn; + this.range = range; + this.size = config2.size; + } + size; + static [entityKind] = "PgArray"; + getSQLType() { + return `${this.baseColumn.getSQLType()}[${typeof this.size === "number" ? this.size : ""}]`; + } + mapFromDriverValue(value) { + if (typeof value === "string") { + value = parsePgArray(value); + } + return value.map((v) => this.baseColumn.mapFromDriverValue(v)); + } + mapToDriverValue(value, isNestedArray = false) { + const a = value.map( + (v) => v === null ? null : is(this.baseColumn, _PgArray) ? this.baseColumn.mapToDriverValue(v, true) : this.baseColumn.mapToDriverValue(v) + ); + if (isNestedArray) return a; + return makePgArray(a); + } +}; + +// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/pg-core/columns/enum.js +var PgEnumObjectColumnBuilder = class extends PgColumnBuilder { + static { + __name(this, "PgEnumObjectColumnBuilder"); + } + static [entityKind] = "PgEnumObjectColumnBuilder"; + constructor(name, enumInstance) { + super(name, "string", "PgEnumObjectColumn"); + this.config.enum = enumInstance; + } + /** @internal */ + build(table) { + return new PgEnumObjectColumn( + table, + this.config + ); + } +}; +var PgEnumObjectColumn = class extends PgColumn { + static { + __name(this, "PgEnumObjectColumn"); + } + static [entityKind] = "PgEnumObjectColumn"; + enum; + enumValues = this.config.enum.enumValues; + constructor(table, config2) { + super(table, config2); + this.enum = config2.enum; + } + getSQLType() { + return this.enum.enumName; + } +}; +var isPgEnumSym = /* @__PURE__ */ Symbol.for("drizzle:isPgEnum"); +function isPgEnum(obj) { + return !!obj && typeof obj === "function" && isPgEnumSym in obj && obj[isPgEnumSym] === true; +} +__name(isPgEnum, "isPgEnum"); +var PgEnumColumnBuilder = class extends PgColumnBuilder { + static { + __name(this, "PgEnumColumnBuilder"); + } + static [entityKind] = "PgEnumColumnBuilder"; + constructor(name, enumInstance) { + super(name, "string", "PgEnumColumn"); + this.config.enum = enumInstance; + } + /** @internal */ + build(table) { + return new PgEnumColumn( + table, + this.config + ); + } +}; +var PgEnumColumn = class extends PgColumn { + static { + __name(this, "PgEnumColumn"); + } + static [entityKind] = "PgEnumColumn"; + enum = this.config.enum; + enumValues = this.config.enum.enumValues; + constructor(table, config2) { + super(table, config2); + this.enum = config2.enum; + } + getSQLType() { + return this.enum.enumName; + } +}; + +// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/subquery.js +init_modules_watch_stub(); +init_performance2(); +var Subquery = class { + static { + __name(this, "Subquery"); + } + static [entityKind] = "Subquery"; + constructor(sql2, fields, alias, isWith = false, usedTables = []) { + this._ = { + brand: "Subquery", + sql: sql2, + selectedFields: fields, + alias, + isWith, + usedTables + }; + } + // getSQL(): SQL { + // return new SQL([this]); + // } +}; +var WithSubquery = class extends Subquery { + static { + __name(this, "WithSubquery"); + } + static [entityKind] = "WithSubquery"; +}; + +// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/tracing.js +init_modules_watch_stub(); +init_performance2(); + +// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/version.js +init_modules_watch_stub(); +init_performance2(); +var version2 = "0.45.1"; + +// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/tracing.js +var otel; +var rawTracer; +var tracer = { + startActiveSpan(name, fn) { + if (!otel) { + return fn(); + } + if (!rawTracer) { + rawTracer = otel.trace.getTracer("drizzle-orm", version2); + } + return iife( + (otel2, rawTracer2) => rawTracer2.startActiveSpan( + name, + (span) => { + try { + return fn(span); + } catch (e) { + span.setStatus({ + code: otel2.SpanStatusCode.ERROR, + message: e instanceof Error ? e.message : "Unknown error" + // eslint-disable-line no-instanceof/no-instanceof + }); + throw e; + } finally { + span.end(); + } + } + ), + otel, + rawTracer + ); + } +}; + +// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/view-common.js +init_modules_watch_stub(); +init_performance2(); +var ViewBaseConfig = /* @__PURE__ */ Symbol.for("drizzle:ViewBaseConfig"); + +// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/sql/sql.js +var FakePrimitiveParam = class { + static { + __name(this, "FakePrimitiveParam"); + } + static [entityKind] = "FakePrimitiveParam"; +}; +function isSQLWrapper(value) { + return value !== null && value !== void 0 && typeof value.getSQL === "function"; +} +__name(isSQLWrapper, "isSQLWrapper"); +function mergeQueries(queries) { + const result = { sql: "", params: [] }; + for (const query of queries) { + result.sql += query.sql; + result.params.push(...query.params); + if (query.typings?.length) { + if (!result.typings) { + result.typings = []; + } + result.typings.push(...query.typings); + } + } + return result; +} +__name(mergeQueries, "mergeQueries"); +var StringChunk = class { + static { + __name(this, "StringChunk"); + } + static [entityKind] = "StringChunk"; + value; + constructor(value) { + this.value = Array.isArray(value) ? value : [value]; + } + getSQL() { + return new SQL([this]); + } +}; +var SQL = class _SQL { + static { + __name(this, "SQL"); + } + constructor(queryChunks) { + this.queryChunks = queryChunks; + for (const chunk of queryChunks) { + if (is(chunk, Table)) { + const schemaName = chunk[Table.Symbol.Schema]; + this.usedTables.push( + schemaName === void 0 ? chunk[Table.Symbol.Name] : schemaName + "." + chunk[Table.Symbol.Name] + ); + } + } + } + static [entityKind] = "SQL"; + /** @internal */ + decoder = noopDecoder; + shouldInlineParams = false; + /** @internal */ + usedTables = []; + append(query) { + this.queryChunks.push(...query.queryChunks); + return this; + } + toQuery(config2) { + return tracer.startActiveSpan("drizzle.buildSQL", (span) => { + const query = this.buildQueryFromSourceParams(this.queryChunks, config2); + span?.setAttributes({ + "drizzle.query.text": query.sql, + "drizzle.query.params": JSON.stringify(query.params) + }); + return query; + }); + } + buildQueryFromSourceParams(chunks, _config) { + const config2 = Object.assign({}, _config, { + inlineParams: _config.inlineParams || this.shouldInlineParams, + paramStartIndex: _config.paramStartIndex || { value: 0 } + }); + const { + casing, + escapeName, + escapeParam, + prepareTyping, + inlineParams, + paramStartIndex + } = config2; + return mergeQueries(chunks.map((chunk) => { + if (is(chunk, StringChunk)) { + return { sql: chunk.value.join(""), params: [] }; + } + if (is(chunk, Name)) { + return { sql: escapeName(chunk.value), params: [] }; + } + if (chunk === void 0) { + return { sql: "", params: [] }; + } + if (Array.isArray(chunk)) { + const result = [new StringChunk("(")]; + for (const [i, p] of chunk.entries()) { + result.push(p); + if (i < chunk.length - 1) { + result.push(new StringChunk(", ")); + } + } + result.push(new StringChunk(")")); + return this.buildQueryFromSourceParams(result, config2); + } + if (is(chunk, _SQL)) { + return this.buildQueryFromSourceParams(chunk.queryChunks, { + ...config2, + inlineParams: inlineParams || chunk.shouldInlineParams + }); + } + if (is(chunk, Table)) { + const schemaName = chunk[Table.Symbol.Schema]; + const tableName = chunk[Table.Symbol.Name]; + return { + sql: schemaName === void 0 || chunk[IsAlias] ? escapeName(tableName) : escapeName(schemaName) + "." + escapeName(tableName), + params: [] + }; + } + if (is(chunk, Column)) { + const columnName = casing.getColumnCasing(chunk); + if (_config.invokeSource === "indexes") { + return { sql: escapeName(columnName), params: [] }; + } + const schemaName = chunk.table[Table.Symbol.Schema]; + return { + sql: chunk.table[IsAlias] || schemaName === void 0 ? escapeName(chunk.table[Table.Symbol.Name]) + "." + escapeName(columnName) : escapeName(schemaName) + "." + escapeName(chunk.table[Table.Symbol.Name]) + "." + escapeName(columnName), + params: [] + }; + } + if (is(chunk, View)) { + const schemaName = chunk[ViewBaseConfig].schema; + const viewName = chunk[ViewBaseConfig].name; + return { + sql: schemaName === void 0 || chunk[ViewBaseConfig].isAlias ? escapeName(viewName) : escapeName(schemaName) + "." + escapeName(viewName), + params: [] + }; + } + if (is(chunk, Param)) { + if (is(chunk.value, Placeholder)) { + return { sql: escapeParam(paramStartIndex.value++, chunk), params: [chunk], typings: ["none"] }; + } + const mappedValue = chunk.value === null ? null : chunk.encoder.mapToDriverValue(chunk.value); + if (is(mappedValue, _SQL)) { + return this.buildQueryFromSourceParams([mappedValue], config2); + } + if (inlineParams) { + return { sql: this.mapInlineParam(mappedValue, config2), params: [] }; + } + let typings = ["none"]; + if (prepareTyping) { + typings = [prepareTyping(chunk.encoder)]; + } + return { sql: escapeParam(paramStartIndex.value++, mappedValue), params: [mappedValue], typings }; + } + if (is(chunk, Placeholder)) { + return { sql: escapeParam(paramStartIndex.value++, chunk), params: [chunk], typings: ["none"] }; + } + if (is(chunk, _SQL.Aliased) && chunk.fieldAlias !== void 0) { + return { sql: escapeName(chunk.fieldAlias), params: [] }; + } + if (is(chunk, Subquery)) { + if (chunk._.isWith) { + return { sql: escapeName(chunk._.alias), params: [] }; + } + return this.buildQueryFromSourceParams([ + new StringChunk("("), + chunk._.sql, + new StringChunk(") "), + new Name(chunk._.alias) + ], config2); + } + if (isPgEnum(chunk)) { + if (chunk.schema) { + return { sql: escapeName(chunk.schema) + "." + escapeName(chunk.enumName), params: [] }; + } + return { sql: escapeName(chunk.enumName), params: [] }; + } + if (isSQLWrapper(chunk)) { + if (chunk.shouldOmitSQLParens?.()) { + return this.buildQueryFromSourceParams([chunk.getSQL()], config2); + } + return this.buildQueryFromSourceParams([ + new StringChunk("("), + chunk.getSQL(), + new StringChunk(")") + ], config2); + } + if (inlineParams) { + return { sql: this.mapInlineParam(chunk, config2), params: [] }; + } + return { sql: escapeParam(paramStartIndex.value++, chunk), params: [chunk], typings: ["none"] }; + })); + } + mapInlineParam(chunk, { escapeString }) { + if (chunk === null) { + return "null"; + } + if (typeof chunk === "number" || typeof chunk === "boolean") { + return chunk.toString(); + } + if (typeof chunk === "string") { + return escapeString(chunk); + } + if (typeof chunk === "object") { + const mappedValueAsString = chunk.toString(); + if (mappedValueAsString === "[object Object]") { + return escapeString(JSON.stringify(chunk)); + } + return escapeString(mappedValueAsString); + } + throw new Error("Unexpected param value: " + chunk); + } + getSQL() { + return this; + } + as(alias) { + if (alias === void 0) { + return this; + } + return new _SQL.Aliased(this, alias); + } + mapWith(decoder) { + this.decoder = typeof decoder === "function" ? { mapFromDriverValue: decoder } : decoder; + return this; + } + inlineParams() { + this.shouldInlineParams = true; + return this; + } + /** + * This method is used to conditionally include a part of the query. + * + * @param condition - Condition to check + * @returns itself if the condition is `true`, otherwise `undefined` + */ + if(condition) { + return condition ? this : void 0; + } +}; +var Name = class { + static { + __name(this, "Name"); + } + constructor(value) { + this.value = value; + } + static [entityKind] = "Name"; + brand; + getSQL() { + return new SQL([this]); + } +}; +function isDriverValueEncoder(value) { + return typeof value === "object" && value !== null && "mapToDriverValue" in value && typeof value.mapToDriverValue === "function"; +} +__name(isDriverValueEncoder, "isDriverValueEncoder"); +var noopDecoder = { + mapFromDriverValue: /* @__PURE__ */ __name((value) => value, "mapFromDriverValue") +}; +var noopEncoder = { + mapToDriverValue: /* @__PURE__ */ __name((value) => value, "mapToDriverValue") +}; +var noopMapper = { + ...noopDecoder, + ...noopEncoder +}; +var Param = class { + static { + __name(this, "Param"); + } + /** + * @param value - Parameter value + * @param encoder - Encoder to convert the value to a driver parameter + */ + constructor(value, encoder = noopEncoder) { + this.value = value; + this.encoder = encoder; + } + static [entityKind] = "Param"; + brand; + getSQL() { + return new SQL([this]); + } +}; +function sql(strings, ...params) { + const queryChunks = []; + if (params.length > 0 || strings.length > 0 && strings[0] !== "") { + queryChunks.push(new StringChunk(strings[0])); + } + for (const [paramIndex, param2] of params.entries()) { + queryChunks.push(param2, new StringChunk(strings[paramIndex + 1])); + } + return new SQL(queryChunks); +} +__name(sql, "sql"); +((sql2) => { + function empty() { + return new SQL([]); + } + __name(empty, "empty"); + sql2.empty = empty; + function fromList(list) { + return new SQL(list); + } + __name(fromList, "fromList"); + sql2.fromList = fromList; + function raw2(str2) { + return new SQL([new StringChunk(str2)]); + } + __name(raw2, "raw"); + sql2.raw = raw2; + function join(chunks, separator) { + const result = []; + for (const [i, chunk] of chunks.entries()) { + if (i > 0 && separator !== void 0) { + result.push(separator); + } + result.push(chunk); + } + return new SQL(result); + } + __name(join, "join"); + sql2.join = join; + function identifier(value) { + return new Name(value); + } + __name(identifier, "identifier"); + sql2.identifier = identifier; + function placeholder2(name2) { + return new Placeholder(name2); + } + __name(placeholder2, "placeholder2"); + sql2.placeholder = placeholder2; + function param2(value, encoder) { + return new Param(value, encoder); + } + __name(param2, "param2"); + sql2.param = param2; +})(sql || (sql = {})); +((SQL2) => { + class Aliased { + static { + __name(this, "Aliased"); + } + constructor(sql2, fieldAlias) { + this.sql = sql2; + this.fieldAlias = fieldAlias; + } + static [entityKind] = "SQL.Aliased"; + /** @internal */ + isSelectionField = false; + getSQL() { + return this.sql; + } + /** @internal */ + clone() { + return new Aliased(this.sql, this.fieldAlias); + } + } + SQL2.Aliased = Aliased; +})(SQL || (SQL = {})); +var Placeholder = class { + static { + __name(this, "Placeholder"); + } + constructor(name2) { + this.name = name2; + } + static [entityKind] = "Placeholder"; + getSQL() { + return new SQL([this]); + } +}; +function fillPlaceholders(params, values) { + return params.map((p) => { + if (is(p, Placeholder)) { + if (!(p.name in values)) { + throw new Error(`No value for placeholder "${p.name}" was provided`); + } + return values[p.name]; + } + if (is(p, Param) && is(p.value, Placeholder)) { + if (!(p.value.name in values)) { + throw new Error(`No value for placeholder "${p.value.name}" was provided`); + } + return p.encoder.mapToDriverValue(values[p.value.name]); + } + return p; + }); +} +__name(fillPlaceholders, "fillPlaceholders"); +var IsDrizzleView = /* @__PURE__ */ Symbol.for("drizzle:IsDrizzleView"); +var View = class { + static { + __name(this, "View"); + } + static [entityKind] = "View"; + /** @internal */ + [ViewBaseConfig]; + /** @internal */ + [IsDrizzleView] = true; + constructor({ name: name2, schema, selectedFields, query }) { + this[ViewBaseConfig] = { + name: name2, + originalName: name2, + schema, + selectedFields, + query, + isExisting: !query, + isAlias: false + }; + } + getSQL() { + return new SQL([this]); + } +}; +Column.prototype.getSQL = function() { + return new SQL([this]); +}; +Table.prototype.getSQL = function() { + return new SQL([this]); +}; +Subquery.prototype.getSQL = function() { + return new SQL([this]); +}; + +// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/utils.js +function mapResultRow(columns, row, joinsNotNullableMap) { + const nullifyMap = {}; + const result = columns.reduce( + (result2, { path, field }, columnIndex) => { + let decoder; + if (is(field, Column)) { + decoder = field; + } else if (is(field, SQL)) { + decoder = field.decoder; + } else if (is(field, Subquery)) { + decoder = field._.sql.decoder; + } else { + decoder = field.sql.decoder; + } + let node = result2; + for (const [pathChunkIndex, pathChunk] of path.entries()) { + if (pathChunkIndex < path.length - 1) { + if (!(pathChunk in node)) { + node[pathChunk] = {}; + } + node = node[pathChunk]; + } else { + const rawValue = row[columnIndex]; + const value = node[pathChunk] = rawValue === null ? null : decoder.mapFromDriverValue(rawValue); + if (joinsNotNullableMap && is(field, Column) && path.length === 2) { + const objectName = path[0]; + if (!(objectName in nullifyMap)) { + nullifyMap[objectName] = value === null ? getTableName(field.table) : false; + } else if (typeof nullifyMap[objectName] === "string" && nullifyMap[objectName] !== getTableName(field.table)) { + nullifyMap[objectName] = false; + } + } + } + } + return result2; + }, + {} + ); + if (joinsNotNullableMap && Object.keys(nullifyMap).length > 0) { + for (const [objectName, tableName] of Object.entries(nullifyMap)) { + if (typeof tableName === "string" && !joinsNotNullableMap[tableName]) { + result[objectName] = null; + } + } + } + return result; +} +__name(mapResultRow, "mapResultRow"); +function orderSelectedFields(fields, pathPrefix) { + return Object.entries(fields).reduce((result, [name, field]) => { + if (typeof name !== "string") { + return result; + } + const newPath = pathPrefix ? [...pathPrefix, name] : [name]; + if (is(field, Column) || is(field, SQL) || is(field, SQL.Aliased) || is(field, Subquery)) { + result.push({ path: newPath, field }); + } else if (is(field, Table)) { + result.push(...orderSelectedFields(field[Table.Symbol.Columns], newPath)); + } else { + result.push(...orderSelectedFields(field, newPath)); + } + return result; + }, []); +} +__name(orderSelectedFields, "orderSelectedFields"); +function haveSameKeys(left, right) { + const leftKeys = Object.keys(left); + const rightKeys = Object.keys(right); + if (leftKeys.length !== rightKeys.length) { + return false; + } + for (const [index, key] of leftKeys.entries()) { + if (key !== rightKeys[index]) { + return false; + } + } + return true; +} +__name(haveSameKeys, "haveSameKeys"); +function mapUpdateSet(table, values) { + const entries = Object.entries(values).filter(([, value]) => value !== void 0).map(([key, value]) => { + if (is(value, SQL) || is(value, Column)) { + return [key, value]; + } else { + return [key, new Param(value, table[Table.Symbol.Columns][key])]; + } + }); + if (entries.length === 0) { + throw new Error("No values to set"); + } + return Object.fromEntries(entries); +} +__name(mapUpdateSet, "mapUpdateSet"); +function applyMixins(baseClass, extendedClasses) { + for (const extendedClass of extendedClasses) { + for (const name of Object.getOwnPropertyNames(extendedClass.prototype)) { + if (name === "constructor") continue; + Object.defineProperty( + baseClass.prototype, + name, + Object.getOwnPropertyDescriptor(extendedClass.prototype, name) || /* @__PURE__ */ Object.create(null) + ); + } + } +} +__name(applyMixins, "applyMixins"); +function getTableColumns(table) { + return table[Table.Symbol.Columns]; +} +__name(getTableColumns, "getTableColumns"); +function getTableLikeName(table) { + return is(table, Subquery) ? table._.alias : is(table, View) ? table[ViewBaseConfig].name : is(table, SQL) ? void 0 : table[Table.Symbol.IsAlias] ? table[Table.Symbol.Name] : table[Table.Symbol.BaseName]; +} +__name(getTableLikeName, "getTableLikeName"); +function getColumnNameAndConfig(a, b) { + return { + name: typeof a === "string" && a.length > 0 ? a : "", + config: typeof a === "object" ? a : b + }; +} +__name(getColumnNameAndConfig, "getColumnNameAndConfig"); +var textDecoder = typeof TextDecoder === "undefined" ? null : new TextDecoder(); + +// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/pg-core/table.js +var InlineForeignKeys = /* @__PURE__ */ Symbol.for("drizzle:PgInlineForeignKeys"); +var EnableRLS = /* @__PURE__ */ Symbol.for("drizzle:EnableRLS"); +var PgTable = class extends Table { + static { + __name(this, "PgTable"); + } + static [entityKind] = "PgTable"; + /** @internal */ + static Symbol = Object.assign({}, Table.Symbol, { + InlineForeignKeys, + EnableRLS + }); + /**@internal */ + [InlineForeignKeys] = []; + /** @internal */ + [EnableRLS] = false; + /** @internal */ + [Table.Symbol.ExtraConfigBuilder] = void 0; + /** @internal */ + [Table.Symbol.ExtraConfigColumns] = {}; +}; + +// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/pg-core/primary-keys.js +var PrimaryKeyBuilder = class { + static { + __name(this, "PrimaryKeyBuilder"); + } + static [entityKind] = "PgPrimaryKeyBuilder"; + /** @internal */ + columns; + /** @internal */ + name; + constructor(columns, name) { + this.columns = columns; + this.name = name; + } + /** @internal */ + build(table) { + return new PrimaryKey(table, this.columns, this.name); + } +}; +var PrimaryKey = class { + static { + __name(this, "PrimaryKey"); + } + constructor(table, columns, name) { + this.table = table; + this.columns = columns; + this.name = name; + } + static [entityKind] = "PgPrimaryKey"; + columns; + name; + getName() { + return this.name ?? `${this.table[PgTable.Symbol.Name]}_${this.columns.map((column) => column.name).join("_")}_pk`; + } +}; + +// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/sql/expressions/conditions.js +init_modules_watch_stub(); +init_performance2(); +function bindIfParam(value, column) { + if (isDriverValueEncoder(column) && !isSQLWrapper(value) && !is(value, Param) && !is(value, Placeholder) && !is(value, Column) && !is(value, Table) && !is(value, View)) { + return new Param(value, column); + } + return value; +} +__name(bindIfParam, "bindIfParam"); +var eq = /* @__PURE__ */ __name((left, right) => { + return sql`${left} = ${bindIfParam(right, left)}`; +}, "eq"); +var ne = /* @__PURE__ */ __name((left, right) => { + return sql`${left} <> ${bindIfParam(right, left)}`; +}, "ne"); +function and(...unfilteredConditions) { + const conditions = unfilteredConditions.filter( + (c) => c !== void 0 + ); + if (conditions.length === 0) { + return void 0; + } + if (conditions.length === 1) { + return new SQL(conditions); + } + return new SQL([ + new StringChunk("("), + sql.join(conditions, new StringChunk(" and ")), + new StringChunk(")") + ]); +} +__name(and, "and"); +function or2(...unfilteredConditions) { + const conditions = unfilteredConditions.filter( + (c) => c !== void 0 + ); + if (conditions.length === 0) { + return void 0; + } + if (conditions.length === 1) { + return new SQL(conditions); + } + return new SQL([ + new StringChunk("("), + sql.join(conditions, new StringChunk(" or ")), + new StringChunk(")") + ]); +} +__name(or2, "or"); +function not(condition) { + return sql`not ${condition}`; +} +__name(not, "not"); +var gt = /* @__PURE__ */ __name((left, right) => { + return sql`${left} > ${bindIfParam(right, left)}`; +}, "gt"); +var gte = /* @__PURE__ */ __name((left, right) => { + return sql`${left} >= ${bindIfParam(right, left)}`; +}, "gte"); +var lt = /* @__PURE__ */ __name((left, right) => { + return sql`${left} < ${bindIfParam(right, left)}`; +}, "lt"); +var lte = /* @__PURE__ */ __name((left, right) => { + return sql`${left} <= ${bindIfParam(right, left)}`; +}, "lte"); +function inArray(column, values) { + if (Array.isArray(values)) { + if (values.length === 0) { + return sql`false`; + } + return sql`${column} in ${values.map((v) => bindIfParam(v, column))}`; + } + return sql`${column} in ${bindIfParam(values, column)}`; +} +__name(inArray, "inArray"); +function notInArray(column, values) { + if (Array.isArray(values)) { + if (values.length === 0) { + return sql`true`; + } + return sql`${column} not in ${values.map((v) => bindIfParam(v, column))}`; + } + return sql`${column} not in ${bindIfParam(values, column)}`; +} +__name(notInArray, "notInArray"); +function isNull(value) { + return sql`${value} is null`; +} +__name(isNull, "isNull"); +function isNotNull(value) { + return sql`${value} is not null`; +} +__name(isNotNull, "isNotNull"); +function exists(subquery) { + return sql`exists ${subquery}`; +} +__name(exists, "exists"); +function notExists(subquery) { + return sql`not exists ${subquery}`; +} +__name(notExists, "notExists"); +function between(column, min, max) { + return sql`${column} between ${bindIfParam(min, column)} and ${bindIfParam( + max, + column + )}`; +} +__name(between, "between"); +function notBetween(column, min, max) { + return sql`${column} not between ${bindIfParam( + min, + column + )} and ${bindIfParam(max, column)}`; +} +__name(notBetween, "notBetween"); +function like(column, value) { + return sql`${column} like ${value}`; +} +__name(like, "like"); +function notLike(column, value) { + return sql`${column} not like ${value}`; +} +__name(notLike, "notLike"); +function ilike(column, value) { + return sql`${column} ilike ${value}`; +} +__name(ilike, "ilike"); +function notIlike(column, value) { + return sql`${column} not ilike ${value}`; +} +__name(notIlike, "notIlike"); + +// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/sql/expressions/select.js +init_modules_watch_stub(); +init_performance2(); +function asc(column) { + return sql`${column} asc`; +} +__name(asc, "asc"); +function desc(column) { + return sql`${column} desc`; +} +__name(desc, "desc"); + +// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/relations.js +var Relation = class { + static { + __name(this, "Relation"); + } + constructor(sourceTable, referencedTable, relationName) { + this.sourceTable = sourceTable; + this.referencedTable = referencedTable; + this.relationName = relationName; + this.referencedTableName = referencedTable[Table.Symbol.Name]; + } + static [entityKind] = "Relation"; + referencedTableName; + fieldName; +}; +var Relations = class { + static { + __name(this, "Relations"); + } + constructor(table, config2) { + this.table = table; + this.config = config2; + } + static [entityKind] = "Relations"; +}; +var One = class _One extends Relation { + static { + __name(this, "One"); + } + constructor(sourceTable, referencedTable, config2, isNullable) { + super(sourceTable, referencedTable, config2?.relationName); + this.config = config2; + this.isNullable = isNullable; + } + static [entityKind] = "One"; + withFieldName(fieldName) { + const relation = new _One( + this.sourceTable, + this.referencedTable, + this.config, + this.isNullable + ); + relation.fieldName = fieldName; + return relation; + } +}; +var Many = class _Many extends Relation { + static { + __name(this, "Many"); + } + constructor(sourceTable, referencedTable, config2) { + super(sourceTable, referencedTable, config2?.relationName); + this.config = config2; + } + static [entityKind] = "Many"; + withFieldName(fieldName) { + const relation = new _Many( + this.sourceTable, + this.referencedTable, + this.config + ); + relation.fieldName = fieldName; + return relation; + } +}; +function getOperators() { + return { + and, + between, + eq, + exists, + gt, + gte, + ilike, + inArray, + isNull, + isNotNull, + like, + lt, + lte, + ne, + not, + notBetween, + notExists, + notLike, + notIlike, + notInArray, + or: or2, + sql + }; +} +__name(getOperators, "getOperators"); +function getOrderByOperators() { + return { + sql, + asc, + desc + }; +} +__name(getOrderByOperators, "getOrderByOperators"); +function extractTablesRelationalConfig(schema, configHelpers) { + if (Object.keys(schema).length === 1 && "default" in schema && !is(schema["default"], Table)) { + schema = schema["default"]; + } + const tableNamesMap = {}; + const relationsBuffer = {}; + const tablesConfig = {}; + for (const [key, value] of Object.entries(schema)) { + if (is(value, Table)) { + const dbName = getTableUniqueName(value); + const bufferedRelations = relationsBuffer[dbName]; + tableNamesMap[dbName] = key; + tablesConfig[key] = { + tsName: key, + dbName: value[Table.Symbol.Name], + schema: value[Table.Symbol.Schema], + columns: value[Table.Symbol.Columns], + relations: bufferedRelations?.relations ?? {}, + primaryKey: bufferedRelations?.primaryKey ?? [] + }; + for (const column of Object.values( + value[Table.Symbol.Columns] + )) { + if (column.primary) { + tablesConfig[key].primaryKey.push(column); + } + } + const extraConfig = value[Table.Symbol.ExtraConfigBuilder]?.(value[Table.Symbol.ExtraConfigColumns]); + if (extraConfig) { + for (const configEntry of Object.values(extraConfig)) { + if (is(configEntry, PrimaryKeyBuilder)) { + tablesConfig[key].primaryKey.push(...configEntry.columns); + } + } + } + } else if (is(value, Relations)) { + const dbName = getTableUniqueName(value.table); + const tableName = tableNamesMap[dbName]; + const relations2 = value.config( + configHelpers(value.table) + ); + let primaryKey; + for (const [relationName, relation] of Object.entries(relations2)) { + if (tableName) { + const tableConfig = tablesConfig[tableName]; + tableConfig.relations[relationName] = relation; + if (primaryKey) { + tableConfig.primaryKey.push(...primaryKey); + } + } else { + if (!(dbName in relationsBuffer)) { + relationsBuffer[dbName] = { + relations: {}, + primaryKey + }; + } + relationsBuffer[dbName].relations[relationName] = relation; + } + } + } + } + return { tables: tablesConfig, tableNamesMap }; +} +__name(extractTablesRelationalConfig, "extractTablesRelationalConfig"); +function relations(table, relations2) { + return new Relations( + table, + (helpers) => Object.fromEntries( + Object.entries(relations2(helpers)).map(([key, value]) => [ + key, + value.withFieldName(key) + ]) + ) + ); +} +__name(relations, "relations"); +function createOne(sourceTable) { + return /* @__PURE__ */ __name(function one(table, config2) { + return new One( + sourceTable, + table, + config2, + config2?.fields.reduce((res, f) => res && f.notNull, true) ?? false + ); + }, "one"); +} +__name(createOne, "createOne"); +function createMany(sourceTable) { + return /* @__PURE__ */ __name(function many(referencedTable, config2) { + return new Many(sourceTable, referencedTable, config2); + }, "many"); +} +__name(createMany, "createMany"); +function normalizeRelation(schema, tableNamesMap, relation) { + if (is(relation, One) && relation.config) { + return { + fields: relation.config.fields, + references: relation.config.references + }; + } + const referencedTableTsName = tableNamesMap[getTableUniqueName(relation.referencedTable)]; + if (!referencedTableTsName) { + throw new Error( + `Table "${relation.referencedTable[Table.Symbol.Name]}" not found in schema` + ); + } + const referencedTableConfig = schema[referencedTableTsName]; + if (!referencedTableConfig) { + throw new Error(`Table "${referencedTableTsName}" not found in schema`); + } + const sourceTable = relation.sourceTable; + const sourceTableTsName = tableNamesMap[getTableUniqueName(sourceTable)]; + if (!sourceTableTsName) { + throw new Error( + `Table "${sourceTable[Table.Symbol.Name]}" not found in schema` + ); + } + const reverseRelations = []; + for (const referencedTableRelation of Object.values( + referencedTableConfig.relations + )) { + if (relation.relationName && relation !== referencedTableRelation && referencedTableRelation.relationName === relation.relationName || !relation.relationName && referencedTableRelation.referencedTable === relation.sourceTable) { + reverseRelations.push(referencedTableRelation); + } + } + if (reverseRelations.length > 1) { + throw relation.relationName ? new Error( + `There are multiple relations with name "${relation.relationName}" in table "${referencedTableTsName}"` + ) : new Error( + `There are multiple relations between "${referencedTableTsName}" and "${relation.sourceTable[Table.Symbol.Name]}". Please specify relation name` + ); + } + if (reverseRelations[0] && is(reverseRelations[0], One) && reverseRelations[0].config) { + return { + fields: reverseRelations[0].config.references, + references: reverseRelations[0].config.fields + }; + } + throw new Error( + `There is not enough information to infer relation "${sourceTableTsName}.${relation.fieldName}"` + ); +} +__name(normalizeRelation, "normalizeRelation"); +function createTableRelationsHelpers(sourceTable) { + return { + one: createOne(sourceTable), + many: createMany(sourceTable) + }; +} +__name(createTableRelationsHelpers, "createTableRelationsHelpers"); +function mapRelationalRow(tablesConfig, tableConfig, row, buildQueryResultSelection, mapColumnValue = (value) => value) { + const result = {}; + for (const [ + selectionItemIndex, + selectionItem + ] of buildQueryResultSelection.entries()) { + if (selectionItem.isJson) { + const relation = tableConfig.relations[selectionItem.tsKey]; + const rawSubRows = row[selectionItemIndex]; + const subRows = typeof rawSubRows === "string" ? JSON.parse(rawSubRows) : rawSubRows; + result[selectionItem.tsKey] = is(relation, One) ? subRows && mapRelationalRow( + tablesConfig, + tablesConfig[selectionItem.relationTableTsKey], + subRows, + selectionItem.selection, + mapColumnValue + ) : subRows.map( + (subRow) => mapRelationalRow( + tablesConfig, + tablesConfig[selectionItem.relationTableTsKey], + subRow, + selectionItem.selection, + mapColumnValue + ) + ); + } else { + const value = mapColumnValue(row[selectionItemIndex]); + const field = selectionItem.field; + let decoder; + if (is(field, Column)) { + decoder = field; + } else if (is(field, SQL)) { + decoder = field.decoder; + } else { + decoder = field.sql.decoder; + } + result[selectionItem.tsKey] = value === null ? null : decoder.mapFromDriverValue(value); + } + } + return result; +} +__name(mapRelationalRow, "mapRelationalRow"); + +// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/sqlite-core/db.js +init_modules_watch_stub(); +init_performance2(); + +// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/selection-proxy.js +init_modules_watch_stub(); +init_performance2(); + +// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/alias.js +init_modules_watch_stub(); +init_performance2(); +var ColumnAliasProxyHandler = class { + static { + __name(this, "ColumnAliasProxyHandler"); + } + constructor(table) { + this.table = table; + } + static [entityKind] = "ColumnAliasProxyHandler"; + get(columnObj, prop) { + if (prop === "table") { + return this.table; + } + return columnObj[prop]; + } +}; +var TableAliasProxyHandler = class { + static { + __name(this, "TableAliasProxyHandler"); + } + constructor(alias, replaceOriginalName) { + this.alias = alias; + this.replaceOriginalName = replaceOriginalName; + } + static [entityKind] = "TableAliasProxyHandler"; + get(target, prop) { + if (prop === Table.Symbol.IsAlias) { + return true; + } + if (prop === Table.Symbol.Name) { + return this.alias; + } + if (this.replaceOriginalName && prop === Table.Symbol.OriginalName) { + return this.alias; + } + if (prop === ViewBaseConfig) { + return { + ...target[ViewBaseConfig], + name: this.alias, + isAlias: true + }; + } + if (prop === Table.Symbol.Columns) { + const columns = target[Table.Symbol.Columns]; + if (!columns) { + return columns; + } + const proxiedColumns = {}; + Object.keys(columns).map((key) => { + proxiedColumns[key] = new Proxy( + columns[key], + new ColumnAliasProxyHandler(new Proxy(target, this)) + ); + }); + return proxiedColumns; + } + const value = target[prop]; + if (is(value, Column)) { + return new Proxy(value, new ColumnAliasProxyHandler(new Proxy(target, this))); + } + return value; + } +}; +var RelationTableAliasProxyHandler = class { + static { + __name(this, "RelationTableAliasProxyHandler"); + } + constructor(alias) { + this.alias = alias; + } + static [entityKind] = "RelationTableAliasProxyHandler"; + get(target, prop) { + if (prop === "sourceTable") { + return aliasedTable(target.sourceTable, this.alias); + } + return target[prop]; + } +}; +function aliasedTable(table, tableAlias) { + return new Proxy(table, new TableAliasProxyHandler(tableAlias, false)); +} +__name(aliasedTable, "aliasedTable"); +function aliasedTableColumn(column, tableAlias) { + return new Proxy( + column, + new ColumnAliasProxyHandler(new Proxy(column.table, new TableAliasProxyHandler(tableAlias, false))) + ); +} +__name(aliasedTableColumn, "aliasedTableColumn"); +function mapColumnsInAliasedSQLToAlias(query, alias) { + return new SQL.Aliased(mapColumnsInSQLToAlias(query.sql, alias), query.fieldAlias); +} +__name(mapColumnsInAliasedSQLToAlias, "mapColumnsInAliasedSQLToAlias"); +function mapColumnsInSQLToAlias(query, alias) { + return sql.join(query.queryChunks.map((c) => { + if (is(c, Column)) { + return aliasedTableColumn(c, alias); + } + if (is(c, SQL)) { + return mapColumnsInSQLToAlias(c, alias); + } + if (is(c, SQL.Aliased)) { + return mapColumnsInAliasedSQLToAlias(c, alias); + } + return c; + })); +} +__name(mapColumnsInSQLToAlias, "mapColumnsInSQLToAlias"); + +// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/selection-proxy.js +var SelectionProxyHandler = class _SelectionProxyHandler { + static { + __name(this, "SelectionProxyHandler"); + } + static [entityKind] = "SelectionProxyHandler"; + config; + constructor(config2) { + this.config = { ...config2 }; + } + get(subquery, prop) { + if (prop === "_") { + return { + ...subquery["_"], + selectedFields: new Proxy( + subquery._.selectedFields, + this + ) + }; + } + if (prop === ViewBaseConfig) { + return { + ...subquery[ViewBaseConfig], + selectedFields: new Proxy( + subquery[ViewBaseConfig].selectedFields, + this + ) + }; + } + if (typeof prop === "symbol") { + return subquery[prop]; + } + const columns = is(subquery, Subquery) ? subquery._.selectedFields : is(subquery, View) ? subquery[ViewBaseConfig].selectedFields : subquery; + const value = columns[prop]; + if (is(value, SQL.Aliased)) { + if (this.config.sqlAliasedBehavior === "sql" && !value.isSelectionField) { + return value.sql; + } + const newValue = value.clone(); + newValue.isSelectionField = true; + return newValue; + } + if (is(value, SQL)) { + if (this.config.sqlBehavior === "sql") { + return value; + } + throw new Error( + `You tried to reference "${prop}" field from a subquery, which is a raw SQL field, but it doesn't have an alias declared. Please add an alias to the field using ".as('alias')" method.` + ); + } + if (is(value, Column)) { + if (this.config.alias) { + return new Proxy( + value, + new ColumnAliasProxyHandler( + new Proxy( + value.table, + new TableAliasProxyHandler(this.config.alias, this.config.replaceOriginalName ?? false) + ) + ) + ); + } + return value; + } + if (typeof value !== "object" || value === null) { + return value; + } + return new Proxy(value, new _SelectionProxyHandler(this.config)); + } +}; + +// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/sqlite-core/query-builders/delete.js +init_modules_watch_stub(); +init_performance2(); + +// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/query-promise.js +init_modules_watch_stub(); +init_performance2(); +var QueryPromise = class { + static { + __name(this, "QueryPromise"); + } + static [entityKind] = "QueryPromise"; + [Symbol.toStringTag] = "QueryPromise"; + catch(onRejected) { + return this.then(void 0, onRejected); + } + finally(onFinally) { + return this.then( + (value) => { + onFinally?.(); + return value; + }, + (reason) => { + onFinally?.(); + throw reason; + } + ); + } + then(onFulfilled, onRejected) { + return this.execute().then(onFulfilled, onRejected); + } +}; + +// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/sqlite-core/table.js +init_modules_watch_stub(); +init_performance2(); + +// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/sqlite-core/columns/all.js +init_modules_watch_stub(); +init_performance2(); + +// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/sqlite-core/columns/blob.js +init_modules_watch_stub(); +init_performance2(); + +// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/sqlite-core/columns/common.js +init_modules_watch_stub(); +init_performance2(); + +// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/sqlite-core/foreign-keys.js +init_modules_watch_stub(); +init_performance2(); +var ForeignKeyBuilder2 = class { + static { + __name(this, "ForeignKeyBuilder"); + } + static [entityKind] = "SQLiteForeignKeyBuilder"; + /** @internal */ + reference; + /** @internal */ + _onUpdate; + /** @internal */ + _onDelete; + constructor(config2, actions) { + this.reference = () => { + const { name, columns, foreignColumns } = config2(); + return { name, columns, foreignTable: foreignColumns[0].table, foreignColumns }; + }; + if (actions) { + this._onUpdate = actions.onUpdate; + this._onDelete = actions.onDelete; + } + } + onUpdate(action) { + this._onUpdate = action; + return this; + } + onDelete(action) { + this._onDelete = action; + return this; + } + /** @internal */ + build(table) { + return new ForeignKey2(table, this); + } +}; +var ForeignKey2 = class { + static { + __name(this, "ForeignKey"); + } + constructor(table, builder) { + this.table = table; + this.reference = builder.reference; + this.onUpdate = builder._onUpdate; + this.onDelete = builder._onDelete; + } + static [entityKind] = "SQLiteForeignKey"; + reference; + onUpdate; + onDelete; + getName() { + const { name, columns, foreignColumns } = this.reference(); + const columnNames = columns.map((column) => column.name); + const foreignColumnNames = foreignColumns.map((column) => column.name); + const chunks = [ + this.table[TableName], + ...columnNames, + foreignColumns[0].table[TableName], + ...foreignColumnNames + ]; + return name ?? `${chunks.join("_")}_fk`; + } +}; + +// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/sqlite-core/unique-constraint.js +init_modules_watch_stub(); +init_performance2(); +function uniqueKeyName2(table, columns) { + return `${table[TableName]}_${columns.join("_")}_unique`; +} +__name(uniqueKeyName2, "uniqueKeyName"); +var UniqueConstraintBuilder2 = class { + static { + __name(this, "UniqueConstraintBuilder"); + } + constructor(columns, name) { + this.name = name; + this.columns = columns; + } + static [entityKind] = "SQLiteUniqueConstraintBuilder"; + /** @internal */ + columns; + /** @internal */ + build(table) { + return new UniqueConstraint2(table, this.columns, this.name); + } +}; +var UniqueOnConstraintBuilder2 = class { + static { + __name(this, "UniqueOnConstraintBuilder"); + } + static [entityKind] = "SQLiteUniqueOnConstraintBuilder"; + /** @internal */ + name; + constructor(name) { + this.name = name; + } + on(...columns) { + return new UniqueConstraintBuilder2(columns, this.name); + } +}; +var UniqueConstraint2 = class { + static { + __name(this, "UniqueConstraint"); + } + constructor(table, columns, name) { + this.table = table; + this.columns = columns; + this.name = name ?? uniqueKeyName2(this.table, this.columns.map((column) => column.name)); + } + static [entityKind] = "SQLiteUniqueConstraint"; + columns; + name; + getName() { + return this.name; + } +}; + +// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/sqlite-core/columns/common.js +var SQLiteColumnBuilder = class extends ColumnBuilder { + static { + __name(this, "SQLiteColumnBuilder"); + } + static [entityKind] = "SQLiteColumnBuilder"; + foreignKeyConfigs = []; + references(ref, actions = {}) { + this.foreignKeyConfigs.push({ ref, actions }); + return this; + } + unique(name) { + this.config.isUnique = true; + this.config.uniqueName = name; + return this; + } + generatedAlwaysAs(as, config2) { + this.config.generated = { + as, + type: "always", + mode: config2?.mode ?? "virtual" + }; + return this; + } + /** @internal */ + buildForeignKeys(column, table) { + return this.foreignKeyConfigs.map(({ ref, actions }) => { + return ((ref2, actions2) => { + const builder = new ForeignKeyBuilder2(() => { + const foreignColumn = ref2(); + return { columns: [column], foreignColumns: [foreignColumn] }; + }); + if (actions2.onUpdate) { + builder.onUpdate(actions2.onUpdate); + } + if (actions2.onDelete) { + builder.onDelete(actions2.onDelete); + } + return builder.build(table); + })(ref, actions); + }); + } +}; +var SQLiteColumn = class extends Column { + static { + __name(this, "SQLiteColumn"); + } + constructor(table, config2) { + if (!config2.uniqueName) { + config2.uniqueName = uniqueKeyName2(table, [config2.name]); + } + super(table, config2); + this.table = table; + } + static [entityKind] = "SQLiteColumn"; +}; + +// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/sqlite-core/columns/blob.js +var SQLiteBigIntBuilder = class extends SQLiteColumnBuilder { + static { + __name(this, "SQLiteBigIntBuilder"); + } + static [entityKind] = "SQLiteBigIntBuilder"; + constructor(name) { + super(name, "bigint", "SQLiteBigInt"); + } + /** @internal */ + build(table) { + return new SQLiteBigInt(table, this.config); + } +}; +var SQLiteBigInt = class extends SQLiteColumn { + static { + __name(this, "SQLiteBigInt"); + } + static [entityKind] = "SQLiteBigInt"; + getSQLType() { + return "blob"; + } + mapFromDriverValue(value) { + if (typeof Buffer !== "undefined" && Buffer.from) { + const buf = Buffer.isBuffer(value) ? value : value instanceof ArrayBuffer ? Buffer.from(value) : value.buffer ? Buffer.from(value.buffer, value.byteOffset, value.byteLength) : Buffer.from(value); + return BigInt(buf.toString("utf8")); + } + return BigInt(textDecoder.decode(value)); + } + mapToDriverValue(value) { + return Buffer.from(value.toString()); + } +}; +var SQLiteBlobJsonBuilder = class extends SQLiteColumnBuilder { + static { + __name(this, "SQLiteBlobJsonBuilder"); + } + static [entityKind] = "SQLiteBlobJsonBuilder"; + constructor(name) { + super(name, "json", "SQLiteBlobJson"); + } + /** @internal */ + build(table) { + return new SQLiteBlobJson( + table, + this.config + ); + } +}; +var SQLiteBlobJson = class extends SQLiteColumn { + static { + __name(this, "SQLiteBlobJson"); + } + static [entityKind] = "SQLiteBlobJson"; + getSQLType() { + return "blob"; + } + mapFromDriverValue(value) { + if (typeof Buffer !== "undefined" && Buffer.from) { + const buf = Buffer.isBuffer(value) ? value : value instanceof ArrayBuffer ? Buffer.from(value) : value.buffer ? Buffer.from(value.buffer, value.byteOffset, value.byteLength) : Buffer.from(value); + return JSON.parse(buf.toString("utf8")); + } + return JSON.parse(textDecoder.decode(value)); + } + mapToDriverValue(value) { + return Buffer.from(JSON.stringify(value)); + } +}; +var SQLiteBlobBufferBuilder = class extends SQLiteColumnBuilder { + static { + __name(this, "SQLiteBlobBufferBuilder"); + } + static [entityKind] = "SQLiteBlobBufferBuilder"; + constructor(name) { + super(name, "buffer", "SQLiteBlobBuffer"); + } + /** @internal */ + build(table) { + return new SQLiteBlobBuffer(table, this.config); + } +}; +var SQLiteBlobBuffer = class extends SQLiteColumn { + static { + __name(this, "SQLiteBlobBuffer"); + } + static [entityKind] = "SQLiteBlobBuffer"; + mapFromDriverValue(value) { + if (Buffer.isBuffer(value)) { + return value; + } + return Buffer.from(value); + } + getSQLType() { + return "blob"; + } +}; +function blob(a, b) { + const { name, config: config2 } = getColumnNameAndConfig(a, b); + if (config2?.mode === "json") { + return new SQLiteBlobJsonBuilder(name); + } + if (config2?.mode === "bigint") { + return new SQLiteBigIntBuilder(name); + } + return new SQLiteBlobBufferBuilder(name); +} +__name(blob, "blob"); + +// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/sqlite-core/columns/custom.js +init_modules_watch_stub(); +init_performance2(); +var SQLiteCustomColumnBuilder = class extends SQLiteColumnBuilder { + static { + __name(this, "SQLiteCustomColumnBuilder"); + } + static [entityKind] = "SQLiteCustomColumnBuilder"; + constructor(name, fieldConfig, customTypeParams) { + super(name, "custom", "SQLiteCustomColumn"); + this.config.fieldConfig = fieldConfig; + this.config.customTypeParams = customTypeParams; + } + /** @internal */ + build(table) { + return new SQLiteCustomColumn( + table, + this.config + ); + } +}; +var SQLiteCustomColumn = class extends SQLiteColumn { + static { + __name(this, "SQLiteCustomColumn"); + } + static [entityKind] = "SQLiteCustomColumn"; + sqlName; + mapTo; + mapFrom; + constructor(table, config2) { + super(table, config2); + this.sqlName = config2.customTypeParams.dataType(config2.fieldConfig); + this.mapTo = config2.customTypeParams.toDriver; + this.mapFrom = config2.customTypeParams.fromDriver; + } + getSQLType() { + return this.sqlName; + } + mapFromDriverValue(value) { + return typeof this.mapFrom === "function" ? this.mapFrom(value) : value; + } + mapToDriverValue(value) { + return typeof this.mapTo === "function" ? this.mapTo(value) : value; + } +}; +function customType(customTypeParams) { + return (a, b) => { + const { name, config: config2 } = getColumnNameAndConfig(a, b); + return new SQLiteCustomColumnBuilder( + name, + config2, + customTypeParams + ); + }; +} +__name(customType, "customType"); + +// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/sqlite-core/columns/integer.js +init_modules_watch_stub(); +init_performance2(); +var SQLiteBaseIntegerBuilder = class extends SQLiteColumnBuilder { + static { + __name(this, "SQLiteBaseIntegerBuilder"); + } + static [entityKind] = "SQLiteBaseIntegerBuilder"; + constructor(name, dataType, columnType) { + super(name, dataType, columnType); + this.config.autoIncrement = false; + } + primaryKey(config2) { + if (config2?.autoIncrement) { + this.config.autoIncrement = true; + } + this.config.hasDefault = true; + return super.primaryKey(); + } +}; +var SQLiteBaseInteger = class extends SQLiteColumn { + static { + __name(this, "SQLiteBaseInteger"); + } + static [entityKind] = "SQLiteBaseInteger"; + autoIncrement = this.config.autoIncrement; + getSQLType() { + return "integer"; + } +}; +var SQLiteIntegerBuilder = class extends SQLiteBaseIntegerBuilder { + static { + __name(this, "SQLiteIntegerBuilder"); + } + static [entityKind] = "SQLiteIntegerBuilder"; + constructor(name) { + super(name, "number", "SQLiteInteger"); + } + build(table) { + return new SQLiteInteger( + table, + this.config + ); + } +}; +var SQLiteInteger = class extends SQLiteBaseInteger { + static { + __name(this, "SQLiteInteger"); + } + static [entityKind] = "SQLiteInteger"; +}; +var SQLiteTimestampBuilder = class extends SQLiteBaseIntegerBuilder { + static { + __name(this, "SQLiteTimestampBuilder"); + } + static [entityKind] = "SQLiteTimestampBuilder"; + constructor(name, mode) { + super(name, "date", "SQLiteTimestamp"); + this.config.mode = mode; + } + /** + * @deprecated Use `default()` with your own expression instead. + * + * Adds `DEFAULT (cast((julianday('now') - 2440587.5)*86400000 as integer))` to the column, which is the current epoch timestamp in milliseconds. + */ + defaultNow() { + return this.default(sql`(cast((julianday('now') - 2440587.5)*86400000 as integer))`); + } + build(table) { + return new SQLiteTimestamp( + table, + this.config + ); + } +}; +var SQLiteTimestamp = class extends SQLiteBaseInteger { + static { + __name(this, "SQLiteTimestamp"); + } + static [entityKind] = "SQLiteTimestamp"; + mode = this.config.mode; + mapFromDriverValue(value) { + if (this.config.mode === "timestamp") { + return new Date(value * 1e3); + } + return new Date(value); + } + mapToDriverValue(value) { + const unix = value.getTime(); + if (this.config.mode === "timestamp") { + return Math.floor(unix / 1e3); + } + return unix; + } +}; +var SQLiteBooleanBuilder = class extends SQLiteBaseIntegerBuilder { + static { + __name(this, "SQLiteBooleanBuilder"); + } + static [entityKind] = "SQLiteBooleanBuilder"; + constructor(name, mode) { + super(name, "boolean", "SQLiteBoolean"); + this.config.mode = mode; + } + build(table) { + return new SQLiteBoolean( + table, + this.config + ); + } +}; +var SQLiteBoolean = class extends SQLiteBaseInteger { + static { + __name(this, "SQLiteBoolean"); + } + static [entityKind] = "SQLiteBoolean"; + mode = this.config.mode; + mapFromDriverValue(value) { + return Number(value) === 1; + } + mapToDriverValue(value) { + return value ? 1 : 0; + } +}; +function integer(a, b) { + const { name, config: config2 } = getColumnNameAndConfig(a, b); + if (config2?.mode === "timestamp" || config2?.mode === "timestamp_ms") { + return new SQLiteTimestampBuilder(name, config2.mode); + } + if (config2?.mode === "boolean") { + return new SQLiteBooleanBuilder(name, config2.mode); + } + return new SQLiteIntegerBuilder(name); +} +__name(integer, "integer"); + +// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/sqlite-core/columns/numeric.js +init_modules_watch_stub(); +init_performance2(); +var SQLiteNumericBuilder = class extends SQLiteColumnBuilder { + static { + __name(this, "SQLiteNumericBuilder"); + } + static [entityKind] = "SQLiteNumericBuilder"; + constructor(name) { + super(name, "string", "SQLiteNumeric"); + } + /** @internal */ + build(table) { + return new SQLiteNumeric( + table, + this.config + ); + } +}; +var SQLiteNumeric = class extends SQLiteColumn { + static { + __name(this, "SQLiteNumeric"); + } + static [entityKind] = "SQLiteNumeric"; + mapFromDriverValue(value) { + if (typeof value === "string") return value; + return String(value); + } + getSQLType() { + return "numeric"; + } +}; +var SQLiteNumericNumberBuilder = class extends SQLiteColumnBuilder { + static { + __name(this, "SQLiteNumericNumberBuilder"); + } + static [entityKind] = "SQLiteNumericNumberBuilder"; + constructor(name) { + super(name, "number", "SQLiteNumericNumber"); + } + /** @internal */ + build(table) { + return new SQLiteNumericNumber( + table, + this.config + ); + } +}; +var SQLiteNumericNumber = class extends SQLiteColumn { + static { + __name(this, "SQLiteNumericNumber"); + } + static [entityKind] = "SQLiteNumericNumber"; + mapFromDriverValue(value) { + if (typeof value === "number") return value; + return Number(value); + } + mapToDriverValue = String; + getSQLType() { + return "numeric"; + } +}; +var SQLiteNumericBigIntBuilder = class extends SQLiteColumnBuilder { + static { + __name(this, "SQLiteNumericBigIntBuilder"); + } + static [entityKind] = "SQLiteNumericBigIntBuilder"; + constructor(name) { + super(name, "bigint", "SQLiteNumericBigInt"); + } + /** @internal */ + build(table) { + return new SQLiteNumericBigInt( + table, + this.config + ); + } +}; +var SQLiteNumericBigInt = class extends SQLiteColumn { + static { + __name(this, "SQLiteNumericBigInt"); + } + static [entityKind] = "SQLiteNumericBigInt"; + mapFromDriverValue = BigInt; + mapToDriverValue = String; + getSQLType() { + return "numeric"; + } +}; +function numeric(a, b) { + const { name, config: config2 } = getColumnNameAndConfig(a, b); + const mode = config2?.mode; + return mode === "number" ? new SQLiteNumericNumberBuilder(name) : mode === "bigint" ? new SQLiteNumericBigIntBuilder(name) : new SQLiteNumericBuilder(name); +} +__name(numeric, "numeric"); + +// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/sqlite-core/columns/real.js +init_modules_watch_stub(); +init_performance2(); +var SQLiteRealBuilder = class extends SQLiteColumnBuilder { + static { + __name(this, "SQLiteRealBuilder"); + } + static [entityKind] = "SQLiteRealBuilder"; + constructor(name) { + super(name, "number", "SQLiteReal"); + } + /** @internal */ + build(table) { + return new SQLiteReal(table, this.config); + } +}; +var SQLiteReal = class extends SQLiteColumn { + static { + __name(this, "SQLiteReal"); + } + static [entityKind] = "SQLiteReal"; + getSQLType() { + return "real"; + } +}; +function real(name) { + return new SQLiteRealBuilder(name ?? ""); +} +__name(real, "real"); + +// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/sqlite-core/columns/text.js +init_modules_watch_stub(); +init_performance2(); +var SQLiteTextBuilder = class extends SQLiteColumnBuilder { + static { + __name(this, "SQLiteTextBuilder"); + } + static [entityKind] = "SQLiteTextBuilder"; + constructor(name, config2) { + super(name, "string", "SQLiteText"); + this.config.enumValues = config2.enum; + this.config.length = config2.length; + } + /** @internal */ + build(table) { + return new SQLiteText( + table, + this.config + ); + } +}; +var SQLiteText = class extends SQLiteColumn { + static { + __name(this, "SQLiteText"); + } + static [entityKind] = "SQLiteText"; + enumValues = this.config.enumValues; + length = this.config.length; + constructor(table, config2) { + super(table, config2); + } + getSQLType() { + return `text${this.config.length ? `(${this.config.length})` : ""}`; + } +}; +var SQLiteTextJsonBuilder = class extends SQLiteColumnBuilder { + static { + __name(this, "SQLiteTextJsonBuilder"); + } + static [entityKind] = "SQLiteTextJsonBuilder"; + constructor(name) { + super(name, "json", "SQLiteTextJson"); + } + /** @internal */ + build(table) { + return new SQLiteTextJson( + table, + this.config + ); + } +}; +var SQLiteTextJson = class extends SQLiteColumn { + static { + __name(this, "SQLiteTextJson"); + } + static [entityKind] = "SQLiteTextJson"; + getSQLType() { + return "text"; + } + mapFromDriverValue(value) { + return JSON.parse(value); + } + mapToDriverValue(value) { + return JSON.stringify(value); + } +}; +function text(a, b = {}) { + const { name, config: config2 } = getColumnNameAndConfig(a, b); + if (config2.mode === "json") { + return new SQLiteTextJsonBuilder(name); + } + return new SQLiteTextBuilder(name, config2); +} +__name(text, "text"); + +// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/sqlite-core/columns/all.js +function getSQLiteColumnBuilders() { + return { + blob, + customType, + integer, + numeric, + real, + text + }; +} +__name(getSQLiteColumnBuilders, "getSQLiteColumnBuilders"); + +// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/sqlite-core/table.js +var InlineForeignKeys2 = /* @__PURE__ */ Symbol.for("drizzle:SQLiteInlineForeignKeys"); +var SQLiteTable = class extends Table { + static { + __name(this, "SQLiteTable"); + } + static [entityKind] = "SQLiteTable"; + /** @internal */ + static Symbol = Object.assign({}, Table.Symbol, { + InlineForeignKeys: InlineForeignKeys2 + }); + /** @internal */ + [Table.Symbol.Columns]; + /** @internal */ + [InlineForeignKeys2] = []; + /** @internal */ + [Table.Symbol.ExtraConfigBuilder] = void 0; +}; +function sqliteTableBase(name, columns, extraConfig, schema, baseName = name) { + const rawTable = new SQLiteTable(name, schema, baseName); + const parsedColumns = typeof columns === "function" ? columns(getSQLiteColumnBuilders()) : columns; + const builtColumns = Object.fromEntries( + Object.entries(parsedColumns).map(([name2, colBuilderBase]) => { + const colBuilder = colBuilderBase; + colBuilder.setName(name2); + const column = colBuilder.build(rawTable); + rawTable[InlineForeignKeys2].push(...colBuilder.buildForeignKeys(column, rawTable)); + return [name2, column]; + }) + ); + const table = Object.assign(rawTable, builtColumns); + table[Table.Symbol.Columns] = builtColumns; + table[Table.Symbol.ExtraConfigColumns] = builtColumns; + if (extraConfig) { + table[SQLiteTable.Symbol.ExtraConfigBuilder] = extraConfig; + } + return table; +} +__name(sqliteTableBase, "sqliteTableBase"); +var sqliteTable = /* @__PURE__ */ __name((name, columns, extraConfig) => { + return sqliteTableBase(name, columns, extraConfig); +}, "sqliteTable"); + +// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/sqlite-core/utils.js +init_modules_watch_stub(); +init_performance2(); +function extractUsedTable(table) { + if (is(table, SQLiteTable)) { + return [`${table[Table.Symbol.BaseName]}`]; + } + if (is(table, Subquery)) { + return table._.usedTables ?? []; + } + if (is(table, SQL)) { + return table.usedTables ?? []; + } + return []; +} +__name(extractUsedTable, "extractUsedTable"); + +// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/sqlite-core/query-builders/delete.js +var SQLiteDeleteBase = class extends QueryPromise { + static { + __name(this, "SQLiteDeleteBase"); + } + constructor(table, session2, dialect, withList) { + super(); + this.table = table; + this.session = session2; + this.dialect = dialect; + this.config = { table, withList }; + } + static [entityKind] = "SQLiteDelete"; + /** @internal */ + config; + /** + * Adds a `where` clause to the query. + * + * Calling this method will delete only those rows that fulfill a specified condition. + * + * See docs: {@link https://orm.drizzle.team/docs/delete} + * + * @param where the `where` clause. + * + * @example + * You can use conditional operators and `sql function` to filter the rows to be deleted. + * + * ```ts + * // Delete all cars with green color + * db.delete(cars).where(eq(cars.color, 'green')); + * // or + * db.delete(cars).where(sql`${cars.color} = 'green'`) + * ``` + * + * You can logically combine conditional operators with `and()` and `or()` operators: + * + * ```ts + * // Delete all BMW cars with a green color + * db.delete(cars).where(and(eq(cars.color, 'green'), eq(cars.brand, 'BMW'))); + * + * // Delete all cars with the green or blue color + * db.delete(cars).where(or(eq(cars.color, 'green'), eq(cars.color, 'blue'))); + * ``` + */ + where(where) { + this.config.where = where; + return this; + } + orderBy(...columns) { + if (typeof columns[0] === "function") { + const orderBy = columns[0]( + new Proxy( + this.config.table[Table.Symbol.Columns], + new SelectionProxyHandler({ sqlAliasedBehavior: "alias", sqlBehavior: "sql" }) + ) + ); + const orderByArray = Array.isArray(orderBy) ? orderBy : [orderBy]; + this.config.orderBy = orderByArray; + } else { + const orderByArray = columns; + this.config.orderBy = orderByArray; + } + return this; + } + limit(limit) { + this.config.limit = limit; + return this; + } + returning(fields = this.table[SQLiteTable.Symbol.Columns]) { + this.config.returning = orderSelectedFields(fields); + return this; + } + /** @internal */ + getSQL() { + return this.dialect.buildDeleteQuery(this.config); + } + toSQL() { + const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL()); + return rest; + } + /** @internal */ + _prepare(isOneTimeQuery = true) { + return this.session[isOneTimeQuery ? "prepareOneTimeQuery" : "prepareQuery"]( + this.dialect.sqlToQuery(this.getSQL()), + this.config.returning, + this.config.returning ? "all" : "run", + true, + void 0, + { + type: "delete", + tables: extractUsedTable(this.config.table) + } + ); + } + prepare() { + return this._prepare(false); + } + run = /* @__PURE__ */ __name((placeholderValues) => { + return this._prepare().run(placeholderValues); + }, "run"); + all = /* @__PURE__ */ __name((placeholderValues) => { + return this._prepare().all(placeholderValues); + }, "all"); + get = /* @__PURE__ */ __name((placeholderValues) => { + return this._prepare().get(placeholderValues); + }, "get"); + values = /* @__PURE__ */ __name((placeholderValues) => { + return this._prepare().values(placeholderValues); + }, "values"); + async execute(placeholderValues) { + return this._prepare().execute(placeholderValues); + } + $dynamic() { + return this; + } +}; + +// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/sqlite-core/query-builders/insert.js +init_modules_watch_stub(); +init_performance2(); + +// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/sqlite-core/query-builders/query-builder.js +init_modules_watch_stub(); +init_performance2(); + +// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/sqlite-core/dialect.js +init_modules_watch_stub(); +init_performance2(); + +// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/casing.js +init_modules_watch_stub(); +init_performance2(); +function toSnakeCase(input) { + const words = input.replace(/['\u2019]/g, "").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g) ?? []; + return words.map((word) => word.toLowerCase()).join("_"); +} +__name(toSnakeCase, "toSnakeCase"); +function toCamelCase(input) { + const words = input.replace(/['\u2019]/g, "").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g) ?? []; + return words.reduce((acc, word, i) => { + const formattedWord = i === 0 ? word.toLowerCase() : `${word[0].toUpperCase()}${word.slice(1)}`; + return acc + formattedWord; + }, ""); +} +__name(toCamelCase, "toCamelCase"); +function noopCase(input) { + return input; +} +__name(noopCase, "noopCase"); +var CasingCache = class { + static { + __name(this, "CasingCache"); + } + static [entityKind] = "CasingCache"; + /** @internal */ + cache = {}; + cachedTables = {}; + convert; + constructor(casing) { + this.convert = casing === "snake_case" ? toSnakeCase : casing === "camelCase" ? toCamelCase : noopCase; + } + getColumnCasing(column) { + if (!column.keyAsName) return column.name; + const schema = column.table[Table.Symbol.Schema] ?? "public"; + const tableName = column.table[Table.Symbol.OriginalName]; + const key = `${schema}.${tableName}.${column.name}`; + if (!this.cache[key]) { + this.cacheTable(column.table); + } + return this.cache[key]; + } + cacheTable(table) { + const schema = table[Table.Symbol.Schema] ?? "public"; + const tableName = table[Table.Symbol.OriginalName]; + const tableKey = `${schema}.${tableName}`; + if (!this.cachedTables[tableKey]) { + for (const column of Object.values(table[Table.Symbol.Columns])) { + const columnKey = `${tableKey}.${column.name}`; + this.cache[columnKey] = this.convert(column.name); + } + this.cachedTables[tableKey] = true; + } + } + clearCache() { + this.cache = {}; + this.cachedTables = {}; + } +}; + +// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/errors.js +init_modules_watch_stub(); +init_performance2(); +var DrizzleError = class extends Error { + static { + __name(this, "DrizzleError"); + } + static [entityKind] = "DrizzleError"; + constructor({ message, cause }) { + super(message); + this.name = "DrizzleError"; + this.cause = cause; + } +}; +var DrizzleQueryError = class _DrizzleQueryError extends Error { + static { + __name(this, "DrizzleQueryError"); + } + constructor(query, params, cause) { + super(`Failed query: ${query} +params: ${params}`); + this.query = query; + this.params = params; + this.cause = cause; + Error.captureStackTrace(this, _DrizzleQueryError); + if (cause) this.cause = cause; + } +}; +var TransactionRollbackError = class extends DrizzleError { + static { + __name(this, "TransactionRollbackError"); + } + static [entityKind] = "TransactionRollbackError"; + constructor() { + super({ message: "Rollback" }); + } +}; + +// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/sql/functions/aggregate.js +init_modules_watch_stub(); +init_performance2(); +function count(expression) { + return sql`count(${expression || sql.raw("*")})`.mapWith(Number); +} +__name(count, "count"); + +// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/sqlite-core/view-base.js +init_modules_watch_stub(); +init_performance2(); +var SQLiteViewBase = class extends View { + static { + __name(this, "SQLiteViewBase"); + } + static [entityKind] = "SQLiteViewBase"; +}; + +// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/sqlite-core/dialect.js +var SQLiteDialect = class { + static { + __name(this, "SQLiteDialect"); + } + static [entityKind] = "SQLiteDialect"; + /** @internal */ + casing; + constructor(config2) { + this.casing = new CasingCache(config2?.casing); + } + escapeName(name) { + return `"${name}"`; + } + escapeParam(_num) { + return "?"; + } + escapeString(str2) { + return `'${str2.replace(/'/g, "''")}'`; + } + buildWithCTE(queries) { + if (!queries?.length) return void 0; + const withSqlChunks = [sql`with `]; + for (const [i, w2] of queries.entries()) { + withSqlChunks.push(sql`${sql.identifier(w2._.alias)} as (${w2._.sql})`); + if (i < queries.length - 1) { + withSqlChunks.push(sql`, `); + } + } + withSqlChunks.push(sql` `); + return sql.join(withSqlChunks); + } + buildDeleteQuery({ table, where, returning, withList, limit, orderBy }) { + const withSql = this.buildWithCTE(withList); + const returningSql = returning ? sql` returning ${this.buildSelection(returning, { isSingleTable: true })}` : void 0; + const whereSql = where ? sql` where ${where}` : void 0; + const orderBySql = this.buildOrderBy(orderBy); + const limitSql = this.buildLimit(limit); + return sql`${withSql}delete from ${table}${whereSql}${returningSql}${orderBySql}${limitSql}`; + } + buildUpdateSet(table, set) { + const tableColumns = table[Table.Symbol.Columns]; + const columnNames = Object.keys(tableColumns).filter( + (colName) => set[colName] !== void 0 || tableColumns[colName]?.onUpdateFn !== void 0 + ); + const setSize = columnNames.length; + return sql.join(columnNames.flatMap((colName, i) => { + const col = tableColumns[colName]; + const onUpdateFnResult = col.onUpdateFn?.(); + const value = set[colName] ?? (is(onUpdateFnResult, SQL) ? onUpdateFnResult : sql.param(onUpdateFnResult, col)); + const res = sql`${sql.identifier(this.casing.getColumnCasing(col))} = ${value}`; + if (i < setSize - 1) { + return [res, sql.raw(", ")]; + } + return [res]; + })); + } + buildUpdateQuery({ table, set, where, returning, withList, joins, from, limit, orderBy }) { + const withSql = this.buildWithCTE(withList); + const setSql = this.buildUpdateSet(table, set); + const fromSql = from && sql.join([sql.raw(" from "), this.buildFromTable(from)]); + const joinsSql = this.buildJoins(joins); + const returningSql = returning ? sql` returning ${this.buildSelection(returning, { isSingleTable: true })}` : void 0; + const whereSql = where ? sql` where ${where}` : void 0; + const orderBySql = this.buildOrderBy(orderBy); + const limitSql = this.buildLimit(limit); + return sql`${withSql}update ${table} set ${setSql}${fromSql}${joinsSql}${whereSql}${returningSql}${orderBySql}${limitSql}`; + } + /** + * Builds selection SQL with provided fields/expressions + * + * Examples: + * + * `select from` + * + * `insert ... returning ` + * + * If `isSingleTable` is true, then columns won't be prefixed with table name + */ + buildSelection(fields, { isSingleTable = false } = {}) { + const columnsLen = fields.length; + const chunks = fields.flatMap(({ field }, i) => { + const chunk = []; + if (is(field, SQL.Aliased) && field.isSelectionField) { + chunk.push(sql.identifier(field.fieldAlias)); + } else if (is(field, SQL.Aliased) || is(field, SQL)) { + const query = is(field, SQL.Aliased) ? field.sql : field; + if (isSingleTable) { + chunk.push( + new SQL( + query.queryChunks.map((c) => { + if (is(c, Column)) { + return sql.identifier(this.casing.getColumnCasing(c)); + } + return c; + }) + ) + ); + } else { + chunk.push(query); + } + if (is(field, SQL.Aliased)) { + chunk.push(sql` as ${sql.identifier(field.fieldAlias)}`); + } + } else if (is(field, Column)) { + const tableName = field.table[Table.Symbol.Name]; + if (field.columnType === "SQLiteNumericBigInt") { + if (isSingleTable) { + chunk.push(sql`cast(${sql.identifier(this.casing.getColumnCasing(field))} as text)`); + } else { + chunk.push( + sql`cast(${sql.identifier(tableName)}.${sql.identifier(this.casing.getColumnCasing(field))} as text)` + ); + } + } else { + if (isSingleTable) { + chunk.push(sql.identifier(this.casing.getColumnCasing(field))); + } else { + chunk.push(sql`${sql.identifier(tableName)}.${sql.identifier(this.casing.getColumnCasing(field))}`); + } + } + } else if (is(field, Subquery)) { + const entries = Object.entries(field._.selectedFields); + if (entries.length === 1) { + const entry = entries[0][1]; + const fieldDecoder = is(entry, SQL) ? entry.decoder : is(entry, Column) ? { mapFromDriverValue: /* @__PURE__ */ __name((v) => entry.mapFromDriverValue(v), "mapFromDriverValue") } : entry.sql.decoder; + if (fieldDecoder) field._.sql.decoder = fieldDecoder; + } + chunk.push(field); + } + if (i < columnsLen - 1) { + chunk.push(sql`, `); + } + return chunk; + }); + return sql.join(chunks); + } + buildJoins(joins) { + if (!joins || joins.length === 0) { + return void 0; + } + const joinsArray = []; + if (joins) { + for (const [index, joinMeta] of joins.entries()) { + if (index === 0) { + joinsArray.push(sql` `); + } + const table = joinMeta.table; + const onSql = joinMeta.on ? sql` on ${joinMeta.on}` : void 0; + if (is(table, SQLiteTable)) { + const tableName = table[SQLiteTable.Symbol.Name]; + const tableSchema = table[SQLiteTable.Symbol.Schema]; + const origTableName = table[SQLiteTable.Symbol.OriginalName]; + const alias = tableName === origTableName ? void 0 : joinMeta.alias; + joinsArray.push( + sql`${sql.raw(joinMeta.joinType)} join ${tableSchema ? sql`${sql.identifier(tableSchema)}.` : void 0}${sql.identifier(origTableName)}${alias && sql` ${sql.identifier(alias)}`}${onSql}` + ); + } else { + joinsArray.push( + sql`${sql.raw(joinMeta.joinType)} join ${table}${onSql}` + ); + } + if (index < joins.length - 1) { + joinsArray.push(sql` `); + } + } + } + return sql.join(joinsArray); + } + buildLimit(limit) { + return typeof limit === "object" || typeof limit === "number" && limit >= 0 ? sql` limit ${limit}` : void 0; + } + buildOrderBy(orderBy) { + const orderByList = []; + if (orderBy) { + for (const [index, orderByValue] of orderBy.entries()) { + orderByList.push(orderByValue); + if (index < orderBy.length - 1) { + orderByList.push(sql`, `); + } + } + } + return orderByList.length > 0 ? sql` order by ${sql.join(orderByList)}` : void 0; + } + buildFromTable(table) { + if (is(table, Table) && table[Table.Symbol.IsAlias]) { + return sql`${sql`${sql.identifier(table[Table.Symbol.Schema] ?? "")}.`.if(table[Table.Symbol.Schema])}${sql.identifier(table[Table.Symbol.OriginalName])} ${sql.identifier(table[Table.Symbol.Name])}`; + } + return table; + } + buildSelectQuery({ + withList, + fields, + fieldsFlat, + where, + having, + table, + joins, + orderBy, + groupBy, + limit, + offset, + distinct, + setOperators + }) { + const fieldsList = fieldsFlat ?? orderSelectedFields(fields); + for (const f of fieldsList) { + if (is(f.field, Column) && getTableName(f.field.table) !== (is(table, Subquery) ? table._.alias : is(table, SQLiteViewBase) ? table[ViewBaseConfig].name : is(table, SQL) ? void 0 : getTableName(table)) && !((table2) => joins?.some( + ({ alias }) => alias === (table2[Table.Symbol.IsAlias] ? getTableName(table2) : table2[Table.Symbol.BaseName]) + ))(f.field.table)) { + const tableName = getTableName(f.field.table); + throw new Error( + `Your "${f.path.join("->")}" field references a column "${tableName}"."${f.field.name}", but the table "${tableName}" is not part of the query! Did you forget to join it?` + ); + } + } + const isSingleTable = !joins || joins.length === 0; + const withSql = this.buildWithCTE(withList); + const distinctSql = distinct ? sql` distinct` : void 0; + const selection = this.buildSelection(fieldsList, { isSingleTable }); + const tableSql = this.buildFromTable(table); + const joinsSql = this.buildJoins(joins); + const whereSql = where ? sql` where ${where}` : void 0; + const havingSql = having ? sql` having ${having}` : void 0; + const groupByList = []; + if (groupBy) { + for (const [index, groupByValue] of groupBy.entries()) { + groupByList.push(groupByValue); + if (index < groupBy.length - 1) { + groupByList.push(sql`, `); + } + } + } + const groupBySql = groupByList.length > 0 ? sql` group by ${sql.join(groupByList)}` : void 0; + const orderBySql = this.buildOrderBy(orderBy); + const limitSql = this.buildLimit(limit); + const offsetSql = offset ? sql` offset ${offset}` : void 0; + const finalQuery = sql`${withSql}select${distinctSql} ${selection} from ${tableSql}${joinsSql}${whereSql}${groupBySql}${havingSql}${orderBySql}${limitSql}${offsetSql}`; + if (setOperators.length > 0) { + return this.buildSetOperations(finalQuery, setOperators); + } + return finalQuery; + } + buildSetOperations(leftSelect, setOperators) { + const [setOperator, ...rest] = setOperators; + if (!setOperator) { + throw new Error("Cannot pass undefined values to any set operator"); + } + if (rest.length === 0) { + return this.buildSetOperationQuery({ leftSelect, setOperator }); + } + return this.buildSetOperations( + this.buildSetOperationQuery({ leftSelect, setOperator }), + rest + ); + } + buildSetOperationQuery({ + leftSelect, + setOperator: { type, isAll, rightSelect, limit, orderBy, offset } + }) { + const leftChunk = sql`${leftSelect.getSQL()} `; + const rightChunk = sql`${rightSelect.getSQL()}`; + let orderBySql; + if (orderBy && orderBy.length > 0) { + const orderByValues = []; + for (const singleOrderBy of orderBy) { + if (is(singleOrderBy, SQLiteColumn)) { + orderByValues.push(sql.identifier(singleOrderBy.name)); + } else if (is(singleOrderBy, SQL)) { + for (let i = 0; i < singleOrderBy.queryChunks.length; i++) { + const chunk = singleOrderBy.queryChunks[i]; + if (is(chunk, SQLiteColumn)) { + singleOrderBy.queryChunks[i] = sql.identifier(this.casing.getColumnCasing(chunk)); + } + } + orderByValues.push(sql`${singleOrderBy}`); + } else { + orderByValues.push(sql`${singleOrderBy}`); + } + } + orderBySql = sql` order by ${sql.join(orderByValues, sql`, `)}`; + } + const limitSql = typeof limit === "object" || typeof limit === "number" && limit >= 0 ? sql` limit ${limit}` : void 0; + const operatorChunk = sql.raw(`${type} ${isAll ? "all " : ""}`); + const offsetSql = offset ? sql` offset ${offset}` : void 0; + return sql`${leftChunk}${operatorChunk}${rightChunk}${orderBySql}${limitSql}${offsetSql}`; + } + buildInsertQuery({ table, values: valuesOrSelect, onConflict, returning, withList, select }) { + const valuesSqlList = []; + const columns = table[Table.Symbol.Columns]; + const colEntries = Object.entries(columns).filter( + ([_, col]) => !col.shouldDisableInsert() + ); + const insertOrder = colEntries.map(([, column]) => sql.identifier(this.casing.getColumnCasing(column))); + if (select) { + const select2 = valuesOrSelect; + if (is(select2, SQL)) { + valuesSqlList.push(select2); + } else { + valuesSqlList.push(select2.getSQL()); + } + } else { + const values = valuesOrSelect; + valuesSqlList.push(sql.raw("values ")); + for (const [valueIndex, value] of values.entries()) { + const valueList = []; + for (const [fieldName, col] of colEntries) { + const colValue = value[fieldName]; + if (colValue === void 0 || is(colValue, Param) && colValue.value === void 0) { + let defaultValue; + if (col.default !== null && col.default !== void 0) { + defaultValue = is(col.default, SQL) ? col.default : sql.param(col.default, col); + } else if (col.defaultFn !== void 0) { + const defaultFnResult = col.defaultFn(); + defaultValue = is(defaultFnResult, SQL) ? defaultFnResult : sql.param(defaultFnResult, col); + } else if (!col.default && col.onUpdateFn !== void 0) { + const onUpdateFnResult = col.onUpdateFn(); + defaultValue = is(onUpdateFnResult, SQL) ? onUpdateFnResult : sql.param(onUpdateFnResult, col); + } else { + defaultValue = sql`null`; + } + valueList.push(defaultValue); + } else { + valueList.push(colValue); + } + } + valuesSqlList.push(valueList); + if (valueIndex < values.length - 1) { + valuesSqlList.push(sql`, `); + } + } + } + const withSql = this.buildWithCTE(withList); + const valuesSql = sql.join(valuesSqlList); + const returningSql = returning ? sql` returning ${this.buildSelection(returning, { isSingleTable: true })}` : void 0; + const onConflictSql = onConflict?.length ? sql.join(onConflict) : void 0; + return sql`${withSql}insert into ${table} ${insertOrder} ${valuesSql}${onConflictSql}${returningSql}`; + } + sqlToQuery(sql2, invokeSource) { + return sql2.toQuery({ + casing: this.casing, + escapeName: this.escapeName, + escapeParam: this.escapeParam, + escapeString: this.escapeString, + invokeSource + }); + } + buildRelationalQuery({ + fullSchema, + schema, + tableNamesMap, + table, + tableConfig, + queryConfig: config2, + tableAlias, + nestedQueryRelation, + joinOn + }) { + let selection = []; + let limit, offset, orderBy = [], where; + const joins = []; + if (config2 === true) { + const selectionEntries = Object.entries(tableConfig.columns); + selection = selectionEntries.map(([key, value]) => ({ + dbKey: value.name, + tsKey: key, + field: aliasedTableColumn(value, tableAlias), + relationTableTsKey: void 0, + isJson: false, + selection: [] + })); + } else { + const aliasedColumns = Object.fromEntries( + Object.entries(tableConfig.columns).map(([key, value]) => [key, aliasedTableColumn(value, tableAlias)]) + ); + if (config2.where) { + const whereSql = typeof config2.where === "function" ? config2.where(aliasedColumns, getOperators()) : config2.where; + where = whereSql && mapColumnsInSQLToAlias(whereSql, tableAlias); + } + const fieldsSelection = []; + let selectedColumns = []; + if (config2.columns) { + let isIncludeMode = false; + for (const [field, value] of Object.entries(config2.columns)) { + if (value === void 0) { + continue; + } + if (field in tableConfig.columns) { + if (!isIncludeMode && value === true) { + isIncludeMode = true; + } + selectedColumns.push(field); + } + } + if (selectedColumns.length > 0) { + selectedColumns = isIncludeMode ? selectedColumns.filter((c) => config2.columns?.[c] === true) : Object.keys(tableConfig.columns).filter((key) => !selectedColumns.includes(key)); + } + } else { + selectedColumns = Object.keys(tableConfig.columns); + } + for (const field of selectedColumns) { + const column = tableConfig.columns[field]; + fieldsSelection.push({ tsKey: field, value: column }); + } + let selectedRelations = []; + if (config2.with) { + selectedRelations = Object.entries(config2.with).filter((entry) => !!entry[1]).map(([tsKey, queryConfig]) => ({ tsKey, queryConfig, relation: tableConfig.relations[tsKey] })); + } + let extras; + if (config2.extras) { + extras = typeof config2.extras === "function" ? config2.extras(aliasedColumns, { sql }) : config2.extras; + for (const [tsKey, value] of Object.entries(extras)) { + fieldsSelection.push({ + tsKey, + value: mapColumnsInAliasedSQLToAlias(value, tableAlias) + }); + } + } + for (const { tsKey, value } of fieldsSelection) { + selection.push({ + dbKey: is(value, SQL.Aliased) ? value.fieldAlias : tableConfig.columns[tsKey].name, + tsKey, + field: is(value, Column) ? aliasedTableColumn(value, tableAlias) : value, + relationTableTsKey: void 0, + isJson: false, + selection: [] + }); + } + let orderByOrig = typeof config2.orderBy === "function" ? config2.orderBy(aliasedColumns, getOrderByOperators()) : config2.orderBy ?? []; + if (!Array.isArray(orderByOrig)) { + orderByOrig = [orderByOrig]; + } + orderBy = orderByOrig.map((orderByValue) => { + if (is(orderByValue, Column)) { + return aliasedTableColumn(orderByValue, tableAlias); + } + return mapColumnsInSQLToAlias(orderByValue, tableAlias); + }); + limit = config2.limit; + offset = config2.offset; + for (const { + tsKey: selectedRelationTsKey, + queryConfig: selectedRelationConfigValue, + relation + } of selectedRelations) { + const normalizedRelation = normalizeRelation(schema, tableNamesMap, relation); + const relationTableName = getTableUniqueName(relation.referencedTable); + const relationTableTsName = tableNamesMap[relationTableName]; + const relationTableAlias = `${tableAlias}_${selectedRelationTsKey}`; + const joinOn2 = and( + ...normalizedRelation.fields.map( + (field2, i) => eq( + aliasedTableColumn(normalizedRelation.references[i], relationTableAlias), + aliasedTableColumn(field2, tableAlias) + ) + ) + ); + const builtRelation = this.buildRelationalQuery({ + fullSchema, + schema, + tableNamesMap, + table: fullSchema[relationTableTsName], + tableConfig: schema[relationTableTsName], + queryConfig: is(relation, One) ? selectedRelationConfigValue === true ? { limit: 1 } : { ...selectedRelationConfigValue, limit: 1 } : selectedRelationConfigValue, + tableAlias: relationTableAlias, + joinOn: joinOn2, + nestedQueryRelation: relation + }); + const field = sql`(${builtRelation.sql})`.as(selectedRelationTsKey); + selection.push({ + dbKey: selectedRelationTsKey, + tsKey: selectedRelationTsKey, + field, + relationTableTsKey: relationTableTsName, + isJson: true, + selection: builtRelation.selection + }); + } + } + if (selection.length === 0) { + throw new DrizzleError({ + message: `No fields selected for table "${tableConfig.tsName}" ("${tableAlias}"). You need to have at least one item in "columns", "with" or "extras". If you need to select all columns, omit the "columns" key or set it to undefined.` + }); + } + let result; + where = and(joinOn, where); + if (nestedQueryRelation) { + let field = sql`json_array(${sql.join( + selection.map( + ({ field: field2 }) => is(field2, SQLiteColumn) ? sql.identifier(this.casing.getColumnCasing(field2)) : is(field2, SQL.Aliased) ? field2.sql : field2 + ), + sql`, ` + )})`; + if (is(nestedQueryRelation, Many)) { + field = sql`coalesce(json_group_array(${field}), json_array())`; + } + const nestedSelection = [{ + dbKey: "data", + tsKey: "data", + field: field.as("data"), + isJson: true, + relationTableTsKey: tableConfig.tsName, + selection + }]; + const needsSubquery = limit !== void 0 || offset !== void 0 || orderBy.length > 0; + if (needsSubquery) { + result = this.buildSelectQuery({ + table: aliasedTable(table, tableAlias), + fields: {}, + fieldsFlat: [ + { + path: [], + field: sql.raw("*") + } + ], + where, + limit, + offset, + orderBy, + setOperators: [] + }); + where = void 0; + limit = void 0; + offset = void 0; + orderBy = void 0; + } else { + result = aliasedTable(table, tableAlias); + } + result = this.buildSelectQuery({ + table: is(result, SQLiteTable) ? result : new Subquery(result, {}, tableAlias), + fields: {}, + fieldsFlat: nestedSelection.map(({ field: field2 }) => ({ + path: [], + field: is(field2, Column) ? aliasedTableColumn(field2, tableAlias) : field2 + })), + joins, + where, + limit, + offset, + orderBy, + setOperators: [] + }); + } else { + result = this.buildSelectQuery({ + table: aliasedTable(table, tableAlias), + fields: {}, + fieldsFlat: selection.map(({ field }) => ({ + path: [], + field: is(field, Column) ? aliasedTableColumn(field, tableAlias) : field + })), + joins, + where, + limit, + offset, + orderBy, + setOperators: [] + }); + } + return { + tableTsKey: tableConfig.tsName, + sql: result, + selection + }; + } +}; +var SQLiteSyncDialect = class extends SQLiteDialect { + static { + __name(this, "SQLiteSyncDialect"); + } + static [entityKind] = "SQLiteSyncDialect"; + migrate(migrations, session2, config2) { + const migrationsTable = config2 === void 0 ? "__drizzle_migrations" : typeof config2 === "string" ? "__drizzle_migrations" : config2.migrationsTable ?? "__drizzle_migrations"; + const migrationTableCreate = sql` + CREATE TABLE IF NOT EXISTS ${sql.identifier(migrationsTable)} ( + id SERIAL PRIMARY KEY, + hash text NOT NULL, + created_at numeric + ) + `; + session2.run(migrationTableCreate); + const dbMigrations = session2.values( + sql`SELECT id, hash, created_at FROM ${sql.identifier(migrationsTable)} ORDER BY created_at DESC LIMIT 1` + ); + const lastDbMigration = dbMigrations[0] ?? void 0; + session2.run(sql`BEGIN`); + try { + for (const migration of migrations) { + if (!lastDbMigration || Number(lastDbMigration[2]) < migration.folderMillis) { + for (const stmt of migration.sql) { + session2.run(sql.raw(stmt)); + } + session2.run( + sql`INSERT INTO ${sql.identifier(migrationsTable)} ("hash", "created_at") VALUES(${migration.hash}, ${migration.folderMillis})` + ); + } + } + session2.run(sql`COMMIT`); + } catch (e) { + session2.run(sql`ROLLBACK`); + throw e; + } + } +}; +var SQLiteAsyncDialect = class extends SQLiteDialect { + static { + __name(this, "SQLiteAsyncDialect"); + } + static [entityKind] = "SQLiteAsyncDialect"; + async migrate(migrations, session2, config2) { + const migrationsTable = config2 === void 0 ? "__drizzle_migrations" : typeof config2 === "string" ? "__drizzle_migrations" : config2.migrationsTable ?? "__drizzle_migrations"; + const migrationTableCreate = sql` + CREATE TABLE IF NOT EXISTS ${sql.identifier(migrationsTable)} ( + id SERIAL PRIMARY KEY, + hash text NOT NULL, + created_at numeric + ) + `; + await session2.run(migrationTableCreate); + const dbMigrations = await session2.values( + sql`SELECT id, hash, created_at FROM ${sql.identifier(migrationsTable)} ORDER BY created_at DESC LIMIT 1` + ); + const lastDbMigration = dbMigrations[0] ?? void 0; + await session2.transaction(async (tx) => { + for (const migration of migrations) { + if (!lastDbMigration || Number(lastDbMigration[2]) < migration.folderMillis) { + for (const stmt of migration.sql) { + await tx.run(sql.raw(stmt)); + } + await tx.run( + sql`INSERT INTO ${sql.identifier(migrationsTable)} ("hash", "created_at") VALUES(${migration.hash}, ${migration.folderMillis})` + ); + } + } + }); + } +}; + +// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/sqlite-core/query-builders/select.js +init_modules_watch_stub(); +init_performance2(); + +// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/query-builders/query-builder.js +init_modules_watch_stub(); +init_performance2(); +var TypedQueryBuilder = class { + static { + __name(this, "TypedQueryBuilder"); + } + static [entityKind] = "TypedQueryBuilder"; + /** @internal */ + getSelectedFields() { + return this._.selectedFields; + } +}; + +// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/sqlite-core/query-builders/select.js +var SQLiteSelectBuilder = class { + static { + __name(this, "SQLiteSelectBuilder"); + } + static [entityKind] = "SQLiteSelectBuilder"; + fields; + session; + dialect; + withList; + distinct; + constructor(config2) { + this.fields = config2.fields; + this.session = config2.session; + this.dialect = config2.dialect; + this.withList = config2.withList; + this.distinct = config2.distinct; + } + from(source) { + const isPartialSelect = !!this.fields; + let fields; + if (this.fields) { + fields = this.fields; + } else if (is(source, Subquery)) { + fields = Object.fromEntries( + Object.keys(source._.selectedFields).map((key) => [key, source[key]]) + ); + } else if (is(source, SQLiteViewBase)) { + fields = source[ViewBaseConfig].selectedFields; + } else if (is(source, SQL)) { + fields = {}; + } else { + fields = getTableColumns(source); + } + return new SQLiteSelectBase({ + table: source, + fields, + isPartialSelect, + session: this.session, + dialect: this.dialect, + withList: this.withList, + distinct: this.distinct + }); + } +}; +var SQLiteSelectQueryBuilderBase = class extends TypedQueryBuilder { + static { + __name(this, "SQLiteSelectQueryBuilderBase"); + } + static [entityKind] = "SQLiteSelectQueryBuilder"; + _; + /** @internal */ + config; + joinsNotNullableMap; + tableName; + isPartialSelect; + session; + dialect; + cacheConfig = void 0; + usedTables = /* @__PURE__ */ new Set(); + constructor({ table, fields, isPartialSelect, session: session2, dialect, withList, distinct }) { + super(); + this.config = { + withList, + table, + fields: { ...fields }, + distinct, + setOperators: [] + }; + this.isPartialSelect = isPartialSelect; + this.session = session2; + this.dialect = dialect; + this._ = { + selectedFields: fields, + config: this.config + }; + this.tableName = getTableLikeName(table); + this.joinsNotNullableMap = typeof this.tableName === "string" ? { [this.tableName]: true } : {}; + for (const item of extractUsedTable(table)) this.usedTables.add(item); + } + /** @internal */ + getUsedTables() { + return [...this.usedTables]; + } + createJoin(joinType) { + return (table, on2) => { + const baseTableName = this.tableName; + const tableName = getTableLikeName(table); + for (const item of extractUsedTable(table)) this.usedTables.add(item); + if (typeof tableName === "string" && this.config.joins?.some((join) => join.alias === tableName)) { + throw new Error(`Alias "${tableName}" is already used in this query`); + } + if (!this.isPartialSelect) { + if (Object.keys(this.joinsNotNullableMap).length === 1 && typeof baseTableName === "string") { + this.config.fields = { + [baseTableName]: this.config.fields + }; + } + if (typeof tableName === "string" && !is(table, SQL)) { + const selection = is(table, Subquery) ? table._.selectedFields : is(table, View) ? table[ViewBaseConfig].selectedFields : table[Table.Symbol.Columns]; + this.config.fields[tableName] = selection; + } + } + if (typeof on2 === "function") { + on2 = on2( + new Proxy( + this.config.fields, + new SelectionProxyHandler({ sqlAliasedBehavior: "sql", sqlBehavior: "sql" }) + ) + ); + } + if (!this.config.joins) { + this.config.joins = []; + } + this.config.joins.push({ on: on2, table, joinType, alias: tableName }); + if (typeof tableName === "string") { + switch (joinType) { + case "left": { + this.joinsNotNullableMap[tableName] = false; + break; + } + case "right": { + this.joinsNotNullableMap = Object.fromEntries( + Object.entries(this.joinsNotNullableMap).map(([key]) => [key, false]) + ); + this.joinsNotNullableMap[tableName] = true; + break; + } + case "cross": + case "inner": { + this.joinsNotNullableMap[tableName] = true; + break; + } + case "full": { + this.joinsNotNullableMap = Object.fromEntries( + Object.entries(this.joinsNotNullableMap).map(([key]) => [key, false]) + ); + this.joinsNotNullableMap[tableName] = false; + break; + } + } + } + return this; + }; + } + /** + * Executes a `left join` operation by adding another table to the current query. + * + * Calling this method associates each row of the table with the corresponding row from the joined table, if a match is found. If no matching row exists, it sets all columns of the joined table to null. + * + * See docs: {@link https://orm.drizzle.team/docs/joins#left-join} + * + * @param table the table to join. + * @param on the `on` clause. + * + * @example + * + * ```ts + * // Select all users and their pets + * const usersWithPets: { user: User; pets: Pet | null; }[] = await db.select() + * .from(users) + * .leftJoin(pets, eq(users.id, pets.ownerId)) + * + * // Select userId and petId + * const usersIdsAndPetIds: { userId: number; petId: number | null; }[] = await db.select({ + * userId: users.id, + * petId: pets.id, + * }) + * .from(users) + * .leftJoin(pets, eq(users.id, pets.ownerId)) + * ``` + */ + leftJoin = this.createJoin("left"); + /** + * Executes a `right join` operation by adding another table to the current query. + * + * Calling this method associates each row of the joined table with the corresponding row from the main table, if a match is found. If no matching row exists, it sets all columns of the main table to null. + * + * See docs: {@link https://orm.drizzle.team/docs/joins#right-join} + * + * @param table the table to join. + * @param on the `on` clause. + * + * @example + * + * ```ts + * // Select all users and their pets + * const usersWithPets: { user: User | null; pets: Pet; }[] = await db.select() + * .from(users) + * .rightJoin(pets, eq(users.id, pets.ownerId)) + * + * // Select userId and petId + * const usersIdsAndPetIds: { userId: number | null; petId: number; }[] = await db.select({ + * userId: users.id, + * petId: pets.id, + * }) + * .from(users) + * .rightJoin(pets, eq(users.id, pets.ownerId)) + * ``` + */ + rightJoin = this.createJoin("right"); + /** + * Executes an `inner join` operation, creating a new table by combining rows from two tables that have matching values. + * + * Calling this method retrieves rows that have corresponding entries in both joined tables. Rows without matching entries in either table are excluded, resulting in a table that includes only matching pairs. + * + * See docs: {@link https://orm.drizzle.team/docs/joins#inner-join} + * + * @param table the table to join. + * @param on the `on` clause. + * + * @example + * + * ```ts + * // Select all users and their pets + * const usersWithPets: { user: User; pets: Pet; }[] = await db.select() + * .from(users) + * .innerJoin(pets, eq(users.id, pets.ownerId)) + * + * // Select userId and petId + * const usersIdsAndPetIds: { userId: number; petId: number; }[] = await db.select({ + * userId: users.id, + * petId: pets.id, + * }) + * .from(users) + * .innerJoin(pets, eq(users.id, pets.ownerId)) + * ``` + */ + innerJoin = this.createJoin("inner"); + /** + * Executes a `full join` operation by combining rows from two tables into a new table. + * + * Calling this method retrieves all rows from both main and joined tables, merging rows with matching values and filling in `null` for non-matching columns. + * + * See docs: {@link https://orm.drizzle.team/docs/joins#full-join} + * + * @param table the table to join. + * @param on the `on` clause. + * + * @example + * + * ```ts + * // Select all users and their pets + * const usersWithPets: { user: User | null; pets: Pet | null; }[] = await db.select() + * .from(users) + * .fullJoin(pets, eq(users.id, pets.ownerId)) + * + * // Select userId and petId + * const usersIdsAndPetIds: { userId: number | null; petId: number | null; }[] = await db.select({ + * userId: users.id, + * petId: pets.id, + * }) + * .from(users) + * .fullJoin(pets, eq(users.id, pets.ownerId)) + * ``` + */ + fullJoin = this.createJoin("full"); + /** + * Executes a `cross join` operation by combining rows from two tables into a new table. + * + * Calling this method retrieves all rows from both main and joined tables, merging all rows from each table. + * + * See docs: {@link https://orm.drizzle.team/docs/joins#cross-join} + * + * @param table the table to join. + * + * @example + * + * ```ts + * // Select all users, each user with every pet + * const usersWithPets: { user: User; pets: Pet; }[] = await db.select() + * .from(users) + * .crossJoin(pets) + * + * // Select userId and petId + * const usersIdsAndPetIds: { userId: number; petId: number; }[] = await db.select({ + * userId: users.id, + * petId: pets.id, + * }) + * .from(users) + * .crossJoin(pets) + * ``` + */ + crossJoin = this.createJoin("cross"); + createSetOperator(type, isAll) { + return (rightSelection) => { + const rightSelect = typeof rightSelection === "function" ? rightSelection(getSQLiteSetOperators()) : rightSelection; + if (!haveSameKeys(this.getSelectedFields(), rightSelect.getSelectedFields())) { + throw new Error( + "Set operator error (union / intersect / except): selected fields are not the same or are in a different order" + ); + } + this.config.setOperators.push({ type, isAll, rightSelect }); + return this; + }; + } + /** + * Adds `union` set operator to the query. + * + * Calling this method will combine the result sets of the `select` statements and remove any duplicate rows that appear across them. + * + * See docs: {@link https://orm.drizzle.team/docs/set-operations#union} + * + * @example + * + * ```ts + * // Select all unique names from customers and users tables + * await db.select({ name: users.name }) + * .from(users) + * .union( + * db.select({ name: customers.name }).from(customers) + * ); + * // or + * import { union } from 'drizzle-orm/sqlite-core' + * + * await union( + * db.select({ name: users.name }).from(users), + * db.select({ name: customers.name }).from(customers) + * ); + * ``` + */ + union = this.createSetOperator("union", false); + /** + * Adds `union all` set operator to the query. + * + * Calling this method will combine the result-set of the `select` statements and keep all duplicate rows that appear across them. + * + * See docs: {@link https://orm.drizzle.team/docs/set-operations#union-all} + * + * @example + * + * ```ts + * // Select all transaction ids from both online and in-store sales + * await db.select({ transaction: onlineSales.transactionId }) + * .from(onlineSales) + * .unionAll( + * db.select({ transaction: inStoreSales.transactionId }).from(inStoreSales) + * ); + * // or + * import { unionAll } from 'drizzle-orm/sqlite-core' + * + * await unionAll( + * db.select({ transaction: onlineSales.transactionId }).from(onlineSales), + * db.select({ transaction: inStoreSales.transactionId }).from(inStoreSales) + * ); + * ``` + */ + unionAll = this.createSetOperator("union", true); + /** + * Adds `intersect` set operator to the query. + * + * Calling this method will retain only the rows that are present in both result sets and eliminate duplicates. + * + * See docs: {@link https://orm.drizzle.team/docs/set-operations#intersect} + * + * @example + * + * ```ts + * // Select course names that are offered in both departments A and B + * await db.select({ courseName: depA.courseName }) + * .from(depA) + * .intersect( + * db.select({ courseName: depB.courseName }).from(depB) + * ); + * // or + * import { intersect } from 'drizzle-orm/sqlite-core' + * + * await intersect( + * db.select({ courseName: depA.courseName }).from(depA), + * db.select({ courseName: depB.courseName }).from(depB) + * ); + * ``` + */ + intersect = this.createSetOperator("intersect", false); + /** + * Adds `except` set operator to the query. + * + * Calling this method will retrieve all unique rows from the left query, except for the rows that are present in the result set of the right query. + * + * See docs: {@link https://orm.drizzle.team/docs/set-operations#except} + * + * @example + * + * ```ts + * // Select all courses offered in department A but not in department B + * await db.select({ courseName: depA.courseName }) + * .from(depA) + * .except( + * db.select({ courseName: depB.courseName }).from(depB) + * ); + * // or + * import { except } from 'drizzle-orm/sqlite-core' + * + * await except( + * db.select({ courseName: depA.courseName }).from(depA), + * db.select({ courseName: depB.courseName }).from(depB) + * ); + * ``` + */ + except = this.createSetOperator("except", false); + /** @internal */ + addSetOperators(setOperators) { + this.config.setOperators.push(...setOperators); + return this; + } + /** + * Adds a `where` clause to the query. + * + * Calling this method will select only those rows that fulfill a specified condition. + * + * See docs: {@link https://orm.drizzle.team/docs/select#filtering} + * + * @param where the `where` clause. + * + * @example + * You can use conditional operators and `sql function` to filter the rows to be selected. + * + * ```ts + * // Select all cars with green color + * await db.select().from(cars).where(eq(cars.color, 'green')); + * // or + * await db.select().from(cars).where(sql`${cars.color} = 'green'`) + * ``` + * + * You can logically combine conditional operators with `and()` and `or()` operators: + * + * ```ts + * // Select all BMW cars with a green color + * await db.select().from(cars).where(and(eq(cars.color, 'green'), eq(cars.brand, 'BMW'))); + * + * // Select all cars with the green or blue color + * await db.select().from(cars).where(or(eq(cars.color, 'green'), eq(cars.color, 'blue'))); + * ``` + */ + where(where) { + if (typeof where === "function") { + where = where( + new Proxy( + this.config.fields, + new SelectionProxyHandler({ sqlAliasedBehavior: "sql", sqlBehavior: "sql" }) + ) + ); + } + this.config.where = where; + return this; + } + /** + * Adds a `having` clause to the query. + * + * Calling this method will select only those rows that fulfill a specified condition. It is typically used with aggregate functions to filter the aggregated data based on a specified condition. + * + * See docs: {@link https://orm.drizzle.team/docs/select#aggregations} + * + * @param having the `having` clause. + * + * @example + * + * ```ts + * // Select all brands with more than one car + * await db.select({ + * brand: cars.brand, + * count: sql`cast(count(${cars.id}) as int)`, + * }) + * .from(cars) + * .groupBy(cars.brand) + * .having(({ count }) => gt(count, 1)); + * ``` + */ + having(having) { + if (typeof having === "function") { + having = having( + new Proxy( + this.config.fields, + new SelectionProxyHandler({ sqlAliasedBehavior: "sql", sqlBehavior: "sql" }) + ) + ); + } + this.config.having = having; + return this; + } + groupBy(...columns) { + if (typeof columns[0] === "function") { + const groupBy = columns[0]( + new Proxy( + this.config.fields, + new SelectionProxyHandler({ sqlAliasedBehavior: "alias", sqlBehavior: "sql" }) + ) + ); + this.config.groupBy = Array.isArray(groupBy) ? groupBy : [groupBy]; + } else { + this.config.groupBy = columns; + } + return this; + } + orderBy(...columns) { + if (typeof columns[0] === "function") { + const orderBy = columns[0]( + new Proxy( + this.config.fields, + new SelectionProxyHandler({ sqlAliasedBehavior: "alias", sqlBehavior: "sql" }) + ) + ); + const orderByArray = Array.isArray(orderBy) ? orderBy : [orderBy]; + if (this.config.setOperators.length > 0) { + this.config.setOperators.at(-1).orderBy = orderByArray; + } else { + this.config.orderBy = orderByArray; + } + } else { + const orderByArray = columns; + if (this.config.setOperators.length > 0) { + this.config.setOperators.at(-1).orderBy = orderByArray; + } else { + this.config.orderBy = orderByArray; + } + } + return this; + } + /** + * Adds a `limit` clause to the query. + * + * Calling this method will set the maximum number of rows that will be returned by this query. + * + * See docs: {@link https://orm.drizzle.team/docs/select#limit--offset} + * + * @param limit the `limit` clause. + * + * @example + * + * ```ts + * // Get the first 10 people from this query. + * await db.select().from(people).limit(10); + * ``` + */ + limit(limit) { + if (this.config.setOperators.length > 0) { + this.config.setOperators.at(-1).limit = limit; + } else { + this.config.limit = limit; + } + return this; + } + /** + * Adds an `offset` clause to the query. + * + * Calling this method will skip a number of rows when returning results from this query. + * + * See docs: {@link https://orm.drizzle.team/docs/select#limit--offset} + * + * @param offset the `offset` clause. + * + * @example + * + * ```ts + * // Get the 10th-20th people from this query. + * await db.select().from(people).offset(10).limit(10); + * ``` + */ + offset(offset) { + if (this.config.setOperators.length > 0) { + this.config.setOperators.at(-1).offset = offset; + } else { + this.config.offset = offset; + } + return this; + } + /** @internal */ + getSQL() { + return this.dialect.buildSelectQuery(this.config); + } + toSQL() { + const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL()); + return rest; + } + as(alias) { + const usedTables = []; + usedTables.push(...extractUsedTable(this.config.table)); + if (this.config.joins) { + for (const it of this.config.joins) usedTables.push(...extractUsedTable(it.table)); + } + return new Proxy( + new Subquery(this.getSQL(), this.config.fields, alias, false, [...new Set(usedTables)]), + new SelectionProxyHandler({ alias, sqlAliasedBehavior: "alias", sqlBehavior: "error" }) + ); + } + /** @internal */ + getSelectedFields() { + return new Proxy( + this.config.fields, + new SelectionProxyHandler({ alias: this.tableName, sqlAliasedBehavior: "alias", sqlBehavior: "error" }) + ); + } + $dynamic() { + return this; + } +}; +var SQLiteSelectBase = class extends SQLiteSelectQueryBuilderBase { + static { + __name(this, "SQLiteSelectBase"); + } + static [entityKind] = "SQLiteSelect"; + /** @internal */ + _prepare(isOneTimeQuery = true) { + if (!this.session) { + throw new Error("Cannot execute a query on a query builder. Please use a database instance instead."); + } + const fieldsList = orderSelectedFields(this.config.fields); + const query = this.session[isOneTimeQuery ? "prepareOneTimeQuery" : "prepareQuery"]( + this.dialect.sqlToQuery(this.getSQL()), + fieldsList, + "all", + true, + void 0, + { + type: "select", + tables: [...this.usedTables] + }, + this.cacheConfig + ); + query.joinsNotNullableMap = this.joinsNotNullableMap; + return query; + } + $withCache(config2) { + this.cacheConfig = config2 === void 0 ? { config: {}, enable: true, autoInvalidate: true } : config2 === false ? { enable: false } : { enable: true, autoInvalidate: true, ...config2 }; + return this; + } + prepare() { + return this._prepare(false); + } + run = /* @__PURE__ */ __name((placeholderValues) => { + return this._prepare().run(placeholderValues); + }, "run"); + all = /* @__PURE__ */ __name((placeholderValues) => { + return this._prepare().all(placeholderValues); + }, "all"); + get = /* @__PURE__ */ __name((placeholderValues) => { + return this._prepare().get(placeholderValues); + }, "get"); + values = /* @__PURE__ */ __name((placeholderValues) => { + return this._prepare().values(placeholderValues); + }, "values"); + async execute() { + return this.all(); + } +}; +applyMixins(SQLiteSelectBase, [QueryPromise]); +function createSetOperator(type, isAll) { + return (leftSelect, rightSelect, ...restSelects) => { + const setOperators = [rightSelect, ...restSelects].map((select) => ({ + type, + isAll, + rightSelect: select + })); + for (const setOperator of setOperators) { + if (!haveSameKeys(leftSelect.getSelectedFields(), setOperator.rightSelect.getSelectedFields())) { + throw new Error( + "Set operator error (union / intersect / except): selected fields are not the same or are in a different order" + ); + } + } + return leftSelect.addSetOperators(setOperators); + }; +} +__name(createSetOperator, "createSetOperator"); +var getSQLiteSetOperators = /* @__PURE__ */ __name(() => ({ + union, + unionAll, + intersect, + except +}), "getSQLiteSetOperators"); +var union = createSetOperator("union", false); +var unionAll = createSetOperator("union", true); +var intersect = createSetOperator("intersect", false); +var except = createSetOperator("except", false); + +// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/sqlite-core/query-builders/query-builder.js +var QueryBuilder = class { + static { + __name(this, "QueryBuilder"); + } + static [entityKind] = "SQLiteQueryBuilder"; + dialect; + dialectConfig; + constructor(dialect) { + this.dialect = is(dialect, SQLiteDialect) ? dialect : void 0; + this.dialectConfig = is(dialect, SQLiteDialect) ? void 0 : dialect; + } + $with = /* @__PURE__ */ __name((alias, selection) => { + const queryBuilder = this; + const as = /* @__PURE__ */ __name((qb) => { + if (typeof qb === "function") { + qb = qb(queryBuilder); + } + return new Proxy( + new WithSubquery( + qb.getSQL(), + selection ?? ("getSelectedFields" in qb ? qb.getSelectedFields() ?? {} : {}), + alias, + true + ), + new SelectionProxyHandler({ alias, sqlAliasedBehavior: "alias", sqlBehavior: "error" }) + ); + }, "as"); + return { as }; + }, "$with"); + with(...queries) { + const self2 = this; + function select(fields) { + return new SQLiteSelectBuilder({ + fields: fields ?? void 0, + session: void 0, + dialect: self2.getDialect(), + withList: queries + }); + } + __name(select, "select"); + function selectDistinct(fields) { + return new SQLiteSelectBuilder({ + fields: fields ?? void 0, + session: void 0, + dialect: self2.getDialect(), + withList: queries, + distinct: true + }); + } + __name(selectDistinct, "selectDistinct"); + return { select, selectDistinct }; + } + select(fields) { + return new SQLiteSelectBuilder({ fields: fields ?? void 0, session: void 0, dialect: this.getDialect() }); + } + selectDistinct(fields) { + return new SQLiteSelectBuilder({ + fields: fields ?? void 0, + session: void 0, + dialect: this.getDialect(), + distinct: true + }); + } + // Lazy load dialect to avoid circular dependency + getDialect() { + if (!this.dialect) { + this.dialect = new SQLiteSyncDialect(this.dialectConfig); + } + return this.dialect; + } +}; + +// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/sqlite-core/query-builders/insert.js +var SQLiteInsertBuilder = class { + static { + __name(this, "SQLiteInsertBuilder"); + } + constructor(table, session2, dialect, withList) { + this.table = table; + this.session = session2; + this.dialect = dialect; + this.withList = withList; + } + static [entityKind] = "SQLiteInsertBuilder"; + values(values) { + values = Array.isArray(values) ? values : [values]; + if (values.length === 0) { + throw new Error("values() must be called with at least one value"); + } + const mappedValues = values.map((entry) => { + const result = {}; + const cols = this.table[Table.Symbol.Columns]; + for (const colKey of Object.keys(entry)) { + const colValue = entry[colKey]; + result[colKey] = is(colValue, SQL) ? colValue : new Param(colValue, cols[colKey]); + } + return result; + }); + return new SQLiteInsertBase(this.table, mappedValues, this.session, this.dialect, this.withList); + } + select(selectQuery) { + const select = typeof selectQuery === "function" ? selectQuery(new QueryBuilder()) : selectQuery; + if (!is(select, SQL) && !haveSameKeys(this.table[Columns], select._.selectedFields)) { + throw new Error( + "Insert select error: selected fields are not the same or are in a different order compared to the table definition" + ); + } + return new SQLiteInsertBase(this.table, select, this.session, this.dialect, this.withList, true); + } +}; +var SQLiteInsertBase = class extends QueryPromise { + static { + __name(this, "SQLiteInsertBase"); + } + constructor(table, values, session2, dialect, withList, select) { + super(); + this.session = session2; + this.dialect = dialect; + this.config = { table, values, withList, select }; + } + static [entityKind] = "SQLiteInsert"; + /** @internal */ + config; + returning(fields = this.config.table[SQLiteTable.Symbol.Columns]) { + this.config.returning = orderSelectedFields(fields); + return this; + } + /** + * Adds an `on conflict do nothing` clause to the query. + * + * Calling this method simply avoids inserting a row as its alternative action. + * + * See docs: {@link https://orm.drizzle.team/docs/insert#on-conflict-do-nothing} + * + * @param config The `target` and `where` clauses. + * + * @example + * ```ts + * // Insert one row and cancel the insert if there's a conflict + * await db.insert(cars) + * .values({ id: 1, brand: 'BMW' }) + * .onConflictDoNothing(); + * + * // Explicitly specify conflict target + * await db.insert(cars) + * .values({ id: 1, brand: 'BMW' }) + * .onConflictDoNothing({ target: cars.id }); + * ``` + */ + onConflictDoNothing(config2 = {}) { + if (!this.config.onConflict) this.config.onConflict = []; + if (config2.target === void 0) { + this.config.onConflict.push(sql` on conflict do nothing`); + } else { + const targetSql = Array.isArray(config2.target) ? sql`${config2.target}` : sql`${[config2.target]}`; + const whereSql = config2.where ? sql` where ${config2.where}` : sql``; + this.config.onConflict.push(sql` on conflict ${targetSql} do nothing${whereSql}`); + } + return this; + } + /** + * Adds an `on conflict do update` clause to the query. + * + * Calling this method will update the existing row that conflicts with the row proposed for insertion as its alternative action. + * + * See docs: {@link https://orm.drizzle.team/docs/insert#upserts-and-conflicts} + * + * @param config The `target`, `set` and `where` clauses. + * + * @example + * ```ts + * // Update the row if there's a conflict + * await db.insert(cars) + * .values({ id: 1, brand: 'BMW' }) + * .onConflictDoUpdate({ + * target: cars.id, + * set: { brand: 'Porsche' } + * }); + * + * // Upsert with 'where' clause + * await db.insert(cars) + * .values({ id: 1, brand: 'BMW' }) + * .onConflictDoUpdate({ + * target: cars.id, + * set: { brand: 'newBMW' }, + * where: sql`${cars.createdAt} > '2023-01-01'::date`, + * }); + * ``` + */ + onConflictDoUpdate(config2) { + if (config2.where && (config2.targetWhere || config2.setWhere)) { + throw new Error( + 'You cannot use both "where" and "targetWhere"/"setWhere" at the same time - "where" is deprecated, use "targetWhere" or "setWhere" instead.' + ); + } + if (!this.config.onConflict) this.config.onConflict = []; + const whereSql = config2.where ? sql` where ${config2.where}` : void 0; + const targetWhereSql = config2.targetWhere ? sql` where ${config2.targetWhere}` : void 0; + const setWhereSql = config2.setWhere ? sql` where ${config2.setWhere}` : void 0; + const targetSql = Array.isArray(config2.target) ? sql`${config2.target}` : sql`${[config2.target]}`; + const setSql = this.dialect.buildUpdateSet(this.config.table, mapUpdateSet(this.config.table, config2.set)); + this.config.onConflict.push( + sql` on conflict ${targetSql}${targetWhereSql} do update set ${setSql}${whereSql}${setWhereSql}` + ); + return this; + } + /** @internal */ + getSQL() { + return this.dialect.buildInsertQuery(this.config); + } + toSQL() { + const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL()); + return rest; + } + /** @internal */ + _prepare(isOneTimeQuery = true) { + return this.session[isOneTimeQuery ? "prepareOneTimeQuery" : "prepareQuery"]( + this.dialect.sqlToQuery(this.getSQL()), + this.config.returning, + this.config.returning ? "all" : "run", + true, + void 0, + { + type: "insert", + tables: extractUsedTable(this.config.table) + } + ); + } + prepare() { + return this._prepare(false); + } + run = /* @__PURE__ */ __name((placeholderValues) => { + return this._prepare().run(placeholderValues); + }, "run"); + all = /* @__PURE__ */ __name((placeholderValues) => { + return this._prepare().all(placeholderValues); + }, "all"); + get = /* @__PURE__ */ __name((placeholderValues) => { + return this._prepare().get(placeholderValues); + }, "get"); + values = /* @__PURE__ */ __name((placeholderValues) => { + return this._prepare().values(placeholderValues); + }, "values"); + async execute() { + return this.config.returning ? this.all() : this.run(); + } + $dynamic() { + return this; + } +}; + +// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/sqlite-core/query-builders/update.js +init_modules_watch_stub(); +init_performance2(); +var SQLiteUpdateBuilder = class { + static { + __name(this, "SQLiteUpdateBuilder"); + } + constructor(table, session2, dialect, withList) { + this.table = table; + this.session = session2; + this.dialect = dialect; + this.withList = withList; + } + static [entityKind] = "SQLiteUpdateBuilder"; + set(values) { + return new SQLiteUpdateBase( + this.table, + mapUpdateSet(this.table, values), + this.session, + this.dialect, + this.withList + ); + } +}; +var SQLiteUpdateBase = class extends QueryPromise { + static { + __name(this, "SQLiteUpdateBase"); + } + constructor(table, set, session2, dialect, withList) { + super(); + this.session = session2; + this.dialect = dialect; + this.config = { set, table, withList, joins: [] }; + } + static [entityKind] = "SQLiteUpdate"; + /** @internal */ + config; + from(source) { + this.config.from = source; + return this; + } + createJoin(joinType) { + return (table, on2) => { + const tableName = getTableLikeName(table); + if (typeof tableName === "string" && this.config.joins.some((join) => join.alias === tableName)) { + throw new Error(`Alias "${tableName}" is already used in this query`); + } + if (typeof on2 === "function") { + const from = this.config.from ? is(table, SQLiteTable) ? table[Table.Symbol.Columns] : is(table, Subquery) ? table._.selectedFields : is(table, SQLiteViewBase) ? table[ViewBaseConfig].selectedFields : void 0 : void 0; + on2 = on2( + new Proxy( + this.config.table[Table.Symbol.Columns], + new SelectionProxyHandler({ sqlAliasedBehavior: "sql", sqlBehavior: "sql" }) + ), + from && new Proxy( + from, + new SelectionProxyHandler({ sqlAliasedBehavior: "sql", sqlBehavior: "sql" }) + ) + ); + } + this.config.joins.push({ on: on2, table, joinType, alias: tableName }); + return this; + }; + } + leftJoin = this.createJoin("left"); + rightJoin = this.createJoin("right"); + innerJoin = this.createJoin("inner"); + fullJoin = this.createJoin("full"); + /** + * Adds a 'where' clause to the query. + * + * Calling this method will update only those rows that fulfill a specified condition. + * + * See docs: {@link https://orm.drizzle.team/docs/update} + * + * @param where the 'where' clause. + * + * @example + * You can use conditional operators and `sql function` to filter the rows to be updated. + * + * ```ts + * // Update all cars with green color + * db.update(cars).set({ color: 'red' }) + * .where(eq(cars.color, 'green')); + * // or + * db.update(cars).set({ color: 'red' }) + * .where(sql`${cars.color} = 'green'`) + * ``` + * + * You can logically combine conditional operators with `and()` and `or()` operators: + * + * ```ts + * // Update all BMW cars with a green color + * db.update(cars).set({ color: 'red' }) + * .where(and(eq(cars.color, 'green'), eq(cars.brand, 'BMW'))); + * + * // Update all cars with the green or blue color + * db.update(cars).set({ color: 'red' }) + * .where(or(eq(cars.color, 'green'), eq(cars.color, 'blue'))); + * ``` + */ + where(where) { + this.config.where = where; + return this; + } + orderBy(...columns) { + if (typeof columns[0] === "function") { + const orderBy = columns[0]( + new Proxy( + this.config.table[Table.Symbol.Columns], + new SelectionProxyHandler({ sqlAliasedBehavior: "alias", sqlBehavior: "sql" }) + ) + ); + const orderByArray = Array.isArray(orderBy) ? orderBy : [orderBy]; + this.config.orderBy = orderByArray; + } else { + const orderByArray = columns; + this.config.orderBy = orderByArray; + } + return this; + } + limit(limit) { + this.config.limit = limit; + return this; + } + returning(fields = this.config.table[SQLiteTable.Symbol.Columns]) { + this.config.returning = orderSelectedFields(fields); + return this; + } + /** @internal */ + getSQL() { + return this.dialect.buildUpdateQuery(this.config); + } + toSQL() { + const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL()); + return rest; + } + /** @internal */ + _prepare(isOneTimeQuery = true) { + return this.session[isOneTimeQuery ? "prepareOneTimeQuery" : "prepareQuery"]( + this.dialect.sqlToQuery(this.getSQL()), + this.config.returning, + this.config.returning ? "all" : "run", + true, + void 0, + { + type: "insert", + tables: extractUsedTable(this.config.table) + } + ); + } + prepare() { + return this._prepare(false); + } + run = /* @__PURE__ */ __name((placeholderValues) => { + return this._prepare().run(placeholderValues); + }, "run"); + all = /* @__PURE__ */ __name((placeholderValues) => { + return this._prepare().all(placeholderValues); + }, "all"); + get = /* @__PURE__ */ __name((placeholderValues) => { + return this._prepare().get(placeholderValues); + }, "get"); + values = /* @__PURE__ */ __name((placeholderValues) => { + return this._prepare().values(placeholderValues); + }, "values"); + async execute() { + return this.config.returning ? this.all() : this.run(); + } + $dynamic() { + return this; + } +}; + +// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/sqlite-core/query-builders/count.js +init_modules_watch_stub(); +init_performance2(); +var SQLiteCountBuilder = class _SQLiteCountBuilder extends SQL { + static { + __name(this, "SQLiteCountBuilder"); + } + constructor(params) { + super(_SQLiteCountBuilder.buildEmbeddedCount(params.source, params.filters).queryChunks); + this.params = params; + this.session = params.session; + this.sql = _SQLiteCountBuilder.buildCount( + params.source, + params.filters + ); + } + sql; + static [entityKind] = "SQLiteCountBuilderAsync"; + [Symbol.toStringTag] = "SQLiteCountBuilderAsync"; + session; + static buildEmbeddedCount(source, filters) { + return sql`(select count(*) from ${source}${sql.raw(" where ").if(filters)}${filters})`; + } + static buildCount(source, filters) { + return sql`select count(*) from ${source}${sql.raw(" where ").if(filters)}${filters}`; + } + then(onfulfilled, onrejected) { + return Promise.resolve(this.session.count(this.sql)).then( + onfulfilled, + onrejected + ); + } + catch(onRejected) { + return this.then(void 0, onRejected); + } + finally(onFinally) { + return this.then( + (value) => { + onFinally?.(); + return value; + }, + (reason) => { + onFinally?.(); + throw reason; + } + ); + } +}; + +// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/sqlite-core/query-builders/query.js +init_modules_watch_stub(); +init_performance2(); +var RelationalQueryBuilder = class { + static { + __name(this, "RelationalQueryBuilder"); + } + constructor(mode, fullSchema, schema, tableNamesMap, table, tableConfig, dialect, session2) { + this.mode = mode; + this.fullSchema = fullSchema; + this.schema = schema; + this.tableNamesMap = tableNamesMap; + this.table = table; + this.tableConfig = tableConfig; + this.dialect = dialect; + this.session = session2; + } + static [entityKind] = "SQLiteAsyncRelationalQueryBuilder"; + findMany(config2) { + return this.mode === "sync" ? new SQLiteSyncRelationalQuery( + this.fullSchema, + this.schema, + this.tableNamesMap, + this.table, + this.tableConfig, + this.dialect, + this.session, + config2 ? config2 : {}, + "many" + ) : new SQLiteRelationalQuery( + this.fullSchema, + this.schema, + this.tableNamesMap, + this.table, + this.tableConfig, + this.dialect, + this.session, + config2 ? config2 : {}, + "many" + ); + } + findFirst(config2) { + return this.mode === "sync" ? new SQLiteSyncRelationalQuery( + this.fullSchema, + this.schema, + this.tableNamesMap, + this.table, + this.tableConfig, + this.dialect, + this.session, + config2 ? { ...config2, limit: 1 } : { limit: 1 }, + "first" + ) : new SQLiteRelationalQuery( + this.fullSchema, + this.schema, + this.tableNamesMap, + this.table, + this.tableConfig, + this.dialect, + this.session, + config2 ? { ...config2, limit: 1 } : { limit: 1 }, + "first" + ); + } +}; +var SQLiteRelationalQuery = class extends QueryPromise { + static { + __name(this, "SQLiteRelationalQuery"); + } + constructor(fullSchema, schema, tableNamesMap, table, tableConfig, dialect, session2, config2, mode) { + super(); + this.fullSchema = fullSchema; + this.schema = schema; + this.tableNamesMap = tableNamesMap; + this.table = table; + this.tableConfig = tableConfig; + this.dialect = dialect; + this.session = session2; + this.config = config2; + this.mode = mode; + } + static [entityKind] = "SQLiteAsyncRelationalQuery"; + /** @internal */ + mode; + /** @internal */ + getSQL() { + return this.dialect.buildRelationalQuery({ + fullSchema: this.fullSchema, + schema: this.schema, + tableNamesMap: this.tableNamesMap, + table: this.table, + tableConfig: this.tableConfig, + queryConfig: this.config, + tableAlias: this.tableConfig.tsName + }).sql; + } + /** @internal */ + _prepare(isOneTimeQuery = false) { + const { query, builtQuery } = this._toSQL(); + return this.session[isOneTimeQuery ? "prepareOneTimeQuery" : "prepareQuery"]( + builtQuery, + void 0, + this.mode === "first" ? "get" : "all", + true, + (rawRows, mapColumnValue) => { + const rows = rawRows.map( + (row) => mapRelationalRow(this.schema, this.tableConfig, row, query.selection, mapColumnValue) + ); + if (this.mode === "first") { + return rows[0]; + } + return rows; + } + ); + } + prepare() { + return this._prepare(false); + } + _toSQL() { + const query = this.dialect.buildRelationalQuery({ + fullSchema: this.fullSchema, + schema: this.schema, + tableNamesMap: this.tableNamesMap, + table: this.table, + tableConfig: this.tableConfig, + queryConfig: this.config, + tableAlias: this.tableConfig.tsName + }); + const builtQuery = this.dialect.sqlToQuery(query.sql); + return { query, builtQuery }; + } + toSQL() { + return this._toSQL().builtQuery; + } + /** @internal */ + executeRaw() { + if (this.mode === "first") { + return this._prepare(false).get(); + } + return this._prepare(false).all(); + } + async execute() { + return this.executeRaw(); + } +}; +var SQLiteSyncRelationalQuery = class extends SQLiteRelationalQuery { + static { + __name(this, "SQLiteSyncRelationalQuery"); + } + static [entityKind] = "SQLiteSyncRelationalQuery"; + sync() { + return this.executeRaw(); + } +}; + +// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/sqlite-core/query-builders/raw.js +init_modules_watch_stub(); +init_performance2(); +var SQLiteRaw = class extends QueryPromise { + static { + __name(this, "SQLiteRaw"); + } + constructor(execute, getSQL, action, dialect, mapBatchResult) { + super(); + this.execute = execute; + this.getSQL = getSQL; + this.dialect = dialect; + this.mapBatchResult = mapBatchResult; + this.config = { action }; + } + static [entityKind] = "SQLiteRaw"; + /** @internal */ + config; + getQuery() { + return { ...this.dialect.sqlToQuery(this.getSQL()), method: this.config.action }; + } + mapResult(result, isFromBatch) { + return isFromBatch ? this.mapBatchResult(result) : result; + } + _prepare() { + return this; + } + /** @internal */ + isResponseInArrayMode() { + return false; + } +}; + +// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/sqlite-core/db.js +var BaseSQLiteDatabase = class { + static { + __name(this, "BaseSQLiteDatabase"); + } + constructor(resultKind, dialect, session2, schema) { + this.resultKind = resultKind; + this.dialect = dialect; + this.session = session2; + this._ = schema ? { + schema: schema.schema, + fullSchema: schema.fullSchema, + tableNamesMap: schema.tableNamesMap + } : { + schema: void 0, + fullSchema: {}, + tableNamesMap: {} + }; + this.query = {}; + const query = this.query; + if (this._.schema) { + for (const [tableName, columns] of Object.entries(this._.schema)) { + query[tableName] = new RelationalQueryBuilder( + resultKind, + schema.fullSchema, + this._.schema, + this._.tableNamesMap, + schema.fullSchema[tableName], + columns, + dialect, + session2 + ); + } + } + this.$cache = { invalidate: /* @__PURE__ */ __name(async (_params) => { + }, "invalidate") }; + } + static [entityKind] = "BaseSQLiteDatabase"; + query; + /** + * Creates a subquery that defines a temporary named result set as a CTE. + * + * It is useful for breaking down complex queries into simpler parts and for reusing the result set in subsequent parts of the query. + * + * See docs: {@link https://orm.drizzle.team/docs/select#with-clause} + * + * @param alias The alias for the subquery. + * + * Failure to provide an alias will result in a DrizzleTypeError, preventing the subquery from being referenced in other queries. + * + * @example + * + * ```ts + * // Create a subquery with alias 'sq' and use it in the select query + * const sq = db.$with('sq').as(db.select().from(users).where(eq(users.id, 42))); + * + * const result = await db.with(sq).select().from(sq); + * ``` + * + * To select arbitrary SQL values as fields in a CTE and reference them in other CTEs or in the main query, you need to add aliases to them: + * + * ```ts + * // Select an arbitrary SQL value as a field in a CTE and reference it in the main query + * const sq = db.$with('sq').as(db.select({ + * name: sql`upper(${users.name})`.as('name'), + * }) + * .from(users)); + * + * const result = await db.with(sq).select({ name: sq.name }).from(sq); + * ``` + */ + $with = /* @__PURE__ */ __name((alias, selection) => { + const self2 = this; + const as = /* @__PURE__ */ __name((qb) => { + if (typeof qb === "function") { + qb = qb(new QueryBuilder(self2.dialect)); + } + return new Proxy( + new WithSubquery( + qb.getSQL(), + selection ?? ("getSelectedFields" in qb ? qb.getSelectedFields() ?? {} : {}), + alias, + true + ), + new SelectionProxyHandler({ alias, sqlAliasedBehavior: "alias", sqlBehavior: "error" }) + ); + }, "as"); + return { as }; + }, "$with"); + $count(source, filters) { + return new SQLiteCountBuilder({ source, filters, session: this.session }); + } + /** + * Incorporates a previously defined CTE (using `$with`) into the main query. + * + * This method allows the main query to reference a temporary named result set. + * + * See docs: {@link https://orm.drizzle.team/docs/select#with-clause} + * + * @param queries The CTEs to incorporate into the main query. + * + * @example + * + * ```ts + * // Define a subquery 'sq' as a CTE using $with + * const sq = db.$with('sq').as(db.select().from(users).where(eq(users.id, 42))); + * + * // Incorporate the CTE 'sq' into the main query and select from it + * const result = await db.with(sq).select().from(sq); + * ``` + */ + with(...queries) { + const self2 = this; + function select(fields) { + return new SQLiteSelectBuilder({ + fields: fields ?? void 0, + session: self2.session, + dialect: self2.dialect, + withList: queries + }); + } + __name(select, "select"); + function selectDistinct(fields) { + return new SQLiteSelectBuilder({ + fields: fields ?? void 0, + session: self2.session, + dialect: self2.dialect, + withList: queries, + distinct: true + }); + } + __name(selectDistinct, "selectDistinct"); + function update(table) { + return new SQLiteUpdateBuilder(table, self2.session, self2.dialect, queries); + } + __name(update, "update"); + function insert(into) { + return new SQLiteInsertBuilder(into, self2.session, self2.dialect, queries); + } + __name(insert, "insert"); + function delete_(from) { + return new SQLiteDeleteBase(from, self2.session, self2.dialect, queries); + } + __name(delete_, "delete_"); + return { select, selectDistinct, update, insert, delete: delete_ }; + } + select(fields) { + return new SQLiteSelectBuilder({ fields: fields ?? void 0, session: this.session, dialect: this.dialect }); + } + selectDistinct(fields) { + return new SQLiteSelectBuilder({ + fields: fields ?? void 0, + session: this.session, + dialect: this.dialect, + distinct: true + }); + } + /** + * Creates an update query. + * + * Calling this method without `.where()` clause will update all rows in a table. The `.where()` clause specifies which rows should be updated. + * + * Use `.set()` method to specify which values to update. + * + * See docs: {@link https://orm.drizzle.team/docs/update} + * + * @param table The table to update. + * + * @example + * + * ```ts + * // Update all rows in the 'cars' table + * await db.update(cars).set({ color: 'red' }); + * + * // Update rows with filters and conditions + * await db.update(cars).set({ color: 'red' }).where(eq(cars.brand, 'BMW')); + * + * // Update with returning clause + * const updatedCar: Car[] = await db.update(cars) + * .set({ color: 'red' }) + * .where(eq(cars.id, 1)) + * .returning(); + * ``` + */ + update(table) { + return new SQLiteUpdateBuilder(table, this.session, this.dialect); + } + $cache; + /** + * Creates an insert query. + * + * Calling this method will create new rows in a table. Use `.values()` method to specify which values to insert. + * + * See docs: {@link https://orm.drizzle.team/docs/insert} + * + * @param table The table to insert into. + * + * @example + * + * ```ts + * // Insert one row + * await db.insert(cars).values({ brand: 'BMW' }); + * + * // Insert multiple rows + * await db.insert(cars).values([{ brand: 'BMW' }, { brand: 'Porsche' }]); + * + * // Insert with returning clause + * const insertedCar: Car[] = await db.insert(cars) + * .values({ brand: 'BMW' }) + * .returning(); + * ``` + */ + insert(into) { + return new SQLiteInsertBuilder(into, this.session, this.dialect); + } + /** + * Creates a delete query. + * + * Calling this method without `.where()` clause will delete all rows in a table. The `.where()` clause specifies which rows should be deleted. + * + * See docs: {@link https://orm.drizzle.team/docs/delete} + * + * @param table The table to delete from. + * + * @example + * + * ```ts + * // Delete all rows in the 'cars' table + * await db.delete(cars); + * + * // Delete rows with filters and conditions + * await db.delete(cars).where(eq(cars.color, 'green')); + * + * // Delete with returning clause + * const deletedCar: Car[] = await db.delete(cars) + * .where(eq(cars.id, 1)) + * .returning(); + * ``` + */ + delete(from) { + return new SQLiteDeleteBase(from, this.session, this.dialect); + } + run(query) { + const sequel = typeof query === "string" ? sql.raw(query) : query.getSQL(); + if (this.resultKind === "async") { + return new SQLiteRaw( + async () => this.session.run(sequel), + () => sequel, + "run", + this.dialect, + this.session.extractRawRunValueFromBatchResult.bind(this.session) + ); + } + return this.session.run(sequel); + } + all(query) { + const sequel = typeof query === "string" ? sql.raw(query) : query.getSQL(); + if (this.resultKind === "async") { + return new SQLiteRaw( + async () => this.session.all(sequel), + () => sequel, + "all", + this.dialect, + this.session.extractRawAllValueFromBatchResult.bind(this.session) + ); + } + return this.session.all(sequel); + } + get(query) { + const sequel = typeof query === "string" ? sql.raw(query) : query.getSQL(); + if (this.resultKind === "async") { + return new SQLiteRaw( + async () => this.session.get(sequel), + () => sequel, + "get", + this.dialect, + this.session.extractRawGetValueFromBatchResult.bind(this.session) + ); + } + return this.session.get(sequel); + } + values(query) { + const sequel = typeof query === "string" ? sql.raw(query) : query.getSQL(); + if (this.resultKind === "async") { + return new SQLiteRaw( + async () => this.session.values(sequel), + () => sequel, + "values", + this.dialect, + this.session.extractRawValuesValueFromBatchResult.bind(this.session) + ); + } + return this.session.values(sequel); + } + transaction(transaction, config2) { + return this.session.transaction(transaction, config2); + } +}; + +// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/d1/session.js +init_modules_watch_stub(); +init_performance2(); + +// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/cache/core/cache.js +init_modules_watch_stub(); +init_performance2(); +var Cache = class { + static { + __name(this, "Cache"); + } + static [entityKind] = "Cache"; +}; +var NoopCache = class extends Cache { + static { + __name(this, "NoopCache"); + } + strategy() { + return "all"; + } + static [entityKind] = "NoopCache"; + async get(_key) { + return void 0; + } + async put(_hashedQuery, _response, _tables, _config) { + } + async onMutate(_params) { + } +}; +async function hashQuery(sql2, params) { + const dataToHash = `${sql2}-${JSON.stringify(params)}`; + const encoder = new TextEncoder(); + const data2 = encoder.encode(dataToHash); + const hashBuffer = await crypto.subtle.digest("SHA-256", data2); + const hashArray = [...new Uint8Array(hashBuffer)]; + const hashHex = hashArray.map((b) => b.toString(16).padStart(2, "0")).join(""); + return hashHex; +} +__name(hashQuery, "hashQuery"); + +// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/sqlite-core/session.js +init_modules_watch_stub(); +init_performance2(); +var ExecuteResultSync = class extends QueryPromise { + static { + __name(this, "ExecuteResultSync"); + } + constructor(resultCb) { + super(); + this.resultCb = resultCb; + } + static [entityKind] = "ExecuteResultSync"; + async execute() { + return this.resultCb(); + } + sync() { + return this.resultCb(); + } +}; +var SQLitePreparedQuery = class { + static { + __name(this, "SQLitePreparedQuery"); + } + constructor(mode, executeMethod, query, cache, queryMetadata, cacheConfig) { + this.mode = mode; + this.executeMethod = executeMethod; + this.query = query; + this.cache = cache; + this.queryMetadata = queryMetadata; + this.cacheConfig = cacheConfig; + if (cache && cache.strategy() === "all" && cacheConfig === void 0) { + this.cacheConfig = { enable: true, autoInvalidate: true }; + } + if (!this.cacheConfig?.enable) { + this.cacheConfig = void 0; + } + } + static [entityKind] = "PreparedQuery"; + /** @internal */ + joinsNotNullableMap; + /** @internal */ + async queryWithCache(queryString, params, query) { + if (this.cache === void 0 || is(this.cache, NoopCache) || this.queryMetadata === void 0) { + try { + return await query(); + } catch (e) { + throw new DrizzleQueryError(queryString, params, e); + } + } + if (this.cacheConfig && !this.cacheConfig.enable) { + try { + return await query(); + } catch (e) { + throw new DrizzleQueryError(queryString, params, e); + } + } + if ((this.queryMetadata.type === "insert" || this.queryMetadata.type === "update" || this.queryMetadata.type === "delete") && this.queryMetadata.tables.length > 0) { + try { + const [res] = await Promise.all([ + query(), + this.cache.onMutate({ tables: this.queryMetadata.tables }) + ]); + return res; + } catch (e) { + throw new DrizzleQueryError(queryString, params, e); + } + } + if (!this.cacheConfig) { + try { + return await query(); + } catch (e) { + throw new DrizzleQueryError(queryString, params, e); + } + } + if (this.queryMetadata.type === "select") { + const fromCache = await this.cache.get( + this.cacheConfig.tag ?? await hashQuery(queryString, params), + this.queryMetadata.tables, + this.cacheConfig.tag !== void 0, + this.cacheConfig.autoInvalidate + ); + if (fromCache === void 0) { + let result; + try { + result = await query(); + } catch (e) { + throw new DrizzleQueryError(queryString, params, e); + } + await this.cache.put( + this.cacheConfig.tag ?? await hashQuery(queryString, params), + result, + // make sure we send tables that were used in a query only if user wants to invalidate it on each write + this.cacheConfig.autoInvalidate ? this.queryMetadata.tables : [], + this.cacheConfig.tag !== void 0, + this.cacheConfig.config + ); + return result; + } + return fromCache; + } + try { + return await query(); + } catch (e) { + throw new DrizzleQueryError(queryString, params, e); + } + } + getQuery() { + return this.query; + } + mapRunResult(result, _isFromBatch) { + return result; + } + mapAllResult(_result, _isFromBatch) { + throw new Error("Not implemented"); + } + mapGetResult(_result, _isFromBatch) { + throw new Error("Not implemented"); + } + execute(placeholderValues) { + if (this.mode === "async") { + return this[this.executeMethod](placeholderValues); + } + return new ExecuteResultSync(() => this[this.executeMethod](placeholderValues)); + } + mapResult(response, isFromBatch) { + switch (this.executeMethod) { + case "run": { + return this.mapRunResult(response, isFromBatch); + } + case "all": { + return this.mapAllResult(response, isFromBatch); + } + case "get": { + return this.mapGetResult(response, isFromBatch); + } + } + } +}; +var SQLiteSession = class { + static { + __name(this, "SQLiteSession"); + } + constructor(dialect) { + this.dialect = dialect; + } + static [entityKind] = "SQLiteSession"; + prepareOneTimeQuery(query, fields, executeMethod, isResponseInArrayMode, customResultMapper, queryMetadata, cacheConfig) { + return this.prepareQuery( + query, + fields, + executeMethod, + isResponseInArrayMode, + customResultMapper, + queryMetadata, + cacheConfig + ); + } + run(query) { + const staticQuery = this.dialect.sqlToQuery(query); + try { + return this.prepareOneTimeQuery(staticQuery, void 0, "run", false).run(); + } catch (err) { + throw new DrizzleError({ cause: err, message: `Failed to run the query '${staticQuery.sql}'` }); + } + } + /** @internal */ + extractRawRunValueFromBatchResult(result) { + return result; + } + all(query) { + return this.prepareOneTimeQuery(this.dialect.sqlToQuery(query), void 0, "run", false).all(); + } + /** @internal */ + extractRawAllValueFromBatchResult(_result) { + throw new Error("Not implemented"); + } + get(query) { + return this.prepareOneTimeQuery(this.dialect.sqlToQuery(query), void 0, "run", false).get(); + } + /** @internal */ + extractRawGetValueFromBatchResult(_result) { + throw new Error("Not implemented"); + } + values(query) { + return this.prepareOneTimeQuery(this.dialect.sqlToQuery(query), void 0, "run", false).values(); + } + async count(sql2) { + const result = await this.values(sql2); + return result[0][0]; + } + /** @internal */ + extractRawValuesValueFromBatchResult(_result) { + throw new Error("Not implemented"); + } +}; +var SQLiteTransaction = class extends BaseSQLiteDatabase { + static { + __name(this, "SQLiteTransaction"); + } + constructor(resultType, dialect, session2, schema, nestedIndex = 0) { + super(resultType, dialect, session2, schema); + this.schema = schema; + this.nestedIndex = nestedIndex; + } + static [entityKind] = "SQLiteTransaction"; + rollback() { + throw new TransactionRollbackError(); + } +}; + +// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/d1/session.js +var SQLiteD1Session = class extends SQLiteSession { + static { + __name(this, "SQLiteD1Session"); + } + constructor(client, dialect, schema, options = {}) { + super(dialect); + this.client = client; + this.schema = schema; + this.options = options; + this.logger = options.logger ?? new NoopLogger(); + this.cache = options.cache ?? new NoopCache(); + } + static [entityKind] = "SQLiteD1Session"; + logger; + cache; + prepareQuery(query, fields, executeMethod, isResponseInArrayMode, customResultMapper, queryMetadata, cacheConfig) { + const stmt = this.client.prepare(query.sql); + return new D1PreparedQuery( + stmt, + query, + this.logger, + this.cache, + queryMetadata, + cacheConfig, + fields, + executeMethod, + isResponseInArrayMode, + customResultMapper + ); + } + async batch(queries) { + const preparedQueries = []; + const builtQueries = []; + for (const query of queries) { + const preparedQuery = query._prepare(); + const builtQuery = preparedQuery.getQuery(); + preparedQueries.push(preparedQuery); + if (builtQuery.params.length > 0) { + builtQueries.push(preparedQuery.stmt.bind(...builtQuery.params)); + } else { + const builtQuery2 = preparedQuery.getQuery(); + builtQueries.push( + this.client.prepare(builtQuery2.sql).bind(...builtQuery2.params) + ); + } + } + const batchResults = await this.client.batch(builtQueries); + return batchResults.map((result, i) => preparedQueries[i].mapResult(result, true)); + } + extractRawAllValueFromBatchResult(result) { + return result.results; + } + extractRawGetValueFromBatchResult(result) { + return result.results[0]; + } + extractRawValuesValueFromBatchResult(result) { + return d1ToRawMapping(result.results); + } + async transaction(transaction, config2) { + const tx = new D1Transaction("async", this.dialect, this, this.schema); + await this.run(sql.raw(`begin${config2?.behavior ? " " + config2.behavior : ""}`)); + try { + const result = await transaction(tx); + await this.run(sql`commit`); + return result; + } catch (err) { + await this.run(sql`rollback`); + throw err; + } + } +}; +var D1Transaction = class _D1Transaction extends SQLiteTransaction { + static { + __name(this, "D1Transaction"); + } + static [entityKind] = "D1Transaction"; + async transaction(transaction) { + const savepointName = `sp${this.nestedIndex}`; + const tx = new _D1Transaction("async", this.dialect, this.session, this.schema, this.nestedIndex + 1); + await this.session.run(sql.raw(`savepoint ${savepointName}`)); + try { + const result = await transaction(tx); + await this.session.run(sql.raw(`release savepoint ${savepointName}`)); + return result; + } catch (err) { + await this.session.run(sql.raw(`rollback to savepoint ${savepointName}`)); + throw err; + } + } +}; +function d1ToRawMapping(results) { + const rows = []; + for (const row of results) { + const entry = Object.keys(row).map((k) => row[k]); + rows.push(entry); + } + return rows; +} +__name(d1ToRawMapping, "d1ToRawMapping"); +var D1PreparedQuery = class extends SQLitePreparedQuery { + static { + __name(this, "D1PreparedQuery"); + } + constructor(stmt, query, logger, cache, queryMetadata, cacheConfig, fields, executeMethod, _isResponseInArrayMode, customResultMapper) { + super("async", executeMethod, query, cache, queryMetadata, cacheConfig); + this.logger = logger; + this._isResponseInArrayMode = _isResponseInArrayMode; + this.customResultMapper = customResultMapper; + this.fields = fields; + this.stmt = stmt; + } + static [entityKind] = "D1PreparedQuery"; + /** @internal */ + customResultMapper; + /** @internal */ + fields; + /** @internal */ + stmt; + async run(placeholderValues) { + const params = fillPlaceholders(this.query.params, placeholderValues ?? {}); + this.logger.logQuery(this.query.sql, params); + return await this.queryWithCache(this.query.sql, params, async () => { + return this.stmt.bind(...params).run(); + }); + } + async all(placeholderValues) { + const { fields, query, logger, stmt, customResultMapper } = this; + if (!fields && !customResultMapper) { + const params = fillPlaceholders(query.params, placeholderValues ?? {}); + logger.logQuery(query.sql, params); + return await this.queryWithCache(query.sql, params, async () => { + return stmt.bind(...params).all().then(({ results }) => this.mapAllResult(results)); + }); + } + const rows = await this.values(placeholderValues); + return this.mapAllResult(rows); + } + mapAllResult(rows, isFromBatch) { + if (isFromBatch) { + rows = d1ToRawMapping(rows.results); + } + if (!this.fields && !this.customResultMapper) { + return rows; + } + if (this.customResultMapper) { + return this.customResultMapper(rows); + } + return rows.map((row) => mapResultRow(this.fields, row, this.joinsNotNullableMap)); + } + async get(placeholderValues) { + const { fields, joinsNotNullableMap, query, logger, stmt, customResultMapper } = this; + if (!fields && !customResultMapper) { + const params = fillPlaceholders(query.params, placeholderValues ?? {}); + logger.logQuery(query.sql, params); + return await this.queryWithCache(query.sql, params, async () => { + return stmt.bind(...params).all().then(({ results }) => results[0]); + }); + } + const rows = await this.values(placeholderValues); + if (!rows[0]) { + return void 0; + } + if (customResultMapper) { + return customResultMapper(rows); + } + return mapResultRow(fields, rows[0], joinsNotNullableMap); + } + mapGetResult(result, isFromBatch) { + if (isFromBatch) { + result = d1ToRawMapping(result.results)[0]; + } + if (!this.fields && !this.customResultMapper) { + return result; + } + if (this.customResultMapper) { + return this.customResultMapper([result]); + } + return mapResultRow(this.fields, result, this.joinsNotNullableMap); + } + async values(placeholderValues) { + const params = fillPlaceholders(this.query.params, placeholderValues ?? {}); + this.logger.logQuery(this.query.sql, params); + return await this.queryWithCache(this.query.sql, params, async () => { + return this.stmt.bind(...params).raw(); + }); + } + /** @internal */ + isResponseInArrayMode() { + return this._isResponseInArrayMode; + } +}; + +// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/d1/driver.js +var DrizzleD1Database = class extends BaseSQLiteDatabase { + static { + __name(this, "DrizzleD1Database"); + } + static [entityKind] = "D1Database"; + async batch(batch) { + return this.session.batch(batch); + } +}; +function drizzle(client, config2 = {}) { + const dialect = new SQLiteAsyncDialect({ casing: config2.casing }); + let logger; + if (config2.logger === true) { + logger = new DefaultLogger(); + } else if (config2.logger !== false) { + logger = config2.logger; + } + let schema; + if (config2.schema) { + const tablesConfig = extractTablesRelationalConfig( + config2.schema, + createTableRelationsHelpers + ); + schema = { + fullSchema: config2.schema, + schema: tablesConfig.tables, + tableNamesMap: tablesConfig.tableNamesMap + }; + } + const session2 = new SQLiteD1Session(client, dialect, schema, { logger, cache: config2.cache }); + const db = new DrizzleD1Database("async", dialect, session2, schema); + db.$client = client; + db.$cache = config2.cache; + if (db.$cache) { + db.$cache["invalidate"] = config2.cache?.onMutate; + } + return db; +} +__name(drizzle, "drizzle"); + +// src/bot/index.ts +init_modules_watch_stub(); +init_performance2(); + +// src/bot/storage.ts +init_modules_watch_stub(); +init_performance2(); +var DatabaseSessionStorage = class { + constructor(sessionRepo, ttl) { + this.sessionRepo = sessionRepo; + this.ttl = ttl; + } + static { + __name(this, "DatabaseSessionStorage"); + } + async read(key) { + const value = await this.sessionRepo.get(key); + if (!value) return void 0; + try { + return JSON.parse(value); + } catch (error) { + console.error("Failed to parse session data:", error); + return void 0; + } + } + async write(key, value) { + const expiresAt = this.ttl ? Date.now() + this.ttl * 1e3 : void 0; + await this.sessionRepo.set(key, JSON.stringify(value), expiresAt); + } + async delete(key) { + await this.sessionRepo.delete(key); + } + async has(key) { + const value = await this.sessionRepo.get(key); + return value !== void 0; + } + /** + * Clean up expired sessions + * Should be called periodically (e.g., via cron job) + */ + async cleanup() { + await this.sessionRepo.cleanup(); + } +}; + +// src/bot/commands/index.ts +init_modules_watch_stub(); +init_performance2(); + +// src/bot/commands/start.command.ts +init_modules_watch_stub(); +init_performance2(); + +// src/bot/helpers.ts +init_modules_watch_stub(); +init_performance2(); +async function sendSettingsMenu(ctx, chat) { + const settings = chat.settings; + if (!settings) return; + const createCheckmark = /* @__PURE__ */ __name((value) => value ? "\u2705" : "\u274C", "createCheckmark"); + const keyboard = new InlineKeyboard().text( + `${createCheckmark(settings.gameChangeNotification)} ${ctx.t("commands.start.game_change_notification_setting.button")}`, + "toggle_game_change" + ).row().text( + `${createCheckmark(settings.offlineNotification)} ${ctx.t("commands.start.offline_notification.button")}`, + "toggle_offline" + ).row().text( + `${createCheckmark(settings.titleChangeNotification)} ${ctx.t("commands.start.title_change_notification_setting.button")}`, + "toggle_title_change" + ).row().text( + `${createCheckmark(settings.gameAndTitleChangeNotification)} ${ctx.t("commands.start.game_and_title_change_notification_setting.button")}`, + "toggle_game_and_title" + ).row().text( + `${createCheckmark(settings.imageInNotification)} ${ctx.t("commands.start.image_in_notification_setting.button")}`, + "toggle_image" + ).row().text( + ctx.t("commands.start.language.button"), + "language_picker" + ).row().url("Github", "https://github.com/Satont/twitch-notifier"); + const description = ctx.t("bot.description"); + if (ctx.callbackQuery) { + await ctx.editMessageText(description, { reply_markup: keyboard }); + } else { + await ctx.reply(description, { reply_markup: keyboard }); + } +} +__name(sendSettingsMenu, "sendSettingsMenu"); +async function sendLanguagePicker(ctx) { + const keyboard = new InlineKeyboard(); + const locales = ctx.services.i18n.getAvailableLocales(); + for (const locale of locales) { + const emoji = ctx.services.i18n.t(locale, "language.emoji"); + const name = ctx.services.i18n.t(locale, "language.name"); + keyboard.text(`${emoji} ${name}`, `language_picker_set_${locale}`).row(); + } + keyboard.text("\xAB", "start_command_menu"); + const text2 = ctx.t("language.select"); + if (ctx.callbackQuery) { + await ctx.editMessageText(text2, { reply_markup: keyboard }); + } else { + await ctx.reply(text2, { reply_markup: keyboard }); + } +} +__name(sendLanguagePicker, "sendLanguagePicker"); +async function buildFollowsKeyboard(ctx, chatId) { + const follows2 = await ctx.services.followRepo.findByChatId(chatId); + const keyboard = new InlineKeyboard(); + for (const follow of follows2) { + const channel = await ctx.services.channelRepo.findById(follow.channelId); + if (!channel) continue; + const twitchUser = await ctx.services.twitch.getUserById(channel.channelId); + if (!twitchUser) continue; + keyboard.text(twitchUser.displayName, `channels_unfollow_${channel.channelId}`).row(); + } + if (ctx.session.followsMenu) { + const { currentPage, totalPages } = ctx.session.followsMenu; + if (totalPages > 1) { + keyboard.text("\xAB", "channels_unfollow_prev_page"); + keyboard.text("\xBB", "channels_unfollow_next_page"); + } + } + return keyboard; +} +__name(buildFollowsKeyboard, "buildFollowsKeyboard"); +async function handleToggleSetting(ctx, data2, chat) { + const chatId = ctx.chat?.id; + if (!chatId || !chat.settings) return; + const updates = {}; + switch (data2) { + case "toggle_game_change": + updates.gameChangeNotification = !chat.settings.gameChangeNotification; + chat.settings.gameChangeNotification = updates.gameChangeNotification; + break; + case "toggle_offline": + updates.offlineNotification = !chat.settings.offlineNotification; + chat.settings.offlineNotification = updates.offlineNotification; + break; + case "toggle_title_change": + updates.titleChangeNotification = !chat.settings.titleChangeNotification; + chat.settings.titleChangeNotification = updates.titleChangeNotification; + break; + case "toggle_game_and_title": + updates.gameAndTitleChangeNotification = !chat.settings.gameAndTitleChangeNotification; + chat.settings.gameAndTitleChangeNotification = updates.gameAndTitleChangeNotification; + break; + case "toggle_image": + updates.imageInNotification = !chat.settings.imageInNotification; + chat.settings.imageInNotification = updates.imageInNotification; + break; + } + if (Object.keys(updates).length > 0) { + await ctx.services.chatRepo.updateSettings(chat.settings.id, updates); + } +} +__name(handleToggleSetting, "handleToggleSetting"); +async function handleUnfollow(ctx, chat, channelIdFromCallback) { + const channel = await ctx.services.channelRepo.findById(channelIdFromCallback); + if (!channel) { + await ctx.answerCallbackQuery("Channel not found"); + return; + } + const follow = await ctx.services.followRepo.findByChatAndChannel(chat.id, channel.id); + if (!follow) { + await ctx.answerCallbackQuery("Already unfollowed"); + return; + } + const twitchUser = await ctx.services.twitch.getUserById(channel.channelId); + const streamerName = twitchUser?.displayName || channel.channelId; + await ctx.services.followRepo.delete(follow.id); + const remainingFollows = await ctx.services.followRepo.findByChannelId(channel.id); + if (remainingFollows.length === 0) { + try { + await ctx.services.eventsub.unsubscribeFromChannel(channel.channelId); + console.log(`Unsubscribed from EventSub for channel ${channel.channelId}`); + } catch (error) { + console.error(`Failed to unsubscribe from EventSub for ${channel.channelId}:`, error); + } + } + await ctx.answerCallbackQuery( + ctx.t("commands.unfollow.success", { + streamer: streamerName + }) + ); + const totalFollows = await ctx.services.followRepo.countByChatId(chat.id); + if (totalFollows === 0) { + await ctx.editMessageText("You are not following any channels."); + await ctx.editMessageReplyMarkup({ reply_markup: new InlineKeyboard() }); + return; + } + const keyboard = await buildFollowsKeyboard(ctx, chat.id); + await ctx.editMessageText( + ctx.t("commands.follows.total", { + count: totalFollows.toString() + }), + { + reply_markup: keyboard + } + ); +} +__name(handleUnfollow, "handleUnfollow"); + +// src/bot/commands/start.command.ts +var startCommand = new Composer(); +startCommand.command(["start", "help", "info", "settings"], async (ctx) => { + const chatId = ctx.chat?.id; + if (!chatId) return; + let chat = await ctx.services.chatRepo.findByChatId(chatId, "telegram"); + if (!chat) { + await ctx.services.chatRepo.create(chatId.toString(), "telegram"); + chat = await ctx.services.chatRepo.findByChatId(chatId, "telegram"); + } + if (chat?.settings) { + ctx.session.language = chat.settings.language; + } + if (chat) { + await sendSettingsMenu(ctx, chat); + } +}); + +// src/bot/commands/follow.command.ts +init_modules_watch_stub(); +init_performance2(); +var followCommand = new Composer(); +followCommand.command("follow", async (ctx) => { + const text2 = ctx.message?.text?.replace("/follow", "").trim(); + if (!text2) { + await ctx.reply( + ctx.t("commands.follow.enter") + ); + ctx.session.scene = "follow"; + return; + } + await handleFollow(ctx, text2); +}); +followCommand.on("message:text", async (ctx, next) => { + if (ctx.session.scene === "follow") { + await handleFollow(ctx, ctx.message.text); + ctx.session.scene = void 0; + return; + } + await next(); +}); +async function handleFollow(ctx, text2) { + const chatId = ctx.chat?.id; + if (!chatId) return; + const chat = await ctx.services.chatRepo.findByChatId(chatId, "telegram"); + if (!chat) return; + const twitchLinkRegex = /(?:https?:\/\/)?(?:www\.)?twitch\.tv\/(\w+)/g; + const matches = Array.from(text2.matchAll(twitchLinkRegex)); + const usernames = matches.length > 0 ? matches.map((m2) => m2[1]) : [text2.trim()]; + const results = []; + for (const username of usernames) { + if (!/^[a-zA-Z0-9_]{3,25}$/.test(username)) { + results.push( + ctx.t( + "commands.follow.errors.badUsername", + { streamer: username } + ) + ); + continue; + } + try { + const twitchUser = await ctx.services.twitch.getUserByLogin(username); + if (!twitchUser) { + results.push( + ctx.t( + "commands.follow.errors.streamerNotFound", + { streamer: username } + ) + ); + continue; + } + let channel = await ctx.services.channelRepo.findByChannelId(twitchUser.id, "twitch"); + if (!channel) { + channel = await ctx.services.channelRepo.create(twitchUser.id, "twitch"); + } + try { + await ctx.services.followRepo.create(chat.id, channel.id); + const hasSubscriptions = await ctx.services.eventsub.hasActiveSubscriptions(twitchUser.id); + if (!hasSubscriptions) { + try { + await ctx.services.eventsub.subscribeToChannel(twitchUser.id); + console.log(`Subscribed to EventSub for channel ${twitchUser.id}`); + } catch (eventSubError) { + console.error(`Failed to subscribe to EventSub for ${twitchUser.id}:`, eventSubError); + } + } + results.push( + ctx.t( + "commands.follow.success", + { streamer: username } + ) + ); + } catch (error) { + if (error.message?.includes("UNIQUE constraint failed")) { + results.push( + ctx.t( + "commands.follow.errors.alreadyFollowed", + { streamer: username } + ) + ); + } else { + throw error; + } + } + } catch (error) { + console.error("Error following user:", error); + results.push(`${username} - internal error`); + } + } + await ctx.reply(results.join("\n")); +} +__name(handleFollow, "handleFollow"); + +// src/bot/commands/follows.command.ts +init_modules_watch_stub(); +init_performance2(); +var followsCommand = new Composer(); +followsCommand.command(["follows", "unfollow"], async (ctx) => { + const chatId = ctx.chat?.id; + if (!chatId) return; + const chat = await ctx.services.chatRepo.findByChatId(chatId, "telegram"); + if (!chat) return; + ctx.session.followsMenu = { + currentPage: 1, + totalPages: 1 + }; + const totalFollows = await ctx.services.followRepo.countByChatId(chat.id); + if (totalFollows === 0) { + await ctx.reply("You are not following any channels."); + return; + } + const keyboard = await buildFollowsKeyboard(ctx, chat.id); + await ctx.reply( + ctx.t( + "commands.follows.total", + { count: totalFollows.toString() } + ), + { + reply_markup: keyboard + } + ); +}); + +// src/bot/commands/live.command.ts +init_modules_watch_stub(); +init_performance2(); +var liveCommand = new Composer(); +liveCommand.command("live", async (ctx) => { + const chatId = ctx.chat?.id; + if (!chatId) return; + const chat = await ctx.services.chatRepo.findByChatId(chatId, "telegram"); + if (!chat) return; + const follows2 = await ctx.services.followRepo.findByChatId(chat.id); + if (follows2.length === 0) { + await ctx.reply("You are not following any channels."); + return; + } + const channelIds = []; + for (const follow of follows2) { + const channel = await ctx.services.channelRepo.findById(follow.channelId); + if (channel) { + channelIds.push(channel.channelId); + } + } + if (channelIds.length === 0) { + await ctx.reply("No channels found."); + return; + } + const liveChannels = []; + for (const channelId of channelIds) { + const stream = await ctx.services.twitch.getStreamByUserId(channelId); + if (stream) { + const user = await ctx.services.twitch.getUserById(channelId); + if (user) { + liveChannels.push({ + name: user.displayName, + login: user.name, + startedAt: stream.startDate, + title: stream.title, + category: stream.gameName, + viewers: stream.viewers + }); + } + } + } + if (liveChannels.length === 0) { + await ctx.reply("No one is online."); + return; + } + const messages = []; + for (const channel of liveChannels) { + const channelMessage = []; + channelMessage.push( + `\u{1F7E2} ${channel.name} - ${channel.viewers} \u{1F441}\uFE0F\uFE0F` + ); + if (channel.category) { + channelMessage.push(`\u{1F3AE} ${channel.category}`); + } + if (channel.title) { + channelMessage.push(`\u{1F4DD} ${channel.title}`); + } + const uptime2 = Date.now() - channel.startedAt.getTime(); + const hours = Math.floor(uptime2 / 36e5); + const minutes = Math.floor(uptime2 % 36e5 / 6e4); + const seconds = Math.floor(uptime2 % 6e4 / 1e3); + let uptimeStr = "\u231B "; + if (hours > 0) uptimeStr += `${hours}h `; + if (minutes > 0) uptimeStr += `${minutes}m `; + if (seconds > 0) uptimeStr += `${seconds}s `; + channelMessage.push(uptimeStr); + messages.push(channelMessage.join("\n")); + } + await ctx.reply(messages.join("\n\n"), { + parse_mode: "HTML", + link_preview_options: { is_disabled: true } + }); +}); + +// src/bot/commands/broadcast.command.ts +init_modules_watch_stub(); +init_performance2(); +function createBroadcastCommand(env) { + const broadcast = new Composer(); + const isAdmin = /* @__PURE__ */ __name((userId) => { + const admins = env.TELEGRAM_BOT_ADMINS.split(",").map((id) => parseInt(id.trim())); + return admins.includes(userId); + }, "isAdmin"); + broadcast.command("broadcast", async (ctx) => { + const userId = ctx.from?.id; + if (!userId || !isAdmin(userId)) { + return; + } + const text2 = ctx.message?.text?.replace("/broadcast", "").trim(); + if (!text2) { + await ctx.reply("Usage: /broadcast "); + return; + } + const allChats = await ctx.services.chatRepo.findAllByService("telegram"); + let sent = 0; + let failed = 0; + for (const chat of allChats) { + const chatIdNum = parseInt(chat.chatId); + if (chatIdNum <= 0) continue; + try { + await ctx.api.sendMessage(chatIdNum, text2); + sent++; + } catch (error) { + console.error(`Failed to send to ${chat.chatId}:`, error); + failed++; + } + } + await ctx.reply(`Broadcast completed! +Sent: ${sent} +Failed: ${failed}`); + }); + return broadcast; +} +__name(createBroadcastCommand, "createBroadcastCommand"); + +// src/bot/commands/change-channel-id.command.ts +init_modules_watch_stub(); +init_performance2(); +function createChangeChannelIdCommand(env) { + const changeChannelId = new Composer(); + const isAdmin = /* @__PURE__ */ __name((userId) => { + const admins = env.TELEGRAM_BOT_ADMINS.split(",").map((id) => parseInt(id.trim())); + return admins.includes(userId); + }, "isAdmin"); + changeChannelId.command("change_channel_id", async (ctx) => { + const userId = ctx.from?.id; + if (!userId || !isAdmin(userId)) { + return; + } + const text2 = ctx.message?.text?.replace("/change_channel_id", "").trim(); + if (!text2) { + await ctx.reply("Usage: /change_channel_id "); + return; + } + const parts = text2.split(" "); + if (parts.length !== 2) { + await ctx.reply("Usage: /change_channel_id "); + return; + } + const [oldId, newId] = parts; + try { + await ctx.services.channelRepo.updateChannelId(oldId, newId, "twitch"); + await ctx.reply("Channel ID updated successfully!"); + } catch (error) { + console.error("Error updating channel ID:", error); + await ctx.reply("Error updating channel ID."); + } + }); + return changeChannelId; +} +__name(createChangeChannelIdCommand, "createChangeChannelIdCommand"); + +// src/bot/commands/callback.handler.ts +init_modules_watch_stub(); +init_performance2(); +var callbackQueryHandler = new Composer(); +callbackQueryHandler.on("callback_query:data", async (ctx) => { + const data2 = ctx.callbackQuery.data; + const chatId = ctx.chat?.id; + if (!chatId) return; + const chat = await ctx.services.chatRepo.findByChatId(chatId, "telegram"); + if (!chat || !chat.settings) return; + if (data2.startsWith("toggle_")) { + await handleToggleSetting(ctx, data2, chat); + await sendSettingsMenu(ctx, chat); + } else if (data2 === "language_picker") { + await sendLanguagePicker(ctx); + } else if (data2.startsWith("language_picker_set_")) { + const lang = data2.replace("language_picker_set_", ""); + if (ctx.services.i18n.isValidLocale(lang)) { + await ctx.services.chatRepo.updateSettings(chat.settings.id, { language: lang }); + ctx.session.language = lang; + await ctx.answerCallbackQuery( + ctx.services.i18n.t(lang, "language.changed") + ); + await sendLanguagePicker(ctx); + } + } else if (data2 === "start_command_menu") { + await sendSettingsMenu(ctx, chat); + } else if (data2.startsWith("channels_unfollow_")) { + const channelId = data2.replace("channels_unfollow_", ""); + await handleUnfollow(ctx, chat, channelId); + } else if (data2 === "channels_unfollow_prev_page") { + if (ctx.session.followsMenu && ctx.session.followsMenu.currentPage > 1) { + ctx.session.followsMenu.currentPage--; + } + const keyboard = await buildFollowsKeyboard(ctx, chat.id); + await ctx.editMessageReplyMarkup({ reply_markup: keyboard }); + } else if (data2 === "channels_unfollow_next_page") { + if (ctx.session.followsMenu && ctx.session.followsMenu.currentPage < ctx.session.followsMenu.totalPages) { + ctx.session.followsMenu.currentPage++; + } + const keyboard = await buildFollowsKeyboard(ctx, chat.id); + await ctx.editMessageReplyMarkup({ reply_markup: keyboard }); + } + await ctx.answerCallbackQuery(); +}); + +// src/bot/index.ts +function createBot(env, services) { + const bot = new Bot(env.TELEGRAM_TOKEN); + const sessionStorage = new DatabaseSessionStorage( + services.sessionRepo, + 86400 + // 24 hours TTL + ); + bot.use(session({ + initial: /* @__PURE__ */ __name(() => ({ + language: "en", + followsMenu: { + currentPage: 1, + totalPages: 1 + } + }), "initial"), + storage: sessionStorage + })); + bot.use(async (ctx, next) => { + ctx.env = env; + ctx.services = services; + await next(); + }); + bot.use(services.i18n.middleware()); + bot.use(startCommand); + bot.use(followCommand); + bot.use(followsCommand); + bot.use(liveCommand); + bot.use(createBroadcastCommand(env)); + bot.use(createChangeChannelIdCommand(env)); + bot.use(callbackQueryHandler); + return bot; +} +__name(createBot, "createBot"); + +// src/services/i18n.service.ts +init_modules_watch_stub(); +init_performance2(); + +// node_modules/.pnpm/i18next@25.8.14_typescript@5.9.3/node_modules/i18next/dist/esm/i18next.js +init_modules_watch_stub(); +init_performance2(); +var isString = /* @__PURE__ */ __name((obj) => typeof obj === "string", "isString"); +var defer = /* @__PURE__ */ __name(() => { + let res; + let rej; + const promise = new Promise((resolve, reject) => { + res = resolve; + rej = reject; + }); + promise.resolve = res; + promise.reject = rej; + return promise; +}, "defer"); +var makeString = /* @__PURE__ */ __name((object) => { + if (object == null) return ""; + return "" + object; +}, "makeString"); +var copy = /* @__PURE__ */ __name((a, s2, t2) => { + a.forEach((m2) => { + if (s2[m2]) t2[m2] = s2[m2]; + }); +}, "copy"); +var lastOfPathSeparatorRegExp = /###/g; +var cleanKey = /* @__PURE__ */ __name((key) => key && key.indexOf("###") > -1 ? key.replace(lastOfPathSeparatorRegExp, ".") : key, "cleanKey"); +var canNotTraverseDeeper = /* @__PURE__ */ __name((object) => !object || isString(object), "canNotTraverseDeeper"); +var getLastOfPath = /* @__PURE__ */ __name((object, path, Empty) => { + const stack = !isString(path) ? path : path.split("."); + let stackIndex = 0; + while (stackIndex < stack.length - 1) { + if (canNotTraverseDeeper(object)) return {}; + const key = cleanKey(stack[stackIndex]); + if (!object[key] && Empty) object[key] = new Empty(); + if (Object.prototype.hasOwnProperty.call(object, key)) { + object = object[key]; + } else { + object = {}; + } + ++stackIndex; + } + if (canNotTraverseDeeper(object)) return {}; + return { + obj: object, + k: cleanKey(stack[stackIndex]) + }; +}, "getLastOfPath"); +var setPath = /* @__PURE__ */ __name((object, path, newValue) => { + const { + obj, + k + } = getLastOfPath(object, path, Object); + if (obj !== void 0 || path.length === 1) { + obj[k] = newValue; + return; + } + let e = path[path.length - 1]; + let p = path.slice(0, path.length - 1); + let last = getLastOfPath(object, p, Object); + while (last.obj === void 0 && p.length) { + e = `${p[p.length - 1]}.${e}`; + p = p.slice(0, p.length - 1); + last = getLastOfPath(object, p, Object); + if (last?.obj && typeof last.obj[`${last.k}.${e}`] !== "undefined") { + last.obj = void 0; + } + } + last.obj[`${last.k}.${e}`] = newValue; +}, "setPath"); +var pushPath = /* @__PURE__ */ __name((object, path, newValue, concat2) => { + const { + obj, + k + } = getLastOfPath(object, path, Object); + obj[k] = obj[k] || []; + obj[k].push(newValue); +}, "pushPath"); +var getPath2 = /* @__PURE__ */ __name((object, path) => { + const { + obj, + k + } = getLastOfPath(object, path); + if (!obj) return void 0; + if (!Object.prototype.hasOwnProperty.call(obj, k)) return void 0; + return obj[k]; +}, "getPath"); +var getPathWithDefaults = /* @__PURE__ */ __name((data2, defaultData, key) => { + const value = getPath2(data2, key); + if (value !== void 0) { + return value; + } + return getPath2(defaultData, key); +}, "getPathWithDefaults"); +var deepExtend = /* @__PURE__ */ __name((target, source, overwrite) => { + for (const prop in source) { + if (prop !== "__proto__" && prop !== "constructor") { + if (prop in target) { + if (isString(target[prop]) || target[prop] instanceof String || isString(source[prop]) || source[prop] instanceof String) { + if (overwrite) target[prop] = source[prop]; + } else { + deepExtend(target[prop], source[prop], overwrite); + } + } else { + target[prop] = source[prop]; + } + } + } + return target; +}, "deepExtend"); +var regexEscape = /* @__PURE__ */ __name((str2) => str2.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"), "regexEscape"); +var _entityMap = { + "&": "&", + "<": "<", + ">": ">", + '"': """, + "'": "'", + "/": "/" +}; +var escape = /* @__PURE__ */ __name((data2) => { + if (isString(data2)) { + return data2.replace(/[&<>"'\/]/g, (s2) => _entityMap[s2]); + } + return data2; +}, "escape"); +var RegExpCache = class { + static { + __name(this, "RegExpCache"); + } + constructor(capacity) { + this.capacity = capacity; + this.regExpMap = /* @__PURE__ */ new Map(); + this.regExpQueue = []; + } + getRegExp(pattern) { + const regExpFromCache = this.regExpMap.get(pattern); + if (regExpFromCache !== void 0) { + return regExpFromCache; + } + const regExpNew = new RegExp(pattern); + if (this.regExpQueue.length === this.capacity) { + this.regExpMap.delete(this.regExpQueue.shift()); + } + this.regExpMap.set(pattern, regExpNew); + this.regExpQueue.push(pattern); + return regExpNew; + } +}; +var chars = [" ", ",", "?", "!", ";"]; +var looksLikeObjectPathRegExpCache = new RegExpCache(20); +var looksLikeObjectPath = /* @__PURE__ */ __name((key, nsSeparator, keySeparator) => { + nsSeparator = nsSeparator || ""; + keySeparator = keySeparator || ""; + const possibleChars = chars.filter((c) => nsSeparator.indexOf(c) < 0 && keySeparator.indexOf(c) < 0); + if (possibleChars.length === 0) return true; + const r = looksLikeObjectPathRegExpCache.getRegExp(`(${possibleChars.map((c) => c === "?" ? "\\?" : c).join("|")})`); + let matched = !r.test(key); + if (!matched) { + const ki = key.indexOf(keySeparator); + if (ki > 0 && !r.test(key.substring(0, ki))) { + matched = true; + } + } + return matched; +}, "looksLikeObjectPath"); +var deepFind = /* @__PURE__ */ __name((obj, path, keySeparator = ".") => { + if (!obj) return void 0; + if (obj[path]) { + if (!Object.prototype.hasOwnProperty.call(obj, path)) return void 0; + return obj[path]; + } + const tokens = path.split(keySeparator); + let current = obj; + for (let i = 0; i < tokens.length; ) { + if (!current || typeof current !== "object") { + return void 0; + } + let next; + let nextPath = ""; + for (let j = i; j < tokens.length; ++j) { + if (j !== i) { + nextPath += keySeparator; + } + nextPath += tokens[j]; + next = current[nextPath]; + if (next !== void 0) { + if (["string", "number", "boolean"].indexOf(typeof next) > -1 && j < tokens.length - 1) { + continue; + } + i += j - i + 1; + break; + } + } + current = next; + } + return current; +}, "deepFind"); +var getCleanedCode = /* @__PURE__ */ __name((code) => code?.replace(/_/g, "-"), "getCleanedCode"); +var consoleLogger = { + type: "logger", + log(args) { + this.output("log", args); + }, + warn(args) { + this.output("warn", args); + }, + error(args) { + this.output("error", args); + }, + output(type, args) { + console?.[type]?.apply?.(console, args); + } +}; +var Logger = class _Logger { + static { + __name(this, "Logger"); + } + constructor(concreteLogger, options = {}) { + this.init(concreteLogger, options); + } + init(concreteLogger, options = {}) { + this.prefix = options.prefix || "i18next:"; + this.logger = concreteLogger || consoleLogger; + this.options = options; + this.debug = options.debug; + } + log(...args) { + return this.forward(args, "log", "", true); + } + warn(...args) { + return this.forward(args, "warn", "", true); + } + error(...args) { + return this.forward(args, "error", ""); + } + deprecate(...args) { + return this.forward(args, "warn", "WARNING DEPRECATED: ", true); + } + forward(args, lvl, prefix, debugOnly) { + if (debugOnly && !this.debug) return null; + if (isString(args[0])) args[0] = `${prefix}${this.prefix} ${args[0]}`; + return this.logger[lvl](args); + } + create(moduleName) { + return new _Logger(this.logger, { + ...{ + prefix: `${this.prefix}:${moduleName}:` + }, + ...this.options + }); + } + clone(options) { + options = options || this.options; + options.prefix = options.prefix || this.prefix; + return new _Logger(this.logger, options); + } +}; +var baseLogger = new Logger(); +var EventEmitter = class { + static { + __name(this, "EventEmitter"); + } + constructor() { + this.observers = {}; + } + on(events, listener) { + events.split(" ").forEach((event) => { + if (!this.observers[event]) this.observers[event] = /* @__PURE__ */ new Map(); + const numListeners = this.observers[event].get(listener) || 0; + this.observers[event].set(listener, numListeners + 1); + }); + return this; + } + off(event, listener) { + if (!this.observers[event]) return; + if (!listener) { + delete this.observers[event]; + return; + } + this.observers[event].delete(listener); + } + emit(event, ...args) { + if (this.observers[event]) { + const cloned = Array.from(this.observers[event].entries()); + cloned.forEach(([observer, numTimesAdded]) => { + for (let i = 0; i < numTimesAdded; i++) { + observer(...args); + } + }); + } + if (this.observers["*"]) { + const cloned = Array.from(this.observers["*"].entries()); + cloned.forEach(([observer, numTimesAdded]) => { + for (let i = 0; i < numTimesAdded; i++) { + observer.apply(observer, [event, ...args]); + } + }); + } + } +}; +var ResourceStore = class extends EventEmitter { + static { + __name(this, "ResourceStore"); + } + constructor(data2, options = { + ns: ["translation"], + defaultNS: "translation" + }) { + super(); + this.data = data2 || {}; + this.options = options; + if (this.options.keySeparator === void 0) { + this.options.keySeparator = "."; + } + if (this.options.ignoreJSONStructure === void 0) { + this.options.ignoreJSONStructure = true; + } + } + addNamespaces(ns) { + if (this.options.ns.indexOf(ns) < 0) { + this.options.ns.push(ns); + } + } + removeNamespaces(ns) { + const index = this.options.ns.indexOf(ns); + if (index > -1) { + this.options.ns.splice(index, 1); + } + } + getResource(lng, ns, key, options = {}) { + const keySeparator = options.keySeparator !== void 0 ? options.keySeparator : this.options.keySeparator; + const ignoreJSONStructure = options.ignoreJSONStructure !== void 0 ? options.ignoreJSONStructure : this.options.ignoreJSONStructure; + let path; + if (lng.indexOf(".") > -1) { + path = lng.split("."); + } else { + path = [lng, ns]; + if (key) { + if (Array.isArray(key)) { + path.push(...key); + } else if (isString(key) && keySeparator) { + path.push(...key.split(keySeparator)); + } else { + path.push(key); + } + } + } + const result = getPath2(this.data, path); + if (!result && !ns && !key && lng.indexOf(".") > -1) { + lng = path[0]; + ns = path[1]; + key = path.slice(2).join("."); + } + if (result || !ignoreJSONStructure || !isString(key)) return result; + return deepFind(this.data?.[lng]?.[ns], key, keySeparator); + } + addResource(lng, ns, key, value, options = { + silent: false + }) { + const keySeparator = options.keySeparator !== void 0 ? options.keySeparator : this.options.keySeparator; + let path = [lng, ns]; + if (key) path = path.concat(keySeparator ? key.split(keySeparator) : key); + if (lng.indexOf(".") > -1) { + path = lng.split("."); + value = ns; + ns = path[1]; + } + this.addNamespaces(ns); + setPath(this.data, path, value); + if (!options.silent) this.emit("added", lng, ns, key, value); + } + addResources(lng, ns, resources, options = { + silent: false + }) { + for (const m2 in resources) { + if (isString(resources[m2]) || Array.isArray(resources[m2])) this.addResource(lng, ns, m2, resources[m2], { + silent: true + }); + } + if (!options.silent) this.emit("added", lng, ns, resources); + } + addResourceBundle(lng, ns, resources, deep, overwrite, options = { + silent: false, + skipCopy: false + }) { + let path = [lng, ns]; + if (lng.indexOf(".") > -1) { + path = lng.split("."); + deep = resources; + resources = ns; + ns = path[1]; + } + this.addNamespaces(ns); + let pack = getPath2(this.data, path) || {}; + if (!options.skipCopy) resources = JSON.parse(JSON.stringify(resources)); + if (deep) { + deepExtend(pack, resources, overwrite); + } else { + pack = { + ...pack, + ...resources + }; + } + setPath(this.data, path, pack); + if (!options.silent) this.emit("added", lng, ns, resources); + } + removeResourceBundle(lng, ns) { + if (this.hasResourceBundle(lng, ns)) { + delete this.data[lng][ns]; + } + this.removeNamespaces(ns); + this.emit("removed", lng, ns); + } + hasResourceBundle(lng, ns) { + return this.getResource(lng, ns) !== void 0; + } + getResourceBundle(lng, ns) { + if (!ns) ns = this.options.defaultNS; + return this.getResource(lng, ns); + } + getDataByLanguage(lng) { + return this.data[lng]; + } + hasLanguageSomeTranslations(lng) { + const data2 = this.getDataByLanguage(lng); + const n = data2 && Object.keys(data2) || []; + return !!n.find((v) => data2[v] && Object.keys(data2[v]).length > 0); + } + toJSON() { + return this.data; + } +}; +var postProcessor = { + processors: {}, + addPostProcessor(module) { + this.processors[module.name] = module; + }, + handle(processors, value, key, options, translator) { + processors.forEach((processor) => { + value = this.processors[processor]?.process(value, key, options, translator) ?? value; + }); + return value; + } +}; +var PATH_KEY = /* @__PURE__ */ Symbol("i18next/PATH_KEY"); +function createProxy() { + const state = []; + const handler = /* @__PURE__ */ Object.create(null); + let proxy; + handler.get = (target, key) => { + proxy?.revoke?.(); + if (key === PATH_KEY) return state; + state.push(key); + proxy = Proxy.revocable(target, handler); + return proxy.proxy; + }; + return Proxy.revocable(/* @__PURE__ */ Object.create(null), handler).proxy; +} +__name(createProxy, "createProxy"); +function keysFromSelector(selector, opts) { + const { + [PATH_KEY]: path + } = selector(createProxy()); + return path.join(opts?.keySeparator ?? "."); +} +__name(keysFromSelector, "keysFromSelector"); +var checkedLoadedFor = {}; +var shouldHandleAsObject = /* @__PURE__ */ __name((res) => !isString(res) && typeof res !== "boolean" && typeof res !== "number", "shouldHandleAsObject"); +var Translator = class _Translator extends EventEmitter { + static { + __name(this, "Translator"); + } + constructor(services, options = {}) { + super(); + copy(["resourceStore", "languageUtils", "pluralResolver", "interpolator", "backendConnector", "i18nFormat", "utils"], services, this); + this.options = options; + if (this.options.keySeparator === void 0) { + this.options.keySeparator = "."; + } + this.logger = baseLogger.create("translator"); + } + changeLanguage(lng) { + if (lng) this.language = lng; + } + exists(key, o = { + interpolation: {} + }) { + const opt = { + ...o + }; + if (key == null) return false; + const resolved = this.resolve(key, opt); + if (resolved?.res === void 0) return false; + const isObject = shouldHandleAsObject(resolved.res); + if (opt.returnObjects === false && isObject) { + return false; + } + return true; + } + extractFromKey(key, opt) { + let nsSeparator = opt.nsSeparator !== void 0 ? opt.nsSeparator : this.options.nsSeparator; + if (nsSeparator === void 0) nsSeparator = ":"; + const keySeparator = opt.keySeparator !== void 0 ? opt.keySeparator : this.options.keySeparator; + let namespaces = opt.ns || this.options.defaultNS || []; + const wouldCheckForNsInKey = nsSeparator && key.indexOf(nsSeparator) > -1; + const seemsNaturalLanguage = !this.options.userDefinedKeySeparator && !opt.keySeparator && !this.options.userDefinedNsSeparator && !opt.nsSeparator && !looksLikeObjectPath(key, nsSeparator, keySeparator); + if (wouldCheckForNsInKey && !seemsNaturalLanguage) { + const m2 = key.match(this.interpolator.nestingRegexp); + if (m2 && m2.length > 0) { + return { + key, + namespaces: isString(namespaces) ? [namespaces] : namespaces + }; + } + const parts = key.split(nsSeparator); + if (nsSeparator !== keySeparator || nsSeparator === keySeparator && this.options.ns.indexOf(parts[0]) > -1) namespaces = parts.shift(); + key = parts.join(keySeparator); + } + return { + key, + namespaces: isString(namespaces) ? [namespaces] : namespaces + }; + } + translate(keys, o, lastKey) { + let opt = typeof o === "object" ? { + ...o + } : o; + if (typeof opt !== "object" && this.options.overloadTranslationOptionHandler) { + opt = this.options.overloadTranslationOptionHandler(arguments); + } + if (typeof opt === "object") opt = { + ...opt + }; + if (!opt) opt = {}; + if (keys == null) return ""; + if (typeof keys === "function") keys = keysFromSelector(keys, { + ...this.options, + ...opt + }); + if (!Array.isArray(keys)) keys = [String(keys)]; + const returnDetails = opt.returnDetails !== void 0 ? opt.returnDetails : this.options.returnDetails; + const keySeparator = opt.keySeparator !== void 0 ? opt.keySeparator : this.options.keySeparator; + const { + key, + namespaces + } = this.extractFromKey(keys[keys.length - 1], opt); + const namespace = namespaces[namespaces.length - 1]; + let nsSeparator = opt.nsSeparator !== void 0 ? opt.nsSeparator : this.options.nsSeparator; + if (nsSeparator === void 0) nsSeparator = ":"; + const lng = opt.lng || this.language; + const appendNamespaceToCIMode = opt.appendNamespaceToCIMode || this.options.appendNamespaceToCIMode; + if (lng?.toLowerCase() === "cimode") { + if (appendNamespaceToCIMode) { + if (returnDetails) { + return { + res: `${namespace}${nsSeparator}${key}`, + usedKey: key, + exactUsedKey: key, + usedLng: lng, + usedNS: namespace, + usedParams: this.getUsedParamsDetails(opt) + }; + } + return `${namespace}${nsSeparator}${key}`; + } + if (returnDetails) { + return { + res: key, + usedKey: key, + exactUsedKey: key, + usedLng: lng, + usedNS: namespace, + usedParams: this.getUsedParamsDetails(opt) + }; + } + return key; + } + const resolved = this.resolve(keys, opt); + let res = resolved?.res; + const resUsedKey = resolved?.usedKey || key; + const resExactUsedKey = resolved?.exactUsedKey || key; + const noObject = ["[object Number]", "[object Function]", "[object RegExp]"]; + const joinArrays = opt.joinArrays !== void 0 ? opt.joinArrays : this.options.joinArrays; + const handleAsObjectInI18nFormat = !this.i18nFormat || this.i18nFormat.handleAsObject; + const needsPluralHandling = opt.count !== void 0 && !isString(opt.count); + const hasDefaultValue = _Translator.hasDefaultValue(opt); + const defaultValueSuffix = needsPluralHandling ? this.pluralResolver.getSuffix(lng, opt.count, opt) : ""; + const defaultValueSuffixOrdinalFallback = opt.ordinal && needsPluralHandling ? this.pluralResolver.getSuffix(lng, opt.count, { + ordinal: false + }) : ""; + const needsZeroSuffixLookup = needsPluralHandling && !opt.ordinal && opt.count === 0; + const defaultValue = needsZeroSuffixLookup && opt[`defaultValue${this.options.pluralSeparator}zero`] || opt[`defaultValue${defaultValueSuffix}`] || opt[`defaultValue${defaultValueSuffixOrdinalFallback}`] || opt.defaultValue; + let resForObjHndl = res; + if (handleAsObjectInI18nFormat && !res && hasDefaultValue) { + resForObjHndl = defaultValue; + } + const handleAsObject = shouldHandleAsObject(resForObjHndl); + const resType = Object.prototype.toString.apply(resForObjHndl); + if (handleAsObjectInI18nFormat && resForObjHndl && handleAsObject && noObject.indexOf(resType) < 0 && !(isString(joinArrays) && Array.isArray(resForObjHndl))) { + if (!opt.returnObjects && !this.options.returnObjects) { + if (!this.options.returnedObjectHandler) { + this.logger.warn("accessing an object - but returnObjects options is not enabled!"); + } + const r = this.options.returnedObjectHandler ? this.options.returnedObjectHandler(resUsedKey, resForObjHndl, { + ...opt, + ns: namespaces + }) : `key '${key} (${this.language})' returned an object instead of string.`; + if (returnDetails) { + resolved.res = r; + resolved.usedParams = this.getUsedParamsDetails(opt); + return resolved; + } + return r; + } + if (keySeparator) { + const resTypeIsArray = Array.isArray(resForObjHndl); + const copy2 = resTypeIsArray ? [] : {}; + const newKeyToUse = resTypeIsArray ? resExactUsedKey : resUsedKey; + for (const m2 in resForObjHndl) { + if (Object.prototype.hasOwnProperty.call(resForObjHndl, m2)) { + const deepKey = `${newKeyToUse}${keySeparator}${m2}`; + if (hasDefaultValue && !res) { + copy2[m2] = this.translate(deepKey, { + ...opt, + defaultValue: shouldHandleAsObject(defaultValue) ? defaultValue[m2] : void 0, + ...{ + joinArrays: false, + ns: namespaces + } + }); + } else { + copy2[m2] = this.translate(deepKey, { + ...opt, + ...{ + joinArrays: false, + ns: namespaces + } + }); + } + if (copy2[m2] === deepKey) copy2[m2] = resForObjHndl[m2]; + } + } + res = copy2; + } + } else if (handleAsObjectInI18nFormat && isString(joinArrays) && Array.isArray(res)) { + res = res.join(joinArrays); + if (res) res = this.extendTranslation(res, keys, opt, lastKey); + } else { + let usedDefault = false; + let usedKey = false; + if (!this.isValidLookup(res) && hasDefaultValue) { + usedDefault = true; + res = defaultValue; + } + if (!this.isValidLookup(res)) { + usedKey = true; + res = key; + } + const missingKeyNoValueFallbackToKey = opt.missingKeyNoValueFallbackToKey || this.options.missingKeyNoValueFallbackToKey; + const resForMissing = missingKeyNoValueFallbackToKey && usedKey ? void 0 : res; + const updateMissing = hasDefaultValue && defaultValue !== res && this.options.updateMissing; + if (usedKey || usedDefault || updateMissing) { + this.logger.log(updateMissing ? "updateKey" : "missingKey", lng, namespace, key, updateMissing ? defaultValue : res); + if (keySeparator) { + const fk = this.resolve(key, { + ...opt, + keySeparator: false + }); + if (fk && fk.res) this.logger.warn("Seems the loaded translations were in flat JSON format instead of nested. Either set keySeparator: false on init or make sure your translations are published in nested format."); + } + let lngs = []; + const fallbackLngs = this.languageUtils.getFallbackCodes(this.options.fallbackLng, opt.lng || this.language); + if (this.options.saveMissingTo === "fallback" && fallbackLngs && fallbackLngs[0]) { + for (let i = 0; i < fallbackLngs.length; i++) { + lngs.push(fallbackLngs[i]); + } + } else if (this.options.saveMissingTo === "all") { + lngs = this.languageUtils.toResolveHierarchy(opt.lng || this.language); + } else { + lngs.push(opt.lng || this.language); + } + const send = /* @__PURE__ */ __name((l, k, specificDefaultValue) => { + const defaultForMissing = hasDefaultValue && specificDefaultValue !== res ? specificDefaultValue : resForMissing; + if (this.options.missingKeyHandler) { + this.options.missingKeyHandler(l, namespace, k, defaultForMissing, updateMissing, opt); + } else if (this.backendConnector?.saveMissing) { + this.backendConnector.saveMissing(l, namespace, k, defaultForMissing, updateMissing, opt); + } + this.emit("missingKey", l, namespace, k, res); + }, "send"); + if (this.options.saveMissing) { + if (this.options.saveMissingPlurals && needsPluralHandling) { + lngs.forEach((language) => { + const suffixes = this.pluralResolver.getSuffixes(language, opt); + if (needsZeroSuffixLookup && opt[`defaultValue${this.options.pluralSeparator}zero`] && suffixes.indexOf(`${this.options.pluralSeparator}zero`) < 0) { + suffixes.push(`${this.options.pluralSeparator}zero`); + } + suffixes.forEach((suffix) => { + send([language], key + suffix, opt[`defaultValue${suffix}`] || defaultValue); + }); + }); + } else { + send(lngs, key, defaultValue); + } + } + } + res = this.extendTranslation(res, keys, opt, resolved, lastKey); + if (usedKey && res === key && this.options.appendNamespaceToMissingKey) { + res = `${namespace}${nsSeparator}${key}`; + } + if ((usedKey || usedDefault) && this.options.parseMissingKeyHandler) { + res = this.options.parseMissingKeyHandler(this.options.appendNamespaceToMissingKey ? `${namespace}${nsSeparator}${key}` : key, usedDefault ? res : void 0, opt); + } + } + if (returnDetails) { + resolved.res = res; + resolved.usedParams = this.getUsedParamsDetails(opt); + return resolved; + } + return res; + } + extendTranslation(res, key, opt, resolved, lastKey) { + if (this.i18nFormat?.parse) { + res = this.i18nFormat.parse(res, { + ...this.options.interpolation.defaultVariables, + ...opt + }, opt.lng || this.language || resolved.usedLng, resolved.usedNS, resolved.usedKey, { + resolved + }); + } else if (!opt.skipInterpolation) { + if (opt.interpolation) this.interpolator.init({ + ...opt, + ...{ + interpolation: { + ...this.options.interpolation, + ...opt.interpolation + } + } + }); + const skipOnVariables = isString(res) && (opt?.interpolation?.skipOnVariables !== void 0 ? opt.interpolation.skipOnVariables : this.options.interpolation.skipOnVariables); + let nestBef; + if (skipOnVariables) { + const nb = res.match(this.interpolator.nestingRegexp); + nestBef = nb && nb.length; + } + let data2 = opt.replace && !isString(opt.replace) ? opt.replace : opt; + if (this.options.interpolation.defaultVariables) data2 = { + ...this.options.interpolation.defaultVariables, + ...data2 + }; + res = this.interpolator.interpolate(res, data2, opt.lng || this.language || resolved.usedLng, opt); + if (skipOnVariables) { + const na = res.match(this.interpolator.nestingRegexp); + const nestAft = na && na.length; + if (nestBef < nestAft) opt.nest = false; + } + if (!opt.lng && resolved && resolved.res) opt.lng = this.language || resolved.usedLng; + if (opt.nest !== false) res = this.interpolator.nest(res, (...args) => { + if (lastKey?.[0] === args[0] && !opt.context) { + this.logger.warn(`It seems you are nesting recursively key: ${args[0]} in key: ${key[0]}`); + return null; + } + return this.translate(...args, key); + }, opt); + if (opt.interpolation) this.interpolator.reset(); + } + const postProcess = opt.postProcess || this.options.postProcess; + const postProcessorNames = isString(postProcess) ? [postProcess] : postProcess; + if (res != null && postProcessorNames?.length && opt.applyPostProcessor !== false) { + res = postProcessor.handle(postProcessorNames, res, key, this.options && this.options.postProcessPassResolved ? { + i18nResolved: { + ...resolved, + usedParams: this.getUsedParamsDetails(opt) + }, + ...opt + } : opt, this); + } + return res; + } + resolve(keys, opt = {}) { + let found; + let usedKey; + let exactUsedKey; + let usedLng; + let usedNS; + if (isString(keys)) keys = [keys]; + keys.forEach((k) => { + if (this.isValidLookup(found)) return; + const extracted = this.extractFromKey(k, opt); + const key = extracted.key; + usedKey = key; + let namespaces = extracted.namespaces; + if (this.options.fallbackNS) namespaces = namespaces.concat(this.options.fallbackNS); + const needsPluralHandling = opt.count !== void 0 && !isString(opt.count); + const needsZeroSuffixLookup = needsPluralHandling && !opt.ordinal && opt.count === 0; + const needsContextHandling = opt.context !== void 0 && (isString(opt.context) || typeof opt.context === "number") && opt.context !== ""; + const codes = opt.lngs ? opt.lngs : this.languageUtils.toResolveHierarchy(opt.lng || this.language, opt.fallbackLng); + namespaces.forEach((ns) => { + if (this.isValidLookup(found)) return; + usedNS = ns; + if (!checkedLoadedFor[`${codes[0]}-${ns}`] && this.utils?.hasLoadedNamespace && !this.utils?.hasLoadedNamespace(usedNS)) { + checkedLoadedFor[`${codes[0]}-${ns}`] = true; + this.logger.warn(`key "${usedKey}" for languages "${codes.join(", ")}" won't get resolved as namespace "${usedNS}" was not yet loaded`, "This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!"); + } + codes.forEach((code) => { + if (this.isValidLookup(found)) return; + usedLng = code; + const finalKeys = [key]; + if (this.i18nFormat?.addLookupKeys) { + this.i18nFormat.addLookupKeys(finalKeys, key, code, ns, opt); + } else { + let pluralSuffix; + if (needsPluralHandling) pluralSuffix = this.pluralResolver.getSuffix(code, opt.count, opt); + const zeroSuffix = `${this.options.pluralSeparator}zero`; + const ordinalPrefix = `${this.options.pluralSeparator}ordinal${this.options.pluralSeparator}`; + if (needsPluralHandling) { + if (opt.ordinal && pluralSuffix.indexOf(ordinalPrefix) === 0) { + finalKeys.push(key + pluralSuffix.replace(ordinalPrefix, this.options.pluralSeparator)); + } + finalKeys.push(key + pluralSuffix); + if (needsZeroSuffixLookup) { + finalKeys.push(key + zeroSuffix); + } + } + if (needsContextHandling) { + const contextKey = `${key}${this.options.contextSeparator || "_"}${opt.context}`; + finalKeys.push(contextKey); + if (needsPluralHandling) { + if (opt.ordinal && pluralSuffix.indexOf(ordinalPrefix) === 0) { + finalKeys.push(contextKey + pluralSuffix.replace(ordinalPrefix, this.options.pluralSeparator)); + } + finalKeys.push(contextKey + pluralSuffix); + if (needsZeroSuffixLookup) { + finalKeys.push(contextKey + zeroSuffix); + } + } + } + } + let possibleKey; + while (possibleKey = finalKeys.pop()) { + if (!this.isValidLookup(found)) { + exactUsedKey = possibleKey; + found = this.getResource(code, ns, possibleKey, opt); + } + } + }); + }); + }); + return { + res: found, + usedKey, + exactUsedKey, + usedLng, + usedNS + }; + } + isValidLookup(res) { + return res !== void 0 && !(!this.options.returnNull && res === null) && !(!this.options.returnEmptyString && res === ""); + } + getResource(code, ns, key, options = {}) { + if (this.i18nFormat?.getResource) return this.i18nFormat.getResource(code, ns, key, options); + return this.resourceStore.getResource(code, ns, key, options); + } + getUsedParamsDetails(options = {}) { + const optionsKeys = ["defaultValue", "ordinal", "context", "replace", "lng", "lngs", "fallbackLng", "ns", "keySeparator", "nsSeparator", "returnObjects", "returnDetails", "joinArrays", "postProcess", "interpolation"]; + const useOptionsReplaceForData = options.replace && !isString(options.replace); + let data2 = useOptionsReplaceForData ? options.replace : options; + if (useOptionsReplaceForData && typeof options.count !== "undefined") { + data2.count = options.count; + } + if (this.options.interpolation.defaultVariables) { + data2 = { + ...this.options.interpolation.defaultVariables, + ...data2 + }; + } + if (!useOptionsReplaceForData) { + data2 = { + ...data2 + }; + for (const key of optionsKeys) { + delete data2[key]; + } + } + return data2; + } + static hasDefaultValue(options) { + const prefix = "defaultValue"; + for (const option in options) { + if (Object.prototype.hasOwnProperty.call(options, option) && prefix === option.substring(0, prefix.length) && void 0 !== options[option]) { + return true; + } + } + return false; + } +}; +var LanguageUtil = class { + static { + __name(this, "LanguageUtil"); + } + constructor(options) { + this.options = options; + this.supportedLngs = this.options.supportedLngs || false; + this.logger = baseLogger.create("languageUtils"); + } + getScriptPartFromCode(code) { + code = getCleanedCode(code); + if (!code || code.indexOf("-") < 0) return null; + const p = code.split("-"); + if (p.length === 2) return null; + p.pop(); + if (p[p.length - 1].toLowerCase() === "x") return null; + return this.formatLanguageCode(p.join("-")); + } + getLanguagePartFromCode(code) { + code = getCleanedCode(code); + if (!code || code.indexOf("-") < 0) return code; + const p = code.split("-"); + return this.formatLanguageCode(p[0]); + } + formatLanguageCode(code) { + if (isString(code) && code.indexOf("-") > -1) { + let formattedCode; + try { + formattedCode = Intl.getCanonicalLocales(code)[0]; + } catch (e) { + } + if (formattedCode && this.options.lowerCaseLng) { + formattedCode = formattedCode.toLowerCase(); + } + if (formattedCode) return formattedCode; + if (this.options.lowerCaseLng) { + return code.toLowerCase(); + } + return code; + } + return this.options.cleanCode || this.options.lowerCaseLng ? code.toLowerCase() : code; + } + isSupportedCode(code) { + if (this.options.load === "languageOnly" || this.options.nonExplicitSupportedLngs) { + code = this.getLanguagePartFromCode(code); + } + return !this.supportedLngs || !this.supportedLngs.length || this.supportedLngs.indexOf(code) > -1; + } + getBestMatchFromCodes(codes) { + if (!codes) return null; + let found; + codes.forEach((code) => { + if (found) return; + const cleanedLng = this.formatLanguageCode(code); + if (!this.options.supportedLngs || this.isSupportedCode(cleanedLng)) found = cleanedLng; + }); + if (!found && this.options.supportedLngs) { + codes.forEach((code) => { + if (found) return; + const lngScOnly = this.getScriptPartFromCode(code); + if (this.isSupportedCode(lngScOnly)) return found = lngScOnly; + const lngOnly = this.getLanguagePartFromCode(code); + if (this.isSupportedCode(lngOnly)) return found = lngOnly; + found = this.options.supportedLngs.find((supportedLng) => { + if (supportedLng === lngOnly) return supportedLng; + if (supportedLng.indexOf("-") < 0 && lngOnly.indexOf("-") < 0) return; + if (supportedLng.indexOf("-") > 0 && lngOnly.indexOf("-") < 0 && supportedLng.substring(0, supportedLng.indexOf("-")) === lngOnly) return supportedLng; + if (supportedLng.indexOf(lngOnly) === 0 && lngOnly.length > 1) return supportedLng; + }); + }); + } + if (!found) found = this.getFallbackCodes(this.options.fallbackLng)[0]; + return found; + } + getFallbackCodes(fallbacks, code) { + if (!fallbacks) return []; + if (typeof fallbacks === "function") fallbacks = fallbacks(code); + if (isString(fallbacks)) fallbacks = [fallbacks]; + if (Array.isArray(fallbacks)) return fallbacks; + if (!code) return fallbacks.default || []; + let found = fallbacks[code]; + if (!found) found = fallbacks[this.getScriptPartFromCode(code)]; + if (!found) found = fallbacks[this.formatLanguageCode(code)]; + if (!found) found = fallbacks[this.getLanguagePartFromCode(code)]; + if (!found) found = fallbacks.default; + return found || []; + } + toResolveHierarchy(code, fallbackCode) { + const fallbackCodes = this.getFallbackCodes((fallbackCode === false ? [] : fallbackCode) || this.options.fallbackLng || [], code); + const codes = []; + const addCode = /* @__PURE__ */ __name((c) => { + if (!c) return; + if (this.isSupportedCode(c)) { + codes.push(c); + } else { + this.logger.warn(`rejecting language code not found in supportedLngs: ${c}`); + } + }, "addCode"); + if (isString(code) && (code.indexOf("-") > -1 || code.indexOf("_") > -1)) { + if (this.options.load !== "languageOnly") addCode(this.formatLanguageCode(code)); + if (this.options.load !== "languageOnly" && this.options.load !== "currentOnly") addCode(this.getScriptPartFromCode(code)); + if (this.options.load !== "currentOnly") addCode(this.getLanguagePartFromCode(code)); + } else if (isString(code)) { + addCode(this.formatLanguageCode(code)); + } + fallbackCodes.forEach((fc) => { + if (codes.indexOf(fc) < 0) addCode(this.formatLanguageCode(fc)); + }); + return codes; + } +}; +var suffixesOrder = { + zero: 0, + one: 1, + two: 2, + few: 3, + many: 4, + other: 5 +}; +var dummyRule = { + select: /* @__PURE__ */ __name((count2) => count2 === 1 ? "one" : "other", "select"), + resolvedOptions: /* @__PURE__ */ __name(() => ({ + pluralCategories: ["one", "other"] + }), "resolvedOptions") +}; +var PluralResolver = class { + static { + __name(this, "PluralResolver"); + } + constructor(languageUtils, options = {}) { + this.languageUtils = languageUtils; + this.options = options; + this.logger = baseLogger.create("pluralResolver"); + this.pluralRulesCache = {}; + } + clearCache() { + this.pluralRulesCache = {}; + } + getRule(code, options = {}) { + const cleanedCode = getCleanedCode(code === "dev" ? "en" : code); + const type = options.ordinal ? "ordinal" : "cardinal"; + const cacheKey = JSON.stringify({ + cleanedCode, + type + }); + if (cacheKey in this.pluralRulesCache) { + return this.pluralRulesCache[cacheKey]; + } + let rule; + try { + rule = new Intl.PluralRules(cleanedCode, { + type + }); + } catch (err) { + if (typeof Intl === "undefined") { + this.logger.error("No Intl support, please use an Intl polyfill!"); + return dummyRule; + } + if (!code.match(/-|_/)) return dummyRule; + const lngPart = this.languageUtils.getLanguagePartFromCode(code); + rule = this.getRule(lngPart, options); + } + this.pluralRulesCache[cacheKey] = rule; + return rule; + } + needsPlural(code, options = {}) { + let rule = this.getRule(code, options); + if (!rule) rule = this.getRule("dev", options); + return rule?.resolvedOptions().pluralCategories.length > 1; + } + getPluralFormsOfKey(code, key, options = {}) { + return this.getSuffixes(code, options).map((suffix) => `${key}${suffix}`); + } + getSuffixes(code, options = {}) { + let rule = this.getRule(code, options); + if (!rule) rule = this.getRule("dev", options); + if (!rule) return []; + return rule.resolvedOptions().pluralCategories.sort((pluralCategory1, pluralCategory2) => suffixesOrder[pluralCategory1] - suffixesOrder[pluralCategory2]).map((pluralCategory) => `${this.options.prepend}${options.ordinal ? `ordinal${this.options.prepend}` : ""}${pluralCategory}`); + } + getSuffix(code, count2, options = {}) { + const rule = this.getRule(code, options); + if (rule) { + return `${this.options.prepend}${options.ordinal ? `ordinal${this.options.prepend}` : ""}${rule.select(count2)}`; + } + this.logger.warn(`no plural rule found for: ${code}`); + return this.getSuffix("dev", count2, options); + } +}; +var deepFindWithDefaults = /* @__PURE__ */ __name((data2, defaultData, key, keySeparator = ".", ignoreJSONStructure = true) => { + let path = getPathWithDefaults(data2, defaultData, key); + if (!path && ignoreJSONStructure && isString(key)) { + path = deepFind(data2, key, keySeparator); + if (path === void 0) path = deepFind(defaultData, key, keySeparator); + } + return path; +}, "deepFindWithDefaults"); +var regexSafe = /* @__PURE__ */ __name((val) => val.replace(/\$/g, "$$$$"), "regexSafe"); +var Interpolator = class { + static { + __name(this, "Interpolator"); + } + constructor(options = {}) { + this.logger = baseLogger.create("interpolator"); + this.options = options; + this.format = options?.interpolation?.format || ((value) => value); + this.init(options); + } + init(options = {}) { + if (!options.interpolation) options.interpolation = { + escapeValue: true + }; + const { + escape: escape$1, + escapeValue, + useRawValueToEscape, + prefix, + prefixEscaped, + suffix, + suffixEscaped, + formatSeparator, + unescapeSuffix, + unescapePrefix, + nestingPrefix, + nestingPrefixEscaped, + nestingSuffix, + nestingSuffixEscaped, + nestingOptionsSeparator, + maxReplaces, + alwaysFormat + } = options.interpolation; + this.escape = escape$1 !== void 0 ? escape$1 : escape; + this.escapeValue = escapeValue !== void 0 ? escapeValue : true; + this.useRawValueToEscape = useRawValueToEscape !== void 0 ? useRawValueToEscape : false; + this.prefix = prefix ? regexEscape(prefix) : prefixEscaped || "{{"; + this.suffix = suffix ? regexEscape(suffix) : suffixEscaped || "}}"; + this.formatSeparator = formatSeparator || ","; + this.unescapePrefix = unescapeSuffix ? "" : unescapePrefix || "-"; + this.unescapeSuffix = this.unescapePrefix ? "" : unescapeSuffix || ""; + this.nestingPrefix = nestingPrefix ? regexEscape(nestingPrefix) : nestingPrefixEscaped || regexEscape("$t("); + this.nestingSuffix = nestingSuffix ? regexEscape(nestingSuffix) : nestingSuffixEscaped || regexEscape(")"); + this.nestingOptionsSeparator = nestingOptionsSeparator || ","; + this.maxReplaces = maxReplaces || 1e3; + this.alwaysFormat = alwaysFormat !== void 0 ? alwaysFormat : false; + this.resetRegExp(); + } + reset() { + if (this.options) this.init(this.options); + } + resetRegExp() { + const getOrResetRegExp = /* @__PURE__ */ __name((existingRegExp, pattern) => { + if (existingRegExp?.source === pattern) { + existingRegExp.lastIndex = 0; + return existingRegExp; + } + return new RegExp(pattern, "g"); + }, "getOrResetRegExp"); + this.regexp = getOrResetRegExp(this.regexp, `${this.prefix}(.+?)${this.suffix}`); + this.regexpUnescape = getOrResetRegExp(this.regexpUnescape, `${this.prefix}${this.unescapePrefix}(.+?)${this.unescapeSuffix}${this.suffix}`); + this.nestingRegexp = getOrResetRegExp(this.nestingRegexp, `${this.nestingPrefix}((?:[^()"']+|"[^"]*"|'[^']*'|\\((?:[^()]|"[^"]*"|'[^']*')*\\))*?)${this.nestingSuffix}`); + } + interpolate(str2, data2, lng, options) { + let match3; + let value; + let replaces; + const defaultData = this.options && this.options.interpolation && this.options.interpolation.defaultVariables || {}; + const handleFormat = /* @__PURE__ */ __name((key) => { + if (key.indexOf(this.formatSeparator) < 0) { + const path = deepFindWithDefaults(data2, defaultData, key, this.options.keySeparator, this.options.ignoreJSONStructure); + return this.alwaysFormat ? this.format(path, void 0, lng, { + ...options, + ...data2, + interpolationkey: key + }) : path; + } + const p = key.split(this.formatSeparator); + const k = p.shift().trim(); + const f = p.join(this.formatSeparator).trim(); + return this.format(deepFindWithDefaults(data2, defaultData, k, this.options.keySeparator, this.options.ignoreJSONStructure), f, lng, { + ...options, + ...data2, + interpolationkey: k + }); + }, "handleFormat"); + this.resetRegExp(); + const missingInterpolationHandler = options?.missingInterpolationHandler || this.options.missingInterpolationHandler; + const skipOnVariables = options?.interpolation?.skipOnVariables !== void 0 ? options.interpolation.skipOnVariables : this.options.interpolation.skipOnVariables; + const todos = [{ + regex: this.regexpUnescape, + safeValue: /* @__PURE__ */ __name((val) => regexSafe(val), "safeValue") + }, { + regex: this.regexp, + safeValue: /* @__PURE__ */ __name((val) => this.escapeValue ? regexSafe(this.escape(val)) : regexSafe(val), "safeValue") + }]; + todos.forEach((todo) => { + replaces = 0; + while (match3 = todo.regex.exec(str2)) { + const matchedVar = match3[1].trim(); + value = handleFormat(matchedVar); + if (value === void 0) { + if (typeof missingInterpolationHandler === "function") { + const temp = missingInterpolationHandler(str2, match3, options); + value = isString(temp) ? temp : ""; + } else if (options && Object.prototype.hasOwnProperty.call(options, matchedVar)) { + value = ""; + } else if (skipOnVariables) { + value = match3[0]; + continue; + } else { + this.logger.warn(`missed to pass in variable ${matchedVar} for interpolating ${str2}`); + value = ""; + } + } else if (!isString(value) && !this.useRawValueToEscape) { + value = makeString(value); + } + const safeValue = todo.safeValue(value); + str2 = str2.replace(match3[0], safeValue); + if (skipOnVariables) { + todo.regex.lastIndex += value.length; + todo.regex.lastIndex -= match3[0].length; + } else { + todo.regex.lastIndex = 0; + } + replaces++; + if (replaces >= this.maxReplaces) { + break; + } + } + }); + return str2; + } + nest(str2, fc, options = {}) { + let match3; + let value; + let clonedOptions; + const handleHasOptions = /* @__PURE__ */ __name((key, inheritedOptions) => { + const sep = this.nestingOptionsSeparator; + if (key.indexOf(sep) < 0) return key; + const c = key.split(new RegExp(`${regexEscape(sep)}[ ]*{`)); + let optionsString = `{${c[1]}`; + key = c[0]; + optionsString = this.interpolate(optionsString, clonedOptions); + const matchedSingleQuotes = optionsString.match(/'/g); + const matchedDoubleQuotes = optionsString.match(/"/g); + if ((matchedSingleQuotes?.length ?? 0) % 2 === 0 && !matchedDoubleQuotes || (matchedDoubleQuotes?.length ?? 0) % 2 !== 0) { + optionsString = optionsString.replace(/'/g, '"'); + } + try { + clonedOptions = JSON.parse(optionsString); + if (inheritedOptions) clonedOptions = { + ...inheritedOptions, + ...clonedOptions + }; + } catch (e) { + this.logger.warn(`failed parsing options string in nesting for key ${key}`, e); + return `${key}${sep}${optionsString}`; + } + if (clonedOptions.defaultValue && clonedOptions.defaultValue.indexOf(this.prefix) > -1) delete clonedOptions.defaultValue; + return key; + }, "handleHasOptions"); + while (match3 = this.nestingRegexp.exec(str2)) { + let formatters = []; + clonedOptions = { + ...options + }; + clonedOptions = clonedOptions.replace && !isString(clonedOptions.replace) ? clonedOptions.replace : clonedOptions; + clonedOptions.applyPostProcessor = false; + delete clonedOptions.defaultValue; + const keyEndIndex = /{.*}/.test(match3[1]) ? match3[1].lastIndexOf("}") + 1 : match3[1].indexOf(this.formatSeparator); + if (keyEndIndex !== -1) { + formatters = match3[1].slice(keyEndIndex).split(this.formatSeparator).map((elem) => elem.trim()).filter(Boolean); + match3[1] = match3[1].slice(0, keyEndIndex); + } + value = fc(handleHasOptions.call(this, match3[1].trim(), clonedOptions), clonedOptions); + if (value && match3[0] === str2 && !isString(value)) return value; + if (!isString(value)) value = makeString(value); + if (!value) { + this.logger.warn(`missed to resolve ${match3[1]} for nesting ${str2}`); + value = ""; + } + if (formatters.length) { + value = formatters.reduce((v, f) => this.format(v, f, options.lng, { + ...options, + interpolationkey: match3[1].trim() + }), value.trim()); + } + str2 = str2.replace(match3[0], value); + this.regexp.lastIndex = 0; + } + return str2; + } +}; +var parseFormatStr = /* @__PURE__ */ __name((formatStr) => { + let formatName = formatStr.toLowerCase().trim(); + const formatOptions = {}; + if (formatStr.indexOf("(") > -1) { + const p = formatStr.split("("); + formatName = p[0].toLowerCase().trim(); + const optStr = p[1].substring(0, p[1].length - 1); + if (formatName === "currency" && optStr.indexOf(":") < 0) { + if (!formatOptions.currency) formatOptions.currency = optStr.trim(); + } else if (formatName === "relativetime" && optStr.indexOf(":") < 0) { + if (!formatOptions.range) formatOptions.range = optStr.trim(); + } else { + const opts = optStr.split(";"); + opts.forEach((opt) => { + if (opt) { + const [key, ...rest] = opt.split(":"); + const val = rest.join(":").trim().replace(/^'+|'+$/g, ""); + const trimmedKey = key.trim(); + if (!formatOptions[trimmedKey]) formatOptions[trimmedKey] = val; + if (val === "false") formatOptions[trimmedKey] = false; + if (val === "true") formatOptions[trimmedKey] = true; + if (!isNaN(val)) formatOptions[trimmedKey] = parseInt(val, 10); + } + }); + } + } + return { + formatName, + formatOptions + }; +}, "parseFormatStr"); +var createCachedFormatter = /* @__PURE__ */ __name((fn) => { + const cache = {}; + return (v, l, o) => { + let optForCache = o; + if (o && o.interpolationkey && o.formatParams && o.formatParams[o.interpolationkey] && o[o.interpolationkey]) { + optForCache = { + ...optForCache, + [o.interpolationkey]: void 0 + }; + } + const key = l + JSON.stringify(optForCache); + let frm = cache[key]; + if (!frm) { + frm = fn(getCleanedCode(l), o); + cache[key] = frm; + } + return frm(v); + }; +}, "createCachedFormatter"); +var createNonCachedFormatter = /* @__PURE__ */ __name((fn) => (v, l, o) => fn(getCleanedCode(l), o)(v), "createNonCachedFormatter"); +var Formatter = class { + static { + __name(this, "Formatter"); + } + constructor(options = {}) { + this.logger = baseLogger.create("formatter"); + this.options = options; + this.init(options); + } + init(services, options = { + interpolation: {} + }) { + this.formatSeparator = options.interpolation.formatSeparator || ","; + const cf = options.cacheInBuiltFormats ? createCachedFormatter : createNonCachedFormatter; + this.formats = { + number: cf((lng, opt) => { + const formatter = new Intl.NumberFormat(lng, { + ...opt + }); + return (val) => formatter.format(val); + }), + currency: cf((lng, opt) => { + const formatter = new Intl.NumberFormat(lng, { + ...opt, + style: "currency" + }); + return (val) => formatter.format(val); + }), + datetime: cf((lng, opt) => { + const formatter = new Intl.DateTimeFormat(lng, { + ...opt + }); + return (val) => formatter.format(val); + }), + relativetime: cf((lng, opt) => { + const formatter = new Intl.RelativeTimeFormat(lng, { + ...opt + }); + return (val) => formatter.format(val, opt.range || "day"); + }), + list: cf((lng, opt) => { + const formatter = new Intl.ListFormat(lng, { + ...opt + }); + return (val) => formatter.format(val); + }) + }; + } + add(name, fc) { + this.formats[name.toLowerCase().trim()] = fc; + } + addCached(name, fc) { + this.formats[name.toLowerCase().trim()] = createCachedFormatter(fc); + } + format(value, format, lng, options = {}) { + const formats = format.split(this.formatSeparator); + if (formats.length > 1 && formats[0].indexOf("(") > 1 && formats[0].indexOf(")") < 0 && formats.find((f) => f.indexOf(")") > -1)) { + const lastIndex = formats.findIndex((f) => f.indexOf(")") > -1); + formats[0] = [formats[0], ...formats.splice(1, lastIndex)].join(this.formatSeparator); + } + const result = formats.reduce((mem, f) => { + const { + formatName, + formatOptions + } = parseFormatStr(f); + if (this.formats[formatName]) { + let formatted = mem; + try { + const valOptions = options?.formatParams?.[options.interpolationkey] || {}; + const l = valOptions.locale || valOptions.lng || options.locale || options.lng || lng; + formatted = this.formats[formatName](mem, l, { + ...formatOptions, + ...options, + ...valOptions + }); + } catch (error) { + this.logger.warn(error); + } + return formatted; + } else { + this.logger.warn(`there was no format function for ${formatName}`); + } + return mem; + }, value); + return result; + } +}; +var removePending = /* @__PURE__ */ __name((q, name) => { + if (q.pending[name] !== void 0) { + delete q.pending[name]; + q.pendingCount--; + } +}, "removePending"); +var Connector = class extends EventEmitter { + static { + __name(this, "Connector"); + } + constructor(backend, store, services, options = {}) { + super(); + this.backend = backend; + this.store = store; + this.services = services; + this.languageUtils = services.languageUtils; + this.options = options; + this.logger = baseLogger.create("backendConnector"); + this.waitingReads = []; + this.maxParallelReads = options.maxParallelReads || 10; + this.readingCalls = 0; + this.maxRetries = options.maxRetries >= 0 ? options.maxRetries : 5; + this.retryTimeout = options.retryTimeout >= 1 ? options.retryTimeout : 350; + this.state = {}; + this.queue = []; + this.backend?.init?.(services, options.backend, options); + } + queueLoad(languages, namespaces, options, callback) { + const toLoad = {}; + const pending = {}; + const toLoadLanguages = {}; + const toLoadNamespaces = {}; + languages.forEach((lng) => { + let hasAllNamespaces = true; + namespaces.forEach((ns) => { + const name = `${lng}|${ns}`; + if (!options.reload && this.store.hasResourceBundle(lng, ns)) { + this.state[name] = 2; + } else if (this.state[name] < 0) ; + else if (this.state[name] === 1) { + if (pending[name] === void 0) pending[name] = true; + } else { + this.state[name] = 1; + hasAllNamespaces = false; + if (pending[name] === void 0) pending[name] = true; + if (toLoad[name] === void 0) toLoad[name] = true; + if (toLoadNamespaces[ns] === void 0) toLoadNamespaces[ns] = true; + } + }); + if (!hasAllNamespaces) toLoadLanguages[lng] = true; + }); + if (Object.keys(toLoad).length || Object.keys(pending).length) { + this.queue.push({ + pending, + pendingCount: Object.keys(pending).length, + loaded: {}, + errors: [], + callback + }); + } + return { + toLoad: Object.keys(toLoad), + pending: Object.keys(pending), + toLoadLanguages: Object.keys(toLoadLanguages), + toLoadNamespaces: Object.keys(toLoadNamespaces) + }; + } + loaded(name, err, data2) { + const s2 = name.split("|"); + const lng = s2[0]; + const ns = s2[1]; + if (err) this.emit("failedLoading", lng, ns, err); + if (!err && data2) { + this.store.addResourceBundle(lng, ns, data2, void 0, void 0, { + skipCopy: true + }); + } + this.state[name] = err ? -1 : 2; + if (err && data2) this.state[name] = 0; + const loaded = {}; + this.queue.forEach((q) => { + pushPath(q.loaded, [lng], ns); + removePending(q, name); + if (err) q.errors.push(err); + if (q.pendingCount === 0 && !q.done) { + Object.keys(q.loaded).forEach((l) => { + if (!loaded[l]) loaded[l] = {}; + const loadedKeys = q.loaded[l]; + if (loadedKeys.length) { + loadedKeys.forEach((n) => { + if (loaded[l][n] === void 0) loaded[l][n] = true; + }); + } + }); + q.done = true; + if (q.errors.length) { + q.callback(q.errors); + } else { + q.callback(); + } + } + }); + this.emit("loaded", loaded); + this.queue = this.queue.filter((q) => !q.done); + } + read(lng, ns, fcName, tried = 0, wait = this.retryTimeout, callback) { + if (!lng.length) return callback(null, {}); + if (this.readingCalls >= this.maxParallelReads) { + this.waitingReads.push({ + lng, + ns, + fcName, + tried, + wait, + callback + }); + return; + } + this.readingCalls++; + const resolver = /* @__PURE__ */ __name((err, data2) => { + this.readingCalls--; + if (this.waitingReads.length > 0) { + const next = this.waitingReads.shift(); + this.read(next.lng, next.ns, next.fcName, next.tried, next.wait, next.callback); + } + if (err && data2 && tried < this.maxRetries) { + setTimeout(() => { + this.read.call(this, lng, ns, fcName, tried + 1, wait * 2, callback); + }, wait); + return; + } + callback(err, data2); + }, "resolver"); + const fc = this.backend[fcName].bind(this.backend); + if (fc.length === 2) { + try { + const r = fc(lng, ns); + if (r && typeof r.then === "function") { + r.then((data2) => resolver(null, data2)).catch(resolver); + } else { + resolver(null, r); + } + } catch (err) { + resolver(err); + } + return; + } + return fc(lng, ns, resolver); + } + prepareLoading(languages, namespaces, options = {}, callback) { + if (!this.backend) { + this.logger.warn("No backend was added via i18next.use. Will not load resources."); + return callback && callback(); + } + if (isString(languages)) languages = this.languageUtils.toResolveHierarchy(languages); + if (isString(namespaces)) namespaces = [namespaces]; + const toLoad = this.queueLoad(languages, namespaces, options, callback); + if (!toLoad.toLoad.length) { + if (!toLoad.pending.length) callback(); + return null; + } + toLoad.toLoad.forEach((name) => { + this.loadOne(name); + }); + } + load(languages, namespaces, callback) { + this.prepareLoading(languages, namespaces, {}, callback); + } + reload(languages, namespaces, callback) { + this.prepareLoading(languages, namespaces, { + reload: true + }, callback); + } + loadOne(name, prefix = "") { + const s2 = name.split("|"); + const lng = s2[0]; + const ns = s2[1]; + this.read(lng, ns, "read", void 0, void 0, (err, data2) => { + if (err) this.logger.warn(`${prefix}loading namespace ${ns} for language ${lng} failed`, err); + if (!err && data2) this.logger.log(`${prefix}loaded namespace ${ns} for language ${lng}`, data2); + this.loaded(name, err, data2); + }); + } + saveMissing(languages, namespace, key, fallbackValue, isUpdate, options = {}, clb = () => { + }) { + if (this.services?.utils?.hasLoadedNamespace && !this.services?.utils?.hasLoadedNamespace(namespace)) { + this.logger.warn(`did not save key "${key}" as the namespace "${namespace}" was not yet loaded`, "This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!"); + return; + } + if (key === void 0 || key === null || key === "") return; + if (this.backend?.create) { + const opts = { + ...options, + isUpdate + }; + const fc = this.backend.create.bind(this.backend); + if (fc.length < 6) { + try { + let r; + if (fc.length === 5) { + r = fc(languages, namespace, key, fallbackValue, opts); + } else { + r = fc(languages, namespace, key, fallbackValue); + } + if (r && typeof r.then === "function") { + r.then((data2) => clb(null, data2)).catch(clb); + } else { + clb(null, r); + } + } catch (err) { + clb(err); + } + } else { + fc(languages, namespace, key, fallbackValue, clb, opts); + } + } + if (!languages || !languages[0]) return; + this.store.addResource(languages[0], namespace, key, fallbackValue); + } +}; +var get = /* @__PURE__ */ __name(() => ({ + debug: false, + initAsync: true, + ns: ["translation"], + defaultNS: ["translation"], + fallbackLng: ["dev"], + fallbackNS: false, + supportedLngs: false, + nonExplicitSupportedLngs: false, + load: "all", + preload: false, + simplifyPluralSuffix: true, + keySeparator: ".", + nsSeparator: ":", + pluralSeparator: "_", + contextSeparator: "_", + partialBundledLanguages: false, + saveMissing: false, + updateMissing: false, + saveMissingTo: "fallback", + saveMissingPlurals: true, + missingKeyHandler: false, + missingInterpolationHandler: false, + postProcess: false, + postProcessPassResolved: false, + returnNull: false, + returnEmptyString: true, + returnObjects: false, + joinArrays: false, + returnedObjectHandler: false, + parseMissingKeyHandler: false, + appendNamespaceToMissingKey: false, + appendNamespaceToCIMode: false, + overloadTranslationOptionHandler: /* @__PURE__ */ __name((args) => { + let ret = {}; + if (typeof args[1] === "object") ret = args[1]; + if (isString(args[1])) ret.defaultValue = args[1]; + if (isString(args[2])) ret.tDescription = args[2]; + if (typeof args[2] === "object" || typeof args[3] === "object") { + const options = args[3] || args[2]; + Object.keys(options).forEach((key) => { + ret[key] = options[key]; + }); + } + return ret; + }, "overloadTranslationOptionHandler"), + interpolation: { + escapeValue: true, + format: /* @__PURE__ */ __name((value) => value, "format"), + prefix: "{{", + suffix: "}}", + formatSeparator: ",", + unescapePrefix: "-", + nestingPrefix: "$t(", + nestingSuffix: ")", + nestingOptionsSeparator: ",", + maxReplaces: 1e3, + skipOnVariables: true + }, + cacheInBuiltFormats: true +}), "get"); +var transformOptions = /* @__PURE__ */ __name((options) => { + if (isString(options.ns)) options.ns = [options.ns]; + if (isString(options.fallbackLng)) options.fallbackLng = [options.fallbackLng]; + if (isString(options.fallbackNS)) options.fallbackNS = [options.fallbackNS]; + if (options.supportedLngs?.indexOf?.("cimode") < 0) { + options.supportedLngs = options.supportedLngs.concat(["cimode"]); + } + if (typeof options.initImmediate === "boolean") options.initAsync = options.initImmediate; + return options; +}, "transformOptions"); +var noop2 = /* @__PURE__ */ __name(() => { +}, "noop"); +var bindMemberFunctions = /* @__PURE__ */ __name((inst) => { + const mems = Object.getOwnPropertyNames(Object.getPrototypeOf(inst)); + mems.forEach((mem) => { + if (typeof inst[mem] === "function") { + inst[mem] = inst[mem].bind(inst); + } + }); +}, "bindMemberFunctions"); +var SUPPORT_NOTICE_KEY = "__i18next_supportNoticeShown"; +var getSupportNoticeShown = /* @__PURE__ */ __name(() => typeof globalThis !== "undefined" && !!globalThis[SUPPORT_NOTICE_KEY], "getSupportNoticeShown"); +var setSupportNoticeShown = /* @__PURE__ */ __name(() => { + if (typeof globalThis !== "undefined") globalThis[SUPPORT_NOTICE_KEY] = true; +}, "setSupportNoticeShown"); +var usesLocize = /* @__PURE__ */ __name((inst) => { + if (inst?.modules?.backend?.name?.indexOf("Locize") > 0) return true; + if (inst?.modules?.backend?.constructor?.name?.indexOf("Locize") > 0) return true; + if (inst?.options?.backend?.backends) { + if (inst.options.backend.backends.some((b) => b?.name?.indexOf("Locize") > 0 || b?.constructor?.name?.indexOf("Locize") > 0)) return true; + } + if (inst?.options?.backend?.projectId) return true; + if (inst?.options?.backend?.backendOptions) { + if (inst.options.backend.backendOptions.some((b) => b?.projectId)) return true; + } + return false; +}, "usesLocize"); +var I18n = class _I18n extends EventEmitter { + static { + __name(this, "I18n"); + } + constructor(options = {}, callback) { + super(); + this.options = transformOptions(options); + this.services = {}; + this.logger = baseLogger; + this.modules = { + external: [] + }; + bindMemberFunctions(this); + if (callback && !this.isInitialized && !options.isClone) { + if (!this.options.initAsync) { + this.init(options, callback); + return this; + } + setTimeout(() => { + this.init(options, callback); + }, 0); + } + } + init(options = {}, callback) { + this.isInitializing = true; + if (typeof options === "function") { + callback = options; + options = {}; + } + if (options.defaultNS == null && options.ns) { + if (isString(options.ns)) { + options.defaultNS = options.ns; + } else if (options.ns.indexOf("translation") < 0) { + options.defaultNS = options.ns[0]; + } + } + const defOpts = get(); + this.options = { + ...defOpts, + ...this.options, + ...transformOptions(options) + }; + this.options.interpolation = { + ...defOpts.interpolation, + ...this.options.interpolation + }; + if (options.keySeparator !== void 0) { + this.options.userDefinedKeySeparator = options.keySeparator; + } + if (options.nsSeparator !== void 0) { + this.options.userDefinedNsSeparator = options.nsSeparator; + } + if (typeof this.options.overloadTranslationOptionHandler !== "function") { + this.options.overloadTranslationOptionHandler = defOpts.overloadTranslationOptionHandler; + } + if (this.options.showSupportNotice !== false && !usesLocize(this) && !getSupportNoticeShown()) { + if (typeof console !== "undefined" && typeof console.info !== "undefined") console.info("\u{1F310} i18next is maintained with support from Locize \u2014 consider powering your project with managed localization (AI, CDN, integrations): https://locize.com \u{1F499}"); + setSupportNoticeShown(); + } + const createClassOnDemand = /* @__PURE__ */ __name((ClassOrObject) => { + if (!ClassOrObject) return null; + if (typeof ClassOrObject === "function") return new ClassOrObject(); + return ClassOrObject; + }, "createClassOnDemand"); + if (!this.options.isClone) { + if (this.modules.logger) { + baseLogger.init(createClassOnDemand(this.modules.logger), this.options); + } else { + baseLogger.init(null, this.options); + } + let formatter; + if (this.modules.formatter) { + formatter = this.modules.formatter; + } else { + formatter = Formatter; + } + const lu = new LanguageUtil(this.options); + this.store = new ResourceStore(this.options.resources, this.options); + const s2 = this.services; + s2.logger = baseLogger; + s2.resourceStore = this.store; + s2.languageUtils = lu; + s2.pluralResolver = new PluralResolver(lu, { + prepend: this.options.pluralSeparator, + simplifyPluralSuffix: this.options.simplifyPluralSuffix + }); + const usingLegacyFormatFunction = this.options.interpolation.format && this.options.interpolation.format !== defOpts.interpolation.format; + if (usingLegacyFormatFunction) { + this.logger.deprecate(`init: you are still using the legacy format function, please use the new approach: https://www.i18next.com/translation-function/formatting`); + } + if (formatter && (!this.options.interpolation.format || this.options.interpolation.format === defOpts.interpolation.format)) { + s2.formatter = createClassOnDemand(formatter); + if (s2.formatter.init) s2.formatter.init(s2, this.options); + this.options.interpolation.format = s2.formatter.format.bind(s2.formatter); + } + s2.interpolator = new Interpolator(this.options); + s2.utils = { + hasLoadedNamespace: this.hasLoadedNamespace.bind(this) + }; + s2.backendConnector = new Connector(createClassOnDemand(this.modules.backend), s2.resourceStore, s2, this.options); + s2.backendConnector.on("*", (event, ...args) => { + this.emit(event, ...args); + }); + if (this.modules.languageDetector) { + s2.languageDetector = createClassOnDemand(this.modules.languageDetector); + if (s2.languageDetector.init) s2.languageDetector.init(s2, this.options.detection, this.options); + } + if (this.modules.i18nFormat) { + s2.i18nFormat = createClassOnDemand(this.modules.i18nFormat); + if (s2.i18nFormat.init) s2.i18nFormat.init(this); + } + this.translator = new Translator(this.services, this.options); + this.translator.on("*", (event, ...args) => { + this.emit(event, ...args); + }); + this.modules.external.forEach((m2) => { + if (m2.init) m2.init(this); + }); + } + this.format = this.options.interpolation.format; + if (!callback) callback = noop2; + if (this.options.fallbackLng && !this.services.languageDetector && !this.options.lng) { + const codes = this.services.languageUtils.getFallbackCodes(this.options.fallbackLng); + if (codes.length > 0 && codes[0] !== "dev") this.options.lng = codes[0]; + } + if (!this.services.languageDetector && !this.options.lng) { + this.logger.warn("init: no languageDetector is used and no lng is defined"); + } + const storeApi = ["getResource", "hasResourceBundle", "getResourceBundle", "getDataByLanguage"]; + storeApi.forEach((fcName) => { + this[fcName] = (...args) => this.store[fcName](...args); + }); + const storeApiChained = ["addResource", "addResources", "addResourceBundle", "removeResourceBundle"]; + storeApiChained.forEach((fcName) => { + this[fcName] = (...args) => { + this.store[fcName](...args); + return this; + }; + }); + const deferred = defer(); + const load = /* @__PURE__ */ __name(() => { + const finish = /* @__PURE__ */ __name((err, t2) => { + this.isInitializing = false; + if (this.isInitialized && !this.initializedStoreOnce) this.logger.warn("init: i18next is already initialized. You should call init just once!"); + this.isInitialized = true; + if (!this.options.isClone) this.logger.log("initialized", this.options); + this.emit("initialized", this.options); + deferred.resolve(t2); + callback(err, t2); + }, "finish"); + if (this.languages && !this.isInitialized) return finish(null, this.t.bind(this)); + this.changeLanguage(this.options.lng, finish); + }, "load"); + if (this.options.resources || !this.options.initAsync) { + load(); + } else { + setTimeout(load, 0); + } + return deferred; + } + loadResources(language, callback = noop2) { + let usedCallback = callback; + const usedLng = isString(language) ? language : this.language; + if (typeof language === "function") usedCallback = language; + if (!this.options.resources || this.options.partialBundledLanguages) { + if (usedLng?.toLowerCase() === "cimode" && (!this.options.preload || this.options.preload.length === 0)) return usedCallback(); + const toLoad = []; + const append = /* @__PURE__ */ __name((lng) => { + if (!lng) return; + if (lng === "cimode") return; + const lngs = this.services.languageUtils.toResolveHierarchy(lng); + lngs.forEach((l) => { + if (l === "cimode") return; + if (toLoad.indexOf(l) < 0) toLoad.push(l); + }); + }, "append"); + if (!usedLng) { + const fallbacks = this.services.languageUtils.getFallbackCodes(this.options.fallbackLng); + fallbacks.forEach((l) => append(l)); + } else { + append(usedLng); + } + this.options.preload?.forEach?.((l) => append(l)); + this.services.backendConnector.load(toLoad, this.options.ns, (e) => { + if (!e && !this.resolvedLanguage && this.language) this.setResolvedLanguage(this.language); + usedCallback(e); + }); + } else { + usedCallback(null); + } + } + reloadResources(lngs, ns, callback) { + const deferred = defer(); + if (typeof lngs === "function") { + callback = lngs; + lngs = void 0; + } + if (typeof ns === "function") { + callback = ns; + ns = void 0; + } + if (!lngs) lngs = this.languages; + if (!ns) ns = this.options.ns; + if (!callback) callback = noop2; + this.services.backendConnector.reload(lngs, ns, (err) => { + deferred.resolve(); + callback(err); + }); + return deferred; + } + use(module) { + if (!module) throw new Error("You are passing an undefined module! Please check the object you are passing to i18next.use()"); + if (!module.type) throw new Error("You are passing a wrong module! Please check the object you are passing to i18next.use()"); + if (module.type === "backend") { + this.modules.backend = module; + } + if (module.type === "logger" || module.log && module.warn && module.error) { + this.modules.logger = module; + } + if (module.type === "languageDetector") { + this.modules.languageDetector = module; + } + if (module.type === "i18nFormat") { + this.modules.i18nFormat = module; + } + if (module.type === "postProcessor") { + postProcessor.addPostProcessor(module); + } + if (module.type === "formatter") { + this.modules.formatter = module; + } + if (module.type === "3rdParty") { + this.modules.external.push(module); + } + return this; + } + setResolvedLanguage(l) { + if (!l || !this.languages) return; + if (["cimode", "dev"].indexOf(l) > -1) return; + for (let li = 0; li < this.languages.length; li++) { + const lngInLngs = this.languages[li]; + if (["cimode", "dev"].indexOf(lngInLngs) > -1) continue; + if (this.store.hasLanguageSomeTranslations(lngInLngs)) { + this.resolvedLanguage = lngInLngs; + break; + } + } + if (!this.resolvedLanguage && this.languages.indexOf(l) < 0 && this.store.hasLanguageSomeTranslations(l)) { + this.resolvedLanguage = l; + this.languages.unshift(l); + } + } + changeLanguage(lng, callback) { + this.isLanguageChangingTo = lng; + const deferred = defer(); + this.emit("languageChanging", lng); + const setLngProps = /* @__PURE__ */ __name((l) => { + this.language = l; + this.languages = this.services.languageUtils.toResolveHierarchy(l); + this.resolvedLanguage = void 0; + this.setResolvedLanguage(l); + }, "setLngProps"); + const done = /* @__PURE__ */ __name((err, l) => { + if (l) { + if (this.isLanguageChangingTo === lng) { + setLngProps(l); + this.translator.changeLanguage(l); + this.isLanguageChangingTo = void 0; + this.emit("languageChanged", l); + this.logger.log("languageChanged", l); + } + } else { + this.isLanguageChangingTo = void 0; + } + deferred.resolve((...args) => this.t(...args)); + if (callback) callback(err, (...args) => this.t(...args)); + }, "done"); + const setLng = /* @__PURE__ */ __name((lngs) => { + if (!lng && !lngs && this.services.languageDetector) lngs = []; + const fl = isString(lngs) ? lngs : lngs && lngs[0]; + const l = this.store.hasLanguageSomeTranslations(fl) ? fl : this.services.languageUtils.getBestMatchFromCodes(isString(lngs) ? [lngs] : lngs); + if (l) { + if (!this.language) { + setLngProps(l); + } + if (!this.translator.language) this.translator.changeLanguage(l); + this.services.languageDetector?.cacheUserLanguage?.(l); + } + this.loadResources(l, (err) => { + done(err, l); + }); + }, "setLng"); + if (!lng && this.services.languageDetector && !this.services.languageDetector.async) { + setLng(this.services.languageDetector.detect()); + } else if (!lng && this.services.languageDetector && this.services.languageDetector.async) { + if (this.services.languageDetector.detect.length === 0) { + this.services.languageDetector.detect().then(setLng); + } else { + this.services.languageDetector.detect(setLng); + } + } else { + setLng(lng); + } + return deferred; + } + getFixedT(lng, ns, keyPrefix) { + const fixedT = /* @__PURE__ */ __name((key, opts, ...rest) => { + let o; + if (typeof opts !== "object") { + o = this.options.overloadTranslationOptionHandler([key, opts].concat(rest)); + } else { + o = { + ...opts + }; + } + o.lng = o.lng || fixedT.lng; + o.lngs = o.lngs || fixedT.lngs; + o.ns = o.ns || fixedT.ns; + if (o.keyPrefix !== "") o.keyPrefix = o.keyPrefix || keyPrefix || fixedT.keyPrefix; + const keySeparator = this.options.keySeparator || "."; + let resultKey; + if (o.keyPrefix && Array.isArray(key)) { + resultKey = key.map((k) => { + if (typeof k === "function") k = keysFromSelector(k, { + ...this.options, + ...opts + }); + return `${o.keyPrefix}${keySeparator}${k}`; + }); + } else { + if (typeof key === "function") key = keysFromSelector(key, { + ...this.options, + ...opts + }); + resultKey = o.keyPrefix ? `${o.keyPrefix}${keySeparator}${key}` : key; + } + return this.t(resultKey, o); + }, "fixedT"); + if (isString(lng)) { + fixedT.lng = lng; + } else { + fixedT.lngs = lng; + } + fixedT.ns = ns; + fixedT.keyPrefix = keyPrefix; + return fixedT; + } + t(...args) { + return this.translator?.translate(...args); + } + exists(...args) { + return this.translator?.exists(...args); + } + setDefaultNamespace(ns) { + this.options.defaultNS = ns; + } + hasLoadedNamespace(ns, options = {}) { + if (!this.isInitialized) { + this.logger.warn("hasLoadedNamespace: i18next was not initialized", this.languages); + return false; + } + if (!this.languages || !this.languages.length) { + this.logger.warn("hasLoadedNamespace: i18n.languages were undefined or empty", this.languages); + return false; + } + const lng = options.lng || this.resolvedLanguage || this.languages[0]; + const fallbackLng = this.options ? this.options.fallbackLng : false; + const lastLng = this.languages[this.languages.length - 1]; + if (lng.toLowerCase() === "cimode") return true; + const loadNotPending = /* @__PURE__ */ __name((l, n) => { + const loadState = this.services.backendConnector.state[`${l}|${n}`]; + return loadState === -1 || loadState === 0 || loadState === 2; + }, "loadNotPending"); + if (options.precheck) { + const preResult = options.precheck(this, loadNotPending); + if (preResult !== void 0) return preResult; + } + if (this.hasResourceBundle(lng, ns)) return true; + if (!this.services.backendConnector.backend || this.options.resources && !this.options.partialBundledLanguages) return true; + if (loadNotPending(lng, ns) && (!fallbackLng || loadNotPending(lastLng, ns))) return true; + return false; + } + loadNamespaces(ns, callback) { + const deferred = defer(); + if (!this.options.ns) { + if (callback) callback(); + return Promise.resolve(); + } + if (isString(ns)) ns = [ns]; + ns.forEach((n) => { + if (this.options.ns.indexOf(n) < 0) this.options.ns.push(n); + }); + this.loadResources((err) => { + deferred.resolve(); + if (callback) callback(err); + }); + return deferred; + } + loadLanguages(lngs, callback) { + const deferred = defer(); + if (isString(lngs)) lngs = [lngs]; + const preloaded = this.options.preload || []; + const newLngs = lngs.filter((lng) => preloaded.indexOf(lng) < 0 && this.services.languageUtils.isSupportedCode(lng)); + if (!newLngs.length) { + if (callback) callback(); + return Promise.resolve(); + } + this.options.preload = preloaded.concat(newLngs); + this.loadResources((err) => { + deferred.resolve(); + if (callback) callback(err); + }); + return deferred; + } + dir(lng) { + if (!lng) lng = this.resolvedLanguage || (this.languages?.length > 0 ? this.languages[0] : this.language); + if (!lng) return "rtl"; + try { + const l = new Intl.Locale(lng); + if (l && l.getTextInfo) { + const ti = l.getTextInfo(); + if (ti && ti.direction) return ti.direction; + } + } catch (e) { + } + const rtlLngs = ["ar", "shu", "sqr", "ssh", "xaa", "yhd", "yud", "aao", "abh", "abv", "acm", "acq", "acw", "acx", "acy", "adf", "ads", "aeb", "aec", "afb", "ajp", "apc", "apd", "arb", "arq", "ars", "ary", "arz", "auz", "avl", "ayh", "ayl", "ayn", "ayp", "bbz", "pga", "he", "iw", "ps", "pbt", "pbu", "pst", "prp", "prd", "ug", "ur", "ydd", "yds", "yih", "ji", "yi", "hbo", "men", "xmn", "fa", "jpr", "peo", "pes", "prs", "dv", "sam", "ckb"]; + const languageUtils = this.services?.languageUtils || new LanguageUtil(get()); + if (lng.toLowerCase().indexOf("-latn") > 1) return "ltr"; + return rtlLngs.indexOf(languageUtils.getLanguagePartFromCode(lng)) > -1 || lng.toLowerCase().indexOf("-arab") > 1 ? "rtl" : "ltr"; + } + static createInstance(options = {}, callback) { + const instance2 = new _I18n(options, callback); + instance2.createInstance = _I18n.createInstance; + return instance2; + } + cloneInstance(options = {}, callback = noop2) { + const forkResourceStore = options.forkResourceStore; + if (forkResourceStore) delete options.forkResourceStore; + const mergedOptions = { + ...this.options, + ...options, + ...{ + isClone: true + } + }; + const clone = new _I18n(mergedOptions); + if (options.debug !== void 0 || options.prefix !== void 0) { + clone.logger = clone.logger.clone(options); + } + const membersToCopy = ["store", "services", "language"]; + membersToCopy.forEach((m2) => { + clone[m2] = this[m2]; + }); + clone.services = { + ...this.services + }; + clone.services.utils = { + hasLoadedNamespace: clone.hasLoadedNamespace.bind(clone) + }; + if (forkResourceStore) { + const clonedData = Object.keys(this.store.data).reduce((prev, l) => { + prev[l] = { + ...this.store.data[l] + }; + prev[l] = Object.keys(prev[l]).reduce((acc, n) => { + acc[n] = { + ...prev[l][n] + }; + return acc; + }, prev[l]); + return prev; + }, {}); + clone.store = new ResourceStore(clonedData, mergedOptions); + clone.services.resourceStore = clone.store; + } + if (options.interpolation) { + const defOpts = get(); + const mergedInterpolation = { + ...defOpts.interpolation, + ...this.options.interpolation, + ...options.interpolation + }; + const mergedForInterpolator = { + ...mergedOptions, + interpolation: mergedInterpolation + }; + clone.services.interpolator = new Interpolator(mergedForInterpolator); + } + clone.translator = new Translator(clone.services, mergedOptions); + clone.translator.on("*", (event, ...args) => { + clone.emit(event, ...args); + }); + clone.init(mergedOptions, callback); + clone.translator.options = mergedOptions; + clone.translator.backendConnector.services.utils = { + hasLoadedNamespace: clone.hasLoadedNamespace.bind(clone) + }; + return clone; + } + toJSON() { + return { + options: this.options, + store: this.store, + language: this.language, + languages: this.languages, + resolvedLanguage: this.resolvedLanguage + }; + } +}; +var instance = I18n.createInstance(); +var createInstance = instance.createInstance; +var dir = instance.dir; +var init = instance.init; +var loadResources = instance.loadResources; +var reloadResources = instance.reloadResources; +var use = instance.use; +var changeLanguage = instance.changeLanguage; +var getFixedT = instance.getFixedT; +var t = instance.t; +var exists2 = instance.exists; +var setDefaultNamespace = instance.setDefaultNamespace; +var hasLoadedNamespace = instance.hasLoadedNamespace; +var loadNamespaces = instance.loadNamespaces; +var loadLanguages = instance.loadLanguages; + +// locales/en.json +var en_default = { + language: { + name: "English", + changed: "Language is set to english.", + emoji: "\u{1F1EC}\u{1F1E7}" + }, + bot: { + description: "Hello! I will notify you when Twitch broadcasts start." + }, + enable: "Enable", + disable: "Disable", + enabled: "Enabled", + disabled: "Disabled", + commands: { + follow: { + errors: { + badUsername: '{{ streamer }} - username can only contain "a-z", "0-9" and "_" symbols.', + streamerNotFound: "{{ streamer }} - not found on twitch.", + alreadyFollowed: "{{ streamer }} - already followed." + }, + success: "{{ streamer }} - now followed.", + enter: "Enter username of streamer you want to follow.\nYou can use multiple links to streamers.\n\nType /cancel for cancel action." + }, + follows: { + total: "You followed to notifications from {{ count }} channels. Click on streamer nickname to unfollow from notifications." + }, + unfollow: { + callbackButton: "Unfollow {{ streamer }}", + success: "Unfollowed from {{ streamer }}" + }, + start: { + game_change_notification_setting: { + button: "Game change notification" + }, + language: { + button: "\u{1F30D} Language" + }, + offline_notification: { + button: "Offline notification" + }, + title_change_notification_setting: { + button: "Title change notification" + }, + image_in_notification_setting: { + button: "Show images in notifications" + }, + game_and_title_change_notification_setting: { + button: "Game and title change notification" + } + } + }, + notifications: { + streams: { + nowOffline: "\u{1F534} {{ channelLink }} now offline.\n{{ categories }}\n{{ duration }}", + nowOnline: "\u{1F7E2} {{ channelLink }} now online.\nCategory: {{ category }}\nTitle: {{ title }}", + newCategory: "\u{1F504} {{ channelLink }} updated category from {{ oldCategory }} to {{ category }}", + titleChanged: "\u{1F504} {{ channelLink }} updated title from {{ oldTitle }} to {{ title }}", + titleAndCategoryChanged: "\u{1F504} {{ channelLink }} updated title from {{ oldTitle }} to {{ title }} and category from {{ oldCategory }} to {{ category }}" + } + } +}; + +// locales/ru.json +var ru_default = { + language: { + name: "\u0420\u0443\u0441\u0441\u043A\u0438\u0439", + changed: "\u042F\u0437\u044B\u043A \u0443\u0441\u0442\u0430\u043D\u043E\u0432\u043B\u0435\u043D \u043D\u0430 \u0440\u0443\u0441\u0441\u043A\u0438\u0439.", + emoji: "\u{1F1F7}\u{1F1FA}" + }, + bot: { + description: "\u0417\u0434\u0440\u0430\u0432\u0441\u0442\u0432\u0443\u0439\u0442\u0435! \u042F \u0431\u0443\u0434\u0443 \u0443\u0432\u0435\u0434\u043E\u043C\u043B\u044F\u0442\u044C \u0432\u0430\u0441 \u043E \u043D\u0430\u0447\u0430\u043B\u0435 \u0442\u0440\u0430\u043D\u0441\u043B\u044F\u0446\u0438\u0439 Twitch." + }, + enable: "\u0412\u043A\u043B\u044E\u0447\u0438\u0442\u044C", + disable: "\u0412\u044B\u043A\u043B\u044E\u0447\u0438\u0442\u044C", + enabled: "\u0412\u043A\u043B\u044E\u0447\u0435\u043D\u043E", + disabled: "\u0412\u044B\u043A\u043B\u044E\u0447\u0435\u043D\u043E", + commands: { + follow: { + errors: { + badUsername: '\u0418\u043C\u044F \u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044F \u043C\u043E\u0436\u0435\u0442 \u0441\u043E\u0434\u0435\u0440\u0436\u0430\u0442\u044C \u0442\u043E\u043B\u044C\u043A\u043E "a-z", "0-9" and "_" \u0441\u0438\u043C\u0432\u043E\u043B\u044B.', + streamerNotFound: "{{ streamer }} - \u043D\u0435 \u043D\u0430\u0439\u0434\u0435\u043D \u043D\u0430 \u0442\u0432\u0438\u0447\u0435.", + alreadyFollowed: "{{ streamer }} - \u0432\u044B \u0443\u0436\u0435 \u043F\u043E\u0434\u043F\u0438\u0441\u0430\u043D\u044B." + }, + success: "{{ streamer }} - \u0442\u0435\u043F\u0435\u0440\u044C \u043E\u0442\u0441\u043B\u0435\u0436\u0438\u0432\u0430\u0435\u0442\u0441\u044F.", + enter: "\u0412\u0432\u0435\u0434\u0438\u0442\u0435 \u0438\u043C\u044F \u0441\u0442\u0440\u0438\u043C\u0435\u0440\u0430, \u0443\u0432\u0435\u0434\u043E\u043C\u043B\u0435\u043D\u0438\u044F \u043E\u0442 \u043A\u043E\u0442\u043E\u0440\u043E\u0433\u043E \u0445\u043E\u0442\u0438\u0442\u0435 \u043F\u043E\u043B\u0443\u0447\u0430\u0442\u044C.\n\u0412\u044B \u043C\u043E\u0436\u0435\u0442\u0435 \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u044C \u0441\u0441\u044B\u043B\u043A\u0438.\n\n\u0412\u0432\u0435\u0434\u0438\u0442\u0435 /cancel \u0434\u043B\u044F \u043E\u0442\u043C\u0435\u043D\u044B \u0434\u0435\u0439\u0441\u0442\u0432\u0438\u044F." + }, + follows: { + total: "\u0412\u044B \u043F\u043E\u0434\u043F\u0438\u0441\u0430\u043D\u044B \u043D\u0430 \u0443\u0432\u0435\u0434\u043E\u043C\u043B\u0435\u043D\u0438\u044F {{ count }} \u043A\u0430\u043D\u0430\u043B\u043E\u0432. \u041A\u043B\u0438\u043A\u043D\u0438\u0442\u0435 \u043D\u0430 \u043D\u0438\u043A\u043D\u0435\u0439\u043C \u0441\u0442\u0440\u0438\u043C\u0435\u0440\u0430, \u0447\u0442\u043E\u0431\u044B \u043E\u0442\u043F\u0438\u0441\u0430\u0442\u044C\u0441\u044F \u043E\u0442 \u0443\u0432\u0435\u0434\u043E\u043C\u043B\u0435\u043D\u0438\u0439." + }, + unfollow: { + callbackButton: "\u041E\u0442\u043F\u0438\u0441\u0430\u0442\u044C\u0441\u044F \u043E\u0442 {{ streamer }}", + success: "\u0412\u044B \u043E\u0442\u043F\u0438\u0441\u0430\u043B\u0438\u0441\u044C \u043E\u0442 {{ streamer }}" + }, + start: { + game_change_notification_setting: { + button: "\u0423\u0432\u0435\u0434\u043E\u043C\u043B\u0435\u043D\u0438\u0435 \u043E \u0441\u043C\u0435\u043D\u0435 \u043A\u0430\u0442\u0435\u0433\u043E\u0440\u0438\u0438" + }, + language: { + button: "\u{1F30D} \u042F\u0437\u044B\u043A" + }, + offline_notification: { + button: "\u0423\u0432\u0435\u0434\u043E\u043C\u043B\u0435\u043D\u0438\u0435 \u043E\u0431 \u0443\u0445\u043E\u0434\u0435 \u0432 \u043E\u0444\u0444\u043B\u0430\u0439\u043D" + }, + title_change_notification_setting: { + button: "\u0423\u0432\u0435\u0434\u043E\u043C\u043B\u0435\u043D\u0438\u0435 \u043E \u0441\u043C\u0435\u043D\u0435 \u043D\u0430\u0437\u0432\u0430\u043D\u0438\u044F" + }, + image_in_notification_setting: { + button: "\u041F\u043E\u043A\u0430\u0437\u044B\u0432\u0430\u0442\u044C \u0438\u0437\u043E\u0431\u0440\u0430\u0436\u0435\u043D\u0438\u044F \u0432 \u0443\u0432\u0435\u0434\u043E\u043C\u043B\u0435\u043D\u0438\u044F\u0445" + }, + game_and_title_change_notification_setting: { + button: "\u0423\u0432\u0435\u0434\u043E\u043C\u0435\u043B\u043D\u0438\u0435 \u043E \u0441\u043C\u0435\u043D\u0435 \u043A\u0430\u0442\u0435\u0433\u043E\u0440\u0438\u0438 \u0438 \u043D\u0430\u0437\u0432\u0430\u043D\u0438\u044F" + } + } + }, + notifications: { + streams: { + nowOffline: "\u{1F534} {{ channelLink }} \u0442\u0435\u043F\u0435\u0440\u044C \u043E\u0444\u0444\u043B\u0430\u0439\u043D.\n{{ categories }}\n{{ duration }}", + nowOnline: "\u{1F7E2} {{ channelLink }} \u0442\u0435\u043F\u0435\u0440\u044C \u043E\u043D\u043B\u0430\u0439\u043D.\n\u041A\u0430\u0442\u0435\u0433\u043E\u0440\u0438\u044F: {{ category }}\n\u041D\u0430\u0437\u0432\u0430\u043D\u0438\u0435: {{ title }}", + newCategory: "\u{1F504} \u041D\u0430 \u043A\u0430\u043D\u0430\u043B\u0435 {{ channelLink }} \u0438\u0437\u043C\u0435\u043D\u0430\u043B\u0430\u0441\u044C \u043A\u0430\u0442\u0435\u0433\u043E\u0440\u0438\u044F \u0441 {{ oldCategory }} \u043D\u0430 {{ category }}", + titleChanged: "\u{1F504} \u041D\u0430 \u043A\u0430\u043D\u0430\u043B\u0435 {{ channelLink }} \u0438\u0437\u043C\u0435\u043D\u0438\u043B\u043E\u0441\u044C \u043D\u0430\u0437\u0432\u0430\u043D\u0438\u0435 \u0441 {{ oldTitle }} \u043D\u0430 {{ title }}", + titleAndCategoryChanged: "\u{1F504} \u041D\u0430 \u043A\u0430\u043D\u0430\u043B\u0435 {{ channelLink }} \u0438\u0437\u043C\u0435\u043D\u0438\u043B\u0438\u0441\u044C \u043D\u0430\u0437\u0432\u0430\u043D\u0438\u0435 \u0441 {{ oldTitle }} \u043D\u0430 {{ title }} \u0438 \u043A\u0430\u0442\u0435\u0433\u043E\u0440\u0438\u044F \u0441 {{ oldCategory }} \u043D\u0430 {{ category }}" + } + } +}; + +// locales/uk.json +var uk_default = { + language: { + name: "\u0423\u043A\u0440\u0430\u0457\u043D\u0441\u044C\u043A\u0430", + changed: "\u041C\u043E\u0432\u0430 \u0437\u043C\u0456\u043D\u0435\u043D\u0430 \u043D\u0430 \u0443\u043A\u0440\u0430\u0457\u043D\u0441\u044C\u043A\u0443.", + emoji: "\u{1F1FA}\u{1F1E6}" + }, + bot: { + description: "\u0417\u0434\u0440\u0430\u0441\u0442\u0432\u0443\u0439\u0442\u0435! \u042F \u0431\u0443\u0434\u0443 \u0441\u043F\u043E\u0432\u0456\u0449\u0430\u0442\u0438 \u0432\u0430\u0441 \u043F\u0440\u043E \u043F\u043E\u0447\u0430\u0442\u043E\u043A Twitch \u0442\u0440\u0430\u043D\u0441\u043B\u044F\u0446\u0456\u0439." + }, + enable: "\u0423\u0432\u0456\u043C\u043A\u043D\u0443\u0442\u0438", + disable: "\u0412\u0438\u043C\u043A\u043D\u0443\u0442\u0438", + enabled: "\u0423\u0432\u0456\u043C\u043A\u043D\u0435\u043D\u043E", + disabled: "\u0412\u0456\u043C\u043A\u043D\u0435\u043D\u043E", + commands: { + follow: { + errors: { + badUsername: '\u0406\u043C\u02BC\u044F \u043A\u043E\u0440\u0438\u0441\u0442\u0443\u0432\u0430\u0447\u0430 \u043C\u043E\u0436\u0435 \u043C\u0430\u0442\u0438 \u0442\u0456\u043B\u044C\u043A\u0438 "a-z", "0-9" \u0442\u0430 "_" \u0441\u0438\u043C\u0432\u043E\u043B\u0438.', + streamerNotFound: "{{ streamer }} - \u043D\u0435 \u0437\u043D\u0430\u0439\u0434\u0435\u043D\u0438\u0439 \u043D\u0430 \u0442\u0432\u0456\u0447\u0456.", + alreadyFollowed: "{{ streamer }} - \u0432\u0438 \u0432\u0436\u0435 \u043F\u0456\u0434\u043F\u0438\u0441\u0430\u043D\u0456." + }, + success: "{{ streamer }} - \u0442\u0435\u043F\u0435\u0440 \u0432\u0456\u0434\u0441\u043B\u0456\u0434\u043A\u043E\u0432\u0443\u0454\u0442\u044C\u0441\u044F.", + enter: "\u0412\u0432\u0435\u0434\u0456\u0442\u044C \u0456\u043C\u02BC\u044F \u0441\u0442\u0440\u0456\u043C\u0435\u0440\u0430, \u0441\u043F\u043E\u0432\u0456\u0449\u0435\u043D\u043D\u044F \u0432\u0456\u0434 \u044F\u043A\u043E\u0433\u043E \u0432\u0438 \u0445\u043E\u0447\u0435\u0442\u0435 \u043E\u0442\u0440\u0438\u043C\u0443\u0432\u0430\u0442\u0438.\n\u0412\u0438 \u043C\u043E\u0436\u0435\u0442\u0435 \u0432\u0438\u043A\u043E\u0440\u0438\u0441\u0442\u043E\u0432\u0443\u0432\u0430\u0442\u0438 \u043F\u043E\u0441\u0438\u043B\u0430\u043D\u043D\u044F.\n\n\u0412\u0432\u0435\u0434\u0456\u0442\u044C /cancel \u0434\u043B\u044F \u0441\u043A\u0430\u0441\u0443\u0432\u0430\u043D\u043D\u044F \u0434\u0456\u0457." + }, + follows: { + total: "\u0412\u0438 \u043F\u0456\u0434\u043F\u0438\u0441\u0430\u043D\u0456 \u043D\u0430 \u0441\u043F\u043E\u0432\u0456\u0449\u0435\u043D\u043D\u044F \u0432\u0456\u0434 {{ count }} \u043A\u0430\u043D\u0430\u043B\u0456\u0432. \u041A\u043B\u0430\u0446\u043D\u0456\u0442\u044C \u043D\u0430 \u043D\u0456\u043A\u043D\u0435\u0439\u043C \u0441\u0442\u0440\u0456\u043C\u0435\u0440\u0430, \u0449\u043E\u0431 \u0432\u0456\u0434\u043F\u0438\u0441\u0430\u0442\u0438\u0441\u044C \u0432\u0456\u0434 \u0441\u043F\u043E\u0432\u0456\u0449\u0435\u043D\u044C." + }, + unfollow: { + callbackButton: "\u0412\u0456\u0434\u043F\u0438\u0441\u0430\u0442\u0438\u0441\u044C \u0432\u0456\u0434 {{ streamer }}", + success: "\u0412\u0438 \u0432\u0456\u0434\u043F\u0438\u0441\u0430\u043B\u0438\u0441\u044C \u0432\u0456\u0434 {{ streamer }}" + }, + start: { + game_change_notification_setting: { + button: "\u0421\u043F\u043E\u0432\u0456\u0449\u0435\u043D\u043D\u044F \u043F\u0440\u043E \u0437\u043C\u0456\u043D\u0443 \u043A\u0430\u0442\u0435\u0433\u043E\u0440\u0456\u0457" + }, + language: { + button: "\u{1F30D} \u041C\u043E\u0432\u0430" + }, + offline_notification: { + button: "\u0421\u043F\u043E\u0432\u0456\u0449\u0435\u043D\u043D\u044F \u043F\u0440\u0438 \u0443\u0445\u043E\u0434\u0456 \u0432 \u043E\u0444\u0444\u043B\u0430\u0439\u043D" + }, + title_change_notification_setting: { + button: "\u0421\u043F\u043E\u0432\u0456\u0449\u0435\u043D\u043D\u044F \u043F\u0440\u043E \u0437\u043C\u0456\u043D\u0443 \u043D\u0430\u0437\u0432\u0438" + }, + image_in_notification_setting: { + button: "\u041F\u043E\u043A\u0430\u0437\u0443\u0432\u0430\u0442\u0438 \u0437\u043E\u0431\u0440\u0430\u0436\u0435\u043D\u043D\u044F \u0432 \u0441\u043F\u043E\u0432\u0456\u0449\u0435\u043D\u043D\u044F\u0445" + }, + game_and_title_change_notification_setting: { + button: "\u0421\u043F\u043E\u0432\u0456\u0449\u0435\u043D\u043D\u044F \u043F\u0440\u043E \u0437\u043C\u0456\u043D\u0443 \u043A\u0430\u0442\u0435\u0433\u043E\u0440\u0456\u0457 \u0442\u0430 \u043D\u0430\u0437\u0432\u0438" + } + } + }, + notifications: { + streams: { + nowOffline: "\u{1F534} {{ channelLink }} \u0442\u0435\u043F\u0435\u0440 \u043E\u0444\u0444\u043B\u0430\u0439\u043D.\n{{ categories }}\n{{ duration }}", + nowOnline: "\u{1F7E2} {{ channelLink }} \u0442\u0435\u043F\u0435\u0440 \u043E\u043D\u043B\u0430\u0439\u043D.\n\u041A\u0430\u0442\u0435\u0433\u043E\u0440\u0456\u044F: {{ category }}\n\u041D\u0430\u0437\u0432\u0430: {{ title }}", + newCategory: "\u{1F504} \u041D\u0430 \u043A\u0430\u043D\u0430\u043B\u0456 {{ channelLink }} \u0431\u0443\u043B\u0430 \u0437\u043C\u0456\u043D\u0435\u043D\u0430 \u043A\u0430\u0442\u0435\u0433\u043E\u0440\u0456\u044F \u0437 {{ oldCategory }} \u043D\u0430 {{ category }}", + titleChanged: "\u{1F504} \u041D\u0430 \u043A\u0430\u043D\u0430\u043B\u0456{{ channelLink }} \u0431\u0443\u043B\u0430 \u0437\u043C\u0456\u043D\u0435\u043D\u0430 \u043D\u0430\u0437\u0432\u0430 \u0437 {{ oldTitle }} \u043D\u0430 {{ title }}", + titleAndCategoryChanged: "\u{1F504} \u041D\u0430 \u043A\u0430\u043D\u0430\u043B\u0456 {{ channelLink }} \u0431\u0443\u043B\u0430 \u0437\u043C\u0456\u043D\u0435\u043D\u0430 \u043D\u0430\u0437\u0432\u0430 \u0437 {{ oldTitle }} \u043D\u0430 {{ title }} \u0442\u0430 \u043A\u0430\u0442\u0435\u0433\u043E\u0440\u0456\u044F \u0437 {{ oldCategory }} \u043D\u0430 {{ category }}" + } + } +}; + +// src/services/i18n.service.ts +var I18nService = class { + static { + __name(this, "I18nService"); + } + i18n; + initialized = false; + constructor() { + this.i18n = instance.createInstance(); + } + /** + * Initialize i18next instance with locales + * Must be called before using the service + */ + async init() { + if (this.initialized) return; + await this.i18n.init({ + lng: "en", + fallbackLng: "en", + defaultNS: "translation", + ns: ["translation"], + resources: { + en: { translation: en_default }, + ru: { translation: ru_default }, + uk: { translation: uk_default } + }, + interpolation: { + escapeValue: false + // Not needed for Telegram (no XSS risk) + } + }); + this.initialized = true; + } + /** + * Get translated string + * @param locale - Language code + * @param key - Translation key (dot notation) + * @param params - Template parameters + */ + t(locale, key, params) { + if (!this.initialized) { + throw new Error("I18nService not initialized. Call init() first."); + } + return this.i18n.t(key, { ...params, lng: locale }); + } + /** + * Get Grammy middleware that attaches t() function to context + */ + middleware() { + return async (ctx, next) => { + const language = ctx.session?.language || "en"; + ctx.t = (key, params) => { + return this.t(language, key, params); + }; + await next(); + }; + } + /** + * Get all available locales + */ + getAvailableLocales() { + return ["en", "ru", "uk"]; + } + /** + * Check if locale is supported + */ + isValidLocale(locale) { + return ["en", "ru", "uk"].includes(locale); + } +}; + +// src/services/twitch.service.ts +init_modules_watch_stub(); +init_performance2(); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/index.js +init_modules_watch_stub(); +init_performance2(); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/client/ApiClient.js +init_modules_watch_stub(); +init_performance2(); + +// node_modules/.pnpm/tslib@2.8.1/node_modules/tslib/tslib.es6.mjs +init_modules_watch_stub(); +init_performance2(); +var extendStatics = /* @__PURE__ */ __name(function(d2, b) { + extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d3, b2) { + d3.__proto__ = b2; + } || function(d3, b2) { + for (var p in b2) if (Object.prototype.hasOwnProperty.call(b2, p)) d3[p] = b2[p]; + }; + return extendStatics(d2, b); +}, "extendStatics"); +function __extends(d2, b) { + if (typeof b !== "function" && b !== null) + throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); + extendStatics(d2, b); + function __() { + this.constructor = d2; + } + __name(__, "__"); + d2.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +} +__name(__extends, "__extends"); +function __decorate(decorators, target, key, desc2) { + var c = arguments.length, r = c < 3 ? target : desc2 === null ? desc2 = Object.getOwnPropertyDescriptor(target, key) : desc2, d2; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc2); + else for (var i = decorators.length - 1; i >= 0; i--) if (d2 = decorators[i]) r = (c < 3 ? d2(r) : c > 3 ? d2(target, key, r) : d2(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; +} +__name(__decorate, "__decorate"); +function __read(o, n) { + var m2 = typeof Symbol === "function" && o[Symbol.iterator]; + if (!m2) return o; + var i = m2.call(o), r, ar = [], e; + try { + while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); + } catch (error) { + e = { error }; + } finally { + try { + if (r && !r.done && (m2 = i["return"])) m2.call(i); + } finally { + if (e) throw e.error; + } + } + return ar; +} +__name(__read, "__read"); +function __spreadArray(to, from, pack) { + if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { + if (ar || !(i in from)) { + if (!ar) ar = Array.prototype.slice.call(from, 0, i); + ar[i] = from[i]; + } + } + return to.concat(ar || Array.prototype.slice.call(from)); +} +__name(__spreadArray, "__spreadArray"); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/client/ApiClient.js +var import_detect_node4 = __toESM(require_browser(), 1); + +// node_modules/.pnpm/@d-fischer+logger@4.2.4/node_modules/@d-fischer/logger/es/index.mjs +init_modules_watch_stub(); +init_performance2(); + +// node_modules/.pnpm/@d-fischer+logger@4.2.4/node_modules/@d-fischer/logger/es/createLogger.mjs +init_modules_watch_stub(); +init_performance2(); +var import_detect_node3 = __toESM(require_browser(), 1); + +// node_modules/.pnpm/@d-fischer+logger@4.2.4/node_modules/@d-fischer/logger/es/BrowserLogger.mjs +init_modules_watch_stub(); +init_performance2(); + +// node_modules/.pnpm/@d-fischer+logger@4.2.4/node_modules/@d-fischer/logger/es/LogLevel.mjs +init_modules_watch_stub(); +init_performance2(); +var import_detect_node = __toESM(require_browser(), 1); +var _a; +var LogLevel; +(function(LogLevel2) { + LogLevel2[LogLevel2["CRITICAL"] = 0] = "CRITICAL"; + LogLevel2[LogLevel2["ERROR"] = 1] = "ERROR"; + LogLevel2[LogLevel2["WARNING"] = 2] = "WARNING"; + LogLevel2[LogLevel2["INFO"] = 3] = "INFO"; + LogLevel2[LogLevel2["DEBUG"] = 4] = "DEBUG"; + LogLevel2[LogLevel2["TRACE"] = 7] = "TRACE"; +})(LogLevel || (LogLevel = {})); +function resolveLogLevel(level) { + if (typeof level === "number") { + if (Object.prototype.hasOwnProperty.call(LogLevel, level)) { + return level; + } + var eligibleLevels = Object.keys(LogLevel).map(function(k) { + return parseInt(k, 10); + }).filter(function(k) { + return !isNaN(k) && k < level; + }); + if (!eligibleLevels.length) { + return LogLevel.WARNING; + } + return Math.max.apply(Math, eligibleLevels); + } + var strLevel = level.replace(/\d+$/, "").toUpperCase(); + if (!Object.prototype.hasOwnProperty.call(LogLevel, strLevel)) { + throw new Error("Unknown log level string: ".concat(level)); + } + return LogLevel[strLevel]; +} +__name(resolveLogLevel, "resolveLogLevel"); +var debugFunction = import_detect_node.isNode ? console.log.bind(console) : console.debug.bind(console); +var LogLevelToConsoleFunction = (_a = {}, _a[LogLevel.CRITICAL] = console.error.bind(console), _a[LogLevel.ERROR] = console.error.bind(console), _a[LogLevel.WARNING] = console.warn.bind(console), _a[LogLevel.INFO] = console.info.bind(console), _a[LogLevel.DEBUG] = debugFunction.bind(console), _a[LogLevel.TRACE] = console.trace.bind(console), _a); + +// node_modules/.pnpm/@d-fischer+logger@4.2.4/node_modules/@d-fischer/logger/es/BaseLogger.mjs +init_modules_watch_stub(); +init_performance2(); + +// node_modules/.pnpm/@d-fischer+shared-utils@3.6.4/node_modules/@d-fischer/shared-utils/es/index.mjs +init_modules_watch_stub(); +init_performance2(); + +// node_modules/.pnpm/@d-fischer+shared-utils@3.6.4/node_modules/@d-fischer/shared-utils/es/decorators/Enumerable.mjs +init_modules_watch_stub(); +init_performance2(); +function Enumerable(enumerable) { + if (enumerable === void 0) { + enumerable = true; + } + return function(target, key) { + Object.defineProperty(target, key, { + get: /* @__PURE__ */ __name(function() { + return; + }, "get"), + // eslint-disable-next-line @typescript-eslint/no-explicit-any + set: /* @__PURE__ */ __name(function(val) { + Object.defineProperty(this, key, { + value: val, + writable: true, + enumerable + }); + }, "set"), + enumerable + }); + }; +} +__name(Enumerable, "Enumerable"); + +// node_modules/.pnpm/@d-fischer+shared-utils@3.6.4/node_modules/@d-fischer/shared-utils/es/functions/array/flatten.mjs +init_modules_watch_stub(); +init_performance2(); +function flatten2(arr) { + var _a4; + return (_a4 = []).concat.apply(_a4, __spreadArray([], __read(arr), false)); +} +__name(flatten2, "flatten"); + +// node_modules/.pnpm/@d-fischer+shared-utils@3.6.4/node_modules/@d-fischer/shared-utils/es/functions/object/arrayToObject.mjs +init_modules_watch_stub(); +init_performance2(); +function arrayToObject(arr, fn) { + return Object.assign.apply(Object, __spreadArray([{}], __read(arr.map(fn)), false)); +} +__name(arrayToObject, "arrayToObject"); + +// node_modules/.pnpm/@d-fischer+shared-utils@3.6.4/node_modules/@d-fischer/shared-utils/es/functions/object/indexBy.mjs +init_modules_watch_stub(); +init_performance2(); +function indexBy(arr, keyFn) { + if (typeof keyFn !== "function") { + var key_1 = keyFn; + keyFn = /* @__PURE__ */ __name((function(value) { + return value[key_1].toString(); + }), "keyFn"); + } + return arrayToObject(arr, function(val) { + var _a4; + return _a4 = {}, _a4[keyFn(val)] = val, _a4; + }); +} +__name(indexBy, "indexBy"); + +// node_modules/.pnpm/@d-fischer+shared-utils@3.6.4/node_modules/@d-fischer/shared-utils/es/functions/optional/mapOptional.mjs +init_modules_watch_stub(); +init_performance2(); +function isNullish(value) { + return value == null; +} +__name(isNullish, "isNullish"); +function mapNullable(value, cb) { + return isNullish(value) ? null : cb(value); +} +__name(mapNullable, "mapNullable"); +function mapOptional(value, cb) { + return isNullish(value) ? void 0 : cb(value); +} +__name(mapOptional, "mapOptional"); + +// node_modules/.pnpm/@d-fischer+shared-utils@3.6.4/node_modules/@d-fischer/shared-utils/es/functions/promise/withResolvers.mjs +init_modules_watch_stub(); +init_performance2(); +function promiseWithResolvers() { + var resolve; + var reject; + var promise = new Promise(function(_resolve, _reject) { + resolve = _resolve; + reject = _reject; + }); + return { promise, resolve, reject }; +} +__name(promiseWithResolvers, "promiseWithResolvers"); + +// node_modules/.pnpm/@d-fischer+logger@4.2.4/node_modules/@d-fischer/logger/es/BaseLogger.mjs +var import_detect_node2 = __toESM(require_browser(), 1); + +// node_modules/.pnpm/@d-fischer+logger@4.2.4/node_modules/@d-fischer/logger/es/getMinLogLevelFromEnv.mjs +init_modules_watch_stub(); +init_performance2(); +var _a2; +var _b; +var data = typeof process === "undefined" ? [] : (_b = (_a2 = process.env.LOGGING) === null || _a2 === void 0 ? void 0 : _a2.split(";").map(function(part) { + var _a4 = part.split("=", 2), namespace = _a4[0], strLevel = _a4[1]; + if (strLevel) { + return [namespace === "default" ? void 0 : namespace.split(":"), resolveLogLevel(strLevel)]; + } + return null; +}).filter(function(v) { + return !!v; +}).sort(function(_a4, _b3) { + var _c2, _d; + var a = _a4[0]; + var b = _b3[0]; + return ((_c2 = b === null || b === void 0 ? void 0 : b.length) !== null && _c2 !== void 0 ? _c2 : 0) - ((_d = a === null || a === void 0 ? void 0 : a.length) !== null && _d !== void 0 ? _d : 0); +})) !== null && _b !== void 0 ? _b : []; +var defaultIndex = data.findIndex(function(_a4) { + var nsParts = _a4[0]; + return !nsParts; +}); +var defaultLevel = void 0; +if (defaultIndex !== -1) { + defaultLevel = data[defaultIndex][1]; + data.splice(defaultIndex); +} +function isPrefix(value, prefix) { + return prefix.length <= value.length && prefix.every(function(item, i) { + return item === value[i]; + }); +} +__name(isPrefix, "isPrefix"); +function getMinLogLevelFromEnv(name) { + var nameSplit = name.split(":"); + for (var _i = 0, data_1 = data; _i < data_1.length; _i++) { + var _a4 = data_1[_i], nsParts = _a4[0], level = _a4[1]; + if (isPrefix(nameSplit, nsParts)) { + return level; + } + } + return defaultLevel; +} +__name(getMinLogLevelFromEnv, "getMinLogLevelFromEnv"); + +// node_modules/.pnpm/@d-fischer+logger@4.2.4/node_modules/@d-fischer/logger/es/BaseLogger.mjs +var BaseLogger = ( + /** @class */ + (function() { + function BaseLogger2(_a4) { + var name = _a4.name, minLevel = _a4.minLevel, _b3 = _a4.emoji, emoji = _b3 === void 0 ? false : _b3, colors2 = _a4.colors, _c2 = _a4.timestamps, timestamps = _c2 === void 0 ? import_detect_node2.isNode : _c2; + var _d, _e; + this._name = name; + this._minLevel = (_e = (_d = mapOptional(minLevel, function(lv) { + return resolveLogLevel(lv); + })) !== null && _d !== void 0 ? _d : getMinLogLevelFromEnv(name)) !== null && _e !== void 0 ? _e : LogLevel.WARNING; + this._emoji = emoji; + this._colors = colors2; + this._timestamps = timestamps; + } + __name(BaseLogger2, "BaseLogger"); + BaseLogger2.prototype.crit = function(message) { + this.log(LogLevel.CRITICAL, message); + }; + BaseLogger2.prototype.error = function(message) { + this.log(LogLevel.ERROR, message); + }; + BaseLogger2.prototype.warn = function(message) { + this.log(LogLevel.WARNING, message); + }; + BaseLogger2.prototype.info = function(message) { + this.log(LogLevel.INFO, message); + }; + BaseLogger2.prototype.debug = function(message) { + this.log(LogLevel.DEBUG, message); + }; + BaseLogger2.prototype.trace = function(message) { + this.log(LogLevel.TRACE, message); + }; + return BaseLogger2; + })() +); + +// node_modules/.pnpm/@d-fischer+logger@4.2.4/node_modules/@d-fischer/logger/es/BrowserLogger.mjs +var BrowserLogger = ( + /** @class */ + (function(_super) { + __extends(BrowserLogger2, _super); + function BrowserLogger2() { + return _super !== null && _super.apply(this, arguments) || this; + } + __name(BrowserLogger2, "BrowserLogger"); + BrowserLogger2.prototype.log = function(level, message) { + if (level > this._minLevel) { + return; + } + var logFn = LogLevelToConsoleFunction[level]; + var formattedMessage = "[".concat(this._name, "] ").concat(message); + if (this._timestamps) { + formattedMessage = "[".concat((/* @__PURE__ */ new Date()).toISOString(), "] ").concat(message); + } + logFn(formattedMessage); + }; + return BrowserLogger2; + })(BaseLogger) +); + +// node_modules/.pnpm/@d-fischer+logger@4.2.4/node_modules/@d-fischer/logger/es/CustomLoggerWrapper.mjs +init_modules_watch_stub(); +init_performance2(); +var CustomLoggerWrapper = ( + /** @class */ + (function() { + function CustomLoggerWrapper2(_a4) { + var name = _a4.name, minLevel = _a4.minLevel, custom = _a4.custom; + var _b3; + this._minLevel = (_b3 = mapOptional(minLevel, function(lv) { + return resolveLogLevel(lv); + })) !== null && _b3 !== void 0 ? _b3 : getMinLogLevelFromEnv(name); + this._override = typeof custom === "function" ? { log: custom } : custom; + } + __name(CustomLoggerWrapper2, "CustomLoggerWrapper"); + CustomLoggerWrapper2.prototype.log = function(level, message) { + if (this._shouldLog(level)) { + this._override.log(level, message); + } + }; + CustomLoggerWrapper2.prototype.crit = function(message) { + if (!this._override.crit) { + this.log(LogLevel.CRITICAL, message); + } else if (this._shouldLog(LogLevel.CRITICAL)) { + this._override.crit(message); + } + }; + CustomLoggerWrapper2.prototype.error = function(message) { + if (!this._override.error) { + this.log(LogLevel.ERROR, message); + } else if (this._shouldLog(LogLevel.ERROR)) { + this._override.error(message); + } + }; + CustomLoggerWrapper2.prototype.warn = function(message) { + if (!this._override.warn) { + this.log(LogLevel.WARNING, message); + } else if (this._shouldLog(LogLevel.WARNING)) { + this._override.warn(message); + } + }; + CustomLoggerWrapper2.prototype.info = function(message) { + if (!this._override.info) { + this.log(LogLevel.INFO, message); + } else if (this._shouldLog(LogLevel.INFO)) { + this._override.info(message); + } + }; + CustomLoggerWrapper2.prototype.debug = function(message) { + if (!this._override.debug) { + this.log(LogLevel.DEBUG, message); + } else if (this._shouldLog(LogLevel.DEBUG)) { + this._override.debug(message); + } + }; + CustomLoggerWrapper2.prototype.trace = function(message) { + if (!this._override.trace) { + this.log(LogLevel.TRACE, message); + } else if (this._shouldLog(LogLevel.TRACE)) { + this._override.trace(message); + } + }; + CustomLoggerWrapper2.prototype._shouldLog = function(level) { + return this._minLevel === void 0 || this._minLevel >= level; + }; + return CustomLoggerWrapper2; + })() +); + +// node_modules/.pnpm/@d-fischer+logger@4.2.4/node_modules/@d-fischer/logger/es/NodeLogger.mjs +init_modules_watch_stub(); +init_performance2(); +var _a3; +var _b2; +var _c; +var LogLevelToEmoji = (_a3 = {}, _a3[LogLevel.CRITICAL] = "\u{1F6D1}", _a3[LogLevel.ERROR] = "\u274C", // these following two need extra spaces at the end because somehow they consume less space in a terminal than they should... +_a3[LogLevel.WARNING] = "\u26A0\uFE0F ", _a3[LogLevel.INFO] = "\u2139\uFE0F ", _a3[LogLevel.DEBUG] = "\u{1F41E}", _a3[LogLevel.TRACE] = "\u{1F43E}", _a3); +var colors = { + black: 30, + red: 31, + green: 32, + yellow: 33, + blue: 34, + magenta: 35, + cyan: 36, + white: 37, + blackBright: 90, + redBright: 91, + greenBright: 92, + yellowBright: 93, + blueBright: 94, + magentaBright: 95, + cyanBright: 96, + whiteBright: 97 +}; +var bgColors = { + bgBlack: 40, + bgRed: 41, + bgGreen: 42, + bgYellow: 43, + bgBlue: 44, + bgMagenta: 45, + bgCyan: 46, + bgWhite: 47, + bgBlackBright: 100, + bgRedBright: 101, + bgGreenBright: 102, + bgYellowBright: 103, + bgBlueBright: 104, + bgMagentaBright: 105, + bgCyanBright: 106, + bgWhiteBright: 107 +}; +function createGenericWrapper(color, ending, inner) { + return function(str2) { + return "\x1B[".concat(color, "m").concat(inner ? inner(str2) : str2, "\x1B[").concat(ending, "m"); + }; +} +__name(createGenericWrapper, "createGenericWrapper"); +function createColorWrapper(color) { + return createGenericWrapper(colors[color], 39); +} +__name(createColorWrapper, "createColorWrapper"); +function createBgWrapper(color, fgWrapper) { + return createGenericWrapper(bgColors[color], 49, fgWrapper); +} +__name(createBgWrapper, "createBgWrapper"); +var LogLevelToColor = (_b2 = {}, _b2[LogLevel.CRITICAL] = createColorWrapper("red"), _b2[LogLevel.ERROR] = createColorWrapper("redBright"), _b2[LogLevel.WARNING] = createColorWrapper("yellow"), _b2[LogLevel.INFO] = createColorWrapper("blue"), _b2[LogLevel.DEBUG] = createColorWrapper("magenta"), _b2[LogLevel.TRACE] = createGenericWrapper(0, 0), _b2); +var LogLevelToBackgroundColor = (_c = {}, _c[LogLevel.CRITICAL] = createBgWrapper("bgRed", createColorWrapper("white")), _c[LogLevel.ERROR] = createBgWrapper("bgRedBright", createColorWrapper("white")), _c[LogLevel.WARNING] = createBgWrapper("bgYellow", createColorWrapper("black")), _c[LogLevel.INFO] = createBgWrapper("bgBlue", createColorWrapper("white")), _c[LogLevel.DEBUG] = createBgWrapper("bgMagenta", createColorWrapper("black")), _c[LogLevel.TRACE] = createGenericWrapper(7, 27), _c); +var NodeLogger = ( + /** @class */ + (function(_super) { + __extends(NodeLogger2, _super); + function NodeLogger2() { + return _super !== null && _super.apply(this, arguments) || this; + } + __name(NodeLogger2, "NodeLogger"); + NodeLogger2.prototype.log = function(level, message) { + var _a4, _b3, _c2; + if (level > this._minLevel) { + return; + } + var logFn = LogLevelToConsoleFunction[level]; + var builtMessage = ""; + if (this._timestamps) { + builtMessage += "[".concat((/* @__PURE__ */ new Date()).toISOString(), "] "); + } + if (this._emoji) { + var emoji = LogLevelToEmoji[level]; + builtMessage += "".concat(emoji, " "); + } + var useColors = (_c2 = (_a4 = this._colors) !== null && _a4 !== void 0 ? _a4 : (_b3 = process.stdout) === null || _b3 === void 0 ? void 0 : _b3.isTTY) !== null && _c2 !== void 0 ? _c2 : true; + if (useColors) { + builtMessage += "".concat(LogLevelToBackgroundColor[level](this._name), " ").concat(LogLevelToBackgroundColor[level](LogLevel[level]), " ").concat(LogLevelToColor[level](message)); + } else { + builtMessage += "[".concat(this._name, ":").concat(LogLevel[level].toLowerCase(), "] ").concat(message); + } + logFn(builtMessage); + }; + return NodeLogger2; + })(BaseLogger) +); + +// node_modules/.pnpm/@d-fischer+logger@4.2.4/node_modules/@d-fischer/logger/es/createLogger.mjs +function createLogger(options) { + if (options.custom) { + return new CustomLoggerWrapper(options); + } + if (import_detect_node3.isNode) { + return new NodeLogger(options); + } + return new BrowserLogger(options); +} +__name(createLogger, "createLogger"); + +// node_modules/.pnpm/@d-fischer+rate-limiter@1.1.0/node_modules/@d-fischer/rate-limiter/es/index.mjs +init_modules_watch_stub(); +init_performance2(); + +// node_modules/.pnpm/@d-fischer+rate-limiter@1.1.0/node_modules/@d-fischer/rate-limiter/es/errors/RateLimiterDestroyedError.mjs +init_modules_watch_stub(); +init_performance2(); + +// node_modules/.pnpm/@d-fischer+rate-limiter@1.1.0/node_modules/@d-fischer/rate-limiter/es/errors/CustomError.mjs +init_modules_watch_stub(); +init_performance2(); +var CustomError = class extends Error { + static { + __name(this, "CustomError"); + } + constructor(...params) { + var _a4; + super(...params); + Object.setPrototypeOf(this, new.target.prototype); + (_a4 = Error.captureStackTrace) === null || _a4 === void 0 ? void 0 : _a4.call(Error, this, new.target.constructor); + } + get name() { + return this.constructor.name; + } +}; + +// node_modules/.pnpm/@d-fischer+rate-limiter@1.1.0/node_modules/@d-fischer/rate-limiter/es/errors/RateLimiterDestroyedError.mjs +var RateLimiterDestroyedError = class extends CustomError { + static { + __name(this, "RateLimiterDestroyedError"); + } +}; + +// node_modules/.pnpm/@d-fischer+rate-limiter@1.1.0/node_modules/@d-fischer/rate-limiter/es/errors/RateLimitReachedError.mjs +init_modules_watch_stub(); +init_performance2(); +var RateLimitReachedError = class extends CustomError { + static { + __name(this, "RateLimitReachedError"); + } +}; + +// node_modules/.pnpm/@d-fischer+rate-limiter@1.1.0/node_modules/@d-fischer/rate-limiter/es/errors/RetryAfterError.mjs +init_modules_watch_stub(); +init_performance2(); +var RetryAfterError = class extends CustomError { + static { + __name(this, "RetryAfterError"); + } + constructor(after) { + super(`Need to retry after ${after} ms`); + this._retryAt = Date.now() + after; + } + get retryAt() { + return this._retryAt; + } +}; + +// node_modules/.pnpm/@d-fischer+rate-limiter@1.1.0/node_modules/@d-fischer/rate-limiter/es/limiters/PartitionedRateLimiter.mjs +init_modules_watch_stub(); +init_performance2(); + +// node_modules/.pnpm/@d-fischer+rate-limiter@1.1.0/node_modules/@d-fischer/rate-limiter/es/limiters/ResponseBasedRateLimiter.mjs +init_modules_watch_stub(); +init_performance2(); +var ResponseBasedRateLimiter = class { + static { + __name(this, "ResponseBasedRateLimiter"); + } + constructor({ logger }) { + this._queue = []; + this._batchRunning = false; + this._paused = false; + this._logger = createLogger({ name: "rate-limiter", emoji: true, ...logger }); + } + async request(req, options) { + this._logger.trace("request start"); + return await new Promise((resolve, reject) => { + var _a4; + const reqSpec = { + req, + resolve, + reject, + limitReachedBehavior: (_a4 = options === null || options === void 0 ? void 0 : options.limitReachedBehavior) !== null && _a4 !== void 0 ? _a4 : "enqueue" + }; + if (this._batchRunning || !!this._nextBatchTimer || this._paused) { + this._logger.trace(`request queued batchRunning:${this._batchRunning.toString()} hasNextBatchTimer:${(!!this._nextBatchTimer).toString()} paused:${this._paused.toString()}`); + this._queue.push(reqSpec); + } else { + void this._runRequestBatch([reqSpec]); + } + }); + } + clear() { + this._queue = []; + } + pause() { + this._paused = true; + } + resume() { + this._paused = false; + this._runNextBatch(); + } + get stats() { + var _a4, _b3, _c2, _d, _e; + return { + lastKnownLimit: (_b3 = (_a4 = this._parameters) === null || _a4 === void 0 ? void 0 : _a4.limit) !== null && _b3 !== void 0 ? _b3 : null, + lastKnownRemainingRequests: (_d = (_c2 = this._parameters) === null || _c2 === void 0 ? void 0 : _c2.remaining) !== null && _d !== void 0 ? _d : null, + lastKnownResetDate: mapNullable((_e = this._parameters) === null || _e === void 0 ? void 0 : _e.resetsAt, (v) => new Date(v)) + }; + } + async _runRequestBatch(reqSpecs) { + this._logger.trace(`runRequestBatch start specs:${reqSpecs.length}`); + this._batchRunning = true; + if (this._parameters) { + this._logger.debug(`Remaining requests: ${this._parameters.remaining}`); + } + this._logger.debug(`Doing ${reqSpecs.length} requests, new queue length is ${this._queue.length}`); + const promises = reqSpecs.map(async (reqSpec) => { + const { req, resolve, reject } = reqSpec; + try { + const result = await this.doRequest(req); + const retry2 = this.needsToRetryAfter(result); + if (retry2 !== null) { + this._queue.unshift(reqSpec); + this._logger.info(`Retrying after ${retry2} ms`); + throw new RetryAfterError(retry2); + } + const params = this.getParametersFromResponse(result); + resolve(result); + return params; + } catch (e) { + if (e instanceof RetryAfterError) { + throw e; + } + reject(e); + return void 0; + } + }); + const settledPromises = await Promise.allSettled(promises); + const rejectedPromises = settledPromises.filter((p) => p.status === "rejected"); + const now = Date.now(); + if (rejectedPromises.length) { + this._logger.trace("runRequestBatch some rejected"); + const retryAt = Math.max(now, ...rejectedPromises.map((p) => p.reason.retryAt)); + const retryAfter = retryAt - now; + this._logger.warn(`Waiting for ${retryAfter} ms because the rate limit was exceeded`); + this._nextBatchTimer = setTimeout(() => { + this._parameters = void 0; + this._runNextBatch(); + }, retryAfter); + } else { + this._logger.trace("runRequestBatch none rejected"); + const params = settledPromises.filter((p) => p.status === "fulfilled" && p.value !== void 0).map((p) => p.value).reduce((carry, v) => { + if (!carry) { + return v; + } + return v.remaining < carry.remaining ? v : carry; + }, void 0); + this._batchRunning = false; + if (params) { + this._parameters = params; + if (params.resetsAt < now || params.remaining > 0) { + this._logger.trace("runRequestBatch canRunMore"); + this._runNextBatch(); + } else { + const delay = params.resetsAt - now; + this._logger.trace(`runRequestBatch delay:${delay}`); + this._logger.warn(`Waiting for ${delay} ms because the rate limit was reached`); + this._queue = this._queue.filter((entry) => { + switch (entry.limitReachedBehavior) { + case "enqueue": { + return true; + } + case "null": { + entry.resolve(null); + return false; + } + case "throw": { + entry.reject(new RateLimitReachedError("Request removed from queue because the rate limit was reached")); + return false; + } + default: { + throw new Error("this should never happen"); + } + } + }); + this._nextBatchTimer = setTimeout(() => { + this._parameters = void 0; + this._runNextBatch(); + }, delay); + } + } + } + this._logger.trace("runRequestBatch end"); + } + _runNextBatch() { + if (this._paused) { + return; + } + this._logger.trace("runNextBatch start"); + if (this._nextBatchTimer) { + clearTimeout(this._nextBatchTimer); + this._nextBatchTimer = void 0; + } + const amount = this._parameters ? Math.min(this._parameters.remaining, this._parameters.limit / 10) : 1; + const reqSpecs = this._queue.splice(0, amount); + if (reqSpecs.length) { + void this._runRequestBatch(reqSpecs); + } + this._logger.trace("runNextBatch end"); + } +}; + +// node_modules/.pnpm/@d-fischer+rate-limiter@1.1.0/node_modules/@d-fischer/rate-limiter/es/limiters/PartitionedRateLimiter.mjs +var PartitionedRateLimiter = class { + static { + __name(this, "PartitionedRateLimiter"); + } + constructor(options) { + this._children = /* @__PURE__ */ new Map(); + this._paused = false; + this._partitionKeyCallback = options.getPartitionKey; + this._createChildCallback = options.createChild; + } + async request(req, options) { + const partitionKey = this._partitionKeyCallback(req); + const partitionChild = this._getChild(partitionKey); + return await partitionChild.request(req, options); + } + clear() { + for (const child of this._children.values()) { + child.clear(); + } + } + pause() { + this._paused = true; + for (const child of this._children.values()) { + child.pause(); + } + } + resume() { + this._paused = false; + for (const child of this._children.values()) { + child.resume(); + } + } + getChildStats(partitionKey) { + if (!this._children.has(partitionKey)) { + return null; + } + const child = this._children.get(partitionKey); + if (!(child instanceof ResponseBasedRateLimiter)) { + return null; + } + return child.stats; + } + _getChild(partitionKey) { + if (this._children.has(partitionKey)) { + return this._children.get(partitionKey); + } + const result = this._createChildCallback(partitionKey); + if (this._paused) { + result.pause(); + } + this._children.set(partitionKey, result); + return result; + } +}; + +// node_modules/.pnpm/@d-fischer+rate-limiter@1.1.0/node_modules/@d-fischer/rate-limiter/es/limiters/PartitionedTimeBasedRateLimiter.mjs +init_modules_watch_stub(); +init_performance2(); +var PartitionedTimeBasedRateLimiter = class { + static { + __name(this, "PartitionedTimeBasedRateLimiter"); + } + constructor({ logger, bucketSize, timeFrame, doRequest, getPartitionKey }) { + this._partitionedQueue = /* @__PURE__ */ new Map(); + this._usedFromBucket = /* @__PURE__ */ new Map(); + this._counterTimers = /* @__PURE__ */ new Set(); + this._paused = false; + this._destroyed = false; + this._logger = createLogger({ name: "rate-limiter", emoji: true, ...logger }); + this._bucketSize = bucketSize; + this._timeFrame = timeFrame; + this._callback = doRequest; + this._partitionKeyCallback = getPartitionKey; + } + async request(req, options) { + return await new Promise((resolve, reject) => { + var _a4, _b3; + if (this._destroyed) { + reject(new RateLimiterDestroyedError("Rate limiter was destroyed")); + return; + } + const reqSpec = { + req, + resolve, + reject, + limitReachedBehavior: (_a4 = options === null || options === void 0 ? void 0 : options.limitReachedBehavior) !== null && _a4 !== void 0 ? _a4 : "enqueue" + }; + const partitionKey = this._partitionKeyCallback(req); + const usedFromBucket = (_b3 = this._usedFromBucket.get(partitionKey)) !== null && _b3 !== void 0 ? _b3 : 0; + if (usedFromBucket >= this._bucketSize || this._paused) { + switch (reqSpec.limitReachedBehavior) { + case "enqueue": { + const queue2 = this._getPartitionedQueue(partitionKey); + queue2.push(reqSpec); + if (usedFromBucket + queue2.length >= this._bucketSize) { + this._logger.warn(`Rate limit of ${this._bucketSize} for ${partitionKey ? `partition ${partitionKey}` : "default partition"} was reached, waiting for ${this._paused ? "the limiter to be unpaused" : "a free bucket entry"}; queue size is ${queue2.length}`); + } else { + this._logger.info(`Enqueueing request for ${partitionKey ? `partition ${partitionKey}` : "default partition"} because the rate limiter is paused; queue size is ${queue2.length}`); + } + break; + } + case "null": { + reqSpec.resolve(null); + if (this._paused) { + this._logger.info(`Returning null for request for ${partitionKey ? `partition ${partitionKey}` : "default partition"} because the rate limiter is paused`); + } else { + this._logger.warn(`Rate limit of ${this._bucketSize} for ${partitionKey ? `partition ${partitionKey}` : "default partition"} was reached, dropping request and returning null`); + } + break; + } + case "throw": { + reqSpec.reject(new RateLimitReachedError(`Request dropped because ${this._paused ? "the rate limiter is paused" : `the rate limit for ${partitionKey ? `partition ${partitionKey}` : "default partition"} was reached`}`)); + break; + } + default: { + throw new Error("this should never happen"); + } + } + } else { + void this._runRequest(reqSpec, partitionKey); + } + }); + } + clear() { + this._partitionedQueue.clear(); + } + pause() { + this._paused = true; + } + resume() { + this._paused = false; + for (const partitionKey of this._partitionedQueue.keys()) { + this._runNextRequest(partitionKey); + } + } + destroy() { + this._paused = false; + this._destroyed = true; + this._counterTimers.forEach((timer) => { + clearTimeout(timer); + }); + for (const queue2 of this._partitionedQueue.values()) { + for (const req of queue2) { + req.reject(new RateLimiterDestroyedError("Rate limiter was destroyed")); + } + } + this._partitionedQueue.clear(); + } + _getPartitionedQueue(partitionKey) { + if (this._partitionedQueue.has(partitionKey)) { + return this._partitionedQueue.get(partitionKey); + } + const newQueue = []; + this._partitionedQueue.set(partitionKey, newQueue); + return newQueue; + } + async _runRequest(reqSpec, partitionKey) { + var _a4; + const queue2 = this._getPartitionedQueue(partitionKey); + this._logger.debug(`doing a request for ${partitionKey ? `partition ${partitionKey}` : "default partition"}, new queue length is ${queue2.length}`); + this._usedFromBucket.set(partitionKey, ((_a4 = this._usedFromBucket.get(partitionKey)) !== null && _a4 !== void 0 ? _a4 : 0) + 1); + const { req, resolve, reject } = reqSpec; + try { + resolve(await this._callback(req)); + } catch (e) { + reject(e); + } finally { + const counterTimer = setTimeout(() => { + this._counterTimers.delete(counterTimer); + const newUsed = this._usedFromBucket.get(partitionKey) - 1; + this._usedFromBucket.set(partitionKey, newUsed); + if (queue2.length && newUsed < this._bucketSize) { + this._runNextRequest(partitionKey); + } + }, this._timeFrame); + this._counterTimers.add(counterTimer); + } + } + _runNextRequest(partitionKey) { + if (this._paused) { + return; + } + const queue2 = this._getPartitionedQueue(partitionKey); + const reqSpec = queue2.shift(); + if (reqSpec) { + void this._runRequest(reqSpec, partitionKey); + } + } +}; + +// node_modules/.pnpm/@twurple+api-call@8.0.3/node_modules/@twurple/api-call/lib/index.js +init_modules_watch_stub(); +init_performance2(); + +// node_modules/.pnpm/@twurple+api-call@8.0.3/node_modules/@twurple/api-call/lib/apiCall.js +init_modules_watch_stub(); +init_performance2(); + +// node_modules/.pnpm/@twurple+common@8.0.3/node_modules/@twurple/common/lib/index.js +init_modules_watch_stub(); +init_performance2(); + +// node_modules/.pnpm/@twurple+common@8.0.3/node_modules/@twurple/common/lib/DataObject.js +init_modules_watch_stub(); +init_performance2(); + +// node_modules/.pnpm/klona@2.0.6/node_modules/klona/dist/index.mjs +init_modules_watch_stub(); +init_performance2(); + +// node_modules/.pnpm/@twurple+common@8.0.3/node_modules/@twurple/common/lib/DataObject.js +var rawDataSymbol = /* @__PURE__ */ Symbol("twurpleRawData"); +var DataObject = class { + static { + __name(this, "DataObject"); + } + /** @private */ + [rawDataSymbol]; + /** @private */ + constructor(data2) { + this[rawDataSymbol] = data2; + } +}; + +// node_modules/.pnpm/@twurple+common@8.0.3/node_modules/@twurple/common/lib/mockApiPort.js +init_modules_watch_stub(); +init_performance2(); +function getMockApiPort() { + try { + return process.env.TWURPLE_MOCK_API_PORT ?? null; + } catch { + try { + return import.meta.env.TWURPLE_MOCK_API_PORT ?? null; + } catch { + return null; + } + } +} +__name(getMockApiPort, "getMockApiPort"); + +// node_modules/.pnpm/@twurple+common@8.0.3/node_modules/@twurple/common/lib/qs.js +init_modules_watch_stub(); +init_performance2(); +function qsStringify(obj) { + if (!obj) { + return ""; + } + const params = new URLSearchParams(); + for (const [key, value] of Object.entries(obj)) { + if (value === null) { + params.append(key, ""); + } else if (Array.isArray(value)) { + for (const v of value) { + params.append(key, v.toString()); + } + } else if (value !== void 0) { + params.append(key, value.toString()); + } + } + const result = params.toString(); + return result ? `?${result}` : ""; +} +__name(qsStringify, "qsStringify"); + +// node_modules/.pnpm/@twurple+common@8.0.3/node_modules/@twurple/common/lib/relations.js +init_modules_watch_stub(); +init_performance2(); + +// node_modules/.pnpm/@twurple+common@8.0.3/node_modules/@twurple/common/lib/errors/RelationAssertionError.js +init_modules_watch_stub(); +init_performance2(); + +// node_modules/.pnpm/@twurple+common@8.0.3/node_modules/@twurple/common/lib/errors/CustomError.js +init_modules_watch_stub(); +init_performance2(); +var CustomError2 = class extends Error { + static { + __name(this, "CustomError"); + } + constructor(message, options) { + super(message, options); + Object.setPrototypeOf(this, new.target.prototype); + Error.captureStackTrace?.(this, new.target.constructor); + } + get name() { + return this.constructor.name; + } +}; + +// node_modules/.pnpm/@twurple+common@8.0.3/node_modules/@twurple/common/lib/errors/RelationAssertionError.js +var RelationAssertionError = class extends CustomError2 { + static { + __name(this, "RelationAssertionError"); + } + constructor() { + super("Relation returned null - this may be a library bug or a race condition in your own code"); + } +}; + +// node_modules/.pnpm/@twurple+common@8.0.3/node_modules/@twurple/common/lib/relations.js +function checkRelationAssertion(value) { + if (value == null) { + throw new RelationAssertionError(); + } + return value; +} +__name(checkRelationAssertion, "checkRelationAssertion"); + +// node_modules/.pnpm/@twurple+common@8.0.3/node_modules/@twurple/common/lib/rtfm.js +init_modules_watch_stub(); +init_performance2(); +function rtfm(pkg, name, idKey) { + return (clazz) => { + const fn = idKey ? function() { + return `[${name}#${this[idKey]} - please check https://twurple.js.org/reference/${pkg}/classes/${name}.html for available properties]`; + } : function() { + return `[${name} - please check https://twurple.js.org/reference/${pkg}/classes/${name}.html for available properties]`; + }; + Object.defineProperty(clazz.prototype, /* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom"), { + value: fn, + enumerable: false + }); + }; +} +__name(rtfm, "rtfm"); + +// node_modules/.pnpm/@twurple+common@8.0.3/node_modules/@twurple/common/lib/extensions/HelixExtension.js +init_modules_watch_stub(); +init_performance2(); +var HelixExtension = class HelixExtension2 extends DataObject { + static { + __name(this, "HelixExtension"); + } + /** + * The name of the extension's author. + */ + get authorName() { + return this[rawDataSymbol].author_name; + } + /** + * Whether bits are enabled for the extension. + */ + get bitsEnabled() { + return this[rawDataSymbol].bits_enabled; + } + /** + * Whether the extension can be installed. + */ + get installable() { + return this[rawDataSymbol].can_install; + } + /** + * The location of the extension's configuration. + */ + get configurationLocation() { + return this[rawDataSymbol].configuration_location; + } + /** + * The extension's description. + */ + get description() { + return this[rawDataSymbol].description; + } + /** + * The URL of the extension's terms of service. + */ + get tosUrl() { + return this[rawDataSymbol].eula_tos_url; + } + /** + * Whether the extension has support for sending chat messages. + */ + get hasChatSupport() { + return this[rawDataSymbol].has_chat_support; + } + /** + * The URL of the extension's default sized icon. + */ + get iconUrl() { + return this[rawDataSymbol].icon_url; + } + /** + * Gets the URL of the extension's icon in the given size. + * + * @param size The size of the icon. + */ + getIconUrl(size) { + return this[rawDataSymbol].icon_urls[size]; + } + /** + * The extension's ID. + */ + get id() { + return this[rawDataSymbol].id; + } + /** + * The extension's name. + */ + get name() { + return this[rawDataSymbol].name; + } + /** + * The URL of the extension's privacy policy. + */ + get privacyPolicyUrl() { + return this[rawDataSymbol].privacy_policy_url; + } + /** + * Whether the extension requests its users to share their identity with it. + */ + get requestsIdentityLink() { + return this[rawDataSymbol].request_identity_link; + } + /** + * The URLs of the extension's screenshots. + */ + get screenshotUrls() { + return this[rawDataSymbol].screenshot_urls; + } + /** + * The extension's activity state. + */ + get state() { + return this[rawDataSymbol].state; + } + /** + * The extension's level of support for subscriptions. + */ + get subscriptionsSupportLevel() { + return this[rawDataSymbol].subscriptions_support_level; + } + /** + * The extension's feature summary. + */ + get summary() { + return this[rawDataSymbol].summary; + } + /** + * The extension's support email address. + */ + get supportEmail() { + return this[rawDataSymbol].support_email; + } + /** + * The extension's version. + */ + get version() { + return this[rawDataSymbol].version; + } + /** + * The extension's feature summary for viewers. + */ + get viewerSummary() { + return this[rawDataSymbol].viewer_summary; + } + /** + * The extension's feature summary for viewers. + * + * @deprecated Use `viewerSummary` instead. + */ + get viewerSummery() { + return this[rawDataSymbol].viewer_summary; + } + /** + * The extension's allowed configuration URLs. + */ + get allowedConfigUrls() { + return this[rawDataSymbol].allowlisted_config_urls; + } + /** + * The extension's allowed panel URLs. + */ + get allowedPanelUrls() { + return this[rawDataSymbol].allowlisted_panel_urls; + } + /** + * The URL shown when a viewer opens the extension on a mobile device. + * + * If the extension does not have a mobile view, this is null. + */ + get mobileViewerUrl() { + return this[rawDataSymbol].views.mobile?.viewer_url ?? null; + } + /** + * The URL shown to the viewer when the extension is shown as a panel. + * + * If the extension does not have a panel view, this is null. + */ + get panelViewerUrl() { + return this[rawDataSymbol].views.panel?.viewer_url ?? null; + } + /** + * The height of the extension panel. + * + * If the extension does not have a panel view, this is null. + */ + get panelHeight() { + return this[rawDataSymbol].views.panel?.height ?? null; + } + /** + * Whether the extension can link to external content from its panel view. + * + * If the extension does not have a panel view, this is null. + */ + get panelCanLinkExternalContent() { + return this[rawDataSymbol].views.panel?.can_link_external_content ?? null; + } + /** + * The URL shown to the viewer when the extension is shown as a video overlay. + * + * If the extension does not have a overlay view, this is null. + */ + get overlayViewerUrl() { + return this[rawDataSymbol].views.video_overlay?.viewer_url ?? null; + } + /** + * Whether the extension can link to external content from its overlay view. + * + * If the extension does not have a overlay view, this is null. + */ + get overlayCanLinkExternalContent() { + return this[rawDataSymbol].views.video_overlay?.can_link_external_content ?? null; + } + /** + * The URL shown to the viewer when the extension is shown as a video component. + * + * If the extension does not have a component view, this is null. + */ + get componentViewerUrl() { + return this[rawDataSymbol].views.component?.viewer_url ?? null; + } + /** + * The aspect width of the extension's component view. + * + * If the extension does not have a component view, this is null. + */ + get componentAspectWidth() { + return this[rawDataSymbol].views.component?.aspect_width ?? null; + } + /** + * The aspect height of the extension's component view. + * + * If the extension does not have a component view, this is null. + */ + get componentAspectHeight() { + return this[rawDataSymbol].views.component?.aspect_height ?? null; + } + /** + * The horizontal aspect ratio of the extension's component view. + * + * If the extension does not have a component view, this is null. + */ + get componentAspectRatioX() { + return this[rawDataSymbol].views.component?.aspect_ratio_x ?? null; + } + /** + * The vertical aspect ratio of the extension's component view. + * + * If the extension does not have a component view, this is null. + */ + get componentAspectRatioY() { + return this[rawDataSymbol].views.component?.aspect_ratio_y ?? null; + } + /** + * Whether the extension's component view should automatically scale. + * + * If the extension does not have a component view, this is null. + */ + get componentAutoScales() { + return this[rawDataSymbol].views.component?.autoscale ?? null; + } + /** + * The base width of the extension's component view to use for scaling. + * + * If the extension does not have a component view, this is null. + */ + get componentScalePixels() { + return this[rawDataSymbol].views.component?.scale_pixels ?? null; + } + /** + * The target height of the extension's component view. + * + * If the extension does not have a component view, this is null. + */ + get componentTargetHeight() { + return this[rawDataSymbol].views.component?.target_height ?? null; + } + /** + * The size of the extension's component view. + * + * If the extension does not have a component view, this is null. + */ + get componentSize() { + return this[rawDataSymbol].views.component?.size ?? null; + } + /** + * Whether zooming is enabled for the extension's component view. + * + * If the extension does not have a component view, this is null. + */ + get componentZoom() { + return this[rawDataSymbol].views.component?.zoom ?? null; + } + /** + * The zoom pixels of the extension's component view. + * + * If the extension does not have a component view, this is null. + */ + get componentZoomPixels() { + return this[rawDataSymbol].views.component?.zoom_pixels ?? null; + } + /** + * Whether the extension can link to external content from its component view. + * + * If the extension does not have a component view, this is null. + */ + get componentCanLinkExternalContent() { + return this[rawDataSymbol].views.component?.can_link_external_content ?? null; + } + /** + * The URL shown to the viewer when the extension's configuration page is shown. + * + * If the extension does not have a config view, this is null. + */ + get configViewerUrl() { + return this[rawDataSymbol].views.config?.viewer_url ?? null; + } + /** + * Whether the extension can link to external content from its config view. + * + * If the extension does not have a config view, this is null. + */ + get configCanLinkExternalContent() { + return this[rawDataSymbol].views.config?.can_link_external_content ?? null; + } +}; +HelixExtension = __decorate([ + rtfm("api", "HelixExtension", "id") +], HelixExtension); + +// node_modules/.pnpm/@twurple+common@8.0.3/node_modules/@twurple/common/lib/errors/HellFreezesOverError.js +init_modules_watch_stub(); +init_performance2(); +var HellFreezesOverError = class extends CustomError2 { + static { + __name(this, "HellFreezesOverError"); + } + constructor(message) { + super(`${message} - this should never happen, please file a bug in the GitHub issue tracker`); + } +}; + +// node_modules/.pnpm/@twurple+common@8.0.3/node_modules/@twurple/common/lib/userResolvers.js +init_modules_watch_stub(); +init_performance2(); +function extractUserId(user) { + if (typeof user === "string") { + return user; + } + if (typeof user === "number") { + return user.toString(10); + } + return user.id; +} +__name(extractUserId, "extractUserId"); +function extractUserName(user) { + return typeof user === "string" ? user : user.name; +} +__name(extractUserName, "extractUserName"); + +// node_modules/.pnpm/@twurple+api-call@8.0.3/node_modules/@twurple/api-call/lib/helpers/transform.js +init_modules_watch_stub(); +init_performance2(); + +// node_modules/.pnpm/@twurple+api-call@8.0.3/node_modules/@twurple/api-call/lib/errors/HttpStatusCodeError.js +init_modules_watch_stub(); +init_performance2(); +var HttpStatusCodeError = class extends CustomError2 { + static { + __name(this, "HttpStatusCodeError"); + } + _statusCode; + _url; + _method; + _body; + /** @private */ + constructor(_statusCode, statusText, _url, _method, _body, isJson) { + super(`Encountered HTTP status code ${_statusCode}: ${statusText} + +URL: ${_url} +Method: ${_method} +Body: +${!isJson && _body.length > 150 ? `${_body.slice(0, 147)}...` : _body}`); + this._statusCode = _statusCode; + this._url = _url; + this._method = _method; + this._body = _body; + } + /** + * The HTTP status code of the error. + */ + get statusCode() { + return this._statusCode; + } + /** + * The URL that was requested. + */ + get url() { + return this._url; + } + /** + * The HTTP method that was used for the request. + */ + get method() { + return this._method; + } + /** + * The body that was used for the request, as a string. + */ + get body() { + return this._body; + } +}; + +// node_modules/.pnpm/@twurple+api-call@8.0.3/node_modules/@twurple/api-call/lib/helpers/transform.js +async function handleTwitchApiResponseError(response, options) { + if (!response.ok) { + const isJson = response.headers.get("Content-Type") === "application/json"; + const text2 = isJson ? JSON.stringify(await response.json(), null, 2) : await response.text(); + const params = qsStringify(options.query); + const fullUrl = `${options.url}${params}`; + throw new HttpStatusCodeError(response.status, response.statusText, fullUrl, options.method ?? "GET", text2, isJson); + } +} +__name(handleTwitchApiResponseError, "handleTwitchApiResponseError"); +async function transformTwitchApiResponse(response) { + if (response.status === 204) { + return void 0; + } + const text2 = await response.text(); + if (!text2) { + return void 0; + } + return JSON.parse(text2); +} +__name(transformTwitchApiResponse, "transformTwitchApiResponse"); + +// node_modules/.pnpm/@twurple+api-call@8.0.3/node_modules/@twurple/api-call/lib/helpers/url.js +init_modules_watch_stub(); +init_performance2(); +function getTwitchApiUrl(url, type) { + const mockServerPort = getMockApiPort(); + switch (type) { + case "helix": { + const unprefixedUrl = url.replace(/^\//, ""); + return mockServerPort ? unprefixedUrl === "eventsub/subscriptions" ? `http://localhost:${mockServerPort}/${unprefixedUrl}` : `http://localhost:${mockServerPort}/mock/${unprefixedUrl}` : `https://api.twitch.tv/helix/${unprefixedUrl}`; + } + case "auth": { + const unprefixedUrl = url.replace(/^\//, ""); + return mockServerPort ? `http://localhost:${mockServerPort}/auth/${unprefixedUrl}` : `https://id.twitch.tv/oauth2/${unprefixedUrl}`; + } + case "custom": + return url; + default: + return url; + } +} +__name(getTwitchApiUrl, "getTwitchApiUrl"); + +// node_modules/.pnpm/@twurple+api-call@8.0.3/node_modules/@twurple/api-call/lib/apiCall.js +async function callTwitchApiRaw(options, clientId, accessToken, authorizationType, fetchOptions = {}) { + const type = options.type ?? "helix"; + const url = getTwitchApiUrl(options.url, type); + const params = qsStringify(options.query); + const headers = new Headers({ Accept: "application/json" }); + let body = void 0; + if (options.jsonBody) { + body = JSON.stringify(options.jsonBody); + headers.append("Content-Type", "application/json"); + } + if (clientId && type !== "auth") { + headers.append("Client-ID", clientId); + } + if (accessToken) { + headers.append("Authorization", `${type === "helix" ? authorizationType ?? "Bearer" : "OAuth"} ${accessToken}`); + } + const requestOptions = { + ...fetchOptions, + method: options.method ?? "GET", + headers, + body + }; + return await fetch(`${url}${params}`, requestOptions); +} +__name(callTwitchApiRaw, "callTwitchApiRaw"); +async function callTwitchApi(options, clientId, accessToken, authorizationType, fetchOptions = {}) { + const response = await callTwitchApiRaw(options, clientId, accessToken, authorizationType, fetchOptions); + await handleTwitchApiResponseError(response, options); + return await transformTwitchApiResponse(response); +} +__name(callTwitchApi, "callTwitchApi"); + +// node_modules/.pnpm/@twurple+api-call@8.0.3/node_modules/@twurple/api-call/lib/helpers/queries.external.js +init_modules_watch_stub(); +init_performance2(); +function createBroadcasterQuery(user) { + return { + broadcaster_id: extractUserId(user) + }; +} +__name(createBroadcasterQuery, "createBroadcasterQuery"); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/errors/ConfigError.js +init_modules_watch_stub(); +init_performance2(); +var ConfigError = class extends CustomError2 { + static { + __name(this, "ConfigError"); + } +}; + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/utils/HelixRateLimiter.js +init_modules_watch_stub(); +init_performance2(); +var HelixRateLimiter = class extends ResponseBasedRateLimiter { + static { + __name(this, "HelixRateLimiter"); + } + async doRequest({ options, clientId, accessToken, authorizationType, fetchOptions }) { + return await callTwitchApiRaw(options, clientId, accessToken, authorizationType, fetchOptions); + } + needsToRetryAfter(res) { + if (res.status === 429 && (!res.headers.has("ratelimit-remaining") || Number(res.headers.get("ratelimit-remaining")) === 0)) { + return +res.headers.get("ratelimit-reset") * 1e3 - Date.now(); + } + return null; + } + getParametersFromResponse(res) { + const { headers } = res; + return { + limit: +headers.get("ratelimit-limit"), + remaining: +headers.get("ratelimit-remaining"), + resetsAt: +headers.get("ratelimit-reset") * 1e3 + }; + } +}; + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/client/BaseApiClient.js +init_modules_watch_stub(); +init_performance2(); + +// node_modules/.pnpm/@d-fischer+cache-decorators@4.0.1/node_modules/@d-fischer/cache-decorators/es/index.mjs +init_modules_watch_stub(); +init_performance2(); + +// node_modules/.pnpm/@d-fischer+cache-decorators@4.0.1/node_modules/@d-fischer/cache-decorators/es/decorators/Cacheable.mjs +init_modules_watch_stub(); +init_performance2(); + +// node_modules/.pnpm/@d-fischer+cache-decorators@4.0.1/node_modules/@d-fischer/cache-decorators/es/utils/createCacheKey.mjs +init_modules_watch_stub(); +init_performance2(); +function createSingleCacheKey(param) { + switch (typeof param) { + case "undefined": { + return ""; + } + case "object": { + if (param === null) { + return ""; + } + if ("cacheKey" in param) { + return param.cacheKey; + } + const objKey = JSON.stringify(param); + if (objKey !== "{}") { + return objKey; + } + } + // fallthrough + default: { + return param.toString(); + } + } +} +__name(createSingleCacheKey, "createSingleCacheKey"); +function createCacheKey(propName, params, prefix) { + return [propName, ...params.map(createSingleCacheKey)].join("/") + (prefix ? "/" : ""); +} +__name(createCacheKey, "createCacheKey"); + +// node_modules/.pnpm/@d-fischer+cache-decorators@4.0.1/node_modules/@d-fischer/cache-decorators/es/decorators/Cacheable.mjs +var cacheSymbol = /* @__PURE__ */ Symbol("cache"); +function Cacheable(cls) { + var _a4, _b3; + return _b3 = class extends cls { + static { + __name(this, "_b"); + } + constructor() { + super(...arguments); + this[_a4] = /* @__PURE__ */ new Map(); + } + getFromCache(cacheKey) { + this._cleanCache(); + if (this[cacheSymbol].has(cacheKey)) { + const entry = this[cacheSymbol].get(cacheKey); + if (entry) { + return entry.value; + } + } + return void 0; + } + setCache(cacheKey, value, timeInSeconds) { + this[cacheSymbol].set(cacheKey, { + value, + expires: Date.now() + timeInSeconds * 1e3 + }); + } + removeFromCache(cacheKey, prefix) { + const internalCacheKey = this._getInternalCacheKey(cacheKey, prefix); + if (prefix) { + this[cacheSymbol].forEach((val, key) => { + if (key.startsWith(internalCacheKey)) { + this[cacheSymbol].delete(key); + } + }); + } else { + this[cacheSymbol].delete(internalCacheKey); + } + } + _cleanCache() { + const now = Date.now(); + this[cacheSymbol].forEach((val, key) => { + if (val.expires < now) { + this[cacheSymbol].delete(key); + } + }); + } + _getInternalCacheKey(cacheKey, prefix) { + if (typeof cacheKey === "string") { + let internalCacheKey = cacheKey; + if (!internalCacheKey.endsWith("/")) { + internalCacheKey += "/"; + } + return internalCacheKey; + } else { + const propName = cacheKey.shift(); + return createCacheKey(propName, cacheKey, prefix); + } + } + }, _a4 = cacheSymbol, _b3; +} +__name(Cacheable, "Cacheable"); + +// node_modules/.pnpm/@d-fischer+cache-decorators@4.0.1/node_modules/@d-fischer/cache-decorators/es/decorators/CachedGetter.mjs +init_modules_watch_stub(); +init_performance2(); +function CachedGetter(timeInSeconds = Infinity) { + return function(target, propName, descriptor) { + if (descriptor.get) { + const origFn = descriptor.get; + descriptor.get = function() { + const cacheKey = createCacheKey(propName, []); + const cachedValue = this.getFromCache(cacheKey); + if (cachedValue) { + return cachedValue; + } + const result = origFn.call(this); + this.setCache(cacheKey, result, timeInSeconds); + return result; + }; + } + return descriptor; + }; +} +__name(CachedGetter, "CachedGetter"); + +// node_modules/.pnpm/@d-fischer+typed-event-emitter@3.3.3/node_modules/@d-fischer/typed-event-emitter/es/index.mjs +init_modules_watch_stub(); +init_performance2(); + +// node_modules/.pnpm/@d-fischer+typed-event-emitter@3.3.3/node_modules/@d-fischer/typed-event-emitter/es/EventEmitter.mjs +init_modules_watch_stub(); +init_performance2(); + +// node_modules/.pnpm/@d-fischer+typed-event-emitter@3.3.3/node_modules/@d-fischer/typed-event-emitter/es/Listener.mjs +init_modules_watch_stub(); +init_performance2(); +var Listener = class { + static { + __name(this, "Listener"); + } + /** @private */ + constructor(owner, event, listener, _internal = false) { + this.owner = owner; + this.event = event; + this.listener = listener; + this._internal = _internal; + } + unbind() { + this.owner.removeListener(this); + } +}; + +// node_modules/.pnpm/@d-fischer+typed-event-emitter@3.3.3/node_modules/@d-fischer/typed-event-emitter/es/EventEmitter.mjs +var EventEmitter2 = class { + static { + __name(this, "EventEmitter"); + } + constructor() { + this._eventListeners = /* @__PURE__ */ new Map(); + this._internalEventListeners = /* @__PURE__ */ new Map(); + } + on(event, listener) { + return this._addListener(false, event, listener); + } + addListener(event, listener) { + return this._addListener(false, event, listener); + } + removeListener(idOrEvent, listener) { + this._removeListener(false, idOrEvent, listener); + } + registerEvent() { + const eventBinder = /* @__PURE__ */ __name((handler) => this.addListener(eventBinder, handler), "eventBinder"); + return eventBinder; + } + emit(event, ...args) { + if (this._eventListeners.has(event)) { + for (const listener of this._eventListeners.get(event)) { + listener(...args); + } + } + if (this._internalEventListeners.has(event)) { + for (const listener of this._internalEventListeners.get(event)) { + listener(...args); + } + } + } + registerInternalEvent() { + const eventBinder = /* @__PURE__ */ __name((handler) => this.addInternalListener(eventBinder, handler), "eventBinder"); + return eventBinder; + } + addInternalListener(event, listener) { + return this._addListener(true, event, listener); + } + removeInternalListener(idOrEvent, listener) { + this._removeListener(true, idOrEvent, listener); + } + _addListener(internal, event, listener) { + const listenerMap = internal ? this._eventListeners : this._internalEventListeners; + if (listenerMap.has(event)) { + listenerMap.get(event).push(listener); + } else { + listenerMap.set(event, [listener]); + } + return new Listener(this, event, listener, internal); + } + _removeListener(internal, idOrEvent, listener) { + const listenerMap = internal ? this._eventListeners : this._internalEventListeners; + if (!idOrEvent) { + listenerMap.clear(); + } else if (typeof idOrEvent === "object") { + const id = idOrEvent; + this._removeListener(id._internal, id.event, id.listener); + } else { + const event = idOrEvent; + if (listenerMap.has(event)) { + if (listener) { + const listeners = listenerMap.get(event); + let idx = 0; + while ((idx = listeners.indexOf(listener)) !== -1) { + listeners.splice(idx, 1); + } + } else { + listenerMap.delete(event); + } + } + } + } +}; + +// node_modules/.pnpm/@twurple+auth@8.0.3/node_modules/@twurple/auth/lib/index.js +init_modules_watch_stub(); +init_performance2(); + +// node_modules/.pnpm/@twurple+auth@8.0.3/node_modules/@twurple/auth/lib/AccessToken.js +init_modules_watch_stub(); +init_performance2(); +var EXPIRY_GRACE_PERIOD = 6e4; +function getExpiryMillis(token) { + return mapNullable(token.expiresIn, (_) => token.obtainmentTimestamp + _ * 1e3 - EXPIRY_GRACE_PERIOD); +} +__name(getExpiryMillis, "getExpiryMillis"); +function accessTokenIsExpired(token) { + return mapNullable(getExpiryMillis(token), (_) => Date.now() > _) ?? false; +} +__name(accessTokenIsExpired, "accessTokenIsExpired"); + +// node_modules/.pnpm/@twurple+auth@8.0.3/node_modules/@twurple/auth/lib/helpers.js +init_modules_watch_stub(); +init_performance2(); + +// node_modules/.pnpm/@twurple+auth@8.0.3/node_modules/@twurple/auth/lib/errors/InvalidTokenError.js +init_modules_watch_stub(); +init_performance2(); +var InvalidTokenError = class extends CustomError2 { + static { + __name(this, "InvalidTokenError"); + } + /** @private */ + constructor(options) { + super("Invalid token supplied", options); + } +}; + +// node_modules/.pnpm/@twurple+auth@8.0.3/node_modules/@twurple/auth/lib/helpers.external.js +init_modules_watch_stub(); +init_performance2(); +function createGetAppTokenQuery(clientId, clientSecret) { + return { + grant_type: "client_credentials", + client_id: clientId, + client_secret: clientSecret + }; +} +__name(createGetAppTokenQuery, "createGetAppTokenQuery"); + +// node_modules/.pnpm/@twurple+auth@8.0.3/node_modules/@twurple/auth/lib/TokenInfo.js +init_modules_watch_stub(); +init_performance2(); +var TokenInfo = class TokenInfo2 extends DataObject { + static { + __name(this, "TokenInfo"); + } + _obtainmentDate; + /** @internal */ + constructor(data2) { + super(data2); + this._obtainmentDate = /* @__PURE__ */ new Date(); + } + /** + * The client ID. + */ + get clientId() { + return this[rawDataSymbol].client_id; + } + /** + * The ID of the authenticated user. + */ + get userId() { + return this[rawDataSymbol].user_id ?? null; + } + /** + * The name of the authenticated user. + */ + get userName() { + return this[rawDataSymbol].login ?? null; + } + /** + * The scopes for which the token is valid. + */ + get scopes() { + return this[rawDataSymbol].scopes; + } + /** + * The time when the token will expire. + * + * If this returns null, it means that the token never expires (happens with some old client IDs). + */ + get expiryDate() { + return mapNullable(this[rawDataSymbol].expires_in, (v) => new Date(this._obtainmentDate.getTime() + v * 1e3)); + } +}; +TokenInfo = __decorate([ + rtfm("auth", "TokenInfo", "clientId") +], TokenInfo); + +// node_modules/.pnpm/@twurple+auth@8.0.3/node_modules/@twurple/auth/lib/helpers.js +function createAccessTokenFromData(data2) { + return { + accessToken: data2.access_token, + refreshToken: data2.refresh_token || null, + scope: data2.scope ?? [], + expiresIn: data2.expires_in ?? null, + obtainmentTimestamp: Date.now() + }; +} +__name(createAccessTokenFromData, "createAccessTokenFromData"); +async function getAppToken(clientId, clientSecret) { + return createAccessTokenFromData(await callTwitchApi({ + type: "auth", + url: "token", + method: "POST", + query: createGetAppTokenQuery(clientId, clientSecret) + })); +} +__name(getAppToken, "getAppToken"); + +// node_modules/.pnpm/@twurple+auth@8.0.3/node_modules/@twurple/auth/lib/TokenFetcher.js +init_modules_watch_stub(); +init_performance2(); +var TokenFetcher = class { + static { + __name(this, "TokenFetcher"); + } + _executor; + _newTokenScopeSets = []; + _newTokenPromise = null; + _queuedScopeSets = []; + _queueExecutor = null; + _queuePromise = null; + constructor(executor) { + this._executor = executor; + } + async fetch(...scopeSets) { + const filteredScopeSets = scopeSets.filter((val) => Boolean(val)); + if (this._newTokenPromise) { + if (!filteredScopeSets.length) { + return await this._newTokenPromise; + } + if (this._queueExecutor) { + this._queuedScopeSets.push(...filteredScopeSets); + } else { + this._queuedScopeSets = [...filteredScopeSets]; + } + if (!this._queuePromise) { + const { promise: promise2, resolve: resolve2, reject: reject2 } = promiseWithResolvers(); + this._queuePromise = promise2; + this._queueExecutor = async () => { + if (!this._queuePromise) { + return; + } + this._newTokenScopeSets = this._queuedScopeSets; + this._queuedScopeSets = []; + this._newTokenPromise = this._queuePromise; + this._queuePromise = null; + this._queueExecutor = null; + try { + resolve2(await this._executor(this._newTokenScopeSets)); + } catch (e) { + reject2(e); + } finally { + this._newTokenPromise = null; + this._newTokenScopeSets = []; + this._queueExecutor?.(); + } + }; + } + return await this._queuePromise; + } + this._newTokenScopeSets = [...filteredScopeSets]; + const { promise, resolve, reject } = promiseWithResolvers(); + this._newTokenPromise = promise; + try { + resolve(await this._executor(this._newTokenScopeSets)); + } catch (e) { + reject(e); + } finally { + this._newTokenPromise = null; + this._newTokenScopeSets = []; + this._queueExecutor?.(); + } + return await promise; + } +}; + +// node_modules/.pnpm/@twurple+auth@8.0.3/node_modules/@twurple/auth/lib/providers/AppTokenAuthProvider.js +init_modules_watch_stub(); +init_performance2(); +var AppTokenAuthProvider = class AppTokenAuthProvider2 { + static { + __name(this, "AppTokenAuthProvider"); + } + _clientId; + /** @internal */ + _clientSecret; + /** @internal */ + _token; + /** @internal */ + _fetcher; + _impliedScopes; + /** + * Creates a new auth provider to receive an application token with using the client ID and secret. + * + * @param clientId The client ID of your application. + * @param clientSecret The client secret of your application. + * @param impliedScopes The scopes that are implied for your application, + * for example an extension that is allowed to access subscriptions. + */ + constructor(clientId, clientSecret, impliedScopes = []) { + this._clientId = clientId; + this._clientSecret = clientSecret; + this._impliedScopes = impliedScopes; + this._fetcher = new TokenFetcher(async (scopes) => await this._fetch(scopes)); + } + /** + * The client ID. + */ + get clientId() { + return this._clientId; + } + /** + * The scopes that are currently available using the access token. + */ + get currentScopes() { + return this._impliedScopes; + } + /** + * Can only get tokens for implied scopes (i.e. extension subscription support). + * + * The consumer is expected to take care that this is actually set up in the Twitch developer console. + * + * @param user The user to get an access token for. + * @param scopeSets The requested scopes. + */ + async getAccessTokenForUser(user, ...scopeSets) { + if (scopeSets.every((scopeSet) => scopeSet?.some((scope) => this._impliedScopes.includes(scope)) ?? true)) { + const appToken = await this.getAppAccessToken(); + return { + ...appToken, + userId: extractUserId(user) + }; + } + throw new Error("Can not get user access token for AppTokenAuthProvider"); + } + /** + * Throws, because this auth provider does not support user authentication. + */ + getCurrentScopesForUser() { + return this._impliedScopes; + } + /** + * Fetches an app access token. + */ + async getAnyAccessToken() { + return await this._fetcher.fetch(); + } + /** + * Fetches an app access token. + * + * @param forceNew Whether to always get a new token, even if the old one is still deemed valid internally. + */ + async getAppAccessToken(forceNew = false) { + if (forceNew) { + this._token = void 0; + } + return await this._fetcher.fetch(); + } + async _fetch(scopeSets) { + if (scopeSets.length > 0) { + for (const scopes of scopeSets) { + if (this._impliedScopes.length) { + if (scopes.every((scope) => !this._impliedScopes.includes(scope))) { + throw new Error(`One of the scopes ${scopes.join(", ")} requested but only the scope ${this._impliedScopes.join(", ")} is implied`); + } + } else { + throw new Error(`One of the scopes ${scopes.join(", ")} requested but the client credentials flow does not support scopes`); + } + } + } + if (!this._token || accessTokenIsExpired(this._token)) { + return this._token = await getAppToken(this._clientId, this._clientSecret); + } + return this._token; + } +}; +__decorate([ + Enumerable(false) +], AppTokenAuthProvider.prototype, "_clientSecret", void 0); +__decorate([ + Enumerable(false) +], AppTokenAuthProvider.prototype, "_token", void 0); +__decorate([ + Enumerable(false) +], AppTokenAuthProvider.prototype, "_fetcher", void 0); +AppTokenAuthProvider = __decorate([ + rtfm("auth", "AppTokenAuthProvider", "clientId") +], AppTokenAuthProvider); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/client/BaseApiClient.js +var retry = __toESM(require_retry2(), 1); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/bits/HelixBitsApi.js +init_modules_watch_stub(); +init_performance2(); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/interfaces/endpoints/bits.external.js +init_modules_watch_stub(); +init_performance2(); +function createBitsLeaderboardQuery(params = {}) { + const { count: count2 = 10, period = "all", startDate, contextUserId } = params; + return { + count: count2.toString(), + period, + started_at: startDate?.toISOString(), + user_id: contextUserId + }; +} +__name(createBitsLeaderboardQuery, "createBitsLeaderboardQuery"); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/BaseApi.js +init_modules_watch_stub(); +init_performance2(); +var BaseApi = class { + static { + __name(this, "BaseApi"); + } + /** @internal */ + _client; + /** @internal */ + constructor(client) { + this._client = client; + } + /** @internal */ + _getUserContextIdWithDefault(userId) { + return this._client._getUserIdFromRequestContext(userId) ?? userId; + } +}; +__decorate([ + Enumerable(false) +], BaseApi.prototype, "_client", void 0); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/bits/HelixBitsLeaderboard.js +init_modules_watch_stub(); +init_performance2(); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/bits/HelixBitsLeaderboardEntry.js +init_modules_watch_stub(); +init_performance2(); +var HelixBitsLeaderboardEntry = class HelixBitsLeaderboardEntry2 extends DataObject { + static { + __name(this, "HelixBitsLeaderboardEntry"); + } + /** @internal */ + _client; + /** @internal */ + constructor(data2, client) { + super(data2); + this._client = client; + } + /** + * The ID of the user on the leaderboard. + */ + get userId() { + return this[rawDataSymbol].user_id; + } + /** + * The name of the user on the leaderboard. + */ + get userName() { + return this[rawDataSymbol].user_login; + } + /** + * The display name of the user on the leaderboard. + */ + get userDisplayName() { + return this[rawDataSymbol].user_name; + } + /** + * The position of the user on the leaderboard. + */ + get rank() { + return this[rawDataSymbol].rank; + } + /** + * The amount of bits used in the given period of time. + */ + get amount() { + return this[rawDataSymbol].score; + } + /** + * Gets the user of entry on the leaderboard. + */ + async getUser() { + return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].user_id)); + } +}; +__decorate([ + Enumerable(false) +], HelixBitsLeaderboardEntry.prototype, "_client", void 0); +HelixBitsLeaderboardEntry = __decorate([ + rtfm("api", "HelixBitsLeaderboardEntry", "userId") +], HelixBitsLeaderboardEntry); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/bits/HelixBitsLeaderboard.js +var HelixBitsLeaderboard = class HelixBitsLeaderboard2 extends DataObject { + static { + __name(this, "HelixBitsLeaderboard"); + } + /** @internal */ + _client; + /** @internal */ + constructor(data2, client) { + super(data2); + this._client = client; + } + /** + * The entries of the leaderboard. + */ + get entries() { + return this[rawDataSymbol].data.map((entry) => new HelixBitsLeaderboardEntry(entry, this._client)); + } + /** + * The total amount of people on the requested leaderboard. + */ + get totalCount() { + return this[rawDataSymbol].total; + } +}; +__decorate([ + Enumerable(false) +], HelixBitsLeaderboard.prototype, "_client", void 0); +__decorate([ + CachedGetter() +], HelixBitsLeaderboard.prototype, "entries", null); +HelixBitsLeaderboard = __decorate([ + Cacheable, + rtfm("api", "HelixBitsLeaderboard") +], HelixBitsLeaderboard); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/bits/HelixCheermoteList.js +init_modules_watch_stub(); +init_performance2(); +var HelixCheermoteList = class HelixCheermoteList2 extends DataObject { + static { + __name(this, "HelixCheermoteList"); + } + /** @internal */ + constructor(data2) { + super(indexBy(data2, (action) => action.prefix.toLowerCase())); + } + /** + * Gets the URL and color needed to properly represent a cheer of the given amount of bits with the given prefix. + * + * @param name The name/prefix of the cheermote. + * @param bits The amount of bits cheered. + * @param format The format of the cheermote you want to request. + */ + getCheermoteDisplayInfo(name, bits, format) { + name = name.toLowerCase(); + const { background, state, scale } = format; + const { tiers } = this[rawDataSymbol][name]; + const correctTier = tiers.sort((a, b) => b.min_bits - a.min_bits).find((tier) => tier.min_bits <= bits); + if (!correctTier) { + throw new HellFreezesOverError(`Cheermote "${name}" does not have an applicable tier for ${bits} bits`); + } + return { + url: correctTier.images[background][state][scale], + color: correctTier.color + }; + } + /** + * Gets all possible cheermote names. + */ + getPossibleNames() { + return Object.keys(this[rawDataSymbol]); + } +}; +HelixCheermoteList = __decorate([ + rtfm("api", "HelixCheermoteList") +], HelixCheermoteList); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/bits/HelixBitsApi.js +var HelixBitsApi = class HelixBitsApi2 extends BaseApi { + static { + __name(this, "HelixBitsApi"); + } + /** + * Gets a bits leaderboard of your channel. + * + * @param broadcaster The user to get the leaderboard of. + * @param params + * @expandParams + */ + async getLeaderboard(broadcaster, params = {}) { + const result = await this._client.callApi({ + type: "helix", + url: "bits/leaderboard", + userId: extractUserId(broadcaster), + scopes: ["bits:read"], + query: createBitsLeaderboardQuery(params) + }); + return new HelixBitsLeaderboard(result, this._client); + } + /** + * Gets all available cheermotes. + * + * @param broadcaster The broadcaster to include custom cheermotes of. + * + * If not given, only get global cheermotes. + */ + async getCheermotes(broadcaster) { + const result = await this._client.callApi({ + type: "helix", + url: "bits/cheermotes", + userId: mapOptional(broadcaster, extractUserId), + query: mapOptional(broadcaster, createBroadcasterQuery) + }); + return new HelixCheermoteList(result.data); + } +}; +HelixBitsApi = __decorate([ + rtfm("api", "HelixBitsApi") +], HelixBitsApi); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/channel/HelixChannelApi.js +init_modules_watch_stub(); +init_performance2(); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/interfaces/endpoints/channel.external.js +init_modules_watch_stub(); +init_performance2(); +function createChannelUpdateBody(data2) { + return { + game_id: data2.gameId, + broadcaster_language: data2.language, + title: data2.title, + delay: data2.delay?.toString(), + tags: data2.tags, + content_classification_labels: data2.contentClassificationLabels, + is_branded_content: data2.isBrandedContent + }; +} +__name(createChannelUpdateBody, "createChannelUpdateBody"); +function createChannelCommercialBody(broadcaster, length) { + return { + broadcaster_id: extractUserId(broadcaster), + length + }; +} +__name(createChannelCommercialBody, "createChannelCommercialBody"); +function createChannelVipUpdateQuery(broadcaster, user) { + return { + broadcaster_id: extractUserId(broadcaster), + user_id: extractUserId(user) + }; +} +__name(createChannelVipUpdateQuery, "createChannelVipUpdateQuery"); +function createChannelFollowerQuery(broadcaster, user) { + return { + broadcaster_id: extractUserId(broadcaster), + user_id: mapOptional(user, extractUserId) + }; +} +__name(createChannelFollowerQuery, "createChannelFollowerQuery"); +function createFollowedChannelQuery(user, broadcaster) { + return { + broadcaster_id: mapOptional(broadcaster, extractUserId), + user_id: extractUserId(user) + }; +} +__name(createFollowedChannelQuery, "createFollowedChannelQuery"); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/interfaces/endpoints/generic.external.js +init_modules_watch_stub(); +init_performance2(); +function createSingleKeyQuery(key, value) { + return { [key]: value }; +} +__name(createSingleKeyQuery, "createSingleKeyQuery"); +function createUserQuery(user) { + return { + user_id: extractUserId(user) + }; +} +__name(createUserQuery, "createUserQuery"); +function createModeratorActionQuery(broadcaster, moderatorId) { + return { + broadcaster_id: broadcaster, + moderator_id: moderatorId + }; +} +__name(createModeratorActionQuery, "createModeratorActionQuery"); +function createGetByIdsQuery(broadcaster, rewardIds) { + return { + broadcaster_id: extractUserId(broadcaster), + id: rewardIds + }; +} +__name(createGetByIdsQuery, "createGetByIdsQuery"); +function createChannelUsersCheckQuery(broadcaster, users) { + return { + broadcaster_id: extractUserId(broadcaster), + user_id: users.map(extractUserId) + }; +} +__name(createChannelUsersCheckQuery, "createChannelUsersCheckQuery"); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/relations/HelixUserRelation.js +init_modules_watch_stub(); +init_performance2(); +var HelixUserRelation = class HelixUserRelation2 extends DataObject { + static { + __name(this, "HelixUserRelation"); + } + /** @internal */ + _client; + /** @internal */ + constructor(data2, client) { + super(data2); + this._client = client; + } + /** + * The ID of the user. + */ + get id() { + return this[rawDataSymbol].user_id; + } + /** + * The name of the user. + */ + get name() { + return this[rawDataSymbol].user_login; + } + /** + * The display name of the user. + */ + get displayName() { + return this[rawDataSymbol].user_name; + } + /** + * Gets additional information about the user. + */ + async getUser() { + return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].user_id)); + } +}; +__decorate([ + Enumerable(false) +], HelixUserRelation.prototype, "_client", void 0); +HelixUserRelation = __decorate([ + rtfm("api", "HelixUserRelation", "id") +], HelixUserRelation); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/utils/HelixRequestBatcher.js +init_modules_watch_stub(); +init_performance2(); +var HelixRequestBatcher = class { + static { + __name(this, "HelixRequestBatcher"); + } + _callOptions; + _queryParamName; + _matchKey; + _mapper; + _limitPerRequest; + _client; + _requestedIds = []; + _requestResolversById = /* @__PURE__ */ new Map(); + _delay; + _waitTimer = null; + constructor(_callOptions, _queryParamName, _matchKey, client, _mapper, _limitPerRequest = 100) { + this._callOptions = _callOptions; + this._queryParamName = _queryParamName; + this._matchKey = _matchKey; + this._mapper = _mapper; + this._limitPerRequest = _limitPerRequest; + this._client = client; + this._delay = client._batchDelay; + } + async request(id) { + const { promise, resolve, reject } = promiseWithResolvers(); + if (!this._requestedIds.includes(id)) { + this._requestedIds.push(id); + } + if (this._requestResolversById.has(id)) { + this._requestResolversById.get(id).push({ resolve, reject }); + } else { + this._requestResolversById.set(id, [{ resolve, reject }]); + } + if (this._waitTimer) { + clearTimeout(this._waitTimer); + this._waitTimer = null; + } + if (this._requestedIds.length >= this._limitPerRequest) { + void this._handleBatch(this._requestedIds.splice(0, this._limitPerRequest)); + } else { + this._waitTimer = setTimeout(() => { + void this._handleBatch(this._requestedIds.splice(0, this._limitPerRequest)); + }, this._delay); + } + return await promise; + } + async _handleBatch(ids) { + try { + const { data: data2 } = await this._doRequest(ids); + const dataById = indexBy(data2, this._matchKey); + for (const id of ids) { + for (const resolver of this._requestResolversById.get(id) ?? []) { + if (Object.prototype.hasOwnProperty.call(dataById, id)) { + resolver.resolve(this._mapper(dataById[id])); + } else { + resolver.resolve(null); + } + } + this._requestResolversById.delete(id); + } + } catch (e) { + await Promise.all(ids.map(async (id) => { + try { + const result = await this._doRequest([id]); + for (const resolver of this._requestResolversById.get(id) ?? []) { + resolver.resolve(result.data.length ? this._mapper(result.data[0]) : null); + } + } catch (e_) { + for (const resolver of this._requestResolversById.get(id) ?? []) { + resolver.reject(e_); + } + } + this._requestResolversById.delete(id); + })); + } + } + async _doRequest(ids) { + return await this._client.callApi({ + type: "helix", + ...this._callOptions, + query: { + ...this._callOptions.query, + [this._queryParamName]: ids + } + }); + } +}; +__decorate([ + Enumerable(false) +], HelixRequestBatcher.prototype, "_client", void 0); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/utils/pagination/HelixPaginatedRequest.js +init_modules_watch_stub(); +init_performance2(); +if (!Object.prototype.hasOwnProperty.call(Symbol, "asyncIterator")) { + Symbol.asyncIterator = Symbol.asyncIterator ?? /* @__PURE__ */ Symbol.for("Symbol.asyncIterator"); +} +var HelixPaginatedRequest = class HelixPaginatedRequest2 { + static { + __name(this, "HelixPaginatedRequest"); + } + _callOptions; + _mapper; + _limitPerPage; + /** @internal */ + _client; + /** @internal */ + _currentCursor; + /** @internal */ + _isFinished = false; + /** @internal */ + _currentData; + /** @internal */ + constructor(_callOptions, client, _mapper, _limitPerPage = 100) { + this._callOptions = _callOptions; + this._mapper = _mapper; + this._limitPerPage = _limitPerPage; + this._client = client; + } + /** + * The last fetched page of data associated to the requested resource. + * + * Only works with {@link HelixPaginatedRequest#getNext} and not with any other methods of data fetching. + */ + get current() { + return this._currentData?.data; + } + /** + * Gets the next available page of data associated to the requested resource, or an empty array if there are no more available pages. + */ + async getNext() { + if (this._isFinished) { + return []; + } + const result = await this._fetchData(); + if (!result.data?.length) { + this._isFinished = true; + return []; + } + return this._processResult(result); + } + /** + * Gets all data associated to the requested resource. + * + * Be aware that this makes multiple calls to the Twitch API. Due to this, you might be more suspectible to rate limits. + * + * Also be aware that this resets the internal cursor, so avoid using this and {@link HelixPaginatedRequest#getNext}} together. + */ + async getAll() { + this.reset(); + const result = []; + do { + const data2 = await this.getNext(); + if (!data2.length) { + break; + } + result.push(...data2); + } while (this._currentCursor); + this.reset(); + return result; + } + /** + * Gets the current cursor. + * + * Only useful if you want to make manual requests to the API. + */ + get currentCursor() { + return this._currentCursor; + } + /** + * Resets the internal cursor. + * + * This will make {@link HelixPaginatedRequest#getNext}} start from the first page again. + */ + reset() { + this._currentCursor = void 0; + this._isFinished = false; + this._currentData = void 0; + } + async *[Symbol.asyncIterator]() { + this.reset(); + while (true) { + const data2 = await this.getNext(); + if (!data2.length) { + break; + } + yield* data2[Symbol.iterator](); + } + } + /** @internal */ + async _fetchData(additionalOptions = {}) { + return await this._client.callApi({ + type: "helix", + ...this._callOptions, + ...additionalOptions, + query: { + ...this._callOptions.query, + after: this._currentCursor, + first: this._limitPerPage.toString(), + ...additionalOptions.query + } + }); + } + /** @internal */ + _processResult(result) { + this._currentCursor = typeof result.pagination === "string" ? result.pagination : result.pagination?.cursor; + if (this._currentCursor === void 0) { + this._isFinished = true; + } + this._currentData = result; + return result.data.reduce((acc, elem) => { + const mapped = this._mapper(elem); + return Array.isArray(mapped) ? [...acc, ...mapped] : [...acc, mapped]; + }, []); + } +}; +__decorate([ + Enumerable(false) +], HelixPaginatedRequest.prototype, "_client", void 0); +HelixPaginatedRequest = __decorate([ + rtfm("api", "HelixPaginatedRequest") +], HelixPaginatedRequest); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/utils/pagination/HelixPaginatedRequestWithTotal.js +init_modules_watch_stub(); +init_performance2(); +var HelixPaginatedRequestWithTotal = class HelixPaginatedRequestWithTotal2 extends HelixPaginatedRequest { + static { + __name(this, "HelixPaginatedRequestWithTotal"); + } + /** + * Gets the total number of entities existing in the queried result set. + */ + async getTotalCount() { + const data2 = this._currentData ?? await this._fetchData({ query: { after: void 0 } }); + return data2.total; + } +}; +HelixPaginatedRequestWithTotal = __decorate([ + rtfm("api", "HelixPaginatedRequestWithTotal") +], HelixPaginatedRequestWithTotal); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/utils/pagination/HelixPaginatedResult.js +init_modules_watch_stub(); +init_performance2(); +function createPaginatedResult(response, type, client) { + let dataCache = void 0; + return { + get data() { + return dataCache ??= response.data?.map((data2) => new type(data2, client)) ?? []; + }, + cursor: typeof response.pagination === "string" ? response.pagination : response.pagination?.cursor + }; +} +__name(createPaginatedResult, "createPaginatedResult"); +function createPaginatedResultWithTotal(response, type, client) { + let dataCache = void 0; + return { + get data() { + return dataCache ??= response.data?.map((data2) => new type(data2, client)) ?? []; + }, + cursor: response.pagination.cursor, + total: response.total + }; +} +__name(createPaginatedResultWithTotal, "createPaginatedResultWithTotal"); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/utils/pagination/HelixPagination.js +init_modules_watch_stub(); +init_performance2(); +function createPaginationQuery({ after, before, limit } = {}) { + return { + after, + before, + first: limit?.toString() + }; +} +__name(createPaginationQuery, "createPaginationQuery"); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/channel/HelixChannel.js +init_modules_watch_stub(); +init_performance2(); +var HelixChannel = class HelixChannel2 extends DataObject { + static { + __name(this, "HelixChannel"); + } + /** @internal */ + _client; + /** @internal */ + constructor(data2, client) { + super(data2); + this._client = client; + } + /** + * The ID of the channel. + */ + get id() { + return this[rawDataSymbol].broadcaster_id; + } + /** + * The name of the channel. + */ + get name() { + return this[rawDataSymbol].broadcaster_login; + } + /** + * The display name of the channel. + */ + get displayName() { + return this[rawDataSymbol].broadcaster_name; + } + /** + * Gets more information about the broadcaster of the channel. + */ + async getBroadcaster() { + return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].broadcaster_id)); + } + /** + * The language of the channel. + */ + get language() { + return this[rawDataSymbol].broadcaster_language; + } + /** + * The ID of the game currently played on the channel. + */ + get gameId() { + return this[rawDataSymbol].game_id; + } + /** + * The name of the game currently played on the channel. + */ + get gameName() { + return this[rawDataSymbol].game_name; + } + /** + * Gets information about the game that is being played on the stream. + */ + async getGame() { + return this[rawDataSymbol].game_id ? checkRelationAssertion(await this._client.games.getGameById(this[rawDataSymbol].game_id)) : null; + } + /** + * The title of the channel. + */ + get title() { + return this[rawDataSymbol].title; + } + /** + * The stream delay of the channel, in seconds. + * + * If you didn't request this with broadcaster access, this is always zero. + */ + get delay() { + return this[rawDataSymbol].delay; + } + /** + * The tags applied to the channel. + */ + get tags() { + return this[rawDataSymbol].tags; + } + /** + * The content classification labels applied to the channel. + */ + get contentClassificationLabels() { + return this[rawDataSymbol].content_classification_labels; + } + /** + * Whether the channel currently displays branded content (as specified by the broadcaster). + */ + get isBrandedContent() { + return this[rawDataSymbol].is_branded_content; + } +}; +__decorate([ + Enumerable(false) +], HelixChannel.prototype, "_client", void 0); +HelixChannel = __decorate([ + rtfm("api", "HelixChannel", "id") +], HelixChannel); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/channel/HelixChannelEditor.js +init_modules_watch_stub(); +init_performance2(); +var HelixChannelEditor = class HelixChannelEditor2 extends DataObject { + static { + __name(this, "HelixChannelEditor"); + } + /** @internal */ + _client; + /** @internal */ + constructor(data2, client) { + super(data2); + this._client = client; + } + /** + * The ID of the user. + */ + get userId() { + return this[rawDataSymbol].user_id; + } + /** + * The display name of the user. + */ + get userDisplayName() { + return this[rawDataSymbol].user_name; + } + /** + * Gets additional information about the user. + */ + async getUser() { + return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].user_id)); + } + /** + * The date when the user was given editor status. + */ + get creationDate() { + return new Date(this[rawDataSymbol].created_at); + } +}; +__decorate([ + Enumerable(false) +], HelixChannelEditor.prototype, "_client", void 0); +HelixChannelEditor = __decorate([ + rtfm("api", "HelixChannelEditor", "userId") +], HelixChannelEditor); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/channel/HelixChannelFollower.js +init_modules_watch_stub(); +init_performance2(); +var HelixChannelFollower = class HelixChannelFollower2 extends DataObject { + static { + __name(this, "HelixChannelFollower"); + } + /** @internal */ + _client; + /** @internal */ + constructor(data2, client) { + super(data2); + this._client = client; + } + /** + * The ID of the user. + */ + get userId() { + return this[rawDataSymbol].user_id; + } + /** + * The name of the user. + */ + get userName() { + return this[rawDataSymbol].user_login; + } + /** + * The display name of the user. + */ + get userDisplayName() { + return this[rawDataSymbol].user_name; + } + /** + * Gets additional information about the user. + */ + async getUser() { + return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].user_id)); + } + /** + * The date when the user followed the broadcaster. + */ + get followDate() { + return new Date(this[rawDataSymbol].followed_at); + } +}; +__decorate([ + Enumerable(false) +], HelixChannelFollower.prototype, "_client", void 0); +HelixChannelFollower = __decorate([ + rtfm("api", "HelixChannelFollower", "userId") +], HelixChannelFollower); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/channel/HelixFollowedChannel.js +init_modules_watch_stub(); +init_performance2(); +var HelixFollowedChannel = class HelixFollowedChannel2 extends DataObject { + static { + __name(this, "HelixFollowedChannel"); + } + /** @internal */ + _client; + /** @internal */ + constructor(data2, client) { + super(data2); + this._client = client; + } + /** + * The ID of the broadcaster. + */ + get broadcasterId() { + return this[rawDataSymbol].broadcaster_id; + } + /** + * The name of the broadcaster. + */ + get broadcasterName() { + return this[rawDataSymbol].broadcaster_login; + } + /** + * The display name of the broadcaster. + */ + get broadcasterDisplayName() { + return this[rawDataSymbol].broadcaster_name; + } + /** + * Gets additional information about the broadcaster. + */ + async getBroadcaster() { + return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].broadcaster_id)); + } + /** + * The date when the user followed the broadcaster. + */ + get followDate() { + return new Date(this[rawDataSymbol].followed_at); + } +}; +__decorate([ + Enumerable(false) +], HelixFollowedChannel.prototype, "_client", void 0); +HelixFollowedChannel = __decorate([ + rtfm("api", "HelixFollowedChannel", "broadcasterId") +], HelixFollowedChannel); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/channel/HelixAdSchedule.js +init_modules_watch_stub(); +init_performance2(); +var HelixAdSchedule = class HelixAdSchedule2 extends DataObject { + static { + __name(this, "HelixAdSchedule"); + } + /** + * The number of snoozes available for the broadcaster. + */ + get snoozeCount() { + return this[rawDataSymbol].snooze_count; + } + /** + * The date and time when the broadcaster will gain an additional snooze. + * Returns `null` if all snoozes are already available. + */ + get snoozeRefreshDate() { + return this[rawDataSymbol].snooze_refresh_at ? new Date(this[rawDataSymbol].snooze_refresh_at * 1e3) : null; + } + /** + * The date and time of the broadcaster's next scheduled ad. + * Returns `null` if channel is not live or has no ad scheduled. + */ + get nextAdDate() { + return this[rawDataSymbol].next_ad_at ? new Date(this[rawDataSymbol].next_ad_at * 1e3) : null; + } + /** + * The length in seconds of the scheduled upcoming ad break. + */ + get duration() { + return this[rawDataSymbol].duration; + } + /** + * The date and time of the broadcaster's last ad-break. + * Returns `null` if channel is not live or has not run an ad. + */ + get lastAdDate() { + return this[rawDataSymbol].last_ad_at ? new Date(this[rawDataSymbol].last_ad_at * 1e3) : null; + } + /** + * The amount of pre-roll free time remaining for the channel in seconds. + */ + get prerollFreeTime() { + return this[rawDataSymbol].preroll_free_time; + } +}; +HelixAdSchedule = __decorate([ + rtfm("api", "HelixAdSchedule") +], HelixAdSchedule); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/channel/HelixSnoozeNextAdResult.js +init_modules_watch_stub(); +init_performance2(); +var HelixSnoozeNextAdResult = class HelixSnoozeNextAdResult2 extends DataObject { + static { + __name(this, "HelixSnoozeNextAdResult"); + } + /** + * The number of snoozes remaining for the broadcaster. + */ + get snoozeCount() { + return this[rawDataSymbol].snooze_count; + } + /** + * The date and time when the broadcaster will gain an additional snooze. + */ + get snoozeRefreshDate() { + return new Date(this[rawDataSymbol].snooze_refresh_at * 1e3); + } + /** + * The date and time of the broadcaster's next scheduled ad. + */ + get nextAdDate() { + return new Date(this[rawDataSymbol].next_ad_at * 1e3); + } +}; +HelixSnoozeNextAdResult = __decorate([ + rtfm("api", "HelixSnoozeNextAdResult") +], HelixSnoozeNextAdResult); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/channel/HelixChannelApi.js +var HelixChannelApi = class HelixChannelApi2 extends BaseApi { + static { + __name(this, "HelixChannelApi"); + } + /** @internal */ + _getChannelByIdBatcher = new HelixRequestBatcher({ + url: "channels" + }, "broadcaster_id", "broadcaster_id", this._client, (data2) => new HelixChannel(data2, this._client)); + /** + * Gets the channel data for the given user. + * + * @param user The user you want to get channel info for. + */ + async getChannelInfoById(user) { + const userId = extractUserId(user); + const result = await this._client.callApi({ + type: "helix", + url: "channels", + userId, + query: createBroadcasterQuery(userId) + }); + return mapNullable(result.data[0], (data2) => new HelixChannel(data2, this._client)); + } + /** + * Gets the channel data for the given user, batching multiple calls into fewer requests as the API allows. + * + * @param user The user you want to get channel info for. + */ + async getChannelInfoByIdBatched(user) { + return await this._getChannelByIdBatcher.request(extractUserId(user)); + } + /** + * Gets the channel data for the given users. + * + * @param users The users you want to get channel info for. + */ + async getChannelInfoByIds(users) { + const userIds = users.map(extractUserId); + const result = await this._client.callApi({ + type: "helix", + url: "channels", + query: createSingleKeyQuery("broadcaster_id", userIds) + }); + return result.data.map((data2) => new HelixChannel(data2, this._client)); + } + /** + * Updates the given user's channel data. + * + * @param user The user you want to update channel info for. + * @param data The channel info to set. + */ + async updateChannelInfo(user, data2) { + await this._client.callApi({ + type: "helix", + url: "channels", + method: "PATCH", + userId: extractUserId(user), + scopes: ["channel:manage:broadcast"], + query: createBroadcasterQuery(user), + jsonBody: createChannelUpdateBody(data2) + }); + } + /** + * Starts a commercial on a channel. + * + * @param broadcaster The broadcaster on whose channel the commercial is started. + * @param length The length of the commercial, in seconds. + */ + async startChannelCommercial(broadcaster, length) { + await this._client.callApi({ + type: "helix", + url: "channels/commercial", + method: "POST", + userId: extractUserId(broadcaster), + scopes: ["channel:edit:commercial"], + jsonBody: createChannelCommercialBody(broadcaster, length) + }); + } + /** + * Gets a list of users who have editor permissions on your channel. + * + * @param broadcaster The broadcaster to retreive the editors for. + */ + async getChannelEditors(broadcaster) { + const result = await this._client.callApi({ + type: "helix", + url: "channels/editors", + userId: extractUserId(broadcaster), + scopes: ["channel:read:editors"], + query: createBroadcasterQuery(broadcaster) + }); + return result.data.map((data2) => new HelixChannelEditor(data2, this._client)); + } + /** + * Gets a list of VIPs in a channel. + * + * @param broadcaster The owner of the channel to get VIPs for. + * @param pagination + * + * @expandParams + */ + async getVips(broadcaster, pagination) { + const response = await this._client.callApi({ + type: "helix", + url: "channels/vips", + userId: extractUserId(broadcaster), + scopes: ["channel:read:vips", "channel:manage:vips"], + query: { + ...createBroadcasterQuery(broadcaster), + ...createPaginationQuery(pagination) + } + }); + return createPaginatedResult(response, HelixUserRelation, this._client); + } + /** + * Creates a paginator for VIPs in a channel. + * + * @param broadcaster The owner of the channel to get VIPs for. + */ + getVipsPaginated(broadcaster) { + return new HelixPaginatedRequest({ + url: "channels/vips", + userId: extractUserId(broadcaster), + scopes: ["channel:read:vips", "channel:manage:vips"], + query: createBroadcasterQuery(broadcaster) + }, this._client, (data2) => new HelixUserRelation(data2, this._client)); + } + /** + * Checks the VIP status of a list of users in a channel. + * + * @param broadcaster The owner of the channel to check VIP status in. + * @param users The users to check. + */ + async checkVipForUsers(broadcaster, users) { + const response = await this._client.callApi({ + type: "helix", + url: "channels/vips", + userId: extractUserId(broadcaster), + scopes: ["channel:read:vips", "channel:manage:vips"], + query: createChannelUsersCheckQuery(broadcaster, users) + }); + return response.data.map((data2) => new HelixUserRelation(data2, this._client)); + } + /** + * Checks the VIP status of a user in a channel. + * + * @param broadcaster The owner of the channel to check VIP status in. + * @param user The user to check. + */ + async checkVipForUser(broadcaster, user) { + const userId = extractUserId(user); + const result = await this.checkVipForUsers(broadcaster, [userId]); + return result.some((rel) => rel.id === userId); + } + /** + * Adds a VIP to the broadcaster’s chat room. + * + * @param broadcaster The broadcaster that’s granting VIP status to the user. This ID must match the user ID in the access token. + * @param user The user to add as a VIP in the broadcaster’s chat room. + */ + async addVip(broadcaster, user) { + await this._client.callApi({ + type: "helix", + url: "channels/vips", + method: "POST", + userId: extractUserId(broadcaster), + scopes: ["channel:manage:vips"], + query: createChannelVipUpdateQuery(broadcaster, user) + }); + } + /** + * Removes a VIP from the broadcaster’s chat room. + * + * @param broadcaster The broadcaster that’s removing VIP status from the user. This ID must match the user ID in the access token. + * @param user The user to remove as a VIP from the broadcaster’s chat room. + */ + async removeVip(broadcaster, user) { + await this._client.callApi({ + type: "helix", + url: "channels/vips", + method: "DELETE", + userId: extractUserId(broadcaster), + scopes: ["channel:manage:vips"], + query: createChannelVipUpdateQuery(broadcaster, user) + }); + } + /** + * Gets the total number of users that follow the specified broadcaster. + * + * @param broadcaster The broadcaster you want to get the number of followers of. + */ + async getChannelFollowerCount(broadcaster) { + const result = await this._client.callApi({ + type: "helix", + url: "channels/followers", + method: "GET", + userId: extractUserId(broadcaster), + query: { + ...createChannelFollowerQuery(broadcaster), + ...createPaginationQuery({ limit: 1 }) + } + }); + return result.total; + } + /** + * Gets a list of users that follow the specified broadcaster. + * You can also use this endpoint to see whether a specific user follows the broadcaster. + * + * This uses the token of the broadcaster by default. + * If you want to execute this in the context of another user (who has to be moderator of the channel) + * you can do so using [user context overrides](/docs/auth/concepts/context-switching). + * + * @param broadcaster The broadcaster you want to get a list of followers for. + * @param user An optional user to determine if this user follows the broadcaster. + * If specified, the response contains this user if they follow the broadcaster. + * If not specified, the response contains all users that follow the broadcaster. + * @param pagination + * + * @expandParams + */ + async getChannelFollowers(broadcaster, user, pagination) { + const result = await this._client.callApi({ + type: "helix", + url: "channels/followers", + method: "GET", + userId: extractUserId(broadcaster), + canOverrideScopedUserContext: true, + scopes: ["moderator:read:followers"], + query: { + ...createChannelFollowerQuery(broadcaster, user), + ...createPaginationQuery(pagination) + } + }); + return createPaginatedResultWithTotal(result, HelixChannelFollower, this._client); + } + /** + * Creates a paginator for users that follow the specified broadcaster. + * + * This uses the token of the broadcaster by default. + * If you want to execute this in the context of another user (who has to be moderator of the channel) + * you can do so using [user context overrides](/docs/auth/concepts/context-switching). + * + * @param broadcaster The broadcaster for whom you are getting a list of followers. + * + * @expandParams + */ + getChannelFollowersPaginated(broadcaster) { + return new HelixPaginatedRequestWithTotal({ + url: "channels/followers", + method: "GET", + userId: extractUserId(broadcaster), + canOverrideScopedUserContext: true, + scopes: ["moderator:read:followers"], + query: createChannelFollowerQuery(broadcaster) + }, this._client, (data2) => new HelixChannelFollower(data2, this._client)); + } + /** + * Gets a list of broadcasters that the specified user follows. + * You can also use this endpoint to see whether the user follows a specific broadcaster. + * + * @param user The user that's getting a list of followed channels. + * This ID must match the user ID in the access token. + * @param broadcaster An optional broadcaster to determine if the user follows this broadcaster. + * If specified, the response contains this broadcaster if the user follows them. + * If not specified, the response contains all broadcasters that the user follows. + * @param pagination + * @returns + */ + async getFollowedChannels(user, broadcaster, pagination) { + const result = await this._client.callApi({ + type: "helix", + url: "channels/followed", + method: "GET", + userId: extractUserId(user), + scopes: ["user:read:follows"], + query: { + ...createFollowedChannelQuery(user, broadcaster), + ...createPaginationQuery(pagination) + } + }); + return createPaginatedResultWithTotal(result, HelixFollowedChannel, this._client); + } + /** + * Creates a paginator for broadcasters that the specified user follows. + * + * @param user The user that's getting a list of followed channels. + * The token of this user will be used to get the list of followed channels. + * @param broadcaster An optional broadcaster to determine if the user follows this broadcaster. + * If specified, the response contains this broadcaster if the user follows them. + * If not specified, the response contains all broadcasters that the user follows. + * @returns + */ + getFollowedChannelsPaginated(user, broadcaster) { + return new HelixPaginatedRequestWithTotal({ + url: "channels/followed", + method: "GET", + userId: extractUserId(user), + scopes: ["user:read:follows"], + query: createFollowedChannelQuery(user, broadcaster) + }, this._client, (data2) => new HelixFollowedChannel(data2, this._client)); + } + /** + * Gets information about the broadcaster's ad schedule. + * + * @param broadcaster The broadcaster to get ad schedule information about. + */ + async getAdSchedule(broadcaster) { + const response = await this._client.callApi({ + type: "helix", + url: "channels/ads", + method: "GET", + userId: extractUserId(broadcaster), + scopes: ["channel:read:ads"], + query: createBroadcasterQuery(broadcaster) + }); + return new HelixAdSchedule(response.data[0]); + } + /** + * Snoozes the broadcaster's next ad, if a snooze is available. + * + * @param broadcaster The broadcaster to get ad schedule information about. + */ + async snoozeNextAd(broadcaster) { + const response = await this._client.callApi({ + type: "helix", + url: "channels/ads/schedule/snooze", + method: "POST", + userId: extractUserId(broadcaster), + scopes: ["channel:manage:ads"], + query: createBroadcasterQuery(broadcaster) + }); + return new HelixSnoozeNextAdResult(response.data[0]); + } +}; +__decorate([ + Enumerable(false) +], HelixChannelApi.prototype, "_getChannelByIdBatcher", void 0); +HelixChannelApi = __decorate([ + rtfm("api", "HelixChannelApi") +], HelixChannelApi); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/channelPoints/HelixChannelPointsApi.js +init_modules_watch_stub(); +init_performance2(); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/interfaces/endpoints/channelPoints.external.js +init_modules_watch_stub(); +init_performance2(); +function createCustomRewardsQuery(broadcaster, onlyManageable) { + return { + broadcaster_id: extractUserId(broadcaster), + only_manageable_rewards: onlyManageable?.toString() + }; +} +__name(createCustomRewardsQuery, "createCustomRewardsQuery"); +function createCustomRewardChangeQuery(broadcaster, rewardId) { + return { + broadcaster_id: extractUserId(broadcaster), + id: rewardId + }; +} +__name(createCustomRewardChangeQuery, "createCustomRewardChangeQuery"); +function createCustomRewardBody(data2) { + const result = { + title: data2.title, + cost: data2.cost, + prompt: data2.prompt, + background_color: data2.backgroundColor, + is_enabled: data2.isEnabled, + is_user_input_required: data2.userInputRequired, + should_redemptions_skip_request_queue: data2.autoFulfill + }; + if (data2.maxRedemptionsPerStream !== void 0) { + result.is_max_per_stream_enabled = !!data2.maxRedemptionsPerStream; + result.max_per_stream = data2.maxRedemptionsPerStream ?? 0; + } + if (data2.maxRedemptionsPerUserPerStream !== void 0) { + result.is_max_per_user_per_stream_enabled = !!data2.maxRedemptionsPerUserPerStream; + result.max_per_user_per_stream = data2.maxRedemptionsPerUserPerStream ?? 0; + } + if (data2.globalCooldown !== void 0) { + result.is_global_cooldown_enabled = !!data2.globalCooldown; + result.global_cooldown_seconds = data2.globalCooldown ?? 0; + } + if ("isPaused" in data2) { + result.is_paused = data2.isPaused; + } + return result; +} +__name(createCustomRewardBody, "createCustomRewardBody"); +function createRewardRedemptionsByIdsQuery(broadcaster, rewardId, redemptionIds) { + return { + broadcaster_id: extractUserId(broadcaster), + reward_id: rewardId, + id: redemptionIds + }; +} +__name(createRewardRedemptionsByIdsQuery, "createRewardRedemptionsByIdsQuery"); +function createRedemptionsForBroadcasterQuery(broadcaster, rewardId, status, filter) { + return { + broadcaster_id: extractUserId(broadcaster), + reward_id: rewardId, + status, + sort: filter.newestFirst ? "NEWEST" : "OLDEST" + }; +} +__name(createRedemptionsForBroadcasterQuery, "createRedemptionsForBroadcasterQuery"); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/channelPoints/HelixCustomReward.js +init_modules_watch_stub(); +init_performance2(); +var HelixCustomReward = class HelixCustomReward2 extends DataObject { + static { + __name(this, "HelixCustomReward"); + } + /** @internal */ + _client; + /** @internal */ + constructor(data2, client) { + super(data2); + this._client = client; + } + /** + * The ID of the reward. + */ + get id() { + return this[rawDataSymbol].id; + } + /** + * The ID of the broadcaster the reward belongs to. + */ + get broadcasterId() { + return this[rawDataSymbol].broadcaster_id; + } + /** + * The name of the broadcaster the reward belongs to. + */ + get broadcasterName() { + return this[rawDataSymbol].broadcaster_login; + } + /** + * The display name of the broadcaster the reward belongs to. + */ + get broadcasterDisplayName() { + return this[rawDataSymbol].broadcaster_name; + } + /** + * Gets more information about the reward's broadcaster. + */ + async getBroadcaster() { + return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].broadcaster_id)); + } + /** + * Gets the URL of the image of the reward in the given scale. + * + * @param scale The scale of the image. + */ + getImageUrl(scale) { + const urlProp = `url_${scale}x`; + return this[rawDataSymbol].image?.[urlProp] ?? this[rawDataSymbol].default_image[urlProp]; + } + /** + * The background color of the reward. + */ + get backgroundColor() { + return this[rawDataSymbol].background_color; + } + /** + * Whether the reward is enabled (shown to users). + */ + get isEnabled() { + return this[rawDataSymbol].is_enabled; + } + /** + * The channel points cost of the reward. + */ + get cost() { + return this[rawDataSymbol].cost; + } + /** + * The title of the reward. + */ + get title() { + return this[rawDataSymbol].title; + } + /** + * The prompt shown to users when redeeming the reward. + */ + get prompt() { + return this[rawDataSymbol].prompt; + } + /** + * Whether the reward requires user input to be redeemed. + */ + get userInputRequired() { + return this[rawDataSymbol].is_user_input_required; + } + /** + * The maximum number of redemptions of the reward per stream. `null` means no limit. + */ + get maxRedemptionsPerStream() { + return this[rawDataSymbol].max_per_stream_setting.is_enabled ? this[rawDataSymbol].max_per_stream_setting.max_per_stream : null; + } + /** + * The maximum number of redemptions of the reward per stream for each user. `null` means no limit. + */ + get maxRedemptionsPerUserPerStream() { + return this[rawDataSymbol].max_per_user_per_stream_setting.is_enabled ? this[rawDataSymbol].max_per_user_per_stream_setting.max_per_user_per_stream : null; + } + /** + * The cooldown between two redemptions of the reward, in seconds. `null` means no cooldown. + */ + get globalCooldown() { + return this[rawDataSymbol].global_cooldown_setting.is_enabled ? this[rawDataSymbol].global_cooldown_setting.global_cooldown_seconds : null; + } + /** + * Whether the reward is paused. If true, users can't redeem it. + */ + get isPaused() { + return this[rawDataSymbol].is_paused; + } + /** + * Whether the reward is currently in stock. + */ + get isInStock() { + return this[rawDataSymbol].is_in_stock; + } + /** + * How often the reward was already redeemed this stream. + * + * Only available when the stream is live and `maxRedemptionsPerStream` is set. Otherwise, this is `null`. + */ + get redemptionsThisStream() { + return this[rawDataSymbol].redemptions_redeemed_current_stream; + } + /** + * Whether redemptions should automatically be marked as fulfilled. + */ + get autoFulfill() { + return this[rawDataSymbol].should_redemptions_skip_request_queue; + } + /** + * The time when the cooldown ends. `null` means there is currently no cooldown. + */ + get cooldownExpiryDate() { + return this[rawDataSymbol].cooldown_expires_at ? new Date(this[rawDataSymbol].cooldown_expires_at) : null; + } +}; +__decorate([ + Enumerable(false) +], HelixCustomReward.prototype, "_client", void 0); +HelixCustomReward = __decorate([ + rtfm("api", "HelixCustomReward", "id") +], HelixCustomReward); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/channelPoints/HelixCustomRewardRedemption.js +init_modules_watch_stub(); +init_performance2(); +var HelixCustomRewardRedemption = class HelixCustomRewardRedemption2 extends DataObject { + static { + __name(this, "HelixCustomRewardRedemption"); + } + /** @internal */ + _client; + /** @internal */ + constructor(data2, client) { + super(data2); + this._client = client; + } + /** + * The ID of the redemption. + */ + get id() { + return this[rawDataSymbol].id; + } + /** + * The ID of the broadcaster where the reward was redeemed. + */ + get broadcasterId() { + return this[rawDataSymbol].broadcaster_id; + } + /** + * The name of the broadcaster where the reward was redeemed. + */ + get broadcasterName() { + return this[rawDataSymbol].broadcaster_login; + } + /** + * The display name of the broadcaster where the reward was redeemed. + */ + get broadcasterDisplayName() { + return this[rawDataSymbol].broadcaster_name; + } + /** + * Gets more information about the broadcaster where the reward was redeemed. + */ + async getBroadcaster() { + return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].broadcaster_id)); + } + /** + * The ID of the user that redeemed the reward. + */ + get userId() { + return this[rawDataSymbol].user_id; + } + /** + * The name of the user that redeemed the reward. + */ + get userName() { + return this[rawDataSymbol].user_login; + } + /** + * The display name of the user that redeemed the reward. + */ + get userDisplayName() { + return this[rawDataSymbol].user_name; + } + /** + * Gets more information about the user that redeemed the reward. + */ + async getUser() { + return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].user_id)); + } + /** + * The text the user wrote when redeeming the reward. + */ + get userInput() { + return this[rawDataSymbol].user_input; + } + /** + * Whether the redemption was fulfilled. + */ + get isFulfilled() { + return this[rawDataSymbol].status === "FULFILLED"; + } + /** + * Whether the redemption was canceled. + */ + get isCanceled() { + return this[rawDataSymbol].status === "CANCELED"; + } + /** + * The date and time when the reward was redeemed. + */ + get redemptionDate() { + return new Date(this[rawDataSymbol].redeemed_at); + } + /** + * The ID of the reward that was redeemed. + */ + get rewardId() { + return this[rawDataSymbol].reward.id; + } + /** + * The title of the reward that was redeemed. + */ + get rewardTitle() { + return this[rawDataSymbol].reward.title; + } + /** + * The prompt of the reward that was redeemed. + */ + get rewardPrompt() { + return this[rawDataSymbol].reward.prompt; + } + /** + * The cost of the reward that was redeemed. + */ + get rewardCost() { + return this[rawDataSymbol].reward.cost; + } + /** + * Gets more information about the reward that was redeemed. + */ + async getReward() { + return checkRelationAssertion(await this._client.channelPoints.getCustomRewardById(this[rawDataSymbol].broadcaster_id, this[rawDataSymbol].reward.id)); + } + /** + * Updates the redemption's status. + * + * @param newStatus The status the redemption should have. + */ + async updateStatus(newStatus) { + const result = await this._client.channelPoints.updateRedemptionStatusByIds(this[rawDataSymbol].broadcaster_id, this[rawDataSymbol].reward.id, [this[rawDataSymbol].id], newStatus); + return result[0]; + } +}; +__decorate([ + Enumerable(false) +], HelixCustomRewardRedemption.prototype, "_client", void 0); +HelixCustomRewardRedemption = __decorate([ + rtfm("api", "HelixCustomRewardRedemption", "id") +], HelixCustomRewardRedemption); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/channelPoints/HelixChannelPointsApi.js +var HelixChannelPointsApi = class HelixChannelPointsApi2 extends BaseApi { + static { + __name(this, "HelixChannelPointsApi"); + } + /** + * Gets all custom rewards for the given broadcaster. + * + * @param broadcaster The broadcaster to get the rewards for. + * @param onlyManageable Whether to only get rewards that can be managed by the API. + */ + async getCustomRewards(broadcaster, onlyManageable) { + const result = await this._client.callApi({ + type: "helix", + url: "channel_points/custom_rewards", + userId: extractUserId(broadcaster), + scopes: ["channel:read:redemptions", "channel:manage:redemptions"], + query: createCustomRewardsQuery(broadcaster, onlyManageable) + }); + return result.data.map((data2) => new HelixCustomReward(data2, this._client)); + } + /** + * Gets custom rewards by IDs. + * + * @param broadcaster The broadcaster to get the rewards for. + * @param rewardIds The IDs of the rewards. + */ + async getCustomRewardsByIds(broadcaster, rewardIds) { + if (!rewardIds.length) { + return []; + } + const result = await this._client.callApi({ + type: "helix", + url: "channel_points/custom_rewards", + userId: extractUserId(broadcaster), + scopes: ["channel:read:redemptions", "channel:manage:redemptions"], + query: createGetByIdsQuery(broadcaster, rewardIds) + }); + return result.data.map((data2) => new HelixCustomReward(data2, this._client)); + } + /** + * Gets a custom reward by ID. + * + * @param broadcaster The broadcaster to get the reward for. + * @param rewardId The ID of the reward. + */ + async getCustomRewardById(broadcaster, rewardId) { + const rewards = await this.getCustomRewardsByIds(broadcaster, [rewardId]); + return rewards.length ? rewards[0] : null; + } + /** + * Creates a new custom reward. + * + * @param broadcaster The broadcaster to create the reward for. + * @param data The reward data. + * + * @expandParams + */ + async createCustomReward(broadcaster, data2) { + const result = await this._client.callApi({ + type: "helix", + url: "channel_points/custom_rewards", + method: "POST", + userId: extractUserId(broadcaster), + scopes: ["channel:manage:redemptions"], + query: createBroadcasterQuery(broadcaster), + jsonBody: createCustomRewardBody(data2) + }); + return new HelixCustomReward(result.data[0], this._client); + } + /** + * Updates a custom reward. + * + * @param broadcaster The broadcaster to update the reward for. + * @param rewardId The ID of the reward. + * @param data The reward data. + */ + async updateCustomReward(broadcaster, rewardId, data2) { + const result = await this._client.callApi({ + type: "helix", + url: "channel_points/custom_rewards", + method: "PATCH", + userId: extractUserId(broadcaster), + scopes: ["channel:manage:redemptions"], + query: createCustomRewardChangeQuery(broadcaster, rewardId), + jsonBody: createCustomRewardBody(data2) + }); + return new HelixCustomReward(result.data[0], this._client); + } + /** + * Deletes a custom reward. + * + * @param broadcaster The broadcaster to delete the reward for. + * @param rewardId The ID of the reward. + */ + async deleteCustomReward(broadcaster, rewardId) { + await this._client.callApi({ + type: "helix", + url: "channel_points/custom_rewards", + method: "DELETE", + userId: extractUserId(broadcaster), + scopes: ["channel:manage:redemptions"], + query: createCustomRewardChangeQuery(broadcaster, rewardId) + }); + } + /** + * Gets custom reward redemptions by IDs. + * + * @param broadcaster The broadcaster to get the redemptions for. + * @param rewardId The ID of the reward. + * @param redemptionIds The IDs of the redemptions. + */ + async getRedemptionsByIds(broadcaster, rewardId, redemptionIds) { + if (!redemptionIds.length) { + return []; + } + const result = await this._client.callApi({ + type: "helix", + url: "channel_points/custom_rewards/redemptions", + userId: extractUserId(broadcaster), + scopes: ["channel:read:redemptions", "channel:manage:redemptions"], + query: createRewardRedemptionsByIdsQuery(broadcaster, rewardId, redemptionIds) + }); + return result.data.map((data2) => new HelixCustomRewardRedemption(data2, this._client)); + } + /** + * Gets a custom reward redemption by ID. + * + * @param broadcaster The broadcaster to get the redemption for. + * @param rewardId The ID of the reward. + * @param redemptionId The ID of the redemption. + */ + async getRedemptionById(broadcaster, rewardId, redemptionId) { + const redemptions = await this.getRedemptionsByIds(broadcaster, rewardId, [redemptionId]); + return redemptions.length ? redemptions[0] : null; + } + /** + * Gets custom reward redemptions for the given broadcaster. + * + * @param broadcaster The broadcaster to get the redemptions for. + * @param rewardId The ID of the reward. + * @param status The status of the redemptions to get. + * @param filter + * + * @expandParams + */ + async getRedemptionsForBroadcaster(broadcaster, rewardId, status, filter) { + const result = await this._client.callApi({ + type: "helix", + url: "channel_points/custom_rewards/redemptions", + userId: extractUserId(broadcaster), + scopes: ["channel:read:redemptions", "channel:manage:redemptions"], + query: { + ...createRedemptionsForBroadcasterQuery(broadcaster, rewardId, status, filter), + ...createPaginationQuery(filter) + } + }); + return createPaginatedResult(result, HelixCustomRewardRedemption, this._client); + } + /** + * Creates a paginator for custom reward redemptions for the given broadcaster. + * + * @param broadcaster The broadcaster to get the redemptions for. + * @param rewardId The ID of the reward. + * @param status The status of the redemptions to get. + * @param filter + * + * @expandParams + */ + getRedemptionsForBroadcasterPaginated(broadcaster, rewardId, status, filter) { + return new HelixPaginatedRequest({ + url: "channel_points/custom_rewards/redemptions", + userId: extractUserId(broadcaster), + scopes: ["channel:read:redemptions", "channel:manage:redemptions"], + query: createRedemptionsForBroadcasterQuery(broadcaster, rewardId, status, filter) + }, this._client, (data2) => new HelixCustomRewardRedemption(data2, this._client), 50); + } + /** + * Updates the status of the given redemptions by IDs. + * + * @param broadcaster The broadcaster to update the redemptions for. + * @param rewardId The ID of the reward. + * @param redemptionIds The IDs of the redemptions to update. + * @param status The status to set for the redemptions. + */ + async updateRedemptionStatusByIds(broadcaster, rewardId, redemptionIds, status) { + if (!redemptionIds.length) { + return []; + } + const result = await this._client.callApi({ + type: "helix", + url: "channel_points/custom_rewards/redemptions", + method: "PATCH", + userId: extractUserId(broadcaster), + scopes: ["channel:manage:redemptions"], + query: createRewardRedemptionsByIdsQuery(broadcaster, rewardId, redemptionIds), + jsonBody: { + status + } + }); + return result.data.map((data2) => new HelixCustomRewardRedemption(data2, this._client)); + } +}; +HelixChannelPointsApi = __decorate([ + rtfm("api", "HelixChannelPointsApi") +], HelixChannelPointsApi); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/charity/HelixCharityApi.js +init_modules_watch_stub(); +init_performance2(); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/charity/HelixCharityCampaign.js +init_modules_watch_stub(); +init_performance2(); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/charity/HelixCharityCampaignAmount.js +init_modules_watch_stub(); +init_performance2(); +var HelixCharityCampaignAmount = class HelixCharityCampaignAmount2 extends DataObject { + static { + __name(this, "HelixCharityCampaignAmount"); + } + /** + * The monetary amount. The amount is specified in the currency’s minor unit. + * For example, the minor units for USD is cents, so if the amount is $5.50 USD, `value` is set to 550. + */ + get value() { + return this[rawDataSymbol].value; + } + /** + * The number of decimal places used by the currency. For example, USD uses two decimal places. + * Use this number to translate `value` from minor units to major units by using the formula: + * + * `value / 10^decimalPlaces` + */ + get decimalPlaces() { + return this[rawDataSymbol].decimal_places; + } + /** + * The localized monetary amount based on the value and the decimal places of the currency. + * For example, the minor units for USD is cents which uses two decimal places, so if `value` is 550, `localizedValue` is set to 5.50. + */ + get localizedValue() { + return this.value / 10 ** this.decimalPlaces; + } + /** + * The ISO-4217 three-letter currency code that identifies the type of currency in `value`. + */ + get currency() { + return this[rawDataSymbol].currency; + } +}; +HelixCharityCampaignAmount = __decorate([ + rtfm("api", "HelixCharityCampaignAmount") +], HelixCharityCampaignAmount); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/charity/HelixCharityCampaign.js +var HelixCharityCampaign = class HelixCharityCampaign2 extends DataObject { + static { + __name(this, "HelixCharityCampaign"); + } + /** @internal */ + _client; + /** @internal */ + constructor(data2, client) { + super(data2); + this._client = client; + } + /** + * An ID that identifies the charity campaign. + */ + get id() { + return this[rawDataSymbol].id; + } + /** + * The ID of the broadcaster. + */ + get broadcasterId() { + return this[rawDataSymbol].broadcaster_id; + } + /** + * The name of the broadcaster. + */ + get broadcasterName() { + return this[rawDataSymbol].broadcaster_login; + } + /** + * The display name of the broadcaster. + */ + get broadcasterDisplayName() { + return this[rawDataSymbol].broadcaster_name; + } + /** + * Gets more information about the broadcaster. + */ + async getBroadcaster() { + return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].broadcaster_id)); + } + /** + * The name of the charity. + */ + get charityName() { + return this[rawDataSymbol].charity_name; + } + /** + * A description of the charity. + */ + get charityDescription() { + return this[rawDataSymbol].charity_description; + } + /** + * A URL to an image of the charity's logo. The image’s type is PNG and its size is 100px X 100px. + */ + get charityLogo() { + return this[rawDataSymbol].charity_logo; + } + /** + * A URL to the charity’s website. + */ + get charityWebsite() { + return this[rawDataSymbol].charity_website; + } + /** + * An object that contains the current amount of donations that the campaign has received. + */ + get currentAmount() { + return new HelixCharityCampaignAmount(this[rawDataSymbol].current_amount); + } + /** + * An object that contains the campaign’s target fundraising goal. + */ + get targetAmount() { + return new HelixCharityCampaignAmount(this[rawDataSymbol].target_amount); + } +}; +__decorate([ + Enumerable(false) +], HelixCharityCampaign.prototype, "_client", void 0); +HelixCharityCampaign = __decorate([ + rtfm("api", "HelixCharityCampaign", "id") +], HelixCharityCampaign); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/charity/HelixCharityCampaignDonation.js +init_modules_watch_stub(); +init_performance2(); +var HelixCharityCampaignDonation = class HelixCharityCampaignDonation2 extends DataObject { + static { + __name(this, "HelixCharityCampaignDonation"); + } + /** @internal */ + _client; + /** @internal */ + constructor(data2, client) { + super(data2); + this._client = client; + } + /** + * An ID that identifies the charity campaign. + */ + get campaignId() { + return this[rawDataSymbol].campaign_id; + } + /** + * The ID of the donating user. + */ + get donorId() { + return this[rawDataSymbol].user_id; + } + /** + * The name of the donating user. + */ + get donorName() { + return this[rawDataSymbol].user_login; + } + /** + * The display name of the donating user. + */ + get donorDisplayName() { + return this[rawDataSymbol].user_name; + } + /** + * Gets more information about the donating user. + */ + async getDonor() { + return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].user_id)); + } + /** + * An object that contains the amount of money that the user donated. + */ + get amount() { + return new HelixCharityCampaignAmount(this[rawDataSymbol].amount); + } +}; +__decorate([ + Enumerable(false) +], HelixCharityCampaignDonation.prototype, "_client", void 0); +HelixCharityCampaignDonation = __decorate([ + rtfm("api", "HelixCharityCampaignDonation") +], HelixCharityCampaignDonation); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/charity/HelixCharityApi.js +var HelixCharityApi = class HelixCharityApi2 extends BaseApi { + static { + __name(this, "HelixCharityApi"); + } + /** + * Gets information about the charity campaign that a broadcaster is running. + * Returns null if the specified broadcaster has no active charity campaign. + * + * @param broadcaster The broadcaster to get charity campaign information about. + */ + async getCharityCampaign(broadcaster) { + const response = await this._client.callApi({ + type: "helix", + url: "charity/campaigns", + method: "GET", + userId: extractUserId(broadcaster), + scopes: ["channel:read:charity"], + query: createBroadcasterQuery(broadcaster) + }); + return new HelixCharityCampaign(response.data[0], this._client); + } + /** + * Gets the list of donations that users have made to the broadcaster’s active charity campaign. + * + * @param broadcaster The broadcaster to get charity campaign donation information about. + * @param pagination + * + * @expandParams + */ + async getCharityCampaignDonations(broadcaster, pagination) { + const response = await this._client.callApi({ + type: "helix", + url: "charity/donations", + userId: extractUserId(broadcaster), + scopes: ["channel:read:charity"], + query: { + ...createBroadcasterQuery(broadcaster), + ...createPaginationQuery(pagination) + } + }); + return createPaginatedResult(response, HelixCharityCampaignDonation, this._client); + } +}; +HelixCharityApi = __decorate([ + rtfm("api", "HelixCharityApi") +], HelixCharityApi); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/chat/HelixChatApi.js +init_modules_watch_stub(); +init_performance2(); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/errors/ChatMessageDroppedError.js +init_modules_watch_stub(); +init_performance2(); +var ChatMessageDroppedError = class extends CustomError2 { + static { + __name(this, "ChatMessageDroppedError"); + } + _code; + constructor(broadcasterId, message, code) { + super(`Chat message to channel ${broadcasterId} dropped: ${message ?? "unknown reason"}`); + this._code = code; + } + get code() { + return this._code; + } +}; + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/interfaces/endpoints/chat.external.js +init_modules_watch_stub(); +init_performance2(); +function createChatSettingsUpdateBody(settings) { + return { + slow_mode: settings.slowModeEnabled, + slow_mode_wait_time: settings.slowModeDelay, + follower_mode: settings.followerOnlyModeEnabled, + follower_mode_duration: settings.followerOnlyModeDelay, + subscriber_mode: settings.subscriberOnlyModeEnabled, + emote_mode: settings.emoteOnlyModeEnabled, + unique_chat_mode: settings.uniqueChatModeEnabled, + non_moderator_chat_delay: settings.nonModeratorChatDelayEnabled, + non_moderator_chat_delay_duration: settings.nonModeratorChatDelay + }; +} +__name(createChatSettingsUpdateBody, "createChatSettingsUpdateBody"); +function createChatColorUpdateQuery(user, color) { + return { + user_id: extractUserId(user), + color + }; +} +__name(createChatColorUpdateQuery, "createChatColorUpdateQuery"); +function createShoutoutQuery(from, to, moderatorId) { + return { + from_broadcaster_id: extractUserId(from), + to_broadcaster_id: extractUserId(to), + moderator_id: moderatorId + }; +} +__name(createShoutoutQuery, "createShoutoutQuery"); +function createSendChatMessageQuery(broadcaster, sender) { + return { + broadcaster_id: broadcaster, + sender_id: sender + }; +} +__name(createSendChatMessageQuery, "createSendChatMessageQuery"); +function createSendChatMessageBody(message, params) { + return { + message, + reply_parent_message_id: params?.replyParentMessageId + }; +} +__name(createSendChatMessageBody, "createSendChatMessageBody"); +function createSendChatMessageAsAppBody(message, params) { + return { + message, + reply_parent_message_id: params?.replyParentMessageId, + for_source_only: params?.forSourceOnly + }; +} +__name(createSendChatMessageAsAppBody, "createSendChatMessageAsAppBody"); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/interfaces/endpoints/shared-chat-session.external.js +init_modules_watch_stub(); +init_performance2(); +function createSharedChatSessionQuery(broadcaster) { + return { + broadcaster_id: extractUserId(broadcaster) + }; +} +__name(createSharedChatSessionQuery, "createSharedChatSessionQuery"); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/chat/HelixChannelEmote.js +init_modules_watch_stub(); +init_performance2(); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/chat/HelixEmote.js +init_modules_watch_stub(); +init_performance2(); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/chat/HelixEmoteBase.js +init_modules_watch_stub(); +init_performance2(); +var HelixEmoteBase = class extends DataObject { + static { + __name(this, "HelixEmoteBase"); + } + /** + * The ID of the emote. + */ + get id() { + return this[rawDataSymbol].id; + } + /** + * The name of the emote. + */ + get name() { + return this[rawDataSymbol].name; + } + /** + * The formats that the emote is available in. + */ + get formats() { + return this[rawDataSymbol].format; + } + /** + * The scales that the emote is available in. + */ + get scales() { + return this[rawDataSymbol].scale; + } + /** + * The theme modes that the emote is available in. + */ + get themeModes() { + return this[rawDataSymbol].theme_mode; + } + /** + * Gets the URL of the emote image in static format at the given scale and theme mode, or null if a static emote image at that scale/theme mode doesn't exist. + * + * @param scale The scale of the image. + * @param themeMode The theme mode of the image, either `light` or `dark`. + */ + getStaticImageUrl(scale = "1.0", themeMode = "light") { + if (this[rawDataSymbol].format.includes("static") && this[rawDataSymbol].scale.includes(scale)) { + return this.getFormattedImageUrl(scale, "static", themeMode); + } + return null; + } + /** + * Gets the URL of the emote image in animated format at the given scale and theme mode, or null if an animated emote image at that scale/theme mode doesn't exist. + * + * @param scale The scale of the image. + * @param themeMode The theme mode of the image, either `light` or `dark`. + */ + getAnimatedImageUrl(scale = "1.0", themeMode = "light") { + if (this[rawDataSymbol].format.includes("animated") && this[rawDataSymbol].scale.includes(scale)) { + return this.getFormattedImageUrl(scale, "animated", themeMode); + } + return null; + } + /** + * Gets the URL of the emote image in the given scale, format, and theme mode. + * + * @param scale The scale of the image, either `1.0` (small), `2.0` (medium), or `3.0` (large). + * @param format The format of the image, either `static` or `animated`. + * @param themeMode The theme mode of the image, either `light` or `dark`. + */ + getFormattedImageUrl(scale = "1.0", format = "static", themeMode = "light") { + return `https://static-cdn.jtvnw.net/emoticons/v2/${this[rawDataSymbol].id}/${format}/${themeMode}/${scale}`; + } +}; + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/chat/HelixEmote.js +var HelixEmote = class HelixEmote2 extends HelixEmoteBase { + static { + __name(this, "HelixEmote"); + } + /** + * Gets the URL of the emote image in the given scale. + * + * @param scale The scale of the image. + */ + getImageUrl(scale) { + return this[rawDataSymbol].images[`url_${scale}x`]; + } +}; +HelixEmote = __decorate([ + rtfm("api", "HelixEmote", "id") +], HelixEmote); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/chat/HelixChannelEmote.js +var HelixChannelEmote = class HelixChannelEmote2 extends HelixEmote { + static { + __name(this, "HelixChannelEmote"); + } + /** @internal */ + _client; + constructor(data2, client) { + super(data2); + this._client = client; + } + /** + * The subscription tier necessary to unlock the emote, or null if the emote is not a subscription emote. + */ + get tier() { + return this[rawDataSymbol].tier || null; + } + /** + * The type of the emote. + * + * There are many types of emotes that Twitch seems to arbitrarily assign. Do not rely on this value. + */ + get type() { + return this[rawDataSymbol].emote_type; + } + /** + * The ID of the emote set the emote is part of. + */ + get emoteSetId() { + return this[rawDataSymbol].emote_set_id; + } + /** + * Gets all emotes from the emote's set. + */ + async getAllEmotesFromSet() { + return await this._client.chat.getEmotesFromSets([this[rawDataSymbol].emote_set_id]); + } +}; +__decorate([ + Enumerable(false) +], HelixChannelEmote.prototype, "_client", void 0); +HelixChannelEmote = __decorate([ + rtfm("api", "HelixChannelEmote", "id") +], HelixChannelEmote); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/chat/HelixChatBadgeSet.js +init_modules_watch_stub(); +init_performance2(); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/chat/HelixChatBadgeVersion.js +init_modules_watch_stub(); +init_performance2(); +var HelixChatBadgeVersion = class HelixChatBadgeVersion2 extends DataObject { + static { + __name(this, "HelixChatBadgeVersion"); + } + /** + * The badge version ID. + */ + get id() { + return this[rawDataSymbol].id; + } + /** + * Gets an image URL for the given scale. + * + * @param scale The scale of the badge image. + */ + getImageUrl(scale) { + return this[rawDataSymbol][`image_url_${scale}x`]; + } + /** + * The title of the badge. + */ + get title() { + return this[rawDataSymbol].title; + } + /** + * The description of the badge. + */ + get description() { + return this[rawDataSymbol].description; + } + /** + * The action to take when clicking on the badge. Set to `null` if no action is specified. + */ + get clickAction() { + return this[rawDataSymbol].click_action; + } + /** + * The URL to navigate to when clicking on the badge. Set to `null` if no URL is specified. + */ + get clickUrl() { + return this[rawDataSymbol].click_url; + } +}; +HelixChatBadgeVersion = __decorate([ + rtfm("api", "HelixChatBadgeVersion", "id") +], HelixChatBadgeVersion); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/chat/HelixChatBadgeSet.js +var HelixChatBadgeSet = class HelixChatBadgeSet2 extends DataObject { + static { + __name(this, "HelixChatBadgeSet"); + } + /** + * The badge set ID. + */ + get id() { + return this[rawDataSymbol].set_id; + } + /** + * All versions of the badge. + */ + get versions() { + return this[rawDataSymbol].versions.map((data2) => new HelixChatBadgeVersion(data2)); + } + /** + * Gets a specific version of the badge. + * + * @param versionId The ID of the version. + */ + getVersion(versionId) { + return this.versions.find((v) => v.id === versionId) ?? null; + } +}; +__decorate([ + CachedGetter() +], HelixChatBadgeSet.prototype, "versions", null); +HelixChatBadgeSet = __decorate([ + Cacheable, + rtfm("api", "HelixChatBadgeSet", "id") +], HelixChatBadgeSet); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/chat/HelixChatChatter.js +init_modules_watch_stub(); +init_performance2(); +var HelixChatChatter = class HelixChatChatter2 extends DataObject { + static { + __name(this, "HelixChatChatter"); + } + /** @internal */ + _client; + /** @internal */ + constructor(data2, client) { + super(data2); + this._client = client; + } + /** + * The ID of the user. + */ + get userId() { + return this[rawDataSymbol].user_id; + } + /** + * The name of the user. + */ + get userName() { + return this[rawDataSymbol].user_login; + } + /** + * The display name of the user. + */ + get userDisplayName() { + return this[rawDataSymbol].user_name; + } + /** + * Gets more information about the user. + */ + async getUser() { + return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].user_id)); + } +}; +__decorate([ + Enumerable(false) +], HelixChatChatter.prototype, "_client", void 0); +HelixChatChatter = __decorate([ + rtfm("api", "HelixChatChatter") +], HelixChatChatter); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/chat/HelixChatSettings.js +init_modules_watch_stub(); +init_performance2(); +var HelixChatSettings = class HelixChatSettings2 extends DataObject { + static { + __name(this, "HelixChatSettings"); + } + /** + * The ID of the broadcaster. + */ + get broadcasterId() { + return this[rawDataSymbol].broadcaster_id; + } + /** + * Whether slow mode is enabled. + */ + get slowModeEnabled() { + return this[rawDataSymbol].slow_mode; + } + /** + * The time to wait between messages in slow mode, in seconds. + * + * Is `null` if slow mode is not enabled. + */ + get slowModeDelay() { + return this[rawDataSymbol].slow_mode_wait_time; + } + /** + * Whether follower only mode is enabled. + */ + get followerOnlyModeEnabled() { + return this[rawDataSymbol].follower_mode; + } + /** + * The time after which users are able to send messages after following, in minutes. + * + * Is `null` if follower only mode is not enabled, + * but may also be `0` if you can send messages immediately after following. + */ + get followerOnlyModeDelay() { + return this[rawDataSymbol].follower_mode_duration; + } + /** + * Whether subscriber only mode is enabled. + */ + get subscriberOnlyModeEnabled() { + return this[rawDataSymbol].subscriber_mode; + } + /** + * Whether emote only mode is enabled. + */ + get emoteOnlyModeEnabled() { + return this[rawDataSymbol].emote_mode; + } + /** + * Whether unique chat mode is enabled. + */ + get uniqueChatModeEnabled() { + return this[rawDataSymbol].unique_chat_mode; + } +}; +HelixChatSettings = __decorate([ + rtfm("api", "HelixChatSettings", "broadcasterId") +], HelixChatSettings); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/chat/HelixEmoteFromSet.js +init_modules_watch_stub(); +init_performance2(); +var HelixEmoteFromSet = class HelixEmoteFromSet2 extends HelixEmote { + static { + __name(this, "HelixEmoteFromSet"); + } + /** @internal */ + _client; + constructor(data2, client) { + super(data2); + this._client = client; + } + /** + * The type of the emote. + * + * Known values are: `subscriptions`, `bitstier`, `follower`, `rewards`, `globals`, `smilies`, `prime`, `limitedtime`. + * + * This list may be non-exhaustive. + */ + get type() { + return this[rawDataSymbol].emote_type; + } + /** + * The ID of the emote set the emote is part of. + */ + get emoteSetId() { + return this[rawDataSymbol].emote_set_id; + } + /** + * The ID of the user that owns the emote, or null if the emote is not owned by a user. + */ + get ownerId() { + switch (this[rawDataSymbol].owner_id) { + case "0": + case "twitch": { + return null; + } + default: { + return this[rawDataSymbol].owner_id; + } + } + } + /** + * Gets more information about the user that owns the emote, or null if the emote is not owned by a user. + */ + async getOwner() { + switch (this[rawDataSymbol].owner_id) { + case "0": + case "twitch": { + return null; + } + default: { + return await this._client.users.getUserById(this[rawDataSymbol].owner_id); + } + } + } +}; +__decorate([ + Enumerable(false) +], HelixEmoteFromSet.prototype, "_client", void 0); +HelixEmoteFromSet = __decorate([ + rtfm("api", "HelixEmoteFromSet", "id") +], HelixEmoteFromSet); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/chat/HelixPrivilegedChatSettings.js +init_modules_watch_stub(); +init_performance2(); +var HelixPrivilegedChatSettings = class HelixPrivilegedChatSettings2 extends HelixChatSettings { + static { + __name(this, "HelixPrivilegedChatSettings"); + } + /** + * Whether non-moderator messages are delayed. + */ + get nonModeratorChatDelayEnabled() { + return this[rawDataSymbol].non_moderator_chat_delay; + } + /** + * The delay of non-moderator messages, in seconds. + * + * Is `null` if non-moderator message delay is disabled. + */ + get nonModeratorChatDelay() { + return this[rawDataSymbol].non_moderator_chat_delay_duration; + } +}; +HelixPrivilegedChatSettings = __decorate([ + rtfm("api", "HelixPrivilegedChatSettings", "broadcasterId") +], HelixPrivilegedChatSettings); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/chat/HelixSentChatMessage.js +init_modules_watch_stub(); +init_performance2(); +var HelixSentChatMessage = class HelixSentChatMessage2 extends DataObject { + static { + __name(this, "HelixSentChatMessage"); + } + /** + * The message ID of the sent message. + */ + get id() { + return this[rawDataSymbol].message_id; + } + /** + * If the message passed all checks and was sent. + */ + get isSent() { + return this[rawDataSymbol].is_sent; + } + /** + * The reason code for why the chat message was dropped, if dropped. + */ + get dropReasonCode() { + return this[rawDataSymbol].drop_reason?.code; + } + /** + * The reason message for why the chat message was dropped, if dropped. + */ + get dropReasonMessage() { + return this[rawDataSymbol].drop_reason?.message; + } +}; +HelixSentChatMessage = __decorate([ + rtfm("api", "HelixSentChatMessage", "id") +], HelixSentChatMessage); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/chat/HelixSharedChatSession.js +init_modules_watch_stub(); +init_performance2(); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/chat/HelixSharedChatSessionParticipant.js +init_modules_watch_stub(); +init_performance2(); +var HelixSharedChatSessionParticipant = class HelixSharedChatSessionParticipant2 extends DataObject { + static { + __name(this, "HelixSharedChatSessionParticipant"); + } + /** @internal */ + _client; + /** @internal */ + constructor(data2, client) { + super(data2); + this._client = client; + } + /** + * The ID of the participant broadcaster. + */ + get broadcasterId() { + return this[rawDataSymbol].broadcaster_id; + } + /** + * Gets information about the participant broadcaster. + */ + async getBroadcaster() { + return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].broadcaster_id)); + } +}; +__decorate([ + Enumerable(false) +], HelixSharedChatSessionParticipant.prototype, "_client", void 0); +HelixSharedChatSessionParticipant = __decorate([ + rtfm("api", "HelixSharedChatSessionParticipant", "broadcasterId") +], HelixSharedChatSessionParticipant); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/chat/HelixSharedChatSession.js +var HelixSharedChatSession = class HelixSharedChatSession2 extends DataObject { + static { + __name(this, "HelixSharedChatSession"); + } + /** @internal */ + _client; + /** @internal */ + constructor(data2, client) { + super(data2); + this._client = client; + } + /** + * The unique identifier for the shared chat session. + */ + get sessionId() { + return this[rawDataSymbol].session_id; + } + /** + * The ID of the host broadcaster. + */ + get hostBroadcasterId() { + return this[rawDataSymbol].host_broadcaster_id; + } + /** + * Gets information about the host broadcaster. + */ + async getHostBroadcaster() { + return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].host_broadcaster_id)); + } + /** + * The list of participants in the session. + */ + get participants() { + return this[rawDataSymbol].participants.map((data2) => new HelixSharedChatSessionParticipant(data2, this._client)); + } + /** + * The date for when the session was created. + */ + get createdDate() { + return new Date(this[rawDataSymbol].created_at); + } + /** + * The date for when the session was updated. + */ + get updatedDate() { + return new Date(this[rawDataSymbol].updated_at); + } +}; +__decorate([ + Enumerable(false) +], HelixSharedChatSession.prototype, "_client", void 0); +HelixSharedChatSession = __decorate([ + rtfm("api", "HelixSharedChatSession", "sessionId") +], HelixSharedChatSession); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/chat/HelixUserEmote.js +init_modules_watch_stub(); +init_performance2(); +var HelixUserEmote = class HelixUserEmote2 extends HelixEmoteBase { + static { + __name(this, "HelixUserEmote"); + } + /** @internal */ + _client; + constructor(data2, client) { + super(data2); + this._client = client; + } + /** + * The type of the emote. + * + * There are many types of emotes that Twitch seems to arbitrarily assign. + * Check the relevant values in the official documentation. + * + * @see https://dev.twitch.tv/docs/api/reference/#get-user-emotes + */ + get type() { + return this[rawDataSymbol].emote_type; + } + /** + * The ID that identifies the emote set that the emote belongs to, or `null` if the emote is not from any set. + */ + get emoteSetId() { + return this[rawDataSymbol].emote_set_id || null; + } + /** + * The ID of the broadcaster who owns the emote, or `null` if the emote has no owner, e.g. it's a global emote. + */ + get ownerId() { + return this[rawDataSymbol].owner_id || null; + } + /** + * Gets all emotes from the emotes set, or `null` if emote is not from any set. + */ + async getAllEmotesFromSet() { + return this[rawDataSymbol].emote_set_id ? await this._client.chat.getEmotesFromSets([this[rawDataSymbol].emote_set_id]) : null; + } + /** + * Gets more information about the user that owns the emote, or `null` if the emote is not owned by a user. + */ + async getOwner() { + return this[rawDataSymbol].owner_id ? await this._client.users.getUserById(this[rawDataSymbol].owner_id) : null; + } +}; +__decorate([ + Enumerable(false) +], HelixUserEmote.prototype, "_client", void 0); +HelixUserEmote = __decorate([ + rtfm("api", "HelixUserEmote", "id") +], HelixUserEmote); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/chat/HelixChatApi.js +var HelixChatApi = class HelixChatApi2 extends BaseApi { + static { + __name(this, "HelixChatApi"); + } + /** + * Gets the list of users that are connected to the broadcaster’s chat session. + * + * This uses the token of the broadcaster by default. + * If you want to execute this in the context of another user (who has to be moderator of the channel) + * you can do so using [user context overrides](/docs/auth/concepts/context-switching). + * + * @param broadcaster The broadcaster whose list of chatters you want to get. + * @param pagination + * + * @expandParams + */ + async getChatters(broadcaster, pagination) { + const broadcasterId = extractUserId(broadcaster); + const result = await this._client.callApi({ + type: "helix", + url: "chat/chatters", + userId: broadcasterId, + canOverrideScopedUserContext: true, + scopes: ["moderator:read:chatters"], + query: { + ...this._createModeratorActionQuery(broadcasterId), + ...createPaginationQuery(pagination) + } + }); + return createPaginatedResultWithTotal(result, HelixChatChatter, this._client); + } + /** + * Creates a paginator for users that are connected to the broadcaster’s chat session. + * + * This uses the token of the broadcaster by default. + * If you want to execute this in the context of another user (who has to be moderator of the channel) + * you can do so using [user context overrides](/docs/auth/concepts/context-switching). + * + * @param broadcaster The broadcaster whose list of chatters you want to get. + * + * @expandParams + */ + getChattersPaginated(broadcaster) { + const broadcasterId = extractUserId(broadcaster); + return new HelixPaginatedRequestWithTotal({ + url: "chat/chatters", + userId: broadcasterId, + canOverrideScopedUserContext: true, + scopes: ["moderator:read:chatters"], + query: this._createModeratorActionQuery(broadcasterId) + }, this._client, (data2) => new HelixChatChatter(data2, this._client), 1e3); + } + /** + * Gets all global badges. + */ + async getGlobalBadges() { + const result = await this._client.callApi({ + type: "helix", + url: "chat/badges/global" + }); + return result.data.map((data2) => new HelixChatBadgeSet(data2)); + } + /** + * Gets all badges specific to the given broadcaster. + * + * @param broadcaster The broadcaster to get badges for. + */ + async getChannelBadges(broadcaster) { + const result = await this._client.callApi({ + type: "helix", + url: "chat/badges", + userId: extractUserId(broadcaster), + query: createBroadcasterQuery(broadcaster) + }); + return result.data.map((data2) => new HelixChatBadgeSet(data2)); + } + /** + * Gets all global emotes. + */ + async getGlobalEmotes() { + const result = await this._client.callApi({ + type: "helix", + url: "chat/emotes/global" + }); + return result.data.map((data2) => new HelixEmote(data2)); + } + /** + * Gets all emotes specific to the given broadcaster. + * + * @param broadcaster The broadcaster to get emotes for. + */ + async getChannelEmotes(broadcaster) { + const result = await this._client.callApi({ + type: "helix", + url: "chat/emotes", + userId: extractUserId(broadcaster), + query: createBroadcasterQuery(broadcaster) + }); + return result.data.map((data2) => new HelixChannelEmote(data2, this._client)); + } + /** + * Gets all emotes from a list of emote sets. + * + * @param setIds The IDs of the emote sets to get emotes from. + */ + async getEmotesFromSets(setIds) { + const result = await this._client.callApi({ + type: "helix", + url: "chat/emotes/set", + query: createSingleKeyQuery("emote_set_id", setIds) + }); + return result.data.map((data2) => new HelixEmoteFromSet(data2, this._client)); + } + /** + * Gets emotes available to the user across all channels. + * + * @param user The ID of the user to get available emotes of. + * @param filter Additional query filters. + */ + async getUserEmotes(user, filter) { + const userId = extractUserId(user); + const result = await this._client.callApi({ + type: "helix", + url: "chat/emotes/user", + userId: extractUserId(user), + scopes: ["user:read:emotes"], + query: { + ...createSingleKeyQuery("user_id", userId), + ...createSingleKeyQuery("broadcasterId", filter?.broadcaster ? extractUserId(filter.broadcaster) : void 0), + ...createPaginationQuery(filter) + } + }); + return createPaginatedResult(result, HelixUserEmote, this._client); + } + /** + * Creates a paginator for emotes available to the user across all channels. + * + * @param user The ID of the user to get available emotes of. + * @param broadcaster The ID of a broadcaster you wish to get follower emotes of. Using this query parameter will + * guarantee inclusion of the broadcaster’s follower emotes in the response body. + * + * If the user who retrieves their emotes is subscribed to the broadcaster specified, their follower emotes will + * appear in the response body regardless of whether this query parameter is used. + */ + getUserEmotesPaginated(user, broadcaster) { + const userId = extractUserId(user); + return new HelixPaginatedRequest({ + url: "chat/emotes/user", + userId, + scopes: ["user:read:emotes"], + query: { + ...createSingleKeyQuery("user_id", userId), + ...createSingleKeyQuery("broadcasterId", broadcaster ? extractUserId(broadcaster) : void 0) + } + }, this._client, (data2) => new HelixUserEmote(data2, this._client)); + } + /** + * Gets the settings of a broadcaster's chat. + * + * @param broadcaster The broadcaster the chat belongs to. + */ + async getSettings(broadcaster) { + const result = await this._client.callApi({ + type: "helix", + url: "chat/settings", + userId: extractUserId(broadcaster), + query: createBroadcasterQuery(broadcaster) + }); + return new HelixChatSettings(result.data[0]); + } + /** + * Gets the settings of a broadcaster's chat, including the delay settings. + * + * This uses the token of the broadcaster by default. + * If you want to execute this in the context of another user (who has to be moderator of the channel) + * you can do so using [user context overrides](/docs/auth/concepts/context-switching). + * + * @param broadcaster The broadcaster the chat belongs to. + */ + async getSettingsPrivileged(broadcaster) { + const broadcasterId = extractUserId(broadcaster); + const result = await this._client.callApi({ + type: "helix", + url: "chat/settings", + userId: broadcasterId, + canOverrideScopedUserContext: true, + scopes: ["moderator:read:chat_settings"], + query: this._createModeratorActionQuery(broadcasterId) + }); + return new HelixPrivilegedChatSettings(result.data[0]); + } + /** + * Updates the settings of a broadcaster's chat. + * + * This uses the token of the broadcaster by default. + * If you want to execute this in the context of another user (who has to be moderator of the channel) + * you can do so using [user context overrides](/docs/auth/concepts/context-switching). + * + * @expandParams + * + * @param broadcaster The broadcaster the chat belongs to. + * @param settings The settings to change. + */ + async updateSettings(broadcaster, settings) { + const broadcasterId = extractUserId(broadcaster); + const result = await this._client.callApi({ + type: "helix", + url: "chat/settings", + method: "PATCH", + userId: broadcasterId, + canOverrideScopedUserContext: true, + scopes: ["moderator:manage:chat_settings"], + query: this._createModeratorActionQuery(broadcasterId), + jsonBody: createChatSettingsUpdateBody(settings) + }); + return new HelixPrivilegedChatSettings(result.data[0]); + } + /** + * Sends a chat message to a broadcaster's chat. + * + * This uses the token of the broadcaster by default. + * If you want to execute this in the context of another user + * you can do so using [user context overrides](/docs/auth/concepts/context-switching). + * + * @expandParams + * + * @param broadcaster The broadcaster the chat belongs to. + * @param message The message to send. + * @param params + */ + async sendChatMessage(broadcaster, message, params) { + const broadcasterId = extractUserId(broadcaster); + const result = await this._client.callApi({ + type: "helix", + url: "chat/messages", + method: "POST", + userId: broadcasterId, + canOverrideScopedUserContext: true, + scopes: ["user:write:chat"], + query: createSendChatMessageQuery(broadcasterId, this._getUserContextIdWithDefault(broadcasterId)), + jsonBody: createSendChatMessageBody(message, params) + }); + const msg = new HelixSentChatMessage(result.data[0]); + this._handleUnsentChatMessage(broadcasterId, msg); + return msg; + } + /** + * Sends a chat message to a broadcaster's chat, using an app token. + * + * This requires the scopes `user:write:chat` and `user:bot` for the `user` and `channel:bot` for the `broadcaster`. + * `channel:bot` is not required if the `user` has moderator privileges in the `broadcaster`'s channel. + * + * These scope requirements can not be checked by the library, so they are just assumed. + * Make sure to catch authorization errors yourself. + * + * @expandParams + * + * @param user The user to send the chat message from. + * @param broadcaster The broadcaster the chat belongs to. + * @param message The message to send. + * @param params + */ + async sendChatMessageAsApp(user, broadcaster, message, params) { + const userId = extractUserId(user); + const broadcasterId = extractUserId(broadcaster); + const result = await this._client.callApi({ + type: "helix", + url: "chat/messages", + method: "POST", + forceType: "app", + query: createSendChatMessageQuery(broadcasterId, userId), + jsonBody: createSendChatMessageAsAppBody(message, params) + }); + const msg = new HelixSentChatMessage(result.data[0]); + this._handleUnsentChatMessage(broadcasterId, msg); + return msg; + } + /** + * Sends an announcement to a broadcaster's chat. + * + * This uses the token of the broadcaster by default. + * If you want to execute this in the context of another user (who has to be moderator of the channel) + * you can do so using [user context overrides](/docs/auth/concepts/context-switching). + * + * @param broadcaster The broadcaster the chat belongs to. + * @param announcement The announcement to send. + */ + async sendAnnouncement(broadcaster, announcement) { + const broadcasterId = extractUserId(broadcaster); + await this._client.callApi({ + type: "helix", + url: "chat/announcements", + method: "POST", + userId: broadcasterId, + canOverrideScopedUserContext: true, + scopes: ["moderator:manage:announcements"], + query: this._createModeratorActionQuery(broadcasterId), + jsonBody: { + message: announcement.message, + color: announcement.color + } + }); + } + /** + * Gets the chat colors for a list of users. + * + * Returns a Map with user IDs as keys and their colors as values. + * The value is a color hex code, or `null` if the user did not set a color, + * and unknown users will not be present in the map. + * + * @param users The users to get the chat colors of. + */ + async getColorsForUsers(users) { + const response = await this._client.callApi({ + type: "helix", + url: "chat/color", + query: createSingleKeyQuery("user_id", users.map(extractUserId)) + }); + return new Map(response.data.map((data2) => [data2.user_id, data2.color || null])); + } + /** + * Gets the chat color for a user. + * + * Returns the color as hex code, `null` if the user did not set a color, or `undefined` if the user is unknown. + * + * @param user The user to get the chat color of. + */ + async getColorForUser(user) { + const response = await this._client.callApi({ + type: "helix", + url: "chat/color", + userId: extractUserId(user), + query: createSingleKeyQuery("user_id", extractUserId(user)) + }); + if (!response.data.length) { + return void 0; + } + return response.data[0].color || null; + } + /** + * Changes the chat color for a user. + * + * @param user The user to change the color of. + * @param color The color to set. + * + * Note that hex codes can only be used by users that have a Prime or Turbo subscription. + */ + async setColorForUser(user, color) { + await this._client.callApi({ + type: "helix", + url: "chat/color", + method: "PUT", + userId: extractUserId(user), + scopes: ["user:manage:chat_color"], + query: createChatColorUpdateQuery(user, color) + }); + } + /** + * Sends a shoutout to the specified broadcaster. + * The broadcaster may send a shoutout once every 2 minutes. They may send the same broadcaster a shoutout once every 60 minutes. + * + * This uses the token of the broadcaster by default. + * If you want to execute this in the context of another user (who has to be moderator of the channel) + * you can do so using [user context overrides](/docs/auth/concepts/context-switching). + * + * @param from The ID of the broadcaster that’s sending the shoutout. + * @param to The ID of the broadcaster that’s receiving the shoutout. + */ + async shoutoutUser(from, to) { + const fromId = extractUserId(from); + await this._client.callApi({ + type: "helix", + url: "chat/shoutouts", + method: "POST", + userId: fromId, + canOverrideScopedUserContext: true, + scopes: ["moderator:manage:shoutouts"], + query: createShoutoutQuery(from, to, this._getUserContextIdWithDefault(fromId)) + }); + } + /** + * Gets the active shared chat session for a channel. + * + * Returns `null` if there is no active shared chat session in the channel. + * + * @param broadcaster The broadcaster to get the active shared chat session for. + */ + async getSharedChatSession(broadcaster) { + const broadcasterId = extractUserId(broadcaster); + const response = await this._client.callApi({ + type: "helix", + url: "shared_chat/session", + userId: broadcasterId, + query: createSharedChatSessionQuery(broadcasterId) + }); + if (response.data.length === 0) { + return null; + } + return new HelixSharedChatSession(response.data[0], this._client); + } + _createModeratorActionQuery(broadcasterId) { + return createModeratorActionQuery(broadcasterId, this._getUserContextIdWithDefault(broadcasterId)); + } + _handleUnsentChatMessage(broadcasterId, msg) { + if (!msg.isSent) { + throw new ChatMessageDroppedError(broadcasterId, msg.dropReasonMessage, msg.dropReasonCode); + } + } +}; +HelixChatApi = __decorate([ + rtfm("api", "HelixChatApi") +], HelixChatApi); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/clip/HelixClipApi.js +init_modules_watch_stub(); +init_performance2(); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/interfaces/endpoints/clip.external.js +init_modules_watch_stub(); +init_performance2(); +function createClipCreateQuery(params) { + const { channel, createAfterDelay = false, title: title2, duration } = params; + return { + broadcaster_id: extractUserId(channel), + has_delay: createAfterDelay.toString(), + title: title2, + duration: duration?.toFixed(1) + }; +} +__name(createClipCreateQuery, "createClipCreateQuery"); +function createClipCreateFromVodQuery(params, editorId) { + const { channel, title: title2, duration, vodId, vodOffset } = params; + return { + broadcaster_id: extractUserId(channel), + editor_id: editorId, + title: title2, + duration: duration?.toFixed(1), + vod_id: vodId, + vod_offset: vodOffset.toString() + }; +} +__name(createClipCreateFromVodQuery, "createClipCreateFromVodQuery"); +function createClipQuery(params) { + const { filterType, ids, startDate, endDate, isFeatured } = params; + return { + [filterType]: ids, + started_at: startDate, + ended_at: endDate, + is_featured: isFeatured?.toString() + }; +} +__name(createClipQuery, "createClipQuery"); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/clip/HelixClip.js +init_modules_watch_stub(); +init_performance2(); +var HelixClip = class HelixClip2 extends DataObject { + static { + __name(this, "HelixClip"); + } + /** @internal */ + _client; + /** @internal */ + constructor(data2, client) { + super(data2); + this._client = client; + } + /** + * The clip ID. + */ + get id() { + return this[rawDataSymbol].id; + } + /** + * The URL of the clip. + */ + get url() { + return this[rawDataSymbol].url; + } + /** + * The embed URL of the clip. + */ + get embedUrl() { + return this[rawDataSymbol].embed_url; + } + /** + * The user ID of the broadcaster of the stream where the clip was created. + */ + get broadcasterId() { + return this[rawDataSymbol].broadcaster_id; + } + /** + * The display name of the broadcaster of the stream where the clip was created. + */ + get broadcasterDisplayName() { + return this[rawDataSymbol].broadcaster_name; + } + /** + * Gets information about the broadcaster of the stream where the clip was created. + */ + async getBroadcaster() { + return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].broadcaster_id)); + } + /** + * The user ID of the creator of the clip. + */ + get creatorId() { + return this[rawDataSymbol].creator_id; + } + /** + * The display name of the creator of the clip. + */ + get creatorDisplayName() { + return this[rawDataSymbol].creator_name; + } + /** + * Gets information about the creator of the clip. + */ + async getCreator() { + return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].creator_id)); + } + /** + * The ID of the video the clip is taken from. + */ + get videoId() { + return this[rawDataSymbol].video_id; + } + /** + * Gets information about the video the clip is taken from. + */ + async getVideo() { + return checkRelationAssertion(await this._client.videos.getVideoById(this[rawDataSymbol].video_id)); + } + /** + * The ID of the game that was being played when the clip was created. + */ + get gameId() { + return this[rawDataSymbol].game_id; + } + /** + * Gets information about the game that was being played when the clip was created. + */ + async getGame() { + return this[rawDataSymbol].game_id ? checkRelationAssertion(await this._client.games.getGameById(this[rawDataSymbol].game_id)) : null; + } + /** + * The language of the stream where the clip was created. + */ + get language() { + return this[rawDataSymbol].language; + } + /** + * The title of the clip. + */ + get title() { + return this[rawDataSymbol].title; + } + /** + * The number of views of the clip. + */ + get views() { + return this[rawDataSymbol].view_count; + } + /** + * The date when the clip was created. + */ + get creationDate() { + return new Date(this[rawDataSymbol].created_at); + } + /** + * The URL of the thumbnail of the clip. + */ + get thumbnailUrl() { + return this[rawDataSymbol].thumbnail_url; + } + /** + * The duration of the clip in seconds (up to 0.1 precision). + */ + get duration() { + return this[rawDataSymbol].duration; + } + /** + * The offset of the clip from the start of the corresponding VOD, in seconds. + * + * This may be null if there is no VOD or if the clip is created from a live broadcast, + * in which case it may take a few minutes to associate with the VOD. + */ + get vodOffset() { + return this[rawDataSymbol].vod_offset; + } + /** + * Whether the clip is featured. + */ + get isFeatured() { + return this[rawDataSymbol].is_featured; + } +}; +__decorate([ + Enumerable(false) +], HelixClip.prototype, "_client", void 0); +HelixClip = __decorate([ + rtfm("api", "HelixClip", "id") +], HelixClip); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/clip/HelixClipApi.js +var HelixClipApi = class HelixClipApi2 extends BaseApi { + static { + __name(this, "HelixClipApi"); + } + /** @internal */ + _getClipByIdBatcher = new HelixRequestBatcher({ + url: "clips" + }, "id", "id", this._client, (data2) => new HelixClip(data2, this._client)); + /** + * Gets clips for the specified broadcaster in descending order of views. + * + * @param broadcaster The broadcaster to fetch clips for. + * @param filter + * + * @expandParams + */ + async getClipsForBroadcaster(broadcaster, filter = {}) { + return await this._getClips({ + ...filter, + filterType: "broadcaster_id", + ids: extractUserId(broadcaster), + userId: extractUserId(broadcaster) + }); + } + /** + * Creates a paginator for clips for the specified broadcaster. + * + * @param broadcaster The broadcaster to fetch clips for. + * @param filter + * + * @expandParams + */ + getClipsForBroadcasterPaginated(broadcaster, filter = {}) { + return this._getClipsPaginated({ + ...filter, + filterType: "broadcaster_id", + ids: extractUserId(broadcaster), + userId: extractUserId(broadcaster) + }); + } + /** + * Gets clips for the specified game in descending order of views. + * + * @param gameId The game ID. + * @param filter + * + * @expandParams + */ + async getClipsForGame(gameId, filter = {}) { + return await this._getClips({ + ...filter, + filterType: "game_id", + ids: gameId + }); + } + /** + * Creates a paginator for clips for the specified game. + * + * @param gameId The game ID. + * @param filter + * + * @expandParams + */ + getClipsForGamePaginated(gameId, filter = {}) { + return this._getClipsPaginated({ + ...filter, + filterType: "game_id", + ids: gameId + }); + } + /** + * Gets the clips identified by the given IDs. + * + * @param ids The clip IDs. + */ + async getClipsByIds(ids) { + const result = await this._getClips({ + filterType: "id", + ids + }); + return result.data; + } + /** + * Gets the clip identified by the given ID. + * + * @param id The clip ID. + */ + async getClipById(id) { + const clips = await this.getClipsByIds([id]); + return clips.length ? clips[0] : null; + } + /** + * Gets the clip identified by the given ID, batching multiple calls into fewer requests as the API allows. + * + * @param id The clip ID. + */ + async getClipByIdBatched(id) { + return await this._getClipByIdBatcher.request(id); + } + /** + * Creates a clip of a running stream. + * + * Returns the ID of the clip. + * + * @param params + * @expandParams + */ + async createClip(params) { + const result = await this._client.callApi({ + type: "helix", + url: "clips", + method: "POST", + userId: extractUserId(params.channel), + scopes: ["clips:edit"], + canOverrideScopedUserContext: true, + query: createClipCreateQuery(params) + }); + return result.data[0].id; + } + /** + * Creates a clip of a VOD. + * + * Returns the ID of the clip. + * + * @param params + * @expandParams + */ + async createClipFromVod(params) { + const broadcasterId = extractUserId(params.channel); + const result = await this._client.callApi({ + type: "helix", + url: "videos/clips", + method: "POST", + userId: broadcasterId, + scopes: ["editor:manage:clips", "channel:manage:clips"], + canOverrideScopedUserContext: true, + query: createClipCreateFromVodQuery(params, this._getUserContextIdWithDefault(broadcasterId)) + }); + return result.data[0].id; + } + async _getClips(params) { + if (!params.ids.length) { + return { data: [] }; + } + const result = await this._client.callApi({ + type: "helix", + url: "clips", + userId: params.userId, + query: { + ...createClipQuery(params), + ...createPaginationQuery(params) + } + }); + return createPaginatedResult(result, HelixClip, this._client); + } + _getClipsPaginated(params) { + return new HelixPaginatedRequest({ + url: "clips", + userId: params.userId, + query: createClipQuery(params) + }, this._client, (data2) => new HelixClip(data2, this._client)); + } +}; +__decorate([ + Enumerable(false) +], HelixClipApi.prototype, "_getClipByIdBatcher", void 0); +HelixClipApi = __decorate([ + rtfm("api", "HelixClipApi") +], HelixClipApi); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/contentClassificationLabels/HelixContentClassificationLabelApi.js +init_modules_watch_stub(); +init_performance2(); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/contentClassificationLabels/HelixContentClassificationLabel.js +init_modules_watch_stub(); +init_performance2(); +var HelixContentClassificationLabel = class extends DataObject { + static { + __name(this, "HelixContentClassificationLabel"); + } + /** + * The ID of the content classification label. + */ + get id() { + return this[rawDataSymbol].id; + } + /** + * The name of the content classification label. + */ + get name() { + return this[rawDataSymbol].name; + } + /** + * The description of the content classification label. + */ + get description() { + return this[rawDataSymbol].description; + } +}; + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/contentClassificationLabels/HelixContentClassificationLabelApi.js +var HelixContentClassificationLabelApi = class HelixContentClassificationLabelApi2 extends BaseApi { + static { + __name(this, "HelixContentClassificationLabelApi"); + } + /** + * Fetches a list of all content classification labels. + * + * @param locale The locale for the content classification labels. + */ + async getAll(locale) { + const result = await this._client.callApi({ + url: "content_classification_labels", + query: { + locale + } + }); + return result.data.map((data2) => new HelixContentClassificationLabel(data2)); + } +}; +HelixContentClassificationLabelApi = __decorate([ + rtfm("api", "HelixContentClassificationLabelApi") +], HelixContentClassificationLabelApi); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/entitlements/HelixEntitlementApi.js +init_modules_watch_stub(); +init_performance2(); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/interfaces/endpoints/entitlement.external.js +init_modules_watch_stub(); +init_performance2(); +function createDropsEntitlementQuery(filters, alwaysApp) { + return { + user_id: alwaysApp ? mapOptional(filters.user, extractUserId) : void 0, + game_id: filters.gameId, + fulfillment_status: filters.fulfillmentStatus + }; +} +__name(createDropsEntitlementQuery, "createDropsEntitlementQuery"); +function createDropsEntitlementUpdateBody(ids, fulfillmentStatus) { + return { + fulfillment_status: fulfillmentStatus, + entitlement_ids: ids + }; +} +__name(createDropsEntitlementUpdateBody, "createDropsEntitlementUpdateBody"); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/entitlements/HelixDropsEntitlement.js +init_modules_watch_stub(); +init_performance2(); +var HelixDropsEntitlement = class HelixDropsEntitlement2 extends DataObject { + static { + __name(this, "HelixDropsEntitlement"); + } + /** @internal */ + _client; + /** @internal */ + constructor(data2, client) { + super(data2); + this._client = client; + } + /** + * The ID of the entitlement. + */ + get id() { + return this[rawDataSymbol].id; + } + /** + * The ID of the reward. + */ + get rewardId() { + return this[rawDataSymbol].benefit_id; + } + /** + * The date when the entitlement was granted. + */ + get grantDate() { + return new Date(this[rawDataSymbol].timestamp); + } + /** + * The ID of the entitled user. + */ + get userId() { + return this[rawDataSymbol].user_id; + } + /** + * Gets more information about the entitled user. + */ + async getUser() { + return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].user_id)); + } + /** + * The ID of the game the entitlement was granted for. + */ + get gameId() { + return this[rawDataSymbol].game_id; + } + /** + * Gets more information about the game the entitlement was granted for. + */ + async getGame() { + return checkRelationAssertion(await this._client.games.getGameById(this[rawDataSymbol].game_id)); + } + /** + * The fulfillment status of the entitlement. + */ + get fulfillmentStatus() { + return this[rawDataSymbol].fulfillment_status; + } + /** + * The date when the entitlement was last updated. + */ + get updateDate() { + return new Date(this[rawDataSymbol].last_updated); + } +}; +__decorate([ + Enumerable(false) +], HelixDropsEntitlement.prototype, "_client", void 0); +HelixDropsEntitlement = __decorate([ + rtfm("api", "HelixDropsEntitlement") +], HelixDropsEntitlement); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/entitlements/HelixEntitlementApi.js +var HelixEntitlementApi = class HelixEntitlementApi2 extends BaseApi { + static { + __name(this, "HelixEntitlementApi"); + } + /** @internal */ + _getDropsEntitlementByIdBatcher = new HelixRequestBatcher({ + url: "entitlements/drops" + }, "id", "id", this._client, (data2) => new HelixDropsEntitlement(data2, this._client)); + /** + * Gets the drops entitlements for the given filter. + * + * @expandParams + * + * @param filter + * @param alwaysApp Whether an app token should always be used, even if a user filter is given. + */ + async getDropsEntitlements(filter, alwaysApp = false) { + const response = await this._client.callApi({ + type: "helix", + url: "entitlements/drops", + userId: mapOptional(filter.user, extractUserId), + forceType: filter.user && alwaysApp ? "app" : void 0, + query: { + ...createDropsEntitlementQuery(filter, alwaysApp), + ...createPaginationQuery(filter) + } + }); + return createPaginatedResult(response, HelixDropsEntitlement, this._client); + } + /** + * Creates a paginator for drops entitlements for the given filter. + * + * @expandParams + * + * @param filter + * @param alwaysApp Whether an app token should always be used, even if a user filter is given. + */ + getDropsEntitlementsPaginated(filter, alwaysApp = false) { + return new HelixPaginatedRequest({ + url: "entitlements/drops", + userId: mapOptional(filter.user, extractUserId), + forceType: filter.user && alwaysApp ? "app" : void 0, + query: createDropsEntitlementQuery(filter, alwaysApp) + }, this._client, (data2) => new HelixDropsEntitlement(data2, this._client)); + } + /** + * Gets the drops entitlements for the given IDs. + * + * @param ids The IDs to fetch. + */ + async getDropsEntitlementsByIds(ids) { + const response = await this._client.callApi({ + type: "helix", + url: "entitlements/drops", + query: { + id: ids + } + }); + return response.data.map((data2) => new HelixDropsEntitlement(data2, this._client)); + } + /** + * Gets the drops entitlement for the given ID. + * + * @param id The ID to fetch. + */ + async getDropsEntitlementById(id) { + const result = await this.getDropsEntitlementsByIds([id]); + return result[0] ?? null; + } + /** + * Gets the drops entitlement for the given ID, batching multiple calls into fewer requests as the API allows. + * + * @param id The ID to fetch. + */ + async getDropsEntitlementByIdBatched(id) { + return await this._getDropsEntitlementByIdBatcher.request(id); + } + /** + * Updates the status of a list of drops entitlements. + * + * Returns a map that associates each given ID with its update status. + * + * @param ids The IDs of the entitlements. + * @param fulfillmentStatus The fulfillment status to set the entitlements to. + */ + async updateDropsEntitlements(ids, fulfillmentStatus) { + const response = await this._client.callApi({ + type: "helix", + url: "entitlements/drops", + method: "PATCH", + jsonBody: createDropsEntitlementUpdateBody(ids, fulfillmentStatus) + }); + return new Map(response.data.flatMap((entry) => entry.ids.map((id) => [id, entry.status]))); + } +}; +__decorate([ + Enumerable(false) +], HelixEntitlementApi.prototype, "_getDropsEntitlementByIdBatcher", void 0); +HelixEntitlementApi = __decorate([ + rtfm("api", "HelixEntitlementApi") +], HelixEntitlementApi); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/eventSub/HelixEventSubApi.js +init_modules_watch_stub(); +init_performance2(); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/interfaces/endpoints/eventSub.external.js +init_modules_watch_stub(); +init_performance2(); +function createEventSubBroadcasterCondition(broadcaster) { + return { + broadcaster_user_id: extractUserId(broadcaster) + }; +} +__name(createEventSubBroadcasterCondition, "createEventSubBroadcasterCondition"); +function createEventSubRewardCondition(broadcaster, rewardId) { + return { broadcaster_user_id: extractUserId(broadcaster), reward_id: rewardId }; +} +__name(createEventSubRewardCondition, "createEventSubRewardCondition"); +function createEventSubModeratorCondition(broadcasterId, moderatorId) { + return { + broadcaster_user_id: broadcasterId, + moderator_user_id: moderatorId + }; +} +__name(createEventSubModeratorCondition, "createEventSubModeratorCondition"); +function createEventSubUserCondition(broadcasterId, userId) { + return { + broadcaster_user_id: broadcasterId, + user_id: userId + }; +} +__name(createEventSubUserCondition, "createEventSubUserCondition"); +function createEventSubDropEntitlementGrantCondition(filter) { + return { + organization_id: filter.organizationId, + category_id: filter.categoryId, + campaign_id: filter.campaignId + }; +} +__name(createEventSubDropEntitlementGrantCondition, "createEventSubDropEntitlementGrantCondition"); +function createEventSubConduitCondition(conduitId, status) { + return { + conduit_id: conduitId, + status + }; +} +__name(createEventSubConduitCondition, "createEventSubConduitCondition"); +function createEventSubConduitUpdateCondition(conduitId, shardCount) { + return { + id: conduitId, + shard_count: shardCount.toString() + }; +} +__name(createEventSubConduitUpdateCondition, "createEventSubConduitUpdateCondition"); +function createEventSubConduitShardsUpdateCondition(conduitId, shards) { + return { + conduit_id: conduitId, + shards + }; +} +__name(createEventSubConduitShardsUpdateCondition, "createEventSubConduitShardsUpdateCondition"); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/eventSub/HelixEventSubSubscription.js +init_modules_watch_stub(); +init_performance2(); +var HelixEventSubSubscription = class HelixEventSubSubscription2 extends DataObject { + static { + __name(this, "HelixEventSubSubscription"); + } + /** @internal */ + _client; + /** @internal */ + constructor(data2, client) { + super(data2); + this._client = client; + } + /** + * The ID of the subscription. + */ + get id() { + return this[rawDataSymbol].id; + } + /** + * The status of the subscription. + */ + get status() { + return this[rawDataSymbol].status; + } + /** + * The event type that the subscription is listening to. + */ + get type() { + return this[rawDataSymbol].type; + } + /** + * The cost of the subscription. + */ + get cost() { + return this[rawDataSymbol].cost; + } + /** + * The condition of the subscription. + */ + get condition() { + return this[rawDataSymbol].condition; + } + /** + * The date and time of creation of the subscription. + */ + get creationDate() { + return new Date(this[rawDataSymbol].created_at); + } + /** + * The transport method of the subscription. + */ + get transportMethod() { + return this[rawDataSymbol].transport.method; + } + /** + * End the EventSub subscription. + */ + async unsubscribe() { + await this._client.eventSub.deleteSubscription(this[rawDataSymbol].id); + } + /** @private */ + get _transport() { + return this[rawDataSymbol].transport; + } + /** @private */ + set _status(status) { + this[rawDataSymbol].status = status; + } +}; +__decorate([ + Enumerable(false) +], HelixEventSubSubscription.prototype, "_client", void 0); +HelixEventSubSubscription = __decorate([ + rtfm("api", "HelixEventSubSubscription", "id") +], HelixEventSubSubscription); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/eventSub/HelixPaginatedEventSubSubscriptionsRequest.js +init_modules_watch_stub(); +init_performance2(); +var HelixPaginatedEventSubSubscriptionsRequest = class HelixPaginatedEventSubSubscriptionsRequest2 extends HelixPaginatedRequestWithTotal { + static { + __name(this, "HelixPaginatedEventSubSubscriptionsRequest"); + } + /** @internal */ + constructor(query, userId, client) { + super({ + url: "eventsub/subscriptions", + userId, + query + }, client, (data2) => new HelixEventSubSubscription(data2, client)); + } + /** + * Gets the total cost of EventSub subscriptions. + */ + async getTotalCost() { + const data2 = this._currentData ?? await this._fetchData({ query: { after: void 0 } }); + return data2.total_cost; + } + /** + * Gets the cost limit of EventSub subscriptions. + */ + async getMaxTotalCost() { + const data2 = this._currentData ?? await this._fetchData({ query: { after: void 0 } }); + return data2.max_total_cost; + } +}; +HelixPaginatedEventSubSubscriptionsRequest = __decorate([ + rtfm("api", "HelixPaginatedEventSubSubscriptionsRequest") +], HelixPaginatedEventSubSubscriptionsRequest); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/eventSub/HelixEventSubConduit.js +init_modules_watch_stub(); +init_performance2(); +var HelixEventSubConduit = class HelixEventSubConduit2 extends DataObject { + static { + __name(this, "HelixEventSubConduit"); + } + /** @internal */ + _client; + /** @internal */ + constructor(data2, client) { + super(data2); + this._client = client; + } + /** + * The ID of the conduit. + */ + get id() { + return this[rawDataSymbol].id; + } + /** + * The shard count of the conduit. + */ + get shardCount() { + return this[rawDataSymbol].shard_count; + } + /** + * Update the conduit. + * + * @param shardCount The new shard count. + */ + async update(shardCount) { + return await this._client.eventSub.updateConduit(this[rawDataSymbol].id, shardCount); + } + /** + * Delete the conduit. + */ + async delete() { + await this._client.eventSub.deleteConduit(this[rawDataSymbol].id); + } + /** + * Get the conduit shards. + */ + async getShards() { + return await this._client.eventSub.getConduitShards(this[rawDataSymbol].id); + } +}; +__decorate([ + Enumerable(false) +], HelixEventSubConduit.prototype, "_client", void 0); +HelixEventSubConduit = __decorate([ + rtfm("api", "HelixEventSubConduit") +], HelixEventSubConduit); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/eventSub/HelixEventSubConduitShard.js +init_modules_watch_stub(); +init_performance2(); +var HelixEventSubConduitShard = class HelixEventSubConduitShard2 extends DataObject { + static { + __name(this, "HelixEventSubConduitShard"); + } + /** + * The ID of the shard. + */ + get id() { + return this[rawDataSymbol].id; + } + /** + * The status of the shard. + */ + get status() { + return this[rawDataSymbol].status; + } + /** + * The transport method of the shard. + */ + get transportMethod() { + return this[rawDataSymbol].transport.method; + } +}; +HelixEventSubConduitShard = __decorate([ + rtfm("api", "HelixEventSubConduitShard") +], HelixEventSubConduitShard); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/eventSub/HelixEventSubApi.js +var HelixEventSubApi = class HelixEventSubApi2 extends BaseApi { + static { + __name(this, "HelixEventSubApi"); + } + /** + * Gets the current EventSub subscriptions for the current client. + * + * @param pagination + * + * @expandParams + */ + async getSubscriptions(pagination) { + const result = await this._client.callApi({ + type: "helix", + url: "eventsub/subscriptions", + query: createPaginationQuery(pagination) + }); + return { + ...createPaginatedResultWithTotal(result, HelixEventSubSubscription, this._client), + totalCost: result.total_cost, + maxTotalCost: result.max_total_cost + }; + } + /** + * Creates a paginator for the current EventSub subscriptions for the current client. + */ + getSubscriptionsPaginated() { + return new HelixPaginatedEventSubSubscriptionsRequest({}, void 0, this._client); + } + /** + * Gets the current EventSub subscriptions with the given status for the current client. + * + * @param status The status of the subscriptions to get. + * @param pagination + * + * @expandParams + */ + async getSubscriptionsForStatus(status, pagination) { + const result = await this._client.callApi({ + type: "helix", + url: "eventsub/subscriptions", + query: { + ...createPaginationQuery(pagination), + status + } + }); + return { + ...createPaginatedResultWithTotal(result, HelixEventSubSubscription, this._client), + totalCost: result.total_cost, + maxTotalCost: result.max_total_cost + }; + } + /** + * Creates a paginator for the current EventSub subscriptions with the given status for the current client. + * + * @param status The status of the subscriptions to get. + */ + getSubscriptionsForStatusPaginated(status) { + return new HelixPaginatedEventSubSubscriptionsRequest({ status }, void 0, this._client); + } + /** + * Gets the current EventSub subscriptions with the given type for the current client. + * + * @param type The type of the subscriptions to get. + * @param pagination + * + * @expandParams + */ + async getSubscriptionsForType(type, pagination) { + const result = await this._client.callApi({ + type: "helix", + url: "eventsub/subscriptions", + query: { + ...createPaginationQuery(pagination), + type + } + }); + return { + ...createPaginatedResultWithTotal(result, HelixEventSubSubscription, this._client), + totalCost: result.total_cost, + maxTotalCost: result.max_total_cost + }; + } + /** + * Creates a paginator for the current EventSub subscriptions with the given type for the current client. + * + * @param type The type of the subscriptions to get. + */ + getSubscriptionsForTypePaginated(type) { + return new HelixPaginatedEventSubSubscriptionsRequest({ type }, void 0, this._client); + } + /** + * Gets the current EventSub subscriptions for the current user and client. + * + * @param user The user to get subscriptions for. + * @param pagination + * + * @expandParams + */ + async getSubscriptionsForUser(user, pagination) { + const result = await this._client.callApi({ + type: "helix", + url: "eventsub/subscriptions", + userId: extractUserId(user), + query: { + ...createSingleKeyQuery("user_id", extractUserId(user)), + ...createPaginationQuery(pagination) + } + }); + return { + ...createPaginatedResultWithTotal(result, HelixEventSubSubscription, this._client), + totalCost: result.total_cost, + maxTotalCost: result.max_total_cost + }; + } + /** + * Creates a paginator for the current EventSub subscriptions with the given type for the current client. + * + * @param user The user to get subscriptions for. + */ + getSubscriptionsForUserPaginated(user) { + const userId = extractUserId(user); + return new HelixPaginatedEventSubSubscriptionsRequest(createSingleKeyQuery("user_id", userId), userId, this._client); + } + /** + * Sends an arbitrary request to subscribe to an event. + * + * You can only create WebHook transport subscriptions using app tokens + * and WebSocket transport subscriptions using user tokens. + * + * @param type The type of the event. + * @param version The version of the event. + * @param condition The condition of the subscription. + * @param transport The transport of the subscription. + * @param user The user to create the subscription in context of. + * @param requiredScopeSet The scope set required by the subscription. Will only be checked for applicable transports. + * @param canOverrideScopedUserContext Whether the auth user context can be overridden. + * @param isBatched Whether to enable batching for the subscription. Is only supported for select topics. + */ + async createSubscription(type, version3, condition, transport, user, requiredScopeSet, canOverrideScopedUserContext, isBatched) { + const usesAppAuth = transport.method === "webhook" || transport.method === "conduit"; + const scopes = usesAppAuth ? void 0 : requiredScopeSet; + if (!usesAppAuth && !user) { + throw new Error(`Transport ${transport.method} can only handle subscriptions with user context`); + } + const jsonBody = { + type, + version: version3, + condition, + transport + }; + if (isBatched) { + jsonBody.is_batching_enabled = true; + } + const result = await this._client.callApi({ + type: "helix", + url: "eventsub/subscriptions", + method: "POST", + scopes, + userId: mapOptional(user, extractUserId), + canOverrideScopedUserContext, + forceType: usesAppAuth ? "app" : "user", + jsonBody + }); + return new HelixEventSubSubscription(result.data[0], this._client); + } + /** + * Deletes a subscription. + * + * @param id The ID of the subscription. + */ + async deleteSubscription(id) { + await this._client.callApi({ + type: "helix", + url: "eventsub/subscriptions", + method: "DELETE", + query: { + id + } + }); + } + /** + * Deletes *all* subscriptions. + */ + async deleteAllSubscriptions() { + await this._deleteSubscriptionsWithCondition(); + } + /** + * Deletes all broken subscriptions, i.e. all that are not enabled or pending verification. + */ + async deleteBrokenSubscriptions() { + await this._deleteSubscriptionsWithCondition((sub) => sub.status !== "enabled" && sub.status !== "webhook_callback_verification_pending"); + } + /** + * Subscribe to events that represent a stream going live. + * + * @param broadcaster The broadcaster you want to listen to online events for. + * @param transport The transport options. + */ + async subscribeToStreamOnlineEvents(broadcaster, transport) { + return await this.createSubscription("stream.online", "1", createEventSubBroadcasterCondition(broadcaster), transport, broadcaster); + } + /** + * Subscribe to events that represent a stream going offline. + * + * @param broadcaster The broadcaster you want to listen to online events for. + * @param transport The transport options. + */ + async subscribeToStreamOfflineEvents(broadcaster, transport) { + return await this.createSubscription("stream.offline", "1", createEventSubBroadcasterCondition(broadcaster), transport, broadcaster); + } + /** + * Subscribe to events that represent a channel updating their metadata. + * + * @param broadcaster The broadcaster you want to listen to update events for. + * @param transport The transport options. + */ + async subscribeToChannelUpdateEvents(broadcaster, transport) { + return await this.createSubscription("channel.update", "2", createEventSubBroadcasterCondition(broadcaster), transport, broadcaster); + } + /** + * Subscribe to events that represent a user following a channel. + * + * @param broadcaster The broadcaster you want to listen to follow events for. + * @param transport The transport options. + */ + async subscribeToChannelFollowEvents(broadcaster, transport) { + const broadcasterId = extractUserId(broadcaster); + return await this.createSubscription("channel.follow", "2", createEventSubModeratorCondition(broadcasterId, this._getUserContextIdWithDefault(broadcasterId)), transport, broadcasterId, ["moderator:read:followers"], true); + } + /** + * Subscribe to events that represent a user subscribing to a channel. + * + * @param broadcaster The broadcaster you want to listen to subscribe events for. + * @param transport The transport options. + */ + async subscribeToChannelSubscriptionEvents(broadcaster, transport) { + return await this.createSubscription("channel.subscribe", "1", createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ["channel:read:subscriptions"]); + } + /** + * Subscribe to events that represent a user gifting another user a subscription to a channel. + * + * @param broadcaster The broadcaster you want to listen to subscription gift events for. + * @param transport The transport options. + */ + async subscribeToChannelSubscriptionGiftEvents(broadcaster, transport) { + return await this.createSubscription("channel.subscription.gift", "1", createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ["channel:read:subscriptions"]); + } + /** + * Subscribe to events that represent a user's subscription to a channel being announced. + * + * @param broadcaster The broadcaster you want to listen to subscription message events for. + * @param transport The transport options. + */ + async subscribeToChannelSubscriptionMessageEvents(broadcaster, transport) { + return await this.createSubscription("channel.subscription.message", "1", createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ["channel:read:subscriptions"]); + } + /** + * Subscribe to events that represent a user's subscription to a channel ending. + * + * @param broadcaster The broadcaster you want to listen to subscription end events for. + * @param transport The transport options. + */ + async subscribeToChannelSubscriptionEndEvents(broadcaster, transport) { + return await this.createSubscription("channel.subscription.end", "1", createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ["channel:read:subscriptions"]); + } + /** + * Subscribe to events that represent a user cheering bits to a channel. + * + * @param broadcaster The broadcaster you want to listen to cheer events for. + * @param transport The transport options. + */ + async subscribeToChannelCheerEvents(broadcaster, transport) { + return await this.createSubscription("channel.cheer", "1", createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ["bits:read"]); + } + /** + * Subscribe to events that represent a charity campaign starting in a channel. + * + * @param broadcaster The broadcaster you want to listen to charity donation events for. + * @param transport The transport options. + */ + async subscribeToChannelCharityCampaignStartEvents(broadcaster, transport) { + return await this.createSubscription("channel.charity_campaign.start", "1", createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ["channel:read:charity"]); + } + /** + * Subscribe to events that represent a charity campaign ending in a channel. + * + * @param broadcaster The broadcaster you want to listen to charity donation events for. + * @param transport The transport options. + */ + async subscribeToChannelCharityCampaignStopEvents(broadcaster, transport) { + return await this.createSubscription("channel.charity_campaign.stop", "1", createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ["channel:read:charity"]); + } + /** + * Subscribe to events that represent a user donating to a charity campaign in a channel. + * + * @param broadcaster The broadcaster you want to listen to charity donation events for. + * @param transport The transport options. + */ + async subscribeToChannelCharityDonationEvents(broadcaster, transport) { + return await this.createSubscription("channel.charity_campaign.donate", "1", createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ["channel:read:charity"]); + } + /** + * Subscribe to events that represent a charity campaign progressing in a channel. + * + * @param broadcaster The broadcaster you want to listen to charity donation events for. + * @param transport The transport options. + */ + async subscribeToChannelCharityCampaignProgressEvents(broadcaster, transport) { + return await this.createSubscription("channel.charity_campaign.progress", "1", createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ["channel:read:charity"]); + } + /** + * Subscribe to events that represent a user being banned in a channel. + * + * @param broadcaster The broadcaster you want to listen to ban events for. + * @param transport The transport options. + */ + async subscribeToChannelBanEvents(broadcaster, transport) { + return await this.createSubscription("channel.ban", "1", createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ["channel:moderate"]); + } + /** + * Subscribe to events that represent a user being unbanned in a channel. + * + * @param broadcaster The broadcaster you want to listen to unban events for. + * @param transport The transport options. + */ + async subscribeToChannelUnbanEvents(broadcaster, transport) { + return await this.createSubscription("channel.unban", "1", createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ["channel:moderate"]); + } + /** + * Subscribe to events that represent Shield Mode being activated in a channel. + * + * @param broadcaster The broadcaster you want to listen to Shield Mode activation events for. + * @param transport The transport options. + */ + async subscribeToChannelShieldModeBeginEvents(broadcaster, transport) { + const broadcasterId = extractUserId(broadcaster); + return await this.createSubscription("channel.shield_mode.begin", "1", createEventSubModeratorCondition(broadcasterId, this._getUserContextIdWithDefault(broadcasterId)), transport, broadcasterId, ["moderator:read:shield_mode", "moderator:manage:shield_mode"], true); + } + /** + * Subscribe to events that represent Shield Mode being deactivated in a channel. + * + * @param broadcaster The broadcaster you want to listen to Shield Mode deactivation events for. + * @param transport The transport options. + */ + async subscribeToChannelShieldModeEndEvents(broadcaster, transport) { + const broadcasterId = extractUserId(broadcaster); + return await this.createSubscription("channel.shield_mode.end", "1", createEventSubModeratorCondition(broadcasterId, this._getUserContextIdWithDefault(broadcasterId)), transport, broadcasterId, ["moderator:read:shield_mode", "moderator:manage:shield_mode"], true); + } + /** + * Subscribe to events that represent a moderator being added to a channel. + * + * @param broadcaster The broadcaster you want to listen for moderator add events for. + * @param transport The transport options. + */ + async subscribeToChannelModeratorAddEvents(broadcaster, transport) { + return await this.createSubscription("channel.moderator.add", "1", createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ["moderation:read"]); + } + /** + * Subscribe to events that represent a moderator being removed from a channel. + * + * @param broadcaster The broadcaster you want to listen for moderator remove events for. + * @param transport The transport options. + */ + async subscribeToChannelModeratorRemoveEvents(broadcaster, transport) { + return await this.createSubscription("channel.moderator.remove", "1", createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ["moderation:read"]); + } + /** + * Subscribe to events that represent a broadcaster raiding another broadcaster. + * + * @param broadcaster The broadcaster you want to listen to outgoing raid events for. + * @param transport The transport options. + */ + async subscribeToChannelRaidEventsFrom(broadcaster, transport) { + return await this.createSubscription("channel.raid", "1", createSingleKeyQuery("from_broadcaster_user_id", extractUserId(broadcaster)), transport, broadcaster); + } + /** + * Subscribe to events that represent a broadcaster being raided by another broadcaster. + * + * @param broadcaster The broadcaster you want to listen to incoming raid events for. + * @param transport The transport options. + */ + async subscribeToChannelRaidEventsTo(broadcaster, transport) { + return await this.createSubscription("channel.raid", "1", createSingleKeyQuery("to_broadcaster_user_id", extractUserId(broadcaster)), transport, broadcaster); + } + /** + * Subscribe to events that represent a Channel Points reward being added to a channel. + * + * @param broadcaster The broadcaster you want to listen to reward add events for. + * @param transport The transport options. + */ + async subscribeToChannelRewardAddEvents(broadcaster, transport) { + return await this.createSubscription("channel.channel_points_custom_reward.add", "1", createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ["channel:read:redemptions", "channel:manage:redemptions"]); + } + /** + * Subscribe to events that represent a Channel Points reward being updated in a channel. + * + * @param broadcaster The broadcaster you want to listen to reward update events for. + * @param transport The transport options. + */ + async subscribeToChannelRewardUpdateEvents(broadcaster, transport) { + return await this.createSubscription("channel.channel_points_custom_reward.update", "1", createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ["channel:read:redemptions", "channel:manage:redemptions"]); + } + /** + * Subscribe to events that represent a specific Channel Points reward being updated. + * + * @param broadcaster The broadcaster you want to listen to reward update events for. + * @param rewardId The ID of the reward you want to listen to update events for. + * @param transport The transport options. + */ + async subscribeToChannelRewardUpdateEventsForReward(broadcaster, rewardId, transport) { + return await this.createSubscription("channel.channel_points_custom_reward.update", "1", createEventSubRewardCondition(broadcaster, rewardId), transport, broadcaster, ["channel:read:redemptions", "channel:manage:redemptions"]); + } + /** + * Subscribe to events that represent a Channel Points reward being removed from a channel. + * + * @param broadcaster The broadcaster you want to listen to reward remove events for. + * @param transport The transport options. + */ + async subscribeToChannelRewardRemoveEvents(broadcaster, transport) { + return await this.createSubscription("channel.channel_points_custom_reward.remove", "1", createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ["channel:read:redemptions", "channel:manage:redemptions"]); + } + /** + * Subscribe to events that represent a specific Channel Points reward being removed from a channel. + * + * @param broadcaster The broadcaster you want to listen to reward remove events for. + * @param rewardId The ID of the reward you want to listen to remove events for. + * @param transport The transport options. + */ + async subscribeToChannelRewardRemoveEventsForReward(broadcaster, rewardId, transport) { + return await this.createSubscription("channel.channel_points_custom_reward.remove", "1", createEventSubRewardCondition(broadcaster, rewardId), transport, broadcaster, ["channel:read:redemptions", "channel:manage:redemptions"]); + } + /** + * Subscribe to events that represent a Channel Points reward being redeemed. + * + * @param broadcaster The broadcaster you want to listen to redemption events for. + * @param transport The transport options. + */ + async subscribeToChannelRedemptionAddEvents(broadcaster, transport) { + return await this.createSubscription("channel.channel_points_custom_reward_redemption.add", "1", createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ["channel:read:redemptions", "channel:manage:redemptions"]); + } + /** + * Subscribe to events that represent a specific Channel Points reward being redeemed. + * + * @param broadcaster The broadcaster you want to listen to redemption events for. + * @param rewardId The ID of the reward you want to listen to redemption events for. + * @param transport The transport options. + */ + async subscribeToChannelRedemptionAddEventsForReward(broadcaster, rewardId, transport) { + return await this.createSubscription("channel.channel_points_custom_reward_redemption.add", "1", createEventSubRewardCondition(broadcaster, rewardId), transport, broadcaster, ["channel:read:redemptions", "channel:manage:redemptions"]); + } + /** + * Subscribe to events that represent a Channel Points redemption being updated. + * + * @param broadcaster The broadcaster you want to listen to redemption update events for. + * @param transport The transport options. + */ + async subscribeToChannelRedemptionUpdateEvents(broadcaster, transport) { + return await this.createSubscription("channel.channel_points_custom_reward_redemption.update", "1", createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ["channel:read:redemptions", "channel:manage:redemptions"]); + } + /** + * Subscribe to events that represent a specific Channel Points reward's redemption being updated. + * + * @param broadcaster The broadcaster you want to listen to redemption update events for. + * @param rewardId The ID of the reward you want to listen to redemption updates for. + * @param transport The transport options. + */ + async subscribeToChannelRedemptionUpdateEventsForReward(broadcaster, rewardId, transport) { + return await this.createSubscription("channel.channel_points_custom_reward_redemption.update", "1", createEventSubRewardCondition(broadcaster, rewardId), transport, broadcaster, ["channel:read:redemptions", "channel:manage:redemptions"]); + } + /** + * Subscribe to events that represent a Channel Points automatic reward being redeemed. + * + * @param broadcaster The broadcaster you want to listen to automatic reward redemption events for. + * @param transport The transport options. + */ + async subscribeToChannelAutomaticRewardRedemptionAddEvents(broadcaster, transport) { + return await this.createSubscription("channel.channel_points_automatic_reward_redemption.add", "1", createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ["channel:read:redemptions", "channel:manage:redemptions"]); + } + /** + * Subscribe to events that represent a Channel Points automatic reward being redeemed. + * + * @param broadcaster The broadcaster you want to listen to automatic reward redemption events for. + * @param transport The transport options. + */ + async subscribeToChannelAutomaticRewardRedemptionAddV2Events(broadcaster, transport) { + return await this.createSubscription("channel.channel_points_automatic_reward_redemption.add", "2", createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ["channel:read:redemptions", "channel:manage:redemptions"]); + } + /** + * Subscribe to events that represent a poll starting in a channel. + * + * @param broadcaster The broadcaster you want to listen to poll begin events for. + * @param transport The transport options. + */ + async subscribeToChannelPollBeginEvents(broadcaster, transport) { + return await this.createSubscription("channel.poll.begin", "1", createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ["channel:read:polls", "channel:manage:polls"]); + } + /** + * Subscribe to events that represent a poll being voted on in a channel. + * + * @param broadcaster The broadcaster you want to listen to poll progress events for. + * @param transport The transport options. + */ + async subscribeToChannelPollProgressEvents(broadcaster, transport) { + return await this.createSubscription("channel.poll.progress", "1", createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ["channel:read:polls", "channel:manage:polls"]); + } + /** + * Subscribe to events that represent a poll ending in a channel. + * + * @param broadcaster The broadcaster you want to listen to poll end events for. + * @param transport The transport options. + */ + async subscribeToChannelPollEndEvents(broadcaster, transport) { + return await this.createSubscription("channel.poll.end", "1", createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ["channel:read:polls", "channel:manage:polls"]); + } + /** + * Subscribe to events that represent a prediction starting in a channel. + * + * @param broadcaster The broadcaster you want to listen to prediction begin events for. + * @param transport The transport options. + */ + async subscribeToChannelPredictionBeginEvents(broadcaster, transport) { + return await this.createSubscription("channel.prediction.begin", "1", createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ["channel:read:predictions", "channel:manage:predictions"]); + } + /** + * Subscribe to events that represent a prediction being voted on in a channel. + * + * @param broadcaster The broadcaster you want to listen to prediction preogress events for. + * @param transport The transport options. + */ + async subscribeToChannelPredictionProgressEvents(broadcaster, transport) { + return await this.createSubscription("channel.prediction.progress", "1", createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ["channel:read:predictions", "channel:manage:predictions"]); + } + /** + * Subscribe to events that represent a prediction being locked in a channel. + * + * @param broadcaster The broadcaster you want to listen to prediction lock events for. + * @param transport The transport options. + */ + async subscribeToChannelPredictionLockEvents(broadcaster, transport) { + return await this.createSubscription("channel.prediction.lock", "1", createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ["channel:read:predictions", "channel:manage:predictions"]); + } + /** + * Subscribe to events that represent a prediction ending in a channel. + * + * @param broadcaster The broadcaster you want to listen to prediction end events for. + * @param transport The transport options. + */ + async subscribeToChannelPredictionEndEvents(broadcaster, transport) { + return await this.createSubscription("channel.prediction.end", "1", createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ["channel:read:predictions", "channel:manage:predictions"]); + } + /** + * Subscribe to events that represent the beginning of a creator goal event in a channel. + * + * @param broadcaster The broadcaster you want to listen to goal begin events for. + * @param transport The transport options. + */ + async subscribeToChannelGoalBeginEvents(broadcaster, transport) { + return await this.createSubscription("channel.goal.begin", "1", createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ["channel:read:goals"]); + } + /** + * Subscribe to events that represent progress towards a creator goal. + * + * @param broadcaster The broadcaster for which you want to listen to goal progress events. + * @param transport The transport options. + */ + async subscribeToChannelGoalProgressEvents(broadcaster, transport) { + return await this.createSubscription("channel.goal.progress", "1", createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ["channel:read:goals"]); + } + /** + * Subscribe to events that represent the end of a creator goal event. + * + * @param broadcaster The broadcaster for which you want to listen to goal end events. + * @param transport The transport options. + */ + async subscribeToChannelGoalEndEvents(broadcaster, transport) { + return await this.createSubscription("channel.goal.end", "1", createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ["channel:read:goals"]); + } + /** + * Subscribe to events that represent the beginning of a Hype Train event in a channel. + * + * @param broadcaster The broadcaster you want to listen to Hype train begin events for. + * @param transport The transport options. + */ + async subscribeToChannelHypeTrainBeginEvents(broadcaster, transport) { + return await this.createSubscription("channel.hype_train.begin", "1", createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ["channel:read:hype_train"]); + } + /** + * Subscribe to events that represent progress towards the Hype Train goal. + * + * @param broadcaster The broadcaster for which you want to listen to Hype Train progress events. + * @param transport The transport options. + */ + async subscribeToChannelHypeTrainProgressEvents(broadcaster, transport) { + return await this.createSubscription("channel.hype_train.progress", "1", createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ["channel:read:hype_train"]); + } + /** + * Subscribe to events that represent the end of a Hype Train event. + * + * @param broadcaster The broadcaster for which you want to listen to Hype Train end events. + * @param transport The transport options. + */ + async subscribeToChannelHypeTrainEndEvents(broadcaster, transport) { + return await this.createSubscription("channel.hype_train.end", "1", createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ["channel:read:hype_train"]); + } + /** + * Subscribe to events that represent the beginning of a Hype Train event in a channel. + * + * @param broadcaster The broadcaster you want to listen to Hype train begin events for. + * @param transport The transport options. + */ + async subscribeToChannelHypeTrainBeginV2Events(broadcaster, transport) { + return await this.createSubscription("channel.hype_train.begin", "2", createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ["channel:read:hype_train"]); + } + /** + * Subscribe to events that represent progress towards the Hype Train goal. + * + * @param broadcaster The broadcaster for which you want to listen to Hype Train progress events. + * @param transport The transport options. + */ + async subscribeToChannelHypeTrainProgressV2Events(broadcaster, transport) { + return await this.createSubscription("channel.hype_train.progress", "2", createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ["channel:read:hype_train"]); + } + /** + * Subscribe to events that represent the end of a Hype Train event. + * + * @param broadcaster The broadcaster for which you want to listen to Hype Train end events. + * @param transport The transport options. + */ + async subscribeToChannelHypeTrainEndV2Events(broadcaster, transport) { + return await this.createSubscription("channel.hype_train.end", "2", createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ["channel:read:hype_train"]); + } + /** + * Subscribe to events that represent a broadcaster shouting out another broadcaster. + * + * @param broadcaster The broadcaster for which you want to listen to outgoing shoutout events. + * @param transport The transport options. + */ + async subscribeToChannelShoutoutCreateEvents(broadcaster, transport) { + const broadcasterId = extractUserId(broadcaster); + return await this.createSubscription("channel.shoutout.create", "1", createEventSubModeratorCondition(broadcasterId, this._getUserContextIdWithDefault(broadcasterId)), transport, broadcasterId, ["moderator:read:shoutouts", "moderator:manage:shoutouts"], true); + } + /** + * Subscribe to events that represent a broadcaster being shouting out by another broadcaster. + * + * @param broadcaster The broadcaster for which you want to listen to incoming shoutout events. + * @param transport The transport options. + */ + async subscribeToChannelShoutoutReceiveEvents(broadcaster, transport) { + const broadcasterId = extractUserId(broadcaster); + return await this.createSubscription("channel.shoutout.receive", "1", createEventSubModeratorCondition(broadcasterId, this._getUserContextIdWithDefault(broadcasterId)), transport, broadcasterId, ["moderator:read:shoutouts", "moderator:manage:shoutouts"], true); + } + /** + * Subscribe to events that represent an ad break beginning in a channel. + * + * @param broadcaster The broadcaster for which you want to listen to ad break begin events. + * @param transport The transport options. + */ + async subscribeToChannelAdBreakBeginEvents(broadcaster, transport) { + return await this.createSubscription("channel.ad_break.begin", "1", createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ["channel:read:ads"]); + } + /** + * Subscribe to events that represent a channel's chat being cleared. + * + * @param broadcaster The broadcaster for which you want to listen to chat clear events. + * @param transport The transport options. + */ + async subscribeToChannelChatClearEvents(broadcaster, transport) { + const broadcasterId = extractUserId(broadcaster); + return await this.createSubscription("channel.chat.clear", "1", createEventSubUserCondition(broadcasterId, this._getUserContextIdWithDefault(broadcasterId)), transport, broadcaster, ["user:read:chat"], true); + } + /** + * Subscribe to events that represent a user's chat messages being cleared in a channel. + * + * @param broadcaster The broadcaster for which you want to listen to user chat message clear events. + * @param transport The transport options. + */ + async subscribeToChannelChatClearUserMessagesEvents(broadcaster, transport) { + const broadcasterId = extractUserId(broadcaster); + return await this.createSubscription("channel.chat.clear_user_messages", "1", createEventSubUserCondition(broadcasterId, this._getUserContextIdWithDefault(broadcasterId)), transport, broadcaster, ["user:read:chat"], true); + } + /** + * Subscribe to events that represent a chat message being deleted in a channel. + * + * @param broadcaster The broadcaster for which you want to listen to chat message delete events. + * @param transport The transport options. + */ + async subscribeToChannelChatMessageDeleteEvents(broadcaster, transport) { + const broadcasterId = extractUserId(broadcaster); + return await this.createSubscription("channel.chat.message_delete", "1", createEventSubUserCondition(broadcasterId, this._getUserContextIdWithDefault(broadcasterId)), transport, broadcaster, ["user:read:chat"], true); + } + /** + * Subscribe to events that represent a chat notification in a channel. + * + * @param broadcaster The broadcaster for which you want to listen to chat notification events. + * @param transport The transport options. + */ + async subscribeToChannelChatNotificationEvents(broadcaster, transport) { + const broadcasterId = extractUserId(broadcaster); + return await this.createSubscription("channel.chat.notification", "1", createEventSubUserCondition(broadcasterId, this._getUserContextIdWithDefault(broadcasterId)), transport, broadcaster, ["user:read:chat"], true); + } + /** + * Subscribe to events that represent a chat message in a channel. + * + * @param broadcaster The broadcaster for which you want to listen to chat message events. + * @param transport The transport options. + */ + async subscribeToChannelChatMessageEvents(broadcaster, transport) { + const broadcasterId = extractUserId(broadcaster); + return await this.createSubscription("channel.chat.message", "1", createEventSubUserCondition(broadcasterId, this._getUserContextIdWithDefault(broadcasterId)), transport, broadcaster, ["user:read:chat"], true); + } + /** + * Subscribe to events that represent chat settings being updated in a channel. + * + * @param broadcaster The broadcaster for which you want to listen to chat settings update events. + * @param transport The transport options. + */ + async subscribeToChannelChatSettingsUpdateEvents(broadcaster, transport) { + const broadcasterId = extractUserId(broadcaster); + return await this.createSubscription("channel.chat_settings.update", "1", createEventSubUserCondition(broadcasterId, this._getUserContextIdWithDefault(broadcasterId)), transport, broadcaster, ["user:read:chat"], true); + } + /** + * Subscribe to events that represent a created unban requests in a channel. + * + * @param broadcaster The broadcaster for which you want to listen to unban requests. + * @param transport The transport options. + */ + async subscribeToChannelUnbanRequestCreateEvents(broadcaster, transport) { + const broadcasterId = extractUserId(broadcaster); + return await this.createSubscription("channel.unban_request.create", "1", createEventSubModeratorCondition(broadcasterId, this._getUserContextIdWithDefault(broadcasterId)), transport, broadcaster, ["moderator:read:unban_requests", "moderator:manage:unban_requests"], true); + } + /** + * Subscribe to events that represent a resolved unban requests in a channel. + * + * @param broadcaster The broadcaster for which you want to listen to unban requests. + * @param transport The transport options. + */ + async subscribeToChannelUnbanRequestResolveEvents(broadcaster, transport) { + const broadcasterId = extractUserId(broadcaster); + return await this.createSubscription("channel.unban_request.resolve", "1", createEventSubModeratorCondition(broadcasterId, this._getUserContextIdWithDefault(broadcasterId)), transport, broadcaster, ["moderator:read:unban_requests", "moderator:manage:unban_requests"], true); + } + /** + * Subscribe to events that represent a moderator performing an action on a channel. + * + * This requires the following scopes: + * - `moderator:read:blocked_terms` OR `moderator:manage:blocked_terms` + * - `moderator:read:chat_settings` OR `moderator:manage:chat_settings` + * - `moderator:read:unban_requests` OR `moderator:manage:unban_requests` + * - `moderator:read:banned_users` OR `moderator:manage:banned_users` + * - `moderator:read:chat_messages` OR `moderator:manage:chat_messages` + * - `moderator:read:warnings` OR `moderator:manage:warnings` + * - `moderator:read:moderators` + * - `moderator:read:vips` + * + * These scope requirements cannot be checked by the library, so they are just assumed. + * Make sure to catch authorization errors yourself. + * + * @param broadcaster The broadcaster for which you want to listen to moderation events. + * @param transport The transport options. + */ + async subscribeToChannelModerateEvents(broadcaster, transport) { + const broadcasterId = extractUserId(broadcaster); + return await this.createSubscription("channel.moderate", "2", createEventSubModeratorCondition(broadcasterId, this._getUserContextIdWithDefault(broadcasterId)), transport, broadcaster, [], true); + } + /** + * Subscribe to events that represent a warning being acknowledged by a user. + * + * @param broadcaster The broadcaster for whom you want to listen to warnings. + * @param transport The transport options. + */ + async subscribeToChannelWarningAcknowledgeEvents(broadcaster, transport) { + const broadcasterId = extractUserId(broadcaster); + return await this.createSubscription("channel.warning.acknowledge", "1", createEventSubModeratorCondition(broadcasterId, this._getUserContextIdWithDefault(broadcasterId)), transport, broadcaster, ["moderator:read:warnings", "moderator:manage:warnings"], true); + } + /** + * Subscribe to events that represent a warning sent to a user. + * + * @param broadcaster The broadcaster for whom you want to listen to warnings. + * @param transport The transport options. + */ + async subscribeToChannelWarningSendEvents(broadcaster, transport) { + const broadcasterId = extractUserId(broadcaster); + return await this.createSubscription("channel.warning.send", "1", createEventSubModeratorCondition(broadcasterId, this._getUserContextIdWithDefault(broadcasterId)), transport, broadcaster, ["moderator:read:warnings", "moderator:manage:warnings"], true); + } + /** + * Subscribe to events that represent a VIP being added to a channel. + * + * @param broadcaster The broadcaster you want to listen for VIP add events for. + * @param transport The transport options. + */ + async subscribeToChannelVipAddEvents(broadcaster, transport) { + return await this.createSubscription("channel.vip.add", "1", createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ["channel:read:vips", "channel:manage:vips"]); + } + /** + * Subscribe to events that represent a VIP being removed from a channel. + * + * @param broadcaster The broadcaster you want to listen for VIP remove events for. + * @param transport The transport options. + */ + async subscribeToChannelVipRemoveEvents(broadcaster, transport) { + return await this.createSubscription("channel.vip.remove", "1", createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ["channel:read:vips", "channel:manage:vips"]); + } + /** + * Subscribe to events that represent an extension Bits transaction. + * + * @param clientId The Client ID for the extension you want to listen to Bits transactions for. + * @param transport The transport options. + */ + async subscribeToExtensionBitsTransactionCreateEvents(clientId, transport) { + return await this.createSubscription("extension.bits_transaction.create", "1", createSingleKeyQuery("extension_client_id", clientId), transport); + } + /** + * Subscribe to events that represent a user granting authorization to an application. + * + * @param clientId The Client ID for the application you want to listen to authorization grant events for. + * @param transport The transport options. + */ + async subscribeToUserAuthorizationGrantEvents(clientId, transport) { + return await this.createSubscription("user.authorization.grant", "1", createSingleKeyQuery("client_id", clientId), transport); + } + /** + * Subscribe to events that represent a user revoking their authorization from an application. + * + * @param clientId The Client ID for the application you want to listen to authorization revoke events for. + * @param transport The transport options. + */ + async subscribeToUserAuthorizationRevokeEvents(clientId, transport) { + return await this.createSubscription("user.authorization.revoke", "1", createSingleKeyQuery("client_id", clientId), transport); + } + /** + * Subscribe to events that represent a user updating their account details. + * + * @param user The user you want to listen to user update events for. + * @param transport The transport options. + * @param withEmail Whether to request adding the email address of the user to the notification. + * + * Only has an effect with the websocket transport. + * With the webhook transport, this depends solely on the previous authorization given by the user. + */ + async subscribeToUserUpdateEvents(user, transport, withEmail) { + return await this.createSubscription("user.update", "1", createSingleKeyQuery("user_id", extractUserId(user)), transport, user, withEmail ? ["user:read:email"] : void 0); + } + /** + * Subscribe to events that represent a user receiving a whisper message from another user. + * + * @param user The user you want to listen to whisper message events for. + * @param transport The transport options. + */ + async subscribeToUserWhisperMessageEvents(user, transport) { + return await this.createSubscription("user.whisper.message", "1", createSingleKeyQuery("user_id", extractUserId(user)), transport, user, ["user:read:whispers", "user:manage:whispers"]); + } + /** + * Subscribe to events that represent a drop entitlement being granted. + * + * @expandParams + * + * @param filter + * @param transport The transport options. + */ + async subscribeToDropEntitlementGrantEvents(filter, transport) { + return await this.createSubscription("drop.entitlement.grant", "1", createEventSubDropEntitlementGrantCondition(filter), transport, void 0, void 0, false, true); + } + /** + * Subscribes to events that represent a chat message being held by AutoMod. + * + * @param broadcaster The broadcaster you want to listen to AutoMod message hold events for. + * @param transport The transport options. + */ + async subscribeToAutoModMessageHoldEvents(broadcaster, transport) { + const broadcasterId = extractUserId(broadcaster); + return await this.createSubscription("automod.message.hold", "1", createEventSubModeratorCondition(broadcasterId, this._getUserContextIdWithDefault(broadcasterId)), transport, broadcaster, ["moderator:manage:automod"], true); + } + /** + * Subscribes to events that represent a held chat message by AutoMod being resolved. + * + * @param broadcaster The broadcaster you want to listen to AutoMod message resolution events for. + * @param transport The transport options. + */ + async subscribeToAutoModMessageUpdateEvents(broadcaster, transport) { + const broadcasterId = extractUserId(broadcaster); + return await this.createSubscription("automod.message.update", "1", createEventSubModeratorCondition(broadcasterId, this._getUserContextIdWithDefault(broadcasterId)), transport, broadcaster, ["moderator:manage:automod"], true); + } + /** + * Subscribes to events (v2) that represent a chat message being held by AutoMod. + * + * @param broadcaster The broadcaster you want to listen to AutoMod message hold events for. + * @param transport The transport options. + */ + async subscribeToAutoModMessageHoldV2Events(broadcaster, transport) { + const broadcasterId = extractUserId(broadcaster); + return await this.createSubscription("automod.message.hold", "2", createEventSubModeratorCondition(broadcasterId, this._getUserContextIdWithDefault(broadcasterId)), transport, broadcaster, ["moderator:manage:automod"], true); + } + /** + * Subscribes to events (v2) that represent a held chat message by AutoMod being resolved. + * + * @param broadcaster The broadcaster you want to listen to AutoMod message resolution events for. + * @param transport The transport options. + */ + async subscribeToAutoModMessageUpdateV2Events(broadcaster, transport) { + const broadcasterId = extractUserId(broadcaster); + return await this.createSubscription("automod.message.update", "2", createEventSubModeratorCondition(broadcasterId, this._getUserContextIdWithDefault(broadcasterId)), transport, broadcaster, ["moderator:manage:automod"], true); + } + /** + * Subscribes to events that represent the AutoMod settings being updated. + * + * @param broadcaster The broadcaster you want to listen to AutoMod settings update events. + * @param transport The transport options. + */ + async subscribeToAutoModSettingsUpdateEvents(broadcaster, transport) { + const broadcasterId = extractUserId(broadcaster); + return await this.createSubscription("automod.settings.update", "1", createEventSubModeratorCondition(broadcasterId, this._getUserContextIdWithDefault(broadcasterId)), transport, broadcaster, ["moderator:read:automod_settings"], true); + } + /** + * Subscribes to events that represent the AutoMod terms being updated. + * + * @param broadcaster The broadcaster you want to listen to AutoMod terms update events. + * @param transport The transport options. + */ + async subscribeToAutoModTermsUpdateEvents(broadcaster, transport) { + const broadcasterId = extractUserId(broadcaster); + return await this.createSubscription("automod.terms.update", "1", createEventSubModeratorCondition(broadcasterId, this._getUserContextIdWithDefault(broadcasterId)), transport, broadcaster, ["moderator:manage:automod"], true); + } + /** + * Subscribes to events that represent a user's notification about their message being held by AutoMod. + * + * @param broadcaster The broadcaster you want to listen to AutoMod message hold events for. + * @param transport The transport options. + */ + async subscribeToChannelChatUserMessageHoldEvents(broadcaster, transport) { + const broadcasterId = extractUserId(broadcaster); + return await this.createSubscription("channel.chat.user_message_hold", "1", createEventSubUserCondition(broadcasterId, this._getUserContextIdWithDefault(broadcasterId)), transport, broadcaster, ["user:read:chat"], true); + } + /** + * Subscribes to events that represent a user's notification about a held chat message by AutoMod being resolved. + * + * @param broadcaster The broadcaster you want to listen to AutoMod message resolution events for. + * @param transport The transport options. + */ + async subscribeToChannelChatUserMessageUpdateEvents(broadcaster, transport) { + const broadcasterId = extractUserId(broadcaster); + return await this.createSubscription("channel.chat.user_message_update", "1", createEventSubUserCondition(broadcasterId, this._getUserContextIdWithDefault(broadcasterId)), transport, broadcaster, ["user:read:chat"], true); + } + /** + * Subscribes to events that represent a suspicious user updated in a channel. + * + * @param broadcaster The broadcaster you want to listen for suspicious user update events. + * @param transport The transport options. + */ + async subscribeToChannelSuspiciousUserUpdateEvents(broadcaster, transport) { + const broadcasterId = extractUserId(broadcaster); + return await this.createSubscription("channel.suspicious_user.update", "1", createEventSubModeratorCondition(broadcasterId, this._getUserContextIdWithDefault(broadcasterId)), transport, broadcaster, ["moderator:read:suspicious_users"], true); + } + /** + * Subscribes to events that represent a message sent by a suspicious user. + * + * @param broadcaster The broadcaster you want to listen for messages sent by suspicious users. + * @param transport The transport options. + */ + async subscribeToChannelSuspiciousUserMessageEvents(broadcaster, transport) { + const broadcasterId = extractUserId(broadcaster); + return await this.createSubscription("channel.suspicious_user.message", "1", createEventSubModeratorCondition(broadcasterId, this._getUserContextIdWithDefault(broadcasterId)), transport, broadcaster, ["moderator:read:suspicious_users"], true); + } + /** + * Subscribes to events indicating that a shared chat session has begun in a channel. + * + * @param broadcaster The broadcaster for whom shared chat session begin events should be listened to. + * @param transport The transport options to use for the subscription. + */ + async subscribeToChannelSharedChatSessionBeginEvents(broadcaster, transport) { + const broadcasterId = extractUserId(broadcaster); + return await this.createSubscription("channel.shared_chat.begin", "1", createEventSubBroadcasterCondition(broadcasterId), transport, broadcasterId); + } + /** + * Subscribes to events indicating that a shared chat session has been updated in a channel. + * + * @param broadcaster The broadcaster for whom shared chat session update events should be listened to. + * @param transport The transport options to use for the subscription. + */ + async subscribeToChannelSharedChatSessionUpdateEvents(broadcaster, transport) { + const broadcasterId = extractUserId(broadcaster); + return await this.createSubscription("channel.shared_chat.update", "1", createEventSubBroadcasterCondition(broadcasterId), transport, broadcasterId); + } + /** + * Subscribes to events indicating that a shared chat session has ended in a channel. + * + * @param broadcaster The broadcaster for whom shared chat session end events should be listened to. + * @param transport The transport options to use for the subscription. + */ + async subscribeToChannelSharedChatSessionEndEvents(broadcaster, transport) { + const broadcasterId = extractUserId(broadcaster); + return await this.createSubscription("channel.shared_chat.end", "1", createEventSubBroadcasterCondition(broadcasterId), transport, broadcasterId); + } + /** + * Subscribes to events indicating that bits are used in a channel. + * + * @param broadcaster The broadcaster for whom you want to listen to bits usage events. + * @param transport The transport options to use for the subscription. + */ + async subscribeToChannelBitsUseEvents(broadcaster, transport) { + const broadcasterId = extractUserId(broadcaster); + return await this.createSubscription("channel.bits.use", "1", createEventSubBroadcasterCondition(broadcasterId), transport, broadcasterId, ["bits:read"]); + } + /** + * Gets the current EventSub conduits for the current client. + * + */ + async getConduits() { + const result = await this._client.callApi({ + type: "helix", + url: "eventsub/conduits" + }); + return result.data.map((data2) => new HelixEventSubConduit(data2, this._client)); + } + /** + * Creates a new EventSub conduit for the current client. + * + * @param shardCount The number of shards to create for this conduit. + */ + async createConduit(shardCount) { + const result = await this._client.callApi({ + type: "helix", + url: "eventsub/conduits", + method: "POST", + query: { + ...createSingleKeyQuery("shard_count", shardCount.toString()) + } + }); + return new HelixEventSubConduit(result.data[0], this._client); + } + /** + * Updates an EventSub conduit for the current client. + * + * @param id The ID of the conduit to update. + * @param shardCount The number of shards to update for this conduit. + */ + async updateConduit(id, shardCount) { + const result = await this._client.callApi({ + type: "helix", + url: "eventsub/conduits", + method: "PATCH", + query: createEventSubConduitUpdateCondition(id, shardCount) + }); + return new HelixEventSubConduit(result.data[0], this._client); + } + /** + * Deletes an EventSub conduit for the current client. + * + * @param id The ID of the conduit to delete. + */ + async deleteConduit(id) { + await this._client.callApi({ + type: "helix", + url: "eventsub/conduits", + method: "DELETE", + query: { + ...createSingleKeyQuery("id", id) + } + }); + } + /** + * Gets the shards of an EventSub conduit for the current client. + * + * @param conduitId The ID of the conduit to get shards for. + * @param status The status of the shards to filter by. + * @param pagination + */ + async getConduitShards(conduitId, status, pagination) { + const result = await this._client.callApi({ + type: "helix", + url: "eventsub/conduits/shards", + query: { + ...createEventSubConduitCondition(conduitId, status), + ...createPaginationQuery(pagination) + } + }); + return { + ...createPaginatedResult(result, HelixEventSubConduitShard, this._client) + }; + } + /** + * Creates a paginator for the shards of an EventSub conduit for the current client. + * + * @param conduitId The ID of the conduit to get shards for. + * @param status The status of the shards to filter by. + */ + getConduitShardsPaginated(conduitId, status) { + return new HelixPaginatedRequest({ + url: "eventsub/conduits/shards", + query: createEventSubConduitCondition(conduitId, status) + }, this._client, (data2) => new HelixEventSubConduitShard(data2)); + } + /** + * Updates shards of an EventSub conduit for the current client. + * + * @param conduitId The ID of the conduit to update shards for. + * @param shards List of shards to update + */ + async updateConduitShards(conduitId, shards) { + const result = await this._client.callApi({ + type: "helix", + url: "eventsub/conduits/shards", + method: "PATCH", + jsonBody: createEventSubConduitShardsUpdateCondition(conduitId, shards) + }); + return result.data.map((data2) => new HelixEventSubConduitShard(data2)); + } + async _deleteSubscriptionsWithCondition(cond) { + const subsPaginator = this.getSubscriptionsPaginated(); + for await (const sub of subsPaginator) { + if (!cond || cond(sub)) { + await sub.unsubscribe(); + } + } + } +}; +HelixEventSubApi = __decorate([ + rtfm("api", "HelixEventSubApi") +], HelixEventSubApi); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/extensions/HelixExtensionsApi.js +init_modules_watch_stub(); +init_performance2(); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/interfaces/endpoints/extensions.external.js +init_modules_watch_stub(); +init_performance2(); +function createReleasedExtensionFilter(extensionId, version3) { + return { + extension_id: extensionId, + extension_version: version3 + }; +} +__name(createReleasedExtensionFilter, "createReleasedExtensionFilter"); +function createExtensionProductBody(data2) { + return { + sku: data2.sku, + cost: { + amount: data2.cost, + type: "bits" + }, + display_name: data2.displayName, + in_development: data2.inDevelopment, + expiration: data2.expirationDate, + is_broadcast: data2.broadcast + }; +} +__name(createExtensionProductBody, "createExtensionProductBody"); +function createExtensionTransactionQuery(extensionId, filter) { + return { + extension_id: extensionId, + id: filter.transactionIds + }; +} +__name(createExtensionTransactionQuery, "createExtensionTransactionQuery"); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/channel/HelixChannelReference.js +init_modules_watch_stub(); +init_performance2(); +var HelixChannelReference = class HelixChannelReference2 extends DataObject { + static { + __name(this, "HelixChannelReference"); + } + /** @internal */ + _client; + /** @internal */ + constructor(data2, client) { + super(data2); + this._client = client; + } + /** + * The ID of the channel. + */ + get id() { + return this[rawDataSymbol].broadcaster_id; + } + /** + * The display name of the channel. + */ + get displayName() { + return this[rawDataSymbol].broadcaster_name; + } + /** + * Gets more information about the channel. + */ + async getChannel() { + return checkRelationAssertion(await this._client.channels.getChannelInfoById(this[rawDataSymbol].broadcaster_id)); + } + /** + * Gets more information about the broadcaster of the channel. + */ + async getBroadcaster() { + return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].broadcaster_id)); + } + /** + * The ID of the game currently played on the channel. + */ + get gameId() { + return this[rawDataSymbol].game_id; + } + /** + * The name of the game currently played on the channel. + */ + get gameName() { + return this[rawDataSymbol].game_name; + } + /** + * Gets information about the game that is being played on the stream. + */ + async getGame() { + return this[rawDataSymbol].game_id ? checkRelationAssertion(await this._client.games.getGameById(this[rawDataSymbol].game_id)) : null; + } + /** + * The title of the channel. + */ + get title() { + return this[rawDataSymbol].title; + } +}; +__decorate([ + Enumerable(false) +], HelixChannelReference.prototype, "_client", void 0); +HelixChannelReference = __decorate([ + rtfm("api", "HelixChannelReference", "id") +], HelixChannelReference); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/extensions/HelixExtensionBitsProduct.js +init_modules_watch_stub(); +init_performance2(); +var HelixExtensionBitsProduct = class HelixExtensionBitsProduct2 extends DataObject { + static { + __name(this, "HelixExtensionBitsProduct"); + } + /** + * The product's unique identifier. + */ + get sku() { + return this[rawDataSymbol].sku; + } + /** + * The product's cost, in bits. + */ + get cost() { + return this[rawDataSymbol].cost.amount; + } + /** + * The product's display name. + */ + get displayName() { + return this[rawDataSymbol].display_name; + } + /** + * Whether the product is in development. + */ + get inDevelopment() { + return this[rawDataSymbol].in_development; + } + /** + * Whether the product's purchases is broadcast to all users. + */ + get isBroadcast() { + return this[rawDataSymbol].is_broadcast; + } + /** + * The product's expiration date. If the product never expires, this is null. + */ + get expirationDate() { + return mapNullable(this[rawDataSymbol].expiration, (exp) => new Date(exp)); + } +}; +HelixExtensionBitsProduct = __decorate([ + rtfm("api", "HelixExtensionBitsProduct", "sku") +], HelixExtensionBitsProduct); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/extensions/HelixExtensionTransaction.js +init_modules_watch_stub(); +init_performance2(); +var HelixExtensionTransaction = class HelixExtensionTransaction2 extends DataObject { + static { + __name(this, "HelixExtensionTransaction"); + } + /** @internal */ + _client; + /** @internal */ + constructor(data2, client) { + super(data2); + this._client = client; + } + /** + * The ID of the transaction. + */ + get id() { + return this[rawDataSymbol].id; + } + /** + * The time when the transaction was made. + */ + get transactionDate() { + return new Date(this[rawDataSymbol].timestamp); + } + /** + * The ID of the broadcaster that runs the extension on their channel. + */ + get broadcasterId() { + return this[rawDataSymbol].broadcaster_id; + } + /** + * The name of the broadcaster that runs the extension on their channel. + */ + get broadcasterName() { + return this[rawDataSymbol].broadcaster_name; + } + /** + * The display name of the broadcaster that runs the extension on their channel. + */ + get broadcasterDisplayName() { + return this[rawDataSymbol].broadcaster_name; + } + /** + * Gets information about the broadcaster that runs the extension on their channel. + */ + async getBroadcaster() { + return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].broadcaster_id)); + } + /** + * The ID of the user that made the transaction. + */ + get userId() { + return this[rawDataSymbol].user_id; + } + /** + * The name of the user that made the transaction. + */ + get userName() { + return this[rawDataSymbol].user_login; + } + /** + * The display name of the user that made the transaction. + */ + get userDisplayName() { + return this[rawDataSymbol].user_name; + } + /** + * Gets information about the user that made the transaction. + */ + async getUser() { + return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].user_id)); + } + /** + * The product type. Currently always BITS_IN_EXTENSION. + */ + get productType() { + return this[rawDataSymbol].product_type; + } + /** + * The product SKU. + */ + get productSku() { + return this[rawDataSymbol].product_data.sku; + } + /** + * The cost of the product, in bits. + */ + get productCost() { + return this[rawDataSymbol].product_data.cost.amount; + } + /** + * The display name of the product. + */ + get productDisplayName() { + return this[rawDataSymbol].product_data.displayName; + } + /** + * Whether the product is in development. + */ + get productInDevelopment() { + return this[rawDataSymbol].product_data.inDevelopment; + } +}; +__decorate([ + Enumerable(false) +], HelixExtensionTransaction.prototype, "_client", void 0); +HelixExtensionTransaction = __decorate([ + rtfm("api", "HelixExtensionTransaction", "id") +], HelixExtensionTransaction); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/extensions/HelixExtensionsApi.js +var HelixExtensionsApi = class HelixExtensionsApi2 extends BaseApi { + static { + __name(this, "HelixExtensionsApi"); + } + /** + * Gets a released extension by ID. + * + * @param extensionId The ID of the extension. + * @param version The version of the extension. If not given, gets the latest version. + */ + async getReleasedExtension(extensionId, version3) { + const result = await this._client.callApi({ + type: "helix", + url: "extensions/released", + query: createReleasedExtensionFilter(extensionId, version3) + }); + return new HelixExtension(result.data[0]); + } + /** + * Gets a list of channels that are currently live and have the given extension installed. + * + * @param extensionId The ID of the extension. + * @param pagination + * + * @expandParams + */ + async getLiveChannelsWithExtension(extensionId, pagination) { + const result = await this._client.callApi({ + type: "helix", + url: "extensions/live", + query: { + ...createSingleKeyQuery("extension_id", extensionId), + ...createPaginationQuery(pagination) + } + }); + return createPaginatedResult(result, HelixChannelReference, this._client); + } + /** + * Creates a paginator for channels that are currently live and have the given extension installed. + * + * @param extensionId The ID of the extension. + */ + getLiveChannelsWithExtensionPaginated(extensionId) { + return new HelixPaginatedRequest({ + url: "extensions/live", + query: createSingleKeyQuery("extension_id", extensionId) + }, this._client, (data2) => new HelixChannelReference(data2, this._client)); + } + /** + * Gets an extension's Bits products. + * + * This only works if the provided token belongs to an extension's client ID, + * and will return the products for that extension. + * + * @param includeDisabled Whether to include disabled/expired products. + */ + async getExtensionBitsProducts(includeDisabled) { + const result = await this._client.callApi({ + type: "helix", + url: "bits/extensions", + forceType: "app", + query: createSingleKeyQuery("should_include_all", includeDisabled?.toString()) + }); + return result.data.map((data2) => new HelixExtensionBitsProduct(data2)); + } + /** + * Creates or updates a Bits product of an extension. + * + * This only works if the provided token belongs to an extension's client ID, + * and will create/update a product for that extension. + * + * @param data + * + * @expandParams + */ + async putExtensionBitsProduct(data2) { + const result = await this._client.callApi({ + type: "helix", + url: "bits/extensions", + method: "PUT", + forceType: "app", + jsonBody: createExtensionProductBody(data2) + }); + return new HelixExtensionBitsProduct(result.data[0]); + } + /** + * Gets a list of transactions for the given extension. + * + * @param extensionId The ID of the extension to get transactions for. + * @param filter Additional filters. + */ + async getExtensionTransactions(extensionId, filter = {}) { + const result = await this._client.callApi({ + type: "helix", + url: "extensions/transactions", + forceType: "app", + query: { + ...createExtensionTransactionQuery(extensionId, filter), + ...createPaginationQuery(filter) + } + }); + return createPaginatedResult(result, HelixExtensionTransaction, this._client); + } + /** + * Creates a paginator for transactions for the given extension. + * + * @param extensionId The ID of the extension to get transactions for. + * @param filter Additional filters. + */ + getExtensionTransactionsPaginated(extensionId, filter = {}) { + return new HelixPaginatedRequest({ + url: "extensions/transactions", + forceType: "app", + query: createExtensionTransactionQuery(extensionId, filter) + }, this._client, (data2) => new HelixExtensionTransaction(data2, this._client)); + } +}; +HelixExtensionsApi = __decorate([ + rtfm("api", "HelixExtensionsApi") +], HelixExtensionsApi); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/game/HelixGameApi.js +init_modules_watch_stub(); +init_performance2(); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/game/HelixGame.js +init_modules_watch_stub(); +init_performance2(); +var HelixGame = class HelixGame2 extends DataObject { + static { + __name(this, "HelixGame"); + } + /** @internal */ + _client; + /** @internal */ + constructor(data2, client) { + super(data2); + this._client = client; + } + /** + * The ID of the game. + */ + get id() { + return this[rawDataSymbol].id; + } + /** + * The name of the game. + */ + get name() { + return this[rawDataSymbol].name; + } + /** + * The URL of the box art of the game. + */ + get boxArtUrl() { + return this[rawDataSymbol].box_art_url; + } + /** + * The IGDB ID of the game, or null if the game doesn't have an IGDB ID assigned at Twitch. + */ + get igdbId() { + return this[rawDataSymbol].igdb_id || null; + } + /** + * Builds the URL of the box art of the game using the given dimensions. + * + * @param width The width of the box art. + * @param height The height of the box art. + */ + getBoxArtUrl(width, height) { + return this[rawDataSymbol].box_art_url.replace("{width}", width.toString()).replace("{height}", height.toString()); + } + /** + * Gets streams that are currently playing the game. + * + * @param pagination + * @expandParams + */ + async getStreams(pagination) { + return await this._client.streams.getStreams({ ...pagination, game: this[rawDataSymbol].id }); + } + /** + * Creates a paginator for streams that are currently playing the game. + */ + getStreamsPaginated() { + return this._client.streams.getStreamsPaginated({ game: this[rawDataSymbol].id }); + } +}; +__decorate([ + Enumerable(false) +], HelixGame.prototype, "_client", void 0); +HelixGame = __decorate([ + rtfm("api", "HelixGame", "id") +], HelixGame); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/game/HelixGameApi.js +var HelixGameApi = class HelixGameApi2 extends BaseApi { + static { + __name(this, "HelixGameApi"); + } + /** @internal */ + _getGameByIdBatcher = new HelixRequestBatcher({ + url: "games" + }, "id", "id", this._client, (data2) => new HelixGame(data2, this._client)); + /** @internal */ + _getGameByNameBatcher = new HelixRequestBatcher({ + url: "games" + }, "name", "name", this._client, (data2) => new HelixGame(data2, this._client)); + /** @internal */ + _getGameByIgdbIdBatcher = new HelixRequestBatcher({ + url: "games" + }, "igdb_id", "igdb_id", this._client, (data2) => new HelixGame(data2, this._client)); + /** + * Gets the game data for the given list of game IDs. + * + * @param ids The game IDs you want to look up. + */ + async getGamesByIds(ids) { + return await this._getGames("id", ids); + } + /** + * Gets the game data for the given list of game names. + * + * @param names The game names you want to look up. + */ + async getGamesByNames(names) { + return await this._getGames("name", names); + } + /** + * Gets the game data for the given list of IGDB IDs. + * + * @param igdbIds The IGDB IDs you want to look up. + */ + async getGamesByIgdbIds(igdbIds) { + return await this._getGames("igdb_id", igdbIds); + } + /** + * Gets the game data for the given game ID. + * + * @param id The game ID you want to look up. + */ + async getGameById(id) { + const games = await this._getGames("id", [id]); + return games[0] ?? null; + } + /** + * Gets the game data for the given game name. + * + * @param name The game name you want to look up. + */ + async getGameByName(name) { + const games = await this._getGames("name", [name]); + return games[0] ?? null; + } + /** + * Gets the game data for the given IGDB ID. + * + * @param igdbId The IGDB ID you want to look up. + */ + async getGameByIgdbId(igdbId) { + const games = await this._getGames("igdb_id", [igdbId]); + return games[0] ?? null; + } + /** + * Gets the game data for the given game ID, batching multiple calls into fewer requests as the API allows. + * + * @param id The game ID you want to look up. + */ + async getGameByIdBatched(id) { + return await this._getGameByIdBatcher.request(id); + } + /** + * Gets the game data for the given game name, batching multiple calls into fewer requests as the API allows. + * + * @param name The game name you want to look up. + */ + async getGameByNameBatched(name) { + return await this._getGameByNameBatcher.request(name); + } + /** + * Gets the game data for the given IGDB ID, batching multiple calls into fewer requests as the API allows. + * + * @param igdbId The IGDB ID you want to look up. + */ + async getGameByIgdbIdBatched(igdbId) { + return await this._getGameByIgdbIdBatcher.request(igdbId); + } + /** + * Gets a list of the most viewed games at the moment. + * + * @param pagination + * + * @expandParams + */ + async getTopGames(pagination) { + const result = await this._client.callApi({ + type: "helix", + url: "games/top", + query: createPaginationQuery(pagination) + }); + return createPaginatedResult(result, HelixGame, this._client); + } + /** + * Creates a paginator for the most viewed games at the moment. + */ + getTopGamesPaginated() { + return new HelixPaginatedRequest({ + url: "games/top" + }, this._client, (data2) => new HelixGame(data2, this._client)); + } + /** @internal */ + async _getGames(filterType, filterValues) { + if (!filterValues.length) { + return []; + } + const result = await this._client.callApi({ + type: "helix", + url: "games", + query: { + [filterType]: filterValues + } + }); + return result.data.map((entry) => new HelixGame(entry, this._client)); + } +}; +__decorate([ + Enumerable(false) +], HelixGameApi.prototype, "_getGameByIdBatcher", void 0); +__decorate([ + Enumerable(false) +], HelixGameApi.prototype, "_getGameByNameBatcher", void 0); +__decorate([ + Enumerable(false) +], HelixGameApi.prototype, "_getGameByIgdbIdBatcher", void 0); +HelixGameApi = __decorate([ + rtfm("api", "HelixGameApi") +], HelixGameApi); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/goals/HelixGoalApi.js +init_modules_watch_stub(); +init_performance2(); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/goals/HelixGoal.js +init_modules_watch_stub(); +init_performance2(); +var HelixGoal = class HelixGoal2 extends DataObject { + static { + __name(this, "HelixGoal"); + } + /** @internal */ + _client; + /** @internal */ + constructor(data2, client) { + super(data2); + this._client = client; + } + /** + * The ID of the goal. + */ + get id() { + return this[rawDataSymbol].id; + } + /** + * The ID of the broadcaster the goal belongs to. + */ + get broadcasterId() { + return this[rawDataSymbol].broadcaster_id; + } + /** + * The display name of the broadcaster the goal belongs to. + */ + get broadcasterDisplayName() { + return this[rawDataSymbol].broadcaster_name; + } + /** + * The name of the broadcaster the goal belongs to. + */ + get broadcasterName() { + return this[rawDataSymbol].broadcaster_login; + } + /** + * Gets more information about the broadcaster. + */ + async getBroadcaster() { + return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].broadcaster_id)); + } + /** + * The type of the goal. + */ + get type() { + return this[rawDataSymbol].type; + } + /** + * The description of the goal. + */ + get description() { + return this[rawDataSymbol].description; + } + /** + * The current value of the goal. + */ + get currentAmount() { + return this[rawDataSymbol].current_amount; + } + /** + * The target value of the goal. + */ + get targetAmount() { + return this[rawDataSymbol].target_amount; + } + /** + * The date and time when the goal was created. + */ + get creationDate() { + return this[rawDataSymbol].created_at; + } +}; +__decorate([ + Enumerable(false) +], HelixGoal.prototype, "_client", void 0); +HelixGoal = __decorate([ + rtfm("api", "HelixGoal", "id") +], HelixGoal); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/goals/HelixGoalApi.js +var HelixGoalApi = class HelixGoalApi2 extends BaseApi { + static { + __name(this, "HelixGoalApi"); + } + async getGoals(broadcaster) { + const result = await this._client.callApi({ + type: "helix", + url: "goals", + userId: extractUserId(broadcaster), + scopes: ["channel:read:goals"], + query: createBroadcasterQuery(broadcaster) + }); + return result.data.map((data2) => new HelixGoal(data2, this._client)); + } +}; +HelixGoalApi = __decorate([ + rtfm("api", "HelixGoalApi") +], HelixGoalApi); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/hypeTrain/HelixHypeTrainApi.js +init_modules_watch_stub(); +init_performance2(); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/hypeTrain/HelixHypeTrainStatus.js +init_modules_watch_stub(); +init_performance2(); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/hypeTrain/HelixHypeTrain.js +init_modules_watch_stub(); +init_performance2(); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/hypeTrain/HelixHypeTrainContribution.js +init_modules_watch_stub(); +init_performance2(); +var HelixHypeTrainContribution = class HelixHypeTrainContribution2 extends DataObject { + static { + __name(this, "HelixHypeTrainContribution"); + } + /** @internal */ + _client; + /** @internal */ + constructor(data2, client) { + super(data2); + this._client = client; + } + /** + * The ID of the user contributing to the Hype Train. + */ + get userId() { + return this[rawDataSymbol].user_id; + } + /** + * The name of the user contributing to the Hype Train. + */ + get userName() { + return this[rawDataSymbol].user_login; + } + /** + * The display name of the user contributing to the Hype Train. + */ + get userDisplayName() { + return this[rawDataSymbol].user_name; + } + /** + * Gets additional information about the user contributing to the Hype Train. + */ + async getUser() { + return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].user_id)); + } + /** + * The type of the Hype Train contribution. + */ + get type() { + return this[rawDataSymbol].type; + } + /** + * The total contribution amount in subs or bits. + */ + get total() { + return this[rawDataSymbol].total; + } +}; +__decorate([ + Enumerable(false) +], HelixHypeTrainContribution.prototype, "_client", void 0); +HelixHypeTrainContribution = __decorate([ + rtfm("api", "HelixHypeTrainContribution", "userId") +], HelixHypeTrainContribution); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/hypeTrain/HelixHypeTrain.js +var HelixHypeTrain = class HelixHypeTrain2 extends DataObject { + static { + __name(this, "HelixHypeTrain"); + } + /** @internal */ + _client; + /** @internal */ + constructor(data2, client) { + super(data2); + this._client = client; + } + /** + * The unique ID of the Hype Train event. + */ + get eventId() { + return this[rawDataSymbol].id; + } + /** + * The unique ID of the Hype Train. + */ + get id() { + return this[rawDataSymbol].id; + } + /** + * The user ID of the broadcaster where the Hype Train is happening. + */ + get broadcasterId() { + return this[rawDataSymbol].broadcaster_user_id; + } + /** + * The name of the broadcaster where the Hype Train is happening. + */ + get broadcasterName() { + return this[rawDataSymbol].broadcaster_user_login; + } + /** + * The display name of the broadcaster where the Hype Train is happening. + */ + get broadcasterDisplayName() { + return this[rawDataSymbol].broadcaster_user_name; + } + /** + * Gets more information about the broadcaster where the Hype Train is happening. + */ + async getBroadcaster() { + return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].broadcaster_user_id)); + } + /** + * The level of the Hype Train. + */ + get level() { + return this[rawDataSymbol].level; + } + /** + * The total amount of progress points of the Hype Train. + */ + get total() { + return this[rawDataSymbol].total; + } + /** + * The amount progress points for the current level of the Hype Train. + */ + get progress() { + return this[rawDataSymbol].progress; + } + /** + * The progress points goal to reach the next Hype Train level. + */ + get goal() { + return this[rawDataSymbol].goal; + } + /** + * Array list of the top contributions to the Hype Train event for bits and subs. + */ + get topContributions() { + return this[rawDataSymbol].top_contributions.map((cont) => new HelixHypeTrainContribution(cont, this._client)); + } + /** + * The time when the Hype Train started. + */ + get startDate() { + return new Date(this[rawDataSymbol].started_at); + } + /** + * The time when the Hype Train is set to expire. + */ + get expiryDate() { + return new Date(this[rawDataSymbol].expires_at); + } + /** + * The type of the Hype Train. + */ + get type() { + return this[rawDataSymbol].type; + } + /** + * Whether the Hype Train is a shared train. + */ + get isSharedTrain() { + return this[rawDataSymbol].is_shared_train; + } +}; +__decorate([ + Enumerable(false) +], HelixHypeTrain.prototype, "_client", void 0); +HelixHypeTrain = __decorate([ + rtfm("api", "HelixHypeTrain", "id") +], HelixHypeTrain); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/hypeTrain/HelixHypeTrainAllTimeHigh.js +init_modules_watch_stub(); +init_performance2(); +var HelixHypeTrainAllTimeHigh = class HelixHypeTrainAllTimeHigh2 extends DataObject { + static { + __name(this, "HelixHypeTrainAllTimeHigh"); + } + /** + * The level reached by the all-time-high Hype Train. + */ + get level() { + return this[rawDataSymbol].level; + } + /** + * The total amount of contribution points reached by the all-time-high Hype Train. + */ + get total() { + return this[rawDataSymbol].total; + } + /** + * The time when the all-time-high Hype Train was achieved. + */ + get achievementDate() { + return new Date(this[rawDataSymbol].achieved_at); + } +}; +HelixHypeTrainAllTimeHigh = __decorate([ + rtfm("api", "HelixHypeTrainAllTimeHigh") +], HelixHypeTrainAllTimeHigh); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/hypeTrain/HelixHypeTrainStatus.js +var HelixHypeTrainStatus = class HelixHypeTrainStatus2 extends DataObject { + static { + __name(this, "HelixHypeTrainStatus"); + } + /** @internal */ + _client; + /** @internal */ + constructor(data2, client) { + super(data2); + this._client = client; + } + /** + * The current Hype Train, or null if there is no ongoing Hype Train. + */ + get current() { + return mapNullable(this[rawDataSymbol].current, (data2) => new HelixHypeTrain(data2, this._client)); + } + /** + * The all-time-high Hype Train statistics for this channel, or null if there was no Hype Train yet. + */ + get allTimeHigh() { + return mapNullable(this[rawDataSymbol].all_time_high, (data2) => new HelixHypeTrainAllTimeHigh(data2)); + } + /** + * The all-time-high shared Hype Train statistics for this channel, or null if there was no shared Hype Train yet. + */ + get sharedAllTimeHigh() { + return mapNullable(this[rawDataSymbol].shared_all_time_high, (data2) => new HelixHypeTrainAllTimeHigh(data2)); + } +}; +__decorate([ + Enumerable(false) +], HelixHypeTrainStatus.prototype, "_client", void 0); +HelixHypeTrainStatus = __decorate([ + rtfm("api", "HelixHypeTrainStatus") +], HelixHypeTrainStatus); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/hypeTrain/HelixHypeTrainApi.js +var HelixHypeTrainApi = class extends BaseApi { + static { + __name(this, "HelixHypeTrainApi"); + } + /** + * Gets the Hype Train status and statistics for the specified broadcaster. + * + * @param broadcaster The broadcaster to fetch Hype Train info for. + */ + async getHypeTrainStatusForBroadcaster(broadcaster) { + const result = await this._client.callApi({ + type: "helix", + url: "hypetrain/status", + userId: extractUserId(broadcaster), + scopes: ["channel:read:hype_train"], + query: { + ...createBroadcasterQuery(broadcaster) + } + }); + return new HelixHypeTrainStatus(result.data[0], this._client); + } +}; + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/moderation/HelixModerationApi.js +init_modules_watch_stub(); +init_performance2(); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/interfaces/endpoints/moderation.external.js +init_modules_watch_stub(); +init_performance2(); +function createModerationUserListQuery(channel, filter) { + return { + broadcaster_id: extractUserId(channel), + user_id: filter?.userId + }; +} +__name(createModerationUserListQuery, "createModerationUserListQuery"); +function createModeratorModifyQuery(broadcaster, user) { + return { + broadcaster_id: extractUserId(broadcaster), + user_id: extractUserId(user) + }; +} +__name(createModeratorModifyQuery, "createModeratorModifyQuery"); +function createResolveUnbanRequestQuery(broadcaster, moderator, unbanRequestId, approved, resolutionMessage) { + return { + unban_request_id: unbanRequestId, + broadcaster_id: extractUserId(broadcaster), + moderator_id: extractUserId(moderator), + status: approved ? "approved" : "denied", + resolution_text: resolutionMessage + }; +} +__name(createResolveUnbanRequestQuery, "createResolveUnbanRequestQuery"); +function createAutoModProcessBody(user, msgId, allow) { + return { + user_id: extractUserId(user), + msg_id: msgId, + action: allow ? "ALLOW" : "DENY" + }; +} +__name(createAutoModProcessBody, "createAutoModProcessBody"); +function createAutoModSettingsBody(data2) { + return { + overall_level: data2.overallLevel, + aggression: data2.aggression, + bullying: data2.bullying, + disability: data2.disability, + misogyny: data2.misogyny, + race_ethnicity_or_religion: data2.raceEthnicityOrReligion, + sex_based_terms: data2.sexBasedTerms, + sexuality_sex_or_gender: data2.sexualitySexOrGender, + swearing: data2.swearing + }; +} +__name(createAutoModSettingsBody, "createAutoModSettingsBody"); +function createBanUserBody(data2) { + return { + data: { + duration: data2.duration, + reason: data2.reason, + user_id: extractUserId(data2.user) + } + }; +} +__name(createBanUserBody, "createBanUserBody"); +function createUpdateShieldModeStatusBody(activate) { + return { + is_active: activate + }; +} +__name(createUpdateShieldModeStatusBody, "createUpdateShieldModeStatusBody"); +function createCheckAutoModStatusBody(data2) { + return { + data: data2.map((entry) => ({ + msg_id: entry.messageId, + msg_text: entry.messageText + })) + }; +} +__name(createCheckAutoModStatusBody, "createCheckAutoModStatusBody"); +function createWarnUserBody(user, reason) { + return { + data: { + user_id: extractUserId(user), + reason + } + }; +} +__name(createWarnUserBody, "createWarnUserBody"); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/moderation/HelixAutoModSettings.js +init_modules_watch_stub(); +init_performance2(); +var HelixAutoModSettings = class HelixAutoModSettings2 extends DataObject { + static { + __name(this, "HelixAutoModSettings"); + } + /** + * The ID of the broadcaster for which the AutoMod settings were fetched. + */ + get broadcasterId() { + return this[rawDataSymbol].broadcaster_id; + } + /** + * The ID of a user that has permission to moderate the broadcaster's chat room. + */ + get moderatorId() { + return this[rawDataSymbol].moderator_id; + } + /** + * The default AutoMod level for the broadcaster. This is null if the broadcaster changed individual settings. + */ + get overallLevel() { + return this[rawDataSymbol].overall_level ? this[rawDataSymbol].overall_level : null; + } + /** + * The AutoMod level for discrimination against disability. + */ + get disability() { + return this[rawDataSymbol].disability; + } + /** + * The AutoMod level for hostility involving aggression. + */ + get aggression() { + return this[rawDataSymbol].aggression; + } + /** + * The AutoMod level for discrimination based on sexuality, sex, or gender. + */ + get sexualitySexOrGender() { + return this[rawDataSymbol].sexuality_sex_or_gender; + } + /** + * The AutoMod level for discrimination against women. + */ + get misogyny() { + return this[rawDataSymbol].misogyny; + } + /** + * The AutoMod level for hostility involving name calling or insults. + */ + get bullying() { + return this[rawDataSymbol].bullying; + } + /** + * The AutoMod level for profanity. + */ + get swearing() { + return this[rawDataSymbol].swearing; + } + /** + * The AutoMod level for racial discrimination. + */ + get raceEthnicityOrReligion() { + return this[rawDataSymbol].race_ethnicity_or_religion; + } + /** + * The AutoMod level for sexual content. + */ + get sexBasedTerms() { + return this[rawDataSymbol].sex_based_terms; + } +}; +HelixAutoModSettings = __decorate([ + rtfm("api", "HelixAutoModSettings", "broadcasterId") +], HelixAutoModSettings); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/moderation/HelixAutoModStatus.js +init_modules_watch_stub(); +init_performance2(); +var HelixAutoModStatus = class HelixAutoModStatus2 extends DataObject { + static { + __name(this, "HelixAutoModStatus"); + } + /** + * The developer-generated ID that was sent with the request data. + */ + get messageId() { + return this[rawDataSymbol].msg_id; + } + /** + * Whether the message is permitted by AutoMod or not. + */ + get isPermitted() { + return this[rawDataSymbol].is_permitted; + } +}; +HelixAutoModStatus = __decorate([ + rtfm("api", "HelixAutoModStatus", "messageId") +], HelixAutoModStatus); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/moderation/HelixBan.js +init_modules_watch_stub(); +init_performance2(); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/moderation/HelixBanUser.js +init_modules_watch_stub(); +init_performance2(); +var HelixBanUser = class HelixBanUser2 extends DataObject { + static { + __name(this, "HelixBanUser"); + } + /** @internal */ + _client; + /** @internal */ + _expiryTimestamp; + /** @internal */ + constructor(data2, expiryTimestamp, client) { + super(data2); + this._expiryTimestamp = expiryTimestamp; + this._client = client; + } + /** + * The date and time that the ban/timeout was created. + */ + get creationDate() { + return new Date(this[rawDataSymbol].created_at); + } + /** + * The date and time that the timeout will end. Is `null` if the user was banned instead of put in a timeout. + */ + get expiryDate() { + return mapNullable(this._expiryTimestamp, (ts) => new Date(ts)); + } + /** + * The ID of the moderator that banned or put the user in the timeout. + */ + get moderatorId() { + return this[rawDataSymbol].moderator_id; + } + /** + * Gets more information about the moderator that banned or put the user in the timeout. + */ + async getModerator() { + return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].moderator_id)); + } + /** + * The ID of the user that was banned or put in a timeout. + */ + get userId() { + return this[rawDataSymbol].user_id; + } + /** + * Gets more information about the user that was banned or put in a timeout. + */ + async getUser() { + return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].user_id)); + } +}; +__decorate([ + Enumerable(false) +], HelixBanUser.prototype, "_client", void 0); +__decorate([ + Enumerable(false) +], HelixBanUser.prototype, "_expiryTimestamp", void 0); +HelixBanUser = __decorate([ + rtfm("api", "HelixBanUser", "userId") +], HelixBanUser); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/moderation/HelixBan.js +var HelixBan = class HelixBan2 extends HelixBanUser { + static { + __name(this, "HelixBan"); + } + /** @internal */ + constructor(data2, client) { + super(data2, data2.expires_at || null, client); + } + /** + * The name of the user that was banned or put in a timeout. + */ + get userName() { + return this[rawDataSymbol].user_login; + } + /** + * The display name of the user that was banned or put in a timeout. + */ + get userDisplayName() { + return this[rawDataSymbol].user_name; + } + /** + * The name of the moderator that banned or put the user in the timeout. + */ + get moderatorName() { + return this[rawDataSymbol].moderator_login; + } + /** + * The display name of the moderator that banned or put the user in the timeout. + */ + get moderatorDisplayName() { + return this[rawDataSymbol].moderator_name; + } + /** + * The reason why the user was banned or timed out. Returns `null` if no reason was given. + */ + get reason() { + return this[rawDataSymbol].reason || null; + } +}; +HelixBan = __decorate([ + rtfm("api", "HelixBan", "userId") +], HelixBan); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/moderation/HelixBlockedTerm.js +init_modules_watch_stub(); +init_performance2(); +var HelixBlockedTerm = class HelixBlockedTerm2 extends DataObject { + static { + __name(this, "HelixBlockedTerm"); + } + /** + * The ID of the broadcaster that owns the list of blocked terms. + */ + get broadcasterId() { + return this[rawDataSymbol].broadcaster_id; + } + /** + * The date and time of when the term was blocked. + */ + get creationDate() { + return new Date(this[rawDataSymbol].created_at); + } + /** + * The date and time of when the blocked term is set to expire. After the block expires, users will be able to use the term in the broadcaster’s chat room. + * Is `null` if the term was added manually or permanently blocked by AutoMod. + */ + get expirationDate() { + return this[rawDataSymbol].expires_at ? new Date(this[rawDataSymbol].expires_at) : null; + } + /** + * An ID that uniquely identifies this blocked term. + */ + get id() { + return this[rawDataSymbol].id; + } + /** + * The ID of the moderator that blocked the word or phrase from being used in the broadcaster’s chat room. + */ + get moderatorId() { + return this[rawDataSymbol].moderator_id; + } + /** + * The blocked word or phrase. + */ + get text() { + return this[rawDataSymbol].text; + } + /** + * The date and time of when the term was updated. + */ + get updatedDate() { + return new Date(this[rawDataSymbol].updated_at); + } +}; +HelixBlockedTerm = __decorate([ + rtfm("api", "HelixBlockedTerm", "id") +], HelixBlockedTerm); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/moderation/HelixModeratedChannel.js +init_modules_watch_stub(); +init_performance2(); +var HelixModeratedChannel = class HelixModeratedChannel2 extends DataObject { + static { + __name(this, "HelixModeratedChannel"); + } + /** @internal */ + _client; + /** @internal */ + constructor(data2, client) { + super(data2); + this._client = client; + } + /** + * The ID of the channel. + */ + get id() { + return this[rawDataSymbol].broadcaster_id; + } + /** + * The name of the channel. + */ + get name() { + return this[rawDataSymbol].broadcaster_login; + } + /** + * The display name of the channel. + */ + get displayName() { + return this[rawDataSymbol].broadcaster_name; + } + /** + * Gets more information about the channel. + */ + async getChannel() { + return checkRelationAssertion(await this._client.channels.getChannelInfoById(this[rawDataSymbol].broadcaster_id)); + } + /** + * Gets more information about the broadcaster of the channel. + */ + async getBroadcaster() { + return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].broadcaster_id)); + } +}; +__decorate([ + Enumerable(false) +], HelixModeratedChannel.prototype, "_client", void 0); +HelixModeratedChannel = __decorate([ + rtfm("api", "HelixModeratedChannel", "id") +], HelixModeratedChannel); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/moderation/HelixModerator.js +init_modules_watch_stub(); +init_performance2(); +var HelixModerator = class HelixModerator2 extends DataObject { + static { + __name(this, "HelixModerator"); + } + /** @internal */ + _client; + /** @internal */ + constructor(data2, client) { + super(data2); + this._client = client; + } + /** + * The ID of the user. + */ + get userId() { + return this[rawDataSymbol].user_id; + } + /** + * The name of the user. + */ + get userName() { + return this[rawDataSymbol].user_login; + } + /** + * The display name of the user. + */ + get userDisplayName() { + return this[rawDataSymbol].user_name; + } + /** + * Gets more information about the user. + */ + async getUser() { + return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].user_id)); + } +}; +__decorate([ + Enumerable(false) +], HelixModerator.prototype, "_client", void 0); +HelixModerator = __decorate([ + rtfm("api", "HelixModerator", "userId") +], HelixModerator); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/moderation/HelixShieldModeStatus.js +init_modules_watch_stub(); +init_performance2(); +var HelixShieldModeStatus = class HelixShieldModeStatus2 extends DataObject { + static { + __name(this, "HelixShieldModeStatus"); + } + /** @internal */ + _client; + /** @internal */ + constructor(data2, client) { + super(data2); + this._client = client; + } + /** + * Whether Shield Mode is active. + */ + get isActive() { + return this[rawDataSymbol].is_active; + } + /** + * The ID of the moderator that last activated Shield Mode. + */ + get moderatorId() { + return this[rawDataSymbol].moderator_id; + } + /** + * The name of the moderator that last activated Shield Mode. + */ + get moderatorName() { + return this[rawDataSymbol].moderator_login; + } + /** + * The display name of the moderator that last activated Shield Mode. + */ + get moderatorDisplayName() { + return this[rawDataSymbol].moderator_name; + } + /** + * Gets more information about the moderator that last activated Shield Mode. + */ + async getModerator() { + return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].moderator_id)); + } + /** + * The date when Shield Mode was last activated. `null` indicates Shield Mode hasn't been previously activated. + */ + get lastActivationDate() { + return this[rawDataSymbol].last_activated_at === "" ? null : new Date(this[rawDataSymbol].last_activated_at); + } +}; +__decorate([ + Enumerable(false) +], HelixShieldModeStatus.prototype, "_client", void 0); +HelixShieldModeStatus = __decorate([ + rtfm("api", "HelixShieldModeStatus") +], HelixShieldModeStatus); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/moderation/HelixUnbanRequest.js +init_modules_watch_stub(); +init_performance2(); +var HelixUnbanRequest = class HelixUnbanRequest2 extends DataObject { + static { + __name(this, "HelixUnbanRequest"); + } + /** @internal */ + _client; + /** @internal */ + constructor(data2, client) { + super(data2); + this._client = client; + } + /** + * Unban request ID. + */ + get id() { + return this[rawDataSymbol].id; + } + /** + * The ID of the broadcaster whose channel is receiving the unban request. + */ + get broadcasterId() { + return this[rawDataSymbol].broadcaster_id; + } + /** + * The name of the broadcaster whose channel is receiving the unban request. + */ + get broadcasterName() { + return this[rawDataSymbol].broadcaster_id; + } + /** + * The display name of the broadcaster whose channel is receiving the unban request. + */ + get broadcasterDisplayName() { + return this[rawDataSymbol].broadcaster_id; + } + /** + * Gets more information about the broadcaster. + */ + async getBroadcaster() { + return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].broadcaster_id)); + } + /** + * The ID of the moderator who resolved the unban request. + * + * Can be `null` if the request is not resolved. + */ + get moderatorId() { + return this[rawDataSymbol].moderator_id; + } + /** + * The name of the moderator who resolved the unban request. + * + * Can be `null` if the request is not resolved. + */ + get moderatorName() { + return this[rawDataSymbol].moderator_login; + } + /** + * The display name of the moderator who resolved the unban request. + * + * Can be `null` if the request is not resolved. + */ + get moderatorDisplayName() { + return this[rawDataSymbol].moderator_name; + } + /** + * Gets more information about the moderator. + */ + async getModerator() { + return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].moderator_id)); + } + /** + * The ID of the user who requested to be unbanned. + */ + get userId() { + return this[rawDataSymbol].user_id; + } + /** + * The name of the user who requested to be unbanned. + */ + get userName() { + return this[rawDataSymbol].user_login; + } + /** + * The display name of the user who requested to be unbanned. + */ + get userDisplayName() { + return this[rawDataSymbol].user_name; + } + /** + * Gets more information about the user. + */ + async getUser() { + return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].user_id)); + } + /** + * Text message of the unban request from the requesting user. + */ + get message() { + return this[rawDataSymbol].text; + } + /** + * The date of when the unban request was created. + */ + get creationDate() { + return new Date(this[rawDataSymbol].created_at); + } + /** + * The message written by the moderator who resolved the unban request, or `null` if it has not been resolved yet. + */ + get resolutionMessage() { + return this[rawDataSymbol].resolution_text || null; + } + /** + * The date when the unban request was resolved, or `null` if it has not been resolved yet. + */ + get resolutionDate() { + return mapNullable(this[rawDataSymbol].resolved_at, (val) => new Date(val)); + } +}; +__decorate([ + Enumerable(false) +], HelixUnbanRequest.prototype, "_client", void 0); +HelixUnbanRequest = __decorate([ + rtfm("api", "HelixUnbanRequest", "id") +], HelixUnbanRequest); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/moderation/HelixWarning.js +init_modules_watch_stub(); +init_performance2(); +var HelixWarning = class HelixWarning2 extends DataObject { + static { + __name(this, "HelixWarning"); + } + /** @internal */ + _client; + /** @internal */ + constructor(data2, client) { + super(data2); + this._client = client; + } + /** + * The ID of the channel in which the warning will take effect. + */ + get broadcasterId() { + return this[rawDataSymbol].user_id; + } + /** + * Gets more information about the broadcaster. + */ + async getBroadcaster() { + return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].broadcaster_id)); + } + /** + * The ID of the user who applied the warning. + */ + get moderatorId() { + return this[rawDataSymbol].moderator_id; + } + /** + * Gets more information about the moderator. + */ + async getModerator() { + return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].moderator_id)); + } + /** + * The ID of the warned user. + */ + get userId() { + return this[rawDataSymbol].user_id; + } + /** + * Gets more information about the user. + */ + async getUser() { + return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].user_id)); + } + /** + * The reason provided for the warning. + */ + get reason() { + return this[rawDataSymbol].reason; + } +}; +__decorate([ + Enumerable(false) +], HelixWarning.prototype, "_client", void 0); +HelixWarning = __decorate([ + rtfm("api", "HelixWarning", "userId") +], HelixWarning); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/moderation/HelixModerationApi.js +var HelixModerationApi = class HelixModerationApi2 extends BaseApi { + static { + __name(this, "HelixModerationApi"); + } + /** + * Gets a list of banned users in a given channel. + * + * @param channel The channel to get the banned users from. + * @param filter Additional filters for the result set. + * + * @expandParams + */ + async getBannedUsers(channel, filter) { + const result = await this._client.callApi({ + type: "helix", + url: "moderation/banned", + userId: extractUserId(channel), + scopes: ["moderation:read"], + query: { + ...createModerationUserListQuery(channel, filter), + ...createPaginationQuery(filter) + } + }); + return createPaginatedResult(result, HelixBan, this._client); + } + /** + * Creates a paginator for banned users in a given channel. + * + * @param channel The channel to get the banned users from. + */ + getBannedUsersPaginated(channel) { + return new HelixPaginatedRequest({ + url: "moderation/banned", + userId: extractUserId(channel), + scopes: ["moderation:read"], + query: createBroadcasterQuery(channel) + }, this._client, (data2) => new HelixBan(data2, this._client), 50); + } + /** + * Checks whether a given user is banned in a given channel. + * + * @param channel The channel to check for a ban of the given user. + * @param user The user to check for a ban in the given channel. + */ + async checkUserBan(channel, user) { + const userId = extractUserId(user); + const result = await this.getBannedUsers(channel, { userId }); + return result.data.some((ban) => ban.userId === userId); + } + /** + * Gets a list of moderators in a given channel. + * + * @param channel The channel to get moderators from. + * @param filter Additional filters for the result set. + * + * @expandParams + */ + async getModerators(channel, filter) { + const result = await this._client.callApi({ + type: "helix", + url: "moderation/moderators", + userId: extractUserId(channel), + scopes: ["moderation:read", "channel:manage:moderators"], + query: { + ...createModerationUserListQuery(channel, filter), + ...createPaginationQuery(filter) + } + }); + return createPaginatedResult(result, HelixModerator, this._client); + } + /** + * Creates a paginator for moderators in a given channel. + * + * @param channel The channel to get moderators from. + */ + getModeratorsPaginated(channel) { + return new HelixPaginatedRequest({ + url: "moderation/moderators", + userId: extractUserId(channel), + scopes: ["moderation:read", "channel:manage:moderators"], + query: createBroadcasterQuery(channel) + }, this._client, (data2) => new HelixModerator(data2, this._client)); + } + /** + * Gets a list of channels where the specified user has moderator privileges. + * + * @param user The user for whom to return a list of channels where they have moderator privileges. + * This ID must match the user ID in the access token. + * @param filter + * + * @expandParams + * + * @returns A paginated list of channels where the user has moderator privileges. + */ + async getModeratedChannels(user, filter) { + const userId = extractUserId(user); + const result = await this._client.callApi({ + type: "helix", + url: "moderation/channels", + userId, + scopes: ["user:read:moderated_channels"], + query: { + ...createSingleKeyQuery("user_id", userId), + ...createPaginationQuery(filter) + } + }); + return createPaginatedResult(result, HelixModeratedChannel, this._client); + } + /** + * Creates a paginator for channels where the specified user has moderator privileges. + * + * @param user The user for whom to return the list of channels where they have moderator privileges. + * This ID must match the user ID in the access token. + */ + getModeratedChannelsPaginated(user) { + const userId = extractUserId(user); + return new HelixPaginatedRequest({ + url: "moderation/channels", + userId, + scopes: ["user:read:moderated_channels"], + query: createSingleKeyQuery("user_id", userId) + }, this._client, (data2) => new HelixModeratedChannel(data2, this._client)); + } + /** + * Checks whether a given user is a moderator of a given channel. + * + * @param channel The channel to check. + * @param user The user to check. + */ + async checkUserMod(channel, user) { + const userId = extractUserId(user); + const result = await this.getModerators(channel, { userId }); + return result.data.some((mod) => mod.userId === userId); + } + /** + * Adds a moderator to the broadcaster’s chat room. + * + * @param broadcaster The broadcaster that owns the chat room. This ID must match the user ID in the access token. + * @param user The user to add as a moderator in the broadcaster’s chat room. + */ + async addModerator(broadcaster, user) { + await this._client.callApi({ + type: "helix", + url: "moderation/moderators", + method: "POST", + userId: extractUserId(broadcaster), + scopes: ["channel:manage:moderators"], + query: createModeratorModifyQuery(broadcaster, user) + }); + } + /** + * Removes a moderator from the broadcaster’s chat room. + * + * @param broadcaster The broadcaster that owns the chat room. This ID must match the user ID in the access token. + * @param user The user to remove as a moderator from the broadcaster’s chat room. + */ + async removeModerator(broadcaster, user) { + await this._client.callApi({ + type: "helix", + url: "moderation/moderators", + method: "DELETE", + userId: extractUserId(broadcaster), + scopes: ["channel:manage:moderators"], + query: createModeratorModifyQuery(broadcaster, user) + }); + } + /** + * Determines whether a string message meets the channel's AutoMod requirements. + * + * @param channel The channel in which the messages to check are posted. + * @param data An array of message data objects. + */ + async checkAutoModStatus(channel, data2) { + const result = await this._client.callApi({ + type: "helix", + url: "moderation/enforcements/status", + method: "POST", + userId: extractUserId(channel), + scopes: ["moderation:read"], + query: createBroadcasterQuery(channel), + jsonBody: createCheckAutoModStatusBody(data2) + }); + return result.data.map((statusData) => new HelixAutoModStatus(statusData)); + } + /** + * Processes a message held by AutoMod. + * + * @param user The user who is processing the message. + * @param msgId The ID of the message. + * @param allow Whether to allow the message - `true` allows, and `false` denies. + */ + async processHeldAutoModMessage(user, msgId, allow) { + await this._client.callApi({ + type: "helix", + url: "moderation/automod/message", + method: "POST", + userId: extractUserId(user), + scopes: ["moderator:manage:automod"], + jsonBody: createAutoModProcessBody(user, msgId, allow) + }); + } + /** + * Gets the AutoMod settings for a broadcaster. + * + * This uses the token of the broadcaster by default. + * If you want to execute this in the context of another user (who has to be moderator of the channel) + * you can do so using [user context overrides](/docs/auth/concepts/context-switching). + * + * @param broadcaster The broadcaster to get the AutoMod settings for. + */ + async getAutoModSettings(broadcaster) { + const broadcasterId = extractUserId(broadcaster); + const result = await this._client.callApi({ + type: "helix", + url: "moderation/automod/settings", + userId: broadcasterId, + scopes: ["moderator:read:automod_settings"], + canOverrideScopedUserContext: true, + query: this._createModeratorActionQuery(broadcasterId) + }); + return result.data.map((data2) => new HelixAutoModSettings(data2)); + } + /** + * Updates the AutoMod settings for a broadcaster. + * + * This uses the token of the broadcaster by default. + * If you want to execute this in the context of another user (who has to be moderator of the channel) + * you can do so using [user context overrides](/docs/auth/concepts/context-switching). + * + * @param broadcaster The broadcaster for which the AutoMod settings are updated. + * @param data The updated AutoMod settings that replace the current AutoMod settings. + */ + async updateAutoModSettings(broadcaster, data2) { + const broadcasterId = extractUserId(broadcaster); + const result = await this._client.callApi({ + type: "helix", + url: "moderation/automod/settings", + method: "PUT", + userId: broadcasterId, + scopes: ["moderator:manage:automod_settings"], + canOverrideScopedUserContext: true, + query: this._createModeratorActionQuery(broadcasterId), + jsonBody: createAutoModSettingsBody(data2) + }); + return result.data.map((settingsData) => new HelixAutoModSettings(settingsData)); + } + /** + * Bans or times out a user in a channel. + * + * This uses the token of the broadcaster by default. + * If you want to execute this in the context of another user (who has to be moderator of the channel) + * you can do so using [user context overrides](/docs/auth/concepts/context-switching). + * + * @param broadcaster The broadcaster in whose channel the user will be banned/timed out. + * @param data + * + * @expandParams + * + * @returns The result data from the ban/timeout request. + */ + async banUser(broadcaster, data2) { + const broadcasterId = extractUserId(broadcaster); + const result = await this._client.callApi({ + type: "helix", + url: "moderation/bans", + method: "POST", + userId: broadcasterId, + scopes: ["moderator:manage:banned_users"], + canOverrideScopedUserContext: true, + query: this._createModeratorActionQuery(broadcasterId), + jsonBody: createBanUserBody(data2) + }); + return result.data.map((banData) => new HelixBanUser(banData, banData.end_time, this._client)); + } + /** + * Unbans/removes the timeout for a user in a channel. + * + * This uses the token of the broadcaster by default. + * If you want to execute this in the context of another user (who has to be moderator of the channel) + * you can do so using [user context overrides](/docs/auth/concepts/context-switching). + * + * @param broadcaster The broadcaster in whose channel the user will be unbanned/removed from timeout. + * @param user The user who will be unbanned/removed from timeout. + */ + async unbanUser(broadcaster, user) { + const broadcasterId = extractUserId(broadcaster); + await this._client.callApi({ + type: "helix", + url: "moderation/bans", + method: "DELETE", + userId: broadcasterId, + scopes: ["moderator:manage:banned_users"], + canOverrideScopedUserContext: true, + query: { + ...this._createModeratorActionQuery(broadcasterId), + ...createSingleKeyQuery("user_id", extractUserId(user)) + } + }); + } + /** + * Gets the broadcaster’s list of non-private, blocked words or phrases. + * + * This uses the token of the broadcaster by default. + * If you want to execute this in the context of another user (who has to be moderator of the channel) + * you can do so using [user context overrides](/docs/auth/concepts/context-switching). + * + * @param broadcaster The broadcaster to get their channel's blocked terms for. + * @param pagination + * + * @expandParams + * + * @returns A paginated list of blocked term data in the broadcaster's channel. + */ + async getBlockedTerms(broadcaster, pagination) { + const broadcasterId = extractUserId(broadcaster); + const result = await this._client.callApi({ + type: "helix", + url: "moderation/blocked_terms", + userId: broadcasterId, + scopes: ["moderator:read:blocked_terms"], + canOverrideScopedUserContext: true, + query: { + ...this._createModeratorActionQuery(broadcasterId), + ...createPaginationQuery(pagination) + } + }); + return createPaginatedResult(result, HelixBlockedTerm, this._client); + } + /** + * Adds a blocked term to the broadcaster's channel. + * + * This uses the token of the broadcaster by default. + * If you want to execute this in the context of another user (who has to be moderator of the channel) + * you can do so using [user context overrides](/docs/auth/concepts/context-switching). + * + * @param broadcaster The broadcaster in whose channel the term will be blocked. + * @param text The word or phrase to block from being used in the broadcaster's channel. + * + * @returns Information about the term that has been blocked. + */ + async addBlockedTerm(broadcaster, text2) { + const broadcasterId = extractUserId(broadcaster); + const result = await this._client.callApi({ + type: "helix", + url: "moderation/blocked_terms", + method: "POST", + userId: broadcasterId, + scopes: ["moderator:manage:blocked_terms"], + canOverrideScopedUserContext: true, + query: this._createModeratorActionQuery(broadcasterId), + jsonBody: { + text: text2 + } + }); + return result.data.map((blockedTermData) => new HelixBlockedTerm(blockedTermData)); + } + /** + * Removes a blocked term from the broadcaster's channel. + * + * @param broadcaster The broadcaster in whose channel the term will be unblocked. + * @param moderator A user that has permission to unblock terms in the broadcaster's channel. + * The token of this user will be used to remove the blocked term. + * @param id The ID of the term that should be unblocked. + */ + async removeBlockedTerm(broadcaster, moderator, id) { + const broadcasterId = extractUserId(broadcaster); + await this._client.callApi({ + type: "helix", + url: "moderation/blocked_terms", + method: "DELETE", + userId: broadcasterId, + scopes: ["moderator:manage:blocked_terms"], + canOverrideScopedUserContext: true, + query: { + ...this._createModeratorActionQuery(broadcasterId), + id + } + }); + } + /** + * Removes a single chat message or all chat messages from the broadcaster’s chat room. + * + * This uses the token of the broadcaster by default. + * If you want to execute this in the context of another user (who has to be moderator of the channel) + * you can do so using [user context overrides](/docs/auth/concepts/context-switching). + * + * @param broadcaster The broadcaster the chat belongs to. + * @param messageId The ID of the message to remove. If not specified, the request removes all messages in the broadcaster’s chat room. + */ + async deleteChatMessages(broadcaster, messageId) { + const broadcasterId = extractUserId(broadcaster); + await this._client.callApi({ + type: "helix", + url: "moderation/chat", + method: "DELETE", + userId: broadcasterId, + scopes: ["moderator:manage:chat_messages"], + canOverrideScopedUserContext: true, + query: { + ...this._createModeratorActionQuery(broadcasterId), + ...createSingleKeyQuery("message_id", messageId) + } + }); + } + /** + * Gets the broadcaster's Shield Mode activation status. + * + * @param broadcaster The broadcaster whose Shield Mode activation status you want to get. + */ + async getShieldModeStatus(broadcaster) { + const broadcasterId = extractUserId(broadcaster); + const result = await this._client.callApi({ + type: "helix", + url: "moderation/shield_mode", + method: "GET", + userId: broadcasterId, + scopes: ["moderator:read:shield_mode", "moderator:manage:shield_mode"], + canOverrideScopedUserContext: true, + query: this._createModeratorActionQuery(broadcasterId) + }); + return new HelixShieldModeStatus(result.data[0], this._client); + } + /** + * Activates or deactivates the broadcaster's Shield Mode. + * + * This uses the token of the broadcaster by default. + * If you want to execute this in the context of another user (who has to be moderator of the channel) + * you can do so using [user context overrides](/docs/auth/concepts/context-switching). + * + * @param broadcaster The broadcaster whose Shield Mode you want to activate or deactivate. + * @param activate The desired Shield Mode status on the broadcaster's channel. + */ + async updateShieldModeStatus(broadcaster, activate) { + const broadcasterId = extractUserId(broadcaster); + const result = await this._client.callApi({ + type: "helix", + url: "moderation/shield_mode", + method: "PUT", + userId: broadcasterId, + scopes: ["moderator:manage:shield_mode"], + canOverrideScopedUserContext: true, + query: this._createModeratorActionQuery(broadcasterId), + jsonBody: createUpdateShieldModeStatusBody(activate) + }); + return new HelixShieldModeStatus(result.data[0], this._client); + } + /** + * Gets a list of unban requests. + * + * @param broadcaster The broadcaster to get unban requests of. + * @param status The status of unban requests to retrieve. + * @param filter Additional filters for the result set. + */ + async getUnbanRequests(broadcaster, status, filter) { + const broadcasterId = extractUserId(broadcaster); + const result = await this._client.callApi({ + type: "helix", + url: "moderation/unban_requests", + method: "GET", + userId: broadcasterId, + scopes: ["moderator:read:unban_requests", "moderator:manage:unban_requests"], + canOverrideScopedUserContext: true, + query: { + ...this._createModeratorActionQuery(broadcasterId), + ...createSingleKeyQuery("status", status), + ...createPaginationQuery(filter) + } + }); + return createPaginatedResult(result, HelixUnbanRequest, this._client); + } + /** + * Creates a paginator for unban requests. + * + * @param broadcaster The broadcaster to get unban requests of. + * @param status The status of unban requests to retrieve. + */ + getUnbanRequestsPaginated(broadcaster, status) { + const broadcasterId = extractUserId(broadcaster); + return new HelixPaginatedRequest({ + url: "moderation/unban_requests", + method: "GET", + userId: broadcasterId, + scopes: ["moderator:read:unban_requests", "moderator:manage:unban_requests"], + canOverrideScopedUserContext: true, + query: { + ...this._createModeratorActionQuery(broadcasterId), + ...createSingleKeyQuery("status", status) + } + }, this._client, (data2) => new HelixUnbanRequest(data2, this._client)); + } + /** + * Resolves an unban request by approving or denying it. + * + * This uses the token of the broadcaster by default. + * If you want to execute this in the context of another user (who has to be moderator of the channel) + * you can do so using [user context overrides](/docs/auth/concepts/context-switching). + * + * @param broadcaster The ID of the broadcaster whose channel is approving or denying the unban request. + * @param unbanRequestId The ID of the unban request to resolve. + * @param approved Whether to approve or deny the unban request. + * @param resolutionMessage Message supplied by the unban request resolver. + * + * The message is limited to a maximum of 500 characters. + */ + async resolveUnbanRequest(broadcaster, unbanRequestId, approved, resolutionMessage) { + const broadcasterId = extractUserId(broadcaster); + const result = await this._client.callApi({ + type: "helix", + url: "moderation/unban_requests", + method: "PATCH", + userId: broadcasterId, + scopes: ["moderator:manage:unban_requests"], + canOverrideScopedUserContext: true, + query: createResolveUnbanRequestQuery(broadcasterId, this._getUserContextIdWithDefault(broadcasterId), unbanRequestId, approved, resolutionMessage?.slice(0, 500)) + }); + return new HelixUnbanRequest(result.data[0], this._client); + } + /** + * Warns a user in the specified broadcaster’s chat room, preventing them from chat interaction until the + * warning is acknowledged. + * + * New warnings can be issued to a user when they already have a warning in the channel + * (new warning will replace old warning). + * + * @param broadcaster The ID of the broadcaster in which channel the warning will take effect. + * @param user The ID of the user to be warned. + * @param reason A custom reason for the warning. Max 500 chars. + */ + async warnUser(broadcaster, user, reason) { + const broadcasterId = extractUserId(broadcaster); + const result = await this._client.callApi({ + type: "helix", + url: "moderation/warnings", + method: "POST", + userId: broadcasterId, + scopes: ["moderator:manage:warnings"], + canOverrideScopedUserContext: true, + query: this._createModeratorActionQuery(broadcasterId), + jsonBody: createWarnUserBody(user, reason.slice(0, 500)) + }); + return new HelixWarning(result.data[0], this._client); + } + _createModeratorActionQuery(broadcasterId) { + return createModeratorActionQuery(broadcasterId, this._getUserContextIdWithDefault(broadcasterId)); + } +}; +HelixModerationApi = __decorate([ + rtfm("api", "HelixModerationApi") +], HelixModerationApi); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/poll/HelixPollApi.js +init_modules_watch_stub(); +init_performance2(); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/interfaces/endpoints/poll.external.js +init_modules_watch_stub(); +init_performance2(); +function createPollBody(broadcaster, data2) { + return { + broadcaster_id: extractUserId(broadcaster), + title: data2.title, + choices: data2.choices.map((title2) => ({ title: title2 })), + duration: data2.duration, + channel_points_voting_enabled: data2.channelPointsPerVote != null, + channel_points_per_vote: data2.channelPointsPerVote ?? 0 + }; +} +__name(createPollBody, "createPollBody"); +function createPollEndBody(broadcaster, id, showResult) { + return { + broadcaster_id: extractUserId(broadcaster), + id, + status: showResult ? "TERMINATED" : "ARCHIVED" + }; +} +__name(createPollEndBody, "createPollEndBody"); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/poll/HelixPoll.js +init_modules_watch_stub(); +init_performance2(); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/poll/HelixPollChoice.js +init_modules_watch_stub(); +init_performance2(); +var HelixPollChoice = class HelixPollChoice2 extends DataObject { + static { + __name(this, "HelixPollChoice"); + } + /** + * The ID of the choice. + */ + get id() { + return this[rawDataSymbol].id; + } + /** + * The title of the choice. + */ + get title() { + return this[rawDataSymbol].title; + } + /** + * The total votes the choice received. + */ + get totalVotes() { + return this[rawDataSymbol].votes; + } + /** + * The votes the choice received by spending channel points. + */ + get channelPointsVotes() { + return this[rawDataSymbol].channel_points_votes; + } +}; +HelixPollChoice = __decorate([ + rtfm("api", "HelixPollChoice", "id") +], HelixPollChoice); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/poll/HelixPoll.js +var HelixPoll = class HelixPoll2 extends DataObject { + static { + __name(this, "HelixPoll"); + } + /** @internal */ + _client; + /** @internal */ + constructor(data2, client) { + super(data2); + this._client = client; + } + /** + * The ID of the poll. + */ + get id() { + return this[rawDataSymbol].id; + } + /** + * The ID of the broadcaster. + */ + get broadcasterId() { + return this[rawDataSymbol].broadcaster_id; + } + /** + * The name of the broadcaster. + */ + get broadcasterName() { + return this[rawDataSymbol].broadcaster_login; + } + /** + * The display name of the broadcaster. + */ + get broadcasterDisplayName() { + return this[rawDataSymbol].broadcaster_name; + } + /** + * Gets more information about the broadcaster. + */ + async getBroadcaster() { + return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].broadcaster_id)); + } + /** + * The title of the poll. + */ + get title() { + return this[rawDataSymbol].title; + } + /** + * Whether voting with channel points is enabled for the poll. + */ + get isChannelPointsVotingEnabled() { + return this[rawDataSymbol].channel_points_voting_enabled; + } + /** + * The amount of channel points that a vote costs. + */ + get channelPointsPerVote() { + return this[rawDataSymbol].channel_points_per_vote; + } + /** + * The status of the poll. + */ + get status() { + return this[rawDataSymbol].status; + } + /** + * The duration of the poll, in seconds. + */ + get durationInSeconds() { + return this[rawDataSymbol].duration; + } + /** + * The date when the poll started. + */ + get startDate() { + return new Date(this[rawDataSymbol].started_at); + } + /** + * The date when the poll ended or will end. + */ + get endDate() { + return new Date(this.startDate.getTime() + this[rawDataSymbol].duration * 1e3); + } + /** + * The choices of the poll. + */ + get choices() { + return this[rawDataSymbol].choices.map((data2) => new HelixPollChoice(data2)); + } +}; +__decorate([ + Enumerable(false) +], HelixPoll.prototype, "_client", void 0); +HelixPoll = __decorate([ + rtfm("api", "HelixPoll", "id") +], HelixPoll); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/poll/HelixPollApi.js +var HelixPollApi = class HelixPollApi2 extends BaseApi { + static { + __name(this, "HelixPollApi"); + } + /** + * Gets a list of polls for the given broadcaster. + * + * @param broadcaster The broadcaster to get polls for. + * @param pagination + * + * @expandParams + */ + async getPolls(broadcaster, pagination) { + const result = await this._client.callApi({ + type: "helix", + url: "polls", + userId: extractUserId(broadcaster), + scopes: ["channel:read:polls", "channel:manage:polls"], + query: { + ...createBroadcasterQuery(broadcaster), + ...createPaginationQuery(pagination) + } + }); + return createPaginatedResult(result, HelixPoll, this._client); + } + /** + * Creates a paginator for polls for the given broadcaster. + * + * @param broadcaster The broadcaster to get polls for. + */ + getPollsPaginated(broadcaster) { + return new HelixPaginatedRequest({ + url: "polls", + userId: extractUserId(broadcaster), + scopes: ["channel:read:polls", "channel:manage:polls"], + query: createBroadcasterQuery(broadcaster) + }, this._client, (data2) => new HelixPoll(data2, this._client), 20); + } + /** + * Gets polls by IDs. + * + * @param broadcaster The broadcaster to get the polls for. + * @param ids The IDs of the polls. + */ + async getPollsByIds(broadcaster, ids) { + if (!ids.length) { + return []; + } + const result = await this._client.callApi({ + type: "helix", + url: "polls", + userId: extractUserId(broadcaster), + scopes: ["channel:read:polls", "channel:manage:polls"], + query: createGetByIdsQuery(broadcaster, ids) + }); + return result.data.map((data2) => new HelixPoll(data2, this._client)); + } + /** + * Gets a poll by ID. + * + * @param broadcaster The broadcaster to get the poll for. + * @param id The ID of the poll. + */ + async getPollById(broadcaster, id) { + const polls = await this.getPollsByIds(broadcaster, [id]); + return polls.length ? polls[0] : null; + } + /** + * Creates a new poll. + * + * @param broadcaster The broadcaster to create the poll for. + * @param data + * + * @expandParams + */ + async createPoll(broadcaster, data2) { + const result = await this._client.callApi({ + type: "helix", + url: "polls", + method: "POST", + userId: extractUserId(broadcaster), + scopes: ["channel:manage:polls"], + jsonBody: createPollBody(broadcaster, data2) + }); + return new HelixPoll(result.data[0], this._client); + } + /** + * Ends a poll. + * + * @param broadcaster The broadcaster to end the poll for. + * @param id The ID of the poll to end. + * @param showResult Whether to allow the result to be viewed publicly. + */ + async endPoll(broadcaster, id, showResult = true) { + const result = await this._client.callApi({ + type: "helix", + url: "polls", + method: "PATCH", + userId: extractUserId(broadcaster), + scopes: ["channel:manage:polls"], + jsonBody: createPollEndBody(broadcaster, id, showResult) + }); + return new HelixPoll(result.data[0], this._client); + } +}; +HelixPollApi = __decorate([ + rtfm("api", "HelixPollApi") +], HelixPollApi); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/prediction/HelixPredictionApi.js +init_modules_watch_stub(); +init_performance2(); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/interfaces/endpoints/prediction.external.js +init_modules_watch_stub(); +init_performance2(); +function createPredictionBody(broadcaster, data2) { + return { + broadcaster_id: extractUserId(broadcaster), + title: data2.title, + outcomes: data2.outcomes.map((title2) => ({ title: title2 })), + prediction_window: data2.autoLockAfter + }; +} +__name(createPredictionBody, "createPredictionBody"); +function createEndPredictionBody(broadcaster, id, status, outcomeId) { + return { + broadcaster_id: extractUserId(broadcaster), + id, + status, + winning_outcome_id: outcomeId + }; +} +__name(createEndPredictionBody, "createEndPredictionBody"); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/prediction/HelixPrediction.js +init_modules_watch_stub(); +init_performance2(); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/prediction/HelixPredictionOutcome.js +init_modules_watch_stub(); +init_performance2(); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/prediction/HelixPredictor.js +init_modules_watch_stub(); +init_performance2(); +var HelixPredictor = class HelixPredictor2 extends DataObject { + static { + __name(this, "HelixPredictor"); + } + /** @internal */ + _client; + /** @internal */ + constructor(data2, client) { + super(data2); + this._client = client; + } + /** + * The user ID of the predictor. + */ + get userId() { + return this[rawDataSymbol].user_id; + } + /** + * The name of the predictor. + */ + get userName() { + return this[rawDataSymbol].user_login; + } + /** + * The display name of the predictor. + */ + get userDisplayName() { + return this[rawDataSymbol].user_name; + } + /** + * Gets more information about the predictor. + */ + async getUser() { + return await this._client.users.getUserById(this[rawDataSymbol].user_id); + } + /** + * The amount of channel points the predictor used for the prediction. + */ + get channelPointsUsed() { + return this[rawDataSymbol].channel_points_used; + } + /** + * The amount of channel points the predictor won for the prediction, or null if the prediction is not resolved yet, was cancelled or lost. + */ + get channelPointsWon() { + return this[rawDataSymbol].channel_points_won; + } +}; +__decorate([ + Enumerable(false) +], HelixPredictor.prototype, "_client", void 0); +HelixPredictor = __decorate([ + rtfm("api", "HelixPredictor", "userId") +], HelixPredictor); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/prediction/HelixPredictionOutcome.js +var HelixPredictionOutcome = class HelixPredictionOutcome2 extends DataObject { + static { + __name(this, "HelixPredictionOutcome"); + } + /** @internal */ + _client; + /** @internal */ + constructor(data2, client) { + super(data2); + this._client = client; + } + /** + * The ID of the outcome. + */ + get id() { + return this[rawDataSymbol].id; + } + /** + * The title of the outcome. + */ + get title() { + return this[rawDataSymbol].title; + } + /** + * The number of users that guessed the outcome. + */ + get users() { + return this[rawDataSymbol].users; + } + /** + * The total number of channel points that were spent on guessing the outcome. + */ + get totalChannelPoints() { + return this[rawDataSymbol].channel_points; + } + /** + * The color of the outcome. + */ + get color() { + return this[rawDataSymbol].color; + } + /** + * The top predictors of the outcome. + */ + get topPredictors() { + return this[rawDataSymbol].top_predictors?.map((data2) => new HelixPredictor(data2, this._client)) ?? []; + } +}; +__decorate([ + Enumerable(false) +], HelixPredictionOutcome.prototype, "_client", void 0); +HelixPredictionOutcome = __decorate([ + rtfm("api", "HelixPredictionOutcome", "id") +], HelixPredictionOutcome); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/prediction/HelixPrediction.js +var HelixPrediction = class HelixPrediction2 extends DataObject { + static { + __name(this, "HelixPrediction"); + } + /** @internal */ + _client; + /** @internal */ + constructor(data2, client) { + super(data2); + this._client = client; + } + /** + * The ID of the prediction. + */ + get id() { + return this[rawDataSymbol].id; + } + /** + * The ID of the broadcaster. + */ + get broadcasterId() { + return this[rawDataSymbol].broadcaster_id; + } + /** + * The name of the broadcaster. + */ + get broadcasterName() { + return this[rawDataSymbol].broadcaster_login; + } + /** + * The display name of the broadcaster. + */ + get broadcasterDisplayName() { + return this[rawDataSymbol].broadcaster_name; + } + /** + * Gets more information about the broadcaster. + */ + async getBroadcaster() { + return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].broadcaster_id)); + } + /** + * The title of the prediction. + */ + get title() { + return this[rawDataSymbol].title; + } + /** + * The status of the prediction. + */ + get status() { + return this[rawDataSymbol].status; + } + /** + * The time after which the prediction will be automatically locked, in seconds from creation. + */ + get autoLockAfter() { + return this[rawDataSymbol].prediction_window; + } + /** + * The date when the prediction started. + */ + get creationDate() { + return new Date(this[rawDataSymbol].created_at); + } + /** + * The date when the prediction ended, or null if it didn't end yet. + */ + get endDate() { + return this[rawDataSymbol].ended_at ? new Date(this[rawDataSymbol].ended_at) : null; + } + /** + * The date when the prediction was locked, or null if it wasn't locked yet. + */ + get lockDate() { + return this[rawDataSymbol].locked_at ? new Date(this[rawDataSymbol].locked_at) : null; + } + /** + * The possible outcomes of the prediction. + */ + get outcomes() { + return this[rawDataSymbol].outcomes.map((data2) => new HelixPredictionOutcome(data2, this._client)); + } + /** + * The ID of the winning outcome, or null if the prediction is currently running or was canceled. + */ + get winningOutcomeId() { + return this[rawDataSymbol].winning_outcome_id || null; + } + /** + * The winning outcome, or null if the prediction is currently running or was canceled. + */ + get winningOutcome() { + if (!this[rawDataSymbol].winning_outcome_id) { + return null; + } + const found = this[rawDataSymbol].outcomes.find((o) => o.id === this[rawDataSymbol].winning_outcome_id); + if (!found) { + throw new HellFreezesOverError("Winning outcome not found in outcomes array"); + } + return new HelixPredictionOutcome(found, this._client); + } +}; +__decorate([ + Enumerable(false) +], HelixPrediction.prototype, "_client", void 0); +HelixPrediction = __decorate([ + rtfm("api", "HelixPrediction", "id") +], HelixPrediction); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/prediction/HelixPredictionApi.js +var HelixPredictionApi = class HelixPredictionApi2 extends BaseApi { + static { + __name(this, "HelixPredictionApi"); + } + /** + * Gets a list of predictions for the given broadcaster. + * + * @param broadcaster The broadcaster to get predictions for. + * @param pagination + * + * @expandParams + */ + async getPredictions(broadcaster, pagination) { + const result = await this._client.callApi({ + type: "helix", + url: "predictions", + userId: extractUserId(broadcaster), + scopes: ["channel:read:predictions"], + query: { + ...createBroadcasterQuery(broadcaster), + ...createPaginationQuery(pagination) + } + }); + return createPaginatedResult(result, HelixPrediction, this._client); + } + /** + * Creates a paginator for predictions for the given broadcaster. + * + * @param broadcaster The broadcaster to get predictions for. + */ + getPredictionsPaginated(broadcaster) { + return new HelixPaginatedRequest({ + url: "predictions", + userId: extractUserId(broadcaster), + scopes: ["channel:read:predictions"], + query: createBroadcasterQuery(broadcaster) + }, this._client, (data2) => new HelixPrediction(data2, this._client), 20); + } + /** + * Gets predictions by IDs. + * + * @param broadcaster The broadcaster to get the predictions for. + * @param ids The IDs of the predictions. + */ + async getPredictionsByIds(broadcaster, ids) { + if (!ids.length) { + return []; + } + const result = await this._client.callApi({ + type: "helix", + url: "predictions", + userId: extractUserId(broadcaster), + scopes: ["channel:read:predictions"], + query: createGetByIdsQuery(broadcaster, ids) + }); + return result.data.map((data2) => new HelixPrediction(data2, this._client)); + } + /** + * Gets a prediction by ID. + * + * @param broadcaster The broadcaster to get the prediction for. + * @param id The ID of the prediction. + */ + async getPredictionById(broadcaster, id) { + const predictions = await this.getPredictionsByIds(broadcaster, [id]); + return predictions.length ? predictions[0] : null; + } + /** + * Creates a new prediction. + * + * @param broadcaster The broadcaster to create the prediction for. + * @param data + * + * @expandParams + */ + async createPrediction(broadcaster, data2) { + const result = await this._client.callApi({ + type: "helix", + url: "predictions", + method: "POST", + userId: extractUserId(broadcaster), + scopes: ["channel:manage:predictions"], + jsonBody: createPredictionBody(broadcaster, data2) + }); + return new HelixPrediction(result.data[0], this._client); + } + /** + * Locks a prediction. + * + * @param broadcaster The broadcaster to lock the prediction for. + * @param id The ID of the prediction to lock. + */ + async lockPrediction(broadcaster, id) { + return await this._endPrediction(broadcaster, id, "LOCKED"); + } + /** + * Resolves a prediction. + * + * @param broadcaster The broadcaster to resolve the prediction for. + * @param id The ID of the prediction to resolve. + * @param outcomeId The ID of the winning outcome. + */ + async resolvePrediction(broadcaster, id, outcomeId) { + return await this._endPrediction(broadcaster, id, "RESOLVED", outcomeId); + } + /** + * Cancels a prediction. + * + * @param broadcaster The broadcaster to cancel the prediction for. + * @param id The ID of the prediction to cancel. + */ + async cancelPrediction(broadcaster, id) { + return await this._endPrediction(broadcaster, id, "CANCELED"); + } + async _endPrediction(broadcaster, id, status, outcomeId) { + const result = await this._client.callApi({ + type: "helix", + url: "predictions", + method: "PATCH", + userId: extractUserId(broadcaster), + scopes: ["channel:manage:predictions"], + jsonBody: createEndPredictionBody(broadcaster, id, status, outcomeId) + }); + return new HelixPrediction(result.data[0], this._client); + } +}; +HelixPredictionApi = __decorate([ + rtfm("api", "HelixPredictionApi") +], HelixPredictionApi); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/raids/HelixRaidApi.js +init_modules_watch_stub(); +init_performance2(); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/interfaces/endpoints/raid.external.js +init_modules_watch_stub(); +init_performance2(); +function createRaidStartQuery(from, to) { + return { + from_broadcaster_id: extractUserId(from), + to_broadcaster_id: extractUserId(to) + }; +} +__name(createRaidStartQuery, "createRaidStartQuery"); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/raids/HelixRaid.js +init_modules_watch_stub(); +init_performance2(); +var HelixRaid = class HelixRaid2 extends DataObject { + static { + __name(this, "HelixRaid"); + } + /** + * The date when the raid was initiated. + */ + get creationDate() { + return new Date(this[rawDataSymbol].created_at); + } + /** + * Whether the raid target channel is intended for mature audiences. + */ + get targetIsMature() { + return this[rawDataSymbol].is_mature; + } +}; +HelixRaid = __decorate([ + rtfm("api", "HelixRaid") +], HelixRaid); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/raids/HelixRaidApi.js +var HelixRaidApi = class HelixRaidApi2 extends BaseApi { + static { + __name(this, "HelixRaidApi"); + } + /** + * Initiate a raid from a live broadcaster to another live broadcaster. + * + * @param from The raiding broadcaster. + * @param to The raid target. + */ + async startRaid(from, to) { + const result = await this._client.callApi({ + type: "helix", + url: "raids", + method: "POST", + userId: extractUserId(from), + scopes: ["channel:manage:raids"], + query: createRaidStartQuery(from, to) + }); + return new HelixRaid(result.data[0]); + } + /** + * Cancels an initiated raid. + * + * @param from The raiding broadcaster. + */ + async cancelRaid(from) { + await this._client.callApi({ + type: "helix", + url: "raids", + method: "DELETE", + userId: extractUserId(from), + scopes: ["channel:manage:raids"], + query: createBroadcasterQuery(from) + }); + } +}; +HelixRaidApi = __decorate([ + rtfm("api", "HelixRaidApi") +], HelixRaidApi); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/schedule/HelixScheduleApi.js +init_modules_watch_stub(); +init_performance2(); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/interfaces/endpoints/schedule.external.js +init_modules_watch_stub(); +init_performance2(); +function createScheduleQuery(broadcaster, filter) { + return { + broadcaster_id: extractUserId(broadcaster), + start_time: filter?.startDate, + utc_offset: filter?.utcOffset?.toString() + }; +} +__name(createScheduleQuery, "createScheduleQuery"); +function createScheduleSettingsUpdateQuery(broadcaster, settings) { + if (settings.vacation) { + return { + broadcaster_id: extractUserId(broadcaster), + is_vacation_enabled: "true", + vacation_start_time: settings.vacation.startDate, + vacation_end_time: settings.vacation.endDate, + timezone: settings.vacation.timezone + }; + } + return { + broadcaster_id: extractUserId(broadcaster), + is_vacation_enabled: "false" + }; +} +__name(createScheduleSettingsUpdateQuery, "createScheduleSettingsUpdateQuery"); +function createScheduleSegmentBody(data2) { + return { + start_time: data2.startDate, + timezone: data2.timezone, + is_recurring: data2.isRecurring, + duration: data2.duration, + category_id: data2.categoryId, + title: data2.title + }; +} +__name(createScheduleSegmentBody, "createScheduleSegmentBody"); +function createScheduleSegmentModifyQuery(broadcaster, segmentId) { + return { + broadcaster_id: extractUserId(broadcaster), + id: segmentId + }; +} +__name(createScheduleSegmentModifyQuery, "createScheduleSegmentModifyQuery"); +function createScheduleSegmentUpdateBody(data2) { + return { + start_time: data2.startDate, + timezone: data2.timezone, + is_canceled: data2.isCanceled, + duration: data2.duration, + category_id: data2.categoryId, + title: data2.title + }; +} +__name(createScheduleSegmentUpdateBody, "createScheduleSegmentUpdateBody"); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/schedule/HelixPaginatedScheduleSegmentRequest.js +init_modules_watch_stub(); +init_performance2(); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/schedule/HelixScheduleSegment.js +init_modules_watch_stub(); +init_performance2(); +var HelixScheduleSegment = class HelixScheduleSegment2 extends DataObject { + static { + __name(this, "HelixScheduleSegment"); + } + /** @internal */ + _client; + /** @internal */ + constructor(data2, client) { + super(data2); + this._client = client; + } + /** + * The ID of the segment. + */ + get id() { + return this[rawDataSymbol].id; + } + /** + * The date when the segment starts. + */ + get startDate() { + return new Date(this[rawDataSymbol].start_time); + } + /** + * The date when the segment ends. + */ + get endDate() { + return new Date(this[rawDataSymbol].end_time); + } + /** + * The title of the segment. + */ + get title() { + return this[rawDataSymbol].title; + } + /** + * The date up to which the segment is canceled. + */ + get cancelEndDate() { + return mapNullable(this[rawDataSymbol].canceled_until, (v) => new Date(v)); + } + /** + * The ID of the category the segment is scheduled for, or null if no category is specified. + */ + get categoryId() { + return this[rawDataSymbol].category?.id ?? null; + } + /** + * The name of the category the segment is scheduled for, or null if no category is specified. + */ + get categoryName() { + return this[rawDataSymbol].category?.name ?? null; + } + /** + * Gets more information about the category the segment is scheduled for, or null if no category is specified. + */ + async getCategory() { + const categoryId = this[rawDataSymbol].category?.id; + return categoryId ? await this._client.games.getGameById(categoryId) : null; + } + /** + * Whether the segment is recurring every week. + */ + get isRecurring() { + return this[rawDataSymbol].is_recurring; + } +}; +__decorate([ + Enumerable(false) +], HelixScheduleSegment.prototype, "_client", void 0); +HelixScheduleSegment = __decorate([ + rtfm("api", "HelixScheduleSegment", "id") +], HelixScheduleSegment); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/schedule/HelixPaginatedScheduleSegmentRequest.js +var HelixPaginatedScheduleSegmentRequest = class HelixPaginatedScheduleSegmentRequest2 extends HelixPaginatedRequest { + static { + __name(this, "HelixPaginatedScheduleSegmentRequest"); + } + /** @internal */ + constructor(broadcaster, client, filter) { + super({ + url: "schedule", + query: createScheduleQuery(broadcaster, filter) + }, client, (data2) => new HelixScheduleSegment(data2, client), 25); + } + // sadly, this hack is necessary to work around the weird data model of schedules + // while still keeping the pagination code as generic as possible + /** @internal */ + async _fetchData(additionalOptions = {}) { + const origData = await super._fetchData(additionalOptions); + return { + data: origData.data.segments ?? [], + pagination: origData.pagination + }; + } +}; +HelixPaginatedScheduleSegmentRequest = __decorate([ + rtfm("api", "HelixPaginatedScheduleSegmentRequest") +], HelixPaginatedScheduleSegmentRequest); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/schedule/HelixSchedule.js +init_modules_watch_stub(); +init_performance2(); +var HelixSchedule = class HelixSchedule2 extends DataObject { + static { + __name(this, "HelixSchedule"); + } + /** @internal */ + _client; + /** @internal */ + constructor(data2, client) { + super(data2); + this._client = client; + } + /** + * The segments of the schedule. + */ + get segments() { + return this[rawDataSymbol].segments?.map((data2) => new HelixScheduleSegment(data2, this._client)) ?? []; + } + /** + * The ID of the broadcaster. + */ + get broadcasterId() { + return this[rawDataSymbol].broadcaster_id; + } + /** + * The name of the broadcaster. + */ + get broadcasterName() { + return this[rawDataSymbol].broadcaster_login; + } + /** + * The display name of the broadcaster. + */ + get broadcasterDisplayName() { + return this[rawDataSymbol].broadcaster_name; + } + /** + * Gets more information about the broadcaster. + */ + async getBroadcaster() { + return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].broadcaster_id)); + } + /** + * The date when the current vacation started, or null if the schedule is not in vacation mode. + */ + get vacationStartDate() { + const timestamp = this[rawDataSymbol].vacation?.start_time; + return timestamp ? new Date(timestamp) : null; + } + /** + * The date when the current vacation ends, or null if the schedule is not in vacation mode. + */ + get vacationEndDate() { + const timestamp = this[rawDataSymbol].vacation?.end_time; + return timestamp ? new Date(timestamp) : null; + } +}; +__decorate([ + Enumerable(false) +], HelixSchedule.prototype, "_client", void 0); +HelixSchedule = __decorate([ + rtfm("api", "HelixSchedule", "broadcasterId") +], HelixSchedule); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/schedule/HelixScheduleApi.js +var HelixScheduleApi = class extends BaseApi { + static { + __name(this, "HelixScheduleApi"); + } + /** + * Gets the schedule for a given broadcaster. + * + * @param broadcaster The broadcaster to get the schedule of. + * @param filter + * + * @expandParams + */ + async getSchedule(broadcaster, filter) { + const result = await this._client.callApi({ + type: "helix", + url: "schedule", + userId: extractUserId(broadcaster), + query: { + ...createScheduleQuery(broadcaster, filter), + ...createPaginationQuery(filter) + } + }); + return { + data: new HelixSchedule(result.data, this._client), + cursor: result.pagination.cursor + }; + } + /** + * Creates a paginator for schedule segments for a given broadcaster. + * + * @param broadcaster The broadcaster to get the schedule segments of. + * @param filter + * + * @expandParams + */ + getScheduleSegmentsPaginated(broadcaster, filter) { + return new HelixPaginatedScheduleSegmentRequest(broadcaster, this._client, filter); + } + /** + * Gets a set of schedule segments by IDs. + * + * @param broadcaster The broadcaster to get schedule segments of. + * @param ids The IDs of the schedule segments. + */ + async getScheduleSegmentsByIds(broadcaster, ids) { + const result = await this._client.callApi({ + type: "helix", + url: "schedule", + userId: extractUserId(broadcaster), + query: createGetByIdsQuery(broadcaster, ids) + }); + return result.data.segments?.map((data2) => new HelixScheduleSegment(data2, this._client)) ?? []; + } + /** + * Gets a single schedule segment by ID. + * + * @param broadcaster The broadcaster to get a schedule segment of. + * @param id The ID of the schedule segment. + */ + async getScheduleSegmentById(broadcaster, id) { + const segments = await this.getScheduleSegmentsByIds(broadcaster, [id]); + return segments.length ? segments[0] : null; + } + /** + * Gets the schedule for a given broadcaster in iCal format. + * + * @param broadcaster The broadcaster to get the schedule for. + */ + async getScheduleAsIcal(broadcaster) { + return await this._client.callApi({ + type: "helix", + url: "schedule/icalendar", + query: createBroadcasterQuery(broadcaster) + }); + } + /** + * Updates the schedule settings of a given broadcaster. + * + * @param broadcaster The broadcaster to update the schedule settings for. + * @param settings + * + * @expandParams + */ + async updateScheduleSettings(broadcaster, settings) { + await this._client.callApi({ + type: "helix", + url: "schedule/settings", + method: "PATCH", + userId: extractUserId(broadcaster), + scopes: ["channel:manage:schedule"], + query: createScheduleSettingsUpdateQuery(broadcaster, settings) + }); + } + /** + * Creates a new segment in a given broadcaster's schedule. + * + * @param broadcaster The broadcaster to create a new schedule segment for. + * @param data + * + * @expandParams + */ + async createScheduleSegment(broadcaster, data2) { + const result = await this._client.callApi({ + type: "helix", + url: "schedule/segment", + method: "POST", + userId: extractUserId(broadcaster), + scopes: ["channel:manage:schedule"], + query: createBroadcasterQuery(broadcaster), + jsonBody: createScheduleSegmentBody(data2) + }); + return new HelixScheduleSegment(result.data.segments[0], this._client); + } + /** + * Updates a segment in a given broadcaster's schedule. + * + * @param broadcaster The broadcaster to create a new schedule segment for. + * @param segmentId The ID of the segment to update. + * @param data + * + * @expandParams + */ + async updateScheduleSegment(broadcaster, segmentId, data2) { + const result = await this._client.callApi({ + type: "helix", + url: "schedule/segment", + method: "PATCH", + userId: extractUserId(broadcaster), + scopes: ["channel:manage:schedule"], + query: createScheduleSegmentModifyQuery(broadcaster, segmentId), + jsonBody: createScheduleSegmentUpdateBody(data2) + }); + return new HelixScheduleSegment(result.data.segments[0], this._client); + } + /** + * Deletes a segment in a given broadcaster's schedule. + * + * @param broadcaster The broadcaster to create a new schedule segment for. + * @param segmentId The ID of the segment to update. + */ + async deleteScheduleSegment(broadcaster, segmentId) { + await this._client.callApi({ + type: "helix", + url: "schedule/segment", + method: "DELETE", + userId: extractUserId(broadcaster), + scopes: ["channel:manage:schedule"], + query: createScheduleSegmentModifyQuery(broadcaster, segmentId) + }); + } +}; + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/search/HelixSearchApi.js +init_modules_watch_stub(); +init_performance2(); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/interfaces/endpoints/search.external.js +init_modules_watch_stub(); +init_performance2(); +function createSearchChannelsQuery(query, filter) { + return { + query, + live_only: filter.liveOnly?.toString() + }; +} +__name(createSearchChannelsQuery, "createSearchChannelsQuery"); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/search/HelixChannelSearchResult.js +init_modules_watch_stub(); +init_performance2(); +var HelixChannelSearchResult = class HelixChannelSearchResult2 extends DataObject { + static { + __name(this, "HelixChannelSearchResult"); + } + /** @internal */ + _client; + /** @internal */ + constructor(data2, client) { + super(data2); + this._client = client; + } + /** + * The language of the channel. + */ + get language() { + return this[rawDataSymbol].broadcaster_language; + } + /** + * The ID of the channel. + */ + get id() { + return this[rawDataSymbol].id; + } + /** + * The name of the channel. + */ + get name() { + return this[rawDataSymbol].broadcaster_login; + } + /** + * The display name of the channel. + */ + get displayName() { + return this[rawDataSymbol].display_name; + } + /** + * Gets additional information about the owner of the channel. + */ + async getUser() { + return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].id)); + } + /** + * The ID of the game currently played on the channel. + */ + get gameId() { + return this[rawDataSymbol].game_id; + } + /** + * The name of the game currently played on the channel. + */ + get gameName() { + return this[rawDataSymbol].game_name; + } + /** + * Gets information about the game that is being played on the stream. + */ + async getGame() { + return this[rawDataSymbol].game_id ? checkRelationAssertion(await this._client.games.getGameById(this[rawDataSymbol].game_id)) : null; + } + /** + * Whether the channel is currently live. + */ + get isLive() { + return this[rawDataSymbol].is_live; + } + /** + * The tags applied to the channel. + */ + get tags() { + return this[rawDataSymbol].tags; + } + /** + * The thumbnail URL of the stream. + */ + get thumbnailUrl() { + return this[rawDataSymbol].thumbnail_url; + } + /** + * The start date of the stream. Returns `null` if the stream is not live. + */ + get startDate() { + return this[rawDataSymbol].is_live ? new Date(this[rawDataSymbol].started_at) : null; + } +}; +__decorate([ + Enumerable(false) +], HelixChannelSearchResult.prototype, "_client", void 0); +HelixChannelSearchResult = __decorate([ + rtfm("api", "HelixChannelSearchResult", "id") +], HelixChannelSearchResult); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/search/HelixSearchApi.js +var HelixSearchApi = class HelixSearchApi2 extends BaseApi { + static { + __name(this, "HelixSearchApi"); + } + /** + * Search categories/games for an exact or partial match. + * + * @param query The search term. + * @param pagination + * + * @expandParams + */ + async searchCategories(query, pagination) { + const result = await this._client.callApi({ + type: "helix", + url: "search/categories", + query: { + query, + ...createPaginationQuery(pagination) + } + }); + return createPaginatedResult(result, HelixGame, this._client); + } + /** + * Creates a paginator for a category/game search. + * + * @param query The search term. + */ + searchCategoriesPaginated(query) { + return new HelixPaginatedRequest({ + url: "search/categories", + query: { + query + } + }, this._client, (data2) => new HelixGame(data2, this._client)); + } + /** + * Search channels for an exact or partial match. + * + * @param query The search term. + * @param filter + * + * @expandParams + */ + async searchChannels(query, filter = {}) { + const result = await this._client.callApi({ + type: "helix", + url: "search/channels", + query: { + ...createSearchChannelsQuery(query, filter), + ...createPaginationQuery(filter) + } + }); + return createPaginatedResult(result, HelixChannelSearchResult, this._client); + } + /** + * Creates a paginator for a channel search. + * + * @param query The search term. + * @param filter + * + * @expandParams + */ + searchChannelsPaginated(query, filter = {}) { + return new HelixPaginatedRequest({ + url: "search/channels", + query: createSearchChannelsQuery(query, filter) + }, this._client, (data2) => new HelixChannelSearchResult(data2, this._client)); + } +}; +HelixSearchApi = __decorate([ + rtfm("api", "HelixSearchApi") +], HelixSearchApi); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/stream/HelixStreamApi.js +init_modules_watch_stub(); +init_performance2(); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/errors/StreamNotLiveError.js +init_modules_watch_stub(); +init_performance2(); +var StreamNotLiveError = class extends CustomError2 { + static { + __name(this, "StreamNotLiveError"); + } + /** @private */ + constructor(options) { + super("Your stream needs to be live to do this", options); + } +}; + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/interfaces/endpoints/stream.external.js +init_modules_watch_stub(); +init_performance2(); +function createStreamQuery(filter) { + return { + game_id: filter.game, + language: filter.language, + type: filter.type, + user_id: filter.userId, + user_login: filter.userName + }; +} +__name(createStreamQuery, "createStreamQuery"); +function createStreamMarkerBody(broadcaster, description) { + return { + user_id: extractUserId(broadcaster), + description + }; +} +__name(createStreamMarkerBody, "createStreamMarkerBody"); +function createVideoQuery(id) { + return { + video_id: id + }; +} +__name(createVideoQuery, "createVideoQuery"); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/stream/HelixStream.js +init_modules_watch_stub(); +init_performance2(); +var HelixStream = class HelixStream2 extends DataObject { + static { + __name(this, "HelixStream"); + } + /** @internal */ + _client; + /** @internal */ + constructor(data2, client) { + super(data2); + this._client = client; + } + /** + * The stream ID. + */ + get id() { + return this[rawDataSymbol].id; + } + /** + * The user ID. + */ + get userId() { + return this[rawDataSymbol].user_id; + } + /** + * The user's name. + */ + get userName() { + return this[rawDataSymbol].user_login; + } + /** + * The user's display name. + */ + get userDisplayName() { + return this[rawDataSymbol].user_name; + } + /** + * Gets information about the user broadcasting the stream. + */ + async getUser() { + return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].user_id)); + } + /** + * The game ID, or an empty string if the stream doesn't currently have a game. + */ + get gameId() { + return this[rawDataSymbol].game_id; + } + /** + * The game name, or an empty string if the stream doesn't currently have a game. + */ + get gameName() { + return this[rawDataSymbol].game_name; + } + /** + * Gets information about the game that is being played on the stream. + * + * Returns null if the stream doesn't currently have a game. + */ + async getGame() { + return this[rawDataSymbol].game_id ? checkRelationAssertion(await this._client.games.getGameById(this[rawDataSymbol].game_id)) : null; + } + /** + * The type of the stream. + */ + get type() { + return this[rawDataSymbol].type; + } + /** + * The title of the stream. + */ + get title() { + return this[rawDataSymbol].title; + } + /** + * The number of viewers the stream currently has. + */ + get viewers() { + return this[rawDataSymbol].viewer_count; + } + /** + * The time when the stream started. + */ + get startDate() { + return new Date(this[rawDataSymbol].started_at); + } + /** + * The language of the stream. + */ + get language() { + return this[rawDataSymbol].language; + } + /** + * The URL of the thumbnail of the stream. + * + * This URL includes the placeholders `{width}` and `{height}` + * which you must replace with the desired dimensions of the thumbnail (in pixels). + * + * You can also use {@link HelixStream#getThumbnailUrl} to do this replacement. + */ + get thumbnailUrl() { + return this[rawDataSymbol].thumbnail_url; + } + /** + * Builds the thumbnail URL of the stream using the given dimensions. + * + * @param width The width of the thumbnail. + * @param height The height of the thumbnail. + */ + getThumbnailUrl(width, height) { + return this[rawDataSymbol].thumbnail_url.replace("{width}", width.toString()).replace("{height}", height.toString()); + } + /** + * The tags applied to the stream. + */ + get tags() { + return this[rawDataSymbol].tags; + } + /** + * Whether the stream is set to be targeted to mature audiences only. + */ + get isMature() { + return this[rawDataSymbol].is_mature; + } +}; +__decorate([ + Enumerable(false) +], HelixStream.prototype, "_client", void 0); +HelixStream = __decorate([ + rtfm("api", "HelixStream", "id") +], HelixStream); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/stream/HelixStreamMarker.js +init_modules_watch_stub(); +init_performance2(); +var HelixStreamMarker = class HelixStreamMarker2 extends DataObject { + static { + __name(this, "HelixStreamMarker"); + } + /** @internal */ + _client; + /** @internal */ + constructor(data2, client) { + super(data2); + this._client = client; + } + /** + * The ID of the marker. + */ + get id() { + return this[rawDataSymbol].id; + } + /** + * The date and time when the marker was created. + */ + get creationDate() { + return new Date(this[rawDataSymbol].created_at); + } + /** + * The description of the marker. + */ + get description() { + return this[rawDataSymbol].description; + } + /** + * The position in the stream when the marker was created, in seconds. + */ + get positionInSeconds() { + return this[rawDataSymbol].position_seconds; + } +}; +__decorate([ + Enumerable(false) +], HelixStreamMarker.prototype, "_client", void 0); +HelixStreamMarker = __decorate([ + rtfm("api", "HelixStreamMarker", "id") +], HelixStreamMarker); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/stream/HelixStreamMarkerWithVideo.js +init_modules_watch_stub(); +init_performance2(); +var HelixStreamMarkerWithVideo = class HelixStreamMarkerWithVideo2 extends HelixStreamMarker { + static { + __name(this, "HelixStreamMarkerWithVideo"); + } + _videoId; + /** @internal */ + constructor(data2, _videoId, client) { + super(data2, client); + this._videoId = _videoId; + } + /** + * The URL of the video, which will start playing at the position of the stream marker. + */ + get url() { + return this[rawDataSymbol].URL; + } + /** + * The ID of the video. + */ + get videoId() { + return this._videoId; + } + /** + * Gets the video data of the video the marker was set in. + */ + async getVideo() { + return checkRelationAssertion(await this._client.videos.getVideoById(this._videoId)); + } +}; +HelixStreamMarkerWithVideo = __decorate([ + rtfm("api", "HelixStreamMarkerWithVideo", "id") +], HelixStreamMarkerWithVideo); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/stream/HelixStreamApi.js +var HelixStreamApi_1; +var HelixStreamApi = HelixStreamApi_1 = class HelixStreamApi2 extends BaseApi { + static { + __name(this, "HelixStreamApi"); + } + /** @internal */ + _getStreamByUserIdBatcher = new HelixRequestBatcher({ + url: "streams" + }, "user_id", "user_id", this._client, (data2) => new HelixStream(data2, this._client)); + /** @internal */ + _getStreamByUserNameBatcher = new HelixRequestBatcher({ + url: "streams" + }, "user_login", "user_login", this._client, (data2) => new HelixStream(data2, this._client)); + /** + * Gets a list of streams. + * + * @param filter + * @expandParams + */ + async getStreams(filter = {}) { + const result = await this._client.callApi({ + url: "streams", + type: "helix", + query: { + ...createStreamQuery(filter), + ...createPaginationQuery(filter) + } + }); + return createPaginatedResult(result, HelixStream, this._client); + } + /** + * Creates a paginator for streams. + * + * @param filter + * @expandParams + */ + getStreamsPaginated(filter = {}) { + return new HelixPaginatedRequest({ + url: "streams", + query: createStreamQuery(filter) + }, this._client, (data2) => new HelixStream(data2, this._client)); + } + /** + * Gets the current streams for the given usernames. + * + * @param users The username to get the streams for. + */ + async getStreamsByUserNames(users) { + const result = await this.getStreams({ userName: users.map(extractUserName) }); + return result.data; + } + /** + * Gets the current stream for the given username. + * + * @param user The username to get the stream for. + */ + async getStreamByUserName(user) { + const result = await this.getStreamsByUserNames([user]); + return result[0] ?? null; + } + /** + * Gets the current stream for the given username, batching multiple calls into fewer requests as the API allows. + * + * @param user The username to get the stream for. + */ + async getStreamByUserNameBatched(user) { + return await this._getStreamByUserNameBatcher.request(extractUserName(user)); + } + /** + * Gets the current streams for the given user IDs. + * + * @param users The user IDs to get the streams for. + */ + async getStreamsByUserIds(users) { + const result = await this.getStreams({ userId: users.map(extractUserId) }); + return result.data; + } + /** + * Gets the current stream for the given user ID. + * + * @param user The user ID to get the stream for. + */ + async getStreamByUserId(user) { + const userId = extractUserId(user); + const result = await this._client.callApi({ + url: "streams", + type: "helix", + userId, + query: createStreamQuery({ userId }) + }); + return mapNullable(result.data[0], (data2) => new HelixStream(data2, this._client)); + } + /** + * Gets the current stream for the given user ID, batching multiple calls into fewer requests as the API allows. + * + * @param user The user ID to get the stream for. + */ + async getStreamByUserIdBatched(user) { + return await this._getStreamByUserIdBatcher.request(extractUserId(user)); + } + /** + * Gets a list of all stream markers for a user. + * + * @param user The user to list the stream markers for. + * @param pagination + * + * @expandParams + */ + async getStreamMarkersForUser(user, pagination) { + const result = await this._client.callApi({ + url: "streams/markers", + type: "helix", + query: { + ...createUserQuery(user), + ...createPaginationQuery(pagination) + }, + userId: extractUserId(user), + scopes: ["user:read:broadcast"], + canOverrideScopedUserContext: true + }); + return { + data: flatten2(result.data.map((data2) => HelixStreamApi_1._mapGetStreamMarkersResult(data2, this._client))), + cursor: result.pagination?.cursor + }; + } + /** + * Creates a paginator for all stream markers for a user. + * + * @param user The user to list the stream markers for. + */ + getStreamMarkersForUserPaginated(user) { + return new HelixPaginatedRequest({ + url: "streams/markers", + query: createUserQuery(user), + userId: extractUserId(user), + scopes: ["user:read:broadcast"], + canOverrideScopedUserContext: true + }, this._client, (data2) => HelixStreamApi_1._mapGetStreamMarkersResult(data2, this._client)); + } + /** + * Gets a list of all stream markers for a video. + * + * @param user The user the video belongs to. + * @param videoId The video to list the stream markers for. + * @param pagination + * + * @expandParams + */ + async getStreamMarkersForVideo(user, videoId, pagination) { + const result = await this._client.callApi({ + url: "streams/markers", + type: "helix", + query: { + ...createVideoQuery(videoId), + ...createPaginationQuery(pagination) + }, + userId: extractUserId(user), + scopes: ["user:read:broadcast"], + canOverrideScopedUserContext: true + }); + return { + data: flatten2(result.data.map((data2) => HelixStreamApi_1._mapGetStreamMarkersResult(data2, this._client))), + cursor: result.pagination?.cursor + }; + } + /** + * Creates a paginator for all stream markers for a video. + * + * @param user The user the video belongs to. + * @param videoId The video to list the stream markers for. + */ + getStreamMarkersForVideoPaginated(user, videoId) { + return new HelixPaginatedRequest({ + url: "streams/markers", + query: createVideoQuery(videoId), + userId: extractUserId(user), + scopes: ["user:read:broadcast"], + canOverrideScopedUserContext: true + }, this._client, (data2) => HelixStreamApi_1._mapGetStreamMarkersResult(data2, this._client)); + } + /** + * Creates a new stream marker. + * + * Only works while the specified user's stream is live. + * + * @param broadcaster The broadcaster to create a stream marker for. + * @param description The description of the marker. + */ + async createStreamMarker(broadcaster, description) { + try { + const result = await this._client.callApi({ + url: "streams/markers", + method: "POST", + type: "helix", + userId: extractUserId(broadcaster), + scopes: ["channel:manage:broadcast"], + canOverrideScopedUserContext: true, + jsonBody: createStreamMarkerBody(broadcaster, description) + }); + return new HelixStreamMarker(result.data[0], this._client); + } catch (e) { + if (e instanceof HttpStatusCodeError && e.statusCode === 404) { + throw new StreamNotLiveError({ cause: e }); + } + throw e; + } + } + /** + * Gets the stream key of a stream. + * + * @param broadcaster The broadcaster to get the stream key for. + */ + async getStreamKey(broadcaster) { + const userId = extractUserId(broadcaster); + const result = await this._client.callApi({ + type: "helix", + url: "streams/key", + userId, + scopes: ["channel:read:stream_key"], + query: createBroadcasterQuery(broadcaster) + }); + return result.data[0].stream_key; + } + /** + * Gets the streams that are currently live and are followed by the given user. + * + * @param user The user to check followed streams for. + * @param pagination + * + * @expandParams + */ + async getFollowedStreams(user, pagination) { + const userId = extractUserId(user); + const result = await this._client.callApi({ + type: "helix", + url: "streams/followed", + userId, + scopes: ["user:read:follows"], + query: { + ...createSingleKeyQuery("user_id", userId), + ...createPaginationQuery(pagination) + } + }); + return createPaginatedResult(result, HelixStream, this._client); + } + /** + * Creates a paginator for the streams that are currently live and are followed by the given user. + * + * @param user The user to check followed streams for. + */ + getFollowedStreamsPaginated(user) { + const userId = extractUserId(user); + return new HelixPaginatedRequest({ + url: "streams/followed", + userId, + scopes: ["user:read:follows"], + query: createSingleKeyQuery("user_id", userId) + }, this._client, (data2) => new HelixStream(data2, this._client)); + } + static _mapGetStreamMarkersResult(data2, client) { + return data2.videos.reduce((result, video) => [ + ...result, + ...video.markers.map((marker) => new HelixStreamMarkerWithVideo(marker, video.video_id, client)) + ], []); + } +}; +__decorate([ + Enumerable(false) +], HelixStreamApi.prototype, "_getStreamByUserIdBatcher", void 0); +__decorate([ + Enumerable(false) +], HelixStreamApi.prototype, "_getStreamByUserNameBatcher", void 0); +HelixStreamApi = HelixStreamApi_1 = __decorate([ + rtfm("api", "HelixStreamApi") +], HelixStreamApi); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/subscriptions/HelixSubscriptionApi.js +init_modules_watch_stub(); +init_performance2(); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/interfaces/endpoints/subscription.external.js +init_modules_watch_stub(); +init_performance2(); +function createSubscriptionCheckQuery(broadcaster, user) { + return { + broadcaster_id: extractUserId(broadcaster), + user_id: extractUserId(user) + }; +} +__name(createSubscriptionCheckQuery, "createSubscriptionCheckQuery"); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/subscriptions/HelixPaginatedSubscriptionsRequest.js +init_modules_watch_stub(); +init_performance2(); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/subscriptions/HelixSubscription.js +init_modules_watch_stub(); +init_performance2(); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/subscriptions/HelixUserSubscription.js +init_modules_watch_stub(); +init_performance2(); +var HelixUserSubscription = class HelixUserSubscription2 extends DataObject { + static { + __name(this, "HelixUserSubscription"); + } + /** @internal */ + _client; + /** @internal */ + constructor(data2, client) { + super(data2); + this._client = client; + } + /** + * The user ID of the broadcaster. + */ + get broadcasterId() { + return this[rawDataSymbol].broadcaster_id; + } + /** + * The name of the broadcaster. + */ + get broadcasterName() { + return this[rawDataSymbol].broadcaster_login; + } + /** + * The display name of the broadcaster. + */ + get broadcasterDisplayName() { + return this[rawDataSymbol].broadcaster_name; + } + /** + * Gets more information about the broadcaster. + */ + async getBroadcaster() { + return await this._client.users.getUserById(this[rawDataSymbol].broadcaster_id); + } + /** + * Whether the subscription has been gifted by another user. + */ + get isGift() { + return this[rawDataSymbol].is_gift; + } + /** + * The tier of the subscription. + */ + get tier() { + return this[rawDataSymbol].tier; + } +}; +__decorate([ + Enumerable(false) +], HelixUserSubscription.prototype, "_client", void 0); +HelixUserSubscription = __decorate([ + rtfm("api", "HelixUserSubscription", "broadcasterId") +], HelixUserSubscription); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/subscriptions/HelixSubscription.js +var HelixSubscription = class HelixSubscription2 extends HelixUserSubscription { + static { + __name(this, "HelixSubscription"); + } + /** + * The user ID of the broadcaster. + */ + get broadcasterId() { + return this[rawDataSymbol].broadcaster_id; + } + /** + * The name of the broadcaster. + */ + get broadcasterName() { + return this[rawDataSymbol].broadcaster_login; + } + /** + * The display name of the broadcaster. + */ + get broadcasterDisplayName() { + return this[rawDataSymbol].broadcaster_name; + } + /** + * Gets more information about the broadcaster. + */ + async getBroadcaster() { + return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].broadcaster_id)); + } + /** + * The user ID of the gifter. + */ + get gifterId() { + return this[rawDataSymbol].is_gift ? this[rawDataSymbol].gifter_id : null; + } + /** + * The name of the gifter. + */ + get gifterName() { + return this[rawDataSymbol].is_gift ? this[rawDataSymbol].gifter_login : null; + } + /** + * The display name of the gifter. + */ + get gifterDisplayName() { + return this[rawDataSymbol].is_gift ? this[rawDataSymbol].gifter_name : null; + } + /** + * Gets more information about the gifter. + */ + async getGifter() { + return this[rawDataSymbol].is_gift ? checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].gifter_id)) : null; + } + /** + * The user ID of the subscribed user. + */ + get userId() { + return this[rawDataSymbol].user_id; + } + /** + * The name of the subscribed user. + */ + get userName() { + return this[rawDataSymbol].user_login; + } + /** + * The display name of the subscribed user. + */ + get userDisplayName() { + return this[rawDataSymbol].user_name; + } + /** + * Gets more information about the subscribed user. + */ + async getUser() { + return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].user_id)); + } +}; +HelixSubscription = __decorate([ + rtfm("api", "HelixSubscription", "userId") +], HelixSubscription); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/subscriptions/HelixPaginatedSubscriptionsRequest.js +var HelixPaginatedSubscriptionsRequest = class HelixPaginatedSubscriptionsRequest2 extends HelixPaginatedRequestWithTotal { + static { + __name(this, "HelixPaginatedSubscriptionsRequest"); + } + /** @internal */ + constructor(broadcaster, client) { + super({ + url: "subscriptions", + scopes: ["channel:read:subscriptions"], + userId: extractUserId(broadcaster), + query: createBroadcasterQuery(broadcaster) + }, client, (data2) => new HelixSubscription(data2, client)); + } + /** + * Gets the total sub points of the broadcaster. + */ + async getPoints() { + const data2 = this._currentData ?? await this._fetchData({ query: { after: void 0 } }); + return data2.points; + } +}; +HelixPaginatedSubscriptionsRequest = __decorate([ + rtfm("api", "HelixPaginatedSubscriptionsRequest") +], HelixPaginatedSubscriptionsRequest); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/subscriptions/HelixSubscriptionApi.js +var HelixSubscriptionApi = class HelixSubscriptionApi2 extends BaseApi { + static { + __name(this, "HelixSubscriptionApi"); + } + /** + * Gets a list of all subscriptions to a given broadcaster. + * + * @param broadcaster The broadcaster to list subscriptions to. + * @param pagination + * + * @expandParams + */ + async getSubscriptions(broadcaster, pagination) { + const result = await this._client.callApi({ + url: "subscriptions", + scopes: ["channel:read:subscriptions"], + type: "helix", + userId: extractUserId(broadcaster), + query: { + ...createBroadcasterQuery(broadcaster), + ...createPaginationQuery(pagination) + } + }); + return { + ...createPaginatedResultWithTotal(result, HelixSubscription, this._client), + points: result.points + }; + } + /** + * Creates a paginator for all subscriptions to a given broadcaster. + * + * @param broadcaster The broadcaster to list subscriptions to. + */ + getSubscriptionsPaginated(broadcaster) { + return new HelixPaginatedSubscriptionsRequest(broadcaster, this._client); + } + /** + * Gets the subset of the given user list that is subscribed to the given broadcaster. + * + * @param broadcaster The broadcaster to find subscriptions to. + * @param users The users that should be checked for subscriptions. + */ + async getSubscriptionsForUsers(broadcaster, users) { + const result = await this._client.callApi({ + type: "helix", + url: "subscriptions", + userId: extractUserId(broadcaster), + scopes: ["channel:read:subscriptions"], + query: createChannelUsersCheckQuery(broadcaster, users) + }); + return result.data.map((data2) => new HelixSubscription(data2, this._client)); + } + /** + * Gets the subscription data for a given user to a given broadcaster. + * + * This checks with the authorization of a broadcaster. + * If you only have the authorization of a user, check {@link HelixSubscriptionApi#checkUserSubscription}}. + * + * @param broadcaster The broadcaster to check. + * @param user The user to check. + */ + async getSubscriptionForUser(broadcaster, user) { + const list = await this.getSubscriptionsForUsers(broadcaster, [user]); + return list.length ? list[0] : null; + } + /** + * Checks if a given user is subscribed to a given broadcaster. Returns null if not subscribed. + * + * This checks with the authorization of a user. + * If you only have the authorization of a broadcaster, check {@link HelixSubscriptionApi#getSubscriptionForUser}}. + * + * @param user The user to check. + * @param broadcaster The broadcaster to check the user's subscription for. + */ + async checkUserSubscription(user, broadcaster) { + try { + const result = await this._client.callApi({ + type: "helix", + url: "subscriptions/user", + userId: extractUserId(user), + scopes: ["user:read:subscriptions"], + query: createSubscriptionCheckQuery(broadcaster, user) + }); + return new HelixUserSubscription(result.data[0], this._client); + } catch (e) { + if (e instanceof HttpStatusCodeError && e.statusCode === 404) { + return null; + } + throw e; + } + } +}; +HelixSubscriptionApi = __decorate([ + rtfm("api", "HelixSubscriptionApi") +], HelixSubscriptionApi); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/team/HelixTeamApi.js +init_modules_watch_stub(); +init_performance2(); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/team/HelixTeam.js +init_modules_watch_stub(); +init_performance2(); +var HelixTeam = class HelixTeam2 extends DataObject { + static { + __name(this, "HelixTeam"); + } + /** @internal */ + _client; + /** @internal */ + constructor(data2, client) { + super(data2); + this._client = client; + } + /** + * The ID of the team. + */ + get id() { + return this[rawDataSymbol].id; + } + /** + * The name of the team. + */ + get name() { + return this[rawDataSymbol].team_name; + } + /** + * The display name of the team. + */ + get displayName() { + return this[rawDataSymbol].team_display_name; + } + /** + * The URL of the background image of the team. + */ + get backgroundImageUrl() { + return this[rawDataSymbol].background_image_url; + } + /** + * The URL of the banner of the team. + */ + get bannerUrl() { + return this[rawDataSymbol].banner; + } + /** + * The date when the team was created. + */ + get creationDate() { + return new Date(this[rawDataSymbol].created_at); + } + /** + * The date when the team was last updated. + */ + get updateDate() { + return new Date(this[rawDataSymbol].updated_at); + } + /** + * The info of the team. + * + * May contain HTML tags. + */ + get info() { + return this[rawDataSymbol].info; + } + /** + * The URL of the thumbnail of the team's logo. + */ + get logoThumbnailUrl() { + return this[rawDataSymbol].thumbnail_url; + } + /** + * Gets the relations to the members of the team. + */ + async getUserRelations() { + const teamWithUsers = await this._client.teams.getTeamById(this.id); + return teamWithUsers.userRelations; + } +}; +__decorate([ + Enumerable(false) +], HelixTeam.prototype, "_client", void 0); +HelixTeam = __decorate([ + rtfm("api", "HelixTeam", "id") +], HelixTeam); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/team/HelixTeamWithUsers.js +init_modules_watch_stub(); +init_performance2(); +var HelixTeamWithUsers = class HelixTeamWithUsers2 extends HelixTeam { + static { + __name(this, "HelixTeamWithUsers"); + } + /** + * The relations to the members of the team. + */ + get userRelations() { + return this[rawDataSymbol].users.map((data2) => new HelixUserRelation(data2, this._client)); + } +}; +HelixTeamWithUsers = __decorate([ + rtfm("api", "HelixTeamWithUsers", "id") +], HelixTeamWithUsers); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/team/HelixTeamApi.js +var HelixTeamApi = class HelixTeamApi2 extends BaseApi { + static { + __name(this, "HelixTeamApi"); + } + /** + * Gets a list of all teams a broadcaster is a member of. + * + * @param broadcaster The broadcaster to get the teams of. + */ + async getTeamsForBroadcaster(broadcaster) { + const result = await this._client.callApi({ + type: "helix", + url: "teams/channel", + userId: extractUserId(broadcaster), + query: createBroadcasterQuery(broadcaster) + }); + return result.data?.map((data2) => new HelixTeam(data2, this._client)) ?? []; + } + /** + * Gets a team by ID. + * + * Returns null if there is no team with the given ID. + * + * @param id The ID of the team. + */ + async getTeamById(id) { + try { + const result = await this._client.callApi({ + type: "helix", + url: "teams", + query: { + id + } + }); + return new HelixTeamWithUsers(result.data[0], this._client); + } catch (e) { + if (e instanceof HttpStatusCodeError && e.statusCode === 500) { + return null; + } + throw e; + } + } + /** + * Gets a team by name. + * + * Returns null if there is no team with the given name. + * + * @param name The name of the team. + */ + async getTeamByName(name) { + try { + const result = await this._client.callApi({ + type: "helix", + url: "teams", + query: { + name + } + }); + return new HelixTeamWithUsers(result.data[0], this._client); + } catch (e) { + if (e instanceof HttpStatusCodeError && e.statusCode === 404) { + return null; + } + throw e; + } + } +}; +HelixTeamApi = __decorate([ + rtfm("api", "HelixTeamApi") +], HelixTeamApi); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/user/HelixUserApi.js +init_modules_watch_stub(); +init_performance2(); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/interfaces/endpoints/user.external.js +init_modules_watch_stub(); +init_performance2(); +function createUserBlockCreateQuery(target, additionalInfo) { + return { + target_user_id: extractUserId(target), + source_context: additionalInfo.sourceContext, + reason: additionalInfo.reason + }; +} +__name(createUserBlockCreateQuery, "createUserBlockCreateQuery"); +function createUserBlockDeleteQuery(target) { + return { + target_user_id: extractUserId(target) + }; +} +__name(createUserBlockDeleteQuery, "createUserBlockDeleteQuery"); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/user/extensions/HelixInstalledExtensionList.js +init_modules_watch_stub(); +init_performance2(); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/user/extensions/HelixInstalledExtension.js +init_modules_watch_stub(); +init_performance2(); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/user/extensions/HelixBaseExtension.js +init_modules_watch_stub(); +init_performance2(); +var HelixBaseExtension = class extends DataObject { + static { + __name(this, "HelixBaseExtension"); + } + /** + * The ID of the extension. + */ + get id() { + return this[rawDataSymbol].id; + } + /** + * The version of the extension. + */ + get version() { + return this[rawDataSymbol].version; + } + /** + * The name of the extension. + */ + get name() { + return this[rawDataSymbol].name; + } +}; + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/user/extensions/HelixInstalledExtension.js +var HelixInstalledExtension = class HelixInstalledExtension2 extends HelixBaseExtension { + static { + __name(this, "HelixInstalledExtension"); + } + _slotType; + _slotId; + /** @internal */ + constructor(slotType, slotId, data2) { + super(data2); + this._slotType = slotType; + this._slotId = slotId; + } + /** + * The type of the slot the extension is in. + */ + get slotType() { + return this._slotType; + } + /** + * The ID of the slot the extension is in. + */ + get slotId() { + return this._slotId; + } +}; +HelixInstalledExtension = __decorate([ + rtfm("api", "HelixInstalledExtension", "id") +], HelixInstalledExtension); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/user/extensions/HelixInstalledExtensionList.js +var HelixInstalledExtensionList = class HelixInstalledExtensionList2 extends DataObject { + static { + __name(this, "HelixInstalledExtensionList"); + } + getExtensionAtSlot(type, slotId) { + const data2 = this[rawDataSymbol][type][slotId]; + return data2.active ? new HelixInstalledExtension(type, slotId, data2) : null; + } + getExtensionsForSlotType(type) { + return [...Object.entries(this[rawDataSymbol][type])].filter((entry) => entry[1].active).map(([slotId, slotData]) => new HelixInstalledExtension(type, slotId, slotData)); + } + getAllExtensions() { + return [...Object.entries(this[rawDataSymbol])].flatMap(([type, typeEntries]) => [...Object.entries(typeEntries)].filter((entry) => entry[1].active).map(([slotId, slotData]) => new HelixInstalledExtension(type, slotId, slotData))); + } +}; +HelixInstalledExtensionList = __decorate([ + rtfm("api", "HelixInstalledExtensionList") +], HelixInstalledExtensionList); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/user/extensions/HelixUserExtension.js +init_modules_watch_stub(); +init_performance2(); +var HelixUserExtension = class HelixUserExtension2 extends HelixBaseExtension { + static { + __name(this, "HelixUserExtension"); + } + /** + * Whether the user has configured the extension to be able to activate it. + */ + get canActivate() { + return this[rawDataSymbol].can_activate; + } + /** + * The available types of the extension. + */ + get types() { + return this[rawDataSymbol].type; + } +}; +HelixUserExtension = __decorate([ + rtfm("api", "HelixUserExtension", "id") +], HelixUserExtension); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/user/HelixPrivilegedUser.js +init_modules_watch_stub(); +init_performance2(); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/user/HelixUser.js +init_modules_watch_stub(); +init_performance2(); +var HelixUser = class HelixUser2 extends DataObject { + static { + __name(this, "HelixUser"); + } + /** @internal */ + _client; + /** @internal */ + constructor(data2, client) { + super(data2); + this._client = client; + } + /** + * The ID of the user. + */ + get id() { + return this[rawDataSymbol].id; + } + /** + * The name of the user. + */ + get name() { + return this[rawDataSymbol].login; + } + /** + * The display name of the user. + */ + get displayName() { + return this[rawDataSymbol].display_name; + } + /** + * The description of the user. + */ + get description() { + return this[rawDataSymbol].description; + } + /** + * The type of the user. + */ + get type() { + return this[rawDataSymbol].type; + } + /** + * The type of the broadcaster. + */ + get broadcasterType() { + return this[rawDataSymbol].broadcaster_type; + } + /** + * The URL of the profile picture of the user. + */ + get profilePictureUrl() { + return this[rawDataSymbol].profile_image_url; + } + /** + * The URL of the offline video placeholder of the user. + */ + get offlinePlaceholderUrl() { + return this[rawDataSymbol].offline_image_url; + } + /** + * The date when the user was created, i.e. when they registered on Twitch. + */ + get creationDate() { + return new Date(this[rawDataSymbol].created_at); + } + /** + * Gets the channel's stream data. + */ + async getStream() { + return await this._client.streams.getStreamByUserId(this); + } + /** + * Gets a list of broadcasters the user follows. + */ + async getFollowedChannels() { + return await this._client.channels.getFollowedChannels(this); + } + /** + * Gets the follow data of the user to the given broadcaster, or `null` if the user doesn't follow the broadcaster. + * + * This requires user authentication. + * For broadcaster authentication, you can use `getChannelFollower` while switching `this` and the parameter. + * + * @param broadcaster The broadcaster to check the follow to. + */ + async getFollowedChannel(broadcaster) { + const result = await this._client.channels.getFollowedChannels(this, broadcaster); + return result.data[0] ?? null; + } + /** + * Checks whether the user is following the given broadcaster. + * + * This requires user authentication. + * For broadcaster authentication, you can use `isFollowedBy` while switching `this` and the parameter. + * + * @param broadcaster The broadcaster to check the user's follow to. + */ + async follows(broadcaster) { + return await this.getFollowedChannel(broadcaster) !== null; + } + /** + * Gets a list of users that follow the broadcaster. + */ + async getChannelFollowers() { + return await this._client.channels.getChannelFollowers(this); + } + /** + * Gets the follow data of the given user to the broadcaster, or `null` if the user doesn't follow the broadcaster. + * + * This requires broadcaster authentication. + * For user authentication, you can use `getFollowedChannel` while switching `this` and the parameter. + * + * @param user The user to check the follow from. + */ + async getChannelFollower(user) { + const result = await this._client.channels.getChannelFollowers(this, user); + return result.data[0] ?? null; + } + /** + * Checks whether the given user is following the broadcaster. + * + * This requires broadcaster authentication. + * For user authentication, you can use `follows` while switching `this` and the parameter. + * + * @param user The user to check the broadcaster's follow from. + */ + async isFollowedBy(user) { + return await this.getChannelFollower(user) !== null; + } + /** + * Gets the subscription data for the user to the given broadcaster, or `null` if the user is not subscribed. + * + * This requires user authentication. + * For broadcaster authentication, you can use `getSubscriber` while switching `this` and the parameter. + * + * @param broadcaster The broadcaster you want to get the subscription data for. + */ + async getSubscriptionTo(broadcaster) { + return await this._client.subscriptions.checkUserSubscription(this, broadcaster); + } + /** + * Checks whether the user is subscribed to the given broadcaster. + * + * This requires user authentication. + * For broadcaster authentication, you can use `hasSubscriber` while switching `this` and the parameter. + * + * @param broadcaster The broadcaster you want to check the subscription for. + */ + async isSubscribedTo(broadcaster) { + return await this.getSubscriptionTo(broadcaster) !== null; + } + /** + * Gets the subscription data for the given user to the broadcaster, or `null` if the user is not subscribed. + * + * This requires broadcaster authentication. + * For user authentication, you can use `getSubscriptionTo` while switching `this` and the parameter. + * + * @param user The user you want to get the subscription data for. + */ + async getSubscriber(user) { + return await this._client.subscriptions.getSubscriptionForUser(this, user); + } + /** + * Checks whether the given user is subscribed to the broadcaster. + * + * This requires broadcaster authentication. + * For user authentication, you can use `isSubscribedTo` while switching `this` and the parameter. + * + * @param user The user you want to check the subscription for. + */ + async hasSubscriber(user) { + return await this.getSubscriber(user) !== null; + } +}; +__decorate([ + Enumerable(false) +], HelixUser.prototype, "_client", void 0); +HelixUser = __decorate([ + rtfm("api", "HelixUser", "id") +], HelixUser); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/user/HelixPrivilegedUser.js +var HelixPrivilegedUser = class HelixPrivilegedUser2 extends HelixUser { + static { + __name(this, "HelixPrivilegedUser"); + } + /** + * The email address of the user. + */ + get email() { + return this[rawDataSymbol].email; + } + /** + * Changes the description of the user. + * + * @param description The new description. + */ + async setDescription(description) { + return await this._client.users.updateAuthenticatedUser(this, { description }); + } +}; +HelixPrivilegedUser = __decorate([ + rtfm("api", "HelixPrivilegedUser", "id") +], HelixPrivilegedUser); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/user/HelixUserBlock.js +init_modules_watch_stub(); +init_performance2(); +var HelixUserBlock = class HelixUserBlock2 extends DataObject { + static { + __name(this, "HelixUserBlock"); + } + /** @internal */ + _client; + /** @internal */ + constructor(data2, client) { + super(data2); + this._client = client; + } + /** + * The ID of the blocked user. + */ + get userId() { + return this[rawDataSymbol].user_id; + } + /** + * The name of the blocked user. + */ + get userName() { + return this[rawDataSymbol].user_login; + } + /** + * The display name of the blocked user. + */ + get userDisplayName() { + return this[rawDataSymbol].display_name; + } + /** + * Gets additional information about the blocked user. + */ + async getUser() { + return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].user_id)); + } +}; +__decorate([ + Enumerable(false) +], HelixUserBlock.prototype, "_client", void 0); +HelixUserBlock = __decorate([ + rtfm("api", "HelixUserBlock", "userId") +], HelixUserBlock); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/user/HelixUserApi.js +var HelixUserApi = class HelixUserApi2 extends BaseApi { + static { + __name(this, "HelixUserApi"); + } + /** @internal */ + _getUserByIdBatcher = new HelixRequestBatcher({ + url: "users" + }, "id", "id", this._client, (data2) => new HelixUser(data2, this._client)); + /** @internal */ + _getUserByNameBatcher = new HelixRequestBatcher({ + url: "users" + }, "login", "login", this._client, (data2) => new HelixUser(data2, this._client)); + /** + * Gets the user data for the given list of user IDs. + * + * @param userIds The user IDs you want to look up. + */ + async getUsersByIds(userIds) { + return await this._getUsers("id", userIds.map(extractUserId)); + } + /** + * Gets the user data for the given list of usernames. + * + * @param userNames The usernames you want to look up. + */ + async getUsersByNames(userNames) { + return await this._getUsers("login", userNames.map(extractUserName)); + } + /** + * Gets the user data for the given user ID. + * + * @param user The user ID you want to look up. + */ + async getUserById(user) { + const userId = extractUserId(user); + const result = await this._client.callApi({ + type: "helix", + url: "users", + userId, + query: { + id: userId + } + }); + return mapNullable(result.data[0], (data2) => new HelixUser(data2, this._client)); + } + /** + * Gets the user data for the given user ID, batching multiple calls into fewer requests as the API allows. + * + * @param user The user ID you want to look up. + */ + async getUserByIdBatched(user) { + return await this._getUserByIdBatcher.request(extractUserId(user)); + } + /** + * Gets the user data for the given username. + * + * @param userName The username you want to look up. + */ + async getUserByName(userName) { + const users = await this._getUsers("login", [extractUserName(userName)]); + return users.length ? users[0] : null; + } + /** + * Gets the user data for the given username, batching multiple calls into fewer requests as the API allows. + * + * @param user The username you want to look up. + */ + async getUserByNameBatched(user) { + return await this._getUserByNameBatcher.request(extractUserName(user)); + } + /** + * Gets the user data of the given authenticated user. + * + * @param user The user to get data for. + * @param withEmail Whether you need the user's email address. + */ + async getAuthenticatedUser(user, withEmail = false) { + const result = await this._client.callApi({ + type: "helix", + url: "users", + forceType: "user", + userId: extractUserId(user), + scopes: withEmail ? ["user:read:email"] : void 0 + }); + if (!result.data?.length) { + throw new HellFreezesOverError("Could not get authenticated user"); + } + return new HelixPrivilegedUser(result.data[0], this._client); + } + /** + * Updates the given authenticated user's data. + * + * @param user The user to update. + * @param data The data to update. + */ + async updateAuthenticatedUser(user, data2) { + const result = await this._client.callApi({ + type: "helix", + url: "users", + method: "PUT", + userId: extractUserId(user), + scopes: ["user:edit"], + query: { + description: data2.description + } + }); + return new HelixPrivilegedUser(result.data[0], this._client); + } + /** + * Gets a list of users blocked by the given user. + * + * @param user The user to get blocks for. + * @param pagination + * + * @expandParams + */ + async getBlocks(user, pagination) { + const result = await this._client.callApi({ + type: "helix", + url: "users/blocks", + userId: extractUserId(user), + scopes: ["user:read:blocked_users"], + query: { + ...createBroadcasterQuery(user), + ...createPaginationQuery(pagination) + } + }); + return createPaginatedResult(result, HelixUserBlock, this._client); + } + /** + * Creates a paginator for users blocked by the given user. + * + * @param user The user to get blocks for. + */ + getBlocksPaginated(user) { + return new HelixPaginatedRequest({ + url: "users/blocks", + userId: extractUserId(user), + scopes: ["user:read:blocked_users"], + query: createBroadcasterQuery(user) + }, this._client, (data2) => new HelixUserBlock(data2, this._client)); + } + /** + * Blocks the given user. + * + * @param broadcaster The user to add the block to. + * @param target The user to block. + * @param additionalInfo Additional info to give context to the block. + * + * @expandParams + */ + async createBlock(broadcaster, target, additionalInfo = {}) { + await this._client.callApi({ + type: "helix", + url: "users/blocks", + method: "PUT", + userId: extractUserId(broadcaster), + scopes: ["user:manage:blocked_users"], + query: createUserBlockCreateQuery(target, additionalInfo) + }); + } + /** + * Unblocks the given user. + * + * @param broadcaster The user to remove the block from. + * @param target The user to unblock. + */ + async deleteBlock(broadcaster, target) { + await this._client.callApi({ + type: "helix", + url: "users/blocks", + method: "DELETE", + userId: extractUserId(broadcaster), + scopes: ["user:manage:blocked_users"], + query: createUserBlockDeleteQuery(target) + }); + } + /** + * Gets a list of all extensions for the given authenticated user. + * + * @param broadcaster The broadcaster to get the list of extensions for. + * @param withInactive Whether to include inactive extensions. + */ + async getExtensionsForAuthenticatedUser(broadcaster, withInactive = false) { + const result = await this._client.callApi({ + type: "helix", + url: "users/extensions/list", + userId: extractUserId(broadcaster), + scopes: withInactive ? ["channel:manage:extensions"] : ["user:read:broadcast", "channel:manage:extensions"] + }); + return result.data.map((data2) => new HelixUserExtension(data2)); + } + /** + * Gets a list of all installed extensions for the given user. + * + * @param user The user to get the installed extensions for. + * @param withDev Whether to include extensions that are in development. + */ + async getActiveExtensions(user, withDev = false) { + const userId = extractUserId(user); + const result = await this._client.callApi({ + type: "helix", + url: "users/extensions", + userId, + scopes: withDev ? ["user:read:broadcast", "channel:manage:extensions"] : void 0, + query: createSingleKeyQuery("user_id", userId) + }); + return new HelixInstalledExtensionList(result.data); + } + /** + * Updates the installed extensions for the given authenticated user. + * + * @param broadcaster The user to update the installed extensions for. + * @param data The extension installation payload. + * + * The format is shown on the [Twitch documentation](https://dev.twitch.tv/docs/api/reference#update-user-extensions). + * Don't use the "data" wrapper though. + */ + async updateActiveExtensionsForAuthenticatedUser(broadcaster, data2) { + const result = await this._client.callApi({ + type: "helix", + url: "users/extensions", + method: "PUT", + userId: extractUserId(broadcaster), + scopes: ["channel:manage:extensions"], + jsonBody: { data: data2 } + }); + return new HelixInstalledExtensionList(result.data); + } + async _getUsers(lookupType, param) { + if (param.length === 0) { + return []; + } + const query = { [lookupType]: param }; + const result = await this._client.callApi({ + type: "helix", + url: "users", + query + }); + return result.data.map((userData) => new HelixUser(userData, this._client)); + } +}; +__decorate([ + Enumerable(false) +], HelixUserApi.prototype, "_getUserByIdBatcher", void 0); +__decorate([ + Enumerable(false) +], HelixUserApi.prototype, "_getUserByNameBatcher", void 0); +HelixUserApi = __decorate([ + rtfm("api", "HelixUserApi") +], HelixUserApi); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/video/HelixVideoApi.js +init_modules_watch_stub(); +init_performance2(); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/video/HelixVideo.js +init_modules_watch_stub(); +init_performance2(); +var HelixVideo = class HelixVideo2 extends DataObject { + static { + __name(this, "HelixVideo"); + } + /** @internal */ + _client; + /** @internal */ + constructor(data2, client) { + super(data2); + this._client = client; + } + /** + * The ID of the video. + */ + get id() { + return this[rawDataSymbol].id; + } + /** + * The ID of the user who created the video. + */ + get userId() { + return this[rawDataSymbol].user_id; + } + /** + * The name of the user who created the video. + */ + get userName() { + return this[rawDataSymbol].user_login; + } + /** + * The display name of the user who created the video. + */ + get userDisplayName() { + return this[rawDataSymbol].user_name; + } + /** + * Gets information about the user who created the video. + */ + async getUser() { + return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].user_id)); + } + /** + * The title of the video. + */ + get title() { + return this[rawDataSymbol].title; + } + /** + * The description of the video. + */ + get description() { + return this[rawDataSymbol].description; + } + /** + * The date when the video was created. + */ + get creationDate() { + return new Date(this[rawDataSymbol].created_at); + } + /** + * The date when the video was published. + */ + get publishDate() { + return new Date(this[rawDataSymbol].published_at); + } + /** + * The URL of the video. + */ + get url() { + return this[rawDataSymbol].url; + } + /** + * The URL of the thumbnail of the video. + */ + get thumbnailUrl() { + return this[rawDataSymbol].thumbnail_url; + } + /** + * Builds the thumbnail URL of the video using the given dimensions. + * + * @param width The width of the thumbnail. + * @param height The height of the thumbnail. + */ + getThumbnailUrl(width, height) { + return this[rawDataSymbol].thumbnail_url.replace("%{width}", width.toString()).replace("%{height}", height.toString()); + } + /** + * Whether the video is public or not. + */ + get isPublic() { + return this[rawDataSymbol].viewable === "public"; + } + /** + * The number of views of the video. + */ + get views() { + return this[rawDataSymbol].view_count; + } + /** + * The language of the video. + */ + get language() { + return this[rawDataSymbol].language; + } + /** + * The type of the video. + */ + get type() { + return this[rawDataSymbol].type; + } + /** + * The duration of the video, as formatted by Twitch. + */ + get duration() { + return this[rawDataSymbol].duration; + } + /** + * The duration of the video, in seconds. + */ + get durationInSeconds() { + const parts = this[rawDataSymbol].duration.match(/\d+[hms]/g); + if (!parts) { + throw new HellFreezesOverError(`Could not parse duration string: ${this[rawDataSymbol].duration}`); + } + return parts.map((part) => { + const partialMatch = /(\d+)([hms])/.exec(part); + if (!partialMatch) { + throw new HellFreezesOverError(`Could not parse partial duration string: ${part}`); + } + const [, num, unit] = partialMatch; + return parseInt(num, 10) * { h: 3600, m: 60, s: 1 }[unit]; + }).reduce((a, b) => a + b); + } + /** + * The ID of the stream this video belongs to. + * + * Returns null if the video is not an archived stream. + */ + get streamId() { + return this[rawDataSymbol].stream_id; + } + /** + * The raw data of muted segments of the video. + */ + get mutedSegmentData() { + return this[rawDataSymbol].muted_segments?.slice() ?? []; + } + /** + * Checks whether the video is muted at a given offset or range. + * + * @param offset The start of your range, in seconds from the start of the video, + * or if no duration is given, the exact offset that is checked. + * @param duration The duration of your range, in seconds. + * @param partial Whether the range check is only partial. + * + * By default, this function returns true only if the passed range is entirely contained in a muted segment. + */ + isMutedAt(offset, duration, partial = false) { + if (this[rawDataSymbol].muted_segments === null) { + return false; + } + if (duration == null) { + return this[rawDataSymbol].muted_segments.some((seg) => seg.offset <= offset && offset <= seg.offset + seg.duration); + } + const end = offset + duration; + if (partial) { + return this[rawDataSymbol].muted_segments.some((seg) => { + const segEnd = seg.offset + seg.duration; + return offset < segEnd && seg.offset < end; + }); + } + return this[rawDataSymbol].muted_segments.some((seg) => { + const segEnd = seg.offset + seg.duration; + return seg.offset <= offset && end <= segEnd; + }); + } +}; +__decorate([ + Enumerable(false) +], HelixVideo.prototype, "_client", void 0); +__decorate([ + CachedGetter() +], HelixVideo.prototype, "durationInSeconds", null); +HelixVideo = __decorate([ + Cacheable, + rtfm("api", "HelixVideo", "id") +], HelixVideo); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/video/HelixVideoApi.js +var HelixVideoApi_1; +var HelixVideoApi = HelixVideoApi_1 = class HelixVideoApi2 extends BaseApi { + static { + __name(this, "HelixVideoApi"); + } + /** @internal */ + _getVideoByIdBatcher = new HelixRequestBatcher({ + url: "videos" + }, "id", "id", this._client, (data2) => new HelixVideo(data2, this._client)); + /** + * Gets the video data for the given list of video IDs. + * + * @param ids The video IDs you want to look up. + */ + async getVideosByIds(ids) { + const result = await this._getVideos("id", ids); + return result.data; + } + /** + * Gets the video data for the given video ID. + * + * @param id The video ID you want to look up. + */ + async getVideoById(id) { + const videos = await this.getVideosByIds([id]); + return videos.length ? videos[0] : null; + } + /** + * Gets the video data for the given video ID, batching multiple calls into fewer requests as the API allows. + * + * @param id The video ID you want to look up. + */ + async getVideoByIdBatched(id) { + return await this._getVideoByIdBatcher.request(id); + } + /** + * Gets the videos of the given user. + * + * @param user The user you want to get videos from. + * @param filter + * + * @expandParams + */ + async getVideosByUser(user, filter = {}) { + const userId = extractUserId(user); + return await this._getVideos("user_id", [userId], filter); + } + /** + * Creates a paginator for videos of the given user. + * + * @param user The user you want to get videos from. + * @param filter + * + * @expandParams + */ + getVideosByUserPaginated(user, filter = {}) { + const userId = extractUserId(user); + return this._getVideosPaginated("user_id", [userId], filter); + } + /** + * Gets the videos of the given game. + * + * @param gameId The game you want to get videos from. + * @param filter + * + * @expandParams + */ + async getVideosByGame(gameId, filter = {}) { + return await this._getVideos("game_id", [gameId], filter); + } + /** + * Creates a paginator for videos of the given game. + * + * @param gameId The game you want to get videos from. + * @param filter + * + * @expandParams + */ + getVideosByGamePaginated(gameId, filter = {}) { + return this._getVideosPaginated("game_id", [gameId], filter); + } + /** + * Deletes videos by its IDs. + * + * @param broadcaster The broadcaster to delete the videos for. + * @param ids The IDs of the videos to delete. + */ + async deleteVideosByIds(broadcaster, ids) { + await this._client.callApi({ + type: "helix", + url: "videos", + method: "DELETE", + scopes: ["channel:manage:videos"], + userId: extractUserId(broadcaster), + query: { + id: ids + } + }); + } + /** @internal */ + async _getVideos(filterType, filterValues, filter = {}) { + if (!filterValues.length) { + return { data: [] }; + } + const result = await this._client.callApi({ + type: "helix", + url: "videos", + userId: filterType === "user_id" ? filterValues[0] : void 0, + query: { + ...HelixVideoApi_1._makeVideosQuery(filterType, filterValues, filter), + ...createPaginationQuery(filter) + } + }); + return createPaginatedResult(result, HelixVideo, this._client); + } + /** @internal */ + _getVideosPaginated(filterType, filterValues, filter = {}) { + return new HelixPaginatedRequest({ + url: "videos", + userId: filterType === "user_id" ? filterValues[0] : void 0, + query: HelixVideoApi_1._makeVideosQuery(filterType, filterValues, filter) + }, this._client, (data2) => new HelixVideo(data2, this._client)); + } + /** @internal */ + static _makeVideosQuery(filterType, filterValues, filter = {}) { + const { language, period, orderBy, type } = filter; + return { + [filterType]: filterValues, + language, + period, + sort: orderBy, + type + }; + } +}; +__decorate([ + Enumerable(false) +], HelixVideoApi.prototype, "_getVideoByIdBatcher", void 0); +HelixVideoApi = HelixVideoApi_1 = __decorate([ + rtfm("api", "HelixVideoApi") +], HelixVideoApi); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/whisper/HelixWhisperApi.js +init_modules_watch_stub(); +init_performance2(); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/interfaces/endpoints/whisper.external.js +init_modules_watch_stub(); +init_performance2(); +function createWhisperQuery(from, to) { + return { + from_user_id: extractUserId(from), + to_user_id: extractUserId(to) + }; +} +__name(createWhisperQuery, "createWhisperQuery"); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/whisper/HelixWhisperApi.js +var HelixWhisperApi = class HelixWhisperApi2 extends BaseApi { + static { + __name(this, "HelixWhisperApi"); + } + /** + * Sends a whisper message to the specified user. + * + * NOTE: The API may silently drop whispers that it suspects of violating Twitch policies. (The API does not indicate that it dropped the whisper; it returns a 204 status code as if it succeeded). + * + * @param from The user sending the whisper. This user must have a verified phone number and must match the user in the access token. + * @param to The user to receive the whisper. + * @param message The whisper message to send. The message must not be empty. + * + * The maximum message lengths are: + * + * 500 characters if the user you're sending the message to hasn't whispered you before. + * 10,000 characters if the user you're sending the message to has whispered you before. + * + * Messages that exceed the maximum length are truncated. + */ + async sendWhisper(from, to, message) { + await this._client.callApi({ + type: "helix", + url: "whispers", + method: "POST", + userId: extractUserId(from), + scopes: ["user:manage:whispers"], + query: createWhisperQuery(from, to), + jsonBody: { + message + } + }); + } +}; +HelixWhisperApi = __decorate([ + rtfm("api", "HelixWhisperApi") +], HelixWhisperApi); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/reporting/ApiReportedRequest.js +init_modules_watch_stub(); +init_performance2(); +var ApiReportedRequest = class { + static { + __name(this, "ApiReportedRequest"); + } + _options; + _httpStatus; + _resolvedUserId; + /** @internal */ + constructor(_options, _httpStatus, _resolvedUserId) { + this._options = _options; + this._httpStatus = _httpStatus; + this._resolvedUserId = _resolvedUserId; + } + /** + * The options used to call the API. + */ + get options() { + return this._options; + } + /** + * The HTTP status code returned by Twitch for the request. + */ + get httpStatus() { + return this._httpStatus; + } + /** + * The ID of the user that was used for authentication, or `null` if an app access token was used. + */ + get resolvedUserId() { + return this._resolvedUserId; + } +}; + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/client/BaseApiClient.js +var BaseApiClient = class BaseApiClient2 extends EventEmitter2 { + static { + __name(this, "BaseApiClient"); + } + _config; + _logger; + _rateLimiter; + onRequest = this.registerEvent(); + /** @internal */ + constructor(config2, logger, rateLimiter) { + super(); + this._config = config2; + this._logger = logger; + this._rateLimiter = rateLimiter; + } + /** + * Requests scopes from the auth provider for the given user. + * + * @param user The user to request scopes for. + * @param scopes The scopes to request. + */ + async requestScopesForUser(user, scopes) { + await this._config.authProvider.getAccessTokenForUser(user, ...scopes.map((scope) => [scope])); + } + /** + * Gets information about your access token. + */ + async getTokenInfo() { + try { + const data2 = await this.callApi({ type: "auth", url: "validate" }); + return new TokenInfo(data2); + } catch (e) { + if (e instanceof HttpStatusCodeError && e.statusCode === 401) { + throw new InvalidTokenError({ cause: e }); + } + throw e; + } + } + /** + * Makes a call to the Twitch API using your access token. + * + * @param options The configuration of the call. + */ + async callApi(options) { + const { authProvider } = this._config; + const shouldAuth = options.auth ?? true; + if (!shouldAuth) { + return await callTwitchApi(options, authProvider.clientId, void 0, void 0, this._config.fetchOptions); + } + let forceUser = false; + if (options.forceType) { + switch (options.forceType) { + case "app": { + if (!authProvider.getAppAccessToken) { + throw new Error("Tried to make an API call that requires an app access token but your auth provider does not support that"); + } + const accessToken2 = await authProvider.getAppAccessToken(); + return await this._callApiUsingInitialToken(options, accessToken2); + } + case "user": { + forceUser = true; + break; + } + default: { + throw new HellFreezesOverError(`Unknown forced token type: ${options.forceType}`); + } + } + } + if (options.scopes) { + forceUser = true; + } + if (forceUser) { + const contextUserId = options.canOverrideScopedUserContext ? this._getUserIdFromRequestContext(options.userId) : options.userId; + if (!contextUserId) { + throw new Error("Tried to make an API call with a user context but no context user ID"); + } + const accessToken2 = await authProvider.getAccessTokenForUser(contextUserId, options.scopes); + if (!accessToken2) { + throw new Error(`Tried to make an API call with a user context for user ID ${contextUserId} but no token was found`); + } + if (accessTokenIsExpired(accessToken2) && authProvider.refreshAccessTokenForUser) { + const newAccessToken = await authProvider.refreshAccessTokenForUser(contextUserId); + return await this._callApiUsingInitialToken(options, newAccessToken, true); + } + return await this._callApiUsingInitialToken(options, accessToken2); + } + const requestContextUserId = this._getUserIdFromRequestContext(options.userId); + const accessToken = requestContextUserId === null ? await authProvider.getAnyAccessToken() : await authProvider.getAnyAccessToken(requestContextUserId ?? options.userId); + if (accessTokenIsExpired(accessToken) && accessToken.userId && authProvider.refreshAccessTokenForUser) { + const newAccessToken = await authProvider.refreshAccessTokenForUser(accessToken.userId); + return await this._callApiUsingInitialToken(options, newAccessToken, true); + } + return await this._callApiUsingInitialToken(options, accessToken); + } + /** + * The Helix bits API methods. + */ + get bits() { + return new HelixBitsApi(this); + } + /** + * The Helix channels API methods. + */ + get channels() { + return new HelixChannelApi(this); + } + /** + * The Helix channel points API methods. + */ + get channelPoints() { + return new HelixChannelPointsApi(this); + } + /** + * The Helix charity API methods. + */ + get charity() { + return new HelixCharityApi(this); + } + /** + * The Helix chat API methods. + */ + get chat() { + return new HelixChatApi(this); + } + /** + * The Helix clips API methods. + */ + get clips() { + return new HelixClipApi(this); + } + /** + * The Helix content classification label API methods. + */ + get contentClassificationLabels() { + return new HelixContentClassificationLabelApi(this); + } + /** + * The Helix entitlement API methods. + */ + get entitlements() { + return new HelixEntitlementApi(this); + } + /** + * The Helix EventSub API methods. + */ + get eventSub() { + return new HelixEventSubApi(this); + } + /** + * The Helix extensions API methods. + */ + get extensions() { + return new HelixExtensionsApi(this); + } + /** + * The Helix game API methods. + */ + get games() { + return new HelixGameApi(this); + } + /** + * The Helix Hype Train API methods. + */ + get hypeTrain() { + return new HelixHypeTrainApi(this); + } + /** + * The Helix goal API methods. + */ + get goals() { + return new HelixGoalApi(this); + } + /** + * The Helix moderation API methods. + */ + get moderation() { + return new HelixModerationApi(this); + } + /** + * The Helix poll API methods. + */ + get polls() { + return new HelixPollApi(this); + } + /** + * The Helix prediction API methods. + */ + get predictions() { + return new HelixPredictionApi(this); + } + /** + * The Helix raid API methods. + */ + get raids() { + return new HelixRaidApi(this); + } + /** + * The Helix schedule API methods. + */ + get schedule() { + return new HelixScheduleApi(this); + } + /** + * The Helix search API methods. + */ + get search() { + return new HelixSearchApi(this); + } + /** + * The Helix stream API methods. + */ + get streams() { + return new HelixStreamApi(this); + } + /** + * The Helix subscription API methods. + */ + get subscriptions() { + return new HelixSubscriptionApi(this); + } + /** + * The Helix team API methods. + */ + get teams() { + return new HelixTeamApi(this); + } + /** + * The Helix user API methods. + */ + get users() { + return new HelixUserApi(this); + } + /** + * The Helix video API methods. + */ + get videos() { + return new HelixVideoApi(this); + } + /** + * The API methods that deal with whispers. + */ + get whispers() { + return new HelixWhisperApi(this); + } + /** + * Statistics on the rate limiter for the Helix API. + */ + get rateLimiterStats() { + if (this._rateLimiter instanceof ResponseBasedRateLimiter) { + return this._rateLimiter.stats; + } + return null; + } + /** @private */ + get _authProvider() { + return this._config.authProvider; + } + /** @internal */ + get _batchDelay() { + return this._config.batchDelay ?? 0; + } + // null means app access, undefined means none specified + /** @internal */ + _getUserIdFromRequestContext(contextUserId) { + return contextUserId; + } + async _callApiUsingInitialToken(options, accessToken, wasRefreshed = false) { + const { authProvider } = this._config; + const { authorizationType } = authProvider; + let response = await this._callApiInternal(options, authProvider.clientId, accessToken.accessToken, authorizationType); + if (response.status === 401 && !wasRefreshed) { + if (accessToken.userId) { + if (authProvider.refreshAccessTokenForUser) { + const token = await authProvider.refreshAccessTokenForUser(accessToken.userId); + response = await this._callApiInternal(options, authProvider.clientId, token.accessToken, authorizationType); + } + } else if (authProvider.getAppAccessToken) { + const token = await authProvider.getAppAccessToken(true); + response = await this._callApiInternal(options, authProvider.clientId, token.accessToken, authorizationType); + } + } + this.emit(this.onRequest, new ApiReportedRequest(options, response.status, accessToken.userId ?? null)); + await handleTwitchApiResponseError(response, options); + return await transformTwitchApiResponse(response); + } + async _callApiInternal(options, clientId, accessToken, authorizationType) { + const { fetchOptions } = this._config; + const type = options.type ?? "helix"; + this._logger.debug(`Calling ${type} API: ${options.method ?? "GET"} ${options.url}`); + this._logger.trace(`Query: ${JSON.stringify(options.query)}`); + if (options.jsonBody) { + this._logger.trace(`Request body: ${JSON.stringify(options.jsonBody)}`); + } + const op = retry.operation({ + retries: 3, + minTimeout: 500, + factor: 2 + }); + const { promise, resolve, reject } = promiseWithResolvers(); + op.attempt(async () => { + try { + const response = type === "helix" ? await this._rateLimiter.request({ + options, + clientId, + accessToken, + authorizationType, + fetchOptions + }) : await callTwitchApiRaw(options, clientId, accessToken, authorizationType, fetchOptions); + if (!response.ok && response.status >= 500 && response.status < 600) { + await handleTwitchApiResponseError(response, options); + } + resolve(response); + } catch (e) { + if (op.retry(e)) { + return; + } + reject(op.mainError()); + } + }); + const result = await promise; + this._logger.debug(`Called ${type} API: ${options.method ?? "GET"} ${options.url} - result: ${result.status}`); + return result; + } +}; +__decorate([ + CachedGetter() +], BaseApiClient.prototype, "bits", null); +__decorate([ + CachedGetter() +], BaseApiClient.prototype, "channels", null); +__decorate([ + CachedGetter() +], BaseApiClient.prototype, "channelPoints", null); +__decorate([ + CachedGetter() +], BaseApiClient.prototype, "charity", null); +__decorate([ + CachedGetter() +], BaseApiClient.prototype, "chat", null); +__decorate([ + CachedGetter() +], BaseApiClient.prototype, "clips", null); +__decorate([ + CachedGetter() +], BaseApiClient.prototype, "contentClassificationLabels", null); +__decorate([ + CachedGetter() +], BaseApiClient.prototype, "entitlements", null); +__decorate([ + CachedGetter() +], BaseApiClient.prototype, "eventSub", null); +__decorate([ + CachedGetter() +], BaseApiClient.prototype, "extensions", null); +__decorate([ + CachedGetter() +], BaseApiClient.prototype, "games", null); +__decorate([ + CachedGetter() +], BaseApiClient.prototype, "hypeTrain", null); +__decorate([ + CachedGetter() +], BaseApiClient.prototype, "goals", null); +__decorate([ + CachedGetter() +], BaseApiClient.prototype, "moderation", null); +__decorate([ + CachedGetter() +], BaseApiClient.prototype, "polls", null); +__decorate([ + CachedGetter() +], BaseApiClient.prototype, "predictions", null); +__decorate([ + CachedGetter() +], BaseApiClient.prototype, "raids", null); +__decorate([ + CachedGetter() +], BaseApiClient.prototype, "schedule", null); +__decorate([ + CachedGetter() +], BaseApiClient.prototype, "search", null); +__decorate([ + CachedGetter() +], BaseApiClient.prototype, "streams", null); +__decorate([ + CachedGetter() +], BaseApiClient.prototype, "subscriptions", null); +__decorate([ + CachedGetter() +], BaseApiClient.prototype, "teams", null); +__decorate([ + CachedGetter() +], BaseApiClient.prototype, "users", null); +__decorate([ + CachedGetter() +], BaseApiClient.prototype, "videos", null); +__decorate([ + CachedGetter() +], BaseApiClient.prototype, "whispers", null); +BaseApiClient = __decorate([ + Cacheable, + rtfm("api", "ApiClient") +], BaseApiClient); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/client/NoContextApiClient.js +init_modules_watch_stub(); +init_performance2(); +var NoContextApiClient = class NoContextApiClient2 extends BaseApiClient { + static { + __name(this, "NoContextApiClient"); + } + /** @internal */ + _getUserIdFromRequestContext() { + return null; + } +}; +NoContextApiClient = __decorate([ + rtfm("api", "ApiClient") +], NoContextApiClient); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/client/UserContextApiClient.js +init_modules_watch_stub(); +init_performance2(); +var UserContextApiClient = class UserContextApiClient2 extends BaseApiClient { + static { + __name(this, "UserContextApiClient"); + } + _userId; + /** @internal */ + constructor(config2, logger, rateLimiter, _userId) { + super(config2, logger, rateLimiter); + this._userId = _userId; + } + /** @internal */ + _getUserIdFromRequestContext() { + return this._userId; + } +}; +UserContextApiClient = __decorate([ + rtfm("api", "ApiClient") +], UserContextApiClient); + +// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/client/ApiClient.js +var ApiClient2 = class ApiClient3 extends BaseApiClient { + static { + __name(this, "ApiClient"); + } + /** + * Creates a new API client instance. + * + * @param config Configuration for the client instance. + */ + constructor(config2) { + if (!config2.authProvider) { + throw new ConfigError("No auth provider given. Please supply the `authProvider` option."); + } + const rateLimitLoggerOptions = { name: "twurple:api:rate-limiter", ...config2.logger }; + super(config2, createLogger({ name: "twurple:api:client", ...config2.logger }), import_detect_node4.isNode ? new PartitionedRateLimiter({ + getPartitionKey: /* @__PURE__ */ __name((req) => req.userId ?? null, "getPartitionKey"), + createChild: /* @__PURE__ */ __name(() => new HelixRateLimiter({ logger: rateLimitLoggerOptions }), "createChild") + }) : new PartitionedTimeBasedRateLimiter({ + logger: rateLimitLoggerOptions, + bucketSize: 800, + timeFrame: 64e3, + doRequest: /* @__PURE__ */ __name(async ({ options, clientId, accessToken, authorizationType, fetchOptions }) => await callTwitchApiRaw(options, clientId, accessToken, authorizationType, fetchOptions), "doRequest"), + getPartitionKey: /* @__PURE__ */ __name((req) => req.userId ?? null, "getPartitionKey") + })); + } + /** + * Creates a contextualized ApiClient that can be used to call the API in the context of a given user. + * + * @param user The user to use as context. + * @param runner The callback to execute. + * + * A parameter is passed that should be used in place of the normal `ApiClient` + * to ensure that all requests are executed in the given user's context. + * + * Please note that requests which require scope authorization ignore this context. + * + * The return value of your callback will be propagated to the return value of this method. + */ + async asUser(user, runner) { + const ctx = new UserContextApiClient(this._config, this._logger, this._rateLimiter, extractUserId(user)); + return await runner(ctx); + } + /** + * Creates a contextualized ApiClient that can be used to call the API in the context of a given intent. + * + * @param intents A list of intents. The first one that is found in your auth provider will be used. + * @param runner The callback to execute. + * + * A parameter is passed that should be used in place of the normal `ApiClient` + * to ensure that all requests are executed in the given user's context. + * + * Please note that requests which require scope authorization ignore this context. + * + * The return value of your callback will be propagated to the return value of this method. + */ + async asIntent(intents, runner) { + if (!this._authProvider.getAccessTokenForIntent) { + throw new Error("Trying to use intents with an auth provider that does not support them"); + } + for (const intent of intents) { + const user = await this._authProvider.getAccessTokenForIntent(intent); + if (user) { + const ctx = new UserContextApiClient(this._config, this._logger, this._rateLimiter, user.userId); + return await runner(ctx); + } + } + throw new Error(`Intents [${intents.join(", ")}] not found in auth provider`); + } + /** + * Creates a contextualized ApiClient that can be used to call the API without the context of any user. + * + * This usually means that an app access token is used. + * + * @param runner The callback to execute. + * + * A parameter is passed that should be used in place of the normal `ApiClient` + * to ensure that all requests are executed without user context. + * + * Please note that requests which require scope authorization ignore this context erasure. + * + * The return value of your callback will be propagated to the return value of this method. + */ + async withoutUser(runner) { + const ctx = new NoContextApiClient(this._config, this._logger, this._rateLimiter); + return await runner(ctx); + } +}; +ApiClient2 = __decorate([ + rtfm("api", "ApiClient") +], ApiClient2); + +// src/services/twitch.service.ts +var TwitchService = class { + static { + __name(this, "TwitchService"); + } + apiClient; + authProvider; + constructor(env) { + this.authProvider = new AppTokenAuthProvider( + env.TWITCH_CLIENT_ID, + env.TWITCH_CLIENT_SECRET + ); + this.apiClient = new ApiClient2({ authProvider: this.authProvider }); + } + async getUserByLogin(login) { + try { + return await this.apiClient.users.getUserByName(login); + } catch (error) { + return null; + } + } + async getUserById(id) { + try { + return await this.apiClient.users.getUserById(id); + } catch (error) { + return null; + } + } + async getStreamByUserId(userId) { + try { + return await this.apiClient.streams.getStreamByUserId(userId); + } catch (error) { + return null; + } + } + async getGameById(gameId) { + try { + return await this.apiClient.games.getGameById(gameId); + } catch (error) { + return null; + } + } + getApiClient() { + return this.apiClient; + } + getAuthProvider() { + return this.authProvider; + } +}; + +// src/services/telegram.service.ts +init_modules_watch_stub(); +init_performance2(); + +// src/utils/thumbnail.ts +init_modules_watch_stub(); +init_performance2(); +var ThumbnailBuilder = class { + static { + __name(this, "ThumbnailBuilder"); + } + /** + * Build thumbnail URL from Twitch template URL + * @param thumbnailUrl - Twitch thumbnail URL with {width} and {height} placeholders + * @param checkValidity - Whether to check if the URL is accessible (with retry logic) + * @returns Final thumbnail URL + */ + async build(thumbnailUrl, checkValidity = false) { + let thumbnail = thumbnailUrl.replace("{width}", "1920").replace("{height}", "1080"); + if (!checkValidity) { + return thumbnail; + } + const isValid = await this.checkValidity(thumbnail, 0); + if (!isValid) { + thumbnail = thumbnail.replace("1920", "1280").replace("1080", "720"); + } + return thumbnail; + } + /** + * Check if thumbnail URL is accessible with retry logic + * @param url - URL to check + * @param attempt - Current attempt number (max 5) + * @returns Whether the URL is valid + */ + async checkValidity(url, attempt) { + try { + const response = await fetch(url, { + method: "HEAD", + redirect: "manual" + }); + if (response.status === 200) { + return true; + } + if (attempt >= 5) { + return false; + } + await new Promise((resolve) => setTimeout(resolve, 5e3)); + return this.checkValidity(url, attempt + 1); + } catch (error) { + if (attempt >= 5) { + return false; + } + await new Promise((resolve) => setTimeout(resolve, 5e3)); + return this.checkValidity(url, attempt + 1); + } + } +}; + +// src/services/telegram.service.ts +var TelegramService = class { + static { + __name(this, "TelegramService"); + } + bot; + i18n; + thumbnailBuilder; + constructor(env, i18n) { + this.bot = new Bot(env.TELEGRAM_TOKEN); + this.i18n = i18n; + this.thumbnailBuilder = new ThumbnailBuilder(); + } + async sendStreamOnlineNotification(notification) { + const channelLink = `${notification.channelName}`; + const text2 = this.i18n.t(notification.language, "notifications.streams.nowOnline", { + channelLink, + category: notification.category, + title: notification.title + }); + if (notification.showImage && notification.thumbnailUrl) { + try { + const thumbnailUrl = await this.thumbnailBuilder.build(notification.thumbnailUrl, true); + await this.bot.api.sendPhoto(notification.chatId, new InputFile(new URL(thumbnailUrl)), { + caption: text2, + parse_mode: "HTML" + }); + return; + } catch (error) { + console.error("Failed to send photo:", error); + } + } + await this.bot.api.sendMessage(notification.chatId, text2, { + parse_mode: "HTML", + link_preview_options: { is_disabled: false } + }); + } + async sendStreamOfflineNotification(notification) { + const channelLink = `${notification.channelName}`; + const categories = notification.categories.join(", "); + const text2 = this.i18n.t(notification.language, "notifications.streams.nowOffline", { + channelLink, + categories, + duration: notification.duration + }); + await this.bot.api.sendMessage(notification.chatId, text2, { + parse_mode: "HTML", + link_preview_options: { is_disabled: true } + }); + } + async sendCategoryChangeNotification(notification) { + const channelLink = `${notification.channelName}`; + const text2 = this.i18n.t(notification.language, "notifications.streams.newCategory", { + channelLink, + oldCategory: notification.oldCategory, + category: notification.category + }); + await this.bot.api.sendMessage(notification.chatId, text2, { + parse_mode: "HTML", + link_preview_options: { is_disabled: true } + }); + } + async sendTitleChangeNotification(notification) { + const channelLink = `${notification.channelName}`; + const text2 = this.i18n.t(notification.language, "notifications.streams.titleChanged", { + channelLink, + oldTitle: notification.oldTitle, + title: notification.title + }); + await this.bot.api.sendMessage(notification.chatId, text2, { + parse_mode: "HTML", + link_preview_options: { is_disabled: true } + }); + } + async sendTitleAndCategoryChangeNotification(notification) { + const channelLink = `${notification.channelName}`; + const text2 = this.i18n.t(notification.language, "notifications.streams.titleAndCategoryChanged", { + channelLink, + oldTitle: notification.oldTitle, + title: notification.title, + oldCategory: notification.oldCategory, + category: notification.category + }); + await this.bot.api.sendMessage(notification.chatId, text2, { + parse_mode: "HTML", + link_preview_options: { is_disabled: true } + }); + } + getBot() { + return this.bot; + } +}; + +// src/services/eventsub.service.ts +init_modules_watch_stub(); +init_performance2(); +var EventSubService = class { + static { + __name(this, "EventSubService"); + } + apiClient; + webhookUrl; + secret; + constructor(apiClient, env, baseUrl) { + this.apiClient = apiClient; + this.webhookUrl = `${baseUrl}/twitch-webhook`; + this.secret = env.TWITCH_EVENTSUB_SECRET; + } + /** + * Subscribe to all events for a broadcaster (stream.online, stream.offline, channel.update) + */ + async subscribeToChannel(broadcasterId) { + try { + await this.apiClient.eventSub.subscribeToStreamOnlineEvents( + broadcasterId, + { + method: "webhook", + callback: this.webhookUrl, + secret: this.secret + } + ); + await this.apiClient.eventSub.subscribeToStreamOfflineEvents( + broadcasterId, + { + method: "webhook", + callback: this.webhookUrl, + secret: this.secret + } + ); + await this.apiClient.eventSub.subscribeToChannelUpdateEvents( + broadcasterId, + { + method: "webhook", + callback: this.webhookUrl, + secret: this.secret + } + ); + } catch (error) { + console.error(`Failed to subscribe to events for broadcaster ${broadcasterId}:`, error); + throw error; + } + } + /** + * Unsubscribe from all events for a broadcaster + */ + async unsubscribeFromChannel(broadcasterId) { + try { + const subscriptions = await this.apiClient.eventSub.getSubscriptions(); + const broadcasterSubs = subscriptions.data.filter( + (sub) => { + const transportMethod = sub.transport?.callback || sub._transport?.callback; + const broadcastId = sub.condition.broadcaster_user_id; + return transportMethod === this.webhookUrl && broadcastId === broadcasterId; + } + ); + for (const sub of broadcasterSubs) { + await this.apiClient.eventSub.deleteSubscription(sub.id); + } + } catch (error) { + console.error(`Failed to unsubscribe from events for broadcaster ${broadcasterId}:`, error); + throw error; + } + } + /** + * Check if we already have active subscriptions for a broadcaster + */ + async hasActiveSubscriptions(broadcasterId) { + try { + const subscriptions = await this.apiClient.eventSub.getSubscriptions(); + return subscriptions.data.some( + (sub) => { + const transportMethod = sub.transport?.callback || sub._transport?.callback; + const broadcastId = sub.condition.broadcaster_user_id; + return transportMethod === this.webhookUrl && broadcastId === broadcasterId && sub.status === "enabled"; + } + ); + } catch (error) { + console.error(`Failed to check subscriptions for broadcaster ${broadcasterId}:`, error); + return false; + } + } + /** + * Delete a specific subscription by ID + */ + async deleteSubscription(subscriptionId) { + try { + await this.apiClient.eventSub.deleteSubscription(subscriptionId); + } catch (error) { + console.error(`Failed to delete subscription ${subscriptionId}:`, error); + throw error; + } + } + /** + * Get all active subscriptions for our webhook + */ + async getActiveSubscriptions() { + try { + const subscriptions = await this.apiClient.eventSub.getSubscriptions(); + return subscriptions.data.filter((sub) => { + const transportMethod = sub.transport?.callback || sub._transport?.callback; + return transportMethod === this.webhookUrl; + }); + } catch (error) { + console.error("Failed to get active subscriptions:", error); + return []; + } + } +}; + +// src/db/connection.ts +init_modules_watch_stub(); +init_performance2(); +var CloudflareD1Connection = class { + constructor(client) { + this.client = client; + } + static { + __name(this, "CloudflareD1Connection"); + } + getClient() { + return this.client; + } +}; + +// src/db/repository.factory.ts +init_modules_watch_stub(); +init_performance2(); + +// src/db/repositories/drizzle/index.ts +init_modules_watch_stub(); +init_performance2(); + +// src/db/repositories/drizzle/chat.drizzle.repository.ts +init_modules_watch_stub(); +init_performance2(); +import { randomUUID as randomUUID2 } from "node:crypto"; + +// src/db/schema.ts +init_modules_watch_stub(); +init_performance2(); +import { randomUUID } from "node:crypto"; +var chats = sqliteTable("chats", { + id: text("id").primaryKey().$defaultFn(() => randomUUID()), + chatId: text("chat_id").notNull(), + service: text("service", { enum: ["telegram"] }).notNull().default("telegram") +}); +var chatsRelations = relations(chats, ({ one, many }) => ({ + settings: one(chatSettings, { + fields: [chats.id], + references: [chatSettings.chatId] + }), + follows: many(follows) +})); +var chatSettings = sqliteTable("chat_settings", { + id: text("id").primaryKey().$defaultFn(() => randomUUID()), + chatId: text("chat_id").notNull().unique().references(() => chats.id, { onDelete: "cascade" }), + gameChangeNotification: integer("game_change_notification", { mode: "boolean" }).notNull().default(true), + titleChangeNotification: integer("title_change_notification", { mode: "boolean" }).notNull().default(false), + gameAndTitleChangeNotification: integer("game_and_title_change_notification", { mode: "boolean" }).notNull().default(false), + offlineNotification: integer("offline_notification", { mode: "boolean" }).notNull().default(true), + imageInNotification: integer("image_in_notification", { mode: "boolean" }).notNull().default(true), + language: text("language", { enum: ["ru", "en", "uk"] }).notNull().default("en") +}); +var chatSettingsRelations = relations(chatSettings, ({ one }) => ({ + chat: one(chats, { + fields: [chatSettings.chatId], + references: [chats.id] + }) +})); +var channels = sqliteTable("channels", { + id: text("id").primaryKey().$defaultFn(() => randomUUID()), + channelId: text("channel_id").notNull(), + service: text("service", { enum: ["twitch"] }).notNull().default("twitch"), + isLive: integer("is_live", { mode: "boolean" }).notNull().default(false), + title: text("title"), + category: text("category"), + updatedAt: text("updated_at").$defaultFn(() => (/* @__PURE__ */ new Date()).toISOString()) +}); +var channelsRelations = relations(channels, ({ many }) => ({ + follows: many(follows), + streams: many(streams) +})); +var follows = sqliteTable("follows", { + id: text("id").primaryKey().$defaultFn(() => randomUUID()), + channelId: text("channel_id").notNull().references(() => channels.id, { onDelete: "cascade" }), + chatId: text("chat_id").notNull().references(() => chats.id, { onDelete: "cascade" }) +}); +var followsRelations = relations(follows, ({ one }) => ({ + channel: one(channels, { + fields: [follows.channelId], + references: [channels.id] + }), + chat: one(chats, { + fields: [follows.chatId], + references: [chats.id] + }) +})); +var streams = sqliteTable("streams", { + id: text("id").primaryKey(), + // Twitch stream ID + channelId: text("channel_id").notNull().references(() => channels.id, { onDelete: "cascade" }), + isLive: integer("is_live", { mode: "boolean" }).notNull().default(true), + title: text("title"), + category: text("category"), + titles: text("titles", { mode: "json" }).$type().notNull().default([]), + categories: text("categories", { mode: "json" }).$type().notNull().default([]), + startedAt: text("started_at").$defaultFn(() => (/* @__PURE__ */ new Date()).toISOString()), + updatedAt: text("updated_at").$defaultFn(() => (/* @__PURE__ */ new Date()).toISOString()), + endedAt: text("ended_at") +}); +var streamsRelations = relations(streams, ({ one }) => ({ + channel: one(channels, { + fields: [streams.channelId], + references: [channels.id] + }) +})); + +// src/domain/mapper.ts +init_modules_watch_stub(); +init_performance2(); + +// src/domain/models.ts +init_modules_watch_stub(); +init_performance2(); +var Chat = class { + static { + __name(this, "Chat"); + } + id; + chatId; + service; + settings; + follows; + constructor(data2) { + this.id = data2.id; + this.chatId = data2.chatId; + this.service = data2.service; + this.settings = data2.settings; + this.follows = data2.follows; + } +}; +var ChatSettings = class { + static { + __name(this, "ChatSettings"); + } + id; + chatId; + gameChangeNotification; + titleChangeNotification; + gameAndTitleChangeNotification; + offlineNotification; + imageInNotification; + language; + constructor(data2) { + this.id = data2.id; + this.chatId = data2.chatId; + this.gameChangeNotification = data2.gameChangeNotification; + this.titleChangeNotification = data2.titleChangeNotification; + this.gameAndTitleChangeNotification = data2.gameAndTitleChangeNotification; + this.offlineNotification = data2.offlineNotification; + this.imageInNotification = data2.imageInNotification; + this.language = data2.language; + } +}; +var Channel = class { + static { + __name(this, "Channel"); + } + id; + channelId; + service; + isLive; + title; + category; + updatedAt; + follows; + streams; + constructor(data2) { + this.id = data2.id; + this.channelId = data2.channelId; + this.service = data2.service; + this.isLive = data2.isLive; + this.title = data2.title; + this.category = data2.category; + this.updatedAt = data2.updatedAt; + this.follows = data2.follows; + this.streams = data2.streams; + } +}; +var Follow = class { + static { + __name(this, "Follow"); + } + id; + channelId; + chatId; + channel; + chat; + constructor(data2) { + this.id = data2.id; + this.channelId = data2.channelId; + this.chatId = data2.chatId; + this.channel = data2.channel; + this.chat = data2.chat; + } +}; +var Stream = class { + static { + __name(this, "Stream"); + } + id; + channelId; + isLive; + title; + category; + titles; + categories; + startedAt; + updatedAt; + endedAt; + constructor(data2) { + this.id = data2.id; + this.channelId = data2.channelId; + this.isLive = data2.isLive; + this.title = data2.title; + this.category = data2.category; + this.titles = data2.titles; + this.categories = data2.categories; + this.startedAt = data2.startedAt; + this.updatedAt = data2.updatedAt; + this.endedAt = data2.endedAt; + } +}; +var FollowAlreadyExistsError = class extends Error { + static { + __name(this, "FollowAlreadyExistsError"); + } + constructor() { + super("Follow already exists"); + this.name = "FollowAlreadyExistsError"; + } +}; +var FollowNotFoundError = class extends Error { + static { + __name(this, "FollowNotFoundError"); + } + constructor() { + super("Follow not found"); + this.name = "FollowNotFoundError"; + } +}; +var ChannelNotFoundError = class extends Error { + static { + __name(this, "ChannelNotFoundError"); + } + constructor() { + super("Channel not found"); + this.name = "ChannelNotFoundError"; + } +}; + +// src/domain/mapper.ts +var DomainMapper = class { + static { + __name(this, "DomainMapper"); + } + static toDomainChat(dbChat) { + return new Chat({ + id: dbChat.id, + chatId: dbChat.chatId, + service: dbChat.service, + settings: dbChat.settings ? this.toDomainChatSettings(dbChat.settings) : void 0 + }); + } + static toDomainChatSettings(dbSettings) { + return new ChatSettings({ + id: dbSettings.id, + chatId: dbSettings.chatId, + gameChangeNotification: dbSettings.gameChangeNotification, + titleChangeNotification: dbSettings.titleChangeNotification, + gameAndTitleChangeNotification: dbSettings.gameAndTitleChangeNotification, + offlineNotification: dbSettings.offlineNotification, + imageInNotification: dbSettings.imageInNotification, + language: dbSettings.language + }); + } + static toDomainChannel(dbChannel) { + return new Channel({ + id: dbChannel.id, + channelId: dbChannel.channelId, + service: dbChannel.service, + isLive: dbChannel.isLive, + title: dbChannel.title ?? void 0, + category: dbChannel.category ?? void 0, + updatedAt: dbChannel.updatedAt ? new Date(dbChannel.updatedAt) : void 0 + }); + } + static toDomainFollow(dbFollow) { + return new Follow({ + id: dbFollow.id, + channelId: dbFollow.channelId, + chatId: dbFollow.chatId + }); + } + static toDomainStream(dbStream) { + return new Stream({ + id: dbStream.id, + channelId: dbStream.channelId, + isLive: dbStream.isLive, + title: dbStream.title ?? void 0, + category: dbStream.category ?? void 0, + titles: dbStream.titles, + categories: dbStream.categories, + startedAt: new Date(dbStream.startedAt), + updatedAt: dbStream.updatedAt ? new Date(dbStream.updatedAt) : void 0, + endedAt: dbStream.endedAt ? new Date(dbStream.endedAt) : void 0 + }); + } +}; + +// src/db/repositories/drizzle/chat.drizzle.repository.ts +var ChatDrizzleRepository = class { + constructor(db) { + this.db = db; + } + static { + __name(this, "ChatDrizzleRepository"); + } + async findByChatId(chatId, service = "telegram") { + const chatIdStr = chatId.toString(); + const chatResult = await this.db.select().from(chats).where(eq(chats.chatId, chatIdStr)).limit(1); + if (!chatResult[0]) return void 0; + const settingsResult = await this.db.select().from(chatSettings).where(eq(chatSettings.chatId, chatResult[0].id)).limit(1); + return DomainMapper.toDomainChat({ + ...chatResult[0], + settings: settingsResult[0] || null + }); + } + async findById(id) { + const chatResult = await this.db.select().from(chats).where(eq(chats.id, id)).limit(1); + if (!chatResult[0]) return void 0; + const settingsResult = await this.db.select().from(chatSettings).where(eq(chatSettings.chatId, chatResult[0].id)).limit(1); + return DomainMapper.toDomainChat({ + ...chatResult[0], + settings: settingsResult[0] || null + }); + } + async findAllByService(service = "telegram") { + const chatResults = await this.db.select().from(chats).where(eq(chats.service, service)); + const chatsWithSettings = []; + for (const chat of chatResults) { + const settingsResult = await this.db.select().from(chatSettings).where(eq(chatSettings.chatId, chat.id)).limit(1); + chatsWithSettings.push(DomainMapper.toDomainChat({ + ...chat, + settings: settingsResult[0] || null + })); + } + return chatsWithSettings; + } + async create(chatId, service = "telegram") { + const id = randomUUID2(); + await this.db.insert(chats).values({ id, chatId, service }); + await this.db.insert(chatSettings).values({ + chatId: id, + language: "en", + offlineNotification: true, + gameChangeNotification: false, + titleChangeNotification: false, + gameAndTitleChangeNotification: false, + imageInNotification: true + }); + return id; + } + async updateSettings(chatId, settings) { + await this.db.update(chatSettings).set(settings).where(eq(chatSettings.chatId, chatId)); + } +}; + +// src/db/repositories/drizzle/channel.drizzle.repository.ts +init_modules_watch_stub(); +init_performance2(); +import { randomUUID as randomUUID3 } from "node:crypto"; +var ChannelDrizzleRepository = class { + constructor(db) { + this.db = db; + } + static { + __name(this, "ChannelDrizzleRepository"); + } + async findByChannelId(channelId, service = "twitch") { + const result = await this.db.select().from(channels).where(and(eq(channels.channelId, channelId), eq(channels.service, service))).limit(1); + return result[0] ? DomainMapper.toDomainChannel(result[0]) : void 0; + } + async findById(id) { + const result = await this.db.select().from(channels).where(eq(channels.id, id)).limit(1); + return result[0] ? DomainMapper.toDomainChannel(result[0]) : void 0; + } + async create(channelId, service = "twitch") { + const id = randomUUID3(); + const result = await this.db.insert(channels).values({ + id, + channelId, + service, + isLive: false + }).returning(); + return DomainMapper.toDomainChannel(result[0]); + } + async update(id, data2) { + const result = await this.db.update(channels).set({ ...data2, updatedAt: (/* @__PURE__ */ new Date()).toISOString() }).where(eq(channels.id, id)).returning(); + if (!result[0]) { + throw new ChannelNotFoundError(); + } + return DomainMapper.toDomainChannel(result[0]); + } + async updateChannelId(oldChannelId, newChannelId, service = "twitch") { + await this.db.update(channels).set({ channelId: newChannelId, updatedAt: (/* @__PURE__ */ new Date()).toISOString() }).where(and(eq(channels.channelId, oldChannelId), eq(channels.service, service))); + } +}; + +// src/db/repositories/drizzle/follow.drizzle.repository.ts +init_modules_watch_stub(); +init_performance2(); +import { randomUUID as randomUUID4 } from "node:crypto"; +var FollowDrizzleRepository = class { + constructor(db) { + this.db = db; + } + static { + __name(this, "FollowDrizzleRepository"); + } + async findByChatAndChannel(chatId, channelId) { + const result = await this.db.select().from(follows).where(and(eq(follows.chatId, chatId), eq(follows.channelId, channelId))).limit(1); + return result[0] ? DomainMapper.toDomainFollow(result[0]) : void 0; + } + async findByChatId(chatId) { + const results = await this.db.select().from(follows).where(eq(follows.chatId, chatId)); + return results.map((r) => DomainMapper.toDomainFollow(r)); + } + async create(chatId, channelId) { + const existing = await this.findByChatAndChannel(chatId, channelId); + if (existing) { + throw new FollowAlreadyExistsError(); + } + const id = randomUUID4(); + await this.db.insert(follows).values({ id, chatId, channelId }); + return id; + } + async delete(id) { + const result = await this.db.delete(follows).where(eq(follows.id, id)).returning(); + if (result.length === 0) { + throw new FollowNotFoundError(); + } + } + async findByChannelId(channelId) { + const results = await this.db.select().from(follows).where(eq(follows.channelId, channelId)); + return results.map((r) => DomainMapper.toDomainFollow(r)); + } + async findByChatIdPaginated(chatId, limit, offset) { + const results = await this.db.select().from(follows).where(eq(follows.chatId, chatId)).limit(limit).offset(offset); + return results.map((r) => DomainMapper.toDomainFollow(r)); + } + async countByChatId(chatId) { + const result = await this.db.select({ count: count() }).from(follows).where(eq(follows.chatId, chatId)); + return result[0]?.count ?? 0; + } +}; + +// src/db/repositories/drizzle/stream.drizzle.repository.ts +init_modules_watch_stub(); +init_performance2(); +var StreamDrizzleRepository = class { + constructor(db) { + this.db = db; + } + static { + __name(this, "StreamDrizzleRepository"); + } + async findLatestByChannelId(channelId) { + const result = await this.db.select().from(streams).where(eq(streams.channelId, channelId)).orderBy(desc(streams.startedAt)).limit(1); + return result[0] ? DomainMapper.toDomainStream(result[0]) : void 0; + } + async create(id, channelId, category, title2) { + await this.db.insert(streams).values({ + id, + channelId, + isLive: true, + category, + title: title2, + startedAt: (/* @__PURE__ */ new Date()).toISOString(), + titles: [title2], + categories: [category] + }); + return id; + } + async update(id, data2) { + const result = await this.db.update(streams).set(data2).where(eq(streams.id, id)).returning(); + if (!result[0]) { + throw new Error("Stream not found"); + } + return DomainMapper.toDomainStream(result[0]); + } + async findById(id) { + const result = await this.db.select().from(streams).where(eq(streams.id, id)).limit(1); + return result[0] ? DomainMapper.toDomainStream(result[0]) : void 0; + } +}; + +// src/db/repository.factory.ts +var DrizzleRepositoryFactory = class { + constructor(connection) { + this.connection = connection; + } + static { + __name(this, "DrizzleRepositoryFactory"); + } + createChatRepository() { + return new ChatDrizzleRepository(this.connection.getClient()); + } + createChannelRepository() { + return new ChannelDrizzleRepository(this.connection.getClient()); + } + createFollowRepository() { + return new FollowDrizzleRepository(this.connection.getClient()); + } + createStreamRepository() { + return new StreamDrizzleRepository(this.connection.getClient()); + } +}; + +// src/db/repositories/cloudflare-kv/index.ts +init_modules_watch_stub(); +init_performance2(); + +// src/db/repositories/cloudflare-kv/session.kv.repository.ts +init_modules_watch_stub(); +init_performance2(); +var CloudflareKVSessionRepository = class { + constructor(kv) { + this.kv = kv; + } + static { + __name(this, "CloudflareKVSessionRepository"); + } + async get(key) { + const value = await this.kv.get(key); + return value ?? void 0; + } + async set(key, value, expiresAt) { + const options = {}; + if (expiresAt) { + const ttl = Math.floor((expiresAt - Date.now()) / 1e3); + if (ttl > 0) { + options.expirationTtl = ttl; + } + } + await this.kv.put(key, value, options); + } + async delete(key) { + await this.kv.delete(key); + } + async cleanup() { + return; + } +}; + +// src/webhooks/twitch.ts +init_modules_watch_stub(); +init_performance2(); + +// src/services/notification.service.ts +init_modules_watch_stub(); +init_performance2(); +var NotificationService = class { + constructor(env, db, telegramService, twitchService, i18nService, chatRepo, channelRepo, followRepo, streamRepo) { + this.env = env; + this.db = db; + this.telegramService = telegramService; + this.twitchService = twitchService; + this.i18nService = i18nService; + this.chatRepo = chatRepo; + this.channelRepo = channelRepo; + this.followRepo = followRepo; + this.streamRepo = streamRepo; + } + static { + __name(this, "NotificationService"); + } + async handleStreamOnline(data2) { + let channel = await this.channelRepo.findByChannelId(data2.channelId, "twitch"); + if (!channel) { + channel = await this.channelRepo.create(data2.channelId, "twitch"); + } + await this.streamRepo.create( + data2.streamId, + channel.id, + data2.category, + data2.title + ); + const follows2 = await this.followRepo.findByChannelId(channel.id); + for (const follow of follows2) { + try { + const chat = await this.chatRepo.findById(follow.chatId); + if (!chat || !chat.settings) continue; + await this.telegramService.sendStreamOnlineNotification({ + chatId: parseInt(chat.chatId), + language: chat.settings.language, + channelName: data2.channelName, + channelUrl: `https://twitch.tv/${data2.channelName}`, + category: data2.category, + title: data2.title, + thumbnailUrl: data2.thumbnailUrl, + showImage: chat.settings.imageInNotification + }); + } catch (error) { + console.error("Failed to send online notification:", error); + } + } + } + async handleStreamOffline(data2) { + const channel = await this.channelRepo.findByChannelId(data2.channelId, "twitch"); + if (!channel) return; + const stream = await this.streamRepo.findLatestByChannelId(channel.id); + if (!stream || !stream.isLive) return; + await this.streamRepo.update(stream.id, { + isLive: false, + endedAt: (/* @__PURE__ */ new Date()).toISOString() + }); + const follows2 = await this.followRepo.findByChannelId(channel.id); + for (const follow of follows2) { + try { + const chat = await this.chatRepo.findById(follow.chatId); + if (!chat || !chat.settings || !chat.settings.offlineNotification) continue; + const duration = stream.startedAt ? Math.floor((Date.now() - new Date(stream.startedAt).getTime()) / 1e3) : 0; + const hours = Math.floor(duration / 3600); + const minutes = Math.floor(duration % 3600 / 60); + const seconds = duration % 60; + const durationStr = `${hours}h ${minutes}m ${seconds}s`; + await this.telegramService.sendStreamOfflineNotification({ + chatId: parseInt(chat.chatId), + language: chat.settings.language, + channelName: data2.channelName, + channelUrl: `https://twitch.tv/${data2.channelName}`, + categories: stream.categories || [], + duration: durationStr + }); + } catch (error) { + console.error("Failed to send offline notification:", error); + } + } + } + async handleCategoryChange(data2) { + const channel = await this.channelRepo.findByChannelId(data2.channelId, "twitch"); + if (!channel) return; + const stream = await this.streamRepo.findLatestByChannelId(channel.id); + if (!stream || !stream.isLive) return; + const categories = [...stream.categories || [], data2.newCategory]; + await this.streamRepo.update(stream.id, { + category: data2.newCategory, + categories + }); + const follows2 = await this.followRepo.findByChannelId(channel.id); + for (const follow of follows2) { + try { + const chat = await this.chatRepo.findById(follow.chatId); + if (!chat || !chat.settings || !chat.settings.gameChangeNotification) continue; + await this.telegramService.sendCategoryChangeNotification({ + chatId: parseInt(chat.chatId), + language: chat.settings.language, + channelName: data2.channelName, + channelUrl: `https://twitch.tv/${data2.channelName}`, + oldCategory: data2.oldCategory, + category: data2.newCategory + }); + } catch (error) { + console.error("Failed to send category change notification:", error); + } + } + } + async handleTitleChange(data2) { + const channel = await this.channelRepo.findByChannelId(data2.channelId, "twitch"); + if (!channel) return; + const stream = await this.streamRepo.findLatestByChannelId(channel.id); + if (!stream || !stream.isLive) return; + const titles = [...stream.titles || [], data2.newTitle]; + await this.streamRepo.update(stream.id, { + title: data2.newTitle, + titles + }); + const follows2 = await this.followRepo.findByChannelId(channel.id); + for (const follow of follows2) { + try { + const chat = await this.chatRepo.findById(follow.chatId); + if (!chat || !chat.settings || !chat.settings.titleChangeNotification) continue; + await this.telegramService.sendTitleChangeNotification({ + chatId: parseInt(chat.chatId), + language: chat.settings.language, + channelName: data2.channelName, + channelUrl: `https://twitch.tv/${data2.channelName}`, + oldTitle: data2.oldTitle, + title: data2.newTitle + }); + } catch (error) { + console.error("Failed to send title change notification:", error); + } + } + } +}; + +// src/webhooks/twitch.ts +import { createHmac } from "node:crypto"; +async function handleTwitchWebhook(request, env, db) { + try { + const messageId = request.headers.get("Twitch-Eventsub-Message-Id"); + const timestamp = request.headers.get("Twitch-Eventsub-Message-Timestamp"); + const signature = request.headers.get("Twitch-Eventsub-Message-Signature"); + const messageType = request.headers.get("Twitch-Eventsub-Message-Type"); + if (!messageId || !timestamp || !signature) { + return new Response("Missing required headers", { status: 400 }); + } + const body = await request.text(); + const hmac = createHmac("sha256", env.TWITCH_EVENTSUB_SECRET); + hmac.update(messageId + timestamp + body); + const expectedSignature = "sha256=" + hmac.digest("hex"); + if (signature !== expectedSignature) { + return new Response("Invalid signature", { status: 403 }); + } + const payload = JSON.parse(body); + if (messageType === "webhook_callback_verification") { + const verification = payload; + return new Response(verification.challenge, { + status: 200, + headers: { "Content-Type": "text/plain" } + }); + } + if (messageType === "notification") { + const notification = payload; + const i18nService = new I18nService(); + const twitchService = new TwitchService(env); + const telegramService = new TelegramService(env, i18nService); + const dbConnection = new CloudflareD1Connection(db); + const repositoryFactory = new DrizzleRepositoryFactory(dbConnection); + const chatRepo = repositoryFactory.createChatRepository(); + const channelRepo = repositoryFactory.createChannelRepository(); + const followRepo = repositoryFactory.createFollowRepository(); + const streamRepo = repositoryFactory.createStreamRepository(); + const notificationService = new NotificationService( + env, + db, + telegramService, + twitchService, + i18nService, + chatRepo, + channelRepo, + followRepo, + streamRepo + ); + switch (notification.subscription.type) { + case "stream.online": { + const event = notification.event; + const stream = await twitchService.getStreamByUserId(event.broadcaster_user_id); + if (stream) { + await notificationService.handleStreamOnline({ + channelId: event.broadcaster_user_id, + channelName: event.broadcaster_user_name, + streamId: stream.id, + category: stream.gameName, + title: stream.title, + thumbnailUrl: stream.thumbnailUrl + }); + } + break; + } + case "stream.offline": { + const event = notification.event; + await notificationService.handleStreamOffline({ + channelId: event.broadcaster_user_id, + channelName: event.broadcaster_user_name + }); + break; + } + case "channel.update": { + const event = notification.event; + const channel = await channelRepo.findByChannelId(event.broadcaster_user_id, "twitch"); + if (!channel) break; + const stream = await streamRepo.findLatestByChannelId(channel.id); + if (!stream || !stream.isLive) break; + if (stream.category && event.category_name !== stream.category) { + await notificationService.handleCategoryChange({ + channelId: event.broadcaster_user_id, + channelName: event.broadcaster_user_name, + oldCategory: stream.category, + newCategory: event.category_name + }); + } + if (stream.title && event.title !== stream.title) { + await notificationService.handleTitleChange({ + channelId: event.broadcaster_user_id, + channelName: event.broadcaster_user_name, + oldTitle: stream.title, + newTitle: event.title + }); + } + break; + } + } + return new Response("OK", { status: 200 }); + } + if (messageType === "revocation") { + console.log("Subscription revoked:", payload); + return new Response("OK", { status: 200 }); + } + return new Response("Unknown message type", { status: 400 }); + } catch (error) { + console.error("Error handling Twitch webhook:", error); + return new Response("Internal Server Error", { status: 500 }); + } +} +__name(handleTwitchWebhook, "handleTwitchWebhook"); + +// src/index.ts +var app = new Hono2(); +app.get("/", (c) => { + return c.json({ status: "ok", service: "twitch-notifier" }); +}); +app.post("/telegram-webhook", async (c) => { + const env = c.env; + const dbClient = drizzle(env.DB); + const dbConnection = new CloudflareD1Connection(dbClient); + const repositoryFactory = new DrizzleRepositoryFactory(dbConnection); + const chatRepo = repositoryFactory.createChatRepository(); + const channelRepo = repositoryFactory.createChannelRepository(); + const followRepo = repositoryFactory.createFollowRepository(); + const streamRepo = repositoryFactory.createStreamRepository(); + const sessionRepo = new CloudflareKVSessionRepository(env.SESSIONS_KV); + const i18nService = new I18nService(); + await i18nService.init(); + const twitchService = new TwitchService(env); + const telegramService = new TelegramService(env, i18nService); + const eventSubService = new EventSubService( + twitchService.getApiClient(), + env, + env.BASE_URL + ); + const bot = createBot(env, { + i18n: i18nService, + twitch: twitchService, + eventsub: eventSubService, + chatRepo, + channelRepo, + followRepo, + sessionRepo + }); + const handler = webhookCallback(bot, "hono"); + return handler(c); +}); +app.post("/twitch-webhook", async (c) => { + const env = c.env; + const db = drizzle(env.DB); + return await handleTwitchWebhook(c.req.raw, env, db); +}); +var src_default = app; + +// node_modules/.pnpm/wrangler@4.71.0_@cloudflare+workers-types@4.20260307.1/node_modules/wrangler/templates/middleware/middleware-ensure-req-body-drained.ts +init_modules_watch_stub(); +init_performance2(); +var drainBody = /* @__PURE__ */ __name(async (request, env, _ctx, middlewareCtx) => { + try { + return await middlewareCtx.next(request, env); + } finally { + try { + if (request.body !== null && !request.bodyUsed) { + const reader = request.body.getReader(); + while (!(await reader.read()).done) { + } + } + } catch (e) { + console.error("Failed to drain the unused request body.", e); + } + } +}, "drainBody"); +var middleware_ensure_req_body_drained_default = drainBody; + +// node_modules/.pnpm/wrangler@4.71.0_@cloudflare+workers-types@4.20260307.1/node_modules/wrangler/templates/middleware/middleware-miniflare3-json-error.ts +init_modules_watch_stub(); +init_performance2(); +function reduceError(e) { + return { + name: e?.name, + message: e?.message ?? String(e), + stack: e?.stack, + cause: e?.cause === void 0 ? void 0 : reduceError(e.cause) + }; +} +__name(reduceError, "reduceError"); +var jsonError = /* @__PURE__ */ __name(async (request, env, _ctx, middlewareCtx) => { + try { + return await middlewareCtx.next(request, env); + } catch (e) { + const error = reduceError(e); + return Response.json(error, { + status: 500, + headers: { "MF-Experimental-Error-Stack": "true" } + }); + } +}, "jsonError"); +var middleware_miniflare3_json_error_default = jsonError; + +// .wrangler/tmp/bundle-ldhBcJ/middleware-insertion-facade.js +var __INTERNAL_WRANGLER_MIDDLEWARE__ = [ + middleware_ensure_req_body_drained_default, + middleware_miniflare3_json_error_default +]; +var middleware_insertion_facade_default = src_default; + +// node_modules/.pnpm/wrangler@4.71.0_@cloudflare+workers-types@4.20260307.1/node_modules/wrangler/templates/middleware/common.ts +init_modules_watch_stub(); +init_performance2(); +var __facade_middleware__ = []; +function __facade_register__(...args) { + __facade_middleware__.push(...args.flat()); +} +__name(__facade_register__, "__facade_register__"); +function __facade_invokeChain__(request, env, ctx, dispatch, middlewareChain) { + const [head, ...tail] = middlewareChain; + const middlewareCtx = { + dispatch, + next(newRequest, newEnv) { + return __facade_invokeChain__(newRequest, newEnv, ctx, dispatch, tail); + } + }; + return head(request, env, ctx, middlewareCtx); +} +__name(__facade_invokeChain__, "__facade_invokeChain__"); +function __facade_invoke__(request, env, ctx, dispatch, finalMiddleware) { + return __facade_invokeChain__(request, env, ctx, dispatch, [ + ...__facade_middleware__, + finalMiddleware + ]); +} +__name(__facade_invoke__, "__facade_invoke__"); + +// .wrangler/tmp/bundle-ldhBcJ/middleware-loader.entry.ts +var __Facade_ScheduledController__ = class ___Facade_ScheduledController__ { + constructor(scheduledTime, cron, noRetry) { + this.scheduledTime = scheduledTime; + this.cron = cron; + this.#noRetry = noRetry; + } + static { + __name(this, "__Facade_ScheduledController__"); + } + #noRetry; + noRetry() { + if (!(this instanceof ___Facade_ScheduledController__)) { + throw new TypeError("Illegal invocation"); + } + this.#noRetry(); + } +}; +function wrapExportedHandler(worker) { + if (__INTERNAL_WRANGLER_MIDDLEWARE__ === void 0 || __INTERNAL_WRANGLER_MIDDLEWARE__.length === 0) { + return worker; + } + for (const middleware of __INTERNAL_WRANGLER_MIDDLEWARE__) { + __facade_register__(middleware); + } + const fetchDispatcher = /* @__PURE__ */ __name(function(request, env, ctx) { + if (worker.fetch === void 0) { + throw new Error("Handler does not export a fetch() function."); + } + return worker.fetch(request, env, ctx); + }, "fetchDispatcher"); + return { + ...worker, + fetch(request, env, ctx) { + const dispatcher = /* @__PURE__ */ __name(function(type, init2) { + if (type === "scheduled" && worker.scheduled !== void 0) { + const controller = new __Facade_ScheduledController__( + Date.now(), + init2.cron ?? "", + () => { + } + ); + return worker.scheduled(controller, env, ctx); + } + }, "dispatcher"); + return __facade_invoke__(request, env, ctx, dispatcher, fetchDispatcher); + } + }; +} +__name(wrapExportedHandler, "wrapExportedHandler"); +function wrapWorkerEntrypoint(klass) { + if (__INTERNAL_WRANGLER_MIDDLEWARE__ === void 0 || __INTERNAL_WRANGLER_MIDDLEWARE__.length === 0) { + return klass; + } + for (const middleware of __INTERNAL_WRANGLER_MIDDLEWARE__) { + __facade_register__(middleware); + } + return class extends klass { + #fetchDispatcher = /* @__PURE__ */ __name((request, env, ctx) => { + this.env = env; + this.ctx = ctx; + if (super.fetch === void 0) { + throw new Error("Entrypoint class does not define a fetch() function."); + } + return super.fetch(request); + }, "#fetchDispatcher"); + #dispatcher = /* @__PURE__ */ __name((type, init2) => { + if (type === "scheduled" && super.scheduled !== void 0) { + const controller = new __Facade_ScheduledController__( + Date.now(), + init2.cron ?? "", + () => { + } + ); + return super.scheduled(controller); + } + }, "#dispatcher"); + fetch(request) { + return __facade_invoke__( + request, + this.env, + this.ctx, + this.#dispatcher, + this.#fetchDispatcher + ); + } + }; +} +__name(wrapWorkerEntrypoint, "wrapWorkerEntrypoint"); +var WRAPPED_ENTRY; +if (typeof middleware_insertion_facade_default === "object") { + WRAPPED_ENTRY = wrapExportedHandler(middleware_insertion_facade_default); +} else if (typeof middleware_insertion_facade_default === "function") { + WRAPPED_ENTRY = wrapWorkerEntrypoint(middleware_insertion_facade_default); +} +var middleware_loader_entry_default = WRAPPED_ENTRY; +export { + __INTERNAL_WRANGLER_MIDDLEWARE__, + middleware_loader_entry_default as default +}; +//# sourceMappingURL=index.js.map diff --git a/.wrangler/tmp/dev-FVjRI2/index.js.map b/.wrangler/tmp/dev-FVjRI2/index.js.map new file mode 100644 index 00000000..cdc1a00e --- /dev/null +++ b/.wrangler/tmp/dev-FVjRI2/index.js.map @@ -0,0 +1,8 @@ +{ + "version": 3, + "sources": ["../../../node_modules/.pnpm/unenv@2.0.0-rc.24/node_modules/unenv/dist/runtime/_internal/utils.mjs", "../../../node_modules/.pnpm/unenv@2.0.0-rc.24/node_modules/unenv/dist/runtime/node/internal/perf_hooks/performance.mjs", "../../../node_modules/.pnpm/unenv@2.0.0-rc.24/node_modules/unenv/dist/runtime/node/perf_hooks.mjs", "../../../node_modules/.pnpm/@cloudflare+unenv-preset@2.15.0_unenv@2.0.0-rc.24_workerd@1.20260301.1/node_modules/@cloudflare/unenv-preset/dist/runtime/polyfill/performance.mjs", "wrangler-modules-watch:wrangler:modules-watch", "../../../node_modules/.pnpm/wrangler@4.71.0_@cloudflare+workers-types@4.20260307.1/node_modules/wrangler/templates/modules-watch-stub.js", "../../../node_modules/.pnpm/@d-fischer+detect-node@3.0.1/node_modules/@d-fischer/detect-node/browser.js", "../../../node_modules/.pnpm/retry@0.13.1/node_modules/retry/lib/retry_operation.js", "../../../node_modules/.pnpm/retry@0.13.1/node_modules/retry/lib/retry.js", "../../../node_modules/.pnpm/retry@0.13.1/node_modules/retry/index.js", "../bundle-ldhBcJ/middleware-loader.entry.ts", "../bundle-ldhBcJ/middleware-insertion-facade.js", "../../../src/index.ts", "../../../node_modules/.pnpm/hono@4.12.5/node_modules/hono/dist/index.js", "../../../node_modules/.pnpm/hono@4.12.5/node_modules/hono/dist/hono.js", "../../../node_modules/.pnpm/hono@4.12.5/node_modules/hono/dist/hono-base.js", "../../../node_modules/.pnpm/hono@4.12.5/node_modules/hono/dist/compose.js", "../../../node_modules/.pnpm/hono@4.12.5/node_modules/hono/dist/context.js", "../../../node_modules/.pnpm/hono@4.12.5/node_modules/hono/dist/request.js", "../../../node_modules/.pnpm/hono@4.12.5/node_modules/hono/dist/http-exception.js", "../../../node_modules/.pnpm/hono@4.12.5/node_modules/hono/dist/request/constants.js", "../../../node_modules/.pnpm/hono@4.12.5/node_modules/hono/dist/utils/body.js", "../../../node_modules/.pnpm/hono@4.12.5/node_modules/hono/dist/utils/url.js", "../../../node_modules/.pnpm/hono@4.12.5/node_modules/hono/dist/utils/html.js", "../../../node_modules/.pnpm/hono@4.12.5/node_modules/hono/dist/router.js", "../../../node_modules/.pnpm/hono@4.12.5/node_modules/hono/dist/utils/constants.js", "../../../node_modules/.pnpm/hono@4.12.5/node_modules/hono/dist/router/reg-exp-router/index.js", "../../../node_modules/.pnpm/hono@4.12.5/node_modules/hono/dist/router/reg-exp-router/router.js", "../../../node_modules/.pnpm/hono@4.12.5/node_modules/hono/dist/router/reg-exp-router/matcher.js", "../../../node_modules/.pnpm/hono@4.12.5/node_modules/hono/dist/router/reg-exp-router/node.js", "../../../node_modules/.pnpm/hono@4.12.5/node_modules/hono/dist/router/reg-exp-router/trie.js", "../../../node_modules/.pnpm/hono@4.12.5/node_modules/hono/dist/router/reg-exp-router/prepared-router.js", "../../../node_modules/.pnpm/hono@4.12.5/node_modules/hono/dist/router/smart-router/index.js", "../../../node_modules/.pnpm/hono@4.12.5/node_modules/hono/dist/router/smart-router/router.js", "../../../node_modules/.pnpm/hono@4.12.5/node_modules/hono/dist/router/trie-router/index.js", "../../../node_modules/.pnpm/hono@4.12.5/node_modules/hono/dist/router/trie-router/router.js", "../../../node_modules/.pnpm/hono@4.12.5/node_modules/hono/dist/router/trie-router/node.js", "../../../node_modules/.pnpm/grammy@1.41.1/node_modules/grammy/out/web.mjs", "../../../node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/src/d1/driver.ts", "../../../node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/src/entity.ts", "../../../node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/src/logger.ts", "../../../node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/src/relations.ts", "../../../node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/src/table.ts", "../../../node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/src/table.utils.ts", "../../../node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/src/column.ts", "../../../node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/src/pg-core/primary-keys.ts", "../../../node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/src/pg-core/table.ts", "../../../node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/src/utils.ts", "../../../node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/src/sql/sql.ts", "../../../node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/src/pg-core/columns/enum.ts", "../../../node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/src/pg-core/columns/common.ts", "../../../node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/src/column-builder.ts", "../../../node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/src/pg-core/foreign-keys.ts", "../../../node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/src/tracing-utils.ts", "../../../node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/src/pg-core/unique-constraint.ts", "../../../node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/src/pg-core/utils/array.ts", "../../../node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/src/subquery.ts", "../../../node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/src/tracing.ts", "../../../node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/version.js", "../../../node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/src/view-common.ts", "../../../node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/src/sql/expressions/conditions.ts", "../../../node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/src/sql/expressions/select.ts", "../../../node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/src/sqlite-core/db.ts", "../../../node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/src/selection-proxy.ts", "../../../node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/src/alias.ts", "../../../node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/src/sqlite-core/query-builders/delete.ts", "../../../node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/src/query-promise.ts", "../../../node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/src/sqlite-core/table.ts", "../../../node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/src/sqlite-core/columns/all.ts", "../../../node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/src/sqlite-core/columns/blob.ts", "../../../node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/src/sqlite-core/columns/common.ts", "../../../node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/src/sqlite-core/foreign-keys.ts", "../../../node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/src/sqlite-core/unique-constraint.ts", "../../../node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/src/sqlite-core/columns/custom.ts", "../../../node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/src/sqlite-core/columns/integer.ts", "../../../node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/src/sqlite-core/columns/numeric.ts", "../../../node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/src/sqlite-core/columns/real.ts", "../../../node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/src/sqlite-core/columns/text.ts", "../../../node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/src/sqlite-core/utils.ts", "../../../node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/src/sqlite-core/query-builders/insert.ts", "../../../node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/src/sqlite-core/query-builders/query-builder.ts", "../../../node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/src/sqlite-core/dialect.ts", "../../../node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/src/casing.ts", "../../../node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/src/errors.ts", "../../../node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/src/sql/functions/aggregate.ts", "../../../node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/src/sqlite-core/view-base.ts", "../../../node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/src/sqlite-core/query-builders/select.ts", "../../../node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/src/query-builders/query-builder.ts", "../../../node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/src/sqlite-core/query-builders/update.ts", "../../../node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/src/sqlite-core/query-builders/count.ts", "../../../node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/src/sqlite-core/query-builders/query.ts", "../../../node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/src/sqlite-core/query-builders/raw.ts", "../../../node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/src/d1/session.ts", "../../../node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/src/cache/core/cache.ts", "../../../node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/src/sqlite-core/session.ts", "../../../src/bot/index.ts", "../../../src/bot/storage.ts", "../../../src/bot/commands/index.ts", "../../../src/bot/commands/start.command.ts", "../../../src/bot/helpers.ts", "../../../src/bot/commands/follow.command.ts", "../../../src/bot/commands/follows.command.ts", "../../../src/bot/commands/live.command.ts", "../../../src/bot/commands/broadcast.command.ts", "../../../src/bot/commands/change-channel-id.command.ts", "../../../src/bot/commands/callback.handler.ts", "../../../src/services/i18n.service.ts", "../../../node_modules/.pnpm/i18next@25.8.14_typescript@5.9.3/node_modules/i18next/dist/esm/i18next.js", "../../../locales/en.json", "../../../locales/ru.json", "../../../locales/uk.json", "../../../src/services/twitch.service.ts", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/index.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/client/ApiClient.js", "../../../node_modules/.pnpm/tslib@2.8.1/node_modules/tslib/tslib.es6.mjs", "../../../node_modules/.pnpm/@d-fischer+logger@4.2.4/node_modules/@d-fischer/logger/es/index.mjs", "../../../node_modules/.pnpm/@d-fischer+logger@4.2.4/node_modules/@d-fischer/logger/es/createLogger.mjs", "../../../node_modules/.pnpm/@d-fischer+logger@4.2.4/node_modules/@d-fischer/logger/es/BrowserLogger.mjs", "../../../node_modules/.pnpm/@d-fischer+logger@4.2.4/node_modules/@d-fischer/logger/es/LogLevel.mjs", "../../../node_modules/.pnpm/@d-fischer+logger@4.2.4/node_modules/@d-fischer/logger/es/BaseLogger.mjs", "../../../node_modules/.pnpm/@d-fischer+shared-utils@3.6.4/node_modules/@d-fischer/shared-utils/es/index.mjs", "../../../node_modules/.pnpm/@d-fischer+shared-utils@3.6.4/node_modules/@d-fischer/shared-utils/es/decorators/Enumerable.mjs", "../../../node_modules/.pnpm/@d-fischer+shared-utils@3.6.4/node_modules/@d-fischer/shared-utils/es/functions/array/flatten.mjs", "../../../node_modules/.pnpm/@d-fischer+shared-utils@3.6.4/node_modules/@d-fischer/shared-utils/es/functions/object/arrayToObject.mjs", "../../../node_modules/.pnpm/@d-fischer+shared-utils@3.6.4/node_modules/@d-fischer/shared-utils/es/functions/object/indexBy.mjs", "../../../node_modules/.pnpm/@d-fischer+shared-utils@3.6.4/node_modules/@d-fischer/shared-utils/es/functions/optional/mapOptional.mjs", "../../../node_modules/.pnpm/@d-fischer+shared-utils@3.6.4/node_modules/@d-fischer/shared-utils/es/functions/promise/withResolvers.mjs", "../../../node_modules/.pnpm/@d-fischer+logger@4.2.4/node_modules/@d-fischer/logger/es/getMinLogLevelFromEnv.mjs", "../../../node_modules/.pnpm/@d-fischer+logger@4.2.4/node_modules/@d-fischer/logger/es/CustomLoggerWrapper.mjs", "../../../node_modules/.pnpm/@d-fischer+logger@4.2.4/node_modules/@d-fischer/logger/es/NodeLogger.mjs", "../../../node_modules/.pnpm/@d-fischer+rate-limiter@1.1.0/node_modules/@d-fischer/rate-limiter/es/index.mjs", "../../../node_modules/.pnpm/@d-fischer+rate-limiter@1.1.0/node_modules/@d-fischer/rate-limiter/es/errors/RateLimiterDestroyedError.mjs", "../../../node_modules/.pnpm/@d-fischer+rate-limiter@1.1.0/node_modules/@d-fischer/rate-limiter/es/errors/CustomError.mjs", "../../../node_modules/.pnpm/@d-fischer+rate-limiter@1.1.0/node_modules/@d-fischer/rate-limiter/es/errors/RateLimitReachedError.mjs", "../../../node_modules/.pnpm/@d-fischer+rate-limiter@1.1.0/node_modules/@d-fischer/rate-limiter/es/errors/RetryAfterError.mjs", "../../../node_modules/.pnpm/@d-fischer+rate-limiter@1.1.0/node_modules/@d-fischer/rate-limiter/es/limiters/PartitionedRateLimiter.mjs", "../../../node_modules/.pnpm/@d-fischer+rate-limiter@1.1.0/node_modules/@d-fischer/rate-limiter/es/limiters/ResponseBasedRateLimiter.mjs", "../../../node_modules/.pnpm/@d-fischer+rate-limiter@1.1.0/node_modules/@d-fischer/rate-limiter/es/limiters/PartitionedTimeBasedRateLimiter.mjs", "../../../node_modules/.pnpm/@twurple+api-call@8.0.3/node_modules/@twurple/api-call/lib/index.js", "../../../node_modules/.pnpm/@twurple+api-call@8.0.3/node_modules/@twurple/api-call/lib/apiCall.js", "../../../node_modules/.pnpm/@twurple+common@8.0.3/node_modules/@twurple/common/lib/index.js", "../../../node_modules/.pnpm/@twurple+common@8.0.3/node_modules/@twurple/common/lib/DataObject.js", "../../../node_modules/.pnpm/klona@2.0.6/node_modules/klona/dist/index.mjs", "../../../node_modules/.pnpm/@twurple+common@8.0.3/node_modules/@twurple/common/lib/mockApiPort.js", "../../../node_modules/.pnpm/@twurple+common@8.0.3/node_modules/@twurple/common/lib/qs.js", "../../../node_modules/.pnpm/@twurple+common@8.0.3/node_modules/@twurple/common/lib/relations.js", "../../../node_modules/.pnpm/@twurple+common@8.0.3/node_modules/@twurple/common/lib/errors/RelationAssertionError.js", "../../../node_modules/.pnpm/@twurple+common@8.0.3/node_modules/@twurple/common/lib/errors/CustomError.js", "../../../node_modules/.pnpm/@twurple+common@8.0.3/node_modules/@twurple/common/lib/rtfm.js", "../../../node_modules/.pnpm/@twurple+common@8.0.3/node_modules/@twurple/common/lib/extensions/HelixExtension.js", "../../../node_modules/.pnpm/@twurple+common@8.0.3/node_modules/@twurple/common/lib/errors/HellFreezesOverError.js", "../../../node_modules/.pnpm/@twurple+common@8.0.3/node_modules/@twurple/common/lib/userResolvers.js", "../../../node_modules/.pnpm/@twurple+api-call@8.0.3/node_modules/@twurple/api-call/lib/helpers/transform.js", "../../../node_modules/.pnpm/@twurple+api-call@8.0.3/node_modules/@twurple/api-call/lib/errors/HttpStatusCodeError.js", "../../../node_modules/.pnpm/@twurple+api-call@8.0.3/node_modules/@twurple/api-call/lib/helpers/url.js", "../../../node_modules/.pnpm/@twurple+api-call@8.0.3/node_modules/@twurple/api-call/lib/helpers/queries.external.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/errors/ConfigError.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/utils/HelixRateLimiter.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/client/BaseApiClient.js", "../../../node_modules/.pnpm/@d-fischer+cache-decorators@4.0.1/node_modules/@d-fischer/cache-decorators/es/index.mjs", "../../../node_modules/.pnpm/@d-fischer+cache-decorators@4.0.1/node_modules/@d-fischer/cache-decorators/es/decorators/Cacheable.mjs", "../../../node_modules/.pnpm/@d-fischer+cache-decorators@4.0.1/node_modules/@d-fischer/cache-decorators/es/utils/createCacheKey.mjs", "../../../node_modules/.pnpm/@d-fischer+cache-decorators@4.0.1/node_modules/@d-fischer/cache-decorators/es/decorators/CachedGetter.mjs", "../../../node_modules/.pnpm/@d-fischer+typed-event-emitter@3.3.3/node_modules/@d-fischer/typed-event-emitter/es/index.mjs", "../../../node_modules/.pnpm/@d-fischer+typed-event-emitter@3.3.3/node_modules/@d-fischer/typed-event-emitter/es/EventEmitter.mjs", "../../../node_modules/.pnpm/@d-fischer+typed-event-emitter@3.3.3/node_modules/@d-fischer/typed-event-emitter/es/Listener.mjs", "../../../node_modules/.pnpm/@twurple+auth@8.0.3/node_modules/@twurple/auth/lib/index.js", "../../../node_modules/.pnpm/@twurple+auth@8.0.3/node_modules/@twurple/auth/lib/AccessToken.js", "../../../node_modules/.pnpm/@twurple+auth@8.0.3/node_modules/@twurple/auth/lib/helpers.js", "../../../node_modules/.pnpm/@twurple+auth@8.0.3/node_modules/@twurple/auth/lib/errors/InvalidTokenError.js", "../../../node_modules/.pnpm/@twurple+auth@8.0.3/node_modules/@twurple/auth/lib/helpers.external.js", "../../../node_modules/.pnpm/@twurple+auth@8.0.3/node_modules/@twurple/auth/lib/TokenInfo.js", "../../../node_modules/.pnpm/@twurple+auth@8.0.3/node_modules/@twurple/auth/lib/TokenFetcher.js", "../../../node_modules/.pnpm/@twurple+auth@8.0.3/node_modules/@twurple/auth/lib/providers/AppTokenAuthProvider.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/bits/HelixBitsApi.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/interfaces/endpoints/bits.external.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/BaseApi.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/bits/HelixBitsLeaderboard.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/bits/HelixBitsLeaderboardEntry.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/bits/HelixCheermoteList.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/channel/HelixChannelApi.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/interfaces/endpoints/channel.external.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/interfaces/endpoints/generic.external.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/relations/HelixUserRelation.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/utils/HelixRequestBatcher.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/utils/pagination/HelixPaginatedRequest.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/utils/pagination/HelixPaginatedRequestWithTotal.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/utils/pagination/HelixPaginatedResult.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/utils/pagination/HelixPagination.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/channel/HelixChannel.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/channel/HelixChannelEditor.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/channel/HelixChannelFollower.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/channel/HelixFollowedChannel.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/channel/HelixAdSchedule.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/channel/HelixSnoozeNextAdResult.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/channelPoints/HelixChannelPointsApi.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/interfaces/endpoints/channelPoints.external.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/channelPoints/HelixCustomReward.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/channelPoints/HelixCustomRewardRedemption.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/charity/HelixCharityApi.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/charity/HelixCharityCampaign.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/charity/HelixCharityCampaignAmount.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/charity/HelixCharityCampaignDonation.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/chat/HelixChatApi.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/errors/ChatMessageDroppedError.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/interfaces/endpoints/chat.external.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/interfaces/endpoints/shared-chat-session.external.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/chat/HelixChannelEmote.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/chat/HelixEmote.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/chat/HelixEmoteBase.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/chat/HelixChatBadgeSet.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/chat/HelixChatBadgeVersion.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/chat/HelixChatChatter.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/chat/HelixChatSettings.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/chat/HelixEmoteFromSet.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/chat/HelixPrivilegedChatSettings.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/chat/HelixSentChatMessage.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/chat/HelixSharedChatSession.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/chat/HelixSharedChatSessionParticipant.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/chat/HelixUserEmote.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/clip/HelixClipApi.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/interfaces/endpoints/clip.external.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/clip/HelixClip.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/contentClassificationLabels/HelixContentClassificationLabelApi.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/contentClassificationLabels/HelixContentClassificationLabel.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/entitlements/HelixEntitlementApi.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/interfaces/endpoints/entitlement.external.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/entitlements/HelixDropsEntitlement.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/eventSub/HelixEventSubApi.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/interfaces/endpoints/eventSub.external.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/eventSub/HelixEventSubSubscription.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/eventSub/HelixPaginatedEventSubSubscriptionsRequest.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/eventSub/HelixEventSubConduit.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/eventSub/HelixEventSubConduitShard.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/extensions/HelixExtensionsApi.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/interfaces/endpoints/extensions.external.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/channel/HelixChannelReference.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/extensions/HelixExtensionBitsProduct.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/extensions/HelixExtensionTransaction.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/game/HelixGameApi.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/game/HelixGame.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/goals/HelixGoalApi.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/goals/HelixGoal.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/hypeTrain/HelixHypeTrainApi.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/hypeTrain/HelixHypeTrainStatus.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/hypeTrain/HelixHypeTrain.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/hypeTrain/HelixHypeTrainContribution.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/hypeTrain/HelixHypeTrainAllTimeHigh.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/moderation/HelixModerationApi.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/interfaces/endpoints/moderation.external.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/moderation/HelixAutoModSettings.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/moderation/HelixAutoModStatus.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/moderation/HelixBan.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/moderation/HelixBanUser.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/moderation/HelixBlockedTerm.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/moderation/HelixModeratedChannel.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/moderation/HelixModerator.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/moderation/HelixShieldModeStatus.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/moderation/HelixUnbanRequest.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/moderation/HelixWarning.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/poll/HelixPollApi.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/interfaces/endpoints/poll.external.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/poll/HelixPoll.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/poll/HelixPollChoice.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/prediction/HelixPredictionApi.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/interfaces/endpoints/prediction.external.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/prediction/HelixPrediction.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/prediction/HelixPredictionOutcome.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/prediction/HelixPredictor.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/raids/HelixRaidApi.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/interfaces/endpoints/raid.external.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/raids/HelixRaid.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/schedule/HelixScheduleApi.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/interfaces/endpoints/schedule.external.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/schedule/HelixPaginatedScheduleSegmentRequest.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/schedule/HelixScheduleSegment.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/schedule/HelixSchedule.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/search/HelixSearchApi.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/interfaces/endpoints/search.external.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/search/HelixChannelSearchResult.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/stream/HelixStreamApi.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/errors/StreamNotLiveError.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/interfaces/endpoints/stream.external.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/stream/HelixStream.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/stream/HelixStreamMarker.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/stream/HelixStreamMarkerWithVideo.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/subscriptions/HelixSubscriptionApi.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/interfaces/endpoints/subscription.external.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/subscriptions/HelixPaginatedSubscriptionsRequest.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/subscriptions/HelixSubscription.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/subscriptions/HelixUserSubscription.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/team/HelixTeamApi.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/team/HelixTeam.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/team/HelixTeamWithUsers.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/user/HelixUserApi.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/interfaces/endpoints/user.external.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/user/extensions/HelixInstalledExtensionList.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/user/extensions/HelixInstalledExtension.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/user/extensions/HelixBaseExtension.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/user/extensions/HelixUserExtension.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/user/HelixPrivilegedUser.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/user/HelixUser.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/user/HelixUserBlock.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/video/HelixVideoApi.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/video/HelixVideo.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/whisper/HelixWhisperApi.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/interfaces/endpoints/whisper.external.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/reporting/ApiReportedRequest.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/client/NoContextApiClient.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/client/UserContextApiClient.js", "../../../src/services/telegram.service.ts", "../../../src/utils/thumbnail.ts", "../../../src/services/eventsub.service.ts", "../../../src/db/connection.ts", "../../../src/db/repository.factory.ts", "../../../src/db/repositories/drizzle/index.ts", "../../../src/db/repositories/drizzle/chat.drizzle.repository.ts", "../../../src/db/schema.ts", "../../../src/domain/mapper.ts", "../../../src/domain/models.ts", "../../../src/db/repositories/drizzle/channel.drizzle.repository.ts", "../../../src/db/repositories/drizzle/follow.drizzle.repository.ts", "../../../src/db/repositories/drizzle/stream.drizzle.repository.ts", "../../../src/db/repositories/cloudflare-kv/index.ts", "../../../src/db/repositories/cloudflare-kv/session.kv.repository.ts", "../../../src/webhooks/twitch.ts", "../../../src/services/notification.service.ts", "../../../node_modules/.pnpm/wrangler@4.71.0_@cloudflare+workers-types@4.20260307.1/node_modules/wrangler/templates/middleware/middleware-ensure-req-body-drained.ts", "../../../node_modules/.pnpm/wrangler@4.71.0_@cloudflare+workers-types@4.20260307.1/node_modules/wrangler/templates/middleware/middleware-miniflare3-json-error.ts", "../../../node_modules/.pnpm/wrangler@4.71.0_@cloudflare+workers-types@4.20260307.1/node_modules/wrangler/templates/middleware/common.ts"], + "sourceRoot": "/home/satont/Projects/twitch-notifier/.wrangler/tmp/dev-FVjRI2", + "sourcesContent": ["/* @__NO_SIDE_EFFECTS__ */\nexport function rawHeaders(headers) {\n\tconst rawHeaders = [];\n\tfor (const key in headers) {\n\t\tif (Array.isArray(headers[key])) {\n\t\t\tfor (const h of headers[key]) {\n\t\t\t\trawHeaders.push(key, h);\n\t\t\t}\n\t\t} else {\n\t\t\trawHeaders.push(key, headers[key]);\n\t\t}\n\t}\n\treturn rawHeaders;\n}\n/* @__NO_SIDE_EFFECTS__ */\nexport function mergeFns(...functions) {\n\treturn function(...args) {\n\t\tfor (const fn of functions) {\n\t\t\tfn(...args);\n\t\t}\n\t};\n}\n/* @__NO_SIDE_EFFECTS__ */\nexport function createNotImplementedError(name) {\n\treturn new Error(`[unenv] ${name} is not implemented yet!`);\n}\n/* @__NO_SIDE_EFFECTS__ */\nexport function notImplemented(name) {\n\tconst fn = () => {\n\t\tthrow createNotImplementedError(name);\n\t};\n\treturn Object.assign(fn, { __unenv__: true });\n}\n/* @__NO_SIDE_EFFECTS__ */\nexport function notImplementedAsync(name) {\n\tconst fn = notImplemented(name);\n\tfn.__promisify__ = () => notImplemented(name + \".__promisify__\");\n\tfn.native = fn;\n\treturn fn;\n}\n/* @__NO_SIDE_EFFECTS__ */\nexport function notImplementedClass(name) {\n\treturn class {\n\t\t__unenv__ = true;\n\t\tconstructor() {\n\t\t\tthrow new Error(`[unenv] ${name} is not implemented yet!`);\n\t\t}\n\t};\n}\n", "import { createNotImplementedError } from \"../../../_internal/utils.mjs\";\nconst _timeOrigin = globalThis.performance?.timeOrigin ?? Date.now();\nconst _performanceNow = globalThis.performance?.now ? globalThis.performance.now.bind(globalThis.performance) : () => Date.now() - _timeOrigin;\nconst nodeTiming = {\n\tname: \"node\",\n\tentryType: \"node\",\n\tstartTime: 0,\n\tduration: 0,\n\tnodeStart: 0,\n\tv8Start: 0,\n\tbootstrapComplete: 0,\n\tenvironment: 0,\n\tloopStart: 0,\n\tloopExit: 0,\n\tidleTime: 0,\n\tuvMetricsInfo: {\n\t\tloopCount: 0,\n\t\tevents: 0,\n\t\teventsWaiting: 0\n\t},\n\tdetail: undefined,\n\ttoJSON() {\n\t\treturn this;\n\t}\n};\n// PerformanceEntry\nexport class PerformanceEntry {\n\t__unenv__ = true;\n\tdetail;\n\tentryType = \"event\";\n\tname;\n\tstartTime;\n\tconstructor(name, options) {\n\t\tthis.name = name;\n\t\tthis.startTime = options?.startTime || _performanceNow();\n\t\tthis.detail = options?.detail;\n\t}\n\tget duration() {\n\t\treturn _performanceNow() - this.startTime;\n\t}\n\ttoJSON() {\n\t\treturn {\n\t\t\tname: this.name,\n\t\t\tentryType: this.entryType,\n\t\t\tstartTime: this.startTime,\n\t\t\tduration: this.duration,\n\t\t\tdetail: this.detail\n\t\t};\n\t}\n}\n// PerformanceMark\nexport const PerformanceMark = class PerformanceMark extends PerformanceEntry {\n\tentryType = \"mark\";\n\tconstructor() {\n\t\t// @ts-ignore\n\t\tsuper(...arguments);\n\t}\n\tget duration() {\n\t\treturn 0;\n\t}\n};\n// PerformanceMark\nexport class PerformanceMeasure extends PerformanceEntry {\n\tentryType = \"measure\";\n}\n// PerformanceResourceTiming\nexport class PerformanceResourceTiming extends PerformanceEntry {\n\tentryType = \"resource\";\n\tserverTiming = [];\n\tconnectEnd = 0;\n\tconnectStart = 0;\n\tdecodedBodySize = 0;\n\tdomainLookupEnd = 0;\n\tdomainLookupStart = 0;\n\tencodedBodySize = 0;\n\tfetchStart = 0;\n\tinitiatorType = \"\";\n\tname = \"\";\n\tnextHopProtocol = \"\";\n\tredirectEnd = 0;\n\tredirectStart = 0;\n\trequestStart = 0;\n\tresponseEnd = 0;\n\tresponseStart = 0;\n\tsecureConnectionStart = 0;\n\tstartTime = 0;\n\ttransferSize = 0;\n\tworkerStart = 0;\n\tresponseStatus = 0;\n}\n// PerformanceObserverEntryList\nexport class PerformanceObserverEntryList {\n\t__unenv__ = true;\n\tgetEntries() {\n\t\treturn [];\n\t}\n\tgetEntriesByName(_name, _type) {\n\t\treturn [];\n\t}\n\tgetEntriesByType(type) {\n\t\treturn [];\n\t}\n}\n// Performance\nexport class Performance {\n\t__unenv__ = true;\n\ttimeOrigin = _timeOrigin;\n\teventCounts = new Map();\n\t_entries = [];\n\t_resourceTimingBufferSize = 0;\n\tnavigation = undefined;\n\ttiming = undefined;\n\ttimerify(_fn, _options) {\n\t\tthrow createNotImplementedError(\"Performance.timerify\");\n\t}\n\tget nodeTiming() {\n\t\treturn nodeTiming;\n\t}\n\teventLoopUtilization() {\n\t\treturn {};\n\t}\n\tmarkResourceTiming() {\n\t\t// TODO: create a new PerformanceResourceTiming entry\n\t\t// so that performance.getEntries, getEntriesByName, and getEntriesByType return it\n\t\t// see: https://nodejs.org/api/perf_hooks.html#performancemarkresourcetimingtiminginfo-requestedurl-initiatortype-global-cachemode-bodyinfo-responsestatus-deliverytype\n\t\treturn new PerformanceResourceTiming(\"\");\n\t}\n\tonresourcetimingbufferfull = null;\n\tnow() {\n\t\t// https://developer.mozilla.org/en-US/docs/Web/API/Performance/now\n\t\tif (this.timeOrigin === _timeOrigin) {\n\t\t\treturn _performanceNow();\n\t\t}\n\t\treturn Date.now() - this.timeOrigin;\n\t}\n\tclearMarks(markName) {\n\t\tthis._entries = markName ? this._entries.filter((e) => e.name !== markName) : this._entries.filter((e) => e.entryType !== \"mark\");\n\t}\n\tclearMeasures(measureName) {\n\t\tthis._entries = measureName ? this._entries.filter((e) => e.name !== measureName) : this._entries.filter((e) => e.entryType !== \"measure\");\n\t}\n\tclearResourceTimings() {\n\t\tthis._entries = this._entries.filter((e) => e.entryType !== \"resource\" || e.entryType !== \"navigation\");\n\t}\n\tgetEntries() {\n\t\treturn this._entries;\n\t}\n\tgetEntriesByName(name, type) {\n\t\treturn this._entries.filter((e) => e.name === name && (!type || e.entryType === type));\n\t}\n\tgetEntriesByType(type) {\n\t\treturn this._entries.filter((e) => e.entryType === type);\n\t}\n\tmark(name, options) {\n\t\t// @ts-expect-error constructor is not protected\n\t\tconst entry = new PerformanceMark(name, options);\n\t\tthis._entries.push(entry);\n\t\treturn entry;\n\t}\n\tmeasure(measureName, startOrMeasureOptions, endMark) {\n\t\tlet start;\n\t\tlet end;\n\t\tif (typeof startOrMeasureOptions === \"string\") {\n\t\t\tstart = this.getEntriesByName(startOrMeasureOptions, \"mark\")[0]?.startTime;\n\t\t\tend = this.getEntriesByName(endMark, \"mark\")[0]?.startTime;\n\t\t} else {\n\t\t\tstart = Number.parseFloat(startOrMeasureOptions?.start) || this.now();\n\t\t\tend = Number.parseFloat(startOrMeasureOptions?.end) || this.now();\n\t\t}\n\t\tconst entry = new PerformanceMeasure(measureName, {\n\t\t\tstartTime: start,\n\t\t\tdetail: {\n\t\t\t\tstart,\n\t\t\t\tend\n\t\t\t}\n\t\t});\n\t\tthis._entries.push(entry);\n\t\treturn entry;\n\t}\n\tsetResourceTimingBufferSize(maxSize) {\n\t\tthis._resourceTimingBufferSize = maxSize;\n\t}\n\taddEventListener(type, listener, options) {\n\t\tthrow createNotImplementedError(\"Performance.addEventListener\");\n\t}\n\tremoveEventListener(type, listener, options) {\n\t\tthrow createNotImplementedError(\"Performance.removeEventListener\");\n\t}\n\tdispatchEvent(event) {\n\t\tthrow createNotImplementedError(\"Performance.dispatchEvent\");\n\t}\n\ttoJSON() {\n\t\treturn this;\n\t}\n}\n// PerformanceObserver\nexport class PerformanceObserver {\n\t__unenv__ = true;\n\tstatic supportedEntryTypes = [];\n\t_callback = null;\n\tconstructor(callback) {\n\t\tthis._callback = callback;\n\t}\n\ttakeRecords() {\n\t\treturn [];\n\t}\n\tdisconnect() {\n\t\tthrow createNotImplementedError(\"PerformanceObserver.disconnect\");\n\t}\n\tobserve(options) {\n\t\tthrow createNotImplementedError(\"PerformanceObserver.observe\");\n\t}\n\tbind(fn) {\n\t\treturn fn;\n\t}\n\trunInAsyncScope(fn, thisArg, ...args) {\n\t\treturn fn.call(thisArg, ...args);\n\t}\n\tasyncId() {\n\t\treturn 0;\n\t}\n\ttriggerAsyncId() {\n\t\treturn 0;\n\t}\n\temitDestroy() {\n\t\treturn this;\n\t}\n}\n// workerd implements a subset of globalThis.performance (as of last check, only timeOrigin set to 0 + now() implemented)\n// We already use performance.now() from globalThis.performance, if provided (see top of this file)\n// If we detect this condition, we can just use polyfill instead.\nexport const performance = globalThis.performance && \"addEventListener\" in globalThis.performance ? globalThis.performance : new Performance();\n", "import { IntervalHistogram, RecordableHistogram } from \"./internal/perf_hooks/histogram.mjs\";\nimport { performance, Performance, PerformanceEntry, PerformanceMark, PerformanceMeasure, PerformanceObserverEntryList, PerformanceObserver, PerformanceResourceTiming } from \"./internal/perf_hooks/performance.mjs\";\nexport * from \"./internal/perf_hooks/performance.mjs\";\n// prettier-ignore\nimport { NODE_PERFORMANCE_GC_MAJOR, NODE_PERFORMANCE_GC_MINOR, NODE_PERFORMANCE_GC_INCREMENTAL, NODE_PERFORMANCE_GC_WEAKCB, NODE_PERFORMANCE_GC_FLAGS_NO, NODE_PERFORMANCE_GC_FLAGS_CONSTRUCT_RETAINED, NODE_PERFORMANCE_GC_FLAGS_FORCED, NODE_PERFORMANCE_GC_FLAGS_SYNCHRONOUS_PHANTOM_PROCESSING, NODE_PERFORMANCE_GC_FLAGS_ALL_AVAILABLE_GARBAGE, NODE_PERFORMANCE_GC_FLAGS_ALL_EXTERNAL_MEMORY, NODE_PERFORMANCE_GC_FLAGS_SCHEDULE_IDLE, NODE_PERFORMANCE_ENTRY_TYPE_GC, NODE_PERFORMANCE_ENTRY_TYPE_HTTP, NODE_PERFORMANCE_ENTRY_TYPE_HTTP2, NODE_PERFORMANCE_ENTRY_TYPE_NET, NODE_PERFORMANCE_ENTRY_TYPE_DNS, NODE_PERFORMANCE_MILESTONE_TIME_ORIGIN_TIMESTAMP, NODE_PERFORMANCE_MILESTONE_TIME_ORIGIN, NODE_PERFORMANCE_MILESTONE_ENVIRONMENT, NODE_PERFORMANCE_MILESTONE_NODE_START, NODE_PERFORMANCE_MILESTONE_V8_START, NODE_PERFORMANCE_MILESTONE_LOOP_START, NODE_PERFORMANCE_MILESTONE_LOOP_EXIT, NODE_PERFORMANCE_MILESTONE_BOOTSTRAP_COMPLETE } from \"./internal/perf_hooks/constants.mjs\";\n// prettier-ignore\nexport const constants = {\n\tNODE_PERFORMANCE_GC_MAJOR,\n\tNODE_PERFORMANCE_GC_MINOR,\n\tNODE_PERFORMANCE_GC_INCREMENTAL,\n\tNODE_PERFORMANCE_GC_WEAKCB,\n\tNODE_PERFORMANCE_GC_FLAGS_NO,\n\tNODE_PERFORMANCE_GC_FLAGS_CONSTRUCT_RETAINED,\n\tNODE_PERFORMANCE_GC_FLAGS_FORCED,\n\tNODE_PERFORMANCE_GC_FLAGS_SYNCHRONOUS_PHANTOM_PROCESSING,\n\tNODE_PERFORMANCE_GC_FLAGS_ALL_AVAILABLE_GARBAGE,\n\tNODE_PERFORMANCE_GC_FLAGS_ALL_EXTERNAL_MEMORY,\n\tNODE_PERFORMANCE_GC_FLAGS_SCHEDULE_IDLE,\n\tNODE_PERFORMANCE_ENTRY_TYPE_GC,\n\tNODE_PERFORMANCE_ENTRY_TYPE_HTTP,\n\tNODE_PERFORMANCE_ENTRY_TYPE_HTTP2,\n\tNODE_PERFORMANCE_ENTRY_TYPE_NET,\n\tNODE_PERFORMANCE_ENTRY_TYPE_DNS,\n\tNODE_PERFORMANCE_MILESTONE_TIME_ORIGIN_TIMESTAMP,\n\tNODE_PERFORMANCE_MILESTONE_TIME_ORIGIN,\n\tNODE_PERFORMANCE_MILESTONE_ENVIRONMENT,\n\tNODE_PERFORMANCE_MILESTONE_NODE_START,\n\tNODE_PERFORMANCE_MILESTONE_V8_START,\n\tNODE_PERFORMANCE_MILESTONE_LOOP_START,\n\tNODE_PERFORMANCE_MILESTONE_LOOP_EXIT,\n\tNODE_PERFORMANCE_MILESTONE_BOOTSTRAP_COMPLETE\n};\nexport const monitorEventLoopDelay = function(_options) {\n\treturn new IntervalHistogram();\n};\nexport const createHistogram = function(_options) {\n\treturn new RecordableHistogram();\n};\nexport default {\n\tPerformance,\n\tPerformanceMark,\n\tPerformanceEntry,\n\tPerformanceMeasure,\n\tPerformanceObserverEntryList,\n\tPerformanceObserver,\n\tPerformanceResourceTiming,\n\tperformance,\n\tconstants,\n\tcreateHistogram,\n\tmonitorEventLoopDelay\n};\n", "import {\n performance,\n Performance,\n PerformanceEntry,\n PerformanceMark,\n PerformanceMeasure,\n PerformanceObserver,\n PerformanceObserverEntryList,\n PerformanceResourceTiming\n} from \"node:perf_hooks\";\nglobalThis.performance = performance;\nglobalThis.Performance = Performance;\nglobalThis.PerformanceEntry = PerformanceEntry;\nglobalThis.PerformanceMark = PerformanceMark;\nglobalThis.PerformanceMeasure = PerformanceMeasure;\nglobalThis.PerformanceObserver = PerformanceObserver;\nglobalThis.PerformanceObserverEntryList = PerformanceObserverEntryList;\nglobalThis.PerformanceResourceTiming = PerformanceResourceTiming;\n", "", "// `esbuild` doesn't support returning `watch*` options from `onStart()`\n// plugin callbacks. Instead, we define an empty virtual module that is\n// imported by this injected file. Importing the module registers watchers.\nimport \"wrangler:modules-watch\";\n", "module.exports.isNode = false;\n\n", "function RetryOperation(timeouts, options) {\n // Compatibility for the old (timeouts, retryForever) signature\n if (typeof options === 'boolean') {\n options = { forever: options };\n }\n\n this._originalTimeouts = JSON.parse(JSON.stringify(timeouts));\n this._timeouts = timeouts;\n this._options = options || {};\n this._maxRetryTime = options && options.maxRetryTime || Infinity;\n this._fn = null;\n this._errors = [];\n this._attempts = 1;\n this._operationTimeout = null;\n this._operationTimeoutCb = null;\n this._timeout = null;\n this._operationStart = null;\n this._timer = null;\n\n if (this._options.forever) {\n this._cachedTimeouts = this._timeouts.slice(0);\n }\n}\nmodule.exports = RetryOperation;\n\nRetryOperation.prototype.reset = function() {\n this._attempts = 1;\n this._timeouts = this._originalTimeouts.slice(0);\n}\n\nRetryOperation.prototype.stop = function() {\n if (this._timeout) {\n clearTimeout(this._timeout);\n }\n if (this._timer) {\n clearTimeout(this._timer);\n }\n\n this._timeouts = [];\n this._cachedTimeouts = null;\n};\n\nRetryOperation.prototype.retry = function(err) {\n if (this._timeout) {\n clearTimeout(this._timeout);\n }\n\n if (!err) {\n return false;\n }\n var currentTime = new Date().getTime();\n if (err && currentTime - this._operationStart >= this._maxRetryTime) {\n this._errors.push(err);\n this._errors.unshift(new Error('RetryOperation timeout occurred'));\n return false;\n }\n\n this._errors.push(err);\n\n var timeout = this._timeouts.shift();\n if (timeout === undefined) {\n if (this._cachedTimeouts) {\n // retry forever, only keep last error\n this._errors.splice(0, this._errors.length - 1);\n timeout = this._cachedTimeouts.slice(-1);\n } else {\n return false;\n }\n }\n\n var self = this;\n this._timer = setTimeout(function() {\n self._attempts++;\n\n if (self._operationTimeoutCb) {\n self._timeout = setTimeout(function() {\n self._operationTimeoutCb(self._attempts);\n }, self._operationTimeout);\n\n if (self._options.unref) {\n self._timeout.unref();\n }\n }\n\n self._fn(self._attempts);\n }, timeout);\n\n if (this._options.unref) {\n this._timer.unref();\n }\n\n return true;\n};\n\nRetryOperation.prototype.attempt = function(fn, timeoutOps) {\n this._fn = fn;\n\n if (timeoutOps) {\n if (timeoutOps.timeout) {\n this._operationTimeout = timeoutOps.timeout;\n }\n if (timeoutOps.cb) {\n this._operationTimeoutCb = timeoutOps.cb;\n }\n }\n\n var self = this;\n if (this._operationTimeoutCb) {\n this._timeout = setTimeout(function() {\n self._operationTimeoutCb();\n }, self._operationTimeout);\n }\n\n this._operationStart = new Date().getTime();\n\n this._fn(this._attempts);\n};\n\nRetryOperation.prototype.try = function(fn) {\n console.log('Using RetryOperation.try() is deprecated');\n this.attempt(fn);\n};\n\nRetryOperation.prototype.start = function(fn) {\n console.log('Using RetryOperation.start() is deprecated');\n this.attempt(fn);\n};\n\nRetryOperation.prototype.start = RetryOperation.prototype.try;\n\nRetryOperation.prototype.errors = function() {\n return this._errors;\n};\n\nRetryOperation.prototype.attempts = function() {\n return this._attempts;\n};\n\nRetryOperation.prototype.mainError = function() {\n if (this._errors.length === 0) {\n return null;\n }\n\n var counts = {};\n var mainError = null;\n var mainErrorCount = 0;\n\n for (var i = 0; i < this._errors.length; i++) {\n var error = this._errors[i];\n var message = error.message;\n var count = (counts[message] || 0) + 1;\n\n counts[message] = count;\n\n if (count >= mainErrorCount) {\n mainError = error;\n mainErrorCount = count;\n }\n }\n\n return mainError;\n};\n", "var RetryOperation = require('./retry_operation');\n\nexports.operation = function(options) {\n var timeouts = exports.timeouts(options);\n return new RetryOperation(timeouts, {\n forever: options && (options.forever || options.retries === Infinity),\n unref: options && options.unref,\n maxRetryTime: options && options.maxRetryTime\n });\n};\n\nexports.timeouts = function(options) {\n if (options instanceof Array) {\n return [].concat(options);\n }\n\n var opts = {\n retries: 10,\n factor: 2,\n minTimeout: 1 * 1000,\n maxTimeout: Infinity,\n randomize: false\n };\n for (var key in options) {\n opts[key] = options[key];\n }\n\n if (opts.minTimeout > opts.maxTimeout) {\n throw new Error('minTimeout is greater than maxTimeout');\n }\n\n var timeouts = [];\n for (var i = 0; i < opts.retries; i++) {\n timeouts.push(this.createTimeout(i, opts));\n }\n\n if (options && options.forever && !timeouts.length) {\n timeouts.push(this.createTimeout(i, opts));\n }\n\n // sort the array numerically ascending\n timeouts.sort(function(a,b) {\n return a - b;\n });\n\n return timeouts;\n};\n\nexports.createTimeout = function(attempt, opts) {\n var random = (opts.randomize)\n ? (Math.random() + 1)\n : 1;\n\n var timeout = Math.round(random * Math.max(opts.minTimeout, 1) * Math.pow(opts.factor, attempt));\n timeout = Math.min(timeout, opts.maxTimeout);\n\n return timeout;\n};\n\nexports.wrap = function(obj, options, methods) {\n if (options instanceof Array) {\n methods = options;\n options = null;\n }\n\n if (!methods) {\n methods = [];\n for (var key in obj) {\n if (typeof obj[key] === 'function') {\n methods.push(key);\n }\n }\n }\n\n for (var i = 0; i < methods.length; i++) {\n var method = methods[i];\n var original = obj[method];\n\n obj[method] = function retryWrapper(original) {\n var op = exports.operation(options);\n var args = Array.prototype.slice.call(arguments, 1);\n var callback = args.pop();\n\n args.push(function(err) {\n if (op.retry(err)) {\n return;\n }\n if (err) {\n arguments[0] = op.mainError();\n }\n callback.apply(this, arguments);\n });\n\n op.attempt(function() {\n original.apply(obj, args);\n });\n }.bind(obj, original);\n obj[method].options = options;\n }\n};\n", "module.exports = require('./lib/retry');", "// This loads all middlewares exposed on the middleware object and then starts\n// the invocation chain. The big idea is that we can add these to the middleware\n// export dynamically through wrangler, or we can potentially let users directly\n// add them as a sort of \"plugin\" system.\n\nimport ENTRY, { __INTERNAL_WRANGLER_MIDDLEWARE__ } from \"/home/satont/Projects/twitch-notifier/.wrangler/tmp/bundle-ldhBcJ/middleware-insertion-facade.js\";\nimport { __facade_invoke__, __facade_register__, Dispatcher } from \"/home/satont/Projects/twitch-notifier/node_modules/.pnpm/wrangler@4.71.0_@cloudflare+workers-types@4.20260307.1/node_modules/wrangler/templates/middleware/common.ts\";\nimport type { WorkerEntrypointConstructor } from \"/home/satont/Projects/twitch-notifier/.wrangler/tmp/bundle-ldhBcJ/middleware-insertion-facade.js\";\n\n// Preserve all the exports from the worker\nexport * from \"/home/satont/Projects/twitch-notifier/.wrangler/tmp/bundle-ldhBcJ/middleware-insertion-facade.js\";\n\nclass __Facade_ScheduledController__ implements ScheduledController {\n\treadonly #noRetry: ScheduledController[\"noRetry\"];\n\n\tconstructor(\n\t\treadonly scheduledTime: number,\n\t\treadonly cron: string,\n\t\tnoRetry: ScheduledController[\"noRetry\"]\n\t) {\n\t\tthis.#noRetry = noRetry;\n\t}\n\n\tnoRetry() {\n\t\tif (!(this instanceof __Facade_ScheduledController__)) {\n\t\t\tthrow new TypeError(\"Illegal invocation\");\n\t\t}\n\t\t// Need to call native method immediately in case uncaught error thrown\n\t\tthis.#noRetry();\n\t}\n}\n\nfunction wrapExportedHandler(worker: ExportedHandler): ExportedHandler {\n\t// If we don't have any middleware defined, just return the handler as is\n\tif (\n\t\t__INTERNAL_WRANGLER_MIDDLEWARE__ === undefined ||\n\t\t__INTERNAL_WRANGLER_MIDDLEWARE__.length === 0\n\t) {\n\t\treturn worker;\n\t}\n\t// Otherwise, register all middleware once\n\tfor (const middleware of __INTERNAL_WRANGLER_MIDDLEWARE__) {\n\t\t__facade_register__(middleware);\n\t}\n\n\tconst fetchDispatcher: ExportedHandlerFetchHandler = function (\n\t\trequest,\n\t\tenv,\n\t\tctx\n\t) {\n\t\tif (worker.fetch === undefined) {\n\t\t\tthrow new Error(\"Handler does not export a fetch() function.\");\n\t\t}\n\t\treturn worker.fetch(request, env, ctx);\n\t};\n\n\treturn {\n\t\t...worker,\n\t\tfetch(request, env, ctx) {\n\t\t\tconst dispatcher: Dispatcher = function (type, init) {\n\t\t\t\tif (type === \"scheduled\" && worker.scheduled !== undefined) {\n\t\t\t\t\tconst controller = new __Facade_ScheduledController__(\n\t\t\t\t\t\tDate.now(),\n\t\t\t\t\t\tinit.cron ?? \"\",\n\t\t\t\t\t\t() => {}\n\t\t\t\t\t);\n\t\t\t\t\treturn worker.scheduled(controller, env, ctx);\n\t\t\t\t}\n\t\t\t};\n\t\t\treturn __facade_invoke__(request, env, ctx, dispatcher, fetchDispatcher);\n\t\t},\n\t};\n}\n\nfunction wrapWorkerEntrypoint(\n\tklass: WorkerEntrypointConstructor\n): WorkerEntrypointConstructor {\n\t// If we don't have any middleware defined, just return the handler as is\n\tif (\n\t\t__INTERNAL_WRANGLER_MIDDLEWARE__ === undefined ||\n\t\t__INTERNAL_WRANGLER_MIDDLEWARE__.length === 0\n\t) {\n\t\treturn klass;\n\t}\n\t// Otherwise, register all middleware once\n\tfor (const middleware of __INTERNAL_WRANGLER_MIDDLEWARE__) {\n\t\t__facade_register__(middleware);\n\t}\n\n\t// `extend`ing `klass` here so other RPC methods remain callable\n\treturn class extends klass {\n\t\t#fetchDispatcher: ExportedHandlerFetchHandler> = (\n\t\t\trequest,\n\t\t\tenv,\n\t\t\tctx\n\t\t) => {\n\t\t\tthis.env = env;\n\t\t\tthis.ctx = ctx;\n\t\t\tif (super.fetch === undefined) {\n\t\t\t\tthrow new Error(\"Entrypoint class does not define a fetch() function.\");\n\t\t\t}\n\t\t\treturn super.fetch(request);\n\t\t};\n\n\t\t#dispatcher: Dispatcher = (type, init) => {\n\t\t\tif (type === \"scheduled\" && super.scheduled !== undefined) {\n\t\t\t\tconst controller = new __Facade_ScheduledController__(\n\t\t\t\t\tDate.now(),\n\t\t\t\t\tinit.cron ?? \"\",\n\t\t\t\t\t() => {}\n\t\t\t\t);\n\t\t\t\treturn super.scheduled(controller);\n\t\t\t}\n\t\t};\n\n\t\tfetch(request: Request) {\n\t\t\treturn __facade_invoke__(\n\t\t\t\trequest,\n\t\t\t\tthis.env,\n\t\t\t\tthis.ctx,\n\t\t\t\tthis.#dispatcher,\n\t\t\t\tthis.#fetchDispatcher\n\t\t\t);\n\t\t}\n\t};\n}\n\nlet WRAPPED_ENTRY: ExportedHandler | WorkerEntrypointConstructor | undefined;\nif (typeof ENTRY === \"object\") {\n\tWRAPPED_ENTRY = wrapExportedHandler(ENTRY);\n} else if (typeof ENTRY === \"function\") {\n\tWRAPPED_ENTRY = wrapWorkerEntrypoint(ENTRY);\n}\nexport default WRAPPED_ENTRY;\n", "\t\t\t\timport worker, * as OTHER_EXPORTS from \"/home/satont/Projects/twitch-notifier/src/index.ts\";\n\t\t\t\timport * as __MIDDLEWARE_0__ from \"/home/satont/Projects/twitch-notifier/node_modules/.pnpm/wrangler@4.71.0_@cloudflare+workers-types@4.20260307.1/node_modules/wrangler/templates/middleware/middleware-ensure-req-body-drained.ts\";\nimport * as __MIDDLEWARE_1__ from \"/home/satont/Projects/twitch-notifier/node_modules/.pnpm/wrangler@4.71.0_@cloudflare+workers-types@4.20260307.1/node_modules/wrangler/templates/middleware/middleware-miniflare3-json-error.ts\";\n\n\t\t\t\texport * from \"/home/satont/Projects/twitch-notifier/src/index.ts\";\n\t\t\t\tconst MIDDLEWARE_TEST_INJECT = \"__INJECT_FOR_TESTING_WRANGLER_MIDDLEWARE__\";\n\t\t\t\texport const __INTERNAL_WRANGLER_MIDDLEWARE__ = [\n\t\t\t\t\t\n\t\t\t\t\t__MIDDLEWARE_0__.default,__MIDDLEWARE_1__.default\n\t\t\t\t]\n\t\t\t\texport default worker;", "import { Hono } from 'hono';\nimport { webhookCallback } from 'grammy';\nimport { drizzle } from 'drizzle-orm/d1';\nimport type { Env } from './types';\nimport { createBot } from './bot';\nimport { I18nService } from './services/i18n.service';\nimport { TwitchService } from './services/twitch.service';\nimport { TelegramService } from './services/telegram.service';\nimport { EventSubService } from './services/eventsub.service';\nimport { CloudflareD1Connection } from './db/connection';\nimport { DrizzleRepositoryFactory } from './db/repository.factory';\nimport { CloudflareKVSessionRepository } from './db/repositories/cloudflare-kv';\nimport { handleTwitchWebhook } from './webhooks/twitch';\n\nconst app = new Hono<{ Bindings: Env }>();\n\n// Health check\napp.get('/', (c) => {\n return c.json({ status: 'ok', service: 'twitch-notifier' });\n});\n\n// Telegram webhook endpoint\napp.post('/telegram-webhook', async (c) => {\n const env = c.env;\n\n // Create database connection (serverless-agnostic)\n const dbClient = drizzle(env.DB);\n const dbConnection = new CloudflareD1Connection(dbClient);\n\n // Create repository factory\n const repositoryFactory = new DrizzleRepositoryFactory(dbConnection);\n\n // Create repositories\n const chatRepo = repositoryFactory.createChatRepository();\n const channelRepo = repositoryFactory.createChannelRepository();\n const followRepo = repositoryFactory.createFollowRepository();\n const streamRepo = repositoryFactory.createStreamRepository();\n\n // Create session repository using Cloudflare KV\n const sessionRepo = new CloudflareKVSessionRepository(env.SESSIONS_KV);\n\n // Initialize services\n const i18nService = new I18nService();\n await i18nService.init(); // Initialize i18next\n const twitchService = new TwitchService(env);\n const telegramService = new TelegramService(env, i18nService);\n const eventSubService = new EventSubService(\n twitchService.getApiClient(),\n env,\n env.BASE_URL\n );\n\n // Create bot instance\n const bot = createBot(env, {\n i18n: i18nService,\n twitch: twitchService,\n eventsub: eventSubService,\n chatRepo,\n channelRepo,\n followRepo,\n sessionRepo,\n });\n\n // Handle webhook\n const handler = webhookCallback(bot, 'hono');\n return handler(c);\n});\n\n// Twitch EventSub webhook endpoint\napp.post('/twitch-webhook', async (c) => {\n const env = c.env;\n const db = drizzle(env.DB);\n\n return await handleTwitchWebhook(c.req.raw, env, db);\n});\n\nexport default app;\n", "// src/index.ts\nimport { Hono } from \"./hono.js\";\nexport {\n Hono\n};\n", "// src/hono.ts\nimport { HonoBase } from \"./hono-base.js\";\nimport { RegExpRouter } from \"./router/reg-exp-router/index.js\";\nimport { SmartRouter } from \"./router/smart-router/index.js\";\nimport { TrieRouter } from \"./router/trie-router/index.js\";\nvar Hono = class extends HonoBase {\n /**\n * Creates an instance of the Hono class.\n *\n * @param options - Optional configuration options for the Hono instance.\n */\n constructor(options = {}) {\n super(options);\n this.router = options.router ?? new SmartRouter({\n routers: [new RegExpRouter(), new TrieRouter()]\n });\n }\n};\nexport {\n Hono\n};\n", "// src/hono-base.ts\nimport { compose } from \"./compose.js\";\nimport { Context } from \"./context.js\";\nimport { METHODS, METHOD_NAME_ALL, METHOD_NAME_ALL_LOWERCASE } from \"./router.js\";\nimport { COMPOSED_HANDLER } from \"./utils/constants.js\";\nimport { getPath, getPathNoStrict, mergePath } from \"./utils/url.js\";\nvar notFoundHandler = (c) => {\n return c.text(\"404 Not Found\", 404);\n};\nvar errorHandler = (err, c) => {\n if (\"getResponse\" in err) {\n const res = err.getResponse();\n return c.newResponse(res.body, res);\n }\n console.error(err);\n return c.text(\"Internal Server Error\", 500);\n};\nvar Hono = class _Hono {\n get;\n post;\n put;\n delete;\n options;\n patch;\n all;\n on;\n use;\n /*\n This class is like an abstract class and does not have a router.\n To use it, inherit the class and implement router in the constructor.\n */\n router;\n getPath;\n // Cannot use `#` because it requires visibility at JavaScript runtime.\n _basePath = \"/\";\n #path = \"/\";\n routes = [];\n constructor(options = {}) {\n const allMethods = [...METHODS, METHOD_NAME_ALL_LOWERCASE];\n allMethods.forEach((method) => {\n this[method] = (args1, ...args) => {\n if (typeof args1 === \"string\") {\n this.#path = args1;\n } else {\n this.#addRoute(method, this.#path, args1);\n }\n args.forEach((handler) => {\n this.#addRoute(method, this.#path, handler);\n });\n return this;\n };\n });\n this.on = (method, path, ...handlers) => {\n for (const p of [path].flat()) {\n this.#path = p;\n for (const m of [method].flat()) {\n handlers.map((handler) => {\n this.#addRoute(m.toUpperCase(), this.#path, handler);\n });\n }\n }\n return this;\n };\n this.use = (arg1, ...handlers) => {\n if (typeof arg1 === \"string\") {\n this.#path = arg1;\n } else {\n this.#path = \"*\";\n handlers.unshift(arg1);\n }\n handlers.forEach((handler) => {\n this.#addRoute(METHOD_NAME_ALL, this.#path, handler);\n });\n return this;\n };\n const { strict, ...optionsWithoutStrict } = options;\n Object.assign(this, optionsWithoutStrict);\n this.getPath = strict ?? true ? options.getPath ?? getPath : getPathNoStrict;\n }\n #clone() {\n const clone = new _Hono({\n router: this.router,\n getPath: this.getPath\n });\n clone.errorHandler = this.errorHandler;\n clone.#notFoundHandler = this.#notFoundHandler;\n clone.routes = this.routes;\n return clone;\n }\n #notFoundHandler = notFoundHandler;\n // Cannot use `#` because it requires visibility at JavaScript runtime.\n errorHandler = errorHandler;\n /**\n * `.route()` allows grouping other Hono instance in routes.\n *\n * @see {@link https://hono.dev/docs/api/routing#grouping}\n *\n * @param {string} path - base Path\n * @param {Hono} app - other Hono instance\n * @returns {Hono} routed Hono instance\n *\n * @example\n * ```ts\n * const app = new Hono()\n * const app2 = new Hono()\n *\n * app2.get(\"/user\", (c) => c.text(\"user\"))\n * app.route(\"/api\", app2) // GET /api/user\n * ```\n */\n route(path, app) {\n const subApp = this.basePath(path);\n app.routes.map((r) => {\n let handler;\n if (app.errorHandler === errorHandler) {\n handler = r.handler;\n } else {\n handler = async (c, next) => (await compose([], app.errorHandler)(c, () => r.handler(c, next))).res;\n handler[COMPOSED_HANDLER] = r.handler;\n }\n subApp.#addRoute(r.method, r.path, handler);\n });\n return this;\n }\n /**\n * `.basePath()` allows base paths to be specified.\n *\n * @see {@link https://hono.dev/docs/api/routing#base-path}\n *\n * @param {string} path - base Path\n * @returns {Hono} changed Hono instance\n *\n * @example\n * ```ts\n * const api = new Hono().basePath('/api')\n * ```\n */\n basePath(path) {\n const subApp = this.#clone();\n subApp._basePath = mergePath(this._basePath, path);\n return subApp;\n }\n /**\n * `.onError()` handles an error and returns a customized Response.\n *\n * @see {@link https://hono.dev/docs/api/hono#error-handling}\n *\n * @param {ErrorHandler} handler - request Handler for error\n * @returns {Hono} changed Hono instance\n *\n * @example\n * ```ts\n * app.onError((err, c) => {\n * console.error(`${err}`)\n * return c.text('Custom Error Message', 500)\n * })\n * ```\n */\n onError = (handler) => {\n this.errorHandler = handler;\n return this;\n };\n /**\n * `.notFound()` allows you to customize a Not Found Response.\n *\n * @see {@link https://hono.dev/docs/api/hono#not-found}\n *\n * @param {NotFoundHandler} handler - request handler for not-found\n * @returns {Hono} changed Hono instance\n *\n * @example\n * ```ts\n * app.notFound((c) => {\n * return c.text('Custom 404 Message', 404)\n * })\n * ```\n */\n notFound = (handler) => {\n this.#notFoundHandler = handler;\n return this;\n };\n /**\n * `.mount()` allows you to mount applications built with other frameworks into your Hono application.\n *\n * @see {@link https://hono.dev/docs/api/hono#mount}\n *\n * @param {string} path - base Path\n * @param {Function} applicationHandler - other Request Handler\n * @param {MountOptions} [options] - options of `.mount()`\n * @returns {Hono} mounted Hono instance\n *\n * @example\n * ```ts\n * import { Router as IttyRouter } from 'itty-router'\n * import { Hono } from 'hono'\n * // Create itty-router application\n * const ittyRouter = IttyRouter()\n * // GET /itty-router/hello\n * ittyRouter.get('/hello', () => new Response('Hello from itty-router'))\n *\n * const app = new Hono()\n * app.mount('/itty-router', ittyRouter.handle)\n * ```\n *\n * @example\n * ```ts\n * const app = new Hono()\n * // Send the request to another application without modification.\n * app.mount('/app', anotherApp, {\n * replaceRequest: (req) => req,\n * })\n * ```\n */\n mount(path, applicationHandler, options) {\n let replaceRequest;\n let optionHandler;\n if (options) {\n if (typeof options === \"function\") {\n optionHandler = options;\n } else {\n optionHandler = options.optionHandler;\n if (options.replaceRequest === false) {\n replaceRequest = (request) => request;\n } else {\n replaceRequest = options.replaceRequest;\n }\n }\n }\n const getOptions = optionHandler ? (c) => {\n const options2 = optionHandler(c);\n return Array.isArray(options2) ? options2 : [options2];\n } : (c) => {\n let executionContext = void 0;\n try {\n executionContext = c.executionCtx;\n } catch {\n }\n return [c.env, executionContext];\n };\n replaceRequest ||= (() => {\n const mergedPath = mergePath(this._basePath, path);\n const pathPrefixLength = mergedPath === \"/\" ? 0 : mergedPath.length;\n return (request) => {\n const url = new URL(request.url);\n url.pathname = url.pathname.slice(pathPrefixLength) || \"/\";\n return new Request(url, request);\n };\n })();\n const handler = async (c, next) => {\n const res = await applicationHandler(replaceRequest(c.req.raw), ...getOptions(c));\n if (res) {\n return res;\n }\n await next();\n };\n this.#addRoute(METHOD_NAME_ALL, mergePath(path, \"*\"), handler);\n return this;\n }\n #addRoute(method, path, handler) {\n method = method.toUpperCase();\n path = mergePath(this._basePath, path);\n const r = { basePath: this._basePath, path, method, handler };\n this.router.add(method, path, [handler, r]);\n this.routes.push(r);\n }\n #handleError(err, c) {\n if (err instanceof Error) {\n return this.errorHandler(err, c);\n }\n throw err;\n }\n #dispatch(request, executionCtx, env, method) {\n if (method === \"HEAD\") {\n return (async () => new Response(null, await this.#dispatch(request, executionCtx, env, \"GET\")))();\n }\n const path = this.getPath(request, { env });\n const matchResult = this.router.match(method, path);\n const c = new Context(request, {\n path,\n matchResult,\n env,\n executionCtx,\n notFoundHandler: this.#notFoundHandler\n });\n if (matchResult[0].length === 1) {\n let res;\n try {\n res = matchResult[0][0][0][0](c, async () => {\n c.res = await this.#notFoundHandler(c);\n });\n } catch (err) {\n return this.#handleError(err, c);\n }\n return res instanceof Promise ? res.then(\n (resolved) => resolved || (c.finalized ? c.res : this.#notFoundHandler(c))\n ).catch((err) => this.#handleError(err, c)) : res ?? this.#notFoundHandler(c);\n }\n const composed = compose(matchResult[0], this.errorHandler, this.#notFoundHandler);\n return (async () => {\n try {\n const context = await composed(c);\n if (!context.finalized) {\n throw new Error(\n \"Context is not finalized. Did you forget to return a Response object or `await next()`?\"\n );\n }\n return context.res;\n } catch (err) {\n return this.#handleError(err, c);\n }\n })();\n }\n /**\n * `.fetch()` will be entry point of your app.\n *\n * @see {@link https://hono.dev/docs/api/hono#fetch}\n *\n * @param {Request} request - request Object of request\n * @param {Env} Env - env Object\n * @param {ExecutionContext} - context of execution\n * @returns {Response | Promise} response of request\n *\n */\n fetch = (request, ...rest) => {\n return this.#dispatch(request, rest[1], rest[0], request.method);\n };\n /**\n * `.request()` is a useful method for testing.\n * You can pass a URL or pathname to send a GET request.\n * app will return a Response object.\n * ```ts\n * test('GET /hello is ok', async () => {\n * const res = await app.request('/hello')\n * expect(res.status).toBe(200)\n * })\n * ```\n * @see https://hono.dev/docs/api/hono#request\n */\n request = (input, requestInit, Env, executionCtx) => {\n if (input instanceof Request) {\n return this.fetch(requestInit ? new Request(input, requestInit) : input, Env, executionCtx);\n }\n input = input.toString();\n return this.fetch(\n new Request(\n /^https?:\\/\\//.test(input) ? input : `http://localhost${mergePath(\"/\", input)}`,\n requestInit\n ),\n Env,\n executionCtx\n );\n };\n /**\n * `.fire()` automatically adds a global fetch event listener.\n * This can be useful for environments that adhere to the Service Worker API, such as non-ES module Cloudflare Workers.\n * @deprecated\n * Use `fire` from `hono/service-worker` instead.\n * ```ts\n * import { Hono } from 'hono'\n * import { fire } from 'hono/service-worker'\n *\n * const app = new Hono()\n * // ...\n * fire(app)\n * ```\n * @see https://hono.dev/docs/api/hono#fire\n * @see https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API\n * @see https://developers.cloudflare.com/workers/reference/migrate-to-module-workers/\n */\n fire = () => {\n addEventListener(\"fetch\", (event) => {\n event.respondWith(this.#dispatch(event.request, event, void 0, event.request.method));\n });\n };\n};\nexport {\n Hono as HonoBase\n};\n", "// src/compose.ts\nvar compose = (middleware, onError, onNotFound) => {\n return (context, next) => {\n let index = -1;\n return dispatch(0);\n async function dispatch(i) {\n if (i <= index) {\n throw new Error(\"next() called multiple times\");\n }\n index = i;\n let res;\n let isError = false;\n let handler;\n if (middleware[i]) {\n handler = middleware[i][0][0];\n context.req.routeIndex = i;\n } else {\n handler = i === middleware.length && next || void 0;\n }\n if (handler) {\n try {\n res = await handler(context, () => dispatch(i + 1));\n } catch (err) {\n if (err instanceof Error && onError) {\n context.error = err;\n res = await onError(err, context);\n isError = true;\n } else {\n throw err;\n }\n }\n } else {\n if (context.finalized === false && onNotFound) {\n res = await onNotFound(context);\n }\n }\n if (res && (context.finalized === false || isError)) {\n context.res = res;\n }\n return context;\n }\n };\n};\nexport {\n compose\n};\n", "// src/context.ts\nimport { HonoRequest } from \"./request.js\";\nimport { HtmlEscapedCallbackPhase, resolveCallback } from \"./utils/html.js\";\nvar TEXT_PLAIN = \"text/plain; charset=UTF-8\";\nvar setDefaultContentType = (contentType, headers) => {\n return {\n \"Content-Type\": contentType,\n ...headers\n };\n};\nvar createResponseInstance = (body, init) => new Response(body, init);\nvar Context = class {\n #rawRequest;\n #req;\n /**\n * `.env` can get bindings (environment variables, secrets, KV namespaces, D1 database, R2 bucket etc.) in Cloudflare Workers.\n *\n * @see {@link https://hono.dev/docs/api/context#env}\n *\n * @example\n * ```ts\n * // Environment object for Cloudflare Workers\n * app.get('*', async c => {\n * const counter = c.env.COUNTER\n * })\n * ```\n */\n env = {};\n #var;\n finalized = false;\n /**\n * `.error` can get the error object from the middleware if the Handler throws an error.\n *\n * @see {@link https://hono.dev/docs/api/context#error}\n *\n * @example\n * ```ts\n * app.use('*', async (c, next) => {\n * await next()\n * if (c.error) {\n * // do something...\n * }\n * })\n * ```\n */\n error;\n #status;\n #executionCtx;\n #res;\n #layout;\n #renderer;\n #notFoundHandler;\n #preparedHeaders;\n #matchResult;\n #path;\n /**\n * Creates an instance of the Context class.\n *\n * @param req - The Request object.\n * @param options - Optional configuration options for the context.\n */\n constructor(req, options) {\n this.#rawRequest = req;\n if (options) {\n this.#executionCtx = options.executionCtx;\n this.env = options.env;\n this.#notFoundHandler = options.notFoundHandler;\n this.#path = options.path;\n this.#matchResult = options.matchResult;\n }\n }\n /**\n * `.req` is the instance of {@link HonoRequest}.\n */\n get req() {\n this.#req ??= new HonoRequest(this.#rawRequest, this.#path, this.#matchResult);\n return this.#req;\n }\n /**\n * @see {@link https://hono.dev/docs/api/context#event}\n * The FetchEvent associated with the current request.\n *\n * @throws Will throw an error if the context does not have a FetchEvent.\n */\n get event() {\n if (this.#executionCtx && \"respondWith\" in this.#executionCtx) {\n return this.#executionCtx;\n } else {\n throw Error(\"This context has no FetchEvent\");\n }\n }\n /**\n * @see {@link https://hono.dev/docs/api/context#executionctx}\n * The ExecutionContext associated with the current request.\n *\n * @throws Will throw an error if the context does not have an ExecutionContext.\n */\n get executionCtx() {\n if (this.#executionCtx) {\n return this.#executionCtx;\n } else {\n throw Error(\"This context has no ExecutionContext\");\n }\n }\n /**\n * @see {@link https://hono.dev/docs/api/context#res}\n * The Response object for the current request.\n */\n get res() {\n return this.#res ||= createResponseInstance(null, {\n headers: this.#preparedHeaders ??= new Headers()\n });\n }\n /**\n * Sets the Response object for the current request.\n *\n * @param _res - The Response object to set.\n */\n set res(_res) {\n if (this.#res && _res) {\n _res = createResponseInstance(_res.body, _res);\n for (const [k, v] of this.#res.headers.entries()) {\n if (k === \"content-type\") {\n continue;\n }\n if (k === \"set-cookie\") {\n const cookies = this.#res.headers.getSetCookie();\n _res.headers.delete(\"set-cookie\");\n for (const cookie of cookies) {\n _res.headers.append(\"set-cookie\", cookie);\n }\n } else {\n _res.headers.set(k, v);\n }\n }\n }\n this.#res = _res;\n this.finalized = true;\n }\n /**\n * `.render()` can create a response within a layout.\n *\n * @see {@link https://hono.dev/docs/api/context#render-setrenderer}\n *\n * @example\n * ```ts\n * app.get('/', (c) => {\n * return c.render('Hello!')\n * })\n * ```\n */\n render = (...args) => {\n this.#renderer ??= (content) => this.html(content);\n return this.#renderer(...args);\n };\n /**\n * Sets the layout for the response.\n *\n * @param layout - The layout to set.\n * @returns The layout function.\n */\n setLayout = (layout) => this.#layout = layout;\n /**\n * Gets the current layout for the response.\n *\n * @returns The current layout function.\n */\n getLayout = () => this.#layout;\n /**\n * `.setRenderer()` can set the layout in the custom middleware.\n *\n * @see {@link https://hono.dev/docs/api/context#render-setrenderer}\n *\n * @example\n * ```tsx\n * app.use('*', async (c, next) => {\n * c.setRenderer((content) => {\n * return c.html(\n * \n * \n *

{content}

\n * \n * \n * )\n * })\n * await next()\n * })\n * ```\n */\n setRenderer = (renderer) => {\n this.#renderer = renderer;\n };\n /**\n * `.header()` can set headers.\n *\n * @see {@link https://hono.dev/docs/api/context#header}\n *\n * @example\n * ```ts\n * app.get('/welcome', (c) => {\n * // Set headers\n * c.header('X-Message', 'Hello!')\n * c.header('Content-Type', 'text/plain')\n *\n * return c.body('Thank you for coming')\n * })\n * ```\n */\n header = (name, value, options) => {\n if (this.finalized) {\n this.#res = createResponseInstance(this.#res.body, this.#res);\n }\n const headers = this.#res ? this.#res.headers : this.#preparedHeaders ??= new Headers();\n if (value === void 0) {\n headers.delete(name);\n } else if (options?.append) {\n headers.append(name, value);\n } else {\n headers.set(name, value);\n }\n };\n status = (status) => {\n this.#status = status;\n };\n /**\n * `.set()` can set the value specified by the key.\n *\n * @see {@link https://hono.dev/docs/api/context#set-get}\n *\n * @example\n * ```ts\n * app.use('*', async (c, next) => {\n * c.set('message', 'Hono is hot!!')\n * await next()\n * })\n * ```\n */\n set = (key, value) => {\n this.#var ??= /* @__PURE__ */ new Map();\n this.#var.set(key, value);\n };\n /**\n * `.get()` can use the value specified by the key.\n *\n * @see {@link https://hono.dev/docs/api/context#set-get}\n *\n * @example\n * ```ts\n * app.get('/', (c) => {\n * const message = c.get('message')\n * return c.text(`The message is \"${message}\"`)\n * })\n * ```\n */\n get = (key) => {\n return this.#var ? this.#var.get(key) : void 0;\n };\n /**\n * `.var` can access the value of a variable.\n *\n * @see {@link https://hono.dev/docs/api/context#var}\n *\n * @example\n * ```ts\n * const result = c.var.client.oneMethod()\n * ```\n */\n // c.var.propName is a read-only\n get var() {\n if (!this.#var) {\n return {};\n }\n return Object.fromEntries(this.#var);\n }\n #newResponse(data, arg, headers) {\n const responseHeaders = this.#res ? new Headers(this.#res.headers) : this.#preparedHeaders ?? new Headers();\n if (typeof arg === \"object\" && \"headers\" in arg) {\n const argHeaders = arg.headers instanceof Headers ? arg.headers : new Headers(arg.headers);\n for (const [key, value] of argHeaders) {\n if (key.toLowerCase() === \"set-cookie\") {\n responseHeaders.append(key, value);\n } else {\n responseHeaders.set(key, value);\n }\n }\n }\n if (headers) {\n for (const [k, v] of Object.entries(headers)) {\n if (typeof v === \"string\") {\n responseHeaders.set(k, v);\n } else {\n responseHeaders.delete(k);\n for (const v2 of v) {\n responseHeaders.append(k, v2);\n }\n }\n }\n }\n const status = typeof arg === \"number\" ? arg : arg?.status ?? this.#status;\n return createResponseInstance(data, { status, headers: responseHeaders });\n }\n newResponse = (...args) => this.#newResponse(...args);\n /**\n * `.body()` can return the HTTP response.\n * You can set headers with `.header()` and set HTTP status code with `.status`.\n * This can also be set in `.text()`, `.json()` and so on.\n *\n * @see {@link https://hono.dev/docs/api/context#body}\n *\n * @example\n * ```ts\n * app.get('/welcome', (c) => {\n * // Set headers\n * c.header('X-Message', 'Hello!')\n * c.header('Content-Type', 'text/plain')\n * // Set HTTP status code\n * c.status(201)\n *\n * // Return the response body\n * return c.body('Thank you for coming')\n * })\n * ```\n */\n body = (data, arg, headers) => this.#newResponse(data, arg, headers);\n /**\n * `.text()` can render text as `Content-Type:text/plain`.\n *\n * @see {@link https://hono.dev/docs/api/context#text}\n *\n * @example\n * ```ts\n * app.get('/say', (c) => {\n * return c.text('Hello!')\n * })\n * ```\n */\n text = (text, arg, headers) => {\n return !this.#preparedHeaders && !this.#status && !arg && !headers && !this.finalized ? new Response(text) : this.#newResponse(\n text,\n arg,\n setDefaultContentType(TEXT_PLAIN, headers)\n );\n };\n /**\n * `.json()` can render JSON as `Content-Type:application/json`.\n *\n * @see {@link https://hono.dev/docs/api/context#json}\n *\n * @example\n * ```ts\n * app.get('/api', (c) => {\n * return c.json({ message: 'Hello!' })\n * })\n * ```\n */\n json = (object, arg, headers) => {\n return this.#newResponse(\n JSON.stringify(object),\n arg,\n setDefaultContentType(\"application/json\", headers)\n );\n };\n html = (html, arg, headers) => {\n const res = (html2) => this.#newResponse(html2, arg, setDefaultContentType(\"text/html; charset=UTF-8\", headers));\n return typeof html === \"object\" ? resolveCallback(html, HtmlEscapedCallbackPhase.Stringify, false, {}).then(res) : res(html);\n };\n /**\n * `.redirect()` can Redirect, default status code is 302.\n *\n * @see {@link https://hono.dev/docs/api/context#redirect}\n *\n * @example\n * ```ts\n * app.get('/redirect', (c) => {\n * return c.redirect('/')\n * })\n * app.get('/redirect-permanently', (c) => {\n * return c.redirect('/', 301)\n * })\n * ```\n */\n redirect = (location, status) => {\n const locationString = String(location);\n this.header(\n \"Location\",\n // Multibyes should be encoded\n // eslint-disable-next-line no-control-regex\n !/[^\\x00-\\xFF]/.test(locationString) ? locationString : encodeURI(locationString)\n );\n return this.newResponse(null, status ?? 302);\n };\n /**\n * `.notFound()` can return the Not Found Response.\n *\n * @see {@link https://hono.dev/docs/api/context#notfound}\n *\n * @example\n * ```ts\n * app.get('/notfound', (c) => {\n * return c.notFound()\n * })\n * ```\n */\n notFound = () => {\n this.#notFoundHandler ??= () => createResponseInstance();\n return this.#notFoundHandler(this);\n };\n};\nexport {\n Context,\n TEXT_PLAIN\n};\n", "// src/request.ts\nimport { HTTPException } from \"./http-exception.js\";\nimport { GET_MATCH_RESULT } from \"./request/constants.js\";\nimport { parseBody } from \"./utils/body.js\";\nimport { decodeURIComponent_, getQueryParam, getQueryParams, tryDecode } from \"./utils/url.js\";\nvar tryDecodeURIComponent = (str) => tryDecode(str, decodeURIComponent_);\nvar HonoRequest = class {\n /**\n * `.raw` can get the raw Request object.\n *\n * @see {@link https://hono.dev/docs/api/request#raw}\n *\n * @example\n * ```ts\n * // For Cloudflare Workers\n * app.post('/', async (c) => {\n * const metadata = c.req.raw.cf?.hostMetadata?\n * ...\n * })\n * ```\n */\n raw;\n #validatedData;\n // Short name of validatedData\n #matchResult;\n routeIndex = 0;\n /**\n * `.path` can get the pathname of the request.\n *\n * @see {@link https://hono.dev/docs/api/request#path}\n *\n * @example\n * ```ts\n * app.get('/about/me', (c) => {\n * const pathname = c.req.path // `/about/me`\n * })\n * ```\n */\n path;\n bodyCache = {};\n constructor(request, path = \"/\", matchResult = [[]]) {\n this.raw = request;\n this.path = path;\n this.#matchResult = matchResult;\n this.#validatedData = {};\n }\n param(key) {\n return key ? this.#getDecodedParam(key) : this.#getAllDecodedParams();\n }\n #getDecodedParam(key) {\n const paramKey = this.#matchResult[0][this.routeIndex][1][key];\n const param = this.#getParamValue(paramKey);\n return param && /\\%/.test(param) ? tryDecodeURIComponent(param) : param;\n }\n #getAllDecodedParams() {\n const decoded = {};\n const keys = Object.keys(this.#matchResult[0][this.routeIndex][1]);\n for (const key of keys) {\n const value = this.#getParamValue(this.#matchResult[0][this.routeIndex][1][key]);\n if (value !== void 0) {\n decoded[key] = /\\%/.test(value) ? tryDecodeURIComponent(value) : value;\n }\n }\n return decoded;\n }\n #getParamValue(paramKey) {\n return this.#matchResult[1] ? this.#matchResult[1][paramKey] : paramKey;\n }\n query(key) {\n return getQueryParam(this.url, key);\n }\n queries(key) {\n return getQueryParams(this.url, key);\n }\n header(name) {\n if (name) {\n return this.raw.headers.get(name) ?? void 0;\n }\n const headerData = {};\n this.raw.headers.forEach((value, key) => {\n headerData[key] = value;\n });\n return headerData;\n }\n async parseBody(options) {\n return this.bodyCache.parsedBody ??= await parseBody(this, options);\n }\n #cachedBody = (key) => {\n const { bodyCache, raw } = this;\n const cachedBody = bodyCache[key];\n if (cachedBody) {\n return cachedBody;\n }\n const anyCachedKey = Object.keys(bodyCache)[0];\n if (anyCachedKey) {\n return bodyCache[anyCachedKey].then((body) => {\n if (anyCachedKey === \"json\") {\n body = JSON.stringify(body);\n }\n return new Response(body)[key]();\n });\n }\n return bodyCache[key] = raw[key]();\n };\n /**\n * `.json()` can parse Request body of type `application/json`\n *\n * @see {@link https://hono.dev/docs/api/request#json}\n *\n * @example\n * ```ts\n * app.post('/entry', async (c) => {\n * const body = await c.req.json()\n * })\n * ```\n */\n json() {\n return this.#cachedBody(\"text\").then((text) => JSON.parse(text));\n }\n /**\n * `.text()` can parse Request body of type `text/plain`\n *\n * @see {@link https://hono.dev/docs/api/request#text}\n *\n * @example\n * ```ts\n * app.post('/entry', async (c) => {\n * const body = await c.req.text()\n * })\n * ```\n */\n text() {\n return this.#cachedBody(\"text\");\n }\n /**\n * `.arrayBuffer()` parse Request body as an `ArrayBuffer`\n *\n * @see {@link https://hono.dev/docs/api/request#arraybuffer}\n *\n * @example\n * ```ts\n * app.post('/entry', async (c) => {\n * const body = await c.req.arrayBuffer()\n * })\n * ```\n */\n arrayBuffer() {\n return this.#cachedBody(\"arrayBuffer\");\n }\n /**\n * Parses the request body as a `Blob`.\n * @example\n * ```ts\n * app.post('/entry', async (c) => {\n * const body = await c.req.blob();\n * });\n * ```\n * @see https://hono.dev/docs/api/request#blob\n */\n blob() {\n return this.#cachedBody(\"blob\");\n }\n /**\n * Parses the request body as `FormData`.\n * @example\n * ```ts\n * app.post('/entry', async (c) => {\n * const body = await c.req.formData();\n * });\n * ```\n * @see https://hono.dev/docs/api/request#formdata\n */\n formData() {\n return this.#cachedBody(\"formData\");\n }\n /**\n * Adds validated data to the request.\n *\n * @param target - The target of the validation.\n * @param data - The validated data to add.\n */\n addValidatedData(target, data) {\n this.#validatedData[target] = data;\n }\n valid(target) {\n return this.#validatedData[target];\n }\n /**\n * `.url()` can get the request url strings.\n *\n * @see {@link https://hono.dev/docs/api/request#url}\n *\n * @example\n * ```ts\n * app.get('/about/me', (c) => {\n * const url = c.req.url // `http://localhost:8787/about/me`\n * ...\n * })\n * ```\n */\n get url() {\n return this.raw.url;\n }\n /**\n * `.method()` can get the method name of the request.\n *\n * @see {@link https://hono.dev/docs/api/request#method}\n *\n * @example\n * ```ts\n * app.get('/about/me', (c) => {\n * const method = c.req.method // `GET`\n * })\n * ```\n */\n get method() {\n return this.raw.method;\n }\n get [GET_MATCH_RESULT]() {\n return this.#matchResult;\n }\n /**\n * `.matchedRoutes()` can return a matched route in the handler\n *\n * @deprecated\n *\n * Use matchedRoutes helper defined in \"hono/route\" instead.\n *\n * @see {@link https://hono.dev/docs/api/request#matchedroutes}\n *\n * @example\n * ```ts\n * app.use('*', async function logger(c, next) {\n * await next()\n * c.req.matchedRoutes.forEach(({ handler, method, path }, i) => {\n * const name = handler.name || (handler.length < 2 ? '[handler]' : '[middleware]')\n * console.log(\n * method,\n * ' ',\n * path,\n * ' '.repeat(Math.max(10 - path.length, 0)),\n * name,\n * i === c.req.routeIndex ? '<- respond from here' : ''\n * )\n * })\n * })\n * ```\n */\n get matchedRoutes() {\n return this.#matchResult[0].map(([[, route]]) => route);\n }\n /**\n * `routePath()` can retrieve the path registered within the handler\n *\n * @deprecated\n *\n * Use routePath helper defined in \"hono/route\" instead.\n *\n * @see {@link https://hono.dev/docs/api/request#routepath}\n *\n * @example\n * ```ts\n * app.get('/posts/:id', (c) => {\n * return c.json({ path: c.req.routePath })\n * })\n * ```\n */\n get routePath() {\n return this.#matchResult[0].map(([[, route]]) => route)[this.routeIndex].path;\n }\n};\nvar cloneRawRequest = async (req) => {\n if (!req.raw.bodyUsed) {\n return req.raw.clone();\n }\n const cacheKey = Object.keys(req.bodyCache)[0];\n if (!cacheKey) {\n throw new HTTPException(500, {\n message: \"Cannot clone request: body was already consumed and not cached. Please use HonoRequest methods (e.g., req.json(), req.text()) instead of consuming req.raw directly.\"\n });\n }\n const requestInit = {\n body: await req[cacheKey](),\n cache: req.raw.cache,\n credentials: req.raw.credentials,\n headers: req.header(),\n integrity: req.raw.integrity,\n keepalive: req.raw.keepalive,\n method: req.method,\n mode: req.raw.mode,\n redirect: req.raw.redirect,\n referrer: req.raw.referrer,\n referrerPolicy: req.raw.referrerPolicy,\n signal: req.raw.signal\n };\n return new Request(req.url, requestInit);\n};\nexport {\n HonoRequest,\n cloneRawRequest\n};\n", "// src/http-exception.ts\nvar HTTPException = class extends Error {\n res;\n status;\n /**\n * Creates an instance of `HTTPException`.\n * @param status - HTTP status code for the exception. Defaults to 500.\n * @param options - Additional options for the exception.\n */\n constructor(status = 500, options) {\n super(options?.message, { cause: options?.cause });\n this.res = options?.res;\n this.status = status;\n }\n /**\n * Returns the response object associated with the exception.\n * If a response object is not provided, a new response is created with the error message and status code.\n * @returns The response object.\n */\n getResponse() {\n if (this.res) {\n const newResponse = new Response(this.res.body, {\n status: this.status,\n headers: this.res.headers\n });\n return newResponse;\n }\n return new Response(this.message, {\n status: this.status\n });\n }\n};\nexport {\n HTTPException\n};\n", "// src/request/constants.ts\nvar GET_MATCH_RESULT = /* @__PURE__ */ Symbol();\nexport {\n GET_MATCH_RESULT\n};\n", "// src/utils/body.ts\nimport { HonoRequest } from \"../request.js\";\nvar parseBody = async (request, options = /* @__PURE__ */ Object.create(null)) => {\n const { all = false, dot = false } = options;\n const headers = request instanceof HonoRequest ? request.raw.headers : request.headers;\n const contentType = headers.get(\"Content-Type\");\n if (contentType?.startsWith(\"multipart/form-data\") || contentType?.startsWith(\"application/x-www-form-urlencoded\")) {\n return parseFormData(request, { all, dot });\n }\n return {};\n};\nasync function parseFormData(request, options) {\n const formData = await request.formData();\n if (formData) {\n return convertFormDataToBodyData(formData, options);\n }\n return {};\n}\nfunction convertFormDataToBodyData(formData, options) {\n const form = /* @__PURE__ */ Object.create(null);\n formData.forEach((value, key) => {\n const shouldParseAllValues = options.all || key.endsWith(\"[]\");\n if (!shouldParseAllValues) {\n form[key] = value;\n } else {\n handleParsingAllValues(form, key, value);\n }\n });\n if (options.dot) {\n Object.entries(form).forEach(([key, value]) => {\n const shouldParseDotValues = key.includes(\".\");\n if (shouldParseDotValues) {\n handleParsingNestedValues(form, key, value);\n delete form[key];\n }\n });\n }\n return form;\n}\nvar handleParsingAllValues = (form, key, value) => {\n if (form[key] !== void 0) {\n if (Array.isArray(form[key])) {\n ;\n form[key].push(value);\n } else {\n form[key] = [form[key], value];\n }\n } else {\n if (!key.endsWith(\"[]\")) {\n form[key] = value;\n } else {\n form[key] = [value];\n }\n }\n};\nvar handleParsingNestedValues = (form, key, value) => {\n let nestedForm = form;\n const keys = key.split(\".\");\n keys.forEach((key2, index) => {\n if (index === keys.length - 1) {\n nestedForm[key2] = value;\n } else {\n if (!nestedForm[key2] || typeof nestedForm[key2] !== \"object\" || Array.isArray(nestedForm[key2]) || nestedForm[key2] instanceof File) {\n nestedForm[key2] = /* @__PURE__ */ Object.create(null);\n }\n nestedForm = nestedForm[key2];\n }\n });\n};\nexport {\n parseBody\n};\n", "// src/utils/url.ts\nvar splitPath = (path) => {\n const paths = path.split(\"/\");\n if (paths[0] === \"\") {\n paths.shift();\n }\n return paths;\n};\nvar splitRoutingPath = (routePath) => {\n const { groups, path } = extractGroupsFromPath(routePath);\n const paths = splitPath(path);\n return replaceGroupMarks(paths, groups);\n};\nvar extractGroupsFromPath = (path) => {\n const groups = [];\n path = path.replace(/\\{[^}]+\\}/g, (match, index) => {\n const mark = `@${index}`;\n groups.push([mark, match]);\n return mark;\n });\n return { groups, path };\n};\nvar replaceGroupMarks = (paths, groups) => {\n for (let i = groups.length - 1; i >= 0; i--) {\n const [mark] = groups[i];\n for (let j = paths.length - 1; j >= 0; j--) {\n if (paths[j].includes(mark)) {\n paths[j] = paths[j].replace(mark, groups[i][1]);\n break;\n }\n }\n }\n return paths;\n};\nvar patternCache = {};\nvar getPattern = (label, next) => {\n if (label === \"*\") {\n return \"*\";\n }\n const match = label.match(/^\\:([^\\{\\}]+)(?:\\{(.+)\\})?$/);\n if (match) {\n const cacheKey = `${label}#${next}`;\n if (!patternCache[cacheKey]) {\n if (match[2]) {\n patternCache[cacheKey] = next && next[0] !== \":\" && next[0] !== \"*\" ? [cacheKey, match[1], new RegExp(`^${match[2]}(?=/${next})`)] : [label, match[1], new RegExp(`^${match[2]}$`)];\n } else {\n patternCache[cacheKey] = [label, match[1], true];\n }\n }\n return patternCache[cacheKey];\n }\n return null;\n};\nvar tryDecode = (str, decoder) => {\n try {\n return decoder(str);\n } catch {\n return str.replace(/(?:%[0-9A-Fa-f]{2})+/g, (match) => {\n try {\n return decoder(match);\n } catch {\n return match;\n }\n });\n }\n};\nvar tryDecodeURI = (str) => tryDecode(str, decodeURI);\nvar getPath = (request) => {\n const url = request.url;\n const start = url.indexOf(\"/\", url.indexOf(\":\") + 4);\n let i = start;\n for (; i < url.length; i++) {\n const charCode = url.charCodeAt(i);\n if (charCode === 37) {\n const queryIndex = url.indexOf(\"?\", i);\n const hashIndex = url.indexOf(\"#\", i);\n const end = queryIndex === -1 ? hashIndex === -1 ? void 0 : hashIndex : hashIndex === -1 ? queryIndex : Math.min(queryIndex, hashIndex);\n const path = url.slice(start, end);\n return tryDecodeURI(path.includes(\"%25\") ? path.replace(/%25/g, \"%2525\") : path);\n } else if (charCode === 63 || charCode === 35) {\n break;\n }\n }\n return url.slice(start, i);\n};\nvar getQueryStrings = (url) => {\n const queryIndex = url.indexOf(\"?\", 8);\n return queryIndex === -1 ? \"\" : \"?\" + url.slice(queryIndex + 1);\n};\nvar getPathNoStrict = (request) => {\n const result = getPath(request);\n return result.length > 1 && result.at(-1) === \"/\" ? result.slice(0, -1) : result;\n};\nvar mergePath = (base, sub, ...rest) => {\n if (rest.length) {\n sub = mergePath(sub, ...rest);\n }\n return `${base?.[0] === \"/\" ? \"\" : \"/\"}${base}${sub === \"/\" ? \"\" : `${base?.at(-1) === \"/\" ? \"\" : \"/\"}${sub?.[0] === \"/\" ? sub.slice(1) : sub}`}`;\n};\nvar checkOptionalParameter = (path) => {\n if (path.charCodeAt(path.length - 1) !== 63 || !path.includes(\":\")) {\n return null;\n }\n const segments = path.split(\"/\");\n const results = [];\n let basePath = \"\";\n segments.forEach((segment) => {\n if (segment !== \"\" && !/\\:/.test(segment)) {\n basePath += \"/\" + segment;\n } else if (/\\:/.test(segment)) {\n if (/\\?/.test(segment)) {\n if (results.length === 0 && basePath === \"\") {\n results.push(\"/\");\n } else {\n results.push(basePath);\n }\n const optionalSegment = segment.replace(\"?\", \"\");\n basePath += \"/\" + optionalSegment;\n results.push(basePath);\n } else {\n basePath += \"/\" + segment;\n }\n }\n });\n return results.filter((v, i, a) => a.indexOf(v) === i);\n};\nvar _decodeURI = (value) => {\n if (!/[%+]/.test(value)) {\n return value;\n }\n if (value.indexOf(\"+\") !== -1) {\n value = value.replace(/\\+/g, \" \");\n }\n return value.indexOf(\"%\") !== -1 ? tryDecode(value, decodeURIComponent_) : value;\n};\nvar _getQueryParam = (url, key, multiple) => {\n let encoded;\n if (!multiple && key && !/[%+]/.test(key)) {\n let keyIndex2 = url.indexOf(\"?\", 8);\n if (keyIndex2 === -1) {\n return void 0;\n }\n if (!url.startsWith(key, keyIndex2 + 1)) {\n keyIndex2 = url.indexOf(`&${key}`, keyIndex2 + 1);\n }\n while (keyIndex2 !== -1) {\n const trailingKeyCode = url.charCodeAt(keyIndex2 + key.length + 1);\n if (trailingKeyCode === 61) {\n const valueIndex = keyIndex2 + key.length + 2;\n const endIndex = url.indexOf(\"&\", valueIndex);\n return _decodeURI(url.slice(valueIndex, endIndex === -1 ? void 0 : endIndex));\n } else if (trailingKeyCode == 38 || isNaN(trailingKeyCode)) {\n return \"\";\n }\n keyIndex2 = url.indexOf(`&${key}`, keyIndex2 + 1);\n }\n encoded = /[%+]/.test(url);\n if (!encoded) {\n return void 0;\n }\n }\n const results = {};\n encoded ??= /[%+]/.test(url);\n let keyIndex = url.indexOf(\"?\", 8);\n while (keyIndex !== -1) {\n const nextKeyIndex = url.indexOf(\"&\", keyIndex + 1);\n let valueIndex = url.indexOf(\"=\", keyIndex);\n if (valueIndex > nextKeyIndex && nextKeyIndex !== -1) {\n valueIndex = -1;\n }\n let name = url.slice(\n keyIndex + 1,\n valueIndex === -1 ? nextKeyIndex === -1 ? void 0 : nextKeyIndex : valueIndex\n );\n if (encoded) {\n name = _decodeURI(name);\n }\n keyIndex = nextKeyIndex;\n if (name === \"\") {\n continue;\n }\n let value;\n if (valueIndex === -1) {\n value = \"\";\n } else {\n value = url.slice(valueIndex + 1, nextKeyIndex === -1 ? void 0 : nextKeyIndex);\n if (encoded) {\n value = _decodeURI(value);\n }\n }\n if (multiple) {\n if (!(results[name] && Array.isArray(results[name]))) {\n results[name] = [];\n }\n ;\n results[name].push(value);\n } else {\n results[name] ??= value;\n }\n }\n return key ? results[key] : results;\n};\nvar getQueryParam = _getQueryParam;\nvar getQueryParams = (url, key) => {\n return _getQueryParam(url, key, true);\n};\nvar decodeURIComponent_ = decodeURIComponent;\nexport {\n checkOptionalParameter,\n decodeURIComponent_,\n getPath,\n getPathNoStrict,\n getPattern,\n getQueryParam,\n getQueryParams,\n getQueryStrings,\n mergePath,\n splitPath,\n splitRoutingPath,\n tryDecode,\n tryDecodeURI\n};\n", "// src/utils/html.ts\nvar HtmlEscapedCallbackPhase = {\n Stringify: 1,\n BeforeStream: 2,\n Stream: 3\n};\nvar raw = (value, callbacks) => {\n const escapedString = new String(value);\n escapedString.isEscaped = true;\n escapedString.callbacks = callbacks;\n return escapedString;\n};\nvar escapeRe = /[&<>'\"]/;\nvar stringBufferToString = async (buffer, callbacks) => {\n let str = \"\";\n callbacks ||= [];\n const resolvedBuffer = await Promise.all(buffer);\n for (let i = resolvedBuffer.length - 1; ; i--) {\n str += resolvedBuffer[i];\n i--;\n if (i < 0) {\n break;\n }\n let r = resolvedBuffer[i];\n if (typeof r === \"object\") {\n callbacks.push(...r.callbacks || []);\n }\n const isEscaped = r.isEscaped;\n r = await (typeof r === \"object\" ? r.toString() : r);\n if (typeof r === \"object\") {\n callbacks.push(...r.callbacks || []);\n }\n if (r.isEscaped ?? isEscaped) {\n str += r;\n } else {\n const buf = [str];\n escapeToBuffer(r, buf);\n str = buf[0];\n }\n }\n return raw(str, callbacks);\n};\nvar escapeToBuffer = (str, buffer) => {\n const match = str.search(escapeRe);\n if (match === -1) {\n buffer[0] += str;\n return;\n }\n let escape;\n let index;\n let lastIndex = 0;\n for (index = match; index < str.length; index++) {\n switch (str.charCodeAt(index)) {\n case 34:\n escape = \""\";\n break;\n case 39:\n escape = \"'\";\n break;\n case 38:\n escape = \"&\";\n break;\n case 60:\n escape = \"<\";\n break;\n case 62:\n escape = \">\";\n break;\n default:\n continue;\n }\n buffer[0] += str.substring(lastIndex, index) + escape;\n lastIndex = index + 1;\n }\n buffer[0] += str.substring(lastIndex, index);\n};\nvar resolveCallbackSync = (str) => {\n const callbacks = str.callbacks;\n if (!callbacks?.length) {\n return str;\n }\n const buffer = [str];\n const context = {};\n callbacks.forEach((c) => c({ phase: HtmlEscapedCallbackPhase.Stringify, buffer, context }));\n return buffer[0];\n};\nvar resolveCallback = async (str, phase, preserveCallbacks, context, buffer) => {\n if (typeof str === \"object\" && !(str instanceof String)) {\n if (!(str instanceof Promise)) {\n str = str.toString();\n }\n if (str instanceof Promise) {\n str = await str;\n }\n }\n const callbacks = str.callbacks;\n if (!callbacks?.length) {\n return Promise.resolve(str);\n }\n if (buffer) {\n buffer[0] += str;\n } else {\n buffer = [str];\n }\n const resStr = Promise.all(callbacks.map((c) => c({ phase, buffer, context }))).then(\n (res) => Promise.all(\n res.filter(Boolean).map((str2) => resolveCallback(str2, phase, false, context, buffer))\n ).then(() => buffer[0])\n );\n if (preserveCallbacks) {\n return raw(await resStr, callbacks);\n } else {\n return resStr;\n }\n};\nexport {\n HtmlEscapedCallbackPhase,\n escapeToBuffer,\n raw,\n resolveCallback,\n resolveCallbackSync,\n stringBufferToString\n};\n", "// src/router.ts\nvar METHOD_NAME_ALL = \"ALL\";\nvar METHOD_NAME_ALL_LOWERCASE = \"all\";\nvar METHODS = [\"get\", \"post\", \"put\", \"delete\", \"options\", \"patch\"];\nvar MESSAGE_MATCHER_IS_ALREADY_BUILT = \"Can not add a route since the matcher is already built.\";\nvar UnsupportedPathError = class extends Error {\n};\nexport {\n MESSAGE_MATCHER_IS_ALREADY_BUILT,\n METHODS,\n METHOD_NAME_ALL,\n METHOD_NAME_ALL_LOWERCASE,\n UnsupportedPathError\n};\n", "// src/utils/constants.ts\nvar COMPOSED_HANDLER = \"__COMPOSED_HANDLER\";\nexport {\n COMPOSED_HANDLER\n};\n", "// src/router/reg-exp-router/index.ts\nimport { RegExpRouter } from \"./router.js\";\nimport { PreparedRegExpRouter, buildInitParams, serializeInitParams } from \"./prepared-router.js\";\nexport {\n PreparedRegExpRouter,\n RegExpRouter,\n buildInitParams,\n serializeInitParams\n};\n", "// src/router/reg-exp-router/router.ts\nimport {\n MESSAGE_MATCHER_IS_ALREADY_BUILT,\n METHOD_NAME_ALL,\n UnsupportedPathError\n} from \"../../router.js\";\nimport { checkOptionalParameter } from \"../../utils/url.js\";\nimport { match, emptyParam } from \"./matcher.js\";\nimport { PATH_ERROR } from \"./node.js\";\nimport { Trie } from \"./trie.js\";\nvar nullMatcher = [/^$/, [], /* @__PURE__ */ Object.create(null)];\nvar wildcardRegExpCache = /* @__PURE__ */ Object.create(null);\nfunction buildWildcardRegExp(path) {\n return wildcardRegExpCache[path] ??= new RegExp(\n path === \"*\" ? \"\" : `^${path.replace(\n /\\/\\*$|([.\\\\+*[^\\]$()])/g,\n (_, metaChar) => metaChar ? `\\\\${metaChar}` : \"(?:|/.*)\"\n )}$`\n );\n}\nfunction clearWildcardRegExpCache() {\n wildcardRegExpCache = /* @__PURE__ */ Object.create(null);\n}\nfunction buildMatcherFromPreprocessedRoutes(routes) {\n const trie = new Trie();\n const handlerData = [];\n if (routes.length === 0) {\n return nullMatcher;\n }\n const routesWithStaticPathFlag = routes.map(\n (route) => [!/\\*|\\/:/.test(route[0]), ...route]\n ).sort(\n ([isStaticA, pathA], [isStaticB, pathB]) => isStaticA ? 1 : isStaticB ? -1 : pathA.length - pathB.length\n );\n const staticMap = /* @__PURE__ */ Object.create(null);\n for (let i = 0, j = -1, len = routesWithStaticPathFlag.length; i < len; i++) {\n const [pathErrorCheckOnly, path, handlers] = routesWithStaticPathFlag[i];\n if (pathErrorCheckOnly) {\n staticMap[path] = [handlers.map(([h]) => [h, /* @__PURE__ */ Object.create(null)]), emptyParam];\n } else {\n j++;\n }\n let paramAssoc;\n try {\n paramAssoc = trie.insert(path, j, pathErrorCheckOnly);\n } catch (e) {\n throw e === PATH_ERROR ? new UnsupportedPathError(path) : e;\n }\n if (pathErrorCheckOnly) {\n continue;\n }\n handlerData[j] = handlers.map(([h, paramCount]) => {\n const paramIndexMap = /* @__PURE__ */ Object.create(null);\n paramCount -= 1;\n for (; paramCount >= 0; paramCount--) {\n const [key, value] = paramAssoc[paramCount];\n paramIndexMap[key] = value;\n }\n return [h, paramIndexMap];\n });\n }\n const [regexp, indexReplacementMap, paramReplacementMap] = trie.buildRegExp();\n for (let i = 0, len = handlerData.length; i < len; i++) {\n for (let j = 0, len2 = handlerData[i].length; j < len2; j++) {\n const map = handlerData[i][j]?.[1];\n if (!map) {\n continue;\n }\n const keys = Object.keys(map);\n for (let k = 0, len3 = keys.length; k < len3; k++) {\n map[keys[k]] = paramReplacementMap[map[keys[k]]];\n }\n }\n }\n const handlerMap = [];\n for (const i in indexReplacementMap) {\n handlerMap[i] = handlerData[indexReplacementMap[i]];\n }\n return [regexp, handlerMap, staticMap];\n}\nfunction findMiddleware(middleware, path) {\n if (!middleware) {\n return void 0;\n }\n for (const k of Object.keys(middleware).sort((a, b) => b.length - a.length)) {\n if (buildWildcardRegExp(k).test(path)) {\n return [...middleware[k]];\n }\n }\n return void 0;\n}\nvar RegExpRouter = class {\n name = \"RegExpRouter\";\n #middleware;\n #routes;\n constructor() {\n this.#middleware = { [METHOD_NAME_ALL]: /* @__PURE__ */ Object.create(null) };\n this.#routes = { [METHOD_NAME_ALL]: /* @__PURE__ */ Object.create(null) };\n }\n add(method, path, handler) {\n const middleware = this.#middleware;\n const routes = this.#routes;\n if (!middleware || !routes) {\n throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);\n }\n if (!middleware[method]) {\n ;\n [middleware, routes].forEach((handlerMap) => {\n handlerMap[method] = /* @__PURE__ */ Object.create(null);\n Object.keys(handlerMap[METHOD_NAME_ALL]).forEach((p) => {\n handlerMap[method][p] = [...handlerMap[METHOD_NAME_ALL][p]];\n });\n });\n }\n if (path === \"/*\") {\n path = \"*\";\n }\n const paramCount = (path.match(/\\/:/g) || []).length;\n if (/\\*$/.test(path)) {\n const re = buildWildcardRegExp(path);\n if (method === METHOD_NAME_ALL) {\n Object.keys(middleware).forEach((m) => {\n middleware[m][path] ||= findMiddleware(middleware[m], path) || findMiddleware(middleware[METHOD_NAME_ALL], path) || [];\n });\n } else {\n middleware[method][path] ||= findMiddleware(middleware[method], path) || findMiddleware(middleware[METHOD_NAME_ALL], path) || [];\n }\n Object.keys(middleware).forEach((m) => {\n if (method === METHOD_NAME_ALL || method === m) {\n Object.keys(middleware[m]).forEach((p) => {\n re.test(p) && middleware[m][p].push([handler, paramCount]);\n });\n }\n });\n Object.keys(routes).forEach((m) => {\n if (method === METHOD_NAME_ALL || method === m) {\n Object.keys(routes[m]).forEach(\n (p) => re.test(p) && routes[m][p].push([handler, paramCount])\n );\n }\n });\n return;\n }\n const paths = checkOptionalParameter(path) || [path];\n for (let i = 0, len = paths.length; i < len; i++) {\n const path2 = paths[i];\n Object.keys(routes).forEach((m) => {\n if (method === METHOD_NAME_ALL || method === m) {\n routes[m][path2] ||= [\n ...findMiddleware(middleware[m], path2) || findMiddleware(middleware[METHOD_NAME_ALL], path2) || []\n ];\n routes[m][path2].push([handler, paramCount - len + i + 1]);\n }\n });\n }\n }\n match = match;\n buildAllMatchers() {\n const matchers = /* @__PURE__ */ Object.create(null);\n Object.keys(this.#routes).concat(Object.keys(this.#middleware)).forEach((method) => {\n matchers[method] ||= this.#buildMatcher(method);\n });\n this.#middleware = this.#routes = void 0;\n clearWildcardRegExpCache();\n return matchers;\n }\n #buildMatcher(method) {\n const routes = [];\n let hasOwnRoute = method === METHOD_NAME_ALL;\n [this.#middleware, this.#routes].forEach((r) => {\n const ownRoute = r[method] ? Object.keys(r[method]).map((path) => [path, r[method][path]]) : [];\n if (ownRoute.length !== 0) {\n hasOwnRoute ||= true;\n routes.push(...ownRoute);\n } else if (method !== METHOD_NAME_ALL) {\n routes.push(\n ...Object.keys(r[METHOD_NAME_ALL]).map((path) => [path, r[METHOD_NAME_ALL][path]])\n );\n }\n });\n if (!hasOwnRoute) {\n return null;\n } else {\n return buildMatcherFromPreprocessedRoutes(routes);\n }\n }\n};\nexport {\n RegExpRouter\n};\n", "// src/router/reg-exp-router/matcher.ts\nimport { METHOD_NAME_ALL } from \"../../router.js\";\nvar emptyParam = [];\nfunction match(method, path) {\n const matchers = this.buildAllMatchers();\n const match2 = ((method2, path2) => {\n const matcher = matchers[method2] || matchers[METHOD_NAME_ALL];\n const staticMatch = matcher[2][path2];\n if (staticMatch) {\n return staticMatch;\n }\n const match3 = path2.match(matcher[0]);\n if (!match3) {\n return [[], emptyParam];\n }\n const index = match3.indexOf(\"\", 1);\n return [matcher[1][index], match3];\n });\n this.match = match2;\n return match2(method, path);\n}\nexport {\n emptyParam,\n match\n};\n", "// src/router/reg-exp-router/node.ts\nvar LABEL_REG_EXP_STR = \"[^/]+\";\nvar ONLY_WILDCARD_REG_EXP_STR = \".*\";\nvar TAIL_WILDCARD_REG_EXP_STR = \"(?:|/.*)\";\nvar PATH_ERROR = /* @__PURE__ */ Symbol();\nvar regExpMetaChars = new Set(\".\\\\+*[^]$()\");\nfunction compareKey(a, b) {\n if (a.length === 1) {\n return b.length === 1 ? a < b ? -1 : 1 : -1;\n }\n if (b.length === 1) {\n return 1;\n }\n if (a === ONLY_WILDCARD_REG_EXP_STR || a === TAIL_WILDCARD_REG_EXP_STR) {\n return 1;\n } else if (b === ONLY_WILDCARD_REG_EXP_STR || b === TAIL_WILDCARD_REG_EXP_STR) {\n return -1;\n }\n if (a === LABEL_REG_EXP_STR) {\n return 1;\n } else if (b === LABEL_REG_EXP_STR) {\n return -1;\n }\n return a.length === b.length ? a < b ? -1 : 1 : b.length - a.length;\n}\nvar Node = class _Node {\n #index;\n #varIndex;\n #children = /* @__PURE__ */ Object.create(null);\n insert(tokens, index, paramMap, context, pathErrorCheckOnly) {\n if (tokens.length === 0) {\n if (this.#index !== void 0) {\n throw PATH_ERROR;\n }\n if (pathErrorCheckOnly) {\n return;\n }\n this.#index = index;\n return;\n }\n const [token, ...restTokens] = tokens;\n const pattern = token === \"*\" ? restTokens.length === 0 ? [\"\", \"\", ONLY_WILDCARD_REG_EXP_STR] : [\"\", \"\", LABEL_REG_EXP_STR] : token === \"/*\" ? [\"\", \"\", TAIL_WILDCARD_REG_EXP_STR] : token.match(/^\\:([^\\{\\}]+)(?:\\{(.+)\\})?$/);\n let node;\n if (pattern) {\n const name = pattern[1];\n let regexpStr = pattern[2] || LABEL_REG_EXP_STR;\n if (name && pattern[2]) {\n if (regexpStr === \".*\") {\n throw PATH_ERROR;\n }\n regexpStr = regexpStr.replace(/^\\((?!\\?:)(?=[^)]+\\)$)/, \"(?:\");\n if (/\\((?!\\?:)/.test(regexpStr)) {\n throw PATH_ERROR;\n }\n }\n node = this.#children[regexpStr];\n if (!node) {\n if (Object.keys(this.#children).some(\n (k) => k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR\n )) {\n throw PATH_ERROR;\n }\n if (pathErrorCheckOnly) {\n return;\n }\n node = this.#children[regexpStr] = new _Node();\n if (name !== \"\") {\n node.#varIndex = context.varIndex++;\n }\n }\n if (!pathErrorCheckOnly && name !== \"\") {\n paramMap.push([name, node.#varIndex]);\n }\n } else {\n node = this.#children[token];\n if (!node) {\n if (Object.keys(this.#children).some(\n (k) => k.length > 1 && k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR\n )) {\n throw PATH_ERROR;\n }\n if (pathErrorCheckOnly) {\n return;\n }\n node = this.#children[token] = new _Node();\n }\n }\n node.insert(restTokens, index, paramMap, context, pathErrorCheckOnly);\n }\n buildRegExpStr() {\n const childKeys = Object.keys(this.#children).sort(compareKey);\n const strList = childKeys.map((k) => {\n const c = this.#children[k];\n return (typeof c.#varIndex === \"number\" ? `(${k})@${c.#varIndex}` : regExpMetaChars.has(k) ? `\\\\${k}` : k) + c.buildRegExpStr();\n });\n if (typeof this.#index === \"number\") {\n strList.unshift(`#${this.#index}`);\n }\n if (strList.length === 0) {\n return \"\";\n }\n if (strList.length === 1) {\n return strList[0];\n }\n return \"(?:\" + strList.join(\"|\") + \")\";\n }\n};\nexport {\n Node,\n PATH_ERROR\n};\n", "// src/router/reg-exp-router/trie.ts\nimport { Node } from \"./node.js\";\nvar Trie = class {\n #context = { varIndex: 0 };\n #root = new Node();\n insert(path, index, pathErrorCheckOnly) {\n const paramAssoc = [];\n const groups = [];\n for (let i = 0; ; ) {\n let replaced = false;\n path = path.replace(/\\{[^}]+\\}/g, (m) => {\n const mark = `@\\\\${i}`;\n groups[i] = [mark, m];\n i++;\n replaced = true;\n return mark;\n });\n if (!replaced) {\n break;\n }\n }\n const tokens = path.match(/(?::[^\\/]+)|(?:\\/\\*$)|./g) || [];\n for (let i = groups.length - 1; i >= 0; i--) {\n const [mark] = groups[i];\n for (let j = tokens.length - 1; j >= 0; j--) {\n if (tokens[j].indexOf(mark) !== -1) {\n tokens[j] = tokens[j].replace(mark, groups[i][1]);\n break;\n }\n }\n }\n this.#root.insert(tokens, index, paramAssoc, this.#context, pathErrorCheckOnly);\n return paramAssoc;\n }\n buildRegExp() {\n let regexp = this.#root.buildRegExpStr();\n if (regexp === \"\") {\n return [/^$/, [], []];\n }\n let captureIndex = 0;\n const indexReplacementMap = [];\n const paramReplacementMap = [];\n regexp = regexp.replace(/#(\\d+)|@(\\d+)|\\.\\*\\$/g, (_, handlerIndex, paramIndex) => {\n if (handlerIndex !== void 0) {\n indexReplacementMap[++captureIndex] = Number(handlerIndex);\n return \"$()\";\n }\n if (paramIndex !== void 0) {\n paramReplacementMap[Number(paramIndex)] = ++captureIndex;\n return \"\";\n }\n return \"\";\n });\n return [new RegExp(`^${regexp}`), indexReplacementMap, paramReplacementMap];\n }\n};\nexport {\n Trie\n};\n", "// src/router/reg-exp-router/prepared-router.ts\nimport { METHOD_NAME_ALL } from \"../../router.js\";\nimport { match, emptyParam } from \"./matcher.js\";\nimport { RegExpRouter } from \"./router.js\";\nvar PreparedRegExpRouter = class {\n name = \"PreparedRegExpRouter\";\n #matchers;\n #relocateMap;\n constructor(matchers, relocateMap) {\n this.#matchers = matchers;\n this.#relocateMap = relocateMap;\n }\n #addWildcard(method, handlerData) {\n const matcher = this.#matchers[method];\n matcher[1].forEach((list) => list && list.push(handlerData));\n Object.values(matcher[2]).forEach((list) => list[0].push(handlerData));\n }\n #addPath(method, path, handler, indexes, map) {\n const matcher = this.#matchers[method];\n if (!map) {\n matcher[2][path][0].push([handler, {}]);\n } else {\n indexes.forEach((index) => {\n if (typeof index === \"number\") {\n matcher[1][index].push([handler, map]);\n } else {\n ;\n matcher[2][index || path][0].push([handler, map]);\n }\n });\n }\n }\n add(method, path, handler) {\n if (!this.#matchers[method]) {\n const all = this.#matchers[METHOD_NAME_ALL];\n const staticMap = {};\n for (const key in all[2]) {\n staticMap[key] = [all[2][key][0].slice(), emptyParam];\n }\n this.#matchers[method] = [\n all[0],\n all[1].map((list) => Array.isArray(list) ? list.slice() : 0),\n staticMap\n ];\n }\n if (path === \"/*\" || path === \"*\") {\n const handlerData = [handler, {}];\n if (method === METHOD_NAME_ALL) {\n for (const m in this.#matchers) {\n this.#addWildcard(m, handlerData);\n }\n } else {\n this.#addWildcard(method, handlerData);\n }\n return;\n }\n const data = this.#relocateMap[path];\n if (!data) {\n throw new Error(`Path ${path} is not registered`);\n }\n for (const [indexes, map] of data) {\n if (method === METHOD_NAME_ALL) {\n for (const m in this.#matchers) {\n this.#addPath(m, path, handler, indexes, map);\n }\n } else {\n this.#addPath(method, path, handler, indexes, map);\n }\n }\n }\n buildAllMatchers() {\n return this.#matchers;\n }\n match = match;\n};\nvar buildInitParams = ({ paths }) => {\n const RegExpRouterWithMatcherExport = class extends RegExpRouter {\n buildAndExportAllMatchers() {\n return this.buildAllMatchers();\n }\n };\n const router = new RegExpRouterWithMatcherExport();\n for (const path of paths) {\n router.add(METHOD_NAME_ALL, path, path);\n }\n const matchers = router.buildAndExportAllMatchers();\n const all = matchers[METHOD_NAME_ALL];\n const relocateMap = {};\n for (const path of paths) {\n if (path === \"/*\" || path === \"*\") {\n continue;\n }\n all[1].forEach((list, i) => {\n list.forEach(([p, map]) => {\n if (p === path) {\n if (relocateMap[path]) {\n relocateMap[path][0][1] = {\n ...relocateMap[path][0][1],\n ...map\n };\n } else {\n relocateMap[path] = [[[], map]];\n }\n if (relocateMap[path][0][0].findIndex((j) => j === i) === -1) {\n relocateMap[path][0][0].push(i);\n }\n }\n });\n });\n for (const path2 in all[2]) {\n all[2][path2][0].forEach(([p]) => {\n if (p === path) {\n relocateMap[path] ||= [[[]]];\n const value = path2 === path ? \"\" : path2;\n if (relocateMap[path][0][0].findIndex((v) => v === value) === -1) {\n relocateMap[path][0][0].push(value);\n }\n }\n });\n }\n }\n for (let i = 0, len = all[1].length; i < len; i++) {\n all[1][i] = all[1][i] ? [] : 0;\n }\n for (const path in all[2]) {\n all[2][path][0] = [];\n }\n return [matchers, relocateMap];\n};\nvar serializeInitParams = ([matchers, relocateMap]) => {\n const matchersStr = JSON.stringify(\n matchers,\n (_, value) => value instanceof RegExp ? `##${value.toString()}##` : value\n ).replace(/\"##(.+?)##\"/g, (_, str) => str.replace(/\\\\\\\\/g, \"\\\\\"));\n const relocateMapStr = JSON.stringify(relocateMap);\n return `[${matchersStr},${relocateMapStr}]`;\n};\nexport {\n PreparedRegExpRouter,\n buildInitParams,\n serializeInitParams\n};\n", "// src/router/smart-router/index.ts\nimport { SmartRouter } from \"./router.js\";\nexport {\n SmartRouter\n};\n", "// src/router/smart-router/router.ts\nimport { MESSAGE_MATCHER_IS_ALREADY_BUILT, UnsupportedPathError } from \"../../router.js\";\nvar SmartRouter = class {\n name = \"SmartRouter\";\n #routers = [];\n #routes = [];\n constructor(init) {\n this.#routers = init.routers;\n }\n add(method, path, handler) {\n if (!this.#routes) {\n throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);\n }\n this.#routes.push([method, path, handler]);\n }\n match(method, path) {\n if (!this.#routes) {\n throw new Error(\"Fatal error\");\n }\n const routers = this.#routers;\n const routes = this.#routes;\n const len = routers.length;\n let i = 0;\n let res;\n for (; i < len; i++) {\n const router = routers[i];\n try {\n for (let i2 = 0, len2 = routes.length; i2 < len2; i2++) {\n router.add(...routes[i2]);\n }\n res = router.match(method, path);\n } catch (e) {\n if (e instanceof UnsupportedPathError) {\n continue;\n }\n throw e;\n }\n this.match = router.match.bind(router);\n this.#routers = [router];\n this.#routes = void 0;\n break;\n }\n if (i === len) {\n throw new Error(\"Fatal error\");\n }\n this.name = `SmartRouter + ${this.activeRouter.name}`;\n return res;\n }\n get activeRouter() {\n if (this.#routes || this.#routers.length !== 1) {\n throw new Error(\"No active router has been determined yet.\");\n }\n return this.#routers[0];\n }\n};\nexport {\n SmartRouter\n};\n", "// src/router/trie-router/index.ts\nimport { TrieRouter } from \"./router.js\";\nexport {\n TrieRouter\n};\n", "// src/router/trie-router/router.ts\nimport { checkOptionalParameter } from \"../../utils/url.js\";\nimport { Node } from \"./node.js\";\nvar TrieRouter = class {\n name = \"TrieRouter\";\n #node;\n constructor() {\n this.#node = new Node();\n }\n add(method, path, handler) {\n const results = checkOptionalParameter(path);\n if (results) {\n for (let i = 0, len = results.length; i < len; i++) {\n this.#node.insert(method, results[i], handler);\n }\n return;\n }\n this.#node.insert(method, path, handler);\n }\n match(method, path) {\n return this.#node.search(method, path);\n }\n};\nexport {\n TrieRouter\n};\n", "// src/router/trie-router/node.ts\nimport { METHOD_NAME_ALL } from \"../../router.js\";\nimport { getPattern, splitPath, splitRoutingPath } from \"../../utils/url.js\";\nvar emptyParams = /* @__PURE__ */ Object.create(null);\nvar hasChildren = (children) => {\n for (const _ in children) {\n return true;\n }\n return false;\n};\nvar Node = class _Node {\n #methods;\n #children;\n #patterns;\n #order = 0;\n #params = emptyParams;\n constructor(method, handler, children) {\n this.#children = children || /* @__PURE__ */ Object.create(null);\n this.#methods = [];\n if (method && handler) {\n const m = /* @__PURE__ */ Object.create(null);\n m[method] = { handler, possibleKeys: [], score: 0 };\n this.#methods = [m];\n }\n this.#patterns = [];\n }\n insert(method, path, handler) {\n this.#order = ++this.#order;\n let curNode = this;\n const parts = splitRoutingPath(path);\n const possibleKeys = [];\n for (let i = 0, len = parts.length; i < len; i++) {\n const p = parts[i];\n const nextP = parts[i + 1];\n const pattern = getPattern(p, nextP);\n const key = Array.isArray(pattern) ? pattern[0] : p;\n if (key in curNode.#children) {\n curNode = curNode.#children[key];\n if (pattern) {\n possibleKeys.push(pattern[1]);\n }\n continue;\n }\n curNode.#children[key] = new _Node();\n if (pattern) {\n curNode.#patterns.push(pattern);\n possibleKeys.push(pattern[1]);\n }\n curNode = curNode.#children[key];\n }\n curNode.#methods.push({\n [method]: {\n handler,\n possibleKeys: possibleKeys.filter((v, i, a) => a.indexOf(v) === i),\n score: this.#order\n }\n });\n return curNode;\n }\n #pushHandlerSets(handlerSets, node, method, nodeParams, params) {\n for (let i = 0, len = node.#methods.length; i < len; i++) {\n const m = node.#methods[i];\n const handlerSet = m[method] || m[METHOD_NAME_ALL];\n const processedSet = {};\n if (handlerSet !== void 0) {\n handlerSet.params = /* @__PURE__ */ Object.create(null);\n handlerSets.push(handlerSet);\n if (nodeParams !== emptyParams || params && params !== emptyParams) {\n for (let i2 = 0, len2 = handlerSet.possibleKeys.length; i2 < len2; i2++) {\n const key = handlerSet.possibleKeys[i2];\n const processed = processedSet[handlerSet.score];\n handlerSet.params[key] = params?.[key] && !processed ? params[key] : nodeParams[key] ?? params?.[key];\n processedSet[handlerSet.score] = true;\n }\n }\n }\n }\n }\n search(method, path) {\n const handlerSets = [];\n this.#params = emptyParams;\n const curNode = this;\n let curNodes = [curNode];\n const parts = splitPath(path);\n const curNodesQueue = [];\n const len = parts.length;\n let partOffsets = null;\n for (let i = 0; i < len; i++) {\n const part = parts[i];\n const isLast = i === len - 1;\n const tempNodes = [];\n for (let j = 0, len2 = curNodes.length; j < len2; j++) {\n const node = curNodes[j];\n const nextNode = node.#children[part];\n if (nextNode) {\n nextNode.#params = node.#params;\n if (isLast) {\n if (nextNode.#children[\"*\"]) {\n this.#pushHandlerSets(handlerSets, nextNode.#children[\"*\"], method, node.#params);\n }\n this.#pushHandlerSets(handlerSets, nextNode, method, node.#params);\n } else {\n tempNodes.push(nextNode);\n }\n }\n for (let k = 0, len3 = node.#patterns.length; k < len3; k++) {\n const pattern = node.#patterns[k];\n const params = node.#params === emptyParams ? {} : { ...node.#params };\n if (pattern === \"*\") {\n const astNode = node.#children[\"*\"];\n if (astNode) {\n this.#pushHandlerSets(handlerSets, astNode, method, node.#params);\n astNode.#params = params;\n tempNodes.push(astNode);\n }\n continue;\n }\n const [key, name, matcher] = pattern;\n if (!part && !(matcher instanceof RegExp)) {\n continue;\n }\n const child = node.#children[key];\n if (matcher instanceof RegExp) {\n if (partOffsets === null) {\n partOffsets = new Array(len);\n let offset = path[0] === \"/\" ? 1 : 0;\n for (let p = 0; p < len; p++) {\n partOffsets[p] = offset;\n offset += parts[p].length + 1;\n }\n }\n const restPathString = path.substring(partOffsets[i]);\n const m = matcher.exec(restPathString);\n if (m) {\n params[name] = m[0];\n this.#pushHandlerSets(handlerSets, child, method, node.#params, params);\n if (hasChildren(child.#children)) {\n child.#params = params;\n const componentCount = m[0].match(/\\//)?.length ?? 0;\n const targetCurNodes = curNodesQueue[componentCount] ||= [];\n targetCurNodes.push(child);\n }\n continue;\n }\n }\n if (matcher === true || matcher.test(part)) {\n params[name] = part;\n if (isLast) {\n this.#pushHandlerSets(handlerSets, child, method, params, node.#params);\n if (child.#children[\"*\"]) {\n this.#pushHandlerSets(\n handlerSets,\n child.#children[\"*\"],\n method,\n params,\n node.#params\n );\n }\n } else {\n child.#params = params;\n tempNodes.push(child);\n }\n }\n }\n }\n const shifted = curNodesQueue.shift();\n curNodes = shifted ? tempNodes.concat(shifted) : tempNodes;\n }\n if (handlerSets.length > 1) {\n handlerSets.sort((a, b) => {\n return a.score - b.score;\n });\n }\n return [handlerSets.map(({ handler, params }) => [handler, params])];\n }\n};\nexport {\n Node\n};\n", "const filterQueryCache = new Map();\nfunction matchFilter(filter) {\n const queries = Array.isArray(filter) ? filter : [\n filter\n ];\n const key = queries.join(\",\");\n const predicate = filterQueryCache.get(key) ?? (()=>{\n const parsed = parse(queries);\n const pred = compile(parsed);\n filterQueryCache.set(key, pred);\n return pred;\n })();\n return (ctx)=>predicate(ctx);\n}\nfunction parse(filter) {\n return Array.isArray(filter) ? filter.map((q)=>q.split(\":\")) : [\n filter.split(\":\")\n ];\n}\nfunction compile(parsed) {\n const preprocessed = parsed.flatMap((q)=>check(q, preprocess(q)));\n const ltree = treeify(preprocessed);\n const predicate = arborist(ltree);\n return (ctx)=>!!predicate(ctx.update, ctx);\n}\nfunction preprocess(filter) {\n const valid = UPDATE_KEYS;\n const expanded = [\n filter\n ].flatMap((q)=>{\n const [l1, l2, l3] = q;\n if (!(l1 in L1_SHORTCUTS)) return [\n q\n ];\n if (!l1 && !l2 && !l3) return [\n q\n ];\n const targets = L1_SHORTCUTS[l1];\n const expanded = targets.map((s)=>[\n s,\n l2,\n l3\n ]);\n if (l2 === undefined) return expanded;\n if (l2 in L2_SHORTCUTS && (l2 || l3)) return expanded;\n return expanded.filter(([s])=>!!valid[s]?.[l2]);\n }).flatMap((q)=>{\n const [l1, l2, l3] = q;\n if (!(l2 in L2_SHORTCUTS)) return [\n q\n ];\n if (!l2 && !l3) return [\n q\n ];\n const targets = L2_SHORTCUTS[l2];\n const expanded = targets.map((s)=>[\n l1,\n s,\n l3\n ]);\n if (l3 === undefined) return expanded;\n return expanded.filter(([, s])=>!!valid[l1]?.[s]?.[l3]);\n });\n if (expanded.length === 0) {\n throw new Error(`Shortcuts in '${filter.join(\":\")}' do not expand to any valid filter query`);\n }\n return expanded;\n}\nfunction check(original, preprocessed) {\n if (preprocessed.length === 0) throw new Error(\"Empty filter query given\");\n const errors = preprocessed.map(checkOne).filter((r)=>r !== true);\n if (errors.length === 0) return preprocessed;\n else if (errors.length === 1) throw new Error(errors[0]);\n else {\n throw new Error(`Invalid filter query '${original.join(\":\")}'. There are ${errors.length} errors after expanding the contained shortcuts: ${errors.join(\"; \")}`);\n }\n}\nfunction checkOne(filter) {\n const [l1, l2, l3, ...n] = filter;\n if (l1 === undefined) return \"Empty filter query given\";\n if (!(l1 in UPDATE_KEYS)) {\n const permitted = Object.keys(UPDATE_KEYS);\n return `Invalid L1 filter '${l1}' given in '${filter.join(\":\")}'. \\\nPermitted values are: ${permitted.map((k)=>`'${k}'`).join(\", \")}.`;\n }\n if (l2 === undefined) return true;\n const l1Obj = UPDATE_KEYS[l1];\n if (!(l2 in l1Obj)) {\n const permitted = Object.keys(l1Obj);\n return `Invalid L2 filter '${l2}' given in '${filter.join(\":\")}'. \\\nPermitted values are: ${permitted.map((k)=>`'${k}'`).join(\", \")}.`;\n }\n if (l3 === undefined) return true;\n const l2Obj = l1Obj[l2];\n if (!(l3 in l2Obj)) {\n const permitted = Object.keys(l2Obj);\n return `Invalid L3 filter '${l3}' given in '${filter.join(\":\")}'. ${permitted.length === 0 ? `No further filtering is possible after '${l1}:${l2}'.` : `Permitted values are: ${permitted.map((k)=>`'${k}'`).join(\", \")}.`}`;\n }\n if (n.length === 0) return true;\n return `Cannot filter further than three levels, ':${n.join(\":\")}' is invalid!`;\n}\nfunction treeify(paths) {\n const tree = {};\n for (const [l1, l2, l3] of paths){\n const subtree = tree[l1] ??= {};\n if (l2 !== undefined) {\n const set = subtree[l2] ??= new Set();\n if (l3 !== undefined) set.add(l3);\n }\n }\n return tree;\n}\nfunction or(left, right) {\n return (obj, ctx)=>left(obj, ctx) || right(obj, ctx);\n}\nfunction concat(get, test) {\n return (obj, ctx)=>{\n const nextObj = get(obj, ctx);\n return nextObj && test(nextObj, ctx);\n };\n}\nfunction leaf(pred) {\n return (obj, ctx)=>pred(obj, ctx) != null;\n}\nfunction arborist(tree) {\n const l1Predicates = Object.entries(tree).map(([l1, subtree])=>{\n const l1Pred = (obj)=>obj[l1];\n const l2Predicates = Object.entries(subtree).map(([l2, set])=>{\n const l2Pred = (obj)=>obj[l2];\n const l3Predicates = Array.from(set).map((l3)=>{\n const l3Pred = l3 === \"me\" ? (obj, ctx)=>{\n const me = ctx.me.id;\n return testMaybeArray(obj, (u)=>u.id === me);\n } : (obj)=>testMaybeArray(obj, (e)=>e[l3] || e.type === l3);\n return l3Pred;\n });\n return l3Predicates.length === 0 ? leaf(l2Pred) : concat(l2Pred, l3Predicates.reduce(or));\n });\n return l2Predicates.length === 0 ? leaf(l1Pred) : concat(l1Pred, l2Predicates.reduce(or));\n });\n if (l1Predicates.length === 0) {\n throw new Error(\"Cannot create filter function for empty query\");\n }\n return l1Predicates.reduce(or);\n}\nfunction testMaybeArray(t, pred) {\n const p = (x)=>x != null && pred(x);\n return Array.isArray(t) ? t.some(p) : p(t);\n}\nconst ENTITY_KEYS = {\n mention: {},\n hashtag: {},\n cashtag: {},\n bot_command: {},\n url: {},\n email: {},\n phone_number: {},\n bold: {},\n italic: {},\n underline: {},\n strikethrough: {},\n spoiler: {},\n blockquote: {},\n expandable_blockquote: {},\n code: {},\n pre: {},\n text_link: {},\n text_mention: {},\n custom_emoji: {}\n};\nconst USER_KEYS = {\n me: {},\n is_bot: {},\n is_premium: {},\n added_to_attachment_menu: {}\n};\nconst FORWARD_ORIGIN_KEYS = {\n user: {},\n hidden_user: {},\n chat: {},\n channel: {}\n};\nconst STICKER_KEYS = {\n is_video: {},\n is_animated: {},\n premium_animation: {}\n};\nconst REACTION_KEYS = {\n emoji: {},\n custom_emoji: {},\n paid: {}\n};\nconst GIFT_INFO_KEYS = {\n can_be_upgraded: {},\n is_upgrade_separate: {},\n is_private: {}\n};\nconst COMMON_MESSAGE_KEYS = {\n forward_origin: FORWARD_ORIGIN_KEYS,\n is_topic_message: {},\n is_automatic_forward: {},\n business_connection_id: {},\n text: {},\n animation: {},\n audio: {},\n document: {},\n paid_media: {},\n photo: {},\n sticker: STICKER_KEYS,\n story: {},\n video: {},\n video_note: {},\n voice: {},\n contact: {},\n dice: {},\n game: {},\n poll: {},\n venue: {},\n location: {},\n entities: ENTITY_KEYS,\n caption_entities: ENTITY_KEYS,\n caption: {},\n link_preview_options: {\n url: {},\n prefer_small_media: {},\n prefer_large_media: {},\n show_above_text: {}\n },\n effect_id: {},\n paid_star_count: {},\n has_media_spoiler: {},\n new_chat_title: {},\n new_chat_photo: {},\n delete_chat_photo: {},\n message_auto_delete_timer_changed: {},\n pinned_message: {},\n invoice: {},\n proximity_alert_triggered: {},\n chat_background_set: {},\n giveaway_created: {},\n giveaway: {\n only_new_members: {},\n has_public_winners: {}\n },\n giveaway_winners: {\n only_new_members: {},\n was_refunded: {}\n },\n giveaway_completed: {},\n gift: GIFT_INFO_KEYS,\n gift_upgrade_sent: GIFT_INFO_KEYS,\n unique_gift: {\n transfer_star_count: {}\n },\n paid_message_price_changed: {},\n video_chat_scheduled: {},\n video_chat_started: {},\n video_chat_ended: {},\n video_chat_participants_invited: {},\n web_app_data: {}\n};\nconst MESSAGE_KEYS = {\n ...COMMON_MESSAGE_KEYS,\n direct_messages_topic: {},\n chat_owner_left: {\n new_owner: {}\n },\n chat_owner_changd: {},\n new_chat_members: USER_KEYS,\n left_chat_member: USER_KEYS,\n group_chat_created: {},\n supergroup_chat_created: {},\n migrate_to_chat_id: {},\n migrate_from_chat_id: {},\n successful_payment: {},\n refunded_payment: {},\n users_shared: {},\n chat_shared: {},\n connected_website: {},\n write_access_allowed: {},\n passport_data: {},\n boost_added: {},\n forum_topic_created: {\n is_name_implicit: {}\n },\n forum_topic_edited: {\n name: {},\n icon_custom_emoji_id: {}\n },\n forum_topic_closed: {},\n forum_topic_reopened: {},\n general_forum_topic_hidden: {},\n general_forum_topic_unhidden: {},\n checklist: {\n others_can_add_tasks: {},\n others_can_mark_tasks_as_done: {}\n },\n checklist_tasks_done: {},\n checklist_tasks_added: {},\n suggested_post_info: {},\n suggested_post_approved: {},\n suggested_post_approval_failed: {},\n suggested_post_declined: {},\n suggested_post_paid: {},\n suggested_post_refunded: {},\n sender_boost_count: {}\n};\nconst CHANNEL_POST_KEYS = {\n ...COMMON_MESSAGE_KEYS,\n channel_chat_created: {},\n direct_message_price_changed: {},\n is_paid_post: {}\n};\nconst BUSINESS_CONNECTION_KEYS = {\n can_reply: {},\n is_enabled: {}\n};\nconst MESSAGE_REACTION_KEYS = {\n old_reaction: REACTION_KEYS,\n new_reaction: REACTION_KEYS\n};\nconst MESSAGE_REACTION_COUNT_UPDATED_KEYS = {\n reactions: REACTION_KEYS\n};\nconst CALLBACK_QUERY_KEYS = {\n data: {},\n game_short_name: {}\n};\nconst CHAT_MEMBER_UPDATED_KEYS = {\n from: USER_KEYS\n};\nconst UPDATE_KEYS = {\n message: MESSAGE_KEYS,\n edited_message: MESSAGE_KEYS,\n channel_post: CHANNEL_POST_KEYS,\n edited_channel_post: CHANNEL_POST_KEYS,\n business_connection: BUSINESS_CONNECTION_KEYS,\n business_message: MESSAGE_KEYS,\n edited_business_message: MESSAGE_KEYS,\n deleted_business_messages: {},\n inline_query: {},\n chosen_inline_result: {},\n callback_query: CALLBACK_QUERY_KEYS,\n shipping_query: {},\n pre_checkout_query: {},\n poll: {},\n poll_answer: {},\n my_chat_member: CHAT_MEMBER_UPDATED_KEYS,\n chat_member: CHAT_MEMBER_UPDATED_KEYS,\n chat_join_request: {},\n message_reaction: MESSAGE_REACTION_KEYS,\n message_reaction_count: MESSAGE_REACTION_COUNT_UPDATED_KEYS,\n chat_boost: {},\n removed_chat_boost: {},\n purchased_paid_media: {}\n};\nconst L1_SHORTCUTS = {\n \"\": [\n \"message\",\n \"channel_post\"\n ],\n msg: [\n \"message\",\n \"channel_post\"\n ],\n edit: [\n \"edited_message\",\n \"edited_channel_post\"\n ]\n};\nconst L2_SHORTCUTS = {\n \"\": [\n \"entities\",\n \"caption_entities\"\n ],\n media: [\n \"photo\",\n \"video\"\n ],\n file: [\n \"photo\",\n \"animation\",\n \"audio\",\n \"document\",\n \"video\",\n \"video_note\",\n \"voice\",\n \"sticker\"\n ]\n};\nconst checker = {\n filterQuery (filter) {\n const pred = matchFilter(filter);\n return (ctx)=>pred(ctx);\n },\n text (trigger) {\n const hasText = checker.filterQuery([\n \":text\",\n \":caption\"\n ]);\n const trg = triggerFn(trigger);\n return (ctx)=>{\n if (!hasText(ctx)) return false;\n const msg = ctx.message ?? ctx.channelPost;\n const txt = msg.text ?? msg.caption;\n return match(ctx, txt, trg);\n };\n },\n command (command) {\n const hasEntities = checker.filterQuery(\":entities:bot_command\");\n const atCommands = new Set();\n const noAtCommands = new Set();\n toArray(command).forEach((cmd)=>{\n if (cmd.startsWith(\"/\")) {\n throw new Error(`Do not include '/' when registering command handlers (use '${cmd.substring(1)}' not '${cmd}')`);\n }\n const set = cmd.includes(\"@\") ? atCommands : noAtCommands;\n set.add(cmd);\n });\n return (ctx)=>{\n if (!hasEntities(ctx)) return false;\n const msg = ctx.message ?? ctx.channelPost;\n const txt = msg.text ?? msg.caption;\n return msg.entities.some((e)=>{\n if (e.type !== \"bot_command\") return false;\n if (e.offset !== 0) return false;\n const cmd = txt.substring(1, e.length);\n if (noAtCommands.has(cmd) || atCommands.has(cmd)) {\n ctx.match = txt.substring(cmd.length + 1).trimStart();\n return true;\n }\n const index = cmd.indexOf(\"@\");\n if (index === -1) return false;\n const atTarget = cmd.substring(index + 1).toLowerCase();\n const username = ctx.me.username.toLowerCase();\n if (atTarget !== username) return false;\n const atCommand = cmd.substring(0, index);\n if (noAtCommands.has(atCommand)) {\n ctx.match = txt.substring(cmd.length + 1).trimStart();\n return true;\n }\n return false;\n });\n };\n },\n reaction (reaction) {\n const hasMessageReaction = checker.filterQuery(\"message_reaction\");\n const normalized = typeof reaction === \"string\" ? [\n {\n type: \"emoji\",\n emoji: reaction\n }\n ] : (Array.isArray(reaction) ? reaction : [\n reaction\n ]).map((emoji)=>typeof emoji === \"string\" ? {\n type: \"emoji\",\n emoji\n } : emoji);\n const emoji = new Set(normalized.filter((r)=>r.type === \"emoji\").map((r)=>r.emoji));\n const customEmoji = new Set(normalized.filter((r)=>r.type === \"custom_emoji\").map((r)=>r.custom_emoji_id));\n const paid = normalized.some((r)=>r.type === \"paid\");\n return (ctx)=>{\n if (!hasMessageReaction(ctx)) return false;\n const { old_reaction, new_reaction } = ctx.messageReaction;\n for (const reaction of new_reaction){\n let isOld = false;\n if (reaction.type === \"emoji\") {\n for (const old of old_reaction){\n if (old.type !== \"emoji\") continue;\n if (old.emoji === reaction.emoji) {\n isOld = true;\n break;\n }\n }\n } else if (reaction.type === \"custom_emoji\") {\n for (const old of old_reaction){\n if (old.type !== \"custom_emoji\") continue;\n if (old.custom_emoji_id === reaction.custom_emoji_id) {\n isOld = true;\n break;\n }\n }\n } else if (reaction.type === \"paid\") {\n for (const old of old_reaction){\n if (old.type !== \"paid\") continue;\n isOld = true;\n break;\n }\n } else {}\n if (isOld) continue;\n if (reaction.type === \"emoji\") {\n if (emoji.has(reaction.emoji)) return true;\n } else if (reaction.type === \"custom_emoji\") {\n if (customEmoji.has(reaction.custom_emoji_id)) return true;\n } else if (reaction.type === \"paid\") {\n if (paid) return true;\n } else {\n return true;\n }\n }\n return false;\n };\n },\n chatType (chatType) {\n const set = new Set(toArray(chatType));\n return (ctx)=>ctx.chat?.type !== undefined && set.has(ctx.chat.type);\n },\n callbackQuery (trigger) {\n const hasCallbackQuery = checker.filterQuery(\"callback_query:data\");\n const trg = triggerFn(trigger);\n return (ctx)=>hasCallbackQuery(ctx) && match(ctx, ctx.callbackQuery.data, trg);\n },\n gameQuery (trigger) {\n const hasGameQuery = checker.filterQuery(\"callback_query:game_short_name\");\n const trg = triggerFn(trigger);\n return (ctx)=>hasGameQuery(ctx) && match(ctx, ctx.callbackQuery.game_short_name, trg);\n },\n inlineQuery (trigger) {\n const hasInlineQuery = checker.filterQuery(\"inline_query\");\n const trg = triggerFn(trigger);\n return (ctx)=>hasInlineQuery(ctx) && match(ctx, ctx.inlineQuery.query, trg);\n },\n chosenInlineResult (trigger) {\n const hasChosenInlineResult = checker.filterQuery(\"chosen_inline_result\");\n const trg = triggerFn(trigger);\n return (ctx)=>hasChosenInlineResult(ctx) && match(ctx, ctx.chosenInlineResult.result_id, trg);\n },\n preCheckoutQuery (trigger) {\n const hasPreCheckoutQuery = checker.filterQuery(\"pre_checkout_query\");\n const trg = triggerFn(trigger);\n return (ctx)=>hasPreCheckoutQuery(ctx) && match(ctx, ctx.preCheckoutQuery.invoice_payload, trg);\n },\n shippingQuery (trigger) {\n const hasShippingQuery = checker.filterQuery(\"shipping_query\");\n const trg = triggerFn(trigger);\n return (ctx)=>hasShippingQuery(ctx) && match(ctx, ctx.shippingQuery.invoice_payload, trg);\n }\n};\nclass Context {\n update;\n api;\n me;\n match;\n constructor(update, api, me){\n this.update = update;\n this.api = api;\n this.me = me;\n }\n get message() {\n return this.update.message;\n }\n get editedMessage() {\n return this.update.edited_message;\n }\n get channelPost() {\n return this.update.channel_post;\n }\n get editedChannelPost() {\n return this.update.edited_channel_post;\n }\n get businessConnection() {\n return this.update.business_connection;\n }\n get businessMessage() {\n return this.update.business_message;\n }\n get editedBusinessMessage() {\n return this.update.edited_business_message;\n }\n get deletedBusinessMessages() {\n return this.update.deleted_business_messages;\n }\n get messageReaction() {\n return this.update.message_reaction;\n }\n get messageReactionCount() {\n return this.update.message_reaction_count;\n }\n get inlineQuery() {\n return this.update.inline_query;\n }\n get chosenInlineResult() {\n return this.update.chosen_inline_result;\n }\n get callbackQuery() {\n return this.update.callback_query;\n }\n get shippingQuery() {\n return this.update.shipping_query;\n }\n get preCheckoutQuery() {\n return this.update.pre_checkout_query;\n }\n get poll() {\n return this.update.poll;\n }\n get pollAnswer() {\n return this.update.poll_answer;\n }\n get myChatMember() {\n return this.update.my_chat_member;\n }\n get chatMember() {\n return this.update.chat_member;\n }\n get chatJoinRequest() {\n return this.update.chat_join_request;\n }\n get chatBoost() {\n return this.update.chat_boost;\n }\n get removedChatBoost() {\n return this.update.removed_chat_boost;\n }\n get purchasedPaidMedia() {\n return this.update.purchased_paid_media;\n }\n get msg() {\n return this.message ?? this.editedMessage ?? this.channelPost ?? this.editedChannelPost ?? this.businessMessage ?? this.editedBusinessMessage ?? this.callbackQuery?.message;\n }\n get chat() {\n return (this.msg ?? this.deletedBusinessMessages ?? this.messageReaction ?? this.messageReactionCount ?? this.myChatMember ?? this.chatMember ?? this.chatJoinRequest ?? this.chatBoost ?? this.removedChatBoost)?.chat;\n }\n get senderChat() {\n return this.msg?.sender_chat;\n }\n get from() {\n return (this.businessConnection ?? this.messageReaction ?? (this.chatBoost?.boost ?? this.removedChatBoost)?.source)?.user ?? (this.callbackQuery ?? this.msg ?? this.inlineQuery ?? this.chosenInlineResult ?? this.shippingQuery ?? this.preCheckoutQuery ?? this.myChatMember ?? this.chatMember ?? this.chatJoinRequest ?? this.purchasedPaidMedia)?.from;\n }\n get msgId() {\n return this.msg?.message_id ?? this.messageReaction?.message_id ?? this.messageReactionCount?.message_id;\n }\n get chatId() {\n return this.chat?.id ?? this.businessConnection?.user_chat_id;\n }\n get inlineMessageId() {\n return this.callbackQuery?.inline_message_id ?? this.chosenInlineResult?.inline_message_id;\n }\n get businessConnectionId() {\n return this.msg?.business_connection_id ?? this.businessConnection?.id ?? this.deletedBusinessMessages?.business_connection_id;\n }\n entities(types) {\n const message = this.msg;\n if (message === undefined) return [];\n const text = message.text ?? message.caption;\n if (text === undefined) return [];\n let entities = message.entities ?? message.caption_entities;\n if (entities === undefined) return [];\n if (types !== undefined) {\n const filters = new Set(toArray(types));\n entities = entities.filter((entity)=>filters.has(entity.type));\n }\n return entities.map((entity)=>({\n ...entity,\n text: text.substring(entity.offset, entity.offset + entity.length)\n }));\n }\n reactions() {\n const emoji = [];\n const emojiAdded = [];\n const emojiKept = [];\n const emojiRemoved = [];\n const customEmoji = [];\n const customEmojiAdded = [];\n const customEmojiKept = [];\n const customEmojiRemoved = [];\n let paid = false;\n let paidAdded = false;\n const r = this.messageReaction;\n if (r !== undefined) {\n const { old_reaction, new_reaction } = r;\n for (const reaction of new_reaction){\n if (reaction.type === \"emoji\") {\n emoji.push(reaction.emoji);\n } else if (reaction.type === \"custom_emoji\") {\n customEmoji.push(reaction.custom_emoji_id);\n } else if (reaction.type === \"paid\") {\n paid = paidAdded = true;\n }\n }\n for (const reaction of old_reaction){\n if (reaction.type === \"emoji\") {\n emojiRemoved.push(reaction.emoji);\n } else if (reaction.type === \"custom_emoji\") {\n customEmojiRemoved.push(reaction.custom_emoji_id);\n } else if (reaction.type === \"paid\") {\n paidAdded = false;\n }\n }\n emojiAdded.push(...emoji);\n customEmojiAdded.push(...customEmoji);\n for(let i = 0; i < emojiRemoved.length; i++){\n const len = emojiAdded.length;\n if (len === 0) break;\n const rem = emojiRemoved[i];\n for(let j = 0; j < len; j++){\n if (rem === emojiAdded[j]) {\n emojiKept.push(rem);\n emojiRemoved.splice(i, 1);\n emojiAdded.splice(j, 1);\n i--;\n break;\n }\n }\n }\n for(let i = 0; i < customEmojiRemoved.length; i++){\n const len = customEmojiAdded.length;\n if (len === 0) break;\n const rem = customEmojiRemoved[i];\n for(let j = 0; j < len; j++){\n if (rem === customEmojiAdded[j]) {\n customEmojiKept.push(rem);\n customEmojiRemoved.splice(i, 1);\n customEmojiAdded.splice(j, 1);\n i--;\n break;\n }\n }\n }\n }\n return {\n emoji,\n emojiAdded,\n emojiKept,\n emojiRemoved,\n customEmoji,\n customEmojiAdded,\n customEmojiKept,\n customEmojiRemoved,\n paid,\n paidAdded\n };\n }\n static has = checker;\n has(filter) {\n return Context.has.filterQuery(filter)(this);\n }\n hasText(trigger) {\n return Context.has.text(trigger)(this);\n }\n hasCommand(command) {\n return Context.has.command(command)(this);\n }\n hasReaction(reaction) {\n return Context.has.reaction(reaction)(this);\n }\n hasChatType(chatType) {\n return Context.has.chatType(chatType)(this);\n }\n hasCallbackQuery(trigger) {\n return Context.has.callbackQuery(trigger)(this);\n }\n hasGameQuery(trigger) {\n return Context.has.gameQuery(trigger)(this);\n }\n hasInlineQuery(trigger) {\n return Context.has.inlineQuery(trigger)(this);\n }\n hasChosenInlineResult(trigger) {\n return Context.has.chosenInlineResult(trigger)(this);\n }\n hasPreCheckoutQuery(trigger) {\n return Context.has.preCheckoutQuery(trigger)(this);\n }\n hasShippingQuery(trigger) {\n return Context.has.shippingQuery(trigger)(this);\n }\n reply(text, other, signal) {\n const msg = this.msg;\n return this.api.sendMessage(orThrow(this.chatId, \"sendMessage\"), text, {\n business_connection_id: this.businessConnectionId,\n ...msg?.is_topic_message ? {\n message_thread_id: msg.message_thread_id\n } : {},\n direct_messages_topic_id: msg?.direct_messages_topic?.topic_id,\n ...other\n }, signal);\n }\n replyWithDraft(text, other, signal) {\n const msg = this.msg;\n return this.api.sendMessageDraft(orThrow(this.chatId, \"sendMessageDraft\"), this.update.update_id, text, {\n ...msg?.is_topic_message ? {\n message_thread_id: msg?.message_thread_id\n } : {},\n ...other\n }, signal);\n }\n forwardMessage(chat_id, other, signal) {\n const msg = this.msg;\n return this.api.forwardMessage(chat_id, orThrow(this.chatId, \"forwardMessage\"), orThrow(this.msgId, \"forwardMessage\"), {\n direct_messages_topic_id: msg?.direct_messages_topic?.topic_id,\n ...other\n }, signal);\n }\n forwardMessages(chat_id, message_ids, other, signal) {\n const msg = this.msg;\n return this.api.forwardMessages(chat_id, orThrow(this.chatId, \"forwardMessages\"), message_ids, {\n direct_messages_topic_id: msg?.direct_messages_topic?.topic_id,\n ...other\n }, signal);\n }\n copyMessage(chat_id, other, signal) {\n const msg = this.msg;\n return this.api.copyMessage(chat_id, orThrow(this.chatId, \"copyMessage\"), orThrow(this.msgId, \"copyMessage\"), {\n direct_messages_topic_id: msg?.direct_messages_topic?.topic_id,\n ...other\n }, signal);\n }\n copyMessages(chat_id, message_ids, other, signal) {\n const msg = this.msg;\n return this.api.copyMessages(chat_id, orThrow(this.chatId, \"copyMessages\"), message_ids, {\n direct_messages_topic_id: msg?.direct_messages_topic?.topic_id,\n ...other\n }, signal);\n }\n replyWithPhoto(photo, other, signal) {\n const msg = this.msg;\n return this.api.sendPhoto(orThrow(this.chatId, \"sendPhoto\"), photo, {\n business_connection_id: this.businessConnectionId,\n ...msg?.is_topic_message ? {\n message_thread_id: msg.message_thread_id\n } : {},\n direct_messages_topic_id: msg?.direct_messages_topic?.topic_id,\n ...other\n }, signal);\n }\n replyWithAudio(audio, other, signal) {\n const msg = this.msg;\n return this.api.sendAudio(orThrow(this.chatId, \"sendAudio\"), audio, {\n business_connection_id: this.businessConnectionId,\n ...msg?.is_topic_message ? {\n message_thread_id: msg.message_thread_id\n } : {},\n direct_messages_topic_id: msg?.direct_messages_topic?.topic_id,\n ...other\n }, signal);\n }\n replyWithDocument(document1, other, signal) {\n const msg = this.msg;\n return this.api.sendDocument(orThrow(this.chatId, \"sendDocument\"), document1, {\n business_connection_id: this.businessConnectionId,\n ...msg?.is_topic_message ? {\n message_thread_id: msg.message_thread_id\n } : {},\n direct_messages_topic_id: msg?.direct_messages_topic?.topic_id,\n ...other\n }, signal);\n }\n replyWithVideo(video, other, signal) {\n const msg = this.msg;\n return this.api.sendVideo(orThrow(this.chatId, \"sendVideo\"), video, {\n business_connection_id: this.businessConnectionId,\n ...msg?.is_topic_message ? {\n message_thread_id: msg.message_thread_id\n } : {},\n direct_messages_topic_id: msg?.direct_messages_topic?.topic_id,\n ...other\n }, signal);\n }\n replyWithAnimation(animation, other, signal) {\n const msg = this.msg;\n return this.api.sendAnimation(orThrow(this.chatId, \"sendAnimation\"), animation, {\n business_connection_id: this.businessConnectionId,\n ...msg?.is_topic_message ? {\n message_thread_id: msg.message_thread_id\n } : {},\n direct_messages_topic_id: msg?.direct_messages_topic?.topic_id,\n ...other\n }, signal);\n }\n replyWithVoice(voice, other, signal) {\n const msg = this.msg;\n return this.api.sendVoice(orThrow(this.chatId, \"sendVoice\"), voice, {\n business_connection_id: this.businessConnectionId,\n ...msg?.is_topic_message ? {\n message_thread_id: msg.message_thread_id\n } : {},\n direct_messages_topic_id: msg?.direct_messages_topic?.topic_id,\n ...other\n }, signal);\n }\n replyWithVideoNote(video_note, other, signal) {\n const msg = this.msg;\n return this.api.sendVideoNote(orThrow(this.chatId, \"sendVideoNote\"), video_note, {\n business_connection_id: this.businessConnectionId,\n ...msg?.is_topic_message ? {\n message_thread_id: msg.message_thread_id\n } : {},\n direct_messages_topic_id: msg?.direct_messages_topic?.topic_id,\n ...other\n }, signal);\n }\n replyWithMediaGroup(media, other, signal) {\n const msg = this.msg;\n return this.api.sendMediaGroup(orThrow(this.chatId, \"sendMediaGroup\"), media, {\n business_connection_id: this.businessConnectionId,\n ...msg?.is_topic_message ? {\n message_thread_id: msg.message_thread_id\n } : {},\n direct_messages_topic_id: msg?.direct_messages_topic?.topic_id,\n ...other\n }, signal);\n }\n replyWithLocation(latitude, longitude, other, signal) {\n const msg = this.msg;\n return this.api.sendLocation(orThrow(this.chatId, \"sendLocation\"), latitude, longitude, {\n business_connection_id: this.businessConnectionId,\n ...msg?.is_topic_message ? {\n message_thread_id: msg.message_thread_id\n } : {},\n direct_messages_topic_id: msg?.direct_messages_topic?.topic_id,\n ...other\n }, signal);\n }\n editMessageLiveLocation(latitude, longitude, other, signal) {\n const inlineId = this.inlineMessageId;\n return inlineId !== undefined ? this.api.editMessageLiveLocationInline(inlineId, latitude, longitude, {\n business_connection_id: this.businessConnectionId,\n ...other\n }, signal) : this.api.editMessageLiveLocation(orThrow(this.chatId, \"editMessageLiveLocation\"), orThrow(this.msgId, \"editMessageLiveLocation\"), latitude, longitude, {\n business_connection_id: this.businessConnectionId,\n ...other\n }, signal);\n }\n stopMessageLiveLocation(other, signal) {\n const inlineId = this.inlineMessageId;\n return inlineId !== undefined ? this.api.stopMessageLiveLocationInline(inlineId, {\n business_connection_id: this.businessConnectionId,\n ...other\n }, signal) : this.api.stopMessageLiveLocation(orThrow(this.chatId, \"stopMessageLiveLocation\"), orThrow(this.msgId, \"stopMessageLiveLocation\"), {\n business_connection_id: this.businessConnectionId,\n ...other\n }, signal);\n }\n sendPaidMedia(star_count, media, other, signal) {\n const msg = this.msg;\n return this.api.sendPaidMedia(orThrow(this.chatId, \"sendPaidMedia\"), star_count, media, {\n business_connection_id: this.businessConnectionId,\n ...msg?.is_topic_message ? {\n message_thread_id: msg.message_thread_id\n } : {},\n direct_messages_topic_id: this.msg?.direct_messages_topic?.topic_id,\n ...other\n }, signal);\n }\n replyWithVenue(latitude, longitude, title, address, other, signal) {\n const msg = this.msg;\n return this.api.sendVenue(orThrow(this.chatId, \"sendVenue\"), latitude, longitude, title, address, {\n business_connection_id: this.businessConnectionId,\n ...msg?.is_topic_message ? {\n message_thread_id: msg.message_thread_id\n } : {},\n direct_messages_topic_id: msg?.direct_messages_topic?.topic_id,\n ...other\n }, signal);\n }\n replyWithContact(phone_number, first_name, other, signal) {\n const msg = this.msg;\n return this.api.sendContact(orThrow(this.chatId, \"sendContact\"), phone_number, first_name, {\n business_connection_id: this.businessConnectionId,\n ...msg?.is_topic_message ? {\n message_thread_id: msg.message_thread_id\n } : {},\n direct_messages_topic_id: msg?.direct_messages_topic?.topic_id,\n ...other\n }, signal);\n }\n replyWithPoll(question, options, other, signal) {\n const msg = this.msg;\n return this.api.sendPoll(orThrow(this.chatId, \"sendPoll\"), question, options, {\n business_connection_id: this.businessConnectionId,\n ...msg?.is_topic_message ? {\n message_thread_id: msg.message_thread_id\n } : {},\n ...other\n }, signal);\n }\n replyWithChecklist(checklist, other, signal) {\n return this.api.sendChecklist(orThrow(this.businessConnectionId, \"sendChecklist\"), orThrow(this.chatId, \"sendChecklist\"), checklist, other, signal);\n }\n editMessageChecklist(checklist, other, signal) {\n const msg = orThrow(this.msg, \"editMessageChecklist\");\n const target = msg.checklist_tasks_done?.checklist_message ?? msg.checklist_tasks_added?.checklist_message ?? msg;\n return this.api.editMessageChecklist(orThrow(this.businessConnectionId, \"editMessageChecklist\"), orThrow(target.chat.id, \"editMessageChecklist\"), orThrow(target.message_id, \"editMessageChecklist\"), checklist, other, signal);\n }\n replyWithDice(emoji, other, signal) {\n const msg = this.msg;\n return this.api.sendDice(orThrow(this.chatId, \"sendDice\"), emoji, {\n business_connection_id: this.businessConnectionId,\n ...msg?.is_topic_message ? {\n message_thread_id: msg.message_thread_id\n } : {},\n direct_messages_topic_id: msg?.direct_messages_topic?.topic_id,\n ...other\n }, signal);\n }\n replyWithChatAction(action, other, signal) {\n const msg = this.msg;\n return this.api.sendChatAction(orThrow(this.chatId, \"sendChatAction\"), action, {\n business_connection_id: this.businessConnectionId,\n message_thread_id: msg?.message_thread_id,\n ...other\n }, signal);\n }\n react(reaction, other, signal) {\n return this.api.setMessageReaction(orThrow(this.chatId, \"setMessageReaction\"), orThrow(this.msgId, \"setMessageReaction\"), typeof reaction === \"string\" ? [\n {\n type: \"emoji\",\n emoji: reaction\n }\n ] : (Array.isArray(reaction) ? reaction : [\n reaction\n ]).map((emoji)=>typeof emoji === \"string\" ? {\n type: \"emoji\",\n emoji\n } : emoji), other, signal);\n }\n getUserProfilePhotos(other, signal) {\n return this.api.getUserProfilePhotos(orThrow(this.from, \"getUserProfilePhotos\").id, other, signal);\n }\n getUserProfileAudios(other, signal) {\n return this.api.getUserProfileAudios(orThrow(this.from, \"getUserProfileAudios\").id, other, signal);\n }\n setUserEmojiStatus(other, signal) {\n return this.api.setUserEmojiStatus(orThrow(this.from, \"setUserEmojiStatus\").id, other, signal);\n }\n getUserChatBoosts(chat_id, signal) {\n return this.api.getUserChatBoosts(chat_id ?? orThrow(this.chatId, \"getUserChatBoosts\"), orThrow(this.from, \"getUserChatBoosts\").id, signal);\n }\n getUserGifts(other, signal) {\n return this.api.getUserGifts(orThrow(this.from, \"getUserGifts\").id, other, signal);\n }\n getChatGifts(other, signal) {\n return this.api.getChatGifts(orThrow(this.chatId, \"getChatGifts\"), other, signal);\n }\n getBusinessConnection(signal) {\n return this.api.getBusinessConnection(orThrow(this.businessConnectionId, \"getBusinessConnection\"), signal);\n }\n getFile(signal) {\n const m = orThrow(this.msg, \"getFile\");\n const file = m.photo !== undefined ? m.photo[m.photo.length - 1] : m.animation ?? m.audio ?? m.document ?? m.video ?? m.video_note ?? m.voice ?? m.sticker;\n return this.api.getFile(orThrow(file, \"getFile\").file_id, signal);\n }\n kickAuthor(...args) {\n return this.banAuthor(...args);\n }\n banAuthor(other, signal) {\n return this.api.banChatMember(orThrow(this.chatId, \"banAuthor\"), orThrow(this.from, \"banAuthor\").id, other, signal);\n }\n kickChatMember(...args) {\n return this.banChatMember(...args);\n }\n banChatMember(user_id, other, signal) {\n return this.api.banChatMember(orThrow(this.chatId, \"banChatMember\"), user_id, other, signal);\n }\n unbanChatMember(user_id, other, signal) {\n return this.api.unbanChatMember(orThrow(this.chatId, \"unbanChatMember\"), user_id, other, signal);\n }\n restrictAuthor(permissions, other, signal) {\n return this.api.restrictChatMember(orThrow(this.chatId, \"restrictAuthor\"), orThrow(this.from, \"restrictAuthor\").id, permissions, other, signal);\n }\n restrictChatMember(user_id, permissions, other, signal) {\n return this.api.restrictChatMember(orThrow(this.chatId, \"restrictChatMember\"), user_id, permissions, other, signal);\n }\n promoteAuthor(other, signal) {\n return this.api.promoteChatMember(orThrow(this.chatId, \"promoteAuthor\"), orThrow(this.from, \"promoteAuthor\").id, other, signal);\n }\n promoteChatMember(user_id, other, signal) {\n return this.api.promoteChatMember(orThrow(this.chatId, \"promoteChatMember\"), user_id, other, signal);\n }\n setChatAdministratorAuthorCustomTitle(custom_title, signal) {\n return this.api.setChatAdministratorCustomTitle(orThrow(this.chatId, \"setChatAdministratorAuthorCustomTitle\"), orThrow(this.from, \"setChatAdministratorAuthorCustomTitle\").id, custom_title, signal);\n }\n setChatAdministratorCustomTitle(user_id, custom_title, signal) {\n return this.api.setChatAdministratorCustomTitle(orThrow(this.chatId, \"setChatAdministratorCustomTitle\"), user_id, custom_title, signal);\n }\n setAuthorTag(tag, signal) {\n return this.api.setChatMemberTag(orThrow(this.chatId, \"setChatMemberTag\"), orThrow(this.from, \"setChatMemberTag\").id, tag, signal);\n }\n setChatMemberTag(user_id, tag, signal) {\n return this.api.setChatMemberTag(orThrow(this.chatId, \"setChatMemberTag\"), user_id, tag, signal);\n }\n banChatSenderChat(sender_chat_id, signal) {\n return this.api.banChatSenderChat(orThrow(this.chatId, \"banChatSenderChat\"), sender_chat_id, signal);\n }\n unbanChatSenderChat(sender_chat_id, signal) {\n return this.api.unbanChatSenderChat(orThrow(this.chatId, \"unbanChatSenderChat\"), sender_chat_id, signal);\n }\n setChatPermissions(permissions, other, signal) {\n return this.api.setChatPermissions(orThrow(this.chatId, \"setChatPermissions\"), permissions, other, signal);\n }\n exportChatInviteLink(signal) {\n return this.api.exportChatInviteLink(orThrow(this.chatId, \"exportChatInviteLink\"), signal);\n }\n createChatInviteLink(other, signal) {\n return this.api.createChatInviteLink(orThrow(this.chatId, \"createChatInviteLink\"), other, signal);\n }\n editChatInviteLink(invite_link, other, signal) {\n return this.api.editChatInviteLink(orThrow(this.chatId, \"editChatInviteLink\"), invite_link, other, signal);\n }\n createChatSubscriptionInviteLink(subscription_period, subscription_price, other, signal) {\n return this.api.createChatSubscriptionInviteLink(orThrow(this.chatId, \"createChatSubscriptionInviteLink\"), subscription_period, subscription_price, other, signal);\n }\n editChatSubscriptionInviteLink(invite_link, other, signal) {\n return this.api.editChatSubscriptionInviteLink(orThrow(this.chatId, \"editChatSubscriptionInviteLink\"), invite_link, other, signal);\n }\n revokeChatInviteLink(invite_link, signal) {\n return this.api.revokeChatInviteLink(orThrow(this.chatId, \"editChatInviteLink\"), invite_link, signal);\n }\n approveChatJoinRequest(user_id, signal) {\n return this.api.approveChatJoinRequest(orThrow(this.chatId, \"approveChatJoinRequest\"), user_id, signal);\n }\n declineChatJoinRequest(user_id, signal) {\n return this.api.declineChatJoinRequest(orThrow(this.chatId, \"declineChatJoinRequest\"), user_id, signal);\n }\n approveSuggestedPost(other, signal) {\n return this.api.approveSuggestedPost(orThrow(this.chatId, \"approveSuggestedPost\"), orThrow(this.msgId, \"approveSuggestedPost\"), other, signal);\n }\n declineSuggestedPost(other, signal) {\n return this.api.declineSuggestedPost(orThrow(this.chatId, \"declineSuggestedPost\"), orThrow(this.msgId, \"declineSuggestedPost\"), other, signal);\n }\n setChatPhoto(photo, signal) {\n return this.api.setChatPhoto(orThrow(this.chatId, \"setChatPhoto\"), photo, signal);\n }\n deleteChatPhoto(signal) {\n return this.api.deleteChatPhoto(orThrow(this.chatId, \"deleteChatPhoto\"), signal);\n }\n setChatTitle(title, signal) {\n return this.api.setChatTitle(orThrow(this.chatId, \"setChatTitle\"), title, signal);\n }\n setChatDescription(description, signal) {\n return this.api.setChatDescription(orThrow(this.chatId, \"setChatDescription\"), description, signal);\n }\n pinChatMessage(message_id, other, signal) {\n return this.api.pinChatMessage(orThrow(this.chatId, \"pinChatMessage\"), message_id, {\n business_connection_id: this.businessConnectionId,\n ...other\n }, signal);\n }\n unpinChatMessage(message_id, other, signal) {\n return this.api.unpinChatMessage(orThrow(this.chatId, \"unpinChatMessage\"), message_id, {\n business_connection_id: this.businessConnectionId,\n ...other\n }, signal);\n }\n unpinAllChatMessages(signal) {\n return this.api.unpinAllChatMessages(orThrow(this.chatId, \"unpinAllChatMessages\"), signal);\n }\n leaveChat(signal) {\n return this.api.leaveChat(orThrow(this.chatId, \"leaveChat\"), signal);\n }\n getChat(signal) {\n return this.api.getChat(orThrow(this.chatId, \"getChat\"), signal);\n }\n getChatAdministrators(signal) {\n return this.api.getChatAdministrators(orThrow(this.chatId, \"getChatAdministrators\"), signal);\n }\n getChatMembersCount(...args) {\n return this.getChatMemberCount(...args);\n }\n getChatMemberCount(signal) {\n return this.api.getChatMemberCount(orThrow(this.chatId, \"getChatMemberCount\"), signal);\n }\n getAuthor(signal) {\n return this.api.getChatMember(orThrow(this.chatId, \"getAuthor\"), orThrow(this.from, \"getAuthor\").id, signal);\n }\n getChatMember(user_id, signal) {\n return this.api.getChatMember(orThrow(this.chatId, \"getChatMember\"), user_id, signal);\n }\n setChatStickerSet(sticker_set_name, signal) {\n return this.api.setChatStickerSet(orThrow(this.chatId, \"setChatStickerSet\"), sticker_set_name, signal);\n }\n deleteChatStickerSet(signal) {\n return this.api.deleteChatStickerSet(orThrow(this.chatId, \"deleteChatStickerSet\"), signal);\n }\n createForumTopic(name, other, signal) {\n return this.api.createForumTopic(orThrow(this.chatId, \"createForumTopic\"), name, other, signal);\n }\n editForumTopic(other, signal) {\n const message = orThrow(this.msg, \"editForumTopic\");\n const thread = orThrow(message.message_thread_id, \"editForumTopic\");\n return this.api.editForumTopic(message.chat.id, thread, other, signal);\n }\n closeForumTopic(signal) {\n const message = orThrow(this.msg, \"closeForumTopic\");\n const thread = orThrow(message.message_thread_id, \"closeForumTopic\");\n return this.api.closeForumTopic(message.chat.id, thread, signal);\n }\n reopenForumTopic(signal) {\n const message = orThrow(this.msg, \"reopenForumTopic\");\n const thread = orThrow(message.message_thread_id, \"reopenForumTopic\");\n return this.api.reopenForumTopic(message.chat.id, thread, signal);\n }\n deleteForumTopic(signal) {\n const message = orThrow(this.msg, \"deleteForumTopic\");\n const thread = orThrow(message.message_thread_id, \"deleteForumTopic\");\n return this.api.deleteForumTopic(message.chat.id, thread, signal);\n }\n unpinAllForumTopicMessages(signal) {\n const message = orThrow(this.msg, \"unpinAllForumTopicMessages\");\n const thread = orThrow(message.message_thread_id, \"unpinAllForumTopicMessages\");\n return this.api.unpinAllForumTopicMessages(message.chat.id, thread, signal);\n }\n editGeneralForumTopic(name, signal) {\n return this.api.editGeneralForumTopic(orThrow(this.chatId, \"editGeneralForumTopic\"), name, signal);\n }\n closeGeneralForumTopic(signal) {\n return this.api.closeGeneralForumTopic(orThrow(this.chatId, \"closeGeneralForumTopic\"), signal);\n }\n reopenGeneralForumTopic(signal) {\n return this.api.reopenGeneralForumTopic(orThrow(this.chatId, \"reopenGeneralForumTopic\"), signal);\n }\n hideGeneralForumTopic(signal) {\n return this.api.hideGeneralForumTopic(orThrow(this.chatId, \"hideGeneralForumTopic\"), signal);\n }\n unhideGeneralForumTopic(signal) {\n return this.api.unhideGeneralForumTopic(orThrow(this.chatId, \"unhideGeneralForumTopic\"), signal);\n }\n unpinAllGeneralForumTopicMessages(signal) {\n return this.api.unpinAllGeneralForumTopicMessages(orThrow(this.chatId, \"unpinAllGeneralForumTopicMessages\"), signal);\n }\n answerCallbackQuery(other, signal) {\n return this.api.answerCallbackQuery(orThrow(this.callbackQuery, \"answerCallbackQuery\").id, typeof other === \"string\" ? {\n text: other\n } : other, signal);\n }\n setChatMenuButton(other, signal) {\n return this.api.setChatMenuButton(other, signal);\n }\n getChatMenuButton(other, signal) {\n return this.api.getChatMenuButton(other, signal);\n }\n setMyDefaultAdministratorRights(other, signal) {\n return this.api.setMyDefaultAdministratorRights(other, signal);\n }\n getMyDefaultAdministratorRights(other, signal) {\n return this.api.getMyDefaultAdministratorRights(other, signal);\n }\n editMessageText(text, other, signal) {\n const inlineId = this.inlineMessageId;\n return inlineId !== undefined ? this.api.editMessageTextInline(inlineId, text, {\n business_connection_id: this.businessConnectionId,\n ...other\n }, signal) : this.api.editMessageText(orThrow(this.chatId, \"editMessageText\"), orThrow(this.msg?.message_id ?? this.messageReaction?.message_id ?? this.messageReactionCount?.message_id, \"editMessageText\"), text, {\n business_connection_id: this.businessConnectionId,\n ...other\n }, signal);\n }\n editMessageCaption(other, signal) {\n const inlineId = this.inlineMessageId;\n return inlineId !== undefined ? this.api.editMessageCaptionInline(inlineId, {\n business_connection_id: this.businessConnectionId,\n ...other\n }, signal) : this.api.editMessageCaption(orThrow(this.chatId, \"editMessageCaption\"), orThrow(this.msg?.message_id ?? this.messageReaction?.message_id ?? this.messageReactionCount?.message_id, \"editMessageCaption\"), {\n business_connection_id: this.businessConnectionId,\n ...other\n }, signal);\n }\n editMessageMedia(media, other, signal) {\n const inlineId = this.inlineMessageId;\n return inlineId !== undefined ? this.api.editMessageMediaInline(inlineId, media, {\n business_connection_id: this.businessConnectionId,\n ...other\n }, signal) : this.api.editMessageMedia(orThrow(this.chatId, \"editMessageMedia\"), orThrow(this.msg?.message_id ?? this.messageReaction?.message_id ?? this.messageReactionCount?.message_id, \"editMessageMedia\"), media, {\n business_connection_id: this.businessConnectionId,\n ...other\n }, signal);\n }\n editMessageReplyMarkup(other, signal) {\n const inlineId = this.inlineMessageId;\n return inlineId !== undefined ? this.api.editMessageReplyMarkupInline(inlineId, {\n business_connection_id: this.businessConnectionId,\n ...other\n }, signal) : this.api.editMessageReplyMarkup(orThrow(this.chatId, \"editMessageReplyMarkup\"), orThrow(this.msg?.message_id ?? this.messageReaction?.message_id ?? this.messageReactionCount?.message_id, \"editMessageReplyMarkup\"), {\n business_connection_id: this.businessConnectionId,\n ...other\n }, signal);\n }\n stopPoll(other, signal) {\n return this.api.stopPoll(orThrow(this.chatId, \"stopPoll\"), orThrow(this.msg?.message_id ?? this.messageReaction?.message_id ?? this.messageReactionCount?.message_id, \"stopPoll\"), {\n business_connection_id: this.businessConnectionId,\n ...other\n }, signal);\n }\n deleteMessage(signal) {\n return this.api.deleteMessage(orThrow(this.chatId, \"deleteMessage\"), orThrow(this.msg?.message_id ?? this.messageReaction?.message_id ?? this.messageReactionCount?.message_id, \"deleteMessage\"), signal);\n }\n deleteMessages(message_ids, signal) {\n return this.api.deleteMessages(orThrow(this.chatId, \"deleteMessages\"), message_ids, signal);\n }\n deleteBusinessMessages(message_ids, signal) {\n return this.api.deleteBusinessMessages(orThrow(this.businessConnectionId, \"deleteBusinessMessages\"), message_ids, signal);\n }\n setBusinessAccountName(first_name, other, signal) {\n return this.api.setBusinessAccountName(orThrow(this.businessConnectionId, \"setBusinessAccountName\"), first_name, other, signal);\n }\n setBusinessAccountUsername(username, signal) {\n return this.api.setBusinessAccountUsername(orThrow(this.businessConnectionId, \"setBusinessAccountUsername\"), username, signal);\n }\n setBusinessAccountBio(bio, signal) {\n return this.api.setBusinessAccountBio(orThrow(this.businessConnectionId, \"setBusinessAccountBio\"), bio, signal);\n }\n setBusinessAccountProfilePhoto(photo, other, signal) {\n return this.api.setBusinessAccountProfilePhoto(orThrow(this.businessConnectionId, \"setBusinessAccountProfilePhoto\"), photo, other, signal);\n }\n removeBusinessAccountProfilePhoto(other, signal) {\n return this.api.removeBusinessAccountProfilePhoto(orThrow(this.businessConnectionId, \"removeBusinessAccountProfilePhoto\"), other, signal);\n }\n setBusinessAccountGiftSettings(show_gift_button, accepted_gift_types, signal) {\n return this.api.setBusinessAccountGiftSettings(orThrow(this.businessConnectionId, \"setBusinessAccountGiftSettings\"), show_gift_button, accepted_gift_types, signal);\n }\n getBusinessAccountStarBalance(signal) {\n return this.api.getBusinessAccountStarBalance(orThrow(this.businessConnectionId, \"getBusinessAccountStarBalance\"), signal);\n }\n transferBusinessAccountStars(star_count, signal) {\n return this.api.transferBusinessAccountStars(orThrow(this.businessConnectionId, \"transferBusinessAccountStars\"), star_count, signal);\n }\n getBusinessAccountGifts(other, signal) {\n return this.api.getBusinessAccountGifts(orThrow(this.businessConnectionId, \"getBusinessAccountGifts\"), other, signal);\n }\n convertGiftToStars(owned_gift_id, signal) {\n return this.api.convertGiftToStars(orThrow(this.businessConnectionId, \"convertGiftToStars\"), owned_gift_id, signal);\n }\n upgradeGift(owned_gift_id, other, signal) {\n return this.api.upgradeGift(orThrow(this.businessConnectionId, \"upgradeGift\"), owned_gift_id, other, signal);\n }\n transferGift(owned_gift_id, new_owner_chat_id, star_count, signal) {\n return this.api.transferGift(orThrow(this.businessConnectionId, \"transferGift\"), owned_gift_id, new_owner_chat_id, star_count, signal);\n }\n postStory(content, active_period, other, signal) {\n return this.api.postStory(orThrow(this.businessConnectionId, \"postStory\"), content, active_period, other, signal);\n }\n repostStory(active_period, other, signal) {\n const story = orThrow(this.msg?.story, \"repostStory\");\n return this.api.repostStory(orThrow(this.businessConnectionId, \"repostStory\"), story.chat.id, story.id, active_period, other, signal);\n }\n editStory(story_id, content, other, signal) {\n return this.api.editStory(orThrow(this.businessConnectionId, \"editStory\"), story_id, content, other, signal);\n }\n deleteStory(story_id, signal) {\n return this.api.deleteStory(orThrow(this.businessConnectionId, \"deleteStory\"), story_id, signal);\n }\n replyWithSticker(sticker, other, signal) {\n const msg = this.msg;\n return this.api.sendSticker(orThrow(this.chatId, \"sendSticker\"), sticker, {\n business_connection_id: this.businessConnectionId,\n ...msg?.is_topic_message ? {\n message_thread_id: msg.message_thread_id\n } : {},\n direct_messages_topic_id: msg?.direct_messages_topic?.topic_id,\n ...other\n }, signal);\n }\n getCustomEmojiStickers(signal) {\n return this.api.getCustomEmojiStickers((this.msg?.entities ?? []).filter((e)=>e.type === \"custom_emoji\").map((e)=>e.custom_emoji_id), signal);\n }\n replyWithGift(gift_id, other, signal) {\n return this.api.sendGift(orThrow(this.from, \"sendGift\").id, gift_id, other, signal);\n }\n giftPremiumSubscription(month_count, star_count, other, signal) {\n return this.api.giftPremiumSubscription(orThrow(this.from, \"giftPremiumSubscription\").id, month_count, star_count, other, signal);\n }\n replyWithGiftToChannel(gift_id, other, signal) {\n return this.api.sendGiftToChannel(orThrow(this.chat, \"sendGift\").id, gift_id, other, signal);\n }\n answerInlineQuery(results, other, signal) {\n return this.api.answerInlineQuery(orThrow(this.inlineQuery, \"answerInlineQuery\").id, results, other, signal);\n }\n savePreparedInlineMessage(result, other, signal) {\n return this.api.savePreparedInlineMessage(orThrow(this.from, \"savePreparedInlineMessage\").id, result, other, signal);\n }\n replyWithInvoice(title, description, payload, currency, prices, other, signal) {\n const msg = this.msg;\n return this.api.sendInvoice(orThrow(this.chatId, \"sendInvoice\"), title, description, payload, currency, prices, {\n ...msg?.is_topic_message ? {\n message_thread_id: msg.message_thread_id\n } : {},\n direct_messages_topic_id: msg?.direct_messages_topic?.topic_id,\n ...other\n }, signal);\n }\n answerShippingQuery(ok, other, signal) {\n return this.api.answerShippingQuery(orThrow(this.shippingQuery, \"answerShippingQuery\").id, ok, other, signal);\n }\n answerPreCheckoutQuery(ok, other, signal) {\n return this.api.answerPreCheckoutQuery(orThrow(this.preCheckoutQuery, \"answerPreCheckoutQuery\").id, ok, typeof other === \"string\" ? {\n error_message: other\n } : other, signal);\n }\n refundStarPayment(signal) {\n return this.api.refundStarPayment(orThrow(this.from, \"refundStarPayment\").id, orThrow(this.msg?.successful_payment, \"refundStarPayment\").telegram_payment_charge_id, signal);\n }\n editUserStarSubscription(telegram_payment_charge_id, is_canceled, signal) {\n return this.api.editUserStarSubscription(orThrow(this.from, \"editUserStarSubscription\").id, telegram_payment_charge_id, is_canceled, signal);\n }\n verifyUser(other, signal) {\n return this.api.verifyUser(orThrow(this.from, \"verifyUser\").id, other, signal);\n }\n verifyChat(other, signal) {\n return this.api.verifyChat(orThrow(this.chatId, \"verifyChat\"), other, signal);\n }\n removeUserVerification(signal) {\n return this.api.removeUserVerification(orThrow(this.from, \"removeUserVerification\").id, signal);\n }\n removeChatVerification(signal) {\n return this.api.removeChatVerification(orThrow(this.chatId, \"removeChatVerification\"), signal);\n }\n readBusinessMessage(signal) {\n return this.api.readBusinessMessage(orThrow(this.businessConnectionId, \"readBusinessMessage\"), orThrow(this.chatId, \"readBusinessMessage\"), orThrow(this.msgId, \"readBusinessMessage\"), signal);\n }\n setPassportDataErrors(errors, signal) {\n return this.api.setPassportDataErrors(orThrow(this.from, \"setPassportDataErrors\").id, errors, signal);\n }\n replyWithGame(game_short_name, other, signal) {\n const msg = this.msg;\n return this.api.sendGame(orThrow(this.chatId, \"sendGame\"), game_short_name, {\n business_connection_id: this.businessConnectionId,\n ...msg?.is_topic_message ? {\n message_thread_id: msg.message_thread_id\n } : {},\n ...other\n }, signal);\n }\n}\nfunction orThrow(value, method) {\n if (value === undefined) {\n throw new Error(`Missing information for API call to ${method}`);\n }\n return value;\n}\nfunction triggerFn(trigger) {\n return toArray(trigger).map((t)=>typeof t === \"string\" ? (txt)=>txt === t ? t : null : (txt)=>txt.match(t));\n}\nfunction match(ctx, content, triggers) {\n for (const t of triggers){\n const res = t(content);\n if (res) {\n ctx.match = res;\n return true;\n }\n }\n return false;\n}\nfunction toArray(e) {\n return Array.isArray(e) ? e : [\n e\n ];\n}\nclass BotError extends Error {\n error;\n ctx;\n constructor(error, ctx){\n super(generateBotErrorMessage(error));\n this.error = error;\n this.ctx = ctx;\n this.name = \"BotError\";\n if (error instanceof Error) this.stack = error.stack;\n }\n}\nfunction generateBotErrorMessage(error) {\n let msg;\n if (error instanceof Error) {\n msg = `${error.name} in middleware: ${error.message}`;\n } else {\n const type = typeof error;\n msg = `Non-error value of type ${type} thrown in middleware`;\n switch(type){\n case \"bigint\":\n case \"boolean\":\n case \"number\":\n case \"symbol\":\n msg += `: ${error}`;\n break;\n case \"string\":\n msg += `: ${String(error).substring(0, 50)}`;\n break;\n default:\n msg += \"!\";\n break;\n }\n }\n return msg;\n}\nfunction flatten(mw) {\n return typeof mw === \"function\" ? mw : (ctx, next)=>mw.middleware()(ctx, next);\n}\nfunction concat1(first, andThen) {\n return async (ctx, next)=>{\n let nextCalled = false;\n await first(ctx, async ()=>{\n if (nextCalled) throw new Error(\"`next` already called before!\");\n else nextCalled = true;\n await andThen(ctx, next);\n });\n };\n}\nfunction pass(_ctx, next) {\n return next();\n}\nconst leaf1 = ()=>Promise.resolve();\nasync function run(middleware, ctx) {\n await middleware(ctx, leaf1);\n}\nclass Composer {\n handler;\n constructor(...middleware){\n this.handler = middleware.length === 0 ? pass : middleware.map(flatten).reduce(concat1);\n }\n middleware() {\n return this.handler;\n }\n use(...middleware) {\n const composer = new Composer(...middleware);\n this.handler = concat1(this.handler, flatten(composer));\n return composer;\n }\n on(filter, ...middleware) {\n return this.filter(Context.has.filterQuery(filter), ...middleware);\n }\n hears(trigger, ...middleware) {\n return this.filter(Context.has.text(trigger), ...middleware);\n }\n command(command, ...middleware) {\n return this.filter(Context.has.command(command), ...middleware);\n }\n reaction(reaction, ...middleware) {\n return this.filter(Context.has.reaction(reaction), ...middleware);\n }\n chatType(chatType, ...middleware) {\n return this.filter(Context.has.chatType(chatType), ...middleware);\n }\n callbackQuery(trigger, ...middleware) {\n return this.filter(Context.has.callbackQuery(trigger), ...middleware);\n }\n gameQuery(trigger, ...middleware) {\n return this.filter(Context.has.gameQuery(trigger), ...middleware);\n }\n inlineQuery(trigger, ...middleware) {\n return this.filter(Context.has.inlineQuery(trigger), ...middleware);\n }\n chosenInlineResult(resultId, ...middleware) {\n return this.filter(Context.has.chosenInlineResult(resultId), ...middleware);\n }\n preCheckoutQuery(trigger, ...middleware) {\n return this.filter(Context.has.preCheckoutQuery(trigger), ...middleware);\n }\n shippingQuery(trigger, ...middleware) {\n return this.filter(Context.has.shippingQuery(trigger), ...middleware);\n }\n filter(predicate, ...middleware) {\n const composer = new Composer(...middleware);\n this.branch(predicate, composer, pass);\n return composer;\n }\n drop(predicate, ...middleware) {\n return this.filter(async (ctx)=>!await predicate(ctx), ...middleware);\n }\n fork(...middleware) {\n const composer = new Composer(...middleware);\n const fork = flatten(composer);\n this.use((ctx, next)=>Promise.all([\n next(),\n run(fork, ctx)\n ]));\n return composer;\n }\n lazy(middlewareFactory) {\n return this.use(async (ctx, next)=>{\n const middleware = await middlewareFactory(ctx);\n const arr = Array.isArray(middleware) ? middleware : [\n middleware\n ];\n await flatten(new Composer(...arr))(ctx, next);\n });\n }\n route(router, routeHandlers, fallback = pass) {\n return this.lazy(async (ctx)=>{\n const route = await router(ctx);\n return (route === undefined || !routeHandlers[route] ? fallback : routeHandlers[route]) ?? [];\n });\n }\n branch(predicate, trueMiddleware, falseMiddleware) {\n return this.lazy(async (ctx)=>await predicate(ctx) ? trueMiddleware : falseMiddleware);\n }\n errorBoundary(errorHandler, ...middleware) {\n const composer = new Composer(...middleware);\n const bound = flatten(composer);\n this.use(async (ctx, next)=>{\n let nextCalled = false;\n const cont = ()=>(nextCalled = true, Promise.resolve());\n try {\n await bound(ctx, cont);\n } catch (err) {\n nextCalled = false;\n await errorHandler(new BotError(err, ctx), cont);\n }\n if (nextCalled) await next();\n });\n return composer;\n }\n}\nvar s = 1e3;\nvar m = s * 60;\nvar h = m * 60;\nvar d = h * 24;\nvar w = d * 7;\nvar y = d * 365.25;\nvar ms = function(val, options) {\n options = options || {};\n var type = typeof val;\n if (type === \"string\" && val.length > 0) {\n return parse1(val);\n } else if (type === \"number\" && isFinite(val)) {\n return options.long ? fmtLong(val) : fmtShort(val);\n }\n throw new Error(\"val is not a non-empty string or a valid number. val=\" + JSON.stringify(val));\n};\nfunction parse1(str) {\n str = String(str);\n if (str.length > 100) {\n return;\n }\n var match = /^(-?(?:\\d+)?\\.?\\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(str);\n if (!match) {\n return;\n }\n var n = parseFloat(match[1]);\n var type = (match[2] || \"ms\").toLowerCase();\n switch(type){\n case \"years\":\n case \"year\":\n case \"yrs\":\n case \"yr\":\n case \"y\":\n return n * y;\n case \"weeks\":\n case \"week\":\n case \"w\":\n return n * w;\n case \"days\":\n case \"day\":\n case \"d\":\n return n * d;\n case \"hours\":\n case \"hour\":\n case \"hrs\":\n case \"hr\":\n case \"h\":\n return n * h;\n case \"minutes\":\n case \"minute\":\n case \"mins\":\n case \"min\":\n case \"m\":\n return n * m;\n case \"seconds\":\n case \"second\":\n case \"secs\":\n case \"sec\":\n case \"s\":\n return n * s;\n case \"milliseconds\":\n case \"millisecond\":\n case \"msecs\":\n case \"msec\":\n case \"ms\":\n return n;\n default:\n return void 0;\n }\n}\nfunction fmtShort(ms2) {\n var msAbs = Math.abs(ms2);\n if (msAbs >= d) {\n return Math.round(ms2 / d) + \"d\";\n }\n if (msAbs >= h) {\n return Math.round(ms2 / h) + \"h\";\n }\n if (msAbs >= m) {\n return Math.round(ms2 / m) + \"m\";\n }\n if (msAbs >= s) {\n return Math.round(ms2 / s) + \"s\";\n }\n return ms2 + \"ms\";\n}\nfunction fmtLong(ms2) {\n var msAbs = Math.abs(ms2);\n if (msAbs >= d) {\n return plural(ms2, msAbs, d, \"day\");\n }\n if (msAbs >= h) {\n return plural(ms2, msAbs, h, \"hour\");\n }\n if (msAbs >= m) {\n return plural(ms2, msAbs, m, \"minute\");\n }\n if (msAbs >= s) {\n return plural(ms2, msAbs, s, \"second\");\n }\n return ms2 + \" ms\";\n}\nfunction plural(ms2, msAbs, n, name) {\n var isPlural = msAbs >= n * 1.5;\n return Math.round(ms2 / n) + \" \" + name + (isPlural ? \"s\" : \"\");\n}\nfunction defaultSetTimout() {\n throw new Error(\"setTimeout has not been defined\");\n}\nfunction defaultClearTimeout() {\n throw new Error(\"clearTimeout has not been defined\");\n}\nvar cachedSetTimeout = defaultSetTimout;\nvar cachedClearTimeout = defaultClearTimeout;\nvar globalContext;\nif (typeof window !== \"undefined\") {\n globalContext = window;\n} else if (typeof self !== \"undefined\") {\n globalContext = self;\n} else {\n globalContext = {};\n}\nif (typeof globalContext.setTimeout === \"function\") {\n cachedSetTimeout = setTimeout;\n}\nif (typeof globalContext.clearTimeout === \"function\") {\n cachedClearTimeout = clearTimeout;\n}\nfunction runTimeout(fun) {\n if (cachedSetTimeout === setTimeout) {\n return setTimeout(fun, 0);\n }\n if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {\n cachedSetTimeout = setTimeout;\n return setTimeout(fun, 0);\n }\n try {\n return cachedSetTimeout(fun, 0);\n } catch (e) {\n try {\n return cachedSetTimeout.call(null, fun, 0);\n } catch (e2) {\n return cachedSetTimeout.call(this, fun, 0);\n }\n }\n}\nfunction runClearTimeout(marker) {\n if (cachedClearTimeout === clearTimeout) {\n return clearTimeout(marker);\n }\n if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {\n cachedClearTimeout = clearTimeout;\n return clearTimeout(marker);\n }\n try {\n return cachedClearTimeout(marker);\n } catch (e) {\n try {\n return cachedClearTimeout.call(null, marker);\n } catch (e2) {\n return cachedClearTimeout.call(this, marker);\n }\n }\n}\nvar queue = [];\nvar draining = false;\nvar currentQueue;\nvar queueIndex = -1;\nfunction cleanUpNextTick() {\n if (!draining || !currentQueue) {\n return;\n }\n draining = false;\n if (currentQueue.length) {\n queue = currentQueue.concat(queue);\n } else {\n queueIndex = -1;\n }\n if (queue.length) {\n drainQueue();\n }\n}\nfunction drainQueue() {\n if (draining) {\n return;\n }\n var timeout = runTimeout(cleanUpNextTick);\n draining = true;\n var len = queue.length;\n while(len){\n currentQueue = queue;\n queue = [];\n while(++queueIndex < len){\n if (currentQueue) {\n currentQueue[queueIndex].run();\n }\n }\n queueIndex = -1;\n len = queue.length;\n }\n currentQueue = null;\n draining = false;\n runClearTimeout(timeout);\n}\nfunction nextTick(fun) {\n var args = new Array(arguments.length - 1);\n if (arguments.length > 1) {\n for(var i = 1; i < arguments.length; i++){\n args[i - 1] = arguments[i];\n }\n }\n queue.push(new Item(fun, args));\n if (queue.length === 1 && !draining) {\n runTimeout(drainQueue);\n }\n}\nfunction Item(fun, array) {\n this.fun = fun;\n this.array = array;\n}\nItem.prototype.run = function() {\n this.fun.apply(null, this.array);\n};\nvar title = \"browser\";\nvar platform = \"browser\";\nvar browser = true;\nvar argv = [];\nvar version = \"\";\nvar versions = {};\nvar release = {};\nvar config = {};\nfunction noop() {}\nvar on = noop;\nvar addListener = noop;\nvar once = noop;\nvar off = noop;\nvar removeListener = noop;\nvar removeAllListeners = noop;\nvar emit = noop;\nfunction binding(name) {\n throw new Error(\"process.binding is not supported\");\n}\nfunction cwd() {\n return \"/\";\n}\nfunction chdir(dir) {\n throw new Error(\"process.chdir is not supported\");\n}\nfunction umask() {\n return 0;\n}\nvar performance = globalContext.performance || {};\nvar performanceNow = performance.now || performance.mozNow || performance.msNow || performance.oNow || performance.webkitNow || function() {\n return new Date().getTime();\n};\nfunction hrtime(previousTimestamp) {\n var clocktime = performanceNow.call(performance) * 1e-3;\n var seconds = Math.floor(clocktime);\n var nanoseconds = Math.floor(clocktime % 1 * 1e9);\n if (previousTimestamp) {\n seconds = seconds - previousTimestamp[0];\n nanoseconds = nanoseconds - previousTimestamp[1];\n if (nanoseconds < 0) {\n seconds--;\n nanoseconds += 1e9;\n }\n }\n return [\n seconds,\n nanoseconds\n ];\n}\nvar startTime = new Date();\nfunction uptime() {\n var currentTime = new Date();\n var dif = currentTime - startTime;\n return dif / 1e3;\n}\nvar process = {\n nextTick,\n title,\n browser,\n env: {\n NODE_ENV: \"production\"\n },\n argv,\n version,\n versions,\n on,\n addListener,\n once,\n off,\n removeListener,\n removeAllListeners,\n emit,\n binding,\n cwd,\n chdir,\n umask,\n hrtime,\n platform,\n release,\n config,\n uptime\n};\nfunction createCommonjsModule(fn, basedir, module) {\n return module = {\n path: basedir,\n exports: {},\n require: function(path, base) {\n return commonjsRequire(path, base === void 0 || base === null ? module.path : base);\n }\n }, fn(module, module.exports), module.exports;\n}\nfunction commonjsRequire() {\n throw new Error(\"Dynamic requires are not currently supported by @rollup/plugin-commonjs\");\n}\nfunction setup(env) {\n createDebug.debug = createDebug;\n createDebug.default = createDebug;\n createDebug.coerce = coerce;\n createDebug.disable = disable;\n createDebug.enable = enable;\n createDebug.enabled = enabled;\n createDebug.humanize = ms;\n createDebug.destroy = destroy2;\n Object.keys(env).forEach((key)=>{\n createDebug[key] = env[key];\n });\n createDebug.names = [];\n createDebug.skips = [];\n createDebug.formatters = {};\n function selectColor(namespace) {\n let hash = 0;\n for(let i = 0; i < namespace.length; i++){\n hash = (hash << 5) - hash + namespace.charCodeAt(i);\n hash |= 0;\n }\n return createDebug.colors[Math.abs(hash) % createDebug.colors.length];\n }\n createDebug.selectColor = selectColor;\n function createDebug(namespace) {\n let prevTime;\n let enableOverride = null;\n let namespacesCache;\n let enabledCache;\n function debug(...args) {\n if (!debug.enabled) {\n return;\n }\n const self2 = debug;\n const curr = Number(new Date());\n const ms2 = curr - (prevTime || curr);\n self2.diff = ms2;\n self2.prev = prevTime;\n self2.curr = curr;\n prevTime = curr;\n args[0] = createDebug.coerce(args[0]);\n if (typeof args[0] !== \"string\") {\n args.unshift(\"%O\");\n }\n let index = 0;\n args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format)=>{\n if (match === \"%%\") {\n return \"%\";\n }\n index++;\n const formatter = createDebug.formatters[format];\n if (typeof formatter === \"function\") {\n const val = args[index];\n match = formatter.call(self2, val);\n args.splice(index, 1);\n index--;\n }\n return match;\n });\n createDebug.formatArgs.call(self2, args);\n const logFn = self2.log || createDebug.log;\n logFn.apply(self2, args);\n }\n debug.namespace = namespace;\n debug.useColors = createDebug.useColors();\n debug.color = createDebug.selectColor(namespace);\n debug.extend = extend;\n debug.destroy = createDebug.destroy;\n Object.defineProperty(debug, \"enabled\", {\n enumerable: true,\n configurable: false,\n get: ()=>{\n if (enableOverride !== null) {\n return enableOverride;\n }\n if (namespacesCache !== createDebug.namespaces) {\n namespacesCache = createDebug.namespaces;\n enabledCache = createDebug.enabled(namespace);\n }\n return enabledCache;\n },\n set: (v)=>{\n enableOverride = v;\n }\n });\n if (typeof createDebug.init === \"function\") {\n createDebug.init(debug);\n }\n return debug;\n }\n function extend(namespace, delimiter) {\n const newDebug = createDebug(this.namespace + (typeof delimiter === \"undefined\" ? \":\" : delimiter) + namespace);\n newDebug.log = this.log;\n return newDebug;\n }\n function enable(namespaces) {\n createDebug.save(namespaces);\n createDebug.namespaces = namespaces;\n createDebug.names = [];\n createDebug.skips = [];\n const split = (typeof namespaces === \"string\" ? namespaces : \"\").trim().replace(/\\s+/g, \",\").split(\",\").filter(Boolean);\n for (const ns of split){\n if (ns[0] === \"-\") {\n createDebug.skips.push(ns.slice(1));\n } else {\n createDebug.names.push(ns);\n }\n }\n }\n function matchesTemplate(search, template) {\n let searchIndex = 0;\n let templateIndex = 0;\n let starIndex = -1;\n let matchIndex = 0;\n while(searchIndex < search.length){\n if (templateIndex < template.length && (template[templateIndex] === search[searchIndex] || template[templateIndex] === \"*\")) {\n if (template[templateIndex] === \"*\") {\n starIndex = templateIndex;\n matchIndex = searchIndex;\n templateIndex++;\n } else {\n searchIndex++;\n templateIndex++;\n }\n } else if (starIndex !== -1) {\n templateIndex = starIndex + 1;\n matchIndex++;\n searchIndex = matchIndex;\n } else {\n return false;\n }\n }\n while(templateIndex < template.length && template[templateIndex] === \"*\"){\n templateIndex++;\n }\n return templateIndex === template.length;\n }\n function disable() {\n const namespaces = [\n ...createDebug.names,\n ...createDebug.skips.map((namespace)=>\"-\" + namespace)\n ].join(\",\");\n createDebug.enable(\"\");\n return namespaces;\n }\n function enabled(name) {\n for (const skip of createDebug.skips){\n if (matchesTemplate(name, skip)) {\n return false;\n }\n }\n for (const ns of createDebug.names){\n if (matchesTemplate(name, ns)) {\n return true;\n }\n }\n return false;\n }\n function coerce(val) {\n if (val instanceof Error) {\n return val.stack || val.message;\n }\n return val;\n }\n function destroy2() {\n console.warn(\"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.\");\n }\n createDebug.enable(createDebug.load());\n return createDebug;\n}\nvar common = setup;\nvar browser$1 = createCommonjsModule(function(module, exports) {\n exports.formatArgs = formatArgs2;\n exports.save = save2;\n exports.load = load2;\n exports.useColors = useColors2;\n exports.storage = localstorage();\n exports.destroy = (()=>{\n let warned = false;\n return ()=>{\n if (!warned) {\n warned = true;\n console.warn(\"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.\");\n }\n };\n })();\n exports.colors = [\n \"#0000CC\",\n \"#0000FF\",\n \"#0033CC\",\n \"#0033FF\",\n \"#0066CC\",\n \"#0066FF\",\n \"#0099CC\",\n \"#0099FF\",\n \"#00CC00\",\n \"#00CC33\",\n \"#00CC66\",\n \"#00CC99\",\n \"#00CCCC\",\n \"#00CCFF\",\n \"#3300CC\",\n \"#3300FF\",\n \"#3333CC\",\n \"#3333FF\",\n \"#3366CC\",\n \"#3366FF\",\n \"#3399CC\",\n \"#3399FF\",\n \"#33CC00\",\n \"#33CC33\",\n \"#33CC66\",\n \"#33CC99\",\n \"#33CCCC\",\n \"#33CCFF\",\n \"#6600CC\",\n \"#6600FF\",\n \"#6633CC\",\n \"#6633FF\",\n \"#66CC00\",\n \"#66CC33\",\n \"#9900CC\",\n \"#9900FF\",\n \"#9933CC\",\n \"#9933FF\",\n \"#99CC00\",\n \"#99CC33\",\n \"#CC0000\",\n \"#CC0033\",\n \"#CC0066\",\n \"#CC0099\",\n \"#CC00CC\",\n \"#CC00FF\",\n \"#CC3300\",\n \"#CC3333\",\n \"#CC3366\",\n \"#CC3399\",\n \"#CC33CC\",\n \"#CC33FF\",\n \"#CC6600\",\n \"#CC6633\",\n \"#CC9900\",\n \"#CC9933\",\n \"#CCCC00\",\n \"#CCCC33\",\n \"#FF0000\",\n \"#FF0033\",\n \"#FF0066\",\n \"#FF0099\",\n \"#FF00CC\",\n \"#FF00FF\",\n \"#FF3300\",\n \"#FF3333\",\n \"#FF3366\",\n \"#FF3399\",\n \"#FF33CC\",\n \"#FF33FF\",\n \"#FF6600\",\n \"#FF6633\",\n \"#FF9900\",\n \"#FF9933\",\n \"#FFCC00\",\n \"#FFCC33\"\n ];\n function useColors2() {\n if (typeof window !== \"undefined\" && window.process && (window.process.type === \"renderer\" || window.process.__nwjs)) {\n return true;\n }\n if (typeof navigator !== \"undefined\" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\\/(\\d+)/)) {\n return false;\n }\n let m;\n return typeof document !== \"undefined\" && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance || typeof window !== \"undefined\" && window.console && (window.console.firebug || window.console.exception && window.console.table) || typeof navigator !== \"undefined\" && navigator.userAgent && (m = navigator.userAgent.toLowerCase().match(/firefox\\/(\\d+)/)) && parseInt(m[1], 10) >= 31 || typeof navigator !== \"undefined\" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\\/(\\d+)/);\n }\n function formatArgs2(args) {\n args[0] = (this.useColors ? \"%c\" : \"\") + this.namespace + (this.useColors ? \" %c\" : \" \") + args[0] + (this.useColors ? \"%c \" : \" \") + \"+\" + module.exports.humanize(this.diff);\n if (!this.useColors) {\n return;\n }\n const c = \"color: \" + this.color;\n args.splice(1, 0, c, \"color: inherit\");\n let index = 0;\n let lastC = 0;\n args[0].replace(/%[a-zA-Z%]/g, (match)=>{\n if (match === \"%%\") {\n return;\n }\n index++;\n if (match === \"%c\") {\n lastC = index;\n }\n });\n args.splice(lastC, 0, c);\n }\n exports.log = console.debug || console.log || (()=>{});\n function save2(namespaces) {\n try {\n if (namespaces) {\n exports.storage.setItem(\"debug\", namespaces);\n } else {\n exports.storage.removeItem(\"debug\");\n }\n } catch (error) {}\n }\n function load2() {\n let r;\n try {\n r = exports.storage.getItem(\"debug\") || exports.storage.getItem(\"DEBUG\");\n } catch (error) {}\n if (!r && typeof process !== \"undefined\" && \"env\" in process) {\n r = process.env.DEBUG;\n }\n return r;\n }\n function localstorage() {\n try {\n return localStorage;\n } catch (error) {}\n }\n module.exports = common(exports);\n const { formatters } = module.exports;\n formatters.j = function(v) {\n try {\n return JSON.stringify(v);\n } catch (error) {\n return \"[UnexpectedJSONParseError]: \" + error.message;\n }\n };\n});\nbrowser$1.colors;\nbrowser$1.destroy;\nbrowser$1.formatArgs;\nbrowser$1.load;\nbrowser$1.log;\nbrowser$1.save;\nbrowser$1.storage;\nbrowser$1.useColors;\nconst itrToStream = (itr)=>{\n const it = itr[Symbol.asyncIterator]();\n return new ReadableStream({\n async pull (controller) {\n const chunk = await it.next();\n if (chunk.done) controller.close();\n else controller.enqueue(chunk.value);\n }\n });\n};\nconst baseFetchConfig = (_apiRoot)=>({});\nconst defaultAdapter = \"cloudflare\";\nconst debug = browser$1(\"grammy:warn\");\nclass GrammyError extends Error {\n method;\n payload;\n ok;\n error_code;\n description;\n parameters;\n constructor(message, err, method, payload){\n super(`${message} (${err.error_code}: ${err.description})`);\n this.method = method;\n this.payload = payload;\n this.ok = false;\n this.name = \"GrammyError\";\n this.error_code = err.error_code;\n this.description = err.description;\n this.parameters = err.parameters ?? {};\n }\n}\nfunction toGrammyError(err, method, payload) {\n switch(err.error_code){\n case 401:\n debug(\"Error 401 means that your bot token is wrong, talk to https://t.me/BotFather to check it.\");\n break;\n case 409:\n debug(\"Error 409 means that you are running your bot several times on long polling. Consider revoking the bot token if you believe that no other instance is running.\");\n break;\n }\n return new GrammyError(`Call to '${method}' failed!`, err, method, payload);\n}\nclass HttpError extends Error {\n error;\n constructor(message, error){\n super(message);\n this.error = error;\n this.name = \"HttpError\";\n }\n}\nfunction isTelegramError(err) {\n return typeof err === \"object\" && err !== null && \"status\" in err && \"statusText\" in err;\n}\nfunction toHttpError(method, sensitiveLogs, err) {\n let msg = `Network request for '${method}' failed!`;\n if (isTelegramError(err)) msg += ` (${err.status}: ${err.statusText})`;\n if (sensitiveLogs && err instanceof Error) msg += ` ${err.message}`;\n return new HttpError(msg, err);\n}\nfunction checkWindows() {\n const global = globalThis;\n const os = global.Deno?.build?.os;\n return typeof os === \"string\" ? os === \"windows\" : global.navigator?.platform?.startsWith(\"Win\") ?? global.process?.platform?.startsWith(\"win\") ?? false;\n}\nconst isWindows = checkWindows();\nfunction assertPath(path) {\n if (typeof path !== \"string\") {\n throw new TypeError(`Path must be a string, received \"${JSON.stringify(path)}\"`);\n }\n}\nfunction stripSuffix(name, suffix) {\n if (suffix.length >= name.length) {\n return name;\n }\n const lenDiff = name.length - suffix.length;\n for(let i = suffix.length - 1; i >= 0; --i){\n if (name.charCodeAt(lenDiff + i) !== suffix.charCodeAt(i)) {\n return name;\n }\n }\n return name.slice(0, -suffix.length);\n}\nfunction lastPathSegment(path, isSep, start = 0) {\n let matchedNonSeparator = false;\n let end = path.length;\n for(let i = path.length - 1; i >= start; --i){\n if (isSep(path.charCodeAt(i))) {\n if (matchedNonSeparator) {\n start = i + 1;\n break;\n }\n } else if (!matchedNonSeparator) {\n matchedNonSeparator = true;\n end = i + 1;\n }\n }\n return path.slice(start, end);\n}\nfunction assertArgs(path, suffix) {\n assertPath(path);\n if (path.length === 0) return path;\n if (typeof suffix !== \"string\") {\n throw new TypeError(`Suffix must be a string, received \"${JSON.stringify(suffix)}\"`);\n }\n}\nfunction assertArg(url) {\n url = url instanceof URL ? url : new URL(url);\n if (url.protocol !== \"file:\") {\n throw new TypeError(`URL must be a file URL: received \"${url.protocol}\"`);\n }\n return url;\n}\nfunction fromFileUrl(url) {\n url = assertArg(url);\n return decodeURIComponent(url.pathname.replace(/%(?![0-9A-Fa-f]{2})/g, \"%25\"));\n}\nfunction stripTrailingSeparators(segment, isSep) {\n if (segment.length <= 1) {\n return segment;\n }\n let end = segment.length;\n for(let i = segment.length - 1; i > 0; i--){\n if (isSep(segment.charCodeAt(i))) {\n end = i;\n } else {\n break;\n }\n }\n return segment.slice(0, end);\n}\nfunction isPosixPathSeparator(code) {\n return code === 47;\n}\nfunction basename(path, suffix = \"\") {\n if (path instanceof URL) {\n path = fromFileUrl(path);\n }\n assertArgs(path, suffix);\n const lastSegment = lastPathSegment(path, isPosixPathSeparator);\n const strippedSegment = stripTrailingSeparators(lastSegment, isPosixPathSeparator);\n return suffix ? stripSuffix(strippedSegment, suffix) : strippedSegment;\n}\nfunction isPathSeparator(code) {\n return code === 47 || code === 92;\n}\nfunction isWindowsDeviceRoot(code) {\n return code >= 97 && code <= 122 || code >= 65 && code <= 90;\n}\nfunction fromFileUrl1(url) {\n url = assertArg(url);\n let path = decodeURIComponent(url.pathname.replace(/\\//g, \"\\\\\").replace(/%(?![0-9A-Fa-f]{2})/g, \"%25\")).replace(/^\\\\*([A-Za-z]:)(\\\\|$)/, \"$1\\\\\");\n if (url.hostname !== \"\") {\n path = `\\\\\\\\${url.hostname}${path}`;\n }\n return path;\n}\nfunction basename1(path, suffix = \"\") {\n if (path instanceof URL) {\n path = fromFileUrl1(path);\n }\n assertArgs(path, suffix);\n let start = 0;\n if (path.length >= 2) {\n const drive = path.charCodeAt(0);\n if (isWindowsDeviceRoot(drive)) {\n if (path.charCodeAt(1) === 58) start = 2;\n }\n }\n const lastSegment = lastPathSegment(path, isPathSeparator, start);\n const strippedSegment = stripTrailingSeparators(lastSegment, isPathSeparator);\n return suffix ? stripSuffix(strippedSegment, suffix) : strippedSegment;\n}\nfunction basename2(path, suffix = \"\") {\n return isWindows ? basename1(path, suffix) : basename(path, suffix);\n}\nclass InputFile {\n consumed = false;\n fileData;\n filename;\n constructor(file, filename){\n this.fileData = file;\n filename ??= this.guessFilename(file);\n this.filename = filename;\n }\n guessFilename(file) {\n if (typeof file === \"string\") return basename2(file);\n if (typeof file !== \"object\") return undefined;\n if (\"url\" in file) return basename2(file.url);\n if (!(file instanceof URL)) return undefined;\n return basename2(file.pathname) || basename2(file.hostname);\n }\n toRaw() {\n if (this.consumed) {\n throw new Error(\"Cannot reuse InputFile data source!\");\n }\n const data = this.fileData;\n if (data instanceof Blob) return data.stream();\n if (data instanceof URL) return fetchFile(data);\n if (\"url\" in data) return fetchFile(data.url);\n if (!(data instanceof Uint8Array)) this.consumed = true;\n return data;\n }\n toJSON() {\n throw new Error(\"InputFile instances must be sent via grammY\");\n }\n}\nasync function* fetchFile(url) {\n const { body } = await fetch(url);\n if (body === null) {\n throw new Error(`Download failed, no response body from '${url}'`);\n }\n yield* body;\n}\nfunction requiresFormDataUpload(payload) {\n return payload instanceof InputFile || typeof payload === \"object\" && payload !== null && Object.values(payload).some((v)=>Array.isArray(v) ? v.some(requiresFormDataUpload) : v instanceof InputFile || requiresFormDataUpload(v));\n}\nfunction str(value) {\n return JSON.stringify(value, (_, v)=>v ?? undefined);\n}\nfunction createJsonPayload(payload) {\n return {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n connection: \"keep-alive\"\n },\n body: str(payload)\n };\n}\nasync function* protectItr(itr, onError) {\n try {\n yield* itr;\n } catch (err) {\n onError(err);\n }\n}\nfunction createFormDataPayload(payload, onError) {\n const boundary = createBoundary();\n const itr = payloadToMultipartItr(payload, boundary);\n const safeItr = protectItr(itr, onError);\n const stream = itrToStream(safeItr);\n return {\n method: \"POST\",\n headers: {\n \"content-type\": `multipart/form-data; boundary=${boundary}`,\n connection: \"keep-alive\"\n },\n body: stream\n };\n}\nfunction createBoundary() {\n return \"----------\" + randomId(32);\n}\nfunction randomId(length = 16) {\n return Array.from(Array(length)).map(()=>Math.random().toString(36)[2] || 0).join(\"\");\n}\nconst enc = new TextEncoder();\nasync function* payloadToMultipartItr(payload, boundary) {\n const files = collectFiles(payload);\n yield enc.encode(`--${boundary}\\r\\n`);\n const separator = enc.encode(`\\r\\n--${boundary}\\r\\n`);\n let first = true;\n for (const [key, value] of Object.entries(payload)){\n if (value == null) continue;\n if (!first) yield separator;\n yield valuePart(key, value instanceof InputFile ? value.toJSON() : typeof value === \"object\" ? str(value) : value);\n first = false;\n }\n for (const { id, origin, file } of files){\n if (!first) yield separator;\n yield* filePart(id, origin, file);\n first = false;\n }\n yield enc.encode(`\\r\\n--${boundary}--\\r\\n`);\n}\nfunction collectFiles(value) {\n if (typeof value !== \"object\" || value === null) return [];\n return Object.entries(value).flatMap(([k, v])=>{\n if (Array.isArray(v)) return v.flatMap((p)=>collectFiles(p));\n else if (v instanceof InputFile) {\n const id = randomId();\n Object.assign(v, {\n toJSON: ()=>`attach://${id}`\n });\n const origin = k === \"media\" && \"type\" in value && typeof value.type === \"string\" ? value.type : k;\n return {\n id,\n origin,\n file: v\n };\n } else return collectFiles(v);\n });\n}\nfunction valuePart(key, value) {\n return enc.encode(`content-disposition:form-data;name=\"${key}\"\\r\\n\\r\\n${value}`);\n}\nasync function* filePart(id, origin, input) {\n const filename = input.filename || `${origin}.${getExt(origin)}`;\n if (filename.includes(\"\\r\") || filename.includes(\"\\n\")) {\n throw new Error(`File paths cannot contain carriage-return (\\\\r) \\\nor newline (\\\\n) characters! Filename for property '${origin}' was:\n\"\"\"\n${filename}\n\"\"\"`);\n }\n yield enc.encode(`content-disposition:form-data;name=\"${id}\";filename=${filename}\\r\\ncontent-type:application/octet-stream\\r\\n\\r\\n`);\n const data = await input.toRaw();\n if (data instanceof Uint8Array) yield data;\n else yield* data;\n}\nfunction getExt(key) {\n switch(key){\n case \"certificate\":\n return \"pem\";\n case \"photo\":\n case \"thumbnail\":\n return \"jpg\";\n case \"voice\":\n return \"ogg\";\n case \"audio\":\n return \"mp3\";\n case \"animation\":\n case \"video\":\n case \"video_note\":\n return \"mp4\";\n case \"sticker\":\n return \"webp\";\n default:\n return \"dat\";\n }\n}\nconst debug1 = browser$1(\"grammy:core\");\nfunction concatTransformer(prev, trans) {\n return (method, payload, signal)=>trans(prev, method, payload, signal);\n}\nclass ApiClient {\n token;\n webhookReplyEnvelope;\n options;\n fetch;\n hasUsedWebhookReply;\n installedTransformers;\n constructor(token, options = {}, webhookReplyEnvelope = {}){\n this.token = token;\n this.webhookReplyEnvelope = webhookReplyEnvelope;\n this.hasUsedWebhookReply = false;\n this.installedTransformers = [];\n this.call = async (method, p, signal)=>{\n const payload = p ?? {};\n debug1(`Calling ${method}`);\n if (signal !== undefined) validateSignal(method, payload, signal);\n const opts = this.options;\n const formDataRequired = requiresFormDataUpload(payload);\n if (this.webhookReplyEnvelope.send !== undefined && !this.hasUsedWebhookReply && !formDataRequired && opts.canUseWebhookReply(method)) {\n this.hasUsedWebhookReply = true;\n const config = createJsonPayload({\n ...payload,\n method\n });\n await this.webhookReplyEnvelope.send(config.body);\n return {\n ok: true,\n result: true\n };\n }\n const controller = createAbortControllerFromSignal(signal);\n const timeout = createTimeout(controller, opts.timeoutSeconds, method);\n const streamErr = createStreamError(controller);\n const url = opts.buildUrl(opts.apiRoot, this.token, method, opts.environment);\n const config = formDataRequired ? createFormDataPayload(payload, (err)=>streamErr.catch(err)) : createJsonPayload(payload);\n const sig = controller.signal;\n const options = {\n ...opts.baseFetchConfig,\n signal: sig,\n ...config\n };\n const successPromise = this.fetch(url, options).then((res)=>res.json());\n const operations = [\n successPromise,\n streamErr.promise,\n timeout.promise\n ];\n try {\n return await Promise.race(operations);\n } catch (error) {\n throw toHttpError(method, opts.sensitiveLogs, error);\n } finally{\n if (timeout.handle !== undefined) clearTimeout(timeout.handle);\n }\n };\n const apiRoot = options.apiRoot ?? \"https://api.telegram.org\";\n const environment = options.environment ?? \"prod\";\n const { fetch: customFetch } = options;\n const fetchFn = customFetch ?? fetch;\n this.options = {\n apiRoot,\n environment,\n buildUrl: options.buildUrl ?? defaultBuildUrl,\n timeoutSeconds: options.timeoutSeconds ?? 500,\n baseFetchConfig: {\n ...baseFetchConfig(apiRoot),\n ...options.baseFetchConfig\n },\n canUseWebhookReply: options.canUseWebhookReply ?? (()=>false),\n sensitiveLogs: options.sensitiveLogs ?? false,\n fetch: (...args)=>fetchFn(...args)\n };\n this.fetch = this.options.fetch;\n if (this.options.apiRoot.endsWith(\"/\")) {\n throw new Error(`Remove the trailing '/' from the 'apiRoot' option (use '${this.options.apiRoot.substring(0, this.options.apiRoot.length - 1)}' instead of '${this.options.apiRoot}')`);\n }\n }\n call;\n use(...transformers) {\n this.call = transformers.reduce(concatTransformer, this.call);\n this.installedTransformers.push(...transformers);\n return this;\n }\n async callApi(method, payload, signal) {\n const data = await this.call(method, payload, signal);\n if (data.ok) return data.result;\n else throw toGrammyError(data, method, payload);\n }\n}\nfunction createRawApi(token, options, webhookReplyEnvelope) {\n const client = new ApiClient(token, options, webhookReplyEnvelope);\n const proxyHandler = {\n get (_, m) {\n return m === \"toJSON\" ? \"__internal\" : m === \"getMe\" || m === \"getWebhookInfo\" || m === \"getForumTopicIconStickers\" || m === \"getAvailableGifts\" || m === \"logOut\" || m === \"close\" || m === \"getMyStarBalance\" || m === \"removeMyProfilePhoto\" ? client.callApi.bind(client, m, {}) : client.callApi.bind(client, m);\n },\n ...proxyMethods\n };\n const raw = new Proxy({}, proxyHandler);\n const installedTransformers = client.installedTransformers;\n const api = {\n raw,\n installedTransformers,\n use: (...t)=>{\n client.use(...t);\n return api;\n }\n };\n return api;\n}\nconst defaultBuildUrl = (root, token, method, env)=>{\n const prefix = env === \"test\" ? \"test/\" : \"\";\n return `${root}/bot${token}/${prefix}${method}`;\n};\nconst proxyMethods = {\n set () {\n return false;\n },\n defineProperty () {\n return false;\n },\n deleteProperty () {\n return false;\n },\n ownKeys () {\n return [];\n }\n};\nfunction createTimeout(controller, seconds, method) {\n let handle = undefined;\n const promise = new Promise((_, reject)=>{\n handle = setTimeout(()=>{\n const msg = `Request to '${method}' timed out after ${seconds} seconds`;\n reject(new Error(msg));\n controller.abort();\n }, 1000 * seconds);\n });\n return {\n promise,\n handle\n };\n}\nfunction createStreamError(abortController) {\n let onError = (err)=>{\n throw err;\n };\n const promise = new Promise((_, reject)=>{\n onError = (err)=>{\n reject(err);\n abortController.abort();\n };\n });\n return {\n promise,\n catch: onError\n };\n}\nfunction createAbortControllerFromSignal(signal) {\n const abortController = new AbortController();\n if (signal === undefined) return abortController;\n const sig = signal;\n function abort() {\n abortController.abort();\n sig.removeEventListener(\"abort\", abort);\n }\n if (sig.aborted) abort();\n else sig.addEventListener(\"abort\", abort);\n return {\n abort,\n signal: abortController.signal\n };\n}\nfunction validateSignal(method, payload, signal) {\n if (typeof signal?.addEventListener === \"function\") {\n return;\n }\n let payload0 = JSON.stringify(payload);\n if (payload0.length > 20) {\n payload0 = payload0.substring(0, 16) + \" ...\";\n }\n let payload1 = JSON.stringify(signal);\n if (payload1.length > 20) {\n payload1 = payload1.substring(0, 16) + \" ...\";\n }\n throw new Error(`Incorrect abort signal instance found! \\\nYou passed two payloads to '${method}' but you should merge \\\nthe second one containing '${payload1}' into the first one \\\ncontaining '${payload0}'! If you are using context shortcuts, \\\nyou may want to use a method on 'ctx.api' instead.\n\nIf you want to prevent such mistakes in the future, \\\nconsider using TypeScript. https://www.typescriptlang.org/`);\n}\nclass Api {\n token;\n options;\n raw;\n config;\n constructor(token, options, webhookReplyEnvelope){\n this.token = token;\n this.options = options;\n const { raw, use, installedTransformers } = createRawApi(token, options, webhookReplyEnvelope);\n this.raw = raw;\n this.config = {\n use,\n installedTransformers: ()=>installedTransformers.slice()\n };\n }\n getUpdates(other, signal) {\n return this.raw.getUpdates({\n ...other\n }, signal);\n }\n setWebhook(url, other, signal) {\n return this.raw.setWebhook({\n url,\n ...other\n }, signal);\n }\n deleteWebhook(other, signal) {\n return this.raw.deleteWebhook({\n ...other\n }, signal);\n }\n getWebhookInfo(signal) {\n return this.raw.getWebhookInfo(signal);\n }\n getMe(signal) {\n return this.raw.getMe(signal);\n }\n logOut(signal) {\n return this.raw.logOut(signal);\n }\n close(signal) {\n return this.raw.close(signal);\n }\n sendMessage(chat_id, text, other, signal) {\n return this.raw.sendMessage({\n chat_id,\n text,\n ...other\n }, signal);\n }\n sendMessageDraft(chat_id, draft_id, text, other, signal) {\n return this.raw.sendMessageDraft({\n chat_id,\n draft_id,\n text,\n ...other\n }, signal);\n }\n forwardMessage(chat_id, from_chat_id, message_id, other, signal) {\n return this.raw.forwardMessage({\n chat_id,\n from_chat_id,\n message_id,\n ...other\n }, signal);\n }\n forwardMessages(chat_id, from_chat_id, message_ids, other, signal) {\n return this.raw.forwardMessages({\n chat_id,\n from_chat_id,\n message_ids,\n ...other\n }, signal);\n }\n copyMessage(chat_id, from_chat_id, message_id, other, signal) {\n return this.raw.copyMessage({\n chat_id,\n from_chat_id,\n message_id,\n ...other\n }, signal);\n }\n copyMessages(chat_id, from_chat_id, message_ids, other, signal) {\n return this.raw.copyMessages({\n chat_id,\n from_chat_id,\n message_ids,\n ...other\n }, signal);\n }\n sendPhoto(chat_id, photo, other, signal) {\n return this.raw.sendPhoto({\n chat_id,\n photo,\n ...other\n }, signal);\n }\n sendAudio(chat_id, audio, other, signal) {\n return this.raw.sendAudio({\n chat_id,\n audio,\n ...other\n }, signal);\n }\n sendDocument(chat_id, document1, other, signal) {\n return this.raw.sendDocument({\n chat_id,\n document: document1,\n ...other\n }, signal);\n }\n sendVideo(chat_id, video, other, signal) {\n return this.raw.sendVideo({\n chat_id,\n video,\n ...other\n }, signal);\n }\n sendAnimation(chat_id, animation, other, signal) {\n return this.raw.sendAnimation({\n chat_id,\n animation,\n ...other\n }, signal);\n }\n sendVoice(chat_id, voice, other, signal) {\n return this.raw.sendVoice({\n chat_id,\n voice,\n ...other\n }, signal);\n }\n sendVideoNote(chat_id, video_note, other, signal) {\n return this.raw.sendVideoNote({\n chat_id,\n video_note,\n ...other\n }, signal);\n }\n sendMediaGroup(chat_id, media, other, signal) {\n return this.raw.sendMediaGroup({\n chat_id,\n media,\n ...other\n }, signal);\n }\n sendLocation(chat_id, latitude, longitude, other, signal) {\n return this.raw.sendLocation({\n chat_id,\n latitude,\n longitude,\n ...other\n }, signal);\n }\n editMessageLiveLocation(chat_id, message_id, latitude, longitude, other, signal) {\n return this.raw.editMessageLiveLocation({\n chat_id,\n message_id,\n latitude,\n longitude,\n ...other\n }, signal);\n }\n editMessageLiveLocationInline(inline_message_id, latitude, longitude, other, signal) {\n return this.raw.editMessageLiveLocation({\n inline_message_id,\n latitude,\n longitude,\n ...other\n }, signal);\n }\n stopMessageLiveLocation(chat_id, message_id, other, signal) {\n return this.raw.stopMessageLiveLocation({\n chat_id,\n message_id,\n ...other\n }, signal);\n }\n stopMessageLiveLocationInline(inline_message_id, other, signal) {\n return this.raw.stopMessageLiveLocation({\n inline_message_id,\n ...other\n }, signal);\n }\n sendPaidMedia(chat_id, star_count, media, other, signal) {\n return this.raw.sendPaidMedia({\n chat_id,\n star_count,\n media,\n ...other\n }, signal);\n }\n sendVenue(chat_id, latitude, longitude, title, address, other, signal) {\n return this.raw.sendVenue({\n chat_id,\n latitude,\n longitude,\n title,\n address,\n ...other\n }, signal);\n }\n sendContact(chat_id, phone_number, first_name, other, signal) {\n return this.raw.sendContact({\n chat_id,\n phone_number,\n first_name,\n ...other\n }, signal);\n }\n sendPoll(chat_id, question, options, other, signal) {\n const opts = options.map((o)=>typeof o === \"string\" ? {\n text: o\n } : o);\n return this.raw.sendPoll({\n chat_id,\n question,\n options: opts,\n ...other\n }, signal);\n }\n sendChecklist(business_connection_id, chat_id, checklist, other, signal) {\n return this.raw.sendChecklist({\n business_connection_id,\n chat_id,\n checklist,\n ...other\n }, signal);\n }\n editMessageChecklist(business_connection_id, chat_id, message_id, checklist, other, signal) {\n return this.raw.editMessageChecklist({\n business_connection_id,\n chat_id,\n message_id,\n checklist,\n ...other\n }, signal);\n }\n sendDice(chat_id, emoji, other, signal) {\n return this.raw.sendDice({\n chat_id,\n emoji,\n ...other\n }, signal);\n }\n setMessageReaction(chat_id, message_id, reaction, other, signal) {\n return this.raw.setMessageReaction({\n chat_id,\n message_id,\n reaction,\n ...other\n }, signal);\n }\n sendChatAction(chat_id, action, other, signal) {\n return this.raw.sendChatAction({\n chat_id,\n action,\n ...other\n }, signal);\n }\n getUserProfilePhotos(user_id, other, signal) {\n return this.raw.getUserProfilePhotos({\n user_id,\n ...other\n }, signal);\n }\n getUserProfileAudios(user_id, other, signal) {\n return this.raw.getUserProfileAudios({\n user_id,\n ...other\n }, signal);\n }\n setUserEmojiStatus(user_id, other, signal) {\n return this.raw.setUserEmojiStatus({\n user_id,\n ...other\n }, signal);\n }\n getUserChatBoosts(chat_id, user_id, signal) {\n return this.raw.getUserChatBoosts({\n chat_id,\n user_id\n }, signal);\n }\n getUserGifts(user_id, other, signal) {\n return this.raw.getUserGifts({\n user_id,\n ...other\n }, signal);\n }\n getChatGifts(chat_id, other, signal) {\n return this.raw.getChatGifts({\n chat_id,\n ...other\n }, signal);\n }\n getBusinessConnection(business_connection_id, signal) {\n return this.raw.getBusinessConnection({\n business_connection_id\n }, signal);\n }\n getFile(file_id, signal) {\n return this.raw.getFile({\n file_id\n }, signal);\n }\n kickChatMember(...args) {\n return this.banChatMember(...args);\n }\n banChatMember(chat_id, user_id, other, signal) {\n return this.raw.banChatMember({\n chat_id,\n user_id,\n ...other\n }, signal);\n }\n unbanChatMember(chat_id, user_id, other, signal) {\n return this.raw.unbanChatMember({\n chat_id,\n user_id,\n ...other\n }, signal);\n }\n restrictChatMember(chat_id, user_id, permissions, other, signal) {\n return this.raw.restrictChatMember({\n chat_id,\n user_id,\n permissions,\n ...other\n }, signal);\n }\n promoteChatMember(chat_id, user_id, other, signal) {\n return this.raw.promoteChatMember({\n chat_id,\n user_id,\n ...other\n }, signal);\n }\n setChatAdministratorCustomTitle(chat_id, user_id, custom_title, signal) {\n return this.raw.setChatAdministratorCustomTitle({\n chat_id,\n user_id,\n custom_title\n }, signal);\n }\n setChatMemberTag(chat_id, user_id, tag, signal) {\n return this.raw.setChatMemberTag({\n chat_id,\n user_id,\n tag\n }, signal);\n }\n banChatSenderChat(chat_id, sender_chat_id, signal) {\n return this.raw.banChatSenderChat({\n chat_id,\n sender_chat_id\n }, signal);\n }\n unbanChatSenderChat(chat_id, sender_chat_id, signal) {\n return this.raw.unbanChatSenderChat({\n chat_id,\n sender_chat_id\n }, signal);\n }\n setChatPermissions(chat_id, permissions, other, signal) {\n return this.raw.setChatPermissions({\n chat_id,\n permissions,\n ...other\n }, signal);\n }\n exportChatInviteLink(chat_id, signal) {\n return this.raw.exportChatInviteLink({\n chat_id\n }, signal);\n }\n createChatInviteLink(chat_id, other, signal) {\n return this.raw.createChatInviteLink({\n chat_id,\n ...other\n }, signal);\n }\n editChatInviteLink(chat_id, invite_link, other, signal) {\n return this.raw.editChatInviteLink({\n chat_id,\n invite_link,\n ...other\n }, signal);\n }\n createChatSubscriptionInviteLink(chat_id, subscription_period, subscription_price, other, signal) {\n return this.raw.createChatSubscriptionInviteLink({\n chat_id,\n subscription_period,\n subscription_price,\n ...other\n }, signal);\n }\n editChatSubscriptionInviteLink(chat_id, invite_link, other, signal) {\n return this.raw.editChatSubscriptionInviteLink({\n chat_id,\n invite_link,\n ...other\n }, signal);\n }\n revokeChatInviteLink(chat_id, invite_link, signal) {\n return this.raw.revokeChatInviteLink({\n chat_id,\n invite_link\n }, signal);\n }\n approveChatJoinRequest(chat_id, user_id, signal) {\n return this.raw.approveChatJoinRequest({\n chat_id,\n user_id\n }, signal);\n }\n declineChatJoinRequest(chat_id, user_id, signal) {\n return this.raw.declineChatJoinRequest({\n chat_id,\n user_id\n }, signal);\n }\n approveSuggestedPost(chat_id, message_id, other, signal) {\n return this.raw.approveSuggestedPost({\n chat_id,\n message_id,\n ...other\n }, signal);\n }\n declineSuggestedPost(chat_id, message_id, other, signal) {\n return this.raw.declineSuggestedPost({\n chat_id,\n message_id,\n ...other\n }, signal);\n }\n setChatPhoto(chat_id, photo, signal) {\n return this.raw.setChatPhoto({\n chat_id,\n photo\n }, signal);\n }\n deleteChatPhoto(chat_id, signal) {\n return this.raw.deleteChatPhoto({\n chat_id\n }, signal);\n }\n setChatTitle(chat_id, title, signal) {\n return this.raw.setChatTitle({\n chat_id,\n title\n }, signal);\n }\n setChatDescription(chat_id, description, signal) {\n return this.raw.setChatDescription({\n chat_id,\n description\n }, signal);\n }\n pinChatMessage(chat_id, message_id, other, signal) {\n return this.raw.pinChatMessage({\n chat_id,\n message_id,\n ...other\n }, signal);\n }\n unpinChatMessage(chat_id, message_id, other, signal) {\n return this.raw.unpinChatMessage({\n chat_id,\n message_id,\n ...other\n }, signal);\n }\n unpinAllChatMessages(chat_id, signal) {\n return this.raw.unpinAllChatMessages({\n chat_id\n }, signal);\n }\n leaveChat(chat_id, signal) {\n return this.raw.leaveChat({\n chat_id\n }, signal);\n }\n getChat(chat_id, signal) {\n return this.raw.getChat({\n chat_id\n }, signal);\n }\n getChatAdministrators(chat_id, signal) {\n return this.raw.getChatAdministrators({\n chat_id\n }, signal);\n }\n getChatMembersCount(...args) {\n return this.getChatMemberCount(...args);\n }\n getChatMemberCount(chat_id, signal) {\n return this.raw.getChatMemberCount({\n chat_id\n }, signal);\n }\n getChatMember(chat_id, user_id, signal) {\n return this.raw.getChatMember({\n chat_id,\n user_id\n }, signal);\n }\n setChatStickerSet(chat_id, sticker_set_name, signal) {\n return this.raw.setChatStickerSet({\n chat_id,\n sticker_set_name\n }, signal);\n }\n deleteChatStickerSet(chat_id, signal) {\n return this.raw.deleteChatStickerSet({\n chat_id\n }, signal);\n }\n getForumTopicIconStickers(signal) {\n return this.raw.getForumTopicIconStickers(signal);\n }\n createForumTopic(chat_id, name, other, signal) {\n return this.raw.createForumTopic({\n chat_id,\n name,\n ...other\n }, signal);\n }\n editForumTopic(chat_id, message_thread_id, other, signal) {\n return this.raw.editForumTopic({\n chat_id,\n message_thread_id,\n ...other\n }, signal);\n }\n closeForumTopic(chat_id, message_thread_id, signal) {\n return this.raw.closeForumTopic({\n chat_id,\n message_thread_id\n }, signal);\n }\n reopenForumTopic(chat_id, message_thread_id, signal) {\n return this.raw.reopenForumTopic({\n chat_id,\n message_thread_id\n }, signal);\n }\n deleteForumTopic(chat_id, message_thread_id, signal) {\n return this.raw.deleteForumTopic({\n chat_id,\n message_thread_id\n }, signal);\n }\n unpinAllForumTopicMessages(chat_id, message_thread_id, signal) {\n return this.raw.unpinAllForumTopicMessages({\n chat_id,\n message_thread_id\n }, signal);\n }\n editGeneralForumTopic(chat_id, name, signal) {\n return this.raw.editGeneralForumTopic({\n chat_id,\n name\n }, signal);\n }\n closeGeneralForumTopic(chat_id, signal) {\n return this.raw.closeGeneralForumTopic({\n chat_id\n }, signal);\n }\n reopenGeneralForumTopic(chat_id, signal) {\n return this.raw.reopenGeneralForumTopic({\n chat_id\n }, signal);\n }\n hideGeneralForumTopic(chat_id, signal) {\n return this.raw.hideGeneralForumTopic({\n chat_id\n }, signal);\n }\n unhideGeneralForumTopic(chat_id, signal) {\n return this.raw.unhideGeneralForumTopic({\n chat_id\n }, signal);\n }\n unpinAllGeneralForumTopicMessages(chat_id, signal) {\n return this.raw.unpinAllGeneralForumTopicMessages({\n chat_id\n }, signal);\n }\n answerCallbackQuery(callback_query_id, other, signal) {\n return this.raw.answerCallbackQuery({\n callback_query_id,\n ...other\n }, signal);\n }\n setMyName(name, other, signal) {\n return this.raw.setMyName({\n name,\n ...other\n }, signal);\n }\n getMyName(other, signal) {\n return this.raw.getMyName(other ?? {}, signal);\n }\n setMyCommands(commands, other, signal) {\n return this.raw.setMyCommands({\n commands,\n ...other\n }, signal);\n }\n deleteMyCommands(other, signal) {\n return this.raw.deleteMyCommands({\n ...other\n }, signal);\n }\n getMyCommands(other, signal) {\n return this.raw.getMyCommands({\n ...other\n }, signal);\n }\n setMyDescription(description, other, signal) {\n return this.raw.setMyDescription({\n description,\n ...other\n }, signal);\n }\n getMyDescription(other, signal) {\n return this.raw.getMyDescription({\n ...other\n }, signal);\n }\n setMyShortDescription(short_description, other, signal) {\n return this.raw.setMyShortDescription({\n short_description,\n ...other\n }, signal);\n }\n getMyShortDescription(other, signal) {\n return this.raw.getMyShortDescription({\n ...other\n }, signal);\n }\n setMyProfilePhoto(photo, signal) {\n return this.raw.setMyProfilePhoto({\n photo\n }, signal);\n }\n removeMyProfilePhoto(signal) {\n return this.raw.removeMyProfilePhoto(signal);\n }\n setChatMenuButton(other, signal) {\n return this.raw.setChatMenuButton({\n ...other\n }, signal);\n }\n getChatMenuButton(other, signal) {\n return this.raw.getChatMenuButton({\n ...other\n }, signal);\n }\n setMyDefaultAdministratorRights(other, signal) {\n return this.raw.setMyDefaultAdministratorRights({\n ...other\n }, signal);\n }\n getMyDefaultAdministratorRights(other, signal) {\n return this.raw.getMyDefaultAdministratorRights({\n ...other\n }, signal);\n }\n getMyStarBalance(signal) {\n return this.raw.getMyStarBalance(signal);\n }\n editMessageText(chat_id, message_id, text, other, signal) {\n return this.raw.editMessageText({\n chat_id,\n message_id,\n text,\n ...other\n }, signal);\n }\n editMessageTextInline(inline_message_id, text, other, signal) {\n return this.raw.editMessageText({\n inline_message_id,\n text,\n ...other\n }, signal);\n }\n editMessageCaption(chat_id, message_id, other, signal) {\n return this.raw.editMessageCaption({\n chat_id,\n message_id,\n ...other\n }, signal);\n }\n editMessageCaptionInline(inline_message_id, other, signal) {\n return this.raw.editMessageCaption({\n inline_message_id,\n ...other\n }, signal);\n }\n editMessageMedia(chat_id, message_id, media, other, signal) {\n return this.raw.editMessageMedia({\n chat_id,\n message_id,\n media,\n ...other\n }, signal);\n }\n editMessageMediaInline(inline_message_id, media, other, signal) {\n return this.raw.editMessageMedia({\n inline_message_id,\n media,\n ...other\n }, signal);\n }\n editMessageReplyMarkup(chat_id, message_id, other, signal) {\n return this.raw.editMessageReplyMarkup({\n chat_id,\n message_id,\n ...other\n }, signal);\n }\n editMessageReplyMarkupInline(inline_message_id, other, signal) {\n return this.raw.editMessageReplyMarkup({\n inline_message_id,\n ...other\n }, signal);\n }\n stopPoll(chat_id, message_id, other, signal) {\n return this.raw.stopPoll({\n chat_id,\n message_id,\n ...other\n }, signal);\n }\n deleteMessage(chat_id, message_id, signal) {\n return this.raw.deleteMessage({\n chat_id,\n message_id\n }, signal);\n }\n deleteMessages(chat_id, message_ids, signal) {\n return this.raw.deleteMessages({\n chat_id,\n message_ids\n }, signal);\n }\n deleteBusinessMessages(business_connection_id, message_ids, signal) {\n return this.raw.deleteBusinessMessages({\n business_connection_id,\n message_ids\n }, signal);\n }\n setBusinessAccountName(business_connection_id, first_name, other, signal) {\n return this.raw.setBusinessAccountName({\n business_connection_id,\n first_name,\n ...other\n }, signal);\n }\n setBusinessAccountUsername(business_connection_id, username, signal) {\n return this.raw.setBusinessAccountUsername({\n business_connection_id,\n username\n }, signal);\n }\n setBusinessAccountBio(business_connection_id, bio, signal) {\n return this.raw.setBusinessAccountBio({\n business_connection_id,\n bio\n }, signal);\n }\n setBusinessAccountProfilePhoto(business_connection_id, photo, other, signal) {\n return this.raw.setBusinessAccountProfilePhoto({\n business_connection_id,\n photo,\n ...other\n }, signal);\n }\n removeBusinessAccountProfilePhoto(business_connection_id, other, signal) {\n return this.raw.removeBusinessAccountProfilePhoto({\n business_connection_id,\n ...other\n }, signal);\n }\n setBusinessAccountGiftSettings(business_connection_id, show_gift_button, accepted_gift_types, signal) {\n return this.raw.setBusinessAccountGiftSettings({\n business_connection_id,\n show_gift_button,\n accepted_gift_types\n }, signal);\n }\n getBusinessAccountStarBalance(business_connection_id, signal) {\n return this.raw.getBusinessAccountStarBalance({\n business_connection_id\n }, signal);\n }\n transferBusinessAccountStars(business_connection_id, star_count, signal) {\n return this.raw.transferBusinessAccountStars({\n business_connection_id,\n star_count\n }, signal);\n }\n getBusinessAccountGifts(business_connection_id, other, signal) {\n return this.raw.getBusinessAccountGifts({\n business_connection_id,\n ...other\n }, signal);\n }\n convertGiftToStars(business_connection_id, owned_gift_id, signal) {\n return this.raw.convertGiftToStars({\n business_connection_id,\n owned_gift_id\n }, signal);\n }\n upgradeGift(business_connection_id, owned_gift_id, other, signal) {\n return this.raw.upgradeGift({\n business_connection_id,\n owned_gift_id,\n ...other\n }, signal);\n }\n transferGift(business_connection_id, owned_gift_id, new_owner_chat_id, star_count, signal) {\n return this.raw.transferGift({\n business_connection_id,\n owned_gift_id,\n new_owner_chat_id,\n star_count\n }, signal);\n }\n postStory(business_connection_id, content, active_period, other, signal) {\n return this.raw.postStory({\n business_connection_id,\n content,\n active_period,\n ...other\n }, signal);\n }\n repostStory(business_connection_id, from_chat_id, from_story_id, active_period, other, signal) {\n return this.raw.repostStory({\n business_connection_id,\n from_chat_id,\n from_story_id,\n active_period,\n ...other\n }, signal);\n }\n editStory(business_connection_id, story_id, content, other, signal) {\n return this.raw.editStory({\n business_connection_id,\n story_id,\n content,\n ...other\n }, signal);\n }\n deleteStory(business_connection_id, story_id, signal) {\n return this.raw.deleteStory({\n business_connection_id,\n story_id\n }, signal);\n }\n sendSticker(chat_id, sticker, other, signal) {\n return this.raw.sendSticker({\n chat_id,\n sticker,\n ...other\n }, signal);\n }\n getStickerSet(name, signal) {\n return this.raw.getStickerSet({\n name\n }, signal);\n }\n getCustomEmojiStickers(custom_emoji_ids, signal) {\n return this.raw.getCustomEmojiStickers({\n custom_emoji_ids\n }, signal);\n }\n uploadStickerFile(user_id, sticker_format, sticker, signal) {\n return this.raw.uploadStickerFile({\n user_id,\n sticker_format,\n sticker\n }, signal);\n }\n createNewStickerSet(user_id, name, title, stickers, other, signal) {\n return this.raw.createNewStickerSet({\n user_id,\n name,\n title,\n stickers,\n ...other\n }, signal);\n }\n addStickerToSet(user_id, name, sticker, signal) {\n return this.raw.addStickerToSet({\n user_id,\n name,\n sticker\n }, signal);\n }\n setStickerPositionInSet(sticker, position, signal) {\n return this.raw.setStickerPositionInSet({\n sticker,\n position\n }, signal);\n }\n deleteStickerFromSet(sticker, signal) {\n return this.raw.deleteStickerFromSet({\n sticker\n }, signal);\n }\n replaceStickerInSet(user_id, name, old_sticker, sticker, signal) {\n return this.raw.replaceStickerInSet({\n user_id,\n name,\n old_sticker,\n sticker\n }, signal);\n }\n setStickerEmojiList(sticker, emoji_list, signal) {\n return this.raw.setStickerEmojiList({\n sticker,\n emoji_list\n }, signal);\n }\n setStickerKeywords(sticker, keywords, signal) {\n return this.raw.setStickerKeywords({\n sticker,\n keywords\n }, signal);\n }\n setStickerMaskPosition(sticker, mask_position, signal) {\n return this.raw.setStickerMaskPosition({\n sticker,\n mask_position\n }, signal);\n }\n setStickerSetTitle(name, title, signal) {\n return this.raw.setStickerSetTitle({\n name,\n title\n }, signal);\n }\n deleteStickerSet(name, signal) {\n return this.raw.deleteStickerSet({\n name\n }, signal);\n }\n setStickerSetThumbnail(name, user_id, thumbnail, format, signal) {\n return this.raw.setStickerSetThumbnail({\n name,\n user_id,\n thumbnail,\n format\n }, signal);\n }\n setCustomEmojiStickerSetThumbnail(name, custom_emoji_id, signal) {\n return this.raw.setCustomEmojiStickerSetThumbnail({\n name,\n custom_emoji_id\n }, signal);\n }\n getAvailableGifts(signal) {\n return this.raw.getAvailableGifts(signal);\n }\n sendGift(user_id, gift_id, other, signal) {\n return this.raw.sendGift({\n user_id,\n gift_id,\n ...other\n }, signal);\n }\n giftPremiumSubscription(user_id, month_count, star_count, other, signal) {\n return this.raw.giftPremiumSubscription({\n user_id,\n month_count,\n star_count,\n ...other\n }, signal);\n }\n sendGiftToChannel(chat_id, gift_id, other, signal) {\n return this.raw.sendGift({\n chat_id,\n gift_id,\n ...other\n }, signal);\n }\n answerInlineQuery(inline_query_id, results, other, signal) {\n return this.raw.answerInlineQuery({\n inline_query_id,\n results,\n ...other\n }, signal);\n }\n answerWebAppQuery(web_app_query_id, result, signal) {\n return this.raw.answerWebAppQuery({\n web_app_query_id,\n result\n }, signal);\n }\n savePreparedInlineMessage(user_id, result, other, signal) {\n return this.raw.savePreparedInlineMessage({\n user_id,\n result,\n ...other\n }, signal);\n }\n sendInvoice(chat_id, title, description, payload, currency, prices, other, signal) {\n return this.raw.sendInvoice({\n chat_id,\n title,\n description,\n payload,\n currency,\n prices,\n ...other\n }, signal);\n }\n createInvoiceLink(title, description, payload, provider_token, currency, prices, other, signal) {\n return this.raw.createInvoiceLink({\n title,\n description,\n payload,\n provider_token,\n currency,\n prices,\n ...other\n }, signal);\n }\n answerShippingQuery(shipping_query_id, ok, other, signal) {\n return this.raw.answerShippingQuery({\n shipping_query_id,\n ok,\n ...other\n }, signal);\n }\n answerPreCheckoutQuery(pre_checkout_query_id, ok, other, signal) {\n return this.raw.answerPreCheckoutQuery({\n pre_checkout_query_id,\n ok,\n ...other\n }, signal);\n }\n getStarTransactions(other, signal) {\n return this.raw.getStarTransactions({\n ...other\n }, signal);\n }\n refundStarPayment(user_id, telegram_payment_charge_id, signal) {\n return this.raw.refundStarPayment({\n user_id,\n telegram_payment_charge_id\n }, signal);\n }\n editUserStarSubscription(user_id, telegram_payment_charge_id, is_canceled, signal) {\n return this.raw.editUserStarSubscription({\n user_id,\n telegram_payment_charge_id,\n is_canceled\n }, signal);\n }\n verifyUser(user_id, other, signal) {\n return this.raw.verifyUser({\n user_id,\n ...other\n }, signal);\n }\n verifyChat(chat_id, other, signal) {\n return this.raw.verifyChat({\n chat_id,\n ...other\n }, signal);\n }\n removeUserVerification(user_id, signal) {\n return this.raw.removeUserVerification({\n user_id\n }, signal);\n }\n removeChatVerification(chat_id, signal) {\n return this.raw.removeChatVerification({\n chat_id\n }, signal);\n }\n readBusinessMessage(business_connection_id, chat_id, message_id, signal) {\n return this.raw.readBusinessMessage({\n business_connection_id,\n chat_id,\n message_id\n }, signal);\n }\n setPassportDataErrors(user_id, errors, signal) {\n return this.raw.setPassportDataErrors({\n user_id,\n errors\n }, signal);\n }\n sendGame(chat_id, game_short_name, other, signal) {\n return this.raw.sendGame({\n chat_id,\n game_short_name,\n ...other\n }, signal);\n }\n setGameScore(chat_id, message_id, user_id, score, other, signal) {\n return this.raw.setGameScore({\n chat_id,\n message_id,\n user_id,\n score,\n ...other\n }, signal);\n }\n setGameScoreInline(inline_message_id, user_id, score, other, signal) {\n return this.raw.setGameScore({\n inline_message_id,\n user_id,\n score,\n ...other\n }, signal);\n }\n getGameHighScores(chat_id, message_id, user_id, signal) {\n return this.raw.getGameHighScores({\n chat_id,\n message_id,\n user_id\n }, signal);\n }\n getGameHighScoresInline(inline_message_id, user_id, signal) {\n return this.raw.getGameHighScores({\n inline_message_id,\n user_id\n }, signal);\n }\n}\nconst debug2 = browser$1(\"grammy:bot\");\nconst debugWarn = browser$1(\"grammy:warn\");\nconst debugErr = browser$1(\"grammy:error\");\nconst DEFAULT_UPDATE_TYPES = [\n \"message\",\n \"edited_message\",\n \"channel_post\",\n \"edited_channel_post\",\n \"business_connection\",\n \"business_message\",\n \"edited_business_message\",\n \"deleted_business_messages\",\n \"inline_query\",\n \"chosen_inline_result\",\n \"callback_query\",\n \"shipping_query\",\n \"pre_checkout_query\",\n \"purchased_paid_media\",\n \"poll\",\n \"poll_answer\",\n \"my_chat_member\",\n \"chat_join_request\",\n \"chat_boost\",\n \"removed_chat_boost\"\n];\nclass Bot extends Composer {\n token;\n pollingRunning;\n pollingAbortController;\n lastTriedUpdateId;\n api;\n me;\n mePromise;\n clientConfig;\n ContextConstructor;\n observedUpdateTypes;\n errorHandler;\n constructor(token, config){\n super();\n this.token = token;\n this.pollingRunning = false;\n this.lastTriedUpdateId = 0;\n this.observedUpdateTypes = new Set();\n this.errorHandler = async (err)=>{\n console.error(\"Error in middleware while handling update\", err.ctx?.update?.update_id, err.error);\n console.error(\"No error handler was set!\");\n console.error(\"Set your own error handler with `bot.catch = ...`\");\n if (this.pollingRunning) {\n console.error(\"Stopping bot\");\n await this.stop();\n }\n throw err;\n };\n if (!token) throw new Error(\"Empty token!\");\n this.me = config?.botInfo;\n this.clientConfig = config?.client;\n this.ContextConstructor = config?.ContextConstructor ?? Context;\n this.api = new Api(token, this.clientConfig);\n }\n set botInfo(botInfo) {\n this.me = botInfo;\n }\n get botInfo() {\n if (this.me === undefined) {\n throw new Error(\"Bot information unavailable! Make sure to call `await bot.init()` before accessing `bot.botInfo`!\");\n }\n return this.me;\n }\n on(filter, ...middleware) {\n for (const [u] of parse(filter).flatMap(preprocess)){\n this.observedUpdateTypes.add(u);\n }\n return super.on(filter, ...middleware);\n }\n reaction(reaction, ...middleware) {\n this.observedUpdateTypes.add(\"message_reaction\");\n return super.reaction(reaction, ...middleware);\n }\n isInited() {\n return this.me !== undefined;\n }\n async init(signal) {\n if (!this.isInited()) {\n debug2(\"Initializing bot\");\n this.mePromise ??= withRetries(()=>this.api.getMe(signal), signal);\n let me;\n try {\n me = await this.mePromise;\n } finally{\n this.mePromise = undefined;\n }\n if (this.me === undefined) this.me = me;\n else debug2(\"Bot info was set by now, will not overwrite\");\n }\n debug2(`I am ${this.me.username}!`);\n }\n async handleUpdates(updates) {\n for (const update of updates){\n this.lastTriedUpdateId = update.update_id;\n try {\n await this.handleUpdate(update);\n } catch (err) {\n if (err instanceof BotError) {\n await this.errorHandler(err);\n } else {\n console.error(\"FATAL: grammY unable to handle:\", err);\n throw err;\n }\n }\n }\n }\n async handleUpdate(update, webhookReplyEnvelope) {\n if (this.me === undefined) {\n throw new Error(\"Bot not initialized! Either call `await bot.init()`, \\\nor directly set the `botInfo` option in the `Bot` constructor to specify \\\na known bot info object.\");\n }\n debug2(`Processing update ${update.update_id}`);\n const api = new Api(this.token, this.clientConfig, webhookReplyEnvelope);\n const t = this.api.config.installedTransformers();\n if (t.length > 0) api.config.use(...t);\n const ctx = new this.ContextConstructor(update, api, this.me);\n try {\n await run(this.middleware(), ctx);\n } catch (err) {\n debugErr(`Error in middleware for update ${update.update_id}`);\n throw new BotError(err, ctx);\n }\n }\n async start(options) {\n const setup = [];\n if (!this.isInited()) {\n setup.push(this.init(this.pollingAbortController?.signal));\n }\n if (this.pollingRunning) {\n await Promise.all(setup);\n debug2(\"Simple long polling already running!\");\n return;\n }\n this.pollingRunning = true;\n this.pollingAbortController = new AbortController();\n try {\n setup.push(withRetries(async ()=>{\n await this.api.deleteWebhook({\n drop_pending_updates: options?.drop_pending_updates\n }, this.pollingAbortController?.signal);\n }, this.pollingAbortController?.signal));\n await Promise.all(setup);\n await options?.onStart?.(this.botInfo);\n } catch (err) {\n this.pollingRunning = false;\n this.pollingAbortController = undefined;\n throw err;\n }\n if (!this.pollingRunning) return;\n validateAllowedUpdates(this.observedUpdateTypes, options?.allowed_updates);\n this.use = noUseFunction;\n debug2(\"Starting simple long polling\");\n await this.loop(options);\n debug2(\"Middleware is done running\");\n }\n async stop() {\n if (this.pollingRunning) {\n debug2(\"Stopping bot, saving update offset\");\n this.pollingRunning = false;\n this.pollingAbortController?.abort();\n const offset = this.lastTriedUpdateId + 1;\n await this.api.getUpdates({\n offset,\n limit: 1\n }).finally(()=>this.pollingAbortController = undefined);\n } else {\n debug2(\"Bot is not running!\");\n }\n }\n isRunning() {\n return this.pollingRunning;\n }\n catch(errorHandler) {\n this.errorHandler = errorHandler;\n }\n async loop(options) {\n const limit = options?.limit;\n const timeout = options?.timeout ?? 30;\n let allowed_updates = options?.allowed_updates ?? [];\n try {\n while(this.pollingRunning){\n const updates = await this.fetchUpdates({\n limit,\n timeout,\n allowed_updates\n });\n if (updates === undefined) break;\n await this.handleUpdates(updates);\n allowed_updates = undefined;\n }\n } finally{\n this.pollingRunning = false;\n }\n }\n async fetchUpdates({ limit, timeout, allowed_updates }) {\n const offset = this.lastTriedUpdateId + 1;\n let updates = undefined;\n do {\n try {\n updates = await this.api.getUpdates({\n offset,\n limit,\n timeout,\n allowed_updates\n }, this.pollingAbortController?.signal);\n } catch (error) {\n await this.handlePollingError(error);\n }\n }while (updates === undefined && this.pollingRunning)\n return updates;\n }\n async handlePollingError(error) {\n if (!this.pollingRunning) {\n debug2(\"Pending getUpdates request cancelled\");\n return;\n }\n let sleepSeconds = 3;\n if (error instanceof GrammyError) {\n debugErr(error.message);\n if (error.error_code === 401 || error.error_code === 409) {\n throw error;\n } else if (error.error_code === 429) {\n debugErr(\"Bot API server is closing.\");\n sleepSeconds = error.parameters.retry_after ?? sleepSeconds;\n }\n } else debugErr(error);\n debugErr(`Call to getUpdates failed, retrying in ${sleepSeconds} seconds ...`);\n await sleep(sleepSeconds);\n }\n}\nasync function withRetries(task, signal) {\n const INITIAL_DELAY = 50;\n let lastDelay = 50;\n async function handleError(error) {\n let delay = false;\n let strategy = \"rethrow\";\n if (error instanceof HttpError) {\n delay = true;\n strategy = \"retry\";\n } else if (error instanceof GrammyError) {\n if (error.error_code >= 500) {\n delay = true;\n strategy = \"retry\";\n } else if (error.error_code === 429) {\n const retryAfter = error.parameters.retry_after;\n if (typeof retryAfter === \"number\") {\n await sleep(retryAfter, signal);\n lastDelay = INITIAL_DELAY;\n } else {\n delay = true;\n }\n strategy = \"retry\";\n }\n }\n if (delay) {\n if (lastDelay !== 50) {\n await sleep(lastDelay, signal);\n }\n const TWENTY_MINUTES = 20 * 60 * 1000;\n lastDelay = Math.min(TWENTY_MINUTES, 2 * lastDelay);\n }\n return strategy;\n }\n let result = {\n ok: false\n };\n while(!result.ok){\n try {\n result = {\n ok: true,\n value: await task()\n };\n } catch (error) {\n debugErr(error);\n const strategy = await handleError(error);\n switch(strategy){\n case \"retry\":\n continue;\n case \"rethrow\":\n throw error;\n }\n }\n }\n return result.value;\n}\nasync function sleep(seconds, signal) {\n let handle;\n let reject;\n function abort() {\n reject?.(new Error(\"Aborted delay\"));\n if (handle !== undefined) clearTimeout(handle);\n }\n try {\n await new Promise((res, rej)=>{\n reject = rej;\n if (signal?.aborted) {\n abort();\n return;\n }\n signal?.addEventListener(\"abort\", abort);\n handle = setTimeout(res, 1000 * seconds);\n });\n } finally{\n signal?.removeEventListener(\"abort\", abort);\n }\n}\nfunction validateAllowedUpdates(updates, allowed = DEFAULT_UPDATE_TYPES) {\n const impossible = Array.from(updates).filter((u)=>!allowed.includes(u));\n if (impossible.length > 0) {\n debugWarn(`You registered listeners for the following update types, \\\nbut you did not specify them in \\`allowed_updates\\` \\\nso they may not be received: ${impossible.map((u)=>`'${u}'`).join(\", \")}`);\n }\n}\nfunction noUseFunction() {\n throw new Error(`It looks like you are registering more listeners \\\non your bot from within other listeners! This means that every time your bot \\\nhandles a message like this one, new listeners will be added. This list grows until \\\nyour machine crashes, so grammY throws this error to tell you that you should \\\nprobably do things a bit differently. If you're unsure how to resolve this problem, \\\nyou can ask in the group chat: https://telegram.me/grammyjs\n\nOn the other hand, if you actually know what you're doing and you do need to install \\\nfurther middleware while your bot is running, consider installing a composer \\\ninstance on your bot, and in turn augment the composer after the fact. This way, \\\nyou can circumvent this protection against memory leaks.`);\n}\nconst ALL_UPDATE_TYPES = [\n ...DEFAULT_UPDATE_TYPES,\n \"chat_member\",\n \"message_reaction\",\n \"message_reaction_count\"\n];\nconst ALL_CHAT_PERMISSIONS = {\n can_send_messages: true,\n can_send_audios: true,\n can_send_documents: true,\n can_send_photos: true,\n can_send_videos: true,\n can_send_video_notes: true,\n can_send_voice_notes: true,\n can_send_polls: true,\n can_send_other_messages: true,\n can_add_web_page_previews: true,\n can_change_info: true,\n can_invite_users: true,\n can_edit_tag: true,\n can_pin_messages: true,\n can_manage_topics: true\n};\nconst API_CONSTANTS = {\n DEFAULT_UPDATE_TYPES,\n ALL_UPDATE_TYPES,\n ALL_CHAT_PERMISSIONS\n};\nObject.freeze(API_CONSTANTS);\nexport { API_CONSTANTS as API_CONSTANTS };\nfunction inputMessage(queryTemplate) {\n return {\n ...queryTemplate,\n ...inputMessageMethods(queryTemplate)\n };\n}\nfunction inputMessageMethods(queryTemplate) {\n return {\n text (message_text, options = {}) {\n const content = {\n message_text,\n ...options\n };\n return {\n ...queryTemplate,\n input_message_content: content\n };\n },\n location (latitude, longitude, options = {}) {\n const content = {\n latitude,\n longitude,\n ...options\n };\n return {\n ...queryTemplate,\n input_message_content: content\n };\n },\n venue (title, latitude, longitude, address, options) {\n const content = {\n title,\n latitude,\n longitude,\n address,\n ...options\n };\n return {\n ...queryTemplate,\n input_message_content: content\n };\n },\n contact (first_name, phone_number, options = {}) {\n const content = {\n first_name,\n phone_number,\n ...options\n };\n return {\n ...queryTemplate,\n input_message_content: content\n };\n },\n invoice (title, description, payload, provider_token, currency, prices, options = {}) {\n const content = {\n title,\n description,\n payload,\n provider_token,\n currency,\n prices,\n ...options\n };\n return {\n ...queryTemplate,\n input_message_content: content\n };\n }\n };\n}\nconst InlineQueryResultBuilder = {\n article (id, title, options = {}) {\n return inputMessageMethods({\n type: \"article\",\n id,\n title,\n ...options\n });\n },\n audio (id, title, audio_url, options = {}) {\n return inputMessage({\n type: \"audio\",\n id,\n title,\n audio_url: typeof audio_url === \"string\" ? audio_url : audio_url.href,\n ...options\n });\n },\n audioCached (id, audio_file_id, options = {}) {\n return inputMessage({\n type: \"audio\",\n id,\n audio_file_id,\n ...options\n });\n },\n contact (id, phone_number, first_name, options = {}) {\n return inputMessage({\n type: \"contact\",\n id,\n phone_number,\n first_name,\n ...options\n });\n },\n documentPdf (id, title, document_url, options = {}) {\n return inputMessage({\n type: \"document\",\n mime_type: \"application/pdf\",\n id,\n title,\n document_url: typeof document_url === \"string\" ? document_url : document_url.href,\n ...options\n });\n },\n documentZip (id, title, document_url, options = {}) {\n return inputMessage({\n type: \"document\",\n mime_type: \"application/zip\",\n id,\n title,\n document_url: typeof document_url === \"string\" ? document_url : document_url.href,\n ...options\n });\n },\n documentCached (id, title, document_file_id, options = {}) {\n return inputMessage({\n type: \"document\",\n id,\n title,\n document_file_id,\n ...options\n });\n },\n game (id, game_short_name, options = {}) {\n return {\n type: \"game\",\n id,\n game_short_name,\n ...options\n };\n },\n gif (id, gif_url, thumbnail_url, options = {}) {\n return inputMessage({\n type: \"gif\",\n id,\n gif_url: typeof gif_url === \"string\" ? gif_url : gif_url.href,\n thumbnail_url: typeof thumbnail_url === \"string\" ? thumbnail_url : thumbnail_url.href,\n ...options\n });\n },\n gifCached (id, gif_file_id, options = {}) {\n return inputMessage({\n type: \"gif\",\n id,\n gif_file_id,\n ...options\n });\n },\n location (id, title, latitude, longitude, options = {}) {\n return inputMessage({\n type: \"location\",\n id,\n title,\n latitude,\n longitude,\n ...options\n });\n },\n mpeg4gif (id, mpeg4_url, thumbnail_url, options = {}) {\n return inputMessage({\n type: \"mpeg4_gif\",\n id,\n mpeg4_url: typeof mpeg4_url === \"string\" ? mpeg4_url : mpeg4_url.href,\n thumbnail_url: typeof thumbnail_url === \"string\" ? thumbnail_url : thumbnail_url.href,\n ...options\n });\n },\n mpeg4gifCached (id, mpeg4_file_id, options = {}) {\n return inputMessage({\n type: \"mpeg4_gif\",\n id,\n mpeg4_file_id,\n ...options\n });\n },\n photo (id, photo_url, options = {}) {\n const photoUrl = typeof photo_url === \"string\" ? photo_url : photo_url.href;\n return inputMessage({\n type: \"photo\",\n id,\n photo_url: photoUrl,\n thumbnail_url: photoUrl,\n ...options\n });\n },\n photoCached (id, photo_file_id, options = {}) {\n return inputMessage({\n type: \"photo\",\n id,\n photo_file_id,\n ...options\n });\n },\n stickerCached (id, sticker_file_id, options = {}) {\n return inputMessage({\n type: \"sticker\",\n id,\n sticker_file_id,\n ...options\n });\n },\n venue (id, title, latitude, longitude, address, options = {}) {\n return inputMessage({\n type: \"venue\",\n id,\n title,\n latitude,\n longitude,\n address,\n ...options\n });\n },\n videoHtml (id, title, video_url, thumbnail_url, options = {}) {\n return inputMessageMethods({\n type: \"video\",\n mime_type: \"text/html\",\n id,\n title,\n video_url: typeof video_url === \"string\" ? video_url : video_url.href,\n thumbnail_url: typeof thumbnail_url === \"string\" ? thumbnail_url : thumbnail_url.href,\n ...options\n });\n },\n videoMp4 (id, title, video_url, thumbnail_url, options = {}) {\n return inputMessage({\n type: \"video\",\n mime_type: \"video/mp4\",\n id,\n title,\n video_url: typeof video_url === \"string\" ? video_url : video_url.href,\n thumbnail_url: typeof thumbnail_url === \"string\" ? thumbnail_url : thumbnail_url.href,\n ...options\n });\n },\n videoCached (id, title, video_file_id, options = {}) {\n return inputMessage({\n type: \"video\",\n id,\n title,\n video_file_id,\n ...options\n });\n },\n voice (id, title, voice_url, options = {}) {\n return inputMessage({\n type: \"voice\",\n id,\n title,\n voice_url: typeof voice_url === \"string\" ? voice_url : voice_url.href,\n ...options\n });\n },\n voiceCached (id, title, voice_file_id, options = {}) {\n return inputMessage({\n type: \"voice\",\n id,\n title,\n voice_file_id,\n ...options\n });\n }\n};\nexport { InlineQueryResultBuilder as InlineQueryResultBuilder };\nconst InputMediaBuilder = {\n photo (media, options = {}) {\n return {\n type: \"photo\",\n media,\n ...options\n };\n },\n video (media, options = {}) {\n return {\n type: \"video\",\n media,\n ...options\n };\n },\n animation (media, options = {}) {\n return {\n type: \"animation\",\n media,\n ...options\n };\n },\n audio (media, options = {}) {\n return {\n type: \"audio\",\n media,\n ...options\n };\n },\n document (media, options = {}) {\n return {\n type: \"document\",\n media,\n ...options\n };\n }\n};\nexport { InputMediaBuilder as InputMediaBuilder };\nclass Keyboard {\n keyboard;\n is_persistent;\n selective;\n one_time_keyboard;\n resize_keyboard;\n input_field_placeholder;\n constructor(keyboard = [\n []\n ]){\n this.keyboard = keyboard;\n }\n add(...buttons) {\n this.keyboard[this.keyboard.length - 1]?.push(...buttons);\n return this;\n }\n row(...buttons) {\n this.keyboard.push(buttons);\n return this;\n }\n text(text, options) {\n return this.add(Keyboard.text(text, options));\n }\n static text(text, options) {\n return typeof options === \"string\" ? {\n text,\n style: options\n } : {\n text,\n ...options\n };\n }\n requestUsers(text, requestId, options = {}) {\n return this.add(Keyboard.requestUsers(text, requestId, options));\n }\n static requestUsers(text, requestId, options = {}) {\n return typeof text === \"string\" ? {\n text,\n request_users: {\n request_id: requestId,\n ...options\n }\n } : {\n ...text,\n request_users: {\n request_id: requestId,\n ...options\n }\n };\n }\n requestChat(text, requestId, options = {\n chat_is_channel: false\n }) {\n return this.add(Keyboard.requestChat(text, requestId, options));\n }\n static requestChat(text, requestId, options = {\n chat_is_channel: false\n }) {\n const request_chat = {\n request_id: requestId,\n ...options\n };\n return typeof text === \"string\" ? {\n text,\n request_chat\n } : {\n ...text,\n request_chat\n };\n }\n requestContact(text) {\n return this.add(Keyboard.requestContact(text));\n }\n static requestContact(text) {\n return typeof text === \"string\" ? {\n text,\n request_contact: true\n } : {\n ...text,\n request_contact: true\n };\n }\n requestLocation(text) {\n return this.add(Keyboard.requestLocation(text));\n }\n static requestLocation(text) {\n return typeof text === \"string\" ? {\n text,\n request_location: true\n } : {\n ...text,\n request_location: true\n };\n }\n requestPoll(text, type) {\n return this.add(Keyboard.requestPoll(text, type));\n }\n static requestPoll(text, type) {\n const request_poll = {\n type\n };\n return typeof text === \"string\" ? {\n text,\n request_poll\n } : {\n ...text,\n request_poll\n };\n }\n webApp(text, url) {\n return this.add(Keyboard.webApp(text, url));\n }\n static webApp(text, url) {\n const web_app = {\n url\n };\n return typeof text === \"string\" ? {\n text,\n web_app\n } : {\n ...text,\n web_app\n };\n }\n style(style) {\n const rows = this.keyboard.length;\n if (rows === 0) {\n throw new Error(\"Need to add a button before applying a style!\");\n }\n const lastRow = this.keyboard[rows - 1];\n const cols = lastRow.length;\n if (cols === 0) {\n throw new Error(\"Need to add a button before applying a style!\");\n }\n let lastButton = lastRow[cols - 1];\n if (typeof lastButton === \"string\") {\n lastButton = {\n text: lastButton\n };\n lastRow[cols - 1] = lastButton;\n }\n lastButton.style = style;\n return this;\n }\n danger() {\n return this.style(\"danger\");\n }\n success() {\n return this.style(\"success\");\n }\n primary() {\n return this.style(\"primary\");\n }\n icon(icon) {\n const rows = this.keyboard.length;\n if (rows === 0) {\n throw new Error(\"Need to add a button before adding an icon!\");\n }\n const lastRow = this.keyboard[rows - 1];\n const cols = lastRow.length;\n if (cols === 0) {\n throw new Error(\"Need to add a button before adding an icon!\");\n }\n let lastButton = lastRow[cols - 1];\n if (typeof lastButton === \"string\") {\n lastButton = {\n text: lastButton\n };\n lastRow[cols - 1] = lastButton;\n }\n lastButton.icon_custom_emoji_id = icon;\n return this;\n }\n persistent(isEnabled = true) {\n this.is_persistent = isEnabled;\n return this;\n }\n selected(isEnabled = true) {\n this.selective = isEnabled;\n return this;\n }\n oneTime(isEnabled = true) {\n this.one_time_keyboard = isEnabled;\n return this;\n }\n resized(isEnabled = true) {\n this.resize_keyboard = isEnabled;\n return this;\n }\n placeholder(value) {\n this.input_field_placeholder = value;\n return this;\n }\n toTransposed() {\n const original = this.keyboard;\n const transposed = transpose(original);\n return this.clone(transposed);\n }\n toFlowed(columns, options = {}) {\n const original = this.keyboard;\n const flowed = reflow(original, columns, options);\n return this.clone(flowed);\n }\n clone(keyboard = this.keyboard) {\n const clone = new Keyboard(keyboard.map((row)=>row.slice()));\n clone.is_persistent = this.is_persistent;\n clone.selective = this.selective;\n clone.one_time_keyboard = this.one_time_keyboard;\n clone.resize_keyboard = this.resize_keyboard;\n clone.input_field_placeholder = this.input_field_placeholder;\n return clone;\n }\n append(...sources) {\n for (const source of sources){\n const keyboard = Keyboard.from(source);\n this.keyboard.push(...keyboard.keyboard.map((row)=>row.slice()));\n }\n return this;\n }\n build() {\n return this.keyboard;\n }\n static from(source) {\n if (source instanceof Keyboard) return source.clone();\n function toButton(btn) {\n return typeof btn === \"string\" ? Keyboard.text(btn) : btn;\n }\n return new Keyboard(source.map((row)=>row.map(toButton)));\n }\n}\nclass InlineKeyboard {\n inline_keyboard;\n constructor(inline_keyboard = [\n []\n ]){\n this.inline_keyboard = inline_keyboard;\n }\n add(...buttons) {\n this.inline_keyboard[this.inline_keyboard.length - 1]?.push(...buttons);\n return this;\n }\n row(...buttons) {\n this.inline_keyboard.push(buttons);\n return this;\n }\n url(text, url) {\n return this.add(InlineKeyboard.url(text, url));\n }\n static url(text, url) {\n return typeof text === \"string\" ? {\n text,\n url\n } : {\n ...text,\n url\n };\n }\n text(text, data = typeof text === \"string\" ? text : text.text) {\n return this.add(InlineKeyboard.text(text, data));\n }\n static text(text, data = typeof text === \"string\" ? text : text.text) {\n return typeof text === \"string\" ? {\n text,\n callback_data: data\n } : {\n ...text,\n callback_data: data\n };\n }\n webApp(text, url) {\n return this.add(InlineKeyboard.webApp(text, url));\n }\n static webApp(text, url) {\n const web_app = typeof url === \"string\" ? {\n url\n } : url;\n return typeof text === \"string\" ? {\n text,\n web_app\n } : {\n ...text,\n web_app\n };\n }\n login(text, loginUrl) {\n return this.add(InlineKeyboard.login(text, loginUrl));\n }\n static login(text, loginUrl) {\n const login_url = typeof loginUrl === \"string\" ? {\n url: loginUrl\n } : loginUrl;\n return typeof text === \"string\" ? {\n text,\n login_url\n } : {\n ...text,\n login_url\n };\n }\n switchInline(text, query = \"\") {\n return this.add(InlineKeyboard.switchInline(text, query));\n }\n static switchInline(text, query = \"\") {\n return typeof text === \"string\" ? {\n text,\n switch_inline_query: query\n } : {\n ...text,\n switch_inline_query: query\n };\n }\n switchInlineCurrent(text, query = \"\") {\n return this.add(InlineKeyboard.switchInlineCurrent(text, query));\n }\n static switchInlineCurrent(text, query = \"\") {\n return typeof text === \"string\" ? {\n text,\n switch_inline_query_current_chat: query\n } : {\n ...text,\n switch_inline_query_current_chat: query\n };\n }\n switchInlineChosen(text, query = {}) {\n return this.add(InlineKeyboard.switchInlineChosen(text, query));\n }\n static switchInlineChosen(text, query = {}) {\n return typeof text === \"string\" ? {\n text,\n switch_inline_query_chosen_chat: query\n } : {\n ...text,\n switch_inline_query_chosen_chat: query\n };\n }\n copyText(text, copyText) {\n return this.add(InlineKeyboard.copyText(text, copyText));\n }\n static copyText(text, copyText) {\n const copy_text = typeof copyText === \"string\" ? {\n text: copyText\n } : copyText;\n return typeof text === \"string\" ? {\n text,\n copy_text\n } : {\n ...text,\n copy_text\n };\n }\n game(text) {\n return this.add(InlineKeyboard.game(text));\n }\n static game(text) {\n const callback_game = {};\n return typeof text === \"string\" ? {\n text,\n callback_game\n } : {\n ...text,\n callback_game\n };\n }\n pay(text) {\n return this.add(InlineKeyboard.pay(text));\n }\n static pay(text) {\n return typeof text === \"string\" ? {\n text,\n pay: true\n } : {\n ...text,\n pay: true\n };\n }\n style(style) {\n const rows = this.inline_keyboard.length;\n if (rows === 0) {\n throw new Error(\"Need to add a button before applying a style!\");\n }\n const lastRow = this.inline_keyboard[rows - 1];\n const cols = lastRow.length;\n if (cols === 0) {\n throw new Error(\"Need to add a button before applying a style!\");\n }\n lastRow[cols - 1].style = style;\n return this;\n }\n danger() {\n return this.style(\"danger\");\n }\n success() {\n return this.style(\"success\");\n }\n primary() {\n return this.style(\"primary\");\n }\n icon(icon) {\n const rows = this.inline_keyboard.length;\n if (rows === 0) {\n throw new Error(\"Need to add a button before adding an icon!\");\n }\n const lastRow = this.inline_keyboard[rows - 1];\n const cols = lastRow.length;\n if (cols === 0) {\n throw new Error(\"Need to add a button before adding an icon!\");\n }\n lastRow[cols - 1].icon_custom_emoji_id = icon;\n return this;\n }\n toTransposed() {\n const original = this.inline_keyboard;\n const transposed = transpose(original);\n return new InlineKeyboard(transposed);\n }\n toFlowed(columns, options = {}) {\n const original = this.inline_keyboard;\n const flowed = reflow(original, columns, options);\n return new InlineKeyboard(flowed);\n }\n clone() {\n return new InlineKeyboard(this.inline_keyboard.map((row)=>row.slice()));\n }\n append(...sources) {\n for (const source of sources){\n const keyboard = InlineKeyboard.from(source);\n this.inline_keyboard.push(...keyboard.inline_keyboard.map((row)=>row.slice()));\n }\n return this;\n }\n static from(source) {\n if (source instanceof InlineKeyboard) return source.clone();\n return new InlineKeyboard(source.map((row)=>row.slice()));\n }\n}\nfunction transpose(grid) {\n const transposed = [];\n for(let i = 0; i < grid.length; i++){\n const row = grid[i];\n for(let j = 0; j < row.length; j++){\n const button = row[j];\n (transposed[j] ??= []).push(button);\n }\n }\n return transposed;\n}\nfunction reflow(grid, columns, { fillLastRow = false }) {\n let first = columns;\n if (fillLastRow) {\n const buttonCount = grid.map((row)=>row.length).reduce((a, b)=>a + b, 0);\n first = buttonCount % columns;\n }\n const reflowed = [];\n for (const row of grid){\n for (const button of row){\n const at = Math.max(0, reflowed.length - 1);\n const max = at === 0 ? first : columns;\n let next = reflowed[at] ??= [];\n if (next.length === max) {\n next = [];\n reflowed.push(next);\n }\n next.push(button);\n }\n }\n return reflowed;\n}\nexport { Keyboard as Keyboard };\nexport { InlineKeyboard as InlineKeyboard };\nconst debug3 = browser$1(\"grammy:session\");\nfunction session(options = {}) {\n return options.type === \"multi\" ? strictMultiSession(options) : strictSingleSession(options);\n}\nfunction strictSingleSession(options) {\n const { initial, storage, getSessionKey, custom } = fillDefaults(options);\n return async (ctx, next)=>{\n const propSession = new PropertySession(storage, ctx, \"session\", initial);\n const key = await getSessionKey(ctx);\n await propSession.init(key, {\n custom,\n lazy: false\n });\n await next();\n await propSession.finish();\n };\n}\nfunction strictMultiSession(options) {\n const props = Object.keys(options).filter((k)=>k !== \"type\");\n const defaults = Object.fromEntries(props.map((prop)=>[\n prop,\n fillDefaults(options[prop])\n ]));\n return async (ctx, next)=>{\n ctx.session = {};\n const propSessions = await Promise.all(props.map(async (prop)=>{\n const { initial, storage, getSessionKey, custom } = defaults[prop];\n const s = new PropertySession(storage, ctx.session, prop, initial);\n const key = await getSessionKey(ctx);\n await s.init(key, {\n custom,\n lazy: false\n });\n return s;\n }));\n await next();\n if (ctx.session == null) propSessions.forEach((s)=>s.delete());\n await Promise.all(propSessions.map((s)=>s.finish()));\n };\n}\nfunction lazySession(options = {}) {\n if (options.type !== undefined && options.type !== \"single\") {\n throw new Error(\"Cannot use lazy multi sessions!\");\n }\n const { initial, storage, getSessionKey, custom } = fillDefaults(options);\n return async (ctx, next)=>{\n const propSession = new PropertySession(storage, ctx, \"session\", initial);\n const key = await getSessionKey(ctx);\n await propSession.init(key, {\n custom,\n lazy: true\n });\n await next();\n await propSession.finish();\n };\n}\nclass PropertySession {\n storage;\n obj;\n prop;\n initial;\n key;\n value;\n promise;\n fetching;\n read;\n wrote;\n constructor(storage, obj, prop, initial){\n this.storage = storage;\n this.obj = obj;\n this.prop = prop;\n this.initial = initial;\n this.fetching = false;\n this.read = false;\n this.wrote = false;\n }\n load() {\n if (this.key === undefined) {\n return;\n }\n if (this.wrote) {\n return;\n }\n if (this.promise === undefined) {\n this.fetching = true;\n this.promise = Promise.resolve(this.storage.read(this.key)).then((val)=>{\n this.fetching = false;\n if (this.wrote) {\n return this.value;\n }\n if (val !== undefined) {\n this.value = val;\n return val;\n }\n val = this.initial?.();\n if (val !== undefined) {\n this.wrote = true;\n this.value = val;\n }\n return val;\n });\n }\n return this.promise;\n }\n async init(key, opts) {\n this.key = key;\n if (!opts.lazy) await this.load();\n Object.defineProperty(this.obj, this.prop, {\n enumerable: true,\n get: ()=>{\n if (key === undefined) {\n const msg = undef(\"access\", opts);\n throw new Error(msg);\n }\n this.read = true;\n if (!opts.lazy || this.wrote) return this.value;\n this.load();\n return this.fetching ? this.promise : this.value;\n },\n set: (v)=>{\n if (key === undefined) {\n const msg = undef(\"assign\", opts);\n throw new Error(msg);\n }\n this.wrote = true;\n this.fetching = false;\n this.value = v;\n }\n });\n }\n delete() {\n Object.assign(this.obj, {\n [this.prop]: undefined\n });\n }\n async finish() {\n if (this.key !== undefined) {\n if (this.read) await this.load();\n if (this.read || this.wrote) {\n const value = await this.value;\n if (value == null) await this.storage.delete(this.key);\n else await this.storage.write(this.key, value);\n }\n }\n }\n}\nfunction fillDefaults(opts = {}) {\n let { prefix = \"\", getSessionKey = defaultGetSessionKey, initial, storage } = opts;\n if (storage == null) {\n debug3(\"Storing session data in memory, all data will be lost when the bot restarts.\");\n storage = new MemorySessionStorage();\n }\n const custom = getSessionKey !== defaultGetSessionKey;\n return {\n initial,\n storage,\n getSessionKey: async (ctx)=>{\n const key = await getSessionKey(ctx);\n return key === undefined ? undefined : prefix + key;\n },\n custom\n };\n}\nfunction defaultGetSessionKey(ctx) {\n return ctx.chatId?.toString();\n}\nfunction undef(op, opts) {\n const { lazy = false, custom } = opts;\n const reason = custom ? \"the custom `getSessionKey` function returned undefined for this update\" : \"this update does not belong to a chat, so the session key is undefined\";\n return `Cannot ${op} ${lazy ? \"lazy \" : \"\"}session data because ${reason}!`;\n}\nfunction isEnhance(value) {\n return value === undefined || typeof value === \"object\" && value !== null && \"__d\" in value;\n}\nfunction enhanceStorage(options) {\n let { storage, millisecondsToLive, migrations } = options;\n storage = compatStorage(storage);\n if (millisecondsToLive !== undefined) {\n storage = timeoutStorage(storage, millisecondsToLive);\n }\n if (migrations !== undefined) {\n storage = migrationStorage(storage, migrations);\n }\n return wrapStorage(storage);\n}\nfunction compatStorage(storage) {\n return {\n read: async (k)=>{\n const v = await storage.read(k);\n return isEnhance(v) ? v : {\n __d: v\n };\n },\n write: (k, v)=>storage.write(k, v),\n delete: (k)=>storage.delete(k)\n };\n}\nfunction timeoutStorage(storage, millisecondsToLive) {\n const ttlStorage = {\n read: async (k)=>{\n const value = await storage.read(k);\n if (value === undefined) return undefined;\n if (value.e === undefined) {\n await ttlStorage.write(k, value);\n return value;\n }\n if (value.e < Date.now()) {\n await ttlStorage.delete(k);\n return undefined;\n }\n return value;\n },\n write: async (k, v)=>{\n v.e = addExpiryDate(v, millisecondsToLive).expires;\n await storage.write(k, v);\n },\n delete: (k)=>storage.delete(k)\n };\n return ttlStorage;\n}\nfunction migrationStorage(storage, migrations) {\n const versions = Object.keys(migrations).map((v)=>parseInt(v)).sort((a, b)=>a - b);\n const count = versions.length;\n if (count === 0) throw new Error(\"No migrations given!\");\n const earliest = versions[0];\n const last = count - 1;\n const latest = versions[last];\n const index = new Map();\n versions.forEach((v, i)=>index.set(v, i));\n function nextAfter(current) {\n let i = last;\n while(current <= versions[i])i--;\n return i;\n }\n return {\n read: async (k)=>{\n const val = await storage.read(k);\n if (val === undefined) return val;\n let { __d: value, v: current = earliest - 1 } = val;\n let i = 1 + (index.get(current) ?? nextAfter(current));\n for(; i < count; i++)value = migrations[versions[i]](value);\n return {\n ...val,\n v: latest,\n __d: value\n };\n },\n write: (k, v)=>storage.write(k, {\n v: latest,\n ...v\n }),\n delete: (k)=>storage.delete(k)\n };\n}\nfunction wrapStorage(storage) {\n return {\n read: (k)=>Promise.resolve(storage.read(k)).then((v)=>v?.__d),\n write: (k, v)=>storage.write(k, {\n __d: v\n }),\n delete: (k)=>storage.delete(k)\n };\n}\nclass MemorySessionStorage {\n timeToLive;\n storage;\n constructor(timeToLive){\n this.timeToLive = timeToLive;\n this.storage = new Map();\n }\n read(key) {\n const value = this.storage.get(key);\n if (value === undefined) return undefined;\n if (value.expires !== undefined && value.expires < Date.now()) {\n this.delete(key);\n return undefined;\n }\n return value.session;\n }\n readAll() {\n return this.readAllValues();\n }\n readAllKeys() {\n return Array.from(this.storage.keys());\n }\n readAllValues() {\n return Array.from(this.storage.keys()).map((key)=>this.read(key)).filter((value)=>value !== undefined);\n }\n readAllEntries() {\n return Array.from(this.storage.keys()).map((key)=>[\n key,\n this.read(key)\n ]).filter((pair)=>pair[1] !== undefined);\n }\n has(key) {\n return this.storage.has(key);\n }\n write(key, value) {\n this.storage.set(key, addExpiryDate(value, this.timeToLive));\n }\n delete(key) {\n this.storage.delete(key);\n }\n}\nfunction addExpiryDate(value, ttl) {\n if (ttl !== undefined && ttl < Infinity) {\n const now = Date.now();\n return {\n session: value,\n expires: now + ttl\n };\n } else {\n return {\n session: value\n };\n }\n}\nexport { session as session };\nexport { lazySession as lazySession };\nexport { enhanceStorage as enhanceStorage };\nexport { MemorySessionStorage as MemorySessionStorage };\nconst SECRET_HEADER = \"X-Telegram-Bot-Api-Secret-Token\";\nconst SECRET_HEADER_LOWERCASE = SECRET_HEADER.toLowerCase();\nconst WRONG_TOKEN_ERROR = \"secret token is wrong\";\nconst ok = ()=>new Response(null, {\n status: 200\n });\nconst okJson = (json)=>new Response(json, {\n status: 200,\n headers: {\n \"Content-Type\": \"application/json\"\n }\n });\nconst unauthorized = ()=>new Response('\"unauthorized\"', {\n status: 401,\n statusText: WRONG_TOKEN_ERROR\n });\nconst awsLambda = (event, _context, callback)=>({\n get update () {\n return JSON.parse(event.body ?? \"{}\");\n },\n header: event.headers[SECRET_HEADER],\n end: ()=>callback(null, {\n statusCode: 200\n }),\n respond: (json)=>callback(null, {\n statusCode: 200,\n headers: {\n \"Content-Type\": \"application/json\"\n },\n body: json\n }),\n unauthorized: ()=>callback(null, {\n statusCode: 401\n })\n });\nconst awsLambdaAsync = (event, _context)=>{\n let resolveResponse;\n return {\n get update () {\n return JSON.parse(event.body ?? \"{}\");\n },\n header: event.headers[SECRET_HEADER],\n end: ()=>resolveResponse({\n statusCode: 200\n }),\n respond: (json)=>resolveResponse({\n statusCode: 200,\n headers: {\n \"Content-Type\": \"application/json\"\n },\n body: json\n }),\n unauthorized: ()=>resolveResponse({\n statusCode: 401\n }),\n handlerReturn: new Promise((res)=>resolveResponse = res)\n };\n};\nconst azure = (context, request)=>({\n get update () {\n return request.body;\n },\n header: context.res?.headers?.[SECRET_HEADER],\n end: ()=>context.res = {\n status: 200,\n body: \"\"\n },\n respond: (json)=>{\n context.res?.set?.(\"Content-Type\", \"application/json\");\n context.res?.send?.(json);\n },\n unauthorized: ()=>{\n context.res?.send?.(401, WRONG_TOKEN_ERROR);\n }\n });\nconst azureV4 = (request)=>{\n let resolveResponse;\n return {\n get update () {\n return request.json();\n },\n header: request.headers.get(SECRET_HEADER) || undefined,\n end: ()=>resolveResponse({\n status: 204\n }),\n respond: (json)=>resolveResponse({\n jsonBody: json\n }),\n unauthorized: ()=>resolveResponse({\n status: 401,\n body: WRONG_TOKEN_ERROR\n }),\n handlerReturn: new Promise((resolve)=>resolveResponse = resolve)\n };\n};\nconst bun = (request)=>{\n let resolveResponse;\n return {\n get update () {\n return request.json();\n },\n header: request.headers.get(SECRET_HEADER) || undefined,\n end: ()=>{\n resolveResponse(ok());\n },\n respond: (json)=>{\n resolveResponse(okJson(json));\n },\n unauthorized: ()=>{\n resolveResponse(unauthorized());\n },\n handlerReturn: new Promise((res)=>resolveResponse = res)\n };\n};\nconst cloudflare = (event)=>{\n let resolveResponse;\n event.respondWith(new Promise((resolve)=>{\n resolveResponse = resolve;\n }));\n return {\n get update () {\n return event.request.json();\n },\n header: event.request.headers.get(SECRET_HEADER) || undefined,\n end: ()=>{\n resolveResponse(ok());\n },\n respond: (json)=>{\n resolveResponse(okJson(json));\n },\n unauthorized: ()=>{\n resolveResponse(unauthorized());\n }\n };\n};\nconst cloudflareModule = (request)=>{\n let resolveResponse;\n return {\n get update () {\n return request.json();\n },\n header: request.headers.get(SECRET_HEADER) || undefined,\n end: ()=>{\n resolveResponse(ok());\n },\n respond: (json)=>{\n resolveResponse(okJson(json));\n },\n unauthorized: ()=>{\n resolveResponse(unauthorized());\n },\n handlerReturn: new Promise((res)=>resolveResponse = res)\n };\n};\nconst express = (req, res)=>({\n get update () {\n return req.body;\n },\n header: req.header(SECRET_HEADER),\n end: ()=>res.end(),\n respond: (json)=>{\n res.set(\"Content-Type\", \"application/json\");\n res.send(json);\n },\n unauthorized: ()=>{\n res.status(401).send(WRONG_TOKEN_ERROR);\n }\n });\nconst fastify = (request, reply)=>({\n get update () {\n return request.body;\n },\n header: request.headers[SECRET_HEADER_LOWERCASE],\n end: ()=>reply.send(\"\"),\n respond: (json)=>reply.headers({\n \"Content-Type\": \"application/json\"\n }).send(json),\n unauthorized: ()=>reply.code(401).send(WRONG_TOKEN_ERROR)\n });\nconst hono = (c)=>{\n let resolveResponse;\n return {\n get update () {\n return c.req.json();\n },\n header: c.req.header(SECRET_HEADER),\n end: ()=>{\n resolveResponse(c.body(\"\"));\n },\n respond: (json)=>{\n resolveResponse(c.json(json));\n },\n unauthorized: ()=>{\n c.status(401);\n resolveResponse(c.body(\"\"));\n },\n handlerReturn: new Promise((res)=>resolveResponse = res)\n };\n};\nconst http = (req, res)=>{\n const secretHeaderFromRequest = req.headers[SECRET_HEADER_LOWERCASE];\n return {\n get update () {\n return new Promise((resolve, reject)=>{\n const chunks = [];\n req.on(\"data\", (chunk)=>chunks.push(chunk)).once(\"end\", ()=>{\n const raw = Buffer.concat(chunks).toString(\"utf-8\");\n try {\n resolve(JSON.parse(raw));\n } catch (err) {\n reject(err);\n }\n }).once(\"error\", reject);\n });\n },\n header: Array.isArray(secretHeaderFromRequest) ? secretHeaderFromRequest[0] : secretHeaderFromRequest,\n end: ()=>res.end(),\n respond: (json)=>res.writeHead(200, {\n \"Content-Type\": \"application/json\"\n }).end(json),\n unauthorized: ()=>res.writeHead(401).end(WRONG_TOKEN_ERROR)\n };\n};\nconst koa = (ctx)=>({\n get update () {\n return ctx.request.body;\n },\n header: ctx.get(SECRET_HEADER) || undefined,\n end: ()=>{\n ctx.body = \"\";\n },\n respond: (json)=>{\n ctx.set(\"Content-Type\", \"application/json\");\n ctx.response.body = json;\n },\n unauthorized: ()=>{\n ctx.status = 401;\n }\n });\nconst nextJs = (request, response)=>({\n get update () {\n return request.body;\n },\n header: request.headers[SECRET_HEADER_LOWERCASE],\n end: ()=>response.end(),\n respond: (json)=>response.status(200).json(json),\n unauthorized: ()=>response.status(401).send(WRONG_TOKEN_ERROR)\n });\nconst nhttp = (rev)=>({\n get update () {\n return rev.body;\n },\n header: rev.headers.get(SECRET_HEADER) || undefined,\n end: ()=>rev.response.sendStatus(200),\n respond: (json)=>rev.response.status(200).send(json),\n unauthorized: ()=>rev.response.status(401).send(WRONG_TOKEN_ERROR)\n });\nconst oak = (ctx)=>({\n get update () {\n return ctx.request.body.json();\n },\n header: ctx.request.headers.get(SECRET_HEADER) || undefined,\n end: ()=>{\n ctx.response.status = 200;\n },\n respond: (json)=>{\n ctx.response.type = \"json\";\n ctx.response.body = json;\n },\n unauthorized: ()=>{\n ctx.response.status = 401;\n }\n });\nconst serveHttp = (requestEvent)=>({\n get update () {\n return requestEvent.request.json();\n },\n header: requestEvent.request.headers.get(SECRET_HEADER) || undefined,\n end: ()=>requestEvent.respondWith(ok()),\n respond: (json)=>requestEvent.respondWith(okJson(json)),\n unauthorized: ()=>requestEvent.respondWith(unauthorized())\n });\nconst stdHttp = (req)=>{\n let resolveResponse;\n return {\n get update () {\n return req.json();\n },\n header: req.headers.get(SECRET_HEADER) || undefined,\n end: ()=>{\n if (resolveResponse) resolveResponse(ok());\n },\n respond: (json)=>{\n if (resolveResponse) resolveResponse(okJson(json));\n },\n unauthorized: ()=>{\n if (resolveResponse) resolveResponse(unauthorized());\n },\n handlerReturn: new Promise((res)=>resolveResponse = res)\n };\n};\nconst sveltekit = ({ request })=>{\n let resolveResponse;\n return {\n get update () {\n return request.json();\n },\n header: request.headers.get(SECRET_HEADER) || undefined,\n end: ()=>{\n if (resolveResponse) resolveResponse(ok());\n },\n respond: (json)=>{\n if (resolveResponse) resolveResponse(okJson(json));\n },\n unauthorized: ()=>{\n if (resolveResponse) resolveResponse(unauthorized());\n },\n handlerReturn: new Promise((res)=>resolveResponse = res)\n };\n};\nconst worktop = (req, res)=>({\n get update () {\n return req.json();\n },\n header: req.headers.get(SECRET_HEADER) ?? undefined,\n end: ()=>res.end(null),\n respond: (json)=>res.send(200, json),\n unauthorized: ()=>res.send(401, WRONG_TOKEN_ERROR)\n });\nconst elysia = (ctx)=>{\n let resolveResponse;\n return {\n get update () {\n return ctx.body;\n },\n header: ctx.headers[SECRET_HEADER_LOWERCASE],\n end () {\n resolveResponse(\"\");\n },\n respond (json) {\n ctx.set.headers[\"content-type\"] = \"application/json\";\n resolveResponse(json);\n },\n unauthorized () {\n ctx.set.status = 401;\n resolveResponse(\"\");\n },\n handlerReturn: new Promise((res)=>resolveResponse = res)\n };\n};\nconst adapters = {\n \"aws-lambda\": awsLambda,\n \"aws-lambda-async\": awsLambdaAsync,\n azure,\n \"azure-v4\": azureV4,\n bun,\n cloudflare,\n \"cloudflare-mod\": cloudflareModule,\n elysia,\n express,\n fastify,\n hono,\n http,\n https: http,\n koa,\n \"next-js\": nextJs,\n nhttp,\n oak,\n serveHttp,\n \"std/http\": stdHttp,\n sveltekit,\n worktop\n};\nconst debugErr1 = browser$1(\"grammy:error\");\nconst callbackAdapter = (update, callback, header, unauthorized = ()=>callback('\"unauthorized\"'))=>({\n update: Promise.resolve(update),\n respond: callback,\n header,\n unauthorized\n });\nconst adapters1 = {\n ...adapters,\n callback: callbackAdapter\n};\nfunction compareSecretToken(header, token) {\n if (token === undefined) {\n return true;\n }\n if (header === undefined) {\n return false;\n }\n const encoder = new TextEncoder();\n const headerBytes = encoder.encode(header);\n const tokenBytes = encoder.encode(token);\n if (headerBytes.length !== tokenBytes.length) {\n return false;\n }\n let hasDifference = 0;\n for(let i = 0; i < tokenBytes.length; i++){\n const headerByte = i < headerBytes.length ? headerBytes[i] : 0;\n const tokenByte = tokenBytes[i];\n hasDifference |= headerByte ^ tokenByte;\n }\n return hasDifference === 0;\n}\nfunction webhookCallback(bot, adapter = defaultAdapter, onTimeout, timeoutMilliseconds, secretToken) {\n if (bot.isRunning()) {\n throw new Error(\"Bot is already running via long polling, the webhook setup won't receive any updates!\");\n } else {\n bot.start = ()=>{\n throw new Error(\"You already started the bot via webhooks, calling `bot.start()` starts the bot with long polling and this will prevent your webhook setup from receiving any updates!\");\n };\n }\n const { onTimeout: timeout = \"throw\", timeoutMilliseconds: ms = 10_000, secretToken: token } = typeof onTimeout === \"object\" ? onTimeout : {\n onTimeout,\n timeoutMilliseconds,\n secretToken\n };\n let initialized = false;\n const server = typeof adapter === \"string\" ? adapters1[adapter] : adapter;\n return async (...args)=>{\n const handler = server(...args);\n if (!initialized) {\n await bot.init();\n initialized = true;\n }\n if (!compareSecretToken(handler.header, token)) {\n await handler.unauthorized();\n return handler.handlerReturn;\n }\n let usedWebhookReply = false;\n const webhookReplyEnvelope = {\n async send (json) {\n usedWebhookReply = true;\n await handler.respond(json);\n }\n };\n await timeoutIfNecessary(bot.handleUpdate(await handler.update, webhookReplyEnvelope), typeof timeout === \"function\" ? ()=>timeout(...args) : timeout, ms);\n if (!usedWebhookReply) handler.end?.();\n return handler.handlerReturn;\n };\n}\nfunction timeoutIfNecessary(task, onTimeout, timeout) {\n if (timeout === Infinity) return task;\n return new Promise((resolve, reject)=>{\n const handle = setTimeout(()=>{\n debugErr1(`Request timed out after ${timeout} ms`);\n if (onTimeout === \"throw\") {\n reject(new Error(`Request timed out after ${timeout} ms`));\n } else {\n if (typeof onTimeout === \"function\") onTimeout();\n resolve();\n }\n const now = Date.now();\n task.finally(()=>{\n const diff = Date.now() - now;\n debugErr1(`Request completed ${diff} ms after timeout!`);\n });\n }, timeout);\n task.then(resolve).catch(reject).finally(()=>clearTimeout(handle));\n });\n}\nexport { webhookCallback as webhookCallback };\nexport { Bot as Bot, BotError as BotError };\nexport { InputFile as InputFile };\nexport { Context as Context };\nexport { Composer as Composer };\nexport { matchFilter as matchFilter };\nexport { Api as Api };\nexport { GrammyError as GrammyError, HttpError as HttpError };\n", "/// \nimport type { D1Database as MiniflareD1Database } from '@miniflare/d1';\nimport type { BatchItem, BatchResponse } from '~/batch.ts';\nimport { entityKind } from '~/entity.ts';\nimport { DefaultLogger } from '~/logger.ts';\nimport {\n\tcreateTableRelationsHelpers,\n\textractTablesRelationalConfig,\n\ttype ExtractTablesWithRelations,\n\ttype RelationalSchemaConfig,\n\ttype TablesRelationalConfig,\n} from '~/relations.ts';\nimport { BaseSQLiteDatabase } from '~/sqlite-core/db.ts';\nimport { SQLiteAsyncDialect } from '~/sqlite-core/dialect.ts';\nimport type { DrizzleConfig, IfNotImported } from '~/utils.ts';\nimport { SQLiteD1Session } from './session.ts';\n\nexport type AnyD1Database = IfNotImported<\n\tD1Database,\n\tMiniflareD1Database,\n\tD1Database | IfNotImported\n>;\n\nexport class DrizzleD1Database<\n\tTSchema extends Record = Record,\n> extends BaseSQLiteDatabase<'async', D1Result, TSchema> {\n\tstatic override readonly [entityKind]: string = 'D1Database';\n\n\t/** @internal */\n\tdeclare readonly session: SQLiteD1Session>;\n\n\tasync batch, T extends Readonly<[U, ...U[]]>>(\n\t\tbatch: T,\n\t): Promise> {\n\t\treturn this.session.batch(batch) as Promise>;\n\t}\n}\n\nexport function drizzle<\n\tTSchema extends Record = Record,\n\tTClient extends AnyD1Database = AnyD1Database,\n>(\n\tclient: TClient,\n\tconfig: DrizzleConfig = {},\n): DrizzleD1Database & {\n\t$client: TClient;\n} {\n\tconst dialect = new SQLiteAsyncDialect({ casing: config.casing });\n\tlet logger;\n\tif (config.logger === true) {\n\t\tlogger = new DefaultLogger();\n\t} else if (config.logger !== false) {\n\t\tlogger = config.logger;\n\t}\n\n\tlet schema: RelationalSchemaConfig | undefined;\n\tif (config.schema) {\n\t\tconst tablesConfig = extractTablesRelationalConfig(\n\t\t\tconfig.schema,\n\t\t\tcreateTableRelationsHelpers,\n\t\t);\n\t\tschema = {\n\t\t\tfullSchema: config.schema,\n\t\t\tschema: tablesConfig.tables,\n\t\t\ttableNamesMap: tablesConfig.tableNamesMap,\n\t\t};\n\t}\n\n\tconst session = new SQLiteD1Session(client as D1Database, dialect, schema, { logger, cache: config.cache });\n\tconst db = new DrizzleD1Database('async', dialect, session, schema) as DrizzleD1Database;\n\t( db).$client = client;\n\t( db).$cache = config.cache;\n\tif (( db).$cache) {\n\t\t( db).$cache['invalidate'] = config.cache?.onMutate;\n\t}\n\n\treturn db as any;\n}\n", "export const entityKind = Symbol.for('drizzle:entityKind');\nexport const hasOwnEntityKind = Symbol.for('drizzle:hasOwnEntityKind');\n\nexport interface DrizzleEntity {\n\t[entityKind]: string;\n}\n\nexport type DrizzleEntityClass =\n\t& ((abstract new(...args: any[]) => T) | (new(...args: any[]) => T))\n\t& DrizzleEntity;\n\nexport function is>(value: any, type: T): value is InstanceType {\n\tif (!value || typeof value !== 'object') {\n\t\treturn false;\n\t}\n\n\tif (value instanceof type) { // eslint-disable-line no-instanceof/no-instanceof\n\t\treturn true;\n\t}\n\n\tif (!Object.prototype.hasOwnProperty.call(type, entityKind)) {\n\t\tthrow new Error(\n\t\t\t`Class \"${\n\t\t\t\ttype.name ?? ''\n\t\t\t}\" doesn't look like a Drizzle entity. If this is incorrect and the class is provided by Drizzle, please report this as a bug.`,\n\t\t);\n\t}\n\n\tlet cls = Object.getPrototypeOf(value).constructor;\n\tif (cls) {\n\t\t// Traverse the prototype chain to find the entityKind\n\t\twhile (cls) {\n\t\t\tif (entityKind in cls && cls[entityKind] === type[entityKind]) {\n\t\t\t\treturn true;\n\t\t\t}\n\n\t\t\tcls = Object.getPrototypeOf(cls);\n\t\t}\n\t}\n\n\treturn false;\n}\n", "import { entityKind } from '~/entity.ts';\n\nexport interface Logger {\n\tlogQuery(query: string, params: unknown[]): void;\n}\n\nexport interface LogWriter {\n\twrite(message: string): void;\n}\n\nexport class ConsoleLogWriter implements LogWriter {\n\tstatic readonly [entityKind]: string = 'ConsoleLogWriter';\n\n\twrite(message: string) {\n\t\tconsole.log(message);\n\t}\n}\n\nexport class DefaultLogger implements Logger {\n\tstatic readonly [entityKind]: string = 'DefaultLogger';\n\n\treadonly writer: LogWriter;\n\n\tconstructor(config?: { writer: LogWriter }) {\n\t\tthis.writer = config?.writer ?? new ConsoleLogWriter();\n\t}\n\n\tlogQuery(query: string, params: unknown[]): void {\n\t\tconst stringifiedParams = params.map((p) => {\n\t\t\ttry {\n\t\t\t\treturn JSON.stringify(p);\n\t\t\t} catch {\n\t\t\t\treturn String(p);\n\t\t\t}\n\t\t});\n\t\tconst paramsStr = stringifiedParams.length ? ` -- params: [${stringifiedParams.join(', ')}]` : '';\n\t\tthis.writer.write(`Query: ${query}${paramsStr}`);\n\t}\n}\n\nexport class NoopLogger implements Logger {\n\tstatic readonly [entityKind]: string = 'NoopLogger';\n\n\tlogQuery(): void {\n\t\t// noop\n\t}\n}\n", "import { type AnyTable, getTableUniqueName, type InferModelFromColumns, Table } from '~/table.ts';\nimport { type AnyColumn, Column } from './column.ts';\nimport { entityKind, is } from './entity.ts';\nimport { PrimaryKeyBuilder } from './pg-core/primary-keys.ts';\nimport {\n\tand,\n\tasc,\n\tbetween,\n\tdesc,\n\teq,\n\texists,\n\tgt,\n\tgte,\n\tilike,\n\tinArray,\n\tisNotNull,\n\tisNull,\n\tlike,\n\tlt,\n\tlte,\n\tne,\n\tnot,\n\tnotBetween,\n\tnotExists,\n\tnotIlike,\n\tnotInArray,\n\tnotLike,\n\tor,\n} from './sql/expressions/index.ts';\nimport { type Placeholder, SQL, sql } from './sql/sql.ts';\nimport type { Assume, ColumnsWithTable, Equal, Simplify, ValueOrArray } from './utils.ts';\n\nexport abstract class Relation {\n\tstatic readonly [entityKind]: string = 'Relation';\n\n\tdeclare readonly $brand: 'Relation';\n\treadonly referencedTableName: TTableName;\n\tfieldName!: string;\n\n\tconstructor(\n\t\treadonly sourceTable: Table,\n\t\treadonly referencedTable: AnyTable<{ name: TTableName }>,\n\t\treadonly relationName: string | undefined,\n\t) {\n\t\tthis.referencedTableName = referencedTable[Table.Symbol.Name] as TTableName;\n\t}\n\n\tabstract withFieldName(fieldName: string): Relation;\n}\n\nexport class Relations<\n\tTTableName extends string = string,\n\tTConfig extends Record = Record,\n> {\n\tstatic readonly [entityKind]: string = 'Relations';\n\n\tdeclare readonly $brand: 'Relations';\n\n\tconstructor(\n\t\treadonly table: AnyTable<{ name: TTableName }>,\n\t\treadonly config: (helpers: TableRelationsHelpers) => TConfig,\n\t) {}\n}\n\nexport class One<\n\tTTableName extends string = string,\n\tTIsNullable extends boolean = boolean,\n> extends Relation {\n\tstatic override readonly [entityKind]: string = 'One';\n\n\tdeclare protected $relationBrand: 'One';\n\n\tconstructor(\n\t\tsourceTable: Table,\n\t\treferencedTable: AnyTable<{ name: TTableName }>,\n\t\treadonly config:\n\t\t\t| RelationConfig<\n\t\t\t\tTTableName,\n\t\t\t\tstring,\n\t\t\t\tAnyColumn<{ tableName: TTableName }>[]\n\t\t\t>\n\t\t\t| undefined,\n\t\treadonly isNullable: TIsNullable,\n\t) {\n\t\tsuper(sourceTable, referencedTable, config?.relationName);\n\t}\n\n\twithFieldName(fieldName: string): One {\n\t\tconst relation = new One(\n\t\t\tthis.sourceTable,\n\t\t\tthis.referencedTable,\n\t\t\tthis.config,\n\t\t\tthis.isNullable,\n\t\t);\n\t\trelation.fieldName = fieldName;\n\t\treturn relation;\n\t}\n}\n\nexport class Many extends Relation {\n\tstatic override readonly [entityKind]: string = 'Many';\n\n\tdeclare protected $relationBrand: 'Many';\n\n\tconstructor(\n\t\tsourceTable: Table,\n\t\treferencedTable: AnyTable<{ name: TTableName }>,\n\t\treadonly config: { relationName: string } | undefined,\n\t) {\n\t\tsuper(sourceTable, referencedTable, config?.relationName);\n\t}\n\n\twithFieldName(fieldName: string): Many {\n\t\tconst relation = new Many(\n\t\t\tthis.sourceTable,\n\t\t\tthis.referencedTable,\n\t\t\tthis.config,\n\t\t);\n\t\trelation.fieldName = fieldName;\n\t\treturn relation;\n\t}\n}\n\nexport type TableRelationsKeysOnly<\n\tTSchema extends Record,\n\tTTableName extends string,\n\tK extends keyof TSchema,\n> = TSchema[K] extends Relations ? K : never;\n\nexport type ExtractTableRelationsFromSchema<\n\tTSchema extends Record,\n\tTTableName extends string,\n> = ExtractObjectValues<\n\t{\n\t\t[\n\t\t\tK in keyof TSchema as TableRelationsKeysOnly<\n\t\t\t\tTSchema,\n\t\t\t\tTTableName,\n\t\t\t\tK\n\t\t\t>\n\t\t]: TSchema[K] extends Relations ? TConfig : never;\n\t}\n>;\n\nexport type ExtractObjectValues = T[keyof T];\n\nexport type ExtractRelationsFromTableExtraConfigSchema<\n\tTConfig extends unknown[],\n> = ExtractObjectValues<\n\t{\n\t\t[\n\t\t\tK in keyof TConfig as TConfig[K] extends Relations ? K\n\t\t\t\t: never\n\t\t]: TConfig[K] extends Relations ? TRelationConfig\n\t\t\t: never;\n\t}\n>;\n\nexport function getOperators() {\n\treturn {\n\t\tand,\n\t\tbetween,\n\t\teq,\n\t\texists,\n\t\tgt,\n\t\tgte,\n\t\tilike,\n\t\tinArray,\n\t\tisNull,\n\t\tisNotNull,\n\t\tlike,\n\t\tlt,\n\t\tlte,\n\t\tne,\n\t\tnot,\n\t\tnotBetween,\n\t\tnotExists,\n\t\tnotLike,\n\t\tnotIlike,\n\t\tnotInArray,\n\t\tor,\n\t\tsql,\n\t};\n}\n\nexport type Operators = ReturnType;\n\nexport function getOrderByOperators() {\n\treturn {\n\t\tsql,\n\t\tasc,\n\t\tdesc,\n\t};\n}\n\nexport type OrderByOperators = ReturnType;\n\nexport type FindTableByDBName<\n\tTSchema extends TablesRelationalConfig,\n\tTTableName extends string,\n> = ExtractObjectValues<\n\t{\n\t\t[\n\t\t\tK in keyof TSchema as TSchema[K]['dbName'] extends TTableName ? K\n\t\t\t\t: never\n\t\t]: TSchema[K];\n\t}\n>;\n\nexport type DBQueryConfig<\n\tTRelationType extends 'one' | 'many' = 'one' | 'many',\n\tTIsRoot extends boolean = boolean,\n\tTSchema extends TablesRelationalConfig = TablesRelationalConfig,\n\tTTableConfig extends TableRelationalConfig = TableRelationalConfig,\n> =\n\t& {\n\t\tcolumns?:\n\t\t\t| {\n\t\t\t\t[K in keyof TTableConfig['columns']]?: boolean;\n\t\t\t}\n\t\t\t| undefined;\n\t\twith?:\n\t\t\t| {\n\t\t\t\t[K in keyof TTableConfig['relations']]?:\n\t\t\t\t\t| true\n\t\t\t\t\t| DBQueryConfig<\n\t\t\t\t\t\tTTableConfig['relations'][K] extends One ? 'one' : 'many',\n\t\t\t\t\t\tfalse,\n\t\t\t\t\t\tTSchema,\n\t\t\t\t\t\tFindTableByDBName<\n\t\t\t\t\t\t\tTSchema,\n\t\t\t\t\t\t\tTTableConfig['relations'][K]['referencedTableName']\n\t\t\t\t\t\t>\n\t\t\t\t\t>\n\t\t\t\t\t| undefined;\n\t\t\t}\n\t\t\t| undefined;\n\t\textras?:\n\t\t\t| Record\n\t\t\t| ((\n\t\t\t\tfields: Simplify<\n\t\t\t\t\t[TTableConfig['columns']] extends [never] ? {}\n\t\t\t\t\t\t: TTableConfig['columns']\n\t\t\t\t>,\n\t\t\t\toperators: { sql: Operators['sql'] },\n\t\t\t) => Record)\n\t\t\t| undefined;\n\t}\n\t& (TRelationType extends 'many' ?\n\t\t\t& {\n\t\t\t\twhere?:\n\t\t\t\t\t| SQL\n\t\t\t\t\t| undefined\n\t\t\t\t\t| ((\n\t\t\t\t\t\tfields: Simplify<\n\t\t\t\t\t\t\t[TTableConfig['columns']] extends [never] ? {}\n\t\t\t\t\t\t\t\t: TTableConfig['columns']\n\t\t\t\t\t\t>,\n\t\t\t\t\t\toperators: Operators,\n\t\t\t\t\t) => SQL | undefined);\n\t\t\t\torderBy?:\n\t\t\t\t\t| ValueOrArray\n\t\t\t\t\t| ((\n\t\t\t\t\t\tfields: Simplify<\n\t\t\t\t\t\t\t[TTableConfig['columns']] extends [never] ? {}\n\t\t\t\t\t\t\t\t: TTableConfig['columns']\n\t\t\t\t\t\t>,\n\t\t\t\t\t\toperators: OrderByOperators,\n\t\t\t\t\t) => ValueOrArray)\n\t\t\t\t\t| undefined;\n\t\t\t\tlimit?: number | Placeholder | undefined;\n\t\t\t}\n\t\t\t& (TIsRoot extends true ? {\n\t\t\t\t\toffset?: number | Placeholder | undefined;\n\t\t\t\t}\n\t\t\t\t: {})\n\t\t: {});\n\nexport interface TableRelationalConfig {\n\ttsName: string;\n\tdbName: string;\n\tcolumns: Record;\n\trelations: Record;\n\tprimaryKey: AnyColumn[];\n\tschema?: string;\n}\n\nexport type TablesRelationalConfig = Record;\n\nexport interface RelationalSchemaConfig<\n\tTSchema extends TablesRelationalConfig,\n> {\n\tfullSchema: Record;\n\tschema: TSchema;\n\ttableNamesMap: Record;\n}\n\nexport type ExtractTablesWithRelations<\n\tTSchema extends Record,\n> = {\n\t[\n\t\tK in keyof TSchema as TSchema[K] extends Table ? K\n\t\t\t: never\n\t]: TSchema[K] extends Table ? {\n\t\t\ttsName: K & string;\n\t\t\tdbName: TSchema[K]['_']['name'];\n\t\t\tcolumns: TSchema[K]['_']['columns'];\n\t\t\trelations: ExtractTableRelationsFromSchema<\n\t\t\t\tTSchema,\n\t\t\t\tTSchema[K]['_']['name']\n\t\t\t>;\n\t\t\tprimaryKey: AnyColumn[];\n\t\t}\n\t\t: never;\n};\n\nexport type ReturnTypeOrValue = T extends (...args: any[]) => infer R ? R\n\t: T;\n\nexport type BuildRelationResult<\n\tTSchema extends TablesRelationalConfig,\n\tTInclude,\n\tTRelations extends Record,\n> = {\n\t[\n\t\tK in\n\t\t\t& NonUndefinedKeysOnly\n\t\t\t& keyof TRelations\n\t]: TRelations[K] extends infer TRel extends Relation ? BuildQueryResult<\n\t\t\tTSchema,\n\t\t\tFindTableByDBName,\n\t\t\tAssume>\n\t\t> extends infer TResult ? TRel extends One ?\n\t\t\t\t\t| TResult\n\t\t\t\t\t| (Equal extends true ? null : never)\n\t\t\t: TResult[]\n\t\t: never\n\t\t: never;\n};\n\nexport type NonUndefinedKeysOnly =\n\t& ExtractObjectValues<\n\t\t{\n\t\t\t[K in keyof T as T[K] extends undefined ? never : K]: K;\n\t\t}\n\t>\n\t& keyof T;\n\nexport type BuildQueryResult<\n\tTSchema extends TablesRelationalConfig,\n\tTTableConfig extends TableRelationalConfig,\n\tTFullSelection extends true | Record,\n> = Equal extends true ? InferModelFromColumns\n\t: TFullSelection extends Record ? Simplify<\n\t\t\t& (TFullSelection['columns'] extends Record ? InferModelFromColumns<\n\t\t\t\t\t{\n\t\t\t\t\t\t[\n\t\t\t\t\t\t\tK in Equal<\n\t\t\t\t\t\t\t\tExclude<\n\t\t\t\t\t\t\t\t\tTFullSelection['columns'][\n\t\t\t\t\t\t\t\t\t\t& keyof TFullSelection['columns']\n\t\t\t\t\t\t\t\t\t\t& keyof TTableConfig['columns']\n\t\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t\t\tundefined\n\t\t\t\t\t\t\t\t>,\n\t\t\t\t\t\t\t\tfalse\n\t\t\t\t\t\t\t> extends true ? Exclude<\n\t\t\t\t\t\t\t\t\tkeyof TTableConfig['columns'],\n\t\t\t\t\t\t\t\t\tNonUndefinedKeysOnly\n\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t:\n\t\t\t\t\t\t\t\t\t& {\n\t\t\t\t\t\t\t\t\t\t[K in keyof TFullSelection['columns']]: Equal<\n\t\t\t\t\t\t\t\t\t\t\tTFullSelection['columns'][K],\n\t\t\t\t\t\t\t\t\t\t\ttrue\n\t\t\t\t\t\t\t\t\t\t> extends true ? K\n\t\t\t\t\t\t\t\t\t\t\t: never;\n\t\t\t\t\t\t\t\t\t}[keyof TFullSelection['columns']]\n\t\t\t\t\t\t\t\t\t& keyof TTableConfig['columns']\n\t\t\t\t\t\t]: TTableConfig['columns'][K];\n\t\t\t\t\t}\n\t\t\t\t>\n\t\t\t\t: InferModelFromColumns)\n\t\t\t& (TFullSelection['extras'] extends\n\t\t\t\t| Record\n\t\t\t\t| ((...args: any[]) => Record) ? {\n\t\t\t\t\t[\n\t\t\t\t\t\tK in NonUndefinedKeysOnly<\n\t\t\t\t\t\t\tReturnTypeOrValue\n\t\t\t\t\t\t>\n\t\t\t\t\t]: Assume<\n\t\t\t\t\t\tReturnTypeOrValue[K],\n\t\t\t\t\t\tSQL.Aliased\n\t\t\t\t\t>['_']['type'];\n\t\t\t\t}\n\t\t\t\t: {})\n\t\t\t& (TFullSelection['with'] extends Record ? BuildRelationResult<\n\t\t\t\t\tTSchema,\n\t\t\t\t\tTFullSelection['with'],\n\t\t\t\t\tTTableConfig['relations']\n\t\t\t\t>\n\t\t\t\t: {})\n\t\t>\n\t: never;\n\nexport interface RelationConfig<\n\tTTableName extends string,\n\tTForeignTableName extends string,\n\tTColumns extends AnyColumn<{ tableName: TTableName }>[],\n> {\n\trelationName?: string;\n\tfields: TColumns;\n\treferences: ColumnsWithTable;\n}\n\nexport function extractTablesRelationalConfig<\n\tTTables extends TablesRelationalConfig,\n>(\n\tschema: Record,\n\tconfigHelpers: (table: Table) => any,\n): { tables: TTables; tableNamesMap: Record } {\n\tif (\n\t\tObject.keys(schema).length === 1\n\t\t&& 'default' in schema\n\t\t&& !is(schema['default'], Table)\n\t) {\n\t\tschema = schema['default'] as Record;\n\t}\n\n\t// table DB name -> schema table key\n\tconst tableNamesMap: Record = {};\n\t// Table relations found before their tables - need to buffer them until we know the schema table key\n\tconst relationsBuffer: Record<\n\t\tstring,\n\t\t{ relations: Record; primaryKey?: AnyColumn[] }\n\t> = {};\n\tconst tablesConfig: TablesRelationalConfig = {};\n\tfor (const [key, value] of Object.entries(schema)) {\n\t\tif (is(value, Table)) {\n\t\t\tconst dbName = getTableUniqueName(value);\n\t\t\tconst bufferedRelations = relationsBuffer[dbName];\n\t\t\ttableNamesMap[dbName] = key;\n\t\t\ttablesConfig[key] = {\n\t\t\t\ttsName: key,\n\t\t\t\tdbName: value[Table.Symbol.Name],\n\t\t\t\tschema: value[Table.Symbol.Schema],\n\t\t\t\tcolumns: value[Table.Symbol.Columns],\n\t\t\t\trelations: bufferedRelations?.relations ?? {},\n\t\t\t\tprimaryKey: bufferedRelations?.primaryKey ?? [],\n\t\t\t};\n\n\t\t\t// Fill in primary keys\n\t\t\tfor (\n\t\t\t\tconst column of Object.values(\n\t\t\t\t\t(value as Table)[Table.Symbol.Columns],\n\t\t\t\t)\n\t\t\t) {\n\t\t\t\tif (column.primary) {\n\t\t\t\t\ttablesConfig[key]!.primaryKey.push(column);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst extraConfig = value[Table.Symbol.ExtraConfigBuilder]?.((value as Table)[Table.Symbol.ExtraConfigColumns]);\n\t\t\tif (extraConfig) {\n\t\t\t\tfor (const configEntry of Object.values(extraConfig)) {\n\t\t\t\t\tif (is(configEntry, PrimaryKeyBuilder)) {\n\t\t\t\t\t\ttablesConfig[key]!.primaryKey.push(...configEntry.columns);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t} else if (is(value, Relations)) {\n\t\t\tconst dbName = getTableUniqueName(value.table);\n\t\t\tconst tableName = tableNamesMap[dbName];\n\t\t\tconst relations: Record = value.config(\n\t\t\t\tconfigHelpers(value.table),\n\t\t\t);\n\t\t\tlet primaryKey: AnyColumn[] | undefined;\n\n\t\t\tfor (const [relationName, relation] of Object.entries(relations)) {\n\t\t\t\tif (tableName) {\n\t\t\t\t\tconst tableConfig = tablesConfig[tableName]!;\n\t\t\t\t\ttableConfig.relations[relationName] = relation;\n\t\t\t\t\tif (primaryKey) {\n\t\t\t\t\t\ttableConfig.primaryKey.push(...primaryKey);\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tif (!(dbName in relationsBuffer)) {\n\t\t\t\t\t\trelationsBuffer[dbName] = {\n\t\t\t\t\t\t\trelations: {},\n\t\t\t\t\t\t\tprimaryKey,\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t\trelationsBuffer[dbName]!.relations[relationName] = relation;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn { tables: tablesConfig as TTables, tableNamesMap };\n}\n\nexport function relations<\n\tTTableName extends string,\n\tTRelations extends Record>,\n>(\n\ttable: AnyTable<{ name: TTableName }>,\n\trelations: (helpers: TableRelationsHelpers) => TRelations,\n): Relations {\n\treturn new Relations(\n\t\ttable,\n\t\t(helpers: TableRelationsHelpers) =>\n\t\t\tObject.fromEntries(\n\t\t\t\tObject.entries(relations(helpers)).map(([key, value]) => [\n\t\t\t\t\tkey,\n\t\t\t\t\tvalue.withFieldName(key),\n\t\t\t\t]),\n\t\t\t) as TRelations,\n\t);\n}\n\nexport function createOne(sourceTable: Table) {\n\treturn function one<\n\t\tTForeignTable extends Table,\n\t\tTColumns extends [\n\t\t\tAnyColumn<{ tableName: TTableName }>,\n\t\t\t...AnyColumn<{ tableName: TTableName }>[],\n\t\t],\n\t>(\n\t\ttable: TForeignTable,\n\t\tconfig?: RelationConfig,\n\t): One<\n\t\tTForeignTable['_']['name'],\n\t\tEqual\n\t> {\n\t\treturn new One(\n\t\t\tsourceTable,\n\t\t\ttable,\n\t\t\tconfig,\n\t\t\t(config?.fields.reduce((res, f) => res && f.notNull, true)\n\t\t\t\t?? false) as Equal,\n\t\t);\n\t};\n}\n\nexport function createMany(sourceTable: Table) {\n\treturn function many(\n\t\treferencedTable: TForeignTable,\n\t\tconfig?: { relationName: string },\n\t): Many {\n\t\treturn new Many(sourceTable, referencedTable, config);\n\t};\n}\n\nexport interface NormalizedRelation {\n\tfields: AnyColumn[];\n\treferences: AnyColumn[];\n}\n\nexport function normalizeRelation(\n\tschema: TablesRelationalConfig,\n\ttableNamesMap: Record,\n\trelation: Relation,\n): NormalizedRelation {\n\tif (is(relation, One) && relation.config) {\n\t\treturn {\n\t\t\tfields: relation.config.fields,\n\t\t\treferences: relation.config.references,\n\t\t};\n\t}\n\n\tconst referencedTableTsName = tableNamesMap[getTableUniqueName(relation.referencedTable)];\n\tif (!referencedTableTsName) {\n\t\tthrow new Error(\n\t\t\t`Table \"${relation.referencedTable[Table.Symbol.Name]}\" not found in schema`,\n\t\t);\n\t}\n\n\tconst referencedTableConfig = schema[referencedTableTsName];\n\tif (!referencedTableConfig) {\n\t\tthrow new Error(`Table \"${referencedTableTsName}\" not found in schema`);\n\t}\n\n\tconst sourceTable = relation.sourceTable;\n\tconst sourceTableTsName = tableNamesMap[getTableUniqueName(sourceTable)];\n\tif (!sourceTableTsName) {\n\t\tthrow new Error(\n\t\t\t`Table \"${sourceTable[Table.Symbol.Name]}\" not found in schema`,\n\t\t);\n\t}\n\n\tconst reverseRelations: Relation[] = [];\n\tfor (\n\t\tconst referencedTableRelation of Object.values(\n\t\t\treferencedTableConfig.relations,\n\t\t)\n\t) {\n\t\tif (\n\t\t\t(relation.relationName\n\t\t\t\t&& relation !== referencedTableRelation\n\t\t\t\t&& referencedTableRelation.relationName === relation.relationName)\n\t\t\t|| (!relation.relationName\n\t\t\t\t&& referencedTableRelation.referencedTable === relation.sourceTable)\n\t\t) {\n\t\t\treverseRelations.push(referencedTableRelation);\n\t\t}\n\t}\n\n\tif (reverseRelations.length > 1) {\n\t\tthrow relation.relationName\n\t\t\t? new Error(\n\t\t\t\t`There are multiple relations with name \"${relation.relationName}\" in table \"${referencedTableTsName}\"`,\n\t\t\t)\n\t\t\t: new Error(\n\t\t\t\t`There are multiple relations between \"${referencedTableTsName}\" and \"${\n\t\t\t\t\trelation.sourceTable[Table.Symbol.Name]\n\t\t\t\t}\". Please specify relation name`,\n\t\t\t);\n\t}\n\n\tif (\n\t\treverseRelations[0]\n\t\t&& is(reverseRelations[0], One)\n\t\t&& reverseRelations[0].config\n\t) {\n\t\treturn {\n\t\t\tfields: reverseRelations[0].config.references,\n\t\t\treferences: reverseRelations[0].config.fields,\n\t\t};\n\t}\n\n\tthrow new Error(\n\t\t`There is not enough information to infer relation \"${sourceTableTsName}.${relation.fieldName}\"`,\n\t);\n}\n\nexport function createTableRelationsHelpers(\n\tsourceTable: AnyTable<{ name: TTableName }>,\n) {\n\treturn {\n\t\tone: createOne(sourceTable),\n\t\tmany: createMany(sourceTable),\n\t};\n}\n\nexport type TableRelationsHelpers = ReturnType<\n\ttypeof createTableRelationsHelpers\n>;\n\nexport interface BuildRelationalQueryResult<\n\tTTable extends Table = Table,\n\tTColumn extends Column = Column,\n> {\n\ttableTsKey: string;\n\tselection: {\n\t\tdbKey: string;\n\t\ttsKey: string;\n\t\tfield: TColumn | SQL | SQL.Aliased;\n\t\trelationTableTsKey: string | undefined;\n\t\tisJson: boolean;\n\t\tisExtra?: boolean;\n\t\tselection: BuildRelationalQueryResult['selection'];\n\t}[];\n\tsql: TTable | SQL;\n}\n\nexport function mapRelationalRow(\n\ttablesConfig: TablesRelationalConfig,\n\ttableConfig: TableRelationalConfig,\n\trow: unknown[],\n\tbuildQueryResultSelection: BuildRelationalQueryResult['selection'],\n\tmapColumnValue: (value: unknown) => unknown = (value) => value,\n): Record {\n\tconst result: Record = {};\n\n\tfor (\n\t\tconst [\n\t\t\tselectionItemIndex,\n\t\t\tselectionItem,\n\t\t] of buildQueryResultSelection.entries()\n\t) {\n\t\tif (selectionItem.isJson) {\n\t\t\tconst relation = tableConfig.relations[selectionItem.tsKey]!;\n\t\t\tconst rawSubRows = row[selectionItemIndex] as\n\t\t\t\t| unknown[]\n\t\t\t\t| null\n\t\t\t\t| [null]\n\t\t\t\t| string;\n\t\t\tconst subRows = typeof rawSubRows === 'string'\n\t\t\t\t? (JSON.parse(rawSubRows) as unknown[])\n\t\t\t\t: rawSubRows;\n\t\t\tresult[selectionItem.tsKey] = is(relation, One)\n\t\t\t\t? subRows\n\t\t\t\t\t&& mapRelationalRow(\n\t\t\t\t\t\ttablesConfig,\n\t\t\t\t\t\ttablesConfig[selectionItem.relationTableTsKey!]!,\n\t\t\t\t\t\tsubRows,\n\t\t\t\t\t\tselectionItem.selection,\n\t\t\t\t\t\tmapColumnValue,\n\t\t\t\t\t)\n\t\t\t\t: (subRows as unknown[][]).map((subRow) =>\n\t\t\t\t\tmapRelationalRow(\n\t\t\t\t\t\ttablesConfig,\n\t\t\t\t\t\ttablesConfig[selectionItem.relationTableTsKey!]!,\n\t\t\t\t\t\tsubRow,\n\t\t\t\t\t\tselectionItem.selection,\n\t\t\t\t\t\tmapColumnValue,\n\t\t\t\t\t)\n\t\t\t\t);\n\t\t} else {\n\t\t\tconst value = mapColumnValue(row[selectionItemIndex]);\n\t\t\tconst field = selectionItem.field!;\n\t\t\tlet decoder;\n\t\t\tif (is(field, Column)) {\n\t\t\t\tdecoder = field;\n\t\t\t} else if (is(field, SQL)) {\n\t\t\t\tdecoder = field.decoder;\n\t\t\t} else {\n\t\t\t\tdecoder = field.sql.decoder;\n\t\t\t}\n\t\t\tresult[selectionItem.tsKey] = value === null ? null : decoder.mapFromDriverValue(value);\n\t\t}\n\t}\n\n\treturn result;\n}\n", "import type { Column, GetColumnData } from './column.ts';\nimport { entityKind } from './entity.ts';\nimport type { OptionalKeyOnly, RequiredKeyOnly } from './operations.ts';\nimport type { SQLWrapper } from './sql/sql.ts';\nimport { TableName } from './table.utils.ts';\nimport type { Simplify, Update } from './utils.ts';\n\nexport interface TableConfig> {\n\tname: string;\n\tschema: string | undefined;\n\tcolumns: Record;\n\tdialect: string;\n}\n\nexport type UpdateTableConfig> = Required<\n\tUpdate\n>;\n\n/** @internal */\nexport const Schema = Symbol.for('drizzle:Schema');\n\n/** @internal */\nexport const Columns = Symbol.for('drizzle:Columns');\n\n/** @internal */\nexport const ExtraConfigColumns = Symbol.for('drizzle:ExtraConfigColumns');\n\n/** @internal */\nexport const OriginalName = Symbol.for('drizzle:OriginalName');\n\n/** @internal */\nexport const BaseName = Symbol.for('drizzle:BaseName');\n\n/** @internal */\nexport const IsAlias = Symbol.for('drizzle:IsAlias');\n\n/** @internal */\nexport const ExtraConfigBuilder = Symbol.for('drizzle:ExtraConfigBuilder');\n\nconst IsDrizzleTable = Symbol.for('drizzle:IsDrizzleTable');\n\nexport interface Table<\n\t// eslint-disable-next-line @typescript-eslint/no-unused-vars\n\tT extends TableConfig = TableConfig,\n> extends SQLWrapper {\n\t// SQLWrapper runtime implementation is defined in 'sql/sql.ts'\n}\n\nexport class Table implements SQLWrapper {\n\tstatic readonly [entityKind]: string = 'Table';\n\n\tdeclare readonly _: {\n\t\treadonly brand: 'Table';\n\t\treadonly config: T;\n\t\treadonly name: T['name'];\n\t\treadonly schema: T['schema'];\n\t\treadonly columns: T['columns'];\n\t\treadonly inferSelect: InferSelectModel>;\n\t\treadonly inferInsert: InferInsertModel>;\n\t};\n\n\tdeclare readonly $inferSelect: InferSelectModel>;\n\tdeclare readonly $inferInsert: InferInsertModel>;\n\n\t/** @internal */\n\tstatic readonly Symbol = {\n\t\tName: TableName as typeof TableName,\n\t\tSchema: Schema as typeof Schema,\n\t\tOriginalName: OriginalName as typeof OriginalName,\n\t\tColumns: Columns as typeof Columns,\n\t\tExtraConfigColumns: ExtraConfigColumns as typeof ExtraConfigColumns,\n\t\tBaseName: BaseName as typeof BaseName,\n\t\tIsAlias: IsAlias as typeof IsAlias,\n\t\tExtraConfigBuilder: ExtraConfigBuilder as typeof ExtraConfigBuilder,\n\t};\n\n\t/**\n\t * @internal\n\t * Can be changed if the table is aliased.\n\t */\n\t[TableName]: string;\n\n\t/**\n\t * @internal\n\t * Used to store the original name of the table, before any aliasing.\n\t */\n\t[OriginalName]: string;\n\n\t/** @internal */\n\t[Schema]: string | undefined;\n\n\t/** @internal */\n\t[Columns]!: T['columns'];\n\n\t/** @internal */\n\t[ExtraConfigColumns]!: Record;\n\n\t/**\n\t * @internal\n\t * Used to store the table name before the transformation via the `tableCreator` functions.\n\t */\n\t[BaseName]: string;\n\n\t/** @internal */\n\t[IsAlias] = false;\n\n\t/** @internal */\n\t[IsDrizzleTable] = true;\n\n\t/** @internal */\n\t[ExtraConfigBuilder]: ((self: any) => Record | unknown[]) | undefined = undefined;\n\n\tconstructor(name: string, schema: string | undefined, baseName: string) {\n\t\tthis[TableName] = this[OriginalName] = name;\n\t\tthis[Schema] = schema;\n\t\tthis[BaseName] = baseName;\n\t}\n}\n\nexport function isTable(table: unknown): table is Table {\n\treturn typeof table === 'object' && table !== null && IsDrizzleTable in table;\n}\n\n/**\n * Any table with a specified boundary.\n *\n * @example\n\t```ts\n\t// Any table with a specific name\n\ttype AnyUsersTable = AnyTable<{ name: 'users' }>;\n\t```\n *\n * To describe any table with any config, simply use `Table` without any type arguments, like this:\n *\n\t```ts\n\tfunction needsTable(table: Table) {\n\t\t...\n\t}\n\t```\n */\nexport type AnyTable> = Table>;\n\nexport function getTableName(table: T): T['_']['name'] {\n\treturn table[TableName];\n}\n\nexport function getTableUniqueName(table: T): `${T['_']['schema']}.${T['_']['name']}` {\n\treturn `${table[Schema] ?? 'public'}.${table[TableName]}`;\n}\n\nexport type MapColumnName =\n\tTDBColumNames extends true ? TColumn['_']['name']\n\t\t: TName;\n\nexport type InferModelFromColumns<\n\tTColumns extends Record,\n\tTInferMode extends 'select' | 'insert' = 'select',\n\tTConfig extends { dbColumnNames: boolean; override?: boolean } = { dbColumnNames: false; override: false },\n> = Simplify<\n\tTInferMode extends 'insert' ?\n\t\t\t& {\n\t\t\t\t[\n\t\t\t\t\tKey in keyof TColumns & string as RequiredKeyOnly<\n\t\t\t\t\t\tMapColumnName,\n\t\t\t\t\t\tTColumns[Key]\n\t\t\t\t\t>\n\t\t\t\t]: GetColumnData;\n\t\t\t}\n\t\t\t& {\n\t\t\t\t[\n\t\t\t\t\tKey in keyof TColumns & string as OptionalKeyOnly<\n\t\t\t\t\t\tMapColumnName,\n\t\t\t\t\t\tTColumns[Key],\n\t\t\t\t\t\tTConfig['override']\n\t\t\t\t\t>\n\t\t\t\t]?: GetColumnData | undefined;\n\t\t\t}\n\t\t: {\n\t\t\t[\n\t\t\t\tKey in keyof TColumns & string as MapColumnName<\n\t\t\t\t\tKey,\n\t\t\t\t\tTColumns[Key],\n\t\t\t\t\tTConfig['dbColumnNames']\n\t\t\t\t>\n\t\t\t]: GetColumnData;\n\t\t}\n>;\n\n/** @deprecated Use one of the alternatives: {@link InferSelectModel} / {@link InferInsertModel}, or `table.$inferSelect` / `table.$inferInsert`\n */\nexport type InferModel<\n\tTTable extends Table,\n\tTInferMode extends 'select' | 'insert' = 'select',\n\tTConfig extends { dbColumnNames: boolean } = { dbColumnNames: false },\n> = InferModelFromColumns;\n\nexport type InferSelectModel<\n\tTTable extends Table,\n\tTConfig extends { dbColumnNames: boolean } = { dbColumnNames: false },\n> = InferModelFromColumns;\n\nexport type InferInsertModel<\n\tTTable extends Table,\n\tTConfig extends { dbColumnNames: boolean; override?: boolean } = { dbColumnNames: false; override: false },\n> = InferModelFromColumns;\n\nexport type InferEnum = T extends { enumValues: readonly (infer U)[] } ? U\n\t: never;\n", "/** @internal */\nexport const TableName = Symbol.for('drizzle:Name');\n", "import type {\n\tColumnBuilderBaseConfig,\n\tColumnBuilderRuntimeConfig,\n\tColumnDataType,\n\tGeneratedColumnConfig,\n\tGeneratedIdentityConfig,\n} from './column-builder.ts';\nimport { entityKind } from './entity.ts';\nimport type { DriverValueMapper, SQL, SQLWrapper } from './sql/sql.ts';\nimport type { Table } from './table.ts';\nimport type { Update } from './utils.ts';\n\nexport interface ColumnBaseConfig<\n\tTDataType extends ColumnDataType,\n\tTColumnType extends string,\n> extends ColumnBuilderBaseConfig {\n\ttableName: string;\n\tnotNull: boolean;\n\thasDefault: boolean;\n\tisPrimaryKey: boolean;\n\tisAutoincrement: boolean;\n\thasRuntimeDefault: boolean;\n}\n\nexport type ColumnTypeConfig, TTypeConfig extends object> = T & {\n\tbrand: 'Column';\n\ttableName: T['tableName'];\n\tname: T['name'];\n\tdataType: T['dataType'];\n\tcolumnType: T['columnType'];\n\tdata: T['data'];\n\tdriverParam: T['driverParam'];\n\tnotNull: T['notNull'];\n\thasDefault: T['hasDefault'];\n\tisPrimaryKey: T['isPrimaryKey'];\n\tisAutoincrement: T['isAutoincrement'];\n\thasRuntimeDefault: T['hasRuntimeDefault'];\n\tenumValues: T['enumValues'];\n\tbaseColumn: T extends { baseColumn: infer U } ? U : unknown;\n\tgenerated: GeneratedColumnConfig | undefined;\n\tidentity: undefined | 'always' | 'byDefault';\n} & TTypeConfig;\n\nexport type ColumnRuntimeConfig = ColumnBuilderRuntimeConfig<\n\tTData,\n\tTRuntimeConfig\n>;\n\nexport interface Column<\n\tT extends ColumnBaseConfig = ColumnBaseConfig,\n\t// eslint-disable-next-line @typescript-eslint/no-unused-vars\n\tTRuntimeConfig extends object = object,\n\t// eslint-disable-next-line @typescript-eslint/no-unused-vars\n\tTTypeConfig extends object = object,\n> extends DriverValueMapper, SQLWrapper {\n\t// SQLWrapper runtime implementation is defined in 'sql/sql.ts'\n}\n/*\n\t`Column` only accepts a full `ColumnConfig` as its generic.\n\tTo infer parts of the config, use `AnyColumn` that accepts a partial config.\n\tSee `GetColumnData` for example usage of inferring.\n*/\nexport abstract class Column<\n\tT extends ColumnBaseConfig = ColumnBaseConfig,\n\tTRuntimeConfig extends object = object,\n\tTTypeConfig extends object = object,\n> implements DriverValueMapper, SQLWrapper {\n\tstatic readonly [entityKind]: string = 'Column';\n\n\tdeclare readonly _: ColumnTypeConfig;\n\n\treadonly name: string;\n\treadonly keyAsName: boolean;\n\treadonly primary: boolean;\n\treadonly notNull: boolean;\n\treadonly default: T['data'] | SQL | undefined;\n\treadonly defaultFn: (() => T['data'] | SQL) | undefined;\n\treadonly onUpdateFn: (() => T['data'] | SQL) | undefined;\n\treadonly hasDefault: boolean;\n\treadonly isUnique: boolean;\n\treadonly uniqueName: string | undefined;\n\treadonly uniqueType: string | undefined;\n\treadonly dataType: T['dataType'];\n\treadonly columnType: T['columnType'];\n\treadonly enumValues: T['enumValues'] = undefined;\n\treadonly generated: GeneratedColumnConfig | undefined = undefined;\n\treadonly generatedIdentity: GeneratedIdentityConfig | undefined = undefined;\n\n\tprotected config: ColumnRuntimeConfig;\n\n\tconstructor(\n\t\treadonly table: Table,\n\t\tconfig: ColumnRuntimeConfig,\n\t) {\n\t\tthis.config = config;\n\t\tthis.name = config.name;\n\t\tthis.keyAsName = config.keyAsName;\n\t\tthis.notNull = config.notNull;\n\t\tthis.default = config.default;\n\t\tthis.defaultFn = config.defaultFn;\n\t\tthis.onUpdateFn = config.onUpdateFn;\n\t\tthis.hasDefault = config.hasDefault;\n\t\tthis.primary = config.primaryKey;\n\t\tthis.isUnique = config.isUnique;\n\t\tthis.uniqueName = config.uniqueName;\n\t\tthis.uniqueType = config.uniqueType;\n\t\tthis.dataType = config.dataType as T['dataType'];\n\t\tthis.columnType = config.columnType;\n\t\tthis.generated = config.generated;\n\t\tthis.generatedIdentity = config.generatedIdentity;\n\t}\n\n\tabstract getSQLType(): string;\n\n\tmapFromDriverValue(value: unknown): unknown {\n\t\treturn value;\n\t}\n\n\tmapToDriverValue(value: unknown): unknown {\n\t\treturn value;\n\t}\n\n\t// ** @internal */\n\tshouldDisableInsert(): boolean {\n\t\treturn this.config.generated !== undefined && this.config.generated.type !== 'byDefault';\n\t}\n}\n\nexport type UpdateColConfig<\n\tT extends ColumnBaseConfig,\n\tTUpdate extends Partial>,\n> = Update;\n\nexport type AnyColumn> = {}> = Column<\n\tRequired, TPartial>>\n>;\n\nexport type GetColumnData =\n\t// dprint-ignore\n\tTInferMode extends 'raw' // Raw mode\n\t\t? TColumn['_']['data'] // Just return the underlying type\n\t\t: TColumn['_']['notNull'] extends true // Query mode\n\t\t? TColumn['_']['data'] // Query mode, not null\n\t\t: TColumn['_']['data'] | null; // Query mode, nullable\n\nexport type InferColumnsDataTypes> = {\n\t[Key in keyof TColumns]: GetColumnData;\n};\n", "import { entityKind } from '~/entity.ts';\nimport type { AnyPgColumn, PgColumn } from './columns/index.ts';\nimport { PgTable } from './table.ts';\n\nexport function primaryKey<\n\tTTableName extends string,\n\tTColumn extends AnyPgColumn<{ tableName: TTableName }>,\n\tTColumns extends AnyPgColumn<{ tableName: TTableName }>[],\n>(config: { name?: string; columns: [TColumn, ...TColumns] }): PrimaryKeyBuilder;\n/**\n * @deprecated: Please use primaryKey({ columns: [] }) instead of this function\n * @param columns\n */\nexport function primaryKey<\n\tTTableName extends string,\n\tTColumns extends AnyPgColumn<{ tableName: TTableName }>[],\n>(...columns: TColumns): PrimaryKeyBuilder;\nexport function primaryKey(...config: any) {\n\tif (config[0].columns) {\n\t\treturn new PrimaryKeyBuilder(config[0].columns, config[0].name);\n\t}\n\treturn new PrimaryKeyBuilder(config);\n}\n\nexport class PrimaryKeyBuilder {\n\tstatic readonly [entityKind]: string = 'PgPrimaryKeyBuilder';\n\n\t/** @internal */\n\tcolumns: PgColumn[];\n\n\t/** @internal */\n\tname?: string;\n\n\tconstructor(\n\t\tcolumns: PgColumn[],\n\t\tname?: string,\n\t) {\n\t\tthis.columns = columns;\n\t\tthis.name = name;\n\t}\n\n\t/** @internal */\n\tbuild(table: PgTable): PrimaryKey {\n\t\treturn new PrimaryKey(table, this.columns, this.name);\n\t}\n}\n\nexport class PrimaryKey {\n\tstatic readonly [entityKind]: string = 'PgPrimaryKey';\n\n\treadonly columns: AnyPgColumn<{}>[];\n\treadonly name?: string;\n\n\tconstructor(readonly table: PgTable, columns: AnyPgColumn<{}>[], name?: string) {\n\t\tthis.columns = columns;\n\t\tthis.name = name;\n\t}\n\n\tgetName(): string {\n\t\treturn this.name ?? `${this.table[PgTable.Symbol.Name]}_${this.columns.map((column) => column.name).join('_')}_pk`;\n\t}\n}\n", "import type { BuildColumns, BuildExtraConfigColumns } from '~/column-builder.ts';\nimport { entityKind } from '~/entity.ts';\nimport { Table, type TableConfig as TableConfigBase, type UpdateTableConfig } from '~/table.ts';\nimport type { CheckBuilder } from './checks.ts';\nimport { getPgColumnBuilders, type PgColumnsBuilders } from './columns/all.ts';\nimport type { ExtraConfigColumn, PgColumn, PgColumnBuilder, PgColumnBuilderBase } from './columns/common.ts';\nimport type { ForeignKey, ForeignKeyBuilder } from './foreign-keys.ts';\nimport type { AnyIndexBuilder } from './indexes.ts';\nimport type { PgPolicy } from './policies.ts';\nimport type { PrimaryKeyBuilder } from './primary-keys.ts';\nimport type { UniqueConstraintBuilder } from './unique-constraint.ts';\n\nexport type PgTableExtraConfigValue =\n\t| AnyIndexBuilder\n\t| CheckBuilder\n\t| ForeignKeyBuilder\n\t| PrimaryKeyBuilder\n\t| UniqueConstraintBuilder\n\t| PgPolicy;\n\nexport type PgTableExtraConfig = Record<\n\tstring,\n\tPgTableExtraConfigValue\n>;\n\nexport type TableConfig = TableConfigBase;\n\n/** @internal */\nexport const InlineForeignKeys = Symbol.for('drizzle:PgInlineForeignKeys');\n/** @internal */\nexport const EnableRLS = Symbol.for('drizzle:EnableRLS');\n\nexport class PgTable extends Table {\n\tstatic override readonly [entityKind]: string = 'PgTable';\n\n\t/** @internal */\n\tstatic override readonly Symbol = Object.assign({}, Table.Symbol, {\n\t\tInlineForeignKeys: InlineForeignKeys as typeof InlineForeignKeys,\n\t\tEnableRLS: EnableRLS as typeof EnableRLS,\n\t});\n\n\t/**@internal */\n\t[InlineForeignKeys]: ForeignKey[] = [];\n\n\t/** @internal */\n\t[EnableRLS]: boolean = false;\n\n\t/** @internal */\n\toverride [Table.Symbol.ExtraConfigBuilder]: ((self: Record) => PgTableExtraConfig) | undefined =\n\t\tundefined;\n\n\t/** @internal */\n\toverride [Table.Symbol.ExtraConfigColumns]: Record = {};\n}\n\nexport type AnyPgTable = {}> = PgTable>;\n\nexport type PgTableWithColumns =\n\t& PgTable\n\t& {\n\t\t[Key in keyof T['columns']]: T['columns'][Key];\n\t}\n\t& {\n\t\tenableRLS: () => Omit<\n\t\t\tPgTableWithColumns,\n\t\t\t'enableRLS'\n\t\t>;\n\t};\n\n/** @internal */\nexport function pgTableWithSchema<\n\tTTableName extends string,\n\tTSchemaName extends string | undefined,\n\tTColumnsMap extends Record,\n>(\n\tname: TTableName,\n\tcolumns: TColumnsMap | ((columnTypes: PgColumnsBuilders) => TColumnsMap),\n\textraConfig:\n\t\t| ((self: BuildExtraConfigColumns) => PgTableExtraConfig | PgTableExtraConfigValue[])\n\t\t| undefined,\n\tschema: TSchemaName,\n\tbaseName = name,\n): PgTableWithColumns<{\n\tname: TTableName;\n\tschema: TSchemaName;\n\tcolumns: BuildColumns;\n\tdialect: 'pg';\n}> {\n\tconst rawTable = new PgTable<{\n\t\tname: TTableName;\n\t\tschema: TSchemaName;\n\t\tcolumns: BuildColumns;\n\t\tdialect: 'pg';\n\t}>(name, schema, baseName);\n\n\tconst parsedColumns: TColumnsMap = typeof columns === 'function' ? columns(getPgColumnBuilders()) : columns;\n\n\tconst builtColumns = Object.fromEntries(\n\t\tObject.entries(parsedColumns).map(([name, colBuilderBase]) => {\n\t\t\tconst colBuilder = colBuilderBase as PgColumnBuilder;\n\t\t\tcolBuilder.setName(name);\n\t\t\tconst column = colBuilder.build(rawTable);\n\t\t\trawTable[InlineForeignKeys].push(...colBuilder.buildForeignKeys(column, rawTable));\n\t\t\treturn [name, column];\n\t\t}),\n\t) as unknown as BuildColumns;\n\n\tconst builtColumnsForExtraConfig = Object.fromEntries(\n\t\tObject.entries(parsedColumns).map(([name, colBuilderBase]) => {\n\t\t\tconst colBuilder = colBuilderBase as PgColumnBuilder;\n\t\t\tcolBuilder.setName(name);\n\t\t\tconst column = colBuilder.buildExtraConfigColumn(rawTable);\n\t\t\treturn [name, column];\n\t\t}),\n\t) as unknown as BuildExtraConfigColumns;\n\n\tconst table = Object.assign(rawTable, builtColumns);\n\n\ttable[Table.Symbol.Columns] = builtColumns;\n\ttable[Table.Symbol.ExtraConfigColumns] = builtColumnsForExtraConfig;\n\n\tif (extraConfig) {\n\t\ttable[PgTable.Symbol.ExtraConfigBuilder] = extraConfig as any;\n\t}\n\n\treturn Object.assign(table, {\n\t\tenableRLS: () => {\n\t\t\ttable[PgTable.Symbol.EnableRLS] = true;\n\t\t\treturn table as PgTableWithColumns<{\n\t\t\t\tname: TTableName;\n\t\t\t\tschema: TSchemaName;\n\t\t\t\tcolumns: BuildColumns;\n\t\t\t\tdialect: 'pg';\n\t\t\t}>;\n\t\t},\n\t});\n}\n\nexport interface PgTableFn {\n\t<\n\t\tTTableName extends string,\n\t\tTColumnsMap extends Record,\n\t>(\n\t\tname: TTableName,\n\t\tcolumns: TColumnsMap,\n\t\textraConfig?: (\n\t\t\tself: BuildExtraConfigColumns,\n\t\t) => PgTableExtraConfigValue[],\n\t): PgTableWithColumns<{\n\t\tname: TTableName;\n\t\tschema: TSchema;\n\t\tcolumns: BuildColumns;\n\t\tdialect: 'pg';\n\t}>;\n\n\t<\n\t\tTTableName extends string,\n\t\tTColumnsMap extends Record,\n\t>(\n\t\tname: TTableName,\n\t\tcolumns: (columnTypes: PgColumnsBuilders) => TColumnsMap,\n\t\textraConfig?: (self: BuildExtraConfigColumns) => PgTableExtraConfigValue[],\n\t): PgTableWithColumns<{\n\t\tname: TTableName;\n\t\tschema: TSchema;\n\t\tcolumns: BuildColumns;\n\t\tdialect: 'pg';\n\t}>;\n\t/**\n\t * @deprecated The third parameter of pgTable is changing and will only accept an array instead of an object\n\t *\n\t * @example\n\t * Deprecated version:\n\t * ```ts\n\t * export const users = pgTable(\"users\", {\n\t * \tid: integer(),\n\t * }, (t) => ({\n\t * \tidx: index('custom_name').on(t.id)\n\t * }));\n\t * ```\n\t *\n\t * New API:\n\t * ```ts\n\t * export const users = pgTable(\"users\", {\n\t * \tid: integer(),\n\t * }, (t) => [\n\t * \tindex('custom_name').on(t.id)\n\t * ]);\n\t * ```\n\t */\n\t<\n\t\tTTableName extends string,\n\t\tTColumnsMap extends Record,\n\t>(\n\t\tname: TTableName,\n\t\tcolumns: TColumnsMap,\n\t\textraConfig: (\n\t\t\tself: BuildExtraConfigColumns,\n\t\t) => PgTableExtraConfig,\n\t): PgTableWithColumns<{\n\t\tname: TTableName;\n\t\tschema: TSchema;\n\t\tcolumns: BuildColumns;\n\t\tdialect: 'pg';\n\t}>;\n\n\t/**\n\t * @deprecated The third parameter of pgTable is changing and will only accept an array instead of an object\n\t *\n\t * @example\n\t * Deprecated version:\n\t * ```ts\n\t * export const users = pgTable(\"users\", {\n\t * \tid: integer(),\n\t * }, (t) => ({\n\t * \tidx: index('custom_name').on(t.id)\n\t * }));\n\t * ```\n\t *\n\t * New API:\n\t * ```ts\n\t * export const users = pgTable(\"users\", {\n\t * \tid: integer(),\n\t * }, (t) => [\n\t * \tindex('custom_name').on(t.id)\n\t * ]);\n\t * ```\n\t */\n\t<\n\t\tTTableName extends string,\n\t\tTColumnsMap extends Record,\n\t>(\n\t\tname: TTableName,\n\t\tcolumns: (columnTypes: PgColumnsBuilders) => TColumnsMap,\n\t\textraConfig: (self: BuildExtraConfigColumns) => PgTableExtraConfig,\n\t): PgTableWithColumns<{\n\t\tname: TTableName;\n\t\tschema: TSchema;\n\t\tcolumns: BuildColumns;\n\t\tdialect: 'pg';\n\t}>;\n}\n\nexport const pgTable: PgTableFn = (name, columns, extraConfig) => {\n\treturn pgTableWithSchema(name, columns, extraConfig, undefined);\n};\n\nexport function pgTableCreator(customizeTableName: (name: string) => string): PgTableFn {\n\treturn (name, columns, extraConfig) => {\n\t\treturn pgTableWithSchema(customizeTableName(name) as typeof name, columns, extraConfig, undefined, name);\n\t};\n}\n", "import type { Cache } from './cache/core/cache.ts';\nimport type { AnyColumn } from './column.ts';\nimport { Column } from './column.ts';\nimport { is } from './entity.ts';\nimport type { Logger } from './logger.ts';\nimport type { SelectedFieldsOrdered } from './operations.ts';\nimport type { TableLike } from './query-builders/select.types.ts';\nimport { Param, SQL, View } from './sql/sql.ts';\nimport type { DriverValueDecoder } from './sql/sql.ts';\nimport { Subquery } from './subquery.ts';\nimport { getTableName, Table } from './table.ts';\nimport { ViewBaseConfig } from './view-common.ts';\n\n/** @internal */\nexport function mapResultRow(\n\tcolumns: SelectedFieldsOrdered,\n\trow: unknown[],\n\tjoinsNotNullableMap: Record | undefined,\n): TResult {\n\t// Key -> nested object key, value -> table name if all fields in the nested object are from the same table, false otherwise\n\tconst nullifyMap: Record = {};\n\n\tconst result = columns.reduce>(\n\t\t(result, { path, field }, columnIndex) => {\n\t\t\tlet decoder: DriverValueDecoder;\n\t\t\tif (is(field, Column)) {\n\t\t\t\tdecoder = field;\n\t\t\t} else if (is(field, SQL)) {\n\t\t\t\tdecoder = field.decoder;\n\t\t\t} else if (is(field, Subquery)) {\n\t\t\t\tdecoder = field._.sql.decoder;\n\t\t\t} else {\n\t\t\t\tdecoder = field.sql.decoder;\n\t\t\t}\n\t\t\tlet node = result;\n\t\t\tfor (const [pathChunkIndex, pathChunk] of path.entries()) {\n\t\t\t\tif (pathChunkIndex < path.length - 1) {\n\t\t\t\t\tif (!(pathChunk in node)) {\n\t\t\t\t\t\tnode[pathChunk] = {};\n\t\t\t\t\t}\n\t\t\t\t\tnode = node[pathChunk];\n\t\t\t\t} else {\n\t\t\t\t\tconst rawValue = row[columnIndex]!;\n\t\t\t\t\tconst value = node[pathChunk] = rawValue === null ? null : decoder.mapFromDriverValue(rawValue);\n\n\t\t\t\t\tif (joinsNotNullableMap && is(field, Column) && path.length === 2) {\n\t\t\t\t\t\tconst objectName = path[0]!;\n\t\t\t\t\t\tif (!(objectName in nullifyMap)) {\n\t\t\t\t\t\t\tnullifyMap[objectName] = value === null ? getTableName(field.table) : false;\n\t\t\t\t\t\t} else if (\n\t\t\t\t\t\t\ttypeof nullifyMap[objectName] === 'string' && nullifyMap[objectName] !== getTableName(field.table)\n\t\t\t\t\t\t) {\n\t\t\t\t\t\t\tnullifyMap[objectName] = false;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn result;\n\t\t},\n\t\t{},\n\t);\n\n\t// Nullify all nested objects from nullifyMap that are nullable\n\tif (joinsNotNullableMap && Object.keys(nullifyMap).length > 0) {\n\t\tfor (const [objectName, tableName] of Object.entries(nullifyMap)) {\n\t\t\tif (typeof tableName === 'string' && !joinsNotNullableMap[tableName]) {\n\t\t\t\tresult[objectName] = null;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn result as TResult;\n}\n\n/** @internal */\nexport function orderSelectedFields(\n\tfields: Record,\n\tpathPrefix?: string[],\n): SelectedFieldsOrdered {\n\treturn Object.entries(fields).reduce>((result, [name, field]) => {\n\t\tif (typeof name !== 'string') {\n\t\t\treturn result;\n\t\t}\n\n\t\tconst newPath = pathPrefix ? [...pathPrefix, name] : [name];\n\t\tif (is(field, Column) || is(field, SQL) || is(field, SQL.Aliased) || is(field, Subquery)) {\n\t\t\tresult.push({ path: newPath, field });\n\t\t} else if (is(field, Table)) {\n\t\t\tresult.push(...orderSelectedFields(field[Table.Symbol.Columns], newPath));\n\t\t} else {\n\t\t\tresult.push(...orderSelectedFields(field as Record, newPath));\n\t\t}\n\t\treturn result;\n\t}, []) as SelectedFieldsOrdered;\n}\n\nexport function haveSameKeys(left: Record, right: Record) {\n\tconst leftKeys = Object.keys(left);\n\tconst rightKeys = Object.keys(right);\n\n\tif (leftKeys.length !== rightKeys.length) {\n\t\treturn false;\n\t}\n\n\tfor (const [index, key] of leftKeys.entries()) {\n\t\tif (key !== rightKeys[index]) {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\treturn true;\n}\n\n/** @internal */\nexport function mapUpdateSet(table: Table, values: Record): UpdateSet {\n\tconst entries: [string, UpdateSet[string]][] = Object.entries(values)\n\t\t.filter(([, value]) => value !== undefined)\n\t\t.map(([key, value]) => {\n\t\t\t// eslint-disable-next-line unicorn/prefer-ternary\n\t\t\tif (is(value, SQL) || is(value, Column)) {\n\t\t\t\treturn [key, value];\n\t\t\t} else {\n\t\t\t\treturn [key, new Param(value, table[Table.Symbol.Columns][key])];\n\t\t\t}\n\t\t});\n\n\tif (entries.length === 0) {\n\t\tthrow new Error('No values to set');\n\t}\n\n\treturn Object.fromEntries(entries);\n}\n\nexport type UpdateSet = Record;\n\nexport type OneOrMany = T | T[];\n\nexport type Update =\n\t& {\n\t\t[K in Exclude]: T[K];\n\t}\n\t& TUpdate;\n\nexport type Simplify =\n\t& {\n\t\t// @ts-ignore - \"Type parameter 'K' has a circular constraint\", not sure why\n\t\t[K in keyof T]: T[K];\n\t}\n\t& {};\n\nexport type Not = T extends true ? false : true;\n\nexport type IsNever = [T] extends [never] ? true : false;\n\nexport type IsUnion = (T extends any ? (U extends T ? false : true) : never) extends false ? false\n\t: true;\n\nexport type SingleKeyObject = IsNever extends true ? never\n\t: IsUnion extends true ? DrizzleTypeError\n\t: T;\n\nexport type FromSingleKeyObject = IsNever extends true ? never\n\t: IsUnion extends true ? DrizzleTypeError\n\t: Result;\n\nexport type SimplifyMappedType = [T] extends [unknown] ? T : never;\n\nexport type ShallowRecord = SimplifyMappedType<{ [P in K]: T }>;\n\nexport type Assume = T extends U ? T : U;\n\nexport type Equal = (() => T extends X ? 1 : 2) extends (() => T extends Y ? 1 : 2) ? true : false;\n\nexport interface DrizzleTypeError {\n\t$drizzleTypeError: T;\n}\n\nexport type ValueOrArray = T | T[];\n\n/** @internal */\nexport function applyMixins(baseClass: any, extendedClasses: any[]) {\n\tfor (const extendedClass of extendedClasses) {\n\t\tfor (const name of Object.getOwnPropertyNames(extendedClass.prototype)) {\n\t\t\tif (name === 'constructor') continue;\n\n\t\t\tObject.defineProperty(\n\t\t\t\tbaseClass.prototype,\n\t\t\t\tname,\n\t\t\t\tObject.getOwnPropertyDescriptor(extendedClass.prototype, name) || Object.create(null),\n\t\t\t);\n\t\t}\n\t}\n}\n\nexport type Or = T1 extends true ? true : T2 extends true ? true : false;\n\nexport type IfThenElse = If extends true ? Then : Else;\n\nexport type PromiseOf = T extends Promise ? U : T;\n\nexport type Writable = {\n\t-readonly [P in keyof T]: T[P];\n};\n\nexport type NonArray = T extends any[] ? never : T;\n\nexport function getTableColumns(table: T): T['_']['columns'] {\n\treturn table[Table.Symbol.Columns];\n}\n\nexport function getViewSelectedFields(view: T): T['_']['selectedFields'] {\n\treturn view[ViewBaseConfig].selectedFields;\n}\n\n/** @internal */\nexport function getTableLikeName(table: TableLike): string | undefined {\n\treturn is(table, Subquery)\n\t\t? table._.alias\n\t\t: is(table, View)\n\t\t? table[ViewBaseConfig].name\n\t\t: is(table, SQL)\n\t\t? undefined\n\t\t: table[Table.Symbol.IsAlias]\n\t\t? table[Table.Symbol.Name]\n\t\t: table[Table.Symbol.BaseName];\n}\n\nexport type ColumnsWithTable<\n\tTTableName extends string,\n\tTForeignTableName extends string,\n\tTColumns extends AnyColumn<{ tableName: TTableName }>[],\n> = { [Key in keyof TColumns]: AnyColumn<{ tableName: TForeignTableName }> };\n\nexport type Casing = 'snake_case' | 'camelCase';\n\nexport interface DrizzleConfig = Record> {\n\tlogger?: boolean | Logger;\n\tschema?: TSchema;\n\tcasing?: Casing;\n\tcache?: Cache;\n}\nexport type ValidateShape = T extends ValidShape\n\t? Exclude extends never ? TResult\n\t: DrizzleTypeError<\n\t\t`Invalid key(s): ${Exclude<(keyof T) & (string | number | bigint | boolean | null | undefined), keyof ValidShape>}`\n\t>\n\t: never;\n\nexport type KnownKeysOnly = {\n\t[K in keyof T]: K extends keyof U ? T[K] : never;\n};\n\nexport type IsAny = 0 extends (1 & T) ? true : false;\n\n/** @internal */\nexport function getColumnNameAndConfig<\n\tTConfig extends Record | undefined,\n>(a: string | TConfig | undefined, b: TConfig | undefined) {\n\treturn {\n\t\tname: typeof a === 'string' && a.length > 0 ? a : '' as string,\n\t\tconfig: typeof a === 'object' ? a : b as TConfig,\n\t};\n}\n\nexport type IfNotImported = unknown extends T ? Y : N;\n\nexport type ImportTypeError =\n\t`Please install \\`${TPackageName}\\` to allow Drizzle ORM to connect to the database`;\n\nexport type RequireAtLeastOne = Keys extends any\n\t? Required> & Partial>\n\t: never;\n\ntype ExpectedConfigShape = {\n\tlogger?: boolean | {\n\t\tlogQuery(query: string, params: unknown[]): void;\n\t};\n\tschema?: Record;\n\tcasing?: 'snake_case' | 'camelCase';\n};\n\n// If this errors, you must update config shape checker function with new config specs\nconst _: DrizzleConfig = {} as ExpectedConfigShape;\nconst __: ExpectedConfigShape = {} as DrizzleConfig;\n\nexport function isConfig(data: any): boolean {\n\tif (typeof data !== 'object' || data === null) return false;\n\n\tif (data.constructor.name !== 'Object') return false;\n\n\tif ('logger' in data) {\n\t\tconst type = typeof data['logger'];\n\t\tif (\n\t\t\ttype !== 'boolean' && (type !== 'object' || typeof data['logger']['logQuery'] !== 'function')\n\t\t\t&& type !== 'undefined'\n\t\t) return false;\n\n\t\treturn true;\n\t}\n\n\tif ('schema' in data) {\n\t\tconst type = typeof data['schema'];\n\t\tif (type !== 'object' && type !== 'undefined') return false;\n\n\t\treturn true;\n\t}\n\n\tif ('casing' in data) {\n\t\tconst type = typeof data['casing'];\n\t\tif (type !== 'string' && type !== 'undefined') return false;\n\n\t\treturn true;\n\t}\n\n\tif ('mode' in data) {\n\t\tif (data['mode'] !== 'default' || data['mode'] !== 'planetscale' || data['mode'] !== undefined) return false;\n\n\t\treturn true;\n\t}\n\n\tif ('connection' in data) {\n\t\tconst type = typeof data['connection'];\n\t\tif (type !== 'string' && type !== 'object' && type !== 'undefined') return false;\n\n\t\treturn true;\n\t}\n\n\tif ('client' in data) {\n\t\tconst type = typeof data['client'];\n\t\tif (type !== 'object' && type !== 'function' && type !== 'undefined') return false;\n\n\t\treturn true;\n\t}\n\n\tif (Object.keys(data).length === 0) return true;\n\n\treturn false;\n}\n\nexport type NeonAuthToken = string | (() => string | Promise);\n\nexport const textDecoder = typeof TextDecoder === 'undefined' ? null : new TextDecoder();\n", "import type { CasingCache } from '~/casing.ts';\nimport { entityKind, is } from '~/entity.ts';\nimport { isPgEnum } from '~/pg-core/columns/enum.ts';\nimport type { SelectResult } from '~/query-builders/select.types.ts';\nimport { Subquery } from '~/subquery.ts';\nimport { tracer } from '~/tracing.ts';\nimport type { Assume, Equal } from '~/utils.ts';\nimport { ViewBaseConfig } from '~/view-common.ts';\nimport type { AnyColumn } from '../column.ts';\nimport { Column } from '../column.ts';\nimport { IsAlias, Table } from '../table.ts';\n\n/**\n * This class is used to indicate a primitive param value that is used in `sql` tag.\n * It is only used on type level and is never instantiated at runtime.\n * If you see a value of this type in the code, its runtime value is actually the primitive param value.\n */\nexport class FakePrimitiveParam {\n\tstatic readonly [entityKind]: string = 'FakePrimitiveParam';\n}\n\nexport type Chunk =\n\t| string\n\t| Table\n\t| View\n\t| AnyColumn\n\t| Name\n\t| Param\n\t| Placeholder\n\t| SQL;\n\nexport interface BuildQueryConfig {\n\tcasing: CasingCache;\n\tescapeName(name: string): string;\n\tescapeParam(num: number, value: unknown): string;\n\tescapeString(str: string): string;\n\tprepareTyping?: (encoder: DriverValueEncoder) => QueryTypingsValue;\n\tparamStartIndex?: { value: number };\n\tinlineParams?: boolean;\n\tinvokeSource?: 'indexes' | undefined;\n}\n\nexport type QueryTypingsValue = 'json' | 'decimal' | 'time' | 'timestamp' | 'uuid' | 'date' | 'none';\n\nexport interface Query {\n\tsql: string;\n\tparams: unknown[];\n}\n\nexport interface QueryWithTypings extends Query {\n\ttypings?: QueryTypingsValue[];\n}\n\n/**\n * Any value that implements the `getSQL` method. The implementations include:\n * - `Table`\n * - `Column`\n * - `View`\n * - `Subquery`\n * - `SQL`\n * - `SQL.Aliased`\n * - `Placeholder`\n * - `Param`\n */\nexport interface SQLWrapper {\n\tgetSQL(): SQL;\n\tshouldOmitSQLParens?(): boolean;\n}\n\nexport function isSQLWrapper(value: unknown): value is SQLWrapper {\n\treturn value !== null && value !== undefined && typeof (value as any).getSQL === 'function';\n}\n\nfunction mergeQueries(queries: QueryWithTypings[]): QueryWithTypings {\n\tconst result: QueryWithTypings = { sql: '', params: [] };\n\tfor (const query of queries) {\n\t\tresult.sql += query.sql;\n\t\tresult.params.push(...query.params);\n\t\tif (query.typings?.length) {\n\t\t\tif (!result.typings) {\n\t\t\t\tresult.typings = [];\n\t\t\t}\n\t\t\tresult.typings.push(...query.typings);\n\t\t}\n\t}\n\treturn result;\n}\n\nexport class StringChunk implements SQLWrapper {\n\tstatic readonly [entityKind]: string = 'StringChunk';\n\n\treadonly value: string[];\n\n\tconstructor(value: string | string[]) {\n\t\tthis.value = Array.isArray(value) ? value : [value];\n\t}\n\n\tgetSQL(): SQL {\n\t\treturn new SQL([this]);\n\t}\n}\n\nexport class SQL implements SQLWrapper {\n\tstatic readonly [entityKind]: string = 'SQL';\n\n\tdeclare _: {\n\t\tbrand: 'SQL';\n\t\ttype: T;\n\t};\n\n\t/** @internal */\n\tdecoder: DriverValueDecoder = noopDecoder;\n\tprivate shouldInlineParams = false;\n\n\t/** @internal */\n\tusedTables: string[] = [];\n\n\tconstructor(readonly queryChunks: SQLChunk[]) {\n\t\tfor (const chunk of queryChunks) {\n\t\t\tif (is(chunk, Table)) {\n\t\t\t\tconst schemaName = chunk[Table.Symbol.Schema];\n\n\t\t\t\tthis.usedTables.push(\n\t\t\t\t\tschemaName === undefined\n\t\t\t\t\t\t? chunk[Table.Symbol.Name]\n\t\t\t\t\t\t: schemaName + '.' + chunk[Table.Symbol.Name],\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\n\tappend(query: SQL): this {\n\t\tthis.queryChunks.push(...query.queryChunks);\n\t\treturn this;\n\t}\n\n\ttoQuery(config: BuildQueryConfig): QueryWithTypings {\n\t\treturn tracer.startActiveSpan('drizzle.buildSQL', (span) => {\n\t\t\tconst query = this.buildQueryFromSourceParams(this.queryChunks, config);\n\t\t\tspan?.setAttributes({\n\t\t\t\t'drizzle.query.text': query.sql,\n\t\t\t\t'drizzle.query.params': JSON.stringify(query.params),\n\t\t\t});\n\t\t\treturn query;\n\t\t});\n\t}\n\n\tbuildQueryFromSourceParams(chunks: SQLChunk[], _config: BuildQueryConfig): Query {\n\t\tconst config = Object.assign({}, _config, {\n\t\t\tinlineParams: _config.inlineParams || this.shouldInlineParams,\n\t\t\tparamStartIndex: _config.paramStartIndex || { value: 0 },\n\t\t});\n\n\t\tconst {\n\t\t\tcasing,\n\t\t\tescapeName,\n\t\t\tescapeParam,\n\t\t\tprepareTyping,\n\t\t\tinlineParams,\n\t\t\tparamStartIndex,\n\t\t} = config;\n\n\t\treturn mergeQueries(chunks.map((chunk): QueryWithTypings => {\n\t\t\tif (is(chunk, StringChunk)) {\n\t\t\t\treturn { sql: chunk.value.join(''), params: [] };\n\t\t\t}\n\n\t\t\tif (is(chunk, Name)) {\n\t\t\t\treturn { sql: escapeName(chunk.value), params: [] };\n\t\t\t}\n\n\t\t\tif (chunk === undefined) {\n\t\t\t\treturn { sql: '', params: [] };\n\t\t\t}\n\n\t\t\tif (Array.isArray(chunk)) {\n\t\t\t\tconst result: SQLChunk[] = [new StringChunk('(')];\n\t\t\t\tfor (const [i, p] of chunk.entries()) {\n\t\t\t\t\tresult.push(p);\n\t\t\t\t\tif (i < chunk.length - 1) {\n\t\t\t\t\t\tresult.push(new StringChunk(', '));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tresult.push(new StringChunk(')'));\n\t\t\t\treturn this.buildQueryFromSourceParams(result, config);\n\t\t\t}\n\n\t\t\tif (is(chunk, SQL)) {\n\t\t\t\treturn this.buildQueryFromSourceParams(chunk.queryChunks, {\n\t\t\t\t\t...config,\n\t\t\t\t\tinlineParams: inlineParams || chunk.shouldInlineParams,\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tif (is(chunk, Table)) {\n\t\t\t\tconst schemaName = chunk[Table.Symbol.Schema];\n\t\t\t\tconst tableName = chunk[Table.Symbol.Name];\n\t\t\t\treturn {\n\t\t\t\t\tsql: schemaName === undefined || chunk[IsAlias]\n\t\t\t\t\t\t? escapeName(tableName)\n\t\t\t\t\t\t: escapeName(schemaName) + '.' + escapeName(tableName),\n\t\t\t\t\tparams: [],\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tif (is(chunk, Column)) {\n\t\t\t\tconst columnName = casing.getColumnCasing(chunk);\n\t\t\t\tif (_config.invokeSource === 'indexes') {\n\t\t\t\t\treturn { sql: escapeName(columnName), params: [] };\n\t\t\t\t}\n\n\t\t\t\tconst schemaName = chunk.table[Table.Symbol.Schema];\n\t\t\t\treturn {\n\t\t\t\t\tsql: chunk.table[IsAlias] || schemaName === undefined\n\t\t\t\t\t\t? escapeName(chunk.table[Table.Symbol.Name]) + '.' + escapeName(columnName)\n\t\t\t\t\t\t: escapeName(schemaName) + '.' + escapeName(chunk.table[Table.Symbol.Name]) + '.'\n\t\t\t\t\t\t\t+ escapeName(columnName),\n\t\t\t\t\tparams: [],\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tif (is(chunk, View)) {\n\t\t\t\tconst schemaName = chunk[ViewBaseConfig].schema;\n\t\t\t\tconst viewName = chunk[ViewBaseConfig].name;\n\t\t\t\treturn {\n\t\t\t\t\tsql: schemaName === undefined || chunk[ViewBaseConfig].isAlias\n\t\t\t\t\t\t? escapeName(viewName)\n\t\t\t\t\t\t: escapeName(schemaName) + '.' + escapeName(viewName),\n\t\t\t\t\tparams: [],\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tif (is(chunk, Param)) {\n\t\t\t\tif (is(chunk.value, Placeholder)) {\n\t\t\t\t\treturn { sql: escapeParam(paramStartIndex.value++, chunk), params: [chunk], typings: ['none'] };\n\t\t\t\t}\n\n\t\t\t\tconst mappedValue = chunk.value === null ? null : chunk.encoder.mapToDriverValue(chunk.value);\n\n\t\t\t\tif (is(mappedValue, SQL)) {\n\t\t\t\t\treturn this.buildQueryFromSourceParams([mappedValue], config);\n\t\t\t\t}\n\n\t\t\t\tif (inlineParams) {\n\t\t\t\t\treturn { sql: this.mapInlineParam(mappedValue, config), params: [] };\n\t\t\t\t}\n\n\t\t\t\tlet typings: QueryTypingsValue[] = ['none'];\n\t\t\t\tif (prepareTyping) {\n\t\t\t\t\ttypings = [prepareTyping(chunk.encoder)];\n\t\t\t\t}\n\n\t\t\t\treturn { sql: escapeParam(paramStartIndex.value++, mappedValue), params: [mappedValue], typings };\n\t\t\t}\n\n\t\t\tif (is(chunk, Placeholder)) {\n\t\t\t\treturn { sql: escapeParam(paramStartIndex.value++, chunk), params: [chunk], typings: ['none'] };\n\t\t\t}\n\n\t\t\tif (is(chunk, SQL.Aliased) && chunk.fieldAlias !== undefined) {\n\t\t\t\treturn { sql: escapeName(chunk.fieldAlias), params: [] };\n\t\t\t}\n\n\t\t\tif (is(chunk, Subquery)) {\n\t\t\t\tif (chunk._.isWith) {\n\t\t\t\t\treturn { sql: escapeName(chunk._.alias), params: [] };\n\t\t\t\t}\n\t\t\t\treturn this.buildQueryFromSourceParams([\n\t\t\t\t\tnew StringChunk('('),\n\t\t\t\t\tchunk._.sql,\n\t\t\t\t\tnew StringChunk(') '),\n\t\t\t\t\tnew Name(chunk._.alias),\n\t\t\t\t], config);\n\t\t\t}\n\n\t\t\tif (isPgEnum(chunk)) {\n\t\t\t\tif (chunk.schema) {\n\t\t\t\t\treturn { sql: escapeName(chunk.schema) + '.' + escapeName(chunk.enumName), params: [] };\n\t\t\t\t}\n\t\t\t\treturn { sql: escapeName(chunk.enumName), params: [] };\n\t\t\t}\n\n\t\t\tif (isSQLWrapper(chunk)) {\n\t\t\t\tif (chunk.shouldOmitSQLParens?.()) {\n\t\t\t\t\treturn this.buildQueryFromSourceParams([chunk.getSQL()], config);\n\t\t\t\t}\n\t\t\t\treturn this.buildQueryFromSourceParams([\n\t\t\t\t\tnew StringChunk('('),\n\t\t\t\t\tchunk.getSQL(),\n\t\t\t\t\tnew StringChunk(')'),\n\t\t\t\t], config);\n\t\t\t}\n\n\t\t\tif (inlineParams) {\n\t\t\t\treturn { sql: this.mapInlineParam(chunk, config), params: [] };\n\t\t\t}\n\n\t\t\treturn { sql: escapeParam(paramStartIndex.value++, chunk), params: [chunk], typings: ['none'] };\n\t\t}));\n\t}\n\n\tprivate mapInlineParam(\n\t\tchunk: unknown,\n\t\t{ escapeString }: BuildQueryConfig,\n\t): string {\n\t\tif (chunk === null) {\n\t\t\treturn 'null';\n\t\t}\n\t\tif (typeof chunk === 'number' || typeof chunk === 'boolean') {\n\t\t\treturn chunk.toString();\n\t\t}\n\t\tif (typeof chunk === 'string') {\n\t\t\treturn escapeString(chunk);\n\t\t}\n\t\tif (typeof chunk === 'object') {\n\t\t\tconst mappedValueAsString = chunk.toString();\n\t\t\tif (mappedValueAsString === '[object Object]') {\n\t\t\t\treturn escapeString(JSON.stringify(chunk));\n\t\t\t}\n\t\t\treturn escapeString(mappedValueAsString);\n\t\t}\n\t\tthrow new Error('Unexpected param value: ' + chunk);\n\t}\n\n\tgetSQL(): SQL {\n\t\treturn this;\n\t}\n\n\tas(alias: string): SQL.Aliased;\n\t/**\n\t * @deprecated\n\t * Use ``sql`query`.as(alias)`` instead.\n\t */\n\tas(): SQL;\n\t/**\n\t * @deprecated\n\t * Use ``sql`query`.as(alias)`` instead.\n\t */\n\tas(alias: string): SQL.Aliased;\n\tas(alias?: string): SQL | SQL.Aliased {\n\t\t// TODO: remove with deprecated overloads\n\t\tif (alias === undefined) {\n\t\t\treturn this;\n\t\t}\n\n\t\treturn new SQL.Aliased(this, alias);\n\t}\n\n\tmapWith<\n\t\tTDecoder extends\n\t\t\t| DriverValueDecoder\n\t\t\t| DriverValueDecoder['mapFromDriverValue'],\n\t>(decoder: TDecoder): SQL> {\n\t\tthis.decoder = typeof decoder === 'function' ? { mapFromDriverValue: decoder } : decoder;\n\t\treturn this as SQL>;\n\t}\n\n\tinlineParams(): this {\n\t\tthis.shouldInlineParams = true;\n\t\treturn this;\n\t}\n\n\t/**\n\t * This method is used to conditionally include a part of the query.\n\t *\n\t * @param condition - Condition to check\n\t * @returns itself if the condition is `true`, otherwise `undefined`\n\t */\n\tif(condition: any | undefined): this | undefined {\n\t\treturn condition ? this : undefined;\n\t}\n}\n\nexport type GetDecoderResult = T extends Column ? T['_']['data'] : T extends\n\t| DriverValueDecoder\n\t| DriverValueDecoder['mapFromDriverValue'] ? TData\n: never;\n\n/**\n * Any DB name (table, column, index etc.)\n */\nexport class Name implements SQLWrapper {\n\tstatic readonly [entityKind]: string = 'Name';\n\n\tprotected brand!: 'Name';\n\n\tconstructor(readonly value: string) {}\n\n\tgetSQL(): SQL {\n\t\treturn new SQL([this]);\n\t}\n}\n\n/**\n * Any DB name (table, column, index etc.)\n * @deprecated Use `sql.identifier` instead.\n */\nexport function name(value: string): Name {\n\treturn new Name(value);\n}\n\nexport interface DriverValueDecoder {\n\tmapFromDriverValue(value: TDriverParam): TData;\n}\n\nexport interface DriverValueEncoder {\n\tmapToDriverValue(value: TData): TDriverParam | SQL;\n}\n\nexport function isDriverValueEncoder(value: unknown): value is DriverValueEncoder {\n\treturn typeof value === 'object' && value !== null && 'mapToDriverValue' in value\n\t\t&& typeof (value as any).mapToDriverValue === 'function';\n}\n\nexport const noopDecoder: DriverValueDecoder = {\n\tmapFromDriverValue: (value) => value,\n};\n\nexport const noopEncoder: DriverValueEncoder = {\n\tmapToDriverValue: (value) => value,\n};\n\nexport interface DriverValueMapper\n\textends DriverValueDecoder, DriverValueEncoder\n{}\n\nexport const noopMapper: DriverValueMapper = {\n\t...noopDecoder,\n\t...noopEncoder,\n};\n\n/** Parameter value that is optionally bound to an encoder (for example, a column). */\nexport class Param implements SQLWrapper {\n\tstatic readonly [entityKind]: string = 'Param';\n\n\tprotected brand!: 'BoundParamValue';\n\n\t/**\n\t * @param value - Parameter value\n\t * @param encoder - Encoder to convert the value to a driver parameter\n\t */\n\tconstructor(\n\t\treadonly value: TDataType,\n\t\treadonly encoder: DriverValueEncoder = noopEncoder,\n\t) {}\n\n\tgetSQL(): SQL {\n\t\treturn new SQL([this]);\n\t}\n}\n\n/** @deprecated Use `sql.param` instead. */\nexport function param(\n\tvalue: TData,\n\tencoder?: DriverValueEncoder,\n): Param {\n\treturn new Param(value, encoder);\n}\n\n/**\n * Anything that can be passed to the `` sql`...` `` tagged function.\n */\nexport type SQLChunk =\n\t| StringChunk\n\t| SQLChunk[]\n\t| SQLWrapper\n\t| SQL\n\t| Table\n\t| View\n\t| Subquery\n\t| AnyColumn\n\t| Param\n\t| Name\n\t| undefined\n\t| FakePrimitiveParam\n\t| Placeholder;\n\nexport function sql(strings: TemplateStringsArray, ...params: any[]): SQL;\n/*\n\tThe type of `params` is specified as `SQLChunk[]`, but that's slightly incorrect -\n\tin runtime, users won't pass `FakePrimitiveParam` instances as `params` - they will pass primitive values\n\twhich will be wrapped in `Param`. That's why the overload specifies `params` as `any[]` and not as `SQLSourceParam[]`.\n\tThis type is used to make our lives easier and the type checker happy.\n*/\nexport function sql(strings: TemplateStringsArray, ...params: SQLChunk[]): SQL {\n\tconst queryChunks: SQLChunk[] = [];\n\tif (params.length > 0 || (strings.length > 0 && strings[0] !== '')) {\n\t\tqueryChunks.push(new StringChunk(strings[0]!));\n\t}\n\tfor (const [paramIndex, param] of params.entries()) {\n\t\tqueryChunks.push(param, new StringChunk(strings[paramIndex + 1]!));\n\t}\n\n\treturn new SQL(queryChunks);\n}\n\nexport namespace sql {\n\texport function empty(): SQL {\n\t\treturn new SQL([]);\n\t}\n\n\t/** @deprecated - use `sql.join()` */\n\texport function fromList(list: SQLChunk[]): SQL {\n\t\treturn new SQL(list);\n\t}\n\n\t/**\n\t * Convenience function to create an SQL query from a raw string.\n\t * @param str The raw SQL query string.\n\t */\n\texport function raw(str: string): SQL {\n\t\treturn new SQL([new StringChunk(str)]);\n\t}\n\n\t/**\n\t * Join a list of SQL chunks with a separator.\n\t * @example\n\t * ```ts\n\t * const query = sql.join([sql`a`, sql`b`, sql`c`]);\n\t * // sql`abc`\n\t * ```\n\t * @example\n\t * ```ts\n\t * const query = sql.join([sql`a`, sql`b`, sql`c`], sql`, `);\n\t * // sql`a, b, c`\n\t * ```\n\t */\n\texport function join(chunks: SQLChunk[], separator?: SQLChunk): SQL {\n\t\tconst result: SQLChunk[] = [];\n\t\tfor (const [i, chunk] of chunks.entries()) {\n\t\t\tif (i > 0 && separator !== undefined) {\n\t\t\t\tresult.push(separator);\n\t\t\t}\n\t\t\tresult.push(chunk);\n\t\t}\n\t\treturn new SQL(result);\n\t}\n\n\t/**\n\t * Create a SQL chunk that represents a DB identifier (table, column, index etc.).\n\t * When used in a query, the identifier will be escaped based on the DB engine.\n\t * For example, in PostgreSQL, identifiers are escaped with double quotes.\n\t *\n\t * **WARNING: This function does not offer any protection against SQL injections, so you must validate any user input beforehand.**\n\t *\n\t * @example ```ts\n\t * const query = sql`SELECT * FROM ${sql.identifier('my-table')}`;\n\t * // 'SELECT * FROM \"my-table\"'\n\t * ```\n\t */\n\texport function identifier(value: string): Name {\n\t\treturn new Name(value);\n\t}\n\n\texport function placeholder(name: TName): Placeholder {\n\t\treturn new Placeholder(name);\n\t}\n\n\texport function param(\n\t\tvalue: TData,\n\t\tencoder?: DriverValueEncoder,\n\t): Param {\n\t\treturn new Param(value, encoder);\n\t}\n}\n\nexport namespace SQL {\n\texport class Aliased implements SQLWrapper {\n\t\tstatic readonly [entityKind]: string = 'SQL.Aliased';\n\n\t\tdeclare _: {\n\t\t\tbrand: 'SQL.Aliased';\n\t\t\ttype: T;\n\t\t};\n\n\t\t/** @internal */\n\t\tisSelectionField = false;\n\n\t\tconstructor(\n\t\t\treadonly sql: SQL,\n\t\t\treadonly fieldAlias: string,\n\t\t) {}\n\n\t\tgetSQL(): SQL {\n\t\t\treturn this.sql;\n\t\t}\n\n\t\t/** @internal */\n\t\tclone() {\n\t\t\treturn new Aliased(this.sql, this.fieldAlias);\n\t\t}\n\t}\n}\n\nexport class Placeholder implements SQLWrapper {\n\tstatic readonly [entityKind]: string = 'Placeholder';\n\n\tdeclare protected: TValue;\n\n\tconstructor(readonly name: TName) {}\n\n\tgetSQL(): SQL {\n\t\treturn new SQL([this]);\n\t}\n}\n\n/** @deprecated Use `sql.placeholder` instead. */\nexport function placeholder(name: TName): Placeholder {\n\treturn new Placeholder(name);\n}\n\nexport function fillPlaceholders(params: unknown[], values: Record): unknown[] {\n\treturn params.map((p) => {\n\t\tif (is(p, Placeholder)) {\n\t\t\tif (!(p.name in values)) {\n\t\t\t\tthrow new Error(`No value for placeholder \"${p.name}\" was provided`);\n\t\t\t}\n\n\t\t\treturn values[p.name];\n\t\t}\n\n\t\tif (is(p, Param) && is(p.value, Placeholder)) {\n\t\t\tif (!(p.value.name in values)) {\n\t\t\t\tthrow new Error(`No value for placeholder \"${p.value.name}\" was provided`);\n\t\t\t}\n\n\t\t\treturn p.encoder.mapToDriverValue(values[p.value.name]);\n\t\t}\n\n\t\treturn p;\n\t});\n}\n\nexport type ColumnsSelection = Record;\n\nconst IsDrizzleView = Symbol.for('drizzle:IsDrizzleView');\n\nexport abstract class View<\n\tTName extends string = string,\n\tTExisting extends boolean = boolean,\n\tTSelection extends ColumnsSelection = ColumnsSelection,\n> implements SQLWrapper {\n\tstatic readonly [entityKind]: string = 'View';\n\n\tdeclare _: {\n\t\tbrand: 'View';\n\t\tviewBrand: string;\n\t\tname: TName;\n\t\texisting: TExisting;\n\t\tselectedFields: TSelection;\n\t};\n\n\t/** @internal */\n\t[ViewBaseConfig]: {\n\t\tname: TName;\n\t\toriginalName: TName;\n\t\tschema: string | undefined;\n\t\tselectedFields: ColumnsSelection;\n\t\tisExisting: TExisting;\n\t\tquery: TExisting extends true ? undefined : SQL;\n\t\tisAlias: boolean;\n\t};\n\n\t/** @internal */\n\t[IsDrizzleView] = true;\n\n\tdeclare readonly $inferSelect: InferSelectViewModel, TExisting, TSelection>>;\n\n\tconstructor(\n\t\t{ name, schema, selectedFields, query }: {\n\t\t\tname: TName;\n\t\t\tschema: string | undefined;\n\t\t\tselectedFields: ColumnsSelection;\n\t\t\tquery: SQL | undefined;\n\t\t},\n\t) {\n\t\tthis[ViewBaseConfig] = {\n\t\t\tname,\n\t\t\toriginalName: name,\n\t\t\tschema,\n\t\t\tselectedFields,\n\t\t\tquery: query as (TExisting extends true ? undefined : SQL),\n\t\t\tisExisting: !query as TExisting,\n\t\t\tisAlias: false,\n\t\t};\n\t}\n\n\tgetSQL(): SQL {\n\t\treturn new SQL([this]);\n\t}\n}\n\nexport function isView(view: unknown): view is View {\n\treturn typeof view === 'object' && view !== null && IsDrizzleView in view;\n}\n\nexport function getViewName(view: T): T['_']['name'] {\n\treturn view[ViewBaseConfig].name;\n}\n\nexport type InferSelectViewModel =\n\tEqual extends true ? { [x: string]: unknown }\n\t\t: SelectResult<\n\t\t\tTView['_']['selectedFields'],\n\t\t\t'single',\n\t\t\tRecord\n\t\t>;\n\n// Defined separately from the Column class to resolve circular dependency\nColumn.prototype.getSQL = function() {\n\treturn new SQL([this]);\n};\n\n// Defined separately from the Table class to resolve circular dependency\nTable.prototype.getSQL = function() {\n\treturn new SQL([this]);\n};\n\n// Defined separately from the Column class to resolve circular dependency\nSubquery.prototype.getSQL = function() {\n\treturn new SQL([this]);\n};\n", "import type { ColumnBuilderBaseConfig, ColumnBuilderRuntimeConfig, MakeColumnConfig } from '~/column-builder.ts';\nimport type { ColumnBaseConfig } from '~/column.ts';\nimport { entityKind } from '~/entity.ts';\nimport type { AnyPgTable } from '~/pg-core/table.ts';\nimport type { NonArray, Writable } from '~/utils.ts';\nimport { PgColumn, PgColumnBuilder } from './common.ts';\n\n// Enum as ts enum\n\nexport type PgEnumObjectColumnBuilderInitial = PgEnumObjectColumnBuilder<{\n\tname: TName;\n\tdataType: 'string';\n\tcolumnType: 'PgEnumObjectColumn';\n\tdata: TValues[keyof TValues];\n\tenumValues: string[];\n\tdriverParam: string;\n}>;\n\nexport interface PgEnumObject {\n\t(): PgEnumObjectColumnBuilderInitial<'', TValues>;\n\t(name: TName): PgEnumObjectColumnBuilderInitial;\n\t(name?: TName): PgEnumObjectColumnBuilderInitial;\n\n\treadonly enumName: string;\n\treadonly enumValues: string[];\n\treadonly schema: string | undefined;\n\t/** @internal */\n\t[isPgEnumSym]: true;\n}\n\nexport class PgEnumObjectColumnBuilder<\n\tT extends ColumnBuilderBaseConfig<'string', 'PgEnumObjectColumn'> & { enumValues: string[] },\n> extends PgColumnBuilder }> {\n\tstatic override readonly [entityKind]: string = 'PgEnumObjectColumnBuilder';\n\n\tconstructor(name: T['name'], enumInstance: PgEnumObject) {\n\t\tsuper(name, 'string', 'PgEnumObjectColumn');\n\t\tthis.config.enum = enumInstance;\n\t}\n\n\t/** @internal */\n\toverride build(\n\t\ttable: AnyPgTable<{ name: TTableName }>,\n\t): PgEnumObjectColumn> {\n\t\treturn new PgEnumObjectColumn>(\n\t\t\ttable,\n\t\t\tthis.config as ColumnBuilderRuntimeConfig,\n\t\t);\n\t}\n}\n\nexport class PgEnumObjectColumn & { enumValues: object }>\n\textends PgColumn }>\n{\n\tstatic override readonly [entityKind]: string = 'PgEnumObjectColumn';\n\n\treadonly enum;\n\toverride readonly enumValues = this.config.enum.enumValues;\n\n\tconstructor(\n\t\ttable: AnyPgTable<{ name: T['tableName'] }>,\n\t\tconfig: PgEnumObjectColumnBuilder['config'],\n\t) {\n\t\tsuper(table, config);\n\t\tthis.enum = config.enum;\n\t}\n\n\tgetSQLType(): string {\n\t\treturn this.enum.enumName;\n\t}\n}\n\n// Enum as string union\n\nexport type PgEnumColumnBuilderInitial =\n\tPgEnumColumnBuilder<{\n\t\tname: TName;\n\t\tdataType: 'string';\n\t\tcolumnType: 'PgEnumColumn';\n\t\tdata: TValues[number];\n\t\tenumValues: TValues;\n\t\tdriverParam: string;\n\t}>;\n\nconst isPgEnumSym = Symbol.for('drizzle:isPgEnum');\nexport interface PgEnum {\n\t(): PgEnumColumnBuilderInitial<'', TValues>;\n\t(name: TName): PgEnumColumnBuilderInitial;\n\t(name?: TName): PgEnumColumnBuilderInitial;\n\n\treadonly enumName: string;\n\treadonly enumValues: TValues;\n\treadonly schema: string | undefined;\n\t/** @internal */\n\t[isPgEnumSym]: true;\n}\n\nexport function isPgEnum(obj: unknown): obj is PgEnum<[string, ...string[]]> {\n\treturn !!obj && typeof obj === 'function' && isPgEnumSym in obj && obj[isPgEnumSym] === true;\n}\n\nexport class PgEnumColumnBuilder<\n\tT extends ColumnBuilderBaseConfig<'string', 'PgEnumColumn'> & { enumValues: [string, ...string[]] },\n> extends PgColumnBuilder }> {\n\tstatic override readonly [entityKind]: string = 'PgEnumColumnBuilder';\n\n\tconstructor(name: T['name'], enumInstance: PgEnum) {\n\t\tsuper(name, 'string', 'PgEnumColumn');\n\t\tthis.config.enum = enumInstance;\n\t}\n\n\t/** @internal */\n\toverride build(\n\t\ttable: AnyPgTable<{ name: TTableName }>,\n\t): PgEnumColumn> {\n\t\treturn new PgEnumColumn>(\n\t\t\ttable,\n\t\t\tthis.config as ColumnBuilderRuntimeConfig,\n\t\t);\n\t}\n}\n\nexport class PgEnumColumn & { enumValues: [string, ...string[]] }>\n\textends PgColumn }>\n{\n\tstatic override readonly [entityKind]: string = 'PgEnumColumn';\n\n\treadonly enum = this.config.enum;\n\toverride readonly enumValues = this.config.enum.enumValues;\n\n\tconstructor(\n\t\ttable: AnyPgTable<{ name: T['tableName'] }>,\n\t\tconfig: PgEnumColumnBuilder['config'],\n\t) {\n\t\tsuper(table, config);\n\t\tthis.enum = config.enum;\n\t}\n\n\tgetSQLType(): string {\n\t\treturn this.enum.enumName;\n\t}\n}\n\nexport function pgEnum>(\n\tenumName: string,\n\tvalues: T | Writable,\n): PgEnum>;\n\nexport function pgEnum>(\n\tenumName: string,\n\tenumObj: NonArray,\n): PgEnumObject;\n\nexport function pgEnum(\n\tenumName: any,\n\tinput: any,\n): any {\n\treturn Array.isArray(input)\n\t\t? pgEnumWithSchema(enumName, [...input] as [string, ...string[]], undefined)\n\t\t: pgEnumObjectWithSchema(enumName, input, undefined);\n}\n\n/** @internal */\nexport function pgEnumWithSchema>(\n\tenumName: string,\n\tvalues: T | Writable,\n\tschema?: string,\n): PgEnum> {\n\tconst enumInstance: PgEnum> = Object.assign(\n\t\t(name?: TName): PgEnumColumnBuilderInitial> =>\n\t\t\tnew PgEnumColumnBuilder(name ?? '' as TName, enumInstance),\n\t\t{\n\t\t\tenumName,\n\t\t\tenumValues: values,\n\t\t\tschema,\n\t\t\t[isPgEnumSym]: true,\n\t\t} as const,\n\t);\n\n\treturn enumInstance;\n}\n\n/** @internal */\nexport function pgEnumObjectWithSchema(\n\tenumName: string,\n\tvalues: T,\n\tschema?: string,\n): PgEnumObject {\n\tconst enumInstance: PgEnumObject = Object.assign(\n\t\t(name?: TName): PgEnumObjectColumnBuilderInitial =>\n\t\t\tnew PgEnumObjectColumnBuilder(name ?? '' as TName, enumInstance),\n\t\t{\n\t\t\tenumName,\n\t\t\tenumValues: Object.values(values),\n\t\t\tschema,\n\t\t\t[isPgEnumSym]: true,\n\t\t} as const,\n\t);\n\n\treturn enumInstance;\n}\n", "import type {\n\tColumnBuilderBase,\n\tColumnBuilderBaseConfig,\n\tColumnBuilderExtraConfig,\n\tColumnBuilderRuntimeConfig,\n\tColumnDataType,\n\tHasGenerated,\n\tMakeColumnConfig,\n} from '~/column-builder.ts';\nimport { ColumnBuilder } from '~/column-builder.ts';\nimport type { ColumnBaseConfig } from '~/column.ts';\nimport { Column } from '~/column.ts';\nimport { entityKind, is } from '~/entity.ts';\nimport type { Simplify, Update } from '~/utils.ts';\n\nimport type { ForeignKey, UpdateDeleteAction } from '~/pg-core/foreign-keys.ts';\nimport { ForeignKeyBuilder } from '~/pg-core/foreign-keys.ts';\nimport type { AnyPgTable, PgTable } from '~/pg-core/table.ts';\nimport type { SQL } from '~/sql/sql.ts';\nimport { iife } from '~/tracing-utils.ts';\nimport type { PgIndexOpClass } from '../indexes.ts';\nimport { uniqueKeyName } from '../unique-constraint.ts';\nimport { makePgArray, parsePgArray } from '../utils/array.ts';\n\nexport interface ReferenceConfig {\n\tref: () => PgColumn;\n\tactions: {\n\t\tonUpdate?: UpdateDeleteAction;\n\t\tonDelete?: UpdateDeleteAction;\n\t};\n}\n\nexport interface PgColumnBuilderBase<\n\tT extends ColumnBuilderBaseConfig = ColumnBuilderBaseConfig,\n\tTTypeConfig extends object = object,\n> extends ColumnBuilderBase {}\n\nexport abstract class PgColumnBuilder<\n\tT extends ColumnBuilderBaseConfig = ColumnBuilderBaseConfig,\n\tTRuntimeConfig extends object = object,\n\tTTypeConfig extends object = object,\n\tTExtraConfig extends ColumnBuilderExtraConfig = ColumnBuilderExtraConfig,\n> extends ColumnBuilder\n\timplements PgColumnBuilderBase\n{\n\tprivate foreignKeyConfigs: ReferenceConfig[] = [];\n\n\tstatic override readonly [entityKind]: string = 'PgColumnBuilder';\n\n\tarray(size?: TSize): PgArrayBuilder<\n\t\t& {\n\t\t\tname: T['name'];\n\t\t\tdataType: 'array';\n\t\t\tcolumnType: 'PgArray';\n\t\t\tdata: T['data'][];\n\t\t\tdriverParam: T['driverParam'][] | string;\n\t\t\tenumValues: T['enumValues'];\n\t\t\tsize: TSize;\n\t\t\tbaseBuilder: T;\n\t\t}\n\t\t& (T extends { notNull: true } ? { notNull: true } : {})\n\t\t& (T extends { hasDefault: true } ? { hasDefault: true } : {}),\n\t\tT\n\t> {\n\t\treturn new PgArrayBuilder(this.config.name, this as PgColumnBuilder, size as any);\n\t}\n\n\treferences(\n\t\tref: ReferenceConfig['ref'],\n\t\tactions: ReferenceConfig['actions'] = {},\n\t): this {\n\t\tthis.foreignKeyConfigs.push({ ref, actions });\n\t\treturn this;\n\t}\n\n\tunique(\n\t\tname?: string,\n\t\tconfig?: { nulls: 'distinct' | 'not distinct' },\n\t): this {\n\t\tthis.config.isUnique = true;\n\t\tthis.config.uniqueName = name;\n\t\tthis.config.uniqueType = config?.nulls;\n\t\treturn this;\n\t}\n\n\tgeneratedAlwaysAs(as: SQL | T['data'] | (() => SQL)): HasGenerated {\n\t\tthis.config.generated = {\n\t\t\tas,\n\t\t\ttype: 'always',\n\t\t\tmode: 'stored',\n\t\t};\n\t\treturn this as HasGenerated;\n\t}\n\n\t/** @internal */\n\tbuildForeignKeys(column: PgColumn, table: PgTable): ForeignKey[] {\n\t\treturn this.foreignKeyConfigs.map(({ ref, actions }) => {\n\t\t\treturn iife(\n\t\t\t\t(ref, actions) => {\n\t\t\t\t\tconst builder = new ForeignKeyBuilder(() => {\n\t\t\t\t\t\tconst foreignColumn = ref();\n\t\t\t\t\t\treturn { columns: [column], foreignColumns: [foreignColumn] };\n\t\t\t\t\t});\n\t\t\t\t\tif (actions.onUpdate) {\n\t\t\t\t\t\tbuilder.onUpdate(actions.onUpdate);\n\t\t\t\t\t}\n\t\t\t\t\tif (actions.onDelete) {\n\t\t\t\t\t\tbuilder.onDelete(actions.onDelete);\n\t\t\t\t\t}\n\t\t\t\t\treturn builder.build(table);\n\t\t\t\t},\n\t\t\t\tref,\n\t\t\t\tactions,\n\t\t\t);\n\t\t});\n\t}\n\n\t/** @internal */\n\tabstract build(\n\t\ttable: AnyPgTable<{ name: TTableName }>,\n\t): PgColumn>;\n\n\t/** @internal */\n\tbuildExtraConfigColumn(\n\t\ttable: AnyPgTable<{ name: TTableName }>,\n\t): ExtraConfigColumn {\n\t\treturn new ExtraConfigColumn(table, this.config);\n\t}\n}\n\n// To understand how to use `PgColumn` and `PgColumn`, see `Column` and `AnyColumn` documentation.\nexport abstract class PgColumn<\n\tT extends ColumnBaseConfig = ColumnBaseConfig,\n\tTRuntimeConfig extends object = {},\n\tTTypeConfig extends object = {},\n> extends Column {\n\tstatic override readonly [entityKind]: string = 'PgColumn';\n\n\tconstructor(\n\t\toverride readonly table: PgTable,\n\t\tconfig: ColumnBuilderRuntimeConfig,\n\t) {\n\t\tif (!config.uniqueName) {\n\t\t\tconfig.uniqueName = uniqueKeyName(table, [config.name]);\n\t\t}\n\t\tsuper(table, config);\n\t}\n}\n\nexport type IndexedExtraConfigType = { order?: 'asc' | 'desc'; nulls?: 'first' | 'last'; opClass?: string };\n\nexport class ExtraConfigColumn<\n\tT extends ColumnBaseConfig = ColumnBaseConfig,\n> extends PgColumn {\n\tstatic override readonly [entityKind]: string = 'ExtraConfigColumn';\n\n\toverride getSQLType(): string {\n\t\treturn this.getSQLType();\n\t}\n\n\tindexConfig: IndexedExtraConfigType = {\n\t\torder: this.config.order ?? 'asc',\n\t\tnulls: this.config.nulls ?? 'last',\n\t\topClass: this.config.opClass,\n\t};\n\tdefaultConfig: IndexedExtraConfigType = {\n\t\torder: 'asc',\n\t\tnulls: 'last',\n\t\topClass: undefined,\n\t};\n\n\tasc(): Omit {\n\t\tthis.indexConfig.order = 'asc';\n\t\treturn this;\n\t}\n\n\tdesc(): Omit {\n\t\tthis.indexConfig.order = 'desc';\n\t\treturn this;\n\t}\n\n\tnullsFirst(): Omit {\n\t\tthis.indexConfig.nulls = 'first';\n\t\treturn this;\n\t}\n\n\tnullsLast(): Omit {\n\t\tthis.indexConfig.nulls = 'last';\n\t\treturn this;\n\t}\n\n\t/**\n\t * ### PostgreSQL documentation quote\n\t *\n\t * > An operator class with optional parameters can be specified for each column of an index.\n\t * The operator class identifies the operators to be used by the index for that column.\n\t * For example, a B-tree index on four-byte integers would use the int4_ops class;\n\t * this operator class includes comparison functions for four-byte integers.\n\t * In practice the default operator class for the column's data type is usually sufficient.\n\t * The main point of having operator classes is that for some data types, there could be more than one meaningful ordering.\n\t * For example, we might want to sort a complex-number data type either by absolute value or by real part.\n\t * We could do this by defining two operator classes for the data type and then selecting the proper class when creating an index.\n\t * More information about operator classes check:\n\t *\n\t * ### Useful links\n\t * https://www.postgresql.org/docs/current/sql-createindex.html\n\t *\n\t * https://www.postgresql.org/docs/current/indexes-opclass.html\n\t *\n\t * https://www.postgresql.org/docs/current/xindex.html\n\t *\n\t * ### Additional types\n\t * If you have the `pg_vector` extension installed in your database, you can use the\n\t * `vector_l2_ops`, `vector_ip_ops`, `vector_cosine_ops`, `vector_l1_ops`, `bit_hamming_ops`, `bit_jaccard_ops`, `halfvec_l2_ops`, `sparsevec_l2_ops` options, which are predefined types.\n\t *\n\t * **You can always specify any string you want in the operator class, in case Drizzle doesn't have it natively in its types**\n\t *\n\t * @param opClass\n\t * @returns\n\t */\n\top(opClass: PgIndexOpClass): Omit {\n\t\tthis.indexConfig.opClass = opClass;\n\t\treturn this;\n\t}\n}\n\nexport class IndexedColumn {\n\tstatic readonly [entityKind]: string = 'IndexedColumn';\n\tconstructor(\n\t\tname: string | undefined,\n\t\tkeyAsName: boolean,\n\t\ttype: string,\n\t\tindexConfig: IndexedExtraConfigType,\n\t) {\n\t\tthis.name = name;\n\t\tthis.keyAsName = keyAsName;\n\t\tthis.type = type;\n\t\tthis.indexConfig = indexConfig;\n\t}\n\n\tname: string | undefined;\n\tkeyAsName: boolean;\n\ttype: string;\n\tindexConfig: IndexedExtraConfigType;\n}\n\nexport type AnyPgColumn> = {}> = PgColumn<\n\tRequired, TPartial>>\n>;\n\nexport type PgArrayColumnBuilderBaseConfig = ColumnBuilderBaseConfig<'array', 'PgArray'> & {\n\tsize: number | undefined;\n\tbaseBuilder: ColumnBuilderBaseConfig;\n};\n\nexport class PgArrayBuilder<\n\tT extends PgArrayColumnBuilderBaseConfig,\n\tTBase extends ColumnBuilderBaseConfig | PgArrayColumnBuilderBaseConfig,\n> extends PgColumnBuilder<\n\tT,\n\t{\n\t\tbaseBuilder: TBase extends PgArrayColumnBuilderBaseConfig ? PgArrayBuilder<\n\t\t\t\tTBase,\n\t\t\t\tTBase extends { baseBuilder: infer TBaseBuilder extends ColumnBuilderBaseConfig } ? TBaseBuilder\n\t\t\t\t\t: never\n\t\t\t>\n\t\t\t: PgColumnBuilder>>>;\n\t\tsize: T['size'];\n\t},\n\t{\n\t\tbaseBuilder: TBase extends PgArrayColumnBuilderBaseConfig ? PgArrayBuilder<\n\t\t\t\tTBase,\n\t\t\t\tTBase extends { baseBuilder: infer TBaseBuilder extends ColumnBuilderBaseConfig } ? TBaseBuilder\n\t\t\t\t\t: never\n\t\t\t>\n\t\t\t: PgColumnBuilder>>>;\n\t\tsize: T['size'];\n\t}\n> {\n\tstatic override readonly [entityKind] = 'PgArrayBuilder';\n\n\tconstructor(\n\t\tname: string,\n\t\tbaseBuilder: PgArrayBuilder['config']['baseBuilder'],\n\t\tsize: T['size'],\n\t) {\n\t\tsuper(name, 'array', 'PgArray');\n\t\tthis.config.baseBuilder = baseBuilder;\n\t\tthis.config.size = size;\n\t}\n\n\t/** @internal */\n\toverride build(\n\t\ttable: AnyPgTable<{ name: TTableName }>,\n\t): PgArray & { size: T['size']; baseBuilder: T['baseBuilder'] }, TBase> {\n\t\tconst baseColumn = this.config.baseBuilder.build(table);\n\t\treturn new PgArray & { size: T['size']; baseBuilder: T['baseBuilder'] }, TBase>(\n\t\t\ttable as AnyPgTable<{ name: MakeColumnConfig['tableName'] }>,\n\t\t\tthis.config as ColumnBuilderRuntimeConfig,\n\t\t\tbaseColumn,\n\t\t);\n\t}\n}\n\nexport class PgArray<\n\tT extends ColumnBaseConfig<'array', 'PgArray'> & {\n\t\tsize: number | undefined;\n\t\tbaseBuilder: ColumnBuilderBaseConfig;\n\t},\n\tTBase extends ColumnBuilderBaseConfig,\n> extends PgColumn {\n\treadonly size: T['size'];\n\n\tstatic override readonly [entityKind]: string = 'PgArray';\n\n\tconstructor(\n\t\ttable: AnyPgTable<{ name: T['tableName'] }>,\n\t\tconfig: PgArrayBuilder['config'],\n\t\treadonly baseColumn: PgColumn,\n\t\treadonly range?: [number | undefined, number | undefined],\n\t) {\n\t\tsuper(table, config);\n\t\tthis.size = config.size;\n\t}\n\n\tgetSQLType(): string {\n\t\treturn `${this.baseColumn.getSQLType()}[${typeof this.size === 'number' ? this.size : ''}]`;\n\t}\n\n\toverride mapFromDriverValue(value: unknown[] | string): T['data'] {\n\t\tif (typeof value === 'string') {\n\t\t\t// Thank you node-postgres for not parsing enum arrays\n\t\t\tvalue = parsePgArray(value);\n\t\t}\n\t\treturn value.map((v) => this.baseColumn.mapFromDriverValue(v));\n\t}\n\n\toverride mapToDriverValue(value: unknown[], isNestedArray = false): unknown[] | string {\n\t\tconst a = value.map((v) =>\n\t\t\tv === null\n\t\t\t\t? null\n\t\t\t\t: is(this.baseColumn, PgArray)\n\t\t\t\t? this.baseColumn.mapToDriverValue(v as unknown[], true)\n\t\t\t\t: this.baseColumn.mapToDriverValue(v)\n\t\t);\n\t\tif (isNestedArray) return a;\n\t\treturn makePgArray(a);\n\t}\n}\n", "import { entityKind } from '~/entity.ts';\nimport type { Column } from './column.ts';\nimport type { GelColumn, GelExtraConfigColumn } from './gel-core/index.ts';\nimport type { MySqlColumn } from './mysql-core/index.ts';\nimport type { ExtraConfigColumn, PgColumn, PgSequenceOptions } from './pg-core/index.ts';\nimport type { SingleStoreColumn } from './singlestore-core/index.ts';\nimport type { SQL } from './sql/sql.ts';\nimport type { SQLiteColumn } from './sqlite-core/index.ts';\nimport type { Assume, Simplify } from './utils.ts';\n\nexport type ColumnDataType =\n\t| 'string'\n\t| 'number'\n\t| 'boolean'\n\t| 'array'\n\t| 'json'\n\t| 'date'\n\t| 'bigint'\n\t| 'custom'\n\t| 'buffer'\n\t| 'dateDuration'\n\t| 'duration'\n\t| 'relDuration'\n\t| 'localTime'\n\t| 'localDate'\n\t| 'localDateTime';\n\nexport type Dialect = 'pg' | 'mysql' | 'sqlite' | 'singlestore' | 'common' | 'gel';\n\nexport type GeneratedStorageMode = 'virtual' | 'stored';\n\nexport type GeneratedType = 'always' | 'byDefault';\n\nexport type GeneratedColumnConfig = {\n\tas: TDataType | SQL | (() => SQL);\n\ttype?: GeneratedType;\n\tmode?: GeneratedStorageMode;\n};\n\nexport type GeneratedIdentityConfig = {\n\tsequenceName?: string;\n\tsequenceOptions?: PgSequenceOptions;\n\ttype: 'always' | 'byDefault';\n};\n\nexport interface ColumnBuilderBaseConfig {\n\tname: string;\n\tdataType: TDataType;\n\tcolumnType: TColumnType;\n\tdata: unknown;\n\tdriverParam: unknown;\n\tenumValues: string[] | undefined;\n}\n\nexport type MakeColumnConfig<\n\tT extends ColumnBuilderBaseConfig,\n\tTTableName extends string,\n\tTData = T extends { $type: infer U } ? U : T['data'],\n> = {\n\tname: T['name'];\n\ttableName: TTableName;\n\tdataType: T['dataType'];\n\tcolumnType: T['columnType'];\n\tdata: TData;\n\tdriverParam: T['driverParam'];\n\tnotNull: T extends { notNull: true } ? true : false;\n\thasDefault: T extends { hasDefault: true } ? true : false;\n\tisPrimaryKey: T extends { isPrimaryKey: true } ? true : false;\n\tisAutoincrement: T extends { isAutoincrement: true } ? true : false;\n\thasRuntimeDefault: T extends { hasRuntimeDefault: true } ? true : false;\n\tenumValues: T['enumValues'];\n\tbaseColumn: T extends { baseBuilder: infer U extends ColumnBuilderBase } ? BuildColumn\n\t\t: never;\n\tidentity: T extends { identity: 'always' } ? 'always' : T extends { identity: 'byDefault' } ? 'byDefault' : undefined;\n\tgenerated: T extends { generated: infer G } ? unknown extends G ? undefined\n\t\t: G extends undefined ? undefined\n\t\t: G\n\t\t: undefined;\n} & {};\n\nexport type ColumnBuilderTypeConfig<\n\t// eslint-disable-next-line @typescript-eslint/no-unused-vars\n\tT extends ColumnBuilderBaseConfig,\n\tTTypeConfig extends object = object,\n> = Simplify<\n\t& {\n\t\tbrand: 'ColumnBuilder';\n\t\tname: T['name'];\n\t\tdataType: T['dataType'];\n\t\tcolumnType: T['columnType'];\n\t\tdata: T['data'];\n\t\tdriverParam: T['driverParam'];\n\t\tnotNull: T extends { notNull: infer U } ? U : boolean;\n\t\thasDefault: T extends { hasDefault: infer U } ? U : boolean;\n\t\tenumValues: T['enumValues'];\n\t\tidentity: T extends { identity: infer U } ? U : unknown;\n\t\tgenerated: T extends { generated: infer G } ? G extends undefined ? unknown : G : unknown;\n\t}\n\t& TTypeConfig\n>;\n\nexport type ColumnBuilderRuntimeConfig = {\n\tname: string;\n\tkeyAsName: boolean;\n\tnotNull: boolean;\n\tdefault: TData | SQL | undefined;\n\tdefaultFn: (() => TData | SQL) | undefined;\n\tonUpdateFn: (() => TData | SQL) | undefined;\n\thasDefault: boolean;\n\tprimaryKey: boolean;\n\tisUnique: boolean;\n\tuniqueName: string | undefined;\n\tuniqueType: string | undefined;\n\tdataType: string;\n\tcolumnType: string;\n\tgenerated: GeneratedColumnConfig | undefined;\n\tgeneratedIdentity: GeneratedIdentityConfig | undefined;\n} & TRuntimeConfig;\n\nexport interface ColumnBuilderExtraConfig {\n\tprimaryKeyHasDefault?: boolean;\n}\n\nexport type NotNull = T & {\n\t_: {\n\t\tnotNull: true;\n\t};\n};\n\nexport type HasDefault = T & {\n\t_: {\n\t\thasDefault: true;\n\t};\n};\n\nexport type IsPrimaryKey = T & {\n\t_: {\n\t\tisPrimaryKey: true;\n\t};\n};\n\nexport type IsAutoincrement = T & {\n\t_: {\n\t\tisAutoincrement: true;\n\t};\n};\n\nexport type HasRuntimeDefault = T & {\n\t_: {\n\t\thasRuntimeDefault: true;\n\t};\n};\n\nexport type $Type = T & {\n\t_: {\n\t\t$type: TType;\n\t};\n};\n\nexport type HasGenerated = T & {\n\t_: {\n\t\thasDefault: true;\n\t\tgenerated: TGenerated;\n\t};\n};\n\nexport type IsIdentity<\n\tT extends ColumnBuilderBase,\n\tTType extends 'always' | 'byDefault',\n> = T & {\n\t_: {\n\t\tnotNull: true;\n\t\thasDefault: true;\n\t\tidentity: TType;\n\t};\n};\nexport interface ColumnBuilderBase<\n\tT extends ColumnBuilderBaseConfig = ColumnBuilderBaseConfig,\n\tTTypeConfig extends object = object,\n> {\n\t_: ColumnBuilderTypeConfig;\n}\n\n// To understand how to use `ColumnBuilder` and `AnyColumnBuilder`, see `Column` and `AnyColumn` documentation.\nexport abstract class ColumnBuilder<\n\tT extends ColumnBuilderBaseConfig = ColumnBuilderBaseConfig,\n\tTRuntimeConfig extends object = object,\n\tTTypeConfig extends object = object,\n\tTExtraConfig extends ColumnBuilderExtraConfig = ColumnBuilderExtraConfig,\n> implements ColumnBuilderBase {\n\tstatic readonly [entityKind]: string = 'ColumnBuilder';\n\n\tdeclare _: ColumnBuilderTypeConfig;\n\n\tprotected config: ColumnBuilderRuntimeConfig;\n\n\tconstructor(name: T['name'], dataType: T['dataType'], columnType: T['columnType']) {\n\t\tthis.config = {\n\t\t\tname,\n\t\t\tkeyAsName: name === '',\n\t\t\tnotNull: false,\n\t\t\tdefault: undefined,\n\t\t\thasDefault: false,\n\t\t\tprimaryKey: false,\n\t\t\tisUnique: false,\n\t\t\tuniqueName: undefined,\n\t\t\tuniqueType: undefined,\n\t\t\tdataType,\n\t\t\tcolumnType,\n\t\t\tgenerated: undefined,\n\t\t} as ColumnBuilderRuntimeConfig;\n\t}\n\n\t/**\n\t * Changes the data type of the column. Commonly used with `json` columns. Also, useful for branded types.\n\t *\n\t * @example\n\t * ```ts\n\t * const users = pgTable('users', {\n\t * \tid: integer('id').$type().primaryKey(),\n\t * \tdetails: json('details').$type().notNull(),\n\t * });\n\t * ```\n\t */\n\t$type(): $Type {\n\t\treturn this as $Type;\n\t}\n\n\t/**\n\t * Adds a `not null` clause to the column definition.\n\t *\n\t * Affects the `select` model of the table - columns *without* `not null` will be nullable on select.\n\t */\n\tnotNull(): NotNull {\n\t\tthis.config.notNull = true;\n\t\treturn this as NotNull;\n\t}\n\n\t/**\n\t * Adds a `default ` clause to the column definition.\n\t *\n\t * Affects the `insert` model of the table - columns *with* `default` are optional on insert.\n\t *\n\t * If you need to set a dynamic default value, use {@link $defaultFn} instead.\n\t */\n\tdefault(value: (this['_'] extends { $type: infer U } ? U : this['_']['data']) | SQL): HasDefault {\n\t\tthis.config.default = value;\n\t\tthis.config.hasDefault = true;\n\t\treturn this as HasDefault;\n\t}\n\n\t/**\n\t * Adds a dynamic default value to the column.\n\t * The function will be called when the row is inserted, and the returned value will be used as the column value.\n\t *\n\t * **Note:** This value does not affect the `drizzle-kit` behavior, it is only used at runtime in `drizzle-orm`.\n\t */\n\t$defaultFn(\n\t\tfn: () => (this['_'] extends { $type: infer U } ? U : this['_']['data']) | SQL,\n\t): HasRuntimeDefault> {\n\t\tthis.config.defaultFn = fn;\n\t\tthis.config.hasDefault = true;\n\t\treturn this as HasRuntimeDefault>;\n\t}\n\n\t/**\n\t * Alias for {@link $defaultFn}.\n\t */\n\t$default = this.$defaultFn;\n\n\t/**\n\t * Adds a dynamic update value to the column.\n\t * The function will be called when the row is updated, and the returned value will be used as the column value if none is provided.\n\t * If no `default` (or `$defaultFn`) value is provided, the function will be called when the row is inserted as well, and the returned value will be used as the column value.\n\t *\n\t * **Note:** This value does not affect the `drizzle-kit` behavior, it is only used at runtime in `drizzle-orm`.\n\t */\n\t$onUpdateFn(\n\t\tfn: () => (this['_'] extends { $type: infer U } ? U : this['_']['data']) | SQL,\n\t): HasDefault {\n\t\tthis.config.onUpdateFn = fn;\n\t\tthis.config.hasDefault = true;\n\t\treturn this as HasDefault;\n\t}\n\n\t/**\n\t * Alias for {@link $onUpdateFn}.\n\t */\n\t$onUpdate = this.$onUpdateFn;\n\n\t/**\n\t * Adds a `primary key` clause to the column definition. This implicitly makes the column `not null`.\n\t *\n\t * In SQLite, `integer primary key` implicitly makes the column auto-incrementing.\n\t */\n\tprimaryKey(): TExtraConfig['primaryKeyHasDefault'] extends true ? IsPrimaryKey>>\n\t\t: IsPrimaryKey>\n\t{\n\t\tthis.config.primaryKey = true;\n\t\tthis.config.notNull = true;\n\t\treturn this as TExtraConfig['primaryKeyHasDefault'] extends true ? IsPrimaryKey>>\n\t\t\t: IsPrimaryKey>;\n\t}\n\n\tabstract generatedAlwaysAs(\n\t\tas: SQL | T['data'] | (() => SQL),\n\t\tconfig?: Partial>,\n\t): HasGenerated;\n\n\t/** @internal Sets the name of the column to the key within the table definition if a name was not given. */\n\tsetName(name: string) {\n\t\tif (this.config.name !== '') return;\n\t\tthis.config.name = name;\n\t}\n}\n\nexport type BuildColumn<\n\tTTableName extends string,\n\tTBuilder extends ColumnBuilderBase,\n\tTDialect extends Dialect,\n> = TDialect extends 'pg' ? PgColumn<\n\t\tMakeColumnConfig,\n\t\t{},\n\t\tSimplify | 'brand' | 'dialect'>>\n\t>\n\t: TDialect extends 'mysql' ? MySqlColumn<\n\t\t\tMakeColumnConfig,\n\t\t\t{},\n\t\t\tSimplify<\n\t\t\t\tOmit<\n\t\t\t\t\tTBuilder['_'],\n\t\t\t\t\t| keyof MakeColumnConfig\n\t\t\t\t\t| 'brand'\n\t\t\t\t\t| 'dialect'\n\t\t\t\t\t| 'primaryKeyHasDefault'\n\t\t\t\t\t| 'mysqlColumnBuilderBrand'\n\t\t\t\t>\n\t\t\t>\n\t\t>\n\t: TDialect extends 'sqlite' ? SQLiteColumn<\n\t\t\tMakeColumnConfig,\n\t\t\t{},\n\t\t\tSimplify | 'brand' | 'dialect'>>\n\t\t>\n\t: TDialect extends 'common' ? Column<\n\t\t\tMakeColumnConfig,\n\t\t\t{},\n\t\t\tSimplify | 'brand' | 'dialect'>>\n\t\t>\n\t: TDialect extends 'singlestore' ? SingleStoreColumn<\n\t\t\tMakeColumnConfig,\n\t\t\t{},\n\t\t\tSimplify<\n\t\t\t\tOmit<\n\t\t\t\t\tTBuilder['_'],\n\t\t\t\t\t| keyof MakeColumnConfig\n\t\t\t\t\t| 'brand'\n\t\t\t\t\t| 'dialect'\n\t\t\t\t\t| 'primaryKeyHasDefault'\n\t\t\t\t\t| 'singlestoreColumnBuilderBrand'\n\t\t\t\t>\n\t\t\t>\n\t\t>\n\t: TDialect extends 'gel' ? GelColumn<\n\t\t\tMakeColumnConfig,\n\t\t\t{},\n\t\t\tSimplify | 'brand' | 'dialect'>>\n\t\t>\n\t: never;\n\nexport type BuildIndexColumn<\n\tTDialect extends Dialect,\n> = TDialect extends 'pg' ? ExtraConfigColumn\n\t: TDialect extends 'gel' ? GelExtraConfigColumn\n\t: never;\n\n// TODO\n// try to make sql as well + indexRaw\n\n// optional after everything will be working as expected\n// also try to leave only needed methods for extraConfig\n// make an error if I pass .asc() to fk and so on\n\nexport type BuildColumns<\n\tTTableName extends string,\n\tTConfigMap extends Record,\n\tTDialect extends Dialect,\n> =\n\t& {\n\t\t[Key in keyof TConfigMap]: BuildColumn\n\t\t\t\t& { name: TConfigMap[Key]['_']['name'] extends '' ? Assume : TConfigMap[Key]['_']['name'] };\n\t\t}, TDialect>;\n\t}\n\t& {};\n\nexport type BuildExtraConfigColumns<\n\t_TTableName extends string,\n\tTConfigMap extends Record,\n\tTDialect extends Dialect,\n> =\n\t& {\n\t\t[Key in keyof TConfigMap]: BuildIndexColumn;\n\t}\n\t& {};\n\nexport type ChangeColumnTableName =\n\tTDialect extends 'pg' ? PgColumn>\n\t\t: TDialect extends 'mysql' ? MySqlColumn>\n\t\t: TDialect extends 'singlestore' ? SingleStoreColumn>\n\t\t: TDialect extends 'sqlite' ? SQLiteColumn>\n\t\t: TDialect extends 'gel' ? GelColumn>\n\t\t: never;\n", "import { entityKind } from '~/entity.ts';\nimport { TableName } from '~/table.utils.ts';\nimport type { AnyPgColumn, PgColumn } from './columns/index.ts';\nimport type { PgTable } from './table.ts';\n\nexport type UpdateDeleteAction = 'cascade' | 'restrict' | 'no action' | 'set null' | 'set default';\n\nexport type Reference = () => {\n\treadonly name?: string;\n\treadonly columns: PgColumn[];\n\treadonly foreignTable: PgTable;\n\treadonly foreignColumns: PgColumn[];\n};\n\nexport class ForeignKeyBuilder {\n\tstatic readonly [entityKind]: string = 'PgForeignKeyBuilder';\n\n\t/** @internal */\n\treference: Reference;\n\n\t/** @internal */\n\t_onUpdate: UpdateDeleteAction | undefined = 'no action';\n\n\t/** @internal */\n\t_onDelete: UpdateDeleteAction | undefined = 'no action';\n\n\tconstructor(\n\t\tconfig: () => {\n\t\t\tname?: string;\n\t\t\tcolumns: PgColumn[];\n\t\t\tforeignColumns: PgColumn[];\n\t\t},\n\t\tactions?: {\n\t\t\tonUpdate?: UpdateDeleteAction;\n\t\t\tonDelete?: UpdateDeleteAction;\n\t\t} | undefined,\n\t) {\n\t\tthis.reference = () => {\n\t\t\tconst { name, columns, foreignColumns } = config();\n\t\t\treturn { name, columns, foreignTable: foreignColumns[0]!.table as PgTable, foreignColumns };\n\t\t};\n\t\tif (actions) {\n\t\t\tthis._onUpdate = actions.onUpdate;\n\t\t\tthis._onDelete = actions.onDelete;\n\t\t}\n\t}\n\n\tonUpdate(action: UpdateDeleteAction): this {\n\t\tthis._onUpdate = action === undefined ? 'no action' : action;\n\t\treturn this;\n\t}\n\n\tonDelete(action: UpdateDeleteAction): this {\n\t\tthis._onDelete = action === undefined ? 'no action' : action;\n\t\treturn this;\n\t}\n\n\t/** @internal */\n\tbuild(table: PgTable): ForeignKey {\n\t\treturn new ForeignKey(table, this);\n\t}\n}\n\nexport type AnyForeignKeyBuilder = ForeignKeyBuilder;\n\nexport class ForeignKey {\n\tstatic readonly [entityKind]: string = 'PgForeignKey';\n\n\treadonly reference: Reference;\n\treadonly onUpdate: UpdateDeleteAction | undefined;\n\treadonly onDelete: UpdateDeleteAction | undefined;\n\n\tconstructor(readonly table: PgTable, builder: ForeignKeyBuilder) {\n\t\tthis.reference = builder.reference;\n\t\tthis.onUpdate = builder._onUpdate;\n\t\tthis.onDelete = builder._onDelete;\n\t}\n\n\tgetName(): string {\n\t\tconst { name, columns, foreignColumns } = this.reference();\n\t\tconst columnNames = columns.map((column) => column.name);\n\t\tconst foreignColumnNames = foreignColumns.map((column) => column.name);\n\t\tconst chunks = [\n\t\t\tthis.table[TableName],\n\t\t\t...columnNames,\n\t\t\tforeignColumns[0]!.table[TableName],\n\t\t\t...foreignColumnNames,\n\t\t];\n\t\treturn name ?? `${chunks.join('_')}_fk`;\n\t}\n}\n\ntype ColumnsWithTable<\n\tTTableName extends string,\n\tTColumns extends PgColumn[],\n> = { [Key in keyof TColumns]: AnyPgColumn<{ tableName: TTableName }> };\n\nexport function foreignKey<\n\tTTableName extends string,\n\tTForeignTableName extends string,\n\tTColumns extends [AnyPgColumn<{ tableName: TTableName }>, ...AnyPgColumn<{ tableName: TTableName }>[]],\n>(\n\tconfig: {\n\t\tname?: string;\n\t\tcolumns: TColumns;\n\t\tforeignColumns: ColumnsWithTable;\n\t},\n): ForeignKeyBuilder {\n\tfunction mappedConfig() {\n\t\tconst { name, columns, foreignColumns } = config;\n\t\treturn {\n\t\t\tname,\n\t\t\tcolumns,\n\t\t\tforeignColumns,\n\t\t};\n\t}\n\n\treturn new ForeignKeyBuilder(mappedConfig);\n}\n", "export function iife(fn: (...args: T) => U, ...args: T): U {\n\treturn fn(...args);\n}\n", "import { entityKind } from '~/entity.ts';\nimport { TableName } from '~/table.utils.ts';\nimport type { PgColumn } from './columns/index.ts';\nimport type { PgTable } from './table.ts';\n\nexport function unique(name?: string): UniqueOnConstraintBuilder {\n\treturn new UniqueOnConstraintBuilder(name);\n}\n\nexport function uniqueKeyName(table: PgTable, columns: string[]) {\n\treturn `${table[TableName]}_${columns.join('_')}_unique`;\n}\n\nexport class UniqueConstraintBuilder {\n\tstatic readonly [entityKind]: string = 'PgUniqueConstraintBuilder';\n\n\t/** @internal */\n\tcolumns: PgColumn[];\n\t/** @internal */\n\tnullsNotDistinctConfig = false;\n\n\tconstructor(\n\t\tcolumns: PgColumn[],\n\t\tprivate name?: string,\n\t) {\n\t\tthis.columns = columns;\n\t}\n\n\tnullsNotDistinct() {\n\t\tthis.nullsNotDistinctConfig = true;\n\t\treturn this;\n\t}\n\n\t/** @internal */\n\tbuild(table: PgTable): UniqueConstraint {\n\t\treturn new UniqueConstraint(table, this.columns, this.nullsNotDistinctConfig, this.name);\n\t}\n}\n\nexport class UniqueOnConstraintBuilder {\n\tstatic readonly [entityKind]: string = 'PgUniqueOnConstraintBuilder';\n\n\t/** @internal */\n\tname?: string;\n\n\tconstructor(\n\t\tname?: string,\n\t) {\n\t\tthis.name = name;\n\t}\n\n\ton(...columns: [PgColumn, ...PgColumn[]]) {\n\t\treturn new UniqueConstraintBuilder(columns, this.name);\n\t}\n}\n\nexport class UniqueConstraint {\n\tstatic readonly [entityKind]: string = 'PgUniqueConstraint';\n\n\treadonly columns: PgColumn[];\n\treadonly name?: string;\n\treadonly nullsNotDistinct: boolean = false;\n\n\tconstructor(readonly table: PgTable, columns: PgColumn[], nullsNotDistinct: boolean, name?: string) {\n\t\tthis.columns = columns;\n\t\tthis.name = name ?? uniqueKeyName(this.table, this.columns.map((column) => column.name));\n\t\tthis.nullsNotDistinct = nullsNotDistinct;\n\t}\n\n\tgetName() {\n\t\treturn this.name;\n\t}\n}\n", "function parsePgArrayValue(arrayString: string, startFrom: number, inQuotes: boolean): [string, number] {\n\tfor (let i = startFrom; i < arrayString.length; i++) {\n\t\tconst char = arrayString[i];\n\n\t\tif (char === '\\\\') {\n\t\t\ti++;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (char === '\"') {\n\t\t\treturn [arrayString.slice(startFrom, i).replace(/\\\\/g, ''), i + 1];\n\t\t}\n\n\t\tif (inQuotes) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (char === ',' || char === '}') {\n\t\t\treturn [arrayString.slice(startFrom, i).replace(/\\\\/g, ''), i];\n\t\t}\n\t}\n\n\treturn [arrayString.slice(startFrom).replace(/\\\\/g, ''), arrayString.length];\n}\n\nexport function parsePgNestedArray(arrayString: string, startFrom = 0): [any[], number] {\n\tconst result: any[] = [];\n\tlet i = startFrom;\n\tlet lastCharIsComma = false;\n\n\twhile (i < arrayString.length) {\n\t\tconst char = arrayString[i];\n\n\t\tif (char === ',') {\n\t\t\tif (lastCharIsComma || i === startFrom) {\n\t\t\t\tresult.push('');\n\t\t\t}\n\t\t\tlastCharIsComma = true;\n\t\t\ti++;\n\t\t\tcontinue;\n\t\t}\n\n\t\tlastCharIsComma = false;\n\n\t\tif (char === '\\\\') {\n\t\t\ti += 2;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (char === '\"') {\n\t\t\tconst [value, startFrom] = parsePgArrayValue(arrayString, i + 1, true);\n\t\t\tresult.push(value);\n\t\t\ti = startFrom;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (char === '}') {\n\t\t\treturn [result, i + 1];\n\t\t}\n\n\t\tif (char === '{') {\n\t\t\tconst [value, startFrom] = parsePgNestedArray(arrayString, i + 1);\n\t\t\tresult.push(value);\n\t\t\ti = startFrom;\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst [value, newStartFrom] = parsePgArrayValue(arrayString, i, false);\n\t\tresult.push(value);\n\t\ti = newStartFrom;\n\t}\n\n\treturn [result, i];\n}\n\nexport function parsePgArray(arrayString: string): any[] {\n\tconst [result] = parsePgNestedArray(arrayString, 1);\n\treturn result;\n}\n\nexport function makePgArray(array: any[]): string {\n\treturn `{${\n\t\tarray.map((item) => {\n\t\t\tif (Array.isArray(item)) {\n\t\t\t\treturn makePgArray(item);\n\t\t\t}\n\n\t\t\tif (typeof item === 'string') {\n\t\t\t\treturn `\"${item.replace(/\\\\/g, '\\\\\\\\').replace(/\"/g, '\\\\\"')}\"`;\n\t\t\t}\n\n\t\t\treturn `${item}`;\n\t\t}).join(',')\n\t}}`;\n}\n", "import { entityKind } from './entity.ts';\nimport type { SQL, SQLWrapper } from './sql/sql.ts';\n\nexport interface Subquery<\n\t// eslint-disable-next-line @typescript-eslint/no-unused-vars\n\tTAlias extends string = string,\n\t// eslint-disable-next-line @typescript-eslint/no-unused-vars\n\tTSelectedFields extends Record = Record,\n> extends SQLWrapper {\n\t// SQLWrapper runtime implementation is defined in 'sql/sql.ts'\n}\nexport class Subquery<\n\tTAlias extends string = string,\n\tTSelectedFields extends Record = Record,\n> implements SQLWrapper {\n\tstatic readonly [entityKind]: string = 'Subquery';\n\n\tdeclare _: {\n\t\tbrand: 'Subquery';\n\t\tsql: SQL;\n\t\tselectedFields: TSelectedFields;\n\t\talias: TAlias;\n\t\tisWith: boolean;\n\t\tusedTables?: string[];\n\t};\n\n\tconstructor(sql: SQL, fields: TSelectedFields, alias: string, isWith = false, usedTables: string[] = []) {\n\t\tthis._ = {\n\t\t\tbrand: 'Subquery',\n\t\t\tsql,\n\t\t\tselectedFields: fields as TSelectedFields,\n\t\t\talias: alias as TAlias,\n\t\t\tisWith,\n\t\t\tusedTables,\n\t\t};\n\t}\n\n\t// getSQL(): SQL {\n\t// \treturn new SQL([this]);\n\t// }\n}\n\nexport class WithSubquery<\n\tTAlias extends string = string,\n\tTSelection extends Record = Record,\n> extends Subquery {\n\tstatic override readonly [entityKind]: string = 'WithSubquery';\n}\n\nexport type WithSubqueryWithoutSelection = WithSubquery;\n", "import type { Span, Tracer } from '@opentelemetry/api';\nimport { iife } from '~/tracing-utils.ts';\nimport { npmVersion } from '~/version.ts';\n\nlet otel: typeof import('@opentelemetry/api') | undefined;\nlet rawTracer: Tracer | undefined;\n// try {\n// \totel = await import('@opentelemetry/api');\n// } catch (err: any) {\n// \tif (err.code !== 'MODULE_NOT_FOUND' && err.code !== 'ERR_MODULE_NOT_FOUND') {\n// \t\tthrow err;\n// \t}\n// }\n\ntype SpanName =\n\t| 'drizzle.operation'\n\t| 'drizzle.prepareQuery'\n\t| 'drizzle.buildSQL'\n\t| 'drizzle.execute'\n\t| 'drizzle.driver.execute'\n\t| 'drizzle.mapResponse';\n\n/** @internal */\nexport const tracer = {\n\tstartActiveSpan unknown>(name: SpanName, fn: F): ReturnType {\n\t\tif (!otel) {\n\t\t\treturn fn() as ReturnType;\n\t\t}\n\n\t\tif (!rawTracer) {\n\t\t\trawTracer = otel.trace.getTracer('drizzle-orm', npmVersion);\n\t\t}\n\n\t\treturn iife(\n\t\t\t(otel, rawTracer) =>\n\t\t\t\trawTracer.startActiveSpan(\n\t\t\t\t\tname,\n\t\t\t\t\t((span: Span) => {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\treturn fn(span);\n\t\t\t\t\t\t} catch (e) {\n\t\t\t\t\t\t\tspan.setStatus({\n\t\t\t\t\t\t\t\tcode: otel.SpanStatusCode.ERROR,\n\t\t\t\t\t\t\t\tmessage: e instanceof Error ? e.message : 'Unknown error', // eslint-disable-line no-instanceof/no-instanceof\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tthrow e;\n\t\t\t\t\t\t} finally {\n\t\t\t\t\t\t\tspan.end();\n\t\t\t\t\t\t}\n\t\t\t\t\t}) as F,\n\t\t\t\t),\n\t\t\totel,\n\t\t\trawTracer,\n\t\t);\n\t},\n};\n", "// package.json\nvar version = \"0.45.1\";\n\n// src/version.ts\nvar compatibilityVersion = 10;\nexport {\n compatibilityVersion,\n version as npmVersion\n};\n", "export const ViewBaseConfig = Symbol.for('drizzle:ViewBaseConfig');\n", "import { type AnyColumn, Column, type GetColumnData } from '~/column.ts';\nimport { is } from '~/entity.ts';\nimport { Table } from '~/table.ts';\nimport {\n\tisDriverValueEncoder,\n\tisSQLWrapper,\n\tParam,\n\tPlaceholder,\n\tSQL,\n\tsql,\n\ttype SQLChunk,\n\ttype SQLWrapper,\n\tStringChunk,\n\tView,\n} from '../sql.ts';\n\nexport function bindIfParam(value: unknown, column: SQLWrapper): SQLChunk {\n\tif (\n\t\tisDriverValueEncoder(column)\n\t\t&& !isSQLWrapper(value)\n\t\t&& !is(value, Param)\n\t\t&& !is(value, Placeholder)\n\t\t&& !is(value, Column)\n\t\t&& !is(value, Table)\n\t\t&& !is(value, View)\n\t) {\n\t\treturn new Param(value, column);\n\t}\n\treturn value as SQLChunk;\n}\n\nexport interface BinaryOperator {\n\t(\n\t\tleft: TColumn,\n\t\tright: GetColumnData | SQLWrapper,\n\t): SQL;\n\t(left: SQL.Aliased, right: T | SQLWrapper): SQL;\n\t(\n\t\tleft: Exclude,\n\t\tright: unknown,\n\t): SQL;\n}\n\n/**\n * Test that two values are equal.\n *\n * Remember that the SQL standard dictates that\n * two NULL values are not equal, so if you want to test\n * whether a value is null, you may want to use\n * `isNull` instead.\n *\n * ## Examples\n *\n * ```ts\n * // Select cars made by Ford\n * db.select().from(cars)\n * .where(eq(cars.make, 'Ford'))\n * ```\n *\n * @see isNull for a way to test equality to NULL.\n */\nexport const eq: BinaryOperator = (left: SQLWrapper, right: unknown): SQL => {\n\treturn sql`${left} = ${bindIfParam(right, left)}`;\n};\n\n/**\n * Test that two values are not equal.\n *\n * Remember that the SQL standard dictates that\n * two NULL values are not equal, so if you want to test\n * whether a value is not null, you may want to use\n * `isNotNull` instead.\n *\n * ## Examples\n *\n * ```ts\n * // Select cars not made by Ford\n * db.select().from(cars)\n * .where(ne(cars.make, 'Ford'))\n * ```\n *\n * @see isNotNull for a way to test whether a value is not null.\n */\nexport const ne: BinaryOperator = (left: SQLWrapper, right: unknown): SQL => {\n\treturn sql`${left} <> ${bindIfParam(right, left)}`;\n};\n\n/**\n * Combine a list of conditions with the `and` operator. Conditions\n * that are equal `undefined` are automatically ignored.\n *\n * ## Examples\n *\n * ```ts\n * db.select().from(cars)\n * .where(\n * and(\n * eq(cars.make, 'Volvo'),\n * eq(cars.year, 1950),\n * )\n * )\n * ```\n */\nexport function and(...conditions: (SQLWrapper | undefined)[]): SQL | undefined;\nexport function and(\n\t...unfilteredConditions: (SQLWrapper | undefined)[]\n): SQL | undefined {\n\tconst conditions = unfilteredConditions.filter(\n\t\t(c): c is Exclude => c !== undefined,\n\t);\n\n\tif (conditions.length === 0) {\n\t\treturn undefined;\n\t}\n\n\tif (conditions.length === 1) {\n\t\treturn new SQL(conditions);\n\t}\n\n\treturn new SQL([\n\t\tnew StringChunk('('),\n\t\tsql.join(conditions, new StringChunk(' and ')),\n\t\tnew StringChunk(')'),\n\t]);\n}\n\n/**\n * Combine a list of conditions with the `or` operator. Conditions\n * that are equal `undefined` are automatically ignored.\n *\n * ## Examples\n *\n * ```ts\n * db.select().from(cars)\n * .where(\n * or(\n * eq(cars.make, 'GM'),\n * eq(cars.make, 'Ford'),\n * )\n * )\n * ```\n */\nexport function or(...conditions: (SQLWrapper | undefined)[]): SQL | undefined;\nexport function or(\n\t...unfilteredConditions: (SQLWrapper | undefined)[]\n): SQL | undefined {\n\tconst conditions = unfilteredConditions.filter(\n\t\t(c): c is Exclude => c !== undefined,\n\t);\n\n\tif (conditions.length === 0) {\n\t\treturn undefined;\n\t}\n\n\tif (conditions.length === 1) {\n\t\treturn new SQL(conditions);\n\t}\n\n\treturn new SQL([\n\t\tnew StringChunk('('),\n\t\tsql.join(conditions, new StringChunk(' or ')),\n\t\tnew StringChunk(')'),\n\t]);\n}\n\n/**\n * Negate the meaning of an expression using the `not` keyword.\n *\n * ## Examples\n *\n * ```ts\n * // Select cars _not_ made by GM or Ford.\n * db.select().from(cars)\n * .where(not(inArray(cars.make, ['GM', 'Ford'])))\n * ```\n */\nexport function not(condition: SQLWrapper): SQL {\n\treturn sql`not ${condition}`;\n}\n\n/**\n * Test that the first expression passed is greater than\n * the second expression.\n *\n * ## Examples\n *\n * ```ts\n * // Select cars made after 2000.\n * db.select().from(cars)\n * .where(gt(cars.year, 2000))\n * ```\n *\n * @see gte for greater-than-or-equal\n */\nexport const gt: BinaryOperator = (left: SQLWrapper, right: unknown): SQL => {\n\treturn sql`${left} > ${bindIfParam(right, left)}`;\n};\n\n/**\n * Test that the first expression passed is greater than\n * or equal to the second expression. Use `gt` to\n * test whether an expression is strictly greater\n * than another.\n *\n * ## Examples\n *\n * ```ts\n * // Select cars made on or after 2000.\n * db.select().from(cars)\n * .where(gte(cars.year, 2000))\n * ```\n *\n * @see gt for a strictly greater-than condition\n */\nexport const gte: BinaryOperator = (left: SQLWrapper, right: unknown): SQL => {\n\treturn sql`${left} >= ${bindIfParam(right, left)}`;\n};\n\n/**\n * Test that the first expression passed is less than\n * the second expression.\n *\n * ## Examples\n *\n * ```ts\n * // Select cars made before 2000.\n * db.select().from(cars)\n * .where(lt(cars.year, 2000))\n * ```\n *\n * @see lte for less-than-or-equal\n */\nexport const lt: BinaryOperator = (left: SQLWrapper, right: unknown): SQL => {\n\treturn sql`${left} < ${bindIfParam(right, left)}`;\n};\n\n/**\n * Test that the first expression passed is less than\n * or equal to the second expression.\n *\n * ## Examples\n *\n * ```ts\n * // Select cars made before 2000.\n * db.select().from(cars)\n * .where(lte(cars.year, 2000))\n * ```\n *\n * @see lt for a strictly less-than condition\n */\nexport const lte: BinaryOperator = (left: SQLWrapper, right: unknown): SQL => {\n\treturn sql`${left} <= ${bindIfParam(right, left)}`;\n};\n\n/**\n * Test whether the first parameter, a column or expression,\n * has a value from a list passed as the second argument.\n *\n * ## Examples\n *\n * ```ts\n * // Select cars made by Ford or GM.\n * db.select().from(cars)\n * .where(inArray(cars.make, ['Ford', 'GM']))\n * ```\n *\n * @see notInArray for the inverse of this test\n */\nexport function inArray(\n\tcolumn: SQL.Aliased,\n\tvalues: (T | Placeholder)[] | SQLWrapper,\n): SQL;\nexport function inArray(\n\tcolumn: TColumn,\n\tvalues: ReadonlyArray | Placeholder> | SQLWrapper,\n): SQL;\nexport function inArray(\n\tcolumn: Exclude,\n\tvalues: ReadonlyArray | SQLWrapper,\n): SQL;\nexport function inArray(\n\tcolumn: SQLWrapper,\n\tvalues: ReadonlyArray | SQLWrapper,\n): SQL {\n\tif (Array.isArray(values)) {\n\t\tif (values.length === 0) {\n\t\t\treturn sql`false`;\n\t\t}\n\t\treturn sql`${column} in ${values.map((v) => bindIfParam(v, column))}`;\n\t}\n\n\treturn sql`${column} in ${bindIfParam(values, column)}`;\n}\n\n/**\n * Test whether the first parameter, a column or expression,\n * has a value that is not present in a list passed as the\n * second argument.\n *\n * ## Examples\n *\n * ```ts\n * // Select cars made by any company except Ford or GM.\n * db.select().from(cars)\n * .where(notInArray(cars.make, ['Ford', 'GM']))\n * ```\n *\n * @see inArray for the inverse of this test\n */\nexport function notInArray(\n\tcolumn: SQL.Aliased,\n\tvalues: (T | Placeholder)[] | SQLWrapper,\n): SQL;\nexport function notInArray(\n\tcolumn: TColumn,\n\tvalues: (GetColumnData | Placeholder)[] | SQLWrapper,\n): SQL;\nexport function notInArray(\n\tcolumn: Exclude,\n\tvalues: (unknown | Placeholder)[] | SQLWrapper,\n): SQL;\nexport function notInArray(\n\tcolumn: SQLWrapper,\n\tvalues: (unknown | Placeholder)[] | SQLWrapper,\n): SQL {\n\tif (Array.isArray(values)) {\n\t\tif (values.length === 0) {\n\t\t\treturn sql`true`;\n\t\t}\n\t\treturn sql`${column} not in ${values.map((v) => bindIfParam(v, column))}`;\n\t}\n\n\treturn sql`${column} not in ${bindIfParam(values, column)}`;\n}\n\n/**\n * Test whether an expression is NULL. By the SQL standard,\n * NULL is neither equal nor not equal to itself, so\n * it's recommended to use `isNull` and `notIsNull` for\n * comparisons to NULL.\n *\n * ## Examples\n *\n * ```ts\n * // Select cars that have no discontinuedAt date.\n * db.select().from(cars)\n * .where(isNull(cars.discontinuedAt))\n * ```\n *\n * @see isNotNull for the inverse of this test\n */\nexport function isNull(value: SQLWrapper): SQL {\n\treturn sql`${value} is null`;\n}\n\n/**\n * Test whether an expression is not NULL. By the SQL standard,\n * NULL is neither equal nor not equal to itself, so\n * it's recommended to use `isNull` and `notIsNull` for\n * comparisons to NULL.\n *\n * ## Examples\n *\n * ```ts\n * // Select cars that have been discontinued.\n * db.select().from(cars)\n * .where(isNotNull(cars.discontinuedAt))\n * ```\n *\n * @see isNull for the inverse of this test\n */\nexport function isNotNull(value: SQLWrapper): SQL {\n\treturn sql`${value} is not null`;\n}\n\n/**\n * Test whether a subquery evaluates to have any rows.\n *\n * ## Examples\n *\n * ```ts\n * // Users whose `homeCity` column has a match in a cities\n * // table.\n * db\n * .select()\n * .from(users)\n * .where(\n * exists(db.select()\n * .from(cities)\n * .where(eq(users.homeCity, cities.id))),\n * );\n * ```\n *\n * @see notExists for the inverse of this test\n */\nexport function exists(subquery: SQLWrapper): SQL {\n\treturn sql`exists ${subquery}`;\n}\n\n/**\n * Test whether a subquery doesn't include any result\n * rows.\n *\n * ## Examples\n *\n * ```ts\n * // Users whose `homeCity` column doesn't match\n * // a row in the cities table.\n * db\n * .select()\n * .from(users)\n * .where(\n * notExists(db.select()\n * .from(cities)\n * .where(eq(users.homeCity, cities.id))),\n * );\n * ```\n *\n * @see exists for the inverse of this test\n */\nexport function notExists(subquery: SQLWrapper): SQL {\n\treturn sql`not exists ${subquery}`;\n}\n\n/**\n * Test whether an expression is between two values. This\n * is an easier way to express range tests, which would be\n * expressed mathematically as `x <= a <= y` but in SQL\n * would have to be like `a >= x AND a <= y`.\n *\n * Between is inclusive of the endpoints: if `column`\n * is equal to `min` or `max`, it will be TRUE.\n *\n * ## Examples\n *\n * ```ts\n * // Select cars made between 1990 and 2000\n * db.select().from(cars)\n * .where(between(cars.year, 1990, 2000))\n * ```\n *\n * @see notBetween for the inverse of this test\n */\nexport function between(\n\tcolumn: SQL.Aliased,\n\tmin: T | SQLWrapper,\n\tmax: T | SQLWrapper,\n): SQL;\nexport function between(\n\tcolumn: TColumn,\n\tmin: GetColumnData | SQLWrapper,\n\tmax: GetColumnData | SQLWrapper,\n): SQL;\nexport function between(\n\tcolumn: Exclude,\n\tmin: unknown,\n\tmax: unknown,\n): SQL;\nexport function between(column: SQLWrapper, min: unknown, max: unknown): SQL {\n\treturn sql`${column} between ${bindIfParam(min, column)} and ${\n\t\tbindIfParam(\n\t\t\tmax,\n\t\t\tcolumn,\n\t\t)\n\t}`;\n}\n\n/**\n * Test whether an expression is not between two values.\n *\n * This, like `between`, includes its endpoints, so if\n * the `column` is equal to `min` or `max`, in this case\n * it will evaluate to FALSE.\n *\n * ## Examples\n *\n * ```ts\n * // Exclude cars made in the 1970s\n * db.select().from(cars)\n * .where(notBetween(cars.year, 1970, 1979))\n * ```\n *\n * @see between for the inverse of this test\n */\nexport function notBetween(\n\tcolumn: SQL.Aliased,\n\tmin: T | SQLWrapper,\n\tmax: T | SQLWrapper,\n): SQL;\nexport function notBetween(\n\tcolumn: TColumn,\n\tmin: GetColumnData | SQLWrapper,\n\tmax: GetColumnData | SQLWrapper,\n): SQL;\nexport function notBetween(\n\tcolumn: Exclude,\n\tmin: unknown,\n\tmax: unknown,\n): SQL;\nexport function notBetween(\n\tcolumn: SQLWrapper,\n\tmin: unknown,\n\tmax: unknown,\n): SQL {\n\treturn sql`${column} not between ${\n\t\tbindIfParam(\n\t\t\tmin,\n\t\t\tcolumn,\n\t\t)\n\t} and ${bindIfParam(max, column)}`;\n}\n\n/**\n * Compare a column to a pattern, which can include `%` and `_`\n * characters to match multiple variations. Including `%`\n * in the pattern matches zero or more characters, and including\n * `_` will match a single character.\n *\n * ## Examples\n *\n * ```ts\n * // Select all cars with 'Turbo' in their names.\n * db.select().from(cars)\n * .where(like(cars.name, '%Turbo%'))\n * ```\n *\n * @see ilike for a case-insensitive version of this condition\n */\nexport function like(column: Column | SQL.Aliased | SQL, value: string | SQLWrapper): SQL {\n\treturn sql`${column} like ${value}`;\n}\n\n/**\n * The inverse of like - this tests that a given column\n * does not match a pattern, which can include `%` and `_`\n * characters to match multiple variations. Including `%`\n * in the pattern matches zero or more characters, and including\n * `_` will match a single character.\n *\n * ## Examples\n *\n * ```ts\n * // Select all cars that don't have \"ROver\" in their name.\n * db.select().from(cars)\n * .where(notLike(cars.name, '%Rover%'))\n * ```\n *\n * @see like for the inverse condition\n * @see notIlike for a case-insensitive version of this condition\n */\nexport function notLike(column: Column | SQL.Aliased | SQL, value: string | SQLWrapper): SQL {\n\treturn sql`${column} not like ${value}`;\n}\n\n/**\n * Case-insensitively compare a column to a pattern,\n * which can include `%` and `_`\n * characters to match multiple variations. Including `%`\n * in the pattern matches zero or more characters, and including\n * `_` will match a single character.\n *\n * Unlike like, this performs a case-insensitive comparison.\n *\n * ## Examples\n *\n * ```ts\n * // Select all cars with 'Turbo' in their names.\n * db.select().from(cars)\n * .where(ilike(cars.name, '%Turbo%'))\n * ```\n *\n * @see like for a case-sensitive version of this condition\n */\nexport function ilike(column: Column | SQL.Aliased | SQL, value: string | SQLWrapper): SQL {\n\treturn sql`${column} ilike ${value}`;\n}\n\n/**\n * The inverse of ilike - this case-insensitively tests that a given column\n * does not match a pattern, which can include `%` and `_`\n * characters to match multiple variations. Including `%`\n * in the pattern matches zero or more characters, and including\n * `_` will match a single character.\n *\n * ## Examples\n *\n * ```ts\n * // Select all cars that don't have \"Rover\" in their name.\n * db.select().from(cars)\n * .where(notLike(cars.name, '%Rover%'))\n * ```\n *\n * @see ilike for the inverse condition\n * @see notLike for a case-sensitive version of this condition\n */\nexport function notIlike(column: Column | SQL.Aliased | SQL, value: string | SQLWrapper): SQL {\n\treturn sql`${column} not ilike ${value}`;\n}\n\n/**\n * Test that a column or expression contains all elements of\n * the list passed as the second argument.\n *\n * ## Throws\n *\n * The argument passed in the second array can't be empty:\n * if an empty is provided, this method will throw.\n *\n * ## Examples\n *\n * ```ts\n * // Select posts where its tags contain \"Typescript\" and \"ORM\".\n * db.select().from(posts)\n * .where(arrayContains(posts.tags, ['Typescript', 'ORM']))\n * ```\n *\n * @see arrayContained to find if an array contains all elements of a column or expression\n * @see arrayOverlaps to find if a column or expression contains any elements of an array\n */\nexport function arrayContains(\n\tcolumn: SQL.Aliased,\n\tvalues: (T | Placeholder) | SQLWrapper,\n): SQL;\nexport function arrayContains(\n\tcolumn: TColumn,\n\tvalues: (GetColumnData | Placeholder) | SQLWrapper,\n): SQL;\nexport function arrayContains(\n\tcolumn: Exclude,\n\tvalues: (unknown | Placeholder)[] | SQLWrapper,\n): SQL;\nexport function arrayContains(\n\tcolumn: SQLWrapper,\n\tvalues: (unknown | Placeholder)[] | SQLWrapper,\n): SQL {\n\tif (Array.isArray(values)) {\n\t\tif (values.length === 0) {\n\t\t\tthrow new Error('arrayContains requires at least one value');\n\t\t}\n\t\tconst array = sql`${bindIfParam(values, column)}`;\n\t\treturn sql`${column} @> ${array}`;\n\t}\n\n\treturn sql`${column} @> ${bindIfParam(values, column)}`;\n}\n\n/**\n * Test that the list passed as the second argument contains\n * all elements of a column or expression.\n *\n * ## Throws\n *\n * The argument passed in the second array can't be empty:\n * if an empty is provided, this method will throw.\n *\n * ## Examples\n *\n * ```ts\n * // Select posts where its tags contain \"Typescript\", \"ORM\" or both,\n * // but filtering posts that have additional tags.\n * db.select().from(posts)\n * .where(arrayContained(posts.tags, ['Typescript', 'ORM']))\n * ```\n *\n * @see arrayContains to find if a column or expression contains all elements of an array\n * @see arrayOverlaps to find if a column or expression contains any elements of an array\n */\nexport function arrayContained(\n\tcolumn: SQL.Aliased,\n\tvalues: (T | Placeholder) | SQLWrapper,\n): SQL;\nexport function arrayContained(\n\tcolumn: TColumn,\n\tvalues: (GetColumnData | Placeholder) | SQLWrapper,\n): SQL;\nexport function arrayContained(\n\tcolumn: Exclude,\n\tvalues: (unknown | Placeholder)[] | SQLWrapper,\n): SQL;\nexport function arrayContained(\n\tcolumn: SQLWrapper,\n\tvalues: (unknown | Placeholder)[] | SQLWrapper,\n): SQL {\n\tif (Array.isArray(values)) {\n\t\tif (values.length === 0) {\n\t\t\tthrow new Error('arrayContained requires at least one value');\n\t\t}\n\t\tconst array = sql`${bindIfParam(values, column)}`;\n\t\treturn sql`${column} <@ ${array}`;\n\t}\n\n\treturn sql`${column} <@ ${bindIfParam(values, column)}`;\n}\n\n/**\n * Test that a column or expression contains any elements of\n * the list passed as the second argument.\n *\n * ## Throws\n *\n * The argument passed in the second array can't be empty:\n * if an empty is provided, this method will throw.\n *\n * ## Examples\n *\n * ```ts\n * // Select posts where its tags contain \"Typescript\", \"ORM\" or both.\n * db.select().from(posts)\n * .where(arrayOverlaps(posts.tags, ['Typescript', 'ORM']))\n * ```\n *\n * @see arrayContains to find if a column or expression contains all elements of an array\n * @see arrayContained to find if an array contains all elements of a column or expression\n */\nexport function arrayOverlaps(\n\tcolumn: SQL.Aliased,\n\tvalues: (T | Placeholder) | SQLWrapper,\n): SQL;\nexport function arrayOverlaps(\n\tcolumn: TColumn,\n\tvalues: (GetColumnData | Placeholder) | SQLWrapper,\n): SQL;\nexport function arrayOverlaps(\n\tcolumn: Exclude,\n\tvalues: (unknown | Placeholder)[] | SQLWrapper,\n): SQL;\nexport function arrayOverlaps(\n\tcolumn: SQLWrapper,\n\tvalues: (unknown | Placeholder)[] | SQLWrapper,\n): SQL {\n\tif (Array.isArray(values)) {\n\t\tif (values.length === 0) {\n\t\t\tthrow new Error('arrayOverlaps requires at least one value');\n\t\t}\n\t\tconst array = sql`${bindIfParam(values, column)}`;\n\t\treturn sql`${column} && ${array}`;\n\t}\n\n\treturn sql`${column} && ${bindIfParam(values, column)}`;\n}\n", "import type { AnyColumn } from '../../column.ts';\nimport type { SQL, SQLWrapper } from '../sql.ts';\nimport { sql } from '../sql.ts';\n\n/**\n * Used in sorting, this specifies that the given\n * column or expression should be sorted in ascending\n * order. By the SQL standard, ascending order is the\n * default, so it is not usually necessary to specify\n * ascending sort order.\n *\n * ## Examples\n *\n * ```ts\n * // Return cars, starting with the oldest models\n * // and going in ascending order to the newest.\n * db.select().from(cars)\n * .orderBy(asc(cars.year));\n * ```\n *\n * @see desc to sort in descending order\n */\nexport function asc(column: AnyColumn | SQLWrapper): SQL {\n\treturn sql`${column} asc`;\n}\n\n/**\n * Used in sorting, this specifies that the given\n * column or expression should be sorted in descending\n * order.\n *\n * ## Examples\n *\n * ```ts\n * // Select users, with the most recently created\n * // records coming first.\n * db.select().from(users)\n * .orderBy(desc(users.createdAt));\n * ```\n *\n * @see asc to sort in ascending order\n */\nexport function desc(column: AnyColumn | SQLWrapper): SQL {\n\treturn sql`${column} desc`;\n}\n", "import type { Cache } from '~/cache/core/cache.ts';\nimport { entityKind } from '~/entity.ts';\nimport type { TypedQueryBuilder } from '~/query-builders/query-builder.ts';\nimport type { ExtractTablesWithRelations, RelationalSchemaConfig, TablesRelationalConfig } from '~/relations.ts';\nimport { SelectionProxyHandler } from '~/selection-proxy.ts';\nimport { type ColumnsSelection, type SQL, sql, type SQLWrapper } from '~/sql/sql.ts';\nimport type { SQLiteAsyncDialect, SQLiteSyncDialect } from '~/sqlite-core/dialect.ts';\nimport {\n\tQueryBuilder,\n\tSQLiteDeleteBase,\n\tSQLiteInsertBuilder,\n\tSQLiteSelectBuilder,\n\tSQLiteUpdateBuilder,\n} from '~/sqlite-core/query-builders/index.ts';\nimport type {\n\tDBResult,\n\tResult,\n\tSQLiteSession,\n\tSQLiteTransaction,\n\tSQLiteTransactionConfig,\n} from '~/sqlite-core/session.ts';\nimport type { SQLiteTable } from '~/sqlite-core/table.ts';\nimport { WithSubquery } from '~/subquery.ts';\nimport type { DrizzleTypeError } from '~/utils.ts';\nimport { SQLiteCountBuilder } from './query-builders/count.ts';\nimport { RelationalQueryBuilder } from './query-builders/query.ts';\nimport { SQLiteRaw } from './query-builders/raw.ts';\nimport type { SelectedFields } from './query-builders/select.types.ts';\nimport type { WithBuilder } from './subquery.ts';\nimport type { SQLiteViewBase } from './view-base.ts';\n\nexport class BaseSQLiteDatabase<\n\tTResultKind extends 'sync' | 'async',\n\tTRunResult,\n\tTFullSchema extends Record = Record,\n\tTSchema extends TablesRelationalConfig = ExtractTablesWithRelations,\n> {\n\tstatic readonly [entityKind]: string = 'BaseSQLiteDatabase';\n\n\tdeclare readonly _: {\n\t\treadonly schema: TSchema | undefined;\n\t\treadonly fullSchema: TFullSchema;\n\t\treadonly tableNamesMap: Record;\n\t};\n\n\tquery: TFullSchema extends Record\n\t\t? DrizzleTypeError<'Seems like the schema generic is missing - did you forget to add it to your DB type?'>\n\t\t: {\n\t\t\t[K in keyof TSchema]: RelationalQueryBuilder;\n\t\t};\n\n\tconstructor(\n\t\tprivate resultKind: TResultKind,\n\t\t/** @internal */\n\t\treadonly dialect: { sync: SQLiteSyncDialect; async: SQLiteAsyncDialect }[TResultKind],\n\t\t/** @internal */\n\t\treadonly session: SQLiteSession,\n\t\tschema: RelationalSchemaConfig | undefined,\n\t) {\n\t\tthis._ = schema\n\t\t\t? {\n\t\t\t\tschema: schema.schema,\n\t\t\t\tfullSchema: schema.fullSchema as TFullSchema,\n\t\t\t\ttableNamesMap: schema.tableNamesMap,\n\t\t\t}\n\t\t\t: {\n\t\t\t\tschema: undefined,\n\t\t\t\tfullSchema: {} as TFullSchema,\n\t\t\t\ttableNamesMap: {},\n\t\t\t};\n\t\tthis.query = {} as typeof this['query'];\n\t\tconst query = this.query as {\n\t\t\t[K in keyof TSchema]: RelationalQueryBuilder;\n\t\t};\n\t\tif (this._.schema) {\n\t\t\tfor (const [tableName, columns] of Object.entries(this._.schema)) {\n\t\t\t\tquery[tableName as keyof TSchema] = new RelationalQueryBuilder(\n\t\t\t\t\tresultKind,\n\t\t\t\t\tschema!.fullSchema,\n\t\t\t\t\tthis._.schema,\n\t\t\t\t\tthis._.tableNamesMap,\n\t\t\t\t\tschema!.fullSchema[tableName] as SQLiteTable,\n\t\t\t\t\tcolumns,\n\t\t\t\t\tdialect,\n\t\t\t\t\tsession as SQLiteSession as any,\n\t\t\t\t) as typeof query[keyof TSchema];\n\t\t\t}\n\t\t}\n\t\tthis.$cache = { invalidate: async (_params: any) => {} };\n\t}\n\n\t/**\n\t * Creates a subquery that defines a temporary named result set as a CTE.\n\t *\n\t * It is useful for breaking down complex queries into simpler parts and for reusing the result set in subsequent parts of the query.\n\t *\n\t * See docs: {@link https://orm.drizzle.team/docs/select#with-clause}\n\t *\n\t * @param alias The alias for the subquery.\n\t *\n\t * Failure to provide an alias will result in a DrizzleTypeError, preventing the subquery from being referenced in other queries.\n\t *\n\t * @example\n\t *\n\t * ```ts\n\t * // Create a subquery with alias 'sq' and use it in the select query\n\t * const sq = db.$with('sq').as(db.select().from(users).where(eq(users.id, 42)));\n\t *\n\t * const result = await db.with(sq).select().from(sq);\n\t * ```\n\t *\n\t * To select arbitrary SQL values as fields in a CTE and reference them in other CTEs or in the main query, you need to add aliases to them:\n\t *\n\t * ```ts\n\t * // Select an arbitrary SQL value as a field in a CTE and reference it in the main query\n\t * const sq = db.$with('sq').as(db.select({\n\t * name: sql`upper(${users.name})`.as('name'),\n\t * })\n\t * .from(users));\n\t *\n\t * const result = await db.with(sq).select({ name: sq.name }).from(sq);\n\t * ```\n\t */\n\t$with: WithBuilder = (alias: string, selection?: ColumnsSelection) => {\n\t\tconst self = this;\n\t\tconst as = (\n\t\t\tqb:\n\t\t\t\t| TypedQueryBuilder\n\t\t\t\t| SQL\n\t\t\t\t| ((qb: QueryBuilder) => TypedQueryBuilder | SQL),\n\t\t) => {\n\t\t\tif (typeof qb === 'function') {\n\t\t\t\tqb = qb(new QueryBuilder(self.dialect));\n\t\t\t}\n\n\t\t\treturn new Proxy(\n\t\t\t\tnew WithSubquery(\n\t\t\t\t\tqb.getSQL(),\n\t\t\t\t\tselection ?? ('getSelectedFields' in qb ? qb.getSelectedFields() ?? {} : {}) as SelectedFields,\n\t\t\t\t\talias,\n\t\t\t\t\ttrue,\n\t\t\t\t),\n\t\t\t\tnew SelectionProxyHandler({ alias, sqlAliasedBehavior: 'alias', sqlBehavior: 'error' }),\n\t\t\t);\n\t\t};\n\t\treturn { as };\n\t};\n\n\t$count(\n\t\tsource: SQLiteTable | SQLiteViewBase | SQL | SQLWrapper,\n\t\tfilters?: SQL,\n\t) {\n\t\treturn new SQLiteCountBuilder({ source, filters, session: this.session });\n\t}\n\n\t/**\n\t * Incorporates a previously defined CTE (using `$with`) into the main query.\n\t *\n\t * This method allows the main query to reference a temporary named result set.\n\t *\n\t * See docs: {@link https://orm.drizzle.team/docs/select#with-clause}\n\t *\n\t * @param queries The CTEs to incorporate into the main query.\n\t *\n\t * @example\n\t *\n\t * ```ts\n\t * // Define a subquery 'sq' as a CTE using $with\n\t * const sq = db.$with('sq').as(db.select().from(users).where(eq(users.id, 42)));\n\t *\n\t * // Incorporate the CTE 'sq' into the main query and select from it\n\t * const result = await db.with(sq).select().from(sq);\n\t * ```\n\t */\n\twith(...queries: WithSubquery[]) {\n\t\tconst self = this;\n\n\t\t/**\n\t\t * Creates a select query.\n\t\t *\n\t\t * Calling this method with no arguments will select all columns from the table. Pass a selection object to specify the columns you want to select.\n\t\t *\n\t\t * Use `.from()` method to specify which table to select from.\n\t\t *\n\t\t * See docs: {@link https://orm.drizzle.team/docs/select}\n\t\t *\n\t\t * @param fields The selection object.\n\t\t *\n\t\t * @example\n\t\t *\n\t\t * ```ts\n\t\t * // Select all columns and all rows from the 'cars' table\n\t\t * const allCars: Car[] = await db.select().from(cars);\n\t\t *\n\t\t * // Select specific columns and all rows from the 'cars' table\n\t\t * const carsIdsAndBrands: { id: number; brand: string }[] = await db.select({\n\t\t * id: cars.id,\n\t\t * brand: cars.brand\n\t\t * })\n\t\t * .from(cars);\n\t\t * ```\n\t\t *\n\t\t * Like in SQL, you can use arbitrary expressions as selection fields, not just table columns:\n\t\t *\n\t\t * ```ts\n\t\t * // Select specific columns along with expression and all rows from the 'cars' table\n\t\t * const carsIdsAndLowerNames: { id: number; lowerBrand: string }[] = await db.select({\n\t\t * id: cars.id,\n\t\t * lowerBrand: sql`lower(${cars.brand})`,\n\t\t * })\n\t\t * .from(cars);\n\t\t * ```\n\t\t */\n\t\tfunction select(): SQLiteSelectBuilder;\n\t\tfunction select(\n\t\t\tfields: TSelection,\n\t\t): SQLiteSelectBuilder;\n\t\tfunction select(\n\t\t\tfields?: SelectedFields,\n\t\t): SQLiteSelectBuilder {\n\t\t\treturn new SQLiteSelectBuilder({\n\t\t\t\tfields: fields ?? undefined,\n\t\t\t\tsession: self.session,\n\t\t\t\tdialect: self.dialect,\n\t\t\t\twithList: queries,\n\t\t\t});\n\t\t}\n\n\t\t/**\n\t\t * Adds `distinct` expression to the select query.\n\t\t *\n\t\t * Calling this method will return only unique values. When multiple columns are selected, it returns rows with unique combinations of values in these columns.\n\t\t *\n\t\t * Use `.from()` method to specify which table to select from.\n\t\t *\n\t\t * See docs: {@link https://orm.drizzle.team/docs/select#distinct}\n\t\t *\n\t\t * @param fields The selection object.\n\t\t *\n\t\t * @example\n\t\t *\n\t\t * ```ts\n\t\t * // Select all unique rows from the 'cars' table\n\t\t * await db.selectDistinct()\n\t\t * .from(cars)\n\t\t * .orderBy(cars.id, cars.brand, cars.color);\n\t\t *\n\t\t * // Select all unique brands from the 'cars' table\n\t\t * await db.selectDistinct({ brand: cars.brand })\n\t\t * .from(cars)\n\t\t * .orderBy(cars.brand);\n\t\t * ```\n\t\t */\n\t\tfunction selectDistinct(): SQLiteSelectBuilder;\n\t\tfunction selectDistinct(\n\t\t\tfields: TSelection,\n\t\t): SQLiteSelectBuilder;\n\t\tfunction selectDistinct(\n\t\t\tfields?: SelectedFields,\n\t\t): SQLiteSelectBuilder {\n\t\t\treturn new SQLiteSelectBuilder({\n\t\t\t\tfields: fields ?? undefined,\n\t\t\t\tsession: self.session,\n\t\t\t\tdialect: self.dialect,\n\t\t\t\twithList: queries,\n\t\t\t\tdistinct: true,\n\t\t\t});\n\t\t}\n\n\t\t/**\n\t\t * Creates an update query.\n\t\t *\n\t\t * Calling this method without `.where()` clause will update all rows in a table. The `.where()` clause specifies which rows should be updated.\n\t\t *\n\t\t * Use `.set()` method to specify which values to update.\n\t\t *\n\t\t * See docs: {@link https://orm.drizzle.team/docs/update}\n\t\t *\n\t\t * @param table The table to update.\n\t\t *\n\t\t * @example\n\t\t *\n\t\t * ```ts\n\t\t * // Update all rows in the 'cars' table\n\t\t * await db.update(cars).set({ color: 'red' });\n\t\t *\n\t\t * // Update rows with filters and conditions\n\t\t * await db.update(cars).set({ color: 'red' }).where(eq(cars.brand, 'BMW'));\n\t\t *\n\t\t * // Update with returning clause\n\t\t * const updatedCar: Car[] = await db.update(cars)\n\t\t * .set({ color: 'red' })\n\t\t * .where(eq(cars.id, 1))\n\t\t * .returning();\n\t\t * ```\n\t\t */\n\t\tfunction update(table: TTable): SQLiteUpdateBuilder {\n\t\t\treturn new SQLiteUpdateBuilder(table, self.session, self.dialect, queries);\n\t\t}\n\n\t\t/**\n\t\t * Creates an insert query.\n\t\t *\n\t\t * Calling this method will create new rows in a table. Use `.values()` method to specify which values to insert.\n\t\t *\n\t\t * See docs: {@link https://orm.drizzle.team/docs/insert}\n\t\t *\n\t\t * @param table The table to insert into.\n\t\t *\n\t\t * @example\n\t\t *\n\t\t * ```ts\n\t\t * // Insert one row\n\t\t * await db.insert(cars).values({ brand: 'BMW' });\n\t\t *\n\t\t * // Insert multiple rows\n\t\t * await db.insert(cars).values([{ brand: 'BMW' }, { brand: 'Porsche' }]);\n\t\t *\n\t\t * // Insert with returning clause\n\t\t * const insertedCar: Car[] = await db.insert(cars)\n\t\t * .values({ brand: 'BMW' })\n\t\t * .returning();\n\t\t * ```\n\t\t */\n\t\tfunction insert(into: TTable): SQLiteInsertBuilder {\n\t\t\treturn new SQLiteInsertBuilder(into, self.session, self.dialect, queries);\n\t\t}\n\n\t\t/**\n\t\t * Creates a delete query.\n\t\t *\n\t\t * Calling this method without `.where()` clause will delete all rows in a table. The `.where()` clause specifies which rows should be deleted.\n\t\t *\n\t\t * See docs: {@link https://orm.drizzle.team/docs/delete}\n\t\t *\n\t\t * @param table The table to delete from.\n\t\t *\n\t\t * @example\n\t\t *\n\t\t * ```ts\n\t\t * // Delete all rows in the 'cars' table\n\t\t * await db.delete(cars);\n\t\t *\n\t\t * // Delete rows with filters and conditions\n\t\t * await db.delete(cars).where(eq(cars.color, 'green'));\n\t\t *\n\t\t * // Delete with returning clause\n\t\t * const deletedCar: Car[] = await db.delete(cars)\n\t\t * .where(eq(cars.id, 1))\n\t\t * .returning();\n\t\t * ```\n\t\t */\n\t\tfunction delete_(from: TTable): SQLiteDeleteBase {\n\t\t\treturn new SQLiteDeleteBase(from, self.session, self.dialect, queries);\n\t\t}\n\n\t\treturn { select, selectDistinct, update, insert, delete: delete_ };\n\t}\n\n\t/**\n\t * Creates a select query.\n\t *\n\t * Calling this method with no arguments will select all columns from the table. Pass a selection object to specify the columns you want to select.\n\t *\n\t * Use `.from()` method to specify which table to select from.\n\t *\n\t * See docs: {@link https://orm.drizzle.team/docs/select}\n\t *\n\t * @param fields The selection object.\n\t *\n\t * @example\n\t *\n\t * ```ts\n\t * // Select all columns and all rows from the 'cars' table\n\t * const allCars: Car[] = await db.select().from(cars);\n\t *\n\t * // Select specific columns and all rows from the 'cars' table\n\t * const carsIdsAndBrands: { id: number; brand: string }[] = await db.select({\n\t * id: cars.id,\n\t * brand: cars.brand\n\t * })\n\t * .from(cars);\n\t * ```\n\t *\n\t * Like in SQL, you can use arbitrary expressions as selection fields, not just table columns:\n\t *\n\t * ```ts\n\t * // Select specific columns along with expression and all rows from the 'cars' table\n\t * const carsIdsAndLowerNames: { id: number; lowerBrand: string }[] = await db.select({\n\t * id: cars.id,\n\t * lowerBrand: sql`lower(${cars.brand})`,\n\t * })\n\t * .from(cars);\n\t * ```\n\t */\n\tselect(): SQLiteSelectBuilder;\n\tselect(\n\t\tfields: TSelection,\n\t): SQLiteSelectBuilder;\n\tselect(fields?: SelectedFields): SQLiteSelectBuilder {\n\t\treturn new SQLiteSelectBuilder({ fields: fields ?? undefined, session: this.session, dialect: this.dialect });\n\t}\n\n\t/**\n\t * Adds `distinct` expression to the select query.\n\t *\n\t * Calling this method will return only unique values. When multiple columns are selected, it returns rows with unique combinations of values in these columns.\n\t *\n\t * Use `.from()` method to specify which table to select from.\n\t *\n\t * See docs: {@link https://orm.drizzle.team/docs/select#distinct}\n\t *\n\t * @param fields The selection object.\n\t *\n\t * @example\n\t *\n\t * ```ts\n\t * // Select all unique rows from the 'cars' table\n\t * await db.selectDistinct()\n\t * .from(cars)\n\t * .orderBy(cars.id, cars.brand, cars.color);\n\t *\n\t * // Select all unique brands from the 'cars' table\n\t * await db.selectDistinct({ brand: cars.brand })\n\t * .from(cars)\n\t * .orderBy(cars.brand);\n\t * ```\n\t */\n\tselectDistinct(): SQLiteSelectBuilder;\n\tselectDistinct(\n\t\tfields: TSelection,\n\t): SQLiteSelectBuilder;\n\tselectDistinct(\n\t\tfields?: SelectedFields,\n\t): SQLiteSelectBuilder {\n\t\treturn new SQLiteSelectBuilder({\n\t\t\tfields: fields ?? undefined,\n\t\t\tsession: this.session,\n\t\t\tdialect: this.dialect,\n\t\t\tdistinct: true,\n\t\t});\n\t}\n\n\t/**\n\t * Creates an update query.\n\t *\n\t * Calling this method without `.where()` clause will update all rows in a table. The `.where()` clause specifies which rows should be updated.\n\t *\n\t * Use `.set()` method to specify which values to update.\n\t *\n\t * See docs: {@link https://orm.drizzle.team/docs/update}\n\t *\n\t * @param table The table to update.\n\t *\n\t * @example\n\t *\n\t * ```ts\n\t * // Update all rows in the 'cars' table\n\t * await db.update(cars).set({ color: 'red' });\n\t *\n\t * // Update rows with filters and conditions\n\t * await db.update(cars).set({ color: 'red' }).where(eq(cars.brand, 'BMW'));\n\t *\n\t * // Update with returning clause\n\t * const updatedCar: Car[] = await db.update(cars)\n\t * .set({ color: 'red' })\n\t * .where(eq(cars.id, 1))\n\t * .returning();\n\t * ```\n\t */\n\tupdate(table: TTable): SQLiteUpdateBuilder {\n\t\treturn new SQLiteUpdateBuilder(table, this.session, this.dialect);\n\t}\n\n\t$cache: { invalidate: Cache['onMutate'] };\n\n\t/**\n\t * Creates an insert query.\n\t *\n\t * Calling this method will create new rows in a table. Use `.values()` method to specify which values to insert.\n\t *\n\t * See docs: {@link https://orm.drizzle.team/docs/insert}\n\t *\n\t * @param table The table to insert into.\n\t *\n\t * @example\n\t *\n\t * ```ts\n\t * // Insert one row\n\t * await db.insert(cars).values({ brand: 'BMW' });\n\t *\n\t * // Insert multiple rows\n\t * await db.insert(cars).values([{ brand: 'BMW' }, { brand: 'Porsche' }]);\n\t *\n\t * // Insert with returning clause\n\t * const insertedCar: Car[] = await db.insert(cars)\n\t * .values({ brand: 'BMW' })\n\t * .returning();\n\t * ```\n\t */\n\tinsert(into: TTable): SQLiteInsertBuilder {\n\t\treturn new SQLiteInsertBuilder(into, this.session, this.dialect);\n\t}\n\n\t/**\n\t * Creates a delete query.\n\t *\n\t * Calling this method without `.where()` clause will delete all rows in a table. The `.where()` clause specifies which rows should be deleted.\n\t *\n\t * See docs: {@link https://orm.drizzle.team/docs/delete}\n\t *\n\t * @param table The table to delete from.\n\t *\n\t * @example\n\t *\n\t * ```ts\n\t * // Delete all rows in the 'cars' table\n\t * await db.delete(cars);\n\t *\n\t * // Delete rows with filters and conditions\n\t * await db.delete(cars).where(eq(cars.color, 'green'));\n\t *\n\t * // Delete with returning clause\n\t * const deletedCar: Car[] = await db.delete(cars)\n\t * .where(eq(cars.id, 1))\n\t * .returning();\n\t * ```\n\t */\n\tdelete(from: TTable): SQLiteDeleteBase {\n\t\treturn new SQLiteDeleteBase(from, this.session, this.dialect);\n\t}\n\n\trun(query: SQLWrapper | string): DBResult {\n\t\tconst sequel = typeof query === 'string' ? sql.raw(query) : query.getSQL();\n\t\tif (this.resultKind === 'async') {\n\t\t\treturn new SQLiteRaw(\n\t\t\t\tasync () => this.session.run(sequel),\n\t\t\t\t() => sequel,\n\t\t\t\t'run',\n\t\t\t\tthis.dialect as SQLiteAsyncDialect,\n\t\t\t\tthis.session.extractRawRunValueFromBatchResult.bind(this.session),\n\t\t\t) as DBResult;\n\t\t}\n\t\treturn this.session.run(sequel) as DBResult;\n\t}\n\n\tall(query: SQLWrapper | string): DBResult {\n\t\tconst sequel = typeof query === 'string' ? sql.raw(query) : query.getSQL();\n\t\tif (this.resultKind === 'async') {\n\t\t\treturn new SQLiteRaw(\n\t\t\t\tasync () => this.session.all(sequel),\n\t\t\t\t() => sequel,\n\t\t\t\t'all',\n\t\t\t\tthis.dialect as SQLiteAsyncDialect,\n\t\t\t\tthis.session.extractRawAllValueFromBatchResult.bind(this.session),\n\t\t\t) as any;\n\t\t}\n\t\treturn this.session.all(sequel) as DBResult;\n\t}\n\n\tget(query: SQLWrapper | string): DBResult {\n\t\tconst sequel = typeof query === 'string' ? sql.raw(query) : query.getSQL();\n\t\tif (this.resultKind === 'async') {\n\t\t\treturn new SQLiteRaw(\n\t\t\t\tasync () => this.session.get(sequel),\n\t\t\t\t() => sequel,\n\t\t\t\t'get',\n\t\t\t\tthis.dialect as SQLiteAsyncDialect,\n\t\t\t\tthis.session.extractRawGetValueFromBatchResult.bind(this.session),\n\t\t\t) as DBResult;\n\t\t}\n\t\treturn this.session.get(sequel) as DBResult;\n\t}\n\n\tvalues(query: SQLWrapper | string): DBResult {\n\t\tconst sequel = typeof query === 'string' ? sql.raw(query) : query.getSQL();\n\t\tif (this.resultKind === 'async') {\n\t\t\treturn new SQLiteRaw(\n\t\t\t\tasync () => this.session.values(sequel),\n\t\t\t\t() => sequel,\n\t\t\t\t'values',\n\t\t\t\tthis.dialect as SQLiteAsyncDialect,\n\t\t\t\tthis.session.extractRawValuesValueFromBatchResult.bind(this.session),\n\t\t\t) as any;\n\t\t}\n\t\treturn this.session.values(sequel) as DBResult;\n\t}\n\n\ttransaction(\n\t\ttransaction: (tx: SQLiteTransaction) => Result,\n\t\tconfig?: SQLiteTransactionConfig,\n\t): Result {\n\t\treturn this.session.transaction(transaction, config);\n\t}\n}\n\nexport type SQLiteWithReplicas = Q & { $primary: Q; $replicas: Q[] };\n\nexport const withReplicas = <\n\tTResultKind extends 'sync' | 'async',\n\tTRunResult,\n\tTFullSchema extends Record,\n\tTSchema extends TablesRelationalConfig,\n\tQ extends BaseSQLiteDatabase<\n\t\tTResultKind,\n\t\tTRunResult,\n\t\tTFullSchema,\n\t\tTSchema extends Record ? ExtractTablesWithRelations : TSchema\n\t>,\n>(\n\tprimary: Q,\n\treplicas: [Q, ...Q[]],\n\tgetReplica: (replicas: Q[]) => Q = () => replicas[Math.floor(Math.random() * replicas.length)]!,\n): SQLiteWithReplicas => {\n\tconst select: Q['select'] = (...args: []) => getReplica(replicas).select(...args);\n\tconst selectDistinct: Q['selectDistinct'] = (...args: []) => getReplica(replicas).selectDistinct(...args);\n\tconst $count: Q['$count'] = (...args: [any]) => getReplica(replicas).$count(...args);\n\tconst $with: Q['with'] = (...args: []) => getReplica(replicas).with(...args);\n\n\tconst update: Q['update'] = (...args: [any]) => primary.update(...args);\n\tconst insert: Q['insert'] = (...args: [any]) => primary.insert(...args);\n\tconst $delete: Q['delete'] = (...args: [any]) => primary.delete(...args);\n\tconst run: Q['run'] = (...args: [any]) => primary.run(...args);\n\tconst all: Q['all'] = (...args: [any]) => primary.all(...args);\n\tconst get: Q['get'] = (...args: [any]) => primary.get(...args);\n\tconst values: Q['values'] = (...args: [any]) => primary.values(...args);\n\tconst transaction: Q['transaction'] = (...args: [any]) => primary.transaction(...args);\n\n\treturn {\n\t\t...primary,\n\t\tupdate,\n\t\tinsert,\n\t\tdelete: $delete,\n\t\trun,\n\t\tall,\n\t\tget,\n\t\tvalues,\n\t\ttransaction,\n\t\t$primary: primary,\n\t\t$replicas: replicas,\n\t\tselect,\n\t\tselectDistinct,\n\t\t$count,\n\t\twith: $with,\n\t\tget query() {\n\t\t\treturn getReplica(replicas).query;\n\t\t},\n\t};\n};\n", "import { ColumnAliasProxyHandler, TableAliasProxyHandler } from './alias.ts';\nimport { Column } from './column.ts';\nimport { entityKind, is } from './entity.ts';\nimport { SQL, View } from './sql/sql.ts';\nimport { Subquery } from './subquery.ts';\nimport { ViewBaseConfig } from './view-common.ts';\n\nexport class SelectionProxyHandler | View>\n\timplements ProxyHandler | View>\n{\n\tstatic readonly [entityKind]: string = 'SelectionProxyHandler';\n\n\tprivate config: {\n\t\t/**\n\t\t * Table alias for the columns\n\t\t */\n\t\talias?: string;\n\t\t/**\n\t\t * What to do when a field is an instance of `SQL.Aliased` and it's not a selection field (from a subquery)\n\t\t *\n\t\t * `sql` - return the underlying SQL expression\n\t\t *\n\t\t * `alias` - return the field alias\n\t\t */\n\t\tsqlAliasedBehavior: 'sql' | 'alias';\n\t\t/**\n\t\t * What to do when a field is an instance of `SQL` and it doesn't have an alias declared\n\t\t *\n\t\t * `sql` - return the underlying SQL expression\n\t\t *\n\t\t * `error` - return a DrizzleTypeError on type level and throw an error on runtime\n\t\t */\n\t\tsqlBehavior: 'sql' | 'error';\n\n\t\t/**\n\t\t * Whether to replace the original name of the column with the alias\n\t\t * Should be set to `true` for views creation\n\t\t * @default false\n\t\t */\n\t\treplaceOriginalName?: boolean;\n\t};\n\n\tconstructor(config: SelectionProxyHandler['config']) {\n\t\tthis.config = { ...config };\n\t}\n\n\tget(subquery: T, prop: string | symbol): any {\n\t\tif (prop === '_') {\n\t\t\treturn {\n\t\t\t\t...subquery['_' as keyof typeof subquery],\n\t\t\t\tselectedFields: new Proxy(\n\t\t\t\t\t(subquery as Subquery)._.selectedFields,\n\t\t\t\t\tthis as ProxyHandler>,\n\t\t\t\t),\n\t\t\t};\n\t\t}\n\n\t\tif (prop === ViewBaseConfig) {\n\t\t\treturn {\n\t\t\t\t...subquery[ViewBaseConfig as keyof typeof subquery],\n\t\t\t\tselectedFields: new Proxy(\n\t\t\t\t\t(subquery as View)[ViewBaseConfig].selectedFields,\n\t\t\t\t\tthis as ProxyHandler>,\n\t\t\t\t),\n\t\t\t};\n\t\t}\n\n\t\tif (typeof prop === 'symbol') {\n\t\t\treturn subquery[prop as keyof typeof subquery];\n\t\t}\n\n\t\tconst columns = is(subquery, Subquery)\n\t\t\t? subquery._.selectedFields\n\t\t\t: is(subquery, View)\n\t\t\t? subquery[ViewBaseConfig].selectedFields\n\t\t\t: subquery;\n\t\tconst value: unknown = columns[prop as keyof typeof columns];\n\n\t\tif (is(value, SQL.Aliased)) {\n\t\t\t// Never return the underlying SQL expression for a field previously selected in a subquery\n\t\t\tif (this.config.sqlAliasedBehavior === 'sql' && !value.isSelectionField) {\n\t\t\t\treturn value.sql;\n\t\t\t}\n\n\t\t\tconst newValue = value.clone();\n\t\t\tnewValue.isSelectionField = true;\n\t\t\treturn newValue;\n\t\t}\n\n\t\tif (is(value, SQL)) {\n\t\t\tif (this.config.sqlBehavior === 'sql') {\n\t\t\t\treturn value;\n\t\t\t}\n\n\t\t\tthrow new Error(\n\t\t\t\t`You tried to reference \"${prop}\" field from a subquery, which is a raw SQL field, but it doesn't have an alias declared. Please add an alias to the field using \".as('alias')\" method.`,\n\t\t\t);\n\t\t}\n\n\t\tif (is(value, Column)) {\n\t\t\tif (this.config.alias) {\n\t\t\t\treturn new Proxy(\n\t\t\t\t\tvalue,\n\t\t\t\t\tnew ColumnAliasProxyHandler(\n\t\t\t\t\t\tnew Proxy(\n\t\t\t\t\t\t\tvalue.table,\n\t\t\t\t\t\t\tnew TableAliasProxyHandler(this.config.alias, this.config.replaceOriginalName ?? false),\n\t\t\t\t\t\t),\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn value;\n\t\t}\n\n\t\tif (typeof value !== 'object' || value === null) {\n\t\t\treturn value;\n\t\t}\n\n\t\treturn new Proxy(value, new SelectionProxyHandler(this.config));\n\t}\n}\n", "import type { AnyColumn } from './column.ts';\nimport { Column } from './column.ts';\nimport { entityKind, is } from './entity.ts';\nimport type { Relation } from './relations.ts';\nimport type { View } from './sql/sql.ts';\nimport { SQL, sql } from './sql/sql.ts';\nimport { Table } from './table.ts';\nimport { ViewBaseConfig } from './view-common.ts';\n\nexport class ColumnAliasProxyHandler implements ProxyHandler {\n\tstatic readonly [entityKind]: string = 'ColumnAliasProxyHandler';\n\n\tconstructor(private table: Table | View) {}\n\n\tget(columnObj: TColumn, prop: string | symbol): any {\n\t\tif (prop === 'table') {\n\t\t\treturn this.table;\n\t\t}\n\n\t\treturn columnObj[prop as keyof TColumn];\n\t}\n}\n\nexport class TableAliasProxyHandler implements ProxyHandler {\n\tstatic readonly [entityKind]: string = 'TableAliasProxyHandler';\n\n\tconstructor(private alias: string, private replaceOriginalName: boolean) {}\n\n\tget(target: T, prop: string | symbol): any {\n\t\tif (prop === Table.Symbol.IsAlias) {\n\t\t\treturn true;\n\t\t}\n\n\t\tif (prop === Table.Symbol.Name) {\n\t\t\treturn this.alias;\n\t\t}\n\n\t\tif (this.replaceOriginalName && prop === Table.Symbol.OriginalName) {\n\t\t\treturn this.alias;\n\t\t}\n\n\t\tif (prop === ViewBaseConfig) {\n\t\t\treturn {\n\t\t\t\t...target[ViewBaseConfig as keyof typeof target],\n\t\t\t\tname: this.alias,\n\t\t\t\tisAlias: true,\n\t\t\t};\n\t\t}\n\n\t\tif (prop === Table.Symbol.Columns) {\n\t\t\tconst columns = (target as Table)[Table.Symbol.Columns];\n\t\t\tif (!columns) {\n\t\t\t\treturn columns;\n\t\t\t}\n\n\t\t\tconst proxiedColumns: { [key: string]: any } = {};\n\n\t\t\tObject.keys(columns).map((key) => {\n\t\t\t\tproxiedColumns[key] = new Proxy(\n\t\t\t\t\tcolumns[key]!,\n\t\t\t\t\tnew ColumnAliasProxyHandler(new Proxy(target, this)),\n\t\t\t\t);\n\t\t\t});\n\n\t\t\treturn proxiedColumns;\n\t\t}\n\n\t\tconst value = target[prop as keyof typeof target];\n\t\tif (is(value, Column)) {\n\t\t\treturn new Proxy(value as AnyColumn, new ColumnAliasProxyHandler(new Proxy(target, this)));\n\t\t}\n\n\t\treturn value;\n\t}\n}\n\nexport class RelationTableAliasProxyHandler implements ProxyHandler {\n\tstatic readonly [entityKind]: string = 'RelationTableAliasProxyHandler';\n\n\tconstructor(private alias: string) {}\n\n\tget(target: T, prop: string | symbol): any {\n\t\tif (prop === 'sourceTable') {\n\t\t\treturn aliasedTable(target.sourceTable, this.alias);\n\t\t}\n\n\t\treturn target[prop as keyof typeof target];\n\t}\n}\n\nexport function aliasedTable(\n\ttable: T,\n\ttableAlias: string,\n): T {\n\treturn new Proxy(table, new TableAliasProxyHandler(tableAlias, false)) as any;\n}\n\nexport function aliasedRelation(relation: T, tableAlias: string): T {\n\treturn new Proxy(relation, new RelationTableAliasProxyHandler(tableAlias));\n}\n\nexport function aliasedTableColumn(column: T, tableAlias: string): T {\n\treturn new Proxy(\n\t\tcolumn,\n\t\tnew ColumnAliasProxyHandler(new Proxy(column.table, new TableAliasProxyHandler(tableAlias, false))),\n\t);\n}\n\nexport function mapColumnsInAliasedSQLToAlias(query: SQL.Aliased, alias: string): SQL.Aliased {\n\treturn new SQL.Aliased(mapColumnsInSQLToAlias(query.sql, alias), query.fieldAlias);\n}\n\nexport function mapColumnsInSQLToAlias(query: SQL, alias: string): SQL {\n\treturn sql.join(query.queryChunks.map((c) => {\n\t\tif (is(c, Column)) {\n\t\t\treturn aliasedTableColumn(c, alias);\n\t\t}\n\t\tif (is(c, SQL)) {\n\t\t\treturn mapColumnsInSQLToAlias(c, alias);\n\t\t}\n\t\tif (is(c, SQL.Aliased)) {\n\t\t\treturn mapColumnsInAliasedSQLToAlias(c, alias);\n\t\t}\n\t\treturn c;\n\t}));\n}\n", "import { entityKind } from '~/entity.ts';\nimport type { SelectResultFields } from '~/query-builders/select.types.ts';\nimport { QueryPromise } from '~/query-promise.ts';\nimport type { RunnableQuery } from '~/runnable-query.ts';\nimport { SelectionProxyHandler } from '~/selection-proxy.ts';\nimport type { Placeholder, Query, SQL, SQLWrapper } from '~/sql/sql.ts';\nimport type { SQLiteDialect } from '~/sqlite-core/dialect.ts';\nimport type { SQLitePreparedQuery, SQLiteSession } from '~/sqlite-core/session.ts';\nimport { SQLiteTable } from '~/sqlite-core/table.ts';\nimport type { Subquery } from '~/subquery.ts';\nimport { Table } from '~/table.ts';\nimport { type DrizzleTypeError, orderSelectedFields, type ValueOrArray } from '~/utils.ts';\nimport type { SQLiteColumn } from '../columns/common.ts';\nimport { extractUsedTable } from '../utils.ts';\nimport type { SelectedFieldsFlat, SelectedFieldsOrdered } from './select.types.ts';\n\nexport type SQLiteDeleteWithout<\n\tT extends AnySQLiteDeleteBase,\n\tTDynamic extends boolean,\n\tK extends keyof T & string,\n> = TDynamic extends true ? T\n\t: Omit<\n\t\tSQLiteDeleteBase<\n\t\t\tT['_']['table'],\n\t\t\tT['_']['resultType'],\n\t\t\tT['_']['runResult'],\n\t\t\tT['_']['returning'],\n\t\t\tTDynamic,\n\t\t\tT['_']['excludedMethods'] | K\n\t\t>,\n\t\tT['_']['excludedMethods'] | K\n\t>;\n\nexport type SQLiteDelete<\n\tTTable extends SQLiteTable = SQLiteTable,\n\tTResultType extends 'sync' | 'async' = 'sync' | 'async',\n\tTRunResult = unknown,\n\tTReturning extends Record | undefined = undefined,\n> = SQLiteDeleteBase;\n\nexport interface SQLiteDeleteConfig {\n\twhere?: SQL | undefined;\n\tlimit?: number | Placeholder;\n\torderBy?: (SQLiteColumn | SQL | SQL.Aliased)[];\n\ttable: SQLiteTable;\n\treturning?: SelectedFieldsOrdered;\n\twithList?: Subquery[];\n}\n\nexport type SQLiteDeleteReturningAll<\n\tT extends AnySQLiteDeleteBase,\n\tTDynamic extends boolean,\n> = SQLiteDeleteWithout<\n\tSQLiteDeleteBase<\n\t\tT['_']['table'],\n\t\tT['_']['resultType'],\n\t\tT['_']['runResult'],\n\t\tT['_']['table']['$inferSelect'],\n\t\tT['_']['dynamic'],\n\t\tT['_']['excludedMethods']\n\t>,\n\tTDynamic,\n\t'returning'\n>;\n\nexport type SQLiteDeleteReturning<\n\tT extends AnySQLiteDeleteBase,\n\tTDynamic extends boolean,\n\tTSelectedFields extends SelectedFieldsFlat,\n> = SQLiteDeleteWithout<\n\tSQLiteDeleteBase<\n\t\tT['_']['table'],\n\t\tT['_']['resultType'],\n\t\tT['_']['runResult'],\n\t\tSelectResultFields,\n\t\tT['_']['dynamic'],\n\t\tT['_']['excludedMethods']\n\t>,\n\tTDynamic,\n\t'returning'\n>;\n\nexport type SQLiteDeleteExecute = T['_']['returning'] extends undefined\n\t? T['_']['runResult']\n\t: T['_']['returning'][];\n\nexport type SQLiteDeletePrepare = SQLitePreparedQuery<{\n\ttype: T['_']['resultType'];\n\trun: T['_']['runResult'];\n\tall: T['_']['returning'] extends undefined ? DrizzleTypeError<'.all() cannot be used without .returning()'>\n\t\t: T['_']['returning'][];\n\tget: T['_']['returning'] extends undefined ? DrizzleTypeError<'.get() cannot be used without .returning()'>\n\t\t: T['_']['returning'] | undefined;\n\tvalues: T['_']['returning'] extends undefined ? DrizzleTypeError<'.values() cannot be used without .returning()'>\n\t\t: any[][];\n\texecute: SQLiteDeleteExecute;\n}>;\n\nexport type SQLiteDeleteDynamic = SQLiteDelete<\n\tT['_']['table'],\n\tT['_']['resultType'],\n\tT['_']['runResult'],\n\tT['_']['returning']\n>;\n\nexport type AnySQLiteDeleteBase = SQLiteDeleteBase;\n\nexport interface SQLiteDeleteBase<\n\tTTable extends SQLiteTable,\n\tTResultType extends 'sync' | 'async',\n\tTRunResult,\n\tTReturning extends Record | undefined = undefined,\n\tTDynamic extends boolean = false,\n\tTExcludedMethods extends string = never,\n> extends\n\tQueryPromise,\n\tRunnableQuery,\n\tSQLWrapper\n{\n\treadonly _: {\n\t\tdialect: 'sqlite';\n\t\treadonly table: TTable;\n\t\treadonly resultType: TResultType;\n\t\treadonly runResult: TRunResult;\n\t\treadonly returning: TReturning;\n\t\treadonly dynamic: TDynamic;\n\t\treadonly excludedMethods: TExcludedMethods;\n\t\treadonly result: TReturning extends undefined ? TRunResult : TReturning[];\n\t};\n}\n\nexport class SQLiteDeleteBase<\n\tTTable extends SQLiteTable,\n\t// eslint-disable-next-line @typescript-eslint/no-unused-vars\n\tTResultType extends 'sync' | 'async',\n\tTRunResult,\n\tTReturning extends Record | undefined = undefined,\n\tTDynamic extends boolean = false,\n\t// eslint-disable-next-line @typescript-eslint/no-unused-vars\n\tTExcludedMethods extends string = never,\n> extends QueryPromise\n\timplements RunnableQuery, SQLWrapper\n{\n\tstatic override readonly [entityKind]: string = 'SQLiteDelete';\n\n\t/** @internal */\n\tconfig: SQLiteDeleteConfig;\n\n\tconstructor(\n\t\tprivate table: TTable,\n\t\tprivate session: SQLiteSession,\n\t\tprivate dialect: SQLiteDialect,\n\t\twithList?: Subquery[],\n\t) {\n\t\tsuper();\n\t\tthis.config = { table, withList };\n\t}\n\n\t/**\n\t * Adds a `where` clause to the query.\n\t *\n\t * Calling this method will delete only those rows that fulfill a specified condition.\n\t *\n\t * See docs: {@link https://orm.drizzle.team/docs/delete}\n\t *\n\t * @param where the `where` clause.\n\t *\n\t * @example\n\t * You can use conditional operators and `sql function` to filter the rows to be deleted.\n\t *\n\t * ```ts\n\t * // Delete all cars with green color\n\t * db.delete(cars).where(eq(cars.color, 'green'));\n\t * // or\n\t * db.delete(cars).where(sql`${cars.color} = 'green'`)\n\t * ```\n\t *\n\t * You can logically combine conditional operators with `and()` and `or()` operators:\n\t *\n\t * ```ts\n\t * // Delete all BMW cars with a green color\n\t * db.delete(cars).where(and(eq(cars.color, 'green'), eq(cars.brand, 'BMW')));\n\t *\n\t * // Delete all cars with the green or blue color\n\t * db.delete(cars).where(or(eq(cars.color, 'green'), eq(cars.color, 'blue')));\n\t * ```\n\t */\n\twhere(where: SQL | undefined): SQLiteDeleteWithout {\n\t\tthis.config.where = where;\n\t\treturn this as any;\n\t}\n\n\torderBy(\n\t\tbuilder: (deleteTable: TTable) => ValueOrArray,\n\t): SQLiteDeleteWithout;\n\torderBy(...columns: (SQLiteColumn | SQL | SQL.Aliased)[]): SQLiteDeleteWithout;\n\torderBy(\n\t\t...columns:\n\t\t\t| [(deleteTable: TTable) => ValueOrArray]\n\t\t\t| (SQLiteColumn | SQL | SQL.Aliased)[]\n\t): SQLiteDeleteWithout {\n\t\tif (typeof columns[0] === 'function') {\n\t\t\tconst orderBy = columns[0](\n\t\t\t\tnew Proxy(\n\t\t\t\t\tthis.config.table[Table.Symbol.Columns],\n\t\t\t\t\tnew SelectionProxyHandler({ sqlAliasedBehavior: 'alias', sqlBehavior: 'sql' }),\n\t\t\t\t) as any,\n\t\t\t);\n\n\t\t\tconst orderByArray = Array.isArray(orderBy) ? orderBy : [orderBy];\n\t\t\tthis.config.orderBy = orderByArray;\n\t\t} else {\n\t\t\tconst orderByArray = columns as (SQLiteColumn | SQL | SQL.Aliased)[];\n\t\t\tthis.config.orderBy = orderByArray;\n\t\t}\n\t\treturn this as any;\n\t}\n\n\tlimit(limit: number | Placeholder): SQLiteDeleteWithout {\n\t\tthis.config.limit = limit;\n\t\treturn this as any;\n\t}\n\n\t/**\n\t * Adds a `returning` clause to the query.\n\t *\n\t * Calling this method will return the specified fields of the deleted rows. If no fields are specified, all fields will be returned.\n\t *\n\t * See docs: {@link https://orm.drizzle.team/docs/delete#delete-with-return}\n\t *\n\t * @example\n\t * ```ts\n\t * // Delete all cars with the green color and return all fields\n\t * const deletedCars: Car[] = await db.delete(cars)\n\t * .where(eq(cars.color, 'green'))\n\t * .returning();\n\t *\n\t * // Delete all cars with the green color and return only their id and brand fields\n\t * const deletedCarsIdsAndBrands: { id: number, brand: string }[] = await db.delete(cars)\n\t * .where(eq(cars.color, 'green'))\n\t * .returning({ id: cars.id, brand: cars.brand });\n\t * ```\n\t */\n\treturning(): SQLiteDeleteReturningAll;\n\treturning(\n\t\tfields: TSelectedFields,\n\t): SQLiteDeleteReturning;\n\treturning(\n\t\tfields: SelectedFieldsFlat = this.table[SQLiteTable.Symbol.Columns],\n\t): SQLiteDeleteReturning {\n\t\tthis.config.returning = orderSelectedFields(fields);\n\t\treturn this as any;\n\t}\n\n\t/** @internal */\n\tgetSQL(): SQL {\n\t\treturn this.dialect.buildDeleteQuery(this.config);\n\t}\n\n\ttoSQL(): Query {\n\t\tconst { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());\n\t\treturn rest;\n\t}\n\n\t/** @internal */\n\t_prepare(isOneTimeQuery = true): SQLiteDeletePrepare {\n\t\treturn this.session[isOneTimeQuery ? 'prepareOneTimeQuery' : 'prepareQuery'](\n\t\t\tthis.dialect.sqlToQuery(this.getSQL()),\n\t\t\tthis.config.returning,\n\t\t\tthis.config.returning ? 'all' : 'run',\n\t\t\ttrue,\n\t\t\tundefined,\n\t\t\t{\n\t\t\t\ttype: 'delete',\n\t\t\t\ttables: extractUsedTable(this.config.table),\n\t\t\t},\n\t\t) as SQLiteDeletePrepare;\n\t}\n\n\tprepare(): SQLiteDeletePrepare {\n\t\treturn this._prepare(false);\n\t}\n\n\trun: ReturnType['run'] = (placeholderValues) => {\n\t\treturn this._prepare().run(placeholderValues);\n\t};\n\n\tall: ReturnType['all'] = (placeholderValues) => {\n\t\treturn this._prepare().all(placeholderValues);\n\t};\n\n\tget: ReturnType['get'] = (placeholderValues) => {\n\t\treturn this._prepare().get(placeholderValues);\n\t};\n\n\tvalues: ReturnType['values'] = (placeholderValues) => {\n\t\treturn this._prepare().values(placeholderValues);\n\t};\n\n\toverride async execute(placeholderValues?: Record): Promise> {\n\t\treturn this._prepare().execute(placeholderValues) as SQLiteDeleteExecute;\n\t}\n\n\t$dynamic(): SQLiteDeleteDynamic {\n\t\treturn this as any;\n\t}\n}\n", "import { entityKind } from '~/entity.ts';\n\nexport abstract class QueryPromise implements Promise {\n\tstatic readonly [entityKind]: string = 'QueryPromise';\n\n\t[Symbol.toStringTag] = 'QueryPromise';\n\n\tcatch(\n\t\tonRejected?: ((reason: any) => TResult | PromiseLike) | null | undefined,\n\t): Promise {\n\t\treturn this.then(undefined, onRejected);\n\t}\n\n\tfinally(onFinally?: (() => void) | null | undefined): Promise {\n\t\treturn this.then(\n\t\t\t(value) => {\n\t\t\t\tonFinally?.();\n\t\t\t\treturn value;\n\t\t\t},\n\t\t\t(reason) => {\n\t\t\t\tonFinally?.();\n\t\t\t\tthrow reason;\n\t\t\t},\n\t\t);\n\t}\n\n\tthen(\n\t\tonFulfilled?: ((value: T) => TResult1 | PromiseLike) | undefined | null,\n\t\tonRejected?: ((reason: any) => TResult2 | PromiseLike) | undefined | null,\n\t): Promise {\n\t\treturn this.execute().then(onFulfilled, onRejected);\n\t}\n\n\tabstract execute(): Promise;\n}\n", "import type { BuildColumns, BuildExtraConfigColumns } from '~/column-builder.ts';\nimport { entityKind } from '~/entity.ts';\nimport { Table, type TableConfig as TableConfigBase, type UpdateTableConfig } from '~/table.ts';\nimport type { CheckBuilder } from './checks.ts';\nimport { getSQLiteColumnBuilders, type SQLiteColumnBuilders } from './columns/all.ts';\nimport type { SQLiteColumn, SQLiteColumnBuilder, SQLiteColumnBuilderBase } from './columns/common.ts';\nimport type { ForeignKey, ForeignKeyBuilder } from './foreign-keys.ts';\nimport type { IndexBuilder } from './indexes.ts';\nimport type { PrimaryKeyBuilder } from './primary-keys.ts';\nimport type { UniqueConstraintBuilder } from './unique-constraint.ts';\n\nexport type SQLiteTableExtraConfigValue =\n\t| IndexBuilder\n\t| CheckBuilder\n\t| ForeignKeyBuilder\n\t| PrimaryKeyBuilder\n\t| UniqueConstraintBuilder;\n\nexport type SQLiteTableExtraConfig = Record<\n\tstring,\n\tSQLiteTableExtraConfigValue\n>;\n\nexport type TableConfig = TableConfigBase>;\n\n/** @internal */\nexport const InlineForeignKeys = Symbol.for('drizzle:SQLiteInlineForeignKeys');\n\nexport class SQLiteTable extends Table {\n\tstatic override readonly [entityKind]: string = 'SQLiteTable';\n\n\t/** @internal */\n\tstatic override readonly Symbol = Object.assign({}, Table.Symbol, {\n\t\tInlineForeignKeys: InlineForeignKeys as typeof InlineForeignKeys,\n\t});\n\n\t/** @internal */\n\toverride [Table.Symbol.Columns]!: NonNullable;\n\n\t/** @internal */\n\t[InlineForeignKeys]: ForeignKey[] = [];\n\n\t/** @internal */\n\toverride [Table.Symbol.ExtraConfigBuilder]:\n\t\t| ((self: Record) => SQLiteTableExtraConfig)\n\t\t| undefined = undefined;\n}\n\nexport type AnySQLiteTable = {}> = SQLiteTable<\n\tUpdateTableConfig\n>;\n\nexport type SQLiteTableWithColumns =\n\t& SQLiteTable\n\t& {\n\t\t[Key in keyof T['columns']]: T['columns'][Key];\n\t};\n\nexport interface SQLiteTableFn {\n\t<\n\t\tTTableName extends string,\n\t\tTColumnsMap extends Record,\n\t>(\n\t\tname: TTableName,\n\t\tcolumns: TColumnsMap,\n\t\textraConfig?: (\n\t\t\tself: BuildColumns,\n\t\t) => SQLiteTableExtraConfigValue[],\n\t): SQLiteTableWithColumns<{\n\t\tname: TTableName;\n\t\tschema: TSchema;\n\t\tcolumns: BuildColumns;\n\t\tdialect: 'sqlite';\n\t}>;\n\n\t<\n\t\tTTableName extends string,\n\t\tTColumnsMap extends Record,\n\t>(\n\t\tname: TTableName,\n\t\tcolumns: (columnTypes: SQLiteColumnBuilders) => TColumnsMap,\n\t\textraConfig?: (self: BuildColumns) => SQLiteTableExtraConfigValue[],\n\t): SQLiteTableWithColumns<{\n\t\tname: TTableName;\n\t\tschema: TSchema;\n\t\tcolumns: BuildColumns;\n\t\tdialect: 'sqlite';\n\t}>;\n\t/**\n\t * @deprecated The third parameter of sqliteTable is changing and will only accept an array instead of an object\n\t *\n\t * @example\n\t * Deprecated version:\n\t * ```ts\n\t * export const users = sqliteTable(\"users\", {\n\t * \tid: int(),\n\t * }, (t) => ({\n\t * \tidx: index('custom_name').on(t.id)\n\t * }));\n\t * ```\n\t *\n\t * New API:\n\t * ```ts\n\t * export const users = sqliteTable(\"users\", {\n\t * \tid: int(),\n\t * }, (t) => [\n\t * \tindex('custom_name').on(t.id)\n\t * ]);\n\t * ```\n\t */\n\t<\n\t\tTTableName extends string,\n\t\tTColumnsMap extends Record,\n\t>(\n\t\tname: TTableName,\n\t\tcolumns: TColumnsMap,\n\t\textraConfig?: (self: BuildColumns) => SQLiteTableExtraConfig,\n\t): SQLiteTableWithColumns<{\n\t\tname: TTableName;\n\t\tschema: TSchema;\n\t\tcolumns: BuildColumns;\n\t\tdialect: 'sqlite';\n\t}>;\n\n\t/**\n\t * @deprecated The third parameter of sqliteTable is changing and will only accept an array instead of an object\n\t *\n\t * @example\n\t * Deprecated version:\n\t * ```ts\n\t * export const users = sqliteTable(\"users\", {\n\t * \tid: int(),\n\t * }, (t) => ({\n\t * \tidx: index('custom_name').on(t.id)\n\t * }));\n\t * ```\n\t *\n\t * New API:\n\t * ```ts\n\t * export const users = sqliteTable(\"users\", {\n\t * \tid: int(),\n\t * }, (t) => [\n\t * \tindex('custom_name').on(t.id)\n\t * ]);\n\t * ```\n\t */\n\t<\n\t\tTTableName extends string,\n\t\tTColumnsMap extends Record,\n\t>(\n\t\tname: TTableName,\n\t\tcolumns: (columnTypes: SQLiteColumnBuilders) => TColumnsMap,\n\t\textraConfig?: (self: BuildColumns) => SQLiteTableExtraConfig,\n\t): SQLiteTableWithColumns<{\n\t\tname: TTableName;\n\t\tschema: TSchema;\n\t\tcolumns: BuildColumns;\n\t\tdialect: 'sqlite';\n\t}>;\n}\n\nfunction sqliteTableBase<\n\tTTableName extends string,\n\tTColumnsMap extends Record,\n\tTSchema extends string | undefined,\n>(\n\tname: TTableName,\n\tcolumns: TColumnsMap | ((columnTypes: SQLiteColumnBuilders) => TColumnsMap),\n\textraConfig:\n\t\t| ((\n\t\t\tself: BuildColumns,\n\t\t) => SQLiteTableExtraConfig | SQLiteTableExtraConfigValue[])\n\t\t| undefined,\n\tschema?: TSchema,\n\tbaseName = name,\n): SQLiteTableWithColumns<{\n\tname: TTableName;\n\tschema: TSchema;\n\tcolumns: BuildColumns;\n\tdialect: 'sqlite';\n}> {\n\tconst rawTable = new SQLiteTable<{\n\t\tname: TTableName;\n\t\tschema: TSchema;\n\t\tcolumns: BuildColumns;\n\t\tdialect: 'sqlite';\n\t}>(name, schema, baseName);\n\n\tconst parsedColumns: TColumnsMap = typeof columns === 'function' ? columns(getSQLiteColumnBuilders()) : columns;\n\n\tconst builtColumns = Object.fromEntries(\n\t\tObject.entries(parsedColumns).map(([name, colBuilderBase]) => {\n\t\t\tconst colBuilder = colBuilderBase as SQLiteColumnBuilder;\n\t\t\tcolBuilder.setName(name);\n\t\t\tconst column = colBuilder.build(rawTable);\n\t\t\trawTable[InlineForeignKeys].push(...colBuilder.buildForeignKeys(column, rawTable));\n\t\t\treturn [name, column];\n\t\t}),\n\t) as unknown as BuildColumns;\n\n\tconst table = Object.assign(rawTable, builtColumns);\n\n\ttable[Table.Symbol.Columns] = builtColumns;\n\ttable[Table.Symbol.ExtraConfigColumns] = builtColumns as unknown as BuildExtraConfigColumns<\n\t\tTTableName,\n\t\tTColumnsMap,\n\t\t'sqlite'\n\t>;\n\n\tif (extraConfig) {\n\t\ttable[SQLiteTable.Symbol.ExtraConfigBuilder] = extraConfig as (\n\t\t\tself: Record,\n\t\t) => SQLiteTableExtraConfig;\n\t}\n\n\treturn table;\n}\n\nexport const sqliteTable: SQLiteTableFn = (name, columns, extraConfig) => {\n\treturn sqliteTableBase(name, columns, extraConfig);\n};\n\nexport function sqliteTableCreator(customizeTableName: (name: string) => string): SQLiteTableFn {\n\treturn (name, columns, extraConfig) => {\n\t\treturn sqliteTableBase(customizeTableName(name) as typeof name, columns, extraConfig, undefined, name);\n\t};\n}\n", "import { blob } from './blob.ts';\nimport { customType } from './custom.ts';\nimport { integer } from './integer.ts';\nimport { numeric } from './numeric.ts';\nimport { real } from './real.ts';\nimport { text } from './text.ts';\n\nexport function getSQLiteColumnBuilders() {\n\treturn {\n\t\tblob,\n\t\tcustomType,\n\t\tinteger,\n\t\tnumeric,\n\t\treal,\n\t\ttext,\n\t};\n}\n\nexport type SQLiteColumnBuilders = ReturnType;\n", "import type { ColumnBuilderBaseConfig, ColumnBuilderRuntimeConfig, MakeColumnConfig } from '~/column-builder.ts';\nimport type { ColumnBaseConfig } from '~/column.ts';\nimport { entityKind } from '~/entity.ts';\nimport type { AnySQLiteTable } from '~/sqlite-core/table.ts';\nimport { type Equal, getColumnNameAndConfig, textDecoder } from '~/utils.ts';\nimport { SQLiteColumn, SQLiteColumnBuilder } from './common.ts';\n\ntype BlobMode = 'buffer' | 'json' | 'bigint';\n\nexport type SQLiteBigIntBuilderInitial = SQLiteBigIntBuilder<{\n\tname: TName;\n\tdataType: 'bigint';\n\tcolumnType: 'SQLiteBigInt';\n\tdata: bigint;\n\tdriverParam: Buffer;\n\tenumValues: undefined;\n}>;\n\nexport class SQLiteBigIntBuilder>\n\textends SQLiteColumnBuilder\n{\n\tstatic override readonly [entityKind]: string = 'SQLiteBigIntBuilder';\n\n\tconstructor(name: T['name']) {\n\t\tsuper(name, 'bigint', 'SQLiteBigInt');\n\t}\n\n\t/** @internal */\n\toverride build(\n\t\ttable: AnySQLiteTable<{ name: TTableName }>,\n\t): SQLiteBigInt> {\n\t\treturn new SQLiteBigInt>(table, this.config as ColumnBuilderRuntimeConfig);\n\t}\n}\n\nexport class SQLiteBigInt> extends SQLiteColumn {\n\tstatic override readonly [entityKind]: string = 'SQLiteBigInt';\n\n\tgetSQLType(): string {\n\t\treturn 'blob';\n\t}\n\n\toverride mapFromDriverValue(value: Buffer | Uint8Array | ArrayBuffer): bigint {\n\t\tif (typeof Buffer !== 'undefined' && Buffer.from) {\n\t\t\tconst buf = Buffer.isBuffer(value)\n\t\t\t\t? value\n\t\t\t\t// eslint-disable-next-line no-instanceof/no-instanceof\n\t\t\t\t: value instanceof ArrayBuffer\n\t\t\t\t? Buffer.from(value)\n\t\t\t\t: value.buffer\n\t\t\t\t? Buffer.from(value.buffer, value.byteOffset, value.byteLength)\n\t\t\t\t: Buffer.from(value);\n\t\t\treturn BigInt(buf.toString('utf8'));\n\t\t}\n\n\t\treturn BigInt(textDecoder!.decode(value));\n\t}\n\n\toverride mapToDriverValue(value: bigint): Buffer {\n\t\treturn Buffer.from(value.toString());\n\t}\n}\n\nexport type SQLiteBlobJsonBuilderInitial = SQLiteBlobJsonBuilder<{\n\tname: TName;\n\tdataType: 'json';\n\tcolumnType: 'SQLiteBlobJson';\n\tdata: unknown;\n\tdriverParam: Buffer;\n\tenumValues: undefined;\n}>;\n\nexport class SQLiteBlobJsonBuilder>\n\textends SQLiteColumnBuilder\n{\n\tstatic override readonly [entityKind]: string = 'SQLiteBlobJsonBuilder';\n\n\tconstructor(name: T['name']) {\n\t\tsuper(name, 'json', 'SQLiteBlobJson');\n\t}\n\n\t/** @internal */\n\toverride build(\n\t\ttable: AnySQLiteTable<{ name: TTableName }>,\n\t): SQLiteBlobJson> {\n\t\treturn new SQLiteBlobJson>(\n\t\t\ttable,\n\t\t\tthis.config as ColumnBuilderRuntimeConfig,\n\t\t);\n\t}\n}\n\nexport class SQLiteBlobJson> extends SQLiteColumn {\n\tstatic override readonly [entityKind]: string = 'SQLiteBlobJson';\n\n\tgetSQLType(): string {\n\t\treturn 'blob';\n\t}\n\n\toverride mapFromDriverValue(value: Buffer | Uint8Array | ArrayBuffer): T['data'] {\n\t\tif (typeof Buffer !== 'undefined' && Buffer.from) {\n\t\t\tconst buf = Buffer.isBuffer(value)\n\t\t\t\t? value\n\t\t\t\t// eslint-disable-next-line no-instanceof/no-instanceof\n\t\t\t\t: value instanceof ArrayBuffer\n\t\t\t\t? Buffer.from(value)\n\t\t\t\t: value.buffer\n\t\t\t\t? Buffer.from(value.buffer, value.byteOffset, value.byteLength)\n\t\t\t\t: Buffer.from(value);\n\t\t\treturn JSON.parse(buf.toString('utf8'));\n\t\t}\n\n\t\treturn JSON.parse(textDecoder!.decode(value));\n\t}\n\n\toverride mapToDriverValue(value: T['data']): Buffer {\n\t\treturn Buffer.from(JSON.stringify(value));\n\t}\n}\n\nexport type SQLiteBlobBufferBuilderInitial = SQLiteBlobBufferBuilder<{\n\tname: TName;\n\tdataType: 'buffer';\n\tcolumnType: 'SQLiteBlobBuffer';\n\tdata: Buffer;\n\tdriverParam: Buffer;\n\tenumValues: undefined;\n}>;\n\nexport class SQLiteBlobBufferBuilder>\n\textends SQLiteColumnBuilder\n{\n\tstatic override readonly [entityKind]: string = 'SQLiteBlobBufferBuilder';\n\n\tconstructor(name: T['name']) {\n\t\tsuper(name, 'buffer', 'SQLiteBlobBuffer');\n\t}\n\n\t/** @internal */\n\toverride build(\n\t\ttable: AnySQLiteTable<{ name: TTableName }>,\n\t): SQLiteBlobBuffer> {\n\t\treturn new SQLiteBlobBuffer>(table, this.config as ColumnBuilderRuntimeConfig);\n\t}\n}\n\nexport class SQLiteBlobBuffer> extends SQLiteColumn {\n\tstatic override readonly [entityKind]: string = 'SQLiteBlobBuffer';\n\n\toverride mapFromDriverValue(value: Buffer | Uint8Array | ArrayBuffer): T['data'] {\n\t\tif (Buffer.isBuffer(value)) {\n\t\t\treturn value;\n\t\t}\n\n\t\treturn Buffer.from(value as Uint8Array);\n\t}\n\n\tgetSQLType(): string {\n\t\treturn 'blob';\n\t}\n}\n\nexport interface BlobConfig {\n\tmode: TMode;\n}\n\n/**\n * It's recommended to use `text('...', { mode: 'json' })` instead of `blob` in JSON mode, because it supports JSON functions:\n * >All JSON functions currently throw an error if any of their arguments are BLOBs because BLOBs are reserved for a future enhancement in which BLOBs will store the binary encoding for JSON.\n *\n * https://www.sqlite.org/json1.html\n */\nexport function blob(): SQLiteBlobJsonBuilderInitial<''>;\nexport function blob(\n\tconfig?: BlobConfig,\n): Equal extends true ? SQLiteBigIntBuilderInitial<''>\n\t: Equal extends true ? SQLiteBlobBufferBuilderInitial<''>\n\t: SQLiteBlobJsonBuilderInitial<''>;\nexport function blob(\n\tname: TName,\n\tconfig?: BlobConfig,\n): Equal extends true ? SQLiteBigIntBuilderInitial\n\t: Equal extends true ? SQLiteBlobBufferBuilderInitial\n\t: SQLiteBlobJsonBuilderInitial;\nexport function blob(a?: string | BlobConfig, b?: BlobConfig) {\n\tconst { name, config } = getColumnNameAndConfig(a, b);\n\tif (config?.mode === 'json') {\n\t\treturn new SQLiteBlobJsonBuilder(name);\n\t}\n\tif (config?.mode === 'bigint') {\n\t\treturn new SQLiteBigIntBuilder(name);\n\t}\n\treturn new SQLiteBlobBufferBuilder(name);\n}\n", "import type {\n\tColumnBuilderBase,\n\tColumnBuilderBaseConfig,\n\tColumnBuilderExtraConfig,\n\tColumnBuilderRuntimeConfig,\n\tColumnDataType,\n\tHasGenerated,\n\tMakeColumnConfig,\n} from '~/column-builder.ts';\nimport { ColumnBuilder } from '~/column-builder.ts';\nimport { Column } from '~/column.ts';\nimport type { ColumnBaseConfig } from '~/column.ts';\nimport { entityKind } from '~/entity.ts';\nimport type { SQL } from '~/sql/sql.ts';\nimport type { ForeignKey, UpdateDeleteAction } from '~/sqlite-core/foreign-keys.ts';\nimport { ForeignKeyBuilder } from '~/sqlite-core/foreign-keys.ts';\nimport type { AnySQLiteTable, SQLiteTable } from '~/sqlite-core/table.ts';\nimport type { Update } from '~/utils.ts';\nimport { uniqueKeyName } from '../unique-constraint.ts';\n\nexport interface ReferenceConfig {\n\tref: () => SQLiteColumn;\n\tactions: {\n\t\tonUpdate?: UpdateDeleteAction;\n\t\tonDelete?: UpdateDeleteAction;\n\t};\n}\n\nexport interface SQLiteColumnBuilderBase<\n\tT extends ColumnBuilderBaseConfig = ColumnBuilderBaseConfig,\n\tTTypeConfig extends object = object,\n> extends ColumnBuilderBase {}\n\nexport interface SQLiteGeneratedColumnConfig {\n\tmode?: 'virtual' | 'stored';\n}\n\nexport abstract class SQLiteColumnBuilder<\n\tT extends ColumnBuilderBaseConfig = ColumnBuilderBaseConfig,\n\tTRuntimeConfig extends object = object,\n\tTTypeConfig extends object = object,\n\tTExtraConfig extends ColumnBuilderExtraConfig = object,\n> extends ColumnBuilder\n\timplements SQLiteColumnBuilderBase\n{\n\tstatic override readonly [entityKind]: string = 'SQLiteColumnBuilder';\n\n\tprivate foreignKeyConfigs: ReferenceConfig[] = [];\n\n\treferences(\n\t\tref: ReferenceConfig['ref'],\n\t\tactions: ReferenceConfig['actions'] = {},\n\t): this {\n\t\tthis.foreignKeyConfigs.push({ ref, actions });\n\t\treturn this;\n\t}\n\n\tunique(\n\t\tname?: string,\n\t): this {\n\t\tthis.config.isUnique = true;\n\t\tthis.config.uniqueName = name;\n\t\treturn this;\n\t}\n\n\tgeneratedAlwaysAs(as: SQL | T['data'] | (() => SQL), config?: SQLiteGeneratedColumnConfig): HasGenerated {\n\t\tthis.config.generated = {\n\t\t\tas,\n\t\t\ttype: 'always',\n\t\t\tmode: config?.mode ?? 'virtual',\n\t\t};\n\t\treturn this as any;\n\t}\n\n\t/** @internal */\n\tbuildForeignKeys(column: SQLiteColumn, table: SQLiteTable): ForeignKey[] {\n\t\treturn this.foreignKeyConfigs.map(({ ref, actions }) => {\n\t\t\treturn ((ref, actions) => {\n\t\t\t\tconst builder = new ForeignKeyBuilder(() => {\n\t\t\t\t\tconst foreignColumn = ref();\n\t\t\t\t\treturn { columns: [column], foreignColumns: [foreignColumn] };\n\t\t\t\t});\n\t\t\t\tif (actions.onUpdate) {\n\t\t\t\t\tbuilder.onUpdate(actions.onUpdate);\n\t\t\t\t}\n\t\t\t\tif (actions.onDelete) {\n\t\t\t\t\tbuilder.onDelete(actions.onDelete);\n\t\t\t\t}\n\t\t\t\treturn builder.build(table);\n\t\t\t})(ref, actions);\n\t\t});\n\t}\n\n\t/** @internal */\n\tabstract build(\n\t\ttable: AnySQLiteTable<{ name: TTableName }>,\n\t): SQLiteColumn>;\n}\n\n// To understand how to use `SQLiteColumn` and `AnySQLiteColumn`, see `Column` and `AnyColumn` documentation.\nexport abstract class SQLiteColumn<\n\tT extends ColumnBaseConfig = ColumnBaseConfig,\n\tTRuntimeConfig extends object = {},\n\tTTypeConfig extends object = {},\n> extends Column {\n\tstatic override readonly [entityKind]: string = 'SQLiteColumn';\n\n\tconstructor(\n\t\toverride readonly table: SQLiteTable,\n\t\tconfig: ColumnBuilderRuntimeConfig,\n\t) {\n\t\tif (!config.uniqueName) {\n\t\t\tconfig.uniqueName = uniqueKeyName(table, [config.name]);\n\t\t}\n\t\tsuper(table, config);\n\t}\n}\n\nexport type AnySQLiteColumn> = {}> = SQLiteColumn<\n\tRequired, TPartial>>\n>;\n", "import { entityKind } from '~/entity.ts';\nimport { TableName } from '~/table.utils.ts';\nimport type { AnySQLiteColumn, SQLiteColumn } from './columns/index.ts';\nimport type { SQLiteTable } from './table.ts';\n\nexport type UpdateDeleteAction = 'cascade' | 'restrict' | 'no action' | 'set null' | 'set default';\n\nexport type Reference = () => {\n\treadonly name?: string;\n\treadonly columns: SQLiteColumn[];\n\treadonly foreignTable: SQLiteTable;\n\treadonly foreignColumns: SQLiteColumn[];\n};\n\nexport class ForeignKeyBuilder {\n\tstatic readonly [entityKind]: string = 'SQLiteForeignKeyBuilder';\n\n\tdeclare _: {\n\t\tbrand: 'SQLiteForeignKeyBuilder';\n\t\tforeignTableName: 'TForeignTableName';\n\t};\n\n\t/** @internal */\n\treference: Reference;\n\n\t/** @internal */\n\t_onUpdate: UpdateDeleteAction | undefined;\n\n\t/** @internal */\n\t_onDelete: UpdateDeleteAction | undefined;\n\n\tconstructor(\n\t\tconfig: () => {\n\t\t\tname?: string;\n\t\t\tcolumns: SQLiteColumn[];\n\t\t\tforeignColumns: SQLiteColumn[];\n\t\t},\n\t\tactions?: {\n\t\t\tonUpdate?: UpdateDeleteAction;\n\t\t\tonDelete?: UpdateDeleteAction;\n\t\t} | undefined,\n\t) {\n\t\tthis.reference = () => {\n\t\t\tconst { name, columns, foreignColumns } = config();\n\t\t\treturn { name, columns, foreignTable: foreignColumns[0]!.table as SQLiteTable, foreignColumns };\n\t\t};\n\t\tif (actions) {\n\t\t\tthis._onUpdate = actions.onUpdate;\n\t\t\tthis._onDelete = actions.onDelete;\n\t\t}\n\t}\n\n\tonUpdate(action: UpdateDeleteAction): this {\n\t\tthis._onUpdate = action;\n\t\treturn this;\n\t}\n\n\tonDelete(action: UpdateDeleteAction): this {\n\t\tthis._onDelete = action;\n\t\treturn this;\n\t}\n\n\t/** @internal */\n\tbuild(table: SQLiteTable): ForeignKey {\n\t\treturn new ForeignKey(table, this);\n\t}\n}\n\nexport class ForeignKey {\n\tstatic readonly [entityKind]: string = 'SQLiteForeignKey';\n\n\treadonly reference: Reference;\n\treadonly onUpdate: UpdateDeleteAction | undefined;\n\treadonly onDelete: UpdateDeleteAction | undefined;\n\n\tconstructor(readonly table: SQLiteTable, builder: ForeignKeyBuilder) {\n\t\tthis.reference = builder.reference;\n\t\tthis.onUpdate = builder._onUpdate;\n\t\tthis.onDelete = builder._onDelete;\n\t}\n\n\tgetName(): string {\n\t\tconst { name, columns, foreignColumns } = this.reference();\n\t\tconst columnNames = columns.map((column) => column.name);\n\t\tconst foreignColumnNames = foreignColumns.map((column) => column.name);\n\t\tconst chunks = [\n\t\t\tthis.table[TableName],\n\t\t\t...columnNames,\n\t\t\tforeignColumns[0]!.table[TableName],\n\t\t\t...foreignColumnNames,\n\t\t];\n\t\treturn name ?? `${chunks.join('_')}_fk`;\n\t}\n}\n\ntype ColumnsWithTable<\n\tTTableName extends string,\n\tTColumns extends SQLiteColumn[],\n> = { [Key in keyof TColumns]: AnySQLiteColumn<{ tableName: TTableName }> };\n\n/**\n * @deprecated please use `foreignKey({ columns: [], foreignColumns: [] })` syntax without callback\n * @param config\n * @returns\n */\nexport function foreignKey<\n\tTTableName extends string,\n\tTForeignTableName extends string,\n\tTColumns extends [AnySQLiteColumn<{ tableName: TTableName }>, ...AnySQLiteColumn<{ tableName: TTableName }>[]],\n>(\n\tconfig: () => {\n\t\tname?: string;\n\t\tcolumns: TColumns;\n\t\tforeignColumns: ColumnsWithTable;\n\t},\n): ForeignKeyBuilder;\nexport function foreignKey<\n\tTTableName extends string,\n\tTForeignTableName extends string,\n\tTColumns extends [AnySQLiteColumn<{ tableName: TTableName }>, ...AnySQLiteColumn<{ tableName: TTableName }>[]],\n>(\n\tconfig: {\n\t\tname?: string;\n\t\tcolumns: TColumns;\n\t\tforeignColumns: ColumnsWithTable;\n\t},\n): ForeignKeyBuilder;\nexport function foreignKey(\n\tconfig: any,\n): ForeignKeyBuilder {\n\tfunction mappedConfig() {\n\t\tif (typeof config === 'function') {\n\t\t\tconst { name, columns, foreignColumns } = config();\n\t\t\treturn {\n\t\t\t\tname,\n\t\t\t\tcolumns,\n\t\t\t\tforeignColumns,\n\t\t\t};\n\t\t}\n\t\treturn config;\n\t}\n\n\treturn new ForeignKeyBuilder(mappedConfig);\n}\n", "import { entityKind } from '~/entity.ts';\nimport { TableName } from '~/table.utils.ts';\nimport type { SQLiteColumn } from './columns/common.ts';\nimport type { SQLiteTable } from './table.ts';\n\nexport function uniqueKeyName(table: SQLiteTable, columns: string[]) {\n\treturn `${table[TableName]}_${columns.join('_')}_unique`;\n}\n\nexport function unique(name?: string): UniqueOnConstraintBuilder {\n\treturn new UniqueOnConstraintBuilder(name);\n}\n\nexport class UniqueConstraintBuilder {\n\tstatic readonly [entityKind]: string = 'SQLiteUniqueConstraintBuilder';\n\n\t/** @internal */\n\tcolumns: SQLiteColumn[];\n\n\tconstructor(\n\t\tcolumns: SQLiteColumn[],\n\t\tprivate name?: string,\n\t) {\n\t\tthis.columns = columns;\n\t}\n\n\t/** @internal */\n\tbuild(table: SQLiteTable): UniqueConstraint {\n\t\treturn new UniqueConstraint(table, this.columns, this.name);\n\t}\n}\n\nexport class UniqueOnConstraintBuilder {\n\tstatic readonly [entityKind]: string = 'SQLiteUniqueOnConstraintBuilder';\n\n\t/** @internal */\n\tname?: string;\n\n\tconstructor(\n\t\tname?: string,\n\t) {\n\t\tthis.name = name;\n\t}\n\n\ton(...columns: [SQLiteColumn, ...SQLiteColumn[]]) {\n\t\treturn new UniqueConstraintBuilder(columns, this.name);\n\t}\n}\n\nexport class UniqueConstraint {\n\tstatic readonly [entityKind]: string = 'SQLiteUniqueConstraint';\n\n\treadonly columns: SQLiteColumn[];\n\treadonly name?: string;\n\n\tconstructor(readonly table: SQLiteTable, columns: SQLiteColumn[], name?: string) {\n\t\tthis.columns = columns;\n\t\tthis.name = name ?? uniqueKeyName(this.table, this.columns.map((column) => column.name));\n\t}\n\n\tgetName() {\n\t\treturn this.name;\n\t}\n}\n", "import type { ColumnBuilderBaseConfig, ColumnBuilderRuntimeConfig, MakeColumnConfig } from '~/column-builder.ts';\nimport type { ColumnBaseConfig } from '~/column.ts';\nimport { entityKind } from '~/entity.ts';\nimport type { SQL } from '~/sql/sql.ts';\nimport type { AnySQLiteTable } from '~/sqlite-core/table.ts';\nimport { type Equal, getColumnNameAndConfig } from '~/utils.ts';\nimport { SQLiteColumn, SQLiteColumnBuilder } from './common.ts';\n\nexport type ConvertCustomConfig> =\n\t& {\n\t\tname: TName;\n\t\tdataType: 'custom';\n\t\tcolumnType: 'SQLiteCustomColumn';\n\t\tdata: T['data'];\n\t\tdriverParam: T['driverData'];\n\t\tenumValues: undefined;\n\t}\n\t& (T['notNull'] extends true ? { notNull: true } : {})\n\t& (T['default'] extends true ? { hasDefault: true } : {});\n\nexport interface SQLiteCustomColumnInnerConfig {\n\tcustomTypeValues: CustomTypeValues;\n}\n\nexport class SQLiteCustomColumnBuilder>\n\textends SQLiteColumnBuilder<\n\t\tT,\n\t\t{\n\t\t\tfieldConfig: CustomTypeValues['config'];\n\t\t\tcustomTypeParams: CustomTypeParams;\n\t\t},\n\t\t{\n\t\t\tsqliteColumnBuilderBrand: 'SQLiteCustomColumnBuilderBrand';\n\t\t}\n\t>\n{\n\tstatic override readonly [entityKind]: string = 'SQLiteCustomColumnBuilder';\n\n\tconstructor(\n\t\tname: T['name'],\n\t\tfieldConfig: CustomTypeValues['config'],\n\t\tcustomTypeParams: CustomTypeParams,\n\t) {\n\t\tsuper(name, 'custom', 'SQLiteCustomColumn');\n\t\tthis.config.fieldConfig = fieldConfig;\n\t\tthis.config.customTypeParams = customTypeParams;\n\t}\n\n\t/** @internal */\n\tbuild(\n\t\ttable: AnySQLiteTable<{ name: TTableName }>,\n\t): SQLiteCustomColumn> {\n\t\treturn new SQLiteCustomColumn>(\n\t\t\ttable,\n\t\t\tthis.config as ColumnBuilderRuntimeConfig,\n\t\t);\n\t}\n}\n\nexport class SQLiteCustomColumn> extends SQLiteColumn {\n\tstatic override readonly [entityKind]: string = 'SQLiteCustomColumn';\n\n\tprivate sqlName: string;\n\tprivate mapTo?: (value: T['data']) => T['driverParam'];\n\tprivate mapFrom?: (value: T['driverParam']) => T['data'];\n\n\tconstructor(\n\t\ttable: AnySQLiteTable<{ name: T['tableName'] }>,\n\t\tconfig: SQLiteCustomColumnBuilder['config'],\n\t) {\n\t\tsuper(table, config);\n\t\tthis.sqlName = config.customTypeParams.dataType(config.fieldConfig);\n\t\tthis.mapTo = config.customTypeParams.toDriver;\n\t\tthis.mapFrom = config.customTypeParams.fromDriver;\n\t}\n\n\tgetSQLType(): string {\n\t\treturn this.sqlName;\n\t}\n\n\toverride mapFromDriverValue(value: T['driverParam']): T['data'] {\n\t\treturn typeof this.mapFrom === 'function' ? this.mapFrom(value) : value as T['data'];\n\t}\n\n\toverride mapToDriverValue(value: T['data']): T['driverParam'] {\n\t\treturn typeof this.mapTo === 'function' ? this.mapTo(value) : value as T['data'];\n\t}\n}\n\nexport type CustomTypeValues = {\n\t/**\n\t * Required type for custom column, that will infer proper type model\n\t *\n\t * Examples:\n\t *\n\t * If you want your column to be `string` type after selecting/or on inserting - use `data: string`. Like `text`, `varchar`\n\t *\n\t * If you want your column to be `number` type after selecting/or on inserting - use `data: number`. Like `integer`\n\t */\n\tdata: unknown;\n\n\t/**\n\t * Type helper, that represents what type database driver is accepting for specific database data type\n\t */\n\tdriverData?: unknown;\n\n\t/**\n\t * What config type should be used for {@link CustomTypeParams} `dataType` generation\n\t */\n\tconfig?: Record;\n\n\t/**\n\t * Whether the config argument should be required or not\n\t * @default false\n\t */\n\tconfigRequired?: boolean;\n\n\t/**\n\t * If your custom data type should be notNull by default you can use `notNull: true`\n\t *\n\t * @example\n\t * const customSerial = customType<{ data: number, notNull: true, default: true }>({\n\t * \t dataType() {\n\t * \t return 'serial';\n\t * },\n\t * });\n\t */\n\tnotNull?: boolean;\n\n\t/**\n\t * If your custom data type has default you can use `default: true`\n\t *\n\t * @example\n\t * const customSerial = customType<{ data: number, notNull: true, default: true }>({\n\t * \t dataType() {\n\t * \t return 'serial';\n\t * },\n\t * });\n\t */\n\tdefault?: boolean;\n};\n\nexport interface CustomTypeParams {\n\t/**\n\t * Database data type string representation, that is used for migrations\n\t * @example\n\t * ```\n\t * `jsonb`, `text`\n\t * ```\n\t *\n\t * If database data type needs additional params you can use them from `config` param\n\t * @example\n\t * ```\n\t * `varchar(256)`, `numeric(2,3)`\n\t * ```\n\t *\n\t * To make `config` be of specific type please use config generic in {@link CustomTypeValues}\n\t *\n\t * @example\n\t * Usage example\n\t * ```\n\t * dataType() {\n\t * return 'boolean';\n\t * },\n\t * ```\n\t * Or\n\t * ```\n\t * dataType(config) {\n\t * \t return typeof config.length !== 'undefined' ? `varchar(${config.length})` : `varchar`;\n\t * \t }\n\t * ```\n\t */\n\tdataType: (config: T['config'] | (Equal extends true ? never : undefined)) => string;\n\n\t/**\n\t * Optional mapping function, between user input and driver\n\t * @example\n\t * For example, when using jsonb we need to map JS/TS object to string before writing to database\n\t * ```\n\t * toDriver(value: TData): string {\n\t * \t return JSON.stringify(value);\n\t * }\n\t * ```\n\t */\n\ttoDriver?: (value: T['data']) => T['driverData'] | SQL;\n\n\t/**\n\t * Optional mapping function, that is responsible for data mapping from database to JS/TS code\n\t * @example\n\t * For example, when using timestamp we need to map string Date representation to JS Date\n\t * ```\n\t * fromDriver(value: string): Date {\n\t * \treturn new Date(value);\n\t * },\n\t * ```\n\t */\n\tfromDriver?: (value: T['driverData']) => T['data'];\n}\n\n/**\n * Custom sqlite database data type generator\n */\nexport function customType(\n\tcustomTypeParams: CustomTypeParams,\n): Equal extends true ? {\n\t\t & T['config']>(\n\t\t\tfieldConfig: TConfig,\n\t\t): SQLiteCustomColumnBuilder>;\n\t\t(\n\t\t\tdbName: TName,\n\t\t\tfieldConfig: T['config'],\n\t\t): SQLiteCustomColumnBuilder>;\n\t}\n\t: {\n\t\t(): SQLiteCustomColumnBuilder>;\n\t\t & T['config']>(\n\t\t\tfieldConfig?: TConfig,\n\t\t): SQLiteCustomColumnBuilder>;\n\t\t(\n\t\t\tdbName: TName,\n\t\t\tfieldConfig?: T['config'],\n\t\t): SQLiteCustomColumnBuilder>;\n\t}\n{\n\treturn (\n\t\ta?: TName | T['config'],\n\t\tb?: T['config'],\n\t): SQLiteCustomColumnBuilder> => {\n\t\tconst { name, config } = getColumnNameAndConfig(a, b);\n\t\treturn new SQLiteCustomColumnBuilder(\n\t\t\tname as ConvertCustomConfig['name'],\n\t\t\tconfig,\n\t\t\tcustomTypeParams,\n\t\t);\n\t};\n}\n", "import type {\n\tColumnBuilderBaseConfig,\n\tColumnBuilderRuntimeConfig,\n\tColumnDataType,\n\tHasDefault,\n\tIsPrimaryKey,\n\tMakeColumnConfig,\n\tNotNull,\n} from '~/column-builder.ts';\nimport type { ColumnBaseConfig } from '~/column.ts';\nimport { entityKind } from '~/entity.ts';\nimport { sql } from '~/sql/sql.ts';\nimport type { OnConflict } from '~/sqlite-core/utils.ts';\nimport { type Equal, getColumnNameAndConfig, type Or } from '~/utils.ts';\nimport type { AnySQLiteTable } from '../table.ts';\nimport { SQLiteColumn, SQLiteColumnBuilder } from './common.ts';\n\nexport interface PrimaryKeyConfig {\n\tautoIncrement?: boolean;\n\tonConflict?: OnConflict;\n}\n\nexport abstract class SQLiteBaseIntegerBuilder<\n\tT extends ColumnBuilderBaseConfig,\n\tTRuntimeConfig extends object = object,\n> extends SQLiteColumnBuilder<\n\tT,\n\tTRuntimeConfig & { autoIncrement: boolean },\n\t{},\n\t{ primaryKeyHasDefault: true }\n> {\n\tstatic override readonly [entityKind]: string = 'SQLiteBaseIntegerBuilder';\n\n\tconstructor(name: T['name'], dataType: T['dataType'], columnType: T['columnType']) {\n\t\tsuper(name, dataType, columnType);\n\t\tthis.config.autoIncrement = false;\n\t}\n\n\toverride primaryKey(config?: PrimaryKeyConfig): IsPrimaryKey>> {\n\t\tif (config?.autoIncrement) {\n\t\t\tthis.config.autoIncrement = true;\n\t\t}\n\t\tthis.config.hasDefault = true;\n\t\treturn super.primaryKey() as IsPrimaryKey>>;\n\t}\n\n\t/** @internal */\n\tabstract override build(\n\t\ttable: AnySQLiteTable<{ name: TTableName }>,\n\t): SQLiteBaseInteger>;\n}\n\nexport abstract class SQLiteBaseInteger<\n\tT extends ColumnBaseConfig,\n\tTRuntimeConfig extends object = object,\n> extends SQLiteColumn {\n\tstatic override readonly [entityKind]: string = 'SQLiteBaseInteger';\n\n\treadonly autoIncrement: boolean = this.config.autoIncrement;\n\n\tgetSQLType(): string {\n\t\treturn 'integer';\n\t}\n}\n\nexport type SQLiteIntegerBuilderInitial = SQLiteIntegerBuilder<{\n\tname: TName;\n\tdataType: 'number';\n\tcolumnType: 'SQLiteInteger';\n\tdata: number;\n\tdriverParam: number;\n\tenumValues: undefined;\n}>;\n\nexport class SQLiteIntegerBuilder>\n\textends SQLiteBaseIntegerBuilder\n{\n\tstatic override readonly [entityKind]: string = 'SQLiteIntegerBuilder';\n\n\tconstructor(name: T['name']) {\n\t\tsuper(name, 'number', 'SQLiteInteger');\n\t}\n\n\tbuild(\n\t\ttable: AnySQLiteTable<{ name: TTableName }>,\n\t): SQLiteInteger> {\n\t\treturn new SQLiteInteger>(\n\t\t\ttable,\n\t\t\tthis.config as ColumnBuilderRuntimeConfig,\n\t\t);\n\t}\n}\n\nexport class SQLiteInteger> extends SQLiteBaseInteger {\n\tstatic override readonly [entityKind]: string = 'SQLiteInteger';\n}\n\nexport type SQLiteTimestampBuilderInitial = SQLiteTimestampBuilder<{\n\tname: TName;\n\tdataType: 'date';\n\tcolumnType: 'SQLiteTimestamp';\n\tdata: Date;\n\tdriverParam: number;\n\tenumValues: undefined;\n}>;\n\nexport class SQLiteTimestampBuilder>\n\textends SQLiteBaseIntegerBuilder\n{\n\tstatic override readonly [entityKind]: string = 'SQLiteTimestampBuilder';\n\n\tconstructor(name: T['name'], mode: 'timestamp' | 'timestamp_ms') {\n\t\tsuper(name, 'date', 'SQLiteTimestamp');\n\t\tthis.config.mode = mode;\n\t}\n\n\t/**\n\t * @deprecated Use `default()` with your own expression instead.\n\t *\n\t * Adds `DEFAULT (cast((julianday('now') - 2440587.5)*86400000 as integer))` to the column, which is the current epoch timestamp in milliseconds.\n\t */\n\tdefaultNow(): HasDefault {\n\t\treturn this.default(sql`(cast((julianday('now') - 2440587.5)*86400000 as integer))`) as any;\n\t}\n\n\tbuild(\n\t\ttable: AnySQLiteTable<{ name: TTableName }>,\n\t): SQLiteTimestamp> {\n\t\treturn new SQLiteTimestamp>(\n\t\t\ttable,\n\t\t\tthis.config as ColumnBuilderRuntimeConfig,\n\t\t);\n\t}\n}\n\nexport class SQLiteTimestamp>\n\textends SQLiteBaseInteger\n{\n\tstatic override readonly [entityKind]: string = 'SQLiteTimestamp';\n\n\treadonly mode: 'timestamp' | 'timestamp_ms' = this.config.mode;\n\n\toverride mapFromDriverValue(value: number): Date {\n\t\tif (this.config.mode === 'timestamp') {\n\t\t\treturn new Date(value * 1000);\n\t\t}\n\t\treturn new Date(value);\n\t}\n\n\toverride mapToDriverValue(value: Date): number {\n\t\tconst unix = value.getTime();\n\t\tif (this.config.mode === 'timestamp') {\n\t\t\treturn Math.floor(unix / 1000);\n\t\t}\n\t\treturn unix;\n\t}\n}\n\nexport type SQLiteBooleanBuilderInitial = SQLiteBooleanBuilder<{\n\tname: TName;\n\tdataType: 'boolean';\n\tcolumnType: 'SQLiteBoolean';\n\tdata: boolean;\n\tdriverParam: number;\n\tenumValues: undefined;\n}>;\n\nexport class SQLiteBooleanBuilder>\n\textends SQLiteBaseIntegerBuilder\n{\n\tstatic override readonly [entityKind]: string = 'SQLiteBooleanBuilder';\n\n\tconstructor(name: T['name'], mode: 'boolean') {\n\t\tsuper(name, 'boolean', 'SQLiteBoolean');\n\t\tthis.config.mode = mode;\n\t}\n\n\tbuild(\n\t\ttable: AnySQLiteTable<{ name: TTableName }>,\n\t): SQLiteBoolean> {\n\t\treturn new SQLiteBoolean>(\n\t\t\ttable,\n\t\t\tthis.config as ColumnBuilderRuntimeConfig,\n\t\t);\n\t}\n}\n\nexport class SQLiteBoolean>\n\textends SQLiteBaseInteger\n{\n\tstatic override readonly [entityKind]: string = 'SQLiteBoolean';\n\n\treadonly mode: 'boolean' = this.config.mode;\n\n\toverride mapFromDriverValue(value: number): boolean {\n\t\treturn Number(value) === 1;\n\t}\n\n\toverride mapToDriverValue(value: boolean): number {\n\t\treturn value ? 1 : 0;\n\t}\n}\n\nexport interface IntegerConfig<\n\tTMode extends 'number' | 'timestamp' | 'timestamp_ms' | 'boolean' =\n\t\t| 'number'\n\t\t| 'timestamp'\n\t\t| 'timestamp_ms'\n\t\t| 'boolean',\n> {\n\tmode: TMode;\n}\n\nexport function integer(): SQLiteIntegerBuilderInitial<''>;\nexport function integer(\n\tconfig?: IntegerConfig,\n): Or, Equal> extends true ? SQLiteTimestampBuilderInitial<''>\n\t: Equal extends true ? SQLiteBooleanBuilderInitial<''>\n\t: SQLiteIntegerBuilderInitial<''>;\nexport function integer(\n\tname: TName,\n\tconfig?: IntegerConfig,\n): Or, Equal> extends true ? SQLiteTimestampBuilderInitial\n\t: Equal extends true ? SQLiteBooleanBuilderInitial\n\t: SQLiteIntegerBuilderInitial;\nexport function integer(a?: string | IntegerConfig, b?: IntegerConfig) {\n\tconst { name, config } = getColumnNameAndConfig(a, b);\n\tif (config?.mode === 'timestamp' || config?.mode === 'timestamp_ms') {\n\t\treturn new SQLiteTimestampBuilder(name, config.mode);\n\t}\n\tif (config?.mode === 'boolean') {\n\t\treturn new SQLiteBooleanBuilder(name, config.mode);\n\t}\n\treturn new SQLiteIntegerBuilder(name);\n}\n\nexport const int = integer;\n", "import type { ColumnBuilderBaseConfig, ColumnBuilderRuntimeConfig, MakeColumnConfig } from '~/column-builder.ts';\nimport type { ColumnBaseConfig } from '~/column.ts';\nimport { entityKind } from '~/entity.ts';\nimport type { AnySQLiteTable } from '~/sqlite-core/table.ts';\nimport { type Equal, getColumnNameAndConfig } from '~/utils.ts';\nimport { SQLiteColumn, SQLiteColumnBuilder } from './common.ts';\n\nexport type SQLiteNumericBuilderInitial = SQLiteNumericBuilder<{\n\tname: TName;\n\tdataType: 'string';\n\tcolumnType: 'SQLiteNumeric';\n\tdata: string;\n\tdriverParam: string;\n\tenumValues: undefined;\n}>;\n\nexport class SQLiteNumericBuilder>\n\textends SQLiteColumnBuilder\n{\n\tstatic override readonly [entityKind]: string = 'SQLiteNumericBuilder';\n\n\tconstructor(name: T['name']) {\n\t\tsuper(name, 'string', 'SQLiteNumeric');\n\t}\n\n\t/** @internal */\n\toverride build(\n\t\ttable: AnySQLiteTable<{ name: TTableName }>,\n\t): SQLiteNumeric> {\n\t\treturn new SQLiteNumeric>(\n\t\t\ttable,\n\t\t\tthis.config as ColumnBuilderRuntimeConfig,\n\t\t);\n\t}\n}\n\nexport class SQLiteNumeric> extends SQLiteColumn {\n\tstatic override readonly [entityKind]: string = 'SQLiteNumeric';\n\n\toverride mapFromDriverValue(value: unknown): string {\n\t\tif (typeof value === 'string') return value;\n\n\t\treturn String(value);\n\t}\n\n\tgetSQLType(): string {\n\t\treturn 'numeric';\n\t}\n}\n\nexport type SQLiteNumericNumberBuilderInitial = SQLiteNumericNumberBuilder<{\n\tname: TName;\n\tdataType: 'number';\n\tcolumnType: 'SQLiteNumericNumber';\n\tdata: number;\n\tdriverParam: string;\n\tenumValues: undefined;\n}>;\n\nexport class SQLiteNumericNumberBuilder>\n\textends SQLiteColumnBuilder\n{\n\tstatic override readonly [entityKind]: string = 'SQLiteNumericNumberBuilder';\n\n\tconstructor(name: T['name']) {\n\t\tsuper(name, 'number', 'SQLiteNumericNumber');\n\t}\n\n\t/** @internal */\n\toverride build(\n\t\ttable: AnySQLiteTable<{ name: TTableName }>,\n\t): SQLiteNumericNumber> {\n\t\treturn new SQLiteNumericNumber>(\n\t\t\ttable,\n\t\t\tthis.config as ColumnBuilderRuntimeConfig,\n\t\t);\n\t}\n}\n\nexport class SQLiteNumericNumber> extends SQLiteColumn {\n\tstatic override readonly [entityKind]: string = 'SQLiteNumericNumber';\n\n\toverride mapFromDriverValue(value: unknown): number {\n\t\tif (typeof value === 'number') return value;\n\n\t\treturn Number(value);\n\t}\n\n\toverride mapToDriverValue = String;\n\n\tgetSQLType(): string {\n\t\treturn 'numeric';\n\t}\n}\n\nexport type SQLiteNumericBigIntBuilderInitial = SQLiteNumericBigIntBuilder<{\n\tname: TName;\n\tdataType: 'bigint';\n\tcolumnType: 'SQLiteNumericBigInt';\n\tdata: bigint;\n\tdriverParam: string;\n\tenumValues: undefined;\n}>;\n\nexport class SQLiteNumericBigIntBuilder>\n\textends SQLiteColumnBuilder\n{\n\tstatic override readonly [entityKind]: string = 'SQLiteNumericBigIntBuilder';\n\n\tconstructor(name: T['name']) {\n\t\tsuper(name, 'bigint', 'SQLiteNumericBigInt');\n\t}\n\n\t/** @internal */\n\toverride build(\n\t\ttable: AnySQLiteTable<{ name: TTableName }>,\n\t): SQLiteNumericBigInt> {\n\t\treturn new SQLiteNumericBigInt>(\n\t\t\ttable,\n\t\t\tthis.config as ColumnBuilderRuntimeConfig,\n\t\t);\n\t}\n}\n\nexport class SQLiteNumericBigInt> extends SQLiteColumn {\n\tstatic override readonly [entityKind]: string = 'SQLiteNumericBigInt';\n\n\toverride mapFromDriverValue = BigInt;\n\n\toverride mapToDriverValue = String;\n\n\tgetSQLType(): string {\n\t\treturn 'numeric';\n\t}\n}\n\nexport type SQLiteNumericConfig = {\n\tmode: T;\n};\n\nexport function numeric(\n\tconfig?: SQLiteNumericConfig,\n): Equal extends true ? SQLiteNumericNumberBuilderInitial<''>\n\t: Equal extends true ? SQLiteNumericBigIntBuilderInitial<''>\n\t: SQLiteNumericBuilderInitial<''>;\nexport function numeric(\n\tname: TName,\n\tconfig?: SQLiteNumericConfig,\n): Equal extends true ? SQLiteNumericNumberBuilderInitial\n\t: Equal extends true ? SQLiteNumericBigIntBuilderInitial\n\t: SQLiteNumericBuilderInitial;\nexport function numeric(a?: string | SQLiteNumericConfig, b?: SQLiteNumericConfig) {\n\tconst { name, config } = getColumnNameAndConfig(a, b);\n\tconst mode = config?.mode;\n\treturn mode === 'number'\n\t\t? new SQLiteNumericNumberBuilder(name)\n\t\t: mode === 'bigint'\n\t\t? new SQLiteNumericBigIntBuilder(name)\n\t\t: new SQLiteNumericBuilder(name);\n}\n", "import type { ColumnBuilderBaseConfig, ColumnBuilderRuntimeConfig, MakeColumnConfig } from '~/column-builder.ts';\nimport type { ColumnBaseConfig } from '~/column.ts';\nimport { entityKind } from '~/entity.ts';\nimport type { AnySQLiteTable } from '../table.ts';\nimport { SQLiteColumn, SQLiteColumnBuilder } from './common.ts';\n\nexport type SQLiteRealBuilderInitial = SQLiteRealBuilder<{\n\tname: TName;\n\tdataType: 'number';\n\tcolumnType: 'SQLiteReal';\n\tdata: number;\n\tdriverParam: number;\n\tenumValues: undefined;\n}>;\n\nexport class SQLiteRealBuilder>\n\textends SQLiteColumnBuilder\n{\n\tstatic override readonly [entityKind]: string = 'SQLiteRealBuilder';\n\n\tconstructor(name: T['name']) {\n\t\tsuper(name, 'number', 'SQLiteReal');\n\t}\n\n\t/** @internal */\n\toverride build(\n\t\ttable: AnySQLiteTable<{ name: TTableName }>,\n\t): SQLiteReal> {\n\t\treturn new SQLiteReal>(table, this.config as ColumnBuilderRuntimeConfig);\n\t}\n}\n\nexport class SQLiteReal> extends SQLiteColumn {\n\tstatic override readonly [entityKind]: string = 'SQLiteReal';\n\n\tgetSQLType(): string {\n\t\treturn 'real';\n\t}\n}\n\nexport function real(): SQLiteRealBuilderInitial<''>;\nexport function real(name: TName): SQLiteRealBuilderInitial;\nexport function real(name?: string) {\n\treturn new SQLiteRealBuilder(name ?? '');\n}\n", "import type { ColumnBuilderBaseConfig, ColumnBuilderRuntimeConfig, MakeColumnConfig } from '~/column-builder.ts';\nimport type { ColumnBaseConfig } from '~/column.ts';\nimport { entityKind } from '~/entity.ts';\nimport type { AnySQLiteTable } from '~/sqlite-core/table.ts';\nimport { type Equal, getColumnNameAndConfig, type Writable } from '~/utils.ts';\nimport { SQLiteColumn, SQLiteColumnBuilder } from './common.ts';\n\nexport type SQLiteTextBuilderInitial<\n\tTName extends string,\n\tTEnum extends [string, ...string[]],\n\tTLength extends number | undefined,\n> = SQLiteTextBuilder<{\n\tname: TName;\n\tdataType: 'string';\n\tcolumnType: 'SQLiteText';\n\tdata: TEnum[number];\n\tdriverParam: string;\n\tenumValues: TEnum;\n\tlength: TLength;\n}>;\n\nexport class SQLiteTextBuilder<\n\tT extends ColumnBuilderBaseConfig<'string', 'SQLiteText'> & { length?: number | undefined },\n> extends SQLiteColumnBuilder<\n\tT,\n\t{ length: T['length']; enumValues: T['enumValues'] },\n\t{ length: T['length'] }\n> {\n\tstatic override readonly [entityKind]: string = 'SQLiteTextBuilder';\n\n\tconstructor(name: T['name'], config: SQLiteTextConfig<'text', T['enumValues'], T['length']>) {\n\t\tsuper(name, 'string', 'SQLiteText');\n\t\tthis.config.enumValues = config.enum;\n\t\tthis.config.length = config.length;\n\t}\n\n\t/** @internal */\n\toverride build(\n\t\ttable: AnySQLiteTable<{ name: TTableName }>,\n\t): SQLiteText & { length: T['length'] }> {\n\t\treturn new SQLiteText & { length: T['length'] }>(\n\t\t\ttable,\n\t\t\tthis.config as ColumnBuilderRuntimeConfig,\n\t\t);\n\t}\n}\n\nexport class SQLiteText & { length?: number | undefined }>\n\textends SQLiteColumn\n{\n\tstatic override readonly [entityKind]: string = 'SQLiteText';\n\n\toverride readonly enumValues = this.config.enumValues;\n\n\treadonly length: T['length'] = this.config.length;\n\n\tconstructor(\n\t\ttable: AnySQLiteTable<{ name: T['tableName'] }>,\n\t\tconfig: SQLiteTextBuilder['config'],\n\t) {\n\t\tsuper(table, config);\n\t}\n\n\tgetSQLType(): string {\n\t\treturn `text${this.config.length ? `(${this.config.length})` : ''}`;\n\t}\n}\n\nexport type SQLiteTextJsonBuilderInitial = SQLiteTextJsonBuilder<{\n\tname: TName;\n\tdataType: 'json';\n\tcolumnType: 'SQLiteTextJson';\n\tdata: unknown;\n\tdriverParam: string;\n\tenumValues: undefined;\n\tgenerated: undefined;\n}>;\n\nexport class SQLiteTextJsonBuilder>\n\textends SQLiteColumnBuilder\n{\n\tstatic override readonly [entityKind]: string = 'SQLiteTextJsonBuilder';\n\n\tconstructor(name: T['name']) {\n\t\tsuper(name, 'json', 'SQLiteTextJson');\n\t}\n\n\t/** @internal */\n\toverride build(\n\t\ttable: AnySQLiteTable<{ name: TTableName }>,\n\t): SQLiteTextJson> {\n\t\treturn new SQLiteTextJson>(\n\t\t\ttable,\n\t\t\tthis.config as ColumnBuilderRuntimeConfig,\n\t\t);\n\t}\n}\n\nexport class SQLiteTextJson>\n\textends SQLiteColumn\n{\n\tstatic override readonly [entityKind]: string = 'SQLiteTextJson';\n\n\tgetSQLType(): string {\n\t\treturn 'text';\n\t}\n\n\toverride mapFromDriverValue(value: string): T['data'] {\n\t\treturn JSON.parse(value);\n\t}\n\n\toverride mapToDriverValue(value: T['data']): string {\n\t\treturn JSON.stringify(value);\n\t}\n}\n\nexport type SQLiteTextConfig<\n\tTMode extends 'text' | 'json' = 'text' | 'json',\n\tTEnum extends readonly string[] | string[] | undefined = readonly string[] | string[] | undefined,\n\tTLength extends number | undefined = number | undefined,\n> = TMode extends 'text' ? {\n\t\tmode?: TMode;\n\t\tlength?: TLength;\n\t\tenum?: TEnum;\n\t}\n\t: {\n\t\tmode?: TMode;\n\t};\n\nexport function text(): SQLiteTextBuilderInitial<'', [string, ...string[]], undefined>;\nexport function text<\n\tU extends string,\n\tT extends Readonly<[U, ...U[]]>,\n\tL extends number | undefined,\n\tTMode extends 'text' | 'json' = 'text' | 'json',\n>(\n\tconfig?: SQLiteTextConfig, L>,\n): Equal extends true ? SQLiteTextJsonBuilderInitial<''>\n\t: SQLiteTextBuilderInitial<'', Writable, L>;\nexport function text<\n\tTName extends string,\n\tU extends string,\n\tT extends Readonly<[U, ...U[]]>,\n\tL extends number | undefined,\n\tTMode extends 'text' | 'json' = 'text' | 'json',\n>(\n\tname: TName,\n\tconfig?: SQLiteTextConfig, L>,\n): Equal extends true ? SQLiteTextJsonBuilderInitial\n\t: SQLiteTextBuilderInitial, L>;\nexport function text(a?: string | SQLiteTextConfig, b: SQLiteTextConfig = {}): any {\n\tconst { name, config } = getColumnNameAndConfig(a, b);\n\tif (config.mode === 'json') {\n\t\treturn new SQLiteTextJsonBuilder(name);\n\t}\n\treturn new SQLiteTextBuilder(name, config as any);\n}\n", "import { is } from '~/entity.ts';\nimport { SQL } from '~/sql/sql.ts';\nimport { Subquery } from '~/subquery.ts';\nimport { Table } from '~/table.ts';\nimport { ViewBaseConfig } from '~/view-common.ts';\nimport type { Check } from './checks.ts';\nimport { CheckBuilder } from './checks.ts';\nimport type { ForeignKey } from './foreign-keys.ts';\nimport { ForeignKeyBuilder } from './foreign-keys.ts';\nimport type { Index } from './indexes.ts';\nimport { IndexBuilder } from './indexes.ts';\nimport type { PrimaryKey } from './primary-keys.ts';\nimport { PrimaryKeyBuilder } from './primary-keys.ts';\nimport { SQLiteTable } from './table.ts';\nimport { type UniqueConstraint, UniqueConstraintBuilder } from './unique-constraint.ts';\nimport type { SQLiteViewBase } from './view-base.ts';\nimport type { SQLiteView } from './view.ts';\n\nexport function getTableConfig(table: TTable) {\n\tconst columns = Object.values(table[SQLiteTable.Symbol.Columns]);\n\tconst indexes: Index[] = [];\n\tconst checks: Check[] = [];\n\tconst primaryKeys: PrimaryKey[] = [];\n\tconst uniqueConstraints: UniqueConstraint[] = [];\n\tconst foreignKeys: ForeignKey[] = Object.values(table[SQLiteTable.Symbol.InlineForeignKeys]);\n\tconst name = table[Table.Symbol.Name];\n\n\tconst extraConfigBuilder = table[SQLiteTable.Symbol.ExtraConfigBuilder];\n\n\tif (extraConfigBuilder !== undefined) {\n\t\tconst extraConfig = extraConfigBuilder(table[SQLiteTable.Symbol.Columns]);\n\t\tconst extraValues = Array.isArray(extraConfig) ? extraConfig.flat(1) as any[] : Object.values(extraConfig);\n\t\tfor (const builder of Object.values(extraValues)) {\n\t\t\tif (is(builder, IndexBuilder)) {\n\t\t\t\tindexes.push(builder.build(table));\n\t\t\t} else if (is(builder, CheckBuilder)) {\n\t\t\t\tchecks.push(builder.build(table));\n\t\t\t} else if (is(builder, UniqueConstraintBuilder)) {\n\t\t\t\tuniqueConstraints.push(builder.build(table));\n\t\t\t} else if (is(builder, PrimaryKeyBuilder)) {\n\t\t\t\tprimaryKeys.push(builder.build(table));\n\t\t\t} else if (is(builder, ForeignKeyBuilder)) {\n\t\t\t\tforeignKeys.push(builder.build(table));\n\t\t\t}\n\t\t}\n\t}\n\n\treturn {\n\t\tcolumns,\n\t\tindexes,\n\t\tforeignKeys,\n\t\tchecks,\n\t\tprimaryKeys,\n\t\tuniqueConstraints,\n\t\tname,\n\t};\n}\n\nexport function extractUsedTable(table: SQLiteTable | Subquery | SQLiteViewBase | SQL): string[] {\n\tif (is(table, SQLiteTable)) {\n\t\treturn [`${table[Table.Symbol.BaseName]}`];\n\t}\n\tif (is(table, Subquery)) {\n\t\treturn table._.usedTables ?? [];\n\t}\n\tif (is(table, SQL)) {\n\t\treturn table.usedTables ?? [];\n\t}\n\treturn [];\n}\n\nexport type OnConflict = 'rollback' | 'abort' | 'fail' | 'ignore' | 'replace';\n\nexport function getViewConfig<\n\tTName extends string = string,\n\tTExisting extends boolean = boolean,\n>(view: SQLiteView) {\n\treturn {\n\t\t...view[ViewBaseConfig],\n\t\t// ...view[SQLiteViewConfig],\n\t};\n}\n", "import { entityKind, is } from '~/entity.ts';\nimport type { TypedQueryBuilder } from '~/query-builders/query-builder.ts';\nimport type { SelectResultFields } from '~/query-builders/select.types.ts';\nimport { QueryPromise } from '~/query-promise.ts';\nimport type { RunnableQuery } from '~/runnable-query.ts';\nimport type { Placeholder, Query, SQLWrapper } from '~/sql/sql.ts';\nimport { Param, SQL, sql } from '~/sql/sql.ts';\nimport type { SQLiteDialect } from '~/sqlite-core/dialect.ts';\nimport type { IndexColumn } from '~/sqlite-core/indexes.ts';\nimport type { SQLitePreparedQuery, SQLiteSession } from '~/sqlite-core/session.ts';\nimport { SQLiteTable } from '~/sqlite-core/table.ts';\nimport type { Subquery } from '~/subquery.ts';\nimport { Columns, Table } from '~/table.ts';\nimport { type DrizzleTypeError, haveSameKeys, mapUpdateSet, orderSelectedFields, type Simplify } from '~/utils.ts';\nimport type { AnySQLiteColumn, SQLiteColumn } from '../columns/common.ts';\nimport { extractUsedTable } from '../utils.ts';\nimport { QueryBuilder } from './query-builder.ts';\nimport type { SelectedFieldsFlat, SelectedFieldsOrdered } from './select.types.ts';\nimport type { SQLiteUpdateSetSource } from './update.ts';\n\nexport interface SQLiteInsertConfig {\n\ttable: TTable;\n\tvalues: Record[] | SQLiteInsertSelectQueryBuilder | SQL;\n\twithList?: Subquery[];\n\tonConflict?: SQL[];\n\treturning?: SelectedFieldsOrdered;\n\tselect?: boolean;\n}\n\nexport type SQLiteInsertValue = Simplify<\n\t{\n\t\t[Key in keyof TTable['$inferInsert']]: TTable['$inferInsert'][Key] | SQL | Placeholder;\n\t}\n>;\n\nexport type SQLiteInsertSelectQueryBuilder = TypedQueryBuilder<\n\t{ [K in keyof TTable['$inferInsert']]: AnySQLiteColumn | SQL | SQL.Aliased | TTable['$inferInsert'][K] }\n>;\n\nexport class SQLiteInsertBuilder<\n\tTTable extends SQLiteTable,\n\tTResultType extends 'sync' | 'async',\n\tTRunResult,\n> {\n\tstatic readonly [entityKind]: string = 'SQLiteInsertBuilder';\n\n\tconstructor(\n\t\tprotected table: TTable,\n\t\tprotected session: SQLiteSession,\n\t\tprotected dialect: SQLiteDialect,\n\t\tprivate withList?: Subquery[],\n\t) {}\n\n\tvalues(value: SQLiteInsertValue): SQLiteInsertBase;\n\tvalues(values: SQLiteInsertValue[]): SQLiteInsertBase;\n\tvalues(\n\t\tvalues: SQLiteInsertValue | SQLiteInsertValue[],\n\t): SQLiteInsertBase {\n\t\tvalues = Array.isArray(values) ? values : [values];\n\t\tif (values.length === 0) {\n\t\t\tthrow new Error('values() must be called with at least one value');\n\t\t}\n\t\tconst mappedValues = values.map((entry) => {\n\t\t\tconst result: Record = {};\n\t\t\tconst cols = this.table[Table.Symbol.Columns];\n\t\t\tfor (const colKey of Object.keys(entry)) {\n\t\t\t\tconst colValue = entry[colKey as keyof typeof entry];\n\t\t\t\tresult[colKey] = is(colValue, SQL) ? colValue : new Param(colValue, cols[colKey]);\n\t\t\t}\n\t\t\treturn result;\n\t\t});\n\n\t\t// if (mappedValues.length > 1 && mappedValues.some((t) => Object.keys(t).length === 0)) {\n\t\t// \tthrow new Error(\n\t\t// \t\t`One of the values you want to insert is empty. In SQLite you can insert only one empty object per statement. For this case Drizzle with use \"INSERT INTO ... DEFAULT VALUES\" syntax`,\n\t\t// \t);\n\t\t// }\n\n\t\treturn new SQLiteInsertBase(this.table, mappedValues, this.session, this.dialect, this.withList);\n\t}\n\n\tselect(\n\t\tselectQuery: (qb: QueryBuilder) => SQLiteInsertSelectQueryBuilder,\n\t): SQLiteInsertBase;\n\tselect(selectQuery: (qb: QueryBuilder) => SQL): SQLiteInsertBase;\n\tselect(selectQuery: SQL): SQLiteInsertBase;\n\tselect(selectQuery: SQLiteInsertSelectQueryBuilder): SQLiteInsertBase;\n\tselect(\n\t\tselectQuery:\n\t\t\t| SQL\n\t\t\t| SQLiteInsertSelectQueryBuilder\n\t\t\t| ((qb: QueryBuilder) => SQLiteInsertSelectQueryBuilder | SQL),\n\t): SQLiteInsertBase {\n\t\tconst select = typeof selectQuery === 'function' ? selectQuery(new QueryBuilder()) : selectQuery;\n\n\t\tif (\n\t\t\t!is(select, SQL)\n\t\t\t&& !haveSameKeys(this.table[Columns], select._.selectedFields)\n\t\t) {\n\t\t\tthrow new Error(\n\t\t\t\t'Insert select error: selected fields are not the same or are in a different order compared to the table definition',\n\t\t\t);\n\t\t}\n\n\t\treturn new SQLiteInsertBase(this.table, select, this.session, this.dialect, this.withList, true);\n\t}\n}\n\nexport type SQLiteInsertWithout =\n\tTDynamic extends true ? T\n\t\t: Omit<\n\t\t\tSQLiteInsertBase<\n\t\t\t\tT['_']['table'],\n\t\t\t\tT['_']['resultType'],\n\t\t\t\tT['_']['runResult'],\n\t\t\t\tT['_']['returning'],\n\t\t\t\tTDynamic,\n\t\t\t\tT['_']['excludedMethods'] | K\n\t\t\t>,\n\t\t\tT['_']['excludedMethods'] | K\n\t\t>;\n\nexport type SQLiteInsertReturning<\n\tT extends AnySQLiteInsert,\n\tTDynamic extends boolean,\n\tTSelectedFields extends SelectedFieldsFlat,\n> = SQLiteInsertWithout<\n\tSQLiteInsertBase<\n\t\tT['_']['table'],\n\t\tT['_']['resultType'],\n\t\tT['_']['runResult'],\n\t\tSelectResultFields,\n\t\tTDynamic,\n\t\tT['_']['excludedMethods']\n\t>,\n\tTDynamic,\n\t'returning'\n>;\n\nexport type SQLiteInsertReturningAll<\n\tT extends AnySQLiteInsert,\n\tTDynamic extends boolean,\n> = SQLiteInsertWithout<\n\tSQLiteInsertBase<\n\t\tT['_']['table'],\n\t\tT['_']['resultType'],\n\t\tT['_']['runResult'],\n\t\tT['_']['table']['$inferSelect'],\n\t\tTDynamic,\n\t\tT['_']['excludedMethods']\n\t>,\n\tTDynamic,\n\t'returning'\n>;\n\nexport type SQLiteInsertOnConflictDoUpdateConfig = {\n\ttarget: IndexColumn | IndexColumn[];\n\t/** @deprecated - use either `targetWhere` or `setWhere` */\n\twhere?: SQL;\n\t// TODO: add tests for targetWhere and setWhere\n\ttargetWhere?: SQL;\n\tsetWhere?: SQL;\n\tset: SQLiteUpdateSetSource;\n};\n\nexport type SQLiteInsertDynamic = SQLiteInsert<\n\tT['_']['table'],\n\tT['_']['resultType'],\n\tT['_']['runResult'],\n\tT['_']['returning']\n>;\n\nexport type SQLiteInsertExecute = T['_']['returning'] extends undefined ? T['_']['runResult']\n\t: T['_']['returning'][];\n\nexport type SQLiteInsertPrepare = SQLitePreparedQuery<\n\t{\n\t\ttype: T['_']['resultType'];\n\t\trun: T['_']['runResult'];\n\t\tall: T['_']['returning'] extends undefined ? DrizzleTypeError<'.all() cannot be used without .returning()'>\n\t\t\t: T['_']['returning'][];\n\t\tget: T['_']['returning'] extends undefined ? DrizzleTypeError<'.get() cannot be used without .returning()'>\n\t\t\t: T['_']['returning'];\n\t\tvalues: T['_']['returning'] extends undefined ? DrizzleTypeError<'.values() cannot be used without .returning()'>\n\t\t\t: any[][];\n\t\texecute: SQLiteInsertExecute;\n\t}\n>;\n\nexport type AnySQLiteInsert = SQLiteInsertBase;\n\nexport type SQLiteInsert<\n\tTTable extends SQLiteTable = SQLiteTable,\n\tTResultType extends 'sync' | 'async' = 'sync' | 'async',\n\tTRunResult = unknown,\n\tTReturning = any,\n> = SQLiteInsertBase;\n\nexport interface SQLiteInsertBase<\n\tTTable extends SQLiteTable,\n\tTResultType extends 'sync' | 'async',\n\tTRunResult,\n\tTReturning = undefined,\n\tTDynamic extends boolean = false,\n\tTExcludedMethods extends string = never,\n> extends\n\tSQLWrapper,\n\tQueryPromise,\n\tRunnableQuery\n{\n\treadonly _: {\n\t\treadonly dialect: 'sqlite';\n\t\treadonly table: TTable;\n\t\treadonly resultType: TResultType;\n\t\treadonly runResult: TRunResult;\n\t\treadonly returning: TReturning;\n\t\treadonly dynamic: TDynamic;\n\t\treadonly excludedMethods: TExcludedMethods;\n\t\treadonly result: TReturning extends undefined ? TRunResult : TReturning[];\n\t};\n}\n\nexport class SQLiteInsertBase<\n\tTTable extends SQLiteTable,\n\t// eslint-disable-next-line @typescript-eslint/no-unused-vars\n\tTResultType extends 'sync' | 'async',\n\tTRunResult,\n\tTReturning = undefined,\n\t// eslint-disable-next-line @typescript-eslint/no-unused-vars\n\tTDynamic extends boolean = false,\n\t// eslint-disable-next-line @typescript-eslint/no-unused-vars\n\tTExcludedMethods extends string = never,\n> extends QueryPromise\n\timplements RunnableQuery, SQLWrapper\n{\n\tstatic override readonly [entityKind]: string = 'SQLiteInsert';\n\n\t/** @internal */\n\tconfig: SQLiteInsertConfig;\n\n\tconstructor(\n\t\ttable: TTable,\n\t\tvalues: SQLiteInsertConfig['values'],\n\t\tprivate session: SQLiteSession,\n\t\tprivate dialect: SQLiteDialect,\n\t\twithList?: Subquery[],\n\t\tselect?: boolean,\n\t) {\n\t\tsuper();\n\t\tthis.config = { table, values: values as any, withList, select };\n\t}\n\n\t/**\n\t * Adds a `returning` clause to the query.\n\t *\n\t * Calling this method will return the specified fields of the inserted rows. If no fields are specified, all fields will be returned.\n\t *\n\t * See docs: {@link https://orm.drizzle.team/docs/insert#insert-returning}\n\t *\n\t * @example\n\t * ```ts\n\t * // Insert one row and return all fields\n\t * const insertedCar: Car[] = await db.insert(cars)\n\t * .values({ brand: 'BMW' })\n\t * .returning();\n\t *\n\t * // Insert one row and return only the id\n\t * const insertedCarId: { id: number }[] = await db.insert(cars)\n\t * .values({ brand: 'BMW' })\n\t * .returning({ id: cars.id });\n\t * ```\n\t */\n\treturning(): SQLiteInsertReturningAll;\n\treturning(\n\t\tfields: TSelectedFields,\n\t): SQLiteInsertReturning;\n\treturning(\n\t\tfields: SelectedFieldsFlat = this.config.table[SQLiteTable.Symbol.Columns],\n\t): SQLiteInsertWithout {\n\t\tthis.config.returning = orderSelectedFields(fields);\n\t\treturn this as any;\n\t}\n\n\t/**\n\t * Adds an `on conflict do nothing` clause to the query.\n\t *\n\t * Calling this method simply avoids inserting a row as its alternative action.\n\t *\n\t * See docs: {@link https://orm.drizzle.team/docs/insert#on-conflict-do-nothing}\n\t *\n\t * @param config The `target` and `where` clauses.\n\t *\n\t * @example\n\t * ```ts\n\t * // Insert one row and cancel the insert if there's a conflict\n\t * await db.insert(cars)\n\t * .values({ id: 1, brand: 'BMW' })\n\t * .onConflictDoNothing();\n\t *\n\t * // Explicitly specify conflict target\n\t * await db.insert(cars)\n\t * .values({ id: 1, brand: 'BMW' })\n\t * .onConflictDoNothing({ target: cars.id });\n\t * ```\n\t */\n\tonConflictDoNothing(config: { target?: IndexColumn | IndexColumn[]; where?: SQL } = {}): this {\n\t\tif (!this.config.onConflict) this.config.onConflict = [];\n\n\t\tif (config.target === undefined) {\n\t\t\tthis.config.onConflict.push(sql` on conflict do nothing`);\n\t\t} else {\n\t\t\tconst targetSql = Array.isArray(config.target) ? sql`${config.target}` : sql`${[config.target]}`;\n\t\t\tconst whereSql = config.where ? sql` where ${config.where}` : sql``;\n\t\t\tthis.config.onConflict.push(sql` on conflict ${targetSql} do nothing${whereSql}`);\n\t\t}\n\t\treturn this;\n\t}\n\n\t/**\n\t * Adds an `on conflict do update` clause to the query.\n\t *\n\t * Calling this method will update the existing row that conflicts with the row proposed for insertion as its alternative action.\n\t *\n\t * See docs: {@link https://orm.drizzle.team/docs/insert#upserts-and-conflicts}\n\t *\n\t * @param config The `target`, `set` and `where` clauses.\n\t *\n\t * @example\n\t * ```ts\n\t * // Update the row if there's a conflict\n\t * await db.insert(cars)\n\t * .values({ id: 1, brand: 'BMW' })\n\t * .onConflictDoUpdate({\n\t * target: cars.id,\n\t * set: { brand: 'Porsche' }\n\t * });\n\t *\n\t * // Upsert with 'where' clause\n\t * await db.insert(cars)\n\t * .values({ id: 1, brand: 'BMW' })\n\t * .onConflictDoUpdate({\n\t * target: cars.id,\n\t * set: { brand: 'newBMW' },\n\t * where: sql`${cars.createdAt} > '2023-01-01'::date`,\n\t * });\n\t * ```\n\t */\n\tonConflictDoUpdate(config: SQLiteInsertOnConflictDoUpdateConfig): this {\n\t\tif (config.where && (config.targetWhere || config.setWhere)) {\n\t\t\tthrow new Error(\n\t\t\t\t'You cannot use both \"where\" and \"targetWhere\"/\"setWhere\" at the same time - \"where\" is deprecated, use \"targetWhere\" or \"setWhere\" instead.',\n\t\t\t);\n\t\t}\n\n\t\tif (!this.config.onConflict) this.config.onConflict = [];\n\n\t\tconst whereSql = config.where ? sql` where ${config.where}` : undefined;\n\t\tconst targetWhereSql = config.targetWhere ? sql` where ${config.targetWhere}` : undefined;\n\t\tconst setWhereSql = config.setWhere ? sql` where ${config.setWhere}` : undefined;\n\t\tconst targetSql = Array.isArray(config.target) ? sql`${config.target}` : sql`${[config.target]}`;\n\t\tconst setSql = this.dialect.buildUpdateSet(this.config.table, mapUpdateSet(this.config.table, config.set));\n\t\tthis.config.onConflict.push(\n\t\t\tsql` on conflict ${targetSql}${targetWhereSql} do update set ${setSql}${whereSql}${setWhereSql}`,\n\t\t);\n\t\treturn this;\n\t}\n\n\t/** @internal */\n\tgetSQL(): SQL {\n\t\treturn this.dialect.buildInsertQuery(this.config);\n\t}\n\n\ttoSQL(): Query {\n\t\tconst { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());\n\t\treturn rest;\n\t}\n\n\t/** @internal */\n\t_prepare(isOneTimeQuery = true): SQLiteInsertPrepare {\n\t\treturn this.session[isOneTimeQuery ? 'prepareOneTimeQuery' : 'prepareQuery'](\n\t\t\tthis.dialect.sqlToQuery(this.getSQL()),\n\t\t\tthis.config.returning,\n\t\t\tthis.config.returning ? 'all' : 'run',\n\t\t\ttrue,\n\t\t\tundefined,\n\t\t\t{\n\t\t\t\ttype: 'insert',\n\t\t\t\ttables: extractUsedTable(this.config.table),\n\t\t\t},\n\t\t) as SQLiteInsertPrepare;\n\t}\n\n\tprepare(): SQLiteInsertPrepare {\n\t\treturn this._prepare(false);\n\t}\n\n\trun: ReturnType['run'] = (placeholderValues) => {\n\t\treturn this._prepare().run(placeholderValues);\n\t};\n\n\tall: ReturnType['all'] = (placeholderValues) => {\n\t\treturn this._prepare().all(placeholderValues);\n\t};\n\n\tget: ReturnType['get'] = (placeholderValues) => {\n\t\treturn this._prepare().get(placeholderValues);\n\t};\n\n\tvalues: ReturnType['values'] = (placeholderValues) => {\n\t\treturn this._prepare().values(placeholderValues);\n\t};\n\n\toverride async execute(): Promise> {\n\t\treturn (this.config.returning ? this.all() : this.run()) as SQLiteInsertExecute;\n\t}\n\n\t$dynamic(): SQLiteInsertDynamic {\n\t\treturn this as any;\n\t}\n}\n", "import { entityKind, is } from '~/entity.ts';\nimport type { TypedQueryBuilder } from '~/query-builders/query-builder.ts';\nimport { SelectionProxyHandler } from '~/selection-proxy.ts';\nimport type { ColumnsSelection, SQL } from '~/sql/sql.ts';\nimport type { SQLiteDialectConfig } from '~/sqlite-core/dialect.ts';\nimport { SQLiteDialect, SQLiteSyncDialect } from '~/sqlite-core/dialect.ts';\nimport type { WithBuilder } from '~/sqlite-core/subquery.ts';\nimport { WithSubquery } from '~/subquery.ts';\nimport { SQLiteSelectBuilder } from './select.ts';\nimport type { SelectedFields } from './select.types.ts';\n\nexport class QueryBuilder {\n\tstatic readonly [entityKind]: string = 'SQLiteQueryBuilder';\n\n\tprivate dialect: SQLiteDialect | undefined;\n\tprivate dialectConfig: SQLiteDialectConfig | undefined;\n\n\tconstructor(dialect?: SQLiteDialect | SQLiteDialectConfig) {\n\t\tthis.dialect = is(dialect, SQLiteDialect) ? dialect : undefined;\n\t\tthis.dialectConfig = is(dialect, SQLiteDialect) ? undefined : dialect;\n\t}\n\n\t$with: WithBuilder = (alias: string, selection?: ColumnsSelection) => {\n\t\tconst queryBuilder = this;\n\t\tconst as = (\n\t\t\tqb:\n\t\t\t\t| TypedQueryBuilder\n\t\t\t\t| SQL\n\t\t\t\t| ((qb: QueryBuilder) => TypedQueryBuilder | SQL),\n\t\t) => {\n\t\t\tif (typeof qb === 'function') {\n\t\t\t\tqb = qb(queryBuilder);\n\t\t\t}\n\n\t\t\treturn new Proxy(\n\t\t\t\tnew WithSubquery(\n\t\t\t\t\tqb.getSQL(),\n\t\t\t\t\tselection ?? ('getSelectedFields' in qb ? qb.getSelectedFields() ?? {} : {}) as SelectedFields,\n\t\t\t\t\talias,\n\t\t\t\t\ttrue,\n\t\t\t\t),\n\t\t\t\tnew SelectionProxyHandler({ alias, sqlAliasedBehavior: 'alias', sqlBehavior: 'error' }),\n\t\t\t) as any;\n\t\t};\n\t\treturn { as };\n\t};\n\n\twith(...queries: WithSubquery[]) {\n\t\tconst self = this;\n\n\t\tfunction select(): SQLiteSelectBuilder;\n\t\tfunction select(\n\t\t\tfields: TSelection,\n\t\t): SQLiteSelectBuilder;\n\t\tfunction select(\n\t\t\tfields?: TSelection,\n\t\t): SQLiteSelectBuilder {\n\t\t\treturn new SQLiteSelectBuilder({\n\t\t\t\tfields: fields ?? undefined,\n\t\t\t\tsession: undefined,\n\t\t\t\tdialect: self.getDialect(),\n\t\t\t\twithList: queries,\n\t\t\t});\n\t\t}\n\n\t\tfunction selectDistinct(): SQLiteSelectBuilder;\n\t\tfunction selectDistinct(\n\t\t\tfields: TSelection,\n\t\t): SQLiteSelectBuilder;\n\t\tfunction selectDistinct(\n\t\t\tfields?: TSelection,\n\t\t): SQLiteSelectBuilder {\n\t\t\treturn new SQLiteSelectBuilder({\n\t\t\t\tfields: fields ?? undefined,\n\t\t\t\tsession: undefined,\n\t\t\t\tdialect: self.getDialect(),\n\t\t\t\twithList: queries,\n\t\t\t\tdistinct: true,\n\t\t\t});\n\t\t}\n\n\t\treturn { select, selectDistinct };\n\t}\n\n\tselect(): SQLiteSelectBuilder;\n\tselect(\n\t\tfields: TSelection,\n\t): SQLiteSelectBuilder;\n\tselect(\n\t\tfields?: TSelection,\n\t): SQLiteSelectBuilder {\n\t\treturn new SQLiteSelectBuilder({ fields: fields ?? undefined, session: undefined, dialect: this.getDialect() });\n\t}\n\n\tselectDistinct(): SQLiteSelectBuilder;\n\tselectDistinct(\n\t\tfields: TSelection,\n\t): SQLiteSelectBuilder;\n\tselectDistinct(\n\t\tfields?: TSelection,\n\t): SQLiteSelectBuilder {\n\t\treturn new SQLiteSelectBuilder({\n\t\t\tfields: fields ?? undefined,\n\t\t\tsession: undefined,\n\t\t\tdialect: this.getDialect(),\n\t\t\tdistinct: true,\n\t\t});\n\t}\n\n\t// Lazy load dialect to avoid circular dependency\n\tprivate getDialect() {\n\t\tif (!this.dialect) {\n\t\t\tthis.dialect = new SQLiteSyncDialect(this.dialectConfig);\n\t\t}\n\n\t\treturn this.dialect;\n\t}\n}\n", "import { aliasedTable, aliasedTableColumn, mapColumnsInAliasedSQLToAlias, mapColumnsInSQLToAlias } from '~/alias.ts';\nimport { CasingCache } from '~/casing.ts';\nimport type { AnyColumn } from '~/column.ts';\nimport { Column } from '~/column.ts';\nimport { entityKind, is } from '~/entity.ts';\nimport { DrizzleError } from '~/errors.ts';\nimport type { MigrationConfig, MigrationMeta } from '~/migrator.ts';\nimport {\n\ttype BuildRelationalQueryResult,\n\ttype DBQueryConfig,\n\tgetOperators,\n\tgetOrderByOperators,\n\tMany,\n\tnormalizeRelation,\n\tOne,\n\ttype Relation,\n\ttype TableRelationalConfig,\n\ttype TablesRelationalConfig,\n} from '~/relations.ts';\nimport type { Name, Placeholder } from '~/sql/index.ts';\nimport { and, eq } from '~/sql/index.ts';\nimport { Param, type QueryWithTypings, SQL, sql, type SQLChunk } from '~/sql/sql.ts';\nimport { SQLiteColumn } from '~/sqlite-core/columns/index.ts';\nimport type {\n\tAnySQLiteSelectQueryBuilder,\n\tSQLiteDeleteConfig,\n\tSQLiteInsertConfig,\n\tSQLiteUpdateConfig,\n} from '~/sqlite-core/query-builders/index.ts';\nimport { SQLiteTable } from '~/sqlite-core/table.ts';\nimport { Subquery } from '~/subquery.ts';\nimport { getTableName, getTableUniqueName, Table } from '~/table.ts';\nimport { type Casing, orderSelectedFields, type UpdateSet } from '~/utils.ts';\nimport { ViewBaseConfig } from '~/view-common.ts';\nimport type {\n\tSelectedFieldsOrdered,\n\tSQLiteSelectConfig,\n\tSQLiteSelectJoinConfig,\n} from './query-builders/select.types.ts';\nimport type { SQLiteSession } from './session.ts';\nimport { SQLiteViewBase } from './view-base.ts';\n\nexport interface SQLiteDialectConfig {\n\tcasing?: Casing;\n}\n\nexport abstract class SQLiteDialect {\n\tstatic readonly [entityKind]: string = 'SQLiteDialect';\n\n\t/** @internal */\n\treadonly casing: CasingCache;\n\n\tconstructor(config?: SQLiteDialectConfig) {\n\t\tthis.casing = new CasingCache(config?.casing);\n\t}\n\n\tescapeName(name: string): string {\n\t\treturn `\"${name}\"`;\n\t}\n\n\tescapeParam(_num: number): string {\n\t\treturn '?';\n\t}\n\n\tescapeString(str: string): string {\n\t\treturn `'${str.replace(/'/g, \"''\")}'`;\n\t}\n\n\tprivate buildWithCTE(queries: Subquery[] | undefined): SQL | undefined {\n\t\tif (!queries?.length) return undefined;\n\n\t\tconst withSqlChunks = [sql`with `];\n\t\tfor (const [i, w] of queries.entries()) {\n\t\t\twithSqlChunks.push(sql`${sql.identifier(w._.alias)} as (${w._.sql})`);\n\t\t\tif (i < queries.length - 1) {\n\t\t\t\twithSqlChunks.push(sql`, `);\n\t\t\t}\n\t\t}\n\t\twithSqlChunks.push(sql` `);\n\t\treturn sql.join(withSqlChunks);\n\t}\n\n\tbuildDeleteQuery({ table, where, returning, withList, limit, orderBy }: SQLiteDeleteConfig): SQL {\n\t\tconst withSql = this.buildWithCTE(withList);\n\n\t\tconst returningSql = returning\n\t\t\t? sql` returning ${this.buildSelection(returning, { isSingleTable: true })}`\n\t\t\t: undefined;\n\n\t\tconst whereSql = where ? sql` where ${where}` : undefined;\n\n\t\tconst orderBySql = this.buildOrderBy(orderBy);\n\n\t\tconst limitSql = this.buildLimit(limit);\n\n\t\treturn sql`${withSql}delete from ${table}${whereSql}${returningSql}${orderBySql}${limitSql}`;\n\t}\n\n\tbuildUpdateSet(table: SQLiteTable, set: UpdateSet): SQL {\n\t\tconst tableColumns = table[Table.Symbol.Columns];\n\n\t\tconst columnNames = Object.keys(tableColumns).filter((colName) =>\n\t\t\tset[colName] !== undefined || tableColumns[colName]?.onUpdateFn !== undefined\n\t\t);\n\n\t\tconst setSize = columnNames.length;\n\t\treturn sql.join(columnNames.flatMap((colName, i) => {\n\t\t\tconst col = tableColumns[colName]!;\n\n\t\t\tconst onUpdateFnResult = col.onUpdateFn?.();\n\t\t\tconst value = set[colName] ?? (is(onUpdateFnResult, SQL) ? onUpdateFnResult : sql.param(onUpdateFnResult, col));\n\t\t\tconst res = sql`${sql.identifier(this.casing.getColumnCasing(col))} = ${value}`;\n\n\t\t\tif (i < setSize - 1) {\n\t\t\t\treturn [res, sql.raw(', ')];\n\t\t\t}\n\t\t\treturn [res];\n\t\t}));\n\t}\n\n\tbuildUpdateQuery({ table, set, where, returning, withList, joins, from, limit, orderBy }: SQLiteUpdateConfig): SQL {\n\t\tconst withSql = this.buildWithCTE(withList);\n\n\t\tconst setSql = this.buildUpdateSet(table, set);\n\n\t\tconst fromSql = from && sql.join([sql.raw(' from '), this.buildFromTable(from)]);\n\n\t\tconst joinsSql = this.buildJoins(joins);\n\n\t\tconst returningSql = returning\n\t\t\t? sql` returning ${this.buildSelection(returning, { isSingleTable: true })}`\n\t\t\t: undefined;\n\n\t\tconst whereSql = where ? sql` where ${where}` : undefined;\n\n\t\tconst orderBySql = this.buildOrderBy(orderBy);\n\n\t\tconst limitSql = this.buildLimit(limit);\n\n\t\treturn sql`${withSql}update ${table} set ${setSql}${fromSql}${joinsSql}${whereSql}${returningSql}${orderBySql}${limitSql}`;\n\t}\n\n\t/**\n\t * Builds selection SQL with provided fields/expressions\n\t *\n\t * Examples:\n\t *\n\t * `select from`\n\t *\n\t * `insert ... returning `\n\t *\n\t * If `isSingleTable` is true, then columns won't be prefixed with table name\n\t */\n\tprivate buildSelection(\n\t\tfields: SelectedFieldsOrdered,\n\t\t{ isSingleTable = false }: { isSingleTable?: boolean } = {},\n\t): SQL {\n\t\tconst columnsLen = fields.length;\n\n\t\tconst chunks = fields\n\t\t\t.flatMap(({ field }, i) => {\n\t\t\t\tconst chunk: SQLChunk[] = [];\n\n\t\t\t\tif (is(field, SQL.Aliased) && field.isSelectionField) {\n\t\t\t\t\tchunk.push(sql.identifier(field.fieldAlias));\n\t\t\t\t} else if (is(field, SQL.Aliased) || is(field, SQL)) {\n\t\t\t\t\tconst query = is(field, SQL.Aliased) ? field.sql : field;\n\n\t\t\t\t\tif (isSingleTable) {\n\t\t\t\t\t\tchunk.push(\n\t\t\t\t\t\t\tnew SQL(\n\t\t\t\t\t\t\t\tquery.queryChunks.map((c) => {\n\t\t\t\t\t\t\t\t\tif (is(c, Column)) {\n\t\t\t\t\t\t\t\t\t\treturn sql.identifier(this.casing.getColumnCasing(c));\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\treturn c;\n\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tchunk.push(query);\n\t\t\t\t\t}\n\n\t\t\t\t\tif (is(field, SQL.Aliased)) {\n\t\t\t\t\t\tchunk.push(sql` as ${sql.identifier(field.fieldAlias)}`);\n\t\t\t\t\t}\n\t\t\t\t} else if (is(field, Column)) {\n\t\t\t\t\tconst tableName = field.table[Table.Symbol.Name];\n\t\t\t\t\tif (field.columnType === 'SQLiteNumericBigInt') {\n\t\t\t\t\t\tif (isSingleTable) {\n\t\t\t\t\t\t\tchunk.push(sql`cast(${sql.identifier(this.casing.getColumnCasing(field))} as text)`);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tchunk.push(\n\t\t\t\t\t\t\t\tsql`cast(${sql.identifier(tableName)}.${sql.identifier(this.casing.getColumnCasing(field))} as text)`,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tif (isSingleTable) {\n\t\t\t\t\t\t\tchunk.push(sql.identifier(this.casing.getColumnCasing(field)));\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tchunk.push(sql`${sql.identifier(tableName)}.${sql.identifier(this.casing.getColumnCasing(field))}`);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else if (is(field, Subquery)) {\n\t\t\t\t\tconst entries = Object.entries(field._.selectedFields) as [string, SQL.Aliased | Column | SQL][];\n\n\t\t\t\t\tif (entries.length === 1) {\n\t\t\t\t\t\tconst entry = entries[0]![1];\n\n\t\t\t\t\t\tconst fieldDecoder = is(entry, SQL)\n\t\t\t\t\t\t\t? entry.decoder\n\t\t\t\t\t\t\t: is(entry, Column)\n\t\t\t\t\t\t\t? { mapFromDriverValue: (v: any) => entry.mapFromDriverValue(v) }\n\t\t\t\t\t\t\t: entry.sql.decoder;\n\t\t\t\t\t\tif (fieldDecoder) field._.sql.decoder = fieldDecoder;\n\t\t\t\t\t}\n\t\t\t\t\tchunk.push(field);\n\t\t\t\t}\n\n\t\t\t\tif (i < columnsLen - 1) {\n\t\t\t\t\tchunk.push(sql`, `);\n\t\t\t\t}\n\n\t\t\t\treturn chunk;\n\t\t\t});\n\n\t\treturn sql.join(chunks);\n\t}\n\n\tprivate buildJoins(joins: SQLiteSelectJoinConfig[] | undefined): SQL | undefined {\n\t\tif (!joins || joins.length === 0) {\n\t\t\treturn undefined;\n\t\t}\n\n\t\tconst joinsArray: SQL[] = [];\n\n\t\tif (joins) {\n\t\t\tfor (const [index, joinMeta] of joins.entries()) {\n\t\t\t\tif (index === 0) {\n\t\t\t\t\tjoinsArray.push(sql` `);\n\t\t\t\t}\n\t\t\t\tconst table = joinMeta.table;\n\t\t\t\tconst onSql = joinMeta.on ? sql` on ${joinMeta.on}` : undefined;\n\n\t\t\t\tif (is(table, SQLiteTable)) {\n\t\t\t\t\tconst tableName = table[SQLiteTable.Symbol.Name];\n\t\t\t\t\tconst tableSchema = table[SQLiteTable.Symbol.Schema];\n\t\t\t\t\tconst origTableName = table[SQLiteTable.Symbol.OriginalName];\n\t\t\t\t\tconst alias = tableName === origTableName ? undefined : joinMeta.alias;\n\t\t\t\t\tjoinsArray.push(\n\t\t\t\t\t\tsql`${sql.raw(joinMeta.joinType)} join ${tableSchema ? sql`${sql.identifier(tableSchema)}.` : undefined}${\n\t\t\t\t\t\t\tsql.identifier(origTableName)\n\t\t\t\t\t\t}${alias && sql` ${sql.identifier(alias)}`}${onSql}`,\n\t\t\t\t\t);\n\t\t\t\t} else {\n\t\t\t\t\tjoinsArray.push(\n\t\t\t\t\t\tsql`${sql.raw(joinMeta.joinType)} join ${table}${onSql}`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tif (index < joins.length - 1) {\n\t\t\t\t\tjoinsArray.push(sql` `);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn sql.join(joinsArray);\n\t}\n\n\tprivate buildLimit(limit: number | Placeholder | undefined): SQL | undefined {\n\t\treturn typeof limit === 'object' || (typeof limit === 'number' && limit >= 0)\n\t\t\t? sql` limit ${limit}`\n\t\t\t: undefined;\n\t}\n\n\tprivate buildOrderBy(orderBy: (SQLiteColumn | SQL | SQL.Aliased)[] | undefined): SQL | undefined {\n\t\tconst orderByList: (SQLiteColumn | SQL | SQL.Aliased)[] = [];\n\n\t\tif (orderBy) {\n\t\t\tfor (const [index, orderByValue] of orderBy.entries()) {\n\t\t\t\torderByList.push(orderByValue);\n\n\t\t\t\tif (index < orderBy.length - 1) {\n\t\t\t\t\torderByList.push(sql`, `);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn orderByList.length > 0 ? sql` order by ${sql.join(orderByList)}` : undefined;\n\t}\n\n\tprivate buildFromTable(\n\t\ttable: SQL | Subquery | SQLiteViewBase | SQLiteTable | undefined,\n\t): SQL | Subquery | SQLiteViewBase | SQLiteTable | undefined {\n\t\tif (is(table, Table) && table[Table.Symbol.IsAlias]) {\n\t\t\treturn sql`${sql`${sql.identifier(table[Table.Symbol.Schema] ?? '')}.`.if(table[Table.Symbol.Schema])}${\n\t\t\t\tsql.identifier(table[Table.Symbol.OriginalName])\n\t\t\t} ${sql.identifier(table[Table.Symbol.Name])}`;\n\t\t}\n\n\t\treturn table;\n\t}\n\n\tbuildSelectQuery(\n\t\t{\n\t\t\twithList,\n\t\t\tfields,\n\t\t\tfieldsFlat,\n\t\t\twhere,\n\t\t\thaving,\n\t\t\ttable,\n\t\t\tjoins,\n\t\t\torderBy,\n\t\t\tgroupBy,\n\t\t\tlimit,\n\t\t\toffset,\n\t\t\tdistinct,\n\t\t\tsetOperators,\n\t\t}: SQLiteSelectConfig,\n\t): SQL {\n\t\tconst fieldsList = fieldsFlat ?? orderSelectedFields(fields);\n\t\tfor (const f of fieldsList) {\n\t\t\tif (\n\t\t\t\tis(f.field, Column)\n\t\t\t\t&& getTableName(f.field.table)\n\t\t\t\t\t!== (is(table, Subquery)\n\t\t\t\t\t\t? table._.alias\n\t\t\t\t\t\t: is(table, SQLiteViewBase)\n\t\t\t\t\t\t? table[ViewBaseConfig].name\n\t\t\t\t\t\t: is(table, SQL)\n\t\t\t\t\t\t? undefined\n\t\t\t\t\t\t: getTableName(table))\n\t\t\t\t&& !((table) =>\n\t\t\t\t\tjoins?.some(({ alias }) =>\n\t\t\t\t\t\talias === (table[Table.Symbol.IsAlias] ? getTableName(table) : table[Table.Symbol.BaseName])\n\t\t\t\t\t))(f.field.table)\n\t\t\t) {\n\t\t\t\tconst tableName = getTableName(f.field.table);\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Your \"${\n\t\t\t\t\t\tf.path.join('->')\n\t\t\t\t\t}\" field references a column \"${tableName}\".\"${f.field.name}\", but the table \"${tableName}\" is not part of the query! Did you forget to join it?`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\tconst isSingleTable = !joins || joins.length === 0;\n\n\t\tconst withSql = this.buildWithCTE(withList);\n\n\t\tconst distinctSql = distinct ? sql` distinct` : undefined;\n\n\t\tconst selection = this.buildSelection(fieldsList, { isSingleTable });\n\n\t\tconst tableSql = this.buildFromTable(table);\n\n\t\tconst joinsSql = this.buildJoins(joins);\n\n\t\tconst whereSql = where ? sql` where ${where}` : undefined;\n\n\t\tconst havingSql = having ? sql` having ${having}` : undefined;\n\n\t\tconst groupByList: (SQL | AnyColumn | SQL.Aliased)[] = [];\n\t\tif (groupBy) {\n\t\t\tfor (const [index, groupByValue] of groupBy.entries()) {\n\t\t\t\tgroupByList.push(groupByValue);\n\n\t\t\t\tif (index < groupBy.length - 1) {\n\t\t\t\t\tgroupByList.push(sql`, `);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tconst groupBySql = groupByList.length > 0 ? sql` group by ${sql.join(groupByList)}` : undefined;\n\n\t\tconst orderBySql = this.buildOrderBy(orderBy);\n\n\t\tconst limitSql = this.buildLimit(limit);\n\n\t\tconst offsetSql = offset ? sql` offset ${offset}` : undefined;\n\n\t\tconst finalQuery =\n\t\t\tsql`${withSql}select${distinctSql} ${selection} from ${tableSql}${joinsSql}${whereSql}${groupBySql}${havingSql}${orderBySql}${limitSql}${offsetSql}`;\n\n\t\tif (setOperators.length > 0) {\n\t\t\treturn this.buildSetOperations(finalQuery, setOperators);\n\t\t}\n\n\t\treturn finalQuery;\n\t}\n\n\tbuildSetOperations(leftSelect: SQL, setOperators: SQLiteSelectConfig['setOperators']): SQL {\n\t\tconst [setOperator, ...rest] = setOperators;\n\n\t\tif (!setOperator) {\n\t\t\tthrow new Error('Cannot pass undefined values to any set operator');\n\t\t}\n\n\t\tif (rest.length === 0) {\n\t\t\treturn this.buildSetOperationQuery({ leftSelect, setOperator });\n\t\t}\n\n\t\t// Some recursive magic here\n\t\treturn this.buildSetOperations(\n\t\t\tthis.buildSetOperationQuery({ leftSelect, setOperator }),\n\t\t\trest,\n\t\t);\n\t}\n\n\tbuildSetOperationQuery({\n\t\tleftSelect,\n\t\tsetOperator: { type, isAll, rightSelect, limit, orderBy, offset },\n\t}: { leftSelect: SQL; setOperator: SQLiteSelectConfig['setOperators'][number] }): SQL {\n\t\t// SQLite doesn't support parenthesis in set operations\n\t\tconst leftChunk = sql`${leftSelect.getSQL()} `;\n\t\tconst rightChunk = sql`${rightSelect.getSQL()}`;\n\n\t\tlet orderBySql;\n\t\tif (orderBy && orderBy.length > 0) {\n\t\t\tconst orderByValues: (SQL | Name)[] = [];\n\n\t\t\t// The next bit is necessary because the sql operator replaces ${table.column} with `table`.`column`\n\t\t\t// which is invalid Sql syntax, Table from one of the SELECTs cannot be used in global ORDER clause\n\t\t\tfor (const singleOrderBy of orderBy) {\n\t\t\t\tif (is(singleOrderBy, SQLiteColumn)) {\n\t\t\t\t\torderByValues.push(sql.identifier(singleOrderBy.name));\n\t\t\t\t} else if (is(singleOrderBy, SQL)) {\n\t\t\t\t\tfor (let i = 0; i < singleOrderBy.queryChunks.length; i++) {\n\t\t\t\t\t\tconst chunk = singleOrderBy.queryChunks[i];\n\n\t\t\t\t\t\tif (is(chunk, SQLiteColumn)) {\n\t\t\t\t\t\t\tsingleOrderBy.queryChunks[i] = sql.identifier(this.casing.getColumnCasing(chunk));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\torderByValues.push(sql`${singleOrderBy}`);\n\t\t\t\t} else {\n\t\t\t\t\torderByValues.push(sql`${singleOrderBy}`);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\torderBySql = sql` order by ${sql.join(orderByValues, sql`, `)}`;\n\t\t}\n\n\t\tconst limitSql = typeof limit === 'object' || (typeof limit === 'number' && limit >= 0)\n\t\t\t? sql` limit ${limit}`\n\t\t\t: undefined;\n\n\t\tconst operatorChunk = sql.raw(`${type} ${isAll ? 'all ' : ''}`);\n\n\t\tconst offsetSql = offset ? sql` offset ${offset}` : undefined;\n\n\t\treturn sql`${leftChunk}${operatorChunk}${rightChunk}${orderBySql}${limitSql}${offsetSql}`;\n\t}\n\n\tbuildInsertQuery(\n\t\t{ table, values: valuesOrSelect, onConflict, returning, withList, select }: SQLiteInsertConfig,\n\t): SQL {\n\t\t// const isSingleValue = values.length === 1;\n\t\tconst valuesSqlList: ((SQLChunk | SQL)[] | SQL)[] = [];\n\t\tconst columns: Record = table[Table.Symbol.Columns];\n\n\t\tconst colEntries: [string, SQLiteColumn][] = Object.entries(columns).filter(([_, col]) =>\n\t\t\t!col.shouldDisableInsert()\n\t\t);\n\t\tconst insertOrder = colEntries.map(([, column]) => sql.identifier(this.casing.getColumnCasing(column)));\n\n\t\tif (select) {\n\t\t\tconst select = valuesOrSelect as AnySQLiteSelectQueryBuilder | SQL;\n\n\t\t\tif (is(select, SQL)) {\n\t\t\t\tvaluesSqlList.push(select);\n\t\t\t} else {\n\t\t\t\tvaluesSqlList.push(select.getSQL());\n\t\t\t}\n\t\t} else {\n\t\t\tconst values = valuesOrSelect as Record[];\n\t\t\tvaluesSqlList.push(sql.raw('values '));\n\n\t\t\tfor (const [valueIndex, value] of values.entries()) {\n\t\t\t\tconst valueList: (SQLChunk | SQL)[] = [];\n\t\t\t\tfor (const [fieldName, col] of colEntries) {\n\t\t\t\t\tconst colValue = value[fieldName];\n\t\t\t\t\tif (colValue === undefined || (is(colValue, Param) && colValue.value === undefined)) {\n\t\t\t\t\t\tlet defaultValue;\n\t\t\t\t\t\tif (col.default !== null && col.default !== undefined) {\n\t\t\t\t\t\t\tdefaultValue = is(col.default, SQL) ? col.default : sql.param(col.default, col);\n\t\t\t\t\t\t\t// eslint-disable-next-line unicorn/no-negated-condition\n\t\t\t\t\t\t} else if (col.defaultFn !== undefined) {\n\t\t\t\t\t\t\tconst defaultFnResult = col.defaultFn();\n\t\t\t\t\t\t\tdefaultValue = is(defaultFnResult, SQL) ? defaultFnResult : sql.param(defaultFnResult, col);\n\t\t\t\t\t\t\t// eslint-disable-next-line unicorn/no-negated-condition\n\t\t\t\t\t\t} else if (!col.default && col.onUpdateFn !== undefined) {\n\t\t\t\t\t\t\tconst onUpdateFnResult = col.onUpdateFn();\n\t\t\t\t\t\t\tdefaultValue = is(onUpdateFnResult, SQL) ? onUpdateFnResult : sql.param(onUpdateFnResult, col);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tdefaultValue = sql`null`;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tvalueList.push(defaultValue);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tvalueList.push(colValue);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tvaluesSqlList.push(valueList);\n\t\t\t\tif (valueIndex < values.length - 1) {\n\t\t\t\t\tvaluesSqlList.push(sql`, `);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tconst withSql = this.buildWithCTE(withList);\n\n\t\tconst valuesSql = sql.join(valuesSqlList);\n\n\t\tconst returningSql = returning\n\t\t\t? sql` returning ${this.buildSelection(returning, { isSingleTable: true })}`\n\t\t\t: undefined;\n\n\t\tconst onConflictSql = onConflict?.length\n\t\t\t? sql.join(onConflict)\n\t\t\t: undefined;\n\n\t\t// if (isSingleValue && valuesSqlList.length === 0){\n\t\t// \treturn sql`insert into ${table} default values ${onConflictSql}${returningSql}`;\n\t\t// }\n\n\t\treturn sql`${withSql}insert into ${table} ${insertOrder} ${valuesSql}${onConflictSql}${returningSql}`;\n\t}\n\n\tsqlToQuery(sql: SQL, invokeSource?: 'indexes' | undefined): QueryWithTypings {\n\t\treturn sql.toQuery({\n\t\t\tcasing: this.casing,\n\t\t\tescapeName: this.escapeName,\n\t\t\tescapeParam: this.escapeParam,\n\t\t\tescapeString: this.escapeString,\n\t\t\tinvokeSource,\n\t\t});\n\t}\n\n\tbuildRelationalQuery({\n\t\tfullSchema,\n\t\tschema,\n\t\ttableNamesMap,\n\t\ttable,\n\t\ttableConfig,\n\t\tqueryConfig: config,\n\t\ttableAlias,\n\t\tnestedQueryRelation,\n\t\tjoinOn,\n\t}: {\n\t\tfullSchema: Record;\n\t\tschema: TablesRelationalConfig;\n\t\ttableNamesMap: Record;\n\t\ttable: SQLiteTable;\n\t\ttableConfig: TableRelationalConfig;\n\t\tqueryConfig: true | DBQueryConfig<'many', true>;\n\t\ttableAlias: string;\n\t\tnestedQueryRelation?: Relation;\n\t\tjoinOn?: SQL;\n\t}): BuildRelationalQueryResult {\n\t\tlet selection: BuildRelationalQueryResult['selection'] = [];\n\t\tlet limit, offset, orderBy: SQLiteSelectConfig['orderBy'] = [], where;\n\t\tconst joins: SQLiteSelectJoinConfig[] = [];\n\n\t\tif (config === true) {\n\t\t\tconst selectionEntries = Object.entries(tableConfig.columns);\n\t\t\tselection = selectionEntries.map((\n\t\t\t\t[key, value],\n\t\t\t) => ({\n\t\t\t\tdbKey: value.name,\n\t\t\t\ttsKey: key,\n\t\t\t\tfield: aliasedTableColumn(value as SQLiteColumn, tableAlias),\n\t\t\t\trelationTableTsKey: undefined,\n\t\t\t\tisJson: false,\n\t\t\t\tselection: [],\n\t\t\t}));\n\t\t} else {\n\t\t\tconst aliasedColumns = Object.fromEntries(\n\t\t\t\tObject.entries(tableConfig.columns).map(([key, value]) => [key, aliasedTableColumn(value, tableAlias)]),\n\t\t\t);\n\n\t\t\tif (config.where) {\n\t\t\t\tconst whereSql = typeof config.where === 'function'\n\t\t\t\t\t? config.where(aliasedColumns, getOperators())\n\t\t\t\t\t: config.where;\n\t\t\t\twhere = whereSql && mapColumnsInSQLToAlias(whereSql, tableAlias);\n\t\t\t}\n\n\t\t\tconst fieldsSelection: { tsKey: string; value: SQLiteColumn | SQL.Aliased }[] = [];\n\t\t\tlet selectedColumns: string[] = [];\n\n\t\t\t// Figure out which columns to select\n\t\t\tif (config.columns) {\n\t\t\t\tlet isIncludeMode = false;\n\n\t\t\t\tfor (const [field, value] of Object.entries(config.columns)) {\n\t\t\t\t\tif (value === undefined) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (field in tableConfig.columns) {\n\t\t\t\t\t\tif (!isIncludeMode && value === true) {\n\t\t\t\t\t\t\tisIncludeMode = true;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tselectedColumns.push(field);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (selectedColumns.length > 0) {\n\t\t\t\t\tselectedColumns = isIncludeMode\n\t\t\t\t\t\t? selectedColumns.filter((c) => config.columns?.[c] === true)\n\t\t\t\t\t\t: Object.keys(tableConfig.columns).filter((key) => !selectedColumns.includes(key));\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// Select all columns if selection is not specified\n\t\t\t\tselectedColumns = Object.keys(tableConfig.columns);\n\t\t\t}\n\n\t\t\tfor (const field of selectedColumns) {\n\t\t\t\tconst column = tableConfig.columns[field]! as SQLiteColumn;\n\t\t\t\tfieldsSelection.push({ tsKey: field, value: column });\n\t\t\t}\n\n\t\t\tlet selectedRelations: {\n\t\t\t\ttsKey: string;\n\t\t\t\tqueryConfig: true | DBQueryConfig<'many', false>;\n\t\t\t\trelation: Relation;\n\t\t\t}[] = [];\n\n\t\t\t// Figure out which relations to select\n\t\t\tif (config.with) {\n\t\t\t\tselectedRelations = Object.entries(config.with)\n\t\t\t\t\t.filter((entry): entry is [typeof entry[0], NonNullable] => !!entry[1])\n\t\t\t\t\t.map(([tsKey, queryConfig]) => ({ tsKey, queryConfig, relation: tableConfig.relations[tsKey]! }));\n\t\t\t}\n\n\t\t\tlet extras;\n\n\t\t\t// Figure out which extras to select\n\t\t\tif (config.extras) {\n\t\t\t\textras = typeof config.extras === 'function'\n\t\t\t\t\t? config.extras(aliasedColumns, { sql })\n\t\t\t\t\t: config.extras;\n\t\t\t\tfor (const [tsKey, value] of Object.entries(extras)) {\n\t\t\t\t\tfieldsSelection.push({\n\t\t\t\t\t\ttsKey,\n\t\t\t\t\t\tvalue: mapColumnsInAliasedSQLToAlias(value, tableAlias),\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Transform `fieldsSelection` into `selection`\n\t\t\t// `fieldsSelection` shouldn't be used after this point\n\t\t\tfor (const { tsKey, value } of fieldsSelection) {\n\t\t\t\tselection.push({\n\t\t\t\t\tdbKey: is(value, SQL.Aliased) ? value.fieldAlias : tableConfig.columns[tsKey]!.name,\n\t\t\t\t\ttsKey,\n\t\t\t\t\tfield: is(value, Column) ? aliasedTableColumn(value, tableAlias) : value,\n\t\t\t\t\trelationTableTsKey: undefined,\n\t\t\t\t\tisJson: false,\n\t\t\t\t\tselection: [],\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tlet orderByOrig = typeof config.orderBy === 'function'\n\t\t\t\t? config.orderBy(aliasedColumns, getOrderByOperators())\n\t\t\t\t: config.orderBy ?? [];\n\t\t\tif (!Array.isArray(orderByOrig)) {\n\t\t\t\torderByOrig = [orderByOrig];\n\t\t\t}\n\t\t\torderBy = orderByOrig.map((orderByValue) => {\n\t\t\t\tif (is(orderByValue, Column)) {\n\t\t\t\t\treturn aliasedTableColumn(orderByValue, tableAlias) as SQLiteColumn;\n\t\t\t\t}\n\t\t\t\treturn mapColumnsInSQLToAlias(orderByValue, tableAlias);\n\t\t\t});\n\n\t\t\tlimit = config.limit;\n\t\t\toffset = config.offset;\n\n\t\t\t// Process all relations\n\t\t\tfor (\n\t\t\t\tconst {\n\t\t\t\t\ttsKey: selectedRelationTsKey,\n\t\t\t\t\tqueryConfig: selectedRelationConfigValue,\n\t\t\t\t\trelation,\n\t\t\t\t} of selectedRelations\n\t\t\t) {\n\t\t\t\tconst normalizedRelation = normalizeRelation(schema, tableNamesMap, relation);\n\t\t\t\tconst relationTableName = getTableUniqueName(relation.referencedTable);\n\t\t\t\tconst relationTableTsName = tableNamesMap[relationTableName]!;\n\t\t\t\tconst relationTableAlias = `${tableAlias}_${selectedRelationTsKey}`;\n\t\t\t\t// const relationTable = schema[relationTableTsName]!;\n\t\t\t\tconst joinOn = and(\n\t\t\t\t\t...normalizedRelation.fields.map((field, i) =>\n\t\t\t\t\t\teq(\n\t\t\t\t\t\t\taliasedTableColumn(normalizedRelation.references[i]!, relationTableAlias),\n\t\t\t\t\t\t\taliasedTableColumn(field, tableAlias),\n\t\t\t\t\t\t)\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t\tconst builtRelation = this.buildRelationalQuery({\n\t\t\t\t\tfullSchema,\n\t\t\t\t\tschema,\n\t\t\t\t\ttableNamesMap,\n\t\t\t\t\ttable: fullSchema[relationTableTsName] as SQLiteTable,\n\t\t\t\t\ttableConfig: schema[relationTableTsName]!,\n\t\t\t\t\tqueryConfig: is(relation, One)\n\t\t\t\t\t\t? (selectedRelationConfigValue === true\n\t\t\t\t\t\t\t? { limit: 1 }\n\t\t\t\t\t\t\t: { ...selectedRelationConfigValue, limit: 1 })\n\t\t\t\t\t\t: selectedRelationConfigValue,\n\t\t\t\t\ttableAlias: relationTableAlias,\n\t\t\t\t\tjoinOn,\n\t\t\t\t\tnestedQueryRelation: relation,\n\t\t\t\t});\n\t\t\t\tconst field = (sql`(${builtRelation.sql})`).as(selectedRelationTsKey);\n\t\t\t\tselection.push({\n\t\t\t\t\tdbKey: selectedRelationTsKey,\n\t\t\t\t\ttsKey: selectedRelationTsKey,\n\t\t\t\t\tfield,\n\t\t\t\t\trelationTableTsKey: relationTableTsName,\n\t\t\t\t\tisJson: true,\n\t\t\t\t\tselection: builtRelation.selection,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\n\t\tif (selection.length === 0) {\n\t\t\tthrow new DrizzleError({\n\t\t\t\tmessage:\n\t\t\t\t\t`No fields selected for table \"${tableConfig.tsName}\" (\"${tableAlias}\"). You need to have at least one item in \"columns\", \"with\" or \"extras\". If you need to select all columns, omit the \"columns\" key or set it to undefined.`,\n\t\t\t});\n\t\t}\n\n\t\tlet result;\n\n\t\twhere = and(joinOn, where);\n\n\t\tif (nestedQueryRelation) {\n\t\t\tlet field = sql`json_array(${\n\t\t\t\tsql.join(\n\t\t\t\t\tselection.map(({ field }) =>\n\t\t\t\t\t\tis(field, SQLiteColumn)\n\t\t\t\t\t\t\t? sql.identifier(this.casing.getColumnCasing(field))\n\t\t\t\t\t\t\t: is(field, SQL.Aliased)\n\t\t\t\t\t\t\t? field.sql\n\t\t\t\t\t\t\t: field\n\t\t\t\t\t),\n\t\t\t\t\tsql`, `,\n\t\t\t\t)\n\t\t\t})`;\n\t\t\tif (is(nestedQueryRelation, Many)) {\n\t\t\t\tfield = sql`coalesce(json_group_array(${field}), json_array())`;\n\t\t\t}\n\t\t\tconst nestedSelection = [{\n\t\t\t\tdbKey: 'data',\n\t\t\t\ttsKey: 'data',\n\t\t\t\tfield: field.as('data'),\n\t\t\t\tisJson: true,\n\t\t\t\trelationTableTsKey: tableConfig.tsName,\n\t\t\t\tselection,\n\t\t\t}];\n\n\t\t\tconst needsSubquery = limit !== undefined || offset !== undefined || orderBy.length > 0;\n\n\t\t\tif (needsSubquery) {\n\t\t\t\tresult = this.buildSelectQuery({\n\t\t\t\t\ttable: aliasedTable(table, tableAlias),\n\t\t\t\t\tfields: {},\n\t\t\t\t\tfieldsFlat: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tpath: [],\n\t\t\t\t\t\t\tfield: sql.raw('*'),\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t\twhere,\n\t\t\t\t\tlimit,\n\t\t\t\t\toffset,\n\t\t\t\t\torderBy,\n\t\t\t\t\tsetOperators: [],\n\t\t\t\t});\n\n\t\t\t\twhere = undefined;\n\t\t\t\tlimit = undefined;\n\t\t\t\toffset = undefined;\n\t\t\t\torderBy = undefined;\n\t\t\t} else {\n\t\t\t\tresult = aliasedTable(table, tableAlias);\n\t\t\t}\n\n\t\t\tresult = this.buildSelectQuery({\n\t\t\t\ttable: is(result, SQLiteTable) ? result : new Subquery(result, {}, tableAlias),\n\t\t\t\tfields: {},\n\t\t\t\tfieldsFlat: nestedSelection.map(({ field }) => ({\n\t\t\t\t\tpath: [],\n\t\t\t\t\tfield: is(field, Column) ? aliasedTableColumn(field, tableAlias) : field,\n\t\t\t\t})),\n\t\t\t\tjoins,\n\t\t\t\twhere,\n\t\t\t\tlimit,\n\t\t\t\toffset,\n\t\t\t\torderBy,\n\t\t\t\tsetOperators: [],\n\t\t\t});\n\t\t} else {\n\t\t\tresult = this.buildSelectQuery({\n\t\t\t\ttable: aliasedTable(table, tableAlias),\n\t\t\t\tfields: {},\n\t\t\t\tfieldsFlat: selection.map(({ field }) => ({\n\t\t\t\t\tpath: [],\n\t\t\t\t\tfield: is(field, Column) ? aliasedTableColumn(field, tableAlias) : field,\n\t\t\t\t})),\n\t\t\t\tjoins,\n\t\t\t\twhere,\n\t\t\t\tlimit,\n\t\t\t\toffset,\n\t\t\t\torderBy,\n\t\t\t\tsetOperators: [],\n\t\t\t});\n\t\t}\n\n\t\treturn {\n\t\t\ttableTsKey: tableConfig.tsName,\n\t\t\tsql: result,\n\t\t\tselection,\n\t\t};\n\t}\n}\n\nexport class SQLiteSyncDialect extends SQLiteDialect {\n\tstatic override readonly [entityKind]: string = 'SQLiteSyncDialect';\n\n\tmigrate(\n\t\tmigrations: MigrationMeta[],\n\t\tsession: SQLiteSession<'sync', unknown, Record, TablesRelationalConfig>,\n\t\tconfig?: string | MigrationConfig,\n\t): void {\n\t\tconst migrationsTable = config === undefined\n\t\t\t? '__drizzle_migrations'\n\t\t\t: typeof config === 'string'\n\t\t\t? '__drizzle_migrations'\n\t\t\t: config.migrationsTable ?? '__drizzle_migrations';\n\n\t\tconst migrationTableCreate = sql`\n\t\t\tCREATE TABLE IF NOT EXISTS ${sql.identifier(migrationsTable)} (\n\t\t\t\tid SERIAL PRIMARY KEY,\n\t\t\t\thash text NOT NULL,\n\t\t\t\tcreated_at numeric\n\t\t\t)\n\t\t`;\n\t\tsession.run(migrationTableCreate);\n\n\t\tconst dbMigrations = session.values<[number, string, string]>(\n\t\t\tsql`SELECT id, hash, created_at FROM ${sql.identifier(migrationsTable)} ORDER BY created_at DESC LIMIT 1`,\n\t\t);\n\n\t\tconst lastDbMigration = dbMigrations[0] ?? undefined;\n\t\tsession.run(sql`BEGIN`);\n\n\t\ttry {\n\t\t\tfor (const migration of migrations) {\n\t\t\t\tif (!lastDbMigration || Number(lastDbMigration[2])! < migration.folderMillis) {\n\t\t\t\t\tfor (const stmt of migration.sql) {\n\t\t\t\t\t\tsession.run(sql.raw(stmt));\n\t\t\t\t\t}\n\t\t\t\t\tsession.run(\n\t\t\t\t\t\tsql`INSERT INTO ${\n\t\t\t\t\t\t\tsql.identifier(migrationsTable)\n\t\t\t\t\t\t} (\"hash\", \"created_at\") VALUES(${migration.hash}, ${migration.folderMillis})`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tsession.run(sql`COMMIT`);\n\t\t} catch (e) {\n\t\t\tsession.run(sql`ROLLBACK`);\n\t\t\tthrow e;\n\t\t}\n\t}\n}\n\nexport class SQLiteAsyncDialect extends SQLiteDialect {\n\tstatic override readonly [entityKind]: string = 'SQLiteAsyncDialect';\n\n\tasync migrate(\n\t\tmigrations: MigrationMeta[],\n\t\tsession: SQLiteSession<'async', any, any, any>,\n\t\tconfig?: string | MigrationConfig,\n\t): Promise {\n\t\tconst migrationsTable = config === undefined\n\t\t\t? '__drizzle_migrations'\n\t\t\t: typeof config === 'string'\n\t\t\t? '__drizzle_migrations'\n\t\t\t: config.migrationsTable ?? '__drizzle_migrations';\n\n\t\tconst migrationTableCreate = sql`\n\t\t\tCREATE TABLE IF NOT EXISTS ${sql.identifier(migrationsTable)} (\n\t\t\t\tid SERIAL PRIMARY KEY,\n\t\t\t\thash text NOT NULL,\n\t\t\t\tcreated_at numeric\n\t\t\t)\n\t\t`;\n\t\tawait session.run(migrationTableCreate);\n\n\t\tconst dbMigrations = await session.values<[number, string, string]>(\n\t\t\tsql`SELECT id, hash, created_at FROM ${sql.identifier(migrationsTable)} ORDER BY created_at DESC LIMIT 1`,\n\t\t);\n\n\t\tconst lastDbMigration = dbMigrations[0] ?? undefined;\n\n\t\tawait session.transaction(async (tx) => {\n\t\t\tfor (const migration of migrations) {\n\t\t\t\tif (!lastDbMigration || Number(lastDbMigration[2])! < migration.folderMillis) {\n\t\t\t\t\tfor (const stmt of migration.sql) {\n\t\t\t\t\t\tawait tx.run(sql.raw(stmt));\n\t\t\t\t\t}\n\t\t\t\t\tawait tx.run(\n\t\t\t\t\t\tsql`INSERT INTO ${\n\t\t\t\t\t\t\tsql.identifier(migrationsTable)\n\t\t\t\t\t\t} (\"hash\", \"created_at\") VALUES(${migration.hash}, ${migration.folderMillis})`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t}\n}\n", "import type { Column } from '~/column.ts';\nimport { entityKind } from './entity.ts';\nimport { Table } from './table.ts';\nimport type { Casing } from './utils.ts';\n\nexport function toSnakeCase(input: string) {\n\tconst words = input\n\t\t.replace(/['\\u2019]/g, '')\n\t\t.match(/[\\da-z]+|[A-Z]+(?![a-z])|[A-Z][\\da-z]+/g) ?? [];\n\n\treturn words.map((word) => word.toLowerCase()).join('_');\n}\n\nexport function toCamelCase(input: string) {\n\tconst words = input\n\t\t.replace(/['\\u2019]/g, '')\n\t\t.match(/[\\da-z]+|[A-Z]+(?![a-z])|[A-Z][\\da-z]+/g) ?? [];\n\n\treturn words.reduce((acc, word, i) => {\n\t\tconst formattedWord = i === 0 ? word.toLowerCase() : `${word[0]!.toUpperCase()}${word.slice(1)}`;\n\t\treturn acc + formattedWord;\n\t}, '');\n}\n\nfunction noopCase(input: string) {\n\treturn input;\n}\n\nexport class CasingCache {\n\tstatic readonly [entityKind]: string = 'CasingCache';\n\n\t/** @internal */\n\tcache: Record = {};\n\tprivate cachedTables: Record = {};\n\tprivate convert: (input: string) => string;\n\n\tconstructor(casing?: Casing) {\n\t\tthis.convert = casing === 'snake_case'\n\t\t\t? toSnakeCase\n\t\t\t: casing === 'camelCase'\n\t\t\t? toCamelCase\n\t\t\t: noopCase;\n\t}\n\n\tgetColumnCasing(column: Column): string {\n\t\tif (!column.keyAsName) return column.name;\n\n\t\tconst schema = column.table[Table.Symbol.Schema] ?? 'public';\n\t\tconst tableName = column.table[Table.Symbol.OriginalName];\n\t\tconst key = `${schema}.${tableName}.${column.name}`;\n\n\t\tif (!this.cache[key]) {\n\t\t\tthis.cacheTable(column.table);\n\t\t}\n\t\treturn this.cache[key]!;\n\t}\n\n\tprivate cacheTable(table: Table) {\n\t\tconst schema = table[Table.Symbol.Schema] ?? 'public';\n\t\tconst tableName = table[Table.Symbol.OriginalName];\n\t\tconst tableKey = `${schema}.${tableName}`;\n\n\t\tif (!this.cachedTables[tableKey]) {\n\t\t\tfor (const column of Object.values(table[Table.Symbol.Columns])) {\n\t\t\t\tconst columnKey = `${tableKey}.${column.name}`;\n\t\t\t\tthis.cache[columnKey] = this.convert(column.name);\n\t\t\t}\n\t\t\tthis.cachedTables[tableKey] = true;\n\t\t}\n\t}\n\n\tclearCache() {\n\t\tthis.cache = {};\n\t\tthis.cachedTables = {};\n\t}\n}\n", "import { entityKind } from '~/entity.ts';\n\nexport class DrizzleError extends Error {\n\tstatic readonly [entityKind]: string = 'DrizzleError';\n\n\tconstructor({ message, cause }: { message?: string; cause?: unknown }) {\n\t\tsuper(message);\n\t\tthis.name = 'DrizzleError';\n\t\tthis.cause = cause;\n\t}\n}\n\nexport class DrizzleQueryError extends Error {\n\tconstructor(\n\t\tpublic query: string,\n\t\tpublic params: any[],\n\t\tpublic override cause?: Error,\n\t) {\n\t\tsuper(`Failed query: ${query}\\nparams: ${params}`);\n\t\tError.captureStackTrace(this, DrizzleQueryError);\n\n\t\t// ES2022+: preserves original error on `.cause`\n\t\tif (cause) (this as any).cause = cause;\n\t}\n}\n\nexport class TransactionRollbackError extends DrizzleError {\n\tstatic override readonly [entityKind]: string = 'TransactionRollbackError';\n\n\tconstructor() {\n\t\tsuper({ message: 'Rollback' });\n\t}\n}\n", "import { type AnyColumn, Column } from '~/column.ts';\nimport { is } from '~/entity.ts';\nimport { type SQL, sql, type SQLWrapper } from '../sql.ts';\n\n/**\n * Returns the number of values in `expression`.\n *\n * ## Examples\n *\n * ```ts\n * // Number employees with null values\n * db.select({ value: count() }).from(employees)\n * // Number of employees where `name` is not null\n * db.select({ value: count(employees.name) }).from(employees)\n * ```\n *\n * @see countDistinct to get the number of non-duplicate values in `expression`\n */\nexport function count(expression?: SQLWrapper): SQL {\n\treturn sql`count(${expression || sql.raw('*')})`.mapWith(Number);\n}\n\n/**\n * Returns the number of non-duplicate values in `expression`.\n *\n * ## Examples\n *\n * ```ts\n * // Number of employees where `name` is distinct\n * db.select({ value: countDistinct(employees.name) }).from(employees)\n * ```\n *\n * @see count to get the number of values in `expression`, including duplicates\n */\nexport function countDistinct(expression: SQLWrapper): SQL {\n\treturn sql`count(distinct ${expression})`.mapWith(Number);\n}\n\n/**\n * Returns the average (arithmetic mean) of all non-null values in `expression`.\n *\n * ## Examples\n *\n * ```ts\n * // Average salary of an employee\n * db.select({ value: avg(employees.salary) }).from(employees)\n * ```\n *\n * @see avgDistinct to get the average of all non-null and non-duplicate values in `expression`\n */\nexport function avg(expression: SQLWrapper): SQL {\n\treturn sql`avg(${expression})`.mapWith(String);\n}\n\n/**\n * Returns the average (arithmetic mean) of all non-null and non-duplicate values in `expression`.\n *\n * ## Examples\n *\n * ```ts\n * // Average salary of an employee where `salary` is distinct\n * db.select({ value: avgDistinct(employees.salary) }).from(employees)\n * ```\n *\n * @see avg to get the average of all non-null values in `expression`, including duplicates\n */\nexport function avgDistinct(expression: SQLWrapper): SQL {\n\treturn sql`avg(distinct ${expression})`.mapWith(String);\n}\n\n/**\n * Returns the sum of all non-null values in `expression`.\n *\n * ## Examples\n *\n * ```ts\n * // Sum of every employee's salary\n * db.select({ value: sum(employees.salary) }).from(employees)\n * ```\n *\n * @see sumDistinct to get the sum of all non-null and non-duplicate values in `expression`\n */\nexport function sum(expression: SQLWrapper): SQL {\n\treturn sql`sum(${expression})`.mapWith(String);\n}\n\n/**\n * Returns the sum of all non-null and non-duplicate values in `expression`.\n *\n * ## Examples\n *\n * ```ts\n * // Sum of every employee's salary where `salary` is distinct (no duplicates)\n * db.select({ value: sumDistinct(employees.salary) }).from(employees)\n * ```\n *\n * @see sum to get the sum of all non-null values in `expression`, including duplicates\n */\nexport function sumDistinct(expression: SQLWrapper): SQL {\n\treturn sql`sum(distinct ${expression})`.mapWith(String);\n}\n\n/**\n * Returns the maximum value in `expression`.\n *\n * ## Examples\n *\n * ```ts\n * // The employee with the highest salary\n * db.select({ value: max(employees.salary) }).from(employees)\n * ```\n */\nexport function max(expression: T): SQL<(T extends AnyColumn ? T['_']['data'] : string) | null> {\n\treturn sql`max(${expression})`.mapWith(is(expression, Column) ? expression : String) as any;\n}\n\n/**\n * Returns the minimum value in `expression`.\n *\n * ## Examples\n *\n * ```ts\n * // The employee with the lowest salary\n * db.select({ value: min(employees.salary) }).from(employees)\n * ```\n */\nexport function min(expression: T): SQL<(T extends AnyColumn ? T['_']['data'] : string) | null> {\n\treturn sql`min(${expression})`.mapWith(is(expression, Column) ? expression : String) as any;\n}\n", "import { entityKind } from '~/entity.ts';\nimport type { ColumnsSelection } from '~/sql/sql.ts';\nimport { View } from '~/sql/sql.ts';\n\nexport abstract class SQLiteViewBase<\n\tTName extends string = string,\n\tTExisting extends boolean = boolean,\n\tTSelection extends ColumnsSelection = ColumnsSelection,\n> extends View {\n\tstatic override readonly [entityKind]: string = 'SQLiteViewBase';\n\n\tdeclare _: View['_'] & {\n\t\tviewBrand: 'SQLiteView';\n\t};\n}\n", "import type { CacheConfig, WithCacheConfig } from '~/cache/core/types.ts';\nimport { entityKind, is } from '~/entity.ts';\nimport { TypedQueryBuilder } from '~/query-builders/query-builder.ts';\nimport type {\n\tBuildSubquerySelection,\n\tGetSelectTableName,\n\tGetSelectTableSelection,\n\tJoinNullability,\n\tJoinType,\n\tSelectMode,\n\tSelectResult,\n\tSetOperator,\n} from '~/query-builders/select.types.ts';\nimport { QueryPromise } from '~/query-promise.ts';\nimport type { RunnableQuery } from '~/runnable-query.ts';\nimport { SelectionProxyHandler } from '~/selection-proxy.ts';\nimport { SQL, View } from '~/sql/sql.ts';\nimport type { ColumnsSelection, Placeholder, Query, SQLWrapper } from '~/sql/sql.ts';\nimport type { SQLiteColumn } from '~/sqlite-core/columns/index.ts';\nimport type { SQLiteDialect } from '~/sqlite-core/dialect.ts';\nimport type { SQLiteSession } from '~/sqlite-core/session.ts';\nimport type { SubqueryWithSelection } from '~/sqlite-core/subquery.ts';\nimport type { SQLiteTable } from '~/sqlite-core/table.ts';\nimport { Subquery } from '~/subquery.ts';\nimport { Table } from '~/table.ts';\nimport {\n\tapplyMixins,\n\tgetTableColumns,\n\tgetTableLikeName,\n\thaveSameKeys,\n\torderSelectedFields,\n\ttype ValueOrArray,\n} from '~/utils.ts';\nimport { ViewBaseConfig } from '~/view-common.ts';\nimport { extractUsedTable } from '../utils.ts';\nimport { SQLiteViewBase } from '../view-base.ts';\nimport type {\n\tAnySQLiteSelect,\n\tCreateSQLiteSelectFromBuilderMode,\n\tGetSQLiteSetOperators,\n\tSelectedFields,\n\tSetOperatorRightSelect,\n\tSQLiteCreateSetOperatorFn,\n\tSQLiteSelectConfig,\n\tSQLiteSelectCrossJoinFn,\n\tSQLiteSelectDynamic,\n\tSQLiteSelectExecute,\n\tSQLiteSelectHKT,\n\tSQLiteSelectHKTBase,\n\tSQLiteSelectJoinFn,\n\tSQLiteSelectPrepare,\n\tSQLiteSelectWithout,\n\tSQLiteSetOperatorExcludedMethods,\n\tSQLiteSetOperatorWithResult,\n} from './select.types.ts';\n\nexport class SQLiteSelectBuilder<\n\tTSelection extends SelectedFields | undefined,\n\tTResultType extends 'sync' | 'async',\n\tTRunResult,\n\tTBuilderMode extends 'db' | 'qb' = 'db',\n> {\n\tstatic readonly [entityKind]: string = 'SQLiteSelectBuilder';\n\n\tprivate fields: TSelection;\n\tprivate session: SQLiteSession | undefined;\n\tprivate dialect: SQLiteDialect;\n\tprivate withList: Subquery[] | undefined;\n\tprivate distinct: boolean | undefined;\n\n\tconstructor(\n\t\tconfig: {\n\t\t\tfields: TSelection;\n\t\t\tsession: SQLiteSession | undefined;\n\t\t\tdialect: SQLiteDialect;\n\t\t\twithList?: Subquery[];\n\t\t\tdistinct?: boolean;\n\t\t},\n\t) {\n\t\tthis.fields = config.fields;\n\t\tthis.session = config.session;\n\t\tthis.dialect = config.dialect;\n\t\tthis.withList = config.withList;\n\t\tthis.distinct = config.distinct;\n\t}\n\n\tfrom(\n\t\tsource: TFrom,\n\t): CreateSQLiteSelectFromBuilderMode<\n\t\tTBuilderMode,\n\t\tGetSelectTableName,\n\t\tTResultType,\n\t\tTRunResult,\n\t\tTSelection extends undefined ? GetSelectTableSelection : TSelection,\n\t\tTSelection extends undefined ? 'single' : 'partial'\n\t> {\n\t\tconst isPartialSelect = !!this.fields;\n\n\t\tlet fields: SelectedFields;\n\t\tif (this.fields) {\n\t\t\tfields = this.fields;\n\t\t} else if (is(source, Subquery)) {\n\t\t\t// This is required to use the proxy handler to get the correct field values from the subquery\n\t\t\tfields = Object.fromEntries(\n\t\t\t\tObject.keys(source._.selectedFields).map((\n\t\t\t\t\tkey,\n\t\t\t\t) => [key, source[key as unknown as keyof typeof source] as unknown as SelectedFields[string]]),\n\t\t\t);\n\t\t} else if (is(source, SQLiteViewBase)) {\n\t\t\tfields = source[ViewBaseConfig].selectedFields as SelectedFields;\n\t\t} else if (is(source, SQL)) {\n\t\t\tfields = {};\n\t\t} else {\n\t\t\tfields = getTableColumns(source);\n\t\t}\n\n\t\treturn new SQLiteSelectBase({\n\t\t\ttable: source,\n\t\t\tfields,\n\t\t\tisPartialSelect,\n\t\t\tsession: this.session,\n\t\t\tdialect: this.dialect,\n\t\t\twithList: this.withList,\n\t\t\tdistinct: this.distinct,\n\t\t}) as any;\n\t}\n}\n\nexport abstract class SQLiteSelectQueryBuilderBase<\n\tTHKT extends SQLiteSelectHKTBase,\n\tTTableName extends string | undefined,\n\tTResultType extends 'sync' | 'async',\n\tTRunResult,\n\tTSelection extends ColumnsSelection,\n\tTSelectMode extends SelectMode,\n\tTNullabilityMap extends Record = TTableName extends string ? Record\n\t\t: {},\n\tTDynamic extends boolean = false,\n\tTExcludedMethods extends string = never,\n\tTResult extends any[] = SelectResult[],\n\tTSelectedFields extends ColumnsSelection = BuildSubquerySelection,\n> extends TypedQueryBuilder {\n\tstatic override readonly [entityKind]: string = 'SQLiteSelectQueryBuilder';\n\n\toverride readonly _: {\n\t\treadonly dialect: 'sqlite';\n\t\treadonly hkt: THKT;\n\t\treadonly tableName: TTableName;\n\t\treadonly resultType: TResultType;\n\t\treadonly runResult: TRunResult;\n\t\treadonly selection: TSelection;\n\t\treadonly selectMode: TSelectMode;\n\t\treadonly nullabilityMap: TNullabilityMap;\n\t\treadonly dynamic: TDynamic;\n\t\treadonly excludedMethods: TExcludedMethods;\n\t\treadonly result: TResult;\n\t\treadonly selectedFields: TSelectedFields;\n\t\treadonly config: SQLiteSelectConfig;\n\t};\n\n\t/** @internal */\n\tconfig: SQLiteSelectConfig;\n\tprotected joinsNotNullableMap: Record;\n\tprivate tableName: string | undefined;\n\tprivate isPartialSelect: boolean;\n\tprotected session: SQLiteSession | undefined;\n\tprotected dialect: SQLiteDialect;\n\tprotected cacheConfig?: WithCacheConfig = undefined;\n\tprotected usedTables: Set = new Set();\n\n\tconstructor(\n\t\t{ table, fields, isPartialSelect, session, dialect, withList, distinct }: {\n\t\t\ttable: SQLiteSelectConfig['table'];\n\t\t\tfields: SQLiteSelectConfig['fields'];\n\t\t\tisPartialSelect: boolean;\n\t\t\tsession: SQLiteSession | undefined;\n\t\t\tdialect: SQLiteDialect;\n\t\t\twithList: Subquery[] | undefined;\n\t\t\tdistinct: boolean | undefined;\n\t\t},\n\t) {\n\t\tsuper();\n\t\tthis.config = {\n\t\t\twithList,\n\t\t\ttable,\n\t\t\tfields: { ...fields },\n\t\t\tdistinct,\n\t\t\tsetOperators: [],\n\t\t};\n\t\tthis.isPartialSelect = isPartialSelect;\n\t\tthis.session = session;\n\t\tthis.dialect = dialect;\n\t\tthis._ = {\n\t\t\tselectedFields: fields as TSelectedFields,\n\t\t\tconfig: this.config,\n\t\t} as this['_'];\n\t\tthis.tableName = getTableLikeName(table);\n\t\tthis.joinsNotNullableMap = typeof this.tableName === 'string' ? { [this.tableName]: true } : {};\n\t\tfor (const item of extractUsedTable(table)) this.usedTables.add(item);\n\t}\n\n\t/** @internal */\n\tgetUsedTables() {\n\t\treturn [...this.usedTables];\n\t}\n\n\tprivate createJoin(\n\t\tjoinType: TJoinType,\n\t): 'cross' extends TJoinType ? SQLiteSelectCrossJoinFn\n\t\t: SQLiteSelectJoinFn\n\t{\n\t\treturn (\n\t\t\ttable: SQLiteTable | Subquery | SQLiteViewBase | SQL,\n\t\t\ton?: ((aliases: TSelection) => SQL | undefined) | SQL | undefined,\n\t\t) => {\n\t\t\tconst baseTableName = this.tableName;\n\t\t\tconst tableName = getTableLikeName(table);\n\n\t\t\t// store all tables used in a query\n\t\t\tfor (const item of extractUsedTable(table)) this.usedTables.add(item);\n\n\t\t\tif (typeof tableName === 'string' && this.config.joins?.some((join) => join.alias === tableName)) {\n\t\t\t\tthrow new Error(`Alias \"${tableName}\" is already used in this query`);\n\t\t\t}\n\n\t\t\tif (!this.isPartialSelect) {\n\t\t\t\t// If this is the first join and this is not a partial select and we're not selecting from raw SQL, \"move\" the fields from the main table to the nested object\n\t\t\t\tif (Object.keys(this.joinsNotNullableMap).length === 1 && typeof baseTableName === 'string') {\n\t\t\t\t\tthis.config.fields = {\n\t\t\t\t\t\t[baseTableName]: this.config.fields,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tif (typeof tableName === 'string' && !is(table, SQL)) {\n\t\t\t\t\tconst selection = is(table, Subquery)\n\t\t\t\t\t\t? table._.selectedFields\n\t\t\t\t\t\t: is(table, View)\n\t\t\t\t\t\t? table[ViewBaseConfig].selectedFields\n\t\t\t\t\t\t: table[Table.Symbol.Columns];\n\t\t\t\t\tthis.config.fields[tableName] = selection;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (typeof on === 'function') {\n\t\t\t\ton = on(\n\t\t\t\t\tnew Proxy(\n\t\t\t\t\t\tthis.config.fields,\n\t\t\t\t\t\tnew SelectionProxyHandler({ sqlAliasedBehavior: 'sql', sqlBehavior: 'sql' }),\n\t\t\t\t\t) as TSelection,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tif (!this.config.joins) {\n\t\t\t\tthis.config.joins = [];\n\t\t\t}\n\t\t\tthis.config.joins.push({ on, table, joinType, alias: tableName });\n\n\t\t\tif (typeof tableName === 'string') {\n\t\t\t\tswitch (joinType) {\n\t\t\t\t\tcase 'left': {\n\t\t\t\t\t\tthis.joinsNotNullableMap[tableName] = false;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tcase 'right': {\n\t\t\t\t\t\tthis.joinsNotNullableMap = Object.fromEntries(\n\t\t\t\t\t\t\tObject.entries(this.joinsNotNullableMap).map(([key]) => [key, false]),\n\t\t\t\t\t\t);\n\t\t\t\t\t\tthis.joinsNotNullableMap[tableName] = true;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tcase 'cross':\n\t\t\t\t\tcase 'inner': {\n\t\t\t\t\t\tthis.joinsNotNullableMap[tableName] = true;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tcase 'full': {\n\t\t\t\t\t\tthis.joinsNotNullableMap = Object.fromEntries(\n\t\t\t\t\t\t\tObject.entries(this.joinsNotNullableMap).map(([key]) => [key, false]),\n\t\t\t\t\t\t);\n\t\t\t\t\t\tthis.joinsNotNullableMap[tableName] = false;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn this as any;\n\t\t};\n\t}\n\n\t/**\n\t * Executes a `left join` operation by adding another table to the current query.\n\t *\n\t * Calling this method associates each row of the table with the corresponding row from the joined table, if a match is found. If no matching row exists, it sets all columns of the joined table to null.\n\t *\n\t * See docs: {@link https://orm.drizzle.team/docs/joins#left-join}\n\t *\n\t * @param table the table to join.\n\t * @param on the `on` clause.\n\t *\n\t * @example\n\t *\n\t * ```ts\n\t * // Select all users and their pets\n\t * const usersWithPets: { user: User; pets: Pet | null; }[] = await db.select()\n\t * .from(users)\n\t * .leftJoin(pets, eq(users.id, pets.ownerId))\n\t *\n\t * // Select userId and petId\n\t * const usersIdsAndPetIds: { userId: number; petId: number | null; }[] = await db.select({\n\t * userId: users.id,\n\t * petId: pets.id,\n\t * })\n\t * .from(users)\n\t * .leftJoin(pets, eq(users.id, pets.ownerId))\n\t * ```\n\t */\n\tleftJoin = this.createJoin('left');\n\n\t/**\n\t * Executes a `right join` operation by adding another table to the current query.\n\t *\n\t * Calling this method associates each row of the joined table with the corresponding row from the main table, if a match is found. If no matching row exists, it sets all columns of the main table to null.\n\t *\n\t * See docs: {@link https://orm.drizzle.team/docs/joins#right-join}\n\t *\n\t * @param table the table to join.\n\t * @param on the `on` clause.\n\t *\n\t * @example\n\t *\n\t * ```ts\n\t * // Select all users and their pets\n\t * const usersWithPets: { user: User | null; pets: Pet; }[] = await db.select()\n\t * .from(users)\n\t * .rightJoin(pets, eq(users.id, pets.ownerId))\n\t *\n\t * // Select userId and petId\n\t * const usersIdsAndPetIds: { userId: number | null; petId: number; }[] = await db.select({\n\t * userId: users.id,\n\t * petId: pets.id,\n\t * })\n\t * .from(users)\n\t * .rightJoin(pets, eq(users.id, pets.ownerId))\n\t * ```\n\t */\n\trightJoin = this.createJoin('right');\n\n\t/**\n\t * Executes an `inner join` operation, creating a new table by combining rows from two tables that have matching values.\n\t *\n\t * Calling this method retrieves rows that have corresponding entries in both joined tables. Rows without matching entries in either table are excluded, resulting in a table that includes only matching pairs.\n\t *\n\t * See docs: {@link https://orm.drizzle.team/docs/joins#inner-join}\n\t *\n\t * @param table the table to join.\n\t * @param on the `on` clause.\n\t *\n\t * @example\n\t *\n\t * ```ts\n\t * // Select all users and their pets\n\t * const usersWithPets: { user: User; pets: Pet; }[] = await db.select()\n\t * .from(users)\n\t * .innerJoin(pets, eq(users.id, pets.ownerId))\n\t *\n\t * // Select userId and petId\n\t * const usersIdsAndPetIds: { userId: number; petId: number; }[] = await db.select({\n\t * userId: users.id,\n\t * petId: pets.id,\n\t * })\n\t * .from(users)\n\t * .innerJoin(pets, eq(users.id, pets.ownerId))\n\t * ```\n\t */\n\tinnerJoin = this.createJoin('inner');\n\n\t/**\n\t * Executes a `full join` operation by combining rows from two tables into a new table.\n\t *\n\t * Calling this method retrieves all rows from both main and joined tables, merging rows with matching values and filling in `null` for non-matching columns.\n\t *\n\t * See docs: {@link https://orm.drizzle.team/docs/joins#full-join}\n\t *\n\t * @param table the table to join.\n\t * @param on the `on` clause.\n\t *\n\t * @example\n\t *\n\t * ```ts\n\t * // Select all users and their pets\n\t * const usersWithPets: { user: User | null; pets: Pet | null; }[] = await db.select()\n\t * .from(users)\n\t * .fullJoin(pets, eq(users.id, pets.ownerId))\n\t *\n\t * // Select userId and petId\n\t * const usersIdsAndPetIds: { userId: number | null; petId: number | null; }[] = await db.select({\n\t * userId: users.id,\n\t * petId: pets.id,\n\t * })\n\t * .from(users)\n\t * .fullJoin(pets, eq(users.id, pets.ownerId))\n\t * ```\n\t */\n\tfullJoin = this.createJoin('full');\n\n\t/**\n\t * Executes a `cross join` operation by combining rows from two tables into a new table.\n\t *\n\t * Calling this method retrieves all rows from both main and joined tables, merging all rows from each table.\n\t *\n\t * See docs: {@link https://orm.drizzle.team/docs/joins#cross-join}\n\t *\n\t * @param table the table to join.\n\t *\n\t * @example\n\t *\n\t * ```ts\n\t * // Select all users, each user with every pet\n\t * const usersWithPets: { user: User; pets: Pet; }[] = await db.select()\n\t * .from(users)\n\t * .crossJoin(pets)\n\t *\n\t * // Select userId and petId\n\t * const usersIdsAndPetIds: { userId: number; petId: number; }[] = await db.select({\n\t * userId: users.id,\n\t * petId: pets.id,\n\t * })\n\t * .from(users)\n\t * .crossJoin(pets)\n\t * ```\n\t */\n\tcrossJoin = this.createJoin('cross');\n\n\tprivate createSetOperator(\n\t\ttype: SetOperator,\n\t\tisAll: boolean,\n\t): >(\n\t\trightSelection:\n\t\t\t| ((setOperators: GetSQLiteSetOperators) => SetOperatorRightSelect)\n\t\t\t| SetOperatorRightSelect,\n\t) => SQLiteSelectWithout<\n\t\tthis,\n\t\tTDynamic,\n\t\tSQLiteSetOperatorExcludedMethods,\n\t\ttrue\n\t> {\n\t\treturn (rightSelection) => {\n\t\t\tconst rightSelect = (typeof rightSelection === 'function'\n\t\t\t\t? rightSelection(getSQLiteSetOperators())\n\t\t\t\t: rightSelection) as TypedQueryBuilder<\n\t\t\t\t\tany,\n\t\t\t\t\tTResult\n\t\t\t\t>;\n\n\t\t\tif (!haveSameKeys(this.getSelectedFields(), rightSelect.getSelectedFields())) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t'Set operator error (union / intersect / except): selected fields are not the same or are in a different order',\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tthis.config.setOperators.push({ type, isAll, rightSelect });\n\t\t\treturn this as any;\n\t\t};\n\t}\n\n\t/**\n\t * Adds `union` set operator to the query.\n\t *\n\t * Calling this method will combine the result sets of the `select` statements and remove any duplicate rows that appear across them.\n\t *\n\t * See docs: {@link https://orm.drizzle.team/docs/set-operations#union}\n\t *\n\t * @example\n\t *\n\t * ```ts\n\t * // Select all unique names from customers and users tables\n\t * await db.select({ name: users.name })\n\t * .from(users)\n\t * .union(\n\t * db.select({ name: customers.name }).from(customers)\n\t * );\n\t * // or\n\t * import { union } from 'drizzle-orm/sqlite-core'\n\t *\n\t * await union(\n\t * db.select({ name: users.name }).from(users),\n\t * db.select({ name: customers.name }).from(customers)\n\t * );\n\t * ```\n\t */\n\tunion = this.createSetOperator('union', false);\n\n\t/**\n\t * Adds `union all` set operator to the query.\n\t *\n\t * Calling this method will combine the result-set of the `select` statements and keep all duplicate rows that appear across them.\n\t *\n\t * See docs: {@link https://orm.drizzle.team/docs/set-operations#union-all}\n\t *\n\t * @example\n\t *\n\t * ```ts\n\t * // Select all transaction ids from both online and in-store sales\n\t * await db.select({ transaction: onlineSales.transactionId })\n\t * .from(onlineSales)\n\t * .unionAll(\n\t * db.select({ transaction: inStoreSales.transactionId }).from(inStoreSales)\n\t * );\n\t * // or\n\t * import { unionAll } from 'drizzle-orm/sqlite-core'\n\t *\n\t * await unionAll(\n\t * db.select({ transaction: onlineSales.transactionId }).from(onlineSales),\n\t * db.select({ transaction: inStoreSales.transactionId }).from(inStoreSales)\n\t * );\n\t * ```\n\t */\n\tunionAll = this.createSetOperator('union', true);\n\n\t/**\n\t * Adds `intersect` set operator to the query.\n\t *\n\t * Calling this method will retain only the rows that are present in both result sets and eliminate duplicates.\n\t *\n\t * See docs: {@link https://orm.drizzle.team/docs/set-operations#intersect}\n\t *\n\t * @example\n\t *\n\t * ```ts\n\t * // Select course names that are offered in both departments A and B\n\t * await db.select({ courseName: depA.courseName })\n\t * .from(depA)\n\t * .intersect(\n\t * db.select({ courseName: depB.courseName }).from(depB)\n\t * );\n\t * // or\n\t * import { intersect } from 'drizzle-orm/sqlite-core'\n\t *\n\t * await intersect(\n\t * db.select({ courseName: depA.courseName }).from(depA),\n\t * db.select({ courseName: depB.courseName }).from(depB)\n\t * );\n\t * ```\n\t */\n\tintersect = this.createSetOperator('intersect', false);\n\n\t/**\n\t * Adds `except` set operator to the query.\n\t *\n\t * Calling this method will retrieve all unique rows from the left query, except for the rows that are present in the result set of the right query.\n\t *\n\t * See docs: {@link https://orm.drizzle.team/docs/set-operations#except}\n\t *\n\t * @example\n\t *\n\t * ```ts\n\t * // Select all courses offered in department A but not in department B\n\t * await db.select({ courseName: depA.courseName })\n\t * .from(depA)\n\t * .except(\n\t * db.select({ courseName: depB.courseName }).from(depB)\n\t * );\n\t * // or\n\t * import { except } from 'drizzle-orm/sqlite-core'\n\t *\n\t * await except(\n\t * db.select({ courseName: depA.courseName }).from(depA),\n\t * db.select({ courseName: depB.courseName }).from(depB)\n\t * );\n\t * ```\n\t */\n\texcept = this.createSetOperator('except', false);\n\n\t/** @internal */\n\taddSetOperators(setOperators: SQLiteSelectConfig['setOperators']): SQLiteSelectWithout<\n\t\tthis,\n\t\tTDynamic,\n\t\tSQLiteSetOperatorExcludedMethods,\n\t\ttrue\n\t> {\n\t\tthis.config.setOperators.push(...setOperators);\n\t\treturn this as any;\n\t}\n\n\t/**\n\t * Adds a `where` clause to the query.\n\t *\n\t * Calling this method will select only those rows that fulfill a specified condition.\n\t *\n\t * See docs: {@link https://orm.drizzle.team/docs/select#filtering}\n\t *\n\t * @param where the `where` clause.\n\t *\n\t * @example\n\t * You can use conditional operators and `sql function` to filter the rows to be selected.\n\t *\n\t * ```ts\n\t * // Select all cars with green color\n\t * await db.select().from(cars).where(eq(cars.color, 'green'));\n\t * // or\n\t * await db.select().from(cars).where(sql`${cars.color} = 'green'`)\n\t * ```\n\t *\n\t * You can logically combine conditional operators with `and()` and `or()` operators:\n\t *\n\t * ```ts\n\t * // Select all BMW cars with a green color\n\t * await db.select().from(cars).where(and(eq(cars.color, 'green'), eq(cars.brand, 'BMW')));\n\t *\n\t * // Select all cars with the green or blue color\n\t * await db.select().from(cars).where(or(eq(cars.color, 'green'), eq(cars.color, 'blue')));\n\t * ```\n\t */\n\twhere(\n\t\twhere: ((aliases: TSelection) => SQL | undefined) | SQL | undefined,\n\t): SQLiteSelectWithout {\n\t\tif (typeof where === 'function') {\n\t\t\twhere = where(\n\t\t\t\tnew Proxy(\n\t\t\t\t\tthis.config.fields,\n\t\t\t\t\tnew SelectionProxyHandler({ sqlAliasedBehavior: 'sql', sqlBehavior: 'sql' }),\n\t\t\t\t) as TSelection,\n\t\t\t);\n\t\t}\n\t\tthis.config.where = where;\n\t\treturn this as any;\n\t}\n\n\t/**\n\t * Adds a `having` clause to the query.\n\t *\n\t * Calling this method will select only those rows that fulfill a specified condition. It is typically used with aggregate functions to filter the aggregated data based on a specified condition.\n\t *\n\t * See docs: {@link https://orm.drizzle.team/docs/select#aggregations}\n\t *\n\t * @param having the `having` clause.\n\t *\n\t * @example\n\t *\n\t * ```ts\n\t * // Select all brands with more than one car\n\t * await db.select({\n\t * \tbrand: cars.brand,\n\t * \tcount: sql`cast(count(${cars.id}) as int)`,\n\t * })\n\t * .from(cars)\n\t * .groupBy(cars.brand)\n\t * .having(({ count }) => gt(count, 1));\n\t * ```\n\t */\n\thaving(\n\t\thaving: ((aliases: this['_']['selection']) => SQL | undefined) | SQL | undefined,\n\t): SQLiteSelectWithout {\n\t\tif (typeof having === 'function') {\n\t\t\thaving = having(\n\t\t\t\tnew Proxy(\n\t\t\t\t\tthis.config.fields,\n\t\t\t\t\tnew SelectionProxyHandler({ sqlAliasedBehavior: 'sql', sqlBehavior: 'sql' }),\n\t\t\t\t) as TSelection,\n\t\t\t);\n\t\t}\n\t\tthis.config.having = having;\n\t\treturn this as any;\n\t}\n\n\t/**\n\t * Adds a `group by` clause to the query.\n\t *\n\t * Calling this method will group rows that have the same values into summary rows, often used for aggregation purposes.\n\t *\n\t * See docs: {@link https://orm.drizzle.team/docs/select#aggregations}\n\t *\n\t * @example\n\t *\n\t * ```ts\n\t * // Group and count people by their last names\n\t * await db.select({\n\t * lastName: people.lastName,\n\t * count: sql`cast(count(*) as int)`\n\t * })\n\t * .from(people)\n\t * .groupBy(people.lastName);\n\t * ```\n\t */\n\tgroupBy(\n\t\tbuilder: (aliases: this['_']['selection']) => ValueOrArray,\n\t): SQLiteSelectWithout;\n\tgroupBy(...columns: (SQLiteColumn | SQL)[]): SQLiteSelectWithout;\n\tgroupBy(\n\t\t...columns:\n\t\t\t| [(aliases: this['_']['selection']) => ValueOrArray]\n\t\t\t| (SQLiteColumn | SQL | SQL.Aliased)[]\n\t): SQLiteSelectWithout {\n\t\tif (typeof columns[0] === 'function') {\n\t\t\tconst groupBy = columns[0](\n\t\t\t\tnew Proxy(\n\t\t\t\t\tthis.config.fields,\n\t\t\t\t\tnew SelectionProxyHandler({ sqlAliasedBehavior: 'alias', sqlBehavior: 'sql' }),\n\t\t\t\t) as TSelection,\n\t\t\t);\n\t\t\tthis.config.groupBy = Array.isArray(groupBy) ? groupBy : [groupBy];\n\t\t} else {\n\t\t\tthis.config.groupBy = columns as (SQLiteColumn | SQL | SQL.Aliased)[];\n\t\t}\n\t\treturn this as any;\n\t}\n\n\t/**\n\t * Adds an `order by` clause to the query.\n\t *\n\t * Calling this method will sort the result-set in ascending or descending order. By default, the sort order is ascending.\n\t *\n\t * See docs: {@link https://orm.drizzle.team/docs/select#order-by}\n\t *\n\t * @example\n\t *\n\t * ```\n\t * // Select cars ordered by year\n\t * await db.select().from(cars).orderBy(cars.year);\n\t * ```\n\t *\n\t * You can specify whether results are in ascending or descending order with the `asc()` and `desc()` operators.\n\t *\n\t * ```ts\n\t * // Select cars ordered by year in descending order\n\t * await db.select().from(cars).orderBy(desc(cars.year));\n\t *\n\t * // Select cars ordered by year and price\n\t * await db.select().from(cars).orderBy(asc(cars.year), desc(cars.price));\n\t * ```\n\t */\n\torderBy(\n\t\tbuilder: (aliases: this['_']['selection']) => ValueOrArray,\n\t): SQLiteSelectWithout;\n\torderBy(...columns: (SQLiteColumn | SQL)[]): SQLiteSelectWithout;\n\torderBy(\n\t\t...columns:\n\t\t\t| [(aliases: this['_']['selection']) => ValueOrArray]\n\t\t\t| (SQLiteColumn | SQL | SQL.Aliased)[]\n\t): SQLiteSelectWithout {\n\t\tif (typeof columns[0] === 'function') {\n\t\t\tconst orderBy = columns[0](\n\t\t\t\tnew Proxy(\n\t\t\t\t\tthis.config.fields,\n\t\t\t\t\tnew SelectionProxyHandler({ sqlAliasedBehavior: 'alias', sqlBehavior: 'sql' }),\n\t\t\t\t) as TSelection,\n\t\t\t);\n\n\t\t\tconst orderByArray = Array.isArray(orderBy) ? orderBy : [orderBy];\n\n\t\t\tif (this.config.setOperators.length > 0) {\n\t\t\t\tthis.config.setOperators.at(-1)!.orderBy = orderByArray;\n\t\t\t} else {\n\t\t\t\tthis.config.orderBy = orderByArray;\n\t\t\t}\n\t\t} else {\n\t\t\tconst orderByArray = columns as (SQLiteColumn | SQL | SQL.Aliased)[];\n\n\t\t\tif (this.config.setOperators.length > 0) {\n\t\t\t\tthis.config.setOperators.at(-1)!.orderBy = orderByArray;\n\t\t\t} else {\n\t\t\t\tthis.config.orderBy = orderByArray;\n\t\t\t}\n\t\t}\n\t\treturn this as any;\n\t}\n\n\t/**\n\t * Adds a `limit` clause to the query.\n\t *\n\t * Calling this method will set the maximum number of rows that will be returned by this query.\n\t *\n\t * See docs: {@link https://orm.drizzle.team/docs/select#limit--offset}\n\t *\n\t * @param limit the `limit` clause.\n\t *\n\t * @example\n\t *\n\t * ```ts\n\t * // Get the first 10 people from this query.\n\t * await db.select().from(people).limit(10);\n\t * ```\n\t */\n\tlimit(limit: number | Placeholder): SQLiteSelectWithout {\n\t\tif (this.config.setOperators.length > 0) {\n\t\t\tthis.config.setOperators.at(-1)!.limit = limit;\n\t\t} else {\n\t\t\tthis.config.limit = limit;\n\t\t}\n\t\treturn this as any;\n\t}\n\n\t/**\n\t * Adds an `offset` clause to the query.\n\t *\n\t * Calling this method will skip a number of rows when returning results from this query.\n\t *\n\t * See docs: {@link https://orm.drizzle.team/docs/select#limit--offset}\n\t *\n\t * @param offset the `offset` clause.\n\t *\n\t * @example\n\t *\n\t * ```ts\n\t * // Get the 10th-20th people from this query.\n\t * await db.select().from(people).offset(10).limit(10);\n\t * ```\n\t */\n\toffset(offset: number | Placeholder): SQLiteSelectWithout {\n\t\tif (this.config.setOperators.length > 0) {\n\t\t\tthis.config.setOperators.at(-1)!.offset = offset;\n\t\t} else {\n\t\t\tthis.config.offset = offset;\n\t\t}\n\t\treturn this as any;\n\t}\n\n\t/** @internal */\n\tgetSQL(): SQL {\n\t\treturn this.dialect.buildSelectQuery(this.config);\n\t}\n\n\ttoSQL(): Query {\n\t\tconst { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());\n\t\treturn rest;\n\t}\n\n\tas(\n\t\talias: TAlias,\n\t): SubqueryWithSelection {\n\t\tconst usedTables: string[] = [];\n\t\tusedTables.push(...extractUsedTable(this.config.table));\n\t\tif (this.config.joins) { for (const it of this.config.joins) usedTables.push(...extractUsedTable(it.table)); }\n\n\t\treturn new Proxy(\n\t\t\tnew Subquery(this.getSQL(), this.config.fields, alias, false, [...new Set(usedTables)]),\n\t\t\tnew SelectionProxyHandler({ alias, sqlAliasedBehavior: 'alias', sqlBehavior: 'error' }),\n\t\t) as SubqueryWithSelection;\n\t}\n\n\t/** @internal */\n\toverride getSelectedFields(): this['_']['selectedFields'] {\n\t\treturn new Proxy(\n\t\t\tthis.config.fields,\n\t\t\tnew SelectionProxyHandler({ alias: this.tableName, sqlAliasedBehavior: 'alias', sqlBehavior: 'error' }),\n\t\t) as this['_']['selectedFields'];\n\t}\n\n\t$dynamic(): SQLiteSelectDynamic {\n\t\treturn this;\n\t}\n}\n\n// eslint-disable-next-line @typescript-eslint/no-empty-interface\nexport interface SQLiteSelectBase<\n\tTTableName extends string | undefined,\n\tTResultType extends 'sync' | 'async',\n\tTRunResult,\n\tTSelection extends ColumnsSelection,\n\tTSelectMode extends SelectMode = 'single',\n\tTNullabilityMap extends Record = TTableName extends string ? Record\n\t\t: {},\n\tTDynamic extends boolean = false,\n\tTExcludedMethods extends string = never,\n\tTResult extends any[] = SelectResult[],\n\tTSelectedFields extends ColumnsSelection = BuildSubquerySelection,\n> extends\n\tSQLiteSelectQueryBuilderBase<\n\t\tSQLiteSelectHKT,\n\t\tTTableName,\n\t\tTResultType,\n\t\tTRunResult,\n\t\tTSelection,\n\t\tTSelectMode,\n\t\tTNullabilityMap,\n\t\tTDynamic,\n\t\tTExcludedMethods,\n\t\tTResult,\n\t\tTSelectedFields\n\t>,\n\tQueryPromise\n{}\n\nexport class SQLiteSelectBase<\n\tTTableName extends string | undefined,\n\tTResultType extends 'sync' | 'async',\n\tTRunResult,\n\tTSelection,\n\tTSelectMode extends SelectMode = 'single',\n\tTNullabilityMap extends Record = TTableName extends string ? Record\n\t\t: {},\n\tTDynamic extends boolean = false,\n\tTExcludedMethods extends string = never,\n\tTResult = SelectResult[],\n\tTSelectedFields extends ColumnsSelection = BuildSubquerySelection,\n> extends SQLiteSelectQueryBuilderBase<\n\tSQLiteSelectHKT,\n\tTTableName,\n\tTResultType,\n\tTRunResult,\n\tTSelection,\n\tTSelectMode,\n\tTNullabilityMap,\n\tTDynamic,\n\tTExcludedMethods,\n\tTResult,\n\tTSelectedFields\n> implements RunnableQuery, SQLWrapper {\n\tstatic override readonly [entityKind]: string = 'SQLiteSelect';\n\n\t/** @internal */\n\t_prepare(isOneTimeQuery = true): SQLiteSelectPrepare {\n\t\tif (!this.session) {\n\t\t\tthrow new Error('Cannot execute a query on a query builder. Please use a database instance instead.');\n\t\t}\n\t\tconst fieldsList = orderSelectedFields(this.config.fields);\n\t\tconst query = this.session[isOneTimeQuery ? 'prepareOneTimeQuery' : 'prepareQuery'](\n\t\t\tthis.dialect.sqlToQuery(this.getSQL()),\n\t\t\tfieldsList,\n\t\t\t'all',\n\t\t\ttrue,\n\t\t\tundefined,\n\t\t\t{\n\t\t\t\ttype: 'select',\n\t\t\t\ttables: [...this.usedTables],\n\t\t\t},\n\t\t\tthis.cacheConfig,\n\t\t);\n\t\tquery.joinsNotNullableMap = this.joinsNotNullableMap;\n\t\treturn query as ReturnType;\n\t}\n\n\t$withCache(config?: { config?: CacheConfig; tag?: string; autoInvalidate?: boolean } | false) {\n\t\tthis.cacheConfig = config === undefined\n\t\t\t? { config: {}, enable: true, autoInvalidate: true }\n\t\t\t: config === false\n\t\t\t? { enable: false }\n\t\t\t: { enable: true, autoInvalidate: true, ...config };\n\t\treturn this;\n\t}\n\n\tprepare(): SQLiteSelectPrepare {\n\t\treturn this._prepare(false);\n\t}\n\n\trun: ReturnType['run'] = (placeholderValues) => {\n\t\treturn this._prepare().run(placeholderValues);\n\t};\n\n\tall: ReturnType['all'] = (placeholderValues) => {\n\t\treturn this._prepare().all(placeholderValues);\n\t};\n\n\tget: ReturnType['get'] = (placeholderValues) => {\n\t\treturn this._prepare().get(placeholderValues);\n\t};\n\n\tvalues: ReturnType['values'] = (placeholderValues) => {\n\t\treturn this._prepare().values(placeholderValues);\n\t};\n\n\tasync execute(): Promise> {\n\t\treturn this.all() as SQLiteSelectExecute;\n\t}\n}\n\napplyMixins(SQLiteSelectBase, [QueryPromise]);\n\nfunction createSetOperator(type: SetOperator, isAll: boolean): SQLiteCreateSetOperatorFn {\n\treturn (leftSelect, rightSelect, ...restSelects) => {\n\t\tconst setOperators = [rightSelect, ...restSelects].map((select) => ({\n\t\t\ttype,\n\t\t\tisAll,\n\t\t\trightSelect: select as AnySQLiteSelect,\n\t\t}));\n\n\t\tfor (const setOperator of setOperators) {\n\t\t\tif (!haveSameKeys((leftSelect as any).getSelectedFields(), setOperator.rightSelect.getSelectedFields())) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t'Set operator error (union / intersect / except): selected fields are not the same or are in a different order',\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\treturn (leftSelect as AnySQLiteSelect).addSetOperators(setOperators) as any;\n\t};\n}\n\nconst getSQLiteSetOperators = () => ({\n\tunion,\n\tunionAll,\n\tintersect,\n\texcept,\n});\n\n/**\n * Adds `union` set operator to the query.\n *\n * Calling this method will combine the result sets of the `select` statements and remove any duplicate rows that appear across them.\n *\n * See docs: {@link https://orm.drizzle.team/docs/set-operations#union}\n *\n * @example\n *\n * ```ts\n * // Select all unique names from customers and users tables\n * import { union } from 'drizzle-orm/sqlite-core'\n *\n * await union(\n * db.select({ name: users.name }).from(users),\n * db.select({ name: customers.name }).from(customers)\n * );\n * // or\n * await db.select({ name: users.name })\n * .from(users)\n * .union(\n * db.select({ name: customers.name }).from(customers)\n * );\n * ```\n */\nexport const union = createSetOperator('union', false);\n\n/**\n * Adds `union all` set operator to the query.\n *\n * Calling this method will combine the result-set of the `select` statements and keep all duplicate rows that appear across them.\n *\n * See docs: {@link https://orm.drizzle.team/docs/set-operations#union-all}\n *\n * @example\n *\n * ```ts\n * // Select all transaction ids from both online and in-store sales\n * import { unionAll } from 'drizzle-orm/sqlite-core'\n *\n * await unionAll(\n * db.select({ transaction: onlineSales.transactionId }).from(onlineSales),\n * db.select({ transaction: inStoreSales.transactionId }).from(inStoreSales)\n * );\n * // or\n * await db.select({ transaction: onlineSales.transactionId })\n * .from(onlineSales)\n * .unionAll(\n * db.select({ transaction: inStoreSales.transactionId }).from(inStoreSales)\n * );\n * ```\n */\nexport const unionAll = createSetOperator('union', true);\n\n/**\n * Adds `intersect` set operator to the query.\n *\n * Calling this method will retain only the rows that are present in both result sets and eliminate duplicates.\n *\n * See docs: {@link https://orm.drizzle.team/docs/set-operations#intersect}\n *\n * @example\n *\n * ```ts\n * // Select course names that are offered in both departments A and B\n * import { intersect } from 'drizzle-orm/sqlite-core'\n *\n * await intersect(\n * db.select({ courseName: depA.courseName }).from(depA),\n * db.select({ courseName: depB.courseName }).from(depB)\n * );\n * // or\n * await db.select({ courseName: depA.courseName })\n * .from(depA)\n * .intersect(\n * db.select({ courseName: depB.courseName }).from(depB)\n * );\n * ```\n */\nexport const intersect = createSetOperator('intersect', false);\n\n/**\n * Adds `except` set operator to the query.\n *\n * Calling this method will retrieve all unique rows from the left query, except for the rows that are present in the result set of the right query.\n *\n * See docs: {@link https://orm.drizzle.team/docs/set-operations#except}\n *\n * @example\n *\n * ```ts\n * // Select all courses offered in department A but not in department B\n * import { except } from 'drizzle-orm/sqlite-core'\n *\n * await except(\n * db.select({ courseName: depA.courseName }).from(depA),\n * db.select({ courseName: depB.courseName }).from(depB)\n * );\n * // or\n * await db.select({ courseName: depA.courseName })\n * .from(depA)\n * .except(\n * db.select({ courseName: depB.courseName }).from(depB)\n * );\n * ```\n */\nexport const except = createSetOperator('except', false);\n", "import { entityKind } from '~/entity.ts';\nimport type { SQL, SQLWrapper } from '~/sql/index.ts';\n\nexport abstract class TypedQueryBuilder implements SQLWrapper {\n\tstatic readonly [entityKind]: string = 'TypedQueryBuilder';\n\n\tdeclare _: {\n\t\tselectedFields: TSelection;\n\t\tresult: TResult;\n\t\tconfig?: TConfig;\n\t};\n\n\t/** @internal */\n\tgetSelectedFields(): TSelection {\n\t\treturn this._.selectedFields;\n\t}\n\n\tabstract getSQL(): SQL;\n}\n", "import type { GetColumnData } from '~/column.ts';\nimport { entityKind, is } from '~/entity.ts';\nimport type { JoinType, SelectResultFields } from '~/query-builders/select.types.ts';\nimport { QueryPromise } from '~/query-promise.ts';\nimport type { RunnableQuery } from '~/runnable-query.ts';\nimport { SelectionProxyHandler } from '~/selection-proxy.ts';\nimport type { Placeholder, Query, SQL, SQLWrapper } from '~/sql/sql.ts';\nimport type { SQLiteDialect } from '~/sqlite-core/dialect.ts';\nimport type { SQLitePreparedQuery, SQLiteSession } from '~/sqlite-core/session.ts';\nimport { SQLiteTable } from '~/sqlite-core/table.ts';\nimport { Subquery } from '~/subquery.ts';\nimport { Table } from '~/table.ts';\nimport {\n\ttype DrizzleTypeError,\n\tgetTableLikeName,\n\tmapUpdateSet,\n\torderSelectedFields,\n\ttype UpdateSet,\n\ttype ValueOrArray,\n} from '~/utils.ts';\nimport { ViewBaseConfig } from '~/view-common.ts';\nimport type { SQLiteColumn } from '../columns/common.ts';\nimport { extractUsedTable } from '../utils.ts';\nimport { SQLiteViewBase } from '../view-base.ts';\nimport type { SelectedFields, SelectedFieldsOrdered, SQLiteSelectJoinConfig } from './select.types.ts';\n\nexport interface SQLiteUpdateConfig {\n\twhere?: SQL | undefined;\n\tlimit?: number | Placeholder;\n\torderBy?: (SQLiteColumn | SQL | SQL.Aliased)[];\n\tset: UpdateSet;\n\ttable: SQLiteTable;\n\tfrom?: SQLiteTable | Subquery | SQLiteViewBase | SQL;\n\tjoins: SQLiteSelectJoinConfig[];\n\treturning?: SelectedFieldsOrdered;\n\twithList?: Subquery[];\n}\n\nexport type SQLiteUpdateSetSource =\n\t& {\n\t\t[Key in keyof TTable['$inferInsert']]?:\n\t\t\t| GetColumnData\n\t\t\t| SQL\n\t\t\t| SQLiteColumn\n\t\t\t| undefined;\n\t}\n\t& {};\n\nexport class SQLiteUpdateBuilder<\n\tTTable extends SQLiteTable,\n\tTResultType extends 'sync' | 'async',\n\tTRunResult,\n> {\n\tstatic readonly [entityKind]: string = 'SQLiteUpdateBuilder';\n\n\tdeclare readonly _: {\n\t\treadonly table: TTable;\n\t};\n\n\tconstructor(\n\t\tprotected table: TTable,\n\t\tprotected session: SQLiteSession,\n\t\tprotected dialect: SQLiteDialect,\n\t\tprivate withList?: Subquery[],\n\t) {}\n\n\tset(\n\t\tvalues: SQLiteUpdateSetSource,\n\t): SQLiteUpdateWithout<\n\t\tSQLiteUpdateBase,\n\t\tfalse,\n\t\t'leftJoin' | 'rightJoin' | 'innerJoin' | 'fullJoin'\n\t> {\n\t\treturn new SQLiteUpdateBase(\n\t\t\tthis.table,\n\t\t\tmapUpdateSet(this.table, values),\n\t\t\tthis.session,\n\t\t\tthis.dialect,\n\t\t\tthis.withList,\n\t\t) as any;\n\t}\n}\n\nexport type SQLiteUpdateWithout<\n\tT extends AnySQLiteUpdate,\n\tTDynamic extends boolean,\n\tK extends keyof T & string,\n> = TDynamic extends true ? T : Omit<\n\tSQLiteUpdateBase<\n\t\tT['_']['table'],\n\t\tT['_']['resultType'],\n\t\tT['_']['runResult'],\n\t\tT['_']['from'],\n\t\tT['_']['returning'],\n\t\tTDynamic,\n\t\tT['_']['excludedMethods'] | K\n\t>,\n\tT['_']['excludedMethods'] | K\n>;\n\nexport type SQLiteUpdateWithJoins<\n\tT extends AnySQLiteUpdate,\n\tTDynamic extends boolean,\n\tTFrom extends SQLiteTable | Subquery | SQLiteViewBase | SQL,\n> = TDynamic extends true ? T : Omit<\n\tSQLiteUpdateBase<\n\t\tT['_']['table'],\n\t\tT['_']['resultType'],\n\t\tT['_']['runResult'],\n\t\tTFrom,\n\t\tT['_']['returning'],\n\t\tTDynamic,\n\t\tExclude\n\t>,\n\tExclude\n>;\n\nexport type SQLiteUpdateReturningAll = SQLiteUpdateWithout<\n\tSQLiteUpdateBase<\n\t\tT['_']['table'],\n\t\tT['_']['resultType'],\n\t\tT['_']['runResult'],\n\t\tT['_']['from'],\n\t\tT['_']['table']['$inferSelect'],\n\t\tTDynamic,\n\t\tT['_']['excludedMethods']\n\t>,\n\tTDynamic,\n\t'returning'\n>;\n\nexport type SQLiteUpdateReturning<\n\tT extends AnySQLiteUpdate,\n\tTDynamic extends boolean,\n\tTSelectedFields extends SelectedFields,\n> = SQLiteUpdateWithout<\n\tSQLiteUpdateBase<\n\t\tT['_']['table'],\n\t\tT['_']['resultType'],\n\t\tT['_']['runResult'],\n\t\tT['_']['from'],\n\t\tSelectResultFields,\n\t\tTDynamic,\n\t\tT['_']['excludedMethods']\n\t>,\n\tTDynamic,\n\t'returning'\n>;\n\nexport type SQLiteUpdateExecute = T['_']['returning'] extends undefined ? T['_']['runResult']\n\t: T['_']['returning'][];\n\nexport type SQLiteUpdatePrepare = SQLitePreparedQuery<\n\t{\n\t\ttype: T['_']['resultType'];\n\t\trun: T['_']['runResult'];\n\t\tall: T['_']['returning'] extends undefined ? DrizzleTypeError<'.all() cannot be used without .returning()'>\n\t\t\t: T['_']['returning'][];\n\t\tget: T['_']['returning'] extends undefined ? DrizzleTypeError<'.get() cannot be used without .returning()'>\n\t\t\t: T['_']['returning'];\n\t\tvalues: T['_']['returning'] extends undefined ? DrizzleTypeError<'.values() cannot be used without .returning()'>\n\t\t\t: any[][];\n\t\texecute: SQLiteUpdateExecute;\n\t}\n>;\n\nexport type SQLiteUpdateJoinFn<\n\tT extends AnySQLiteUpdate,\n> = <\n\tTJoinedTable extends SQLiteTable | Subquery | SQLiteViewBase | SQL,\n>(\n\ttable: TJoinedTable,\n\ton:\n\t\t| (\n\t\t\t(\n\t\t\t\tupdateTable: T['_']['table']['_']['columns'],\n\t\t\t\tfrom: T['_']['from'] extends SQLiteTable ? T['_']['from']['_']['columns']\n\t\t\t\t\t: T['_']['from'] extends Subquery | SQLiteViewBase ? T['_']['from']['_']['selectedFields']\n\t\t\t\t\t: never,\n\t\t\t) => SQL | undefined\n\t\t)\n\t\t| SQL\n\t\t| undefined,\n) => T;\n\nexport type SQLiteUpdateDynamic = SQLiteUpdate<\n\tT['_']['table'],\n\tT['_']['resultType'],\n\tT['_']['runResult'],\n\tT['_']['returning']\n>;\n\nexport type SQLiteUpdate<\n\tTTable extends SQLiteTable = SQLiteTable,\n\tTResultType extends 'sync' | 'async' = 'sync' | 'async',\n\tTRunResult = any,\n\tTFrom extends SQLiteTable | Subquery | SQLiteViewBase | SQL | undefined = undefined,\n\tTReturning extends Record | undefined = Record | undefined,\n> = SQLiteUpdateBase;\n\nexport type AnySQLiteUpdate = SQLiteUpdateBase;\n\nexport interface SQLiteUpdateBase<\n\tTTable extends SQLiteTable = SQLiteTable,\n\tTResultType extends 'sync' | 'async' = 'sync' | 'async',\n\tTRunResult = unknown,\n\tTFrom extends SQLiteTable | Subquery | SQLiteViewBase | SQL | undefined = undefined,\n\tTReturning = undefined,\n\tTDynamic extends boolean = false,\n\tTExcludedMethods extends string = never,\n> extends SQLWrapper, QueryPromise {\n\treadonly _: {\n\t\treadonly dialect: 'sqlite';\n\t\treadonly table: TTable;\n\t\treadonly resultType: TResultType;\n\t\treadonly runResult: TRunResult;\n\t\treadonly from: TFrom;\n\t\treadonly returning: TReturning;\n\t\treadonly dynamic: TDynamic;\n\t\treadonly excludedMethods: TExcludedMethods;\n\t\treadonly result: TReturning extends undefined ? TRunResult : TReturning[];\n\t};\n}\n\nexport class SQLiteUpdateBase<\n\tTTable extends SQLiteTable = SQLiteTable,\n\t// eslint-disable-next-line @typescript-eslint/no-unused-vars\n\tTResultType extends 'sync' | 'async' = 'sync' | 'async',\n\tTRunResult = unknown,\n\tTFrom extends SQLiteTable | Subquery | SQLiteViewBase | SQL | undefined = undefined,\n\tTReturning = undefined,\n\t// eslint-disable-next-line @typescript-eslint/no-unused-vars\n\tTDynamic extends boolean = false,\n\t// eslint-disable-next-line @typescript-eslint/no-unused-vars\n\tTExcludedMethods extends string = never,\n> extends QueryPromise\n\timplements RunnableQuery, SQLWrapper\n{\n\tstatic override readonly [entityKind]: string = 'SQLiteUpdate';\n\n\t/** @internal */\n\tconfig: SQLiteUpdateConfig;\n\n\tconstructor(\n\t\ttable: TTable,\n\t\tset: UpdateSet,\n\t\tprivate session: SQLiteSession,\n\t\tprivate dialect: SQLiteDialect,\n\t\twithList?: Subquery[],\n\t) {\n\t\tsuper();\n\t\tthis.config = { set, table, withList, joins: [] };\n\t}\n\n\tfrom(\n\t\tsource: TFrom,\n\t): SQLiteUpdateWithJoins {\n\t\tthis.config.from = source;\n\t\treturn this as any;\n\t}\n\n\tprivate createJoin(\n\t\tjoinType: TJoinType,\n\t): SQLiteUpdateJoinFn {\n\t\treturn ((\n\t\t\ttable: SQLiteTable | Subquery | SQLiteViewBase | SQL,\n\t\t\ton: ((updateTable: TTable, from: TFrom) => SQL | undefined) | SQL | undefined,\n\t\t) => {\n\t\t\tconst tableName = getTableLikeName(table);\n\n\t\t\tif (typeof tableName === 'string' && this.config.joins.some((join) => join.alias === tableName)) {\n\t\t\t\tthrow new Error(`Alias \"${tableName}\" is already used in this query`);\n\t\t\t}\n\n\t\t\tif (typeof on === 'function') {\n\t\t\t\tconst from = this.config.from\n\t\t\t\t\t? is(table, SQLiteTable)\n\t\t\t\t\t\t? table[Table.Symbol.Columns]\n\t\t\t\t\t\t: is(table, Subquery)\n\t\t\t\t\t\t? table._.selectedFields\n\t\t\t\t\t\t: is(table, SQLiteViewBase)\n\t\t\t\t\t\t? table[ViewBaseConfig].selectedFields\n\t\t\t\t\t\t: undefined\n\t\t\t\t\t: undefined;\n\t\t\t\ton = on(\n\t\t\t\t\tnew Proxy(\n\t\t\t\t\t\tthis.config.table[Table.Symbol.Columns],\n\t\t\t\t\t\tnew SelectionProxyHandler({ sqlAliasedBehavior: 'sql', sqlBehavior: 'sql' }),\n\t\t\t\t\t) as any,\n\t\t\t\t\tfrom && new Proxy(\n\t\t\t\t\t\tfrom,\n\t\t\t\t\t\tnew SelectionProxyHandler({ sqlAliasedBehavior: 'sql', sqlBehavior: 'sql' }),\n\t\t\t\t\t) as any,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tthis.config.joins.push({ on, table, joinType, alias: tableName });\n\n\t\t\treturn this as any;\n\t\t}) as any;\n\t}\n\n\tleftJoin = this.createJoin('left');\n\n\trightJoin = this.createJoin('right');\n\n\tinnerJoin = this.createJoin('inner');\n\n\tfullJoin = this.createJoin('full');\n\n\t/**\n\t * Adds a 'where' clause to the query.\n\t *\n\t * Calling this method will update only those rows that fulfill a specified condition.\n\t *\n\t * See docs: {@link https://orm.drizzle.team/docs/update}\n\t *\n\t * @param where the 'where' clause.\n\t *\n\t * @example\n\t * You can use conditional operators and `sql function` to filter the rows to be updated.\n\t *\n\t * ```ts\n\t * // Update all cars with green color\n\t * db.update(cars).set({ color: 'red' })\n\t * .where(eq(cars.color, 'green'));\n\t * // or\n\t * db.update(cars).set({ color: 'red' })\n\t * .where(sql`${cars.color} = 'green'`)\n\t * ```\n\t *\n\t * You can logically combine conditional operators with `and()` and `or()` operators:\n\t *\n\t * ```ts\n\t * // Update all BMW cars with a green color\n\t * db.update(cars).set({ color: 'red' })\n\t * .where(and(eq(cars.color, 'green'), eq(cars.brand, 'BMW')));\n\t *\n\t * // Update all cars with the green or blue color\n\t * db.update(cars).set({ color: 'red' })\n\t * .where(or(eq(cars.color, 'green'), eq(cars.color, 'blue')));\n\t * ```\n\t */\n\twhere(where: SQL | undefined): SQLiteUpdateWithout {\n\t\tthis.config.where = where;\n\t\treturn this as any;\n\t}\n\n\torderBy(\n\t\tbuilder: (updateTable: TTable) => ValueOrArray,\n\t): SQLiteUpdateWithout;\n\torderBy(...columns: (SQLiteColumn | SQL | SQL.Aliased)[]): SQLiteUpdateWithout;\n\torderBy(\n\t\t...columns:\n\t\t\t| [(updateTable: TTable) => ValueOrArray]\n\t\t\t| (SQLiteColumn | SQL | SQL.Aliased)[]\n\t): SQLiteUpdateWithout {\n\t\tif (typeof columns[0] === 'function') {\n\t\t\tconst orderBy = columns[0](\n\t\t\t\tnew Proxy(\n\t\t\t\t\tthis.config.table[Table.Symbol.Columns],\n\t\t\t\t\tnew SelectionProxyHandler({ sqlAliasedBehavior: 'alias', sqlBehavior: 'sql' }),\n\t\t\t\t) as any,\n\t\t\t);\n\n\t\t\tconst orderByArray = Array.isArray(orderBy) ? orderBy : [orderBy];\n\t\t\tthis.config.orderBy = orderByArray;\n\t\t} else {\n\t\t\tconst orderByArray = columns as (SQLiteColumn | SQL | SQL.Aliased)[];\n\t\t\tthis.config.orderBy = orderByArray;\n\t\t}\n\t\treturn this as any;\n\t}\n\n\tlimit(limit: number | Placeholder): SQLiteUpdateWithout {\n\t\tthis.config.limit = limit;\n\t\treturn this as any;\n\t}\n\n\t/**\n\t * Adds a `returning` clause to the query.\n\t *\n\t * Calling this method will return the specified fields of the updated rows. If no fields are specified, all fields will be returned.\n\t *\n\t * See docs: {@link https://orm.drizzle.team/docs/update#update-with-returning}\n\t *\n\t * @example\n\t * ```ts\n\t * // Update all cars with the green color and return all fields\n\t * const updatedCars: Car[] = await db.update(cars)\n\t * .set({ color: 'red' })\n\t * .where(eq(cars.color, 'green'))\n\t * .returning();\n\t *\n\t * // Update all cars with the green color and return only their id and brand fields\n\t * const updatedCarsIdsAndBrands: { id: number, brand: string }[] = await db.update(cars)\n\t * .set({ color: 'red' })\n\t * .where(eq(cars.color, 'green'))\n\t * .returning({ id: cars.id, brand: cars.brand });\n\t * ```\n\t */\n\treturning(): SQLiteUpdateReturningAll;\n\treturning(\n\t\tfields: TSelectedFields,\n\t): SQLiteUpdateReturning;\n\treturning(\n\t\tfields: SelectedFields = this.config.table[SQLiteTable.Symbol.Columns],\n\t): SQLiteUpdateWithout {\n\t\tthis.config.returning = orderSelectedFields(fields);\n\t\treturn this as any;\n\t}\n\n\t/** @internal */\n\tgetSQL(): SQL {\n\t\treturn this.dialect.buildUpdateQuery(this.config);\n\t}\n\n\ttoSQL(): Query {\n\t\tconst { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());\n\t\treturn rest;\n\t}\n\n\t/** @internal */\n\t_prepare(isOneTimeQuery = true): SQLiteUpdatePrepare {\n\t\treturn this.session[isOneTimeQuery ? 'prepareOneTimeQuery' : 'prepareQuery'](\n\t\t\tthis.dialect.sqlToQuery(this.getSQL()),\n\t\t\tthis.config.returning,\n\t\t\tthis.config.returning ? 'all' : 'run',\n\t\t\ttrue,\n\t\t\tundefined,\n\t\t\t{\n\t\t\t\ttype: 'insert',\n\t\t\t\ttables: extractUsedTable(this.config.table),\n\t\t\t},\n\t\t) as SQLiteUpdatePrepare;\n\t}\n\n\tprepare(): SQLiteUpdatePrepare {\n\t\treturn this._prepare(false);\n\t}\n\n\trun: ReturnType['run'] = (placeholderValues) => {\n\t\treturn this._prepare().run(placeholderValues);\n\t};\n\n\tall: ReturnType['all'] = (placeholderValues) => {\n\t\treturn this._prepare().all(placeholderValues);\n\t};\n\n\tget: ReturnType['get'] = (placeholderValues) => {\n\t\treturn this._prepare().get(placeholderValues);\n\t};\n\n\tvalues: ReturnType['values'] = (placeholderValues) => {\n\t\treturn this._prepare().values(placeholderValues);\n\t};\n\n\toverride async execute(): Promise> {\n\t\treturn (this.config.returning ? this.all() : this.run()) as SQLiteUpdateExecute;\n\t}\n\n\t$dynamic(): SQLiteUpdateDynamic {\n\t\treturn this as any;\n\t}\n}\n", "import { entityKind } from '~/entity.ts';\nimport { SQL, sql, type SQLWrapper } from '~/sql/sql.ts';\nimport type { SQLiteSession } from '../session.ts';\nimport type { SQLiteTable } from '../table.ts';\nimport type { SQLiteView } from '../view.ts';\n\nexport class SQLiteCountBuilder<\n\tTSession extends SQLiteSession,\n> extends SQL implements Promise, SQLWrapper {\n\tprivate sql: SQL;\n\n\tstatic override readonly [entityKind] = 'SQLiteCountBuilderAsync';\n\t[Symbol.toStringTag] = 'SQLiteCountBuilderAsync';\n\n\tprivate session: TSession;\n\n\tprivate static buildEmbeddedCount(\n\t\tsource: SQLiteTable | SQLiteView | SQL | SQLWrapper,\n\t\tfilters?: SQL,\n\t): SQL {\n\t\treturn sql`(select count(*) from ${source}${sql.raw(' where ').if(filters)}${filters})`;\n\t}\n\n\tprivate static buildCount(\n\t\tsource: SQLiteTable | SQLiteView | SQL | SQLWrapper,\n\t\tfilters?: SQL,\n\t): SQL {\n\t\treturn sql`select count(*) from ${source}${sql.raw(' where ').if(filters)}${filters}`;\n\t}\n\n\tconstructor(\n\t\treadonly params: {\n\t\t\tsource: SQLiteTable | SQLiteView | SQL | SQLWrapper;\n\t\t\tfilters?: SQL;\n\t\t\tsession: TSession;\n\t\t},\n\t) {\n\t\tsuper(SQLiteCountBuilder.buildEmbeddedCount(params.source, params.filters).queryChunks);\n\n\t\tthis.session = params.session;\n\n\t\tthis.sql = SQLiteCountBuilder.buildCount(\n\t\t\tparams.source,\n\t\t\tparams.filters,\n\t\t);\n\t}\n\n\tthen(\n\t\tonfulfilled?: ((value: number) => TResult1 | PromiseLike) | null | undefined,\n\t\tonrejected?: ((reason: any) => TResult2 | PromiseLike) | null | undefined,\n\t): Promise {\n\t\treturn Promise.resolve(this.session.count(this.sql)).then(\n\t\t\tonfulfilled,\n\t\t\tonrejected,\n\t\t);\n\t}\n\n\tcatch(\n\t\tonRejected?: ((reason: any) => never | PromiseLike) | null | undefined,\n\t): Promise {\n\t\treturn this.then(undefined, onRejected);\n\t}\n\n\tfinally(onFinally?: (() => void) | null | undefined): Promise {\n\t\treturn this.then(\n\t\t\t(value) => {\n\t\t\t\tonFinally?.();\n\t\t\t\treturn value;\n\t\t\t},\n\t\t\t(reason) => {\n\t\t\t\tonFinally?.();\n\t\t\t\tthrow reason;\n\t\t\t},\n\t\t);\n\t}\n}\n", "import { entityKind } from '~/entity.ts';\nimport { QueryPromise } from '~/query-promise.ts';\nimport {\n\ttype BuildQueryResult,\n\ttype BuildRelationalQueryResult,\n\ttype DBQueryConfig,\n\tmapRelationalRow,\n\ttype TableRelationalConfig,\n\ttype TablesRelationalConfig,\n} from '~/relations.ts';\nimport type { RunnableQuery } from '~/runnable-query.ts';\nimport type { Query, QueryWithTypings, SQL, SQLWrapper } from '~/sql/sql.ts';\nimport type { KnownKeysOnly } from '~/utils.ts';\nimport type { SQLiteDialect } from '../dialect.ts';\nimport type { PreparedQueryConfig, SQLitePreparedQuery, SQLiteSession } from '../session.ts';\nimport type { SQLiteTable } from '../table.ts';\n\nexport type SQLiteRelationalQueryKind = TMode extends 'async'\n\t? SQLiteRelationalQuery\n\t: SQLiteSyncRelationalQuery;\n\nexport class RelationalQueryBuilder<\n\tTMode extends 'sync' | 'async',\n\tTFullSchema extends Record,\n\tTSchema extends TablesRelationalConfig,\n\tTFields extends TableRelationalConfig,\n> {\n\tstatic readonly [entityKind]: string = 'SQLiteAsyncRelationalQueryBuilder';\n\n\tconstructor(\n\t\tprotected mode: TMode,\n\t\tprotected fullSchema: Record,\n\t\tprotected schema: TSchema,\n\t\tprotected tableNamesMap: Record,\n\t\tprotected table: SQLiteTable,\n\t\tprotected tableConfig: TableRelationalConfig,\n\t\tprotected dialect: SQLiteDialect,\n\t\tprotected session: SQLiteSession<'async', unknown, TFullSchema, TSchema>,\n\t) {}\n\n\tfindMany>(\n\t\tconfig?: KnownKeysOnly>,\n\t): SQLiteRelationalQueryKind[]> {\n\t\treturn (this.mode === 'sync'\n\t\t\t? new SQLiteSyncRelationalQuery(\n\t\t\t\tthis.fullSchema,\n\t\t\t\tthis.schema,\n\t\t\t\tthis.tableNamesMap,\n\t\t\t\tthis.table,\n\t\t\t\tthis.tableConfig,\n\t\t\t\tthis.dialect,\n\t\t\t\tthis.session,\n\t\t\t\tconfig ? (config as DBQueryConfig<'many', true>) : {},\n\t\t\t\t'many',\n\t\t\t)\n\t\t\t: new SQLiteRelationalQuery(\n\t\t\t\tthis.fullSchema,\n\t\t\t\tthis.schema,\n\t\t\t\tthis.tableNamesMap,\n\t\t\t\tthis.table,\n\t\t\t\tthis.tableConfig,\n\t\t\t\tthis.dialect,\n\t\t\t\tthis.session,\n\t\t\t\tconfig ? (config as DBQueryConfig<'many', true>) : {},\n\t\t\t\t'many',\n\t\t\t)) as SQLiteRelationalQueryKind[]>;\n\t}\n\n\tfindFirst, 'limit'>>(\n\t\tconfig?: KnownKeysOnly, 'limit'>>,\n\t): SQLiteRelationalQueryKind | undefined> {\n\t\treturn (this.mode === 'sync'\n\t\t\t? new SQLiteSyncRelationalQuery(\n\t\t\t\tthis.fullSchema,\n\t\t\t\tthis.schema,\n\t\t\t\tthis.tableNamesMap,\n\t\t\t\tthis.table,\n\t\t\t\tthis.tableConfig,\n\t\t\t\tthis.dialect,\n\t\t\t\tthis.session,\n\t\t\t\tconfig ? { ...(config as DBQueryConfig<'many', true> | undefined), limit: 1 } : { limit: 1 },\n\t\t\t\t'first',\n\t\t\t)\n\t\t\t: new SQLiteRelationalQuery(\n\t\t\t\tthis.fullSchema,\n\t\t\t\tthis.schema,\n\t\t\t\tthis.tableNamesMap,\n\t\t\t\tthis.table,\n\t\t\t\tthis.tableConfig,\n\t\t\t\tthis.dialect,\n\t\t\t\tthis.session,\n\t\t\t\tconfig ? { ...(config as DBQueryConfig<'many', true> | undefined), limit: 1 } : { limit: 1 },\n\t\t\t\t'first',\n\t\t\t)) as SQLiteRelationalQueryKind | undefined>;\n\t}\n}\n\nexport class SQLiteRelationalQuery extends QueryPromise\n\timplements RunnableQuery, SQLWrapper\n{\n\tstatic override readonly [entityKind]: string = 'SQLiteAsyncRelationalQuery';\n\n\tdeclare readonly _: {\n\t\treadonly dialect: 'sqlite';\n\t\treadonly type: TType;\n\t\treadonly result: TResult;\n\t};\n\n\t/** @internal */\n\tmode: 'many' | 'first';\n\n\tconstructor(\n\t\tprivate fullSchema: Record,\n\t\tprivate schema: TablesRelationalConfig,\n\t\tprivate tableNamesMap: Record,\n\t\t/** @internal */\n\t\tpublic table: SQLiteTable,\n\t\tprivate tableConfig: TableRelationalConfig,\n\t\tprivate dialect: SQLiteDialect,\n\t\tprivate session: SQLiteSession<'sync' | 'async', unknown, Record, TablesRelationalConfig>,\n\t\tprivate config: DBQueryConfig<'many', true> | true,\n\t\tmode: 'many' | 'first',\n\t) {\n\t\tsuper();\n\t\tthis.mode = mode;\n\t}\n\n\t/** @internal */\n\tgetSQL(): SQL {\n\t\treturn this.dialect.buildRelationalQuery({\n\t\t\tfullSchema: this.fullSchema,\n\t\t\tschema: this.schema,\n\t\t\ttableNamesMap: this.tableNamesMap,\n\t\t\ttable: this.table,\n\t\t\ttableConfig: this.tableConfig,\n\t\t\tqueryConfig: this.config,\n\t\t\ttableAlias: this.tableConfig.tsName,\n\t\t}).sql as SQL;\n\t}\n\n\t/** @internal */\n\t_prepare(\n\t\tisOneTimeQuery = false,\n\t): SQLitePreparedQuery {\n\t\tconst { query, builtQuery } = this._toSQL();\n\n\t\treturn this.session[isOneTimeQuery ? 'prepareOneTimeQuery' : 'prepareQuery'](\n\t\t\tbuiltQuery,\n\t\t\tundefined,\n\t\t\tthis.mode === 'first' ? 'get' : 'all',\n\t\t\ttrue,\n\t\t\t(rawRows, mapColumnValue) => {\n\t\t\t\tconst rows = rawRows.map((row) =>\n\t\t\t\t\tmapRelationalRow(this.schema, this.tableConfig, row, query.selection, mapColumnValue)\n\t\t\t\t);\n\t\t\t\tif (this.mode === 'first') {\n\t\t\t\t\treturn rows[0] as TResult;\n\t\t\t\t}\n\t\t\t\treturn rows as TResult;\n\t\t\t},\n\t\t) as SQLitePreparedQuery;\n\t}\n\n\tprepare(): SQLitePreparedQuery {\n\t\treturn this._prepare(false);\n\t}\n\n\tprivate _toSQL(): { query: BuildRelationalQueryResult; builtQuery: QueryWithTypings } {\n\t\tconst query = this.dialect.buildRelationalQuery({\n\t\t\tfullSchema: this.fullSchema,\n\t\t\tschema: this.schema,\n\t\t\ttableNamesMap: this.tableNamesMap,\n\t\t\ttable: this.table,\n\t\t\ttableConfig: this.tableConfig,\n\t\t\tqueryConfig: this.config,\n\t\t\ttableAlias: this.tableConfig.tsName,\n\t\t});\n\n\t\tconst builtQuery = this.dialect.sqlToQuery(query.sql as SQL);\n\n\t\treturn { query, builtQuery };\n\t}\n\n\ttoSQL(): Query {\n\t\treturn this._toSQL().builtQuery;\n\t}\n\n\t/** @internal */\n\texecuteRaw(): TResult {\n\t\tif (this.mode === 'first') {\n\t\t\treturn this._prepare(false).get() as TResult;\n\t\t}\n\t\treturn this._prepare(false).all() as TResult;\n\t}\n\n\toverride async execute(): Promise {\n\t\treturn this.executeRaw();\n\t}\n}\n\nexport class SQLiteSyncRelationalQuery extends SQLiteRelationalQuery<'sync', TResult> {\n\tstatic override readonly [entityKind]: string = 'SQLiteSyncRelationalQuery';\n\n\tsync(): TResult {\n\t\treturn this.executeRaw();\n\t}\n}\n", "import { entityKind } from '~/entity.ts';\nimport { QueryPromise } from '~/query-promise.ts';\nimport type { RunnableQuery } from '~/runnable-query.ts';\nimport type { PreparedQuery } from '~/session.ts';\nimport type { SQL, SQLWrapper } from '~/sql/sql.ts';\nimport type { SQLiteAsyncDialect } from '../dialect.ts';\n\ntype SQLiteRawAction = 'all' | 'get' | 'values' | 'run';\nexport interface SQLiteRawConfig {\n\taction: SQLiteRawAction;\n}\n\nexport interface SQLiteRaw extends QueryPromise, RunnableQuery, SQLWrapper {}\n\nexport class SQLiteRaw extends QueryPromise\n\timplements RunnableQuery, SQLWrapper, PreparedQuery\n{\n\tstatic override readonly [entityKind]: string = 'SQLiteRaw';\n\n\tdeclare readonly _: {\n\t\treadonly dialect: 'sqlite';\n\t\treadonly result: TResult;\n\t};\n\n\t/** @internal */\n\tconfig: SQLiteRawConfig;\n\n\tconstructor(\n\t\tpublic execute: () => Promise,\n\t\t/** @internal */\n\t\tpublic getSQL: () => SQL,\n\t\taction: SQLiteRawAction,\n\t\tprivate dialect: SQLiteAsyncDialect,\n\t\tprivate mapBatchResult: (result: unknown) => unknown,\n\t) {\n\t\tsuper();\n\t\tthis.config = { action };\n\t}\n\n\tgetQuery() {\n\t\treturn { ...this.dialect.sqlToQuery(this.getSQL()), method: this.config.action };\n\t}\n\n\tmapResult(result: unknown, isFromBatch?: boolean) {\n\t\treturn isFromBatch ? this.mapBatchResult(result) : result;\n\t}\n\n\t_prepare(): PreparedQuery {\n\t\treturn this;\n\t}\n\n\t/** @internal */\n\tisResponseInArrayMode(): boolean {\n\t\treturn false;\n\t}\n}\n", "/// \n\nimport type { BatchItem } from '~/batch.ts';\nimport { type Cache, NoopCache } from '~/cache/core/index.ts';\nimport type { WithCacheConfig } from '~/cache/core/types.ts';\nimport { entityKind } from '~/entity.ts';\nimport type { Logger } from '~/logger.ts';\nimport { NoopLogger } from '~/logger.ts';\nimport type { RelationalSchemaConfig, TablesRelationalConfig } from '~/relations.ts';\nimport type { PreparedQuery } from '~/session.ts';\nimport { fillPlaceholders, type Query, sql } from '~/sql/sql.ts';\nimport type { SQLiteAsyncDialect } from '~/sqlite-core/dialect.ts';\nimport { SQLiteTransaction } from '~/sqlite-core/index.ts';\nimport type { SelectedFieldsOrdered } from '~/sqlite-core/query-builders/select.types.ts';\nimport type {\n\tPreparedQueryConfig as PreparedQueryConfigBase,\n\tSQLiteExecuteMethod,\n\tSQLiteTransactionConfig,\n} from '~/sqlite-core/session.ts';\nimport { SQLitePreparedQuery, SQLiteSession } from '~/sqlite-core/session.ts';\nimport { mapResultRow } from '~/utils.ts';\n\nexport interface SQLiteD1SessionOptions {\n\tlogger?: Logger;\n\tcache?: Cache;\n}\n\ntype PreparedQueryConfig = Omit;\n\nexport class SQLiteD1Session<\n\tTFullSchema extends Record,\n\tTSchema extends TablesRelationalConfig,\n> extends SQLiteSession<'async', D1Result, TFullSchema, TSchema> {\n\tstatic override readonly [entityKind]: string = 'SQLiteD1Session';\n\n\tprivate logger: Logger;\n\tprivate cache: Cache;\n\n\tconstructor(\n\t\tprivate client: D1Database,\n\t\tdialect: SQLiteAsyncDialect,\n\t\tprivate schema: RelationalSchemaConfig | undefined,\n\t\tprivate options: SQLiteD1SessionOptions = {},\n\t) {\n\t\tsuper(dialect);\n\t\tthis.logger = options.logger ?? new NoopLogger();\n\t\tthis.cache = options.cache ?? new NoopCache();\n\t}\n\n\tprepareQuery(\n\t\tquery: Query,\n\t\tfields: SelectedFieldsOrdered | undefined,\n\t\texecuteMethod: SQLiteExecuteMethod,\n\t\tisResponseInArrayMode: boolean,\n\t\tcustomResultMapper?: (rows: unknown[][]) => unknown,\n\t\tqueryMetadata?: {\n\t\t\ttype: 'select' | 'update' | 'delete' | 'insert';\n\t\t\ttables: string[];\n\t\t},\n\t\tcacheConfig?: WithCacheConfig,\n\t): D1PreparedQuery {\n\t\tconst stmt = this.client.prepare(query.sql);\n\t\treturn new D1PreparedQuery(\n\t\t\tstmt,\n\t\t\tquery,\n\t\t\tthis.logger,\n\t\t\tthis.cache,\n\t\t\tqueryMetadata,\n\t\t\tcacheConfig,\n\t\t\tfields,\n\t\t\texecuteMethod,\n\t\t\tisResponseInArrayMode,\n\t\t\tcustomResultMapper,\n\t\t);\n\t}\n\n\tasync batch[] | readonly BatchItem<'sqlite'>[]>(queries: T) {\n\t\tconst preparedQueries: PreparedQuery[] = [];\n\t\tconst builtQueries: D1PreparedStatement[] = [];\n\n\t\tfor (const query of queries) {\n\t\t\tconst preparedQuery = query._prepare();\n\t\t\tconst builtQuery = preparedQuery.getQuery();\n\t\t\tpreparedQueries.push(preparedQuery);\n\t\t\tif (builtQuery.params.length > 0) {\n\t\t\t\tbuiltQueries.push((preparedQuery as D1PreparedQuery).stmt.bind(...builtQuery.params));\n\t\t\t} else {\n\t\t\t\tconst builtQuery = preparedQuery.getQuery();\n\t\t\t\tbuiltQueries.push(\n\t\t\t\t\tthis.client.prepare(builtQuery.sql).bind(...builtQuery.params),\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\tconst batchResults = await this.client.batch(builtQueries);\n\t\treturn batchResults.map((result, i) => preparedQueries[i]!.mapResult(result, true));\n\t}\n\n\toverride extractRawAllValueFromBatchResult(result: unknown): unknown {\n\t\treturn (result as D1Result).results;\n\t}\n\n\toverride extractRawGetValueFromBatchResult(result: unknown): unknown {\n\t\treturn (result as D1Result).results[0];\n\t}\n\n\toverride extractRawValuesValueFromBatchResult(result: unknown): unknown {\n\t\treturn d1ToRawMapping((result as D1Result).results);\n\t}\n\n\toverride async transaction(\n\t\ttransaction: (tx: D1Transaction) => T | Promise,\n\t\tconfig?: SQLiteTransactionConfig,\n\t): Promise {\n\t\tconst tx = new D1Transaction('async', this.dialect, this, this.schema);\n\t\tawait this.run(sql.raw(`begin${config?.behavior ? ' ' + config.behavior : ''}`));\n\t\ttry {\n\t\t\tconst result = await transaction(tx);\n\t\t\tawait this.run(sql`commit`);\n\t\t\treturn result;\n\t\t} catch (err) {\n\t\t\tawait this.run(sql`rollback`);\n\t\t\tthrow err;\n\t\t}\n\t}\n}\n\nexport class D1Transaction<\n\tTFullSchema extends Record,\n\tTSchema extends TablesRelationalConfig,\n> extends SQLiteTransaction<'async', D1Result, TFullSchema, TSchema> {\n\tstatic override readonly [entityKind]: string = 'D1Transaction';\n\n\toverride async transaction(transaction: (tx: D1Transaction) => Promise): Promise {\n\t\tconst savepointName = `sp${this.nestedIndex}`;\n\t\tconst tx = new D1Transaction('async', this.dialect, this.session, this.schema, this.nestedIndex + 1);\n\t\tawait this.session.run(sql.raw(`savepoint ${savepointName}`));\n\t\ttry {\n\t\t\tconst result = await transaction(tx);\n\t\t\tawait this.session.run(sql.raw(`release savepoint ${savepointName}`));\n\t\t\treturn result;\n\t\t} catch (err) {\n\t\t\tawait this.session.run(sql.raw(`rollback to savepoint ${savepointName}`));\n\t\t\tthrow err;\n\t\t}\n\t}\n}\n\n/**\n * This function was taken from the D1 implementation: https://github.com/cloudflare/workerd/blob/4aae9f4c7ae30a59a88ca868c4aff88bda85c956/src/cloudflare/internal/d1-api.ts#L287\n * It may cause issues with duplicated column names in join queries, which should be fixed on the D1 side.\n * @param results\n * @returns\n */\nfunction d1ToRawMapping(results: any) {\n\tconst rows: unknown[][] = [];\n\tfor (const row of results) {\n\t\tconst entry = Object.keys(row).map((k) => row[k]);\n\t\trows.push(entry);\n\t}\n\treturn rows;\n}\n\nexport class D1PreparedQuery extends SQLitePreparedQuery<\n\t{ type: 'async'; run: D1Response; all: T['all']; get: T['get']; values: T['values']; execute: T['execute'] }\n> {\n\tstatic override readonly [entityKind]: string = 'D1PreparedQuery';\n\n\t/** @internal */\n\tcustomResultMapper?: (rows: unknown[][], mapColumnValue?: (value: unknown) => unknown) => unknown;\n\n\t/** @internal */\n\tfields?: SelectedFieldsOrdered;\n\n\t/** @internal */\n\tstmt: D1PreparedStatement;\n\n\tconstructor(\n\t\tstmt: D1PreparedStatement,\n\t\tquery: Query,\n\t\tprivate logger: Logger,\n\t\tcache: Cache,\n\t\tqueryMetadata: {\n\t\t\ttype: 'select' | 'update' | 'delete' | 'insert';\n\t\t\ttables: string[];\n\t\t} | undefined,\n\t\tcacheConfig: WithCacheConfig | undefined,\n\t\tfields: SelectedFieldsOrdered | undefined,\n\t\texecuteMethod: SQLiteExecuteMethod,\n\t\tprivate _isResponseInArrayMode: boolean,\n\t\tcustomResultMapper?: (rows: unknown[][]) => unknown,\n\t) {\n\t\tsuper('async', executeMethod, query, cache, queryMetadata, cacheConfig);\n\t\tthis.customResultMapper = customResultMapper;\n\t\tthis.fields = fields;\n\t\tthis.stmt = stmt;\n\t}\n\n\tasync run(placeholderValues?: Record): Promise {\n\t\tconst params = fillPlaceholders(this.query.params, placeholderValues ?? {});\n\t\tthis.logger.logQuery(this.query.sql, params);\n\t\treturn await this.queryWithCache(this.query.sql, params, async () => {\n\t\t\treturn this.stmt.bind(...params).run();\n\t\t});\n\t}\n\n\tasync all(placeholderValues?: Record): Promise {\n\t\tconst { fields, query, logger, stmt, customResultMapper } = this;\n\t\tif (!fields && !customResultMapper) {\n\t\t\tconst params = fillPlaceholders(query.params, placeholderValues ?? {});\n\t\t\tlogger.logQuery(query.sql, params);\n\t\t\treturn await this.queryWithCache(query.sql, params, async () => {\n\t\t\t\treturn stmt.bind(...params).all().then(({ results }) => this.mapAllResult(results!));\n\t\t\t});\n\t\t}\n\n\t\tconst rows = await this.values(placeholderValues);\n\n\t\treturn this.mapAllResult(rows);\n\t}\n\n\toverride mapAllResult(rows: unknown, isFromBatch?: boolean): unknown {\n\t\tif (isFromBatch) {\n\t\t\trows = d1ToRawMapping((rows as D1Result).results);\n\t\t}\n\n\t\tif (!this.fields && !this.customResultMapper) {\n\t\t\treturn rows;\n\t\t}\n\n\t\tif (this.customResultMapper) {\n\t\t\treturn this.customResultMapper(rows as unknown[][]);\n\t\t}\n\n\t\treturn (rows as unknown[][]).map((row) => mapResultRow(this.fields!, row, this.joinsNotNullableMap));\n\t}\n\n\tasync get(placeholderValues?: Record): Promise {\n\t\tconst { fields, joinsNotNullableMap, query, logger, stmt, customResultMapper } = this;\n\t\tif (!fields && !customResultMapper) {\n\t\t\tconst params = fillPlaceholders(query.params, placeholderValues ?? {});\n\t\t\tlogger.logQuery(query.sql, params);\n\t\t\treturn await this.queryWithCache(query.sql, params, async () => {\n\t\t\t\treturn stmt.bind(...params).all().then(({ results }) => results![0]);\n\t\t\t});\n\t\t}\n\n\t\tconst rows = await this.values(placeholderValues);\n\n\t\tif (!rows[0]) {\n\t\t\treturn undefined;\n\t\t}\n\n\t\tif (customResultMapper) {\n\t\t\treturn customResultMapper(rows) as T['all'];\n\t\t}\n\n\t\treturn mapResultRow(fields!, rows[0], joinsNotNullableMap);\n\t}\n\n\toverride mapGetResult(result: unknown, isFromBatch?: boolean): unknown {\n\t\tif (isFromBatch) {\n\t\t\tresult = d1ToRawMapping((result as D1Result).results)[0];\n\t\t}\n\n\t\tif (!this.fields && !this.customResultMapper) {\n\t\t\treturn result;\n\t\t}\n\n\t\tif (this.customResultMapper) {\n\t\t\treturn this.customResultMapper([result as unknown[]]) as T['all'];\n\t\t}\n\n\t\treturn mapResultRow(this.fields!, result as unknown[], this.joinsNotNullableMap);\n\t}\n\n\tasync values(placeholderValues?: Record): Promise {\n\t\tconst params = fillPlaceholders(this.query.params, placeholderValues ?? {});\n\t\tthis.logger.logQuery(this.query.sql, params);\n\t\treturn await this.queryWithCache(this.query.sql, params, async () => {\n\t\t\treturn this.stmt.bind(...params).raw();\n\t\t});\n\t}\n\n\t/** @internal */\n\tisResponseInArrayMode(): boolean {\n\t\treturn this._isResponseInArrayMode;\n\t}\n}\n", "import { entityKind } from '~/entity.ts';\nimport type { Table } from '~/index.ts';\nimport type { CacheConfig } from './types.ts';\n\nexport abstract class Cache {\n\tstatic readonly [entityKind]: string = 'Cache';\n\n\tabstract strategy(): 'explicit' | 'all';\n\n\t/**\n\t * Invoked if we should check cache for cached response\n\t * @param sql\n\t * @param tables\n\t */\n\tabstract get(\n\t\tkey: string,\n\t\ttables: string[],\n\t\tisTag: boolean,\n\t\tisAutoInvalidate?: boolean,\n\t): Promise;\n\n\t/**\n\t * Invoked if new query should be inserted to cache\n\t * @param sql\n\t * @param tables\n\t */\n\tabstract put(\n\t\thashedQuery: string,\n\t\tresponse: any,\n\t\ttables: string[],\n\t\tisTag: boolean,\n\t\tconfig?: CacheConfig,\n\t): Promise;\n\n\t/**\n\t * Invoked if insert, update, delete was invoked\n\t * @param tables\n\t */\n\tabstract onMutate(\n\t\tparams: MutationOption,\n\t): Promise;\n}\n\nexport class NoopCache extends Cache {\n\toverride strategy() {\n\t\treturn 'all' as const;\n\t}\n\n\tstatic override readonly [entityKind]: string = 'NoopCache';\n\n\toverride async get(_key: string): Promise {\n\t\treturn undefined;\n\t}\n\toverride async put(\n\t\t_hashedQuery: string,\n\t\t_response: any,\n\t\t_tables: string[],\n\t\t_config?: any,\n\t): Promise {\n\t\t// noop\n\t}\n\toverride async onMutate(_params: MutationOption): Promise {\n\t\t// noop\n\t}\n}\n\nexport type MutationOption = { tags?: string | string[]; tables?: Table | Table[] | string | string[] };\n\nexport async function hashQuery(sql: string, params?: any[]) {\n\tconst dataToHash = `${sql}-${JSON.stringify(params)}`;\n\tconst encoder = new TextEncoder();\n\tconst data = encoder.encode(dataToHash);\n\tconst hashBuffer = await crypto.subtle.digest('SHA-256', data);\n\tconst hashArray = [...new Uint8Array(hashBuffer)];\n\tconst hashHex = hashArray.map((b) => b.toString(16).padStart(2, '0')).join('');\n\n\treturn hashHex;\n}\n", "import { type Cache, hashQuery, NoopCache } from '~/cache/core/cache.ts';\nimport type { WithCacheConfig } from '~/cache/core/types.ts';\nimport { entityKind, is } from '~/entity.ts';\nimport { DrizzleError, DrizzleQueryError, TransactionRollbackError } from '~/errors.ts';\nimport { QueryPromise } from '~/query-promise.ts';\nimport type { TablesRelationalConfig } from '~/relations.ts';\nimport type { PreparedQuery } from '~/session.ts';\nimport type { Query, SQL } from '~/sql/sql.ts';\nimport type { SQLiteAsyncDialect, SQLiteSyncDialect } from '~/sqlite-core/dialect.ts';\nimport { BaseSQLiteDatabase } from './db.ts';\nimport type { SQLiteRaw } from './query-builders/raw.ts';\nimport type { SelectedFieldsOrdered } from './query-builders/select.types.ts';\n\nexport interface PreparedQueryConfig {\n\ttype: 'sync' | 'async';\n\trun: unknown;\n\tall: unknown;\n\tget: unknown;\n\tvalues: unknown;\n\texecute: unknown;\n}\n\nexport class ExecuteResultSync extends QueryPromise {\n\tstatic override readonly [entityKind]: string = 'ExecuteResultSync';\n\n\tconstructor(private resultCb: () => T) {\n\t\tsuper();\n\t}\n\n\toverride async execute(): Promise {\n\t\treturn this.resultCb();\n\t}\n\n\tsync(): T {\n\t\treturn this.resultCb();\n\t}\n}\n\nexport type ExecuteResult = TType extends 'async' ? Promise\n\t: ExecuteResultSync;\n\nexport abstract class SQLitePreparedQuery implements PreparedQuery {\n\tstatic readonly [entityKind]: string = 'PreparedQuery';\n\n\t/** @internal */\n\tjoinsNotNullableMap?: Record;\n\n\tconstructor(\n\t\tprivate mode: 'sync' | 'async',\n\t\tprivate executeMethod: SQLiteExecuteMethod,\n\t\tprotected query: Query,\n\t\tprivate cache?: Cache,\n\t\t// per query related metadata\n\t\tprivate queryMetadata?: {\n\t\t\ttype: 'select' | 'update' | 'delete' | 'insert';\n\t\t\ttables: string[];\n\t\t} | undefined,\n\t\t// config that was passed through $withCache\n\t\tprivate cacheConfig?: WithCacheConfig,\n\t) {\n\t\t// it means that no $withCache options were passed and it should be just enabled\n\t\tif (cache && cache.strategy() === 'all' && cacheConfig === undefined) {\n\t\t\tthis.cacheConfig = { enable: true, autoInvalidate: true };\n\t\t}\n\t\tif (!this.cacheConfig?.enable) {\n\t\t\tthis.cacheConfig = undefined;\n\t\t}\n\t}\n\n\t/** @internal */\n\tprotected async queryWithCache(\n\t\tqueryString: string,\n\t\tparams: any[],\n\t\tquery: () => Promise,\n\t): Promise {\n\t\tif (this.cache === undefined || is(this.cache, NoopCache) || this.queryMetadata === undefined) {\n\t\t\ttry {\n\t\t\t\treturn await query();\n\t\t\t} catch (e) {\n\t\t\t\tthrow new DrizzleQueryError(queryString, params, e as Error);\n\t\t\t}\n\t\t}\n\n\t\t// don't do any mutations, if globally is false\n\t\tif (this.cacheConfig && !this.cacheConfig.enable) {\n\t\t\ttry {\n\t\t\t\treturn await query();\n\t\t\t} catch (e) {\n\t\t\t\tthrow new DrizzleQueryError(queryString, params, e as Error);\n\t\t\t}\n\t\t}\n\n\t\t// For mutate queries, we should query the database, wait for a response, and then perform invalidation\n\t\tif (\n\t\t\t(\n\t\t\t\tthis.queryMetadata.type === 'insert' || this.queryMetadata.type === 'update'\n\t\t\t\t|| this.queryMetadata.type === 'delete'\n\t\t\t) && this.queryMetadata.tables.length > 0\n\t\t) {\n\t\t\ttry {\n\t\t\t\tconst [res] = await Promise.all([\n\t\t\t\t\tquery(),\n\t\t\t\t\tthis.cache.onMutate({ tables: this.queryMetadata.tables }),\n\t\t\t\t]);\n\t\t\t\treturn res;\n\t\t\t} catch (e) {\n\t\t\t\tthrow new DrizzleQueryError(queryString, params, e as Error);\n\t\t\t}\n\t\t}\n\n\t\t// don't do any reads if globally disabled\n\t\tif (!this.cacheConfig) {\n\t\t\ttry {\n\t\t\t\treturn await query();\n\t\t\t} catch (e) {\n\t\t\t\tthrow new DrizzleQueryError(queryString, params, e as Error);\n\t\t\t}\n\t\t}\n\n\t\tif (this.queryMetadata.type === 'select') {\n\t\t\tconst fromCache = await this.cache.get(\n\t\t\t\tthis.cacheConfig.tag ?? await hashQuery(queryString, params),\n\t\t\t\tthis.queryMetadata.tables,\n\t\t\t\tthis.cacheConfig.tag !== undefined,\n\t\t\t\tthis.cacheConfig.autoInvalidate,\n\t\t\t);\n\t\t\tif (fromCache === undefined) {\n\t\t\t\tlet result;\n\t\t\t\ttry {\n\t\t\t\t\tresult = await query();\n\t\t\t\t} catch (e) {\n\t\t\t\t\tthrow new DrizzleQueryError(queryString, params, e as Error);\n\t\t\t\t}\n\n\t\t\t\t// put actual key\n\t\t\t\tawait this.cache.put(\n\t\t\t\t\tthis.cacheConfig.tag ?? await hashQuery(queryString, params),\n\t\t\t\t\tresult,\n\t\t\t\t\t// make sure we send tables that were used in a query only if user wants to invalidate it on each write\n\t\t\t\t\tthis.cacheConfig.autoInvalidate ? this.queryMetadata.tables : [],\n\t\t\t\t\tthis.cacheConfig.tag !== undefined,\n\t\t\t\t\tthis.cacheConfig.config,\n\t\t\t\t);\n\t\t\t\t// put flag if we should invalidate or not\n\t\t\t\treturn result;\n\t\t\t}\n\n\t\t\treturn fromCache as unknown as T;\n\t\t}\n\t\ttry {\n\t\t\treturn await query();\n\t\t} catch (e) {\n\t\t\tthrow new DrizzleQueryError(queryString, params, e as Error);\n\t\t}\n\t}\n\n\tgetQuery(): Query {\n\t\treturn this.query;\n\t}\n\n\tabstract run(placeholderValues?: Record): Result;\n\n\tmapRunResult(result: unknown, _isFromBatch?: boolean): unknown {\n\t\treturn result;\n\t}\n\n\tabstract all(placeholderValues?: Record): Result;\n\n\tmapAllResult(_result: unknown, _isFromBatch?: boolean): unknown {\n\t\tthrow new Error('Not implemented');\n\t}\n\n\tabstract get(placeholderValues?: Record): Result;\n\n\tmapGetResult(_result: unknown, _isFromBatch?: boolean): unknown {\n\t\tthrow new Error('Not implemented');\n\t}\n\n\tabstract values(placeholderValues?: Record): Result;\n\n\texecute(placeholderValues?: Record): ExecuteResult {\n\t\tif (this.mode === 'async') {\n\t\t\treturn this[this.executeMethod](placeholderValues) as ExecuteResult;\n\t\t}\n\t\treturn new ExecuteResultSync(() => this[this.executeMethod](placeholderValues));\n\t}\n\n\tmapResult(response: unknown, isFromBatch?: boolean) {\n\t\tswitch (this.executeMethod) {\n\t\t\tcase 'run': {\n\t\t\t\treturn this.mapRunResult(response, isFromBatch);\n\t\t\t}\n\t\t\tcase 'all': {\n\t\t\t\treturn this.mapAllResult(response, isFromBatch);\n\t\t\t}\n\t\t\tcase 'get': {\n\t\t\t\treturn this.mapGetResult(response, isFromBatch);\n\t\t\t}\n\t\t}\n\t}\n\n\t/** @internal */\n\tabstract isResponseInArrayMode(): boolean;\n}\n\nexport interface SQLiteTransactionConfig {\n\tbehavior?: 'deferred' | 'immediate' | 'exclusive';\n}\n\nexport type SQLiteExecuteMethod = 'run' | 'all' | 'get';\n\nexport abstract class SQLiteSession<\n\tTResultKind extends 'sync' | 'async',\n\tTRunResult,\n\tTFullSchema extends Record,\n\tTSchema extends TablesRelationalConfig,\n> {\n\tstatic readonly [entityKind]: string = 'SQLiteSession';\n\n\tconstructor(\n\t\t/** @internal */\n\t\treadonly dialect: { sync: SQLiteSyncDialect; async: SQLiteAsyncDialect }[TResultKind],\n\t) {}\n\n\tabstract prepareQuery(\n\t\tquery: Query,\n\t\tfields: SelectedFieldsOrdered | undefined,\n\t\texecuteMethod: SQLiteExecuteMethod,\n\t\tisResponseInArrayMode: boolean,\n\t\tcustomResultMapper?: (rows: unknown[][], mapColumnValue?: (value: unknown) => unknown) => unknown,\n\t\tqueryMetadata?: {\n\t\t\ttype: 'select' | 'update' | 'delete' | 'insert';\n\t\t\ttables: string[];\n\t\t},\n\t\tcacheConfig?: WithCacheConfig,\n\t): SQLitePreparedQuery;\n\n\tprepareOneTimeQuery(\n\t\tquery: Query,\n\t\tfields: SelectedFieldsOrdered | undefined,\n\t\texecuteMethod: SQLiteExecuteMethod,\n\t\tisResponseInArrayMode: boolean,\n\t\tcustomResultMapper?: (rows: unknown[][], mapColumnValue?: (value: unknown) => unknown) => unknown,\n\t\tqueryMetadata?: {\n\t\t\ttype: 'select' | 'update' | 'delete' | 'insert';\n\t\t\ttables: string[];\n\t\t},\n\t\tcacheConfig?: WithCacheConfig,\n\t): SQLitePreparedQuery {\n\t\treturn this.prepareQuery(\n\t\t\tquery,\n\t\t\tfields,\n\t\t\texecuteMethod,\n\t\t\tisResponseInArrayMode,\n\t\t\tcustomResultMapper,\n\t\t\tqueryMetadata,\n\t\t\tcacheConfig,\n\t\t);\n\t}\n\n\tabstract transaction(\n\t\ttransaction: (tx: SQLiteTransaction) => Result,\n\t\tconfig?: SQLiteTransactionConfig,\n\t): Result;\n\n\trun(query: SQL): Result {\n\t\tconst staticQuery = this.dialect.sqlToQuery(query);\n\t\ttry {\n\t\t\treturn this.prepareOneTimeQuery(staticQuery, undefined, 'run', false).run() as Result;\n\t\t} catch (err) {\n\t\t\tthrow new DrizzleError({ cause: err, message: `Failed to run the query '${staticQuery.sql}'` });\n\t\t}\n\t}\n\n\t/** @internal */\n\textractRawRunValueFromBatchResult(result: unknown) {\n\t\treturn result;\n\t}\n\n\tall(query: SQL): Result {\n\t\treturn this.prepareOneTimeQuery(this.dialect.sqlToQuery(query), undefined, 'run', false).all() as Result<\n\t\t\tTResultKind,\n\t\t\tT[]\n\t\t>;\n\t}\n\n\t/** @internal */\n\textractRawAllValueFromBatchResult(_result: unknown): unknown {\n\t\tthrow new Error('Not implemented');\n\t}\n\n\tget(query: SQL): Result {\n\t\treturn this.prepareOneTimeQuery(this.dialect.sqlToQuery(query), undefined, 'run', false).get() as Result<\n\t\t\tTResultKind,\n\t\t\tT\n\t\t>;\n\t}\n\n\t/** @internal */\n\textractRawGetValueFromBatchResult(_result: unknown): unknown {\n\t\tthrow new Error('Not implemented');\n\t}\n\n\tvalues(\n\t\tquery: SQL,\n\t): Result {\n\t\treturn this.prepareOneTimeQuery(this.dialect.sqlToQuery(query), undefined, 'run', false).values() as Result<\n\t\t\tTResultKind,\n\t\t\tT[]\n\t\t>;\n\t}\n\n\tasync count(sql: SQL) {\n\t\tconst result = await this.values(sql) as [[number]];\n\n\t\treturn result[0][0];\n\t}\n\n\t/** @internal */\n\textractRawValuesValueFromBatchResult(_result: unknown): unknown {\n\t\tthrow new Error('Not implemented');\n\t}\n}\n\nexport type Result = { sync: TResult; async: Promise }[TKind];\n\nexport type DBResult = { sync: TResult; async: SQLiteRaw }[TKind];\n\nexport abstract class SQLiteTransaction<\n\tTResultType extends 'sync' | 'async',\n\tTRunResult,\n\tTFullSchema extends Record,\n\tTSchema extends TablesRelationalConfig,\n> extends BaseSQLiteDatabase {\n\tstatic override readonly [entityKind]: string = 'SQLiteTransaction';\n\n\tconstructor(\n\t\tresultType: TResultType,\n\t\tdialect: { sync: SQLiteSyncDialect; async: SQLiteAsyncDialect }[TResultType],\n\t\tsession: SQLiteSession,\n\t\tprotected schema: {\n\t\t\tfullSchema: Record;\n\t\t\tschema: TSchema;\n\t\t\ttableNamesMap: Record;\n\t\t} | undefined,\n\t\tprotected readonly nestedIndex = 0,\n\t) {\n\t\tsuper(resultType, dialect, session, schema);\n\t}\n\n\trollback(): never {\n\t\tthrow new TransactionRollbackError();\n\t}\n}\n", "import { Bot } from 'grammy';\nimport { session } from 'grammy'\nimport type { Env } from '../types/env';\nimport type { BotSession, BotContext } from './types';\nimport { I18nService } from '../services/i18n.service';\nimport { TwitchService } from '../services/twitch.service';\nimport { EventSubService } from '../services/eventsub.service';\nimport { DatabaseSessionStorage } from './storage';\nimport type { IChatRepository, IChannelRepository, IFollowRepository, ISessionRepository } from '../db/repositories/interfaces';\nimport {\n startCommand,\n followCommand,\n followsCommand,\n liveCommand,\n createBroadcastCommand,\n createChangeChannelIdCommand,\n callbackQueryHandler\n} from './commands';\n\nexport function createBot(\n env: Env,\n services: {\n i18n: I18nService;\n twitch: TwitchService;\n eventsub: EventSubService;\n chatRepo: IChatRepository;\n channelRepo: IChannelRepository;\n followRepo: IFollowRepository;\n sessionRepo: ISessionRepository;\n }\n): Bot {\n const bot = new Bot(env.TELEGRAM_TOKEN);\n\n // Use database session storage\n const sessionStorage = new DatabaseSessionStorage(\n services.sessionRepo,\n 86400 // 24 hours TTL\n );\n\n\tbot.use(session({\n\t\tinitial: (): BotSession => ({\n\t\t\tlanguage: 'en',\n\t\t\tfollowsMenu: {\n\t\t\t\tcurrentPage: 1,\n\t\t\t\ttotalPages: 1,\n\t\t\t},\n\t\t}),\n\t\tstorage: sessionStorage,\n\t}))\n\n // Attach environment and services to context\n bot.use(async (ctx, next) => {\n ctx.env = env;\n ctx.services = services;\n await next();\n });\n\n // Use i18n middleware\n bot.use(services.i18n.middleware());\n\n // Register commands\n bot.use(startCommand);\n bot.use(followCommand);\n bot.use(followsCommand);\n bot.use(liveCommand);\n bot.use(createBroadcastCommand(env));\n bot.use(createChangeChannelIdCommand(env));\n bot.use(callbackQueryHandler);\n\n return bot;\n}\n", "import type { StorageAdapter } from 'grammy';\nimport type { ISessionRepository } from '../db/repositories/interfaces';\n\n/**\n * Storage adapter for Grammy sessions using database persistence\n * Works with any ISessionRepository implementation (D1, PostgreSQL, etc.)\n */\nexport class DatabaseSessionStorage implements StorageAdapter {\n constructor(\n private sessionRepo: ISessionRepository,\n private ttl?: number // Time to live in seconds\n ) {}\n\n async read(key: string): Promise {\n const value = await this.sessionRepo.get(key);\n if (!value) return undefined;\n\n try {\n return JSON.parse(value) as T;\n } catch (error) {\n console.error('Failed to parse session data:', error);\n return undefined;\n }\n }\n\n async write(key: string, value: T): Promise {\n const expiresAt = this.ttl ? Date.now() + this.ttl * 1000 : undefined;\n await this.sessionRepo.set(key, JSON.stringify(value), expiresAt);\n }\n\n async delete(key: string): Promise {\n await this.sessionRepo.delete(key);\n }\n\n async has(key: string): Promise {\n const value = await this.sessionRepo.get(key);\n return value !== undefined;\n }\n\n /**\n * Clean up expired sessions\n * Should be called periodically (e.g., via cron job)\n */\n async cleanup(): Promise {\n await this.sessionRepo.cleanup();\n }\n}\n", "export { startCommand } from './start.command';\nexport { followCommand } from './follow.command';\nexport { followsCommand } from './follows.command';\nexport { liveCommand } from './live.command';\nexport { createBroadcastCommand } from './broadcast.command';\nexport { createChangeChannelIdCommand } from './change-channel-id.command';\nexport { callbackQueryHandler } from './callback.handler';\n", "import { Composer } from 'grammy';\nimport type { BotContext } from '../types';\nimport type { SupportedLanguage } from '../../services/i18n.service';\nimport { sendSettingsMenu } from '../helpers';\n\nexport const startCommand = new Composer();\n\nstartCommand.command(['start', 'help', 'info', 'settings'], async (ctx) => {\n const chatId = ctx.chat?.id;\n if (!chatId) return;\n\n // Get or create chat in database\n let chat = await ctx.services.chatRepo.findByChatId(chatId, 'telegram');\n if (!chat) {\n await ctx.services.chatRepo.create(chatId.toString(), 'telegram');\n // Fetch the chat again to get it with settings\n chat = await ctx.services.chatRepo.findByChatId(chatId, 'telegram');\n }\n\n // Update session language\n if (chat?.settings) {\n ctx.session.language = chat.settings.language as SupportedLanguage;\n }\n\n if (chat) {\n await sendSettingsMenu(ctx, chat);\n }\n});\n", "import type { BotContext } from './types';\nimport type { Chat } from '../domain/models';\nimport { InlineKeyboard } from 'grammy';\n\nexport async function sendSettingsMenu(ctx: BotContext, chat: Chat) {\n const settings = chat.settings;\n if (!settings) return;\n\n const createCheckmark = (value: boolean) => value ? '\u2705' : '\u274C';\n\n const keyboard = new InlineKeyboard()\n .text(\n `${createCheckmark(settings.gameChangeNotification)} ${ctx.t('commands.start.game_change_notification_setting.button')}`,\n 'toggle_game_change'\n ).row()\n .text(\n `${createCheckmark(settings.offlineNotification)} ${ctx.t('commands.start.offline_notification.button')}`,\n 'toggle_offline'\n ).row()\n .text(\n `${createCheckmark(settings.titleChangeNotification)} ${ctx.t('commands.start.title_change_notification_setting.button')}`,\n 'toggle_title_change'\n ).row()\n .text(\n `${createCheckmark(settings.gameAndTitleChangeNotification)} ${ctx.t('commands.start.game_and_title_change_notification_setting.button')}`,\n 'toggle_game_and_title'\n ).row()\n .text(\n `${createCheckmark(settings.imageInNotification)} ${ctx.t('commands.start.image_in_notification_setting.button')}`,\n 'toggle_image'\n ).row()\n .text(\n ctx.t('commands.start.language.button'),\n 'language_picker'\n ).row()\n .url('Github', 'https://github.com/Satont/twitch-notifier');\n\n const description = ctx.t('bot.description');\n\n if (ctx.callbackQuery) {\n await ctx.editMessageText(description, { reply_markup: keyboard });\n } else {\n await ctx.reply(description, { reply_markup: keyboard });\n }\n}\n\nexport async function sendLanguagePicker(ctx: BotContext) {\n const keyboard = new InlineKeyboard();\n\n const locales = ctx.services.i18n.getAvailableLocales();\n for (const locale of locales) {\n const emoji = ctx.services.i18n.t(locale, 'language.emoji');\n const name = ctx.services.i18n.t(locale, 'language.name');\n keyboard.text(`${emoji} ${name}`, `language_picker_set_${locale}`).row();\n }\n keyboard.text('\u00AB', 'start_command_menu');\n\n const text = ctx.t('language.select');\n\n if (ctx.callbackQuery) {\n await ctx.editMessageText(text, { reply_markup: keyboard });\n } else {\n await ctx.reply(text, { reply_markup: keyboard });\n }\n}\n\nexport async function buildFollowsKeyboard(ctx: BotContext, chatId: string): Promise {\n const follows = await ctx.services.followRepo.findByChatId(chatId);\n const keyboard = new InlineKeyboard();\n\n for (const follow of follows) {\n const channel = await ctx.services.channelRepo.findById(follow.channelId);\n if (!channel) continue;\n\n const twitchUser = await ctx.services.twitch.getUserById(channel.channelId);\n if (!twitchUser) continue;\n\n keyboard.text(twitchUser.displayName, `channels_unfollow_${channel.channelId}`).row();\n }\n\n // Add pagination buttons if needed\n if (ctx.session.followsMenu) {\n const { currentPage, totalPages } = ctx.session.followsMenu;\n if (totalPages > 1) {\n keyboard.text('\u00AB', 'channels_unfollow_prev_page');\n keyboard.text('\u00BB', 'channels_unfollow_next_page');\n }\n }\n\n return keyboard;\n}\n\nexport async function handleToggleSetting(ctx: BotContext, data: string, chat: Chat) {\n const chatId = ctx.chat?.id;\n if (!chatId || !chat.settings) return;\n\n const updates: any = {};\n\n switch (data) {\n case 'toggle_game_change':\n updates.gameChangeNotification = !chat.settings.gameChangeNotification;\n chat.settings.gameChangeNotification = updates.gameChangeNotification;\n break;\n case 'toggle_offline':\n updates.offlineNotification = !chat.settings.offlineNotification;\n chat.settings.offlineNotification = updates.offlineNotification;\n break;\n case 'toggle_title_change':\n updates.titleChangeNotification = !chat.settings.titleChangeNotification;\n chat.settings.titleChangeNotification = updates.titleChangeNotification;\n break;\n case 'toggle_game_and_title':\n updates.gameAndTitleChangeNotification = !chat.settings.gameAndTitleChangeNotification;\n chat.settings.gameAndTitleChangeNotification = updates.gameAndTitleChangeNotification;\n break;\n case 'toggle_image':\n updates.imageInNotification = !chat.settings.imageInNotification;\n chat.settings.imageInNotification = updates.imageInNotification;\n break;\n }\n\n if (Object.keys(updates).length > 0) {\n await ctx.services.chatRepo.updateSettings(chat.settings.id, updates);\n }\n}\n\nexport async function handleUnfollow(ctx: BotContext, chat: Chat, channelIdFromCallback: string) {\n const channel = await ctx.services.channelRepo.findById(channelIdFromCallback);\n if (!channel) {\n await ctx.answerCallbackQuery('Channel not found');\n return;\n }\n\n const follow = await ctx.services.followRepo.findByChatAndChannel(chat.id, channel.id);\n if (!follow) {\n await ctx.answerCallbackQuery('Already unfollowed');\n return;\n }\n\n const twitchUser = await ctx.services.twitch.getUserById(channel.channelId);\n const streamerName = twitchUser?.displayName || channel.channelId;\n\n await ctx.services.followRepo.delete(follow.id);\n\n // Check if this channel still has followers\n const remainingFollows = await ctx.services.followRepo.findByChannelId(channel.id);\n\n // If no followers remain, unsubscribe from EventSub\n if (remainingFollows.length === 0) {\n try {\n await ctx.services.eventsub.unsubscribeFromChannel(channel.channelId);\n console.log(`Unsubscribed from EventSub for channel ${channel.channelId}`);\n } catch (error) {\n console.error(`Failed to unsubscribe from EventSub for ${channel.channelId}:`, error);\n // Don't fail the unfollow if EventSub unsubscription fails\n }\n }\n\n await ctx.answerCallbackQuery(\n ctx.t('commands.unfollow.success', {\n streamer: streamerName,\n })\n );\n\n // Update keyboard\n const totalFollows = await ctx.services.followRepo.countByChatId(chat.id);\n\n if (totalFollows === 0) {\n await ctx.editMessageText('You are not following any channels.');\n await ctx.editMessageReplyMarkup({ reply_markup: new InlineKeyboard() });\n return;\n }\n\n const keyboard = await buildFollowsKeyboard(ctx, chat.id);\n\n await ctx.editMessageText(\n ctx.t('commands.follows.total', {\n count: totalFollows.toString(),\n }),\n {\n reply_markup: keyboard,\n }\n );\n}\n", "import { Composer } from 'grammy';\nimport type { BotContext } from '../types';\n\nexport const followCommand = new Composer();\n\nfollowCommand.command('follow', async (ctx) => {\n const text = ctx.message?.text?.replace('/follow', '').trim();\n\n if (!text) {\n await ctx.reply(\n ctx.t('commands.follow.enter')\n );\n ctx.session.scene = 'follow';\n return;\n }\n\n await handleFollow(ctx, text);\n});\n\n// Handle follow scene\nfollowCommand.on('message:text', async (ctx, next) => {\n if (ctx.session.scene === 'follow') {\n await handleFollow(ctx, ctx.message.text);\n ctx.session.scene = undefined;\n return;\n }\n await next();\n});\n\nasync function handleFollow(ctx: BotContext, text: string) {\n const chatId = ctx.chat?.id;\n if (!chatId) return;\n\n const chat = await ctx.services.chatRepo.findByChatId(chatId, 'telegram');\n if (!chat) return;\n\n // Extract Twitch username from text or URL\n const twitchLinkRegex = /(?:https?:\\/\\/)?(?:www\\.)?twitch\\.tv\\/(\\w+)/g;\n const matches = Array.from(text.matchAll(twitchLinkRegex));\n\n const usernames = matches.length > 0\n ? matches.map(m => m[1])\n : [text.trim()];\n\n const results: string[] = [];\n\n for (const username of usernames) {\n // Validate username\n if (!/^[a-zA-Z0-9_]{3,25}$/.test(username)) {\n results.push(\n ctx.t(\n 'commands.follow.errors.badUsername',\n { streamer: username }\n )\n );\n continue;\n }\n\n try {\n // Get Twitch user\n const twitchUser = await ctx.services.twitch.getUserByLogin(username);\n\n if (!twitchUser) {\n results.push(\n ctx.t(\n 'commands.follow.errors.streamerNotFound',\n { streamer: username }\n )\n );\n continue;\n }\n\n // Get or create channel\n let channel = await ctx.services.channelRepo.findByChannelId(twitchUser.id, 'twitch');\n if (!channel) {\n channel = await ctx.services.channelRepo.create(twitchUser.id, 'twitch');\n }\n\n // Create follow\n try {\n await ctx.services.followRepo.create(chat.id, channel.id);\n\n // Subscribe to EventSub events for this channel\n // Check if we already have subscriptions for this channel\n const hasSubscriptions = await ctx.services.eventsub.hasActiveSubscriptions(twitchUser.id);\n if (!hasSubscriptions) {\n try {\n await ctx.services.eventsub.subscribeToChannel(twitchUser.id);\n console.log(`Subscribed to EventSub for channel ${twitchUser.id}`);\n } catch (eventSubError) {\n console.error(`Failed to subscribe to EventSub for ${twitchUser.id}:`, eventSubError);\n // Don't fail the follow if EventSub subscription fails\n }\n }\n\n results.push(\n ctx.t(\n 'commands.follow.success',\n { streamer: username }\n )\n );\n } catch (error: any) {\n if (error.message?.includes('UNIQUE constraint failed')) {\n results.push(\n ctx.t(\n 'commands.follow.errors.alreadyFollowed',\n { streamer: username }\n )\n );\n } else {\n throw error;\n }\n }\n } catch (error) {\n console.error('Error following user:', error);\n results.push(`${username} - internal error`);\n }\n }\n\n await ctx.reply(results.join('\\n'));\n}\n", "import { Composer } from 'grammy';\nimport type { BotContext } from '../types';\nimport { buildFollowsKeyboard } from '../helpers';\n\nexport const followsCommand = new Composer();\n\nfollowsCommand.command(['follows', 'unfollow'], async (ctx) => {\n const chatId = ctx.chat?.id;\n if (!chatId) return;\n\n const chat = await ctx.services.chatRepo.findByChatId(chatId, 'telegram');\n if (!chat) return;\n\n ctx.session.followsMenu = {\n currentPage: 1,\n totalPages: 1,\n };\n\n const totalFollows = await ctx.services.followRepo.countByChatId(chat.id);\n\n if (totalFollows === 0) {\n await ctx.reply('You are not following any channels.');\n return;\n }\n\n const keyboard = await buildFollowsKeyboard(ctx, chat.id);\n\n await ctx.reply(\n ctx.t(\n 'commands.follows.total',\n { count: totalFollows.toString() }\n ),\n {\n reply_markup: keyboard,\n }\n );\n});\n", "import { Composer } from 'grammy';\nimport type { BotContext } from '../types';\n\nexport const liveCommand = new Composer();\n\nliveCommand.command('live', async (ctx) => {\n const chatId = ctx.chat?.id;\n if (!chatId) return;\n\n const chat = await ctx.services.chatRepo.findByChatId(chatId, 'telegram');\n if (!chat) return;\n\n const follows = await ctx.services.followRepo.findByChatId(chat.id);\n\n if (follows.length === 0) {\n await ctx.reply('You are not following any channels.');\n return;\n }\n\n // Get all followed channel IDs\n const channelIds: string[] = [];\n for (const follow of follows) {\n const channel = await ctx.services.channelRepo.findById(follow.channelId);\n if (channel) {\n channelIds.push(channel.channelId);\n }\n }\n\n if (channelIds.length === 0) {\n await ctx.reply('No channels found.');\n return;\n }\n\n // Get live streams\n const liveChannels: Array<{\n name: string;\n login: string;\n startedAt: Date;\n title: string;\n category: string;\n viewers: number;\n }> = [];\n\n for (const channelId of channelIds) {\n const stream = await ctx.services.twitch.getStreamByUserId(channelId);\n if (stream) {\n const user = await ctx.services.twitch.getUserById(channelId);\n if (user) {\n liveChannels.push({\n name: user.displayName,\n login: user.name,\n startedAt: stream.startDate,\n title: stream.title,\n category: stream.gameName,\n viewers: stream.viewers,\n });\n }\n }\n }\n\n if (liveChannels.length === 0) {\n await ctx.reply('No one is online.');\n return;\n }\n\n // Build message\n const messages: string[] = [];\n for (const channel of liveChannels) {\n const channelMessage: string[] = [];\n\n channelMessage.push(\n `\uD83D\uDFE2 ${channel.name} - ${channel.viewers} \uD83D\uDC41\uFE0F\uFE0F`\n );\n\n if (channel.category) {\n channelMessage.push(`\uD83C\uDFAE ${channel.category}`);\n }\n\n if (channel.title) {\n channelMessage.push(`\uD83D\uDCDD ${channel.title}`);\n }\n\n // Calculate uptime\n const uptime = Date.now() - channel.startedAt.getTime();\n const hours = Math.floor(uptime / 3600000);\n const minutes = Math.floor((uptime % 3600000) / 60000);\n const seconds = Math.floor((uptime % 60000) / 1000);\n\n let uptimeStr = '\u231B ';\n if (hours > 0) uptimeStr += `${hours}h `;\n if (minutes > 0) uptimeStr += `${minutes}m `;\n if (seconds > 0) uptimeStr += `${seconds}s `;\n\n channelMessage.push(uptimeStr);\n messages.push(channelMessage.join('\\n'));\n }\n\n await ctx.reply(messages.join('\\n\\n'), {\n parse_mode: 'HTML',\n link_preview_options: { is_disabled: true },\n });\n});\n", "import { Composer } from 'grammy';\nimport type { BotContext } from '../types';\nimport type { Env } from '../../types/env';\n\nexport function createBroadcastCommand(env: Env) {\n const broadcast = new Composer();\n\n const isAdmin = (userId: number): boolean => {\n const admins = env.TELEGRAM_BOT_ADMINS.split(',').map(id => parseInt(id.trim()));\n return admins.includes(userId);\n };\n\n broadcast.command('broadcast', async (ctx) => {\n const userId = ctx.from?.id;\n if (!userId || !isAdmin(userId)) {\n return;\n }\n\n const text = ctx.message?.text?.replace('/broadcast', '').trim();\n if (!text) {\n await ctx.reply('Usage: /broadcast ');\n return;\n }\n\n // Get all chats (only positive IDs = private chats/groups)\n const allChats = await ctx.services.chatRepo.findAllByService('telegram');\n\n let sent = 0;\n let failed = 0;\n\n for (const chat of allChats) {\n const chatIdNum = parseInt(chat.chatId);\n if (chatIdNum <= 0) continue; // Skip channels/supergroups\n\n try {\n await ctx.api.sendMessage(chatIdNum, text);\n sent++;\n } catch (error) {\n console.error(`Failed to send to ${chat.chatId}:`, error);\n failed++;\n }\n }\n\n await ctx.reply(`Broadcast completed!\\nSent: ${sent}\\nFailed: ${failed}`);\n });\n\n return broadcast;\n}\n", "import { Composer } from 'grammy';\nimport type { BotContext } from '../types';\nimport type { Env } from '../../types/env';\n\nexport function createChangeChannelIdCommand(env: Env) {\n const changeChannelId = new Composer();\n\n const isAdmin = (userId: number): boolean => {\n const admins = env.TELEGRAM_BOT_ADMINS.split(',').map(id => parseInt(id.trim()));\n return admins.includes(userId);\n };\n\n changeChannelId.command('change_channel_id', async (ctx) => {\n const userId = ctx.from?.id;\n if (!userId || !isAdmin(userId)) {\n return;\n }\n\n const text = ctx.message?.text?.replace('/change_channel_id', '').trim();\n\n if (!text) {\n await ctx.reply('Usage: /change_channel_id ');\n return;\n }\n\n const parts = text.split(' ');\n\n if (parts.length !== 2) {\n await ctx.reply('Usage: /change_channel_id ');\n return;\n }\n\n const [oldId, newId] = parts;\n\n try {\n await ctx.services.channelRepo.updateChannelId(oldId, newId, 'twitch');\n await ctx.reply('Channel ID updated successfully!');\n } catch (error) {\n console.error('Error updating channel ID:', error);\n await ctx.reply('Error updating channel ID.');\n }\n });\n\n return changeChannelId;\n}\n", "import { Composer } from 'grammy';\nimport type { BotContext } from '../types';\nimport type { SupportedLanguage } from '../../services/i18n.service';\nimport {\n sendSettingsMenu,\n sendLanguagePicker,\n handleToggleSetting,\n handleUnfollow,\n buildFollowsKeyboard\n} from '../helpers';\n\nexport const callbackQueryHandler = new Composer();\n\ncallbackQueryHandler.on('callback_query:data', async (ctx) => {\n const data = ctx.callbackQuery.data;\n const chatId = ctx.chat?.id;\n if (!chatId) return;\n\n const chat = await ctx.services.chatRepo.findByChatId(chatId, 'telegram');\n if (!chat || !chat.settings) return;\n\n // Handle toggle settings\n if (data.startsWith('toggle_')) {\n await handleToggleSetting(ctx, data, chat);\n await sendSettingsMenu(ctx, chat);\n }\n\n // Handle language picker\n else if (data === 'language_picker') {\n await sendLanguagePicker(ctx);\n }\n\n // Handle language selection\n else if (data.startsWith('language_picker_set_')) {\n const lang = data.replace('language_picker_set_', '') as SupportedLanguage;\n if (ctx.services.i18n.isValidLocale(lang)) {\n await ctx.services.chatRepo.updateSettings(chat.settings.id, { language: lang });\n ctx.session.language = lang;\n await ctx.answerCallbackQuery(\n ctx.services.i18n.t(lang, 'language.changed')\n );\n await sendLanguagePicker(ctx);\n }\n }\n\n // Handle back to main menu\n else if (data === 'start_command_menu') {\n await sendSettingsMenu(ctx, chat);\n }\n\n // Handle unfollow\n else if (data.startsWith('channels_unfollow_')) {\n const channelId = data.replace('channels_unfollow_', '');\n await handleUnfollow(ctx, chat, channelId);\n }\n\n // Handle pagination\n else if (data === 'channels_unfollow_prev_page') {\n if (ctx.session.followsMenu && ctx.session.followsMenu.currentPage > 1) {\n ctx.session.followsMenu.currentPage--;\n }\n const keyboard = await buildFollowsKeyboard(ctx, chat.id);\n await ctx.editMessageReplyMarkup({ reply_markup: keyboard });\n }\n else if (data === 'channels_unfollow_next_page') {\n if (ctx.session.followsMenu && ctx.session.followsMenu.currentPage < ctx.session.followsMenu.totalPages) {\n ctx.session.followsMenu.currentPage++;\n }\n const keyboard = await buildFollowsKeyboard(ctx, chat.id);\n await ctx.editMessageReplyMarkup({ reply_markup: keyboard });\n }\n\n await ctx.answerCallbackQuery();\n});\n", "import i18next from 'i18next';\nimport type { MiddlewareFn } from 'grammy';\nimport enLocale from '../../locales/en.json';\nimport ruLocale from '../../locales/ru.json';\nimport ukLocale from '../../locales/uk.json';\n\nexport type SupportedLanguage = 'en' | 'ru' | 'uk';\n\nexport class I18nService {\n private i18n: typeof i18next;\n private initialized = false;\n\n constructor() {\n this.i18n = i18next.createInstance();\n }\n\n /**\n * Initialize i18next instance with locales\n * Must be called before using the service\n */\n async init(): Promise {\n if (this.initialized) return;\n\n await this.i18n.init({\n lng: 'en',\n fallbackLng: 'en',\n defaultNS: 'translation',\n ns: ['translation'],\n resources: {\n en: { translation: enLocale },\n ru: { translation: ruLocale },\n uk: { translation: ukLocale },\n },\n interpolation: {\n escapeValue: false, // Not needed for Telegram (no XSS risk)\n },\n });\n\n this.initialized = true;\n }\n\n /**\n * Get translated string\n * @param locale - Language code\n * @param key - Translation key (dot notation)\n * @param params - Template parameters\n */\n t(locale: SupportedLanguage, key: string, params?: Record): string {\n if (!this.initialized) {\n throw new Error('I18nService not initialized. Call init() first.');\n }\n return this.i18n.t(key, { ...params, lng: locale });\n }\n\n /**\n * Get Grammy middleware that attaches t() function to context\n */\n middleware(): MiddlewareFn {\n return async (ctx, next) => {\n const language = ctx.session?.language || 'en';\n \n // Attach t() function to context that uses session language\n ctx.t = (key: string, params?: Record) => {\n return this.t(language, key, params);\n };\n\n await next();\n };\n }\n\n /**\n * Get all available locales\n */\n getAvailableLocales(): SupportedLanguage[] {\n return ['en', 'ru', 'uk'];\n }\n\n /**\n * Check if locale is supported\n */\n isValidLocale(locale: string): locale is SupportedLanguage {\n return ['en', 'ru', 'uk'].includes(locale);\n }\n}\n", "const isString = obj => typeof obj === 'string';\nconst defer = () => {\n let res;\n let rej;\n const promise = new Promise((resolve, reject) => {\n res = resolve;\n rej = reject;\n });\n promise.resolve = res;\n promise.reject = rej;\n return promise;\n};\nconst makeString = object => {\n if (object == null) return '';\n return '' + object;\n};\nconst copy = (a, s, t) => {\n a.forEach(m => {\n if (s[m]) t[m] = s[m];\n });\n};\nconst lastOfPathSeparatorRegExp = /###/g;\nconst cleanKey = key => key && key.indexOf('###') > -1 ? key.replace(lastOfPathSeparatorRegExp, '.') : key;\nconst canNotTraverseDeeper = object => !object || isString(object);\nconst getLastOfPath = (object, path, Empty) => {\n const stack = !isString(path) ? path : path.split('.');\n let stackIndex = 0;\n while (stackIndex < stack.length - 1) {\n if (canNotTraverseDeeper(object)) return {};\n const key = cleanKey(stack[stackIndex]);\n if (!object[key] && Empty) object[key] = new Empty();\n if (Object.prototype.hasOwnProperty.call(object, key)) {\n object = object[key];\n } else {\n object = {};\n }\n ++stackIndex;\n }\n if (canNotTraverseDeeper(object)) return {};\n return {\n obj: object,\n k: cleanKey(stack[stackIndex])\n };\n};\nconst setPath = (object, path, newValue) => {\n const {\n obj,\n k\n } = getLastOfPath(object, path, Object);\n if (obj !== undefined || path.length === 1) {\n obj[k] = newValue;\n return;\n }\n let e = path[path.length - 1];\n let p = path.slice(0, path.length - 1);\n let last = getLastOfPath(object, p, Object);\n while (last.obj === undefined && p.length) {\n e = `${p[p.length - 1]}.${e}`;\n p = p.slice(0, p.length - 1);\n last = getLastOfPath(object, p, Object);\n if (last?.obj && typeof last.obj[`${last.k}.${e}`] !== 'undefined') {\n last.obj = undefined;\n }\n }\n last.obj[`${last.k}.${e}`] = newValue;\n};\nconst pushPath = (object, path, newValue, concat) => {\n const {\n obj,\n k\n } = getLastOfPath(object, path, Object);\n obj[k] = obj[k] || [];\n obj[k].push(newValue);\n};\nconst getPath = (object, path) => {\n const {\n obj,\n k\n } = getLastOfPath(object, path);\n if (!obj) return undefined;\n if (!Object.prototype.hasOwnProperty.call(obj, k)) return undefined;\n return obj[k];\n};\nconst getPathWithDefaults = (data, defaultData, key) => {\n const value = getPath(data, key);\n if (value !== undefined) {\n return value;\n }\n return getPath(defaultData, key);\n};\nconst deepExtend = (target, source, overwrite) => {\n for (const prop in source) {\n if (prop !== '__proto__' && prop !== 'constructor') {\n if (prop in target) {\n if (isString(target[prop]) || target[prop] instanceof String || isString(source[prop]) || source[prop] instanceof String) {\n if (overwrite) target[prop] = source[prop];\n } else {\n deepExtend(target[prop], source[prop], overwrite);\n }\n } else {\n target[prop] = source[prop];\n }\n }\n }\n return target;\n};\nconst regexEscape = str => str.replace(/[\\-\\[\\]\\/\\{\\}\\(\\)\\*\\+\\?\\.\\\\\\^\\$\\|]/g, '\\\\$&');\nvar _entityMap = {\n '&': '&',\n '<': '<',\n '>': '>',\n '\"': '"',\n \"'\": ''',\n '/': '/'\n};\nconst escape = data => {\n if (isString(data)) {\n return data.replace(/[&<>\"'\\/]/g, s => _entityMap[s]);\n }\n return data;\n};\nclass RegExpCache {\n constructor(capacity) {\n this.capacity = capacity;\n this.regExpMap = new Map();\n this.regExpQueue = [];\n }\n getRegExp(pattern) {\n const regExpFromCache = this.regExpMap.get(pattern);\n if (regExpFromCache !== undefined) {\n return regExpFromCache;\n }\n const regExpNew = new RegExp(pattern);\n if (this.regExpQueue.length === this.capacity) {\n this.regExpMap.delete(this.regExpQueue.shift());\n }\n this.regExpMap.set(pattern, regExpNew);\n this.regExpQueue.push(pattern);\n return regExpNew;\n }\n}\nconst chars = [' ', ',', '?', '!', ';'];\nconst looksLikeObjectPathRegExpCache = new RegExpCache(20);\nconst looksLikeObjectPath = (key, nsSeparator, keySeparator) => {\n nsSeparator = nsSeparator || '';\n keySeparator = keySeparator || '';\n const possibleChars = chars.filter(c => nsSeparator.indexOf(c) < 0 && keySeparator.indexOf(c) < 0);\n if (possibleChars.length === 0) return true;\n const r = looksLikeObjectPathRegExpCache.getRegExp(`(${possibleChars.map(c => c === '?' ? '\\\\?' : c).join('|')})`);\n let matched = !r.test(key);\n if (!matched) {\n const ki = key.indexOf(keySeparator);\n if (ki > 0 && !r.test(key.substring(0, ki))) {\n matched = true;\n }\n }\n return matched;\n};\nconst deepFind = (obj, path, keySeparator = '.') => {\n if (!obj) return undefined;\n if (obj[path]) {\n if (!Object.prototype.hasOwnProperty.call(obj, path)) return undefined;\n return obj[path];\n }\n const tokens = path.split(keySeparator);\n let current = obj;\n for (let i = 0; i < tokens.length;) {\n if (!current || typeof current !== 'object') {\n return undefined;\n }\n let next;\n let nextPath = '';\n for (let j = i; j < tokens.length; ++j) {\n if (j !== i) {\n nextPath += keySeparator;\n }\n nextPath += tokens[j];\n next = current[nextPath];\n if (next !== undefined) {\n if (['string', 'number', 'boolean'].indexOf(typeof next) > -1 && j < tokens.length - 1) {\n continue;\n }\n i += j - i + 1;\n break;\n }\n }\n current = next;\n }\n return current;\n};\nconst getCleanedCode = code => code?.replace(/_/g, '-');\n\nconst consoleLogger = {\n type: 'logger',\n log(args) {\n this.output('log', args);\n },\n warn(args) {\n this.output('warn', args);\n },\n error(args) {\n this.output('error', args);\n },\n output(type, args) {\n console?.[type]?.apply?.(console, args);\n }\n};\nclass Logger {\n constructor(concreteLogger, options = {}) {\n this.init(concreteLogger, options);\n }\n init(concreteLogger, options = {}) {\n this.prefix = options.prefix || 'i18next:';\n this.logger = concreteLogger || consoleLogger;\n this.options = options;\n this.debug = options.debug;\n }\n log(...args) {\n return this.forward(args, 'log', '', true);\n }\n warn(...args) {\n return this.forward(args, 'warn', '', true);\n }\n error(...args) {\n return this.forward(args, 'error', '');\n }\n deprecate(...args) {\n return this.forward(args, 'warn', 'WARNING DEPRECATED: ', true);\n }\n forward(args, lvl, prefix, debugOnly) {\n if (debugOnly && !this.debug) return null;\n if (isString(args[0])) args[0] = `${prefix}${this.prefix} ${args[0]}`;\n return this.logger[lvl](args);\n }\n create(moduleName) {\n return new Logger(this.logger, {\n ...{\n prefix: `${this.prefix}:${moduleName}:`\n },\n ...this.options\n });\n }\n clone(options) {\n options = options || this.options;\n options.prefix = options.prefix || this.prefix;\n return new Logger(this.logger, options);\n }\n}\nvar baseLogger = new Logger();\n\nclass EventEmitter {\n constructor() {\n this.observers = {};\n }\n on(events, listener) {\n events.split(' ').forEach(event => {\n if (!this.observers[event]) this.observers[event] = new Map();\n const numListeners = this.observers[event].get(listener) || 0;\n this.observers[event].set(listener, numListeners + 1);\n });\n return this;\n }\n off(event, listener) {\n if (!this.observers[event]) return;\n if (!listener) {\n delete this.observers[event];\n return;\n }\n this.observers[event].delete(listener);\n }\n emit(event, ...args) {\n if (this.observers[event]) {\n const cloned = Array.from(this.observers[event].entries());\n cloned.forEach(([observer, numTimesAdded]) => {\n for (let i = 0; i < numTimesAdded; i++) {\n observer(...args);\n }\n });\n }\n if (this.observers['*']) {\n const cloned = Array.from(this.observers['*'].entries());\n cloned.forEach(([observer, numTimesAdded]) => {\n for (let i = 0; i < numTimesAdded; i++) {\n observer.apply(observer, [event, ...args]);\n }\n });\n }\n }\n}\n\nclass ResourceStore extends EventEmitter {\n constructor(data, options = {\n ns: ['translation'],\n defaultNS: 'translation'\n }) {\n super();\n this.data = data || {};\n this.options = options;\n if (this.options.keySeparator === undefined) {\n this.options.keySeparator = '.';\n }\n if (this.options.ignoreJSONStructure === undefined) {\n this.options.ignoreJSONStructure = true;\n }\n }\n addNamespaces(ns) {\n if (this.options.ns.indexOf(ns) < 0) {\n this.options.ns.push(ns);\n }\n }\n removeNamespaces(ns) {\n const index = this.options.ns.indexOf(ns);\n if (index > -1) {\n this.options.ns.splice(index, 1);\n }\n }\n getResource(lng, ns, key, options = {}) {\n const keySeparator = options.keySeparator !== undefined ? options.keySeparator : this.options.keySeparator;\n const ignoreJSONStructure = options.ignoreJSONStructure !== undefined ? options.ignoreJSONStructure : this.options.ignoreJSONStructure;\n let path;\n if (lng.indexOf('.') > -1) {\n path = lng.split('.');\n } else {\n path = [lng, ns];\n if (key) {\n if (Array.isArray(key)) {\n path.push(...key);\n } else if (isString(key) && keySeparator) {\n path.push(...key.split(keySeparator));\n } else {\n path.push(key);\n }\n }\n }\n const result = getPath(this.data, path);\n if (!result && !ns && !key && lng.indexOf('.') > -1) {\n lng = path[0];\n ns = path[1];\n key = path.slice(2).join('.');\n }\n if (result || !ignoreJSONStructure || !isString(key)) return result;\n return deepFind(this.data?.[lng]?.[ns], key, keySeparator);\n }\n addResource(lng, ns, key, value, options = {\n silent: false\n }) {\n const keySeparator = options.keySeparator !== undefined ? options.keySeparator : this.options.keySeparator;\n let path = [lng, ns];\n if (key) path = path.concat(keySeparator ? key.split(keySeparator) : key);\n if (lng.indexOf('.') > -1) {\n path = lng.split('.');\n value = ns;\n ns = path[1];\n }\n this.addNamespaces(ns);\n setPath(this.data, path, value);\n if (!options.silent) this.emit('added', lng, ns, key, value);\n }\n addResources(lng, ns, resources, options = {\n silent: false\n }) {\n for (const m in resources) {\n if (isString(resources[m]) || Array.isArray(resources[m])) this.addResource(lng, ns, m, resources[m], {\n silent: true\n });\n }\n if (!options.silent) this.emit('added', lng, ns, resources);\n }\n addResourceBundle(lng, ns, resources, deep, overwrite, options = {\n silent: false,\n skipCopy: false\n }) {\n let path = [lng, ns];\n if (lng.indexOf('.') > -1) {\n path = lng.split('.');\n deep = resources;\n resources = ns;\n ns = path[1];\n }\n this.addNamespaces(ns);\n let pack = getPath(this.data, path) || {};\n if (!options.skipCopy) resources = JSON.parse(JSON.stringify(resources));\n if (deep) {\n deepExtend(pack, resources, overwrite);\n } else {\n pack = {\n ...pack,\n ...resources\n };\n }\n setPath(this.data, path, pack);\n if (!options.silent) this.emit('added', lng, ns, resources);\n }\n removeResourceBundle(lng, ns) {\n if (this.hasResourceBundle(lng, ns)) {\n delete this.data[lng][ns];\n }\n this.removeNamespaces(ns);\n this.emit('removed', lng, ns);\n }\n hasResourceBundle(lng, ns) {\n return this.getResource(lng, ns) !== undefined;\n }\n getResourceBundle(lng, ns) {\n if (!ns) ns = this.options.defaultNS;\n return this.getResource(lng, ns);\n }\n getDataByLanguage(lng) {\n return this.data[lng];\n }\n hasLanguageSomeTranslations(lng) {\n const data = this.getDataByLanguage(lng);\n const n = data && Object.keys(data) || [];\n return !!n.find(v => data[v] && Object.keys(data[v]).length > 0);\n }\n toJSON() {\n return this.data;\n }\n}\n\nvar postProcessor = {\n processors: {},\n addPostProcessor(module) {\n this.processors[module.name] = module;\n },\n handle(processors, value, key, options, translator) {\n processors.forEach(processor => {\n value = this.processors[processor]?.process(value, key, options, translator) ?? value;\n });\n return value;\n }\n};\n\nconst PATH_KEY = Symbol('i18next/PATH_KEY');\nfunction createProxy() {\n const state = [];\n const handler = Object.create(null);\n let proxy;\n handler.get = (target, key) => {\n proxy?.revoke?.();\n if (key === PATH_KEY) return state;\n state.push(key);\n proxy = Proxy.revocable(target, handler);\n return proxy.proxy;\n };\n return Proxy.revocable(Object.create(null), handler).proxy;\n}\nfunction keysFromSelector(selector, opts) {\n const {\n [PATH_KEY]: path\n } = selector(createProxy());\n return path.join(opts?.keySeparator ?? '.');\n}\n\nconst checkedLoadedFor = {};\nconst shouldHandleAsObject = res => !isString(res) && typeof res !== 'boolean' && typeof res !== 'number';\nclass Translator extends EventEmitter {\n constructor(services, options = {}) {\n super();\n copy(['resourceStore', 'languageUtils', 'pluralResolver', 'interpolator', 'backendConnector', 'i18nFormat', 'utils'], services, this);\n this.options = options;\n if (this.options.keySeparator === undefined) {\n this.options.keySeparator = '.';\n }\n this.logger = baseLogger.create('translator');\n }\n changeLanguage(lng) {\n if (lng) this.language = lng;\n }\n exists(key, o = {\n interpolation: {}\n }) {\n const opt = {\n ...o\n };\n if (key == null) return false;\n const resolved = this.resolve(key, opt);\n if (resolved?.res === undefined) return false;\n const isObject = shouldHandleAsObject(resolved.res);\n if (opt.returnObjects === false && isObject) {\n return false;\n }\n return true;\n }\n extractFromKey(key, opt) {\n let nsSeparator = opt.nsSeparator !== undefined ? opt.nsSeparator : this.options.nsSeparator;\n if (nsSeparator === undefined) nsSeparator = ':';\n const keySeparator = opt.keySeparator !== undefined ? opt.keySeparator : this.options.keySeparator;\n let namespaces = opt.ns || this.options.defaultNS || [];\n const wouldCheckForNsInKey = nsSeparator && key.indexOf(nsSeparator) > -1;\n const seemsNaturalLanguage = !this.options.userDefinedKeySeparator && !opt.keySeparator && !this.options.userDefinedNsSeparator && !opt.nsSeparator && !looksLikeObjectPath(key, nsSeparator, keySeparator);\n if (wouldCheckForNsInKey && !seemsNaturalLanguage) {\n const m = key.match(this.interpolator.nestingRegexp);\n if (m && m.length > 0) {\n return {\n key,\n namespaces: isString(namespaces) ? [namespaces] : namespaces\n };\n }\n const parts = key.split(nsSeparator);\n if (nsSeparator !== keySeparator || nsSeparator === keySeparator && this.options.ns.indexOf(parts[0]) > -1) namespaces = parts.shift();\n key = parts.join(keySeparator);\n }\n return {\n key,\n namespaces: isString(namespaces) ? [namespaces] : namespaces\n };\n }\n translate(keys, o, lastKey) {\n let opt = typeof o === 'object' ? {\n ...o\n } : o;\n if (typeof opt !== 'object' && this.options.overloadTranslationOptionHandler) {\n opt = this.options.overloadTranslationOptionHandler(arguments);\n }\n if (typeof opt === 'object') opt = {\n ...opt\n };\n if (!opt) opt = {};\n if (keys == null) return '';\n if (typeof keys === 'function') keys = keysFromSelector(keys, {\n ...this.options,\n ...opt\n });\n if (!Array.isArray(keys)) keys = [String(keys)];\n const returnDetails = opt.returnDetails !== undefined ? opt.returnDetails : this.options.returnDetails;\n const keySeparator = opt.keySeparator !== undefined ? opt.keySeparator : this.options.keySeparator;\n const {\n key,\n namespaces\n } = this.extractFromKey(keys[keys.length - 1], opt);\n const namespace = namespaces[namespaces.length - 1];\n let nsSeparator = opt.nsSeparator !== undefined ? opt.nsSeparator : this.options.nsSeparator;\n if (nsSeparator === undefined) nsSeparator = ':';\n const lng = opt.lng || this.language;\n const appendNamespaceToCIMode = opt.appendNamespaceToCIMode || this.options.appendNamespaceToCIMode;\n if (lng?.toLowerCase() === 'cimode') {\n if (appendNamespaceToCIMode) {\n if (returnDetails) {\n return {\n res: `${namespace}${nsSeparator}${key}`,\n usedKey: key,\n exactUsedKey: key,\n usedLng: lng,\n usedNS: namespace,\n usedParams: this.getUsedParamsDetails(opt)\n };\n }\n return `${namespace}${nsSeparator}${key}`;\n }\n if (returnDetails) {\n return {\n res: key,\n usedKey: key,\n exactUsedKey: key,\n usedLng: lng,\n usedNS: namespace,\n usedParams: this.getUsedParamsDetails(opt)\n };\n }\n return key;\n }\n const resolved = this.resolve(keys, opt);\n let res = resolved?.res;\n const resUsedKey = resolved?.usedKey || key;\n const resExactUsedKey = resolved?.exactUsedKey || key;\n const noObject = ['[object Number]', '[object Function]', '[object RegExp]'];\n const joinArrays = opt.joinArrays !== undefined ? opt.joinArrays : this.options.joinArrays;\n const handleAsObjectInI18nFormat = !this.i18nFormat || this.i18nFormat.handleAsObject;\n const needsPluralHandling = opt.count !== undefined && !isString(opt.count);\n const hasDefaultValue = Translator.hasDefaultValue(opt);\n const defaultValueSuffix = needsPluralHandling ? this.pluralResolver.getSuffix(lng, opt.count, opt) : '';\n const defaultValueSuffixOrdinalFallback = opt.ordinal && needsPluralHandling ? this.pluralResolver.getSuffix(lng, opt.count, {\n ordinal: false\n }) : '';\n const needsZeroSuffixLookup = needsPluralHandling && !opt.ordinal && opt.count === 0;\n const defaultValue = needsZeroSuffixLookup && opt[`defaultValue${this.options.pluralSeparator}zero`] || opt[`defaultValue${defaultValueSuffix}`] || opt[`defaultValue${defaultValueSuffixOrdinalFallback}`] || opt.defaultValue;\n let resForObjHndl = res;\n if (handleAsObjectInI18nFormat && !res && hasDefaultValue) {\n resForObjHndl = defaultValue;\n }\n const handleAsObject = shouldHandleAsObject(resForObjHndl);\n const resType = Object.prototype.toString.apply(resForObjHndl);\n if (handleAsObjectInI18nFormat && resForObjHndl && handleAsObject && noObject.indexOf(resType) < 0 && !(isString(joinArrays) && Array.isArray(resForObjHndl))) {\n if (!opt.returnObjects && !this.options.returnObjects) {\n if (!this.options.returnedObjectHandler) {\n this.logger.warn('accessing an object - but returnObjects options is not enabled!');\n }\n const r = this.options.returnedObjectHandler ? this.options.returnedObjectHandler(resUsedKey, resForObjHndl, {\n ...opt,\n ns: namespaces\n }) : `key '${key} (${this.language})' returned an object instead of string.`;\n if (returnDetails) {\n resolved.res = r;\n resolved.usedParams = this.getUsedParamsDetails(opt);\n return resolved;\n }\n return r;\n }\n if (keySeparator) {\n const resTypeIsArray = Array.isArray(resForObjHndl);\n const copy = resTypeIsArray ? [] : {};\n const newKeyToUse = resTypeIsArray ? resExactUsedKey : resUsedKey;\n for (const m in resForObjHndl) {\n if (Object.prototype.hasOwnProperty.call(resForObjHndl, m)) {\n const deepKey = `${newKeyToUse}${keySeparator}${m}`;\n if (hasDefaultValue && !res) {\n copy[m] = this.translate(deepKey, {\n ...opt,\n defaultValue: shouldHandleAsObject(defaultValue) ? defaultValue[m] : undefined,\n ...{\n joinArrays: false,\n ns: namespaces\n }\n });\n } else {\n copy[m] = this.translate(deepKey, {\n ...opt,\n ...{\n joinArrays: false,\n ns: namespaces\n }\n });\n }\n if (copy[m] === deepKey) copy[m] = resForObjHndl[m];\n }\n }\n res = copy;\n }\n } else if (handleAsObjectInI18nFormat && isString(joinArrays) && Array.isArray(res)) {\n res = res.join(joinArrays);\n if (res) res = this.extendTranslation(res, keys, opt, lastKey);\n } else {\n let usedDefault = false;\n let usedKey = false;\n if (!this.isValidLookup(res) && hasDefaultValue) {\n usedDefault = true;\n res = defaultValue;\n }\n if (!this.isValidLookup(res)) {\n usedKey = true;\n res = key;\n }\n const missingKeyNoValueFallbackToKey = opt.missingKeyNoValueFallbackToKey || this.options.missingKeyNoValueFallbackToKey;\n const resForMissing = missingKeyNoValueFallbackToKey && usedKey ? undefined : res;\n const updateMissing = hasDefaultValue && defaultValue !== res && this.options.updateMissing;\n if (usedKey || usedDefault || updateMissing) {\n this.logger.log(updateMissing ? 'updateKey' : 'missingKey', lng, namespace, key, updateMissing ? defaultValue : res);\n if (keySeparator) {\n const fk = this.resolve(key, {\n ...opt,\n keySeparator: false\n });\n if (fk && fk.res) this.logger.warn('Seems the loaded translations were in flat JSON format instead of nested. Either set keySeparator: false on init or make sure your translations are published in nested format.');\n }\n let lngs = [];\n const fallbackLngs = this.languageUtils.getFallbackCodes(this.options.fallbackLng, opt.lng || this.language);\n if (this.options.saveMissingTo === 'fallback' && fallbackLngs && fallbackLngs[0]) {\n for (let i = 0; i < fallbackLngs.length; i++) {\n lngs.push(fallbackLngs[i]);\n }\n } else if (this.options.saveMissingTo === 'all') {\n lngs = this.languageUtils.toResolveHierarchy(opt.lng || this.language);\n } else {\n lngs.push(opt.lng || this.language);\n }\n const send = (l, k, specificDefaultValue) => {\n const defaultForMissing = hasDefaultValue && specificDefaultValue !== res ? specificDefaultValue : resForMissing;\n if (this.options.missingKeyHandler) {\n this.options.missingKeyHandler(l, namespace, k, defaultForMissing, updateMissing, opt);\n } else if (this.backendConnector?.saveMissing) {\n this.backendConnector.saveMissing(l, namespace, k, defaultForMissing, updateMissing, opt);\n }\n this.emit('missingKey', l, namespace, k, res);\n };\n if (this.options.saveMissing) {\n if (this.options.saveMissingPlurals && needsPluralHandling) {\n lngs.forEach(language => {\n const suffixes = this.pluralResolver.getSuffixes(language, opt);\n if (needsZeroSuffixLookup && opt[`defaultValue${this.options.pluralSeparator}zero`] && suffixes.indexOf(`${this.options.pluralSeparator}zero`) < 0) {\n suffixes.push(`${this.options.pluralSeparator}zero`);\n }\n suffixes.forEach(suffix => {\n send([language], key + suffix, opt[`defaultValue${suffix}`] || defaultValue);\n });\n });\n } else {\n send(lngs, key, defaultValue);\n }\n }\n }\n res = this.extendTranslation(res, keys, opt, resolved, lastKey);\n if (usedKey && res === key && this.options.appendNamespaceToMissingKey) {\n res = `${namespace}${nsSeparator}${key}`;\n }\n if ((usedKey || usedDefault) && this.options.parseMissingKeyHandler) {\n res = this.options.parseMissingKeyHandler(this.options.appendNamespaceToMissingKey ? `${namespace}${nsSeparator}${key}` : key, usedDefault ? res : undefined, opt);\n }\n }\n if (returnDetails) {\n resolved.res = res;\n resolved.usedParams = this.getUsedParamsDetails(opt);\n return resolved;\n }\n return res;\n }\n extendTranslation(res, key, opt, resolved, lastKey) {\n if (this.i18nFormat?.parse) {\n res = this.i18nFormat.parse(res, {\n ...this.options.interpolation.defaultVariables,\n ...opt\n }, opt.lng || this.language || resolved.usedLng, resolved.usedNS, resolved.usedKey, {\n resolved\n });\n } else if (!opt.skipInterpolation) {\n if (opt.interpolation) this.interpolator.init({\n ...opt,\n ...{\n interpolation: {\n ...this.options.interpolation,\n ...opt.interpolation\n }\n }\n });\n const skipOnVariables = isString(res) && (opt?.interpolation?.skipOnVariables !== undefined ? opt.interpolation.skipOnVariables : this.options.interpolation.skipOnVariables);\n let nestBef;\n if (skipOnVariables) {\n const nb = res.match(this.interpolator.nestingRegexp);\n nestBef = nb && nb.length;\n }\n let data = opt.replace && !isString(opt.replace) ? opt.replace : opt;\n if (this.options.interpolation.defaultVariables) data = {\n ...this.options.interpolation.defaultVariables,\n ...data\n };\n res = this.interpolator.interpolate(res, data, opt.lng || this.language || resolved.usedLng, opt);\n if (skipOnVariables) {\n const na = res.match(this.interpolator.nestingRegexp);\n const nestAft = na && na.length;\n if (nestBef < nestAft) opt.nest = false;\n }\n if (!opt.lng && resolved && resolved.res) opt.lng = this.language || resolved.usedLng;\n if (opt.nest !== false) res = this.interpolator.nest(res, (...args) => {\n if (lastKey?.[0] === args[0] && !opt.context) {\n this.logger.warn(`It seems you are nesting recursively key: ${args[0]} in key: ${key[0]}`);\n return null;\n }\n return this.translate(...args, key);\n }, opt);\n if (opt.interpolation) this.interpolator.reset();\n }\n const postProcess = opt.postProcess || this.options.postProcess;\n const postProcessorNames = isString(postProcess) ? [postProcess] : postProcess;\n if (res != null && postProcessorNames?.length && opt.applyPostProcessor !== false) {\n res = postProcessor.handle(postProcessorNames, res, key, this.options && this.options.postProcessPassResolved ? {\n i18nResolved: {\n ...resolved,\n usedParams: this.getUsedParamsDetails(opt)\n },\n ...opt\n } : opt, this);\n }\n return res;\n }\n resolve(keys, opt = {}) {\n let found;\n let usedKey;\n let exactUsedKey;\n let usedLng;\n let usedNS;\n if (isString(keys)) keys = [keys];\n keys.forEach(k => {\n if (this.isValidLookup(found)) return;\n const extracted = this.extractFromKey(k, opt);\n const key = extracted.key;\n usedKey = key;\n let namespaces = extracted.namespaces;\n if (this.options.fallbackNS) namespaces = namespaces.concat(this.options.fallbackNS);\n const needsPluralHandling = opt.count !== undefined && !isString(opt.count);\n const needsZeroSuffixLookup = needsPluralHandling && !opt.ordinal && opt.count === 0;\n const needsContextHandling = opt.context !== undefined && (isString(opt.context) || typeof opt.context === 'number') && opt.context !== '';\n const codes = opt.lngs ? opt.lngs : this.languageUtils.toResolveHierarchy(opt.lng || this.language, opt.fallbackLng);\n namespaces.forEach(ns => {\n if (this.isValidLookup(found)) return;\n usedNS = ns;\n if (!checkedLoadedFor[`${codes[0]}-${ns}`] && this.utils?.hasLoadedNamespace && !this.utils?.hasLoadedNamespace(usedNS)) {\n checkedLoadedFor[`${codes[0]}-${ns}`] = true;\n this.logger.warn(`key \"${usedKey}\" for languages \"${codes.join(', ')}\" won't get resolved as namespace \"${usedNS}\" was not yet loaded`, 'This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!');\n }\n codes.forEach(code => {\n if (this.isValidLookup(found)) return;\n usedLng = code;\n const finalKeys = [key];\n if (this.i18nFormat?.addLookupKeys) {\n this.i18nFormat.addLookupKeys(finalKeys, key, code, ns, opt);\n } else {\n let pluralSuffix;\n if (needsPluralHandling) pluralSuffix = this.pluralResolver.getSuffix(code, opt.count, opt);\n const zeroSuffix = `${this.options.pluralSeparator}zero`;\n const ordinalPrefix = `${this.options.pluralSeparator}ordinal${this.options.pluralSeparator}`;\n if (needsPluralHandling) {\n if (opt.ordinal && pluralSuffix.indexOf(ordinalPrefix) === 0) {\n finalKeys.push(key + pluralSuffix.replace(ordinalPrefix, this.options.pluralSeparator));\n }\n finalKeys.push(key + pluralSuffix);\n if (needsZeroSuffixLookup) {\n finalKeys.push(key + zeroSuffix);\n }\n }\n if (needsContextHandling) {\n const contextKey = `${key}${this.options.contextSeparator || '_'}${opt.context}`;\n finalKeys.push(contextKey);\n if (needsPluralHandling) {\n if (opt.ordinal && pluralSuffix.indexOf(ordinalPrefix) === 0) {\n finalKeys.push(contextKey + pluralSuffix.replace(ordinalPrefix, this.options.pluralSeparator));\n }\n finalKeys.push(contextKey + pluralSuffix);\n if (needsZeroSuffixLookup) {\n finalKeys.push(contextKey + zeroSuffix);\n }\n }\n }\n }\n let possibleKey;\n while (possibleKey = finalKeys.pop()) {\n if (!this.isValidLookup(found)) {\n exactUsedKey = possibleKey;\n found = this.getResource(code, ns, possibleKey, opt);\n }\n }\n });\n });\n });\n return {\n res: found,\n usedKey,\n exactUsedKey,\n usedLng,\n usedNS\n };\n }\n isValidLookup(res) {\n return res !== undefined && !(!this.options.returnNull && res === null) && !(!this.options.returnEmptyString && res === '');\n }\n getResource(code, ns, key, options = {}) {\n if (this.i18nFormat?.getResource) return this.i18nFormat.getResource(code, ns, key, options);\n return this.resourceStore.getResource(code, ns, key, options);\n }\n getUsedParamsDetails(options = {}) {\n const optionsKeys = ['defaultValue', 'ordinal', 'context', 'replace', 'lng', 'lngs', 'fallbackLng', 'ns', 'keySeparator', 'nsSeparator', 'returnObjects', 'returnDetails', 'joinArrays', 'postProcess', 'interpolation'];\n const useOptionsReplaceForData = options.replace && !isString(options.replace);\n let data = useOptionsReplaceForData ? options.replace : options;\n if (useOptionsReplaceForData && typeof options.count !== 'undefined') {\n data.count = options.count;\n }\n if (this.options.interpolation.defaultVariables) {\n data = {\n ...this.options.interpolation.defaultVariables,\n ...data\n };\n }\n if (!useOptionsReplaceForData) {\n data = {\n ...data\n };\n for (const key of optionsKeys) {\n delete data[key];\n }\n }\n return data;\n }\n static hasDefaultValue(options) {\n const prefix = 'defaultValue';\n for (const option in options) {\n if (Object.prototype.hasOwnProperty.call(options, option) && prefix === option.substring(0, prefix.length) && undefined !== options[option]) {\n return true;\n }\n }\n return false;\n }\n}\n\nclass LanguageUtil {\n constructor(options) {\n this.options = options;\n this.supportedLngs = this.options.supportedLngs || false;\n this.logger = baseLogger.create('languageUtils');\n }\n getScriptPartFromCode(code) {\n code = getCleanedCode(code);\n if (!code || code.indexOf('-') < 0) return null;\n const p = code.split('-');\n if (p.length === 2) return null;\n p.pop();\n if (p[p.length - 1].toLowerCase() === 'x') return null;\n return this.formatLanguageCode(p.join('-'));\n }\n getLanguagePartFromCode(code) {\n code = getCleanedCode(code);\n if (!code || code.indexOf('-') < 0) return code;\n const p = code.split('-');\n return this.formatLanguageCode(p[0]);\n }\n formatLanguageCode(code) {\n if (isString(code) && code.indexOf('-') > -1) {\n let formattedCode;\n try {\n formattedCode = Intl.getCanonicalLocales(code)[0];\n } catch (e) {}\n if (formattedCode && this.options.lowerCaseLng) {\n formattedCode = formattedCode.toLowerCase();\n }\n if (formattedCode) return formattedCode;\n if (this.options.lowerCaseLng) {\n return code.toLowerCase();\n }\n return code;\n }\n return this.options.cleanCode || this.options.lowerCaseLng ? code.toLowerCase() : code;\n }\n isSupportedCode(code) {\n if (this.options.load === 'languageOnly' || this.options.nonExplicitSupportedLngs) {\n code = this.getLanguagePartFromCode(code);\n }\n return !this.supportedLngs || !this.supportedLngs.length || this.supportedLngs.indexOf(code) > -1;\n }\n getBestMatchFromCodes(codes) {\n if (!codes) return null;\n let found;\n codes.forEach(code => {\n if (found) return;\n const cleanedLng = this.formatLanguageCode(code);\n if (!this.options.supportedLngs || this.isSupportedCode(cleanedLng)) found = cleanedLng;\n });\n if (!found && this.options.supportedLngs) {\n codes.forEach(code => {\n if (found) return;\n const lngScOnly = this.getScriptPartFromCode(code);\n if (this.isSupportedCode(lngScOnly)) return found = lngScOnly;\n const lngOnly = this.getLanguagePartFromCode(code);\n if (this.isSupportedCode(lngOnly)) return found = lngOnly;\n found = this.options.supportedLngs.find(supportedLng => {\n if (supportedLng === lngOnly) return supportedLng;\n if (supportedLng.indexOf('-') < 0 && lngOnly.indexOf('-') < 0) return;\n if (supportedLng.indexOf('-') > 0 && lngOnly.indexOf('-') < 0 && supportedLng.substring(0, supportedLng.indexOf('-')) === lngOnly) return supportedLng;\n if (supportedLng.indexOf(lngOnly) === 0 && lngOnly.length > 1) return supportedLng;\n });\n });\n }\n if (!found) found = this.getFallbackCodes(this.options.fallbackLng)[0];\n return found;\n }\n getFallbackCodes(fallbacks, code) {\n if (!fallbacks) return [];\n if (typeof fallbacks === 'function') fallbacks = fallbacks(code);\n if (isString(fallbacks)) fallbacks = [fallbacks];\n if (Array.isArray(fallbacks)) return fallbacks;\n if (!code) return fallbacks.default || [];\n let found = fallbacks[code];\n if (!found) found = fallbacks[this.getScriptPartFromCode(code)];\n if (!found) found = fallbacks[this.formatLanguageCode(code)];\n if (!found) found = fallbacks[this.getLanguagePartFromCode(code)];\n if (!found) found = fallbacks.default;\n return found || [];\n }\n toResolveHierarchy(code, fallbackCode) {\n const fallbackCodes = this.getFallbackCodes((fallbackCode === false ? [] : fallbackCode) || this.options.fallbackLng || [], code);\n const codes = [];\n const addCode = c => {\n if (!c) return;\n if (this.isSupportedCode(c)) {\n codes.push(c);\n } else {\n this.logger.warn(`rejecting language code not found in supportedLngs: ${c}`);\n }\n };\n if (isString(code) && (code.indexOf('-') > -1 || code.indexOf('_') > -1)) {\n if (this.options.load !== 'languageOnly') addCode(this.formatLanguageCode(code));\n if (this.options.load !== 'languageOnly' && this.options.load !== 'currentOnly') addCode(this.getScriptPartFromCode(code));\n if (this.options.load !== 'currentOnly') addCode(this.getLanguagePartFromCode(code));\n } else if (isString(code)) {\n addCode(this.formatLanguageCode(code));\n }\n fallbackCodes.forEach(fc => {\n if (codes.indexOf(fc) < 0) addCode(this.formatLanguageCode(fc));\n });\n return codes;\n }\n}\n\nconst suffixesOrder = {\n zero: 0,\n one: 1,\n two: 2,\n few: 3,\n many: 4,\n other: 5\n};\nconst dummyRule = {\n select: count => count === 1 ? 'one' : 'other',\n resolvedOptions: () => ({\n pluralCategories: ['one', 'other']\n })\n};\nclass PluralResolver {\n constructor(languageUtils, options = {}) {\n this.languageUtils = languageUtils;\n this.options = options;\n this.logger = baseLogger.create('pluralResolver');\n this.pluralRulesCache = {};\n }\n clearCache() {\n this.pluralRulesCache = {};\n }\n getRule(code, options = {}) {\n const cleanedCode = getCleanedCode(code === 'dev' ? 'en' : code);\n const type = options.ordinal ? 'ordinal' : 'cardinal';\n const cacheKey = JSON.stringify({\n cleanedCode,\n type\n });\n if (cacheKey in this.pluralRulesCache) {\n return this.pluralRulesCache[cacheKey];\n }\n let rule;\n try {\n rule = new Intl.PluralRules(cleanedCode, {\n type\n });\n } catch (err) {\n if (typeof Intl === 'undefined') {\n this.logger.error('No Intl support, please use an Intl polyfill!');\n return dummyRule;\n }\n if (!code.match(/-|_/)) return dummyRule;\n const lngPart = this.languageUtils.getLanguagePartFromCode(code);\n rule = this.getRule(lngPart, options);\n }\n this.pluralRulesCache[cacheKey] = rule;\n return rule;\n }\n needsPlural(code, options = {}) {\n let rule = this.getRule(code, options);\n if (!rule) rule = this.getRule('dev', options);\n return rule?.resolvedOptions().pluralCategories.length > 1;\n }\n getPluralFormsOfKey(code, key, options = {}) {\n return this.getSuffixes(code, options).map(suffix => `${key}${suffix}`);\n }\n getSuffixes(code, options = {}) {\n let rule = this.getRule(code, options);\n if (!rule) rule = this.getRule('dev', options);\n if (!rule) return [];\n return rule.resolvedOptions().pluralCategories.sort((pluralCategory1, pluralCategory2) => suffixesOrder[pluralCategory1] - suffixesOrder[pluralCategory2]).map(pluralCategory => `${this.options.prepend}${options.ordinal ? `ordinal${this.options.prepend}` : ''}${pluralCategory}`);\n }\n getSuffix(code, count, options = {}) {\n const rule = this.getRule(code, options);\n if (rule) {\n return `${this.options.prepend}${options.ordinal ? `ordinal${this.options.prepend}` : ''}${rule.select(count)}`;\n }\n this.logger.warn(`no plural rule found for: ${code}`);\n return this.getSuffix('dev', count, options);\n }\n}\n\nconst deepFindWithDefaults = (data, defaultData, key, keySeparator = '.', ignoreJSONStructure = true) => {\n let path = getPathWithDefaults(data, defaultData, key);\n if (!path && ignoreJSONStructure && isString(key)) {\n path = deepFind(data, key, keySeparator);\n if (path === undefined) path = deepFind(defaultData, key, keySeparator);\n }\n return path;\n};\nconst regexSafe = val => val.replace(/\\$/g, '$$$$');\nclass Interpolator {\n constructor(options = {}) {\n this.logger = baseLogger.create('interpolator');\n this.options = options;\n this.format = options?.interpolation?.format || (value => value);\n this.init(options);\n }\n init(options = {}) {\n if (!options.interpolation) options.interpolation = {\n escapeValue: true\n };\n const {\n escape: escape$1,\n escapeValue,\n useRawValueToEscape,\n prefix,\n prefixEscaped,\n suffix,\n suffixEscaped,\n formatSeparator,\n unescapeSuffix,\n unescapePrefix,\n nestingPrefix,\n nestingPrefixEscaped,\n nestingSuffix,\n nestingSuffixEscaped,\n nestingOptionsSeparator,\n maxReplaces,\n alwaysFormat\n } = options.interpolation;\n this.escape = escape$1 !== undefined ? escape$1 : escape;\n this.escapeValue = escapeValue !== undefined ? escapeValue : true;\n this.useRawValueToEscape = useRawValueToEscape !== undefined ? useRawValueToEscape : false;\n this.prefix = prefix ? regexEscape(prefix) : prefixEscaped || '{{';\n this.suffix = suffix ? regexEscape(suffix) : suffixEscaped || '}}';\n this.formatSeparator = formatSeparator || ',';\n this.unescapePrefix = unescapeSuffix ? '' : unescapePrefix || '-';\n this.unescapeSuffix = this.unescapePrefix ? '' : unescapeSuffix || '';\n this.nestingPrefix = nestingPrefix ? regexEscape(nestingPrefix) : nestingPrefixEscaped || regexEscape('$t(');\n this.nestingSuffix = nestingSuffix ? regexEscape(nestingSuffix) : nestingSuffixEscaped || regexEscape(')');\n this.nestingOptionsSeparator = nestingOptionsSeparator || ',';\n this.maxReplaces = maxReplaces || 1000;\n this.alwaysFormat = alwaysFormat !== undefined ? alwaysFormat : false;\n this.resetRegExp();\n }\n reset() {\n if (this.options) this.init(this.options);\n }\n resetRegExp() {\n const getOrResetRegExp = (existingRegExp, pattern) => {\n if (existingRegExp?.source === pattern) {\n existingRegExp.lastIndex = 0;\n return existingRegExp;\n }\n return new RegExp(pattern, 'g');\n };\n this.regexp = getOrResetRegExp(this.regexp, `${this.prefix}(.+?)${this.suffix}`);\n this.regexpUnescape = getOrResetRegExp(this.regexpUnescape, `${this.prefix}${this.unescapePrefix}(.+?)${this.unescapeSuffix}${this.suffix}`);\n this.nestingRegexp = getOrResetRegExp(this.nestingRegexp, `${this.nestingPrefix}((?:[^()\"']+|\"[^\"]*\"|'[^']*'|\\\\((?:[^()]|\"[^\"]*\"|'[^']*')*\\\\))*?)${this.nestingSuffix}`);\n }\n interpolate(str, data, lng, options) {\n let match;\n let value;\n let replaces;\n const defaultData = this.options && this.options.interpolation && this.options.interpolation.defaultVariables || {};\n const handleFormat = key => {\n if (key.indexOf(this.formatSeparator) < 0) {\n const path = deepFindWithDefaults(data, defaultData, key, this.options.keySeparator, this.options.ignoreJSONStructure);\n return this.alwaysFormat ? this.format(path, undefined, lng, {\n ...options,\n ...data,\n interpolationkey: key\n }) : path;\n }\n const p = key.split(this.formatSeparator);\n const k = p.shift().trim();\n const f = p.join(this.formatSeparator).trim();\n return this.format(deepFindWithDefaults(data, defaultData, k, this.options.keySeparator, this.options.ignoreJSONStructure), f, lng, {\n ...options,\n ...data,\n interpolationkey: k\n });\n };\n this.resetRegExp();\n const missingInterpolationHandler = options?.missingInterpolationHandler || this.options.missingInterpolationHandler;\n const skipOnVariables = options?.interpolation?.skipOnVariables !== undefined ? options.interpolation.skipOnVariables : this.options.interpolation.skipOnVariables;\n const todos = [{\n regex: this.regexpUnescape,\n safeValue: val => regexSafe(val)\n }, {\n regex: this.regexp,\n safeValue: val => this.escapeValue ? regexSafe(this.escape(val)) : regexSafe(val)\n }];\n todos.forEach(todo => {\n replaces = 0;\n while (match = todo.regex.exec(str)) {\n const matchedVar = match[1].trim();\n value = handleFormat(matchedVar);\n if (value === undefined) {\n if (typeof missingInterpolationHandler === 'function') {\n const temp = missingInterpolationHandler(str, match, options);\n value = isString(temp) ? temp : '';\n } else if (options && Object.prototype.hasOwnProperty.call(options, matchedVar)) {\n value = '';\n } else if (skipOnVariables) {\n value = match[0];\n continue;\n } else {\n this.logger.warn(`missed to pass in variable ${matchedVar} for interpolating ${str}`);\n value = '';\n }\n } else if (!isString(value) && !this.useRawValueToEscape) {\n value = makeString(value);\n }\n const safeValue = todo.safeValue(value);\n str = str.replace(match[0], safeValue);\n if (skipOnVariables) {\n todo.regex.lastIndex += value.length;\n todo.regex.lastIndex -= match[0].length;\n } else {\n todo.regex.lastIndex = 0;\n }\n replaces++;\n if (replaces >= this.maxReplaces) {\n break;\n }\n }\n });\n return str;\n }\n nest(str, fc, options = {}) {\n let match;\n let value;\n let clonedOptions;\n const handleHasOptions = (key, inheritedOptions) => {\n const sep = this.nestingOptionsSeparator;\n if (key.indexOf(sep) < 0) return key;\n const c = key.split(new RegExp(`${regexEscape(sep)}[ ]*{`));\n let optionsString = `{${c[1]}`;\n key = c[0];\n optionsString = this.interpolate(optionsString, clonedOptions);\n const matchedSingleQuotes = optionsString.match(/'/g);\n const matchedDoubleQuotes = optionsString.match(/\"/g);\n if ((matchedSingleQuotes?.length ?? 0) % 2 === 0 && !matchedDoubleQuotes || (matchedDoubleQuotes?.length ?? 0) % 2 !== 0) {\n optionsString = optionsString.replace(/'/g, '\"');\n }\n try {\n clonedOptions = JSON.parse(optionsString);\n if (inheritedOptions) clonedOptions = {\n ...inheritedOptions,\n ...clonedOptions\n };\n } catch (e) {\n this.logger.warn(`failed parsing options string in nesting for key ${key}`, e);\n return `${key}${sep}${optionsString}`;\n }\n if (clonedOptions.defaultValue && clonedOptions.defaultValue.indexOf(this.prefix) > -1) delete clonedOptions.defaultValue;\n return key;\n };\n while (match = this.nestingRegexp.exec(str)) {\n let formatters = [];\n clonedOptions = {\n ...options\n };\n clonedOptions = clonedOptions.replace && !isString(clonedOptions.replace) ? clonedOptions.replace : clonedOptions;\n clonedOptions.applyPostProcessor = false;\n delete clonedOptions.defaultValue;\n const keyEndIndex = /{.*}/.test(match[1]) ? match[1].lastIndexOf('}') + 1 : match[1].indexOf(this.formatSeparator);\n if (keyEndIndex !== -1) {\n formatters = match[1].slice(keyEndIndex).split(this.formatSeparator).map(elem => elem.trim()).filter(Boolean);\n match[1] = match[1].slice(0, keyEndIndex);\n }\n value = fc(handleHasOptions.call(this, match[1].trim(), clonedOptions), clonedOptions);\n if (value && match[0] === str && !isString(value)) return value;\n if (!isString(value)) value = makeString(value);\n if (!value) {\n this.logger.warn(`missed to resolve ${match[1]} for nesting ${str}`);\n value = '';\n }\n if (formatters.length) {\n value = formatters.reduce((v, f) => this.format(v, f, options.lng, {\n ...options,\n interpolationkey: match[1].trim()\n }), value.trim());\n }\n str = str.replace(match[0], value);\n this.regexp.lastIndex = 0;\n }\n return str;\n }\n}\n\nconst parseFormatStr = formatStr => {\n let formatName = formatStr.toLowerCase().trim();\n const formatOptions = {};\n if (formatStr.indexOf('(') > -1) {\n const p = formatStr.split('(');\n formatName = p[0].toLowerCase().trim();\n const optStr = p[1].substring(0, p[1].length - 1);\n if (formatName === 'currency' && optStr.indexOf(':') < 0) {\n if (!formatOptions.currency) formatOptions.currency = optStr.trim();\n } else if (formatName === 'relativetime' && optStr.indexOf(':') < 0) {\n if (!formatOptions.range) formatOptions.range = optStr.trim();\n } else {\n const opts = optStr.split(';');\n opts.forEach(opt => {\n if (opt) {\n const [key, ...rest] = opt.split(':');\n const val = rest.join(':').trim().replace(/^'+|'+$/g, '');\n const trimmedKey = key.trim();\n if (!formatOptions[trimmedKey]) formatOptions[trimmedKey] = val;\n if (val === 'false') formatOptions[trimmedKey] = false;\n if (val === 'true') formatOptions[trimmedKey] = true;\n if (!isNaN(val)) formatOptions[trimmedKey] = parseInt(val, 10);\n }\n });\n }\n }\n return {\n formatName,\n formatOptions\n };\n};\nconst createCachedFormatter = fn => {\n const cache = {};\n return (v, l, o) => {\n let optForCache = o;\n if (o && o.interpolationkey && o.formatParams && o.formatParams[o.interpolationkey] && o[o.interpolationkey]) {\n optForCache = {\n ...optForCache,\n [o.interpolationkey]: undefined\n };\n }\n const key = l + JSON.stringify(optForCache);\n let frm = cache[key];\n if (!frm) {\n frm = fn(getCleanedCode(l), o);\n cache[key] = frm;\n }\n return frm(v);\n };\n};\nconst createNonCachedFormatter = fn => (v, l, o) => fn(getCleanedCode(l), o)(v);\nclass Formatter {\n constructor(options = {}) {\n this.logger = baseLogger.create('formatter');\n this.options = options;\n this.init(options);\n }\n init(services, options = {\n interpolation: {}\n }) {\n this.formatSeparator = options.interpolation.formatSeparator || ',';\n const cf = options.cacheInBuiltFormats ? createCachedFormatter : createNonCachedFormatter;\n this.formats = {\n number: cf((lng, opt) => {\n const formatter = new Intl.NumberFormat(lng, {\n ...opt\n });\n return val => formatter.format(val);\n }),\n currency: cf((lng, opt) => {\n const formatter = new Intl.NumberFormat(lng, {\n ...opt,\n style: 'currency'\n });\n return val => formatter.format(val);\n }),\n datetime: cf((lng, opt) => {\n const formatter = new Intl.DateTimeFormat(lng, {\n ...opt\n });\n return val => formatter.format(val);\n }),\n relativetime: cf((lng, opt) => {\n const formatter = new Intl.RelativeTimeFormat(lng, {\n ...opt\n });\n return val => formatter.format(val, opt.range || 'day');\n }),\n list: cf((lng, opt) => {\n const formatter = new Intl.ListFormat(lng, {\n ...opt\n });\n return val => formatter.format(val);\n })\n };\n }\n add(name, fc) {\n this.formats[name.toLowerCase().trim()] = fc;\n }\n addCached(name, fc) {\n this.formats[name.toLowerCase().trim()] = createCachedFormatter(fc);\n }\n format(value, format, lng, options = {}) {\n const formats = format.split(this.formatSeparator);\n if (formats.length > 1 && formats[0].indexOf('(') > 1 && formats[0].indexOf(')') < 0 && formats.find(f => f.indexOf(')') > -1)) {\n const lastIndex = formats.findIndex(f => f.indexOf(')') > -1);\n formats[0] = [formats[0], ...formats.splice(1, lastIndex)].join(this.formatSeparator);\n }\n const result = formats.reduce((mem, f) => {\n const {\n formatName,\n formatOptions\n } = parseFormatStr(f);\n if (this.formats[formatName]) {\n let formatted = mem;\n try {\n const valOptions = options?.formatParams?.[options.interpolationkey] || {};\n const l = valOptions.locale || valOptions.lng || options.locale || options.lng || lng;\n formatted = this.formats[formatName](mem, l, {\n ...formatOptions,\n ...options,\n ...valOptions\n });\n } catch (error) {\n this.logger.warn(error);\n }\n return formatted;\n } else {\n this.logger.warn(`there was no format function for ${formatName}`);\n }\n return mem;\n }, value);\n return result;\n }\n}\n\nconst removePending = (q, name) => {\n if (q.pending[name] !== undefined) {\n delete q.pending[name];\n q.pendingCount--;\n }\n};\nclass Connector extends EventEmitter {\n constructor(backend, store, services, options = {}) {\n super();\n this.backend = backend;\n this.store = store;\n this.services = services;\n this.languageUtils = services.languageUtils;\n this.options = options;\n this.logger = baseLogger.create('backendConnector');\n this.waitingReads = [];\n this.maxParallelReads = options.maxParallelReads || 10;\n this.readingCalls = 0;\n this.maxRetries = options.maxRetries >= 0 ? options.maxRetries : 5;\n this.retryTimeout = options.retryTimeout >= 1 ? options.retryTimeout : 350;\n this.state = {};\n this.queue = [];\n this.backend?.init?.(services, options.backend, options);\n }\n queueLoad(languages, namespaces, options, callback) {\n const toLoad = {};\n const pending = {};\n const toLoadLanguages = {};\n const toLoadNamespaces = {};\n languages.forEach(lng => {\n let hasAllNamespaces = true;\n namespaces.forEach(ns => {\n const name = `${lng}|${ns}`;\n if (!options.reload && this.store.hasResourceBundle(lng, ns)) {\n this.state[name] = 2;\n } else if (this.state[name] < 0) ; else if (this.state[name] === 1) {\n if (pending[name] === undefined) pending[name] = true;\n } else {\n this.state[name] = 1;\n hasAllNamespaces = false;\n if (pending[name] === undefined) pending[name] = true;\n if (toLoad[name] === undefined) toLoad[name] = true;\n if (toLoadNamespaces[ns] === undefined) toLoadNamespaces[ns] = true;\n }\n });\n if (!hasAllNamespaces) toLoadLanguages[lng] = true;\n });\n if (Object.keys(toLoad).length || Object.keys(pending).length) {\n this.queue.push({\n pending,\n pendingCount: Object.keys(pending).length,\n loaded: {},\n errors: [],\n callback\n });\n }\n return {\n toLoad: Object.keys(toLoad),\n pending: Object.keys(pending),\n toLoadLanguages: Object.keys(toLoadLanguages),\n toLoadNamespaces: Object.keys(toLoadNamespaces)\n };\n }\n loaded(name, err, data) {\n const s = name.split('|');\n const lng = s[0];\n const ns = s[1];\n if (err) this.emit('failedLoading', lng, ns, err);\n if (!err && data) {\n this.store.addResourceBundle(lng, ns, data, undefined, undefined, {\n skipCopy: true\n });\n }\n this.state[name] = err ? -1 : 2;\n if (err && data) this.state[name] = 0;\n const loaded = {};\n this.queue.forEach(q => {\n pushPath(q.loaded, [lng], ns);\n removePending(q, name);\n if (err) q.errors.push(err);\n if (q.pendingCount === 0 && !q.done) {\n Object.keys(q.loaded).forEach(l => {\n if (!loaded[l]) loaded[l] = {};\n const loadedKeys = q.loaded[l];\n if (loadedKeys.length) {\n loadedKeys.forEach(n => {\n if (loaded[l][n] === undefined) loaded[l][n] = true;\n });\n }\n });\n q.done = true;\n if (q.errors.length) {\n q.callback(q.errors);\n } else {\n q.callback();\n }\n }\n });\n this.emit('loaded', loaded);\n this.queue = this.queue.filter(q => !q.done);\n }\n read(lng, ns, fcName, tried = 0, wait = this.retryTimeout, callback) {\n if (!lng.length) return callback(null, {});\n if (this.readingCalls >= this.maxParallelReads) {\n this.waitingReads.push({\n lng,\n ns,\n fcName,\n tried,\n wait,\n callback\n });\n return;\n }\n this.readingCalls++;\n const resolver = (err, data) => {\n this.readingCalls--;\n if (this.waitingReads.length > 0) {\n const next = this.waitingReads.shift();\n this.read(next.lng, next.ns, next.fcName, next.tried, next.wait, next.callback);\n }\n if (err && data && tried < this.maxRetries) {\n setTimeout(() => {\n this.read.call(this, lng, ns, fcName, tried + 1, wait * 2, callback);\n }, wait);\n return;\n }\n callback(err, data);\n };\n const fc = this.backend[fcName].bind(this.backend);\n if (fc.length === 2) {\n try {\n const r = fc(lng, ns);\n if (r && typeof r.then === 'function') {\n r.then(data => resolver(null, data)).catch(resolver);\n } else {\n resolver(null, r);\n }\n } catch (err) {\n resolver(err);\n }\n return;\n }\n return fc(lng, ns, resolver);\n }\n prepareLoading(languages, namespaces, options = {}, callback) {\n if (!this.backend) {\n this.logger.warn('No backend was added via i18next.use. Will not load resources.');\n return callback && callback();\n }\n if (isString(languages)) languages = this.languageUtils.toResolveHierarchy(languages);\n if (isString(namespaces)) namespaces = [namespaces];\n const toLoad = this.queueLoad(languages, namespaces, options, callback);\n if (!toLoad.toLoad.length) {\n if (!toLoad.pending.length) callback();\n return null;\n }\n toLoad.toLoad.forEach(name => {\n this.loadOne(name);\n });\n }\n load(languages, namespaces, callback) {\n this.prepareLoading(languages, namespaces, {}, callback);\n }\n reload(languages, namespaces, callback) {\n this.prepareLoading(languages, namespaces, {\n reload: true\n }, callback);\n }\n loadOne(name, prefix = '') {\n const s = name.split('|');\n const lng = s[0];\n const ns = s[1];\n this.read(lng, ns, 'read', undefined, undefined, (err, data) => {\n if (err) this.logger.warn(`${prefix}loading namespace ${ns} for language ${lng} failed`, err);\n if (!err && data) this.logger.log(`${prefix}loaded namespace ${ns} for language ${lng}`, data);\n this.loaded(name, err, data);\n });\n }\n saveMissing(languages, namespace, key, fallbackValue, isUpdate, options = {}, clb = () => {}) {\n if (this.services?.utils?.hasLoadedNamespace && !this.services?.utils?.hasLoadedNamespace(namespace)) {\n this.logger.warn(`did not save key \"${key}\" as the namespace \"${namespace}\" was not yet loaded`, 'This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!');\n return;\n }\n if (key === undefined || key === null || key === '') return;\n if (this.backend?.create) {\n const opts = {\n ...options,\n isUpdate\n };\n const fc = this.backend.create.bind(this.backend);\n if (fc.length < 6) {\n try {\n let r;\n if (fc.length === 5) {\n r = fc(languages, namespace, key, fallbackValue, opts);\n } else {\n r = fc(languages, namespace, key, fallbackValue);\n }\n if (r && typeof r.then === 'function') {\n r.then(data => clb(null, data)).catch(clb);\n } else {\n clb(null, r);\n }\n } catch (err) {\n clb(err);\n }\n } else {\n fc(languages, namespace, key, fallbackValue, clb, opts);\n }\n }\n if (!languages || !languages[0]) return;\n this.store.addResource(languages[0], namespace, key, fallbackValue);\n }\n}\n\nconst get = () => ({\n debug: false,\n initAsync: true,\n ns: ['translation'],\n defaultNS: ['translation'],\n fallbackLng: ['dev'],\n fallbackNS: false,\n supportedLngs: false,\n nonExplicitSupportedLngs: false,\n load: 'all',\n preload: false,\n simplifyPluralSuffix: true,\n keySeparator: '.',\n nsSeparator: ':',\n pluralSeparator: '_',\n contextSeparator: '_',\n partialBundledLanguages: false,\n saveMissing: false,\n updateMissing: false,\n saveMissingTo: 'fallback',\n saveMissingPlurals: true,\n missingKeyHandler: false,\n missingInterpolationHandler: false,\n postProcess: false,\n postProcessPassResolved: false,\n returnNull: false,\n returnEmptyString: true,\n returnObjects: false,\n joinArrays: false,\n returnedObjectHandler: false,\n parseMissingKeyHandler: false,\n appendNamespaceToMissingKey: false,\n appendNamespaceToCIMode: false,\n overloadTranslationOptionHandler: args => {\n let ret = {};\n if (typeof args[1] === 'object') ret = args[1];\n if (isString(args[1])) ret.defaultValue = args[1];\n if (isString(args[2])) ret.tDescription = args[2];\n if (typeof args[2] === 'object' || typeof args[3] === 'object') {\n const options = args[3] || args[2];\n Object.keys(options).forEach(key => {\n ret[key] = options[key];\n });\n }\n return ret;\n },\n interpolation: {\n escapeValue: true,\n format: value => value,\n prefix: '{{',\n suffix: '}}',\n formatSeparator: ',',\n unescapePrefix: '-',\n nestingPrefix: '$t(',\n nestingSuffix: ')',\n nestingOptionsSeparator: ',',\n maxReplaces: 1000,\n skipOnVariables: true\n },\n cacheInBuiltFormats: true\n});\nconst transformOptions = options => {\n if (isString(options.ns)) options.ns = [options.ns];\n if (isString(options.fallbackLng)) options.fallbackLng = [options.fallbackLng];\n if (isString(options.fallbackNS)) options.fallbackNS = [options.fallbackNS];\n if (options.supportedLngs?.indexOf?.('cimode') < 0) {\n options.supportedLngs = options.supportedLngs.concat(['cimode']);\n }\n if (typeof options.initImmediate === 'boolean') options.initAsync = options.initImmediate;\n return options;\n};\n\nconst noop = () => {};\nconst bindMemberFunctions = inst => {\n const mems = Object.getOwnPropertyNames(Object.getPrototypeOf(inst));\n mems.forEach(mem => {\n if (typeof inst[mem] === 'function') {\n inst[mem] = inst[mem].bind(inst);\n }\n });\n};\nconst SUPPORT_NOTICE_KEY = '__i18next_supportNoticeShown';\nconst getSupportNoticeShown = () => typeof globalThis !== 'undefined' && !!globalThis[SUPPORT_NOTICE_KEY];\nconst setSupportNoticeShown = () => {\n if (typeof globalThis !== 'undefined') globalThis[SUPPORT_NOTICE_KEY] = true;\n};\nconst usesLocize = inst => {\n if (inst?.modules?.backend?.name?.indexOf('Locize') > 0) return true;\n if (inst?.modules?.backend?.constructor?.name?.indexOf('Locize') > 0) return true;\n if (inst?.options?.backend?.backends) {\n if (inst.options.backend.backends.some(b => b?.name?.indexOf('Locize') > 0 || b?.constructor?.name?.indexOf('Locize') > 0)) return true;\n }\n if (inst?.options?.backend?.projectId) return true;\n if (inst?.options?.backend?.backendOptions) {\n if (inst.options.backend.backendOptions.some(b => b?.projectId)) return true;\n }\n return false;\n};\nclass I18n extends EventEmitter {\n constructor(options = {}, callback) {\n super();\n this.options = transformOptions(options);\n this.services = {};\n this.logger = baseLogger;\n this.modules = {\n external: []\n };\n bindMemberFunctions(this);\n if (callback && !this.isInitialized && !options.isClone) {\n if (!this.options.initAsync) {\n this.init(options, callback);\n return this;\n }\n setTimeout(() => {\n this.init(options, callback);\n }, 0);\n }\n }\n init(options = {}, callback) {\n this.isInitializing = true;\n if (typeof options === 'function') {\n callback = options;\n options = {};\n }\n if (options.defaultNS == null && options.ns) {\n if (isString(options.ns)) {\n options.defaultNS = options.ns;\n } else if (options.ns.indexOf('translation') < 0) {\n options.defaultNS = options.ns[0];\n }\n }\n const defOpts = get();\n this.options = {\n ...defOpts,\n ...this.options,\n ...transformOptions(options)\n };\n this.options.interpolation = {\n ...defOpts.interpolation,\n ...this.options.interpolation\n };\n if (options.keySeparator !== undefined) {\n this.options.userDefinedKeySeparator = options.keySeparator;\n }\n if (options.nsSeparator !== undefined) {\n this.options.userDefinedNsSeparator = options.nsSeparator;\n }\n if (typeof this.options.overloadTranslationOptionHandler !== 'function') {\n this.options.overloadTranslationOptionHandler = defOpts.overloadTranslationOptionHandler;\n }\n if (this.options.showSupportNotice !== false && !usesLocize(this) && !getSupportNoticeShown()) {\n if (typeof console !== 'undefined' && typeof console.info !== 'undefined') console.info('\uD83C\uDF10 i18next is maintained with support from Locize \u2014 consider powering your project with managed localization (AI, CDN, integrations): https://locize.com \uD83D\uDC99');\n setSupportNoticeShown();\n }\n const createClassOnDemand = ClassOrObject => {\n if (!ClassOrObject) return null;\n if (typeof ClassOrObject === 'function') return new ClassOrObject();\n return ClassOrObject;\n };\n if (!this.options.isClone) {\n if (this.modules.logger) {\n baseLogger.init(createClassOnDemand(this.modules.logger), this.options);\n } else {\n baseLogger.init(null, this.options);\n }\n let formatter;\n if (this.modules.formatter) {\n formatter = this.modules.formatter;\n } else {\n formatter = Formatter;\n }\n const lu = new LanguageUtil(this.options);\n this.store = new ResourceStore(this.options.resources, this.options);\n const s = this.services;\n s.logger = baseLogger;\n s.resourceStore = this.store;\n s.languageUtils = lu;\n s.pluralResolver = new PluralResolver(lu, {\n prepend: this.options.pluralSeparator,\n simplifyPluralSuffix: this.options.simplifyPluralSuffix\n });\n const usingLegacyFormatFunction = this.options.interpolation.format && this.options.interpolation.format !== defOpts.interpolation.format;\n if (usingLegacyFormatFunction) {\n this.logger.deprecate(`init: you are still using the legacy format function, please use the new approach: https://www.i18next.com/translation-function/formatting`);\n }\n if (formatter && (!this.options.interpolation.format || this.options.interpolation.format === defOpts.interpolation.format)) {\n s.formatter = createClassOnDemand(formatter);\n if (s.formatter.init) s.formatter.init(s, this.options);\n this.options.interpolation.format = s.formatter.format.bind(s.formatter);\n }\n s.interpolator = new Interpolator(this.options);\n s.utils = {\n hasLoadedNamespace: this.hasLoadedNamespace.bind(this)\n };\n s.backendConnector = new Connector(createClassOnDemand(this.modules.backend), s.resourceStore, s, this.options);\n s.backendConnector.on('*', (event, ...args) => {\n this.emit(event, ...args);\n });\n if (this.modules.languageDetector) {\n s.languageDetector = createClassOnDemand(this.modules.languageDetector);\n if (s.languageDetector.init) s.languageDetector.init(s, this.options.detection, this.options);\n }\n if (this.modules.i18nFormat) {\n s.i18nFormat = createClassOnDemand(this.modules.i18nFormat);\n if (s.i18nFormat.init) s.i18nFormat.init(this);\n }\n this.translator = new Translator(this.services, this.options);\n this.translator.on('*', (event, ...args) => {\n this.emit(event, ...args);\n });\n this.modules.external.forEach(m => {\n if (m.init) m.init(this);\n });\n }\n this.format = this.options.interpolation.format;\n if (!callback) callback = noop;\n if (this.options.fallbackLng && !this.services.languageDetector && !this.options.lng) {\n const codes = this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);\n if (codes.length > 0 && codes[0] !== 'dev') this.options.lng = codes[0];\n }\n if (!this.services.languageDetector && !this.options.lng) {\n this.logger.warn('init: no languageDetector is used and no lng is defined');\n }\n const storeApi = ['getResource', 'hasResourceBundle', 'getResourceBundle', 'getDataByLanguage'];\n storeApi.forEach(fcName => {\n this[fcName] = (...args) => this.store[fcName](...args);\n });\n const storeApiChained = ['addResource', 'addResources', 'addResourceBundle', 'removeResourceBundle'];\n storeApiChained.forEach(fcName => {\n this[fcName] = (...args) => {\n this.store[fcName](...args);\n return this;\n };\n });\n const deferred = defer();\n const load = () => {\n const finish = (err, t) => {\n this.isInitializing = false;\n if (this.isInitialized && !this.initializedStoreOnce) this.logger.warn('init: i18next is already initialized. You should call init just once!');\n this.isInitialized = true;\n if (!this.options.isClone) this.logger.log('initialized', this.options);\n this.emit('initialized', this.options);\n deferred.resolve(t);\n callback(err, t);\n };\n if (this.languages && !this.isInitialized) return finish(null, this.t.bind(this));\n this.changeLanguage(this.options.lng, finish);\n };\n if (this.options.resources || !this.options.initAsync) {\n load();\n } else {\n setTimeout(load, 0);\n }\n return deferred;\n }\n loadResources(language, callback = noop) {\n let usedCallback = callback;\n const usedLng = isString(language) ? language : this.language;\n if (typeof language === 'function') usedCallback = language;\n if (!this.options.resources || this.options.partialBundledLanguages) {\n if (usedLng?.toLowerCase() === 'cimode' && (!this.options.preload || this.options.preload.length === 0)) return usedCallback();\n const toLoad = [];\n const append = lng => {\n if (!lng) return;\n if (lng === 'cimode') return;\n const lngs = this.services.languageUtils.toResolveHierarchy(lng);\n lngs.forEach(l => {\n if (l === 'cimode') return;\n if (toLoad.indexOf(l) < 0) toLoad.push(l);\n });\n };\n if (!usedLng) {\n const fallbacks = this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);\n fallbacks.forEach(l => append(l));\n } else {\n append(usedLng);\n }\n this.options.preload?.forEach?.(l => append(l));\n this.services.backendConnector.load(toLoad, this.options.ns, e => {\n if (!e && !this.resolvedLanguage && this.language) this.setResolvedLanguage(this.language);\n usedCallback(e);\n });\n } else {\n usedCallback(null);\n }\n }\n reloadResources(lngs, ns, callback) {\n const deferred = defer();\n if (typeof lngs === 'function') {\n callback = lngs;\n lngs = undefined;\n }\n if (typeof ns === 'function') {\n callback = ns;\n ns = undefined;\n }\n if (!lngs) lngs = this.languages;\n if (!ns) ns = this.options.ns;\n if (!callback) callback = noop;\n this.services.backendConnector.reload(lngs, ns, err => {\n deferred.resolve();\n callback(err);\n });\n return deferred;\n }\n use(module) {\n if (!module) throw new Error('You are passing an undefined module! Please check the object you are passing to i18next.use()');\n if (!module.type) throw new Error('You are passing a wrong module! Please check the object you are passing to i18next.use()');\n if (module.type === 'backend') {\n this.modules.backend = module;\n }\n if (module.type === 'logger' || module.log && module.warn && module.error) {\n this.modules.logger = module;\n }\n if (module.type === 'languageDetector') {\n this.modules.languageDetector = module;\n }\n if (module.type === 'i18nFormat') {\n this.modules.i18nFormat = module;\n }\n if (module.type === 'postProcessor') {\n postProcessor.addPostProcessor(module);\n }\n if (module.type === 'formatter') {\n this.modules.formatter = module;\n }\n if (module.type === '3rdParty') {\n this.modules.external.push(module);\n }\n return this;\n }\n setResolvedLanguage(l) {\n if (!l || !this.languages) return;\n if (['cimode', 'dev'].indexOf(l) > -1) return;\n for (let li = 0; li < this.languages.length; li++) {\n const lngInLngs = this.languages[li];\n if (['cimode', 'dev'].indexOf(lngInLngs) > -1) continue;\n if (this.store.hasLanguageSomeTranslations(lngInLngs)) {\n this.resolvedLanguage = lngInLngs;\n break;\n }\n }\n if (!this.resolvedLanguage && this.languages.indexOf(l) < 0 && this.store.hasLanguageSomeTranslations(l)) {\n this.resolvedLanguage = l;\n this.languages.unshift(l);\n }\n }\n changeLanguage(lng, callback) {\n this.isLanguageChangingTo = lng;\n const deferred = defer();\n this.emit('languageChanging', lng);\n const setLngProps = l => {\n this.language = l;\n this.languages = this.services.languageUtils.toResolveHierarchy(l);\n this.resolvedLanguage = undefined;\n this.setResolvedLanguage(l);\n };\n const done = (err, l) => {\n if (l) {\n if (this.isLanguageChangingTo === lng) {\n setLngProps(l);\n this.translator.changeLanguage(l);\n this.isLanguageChangingTo = undefined;\n this.emit('languageChanged', l);\n this.logger.log('languageChanged', l);\n }\n } else {\n this.isLanguageChangingTo = undefined;\n }\n deferred.resolve((...args) => this.t(...args));\n if (callback) callback(err, (...args) => this.t(...args));\n };\n const setLng = lngs => {\n if (!lng && !lngs && this.services.languageDetector) lngs = [];\n const fl = isString(lngs) ? lngs : lngs && lngs[0];\n const l = this.store.hasLanguageSomeTranslations(fl) ? fl : this.services.languageUtils.getBestMatchFromCodes(isString(lngs) ? [lngs] : lngs);\n if (l) {\n if (!this.language) {\n setLngProps(l);\n }\n if (!this.translator.language) this.translator.changeLanguage(l);\n this.services.languageDetector?.cacheUserLanguage?.(l);\n }\n this.loadResources(l, err => {\n done(err, l);\n });\n };\n if (!lng && this.services.languageDetector && !this.services.languageDetector.async) {\n setLng(this.services.languageDetector.detect());\n } else if (!lng && this.services.languageDetector && this.services.languageDetector.async) {\n if (this.services.languageDetector.detect.length === 0) {\n this.services.languageDetector.detect().then(setLng);\n } else {\n this.services.languageDetector.detect(setLng);\n }\n } else {\n setLng(lng);\n }\n return deferred;\n }\n getFixedT(lng, ns, keyPrefix) {\n const fixedT = (key, opts, ...rest) => {\n let o;\n if (typeof opts !== 'object') {\n o = this.options.overloadTranslationOptionHandler([key, opts].concat(rest));\n } else {\n o = {\n ...opts\n };\n }\n o.lng = o.lng || fixedT.lng;\n o.lngs = o.lngs || fixedT.lngs;\n o.ns = o.ns || fixedT.ns;\n if (o.keyPrefix !== '') o.keyPrefix = o.keyPrefix || keyPrefix || fixedT.keyPrefix;\n const keySeparator = this.options.keySeparator || '.';\n let resultKey;\n if (o.keyPrefix && Array.isArray(key)) {\n resultKey = key.map(k => {\n if (typeof k === 'function') k = keysFromSelector(k, {\n ...this.options,\n ...opts\n });\n return `${o.keyPrefix}${keySeparator}${k}`;\n });\n } else {\n if (typeof key === 'function') key = keysFromSelector(key, {\n ...this.options,\n ...opts\n });\n resultKey = o.keyPrefix ? `${o.keyPrefix}${keySeparator}${key}` : key;\n }\n return this.t(resultKey, o);\n };\n if (isString(lng)) {\n fixedT.lng = lng;\n } else {\n fixedT.lngs = lng;\n }\n fixedT.ns = ns;\n fixedT.keyPrefix = keyPrefix;\n return fixedT;\n }\n t(...args) {\n return this.translator?.translate(...args);\n }\n exists(...args) {\n return this.translator?.exists(...args);\n }\n setDefaultNamespace(ns) {\n this.options.defaultNS = ns;\n }\n hasLoadedNamespace(ns, options = {}) {\n if (!this.isInitialized) {\n this.logger.warn('hasLoadedNamespace: i18next was not initialized', this.languages);\n return false;\n }\n if (!this.languages || !this.languages.length) {\n this.logger.warn('hasLoadedNamespace: i18n.languages were undefined or empty', this.languages);\n return false;\n }\n const lng = options.lng || this.resolvedLanguage || this.languages[0];\n const fallbackLng = this.options ? this.options.fallbackLng : false;\n const lastLng = this.languages[this.languages.length - 1];\n if (lng.toLowerCase() === 'cimode') return true;\n const loadNotPending = (l, n) => {\n const loadState = this.services.backendConnector.state[`${l}|${n}`];\n return loadState === -1 || loadState === 0 || loadState === 2;\n };\n if (options.precheck) {\n const preResult = options.precheck(this, loadNotPending);\n if (preResult !== undefined) return preResult;\n }\n if (this.hasResourceBundle(lng, ns)) return true;\n if (!this.services.backendConnector.backend || this.options.resources && !this.options.partialBundledLanguages) return true;\n if (loadNotPending(lng, ns) && (!fallbackLng || loadNotPending(lastLng, ns))) return true;\n return false;\n }\n loadNamespaces(ns, callback) {\n const deferred = defer();\n if (!this.options.ns) {\n if (callback) callback();\n return Promise.resolve();\n }\n if (isString(ns)) ns = [ns];\n ns.forEach(n => {\n if (this.options.ns.indexOf(n) < 0) this.options.ns.push(n);\n });\n this.loadResources(err => {\n deferred.resolve();\n if (callback) callback(err);\n });\n return deferred;\n }\n loadLanguages(lngs, callback) {\n const deferred = defer();\n if (isString(lngs)) lngs = [lngs];\n const preloaded = this.options.preload || [];\n const newLngs = lngs.filter(lng => preloaded.indexOf(lng) < 0 && this.services.languageUtils.isSupportedCode(lng));\n if (!newLngs.length) {\n if (callback) callback();\n return Promise.resolve();\n }\n this.options.preload = preloaded.concat(newLngs);\n this.loadResources(err => {\n deferred.resolve();\n if (callback) callback(err);\n });\n return deferred;\n }\n dir(lng) {\n if (!lng) lng = this.resolvedLanguage || (this.languages?.length > 0 ? this.languages[0] : this.language);\n if (!lng) return 'rtl';\n try {\n const l = new Intl.Locale(lng);\n if (l && l.getTextInfo) {\n const ti = l.getTextInfo();\n if (ti && ti.direction) return ti.direction;\n }\n } catch (e) {}\n const rtlLngs = ['ar', 'shu', 'sqr', 'ssh', 'xaa', 'yhd', 'yud', 'aao', 'abh', 'abv', 'acm', 'acq', 'acw', 'acx', 'acy', 'adf', 'ads', 'aeb', 'aec', 'afb', 'ajp', 'apc', 'apd', 'arb', 'arq', 'ars', 'ary', 'arz', 'auz', 'avl', 'ayh', 'ayl', 'ayn', 'ayp', 'bbz', 'pga', 'he', 'iw', 'ps', 'pbt', 'pbu', 'pst', 'prp', 'prd', 'ug', 'ur', 'ydd', 'yds', 'yih', 'ji', 'yi', 'hbo', 'men', 'xmn', 'fa', 'jpr', 'peo', 'pes', 'prs', 'dv', 'sam', 'ckb'];\n const languageUtils = this.services?.languageUtils || new LanguageUtil(get());\n if (lng.toLowerCase().indexOf('-latn') > 1) return 'ltr';\n return rtlLngs.indexOf(languageUtils.getLanguagePartFromCode(lng)) > -1 || lng.toLowerCase().indexOf('-arab') > 1 ? 'rtl' : 'ltr';\n }\n static createInstance(options = {}, callback) {\n const instance = new I18n(options, callback);\n instance.createInstance = I18n.createInstance;\n return instance;\n }\n cloneInstance(options = {}, callback = noop) {\n const forkResourceStore = options.forkResourceStore;\n if (forkResourceStore) delete options.forkResourceStore;\n const mergedOptions = {\n ...this.options,\n ...options,\n ...{\n isClone: true\n }\n };\n const clone = new I18n(mergedOptions);\n if (options.debug !== undefined || options.prefix !== undefined) {\n clone.logger = clone.logger.clone(options);\n }\n const membersToCopy = ['store', 'services', 'language'];\n membersToCopy.forEach(m => {\n clone[m] = this[m];\n });\n clone.services = {\n ...this.services\n };\n clone.services.utils = {\n hasLoadedNamespace: clone.hasLoadedNamespace.bind(clone)\n };\n if (forkResourceStore) {\n const clonedData = Object.keys(this.store.data).reduce((prev, l) => {\n prev[l] = {\n ...this.store.data[l]\n };\n prev[l] = Object.keys(prev[l]).reduce((acc, n) => {\n acc[n] = {\n ...prev[l][n]\n };\n return acc;\n }, prev[l]);\n return prev;\n }, {});\n clone.store = new ResourceStore(clonedData, mergedOptions);\n clone.services.resourceStore = clone.store;\n }\n if (options.interpolation) {\n const defOpts = get();\n const mergedInterpolation = {\n ...defOpts.interpolation,\n ...this.options.interpolation,\n ...options.interpolation\n };\n const mergedForInterpolator = {\n ...mergedOptions,\n interpolation: mergedInterpolation\n };\n clone.services.interpolator = new Interpolator(mergedForInterpolator);\n }\n clone.translator = new Translator(clone.services, mergedOptions);\n clone.translator.on('*', (event, ...args) => {\n clone.emit(event, ...args);\n });\n clone.init(mergedOptions, callback);\n clone.translator.options = mergedOptions;\n clone.translator.backendConnector.services.utils = {\n hasLoadedNamespace: clone.hasLoadedNamespace.bind(clone)\n };\n return clone;\n }\n toJSON() {\n return {\n options: this.options,\n store: this.store,\n language: this.language,\n languages: this.languages,\n resolvedLanguage: this.resolvedLanguage\n };\n }\n}\nconst instance = I18n.createInstance();\n\nconst createInstance = instance.createInstance;\nconst dir = instance.dir;\nconst init = instance.init;\nconst loadResources = instance.loadResources;\nconst reloadResources = instance.reloadResources;\nconst use = instance.use;\nconst changeLanguage = instance.changeLanguage;\nconst getFixedT = instance.getFixedT;\nconst t = instance.t;\nconst exists = instance.exists;\nconst setDefaultNamespace = instance.setDefaultNamespace;\nconst hasLoadedNamespace = instance.hasLoadedNamespace;\nconst loadNamespaces = instance.loadNamespaces;\nconst loadLanguages = instance.loadLanguages;\n\nexport { changeLanguage, createInstance, instance as default, dir, exists, getFixedT, hasLoadedNamespace, init, keysFromSelector as keyFromSelector, loadLanguages, loadNamespaces, loadResources, reloadResources, setDefaultNamespace, t, use };\n", "{\n\t\"language\": {\n\t\t\"name\": \"English\",\n\t\t\"changed\": \"Language is set to english.\",\n\t\t\"emoji\": \"\uD83C\uDDEC\uD83C\uDDE7\"\n\t},\n\n\t\"bot\": {\n\t\t\"description\": \"Hello! I will notify you when Twitch broadcasts start.\"\n\t},\n\n\t\"enable\": \"Enable\",\n\t\"disable\": \"Disable\",\n\t\"enabled\": \"Enabled\",\n\t\"disabled\": \"Disabled\",\n\n\t\"commands\": {\n\t\t\"follow\": {\n\t\t\t\"errors\": {\n\t\t\t\t\"badUsername\": \"{{ streamer }} - username can only contain \\\"a-z\\\", \\\"0-9\\\" and \\\"_\\\" symbols.\",\n\t\t\t\t\"streamerNotFound\": \"{{ streamer }} - not found on twitch.\",\n\t\t\t\t\"alreadyFollowed\": \"{{ streamer }} - already followed.\"\n\t\t\t},\n\t\t\t\"success\": \"{{ streamer }} - now followed.\",\n\t\t\t\"enter\": \"Enter username of streamer you want to follow.\\nYou can use multiple links to streamers.\\n\\nType /cancel for cancel action.\"\n\t\t},\n\n\t\t\"follows\": {\n\t\t\t\"total\": \"You followed to notifications from {{ count }} channels. Click on streamer nickname to unfollow from notifications.\"\n\t\t},\n\n\t\"unfollow\": {\n\t\t\"callbackButton\": \"Unfollow {{ streamer }}\",\n\t\t\"success\": \"Unfollowed from {{ streamer }}\"\n\t},\n\n\t\t\"start\": {\n\t\t\t\"game_change_notification_setting\": {\n\t\t\t\t\"button\": \"Game change notification\"\n\t\t\t},\n\t\t\t\"language\": {\n\t\t\t\t\"button\": \"\uD83C\uDF0D Language\"\n\t\t\t},\n\t\t\t\"offline_notification\": {\n\t\t\t\t\"button\": \"Offline notification\"\n\t\t\t},\n\t\t\t\"title_change_notification_setting\": {\n\t\t\t\t\"button\": \"Title change notification\"\n\t\t\t},\n\t\t\t\"image_in_notification_setting\": {\n\t\t\t\t\"button\": \"Show images in notifications\"\n\t\t\t},\n\t\t\t\"game_and_title_change_notification_setting\": {\n\t\t\t\t\"button\": \"Game and title change notification\"\n\t\t\t}\n\t\t}\n\t},\n\n\t\"notifications\": {\n\t\t\"streams\": {\n\t\t\t\"nowOffline\": \"\\uD83D\\uDD34 {{ channelLink }} now offline.\\n{{ categories }}\\n{{ duration }}\",\n\t\t\t\"nowOnline\": \"\\uD83D\\uDFE2 {{ channelLink }} now online.\\nCategory: {{ category }}\\nTitle: {{ title }}\",\n\t\t\t\"newCategory\": \"\\uD83D\\uDD04 {{ channelLink }} updated category from {{ oldCategory }} to {{ category }}\",\n\t\t\t\"titleChanged\": \"\\uD83D\\uDD04 {{ channelLink }} updated title from {{ oldTitle }} to {{ title }}\",\n\t\t\t\"titleAndCategoryChanged\": \"\\uD83D\\uDD04 {{ channelLink }} updated title from {{ oldTitle }} to {{ title }} and category from {{ oldCategory }} to {{ category }}\"\n\t\t}\n\t}\n}\n", "{\n \"language\": {\n \"name\": \"\u0420\u0443\u0441\u0441\u043A\u0438\u0439\",\n \"changed\": \"\u042F\u0437\u044B\u043A \u0443\u0441\u0442\u0430\u043D\u043E\u0432\u043B\u0435\u043D \u043D\u0430 \u0440\u0443\u0441\u0441\u043A\u0438\u0439.\",\n \"emoji\": \"\uD83C\uDDF7\uD83C\uDDFA\"\n },\n \"bot\": {\n \"description\": \"\u0417\u0434\u0440\u0430\u0432\u0441\u0442\u0432\u0443\u0439\u0442\u0435! \u042F \u0431\u0443\u0434\u0443 \u0443\u0432\u0435\u0434\u043E\u043C\u043B\u044F\u0442\u044C \u0432\u0430\u0441 \u043E \u043D\u0430\u0447\u0430\u043B\u0435 \u0442\u0440\u0430\u043D\u0441\u043B\u044F\u0446\u0438\u0439 Twitch.\"\n },\n \"enable\": \"\u0412\u043A\u043B\u044E\u0447\u0438\u0442\u044C\",\n \"disable\": \"\u0412\u044B\u043A\u043B\u044E\u0447\u0438\u0442\u044C\",\n \"enabled\": \"\u0412\u043A\u043B\u044E\u0447\u0435\u043D\u043E\",\n \"disabled\": \"\u0412\u044B\u043A\u043B\u044E\u0447\u0435\u043D\u043E\",\n \"commands\": {\n \"follow\": {\n \"errors\": {\n \"badUsername\": \"\u0418\u043C\u044F \u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044F \u043C\u043E\u0436\u0435\u0442 \u0441\u043E\u0434\u0435\u0440\u0436\u0430\u0442\u044C \u0442\u043E\u043B\u044C\u043A\u043E \\\"a-z\\\", \\\"0-9\\\" and \\\"_\\\" \u0441\u0438\u043C\u0432\u043E\u043B\u044B.\",\n \"streamerNotFound\": \"{{ streamer }} - \u043D\u0435 \u043D\u0430\u0439\u0434\u0435\u043D \u043D\u0430 \u0442\u0432\u0438\u0447\u0435.\",\n \"alreadyFollowed\": \"{{ streamer }} - \u0432\u044B \u0443\u0436\u0435 \u043F\u043E\u0434\u043F\u0438\u0441\u0430\u043D\u044B.\"\n },\n \"success\": \"{{ streamer }} - \u0442\u0435\u043F\u0435\u0440\u044C \u043E\u0442\u0441\u043B\u0435\u0436\u0438\u0432\u0430\u0435\u0442\u0441\u044F.\",\n \"enter\": \"\u0412\u0432\u0435\u0434\u0438\u0442\u0435 \u0438\u043C\u044F \u0441\u0442\u0440\u0438\u043C\u0435\u0440\u0430, \u0443\u0432\u0435\u0434\u043E\u043C\u043B\u0435\u043D\u0438\u044F \u043E\u0442 \u043A\u043E\u0442\u043E\u0440\u043E\u0433\u043E \u0445\u043E\u0442\u0438\u0442\u0435 \u043F\u043E\u043B\u0443\u0447\u0430\u0442\u044C.\\n\u0412\u044B \u043C\u043E\u0436\u0435\u0442\u0435 \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u044C \u0441\u0441\u044B\u043B\u043A\u0438.\\n\\n\u0412\u0432\u0435\u0434\u0438\u0442\u0435 /cancel \u0434\u043B\u044F \u043E\u0442\u043C\u0435\u043D\u044B \u0434\u0435\u0439\u0441\u0442\u0432\u0438\u044F.\"\n },\n \"follows\": {\n \"total\": \"\u0412\u044B \u043F\u043E\u0434\u043F\u0438\u0441\u0430\u043D\u044B \u043D\u0430 \u0443\u0432\u0435\u0434\u043E\u043C\u043B\u0435\u043D\u0438\u044F {{ count }} \u043A\u0430\u043D\u0430\u043B\u043E\u0432. \u041A\u043B\u0438\u043A\u043D\u0438\u0442\u0435 \u043D\u0430 \u043D\u0438\u043A\u043D\u0435\u0439\u043C \u0441\u0442\u0440\u0438\u043C\u0435\u0440\u0430, \u0447\u0442\u043E\u0431\u044B \u043E\u0442\u043F\u0438\u0441\u0430\u0442\u044C\u0441\u044F \u043E\u0442 \u0443\u0432\u0435\u0434\u043E\u043C\u043B\u0435\u043D\u0438\u0439.\"\n },\n \"unfollow\": {\n \"callbackButton\": \"\u041E\u0442\u043F\u0438\u0441\u0430\u0442\u044C\u0441\u044F \u043E\u0442 {{ streamer }}\",\n \"success\": \"\u0412\u044B \u043E\u0442\u043F\u0438\u0441\u0430\u043B\u0438\u0441\u044C \u043E\u0442 {{ streamer }}\"\n },\n \"start\": {\n \"game_change_notification_setting\": {\n \"button\": \"\u0423\u0432\u0435\u0434\u043E\u043C\u043B\u0435\u043D\u0438\u0435 \u043E \u0441\u043C\u0435\u043D\u0435 \u043A\u0430\u0442\u0435\u0433\u043E\u0440\u0438\u0438\"\n },\n \"language\": {\n \"button\": \"\uD83C\uDF0D \u042F\u0437\u044B\u043A\"\n },\n \"offline_notification\": {\n \"button\": \"\u0423\u0432\u0435\u0434\u043E\u043C\u043B\u0435\u043D\u0438\u0435 \u043E\u0431 \u0443\u0445\u043E\u0434\u0435 \u0432 \u043E\u0444\u0444\u043B\u0430\u0439\u043D\"\n },\n \"title_change_notification_setting\": {\n \"button\": \"\u0423\u0432\u0435\u0434\u043E\u043C\u043B\u0435\u043D\u0438\u0435 \u043E \u0441\u043C\u0435\u043D\u0435 \u043D\u0430\u0437\u0432\u0430\u043D\u0438\u044F\"\n },\n \"image_in_notification_setting\": {\n \"button\": \"\u041F\u043E\u043A\u0430\u0437\u044B\u0432\u0430\u0442\u044C \u0438\u0437\u043E\u0431\u0440\u0430\u0436\u0435\u043D\u0438\u044F \u0432 \u0443\u0432\u0435\u0434\u043E\u043C\u043B\u0435\u043D\u0438\u044F\u0445\"\n },\n \"game_and_title_change_notification_setting\": {\n \"button\": \"\u0423\u0432\u0435\u0434\u043E\u043C\u0435\u043B\u043D\u0438\u0435 \u043E \u0441\u043C\u0435\u043D\u0435 \u043A\u0430\u0442\u0435\u0433\u043E\u0440\u0438\u0438 \u0438 \u043D\u0430\u0437\u0432\u0430\u043D\u0438\u044F\"\n }\n }\n },\n \"notifications\": {\n \"streams\": {\n \"nowOffline\": \"\uD83D\uDD34 {{ channelLink }} \u0442\u0435\u043F\u0435\u0440\u044C \u043E\u0444\u0444\u043B\u0430\u0439\u043D.\\n{{ categories }}\\n{{ duration }}\",\n \"nowOnline\": \"\uD83D\uDFE2 {{ channelLink }} \u0442\u0435\u043F\u0435\u0440\u044C \u043E\u043D\u043B\u0430\u0439\u043D.\\n\u041A\u0430\u0442\u0435\u0433\u043E\u0440\u0438\u044F: {{ category }}\\n\u041D\u0430\u0437\u0432\u0430\u043D\u0438\u0435: {{ title }}\",\n \"newCategory\": \"\uD83D\uDD04 \u041D\u0430 \u043A\u0430\u043D\u0430\u043B\u0435 {{ channelLink }} \u0438\u0437\u043C\u0435\u043D\u0430\u043B\u0430\u0441\u044C \u043A\u0430\u0442\u0435\u0433\u043E\u0440\u0438\u044F \u0441 {{ oldCategory }} \u043D\u0430 {{ category }}\",\n \"titleChanged\": \"\uD83D\uDD04 \u041D\u0430 \u043A\u0430\u043D\u0430\u043B\u0435 {{ channelLink }} \u0438\u0437\u043C\u0435\u043D\u0438\u043B\u043E\u0441\u044C \u043D\u0430\u0437\u0432\u0430\u043D\u0438\u0435 \u0441 {{ oldTitle }} \u043D\u0430 {{ title }}\",\n \"titleAndCategoryChanged\": \"\uD83D\uDD04 \u041D\u0430 \u043A\u0430\u043D\u0430\u043B\u0435 {{ channelLink }} \u0438\u0437\u043C\u0435\u043D\u0438\u043B\u0438\u0441\u044C \u043D\u0430\u0437\u0432\u0430\u043D\u0438\u0435 \u0441 {{ oldTitle }} \u043D\u0430 {{ title }} \u0438 \u043A\u0430\u0442\u0435\u0433\u043E\u0440\u0438\u044F \u0441 {{ oldCategory }} \u043D\u0430 {{ category }}\"\n }\n }\n}\n", "{\n \"language\": {\n \"name\": \"\u0423\u043A\u0440\u0430\u0457\u043D\u0441\u044C\u043A\u0430\",\n \"changed\": \"\u041C\u043E\u0432\u0430 \u0437\u043C\u0456\u043D\u0435\u043D\u0430 \u043D\u0430 \u0443\u043A\u0440\u0430\u0457\u043D\u0441\u044C\u043A\u0443.\",\n \"emoji\": \"\uD83C\uDDFA\uD83C\uDDE6\"\n },\n \"bot\": {\n \"description\": \"\u0417\u0434\u0440\u0430\u0441\u0442\u0432\u0443\u0439\u0442\u0435! \u042F \u0431\u0443\u0434\u0443 \u0441\u043F\u043E\u0432\u0456\u0449\u0430\u0442\u0438 \u0432\u0430\u0441 \u043F\u0440\u043E \u043F\u043E\u0447\u0430\u0442\u043E\u043A Twitch \u0442\u0440\u0430\u043D\u0441\u043B\u044F\u0446\u0456\u0439.\"\n },\n \"enable\": \"\u0423\u0432\u0456\u043C\u043A\u043D\u0443\u0442\u0438\",\n \"disable\": \"\u0412\u0438\u043C\u043A\u043D\u0443\u0442\u0438\",\n \"enabled\": \"\u0423\u0432\u0456\u043C\u043A\u043D\u0435\u043D\u043E\",\n \"disabled\": \"\u0412\u0456\u043C\u043A\u043D\u0435\u043D\u043E\",\n \"commands\": {\n \"follow\": {\n \"errors\": {\n \"badUsername\": \"\u0406\u043C\u02BC\u044F \u043A\u043E\u0440\u0438\u0441\u0442\u0443\u0432\u0430\u0447\u0430 \u043C\u043E\u0436\u0435 \u043C\u0430\u0442\u0438 \u0442\u0456\u043B\u044C\u043A\u0438 \\\"a-z\\\", \\\"0-9\\\" \u0442\u0430 \\\"_\\\" \u0441\u0438\u043C\u0432\u043E\u043B\u0438.\",\n \"streamerNotFound\": \"{{ streamer }} - \u043D\u0435 \u0437\u043D\u0430\u0439\u0434\u0435\u043D\u0438\u0439 \u043D\u0430 \u0442\u0432\u0456\u0447\u0456.\",\n \"alreadyFollowed\": \"{{ streamer }} - \u0432\u0438 \u0432\u0436\u0435 \u043F\u0456\u0434\u043F\u0438\u0441\u0430\u043D\u0456.\"\n },\n \"success\": \"{{ streamer }} - \u0442\u0435\u043F\u0435\u0440 \u0432\u0456\u0434\u0441\u043B\u0456\u0434\u043A\u043E\u0432\u0443\u0454\u0442\u044C\u0441\u044F.\",\n \"enter\": \"\u0412\u0432\u0435\u0434\u0456\u0442\u044C \u0456\u043C\u02BC\u044F \u0441\u0442\u0440\u0456\u043C\u0435\u0440\u0430, \u0441\u043F\u043E\u0432\u0456\u0449\u0435\u043D\u043D\u044F \u0432\u0456\u0434 \u044F\u043A\u043E\u0433\u043E \u0432\u0438 \u0445\u043E\u0447\u0435\u0442\u0435 \u043E\u0442\u0440\u0438\u043C\u0443\u0432\u0430\u0442\u0438.\\n\u0412\u0438 \u043C\u043E\u0436\u0435\u0442\u0435 \u0432\u0438\u043A\u043E\u0440\u0438\u0441\u0442\u043E\u0432\u0443\u0432\u0430\u0442\u0438 \u043F\u043E\u0441\u0438\u043B\u0430\u043D\u043D\u044F.\\n\\n\u0412\u0432\u0435\u0434\u0456\u0442\u044C /cancel \u0434\u043B\u044F \u0441\u043A\u0430\u0441\u0443\u0432\u0430\u043D\u043D\u044F \u0434\u0456\u0457.\"\n },\n \"follows\": {\n \"total\": \"\u0412\u0438 \u043F\u0456\u0434\u043F\u0438\u0441\u0430\u043D\u0456 \u043D\u0430 \u0441\u043F\u043E\u0432\u0456\u0449\u0435\u043D\u043D\u044F \u0432\u0456\u0434 {{ count }} \u043A\u0430\u043D\u0430\u043B\u0456\u0432. \u041A\u043B\u0430\u0446\u043D\u0456\u0442\u044C \u043D\u0430 \u043D\u0456\u043A\u043D\u0435\u0439\u043C \u0441\u0442\u0440\u0456\u043C\u0435\u0440\u0430, \u0449\u043E\u0431 \u0432\u0456\u0434\u043F\u0438\u0441\u0430\u0442\u0438\u0441\u044C \u0432\u0456\u0434 \u0441\u043F\u043E\u0432\u0456\u0449\u0435\u043D\u044C.\"\n },\n \"unfollow\": {\n \"callbackButton\": \"\u0412\u0456\u0434\u043F\u0438\u0441\u0430\u0442\u0438\u0441\u044C \u0432\u0456\u0434 {{ streamer }}\",\n \"success\": \"\u0412\u0438 \u0432\u0456\u0434\u043F\u0438\u0441\u0430\u043B\u0438\u0441\u044C \u0432\u0456\u0434 {{ streamer }}\"\n },\n \"start\": {\n \"game_change_notification_setting\": {\n \"button\": \"\u0421\u043F\u043E\u0432\u0456\u0449\u0435\u043D\u043D\u044F \u043F\u0440\u043E \u0437\u043C\u0456\u043D\u0443 \u043A\u0430\u0442\u0435\u0433\u043E\u0440\u0456\u0457\"\n },\n \"language\": {\n \"button\": \"\uD83C\uDF0D \u041C\u043E\u0432\u0430\"\n },\n \"offline_notification\": {\n \"button\": \"\u0421\u043F\u043E\u0432\u0456\u0449\u0435\u043D\u043D\u044F \u043F\u0440\u0438 \u0443\u0445\u043E\u0434\u0456 \u0432 \u043E\u0444\u0444\u043B\u0430\u0439\u043D\"\n },\n \"title_change_notification_setting\": {\n \"button\": \"\u0421\u043F\u043E\u0432\u0456\u0449\u0435\u043D\u043D\u044F \u043F\u0440\u043E \u0437\u043C\u0456\u043D\u0443 \u043D\u0430\u0437\u0432\u0438\"\n },\n \"image_in_notification_setting\": {\n \"button\": \"\u041F\u043E\u043A\u0430\u0437\u0443\u0432\u0430\u0442\u0438 \u0437\u043E\u0431\u0440\u0430\u0436\u0435\u043D\u043D\u044F \u0432 \u0441\u043F\u043E\u0432\u0456\u0449\u0435\u043D\u043D\u044F\u0445\"\n },\n \"game_and_title_change_notification_setting\": {\n \"button\": \"\u0421\u043F\u043E\u0432\u0456\u0449\u0435\u043D\u043D\u044F \u043F\u0440\u043E \u0437\u043C\u0456\u043D\u0443 \u043A\u0430\u0442\u0435\u0433\u043E\u0440\u0456\u0457 \u0442\u0430 \u043D\u0430\u0437\u0432\u0438\"\n }\n }\n },\n \"notifications\": {\n \"streams\": {\n \"nowOffline\": \"\uD83D\uDD34 {{ channelLink }} \u0442\u0435\u043F\u0435\u0440 \u043E\u0444\u0444\u043B\u0430\u0439\u043D.\\n{{ categories }}\\n{{ duration }}\",\n \"nowOnline\": \"\uD83D\uDFE2 {{ channelLink }} \u0442\u0435\u043F\u0435\u0440 \u043E\u043D\u043B\u0430\u0439\u043D.\\n\u041A\u0430\u0442\u0435\u0433\u043E\u0440\u0456\u044F: {{ category }}\\n\u041D\u0430\u0437\u0432\u0430: {{ title }}\",\n \"newCategory\": \"\uD83D\uDD04 \u041D\u0430 \u043A\u0430\u043D\u0430\u043B\u0456 {{ channelLink }} \u0431\u0443\u043B\u0430 \u0437\u043C\u0456\u043D\u0435\u043D\u0430 \u043A\u0430\u0442\u0435\u0433\u043E\u0440\u0456\u044F \u0437 {{ oldCategory }} \u043D\u0430 {{ category }}\",\n \"titleChanged\": \"\uD83D\uDD04 \u041D\u0430 \u043A\u0430\u043D\u0430\u043B\u0456{{ channelLink }} \u0431\u0443\u043B\u0430 \u0437\u043C\u0456\u043D\u0435\u043D\u0430 \u043D\u0430\u0437\u0432\u0430 \u0437 {{ oldTitle }} \u043D\u0430 {{ title }}\",\n \"titleAndCategoryChanged\": \"\uD83D\uDD04 \u041D\u0430 \u043A\u0430\u043D\u0430\u043B\u0456 {{ channelLink }} \u0431\u0443\u043B\u0430 \u0437\u043C\u0456\u043D\u0435\u043D\u0430 \u043D\u0430\u0437\u0432\u0430 \u0437 {{ oldTitle }} \u043D\u0430 {{ title }} \u0442\u0430 \u043A\u0430\u0442\u0435\u0433\u043E\u0440\u0456\u044F \u0437 {{ oldCategory }} \u043D\u0430 {{ category }}\"\n }\n }\n}\n", "import { ApiClient } from '@twurple/api';\nimport { AppTokenAuthProvider } from '@twurple/auth';\nimport type { Env } from '../types/env';\n\nexport class TwitchService {\n private apiClient: ApiClient;\n private authProvider: AppTokenAuthProvider;\n\n constructor(env: Env) {\n this.authProvider = new AppTokenAuthProvider(\n env.TWITCH_CLIENT_ID,\n env.TWITCH_CLIENT_SECRET\n );\n this.apiClient = new ApiClient({ authProvider: this.authProvider });\n }\n\n async getUserByLogin(login: string) {\n try {\n return await this.apiClient.users.getUserByName(login);\n } catch (error) {\n return null;\n }\n }\n\n async getUserById(id: string) {\n try {\n return await this.apiClient.users.getUserById(id);\n } catch (error) {\n return null;\n }\n }\n\n async getStreamByUserId(userId: string) {\n try {\n return await this.apiClient.streams.getStreamByUserId(userId);\n } catch (error) {\n return null;\n }\n }\n\n async getGameById(gameId: string) {\n try {\n return await this.apiClient.games.getGameById(gameId);\n } catch (error) {\n return null;\n }\n }\n\n getApiClient() {\n return this.apiClient;\n }\n\n getAuthProvider() {\n return this.authProvider;\n }\n}\n", "export { ApiClient } from './client/ApiClient.js';\nexport { HelixBitsApi } from './endpoints/bits/HelixBitsApi.js';\nexport { HelixBitsLeaderboard } from './endpoints/bits/HelixBitsLeaderboard.js';\nexport { HelixBitsLeaderboardEntry } from './endpoints/bits/HelixBitsLeaderboardEntry.js';\nexport { HelixCheermoteList } from './endpoints/bits/HelixCheermoteList.js';\nexport { HelixChannelApi } from './endpoints/channel/HelixChannelApi.js';\nexport { HelixAdSchedule } from './endpoints/channel/HelixAdSchedule.js';\nexport { HelixChannel } from './endpoints/channel/HelixChannel.js';\nexport { HelixChannelEditor } from './endpoints/channel/HelixChannelEditor.js';\nexport { HelixChannelFollower } from './endpoints/channel/HelixChannelFollower.js';\nexport { HelixFollowedChannel } from './endpoints/channel/HelixFollowedChannel.js';\nexport { HelixChannelReference } from './endpoints/channel/HelixChannelReference.js';\nexport { HelixChannelPointsApi } from './endpoints/channelPoints/HelixChannelPointsApi.js';\nexport { HelixCustomReward } from './endpoints/channelPoints/HelixCustomReward.js';\nexport { HelixCustomRewardRedemption } from './endpoints/channelPoints/HelixCustomRewardRedemption.js';\nexport { HelixCharityApi } from './endpoints/charity/HelixCharityApi.js';\nexport { HelixCharityCampaign } from './endpoints/charity/HelixCharityCampaign.js';\nexport { HelixCharityCampaignDonation } from './endpoints/charity/HelixCharityCampaignDonation.js';\nexport { HelixCharityCampaignAmount } from './endpoints/charity/HelixCharityCampaignAmount.js';\nexport { HelixChatApi } from './endpoints/chat/HelixChatApi.js';\nexport { HelixChatBadgeSet } from './endpoints/chat/HelixChatBadgeSet.js';\nexport { HelixChatBadgeVersion } from './endpoints/chat/HelixChatBadgeVersion.js';\nexport { HelixChatSettings } from './endpoints/chat/HelixChatSettings.js';\nexport { HelixChatChatter } from './endpoints/chat/HelixChatChatter.js';\nexport { HelixEmote } from './endpoints/chat/HelixEmote.js';\nexport { HelixChannelEmote } from './endpoints/chat/HelixChannelEmote.js';\nexport { HelixEmoteFromSet } from './endpoints/chat/HelixEmoteFromSet.js';\nexport { HelixUserEmote } from './endpoints/chat/HelixUserEmote.js';\nexport { HelixPrivilegedChatSettings } from './endpoints/chat/HelixPrivilegedChatSettings.js';\nexport { HelixSentChatMessage } from './endpoints/chat/HelixSentChatMessage.js';\nexport { HelixSharedChatSessionParticipant } from './endpoints/chat/HelixSharedChatSessionParticipant.js';\nexport { HelixSharedChatSession } from './endpoints/chat/HelixSharedChatSession.js';\nexport { HelixClipApi } from './endpoints/clip/HelixClipApi.js';\nexport { HelixClip } from './endpoints/clip/HelixClip.js';\nexport { HelixContentClassificationLabelApi } from './endpoints/contentClassificationLabels/HelixContentClassificationLabelApi.js';\nexport { HelixContentClassificationLabel } from './endpoints/contentClassificationLabels/HelixContentClassificationLabel.js';\nexport { HelixEntitlementApi } from './endpoints/entitlements/HelixEntitlementApi.js';\nexport { HelixDropsEntitlement } from './endpoints/entitlements/HelixDropsEntitlement.js';\nexport { HelixEventSubApi } from './endpoints/eventSub/HelixEventSubApi.js';\nexport { HelixEventSubConduit } from './endpoints/eventSub/HelixEventSubConduit.js';\nexport { HelixEventSubConduitShard } from './endpoints/eventSub/HelixEventSubConduitShard.js';\nexport { HelixEventSubSubscription } from './endpoints/eventSub/HelixEventSubSubscription.js';\nexport { HelixPaginatedEventSubSubscriptionsRequest } from './endpoints/eventSub/HelixPaginatedEventSubSubscriptionsRequest.js';\nexport { HelixExtensionsApi } from './endpoints/extensions/HelixExtensionsApi.js';\nexport { HelixExtensionBitsProduct } from './endpoints/extensions/HelixExtensionBitsProduct.js';\nexport { HelixExtensionTransaction } from './endpoints/extensions/HelixExtensionTransaction.js';\nexport { HelixGameApi } from './endpoints/game/HelixGameApi.js';\nexport { HelixGame } from './endpoints/game/HelixGame.js';\nexport { HelixGoalApi } from './endpoints/goals/HelixGoalApi.js';\nexport { HelixGoal } from './endpoints/goals/HelixGoal.js';\nexport { HelixHypeTrainApi } from './endpoints/hypeTrain/HelixHypeTrainApi.js';\nexport { HelixHypeTrain } from './endpoints/hypeTrain/HelixHypeTrain.js';\nexport { HelixHypeTrainAllTimeHigh } from './endpoints/hypeTrain/HelixHypeTrainAllTimeHigh.js';\nexport { HelixHypeTrainContribution } from './endpoints/hypeTrain/HelixHypeTrainContribution.js';\nexport { HelixHypeTrainSharedParticipant } from './endpoints/hypeTrain/HelixHypeTrainSharedParticipant.js';\nexport { HelixHypeTrainStatus } from './endpoints/hypeTrain/HelixHypeTrainStatus.js';\nexport { HelixModerationApi } from './endpoints/moderation/HelixModerationApi.js';\nexport { HelixBan } from './endpoints/moderation/HelixBan.js';\nexport { HelixModerator } from './endpoints/moderation/HelixModerator.js';\nexport { HelixModeratedChannel } from './endpoints/moderation/HelixModeratedChannel.js';\nexport { HelixBanUser } from './endpoints/moderation/HelixBanUser.js';\nexport { HelixBlockedTerm } from './endpoints/moderation/HelixBlockedTerm.js';\nexport { HelixShieldModeStatus } from './endpoints/moderation/HelixShieldModeStatus.js';\nexport { HelixUnbanRequest } from './endpoints/moderation/HelixUnbanRequest.js';\nexport { HelixWarning } from './endpoints/moderation/HelixWarning.js';\nexport { HelixPollApi } from './endpoints/poll/HelixPollApi.js';\nexport { HelixPoll } from './endpoints/poll/HelixPoll.js';\nexport { HelixPollChoice } from './endpoints/poll/HelixPollChoice.js';\nexport { HelixPredictionApi } from './endpoints/prediction/HelixPredictionApi.js';\nexport { HelixPrediction } from './endpoints/prediction/HelixPrediction.js';\nexport { HelixPredictionOutcome } from './endpoints/prediction/HelixPredictionOutcome.js';\nexport { HelixPredictor } from './endpoints/prediction/HelixPredictor.js';\nexport { HelixRaidApi } from './endpoints/raids/HelixRaidApi.js';\nexport { HelixRaid } from './endpoints/raids/HelixRaid.js';\nexport { HelixUserRelation } from './relations/HelixUserRelation.js';\nexport { HelixScheduleApi } from './endpoints/schedule/HelixScheduleApi.js';\nexport { HelixSchedule } from './endpoints/schedule/HelixSchedule.js';\nexport { HelixScheduleSegment } from './endpoints/schedule/HelixScheduleSegment.js';\nexport { HelixPaginatedScheduleSegmentRequest } from './endpoints/schedule/HelixPaginatedScheduleSegmentRequest.js';\nexport { HelixSearchApi } from './endpoints/search/HelixSearchApi.js';\nexport { HelixChannelSearchResult } from './endpoints/search/HelixChannelSearchResult.js';\nexport { HelixStreamApi } from './endpoints/stream/HelixStreamApi.js';\nexport { HelixStream } from './endpoints/stream/HelixStream.js';\nexport { HelixStreamMarker } from './endpoints/stream/HelixStreamMarker.js';\nexport { HelixStreamMarkerWithVideo } from './endpoints/stream/HelixStreamMarkerWithVideo.js';\nexport { HelixPaginatedSubscriptionsRequest } from './endpoints/subscriptions/HelixPaginatedSubscriptionsRequest.js';\nexport { HelixSubscriptionApi } from './endpoints/subscriptions/HelixSubscriptionApi.js';\nexport { HelixSubscription } from './endpoints/subscriptions/HelixSubscription.js';\nexport { HelixUserSubscription } from './endpoints/subscriptions/HelixUserSubscription.js';\nexport { HelixTeamApi } from './endpoints/team/HelixTeamApi.js';\nexport { HelixTeam } from './endpoints/team/HelixTeam.js';\nexport { HelixTeamWithUsers } from './endpoints/team/HelixTeamWithUsers.js';\nexport { HelixUserApi } from './endpoints/user/HelixUserApi.js';\nexport { HelixUserBlock } from './endpoints/user/HelixUserBlock.js';\nexport { HelixFollow } from './endpoints/user/HelixFollow.js';\nexport { HelixPrivilegedUser } from './endpoints/user/HelixPrivilegedUser.js';\nexport { HelixUser } from './endpoints/user/HelixUser.js';\nexport { HelixBaseExtension } from './endpoints/user/extensions/HelixBaseExtension.js';\nexport { HelixInstalledExtension } from './endpoints/user/extensions/HelixInstalledExtension.js';\nexport { HelixInstalledExtensionList } from './endpoints/user/extensions/HelixInstalledExtensionList.js';\nexport { HelixUserExtension } from './endpoints/user/extensions/HelixUserExtension.js';\nexport { HelixVideoApi } from './endpoints/video/HelixVideoApi.js';\nexport { HelixVideo } from './endpoints/video/HelixVideo.js';\nexport { HelixWhisperApi } from './endpoints/whisper/HelixWhisperApi.js';\nexport { ChatMessageDroppedError } from './errors/ChatMessageDroppedError.js';\nexport { ConfigError } from './errors/ConfigError.js';\nexport { StreamNotLiveError } from './errors/StreamNotLiveError.js';\nexport { ApiReportedRequest } from './reporting/ApiReportedRequest.js';\nexport { HelixPaginatedRequest } from './utils/pagination/HelixPaginatedRequest.js';\nexport { HelixPaginatedRequestWithTotal } from './utils/pagination/HelixPaginatedRequestWithTotal.js';\nexport { extractUserId, extractUserName, HelixExtension, HellFreezesOverError } from '@twurple/common';\n", "import { __decorate } from \"tslib\";\nimport { isNode } from '@d-fischer/detect-node';\nimport { createLogger } from '@d-fischer/logger';\nimport { PartitionedRateLimiter, PartitionedTimeBasedRateLimiter } from '@d-fischer/rate-limiter';\nimport { callTwitchApiRaw } from '@twurple/api-call';\nimport { extractUserId, rtfm } from '@twurple/common';\nimport { ConfigError } from '../errors/ConfigError.js';\nimport { HelixRateLimiter } from '../utils/HelixRateLimiter.js';\nimport { BaseApiClient } from './BaseApiClient.js';\nimport { NoContextApiClient } from './NoContextApiClient.js';\nimport { UserContextApiClient } from './UserContextApiClient.js';\n/**\n * An API client for the Twitch Helix API and other miscellaneous endpoints.\n *\n * @meta category main\n * @hideProtected\n */\nlet ApiClient = class ApiClient extends BaseApiClient {\n /**\n * Creates a new API client instance.\n *\n * @param config Configuration for the client instance.\n */\n constructor(config) {\n if (!config.authProvider) {\n throw new ConfigError('No auth provider given. Please supply the `authProvider` option.');\n }\n const rateLimitLoggerOptions = { name: 'twurple:api:rate-limiter', ...config.logger };\n super(config, createLogger({ name: 'twurple:api:client', ...config.logger }), isNode\n ? new PartitionedRateLimiter({\n getPartitionKey: req => req.userId ?? null,\n createChild: () => new HelixRateLimiter({ logger: rateLimitLoggerOptions }),\n })\n : new PartitionedTimeBasedRateLimiter({\n logger: rateLimitLoggerOptions,\n bucketSize: 800,\n timeFrame: 64000,\n doRequest: async ({ options, clientId, accessToken, authorizationType, fetchOptions, }) => await callTwitchApiRaw(options, clientId, accessToken, authorizationType, fetchOptions),\n getPartitionKey: req => req.userId ?? null,\n }));\n }\n /**\n * Creates a contextualized ApiClient that can be used to call the API in the context of a given user.\n *\n * @param user The user to use as context.\n * @param runner The callback to execute.\n *\n * A parameter is passed that should be used in place of the normal `ApiClient`\n * to ensure that all requests are executed in the given user's context.\n *\n * Please note that requests which require scope authorization ignore this context.\n *\n * The return value of your callback will be propagated to the return value of this method.\n */\n async asUser(user, runner) {\n const ctx = new UserContextApiClient(this._config, this._logger, this._rateLimiter, extractUserId(user));\n return await runner(ctx);\n }\n /**\n * Creates a contextualized ApiClient that can be used to call the API in the context of a given intent.\n *\n * @param intents A list of intents. The first one that is found in your auth provider will be used.\n * @param runner The callback to execute.\n *\n * A parameter is passed that should be used in place of the normal `ApiClient`\n * to ensure that all requests are executed in the given user's context.\n *\n * Please note that requests which require scope authorization ignore this context.\n *\n * The return value of your callback will be propagated to the return value of this method.\n */\n async asIntent(intents, runner) {\n if (!this._authProvider.getAccessTokenForIntent) {\n throw new Error('Trying to use intents with an auth provider that does not support them');\n }\n for (const intent of intents) {\n const user = await this._authProvider.getAccessTokenForIntent(intent);\n if (user) {\n const ctx = new UserContextApiClient(this._config, this._logger, this._rateLimiter, user.userId);\n return await runner(ctx);\n }\n }\n throw new Error(`Intents [${intents.join(', ')}] not found in auth provider`);\n }\n /**\n * Creates a contextualized ApiClient that can be used to call the API without the context of any user.\n *\n * This usually means that an app access token is used.\n *\n * @param runner The callback to execute.\n *\n * A parameter is passed that should be used in place of the normal `ApiClient`\n * to ensure that all requests are executed without user context.\n *\n * Please note that requests which require scope authorization ignore this context erasure.\n *\n * The return value of your callback will be propagated to the return value of this method.\n */\n async withoutUser(runner) {\n const ctx = new NoContextApiClient(this._config, this._logger, this._rateLimiter);\n return await runner(ctx);\n }\n};\nApiClient = __decorate([\n rtfm('api', 'ApiClient')\n], ApiClient);\nexport { ApiClient };\n", "/******************************************************************************\nCopyright (c) Microsoft Corporation.\n\nPermission to use, copy, modify, and/or distribute this software for any\npurpose with or without fee is hereby granted.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\nPERFORMANCE OF THIS SOFTWARE.\n***************************************************************************** */\n/* global Reflect, Promise, SuppressedError, Symbol, Iterator */\n\nvar extendStatics = function(d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\n return extendStatics(d, b);\n};\n\nexport function __extends(d, b) {\n if (typeof b !== \"function\" && b !== null)\n throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n}\n\nexport var __assign = function() {\n __assign = Object.assign || function __assign(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\n }\n return t;\n }\n return __assign.apply(this, arguments);\n}\n\nexport function __rest(s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\n t[p[i]] = s[p[i]];\n }\n return t;\n}\n\nexport function __decorate(decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n}\n\nexport function __param(paramIndex, decorator) {\n return function (target, key) { decorator(target, key, paramIndex); }\n}\n\nexport function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {\n function accept(f) { if (f !== void 0 && typeof f !== \"function\") throw new TypeError(\"Function expected\"); return f; }\n var kind = contextIn.kind, key = kind === \"getter\" ? \"get\" : kind === \"setter\" ? \"set\" : \"value\";\n var target = !descriptorIn && ctor ? contextIn[\"static\"] ? ctor : ctor.prototype : null;\n var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});\n var _, done = false;\n for (var i = decorators.length - 1; i >= 0; i--) {\n var context = {};\n for (var p in contextIn) context[p] = p === \"access\" ? {} : contextIn[p];\n for (var p in contextIn.access) context.access[p] = contextIn.access[p];\n context.addInitializer = function (f) { if (done) throw new TypeError(\"Cannot add initializers after decoration has completed\"); extraInitializers.push(accept(f || null)); };\n var result = (0, decorators[i])(kind === \"accessor\" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);\n if (kind === \"accessor\") {\n if (result === void 0) continue;\n if (result === null || typeof result !== \"object\") throw new TypeError(\"Object expected\");\n if (_ = accept(result.get)) descriptor.get = _;\n if (_ = accept(result.set)) descriptor.set = _;\n if (_ = accept(result.init)) initializers.unshift(_);\n }\n else if (_ = accept(result)) {\n if (kind === \"field\") initializers.unshift(_);\n else descriptor[key] = _;\n }\n }\n if (target) Object.defineProperty(target, contextIn.name, descriptor);\n done = true;\n};\n\nexport function __runInitializers(thisArg, initializers, value) {\n var useValue = arguments.length > 2;\n for (var i = 0; i < initializers.length; i++) {\n value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);\n }\n return useValue ? value : void 0;\n};\n\nexport function __propKey(x) {\n return typeof x === \"symbol\" ? x : \"\".concat(x);\n};\n\nexport function __setFunctionName(f, name, prefix) {\n if (typeof name === \"symbol\") name = name.description ? \"[\".concat(name.description, \"]\") : \"\";\n return Object.defineProperty(f, \"name\", { configurable: true, value: prefix ? \"\".concat(prefix, \" \", name) : name });\n};\n\nexport function __metadata(metadataKey, metadataValue) {\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\n}\n\nexport function __awaiter(thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n}\n\nexport function __generator(thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === \"function\" ? Iterator : Object).prototype);\n return g.next = verb(0), g[\"throw\"] = verb(1), g[\"return\"] = verb(2), typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (g && (g = 0, op[0] && (_ = 0)), _) try {\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [op[0] & 2, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n}\n\nexport var __createBinding = Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n});\n\nexport function __exportStar(m, o) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);\n}\n\nexport function __values(o) {\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\n if (m) return m.call(o);\n if (o && typeof o.length === \"number\") return {\n next: function () {\n if (o && i >= o.length) o = void 0;\n return { value: o && o[i++], done: !o };\n }\n };\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\n}\n\nexport function __read(o, n) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n if (!m) return o;\n var i = m.call(o), r, ar = [], e;\n try {\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n }\n catch (error) { e = { error: error }; }\n finally {\n try {\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\n }\n finally { if (e) throw e.error; }\n }\n return ar;\n}\n\n/** @deprecated */\nexport function __spread() {\n for (var ar = [], i = 0; i < arguments.length; i++)\n ar = ar.concat(__read(arguments[i]));\n return ar;\n}\n\n/** @deprecated */\nexport function __spreadArrays() {\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\n r[k] = a[j];\n return r;\n}\n\nexport function __spreadArray(to, from, pack) {\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\n if (ar || !(i in from)) {\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\n ar[i] = from[i];\n }\n }\n return to.concat(ar || Array.prototype.slice.call(from));\n}\n\nexport function __await(v) {\n return this instanceof __await ? (this.v = v, this) : new __await(v);\n}\n\nexport function __asyncGenerator(thisArg, _arguments, generator) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\n return i = Object.create((typeof AsyncIterator === \"function\" ? AsyncIterator : Object).prototype), verb(\"next\"), verb(\"throw\"), verb(\"return\", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i;\n function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; }\n function verb(n, f) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; if (f) i[n] = f(i[n]); } }\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\n function fulfill(value) { resume(\"next\", value); }\n function reject(value) { resume(\"throw\", value); }\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\n}\n\nexport function __asyncDelegator(o) {\n var i, p;\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; }\n}\n\nexport function __asyncValues(o) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var m = o[Symbol.asyncIterator], i;\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\n}\n\nexport function __makeTemplateObject(cooked, raw) {\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\n return cooked;\n};\n\nvar __setModuleDefault = Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n};\n\nvar ownKeys = function(o) {\n ownKeys = Object.getOwnPropertyNames || function (o) {\n var ar = [];\n for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;\n return ar;\n };\n return ownKeys(o);\n};\n\nexport function __importStar(mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== \"default\") __createBinding(result, mod, k[i]);\n __setModuleDefault(result, mod);\n return result;\n}\n\nexport function __importDefault(mod) {\n return (mod && mod.__esModule) ? mod : { default: mod };\n}\n\nexport function __classPrivateFieldGet(receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n}\n\nexport function __classPrivateFieldSet(receiver, state, value, kind, f) {\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n}\n\nexport function __classPrivateFieldIn(state, receiver) {\n if (receiver === null || (typeof receiver !== \"object\" && typeof receiver !== \"function\")) throw new TypeError(\"Cannot use 'in' operator on non-object\");\n return typeof state === \"function\" ? receiver === state : state.has(receiver);\n}\n\nexport function __addDisposableResource(env, value, async) {\n if (value !== null && value !== void 0) {\n if (typeof value !== \"object\" && typeof value !== \"function\") throw new TypeError(\"Object expected.\");\n var dispose, inner;\n if (async) {\n if (!Symbol.asyncDispose) throw new TypeError(\"Symbol.asyncDispose is not defined.\");\n dispose = value[Symbol.asyncDispose];\n }\n if (dispose === void 0) {\n if (!Symbol.dispose) throw new TypeError(\"Symbol.dispose is not defined.\");\n dispose = value[Symbol.dispose];\n if (async) inner = dispose;\n }\n if (typeof dispose !== \"function\") throw new TypeError(\"Object not disposable.\");\n if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } };\n env.stack.push({ value: value, dispose: dispose, async: async });\n }\n else if (async) {\n env.stack.push({ async: true });\n }\n return value;\n}\n\nvar _SuppressedError = typeof SuppressedError === \"function\" ? SuppressedError : function (error, suppressed, message) {\n var e = new Error(message);\n return e.name = \"SuppressedError\", e.error = error, e.suppressed = suppressed, e;\n};\n\nexport function __disposeResources(env) {\n function fail(e) {\n env.error = env.hasError ? new _SuppressedError(e, env.error, \"An error was suppressed during disposal.\") : e;\n env.hasError = true;\n }\n var r, s = 0;\n function next() {\n while (r = env.stack.pop()) {\n try {\n if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);\n if (r.dispose) {\n var result = r.dispose.call(r.value);\n if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { fail(e); return next(); });\n }\n else s |= 1;\n }\n catch (e) {\n fail(e);\n }\n }\n if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();\n if (env.hasError) throw env.error;\n }\n return next();\n}\n\nexport function __rewriteRelativeImportExtension(path, preserveJsx) {\n if (typeof path === \"string\" && /^\\.\\.?\\//.test(path)) {\n return path.replace(/\\.(tsx)$|((?:\\.d)?)((?:\\.[^./]+?)?)\\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {\n return tsx ? preserveJsx ? \".jsx\" : \".js\" : d && (!ext || !cm) ? m : (d + ext + \".\" + cm.toLowerCase() + \"js\");\n });\n }\n return path;\n}\n\nexport default {\n __extends,\n __assign,\n __rest,\n __decorate,\n __param,\n __esDecorate,\n __runInitializers,\n __propKey,\n __setFunctionName,\n __metadata,\n __awaiter,\n __generator,\n __createBinding,\n __exportStar,\n __values,\n __read,\n __spread,\n __spreadArrays,\n __spreadArray,\n __await,\n __asyncGenerator,\n __asyncDelegator,\n __asyncValues,\n __makeTemplateObject,\n __importStar,\n __importDefault,\n __classPrivateFieldGet,\n __classPrivateFieldSet,\n __classPrivateFieldIn,\n __addDisposableResource,\n __disposeResources,\n __rewriteRelativeImportExtension,\n};\n", "export { createLogger } from \"./createLogger.mjs\";\nexport { LogLevel } from \"./LogLevel.mjs\";\n", "import { isNode } from '@d-fischer/detect-node';\nimport { BrowserLogger } from \"./BrowserLogger.mjs\";\nimport { CustomLoggerWrapper } from \"./CustomLoggerWrapper.mjs\";\nimport { NodeLogger } from \"./NodeLogger.mjs\";\nexport function createLogger(options) {\n if (options.custom) {\n return new CustomLoggerWrapper(options);\n }\n if (isNode) {\n return new NodeLogger(options);\n }\n return new BrowserLogger(options);\n}\n", "import { __extends } from \"tslib\";\nimport { LogLevelToConsoleFunction } from \"./LogLevel.mjs\";\nimport { BaseLogger } from \"./BaseLogger.mjs\";\nvar BrowserLogger = /** @class */ (function (_super) {\n __extends(BrowserLogger, _super);\n function BrowserLogger() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n BrowserLogger.prototype.log = function (level, message) {\n if (level > this._minLevel) {\n return;\n }\n var logFn = LogLevelToConsoleFunction[level];\n var formattedMessage = \"[\".concat(this._name, \"] \").concat(message);\n if (this._timestamps) {\n formattedMessage = \"[\".concat(new Date().toISOString(), \"] \").concat(message);\n }\n logFn(formattedMessage);\n };\n return BrowserLogger;\n}(BaseLogger));\nexport { BrowserLogger };\n", "var _a;\nimport { isNode } from '@d-fischer/detect-node';\nexport var LogLevel;\n(function (LogLevel) {\n LogLevel[LogLevel[\"CRITICAL\"] = 0] = \"CRITICAL\";\n LogLevel[LogLevel[\"ERROR\"] = 1] = \"ERROR\";\n LogLevel[LogLevel[\"WARNING\"] = 2] = \"WARNING\";\n LogLevel[LogLevel[\"INFO\"] = 3] = \"INFO\";\n LogLevel[LogLevel[\"DEBUG\"] = 4] = \"DEBUG\";\n LogLevel[LogLevel[\"TRACE\"] = 7] = \"TRACE\";\n})(LogLevel || (LogLevel = {}));\nexport function resolveLogLevel(level) {\n if (typeof level === 'number') {\n if (Object.prototype.hasOwnProperty.call(LogLevel, level)) {\n return level;\n }\n var eligibleLevels = Object.keys(LogLevel)\n .map(function (k) { return parseInt(k, 10); })\n .filter(function (k) { return !isNaN(k) && k < level; });\n if (!eligibleLevels.length) {\n return LogLevel.WARNING;\n }\n return Math.max.apply(Math, eligibleLevels);\n }\n // TODO drop the replace for next major, it keeps the old deprecated debug1/2/3 levels running\n var strLevel = level.replace(/\\d+$/, '').toUpperCase();\n if (!Object.prototype.hasOwnProperty.call(LogLevel, strLevel)) {\n throw new Error(\"Unknown log level string: \".concat(level));\n }\n return LogLevel[strLevel];\n}\n// Node 8+ defines console.debug as noop, and earlier versions don't define it at all\nvar debugFunction = isNode ? console.log.bind(console) : console.debug.bind(console);\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport var LogLevelToConsoleFunction = (_a = {},\n _a[LogLevel.CRITICAL] = console.error.bind(console),\n _a[LogLevel.ERROR] = console.error.bind(console),\n _a[LogLevel.WARNING] = console.warn.bind(console),\n _a[LogLevel.INFO] = console.info.bind(console),\n _a[LogLevel.DEBUG] = debugFunction.bind(console),\n _a[LogLevel.TRACE] = console.trace.bind(console),\n _a);\n", "import { mapOptional } from '@d-fischer/shared-utils';\nimport { isNode } from '@d-fischer/detect-node';\nimport { getMinLogLevelFromEnv } from \"./getMinLogLevelFromEnv.mjs\";\nimport { LogLevel, resolveLogLevel } from \"./LogLevel.mjs\";\nvar BaseLogger = /** @class */ (function () {\n function BaseLogger(_a) {\n var name = _a.name, minLevel = _a.minLevel, _b = _a.emoji, emoji = _b === void 0 ? false : _b, colors = _a.colors, _c = _a.timestamps, timestamps = _c === void 0 ? isNode : _c;\n var _d, _e;\n this._name = name;\n this._minLevel =\n (_e = (_d = mapOptional(minLevel, function (lv) { return resolveLogLevel(lv); })) !== null && _d !== void 0 ? _d : getMinLogLevelFromEnv(name)) !== null && _e !== void 0 ? _e : LogLevel.WARNING;\n this._emoji = emoji;\n this._colors = colors;\n this._timestamps = timestamps;\n }\n // region convenience methods\n BaseLogger.prototype.crit = function (message) {\n this.log(LogLevel.CRITICAL, message);\n };\n BaseLogger.prototype.error = function (message) {\n this.log(LogLevel.ERROR, message);\n };\n BaseLogger.prototype.warn = function (message) {\n this.log(LogLevel.WARNING, message);\n };\n BaseLogger.prototype.info = function (message) {\n this.log(LogLevel.INFO, message);\n };\n BaseLogger.prototype.debug = function (message) {\n this.log(LogLevel.DEBUG, message);\n };\n BaseLogger.prototype.trace = function (message) {\n this.log(LogLevel.TRACE, message);\n };\n return BaseLogger;\n}());\nexport { BaseLogger };\n", "export { Enumerable } from \"./decorators/Enumerable.mjs\";\nexport { flatten } from \"./functions/array/flatten.mjs\";\nexport { immutableSplice } from \"./functions/array/immutableSplice.mjs\";\nexport { partitionedFlatMap } from \"./functions/array/partitionedFlatMap.mjs\";\nexport { resolveConfigValue, resolveConfigValueSync } from \"./functions/config/resolveConfigValue.mjs\";\nexport { deprecateClass } from \"./functions/deprecate/deprecateClass.mjs\";\nexport { match, eq } from \"./functions/match/match.mjs\";\nexport { fibWithLimit } from \"./functions/math/fib.mjs\";\nexport { arrayToObject } from \"./functions/object/arrayToObject.mjs\";\nexport { entriesToObject } from \"./functions/object/entriesToObject.mjs\";\nexport { forEachObjectEntry } from \"./functions/object/forEachObjectEntry.mjs\";\nexport { groupBy } from \"./functions/object/groupBy.mjs\";\nexport { indexBy } from \"./functions/object/indexBy.mjs\";\nexport { mapObject } from \"./functions/object/mapObject.mjs\";\nexport { omit } from \"./functions/object/omit.mjs\";\nexport { pick } from \"./functions/object/pick.mjs\";\nexport { isNullish, mapNullable, mapOptional } from \"./functions/optional/mapOptional.mjs\";\nexport { delay } from \"./functions/promise/delay.mjs\";\nexport { promiseWithResolvers } from \"./functions/promise/withResolvers.mjs\";\nexport { padLeft } from \"./functions/string/padLeft.mjs\";\nexport { splitWithLimit } from \"./functions/string/splitWithLimit.mjs\";\nexport { utf8Length, utf8Substring } from \"./functions/string/utf8.mjs\";\n", "/* eslint-disable @typescript-eslint/naming-convention */\nexport function Enumerable(enumerable) {\n if (enumerable === void 0) { enumerable = true; }\n return function (target, key) {\n // first property defined in prototype, that's why we use getters/setters\n // (otherwise assignment in object will override property in prototype)\n Object.defineProperty(target, key, {\n get: function () {\n return;\n },\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n set: function (val) {\n // here we have a reference to the instance and can set property directly to it\n Object.defineProperty(this, key, {\n value: val,\n writable: true,\n enumerable: enumerable\n });\n },\n enumerable: enumerable\n });\n };\n}\n", "import { __read, __spreadArray } from \"tslib\";\nexport function flatten(arr) {\n var _a;\n return (_a = []).concat.apply(_a, __spreadArray([], __read(arr), false));\n}\n", "import { __read, __spreadArray } from \"tslib\";\nexport function arrayToObject(arr, fn) {\n return Object.assign.apply(Object, __spreadArray([{}], __read(arr.map(fn)), false));\n}\n", "import { arrayToObject } from \"./arrayToObject.mjs\";\nexport function indexBy(arr, keyFn) {\n if (typeof keyFn !== 'function') {\n var key_1 = keyFn;\n // eslint-disable-next-line @typescript-eslint/ban-types,@typescript-eslint/no-base-to-string\n keyFn = (function (value) { return value[key_1].toString(); });\n }\n return arrayToObject(arr, function (val) {\n var _a;\n return (_a = {}, _a[keyFn(val)] = val, _a);\n });\n}\n", "export function isNullish(value) {\n return value == null;\n}\nexport function mapNullable(value, cb) {\n return isNullish(value) ? null : cb(value);\n}\nexport function mapOptional(value, cb) {\n return isNullish(value) ? undefined : cb(value);\n}\n", "export function promiseWithResolvers() {\n // eslint-disable-next-line @typescript-eslint/init-declarations\n var resolve;\n // eslint-disable-next-line @typescript-eslint/init-declarations\n var reject;\n var promise = new Promise(function (_resolve, _reject) {\n resolve = _resolve;\n reject = _reject;\n });\n return { promise: promise, resolve: resolve, reject: reject };\n}\n", "var _a, _b;\nimport { resolveLogLevel } from \"./LogLevel.mjs\";\nvar data = typeof process === 'undefined'\n ? []\n : (_b = (_a = process.env.LOGGING) === null || _a === void 0 ? void 0 : _a.split(';').map(function (part) {\n var _a = part.split('=', 2), namespace = _a[0], strLevel = _a[1];\n if (strLevel) {\n return [namespace === 'default' ? undefined : namespace.split(':'), resolveLogLevel(strLevel)];\n }\n return null;\n }).filter(function (v) { return !!v; }).sort(function (_a, _b) {\n var _c, _d;\n var a = _a[0];\n var b = _b[0];\n return ((_c = b === null || b === void 0 ? void 0 : b.length) !== null && _c !== void 0 ? _c : 0) - ((_d = a === null || a === void 0 ? void 0 : a.length) !== null && _d !== void 0 ? _d : 0);\n })) !== null && _b !== void 0 ? _b : [];\nvar defaultIndex = data.findIndex(function (_a) {\n var nsParts = _a[0];\n return !nsParts;\n});\nvar defaultLevel = undefined;\nif (defaultIndex !== -1) {\n defaultLevel = data[defaultIndex][1];\n data.splice(defaultIndex);\n}\nfunction isPrefix(value, prefix) {\n return prefix.length <= value.length && prefix.every(function (item, i) { return item === value[i]; });\n}\nexport function getMinLogLevelFromEnv(name) {\n var nameSplit = name.split(':');\n for (var _i = 0, data_1 = data; _i < data_1.length; _i++) {\n var _a = data_1[_i], nsParts = _a[0], level = _a[1];\n if (isPrefix(nameSplit, nsParts)) {\n return level;\n }\n }\n return defaultLevel;\n}\n", "import { mapOptional } from '@d-fischer/shared-utils';\nimport { getMinLogLevelFromEnv } from \"./getMinLogLevelFromEnv.mjs\";\nimport { LogLevel, resolveLogLevel } from \"./LogLevel.mjs\";\nvar CustomLoggerWrapper = /** @class */ (function () {\n function CustomLoggerWrapper(_a) {\n var name = _a.name, minLevel = _a.minLevel, custom = _a.custom;\n var _b;\n this._minLevel = (_b = mapOptional(minLevel, function (lv) { return resolveLogLevel(lv); })) !== null && _b !== void 0 ? _b : getMinLogLevelFromEnv(name);\n this._override = typeof custom === 'function' ? { log: custom } : custom;\n }\n CustomLoggerWrapper.prototype.log = function (level, message) {\n if (this._shouldLog(level)) {\n this._override.log(level, message);\n }\n };\n CustomLoggerWrapper.prototype.crit = function (message) {\n if (!this._override.crit) {\n this.log(LogLevel.CRITICAL, message);\n }\n else if (this._shouldLog(LogLevel.CRITICAL)) {\n this._override.crit(message);\n }\n };\n CustomLoggerWrapper.prototype.error = function (message) {\n if (!this._override.error) {\n this.log(LogLevel.ERROR, message);\n }\n else if (this._shouldLog(LogLevel.ERROR)) {\n this._override.error(message);\n }\n };\n CustomLoggerWrapper.prototype.warn = function (message) {\n if (!this._override.warn) {\n this.log(LogLevel.WARNING, message);\n }\n else if (this._shouldLog(LogLevel.WARNING)) {\n this._override.warn(message);\n }\n };\n CustomLoggerWrapper.prototype.info = function (message) {\n if (!this._override.info) {\n this.log(LogLevel.INFO, message);\n }\n else if (this._shouldLog(LogLevel.INFO)) {\n this._override.info(message);\n }\n };\n CustomLoggerWrapper.prototype.debug = function (message) {\n if (!this._override.debug) {\n this.log(LogLevel.DEBUG, message);\n }\n else if (this._shouldLog(LogLevel.DEBUG)) {\n this._override.debug(message);\n }\n };\n CustomLoggerWrapper.prototype.trace = function (message) {\n if (!this._override.trace) {\n this.log(LogLevel.TRACE, message);\n }\n else if (this._shouldLog(LogLevel.TRACE)) {\n this._override.trace(message);\n }\n };\n CustomLoggerWrapper.prototype._shouldLog = function (level) {\n return this._minLevel === undefined || this._minLevel >= level;\n };\n return CustomLoggerWrapper;\n}());\nexport { CustomLoggerWrapper };\n", "var _a, _b, _c;\nimport { __extends } from \"tslib\";\nimport { LogLevel, LogLevelToConsoleFunction } from \"./LogLevel.mjs\";\nimport { BaseLogger } from \"./BaseLogger.mjs\";\nexport var LogLevelToEmoji = (_a = {},\n _a[LogLevel.CRITICAL] = \"\\uD83D\\uDED1\",\n _a[LogLevel.ERROR] = \"\\u274C\",\n // these following two need extra spaces at the end because somehow they consume less space in a terminal than they should...\n _a[LogLevel.WARNING] = \"\\u26A0\\uFE0F \",\n _a[LogLevel.INFO] = \"\\u2139\\uFE0F \",\n _a[LogLevel.DEBUG] = \"\\uD83D\\uDC1E\",\n _a[LogLevel.TRACE] = \"\\uD83D\\uDC3E\",\n _a);\nvar colors = {\n black: 30,\n red: 31,\n green: 32,\n yellow: 33,\n blue: 34,\n magenta: 35,\n cyan: 36,\n white: 37,\n blackBright: 90,\n redBright: 91,\n greenBright: 92,\n yellowBright: 93,\n blueBright: 94,\n magentaBright: 95,\n cyanBright: 96,\n whiteBright: 97\n};\nvar bgColors = {\n bgBlack: 40,\n bgRed: 41,\n bgGreen: 42,\n bgYellow: 43,\n bgBlue: 44,\n bgMagenta: 45,\n bgCyan: 46,\n bgWhite: 47,\n bgBlackBright: 100,\n bgRedBright: 101,\n bgGreenBright: 102,\n bgYellowBright: 103,\n bgBlueBright: 104,\n bgMagentaBright: 105,\n bgCyanBright: 106,\n bgWhiteBright: 107\n};\nfunction createGenericWrapper(color, ending, inner) {\n return function (str) { return \"\\u001B[\".concat(color, \"m\").concat(inner ? inner(str) : str, \"\\u001B[\").concat(ending, \"m\"); };\n}\nfunction createColorWrapper(color) {\n return createGenericWrapper(colors[color], 39);\n}\nfunction createBgWrapper(color, fgWrapper) {\n return createGenericWrapper(bgColors[color], 49, fgWrapper);\n}\nexport var LogLevelToColor = (_b = {},\n _b[LogLevel.CRITICAL] = createColorWrapper('red'),\n _b[LogLevel.ERROR] = createColorWrapper('redBright'),\n _b[LogLevel.WARNING] = createColorWrapper('yellow'),\n _b[LogLevel.INFO] = createColorWrapper('blue'),\n _b[LogLevel.DEBUG] = createColorWrapper('magenta'),\n _b[LogLevel.TRACE] = createGenericWrapper(0, 0),\n _b);\nexport var LogLevelToBackgroundColor = (_c = {},\n _c[LogLevel.CRITICAL] = createBgWrapper('bgRed', createColorWrapper('white')),\n _c[LogLevel.ERROR] = createBgWrapper('bgRedBright', createColorWrapper('white')),\n _c[LogLevel.WARNING] = createBgWrapper('bgYellow', createColorWrapper('black')),\n _c[LogLevel.INFO] = createBgWrapper('bgBlue', createColorWrapper('white')),\n _c[LogLevel.DEBUG] = createBgWrapper('bgMagenta', createColorWrapper('black')),\n _c[LogLevel.TRACE] = createGenericWrapper(7, 27),\n _c);\nvar NodeLogger = /** @class */ (function (_super) {\n __extends(NodeLogger, _super);\n function NodeLogger() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n NodeLogger.prototype.log = function (level, message) {\n var _a, _b, _c;\n if (level > this._minLevel) {\n return;\n }\n var logFn = LogLevelToConsoleFunction[level];\n var builtMessage = '';\n if (this._timestamps) {\n builtMessage += \"[\".concat(new Date().toISOString(), \"] \");\n }\n if (this._emoji) {\n var emoji = LogLevelToEmoji[level];\n builtMessage += \"\".concat(emoji, \" \");\n }\n var useColors = (_c = (_a = this._colors) !== null && _a !== void 0 ? _a : (_b = process.stdout) === null || _b === void 0 ? void 0 : _b.isTTY) !== null && _c !== void 0 ? _c : true;\n if (useColors) {\n builtMessage += \"\".concat(LogLevelToBackgroundColor[level](this._name), \" \").concat(LogLevelToBackgroundColor[level](LogLevel[level]), \" \").concat(LogLevelToColor[level](message));\n }\n else {\n builtMessage += \"[\".concat(this._name, \":\").concat(LogLevel[level].toLowerCase(), \"] \").concat(message);\n }\n logFn(builtMessage);\n };\n return NodeLogger;\n}(BaseLogger));\nexport { NodeLogger };\n", "export { RateLimiterDestroyedError } from \"./errors/RateLimiterDestroyedError.mjs\";\nexport { RateLimitReachedError } from \"./errors/RateLimitReachedError.mjs\";\nexport { RetryAfterError } from \"./errors/RetryAfterError.mjs\";\nexport { NullRateLimiter } from \"./limiters/NullRateLimiter.mjs\";\nexport { PartitionedRateLimiter } from \"./limiters/PartitionedRateLimiter.mjs\";\nexport { PartitionedTimeBasedRateLimiter } from \"./limiters/PartitionedTimeBasedRateLimiter.mjs\";\nexport { ResponseBasedRateLimiter } from \"./limiters/ResponseBasedRateLimiter.mjs\";\nexport { TimeBasedRateLimiter } from \"./limiters/TimeBasedRateLimiter.mjs\";\nexport { TimedPassthruRateLimiter } from \"./limiters/TimedPassthruRateLimiter.mjs\";\n", "import { CustomError } from \"./CustomError.mjs\";\nexport class RateLimiterDestroyedError extends CustomError {\n}\n", "/** @private */\nexport class CustomError extends Error {\n constructor(...params) {\n var _a;\n // @ts-ignore\n super(...params);\n // restore prototype chain\n Object.setPrototypeOf(this, new.target.prototype);\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n (_a = Error.captureStackTrace) === null || _a === void 0 ? void 0 : _a.call(Error, this, new.target.constructor);\n }\n get name() {\n return this.constructor.name;\n }\n}\n", "import { CustomError } from \"./CustomError.mjs\";\nexport class RateLimitReachedError extends CustomError {\n}\n", "import { CustomError } from \"./CustomError.mjs\";\nexport class RetryAfterError extends CustomError {\n constructor(after) {\n super(`Need to retry after ${after} ms`);\n this._retryAt = Date.now() + after;\n }\n get retryAt() {\n return this._retryAt;\n }\n}\n", "import { ResponseBasedRateLimiter } from \"./ResponseBasedRateLimiter.mjs\";\nexport class PartitionedRateLimiter {\n constructor(options) {\n this._children = new Map();\n this._paused = false;\n this._partitionKeyCallback = options.getPartitionKey;\n this._createChildCallback = options.createChild;\n }\n async request(req, options) {\n const partitionKey = this._partitionKeyCallback(req);\n const partitionChild = this._getChild(partitionKey);\n return await partitionChild.request(req, options);\n }\n clear() {\n for (const child of this._children.values()) {\n child.clear();\n }\n }\n pause() {\n this._paused = true;\n for (const child of this._children.values()) {\n child.pause();\n }\n }\n resume() {\n this._paused = false;\n for (const child of this._children.values()) {\n child.resume();\n }\n }\n getChildStats(partitionKey) {\n if (!this._children.has(partitionKey)) {\n return null;\n }\n const child = this._children.get(partitionKey);\n if (!(child instanceof ResponseBasedRateLimiter)) {\n return null;\n }\n return child.stats;\n }\n _getChild(partitionKey) {\n if (this._children.has(partitionKey)) {\n return this._children.get(partitionKey);\n }\n const result = this._createChildCallback(partitionKey);\n if (this._paused) {\n result.pause();\n }\n this._children.set(partitionKey, result);\n return result;\n }\n}\n", "import { createLogger } from '@d-fischer/logger';\nimport { mapNullable } from '@d-fischer/shared-utils';\nimport { RateLimitReachedError } from \"../errors/RateLimitReachedError.mjs\";\nimport { RetryAfterError } from \"../errors/RetryAfterError.mjs\";\nexport class ResponseBasedRateLimiter {\n constructor({ logger }) {\n this._queue = [];\n this._batchRunning = false;\n this._paused = false;\n this._logger = createLogger({ name: 'rate-limiter', emoji: true, ...logger });\n }\n async request(req, options) {\n this._logger.trace('request start');\n return await new Promise((resolve, reject) => {\n var _a;\n const reqSpec = {\n req,\n resolve,\n reject,\n limitReachedBehavior: (_a = options === null || options === void 0 ? void 0 : options.limitReachedBehavior) !== null && _a !== void 0 ? _a : 'enqueue'\n };\n if (this._batchRunning || !!this._nextBatchTimer || this._paused) {\n this._logger.trace(`request queued batchRunning:${this._batchRunning.toString()} hasNextBatchTimer:${(!!this\n ._nextBatchTimer).toString()} paused:${this._paused.toString()}`);\n this._queue.push(reqSpec);\n }\n else {\n void this._runRequestBatch([reqSpec]);\n }\n });\n }\n clear() {\n this._queue = [];\n }\n pause() {\n this._paused = true;\n }\n resume() {\n this._paused = false;\n this._runNextBatch();\n }\n get stats() {\n var _a, _b, _c, _d, _e;\n return {\n lastKnownLimit: (_b = (_a = this._parameters) === null || _a === void 0 ? void 0 : _a.limit) !== null && _b !== void 0 ? _b : null,\n lastKnownRemainingRequests: (_d = (_c = this._parameters) === null || _c === void 0 ? void 0 : _c.remaining) !== null && _d !== void 0 ? _d : null,\n lastKnownResetDate: mapNullable((_e = this._parameters) === null || _e === void 0 ? void 0 : _e.resetsAt, v => new Date(v))\n };\n }\n async _runRequestBatch(reqSpecs) {\n this._logger.trace(`runRequestBatch start specs:${reqSpecs.length}`);\n this._batchRunning = true;\n if (this._parameters) {\n this._logger.debug(`Remaining requests: ${this._parameters.remaining}`);\n }\n this._logger.debug(`Doing ${reqSpecs.length} requests, new queue length is ${this._queue.length}`);\n const promises = reqSpecs.map(async (reqSpec) => {\n const { req, resolve, reject } = reqSpec;\n try {\n const result = await this.doRequest(req);\n const retry = this.needsToRetryAfter(result);\n if (retry !== null) {\n this._queue.unshift(reqSpec);\n this._logger.info(`Retrying after ${retry} ms`);\n throw new RetryAfterError(retry);\n }\n const params = this.getParametersFromResponse(result);\n resolve(result);\n return params;\n }\n catch (e) {\n if (e instanceof RetryAfterError) {\n throw e;\n }\n reject(e);\n return undefined;\n }\n });\n // downleveling problem hack, see https://github.com/es-shims/Promise.allSettled/issues/5\n const settledPromises = await Promise.allSettled(promises);\n const rejectedPromises = settledPromises.filter((p) => p.status === 'rejected');\n const now = Date.now();\n if (rejectedPromises.length) {\n this._logger.trace('runRequestBatch some rejected');\n const retryAt = Math.max(now, ...rejectedPromises.map((p) => p.reason.retryAt));\n const retryAfter = retryAt - now;\n this._logger.warn(`Waiting for ${retryAfter} ms because the rate limit was exceeded`);\n this._nextBatchTimer = setTimeout(() => {\n this._parameters = undefined;\n this._runNextBatch();\n }, retryAfter);\n }\n else {\n this._logger.trace('runRequestBatch none rejected');\n const params = settledPromises\n .filter((p) => p.status === 'fulfilled' && p.value !== undefined)\n .map(p => p.value)\n .reduce((carry, v) => {\n if (!carry) {\n return v;\n }\n // return v.resetsAt > carry.resetsAt ? v : carry;\n return v.remaining < carry.remaining ? v : carry;\n }, undefined);\n this._batchRunning = false;\n if (params) {\n this._parameters = params;\n if (params.resetsAt < now || params.remaining > 0) {\n this._logger.trace('runRequestBatch canRunMore');\n this._runNextBatch();\n }\n else {\n const delay = params.resetsAt - now;\n this._logger.trace(`runRequestBatch delay:${delay}`);\n this._logger.warn(`Waiting for ${delay} ms because the rate limit was reached`);\n this._queue = this._queue.filter(entry => {\n switch (entry.limitReachedBehavior) {\n case 'enqueue': {\n return true;\n }\n case 'null': {\n entry.resolve(null);\n return false;\n }\n case 'throw': {\n entry.reject(new RateLimitReachedError('Request removed from queue because the rate limit was reached'));\n return false;\n }\n default: {\n throw new Error('this should never happen');\n }\n }\n });\n this._nextBatchTimer = setTimeout(() => {\n this._parameters = undefined;\n this._runNextBatch();\n }, delay);\n }\n }\n }\n this._logger.trace('runRequestBatch end');\n }\n _runNextBatch() {\n if (this._paused) {\n return;\n }\n this._logger.trace('runNextBatch start');\n if (this._nextBatchTimer) {\n clearTimeout(this._nextBatchTimer);\n this._nextBatchTimer = undefined;\n }\n const amount = this._parameters ? Math.min(this._parameters.remaining, this._parameters.limit / 10) : 1;\n const reqSpecs = this._queue.splice(0, amount);\n if (reqSpecs.length) {\n void this._runRequestBatch(reqSpecs);\n }\n this._logger.trace('runNextBatch end');\n }\n}\n", "import { createLogger } from '@d-fischer/logger';\nimport { RateLimitReachedError } from \"../errors/RateLimitReachedError.mjs\";\nimport { RateLimiterDestroyedError } from \"../errors/RateLimiterDestroyedError.mjs\";\nexport class PartitionedTimeBasedRateLimiter {\n constructor({ logger, bucketSize, timeFrame, doRequest, getPartitionKey }) {\n this._partitionedQueue = new Map();\n this._usedFromBucket = new Map();\n this._counterTimers = new Set();\n this._paused = false;\n this._destroyed = false;\n this._logger = createLogger({ name: 'rate-limiter', emoji: true, ...logger });\n this._bucketSize = bucketSize;\n this._timeFrame = timeFrame;\n this._callback = doRequest;\n this._partitionKeyCallback = getPartitionKey;\n }\n async request(req, options) {\n return await new Promise((resolve, reject) => {\n var _a, _b;\n if (this._destroyed) {\n reject(new RateLimiterDestroyedError('Rate limiter was destroyed'));\n return;\n }\n const reqSpec = {\n req,\n resolve,\n reject,\n limitReachedBehavior: (_a = options === null || options === void 0 ? void 0 : options.limitReachedBehavior) !== null && _a !== void 0 ? _a : 'enqueue'\n };\n const partitionKey = this._partitionKeyCallback(req);\n const usedFromBucket = (_b = this._usedFromBucket.get(partitionKey)) !== null && _b !== void 0 ? _b : 0;\n if (usedFromBucket >= this._bucketSize || this._paused) {\n switch (reqSpec.limitReachedBehavior) {\n case 'enqueue': {\n const queue = this._getPartitionedQueue(partitionKey);\n queue.push(reqSpec);\n if (usedFromBucket + queue.length >= this._bucketSize) {\n this._logger.warn(`Rate limit of ${this._bucketSize} for ${partitionKey ? `partition ${partitionKey}` : 'default partition'} was reached, waiting for ${this._paused ? 'the limiter to be unpaused' : 'a free bucket entry'}; queue size is ${queue.length}`);\n }\n else {\n this._logger.info(`Enqueueing request for ${partitionKey ? `partition ${partitionKey}` : 'default partition'} because the rate limiter is paused; queue size is ${queue.length}`);\n }\n break;\n }\n case 'null': {\n reqSpec.resolve(null);\n if (this._paused) {\n this._logger.info(`Returning null for request for ${partitionKey ? `partition ${partitionKey}` : 'default partition'} because the rate limiter is paused`);\n }\n else {\n this._logger.warn(`Rate limit of ${this._bucketSize} for ${partitionKey ? `partition ${partitionKey}` : 'default partition'} was reached, dropping request and returning null`);\n }\n break;\n }\n case 'throw': {\n reqSpec.reject(new RateLimitReachedError(`Request dropped because ${this._paused\n ? 'the rate limiter is paused'\n : `the rate limit for ${partitionKey ? `partition ${partitionKey}` : 'default partition'} was reached`}`));\n break;\n }\n default: {\n throw new Error('this should never happen');\n }\n }\n }\n else {\n void this._runRequest(reqSpec, partitionKey);\n }\n });\n }\n clear() {\n this._partitionedQueue.clear();\n }\n pause() {\n this._paused = true;\n }\n resume() {\n this._paused = false;\n for (const partitionKey of this._partitionedQueue.keys()) {\n this._runNextRequest(partitionKey);\n }\n }\n destroy() {\n this._paused = false;\n this._destroyed = true;\n this._counterTimers.forEach(timer => {\n clearTimeout(timer);\n });\n for (const queue of this._partitionedQueue.values()) {\n for (const req of queue) {\n req.reject(new RateLimiterDestroyedError('Rate limiter was destroyed'));\n }\n }\n this._partitionedQueue.clear();\n }\n _getPartitionedQueue(partitionKey) {\n if (this._partitionedQueue.has(partitionKey)) {\n return this._partitionedQueue.get(partitionKey);\n }\n const newQueue = [];\n this._partitionedQueue.set(partitionKey, newQueue);\n return newQueue;\n }\n async _runRequest(reqSpec, partitionKey) {\n var _a;\n const queue = this._getPartitionedQueue(partitionKey);\n this._logger.debug(`doing a request for ${partitionKey ? `partition ${partitionKey}` : 'default partition'}, new queue length is ${queue.length}`);\n this._usedFromBucket.set(partitionKey, ((_a = this._usedFromBucket.get(partitionKey)) !== null && _a !== void 0 ? _a : 0) + 1);\n const { req, resolve, reject } = reqSpec;\n try {\n resolve(await this._callback(req));\n }\n catch (e) {\n reject(e);\n }\n finally {\n const counterTimer = setTimeout(() => {\n this._counterTimers.delete(counterTimer);\n const newUsed = this._usedFromBucket.get(partitionKey) - 1;\n this._usedFromBucket.set(partitionKey, newUsed);\n if (queue.length && newUsed < this._bucketSize) {\n this._runNextRequest(partitionKey);\n }\n }, this._timeFrame);\n this._counterTimers.add(counterTimer);\n }\n }\n _runNextRequest(partitionKey) {\n if (this._paused) {\n return;\n }\n const queue = this._getPartitionedQueue(partitionKey);\n const reqSpec = queue.shift();\n if (reqSpec) {\n void this._runRequest(reqSpec, partitionKey);\n }\n }\n}\n", "export { callTwitchApi, callTwitchApiRaw } from './apiCall.js';\nexport { createBroadcasterQuery } from './helpers/queries.external.js';\nexport { handleTwitchApiResponseError, transformTwitchApiResponse } from './helpers/transform.js';\nexport { HttpStatusCodeError } from './errors/HttpStatusCodeError.js';\n", "import { qsStringify } from '@twurple/common';\nimport { handleTwitchApiResponseError, transformTwitchApiResponse } from './helpers/transform.js';\nimport { getTwitchApiUrl } from './helpers/url.js';\n/**\n * Makes a call to the Twitch API using the given credentials, returning the raw Response object.\n *\n * @param options The configuration of the call.\n * @param clientId The client ID of your application.\n * @param accessToken The access token to call the API with.\n *\n * You need to obtain one using one of the [Twitch OAuth flows](https://dev.twitch.tv/docs/authentication/getting-tokens-oauth/).\n * @param authorizationType The type of Authorization header to send.\n *\n * Defaults to \"Bearer\" for Helix and \"OAuth\" for everything else.\n * @param fetchOptions Additional options to be passed to the `fetch` function.\n */\nexport async function callTwitchApiRaw(options, clientId, accessToken, authorizationType, fetchOptions = {}) {\n const type = options.type ?? 'helix';\n const url = getTwitchApiUrl(options.url, type);\n const params = qsStringify(options.query);\n // eslint-disable-next-line @typescript-eslint/naming-convention\n const headers = new Headers({ Accept: 'application/json' });\n let body = undefined;\n if (options.jsonBody) {\n body = JSON.stringify(options.jsonBody);\n headers.append('Content-Type', 'application/json');\n }\n if (clientId && type !== 'auth') {\n headers.append('Client-ID', clientId);\n }\n if (accessToken) {\n headers.append('Authorization', `${type === 'helix' ? authorizationType ?? 'Bearer' : 'OAuth'} ${accessToken}`);\n }\n const requestOptions = {\n ...fetchOptions,\n method: options.method ?? 'GET',\n headers,\n body,\n };\n return await fetch(`${url}${params}`, requestOptions);\n}\n/**\n * Makes a call to the Twitch API using given credentials.\n *\n * @param options The configuration of the call.\n * @param clientId The client ID of your application.\n * @param accessToken The access token to call the API with.\n *\n * You need to obtain one using one of the [Twitch OAuth flows](https://dev.twitch.tv/docs/authentication/getting-tokens-oauth/).\n * @param authorizationType The type of Authorization header to send.\n *\n * Defaults to \"Bearer\" for Helix and \"OAuth\" for everything else.\n * @param fetchOptions Additional options to be passed to the `fetch` function.\n */\nexport async function callTwitchApi(options, clientId, accessToken, authorizationType, fetchOptions = {}) {\n const response = await callTwitchApiRaw(options, clientId, accessToken, authorizationType, fetchOptions);\n await handleTwitchApiResponseError(response, options);\n return await transformTwitchApiResponse(response);\n}\n", "export { DataObject, getRawData, rawDataSymbol } from './DataObject.js';\nexport { getMockApiPort } from './mockApiPort.js';\nexport { qsStringify } from './qs.js';\nexport { checkRelationAssertion } from './relations.js';\nexport { rtfm } from './rtfm.js';\nexport { HelixExtension } from './extensions/HelixExtension.js';\nexport { CustomError } from './errors/CustomError.js';\nexport { HellFreezesOverError } from './errors/HellFreezesOverError.js';\nexport { RelationAssertionError } from './errors/RelationAssertionError.js';\nexport { extractUserId, extractUserName } from './userResolvers.js';\n", "import { klona } from 'klona';\n/** @private */\nexport const rawDataSymbol = Symbol('twurpleRawData');\n/**\n * Gets the raw data of a data object.\n *\n * @param obj The data object to get the raw data of.\n */\nexport function getRawData(obj) {\n return klona(obj[rawDataSymbol]);\n}\n/** @private */\nexport class DataObject {\n /** @private */ [rawDataSymbol];\n /** @private */\n constructor(data) {\n this[rawDataSymbol] = data;\n }\n}\n", "export function klona(x) {\n\tif (typeof x !== 'object') return x;\n\n\tvar k, tmp, str=Object.prototype.toString.call(x);\n\n\tif (str === '[object Object]') {\n\t\tif (x.constructor !== Object && typeof x.constructor === 'function') {\n\t\t\ttmp = new x.constructor();\n\t\t\tfor (k in x) {\n\t\t\t\tif (x.hasOwnProperty(k) && tmp[k] !== x[k]) {\n\t\t\t\t\ttmp[k] = klona(x[k]);\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\ttmp = {}; // null\n\t\t\tfor (k in x) {\n\t\t\t\tif (k === '__proto__') {\n\t\t\t\t\tObject.defineProperty(tmp, k, {\n\t\t\t\t\t\tvalue: klona(x[k]),\n\t\t\t\t\t\tconfigurable: true,\n\t\t\t\t\t\tenumerable: true,\n\t\t\t\t\t\twritable: true,\n\t\t\t\t\t});\n\t\t\t\t} else {\n\t\t\t\t\ttmp[k] = klona(x[k]);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn tmp;\n\t}\n\n\tif (str === '[object Array]') {\n\t\tk = x.length;\n\t\tfor (tmp=Array(k); k--;) {\n\t\t\ttmp[k] = klona(x[k]);\n\t\t}\n\t\treturn tmp;\n\t}\n\n\tif (str === '[object Set]') {\n\t\ttmp = new Set;\n\t\tx.forEach(function (val) {\n\t\t\ttmp.add(klona(val));\n\t\t});\n\t\treturn tmp;\n\t}\n\n\tif (str === '[object Map]') {\n\t\ttmp = new Map;\n\t\tx.forEach(function (val, key) {\n\t\t\ttmp.set(klona(key), klona(val));\n\t\t});\n\t\treturn tmp;\n\t}\n\n\tif (str === '[object Date]') {\n\t\treturn new Date(+x);\n\t}\n\n\tif (str === '[object RegExp]') {\n\t\ttmp = new RegExp(x.source, x.flags);\n\t\ttmp.lastIndex = x.lastIndex;\n\t\treturn tmp;\n\t}\n\n\tif (str === '[object DataView]') {\n\t\treturn new x.constructor( klona(x.buffer) );\n\t}\n\n\tif (str === '[object ArrayBuffer]') {\n\t\treturn x.slice(0);\n\t}\n\n\t// ArrayBuffer.isView(x)\n\t// ~> `new` bcuz `Buffer.slice` => ref\n\tif (str.slice(-6) === 'Array]') {\n\t\treturn new x.constructor(x);\n\t}\n\n\treturn x;\n}\n", "/** @private */\nexport function getMockApiPort() {\n try {\n return process.env.TWURPLE_MOCK_API_PORT ?? null;\n }\n catch {\n try {\n // @ts-ignore\n return import.meta.env.TWURPLE_MOCK_API_PORT ?? null; // eslint-disable-line @typescript-eslint/no-unsafe-return,@typescript-eslint/no-unsafe-member-access\n }\n catch {\n return null;\n }\n }\n}\n", "export function qsStringify(obj) {\n if (!obj) {\n return '';\n }\n const params = new URLSearchParams();\n for (const [key, value] of Object.entries(obj)) {\n if (value === null) {\n params.append(key, '');\n }\n else if (Array.isArray(value)) {\n for (const v of value) {\n params.append(key, v.toString());\n }\n }\n else if (value !== undefined) {\n params.append(key, value.toString());\n }\n }\n const result = params.toString();\n return result ? `?${result}` : '';\n}\n", "import { RelationAssertionError } from './errors/RelationAssertionError.js';\n/** @private */\nexport function checkRelationAssertion(value) {\n if (value == null) {\n throw new RelationAssertionError();\n }\n return value;\n}\n", "import { CustomError } from './CustomError.js';\n/**\n * Thrown when a relation that is expected to never be null does return null.\n */\nexport class RelationAssertionError extends CustomError {\n constructor() {\n super('Relation returned null - this may be a library bug or a race condition in your own code');\n }\n}\n", "/** @private */\nexport class CustomError extends Error {\n constructor(message, options) {\n super(message, options);\n // restore prototype chain\n Object.setPrototypeOf(this, new.target.prototype);\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n Error.captureStackTrace?.(this, new.target.constructor);\n }\n get name() {\n return this.constructor.name;\n }\n}\n", "/** @private */\nexport function rtfm(pkg, name, idKey) {\n return clazz => {\n const fn = idKey\n ? function () {\n // eslint-disable-next-line @typescript-eslint/restrict-template-expressions\n return `[${name}#${this[idKey]} - please check https://twurple.js.org/reference/${pkg}/classes/${name}.html for available properties]`;\n }\n : function () {\n return `[${name} - please check https://twurple.js.org/reference/${pkg}/classes/${name}.html for available properties]`;\n };\n Object.defineProperty(clazz.prototype, Symbol.for('nodejs.util.inspect.custom'), {\n value: fn,\n enumerable: false,\n });\n };\n}\n", "import { __decorate } from \"tslib\";\nimport { DataObject, rawDataSymbol } from '../DataObject.js';\nimport { rtfm } from '../rtfm.js';\n/**\n * A Twitch Extension.\n */\nlet HelixExtension = class HelixExtension extends DataObject {\n /**\n * The name of the extension's author.\n */\n get authorName() {\n return this[rawDataSymbol].author_name;\n }\n /**\n * Whether bits are enabled for the extension.\n */\n get bitsEnabled() {\n return this[rawDataSymbol].bits_enabled;\n }\n /**\n * Whether the extension can be installed.\n */\n get installable() {\n return this[rawDataSymbol].can_install;\n }\n /**\n * The location of the extension's configuration.\n */\n get configurationLocation() {\n return this[rawDataSymbol].configuration_location;\n }\n /**\n * The extension's description.\n */\n get description() {\n return this[rawDataSymbol].description;\n }\n /**\n * The URL of the extension's terms of service.\n */\n get tosUrl() {\n return this[rawDataSymbol].eula_tos_url;\n }\n /**\n * Whether the extension has support for sending chat messages.\n */\n get hasChatSupport() {\n return this[rawDataSymbol].has_chat_support;\n }\n /**\n * The URL of the extension's default sized icon.\n */\n get iconUrl() {\n return this[rawDataSymbol].icon_url;\n }\n /**\n * Gets the URL of the extension's icon in the given size.\n *\n * @param size The size of the icon.\n */\n getIconUrl(size) {\n return this[rawDataSymbol].icon_urls[size];\n }\n /**\n * The extension's ID.\n */\n get id() {\n return this[rawDataSymbol].id;\n }\n /**\n * The extension's name.\n */\n get name() {\n return this[rawDataSymbol].name;\n }\n /**\n * The URL of the extension's privacy policy.\n */\n get privacyPolicyUrl() {\n return this[rawDataSymbol].privacy_policy_url;\n }\n /**\n * Whether the extension requests its users to share their identity with it.\n */\n get requestsIdentityLink() {\n return this[rawDataSymbol].request_identity_link;\n }\n /**\n * The URLs of the extension's screenshots.\n */\n get screenshotUrls() {\n return this[rawDataSymbol].screenshot_urls;\n }\n /**\n * The extension's activity state.\n */\n get state() {\n return this[rawDataSymbol].state;\n }\n /**\n * The extension's level of support for subscriptions.\n */\n get subscriptionsSupportLevel() {\n return this[rawDataSymbol].subscriptions_support_level;\n }\n /**\n * The extension's feature summary.\n */\n get summary() {\n return this[rawDataSymbol].summary;\n }\n /**\n * The extension's support email address.\n */\n get supportEmail() {\n return this[rawDataSymbol].support_email;\n }\n /**\n * The extension's version.\n */\n get version() {\n return this[rawDataSymbol].version;\n }\n /**\n * The extension's feature summary for viewers.\n */\n get viewerSummary() {\n return this[rawDataSymbol].viewer_summary;\n }\n /**\n * The extension's feature summary for viewers.\n *\n * @deprecated Use `viewerSummary` instead.\n */\n get viewerSummery() {\n return this[rawDataSymbol].viewer_summary;\n }\n /**\n * The extension's allowed configuration URLs.\n */\n get allowedConfigUrls() {\n return this[rawDataSymbol].allowlisted_config_urls;\n }\n /**\n * The extension's allowed panel URLs.\n */\n get allowedPanelUrls() {\n return this[rawDataSymbol].allowlisted_panel_urls;\n }\n /**\n * The URL shown when a viewer opens the extension on a mobile device.\n *\n * If the extension does not have a mobile view, this is null.\n */\n get mobileViewerUrl() {\n return this[rawDataSymbol].views.mobile?.viewer_url ?? null;\n }\n /**\n * The URL shown to the viewer when the extension is shown as a panel.\n *\n * If the extension does not have a panel view, this is null.\n */\n get panelViewerUrl() {\n return this[rawDataSymbol].views.panel?.viewer_url ?? null;\n }\n /**\n * The height of the extension panel.\n *\n * If the extension does not have a panel view, this is null.\n */\n get panelHeight() {\n return this[rawDataSymbol].views.panel?.height ?? null;\n }\n /**\n * Whether the extension can link to external content from its panel view.\n *\n * If the extension does not have a panel view, this is null.\n */\n get panelCanLinkExternalContent() {\n return this[rawDataSymbol].views.panel?.can_link_external_content ?? null;\n }\n /**\n * The URL shown to the viewer when the extension is shown as a video overlay.\n *\n * If the extension does not have a overlay view, this is null.\n */\n get overlayViewerUrl() {\n return this[rawDataSymbol].views.video_overlay?.viewer_url ?? null;\n }\n /**\n * Whether the extension can link to external content from its overlay view.\n *\n * If the extension does not have a overlay view, this is null.\n */\n get overlayCanLinkExternalContent() {\n return this[rawDataSymbol].views.video_overlay?.can_link_external_content ?? null;\n }\n /**\n * The URL shown to the viewer when the extension is shown as a video component.\n *\n * If the extension does not have a component view, this is null.\n */\n get componentViewerUrl() {\n return this[rawDataSymbol].views.component?.viewer_url ?? null;\n }\n /**\n * The aspect width of the extension's component view.\n *\n * If the extension does not have a component view, this is null.\n */\n get componentAspectWidth() {\n return this[rawDataSymbol].views.component?.aspect_width ?? null;\n }\n /**\n * The aspect height of the extension's component view.\n *\n * If the extension does not have a component view, this is null.\n */\n get componentAspectHeight() {\n return this[rawDataSymbol].views.component?.aspect_height ?? null;\n }\n /**\n * The horizontal aspect ratio of the extension's component view.\n *\n * If the extension does not have a component view, this is null.\n */\n get componentAspectRatioX() {\n return this[rawDataSymbol].views.component?.aspect_ratio_x ?? null;\n }\n /**\n * The vertical aspect ratio of the extension's component view.\n *\n * If the extension does not have a component view, this is null.\n */\n get componentAspectRatioY() {\n return this[rawDataSymbol].views.component?.aspect_ratio_y ?? null;\n }\n /**\n * Whether the extension's component view should automatically scale.\n *\n * If the extension does not have a component view, this is null.\n */\n get componentAutoScales() {\n return this[rawDataSymbol].views.component?.autoscale ?? null;\n }\n /**\n * The base width of the extension's component view to use for scaling.\n *\n * If the extension does not have a component view, this is null.\n */\n get componentScalePixels() {\n return this[rawDataSymbol].views.component?.scale_pixels ?? null;\n }\n /**\n * The target height of the extension's component view.\n *\n * If the extension does not have a component view, this is null.\n */\n get componentTargetHeight() {\n return this[rawDataSymbol].views.component?.target_height ?? null;\n }\n /**\n * The size of the extension's component view.\n *\n * If the extension does not have a component view, this is null.\n */\n get componentSize() {\n return this[rawDataSymbol].views.component?.size ?? null;\n }\n /**\n * Whether zooming is enabled for the extension's component view.\n *\n * If the extension does not have a component view, this is null.\n */\n get componentZoom() {\n return this[rawDataSymbol].views.component?.zoom ?? null;\n }\n /**\n * The zoom pixels of the extension's component view.\n *\n * If the extension does not have a component view, this is null.\n */\n get componentZoomPixels() {\n return this[rawDataSymbol].views.component?.zoom_pixels ?? null;\n }\n /**\n * Whether the extension can link to external content from its component view.\n *\n * If the extension does not have a component view, this is null.\n */\n get componentCanLinkExternalContent() {\n return this[rawDataSymbol].views.component?.can_link_external_content ?? null;\n }\n /**\n * The URL shown to the viewer when the extension's configuration page is shown.\n *\n * If the extension does not have a config view, this is null.\n */\n get configViewerUrl() {\n return this[rawDataSymbol].views.config?.viewer_url ?? null;\n }\n /**\n * Whether the extension can link to external content from its config view.\n *\n * If the extension does not have a config view, this is null.\n */\n get configCanLinkExternalContent() {\n return this[rawDataSymbol].views.config?.can_link_external_content ?? null;\n }\n};\nHelixExtension = __decorate([\n rtfm('api', 'HelixExtension', 'id')\n], HelixExtension);\nexport { HelixExtension };\n", "import { CustomError } from './CustomError.js';\n/**\n * These are the kind of errors that should never happen.\n *\n * If you see one thrown, please file a bug in the GitHub issue tracker.\n */\nexport class HellFreezesOverError extends CustomError {\n constructor(message) {\n super(`${message} - this should never happen, please file a bug in the GitHub issue tracker`);\n }\n}\n", "/**\n * Extracts the user ID from an argument that is possibly an object containing that ID.\n *\n * @param user The user ID or object.\n */\nexport function extractUserId(user) {\n if (typeof user === 'string') {\n return user;\n }\n if (typeof user === 'number') {\n return user.toString(10);\n }\n return user.id;\n}\n/**\n * Extracts the username from an argument that is possibly an object containing that name.\n *\n * @param user The username or object.\n */\nexport function extractUserName(user) {\n return typeof user === 'string' ? user : user.name;\n}\n", "import { qsStringify } from '@twurple/common';\nimport { HttpStatusCodeError } from '../errors/HttpStatusCodeError.js';\n/** @private */\nexport async function handleTwitchApiResponseError(response, options) {\n if (!response.ok) {\n const isJson = response.headers.get('Content-Type') === 'application/json';\n const text = isJson ? JSON.stringify(await response.json(), null, 2) : await response.text();\n const params = qsStringify(options.query);\n const fullUrl = `${options.url}${params}`;\n throw new HttpStatusCodeError(response.status, response.statusText, fullUrl, options.method ?? 'GET', text, isJson);\n }\n}\n/** @private */\nexport async function transformTwitchApiResponse(response) {\n if (response.status === 204) {\n return undefined; // oof\n }\n const text = await response.text();\n if (!text) {\n return undefined; // mega oof - Twitch doesn't return a response when it should\n }\n return JSON.parse(text);\n}\n", "import { CustomError } from '@twurple/common';\n/**\n * Thrown whenever a HTTP error occurs. Some HTTP errors are handled in the library when they're expected.\n */\nexport class HttpStatusCodeError extends CustomError {\n _statusCode;\n _url;\n _method;\n _body;\n /** @private */\n constructor(_statusCode, statusText, _url, _method, _body, isJson) {\n super(`Encountered HTTP status code ${_statusCode}: ${statusText}\\n\\nURL: ${_url}\\nMethod: ${_method}\\nBody:\\n${!isJson && _body.length > 150 ? `${_body.slice(0, 147)}...` : _body}`);\n this._statusCode = _statusCode;\n this._url = _url;\n this._method = _method;\n this._body = _body;\n }\n /**\n * The HTTP status code of the error.\n */\n get statusCode() {\n return this._statusCode;\n }\n /**\n * The URL that was requested.\n */\n get url() {\n return this._url;\n }\n /**\n * The HTTP method that was used for the request.\n */\n get method() {\n return this._method;\n }\n /**\n * The body that was used for the request, as a string.\n */\n get body() {\n return this._body;\n }\n}\n", "import { getMockApiPort } from '@twurple/common';\n/** @internal */\nexport function getTwitchApiUrl(url, type) {\n const mockServerPort = getMockApiPort();\n switch (type) {\n case 'helix': {\n const unprefixedUrl = url.replace(/^\\//, '');\n return mockServerPort\n ? unprefixedUrl === 'eventsub/subscriptions'\n ? `http://localhost:${mockServerPort}/${unprefixedUrl}`\n : `http://localhost:${mockServerPort}/mock/${unprefixedUrl}`\n : `https://api.twitch.tv/helix/${unprefixedUrl}`;\n }\n case 'auth': {\n const unprefixedUrl = url.replace(/^\\//, '');\n return mockServerPort\n ? `http://localhost:${mockServerPort}/auth/${unprefixedUrl}`\n : `https://id.twitch.tv/oauth2/${unprefixedUrl}`;\n }\n case 'custom':\n return url;\n default:\n return url; // wat\n }\n}\n", "import { extractUserId } from '@twurple/common';\nexport function createBroadcasterQuery(user) {\n return {\n broadcaster_id: extractUserId(user),\n };\n}\n", "import { CustomError } from '@twurple/common';\n/**\n * Thrown whenever you try using invalid values in the client configuration.\n */\nexport class ConfigError extends CustomError {\n}\n", "import { ResponseBasedRateLimiter } from '@d-fischer/rate-limiter';\nimport { callTwitchApiRaw } from '@twurple/api-call';\n/** @internal */\nexport class HelixRateLimiter extends ResponseBasedRateLimiter {\n async doRequest({ options, clientId, accessToken, authorizationType, fetchOptions, }) {\n return await callTwitchApiRaw(options, clientId, accessToken, authorizationType, fetchOptions);\n }\n needsToRetryAfter(res) {\n if (res.status === 429 &&\n (!res.headers.has('ratelimit-remaining') || Number(res.headers.get('ratelimit-remaining')) === 0)) {\n return +res.headers.get('ratelimit-reset') * 1000 - Date.now();\n }\n return null;\n }\n getParametersFromResponse(res) {\n const { headers } = res;\n return {\n limit: +headers.get('ratelimit-limit'),\n remaining: +headers.get('ratelimit-remaining'),\n resetsAt: +headers.get('ratelimit-reset') * 1000,\n };\n }\n}\n", "import { __decorate } from \"tslib\";\nimport { Cacheable, CachedGetter } from '@d-fischer/cache-decorators';\nimport { ResponseBasedRateLimiter } from '@d-fischer/rate-limiter';\nimport { promiseWithResolvers } from '@d-fischer/shared-utils';\nimport { EventEmitter } from '@d-fischer/typed-event-emitter';\nimport { callTwitchApi, callTwitchApiRaw, handleTwitchApiResponseError, HttpStatusCodeError, transformTwitchApiResponse, } from '@twurple/api-call';\nimport { accessTokenIsExpired, InvalidTokenError, TokenInfo, } from '@twurple/auth';\nimport { HellFreezesOverError, rtfm } from '@twurple/common';\nimport * as retry from 'retry';\nimport { HelixBitsApi } from '../endpoints/bits/HelixBitsApi.js';\nimport { HelixChannelApi } from '../endpoints/channel/HelixChannelApi.js';\nimport { HelixChannelPointsApi } from '../endpoints/channelPoints/HelixChannelPointsApi.js';\nimport { HelixCharityApi } from '../endpoints/charity/HelixCharityApi.js';\nimport { HelixChatApi } from '../endpoints/chat/HelixChatApi.js';\nimport { HelixClipApi } from '../endpoints/clip/HelixClipApi.js';\nimport { HelixContentClassificationLabelApi } from '../endpoints/contentClassificationLabels/HelixContentClassificationLabelApi.js';\nimport { HelixEntitlementApi } from '../endpoints/entitlements/HelixEntitlementApi.js';\nimport { HelixEventSubApi } from '../endpoints/eventSub/HelixEventSubApi.js';\nimport { HelixExtensionsApi } from '../endpoints/extensions/HelixExtensionsApi.js';\nimport { HelixGameApi } from '../endpoints/game/HelixGameApi.js';\nimport { HelixGoalApi } from '../endpoints/goals/HelixGoalApi.js';\nimport { HelixHypeTrainApi } from '../endpoints/hypeTrain/HelixHypeTrainApi.js';\nimport { HelixModerationApi } from '../endpoints/moderation/HelixModerationApi.js';\nimport { HelixPollApi } from '../endpoints/poll/HelixPollApi.js';\nimport { HelixPredictionApi } from '../endpoints/prediction/HelixPredictionApi.js';\nimport { HelixRaidApi } from '../endpoints/raids/HelixRaidApi.js';\nimport { HelixScheduleApi } from '../endpoints/schedule/HelixScheduleApi.js';\nimport { HelixSearchApi } from '../endpoints/search/HelixSearchApi.js';\nimport { HelixStreamApi } from '../endpoints/stream/HelixStreamApi.js';\nimport { HelixSubscriptionApi } from '../endpoints/subscriptions/HelixSubscriptionApi.js';\nimport { HelixTeamApi } from '../endpoints/team/HelixTeamApi.js';\nimport { HelixUserApi } from '../endpoints/user/HelixUserApi.js';\nimport { HelixVideoApi } from '../endpoints/video/HelixVideoApi.js';\nimport { HelixWhisperApi } from '../endpoints/whisper/HelixWhisperApi.js';\nimport { ApiReportedRequest } from '../reporting/ApiReportedRequest.js';\n/** @private */\nlet BaseApiClient = class BaseApiClient extends EventEmitter {\n _config;\n _logger;\n _rateLimiter;\n onRequest = this.registerEvent();\n /** @internal */\n constructor(config, logger, rateLimiter) {\n super();\n this._config = config;\n this._logger = logger;\n this._rateLimiter = rateLimiter;\n }\n /**\n * Requests scopes from the auth provider for the given user.\n *\n * @param user The user to request scopes for.\n * @param scopes The scopes to request.\n */\n async requestScopesForUser(user, scopes) {\n await this._config.authProvider.getAccessTokenForUser(user, ...scopes.map(scope => [scope]));\n }\n /**\n * Gets information about your access token.\n */\n async getTokenInfo() {\n try {\n const data = await this.callApi({ type: 'auth', url: 'validate' });\n return new TokenInfo(data);\n }\n catch (e) {\n if (e instanceof HttpStatusCodeError && e.statusCode === 401) {\n throw new InvalidTokenError({ cause: e });\n }\n throw e;\n }\n }\n /**\n * Makes a call to the Twitch API using your access token.\n *\n * @param options The configuration of the call.\n */\n async callApi(options) {\n const { authProvider } = this._config;\n const shouldAuth = options.auth ?? true;\n if (!shouldAuth) {\n return await callTwitchApi(options, authProvider.clientId, undefined, undefined, this._config.fetchOptions);\n }\n let forceUser = false;\n if (options.forceType) {\n switch (options.forceType) {\n case 'app': {\n if (!authProvider.getAppAccessToken) {\n throw new Error('Tried to make an API call that requires an app access token but your auth provider does not support that');\n }\n const accessToken = await authProvider.getAppAccessToken();\n return await this._callApiUsingInitialToken(options, accessToken);\n }\n case 'user': {\n forceUser = true;\n break;\n }\n default: {\n throw new HellFreezesOverError(`Unknown forced token type: ${options.forceType}`);\n }\n }\n }\n if (options.scopes) {\n forceUser = true;\n }\n if (forceUser) {\n const contextUserId = options.canOverrideScopedUserContext\n ? this._getUserIdFromRequestContext(options.userId)\n : options.userId;\n if (!contextUserId) {\n throw new Error('Tried to make an API call with a user context but no context user ID');\n }\n const accessToken = await authProvider.getAccessTokenForUser(contextUserId, options.scopes);\n if (!accessToken) {\n throw new Error(`Tried to make an API call with a user context for user ID ${contextUserId} but no token was found`);\n }\n if (accessTokenIsExpired(accessToken) && authProvider.refreshAccessTokenForUser) {\n const newAccessToken = await authProvider.refreshAccessTokenForUser(contextUserId);\n return await this._callApiUsingInitialToken(options, newAccessToken, true);\n }\n return await this._callApiUsingInitialToken(options, accessToken);\n }\n const requestContextUserId = this._getUserIdFromRequestContext(options.userId);\n const accessToken = requestContextUserId === null\n ? await authProvider.getAnyAccessToken()\n : await authProvider.getAnyAccessToken(requestContextUserId ?? options.userId);\n if (accessTokenIsExpired(accessToken) && accessToken.userId && authProvider.refreshAccessTokenForUser) {\n const newAccessToken = await authProvider.refreshAccessTokenForUser(accessToken.userId);\n return await this._callApiUsingInitialToken(options, newAccessToken, true);\n }\n return await this._callApiUsingInitialToken(options, accessToken);\n }\n /**\n * The Helix bits API methods.\n */\n get bits() {\n return new HelixBitsApi(this);\n }\n /**\n * The Helix channels API methods.\n */\n get channels() {\n return new HelixChannelApi(this);\n }\n /**\n * The Helix channel points API methods.\n */\n get channelPoints() {\n return new HelixChannelPointsApi(this);\n }\n /**\n * The Helix charity API methods.\n */\n get charity() {\n return new HelixCharityApi(this);\n }\n /**\n * The Helix chat API methods.\n */\n get chat() {\n return new HelixChatApi(this);\n }\n /**\n * The Helix clips API methods.\n */\n get clips() {\n return new HelixClipApi(this);\n }\n /**\n * The Helix content classification label API methods.\n */\n get contentClassificationLabels() {\n return new HelixContentClassificationLabelApi(this);\n }\n /**\n * The Helix entitlement API methods.\n */\n get entitlements() {\n return new HelixEntitlementApi(this);\n }\n /**\n * The Helix EventSub API methods.\n */\n get eventSub() {\n return new HelixEventSubApi(this);\n }\n /**\n * The Helix extensions API methods.\n */\n get extensions() {\n return new HelixExtensionsApi(this);\n }\n /**\n * The Helix game API methods.\n */\n get games() {\n return new HelixGameApi(this);\n }\n /**\n * The Helix Hype Train API methods.\n */\n get hypeTrain() {\n return new HelixHypeTrainApi(this);\n }\n /**\n * The Helix goal API methods.\n */\n get goals() {\n return new HelixGoalApi(this);\n }\n /**\n * The Helix moderation API methods.\n */\n get moderation() {\n return new HelixModerationApi(this);\n }\n /**\n * The Helix poll API methods.\n */\n get polls() {\n return new HelixPollApi(this);\n }\n /**\n * The Helix prediction API methods.\n */\n get predictions() {\n return new HelixPredictionApi(this);\n }\n /**\n * The Helix raid API methods.\n */\n get raids() {\n return new HelixRaidApi(this);\n }\n /**\n * The Helix schedule API methods.\n */\n get schedule() {\n return new HelixScheduleApi(this);\n }\n /**\n * The Helix search API methods.\n */\n get search() {\n return new HelixSearchApi(this);\n }\n /**\n * The Helix stream API methods.\n */\n get streams() {\n return new HelixStreamApi(this);\n }\n /**\n * The Helix subscription API methods.\n */\n get subscriptions() {\n return new HelixSubscriptionApi(this);\n }\n /**\n * The Helix team API methods.\n */\n get teams() {\n return new HelixTeamApi(this);\n }\n /**\n * The Helix user API methods.\n */\n get users() {\n return new HelixUserApi(this);\n }\n /**\n * The Helix video API methods.\n */\n get videos() {\n return new HelixVideoApi(this);\n }\n /**\n * The API methods that deal with whispers.\n */\n get whispers() {\n return new HelixWhisperApi(this);\n }\n /**\n * Statistics on the rate limiter for the Helix API.\n */\n get rateLimiterStats() {\n if (this._rateLimiter instanceof ResponseBasedRateLimiter) {\n return this._rateLimiter.stats;\n }\n return null;\n }\n /** @private */\n get _authProvider() {\n return this._config.authProvider;\n }\n /** @internal */\n get _batchDelay() {\n return this._config.batchDelay ?? 0;\n }\n // null means app access, undefined means none specified\n /** @internal */\n _getUserIdFromRequestContext(contextUserId) {\n return contextUserId;\n }\n async _callApiUsingInitialToken(options, accessToken, wasRefreshed = false) {\n const { authProvider } = this._config;\n const { authorizationType } = authProvider;\n let response = await this._callApiInternal(options, authProvider.clientId, accessToken.accessToken, authorizationType);\n if (response.status === 401 && !wasRefreshed) {\n if (accessToken.userId) {\n if (authProvider.refreshAccessTokenForUser) {\n const token = await authProvider.refreshAccessTokenForUser(accessToken.userId);\n response = await this._callApiInternal(options, authProvider.clientId, token.accessToken, authorizationType);\n }\n }\n else if (authProvider.getAppAccessToken) {\n const token = await authProvider.getAppAccessToken(true);\n response = await this._callApiInternal(options, authProvider.clientId, token.accessToken, authorizationType);\n }\n }\n this.emit(this.onRequest, new ApiReportedRequest(options, response.status, accessToken.userId ?? null));\n await handleTwitchApiResponseError(response, options);\n return await transformTwitchApiResponse(response);\n }\n async _callApiInternal(options, clientId, accessToken, authorizationType) {\n const { fetchOptions } = this._config;\n const type = options.type ?? 'helix';\n this._logger.debug(`Calling ${type} API: ${options.method ?? 'GET'} ${options.url}`);\n this._logger.trace(`Query: ${JSON.stringify(options.query)}`);\n if (options.jsonBody) {\n this._logger.trace(`Request body: ${JSON.stringify(options.jsonBody)}`);\n }\n const op = retry.operation({\n retries: 3,\n minTimeout: 500,\n factor: 2,\n });\n const { promise, resolve, reject } = promiseWithResolvers();\n op.attempt(async () => {\n try {\n const response = type === 'helix'\n ? await this._rateLimiter.request({\n options,\n clientId,\n accessToken,\n authorizationType,\n fetchOptions,\n })\n : await callTwitchApiRaw(options, clientId, accessToken, authorizationType, fetchOptions);\n if (!response.ok && response.status >= 500 && response.status < 600) {\n await handleTwitchApiResponseError(response, options);\n }\n resolve(response);\n }\n catch (e) {\n if (op.retry(e)) {\n return;\n }\n reject(op.mainError());\n }\n });\n const result = await promise;\n this._logger.debug(`Called ${type} API: ${options.method ?? 'GET'} ${options.url} - result: ${result.status}`);\n return result;\n }\n};\n__decorate([\n CachedGetter()\n], BaseApiClient.prototype, \"bits\", null);\n__decorate([\n CachedGetter()\n], BaseApiClient.prototype, \"channels\", null);\n__decorate([\n CachedGetter()\n], BaseApiClient.prototype, \"channelPoints\", null);\n__decorate([\n CachedGetter()\n], BaseApiClient.prototype, \"charity\", null);\n__decorate([\n CachedGetter()\n], BaseApiClient.prototype, \"chat\", null);\n__decorate([\n CachedGetter()\n], BaseApiClient.prototype, \"clips\", null);\n__decorate([\n CachedGetter()\n], BaseApiClient.prototype, \"contentClassificationLabels\", null);\n__decorate([\n CachedGetter()\n], BaseApiClient.prototype, \"entitlements\", null);\n__decorate([\n CachedGetter()\n], BaseApiClient.prototype, \"eventSub\", null);\n__decorate([\n CachedGetter()\n], BaseApiClient.prototype, \"extensions\", null);\n__decorate([\n CachedGetter()\n], BaseApiClient.prototype, \"games\", null);\n__decorate([\n CachedGetter()\n], BaseApiClient.prototype, \"hypeTrain\", null);\n__decorate([\n CachedGetter()\n], BaseApiClient.prototype, \"goals\", null);\n__decorate([\n CachedGetter()\n], BaseApiClient.prototype, \"moderation\", null);\n__decorate([\n CachedGetter()\n], BaseApiClient.prototype, \"polls\", null);\n__decorate([\n CachedGetter()\n], BaseApiClient.prototype, \"predictions\", null);\n__decorate([\n CachedGetter()\n], BaseApiClient.prototype, \"raids\", null);\n__decorate([\n CachedGetter()\n], BaseApiClient.prototype, \"schedule\", null);\n__decorate([\n CachedGetter()\n], BaseApiClient.prototype, \"search\", null);\n__decorate([\n CachedGetter()\n], BaseApiClient.prototype, \"streams\", null);\n__decorate([\n CachedGetter()\n], BaseApiClient.prototype, \"subscriptions\", null);\n__decorate([\n CachedGetter()\n], BaseApiClient.prototype, \"teams\", null);\n__decorate([\n CachedGetter()\n], BaseApiClient.prototype, \"users\", null);\n__decorate([\n CachedGetter()\n], BaseApiClient.prototype, \"videos\", null);\n__decorate([\n CachedGetter()\n], BaseApiClient.prototype, \"whispers\", null);\nBaseApiClient = __decorate([\n Cacheable,\n rtfm('api', 'ApiClient')\n], BaseApiClient);\nexport { BaseApiClient };\n", "export { Cacheable } from \"./decorators/Cacheable.mjs\";\nexport { Cached } from \"./decorators/Cached.mjs\";\nexport { CachedGetter } from \"./decorators/CachedGetter.mjs\";\nexport { ClearsCache } from \"./decorators/ClearsCache.mjs\";\nexport { createCacheKey } from \"./utils/createCacheKey.mjs\";\n", "import { createCacheKey } from \"../utils/createCacheKey.mjs\";\nconst cacheSymbol = Symbol('cache');\nexport function Cacheable(cls) {\n var _a, _b;\n return _b = class extends cls {\n constructor() {\n super(...arguments);\n this[_a] = new Map();\n }\n getFromCache(cacheKey) {\n this._cleanCache();\n if (this[cacheSymbol].has(cacheKey)) {\n const entry = this[cacheSymbol].get(cacheKey);\n if (entry) {\n return entry.value;\n }\n }\n return undefined;\n }\n setCache(cacheKey, value, timeInSeconds) {\n this[cacheSymbol].set(cacheKey, {\n value,\n expires: Date.now() + timeInSeconds * 1000\n });\n }\n removeFromCache(cacheKey, prefix) {\n const internalCacheKey = this._getInternalCacheKey(cacheKey, prefix);\n if (prefix) {\n this[cacheSymbol].forEach((val, key) => {\n if (key.startsWith(internalCacheKey)) {\n this[cacheSymbol].delete(key);\n }\n });\n }\n else {\n this[cacheSymbol].delete(internalCacheKey);\n }\n }\n _cleanCache() {\n const now = Date.now();\n this[cacheSymbol].forEach((val, key) => {\n if (val.expires < now) {\n this[cacheSymbol].delete(key);\n }\n });\n }\n _getInternalCacheKey(cacheKey, prefix) {\n if (typeof cacheKey === 'string') {\n let internalCacheKey = cacheKey;\n if (!internalCacheKey.endsWith('/')) {\n internalCacheKey += '/';\n }\n return internalCacheKey;\n }\n else {\n const propName = cacheKey.shift();\n return createCacheKey(propName, cacheKey, prefix);\n }\n }\n },\n _a = cacheSymbol,\n _b;\n}\n", "function createSingleCacheKey(param) {\n // noinspection FallThroughInSwitchStatementJS\n switch (typeof param) {\n case 'undefined': {\n return '';\n }\n case 'object': {\n if (param === null) {\n return '';\n }\n if ('cacheKey' in param) {\n return param.cacheKey;\n }\n const objKey = JSON.stringify(param);\n if (objKey !== '{}') {\n return objKey;\n }\n }\n // fallthrough\n default: {\n return param.toString();\n }\n }\n}\nexport function createCacheKey(propName, params, prefix) {\n return [propName, ...params.map(createSingleCacheKey)].join('/') + (prefix ? '/' : '');\n}\n", "import { createCacheKey } from \"../utils/createCacheKey.mjs\";\nexport function CachedGetter(timeInSeconds = Infinity) {\n return function (target, propName, descriptor) {\n if (descriptor.get) {\n // eslint-disable-next-line @typescript-eslint/unbound-method\n const origFn = descriptor.get;\n descriptor.get = function () {\n const cacheKey = createCacheKey(propName, []);\n const cachedValue = this.getFromCache(cacheKey);\n if (cachedValue) {\n return cachedValue;\n }\n const result = origFn.call(this);\n this.setCache(cacheKey, result, timeInSeconds);\n return result;\n };\n }\n return descriptor;\n };\n}\n", "export { EventEmitter } from \"./EventEmitter.mjs\";\nexport { Listener } from \"./Listener.mjs\";\n", "import { Listener } from \"./Listener.mjs\";\nexport class EventEmitter {\n constructor() {\n this._eventListeners = new Map();\n this._internalEventListeners = new Map();\n }\n on(event, listener) {\n return this._addListener(false, event, listener);\n }\n addListener(event, listener) {\n return this._addListener(false, event, listener);\n }\n removeListener(idOrEvent, listener) {\n this._removeListener(false, idOrEvent, listener);\n }\n registerEvent() {\n const eventBinder = (handler) => this.addListener(eventBinder, handler);\n return eventBinder;\n }\n emit(event, ...args) {\n if (this._eventListeners.has(event)) {\n for (const listener of this._eventListeners.get(event)) {\n listener(...args);\n }\n }\n if (this._internalEventListeners.has(event)) {\n for (const listener of this._internalEventListeners.get(event)) {\n listener(...args);\n }\n }\n }\n registerInternalEvent() {\n const eventBinder = (handler) => this.addInternalListener(eventBinder, handler);\n return eventBinder;\n }\n addInternalListener(event, listener) {\n return this._addListener(true, event, listener);\n }\n removeInternalListener(idOrEvent, listener) {\n this._removeListener(true, idOrEvent, listener);\n }\n _addListener(internal, event, listener) {\n const listenerMap = internal ? this._eventListeners : this._internalEventListeners;\n if (listenerMap.has(event)) {\n listenerMap.get(event).push(listener);\n }\n else {\n listenerMap.set(event, [listener]);\n }\n return new Listener(this, event, listener, internal);\n }\n _removeListener(internal, idOrEvent, listener) {\n const listenerMap = internal ? this._eventListeners : this._internalEventListeners;\n if (!idOrEvent) {\n listenerMap.clear();\n }\n else if (typeof idOrEvent === 'object') {\n const id = idOrEvent;\n this._removeListener(id._internal, id.event, id.listener);\n }\n else {\n const event = idOrEvent;\n if (listenerMap.has(event)) {\n if (listener) {\n const listeners = listenerMap.get(event);\n let idx = 0;\n while ((idx = listeners.indexOf(listener)) !== -1) {\n listeners.splice(idx, 1);\n }\n }\n else {\n listenerMap.delete(event);\n }\n }\n }\n }\n}\n", "export class Listener {\n /** @private */\n constructor(owner, event, listener, \n /** @private */ _internal = false) {\n this.owner = owner;\n this.event = event;\n this.listener = listener;\n this._internal = _internal;\n }\n unbind() {\n this.owner.removeListener(this);\n }\n}\n", "export { accessTokenIsExpired, getExpiryDateOfAccessToken } from './AccessToken.js';\nexport { exchangeCode, getAppToken, getTokenInfo, getValidTokenFromProviderForUser, getValidTokenFromProviderForIntent, refreshUserToken, revokeToken, } from './helpers.js';\nexport { TokenFetcher } from './TokenFetcher.js';\nexport { TokenInfo } from './TokenInfo.js';\nexport { AppTokenAuthProvider } from './providers/AppTokenAuthProvider.js';\nexport { RefreshingAuthProvider } from './providers/RefreshingAuthProvider.js';\nexport { StaticAuthProvider } from './providers/StaticAuthProvider.js';\nexport { CachedRefreshFailureError } from './errors/CachedRefreshFailureError.js';\nexport { IntermediateUserRemovalError } from './errors/IntermediateUserRemovalError.js';\nexport { InvalidTokenError } from './errors/InvalidTokenError.js';\nexport { InvalidTokenTypeError } from './errors/InvalidTokenTypeError.js';\nexport { UnknownIntentError } from './errors/UnknownIntentError.js';\n", "import { mapNullable } from '@d-fischer/shared-utils';\n// one minute\nconst EXPIRY_GRACE_PERIOD = 60000;\nfunction getExpiryMillis(token) {\n return mapNullable(token.expiresIn, _ => token.obtainmentTimestamp + _ * 1000 - EXPIRY_GRACE_PERIOD);\n}\n/**\n * Calculates the date when the access token will expire.\n *\n * A one-minute grace period is applied for smooth handling of API latency.\n *\n * May be `null`, in which case the token does not expire.\n * This can only be the case with very old Client IDs.\n *\n * @param token The access token.\n */\nexport function getExpiryDateOfAccessToken(token) {\n return mapNullable(getExpiryMillis(token), _ => new Date(_));\n}\n/**\n * Calculates whether the given access token is expired.\n *\n * A one-minute grace period is applied for smooth handling of API latency.\n *\n * @param token The access token.\n */\nexport function accessTokenIsExpired(token) {\n return mapNullable(getExpiryMillis(token), _ => Date.now() > _) ?? false;\n}\n", "import { callTwitchApi, HttpStatusCodeError } from '@twurple/api-call';\nimport { InvalidTokenError } from './errors/InvalidTokenError.js';\nimport { InvalidTokenTypeError } from './errors/InvalidTokenTypeError.js';\nimport { createExchangeCodeQuery, createGetAppTokenQuery, createRefreshTokenQuery, createRevokeTokenQuery, } from './helpers.external.js';\nimport { TokenInfo } from './TokenInfo.js';\n/** @internal */\nfunction createAccessTokenFromData(data) {\n return {\n accessToken: data.access_token,\n refreshToken: data.refresh_token || null,\n scope: data.scope ?? [],\n expiresIn: data.expires_in ?? null,\n obtainmentTimestamp: Date.now(),\n };\n}\n/**\n * Gets an access token with your client credentials and an authorization code.\n *\n * @param clientId The client ID of your application.\n * @param clientSecret The client secret of your application.\n * @param code The authorization code.\n * @param redirectUri The redirect URI.\n *\n * This serves no real purpose here, but must still match one of the redirect URIs you configured in the Twitch Developer dashboard.\n */\nexport async function exchangeCode(clientId, clientSecret, code, redirectUri) {\n return createAccessTokenFromData(await callTwitchApi({\n type: 'auth',\n url: 'token',\n method: 'POST',\n query: createExchangeCodeQuery(clientId, clientSecret, code, redirectUri),\n }));\n}\n/**\n * Gets an app access token with your client credentials.\n *\n * @param clientId The client ID of your application.\n * @param clientSecret The client secret of your application.\n */\nexport async function getAppToken(clientId, clientSecret) {\n return createAccessTokenFromData(await callTwitchApi({\n type: 'auth',\n url: 'token',\n method: 'POST',\n query: createGetAppTokenQuery(clientId, clientSecret),\n }));\n}\n/**\n * Refreshes an expired access token with your client credentials and the refresh token that was given by the initial authentication.\n *\n * @param clientId The client ID of your application.\n * @param clientSecret The client secret of your application.\n * @param refreshToken The refresh token.\n */\nexport async function refreshUserToken(clientId, clientSecret, refreshToken) {\n return createAccessTokenFromData(await callTwitchApi({\n type: 'auth',\n url: 'token',\n method: 'POST',\n query: createRefreshTokenQuery(clientId, clientSecret, refreshToken),\n }));\n}\n/**\n * Revokes an access token.\n *\n * @param clientId The client ID of your application.\n * @param accessToken The access token.\n */\nexport async function revokeToken(clientId, accessToken) {\n await callTwitchApi({\n type: 'auth',\n url: 'revoke',\n method: 'POST',\n query: createRevokeTokenQuery(clientId, accessToken),\n });\n}\n/**\n * Gets information about an access token.\n *\n * @param accessToken The access token to get the information of.\n * @param clientId The client ID of your application.\n *\n * You need to obtain one using one of the [Twitch OAuth flows](https://dev.twitch.tv/docs/authentication/getting-tokens-oauth/).\n */\nexport async function getTokenInfo(accessToken, clientId) {\n try {\n const data = await callTwitchApi({ type: 'auth', url: 'validate' }, clientId, accessToken);\n return new TokenInfo(data);\n }\n catch (e) {\n if (e instanceof HttpStatusCodeError && e.statusCode === 401) {\n throw new InvalidTokenError({ cause: e });\n }\n throw e;\n }\n}\n/** @private */\nexport async function getValidTokenFromProviderForUser(provider, userId, scopes, logger) {\n let lastTokenError = null;\n let foundUser = false;\n try {\n const accessToken = await provider.getAccessTokenForUser(userId, scopes);\n if (accessToken) {\n foundUser = true;\n // check validity\n const tokenInfo = await getTokenInfo(accessToken.accessToken);\n return { accessToken, tokenInfo };\n }\n }\n catch (e) {\n if (e instanceof InvalidTokenError) {\n lastTokenError = e;\n }\n else {\n logger?.error(`Retrieving an access token failed: ${e.message}`);\n }\n }\n if (foundUser) {\n logger?.warn('No valid token available; trying to refresh');\n if (provider.refreshAccessTokenForUser) {\n try {\n const newToken = await provider.refreshAccessTokenForUser(userId);\n // check validity\n const tokenInfo = await getTokenInfo(newToken.accessToken);\n return { accessToken: newToken, tokenInfo };\n }\n catch (e) {\n if (e instanceof InvalidTokenError) {\n lastTokenError = e;\n }\n else {\n logger?.error(`Refreshing the access token failed: ${e.message}`);\n }\n }\n }\n }\n throw lastTokenError ?? new Error('Could not retrieve a valid token');\n}\n/** @private */\nexport async function getValidTokenFromProviderForIntent(provider, intent, scopes, logger) {\n let lastTokenError = null;\n let foundUser = false;\n if (!provider.getAccessTokenForIntent) {\n throw new InvalidTokenTypeError(`This call requires an AuthProvider that supports intents.\nPlease use an auth provider that does, such as \\`RefreshingAuthProvider\\`.`);\n }\n try {\n const accessToken = await provider.getAccessTokenForIntent(intent, scopes);\n if (accessToken) {\n foundUser = true;\n // check validity\n const tokenInfo = await getTokenInfo(accessToken.accessToken);\n return { accessToken, tokenInfo };\n }\n }\n catch (e) {\n if (e instanceof InvalidTokenError) {\n lastTokenError = e;\n }\n else {\n logger?.error(`Retrieving an access token failed: ${e.message}`);\n }\n }\n if (foundUser) {\n logger?.warn('No valid token available; trying to refresh');\n if (provider.refreshAccessTokenForIntent) {\n try {\n const newToken = await provider.refreshAccessTokenForIntent(intent);\n // check validity\n const tokenInfo = await getTokenInfo(newToken.accessToken);\n return { accessToken: newToken, tokenInfo };\n }\n catch (e) {\n if (e instanceof InvalidTokenError) {\n lastTokenError = e;\n }\n else {\n logger?.error(`Refreshing the access token failed: ${e.message}`);\n }\n }\n }\n }\n throw lastTokenError ?? new Error('Could not retrieve a valid token');\n}\nconst scopeEquivalencies = new Map([\n ['channel_commercial', ['channel:edit:commercial']],\n ['channel_editor', ['channel:manage:broadcast']],\n ['channel_read', ['channel:read:stream_key']],\n ['channel_subscriptions', ['channel:read:subscriptions']],\n ['user_blocks_read', ['user:read:blocked_users']],\n ['user_blocks_edit', ['user:manage:blocked_users']],\n ['user_follows_edit', ['user:edit:follows']],\n ['user_read', ['user:read:email']],\n ['user_subscriptions', ['user:read:subscriptions']],\n ['user:edit:broadcast', ['channel:manage:broadcast', 'channel:manage:extensions']],\n]);\n/**\n * Compares scopes for a non-upgradable {@link AuthProvider} instance.\n *\n * @param scopesToCompare The scopes to compare against.\n * @param requestedScopes The scopes you requested.\n */\nexport function compareScopes(scopesToCompare, requestedScopes) {\n if (requestedScopes?.length) {\n const scopes = new Set(scopesToCompare.flatMap(scope => [scope, ...(scopeEquivalencies.get(scope) ?? [])]));\n if (requestedScopes.every(scope => !scopes.has(scope))) {\n const scopesStr = requestedScopes.join(', ');\n throw new Error(`This token does not have any of the requested scopes (${scopesStr}) and can not be upgraded.\nIf you need dynamically upgrading scopes, please implement the AuthProvider interface accordingly:\n\n\\thttps://twurple.js.org/reference/auth/interfaces/AuthProvider.html`);\n }\n }\n}\n/**\n * Compares scope sets for a non-upgradable {@link AuthProvider} instance.\n *\n * @param scopesToCompare The scopes to compare against.\n * @param requestedScopeSets The scope sets you requested.\n */\nexport function compareScopeSets(scopesToCompare, requestedScopeSets) {\n for (const requestedScopes of requestedScopeSets) {\n compareScopes(scopesToCompare, requestedScopes);\n }\n}\n/**\n * Compares scopes for a non-upgradable `AuthProvider` instance, loading them from the token if necessary,\n * and returns them together with the user ID.\n *\n * @param clientId The client ID of your application.\n * @param token The access token.\n * @param userId The user ID that was already loaded.\n * @param loadedScopes The scopes that were already loaded.\n * @param requestedScopeSets The scope sets you requested.\n */\nexport async function loadAndCompareTokenInfo(clientId, token, userId, loadedScopes, requestedScopeSets) {\n // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing\n if (requestedScopeSets?.length || !userId) {\n const userInfo = await getTokenInfo(token, clientId);\n if (!userInfo.userId) {\n throw new Error('Trying to use an app access token as a user access token');\n }\n const scopesToCompare = loadedScopes ?? userInfo.scopes;\n if (requestedScopeSets) {\n compareScopeSets(scopesToCompare, requestedScopeSets.filter((val) => Boolean(val)));\n }\n return [scopesToCompare, userInfo.userId];\n }\n return [loadedScopes, userId];\n}\n", "import { CustomError } from '@twurple/common';\n/**\n * Thrown whenever an invalid token is supplied.\n */\nexport class InvalidTokenError extends CustomError {\n /** @private */\n constructor(options) {\n super('Invalid token supplied', options);\n }\n}\n", "/** @internal */\nexport function createExchangeCodeQuery(clientId, clientSecret, code, redirectUri) {\n return {\n grant_type: 'authorization_code',\n client_id: clientId,\n client_secret: clientSecret,\n code,\n redirect_uri: redirectUri,\n };\n}\n/** @internal */\nexport function createGetAppTokenQuery(clientId, clientSecret) {\n return {\n grant_type: 'client_credentials',\n client_id: clientId,\n client_secret: clientSecret,\n };\n}\n/** @internal */\nexport function createRefreshTokenQuery(clientId, clientSecret, refreshToken) {\n return {\n grant_type: 'refresh_token',\n client_id: clientId,\n client_secret: clientSecret,\n refresh_token: refreshToken,\n };\n}\n/** @internal */\nexport function createRevokeTokenQuery(clientId, accessToken) {\n return {\n client_id: clientId,\n token: accessToken,\n };\n}\n", "import { __decorate } from \"tslib\";\nimport { mapNullable } from '@d-fischer/shared-utils';\nimport { DataObject, rawDataSymbol, rtfm } from '@twurple/common';\n/**\n * Information about an access token.\n */\nlet TokenInfo = class TokenInfo extends DataObject {\n _obtainmentDate;\n /** @internal */\n constructor(data) {\n super(data);\n this._obtainmentDate = new Date();\n }\n /**\n * The client ID.\n */\n get clientId() {\n return this[rawDataSymbol].client_id;\n }\n /**\n * The ID of the authenticated user.\n */\n get userId() {\n return this[rawDataSymbol].user_id ?? null;\n }\n /**\n * The name of the authenticated user.\n */\n get userName() {\n return this[rawDataSymbol].login ?? null;\n }\n /**\n * The scopes for which the token is valid.\n */\n get scopes() {\n return this[rawDataSymbol].scopes;\n }\n /**\n * The time when the token will expire.\n *\n * If this returns null, it means that the token never expires (happens with some old client IDs).\n */\n get expiryDate() {\n return mapNullable(this[rawDataSymbol].expires_in, v => new Date(this._obtainmentDate.getTime() + v * 1000));\n }\n};\nTokenInfo = __decorate([\n rtfm('auth', 'TokenInfo', 'clientId')\n], TokenInfo);\nexport { TokenInfo };\n", "import { promiseWithResolvers } from '@d-fischer/shared-utils';\nexport class TokenFetcher {\n _executor;\n _newTokenScopeSets = [];\n _newTokenPromise = null;\n _queuedScopeSets = [];\n _queueExecutor = null;\n _queuePromise = null;\n constructor(executor) {\n this._executor = executor;\n }\n async fetch(...scopeSets) {\n const filteredScopeSets = scopeSets.filter((val) => Boolean(val));\n if (this._newTokenPromise) {\n if (!filteredScopeSets.length) {\n return await this._newTokenPromise;\n }\n if (this._queueExecutor) {\n this._queuedScopeSets.push(...filteredScopeSets);\n }\n else {\n this._queuedScopeSets = [...filteredScopeSets];\n }\n if (!this._queuePromise) {\n const { promise, resolve, reject } = promiseWithResolvers();\n this._queuePromise = promise;\n this._queueExecutor = async () => {\n if (!this._queuePromise) {\n return;\n }\n this._newTokenScopeSets = this._queuedScopeSets;\n this._queuedScopeSets = [];\n this._newTokenPromise = this._queuePromise;\n this._queuePromise = null;\n this._queueExecutor = null;\n try {\n resolve(await this._executor(this._newTokenScopeSets));\n }\n catch (e) {\n reject(e);\n }\n finally {\n this._newTokenPromise = null;\n this._newTokenScopeSets = [];\n this._queueExecutor?.();\n }\n };\n }\n return await this._queuePromise;\n }\n this._newTokenScopeSets = [...filteredScopeSets];\n const { promise, resolve, reject } = promiseWithResolvers();\n this._newTokenPromise = promise;\n try {\n resolve(await this._executor(this._newTokenScopeSets));\n }\n catch (e) {\n reject(e);\n }\n finally {\n this._newTokenPromise = null;\n this._newTokenScopeSets = [];\n this._queueExecutor?.();\n }\n return await promise;\n }\n}\n", "import { __decorate } from \"tslib\";\nimport { Enumerable } from '@d-fischer/shared-utils';\nimport { extractUserId, rtfm } from '@twurple/common';\nimport { accessTokenIsExpired } from '../AccessToken.js';\nimport { getAppToken } from '../helpers.js';\nimport { TokenFetcher } from '../TokenFetcher.js';\n/**\n * An auth provider that gets tokens using client credentials.\n */\nlet AppTokenAuthProvider = class AppTokenAuthProvider {\n _clientId;\n /** @internal */ _clientSecret;\n /** @internal */ _token;\n /** @internal */ _fetcher;\n _impliedScopes;\n /**\n * Creates a new auth provider to receive an application token with using the client ID and secret.\n *\n * @param clientId The client ID of your application.\n * @param clientSecret The client secret of your application.\n * @param impliedScopes The scopes that are implied for your application,\n * for example an extension that is allowed to access subscriptions.\n */\n constructor(clientId, clientSecret, impliedScopes = []) {\n this._clientId = clientId;\n this._clientSecret = clientSecret;\n this._impliedScopes = impliedScopes;\n this._fetcher = new TokenFetcher(async (scopes) => await this._fetch(scopes));\n }\n /**\n * The client ID.\n */\n get clientId() {\n return this._clientId;\n }\n /**\n * The scopes that are currently available using the access token.\n */\n get currentScopes() {\n return this._impliedScopes;\n }\n /**\n * Can only get tokens for implied scopes (i.e. extension subscription support).\n *\n * The consumer is expected to take care that this is actually set up in the Twitch developer console.\n *\n * @param user The user to get an access token for.\n * @param scopeSets The requested scopes.\n */\n async getAccessTokenForUser(user, ...scopeSets) {\n if (scopeSets.every(scopeSet => scopeSet?.some(scope => this._impliedScopes.includes(scope)) ?? true)) {\n const appToken = await this.getAppAccessToken();\n return {\n ...appToken,\n userId: extractUserId(user),\n };\n }\n throw new Error('Can not get user access token for AppTokenAuthProvider');\n }\n /**\n * Throws, because this auth provider does not support user authentication.\n */\n getCurrentScopesForUser() {\n return this._impliedScopes;\n }\n /**\n * Fetches an app access token.\n */\n async getAnyAccessToken() {\n return await this._fetcher.fetch();\n }\n /**\n * Fetches an app access token.\n *\n * @param forceNew Whether to always get a new token, even if the old one is still deemed valid internally.\n */\n async getAppAccessToken(forceNew = false) {\n if (forceNew) {\n this._token = undefined;\n }\n return await this._fetcher.fetch();\n }\n async _fetch(scopeSets) {\n if (scopeSets.length > 0) {\n for (const scopes of scopeSets) {\n if (this._impliedScopes.length) {\n if (scopes.every(scope => !this._impliedScopes.includes(scope))) {\n throw new Error(`One of the scopes ${scopes.join(', ')} requested but only the scope ${this._impliedScopes.join(', ')} is implied`);\n }\n }\n else {\n throw new Error(`One of the scopes ${scopes.join(', ')} requested but the client credentials flow does not support scopes`);\n }\n }\n }\n if (!this._token || accessTokenIsExpired(this._token)) {\n return (this._token = await getAppToken(this._clientId, this._clientSecret));\n }\n return this._token;\n }\n};\n__decorate([\n Enumerable(false)\n], AppTokenAuthProvider.prototype, \"_clientSecret\", void 0);\n__decorate([\n Enumerable(false)\n], AppTokenAuthProvider.prototype, \"_token\", void 0);\n__decorate([\n Enumerable(false)\n], AppTokenAuthProvider.prototype, \"_fetcher\", void 0);\nAppTokenAuthProvider = __decorate([\n rtfm('auth', 'AppTokenAuthProvider', 'clientId')\n], AppTokenAuthProvider);\nexport { AppTokenAuthProvider };\n", "import { __decorate } from \"tslib\";\nimport { mapOptional } from '@d-fischer/shared-utils';\nimport { createBroadcasterQuery } from '@twurple/api-call';\nimport { extractUserId, rtfm } from '@twurple/common';\nimport { createBitsLeaderboardQuery, } from '../../interfaces/endpoints/bits.external.js';\nimport { BaseApi } from '../BaseApi.js';\nimport { HelixBitsLeaderboard } from './HelixBitsLeaderboard.js';\nimport { HelixCheermoteList } from './HelixCheermoteList.js';\n/**\n * The Helix API methods that deal with bits.\n *\n * Can be accessed using `client.bits` on an {@link ApiClient} instance.\n *\n * ## Example\n * ```ts\n * const api = new ApiClient({ authProvider });\n * const leaderboard = await api.bits.getLeaderboard({ period: 'day' });\n * ```\n *\n * @meta category helix\n * @meta categorizedTitle Bits\n */\nlet HelixBitsApi = class HelixBitsApi extends BaseApi {\n /**\n * Gets a bits leaderboard of your channel.\n *\n * @param broadcaster The user to get the leaderboard of.\n * @param params\n * @expandParams\n */\n async getLeaderboard(broadcaster, params = {}) {\n const result = await this._client.callApi({\n type: 'helix',\n url: 'bits/leaderboard',\n userId: extractUserId(broadcaster),\n scopes: ['bits:read'],\n query: createBitsLeaderboardQuery(params),\n });\n return new HelixBitsLeaderboard(result, this._client);\n }\n /**\n * Gets all available cheermotes.\n *\n * @param broadcaster The broadcaster to include custom cheermotes of.\n *\n * If not given, only get global cheermotes.\n */\n async getCheermotes(broadcaster) {\n const result = await this._client.callApi({\n type: 'helix',\n url: 'bits/cheermotes',\n userId: mapOptional(broadcaster, extractUserId),\n query: mapOptional(broadcaster, createBroadcasterQuery),\n });\n return new HelixCheermoteList(result.data);\n }\n};\nHelixBitsApi = __decorate([\n rtfm('api', 'HelixBitsApi')\n], HelixBitsApi);\nexport { HelixBitsApi };\n", "/** @internal */\nexport function createBitsLeaderboardQuery(params = {}) {\n const { count = 10, period = 'all', startDate, contextUserId } = params;\n return {\n count: count.toString(),\n period,\n started_at: startDate?.toISOString(),\n user_id: contextUserId,\n };\n}\n", "import { __decorate } from \"tslib\";\nimport { Enumerable } from '@d-fischer/shared-utils';\n/** @private */\nexport class BaseApi {\n /** @internal */ _client;\n /** @internal */\n constructor(client) {\n this._client = client;\n }\n /** @internal */\n _getUserContextIdWithDefault(userId) {\n return this._client._getUserIdFromRequestContext(userId) ?? userId;\n }\n}\n__decorate([\n Enumerable(false)\n], BaseApi.prototype, \"_client\", void 0);\n", "import { __decorate } from \"tslib\";\nimport { Cacheable, CachedGetter } from '@d-fischer/cache-decorators';\nimport { Enumerable } from '@d-fischer/shared-utils';\nimport { DataObject, rawDataSymbol, rtfm } from '@twurple/common';\nimport { HelixBitsLeaderboardEntry } from './HelixBitsLeaderboardEntry.js';\n/**\n * A leaderboard where the users who used the most bits to a broadcaster are listed.\n */\nlet HelixBitsLeaderboard = class HelixBitsLeaderboard extends DataObject {\n /** @internal */ _client;\n /** @internal */\n constructor(data, client) {\n super(data);\n this._client = client;\n }\n /**\n * The entries of the leaderboard.\n */\n get entries() {\n return this[rawDataSymbol].data.map(entry => new HelixBitsLeaderboardEntry(entry, this._client));\n }\n /**\n * The total amount of people on the requested leaderboard.\n */\n get totalCount() {\n return this[rawDataSymbol].total;\n }\n};\n__decorate([\n Enumerable(false)\n], HelixBitsLeaderboard.prototype, \"_client\", void 0);\n__decorate([\n CachedGetter()\n], HelixBitsLeaderboard.prototype, \"entries\", null);\nHelixBitsLeaderboard = __decorate([\n Cacheable,\n rtfm('api', 'HelixBitsLeaderboard')\n], HelixBitsLeaderboard);\nexport { HelixBitsLeaderboard };\n", "import { __decorate } from \"tslib\";\nimport { Enumerable } from '@d-fischer/shared-utils';\nimport { checkRelationAssertion, DataObject, rawDataSymbol, rtfm } from '@twurple/common';\n/**\n * A Bits leaderboard entry.\n */\nlet HelixBitsLeaderboardEntry = class HelixBitsLeaderboardEntry extends DataObject {\n /** @internal */ _client;\n /** @internal */\n constructor(data, client) {\n super(data);\n this._client = client;\n }\n /**\n * The ID of the user on the leaderboard.\n */\n get userId() {\n return this[rawDataSymbol].user_id;\n }\n /**\n * The name of the user on the leaderboard.\n */\n get userName() {\n return this[rawDataSymbol].user_login;\n }\n /**\n * The display name of the user on the leaderboard.\n */\n get userDisplayName() {\n return this[rawDataSymbol].user_name;\n }\n /**\n * The position of the user on the leaderboard.\n */\n get rank() {\n return this[rawDataSymbol].rank;\n }\n /**\n * The amount of bits used in the given period of time.\n */\n get amount() {\n return this[rawDataSymbol].score;\n }\n /**\n * Gets the user of entry on the leaderboard.\n */\n async getUser() {\n return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].user_id));\n }\n};\n__decorate([\n Enumerable(false)\n], HelixBitsLeaderboardEntry.prototype, \"_client\", void 0);\nHelixBitsLeaderboardEntry = __decorate([\n rtfm('api', 'HelixBitsLeaderboardEntry', 'userId')\n], HelixBitsLeaderboardEntry);\nexport { HelixBitsLeaderboardEntry };\n", "import { __decorate } from \"tslib\";\nimport { indexBy } from '@d-fischer/shared-utils';\nimport { DataObject, HellFreezesOverError, rawDataSymbol, rtfm } from '@twurple/common';\n/**\n * A list of cheermotes you can use globally or in a specific channel, depending on how you fetched the list.\n *\n * @inheritDoc\n */\nlet HelixCheermoteList = class HelixCheermoteList extends DataObject {\n /** @internal */\n constructor(data) {\n super(indexBy(data, action => action.prefix.toLowerCase()));\n }\n /**\n * Gets the URL and color needed to properly represent a cheer of the given amount of bits with the given prefix.\n *\n * @param name The name/prefix of the cheermote.\n * @param bits The amount of bits cheered.\n * @param format The format of the cheermote you want to request.\n */\n getCheermoteDisplayInfo(name, bits, format) {\n name = name.toLowerCase();\n const { background, state, scale } = format;\n const { tiers } = this[rawDataSymbol][name];\n const correctTier = tiers.sort((a, b) => b.min_bits - a.min_bits).find(tier => tier.min_bits <= bits);\n if (!correctTier) {\n throw new HellFreezesOverError(`Cheermote \"${name}\" does not have an applicable tier for ${bits} bits`);\n }\n return {\n url: correctTier.images[background][state][scale],\n color: correctTier.color,\n };\n }\n /**\n * Gets all possible cheermote names.\n */\n getPossibleNames() {\n return Object.keys(this[rawDataSymbol]);\n }\n};\nHelixCheermoteList = __decorate([\n rtfm('api', 'HelixCheermoteList')\n], HelixCheermoteList);\nexport { HelixCheermoteList };\n", "import { __decorate } from \"tslib\";\nimport { Enumerable, mapNullable } from '@d-fischer/shared-utils';\nimport { createBroadcasterQuery, } from '@twurple/api-call';\nimport { extractUserId, rtfm } from '@twurple/common';\nimport { createChannelCommercialBody, createChannelFollowerQuery, createChannelUpdateBody, createChannelVipUpdateQuery, createFollowedChannelQuery, } from '../../interfaces/endpoints/channel.external.js';\nimport { createChannelUsersCheckQuery, createSingleKeyQuery, } from '../../interfaces/endpoints/generic.external.js';\nimport { HelixUserRelation } from '../../relations/HelixUserRelation.js';\nimport { HelixRequestBatcher } from '../../utils/HelixRequestBatcher.js';\nimport { HelixPaginatedRequest } from '../../utils/pagination/HelixPaginatedRequest.js';\nimport { HelixPaginatedRequestWithTotal } from '../../utils/pagination/HelixPaginatedRequestWithTotal.js';\nimport { createPaginatedResult, createPaginatedResultWithTotal, } from '../../utils/pagination/HelixPaginatedResult.js';\nimport { createPaginationQuery } from '../../utils/pagination/HelixPagination.js';\nimport { BaseApi } from '../BaseApi.js';\nimport { HelixChannel } from './HelixChannel.js';\nimport { HelixChannelEditor } from './HelixChannelEditor.js';\nimport { HelixChannelFollower } from './HelixChannelFollower.js';\nimport { HelixFollowedChannel } from './HelixFollowedChannel.js';\nimport { HelixAdSchedule } from './HelixAdSchedule.js';\nimport { HelixSnoozeNextAdResult } from './HelixSnoozeNextAdResult.js';\n/**\n * The Helix API methods that deal with channels.\n *\n * Can be accessed using `client.channels` on an {@link ApiClient} instance.\n *\n * ## Example\n * ```ts\n * const api = new ApiClient({ authProvider });\n * const channel = await api.channels.getChannelInfoById('125328655');\n * ```\n *\n * @meta category helix\n * @meta categorizedTitle Channels\n */\nlet HelixChannelApi = class HelixChannelApi extends BaseApi {\n /** @internal */\n _getChannelByIdBatcher = new HelixRequestBatcher({\n url: 'channels',\n }, 'broadcaster_id', 'broadcaster_id', this._client, (data) => new HelixChannel(data, this._client));\n /**\n * Gets the channel data for the given user.\n *\n * @param user The user you want to get channel info for.\n */\n async getChannelInfoById(user) {\n const userId = extractUserId(user);\n const result = await this._client.callApi({\n type: 'helix',\n url: 'channels',\n userId,\n query: createBroadcasterQuery(userId),\n });\n return mapNullable(result.data[0], data => new HelixChannel(data, this._client));\n }\n /**\n * Gets the channel data for the given user, batching multiple calls into fewer requests as the API allows.\n *\n * @param user The user you want to get channel info for.\n */\n async getChannelInfoByIdBatched(user) {\n return await this._getChannelByIdBatcher.request(extractUserId(user));\n }\n /**\n * Gets the channel data for the given users.\n *\n * @param users The users you want to get channel info for.\n */\n async getChannelInfoByIds(users) {\n const userIds = users.map(extractUserId);\n const result = await this._client.callApi({\n type: 'helix',\n url: 'channels',\n query: createSingleKeyQuery('broadcaster_id', userIds),\n });\n return result.data.map(data => new HelixChannel(data, this._client));\n }\n /**\n * Updates the given user's channel data.\n *\n * @param user The user you want to update channel info for.\n * @param data The channel info to set.\n */\n async updateChannelInfo(user, data) {\n await this._client.callApi({\n type: 'helix',\n url: 'channels',\n method: 'PATCH',\n userId: extractUserId(user),\n scopes: ['channel:manage:broadcast'],\n query: createBroadcasterQuery(user),\n jsonBody: createChannelUpdateBody(data),\n });\n }\n /**\n * Starts a commercial on a channel.\n *\n * @param broadcaster The broadcaster on whose channel the commercial is started.\n * @param length The length of the commercial, in seconds.\n */\n async startChannelCommercial(broadcaster, length) {\n await this._client.callApi({\n type: 'helix',\n url: 'channels/commercial',\n method: 'POST',\n userId: extractUserId(broadcaster),\n scopes: ['channel:edit:commercial'],\n jsonBody: createChannelCommercialBody(broadcaster, length),\n });\n }\n /**\n * Gets a list of users who have editor permissions on your channel.\n *\n * @param broadcaster The broadcaster to retreive the editors for.\n */\n async getChannelEditors(broadcaster) {\n const result = await this._client.callApi({\n type: 'helix',\n url: 'channels/editors',\n userId: extractUserId(broadcaster),\n scopes: ['channel:read:editors'],\n query: createBroadcasterQuery(broadcaster),\n });\n return result.data.map(data => new HelixChannelEditor(data, this._client));\n }\n /**\n * Gets a list of VIPs in a channel.\n *\n * @param broadcaster The owner of the channel to get VIPs for.\n * @param pagination\n *\n * @expandParams\n */\n async getVips(broadcaster, pagination) {\n const response = await this._client.callApi({\n type: 'helix',\n url: 'channels/vips',\n userId: extractUserId(broadcaster),\n scopes: ['channel:read:vips', 'channel:manage:vips'],\n query: {\n ...createBroadcasterQuery(broadcaster),\n ...createPaginationQuery(pagination),\n },\n });\n return createPaginatedResult(response, HelixUserRelation, this._client);\n }\n /**\n * Creates a paginator for VIPs in a channel.\n *\n * @param broadcaster The owner of the channel to get VIPs for.\n */\n getVipsPaginated(broadcaster) {\n return new HelixPaginatedRequest({\n url: 'channels/vips',\n userId: extractUserId(broadcaster),\n scopes: ['channel:read:vips', 'channel:manage:vips'],\n query: createBroadcasterQuery(broadcaster),\n }, this._client, data => new HelixUserRelation(data, this._client));\n }\n /**\n * Checks the VIP status of a list of users in a channel.\n *\n * @param broadcaster The owner of the channel to check VIP status in.\n * @param users The users to check.\n */\n async checkVipForUsers(broadcaster, users) {\n const response = await this._client.callApi({\n type: 'helix',\n url: 'channels/vips',\n userId: extractUserId(broadcaster),\n scopes: ['channel:read:vips', 'channel:manage:vips'],\n query: createChannelUsersCheckQuery(broadcaster, users),\n });\n return response.data.map(data => new HelixUserRelation(data, this._client));\n }\n /**\n * Checks the VIP status of a user in a channel.\n *\n * @param broadcaster The owner of the channel to check VIP status in.\n * @param user The user to check.\n */\n async checkVipForUser(broadcaster, user) {\n const userId = extractUserId(user);\n const result = await this.checkVipForUsers(broadcaster, [userId]);\n return result.some(rel => rel.id === userId);\n }\n /**\n * Adds a VIP to the broadcaster\u2019s chat room.\n *\n * @param broadcaster The broadcaster that\u2019s granting VIP status to the user. This ID must match the user ID in the access token.\n * @param user The user to add as a VIP in the broadcaster\u2019s chat room.\n */\n async addVip(broadcaster, user) {\n await this._client.callApi({\n type: 'helix',\n url: 'channels/vips',\n method: 'POST',\n userId: extractUserId(broadcaster),\n scopes: ['channel:manage:vips'],\n query: createChannelVipUpdateQuery(broadcaster, user),\n });\n }\n /**\n * Removes a VIP from the broadcaster\u2019s chat room.\n *\n * @param broadcaster The broadcaster that\u2019s removing VIP status from the user. This ID must match the user ID in the access token.\n * @param user The user to remove as a VIP from the broadcaster\u2019s chat room.\n */\n async removeVip(broadcaster, user) {\n await this._client.callApi({\n type: 'helix',\n url: 'channels/vips',\n method: 'DELETE',\n userId: extractUserId(broadcaster),\n scopes: ['channel:manage:vips'],\n query: createChannelVipUpdateQuery(broadcaster, user),\n });\n }\n /**\n * Gets the total number of users that follow the specified broadcaster.\n *\n * @param broadcaster The broadcaster you want to get the number of followers of.\n */\n async getChannelFollowerCount(broadcaster) {\n const result = await this._client.callApi({\n type: 'helix',\n url: 'channels/followers',\n method: 'GET',\n userId: extractUserId(broadcaster),\n query: {\n ...createChannelFollowerQuery(broadcaster),\n ...createPaginationQuery({ limit: 1 }),\n },\n });\n return result.total;\n }\n /**\n * Gets a list of users that follow the specified broadcaster.\n * You can also use this endpoint to see whether a specific user follows the broadcaster.\n *\n * This uses the token of the broadcaster by default.\n * If you want to execute this in the context of another user (who has to be moderator of the channel)\n * you can do so using [user context overrides](/docs/auth/concepts/context-switching).\n *\n * @param broadcaster The broadcaster you want to get a list of followers for.\n * @param user An optional user to determine if this user follows the broadcaster.\n * If specified, the response contains this user if they follow the broadcaster.\n * If not specified, the response contains all users that follow the broadcaster.\n * @param pagination\n *\n * @expandParams\n */\n async getChannelFollowers(broadcaster, user, pagination) {\n const result = await this._client.callApi({\n type: 'helix',\n url: 'channels/followers',\n method: 'GET',\n userId: extractUserId(broadcaster),\n canOverrideScopedUserContext: true,\n scopes: ['moderator:read:followers'],\n query: {\n ...createChannelFollowerQuery(broadcaster, user),\n ...createPaginationQuery(pagination),\n },\n });\n return createPaginatedResultWithTotal(result, HelixChannelFollower, this._client);\n }\n /**\n * Creates a paginator for users that follow the specified broadcaster.\n *\n * This uses the token of the broadcaster by default.\n * If you want to execute this in the context of another user (who has to be moderator of the channel)\n * you can do so using [user context overrides](/docs/auth/concepts/context-switching).\n *\n * @param broadcaster The broadcaster for whom you are getting a list of followers.\n *\n * @expandParams\n */\n getChannelFollowersPaginated(broadcaster) {\n return new HelixPaginatedRequestWithTotal({\n url: 'channels/followers',\n method: 'GET',\n userId: extractUserId(broadcaster),\n canOverrideScopedUserContext: true,\n scopes: ['moderator:read:followers'],\n query: createChannelFollowerQuery(broadcaster),\n }, this._client, data => new HelixChannelFollower(data, this._client));\n }\n /**\n * Gets a list of broadcasters that the specified user follows.\n * You can also use this endpoint to see whether the user follows a specific broadcaster.\n *\n * @param user The user that's getting a list of followed channels.\n * This ID must match the user ID in the access token.\n * @param broadcaster An optional broadcaster to determine if the user follows this broadcaster.\n * If specified, the response contains this broadcaster if the user follows them.\n * If not specified, the response contains all broadcasters that the user follows.\n * @param pagination\n * @returns\n */\n async getFollowedChannels(user, broadcaster, pagination) {\n const result = await this._client.callApi({\n type: 'helix',\n url: 'channels/followed',\n method: 'GET',\n userId: extractUserId(user),\n scopes: ['user:read:follows'],\n query: {\n ...createFollowedChannelQuery(user, broadcaster),\n ...createPaginationQuery(pagination),\n },\n });\n return createPaginatedResultWithTotal(result, HelixFollowedChannel, this._client);\n }\n /**\n * Creates a paginator for broadcasters that the specified user follows.\n *\n * @param user The user that's getting a list of followed channels.\n * The token of this user will be used to get the list of followed channels.\n * @param broadcaster An optional broadcaster to determine if the user follows this broadcaster.\n * If specified, the response contains this broadcaster if the user follows them.\n * If not specified, the response contains all broadcasters that the user follows.\n * @returns\n */\n getFollowedChannelsPaginated(user, broadcaster) {\n return new HelixPaginatedRequestWithTotal({\n url: 'channels/followed',\n method: 'GET',\n userId: extractUserId(user),\n scopes: ['user:read:follows'],\n query: createFollowedChannelQuery(user, broadcaster),\n }, this._client, data => new HelixFollowedChannel(data, this._client));\n }\n /**\n * Gets information about the broadcaster's ad schedule.\n *\n * @param broadcaster The broadcaster to get ad schedule information about.\n */\n async getAdSchedule(broadcaster) {\n const response = await this._client.callApi({\n type: 'helix',\n url: 'channels/ads',\n method: 'GET',\n userId: extractUserId(broadcaster),\n scopes: ['channel:read:ads'],\n query: createBroadcasterQuery(broadcaster),\n });\n return new HelixAdSchedule(response.data[0]);\n }\n /**\n * Snoozes the broadcaster's next ad, if a snooze is available.\n *\n * @param broadcaster The broadcaster to get ad schedule information about.\n */\n async snoozeNextAd(broadcaster) {\n const response = await this._client.callApi({\n type: 'helix',\n url: 'channels/ads/schedule/snooze',\n method: 'POST',\n userId: extractUserId(broadcaster),\n scopes: ['channel:manage:ads'],\n query: createBroadcasterQuery(broadcaster),\n });\n return new HelixSnoozeNextAdResult(response.data[0]);\n }\n};\n__decorate([\n Enumerable(false)\n], HelixChannelApi.prototype, \"_getChannelByIdBatcher\", void 0);\nHelixChannelApi = __decorate([\n rtfm('api', 'HelixChannelApi')\n], HelixChannelApi);\nexport { HelixChannelApi };\n", "import { mapOptional } from '@d-fischer/shared-utils';\nimport { extractUserId } from '@twurple/common';\n/** @internal */\nexport function createChannelUpdateBody(data) {\n return {\n game_id: data.gameId,\n broadcaster_language: data.language,\n title: data.title,\n delay: data.delay?.toString(),\n tags: data.tags,\n content_classification_labels: data.contentClassificationLabels,\n is_branded_content: data.isBrandedContent,\n };\n}\n/** @internal */\nexport function createChannelCommercialBody(broadcaster, length) {\n return {\n broadcaster_id: extractUserId(broadcaster),\n length,\n };\n}\n/** @internal */\nexport function createChannelVipUpdateQuery(broadcaster, user) {\n return {\n broadcaster_id: extractUserId(broadcaster),\n user_id: extractUserId(user),\n };\n}\n/** @internal */\nexport function createChannelFollowerQuery(broadcaster, user) {\n return {\n broadcaster_id: extractUserId(broadcaster),\n user_id: mapOptional(user, extractUserId),\n };\n}\n/** @internal */\nexport function createFollowedChannelQuery(user, broadcaster) {\n return {\n broadcaster_id: mapOptional(broadcaster, extractUserId),\n user_id: extractUserId(user),\n };\n}\n", "import { extractUserId } from '@twurple/common';\n/** @internal */\nexport function createSingleKeyQuery(key, value) {\n return { [key]: value };\n}\n/** @internal */\nexport function createUserQuery(user) {\n return {\n user_id: extractUserId(user),\n };\n}\n/** @internal */\nexport function createModeratorActionQuery(broadcaster, moderatorId) {\n return {\n broadcaster_id: broadcaster,\n moderator_id: moderatorId,\n };\n}\n/** @internal */\nexport function createGetByIdsQuery(broadcaster, rewardIds) {\n return {\n broadcaster_id: extractUserId(broadcaster),\n id: rewardIds,\n };\n}\n/** @internal */\nexport function createChannelUsersCheckQuery(broadcaster, users) {\n return {\n broadcaster_id: extractUserId(broadcaster),\n user_id: users.map(extractUserId),\n };\n}\n", "import { __decorate } from \"tslib\";\nimport { Enumerable } from '@d-fischer/shared-utils';\nimport { checkRelationAssertion, DataObject, rawDataSymbol, rtfm } from '@twurple/common';\n/**\n * A relation of anything with a user.\n */\nlet HelixUserRelation = class HelixUserRelation extends DataObject {\n /** @internal */ _client;\n /** @internal */\n constructor(data, client) {\n super(data);\n this._client = client;\n }\n /**\n * The ID of the user.\n */\n get id() {\n return this[rawDataSymbol].user_id;\n }\n /**\n * The name of the user.\n */\n get name() {\n return this[rawDataSymbol].user_login;\n }\n /**\n * The display name of the user.\n */\n get displayName() {\n return this[rawDataSymbol].user_name;\n }\n /**\n * Gets additional information about the user.\n */\n async getUser() {\n return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].user_id));\n }\n};\n__decorate([\n Enumerable(false)\n], HelixUserRelation.prototype, \"_client\", void 0);\nHelixUserRelation = __decorate([\n rtfm('api', 'HelixUserRelation', 'id')\n], HelixUserRelation);\nexport { HelixUserRelation };\n", "import { __decorate } from \"tslib\";\nimport { Enumerable, indexBy, promiseWithResolvers } from '@d-fischer/shared-utils';\n/** @internal */\nexport class HelixRequestBatcher {\n _callOptions;\n _queryParamName;\n _matchKey;\n _mapper;\n _limitPerRequest;\n _client;\n _requestedIds = [];\n _requestResolversById = new Map();\n _delay;\n _waitTimer = null;\n constructor(_callOptions, _queryParamName, _matchKey, client, _mapper, _limitPerRequest = 100) {\n this._callOptions = _callOptions;\n this._queryParamName = _queryParamName;\n this._matchKey = _matchKey;\n this._mapper = _mapper;\n this._limitPerRequest = _limitPerRequest;\n this._client = client;\n this._delay = client._batchDelay;\n }\n async request(id) {\n const { promise, resolve, reject } = promiseWithResolvers();\n if (!this._requestedIds.includes(id)) {\n this._requestedIds.push(id);\n }\n if (this._requestResolversById.has(id)) {\n this._requestResolversById.get(id).push({ resolve, reject });\n }\n else {\n this._requestResolversById.set(id, [{ resolve, reject }]);\n }\n if (this._waitTimer) {\n clearTimeout(this._waitTimer);\n this._waitTimer = null;\n }\n if (this._requestedIds.length >= this._limitPerRequest) {\n void this._handleBatch(this._requestedIds.splice(0, this._limitPerRequest));\n }\n else {\n this._waitTimer = setTimeout(() => {\n void this._handleBatch(this._requestedIds.splice(0, this._limitPerRequest));\n }, this._delay);\n }\n return await promise;\n }\n async _handleBatch(ids) {\n try {\n const { data } = await this._doRequest(ids);\n const dataById = indexBy(data, this._matchKey);\n for (const id of ids) {\n for (const resolver of this._requestResolversById.get(id) ?? []) {\n if (Object.prototype.hasOwnProperty.call(dataById, id)) {\n resolver.resolve(this._mapper(dataById[id]));\n }\n else {\n resolver.resolve(null);\n }\n }\n this._requestResolversById.delete(id);\n }\n }\n catch (e) {\n await Promise.all(ids.map(async (id) => {\n try {\n const result = await this._doRequest([id]);\n for (const resolver of this._requestResolversById.get(id) ?? []) {\n resolver.resolve(result.data.length ? this._mapper(result.data[0]) : null);\n }\n }\n catch (e_) {\n for (const resolver of this._requestResolversById.get(id) ?? []) {\n resolver.reject(e_);\n }\n }\n this._requestResolversById.delete(id);\n }));\n }\n }\n async _doRequest(ids) {\n return await this._client.callApi({\n type: 'helix',\n ...this._callOptions,\n query: {\n ...this._callOptions.query,\n [this._queryParamName]: ids,\n },\n });\n }\n}\n__decorate([\n Enumerable(false)\n], HelixRequestBatcher.prototype, \"_client\", void 0);\n", "import { __decorate } from \"tslib\";\nimport { Enumerable } from '@d-fischer/shared-utils';\nimport { rtfm } from '@twurple/common';\nif (!Object.prototype.hasOwnProperty.call(Symbol, 'asyncIterator')) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any,@typescript-eslint/no-unnecessary-condition,@typescript-eslint/no-unsafe-member-access\n Symbol.asyncIterator = Symbol.asyncIterator ?? Symbol.for('Symbol.asyncIterator');\n}\n/**\n * Represents a request to the new Twitch API (Helix) that utilizes a cursor to paginate through its results.\n *\n * Aside from the methods described below, you can also utilize the async iterator using `for await .. of`:\n *\n * ```ts\n * const result = client.videos.getVideosByUserPaginated('125328655');\n * for await (const video of result) {\n * console.log(video.title);\n * }\n * ```\n */\nlet HelixPaginatedRequest = class HelixPaginatedRequest {\n _callOptions;\n _mapper;\n _limitPerPage;\n /** @internal */ _client;\n /** @internal */ _currentCursor;\n /** @internal */ _isFinished = false;\n /** @internal */ _currentData;\n /** @internal */\n constructor(_callOptions, client, _mapper, _limitPerPage = 100) {\n this._callOptions = _callOptions;\n this._mapper = _mapper;\n this._limitPerPage = _limitPerPage;\n this._client = client;\n }\n /**\n * The last fetched page of data associated to the requested resource.\n *\n * Only works with {@link HelixPaginatedRequest#getNext} and not with any other methods of data fetching.\n */\n get current() {\n return this._currentData?.data;\n }\n /**\n * Gets the next available page of data associated to the requested resource, or an empty array if there are no more available pages.\n */\n async getNext() {\n if (this._isFinished) {\n return [];\n }\n const result = await this._fetchData();\n // should never be null, but in practice is sometimes\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (!result.data?.length) {\n this._isFinished = true;\n return [];\n }\n return this._processResult(result);\n }\n /**\n * Gets all data associated to the requested resource.\n *\n * Be aware that this makes multiple calls to the Twitch API. Due to this, you might be more suspectible to rate limits.\n *\n * Also be aware that this resets the internal cursor, so avoid using this and {@link HelixPaginatedRequest#getNext}} together.\n */\n async getAll() {\n this.reset();\n const result = [];\n do {\n const data = await this.getNext();\n if (!data.length) {\n break;\n }\n result.push(...data);\n } while (this._currentCursor);\n this.reset();\n return result;\n }\n /**\n * Gets the current cursor.\n *\n * Only useful if you want to make manual requests to the API.\n */\n get currentCursor() {\n return this._currentCursor;\n }\n /**\n * Resets the internal cursor.\n *\n * This will make {@link HelixPaginatedRequest#getNext}} start from the first page again.\n */\n reset() {\n this._currentCursor = undefined;\n this._isFinished = false;\n this._currentData = undefined;\n }\n async *[Symbol.asyncIterator]() {\n this.reset();\n while (true) {\n const data = await this.getNext();\n if (!data.length) {\n break;\n }\n yield* data[Symbol.iterator]();\n }\n }\n /** @internal */\n async _fetchData(additionalOptions = {}) {\n return await this._client.callApi({\n type: 'helix',\n ...this._callOptions,\n ...additionalOptions,\n query: {\n ...this._callOptions.query,\n after: this._currentCursor,\n first: this._limitPerPage.toString(),\n ...additionalOptions.query,\n },\n });\n }\n /** @internal */\n _processResult(result) {\n this._currentCursor = typeof result.pagination === 'string' ? result.pagination : result.pagination?.cursor;\n if (this._currentCursor === undefined) {\n this._isFinished = true;\n }\n this._currentData = result;\n return result.data.reduce((acc, elem) => {\n const mapped = this._mapper(elem);\n return Array.isArray(mapped) ? [...acc, ...mapped] : [...acc, mapped];\n }, []);\n }\n};\n__decorate([\n Enumerable(false)\n], HelixPaginatedRequest.prototype, \"_client\", void 0);\nHelixPaginatedRequest = __decorate([\n rtfm('api', 'HelixPaginatedRequest')\n], HelixPaginatedRequest);\nexport { HelixPaginatedRequest };\n", "import { __decorate } from \"tslib\";\nimport { rtfm } from '@twurple/common';\nimport { HelixPaginatedRequest } from './HelixPaginatedRequest.js';\n/**\n * A special case of {@link HelixPaginatedRequest} with support for fetching the total number of entities, whenever an endpoint supports it.\n *\n * @inheritDoc\n */\nlet HelixPaginatedRequestWithTotal = class HelixPaginatedRequestWithTotal extends HelixPaginatedRequest {\n /**\n * Gets the total number of entities existing in the queried result set.\n */\n async getTotalCount() {\n const data = this._currentData ??\n (await this._fetchData({ query: { after: undefined } }));\n return data.total;\n }\n};\nHelixPaginatedRequestWithTotal = __decorate([\n rtfm('api', 'HelixPaginatedRequestWithTotal')\n], HelixPaginatedRequestWithTotal);\nexport { HelixPaginatedRequestWithTotal };\n", "/** @internal */ export function createPaginatedResult(response, type, client) {\n let dataCache = undefined;\n return {\n get data() {\n return (dataCache ??= response.data?.map(data => new type(data, client)) ?? []);\n },\n cursor: typeof response.pagination === 'string' ? response.pagination : response.pagination?.cursor,\n };\n}\n/** @internal */ export function createPaginatedResultWithTotal(response, type, client) {\n let dataCache = undefined;\n return {\n get data() {\n return (dataCache ??= response.data?.map(data => new type(data, client)) ?? []);\n },\n cursor: response.pagination.cursor,\n total: response.total,\n };\n}\n", "/** @internal */\nexport function createPaginationQuery({ after, before, limit } = {}) {\n return {\n after,\n before,\n first: limit?.toString(),\n };\n}\n", "import { __decorate } from \"tslib\";\nimport { Enumerable } from '@d-fischer/shared-utils';\nimport { checkRelationAssertion, DataObject, rawDataSymbol, rtfm } from '@twurple/common';\n/**\n * A Twitch channel.\n */\nlet HelixChannel = class HelixChannel extends DataObject {\n /** @internal */ _client;\n /** @internal */\n constructor(data, client) {\n super(data);\n this._client = client;\n }\n /**\n * The ID of the channel.\n */\n get id() {\n return this[rawDataSymbol].broadcaster_id;\n }\n /**\n * The name of the channel.\n */\n get name() {\n return this[rawDataSymbol].broadcaster_login;\n }\n /**\n * The display name of the channel.\n */\n get displayName() {\n return this[rawDataSymbol].broadcaster_name;\n }\n /**\n * Gets more information about the broadcaster of the channel.\n */\n async getBroadcaster() {\n return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].broadcaster_id));\n }\n /**\n * The language of the channel.\n */\n get language() {\n return this[rawDataSymbol].broadcaster_language;\n }\n /**\n * The ID of the game currently played on the channel.\n */\n get gameId() {\n return this[rawDataSymbol].game_id;\n }\n /**\n * The name of the game currently played on the channel.\n */\n get gameName() {\n return this[rawDataSymbol].game_name;\n }\n /**\n * Gets information about the game that is being played on the stream.\n */\n async getGame() {\n return this[rawDataSymbol].game_id\n ? checkRelationAssertion(await this._client.games.getGameById(this[rawDataSymbol].game_id))\n : null;\n }\n /**\n * The title of the channel.\n */\n get title() {\n return this[rawDataSymbol].title;\n }\n /**\n * The stream delay of the channel, in seconds.\n *\n * If you didn't request this with broadcaster access, this is always zero.\n */\n get delay() {\n return this[rawDataSymbol].delay;\n }\n /**\n * The tags applied to the channel.\n */\n get tags() {\n return this[rawDataSymbol].tags;\n }\n /**\n * The content classification labels applied to the channel.\n */\n get contentClassificationLabels() {\n return this[rawDataSymbol].content_classification_labels;\n }\n /**\n * Whether the channel currently displays branded content (as specified by the broadcaster).\n */\n get isBrandedContent() {\n return this[rawDataSymbol].is_branded_content;\n }\n};\n__decorate([\n Enumerable(false)\n], HelixChannel.prototype, \"_client\", void 0);\nHelixChannel = __decorate([\n rtfm('api', 'HelixChannel', 'id')\n], HelixChannel);\nexport { HelixChannel };\n", "import { __decorate } from \"tslib\";\nimport { Enumerable } from '@d-fischer/shared-utils';\nimport { checkRelationAssertion, DataObject, rawDataSymbol, rtfm } from '@twurple/common';\n/**\n * An editor of a previously given channel.\n */\nlet HelixChannelEditor = class HelixChannelEditor extends DataObject {\n /** @internal */ _client;\n /** @internal */\n constructor(data, client) {\n super(data);\n this._client = client;\n }\n /**\n * The ID of the user.\n */\n get userId() {\n return this[rawDataSymbol].user_id;\n }\n /**\n * The display name of the user.\n */\n get userDisplayName() {\n return this[rawDataSymbol].user_name;\n }\n /**\n * Gets additional information about the user.\n */\n async getUser() {\n return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].user_id));\n }\n /**\n * The date when the user was given editor status.\n */\n get creationDate() {\n return new Date(this[rawDataSymbol].created_at);\n }\n};\n__decorate([\n Enumerable(false)\n], HelixChannelEditor.prototype, \"_client\", void 0);\nHelixChannelEditor = __decorate([\n rtfm('api', 'HelixChannelEditor', 'userId')\n], HelixChannelEditor);\nexport { HelixChannelEditor };\n", "import { __decorate } from \"tslib\";\nimport { Enumerable } from '@d-fischer/shared-utils';\nimport { checkRelationAssertion, DataObject, rawDataSymbol, rtfm } from '@twurple/common';\n/**\n * Represents a user that follows a channel.\n */\nlet HelixChannelFollower = class HelixChannelFollower extends DataObject {\n /** @internal */ _client;\n /** @internal */\n constructor(data, client) {\n super(data);\n this._client = client;\n }\n /**\n * The ID of the user.\n */\n get userId() {\n return this[rawDataSymbol].user_id;\n }\n /**\n * The name of the user.\n */\n get userName() {\n return this[rawDataSymbol].user_login;\n }\n /**\n * The display name of the user.\n */\n get userDisplayName() {\n return this[rawDataSymbol].user_name;\n }\n /**\n * Gets additional information about the user.\n */\n async getUser() {\n return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].user_id));\n }\n /**\n * The date when the user followed the broadcaster.\n */\n get followDate() {\n return new Date(this[rawDataSymbol].followed_at);\n }\n};\n__decorate([\n Enumerable(false)\n], HelixChannelFollower.prototype, \"_client\", void 0);\nHelixChannelFollower = __decorate([\n rtfm('api', 'HelixChannelFollower', 'userId')\n], HelixChannelFollower);\nexport { HelixChannelFollower };\n", "import { __decorate } from \"tslib\";\nimport { Enumerable } from '@d-fischer/shared-utils';\nimport { checkRelationAssertion, DataObject, rawDataSymbol, rtfm } from '@twurple/common';\n/**\n * Represents a broadcaster that a user follows.\n */\nlet HelixFollowedChannel = class HelixFollowedChannel extends DataObject {\n /** @internal */ _client;\n /** @internal */\n constructor(data, client) {\n super(data);\n this._client = client;\n }\n /**\n * The ID of the broadcaster.\n */\n get broadcasterId() {\n return this[rawDataSymbol].broadcaster_id;\n }\n /**\n * The name of the broadcaster.\n */\n get broadcasterName() {\n return this[rawDataSymbol].broadcaster_login;\n }\n /**\n * The display name of the broadcaster.\n */\n get broadcasterDisplayName() {\n return this[rawDataSymbol].broadcaster_name;\n }\n /**\n * Gets additional information about the broadcaster.\n */\n async getBroadcaster() {\n return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].broadcaster_id));\n }\n /**\n * The date when the user followed the broadcaster.\n */\n get followDate() {\n return new Date(this[rawDataSymbol].followed_at);\n }\n};\n__decorate([\n Enumerable(false)\n], HelixFollowedChannel.prototype, \"_client\", void 0);\nHelixFollowedChannel = __decorate([\n rtfm('api', 'HelixFollowedChannel', 'broadcasterId')\n], HelixFollowedChannel);\nexport { HelixFollowedChannel };\n", "import { __decorate } from \"tslib\";\nimport { DataObject, rawDataSymbol, rtfm } from '@twurple/common';\n/**\n * Represents a broadcaster's ad schedule.\n */\nlet HelixAdSchedule = class HelixAdSchedule extends DataObject {\n /**\n * The number of snoozes available for the broadcaster.\n */\n get snoozeCount() {\n return this[rawDataSymbol].snooze_count;\n }\n /**\n * The date and time when the broadcaster will gain an additional snooze.\n * Returns `null` if all snoozes are already available.\n */\n get snoozeRefreshDate() {\n return this[rawDataSymbol].snooze_refresh_at ? new Date(this[rawDataSymbol].snooze_refresh_at * 1000) : null;\n }\n /**\n * The date and time of the broadcaster's next scheduled ad.\n * Returns `null` if channel is not live or has no ad scheduled.\n */\n get nextAdDate() {\n return this[rawDataSymbol].next_ad_at ? new Date(this[rawDataSymbol].next_ad_at * 1000) : null;\n }\n /**\n * The length in seconds of the scheduled upcoming ad break.\n */\n get duration() {\n return this[rawDataSymbol].duration;\n }\n /**\n * The date and time of the broadcaster's last ad-break.\n * Returns `null` if channel is not live or has not run an ad.\n */\n get lastAdDate() {\n return this[rawDataSymbol].last_ad_at ? new Date(this[rawDataSymbol].last_ad_at * 1000) : null;\n }\n /**\n * The amount of pre-roll free time remaining for the channel in seconds.\n */\n get prerollFreeTime() {\n return this[rawDataSymbol].preroll_free_time;\n }\n};\nHelixAdSchedule = __decorate([\n rtfm('api', 'HelixAdSchedule')\n], HelixAdSchedule);\nexport { HelixAdSchedule };\n", "import { __decorate } from \"tslib\";\nimport { DataObject, rawDataSymbol, rtfm } from '@twurple/common';\n/**\n * Represents the result after a call to snooze the broadcaster's ad schedule.\n */\nlet HelixSnoozeNextAdResult = class HelixSnoozeNextAdResult extends DataObject {\n /**\n * The number of snoozes remaining for the broadcaster.\n */\n get snoozeCount() {\n return this[rawDataSymbol].snooze_count;\n }\n /**\n * The date and time when the broadcaster will gain an additional snooze.\n */\n get snoozeRefreshDate() {\n return new Date(this[rawDataSymbol].snooze_refresh_at * 1000);\n }\n /**\n * The date and time of the broadcaster's next scheduled ad.\n */\n get nextAdDate() {\n return new Date(this[rawDataSymbol].next_ad_at * 1000);\n }\n};\nHelixSnoozeNextAdResult = __decorate([\n rtfm('api', 'HelixSnoozeNextAdResult')\n], HelixSnoozeNextAdResult);\nexport { HelixSnoozeNextAdResult };\n", "import { __decorate } from \"tslib\";\nimport { createBroadcasterQuery } from '@twurple/api-call';\nimport { extractUserId, rtfm } from '@twurple/common';\nimport { createCustomRewardBody, createCustomRewardChangeQuery, createCustomRewardsQuery, createRedemptionsForBroadcasterQuery, createRewardRedemptionsByIdsQuery, } from '../../interfaces/endpoints/channelPoints.external.js';\nimport { createGetByIdsQuery } from '../../interfaces/endpoints/generic.external.js';\nimport { HelixPaginatedRequest } from '../../utils/pagination/HelixPaginatedRequest.js';\nimport { createPaginatedResult } from '../../utils/pagination/HelixPaginatedResult.js';\nimport { createPaginationQuery } from '../../utils/pagination/HelixPagination.js';\nimport { BaseApi } from '../BaseApi.js';\nimport { HelixCustomReward } from './HelixCustomReward.js';\nimport { HelixCustomRewardRedemption } from './HelixCustomRewardRedemption.js';\n/**\n * The Helix API methods that deal with channel points.\n *\n * Can be accessed using `client.channelPoints` on an {@link ApiClient} instance.\n *\n * ## Example\n * ```ts\n * const api = new ApiClient({ authProvider });\n * const rewards = await api.channelPoints.getCustomRewards('125328655');\n * ```\n *\n * @meta category helix\n * @meta categorizedTitle Channel points\n */\nlet HelixChannelPointsApi = class HelixChannelPointsApi extends BaseApi {\n /**\n * Gets all custom rewards for the given broadcaster.\n *\n * @param broadcaster The broadcaster to get the rewards for.\n * @param onlyManageable Whether to only get rewards that can be managed by the API.\n */\n async getCustomRewards(broadcaster, onlyManageable) {\n const result = await this._client.callApi({\n type: 'helix',\n url: 'channel_points/custom_rewards',\n userId: extractUserId(broadcaster),\n scopes: ['channel:read:redemptions', 'channel:manage:redemptions'],\n query: createCustomRewardsQuery(broadcaster, onlyManageable),\n });\n return result.data.map(data => new HelixCustomReward(data, this._client));\n }\n /**\n * Gets custom rewards by IDs.\n *\n * @param broadcaster The broadcaster to get the rewards for.\n * @param rewardIds The IDs of the rewards.\n */\n async getCustomRewardsByIds(broadcaster, rewardIds) {\n if (!rewardIds.length) {\n return [];\n }\n const result = await this._client.callApi({\n type: 'helix',\n url: 'channel_points/custom_rewards',\n userId: extractUserId(broadcaster),\n scopes: ['channel:read:redemptions', 'channel:manage:redemptions'],\n query: createGetByIdsQuery(broadcaster, rewardIds),\n });\n return result.data.map(data => new HelixCustomReward(data, this._client));\n }\n /**\n * Gets a custom reward by ID.\n *\n * @param broadcaster The broadcaster to get the reward for.\n * @param rewardId The ID of the reward.\n */\n async getCustomRewardById(broadcaster, rewardId) {\n const rewards = await this.getCustomRewardsByIds(broadcaster, [rewardId]);\n return rewards.length ? rewards[0] : null;\n }\n /**\n * Creates a new custom reward.\n *\n * @param broadcaster The broadcaster to create the reward for.\n * @param data The reward data.\n *\n * @expandParams\n */\n async createCustomReward(broadcaster, data) {\n const result = await this._client.callApi({\n type: 'helix',\n url: 'channel_points/custom_rewards',\n method: 'POST',\n userId: extractUserId(broadcaster),\n scopes: ['channel:manage:redemptions'],\n query: createBroadcasterQuery(broadcaster),\n jsonBody: createCustomRewardBody(data),\n });\n return new HelixCustomReward(result.data[0], this._client);\n }\n /**\n * Updates a custom reward.\n *\n * @param broadcaster The broadcaster to update the reward for.\n * @param rewardId The ID of the reward.\n * @param data The reward data.\n */\n async updateCustomReward(broadcaster, rewardId, data) {\n const result = await this._client.callApi({\n type: 'helix',\n url: 'channel_points/custom_rewards',\n method: 'PATCH',\n userId: extractUserId(broadcaster),\n scopes: ['channel:manage:redemptions'],\n query: createCustomRewardChangeQuery(broadcaster, rewardId),\n jsonBody: createCustomRewardBody(data),\n });\n return new HelixCustomReward(result.data[0], this._client);\n }\n /**\n * Deletes a custom reward.\n *\n * @param broadcaster The broadcaster to delete the reward for.\n * @param rewardId The ID of the reward.\n */\n async deleteCustomReward(broadcaster, rewardId) {\n await this._client.callApi({\n type: 'helix',\n url: 'channel_points/custom_rewards',\n method: 'DELETE',\n userId: extractUserId(broadcaster),\n scopes: ['channel:manage:redemptions'],\n query: createCustomRewardChangeQuery(broadcaster, rewardId),\n });\n }\n /**\n * Gets custom reward redemptions by IDs.\n *\n * @param broadcaster The broadcaster to get the redemptions for.\n * @param rewardId The ID of the reward.\n * @param redemptionIds The IDs of the redemptions.\n */\n async getRedemptionsByIds(broadcaster, rewardId, redemptionIds) {\n if (!redemptionIds.length) {\n return [];\n }\n const result = await this._client.callApi({\n type: 'helix',\n url: 'channel_points/custom_rewards/redemptions',\n userId: extractUserId(broadcaster),\n scopes: ['channel:read:redemptions', 'channel:manage:redemptions'],\n query: createRewardRedemptionsByIdsQuery(broadcaster, rewardId, redemptionIds),\n });\n return result.data.map(data => new HelixCustomRewardRedemption(data, this._client));\n }\n /**\n * Gets a custom reward redemption by ID.\n *\n * @param broadcaster The broadcaster to get the redemption for.\n * @param rewardId The ID of the reward.\n * @param redemptionId The ID of the redemption.\n */\n async getRedemptionById(broadcaster, rewardId, redemptionId) {\n const redemptions = await this.getRedemptionsByIds(broadcaster, rewardId, [redemptionId]);\n return redemptions.length ? redemptions[0] : null;\n }\n /**\n * Gets custom reward redemptions for the given broadcaster.\n *\n * @param broadcaster The broadcaster to get the redemptions for.\n * @param rewardId The ID of the reward.\n * @param status The status of the redemptions to get.\n * @param filter\n *\n * @expandParams\n */\n async getRedemptionsForBroadcaster(broadcaster, rewardId, status, filter) {\n const result = await this._client.callApi({\n type: 'helix',\n url: 'channel_points/custom_rewards/redemptions',\n userId: extractUserId(broadcaster),\n scopes: ['channel:read:redemptions', 'channel:manage:redemptions'],\n query: {\n ...createRedemptionsForBroadcasterQuery(broadcaster, rewardId, status, filter),\n ...createPaginationQuery(filter),\n },\n });\n return createPaginatedResult(result, HelixCustomRewardRedemption, this._client);\n }\n /**\n * Creates a paginator for custom reward redemptions for the given broadcaster.\n *\n * @param broadcaster The broadcaster to get the redemptions for.\n * @param rewardId The ID of the reward.\n * @param status The status of the redemptions to get.\n * @param filter\n *\n * @expandParams\n */\n getRedemptionsForBroadcasterPaginated(broadcaster, rewardId, status, filter) {\n return new HelixPaginatedRequest({\n url: 'channel_points/custom_rewards/redemptions',\n userId: extractUserId(broadcaster),\n scopes: ['channel:read:redemptions', 'channel:manage:redemptions'],\n query: createRedemptionsForBroadcasterQuery(broadcaster, rewardId, status, filter),\n }, this._client, data => new HelixCustomRewardRedemption(data, this._client), 50);\n }\n /**\n * Updates the status of the given redemptions by IDs.\n *\n * @param broadcaster The broadcaster to update the redemptions for.\n * @param rewardId The ID of the reward.\n * @param redemptionIds The IDs of the redemptions to update.\n * @param status The status to set for the redemptions.\n */\n async updateRedemptionStatusByIds(broadcaster, rewardId, redemptionIds, status) {\n if (!redemptionIds.length) {\n return [];\n }\n const result = await this._client.callApi({\n type: 'helix',\n url: 'channel_points/custom_rewards/redemptions',\n method: 'PATCH',\n userId: extractUserId(broadcaster),\n scopes: ['channel:manage:redemptions'],\n query: createRewardRedemptionsByIdsQuery(broadcaster, rewardId, redemptionIds),\n jsonBody: {\n status,\n },\n });\n return result.data.map(data => new HelixCustomRewardRedemption(data, this._client));\n }\n};\nHelixChannelPointsApi = __decorate([\n rtfm('api', 'HelixChannelPointsApi')\n], HelixChannelPointsApi);\nexport { HelixChannelPointsApi };\n", "import { extractUserId } from '@twurple/common';\n/** @internal */\nexport function createCustomRewardsQuery(broadcaster, onlyManageable) {\n return {\n broadcaster_id: extractUserId(broadcaster),\n only_manageable_rewards: onlyManageable?.toString(),\n };\n}\n/** @internal */\nexport function createCustomRewardChangeQuery(broadcaster, rewardId) {\n return {\n broadcaster_id: extractUserId(broadcaster),\n id: rewardId,\n };\n}\n/** @internal */\nexport function createCustomRewardBody(data) {\n const result = {\n title: data.title,\n cost: data.cost,\n prompt: data.prompt,\n background_color: data.backgroundColor,\n is_enabled: data.isEnabled,\n is_user_input_required: data.userInputRequired,\n should_redemptions_skip_request_queue: data.autoFulfill,\n };\n if (data.maxRedemptionsPerStream !== undefined) {\n result.is_max_per_stream_enabled = !!data.maxRedemptionsPerStream;\n result.max_per_stream = data.maxRedemptionsPerStream ?? 0;\n }\n if (data.maxRedemptionsPerUserPerStream !== undefined) {\n result.is_max_per_user_per_stream_enabled = !!data.maxRedemptionsPerUserPerStream;\n result.max_per_user_per_stream = data.maxRedemptionsPerUserPerStream ?? 0;\n }\n if (data.globalCooldown !== undefined) {\n result.is_global_cooldown_enabled = !!data.globalCooldown;\n result.global_cooldown_seconds = data.globalCooldown ?? 0;\n }\n if ('isPaused' in data) {\n result.is_paused = data.isPaused;\n }\n return result;\n}\n/** @internal */\nexport function createRewardRedemptionsByIdsQuery(broadcaster, rewardId, redemptionIds) {\n return {\n broadcaster_id: extractUserId(broadcaster),\n reward_id: rewardId,\n id: redemptionIds,\n };\n}\n/** @internal */\nexport function createRedemptionsForBroadcasterQuery(broadcaster, rewardId, status, filter) {\n return {\n broadcaster_id: extractUserId(broadcaster),\n reward_id: rewardId,\n status,\n sort: filter.newestFirst ? 'NEWEST' : 'OLDEST',\n };\n}\n", "import { __decorate } from \"tslib\";\nimport { Enumerable } from '@d-fischer/shared-utils';\nimport { checkRelationAssertion, DataObject, rawDataSymbol, rtfm } from '@twurple/common';\n/**\n * A custom Channel Points reward.\n */\nlet HelixCustomReward = class HelixCustomReward extends DataObject {\n /** @internal */ _client;\n /** @internal */\n constructor(data, client) {\n super(data);\n this._client = client;\n }\n /**\n * The ID of the reward.\n */\n get id() {\n return this[rawDataSymbol].id;\n }\n /**\n * The ID of the broadcaster the reward belongs to.\n */\n get broadcasterId() {\n return this[rawDataSymbol].broadcaster_id;\n }\n /**\n * The name of the broadcaster the reward belongs to.\n */\n get broadcasterName() {\n return this[rawDataSymbol].broadcaster_login;\n }\n /**\n * The display name of the broadcaster the reward belongs to.\n */\n get broadcasterDisplayName() {\n return this[rawDataSymbol].broadcaster_name;\n }\n /**\n * Gets more information about the reward's broadcaster.\n */\n async getBroadcaster() {\n return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].broadcaster_id));\n }\n /**\n * Gets the URL of the image of the reward in the given scale.\n *\n * @param scale The scale of the image.\n */\n getImageUrl(scale) {\n const urlProp = `url_${scale}x`;\n return this[rawDataSymbol].image?.[urlProp] ?? this[rawDataSymbol].default_image[urlProp];\n }\n /**\n * The background color of the reward.\n */\n get backgroundColor() {\n return this[rawDataSymbol].background_color;\n }\n /**\n * Whether the reward is enabled (shown to users).\n */\n get isEnabled() {\n return this[rawDataSymbol].is_enabled;\n }\n /**\n * The channel points cost of the reward.\n */\n get cost() {\n return this[rawDataSymbol].cost;\n }\n /**\n * The title of the reward.\n */\n get title() {\n return this[rawDataSymbol].title;\n }\n /**\n * The prompt shown to users when redeeming the reward.\n */\n get prompt() {\n return this[rawDataSymbol].prompt;\n }\n /**\n * Whether the reward requires user input to be redeemed.\n */\n get userInputRequired() {\n return this[rawDataSymbol].is_user_input_required;\n }\n /**\n * The maximum number of redemptions of the reward per stream. `null` means no limit.\n */\n get maxRedemptionsPerStream() {\n return this[rawDataSymbol].max_per_stream_setting.is_enabled\n ? this[rawDataSymbol].max_per_stream_setting.max_per_stream\n : null;\n }\n /**\n * The maximum number of redemptions of the reward per stream for each user. `null` means no limit.\n */\n get maxRedemptionsPerUserPerStream() {\n return this[rawDataSymbol].max_per_user_per_stream_setting.is_enabled\n ? this[rawDataSymbol].max_per_user_per_stream_setting.max_per_user_per_stream\n : null;\n }\n /**\n * The cooldown between two redemptions of the reward, in seconds. `null` means no cooldown.\n */\n get globalCooldown() {\n return this[rawDataSymbol].global_cooldown_setting.is_enabled\n ? this[rawDataSymbol].global_cooldown_setting.global_cooldown_seconds\n : null;\n }\n /**\n * Whether the reward is paused. If true, users can't redeem it.\n */\n get isPaused() {\n return this[rawDataSymbol].is_paused;\n }\n /**\n * Whether the reward is currently in stock.\n */\n get isInStock() {\n return this[rawDataSymbol].is_in_stock;\n }\n /**\n * How often the reward was already redeemed this stream.\n *\n * Only available when the stream is live and `maxRedemptionsPerStream` is set. Otherwise, this is `null`.\n */\n get redemptionsThisStream() {\n return this[rawDataSymbol].redemptions_redeemed_current_stream;\n }\n /**\n * Whether redemptions should automatically be marked as fulfilled.\n */\n get autoFulfill() {\n return this[rawDataSymbol].should_redemptions_skip_request_queue;\n }\n /**\n * The time when the cooldown ends. `null` means there is currently no cooldown.\n */\n get cooldownExpiryDate() {\n return this[rawDataSymbol].cooldown_expires_at ? new Date(this[rawDataSymbol].cooldown_expires_at) : null;\n }\n};\n__decorate([\n Enumerable(false)\n], HelixCustomReward.prototype, \"_client\", void 0);\nHelixCustomReward = __decorate([\n rtfm('api', 'HelixCustomReward', 'id')\n], HelixCustomReward);\nexport { HelixCustomReward };\n", "import { __decorate } from \"tslib\";\nimport { Enumerable } from '@d-fischer/shared-utils';\nimport { checkRelationAssertion, DataObject, rawDataSymbol, rtfm } from '@twurple/common';\n/**\n * A redemption of a custom Channel Points reward.\n */\nlet HelixCustomRewardRedemption = class HelixCustomRewardRedemption extends DataObject {\n /** @internal */ _client;\n /** @internal */\n constructor(data, client) {\n super(data);\n this._client = client;\n }\n /**\n * The ID of the redemption.\n */\n get id() {\n return this[rawDataSymbol].id;\n }\n /**\n * The ID of the broadcaster where the reward was redeemed.\n */\n get broadcasterId() {\n return this[rawDataSymbol].broadcaster_id;\n }\n /**\n * The name of the broadcaster where the reward was redeemed.\n */\n get broadcasterName() {\n return this[rawDataSymbol].broadcaster_login;\n }\n /**\n * The display name of the broadcaster where the reward was redeemed.\n */\n get broadcasterDisplayName() {\n return this[rawDataSymbol].broadcaster_name;\n }\n /**\n * Gets more information about the broadcaster where the reward was redeemed.\n */\n async getBroadcaster() {\n return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].broadcaster_id));\n }\n /**\n * The ID of the user that redeemed the reward.\n */\n get userId() {\n return this[rawDataSymbol].user_id;\n }\n /**\n * The name of the user that redeemed the reward.\n */\n get userName() {\n return this[rawDataSymbol].user_login;\n }\n /**\n * The display name of the user that redeemed the reward.\n */\n get userDisplayName() {\n return this[rawDataSymbol].user_name;\n }\n /**\n * Gets more information about the user that redeemed the reward.\n */\n async getUser() {\n return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].user_id));\n }\n /**\n * The text the user wrote when redeeming the reward.\n */\n get userInput() {\n return this[rawDataSymbol].user_input;\n }\n /**\n * Whether the redemption was fulfilled.\n */\n get isFulfilled() {\n return this[rawDataSymbol].status === 'FULFILLED';\n }\n /**\n * Whether the redemption was canceled.\n */\n get isCanceled() {\n return this[rawDataSymbol].status === 'CANCELED';\n }\n /**\n * The date and time when the reward was redeemed.\n */\n get redemptionDate() {\n return new Date(this[rawDataSymbol].redeemed_at);\n }\n /**\n * The ID of the reward that was redeemed.\n */\n get rewardId() {\n return this[rawDataSymbol].reward.id;\n }\n /**\n * The title of the reward that was redeemed.\n */\n get rewardTitle() {\n return this[rawDataSymbol].reward.title;\n }\n /**\n * The prompt of the reward that was redeemed.\n */\n get rewardPrompt() {\n return this[rawDataSymbol].reward.prompt;\n }\n /**\n * The cost of the reward that was redeemed.\n */\n get rewardCost() {\n return this[rawDataSymbol].reward.cost;\n }\n /**\n * Gets more information about the reward that was redeemed.\n */\n async getReward() {\n return checkRelationAssertion(await this._client.channelPoints.getCustomRewardById(this[rawDataSymbol].broadcaster_id, this[rawDataSymbol].reward.id));\n }\n /**\n * Updates the redemption's status.\n *\n * @param newStatus The status the redemption should have.\n */\n async updateStatus(newStatus) {\n const result = await this._client.channelPoints.updateRedemptionStatusByIds(this[rawDataSymbol].broadcaster_id, this[rawDataSymbol].reward.id, [this[rawDataSymbol].id], newStatus);\n return result[0];\n }\n};\n__decorate([\n Enumerable(false)\n], HelixCustomRewardRedemption.prototype, \"_client\", void 0);\nHelixCustomRewardRedemption = __decorate([\n rtfm('api', 'HelixCustomRewardRedemption', 'id')\n], HelixCustomRewardRedemption);\nexport { HelixCustomRewardRedemption };\n", "import { __decorate } from \"tslib\";\nimport { createBroadcasterQuery } from '@twurple/api-call';\nimport { extractUserId, rtfm } from '@twurple/common';\nimport { createPaginatedResult } from '../../utils/pagination/HelixPaginatedResult.js';\nimport { createPaginationQuery } from '../../utils/pagination/HelixPagination.js';\nimport { BaseApi } from '../BaseApi.js';\nimport { HelixCharityCampaign } from './HelixCharityCampaign.js';\nimport { HelixCharityCampaignDonation } from './HelixCharityCampaignDonation.js';\n/**\n * The Helix API methods that deal with charity campaigns.\n *\n * Can be accessed using `client.charity` on an {@link ApiClient} instance.\n *\n * ## Example\n * ```ts\n * const api = new ApiClient({ authProvider });\n * const charityCampaign = await api.charity.getCharityCampaign('125328655');\n * ```\n *\n * @meta category helix\n * @meta categorizedTitle Charity Campaigns\n */\nlet HelixCharityApi = class HelixCharityApi extends BaseApi {\n /**\n * Gets information about the charity campaign that a broadcaster is running.\n * Returns null if the specified broadcaster has no active charity campaign.\n *\n * @param broadcaster The broadcaster to get charity campaign information about.\n */\n async getCharityCampaign(broadcaster) {\n const response = await this._client.callApi({\n type: 'helix',\n url: 'charity/campaigns',\n method: 'GET',\n userId: extractUserId(broadcaster),\n scopes: ['channel:read:charity'],\n query: createBroadcasterQuery(broadcaster),\n });\n return new HelixCharityCampaign(response.data[0], this._client);\n }\n /**\n * Gets the list of donations that users have made to the broadcaster\u2019s active charity campaign.\n *\n * @param broadcaster The broadcaster to get charity campaign donation information about.\n * @param pagination\n *\n * @expandParams\n */\n async getCharityCampaignDonations(broadcaster, pagination) {\n const response = await this._client.callApi({\n type: 'helix',\n url: 'charity/donations',\n userId: extractUserId(broadcaster),\n scopes: ['channel:read:charity'],\n query: {\n ...createBroadcasterQuery(broadcaster),\n ...createPaginationQuery(pagination),\n },\n });\n return createPaginatedResult(response, HelixCharityCampaignDonation, this._client);\n }\n};\nHelixCharityApi = __decorate([\n rtfm('api', 'HelixCharityApi')\n], HelixCharityApi);\nexport { HelixCharityApi };\n", "import { __decorate } from \"tslib\";\nimport { Enumerable } from '@d-fischer/shared-utils';\nimport { checkRelationAssertion, DataObject, rawDataSymbol, rtfm } from '@twurple/common';\nimport { HelixCharityCampaignAmount } from './HelixCharityCampaignAmount.js';\n/**\n * A charity campaign in a Twitch channel.\n */\nlet HelixCharityCampaign = class HelixCharityCampaign extends DataObject {\n /** @internal */ _client;\n /** @internal */\n constructor(data, client) {\n super(data);\n this._client = client;\n }\n /**\n * An ID that identifies the charity campaign.\n */\n get id() {\n return this[rawDataSymbol].id;\n }\n /**\n * The ID of the broadcaster.\n */\n get broadcasterId() {\n return this[rawDataSymbol].broadcaster_id;\n }\n /**\n * The name of the broadcaster.\n */\n get broadcasterName() {\n return this[rawDataSymbol].broadcaster_login;\n }\n /**\n * The display name of the broadcaster.\n */\n get broadcasterDisplayName() {\n return this[rawDataSymbol].broadcaster_name;\n }\n /**\n * Gets more information about the broadcaster.\n */\n async getBroadcaster() {\n return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].broadcaster_id));\n }\n /**\n * The name of the charity.\n */\n get charityName() {\n return this[rawDataSymbol].charity_name;\n }\n /**\n * A description of the charity.\n */\n get charityDescription() {\n return this[rawDataSymbol].charity_description;\n }\n /**\n * A URL to an image of the charity's logo. The image\u2019s type is PNG and its size is 100px X 100px.\n */\n get charityLogo() {\n return this[rawDataSymbol].charity_logo;\n }\n /**\n * A URL to the charity\u2019s website.\n */\n get charityWebsite() {\n return this[rawDataSymbol].charity_website;\n }\n /**\n * An object that contains the current amount of donations that the campaign has received.\n */\n get currentAmount() {\n return new HelixCharityCampaignAmount(this[rawDataSymbol].current_amount);\n }\n /**\n * An object that contains the campaign\u2019s target fundraising goal.\n */\n get targetAmount() {\n return new HelixCharityCampaignAmount(this[rawDataSymbol].target_amount);\n }\n};\n__decorate([\n Enumerable(false)\n], HelixCharityCampaign.prototype, \"_client\", void 0);\nHelixCharityCampaign = __decorate([\n rtfm('api', 'HelixCharityCampaign', 'id')\n], HelixCharityCampaign);\nexport { HelixCharityCampaign };\n", "import { __decorate } from \"tslib\";\nimport { DataObject, rawDataSymbol, rtfm } from '@twurple/common';\n/**\n * An object representing monetary amount and currency information for charity donations/goals.\n */\nlet HelixCharityCampaignAmount = class HelixCharityCampaignAmount extends DataObject {\n /**\n * The monetary amount. The amount is specified in the currency\u2019s minor unit.\n * For example, the minor units for USD is cents, so if the amount is $5.50 USD, `value` is set to 550.\n */\n get value() {\n return this[rawDataSymbol].value;\n }\n /**\n * The number of decimal places used by the currency. For example, USD uses two decimal places.\n * Use this number to translate `value` from minor units to major units by using the formula:\n *\n * `value / 10^decimalPlaces`\n */\n get decimalPlaces() {\n return this[rawDataSymbol].decimal_places;\n }\n /**\n * The localized monetary amount based on the value and the decimal places of the currency.\n * For example, the minor units for USD is cents which uses two decimal places, so if `value` is 550, `localizedValue` is set to 5.50.\n */\n get localizedValue() {\n return this.value / 10 ** this.decimalPlaces;\n }\n /**\n * The ISO-4217 three-letter currency code that identifies the type of currency in `value`.\n */\n get currency() {\n return this[rawDataSymbol].currency;\n }\n};\nHelixCharityCampaignAmount = __decorate([\n rtfm('api', 'HelixCharityCampaignAmount')\n], HelixCharityCampaignAmount);\nexport { HelixCharityCampaignAmount };\n", "import { __decorate } from \"tslib\";\nimport { Enumerable } from '@d-fischer/shared-utils';\nimport { checkRelationAssertion, DataObject, rawDataSymbol, rtfm } from '@twurple/common';\nimport { HelixCharityCampaignAmount } from './HelixCharityCampaignAmount.js';\n/**\n * A donation to a charity campaign in a Twitch channel.\n */\nlet HelixCharityCampaignDonation = class HelixCharityCampaignDonation extends DataObject {\n /** @internal */ _client;\n /** @internal */\n constructor(data, client) {\n super(data);\n this._client = client;\n }\n /**\n * An ID that identifies the charity campaign.\n */\n get campaignId() {\n return this[rawDataSymbol].campaign_id;\n }\n /**\n * The ID of the donating user.\n */\n get donorId() {\n return this[rawDataSymbol].user_id;\n }\n /**\n * The name of the donating user.\n */\n get donorName() {\n return this[rawDataSymbol].user_login;\n }\n /**\n * The display name of the donating user.\n */\n get donorDisplayName() {\n return this[rawDataSymbol].user_name;\n }\n /**\n * Gets more information about the donating user.\n */\n async getDonor() {\n return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].user_id));\n }\n /**\n * An object that contains the amount of money that the user donated.\n */\n get amount() {\n return new HelixCharityCampaignAmount(this[rawDataSymbol].amount);\n }\n};\n__decorate([\n Enumerable(false)\n], HelixCharityCampaignDonation.prototype, \"_client\", void 0);\nHelixCharityCampaignDonation = __decorate([\n rtfm('api', 'HelixCharityCampaignDonation')\n], HelixCharityCampaignDonation);\nexport { HelixCharityCampaignDonation };\n", "import { __decorate } from \"tslib\";\nimport { createBroadcasterQuery } from '@twurple/api-call';\nimport { extractUserId, rtfm } from '@twurple/common';\nimport { ChatMessageDroppedError } from '../../errors/ChatMessageDroppedError.js';\nimport { createChatColorUpdateQuery, createChatSettingsUpdateBody, createSendChatMessageAsAppBody, createSendChatMessageBody, createSendChatMessageQuery, createShoutoutQuery, } from '../../interfaces/endpoints/chat.external.js';\nimport { createModeratorActionQuery, createSingleKeyQuery } from '../../interfaces/endpoints/generic.external.js';\nimport { createSharedChatSessionQuery, } from '../../interfaces/endpoints/shared-chat-session.external.js';\nimport { HelixPaginatedRequest } from '../../utils/pagination/HelixPaginatedRequest.js';\nimport { HelixPaginatedRequestWithTotal } from '../../utils/pagination/HelixPaginatedRequestWithTotal.js';\nimport { createPaginatedResult, createPaginatedResultWithTotal, } from '../../utils/pagination/HelixPaginatedResult.js';\nimport { createPaginationQuery } from '../../utils/pagination/HelixPagination.js';\nimport { BaseApi } from '../BaseApi.js';\nimport { HelixChannelEmote } from './HelixChannelEmote.js';\nimport { HelixChatBadgeSet } from './HelixChatBadgeSet.js';\nimport { HelixChatChatter } from './HelixChatChatter.js';\nimport { HelixChatSettings } from './HelixChatSettings.js';\nimport { HelixEmote } from './HelixEmote.js';\nimport { HelixEmoteFromSet } from './HelixEmoteFromSet.js';\nimport { HelixPrivilegedChatSettings } from './HelixPrivilegedChatSettings.js';\nimport { HelixSentChatMessage } from './HelixSentChatMessage.js';\nimport { HelixSharedChatSession } from './HelixSharedChatSession.js';\nimport { HelixUserEmote } from './HelixUserEmote.js';\n/**\n * The Helix API methods that deal with chat.\n *\n * Can be accessed using `client.chat` on an {@link ApiClient} instance.\n *\n * ## Example\n * ```ts\n * const api = new ApiClient({ authProvider });\n * const rewards = await api.chat.getChannelBadges('125328655');\n * ```\n *\n * @meta category helix\n * @meta categorizedTitle Chat\n */\nlet HelixChatApi = class HelixChatApi extends BaseApi {\n /**\n * Gets the list of users that are connected to the broadcaster\u2019s chat session.\n *\n * This uses the token of the broadcaster by default.\n * If you want to execute this in the context of another user (who has to be moderator of the channel)\n * you can do so using [user context overrides](/docs/auth/concepts/context-switching).\n *\n * @param broadcaster The broadcaster whose list of chatters you want to get.\n * @param pagination\n *\n * @expandParams\n */\n async getChatters(broadcaster, pagination) {\n const broadcasterId = extractUserId(broadcaster);\n const result = await this._client.callApi({\n type: 'helix',\n url: 'chat/chatters',\n userId: broadcasterId,\n canOverrideScopedUserContext: true,\n scopes: ['moderator:read:chatters'],\n query: {\n ...this._createModeratorActionQuery(broadcasterId),\n ...createPaginationQuery(pagination),\n },\n });\n return createPaginatedResultWithTotal(result, HelixChatChatter, this._client);\n }\n /**\n * Creates a paginator for users that are connected to the broadcaster\u2019s chat session.\n *\n * This uses the token of the broadcaster by default.\n * If you want to execute this in the context of another user (who has to be moderator of the channel)\n * you can do so using [user context overrides](/docs/auth/concepts/context-switching).\n *\n * @param broadcaster The broadcaster whose list of chatters you want to get.\n *\n * @expandParams\n */\n getChattersPaginated(broadcaster) {\n const broadcasterId = extractUserId(broadcaster);\n return new HelixPaginatedRequestWithTotal({\n url: 'chat/chatters',\n userId: broadcasterId,\n canOverrideScopedUserContext: true,\n scopes: ['moderator:read:chatters'],\n query: this._createModeratorActionQuery(broadcasterId),\n }, this._client, data => new HelixChatChatter(data, this._client), 1000);\n }\n /**\n * Gets all global badges.\n */\n async getGlobalBadges() {\n const result = await this._client.callApi({\n type: 'helix',\n url: 'chat/badges/global',\n });\n return result.data.map(data => new HelixChatBadgeSet(data));\n }\n /**\n * Gets all badges specific to the given broadcaster.\n *\n * @param broadcaster The broadcaster to get badges for.\n */\n async getChannelBadges(broadcaster) {\n const result = await this._client.callApi({\n type: 'helix',\n url: 'chat/badges',\n userId: extractUserId(broadcaster),\n query: createBroadcasterQuery(broadcaster),\n });\n return result.data.map(data => new HelixChatBadgeSet(data));\n }\n /**\n * Gets all global emotes.\n */\n async getGlobalEmotes() {\n const result = await this._client.callApi({\n type: 'helix',\n url: 'chat/emotes/global',\n });\n return result.data.map(data => new HelixEmote(data));\n }\n /**\n * Gets all emotes specific to the given broadcaster.\n *\n * @param broadcaster The broadcaster to get emotes for.\n */\n async getChannelEmotes(broadcaster) {\n const result = await this._client.callApi({\n type: 'helix',\n url: 'chat/emotes',\n userId: extractUserId(broadcaster),\n query: createBroadcasterQuery(broadcaster),\n });\n return result.data.map(data => new HelixChannelEmote(data, this._client));\n }\n /**\n * Gets all emotes from a list of emote sets.\n *\n * @param setIds The IDs of the emote sets to get emotes from.\n */\n async getEmotesFromSets(setIds) {\n const result = await this._client.callApi({\n type: 'helix',\n url: 'chat/emotes/set',\n query: createSingleKeyQuery('emote_set_id', setIds),\n });\n return result.data.map(data => new HelixEmoteFromSet(data, this._client));\n }\n /**\n * Gets emotes available to the user across all channels.\n *\n * @param user The ID of the user to get available emotes of.\n * @param filter Additional query filters.\n */\n async getUserEmotes(user, filter) {\n const userId = extractUserId(user);\n const result = await this._client.callApi({\n type: 'helix',\n url: 'chat/emotes/user',\n userId: extractUserId(user),\n scopes: ['user:read:emotes'],\n query: {\n ...createSingleKeyQuery('user_id', userId),\n ...createSingleKeyQuery('broadcasterId', filter?.broadcaster ? extractUserId(filter.broadcaster) : undefined),\n ...createPaginationQuery(filter),\n },\n });\n return createPaginatedResult(result, HelixUserEmote, this._client);\n }\n /**\n * Creates a paginator for emotes available to the user across all channels.\n *\n * @param user The ID of the user to get available emotes of.\n * @param broadcaster The ID of a broadcaster you wish to get follower emotes of. Using this query parameter will\n * guarantee inclusion of the broadcaster\u2019s follower emotes in the response body.\n *\n * If the user who retrieves their emotes is subscribed to the broadcaster specified, their follower emotes will\n * appear in the response body regardless of whether this query parameter is used.\n */\n getUserEmotesPaginated(user, broadcaster) {\n const userId = extractUserId(user);\n return new HelixPaginatedRequest({\n url: 'chat/emotes/user',\n userId,\n scopes: ['user:read:emotes'],\n query: {\n ...createSingleKeyQuery('user_id', userId),\n ...createSingleKeyQuery('broadcasterId', broadcaster ? extractUserId(broadcaster) : undefined),\n },\n }, this._client, (data) => new HelixUserEmote(data, this._client));\n }\n /**\n * Gets the settings of a broadcaster's chat.\n *\n * @param broadcaster The broadcaster the chat belongs to.\n */\n async getSettings(broadcaster) {\n const result = await this._client.callApi({\n type: 'helix',\n url: 'chat/settings',\n userId: extractUserId(broadcaster),\n query: createBroadcasterQuery(broadcaster),\n });\n return new HelixChatSettings(result.data[0]);\n }\n /**\n * Gets the settings of a broadcaster's chat, including the delay settings.\n *\n * This uses the token of the broadcaster by default.\n * If you want to execute this in the context of another user (who has to be moderator of the channel)\n * you can do so using [user context overrides](/docs/auth/concepts/context-switching).\n *\n * @param broadcaster The broadcaster the chat belongs to.\n */\n async getSettingsPrivileged(broadcaster) {\n const broadcasterId = extractUserId(broadcaster);\n const result = await this._client.callApi({\n type: 'helix',\n url: 'chat/settings',\n userId: broadcasterId,\n canOverrideScopedUserContext: true,\n scopes: ['moderator:read:chat_settings'],\n query: this._createModeratorActionQuery(broadcasterId),\n });\n return new HelixPrivilegedChatSettings(result.data[0]);\n }\n /**\n * Updates the settings of a broadcaster's chat.\n *\n * This uses the token of the broadcaster by default.\n * If you want to execute this in the context of another user (who has to be moderator of the channel)\n * you can do so using [user context overrides](/docs/auth/concepts/context-switching).\n *\n * @expandParams\n *\n * @param broadcaster The broadcaster the chat belongs to.\n * @param settings The settings to change.\n */\n async updateSettings(broadcaster, settings) {\n const broadcasterId = extractUserId(broadcaster);\n const result = await this._client.callApi({\n type: 'helix',\n url: 'chat/settings',\n method: 'PATCH',\n userId: broadcasterId,\n canOverrideScopedUserContext: true,\n scopes: ['moderator:manage:chat_settings'],\n query: this._createModeratorActionQuery(broadcasterId),\n jsonBody: createChatSettingsUpdateBody(settings),\n });\n return new HelixPrivilegedChatSettings(result.data[0]);\n }\n /**\n * Sends a chat message to a broadcaster's chat.\n *\n * This uses the token of the broadcaster by default.\n * If you want to execute this in the context of another user\n * you can do so using [user context overrides](/docs/auth/concepts/context-switching).\n *\n * @expandParams\n *\n * @param broadcaster The broadcaster the chat belongs to.\n * @param message The message to send.\n * @param params\n */\n async sendChatMessage(broadcaster, message, params) {\n const broadcasterId = extractUserId(broadcaster);\n const result = await this._client.callApi({\n type: 'helix',\n url: 'chat/messages',\n method: 'POST',\n userId: broadcasterId,\n canOverrideScopedUserContext: true,\n scopes: ['user:write:chat'],\n query: createSendChatMessageQuery(broadcasterId, this._getUserContextIdWithDefault(broadcasterId)),\n jsonBody: createSendChatMessageBody(message, params),\n });\n const msg = new HelixSentChatMessage(result.data[0]);\n this._handleUnsentChatMessage(broadcasterId, msg);\n return msg;\n }\n /**\n * Sends a chat message to a broadcaster's chat, using an app token.\n *\n * This requires the scopes `user:write:chat` and `user:bot` for the `user` and `channel:bot` for the `broadcaster`.\n * `channel:bot` is not required if the `user` has moderator privileges in the `broadcaster`'s channel.\n *\n * These scope requirements can not be checked by the library, so they are just assumed.\n * Make sure to catch authorization errors yourself.\n *\n * @expandParams\n *\n * @param user The user to send the chat message from.\n * @param broadcaster The broadcaster the chat belongs to.\n * @param message The message to send.\n * @param params\n */\n async sendChatMessageAsApp(user, broadcaster, message, params) {\n const userId = extractUserId(user);\n const broadcasterId = extractUserId(broadcaster);\n const result = await this._client.callApi({\n type: 'helix',\n url: 'chat/messages',\n method: 'POST',\n forceType: 'app',\n query: createSendChatMessageQuery(broadcasterId, userId),\n jsonBody: createSendChatMessageAsAppBody(message, params),\n });\n const msg = new HelixSentChatMessage(result.data[0]);\n this._handleUnsentChatMessage(broadcasterId, msg);\n return msg;\n }\n /**\n * Sends an announcement to a broadcaster's chat.\n *\n * This uses the token of the broadcaster by default.\n * If you want to execute this in the context of another user (who has to be moderator of the channel)\n * you can do so using [user context overrides](/docs/auth/concepts/context-switching).\n *\n * @param broadcaster The broadcaster the chat belongs to.\n * @param announcement The announcement to send.\n */\n async sendAnnouncement(broadcaster, announcement) {\n const broadcasterId = extractUserId(broadcaster);\n await this._client.callApi({\n type: 'helix',\n url: 'chat/announcements',\n method: 'POST',\n userId: broadcasterId,\n canOverrideScopedUserContext: true,\n scopes: ['moderator:manage:announcements'],\n query: this._createModeratorActionQuery(broadcasterId),\n jsonBody: {\n message: announcement.message,\n color: announcement.color,\n },\n });\n }\n /**\n * Gets the chat colors for a list of users.\n *\n * Returns a Map with user IDs as keys and their colors as values.\n * The value is a color hex code, or `null` if the user did not set a color,\n * and unknown users will not be present in the map.\n *\n * @param users The users to get the chat colors of.\n */\n async getColorsForUsers(users) {\n const response = await this._client.callApi({\n type: 'helix',\n url: 'chat/color',\n query: createSingleKeyQuery('user_id', users.map(extractUserId)),\n });\n return new Map(response.data.map(data => [data.user_id, data.color || null]));\n }\n /**\n * Gets the chat color for a user.\n *\n * Returns the color as hex code, `null` if the user did not set a color, or `undefined` if the user is unknown.\n *\n * @param user The user to get the chat color of.\n */\n async getColorForUser(user) {\n const response = await this._client.callApi({\n type: 'helix',\n url: 'chat/color',\n userId: extractUserId(user),\n query: createSingleKeyQuery('user_id', extractUserId(user)),\n });\n if (!response.data.length) {\n return undefined;\n }\n return response.data[0].color || null;\n }\n /**\n * Changes the chat color for a user.\n *\n * @param user The user to change the color of.\n * @param color The color to set.\n *\n * Note that hex codes can only be used by users that have a Prime or Turbo subscription.\n */\n async setColorForUser(user, color) {\n await this._client.callApi({\n type: 'helix',\n url: 'chat/color',\n method: 'PUT',\n userId: extractUserId(user),\n scopes: ['user:manage:chat_color'],\n query: createChatColorUpdateQuery(user, color),\n });\n }\n /**\n * Sends a shoutout to the specified broadcaster.\n * The broadcaster may send a shoutout once every 2 minutes. They may send the same broadcaster a shoutout once every 60 minutes.\n *\n * This uses the token of the broadcaster by default.\n * If you want to execute this in the context of another user (who has to be moderator of the channel)\n * you can do so using [user context overrides](/docs/auth/concepts/context-switching).\n *\n * @param from The ID of the broadcaster that\u2019s sending the shoutout.\n * @param to The ID of the broadcaster that\u2019s receiving the shoutout.\n */\n async shoutoutUser(from, to) {\n const fromId = extractUserId(from);\n await this._client.callApi({\n type: 'helix',\n url: 'chat/shoutouts',\n method: 'POST',\n userId: fromId,\n canOverrideScopedUserContext: true,\n scopes: ['moderator:manage:shoutouts'],\n query: createShoutoutQuery(from, to, this._getUserContextIdWithDefault(fromId)),\n });\n }\n /**\n * Gets the active shared chat session for a channel.\n *\n * Returns `null` if there is no active shared chat session in the channel.\n *\n * @param broadcaster The broadcaster to get the active shared chat session for.\n */\n async getSharedChatSession(broadcaster) {\n const broadcasterId = extractUserId(broadcaster);\n const response = await this._client.callApi({\n type: 'helix',\n url: 'shared_chat/session',\n userId: broadcasterId,\n query: createSharedChatSessionQuery(broadcasterId),\n });\n if (response.data.length === 0) {\n return null;\n }\n return new HelixSharedChatSession(response.data[0], this._client);\n }\n _createModeratorActionQuery(broadcasterId) {\n return createModeratorActionQuery(broadcasterId, this._getUserContextIdWithDefault(broadcasterId));\n }\n _handleUnsentChatMessage(broadcasterId, msg) {\n if (!msg.isSent) {\n throw new ChatMessageDroppedError(broadcasterId, msg.dropReasonMessage, msg.dropReasonCode);\n }\n }\n};\nHelixChatApi = __decorate([\n rtfm('api', 'HelixChatApi')\n], HelixChatApi);\nexport { HelixChatApi };\n", "import { CustomError } from '@twurple/common';\n/**\n * Thrown when a chat message is dropped and not delivered to the target channel.\n */\nexport class ChatMessageDroppedError extends CustomError {\n _code;\n constructor(broadcasterId, message, code) {\n super(`Chat message to channel ${broadcasterId} dropped: ${message ?? 'unknown reason'}`);\n this._code = code;\n }\n get code() {\n return this._code;\n }\n}\n", "import { extractUserId } from '@twurple/common';\n/** @internal */\nexport function createChatSettingsUpdateBody(settings) {\n return {\n slow_mode: settings.slowModeEnabled,\n slow_mode_wait_time: settings.slowModeDelay,\n follower_mode: settings.followerOnlyModeEnabled,\n follower_mode_duration: settings.followerOnlyModeDelay,\n subscriber_mode: settings.subscriberOnlyModeEnabled,\n emote_mode: settings.emoteOnlyModeEnabled,\n unique_chat_mode: settings.uniqueChatModeEnabled,\n non_moderator_chat_delay: settings.nonModeratorChatDelayEnabled,\n non_moderator_chat_delay_duration: settings.nonModeratorChatDelay,\n };\n}\n/** @internal */\nexport function createChatColorUpdateQuery(user, color) {\n return {\n user_id: extractUserId(user),\n color,\n };\n}\n/** @internal */\nexport function createShoutoutQuery(from, to, moderatorId) {\n return {\n from_broadcaster_id: extractUserId(from),\n to_broadcaster_id: extractUserId(to),\n moderator_id: moderatorId,\n };\n}\n/** @internal */\nexport function createSendChatMessageQuery(broadcaster, sender) {\n return {\n broadcaster_id: broadcaster,\n sender_id: sender,\n };\n}\n/** @internal */\nexport function createSendChatMessageBody(message, params) {\n return {\n message,\n reply_parent_message_id: params?.replyParentMessageId,\n };\n}\n/** @internal */\nexport function createSendChatMessageAsAppBody(message, params) {\n return {\n message,\n reply_parent_message_id: params?.replyParentMessageId,\n for_source_only: params?.forSourceOnly,\n };\n}\n", "import { extractUserId } from '@twurple/common';\n/** @internal */\nexport function createSharedChatSessionQuery(broadcaster) {\n return {\n broadcaster_id: extractUserId(broadcaster),\n };\n}\n", "import { __decorate } from \"tslib\";\nimport { Enumerable } from '@d-fischer/shared-utils';\nimport { rawDataSymbol, rtfm } from '@twurple/common';\nimport { HelixEmote } from './HelixEmote.js';\n/**\n * A Twitch Channel emote.\n *\n * @inheritDoc\n */\nlet HelixChannelEmote = class HelixChannelEmote extends HelixEmote {\n /** @internal */ _client;\n constructor(data, client) {\n super(data);\n this._client = client;\n }\n /**\n * The subscription tier necessary to unlock the emote, or null if the emote is not a subscription emote.\n */\n get tier() {\n return this[rawDataSymbol].tier || null;\n }\n /**\n * The type of the emote.\n *\n * There are many types of emotes that Twitch seems to arbitrarily assign. Do not rely on this value.\n */\n get type() {\n return this[rawDataSymbol].emote_type;\n }\n /**\n * The ID of the emote set the emote is part of.\n */\n get emoteSetId() {\n return this[rawDataSymbol].emote_set_id;\n }\n /**\n * Gets all emotes from the emote's set.\n */\n async getAllEmotesFromSet() {\n return await this._client.chat.getEmotesFromSets([this[rawDataSymbol].emote_set_id]);\n }\n};\n__decorate([\n Enumerable(false)\n], HelixChannelEmote.prototype, \"_client\", void 0);\nHelixChannelEmote = __decorate([\n rtfm('api', 'HelixChannelEmote', 'id')\n], HelixChannelEmote);\nexport { HelixChannelEmote };\n", "import { __decorate } from \"tslib\";\nimport { rawDataSymbol, rtfm } from '@twurple/common';\nimport { HelixEmoteBase } from './HelixEmoteBase.js';\n/**\n * A Twitch emote.\n */\nlet HelixEmote = class HelixEmote extends HelixEmoteBase {\n /**\n * Gets the URL of the emote image in the given scale.\n *\n * @param scale The scale of the image.\n */\n getImageUrl(scale) {\n return this[rawDataSymbol].images[`url_${scale}x`];\n }\n};\nHelixEmote = __decorate([\n rtfm('api', 'HelixEmote', 'id')\n], HelixEmote);\nexport { HelixEmote };\n", "import { DataObject, rawDataSymbol } from '@twurple/common';\n/** @private */\nexport class HelixEmoteBase extends DataObject {\n /**\n * The ID of the emote.\n */\n get id() {\n return this[rawDataSymbol].id;\n }\n /**\n * The name of the emote.\n */\n get name() {\n return this[rawDataSymbol].name;\n }\n /**\n * The formats that the emote is available in.\n */\n get formats() {\n return this[rawDataSymbol].format;\n }\n /**\n * The scales that the emote is available in.\n */\n get scales() {\n return this[rawDataSymbol].scale;\n }\n /**\n * The theme modes that the emote is available in.\n */\n get themeModes() {\n return this[rawDataSymbol].theme_mode;\n }\n /**\n * Gets the URL of the emote image in static format at the given scale and theme mode, or null if a static emote image at that scale/theme mode doesn't exist.\n *\n * @param scale The scale of the image.\n * @param themeMode The theme mode of the image, either `light` or `dark`.\n */\n getStaticImageUrl(scale = '1.0', themeMode = 'light') {\n if (this[rawDataSymbol].format.includes('static') && this[rawDataSymbol].scale.includes(scale)) {\n return this.getFormattedImageUrl(scale, 'static', themeMode);\n }\n return null;\n }\n /**\n * Gets the URL of the emote image in animated format at the given scale and theme mode, or null if an animated emote image at that scale/theme mode doesn't exist.\n *\n * @param scale The scale of the image.\n * @param themeMode The theme mode of the image, either `light` or `dark`.\n */\n getAnimatedImageUrl(scale = '1.0', themeMode = 'light') {\n if (this[rawDataSymbol].format.includes('animated') && this[rawDataSymbol].scale.includes(scale)) {\n return this.getFormattedImageUrl(scale, 'animated', themeMode);\n }\n return null;\n }\n /**\n * Gets the URL of the emote image in the given scale, format, and theme mode.\n *\n * @param scale The scale of the image, either `1.0` (small), `2.0` (medium), or `3.0` (large).\n * @param format The format of the image, either `static` or `animated`.\n * @param themeMode The theme mode of the image, either `light` or `dark`.\n */\n getFormattedImageUrl(scale = '1.0', format = 'static', themeMode = 'light') {\n return `https://static-cdn.jtvnw.net/emoticons/v2/${this[rawDataSymbol].id}/${format}/${themeMode}/${scale}`;\n }\n}\n", "import { __decorate } from \"tslib\";\nimport { Cacheable, CachedGetter } from '@d-fischer/cache-decorators';\nimport { DataObject, rawDataSymbol, rtfm } from '@twurple/common';\nimport { HelixChatBadgeVersion } from './HelixChatBadgeVersion.js';\n/**\n * A version of a chat badge.\n */\nlet HelixChatBadgeSet = class HelixChatBadgeSet extends DataObject {\n /**\n * The badge set ID.\n */\n get id() {\n return this[rawDataSymbol].set_id;\n }\n /**\n * All versions of the badge.\n */\n get versions() {\n return this[rawDataSymbol].versions.map(data => new HelixChatBadgeVersion(data));\n }\n /**\n * Gets a specific version of the badge.\n *\n * @param versionId The ID of the version.\n */\n getVersion(versionId) {\n return this.versions.find(v => v.id === versionId) ?? null;\n }\n};\n__decorate([\n CachedGetter()\n], HelixChatBadgeSet.prototype, \"versions\", null);\nHelixChatBadgeSet = __decorate([\n Cacheable,\n rtfm('api', 'HelixChatBadgeSet', 'id')\n], HelixChatBadgeSet);\nexport { HelixChatBadgeSet };\n", "import { __decorate } from \"tslib\";\nimport { DataObject, rawDataSymbol, rtfm } from '@twurple/common';\n/**\n * A version of a chat badge.\n */\nlet HelixChatBadgeVersion = class HelixChatBadgeVersion extends DataObject {\n /**\n * The badge version ID.\n */\n get id() {\n return this[rawDataSymbol].id;\n }\n /**\n * Gets an image URL for the given scale.\n *\n * @param scale The scale of the badge image.\n */\n getImageUrl(scale) {\n return this[rawDataSymbol][`image_url_${scale}x`];\n }\n /**\n * The title of the badge.\n */\n get title() {\n return this[rawDataSymbol].title;\n }\n /**\n * The description of the badge.\n */\n get description() {\n return this[rawDataSymbol].description;\n }\n /**\n * The action to take when clicking on the badge. Set to `null` if no action is specified.\n */\n get clickAction() {\n return this[rawDataSymbol].click_action;\n }\n /**\n * The URL to navigate to when clicking on the badge. Set to `null` if no URL is specified.\n */\n get clickUrl() {\n return this[rawDataSymbol].click_url;\n }\n};\nHelixChatBadgeVersion = __decorate([\n rtfm('api', 'HelixChatBadgeVersion', 'id')\n], HelixChatBadgeVersion);\nexport { HelixChatBadgeVersion };\n", "import { __decorate } from \"tslib\";\nimport { Enumerable } from '@d-fischer/shared-utils';\nimport { checkRelationAssertion, DataObject, rawDataSymbol, rtfm } from '@twurple/common';\n/**\n * A user connected to a Twitch channel's chat session.\n */\nlet HelixChatChatter = class HelixChatChatter extends DataObject {\n /** @internal */ _client;\n /** @internal */\n constructor(data, client) {\n super(data);\n this._client = client;\n }\n /**\n * The ID of the user.\n */\n get userId() {\n return this[rawDataSymbol].user_id;\n }\n /**\n * The name of the user.\n */\n get userName() {\n return this[rawDataSymbol].user_login;\n }\n /**\n * The display name of the user.\n */\n get userDisplayName() {\n return this[rawDataSymbol].user_name;\n }\n /**\n * Gets more information about the user.\n */\n async getUser() {\n return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].user_id));\n }\n};\n__decorate([\n Enumerable(false)\n], HelixChatChatter.prototype, \"_client\", void 0);\nHelixChatChatter = __decorate([\n rtfm('api', 'HelixChatChatter')\n], HelixChatChatter);\nexport { HelixChatChatter };\n", "import { __decorate } from \"tslib\";\nimport { DataObject, rawDataSymbol, rtfm } from '@twurple/common';\n/**\n * The settings of a broadcaster's chat.\n */\nlet HelixChatSettings = class HelixChatSettings extends DataObject {\n /**\n * The ID of the broadcaster.\n */\n get broadcasterId() {\n return this[rawDataSymbol].broadcaster_id;\n }\n /**\n * Whether slow mode is enabled.\n */\n get slowModeEnabled() {\n return this[rawDataSymbol].slow_mode;\n }\n /**\n * The time to wait between messages in slow mode, in seconds.\n *\n * Is `null` if slow mode is not enabled.\n */\n get slowModeDelay() {\n return this[rawDataSymbol].slow_mode_wait_time;\n }\n /**\n * Whether follower only mode is enabled.\n */\n get followerOnlyModeEnabled() {\n return this[rawDataSymbol].follower_mode;\n }\n /**\n * The time after which users are able to send messages after following, in minutes.\n *\n * Is `null` if follower only mode is not enabled,\n * but may also be `0` if you can send messages immediately after following.\n */\n get followerOnlyModeDelay() {\n return this[rawDataSymbol].follower_mode_duration;\n }\n /**\n * Whether subscriber only mode is enabled.\n */\n get subscriberOnlyModeEnabled() {\n return this[rawDataSymbol].subscriber_mode;\n }\n /**\n * Whether emote only mode is enabled.\n */\n get emoteOnlyModeEnabled() {\n return this[rawDataSymbol].emote_mode;\n }\n /**\n * Whether unique chat mode is enabled.\n */\n get uniqueChatModeEnabled() {\n return this[rawDataSymbol].unique_chat_mode;\n }\n};\nHelixChatSettings = __decorate([\n rtfm('api', 'HelixChatSettings', 'broadcasterId')\n], HelixChatSettings);\nexport { HelixChatSettings };\n", "import { __decorate } from \"tslib\";\nimport { Enumerable } from '@d-fischer/shared-utils';\nimport { rawDataSymbol, rtfm } from '@twurple/common';\nimport { HelixEmote } from './HelixEmote.js';\n/**\n * A Twitch Channel emote.\n *\n * @inheritDoc\n */\nlet HelixEmoteFromSet = class HelixEmoteFromSet extends HelixEmote {\n /** @internal */ _client;\n constructor(data, client) {\n super(data);\n this._client = client;\n }\n /**\n * The type of the emote.\n *\n * Known values are: `subscriptions`, `bitstier`, `follower`, `rewards`, `globals`, `smilies`, `prime`, `limitedtime`.\n *\n * This list may be non-exhaustive.\n */\n get type() {\n return this[rawDataSymbol].emote_type;\n }\n /**\n * The ID of the emote set the emote is part of.\n */\n get emoteSetId() {\n return this[rawDataSymbol].emote_set_id;\n }\n /**\n * The ID of the user that owns the emote, or null if the emote is not owned by a user.\n */\n get ownerId() {\n switch (this[rawDataSymbol].owner_id) {\n case '0':\n case 'twitch': {\n return null;\n }\n default: {\n return this[rawDataSymbol].owner_id;\n }\n }\n }\n /**\n * Gets more information about the user that owns the emote, or null if the emote is not owned by a user.\n */\n async getOwner() {\n switch (this[rawDataSymbol].owner_id) {\n case '0':\n case 'twitch': {\n return null;\n }\n default: {\n return await this._client.users.getUserById(this[rawDataSymbol].owner_id);\n }\n }\n }\n};\n__decorate([\n Enumerable(false)\n], HelixEmoteFromSet.prototype, \"_client\", void 0);\nHelixEmoteFromSet = __decorate([\n rtfm('api', 'HelixEmoteFromSet', 'id')\n], HelixEmoteFromSet);\nexport { HelixEmoteFromSet };\n", "import { __decorate } from \"tslib\";\nimport { rawDataSymbol, rtfm } from '@twurple/common';\nimport { HelixChatSettings } from './HelixChatSettings.js';\n/**\n * The settings of a broadcaster's chat, with additional privileged data.\n */\nlet HelixPrivilegedChatSettings = class HelixPrivilegedChatSettings extends HelixChatSettings {\n /**\n * Whether non-moderator messages are delayed.\n */\n get nonModeratorChatDelayEnabled() {\n return this[rawDataSymbol].non_moderator_chat_delay;\n }\n /**\n * The delay of non-moderator messages, in seconds.\n *\n * Is `null` if non-moderator message delay is disabled.\n */\n get nonModeratorChatDelay() {\n return this[rawDataSymbol].non_moderator_chat_delay_duration;\n }\n};\nHelixPrivilegedChatSettings = __decorate([\n rtfm('api', 'HelixPrivilegedChatSettings', 'broadcasterId')\n], HelixPrivilegedChatSettings);\nexport { HelixPrivilegedChatSettings };\n", "import { __decorate } from \"tslib\";\nimport { DataObject, rawDataSymbol, rtfm } from '@twurple/common';\n/**\n * Information about a sent Twitch chat message.\n */\nlet HelixSentChatMessage = class HelixSentChatMessage extends DataObject {\n /**\n * The message ID of the sent message.\n */\n get id() {\n return this[rawDataSymbol].message_id;\n }\n /**\n * If the message passed all checks and was sent.\n */\n get isSent() {\n return this[rawDataSymbol].is_sent;\n }\n /**\n * The reason code for why the chat message was dropped, if dropped.\n */\n get dropReasonCode() {\n return this[rawDataSymbol].drop_reason?.code;\n }\n /**\n * The reason message for why the chat message was dropped, if dropped.\n */\n get dropReasonMessage() {\n return this[rawDataSymbol].drop_reason?.message;\n }\n};\nHelixSentChatMessage = __decorate([\n rtfm('api', 'HelixSentChatMessage', 'id')\n], HelixSentChatMessage);\nexport { HelixSentChatMessage };\n", "import { __decorate } from \"tslib\";\nimport { Enumerable } from '@d-fischer/shared-utils';\nimport { checkRelationAssertion, DataObject, rawDataSymbol, rtfm } from '@twurple/common';\nimport { HelixSharedChatSessionParticipant } from './HelixSharedChatSessionParticipant.js';\n/**\n * A shared chat session.\n */\nlet HelixSharedChatSession = class HelixSharedChatSession extends DataObject {\n /** @internal */ _client;\n /** @internal */\n constructor(data, client) {\n super(data);\n this._client = client;\n }\n /**\n * The unique identifier for the shared chat session.\n */\n get sessionId() {\n return this[rawDataSymbol].session_id;\n }\n /**\n * The ID of the host broadcaster.\n */\n get hostBroadcasterId() {\n return this[rawDataSymbol].host_broadcaster_id;\n }\n /**\n * Gets information about the host broadcaster.\n */\n async getHostBroadcaster() {\n return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].host_broadcaster_id));\n }\n /**\n * The list of participants in the session.\n */\n get participants() {\n return this[rawDataSymbol].participants.map(data => new HelixSharedChatSessionParticipant(data, this._client));\n }\n /**\n * The date for when the session was created.\n */\n get createdDate() {\n return new Date(this[rawDataSymbol].created_at);\n }\n /**\n * The date for when the session was updated.\n */\n get updatedDate() {\n return new Date(this[rawDataSymbol].updated_at);\n }\n};\n__decorate([\n Enumerable(false)\n], HelixSharedChatSession.prototype, \"_client\", void 0);\nHelixSharedChatSession = __decorate([\n rtfm('api', 'HelixSharedChatSession', 'sessionId')\n], HelixSharedChatSession);\nexport { HelixSharedChatSession };\n", "import { __decorate } from \"tslib\";\nimport { Enumerable } from '@d-fischer/shared-utils';\nimport { checkRelationAssertion, DataObject, rawDataSymbol, rtfm } from '@twurple/common';\n/**\n * A shared chat session participant.\n */\nlet HelixSharedChatSessionParticipant = class HelixSharedChatSessionParticipant extends DataObject {\n /** @internal */ _client;\n /** @internal */\n constructor(data, client) {\n super(data);\n this._client = client;\n }\n /**\n * The ID of the participant broadcaster.\n */\n get broadcasterId() {\n return this[rawDataSymbol].broadcaster_id;\n }\n /**\n * Gets information about the participant broadcaster.\n */\n async getBroadcaster() {\n return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].broadcaster_id));\n }\n};\n__decorate([\n Enumerable(false)\n], HelixSharedChatSessionParticipant.prototype, \"_client\", void 0);\nHelixSharedChatSessionParticipant = __decorate([\n rtfm('api', 'HelixSharedChatSessionParticipant', 'broadcasterId')\n], HelixSharedChatSessionParticipant);\nexport { HelixSharedChatSessionParticipant };\n", "import { __decorate } from \"tslib\";\nimport { rawDataSymbol, rtfm } from '@twurple/common';\nimport { HelixEmoteBase } from './HelixEmoteBase.js';\nimport { Enumerable } from '@d-fischer/shared-utils';\n/**\n * A Twitch user emote.\n */\nlet HelixUserEmote = class HelixUserEmote extends HelixEmoteBase {\n /** @internal */ _client;\n constructor(data, client) {\n super(data);\n this._client = client;\n }\n /**\n * The type of the emote.\n *\n * There are many types of emotes that Twitch seems to arbitrarily assign.\n * Check the relevant values in the official documentation.\n *\n * @see https://dev.twitch.tv/docs/api/reference/#get-user-emotes\n */\n get type() {\n return this[rawDataSymbol].emote_type;\n }\n /**\n * The ID that identifies the emote set that the emote belongs to, or `null` if the emote is not from any set.\n */\n get emoteSetId() {\n return this[rawDataSymbol].emote_set_id || null;\n }\n /**\n * The ID of the broadcaster who owns the emote, or `null` if the emote has no owner, e.g. it's a global emote.\n */\n get ownerId() {\n return this[rawDataSymbol].owner_id || null;\n }\n /**\n * Gets all emotes from the emotes set, or `null` if emote is not from any set.\n */\n async getAllEmotesFromSet() {\n return this[rawDataSymbol].emote_set_id\n ? await this._client.chat.getEmotesFromSets([this[rawDataSymbol].emote_set_id])\n : null;\n }\n /**\n * Gets more information about the user that owns the emote, or `null` if the emote is not owned by a user.\n */\n async getOwner() {\n return this[rawDataSymbol].owner_id ? await this._client.users.getUserById(this[rawDataSymbol].owner_id) : null;\n }\n};\n__decorate([\n Enumerable(false)\n], HelixUserEmote.prototype, \"_client\", void 0);\nHelixUserEmote = __decorate([\n rtfm('api', 'HelixUserEmote', 'id')\n], HelixUserEmote);\nexport { HelixUserEmote };\n", "import { __decorate } from \"tslib\";\nimport { Enumerable } from '@d-fischer/shared-utils';\nimport { extractUserId, rtfm } from '@twurple/common';\nimport { createClipCreateFromVodQuery, createClipCreateQuery, createClipQuery, } from '../../interfaces/endpoints/clip.external.js';\nimport { HelixRequestBatcher } from '../../utils/HelixRequestBatcher.js';\nimport { HelixPaginatedRequest } from '../../utils/pagination/HelixPaginatedRequest.js';\nimport { createPaginatedResult } from '../../utils/pagination/HelixPaginatedResult.js';\nimport { createPaginationQuery } from '../../utils/pagination/HelixPagination.js';\nimport { BaseApi } from '../BaseApi.js';\nimport { HelixClip } from './HelixClip.js';\n/**\n * The Helix API methods that deal with clips.\n *\n * Can be accessed using `client.clips` on an {@link ApiClient} instance.\n *\n * ## Example\n * ```ts\n * const api = new ApiClient({ authProvider });\n * const clipId = await api.clips.createClip({ channel: '125328655' });\n * ```\n *\n * @meta category helix\n * @meta categorizedTitle Clips\n */\nlet HelixClipApi = class HelixClipApi extends BaseApi {\n /** @internal */\n _getClipByIdBatcher = new HelixRequestBatcher({\n url: 'clips',\n }, 'id', 'id', this._client, (data) => new HelixClip(data, this._client));\n /**\n * Gets clips for the specified broadcaster in descending order of views.\n *\n * @param broadcaster The broadcaster to fetch clips for.\n * @param filter\n *\n * @expandParams\n */\n async getClipsForBroadcaster(broadcaster, filter = {}) {\n return await this._getClips({\n ...filter,\n filterType: 'broadcaster_id',\n ids: extractUserId(broadcaster),\n userId: extractUserId(broadcaster),\n });\n }\n /**\n * Creates a paginator for clips for the specified broadcaster.\n *\n * @param broadcaster The broadcaster to fetch clips for.\n * @param filter\n *\n * @expandParams\n */\n getClipsForBroadcasterPaginated(broadcaster, filter = {}) {\n return this._getClipsPaginated({\n ...filter,\n filterType: 'broadcaster_id',\n ids: extractUserId(broadcaster),\n userId: extractUserId(broadcaster),\n });\n }\n /**\n * Gets clips for the specified game in descending order of views.\n *\n * @param gameId The game ID.\n * @param filter\n *\n * @expandParams\n */\n async getClipsForGame(gameId, filter = {}) {\n return await this._getClips({\n ...filter,\n filterType: 'game_id',\n ids: gameId,\n });\n }\n /**\n * Creates a paginator for clips for the specified game.\n *\n * @param gameId The game ID.\n * @param filter\n *\n * @expandParams\n */\n getClipsForGamePaginated(gameId, filter = {}) {\n return this._getClipsPaginated({\n ...filter,\n filterType: 'game_id',\n ids: gameId,\n });\n }\n /**\n * Gets the clips identified by the given IDs.\n *\n * @param ids The clip IDs.\n */\n async getClipsByIds(ids) {\n const result = await this._getClips({\n filterType: 'id',\n ids,\n });\n return result.data;\n }\n /**\n * Gets the clip identified by the given ID.\n *\n * @param id The clip ID.\n */\n async getClipById(id) {\n const clips = await this.getClipsByIds([id]);\n return clips.length ? clips[0] : null;\n }\n /**\n * Gets the clip identified by the given ID, batching multiple calls into fewer requests as the API allows.\n *\n * @param id The clip ID.\n */\n async getClipByIdBatched(id) {\n return await this._getClipByIdBatcher.request(id);\n }\n /**\n * Creates a clip of a running stream.\n *\n * Returns the ID of the clip.\n *\n * @param params\n * @expandParams\n */\n async createClip(params) {\n const result = await this._client.callApi({\n type: 'helix',\n url: 'clips',\n method: 'POST',\n userId: extractUserId(params.channel),\n scopes: ['clips:edit'],\n canOverrideScopedUserContext: true,\n query: createClipCreateQuery(params),\n });\n return result.data[0].id;\n }\n /**\n * Creates a clip of a VOD.\n *\n * Returns the ID of the clip.\n *\n * @param params\n * @expandParams\n */\n async createClipFromVod(params) {\n const broadcasterId = extractUserId(params.channel);\n const result = await this._client.callApi({\n type: 'helix',\n url: 'videos/clips',\n method: 'POST',\n userId: broadcasterId,\n scopes: ['editor:manage:clips', 'channel:manage:clips'],\n canOverrideScopedUserContext: true,\n query: createClipCreateFromVodQuery(params, this._getUserContextIdWithDefault(broadcasterId)),\n });\n return result.data[0].id;\n }\n async _getClips(params) {\n if (!params.ids.length) {\n return { data: [] };\n }\n const result = await this._client.callApi({\n type: 'helix',\n url: 'clips',\n userId: params.userId,\n query: {\n ...createClipQuery(params),\n ...createPaginationQuery(params),\n },\n });\n return createPaginatedResult(result, HelixClip, this._client);\n }\n _getClipsPaginated(params) {\n return new HelixPaginatedRequest({\n url: 'clips',\n userId: params.userId,\n query: createClipQuery(params),\n }, this._client, data => new HelixClip(data, this._client));\n }\n};\n__decorate([\n Enumerable(false)\n], HelixClipApi.prototype, \"_getClipByIdBatcher\", void 0);\nHelixClipApi = __decorate([\n rtfm('api', 'HelixClipApi')\n], HelixClipApi);\nexport { HelixClipApi };\n", "import { extractUserId } from '@twurple/common';\n/** @internal */\nexport function createClipCreateQuery(params) {\n const { channel, createAfterDelay = false, title, duration } = params;\n return {\n broadcaster_id: extractUserId(channel),\n has_delay: createAfterDelay.toString(),\n title,\n duration: duration?.toFixed(1),\n };\n}\n/** @internal */\nexport function createClipCreateFromVodQuery(params, editorId) {\n const { channel, title, duration, vodId, vodOffset } = params;\n return {\n broadcaster_id: extractUserId(channel),\n editor_id: editorId,\n title,\n duration: duration?.toFixed(1),\n vod_id: vodId,\n vod_offset: vodOffset.toString(),\n };\n}\n/** @internal */\nexport function createClipQuery(params) {\n const { filterType, ids, startDate, endDate, isFeatured } = params;\n return {\n [filterType]: ids,\n started_at: startDate,\n ended_at: endDate,\n is_featured: isFeatured?.toString(),\n };\n}\n", "import { __decorate } from \"tslib\";\nimport { Enumerable } from '@d-fischer/shared-utils';\nimport { checkRelationAssertion, DataObject, rawDataSymbol, rtfm } from '@twurple/common';\n/**\n * A clip from a Twitch stream.\n */\nlet HelixClip = class HelixClip extends DataObject {\n /** @internal */ _client;\n /** @internal */\n constructor(data, client) {\n super(data);\n this._client = client;\n }\n /**\n * The clip ID.\n */\n get id() {\n return this[rawDataSymbol].id;\n }\n /**\n * The URL of the clip.\n */\n get url() {\n return this[rawDataSymbol].url;\n }\n /**\n * The embed URL of the clip.\n */\n get embedUrl() {\n return this[rawDataSymbol].embed_url;\n }\n /**\n * The user ID of the broadcaster of the stream where the clip was created.\n */\n get broadcasterId() {\n return this[rawDataSymbol].broadcaster_id;\n }\n /**\n * The display name of the broadcaster of the stream where the clip was created.\n */\n get broadcasterDisplayName() {\n return this[rawDataSymbol].broadcaster_name;\n }\n /**\n * Gets information about the broadcaster of the stream where the clip was created.\n */\n async getBroadcaster() {\n return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].broadcaster_id));\n }\n /**\n * The user ID of the creator of the clip.\n */\n get creatorId() {\n return this[rawDataSymbol].creator_id;\n }\n /**\n * The display name of the creator of the clip.\n */\n get creatorDisplayName() {\n return this[rawDataSymbol].creator_name;\n }\n /**\n * Gets information about the creator of the clip.\n */\n async getCreator() {\n return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].creator_id));\n }\n /**\n * The ID of the video the clip is taken from.\n */\n get videoId() {\n return this[rawDataSymbol].video_id;\n }\n /**\n * Gets information about the video the clip is taken from.\n */\n async getVideo() {\n return checkRelationAssertion(await this._client.videos.getVideoById(this[rawDataSymbol].video_id));\n }\n /**\n * The ID of the game that was being played when the clip was created.\n */\n get gameId() {\n return this[rawDataSymbol].game_id;\n }\n /**\n * Gets information about the game that was being played when the clip was created.\n */\n async getGame() {\n return this[rawDataSymbol].game_id\n ? checkRelationAssertion(await this._client.games.getGameById(this[rawDataSymbol].game_id))\n : null;\n }\n /**\n * The language of the stream where the clip was created.\n */\n get language() {\n return this[rawDataSymbol].language;\n }\n /**\n * The title of the clip.\n */\n get title() {\n return this[rawDataSymbol].title;\n }\n /**\n * The number of views of the clip.\n */\n get views() {\n return this[rawDataSymbol].view_count;\n }\n /**\n * The date when the clip was created.\n */\n get creationDate() {\n return new Date(this[rawDataSymbol].created_at);\n }\n /**\n * The URL of the thumbnail of the clip.\n */\n get thumbnailUrl() {\n return this[rawDataSymbol].thumbnail_url;\n }\n /**\n * The duration of the clip in seconds (up to 0.1 precision).\n */\n get duration() {\n return this[rawDataSymbol].duration;\n }\n /**\n * The offset of the clip from the start of the corresponding VOD, in seconds.\n *\n * This may be null if there is no VOD or if the clip is created from a live broadcast,\n * in which case it may take a few minutes to associate with the VOD.\n */\n get vodOffset() {\n return this[rawDataSymbol].vod_offset;\n }\n /**\n * Whether the clip is featured.\n */\n get isFeatured() {\n return this[rawDataSymbol].is_featured;\n }\n};\n__decorate([\n Enumerable(false)\n], HelixClip.prototype, \"_client\", void 0);\nHelixClip = __decorate([\n rtfm('api', 'HelixClip', 'id')\n], HelixClip);\nexport { HelixClip };\n", "import { __decorate } from \"tslib\";\nimport { rtfm } from '@twurple/common';\nimport { BaseApi } from '../BaseApi.js';\nimport { HelixContentClassificationLabel } from './HelixContentClassificationLabel.js';\n/**\n * The Helix API methods that deal with content classification labels.\n *\n * Can be accessed using `client.contentClassificationLabels` on an {@link ApiClient} instance.\n *\n * ## Example\n * ```ts\n * const api = new ApiClient({ authProvider });\n * const labels = await api.contentClassificationLabels.getAll();\n * ```\n *\n * @meta category helix\n * @meta categorizedTitle Content classification labels\n */\nlet HelixContentClassificationLabelApi = class HelixContentClassificationLabelApi extends BaseApi {\n /**\n * Fetches a list of all content classification labels.\n *\n * @param locale The locale for the content classification labels.\n */\n async getAll(locale) {\n const result = await this._client.callApi({\n url: 'content_classification_labels',\n query: {\n locale,\n },\n });\n return result.data.map(data => new HelixContentClassificationLabel(data));\n }\n};\nHelixContentClassificationLabelApi = __decorate([\n rtfm('api', 'HelixContentClassificationLabelApi')\n], HelixContentClassificationLabelApi);\nexport { HelixContentClassificationLabelApi };\n", "import { DataObject, rawDataSymbol } from '@twurple/common';\n/**\n * A content classification label that can be applied to a Twitch stream.\n */\nexport class HelixContentClassificationLabel extends DataObject {\n /**\n * The ID of the content classification label.\n */\n get id() {\n return this[rawDataSymbol].id;\n }\n /**\n * The name of the content classification label.\n */\n get name() {\n return this[rawDataSymbol].name;\n }\n /**\n * The description of the content classification label.\n */\n get description() {\n return this[rawDataSymbol].description;\n }\n}\n", "import { __decorate } from \"tslib\";\nimport { Enumerable, mapOptional } from '@d-fischer/shared-utils';\nimport { extractUserId, rtfm } from '@twurple/common';\nimport { createDropsEntitlementQuery, createDropsEntitlementUpdateBody, } from '../../interfaces/endpoints/entitlement.external.js';\nimport { HelixRequestBatcher } from '../../utils/HelixRequestBatcher.js';\nimport { HelixPaginatedRequest } from '../../utils/pagination/HelixPaginatedRequest.js';\nimport { createPaginatedResult } from '../../utils/pagination/HelixPaginatedResult.js';\nimport { createPaginationQuery } from '../../utils/pagination/HelixPagination.js';\nimport { BaseApi } from '../BaseApi.js';\nimport { HelixDropsEntitlement } from './HelixDropsEntitlement.js';\n/**\n * The Helix API methods that deal with entitlements (drops).\n *\n * Can be accessed using `client.entitlements` on an {@link ApiClient} instance.\n *\n * ## Example\n * ```ts\n * const api = new ApiClient({ authProvider });\n * const clipId = await api.entitlements.getDropsEntitlements();\n * ```\n *\n * @meta category helix\n * @meta categorizedTitle Entitlements (Drops)\n */\nlet HelixEntitlementApi = class HelixEntitlementApi extends BaseApi {\n /** @internal */ _getDropsEntitlementByIdBatcher = new HelixRequestBatcher({\n url: 'entitlements/drops',\n }, 'id', 'id', this._client, (data) => new HelixDropsEntitlement(data, this._client));\n /**\n * Gets the drops entitlements for the given filter.\n *\n * @expandParams\n *\n * @param filter\n * @param alwaysApp Whether an app token should always be used, even if a user filter is given.\n */\n async getDropsEntitlements(filter, alwaysApp = false) {\n const response = await this._client.callApi({\n type: 'helix',\n url: 'entitlements/drops',\n userId: mapOptional(filter.user, extractUserId),\n forceType: filter.user && alwaysApp ? 'app' : undefined,\n query: {\n ...createDropsEntitlementQuery(filter, alwaysApp),\n ...createPaginationQuery(filter),\n },\n });\n return createPaginatedResult(response, HelixDropsEntitlement, this._client);\n }\n /**\n * Creates a paginator for drops entitlements for the given filter.\n *\n * @expandParams\n *\n * @param filter\n * @param alwaysApp Whether an app token should always be used, even if a user filter is given.\n */\n getDropsEntitlementsPaginated(filter, alwaysApp = false) {\n return new HelixPaginatedRequest({\n url: 'entitlements/drops',\n userId: mapOptional(filter.user, extractUserId),\n forceType: filter.user && alwaysApp ? 'app' : undefined,\n query: createDropsEntitlementQuery(filter, alwaysApp),\n }, this._client, data => new HelixDropsEntitlement(data, this._client));\n }\n /**\n * Gets the drops entitlements for the given IDs.\n *\n * @param ids The IDs to fetch.\n */\n async getDropsEntitlementsByIds(ids) {\n const response = await this._client.callApi({\n type: 'helix',\n url: 'entitlements/drops',\n query: {\n id: ids,\n },\n });\n return response.data.map(data => new HelixDropsEntitlement(data, this._client));\n }\n /**\n * Gets the drops entitlement for the given ID.\n *\n * @param id The ID to fetch.\n */\n async getDropsEntitlementById(id) {\n const result = await this.getDropsEntitlementsByIds([id]);\n return result[0] ?? null;\n }\n /**\n * Gets the drops entitlement for the given ID, batching multiple calls into fewer requests as the API allows.\n *\n * @param id The ID to fetch.\n */\n async getDropsEntitlementByIdBatched(id) {\n return await this._getDropsEntitlementByIdBatcher.request(id);\n }\n /**\n * Updates the status of a list of drops entitlements.\n *\n * Returns a map that associates each given ID with its update status.\n *\n * @param ids The IDs of the entitlements.\n * @param fulfillmentStatus The fulfillment status to set the entitlements to.\n */\n async updateDropsEntitlements(ids, fulfillmentStatus) {\n const response = await this._client.callApi({\n type: 'helix',\n url: 'entitlements/drops',\n method: 'PATCH',\n jsonBody: createDropsEntitlementUpdateBody(ids, fulfillmentStatus),\n });\n return new Map(response.data.flatMap(entry => entry.ids.map(id => [id, entry.status])));\n }\n};\n__decorate([\n Enumerable(false)\n], HelixEntitlementApi.prototype, \"_getDropsEntitlementByIdBatcher\", void 0);\nHelixEntitlementApi = __decorate([\n rtfm('api', 'HelixEntitlementApi')\n], HelixEntitlementApi);\nexport { HelixEntitlementApi };\n", "import { mapOptional } from '@d-fischer/shared-utils';\nimport { extractUserId } from '@twurple/common';\n/** @internal */\nexport function createDropsEntitlementQuery(filters, alwaysApp) {\n return {\n user_id: alwaysApp ? mapOptional(filters.user, extractUserId) : undefined,\n game_id: filters.gameId,\n fulfillment_status: filters.fulfillmentStatus,\n };\n}\n/** @internal */\nexport function createDropsEntitlementUpdateBody(ids, fulfillmentStatus) {\n return {\n fulfillment_status: fulfillmentStatus,\n entitlement_ids: ids,\n };\n}\n", "import { __decorate } from \"tslib\";\nimport { Enumerable } from '@d-fischer/shared-utils';\nimport { checkRelationAssertion, DataObject, rawDataSymbol, rtfm } from '@twurple/common';\n/**\n * An entitlement for a drop.\n */\nlet HelixDropsEntitlement = class HelixDropsEntitlement extends DataObject {\n /** @internal */ _client;\n /** @internal */\n constructor(data, client) {\n super(data);\n this._client = client;\n }\n /**\n * The ID of the entitlement.\n */\n get id() {\n return this[rawDataSymbol].id;\n }\n /**\n * The ID of the reward.\n */\n get rewardId() {\n return this[rawDataSymbol].benefit_id;\n }\n /**\n * The date when the entitlement was granted.\n */\n get grantDate() {\n return new Date(this[rawDataSymbol].timestamp);\n }\n /**\n * The ID of the entitled user.\n */\n get userId() {\n return this[rawDataSymbol].user_id;\n }\n /**\n * Gets more information about the entitled user.\n */\n async getUser() {\n return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].user_id));\n }\n /**\n * The ID of the game the entitlement was granted for.\n */\n get gameId() {\n return this[rawDataSymbol].game_id;\n }\n /**\n * Gets more information about the game the entitlement was granted for.\n */\n async getGame() {\n return checkRelationAssertion(await this._client.games.getGameById(this[rawDataSymbol].game_id));\n }\n /**\n * The fulfillment status of the entitlement.\n */\n get fulfillmentStatus() {\n return this[rawDataSymbol].fulfillment_status;\n }\n /**\n * The date when the entitlement was last updated.\n */\n get updateDate() {\n return new Date(this[rawDataSymbol].last_updated);\n }\n};\n__decorate([\n Enumerable(false)\n], HelixDropsEntitlement.prototype, \"_client\", void 0);\nHelixDropsEntitlement = __decorate([\n rtfm('api', 'HelixDropsEntitlement')\n], HelixDropsEntitlement);\nexport { HelixDropsEntitlement };\n", "import { __decorate } from \"tslib\";\nimport { mapOptional } from '@d-fischer/shared-utils';\nimport { extractUserId, rtfm } from '@twurple/common';\nimport { createEventSubBroadcasterCondition, createEventSubDropEntitlementGrantCondition, createEventSubModeratorCondition, createEventSubRewardCondition, createEventSubUserCondition, createEventSubConduitCondition, createEventSubConduitUpdateCondition, createEventSubConduitShardsUpdateCondition, } from '../../interfaces/endpoints/eventSub.external.js';\nimport { createSingleKeyQuery } from '../../interfaces/endpoints/generic.external.js';\nimport { HelixPaginatedRequest } from '../../utils/pagination/HelixPaginatedRequest.js';\nimport { createPaginatedResultWithTotal, createPaginatedResult } from '../../utils/pagination/HelixPaginatedResult.js';\nimport { createPaginationQuery } from '../../utils/pagination/HelixPagination.js';\nimport { BaseApi } from '../BaseApi.js';\nimport { HelixEventSubSubscription } from './HelixEventSubSubscription.js';\nimport { HelixPaginatedEventSubSubscriptionsRequest } from './HelixPaginatedEventSubSubscriptionsRequest.js';\nimport { HelixEventSubConduit } from './HelixEventSubConduit.js';\nimport { HelixEventSubConduitShard } from './HelixEventSubConduitShard.js';\n/**\n * The API methods that deal with EventSub.\n *\n * Can be accessed using `client.eventSub` on an {@link ApiClient} instance.\n *\n * ## Before using these methods...\n *\n * All methods in this class assume that you are already running a working EventSub listener reachable using the given transport.\n *\n * If you don't already have one, we recommend use of the `@twurple/eventsub-http` or `@twurple/eventsub-ws` libraries,\n * which handle subscribing and unsubscribing to these topics automatically.\n *\n * ## Example\n * ```ts\n * const api = new ApiClient({ authProvider });\n * await api.eventSub.subscribeToUserFollowsTo('125328655', { callbackUrl: 'https://example.com' });\n * ```\n *\n * @meta category helix\n * @meta categorizedTitle EventSub\n */\nlet HelixEventSubApi = class HelixEventSubApi extends BaseApi {\n /**\n * Gets the current EventSub subscriptions for the current client.\n *\n * @param pagination\n *\n * @expandParams\n */\n async getSubscriptions(pagination) {\n const result = await this._client.callApi({\n type: 'helix',\n url: 'eventsub/subscriptions',\n query: createPaginationQuery(pagination),\n });\n return {\n ...createPaginatedResultWithTotal(result, HelixEventSubSubscription, this._client),\n totalCost: result.total_cost,\n maxTotalCost: result.max_total_cost,\n };\n }\n /**\n * Creates a paginator for the current EventSub subscriptions for the current client.\n */\n getSubscriptionsPaginated() {\n return new HelixPaginatedEventSubSubscriptionsRequest({}, undefined, this._client);\n }\n /**\n * Gets the current EventSub subscriptions with the given status for the current client.\n *\n * @param status The status of the subscriptions to get.\n * @param pagination\n *\n * @expandParams\n */\n async getSubscriptionsForStatus(status, pagination) {\n const result = await this._client.callApi({\n type: 'helix',\n url: 'eventsub/subscriptions',\n query: {\n ...createPaginationQuery(pagination),\n status,\n },\n });\n return {\n ...createPaginatedResultWithTotal(result, HelixEventSubSubscription, this._client),\n totalCost: result.total_cost,\n maxTotalCost: result.max_total_cost,\n };\n }\n /**\n * Creates a paginator for the current EventSub subscriptions with the given status for the current client.\n *\n * @param status The status of the subscriptions to get.\n */\n getSubscriptionsForStatusPaginated(status) {\n return new HelixPaginatedEventSubSubscriptionsRequest({ status }, undefined, this._client);\n }\n /**\n * Gets the current EventSub subscriptions with the given type for the current client.\n *\n * @param type The type of the subscriptions to get.\n * @param pagination\n *\n * @expandParams\n */\n async getSubscriptionsForType(type, pagination) {\n const result = await this._client.callApi({\n type: 'helix',\n url: 'eventsub/subscriptions',\n query: {\n ...createPaginationQuery(pagination),\n type,\n },\n });\n return {\n ...createPaginatedResultWithTotal(result, HelixEventSubSubscription, this._client),\n totalCost: result.total_cost,\n maxTotalCost: result.max_total_cost,\n };\n }\n /**\n * Creates a paginator for the current EventSub subscriptions with the given type for the current client.\n *\n * @param type The type of the subscriptions to get.\n */\n getSubscriptionsForTypePaginated(type) {\n return new HelixPaginatedEventSubSubscriptionsRequest({ type }, undefined, this._client);\n }\n /**\n * Gets the current EventSub subscriptions for the current user and client.\n *\n * @param user The user to get subscriptions for.\n * @param pagination\n *\n * @expandParams\n */\n async getSubscriptionsForUser(user, pagination) {\n const result = await this._client.callApi({\n type: 'helix',\n url: 'eventsub/subscriptions',\n userId: extractUserId(user),\n query: {\n ...createSingleKeyQuery('user_id', extractUserId(user)),\n ...createPaginationQuery(pagination),\n },\n });\n return {\n ...createPaginatedResultWithTotal(result, HelixEventSubSubscription, this._client),\n totalCost: result.total_cost,\n maxTotalCost: result.max_total_cost,\n };\n }\n /**\n * Creates a paginator for the current EventSub subscriptions with the given type for the current client.\n *\n * @param user The user to get subscriptions for.\n */\n getSubscriptionsForUserPaginated(user) {\n const userId = extractUserId(user);\n return new HelixPaginatedEventSubSubscriptionsRequest(createSingleKeyQuery('user_id', userId), userId, this._client);\n }\n /**\n * Sends an arbitrary request to subscribe to an event.\n *\n * You can only create WebHook transport subscriptions using app tokens\n * and WebSocket transport subscriptions using user tokens.\n *\n * @param type The type of the event.\n * @param version The version of the event.\n * @param condition The condition of the subscription.\n * @param transport The transport of the subscription.\n * @param user The user to create the subscription in context of.\n * @param requiredScopeSet The scope set required by the subscription. Will only be checked for applicable transports.\n * @param canOverrideScopedUserContext Whether the auth user context can be overridden.\n * @param isBatched Whether to enable batching for the subscription. Is only supported for select topics.\n */\n async createSubscription(type, version, condition, transport, user, requiredScopeSet, canOverrideScopedUserContext, isBatched) {\n const usesAppAuth = transport.method === 'webhook' || transport.method === 'conduit';\n const scopes = usesAppAuth ? undefined : requiredScopeSet;\n if (!usesAppAuth && !user) {\n throw new Error(`Transport ${transport.method} can only handle subscriptions with user context`);\n }\n const jsonBody = {\n type,\n version,\n condition,\n transport,\n };\n if (isBatched) {\n jsonBody.is_batching_enabled = true;\n }\n const result = await this._client.callApi({\n type: 'helix',\n url: 'eventsub/subscriptions',\n method: 'POST',\n scopes,\n userId: mapOptional(user, extractUserId),\n canOverrideScopedUserContext,\n forceType: usesAppAuth ? 'app' : 'user',\n jsonBody,\n });\n return new HelixEventSubSubscription(result.data[0], this._client);\n }\n /**\n * Deletes a subscription.\n *\n * @param id The ID of the subscription.\n */\n async deleteSubscription(id) {\n await this._client.callApi({\n type: 'helix',\n url: 'eventsub/subscriptions',\n method: 'DELETE',\n query: {\n id,\n },\n });\n }\n /**\n * Deletes *all* subscriptions.\n */\n async deleteAllSubscriptions() {\n await this._deleteSubscriptionsWithCondition();\n }\n /**\n * Deletes all broken subscriptions, i.e. all that are not enabled or pending verification.\n */\n async deleteBrokenSubscriptions() {\n await this._deleteSubscriptionsWithCondition(sub => sub.status !== 'enabled' && sub.status !== 'webhook_callback_verification_pending');\n }\n /**\n * Subscribe to events that represent a stream going live.\n *\n * @param broadcaster The broadcaster you want to listen to online events for.\n * @param transport The transport options.\n */\n async subscribeToStreamOnlineEvents(broadcaster, transport) {\n return await this.createSubscription('stream.online', '1', createEventSubBroadcasterCondition(broadcaster), transport, broadcaster);\n }\n /**\n * Subscribe to events that represent a stream going offline.\n *\n * @param broadcaster The broadcaster you want to listen to online events for.\n * @param transport The transport options.\n */\n async subscribeToStreamOfflineEvents(broadcaster, transport) {\n return await this.createSubscription('stream.offline', '1', createEventSubBroadcasterCondition(broadcaster), transport, broadcaster);\n }\n /**\n * Subscribe to events that represent a channel updating their metadata.\n *\n * @param broadcaster The broadcaster you want to listen to update events for.\n * @param transport The transport options.\n */\n async subscribeToChannelUpdateEvents(broadcaster, transport) {\n return await this.createSubscription('channel.update', '2', createEventSubBroadcasterCondition(broadcaster), transport, broadcaster);\n }\n /**\n * Subscribe to events that represent a user following a channel.\n *\n * @param broadcaster The broadcaster you want to listen to follow events for.\n * @param transport The transport options.\n */\n async subscribeToChannelFollowEvents(broadcaster, transport) {\n const broadcasterId = extractUserId(broadcaster);\n return await this.createSubscription('channel.follow', '2', createEventSubModeratorCondition(broadcasterId, this._getUserContextIdWithDefault(broadcasterId)), transport, broadcasterId, ['moderator:read:followers'], true);\n }\n /**\n * Subscribe to events that represent a user subscribing to a channel.\n *\n * @param broadcaster The broadcaster you want to listen to subscribe events for.\n * @param transport The transport options.\n */\n async subscribeToChannelSubscriptionEvents(broadcaster, transport) {\n return await this.createSubscription('channel.subscribe', '1', createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ['channel:read:subscriptions']);\n }\n /**\n * Subscribe to events that represent a user gifting another user a subscription to a channel.\n *\n * @param broadcaster The broadcaster you want to listen to subscription gift events for.\n * @param transport The transport options.\n */\n async subscribeToChannelSubscriptionGiftEvents(broadcaster, transport) {\n return await this.createSubscription('channel.subscription.gift', '1', createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ['channel:read:subscriptions']);\n }\n /**\n * Subscribe to events that represent a user's subscription to a channel being announced.\n *\n * @param broadcaster The broadcaster you want to listen to subscription message events for.\n * @param transport The transport options.\n */\n async subscribeToChannelSubscriptionMessageEvents(broadcaster, transport) {\n return await this.createSubscription('channel.subscription.message', '1', createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ['channel:read:subscriptions']);\n }\n /**\n * Subscribe to events that represent a user's subscription to a channel ending.\n *\n * @param broadcaster The broadcaster you want to listen to subscription end events for.\n * @param transport The transport options.\n */\n async subscribeToChannelSubscriptionEndEvents(broadcaster, transport) {\n return await this.createSubscription('channel.subscription.end', '1', createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ['channel:read:subscriptions']);\n }\n /**\n * Subscribe to events that represent a user cheering bits to a channel.\n *\n * @param broadcaster The broadcaster you want to listen to cheer events for.\n * @param transport The transport options.\n */\n async subscribeToChannelCheerEvents(broadcaster, transport) {\n return await this.createSubscription('channel.cheer', '1', createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ['bits:read']);\n }\n /**\n * Subscribe to events that represent a charity campaign starting in a channel.\n *\n * @param broadcaster The broadcaster you want to listen to charity donation events for.\n * @param transport The transport options.\n */\n async subscribeToChannelCharityCampaignStartEvents(broadcaster, transport) {\n return await this.createSubscription('channel.charity_campaign.start', '1', createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ['channel:read:charity']);\n }\n /**\n * Subscribe to events that represent a charity campaign ending in a channel.\n *\n * @param broadcaster The broadcaster you want to listen to charity donation events for.\n * @param transport The transport options.\n */\n async subscribeToChannelCharityCampaignStopEvents(broadcaster, transport) {\n return await this.createSubscription('channel.charity_campaign.stop', '1', createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ['channel:read:charity']);\n }\n /**\n * Subscribe to events that represent a user donating to a charity campaign in a channel.\n *\n * @param broadcaster The broadcaster you want to listen to charity donation events for.\n * @param transport The transport options.\n */\n async subscribeToChannelCharityDonationEvents(broadcaster, transport) {\n return await this.createSubscription('channel.charity_campaign.donate', '1', createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ['channel:read:charity']);\n }\n /**\n * Subscribe to events that represent a charity campaign progressing in a channel.\n *\n * @param broadcaster The broadcaster you want to listen to charity donation events for.\n * @param transport The transport options.\n */\n async subscribeToChannelCharityCampaignProgressEvents(broadcaster, transport) {\n return await this.createSubscription('channel.charity_campaign.progress', '1', createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ['channel:read:charity']);\n }\n /**\n * Subscribe to events that represent a user being banned in a channel.\n *\n * @param broadcaster The broadcaster you want to listen to ban events for.\n * @param transport The transport options.\n */\n async subscribeToChannelBanEvents(broadcaster, transport) {\n return await this.createSubscription('channel.ban', '1', createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ['channel:moderate']);\n }\n /**\n * Subscribe to events that represent a user being unbanned in a channel.\n *\n * @param broadcaster The broadcaster you want to listen to unban events for.\n * @param transport The transport options.\n */\n async subscribeToChannelUnbanEvents(broadcaster, transport) {\n return await this.createSubscription('channel.unban', '1', createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ['channel:moderate']);\n }\n /**\n * Subscribe to events that represent Shield Mode being activated in a channel.\n *\n * @param broadcaster The broadcaster you want to listen to Shield Mode activation events for.\n * @param transport The transport options.\n */\n async subscribeToChannelShieldModeBeginEvents(broadcaster, transport) {\n const broadcasterId = extractUserId(broadcaster);\n return await this.createSubscription('channel.shield_mode.begin', '1', createEventSubModeratorCondition(broadcasterId, this._getUserContextIdWithDefault(broadcasterId)), transport, broadcasterId, ['moderator:read:shield_mode', 'moderator:manage:shield_mode'], true);\n }\n /**\n * Subscribe to events that represent Shield Mode being deactivated in a channel.\n *\n * @param broadcaster The broadcaster you want to listen to Shield Mode deactivation events for.\n * @param transport The transport options.\n */\n async subscribeToChannelShieldModeEndEvents(broadcaster, transport) {\n const broadcasterId = extractUserId(broadcaster);\n return await this.createSubscription('channel.shield_mode.end', '1', createEventSubModeratorCondition(broadcasterId, this._getUserContextIdWithDefault(broadcasterId)), transport, broadcasterId, ['moderator:read:shield_mode', 'moderator:manage:shield_mode'], true);\n }\n /**\n * Subscribe to events that represent a moderator being added to a channel.\n *\n * @param broadcaster The broadcaster you want to listen for moderator add events for.\n * @param transport The transport options.\n */\n async subscribeToChannelModeratorAddEvents(broadcaster, transport) {\n return await this.createSubscription('channel.moderator.add', '1', createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ['moderation:read']);\n }\n /**\n * Subscribe to events that represent a moderator being removed from a channel.\n *\n * @param broadcaster The broadcaster you want to listen for moderator remove events for.\n * @param transport The transport options.\n */\n async subscribeToChannelModeratorRemoveEvents(broadcaster, transport) {\n return await this.createSubscription('channel.moderator.remove', '1', createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ['moderation:read']);\n }\n /**\n * Subscribe to events that represent a broadcaster raiding another broadcaster.\n *\n * @param broadcaster The broadcaster you want to listen to outgoing raid events for.\n * @param transport The transport options.\n */\n async subscribeToChannelRaidEventsFrom(broadcaster, transport) {\n return await this.createSubscription('channel.raid', '1', createSingleKeyQuery('from_broadcaster_user_id', extractUserId(broadcaster)), transport, broadcaster);\n }\n /**\n * Subscribe to events that represent a broadcaster being raided by another broadcaster.\n *\n * @param broadcaster The broadcaster you want to listen to incoming raid events for.\n * @param transport The transport options.\n */\n async subscribeToChannelRaidEventsTo(broadcaster, transport) {\n return await this.createSubscription('channel.raid', '1', createSingleKeyQuery('to_broadcaster_user_id', extractUserId(broadcaster)), transport, broadcaster);\n }\n /**\n * Subscribe to events that represent a Channel Points reward being added to a channel.\n *\n * @param broadcaster The broadcaster you want to listen to reward add events for.\n * @param transport The transport options.\n */\n async subscribeToChannelRewardAddEvents(broadcaster, transport) {\n return await this.createSubscription('channel.channel_points_custom_reward.add', '1', createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ['channel:read:redemptions', 'channel:manage:redemptions']);\n }\n /**\n * Subscribe to events that represent a Channel Points reward being updated in a channel.\n *\n * @param broadcaster The broadcaster you want to listen to reward update events for.\n * @param transport The transport options.\n */\n async subscribeToChannelRewardUpdateEvents(broadcaster, transport) {\n return await this.createSubscription('channel.channel_points_custom_reward.update', '1', createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ['channel:read:redemptions', 'channel:manage:redemptions']);\n }\n /**\n * Subscribe to events that represent a specific Channel Points reward being updated.\n *\n * @param broadcaster The broadcaster you want to listen to reward update events for.\n * @param rewardId The ID of the reward you want to listen to update events for.\n * @param transport The transport options.\n */\n async subscribeToChannelRewardUpdateEventsForReward(broadcaster, rewardId, transport) {\n return await this.createSubscription('channel.channel_points_custom_reward.update', '1', createEventSubRewardCondition(broadcaster, rewardId), transport, broadcaster, ['channel:read:redemptions', 'channel:manage:redemptions']);\n }\n /**\n * Subscribe to events that represent a Channel Points reward being removed from a channel.\n *\n * @param broadcaster The broadcaster you want to listen to reward remove events for.\n * @param transport The transport options.\n */\n async subscribeToChannelRewardRemoveEvents(broadcaster, transport) {\n return await this.createSubscription('channel.channel_points_custom_reward.remove', '1', createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ['channel:read:redemptions', 'channel:manage:redemptions']);\n }\n /**\n * Subscribe to events that represent a specific Channel Points reward being removed from a channel.\n *\n * @param broadcaster The broadcaster you want to listen to reward remove events for.\n * @param rewardId The ID of the reward you want to listen to remove events for.\n * @param transport The transport options.\n */\n async subscribeToChannelRewardRemoveEventsForReward(broadcaster, rewardId, transport) {\n return await this.createSubscription('channel.channel_points_custom_reward.remove', '1', createEventSubRewardCondition(broadcaster, rewardId), transport, broadcaster, ['channel:read:redemptions', 'channel:manage:redemptions']);\n }\n /**\n * Subscribe to events that represent a Channel Points reward being redeemed.\n *\n * @param broadcaster The broadcaster you want to listen to redemption events for.\n * @param transport The transport options.\n */\n async subscribeToChannelRedemptionAddEvents(broadcaster, transport) {\n return await this.createSubscription('channel.channel_points_custom_reward_redemption.add', '1', createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ['channel:read:redemptions', 'channel:manage:redemptions']);\n }\n /**\n * Subscribe to events that represent a specific Channel Points reward being redeemed.\n *\n * @param broadcaster The broadcaster you want to listen to redemption events for.\n * @param rewardId The ID of the reward you want to listen to redemption events for.\n * @param transport The transport options.\n */\n async subscribeToChannelRedemptionAddEventsForReward(broadcaster, rewardId, transport) {\n return await this.createSubscription('channel.channel_points_custom_reward_redemption.add', '1', createEventSubRewardCondition(broadcaster, rewardId), transport, broadcaster, ['channel:read:redemptions', 'channel:manage:redemptions']);\n }\n /**\n * Subscribe to events that represent a Channel Points redemption being updated.\n *\n * @param broadcaster The broadcaster you want to listen to redemption update events for.\n * @param transport The transport options.\n */\n async subscribeToChannelRedemptionUpdateEvents(broadcaster, transport) {\n return await this.createSubscription('channel.channel_points_custom_reward_redemption.update', '1', createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ['channel:read:redemptions', 'channel:manage:redemptions']);\n }\n /**\n * Subscribe to events that represent a specific Channel Points reward's redemption being updated.\n *\n * @param broadcaster The broadcaster you want to listen to redemption update events for.\n * @param rewardId The ID of the reward you want to listen to redemption updates for.\n * @param transport The transport options.\n */\n async subscribeToChannelRedemptionUpdateEventsForReward(broadcaster, rewardId, transport) {\n return await this.createSubscription('channel.channel_points_custom_reward_redemption.update', '1', createEventSubRewardCondition(broadcaster, rewardId), transport, broadcaster, ['channel:read:redemptions', 'channel:manage:redemptions']);\n }\n /**\n * Subscribe to events that represent a Channel Points automatic reward being redeemed.\n *\n * @param broadcaster The broadcaster you want to listen to automatic reward redemption events for.\n * @param transport The transport options.\n */\n async subscribeToChannelAutomaticRewardRedemptionAddEvents(broadcaster, transport) {\n return await this.createSubscription('channel.channel_points_automatic_reward_redemption.add', '1', createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ['channel:read:redemptions', 'channel:manage:redemptions']);\n }\n /**\n * Subscribe to events that represent a Channel Points automatic reward being redeemed.\n *\n * @param broadcaster The broadcaster you want to listen to automatic reward redemption events for.\n * @param transport The transport options.\n */\n async subscribeToChannelAutomaticRewardRedemptionAddV2Events(broadcaster, transport) {\n return await this.createSubscription('channel.channel_points_automatic_reward_redemption.add', '2', createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ['channel:read:redemptions', 'channel:manage:redemptions']);\n }\n /**\n * Subscribe to events that represent a poll starting in a channel.\n *\n * @param broadcaster The broadcaster you want to listen to poll begin events for.\n * @param transport The transport options.\n */\n async subscribeToChannelPollBeginEvents(broadcaster, transport) {\n return await this.createSubscription('channel.poll.begin', '1', createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ['channel:read:polls', 'channel:manage:polls']);\n }\n /**\n * Subscribe to events that represent a poll being voted on in a channel.\n *\n * @param broadcaster The broadcaster you want to listen to poll progress events for.\n * @param transport The transport options.\n */\n async subscribeToChannelPollProgressEvents(broadcaster, transport) {\n return await this.createSubscription('channel.poll.progress', '1', createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ['channel:read:polls', 'channel:manage:polls']);\n }\n /**\n * Subscribe to events that represent a poll ending in a channel.\n *\n * @param broadcaster The broadcaster you want to listen to poll end events for.\n * @param transport The transport options.\n */\n async subscribeToChannelPollEndEvents(broadcaster, transport) {\n return await this.createSubscription('channel.poll.end', '1', createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ['channel:read:polls', 'channel:manage:polls']);\n }\n /**\n * Subscribe to events that represent a prediction starting in a channel.\n *\n * @param broadcaster The broadcaster you want to listen to prediction begin events for.\n * @param transport The transport options.\n */\n async subscribeToChannelPredictionBeginEvents(broadcaster, transport) {\n return await this.createSubscription('channel.prediction.begin', '1', createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ['channel:read:predictions', 'channel:manage:predictions']);\n }\n /**\n * Subscribe to events that represent a prediction being voted on in a channel.\n *\n * @param broadcaster The broadcaster you want to listen to prediction preogress events for.\n * @param transport The transport options.\n */\n async subscribeToChannelPredictionProgressEvents(broadcaster, transport) {\n return await this.createSubscription('channel.prediction.progress', '1', createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ['channel:read:predictions', 'channel:manage:predictions']);\n }\n /**\n * Subscribe to events that represent a prediction being locked in a channel.\n *\n * @param broadcaster The broadcaster you want to listen to prediction lock events for.\n * @param transport The transport options.\n */\n async subscribeToChannelPredictionLockEvents(broadcaster, transport) {\n return await this.createSubscription('channel.prediction.lock', '1', createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ['channel:read:predictions', 'channel:manage:predictions']);\n }\n /**\n * Subscribe to events that represent a prediction ending in a channel.\n *\n * @param broadcaster The broadcaster you want to listen to prediction end events for.\n * @param transport The transport options.\n */\n async subscribeToChannelPredictionEndEvents(broadcaster, transport) {\n return await this.createSubscription('channel.prediction.end', '1', createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ['channel:read:predictions', 'channel:manage:predictions']);\n }\n /**\n * Subscribe to events that represent the beginning of a creator goal event in a channel.\n *\n * @param broadcaster The broadcaster you want to listen to goal begin events for.\n * @param transport The transport options.\n */\n async subscribeToChannelGoalBeginEvents(broadcaster, transport) {\n return await this.createSubscription('channel.goal.begin', '1', createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ['channel:read:goals']);\n }\n /**\n * Subscribe to events that represent progress towards a creator goal.\n *\n * @param broadcaster The broadcaster for which you want to listen to goal progress events.\n * @param transport The transport options.\n */\n async subscribeToChannelGoalProgressEvents(broadcaster, transport) {\n return await this.createSubscription('channel.goal.progress', '1', createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ['channel:read:goals']);\n }\n /**\n * Subscribe to events that represent the end of a creator goal event.\n *\n * @param broadcaster The broadcaster for which you want to listen to goal end events.\n * @param transport The transport options.\n */\n async subscribeToChannelGoalEndEvents(broadcaster, transport) {\n return await this.createSubscription('channel.goal.end', '1', createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ['channel:read:goals']);\n }\n /**\n * Subscribe to events that represent the beginning of a Hype Train event in a channel.\n *\n * @param broadcaster The broadcaster you want to listen to Hype train begin events for.\n * @param transport The transport options.\n */\n async subscribeToChannelHypeTrainBeginEvents(broadcaster, transport) {\n return await this.createSubscription('channel.hype_train.begin', '1', createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ['channel:read:hype_train']);\n }\n /**\n * Subscribe to events that represent progress towards the Hype Train goal.\n *\n * @param broadcaster The broadcaster for which you want to listen to Hype Train progress events.\n * @param transport The transport options.\n */\n async subscribeToChannelHypeTrainProgressEvents(broadcaster, transport) {\n return await this.createSubscription('channel.hype_train.progress', '1', createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ['channel:read:hype_train']);\n }\n /**\n * Subscribe to events that represent the end of a Hype Train event.\n *\n * @param broadcaster The broadcaster for which you want to listen to Hype Train end events.\n * @param transport The transport options.\n */\n async subscribeToChannelHypeTrainEndEvents(broadcaster, transport) {\n return await this.createSubscription('channel.hype_train.end', '1', createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ['channel:read:hype_train']);\n }\n /**\n * Subscribe to events that represent the beginning of a Hype Train event in a channel.\n *\n * @param broadcaster The broadcaster you want to listen to Hype train begin events for.\n * @param transport The transport options.\n */\n async subscribeToChannelHypeTrainBeginV2Events(broadcaster, transport) {\n return await this.createSubscription('channel.hype_train.begin', '2', createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ['channel:read:hype_train']);\n }\n /**\n * Subscribe to events that represent progress towards the Hype Train goal.\n *\n * @param broadcaster The broadcaster for which you want to listen to Hype Train progress events.\n * @param transport The transport options.\n */\n async subscribeToChannelHypeTrainProgressV2Events(broadcaster, transport) {\n return await this.createSubscription('channel.hype_train.progress', '2', createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ['channel:read:hype_train']);\n }\n /**\n * Subscribe to events that represent the end of a Hype Train event.\n *\n * @param broadcaster The broadcaster for which you want to listen to Hype Train end events.\n * @param transport The transport options.\n */\n async subscribeToChannelHypeTrainEndV2Events(broadcaster, transport) {\n return await this.createSubscription('channel.hype_train.end', '2', createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ['channel:read:hype_train']);\n }\n /**\n * Subscribe to events that represent a broadcaster shouting out another broadcaster.\n *\n * @param broadcaster The broadcaster for which you want to listen to outgoing shoutout events.\n * @param transport The transport options.\n */\n async subscribeToChannelShoutoutCreateEvents(broadcaster, transport) {\n const broadcasterId = extractUserId(broadcaster);\n return await this.createSubscription('channel.shoutout.create', '1', createEventSubModeratorCondition(broadcasterId, this._getUserContextIdWithDefault(broadcasterId)), transport, broadcasterId, ['moderator:read:shoutouts', 'moderator:manage:shoutouts'], true);\n }\n /**\n * Subscribe to events that represent a broadcaster being shouting out by another broadcaster.\n *\n * @param broadcaster The broadcaster for which you want to listen to incoming shoutout events.\n * @param transport The transport options.\n */\n async subscribeToChannelShoutoutReceiveEvents(broadcaster, transport) {\n const broadcasterId = extractUserId(broadcaster);\n return await this.createSubscription('channel.shoutout.receive', '1', createEventSubModeratorCondition(broadcasterId, this._getUserContextIdWithDefault(broadcasterId)), transport, broadcasterId, ['moderator:read:shoutouts', 'moderator:manage:shoutouts'], true);\n }\n /**\n * Subscribe to events that represent an ad break beginning in a channel.\n *\n * @param broadcaster The broadcaster for which you want to listen to ad break begin events.\n * @param transport The transport options.\n */\n async subscribeToChannelAdBreakBeginEvents(broadcaster, transport) {\n return await this.createSubscription('channel.ad_break.begin', '1', createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ['channel:read:ads']);\n }\n /**\n * Subscribe to events that represent a channel's chat being cleared.\n *\n * @param broadcaster The broadcaster for which you want to listen to chat clear events.\n * @param transport The transport options.\n */\n async subscribeToChannelChatClearEvents(broadcaster, transport) {\n const broadcasterId = extractUserId(broadcaster);\n return await this.createSubscription('channel.chat.clear', '1', createEventSubUserCondition(broadcasterId, this._getUserContextIdWithDefault(broadcasterId)), transport, broadcaster, ['user:read:chat'], true);\n }\n /**\n * Subscribe to events that represent a user's chat messages being cleared in a channel.\n *\n * @param broadcaster The broadcaster for which you want to listen to user chat message clear events.\n * @param transport The transport options.\n */\n async subscribeToChannelChatClearUserMessagesEvents(broadcaster, transport) {\n const broadcasterId = extractUserId(broadcaster);\n return await this.createSubscription('channel.chat.clear_user_messages', '1', createEventSubUserCondition(broadcasterId, this._getUserContextIdWithDefault(broadcasterId)), transport, broadcaster, ['user:read:chat'], true);\n }\n /**\n * Subscribe to events that represent a chat message being deleted in a channel.\n *\n * @param broadcaster The broadcaster for which you want to listen to chat message delete events.\n * @param transport The transport options.\n */\n async subscribeToChannelChatMessageDeleteEvents(broadcaster, transport) {\n const broadcasterId = extractUserId(broadcaster);\n return await this.createSubscription('channel.chat.message_delete', '1', createEventSubUserCondition(broadcasterId, this._getUserContextIdWithDefault(broadcasterId)), transport, broadcaster, ['user:read:chat'], true);\n }\n /**\n * Subscribe to events that represent a chat notification in a channel.\n *\n * @param broadcaster The broadcaster for which you want to listen to chat notification events.\n * @param transport The transport options.\n */\n async subscribeToChannelChatNotificationEvents(broadcaster, transport) {\n const broadcasterId = extractUserId(broadcaster);\n return await this.createSubscription('channel.chat.notification', '1', createEventSubUserCondition(broadcasterId, this._getUserContextIdWithDefault(broadcasterId)), transport, broadcaster, ['user:read:chat'], true);\n }\n /**\n * Subscribe to events that represent a chat message in a channel.\n *\n * @param broadcaster The broadcaster for which you want to listen to chat message events.\n * @param transport The transport options.\n */\n async subscribeToChannelChatMessageEvents(broadcaster, transport) {\n const broadcasterId = extractUserId(broadcaster);\n return await this.createSubscription('channel.chat.message', '1', createEventSubUserCondition(broadcasterId, this._getUserContextIdWithDefault(broadcasterId)), transport, broadcaster, ['user:read:chat'], true);\n }\n /**\n * Subscribe to events that represent chat settings being updated in a channel.\n *\n * @param broadcaster The broadcaster for which you want to listen to chat settings update events.\n * @param transport The transport options.\n */\n async subscribeToChannelChatSettingsUpdateEvents(broadcaster, transport) {\n const broadcasterId = extractUserId(broadcaster);\n return await this.createSubscription('channel.chat_settings.update', '1', createEventSubUserCondition(broadcasterId, this._getUserContextIdWithDefault(broadcasterId)), transport, broadcaster, ['user:read:chat'], true);\n }\n /**\n * Subscribe to events that represent a created unban requests in a channel.\n *\n * @param broadcaster The broadcaster for which you want to listen to unban requests.\n * @param transport The transport options.\n */\n async subscribeToChannelUnbanRequestCreateEvents(broadcaster, transport) {\n const broadcasterId = extractUserId(broadcaster);\n return await this.createSubscription('channel.unban_request.create', '1', createEventSubModeratorCondition(broadcasterId, this._getUserContextIdWithDefault(broadcasterId)), transport, broadcaster, ['moderator:read:unban_requests', 'moderator:manage:unban_requests'], true);\n }\n /**\n * Subscribe to events that represent a resolved unban requests in a channel.\n *\n * @param broadcaster The broadcaster for which you want to listen to unban requests.\n * @param transport The transport options.\n */\n async subscribeToChannelUnbanRequestResolveEvents(broadcaster, transport) {\n const broadcasterId = extractUserId(broadcaster);\n return await this.createSubscription('channel.unban_request.resolve', '1', createEventSubModeratorCondition(broadcasterId, this._getUserContextIdWithDefault(broadcasterId)), transport, broadcaster, ['moderator:read:unban_requests', 'moderator:manage:unban_requests'], true);\n }\n /**\n * Subscribe to events that represent a moderator performing an action on a channel.\n *\n * This requires the following scopes:\n * - `moderator:read:blocked_terms` OR `moderator:manage:blocked_terms`\n * - `moderator:read:chat_settings` OR `moderator:manage:chat_settings`\n * - `moderator:read:unban_requests` OR `moderator:manage:unban_requests`\n * - `moderator:read:banned_users` OR `moderator:manage:banned_users`\n * - `moderator:read:chat_messages` OR `moderator:manage:chat_messages`\n * - `moderator:read:warnings` OR `moderator:manage:warnings`\n * - `moderator:read:moderators`\n * - `moderator:read:vips`\n *\n * These scope requirements cannot be checked by the library, so they are just assumed.\n * Make sure to catch authorization errors yourself.\n *\n * @param broadcaster The broadcaster for which you want to listen to moderation events.\n * @param transport The transport options.\n */\n async subscribeToChannelModerateEvents(broadcaster, transport) {\n const broadcasterId = extractUserId(broadcaster);\n return await this.createSubscription('channel.moderate', '2', createEventSubModeratorCondition(broadcasterId, this._getUserContextIdWithDefault(broadcasterId)), transport, broadcaster, [], true);\n }\n /**\n * Subscribe to events that represent a warning being acknowledged by a user.\n *\n * @param broadcaster The broadcaster for whom you want to listen to warnings.\n * @param transport The transport options.\n */\n async subscribeToChannelWarningAcknowledgeEvents(broadcaster, transport) {\n const broadcasterId = extractUserId(broadcaster);\n return await this.createSubscription('channel.warning.acknowledge', '1', createEventSubModeratorCondition(broadcasterId, this._getUserContextIdWithDefault(broadcasterId)), transport, broadcaster, ['moderator:read:warnings', 'moderator:manage:warnings'], true);\n }\n /**\n * Subscribe to events that represent a warning sent to a user.\n *\n * @param broadcaster The broadcaster for whom you want to listen to warnings.\n * @param transport The transport options.\n */\n async subscribeToChannelWarningSendEvents(broadcaster, transport) {\n const broadcasterId = extractUserId(broadcaster);\n return await this.createSubscription('channel.warning.send', '1', createEventSubModeratorCondition(broadcasterId, this._getUserContextIdWithDefault(broadcasterId)), transport, broadcaster, ['moderator:read:warnings', 'moderator:manage:warnings'], true);\n }\n /**\n * Subscribe to events that represent a VIP being added to a channel.\n *\n * @param broadcaster The broadcaster you want to listen for VIP add events for.\n * @param transport The transport options.\n */\n async subscribeToChannelVipAddEvents(broadcaster, transport) {\n return await this.createSubscription('channel.vip.add', '1', createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ['channel:read:vips', 'channel:manage:vips']);\n }\n /**\n * Subscribe to events that represent a VIP being removed from a channel.\n *\n * @param broadcaster The broadcaster you want to listen for VIP remove events for.\n * @param transport The transport options.\n */\n async subscribeToChannelVipRemoveEvents(broadcaster, transport) {\n return await this.createSubscription('channel.vip.remove', '1', createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ['channel:read:vips', 'channel:manage:vips']);\n }\n /**\n * Subscribe to events that represent an extension Bits transaction.\n *\n * @param clientId The Client ID for the extension you want to listen to Bits transactions for.\n * @param transport The transport options.\n */\n async subscribeToExtensionBitsTransactionCreateEvents(clientId, transport) {\n return await this.createSubscription('extension.bits_transaction.create', '1', createSingleKeyQuery('extension_client_id', clientId), transport);\n }\n /**\n * Subscribe to events that represent a user granting authorization to an application.\n *\n * @param clientId The Client ID for the application you want to listen to authorization grant events for.\n * @param transport The transport options.\n */\n async subscribeToUserAuthorizationGrantEvents(clientId, transport) {\n return await this.createSubscription('user.authorization.grant', '1', createSingleKeyQuery('client_id', clientId), transport);\n }\n /**\n * Subscribe to events that represent a user revoking their authorization from an application.\n *\n * @param clientId The Client ID for the application you want to listen to authorization revoke events for.\n * @param transport The transport options.\n */\n async subscribeToUserAuthorizationRevokeEvents(clientId, transport) {\n return await this.createSubscription('user.authorization.revoke', '1', createSingleKeyQuery('client_id', clientId), transport);\n }\n /**\n * Subscribe to events that represent a user updating their account details.\n *\n * @param user The user you want to listen to user update events for.\n * @param transport The transport options.\n * @param withEmail Whether to request adding the email address of the user to the notification.\n *\n * Only has an effect with the websocket transport.\n * With the webhook transport, this depends solely on the previous authorization given by the user.\n */\n async subscribeToUserUpdateEvents(user, transport, withEmail) {\n return await this.createSubscription('user.update', '1', createSingleKeyQuery('user_id', extractUserId(user)), transport, user, withEmail ? ['user:read:email'] : undefined);\n }\n /**\n * Subscribe to events that represent a user receiving a whisper message from another user.\n *\n * @param user The user you want to listen to whisper message events for.\n * @param transport The transport options.\n */\n async subscribeToUserWhisperMessageEvents(user, transport) {\n return await this.createSubscription('user.whisper.message', '1', createSingleKeyQuery('user_id', extractUserId(user)), transport, user, ['user:read:whispers', 'user:manage:whispers']);\n }\n /**\n * Subscribe to events that represent a drop entitlement being granted.\n *\n * @expandParams\n *\n * @param filter\n * @param transport The transport options.\n */\n async subscribeToDropEntitlementGrantEvents(filter, transport) {\n return await this.createSubscription('drop.entitlement.grant', '1', createEventSubDropEntitlementGrantCondition(filter), transport, undefined, undefined, false, true);\n }\n /**\n * Subscribes to events that represent a chat message being held by AutoMod.\n *\n * @param broadcaster The broadcaster you want to listen to AutoMod message hold events for.\n * @param transport The transport options.\n */\n async subscribeToAutoModMessageHoldEvents(broadcaster, transport) {\n const broadcasterId = extractUserId(broadcaster);\n return await this.createSubscription('automod.message.hold', '1', createEventSubModeratorCondition(broadcasterId, this._getUserContextIdWithDefault(broadcasterId)), transport, broadcaster, ['moderator:manage:automod'], true);\n }\n /**\n * Subscribes to events that represent a held chat message by AutoMod being resolved.\n *\n * @param broadcaster The broadcaster you want to listen to AutoMod message resolution events for.\n * @param transport The transport options.\n */\n async subscribeToAutoModMessageUpdateEvents(broadcaster, transport) {\n const broadcasterId = extractUserId(broadcaster);\n return await this.createSubscription('automod.message.update', '1', createEventSubModeratorCondition(broadcasterId, this._getUserContextIdWithDefault(broadcasterId)), transport, broadcaster, ['moderator:manage:automod'], true);\n }\n /**\n * Subscribes to events (v2) that represent a chat message being held by AutoMod.\n *\n * @param broadcaster The broadcaster you want to listen to AutoMod message hold events for.\n * @param transport The transport options.\n */\n async subscribeToAutoModMessageHoldV2Events(broadcaster, transport) {\n const broadcasterId = extractUserId(broadcaster);\n return await this.createSubscription('automod.message.hold', '2', createEventSubModeratorCondition(broadcasterId, this._getUserContextIdWithDefault(broadcasterId)), transport, broadcaster, ['moderator:manage:automod'], true);\n }\n /**\n * Subscribes to events (v2) that represent a held chat message by AutoMod being resolved.\n *\n * @param broadcaster The broadcaster you want to listen to AutoMod message resolution events for.\n * @param transport The transport options.\n */\n async subscribeToAutoModMessageUpdateV2Events(broadcaster, transport) {\n const broadcasterId = extractUserId(broadcaster);\n return await this.createSubscription('automod.message.update', '2', createEventSubModeratorCondition(broadcasterId, this._getUserContextIdWithDefault(broadcasterId)), transport, broadcaster, ['moderator:manage:automod'], true);\n }\n /**\n * Subscribes to events that represent the AutoMod settings being updated.\n *\n * @param broadcaster The broadcaster you want to listen to AutoMod settings update events.\n * @param transport The transport options.\n */\n async subscribeToAutoModSettingsUpdateEvents(broadcaster, transport) {\n const broadcasterId = extractUserId(broadcaster);\n return await this.createSubscription('automod.settings.update', '1', createEventSubModeratorCondition(broadcasterId, this._getUserContextIdWithDefault(broadcasterId)), transport, broadcaster, ['moderator:read:automod_settings'], true);\n }\n /**\n * Subscribes to events that represent the AutoMod terms being updated.\n *\n * @param broadcaster The broadcaster you want to listen to AutoMod terms update events.\n * @param transport The transport options.\n */\n async subscribeToAutoModTermsUpdateEvents(broadcaster, transport) {\n const broadcasterId = extractUserId(broadcaster);\n return await this.createSubscription('automod.terms.update', '1', createEventSubModeratorCondition(broadcasterId, this._getUserContextIdWithDefault(broadcasterId)), transport, broadcaster, ['moderator:manage:automod'], true);\n }\n /**\n * Subscribes to events that represent a user's notification about their message being held by AutoMod.\n *\n * @param broadcaster The broadcaster you want to listen to AutoMod message hold events for.\n * @param transport The transport options.\n */\n async subscribeToChannelChatUserMessageHoldEvents(broadcaster, transport) {\n const broadcasterId = extractUserId(broadcaster);\n return await this.createSubscription('channel.chat.user_message_hold', '1', createEventSubUserCondition(broadcasterId, this._getUserContextIdWithDefault(broadcasterId)), transport, broadcaster, ['user:read:chat'], true);\n }\n /**\n * Subscribes to events that represent a user's notification about a held chat message by AutoMod being resolved.\n *\n * @param broadcaster The broadcaster you want to listen to AutoMod message resolution events for.\n * @param transport The transport options.\n */\n async subscribeToChannelChatUserMessageUpdateEvents(broadcaster, transport) {\n const broadcasterId = extractUserId(broadcaster);\n return await this.createSubscription('channel.chat.user_message_update', '1', createEventSubUserCondition(broadcasterId, this._getUserContextIdWithDefault(broadcasterId)), transport, broadcaster, ['user:read:chat'], true);\n }\n /**\n * Subscribes to events that represent a suspicious user updated in a channel.\n *\n * @param broadcaster The broadcaster you want to listen for suspicious user update events.\n * @param transport The transport options.\n */\n async subscribeToChannelSuspiciousUserUpdateEvents(broadcaster, transport) {\n const broadcasterId = extractUserId(broadcaster);\n return await this.createSubscription('channel.suspicious_user.update', '1', createEventSubModeratorCondition(broadcasterId, this._getUserContextIdWithDefault(broadcasterId)), transport, broadcaster, ['moderator:read:suspicious_users'], true);\n }\n /**\n * Subscribes to events that represent a message sent by a suspicious user.\n *\n * @param broadcaster The broadcaster you want to listen for messages sent by suspicious users.\n * @param transport The transport options.\n */\n async subscribeToChannelSuspiciousUserMessageEvents(broadcaster, transport) {\n const broadcasterId = extractUserId(broadcaster);\n return await this.createSubscription('channel.suspicious_user.message', '1', createEventSubModeratorCondition(broadcasterId, this._getUserContextIdWithDefault(broadcasterId)), transport, broadcaster, ['moderator:read:suspicious_users'], true);\n }\n /**\n * Subscribes to events indicating that a shared chat session has begun in a channel.\n *\n * @param broadcaster The broadcaster for whom shared chat session begin events should be listened to.\n * @param transport The transport options to use for the subscription.\n */\n async subscribeToChannelSharedChatSessionBeginEvents(broadcaster, transport) {\n const broadcasterId = extractUserId(broadcaster);\n return await this.createSubscription('channel.shared_chat.begin', '1', createEventSubBroadcasterCondition(broadcasterId), transport, broadcasterId);\n }\n /**\n * Subscribes to events indicating that a shared chat session has been updated in a channel.\n *\n * @param broadcaster The broadcaster for whom shared chat session update events should be listened to.\n * @param transport The transport options to use for the subscription.\n */\n async subscribeToChannelSharedChatSessionUpdateEvents(broadcaster, transport) {\n const broadcasterId = extractUserId(broadcaster);\n return await this.createSubscription('channel.shared_chat.update', '1', createEventSubBroadcasterCondition(broadcasterId), transport, broadcasterId);\n }\n /**\n * Subscribes to events indicating that a shared chat session has ended in a channel.\n *\n * @param broadcaster The broadcaster for whom shared chat session end events should be listened to.\n * @param transport The transport options to use for the subscription.\n */\n async subscribeToChannelSharedChatSessionEndEvents(broadcaster, transport) {\n const broadcasterId = extractUserId(broadcaster);\n return await this.createSubscription('channel.shared_chat.end', '1', createEventSubBroadcasterCondition(broadcasterId), transport, broadcasterId);\n }\n /**\n * Subscribes to events indicating that bits are used in a channel.\n *\n * @param broadcaster The broadcaster for whom you want to listen to bits usage events.\n * @param transport The transport options to use for the subscription.\n */\n async subscribeToChannelBitsUseEvents(broadcaster, transport) {\n const broadcasterId = extractUserId(broadcaster);\n return await this.createSubscription('channel.bits.use', '1', createEventSubBroadcasterCondition(broadcasterId), transport, broadcasterId, ['bits:read']);\n }\n /**\n * Gets the current EventSub conduits for the current client.\n *\n */\n async getConduits() {\n const result = await this._client.callApi({\n type: 'helix',\n url: 'eventsub/conduits',\n });\n return result.data.map(data => new HelixEventSubConduit(data, this._client));\n }\n /**\n * Creates a new EventSub conduit for the current client.\n *\n * @param shardCount The number of shards to create for this conduit.\n */\n async createConduit(shardCount) {\n const result = await this._client.callApi({\n type: 'helix',\n url: 'eventsub/conduits',\n method: 'POST',\n query: {\n ...createSingleKeyQuery('shard_count', shardCount.toString()),\n },\n });\n return new HelixEventSubConduit(result.data[0], this._client);\n }\n /**\n * Updates an EventSub conduit for the current client.\n *\n * @param id The ID of the conduit to update.\n * @param shardCount The number of shards to update for this conduit.\n */\n async updateConduit(id, shardCount) {\n const result = await this._client.callApi({\n type: 'helix',\n url: 'eventsub/conduits',\n method: 'PATCH',\n query: createEventSubConduitUpdateCondition(id, shardCount),\n });\n return new HelixEventSubConduit(result.data[0], this._client);\n }\n /**\n * Deletes an EventSub conduit for the current client.\n *\n * @param id The ID of the conduit to delete.\n */\n async deleteConduit(id) {\n await this._client.callApi({\n type: 'helix',\n url: 'eventsub/conduits',\n method: 'DELETE',\n query: {\n ...createSingleKeyQuery('id', id),\n },\n });\n }\n /**\n * Gets the shards of an EventSub conduit for the current client.\n *\n * @param conduitId The ID of the conduit to get shards for.\n * @param status The status of the shards to filter by.\n * @param pagination\n */\n async getConduitShards(conduitId, status, pagination) {\n const result = await this._client.callApi({\n type: 'helix',\n url: 'eventsub/conduits/shards',\n query: {\n ...createEventSubConduitCondition(conduitId, status),\n ...createPaginationQuery(pagination),\n },\n });\n return {\n ...createPaginatedResult(result, HelixEventSubConduitShard, this._client),\n };\n }\n /**\n * Creates a paginator for the shards of an EventSub conduit for the current client.\n *\n * @param conduitId The ID of the conduit to get shards for.\n * @param status The status of the shards to filter by.\n */\n getConduitShardsPaginated(conduitId, status) {\n return new HelixPaginatedRequest({\n url: 'eventsub/conduits/shards',\n query: createEventSubConduitCondition(conduitId, status),\n }, this._client, data => new HelixEventSubConduitShard(data));\n }\n /**\n * Updates shards of an EventSub conduit for the current client.\n *\n * @param conduitId The ID of the conduit to update shards for.\n * @param shards List of shards to update\n */\n async updateConduitShards(conduitId, shards) {\n const result = await this._client.callApi({\n type: 'helix',\n url: 'eventsub/conduits/shards',\n method: 'PATCH',\n jsonBody: createEventSubConduitShardsUpdateCondition(conduitId, shards),\n });\n return result.data.map(data => new HelixEventSubConduitShard(data));\n }\n async _deleteSubscriptionsWithCondition(cond) {\n const subsPaginator = this.getSubscriptionsPaginated();\n for await (const sub of subsPaginator) {\n if (!cond || cond(sub)) {\n await sub.unsubscribe();\n }\n }\n }\n};\nHelixEventSubApi = __decorate([\n rtfm('api', 'HelixEventSubApi')\n], HelixEventSubApi);\nexport { HelixEventSubApi };\n", "import { extractUserId } from '@twurple/common';\n/** @internal */\nexport function createEventSubBroadcasterCondition(broadcaster) {\n return {\n broadcaster_user_id: extractUserId(broadcaster),\n };\n}\n/** @internal */\nexport function createEventSubRewardCondition(broadcaster, rewardId) {\n return { broadcaster_user_id: extractUserId(broadcaster), reward_id: rewardId };\n}\n/** @internal */\nexport function createEventSubModeratorCondition(broadcasterId, moderatorId) {\n return {\n broadcaster_user_id: broadcasterId,\n moderator_user_id: moderatorId,\n };\n}\n/** @internal */\nexport function createEventSubUserCondition(broadcasterId, userId) {\n return {\n broadcaster_user_id: broadcasterId,\n user_id: userId,\n };\n}\n/** @internal */\nexport function createEventSubDropEntitlementGrantCondition(filter) {\n return {\n organization_id: filter.organizationId,\n category_id: filter.categoryId,\n campaign_id: filter.campaignId,\n };\n}\n/** @internal */\nexport function createEventSubConduitCondition(conduitId, status) {\n return {\n conduit_id: conduitId,\n status,\n };\n}\n/** @internal */\nexport function createEventSubConduitUpdateCondition(conduitId, shardCount) {\n return {\n id: conduitId,\n shard_count: shardCount.toString(),\n };\n}\n/** @internal */\nexport function createEventSubConduitShardsUpdateCondition(conduitId, shards) {\n return {\n conduit_id: conduitId,\n shards,\n };\n}\n", "import { __decorate } from \"tslib\";\nimport { Enumerable } from '@d-fischer/shared-utils';\nimport { DataObject, rawDataSymbol, rtfm } from '@twurple/common';\n/**\n * An EventSub subscription.\n */\nlet HelixEventSubSubscription = class HelixEventSubSubscription extends DataObject {\n /** @internal */ _client;\n /** @internal */\n constructor(data, client) {\n super(data);\n this._client = client;\n }\n /**\n * The ID of the subscription.\n */\n get id() {\n return this[rawDataSymbol].id;\n }\n /**\n * The status of the subscription.\n */\n get status() {\n return this[rawDataSymbol].status;\n }\n /**\n * The event type that the subscription is listening to.\n */\n get type() {\n return this[rawDataSymbol].type;\n }\n /**\n * The cost of the subscription.\n */\n get cost() {\n return this[rawDataSymbol].cost;\n }\n /**\n * The condition of the subscription.\n */\n get condition() {\n return this[rawDataSymbol].condition;\n }\n /**\n * The date and time of creation of the subscription.\n */\n get creationDate() {\n return new Date(this[rawDataSymbol].created_at);\n }\n /**\n * The transport method of the subscription.\n */\n get transportMethod() {\n return this[rawDataSymbol].transport.method;\n }\n /**\n * End the EventSub subscription.\n */\n async unsubscribe() {\n await this._client.eventSub.deleteSubscription(this[rawDataSymbol].id);\n }\n /** @private */\n get _transport() {\n return this[rawDataSymbol].transport;\n }\n /** @private */\n set _status(status) {\n this[rawDataSymbol].status = status;\n }\n};\n__decorate([\n Enumerable(false)\n], HelixEventSubSubscription.prototype, \"_client\", void 0);\nHelixEventSubSubscription = __decorate([\n rtfm('api', 'HelixEventSubSubscription', 'id')\n], HelixEventSubSubscription);\nexport { HelixEventSubSubscription };\n", "import { __decorate } from \"tslib\";\nimport { rtfm } from '@twurple/common';\nimport { HelixPaginatedRequestWithTotal } from '../../utils/pagination/HelixPaginatedRequestWithTotal.js';\nimport { HelixEventSubSubscription } from './HelixEventSubSubscription.js';\n/**\n * A special case of {@link HelixPaginatedRequestWithTotal} with support for fetching the total cost and cost limit\n * of EventSub subscriptions.\n *\n * @inheritDoc\n */\nlet HelixPaginatedEventSubSubscriptionsRequest = class HelixPaginatedEventSubSubscriptionsRequest extends HelixPaginatedRequestWithTotal {\n /** @internal */\n constructor(query, userId, client) {\n super({\n url: 'eventsub/subscriptions',\n userId,\n query,\n }, client, data => new HelixEventSubSubscription(data, client));\n }\n /**\n * Gets the total cost of EventSub subscriptions.\n */\n async getTotalCost() {\n const data = this._currentData ??\n (await this._fetchData({ query: { after: undefined } }));\n return data.total_cost;\n }\n /**\n * Gets the cost limit of EventSub subscriptions.\n */\n async getMaxTotalCost() {\n const data = this._currentData ??\n (await this._fetchData({ query: { after: undefined } }));\n return data.max_total_cost;\n }\n};\nHelixPaginatedEventSubSubscriptionsRequest = __decorate([\n rtfm('api', 'HelixPaginatedEventSubSubscriptionsRequest')\n], HelixPaginatedEventSubSubscriptionsRequest);\nexport { HelixPaginatedEventSubSubscriptionsRequest };\n", "import { __decorate } from \"tslib\";\nimport { Enumerable } from '@d-fischer/shared-utils';\nimport { DataObject, rawDataSymbol, rtfm } from '@twurple/common';\n/**\n * Represents an EventSub conduit.\n */\nlet HelixEventSubConduit = class HelixEventSubConduit extends DataObject {\n /** @internal */ _client;\n /** @internal */\n constructor(data, client) {\n super(data);\n this._client = client;\n }\n /**\n * The ID of the conduit.\n */\n get id() {\n return this[rawDataSymbol].id;\n }\n /**\n * The shard count of the conduit.\n */\n get shardCount() {\n return this[rawDataSymbol].shard_count;\n }\n /**\n * Update the conduit.\n *\n * @param shardCount The new shard count.\n */\n async update(shardCount) {\n return await this._client.eventSub.updateConduit(this[rawDataSymbol].id, shardCount);\n }\n /**\n * Delete the conduit.\n */\n async delete() {\n await this._client.eventSub.deleteConduit(this[rawDataSymbol].id);\n }\n /**\n * Get the conduit shards.\n */\n async getShards() {\n return await this._client.eventSub.getConduitShards(this[rawDataSymbol].id);\n }\n};\n__decorate([\n Enumerable(false)\n], HelixEventSubConduit.prototype, \"_client\", void 0);\nHelixEventSubConduit = __decorate([\n rtfm('api', 'HelixEventSubConduit')\n], HelixEventSubConduit);\nexport { HelixEventSubConduit };\n", "import { __decorate } from \"tslib\";\nimport { DataObject, rawDataSymbol, rtfm } from '@twurple/common';\n/**\n * Represents an EventSub conduit shard.\n */\nlet HelixEventSubConduitShard = class HelixEventSubConduitShard extends DataObject {\n /**\n * The ID of the shard.\n */\n get id() {\n return this[rawDataSymbol].id;\n }\n /**\n * The status of the shard.\n */\n get status() {\n return this[rawDataSymbol].status;\n }\n /**\n * The transport method of the shard.\n */\n get transportMethod() {\n return this[rawDataSymbol].transport.method;\n }\n};\nHelixEventSubConduitShard = __decorate([\n rtfm('api', 'HelixEventSubConduitShard')\n], HelixEventSubConduitShard);\nexport { HelixEventSubConduitShard };\n", "import { __decorate } from \"tslib\";\nimport { HelixExtension, rtfm } from '@twurple/common';\nimport { createExtensionProductBody, createExtensionTransactionQuery, createReleasedExtensionFilter, } from '../../interfaces/endpoints/extensions.external.js';\nimport { createSingleKeyQuery } from '../../interfaces/endpoints/generic.external.js';\nimport { HelixPaginatedRequest } from '../../utils/pagination/HelixPaginatedRequest.js';\nimport { createPaginatedResult } from '../../utils/pagination/HelixPaginatedResult.js';\nimport { createPaginationQuery } from '../../utils/pagination/HelixPagination.js';\nimport { BaseApi } from '../BaseApi.js';\nimport { HelixChannelReference } from '../channel/HelixChannelReference.js';\nimport { HelixExtensionBitsProduct } from './HelixExtensionBitsProduct.js';\nimport { HelixExtensionTransaction } from './HelixExtensionTransaction.js';\n/**\n * The Helix API methods that deal with extensions.\n *\n * Can be accessed using `client.extensions` on an {@link ApiClient} instance.\n *\n * ## Example\n * ```ts\n * const api = new ApiClient({ authProvider });\n * const transactions = await api.extionsions.getExtensionTransactions('abcd');\n * ```\n *\n * @meta category helix\n * @meta categorizedTitle Extensions\n */\nlet HelixExtensionsApi = class HelixExtensionsApi extends BaseApi {\n /**\n * Gets a released extension by ID.\n *\n * @param extensionId The ID of the extension.\n * @param version The version of the extension. If not given, gets the latest version.\n */\n async getReleasedExtension(extensionId, version) {\n const result = await this._client.callApi({\n type: 'helix',\n url: 'extensions/released',\n query: createReleasedExtensionFilter(extensionId, version),\n });\n return new HelixExtension(result.data[0]);\n }\n /**\n * Gets a list of channels that are currently live and have the given extension installed.\n *\n * @param extensionId The ID of the extension.\n * @param pagination\n *\n * @expandParams\n */\n async getLiveChannelsWithExtension(extensionId, pagination) {\n const result = await this._client.callApi({\n type: 'helix',\n url: 'extensions/live',\n query: {\n ...createSingleKeyQuery('extension_id', extensionId),\n ...createPaginationQuery(pagination),\n },\n });\n return createPaginatedResult(result, HelixChannelReference, this._client);\n }\n /**\n * Creates a paginator for channels that are currently live and have the given extension installed.\n *\n * @param extensionId The ID of the extension.\n */\n getLiveChannelsWithExtensionPaginated(extensionId) {\n return new HelixPaginatedRequest({\n url: 'extensions/live',\n query: createSingleKeyQuery('extension_id', extensionId),\n }, this._client, data => new HelixChannelReference(data, this._client));\n }\n /**\n * Gets an extension's Bits products.\n *\n * This only works if the provided token belongs to an extension's client ID,\n * and will return the products for that extension.\n *\n * @param includeDisabled Whether to include disabled/expired products.\n */\n async getExtensionBitsProducts(includeDisabled) {\n const result = await this._client.callApi({\n type: 'helix',\n url: 'bits/extensions',\n forceType: 'app',\n query: createSingleKeyQuery('should_include_all', includeDisabled?.toString()),\n });\n return result.data.map(data => new HelixExtensionBitsProduct(data));\n }\n /**\n * Creates or updates a Bits product of an extension.\n *\n * This only works if the provided token belongs to an extension's client ID,\n * and will create/update a product for that extension.\n *\n * @param data\n *\n * @expandParams\n */\n async putExtensionBitsProduct(data) {\n const result = await this._client.callApi({\n type: 'helix',\n url: 'bits/extensions',\n method: 'PUT',\n forceType: 'app',\n jsonBody: createExtensionProductBody(data),\n });\n return new HelixExtensionBitsProduct(result.data[0]);\n }\n /**\n * Gets a list of transactions for the given extension.\n *\n * @param extensionId The ID of the extension to get transactions for.\n * @param filter Additional filters.\n */\n async getExtensionTransactions(extensionId, filter = {}) {\n const result = await this._client.callApi({\n type: 'helix',\n url: 'extensions/transactions',\n forceType: 'app',\n query: {\n ...createExtensionTransactionQuery(extensionId, filter),\n ...createPaginationQuery(filter),\n },\n });\n return createPaginatedResult(result, HelixExtensionTransaction, this._client);\n }\n /**\n * Creates a paginator for transactions for the given extension.\n *\n * @param extensionId The ID of the extension to get transactions for.\n * @param filter Additional filters.\n */\n getExtensionTransactionsPaginated(extensionId, filter = {}) {\n return new HelixPaginatedRequest({\n url: 'extensions/transactions',\n forceType: 'app',\n query: createExtensionTransactionQuery(extensionId, filter),\n }, this._client, data => new HelixExtensionTransaction(data, this._client));\n }\n};\nHelixExtensionsApi = __decorate([\n rtfm('api', 'HelixExtensionsApi')\n], HelixExtensionsApi);\nexport { HelixExtensionsApi };\n", "/** @internal */\nexport function createReleasedExtensionFilter(extensionId, version) {\n return {\n extension_id: extensionId,\n extension_version: version,\n };\n}\n/** @internal */\nexport function createExtensionProductBody(data) {\n return {\n sku: data.sku,\n cost: {\n amount: data.cost,\n type: 'bits',\n },\n display_name: data.displayName,\n in_development: data.inDevelopment,\n expiration: data.expirationDate,\n is_broadcast: data.broadcast,\n };\n}\n/** @internal */\nexport function createExtensionTransactionQuery(extensionId, filter) {\n return {\n extension_id: extensionId,\n id: filter.transactionIds,\n };\n}\n", "import { __decorate } from \"tslib\";\nimport { Enumerable } from '@d-fischer/shared-utils';\nimport { checkRelationAssertion, DataObject, rawDataSymbol, rtfm } from '@twurple/common';\n/**\n * A reference to a Twitch channel.\n */\nlet HelixChannelReference = class HelixChannelReference extends DataObject {\n /** @internal */ _client;\n /** @internal */\n constructor(data, client) {\n super(data);\n this._client = client;\n }\n /**\n * The ID of the channel.\n */\n get id() {\n return this[rawDataSymbol].broadcaster_id;\n }\n /**\n * The display name of the channel.\n */\n get displayName() {\n return this[rawDataSymbol].broadcaster_name;\n }\n /**\n * Gets more information about the channel.\n */\n async getChannel() {\n return checkRelationAssertion(await this._client.channels.getChannelInfoById(this[rawDataSymbol].broadcaster_id));\n }\n /**\n * Gets more information about the broadcaster of the channel.\n */\n async getBroadcaster() {\n return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].broadcaster_id));\n }\n /**\n * The ID of the game currently played on the channel.\n */\n get gameId() {\n return this[rawDataSymbol].game_id;\n }\n /**\n * The name of the game currently played on the channel.\n */\n get gameName() {\n return this[rawDataSymbol].game_name;\n }\n /**\n * Gets information about the game that is being played on the stream.\n */\n async getGame() {\n return this[rawDataSymbol].game_id\n ? checkRelationAssertion(await this._client.games.getGameById(this[rawDataSymbol].game_id))\n : null;\n }\n /**\n * The title of the channel.\n */\n get title() {\n return this[rawDataSymbol].title;\n }\n};\n__decorate([\n Enumerable(false)\n], HelixChannelReference.prototype, \"_client\", void 0);\nHelixChannelReference = __decorate([\n rtfm('api', 'HelixChannelReference', 'id')\n], HelixChannelReference);\nexport { HelixChannelReference };\n", "import { __decorate } from \"tslib\";\nimport { mapNullable } from '@d-fischer/shared-utils';\nimport { DataObject, rawDataSymbol, rtfm } from '@twurple/common';\n/**\n * An extension's product to purchase with Bits.\n */\nlet HelixExtensionBitsProduct = class HelixExtensionBitsProduct extends DataObject {\n /**\n * The product's unique identifier.\n */\n get sku() {\n return this[rawDataSymbol].sku;\n }\n /**\n * The product's cost, in bits.\n */\n get cost() {\n return this[rawDataSymbol].cost.amount;\n }\n /**\n * The product's display name.\n */\n get displayName() {\n return this[rawDataSymbol].display_name;\n }\n /**\n * Whether the product is in development.\n */\n get inDevelopment() {\n return this[rawDataSymbol].in_development;\n }\n /**\n * Whether the product's purchases is broadcast to all users.\n */\n get isBroadcast() {\n return this[rawDataSymbol].is_broadcast;\n }\n /**\n * The product's expiration date. If the product never expires, this is null.\n */\n get expirationDate() {\n return mapNullable(this[rawDataSymbol].expiration, exp => new Date(exp));\n }\n};\nHelixExtensionBitsProduct = __decorate([\n rtfm('api', 'HelixExtensionBitsProduct', 'sku')\n], HelixExtensionBitsProduct);\nexport { HelixExtensionBitsProduct };\n", "import { __decorate } from \"tslib\";\nimport { Enumerable } from '@d-fischer/shared-utils';\nimport { checkRelationAssertion, DataObject, rawDataSymbol, rtfm } from '@twurple/common';\n/**\n * A bits transaction made inside an extension.\n */\nlet HelixExtensionTransaction = class HelixExtensionTransaction extends DataObject {\n /** @internal */ _client;\n /** @internal */\n constructor(data, client) {\n super(data);\n this._client = client;\n }\n /**\n * The ID of the transaction.\n */\n get id() {\n return this[rawDataSymbol].id;\n }\n /**\n * The time when the transaction was made.\n */\n get transactionDate() {\n return new Date(this[rawDataSymbol].timestamp);\n }\n /**\n * The ID of the broadcaster that runs the extension on their channel.\n */\n get broadcasterId() {\n return this[rawDataSymbol].broadcaster_id;\n }\n /**\n * The name of the broadcaster that runs the extension on their channel.\n */\n get broadcasterName() {\n return this[rawDataSymbol].broadcaster_name;\n }\n /**\n * The display name of the broadcaster that runs the extension on their channel.\n */\n get broadcasterDisplayName() {\n return this[rawDataSymbol].broadcaster_name;\n }\n /**\n * Gets information about the broadcaster that runs the extension on their channel.\n */\n async getBroadcaster() {\n return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].broadcaster_id));\n }\n /**\n * The ID of the user that made the transaction.\n */\n get userId() {\n return this[rawDataSymbol].user_id;\n }\n /**\n * The name of the user that made the transaction.\n */\n get userName() {\n return this[rawDataSymbol].user_login;\n }\n /**\n * The display name of the user that made the transaction.\n */\n get userDisplayName() {\n return this[rawDataSymbol].user_name;\n }\n /**\n * Gets information about the user that made the transaction.\n */\n async getUser() {\n return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].user_id));\n }\n /**\n * The product type. Currently always BITS_IN_EXTENSION.\n */\n get productType() {\n return this[rawDataSymbol].product_type;\n }\n /**\n * The product SKU.\n */\n get productSku() {\n return this[rawDataSymbol].product_data.sku;\n }\n /**\n * The cost of the product, in bits.\n */\n get productCost() {\n return this[rawDataSymbol].product_data.cost.amount;\n }\n /**\n * The display name of the product.\n */\n get productDisplayName() {\n return this[rawDataSymbol].product_data.displayName;\n }\n /**\n * Whether the product is in development.\n */\n get productInDevelopment() {\n return this[rawDataSymbol].product_data.inDevelopment;\n }\n};\n__decorate([\n Enumerable(false)\n], HelixExtensionTransaction.prototype, \"_client\", void 0);\nHelixExtensionTransaction = __decorate([\n rtfm('api', 'HelixExtensionTransaction', 'id')\n], HelixExtensionTransaction);\nexport { HelixExtensionTransaction };\n", "import { __decorate } from \"tslib\";\nimport { Enumerable } from '@d-fischer/shared-utils';\nimport { rtfm } from '@twurple/common';\nimport { HelixRequestBatcher } from '../../utils/HelixRequestBatcher.js';\nimport { HelixPaginatedRequest } from '../../utils/pagination/HelixPaginatedRequest.js';\nimport { createPaginatedResult } from '../../utils/pagination/HelixPaginatedResult.js';\nimport { createPaginationQuery } from '../../utils/pagination/HelixPagination.js';\nimport { BaseApi } from '../BaseApi.js';\nimport { HelixGame } from './HelixGame.js';\n/**\n * The Helix API methods that deal with games.\n *\n * Can be accessed using `client.games` on an {@link ApiClient} instance.\n *\n * ## Example\n * ```ts\n * const api = new ApiClient({ authProvider });\n * const game = await api.games.getGameByName('Hearthstone');\n * ```\n *\n * @meta category helix\n * @meta categorizedTitle Games\n */\nlet HelixGameApi = class HelixGameApi extends BaseApi {\n /** @internal */\n _getGameByIdBatcher = new HelixRequestBatcher({\n url: 'games',\n }, 'id', 'id', this._client, (data) => new HelixGame(data, this._client));\n /** @internal */\n _getGameByNameBatcher = new HelixRequestBatcher({\n url: 'games',\n }, 'name', 'name', this._client, (data) => new HelixGame(data, this._client));\n /** @internal */\n _getGameByIgdbIdBatcher = new HelixRequestBatcher({\n url: 'games',\n }, 'igdb_id', 'igdb_id', this._client, (data) => new HelixGame(data, this._client));\n /**\n * Gets the game data for the given list of game IDs.\n *\n * @param ids The game IDs you want to look up.\n */\n async getGamesByIds(ids) {\n return await this._getGames('id', ids);\n }\n /**\n * Gets the game data for the given list of game names.\n *\n * @param names The game names you want to look up.\n */\n async getGamesByNames(names) {\n return await this._getGames('name', names);\n }\n /**\n * Gets the game data for the given list of IGDB IDs.\n *\n * @param igdbIds The IGDB IDs you want to look up.\n */\n async getGamesByIgdbIds(igdbIds) {\n return await this._getGames('igdb_id', igdbIds);\n }\n /**\n * Gets the game data for the given game ID.\n *\n * @param id The game ID you want to look up.\n */\n async getGameById(id) {\n const games = await this._getGames('id', [id]);\n return games[0] ?? null;\n }\n /**\n * Gets the game data for the given game name.\n *\n * @param name The game name you want to look up.\n */\n async getGameByName(name) {\n const games = await this._getGames('name', [name]);\n return games[0] ?? null;\n }\n /**\n * Gets the game data for the given IGDB ID.\n *\n * @param igdbId The IGDB ID you want to look up.\n */\n async getGameByIgdbId(igdbId) {\n const games = await this._getGames('igdb_id', [igdbId]);\n return games[0] ?? null;\n }\n /**\n * Gets the game data for the given game ID, batching multiple calls into fewer requests as the API allows.\n *\n * @param id The game ID you want to look up.\n */\n async getGameByIdBatched(id) {\n return await this._getGameByIdBatcher.request(id);\n }\n /**\n * Gets the game data for the given game name, batching multiple calls into fewer requests as the API allows.\n *\n * @param name The game name you want to look up.\n */\n async getGameByNameBatched(name) {\n return await this._getGameByNameBatcher.request(name);\n }\n /**\n * Gets the game data for the given IGDB ID, batching multiple calls into fewer requests as the API allows.\n *\n * @param igdbId The IGDB ID you want to look up.\n */\n async getGameByIgdbIdBatched(igdbId) {\n return await this._getGameByIgdbIdBatcher.request(igdbId);\n }\n /**\n * Gets a list of the most viewed games at the moment.\n *\n * @param pagination\n *\n * @expandParams\n */\n async getTopGames(pagination) {\n const result = await this._client.callApi({\n type: 'helix',\n url: 'games/top',\n query: createPaginationQuery(pagination),\n });\n return createPaginatedResult(result, HelixGame, this._client);\n }\n /**\n * Creates a paginator for the most viewed games at the moment.\n */\n getTopGamesPaginated() {\n return new HelixPaginatedRequest({\n url: 'games/top',\n }, this._client, data => new HelixGame(data, this._client));\n }\n /** @internal */\n async _getGames(filterType, filterValues) {\n if (!filterValues.length) {\n return [];\n }\n const result = await this._client.callApi({\n type: 'helix',\n url: 'games',\n query: {\n [filterType]: filterValues,\n },\n });\n return result.data.map(entry => new HelixGame(entry, this._client));\n }\n};\n__decorate([\n Enumerable(false)\n], HelixGameApi.prototype, \"_getGameByIdBatcher\", void 0);\n__decorate([\n Enumerable(false)\n], HelixGameApi.prototype, \"_getGameByNameBatcher\", void 0);\n__decorate([\n Enumerable(false)\n], HelixGameApi.prototype, \"_getGameByIgdbIdBatcher\", void 0);\nHelixGameApi = __decorate([\n rtfm('api', 'HelixGameApi')\n], HelixGameApi);\nexport { HelixGameApi };\n", "import { __decorate } from \"tslib\";\nimport { Enumerable } from '@d-fischer/shared-utils';\nimport { DataObject, rawDataSymbol, rtfm } from '@twurple/common';\n/**\n * A game as displayed on Twitch.\n */\nlet HelixGame = class HelixGame extends DataObject {\n /** @internal */ _client;\n /** @internal */\n constructor(data, client) {\n super(data);\n this._client = client;\n }\n /**\n * The ID of the game.\n */\n get id() {\n return this[rawDataSymbol].id;\n }\n /**\n * The name of the game.\n */\n get name() {\n return this[rawDataSymbol].name;\n }\n /**\n * The URL of the box art of the game.\n */\n get boxArtUrl() {\n return this[rawDataSymbol].box_art_url;\n }\n /**\n * The IGDB ID of the game, or null if the game doesn't have an IGDB ID assigned at Twitch.\n */\n get igdbId() {\n return this[rawDataSymbol].igdb_id || null;\n }\n /**\n * Builds the URL of the box art of the game using the given dimensions.\n *\n * @param width The width of the box art.\n * @param height The height of the box art.\n */\n getBoxArtUrl(width, height) {\n return this[rawDataSymbol].box_art_url\n .replace('{width}', width.toString())\n .replace('{height}', height.toString());\n }\n /**\n * Gets streams that are currently playing the game.\n *\n * @param pagination\n * @expandParams\n */\n async getStreams(pagination) {\n return await this._client.streams.getStreams({ ...pagination, game: this[rawDataSymbol].id });\n }\n /**\n * Creates a paginator for streams that are currently playing the game.\n */\n getStreamsPaginated() {\n return this._client.streams.getStreamsPaginated({ game: this[rawDataSymbol].id });\n }\n};\n__decorate([\n Enumerable(false)\n], HelixGame.prototype, \"_client\", void 0);\nHelixGame = __decorate([\n rtfm('api', 'HelixGame', 'id')\n], HelixGame);\nexport { HelixGame };\n", "import { __decorate } from \"tslib\";\nimport { createBroadcasterQuery } from '@twurple/api-call';\nimport { extractUserId, rtfm } from '@twurple/common';\nimport { BaseApi } from '../BaseApi.js';\nimport { HelixGoal } from './HelixGoal.js';\n/**\n * The Helix API methods that deal with creator goals.\n *\n * Can be accessed using `client.goals` on an {@link ApiClient} instance.\n *\n * ## Example\n * ```ts\n * const api = new ApiClient({ authProvider });\n * const { data: goals } = await api.helix.goals.getGoals('61369223');\n *\n * @meta category helix\n * @meta categorizedTitle Goals\n */\nlet HelixGoalApi = class HelixGoalApi extends BaseApi {\n async getGoals(broadcaster) {\n const result = await this._client.callApi({\n type: 'helix',\n url: 'goals',\n userId: extractUserId(broadcaster),\n scopes: ['channel:read:goals'],\n query: createBroadcasterQuery(broadcaster),\n });\n return result.data.map(data => new HelixGoal(data, this._client));\n }\n};\nHelixGoalApi = __decorate([\n rtfm('api', 'HelixGoalApi')\n], HelixGoalApi);\nexport { HelixGoalApi };\n", "import { __decorate } from \"tslib\";\nimport { Enumerable } from '@d-fischer/shared-utils';\nimport { checkRelationAssertion, DataObject, rawDataSymbol, rtfm } from '@twurple/common';\n/**\n * A creator goal.\n */\nlet HelixGoal = class HelixGoal extends DataObject {\n /** @internal */ _client;\n /** @internal */\n constructor(data, client) {\n super(data);\n this._client = client;\n }\n /**\n * The ID of the goal.\n */\n get id() {\n return this[rawDataSymbol].id;\n }\n /**\n * The ID of the broadcaster the goal belongs to.\n */\n get broadcasterId() {\n return this[rawDataSymbol].broadcaster_id;\n }\n /**\n * The display name of the broadcaster the goal belongs to.\n */\n get broadcasterDisplayName() {\n return this[rawDataSymbol].broadcaster_name;\n }\n /**\n * The name of the broadcaster the goal belongs to.\n */\n get broadcasterName() {\n return this[rawDataSymbol].broadcaster_login;\n }\n /**\n * Gets more information about the broadcaster.\n */\n async getBroadcaster() {\n return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].broadcaster_id));\n }\n /**\n * The type of the goal.\n */\n get type() {\n return this[rawDataSymbol].type;\n }\n /**\n * The description of the goal.\n */\n get description() {\n return this[rawDataSymbol].description;\n }\n /**\n * The current value of the goal.\n */\n get currentAmount() {\n return this[rawDataSymbol].current_amount;\n }\n /**\n * The target value of the goal.\n */\n get targetAmount() {\n return this[rawDataSymbol].target_amount;\n }\n /**\n * The date and time when the goal was created.\n */\n get creationDate() {\n return this[rawDataSymbol].created_at;\n }\n};\n__decorate([\n Enumerable(false)\n], HelixGoal.prototype, \"_client\", void 0);\nHelixGoal = __decorate([\n rtfm('api', 'HelixGoal', 'id')\n], HelixGoal);\nexport { HelixGoal };\n", "import { createBroadcasterQuery } from '@twurple/api-call';\nimport { extractUserId } from '@twurple/common';\nimport { BaseApi } from '../BaseApi.js';\nimport { HelixHypeTrainStatus } from './HelixHypeTrainStatus.js';\n/**\n * The Helix API methods that deal with Hype Trains.\n *\n * Can be accessed using `client.hypeTrain` on an {@link ApiClient} instance.\n *\n * ## Example\n * ```ts\n * const api = new ApiClient({ authProvider });\n * const hypeTrainStatus = await api.hypeTrain.getHypeTrainStatusForBroadcaster('125328655');\n * ```\n *\n * @meta category helix\n * @meta categorizedTitle Hype Trains\n */\nexport class HelixHypeTrainApi extends BaseApi {\n /**\n * Gets the Hype Train status and statistics for the specified broadcaster.\n *\n * @param broadcaster The broadcaster to fetch Hype Train info for.\n */\n async getHypeTrainStatusForBroadcaster(broadcaster) {\n const result = await this._client.callApi({\n type: 'helix',\n url: 'hypetrain/status',\n userId: extractUserId(broadcaster),\n scopes: ['channel:read:hype_train'],\n query: {\n ...createBroadcasterQuery(broadcaster),\n },\n });\n return new HelixHypeTrainStatus(result.data[0], this._client);\n }\n}\n", "import { __decorate } from \"tslib\";\nimport { Enumerable, mapNullable } from '@d-fischer/shared-utils';\nimport { DataObject, rawDataSymbol, rtfm } from '@twurple/common';\nimport { HelixHypeTrain } from './HelixHypeTrain.js';\nimport { HelixHypeTrainAllTimeHigh } from './HelixHypeTrainAllTimeHigh.js';\n/**\n * Statistics of Hype Trains on a channel.\n */\nlet HelixHypeTrainStatus = class HelixHypeTrainStatus extends DataObject {\n /** @internal */ _client;\n /** @internal */\n constructor(data, client) {\n super(data);\n this._client = client;\n }\n /**\n * The current Hype Train, or null if there is no ongoing Hype Train.\n */\n get current() {\n return mapNullable(this[rawDataSymbol].current, data => new HelixHypeTrain(data, this._client));\n }\n /**\n * The all-time-high Hype Train statistics for this channel, or null if there was no Hype Train yet.\n */\n get allTimeHigh() {\n return mapNullable(this[rawDataSymbol].all_time_high, data => new HelixHypeTrainAllTimeHigh(data));\n }\n /**\n * The all-time-high shared Hype Train statistics for this channel, or null if there was no shared Hype Train yet.\n */\n get sharedAllTimeHigh() {\n return mapNullable(this[rawDataSymbol].shared_all_time_high, data => new HelixHypeTrainAllTimeHigh(data));\n }\n};\n__decorate([\n Enumerable(false)\n], HelixHypeTrainStatus.prototype, \"_client\", void 0);\nHelixHypeTrainStatus = __decorate([\n rtfm('api', 'HelixHypeTrainStatus')\n], HelixHypeTrainStatus);\nexport { HelixHypeTrainStatus };\n", "import { __decorate } from \"tslib\";\nimport { Enumerable } from '@d-fischer/shared-utils';\nimport { checkRelationAssertion, DataObject, rawDataSymbol, rtfm } from '@twurple/common';\nimport { HelixHypeTrainContribution } from './HelixHypeTrainContribution.js';\n/**\n * Data about the currently running Hype Train.\n */\nlet HelixHypeTrain = class HelixHypeTrain extends DataObject {\n /** @internal */ _client;\n /** @internal */\n constructor(data, client) {\n super(data);\n this._client = client;\n }\n /**\n * The unique ID of the Hype Train event.\n */\n get eventId() {\n return this[rawDataSymbol].id;\n }\n /**\n * The unique ID of the Hype Train.\n */\n get id() {\n return this[rawDataSymbol].id;\n }\n /**\n * The user ID of the broadcaster where the Hype Train is happening.\n */\n get broadcasterId() {\n return this[rawDataSymbol].broadcaster_user_id;\n }\n /**\n * The name of the broadcaster where the Hype Train is happening.\n */\n get broadcasterName() {\n return this[rawDataSymbol].broadcaster_user_login;\n }\n /**\n * The display name of the broadcaster where the Hype Train is happening.\n */\n get broadcasterDisplayName() {\n return this[rawDataSymbol].broadcaster_user_name;\n }\n /**\n * Gets more information about the broadcaster where the Hype Train is happening.\n */\n async getBroadcaster() {\n return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].broadcaster_user_id));\n }\n /**\n * The level of the Hype Train.\n */\n get level() {\n return this[rawDataSymbol].level;\n }\n /**\n * The total amount of progress points of the Hype Train.\n */\n get total() {\n return this[rawDataSymbol].total;\n }\n /**\n * The amount progress points for the current level of the Hype Train.\n */\n get progress() {\n return this[rawDataSymbol].progress;\n }\n /**\n * The progress points goal to reach the next Hype Train level.\n */\n get goal() {\n return this[rawDataSymbol].goal;\n }\n /**\n * Array list of the top contributions to the Hype Train event for bits and subs.\n */\n get topContributions() {\n return this[rawDataSymbol].top_contributions.map(cont => new HelixHypeTrainContribution(cont, this._client));\n }\n /**\n * The time when the Hype Train started.\n */\n get startDate() {\n return new Date(this[rawDataSymbol].started_at);\n }\n /**\n * The time when the Hype Train is set to expire.\n */\n get expiryDate() {\n return new Date(this[rawDataSymbol].expires_at);\n }\n /**\n * The type of the Hype Train.\n */\n get type() {\n return this[rawDataSymbol].type;\n }\n /**\n * Whether the Hype Train is a shared train.\n */\n get isSharedTrain() {\n return this[rawDataSymbol].is_shared_train;\n }\n};\n__decorate([\n Enumerable(false)\n], HelixHypeTrain.prototype, \"_client\", void 0);\nHelixHypeTrain = __decorate([\n rtfm('api', 'HelixHypeTrain', 'id')\n], HelixHypeTrain);\nexport { HelixHypeTrain };\n", "import { __decorate } from \"tslib\";\nimport { Enumerable } from '@d-fischer/shared-utils';\nimport { checkRelationAssertion, DataObject, rawDataSymbol, rtfm } from '@twurple/common';\n/**\n * A Hype Train contributor.\n */\nlet HelixHypeTrainContribution = class HelixHypeTrainContribution extends DataObject {\n /** @internal */ _client;\n /** @internal */\n constructor(data, client) {\n super(data);\n this._client = client;\n }\n /**\n * The ID of the user contributing to the Hype Train.\n */\n get userId() {\n return this[rawDataSymbol].user_id;\n }\n /**\n * The name of the user contributing to the Hype Train.\n */\n get userName() {\n return this[rawDataSymbol].user_login;\n }\n /**\n * The display name of the user contributing to the Hype Train.\n */\n get userDisplayName() {\n return this[rawDataSymbol].user_name;\n }\n /**\n * Gets additional information about the user contributing to the Hype Train.\n */\n async getUser() {\n return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].user_id));\n }\n /**\n * The type of the Hype Train contribution.\n */\n get type() {\n return this[rawDataSymbol].type;\n }\n /**\n * The total contribution amount in subs or bits.\n */\n get total() {\n return this[rawDataSymbol].total;\n }\n};\n__decorate([\n Enumerable(false)\n], HelixHypeTrainContribution.prototype, \"_client\", void 0);\nHelixHypeTrainContribution = __decorate([\n rtfm('api', 'HelixHypeTrainContribution', 'userId')\n], HelixHypeTrainContribution);\nexport { HelixHypeTrainContribution };\n", "import { __decorate } from \"tslib\";\nimport { DataObject, rawDataSymbol, rtfm } from '@twurple/common';\n/**\n * All-time-high Hype Train statistics.\n */\nlet HelixHypeTrainAllTimeHigh = class HelixHypeTrainAllTimeHigh extends DataObject {\n /**\n * The level reached by the all-time-high Hype Train.\n */\n get level() {\n return this[rawDataSymbol].level;\n }\n /**\n * The total amount of contribution points reached by the all-time-high Hype Train.\n */\n get total() {\n return this[rawDataSymbol].total;\n }\n /**\n * The time when the all-time-high Hype Train was achieved.\n */\n get achievementDate() {\n return new Date(this[rawDataSymbol].achieved_at);\n }\n};\nHelixHypeTrainAllTimeHigh = __decorate([\n rtfm('api', 'HelixHypeTrainAllTimeHigh')\n], HelixHypeTrainAllTimeHigh);\nexport { HelixHypeTrainAllTimeHigh };\n", "import { __decorate } from \"tslib\";\nimport { createBroadcasterQuery } from '@twurple/api-call';\nimport { extractUserId, rtfm } from '@twurple/common';\nimport { createModeratorActionQuery, createSingleKeyQuery } from '../../interfaces/endpoints/generic.external.js';\nimport { createAutoModProcessBody, createAutoModSettingsBody, createBanUserBody, createCheckAutoModStatusBody, createModerationUserListQuery, createModeratorModifyQuery, createResolveUnbanRequestQuery, createUpdateShieldModeStatusBody, createWarnUserBody, } from '../../interfaces/endpoints/moderation.external.js';\nimport { HelixPaginatedRequest } from '../../utils/pagination/HelixPaginatedRequest.js';\nimport { createPaginatedResult } from '../../utils/pagination/HelixPaginatedResult.js';\nimport { createPaginationQuery } from '../../utils/pagination/HelixPagination.js';\nimport { BaseApi } from '../BaseApi.js';\nimport { HelixAutoModSettings } from './HelixAutoModSettings.js';\nimport { HelixAutoModStatus } from './HelixAutoModStatus.js';\nimport { HelixBan } from './HelixBan.js';\nimport { HelixBanUser } from './HelixBanUser.js';\nimport { HelixBlockedTerm } from './HelixBlockedTerm.js';\nimport { HelixModeratedChannel } from './HelixModeratedChannel.js';\nimport { HelixModerator } from './HelixModerator.js';\nimport { HelixShieldModeStatus } from './HelixShieldModeStatus.js';\nimport { HelixUnbanRequest } from './HelixUnbanRequest.js';\nimport { HelixWarning } from './HelixWarning.js';\n/**\n * The Helix API methods that deal with moderation.\n *\n * Can be accessed using `client.moderation` on an {@link ApiClient} instance.\n *\n * ## Example\n * ```ts\n * const api = new ApiClient({ authProvider });\n * const { data: users } = await api.moderation.getBannedUsers('61369223');\n * ```\n *\n * @meta category helix\n * @meta categorizedTitle Moderation\n */\nlet HelixModerationApi = class HelixModerationApi extends BaseApi {\n /**\n * Gets a list of banned users in a given channel.\n *\n * @param channel The channel to get the banned users from.\n * @param filter Additional filters for the result set.\n *\n * @expandParams\n */\n async getBannedUsers(channel, filter) {\n const result = await this._client.callApi({\n type: 'helix',\n url: 'moderation/banned',\n userId: extractUserId(channel),\n scopes: ['moderation:read'],\n query: {\n ...createModerationUserListQuery(channel, filter),\n ...createPaginationQuery(filter),\n },\n });\n return createPaginatedResult(result, HelixBan, this._client);\n }\n /**\n * Creates a paginator for banned users in a given channel.\n *\n * @param channel The channel to get the banned users from.\n */\n getBannedUsersPaginated(channel) {\n return new HelixPaginatedRequest({\n url: 'moderation/banned',\n userId: extractUserId(channel),\n scopes: ['moderation:read'],\n query: createBroadcasterQuery(channel),\n }, this._client, data => new HelixBan(data, this._client), 50);\n }\n /**\n * Checks whether a given user is banned in a given channel.\n *\n * @param channel The channel to check for a ban of the given user.\n * @param user The user to check for a ban in the given channel.\n */\n async checkUserBan(channel, user) {\n const userId = extractUserId(user);\n const result = await this.getBannedUsers(channel, { userId });\n return result.data.some(ban => ban.userId === userId);\n }\n /**\n * Gets a list of moderators in a given channel.\n *\n * @param channel The channel to get moderators from.\n * @param filter Additional filters for the result set.\n *\n * @expandParams\n */\n async getModerators(channel, filter) {\n const result = await this._client.callApi({\n type: 'helix',\n url: 'moderation/moderators',\n userId: extractUserId(channel),\n scopes: ['moderation:read', 'channel:manage:moderators'],\n query: {\n ...createModerationUserListQuery(channel, filter),\n ...createPaginationQuery(filter),\n },\n });\n return createPaginatedResult(result, HelixModerator, this._client);\n }\n /**\n * Creates a paginator for moderators in a given channel.\n *\n * @param channel The channel to get moderators from.\n */\n getModeratorsPaginated(channel) {\n return new HelixPaginatedRequest({\n url: 'moderation/moderators',\n userId: extractUserId(channel),\n scopes: ['moderation:read', 'channel:manage:moderators'],\n query: createBroadcasterQuery(channel),\n }, this._client, data => new HelixModerator(data, this._client));\n }\n /**\n * Gets a list of channels where the specified user has moderator privileges.\n *\n * @param user The user for whom to return a list of channels where they have moderator privileges.\n * This ID must match the user ID in the access token.\n * @param filter\n *\n * @expandParams\n *\n * @returns A paginated list of channels where the user has moderator privileges.\n */\n async getModeratedChannels(user, filter) {\n const userId = extractUserId(user);\n const result = await this._client.callApi({\n type: 'helix',\n url: 'moderation/channels',\n userId,\n scopes: ['user:read:moderated_channels'],\n query: {\n ...createSingleKeyQuery('user_id', userId),\n ...createPaginationQuery(filter),\n },\n });\n return createPaginatedResult(result, HelixModeratedChannel, this._client);\n }\n /**\n * Creates a paginator for channels where the specified user has moderator privileges.\n *\n * @param user The user for whom to return the list of channels where they have moderator privileges.\n * This ID must match the user ID in the access token.\n */\n getModeratedChannelsPaginated(user) {\n const userId = extractUserId(user);\n return new HelixPaginatedRequest({\n url: 'moderation/channels',\n userId,\n scopes: ['user:read:moderated_channels'],\n query: createSingleKeyQuery('user_id', userId),\n }, this._client, data => new HelixModeratedChannel(data, this._client));\n }\n /**\n * Checks whether a given user is a moderator of a given channel.\n *\n * @param channel The channel to check.\n * @param user The user to check.\n */\n async checkUserMod(channel, user) {\n const userId = extractUserId(user);\n const result = await this.getModerators(channel, { userId });\n return result.data.some(mod => mod.userId === userId);\n }\n /**\n * Adds a moderator to the broadcaster\u2019s chat room.\n *\n * @param broadcaster The broadcaster that owns the chat room. This ID must match the user ID in the access token.\n * @param user The user to add as a moderator in the broadcaster\u2019s chat room.\n */\n async addModerator(broadcaster, user) {\n await this._client.callApi({\n type: 'helix',\n url: 'moderation/moderators',\n method: 'POST',\n userId: extractUserId(broadcaster),\n scopes: ['channel:manage:moderators'],\n query: createModeratorModifyQuery(broadcaster, user),\n });\n }\n /**\n * Removes a moderator from the broadcaster\u2019s chat room.\n *\n * @param broadcaster The broadcaster that owns the chat room. This ID must match the user ID in the access token.\n * @param user The user to remove as a moderator from the broadcaster\u2019s chat room.\n */\n async removeModerator(broadcaster, user) {\n await this._client.callApi({\n type: 'helix',\n url: 'moderation/moderators',\n method: 'DELETE',\n userId: extractUserId(broadcaster),\n scopes: ['channel:manage:moderators'],\n query: createModeratorModifyQuery(broadcaster, user),\n });\n }\n /**\n * Determines whether a string message meets the channel's AutoMod requirements.\n *\n * @param channel The channel in which the messages to check are posted.\n * @param data An array of message data objects.\n */\n async checkAutoModStatus(channel, data) {\n const result = await this._client.callApi({\n type: 'helix',\n url: 'moderation/enforcements/status',\n method: 'POST',\n userId: extractUserId(channel),\n scopes: ['moderation:read'],\n query: createBroadcasterQuery(channel),\n jsonBody: createCheckAutoModStatusBody(data),\n });\n return result.data.map(statusData => new HelixAutoModStatus(statusData));\n }\n /**\n * Processes a message held by AutoMod.\n *\n * @param user The user who is processing the message.\n * @param msgId The ID of the message.\n * @param allow Whether to allow the message - `true` allows, and `false` denies.\n */\n async processHeldAutoModMessage(user, msgId, allow) {\n await this._client.callApi({\n type: 'helix',\n url: 'moderation/automod/message',\n method: 'POST',\n userId: extractUserId(user),\n scopes: ['moderator:manage:automod'],\n jsonBody: createAutoModProcessBody(user, msgId, allow),\n });\n }\n /**\n * Gets the AutoMod settings for a broadcaster.\n *\n * This uses the token of the broadcaster by default.\n * If you want to execute this in the context of another user (who has to be moderator of the channel)\n * you can do so using [user context overrides](/docs/auth/concepts/context-switching).\n *\n * @param broadcaster The broadcaster to get the AutoMod settings for.\n */\n async getAutoModSettings(broadcaster) {\n const broadcasterId = extractUserId(broadcaster);\n const result = await this._client.callApi({\n type: 'helix',\n url: 'moderation/automod/settings',\n userId: broadcasterId,\n scopes: ['moderator:read:automod_settings'],\n canOverrideScopedUserContext: true,\n query: this._createModeratorActionQuery(broadcasterId),\n });\n return result.data.map(data => new HelixAutoModSettings(data));\n }\n /**\n * Updates the AutoMod settings for a broadcaster.\n *\n * This uses the token of the broadcaster by default.\n * If you want to execute this in the context of another user (who has to be moderator of the channel)\n * you can do so using [user context overrides](/docs/auth/concepts/context-switching).\n *\n * @param broadcaster The broadcaster for which the AutoMod settings are updated.\n * @param data The updated AutoMod settings that replace the current AutoMod settings.\n */\n async updateAutoModSettings(broadcaster, data) {\n const broadcasterId = extractUserId(broadcaster);\n const result = await this._client.callApi({\n type: 'helix',\n url: 'moderation/automod/settings',\n method: 'PUT',\n userId: broadcasterId,\n scopes: ['moderator:manage:automod_settings'],\n canOverrideScopedUserContext: true,\n query: this._createModeratorActionQuery(broadcasterId),\n jsonBody: createAutoModSettingsBody(data),\n });\n return result.data.map(settingsData => new HelixAutoModSettings(settingsData));\n }\n /**\n * Bans or times out a user in a channel.\n *\n * This uses the token of the broadcaster by default.\n * If you want to execute this in the context of another user (who has to be moderator of the channel)\n * you can do so using [user context overrides](/docs/auth/concepts/context-switching).\n *\n * @param broadcaster The broadcaster in whose channel the user will be banned/timed out.\n * @param data\n *\n * @expandParams\n *\n * @returns The result data from the ban/timeout request.\n */\n async banUser(broadcaster, data) {\n const broadcasterId = extractUserId(broadcaster);\n const result = await this._client.callApi({\n type: 'helix',\n url: 'moderation/bans',\n method: 'POST',\n userId: broadcasterId,\n scopes: ['moderator:manage:banned_users'],\n canOverrideScopedUserContext: true,\n query: this._createModeratorActionQuery(broadcasterId),\n jsonBody: createBanUserBody(data),\n });\n return result.data.map(banData => new HelixBanUser(banData, banData.end_time, this._client));\n }\n /**\n * Unbans/removes the timeout for a user in a channel.\n *\n * This uses the token of the broadcaster by default.\n * If you want to execute this in the context of another user (who has to be moderator of the channel)\n * you can do so using [user context overrides](/docs/auth/concepts/context-switching).\n *\n * @param broadcaster The broadcaster in whose channel the user will be unbanned/removed from timeout.\n * @param user The user who will be unbanned/removed from timeout.\n */\n async unbanUser(broadcaster, user) {\n const broadcasterId = extractUserId(broadcaster);\n await this._client.callApi({\n type: 'helix',\n url: 'moderation/bans',\n method: 'DELETE',\n userId: broadcasterId,\n scopes: ['moderator:manage:banned_users'],\n canOverrideScopedUserContext: true,\n query: {\n ...this._createModeratorActionQuery(broadcasterId),\n ...createSingleKeyQuery('user_id', extractUserId(user)),\n },\n });\n }\n /**\n * Gets the broadcaster\u2019s list of non-private, blocked words or phrases.\n *\n * This uses the token of the broadcaster by default.\n * If you want to execute this in the context of another user (who has to be moderator of the channel)\n * you can do so using [user context overrides](/docs/auth/concepts/context-switching).\n *\n * @param broadcaster The broadcaster to get their channel's blocked terms for.\n * @param pagination\n *\n * @expandParams\n *\n * @returns A paginated list of blocked term data in the broadcaster's channel.\n */\n async getBlockedTerms(broadcaster, pagination) {\n const broadcasterId = extractUserId(broadcaster);\n const result = await this._client.callApi({\n type: 'helix',\n url: 'moderation/blocked_terms',\n userId: broadcasterId,\n scopes: ['moderator:read:blocked_terms'],\n canOverrideScopedUserContext: true,\n query: {\n ...this._createModeratorActionQuery(broadcasterId),\n ...createPaginationQuery(pagination),\n },\n });\n return createPaginatedResult(result, HelixBlockedTerm, this._client);\n }\n /**\n * Adds a blocked term to the broadcaster's channel.\n *\n * This uses the token of the broadcaster by default.\n * If you want to execute this in the context of another user (who has to be moderator of the channel)\n * you can do so using [user context overrides](/docs/auth/concepts/context-switching).\n *\n * @param broadcaster The broadcaster in whose channel the term will be blocked.\n * @param text The word or phrase to block from being used in the broadcaster's channel.\n *\n * @returns Information about the term that has been blocked.\n */\n async addBlockedTerm(broadcaster, text) {\n const broadcasterId = extractUserId(broadcaster);\n const result = await this._client.callApi({\n type: 'helix',\n url: 'moderation/blocked_terms',\n method: 'POST',\n userId: broadcasterId,\n scopes: ['moderator:manage:blocked_terms'],\n canOverrideScopedUserContext: true,\n query: this._createModeratorActionQuery(broadcasterId),\n jsonBody: {\n text,\n },\n });\n return result.data.map(blockedTermData => new HelixBlockedTerm(blockedTermData));\n }\n /**\n * Removes a blocked term from the broadcaster's channel.\n *\n * @param broadcaster The broadcaster in whose channel the term will be unblocked.\n * @param moderator A user that has permission to unblock terms in the broadcaster's channel.\n * The token of this user will be used to remove the blocked term.\n * @param id The ID of the term that should be unblocked.\n */\n async removeBlockedTerm(broadcaster, moderator, id) {\n const broadcasterId = extractUserId(broadcaster);\n await this._client.callApi({\n type: 'helix',\n url: 'moderation/blocked_terms',\n method: 'DELETE',\n userId: broadcasterId,\n scopes: ['moderator:manage:blocked_terms'],\n canOverrideScopedUserContext: true,\n query: {\n ...this._createModeratorActionQuery(broadcasterId),\n id,\n },\n });\n }\n /**\n * Removes a single chat message or all chat messages from the broadcaster\u2019s chat room.\n *\n * This uses the token of the broadcaster by default.\n * If you want to execute this in the context of another user (who has to be moderator of the channel)\n * you can do so using [user context overrides](/docs/auth/concepts/context-switching).\n *\n * @param broadcaster The broadcaster the chat belongs to.\n * @param messageId The ID of the message to remove. If not specified, the request removes all messages in the broadcaster\u2019s chat room.\n */\n async deleteChatMessages(broadcaster, messageId) {\n const broadcasterId = extractUserId(broadcaster);\n await this._client.callApi({\n type: 'helix',\n url: 'moderation/chat',\n method: 'DELETE',\n userId: broadcasterId,\n scopes: ['moderator:manage:chat_messages'],\n canOverrideScopedUserContext: true,\n query: {\n ...this._createModeratorActionQuery(broadcasterId),\n ...createSingleKeyQuery('message_id', messageId),\n },\n });\n }\n /**\n * Gets the broadcaster's Shield Mode activation status.\n *\n * @param broadcaster The broadcaster whose Shield Mode activation status you want to get.\n */\n async getShieldModeStatus(broadcaster) {\n const broadcasterId = extractUserId(broadcaster);\n const result = await this._client.callApi({\n type: 'helix',\n url: 'moderation/shield_mode',\n method: 'GET',\n userId: broadcasterId,\n scopes: ['moderator:read:shield_mode', 'moderator:manage:shield_mode'],\n canOverrideScopedUserContext: true,\n query: this._createModeratorActionQuery(broadcasterId),\n });\n return new HelixShieldModeStatus(result.data[0], this._client);\n }\n /**\n * Activates or deactivates the broadcaster's Shield Mode.\n *\n * This uses the token of the broadcaster by default.\n * If you want to execute this in the context of another user (who has to be moderator of the channel)\n * you can do so using [user context overrides](/docs/auth/concepts/context-switching).\n *\n * @param broadcaster The broadcaster whose Shield Mode you want to activate or deactivate.\n * @param activate The desired Shield Mode status on the broadcaster's channel.\n */\n async updateShieldModeStatus(broadcaster, activate) {\n const broadcasterId = extractUserId(broadcaster);\n const result = await this._client.callApi({\n type: 'helix',\n url: 'moderation/shield_mode',\n method: 'PUT',\n userId: broadcasterId,\n scopes: ['moderator:manage:shield_mode'],\n canOverrideScopedUserContext: true,\n query: this._createModeratorActionQuery(broadcasterId),\n jsonBody: createUpdateShieldModeStatusBody(activate),\n });\n return new HelixShieldModeStatus(result.data[0], this._client);\n }\n /**\n * Gets a list of unban requests.\n *\n * @param broadcaster The broadcaster to get unban requests of.\n * @param status The status of unban requests to retrieve.\n * @param filter Additional filters for the result set.\n */\n async getUnbanRequests(broadcaster, status, filter) {\n const broadcasterId = extractUserId(broadcaster);\n const result = await this._client.callApi({\n type: 'helix',\n url: 'moderation/unban_requests',\n method: 'GET',\n userId: broadcasterId,\n scopes: ['moderator:read:unban_requests', 'moderator:manage:unban_requests'],\n canOverrideScopedUserContext: true,\n query: {\n ...this._createModeratorActionQuery(broadcasterId),\n ...createSingleKeyQuery('status', status),\n ...createPaginationQuery(filter),\n },\n });\n return createPaginatedResult(result, HelixUnbanRequest, this._client);\n }\n /**\n * Creates a paginator for unban requests.\n *\n * @param broadcaster The broadcaster to get unban requests of.\n * @param status The status of unban requests to retrieve.\n */\n getUnbanRequestsPaginated(broadcaster, status) {\n const broadcasterId = extractUserId(broadcaster);\n return new HelixPaginatedRequest({\n url: 'moderation/unban_requests',\n method: 'GET',\n userId: broadcasterId,\n scopes: ['moderator:read:unban_requests', 'moderator:manage:unban_requests'],\n canOverrideScopedUserContext: true,\n query: {\n ...this._createModeratorActionQuery(broadcasterId),\n ...createSingleKeyQuery('status', status),\n },\n }, this._client, data => new HelixUnbanRequest(data, this._client));\n }\n /**\n * Resolves an unban request by approving or denying it.\n *\n * This uses the token of the broadcaster by default.\n * If you want to execute this in the context of another user (who has to be moderator of the channel)\n * you can do so using [user context overrides](/docs/auth/concepts/context-switching).\n *\n * @param broadcaster The ID of the broadcaster whose channel is approving or denying the unban request.\n * @param unbanRequestId The ID of the unban request to resolve.\n * @param approved Whether to approve or deny the unban request.\n * @param resolutionMessage Message supplied by the unban request resolver.\n *\n * The message is limited to a maximum of 500 characters.\n */\n async resolveUnbanRequest(broadcaster, unbanRequestId, approved, resolutionMessage) {\n const broadcasterId = extractUserId(broadcaster);\n const result = await this._client.callApi({\n type: 'helix',\n url: 'moderation/unban_requests',\n method: 'PATCH',\n userId: broadcasterId,\n scopes: ['moderator:manage:unban_requests'],\n canOverrideScopedUserContext: true,\n query: createResolveUnbanRequestQuery(broadcasterId, this._getUserContextIdWithDefault(broadcasterId), unbanRequestId, approved, resolutionMessage?.slice(0, 500)),\n });\n return new HelixUnbanRequest(result.data[0], this._client);\n }\n /**\n * Warns a user in the specified broadcaster\u2019s chat room, preventing them from chat interaction until the\n * warning is acknowledged.\n *\n * New warnings can be issued to a user when they already have a warning in the channel\n * (new warning will replace old warning).\n *\n * @param broadcaster The ID of the broadcaster in which channel the warning will take effect.\n * @param user The ID of the user to be warned.\n * @param reason A custom reason for the warning. Max 500 chars.\n */\n async warnUser(broadcaster, user, reason) {\n const broadcasterId = extractUserId(broadcaster);\n const result = await this._client.callApi({\n type: 'helix',\n url: 'moderation/warnings',\n method: 'POST',\n userId: broadcasterId,\n scopes: ['moderator:manage:warnings'],\n canOverrideScopedUserContext: true,\n query: this._createModeratorActionQuery(broadcasterId),\n jsonBody: createWarnUserBody(user, reason.slice(0, 500)),\n });\n return new HelixWarning(result.data[0], this._client);\n }\n _createModeratorActionQuery(broadcasterId) {\n return createModeratorActionQuery(broadcasterId, this._getUserContextIdWithDefault(broadcasterId));\n }\n};\nHelixModerationApi = __decorate([\n rtfm('api', 'HelixModerationApi')\n], HelixModerationApi);\nexport { HelixModerationApi };\n", "import { extractUserId } from '@twurple/common';\n/** @internal */\nexport function createModerationUserListQuery(channel, filter) {\n return {\n broadcaster_id: extractUserId(channel),\n user_id: filter?.userId,\n };\n}\n/** @internal */\nexport function createModeratorModifyQuery(broadcaster, user) {\n return {\n broadcaster_id: extractUserId(broadcaster),\n user_id: extractUserId(user),\n };\n}\n/** @internal */\nexport function createResolveUnbanRequestQuery(broadcaster, moderator, unbanRequestId, approved, resolutionMessage) {\n return {\n unban_request_id: unbanRequestId,\n broadcaster_id: extractUserId(broadcaster),\n moderator_id: extractUserId(moderator),\n status: approved ? 'approved' : 'denied',\n resolution_text: resolutionMessage,\n };\n}\n/** @internal */\nexport function createAutoModProcessBody(user, msgId, allow) {\n return {\n user_id: extractUserId(user),\n msg_id: msgId,\n action: allow ? 'ALLOW' : 'DENY',\n };\n}\n/** @internal */\nexport function createAutoModSettingsBody(data) {\n return {\n overall_level: data.overallLevel,\n aggression: data.aggression,\n bullying: data.bullying,\n disability: data.disability,\n misogyny: data.misogyny,\n race_ethnicity_or_religion: data.raceEthnicityOrReligion,\n sex_based_terms: data.sexBasedTerms,\n sexuality_sex_or_gender: data.sexualitySexOrGender,\n swearing: data.swearing,\n };\n}\n/** @internal */\nexport function createBanUserBody(data) {\n return {\n data: {\n duration: data.duration,\n reason: data.reason,\n user_id: extractUserId(data.user),\n },\n };\n}\n/** @internal */\nexport function createUpdateShieldModeStatusBody(activate) {\n return {\n is_active: activate,\n };\n}\n/** @internal */\nexport function createCheckAutoModStatusBody(data) {\n return {\n data: data.map(entry => ({\n msg_id: entry.messageId,\n msg_text: entry.messageText,\n })),\n };\n}\n/** @internal */\nexport function createWarnUserBody(user, reason) {\n return {\n data: {\n user_id: extractUserId(user),\n reason,\n },\n };\n}\n", "import { __decorate } from \"tslib\";\nimport { DataObject, rawDataSymbol, rtfm } from '@twurple/common';\n/**\n * The AutoMod settings of a channel.\n */\nlet HelixAutoModSettings = class HelixAutoModSettings extends DataObject {\n /**\n * The ID of the broadcaster for which the AutoMod settings were fetched.\n */\n get broadcasterId() {\n return this[rawDataSymbol].broadcaster_id;\n }\n /**\n * The ID of a user that has permission to moderate the broadcaster's chat room.\n */\n get moderatorId() {\n return this[rawDataSymbol].moderator_id;\n }\n /**\n * The default AutoMod level for the broadcaster. This is null if the broadcaster changed individual settings.\n */\n get overallLevel() {\n return this[rawDataSymbol].overall_level ? this[rawDataSymbol].overall_level : null;\n }\n /**\n * The AutoMod level for discrimination against disability.\n */\n get disability() {\n return this[rawDataSymbol].disability;\n }\n /**\n * The AutoMod level for hostility involving aggression.\n */\n get aggression() {\n return this[rawDataSymbol].aggression;\n }\n /**\n * The AutoMod level for discrimination based on sexuality, sex, or gender.\n */\n get sexualitySexOrGender() {\n return this[rawDataSymbol].sexuality_sex_or_gender;\n }\n /**\n * The AutoMod level for discrimination against women.\n */\n get misogyny() {\n return this[rawDataSymbol].misogyny;\n }\n /**\n * The AutoMod level for hostility involving name calling or insults.\n */\n get bullying() {\n return this[rawDataSymbol].bullying;\n }\n /**\n * The AutoMod level for profanity.\n */\n get swearing() {\n return this[rawDataSymbol].swearing;\n }\n /**\n * The AutoMod level for racial discrimination.\n */\n get raceEthnicityOrReligion() {\n return this[rawDataSymbol].race_ethnicity_or_religion;\n }\n /**\n * The AutoMod level for sexual content.\n */\n get sexBasedTerms() {\n return this[rawDataSymbol].sex_based_terms;\n }\n};\nHelixAutoModSettings = __decorate([\n rtfm('api', 'HelixAutoModSettings', 'broadcasterId')\n], HelixAutoModSettings);\nexport { HelixAutoModSettings };\n", "import { __decorate } from \"tslib\";\nimport { DataObject, rawDataSymbol, rtfm } from '@twurple/common';\n/**\n * The status of a message that says whether it is permitted by AutoMod or not.\n */\nlet HelixAutoModStatus = class HelixAutoModStatus extends DataObject {\n /**\n * The developer-generated ID that was sent with the request data.\n */\n get messageId() {\n return this[rawDataSymbol].msg_id;\n }\n /**\n * Whether the message is permitted by AutoMod or not.\n */\n get isPermitted() {\n return this[rawDataSymbol].is_permitted;\n }\n};\nHelixAutoModStatus = __decorate([\n rtfm('api', 'HelixAutoModStatus', 'messageId')\n], HelixAutoModStatus);\nexport { HelixAutoModStatus };\n", "import { __decorate } from \"tslib\";\nimport { rawDataSymbol, rtfm } from '@twurple/common';\nimport { HelixBanUser } from './HelixBanUser.js';\n/**\n * Information about the ban of a user.\n *\n * @inheritDoc\n */\nlet HelixBan = class HelixBan extends HelixBanUser {\n /** @internal */\n constructor(data, client) {\n super(data, data.expires_at || null, client);\n }\n /**\n * The name of the user that was banned or put in a timeout.\n */\n get userName() {\n return this[rawDataSymbol].user_login;\n }\n /**\n * The display name of the user that was banned or put in a timeout.\n */\n get userDisplayName() {\n return this[rawDataSymbol].user_name;\n }\n /**\n * The name of the moderator that banned or put the user in the timeout.\n */\n get moderatorName() {\n return this[rawDataSymbol].moderator_login;\n }\n /**\n * The display name of the moderator that banned or put the user in the timeout.\n */\n get moderatorDisplayName() {\n return this[rawDataSymbol].moderator_name;\n }\n /**\n * The reason why the user was banned or timed out. Returns `null` if no reason was given.\n */\n get reason() {\n return this[rawDataSymbol].reason || null;\n }\n};\nHelixBan = __decorate([\n rtfm('api', 'HelixBan', 'userId')\n], HelixBan);\nexport { HelixBan };\n", "import { __decorate } from \"tslib\";\nimport { Enumerable, mapNullable } from '@d-fischer/shared-utils';\nimport { checkRelationAssertion, DataObject, rawDataSymbol, rtfm } from '@twurple/common';\n/**\n * Information about a user who has been banned/timed out.\n *\n * @hideProtected\n */\nlet HelixBanUser = class HelixBanUser extends DataObject {\n /** @internal */ _client;\n /** @internal */ _expiryTimestamp;\n /** @internal */\n constructor(data, expiryTimestamp, client) {\n super(data);\n this._expiryTimestamp = expiryTimestamp;\n this._client = client;\n }\n /**\n * The date and time that the ban/timeout was created.\n */\n get creationDate() {\n return new Date(this[rawDataSymbol].created_at);\n }\n /**\n * The date and time that the timeout will end. Is `null` if the user was banned instead of put in a timeout.\n */\n get expiryDate() {\n return mapNullable(this._expiryTimestamp, ts => new Date(ts));\n }\n /**\n * The ID of the moderator that banned or put the user in the timeout.\n */\n get moderatorId() {\n return this[rawDataSymbol].moderator_id;\n }\n /**\n * Gets more information about the moderator that banned or put the user in the timeout.\n */\n async getModerator() {\n return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].moderator_id));\n }\n /**\n * The ID of the user that was banned or put in a timeout.\n */\n get userId() {\n return this[rawDataSymbol].user_id;\n }\n /**\n * Gets more information about the user that was banned or put in a timeout.\n */\n async getUser() {\n return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].user_id));\n }\n};\n__decorate([\n Enumerable(false)\n], HelixBanUser.prototype, \"_client\", void 0);\n__decorate([\n Enumerable(false)\n], HelixBanUser.prototype, \"_expiryTimestamp\", void 0);\nHelixBanUser = __decorate([\n rtfm('api', 'HelixBanUser', 'userId')\n], HelixBanUser);\nexport { HelixBanUser };\n", "import { __decorate } from \"tslib\";\nimport { DataObject, rawDataSymbol, rtfm } from '@twurple/common';\n/**\n * Information about a word or phrase blocked in a broadcaster's channel.\n */\nlet HelixBlockedTerm = class HelixBlockedTerm extends DataObject {\n /**\n * The ID of the broadcaster that owns the list of blocked terms.\n */\n get broadcasterId() {\n return this[rawDataSymbol].broadcaster_id;\n }\n /**\n * The date and time of when the term was blocked.\n */\n get creationDate() {\n return new Date(this[rawDataSymbol].created_at);\n }\n /**\n * The date and time of when the blocked term is set to expire. After the block expires, users will be able to use the term in the broadcaster\u2019s chat room.\n * Is `null` if the term was added manually or permanently blocked by AutoMod.\n */\n get expirationDate() {\n return this[rawDataSymbol].expires_at ? new Date(this[rawDataSymbol].expires_at) : null;\n }\n /**\n * An ID that uniquely identifies this blocked term.\n */\n get id() {\n return this[rawDataSymbol].id;\n }\n /**\n * The ID of the moderator that blocked the word or phrase from being used in the broadcaster\u2019s chat room.\n */\n get moderatorId() {\n return this[rawDataSymbol].moderator_id;\n }\n /**\n * The blocked word or phrase.\n */\n get text() {\n return this[rawDataSymbol].text;\n }\n /**\n * The date and time of when the term was updated.\n */\n get updatedDate() {\n return new Date(this[rawDataSymbol].updated_at);\n }\n};\nHelixBlockedTerm = __decorate([\n rtfm('api', 'HelixBlockedTerm', 'id')\n], HelixBlockedTerm);\nexport { HelixBlockedTerm };\n", "import { __decorate } from \"tslib\";\nimport { Enumerable } from '@d-fischer/shared-utils';\nimport { checkRelationAssertion, DataObject, rawDataSymbol, rtfm } from '@twurple/common';\n/**\n * A reference to a Twitch channel where a user is a moderator.\n */\nlet HelixModeratedChannel = class HelixModeratedChannel extends DataObject {\n /** @internal */ _client;\n /** @internal */\n constructor(data, client) {\n super(data);\n this._client = client;\n }\n /**\n * The ID of the channel.\n */\n get id() {\n return this[rawDataSymbol].broadcaster_id;\n }\n /**\n * The name of the channel.\n */\n get name() {\n return this[rawDataSymbol].broadcaster_login;\n }\n /**\n * The display name of the channel.\n */\n get displayName() {\n return this[rawDataSymbol].broadcaster_name;\n }\n /**\n * Gets more information about the channel.\n */\n async getChannel() {\n return checkRelationAssertion(await this._client.channels.getChannelInfoById(this[rawDataSymbol].broadcaster_id));\n }\n /**\n * Gets more information about the broadcaster of the channel.\n */\n async getBroadcaster() {\n return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].broadcaster_id));\n }\n};\n__decorate([\n Enumerable(false)\n], HelixModeratedChannel.prototype, \"_client\", void 0);\nHelixModeratedChannel = __decorate([\n rtfm('api', 'HelixModeratedChannel', 'id')\n], HelixModeratedChannel);\nexport { HelixModeratedChannel };\n", "import { __decorate } from \"tslib\";\nimport { Enumerable } from '@d-fischer/shared-utils';\nimport { checkRelationAssertion, DataObject, rawDataSymbol, rtfm } from '@twurple/common';\n/**\n * Information about the moderator status of a user.\n */\nlet HelixModerator = class HelixModerator extends DataObject {\n /** @internal */ _client;\n /** @internal */\n constructor(data, client) {\n super(data);\n this._client = client;\n }\n /**\n * The ID of the user.\n */\n get userId() {\n return this[rawDataSymbol].user_id;\n }\n /**\n * The name of the user.\n */\n get userName() {\n return this[rawDataSymbol].user_login;\n }\n /**\n * The display name of the user.\n */\n get userDisplayName() {\n return this[rawDataSymbol].user_name;\n }\n /**\n * Gets more information about the user.\n */\n async getUser() {\n return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].user_id));\n }\n};\n__decorate([\n Enumerable(false)\n], HelixModerator.prototype, \"_client\", void 0);\nHelixModerator = __decorate([\n rtfm('api', 'HelixModerator', 'userId')\n], HelixModerator);\nexport { HelixModerator };\n", "import { __decorate } from \"tslib\";\nimport { Enumerable } from '@d-fischer/shared-utils';\nimport { checkRelationAssertion, DataObject, rawDataSymbol, rtfm } from '@twurple/common';\n/**\n * Information about the Shield Mode status of a channel.\n */\nlet HelixShieldModeStatus = class HelixShieldModeStatus extends DataObject {\n /** @internal */ _client;\n /** @internal */\n constructor(data, client) {\n super(data);\n this._client = client;\n }\n /**\n * Whether Shield Mode is active.\n */\n get isActive() {\n return this[rawDataSymbol].is_active;\n }\n /**\n * The ID of the moderator that last activated Shield Mode.\n */\n get moderatorId() {\n return this[rawDataSymbol].moderator_id;\n }\n /**\n * The name of the moderator that last activated Shield Mode.\n */\n get moderatorName() {\n return this[rawDataSymbol].moderator_login;\n }\n /**\n * The display name of the moderator that last activated Shield Mode.\n */\n get moderatorDisplayName() {\n return this[rawDataSymbol].moderator_name;\n }\n /**\n * Gets more information about the moderator that last activated Shield Mode.\n */\n async getModerator() {\n return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].moderator_id));\n }\n /**\n * The date when Shield Mode was last activated. `null` indicates Shield Mode hasn't been previously activated.\n */\n get lastActivationDate() {\n return this[rawDataSymbol].last_activated_at === '' ? null : new Date(this[rawDataSymbol].last_activated_at);\n }\n};\n__decorate([\n Enumerable(false)\n], HelixShieldModeStatus.prototype, \"_client\", void 0);\nHelixShieldModeStatus = __decorate([\n rtfm('api', 'HelixShieldModeStatus')\n], HelixShieldModeStatus);\nexport { HelixShieldModeStatus };\n", "import { __decorate } from \"tslib\";\nimport { Enumerable, mapNullable } from '@d-fischer/shared-utils';\nimport { checkRelationAssertion, DataObject, rawDataSymbol, rtfm } from '@twurple/common';\n/**\n * A request from a user to be unbanned from a channel.\n */\nlet HelixUnbanRequest = class HelixUnbanRequest extends DataObject {\n /** @internal */ _client;\n /** @internal */\n constructor(data, client) {\n super(data);\n this._client = client;\n }\n /**\n * Unban request ID.\n */\n get id() {\n return this[rawDataSymbol].id;\n }\n /**\n * The ID of the broadcaster whose channel is receiving the unban request.\n */\n get broadcasterId() {\n return this[rawDataSymbol].broadcaster_id;\n }\n /**\n * The name of the broadcaster whose channel is receiving the unban request.\n */\n get broadcasterName() {\n return this[rawDataSymbol].broadcaster_id;\n }\n /**\n * The display name of the broadcaster whose channel is receiving the unban request.\n */\n get broadcasterDisplayName() {\n return this[rawDataSymbol].broadcaster_id;\n }\n /**\n * Gets more information about the broadcaster.\n */\n async getBroadcaster() {\n return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].broadcaster_id));\n }\n /**\n * The ID of the moderator who resolved the unban request.\n *\n * Can be `null` if the request is not resolved.\n */\n get moderatorId() {\n return this[rawDataSymbol].moderator_id;\n }\n /**\n * The name of the moderator who resolved the unban request.\n *\n * Can be `null` if the request is not resolved.\n */\n get moderatorName() {\n return this[rawDataSymbol].moderator_login;\n }\n /**\n * The display name of the moderator who resolved the unban request.\n *\n * Can be `null` if the request is not resolved.\n */\n get moderatorDisplayName() {\n return this[rawDataSymbol].moderator_name;\n }\n /**\n * Gets more information about the moderator.\n */\n async getModerator() {\n return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].moderator_id));\n }\n /**\n * The ID of the user who requested to be unbanned.\n */\n get userId() {\n return this[rawDataSymbol].user_id;\n }\n /**\n * The name of the user who requested to be unbanned.\n */\n get userName() {\n return this[rawDataSymbol].user_login;\n }\n /**\n * The display name of the user who requested to be unbanned.\n */\n get userDisplayName() {\n return this[rawDataSymbol].user_name;\n }\n /**\n * Gets more information about the user.\n */\n async getUser() {\n return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].user_id));\n }\n /**\n * Text message of the unban request from the requesting user.\n */\n get message() {\n return this[rawDataSymbol].text;\n }\n /**\n * The date of when the unban request was created.\n */\n get creationDate() {\n return new Date(this[rawDataSymbol].created_at);\n }\n /**\n * The message written by the moderator who resolved the unban request, or `null` if it has not been resolved yet.\n */\n get resolutionMessage() {\n // Can be empty string and null\n // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing\n return this[rawDataSymbol].resolution_text || null;\n }\n /**\n * The date when the unban request was resolved, or `null` if it has not been resolved yet.\n */\n get resolutionDate() {\n return mapNullable(this[rawDataSymbol].resolved_at, val => new Date(val));\n }\n};\n__decorate([\n Enumerable(false)\n], HelixUnbanRequest.prototype, \"_client\", void 0);\nHelixUnbanRequest = __decorate([\n rtfm('api', 'HelixUnbanRequest', 'id')\n], HelixUnbanRequest);\nexport { HelixUnbanRequest };\n", "import { __decorate } from \"tslib\";\nimport { Enumerable } from '@d-fischer/shared-utils';\nimport { checkRelationAssertion, DataObject, rawDataSymbol, rtfm } from '@twurple/common';\n/**\n * Information about the warning.\n */\nlet HelixWarning = class HelixWarning extends DataObject {\n /** @internal */ _client;\n /** @internal */\n constructor(data, client) {\n super(data);\n this._client = client;\n }\n /**\n * The ID of the channel in which the warning will take effect.\n */\n get broadcasterId() {\n return this[rawDataSymbol].user_id;\n }\n /**\n * Gets more information about the broadcaster.\n */\n async getBroadcaster() {\n return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].broadcaster_id));\n }\n /**\n * The ID of the user who applied the warning.\n */\n get moderatorId() {\n return this[rawDataSymbol].moderator_id;\n }\n /**\n * Gets more information about the moderator.\n */\n async getModerator() {\n return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].moderator_id));\n }\n /**\n * The ID of the warned user.\n */\n get userId() {\n return this[rawDataSymbol].user_id;\n }\n /**\n * Gets more information about the user.\n */\n async getUser() {\n return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].user_id));\n }\n /**\n * The reason provided for the warning.\n */\n get reason() {\n return this[rawDataSymbol].reason;\n }\n};\n__decorate([\n Enumerable(false)\n], HelixWarning.prototype, \"_client\", void 0);\nHelixWarning = __decorate([\n rtfm('api', 'HelixWarning', 'userId')\n], HelixWarning);\nexport { HelixWarning };\n", "import { __decorate } from \"tslib\";\nimport { createBroadcasterQuery } from '@twurple/api-call';\nimport { extractUserId, rtfm } from '@twurple/common';\nimport { createGetByIdsQuery } from '../../interfaces/endpoints/generic.external.js';\nimport { createPollBody, createPollEndBody } from '../../interfaces/endpoints/poll.external.js';\nimport { HelixPaginatedRequest } from '../../utils/pagination/HelixPaginatedRequest.js';\nimport { createPaginatedResult } from '../../utils/pagination/HelixPaginatedResult.js';\nimport { createPaginationQuery } from '../../utils/pagination/HelixPagination.js';\nimport { BaseApi } from '../BaseApi.js';\nimport { HelixPoll } from './HelixPoll.js';\n/**\n * The Helix API methods that deal with polls.\n *\n * Can be accessed using `client.polls` on an {@link ApiClient} instance.\n *\n * ## Example\n * ```ts\n * const api = new ApiClient({ authProvider });\n * const { data: polls } = await api.helix.polls.getPolls('61369223');\n * ```\n *\n * @meta category helix\n * @meta categorizedTitle Polls\n */\nlet HelixPollApi = class HelixPollApi extends BaseApi {\n /**\n * Gets a list of polls for the given broadcaster.\n *\n * @param broadcaster The broadcaster to get polls for.\n * @param pagination\n *\n * @expandParams\n */\n async getPolls(broadcaster, pagination) {\n const result = await this._client.callApi({\n type: 'helix',\n url: 'polls',\n userId: extractUserId(broadcaster),\n scopes: ['channel:read:polls', 'channel:manage:polls'],\n query: {\n ...createBroadcasterQuery(broadcaster),\n ...createPaginationQuery(pagination),\n },\n });\n return createPaginatedResult(result, HelixPoll, this._client);\n }\n /**\n * Creates a paginator for polls for the given broadcaster.\n *\n * @param broadcaster The broadcaster to get polls for.\n */\n getPollsPaginated(broadcaster) {\n return new HelixPaginatedRequest({\n url: 'polls',\n userId: extractUserId(broadcaster),\n scopes: ['channel:read:polls', 'channel:manage:polls'],\n query: createBroadcasterQuery(broadcaster),\n }, this._client, data => new HelixPoll(data, this._client), 20);\n }\n /**\n * Gets polls by IDs.\n *\n * @param broadcaster The broadcaster to get the polls for.\n * @param ids The IDs of the polls.\n */\n async getPollsByIds(broadcaster, ids) {\n if (!ids.length) {\n return [];\n }\n const result = await this._client.callApi({\n type: 'helix',\n url: 'polls',\n userId: extractUserId(broadcaster),\n scopes: ['channel:read:polls', 'channel:manage:polls'],\n query: createGetByIdsQuery(broadcaster, ids),\n });\n return result.data.map(data => new HelixPoll(data, this._client));\n }\n /**\n * Gets a poll by ID.\n *\n * @param broadcaster The broadcaster to get the poll for.\n * @param id The ID of the poll.\n */\n async getPollById(broadcaster, id) {\n const polls = await this.getPollsByIds(broadcaster, [id]);\n return polls.length ? polls[0] : null;\n }\n /**\n * Creates a new poll.\n *\n * @param broadcaster The broadcaster to create the poll for.\n * @param data\n *\n * @expandParams\n */\n async createPoll(broadcaster, data) {\n const result = await this._client.callApi({\n type: 'helix',\n url: 'polls',\n method: 'POST',\n userId: extractUserId(broadcaster),\n scopes: ['channel:manage:polls'],\n jsonBody: createPollBody(broadcaster, data),\n });\n return new HelixPoll(result.data[0], this._client);\n }\n /**\n * Ends a poll.\n *\n * @param broadcaster The broadcaster to end the poll for.\n * @param id The ID of the poll to end.\n * @param showResult Whether to allow the result to be viewed publicly.\n */\n async endPoll(broadcaster, id, showResult = true) {\n const result = await this._client.callApi({\n type: 'helix',\n url: 'polls',\n method: 'PATCH',\n userId: extractUserId(broadcaster),\n scopes: ['channel:manage:polls'],\n jsonBody: createPollEndBody(broadcaster, id, showResult),\n });\n return new HelixPoll(result.data[0], this._client);\n }\n};\nHelixPollApi = __decorate([\n rtfm('api', 'HelixPollApi')\n], HelixPollApi);\nexport { HelixPollApi };\n", "import { extractUserId } from '@twurple/common';\n/** @internal */\nexport function createPollBody(broadcaster, data) {\n return {\n broadcaster_id: extractUserId(broadcaster),\n title: data.title,\n choices: data.choices.map(title => ({ title })),\n duration: data.duration,\n channel_points_voting_enabled: data.channelPointsPerVote != null,\n channel_points_per_vote: data.channelPointsPerVote ?? 0,\n };\n}\n/** @internal */\nexport function createPollEndBody(broadcaster, id, showResult) {\n return {\n broadcaster_id: extractUserId(broadcaster),\n id,\n status: showResult ? 'TERMINATED' : 'ARCHIVED',\n };\n}\n", "import { __decorate } from \"tslib\";\nimport { Enumerable } from '@d-fischer/shared-utils';\nimport { checkRelationAssertion, DataObject, rawDataSymbol, rtfm } from '@twurple/common';\nimport { HelixPollChoice } from './HelixPollChoice.js';\n/**\n * A channel poll.\n */\nlet HelixPoll = class HelixPoll extends DataObject {\n /** @internal */ _client;\n /** @internal */\n constructor(data, client) {\n super(data);\n this._client = client;\n }\n /**\n * The ID of the poll.\n */\n get id() {\n return this[rawDataSymbol].id;\n }\n /**\n * The ID of the broadcaster.\n */\n get broadcasterId() {\n return this[rawDataSymbol].broadcaster_id;\n }\n /**\n * The name of the broadcaster.\n */\n get broadcasterName() {\n return this[rawDataSymbol].broadcaster_login;\n }\n /**\n * The display name of the broadcaster.\n */\n get broadcasterDisplayName() {\n return this[rawDataSymbol].broadcaster_name;\n }\n /**\n * Gets more information about the broadcaster.\n */\n async getBroadcaster() {\n return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].broadcaster_id));\n }\n /**\n * The title of the poll.\n */\n get title() {\n return this[rawDataSymbol].title;\n }\n /**\n * Whether voting with channel points is enabled for the poll.\n */\n get isChannelPointsVotingEnabled() {\n return this[rawDataSymbol].channel_points_voting_enabled;\n }\n /**\n * The amount of channel points that a vote costs.\n */\n get channelPointsPerVote() {\n return this[rawDataSymbol].channel_points_per_vote;\n }\n /**\n * The status of the poll.\n */\n get status() {\n return this[rawDataSymbol].status;\n }\n /**\n * The duration of the poll, in seconds.\n */\n get durationInSeconds() {\n return this[rawDataSymbol].duration;\n }\n /**\n * The date when the poll started.\n */\n get startDate() {\n return new Date(this[rawDataSymbol].started_at);\n }\n /**\n * The date when the poll ended or will end.\n */\n get endDate() {\n return new Date(this.startDate.getTime() + this[rawDataSymbol].duration * 1000);\n }\n /**\n * The choices of the poll.\n */\n get choices() {\n return this[rawDataSymbol].choices.map(data => new HelixPollChoice(data));\n }\n};\n__decorate([\n Enumerable(false)\n], HelixPoll.prototype, \"_client\", void 0);\nHelixPoll = __decorate([\n rtfm('api', 'HelixPoll', 'id')\n], HelixPoll);\nexport { HelixPoll };\n", "import { __decorate } from \"tslib\";\nimport { DataObject, rawDataSymbol, rtfm } from '@twurple/common';\n/**\n * A choice in a channel poll.\n */\nlet HelixPollChoice = class HelixPollChoice extends DataObject {\n /**\n * The ID of the choice.\n */\n get id() {\n return this[rawDataSymbol].id;\n }\n /**\n * The title of the choice.\n */\n get title() {\n return this[rawDataSymbol].title;\n }\n /**\n * The total votes the choice received.\n */\n get totalVotes() {\n return this[rawDataSymbol].votes;\n }\n /**\n * The votes the choice received by spending channel points.\n */\n get channelPointsVotes() {\n return this[rawDataSymbol].channel_points_votes;\n }\n};\nHelixPollChoice = __decorate([\n rtfm('api', 'HelixPollChoice', 'id')\n], HelixPollChoice);\nexport { HelixPollChoice };\n", "import { __decorate } from \"tslib\";\nimport { createBroadcasterQuery } from '@twurple/api-call';\nimport { extractUserId, rtfm } from '@twurple/common';\nimport { createGetByIdsQuery } from '../../interfaces/endpoints/generic.external.js';\nimport { createEndPredictionBody, createPredictionBody, } from '../../interfaces/endpoints/prediction.external.js';\nimport { HelixPaginatedRequest } from '../../utils/pagination/HelixPaginatedRequest.js';\nimport { createPaginatedResult } from '../../utils/pagination/HelixPaginatedResult.js';\nimport { createPaginationQuery } from '../../utils/pagination/HelixPagination.js';\nimport { BaseApi } from '../BaseApi.js';\nimport { HelixPrediction } from './HelixPrediction.js';\n/**\n * The Helix API methods that deal with predictions.\n *\n * Can be accessed using `client.predictions` on an {@link ApiClient} instance.\n *\n * ## Example\n * ```ts\n * const api = new ApiClient({ authProvider });\n * const { data: predictions } = await api.helix.predictions.getPredictions('61369223');\n * ```\n *\n * @meta category helix\n * @meta categorizedTitle Predictions\n */\nlet HelixPredictionApi = class HelixPredictionApi extends BaseApi {\n /**\n * Gets a list of predictions for the given broadcaster.\n *\n * @param broadcaster The broadcaster to get predictions for.\n * @param pagination\n *\n * @expandParams\n */\n async getPredictions(broadcaster, pagination) {\n const result = await this._client.callApi({\n type: 'helix',\n url: 'predictions',\n userId: extractUserId(broadcaster),\n scopes: ['channel:read:predictions'],\n query: {\n ...createBroadcasterQuery(broadcaster),\n ...createPaginationQuery(pagination),\n },\n });\n return createPaginatedResult(result, HelixPrediction, this._client);\n }\n /**\n * Creates a paginator for predictions for the given broadcaster.\n *\n * @param broadcaster The broadcaster to get predictions for.\n */\n getPredictionsPaginated(broadcaster) {\n return new HelixPaginatedRequest({\n url: 'predictions',\n userId: extractUserId(broadcaster),\n scopes: ['channel:read:predictions'],\n query: createBroadcasterQuery(broadcaster),\n }, this._client, data => new HelixPrediction(data, this._client), 20);\n }\n /**\n * Gets predictions by IDs.\n *\n * @param broadcaster The broadcaster to get the predictions for.\n * @param ids The IDs of the predictions.\n */\n async getPredictionsByIds(broadcaster, ids) {\n if (!ids.length) {\n return [];\n }\n const result = await this._client.callApi({\n type: 'helix',\n url: 'predictions',\n userId: extractUserId(broadcaster),\n scopes: ['channel:read:predictions'],\n query: createGetByIdsQuery(broadcaster, ids),\n });\n return result.data.map(data => new HelixPrediction(data, this._client));\n }\n /**\n * Gets a prediction by ID.\n *\n * @param broadcaster The broadcaster to get the prediction for.\n * @param id The ID of the prediction.\n */\n async getPredictionById(broadcaster, id) {\n const predictions = await this.getPredictionsByIds(broadcaster, [id]);\n return predictions.length ? predictions[0] : null;\n }\n /**\n * Creates a new prediction.\n *\n * @param broadcaster The broadcaster to create the prediction for.\n * @param data\n *\n * @expandParams\n */\n async createPrediction(broadcaster, data) {\n const result = await this._client.callApi({\n type: 'helix',\n url: 'predictions',\n method: 'POST',\n userId: extractUserId(broadcaster),\n scopes: ['channel:manage:predictions'],\n jsonBody: createPredictionBody(broadcaster, data),\n });\n return new HelixPrediction(result.data[0], this._client);\n }\n /**\n * Locks a prediction.\n *\n * @param broadcaster The broadcaster to lock the prediction for.\n * @param id The ID of the prediction to lock.\n */\n async lockPrediction(broadcaster, id) {\n return await this._endPrediction(broadcaster, id, 'LOCKED');\n }\n /**\n * Resolves a prediction.\n *\n * @param broadcaster The broadcaster to resolve the prediction for.\n * @param id The ID of the prediction to resolve.\n * @param outcomeId The ID of the winning outcome.\n */\n async resolvePrediction(broadcaster, id, outcomeId) {\n return await this._endPrediction(broadcaster, id, 'RESOLVED', outcomeId);\n }\n /**\n * Cancels a prediction.\n *\n * @param broadcaster The broadcaster to cancel the prediction for.\n * @param id The ID of the prediction to cancel.\n */\n async cancelPrediction(broadcaster, id) {\n return await this._endPrediction(broadcaster, id, 'CANCELED');\n }\n async _endPrediction(broadcaster, id, status, outcomeId) {\n const result = await this._client.callApi({\n type: 'helix',\n url: 'predictions',\n method: 'PATCH',\n userId: extractUserId(broadcaster),\n scopes: ['channel:manage:predictions'],\n jsonBody: createEndPredictionBody(broadcaster, id, status, outcomeId),\n });\n return new HelixPrediction(result.data[0], this._client);\n }\n};\nHelixPredictionApi = __decorate([\n rtfm('api', 'HelixPredictionApi')\n], HelixPredictionApi);\nexport { HelixPredictionApi };\n", "import { extractUserId } from '@twurple/common';\n/** @internal */\nexport function createPredictionBody(broadcaster, data) {\n return {\n broadcaster_id: extractUserId(broadcaster),\n title: data.title,\n outcomes: data.outcomes.map(title => ({ title })),\n prediction_window: data.autoLockAfter,\n };\n}\n/** @internal */\nexport function createEndPredictionBody(broadcaster, id, status, outcomeId) {\n return {\n broadcaster_id: extractUserId(broadcaster),\n id,\n status,\n winning_outcome_id: outcomeId,\n };\n}\n", "import { __decorate } from \"tslib\";\nimport { Enumerable } from '@d-fischer/shared-utils';\nimport { checkRelationAssertion, DataObject, HellFreezesOverError, rawDataSymbol, rtfm } from '@twurple/common';\nimport { HelixPredictionOutcome } from './HelixPredictionOutcome.js';\n/**\n * A channel prediction.\n */\nlet HelixPrediction = class HelixPrediction extends DataObject {\n /** @internal */ _client;\n /** @internal */\n constructor(data, client) {\n super(data);\n this._client = client;\n }\n /**\n * The ID of the prediction.\n */\n get id() {\n return this[rawDataSymbol].id;\n }\n /**\n * The ID of the broadcaster.\n */\n get broadcasterId() {\n return this[rawDataSymbol].broadcaster_id;\n }\n /**\n * The name of the broadcaster.\n */\n get broadcasterName() {\n return this[rawDataSymbol].broadcaster_login;\n }\n /**\n * The display name of the broadcaster.\n */\n get broadcasterDisplayName() {\n return this[rawDataSymbol].broadcaster_name;\n }\n /**\n * Gets more information about the broadcaster.\n */\n async getBroadcaster() {\n return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].broadcaster_id));\n }\n /**\n * The title of the prediction.\n */\n get title() {\n return this[rawDataSymbol].title;\n }\n /**\n * The status of the prediction.\n */\n get status() {\n return this[rawDataSymbol].status;\n }\n /**\n * The time after which the prediction will be automatically locked, in seconds from creation.\n */\n get autoLockAfter() {\n return this[rawDataSymbol].prediction_window;\n }\n /**\n * The date when the prediction started.\n */\n get creationDate() {\n return new Date(this[rawDataSymbol].created_at);\n }\n /**\n * The date when the prediction ended, or null if it didn't end yet.\n */\n get endDate() {\n return this[rawDataSymbol].ended_at ? new Date(this[rawDataSymbol].ended_at) : null;\n }\n /**\n * The date when the prediction was locked, or null if it wasn't locked yet.\n */\n get lockDate() {\n return this[rawDataSymbol].locked_at ? new Date(this[rawDataSymbol].locked_at) : null;\n }\n /**\n * The possible outcomes of the prediction.\n */\n get outcomes() {\n return this[rawDataSymbol].outcomes.map(data => new HelixPredictionOutcome(data, this._client));\n }\n /**\n * The ID of the winning outcome, or null if the prediction is currently running or was canceled.\n */\n get winningOutcomeId() {\n // can apparently be empty string\n // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing\n return this[rawDataSymbol].winning_outcome_id || null;\n }\n /**\n * The winning outcome, or null if the prediction is currently running or was canceled.\n */\n get winningOutcome() {\n if (!this[rawDataSymbol].winning_outcome_id) {\n return null;\n }\n const found = this[rawDataSymbol].outcomes.find(o => o.id === this[rawDataSymbol].winning_outcome_id);\n if (!found) {\n throw new HellFreezesOverError('Winning outcome not found in outcomes array');\n }\n return new HelixPredictionOutcome(found, this._client);\n }\n};\n__decorate([\n Enumerable(false)\n], HelixPrediction.prototype, \"_client\", void 0);\nHelixPrediction = __decorate([\n rtfm('api', 'HelixPrediction', 'id')\n], HelixPrediction);\nexport { HelixPrediction };\n", "import { __decorate } from \"tslib\";\nimport { Enumerable } from '@d-fischer/shared-utils';\nimport { DataObject, rawDataSymbol, rtfm } from '@twurple/common';\nimport { HelixPredictor } from './HelixPredictor.js';\n/**\n * A possible outcome in a channel prediction.\n */\nlet HelixPredictionOutcome = class HelixPredictionOutcome extends DataObject {\n /** @internal */ _client;\n /** @internal */\n constructor(data, client) {\n super(data);\n this._client = client;\n }\n /**\n * The ID of the outcome.\n */\n get id() {\n return this[rawDataSymbol].id;\n }\n /**\n * The title of the outcome.\n */\n get title() {\n return this[rawDataSymbol].title;\n }\n /**\n * The number of users that guessed the outcome.\n */\n get users() {\n return this[rawDataSymbol].users;\n }\n /**\n * The total number of channel points that were spent on guessing the outcome.\n */\n get totalChannelPoints() {\n return this[rawDataSymbol].channel_points;\n }\n /**\n * The color of the outcome.\n */\n get color() {\n return this[rawDataSymbol].color;\n }\n /**\n * The top predictors of the outcome.\n */\n get topPredictors() {\n return this[rawDataSymbol].top_predictors?.map(data => new HelixPredictor(data, this._client)) ?? [];\n }\n};\n__decorate([\n Enumerable(false)\n], HelixPredictionOutcome.prototype, \"_client\", void 0);\nHelixPredictionOutcome = __decorate([\n rtfm('api', 'HelixPredictionOutcome', 'id')\n], HelixPredictionOutcome);\nexport { HelixPredictionOutcome };\n", "import { __decorate } from \"tslib\";\nimport { Enumerable } from '@d-fischer/shared-utils';\nimport { DataObject, rawDataSymbol, rtfm } from '@twurple/common';\n/**\n * A user that took part in a prediction.\n */\nlet HelixPredictor = class HelixPredictor extends DataObject {\n /** @internal */ _client;\n /** @internal */\n constructor(data, client) {\n super(data);\n this._client = client;\n }\n /**\n * The user ID of the predictor.\n */\n get userId() {\n return this[rawDataSymbol].user_id;\n }\n /**\n * The name of the predictor.\n */\n get userName() {\n return this[rawDataSymbol].user_login;\n }\n /**\n * The display name of the predictor.\n */\n get userDisplayName() {\n return this[rawDataSymbol].user_name;\n }\n /**\n * Gets more information about the predictor.\n */\n async getUser() {\n return await this._client.users.getUserById(this[rawDataSymbol].user_id);\n }\n /**\n * The amount of channel points the predictor used for the prediction.\n */\n get channelPointsUsed() {\n return this[rawDataSymbol].channel_points_used;\n }\n /**\n * The amount of channel points the predictor won for the prediction, or null if the prediction is not resolved yet, was cancelled or lost.\n */\n get channelPointsWon() {\n return this[rawDataSymbol].channel_points_won;\n }\n};\n__decorate([\n Enumerable(false)\n], HelixPredictor.prototype, \"_client\", void 0);\nHelixPredictor = __decorate([\n rtfm('api', 'HelixPredictor', 'userId')\n], HelixPredictor);\nexport { HelixPredictor };\n", "import { __decorate } from \"tslib\";\nimport { createBroadcasterQuery } from '@twurple/api-call';\nimport { extractUserId, rtfm } from '@twurple/common';\nimport { createRaidStartQuery } from '../../interfaces/endpoints/raid.external.js';\nimport { BaseApi } from '../BaseApi.js';\nimport { HelixRaid } from './HelixRaid.js';\n/**\n * The Helix API methods that deal with raids.\n *\n * Can be accessed using `client.raids` on an {@link ApiClient} instance.\n *\n * ## Example\n * ```ts\n * const api = new ApiClient({ authProvider });\n * const raid = await api.raids.startRaid('125328655', '61369223');\n * ```\n *\n * @meta category helix\n * @meta categorizedTitle Raids\n */\nlet HelixRaidApi = class HelixRaidApi extends BaseApi {\n /**\n * Initiate a raid from a live broadcaster to another live broadcaster.\n *\n * @param from The raiding broadcaster.\n * @param to The raid target.\n */\n async startRaid(from, to) {\n const result = await this._client.callApi({\n type: 'helix',\n url: 'raids',\n method: 'POST',\n userId: extractUserId(from),\n scopes: ['channel:manage:raids'],\n query: createRaidStartQuery(from, to),\n });\n return new HelixRaid(result.data[0]);\n }\n /**\n * Cancels an initiated raid.\n *\n * @param from The raiding broadcaster.\n */\n async cancelRaid(from) {\n await this._client.callApi({\n type: 'helix',\n url: 'raids',\n method: 'DELETE',\n userId: extractUserId(from),\n scopes: ['channel:manage:raids'],\n query: createBroadcasterQuery(from),\n });\n }\n};\nHelixRaidApi = __decorate([\n rtfm('api', 'HelixRaidApi')\n], HelixRaidApi);\nexport { HelixRaidApi };\n", "import { extractUserId } from '@twurple/common';\n/** @internal */\nexport function createRaidStartQuery(from, to) {\n return {\n from_broadcaster_id: extractUserId(from),\n to_broadcaster_id: extractUserId(to),\n };\n}\n", "import { __decorate } from \"tslib\";\nimport { DataObject, rawDataSymbol, rtfm } from '@twurple/common';\n/**\n * A result of a successful raid initiation.\n */\nlet HelixRaid = class HelixRaid extends DataObject {\n /**\n * The date when the raid was initiated.\n */\n get creationDate() {\n return new Date(this[rawDataSymbol].created_at);\n }\n /**\n * Whether the raid target channel is intended for mature audiences.\n */\n get targetIsMature() {\n return this[rawDataSymbol].is_mature;\n }\n};\nHelixRaid = __decorate([\n rtfm('api', 'HelixRaid')\n], HelixRaid);\nexport { HelixRaid };\n", "import { createBroadcasterQuery } from '@twurple/api-call';\nimport { extractUserId } from '@twurple/common';\nimport { createGetByIdsQuery } from '../../interfaces/endpoints/generic.external.js';\nimport { createScheduleQuery, createScheduleSegmentBody, createScheduleSegmentModifyQuery, createScheduleSegmentUpdateBody, createScheduleSettingsUpdateQuery, } from '../../interfaces/endpoints/schedule.external.js';\nimport { createPaginationQuery } from '../../utils/pagination/HelixPagination.js';\nimport { BaseApi } from '../BaseApi.js';\nimport { HelixPaginatedScheduleSegmentRequest } from './HelixPaginatedScheduleSegmentRequest.js';\nimport { HelixSchedule } from './HelixSchedule.js';\nimport { HelixScheduleSegment } from './HelixScheduleSegment.js';\n/**\n * The Helix API methods that deal with schedules.\n *\n * Can be accessed using `client.schedule` on an {@link ApiClient} instance.\n *\n * ## Example\n * ```ts\n * const api = new ApiClient({ authProvider });\n * const { data: schedule } = await api.helix.schedule.getSchedule('61369223');\n * ```\n *\n * @meta category helix\n * @meta categorizedTitle Schedule\n */\nexport class HelixScheduleApi extends BaseApi {\n /**\n * Gets the schedule for a given broadcaster.\n *\n * @param broadcaster The broadcaster to get the schedule of.\n * @param filter\n *\n * @expandParams\n */\n async getSchedule(broadcaster, filter) {\n const result = await this._client.callApi({\n type: 'helix',\n url: 'schedule',\n userId: extractUserId(broadcaster),\n query: {\n ...createScheduleQuery(broadcaster, filter),\n ...createPaginationQuery(filter),\n },\n });\n return {\n data: new HelixSchedule(result.data, this._client),\n cursor: result.pagination.cursor,\n };\n }\n /**\n * Creates a paginator for schedule segments for a given broadcaster.\n *\n * @param broadcaster The broadcaster to get the schedule segments of.\n * @param filter\n *\n * @expandParams\n */\n getScheduleSegmentsPaginated(broadcaster, filter) {\n return new HelixPaginatedScheduleSegmentRequest(broadcaster, this._client, filter);\n }\n /**\n * Gets a set of schedule segments by IDs.\n *\n * @param broadcaster The broadcaster to get schedule segments of.\n * @param ids The IDs of the schedule segments.\n */\n async getScheduleSegmentsByIds(broadcaster, ids) {\n const result = await this._client.callApi({\n type: 'helix',\n url: 'schedule',\n userId: extractUserId(broadcaster),\n query: createGetByIdsQuery(broadcaster, ids),\n });\n return result.data.segments?.map(data => new HelixScheduleSegment(data, this._client)) ?? [];\n }\n /**\n * Gets a single schedule segment by ID.\n *\n * @param broadcaster The broadcaster to get a schedule segment of.\n * @param id The ID of the schedule segment.\n */\n async getScheduleSegmentById(broadcaster, id) {\n const segments = await this.getScheduleSegmentsByIds(broadcaster, [id]);\n return segments.length ? segments[0] : null;\n }\n /**\n * Gets the schedule for a given broadcaster in iCal format.\n *\n * @param broadcaster The broadcaster to get the schedule for.\n */\n async getScheduleAsIcal(broadcaster) {\n return await this._client.callApi({\n type: 'helix',\n url: 'schedule/icalendar',\n query: createBroadcasterQuery(broadcaster),\n });\n }\n /**\n * Updates the schedule settings of a given broadcaster.\n *\n * @param broadcaster The broadcaster to update the schedule settings for.\n * @param settings\n *\n * @expandParams\n */\n async updateScheduleSettings(broadcaster, settings) {\n await this._client.callApi({\n type: 'helix',\n url: 'schedule/settings',\n method: 'PATCH',\n userId: extractUserId(broadcaster),\n scopes: ['channel:manage:schedule'],\n query: createScheduleSettingsUpdateQuery(broadcaster, settings),\n });\n }\n /**\n * Creates a new segment in a given broadcaster's schedule.\n *\n * @param broadcaster The broadcaster to create a new schedule segment for.\n * @param data\n *\n * @expandParams\n */\n async createScheduleSegment(broadcaster, data) {\n const result = await this._client.callApi({\n type: 'helix',\n url: 'schedule/segment',\n method: 'POST',\n userId: extractUserId(broadcaster),\n scopes: ['channel:manage:schedule'],\n query: createBroadcasterQuery(broadcaster),\n jsonBody: createScheduleSegmentBody(data),\n });\n return new HelixScheduleSegment(result.data.segments[0], this._client);\n }\n /**\n * Updates a segment in a given broadcaster's schedule.\n *\n * @param broadcaster The broadcaster to create a new schedule segment for.\n * @param segmentId The ID of the segment to update.\n * @param data\n *\n * @expandParams\n */\n async updateScheduleSegment(broadcaster, segmentId, data) {\n const result = await this._client.callApi({\n type: 'helix',\n url: 'schedule/segment',\n method: 'PATCH',\n userId: extractUserId(broadcaster),\n scopes: ['channel:manage:schedule'],\n query: createScheduleSegmentModifyQuery(broadcaster, segmentId),\n jsonBody: createScheduleSegmentUpdateBody(data),\n });\n return new HelixScheduleSegment(result.data.segments[0], this._client);\n }\n /**\n * Deletes a segment in a given broadcaster's schedule.\n *\n * @param broadcaster The broadcaster to create a new schedule segment for.\n * @param segmentId The ID of the segment to update.\n */\n async deleteScheduleSegment(broadcaster, segmentId) {\n await this._client.callApi({\n type: 'helix',\n url: 'schedule/segment',\n method: 'DELETE',\n userId: extractUserId(broadcaster),\n scopes: ['channel:manage:schedule'],\n query: createScheduleSegmentModifyQuery(broadcaster, segmentId),\n });\n }\n}\n", "import { extractUserId } from '@twurple/common';\n/** @internal */\nexport function createScheduleQuery(broadcaster, filter) {\n return {\n broadcaster_id: extractUserId(broadcaster),\n start_time: filter?.startDate,\n utc_offset: filter?.utcOffset?.toString(),\n };\n}\n/** @internal */\nexport function createScheduleSettingsUpdateQuery(broadcaster, settings) {\n if (settings.vacation) {\n return {\n broadcaster_id: extractUserId(broadcaster),\n is_vacation_enabled: 'true',\n vacation_start_time: settings.vacation.startDate,\n vacation_end_time: settings.vacation.endDate,\n timezone: settings.vacation.timezone,\n };\n }\n return {\n broadcaster_id: extractUserId(broadcaster),\n is_vacation_enabled: 'false',\n };\n}\n/** @internal */\nexport function createScheduleSegmentBody(data) {\n return {\n start_time: data.startDate,\n timezone: data.timezone,\n is_recurring: data.isRecurring,\n duration: data.duration,\n category_id: data.categoryId,\n title: data.title,\n };\n}\n/** @internal */\nexport function createScheduleSegmentModifyQuery(broadcaster, segmentId) {\n return {\n broadcaster_id: extractUserId(broadcaster),\n id: segmentId,\n };\n}\n/** @internal */\nexport function createScheduleSegmentUpdateBody(data) {\n return {\n start_time: data.startDate,\n timezone: data.timezone,\n is_canceled: data.isCanceled,\n duration: data.duration,\n category_id: data.categoryId,\n title: data.title,\n };\n}\n", "import { __decorate } from \"tslib\";\nimport { rtfm } from '@twurple/common';\nimport { createScheduleQuery, } from '../../interfaces/endpoints/schedule.external.js';\nimport { HelixPaginatedRequest } from '../../utils/pagination/HelixPaginatedRequest.js';\nimport { HelixScheduleSegment } from './HelixScheduleSegment.js';\n/**\n * A paginator specifically for schedule segments.\n */\nlet HelixPaginatedScheduleSegmentRequest = class HelixPaginatedScheduleSegmentRequest extends HelixPaginatedRequest {\n /** @internal */\n constructor(broadcaster, client, filter) {\n super({\n url: 'schedule',\n query: createScheduleQuery(broadcaster, filter),\n }, client, data => new HelixScheduleSegment(data, client), 25);\n }\n // sadly, this hack is necessary to work around the weird data model of schedules\n // while still keeping the pagination code as generic as possible\n /** @internal */\n async _fetchData(additionalOptions = {}) {\n const origData = (await super._fetchData(additionalOptions));\n return {\n data: origData.data.segments ?? [],\n pagination: origData.pagination,\n };\n }\n};\nHelixPaginatedScheduleSegmentRequest = __decorate([\n rtfm('api', 'HelixPaginatedScheduleSegmentRequest')\n], HelixPaginatedScheduleSegmentRequest);\nexport { HelixPaginatedScheduleSegmentRequest };\n", "import { __decorate } from \"tslib\";\nimport { Enumerable, mapNullable } from '@d-fischer/shared-utils';\nimport { DataObject, rawDataSymbol, rtfm } from '@twurple/common';\n/**\n * A segment of a schedule.\n */\nlet HelixScheduleSegment = class HelixScheduleSegment extends DataObject {\n /** @internal */ _client;\n /** @internal */\n constructor(data, client) {\n super(data);\n this._client = client;\n }\n /**\n * The ID of the segment.\n */\n get id() {\n return this[rawDataSymbol].id;\n }\n /**\n * The date when the segment starts.\n */\n get startDate() {\n return new Date(this[rawDataSymbol].start_time);\n }\n /**\n * The date when the segment ends.\n */\n get endDate() {\n return new Date(this[rawDataSymbol].end_time);\n }\n /**\n * The title of the segment.\n */\n get title() {\n return this[rawDataSymbol].title;\n }\n /**\n * The date up to which the segment is canceled.\n */\n get cancelEndDate() {\n return mapNullable(this[rawDataSymbol].canceled_until, v => new Date(v));\n }\n /**\n * The ID of the category the segment is scheduled for, or null if no category is specified.\n */\n get categoryId() {\n return this[rawDataSymbol].category?.id ?? null;\n }\n /**\n * The name of the category the segment is scheduled for, or null if no category is specified.\n */\n get categoryName() {\n return this[rawDataSymbol].category?.name ?? null;\n }\n /**\n * Gets more information about the category the segment is scheduled for, or null if no category is specified.\n */\n async getCategory() {\n const categoryId = this[rawDataSymbol].category?.id;\n return categoryId ? await this._client.games.getGameById(categoryId) : null;\n }\n /**\n * Whether the segment is recurring every week.\n */\n get isRecurring() {\n return this[rawDataSymbol].is_recurring;\n }\n};\n__decorate([\n Enumerable(false)\n], HelixScheduleSegment.prototype, \"_client\", void 0);\nHelixScheduleSegment = __decorate([\n rtfm('api', 'HelixScheduleSegment', 'id')\n], HelixScheduleSegment);\nexport { HelixScheduleSegment };\n", "import { __decorate } from \"tslib\";\nimport { Enumerable } from '@d-fischer/shared-utils';\nimport { checkRelationAssertion, DataObject, rawDataSymbol, rtfm } from '@twurple/common';\nimport { HelixScheduleSegment } from './HelixScheduleSegment.js';\n/**\n * A schedule of a channel.\n */\nlet HelixSchedule = class HelixSchedule extends DataObject {\n /** @internal */ _client;\n /** @internal */\n constructor(data, client) {\n super(data);\n this._client = client;\n }\n /**\n * The segments of the schedule.\n */\n get segments() {\n return this[rawDataSymbol].segments?.map(data => new HelixScheduleSegment(data, this._client)) ?? [];\n }\n /**\n * The ID of the broadcaster.\n */\n get broadcasterId() {\n return this[rawDataSymbol].broadcaster_id;\n }\n /**\n * The name of the broadcaster.\n */\n get broadcasterName() {\n return this[rawDataSymbol].broadcaster_login;\n }\n /**\n * The display name of the broadcaster.\n */\n get broadcasterDisplayName() {\n return this[rawDataSymbol].broadcaster_name;\n }\n /**\n * Gets more information about the broadcaster.\n */\n async getBroadcaster() {\n return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].broadcaster_id));\n }\n /**\n * The date when the current vacation started, or null if the schedule is not in vacation mode.\n */\n get vacationStartDate() {\n const timestamp = this[rawDataSymbol].vacation?.start_time;\n return timestamp ? new Date(timestamp) : null;\n }\n /**\n * The date when the current vacation ends, or null if the schedule is not in vacation mode.\n */\n get vacationEndDate() {\n const timestamp = this[rawDataSymbol].vacation?.end_time;\n return timestamp ? new Date(timestamp) : null;\n }\n};\n__decorate([\n Enumerable(false)\n], HelixSchedule.prototype, \"_client\", void 0);\nHelixSchedule = __decorate([\n rtfm('api', 'HelixSchedule', 'broadcasterId')\n], HelixSchedule);\nexport { HelixSchedule };\n", "import { __decorate } from \"tslib\";\nimport { rtfm } from '@twurple/common';\nimport { createSearchChannelsQuery, } from '../../interfaces/endpoints/search.external.js';\nimport { HelixPaginatedRequest } from '../../utils/pagination/HelixPaginatedRequest.js';\nimport { createPaginatedResult } from '../../utils/pagination/HelixPaginatedResult.js';\nimport { createPaginationQuery } from '../../utils/pagination/HelixPagination.js';\nimport { BaseApi } from '../BaseApi.js';\nimport { HelixGame } from '../game/HelixGame.js';\nimport { HelixChannelSearchResult } from './HelixChannelSearchResult.js';\n/**\n * The Helix API methods that run searches.\n *\n * Can be accessed using `client.search` on an {@link ApiClient} instance.\n *\n * ## Example\n * ```ts\n * const api = new ApiClient({ authProvider });\n * const channels = await api.search.searchChannels('pear');\n * ```\n *\n * @meta category helix\n * @meta categorizedTitle Search\n */\nlet HelixSearchApi = class HelixSearchApi extends BaseApi {\n /**\n * Search categories/games for an exact or partial match.\n *\n * @param query The search term.\n * @param pagination\n *\n * @expandParams\n */\n async searchCategories(query, pagination) {\n const result = await this._client.callApi({\n type: 'helix',\n url: 'search/categories',\n query: {\n query,\n ...createPaginationQuery(pagination),\n },\n });\n return createPaginatedResult(result, HelixGame, this._client);\n }\n /**\n * Creates a paginator for a category/game search.\n *\n * @param query The search term.\n */\n searchCategoriesPaginated(query) {\n return new HelixPaginatedRequest({\n url: 'search/categories',\n query: {\n query,\n },\n }, this._client, data => new HelixGame(data, this._client));\n }\n /**\n * Search channels for an exact or partial match.\n *\n * @param query The search term.\n * @param filter\n *\n * @expandParams\n */\n async searchChannels(query, filter = {}) {\n const result = await this._client.callApi({\n type: 'helix',\n url: 'search/channels',\n query: {\n ...createSearchChannelsQuery(query, filter),\n ...createPaginationQuery(filter),\n },\n });\n return createPaginatedResult(result, HelixChannelSearchResult, this._client);\n }\n /**\n * Creates a paginator for a channel search.\n *\n * @param query The search term.\n * @param filter\n *\n * @expandParams\n */\n searchChannelsPaginated(query, filter = {}) {\n return new HelixPaginatedRequest({\n url: 'search/channels',\n query: createSearchChannelsQuery(query, filter),\n }, this._client, data => new HelixChannelSearchResult(data, this._client));\n }\n};\nHelixSearchApi = __decorate([\n rtfm('api', 'HelixSearchApi')\n], HelixSearchApi);\nexport { HelixSearchApi };\n", "/** @internal */\nexport function createSearchChannelsQuery(query, filter) {\n return {\n query,\n live_only: filter.liveOnly?.toString(),\n };\n}\n", "import { __decorate } from \"tslib\";\nimport { Enumerable } from '@d-fischer/shared-utils';\nimport { checkRelationAssertion, DataObject, rawDataSymbol, rtfm } from '@twurple/common';\n/**\n * The result of a channel search.\n */\nlet HelixChannelSearchResult = class HelixChannelSearchResult extends DataObject {\n /** @internal */ _client;\n /** @internal */\n constructor(data, client) {\n super(data);\n this._client = client;\n }\n /**\n * The language of the channel.\n */\n get language() {\n return this[rawDataSymbol].broadcaster_language;\n }\n /**\n * The ID of the channel.\n */\n get id() {\n return this[rawDataSymbol].id;\n }\n /**\n * The name of the channel.\n */\n get name() {\n return this[rawDataSymbol].broadcaster_login;\n }\n /**\n * The display name of the channel.\n */\n get displayName() {\n return this[rawDataSymbol].display_name;\n }\n /**\n * Gets additional information about the owner of the channel.\n */\n async getUser() {\n return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].id));\n }\n /**\n * The ID of the game currently played on the channel.\n */\n get gameId() {\n return this[rawDataSymbol].game_id;\n }\n /**\n * The name of the game currently played on the channel.\n */\n get gameName() {\n return this[rawDataSymbol].game_name;\n }\n /**\n * Gets information about the game that is being played on the stream.\n */\n async getGame() {\n return this[rawDataSymbol].game_id\n ? checkRelationAssertion(await this._client.games.getGameById(this[rawDataSymbol].game_id))\n : null;\n }\n /**\n * Whether the channel is currently live.\n */\n get isLive() {\n return this[rawDataSymbol].is_live;\n }\n /**\n * The tags applied to the channel.\n */\n get tags() {\n return this[rawDataSymbol].tags;\n }\n /**\n * The thumbnail URL of the stream.\n */\n get thumbnailUrl() {\n return this[rawDataSymbol].thumbnail_url;\n }\n /**\n * The start date of the stream. Returns `null` if the stream is not live.\n */\n get startDate() {\n return this[rawDataSymbol].is_live ? new Date(this[rawDataSymbol].started_at) : null;\n }\n};\n__decorate([\n Enumerable(false)\n], HelixChannelSearchResult.prototype, \"_client\", void 0);\nHelixChannelSearchResult = __decorate([\n rtfm('api', 'HelixChannelSearchResult', 'id')\n], HelixChannelSearchResult);\nexport { HelixChannelSearchResult };\n", "var HelixStreamApi_1;\nimport { __decorate } from \"tslib\";\nimport { Enumerable, flatten, mapNullable } from '@d-fischer/shared-utils';\nimport { createBroadcasterQuery, HttpStatusCodeError, } from '@twurple/api-call';\nimport { extractUserId, extractUserName, rtfm } from '@twurple/common';\nimport { StreamNotLiveError } from '../../errors/StreamNotLiveError.js';\nimport { createSingleKeyQuery, createUserQuery } from '../../interfaces/endpoints/generic.external.js';\nimport { createStreamMarkerBody, createStreamQuery, createVideoQuery, } from '../../interfaces/endpoints/stream.external.js';\nimport { HelixRequestBatcher } from '../../utils/HelixRequestBatcher.js';\nimport { HelixPaginatedRequest } from '../../utils/pagination/HelixPaginatedRequest.js';\nimport { createPaginatedResult } from '../../utils/pagination/HelixPaginatedResult.js';\nimport { createPaginationQuery, } from '../../utils/pagination/HelixPagination.js';\nimport { BaseApi } from '../BaseApi.js';\nimport { HelixStream } from './HelixStream.js';\nimport { HelixStreamMarker } from './HelixStreamMarker.js';\nimport { HelixStreamMarkerWithVideo } from './HelixStreamMarkerWithVideo.js';\n/**\n * The Helix API methods that deal with streams.\n *\n * Can be accessed using `client.streams` on an {@link ApiClient} instance.\n *\n * ## Example\n * ```ts\n * const api = new ApiClient({ authProvider });\n * const stream = await api.streams.getStreamByUserId('125328655');\n * ```\n *\n * @meta category helix\n * @meta categorizedTitle Streams\n */\nlet HelixStreamApi = HelixStreamApi_1 = class HelixStreamApi extends BaseApi {\n /** @internal */\n _getStreamByUserIdBatcher = new HelixRequestBatcher({\n url: 'streams',\n }, 'user_id', 'user_id', this._client, (data) => new HelixStream(data, this._client));\n /** @internal */\n _getStreamByUserNameBatcher = new HelixRequestBatcher({\n url: 'streams',\n }, 'user_login', 'user_login', this._client, (data) => new HelixStream(data, this._client));\n /**\n * Gets a list of streams.\n *\n * @param filter\n * @expandParams\n */\n async getStreams(filter = {}) {\n const result = await this._client.callApi({\n url: 'streams',\n type: 'helix',\n query: {\n ...createStreamQuery(filter),\n ...createPaginationQuery(filter),\n },\n });\n return createPaginatedResult(result, HelixStream, this._client);\n }\n /**\n * Creates a paginator for streams.\n *\n * @param filter\n * @expandParams\n */\n getStreamsPaginated(filter = {}) {\n return new HelixPaginatedRequest({\n url: 'streams',\n query: createStreamQuery(filter),\n }, this._client, data => new HelixStream(data, this._client));\n }\n /**\n * Gets the current streams for the given usernames.\n *\n * @param users The username to get the streams for.\n */\n async getStreamsByUserNames(users) {\n const result = await this.getStreams({ userName: users.map(extractUserName) });\n return result.data;\n }\n /**\n * Gets the current stream for the given username.\n *\n * @param user The username to get the stream for.\n */\n async getStreamByUserName(user) {\n const result = await this.getStreamsByUserNames([user]);\n return result[0] ?? null;\n }\n /**\n * Gets the current stream for the given username, batching multiple calls into fewer requests as the API allows.\n *\n * @param user The username to get the stream for.\n */\n async getStreamByUserNameBatched(user) {\n return await this._getStreamByUserNameBatcher.request(extractUserName(user));\n }\n /**\n * Gets the current streams for the given user IDs.\n *\n * @param users The user IDs to get the streams for.\n */\n async getStreamsByUserIds(users) {\n const result = await this.getStreams({ userId: users.map(extractUserId) });\n return result.data;\n }\n /**\n * Gets the current stream for the given user ID.\n *\n * @param user The user ID to get the stream for.\n */\n async getStreamByUserId(user) {\n const userId = extractUserId(user);\n const result = await this._client.callApi({\n url: 'streams',\n type: 'helix',\n userId,\n query: createStreamQuery({ userId }),\n });\n return mapNullable(result.data[0], data => new HelixStream(data, this._client));\n }\n /**\n * Gets the current stream for the given user ID, batching multiple calls into fewer requests as the API allows.\n *\n * @param user The user ID to get the stream for.\n */\n async getStreamByUserIdBatched(user) {\n return await this._getStreamByUserIdBatcher.request(extractUserId(user));\n }\n /**\n * Gets a list of all stream markers for a user.\n *\n * @param user The user to list the stream markers for.\n * @param pagination\n *\n * @expandParams\n */\n async getStreamMarkersForUser(user, pagination) {\n const result = await this._client.callApi({\n url: 'streams/markers',\n type: 'helix',\n query: {\n ...createUserQuery(user),\n ...createPaginationQuery(pagination),\n },\n userId: extractUserId(user),\n scopes: ['user:read:broadcast'],\n canOverrideScopedUserContext: true,\n });\n return {\n data: flatten(result.data.map(data => HelixStreamApi_1._mapGetStreamMarkersResult(data, this._client))),\n cursor: result.pagination?.cursor,\n };\n }\n /**\n * Creates a paginator for all stream markers for a user.\n *\n * @param user The user to list the stream markers for.\n */\n getStreamMarkersForUserPaginated(user) {\n return new HelixPaginatedRequest({\n url: 'streams/markers',\n query: createUserQuery(user),\n userId: extractUserId(user),\n scopes: ['user:read:broadcast'],\n canOverrideScopedUserContext: true,\n }, this._client, data => HelixStreamApi_1._mapGetStreamMarkersResult(data, this._client));\n }\n /**\n * Gets a list of all stream markers for a video.\n *\n * @param user The user the video belongs to.\n * @param videoId The video to list the stream markers for.\n * @param pagination\n *\n * @expandParams\n */\n async getStreamMarkersForVideo(user, videoId, pagination) {\n const result = await this._client.callApi({\n url: 'streams/markers',\n type: 'helix',\n query: {\n ...createVideoQuery(videoId),\n ...createPaginationQuery(pagination),\n },\n userId: extractUserId(user),\n scopes: ['user:read:broadcast'],\n canOverrideScopedUserContext: true,\n });\n return {\n data: flatten(result.data.map(data => HelixStreamApi_1._mapGetStreamMarkersResult(data, this._client))),\n cursor: result.pagination?.cursor,\n };\n }\n /**\n * Creates a paginator for all stream markers for a video.\n *\n * @param user The user the video belongs to.\n * @param videoId The video to list the stream markers for.\n */\n getStreamMarkersForVideoPaginated(user, videoId) {\n return new HelixPaginatedRequest({\n url: 'streams/markers',\n query: createVideoQuery(videoId),\n userId: extractUserId(user),\n scopes: ['user:read:broadcast'],\n canOverrideScopedUserContext: true,\n }, this._client, data => HelixStreamApi_1._mapGetStreamMarkersResult(data, this._client));\n }\n /**\n * Creates a new stream marker.\n *\n * Only works while the specified user's stream is live.\n *\n * @param broadcaster The broadcaster to create a stream marker for.\n * @param description The description of the marker.\n */\n async createStreamMarker(broadcaster, description) {\n try {\n const result = await this._client.callApi({\n url: 'streams/markers',\n method: 'POST',\n type: 'helix',\n userId: extractUserId(broadcaster),\n scopes: ['channel:manage:broadcast'],\n canOverrideScopedUserContext: true,\n jsonBody: createStreamMarkerBody(broadcaster, description),\n });\n return new HelixStreamMarker(result.data[0], this._client);\n }\n catch (e) {\n if (e instanceof HttpStatusCodeError && e.statusCode === 404) {\n throw new StreamNotLiveError({ cause: e });\n }\n throw e;\n }\n }\n /**\n * Gets the stream key of a stream.\n *\n * @param broadcaster The broadcaster to get the stream key for.\n */\n async getStreamKey(broadcaster) {\n const userId = extractUserId(broadcaster);\n const result = await this._client.callApi({\n type: 'helix',\n url: 'streams/key',\n userId,\n scopes: ['channel:read:stream_key'],\n query: createBroadcasterQuery(broadcaster),\n });\n return result.data[0].stream_key;\n }\n /**\n * Gets the streams that are currently live and are followed by the given user.\n *\n * @param user The user to check followed streams for.\n * @param pagination\n *\n * @expandParams\n */\n async getFollowedStreams(user, pagination) {\n const userId = extractUserId(user);\n const result = await this._client.callApi({\n type: 'helix',\n url: 'streams/followed',\n userId,\n scopes: ['user:read:follows'],\n query: {\n ...createSingleKeyQuery('user_id', userId),\n ...createPaginationQuery(pagination),\n },\n });\n return createPaginatedResult(result, HelixStream, this._client);\n }\n /**\n * Creates a paginator for the streams that are currently live and are followed by the given user.\n *\n * @param user The user to check followed streams for.\n */\n getFollowedStreamsPaginated(user) {\n const userId = extractUserId(user);\n return new HelixPaginatedRequest({\n url: 'streams/followed',\n userId,\n scopes: ['user:read:follows'],\n query: createSingleKeyQuery('user_id', userId),\n }, this._client, data => new HelixStream(data, this._client));\n }\n static _mapGetStreamMarkersResult(data, client) {\n return data.videos.reduce((result, video) => [\n ...result,\n ...video.markers.map(marker => new HelixStreamMarkerWithVideo(marker, video.video_id, client)),\n ], []);\n }\n};\n__decorate([\n Enumerable(false)\n], HelixStreamApi.prototype, \"_getStreamByUserIdBatcher\", void 0);\n__decorate([\n Enumerable(false)\n], HelixStreamApi.prototype, \"_getStreamByUserNameBatcher\", void 0);\nHelixStreamApi = HelixStreamApi_1 = __decorate([\n rtfm('api', 'HelixStreamApi')\n], HelixStreamApi);\nexport { HelixStreamApi };\n", "import { CustomError } from '@twurple/common';\n/**\n * Thrown whenever you try something that requires your own stream to be live.\n */\nexport class StreamNotLiveError extends CustomError {\n /** @private */\n constructor(options) {\n super('Your stream needs to be live to do this', options);\n }\n}\n", "import { extractUserId } from '@twurple/common';\n/** @internal */\nexport function createStreamQuery(filter) {\n return {\n game_id: filter.game,\n language: filter.language,\n type: filter.type,\n user_id: filter.userId,\n user_login: filter.userName,\n };\n}\n/** @internal */\nexport function createStreamMarkerBody(broadcaster, description) {\n return {\n user_id: extractUserId(broadcaster),\n description,\n };\n}\n/** @internal */\nexport function createVideoQuery(id) {\n return {\n video_id: id,\n };\n}\n", "import { __decorate } from \"tslib\";\nimport { Enumerable } from '@d-fischer/shared-utils';\nimport { checkRelationAssertion, DataObject, rawDataSymbol, rtfm } from '@twurple/common';\n/**\n * A Twitch stream.\n */\nlet HelixStream = class HelixStream extends DataObject {\n /** @internal */ _client;\n /** @internal */\n constructor(data, client) {\n super(data);\n this._client = client;\n }\n /**\n * The stream ID.\n */\n get id() {\n return this[rawDataSymbol].id;\n }\n /**\n * The user ID.\n */\n get userId() {\n return this[rawDataSymbol].user_id;\n }\n /**\n * The user's name.\n */\n get userName() {\n return this[rawDataSymbol].user_login;\n }\n /**\n * The user's display name.\n */\n get userDisplayName() {\n return this[rawDataSymbol].user_name;\n }\n /**\n * Gets information about the user broadcasting the stream.\n */\n async getUser() {\n return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].user_id));\n }\n /**\n * The game ID, or an empty string if the stream doesn't currently have a game.\n */\n get gameId() {\n return this[rawDataSymbol].game_id;\n }\n /**\n * The game name, or an empty string if the stream doesn't currently have a game.\n */\n get gameName() {\n return this[rawDataSymbol].game_name;\n }\n /**\n * Gets information about the game that is being played on the stream.\n *\n * Returns null if the stream doesn't currently have a game.\n */\n async getGame() {\n return this[rawDataSymbol].game_id\n ? checkRelationAssertion(await this._client.games.getGameById(this[rawDataSymbol].game_id))\n : null;\n }\n /**\n * The type of the stream.\n */\n get type() {\n return this[rawDataSymbol].type;\n }\n /**\n * The title of the stream.\n */\n get title() {\n return this[rawDataSymbol].title;\n }\n /**\n * The number of viewers the stream currently has.\n */\n get viewers() {\n return this[rawDataSymbol].viewer_count;\n }\n /**\n * The time when the stream started.\n */\n get startDate() {\n return new Date(this[rawDataSymbol].started_at);\n }\n /**\n * The language of the stream.\n */\n get language() {\n return this[rawDataSymbol].language;\n }\n /**\n * The URL of the thumbnail of the stream.\n *\n * This URL includes the placeholders `{width}` and `{height}`\n * which you must replace with the desired dimensions of the thumbnail (in pixels).\n *\n * You can also use {@link HelixStream#getThumbnailUrl} to do this replacement.\n */\n get thumbnailUrl() {\n return this[rawDataSymbol].thumbnail_url;\n }\n /**\n * Builds the thumbnail URL of the stream using the given dimensions.\n *\n * @param width The width of the thumbnail.\n * @param height The height of the thumbnail.\n */\n getThumbnailUrl(width, height) {\n return this[rawDataSymbol].thumbnail_url\n .replace('{width}', width.toString())\n .replace('{height}', height.toString());\n }\n /**\n * The tags applied to the stream.\n */\n get tags() {\n return this[rawDataSymbol].tags;\n }\n /**\n * Whether the stream is set to be targeted to mature audiences only.\n */\n get isMature() {\n return this[rawDataSymbol].is_mature;\n }\n};\n__decorate([\n Enumerable(false)\n], HelixStream.prototype, \"_client\", void 0);\nHelixStream = __decorate([\n rtfm('api', 'HelixStream', 'id')\n], HelixStream);\nexport { HelixStream };\n", "import { __decorate } from \"tslib\";\nimport { Enumerable } from '@d-fischer/shared-utils';\nimport { DataObject, rawDataSymbol, rtfm } from '@twurple/common';\n/**\n * A stream marker.\n */\nlet HelixStreamMarker = class HelixStreamMarker extends DataObject {\n /** @internal */ _client;\n /** @internal */\n constructor(data, client) {\n super(data);\n this._client = client;\n }\n /**\n * The ID of the marker.\n */\n get id() {\n return this[rawDataSymbol].id;\n }\n /**\n * The date and time when the marker was created.\n */\n get creationDate() {\n return new Date(this[rawDataSymbol].created_at);\n }\n /**\n * The description of the marker.\n */\n get description() {\n return this[rawDataSymbol].description;\n }\n /**\n * The position in the stream when the marker was created, in seconds.\n */\n get positionInSeconds() {\n return this[rawDataSymbol].position_seconds;\n }\n};\n__decorate([\n Enumerable(false)\n], HelixStreamMarker.prototype, \"_client\", void 0);\nHelixStreamMarker = __decorate([\n rtfm('api', 'HelixStreamMarker', 'id')\n], HelixStreamMarker);\nexport { HelixStreamMarker };\n", "import { __decorate } from \"tslib\";\nimport { checkRelationAssertion, rawDataSymbol, rtfm } from '@twurple/common';\nimport { HelixStreamMarker } from './HelixStreamMarker.js';\n/**\n * A stream marker, also containing some video data.\n *\n * @inheritDoc\n */\nlet HelixStreamMarkerWithVideo = class HelixStreamMarkerWithVideo extends HelixStreamMarker {\n _videoId;\n /** @internal */\n constructor(data, _videoId, client) {\n super(data, client);\n this._videoId = _videoId;\n }\n /**\n * The URL of the video, which will start playing at the position of the stream marker.\n */\n get url() {\n return this[rawDataSymbol].URL;\n }\n /**\n * The ID of the video.\n */\n get videoId() {\n return this._videoId;\n }\n /**\n * Gets the video data of the video the marker was set in.\n */\n async getVideo() {\n return checkRelationAssertion(await this._client.videos.getVideoById(this._videoId));\n }\n};\nHelixStreamMarkerWithVideo = __decorate([\n rtfm('api', 'HelixStreamMarkerWithVideo', 'id')\n], HelixStreamMarkerWithVideo);\nexport { HelixStreamMarkerWithVideo };\n", "import { __decorate } from \"tslib\";\nimport { createBroadcasterQuery, HttpStatusCodeError } from '@twurple/api-call';\nimport { extractUserId, rtfm } from '@twurple/common';\nimport { createChannelUsersCheckQuery } from '../../interfaces/endpoints/generic.external.js';\nimport { createSubscriptionCheckQuery, } from '../../interfaces/endpoints/subscription.external.js';\nimport { createPaginatedResultWithTotal } from '../../utils/pagination/HelixPaginatedResult.js';\nimport { createPaginationQuery } from '../../utils/pagination/HelixPagination.js';\nimport { BaseApi } from '../BaseApi.js';\nimport { HelixPaginatedSubscriptionsRequest } from './HelixPaginatedSubscriptionsRequest.js';\nimport { HelixSubscription } from './HelixSubscription.js';\nimport { HelixUserSubscription } from './HelixUserSubscription.js';\n/**\n * The Helix API methods that deal with subscriptions.\n *\n * Can be accessed using `client.subscriptions` on an {@link ApiClient} instance.\n *\n * ## Example\n * ```ts\n * const api = new ApiClient({ authProvider });\n * const subscription = await api.subscriptions.getSubscriptionForUser('61369223', '125328655');\n * ```\n *\n * @meta category helix\n * @meta categorizedTitle Subscriptions\n */\nlet HelixSubscriptionApi = class HelixSubscriptionApi extends BaseApi {\n /**\n * Gets a list of all subscriptions to a given broadcaster.\n *\n * @param broadcaster The broadcaster to list subscriptions to.\n * @param pagination\n *\n * @expandParams\n */\n async getSubscriptions(broadcaster, pagination) {\n const result = await this._client.callApi({\n url: 'subscriptions',\n scopes: ['channel:read:subscriptions'],\n type: 'helix',\n userId: extractUserId(broadcaster),\n query: {\n ...createBroadcasterQuery(broadcaster),\n ...createPaginationQuery(pagination),\n },\n });\n return {\n ...createPaginatedResultWithTotal(result, HelixSubscription, this._client),\n points: result.points,\n };\n }\n /**\n * Creates a paginator for all subscriptions to a given broadcaster.\n *\n * @param broadcaster The broadcaster to list subscriptions to.\n */\n getSubscriptionsPaginated(broadcaster) {\n return new HelixPaginatedSubscriptionsRequest(broadcaster, this._client);\n }\n /**\n * Gets the subset of the given user list that is subscribed to the given broadcaster.\n *\n * @param broadcaster The broadcaster to find subscriptions to.\n * @param users The users that should be checked for subscriptions.\n */\n async getSubscriptionsForUsers(broadcaster, users) {\n const result = await this._client.callApi({\n type: 'helix',\n url: 'subscriptions',\n userId: extractUserId(broadcaster),\n scopes: ['channel:read:subscriptions'],\n query: createChannelUsersCheckQuery(broadcaster, users),\n });\n return result.data.map(data => new HelixSubscription(data, this._client));\n }\n /**\n * Gets the subscription data for a given user to a given broadcaster.\n *\n * This checks with the authorization of a broadcaster.\n * If you only have the authorization of a user, check {@link HelixSubscriptionApi#checkUserSubscription}}.\n *\n * @param broadcaster The broadcaster to check.\n * @param user The user to check.\n */\n async getSubscriptionForUser(broadcaster, user) {\n const list = await this.getSubscriptionsForUsers(broadcaster, [user]);\n return list.length ? list[0] : null;\n }\n /**\n * Checks if a given user is subscribed to a given broadcaster. Returns null if not subscribed.\n *\n * This checks with the authorization of a user.\n * If you only have the authorization of a broadcaster, check {@link HelixSubscriptionApi#getSubscriptionForUser}}.\n *\n * @param user The user to check.\n * @param broadcaster The broadcaster to check the user's subscription for.\n */\n async checkUserSubscription(user, broadcaster) {\n try {\n const result = await this._client.callApi({\n type: 'helix',\n url: 'subscriptions/user',\n userId: extractUserId(user),\n scopes: ['user:read:subscriptions'],\n query: createSubscriptionCheckQuery(broadcaster, user),\n });\n return new HelixUserSubscription(result.data[0], this._client);\n }\n catch (e) {\n if (e instanceof HttpStatusCodeError && e.statusCode === 404) {\n return null;\n }\n throw e;\n }\n }\n};\nHelixSubscriptionApi = __decorate([\n rtfm('api', 'HelixSubscriptionApi')\n], HelixSubscriptionApi);\nexport { HelixSubscriptionApi };\n", "import { extractUserId } from '@twurple/common';\n/** @internal */\nexport function createSubscriptionCheckQuery(broadcaster, user) {\n return {\n broadcaster_id: extractUserId(broadcaster),\n user_id: extractUserId(user),\n };\n}\n", "import { __decorate } from \"tslib\";\nimport { createBroadcasterQuery } from '@twurple/api-call';\nimport { extractUserId, rtfm } from '@twurple/common';\nimport { HelixPaginatedRequestWithTotal } from '../../utils/pagination/HelixPaginatedRequestWithTotal.js';\nimport { HelixSubscription } from './HelixSubscription.js';\n/**\n * A special case of {@link HelixPaginatedRequestWithTotal}\n * with support for fetching the total sub points of a broadcaster.\n *\n * @inheritDoc\n */\nlet HelixPaginatedSubscriptionsRequest = class HelixPaginatedSubscriptionsRequest extends HelixPaginatedRequestWithTotal {\n /** @internal */\n constructor(broadcaster, client) {\n super({\n url: 'subscriptions',\n scopes: ['channel:read:subscriptions'],\n userId: extractUserId(broadcaster),\n query: createBroadcasterQuery(broadcaster),\n }, client, data => new HelixSubscription(data, client));\n }\n /**\n * Gets the total sub points of the broadcaster.\n */\n async getPoints() {\n const data = this._currentData ??\n (await this._fetchData({ query: { after: undefined } }));\n return data.points;\n }\n};\nHelixPaginatedSubscriptionsRequest = __decorate([\n rtfm('api', 'HelixPaginatedSubscriptionsRequest')\n], HelixPaginatedSubscriptionsRequest);\nexport { HelixPaginatedSubscriptionsRequest };\n", "import { __decorate } from \"tslib\";\nimport { checkRelationAssertion, rawDataSymbol, rtfm } from '@twurple/common';\nimport { HelixUserSubscription } from './HelixUserSubscription.js';\n/**\n * A (paid) subscription of a user to a broadcaster.\n *\n * @inheritDoc\n */\nlet HelixSubscription = class HelixSubscription extends HelixUserSubscription {\n /**\n * The user ID of the broadcaster.\n */\n get broadcasterId() {\n return this[rawDataSymbol].broadcaster_id;\n }\n /**\n * The name of the broadcaster.\n */\n get broadcasterName() {\n return this[rawDataSymbol].broadcaster_login;\n }\n /**\n * The display name of the broadcaster.\n */\n get broadcasterDisplayName() {\n return this[rawDataSymbol].broadcaster_name;\n }\n /**\n * Gets more information about the broadcaster.\n */\n async getBroadcaster() {\n return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].broadcaster_id));\n }\n /**\n * The user ID of the gifter.\n */\n get gifterId() {\n return this[rawDataSymbol].is_gift ? this[rawDataSymbol].gifter_id : null;\n }\n /**\n * The name of the gifter.\n */\n get gifterName() {\n return this[rawDataSymbol].is_gift ? this[rawDataSymbol].gifter_login : null;\n }\n /**\n * The display name of the gifter.\n */\n get gifterDisplayName() {\n return this[rawDataSymbol].is_gift ? this[rawDataSymbol].gifter_name : null;\n }\n /**\n * Gets more information about the gifter.\n */\n async getGifter() {\n return this[rawDataSymbol].is_gift\n ? checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].gifter_id))\n : null;\n }\n /**\n * The user ID of the subscribed user.\n */\n get userId() {\n return this[rawDataSymbol].user_id;\n }\n /**\n * The name of the subscribed user.\n */\n get userName() {\n return this[rawDataSymbol].user_login;\n }\n /**\n * The display name of the subscribed user.\n */\n get userDisplayName() {\n return this[rawDataSymbol].user_name;\n }\n /**\n * Gets more information about the subscribed user.\n */\n async getUser() {\n return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].user_id));\n }\n};\nHelixSubscription = __decorate([\n rtfm('api', 'HelixSubscription', 'userId')\n], HelixSubscription);\nexport { HelixSubscription };\n", "import { __decorate } from \"tslib\";\nimport { Enumerable } from '@d-fischer/shared-utils';\nimport { DataObject, rawDataSymbol, rtfm } from '@twurple/common';\n/**\n * The user info about a (paid) subscription to a broadcaster.\n */\nlet HelixUserSubscription = class HelixUserSubscription extends DataObject {\n /** @internal */ _client;\n /** @internal */\n constructor(data, client) {\n super(data);\n this._client = client;\n }\n /**\n * The user ID of the broadcaster.\n */\n get broadcasterId() {\n return this[rawDataSymbol].broadcaster_id;\n }\n /**\n * The name of the broadcaster.\n */\n get broadcasterName() {\n return this[rawDataSymbol].broadcaster_login;\n }\n /**\n * The display name of the broadcaster.\n */\n get broadcasterDisplayName() {\n return this[rawDataSymbol].broadcaster_name;\n }\n /**\n * Gets more information about the broadcaster.\n */\n async getBroadcaster() {\n return await this._client.users.getUserById(this[rawDataSymbol].broadcaster_id);\n }\n /**\n * Whether the subscription has been gifted by another user.\n */\n get isGift() {\n return this[rawDataSymbol].is_gift;\n }\n /**\n * The tier of the subscription.\n */\n get tier() {\n return this[rawDataSymbol].tier;\n }\n};\n__decorate([\n Enumerable(false)\n], HelixUserSubscription.prototype, \"_client\", void 0);\nHelixUserSubscription = __decorate([\n rtfm('api', 'HelixUserSubscription', 'broadcasterId')\n], HelixUserSubscription);\nexport { HelixUserSubscription };\n", "import { __decorate } from \"tslib\";\nimport { createBroadcasterQuery, HttpStatusCodeError } from '@twurple/api-call';\nimport { extractUserId, rtfm } from '@twurple/common';\nimport { BaseApi } from '../BaseApi.js';\nimport { HelixTeam } from './HelixTeam.js';\nimport { HelixTeamWithUsers } from './HelixTeamWithUsers.js';\n/**\n * The Helix API methods that deal with teams.\n *\n * Can be accessed using `client.teams` on an {@link ApiClient} instance.\n *\n * ## Example\n * ```ts\n * const api = new ApiClient({ authProvider });\n * const tags = await api.teams.getChannelTeams('125328655');\n * ```\n *\n * @meta category helix\n * @meta categorizedTitle Teams\n */\nlet HelixTeamApi = class HelixTeamApi extends BaseApi {\n /**\n * Gets a list of all teams a broadcaster is a member of.\n *\n * @param broadcaster The broadcaster to get the teams of.\n */\n async getTeamsForBroadcaster(broadcaster) {\n const result = await this._client.callApi({\n type: 'helix',\n url: 'teams/channel',\n userId: extractUserId(broadcaster),\n query: createBroadcasterQuery(broadcaster),\n });\n return result.data?.map(data => new HelixTeam(data, this._client)) ?? [];\n }\n /**\n * Gets a team by ID.\n *\n * Returns null if there is no team with the given ID.\n *\n * @param id The ID of the team.\n */\n async getTeamById(id) {\n try {\n const result = await this._client.callApi({\n type: 'helix',\n url: 'teams',\n query: {\n id,\n },\n });\n return new HelixTeamWithUsers(result.data[0], this._client);\n }\n catch (e) {\n // Twitch, please...\n if (e instanceof HttpStatusCodeError && e.statusCode === 500) {\n return null;\n }\n throw e;\n }\n }\n /**\n * Gets a team by name.\n *\n * Returns null if there is no team with the given name.\n *\n * @param name The name of the team.\n */\n async getTeamByName(name) {\n try {\n const result = await this._client.callApi({\n type: 'helix',\n url: 'teams',\n query: {\n name,\n },\n });\n return new HelixTeamWithUsers(result.data[0], this._client);\n }\n catch (e) {\n // ...but this one is fine\n if (e instanceof HttpStatusCodeError && e.statusCode === 404) {\n return null;\n }\n throw e;\n }\n }\n};\nHelixTeamApi = __decorate([\n rtfm('api', 'HelixTeamApi')\n], HelixTeamApi);\nexport { HelixTeamApi };\n", "import { __decorate } from \"tslib\";\nimport { Enumerable } from '@d-fischer/shared-utils';\nimport { DataObject, rawDataSymbol, rtfm } from '@twurple/common';\n/**\n * A Stream Team.\n */\nlet HelixTeam = class HelixTeam extends DataObject {\n /** @internal */ _client;\n /** @internal */\n constructor(data, client) {\n super(data);\n this._client = client;\n }\n /**\n * The ID of the team.\n */\n get id() {\n return this[rawDataSymbol].id;\n }\n /**\n * The name of the team.\n */\n get name() {\n return this[rawDataSymbol].team_name;\n }\n /**\n * The display name of the team.\n */\n get displayName() {\n return this[rawDataSymbol].team_display_name;\n }\n /**\n * The URL of the background image of the team.\n */\n get backgroundImageUrl() {\n return this[rawDataSymbol].background_image_url;\n }\n /**\n * The URL of the banner of the team.\n */\n get bannerUrl() {\n return this[rawDataSymbol].banner;\n }\n /**\n * The date when the team was created.\n */\n get creationDate() {\n return new Date(this[rawDataSymbol].created_at);\n }\n /**\n * The date when the team was last updated.\n */\n get updateDate() {\n return new Date(this[rawDataSymbol].updated_at);\n }\n /**\n * The info of the team.\n *\n * May contain HTML tags.\n */\n get info() {\n return this[rawDataSymbol].info;\n }\n /**\n * The URL of the thumbnail of the team's logo.\n */\n get logoThumbnailUrl() {\n return this[rawDataSymbol].thumbnail_url;\n }\n /**\n * Gets the relations to the members of the team.\n */\n async getUserRelations() {\n const teamWithUsers = await this._client.teams.getTeamById(this.id);\n return teamWithUsers.userRelations;\n }\n};\n__decorate([\n Enumerable(false)\n], HelixTeam.prototype, \"_client\", void 0);\nHelixTeam = __decorate([\n rtfm('api', 'HelixTeam', 'id')\n], HelixTeam);\nexport { HelixTeam };\n", "import { __decorate } from \"tslib\";\nimport { rawDataSymbol, rtfm } from '@twurple/common';\nimport { HelixUserRelation } from '../../relations/HelixUserRelation.js';\nimport { HelixTeam } from './HelixTeam.js';\n/**\n * A Stream Team with its member relations.\n *\n * @inheritDoc\n */\nlet HelixTeamWithUsers = class HelixTeamWithUsers extends HelixTeam {\n /**\n * The relations to the members of the team.\n */\n get userRelations() {\n return this[rawDataSymbol].users.map(data => new HelixUserRelation(data, this._client));\n }\n};\nHelixTeamWithUsers = __decorate([\n rtfm('api', 'HelixTeamWithUsers', 'id')\n], HelixTeamWithUsers);\nexport { HelixTeamWithUsers };\n", "import { __decorate } from \"tslib\";\nimport { Enumerable, mapNullable } from '@d-fischer/shared-utils';\nimport { createBroadcasterQuery } from '@twurple/api-call';\nimport { extractUserId, extractUserName, HellFreezesOverError, rtfm, } from '@twurple/common';\nimport { createSingleKeyQuery } from '../../interfaces/endpoints/generic.external.js';\nimport { createUserBlockCreateQuery, createUserBlockDeleteQuery, } from '../../interfaces/endpoints/user.external.js';\nimport { HelixRequestBatcher } from '../../utils/HelixRequestBatcher.js';\nimport { HelixPaginatedRequest } from '../../utils/pagination/HelixPaginatedRequest.js';\nimport { createPaginatedResult } from '../../utils/pagination/HelixPaginatedResult.js';\nimport { createPaginationQuery } from '../../utils/pagination/HelixPagination.js';\nimport { BaseApi } from '../BaseApi.js';\nimport { HelixInstalledExtensionList } from './extensions/HelixInstalledExtensionList.js';\nimport { HelixUserExtension } from './extensions/HelixUserExtension.js';\nimport { HelixPrivilegedUser } from './HelixPrivilegedUser.js';\nimport { HelixUser } from './HelixUser.js';\nimport { HelixUserBlock } from './HelixUserBlock.js';\n/**\n * The Helix API methods that deal with users.\n *\n * Can be accessed using `client.users` on an {@link ApiClient} instance.\n *\n * ## Example\n * ```ts\n * const api = new ApiClient({ authProvider });\n * const user = await api.users.getUserById('125328655');\n * ```\n *\n * @meta category helix\n * @meta categorizedTitle Users\n */\nlet HelixUserApi = class HelixUserApi extends BaseApi {\n /** @internal */\n _getUserByIdBatcher = new HelixRequestBatcher({\n url: 'users',\n }, 'id', 'id', this._client, (data) => new HelixUser(data, this._client));\n /** @internal */\n _getUserByNameBatcher = new HelixRequestBatcher({\n url: 'users',\n }, 'login', 'login', this._client, (data) => new HelixUser(data, this._client));\n /**\n * Gets the user data for the given list of user IDs.\n *\n * @param userIds The user IDs you want to look up.\n */\n async getUsersByIds(userIds) {\n return await this._getUsers('id', userIds.map(extractUserId));\n }\n /**\n * Gets the user data for the given list of usernames.\n *\n * @param userNames The usernames you want to look up.\n */\n async getUsersByNames(userNames) {\n return await this._getUsers('login', userNames.map(extractUserName));\n }\n /**\n * Gets the user data for the given user ID.\n *\n * @param user The user ID you want to look up.\n */\n async getUserById(user) {\n const userId = extractUserId(user);\n const result = await this._client.callApi({\n type: 'helix',\n url: 'users',\n userId,\n query: {\n id: userId,\n },\n });\n return mapNullable(result.data[0], data => new HelixUser(data, this._client));\n }\n /**\n * Gets the user data for the given user ID, batching multiple calls into fewer requests as the API allows.\n *\n * @param user The user ID you want to look up.\n */\n async getUserByIdBatched(user) {\n return await this._getUserByIdBatcher.request(extractUserId(user));\n }\n /**\n * Gets the user data for the given username.\n *\n * @param userName The username you want to look up.\n */\n async getUserByName(userName) {\n const users = await this._getUsers('login', [extractUserName(userName)]);\n return users.length ? users[0] : null;\n }\n /**\n * Gets the user data for the given username, batching multiple calls into fewer requests as the API allows.\n *\n * @param user The username you want to look up.\n */\n async getUserByNameBatched(user) {\n return await this._getUserByNameBatcher.request(extractUserName(user));\n }\n /**\n * Gets the user data of the given authenticated user.\n *\n * @param user The user to get data for.\n * @param withEmail Whether you need the user's email address.\n */\n async getAuthenticatedUser(user, withEmail = false) {\n const result = await this._client.callApi({\n type: 'helix',\n url: 'users',\n forceType: 'user',\n userId: extractUserId(user),\n scopes: withEmail ? ['user:read:email'] : undefined,\n });\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (!result.data?.length) {\n throw new HellFreezesOverError('Could not get authenticated user');\n }\n return new HelixPrivilegedUser(result.data[0], this._client);\n }\n /**\n * Updates the given authenticated user's data.\n *\n * @param user The user to update.\n * @param data The data to update.\n */\n async updateAuthenticatedUser(user, data) {\n const result = await this._client.callApi({\n type: 'helix',\n url: 'users',\n method: 'PUT',\n userId: extractUserId(user),\n scopes: ['user:edit'],\n query: {\n description: data.description,\n },\n });\n return new HelixPrivilegedUser(result.data[0], this._client);\n }\n /**\n * Gets a list of users blocked by the given user.\n *\n * @param user The user to get blocks for.\n * @param pagination\n *\n * @expandParams\n */\n async getBlocks(user, pagination) {\n const result = await this._client.callApi({\n type: 'helix',\n url: 'users/blocks',\n userId: extractUserId(user),\n scopes: ['user:read:blocked_users'],\n query: {\n ...createBroadcasterQuery(user),\n ...createPaginationQuery(pagination),\n },\n });\n return createPaginatedResult(result, HelixUserBlock, this._client);\n }\n /**\n * Creates a paginator for users blocked by the given user.\n *\n * @param user The user to get blocks for.\n */\n getBlocksPaginated(user) {\n return new HelixPaginatedRequest({\n url: 'users/blocks',\n userId: extractUserId(user),\n scopes: ['user:read:blocked_users'],\n query: createBroadcasterQuery(user),\n }, this._client, data => new HelixUserBlock(data, this._client));\n }\n /**\n * Blocks the given user.\n *\n * @param broadcaster The user to add the block to.\n * @param target The user to block.\n * @param additionalInfo Additional info to give context to the block.\n *\n * @expandParams\n */\n async createBlock(broadcaster, target, additionalInfo = {}) {\n await this._client.callApi({\n type: 'helix',\n url: 'users/blocks',\n method: 'PUT',\n userId: extractUserId(broadcaster),\n scopes: ['user:manage:blocked_users'],\n query: createUserBlockCreateQuery(target, additionalInfo),\n });\n }\n /**\n * Unblocks the given user.\n *\n * @param broadcaster The user to remove the block from.\n * @param target The user to unblock.\n */\n async deleteBlock(broadcaster, target) {\n await this._client.callApi({\n type: 'helix',\n url: 'users/blocks',\n method: 'DELETE',\n userId: extractUserId(broadcaster),\n scopes: ['user:manage:blocked_users'],\n query: createUserBlockDeleteQuery(target),\n });\n }\n /**\n * Gets a list of all extensions for the given authenticated user.\n *\n * @param broadcaster The broadcaster to get the list of extensions for.\n * @param withInactive Whether to include inactive extensions.\n */\n async getExtensionsForAuthenticatedUser(broadcaster, withInactive = false) {\n const result = await this._client.callApi({\n type: 'helix',\n url: 'users/extensions/list',\n userId: extractUserId(broadcaster),\n scopes: withInactive ? ['channel:manage:extensions'] : ['user:read:broadcast', 'channel:manage:extensions'],\n });\n return result.data.map(data => new HelixUserExtension(data));\n }\n /**\n * Gets a list of all installed extensions for the given user.\n *\n * @param user The user to get the installed extensions for.\n * @param withDev Whether to include extensions that are in development.\n */\n async getActiveExtensions(user, withDev = false) {\n const userId = extractUserId(user);\n const result = await this._client.callApi({\n type: 'helix',\n url: 'users/extensions',\n userId,\n scopes: withDev ? ['user:read:broadcast', 'channel:manage:extensions'] : undefined,\n query: createSingleKeyQuery('user_id', userId),\n });\n return new HelixInstalledExtensionList(result.data);\n }\n /**\n * Updates the installed extensions for the given authenticated user.\n *\n * @param broadcaster The user to update the installed extensions for.\n * @param data The extension installation payload.\n *\n * The format is shown on the [Twitch documentation](https://dev.twitch.tv/docs/api/reference#update-user-extensions).\n * Don't use the \"data\" wrapper though.\n */\n async updateActiveExtensionsForAuthenticatedUser(broadcaster, data) {\n const result = await this._client.callApi({\n type: 'helix',\n url: 'users/extensions',\n method: 'PUT',\n userId: extractUserId(broadcaster),\n scopes: ['channel:manage:extensions'],\n jsonBody: { data },\n });\n return new HelixInstalledExtensionList(result.data);\n }\n async _getUsers(lookupType, param) {\n if (param.length === 0) {\n return [];\n }\n const query = { [lookupType]: param };\n const result = await this._client.callApi({\n type: 'helix',\n url: 'users',\n query,\n });\n return result.data.map(userData => new HelixUser(userData, this._client));\n }\n};\n__decorate([\n Enumerable(false)\n], HelixUserApi.prototype, \"_getUserByIdBatcher\", void 0);\n__decorate([\n Enumerable(false)\n], HelixUserApi.prototype, \"_getUserByNameBatcher\", void 0);\nHelixUserApi = __decorate([\n rtfm('api', 'HelixUserApi')\n], HelixUserApi);\nexport { HelixUserApi };\n", "import { extractUserId } from '@twurple/common';\n/** @internal */\nexport function createUserBlockCreateQuery(target, additionalInfo) {\n return {\n target_user_id: extractUserId(target),\n source_context: additionalInfo.sourceContext,\n reason: additionalInfo.reason,\n };\n}\n/** @internal */\nexport function createUserBlockDeleteQuery(target) {\n return {\n target_user_id: extractUserId(target),\n };\n}\n", "import { __decorate } from \"tslib\";\nimport { DataObject, rawDataSymbol, rtfm } from '@twurple/common';\nimport { HelixInstalledExtension } from './HelixInstalledExtension.js';\n/**\n * A list of extensions installed in a channel.\n */\nlet HelixInstalledExtensionList = class HelixInstalledExtensionList extends DataObject {\n getExtensionAtSlot(type, slotId) {\n const data = this[rawDataSymbol][type][slotId];\n return data.active ? new HelixInstalledExtension(type, slotId, data) : null;\n }\n getExtensionsForSlotType(type) {\n return [...Object.entries(this[rawDataSymbol][type])]\n .filter((entry) => entry[1].active)\n .map(([slotId, slotData]) => new HelixInstalledExtension(type, slotId, slotData));\n }\n getAllExtensions() {\n return [...Object.entries(this[rawDataSymbol])].flatMap(([type, typeEntries]) => [...Object.entries(typeEntries)]\n .filter((entry) => entry[1].active)\n .map(([slotId, slotData]) => new HelixInstalledExtension(type, slotId, slotData)));\n }\n};\nHelixInstalledExtensionList = __decorate([\n rtfm('api', 'HelixInstalledExtensionList')\n], HelixInstalledExtensionList);\nexport { HelixInstalledExtensionList };\n", "import { __decorate } from \"tslib\";\nimport { rtfm } from '@twurple/common';\nimport { HelixBaseExtension } from './HelixBaseExtension.js';\n/**\n * A Twitch Extension that is installed in a slot of a channel.\n *\n * @inheritDoc\n */\nlet HelixInstalledExtension = class HelixInstalledExtension extends HelixBaseExtension {\n _slotType;\n _slotId;\n /** @internal */\n constructor(slotType, slotId, data) {\n super(data);\n this._slotType = slotType;\n this._slotId = slotId;\n }\n /**\n * The type of the slot the extension is in.\n */\n get slotType() {\n return this._slotType;\n }\n /**\n * The ID of the slot the extension is in.\n */\n get slotId() {\n return this._slotId;\n }\n};\nHelixInstalledExtension = __decorate([\n rtfm('api', 'HelixInstalledExtension', 'id')\n], HelixInstalledExtension);\nexport { HelixInstalledExtension };\n", "import { DataObject, rawDataSymbol } from '@twurple/common';\n/** @protected */\nexport class HelixBaseExtension extends DataObject {\n /**\n * The ID of the extension.\n */\n get id() {\n return this[rawDataSymbol].id;\n }\n /**\n * The version of the extension.\n */\n get version() {\n return this[rawDataSymbol].version;\n }\n /**\n * The name of the extension.\n */\n get name() {\n return this[rawDataSymbol].name;\n }\n}\n", "import { __decorate } from \"tslib\";\nimport { rawDataSymbol, rtfm } from '@twurple/common';\nimport { HelixBaseExtension } from './HelixBaseExtension.js';\n/**\n * A Twitch Extension that was installed by a user.\n *\n * @inheritDoc\n */\nlet HelixUserExtension = class HelixUserExtension extends HelixBaseExtension {\n /**\n * Whether the user has configured the extension to be able to activate it.\n */\n get canActivate() {\n return this[rawDataSymbol].can_activate;\n }\n /**\n * The available types of the extension.\n */\n get types() {\n return this[rawDataSymbol].type;\n }\n};\nHelixUserExtension = __decorate([\n rtfm('api', 'HelixUserExtension', 'id')\n], HelixUserExtension);\nexport { HelixUserExtension };\n", "import { __decorate } from \"tslib\";\nimport { rawDataSymbol, rtfm } from '@twurple/common';\nimport { HelixUser } from './HelixUser.js';\n/**\n * A user you have extended privilges for, i.e. yourself.\n *\n * @inheritDoc\n */\nlet HelixPrivilegedUser = class HelixPrivilegedUser extends HelixUser {\n /**\n * The email address of the user.\n */\n get email() {\n return this[rawDataSymbol].email;\n }\n /**\n * Changes the description of the user.\n *\n * @param description The new description.\n */\n async setDescription(description) {\n return await this._client.users.updateAuthenticatedUser(this, { description });\n }\n};\nHelixPrivilegedUser = __decorate([\n rtfm('api', 'HelixPrivilegedUser', 'id')\n], HelixPrivilegedUser);\nexport { HelixPrivilegedUser };\n", "import { __decorate } from \"tslib\";\nimport { Enumerable } from '@d-fischer/shared-utils';\nimport { DataObject, rawDataSymbol, rtfm, } from '@twurple/common';\n/**\n * A Twitch user.\n */\nlet HelixUser = class HelixUser extends DataObject {\n /** @internal */ _client;\n /** @internal */\n constructor(data, client) {\n super(data);\n this._client = client;\n }\n /**\n * The ID of the user.\n */\n get id() {\n return this[rawDataSymbol].id;\n }\n /**\n * The name of the user.\n */\n get name() {\n return this[rawDataSymbol].login;\n }\n /**\n * The display name of the user.\n */\n get displayName() {\n return this[rawDataSymbol].display_name;\n }\n /**\n * The description of the user.\n */\n get description() {\n return this[rawDataSymbol].description;\n }\n /**\n * The type of the user.\n */\n get type() {\n return this[rawDataSymbol].type;\n }\n /**\n * The type of the broadcaster.\n */\n get broadcasterType() {\n return this[rawDataSymbol].broadcaster_type;\n }\n /**\n * The URL of the profile picture of the user.\n */\n get profilePictureUrl() {\n return this[rawDataSymbol].profile_image_url;\n }\n /**\n * The URL of the offline video placeholder of the user.\n */\n get offlinePlaceholderUrl() {\n return this[rawDataSymbol].offline_image_url;\n }\n /**\n * The date when the user was created, i.e. when they registered on Twitch.\n */\n get creationDate() {\n return new Date(this[rawDataSymbol].created_at);\n }\n /**\n * Gets the channel's stream data.\n */\n async getStream() {\n return await this._client.streams.getStreamByUserId(this);\n }\n /**\n * Gets a list of broadcasters the user follows.\n */\n async getFollowedChannels() {\n return await this._client.channels.getFollowedChannels(this);\n }\n /**\n * Gets the follow data of the user to the given broadcaster, or `null` if the user doesn't follow the broadcaster.\n *\n * This requires user authentication.\n * For broadcaster authentication, you can use `getChannelFollower` while switching `this` and the parameter.\n *\n * @param broadcaster The broadcaster to check the follow to.\n */\n async getFollowedChannel(broadcaster) {\n const result = await this._client.channels.getFollowedChannels(this, broadcaster);\n return result.data[0] ?? null;\n }\n /**\n * Checks whether the user is following the given broadcaster.\n *\n * This requires user authentication.\n * For broadcaster authentication, you can use `isFollowedBy` while switching `this` and the parameter.\n *\n * @param broadcaster The broadcaster to check the user's follow to.\n */\n async follows(broadcaster) {\n return (await this.getFollowedChannel(broadcaster)) !== null;\n }\n /**\n * Gets a list of users that follow the broadcaster.\n */\n async getChannelFollowers() {\n return await this._client.channels.getChannelFollowers(this);\n }\n /**\n * Gets the follow data of the given user to the broadcaster, or `null` if the user doesn't follow the broadcaster.\n *\n * This requires broadcaster authentication.\n * For user authentication, you can use `getFollowedChannel` while switching `this` and the parameter.\n *\n * @param user The user to check the follow from.\n */\n async getChannelFollower(user) {\n const result = await this._client.channels.getChannelFollowers(this, user);\n return result.data[0] ?? null;\n }\n /**\n * Checks whether the given user is following the broadcaster.\n *\n * This requires broadcaster authentication.\n * For user authentication, you can use `follows` while switching `this` and the parameter.\n *\n * @param user The user to check the broadcaster's follow from.\n */\n async isFollowedBy(user) {\n return (await this.getChannelFollower(user)) !== null;\n }\n /**\n * Gets the subscription data for the user to the given broadcaster, or `null` if the user is not subscribed.\n *\n * This requires user authentication.\n * For broadcaster authentication, you can use `getSubscriber` while switching `this` and the parameter.\n *\n * @param broadcaster The broadcaster you want to get the subscription data for.\n */\n async getSubscriptionTo(broadcaster) {\n return await this._client.subscriptions.checkUserSubscription(this, broadcaster);\n }\n /**\n * Checks whether the user is subscribed to the given broadcaster.\n *\n * This requires user authentication.\n * For broadcaster authentication, you can use `hasSubscriber` while switching `this` and the parameter.\n *\n * @param broadcaster The broadcaster you want to check the subscription for.\n */\n async isSubscribedTo(broadcaster) {\n return (await this.getSubscriptionTo(broadcaster)) !== null;\n }\n /**\n * Gets the subscription data for the given user to the broadcaster, or `null` if the user is not subscribed.\n *\n * This requires broadcaster authentication.\n * For user authentication, you can use `getSubscriptionTo` while switching `this` and the parameter.\n *\n * @param user The user you want to get the subscription data for.\n */\n async getSubscriber(user) {\n return await this._client.subscriptions.getSubscriptionForUser(this, user);\n }\n /**\n * Checks whether the given user is subscribed to the broadcaster.\n *\n * This requires broadcaster authentication.\n * For user authentication, you can use `isSubscribedTo` while switching `this` and the parameter.\n *\n * @param user The user you want to check the subscription for.\n */\n async hasSubscriber(user) {\n return (await this.getSubscriber(user)) !== null;\n }\n};\n__decorate([\n Enumerable(false)\n], HelixUser.prototype, \"_client\", void 0);\nHelixUser = __decorate([\n rtfm('api', 'HelixUser', 'id')\n], HelixUser);\nexport { HelixUser };\n", "import { __decorate } from \"tslib\";\nimport { Enumerable } from '@d-fischer/shared-utils';\nimport { checkRelationAssertion, DataObject, rawDataSymbol, rtfm } from '@twurple/common';\n/**\n * An user blocked by a previously given user.\n */\nlet HelixUserBlock = class HelixUserBlock extends DataObject {\n /** @internal */ _client;\n /** @internal */\n constructor(data, client) {\n super(data);\n this._client = client;\n }\n /**\n * The ID of the blocked user.\n */\n get userId() {\n return this[rawDataSymbol].user_id;\n }\n /**\n * The name of the blocked user.\n */\n get userName() {\n return this[rawDataSymbol].user_login;\n }\n /**\n * The display name of the blocked user.\n */\n get userDisplayName() {\n return this[rawDataSymbol].display_name;\n }\n /**\n * Gets additional information about the blocked user.\n */\n async getUser() {\n return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].user_id));\n }\n};\n__decorate([\n Enumerable(false)\n], HelixUserBlock.prototype, \"_client\", void 0);\nHelixUserBlock = __decorate([\n rtfm('api', 'HelixUserBlock', 'userId')\n], HelixUserBlock);\nexport { HelixUserBlock };\n", "var HelixVideoApi_1;\nimport { __decorate } from \"tslib\";\nimport { Enumerable } from '@d-fischer/shared-utils';\nimport { extractUserId, rtfm } from '@twurple/common';\nimport { HelixRequestBatcher } from '../../utils/HelixRequestBatcher.js';\nimport { HelixPaginatedRequest } from '../../utils/pagination/HelixPaginatedRequest.js';\nimport { createPaginatedResult } from '../../utils/pagination/HelixPaginatedResult.js';\nimport { createPaginationQuery } from '../../utils/pagination/HelixPagination.js';\nimport { BaseApi } from '../BaseApi.js';\nimport { HelixVideo } from './HelixVideo.js';\n/**\n * The Helix API methods that deal with videos.\n *\n * Can be accessed using `client.videos` on an {@link ApiClient} instance.\n *\n * ## Example\n * ```ts\n * const api = new ApiClient({ authProvider });\n * const { data: videos } = await api.videos.getVideosByUser('125328655');\n * ```\n *\n * @meta category helix\n * @meta categorizedTitle Videos\n */\nlet HelixVideoApi = HelixVideoApi_1 = class HelixVideoApi extends BaseApi {\n /** @internal */\n _getVideoByIdBatcher = new HelixRequestBatcher({\n url: 'videos',\n }, 'id', 'id', this._client, (data) => new HelixVideo(data, this._client));\n /**\n * Gets the video data for the given list of video IDs.\n *\n * @param ids The video IDs you want to look up.\n */\n async getVideosByIds(ids) {\n const result = await this._getVideos('id', ids);\n return result.data;\n }\n /**\n * Gets the video data for the given video ID.\n *\n * @param id The video ID you want to look up.\n */\n async getVideoById(id) {\n const videos = await this.getVideosByIds([id]);\n return videos.length ? videos[0] : null;\n }\n /**\n * Gets the video data for the given video ID, batching multiple calls into fewer requests as the API allows.\n *\n * @param id The video ID you want to look up.\n */\n async getVideoByIdBatched(id) {\n return await this._getVideoByIdBatcher.request(id);\n }\n /**\n * Gets the videos of the given user.\n *\n * @param user The user you want to get videos from.\n * @param filter\n *\n * @expandParams\n */\n async getVideosByUser(user, filter = {}) {\n const userId = extractUserId(user);\n return await this._getVideos('user_id', [userId], filter);\n }\n /**\n * Creates a paginator for videos of the given user.\n *\n * @param user The user you want to get videos from.\n * @param filter\n *\n * @expandParams\n */\n getVideosByUserPaginated(user, filter = {}) {\n const userId = extractUserId(user);\n return this._getVideosPaginated('user_id', [userId], filter);\n }\n /**\n * Gets the videos of the given game.\n *\n * @param gameId The game you want to get videos from.\n * @param filter\n *\n * @expandParams\n */\n async getVideosByGame(gameId, filter = {}) {\n return await this._getVideos('game_id', [gameId], filter);\n }\n /**\n * Creates a paginator for videos of the given game.\n *\n * @param gameId The game you want to get videos from.\n * @param filter\n *\n * @expandParams\n */\n getVideosByGamePaginated(gameId, filter = {}) {\n return this._getVideosPaginated('game_id', [gameId], filter);\n }\n /**\n * Deletes videos by its IDs.\n *\n * @param broadcaster The broadcaster to delete the videos for.\n * @param ids The IDs of the videos to delete.\n */\n async deleteVideosByIds(broadcaster, ids) {\n await this._client.callApi({\n type: 'helix',\n url: 'videos',\n method: 'DELETE',\n scopes: ['channel:manage:videos'],\n userId: extractUserId(broadcaster),\n query: {\n id: ids,\n },\n });\n }\n /** @internal */\n async _getVideos(filterType, filterValues, filter = {}) {\n if (!filterValues.length) {\n return { data: [] };\n }\n const result = await this._client.callApi({\n type: 'helix',\n url: 'videos',\n userId: filterType === 'user_id' ? filterValues[0] : undefined,\n query: {\n ...HelixVideoApi_1._makeVideosQuery(filterType, filterValues, filter),\n ...createPaginationQuery(filter),\n },\n });\n return createPaginatedResult(result, HelixVideo, this._client);\n }\n /** @internal */\n _getVideosPaginated(filterType, filterValues, filter = {}) {\n return new HelixPaginatedRequest({\n url: 'videos',\n userId: filterType === 'user_id' ? filterValues[0] : undefined,\n query: HelixVideoApi_1._makeVideosQuery(filterType, filterValues, filter),\n }, this._client, data => new HelixVideo(data, this._client));\n }\n /** @internal */\n static _makeVideosQuery(filterType, filterValues, filter = {}) {\n const { language, period, orderBy, type } = filter;\n return {\n [filterType]: filterValues,\n language,\n period,\n sort: orderBy,\n type,\n };\n }\n};\n__decorate([\n Enumerable(false)\n], HelixVideoApi.prototype, \"_getVideoByIdBatcher\", void 0);\nHelixVideoApi = HelixVideoApi_1 = __decorate([\n rtfm('api', 'HelixVideoApi')\n], HelixVideoApi);\nexport { HelixVideoApi };\n", "import { __decorate } from \"tslib\";\nimport { Cacheable, CachedGetter } from '@d-fischer/cache-decorators';\nimport { Enumerable } from '@d-fischer/shared-utils';\nimport { checkRelationAssertion, DataObject, HellFreezesOverError, rawDataSymbol, rtfm } from '@twurple/common';\n/**\n * A video on Twitch.\n */\nlet HelixVideo = class HelixVideo extends DataObject {\n /** @internal */ _client;\n /** @internal */\n constructor(data, client) {\n super(data);\n this._client = client;\n }\n /**\n * The ID of the video.\n */\n get id() {\n return this[rawDataSymbol].id;\n }\n /**\n * The ID of the user who created the video.\n */\n get userId() {\n return this[rawDataSymbol].user_id;\n }\n /**\n * The name of the user who created the video.\n */\n get userName() {\n return this[rawDataSymbol].user_login;\n }\n /**\n * The display name of the user who created the video.\n */\n get userDisplayName() {\n return this[rawDataSymbol].user_name;\n }\n /**\n * Gets information about the user who created the video.\n */\n async getUser() {\n return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].user_id));\n }\n /**\n * The title of the video.\n */\n get title() {\n return this[rawDataSymbol].title;\n }\n /**\n * The description of the video.\n */\n get description() {\n return this[rawDataSymbol].description;\n }\n /**\n * The date when the video was created.\n */\n get creationDate() {\n return new Date(this[rawDataSymbol].created_at);\n }\n /**\n * The date when the video was published.\n */\n get publishDate() {\n return new Date(this[rawDataSymbol].published_at);\n }\n /**\n * The URL of the video.\n */\n get url() {\n return this[rawDataSymbol].url;\n }\n /**\n * The URL of the thumbnail of the video.\n */\n get thumbnailUrl() {\n return this[rawDataSymbol].thumbnail_url;\n }\n /**\n * Builds the thumbnail URL of the video using the given dimensions.\n *\n * @param width The width of the thumbnail.\n * @param height The height of the thumbnail.\n */\n getThumbnailUrl(width, height) {\n return this[rawDataSymbol].thumbnail_url\n .replace('%{width}', width.toString())\n .replace('%{height}', height.toString());\n }\n /**\n * Whether the video is public or not.\n */\n get isPublic() {\n return this[rawDataSymbol].viewable === 'public';\n }\n /**\n * The number of views of the video.\n */\n get views() {\n return this[rawDataSymbol].view_count;\n }\n /**\n * The language of the video.\n */\n get language() {\n return this[rawDataSymbol].language;\n }\n /**\n * The type of the video.\n */\n get type() {\n return this[rawDataSymbol].type;\n }\n /**\n * The duration of the video, as formatted by Twitch.\n */\n get duration() {\n return this[rawDataSymbol].duration;\n }\n /**\n * The duration of the video, in seconds.\n */\n get durationInSeconds() {\n const parts = this[rawDataSymbol].duration.match(/\\d+[hms]/g);\n if (!parts) {\n throw new HellFreezesOverError(`Could not parse duration string: ${this[rawDataSymbol].duration}`);\n }\n return parts\n .map(part => {\n const partialMatch = /(\\d+)([hms])/.exec(part);\n if (!partialMatch) {\n throw new HellFreezesOverError(`Could not parse partial duration string: ${part}`);\n }\n const [, num, unit] = partialMatch;\n return parseInt(num, 10) * { h: 3600, m: 60, s: 1 }[unit];\n })\n .reduce((a, b) => a + b);\n }\n /**\n * The ID of the stream this video belongs to.\n *\n * Returns null if the video is not an archived stream.\n */\n get streamId() {\n return this[rawDataSymbol].stream_id;\n }\n /**\n * The raw data of muted segments of the video.\n */\n get mutedSegmentData() {\n return this[rawDataSymbol].muted_segments?.slice() ?? [];\n }\n /**\n * Checks whether the video is muted at a given offset or range.\n *\n * @param offset The start of your range, in seconds from the start of the video,\n * or if no duration is given, the exact offset that is checked.\n * @param duration The duration of your range, in seconds.\n * @param partial Whether the range check is only partial.\n *\n * By default, this function returns true only if the passed range is entirely contained in a muted segment.\n */\n isMutedAt(offset, duration, partial = false) {\n if (this[rawDataSymbol].muted_segments === null) {\n return false;\n }\n if (duration == null) {\n return this[rawDataSymbol].muted_segments.some(seg => seg.offset <= offset && offset <= seg.offset + seg.duration);\n }\n const end = offset + duration;\n if (partial) {\n return this[rawDataSymbol].muted_segments.some(seg => {\n const segEnd = seg.offset + seg.duration;\n return offset < segEnd && seg.offset < end;\n });\n }\n return this[rawDataSymbol].muted_segments.some(seg => {\n const segEnd = seg.offset + seg.duration;\n return seg.offset <= offset && end <= segEnd;\n });\n }\n};\n__decorate([\n Enumerable(false)\n], HelixVideo.prototype, \"_client\", void 0);\n__decorate([\n CachedGetter()\n], HelixVideo.prototype, \"durationInSeconds\", null);\nHelixVideo = __decorate([\n Cacheable,\n rtfm('api', 'HelixVideo', 'id')\n], HelixVideo);\nexport { HelixVideo };\n", "import { __decorate } from \"tslib\";\nimport { extractUserId, rtfm } from '@twurple/common';\nimport { createWhisperQuery } from '../../interfaces/endpoints/whisper.external.js';\nimport { BaseApi } from '../BaseApi.js';\n/**\n * The API methods that deal with whispers.\n *\n * Can be accessed using 'client.whispers' on an {@link ApiClient} instance\n *\n * ## Example\n * ```ts\n * const api = new ApiClient({ authProvider });\n * await api.whispers.sendWhisper('61369223', '86753099', 'Howdy, partner!');\n * ```\n *\n * @meta category helix\n * @meta categorizedTitle Whispers\n */\nlet HelixWhisperApi = class HelixWhisperApi extends BaseApi {\n /**\n * Sends a whisper message to the specified user.\n *\n * NOTE: The API may silently drop whispers that it suspects of violating Twitch policies. (The API does not indicate that it dropped the whisper; it returns a 204 status code as if it succeeded).\n *\n * @param from The user sending the whisper. This user must have a verified phone number and must match the user in the access token.\n * @param to The user to receive the whisper.\n * @param message The whisper message to send. The message must not be empty.\n *\n * The maximum message lengths are:\n *\n * 500 characters if the user you're sending the message to hasn't whispered you before.\n * 10,000 characters if the user you're sending the message to has whispered you before.\n *\n * Messages that exceed the maximum length are truncated.\n */\n async sendWhisper(from, to, message) {\n await this._client.callApi({\n type: 'helix',\n url: 'whispers',\n method: 'POST',\n userId: extractUserId(from),\n scopes: ['user:manage:whispers'],\n query: createWhisperQuery(from, to),\n jsonBody: {\n message,\n },\n });\n }\n};\nHelixWhisperApi = __decorate([\n rtfm('api', 'HelixWhisperApi')\n], HelixWhisperApi);\nexport { HelixWhisperApi };\n", "import { extractUserId } from '@twurple/common';\n/** @internal */\nexport function createWhisperQuery(from, to) {\n return {\n from_user_id: extractUserId(from),\n to_user_id: extractUserId(to),\n };\n}\n", "/**\n * Reporting details for an API request.\n */\nexport class ApiReportedRequest {\n _options;\n _httpStatus;\n _resolvedUserId;\n /** @internal */\n constructor(_options, _httpStatus, _resolvedUserId) {\n this._options = _options;\n this._httpStatus = _httpStatus;\n this._resolvedUserId = _resolvedUserId;\n }\n /**\n * The options used to call the API.\n */\n get options() {\n return this._options;\n }\n /**\n * The HTTP status code returned by Twitch for the request.\n */\n get httpStatus() {\n return this._httpStatus;\n }\n /**\n * The ID of the user that was used for authentication, or `null` if an app access token was used.\n */\n get resolvedUserId() {\n return this._resolvedUserId;\n }\n}\n", "import { __decorate } from \"tslib\";\nimport { rtfm } from '@twurple/common';\nimport { BaseApiClient } from './BaseApiClient.js';\n/** @private */\nlet NoContextApiClient = class NoContextApiClient extends BaseApiClient {\n /** @internal */\n _getUserIdFromRequestContext() {\n return null;\n }\n};\nNoContextApiClient = __decorate([\n rtfm('api', 'ApiClient')\n], NoContextApiClient);\nexport { NoContextApiClient };\n", "import { __decorate } from \"tslib\";\nimport { rtfm } from '@twurple/common';\nimport { BaseApiClient } from './BaseApiClient.js';\n/** @private */\nlet UserContextApiClient = class UserContextApiClient extends BaseApiClient {\n _userId;\n /** @internal */\n constructor(config, logger, rateLimiter, _userId) {\n super(config, logger, rateLimiter);\n this._userId = _userId;\n }\n /** @internal */\n _getUserIdFromRequestContext() {\n return this._userId;\n }\n};\nUserContextApiClient = __decorate([\n rtfm('api', 'ApiClient')\n], UserContextApiClient);\nexport { UserContextApiClient };\n", "import { Bot, InputFile } from 'grammy';\nimport type { Env } from '../types/env';\nimport type { I18nService, SupportedLanguage } from './i18n.service';\nimport { ThumbnailBuilder } from '../utils/thumbnail';\n\nexport interface StreamOnlineNotification {\n chatId: number;\n language: SupportedLanguage;\n channelName: string;\n channelUrl: string;\n category: string;\n title: string;\n thumbnailUrl?: string;\n showImage: boolean;\n}\n\nexport interface StreamOfflineNotification {\n chatId: number;\n language: SupportedLanguage;\n channelName: string;\n channelUrl: string;\n categories: string[];\n duration: string;\n}\n\nexport interface CategoryChangeNotification {\n chatId: number;\n language: SupportedLanguage;\n channelName: string;\n channelUrl: string;\n oldCategory: string;\n category: string;\n}\n\nexport interface TitleChangeNotification {\n chatId: number;\n language: SupportedLanguage;\n channelName: string;\n channelUrl: string;\n oldTitle: string;\n title: string;\n}\n\nexport interface TitleAndCategoryChangeNotification {\n chatId: number;\n language: SupportedLanguage;\n channelName: string;\n channelUrl: string;\n oldTitle: string;\n title: string;\n oldCategory: string;\n category: string;\n}\n\nexport class TelegramService {\n private bot: Bot;\n private i18n: I18nService;\n private thumbnailBuilder: ThumbnailBuilder;\n\n constructor(env: Env, i18n: I18nService) {\n this.bot = new Bot(env.TELEGRAM_TOKEN);\n this.i18n = i18n;\n this.thumbnailBuilder = new ThumbnailBuilder();\n }\n\n async sendStreamOnlineNotification(notification: StreamOnlineNotification): Promise {\n const channelLink = `${notification.channelName}`;\n\n const text = this.i18n.t(notification.language, 'notifications.streams.nowOnline', {\n channelLink,\n category: notification.category,\n title: notification.title,\n });\n\n if (notification.showImage && notification.thumbnailUrl) {\n try {\n const thumbnailUrl = await this.thumbnailBuilder.build(notification.thumbnailUrl, true);\n await this.bot.api.sendPhoto(notification.chatId, new InputFile(new URL(thumbnailUrl)), {\n caption: text,\n parse_mode: 'HTML',\n });\n return;\n } catch (error) {\n // Fallback to text message if image fails\n console.error('Failed to send photo:', error);\n }\n }\n\n await this.bot.api.sendMessage(notification.chatId, text, {\n parse_mode: 'HTML',\n link_preview_options: { is_disabled: false },\n });\n }\n\n async sendStreamOfflineNotification(notification: StreamOfflineNotification): Promise {\n const channelLink = `${notification.channelName}`;\n const categories = notification.categories.join(', ');\n\n const text = this.i18n.t(notification.language, 'notifications.streams.nowOffline', {\n channelLink,\n categories,\n duration: notification.duration,\n });\n\n await this.bot.api.sendMessage(notification.chatId, text, {\n parse_mode: 'HTML',\n link_preview_options: { is_disabled: true },\n });\n }\n\n async sendCategoryChangeNotification(notification: CategoryChangeNotification): Promise {\n const channelLink = `${notification.channelName}`;\n\n const text = this.i18n.t(notification.language, 'notifications.streams.newCategory', {\n channelLink,\n oldCategory: notification.oldCategory,\n category: notification.category,\n });\n\n await this.bot.api.sendMessage(notification.chatId, text, {\n parse_mode: 'HTML',\n link_preview_options: { is_disabled: true },\n });\n }\n\n async sendTitleChangeNotification(notification: TitleChangeNotification): Promise {\n const channelLink = `${notification.channelName}`;\n\n const text = this.i18n.t(notification.language, 'notifications.streams.titleChanged', {\n channelLink,\n oldTitle: notification.oldTitle,\n title: notification.title,\n });\n\n await this.bot.api.sendMessage(notification.chatId, text, {\n parse_mode: 'HTML',\n link_preview_options: { is_disabled: true },\n });\n }\n\n async sendTitleAndCategoryChangeNotification(\n notification: TitleAndCategoryChangeNotification\n ): Promise {\n const channelLink = `${notification.channelName}`;\n\n const text = this.i18n.t(notification.language, 'notifications.streams.titleAndCategoryChanged', {\n channelLink,\n oldTitle: notification.oldTitle,\n title: notification.title,\n oldCategory: notification.oldCategory,\n category: notification.category,\n });\n\n await this.bot.api.sendMessage(notification.chatId, text, {\n parse_mode: 'HTML',\n link_preview_options: { is_disabled: true },\n });\n }\n\n getBot(): Bot {\n return this.bot;\n }\n}\n", "export class ThumbnailBuilder {\n /**\n * Build thumbnail URL from Twitch template URL\n * @param thumbnailUrl - Twitch thumbnail URL with {width} and {height} placeholders\n * @param checkValidity - Whether to check if the URL is accessible (with retry logic)\n * @returns Final thumbnail URL\n */\n async build(thumbnailUrl: string, checkValidity = false): Promise {\n let thumbnail = thumbnailUrl\n .replace('{width}', '1920')\n .replace('{height}', '1080');\n\n if (!checkValidity) {\n return thumbnail;\n }\n\n const isValid = await this.checkValidity(thumbnail, 0);\n\n if (!isValid) {\n // Fallback to lower resolution\n thumbnail = thumbnail\n .replace('1920', '1280')\n .replace('1080', '720');\n }\n\n return thumbnail;\n }\n\n /**\n * Check if thumbnail URL is accessible with retry logic\n * @param url - URL to check\n * @param attempt - Current attempt number (max 5)\n * @returns Whether the URL is valid\n */\n private async checkValidity(url: string, attempt: number): Promise {\n try {\n const response = await fetch(url, {\n method: 'HEAD',\n redirect: 'manual',\n });\n\n if (response.status === 200) {\n return true;\n }\n\n if (attempt >= 5) {\n return false;\n }\n\n // Wait 5 seconds before retry\n await new Promise(resolve => setTimeout(resolve, 5000));\n return this.checkValidity(url, attempt + 1);\n } catch (error) {\n if (attempt >= 5) {\n return false;\n }\n\n await new Promise(resolve => setTimeout(resolve, 5000));\n return this.checkValidity(url, attempt + 1);\n }\n }\n}\n", "import { ApiClient } from '@twurple/api';\nimport type { Env } from '../types/env';\n\nexport class EventSubService {\n private apiClient: ApiClient;\n private webhookUrl: string;\n private secret: string;\n\n constructor(apiClient: ApiClient, env: Env, baseUrl: string) {\n this.apiClient = apiClient;\n this.webhookUrl = `${baseUrl}/twitch-webhook`;\n this.secret = env.TWITCH_EVENTSUB_SECRET;\n }\n\n /**\n * Subscribe to all events for a broadcaster (stream.online, stream.offline, channel.update)\n */\n async subscribeToChannel(broadcasterId: string): Promise {\n try {\n // Subscribe to stream online events\n await this.apiClient.eventSub.subscribeToStreamOnlineEvents(\n broadcasterId,\n {\n method: 'webhook',\n callback: this.webhookUrl,\n secret: this.secret,\n }\n );\n\n // Subscribe to stream offline events\n await this.apiClient.eventSub.subscribeToStreamOfflineEvents(\n broadcasterId,\n {\n method: 'webhook',\n callback: this.webhookUrl,\n secret: this.secret,\n }\n );\n\n // Subscribe to channel update events (title/category changes)\n await this.apiClient.eventSub.subscribeToChannelUpdateEvents(\n broadcasterId,\n {\n method: 'webhook',\n callback: this.webhookUrl,\n secret: this.secret,\n }\n );\n } catch (error) {\n console.error(`Failed to subscribe to events for broadcaster ${broadcasterId}:`, error);\n throw error;\n }\n }\n\n /**\n * Unsubscribe from all events for a broadcaster\n */\n async unsubscribeFromChannel(broadcasterId: string): Promise {\n try {\n // Get all subscriptions\n const subscriptions = await this.apiClient.eventSub.getSubscriptions();\n \n // Filter subscriptions for this broadcaster and our webhook URL\n const broadcasterSubs = subscriptions.data.filter(\n (sub) => {\n const transportMethod = (sub as any).transport?.callback || (sub as any)._transport?.callback;\n const broadcastId = (sub.condition as any).broadcaster_user_id;\n return transportMethod === this.webhookUrl && broadcastId === broadcasterId;\n }\n );\n\n // Delete each subscription\n for (const sub of broadcasterSubs) {\n await this.apiClient.eventSub.deleteSubscription(sub.id);\n }\n } catch (error) {\n console.error(`Failed to unsubscribe from events for broadcaster ${broadcasterId}:`, error);\n throw error;\n }\n }\n\n /**\n * Check if we already have active subscriptions for a broadcaster\n */\n async hasActiveSubscriptions(broadcasterId: string): Promise {\n try {\n const subscriptions = await this.apiClient.eventSub.getSubscriptions();\n \n return subscriptions.data.some(\n (sub) => {\n const transportMethod = (sub as any).transport?.callback || (sub as any)._transport?.callback;\n const broadcastId = (sub.condition as any).broadcaster_user_id;\n return transportMethod === this.webhookUrl && broadcastId === broadcasterId && sub.status === 'enabled';\n }\n );\n } catch (error) {\n console.error(`Failed to check subscriptions for broadcaster ${broadcasterId}:`, error);\n return false;\n }\n }\n\n /**\n * Delete a specific subscription by ID\n */\n async deleteSubscription(subscriptionId: string): Promise {\n try {\n await this.apiClient.eventSub.deleteSubscription(subscriptionId);\n } catch (error) {\n console.error(`Failed to delete subscription ${subscriptionId}:`, error);\n throw error;\n }\n }\n\n /**\n * Get all active subscriptions for our webhook\n */\n async getActiveSubscriptions() {\n try {\n const subscriptions = await this.apiClient.eventSub.getSubscriptions();\n return subscriptions.data.filter((sub) => {\n const transportMethod = (sub as any).transport?.callback || (sub as any)._transport?.callback;\n return transportMethod === this.webhookUrl;\n });\n } catch (error) {\n console.error('Failed to get active subscriptions:', error);\n return [];\n }\n }\n}\n", "import type { DrizzleD1Database } from 'drizzle-orm/d1';\n\n/**\n * Database connection abstraction\n * This allows us to support different database implementations (D1, PostgreSQL, etc.)\n */\nexport interface IDatabaseConnection {\n getClient(): any; // Returns the underlying database client (DrizzleD1Database, etc.)\n}\n\n/**\n * Cloudflare D1 database connection\n */\nexport class CloudflareD1Connection implements IDatabaseConnection {\n constructor(private client: DrizzleD1Database) {}\n\n getClient(): DrizzleD1Database {\n return this.client;\n }\n}\n", "import type { \n IChatRepository,\n IChannelRepository,\n IFollowRepository,\n IStreamRepository\n} from './repositories/interfaces';\nimport {\n ChatDrizzleRepository,\n ChannelDrizzleRepository,\n FollowDrizzleRepository,\n StreamDrizzleRepository\n} from './repositories/drizzle';\nimport type { IDatabaseConnection } from './connection';\n\nexport interface IRepositoryFactory {\n createChatRepository(): IChatRepository;\n createChannelRepository(): IChannelRepository;\n createFollowRepository(): IFollowRepository;\n createStreamRepository(): IStreamRepository;\n}\n\n/**\n * Factory for creating Drizzle-based repositories\n * Works with any Drizzle-compatible database (D1, PostgreSQL, etc.)\n */\nexport class DrizzleRepositoryFactory implements IRepositoryFactory {\n constructor(private connection: IDatabaseConnection) {}\n\n createChatRepository(): IChatRepository {\n return new ChatDrizzleRepository(this.connection.getClient());\n }\n\n createChannelRepository(): IChannelRepository {\n return new ChannelDrizzleRepository(this.connection.getClient());\n }\n\n createFollowRepository(): IFollowRepository {\n return new FollowDrizzleRepository(this.connection.getClient());\n }\n\n createStreamRepository(): IStreamRepository {\n return new StreamDrizzleRepository(this.connection.getClient());\n }\n}\n", "export * from './chat.drizzle.repository';\nexport * from './channel.drizzle.repository';\nexport * from './follow.drizzle.repository';\nexport * from './stream.drizzle.repository';\n", "import type { DrizzleD1Database } from 'drizzle-orm/d1';\nimport { eq } from 'drizzle-orm';\nimport { randomUUID } from 'node:crypto';\nimport { chats, chatSettings } from '../../schema';\nimport { Chat, ChatSettings } from '../../../domain/models';\nimport { DomainMapper } from '../../../domain/mapper';\nimport type { IChatRepository } from '../interfaces';\n\nexport class ChatDrizzleRepository implements IChatRepository {\n constructor(private db: DrizzleD1Database) {}\n\n async findByChatId(chatId: number, service: 'telegram' = 'telegram'): Promise {\n const chatIdStr = chatId.toString();\n \n const chatResult = await this.db\n .select()\n .from(chats)\n .where(eq(chats.chatId, chatIdStr))\n .limit(1);\n \n if (!chatResult[0]) return undefined;\n\n const settingsResult = await this.db\n .select()\n .from(chatSettings)\n .where(eq(chatSettings.chatId, chatResult[0].id))\n .limit(1);\n \n return DomainMapper.toDomainChat({\n ...chatResult[0],\n settings: settingsResult[0] || null\n });\n }\n\n async findById(id: string): Promise {\n const chatResult = await this.db\n .select()\n .from(chats)\n .where(eq(chats.id, id))\n .limit(1);\n \n if (!chatResult[0]) return undefined;\n\n const settingsResult = await this.db\n .select()\n .from(chatSettings)\n .where(eq(chatSettings.chatId, chatResult[0].id))\n .limit(1);\n \n return DomainMapper.toDomainChat({\n ...chatResult[0],\n settings: settingsResult[0] || null\n });\n }\n\n async findAllByService(service: 'telegram' = 'telegram'): Promise {\n const chatResults = await this.db\n .select()\n .from(chats)\n .where(eq(chats.service, service));\n \n const chatsWithSettings: Chat[] = [];\n \n for (const chat of chatResults) {\n const settingsResult = await this.db\n .select()\n .from(chatSettings)\n .where(eq(chatSettings.chatId, chat.id))\n .limit(1);\n \n chatsWithSettings.push(DomainMapper.toDomainChat({\n ...chat,\n settings: settingsResult[0] || null\n }));\n }\n \n return chatsWithSettings;\n }\n\n async create(chatId: string, service: 'telegram' = 'telegram'): Promise {\n const id = randomUUID();\n await this.db.insert(chats).values({ id, chatId, service });\n \n // Create default settings\n await this.db.insert(chatSettings).values({\n chatId: id,\n language: 'en',\n offlineNotification: true,\n gameChangeNotification: false,\n titleChangeNotification: false,\n gameAndTitleChangeNotification: false,\n imageInNotification: true,\n });\n \n return id;\n }\n\n async updateSettings(chatId: string, settings: Partial): Promise {\n await this.db\n .update(chatSettings)\n .set(settings)\n .where(eq(chatSettings.chatId, chatId));\n }\n}\n", "import { sqliteTable, text, integer } from 'drizzle-orm/sqlite-core';\nimport { relations } from 'drizzle-orm';\nimport { randomUUID } from 'node:crypto';\n\n// Chat table\nexport const chats = sqliteTable('chats', {\n id: text('id').primaryKey().$defaultFn(() => randomUUID()),\n chatId: text('chat_id').notNull(),\n service: text('service', { enum: ['telegram'] }).notNull().default('telegram'),\n});\n\nexport const chatsRelations = relations(chats, ({ one, many }) => ({\n settings: one(chatSettings, {\n fields: [chats.id],\n references: [chatSettings.chatId],\n }),\n follows: many(follows),\n}));\n\n// Chat Settings table\nexport const chatSettings = sqliteTable('chat_settings', {\n id: text('id').primaryKey().$defaultFn(() => randomUUID()),\n chatId: text('chat_id').notNull().unique().references(() => chats.id, { onDelete: 'cascade' }),\n gameChangeNotification: integer('game_change_notification', { mode: 'boolean' }).notNull().default(true),\n titleChangeNotification: integer('title_change_notification', { mode: 'boolean' }).notNull().default(false),\n gameAndTitleChangeNotification: integer('game_and_title_change_notification', { mode: 'boolean' }).notNull().default(false),\n offlineNotification: integer('offline_notification', { mode: 'boolean' }).notNull().default(true),\n imageInNotification: integer('image_in_notification', { mode: 'boolean' }).notNull().default(true),\n language: text('language', { enum: ['ru', 'en', 'uk'] }).notNull().default('en'),\n});\n\nexport const chatSettingsRelations = relations(chatSettings, ({ one }) => ({\n chat: one(chats, {\n fields: [chatSettings.chatId],\n references: [chats.id],\n }),\n}));\n\n// Channel table\nexport const channels = sqliteTable('channels', {\n id: text('id').primaryKey().$defaultFn(() => randomUUID()),\n channelId: text('channel_id').notNull(),\n service: text('service', { enum: ['twitch'] }).notNull().default('twitch'),\n isLive: integer('is_live', { mode: 'boolean' }).notNull().default(false),\n title: text('title'),\n category: text('category'),\n updatedAt: text('updated_at').$defaultFn(() => new Date().toISOString()),\n});\n\nexport const channelsRelations = relations(channels, ({ many }) => ({\n follows: many(follows),\n streams: many(streams),\n}));\n\n// Follow table\nexport const follows = sqliteTable('follows', {\n id: text('id').primaryKey().$defaultFn(() => randomUUID()),\n channelId: text('channel_id').notNull().references(() => channels.id, { onDelete: 'cascade' }),\n chatId: text('chat_id').notNull().references(() => chats.id, { onDelete: 'cascade' }),\n});\n\nexport const followsRelations = relations(follows, ({ one }) => ({\n channel: one(channels, {\n fields: [follows.channelId],\n references: [channels.id],\n }),\n chat: one(chats, {\n fields: [follows.chatId],\n references: [chats.id],\n }),\n}));\n\n// Stream table\nexport const streams = sqliteTable('streams', {\n id: text('id').primaryKey(), // Twitch stream ID\n channelId: text('channel_id').notNull().references(() => channels.id, { onDelete: 'cascade' }),\n isLive: integer('is_live', { mode: 'boolean' }).notNull().default(true),\n title: text('title'),\n category: text('category'),\n titles: text('titles', { mode: 'json' }).$type().notNull().default([]),\n categories: text('categories', { mode: 'json' }).$type().notNull().default([]),\n startedAt: text('started_at').$defaultFn(() => new Date().toISOString()),\n updatedAt: text('updated_at').$defaultFn(() => new Date().toISOString()),\n endedAt: text('ended_at'),\n});\n\nexport const streamsRelations = relations(streams, ({ one }) => ({\n channel: one(channels, {\n fields: [streams.channelId],\n references: [channels.id],\n }),\n}));\n\n// Types for insert and select\nexport type Chat = typeof chats.$inferSelect;\nexport type NewChat = typeof chats.$inferInsert;\n\nexport type ChatSettings = typeof chatSettings.$inferSelect;\nexport type NewChatSettings = typeof chatSettings.$inferInsert;\n\nexport type Channel = typeof channels.$inferSelect;\nexport type NewChannel = typeof channels.$inferInsert;\n\nexport type Follow = typeof follows.$inferSelect;\nexport type NewFollow = typeof follows.$inferInsert;\n\nexport type Stream = typeof streams.$inferSelect;\nexport type NewStream = typeof streams.$inferInsert;\n", "// Mappers to convert between database schema and domain models\nimport type { Chat as DbChat, ChatSettings as DbChatSettings, Channel as DbChannel, Follow as DbFollow, Stream as DbStream } from '../db/schema';\nimport { Chat, ChatSettings, Channel, Follow, Stream } from './models';\nimport type { SupportedLanguage } from './models';\n\nexport class DomainMapper {\n static toDomainChat(dbChat: DbChat & { settings: DbChatSettings | null }): Chat {\n return new Chat({\n id: dbChat.id,\n chatId: dbChat.chatId,\n service: dbChat.service,\n settings: dbChat.settings ? this.toDomainChatSettings(dbChat.settings) : undefined,\n });\n }\n\n static toDomainChatSettings(dbSettings: DbChatSettings): ChatSettings {\n return new ChatSettings({\n id: dbSettings.id,\n chatId: dbSettings.chatId,\n gameChangeNotification: dbSettings.gameChangeNotification,\n titleChangeNotification: dbSettings.titleChangeNotification,\n gameAndTitleChangeNotification: dbSettings.gameAndTitleChangeNotification,\n offlineNotification: dbSettings.offlineNotification,\n imageInNotification: dbSettings.imageInNotification,\n language: dbSettings.language as SupportedLanguage,\n });\n }\n\n static toDomainChannel(dbChannel: DbChannel): Channel {\n return new Channel({\n id: dbChannel.id,\n channelId: dbChannel.channelId,\n service: dbChannel.service,\n isLive: dbChannel.isLive,\n title: dbChannel.title ?? undefined,\n category: dbChannel.category ?? undefined,\n updatedAt: dbChannel.updatedAt ? new Date(dbChannel.updatedAt) : undefined,\n });\n }\n\n static toDomainFollow(dbFollow: DbFollow): Follow {\n return new Follow({\n id: dbFollow.id,\n channelId: dbFollow.channelId,\n chatId: dbFollow.chatId,\n });\n }\n\n static toDomainStream(dbStream: DbStream): Stream {\n return new Stream({\n id: dbStream.id,\n channelId: dbStream.channelId,\n isLive: dbStream.isLive,\n title: dbStream.title ?? undefined,\n category: dbStream.category ?? undefined,\n titles: dbStream.titles,\n categories: dbStream.categories,\n startedAt: new Date(dbStream.startedAt!),\n updatedAt: dbStream.updatedAt ? new Date(dbStream.updatedAt) : undefined,\n endedAt: dbStream.endedAt ? new Date(dbStream.endedAt) : undefined,\n });\n }\n}\n", "// Domain models - business logic representations\n// These are separate from database schema to allow flexibility\n\nexport type ChatService = 'telegram';\nexport type ChannelService = 'twitch';\nexport type SupportedLanguage = 'en' | 'ru' | 'uk';\n\nexport class Chat {\n id: string;\n chatId: string;\n service: ChatService;\n settings?: ChatSettings;\n follows?: Follow[];\n\n constructor(data: {\n id: string;\n chatId: string;\n service: ChatService;\n settings?: ChatSettings;\n follows?: Follow[];\n }) {\n this.id = data.id;\n this.chatId = data.chatId;\n this.service = data.service;\n this.settings = data.settings;\n this.follows = data.follows;\n }\n}\n\nexport class ChatSettings {\n id: string;\n chatId: string;\n gameChangeNotification: boolean;\n titleChangeNotification: boolean;\n gameAndTitleChangeNotification: boolean;\n offlineNotification: boolean;\n imageInNotification: boolean;\n language: SupportedLanguage;\n\n constructor(data: {\n id: string;\n chatId: string;\n gameChangeNotification: boolean;\n titleChangeNotification: boolean;\n gameAndTitleChangeNotification: boolean;\n offlineNotification: boolean;\n imageInNotification: boolean;\n language: SupportedLanguage;\n }) {\n this.id = data.id;\n this.chatId = data.chatId;\n this.gameChangeNotification = data.gameChangeNotification;\n this.titleChangeNotification = data.titleChangeNotification;\n this.gameAndTitleChangeNotification = data.gameAndTitleChangeNotification;\n this.offlineNotification = data.offlineNotification;\n this.imageInNotification = data.imageInNotification;\n this.language = data.language;\n }\n}\n\nexport class Channel {\n id: string;\n channelId: string;\n service: ChannelService;\n isLive: boolean;\n title?: string;\n category?: string;\n updatedAt?: Date;\n follows?: Follow[];\n streams?: Stream[];\n\n constructor(data: {\n id: string;\n channelId: string;\n service: ChannelService;\n isLive: boolean;\n title?: string;\n category?: string;\n updatedAt?: Date;\n follows?: Follow[];\n streams?: Stream[];\n }) {\n this.id = data.id;\n this.channelId = data.channelId;\n this.service = data.service;\n this.isLive = data.isLive;\n this.title = data.title;\n this.category = data.category;\n this.updatedAt = data.updatedAt;\n this.follows = data.follows;\n this.streams = data.streams;\n }\n}\n\nexport class Follow {\n id: string;\n channelId: string;\n chatId: string;\n channel?: Channel;\n chat?: Chat;\n\n constructor(data: {\n id: string;\n channelId: string;\n chatId: string;\n channel?: Channel;\n chat?: Chat;\n }) {\n this.id = data.id;\n this.channelId = data.channelId;\n this.chatId = data.chatId;\n this.channel = data.channel;\n this.chat = data.chat;\n }\n}\n\nexport class Stream {\n id: string;\n channelId: string;\n isLive: boolean;\n title?: string;\n category?: string;\n titles: string[];\n categories: string[];\n startedAt: Date;\n updatedAt?: Date;\n endedAt?: Date;\n\n constructor(data: {\n id: string;\n channelId: string;\n isLive: boolean;\n title?: string;\n category?: string;\n titles: string[];\n categories: string[];\n startedAt: Date;\n updatedAt?: Date;\n endedAt?: Date;\n }) {\n this.id = data.id;\n this.channelId = data.channelId;\n this.isLive = data.isLive;\n this.title = data.title;\n this.category = data.category;\n this.titles = data.titles;\n this.categories = data.categories;\n this.startedAt = data.startedAt;\n this.updatedAt = data.updatedAt;\n this.endedAt = data.endedAt;\n }\n}\n\n// Errors\nexport class FollowAlreadyExistsError extends Error {\n constructor() {\n super('Follow already exists');\n this.name = 'FollowAlreadyExistsError';\n }\n}\n\nexport class FollowNotFoundError extends Error {\n constructor() {\n super('Follow not found');\n this.name = 'FollowNotFoundError';\n }\n}\n\nexport class ChannelNotFoundError extends Error {\n constructor() {\n super('Channel not found');\n this.name = 'ChannelNotFoundError';\n }\n}\n", "import type { DrizzleD1Database } from 'drizzle-orm/d1';\nimport { eq, and } from 'drizzle-orm';\nimport { randomUUID } from 'node:crypto';\nimport { channels } from '../../schema';\nimport type { NewChannel } from '../../schema';\nimport { Channel, ChannelNotFoundError } from '../../../domain/models';\nimport { DomainMapper } from '../../../domain/mapper';\nimport type { IChannelRepository } from '../interfaces';\n\nexport class ChannelDrizzleRepository implements IChannelRepository {\n constructor(private db: DrizzleD1Database) {}\n\n async findByChannelId(channelId: string, service: 'twitch' = 'twitch'): Promise {\n const result = await this.db\n .select()\n .from(channels)\n .where(and(eq(channels.channelId, channelId), eq(channels.service, service)))\n .limit(1);\n \n return result[0] ? DomainMapper.toDomainChannel(result[0]) : undefined;\n }\n\n async findById(id: string): Promise {\n const result = await this.db\n .select()\n .from(channels)\n .where(eq(channels.id, id))\n .limit(1);\n \n return result[0] ? DomainMapper.toDomainChannel(result[0]) : undefined;\n }\n\n async create(channelId: string, service: 'twitch' = 'twitch'): Promise {\n const id = randomUUID();\n const result = await this.db.insert(channels).values({\n id,\n channelId,\n service,\n isLive: false,\n }).returning();\n \n return DomainMapper.toDomainChannel(result[0]);\n }\n\n async update(id: string, data: Partial>): Promise {\n const result = await this.db\n .update(channels)\n .set({ ...data, updatedAt: new Date().toISOString() })\n .where(eq(channels.id, id))\n .returning();\n \n if (!result[0]) {\n throw new ChannelNotFoundError();\n }\n \n return DomainMapper.toDomainChannel(result[0]);\n }\n\n async updateChannelId(oldChannelId: string, newChannelId: string, service: 'twitch' = 'twitch'): Promise {\n await this.db\n .update(channels)\n .set({ channelId: newChannelId, updatedAt: new Date().toISOString() })\n .where(and(eq(channels.channelId, oldChannelId), eq(channels.service, service)));\n }\n}\n", "import type { DrizzleD1Database } from 'drizzle-orm/d1';\nimport { eq, and, count } from 'drizzle-orm';\nimport { randomUUID } from 'node:crypto';\nimport { follows } from '../../schema';\nimport { Follow, FollowAlreadyExistsError, FollowNotFoundError } from '../../../domain/models';\nimport { DomainMapper } from '../../../domain/mapper';\nimport type { IFollowRepository } from '../interfaces';\n\nexport class FollowDrizzleRepository implements IFollowRepository {\n constructor(private db: DrizzleD1Database) {}\n\n async findByChatAndChannel(chatId: string, channelId: string): Promise {\n const result = await this.db\n .select()\n .from(follows)\n .where(and(eq(follows.chatId, chatId), eq(follows.channelId, channelId)))\n .limit(1);\n \n return result[0] ? DomainMapper.toDomainFollow(result[0]) : undefined;\n }\n\n async findByChatId(chatId: string): Promise {\n const results = await this.db\n .select()\n .from(follows)\n .where(eq(follows.chatId, chatId));\n \n return results.map(r => DomainMapper.toDomainFollow(r));\n }\n\n async create(chatId: string, channelId: string): Promise {\n // Check if already exists\n const existing = await this.findByChatAndChannel(chatId, channelId);\n if (existing) {\n throw new FollowAlreadyExistsError();\n }\n \n const id = randomUUID();\n await this.db.insert(follows).values({ id, chatId, channelId });\n return id;\n }\n\n async delete(id: string): Promise {\n const result = await this.db\n .delete(follows)\n .where(eq(follows.id, id))\n .returning();\n \n if (result.length === 0) {\n throw new FollowNotFoundError();\n }\n }\n\n async findByChannelId(channelId: string): Promise {\n const results = await this.db\n .select()\n .from(follows)\n .where(eq(follows.channelId, channelId));\n \n return results.map(r => DomainMapper.toDomainFollow(r));\n }\n\n async findByChatIdPaginated(chatId: string, limit: number, offset: number): Promise {\n const results = await this.db\n .select()\n .from(follows)\n .where(eq(follows.chatId, chatId))\n .limit(limit)\n .offset(offset);\n \n return results.map(r => DomainMapper.toDomainFollow(r));\n }\n\n async countByChatId(chatId: string): Promise {\n const result = await this.db\n .select({ count: count() })\n .from(follows)\n .where(eq(follows.chatId, chatId));\n \n return result[0]?.count ?? 0;\n }\n}\n", "import type { DrizzleD1Database } from 'drizzle-orm/d1';\nimport { eq, desc } from 'drizzle-orm';\nimport { streams } from '../../schema';\nimport { Stream } from '../../../domain/models';\nimport { DomainMapper } from '../../../domain/mapper';\nimport type { IStreamRepository } from '../interfaces';\n\nexport class StreamDrizzleRepository implements IStreamRepository {\n constructor(private db: DrizzleD1Database) {}\n\n async findLatestByChannelId(channelId: string): Promise {\n const result = await this.db\n .select()\n .from(streams)\n .where(eq(streams.channelId, channelId))\n .orderBy(desc(streams.startedAt))\n .limit(1);\n \n return result[0] ? DomainMapper.toDomainStream(result[0]) : undefined;\n }\n\n async create(id: string, channelId: string, category: string, title: string): Promise {\n await this.db.insert(streams).values({\n id,\n channelId,\n isLive: true,\n category,\n title,\n startedAt: new Date().toISOString(),\n titles: [title] as any,\n categories: [category] as any,\n });\n \n return id;\n }\n\n async update(id: string, data: { isLive?: boolean; category?: string; title?: string; endedAt?: string }): Promise {\n const result = await this.db\n .update(streams)\n .set(data)\n .where(eq(streams.id, id))\n .returning();\n \n if (!result[0]) {\n throw new Error('Stream not found');\n }\n \n return DomainMapper.toDomainStream(result[0]);\n }\n\n async findById(id: string): Promise {\n const result = await this.db\n .select()\n .from(streams)\n .where(eq(streams.id, id))\n .limit(1);\n \n return result[0] ? DomainMapper.toDomainStream(result[0]) : undefined;\n }\n}\n", "export * from './session.kv.repository';\n", "import type { KVNamespace } from '@cloudflare/workers-types';\nimport type { ISessionRepository } from '../interfaces/session.repository.interface';\n\n/**\n * Cloudflare KV-based session repository\n * Fast, distributed key-value storage perfect for sessions\n */\nexport class CloudflareKVSessionRepository implements ISessionRepository {\n constructor(private readonly kv: KVNamespace) {}\n\n async get(key: string): Promise {\n const value = await this.kv.get(key);\n return value ?? undefined;\n }\n\n async set(key: string, value: string, expiresAt?: number): Promise {\n const options: { expirationTtl?: number } = {};\n\n // Convert expiresAt (unix timestamp) to TTL in seconds\n if (expiresAt) {\n const ttl = Math.floor((expiresAt - Date.now()) / 1000);\n if (ttl > 0) {\n options.expirationTtl = ttl;\n }\n }\n\n await this.kv.put(key, value, options);\n }\n\n async delete(key: string): Promise {\n await this.kv.delete(key);\n }\n\n async cleanup(): Promise {\n // KV automatically cleans up expired keys, no manual cleanup needed\n return;\n }\n}\n", "import type { Env } from '../types/env';\nimport type { DrizzleD1Database } from 'drizzle-orm/d1';\nimport { TwitchService } from '../services/twitch.service';\nimport { TelegramService } from '../services/telegram.service';\nimport { I18nService } from '../services/i18n.service';\nimport { NotificationService } from '../services/notification.service';\nimport { CloudflareD1Connection } from '../db/connection';\nimport { DrizzleRepositoryFactory } from '../db/repository.factory';\nimport { createHmac } from 'node:crypto';\n\ninterface EventSubNotification {\n subscription: {\n id: string;\n type: string;\n version: string;\n status: string;\n cost: number;\n condition: Record;\n transport: {\n method: string;\n callback: string;\n };\n created_at: string;\n };\n event: Record;\n}\n\ninterface EventSubVerification {\n challenge: string;\n subscription: {\n id: string;\n type: string;\n version: string;\n status: string;\n cost: number;\n condition: Record;\n transport: {\n method: string;\n callback: string;\n };\n created_at: string;\n };\n}\n\nexport async function handleTwitchWebhook(\n request: Request,\n env: Env,\n db: DrizzleD1Database\n): Promise {\n try {\n // Verify the signature\n const messageId = request.headers.get('Twitch-Eventsub-Message-Id');\n const timestamp = request.headers.get('Twitch-Eventsub-Message-Timestamp');\n const signature = request.headers.get('Twitch-Eventsub-Message-Signature');\n const messageType = request.headers.get('Twitch-Eventsub-Message-Type');\n\n if (!messageId || !timestamp || !signature) {\n return new Response('Missing required headers', { status: 400 });\n }\n\n const body = await request.text();\n\n // Verify signature\n const hmac = createHmac('sha256', env.TWITCH_EVENTSUB_SECRET);\n hmac.update(messageId + timestamp + body);\n const expectedSignature = 'sha256=' + hmac.digest('hex');\n\n if (signature !== expectedSignature) {\n return new Response('Invalid signature', { status: 403 });\n }\n\n const payload = JSON.parse(body);\n\n // Handle verification challenge\n if (messageType === 'webhook_callback_verification') {\n const verification = payload as EventSubVerification;\n return new Response(verification.challenge, {\n status: 200,\n headers: { 'Content-Type': 'text/plain' },\n });\n }\n\n // Handle notification\n if (messageType === 'notification') {\n const notification = payload as EventSubNotification;\n\n // Initialize services\n const i18nService = new I18nService();\n const twitchService = new TwitchService(env);\n const telegramService = new TelegramService(env, i18nService);\n\n // Initialize repositories via factory\n const dbConnection = new CloudflareD1Connection(db);\n const repositoryFactory = new DrizzleRepositoryFactory(dbConnection);\n \n const chatRepo = repositoryFactory.createChatRepository();\n const channelRepo = repositoryFactory.createChannelRepository();\n const followRepo = repositoryFactory.createFollowRepository();\n const streamRepo = repositoryFactory.createStreamRepository();\n\n // Initialize notification service\n const notificationService = new NotificationService(\n env,\n db,\n telegramService,\n twitchService,\n i18nService,\n chatRepo,\n channelRepo,\n followRepo,\n streamRepo\n );\n\n // Handle different event types\n switch (notification.subscription.type) {\n case 'stream.online': {\n const event = notification.event;\n const stream = await twitchService.getStreamByUserId(event.broadcaster_user_id);\n if (stream) {\n await notificationService.handleStreamOnline({\n channelId: event.broadcaster_user_id,\n channelName: event.broadcaster_user_name,\n streamId: stream.id,\n category: stream.gameName,\n title: stream.title,\n thumbnailUrl: stream.thumbnailUrl,\n });\n }\n break;\n }\n\n case 'stream.offline': {\n const event = notification.event;\n await notificationService.handleStreamOffline({\n channelId: event.broadcaster_user_id,\n channelName: event.broadcaster_user_name,\n });\n break;\n }\n\n case 'channel.update': {\n const event = notification.event;\n const channel = await channelRepo.findByChannelId(event.broadcaster_user_id, 'twitch');\n if (!channel) break;\n\n const stream = await streamRepo.findLatestByChannelId(channel.id);\n if (!stream || !stream.isLive) break;\n\n // Check if category changed\n if (stream.category && event.category_name !== stream.category) {\n await notificationService.handleCategoryChange({\n channelId: event.broadcaster_user_id,\n channelName: event.broadcaster_user_name,\n oldCategory: stream.category,\n newCategory: event.category_name,\n });\n }\n\n // Check if title changed\n if (stream.title && event.title !== stream.title) {\n await notificationService.handleTitleChange({\n channelId: event.broadcaster_user_id,\n channelName: event.broadcaster_user_name,\n oldTitle: stream.title,\n newTitle: event.title,\n });\n }\n break;\n }\n }\n\n return new Response('OK', { status: 200 });\n }\n\n // Handle revocation\n if (messageType === 'revocation') {\n console.log('Subscription revoked:', payload);\n return new Response('OK', { status: 200 });\n }\n\n return new Response('Unknown message type', { status: 400 });\n } catch (error) {\n console.error('Error handling Twitch webhook:', error);\n return new Response('Internal Server Error', { status: 500 });\n }\n}\n", "import type { DrizzleD1Database } from 'drizzle-orm/d1';\nimport type { Env } from '../types/env';\nimport { TelegramService } from './telegram.service';\nimport { TwitchService } from './twitch.service';\nimport { I18nService, type SupportedLanguage } from './i18n.service';\nimport type {\n IChatRepository,\n IChannelRepository,\n IFollowRepository,\n IStreamRepository,\n} from '../db/repositories/interfaces';\n\nexport interface StreamOnlineEventData {\n channelId: string;\n channelName: string;\n streamId: string;\n category: string;\n title: string;\n thumbnailUrl: string;\n}\n\nexport interface StreamOfflineEventData {\n channelId: string;\n channelName: string;\n}\n\nexport interface StreamCategoryChangeEventData {\n channelId: string;\n channelName: string;\n oldCategory: string;\n newCategory: string;\n}\n\nexport interface StreamTitleChangeEventData {\n channelId: string;\n channelName: string;\n oldTitle: string;\n newTitle: string;\n}\n\nexport class NotificationService {\n constructor(\n private env: Env,\n private db: DrizzleD1Database,\n private telegramService: TelegramService,\n private twitchService: TwitchService,\n private i18nService: I18nService,\n private chatRepo: IChatRepository,\n private channelRepo: IChannelRepository,\n private followRepo: IFollowRepository,\n private streamRepo: IStreamRepository\n ) {}\n\n async handleStreamOnline(data: StreamOnlineEventData): Promise {\n // Get or create channel\n let channel = await this.channelRepo.findByChannelId(data.channelId, 'twitch');\n if (!channel) {\n channel = await this.channelRepo.create(data.channelId, 'twitch');\n }\n\n // Create stream record\n await this.streamRepo.create(\n data.streamId,\n channel.id,\n data.category,\n data.title\n );\n\n // Get all followers of this channel\n const follows = await this.followRepo.findByChannelId(channel.id);\n\n // Send notifications to all followers\n for (const follow of follows) {\n try {\n const chat = await this.chatRepo.findById(follow.chatId);\n if (!chat || !chat.settings) continue;\n\n await this.telegramService.sendStreamOnlineNotification({\n chatId: parseInt(chat.chatId),\n language: chat.settings.language as SupportedLanguage,\n channelName: data.channelName,\n channelUrl: `https://twitch.tv/${data.channelName}`,\n category: data.category,\n title: data.title,\n thumbnailUrl: data.thumbnailUrl,\n showImage: chat.settings.imageInNotification,\n });\n } catch (error) {\n console.error('Failed to send online notification:', error);\n }\n }\n }\n\n async handleStreamOffline(data: StreamOfflineEventData): Promise {\n const channel = await this.channelRepo.findByChannelId(data.channelId, 'twitch');\n if (!channel) return;\n\n // Get latest stream\n const stream = await this.streamRepo.findLatestByChannelId(channel.id);\n if (!stream || !stream.isLive) return;\n\n // Update stream as offline\n await this.streamRepo.update(stream.id, {\n isLive: false,\n endedAt: new Date().toISOString(),\n });\n\n // Get all followers\n const follows = await this.followRepo.findByChannelId(channel.id);\n\n // Send notifications to followers who want offline notifications\n for (const follow of follows) {\n try {\n const chat = await this.chatRepo.findById(follow.chatId);\n if (!chat || !chat.settings || !chat.settings.offlineNotification) continue;\n\n const duration = stream.startedAt\n ? Math.floor((Date.now() - new Date(stream.startedAt).getTime()) / 1000)\n : 0;\n const hours = Math.floor(duration / 3600);\n const minutes = Math.floor((duration % 3600) / 60);\n const seconds = duration % 60;\n const durationStr = `${hours}h ${minutes}m ${seconds}s`;\n\n await this.telegramService.sendStreamOfflineNotification({\n chatId: parseInt(chat.chatId),\n language: chat.settings.language as SupportedLanguage,\n channelName: data.channelName,\n channelUrl: `https://twitch.tv/${data.channelName}`,\n categories: stream.categories || [],\n duration: durationStr,\n });\n } catch (error) {\n console.error('Failed to send offline notification:', error);\n }\n }\n }\n\n async handleCategoryChange(data: StreamCategoryChangeEventData): Promise {\n const channel = await this.channelRepo.findByChannelId(data.channelId, 'twitch');\n if (!channel) return;\n\n const stream = await this.streamRepo.findLatestByChannelId(channel.id);\n if (!stream || !stream.isLive) return;\n\n // Update stream categories\n const categories = [...(stream.categories || []), data.newCategory];\n await this.streamRepo.update(stream.id, {\n category: data.newCategory,\n categories,\n });\n\n // Get all followers\n const follows = await this.followRepo.findByChannelId(channel.id);\n\n for (const follow of follows) {\n try {\n const chat = await this.chatRepo.findById(follow.chatId);\n if (!chat || !chat.settings || !chat.settings.gameChangeNotification) continue;\n\n await this.telegramService.sendCategoryChangeNotification({\n chatId: parseInt(chat.chatId),\n language: chat.settings.language as SupportedLanguage,\n channelName: data.channelName,\n channelUrl: `https://twitch.tv/${data.channelName}`,\n oldCategory: data.oldCategory,\n category: data.newCategory,\n });\n } catch (error) {\n console.error('Failed to send category change notification:', error);\n }\n }\n }\n\n async handleTitleChange(data: StreamTitleChangeEventData): Promise {\n const channel = await this.channelRepo.findByChannelId(data.channelId, 'twitch');\n if (!channel) return;\n\n const stream = await this.streamRepo.findLatestByChannelId(channel.id);\n if (!stream || !stream.isLive) return;\n\n // Update stream titles\n const titles = [...(stream.titles || []), data.newTitle];\n await this.streamRepo.update(stream.id, {\n title: data.newTitle,\n titles,\n });\n\n // Get all followers\n const follows = await this.followRepo.findByChannelId(channel.id);\n\n for (const follow of follows) {\n try {\n const chat = await this.chatRepo.findById(follow.chatId);\n if (!chat || !chat.settings || !chat.settings.titleChangeNotification) continue;\n\n await this.telegramService.sendTitleChangeNotification({\n chatId: parseInt(chat.chatId),\n language: chat.settings.language as SupportedLanguage,\n channelName: data.channelName,\n channelUrl: `https://twitch.tv/${data.channelName}`,\n oldTitle: data.oldTitle,\n title: data.newTitle,\n });\n } catch (error) {\n console.error('Failed to send title change notification:', error);\n }\n }\n }\n}\n", "import type { Middleware } from \"./common\";\n\nconst drainBody: Middleware = async (request, env, _ctx, middlewareCtx) => {\n\ttry {\n\t\treturn await middlewareCtx.next(request, env);\n\t} finally {\n\t\ttry {\n\t\t\tif (request.body !== null && !request.bodyUsed) {\n\t\t\t\tconst reader = request.body.getReader();\n\t\t\t\twhile (!(await reader.read()).done) {}\n\t\t\t}\n\t\t} catch (e) {\n\t\t\tconsole.error(\"Failed to drain the unused request body.\", e);\n\t\t}\n\t}\n};\n\nexport default drainBody;\n", "import type { Middleware } from \"./common\";\n\ninterface JsonError {\n\tmessage?: string;\n\tname?: string;\n\tstack?: string;\n\tcause?: JsonError;\n}\n\nfunction reduceError(e: any): JsonError {\n\treturn {\n\t\tname: e?.name,\n\t\tmessage: e?.message ?? String(e),\n\t\tstack: e?.stack,\n\t\tcause: e?.cause === undefined ? undefined : reduceError(e.cause),\n\t};\n}\n\n// See comment in `bundle.ts` for details on why this is needed\nconst jsonError: Middleware = async (request, env, _ctx, middlewareCtx) => {\n\ttry {\n\t\treturn await middlewareCtx.next(request, env);\n\t} catch (e: any) {\n\t\tconst error = reduceError(e);\n\t\treturn Response.json(error, {\n\t\t\tstatus: 500,\n\t\t\theaders: { \"MF-Experimental-Error-Stack\": \"true\" },\n\t\t});\n\t}\n};\n\nexport default jsonError;\n", "export type Awaitable = T | Promise;\n// TODO: allow dispatching more events?\nexport type Dispatcher = (\n\ttype: \"scheduled\",\n\tinit: { cron?: string }\n) => Awaitable;\n\nexport type IncomingRequest = Request<\n\tunknown,\n\tIncomingRequestCfProperties\n>;\n\nexport interface MiddlewareContext {\n\tdispatch: Dispatcher;\n\tnext(request: IncomingRequest, env: any): Awaitable;\n}\n\nexport type Middleware = (\n\trequest: IncomingRequest,\n\tenv: any,\n\tctx: ExecutionContext,\n\tmiddlewareCtx: MiddlewareContext\n) => Awaitable;\n\nconst __facade_middleware__: Middleware[] = [];\n\n// The register functions allow for the insertion of one or many middleware,\n// We register internal middleware first in the stack, but have no way of controlling\n// the order that addMiddleware is run in service workers so need an internal function.\nexport function __facade_register__(...args: (Middleware | Middleware[])[]) {\n\t__facade_middleware__.push(...args.flat());\n}\nexport function __facade_registerInternal__(\n\t...args: (Middleware | Middleware[])[]\n) {\n\t__facade_middleware__.unshift(...args.flat());\n}\n\nfunction __facade_invokeChain__(\n\trequest: IncomingRequest,\n\tenv: any,\n\tctx: ExecutionContext,\n\tdispatch: Dispatcher,\n\tmiddlewareChain: Middleware[]\n): Awaitable {\n\tconst [head, ...tail] = middlewareChain;\n\tconst middlewareCtx: MiddlewareContext = {\n\t\tdispatch,\n\t\tnext(newRequest, newEnv) {\n\t\t\treturn __facade_invokeChain__(newRequest, newEnv, ctx, dispatch, tail);\n\t\t},\n\t};\n\treturn head(request, env, ctx, middlewareCtx);\n}\n\nexport function __facade_invoke__(\n\trequest: IncomingRequest,\n\tenv: any,\n\tctx: ExecutionContext,\n\tdispatch: Dispatcher,\n\tfinalMiddleware: Middleware\n): Awaitable {\n\treturn __facade_invokeChain__(request, env, ctx, dispatch, [\n\t\t...__facade_middleware__,\n\t\tfinalMiddleware,\n\t]);\n}\n"], + "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuBO,SAAS,0BAA0B,MAAM;AAC/C,SAAO,IAAI,MAAM,WAAW,IAAI,0BAA0B;AAC3D;AAzBA;AAAA;AAAA;AAAA,IAAAA;AAuBgB;AAAA;AAAA;;;ACvBhB,IACM,aACA,iBACA,YAuBO,kBAyBA,iBAWA,oBAIA,2BAyBA,8BAaA,aA4FA,qBAmCA;AAvOb;AAAA;AAAA;AAAA,IAAAC;AAAA;AACA,IAAM,cAAc,WAAW,aAAa,cAAc,KAAK,IAAI;AACnE,IAAM,kBAAkB,WAAW,aAAa,MAAM,WAAW,YAAY,IAAI,KAAK,WAA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A,QACL,KAAK;AAAA,MACN;AAAA,IACD;AAAA,EACD;AACD;AAnDS;AAqDT,IAAI;AACJ,IAAI,OAAO,wCAAU,UAAU;AAC9B,kBAAgB,oBAAoB,mCAAK;AAC1C,WAAW,OAAO,wCAAU,YAAY;AACvC,kBAAgB,qBAAqB,mCAAK;AAC3C;AACA,IAAO,kCAAQ;", + "names": ["init_performance", "init_performance", "PerformanceMark", "init_performance", "init_performance", "init_performance", "init_performance", "init_performance", "self", "count", "init_performance", "original", "require_retry", "init_performance", "init_performance", "init_performance", "init_performance", "init_performance", "init_performance", "init_performance", "init_performance", "init_performance", "init_performance", "init_performance", "init_performance", "init_performance", "init_performance", "match", "str", "str", "raw", "text", "data", "init_performance", "str", "str2", "init", "data", "text", "init_performance", "init_performance", "m", "app", "init_performance", "init_performance", "init_performance", "match2", "init_performance", "init_performance", "m", "h", "m", "init_performance", "init_performance", "init_performance", "init", "init_performance", "init_performance", "init_performance", "Node", "_Node", "m", "Node", "Hono", "init_performance", "expanded", "s", "get", "t", "match", "emoji", "reaction", "Context", "text", "title", "m", "ok", "errorHandler", "str", "dir", "performance", "process", "debug", "data", "config", "options", "raw", "use", "setup", "text", "data", "s", "raw", "unauthorized", "ms", "init_performance", "init_performance", "init_performance", "config", "init_performance", "init_performance", "init_performance", "init_performance", "config", "init_performance", "init_performance", "init_performance", "init_performance", "init_performance", "init_performance", "init_performance", "init_performance", "config", "init_performance", "init_performance", "init_performance", "value", "startFrom", "config", "ref", "actions", "config", "init_performance", "sql", "init_performance", "init_performance", "version", "version", "otel", "rawTracer", "init_performance", "config", "param", "sql", "raw", "str", "placeholder", "name", "SQL", "name", "result", "init_performance", "or", "init_performance", "config", "or", "relations", "init_performance", "init_performance", "init_performance", "config", "init_performance", "init_performance", "init_performance", "init_performance", "init_performance", "init_performance", "init_performance", "ForeignKeyBuilder", "config", "ForeignKey", "init_performance", "uniqueKeyName", "UniqueConstraintBuilder", "UniqueConstraint", "UniqueOnConstraintBuilder", "uniqueKeyName", "config", "ref", "actions", "ForeignKeyBuilder", "uniqueKeyName", "config", "init_performance", "config", "init_performance", "config", "init_performance", "config", "init_performance", "init_performance", "config", "InlineForeignKeys", "name", "init_performance", "session", "init_performance", "init_performance", "init_performance", "init_performance", "init_performance", "init_performance", "init_performance", "config", "str", "w", "table", "select", "sql", "joinOn", "field", "session", "init_performance", "init_performance", "config", "session", "on", "self", "session", "config", "init_performance", "session", "on", "init_performance", "init_performance", "session", "config", "init_performance", "session", "self", "config", "init_performance", "init_performance", "sql", "data", "init_performance", "sql", "session", "builtQuery", "config", "config", "session", "init_performance", "init_performance", "init_performance", "init_performance", "init_performance", "text", "follows", "data", "init_performance", "text", "m", "init_performance", "init_performance", "follows", "uptime", "init_performance", "text", "init_performance", "text", "init_performance", "data", "init_performance", "init_performance", "s", "t", "m", "concat", "getPath", "data", "str", "copy", "count", "match", "noop", "instance", "exists", "init_performance", "init_performance", "init_performance", "init_performance", "d", "b", "desc", "d", "m", "import_detect_node", "init_performance", "init_performance", "import_detect_node", "init_performance", "init_performance", "LogLevel", "init_performance", "init_performance", "init_performance", "init_performance", "flatten", "_a", "init_performance", "init_performance", "_a", "init_performance", "init_performance", "import_detect_node", "init_performance", "_a", "_b", "_c", "BaseLogger", "_a", "_b", "colors", "_c", "BrowserLogger", "init_performance", "CustomLoggerWrapper", "_a", "_b", "init_performance", "_a", "_b", "str", "NodeLogger", "_c", "init_performance", "init_performance", "init_performance", "_a", "init_performance", "init_performance", "init_performance", "init_performance", "_a", "_b", "_c", "retry", "init_performance", "_a", "_b", "queue", "init_performance", "init_performance", "init_performance", "init_performance", "init_performance", "data", "init_performance", "init_performance", "init_performance", "init_performance", "init_performance", "CustomError", "CustomError", "init_performance", "init_performance", "HelixExtension", "init_performance", "CustomError", "init_performance", "init_performance", "init_performance", "CustomError", "text", "init_performance", "init_performance", "init_performance", "CustomError", "init_performance", "init_performance", "init_performance", "init_performance", "init_performance", "_a", "_b", "init_performance", "init_performance", "init_performance", "init_performance", "EventEmitter", "init_performance", "init_performance", "init_performance", "init_performance", "CustomError", "init_performance", "init_performance", "TokenInfo", "data", "data", "init_performance", "promise", "resolve", "reject", "init_performance", "AppTokenAuthProvider", "init_performance", "init_performance", "count", "init_performance", "init_performance", "init_performance", "HelixBitsLeaderboardEntry", "data", "HelixBitsLeaderboard", "data", "init_performance", "HelixCheermoteList", "data", "HelixBitsApi", "init_performance", "init_performance", "data", "init_performance", "init_performance", "HelixUserRelation", "data", "init_performance", "data", "init_performance", "HelixPaginatedRequest", "data", "init_performance", "HelixPaginatedRequestWithTotal", "data", "init_performance", "data", "init_performance", "init_performance", "HelixChannel", "data", "init_performance", "HelixChannelEditor", "data", "init_performance", "HelixChannelFollower", "data", "init_performance", "HelixFollowedChannel", "data", "init_performance", "HelixAdSchedule", "init_performance", "HelixSnoozeNextAdResult", "HelixChannelApi", "data", "init_performance", "init_performance", "data", "init_performance", "HelixCustomReward", "data", "init_performance", "HelixCustomRewardRedemption", "data", "HelixChannelPointsApi", "data", "init_performance", "init_performance", "init_performance", "HelixCharityCampaignAmount", "HelixCharityCampaign", "data", "init_performance", "HelixCharityCampaignDonation", "data", "HelixCharityApi", "init_performance", "init_performance", "CustomError", "init_performance", "init_performance", "init_performance", "init_performance", "init_performance", "HelixEmote", "HelixChannelEmote", "data", "init_performance", "init_performance", "HelixChatBadgeVersion", "HelixChatBadgeSet", "data", "init_performance", "HelixChatChatter", "data", "init_performance", "HelixChatSettings", "init_performance", "HelixEmoteFromSet", "data", "init_performance", "HelixPrivilegedChatSettings", "init_performance", "HelixSentChatMessage", "init_performance", "init_performance", "HelixSharedChatSessionParticipant", "data", "HelixSharedChatSession", "data", "init_performance", "HelixUserEmote", "data", "HelixChatApi", "data", "init_performance", "init_performance", "title", "init_performance", "HelixClip", "data", "HelixClipApi", "data", "init_performance", "init_performance", "HelixContentClassificationLabelApi", "data", "init_performance", "init_performance", "init_performance", "HelixDropsEntitlement", "data", "HelixEntitlementApi", "data", "init_performance", "init_performance", "init_performance", "HelixEventSubSubscription", "data", "init_performance", "HelixPaginatedEventSubSubscriptionsRequest", "data", "init_performance", "HelixEventSubConduit", "data", "init_performance", "HelixEventSubConduitShard", "HelixEventSubApi", "version", "data", "init_performance", "init_performance", "version", "data", "init_performance", "HelixChannelReference", "data", "init_performance", "HelixExtensionBitsProduct", "init_performance", "HelixExtensionTransaction", "data", "HelixExtensionsApi", "version", "data", "init_performance", "init_performance", "HelixGame", "data", "HelixGameApi", "data", "init_performance", "init_performance", "HelixGoal", "data", "HelixGoalApi", "data", "init_performance", "init_performance", "init_performance", "init_performance", "HelixHypeTrainContribution", "data", "HelixHypeTrain", "data", "init_performance", "HelixHypeTrainAllTimeHigh", "HelixHypeTrainStatus", "data", "init_performance", "init_performance", "data", "init_performance", "HelixAutoModSettings", "init_performance", "HelixAutoModStatus", "init_performance", "init_performance", "HelixBanUser", "data", "HelixBan", "data", "init_performance", "HelixBlockedTerm", "init_performance", "HelixModeratedChannel", "data", "init_performance", "HelixModerator", "data", "init_performance", "HelixShieldModeStatus", "data", "init_performance", "HelixUnbanRequest", "data", "init_performance", "HelixWarning", "data", "HelixModerationApi", "data", "text", "init_performance", "init_performance", "data", "title", "init_performance", "init_performance", "HelixPollChoice", "HelixPoll", "data", "HelixPollApi", "data", "init_performance", "init_performance", "data", "title", "init_performance", "init_performance", "init_performance", "HelixPredictor", "data", "HelixPredictionOutcome", "data", "HelixPrediction", "data", "HelixPredictionApi", "data", "init_performance", "init_performance", "init_performance", "HelixRaid", "HelixRaidApi", "init_performance", "init_performance", "data", "init_performance", "init_performance", "HelixScheduleSegment", "data", "HelixPaginatedScheduleSegmentRequest", "data", "init_performance", "HelixSchedule", "data", "data", "init_performance", "init_performance", "init_performance", "HelixChannelSearchResult", "data", "HelixSearchApi", "data", "init_performance", "init_performance", "CustomError", "init_performance", "init_performance", "HelixStream", "data", "init_performance", "HelixStreamMarker", "data", "init_performance", "HelixStreamMarkerWithVideo", "data", "HelixStreamApi", "data", "flatten", "init_performance", "init_performance", "init_performance", "init_performance", "init_performance", "HelixUserSubscription", "data", "HelixSubscription", "HelixPaginatedSubscriptionsRequest", "data", "HelixSubscriptionApi", "data", "init_performance", "init_performance", "HelixTeam", "data", "init_performance", "HelixTeamWithUsers", "data", "HelixTeamApi", "data", "init_performance", "init_performance", "init_performance", "init_performance", "init_performance", "HelixInstalledExtension", "data", "HelixInstalledExtensionList", "data", "init_performance", "HelixUserExtension", "init_performance", "init_performance", "HelixUser", "data", "HelixPrivilegedUser", "init_performance", "HelixUserBlock", "data", "HelixUserApi", "data", "init_performance", "init_performance", "HelixVideo", "data", "HelixVideoApi", "data", "init_performance", "init_performance", "HelixWhisperApi", "init_performance", "BaseApiClient", "EventEmitter", "config", "data", "accessToken", "init_performance", "NoContextApiClient", "init_performance", "UserContextApiClient", "config", "ApiClient", "config", "ApiClient", "init_performance", "init_performance", "text", "init_performance", "init_performance", "init_performance", "init_performance", "init_performance", "randomUUID", "init_performance", "init_performance", "init_performance", "data", "randomUUID", "init_performance", "randomUUID", "randomUUID", "data", "init_performance", "randomUUID", "randomUUID", "init_performance", "title", "data", "init_performance", "init_performance", "init_performance", "init_performance", "data", "follows", "Hono", "init_performance", "init_performance", "init_performance", "init"] +} diff --git a/MIGRATION_PLAN.md b/MIGRATION_PLAN.md new file mode 100644 index 00000000..a36ef2d1 --- /dev/null +++ b/MIGRATION_PLAN.md @@ -0,0 +1,315 @@ +# План миграции на Cloudflare Workers + +## Обзор проекта + +**Текущий стек:** +- Go 1.19+ +- PostgreSQL + Ent ORM +- Polling Telegram Bot +- Standalone приложение с собственным воркером проверки стримов + +**Целевой стек:** +- TypeScript/JavaScript +- Cloudflare Workers + D1 (SQLite) +- Grammy Bot (Telegram) +- Drizzle ORM с паттерном репозиториев +- pnpm как пакетный менеджер + +## Существующие фичи для сохранения + +### 1. База данных (5 таблиц) + +#### Chat +- `id` (UUID) +- `chat_id` (string) - ID чата в Telegram +- `service` (enum: "telegram") +- Уникальный индекс: `chat_id + service` + +#### ChatSettings +- `id` (UUID) +- `chat_id` (UUID FK -> Chat) +- `game_change_notification` (boolean, default: true) +- `title_change_notification` (boolean, default: false) +- `game_and_title_change_notification` (boolean, default: false) +- `offline_notification` (boolean, default: true) +- `image_in_notification` (boolean, default: true) +- `chat_language` (enum: "ru", "en", "uk", default: "en") + +#### Channel +- `id` (UUID) +- `channel_id` (string) - ID канала на Twitch +- `service` (enum: "twitch") +- `is_live` (boolean, default: false) +- `title` (string, nullable) +- `category` (string, nullable) +- `updated_at` (timestamp) +- Уникальный индекс: `channel_id + service` + +#### Follow +- `id` (UUID) +- `channel_id` (UUID FK -> Channel) +- `chat_id` (UUID FK -> Chat) +- Уникальный индекс: `channel_id + chat_id` + +#### Stream +- `id` (string, unique) - ID стрима от Twitch +- `channel_id` (UUID FK -> Channel) +- `titles` (string[], default: []) +- `categories` (string[], default: []) +- `started_at` (timestamp) +- `updated_at` (timestamp) +- `ended_at` (timestamp, nullable) + +### 2. Telegram команды + +#### Пользовательские команды: +- `/start` (aliases: /help, /info, /settings) - главное меню с настройками +- `/follow ` - подписка на Twitch канал +- `/follows` (alias: /unfollow) - список подписок с возможностью отписки (пагинация) +- `/live` - список онлайн стримов из подписок + +#### Административные команды: +- `/broadcast ` - массовая рассылка +- `/change_channel_id ` - изменение ID канала + +#### Интерактивные элементы: +- Callback buttons для настроек (в /start) +- Callback buttons для отписки (в /follows) +- Кнопки пагинации для списка подписок +- Выбор языка через inline-кнопки + +### 3. Система уведомлений + +Проверка стримов каждую минуту (в dev - 10 секунд) с уведомлениями: + +#### При запуске стрима: +- Сообщение с названием, категорией, стримером +- Превью (thumbnail) если включено +- Кнопка отписки + +#### При завершении стрима: +- Сообщение о завершении +- Список категорий за стрим +- Длительность стрима +- Кнопка отписки + +#### Изменения во время стрима: +- Смена категории (если включено) +- Смена названия (если включено) +- Смена категории И названия одновременно (если включено) + +### 4. Интернационализация (i18n) + +Поддержка языков: +- Русский (ru) +- Английский (en) +- Украинский (uk) + +Переводы хранятся в директории `locales/` + +### 5. Twitch API интеграция + +- Получение информации о каналах +- Получение информации о стримах +- Батчинг запросов (chunked requests) +- OAuth авторизация с автоматическим обновлением токена + +### 6. Конфигурация + +Переменные окружения: +- `TWITCH_CLIENTID` - ID приложения Twitch +- `TWITCH_CLIENTSECRET` - Secret приложения Twitch +- `TELEGRAM_TOKEN` - токен Telegram бота +- `TELEGRAM_BOT_ADMINS` - список ID администраторов (через запятую) +- `DATABASE_URL` - URL базы данных (старый PostgreSQL) +- `SENTRY_DSN` - (опционально) для мониторинга ошибок + +## Архитектура Cloudflare Workers решения + +### Workers + +#### 1. **bot-worker** (основной) +- Обработка Telegram Webhook +- Обработка всех команд +- Grammy bot + conversations для multi-step команд +- Использует KV для хранения session данных + +#### 2. **streams-checker-worker** (Cron Worker) +- Запускается каждую минуту (Cron Trigger) +- Проверяет статус стримов через Twitch API +- Отправляет уведомления через Telegram API +- Использует D1 для чтения/записи данных + +### Cloudflare сервисы + +- **D1** - SQLite база данных для всех таблиц +- **KV** (опционально) - для session storage Grammy +- **Cron Triggers** - для периодической проверки стримов +- **Workers Analytics** (опционально) - для мониторинга + +## Структура проекта + +``` +twitch-notifier/ +├── src/ +│ ├── bot/ # Telegram bot +│ │ ├── index.ts # Entry point для bot-worker +│ │ ├── bot.ts # Grammy bot инициализация +│ │ ├── commands/ # Команды +│ │ │ ├── start.ts +│ │ │ ├── follow.ts +│ │ │ ├── follows.ts +│ │ │ ├── live.ts +│ │ │ ├── broadcast.ts +│ │ │ └── change-channel-id.ts +│ │ ├── keyboards/ # Inline клавиатуры +│ │ │ ├── settings.ts +│ │ │ ├── language.ts +│ │ │ └── follows.ts +│ │ └── middlewares/ # Миддлвары +│ │ ├── logger.ts +│ │ ├── admin.ts +│ │ └── chat.ts +│ ├── checker/ # Streams checker +│ │ ├── index.ts # Entry point для checker-worker +│ │ └── checker.ts # Логика проверки стримов +│ ├── db/ # База данных +│ │ ├── schema.ts # Drizzle схемы +│ │ ├── migrations/ # SQL миграции +│ │ └── repositories/ # Паттерн репозиториев +│ │ ├── chat.repository.ts +│ │ ├── channel.repository.ts +│ │ ├── follow.repository.ts +│ │ └── stream.repository.ts +│ ├── services/ # Сервисы +│ │ ├── twitch.service.ts # Twitch API клиент +│ │ ├── telegram.service.ts # Telegram message sender +│ │ └── i18n.service.ts # Интернационализация +│ ├── types/ # TypeScript типы +│ │ ├── env.ts +│ │ └── index.ts +│ └── utils/ # Утилиты +│ ├── thumbnail.ts +│ └── helpers.ts +├── locales/ # Переводы (скопировать из Go проекта) +│ ├── en.json +│ ├── ru.json +│ └── uk.json +├── migrations/ # Скрипты миграции +│ └── migrate-users.ts # Скрипт миграции из PostgreSQL в D1 +├── drizzle.config.ts # Конфигурация Drizzle +├── wrangler.toml # Конфигурация Cloudflare Workers +├── package.json +├── tsconfig.json +└── README.md +``` + +## План реализации + +### Этап 1: Настройка проекта ✓ +1. Инициализация проекта с pnpm +2. Установка зависимостей: + - `wrangler` - Cloudflare CLI + - `grammy` + `@grammyjs/conversations` - Telegram bot + - `drizzle-orm` + `drizzle-kit` - ORM + - Другие зависимости +3. Создание структуры директорий +4. Настройка TypeScript +5. Настройка wrangler.toml для обоих workers + +### Этап 2: База данных ✓ +1. Создание Drizzle схем на основе Ent схем +2. Имплементация паттерна репозиториев +3. Создание D1 базы через Wrangler +4. Генерация и применение миграций + +### Этап 3: Сервисы ✓ +1. Twitch API клиент с OAuth +2. Telegram message sender +3. i18n сервис (адаптация с Go проекта) +4. Thumbnail builder + +### Этап 4: Telegram Bot ✓ +1. Настройка Grammy bot +2. Имплементация всех команд +3. Создание inline клавиатур +4. Настройка миддлваров (логгирование, admin check, chat persistence) +5. Настройка conversations для multi-step команд (/follow) + +### Этап 5: Streams Checker Worker ✓ +1. Имплементация логики проверки стримов +2. Отправка уведомлений +3. Настройка Cron Trigger + +### Этап 6: Деплой и тестирование ✓ +1. Деплой bot-worker +2. Деплой streams-checker-worker +3. Настройка Telegram Webhook +4. Тестирование всех команд +5. Тестирование уведомлений + +### Этап 7: Миграция данных ✓ +1. Создание скрипта миграции из PostgreSQL в D1 +2. Тестовая миграция +3. Продакшн миграция + +## Скрипт миграции данных + +Создать отдельный скрипт `migrations/migrate-users.ts` который: +1. Подключается к старой PostgreSQL базе +2. Читает все данные из таблиц (Chat, ChatSettings, Channel, Follow, Stream) +3. Трансформирует данные если нужно +4. Записывает в D1 через Wrangler API или D1 HTTP API + +Особенности миграции: +- UUID в PostgreSQL -> сохраняются как есть (D1 поддерживает текстовые UUID) +- Массивы (titles, categories) -> JSON в SQLite +- Timestamps -> ISO 8601 строки в SQLite +- Enum values -> остаются как есть + +## Отличия от Go версии + +### Архитектурные: +- **Polling -> Webhook**: Cloudflare Workers работает по модели request/response, используем Telegram Webhook вместо Long Polling +- **Отдельный воркер для проверки стримов**: вместо горутины - отдельный Worker с Cron Trigger +- **Serverless**: нет постоянно запущенного процесса, оплата за выполнение +- **SQLite вместо PostgreSQL**: D1 - управляемая SQLite база + +### Технические: +- **Grammy вместо go-tg**: официальная TypeScript библиотека для Telegram +- **Drizzle вместо Ent**: type-safe ORM для TypeScript +- **Паттерн репозиториев**: изоляция логики БД для простой замены ORM в будущем + +## Следующие шаги + +После прочтения этого плана: + +1. Убедитесь что у вас есть: + - Аккаунт Cloudflare (Workers Paid plan для Cron Triggers) + - Доступ к текущей PostgreSQL базе для миграции + +2. Дайте подтверждение для начала реализации: + ``` + Да, начинаем! Начни с Этапа 1. + ``` + +3. Я буду реализовывать каждый этап последовательно, показывая прогресс + +## Важные замечания + +- Cloudflare Workers Free tier имеет лимиты (100k запросов/день) +- Cron Triggers требуют Workers Paid plan ($5/месяц) +- D1 пока в beta, но стабильна для продакшн использования +- Webhook требует HTTPS домен (можно использовать workers.dev) +- Grammy conversations требуют хранилище для session (используем KV или D1) + +## Вопросы для уточнения + +1. Есть ли у вас уже Cloudflare аккаунт? +2. Сколько пользователей у текущего бота? (для оценки нагрузки) +3. Нужна ли интеграция с Sentry для мониторинга? +4. Хотите ли сохранить историю стримов (таблица Stream) или только активные? + +--- + +**Готовы начать миграцию?** Дайте команду и я начну с Этапа 1! diff --git a/README.md b/README.md index ee1c2068..9b866c7f 100644 --- a/README.md +++ b/README.md @@ -1,66 +1,187 @@ -# Twitch Notifier +# Twitch Notifier Bot -![GitHub go.mod Go version](https://img.shields.io/github/go-mod/go-version/satont/twitch-notifier) -[![Coverage Status](https://coveralls.io/repos/github/Satont/twitch-notifier/badge.svg)](https://coveralls.io/github/Satont/twitch-notifier) +Telegram бот для уведомлений о стримах Twitch с использованием Cloudflare Workers, D1 и KV. -Bot for sending twitch streams notifications in telegram. +## Архитектура -# Development +### Serverless-Agnostic Design +Проект построен с учетом возможности запуска в разных окружениях: +- **Cloudflare Workers** (основная платформа) +- **Docker** (для локальной разработки) +- Другие serverless платформы (AWS Lambda, Vercel, etc.) -Download dependencies - -```bash -go mod download +### Repository Pattern +``` +src/db/ +├── connection.ts # IDatabaseConnection интерфейс +├── repository.factory.ts # Factory для создания репозиториев +├── repositories/ +│ ├── interfaces/ # Интерфейсы репозиториев +│ ├── drizzle/ # Реализации для Drizzle ORM (D1, PostgreSQL) +│ └── cloudflare-kv/ # Реализации для Cloudflare KV ``` -### Requirements +### Технологический стек +- **Runtime**: Cloudflare Workers (Node.js compatible) +- **Database**: Cloudflare D1 (SQLite) +- **Cache/Sessions**: Cloudflare KV +- **ORM**: Drizzle ORM +- **Bot Framework**: Grammy +- **HTTP Framework**: Hono +- **Twitch API**: Twurple -- Golang `1.19+` +## Команды бота -### Generate +### Пользовательские команды: +- `/start`, `/help`, `/info`, `/settings` - Меню настроек +- `/follow ` - Подписаться на канал Twitch +- `/follows`, `/unfollow` - Управление подписками +- `/live` - Показать онлайн стримы -After clone/on first setup/on schema change - you should run +### Админские команды: +- `/broadcast ` - Рассылка всем пользователям +- `/change_channel_id ` - Обновить Twitch ID канала +## Установка и деплой + +### 1. Установка зависимостей ```bash -make generate +bun install ``` -### Testing +### 2. Создание Cloudflare D1 базы данных +```bash +wrangler d1 create twitch-notifier-db +``` + +Скопируйте `database_id` из вывода команды и вставьте в `wrangler.toml`: +```toml +[[d1_databases]] +binding = "DB" +database_name = "twitch-notifier-db" +database_id = "YOUR_DATABASE_ID_HERE" +``` +### 3. Создание Cloudflare KV namespace для сессий ```bash -make tests +wrangler kv:namespace create SESSIONS_KV ``` -### Running +Скопируйте `id` из вывода команды и вставьте в `wrangler.toml`: +```toml +[[kv_namespaces]] +binding = "SESSIONS_KV" +id = "YOUR_KV_ID_HERE" +``` +### 4. Применение миграций ```bash -docker compose -f docker-compose.dev.yml up -d -make dev +wrangler d1 execute twitch-notifier-db --file=./drizzle/0000_init.sql ``` -## Database schemas and migrations +### 5. Настройка переменных окружения -### Writing schemas +**Через Cloudflare Dashboard** или с помощью `wrangler secret put`: -All schemas located in `./ent/schema` directory, but also we are using internal structures. Internal structures located in `internal/db/db_models`. So you should change both of them. +```bash +wrangler secret put TELEGRAM_TOKEN +wrangler secret put BASE_URL # URL вашего воркера, например: https://twitch-notifier.yourname.workers.dev +``` + +Остальные переменные можно задать в `wrangler.toml`: +```toml +[vars] +TWITCH_CLIENT_ID = "your_client_id" +TWITCH_CLIENT_SECRET = "your_client_secret" +TELEGRAM_BOT_ADMINS = "123456789,987654321" # Telegram user IDs через запятую +TWITCH_EVENTSUB_SECRET = "your_eventsub_secret" +``` -After changing any schema in `/ent/schema` folder, you should regenerate data via `make generate` +### 6. Деплой +```bash +bun run deploy +``` -### Migrations +### 7. Настройка Telegram webhook +После деплоя настройте webhook для бота: +```bash +curl -X POST "https://api.telegram.org/bot/setWebhook" \ + -H "Content-Type: application/json" \ + -d '{"url":"https://your-worker.workers.dev/telegram-webhook"}' +``` -#### Requirements +### 8. Настройка Twitch EventSub +Webhook для Twitch EventSub настроится автоматически при подписке на каналы через команду `/follow`. -- [atlasgo cli](https://atlasgo.io/getting-started#installation) -- Docker +URL для EventSub: `https://your-worker.workers.dev/twitch-webhook` -### Create +## Разработка +### Локальный запуск ```bash -make migrate-create somecoolname +bun run dev ``` -### Apply +### Генерация миграций +```bash +bun drizzle-kit generate +``` + +### Применение миграций локально +```bash +bun drizzle-kit migrate +``` +### Проверка типов ```bash -make migrate-apply +bun run typecheck +``` + +## Структура проекта + ``` +src/ +├── bot/ +│ ├── commands/ # Команды через Composer +│ ├── helpers.ts # Вспомогательные функции +│ ├── storage.ts # Storage adapter для Grammy +│ └── types.ts # Типы контекста +├── db/ +│ ├── connection.ts # Абстракция подключения к БД +│ ├── schema.ts # Drizzle схема +│ ├── repository.factory.ts +│ └── repositories/ +│ ├── interfaces/ # Интерфейсы репозиториев +│ ├── drizzle/ # Реализации для D1 +│ └── cloudflare-kv/ # Реализации для KV +├── domain/ +│ ├── models.ts # Доменные модели +│ └── mapper.ts # Маппер DB → Domain +├── services/ # Сервисы (Twitch, Telegram, etc.) +├── webhooks/ # Обработчики webhook'ов +└── index.ts # Hono приложение +``` + +## Особенности реализации + +### Персистентные сессии через Cloudflare KV +Сессии Grammy хранятся в Cloudflare KV с автоматическим TTL. Это решает проблему сброса сессий в serverless окружении. KV обеспечивает: +- Низкую латентность (читается с ближайшего edge) +- Автоматическое истечение ключей +- Глобальное распределение + +### EventSub вместо polling +Используются Twitch EventSub webhooks для получения событий в реальном времени: +- `stream.online` - стример начал трансляцию +- `stream.offline` - стример закончил трансляцию +- `channel.update` - изменились название или категория + +### Domain-Driven Design +Разделение между DB schema и domain models для чистой архитектуры. + +### Factory Pattern +Единая точка создания репозиториев для простой замены реализаций. + +## Лицензия + +MIT diff --git a/bun.lock b/bun.lock new file mode 100644 index 00000000..76ef1789 --- /dev/null +++ b/bun.lock @@ -0,0 +1,435 @@ +{ + "lockfileVersion": 1, + "configVersion": 1, + "workspaces": { + "": { + "name": "twitch-notifier", + "dependencies": { + "@grammyjs/conversations": "2.1.1", + "@grammyjs/i18n": "1.1.2", + "@twurple/api": "8.0.3", + "@twurple/auth": "8.0.3", + "@twurple/eventsub-http": "8.0.3", + "drizzle-orm": "0.45.1", + "grammy": "1.41.1", + "hono": "^4.7.11", + }, + "devDependencies": { + "@cloudflare/workers-types": "4.20260307.1", + "@types/node": "^22.10.6", + "drizzle-kit": "0.31.9", + "typescript": "^5.7.3", + "wrangler": "4.71.0", + }, + }, + }, + "packages": { + "@cloudflare/kv-asset-handler": ["@cloudflare/kv-asset-handler@0.4.2", "", {}, "sha512-SIOD2DxrRRwQ+jgzlXCqoEFiKOFqaPjhnNTGKXSRLvp1HiOvapLaFG2kEr9dYQTYe8rKrd9uvDUzmAITeNyaHQ=="], + + "@cloudflare/unenv-preset": ["@cloudflare/unenv-preset@2.15.0", "", { "peerDependencies": { "unenv": "2.0.0-rc.24", "workerd": "1.20260301.1 || ~1.20260302.1 || ~1.20260303.1 || ~1.20260304.1 || >1.20260305.0 <2.0.0-0" }, "optionalPeers": ["workerd"] }, "sha512-EGYmJaGZKWl+X8tXxcnx4v2bOZSjQeNI5dWFeXivgX9+YCT69AkzHHwlNbVpqtEUTbew8eQurpyOpeN8fg00nw=="], + + "@cloudflare/workerd-darwin-64": ["@cloudflare/workerd-darwin-64@1.20260301.1", "", { "os": "darwin", "cpu": "x64" }, "sha512-+kJvwociLrvy1JV9BAvoSVsMEIYD982CpFmo/yMEvBwxDIjltYsLTE8DLi0mCkGsQ8Ygidv2fD9wavzXeiY7OQ=="], + + "@cloudflare/workerd-darwin-arm64": ["@cloudflare/workerd-darwin-arm64@1.20260301.1", "", { "os": "darwin", "cpu": "arm64" }, "sha512-PPIetY3e67YBr9O4UhILK8nbm5TqUDl14qx4rwFNrRSBOvlzuczzbd4BqgpAtbGVFxKp1PWpjAnBvGU/OI/tLQ=="], + + "@cloudflare/workerd-linux-64": ["@cloudflare/workerd-linux-64@1.20260301.1", "", { "os": "linux", "cpu": "x64" }, "sha512-Gu5vaVTZuYl3cHa+u5CDzSVDBvSkfNyuAHi6Mdfut7TTUdcb3V5CIcR/mXRSyMXzEy9YxEWIfdKMxOMBjupvYQ=="], + + "@cloudflare/workerd-linux-arm64": ["@cloudflare/workerd-linux-arm64@1.20260301.1", "", { "os": "linux", "cpu": "arm64" }, "sha512-igL1pkyCXW6GiGpjdOAvqMi87UW0LMc/+yIQe/CSzuZJm5GzXoAMrwVTkCFnikk6JVGELrM5x0tGYlxa0sk5Iw=="], + + "@cloudflare/workerd-windows-64": ["@cloudflare/workerd-windows-64@1.20260301.1", "", { "os": "win32", "cpu": "x64" }, "sha512-Q0wMJ4kcujXILwQKQFc1jaYamVsNvjuECzvRrTI8OxGFMx2yq9aOsswViE4X1gaS2YQQ5u0JGwuGi5WdT1Lt7A=="], + + "@cloudflare/workers-types": ["@cloudflare/workers-types@4.20260307.1", "", {}, "sha512-0PvWLVVD6Q64V/XhollYtc8H35Vxm2rZi8bkZbEr3lK+mNgd2FBBVhlZ6A3saAUq3giRF4US/UfU/3a8i1PEcg=="], + + "@cspotcode/source-map-support": ["@cspotcode/source-map-support@0.8.1", "", { "dependencies": { "@jridgewell/trace-mapping": "0.3.9" } }, "sha512-IchNf6dN4tHoMFIn/7OE8LWZ19Y6q/67Bmf6vnGREv8RSbBVb9LPJxEcnwrcwX6ixSvaiGoomAUvu4YSxXrVgw=="], + + "@d-fischer/cache-decorators": ["@d-fischer/cache-decorators@4.0.1", "", { "dependencies": { "@d-fischer/shared-utils": "^3.6.3", "tslib": "^2.6.2" } }, "sha512-HNYLBLWs/t28GFZZeqdIBqq8f37mqDIFO6xNPof94VjpKvuP6ROqCZGafx88dk5zZUlBfViV9jD8iNNlXfc4CA=="], + + "@d-fischer/detect-node": ["@d-fischer/detect-node@3.0.1", "", {}, "sha512-0Rf3XwTzuTh8+oPZW9SfxTIiL+26RRJ0BRPwj5oVjZFyFKmsj9RGfN2zuTRjOuA3FCK/jYm06HOhwNK+8Pfv8w=="], + + "@d-fischer/logger": ["@d-fischer/logger@4.2.4", "", { "dependencies": { "@d-fischer/detect-node": "^3.0.1", "@d-fischer/shared-utils": "^3.6.1", "tslib": "^2.5.0" } }, "sha512-TFMZ/SVW8xyQtyJw9Rcuci4betSKy0qbQn2B5+1+72vVXeO8Qb1pYvuwF5qr0vDGundmSWq7W8r19nVPnXXSvA=="], + + "@d-fischer/rate-limiter": ["@d-fischer/rate-limiter@1.1.0", "", { "dependencies": { "@d-fischer/logger": "^4.2.3", "@d-fischer/shared-utils": "^3.6.3", "tslib": "^2.6.2" } }, "sha512-O5HgACwApyCZhp4JTEBEtbv/W3eAwEkrARFvgWnEsDmXgCMWjIHwohWoHre5BW6IYXFSHBGsuZB/EvNL3942kQ=="], + + "@d-fischer/shared-utils": ["@d-fischer/shared-utils@3.6.4", "", { "dependencies": { "tslib": "^2.4.1" } }, "sha512-BPkVLHfn2Lbyo/ENDBwtEB8JVQ+9OzkjJhUunLaxkw4k59YFlQxUUwlDBejVSFcpQT0t+D3CQlX+ySZnQj0wxw=="], + + "@d-fischer/typed-event-emitter": ["@d-fischer/typed-event-emitter@3.3.3", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-OvSEOa8icfdWDqcRtjSEZtgJTFOFNgTjje7zaL0+nAtu2/kZtRCSK5wUMrI/aXtCH8o0Qz2vA8UqkhWUTARFQQ=="], + + "@deno/shim-deno": ["@deno/shim-deno@0.18.2", "", { "dependencies": { "@deno/shim-deno-test": "^0.5.0", "which": "^4.0.0" } }, "sha512-oQ0CVmOio63wlhwQF75zA4ioolPvOwAoK0yuzcS5bDC1JUvH3y1GS8xPh8EOpcoDQRU4FTG8OQfxhpR+c6DrzA=="], + + "@deno/shim-deno-test": ["@deno/shim-deno-test@0.5.0", "", {}, "sha512-4nMhecpGlPi0cSzT67L+Tm+GOJqvuk8gqHBziqcUQOarnuIax1z96/gJHCSIz2Z0zhxE6Rzwb3IZXPtFh51j+w=="], + + "@drizzle-team/brocli": ["@drizzle-team/brocli@0.10.2", "", {}, "sha512-z33Il7l5dKjUgGULTqBsQBQwckHh5AbIuxhdsIxDDiZAzBOrZO6q9ogcWC65kU382AfynTfgNumVcNIjuIua6w=="], + + "@emnapi/runtime": ["@emnapi/runtime@1.8.1", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-mehfKSMWjjNol8659Z8KxEMrdSJDDot5SXMq00dM8BN4o+CLNXQ0xH2V7EchNHV4RmbZLmmPdEaXZc5H2FXmDg=="], + + "@esbuild-kit/core-utils": ["@esbuild-kit/core-utils@3.3.2", "", { "dependencies": { "esbuild": "~0.18.20", "source-map-support": "^0.5.21" } }, "sha512-sPRAnw9CdSsRmEtnsl2WXWdyquogVpB3yZ3dgwJfe8zrOzTsV7cJvmwrKVa+0ma5BoiGJ+BoqkMvawbayKUsqQ=="], + + "@esbuild-kit/esm-loader": ["@esbuild-kit/esm-loader@2.6.5", "", { "dependencies": { "@esbuild-kit/core-utils": "^3.3.2", "get-tsconfig": "^4.7.0" } }, "sha512-FxEMIkJKnodyA1OaCUoEvbYRkoZlLZ4d/eXFu9Fh8CbBBgP5EmZxrfTRyN0qpXZ4vOvqnE5YdRdcrmUUXuU+dA=="], + + "@esbuild/aix-ppc64": ["@esbuild/aix-ppc64@0.25.12", "", { "os": "aix", "cpu": "ppc64" }, "sha512-Hhmwd6CInZ3dwpuGTF8fJG6yoWmsToE+vYgD4nytZVxcu1ulHpUQRAB1UJ8+N1Am3Mz4+xOByoQoSZf4D+CpkA=="], + + "@esbuild/android-arm": ["@esbuild/android-arm@0.25.12", "", { "os": "android", "cpu": "arm" }, "sha512-VJ+sKvNA/GE7Ccacc9Cha7bpS8nyzVv0jdVgwNDaR4gDMC/2TTRc33Ip8qrNYUcpkOHUT5OZ0bUcNNVZQ9RLlg=="], + + "@esbuild/android-arm64": ["@esbuild/android-arm64@0.25.12", "", { "os": "android", "cpu": "arm64" }, "sha512-6AAmLG7zwD1Z159jCKPvAxZd4y/VTO0VkprYy+3N2FtJ8+BQWFXU+OxARIwA46c5tdD9SsKGZ/1ocqBS/gAKHg=="], + + "@esbuild/android-x64": ["@esbuild/android-x64@0.25.12", "", { "os": "android", "cpu": "x64" }, "sha512-5jbb+2hhDHx5phYR2By8GTWEzn6I9UqR11Kwf22iKbNpYrsmRB18aX/9ivc5cabcUiAT/wM+YIZ6SG9QO6a8kg=="], + + "@esbuild/darwin-arm64": ["@esbuild/darwin-arm64@0.25.12", "", { "os": "darwin", "cpu": "arm64" }, "sha512-N3zl+lxHCifgIlcMUP5016ESkeQjLj/959RxxNYIthIg+CQHInujFuXeWbWMgnTo4cp5XVHqFPmpyu9J65C1Yg=="], + + "@esbuild/darwin-x64": ["@esbuild/darwin-x64@0.25.12", "", { "os": "darwin", "cpu": "x64" }, "sha512-HQ9ka4Kx21qHXwtlTUVbKJOAnmG1ipXhdWTmNXiPzPfWKpXqASVcWdnf2bnL73wgjNrFXAa3yYvBSd9pzfEIpA=="], + + "@esbuild/freebsd-arm64": ["@esbuild/freebsd-arm64@0.25.12", "", { "os": "freebsd", "cpu": "arm64" }, "sha512-gA0Bx759+7Jve03K1S0vkOu5Lg/85dou3EseOGUes8flVOGxbhDDh/iZaoek11Y8mtyKPGF3vP8XhnkDEAmzeg=="], + + "@esbuild/freebsd-x64": ["@esbuild/freebsd-x64@0.25.12", "", { "os": "freebsd", "cpu": "x64" }, "sha512-TGbO26Yw2xsHzxtbVFGEXBFH0FRAP7gtcPE7P5yP7wGy7cXK2oO7RyOhL5NLiqTlBh47XhmIUXuGciXEqYFfBQ=="], + + "@esbuild/linux-arm": ["@esbuild/linux-arm@0.25.12", "", { "os": "linux", "cpu": "arm" }, "sha512-lPDGyC1JPDou8kGcywY0YILzWlhhnRjdof3UlcoqYmS9El818LLfJJc3PXXgZHrHCAKs/Z2SeZtDJr5MrkxtOw=="], + + "@esbuild/linux-arm64": ["@esbuild/linux-arm64@0.25.12", "", { "os": "linux", "cpu": "arm64" }, "sha512-8bwX7a8FghIgrupcxb4aUmYDLp8pX06rGh5HqDT7bB+8Rdells6mHvrFHHW2JAOPZUbnjUpKTLg6ECyzvas2AQ=="], + + "@esbuild/linux-ia32": ["@esbuild/linux-ia32@0.25.12", "", { "os": "linux", "cpu": "ia32" }, "sha512-0y9KrdVnbMM2/vG8KfU0byhUN+EFCny9+8g202gYqSSVMonbsCfLjUO+rCci7pM0WBEtz+oK/PIwHkzxkyharA=="], + + "@esbuild/linux-loong64": ["@esbuild/linux-loong64@0.25.12", "", { "os": "linux", "cpu": "none" }, "sha512-h///Lr5a9rib/v1GGqXVGzjL4TMvVTv+s1DPoxQdz7l/AYv6LDSxdIwzxkrPW438oUXiDtwM10o9PmwS/6Z0Ng=="], + + "@esbuild/linux-mips64el": ["@esbuild/linux-mips64el@0.25.12", "", { "os": "linux", "cpu": "none" }, "sha512-iyRrM1Pzy9GFMDLsXn1iHUm18nhKnNMWscjmp4+hpafcZjrr2WbT//d20xaGljXDBYHqRcl8HnxbX6uaA/eGVw=="], + + "@esbuild/linux-ppc64": ["@esbuild/linux-ppc64@0.25.12", "", { "os": "linux", "cpu": "ppc64" }, "sha512-9meM/lRXxMi5PSUqEXRCtVjEZBGwB7P/D4yT8UG/mwIdze2aV4Vo6U5gD3+RsoHXKkHCfSxZKzmDssVlRj1QQA=="], + + "@esbuild/linux-riscv64": ["@esbuild/linux-riscv64@0.25.12", "", { "os": "linux", "cpu": "none" }, "sha512-Zr7KR4hgKUpWAwb1f3o5ygT04MzqVrGEGXGLnj15YQDJErYu/BGg+wmFlIDOdJp0PmB0lLvxFIOXZgFRrdjR0w=="], + + "@esbuild/linux-s390x": ["@esbuild/linux-s390x@0.25.12", "", { "os": "linux", "cpu": "s390x" }, "sha512-MsKncOcgTNvdtiISc/jZs/Zf8d0cl/t3gYWX8J9ubBnVOwlk65UIEEvgBORTiljloIWnBzLs4qhzPkJcitIzIg=="], + + "@esbuild/linux-x64": ["@esbuild/linux-x64@0.25.12", "", { "os": "linux", "cpu": "x64" }, "sha512-uqZMTLr/zR/ed4jIGnwSLkaHmPjOjJvnm6TVVitAa08SLS9Z0VM8wIRx7gWbJB5/J54YuIMInDquWyYvQLZkgw=="], + + "@esbuild/netbsd-arm64": ["@esbuild/netbsd-arm64@0.25.12", "", { "os": "none", "cpu": "arm64" }, "sha512-xXwcTq4GhRM7J9A8Gv5boanHhRa/Q9KLVmcyXHCTaM4wKfIpWkdXiMog/KsnxzJ0A1+nD+zoecuzqPmCRyBGjg=="], + + "@esbuild/netbsd-x64": ["@esbuild/netbsd-x64@0.25.12", "", { "os": "none", "cpu": "x64" }, "sha512-Ld5pTlzPy3YwGec4OuHh1aCVCRvOXdH8DgRjfDy/oumVovmuSzWfnSJg+VtakB9Cm0gxNO9BzWkj6mtO1FMXkQ=="], + + "@esbuild/openbsd-arm64": ["@esbuild/openbsd-arm64@0.25.12", "", { "os": "openbsd", "cpu": "arm64" }, "sha512-fF96T6KsBo/pkQI950FARU9apGNTSlZGsv1jZBAlcLL1MLjLNIWPBkj5NlSz8aAzYKg+eNqknrUJ24QBybeR5A=="], + + "@esbuild/openbsd-x64": ["@esbuild/openbsd-x64@0.25.12", "", { "os": "openbsd", "cpu": "x64" }, "sha512-MZyXUkZHjQxUvzK7rN8DJ3SRmrVrke8ZyRusHlP+kuwqTcfWLyqMOE3sScPPyeIXN/mDJIfGXvcMqCgYKekoQw=="], + + "@esbuild/openharmony-arm64": ["@esbuild/openharmony-arm64@0.25.12", "", { "os": "none", "cpu": "arm64" }, "sha512-rm0YWsqUSRrjncSXGA7Zv78Nbnw4XL6/dzr20cyrQf7ZmRcsovpcRBdhD43Nuk3y7XIoW2OxMVvwuRvk9XdASg=="], + + "@esbuild/sunos-x64": ["@esbuild/sunos-x64@0.25.12", "", { "os": "sunos", "cpu": "x64" }, "sha512-3wGSCDyuTHQUzt0nV7bocDy72r2lI33QL3gkDNGkod22EsYl04sMf0qLb8luNKTOmgF/eDEDP5BFNwoBKH441w=="], + + "@esbuild/win32-arm64": ["@esbuild/win32-arm64@0.25.12", "", { "os": "win32", "cpu": "arm64" }, "sha512-rMmLrur64A7+DKlnSuwqUdRKyd3UE7oPJZmnljqEptesKM8wx9J8gx5u0+9Pq0fQQW8vqeKebwNXdfOyP+8Bsg=="], + + "@esbuild/win32-ia32": ["@esbuild/win32-ia32@0.25.12", "", { "os": "win32", "cpu": "ia32" }, "sha512-HkqnmmBoCbCwxUKKNPBixiWDGCpQGVsrQfJoVGYLPT41XWF8lHuE5N6WhVia2n4o5QK5M4tYr21827fNhi4byQ=="], + + "@esbuild/win32-x64": ["@esbuild/win32-x64@0.25.12", "", { "os": "win32", "cpu": "x64" }, "sha512-alJC0uCZpTFrSL0CCDjcgleBXPnCrEAhTBILpeAp7M/OFgoqtAetfBzX0xM00MUsVVPpVjlPuMbREqnZCXaTnA=="], + + "@fluent/bundle": ["@fluent/bundle@0.17.1", "", {}, "sha512-CRFNT9QcSFAeFDneTF59eyv3JXFGhIIN4boUO2y22YmsuuKLyDk+N1I/NQUYz9Ab63e6V7T6vItoZIG/2oOOuw=="], + + "@fluent/langneg": ["@fluent/langneg@0.6.2", "", {}, "sha512-YF4gZ4sLYRQfctpUR2uhb5UyPUYY5n/bi3OaED/Q4awKjPjlaF8tInO3uja7pnLQcmLTURkZL7L9zxv2Z5NDwg=="], + + "@grammyjs/conversations": ["@grammyjs/conversations@2.1.1", "", { "peerDependencies": { "grammy": "^1.20.1" } }, "sha512-hoxqwSkaXDeU7mzXulpk3A4Cmd6UZO3HU4aPoITX5ekSHK7ZcUEmMl7RhKKkqw3z6zVbbAShQreJoVV5/dDSLA=="], + + "@grammyjs/i18n": ["@grammyjs/i18n@1.1.2", "", { "dependencies": { "@deno/shim-deno": "~0.18.0", "@fluent/bundle": "^0.17.1", "@fluent/langneg": "^0.6.2" }, "peerDependencies": { "grammy": "^1.10.0" } }, "sha512-PcK06mxuDDZjxdZ5HywBhr+erEITsR816KP4DNIDDds1jpA45pfz/nS9FdZmzF8H6lMyPix3mV5WL1rT4q+BuA=="], + + "@grammyjs/types": ["@grammyjs/types@3.25.0", "", {}, "sha512-iN9i5p+8ZOu9OMxWNcguojQfz4K/PDyMPOnL7PPCON+SoA/F8OKMH3uR7CVUkYfdNe0GCz8QOzAWrnqusQYFOg=="], + + "@img/colour": ["@img/colour@1.1.0", "", {}, "sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ=="], + + "@img/sharp-darwin-arm64": ["@img/sharp-darwin-arm64@0.34.5", "", { "optionalDependencies": { "@img/sharp-libvips-darwin-arm64": "1.2.4" }, "os": "darwin", "cpu": "arm64" }, "sha512-imtQ3WMJXbMY4fxb/Ndp6HBTNVtWCUI0WdobyheGf5+ad6xX8VIDO8u2xE4qc/fr08CKG/7dDseFtn6M6g/r3w=="], + + "@img/sharp-darwin-x64": ["@img/sharp-darwin-x64@0.34.5", "", { "optionalDependencies": { "@img/sharp-libvips-darwin-x64": "1.2.4" }, "os": "darwin", "cpu": "x64" }, "sha512-YNEFAF/4KQ/PeW0N+r+aVVsoIY0/qxxikF2SWdp+NRkmMB7y9LBZAVqQ4yhGCm/H3H270OSykqmQMKLBhBJDEw=="], + + "@img/sharp-libvips-darwin-arm64": ["@img/sharp-libvips-darwin-arm64@1.2.4", "", { "os": "darwin", "cpu": "arm64" }, "sha512-zqjjo7RatFfFoP0MkQ51jfuFZBnVE2pRiaydKJ1G/rHZvnsrHAOcQALIi9sA5co5xenQdTugCvtb1cuf78Vf4g=="], + + "@img/sharp-libvips-darwin-x64": ["@img/sharp-libvips-darwin-x64@1.2.4", "", { "os": "darwin", "cpu": "x64" }, "sha512-1IOd5xfVhlGwX+zXv2N93k0yMONvUlANylbJw1eTah8K/Jtpi15KC+WSiaX/nBmbm2HxRM1gZ0nSdjSsrZbGKg=="], + + "@img/sharp-libvips-linux-arm": ["@img/sharp-libvips-linux-arm@1.2.4", "", { "os": "linux", "cpu": "arm" }, "sha512-bFI7xcKFELdiNCVov8e44Ia4u2byA+l3XtsAj+Q8tfCwO6BQ8iDojYdvoPMqsKDkuoOo+X6HZA0s0q11ANMQ8A=="], + + "@img/sharp-libvips-linux-arm64": ["@img/sharp-libvips-linux-arm64@1.2.4", "", { "os": "linux", "cpu": "arm64" }, "sha512-excjX8DfsIcJ10x1Kzr4RcWe1edC9PquDRRPx3YVCvQv+U5p7Yin2s32ftzikXojb1PIFc/9Mt28/y+iRklkrw=="], + + "@img/sharp-libvips-linux-ppc64": ["@img/sharp-libvips-linux-ppc64@1.2.4", "", { "os": "linux", "cpu": "ppc64" }, "sha512-FMuvGijLDYG6lW+b/UvyilUWu5Ayu+3r2d1S8notiGCIyYU/76eig1UfMmkZ7vwgOrzKzlQbFSuQfgm7GYUPpA=="], + + "@img/sharp-libvips-linux-riscv64": ["@img/sharp-libvips-linux-riscv64@1.2.4", "", { "os": "linux", "cpu": "none" }, "sha512-oVDbcR4zUC0ce82teubSm+x6ETixtKZBh/qbREIOcI3cULzDyb18Sr/Wcyx7NRQeQzOiHTNbZFF1UwPS2scyGA=="], + + "@img/sharp-libvips-linux-s390x": ["@img/sharp-libvips-linux-s390x@1.2.4", "", { "os": "linux", "cpu": "s390x" }, "sha512-qmp9VrzgPgMoGZyPvrQHqk02uyjA0/QrTO26Tqk6l4ZV0MPWIW6LTkqOIov+J1yEu7MbFQaDpwdwJKhbJvuRxQ=="], + + "@img/sharp-libvips-linux-x64": ["@img/sharp-libvips-linux-x64@1.2.4", "", { "os": "linux", "cpu": "x64" }, "sha512-tJxiiLsmHc9Ax1bz3oaOYBURTXGIRDODBqhveVHonrHJ9/+k89qbLl0bcJns+e4t4rvaNBxaEZsFtSfAdquPrw=="], + + "@img/sharp-libvips-linuxmusl-arm64": ["@img/sharp-libvips-linuxmusl-arm64@1.2.4", "", { "os": "linux", "cpu": "arm64" }, "sha512-FVQHuwx1IIuNow9QAbYUzJ+En8KcVm9Lk5+uGUQJHaZmMECZmOlix9HnH7n1TRkXMS0pGxIJokIVB9SuqZGGXw=="], + + "@img/sharp-libvips-linuxmusl-x64": ["@img/sharp-libvips-linuxmusl-x64@1.2.4", "", { "os": "linux", "cpu": "x64" }, "sha512-+LpyBk7L44ZIXwz/VYfglaX/okxezESc6UxDSoyo2Ks6Jxc4Y7sGjpgU9s4PMgqgjj1gZCylTieNamqA1MF7Dg=="], + + "@img/sharp-linux-arm": ["@img/sharp-linux-arm@0.34.5", "", { "optionalDependencies": { "@img/sharp-libvips-linux-arm": "1.2.4" }, "os": "linux", "cpu": "arm" }, "sha512-9dLqsvwtg1uuXBGZKsxem9595+ujv0sJ6Vi8wcTANSFpwV/GONat5eCkzQo/1O6zRIkh0m/8+5BjrRr7jDUSZw=="], + + "@img/sharp-linux-arm64": ["@img/sharp-linux-arm64@0.34.5", "", { "optionalDependencies": { "@img/sharp-libvips-linux-arm64": "1.2.4" }, "os": "linux", "cpu": "arm64" }, "sha512-bKQzaJRY/bkPOXyKx5EVup7qkaojECG6NLYswgktOZjaXecSAeCWiZwwiFf3/Y+O1HrauiE3FVsGxFg8c24rZg=="], + + "@img/sharp-linux-ppc64": ["@img/sharp-linux-ppc64@0.34.5", "", { "optionalDependencies": { "@img/sharp-libvips-linux-ppc64": "1.2.4" }, "os": "linux", "cpu": "ppc64" }, "sha512-7zznwNaqW6YtsfrGGDA6BRkISKAAE1Jo0QdpNYXNMHu2+0dTrPflTLNkpc8l7MUP5M16ZJcUvysVWWrMefZquA=="], + + "@img/sharp-linux-riscv64": ["@img/sharp-linux-riscv64@0.34.5", "", { "optionalDependencies": { "@img/sharp-libvips-linux-riscv64": "1.2.4" }, "os": "linux", "cpu": "none" }, "sha512-51gJuLPTKa7piYPaVs8GmByo7/U7/7TZOq+cnXJIHZKavIRHAP77e3N2HEl3dgiqdD/w0yUfiJnII77PuDDFdw=="], + + "@img/sharp-linux-s390x": ["@img/sharp-linux-s390x@0.34.5", "", { "optionalDependencies": { "@img/sharp-libvips-linux-s390x": "1.2.4" }, "os": "linux", "cpu": "s390x" }, "sha512-nQtCk0PdKfho3eC5MrbQoigJ2gd1CgddUMkabUj+rBevs8tZ2cULOx46E7oyX+04WGfABgIwmMC0VqieTiR4jg=="], + + "@img/sharp-linux-x64": ["@img/sharp-linux-x64@0.34.5", "", { "optionalDependencies": { "@img/sharp-libvips-linux-x64": "1.2.4" }, "os": "linux", "cpu": "x64" }, "sha512-MEzd8HPKxVxVenwAa+JRPwEC7QFjoPWuS5NZnBt6B3pu7EG2Ge0id1oLHZpPJdn3OQK+BQDiw9zStiHBTJQQQQ=="], + + "@img/sharp-linuxmusl-arm64": ["@img/sharp-linuxmusl-arm64@0.34.5", "", { "optionalDependencies": { "@img/sharp-libvips-linuxmusl-arm64": "1.2.4" }, "os": "linux", "cpu": "arm64" }, "sha512-fprJR6GtRsMt6Kyfq44IsChVZeGN97gTD331weR1ex1c1rypDEABN6Tm2xa1wE6lYb5DdEnk03NZPqA7Id21yg=="], + + "@img/sharp-linuxmusl-x64": ["@img/sharp-linuxmusl-x64@0.34.5", "", { "optionalDependencies": { "@img/sharp-libvips-linuxmusl-x64": "1.2.4" }, "os": "linux", "cpu": "x64" }, "sha512-Jg8wNT1MUzIvhBFxViqrEhWDGzqymo3sV7z7ZsaWbZNDLXRJZoRGrjulp60YYtV4wfY8VIKcWidjojlLcWrd8Q=="], + + "@img/sharp-wasm32": ["@img/sharp-wasm32@0.34.5", "", { "dependencies": { "@emnapi/runtime": "^1.7.0" }, "cpu": "none" }, "sha512-OdWTEiVkY2PHwqkbBI8frFxQQFekHaSSkUIJkwzclWZe64O1X4UlUjqqqLaPbUpMOQk6FBu/HtlGXNblIs0huw=="], + + "@img/sharp-win32-arm64": ["@img/sharp-win32-arm64@0.34.5", "", { "os": "win32", "cpu": "arm64" }, "sha512-WQ3AgWCWYSb2yt+IG8mnC6Jdk9Whs7O0gxphblsLvdhSpSTtmu69ZG1Gkb6NuvxsNACwiPV6cNSZNzt0KPsw7g=="], + + "@img/sharp-win32-ia32": ["@img/sharp-win32-ia32@0.34.5", "", { "os": "win32", "cpu": "ia32" }, "sha512-FV9m/7NmeCmSHDD5j4+4pNI8Cp3aW+JvLoXcTUo0IqyjSfAZJ8dIUmijx1qaJsIiU+Hosw6xM5KijAWRJCSgNg=="], + + "@img/sharp-win32-x64": ["@img/sharp-win32-x64@0.34.5", "", { "os": "win32", "cpu": "x64" }, "sha512-+29YMsqY2/9eFEiW93eqWnuLcWcufowXewwSNIT6UwZdUUCrM3oFjMWH/Z6/TMmb4hlFenmfAVbpWeup2jryCw=="], + + "@jridgewell/resolve-uri": ["@jridgewell/resolve-uri@3.1.2", "", {}, "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw=="], + + "@jridgewell/sourcemap-codec": ["@jridgewell/sourcemap-codec@1.5.5", "", {}, "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og=="], + + "@jridgewell/trace-mapping": ["@jridgewell/trace-mapping@0.3.9", "", { "dependencies": { "@jridgewell/resolve-uri": "^3.0.3", "@jridgewell/sourcemap-codec": "^1.4.10" } }, "sha512-3Belt6tdc8bPgAtbcmdtNJlirVoTmEb5e2gC94PnkwEW9jI6CAHUeoG85tjWP5WquqfavoMtMwiG4P926ZKKuQ=="], + + "@poppinss/colors": ["@poppinss/colors@4.1.6", "", { "dependencies": { "kleur": "^4.1.5" } }, "sha512-H9xkIdFswbS8n1d6vmRd8+c10t2Qe+rZITbbDHHkQixH5+2x1FDGmi/0K+WgWiqQFKPSlIYB7jlH6Kpfn6Fleg=="], + + "@poppinss/dumper": ["@poppinss/dumper@0.6.5", "", { "dependencies": { "@poppinss/colors": "^4.1.5", "@sindresorhus/is": "^7.0.2", "supports-color": "^10.0.0" } }, "sha512-NBdYIb90J7LfOI32dOewKI1r7wnkiH6m920puQ3qHUeZkxNkQiFnXVWoE6YtFSv6QOiPPf7ys6i+HWWecDz7sw=="], + + "@poppinss/exception": ["@poppinss/exception@1.2.3", "", {}, "sha512-dCED+QRChTVatE9ibtoaxc+WkdzOSjYTKi/+uacHWIsfodVfpsueo3+DKpgU5Px8qXjgmXkSvhXvSCz3fnP9lw=="], + + "@sindresorhus/is": ["@sindresorhus/is@7.2.0", "", {}, "sha512-P1Cz1dWaFfR4IR+U13mqqiGsLFf1KbayybWwdd2vfctdV6hDpUkgCY0nKOLLTMSoRd/jJNjtbqzf13K8DCCXQw=="], + + "@speed-highlight/core": ["@speed-highlight/core@1.2.14", "", {}, "sha512-G4ewlBNhUtlLvrJTb88d2mdy2KRijzs4UhnlrOSRT4bmjh/IqNElZa3zkrZ+TC47TwtlDWzVLFADljF1Ijp5hA=="], + + "@twurple/api": ["@twurple/api@8.0.3", "", { "dependencies": { "@d-fischer/cache-decorators": "^4.0.0", "@d-fischer/detect-node": "^3.0.1", "@d-fischer/logger": "^4.2.1", "@d-fischer/rate-limiter": "^1.1.0", "@d-fischer/shared-utils": "^3.6.1", "@d-fischer/typed-event-emitter": "^3.3.1", "@twurple/api-call": "8.0.3", "@twurple/common": "8.0.3", "retry": "^0.13.1", "tslib": "^2.0.3" }, "peerDependencies": { "@twurple/auth": "8.0.3" } }, "sha512-vnqVi9YlNDbCqgpUUvTIq4sDitKCY0dkTw9zPluZvRNqUB1eCsuoaRNW96HQDhKtA9P4pRzwZ8xU7v/1KU2ytg=="], + + "@twurple/api-call": ["@twurple/api-call@8.0.3", "", { "dependencies": { "@d-fischer/shared-utils": "^3.6.1", "@twurple/common": "8.0.3", "tslib": "^2.0.3" } }, "sha512-/5DBTqFjpYB+qqOkkFzoTWE79a7+I8uLXmBIIIYjGoq/CIPxKcHnlemXlU8cQhTr87PVa3th8zJXGYiNkpRx8w=="], + + "@twurple/auth": ["@twurple/auth@8.0.3", "", { "dependencies": { "@d-fischer/logger": "^4.2.1", "@d-fischer/shared-utils": "^3.6.1", "@d-fischer/typed-event-emitter": "^3.3.1", "@twurple/api-call": "8.0.3", "@twurple/common": "8.0.3", "tslib": "^2.0.3" } }, "sha512-Xlv+WNXmGQir4aBXYeRCqdno5XurA6jzYTIovSEHa7FZf3AMHMFqtzW7yqTCUn4iOahfUSA2TIIxmxFM0wis0g=="], + + "@twurple/common": ["@twurple/common@8.0.3", "", { "dependencies": { "@d-fischer/shared-utils": "^3.6.1", "klona": "^2.0.4", "tslib": "^2.0.3" } }, "sha512-JQ2lb5qSFT21Y9qMfIouAILb94ppedLHASq49Fe/AP8oq0k3IC9Q7tX2n6tiMzGWqn+n8MnONUpMSZ6FhulMXA=="], + + "@twurple/eventsub-base": ["@twurple/eventsub-base@8.0.3", "", { "dependencies": { "@d-fischer/logger": "^4.2.1", "@d-fischer/shared-utils": "^3.6.1", "@d-fischer/typed-event-emitter": "^3.3.0", "@twurple/api": "8.0.3", "@twurple/auth": "8.0.3", "@twurple/common": "8.0.3", "tslib": "^2.0.3" } }, "sha512-59G5xJbHWLTSO6NAgwtkHPfIlmdjrABgiEumFnHhNusMbLM9qdA+kLcW5NB2NImNliytl6zZtqY92FInzUE6NA=="], + + "@twurple/eventsub-http": ["@twurple/eventsub-http@8.0.3", "", { "dependencies": { "@d-fischer/logger": "^4.2.1", "@d-fischer/shared-utils": "^3.6.1", "@d-fischer/typed-event-emitter": "^3.3.0", "@twurple/auth": "8.0.3", "@twurple/common": "8.0.3", "@twurple/eventsub-base": "8.0.3", "@types/express-serve-static-core": "^5.1.0", "httpanda": "^0.4.6", "raw-body": "^3.0.2", "tslib": "^2.0.3" }, "peerDependencies": { "@twurple/api": "8.0.3" } }, "sha512-ds8l01GfsIC0hhILepv/UUn/Ix8s0wLg9aGy10xWaG9/Hlfe82NPI8gAg0LYsmlCsOADPwJZSckMTGPJrpw1Iw=="], + + "@types/express-serve-static-core": ["@types/express-serve-static-core@5.1.1", "", { "dependencies": { "@types/node": "*", "@types/qs": "*", "@types/range-parser": "*", "@types/send": "*" } }, "sha512-v4zIMr/cX7/d2BpAEX3KNKL/JrT1s43s96lLvvdTmza1oEvDudCqK9aF/djc/SWgy8Yh0h30TZx5VpzqFCxk5A=="], + + "@types/node": ["@types/node@22.19.15", "", { "dependencies": { "undici-types": "~6.21.0" } }, "sha512-F0R/h2+dsy5wJAUe3tAU6oqa2qbWY5TpNfL/RGmo1y38hiyO1w3x2jPtt76wmuaJI4DQnOBu21cNXQ2STIUUWg=="], + + "@types/qs": ["@types/qs@6.15.0", "", {}, "sha512-JawvT8iBVWpzTrz3EGw9BTQFg3BQNmwERdKE22vlTxawwtbyUSlMppvZYKLZzB5zgACXdXxbD3m1bXaMqP/9ow=="], + + "@types/range-parser": ["@types/range-parser@1.2.7", "", {}, "sha512-hKormJbkJqzQGhziax5PItDUTMAM9uE2XXQmM37dyd4hVM+5aVl7oVxMVUiVQn2oCQFN/LKCZdvSM0pFRqbSmQ=="], + + "@types/send": ["@types/send@1.2.1", "", { "dependencies": { "@types/node": "*" } }, "sha512-arsCikDvlU99zl1g69TcAB3mzZPpxgw0UQnaHeC1Nwb015xp8bknZv5rIfri9xTOcMuaVgvabfIRA7PSZVuZIQ=="], + + "abort-controller": ["abort-controller@3.0.0", "", { "dependencies": { "event-target-shim": "^5.0.0" } }, "sha512-h8lQ8tacZYnR3vNQTgibj+tODHI5/+l06Au2Pcriv/Gmet0eaj4TwWH41sO9wnHDiQsEj19q0drzdWdeAHtweg=="], + + "blake3-wasm": ["blake3-wasm@2.1.5", "", {}, "sha512-F1+K8EbfOZE49dtoPtmxUQrpXaBIl3ICvasLh+nJta0xkz+9kF/7uet9fLnwKqhDrmj6g+6K3Tw9yQPUg2ka5g=="], + + "buffer-from": ["buffer-from@1.1.2", "", {}, "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ=="], + + "bytes": ["bytes@3.1.2", "", {}, "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg=="], + + "cookie": ["cookie@1.1.1", "", {}, "sha512-ei8Aos7ja0weRpFzJnEA9UHJ/7XQmqglbRwnf2ATjcB9Wq874VKH9kfjjirM6UhU2/E5fFYadylyhFldcqSidQ=="], + + "debug": ["debug@4.4.3", "", { "dependencies": { "ms": "^2.1.3" } }, "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA=="], + + "depd": ["depd@2.0.0", "", {}, "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw=="], + + "detect-libc": ["detect-libc@2.1.2", "", {}, "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ=="], + + "drizzle-kit": ["drizzle-kit@0.31.9", "", { "dependencies": { "@drizzle-team/brocli": "^0.10.2", "@esbuild-kit/esm-loader": "^2.5.5", "esbuild": "^0.25.4", "esbuild-register": "^3.5.0" }, "bin": { "drizzle-kit": "bin.cjs" } }, "sha512-GViD3IgsXn7trFyBUUHyTFBpH/FsHTxYJ66qdbVggxef4UBPHRYxQaRzYLTuekYnk9i5FIEL9pbBIwMqX/Uwrg=="], + + "drizzle-orm": ["drizzle-orm@0.45.1", "", { "peerDependencies": { "@aws-sdk/client-rds-data": ">=3", "@cloudflare/workers-types": ">=4", "@electric-sql/pglite": ">=0.2.0", "@libsql/client": ">=0.10.0", "@libsql/client-wasm": ">=0.10.0", "@neondatabase/serverless": ">=0.10.0", "@op-engineering/op-sqlite": ">=2", "@opentelemetry/api": "^1.4.1", "@planetscale/database": ">=1.13", "@prisma/client": "*", "@tidbcloud/serverless": "*", "@types/better-sqlite3": "*", "@types/pg": "*", "@types/sql.js": "*", "@upstash/redis": ">=1.34.7", "@vercel/postgres": ">=0.8.0", "@xata.io/client": "*", "better-sqlite3": ">=7", "bun-types": "*", "expo-sqlite": ">=14.0.0", "gel": ">=2", "knex": "*", "kysely": "*", "mysql2": ">=2", "pg": ">=8", "postgres": ">=3", "sql.js": ">=1", "sqlite3": ">=5" }, "optionalPeers": ["@aws-sdk/client-rds-data", "@cloudflare/workers-types", "@electric-sql/pglite", "@libsql/client", "@libsql/client-wasm", "@neondatabase/serverless", "@op-engineering/op-sqlite", "@opentelemetry/api", "@planetscale/database", "@prisma/client", "@tidbcloud/serverless", "@types/better-sqlite3", "@types/pg", "@types/sql.js", "@upstash/redis", "@vercel/postgres", "@xata.io/client", "better-sqlite3", "bun-types", "expo-sqlite", "gel", "knex", "kysely", "mysql2", "pg", "postgres", "sql.js", "sqlite3"] }, "sha512-Te0FOdKIistGNPMq2jscdqngBRfBpC8uMFVwqjf6gtTVJHIQ/dosgV/CLBU2N4ZJBsXL5savCba9b0YJskKdcA=="], + + "error-stack-parser-es": ["error-stack-parser-es@1.0.5", "", {}, "sha512-5qucVt2XcuGMcEGgWI7i+yZpmpByQ8J1lHhcL7PwqCwu9FPP3VUXzT4ltHe5i2z9dePwEHcDVOAfSnHsOlCXRA=="], + + "esbuild": ["esbuild@0.25.12", "", { "optionalDependencies": { "@esbuild/aix-ppc64": "0.25.12", "@esbuild/android-arm": "0.25.12", "@esbuild/android-arm64": "0.25.12", "@esbuild/android-x64": "0.25.12", "@esbuild/darwin-arm64": "0.25.12", "@esbuild/darwin-x64": "0.25.12", "@esbuild/freebsd-arm64": "0.25.12", "@esbuild/freebsd-x64": "0.25.12", "@esbuild/linux-arm": "0.25.12", "@esbuild/linux-arm64": "0.25.12", "@esbuild/linux-ia32": "0.25.12", "@esbuild/linux-loong64": "0.25.12", "@esbuild/linux-mips64el": "0.25.12", "@esbuild/linux-ppc64": "0.25.12", "@esbuild/linux-riscv64": "0.25.12", "@esbuild/linux-s390x": "0.25.12", "@esbuild/linux-x64": "0.25.12", "@esbuild/netbsd-arm64": "0.25.12", "@esbuild/netbsd-x64": "0.25.12", "@esbuild/openbsd-arm64": "0.25.12", "@esbuild/openbsd-x64": "0.25.12", "@esbuild/openharmony-arm64": "0.25.12", "@esbuild/sunos-x64": "0.25.12", "@esbuild/win32-arm64": "0.25.12", "@esbuild/win32-ia32": "0.25.12", "@esbuild/win32-x64": "0.25.12" }, "bin": { "esbuild": "bin/esbuild" } }, "sha512-bbPBYYrtZbkt6Os6FiTLCTFxvq4tt3JKall1vRwshA3fdVztsLAatFaZobhkBC8/BrPetoa0oksYoKXoG4ryJg=="], + + "esbuild-register": ["esbuild-register@3.6.0", "", { "dependencies": { "debug": "^4.3.4" }, "peerDependencies": { "esbuild": ">=0.12 <1" } }, "sha512-H2/S7Pm8a9CL1uhp9OvjwrBh5Pvx0H8qVOxNu8Wed9Y7qv56MPtq+GGM8RJpq6glYJn9Wspr8uw7l55uyinNeg=="], + + "event-target-shim": ["event-target-shim@5.0.1", "", {}, "sha512-i/2XbnSz/uxRCU6+NdVJgKWDTM427+MqYbkQzD321DuCQJUqOuJKIA0IM2+W2xtYHdKOmZ4dR6fExsd4SXL+WQ=="], + + "fsevents": ["fsevents@2.3.3", "", { "os": "darwin" }, "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw=="], + + "get-tsconfig": ["get-tsconfig@4.13.6", "", { "dependencies": { "resolve-pkg-maps": "^1.0.0" } }, "sha512-shZT/QMiSHc/YBLxxOkMtgSid5HFoauqCE3/exfsEcwg1WkeqjG+V40yBbBrsD+jW2HDXcs28xOfcbm2jI8Ddw=="], + + "grammy": ["grammy@1.41.1", "", { "dependencies": { "@grammyjs/types": "3.25.0", "abort-controller": "^3.0.0", "debug": "^4.4.3", "node-fetch": "^2.7.0" } }, "sha512-wcHAQ1e7svL3fJMpDchcQVcWUmywhuepOOjHUHmMmWAwUJEIyK5ea5sbSjZd+Gy1aMpZeP8VYJa+4tP+j1YptQ=="], + + "hono": ["hono@4.12.5", "", {}, "sha512-3qq+FUBtlTHhtYxbxheZgY8NIFnkkC/MR8u5TTsr7YZ3wixryQ3cCwn3iZbg8p8B88iDBBAYSfZDS75t8MN7Vg=="], + + "http-errors": ["http-errors@2.0.1", "", { "dependencies": { "depd": "~2.0.0", "inherits": "~2.0.4", "setprototypeof": "~1.2.0", "statuses": "~2.0.2", "toidentifier": "~1.0.1" } }, "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ=="], + + "httpanda": ["httpanda@0.4.7", "", { "dependencies": { "@types/node": "^14.11.2", "tslib": "^2.0.3" } }, "sha512-NieTiR7kfOheL9OeEi6+JKFmJ2JP9ZRqUQ4tiXZ9J+EMMKxApHUQlEM5l4gZ+l67lxE9Er6oigZnujmhlodNCg=="], + + "iconv-lite": ["iconv-lite@0.7.2", "", { "dependencies": { "safer-buffer": ">= 2.1.2 < 3.0.0" } }, "sha512-im9DjEDQ55s9fL4EYzOAv0yMqmMBSZp6G0VvFyTMPKWxiSBHUj9NW/qqLmXUwXrrM7AvqSlTCfvqRb0cM8yYqw=="], + + "inherits": ["inherits@2.0.4", "", {}, "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ=="], + + "isexe": ["isexe@3.1.5", "", {}, "sha512-6B3tLtFqtQS4ekarvLVMZ+X+VlvQekbe4taUkf/rhVO3d/h0M2rfARm/pXLcPEsjjMsFgrFgSrhQIxcSVrBz8w=="], + + "kleur": ["kleur@4.1.5", "", {}, "sha512-o+NO+8WrRiQEE4/7nwRJhN1HWpVmJm511pBHUxPLtp0BUISzlBplORYSmTclCnJvQq2tKu/sgl3xVpkc7ZWuQQ=="], + + "klona": ["klona@2.0.6", "", {}, "sha512-dhG34DXATL5hSxJbIexCft8FChFXtmskoZYnoPWjXQuebWYCNkVeV3KkGegCK9CP1oswI/vQibS2GY7Em/sJJA=="], + + "miniflare": ["miniflare@4.20260301.1", "", { "dependencies": { "@cspotcode/source-map-support": "0.8.1", "sharp": "^0.34.5", "undici": "7.18.2", "workerd": "1.20260301.1", "ws": "8.18.0", "youch": "4.1.0-beta.10" }, "bin": { "miniflare": "bootstrap.js" } }, "sha512-fqkHx0QMKswRH9uqQQQOU/RoaS3Wjckxy3CUX3YGJr0ZIMu7ObvI+NovdYi6RIsSPthNtq+3TPmRNxjeRiasog=="], + + "ms": ["ms@2.1.3", "", {}, "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="], + + "node-fetch": ["node-fetch@2.7.0", "", { "dependencies": { "whatwg-url": "^5.0.0" }, "peerDependencies": { "encoding": "^0.1.0" }, "optionalPeers": ["encoding"] }, "sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A=="], + + "path-to-regexp": ["path-to-regexp@6.3.0", "", {}, "sha512-Yhpw4T9C6hPpgPeA28us07OJeqZ5EzQTkbfwuhsUg0c237RomFoETJgmp2sa3F/41gfLE6G5cqcYwznmeEeOlQ=="], + + "pathe": ["pathe@2.0.3", "", {}, "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w=="], + + "raw-body": ["raw-body@3.0.2", "", { "dependencies": { "bytes": "~3.1.2", "http-errors": "~2.0.1", "iconv-lite": "~0.7.0", "unpipe": "~1.0.0" } }, "sha512-K5zQjDllxWkf7Z5xJdV0/B0WTNqx6vxG70zJE4N0kBs4LovmEYWJzQGxC9bS9RAKu3bgM40lrd5zoLJ12MQ5BA=="], + + "resolve-pkg-maps": ["resolve-pkg-maps@1.0.0", "", {}, "sha512-seS2Tj26TBVOC2NIc2rOe2y2ZO7efxITtLZcGSOnHHNOQ7CkiUBfw0Iw2ck6xkIhPwLhKNLS8BO+hEpngQlqzw=="], + + "retry": ["retry@0.13.1", "", {}, "sha512-XQBQ3I8W1Cge0Seh+6gjj03LbmRFWuoszgK9ooCpwYIrhhoO80pfq4cUkU5DkknwfOfFteRwlZ56PYOGYyFWdg=="], + + "safer-buffer": ["safer-buffer@2.1.2", "", {}, "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg=="], + + "semver": ["semver@7.7.4", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-vFKC2IEtQnVhpT78h1Yp8wzwrf8CM+MzKMHGJZfBtzhZNycRFnXsHk6E5TxIkkMsgNS7mdX3AGB7x2QM2di4lA=="], + + "setprototypeof": ["setprototypeof@1.2.0", "", {}, "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw=="], + + "sharp": ["sharp@0.34.5", "", { "dependencies": { "@img/colour": "^1.0.0", "detect-libc": "^2.1.2", "semver": "^7.7.3" }, "optionalDependencies": { "@img/sharp-darwin-arm64": "0.34.5", "@img/sharp-darwin-x64": "0.34.5", "@img/sharp-libvips-darwin-arm64": "1.2.4", "@img/sharp-libvips-darwin-x64": "1.2.4", "@img/sharp-libvips-linux-arm": "1.2.4", "@img/sharp-libvips-linux-arm64": "1.2.4", "@img/sharp-libvips-linux-ppc64": "1.2.4", "@img/sharp-libvips-linux-riscv64": "1.2.4", "@img/sharp-libvips-linux-s390x": "1.2.4", "@img/sharp-libvips-linux-x64": "1.2.4", "@img/sharp-libvips-linuxmusl-arm64": "1.2.4", "@img/sharp-libvips-linuxmusl-x64": "1.2.4", "@img/sharp-linux-arm": "0.34.5", "@img/sharp-linux-arm64": "0.34.5", "@img/sharp-linux-ppc64": "0.34.5", "@img/sharp-linux-riscv64": "0.34.5", "@img/sharp-linux-s390x": "0.34.5", "@img/sharp-linux-x64": "0.34.5", "@img/sharp-linuxmusl-arm64": "0.34.5", "@img/sharp-linuxmusl-x64": "0.34.5", "@img/sharp-wasm32": "0.34.5", "@img/sharp-win32-arm64": "0.34.5", "@img/sharp-win32-ia32": "0.34.5", "@img/sharp-win32-x64": "0.34.5" } }, "sha512-Ou9I5Ft9WNcCbXrU9cMgPBcCK8LiwLqcbywW3t4oDV37n1pzpuNLsYiAV8eODnjbtQlSDwZ2cUEeQz4E54Hltg=="], + + "source-map": ["source-map@0.6.1", "", {}, "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g=="], + + "source-map-support": ["source-map-support@0.5.21", "", { "dependencies": { "buffer-from": "^1.0.0", "source-map": "^0.6.0" } }, "sha512-uBHU3L3czsIyYXKX88fdrGovxdSCoTGDRZ6SYXtSRxLZUzHg5P/66Ht6uoUlHu9EZod+inXhKo3qQgwXUT/y1w=="], + + "statuses": ["statuses@2.0.2", "", {}, "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw=="], + + "supports-color": ["supports-color@10.2.2", "", {}, "sha512-SS+jx45GF1QjgEXQx4NJZV9ImqmO2NPz5FNsIHrsDjh2YsHnawpan7SNQ1o8NuhrbHZy9AZhIoCUiCeaW/C80g=="], + + "toidentifier": ["toidentifier@1.0.1", "", {}, "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA=="], + + "tr46": ["tr46@0.0.3", "", {}, "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw=="], + + "tslib": ["tslib@2.8.1", "", {}, "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w=="], + + "typescript": ["typescript@5.9.3", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw=="], + + "undici": ["undici@7.18.2", "", {}, "sha512-y+8YjDFzWdQlSE9N5nzKMT3g4a5UBX1HKowfdXh0uvAnTaqqwqB92Jt4UXBAeKekDs5IaDKyJFR4X1gYVCgXcw=="], + + "undici-types": ["undici-types@6.21.0", "", {}, "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ=="], + + "unenv": ["unenv@2.0.0-rc.24", "", { "dependencies": { "pathe": "^2.0.3" } }, "sha512-i7qRCmY42zmCwnYlh9H2SvLEypEFGye5iRmEMKjcGi7zk9UquigRjFtTLz0TYqr0ZGLZhaMHl/foy1bZR+Cwlw=="], + + "unpipe": ["unpipe@1.0.0", "", {}, "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ=="], + + "webidl-conversions": ["webidl-conversions@3.0.1", "", {}, "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ=="], + + "whatwg-url": ["whatwg-url@5.0.0", "", { "dependencies": { "tr46": "~0.0.3", "webidl-conversions": "^3.0.0" } }, "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw=="], + + "which": ["which@4.0.0", "", { "dependencies": { "isexe": "^3.1.1" }, "bin": { "node-which": "bin/which.js" } }, "sha512-GlaYyEb07DPxYCKhKzplCWBJtvxZcZMrL+4UkrTSJHHPyZU4mYYTv3qaOe77H7EODLSSopAUFAc6W8U4yqvscg=="], + + "workerd": ["workerd@1.20260301.1", "", { "optionalDependencies": { "@cloudflare/workerd-darwin-64": "1.20260301.1", "@cloudflare/workerd-darwin-arm64": "1.20260301.1", "@cloudflare/workerd-linux-64": "1.20260301.1", "@cloudflare/workerd-linux-arm64": "1.20260301.1", "@cloudflare/workerd-windows-64": "1.20260301.1" }, "bin": { "workerd": "bin/workerd" } }, "sha512-oterQ1IFd3h7PjCfT4znSFOkJCvNQ6YMOyZ40YsnO3nrSpgB4TbJVYWFOnyJAw71/RQuupfVqZZWKvsy8GO3fw=="], + + "wrangler": ["wrangler@4.71.0", "", { "dependencies": { "@cloudflare/kv-asset-handler": "0.4.2", "@cloudflare/unenv-preset": "2.15.0", "blake3-wasm": "2.1.5", "esbuild": "0.27.3", "miniflare": "4.20260301.1", "path-to-regexp": "6.3.0", "unenv": "2.0.0-rc.24", "workerd": "1.20260301.1" }, "optionalDependencies": { "fsevents": "~2.3.2" }, "peerDependencies": { "@cloudflare/workers-types": "^4.20260226.1" }, "optionalPeers": ["@cloudflare/workers-types"], "bin": { "wrangler": "bin/wrangler.js", "wrangler2": "bin/wrangler.js" } }, "sha512-j6pSGAncOLNQDRzqtp0EqzYj52CldDP7uz/C9cxVrIgqa5p+cc0b4pIwnapZZAGv9E1Loa3tmPD0aXonH7KTkw=="], + + "ws": ["ws@8.18.0", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-8VbfWfHLbbwu3+N6OKsOMpBdT4kXPDDB9cJk2bJ6mh9ucxdlnNvH1e+roYkKmN9Nxw2yjz7VzeO9oOz2zJ04Pw=="], + + "youch": ["youch@4.1.0-beta.10", "", { "dependencies": { "@poppinss/colors": "^4.1.5", "@poppinss/dumper": "^0.6.4", "@speed-highlight/core": "^1.2.7", "cookie": "^1.0.2", "youch-core": "^0.3.3" } }, "sha512-rLfVLB4FgQneDr0dv1oddCVZmKjcJ6yX6mS4pU82Mq/Dt9a3cLZQ62pDBL4AUO+uVrCvtWz3ZFUL2HFAFJ/BXQ=="], + + "youch-core": ["youch-core@0.3.3", "", { "dependencies": { "@poppinss/exception": "^1.2.2", "error-stack-parser-es": "^1.0.5" } }, "sha512-ho7XuGjLaJ2hWHoK8yFnsUGy2Y5uDpqSTq1FkHLK4/oqKtyUU1AFbOOxY4IpC9f0fTLjwYbslUz0Po5BpD1wrA=="], + + "@esbuild-kit/core-utils/esbuild": ["esbuild@0.18.20", "", { "optionalDependencies": { "@esbuild/android-arm": "0.18.20", "@esbuild/android-arm64": "0.18.20", "@esbuild/android-x64": "0.18.20", "@esbuild/darwin-arm64": "0.18.20", "@esbuild/darwin-x64": "0.18.20", "@esbuild/freebsd-arm64": "0.18.20", "@esbuild/freebsd-x64": "0.18.20", "@esbuild/linux-arm": "0.18.20", "@esbuild/linux-arm64": "0.18.20", "@esbuild/linux-ia32": "0.18.20", "@esbuild/linux-loong64": "0.18.20", "@esbuild/linux-mips64el": "0.18.20", "@esbuild/linux-ppc64": "0.18.20", "@esbuild/linux-riscv64": "0.18.20", "@esbuild/linux-s390x": "0.18.20", "@esbuild/linux-x64": "0.18.20", "@esbuild/netbsd-x64": "0.18.20", "@esbuild/openbsd-x64": "0.18.20", "@esbuild/sunos-x64": "0.18.20", "@esbuild/win32-arm64": "0.18.20", "@esbuild/win32-ia32": "0.18.20", "@esbuild/win32-x64": "0.18.20" }, "bin": { "esbuild": "bin/esbuild" } }, "sha512-ceqxoedUrcayh7Y7ZX6NdbbDzGROiyVBgC4PriJThBKSVPWnnFHZAkfI1lJT8QFkOwH4qOS2SJkS4wvpGl8BpA=="], + + "httpanda/@types/node": ["@types/node@14.18.63", "", {}, "sha512-fAtCfv4jJg+ExtXhvCkCqUKZ+4ok/JQk01qDKhL5BDDoS3AxKXhV5/MAVUZyQnSEd2GT92fkgZl0pz0Q0AzcIQ=="], + + "wrangler/esbuild": ["esbuild@0.27.3", "", { "optionalDependencies": { "@esbuild/aix-ppc64": "0.27.3", "@esbuild/android-arm": "0.27.3", "@esbuild/android-arm64": "0.27.3", "@esbuild/android-x64": "0.27.3", "@esbuild/darwin-arm64": "0.27.3", "@esbuild/darwin-x64": "0.27.3", "@esbuild/freebsd-arm64": "0.27.3", "@esbuild/freebsd-x64": "0.27.3", "@esbuild/linux-arm": "0.27.3", "@esbuild/linux-arm64": "0.27.3", "@esbuild/linux-ia32": "0.27.3", "@esbuild/linux-loong64": "0.27.3", "@esbuild/linux-mips64el": "0.27.3", "@esbuild/linux-ppc64": "0.27.3", "@esbuild/linux-riscv64": "0.27.3", "@esbuild/linux-s390x": "0.27.3", "@esbuild/linux-x64": "0.27.3", "@esbuild/netbsd-arm64": "0.27.3", "@esbuild/netbsd-x64": "0.27.3", "@esbuild/openbsd-arm64": "0.27.3", "@esbuild/openbsd-x64": "0.27.3", "@esbuild/openharmony-arm64": "0.27.3", "@esbuild/sunos-x64": "0.27.3", "@esbuild/win32-arm64": "0.27.3", "@esbuild/win32-ia32": "0.27.3", "@esbuild/win32-x64": "0.27.3" }, "bin": { "esbuild": "bin/esbuild" } }, "sha512-8VwMnyGCONIs6cWue2IdpHxHnAjzxnw2Zr7MkVxB2vjmQ2ivqGFb4LEG3SMnv0Gb2F/G/2yA8zUaiL1gywDCCg=="], + + "@esbuild-kit/core-utils/esbuild/@esbuild/android-arm": ["@esbuild/android-arm@0.18.20", "", { "os": "android", "cpu": "arm" }, "sha512-fyi7TDI/ijKKNZTUJAQqiG5T7YjJXgnzkURqmGj13C6dCqckZBLdl4h7bkhHt/t0WP+zO9/zwroDvANaOqO5Sw=="], + + "@esbuild-kit/core-utils/esbuild/@esbuild/android-arm64": ["@esbuild/android-arm64@0.18.20", "", { "os": "android", "cpu": "arm64" }, "sha512-Nz4rJcchGDtENV0eMKUNa6L12zz2zBDXuhj/Vjh18zGqB44Bi7MBMSXjgunJgjRhCmKOjnPuZp4Mb6OKqtMHLQ=="], + + "@esbuild-kit/core-utils/esbuild/@esbuild/android-x64": ["@esbuild/android-x64@0.18.20", "", { "os": "android", "cpu": "x64" }, "sha512-8GDdlePJA8D6zlZYJV/jnrRAi6rOiNaCC/JclcXpB+KIuvfBN4owLtgzY2bsxnx666XjJx2kDPUmnTtR8qKQUg=="], + + "@esbuild-kit/core-utils/esbuild/@esbuild/darwin-arm64": ["@esbuild/darwin-arm64@0.18.20", "", { "os": "darwin", "cpu": "arm64" }, "sha512-bxRHW5kHU38zS2lPTPOyuyTm+S+eobPUnTNkdJEfAddYgEcll4xkT8DB9d2008DtTbl7uJag2HuE5NZAZgnNEA=="], + + "@esbuild-kit/core-utils/esbuild/@esbuild/darwin-x64": ["@esbuild/darwin-x64@0.18.20", "", { "os": "darwin", "cpu": "x64" }, "sha512-pc5gxlMDxzm513qPGbCbDukOdsGtKhfxD1zJKXjCCcU7ju50O7MeAZ8c4krSJcOIJGFR+qx21yMMVYwiQvyTyQ=="], + + "@esbuild-kit/core-utils/esbuild/@esbuild/freebsd-arm64": ["@esbuild/freebsd-arm64@0.18.20", "", { "os": "freebsd", "cpu": "arm64" }, "sha512-yqDQHy4QHevpMAaxhhIwYPMv1NECwOvIpGCZkECn8w2WFHXjEwrBn3CeNIYsibZ/iZEUemj++M26W3cNR5h+Tw=="], + + "@esbuild-kit/core-utils/esbuild/@esbuild/freebsd-x64": ["@esbuild/freebsd-x64@0.18.20", "", { "os": "freebsd", "cpu": "x64" }, "sha512-tgWRPPuQsd3RmBZwarGVHZQvtzfEBOreNuxEMKFcd5DaDn2PbBxfwLcj4+aenoh7ctXcbXmOQIn8HI6mCSw5MQ=="], + + "@esbuild-kit/core-utils/esbuild/@esbuild/linux-arm": ["@esbuild/linux-arm@0.18.20", "", { "os": "linux", "cpu": "arm" }, "sha512-/5bHkMWnq1EgKr1V+Ybz3s1hWXok7mDFUMQ4cG10AfW3wL02PSZi5kFpYKrptDsgb2WAJIvRcDm+qIvXf/apvg=="], + + "@esbuild-kit/core-utils/esbuild/@esbuild/linux-arm64": ["@esbuild/linux-arm64@0.18.20", "", { "os": "linux", "cpu": "arm64" }, "sha512-2YbscF+UL7SQAVIpnWvYwM+3LskyDmPhe31pE7/aoTMFKKzIc9lLbyGUpmmb8a8AixOL61sQ/mFh3jEjHYFvdA=="], + + "@esbuild-kit/core-utils/esbuild/@esbuild/linux-ia32": ["@esbuild/linux-ia32@0.18.20", "", { "os": "linux", "cpu": "ia32" }, "sha512-P4etWwq6IsReT0E1KHU40bOnzMHoH73aXp96Fs8TIT6z9Hu8G6+0SHSw9i2isWrD2nbx2qo5yUqACgdfVGx7TA=="], + + "@esbuild-kit/core-utils/esbuild/@esbuild/linux-loong64": ["@esbuild/linux-loong64@0.18.20", "", { "os": "linux", "cpu": "none" }, "sha512-nXW8nqBTrOpDLPgPY9uV+/1DjxoQ7DoB2N8eocyq8I9XuqJ7BiAMDMf9n1xZM9TgW0J8zrquIb/A7s3BJv7rjg=="], + + "@esbuild-kit/core-utils/esbuild/@esbuild/linux-mips64el": ["@esbuild/linux-mips64el@0.18.20", "", { "os": "linux", "cpu": "none" }, "sha512-d5NeaXZcHp8PzYy5VnXV3VSd2D328Zb+9dEq5HE6bw6+N86JVPExrA6O68OPwobntbNJ0pzCpUFZTo3w0GyetQ=="], + + "@esbuild-kit/core-utils/esbuild/@esbuild/linux-ppc64": ["@esbuild/linux-ppc64@0.18.20", "", { "os": "linux", "cpu": "ppc64" }, "sha512-WHPyeScRNcmANnLQkq6AfyXRFr5D6N2sKgkFo2FqguP44Nw2eyDlbTdZwd9GYk98DZG9QItIiTlFLHJHjxP3FA=="], + + "@esbuild-kit/core-utils/esbuild/@esbuild/linux-riscv64": ["@esbuild/linux-riscv64@0.18.20", "", { "os": "linux", "cpu": "none" }, "sha512-WSxo6h5ecI5XH34KC7w5veNnKkju3zBRLEQNY7mv5mtBmrP/MjNBCAlsM2u5hDBlS3NGcTQpoBvRzqBcRtpq1A=="], + + "@esbuild-kit/core-utils/esbuild/@esbuild/linux-s390x": ["@esbuild/linux-s390x@0.18.20", "", { "os": "linux", "cpu": "s390x" }, "sha512-+8231GMs3mAEth6Ja1iK0a1sQ3ohfcpzpRLH8uuc5/KVDFneH6jtAJLFGafpzpMRO6DzJ6AvXKze9LfFMrIHVQ=="], + + "@esbuild-kit/core-utils/esbuild/@esbuild/linux-x64": ["@esbuild/linux-x64@0.18.20", "", { "os": "linux", "cpu": "x64" }, "sha512-UYqiqemphJcNsFEskc73jQ7B9jgwjWrSayxawS6UVFZGWrAAtkzjxSqnoclCXxWtfwLdzU+vTpcNYhpn43uP1w=="], + + "@esbuild-kit/core-utils/esbuild/@esbuild/netbsd-x64": ["@esbuild/netbsd-x64@0.18.20", "", { "os": "none", "cpu": "x64" }, "sha512-iO1c++VP6xUBUmltHZoMtCUdPlnPGdBom6IrO4gyKPFFVBKioIImVooR5I83nTew5UOYrk3gIJhbZh8X44y06A=="], + + "@esbuild-kit/core-utils/esbuild/@esbuild/openbsd-x64": ["@esbuild/openbsd-x64@0.18.20", "", { "os": "openbsd", "cpu": "x64" }, "sha512-e5e4YSsuQfX4cxcygw/UCPIEP6wbIL+se3sxPdCiMbFLBWu0eiZOJ7WoD+ptCLrmjZBK1Wk7I6D/I3NglUGOxg=="], + + "@esbuild-kit/core-utils/esbuild/@esbuild/sunos-x64": ["@esbuild/sunos-x64@0.18.20", "", { "os": "sunos", "cpu": "x64" }, "sha512-kDbFRFp0YpTQVVrqUd5FTYmWo45zGaXe0X8E1G/LKFC0v8x0vWrhOWSLITcCn63lmZIxfOMXtCfti/RxN/0wnQ=="], + + "@esbuild-kit/core-utils/esbuild/@esbuild/win32-arm64": ["@esbuild/win32-arm64@0.18.20", "", { "os": "win32", "cpu": "arm64" }, "sha512-ddYFR6ItYgoaq4v4JmQQaAI5s7npztfV4Ag6NrhiaW0RrnOXqBkgwZLofVTlq1daVTQNhtI5oieTvkRPfZrePg=="], + + "@esbuild-kit/core-utils/esbuild/@esbuild/win32-ia32": ["@esbuild/win32-ia32@0.18.20", "", { "os": "win32", "cpu": "ia32" }, "sha512-Wv7QBi3ID/rROT08SABTS7eV4hX26sVduqDOTe1MvGMjNd3EjOz4b7zeexIR62GTIEKrfJXKL9LFxTYgkyeu7g=="], + + "@esbuild-kit/core-utils/esbuild/@esbuild/win32-x64": ["@esbuild/win32-x64@0.18.20", "", { "os": "win32", "cpu": "x64" }, "sha512-kTdfRcSiDfQca/y9QIkng02avJ+NCaQvrMejlsB3RRv5sE9rRoeBPISaZpKxHELzRxZyLvNts1P27W3wV+8geQ=="], + + "wrangler/esbuild/@esbuild/aix-ppc64": ["@esbuild/aix-ppc64@0.27.3", "", { "os": "aix", "cpu": "ppc64" }, "sha512-9fJMTNFTWZMh5qwrBItuziu834eOCUcEqymSH7pY+zoMVEZg3gcPuBNxH1EvfVYe9h0x/Ptw8KBzv7qxb7l8dg=="], + + "wrangler/esbuild/@esbuild/android-arm": ["@esbuild/android-arm@0.27.3", "", { "os": "android", "cpu": "arm" }, "sha512-i5D1hPY7GIQmXlXhs2w8AWHhenb00+GxjxRncS2ZM7YNVGNfaMxgzSGuO8o8SJzRc/oZwU2bcScvVERk03QhzA=="], + + "wrangler/esbuild/@esbuild/android-arm64": ["@esbuild/android-arm64@0.27.3", "", { "os": "android", "cpu": "arm64" }, "sha512-YdghPYUmj/FX2SYKJ0OZxf+iaKgMsKHVPF1MAq/P8WirnSpCStzKJFjOjzsW0QQ7oIAiccHdcqjbHmJxRb/dmg=="], + + "wrangler/esbuild/@esbuild/android-x64": ["@esbuild/android-x64@0.27.3", "", { "os": "android", "cpu": "x64" }, "sha512-IN/0BNTkHtk8lkOM8JWAYFg4ORxBkZQf9zXiEOfERX/CzxW3Vg1ewAhU7QSWQpVIzTW+b8Xy+lGzdYXV6UZObQ=="], + + "wrangler/esbuild/@esbuild/darwin-arm64": ["@esbuild/darwin-arm64@0.27.3", "", { "os": "darwin", "cpu": "arm64" }, "sha512-Re491k7ByTVRy0t3EKWajdLIr0gz2kKKfzafkth4Q8A5n1xTHrkqZgLLjFEHVD+AXdUGgQMq+Godfq45mGpCKg=="], + + "wrangler/esbuild/@esbuild/darwin-x64": ["@esbuild/darwin-x64@0.27.3", "", { "os": "darwin", "cpu": "x64" }, "sha512-vHk/hA7/1AckjGzRqi6wbo+jaShzRowYip6rt6q7VYEDX4LEy1pZfDpdxCBnGtl+A5zq8iXDcyuxwtv3hNtHFg=="], + + "wrangler/esbuild/@esbuild/freebsd-arm64": ["@esbuild/freebsd-arm64@0.27.3", "", { "os": "freebsd", "cpu": "arm64" }, "sha512-ipTYM2fjt3kQAYOvo6vcxJx3nBYAzPjgTCk7QEgZG8AUO3ydUhvelmhrbOheMnGOlaSFUoHXB6un+A7q4ygY9w=="], + + "wrangler/esbuild/@esbuild/freebsd-x64": ["@esbuild/freebsd-x64@0.27.3", "", { "os": "freebsd", "cpu": "x64" }, "sha512-dDk0X87T7mI6U3K9VjWtHOXqwAMJBNN2r7bejDsc+j03SEjtD9HrOl8gVFByeM0aJksoUuUVU9TBaZa2rgj0oA=="], + + "wrangler/esbuild/@esbuild/linux-arm": ["@esbuild/linux-arm@0.27.3", "", { "os": "linux", "cpu": "arm" }, "sha512-s6nPv2QkSupJwLYyfS+gwdirm0ukyTFNl3KTgZEAiJDd+iHZcbTPPcWCcRYH+WlNbwChgH2QkE9NSlNrMT8Gfw=="], + + "wrangler/esbuild/@esbuild/linux-arm64": ["@esbuild/linux-arm64@0.27.3", "", { "os": "linux", "cpu": "arm64" }, "sha512-sZOuFz/xWnZ4KH3YfFrKCf1WyPZHakVzTiqji3WDc0BCl2kBwiJLCXpzLzUBLgmp4veFZdvN5ChW4Eq/8Fc2Fg=="], + + "wrangler/esbuild/@esbuild/linux-ia32": ["@esbuild/linux-ia32@0.27.3", "", { "os": "linux", "cpu": "ia32" }, "sha512-yGlQYjdxtLdh0a3jHjuwOrxQjOZYD/C9PfdbgJJF3TIZWnm/tMd/RcNiLngiu4iwcBAOezdnSLAwQDPqTmtTYg=="], + + "wrangler/esbuild/@esbuild/linux-loong64": ["@esbuild/linux-loong64@0.27.3", "", { "os": "linux", "cpu": "none" }, "sha512-WO60Sn8ly3gtzhyjATDgieJNet/KqsDlX5nRC5Y3oTFcS1l0KWba+SEa9Ja1GfDqSF1z6hif/SkpQJbL63cgOA=="], + + "wrangler/esbuild/@esbuild/linux-mips64el": ["@esbuild/linux-mips64el@0.27.3", "", { "os": "linux", "cpu": "none" }, "sha512-APsymYA6sGcZ4pD6k+UxbDjOFSvPWyZhjaiPyl/f79xKxwTnrn5QUnXR5prvetuaSMsb4jgeHewIDCIWljrSxw=="], + + "wrangler/esbuild/@esbuild/linux-ppc64": ["@esbuild/linux-ppc64@0.27.3", "", { "os": "linux", "cpu": "ppc64" }, "sha512-eizBnTeBefojtDb9nSh4vvVQ3V9Qf9Df01PfawPcRzJH4gFSgrObw+LveUyDoKU3kxi5+9RJTCWlj4FjYXVPEA=="], + + "wrangler/esbuild/@esbuild/linux-riscv64": ["@esbuild/linux-riscv64@0.27.3", "", { "os": "linux", "cpu": "none" }, "sha512-3Emwh0r5wmfm3ssTWRQSyVhbOHvqegUDRd0WhmXKX2mkHJe1SFCMJhagUleMq+Uci34wLSipf8Lagt4LlpRFWQ=="], + + "wrangler/esbuild/@esbuild/linux-s390x": ["@esbuild/linux-s390x@0.27.3", "", { "os": "linux", "cpu": "s390x" }, "sha512-pBHUx9LzXWBc7MFIEEL0yD/ZVtNgLytvx60gES28GcWMqil8ElCYR4kvbV2BDqsHOvVDRrOxGySBM9Fcv744hw=="], + + "wrangler/esbuild/@esbuild/linux-x64": ["@esbuild/linux-x64@0.27.3", "", { "os": "linux", "cpu": "x64" }, "sha512-Czi8yzXUWIQYAtL/2y6vogER8pvcsOsk5cpwL4Gk5nJqH5UZiVByIY8Eorm5R13gq+DQKYg0+JyQoytLQas4dA=="], + + "wrangler/esbuild/@esbuild/netbsd-arm64": ["@esbuild/netbsd-arm64@0.27.3", "", { "os": "none", "cpu": "arm64" }, "sha512-sDpk0RgmTCR/5HguIZa9n9u+HVKf40fbEUt+iTzSnCaGvY9kFP0YKBWZtJaraonFnqef5SlJ8/TiPAxzyS+UoA=="], + + "wrangler/esbuild/@esbuild/netbsd-x64": ["@esbuild/netbsd-x64@0.27.3", "", { "os": "none", "cpu": "x64" }, "sha512-P14lFKJl/DdaE00LItAukUdZO5iqNH7+PjoBm+fLQjtxfcfFE20Xf5CrLsmZdq5LFFZzb5JMZ9grUwvtVYzjiA=="], + + "wrangler/esbuild/@esbuild/openbsd-arm64": ["@esbuild/openbsd-arm64@0.27.3", "", { "os": "openbsd", "cpu": "arm64" }, "sha512-AIcMP77AvirGbRl/UZFTq5hjXK+2wC7qFRGoHSDrZ5v5b8DK/GYpXW3CPRL53NkvDqb9D+alBiC/dV0Fb7eJcw=="], + + "wrangler/esbuild/@esbuild/openbsd-x64": ["@esbuild/openbsd-x64@0.27.3", "", { "os": "openbsd", "cpu": "x64" }, "sha512-DnW2sRrBzA+YnE70LKqnM3P+z8vehfJWHXECbwBmH/CU51z6FiqTQTHFenPlHmo3a8UgpLyH3PT+87OViOh1AQ=="], + + "wrangler/esbuild/@esbuild/openharmony-arm64": ["@esbuild/openharmony-arm64@0.27.3", "", { "os": "none", "cpu": "arm64" }, "sha512-NinAEgr/etERPTsZJ7aEZQvvg/A6IsZG/LgZy+81wON2huV7SrK3e63dU0XhyZP4RKGyTm7aOgmQk0bGp0fy2g=="], + + "wrangler/esbuild/@esbuild/sunos-x64": ["@esbuild/sunos-x64@0.27.3", "", { "os": "sunos", "cpu": "x64" }, "sha512-PanZ+nEz+eWoBJ8/f8HKxTTD172SKwdXebZ0ndd953gt1HRBbhMsaNqjTyYLGLPdoWHy4zLU7bDVJztF5f3BHA=="], + + "wrangler/esbuild/@esbuild/win32-arm64": ["@esbuild/win32-arm64@0.27.3", "", { "os": "win32", "cpu": "arm64" }, "sha512-B2t59lWWYrbRDw/tjiWOuzSsFh1Y/E95ofKz7rIVYSQkUYBjfSgf6oeYPNWHToFRr2zx52JKApIcAS/D5TUBnA=="], + + "wrangler/esbuild/@esbuild/win32-ia32": ["@esbuild/win32-ia32@0.27.3", "", { "os": "win32", "cpu": "ia32" }, "sha512-QLKSFeXNS8+tHW7tZpMtjlNb7HKau0QDpwm49u0vUp9y1WOF+PEzkU84y9GqYaAVW8aH8f3GcBck26jh54cX4Q=="], + + "wrangler/esbuild/@esbuild/win32-x64": ["@esbuild/win32-x64@0.27.3", "", { "os": "win32", "cpu": "x64" }, "sha512-4uJGhsxuptu3OcpVAzli+/gWusVGwZZHTlS63hh++ehExkVT8SgiEf7/uC/PclrPPkLhZqGgCTjd0VWLo6xMqA=="], + } +} diff --git a/drizzle.config.ts b/drizzle.config.ts new file mode 100644 index 00000000..e44c16ec --- /dev/null +++ b/drizzle.config.ts @@ -0,0 +1,8 @@ +import { defineConfig } from 'drizzle-kit'; + +export default defineConfig({ + schema: './src/db/schema.ts', + out: './drizzle', + dialect: 'sqlite', + driver: 'd1-http', +}); diff --git a/drizzle/0000_init.sql b/drizzle/0000_init.sql new file mode 100644 index 00000000..2f0f7b67 --- /dev/null +++ b/drizzle/0000_init.sql @@ -0,0 +1,50 @@ +CREATE TABLE `channels` ( + `id` text PRIMARY KEY NOT NULL, + `channel_id` text NOT NULL, + `service` text DEFAULT 'twitch' NOT NULL, + `is_live` integer DEFAULT false NOT NULL, + `title` text, + `category` text, + `updated_at` text +); +--> statement-breakpoint +CREATE TABLE `chat_settings` ( + `id` text PRIMARY KEY NOT NULL, + `chat_id` text NOT NULL, + `game_change_notification` integer DEFAULT true NOT NULL, + `title_change_notification` integer DEFAULT false NOT NULL, + `game_and_title_change_notification` integer DEFAULT false NOT NULL, + `offline_notification` integer DEFAULT true NOT NULL, + `image_in_notification` integer DEFAULT true NOT NULL, + `language` text DEFAULT 'en' NOT NULL, + FOREIGN KEY (`chat_id`) REFERENCES `chats`(`id`) ON UPDATE no action ON DELETE cascade +); +--> statement-breakpoint +CREATE UNIQUE INDEX `chat_settings_chat_id_unique` ON `chat_settings` (`chat_id`);--> statement-breakpoint +CREATE TABLE `chats` ( + `id` text PRIMARY KEY NOT NULL, + `chat_id` text NOT NULL, + `service` text DEFAULT 'telegram' NOT NULL +); +--> statement-breakpoint +CREATE TABLE `follows` ( + `id` text PRIMARY KEY NOT NULL, + `channel_id` text NOT NULL, + `chat_id` text NOT NULL, + FOREIGN KEY (`channel_id`) REFERENCES `channels`(`id`) ON UPDATE no action ON DELETE cascade, + FOREIGN KEY (`chat_id`) REFERENCES `chats`(`id`) ON UPDATE no action ON DELETE cascade +); +--> statement-breakpoint +CREATE TABLE `streams` ( + `id` text PRIMARY KEY NOT NULL, + `channel_id` text NOT NULL, + `is_live` integer DEFAULT true NOT NULL, + `title` text, + `category` text, + `titles` text DEFAULT '[]' NOT NULL, + `categories` text DEFAULT '[]' NOT NULL, + `started_at` text, + `updated_at` text, + `ended_at` text, + FOREIGN KEY (`channel_id`) REFERENCES `channels`(`id`) ON UPDATE no action ON DELETE cascade +); diff --git a/drizzle/meta/0000_snapshot.json b/drizzle/meta/0000_snapshot.json new file mode 100644 index 00000000..5ce87c82 --- /dev/null +++ b/drizzle/meta/0000_snapshot.json @@ -0,0 +1,360 @@ +{ + "version": "6", + "dialect": "sqlite", + "id": "080aa910-8403-4fd5-8fb8-a1b4af4465dc", + "prevId": "00000000-0000-0000-0000-000000000000", + "tables": { + "channels": { + "name": "channels", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "channel_id": { + "name": "channel_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "service": { + "name": "service", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'twitch'" + }, + "is_live": { + "name": "is_live", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "category": { + "name": "category", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "chat_settings": { + "name": "chat_settings", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "chat_id": { + "name": "chat_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "game_change_notification": { + "name": "game_change_notification", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": true + }, + "title_change_notification": { + "name": "title_change_notification", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "game_and_title_change_notification": { + "name": "game_and_title_change_notification", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "offline_notification": { + "name": "offline_notification", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": true + }, + "image_in_notification": { + "name": "image_in_notification", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": true + }, + "language": { + "name": "language", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'en'" + } + }, + "indexes": { + "chat_settings_chat_id_unique": { + "name": "chat_settings_chat_id_unique", + "columns": [ + "chat_id" + ], + "isUnique": true + } + }, + "foreignKeys": { + "chat_settings_chat_id_chats_id_fk": { + "name": "chat_settings_chat_id_chats_id_fk", + "tableFrom": "chat_settings", + "tableTo": "chats", + "columnsFrom": [ + "chat_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "chats": { + "name": "chats", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "chat_id": { + "name": "chat_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "service": { + "name": "service", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'telegram'" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "follows": { + "name": "follows", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "channel_id": { + "name": "channel_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "chat_id": { + "name": "chat_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": { + "follows_channel_id_channels_id_fk": { + "name": "follows_channel_id_channels_id_fk", + "tableFrom": "follows", + "tableTo": "channels", + "columnsFrom": [ + "channel_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "follows_chat_id_chats_id_fk": { + "name": "follows_chat_id_chats_id_fk", + "tableFrom": "follows", + "tableTo": "chats", + "columnsFrom": [ + "chat_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "streams": { + "name": "streams", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "channel_id": { + "name": "channel_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "is_live": { + "name": "is_live", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "category": { + "name": "category", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "titles": { + "name": "titles", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'[]'" + }, + "categories": { + "name": "categories", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'[]'" + }, + "started_at": { + "name": "started_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "ended_at": { + "name": "ended_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": { + "streams_channel_id_channels_id_fk": { + "name": "streams_channel_id_channels_id_fk", + "tableFrom": "streams", + "tableTo": "channels", + "columnsFrom": [ + "channel_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + } + }, + "views": {}, + "enums": {}, + "_meta": { + "schemas": {}, + "tables": {}, + "columns": {} + }, + "internal": { + "indexes": {} + } +} \ No newline at end of file diff --git a/drizzle/meta/0001_snapshot.json b/drizzle/meta/0001_snapshot.json new file mode 100644 index 00000000..5401acb4 --- /dev/null +++ b/drizzle/meta/0001_snapshot.json @@ -0,0 +1,398 @@ +{ + "version": "6", + "dialect": "sqlite", + "id": "8e53b4b2-0bbe-4525-8758-07164adab3f9", + "prevId": "080aa910-8403-4fd5-8fb8-a1b4af4465dc", + "tables": { + "channels": { + "name": "channels", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "channel_id": { + "name": "channel_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "service": { + "name": "service", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'twitch'" + }, + "is_live": { + "name": "is_live", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "category": { + "name": "category", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "chat_settings": { + "name": "chat_settings", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "chat_id": { + "name": "chat_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "game_change_notification": { + "name": "game_change_notification", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": true + }, + "title_change_notification": { + "name": "title_change_notification", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "game_and_title_change_notification": { + "name": "game_and_title_change_notification", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "offline_notification": { + "name": "offline_notification", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": true + }, + "image_in_notification": { + "name": "image_in_notification", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": true + }, + "language": { + "name": "language", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'en'" + } + }, + "indexes": { + "chat_settings_chat_id_unique": { + "name": "chat_settings_chat_id_unique", + "columns": [ + "chat_id" + ], + "isUnique": true + } + }, + "foreignKeys": { + "chat_settings_chat_id_chats_id_fk": { + "name": "chat_settings_chat_id_chats_id_fk", + "tableFrom": "chat_settings", + "tableTo": "chats", + "columnsFrom": [ + "chat_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "chats": { + "name": "chats", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "chat_id": { + "name": "chat_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "service": { + "name": "service", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'telegram'" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "follows": { + "name": "follows", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "channel_id": { + "name": "channel_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "chat_id": { + "name": "chat_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": { + "follows_channel_id_channels_id_fk": { + "name": "follows_channel_id_channels_id_fk", + "tableFrom": "follows", + "tableTo": "channels", + "columnsFrom": [ + "channel_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "follows_chat_id_chats_id_fk": { + "name": "follows_chat_id_chats_id_fk", + "tableFrom": "follows", + "tableTo": "chats", + "columnsFrom": [ + "chat_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "sessions": { + "name": "sessions", + "columns": { + "key": { + "name": "key", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "value": { + "name": "value", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "expires_at": { + "name": "expires_at", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "streams": { + "name": "streams", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "channel_id": { + "name": "channel_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "is_live": { + "name": "is_live", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "category": { + "name": "category", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "titles": { + "name": "titles", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'[]'" + }, + "categories": { + "name": "categories", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'[]'" + }, + "started_at": { + "name": "started_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "ended_at": { + "name": "ended_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": { + "streams_channel_id_channels_id_fk": { + "name": "streams_channel_id_channels_id_fk", + "tableFrom": "streams", + "tableTo": "channels", + "columnsFrom": [ + "channel_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + } + }, + "views": {}, + "enums": {}, + "_meta": { + "schemas": {}, + "tables": {}, + "columns": {} + }, + "internal": { + "indexes": {} + } +} \ No newline at end of file diff --git a/drizzle/meta/_journal.json b/drizzle/meta/_journal.json new file mode 100644 index 00000000..c15c5130 --- /dev/null +++ b/drizzle/meta/_journal.json @@ -0,0 +1,20 @@ +{ + "version": "7", + "dialect": "sqlite", + "entries": [ + { + "idx": 0, + "version": "6", + "when": 1773043588513, + "tag": "0000_init", + "breakpoints": true + }, + { + "idx": 1, + "version": "6", + "when": 1773045439236, + "tag": "0001_loose_crystal", + "breakpoints": true + } + ] +} \ No newline at end of file diff --git a/locales/en.json b/locales/en.json index b085e55f..24d3ea04 100644 --- a/locales/en.json +++ b/locales/en.json @@ -29,9 +29,10 @@ "total": "You followed to notifications from {{ count }} channels. Click on streamer nickname to unfollow from notifications." }, - "unfollow": { - "callbackButton": "Unfollow {{ streamer }}" - }, + "unfollow": { + "callbackButton": "Unfollow {{ streamer }}", + "success": "Unfollowed from {{ streamer }}" + }, "start": { "game_change_notification_setting": { diff --git a/locales/ru.json b/locales/ru.json index ab6c1c17..085bccf9 100644 --- a/locales/ru.json +++ b/locales/ru.json @@ -24,6 +24,10 @@ "follows": { "total": "Вы подписаны на уведомления {{ count }} каналов. Кликните на никнейм стримера, чтобы отписаться от уведомлений." }, + "unfollow": { + "callbackButton": "Отписаться от {{ streamer }}", + "success": "Вы отписались от {{ streamer }}" + }, "start": { "game_change_notification_setting": { "button": "Уведомление о смене категории" diff --git a/locales/uk.json b/locales/uk.json index a5cf3974..e144e844 100644 --- a/locales/uk.json +++ b/locales/uk.json @@ -24,6 +24,10 @@ "follows": { "total": "Ви підписані на сповіщення від {{ count }} каналів. Клацніть на нікнейм стрімера, щоб відписатись від сповіщень." }, + "unfollow": { + "callbackButton": "Відписатись від {{ streamer }}", + "success": "Ви відписались від {{ streamer }}" + }, "start": { "game_change_notification_setting": { "button": "Сповіщення про зміну категорії" diff --git a/package.json b/package.json new file mode 100644 index 00000000..b40b977a --- /dev/null +++ b/package.json @@ -0,0 +1,40 @@ +{ + "name": "twitch-notifier", + "version": "2.0.0", + "type": "module", + "description": "Telegram bot for Twitch stream notifications on Cloudflare Workers", + "main": "src/index.ts", + "scripts": { + "dev": "wrangler dev", + "deploy": "wrangler deploy", + "db:generate": "drizzle-kit generate", + "db:migrate": "wrangler d1 migrations apply twitch-notifier-db", + "db:migrate:local": "wrangler d1 migrations apply twitch-notifier-db --local", + "db:studio": "drizzle-kit studio" + }, + "keywords": [ + "telegram", + "twitch", + "notifications", + "serverless" + ], + "author": "Satont ", + "license": "MIT", + "dependencies": { + "@grammyjs/conversations": "2.1.1", + "@twurple/api": "8.0.3", + "@twurple/auth": "8.0.3", + "@twurple/eventsub-http": "8.0.3", + "drizzle-orm": "0.45.1", + "grammy": "1.41.1", + "hono": "^4.7.11", + "i18next": "25.8.14" + }, + "devDependencies": { + "@cloudflare/workers-types": "4.20260307.1", + "@types/node": "^22.10.6", + "drizzle-kit": "0.31.9", + "typescript": "^5.7.3", + "wrangler": "4.71.0" + } +} diff --git a/src/bot/commands/broadcast.command.ts b/src/bot/commands/broadcast.command.ts new file mode 100644 index 00000000..5a801cc5 --- /dev/null +++ b/src/bot/commands/broadcast.command.ts @@ -0,0 +1,48 @@ +import { Composer } from 'grammy'; +import type { BotContext } from '../types'; +import type { Env } from '../../types/env'; + +export function createBroadcastCommand(env: Env) { + const broadcast = new Composer(); + + const isAdmin = (userId: number): boolean => { + const admins = env.TELEGRAM_BOT_ADMINS.split(',').map(id => parseInt(id.trim())); + return admins.includes(userId); + }; + + broadcast.command('broadcast', async (ctx) => { + const userId = ctx.from?.id; + if (!userId || !isAdmin(userId)) { + return; + } + + const text = ctx.message?.text?.replace('/broadcast', '').trim(); + if (!text) { + await ctx.reply('Usage: /broadcast '); + return; + } + + // Get all chats (only positive IDs = private chats/groups) + const allChats = await ctx.services.chatRepo.findAllByService('telegram'); + + let sent = 0; + let failed = 0; + + for (const chat of allChats) { + const chatIdNum = parseInt(chat.chatId); + if (chatIdNum <= 0) continue; // Skip channels/supergroups + + try { + await ctx.api.sendMessage(chatIdNum, text); + sent++; + } catch (error) { + console.error(`Failed to send to ${chat.chatId}:`, error); + failed++; + } + } + + await ctx.reply(`Broadcast completed!\nSent: ${sent}\nFailed: ${failed}`); + }); + + return broadcast; +} diff --git a/src/bot/commands/callback.handler.ts b/src/bot/commands/callback.handler.ts new file mode 100644 index 00000000..1e6a14b9 --- /dev/null +++ b/src/bot/commands/callback.handler.ts @@ -0,0 +1,74 @@ +import { Composer } from 'grammy'; +import type { BotContext } from '../types'; +import type { SupportedLanguage } from '../../services/i18n.service'; +import { + sendSettingsMenu, + sendLanguagePicker, + handleToggleSetting, + handleUnfollow, + buildFollowsKeyboard +} from '../helpers'; + +export const callbackQueryHandler = new Composer(); + +callbackQueryHandler.on('callback_query:data', async (ctx) => { + const data = ctx.callbackQuery.data; + const chatId = ctx.chat?.id; + if (!chatId) return; + + const chat = await ctx.services.chatRepo.findByChatId(chatId, 'telegram'); + if (!chat || !chat.settings) return; + + // Handle toggle settings + if (data.startsWith('toggle_')) { + await handleToggleSetting(ctx, data, chat); + await sendSettingsMenu(ctx, chat); + } + + // Handle language picker + else if (data === 'language_picker') { + await sendLanguagePicker(ctx); + } + + // Handle language selection + else if (data.startsWith('language_picker_set_')) { + const lang = data.replace('language_picker_set_', '') as SupportedLanguage; + if (ctx.services.i18n.isValidLocale(lang)) { + await ctx.services.chatRepo.updateSettings(chat.settings.id, { language: lang }); + ctx.session.language = lang; + await ctx.answerCallbackQuery( + ctx.services.i18n.t(lang, 'language.changed') + ); + await sendLanguagePicker(ctx); + } + } + + // Handle back to main menu + else if (data === 'start_command_menu') { + await sendSettingsMenu(ctx, chat); + } + + // Handle unfollow + else if (data.startsWith('channels_unfollow_')) { + const channelId = data.replace('channels_unfollow_', ''); + await handleUnfollow(ctx, chat, channelId); + } + + // Handle pagination + else if (data === 'channels_unfollow_prev_page') { + if (ctx.session.followsMenu && ctx.session.followsMenu.currentPage > 1) { + ctx.session.followsMenu.currentPage--; + } + const keyboard = await buildFollowsKeyboard(ctx, chat.id); + await ctx.editMessageReplyMarkup({ reply_markup: keyboard }); + } + else if (data === 'channels_unfollow_next_page') { + if (ctx.session.followsMenu && ctx.session.followsMenu.currentPage < ctx.session.followsMenu.totalPages) { + ctx.session.followsMenu.currentPage++; + } + const keyboard = await buildFollowsKeyboard(ctx, chat.id); + await ctx.editMessageReplyMarkup({ reply_markup: keyboard }); + } + + await ctx.answerCallbackQuery(); +}); diff --git a/src/bot/commands/change-channel-id.command.ts b/src/bot/commands/change-channel-id.command.ts new file mode 100644 index 00000000..f7513f2e --- /dev/null +++ b/src/bot/commands/change-channel-id.command.ts @@ -0,0 +1,45 @@ +import { Composer } from 'grammy'; +import type { BotContext } from '../types'; +import type { Env } from '../../types/env'; + +export function createChangeChannelIdCommand(env: Env) { + const changeChannelId = new Composer(); + + const isAdmin = (userId: number): boolean => { + const admins = env.TELEGRAM_BOT_ADMINS.split(',').map(id => parseInt(id.trim())); + return admins.includes(userId); + }; + + changeChannelId.command('change_channel_id', async (ctx) => { + const userId = ctx.from?.id; + if (!userId || !isAdmin(userId)) { + return; + } + + const text = ctx.message?.text?.replace('/change_channel_id', '').trim(); + + if (!text) { + await ctx.reply('Usage: /change_channel_id '); + return; + } + + const parts = text.split(' '); + + if (parts.length !== 2) { + await ctx.reply('Usage: /change_channel_id '); + return; + } + + const [oldId, newId] = parts; + + try { + await ctx.services.channelRepo.updateChannelId(oldId, newId, 'twitch'); + await ctx.reply('Channel ID updated successfully!'); + } catch (error) { + console.error('Error updating channel ID:', error); + await ctx.reply('Error updating channel ID.'); + } + }); + + return changeChannelId; +} diff --git a/src/bot/commands/follow.command.ts b/src/bot/commands/follow.command.ts new file mode 100644 index 00000000..b1ea7945 --- /dev/null +++ b/src/bot/commands/follow.command.ts @@ -0,0 +1,121 @@ +import { Composer } from 'grammy'; +import type { BotContext } from '../types'; + +export const followCommand = new Composer(); + +followCommand.command('follow', async (ctx) => { + const text = ctx.message?.text?.replace('/follow', '').trim(); + + if (!text) { + await ctx.reply( + ctx.t('commands.follow.enter') + ); + ctx.session.scene = 'follow'; + return; + } + + await handleFollow(ctx, text); +}); + +// Handle follow scene +followCommand.on('message:text', async (ctx, next) => { + if (ctx.session.scene === 'follow') { + await handleFollow(ctx, ctx.message.text); + ctx.session.scene = undefined; + return; + } + await next(); +}); + +async function handleFollow(ctx: BotContext, text: string) { + const chatId = ctx.chat?.id; + if (!chatId) return; + + const chat = await ctx.services.chatRepo.findByChatId(chatId, 'telegram'); + if (!chat) return; + + // Extract Twitch username from text or URL + const twitchLinkRegex = /(?:https?:\/\/)?(?:www\.)?twitch\.tv\/(\w+)/g; + const matches = Array.from(text.matchAll(twitchLinkRegex)); + + const usernames = matches.length > 0 + ? matches.map(m => m[1]) + : [text.trim()]; + + const results: string[] = []; + + for (const username of usernames) { + // Validate username + if (!/^[a-zA-Z0-9_]{3,25}$/.test(username)) { + results.push( + ctx.t( + 'commands.follow.errors.badUsername', + { streamer: username } + ) + ); + continue; + } + + try { + // Get Twitch user + const twitchUser = await ctx.services.twitch.getUserByLogin(username); + + if (!twitchUser) { + results.push( + ctx.t( + 'commands.follow.errors.streamerNotFound', + { streamer: username } + ) + ); + continue; + } + + // Get or create channel + let channel = await ctx.services.channelRepo.findByChannelId(twitchUser.id, 'twitch'); + if (!channel) { + channel = await ctx.services.channelRepo.create(twitchUser.id, 'twitch'); + } + + // Create follow + try { + await ctx.services.followRepo.create(chat.id, channel.id); + + // Subscribe to EventSub events for this channel + // Check if we already have subscriptions for this channel + const hasSubscriptions = await ctx.services.eventsub.hasActiveSubscriptions(twitchUser.id); + if (!hasSubscriptions) { + try { + await ctx.services.eventsub.subscribeToChannel(twitchUser.id); + console.log(`Subscribed to EventSub for channel ${twitchUser.id}`); + } catch (eventSubError) { + console.error(`Failed to subscribe to EventSub for ${twitchUser.id}:`, eventSubError); + // Don't fail the follow if EventSub subscription fails + } + } + + results.push( + ctx.t( + 'commands.follow.success', + { streamer: username } + ) + ); + } catch (error: any) { + if (error.message?.includes('UNIQUE constraint failed')) { + results.push( + ctx.t( + 'commands.follow.errors.alreadyFollowed', + { streamer: username } + ) + ); + } else { + throw error; + } + } + } catch (error) { + console.error('Error following user:', error); + results.push(`${username} - internal error`); + } + } + + await ctx.reply(results.join('\n')); +} diff --git a/src/bot/commands/follows.command.ts b/src/bot/commands/follows.command.ts new file mode 100644 index 00000000..2768816d --- /dev/null +++ b/src/bot/commands/follows.command.ts @@ -0,0 +1,37 @@ +import { Composer } from 'grammy'; +import type { BotContext } from '../types'; +import { buildFollowsKeyboard } from '../helpers'; + +export const followsCommand = new Composer(); + +followsCommand.command(['follows', 'unfollow'], async (ctx) => { + const chatId = ctx.chat?.id; + if (!chatId) return; + + const chat = await ctx.services.chatRepo.findByChatId(chatId, 'telegram'); + if (!chat) return; + + ctx.session.followsMenu = { + currentPage: 1, + totalPages: 1, + }; + + const totalFollows = await ctx.services.followRepo.countByChatId(chat.id); + + if (totalFollows === 0) { + await ctx.reply('You are not following any channels.'); + return; + } + + const keyboard = await buildFollowsKeyboard(ctx, chat.id); + + await ctx.reply( + ctx.t( + 'commands.follows.total', + { count: totalFollows.toString() } + ), + { + reply_markup: keyboard, + } + ); +}); diff --git a/src/bot/commands/index.ts b/src/bot/commands/index.ts new file mode 100644 index 00000000..a64b3652 --- /dev/null +++ b/src/bot/commands/index.ts @@ -0,0 +1,7 @@ +export { startCommand } from './start.command'; +export { followCommand } from './follow.command'; +export { followsCommand } from './follows.command'; +export { liveCommand } from './live.command'; +export { createBroadcastCommand } from './broadcast.command'; +export { createChangeChannelIdCommand } from './change-channel-id.command'; +export { callbackQueryHandler } from './callback.handler'; diff --git a/src/bot/commands/live.command.ts b/src/bot/commands/live.command.ts new file mode 100644 index 00000000..7545e79f --- /dev/null +++ b/src/bot/commands/live.command.ts @@ -0,0 +1,102 @@ +import { Composer } from 'grammy'; +import type { BotContext } from '../types'; + +export const liveCommand = new Composer(); + +liveCommand.command('live', async (ctx) => { + const chatId = ctx.chat?.id; + if (!chatId) return; + + const chat = await ctx.services.chatRepo.findByChatId(chatId, 'telegram'); + if (!chat) return; + + const follows = await ctx.services.followRepo.findByChatId(chat.id); + + if (follows.length === 0) { + await ctx.reply('You are not following any channels.'); + return; + } + + // Get all followed channel IDs + const channelIds: string[] = []; + for (const follow of follows) { + const channel = await ctx.services.channelRepo.findById(follow.channelId); + if (channel) { + channelIds.push(channel.channelId); + } + } + + if (channelIds.length === 0) { + await ctx.reply('No channels found.'); + return; + } + + // Get live streams + const liveChannels: Array<{ + name: string; + login: string; + startedAt: Date; + title: string; + category: string; + viewers: number; + }> = []; + + for (const channelId of channelIds) { + const stream = await ctx.services.twitch.getStreamByUserId(channelId); + if (stream) { + const user = await ctx.services.twitch.getUserById(channelId); + if (user) { + liveChannels.push({ + name: user.displayName, + login: user.name, + startedAt: stream.startDate, + title: stream.title, + category: stream.gameName, + viewers: stream.viewers, + }); + } + } + } + + if (liveChannels.length === 0) { + await ctx.reply('No one is online.'); + return; + } + + // Build message + const messages: string[] = []; + for (const channel of liveChannels) { + const channelMessage: string[] = []; + + channelMessage.push( + `🟢 ${channel.name} - ${channel.viewers} 👁️️` + ); + + if (channel.category) { + channelMessage.push(`🎮 ${channel.category}`); + } + + if (channel.title) { + channelMessage.push(`📝 ${channel.title}`); + } + + // Calculate uptime + const uptime = Date.now() - channel.startedAt.getTime(); + const hours = Math.floor(uptime / 3600000); + const minutes = Math.floor((uptime % 3600000) / 60000); + const seconds = Math.floor((uptime % 60000) / 1000); + + let uptimeStr = '⌛ '; + if (hours > 0) uptimeStr += `${hours}h `; + if (minutes > 0) uptimeStr += `${minutes}m `; + if (seconds > 0) uptimeStr += `${seconds}s `; + + channelMessage.push(uptimeStr); + messages.push(channelMessage.join('\n')); + } + + await ctx.reply(messages.join('\n\n'), { + parse_mode: 'HTML', + link_preview_options: { is_disabled: true }, + }); +}); diff --git a/src/bot/commands/start.command.ts b/src/bot/commands/start.command.ts new file mode 100644 index 00000000..51c3ff05 --- /dev/null +++ b/src/bot/commands/start.command.ts @@ -0,0 +1,28 @@ +import { Composer } from 'grammy'; +import type { BotContext } from '../types'; +import type { SupportedLanguage } from '../../services/i18n.service'; +import { sendSettingsMenu } from '../helpers'; + +export const startCommand = new Composer(); + +startCommand.command(['start', 'help', 'info', 'settings'], async (ctx) => { + const chatId = ctx.chat?.id; + if (!chatId) return; + + // Get or create chat in database + let chat = await ctx.services.chatRepo.findByChatId(chatId, 'telegram'); + if (!chat) { + await ctx.services.chatRepo.create(chatId.toString(), 'telegram'); + // Fetch the chat again to get it with settings + chat = await ctx.services.chatRepo.findByChatId(chatId, 'telegram'); + } + + // Update session language + if (chat?.settings) { + ctx.session.language = chat.settings.language as SupportedLanguage; + } + + if (chat) { + await sendSettingsMenu(ctx, chat); + } +}); diff --git a/src/bot/helpers.ts b/src/bot/helpers.ts new file mode 100644 index 00000000..cce0cd30 --- /dev/null +++ b/src/bot/helpers.ts @@ -0,0 +1,184 @@ +import type { BotContext } from './types'; +import type { Chat } from '../domain/models'; +import { InlineKeyboard } from 'grammy'; + +export async function sendSettingsMenu(ctx: BotContext, chat: Chat) { + const settings = chat.settings; + if (!settings) return; + + const createCheckmark = (value: boolean) => value ? '✅' : '❌'; + + const keyboard = new InlineKeyboard() + .text( + `${createCheckmark(settings.gameChangeNotification)} ${ctx.t('commands.start.game_change_notification_setting.button')}`, + 'toggle_game_change' + ).row() + .text( + `${createCheckmark(settings.offlineNotification)} ${ctx.t('commands.start.offline_notification.button')}`, + 'toggle_offline' + ).row() + .text( + `${createCheckmark(settings.titleChangeNotification)} ${ctx.t('commands.start.title_change_notification_setting.button')}`, + 'toggle_title_change' + ).row() + .text( + `${createCheckmark(settings.gameAndTitleChangeNotification)} ${ctx.t('commands.start.game_and_title_change_notification_setting.button')}`, + 'toggle_game_and_title' + ).row() + .text( + `${createCheckmark(settings.imageInNotification)} ${ctx.t('commands.start.image_in_notification_setting.button')}`, + 'toggle_image' + ).row() + .text( + ctx.t('commands.start.language.button'), + 'language_picker' + ).row() + .url('Github', 'https://github.com/Satont/twitch-notifier'); + + const description = ctx.t('bot.description'); + + if (ctx.callbackQuery) { + await ctx.editMessageText(description, { reply_markup: keyboard }); + } else { + await ctx.reply(description, { reply_markup: keyboard }); + } +} + +export async function sendLanguagePicker(ctx: BotContext) { + const keyboard = new InlineKeyboard(); + + const locales = ctx.services.i18n.getAvailableLocales(); + for (const locale of locales) { + const emoji = ctx.services.i18n.t(locale, 'language.emoji'); + const name = ctx.services.i18n.t(locale, 'language.name'); + keyboard.text(`${emoji} ${name}`, `language_picker_set_${locale}`).row(); + } + keyboard.text('«', 'start_command_menu'); + + const text = ctx.t('language.select'); + + if (ctx.callbackQuery) { + await ctx.editMessageText(text, { reply_markup: keyboard }); + } else { + await ctx.reply(text, { reply_markup: keyboard }); + } +} + +export async function buildFollowsKeyboard(ctx: BotContext, chatId: string): Promise { + const follows = await ctx.services.followRepo.findByChatId(chatId); + const keyboard = new InlineKeyboard(); + + for (const follow of follows) { + const channel = await ctx.services.channelRepo.findById(follow.channelId); + if (!channel) continue; + + const twitchUser = await ctx.services.twitch.getUserById(channel.channelId); + if (!twitchUser) continue; + + keyboard.text(twitchUser.displayName, `channels_unfollow_${channel.channelId}`).row(); + } + + // Add pagination buttons if needed + if (ctx.session.followsMenu) { + const { currentPage, totalPages } = ctx.session.followsMenu; + if (totalPages > 1) { + keyboard.text('«', 'channels_unfollow_prev_page'); + keyboard.text('»', 'channels_unfollow_next_page'); + } + } + + return keyboard; +} + +export async function handleToggleSetting(ctx: BotContext, data: string, chat: Chat) { + const chatId = ctx.chat?.id; + if (!chatId || !chat.settings) return; + + const updates: any = {}; + + switch (data) { + case 'toggle_game_change': + updates.gameChangeNotification = !chat.settings.gameChangeNotification; + chat.settings.gameChangeNotification = updates.gameChangeNotification; + break; + case 'toggle_offline': + updates.offlineNotification = !chat.settings.offlineNotification; + chat.settings.offlineNotification = updates.offlineNotification; + break; + case 'toggle_title_change': + updates.titleChangeNotification = !chat.settings.titleChangeNotification; + chat.settings.titleChangeNotification = updates.titleChangeNotification; + break; + case 'toggle_game_and_title': + updates.gameAndTitleChangeNotification = !chat.settings.gameAndTitleChangeNotification; + chat.settings.gameAndTitleChangeNotification = updates.gameAndTitleChangeNotification; + break; + case 'toggle_image': + updates.imageInNotification = !chat.settings.imageInNotification; + chat.settings.imageInNotification = updates.imageInNotification; + break; + } + + if (Object.keys(updates).length > 0) { + await ctx.services.chatRepo.updateSettings(chat.settings.id, updates); + } +} + +export async function handleUnfollow(ctx: BotContext, chat: Chat, channelIdFromCallback: string) { + const channel = await ctx.services.channelRepo.findById(channelIdFromCallback); + if (!channel) { + await ctx.answerCallbackQuery('Channel not found'); + return; + } + + const follow = await ctx.services.followRepo.findByChatAndChannel(chat.id, channel.id); + if (!follow) { + await ctx.answerCallbackQuery('Already unfollowed'); + return; + } + + const twitchUser = await ctx.services.twitch.getUserById(channel.channelId); + const streamerName = twitchUser?.displayName || channel.channelId; + + await ctx.services.followRepo.delete(follow.id); + + // Check if this channel still has followers + const remainingFollows = await ctx.services.followRepo.findByChannelId(channel.id); + + // If no followers remain, unsubscribe from EventSub + if (remainingFollows.length === 0) { + try { + await ctx.services.eventsub.unsubscribeFromChannel(channel.channelId); + console.log(`Unsubscribed from EventSub for channel ${channel.channelId}`); + } catch (error) { + console.error(`Failed to unsubscribe from EventSub for ${channel.channelId}:`, error); + // Don't fail the unfollow if EventSub unsubscription fails + } + } + + await ctx.answerCallbackQuery( + ctx.t('commands.unfollow.success', { + streamer: streamerName, + }) + ); + + // Update keyboard + const totalFollows = await ctx.services.followRepo.countByChatId(chat.id); + + if (totalFollows === 0) { + await ctx.editMessageText('You are not following any channels.'); + await ctx.editMessageReplyMarkup({ reply_markup: new InlineKeyboard() }); + return; + } + + const keyboard = await buildFollowsKeyboard(ctx, chat.id); + + await ctx.editMessageText( + ctx.t('commands.follows.total', { + count: totalFollows.toString(), + }), + { + reply_markup: keyboard, + } + ); +} diff --git a/src/bot/index.ts b/src/bot/index.ts new file mode 100644 index 00000000..3a663672 --- /dev/null +++ b/src/bot/index.ts @@ -0,0 +1,71 @@ +import { Bot } from 'grammy'; +import { session } from 'grammy' +import type { Env } from '../types/env'; +import type { BotSession, BotContext } from './types'; +import { I18nService } from '../services/i18n.service'; +import { TwitchService } from '../services/twitch.service'; +import { EventSubService } from '../services/eventsub.service'; +import { DatabaseSessionStorage } from './storage'; +import type { IChatRepository, IChannelRepository, IFollowRepository, ISessionRepository } from '../db/repositories/interfaces'; +import { + startCommand, + followCommand, + followsCommand, + liveCommand, + createBroadcastCommand, + createChangeChannelIdCommand, + callbackQueryHandler +} from './commands'; + +export function createBot( + env: Env, + services: { + i18n: I18nService; + twitch: TwitchService; + eventsub: EventSubService; + chatRepo: IChatRepository; + channelRepo: IChannelRepository; + followRepo: IFollowRepository; + sessionRepo: ISessionRepository; + } +): Bot { + const bot = new Bot(env.TELEGRAM_TOKEN); + + // Use database session storage + const sessionStorage = new DatabaseSessionStorage( + services.sessionRepo, + 86400 // 24 hours TTL + ); + + bot.use(session({ + initial: (): BotSession => ({ + language: 'en', + followsMenu: { + currentPage: 1, + totalPages: 1, + }, + }), + storage: sessionStorage, + })) + + // Attach environment and services to context + bot.use(async (ctx, next) => { + ctx.env = env; + ctx.services = services; + await next(); + }); + + // Use i18n middleware + bot.use(services.i18n.middleware()); + + // Register commands + bot.use(startCommand); + bot.use(followCommand); + bot.use(followsCommand); + bot.use(liveCommand); + bot.use(createBroadcastCommand(env)); + bot.use(createChangeChannelIdCommand(env)); + bot.use(callbackQueryHandler); + + return bot; +} diff --git a/src/bot/storage.ts b/src/bot/storage.ts new file mode 100644 index 00000000..c3a2f443 --- /dev/null +++ b/src/bot/storage.ts @@ -0,0 +1,47 @@ +import type { StorageAdapter } from 'grammy'; +import type { ISessionRepository } from '../db/repositories/interfaces'; + +/** + * Storage adapter for Grammy sessions using database persistence + * Works with any ISessionRepository implementation (D1, PostgreSQL, etc.) + */ +export class DatabaseSessionStorage implements StorageAdapter { + constructor( + private sessionRepo: ISessionRepository, + private ttl?: number // Time to live in seconds + ) {} + + async read(key: string): Promise { + const value = await this.sessionRepo.get(key); + if (!value) return undefined; + + try { + return JSON.parse(value) as T; + } catch (error) { + console.error('Failed to parse session data:', error); + return undefined; + } + } + + async write(key: string, value: T): Promise { + const expiresAt = this.ttl ? Date.now() + this.ttl * 1000 : undefined; + await this.sessionRepo.set(key, JSON.stringify(value), expiresAt); + } + + async delete(key: string): Promise { + await this.sessionRepo.delete(key); + } + + async has(key: string): Promise { + const value = await this.sessionRepo.get(key); + return value !== undefined; + } + + /** + * Clean up expired sessions + * Should be called periodically (e.g., via cron job) + */ + async cleanup(): Promise { + await this.sessionRepo.cleanup(); + } +} diff --git a/src/bot/types.ts b/src/bot/types.ts new file mode 100644 index 00000000..33a44fc5 --- /dev/null +++ b/src/bot/types.ts @@ -0,0 +1,33 @@ +import type { Context, SessionFlavor } from 'grammy'; +import type { ConversationFlavor } from '@grammyjs/conversations'; +import type { SupportedLanguage } from '../services/i18n.service'; +import type { Env } from '../types/env'; +import type { DrizzleD1Database } from 'drizzle-orm/d1'; +import type { I18nService, TwitchService, EventSubService } from '../services'; +import type { IChatRepository, IChannelRepository, IFollowRepository } from '../db/repositories/interfaces'; + +export interface BotSession { + chatId?: number; + language: SupportedLanguage; + scene?: string; + followsMenu?: { + currentPage: number; + totalPages: number; + }; +} + +export type BotContext = Context & + SessionFlavor & + ConversationFlavor & { + t: (key: string, params?: Record) => string; + env: Env; + db: DrizzleD1Database; + services: { + i18n: I18nService; + twitch: TwitchService; + eventsub: EventSubService; + chatRepo: IChatRepository; + channelRepo: IChannelRepository; + followRepo: IFollowRepository; + }; + }; diff --git a/src/db/connection.ts b/src/db/connection.ts new file mode 100644 index 00000000..b9628d02 --- /dev/null +++ b/src/db/connection.ts @@ -0,0 +1,20 @@ +import type { DrizzleD1Database } from 'drizzle-orm/d1'; + +/** + * Database connection abstraction + * This allows us to support different database implementations (D1, PostgreSQL, etc.) + */ +export interface IDatabaseConnection { + getClient(): any; // Returns the underlying database client (DrizzleD1Database, etc.) +} + +/** + * Cloudflare D1 database connection + */ +export class CloudflareD1Connection implements IDatabaseConnection { + constructor(private client: DrizzleD1Database) {} + + getClient(): DrizzleD1Database { + return this.client; + } +} diff --git a/src/db/index.ts b/src/db/index.ts new file mode 100644 index 00000000..1e560f7c --- /dev/null +++ b/src/db/index.ts @@ -0,0 +1,3 @@ +import { drizzle } from 'drizzle-orm/d1'; + +export default drizzle; diff --git a/src/db/repositories/cloudflare-kv/index.ts b/src/db/repositories/cloudflare-kv/index.ts new file mode 100644 index 00000000..84a81496 --- /dev/null +++ b/src/db/repositories/cloudflare-kv/index.ts @@ -0,0 +1 @@ +export * from './session.kv.repository'; diff --git a/src/db/repositories/cloudflare-kv/session.kv.repository.ts b/src/db/repositories/cloudflare-kv/session.kv.repository.ts new file mode 100644 index 00000000..692bb465 --- /dev/null +++ b/src/db/repositories/cloudflare-kv/session.kv.repository.ts @@ -0,0 +1,38 @@ +import type { KVNamespace } from '@cloudflare/workers-types'; +import type { ISessionRepository } from '../interfaces/session.repository.interface'; + +/** + * Cloudflare KV-based session repository + * Fast, distributed key-value storage perfect for sessions + */ +export class CloudflareKVSessionRepository implements ISessionRepository { + constructor(private readonly kv: KVNamespace) {} + + async get(key: string): Promise { + const value = await this.kv.get(key); + return value ?? undefined; + } + + async set(key: string, value: string, expiresAt?: number): Promise { + const options: { expirationTtl?: number } = {}; + + // Convert expiresAt (unix timestamp) to TTL in seconds + if (expiresAt) { + const ttl = Math.floor((expiresAt - Date.now()) / 1000); + if (ttl > 0) { + options.expirationTtl = ttl; + } + } + + await this.kv.put(key, value, options); + } + + async delete(key: string): Promise { + await this.kv.delete(key); + } + + async cleanup(): Promise { + // KV automatically cleans up expired keys, no manual cleanup needed + return; + } +} diff --git a/src/db/repositories/drizzle/channel.drizzle.repository.ts b/src/db/repositories/drizzle/channel.drizzle.repository.ts new file mode 100644 index 00000000..559edfc5 --- /dev/null +++ b/src/db/repositories/drizzle/channel.drizzle.repository.ts @@ -0,0 +1,65 @@ +import type { DrizzleD1Database } from 'drizzle-orm/d1'; +import { eq, and } from 'drizzle-orm'; +import { randomUUID } from 'node:crypto'; +import { channels } from '../../schema'; +import type { NewChannel } from '../../schema'; +import { Channel, ChannelNotFoundError } from '../../../domain/models'; +import { DomainMapper } from '../../../domain/mapper'; +import type { IChannelRepository } from '../interfaces'; + +export class ChannelDrizzleRepository implements IChannelRepository { + constructor(private db: DrizzleD1Database) {} + + async findByChannelId(channelId: string, service: 'twitch' = 'twitch'): Promise { + const result = await this.db + .select() + .from(channels) + .where(and(eq(channels.channelId, channelId), eq(channels.service, service))) + .limit(1); + + return result[0] ? DomainMapper.toDomainChannel(result[0]) : undefined; + } + + async findById(id: string): Promise { + const result = await this.db + .select() + .from(channels) + .where(eq(channels.id, id)) + .limit(1); + + return result[0] ? DomainMapper.toDomainChannel(result[0]) : undefined; + } + + async create(channelId: string, service: 'twitch' = 'twitch'): Promise { + const id = randomUUID(); + const result = await this.db.insert(channels).values({ + id, + channelId, + service, + isLive: false, + }).returning(); + + return DomainMapper.toDomainChannel(result[0]); + } + + async update(id: string, data: Partial>): Promise { + const result = await this.db + .update(channels) + .set({ ...data, updatedAt: new Date().toISOString() }) + .where(eq(channels.id, id)) + .returning(); + + if (!result[0]) { + throw new ChannelNotFoundError(); + } + + return DomainMapper.toDomainChannel(result[0]); + } + + async updateChannelId(oldChannelId: string, newChannelId: string, service: 'twitch' = 'twitch'): Promise { + await this.db + .update(channels) + .set({ channelId: newChannelId, updatedAt: new Date().toISOString() }) + .where(and(eq(channels.channelId, oldChannelId), eq(channels.service, service))); + } +} diff --git a/src/db/repositories/drizzle/chat.drizzle.repository.ts b/src/db/repositories/drizzle/chat.drizzle.repository.ts new file mode 100644 index 00000000..ffa5cc37 --- /dev/null +++ b/src/db/repositories/drizzle/chat.drizzle.repository.ts @@ -0,0 +1,104 @@ +import type { DrizzleD1Database } from 'drizzle-orm/d1'; +import { eq } from 'drizzle-orm'; +import { randomUUID } from 'node:crypto'; +import { chats, chatSettings } from '../../schema'; +import { Chat, ChatSettings } from '../../../domain/models'; +import { DomainMapper } from '../../../domain/mapper'; +import type { IChatRepository } from '../interfaces'; + +export class ChatDrizzleRepository implements IChatRepository { + constructor(private db: DrizzleD1Database) {} + + async findByChatId(chatId: number, service: 'telegram' = 'telegram'): Promise { + const chatIdStr = chatId.toString(); + + const chatResult = await this.db + .select() + .from(chats) + .where(eq(chats.chatId, chatIdStr)) + .limit(1); + + if (!chatResult[0]) return undefined; + + const settingsResult = await this.db + .select() + .from(chatSettings) + .where(eq(chatSettings.chatId, chatResult[0].id)) + .limit(1); + + return DomainMapper.toDomainChat({ + ...chatResult[0], + settings: settingsResult[0] || null + }); + } + + async findById(id: string): Promise { + const chatResult = await this.db + .select() + .from(chats) + .where(eq(chats.id, id)) + .limit(1); + + if (!chatResult[0]) return undefined; + + const settingsResult = await this.db + .select() + .from(chatSettings) + .where(eq(chatSettings.chatId, chatResult[0].id)) + .limit(1); + + return DomainMapper.toDomainChat({ + ...chatResult[0], + settings: settingsResult[0] || null + }); + } + + async findAllByService(service: 'telegram' = 'telegram'): Promise { + const chatResults = await this.db + .select() + .from(chats) + .where(eq(chats.service, service)); + + const chatsWithSettings: Chat[] = []; + + for (const chat of chatResults) { + const settingsResult = await this.db + .select() + .from(chatSettings) + .where(eq(chatSettings.chatId, chat.id)) + .limit(1); + + chatsWithSettings.push(DomainMapper.toDomainChat({ + ...chat, + settings: settingsResult[0] || null + })); + } + + return chatsWithSettings; + } + + async create(chatId: string, service: 'telegram' = 'telegram'): Promise { + const id = randomUUID(); + await this.db.insert(chats).values({ id, chatId, service }); + + // Create default settings + await this.db.insert(chatSettings).values({ + chatId: id, + language: 'en', + offlineNotification: true, + gameChangeNotification: false, + titleChangeNotification: false, + gameAndTitleChangeNotification: false, + imageInNotification: true, + }); + + return id; + } + + async updateSettings(chatId: string, settings: Partial): Promise { + await this.db + .update(chatSettings) + .set(settings) + .where(eq(chatSettings.chatId, chatId)); + } +} diff --git a/src/db/repositories/drizzle/follow.drizzle.repository.ts b/src/db/repositories/drizzle/follow.drizzle.repository.ts new file mode 100644 index 00000000..a8b22b28 --- /dev/null +++ b/src/db/repositories/drizzle/follow.drizzle.repository.ts @@ -0,0 +1,82 @@ +import type { DrizzleD1Database } from 'drizzle-orm/d1'; +import { eq, and, count } from 'drizzle-orm'; +import { randomUUID } from 'node:crypto'; +import { follows } from '../../schema'; +import { Follow, FollowAlreadyExistsError, FollowNotFoundError } from '../../../domain/models'; +import { DomainMapper } from '../../../domain/mapper'; +import type { IFollowRepository } from '../interfaces'; + +export class FollowDrizzleRepository implements IFollowRepository { + constructor(private db: DrizzleD1Database) {} + + async findByChatAndChannel(chatId: string, channelId: string): Promise { + const result = await this.db + .select() + .from(follows) + .where(and(eq(follows.chatId, chatId), eq(follows.channelId, channelId))) + .limit(1); + + return result[0] ? DomainMapper.toDomainFollow(result[0]) : undefined; + } + + async findByChatId(chatId: string): Promise { + const results = await this.db + .select() + .from(follows) + .where(eq(follows.chatId, chatId)); + + return results.map(r => DomainMapper.toDomainFollow(r)); + } + + async create(chatId: string, channelId: string): Promise { + // Check if already exists + const existing = await this.findByChatAndChannel(chatId, channelId); + if (existing) { + throw new FollowAlreadyExistsError(); + } + + const id = randomUUID(); + await this.db.insert(follows).values({ id, chatId, channelId }); + return id; + } + + async delete(id: string): Promise { + const result = await this.db + .delete(follows) + .where(eq(follows.id, id)) + .returning(); + + if (result.length === 0) { + throw new FollowNotFoundError(); + } + } + + async findByChannelId(channelId: string): Promise { + const results = await this.db + .select() + .from(follows) + .where(eq(follows.channelId, channelId)); + + return results.map(r => DomainMapper.toDomainFollow(r)); + } + + async findByChatIdPaginated(chatId: string, limit: number, offset: number): Promise { + const results = await this.db + .select() + .from(follows) + .where(eq(follows.chatId, chatId)) + .limit(limit) + .offset(offset); + + return results.map(r => DomainMapper.toDomainFollow(r)); + } + + async countByChatId(chatId: string): Promise { + const result = await this.db + .select({ count: count() }) + .from(follows) + .where(eq(follows.chatId, chatId)); + + return result[0]?.count ?? 0; + } +} diff --git a/src/db/repositories/drizzle/index.ts b/src/db/repositories/drizzle/index.ts new file mode 100644 index 00000000..84a91a1e --- /dev/null +++ b/src/db/repositories/drizzle/index.ts @@ -0,0 +1,4 @@ +export * from './chat.drizzle.repository'; +export * from './channel.drizzle.repository'; +export * from './follow.drizzle.repository'; +export * from './stream.drizzle.repository'; diff --git a/src/db/repositories/drizzle/stream.drizzle.repository.ts b/src/db/repositories/drizzle/stream.drizzle.repository.ts new file mode 100644 index 00000000..1db49c8f --- /dev/null +++ b/src/db/repositories/drizzle/stream.drizzle.repository.ts @@ -0,0 +1,60 @@ +import type { DrizzleD1Database } from 'drizzle-orm/d1'; +import { eq, desc } from 'drizzle-orm'; +import { streams } from '../../schema'; +import { Stream } from '../../../domain/models'; +import { DomainMapper } from '../../../domain/mapper'; +import type { IStreamRepository } from '../interfaces'; + +export class StreamDrizzleRepository implements IStreamRepository { + constructor(private db: DrizzleD1Database) {} + + async findLatestByChannelId(channelId: string): Promise { + const result = await this.db + .select() + .from(streams) + .where(eq(streams.channelId, channelId)) + .orderBy(desc(streams.startedAt)) + .limit(1); + + return result[0] ? DomainMapper.toDomainStream(result[0]) : undefined; + } + + async create(id: string, channelId: string, category: string, title: string): Promise { + await this.db.insert(streams).values({ + id, + channelId, + isLive: true, + category, + title, + startedAt: new Date().toISOString(), + titles: [title] as any, + categories: [category] as any, + }); + + return id; + } + + async update(id: string, data: { isLive?: boolean; category?: string; title?: string; endedAt?: string }): Promise { + const result = await this.db + .update(streams) + .set(data) + .where(eq(streams.id, id)) + .returning(); + + if (!result[0]) { + throw new Error('Stream not found'); + } + + return DomainMapper.toDomainStream(result[0]); + } + + async findById(id: string): Promise { + const result = await this.db + .select() + .from(streams) + .where(eq(streams.id, id)) + .limit(1); + + return result[0] ? DomainMapper.toDomainStream(result[0]) : undefined; + } +} diff --git a/src/db/repositories/index.ts b/src/db/repositories/index.ts new file mode 100644 index 00000000..dbbbef31 --- /dev/null +++ b/src/db/repositories/index.ts @@ -0,0 +1,20 @@ +// Export interfaces +export * from './interfaces'; + +// Export Drizzle implementations +export * from './drizzle'; + +// Re-export commonly used types for convenience +export type { + IChatRepository, + IChannelRepository, + IFollowRepository, + IStreamRepository +} from './interfaces'; + +export type { + ChatDrizzleRepository, + ChannelDrizzleRepository, + FollowDrizzleRepository, + StreamDrizzleRepository +} from './drizzle'; diff --git a/src/db/repositories/interfaces/channel.repository.interface.ts b/src/db/repositories/interfaces/channel.repository.interface.ts new file mode 100644 index 00000000..1a570203 --- /dev/null +++ b/src/db/repositories/interfaces/channel.repository.interface.ts @@ -0,0 +1,10 @@ +import type { Channel } from '../../../domain/models'; +import type { NewChannel } from '../../schema'; + +export interface IChannelRepository { + findByChannelId(channelId: string, service: 'twitch'): Promise; + findById(id: string): Promise; + create(channelId: string, service: 'twitch'): Promise; + update(id: string, data: Partial>): Promise; + updateChannelId(oldChannelId: string, newChannelId: string, service: 'twitch'): Promise; +} diff --git a/src/db/repositories/interfaces/chat.repository.interface.ts b/src/db/repositories/interfaces/chat.repository.interface.ts new file mode 100644 index 00000000..94d0b4d8 --- /dev/null +++ b/src/db/repositories/interfaces/chat.repository.interface.ts @@ -0,0 +1,9 @@ +import type { Chat, ChatSettings } from '../../../domain/models'; + +export interface IChatRepository { + findByChatId(chatId: number, service: 'telegram'): Promise; + findById(id: string): Promise; + findAllByService(service: 'telegram'): Promise; + create(chatId: string, service: 'telegram'): Promise; + updateSettings(chatId: string, settings: Partial): Promise; +} diff --git a/src/db/repositories/interfaces/follow.repository.interface.ts b/src/db/repositories/interfaces/follow.repository.interface.ts new file mode 100644 index 00000000..24dcc014 --- /dev/null +++ b/src/db/repositories/interfaces/follow.repository.interface.ts @@ -0,0 +1,11 @@ +import type { Follow } from '../../../domain/models'; + +export interface IFollowRepository { + findByChatAndChannel(chatId: string, channelId: string): Promise; + findByChatId(chatId: string): Promise; + create(chatId: string, channelId: string): Promise; + delete(id: string): Promise; + findByChannelId(channelId: string): Promise; + findByChatIdPaginated(chatId: string, limit: number, offset: number): Promise; + countByChatId(chatId: string): Promise; +} diff --git a/src/db/repositories/interfaces/index.ts b/src/db/repositories/interfaces/index.ts new file mode 100644 index 00000000..c46f45e7 --- /dev/null +++ b/src/db/repositories/interfaces/index.ts @@ -0,0 +1,5 @@ +export * from './chat.repository.interface'; +export * from './channel.repository.interface'; +export * from './follow.repository.interface'; +export * from './stream.repository.interface'; +export * from './session.repository.interface'; diff --git a/src/db/repositories/interfaces/session.repository.interface.ts b/src/db/repositories/interfaces/session.repository.interface.ts new file mode 100644 index 00000000..13dcc9ec --- /dev/null +++ b/src/db/repositories/interfaces/session.repository.interface.ts @@ -0,0 +1,6 @@ +export interface ISessionRepository { + get(key: string): Promise; + set(key: string, value: string, expiresAt?: number): Promise; + delete(key: string): Promise; + cleanup(): Promise; // Remove expired sessions +} diff --git a/src/db/repositories/interfaces/stream.repository.interface.ts b/src/db/repositories/interfaces/stream.repository.interface.ts new file mode 100644 index 00000000..120cf1eb --- /dev/null +++ b/src/db/repositories/interfaces/stream.repository.interface.ts @@ -0,0 +1,15 @@ +import type { Stream } from '../../../domain/models'; + +export interface IStreamRepository { + findLatestByChannelId(channelId: string): Promise; + create(id: string, channelId: string, category: string, title: string): Promise; + update(id: string, data: { + isLive?: boolean; + category?: string; + title?: string; + endedAt?: string; + categories?: string[]; + titles?: string[]; + }): Promise; + findById(id: string): Promise; +} diff --git a/src/db/repository.factory.ts b/src/db/repository.factory.ts new file mode 100644 index 00000000..9557fe86 --- /dev/null +++ b/src/db/repository.factory.ts @@ -0,0 +1,44 @@ +import type { + IChatRepository, + IChannelRepository, + IFollowRepository, + IStreamRepository +} from './repositories/interfaces'; +import { + ChatDrizzleRepository, + ChannelDrizzleRepository, + FollowDrizzleRepository, + StreamDrizzleRepository +} from './repositories/drizzle'; +import type { IDatabaseConnection } from './connection'; + +export interface IRepositoryFactory { + createChatRepository(): IChatRepository; + createChannelRepository(): IChannelRepository; + createFollowRepository(): IFollowRepository; + createStreamRepository(): IStreamRepository; +} + +/** + * Factory for creating Drizzle-based repositories + * Works with any Drizzle-compatible database (D1, PostgreSQL, etc.) + */ +export class DrizzleRepositoryFactory implements IRepositoryFactory { + constructor(private connection: IDatabaseConnection) {} + + createChatRepository(): IChatRepository { + return new ChatDrizzleRepository(this.connection.getClient()); + } + + createChannelRepository(): IChannelRepository { + return new ChannelDrizzleRepository(this.connection.getClient()); + } + + createFollowRepository(): IFollowRepository { + return new FollowDrizzleRepository(this.connection.getClient()); + } + + createStreamRepository(): IStreamRepository { + return new StreamDrizzleRepository(this.connection.getClient()); + } +} diff --git a/src/db/schema.ts b/src/db/schema.ts new file mode 100644 index 00000000..f95abbe0 --- /dev/null +++ b/src/db/schema.ts @@ -0,0 +1,108 @@ +import { sqliteTable, text, integer } from 'drizzle-orm/sqlite-core'; +import { relations } from 'drizzle-orm'; +import { randomUUID } from 'node:crypto'; + +// Chat table +export const chats = sqliteTable('chats', { + id: text('id').primaryKey().$defaultFn(() => randomUUID()), + chatId: text('chat_id').notNull(), + service: text('service', { enum: ['telegram'] }).notNull().default('telegram'), +}); + +export const chatsRelations = relations(chats, ({ one, many }) => ({ + settings: one(chatSettings, { + fields: [chats.id], + references: [chatSettings.chatId], + }), + follows: many(follows), +})); + +// Chat Settings table +export const chatSettings = sqliteTable('chat_settings', { + id: text('id').primaryKey().$defaultFn(() => randomUUID()), + chatId: text('chat_id').notNull().unique().references(() => chats.id, { onDelete: 'cascade' }), + gameChangeNotification: integer('game_change_notification', { mode: 'boolean' }).notNull().default(true), + titleChangeNotification: integer('title_change_notification', { mode: 'boolean' }).notNull().default(false), + gameAndTitleChangeNotification: integer('game_and_title_change_notification', { mode: 'boolean' }).notNull().default(false), + offlineNotification: integer('offline_notification', { mode: 'boolean' }).notNull().default(true), + imageInNotification: integer('image_in_notification', { mode: 'boolean' }).notNull().default(true), + language: text('language', { enum: ['ru', 'en', 'uk'] }).notNull().default('en'), +}); + +export const chatSettingsRelations = relations(chatSettings, ({ one }) => ({ + chat: one(chats, { + fields: [chatSettings.chatId], + references: [chats.id], + }), +})); + +// Channel table +export const channels = sqliteTable('channels', { + id: text('id').primaryKey().$defaultFn(() => randomUUID()), + channelId: text('channel_id').notNull(), + service: text('service', { enum: ['twitch'] }).notNull().default('twitch'), + isLive: integer('is_live', { mode: 'boolean' }).notNull().default(false), + title: text('title'), + category: text('category'), + updatedAt: text('updated_at').$defaultFn(() => new Date().toISOString()), +}); + +export const channelsRelations = relations(channels, ({ many }) => ({ + follows: many(follows), + streams: many(streams), +})); + +// Follow table +export const follows = sqliteTable('follows', { + id: text('id').primaryKey().$defaultFn(() => randomUUID()), + channelId: text('channel_id').notNull().references(() => channels.id, { onDelete: 'cascade' }), + chatId: text('chat_id').notNull().references(() => chats.id, { onDelete: 'cascade' }), +}); + +export const followsRelations = relations(follows, ({ one }) => ({ + channel: one(channels, { + fields: [follows.channelId], + references: [channels.id], + }), + chat: one(chats, { + fields: [follows.chatId], + references: [chats.id], + }), +})); + +// Stream table +export const streams = sqliteTable('streams', { + id: text('id').primaryKey(), // Twitch stream ID + channelId: text('channel_id').notNull().references(() => channels.id, { onDelete: 'cascade' }), + isLive: integer('is_live', { mode: 'boolean' }).notNull().default(true), + title: text('title'), + category: text('category'), + titles: text('titles', { mode: 'json' }).$type().notNull().default([]), + categories: text('categories', { mode: 'json' }).$type().notNull().default([]), + startedAt: text('started_at').$defaultFn(() => new Date().toISOString()), + updatedAt: text('updated_at').$defaultFn(() => new Date().toISOString()), + endedAt: text('ended_at'), +}); + +export const streamsRelations = relations(streams, ({ one }) => ({ + channel: one(channels, { + fields: [streams.channelId], + references: [channels.id], + }), +})); + +// Types for insert and select +export type Chat = typeof chats.$inferSelect; +export type NewChat = typeof chats.$inferInsert; + +export type ChatSettings = typeof chatSettings.$inferSelect; +export type NewChatSettings = typeof chatSettings.$inferInsert; + +export type Channel = typeof channels.$inferSelect; +export type NewChannel = typeof channels.$inferInsert; + +export type Follow = typeof follows.$inferSelect; +export type NewFollow = typeof follows.$inferInsert; + +export type Stream = typeof streams.$inferSelect; +export type NewStream = typeof streams.$inferInsert; diff --git a/src/domain/mapper.ts b/src/domain/mapper.ts new file mode 100644 index 00000000..67710e92 --- /dev/null +++ b/src/domain/mapper.ts @@ -0,0 +1,63 @@ +// Mappers to convert between database schema and domain models +import type { Chat as DbChat, ChatSettings as DbChatSettings, Channel as DbChannel, Follow as DbFollow, Stream as DbStream } from '../db/schema'; +import { Chat, ChatSettings, Channel, Follow, Stream } from './models'; +import type { SupportedLanguage } from './models'; + +export class DomainMapper { + static toDomainChat(dbChat: DbChat & { settings: DbChatSettings | null }): Chat { + return new Chat({ + id: dbChat.id, + chatId: dbChat.chatId, + service: dbChat.service, + settings: dbChat.settings ? this.toDomainChatSettings(dbChat.settings) : undefined, + }); + } + + static toDomainChatSettings(dbSettings: DbChatSettings): ChatSettings { + return new ChatSettings({ + id: dbSettings.id, + chatId: dbSettings.chatId, + gameChangeNotification: dbSettings.gameChangeNotification, + titleChangeNotification: dbSettings.titleChangeNotification, + gameAndTitleChangeNotification: dbSettings.gameAndTitleChangeNotification, + offlineNotification: dbSettings.offlineNotification, + imageInNotification: dbSettings.imageInNotification, + language: dbSettings.language as SupportedLanguage, + }); + } + + static toDomainChannel(dbChannel: DbChannel): Channel { + return new Channel({ + id: dbChannel.id, + channelId: dbChannel.channelId, + service: dbChannel.service, + isLive: dbChannel.isLive, + title: dbChannel.title ?? undefined, + category: dbChannel.category ?? undefined, + updatedAt: dbChannel.updatedAt ? new Date(dbChannel.updatedAt) : undefined, + }); + } + + static toDomainFollow(dbFollow: DbFollow): Follow { + return new Follow({ + id: dbFollow.id, + channelId: dbFollow.channelId, + chatId: dbFollow.chatId, + }); + } + + static toDomainStream(dbStream: DbStream): Stream { + return new Stream({ + id: dbStream.id, + channelId: dbStream.channelId, + isLive: dbStream.isLive, + title: dbStream.title ?? undefined, + category: dbStream.category ?? undefined, + titles: dbStream.titles, + categories: dbStream.categories, + startedAt: new Date(dbStream.startedAt!), + updatedAt: dbStream.updatedAt ? new Date(dbStream.updatedAt) : undefined, + endedAt: dbStream.endedAt ? new Date(dbStream.endedAt) : undefined, + }); + } +} diff --git a/src/domain/models.ts b/src/domain/models.ts new file mode 100644 index 00000000..7160242a --- /dev/null +++ b/src/domain/models.ts @@ -0,0 +1,174 @@ +// Domain models - business logic representations +// These are separate from database schema to allow flexibility + +export type ChatService = 'telegram'; +export type ChannelService = 'twitch'; +export type SupportedLanguage = 'en' | 'ru' | 'uk'; + +export class Chat { + id: string; + chatId: string; + service: ChatService; + settings?: ChatSettings; + follows?: Follow[]; + + constructor(data: { + id: string; + chatId: string; + service: ChatService; + settings?: ChatSettings; + follows?: Follow[]; + }) { + this.id = data.id; + this.chatId = data.chatId; + this.service = data.service; + this.settings = data.settings; + this.follows = data.follows; + } +} + +export class ChatSettings { + id: string; + chatId: string; + gameChangeNotification: boolean; + titleChangeNotification: boolean; + gameAndTitleChangeNotification: boolean; + offlineNotification: boolean; + imageInNotification: boolean; + language: SupportedLanguage; + + constructor(data: { + id: string; + chatId: string; + gameChangeNotification: boolean; + titleChangeNotification: boolean; + gameAndTitleChangeNotification: boolean; + offlineNotification: boolean; + imageInNotification: boolean; + language: SupportedLanguage; + }) { + this.id = data.id; + this.chatId = data.chatId; + this.gameChangeNotification = data.gameChangeNotification; + this.titleChangeNotification = data.titleChangeNotification; + this.gameAndTitleChangeNotification = data.gameAndTitleChangeNotification; + this.offlineNotification = data.offlineNotification; + this.imageInNotification = data.imageInNotification; + this.language = data.language; + } +} + +export class Channel { + id: string; + channelId: string; + service: ChannelService; + isLive: boolean; + title?: string; + category?: string; + updatedAt?: Date; + follows?: Follow[]; + streams?: Stream[]; + + constructor(data: { + id: string; + channelId: string; + service: ChannelService; + isLive: boolean; + title?: string; + category?: string; + updatedAt?: Date; + follows?: Follow[]; + streams?: Stream[]; + }) { + this.id = data.id; + this.channelId = data.channelId; + this.service = data.service; + this.isLive = data.isLive; + this.title = data.title; + this.category = data.category; + this.updatedAt = data.updatedAt; + this.follows = data.follows; + this.streams = data.streams; + } +} + +export class Follow { + id: string; + channelId: string; + chatId: string; + channel?: Channel; + chat?: Chat; + + constructor(data: { + id: string; + channelId: string; + chatId: string; + channel?: Channel; + chat?: Chat; + }) { + this.id = data.id; + this.channelId = data.channelId; + this.chatId = data.chatId; + this.channel = data.channel; + this.chat = data.chat; + } +} + +export class Stream { + id: string; + channelId: string; + isLive: boolean; + title?: string; + category?: string; + titles: string[]; + categories: string[]; + startedAt: Date; + updatedAt?: Date; + endedAt?: Date; + + constructor(data: { + id: string; + channelId: string; + isLive: boolean; + title?: string; + category?: string; + titles: string[]; + categories: string[]; + startedAt: Date; + updatedAt?: Date; + endedAt?: Date; + }) { + this.id = data.id; + this.channelId = data.channelId; + this.isLive = data.isLive; + this.title = data.title; + this.category = data.category; + this.titles = data.titles; + this.categories = data.categories; + this.startedAt = data.startedAt; + this.updatedAt = data.updatedAt; + this.endedAt = data.endedAt; + } +} + +// Errors +export class FollowAlreadyExistsError extends Error { + constructor() { + super('Follow already exists'); + this.name = 'FollowAlreadyExistsError'; + } +} + +export class FollowNotFoundError extends Error { + constructor() { + super('Follow not found'); + this.name = 'FollowNotFoundError'; + } +} + +export class ChannelNotFoundError extends Error { + constructor() { + super('Channel not found'); + this.name = 'ChannelNotFoundError'; + } +} diff --git a/src/index.ts b/src/index.ts new file mode 100644 index 00000000..6d719361 --- /dev/null +++ b/src/index.ts @@ -0,0 +1,77 @@ +import { Hono } from 'hono'; +import { webhookCallback } from 'grammy'; +import { drizzle } from 'drizzle-orm/d1'; +import type { Env } from './types'; +import { createBot } from './bot'; +import { I18nService } from './services/i18n.service'; +import { TwitchService } from './services/twitch.service'; +import { TelegramService } from './services/telegram.service'; +import { EventSubService } from './services/eventsub.service'; +import { CloudflareD1Connection } from './db/connection'; +import { DrizzleRepositoryFactory } from './db/repository.factory'; +import { CloudflareKVSessionRepository } from './db/repositories/cloudflare-kv'; +import { handleTwitchWebhook } from './webhooks/twitch'; + +const app = new Hono<{ Bindings: Env }>(); + +// Health check +app.get('/', (c) => { + return c.json({ status: 'ok', service: 'twitch-notifier' }); +}); + +// Telegram webhook endpoint +app.post('/telegram-webhook', async (c) => { + const env = c.env; + + // Create database connection (serverless-agnostic) + const dbClient = drizzle(env.DB); + const dbConnection = new CloudflareD1Connection(dbClient); + + // Create repository factory + const repositoryFactory = new DrizzleRepositoryFactory(dbConnection); + + // Create repositories + const chatRepo = repositoryFactory.createChatRepository(); + const channelRepo = repositoryFactory.createChannelRepository(); + const followRepo = repositoryFactory.createFollowRepository(); + const streamRepo = repositoryFactory.createStreamRepository(); + + // Create session repository using Cloudflare KV + const sessionRepo = new CloudflareKVSessionRepository(env.twitch_notifier_kv); + + // Initialize services + const i18nService = new I18nService(); + await i18nService.init(); // Initialize i18next + const twitchService = new TwitchService(env); + const telegramService = new TelegramService(env, i18nService); + const eventSubService = new EventSubService( + twitchService.getApiClient(), + env, + env.BASE_URL + ); + + // Create bot instance + const bot = createBot(env, { + i18n: i18nService, + twitch: twitchService, + eventsub: eventSubService, + chatRepo, + channelRepo, + followRepo, + sessionRepo, + }); + + // Handle webhook + const handler = webhookCallback(bot, 'hono'); + return handler(c); +}); + +// Twitch EventSub webhook endpoint +app.post('/twitch-webhook', async (c) => { + const env = c.env; + const db = drizzle(env.DB); + + return await handleTwitchWebhook(c.req.raw, env, db); +}); + +export default app; diff --git a/src/services/eventsub.service.ts b/src/services/eventsub.service.ts new file mode 100644 index 00000000..083948de --- /dev/null +++ b/src/services/eventsub.service.ts @@ -0,0 +1,129 @@ +import { ApiClient } from '@twurple/api'; +import type { Env } from '../types/env'; + +export class EventSubService { + private apiClient: ApiClient; + private webhookUrl: string; + private secret: string; + + constructor(apiClient: ApiClient, env: Env, baseUrl: string) { + this.apiClient = apiClient; + this.webhookUrl = `${baseUrl}/twitch-webhook`; + this.secret = env.TWITCH_EVENTSUB_SECRET; + } + + /** + * Subscribe to all events for a broadcaster (stream.online, stream.offline, channel.update) + */ + async subscribeToChannel(broadcasterId: string): Promise { + try { + // Subscribe to stream online events + await this.apiClient.eventSub.subscribeToStreamOnlineEvents( + broadcasterId, + { + method: 'webhook', + callback: this.webhookUrl, + secret: this.secret, + } + ); + + // Subscribe to stream offline events + await this.apiClient.eventSub.subscribeToStreamOfflineEvents( + broadcasterId, + { + method: 'webhook', + callback: this.webhookUrl, + secret: this.secret, + } + ); + + // Subscribe to channel update events (title/category changes) + await this.apiClient.eventSub.subscribeToChannelUpdateEvents( + broadcasterId, + { + method: 'webhook', + callback: this.webhookUrl, + secret: this.secret, + } + ); + } catch (error) { + console.error(`Failed to subscribe to events for broadcaster ${broadcasterId}:`, error); + throw error; + } + } + + /** + * Unsubscribe from all events for a broadcaster + */ + async unsubscribeFromChannel(broadcasterId: string): Promise { + try { + // Get all subscriptions + const subscriptions = await this.apiClient.eventSub.getSubscriptions(); + + // Filter subscriptions for this broadcaster and our webhook URL + const broadcasterSubs = subscriptions.data.filter( + (sub) => { + const transportMethod = (sub as any).transport?.callback || (sub as any)._transport?.callback; + const broadcastId = (sub.condition as any).broadcaster_user_id; + return transportMethod === this.webhookUrl && broadcastId === broadcasterId; + } + ); + + // Delete each subscription + for (const sub of broadcasterSubs) { + await this.apiClient.eventSub.deleteSubscription(sub.id); + } + } catch (error) { + console.error(`Failed to unsubscribe from events for broadcaster ${broadcasterId}:`, error); + throw error; + } + } + + /** + * Check if we already have active subscriptions for a broadcaster + */ + async hasActiveSubscriptions(broadcasterId: string): Promise { + try { + const subscriptions = await this.apiClient.eventSub.getSubscriptions(); + + return subscriptions.data.some( + (sub) => { + const transportMethod = (sub as any).transport?.callback || (sub as any)._transport?.callback; + const broadcastId = (sub.condition as any).broadcaster_user_id; + return transportMethod === this.webhookUrl && broadcastId === broadcasterId && sub.status === 'enabled'; + } + ); + } catch (error) { + console.error(`Failed to check subscriptions for broadcaster ${broadcasterId}:`, error); + return false; + } + } + + /** + * Delete a specific subscription by ID + */ + async deleteSubscription(subscriptionId: string): Promise { + try { + await this.apiClient.eventSub.deleteSubscription(subscriptionId); + } catch (error) { + console.error(`Failed to delete subscription ${subscriptionId}:`, error); + throw error; + } + } + + /** + * Get all active subscriptions for our webhook + */ + async getActiveSubscriptions() { + try { + const subscriptions = await this.apiClient.eventSub.getSubscriptions(); + return subscriptions.data.filter((sub) => { + const transportMethod = (sub as any).transport?.callback || (sub as any)._transport?.callback; + return transportMethod === this.webhookUrl; + }); + } catch (error) { + console.error('Failed to get active subscriptions:', error); + return []; + } + } +} diff --git a/src/services/i18n.service.ts b/src/services/i18n.service.ts new file mode 100644 index 00000000..30d123f2 --- /dev/null +++ b/src/services/i18n.service.ts @@ -0,0 +1,84 @@ +import i18next from 'i18next'; +import type { MiddlewareFn } from 'grammy'; +import enLocale from '../../locales/en.json'; +import ruLocale from '../../locales/ru.json'; +import ukLocale from '../../locales/uk.json'; + +export type SupportedLanguage = 'en' | 'ru' | 'uk'; + +export class I18nService { + private i18n: typeof i18next; + private initialized = false; + + constructor() { + this.i18n = i18next.createInstance(); + } + + /** + * Initialize i18next instance with locales + * Must be called before using the service + */ + async init(): Promise { + if (this.initialized) return; + + await this.i18n.init({ + lng: 'en', + fallbackLng: 'en', + defaultNS: 'translation', + ns: ['translation'], + resources: { + en: { translation: enLocale }, + ru: { translation: ruLocale }, + uk: { translation: ukLocale }, + }, + interpolation: { + escapeValue: false, // Not needed for Telegram (no XSS risk) + }, + }); + + this.initialized = true; + } + + /** + * Get translated string + * @param locale - Language code + * @param key - Translation key (dot notation) + * @param params - Template parameters + */ + t(locale: SupportedLanguage, key: string, params?: Record): string { + if (!this.initialized) { + throw new Error('I18nService not initialized. Call init() first.'); + } + return this.i18n.t(key, { ...params, lng: locale }); + } + + /** + * Get Grammy middleware that attaches t() function to context + */ + middleware(): MiddlewareFn { + return async (ctx, next) => { + const language = ctx.session?.language || 'en'; + + // Attach t() function to context that uses session language + ctx.t = (key: string, params?: Record) => { + return this.t(language, key, params); + }; + + await next(); + }; + } + + /** + * Get all available locales + */ + getAvailableLocales(): SupportedLanguage[] { + return ['en', 'ru', 'uk']; + } + + /** + * Check if locale is supported + */ + isValidLocale(locale: string): locale is SupportedLanguage { + return ['en', 'ru', 'uk'].includes(locale); + } +} diff --git a/src/services/index.ts b/src/services/index.ts new file mode 100644 index 00000000..686fd746 --- /dev/null +++ b/src/services/index.ts @@ -0,0 +1,5 @@ +export * from './twitch.service'; +export * from './telegram.service'; +export * from './i18n.service'; +export * from './notification.service'; +export * from './eventsub.service'; diff --git a/src/services/notification.service.ts b/src/services/notification.service.ts new file mode 100644 index 00000000..9fceac70 --- /dev/null +++ b/src/services/notification.service.ts @@ -0,0 +1,210 @@ +import type { DrizzleD1Database } from 'drizzle-orm/d1'; +import type { Env } from '../types/env'; +import { TelegramService } from './telegram.service'; +import { TwitchService } from './twitch.service'; +import { I18nService, type SupportedLanguage } from './i18n.service'; +import type { + IChatRepository, + IChannelRepository, + IFollowRepository, + IStreamRepository, +} from '../db/repositories/interfaces'; + +export interface StreamOnlineEventData { + channelId: string; + channelName: string; + streamId: string; + category: string; + title: string; + thumbnailUrl: string; +} + +export interface StreamOfflineEventData { + channelId: string; + channelName: string; +} + +export interface StreamCategoryChangeEventData { + channelId: string; + channelName: string; + oldCategory: string; + newCategory: string; +} + +export interface StreamTitleChangeEventData { + channelId: string; + channelName: string; + oldTitle: string; + newTitle: string; +} + +export class NotificationService { + constructor( + private env: Env, + private db: DrizzleD1Database, + private telegramService: TelegramService, + private twitchService: TwitchService, + private i18nService: I18nService, + private chatRepo: IChatRepository, + private channelRepo: IChannelRepository, + private followRepo: IFollowRepository, + private streamRepo: IStreamRepository + ) {} + + async handleStreamOnline(data: StreamOnlineEventData): Promise { + // Get or create channel + let channel = await this.channelRepo.findByChannelId(data.channelId, 'twitch'); + if (!channel) { + channel = await this.channelRepo.create(data.channelId, 'twitch'); + } + + // Create stream record + await this.streamRepo.create( + data.streamId, + channel.id, + data.category, + data.title + ); + + // Get all followers of this channel + const follows = await this.followRepo.findByChannelId(channel.id); + + // Send notifications to all followers + for (const follow of follows) { + try { + const chat = await this.chatRepo.findById(follow.chatId); + if (!chat || !chat.settings) continue; + + await this.telegramService.sendStreamOnlineNotification({ + chatId: parseInt(chat.chatId), + language: chat.settings.language as SupportedLanguage, + channelName: data.channelName, + channelUrl: `https://twitch.tv/${data.channelName}`, + category: data.category, + title: data.title, + thumbnailUrl: data.thumbnailUrl, + showImage: chat.settings.imageInNotification, + }); + } catch (error) { + console.error('Failed to send online notification:', error); + } + } + } + + async handleStreamOffline(data: StreamOfflineEventData): Promise { + const channel = await this.channelRepo.findByChannelId(data.channelId, 'twitch'); + if (!channel) return; + + // Get latest stream + const stream = await this.streamRepo.findLatestByChannelId(channel.id); + if (!stream || !stream.isLive) return; + + // Update stream as offline + await this.streamRepo.update(stream.id, { + isLive: false, + endedAt: new Date().toISOString(), + }); + + // Get all followers + const follows = await this.followRepo.findByChannelId(channel.id); + + // Send notifications to followers who want offline notifications + for (const follow of follows) { + try { + const chat = await this.chatRepo.findById(follow.chatId); + if (!chat || !chat.settings || !chat.settings.offlineNotification) continue; + + const duration = stream.startedAt + ? Math.floor((Date.now() - new Date(stream.startedAt).getTime()) / 1000) + : 0; + const hours = Math.floor(duration / 3600); + const minutes = Math.floor((duration % 3600) / 60); + const seconds = duration % 60; + const durationStr = `${hours}h ${minutes}m ${seconds}s`; + + await this.telegramService.sendStreamOfflineNotification({ + chatId: parseInt(chat.chatId), + language: chat.settings.language as SupportedLanguage, + channelName: data.channelName, + channelUrl: `https://twitch.tv/${data.channelName}`, + categories: stream.categories || [], + duration: durationStr, + }); + } catch (error) { + console.error('Failed to send offline notification:', error); + } + } + } + + async handleCategoryChange(data: StreamCategoryChangeEventData): Promise { + const channel = await this.channelRepo.findByChannelId(data.channelId, 'twitch'); + if (!channel) return; + + const stream = await this.streamRepo.findLatestByChannelId(channel.id); + if (!stream || !stream.isLive) return; + + // Update stream categories + const categories = [...(stream.categories || []), data.newCategory]; + await this.streamRepo.update(stream.id, { + category: data.newCategory, + categories, + }); + + // Get all followers + const follows = await this.followRepo.findByChannelId(channel.id); + + for (const follow of follows) { + try { + const chat = await this.chatRepo.findById(follow.chatId); + if (!chat || !chat.settings || !chat.settings.gameChangeNotification) continue; + + await this.telegramService.sendCategoryChangeNotification({ + chatId: parseInt(chat.chatId), + language: chat.settings.language as SupportedLanguage, + channelName: data.channelName, + channelUrl: `https://twitch.tv/${data.channelName}`, + oldCategory: data.oldCategory, + category: data.newCategory, + }); + } catch (error) { + console.error('Failed to send category change notification:', error); + } + } + } + + async handleTitleChange(data: StreamTitleChangeEventData): Promise { + const channel = await this.channelRepo.findByChannelId(data.channelId, 'twitch'); + if (!channel) return; + + const stream = await this.streamRepo.findLatestByChannelId(channel.id); + if (!stream || !stream.isLive) return; + + // Update stream titles + const titles = [...(stream.titles || []), data.newTitle]; + await this.streamRepo.update(stream.id, { + title: data.newTitle, + titles, + }); + + // Get all followers + const follows = await this.followRepo.findByChannelId(channel.id); + + for (const follow of follows) { + try { + const chat = await this.chatRepo.findById(follow.chatId); + if (!chat || !chat.settings || !chat.settings.titleChangeNotification) continue; + + await this.telegramService.sendTitleChangeNotification({ + chatId: parseInt(chat.chatId), + language: chat.settings.language as SupportedLanguage, + channelName: data.channelName, + channelUrl: `https://twitch.tv/${data.channelName}`, + oldTitle: data.oldTitle, + title: data.newTitle, + }); + } catch (error) { + console.error('Failed to send title change notification:', error); + } + } + } +} diff --git a/src/services/telegram.service.ts b/src/services/telegram.service.ts new file mode 100644 index 00000000..60b0a294 --- /dev/null +++ b/src/services/telegram.service.ts @@ -0,0 +1,163 @@ +import { Bot, InputFile } from 'grammy'; +import type { Env } from '../types/env'; +import type { I18nService, SupportedLanguage } from './i18n.service'; +import { ThumbnailBuilder } from '../utils/thumbnail'; + +export interface StreamOnlineNotification { + chatId: number; + language: SupportedLanguage; + channelName: string; + channelUrl: string; + category: string; + title: string; + thumbnailUrl?: string; + showImage: boolean; +} + +export interface StreamOfflineNotification { + chatId: number; + language: SupportedLanguage; + channelName: string; + channelUrl: string; + categories: string[]; + duration: string; +} + +export interface CategoryChangeNotification { + chatId: number; + language: SupportedLanguage; + channelName: string; + channelUrl: string; + oldCategory: string; + category: string; +} + +export interface TitleChangeNotification { + chatId: number; + language: SupportedLanguage; + channelName: string; + channelUrl: string; + oldTitle: string; + title: string; +} + +export interface TitleAndCategoryChangeNotification { + chatId: number; + language: SupportedLanguage; + channelName: string; + channelUrl: string; + oldTitle: string; + title: string; + oldCategory: string; + category: string; +} + +export class TelegramService { + private bot: Bot; + private i18n: I18nService; + private thumbnailBuilder: ThumbnailBuilder; + + constructor(env: Env, i18n: I18nService) { + this.bot = new Bot(env.TELEGRAM_TOKEN); + this.i18n = i18n; + this.thumbnailBuilder = new ThumbnailBuilder(); + } + + async sendStreamOnlineNotification(notification: StreamOnlineNotification): Promise { + const channelLink = `${notification.channelName}`; + + const text = this.i18n.t(notification.language, 'notifications.streams.nowOnline', { + channelLink, + category: notification.category, + title: notification.title, + }); + + if (notification.showImage && notification.thumbnailUrl) { + try { + const thumbnailUrl = await this.thumbnailBuilder.build(notification.thumbnailUrl, true); + await this.bot.api.sendPhoto(notification.chatId, new InputFile(new URL(thumbnailUrl)), { + caption: text, + parse_mode: 'HTML', + }); + return; + } catch (error) { + // Fallback to text message if image fails + console.error('Failed to send photo:', error); + } + } + + await this.bot.api.sendMessage(notification.chatId, text, { + parse_mode: 'HTML', + link_preview_options: { is_disabled: false }, + }); + } + + async sendStreamOfflineNotification(notification: StreamOfflineNotification): Promise { + const channelLink = `${notification.channelName}`; + const categories = notification.categories.join(', '); + + const text = this.i18n.t(notification.language, 'notifications.streams.nowOffline', { + channelLink, + categories, + duration: notification.duration, + }); + + await this.bot.api.sendMessage(notification.chatId, text, { + parse_mode: 'HTML', + link_preview_options: { is_disabled: true }, + }); + } + + async sendCategoryChangeNotification(notification: CategoryChangeNotification): Promise { + const channelLink = `${notification.channelName}`; + + const text = this.i18n.t(notification.language, 'notifications.streams.newCategory', { + channelLink, + oldCategory: notification.oldCategory, + category: notification.category, + }); + + await this.bot.api.sendMessage(notification.chatId, text, { + parse_mode: 'HTML', + link_preview_options: { is_disabled: true }, + }); + } + + async sendTitleChangeNotification(notification: TitleChangeNotification): Promise { + const channelLink = `${notification.channelName}`; + + const text = this.i18n.t(notification.language, 'notifications.streams.titleChanged', { + channelLink, + oldTitle: notification.oldTitle, + title: notification.title, + }); + + await this.bot.api.sendMessage(notification.chatId, text, { + parse_mode: 'HTML', + link_preview_options: { is_disabled: true }, + }); + } + + async sendTitleAndCategoryChangeNotification( + notification: TitleAndCategoryChangeNotification + ): Promise { + const channelLink = `${notification.channelName}`; + + const text = this.i18n.t(notification.language, 'notifications.streams.titleAndCategoryChanged', { + channelLink, + oldTitle: notification.oldTitle, + title: notification.title, + oldCategory: notification.oldCategory, + category: notification.category, + }); + + await this.bot.api.sendMessage(notification.chatId, text, { + parse_mode: 'HTML', + link_preview_options: { is_disabled: true }, + }); + } + + getBot(): Bot { + return this.bot; + } +} diff --git a/src/services/twitch.service.ts b/src/services/twitch.service.ts new file mode 100644 index 00000000..dcd1935d --- /dev/null +++ b/src/services/twitch.service.ts @@ -0,0 +1,56 @@ +import { ApiClient } from '@twurple/api'; +import { AppTokenAuthProvider } from '@twurple/auth'; +import type { Env } from '../types/env'; + +export class TwitchService { + private apiClient: ApiClient; + private authProvider: AppTokenAuthProvider; + + constructor(env: Env) { + this.authProvider = new AppTokenAuthProvider( + env.TWITCH_CLIENT_ID, + env.TWITCH_CLIENT_SECRET + ); + this.apiClient = new ApiClient({ authProvider: this.authProvider }); + } + + async getUserByLogin(login: string) { + try { + return await this.apiClient.users.getUserByName(login); + } catch (error) { + return null; + } + } + + async getUserById(id: string) { + try { + return await this.apiClient.users.getUserById(id); + } catch (error) { + return null; + } + } + + async getStreamByUserId(userId: string) { + try { + return await this.apiClient.streams.getStreamByUserId(userId); + } catch (error) { + return null; + } + } + + async getGameById(gameId: string) { + try { + return await this.apiClient.games.getGameById(gameId); + } catch (error) { + return null; + } + } + + getApiClient() { + return this.apiClient; + } + + getAuthProvider() { + return this.authProvider; + } +} diff --git a/src/types/env.ts b/src/types/env.ts new file mode 100644 index 00000000..e5ecc41c --- /dev/null +++ b/src/types/env.ts @@ -0,0 +1,21 @@ +import type { D1Database, KVNamespace } from '@cloudflare/workers-types'; + +export interface Env { + // D1 Database + twitch_notifier_db: D1Database; + + // KV Namespace for sessions + twitch_notifier_kv: KVNamespace; + + // Secrets + TELEGRAM_TOKEN: string; + TWITCH_CLIENT_ID: string; + TWITCH_CLIENT_SECRET: string; + TELEGRAM_BOT_ADMINS: string; // comma-separated user IDs + TWITCH_EVENTSUB_SECRET: string; + BASE_URL: string; // Base URL for webhooks (e.g., https://your-worker.workers.dev) + BOT_INFO: string; + + // Variables + APP_ENV: 'development' | 'production'; +} diff --git a/src/types/index.ts b/src/types/index.ts new file mode 100644 index 00000000..c1532d6d --- /dev/null +++ b/src/types/index.ts @@ -0,0 +1 @@ +export * from './env'; diff --git a/src/utils/index.ts b/src/utils/index.ts new file mode 100644 index 00000000..d4ab7a50 --- /dev/null +++ b/src/utils/index.ts @@ -0,0 +1 @@ +export * from './thumbnail'; diff --git a/src/utils/thumbnail.ts b/src/utils/thumbnail.ts new file mode 100644 index 00000000..8589eef5 --- /dev/null +++ b/src/utils/thumbnail.ts @@ -0,0 +1,62 @@ +export class ThumbnailBuilder { + /** + * Build thumbnail URL from Twitch template URL + * @param thumbnailUrl - Twitch thumbnail URL with {width} and {height} placeholders + * @param checkValidity - Whether to check if the URL is accessible (with retry logic) + * @returns Final thumbnail URL + */ + async build(thumbnailUrl: string, checkValidity = false): Promise { + let thumbnail = thumbnailUrl + .replace('{width}', '1920') + .replace('{height}', '1080'); + + if (!checkValidity) { + return thumbnail; + } + + const isValid = await this.checkValidity(thumbnail, 0); + + if (!isValid) { + // Fallback to lower resolution + thumbnail = thumbnail + .replace('1920', '1280') + .replace('1080', '720'); + } + + return thumbnail; + } + + /** + * Check if thumbnail URL is accessible with retry logic + * @param url - URL to check + * @param attempt - Current attempt number (max 5) + * @returns Whether the URL is valid + */ + private async checkValidity(url: string, attempt: number): Promise { + try { + const response = await fetch(url, { + method: 'HEAD', + redirect: 'manual', + }); + + if (response.status === 200) { + return true; + } + + if (attempt >= 5) { + return false; + } + + // Wait 5 seconds before retry + await new Promise(resolve => setTimeout(resolve, 5000)); + return this.checkValidity(url, attempt + 1); + } catch (error) { + if (attempt >= 5) { + return false; + } + + await new Promise(resolve => setTimeout(resolve, 5000)); + return this.checkValidity(url, attempt + 1); + } + } +} diff --git a/src/webhooks/twitch.ts b/src/webhooks/twitch.ts new file mode 100644 index 00000000..0f8f48e4 --- /dev/null +++ b/src/webhooks/twitch.ts @@ -0,0 +1,186 @@ +import type { Env } from '../types/env'; +import type { DrizzleD1Database } from 'drizzle-orm/d1'; +import { TwitchService } from '../services/twitch.service'; +import { TelegramService } from '../services/telegram.service'; +import { I18nService } from '../services/i18n.service'; +import { NotificationService } from '../services/notification.service'; +import { CloudflareD1Connection } from '../db/connection'; +import { DrizzleRepositoryFactory } from '../db/repository.factory'; +import { createHmac } from 'node:crypto'; + +interface EventSubNotification { + subscription: { + id: string; + type: string; + version: string; + status: string; + cost: number; + condition: Record; + transport: { + method: string; + callback: string; + }; + created_at: string; + }; + event: Record; +} + +interface EventSubVerification { + challenge: string; + subscription: { + id: string; + type: string; + version: string; + status: string; + cost: number; + condition: Record; + transport: { + method: string; + callback: string; + }; + created_at: string; + }; +} + +export async function handleTwitchWebhook( + request: Request, + env: Env, + db: DrizzleD1Database +): Promise { + try { + // Verify the signature + const messageId = request.headers.get('Twitch-Eventsub-Message-Id'); + const timestamp = request.headers.get('Twitch-Eventsub-Message-Timestamp'); + const signature = request.headers.get('Twitch-Eventsub-Message-Signature'); + const messageType = request.headers.get('Twitch-Eventsub-Message-Type'); + + if (!messageId || !timestamp || !signature) { + return new Response('Missing required headers', { status: 400 }); + } + + const body = await request.text(); + + // Verify signature + const hmac = createHmac('sha256', env.TWITCH_EVENTSUB_SECRET); + hmac.update(messageId + timestamp + body); + const expectedSignature = 'sha256=' + hmac.digest('hex'); + + if (signature !== expectedSignature) { + return new Response('Invalid signature', { status: 403 }); + } + + const payload = JSON.parse(body); + + // Handle verification challenge + if (messageType === 'webhook_callback_verification') { + const verification = payload as EventSubVerification; + return new Response(verification.challenge, { + status: 200, + headers: { 'Content-Type': 'text/plain' }, + }); + } + + // Handle notification + if (messageType === 'notification') { + const notification = payload as EventSubNotification; + + // Initialize services + const i18nService = new I18nService(); + const twitchService = new TwitchService(env); + const telegramService = new TelegramService(env, i18nService); + + // Initialize repositories via factory + const dbConnection = new CloudflareD1Connection(db); + const repositoryFactory = new DrizzleRepositoryFactory(dbConnection); + + const chatRepo = repositoryFactory.createChatRepository(); + const channelRepo = repositoryFactory.createChannelRepository(); + const followRepo = repositoryFactory.createFollowRepository(); + const streamRepo = repositoryFactory.createStreamRepository(); + + // Initialize notification service + const notificationService = new NotificationService( + env, + db, + telegramService, + twitchService, + i18nService, + chatRepo, + channelRepo, + followRepo, + streamRepo + ); + + // Handle different event types + switch (notification.subscription.type) { + case 'stream.online': { + const event = notification.event; + const stream = await twitchService.getStreamByUserId(event.broadcaster_user_id); + if (stream) { + await notificationService.handleStreamOnline({ + channelId: event.broadcaster_user_id, + channelName: event.broadcaster_user_name, + streamId: stream.id, + category: stream.gameName, + title: stream.title, + thumbnailUrl: stream.thumbnailUrl, + }); + } + break; + } + + case 'stream.offline': { + const event = notification.event; + await notificationService.handleStreamOffline({ + channelId: event.broadcaster_user_id, + channelName: event.broadcaster_user_name, + }); + break; + } + + case 'channel.update': { + const event = notification.event; + const channel = await channelRepo.findByChannelId(event.broadcaster_user_id, 'twitch'); + if (!channel) break; + + const stream = await streamRepo.findLatestByChannelId(channel.id); + if (!stream || !stream.isLive) break; + + // Check if category changed + if (stream.category && event.category_name !== stream.category) { + await notificationService.handleCategoryChange({ + channelId: event.broadcaster_user_id, + channelName: event.broadcaster_user_name, + oldCategory: stream.category, + newCategory: event.category_name, + }); + } + + // Check if title changed + if (stream.title && event.title !== stream.title) { + await notificationService.handleTitleChange({ + channelId: event.broadcaster_user_id, + channelName: event.broadcaster_user_name, + oldTitle: stream.title, + newTitle: event.title, + }); + } + break; + } + } + + return new Response('OK', { status: 200 }); + } + + // Handle revocation + if (messageType === 'revocation') { + console.log('Subscription revoked:', payload); + return new Response('OK', { status: 200 }); + } + + return new Response('Unknown message type', { status: 400 }); + } catch (error) { + console.error('Error handling Twitch webhook:', error); + return new Response('Internal Server Error', { status: 500 }); + } +} diff --git a/tsconfig.json b/tsconfig.json new file mode 100644 index 00000000..a25639df --- /dev/null +++ b/tsconfig.json @@ -0,0 +1,21 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "ES2022", + "lib": ["ES2022"], + "moduleResolution": "bundler", + "resolveJsonModule": true, + "allowSyntheticDefaultImports": true, + "esModuleInterop": true, + "strict": true, + "skipLibCheck": true, + "isolatedModules": true, + "types": ["@cloudflare/workers-types"], + "baseUrl": ".", + "paths": { + "~/*": ["./src/*"] + } + }, + "include": ["src/**/*"], + "exclude": ["node_modules", "dist", ".wrangler"] +} diff --git a/wrangler.example.toml b/wrangler.example.toml new file mode 100644 index 00000000..e4710295 --- /dev/null +++ b/wrangler.example.toml @@ -0,0 +1,43 @@ +name = "twitch-notifier" +main = "src/index.ts" +compatibility_date = "2026-03-06" +compatibility_flags = [ + "nodejs_compat" +] +workers_dev = true + +[observability] +enabled = true + +# D1 Database +[[d1_databases]] +binding = "DB" +database_name = "twitch-notifier-db" +database_id = "" # Will be filled after creating D1 database + +[[kv_namespaces]] +binding = "twitch-notifier-kv" +id = "1" + +# Environment Variables +[vars] +APP_ENV = "development" + +# Secrets (use wrangler secret put) +# TELEGRAM_TOKEN = "" +# TWITCH_CLIENT_ID = "" +# TWITCH_CLIENT_SECRET = "" +# TELEGRAM_BOT_ADMINS = "comma-separated user IDs" +# TWITCH_EVENTSUB_SECRET = "for webhook verification" + +# BOT INFO FOR SKIP /me REQUEST ON EACH REQUEST +#BOT_INFO = """{ +# "id": 1234567890, +# "is_bot": true, +# "first_name": "mybot", +# "username": "MyBot", +# "can_join_groups": true, +# "can_read_all_group_messages": false, +# "supports_inline_queries": true, +# "can_connect_to_business": false +#}""" From 945355235bc0062b7450a424aece1e9c4d57f8f5 Mon Sep 17 00:00:00 2001 From: Satont Date: Mon, 9 Mar 2026 12:54:17 +0300 Subject: [PATCH 2/4] upd --- .github/workflows/deploy.yml | 35 + .gitignore | 1 + .../middleware-insertion-facade.js | 11 - .../bundle-ldhBcJ/middleware-loader.entry.ts | 134 - .wrangler/tmp/dev-FVjRI2/index.js | 32018 ---------------- .wrangler/tmp/dev-FVjRI2/index.js.map | 8 - MIGRATION_PLAN.md | 315 - drizzle/0000_init.sql | 50 - drizzle/meta/0000_snapshot.json | 360 - drizzle/meta/0001_snapshot.json | 398 - drizzle/meta/_journal.json | 20 - ent/generate.go | 3 - .../migrations/20230327181912_initial.sql | 62 - ...20230401125338_TitleChangeNotification.sql | 2 - ...230506114213_EnableImageInNotification.sql | 2 - ..._GameAndTitleChangeNotificationSetting.sql | 2 - ent/migrate/migrations/atlas.sum | 5 - ent/schema/channel.go | 50 - ent/schema/chat.go | 50 - ent/schema/chat_settings.go | 49 - ent/schema/follow.go | 43 - ent/schema/stream.go | 60 - internal/config/config.go | 45 - internal/config/config_test.go | 102 - internal/db/channel.go | 41 - internal/db/channel_impl_ent.go | 192 - internal/db/channel_impl_ent_test.go | 236 - internal/db/chat.go | 40 - internal/db/chat_ent_impl.go | 163 - internal/db/chat_ent_impl_test.go | 280 - internal/db/db_models/channel.go | 34 - internal/db/db_models/chat.go | 58 - internal/db/db_models/follow.go | 20 - internal/db/db_models/stream.go | 16 - internal/db/follow.go | 20 - internal/db/follow_ent_impl.go | 201 - internal/db/follow_ent_test.go | 269 - internal/db/mock_db.go | 26 - internal/db/stream.go | 39 - internal/db/stream_impl_ent.go | 161 - internal/db/stream_impl_ent_test.go | 293 - internal/message_sender/message_sender.go | 36 - .../message_sender/message_sender_impl.go | 89 - .../message_sender_impl_test.go | 240 - internal/telegram/commands/broadcast.go | 77 - internal/telegram/commands/broadcast_test.go | 89 - .../telegram/commands/change_channel_id.go | 64 - internal/telegram/commands/filters.go | 37 - internal/telegram/commands/follow.go | 180 - internal/telegram/commands/follow_test.go | 424 - internal/telegram/commands/follows.go | 249 - internal/telegram/commands/follows_test.go | 429 - internal/telegram/commands/language_picker.go | 109 - .../telegram/commands/language_picker_test.go | 215 - internal/telegram/commands/live.go | 153 - internal/telegram/commands/live_test.go | 273 - internal/telegram/commands/start.go | 346 - internal/telegram/commands/start_test.go | 169 - internal/telegram/middlewares/chat.go | 37 - internal/telegram/middlewares/logg.go | 24 - internal/telegram/set_commands.go | 58 - internal/telegram/telegram.go | 92 - internal/telegram/types/mocked_session.go | 48 - internal/telegram/types/router.go | 141 - internal/telegram/types/session.go | 42 - internal/test_utils/mocks/db_channel.go | 81 - internal/test_utils/mocks/db_chat.go | 53 - internal/test_utils/mocks/db_follow.go | 57 - internal/test_utils/mocks/db_stream.go | 52 - internal/test_utils/mocks/message_sender.go | 19 - .../test_utils/mocks/twitch_api_client.go | 43 - internal/test_utils/telegram_client.go | 21 - internal/twitch/chunked_req.go | 63 - internal/twitch/helpers/rate_limiter.go | 28 - internal/twitch/implementation.go | 165 - internal/twitch/implementation_test.go | 212 - internal/twitch/interface.go | 16 - .../thumbnail_builder.go | 60 - .../twitch_streams_cheker.go | 461 - .../twitch_streams_cheker_test.go | 323 - internal/types/types.go | 20 - migrations/0001_initial.sql | 51 + package.json | 6 +- pkg/i18n/helpers.go | 15 - pkg/i18n/helpers_test.go | 26 - pkg/i18n/i18n.go | 81 - pkg/i18n/i18n_test.go | 124 - pkg/i18n/mocks/i18_mock.go | 21 - pkg/i18n/test_locales/en.json | 7 - src/bot/commands/callback.handler.ts | 19 +- src/bot/helpers.ts | 43 +- src/index.ts | 4 +- 92 files changed, 152 insertions(+), 41454 deletions(-) create mode 100644 .github/workflows/deploy.yml delete mode 100644 .wrangler/tmp/bundle-ldhBcJ/middleware-insertion-facade.js delete mode 100644 .wrangler/tmp/bundle-ldhBcJ/middleware-loader.entry.ts delete mode 100644 .wrangler/tmp/dev-FVjRI2/index.js delete mode 100644 .wrangler/tmp/dev-FVjRI2/index.js.map delete mode 100644 MIGRATION_PLAN.md delete mode 100644 drizzle/0000_init.sql delete mode 100644 drizzle/meta/0000_snapshot.json delete mode 100644 drizzle/meta/0001_snapshot.json delete mode 100644 drizzle/meta/_journal.json delete mode 100644 ent/generate.go delete mode 100644 ent/migrate/migrations/20230327181912_initial.sql delete mode 100644 ent/migrate/migrations/20230401125338_TitleChangeNotification.sql delete mode 100644 ent/migrate/migrations/20230506114213_EnableImageInNotification.sql delete mode 100644 ent/migrate/migrations/20230521162457_GameAndTitleChangeNotificationSetting.sql delete mode 100644 ent/migrate/migrations/atlas.sum delete mode 100644 ent/schema/channel.go delete mode 100644 ent/schema/chat.go delete mode 100644 ent/schema/chat_settings.go delete mode 100644 ent/schema/follow.go delete mode 100644 ent/schema/stream.go delete mode 100644 internal/config/config.go delete mode 100644 internal/config/config_test.go delete mode 100644 internal/db/channel.go delete mode 100644 internal/db/channel_impl_ent.go delete mode 100644 internal/db/channel_impl_ent_test.go delete mode 100644 internal/db/chat.go delete mode 100644 internal/db/chat_ent_impl.go delete mode 100644 internal/db/chat_ent_impl_test.go delete mode 100644 internal/db/db_models/channel.go delete mode 100644 internal/db/db_models/chat.go delete mode 100644 internal/db/db_models/follow.go delete mode 100644 internal/db/db_models/stream.go delete mode 100644 internal/db/follow.go delete mode 100644 internal/db/follow_ent_impl.go delete mode 100644 internal/db/follow_ent_test.go delete mode 100644 internal/db/mock_db.go delete mode 100644 internal/db/stream.go delete mode 100644 internal/db/stream_impl_ent.go delete mode 100644 internal/db/stream_impl_ent_test.go delete mode 100644 internal/message_sender/message_sender.go delete mode 100644 internal/message_sender/message_sender_impl.go delete mode 100644 internal/message_sender/message_sender_impl_test.go delete mode 100644 internal/telegram/commands/broadcast.go delete mode 100644 internal/telegram/commands/broadcast_test.go delete mode 100644 internal/telegram/commands/change_channel_id.go delete mode 100644 internal/telegram/commands/filters.go delete mode 100644 internal/telegram/commands/follow.go delete mode 100644 internal/telegram/commands/follow_test.go delete mode 100644 internal/telegram/commands/follows.go delete mode 100644 internal/telegram/commands/follows_test.go delete mode 100644 internal/telegram/commands/language_picker.go delete mode 100644 internal/telegram/commands/language_picker_test.go delete mode 100644 internal/telegram/commands/live.go delete mode 100644 internal/telegram/commands/live_test.go delete mode 100644 internal/telegram/commands/start.go delete mode 100644 internal/telegram/commands/start_test.go delete mode 100644 internal/telegram/middlewares/chat.go delete mode 100644 internal/telegram/middlewares/logg.go delete mode 100644 internal/telegram/set_commands.go delete mode 100644 internal/telegram/telegram.go delete mode 100644 internal/telegram/types/mocked_session.go delete mode 100644 internal/telegram/types/router.go delete mode 100644 internal/telegram/types/session.go delete mode 100644 internal/test_utils/mocks/db_channel.go delete mode 100644 internal/test_utils/mocks/db_chat.go delete mode 100644 internal/test_utils/mocks/db_follow.go delete mode 100644 internal/test_utils/mocks/db_stream.go delete mode 100644 internal/test_utils/mocks/message_sender.go delete mode 100644 internal/test_utils/mocks/twitch_api_client.go delete mode 100644 internal/test_utils/telegram_client.go delete mode 100644 internal/twitch/chunked_req.go delete mode 100644 internal/twitch/helpers/rate_limiter.go delete mode 100644 internal/twitch/implementation.go delete mode 100644 internal/twitch/implementation_test.go delete mode 100644 internal/twitch/interface.go delete mode 100644 internal/twitch_streams_cheker/thumbnail_builder.go delete mode 100644 internal/twitch_streams_cheker/twitch_streams_cheker.go delete mode 100644 internal/twitch_streams_cheker/twitch_streams_cheker_test.go delete mode 100644 internal/types/types.go create mode 100644 migrations/0001_initial.sql delete mode 100644 pkg/i18n/helpers.go delete mode 100644 pkg/i18n/helpers_test.go delete mode 100644 pkg/i18n/i18n.go delete mode 100644 pkg/i18n/i18n_test.go delete mode 100644 pkg/i18n/mocks/i18_mock.go delete mode 100644 pkg/i18n/test_locales/en.json diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml new file mode 100644 index 00000000..11c58f05 --- /dev/null +++ b/.github/workflows/deploy.yml @@ -0,0 +1,35 @@ +name: Deploy to Cloudflare Workers + +on: + push: + branches: + - main + workflow_dispatch: + +jobs: + deploy: + runs-on: ubuntu-latest + name: Deploy + steps: + - uses: actions/checkout@v4 + + - name: Setup Node.js + uses: actions/setup-node@v4 + with: + node-version: '20' + cache: 'npm' + + - name: Install dependencies + run: npm ci + + - name: Run migrations + run: npm run db:migrate + env: + CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }} + CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }} + + - name: Deploy to Cloudflare Workers + run: npm run deploy + env: + CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }} + CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }} diff --git a/.gitignore b/.gitignore index 4ae3dc57..3c99929e 100644 --- a/.gitignore +++ b/.gitignore @@ -10,3 +10,4 @@ ent/**/* .DS_Store wrangler.toml node_modules +.wrangler diff --git a/.wrangler/tmp/bundle-ldhBcJ/middleware-insertion-facade.js b/.wrangler/tmp/bundle-ldhBcJ/middleware-insertion-facade.js deleted file mode 100644 index ea2d7d47..00000000 --- a/.wrangler/tmp/bundle-ldhBcJ/middleware-insertion-facade.js +++ /dev/null @@ -1,11 +0,0 @@ - import worker, * as OTHER_EXPORTS from "/home/satont/Projects/twitch-notifier/src/index.ts"; - import * as __MIDDLEWARE_0__ from "/home/satont/Projects/twitch-notifier/node_modules/.pnpm/wrangler@4.71.0_@cloudflare+workers-types@4.20260307.1/node_modules/wrangler/templates/middleware/middleware-ensure-req-body-drained.ts"; -import * as __MIDDLEWARE_1__ from "/home/satont/Projects/twitch-notifier/node_modules/.pnpm/wrangler@4.71.0_@cloudflare+workers-types@4.20260307.1/node_modules/wrangler/templates/middleware/middleware-miniflare3-json-error.ts"; - - export * from "/home/satont/Projects/twitch-notifier/src/index.ts"; - const MIDDLEWARE_TEST_INJECT = "__INJECT_FOR_TESTING_WRANGLER_MIDDLEWARE__"; - export const __INTERNAL_WRANGLER_MIDDLEWARE__ = [ - - __MIDDLEWARE_0__.default,__MIDDLEWARE_1__.default - ] - export default worker; \ No newline at end of file diff --git a/.wrangler/tmp/bundle-ldhBcJ/middleware-loader.entry.ts b/.wrangler/tmp/bundle-ldhBcJ/middleware-loader.entry.ts deleted file mode 100644 index 1bfe275f..00000000 --- a/.wrangler/tmp/bundle-ldhBcJ/middleware-loader.entry.ts +++ /dev/null @@ -1,134 +0,0 @@ -// This loads all middlewares exposed on the middleware object and then starts -// the invocation chain. The big idea is that we can add these to the middleware -// export dynamically through wrangler, or we can potentially let users directly -// add them as a sort of "plugin" system. - -import ENTRY, { __INTERNAL_WRANGLER_MIDDLEWARE__ } from "/home/satont/Projects/twitch-notifier/.wrangler/tmp/bundle-ldhBcJ/middleware-insertion-facade.js"; -import { __facade_invoke__, __facade_register__, Dispatcher } from "/home/satont/Projects/twitch-notifier/node_modules/.pnpm/wrangler@4.71.0_@cloudflare+workers-types@4.20260307.1/node_modules/wrangler/templates/middleware/common.ts"; -import type { WorkerEntrypointConstructor } from "/home/satont/Projects/twitch-notifier/.wrangler/tmp/bundle-ldhBcJ/middleware-insertion-facade.js"; - -// Preserve all the exports from the worker -export * from "/home/satont/Projects/twitch-notifier/.wrangler/tmp/bundle-ldhBcJ/middleware-insertion-facade.js"; - -class __Facade_ScheduledController__ implements ScheduledController { - readonly #noRetry: ScheduledController["noRetry"]; - - constructor( - readonly scheduledTime: number, - readonly cron: string, - noRetry: ScheduledController["noRetry"] - ) { - this.#noRetry = noRetry; - } - - noRetry() { - if (!(this instanceof __Facade_ScheduledController__)) { - throw new TypeError("Illegal invocation"); - } - // Need to call native method immediately in case uncaught error thrown - this.#noRetry(); - } -} - -function wrapExportedHandler(worker: ExportedHandler): ExportedHandler { - // If we don't have any middleware defined, just return the handler as is - if ( - __INTERNAL_WRANGLER_MIDDLEWARE__ === undefined || - __INTERNAL_WRANGLER_MIDDLEWARE__.length === 0 - ) { - return worker; - } - // Otherwise, register all middleware once - for (const middleware of __INTERNAL_WRANGLER_MIDDLEWARE__) { - __facade_register__(middleware); - } - - const fetchDispatcher: ExportedHandlerFetchHandler = function ( - request, - env, - ctx - ) { - if (worker.fetch === undefined) { - throw new Error("Handler does not export a fetch() function."); - } - return worker.fetch(request, env, ctx); - }; - - return { - ...worker, - fetch(request, env, ctx) { - const dispatcher: Dispatcher = function (type, init) { - if (type === "scheduled" && worker.scheduled !== undefined) { - const controller = new __Facade_ScheduledController__( - Date.now(), - init.cron ?? "", - () => {} - ); - return worker.scheduled(controller, env, ctx); - } - }; - return __facade_invoke__(request, env, ctx, dispatcher, fetchDispatcher); - }, - }; -} - -function wrapWorkerEntrypoint( - klass: WorkerEntrypointConstructor -): WorkerEntrypointConstructor { - // If we don't have any middleware defined, just return the handler as is - if ( - __INTERNAL_WRANGLER_MIDDLEWARE__ === undefined || - __INTERNAL_WRANGLER_MIDDLEWARE__.length === 0 - ) { - return klass; - } - // Otherwise, register all middleware once - for (const middleware of __INTERNAL_WRANGLER_MIDDLEWARE__) { - __facade_register__(middleware); - } - - // `extend`ing `klass` here so other RPC methods remain callable - return class extends klass { - #fetchDispatcher: ExportedHandlerFetchHandler> = ( - request, - env, - ctx - ) => { - this.env = env; - this.ctx = ctx; - if (super.fetch === undefined) { - throw new Error("Entrypoint class does not define a fetch() function."); - } - return super.fetch(request); - }; - - #dispatcher: Dispatcher = (type, init) => { - if (type === "scheduled" && super.scheduled !== undefined) { - const controller = new __Facade_ScheduledController__( - Date.now(), - init.cron ?? "", - () => {} - ); - return super.scheduled(controller); - } - }; - - fetch(request: Request) { - return __facade_invoke__( - request, - this.env, - this.ctx, - this.#dispatcher, - this.#fetchDispatcher - ); - } - }; -} - -let WRAPPED_ENTRY: ExportedHandler | WorkerEntrypointConstructor | undefined; -if (typeof ENTRY === "object") { - WRAPPED_ENTRY = wrapExportedHandler(ENTRY); -} else if (typeof ENTRY === "function") { - WRAPPED_ENTRY = wrapWorkerEntrypoint(ENTRY); -} -export default WRAPPED_ENTRY; diff --git a/.wrangler/tmp/dev-FVjRI2/index.js b/.wrangler/tmp/dev-FVjRI2/index.js deleted file mode 100644 index 8d15d671..00000000 --- a/.wrangler/tmp/dev-FVjRI2/index.js +++ /dev/null @@ -1,32018 +0,0 @@ -var __create = Object.create; -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __getProtoOf = Object.getPrototypeOf; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __esm = (fn, res) => function __init() { - return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res; -}; -var __commonJS = (cb, mod) => function __require() { - return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; -}; -var __copyProps = (to, from, except2, desc2) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except2) - __defProp(to, key, { get: () => from[key], enumerable: !(desc2 = __getOwnPropDesc(from, key)) || desc2.enumerable }); - } - return to; -}; -var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( - // If the importer is in node compatibility mode or this is not an ESM - // file that has been converted to a CommonJS file using a Babel- - // compatible transform (i.e. "__esModule" has not been set), then set - // "default" to the CommonJS "module.exports" for node compatibility. - isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, - mod -)); - -// node_modules/.pnpm/unenv@2.0.0-rc.24/node_modules/unenv/dist/runtime/_internal/utils.mjs -// @__NO_SIDE_EFFECTS__ -function createNotImplementedError(name) { - return new Error(`[unenv] ${name} is not implemented yet!`); -} -var init_utils = __esm({ - "node_modules/.pnpm/unenv@2.0.0-rc.24/node_modules/unenv/dist/runtime/_internal/utils.mjs"() { - init_modules_watch_stub(); - init_performance2(); - __name(createNotImplementedError, "createNotImplementedError"); - } -}); - -// node_modules/.pnpm/unenv@2.0.0-rc.24/node_modules/unenv/dist/runtime/node/internal/perf_hooks/performance.mjs -var _timeOrigin, _performanceNow, nodeTiming, PerformanceEntry, PerformanceMark, PerformanceMeasure, PerformanceResourceTiming, PerformanceObserverEntryList, Performance, PerformanceObserver, performance; -var init_performance = __esm({ - "node_modules/.pnpm/unenv@2.0.0-rc.24/node_modules/unenv/dist/runtime/node/internal/perf_hooks/performance.mjs"() { - init_modules_watch_stub(); - init_performance2(); - init_utils(); - _timeOrigin = globalThis.performance?.timeOrigin ?? Date.now(); - _performanceNow = globalThis.performance?.now ? globalThis.performance.now.bind(globalThis.performance) : () => Date.now() - _timeOrigin; - nodeTiming = { - name: "node", - entryType: "node", - startTime: 0, - duration: 0, - nodeStart: 0, - v8Start: 0, - bootstrapComplete: 0, - environment: 0, - loopStart: 0, - loopExit: 0, - idleTime: 0, - uvMetricsInfo: { - loopCount: 0, - events: 0, - eventsWaiting: 0 - }, - detail: void 0, - toJSON() { - return this; - } - }; - PerformanceEntry = class { - static { - __name(this, "PerformanceEntry"); - } - __unenv__ = true; - detail; - entryType = "event"; - name; - startTime; - constructor(name, options) { - this.name = name; - this.startTime = options?.startTime || _performanceNow(); - this.detail = options?.detail; - } - get duration() { - return _performanceNow() - this.startTime; - } - toJSON() { - return { - name: this.name, - entryType: this.entryType, - startTime: this.startTime, - duration: this.duration, - detail: this.detail - }; - } - }; - PerformanceMark = class PerformanceMark2 extends PerformanceEntry { - static { - __name(this, "PerformanceMark"); - } - entryType = "mark"; - constructor() { - super(...arguments); - } - get duration() { - return 0; - } - }; - PerformanceMeasure = class extends PerformanceEntry { - static { - __name(this, "PerformanceMeasure"); - } - entryType = "measure"; - }; - PerformanceResourceTiming = class extends PerformanceEntry { - static { - __name(this, "PerformanceResourceTiming"); - } - entryType = "resource"; - serverTiming = []; - connectEnd = 0; - connectStart = 0; - decodedBodySize = 0; - domainLookupEnd = 0; - domainLookupStart = 0; - encodedBodySize = 0; - fetchStart = 0; - initiatorType = ""; - name = ""; - nextHopProtocol = ""; - redirectEnd = 0; - redirectStart = 0; - requestStart = 0; - responseEnd = 0; - responseStart = 0; - secureConnectionStart = 0; - startTime = 0; - transferSize = 0; - workerStart = 0; - responseStatus = 0; - }; - PerformanceObserverEntryList = class { - static { - __name(this, "PerformanceObserverEntryList"); - } - __unenv__ = true; - getEntries() { - return []; - } - getEntriesByName(_name, _type) { - return []; - } - getEntriesByType(type) { - return []; - } - }; - Performance = class { - static { - __name(this, "Performance"); - } - __unenv__ = true; - timeOrigin = _timeOrigin; - eventCounts = /* @__PURE__ */ new Map(); - _entries = []; - _resourceTimingBufferSize = 0; - navigation = void 0; - timing = void 0; - timerify(_fn, _options) { - throw createNotImplementedError("Performance.timerify"); - } - get nodeTiming() { - return nodeTiming; - } - eventLoopUtilization() { - return {}; - } - markResourceTiming() { - return new PerformanceResourceTiming(""); - } - onresourcetimingbufferfull = null; - now() { - if (this.timeOrigin === _timeOrigin) { - return _performanceNow(); - } - return Date.now() - this.timeOrigin; - } - clearMarks(markName) { - this._entries = markName ? this._entries.filter((e) => e.name !== markName) : this._entries.filter((e) => e.entryType !== "mark"); - } - clearMeasures(measureName) { - this._entries = measureName ? this._entries.filter((e) => e.name !== measureName) : this._entries.filter((e) => e.entryType !== "measure"); - } - clearResourceTimings() { - this._entries = this._entries.filter((e) => e.entryType !== "resource" || e.entryType !== "navigation"); - } - getEntries() { - return this._entries; - } - getEntriesByName(name, type) { - return this._entries.filter((e) => e.name === name && (!type || e.entryType === type)); - } - getEntriesByType(type) { - return this._entries.filter((e) => e.entryType === type); - } - mark(name, options) { - const entry = new PerformanceMark(name, options); - this._entries.push(entry); - return entry; - } - measure(measureName, startOrMeasureOptions, endMark) { - let start; - let end; - if (typeof startOrMeasureOptions === "string") { - start = this.getEntriesByName(startOrMeasureOptions, "mark")[0]?.startTime; - end = this.getEntriesByName(endMark, "mark")[0]?.startTime; - } else { - start = Number.parseFloat(startOrMeasureOptions?.start) || this.now(); - end = Number.parseFloat(startOrMeasureOptions?.end) || this.now(); - } - const entry = new PerformanceMeasure(measureName, { - startTime: start, - detail: { - start, - end - } - }); - this._entries.push(entry); - return entry; - } - setResourceTimingBufferSize(maxSize) { - this._resourceTimingBufferSize = maxSize; - } - addEventListener(type, listener, options) { - throw createNotImplementedError("Performance.addEventListener"); - } - removeEventListener(type, listener, options) { - throw createNotImplementedError("Performance.removeEventListener"); - } - dispatchEvent(event) { - throw createNotImplementedError("Performance.dispatchEvent"); - } - toJSON() { - return this; - } - }; - PerformanceObserver = class { - static { - __name(this, "PerformanceObserver"); - } - __unenv__ = true; - static supportedEntryTypes = []; - _callback = null; - constructor(callback) { - this._callback = callback; - } - takeRecords() { - return []; - } - disconnect() { - throw createNotImplementedError("PerformanceObserver.disconnect"); - } - observe(options) { - throw createNotImplementedError("PerformanceObserver.observe"); - } - bind(fn) { - return fn; - } - runInAsyncScope(fn, thisArg, ...args) { - return fn.call(thisArg, ...args); - } - asyncId() { - return 0; - } - triggerAsyncId() { - return 0; - } - emitDestroy() { - return this; - } - }; - performance = globalThis.performance && "addEventListener" in globalThis.performance ? globalThis.performance : new Performance(); - } -}); - -// node_modules/.pnpm/unenv@2.0.0-rc.24/node_modules/unenv/dist/runtime/node/perf_hooks.mjs -var init_perf_hooks = __esm({ - "node_modules/.pnpm/unenv@2.0.0-rc.24/node_modules/unenv/dist/runtime/node/perf_hooks.mjs"() { - init_modules_watch_stub(); - init_performance2(); - init_performance(); - } -}); - -// node_modules/.pnpm/@cloudflare+unenv-preset@2.15.0_unenv@2.0.0-rc.24_workerd@1.20260301.1/node_modules/@cloudflare/unenv-preset/dist/runtime/polyfill/performance.mjs -var init_performance2 = __esm({ - "node_modules/.pnpm/@cloudflare+unenv-preset@2.15.0_unenv@2.0.0-rc.24_workerd@1.20260301.1/node_modules/@cloudflare/unenv-preset/dist/runtime/polyfill/performance.mjs"() { - init_perf_hooks(); - globalThis.performance = performance; - globalThis.Performance = Performance; - globalThis.PerformanceEntry = PerformanceEntry; - globalThis.PerformanceMark = PerformanceMark; - globalThis.PerformanceMeasure = PerformanceMeasure; - globalThis.PerformanceObserver = PerformanceObserver; - globalThis.PerformanceObserverEntryList = PerformanceObserverEntryList; - globalThis.PerformanceResourceTiming = PerformanceResourceTiming; - } -}); - -// wrangler-modules-watch:wrangler:modules-watch -var init_wrangler_modules_watch = __esm({ - "wrangler-modules-watch:wrangler:modules-watch"() { - init_modules_watch_stub(); - init_performance2(); - } -}); - -// node_modules/.pnpm/wrangler@4.71.0_@cloudflare+workers-types@4.20260307.1/node_modules/wrangler/templates/modules-watch-stub.js -var init_modules_watch_stub = __esm({ - "node_modules/.pnpm/wrangler@4.71.0_@cloudflare+workers-types@4.20260307.1/node_modules/wrangler/templates/modules-watch-stub.js"() { - init_wrangler_modules_watch(); - } -}); - -// node_modules/.pnpm/@d-fischer+detect-node@3.0.1/node_modules/@d-fischer/detect-node/browser.js -var require_browser = __commonJS({ - "node_modules/.pnpm/@d-fischer+detect-node@3.0.1/node_modules/@d-fischer/detect-node/browser.js"(exports, module) { - init_modules_watch_stub(); - init_performance2(); - module.exports.isNode = false; - } -}); - -// node_modules/.pnpm/retry@0.13.1/node_modules/retry/lib/retry_operation.js -var require_retry_operation = __commonJS({ - "node_modules/.pnpm/retry@0.13.1/node_modules/retry/lib/retry_operation.js"(exports, module) { - init_modules_watch_stub(); - init_performance2(); - function RetryOperation(timeouts, options) { - if (typeof options === "boolean") { - options = { forever: options }; - } - this._originalTimeouts = JSON.parse(JSON.stringify(timeouts)); - this._timeouts = timeouts; - this._options = options || {}; - this._maxRetryTime = options && options.maxRetryTime || Infinity; - this._fn = null; - this._errors = []; - this._attempts = 1; - this._operationTimeout = null; - this._operationTimeoutCb = null; - this._timeout = null; - this._operationStart = null; - this._timer = null; - if (this._options.forever) { - this._cachedTimeouts = this._timeouts.slice(0); - } - } - __name(RetryOperation, "RetryOperation"); - module.exports = RetryOperation; - RetryOperation.prototype.reset = function() { - this._attempts = 1; - this._timeouts = this._originalTimeouts.slice(0); - }; - RetryOperation.prototype.stop = function() { - if (this._timeout) { - clearTimeout(this._timeout); - } - if (this._timer) { - clearTimeout(this._timer); - } - this._timeouts = []; - this._cachedTimeouts = null; - }; - RetryOperation.prototype.retry = function(err) { - if (this._timeout) { - clearTimeout(this._timeout); - } - if (!err) { - return false; - } - var currentTime = (/* @__PURE__ */ new Date()).getTime(); - if (err && currentTime - this._operationStart >= this._maxRetryTime) { - this._errors.push(err); - this._errors.unshift(new Error("RetryOperation timeout occurred")); - return false; - } - this._errors.push(err); - var timeout = this._timeouts.shift(); - if (timeout === void 0) { - if (this._cachedTimeouts) { - this._errors.splice(0, this._errors.length - 1); - timeout = this._cachedTimeouts.slice(-1); - } else { - return false; - } - } - var self2 = this; - this._timer = setTimeout(function() { - self2._attempts++; - if (self2._operationTimeoutCb) { - self2._timeout = setTimeout(function() { - self2._operationTimeoutCb(self2._attempts); - }, self2._operationTimeout); - if (self2._options.unref) { - self2._timeout.unref(); - } - } - self2._fn(self2._attempts); - }, timeout); - if (this._options.unref) { - this._timer.unref(); - } - return true; - }; - RetryOperation.prototype.attempt = function(fn, timeoutOps) { - this._fn = fn; - if (timeoutOps) { - if (timeoutOps.timeout) { - this._operationTimeout = timeoutOps.timeout; - } - if (timeoutOps.cb) { - this._operationTimeoutCb = timeoutOps.cb; - } - } - var self2 = this; - if (this._operationTimeoutCb) { - this._timeout = setTimeout(function() { - self2._operationTimeoutCb(); - }, self2._operationTimeout); - } - this._operationStart = (/* @__PURE__ */ new Date()).getTime(); - this._fn(this._attempts); - }; - RetryOperation.prototype.try = function(fn) { - console.log("Using RetryOperation.try() is deprecated"); - this.attempt(fn); - }; - RetryOperation.prototype.start = function(fn) { - console.log("Using RetryOperation.start() is deprecated"); - this.attempt(fn); - }; - RetryOperation.prototype.start = RetryOperation.prototype.try; - RetryOperation.prototype.errors = function() { - return this._errors; - }; - RetryOperation.prototype.attempts = function() { - return this._attempts; - }; - RetryOperation.prototype.mainError = function() { - if (this._errors.length === 0) { - return null; - } - var counts = {}; - var mainError = null; - var mainErrorCount = 0; - for (var i = 0; i < this._errors.length; i++) { - var error = this._errors[i]; - var message = error.message; - var count2 = (counts[message] || 0) + 1; - counts[message] = count2; - if (count2 >= mainErrorCount) { - mainError = error; - mainErrorCount = count2; - } - } - return mainError; - }; - } -}); - -// node_modules/.pnpm/retry@0.13.1/node_modules/retry/lib/retry.js -var require_retry = __commonJS({ - "node_modules/.pnpm/retry@0.13.1/node_modules/retry/lib/retry.js"(exports) { - init_modules_watch_stub(); - init_performance2(); - var RetryOperation = require_retry_operation(); - exports.operation = function(options) { - var timeouts = exports.timeouts(options); - return new RetryOperation(timeouts, { - forever: options && (options.forever || options.retries === Infinity), - unref: options && options.unref, - maxRetryTime: options && options.maxRetryTime - }); - }; - exports.timeouts = function(options) { - if (options instanceof Array) { - return [].concat(options); - } - var opts = { - retries: 10, - factor: 2, - minTimeout: 1 * 1e3, - maxTimeout: Infinity, - randomize: false - }; - for (var key in options) { - opts[key] = options[key]; - } - if (opts.minTimeout > opts.maxTimeout) { - throw new Error("minTimeout is greater than maxTimeout"); - } - var timeouts = []; - for (var i = 0; i < opts.retries; i++) { - timeouts.push(this.createTimeout(i, opts)); - } - if (options && options.forever && !timeouts.length) { - timeouts.push(this.createTimeout(i, opts)); - } - timeouts.sort(function(a, b) { - return a - b; - }); - return timeouts; - }; - exports.createTimeout = function(attempt, opts) { - var random = opts.randomize ? Math.random() + 1 : 1; - var timeout = Math.round(random * Math.max(opts.minTimeout, 1) * Math.pow(opts.factor, attempt)); - timeout = Math.min(timeout, opts.maxTimeout); - return timeout; - }; - exports.wrap = function(obj, options, methods) { - if (options instanceof Array) { - methods = options; - options = null; - } - if (!methods) { - methods = []; - for (var key in obj) { - if (typeof obj[key] === "function") { - methods.push(key); - } - } - } - for (var i = 0; i < methods.length; i++) { - var method = methods[i]; - var original = obj[method]; - obj[method] = (/* @__PURE__ */ __name(function retryWrapper(original2) { - var op = exports.operation(options); - var args = Array.prototype.slice.call(arguments, 1); - var callback = args.pop(); - args.push(function(err) { - if (op.retry(err)) { - return; - } - if (err) { - arguments[0] = op.mainError(); - } - callback.apply(this, arguments); - }); - op.attempt(function() { - original2.apply(obj, args); - }); - }, "retryWrapper")).bind(obj, original); - obj[method].options = options; - } - }; - } -}); - -// node_modules/.pnpm/retry@0.13.1/node_modules/retry/index.js -var require_retry2 = __commonJS({ - "node_modules/.pnpm/retry@0.13.1/node_modules/retry/index.js"(exports, module) { - init_modules_watch_stub(); - init_performance2(); - module.exports = require_retry(); - } -}); - -// .wrangler/tmp/bundle-ldhBcJ/middleware-loader.entry.ts -init_modules_watch_stub(); -init_performance2(); - -// .wrangler/tmp/bundle-ldhBcJ/middleware-insertion-facade.js -init_modules_watch_stub(); -init_performance2(); - -// src/index.ts -init_modules_watch_stub(); -init_performance2(); - -// node_modules/.pnpm/hono@4.12.5/node_modules/hono/dist/index.js -init_modules_watch_stub(); -init_performance2(); - -// node_modules/.pnpm/hono@4.12.5/node_modules/hono/dist/hono.js -init_modules_watch_stub(); -init_performance2(); - -// node_modules/.pnpm/hono@4.12.5/node_modules/hono/dist/hono-base.js -init_modules_watch_stub(); -init_performance2(); - -// node_modules/.pnpm/hono@4.12.5/node_modules/hono/dist/compose.js -init_modules_watch_stub(); -init_performance2(); -var compose = /* @__PURE__ */ __name((middleware, onError, onNotFound) => { - return (context, next) => { - let index = -1; - return dispatch(0); - async function dispatch(i) { - if (i <= index) { - throw new Error("next() called multiple times"); - } - index = i; - let res; - let isError = false; - let handler; - if (middleware[i]) { - handler = middleware[i][0][0]; - context.req.routeIndex = i; - } else { - handler = i === middleware.length && next || void 0; - } - if (handler) { - try { - res = await handler(context, () => dispatch(i + 1)); - } catch (err) { - if (err instanceof Error && onError) { - context.error = err; - res = await onError(err, context); - isError = true; - } else { - throw err; - } - } - } else { - if (context.finalized === false && onNotFound) { - res = await onNotFound(context); - } - } - if (res && (context.finalized === false || isError)) { - context.res = res; - } - return context; - } - __name(dispatch, "dispatch"); - }; -}, "compose"); - -// node_modules/.pnpm/hono@4.12.5/node_modules/hono/dist/context.js -init_modules_watch_stub(); -init_performance2(); - -// node_modules/.pnpm/hono@4.12.5/node_modules/hono/dist/request.js -init_modules_watch_stub(); -init_performance2(); - -// node_modules/.pnpm/hono@4.12.5/node_modules/hono/dist/http-exception.js -init_modules_watch_stub(); -init_performance2(); - -// node_modules/.pnpm/hono@4.12.5/node_modules/hono/dist/request/constants.js -init_modules_watch_stub(); -init_performance2(); -var GET_MATCH_RESULT = /* @__PURE__ */ Symbol(); - -// node_modules/.pnpm/hono@4.12.5/node_modules/hono/dist/utils/body.js -init_modules_watch_stub(); -init_performance2(); -var parseBody = /* @__PURE__ */ __name(async (request, options = /* @__PURE__ */ Object.create(null)) => { - const { all = false, dot = false } = options; - const headers = request instanceof HonoRequest ? request.raw.headers : request.headers; - const contentType = headers.get("Content-Type"); - if (contentType?.startsWith("multipart/form-data") || contentType?.startsWith("application/x-www-form-urlencoded")) { - return parseFormData(request, { all, dot }); - } - return {}; -}, "parseBody"); -async function parseFormData(request, options) { - const formData = await request.formData(); - if (formData) { - return convertFormDataToBodyData(formData, options); - } - return {}; -} -__name(parseFormData, "parseFormData"); -function convertFormDataToBodyData(formData, options) { - const form = /* @__PURE__ */ Object.create(null); - formData.forEach((value, key) => { - const shouldParseAllValues = options.all || key.endsWith("[]"); - if (!shouldParseAllValues) { - form[key] = value; - } else { - handleParsingAllValues(form, key, value); - } - }); - if (options.dot) { - Object.entries(form).forEach(([key, value]) => { - const shouldParseDotValues = key.includes("."); - if (shouldParseDotValues) { - handleParsingNestedValues(form, key, value); - delete form[key]; - } - }); - } - return form; -} -__name(convertFormDataToBodyData, "convertFormDataToBodyData"); -var handleParsingAllValues = /* @__PURE__ */ __name((form, key, value) => { - if (form[key] !== void 0) { - if (Array.isArray(form[key])) { - ; - form[key].push(value); - } else { - form[key] = [form[key], value]; - } - } else { - if (!key.endsWith("[]")) { - form[key] = value; - } else { - form[key] = [value]; - } - } -}, "handleParsingAllValues"); -var handleParsingNestedValues = /* @__PURE__ */ __name((form, key, value) => { - let nestedForm = form; - const keys = key.split("."); - keys.forEach((key2, index) => { - if (index === keys.length - 1) { - nestedForm[key2] = value; - } else { - if (!nestedForm[key2] || typeof nestedForm[key2] !== "object" || Array.isArray(nestedForm[key2]) || nestedForm[key2] instanceof File) { - nestedForm[key2] = /* @__PURE__ */ Object.create(null); - } - nestedForm = nestedForm[key2]; - } - }); -}, "handleParsingNestedValues"); - -// node_modules/.pnpm/hono@4.12.5/node_modules/hono/dist/utils/url.js -init_modules_watch_stub(); -init_performance2(); -var splitPath = /* @__PURE__ */ __name((path) => { - const paths = path.split("/"); - if (paths[0] === "") { - paths.shift(); - } - return paths; -}, "splitPath"); -var splitRoutingPath = /* @__PURE__ */ __name((routePath) => { - const { groups, path } = extractGroupsFromPath(routePath); - const paths = splitPath(path); - return replaceGroupMarks(paths, groups); -}, "splitRoutingPath"); -var extractGroupsFromPath = /* @__PURE__ */ __name((path) => { - const groups = []; - path = path.replace(/\{[^}]+\}/g, (match3, index) => { - const mark = `@${index}`; - groups.push([mark, match3]); - return mark; - }); - return { groups, path }; -}, "extractGroupsFromPath"); -var replaceGroupMarks = /* @__PURE__ */ __name((paths, groups) => { - for (let i = groups.length - 1; i >= 0; i--) { - const [mark] = groups[i]; - for (let j = paths.length - 1; j >= 0; j--) { - if (paths[j].includes(mark)) { - paths[j] = paths[j].replace(mark, groups[i][1]); - break; - } - } - } - return paths; -}, "replaceGroupMarks"); -var patternCache = {}; -var getPattern = /* @__PURE__ */ __name((label, next) => { - if (label === "*") { - return "*"; - } - const match3 = label.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/); - if (match3) { - const cacheKey = `${label}#${next}`; - if (!patternCache[cacheKey]) { - if (match3[2]) { - patternCache[cacheKey] = next && next[0] !== ":" && next[0] !== "*" ? [cacheKey, match3[1], new RegExp(`^${match3[2]}(?=/${next})`)] : [label, match3[1], new RegExp(`^${match3[2]}$`)]; - } else { - patternCache[cacheKey] = [label, match3[1], true]; - } - } - return patternCache[cacheKey]; - } - return null; -}, "getPattern"); -var tryDecode = /* @__PURE__ */ __name((str2, decoder) => { - try { - return decoder(str2); - } catch { - return str2.replace(/(?:%[0-9A-Fa-f]{2})+/g, (match3) => { - try { - return decoder(match3); - } catch { - return match3; - } - }); - } -}, "tryDecode"); -var tryDecodeURI = /* @__PURE__ */ __name((str2) => tryDecode(str2, decodeURI), "tryDecodeURI"); -var getPath = /* @__PURE__ */ __name((request) => { - const url = request.url; - const start = url.indexOf("/", url.indexOf(":") + 4); - let i = start; - for (; i < url.length; i++) { - const charCode = url.charCodeAt(i); - if (charCode === 37) { - const queryIndex = url.indexOf("?", i); - const hashIndex = url.indexOf("#", i); - const end = queryIndex === -1 ? hashIndex === -1 ? void 0 : hashIndex : hashIndex === -1 ? queryIndex : Math.min(queryIndex, hashIndex); - const path = url.slice(start, end); - return tryDecodeURI(path.includes("%25") ? path.replace(/%25/g, "%2525") : path); - } else if (charCode === 63 || charCode === 35) { - break; - } - } - return url.slice(start, i); -}, "getPath"); -var getPathNoStrict = /* @__PURE__ */ __name((request) => { - const result = getPath(request); - return result.length > 1 && result.at(-1) === "/" ? result.slice(0, -1) : result; -}, "getPathNoStrict"); -var mergePath = /* @__PURE__ */ __name((base, sub, ...rest) => { - if (rest.length) { - sub = mergePath(sub, ...rest); - } - return `${base?.[0] === "/" ? "" : "/"}${base}${sub === "/" ? "" : `${base?.at(-1) === "/" ? "" : "/"}${sub?.[0] === "/" ? sub.slice(1) : sub}`}`; -}, "mergePath"); -var checkOptionalParameter = /* @__PURE__ */ __name((path) => { - if (path.charCodeAt(path.length - 1) !== 63 || !path.includes(":")) { - return null; - } - const segments = path.split("/"); - const results = []; - let basePath = ""; - segments.forEach((segment) => { - if (segment !== "" && !/\:/.test(segment)) { - basePath += "/" + segment; - } else if (/\:/.test(segment)) { - if (/\?/.test(segment)) { - if (results.length === 0 && basePath === "") { - results.push("/"); - } else { - results.push(basePath); - } - const optionalSegment = segment.replace("?", ""); - basePath += "/" + optionalSegment; - results.push(basePath); - } else { - basePath += "/" + segment; - } - } - }); - return results.filter((v, i, a) => a.indexOf(v) === i); -}, "checkOptionalParameter"); -var _decodeURI = /* @__PURE__ */ __name((value) => { - if (!/[%+]/.test(value)) { - return value; - } - if (value.indexOf("+") !== -1) { - value = value.replace(/\+/g, " "); - } - return value.indexOf("%") !== -1 ? tryDecode(value, decodeURIComponent_) : value; -}, "_decodeURI"); -var _getQueryParam = /* @__PURE__ */ __name((url, key, multiple) => { - let encoded; - if (!multiple && key && !/[%+]/.test(key)) { - let keyIndex2 = url.indexOf("?", 8); - if (keyIndex2 === -1) { - return void 0; - } - if (!url.startsWith(key, keyIndex2 + 1)) { - keyIndex2 = url.indexOf(`&${key}`, keyIndex2 + 1); - } - while (keyIndex2 !== -1) { - const trailingKeyCode = url.charCodeAt(keyIndex2 + key.length + 1); - if (trailingKeyCode === 61) { - const valueIndex = keyIndex2 + key.length + 2; - const endIndex = url.indexOf("&", valueIndex); - return _decodeURI(url.slice(valueIndex, endIndex === -1 ? void 0 : endIndex)); - } else if (trailingKeyCode == 38 || isNaN(trailingKeyCode)) { - return ""; - } - keyIndex2 = url.indexOf(`&${key}`, keyIndex2 + 1); - } - encoded = /[%+]/.test(url); - if (!encoded) { - return void 0; - } - } - const results = {}; - encoded ??= /[%+]/.test(url); - let keyIndex = url.indexOf("?", 8); - while (keyIndex !== -1) { - const nextKeyIndex = url.indexOf("&", keyIndex + 1); - let valueIndex = url.indexOf("=", keyIndex); - if (valueIndex > nextKeyIndex && nextKeyIndex !== -1) { - valueIndex = -1; - } - let name = url.slice( - keyIndex + 1, - valueIndex === -1 ? nextKeyIndex === -1 ? void 0 : nextKeyIndex : valueIndex - ); - if (encoded) { - name = _decodeURI(name); - } - keyIndex = nextKeyIndex; - if (name === "") { - continue; - } - let value; - if (valueIndex === -1) { - value = ""; - } else { - value = url.slice(valueIndex + 1, nextKeyIndex === -1 ? void 0 : nextKeyIndex); - if (encoded) { - value = _decodeURI(value); - } - } - if (multiple) { - if (!(results[name] && Array.isArray(results[name]))) { - results[name] = []; - } - ; - results[name].push(value); - } else { - results[name] ??= value; - } - } - return key ? results[key] : results; -}, "_getQueryParam"); -var getQueryParam = _getQueryParam; -var getQueryParams = /* @__PURE__ */ __name((url, key) => { - return _getQueryParam(url, key, true); -}, "getQueryParams"); -var decodeURIComponent_ = decodeURIComponent; - -// node_modules/.pnpm/hono@4.12.5/node_modules/hono/dist/request.js -var tryDecodeURIComponent = /* @__PURE__ */ __name((str2) => tryDecode(str2, decodeURIComponent_), "tryDecodeURIComponent"); -var HonoRequest = class { - static { - __name(this, "HonoRequest"); - } - /** - * `.raw` can get the raw Request object. - * - * @see {@link https://hono.dev/docs/api/request#raw} - * - * @example - * ```ts - * // For Cloudflare Workers - * app.post('/', async (c) => { - * const metadata = c.req.raw.cf?.hostMetadata? - * ... - * }) - * ``` - */ - raw; - #validatedData; - // Short name of validatedData - #matchResult; - routeIndex = 0; - /** - * `.path` can get the pathname of the request. - * - * @see {@link https://hono.dev/docs/api/request#path} - * - * @example - * ```ts - * app.get('/about/me', (c) => { - * const pathname = c.req.path // `/about/me` - * }) - * ``` - */ - path; - bodyCache = {}; - constructor(request, path = "/", matchResult = [[]]) { - this.raw = request; - this.path = path; - this.#matchResult = matchResult; - this.#validatedData = {}; - } - param(key) { - return key ? this.#getDecodedParam(key) : this.#getAllDecodedParams(); - } - #getDecodedParam(key) { - const paramKey = this.#matchResult[0][this.routeIndex][1][key]; - const param = this.#getParamValue(paramKey); - return param && /\%/.test(param) ? tryDecodeURIComponent(param) : param; - } - #getAllDecodedParams() { - const decoded = {}; - const keys = Object.keys(this.#matchResult[0][this.routeIndex][1]); - for (const key of keys) { - const value = this.#getParamValue(this.#matchResult[0][this.routeIndex][1][key]); - if (value !== void 0) { - decoded[key] = /\%/.test(value) ? tryDecodeURIComponent(value) : value; - } - } - return decoded; - } - #getParamValue(paramKey) { - return this.#matchResult[1] ? this.#matchResult[1][paramKey] : paramKey; - } - query(key) { - return getQueryParam(this.url, key); - } - queries(key) { - return getQueryParams(this.url, key); - } - header(name) { - if (name) { - return this.raw.headers.get(name) ?? void 0; - } - const headerData = {}; - this.raw.headers.forEach((value, key) => { - headerData[key] = value; - }); - return headerData; - } - async parseBody(options) { - return this.bodyCache.parsedBody ??= await parseBody(this, options); - } - #cachedBody = /* @__PURE__ */ __name((key) => { - const { bodyCache, raw: raw2 } = this; - const cachedBody = bodyCache[key]; - if (cachedBody) { - return cachedBody; - } - const anyCachedKey = Object.keys(bodyCache)[0]; - if (anyCachedKey) { - return bodyCache[anyCachedKey].then((body) => { - if (anyCachedKey === "json") { - body = JSON.stringify(body); - } - return new Response(body)[key](); - }); - } - return bodyCache[key] = raw2[key](); - }, "#cachedBody"); - /** - * `.json()` can parse Request body of type `application/json` - * - * @see {@link https://hono.dev/docs/api/request#json} - * - * @example - * ```ts - * app.post('/entry', async (c) => { - * const body = await c.req.json() - * }) - * ``` - */ - json() { - return this.#cachedBody("text").then((text2) => JSON.parse(text2)); - } - /** - * `.text()` can parse Request body of type `text/plain` - * - * @see {@link https://hono.dev/docs/api/request#text} - * - * @example - * ```ts - * app.post('/entry', async (c) => { - * const body = await c.req.text() - * }) - * ``` - */ - text() { - return this.#cachedBody("text"); - } - /** - * `.arrayBuffer()` parse Request body as an `ArrayBuffer` - * - * @see {@link https://hono.dev/docs/api/request#arraybuffer} - * - * @example - * ```ts - * app.post('/entry', async (c) => { - * const body = await c.req.arrayBuffer() - * }) - * ``` - */ - arrayBuffer() { - return this.#cachedBody("arrayBuffer"); - } - /** - * Parses the request body as a `Blob`. - * @example - * ```ts - * app.post('/entry', async (c) => { - * const body = await c.req.blob(); - * }); - * ``` - * @see https://hono.dev/docs/api/request#blob - */ - blob() { - return this.#cachedBody("blob"); - } - /** - * Parses the request body as `FormData`. - * @example - * ```ts - * app.post('/entry', async (c) => { - * const body = await c.req.formData(); - * }); - * ``` - * @see https://hono.dev/docs/api/request#formdata - */ - formData() { - return this.#cachedBody("formData"); - } - /** - * Adds validated data to the request. - * - * @param target - The target of the validation. - * @param data - The validated data to add. - */ - addValidatedData(target, data2) { - this.#validatedData[target] = data2; - } - valid(target) { - return this.#validatedData[target]; - } - /** - * `.url()` can get the request url strings. - * - * @see {@link https://hono.dev/docs/api/request#url} - * - * @example - * ```ts - * app.get('/about/me', (c) => { - * const url = c.req.url // `http://localhost:8787/about/me` - * ... - * }) - * ``` - */ - get url() { - return this.raw.url; - } - /** - * `.method()` can get the method name of the request. - * - * @see {@link https://hono.dev/docs/api/request#method} - * - * @example - * ```ts - * app.get('/about/me', (c) => { - * const method = c.req.method // `GET` - * }) - * ``` - */ - get method() { - return this.raw.method; - } - get [GET_MATCH_RESULT]() { - return this.#matchResult; - } - /** - * `.matchedRoutes()` can return a matched route in the handler - * - * @deprecated - * - * Use matchedRoutes helper defined in "hono/route" instead. - * - * @see {@link https://hono.dev/docs/api/request#matchedroutes} - * - * @example - * ```ts - * app.use('*', async function logger(c, next) { - * await next() - * c.req.matchedRoutes.forEach(({ handler, method, path }, i) => { - * const name = handler.name || (handler.length < 2 ? '[handler]' : '[middleware]') - * console.log( - * method, - * ' ', - * path, - * ' '.repeat(Math.max(10 - path.length, 0)), - * name, - * i === c.req.routeIndex ? '<- respond from here' : '' - * ) - * }) - * }) - * ``` - */ - get matchedRoutes() { - return this.#matchResult[0].map(([[, route]]) => route); - } - /** - * `routePath()` can retrieve the path registered within the handler - * - * @deprecated - * - * Use routePath helper defined in "hono/route" instead. - * - * @see {@link https://hono.dev/docs/api/request#routepath} - * - * @example - * ```ts - * app.get('/posts/:id', (c) => { - * return c.json({ path: c.req.routePath }) - * }) - * ``` - */ - get routePath() { - return this.#matchResult[0].map(([[, route]]) => route)[this.routeIndex].path; - } -}; - -// node_modules/.pnpm/hono@4.12.5/node_modules/hono/dist/utils/html.js -init_modules_watch_stub(); -init_performance2(); -var HtmlEscapedCallbackPhase = { - Stringify: 1, - BeforeStream: 2, - Stream: 3 -}; -var raw = /* @__PURE__ */ __name((value, callbacks) => { - const escapedString = new String(value); - escapedString.isEscaped = true; - escapedString.callbacks = callbacks; - return escapedString; -}, "raw"); -var resolveCallback = /* @__PURE__ */ __name(async (str2, phase, preserveCallbacks, context, buffer) => { - if (typeof str2 === "object" && !(str2 instanceof String)) { - if (!(str2 instanceof Promise)) { - str2 = str2.toString(); - } - if (str2 instanceof Promise) { - str2 = await str2; - } - } - const callbacks = str2.callbacks; - if (!callbacks?.length) { - return Promise.resolve(str2); - } - if (buffer) { - buffer[0] += str2; - } else { - buffer = [str2]; - } - const resStr = Promise.all(callbacks.map((c) => c({ phase, buffer, context }))).then( - (res) => Promise.all( - res.filter(Boolean).map((str22) => resolveCallback(str22, phase, false, context, buffer)) - ).then(() => buffer[0]) - ); - if (preserveCallbacks) { - return raw(await resStr, callbacks); - } else { - return resStr; - } -}, "resolveCallback"); - -// node_modules/.pnpm/hono@4.12.5/node_modules/hono/dist/context.js -var TEXT_PLAIN = "text/plain; charset=UTF-8"; -var setDefaultContentType = /* @__PURE__ */ __name((contentType, headers) => { - return { - "Content-Type": contentType, - ...headers - }; -}, "setDefaultContentType"); -var createResponseInstance = /* @__PURE__ */ __name((body, init2) => new Response(body, init2), "createResponseInstance"); -var Context = class { - static { - __name(this, "Context"); - } - #rawRequest; - #req; - /** - * `.env` can get bindings (environment variables, secrets, KV namespaces, D1 database, R2 bucket etc.) in Cloudflare Workers. - * - * @see {@link https://hono.dev/docs/api/context#env} - * - * @example - * ```ts - * // Environment object for Cloudflare Workers - * app.get('*', async c => { - * const counter = c.env.COUNTER - * }) - * ``` - */ - env = {}; - #var; - finalized = false; - /** - * `.error` can get the error object from the middleware if the Handler throws an error. - * - * @see {@link https://hono.dev/docs/api/context#error} - * - * @example - * ```ts - * app.use('*', async (c, next) => { - * await next() - * if (c.error) { - * // do something... - * } - * }) - * ``` - */ - error; - #status; - #executionCtx; - #res; - #layout; - #renderer; - #notFoundHandler; - #preparedHeaders; - #matchResult; - #path; - /** - * Creates an instance of the Context class. - * - * @param req - The Request object. - * @param options - Optional configuration options for the context. - */ - constructor(req, options) { - this.#rawRequest = req; - if (options) { - this.#executionCtx = options.executionCtx; - this.env = options.env; - this.#notFoundHandler = options.notFoundHandler; - this.#path = options.path; - this.#matchResult = options.matchResult; - } - } - /** - * `.req` is the instance of {@link HonoRequest}. - */ - get req() { - this.#req ??= new HonoRequest(this.#rawRequest, this.#path, this.#matchResult); - return this.#req; - } - /** - * @see {@link https://hono.dev/docs/api/context#event} - * The FetchEvent associated with the current request. - * - * @throws Will throw an error if the context does not have a FetchEvent. - */ - get event() { - if (this.#executionCtx && "respondWith" in this.#executionCtx) { - return this.#executionCtx; - } else { - throw Error("This context has no FetchEvent"); - } - } - /** - * @see {@link https://hono.dev/docs/api/context#executionctx} - * The ExecutionContext associated with the current request. - * - * @throws Will throw an error if the context does not have an ExecutionContext. - */ - get executionCtx() { - if (this.#executionCtx) { - return this.#executionCtx; - } else { - throw Error("This context has no ExecutionContext"); - } - } - /** - * @see {@link https://hono.dev/docs/api/context#res} - * The Response object for the current request. - */ - get res() { - return this.#res ||= createResponseInstance(null, { - headers: this.#preparedHeaders ??= new Headers() - }); - } - /** - * Sets the Response object for the current request. - * - * @param _res - The Response object to set. - */ - set res(_res) { - if (this.#res && _res) { - _res = createResponseInstance(_res.body, _res); - for (const [k, v] of this.#res.headers.entries()) { - if (k === "content-type") { - continue; - } - if (k === "set-cookie") { - const cookies = this.#res.headers.getSetCookie(); - _res.headers.delete("set-cookie"); - for (const cookie of cookies) { - _res.headers.append("set-cookie", cookie); - } - } else { - _res.headers.set(k, v); - } - } - } - this.#res = _res; - this.finalized = true; - } - /** - * `.render()` can create a response within a layout. - * - * @see {@link https://hono.dev/docs/api/context#render-setrenderer} - * - * @example - * ```ts - * app.get('/', (c) => { - * return c.render('Hello!') - * }) - * ``` - */ - render = /* @__PURE__ */ __name((...args) => { - this.#renderer ??= (content) => this.html(content); - return this.#renderer(...args); - }, "render"); - /** - * Sets the layout for the response. - * - * @param layout - The layout to set. - * @returns The layout function. - */ - setLayout = /* @__PURE__ */ __name((layout) => this.#layout = layout, "setLayout"); - /** - * Gets the current layout for the response. - * - * @returns The current layout function. - */ - getLayout = /* @__PURE__ */ __name(() => this.#layout, "getLayout"); - /** - * `.setRenderer()` can set the layout in the custom middleware. - * - * @see {@link https://hono.dev/docs/api/context#render-setrenderer} - * - * @example - * ```tsx - * app.use('*', async (c, next) => { - * c.setRenderer((content) => { - * return c.html( - * - * - *

{content}

- * - * - * ) - * }) - * await next() - * }) - * ``` - */ - setRenderer = /* @__PURE__ */ __name((renderer) => { - this.#renderer = renderer; - }, "setRenderer"); - /** - * `.header()` can set headers. - * - * @see {@link https://hono.dev/docs/api/context#header} - * - * @example - * ```ts - * app.get('/welcome', (c) => { - * // Set headers - * c.header('X-Message', 'Hello!') - * c.header('Content-Type', 'text/plain') - * - * return c.body('Thank you for coming') - * }) - * ``` - */ - header = /* @__PURE__ */ __name((name, value, options) => { - if (this.finalized) { - this.#res = createResponseInstance(this.#res.body, this.#res); - } - const headers = this.#res ? this.#res.headers : this.#preparedHeaders ??= new Headers(); - if (value === void 0) { - headers.delete(name); - } else if (options?.append) { - headers.append(name, value); - } else { - headers.set(name, value); - } - }, "header"); - status = /* @__PURE__ */ __name((status) => { - this.#status = status; - }, "status"); - /** - * `.set()` can set the value specified by the key. - * - * @see {@link https://hono.dev/docs/api/context#set-get} - * - * @example - * ```ts - * app.use('*', async (c, next) => { - * c.set('message', 'Hono is hot!!') - * await next() - * }) - * ``` - */ - set = /* @__PURE__ */ __name((key, value) => { - this.#var ??= /* @__PURE__ */ new Map(); - this.#var.set(key, value); - }, "set"); - /** - * `.get()` can use the value specified by the key. - * - * @see {@link https://hono.dev/docs/api/context#set-get} - * - * @example - * ```ts - * app.get('/', (c) => { - * const message = c.get('message') - * return c.text(`The message is "${message}"`) - * }) - * ``` - */ - get = /* @__PURE__ */ __name((key) => { - return this.#var ? this.#var.get(key) : void 0; - }, "get"); - /** - * `.var` can access the value of a variable. - * - * @see {@link https://hono.dev/docs/api/context#var} - * - * @example - * ```ts - * const result = c.var.client.oneMethod() - * ``` - */ - // c.var.propName is a read-only - get var() { - if (!this.#var) { - return {}; - } - return Object.fromEntries(this.#var); - } - #newResponse(data2, arg, headers) { - const responseHeaders = this.#res ? new Headers(this.#res.headers) : this.#preparedHeaders ?? new Headers(); - if (typeof arg === "object" && "headers" in arg) { - const argHeaders = arg.headers instanceof Headers ? arg.headers : new Headers(arg.headers); - for (const [key, value] of argHeaders) { - if (key.toLowerCase() === "set-cookie") { - responseHeaders.append(key, value); - } else { - responseHeaders.set(key, value); - } - } - } - if (headers) { - for (const [k, v] of Object.entries(headers)) { - if (typeof v === "string") { - responseHeaders.set(k, v); - } else { - responseHeaders.delete(k); - for (const v2 of v) { - responseHeaders.append(k, v2); - } - } - } - } - const status = typeof arg === "number" ? arg : arg?.status ?? this.#status; - return createResponseInstance(data2, { status, headers: responseHeaders }); - } - newResponse = /* @__PURE__ */ __name((...args) => this.#newResponse(...args), "newResponse"); - /** - * `.body()` can return the HTTP response. - * You can set headers with `.header()` and set HTTP status code with `.status`. - * This can also be set in `.text()`, `.json()` and so on. - * - * @see {@link https://hono.dev/docs/api/context#body} - * - * @example - * ```ts - * app.get('/welcome', (c) => { - * // Set headers - * c.header('X-Message', 'Hello!') - * c.header('Content-Type', 'text/plain') - * // Set HTTP status code - * c.status(201) - * - * // Return the response body - * return c.body('Thank you for coming') - * }) - * ``` - */ - body = /* @__PURE__ */ __name((data2, arg, headers) => this.#newResponse(data2, arg, headers), "body"); - /** - * `.text()` can render text as `Content-Type:text/plain`. - * - * @see {@link https://hono.dev/docs/api/context#text} - * - * @example - * ```ts - * app.get('/say', (c) => { - * return c.text('Hello!') - * }) - * ``` - */ - text = /* @__PURE__ */ __name((text2, arg, headers) => { - return !this.#preparedHeaders && !this.#status && !arg && !headers && !this.finalized ? new Response(text2) : this.#newResponse( - text2, - arg, - setDefaultContentType(TEXT_PLAIN, headers) - ); - }, "text"); - /** - * `.json()` can render JSON as `Content-Type:application/json`. - * - * @see {@link https://hono.dev/docs/api/context#json} - * - * @example - * ```ts - * app.get('/api', (c) => { - * return c.json({ message: 'Hello!' }) - * }) - * ``` - */ - json = /* @__PURE__ */ __name((object, arg, headers) => { - return this.#newResponse( - JSON.stringify(object), - arg, - setDefaultContentType("application/json", headers) - ); - }, "json"); - html = /* @__PURE__ */ __name((html, arg, headers) => { - const res = /* @__PURE__ */ __name((html2) => this.#newResponse(html2, arg, setDefaultContentType("text/html; charset=UTF-8", headers)), "res"); - return typeof html === "object" ? resolveCallback(html, HtmlEscapedCallbackPhase.Stringify, false, {}).then(res) : res(html); - }, "html"); - /** - * `.redirect()` can Redirect, default status code is 302. - * - * @see {@link https://hono.dev/docs/api/context#redirect} - * - * @example - * ```ts - * app.get('/redirect', (c) => { - * return c.redirect('/') - * }) - * app.get('/redirect-permanently', (c) => { - * return c.redirect('/', 301) - * }) - * ``` - */ - redirect = /* @__PURE__ */ __name((location, status) => { - const locationString = String(location); - this.header( - "Location", - // Multibyes should be encoded - // eslint-disable-next-line no-control-regex - !/[^\x00-\xFF]/.test(locationString) ? locationString : encodeURI(locationString) - ); - return this.newResponse(null, status ?? 302); - }, "redirect"); - /** - * `.notFound()` can return the Not Found Response. - * - * @see {@link https://hono.dev/docs/api/context#notfound} - * - * @example - * ```ts - * app.get('/notfound', (c) => { - * return c.notFound() - * }) - * ``` - */ - notFound = /* @__PURE__ */ __name(() => { - this.#notFoundHandler ??= () => createResponseInstance(); - return this.#notFoundHandler(this); - }, "notFound"); -}; - -// node_modules/.pnpm/hono@4.12.5/node_modules/hono/dist/router.js -init_modules_watch_stub(); -init_performance2(); -var METHOD_NAME_ALL = "ALL"; -var METHOD_NAME_ALL_LOWERCASE = "all"; -var METHODS = ["get", "post", "put", "delete", "options", "patch"]; -var MESSAGE_MATCHER_IS_ALREADY_BUILT = "Can not add a route since the matcher is already built."; -var UnsupportedPathError = class extends Error { - static { - __name(this, "UnsupportedPathError"); - } -}; - -// node_modules/.pnpm/hono@4.12.5/node_modules/hono/dist/utils/constants.js -init_modules_watch_stub(); -init_performance2(); -var COMPOSED_HANDLER = "__COMPOSED_HANDLER"; - -// node_modules/.pnpm/hono@4.12.5/node_modules/hono/dist/hono-base.js -var notFoundHandler = /* @__PURE__ */ __name((c) => { - return c.text("404 Not Found", 404); -}, "notFoundHandler"); -var errorHandler = /* @__PURE__ */ __name((err, c) => { - if ("getResponse" in err) { - const res = err.getResponse(); - return c.newResponse(res.body, res); - } - console.error(err); - return c.text("Internal Server Error", 500); -}, "errorHandler"); -var Hono = class _Hono { - static { - __name(this, "_Hono"); - } - get; - post; - put; - delete; - options; - patch; - all; - on; - use; - /* - This class is like an abstract class and does not have a router. - To use it, inherit the class and implement router in the constructor. - */ - router; - getPath; - // Cannot use `#` because it requires visibility at JavaScript runtime. - _basePath = "/"; - #path = "/"; - routes = []; - constructor(options = {}) { - const allMethods = [...METHODS, METHOD_NAME_ALL_LOWERCASE]; - allMethods.forEach((method) => { - this[method] = (args1, ...args) => { - if (typeof args1 === "string") { - this.#path = args1; - } else { - this.#addRoute(method, this.#path, args1); - } - args.forEach((handler) => { - this.#addRoute(method, this.#path, handler); - }); - return this; - }; - }); - this.on = (method, path, ...handlers) => { - for (const p of [path].flat()) { - this.#path = p; - for (const m2 of [method].flat()) { - handlers.map((handler) => { - this.#addRoute(m2.toUpperCase(), this.#path, handler); - }); - } - } - return this; - }; - this.use = (arg1, ...handlers) => { - if (typeof arg1 === "string") { - this.#path = arg1; - } else { - this.#path = "*"; - handlers.unshift(arg1); - } - handlers.forEach((handler) => { - this.#addRoute(METHOD_NAME_ALL, this.#path, handler); - }); - return this; - }; - const { strict, ...optionsWithoutStrict } = options; - Object.assign(this, optionsWithoutStrict); - this.getPath = strict ?? true ? options.getPath ?? getPath : getPathNoStrict; - } - #clone() { - const clone = new _Hono({ - router: this.router, - getPath: this.getPath - }); - clone.errorHandler = this.errorHandler; - clone.#notFoundHandler = this.#notFoundHandler; - clone.routes = this.routes; - return clone; - } - #notFoundHandler = notFoundHandler; - // Cannot use `#` because it requires visibility at JavaScript runtime. - errorHandler = errorHandler; - /** - * `.route()` allows grouping other Hono instance in routes. - * - * @see {@link https://hono.dev/docs/api/routing#grouping} - * - * @param {string} path - base Path - * @param {Hono} app - other Hono instance - * @returns {Hono} routed Hono instance - * - * @example - * ```ts - * const app = new Hono() - * const app2 = new Hono() - * - * app2.get("/user", (c) => c.text("user")) - * app.route("/api", app2) // GET /api/user - * ``` - */ - route(path, app2) { - const subApp = this.basePath(path); - app2.routes.map((r) => { - let handler; - if (app2.errorHandler === errorHandler) { - handler = r.handler; - } else { - handler = /* @__PURE__ */ __name(async (c, next) => (await compose([], app2.errorHandler)(c, () => r.handler(c, next))).res, "handler"); - handler[COMPOSED_HANDLER] = r.handler; - } - subApp.#addRoute(r.method, r.path, handler); - }); - return this; - } - /** - * `.basePath()` allows base paths to be specified. - * - * @see {@link https://hono.dev/docs/api/routing#base-path} - * - * @param {string} path - base Path - * @returns {Hono} changed Hono instance - * - * @example - * ```ts - * const api = new Hono().basePath('/api') - * ``` - */ - basePath(path) { - const subApp = this.#clone(); - subApp._basePath = mergePath(this._basePath, path); - return subApp; - } - /** - * `.onError()` handles an error and returns a customized Response. - * - * @see {@link https://hono.dev/docs/api/hono#error-handling} - * - * @param {ErrorHandler} handler - request Handler for error - * @returns {Hono} changed Hono instance - * - * @example - * ```ts - * app.onError((err, c) => { - * console.error(`${err}`) - * return c.text('Custom Error Message', 500) - * }) - * ``` - */ - onError = /* @__PURE__ */ __name((handler) => { - this.errorHandler = handler; - return this; - }, "onError"); - /** - * `.notFound()` allows you to customize a Not Found Response. - * - * @see {@link https://hono.dev/docs/api/hono#not-found} - * - * @param {NotFoundHandler} handler - request handler for not-found - * @returns {Hono} changed Hono instance - * - * @example - * ```ts - * app.notFound((c) => { - * return c.text('Custom 404 Message', 404) - * }) - * ``` - */ - notFound = /* @__PURE__ */ __name((handler) => { - this.#notFoundHandler = handler; - return this; - }, "notFound"); - /** - * `.mount()` allows you to mount applications built with other frameworks into your Hono application. - * - * @see {@link https://hono.dev/docs/api/hono#mount} - * - * @param {string} path - base Path - * @param {Function} applicationHandler - other Request Handler - * @param {MountOptions} [options] - options of `.mount()` - * @returns {Hono} mounted Hono instance - * - * @example - * ```ts - * import { Router as IttyRouter } from 'itty-router' - * import { Hono } from 'hono' - * // Create itty-router application - * const ittyRouter = IttyRouter() - * // GET /itty-router/hello - * ittyRouter.get('/hello', () => new Response('Hello from itty-router')) - * - * const app = new Hono() - * app.mount('/itty-router', ittyRouter.handle) - * ``` - * - * @example - * ```ts - * const app = new Hono() - * // Send the request to another application without modification. - * app.mount('/app', anotherApp, { - * replaceRequest: (req) => req, - * }) - * ``` - */ - mount(path, applicationHandler, options) { - let replaceRequest; - let optionHandler; - if (options) { - if (typeof options === "function") { - optionHandler = options; - } else { - optionHandler = options.optionHandler; - if (options.replaceRequest === false) { - replaceRequest = /* @__PURE__ */ __name((request) => request, "replaceRequest"); - } else { - replaceRequest = options.replaceRequest; - } - } - } - const getOptions = optionHandler ? (c) => { - const options2 = optionHandler(c); - return Array.isArray(options2) ? options2 : [options2]; - } : (c) => { - let executionContext = void 0; - try { - executionContext = c.executionCtx; - } catch { - } - return [c.env, executionContext]; - }; - replaceRequest ||= (() => { - const mergedPath = mergePath(this._basePath, path); - const pathPrefixLength = mergedPath === "/" ? 0 : mergedPath.length; - return (request) => { - const url = new URL(request.url); - url.pathname = url.pathname.slice(pathPrefixLength) || "/"; - return new Request(url, request); - }; - })(); - const handler = /* @__PURE__ */ __name(async (c, next) => { - const res = await applicationHandler(replaceRequest(c.req.raw), ...getOptions(c)); - if (res) { - return res; - } - await next(); - }, "handler"); - this.#addRoute(METHOD_NAME_ALL, mergePath(path, "*"), handler); - return this; - } - #addRoute(method, path, handler) { - method = method.toUpperCase(); - path = mergePath(this._basePath, path); - const r = { basePath: this._basePath, path, method, handler }; - this.router.add(method, path, [handler, r]); - this.routes.push(r); - } - #handleError(err, c) { - if (err instanceof Error) { - return this.errorHandler(err, c); - } - throw err; - } - #dispatch(request, executionCtx, env, method) { - if (method === "HEAD") { - return (async () => new Response(null, await this.#dispatch(request, executionCtx, env, "GET")))(); - } - const path = this.getPath(request, { env }); - const matchResult = this.router.match(method, path); - const c = new Context(request, { - path, - matchResult, - env, - executionCtx, - notFoundHandler: this.#notFoundHandler - }); - if (matchResult[0].length === 1) { - let res; - try { - res = matchResult[0][0][0][0](c, async () => { - c.res = await this.#notFoundHandler(c); - }); - } catch (err) { - return this.#handleError(err, c); - } - return res instanceof Promise ? res.then( - (resolved) => resolved || (c.finalized ? c.res : this.#notFoundHandler(c)) - ).catch((err) => this.#handleError(err, c)) : res ?? this.#notFoundHandler(c); - } - const composed = compose(matchResult[0], this.errorHandler, this.#notFoundHandler); - return (async () => { - try { - const context = await composed(c); - if (!context.finalized) { - throw new Error( - "Context is not finalized. Did you forget to return a Response object or `await next()`?" - ); - } - return context.res; - } catch (err) { - return this.#handleError(err, c); - } - })(); - } - /** - * `.fetch()` will be entry point of your app. - * - * @see {@link https://hono.dev/docs/api/hono#fetch} - * - * @param {Request} request - request Object of request - * @param {Env} Env - env Object - * @param {ExecutionContext} - context of execution - * @returns {Response | Promise} response of request - * - */ - fetch = /* @__PURE__ */ __name((request, ...rest) => { - return this.#dispatch(request, rest[1], rest[0], request.method); - }, "fetch"); - /** - * `.request()` is a useful method for testing. - * You can pass a URL or pathname to send a GET request. - * app will return a Response object. - * ```ts - * test('GET /hello is ok', async () => { - * const res = await app.request('/hello') - * expect(res.status).toBe(200) - * }) - * ``` - * @see https://hono.dev/docs/api/hono#request - */ - request = /* @__PURE__ */ __name((input, requestInit, Env, executionCtx) => { - if (input instanceof Request) { - return this.fetch(requestInit ? new Request(input, requestInit) : input, Env, executionCtx); - } - input = input.toString(); - return this.fetch( - new Request( - /^https?:\/\//.test(input) ? input : `http://localhost${mergePath("/", input)}`, - requestInit - ), - Env, - executionCtx - ); - }, "request"); - /** - * `.fire()` automatically adds a global fetch event listener. - * This can be useful for environments that adhere to the Service Worker API, such as non-ES module Cloudflare Workers. - * @deprecated - * Use `fire` from `hono/service-worker` instead. - * ```ts - * import { Hono } from 'hono' - * import { fire } from 'hono/service-worker' - * - * const app = new Hono() - * // ... - * fire(app) - * ``` - * @see https://hono.dev/docs/api/hono#fire - * @see https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API - * @see https://developers.cloudflare.com/workers/reference/migrate-to-module-workers/ - */ - fire = /* @__PURE__ */ __name(() => { - addEventListener("fetch", (event) => { - event.respondWith(this.#dispatch(event.request, event, void 0, event.request.method)); - }); - }, "fire"); -}; - -// node_modules/.pnpm/hono@4.12.5/node_modules/hono/dist/router/reg-exp-router/index.js -init_modules_watch_stub(); -init_performance2(); - -// node_modules/.pnpm/hono@4.12.5/node_modules/hono/dist/router/reg-exp-router/router.js -init_modules_watch_stub(); -init_performance2(); - -// node_modules/.pnpm/hono@4.12.5/node_modules/hono/dist/router/reg-exp-router/matcher.js -init_modules_watch_stub(); -init_performance2(); -var emptyParam = []; -function match(method, path) { - const matchers = this.buildAllMatchers(); - const match22 = /* @__PURE__ */ __name(((method2, path2) => { - const matcher = matchers[method2] || matchers[METHOD_NAME_ALL]; - const staticMatch = matcher[2][path2]; - if (staticMatch) { - return staticMatch; - } - const match3 = path2.match(matcher[0]); - if (!match3) { - return [[], emptyParam]; - } - const index = match3.indexOf("", 1); - return [matcher[1][index], match3]; - }), "match2"); - this.match = match22; - return match22(method, path); -} -__name(match, "match"); - -// node_modules/.pnpm/hono@4.12.5/node_modules/hono/dist/router/reg-exp-router/node.js -init_modules_watch_stub(); -init_performance2(); -var LABEL_REG_EXP_STR = "[^/]+"; -var ONLY_WILDCARD_REG_EXP_STR = ".*"; -var TAIL_WILDCARD_REG_EXP_STR = "(?:|/.*)"; -var PATH_ERROR = /* @__PURE__ */ Symbol(); -var regExpMetaChars = new Set(".\\+*[^]$()"); -function compareKey(a, b) { - if (a.length === 1) { - return b.length === 1 ? a < b ? -1 : 1 : -1; - } - if (b.length === 1) { - return 1; - } - if (a === ONLY_WILDCARD_REG_EXP_STR || a === TAIL_WILDCARD_REG_EXP_STR) { - return 1; - } else if (b === ONLY_WILDCARD_REG_EXP_STR || b === TAIL_WILDCARD_REG_EXP_STR) { - return -1; - } - if (a === LABEL_REG_EXP_STR) { - return 1; - } else if (b === LABEL_REG_EXP_STR) { - return -1; - } - return a.length === b.length ? a < b ? -1 : 1 : b.length - a.length; -} -__name(compareKey, "compareKey"); -var Node = class _Node { - static { - __name(this, "_Node"); - } - #index; - #varIndex; - #children = /* @__PURE__ */ Object.create(null); - insert(tokens, index, paramMap, context, pathErrorCheckOnly) { - if (tokens.length === 0) { - if (this.#index !== void 0) { - throw PATH_ERROR; - } - if (pathErrorCheckOnly) { - return; - } - this.#index = index; - return; - } - const [token, ...restTokens] = tokens; - const pattern = token === "*" ? restTokens.length === 0 ? ["", "", ONLY_WILDCARD_REG_EXP_STR] : ["", "", LABEL_REG_EXP_STR] : token === "/*" ? ["", "", TAIL_WILDCARD_REG_EXP_STR] : token.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/); - let node; - if (pattern) { - const name = pattern[1]; - let regexpStr = pattern[2] || LABEL_REG_EXP_STR; - if (name && pattern[2]) { - if (regexpStr === ".*") { - throw PATH_ERROR; - } - regexpStr = regexpStr.replace(/^\((?!\?:)(?=[^)]+\)$)/, "(?:"); - if (/\((?!\?:)/.test(regexpStr)) { - throw PATH_ERROR; - } - } - node = this.#children[regexpStr]; - if (!node) { - if (Object.keys(this.#children).some( - (k) => k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR - )) { - throw PATH_ERROR; - } - if (pathErrorCheckOnly) { - return; - } - node = this.#children[regexpStr] = new _Node(); - if (name !== "") { - node.#varIndex = context.varIndex++; - } - } - if (!pathErrorCheckOnly && name !== "") { - paramMap.push([name, node.#varIndex]); - } - } else { - node = this.#children[token]; - if (!node) { - if (Object.keys(this.#children).some( - (k) => k.length > 1 && k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR - )) { - throw PATH_ERROR; - } - if (pathErrorCheckOnly) { - return; - } - node = this.#children[token] = new _Node(); - } - } - node.insert(restTokens, index, paramMap, context, pathErrorCheckOnly); - } - buildRegExpStr() { - const childKeys = Object.keys(this.#children).sort(compareKey); - const strList = childKeys.map((k) => { - const c = this.#children[k]; - return (typeof c.#varIndex === "number" ? `(${k})@${c.#varIndex}` : regExpMetaChars.has(k) ? `\\${k}` : k) + c.buildRegExpStr(); - }); - if (typeof this.#index === "number") { - strList.unshift(`#${this.#index}`); - } - if (strList.length === 0) { - return ""; - } - if (strList.length === 1) { - return strList[0]; - } - return "(?:" + strList.join("|") + ")"; - } -}; - -// node_modules/.pnpm/hono@4.12.5/node_modules/hono/dist/router/reg-exp-router/trie.js -init_modules_watch_stub(); -init_performance2(); -var Trie = class { - static { - __name(this, "Trie"); - } - #context = { varIndex: 0 }; - #root = new Node(); - insert(path, index, pathErrorCheckOnly) { - const paramAssoc = []; - const groups = []; - for (let i = 0; ; ) { - let replaced = false; - path = path.replace(/\{[^}]+\}/g, (m2) => { - const mark = `@\\${i}`; - groups[i] = [mark, m2]; - i++; - replaced = true; - return mark; - }); - if (!replaced) { - break; - } - } - const tokens = path.match(/(?::[^\/]+)|(?:\/\*$)|./g) || []; - for (let i = groups.length - 1; i >= 0; i--) { - const [mark] = groups[i]; - for (let j = tokens.length - 1; j >= 0; j--) { - if (tokens[j].indexOf(mark) !== -1) { - tokens[j] = tokens[j].replace(mark, groups[i][1]); - break; - } - } - } - this.#root.insert(tokens, index, paramAssoc, this.#context, pathErrorCheckOnly); - return paramAssoc; - } - buildRegExp() { - let regexp = this.#root.buildRegExpStr(); - if (regexp === "") { - return [/^$/, [], []]; - } - let captureIndex = 0; - const indexReplacementMap = []; - const paramReplacementMap = []; - regexp = regexp.replace(/#(\d+)|@(\d+)|\.\*\$/g, (_, handlerIndex, paramIndex) => { - if (handlerIndex !== void 0) { - indexReplacementMap[++captureIndex] = Number(handlerIndex); - return "$()"; - } - if (paramIndex !== void 0) { - paramReplacementMap[Number(paramIndex)] = ++captureIndex; - return ""; - } - return ""; - }); - return [new RegExp(`^${regexp}`), indexReplacementMap, paramReplacementMap]; - } -}; - -// node_modules/.pnpm/hono@4.12.5/node_modules/hono/dist/router/reg-exp-router/router.js -var nullMatcher = [/^$/, [], /* @__PURE__ */ Object.create(null)]; -var wildcardRegExpCache = /* @__PURE__ */ Object.create(null); -function buildWildcardRegExp(path) { - return wildcardRegExpCache[path] ??= new RegExp( - path === "*" ? "" : `^${path.replace( - /\/\*$|([.\\+*[^\]$()])/g, - (_, metaChar) => metaChar ? `\\${metaChar}` : "(?:|/.*)" - )}$` - ); -} -__name(buildWildcardRegExp, "buildWildcardRegExp"); -function clearWildcardRegExpCache() { - wildcardRegExpCache = /* @__PURE__ */ Object.create(null); -} -__name(clearWildcardRegExpCache, "clearWildcardRegExpCache"); -function buildMatcherFromPreprocessedRoutes(routes) { - const trie = new Trie(); - const handlerData = []; - if (routes.length === 0) { - return nullMatcher; - } - const routesWithStaticPathFlag = routes.map( - (route) => [!/\*|\/:/.test(route[0]), ...route] - ).sort( - ([isStaticA, pathA], [isStaticB, pathB]) => isStaticA ? 1 : isStaticB ? -1 : pathA.length - pathB.length - ); - const staticMap = /* @__PURE__ */ Object.create(null); - for (let i = 0, j = -1, len = routesWithStaticPathFlag.length; i < len; i++) { - const [pathErrorCheckOnly, path, handlers] = routesWithStaticPathFlag[i]; - if (pathErrorCheckOnly) { - staticMap[path] = [handlers.map(([h2]) => [h2, /* @__PURE__ */ Object.create(null)]), emptyParam]; - } else { - j++; - } - let paramAssoc; - try { - paramAssoc = trie.insert(path, j, pathErrorCheckOnly); - } catch (e) { - throw e === PATH_ERROR ? new UnsupportedPathError(path) : e; - } - if (pathErrorCheckOnly) { - continue; - } - handlerData[j] = handlers.map(([h2, paramCount]) => { - const paramIndexMap = /* @__PURE__ */ Object.create(null); - paramCount -= 1; - for (; paramCount >= 0; paramCount--) { - const [key, value] = paramAssoc[paramCount]; - paramIndexMap[key] = value; - } - return [h2, paramIndexMap]; - }); - } - const [regexp, indexReplacementMap, paramReplacementMap] = trie.buildRegExp(); - for (let i = 0, len = handlerData.length; i < len; i++) { - for (let j = 0, len2 = handlerData[i].length; j < len2; j++) { - const map = handlerData[i][j]?.[1]; - if (!map) { - continue; - } - const keys = Object.keys(map); - for (let k = 0, len3 = keys.length; k < len3; k++) { - map[keys[k]] = paramReplacementMap[map[keys[k]]]; - } - } - } - const handlerMap = []; - for (const i in indexReplacementMap) { - handlerMap[i] = handlerData[indexReplacementMap[i]]; - } - return [regexp, handlerMap, staticMap]; -} -__name(buildMatcherFromPreprocessedRoutes, "buildMatcherFromPreprocessedRoutes"); -function findMiddleware(middleware, path) { - if (!middleware) { - return void 0; - } - for (const k of Object.keys(middleware).sort((a, b) => b.length - a.length)) { - if (buildWildcardRegExp(k).test(path)) { - return [...middleware[k]]; - } - } - return void 0; -} -__name(findMiddleware, "findMiddleware"); -var RegExpRouter = class { - static { - __name(this, "RegExpRouter"); - } - name = "RegExpRouter"; - #middleware; - #routes; - constructor() { - this.#middleware = { [METHOD_NAME_ALL]: /* @__PURE__ */ Object.create(null) }; - this.#routes = { [METHOD_NAME_ALL]: /* @__PURE__ */ Object.create(null) }; - } - add(method, path, handler) { - const middleware = this.#middleware; - const routes = this.#routes; - if (!middleware || !routes) { - throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT); - } - if (!middleware[method]) { - ; - [middleware, routes].forEach((handlerMap) => { - handlerMap[method] = /* @__PURE__ */ Object.create(null); - Object.keys(handlerMap[METHOD_NAME_ALL]).forEach((p) => { - handlerMap[method][p] = [...handlerMap[METHOD_NAME_ALL][p]]; - }); - }); - } - if (path === "/*") { - path = "*"; - } - const paramCount = (path.match(/\/:/g) || []).length; - if (/\*$/.test(path)) { - const re = buildWildcardRegExp(path); - if (method === METHOD_NAME_ALL) { - Object.keys(middleware).forEach((m2) => { - middleware[m2][path] ||= findMiddleware(middleware[m2], path) || findMiddleware(middleware[METHOD_NAME_ALL], path) || []; - }); - } else { - middleware[method][path] ||= findMiddleware(middleware[method], path) || findMiddleware(middleware[METHOD_NAME_ALL], path) || []; - } - Object.keys(middleware).forEach((m2) => { - if (method === METHOD_NAME_ALL || method === m2) { - Object.keys(middleware[m2]).forEach((p) => { - re.test(p) && middleware[m2][p].push([handler, paramCount]); - }); - } - }); - Object.keys(routes).forEach((m2) => { - if (method === METHOD_NAME_ALL || method === m2) { - Object.keys(routes[m2]).forEach( - (p) => re.test(p) && routes[m2][p].push([handler, paramCount]) - ); - } - }); - return; - } - const paths = checkOptionalParameter(path) || [path]; - for (let i = 0, len = paths.length; i < len; i++) { - const path2 = paths[i]; - Object.keys(routes).forEach((m2) => { - if (method === METHOD_NAME_ALL || method === m2) { - routes[m2][path2] ||= [ - ...findMiddleware(middleware[m2], path2) || findMiddleware(middleware[METHOD_NAME_ALL], path2) || [] - ]; - routes[m2][path2].push([handler, paramCount - len + i + 1]); - } - }); - } - } - match = match; - buildAllMatchers() { - const matchers = /* @__PURE__ */ Object.create(null); - Object.keys(this.#routes).concat(Object.keys(this.#middleware)).forEach((method) => { - matchers[method] ||= this.#buildMatcher(method); - }); - this.#middleware = this.#routes = void 0; - clearWildcardRegExpCache(); - return matchers; - } - #buildMatcher(method) { - const routes = []; - let hasOwnRoute = method === METHOD_NAME_ALL; - [this.#middleware, this.#routes].forEach((r) => { - const ownRoute = r[method] ? Object.keys(r[method]).map((path) => [path, r[method][path]]) : []; - if (ownRoute.length !== 0) { - hasOwnRoute ||= true; - routes.push(...ownRoute); - } else if (method !== METHOD_NAME_ALL) { - routes.push( - ...Object.keys(r[METHOD_NAME_ALL]).map((path) => [path, r[METHOD_NAME_ALL][path]]) - ); - } - }); - if (!hasOwnRoute) { - return null; - } else { - return buildMatcherFromPreprocessedRoutes(routes); - } - } -}; - -// node_modules/.pnpm/hono@4.12.5/node_modules/hono/dist/router/reg-exp-router/prepared-router.js -init_modules_watch_stub(); -init_performance2(); - -// node_modules/.pnpm/hono@4.12.5/node_modules/hono/dist/router/smart-router/index.js -init_modules_watch_stub(); -init_performance2(); - -// node_modules/.pnpm/hono@4.12.5/node_modules/hono/dist/router/smart-router/router.js -init_modules_watch_stub(); -init_performance2(); -var SmartRouter = class { - static { - __name(this, "SmartRouter"); - } - name = "SmartRouter"; - #routers = []; - #routes = []; - constructor(init2) { - this.#routers = init2.routers; - } - add(method, path, handler) { - if (!this.#routes) { - throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT); - } - this.#routes.push([method, path, handler]); - } - match(method, path) { - if (!this.#routes) { - throw new Error("Fatal error"); - } - const routers = this.#routers; - const routes = this.#routes; - const len = routers.length; - let i = 0; - let res; - for (; i < len; i++) { - const router = routers[i]; - try { - for (let i2 = 0, len2 = routes.length; i2 < len2; i2++) { - router.add(...routes[i2]); - } - res = router.match(method, path); - } catch (e) { - if (e instanceof UnsupportedPathError) { - continue; - } - throw e; - } - this.match = router.match.bind(router); - this.#routers = [router]; - this.#routes = void 0; - break; - } - if (i === len) { - throw new Error("Fatal error"); - } - this.name = `SmartRouter + ${this.activeRouter.name}`; - return res; - } - get activeRouter() { - if (this.#routes || this.#routers.length !== 1) { - throw new Error("No active router has been determined yet."); - } - return this.#routers[0]; - } -}; - -// node_modules/.pnpm/hono@4.12.5/node_modules/hono/dist/router/trie-router/index.js -init_modules_watch_stub(); -init_performance2(); - -// node_modules/.pnpm/hono@4.12.5/node_modules/hono/dist/router/trie-router/router.js -init_modules_watch_stub(); -init_performance2(); - -// node_modules/.pnpm/hono@4.12.5/node_modules/hono/dist/router/trie-router/node.js -init_modules_watch_stub(); -init_performance2(); -var emptyParams = /* @__PURE__ */ Object.create(null); -var hasChildren = /* @__PURE__ */ __name((children) => { - for (const _ in children) { - return true; - } - return false; -}, "hasChildren"); -var Node2 = class _Node2 { - static { - __name(this, "_Node"); - } - #methods; - #children; - #patterns; - #order = 0; - #params = emptyParams; - constructor(method, handler, children) { - this.#children = children || /* @__PURE__ */ Object.create(null); - this.#methods = []; - if (method && handler) { - const m2 = /* @__PURE__ */ Object.create(null); - m2[method] = { handler, possibleKeys: [], score: 0 }; - this.#methods = [m2]; - } - this.#patterns = []; - } - insert(method, path, handler) { - this.#order = ++this.#order; - let curNode = this; - const parts = splitRoutingPath(path); - const possibleKeys = []; - for (let i = 0, len = parts.length; i < len; i++) { - const p = parts[i]; - const nextP = parts[i + 1]; - const pattern = getPattern(p, nextP); - const key = Array.isArray(pattern) ? pattern[0] : p; - if (key in curNode.#children) { - curNode = curNode.#children[key]; - if (pattern) { - possibleKeys.push(pattern[1]); - } - continue; - } - curNode.#children[key] = new _Node2(); - if (pattern) { - curNode.#patterns.push(pattern); - possibleKeys.push(pattern[1]); - } - curNode = curNode.#children[key]; - } - curNode.#methods.push({ - [method]: { - handler, - possibleKeys: possibleKeys.filter((v, i, a) => a.indexOf(v) === i), - score: this.#order - } - }); - return curNode; - } - #pushHandlerSets(handlerSets, node, method, nodeParams, params) { - for (let i = 0, len = node.#methods.length; i < len; i++) { - const m2 = node.#methods[i]; - const handlerSet = m2[method] || m2[METHOD_NAME_ALL]; - const processedSet = {}; - if (handlerSet !== void 0) { - handlerSet.params = /* @__PURE__ */ Object.create(null); - handlerSets.push(handlerSet); - if (nodeParams !== emptyParams || params && params !== emptyParams) { - for (let i2 = 0, len2 = handlerSet.possibleKeys.length; i2 < len2; i2++) { - const key = handlerSet.possibleKeys[i2]; - const processed = processedSet[handlerSet.score]; - handlerSet.params[key] = params?.[key] && !processed ? params[key] : nodeParams[key] ?? params?.[key]; - processedSet[handlerSet.score] = true; - } - } - } - } - } - search(method, path) { - const handlerSets = []; - this.#params = emptyParams; - const curNode = this; - let curNodes = [curNode]; - const parts = splitPath(path); - const curNodesQueue = []; - const len = parts.length; - let partOffsets = null; - for (let i = 0; i < len; i++) { - const part = parts[i]; - const isLast = i === len - 1; - const tempNodes = []; - for (let j = 0, len2 = curNodes.length; j < len2; j++) { - const node = curNodes[j]; - const nextNode = node.#children[part]; - if (nextNode) { - nextNode.#params = node.#params; - if (isLast) { - if (nextNode.#children["*"]) { - this.#pushHandlerSets(handlerSets, nextNode.#children["*"], method, node.#params); - } - this.#pushHandlerSets(handlerSets, nextNode, method, node.#params); - } else { - tempNodes.push(nextNode); - } - } - for (let k = 0, len3 = node.#patterns.length; k < len3; k++) { - const pattern = node.#patterns[k]; - const params = node.#params === emptyParams ? {} : { ...node.#params }; - if (pattern === "*") { - const astNode = node.#children["*"]; - if (astNode) { - this.#pushHandlerSets(handlerSets, astNode, method, node.#params); - astNode.#params = params; - tempNodes.push(astNode); - } - continue; - } - const [key, name, matcher] = pattern; - if (!part && !(matcher instanceof RegExp)) { - continue; - } - const child = node.#children[key]; - if (matcher instanceof RegExp) { - if (partOffsets === null) { - partOffsets = new Array(len); - let offset = path[0] === "/" ? 1 : 0; - for (let p = 0; p < len; p++) { - partOffsets[p] = offset; - offset += parts[p].length + 1; - } - } - const restPathString = path.substring(partOffsets[i]); - const m2 = matcher.exec(restPathString); - if (m2) { - params[name] = m2[0]; - this.#pushHandlerSets(handlerSets, child, method, node.#params, params); - if (hasChildren(child.#children)) { - child.#params = params; - const componentCount = m2[0].match(/\//)?.length ?? 0; - const targetCurNodes = curNodesQueue[componentCount] ||= []; - targetCurNodes.push(child); - } - continue; - } - } - if (matcher === true || matcher.test(part)) { - params[name] = part; - if (isLast) { - this.#pushHandlerSets(handlerSets, child, method, params, node.#params); - if (child.#children["*"]) { - this.#pushHandlerSets( - handlerSets, - child.#children["*"], - method, - params, - node.#params - ); - } - } else { - child.#params = params; - tempNodes.push(child); - } - } - } - } - const shifted = curNodesQueue.shift(); - curNodes = shifted ? tempNodes.concat(shifted) : tempNodes; - } - if (handlerSets.length > 1) { - handlerSets.sort((a, b) => { - return a.score - b.score; - }); - } - return [handlerSets.map(({ handler, params }) => [handler, params])]; - } -}; - -// node_modules/.pnpm/hono@4.12.5/node_modules/hono/dist/router/trie-router/router.js -var TrieRouter = class { - static { - __name(this, "TrieRouter"); - } - name = "TrieRouter"; - #node; - constructor() { - this.#node = new Node2(); - } - add(method, path, handler) { - const results = checkOptionalParameter(path); - if (results) { - for (let i = 0, len = results.length; i < len; i++) { - this.#node.insert(method, results[i], handler); - } - return; - } - this.#node.insert(method, path, handler); - } - match(method, path) { - return this.#node.search(method, path); - } -}; - -// node_modules/.pnpm/hono@4.12.5/node_modules/hono/dist/hono.js -var Hono2 = class extends Hono { - static { - __name(this, "Hono"); - } - /** - * Creates an instance of the Hono class. - * - * @param options - Optional configuration options for the Hono instance. - */ - constructor(options = {}) { - super(options); - this.router = options.router ?? new SmartRouter({ - routers: [new RegExpRouter(), new TrieRouter()] - }); - } -}; - -// node_modules/.pnpm/grammy@1.41.1/node_modules/grammy/out/web.mjs -init_modules_watch_stub(); -init_performance2(); -var filterQueryCache = /* @__PURE__ */ new Map(); -function matchFilter(filter) { - const queries = Array.isArray(filter) ? filter : [ - filter - ]; - const key = queries.join(","); - const predicate = filterQueryCache.get(key) ?? (() => { - const parsed = parse(queries); - const pred = compile(parsed); - filterQueryCache.set(key, pred); - return pred; - })(); - return (ctx) => predicate(ctx); -} -__name(matchFilter, "matchFilter"); -function parse(filter) { - return Array.isArray(filter) ? filter.map((q) => q.split(":")) : [ - filter.split(":") - ]; -} -__name(parse, "parse"); -function compile(parsed) { - const preprocessed = parsed.flatMap((q) => check(q, preprocess(q))); - const ltree = treeify(preprocessed); - const predicate = arborist(ltree); - return (ctx) => !!predicate(ctx.update, ctx); -} -__name(compile, "compile"); -function preprocess(filter) { - const valid = UPDATE_KEYS; - const expanded = [ - filter - ].flatMap((q) => { - const [l1, l2, l3] = q; - if (!(l1 in L1_SHORTCUTS)) return [ - q - ]; - if (!l1 && !l2 && !l3) return [ - q - ]; - const targets = L1_SHORTCUTS[l1]; - const expanded2 = targets.map((s2) => [ - s2, - l2, - l3 - ]); - if (l2 === void 0) return expanded2; - if (l2 in L2_SHORTCUTS && (l2 || l3)) return expanded2; - return expanded2.filter(([s2]) => !!valid[s2]?.[l2]); - }).flatMap((q) => { - const [l1, l2, l3] = q; - if (!(l2 in L2_SHORTCUTS)) return [ - q - ]; - if (!l2 && !l3) return [ - q - ]; - const targets = L2_SHORTCUTS[l2]; - const expanded2 = targets.map((s2) => [ - l1, - s2, - l3 - ]); - if (l3 === void 0) return expanded2; - return expanded2.filter(([, s2]) => !!valid[l1]?.[s2]?.[l3]); - }); - if (expanded.length === 0) { - throw new Error(`Shortcuts in '${filter.join(":")}' do not expand to any valid filter query`); - } - return expanded; -} -__name(preprocess, "preprocess"); -function check(original, preprocessed) { - if (preprocessed.length === 0) throw new Error("Empty filter query given"); - const errors = preprocessed.map(checkOne).filter((r) => r !== true); - if (errors.length === 0) return preprocessed; - else if (errors.length === 1) throw new Error(errors[0]); - else { - throw new Error(`Invalid filter query '${original.join(":")}'. There are ${errors.length} errors after expanding the contained shortcuts: ${errors.join("; ")}`); - } -} -__name(check, "check"); -function checkOne(filter) { - const [l1, l2, l3, ...n] = filter; - if (l1 === void 0) return "Empty filter query given"; - if (!(l1 in UPDATE_KEYS)) { - const permitted = Object.keys(UPDATE_KEYS); - return `Invalid L1 filter '${l1}' given in '${filter.join(":")}'. Permitted values are: ${permitted.map((k) => `'${k}'`).join(", ")}.`; - } - if (l2 === void 0) return true; - const l1Obj = UPDATE_KEYS[l1]; - if (!(l2 in l1Obj)) { - const permitted = Object.keys(l1Obj); - return `Invalid L2 filter '${l2}' given in '${filter.join(":")}'. Permitted values are: ${permitted.map((k) => `'${k}'`).join(", ")}.`; - } - if (l3 === void 0) return true; - const l2Obj = l1Obj[l2]; - if (!(l3 in l2Obj)) { - const permitted = Object.keys(l2Obj); - return `Invalid L3 filter '${l3}' given in '${filter.join(":")}'. ${permitted.length === 0 ? `No further filtering is possible after '${l1}:${l2}'.` : `Permitted values are: ${permitted.map((k) => `'${k}'`).join(", ")}.`}`; - } - if (n.length === 0) return true; - return `Cannot filter further than three levels, ':${n.join(":")}' is invalid!`; -} -__name(checkOne, "checkOne"); -function treeify(paths) { - const tree = {}; - for (const [l1, l2, l3] of paths) { - const subtree = tree[l1] ??= {}; - if (l2 !== void 0) { - const set = subtree[l2] ??= /* @__PURE__ */ new Set(); - if (l3 !== void 0) set.add(l3); - } - } - return tree; -} -__name(treeify, "treeify"); -function or(left, right) { - return (obj, ctx) => left(obj, ctx) || right(obj, ctx); -} -__name(or, "or"); -function concat(get2, test) { - return (obj, ctx) => { - const nextObj = get2(obj, ctx); - return nextObj && test(nextObj, ctx); - }; -} -__name(concat, "concat"); -function leaf(pred) { - return (obj, ctx) => pred(obj, ctx) != null; -} -__name(leaf, "leaf"); -function arborist(tree) { - const l1Predicates = Object.entries(tree).map(([l1, subtree]) => { - const l1Pred = /* @__PURE__ */ __name((obj) => obj[l1], "l1Pred"); - const l2Predicates = Object.entries(subtree).map(([l2, set]) => { - const l2Pred = /* @__PURE__ */ __name((obj) => obj[l2], "l2Pred"); - const l3Predicates = Array.from(set).map((l3) => { - const l3Pred = l3 === "me" ? (obj, ctx) => { - const me = ctx.me.id; - return testMaybeArray(obj, (u) => u.id === me); - } : (obj) => testMaybeArray(obj, (e) => e[l3] || e.type === l3); - return l3Pred; - }); - return l3Predicates.length === 0 ? leaf(l2Pred) : concat(l2Pred, l3Predicates.reduce(or)); - }); - return l2Predicates.length === 0 ? leaf(l1Pred) : concat(l1Pred, l2Predicates.reduce(or)); - }); - if (l1Predicates.length === 0) { - throw new Error("Cannot create filter function for empty query"); - } - return l1Predicates.reduce(or); -} -__name(arborist, "arborist"); -function testMaybeArray(t2, pred) { - const p = /* @__PURE__ */ __name((x) => x != null && pred(x), "p"); - return Array.isArray(t2) ? t2.some(p) : p(t2); -} -__name(testMaybeArray, "testMaybeArray"); -var ENTITY_KEYS = { - mention: {}, - hashtag: {}, - cashtag: {}, - bot_command: {}, - url: {}, - email: {}, - phone_number: {}, - bold: {}, - italic: {}, - underline: {}, - strikethrough: {}, - spoiler: {}, - blockquote: {}, - expandable_blockquote: {}, - code: {}, - pre: {}, - text_link: {}, - text_mention: {}, - custom_emoji: {} -}; -var USER_KEYS = { - me: {}, - is_bot: {}, - is_premium: {}, - added_to_attachment_menu: {} -}; -var FORWARD_ORIGIN_KEYS = { - user: {}, - hidden_user: {}, - chat: {}, - channel: {} -}; -var STICKER_KEYS = { - is_video: {}, - is_animated: {}, - premium_animation: {} -}; -var REACTION_KEYS = { - emoji: {}, - custom_emoji: {}, - paid: {} -}; -var GIFT_INFO_KEYS = { - can_be_upgraded: {}, - is_upgrade_separate: {}, - is_private: {} -}; -var COMMON_MESSAGE_KEYS = { - forward_origin: FORWARD_ORIGIN_KEYS, - is_topic_message: {}, - is_automatic_forward: {}, - business_connection_id: {}, - text: {}, - animation: {}, - audio: {}, - document: {}, - paid_media: {}, - photo: {}, - sticker: STICKER_KEYS, - story: {}, - video: {}, - video_note: {}, - voice: {}, - contact: {}, - dice: {}, - game: {}, - poll: {}, - venue: {}, - location: {}, - entities: ENTITY_KEYS, - caption_entities: ENTITY_KEYS, - caption: {}, - link_preview_options: { - url: {}, - prefer_small_media: {}, - prefer_large_media: {}, - show_above_text: {} - }, - effect_id: {}, - paid_star_count: {}, - has_media_spoiler: {}, - new_chat_title: {}, - new_chat_photo: {}, - delete_chat_photo: {}, - message_auto_delete_timer_changed: {}, - pinned_message: {}, - invoice: {}, - proximity_alert_triggered: {}, - chat_background_set: {}, - giveaway_created: {}, - giveaway: { - only_new_members: {}, - has_public_winners: {} - }, - giveaway_winners: { - only_new_members: {}, - was_refunded: {} - }, - giveaway_completed: {}, - gift: GIFT_INFO_KEYS, - gift_upgrade_sent: GIFT_INFO_KEYS, - unique_gift: { - transfer_star_count: {} - }, - paid_message_price_changed: {}, - video_chat_scheduled: {}, - video_chat_started: {}, - video_chat_ended: {}, - video_chat_participants_invited: {}, - web_app_data: {} -}; -var MESSAGE_KEYS = { - ...COMMON_MESSAGE_KEYS, - direct_messages_topic: {}, - chat_owner_left: { - new_owner: {} - }, - chat_owner_changd: {}, - new_chat_members: USER_KEYS, - left_chat_member: USER_KEYS, - group_chat_created: {}, - supergroup_chat_created: {}, - migrate_to_chat_id: {}, - migrate_from_chat_id: {}, - successful_payment: {}, - refunded_payment: {}, - users_shared: {}, - chat_shared: {}, - connected_website: {}, - write_access_allowed: {}, - passport_data: {}, - boost_added: {}, - forum_topic_created: { - is_name_implicit: {} - }, - forum_topic_edited: { - name: {}, - icon_custom_emoji_id: {} - }, - forum_topic_closed: {}, - forum_topic_reopened: {}, - general_forum_topic_hidden: {}, - general_forum_topic_unhidden: {}, - checklist: { - others_can_add_tasks: {}, - others_can_mark_tasks_as_done: {} - }, - checklist_tasks_done: {}, - checklist_tasks_added: {}, - suggested_post_info: {}, - suggested_post_approved: {}, - suggested_post_approval_failed: {}, - suggested_post_declined: {}, - suggested_post_paid: {}, - suggested_post_refunded: {}, - sender_boost_count: {} -}; -var CHANNEL_POST_KEYS = { - ...COMMON_MESSAGE_KEYS, - channel_chat_created: {}, - direct_message_price_changed: {}, - is_paid_post: {} -}; -var BUSINESS_CONNECTION_KEYS = { - can_reply: {}, - is_enabled: {} -}; -var MESSAGE_REACTION_KEYS = { - old_reaction: REACTION_KEYS, - new_reaction: REACTION_KEYS -}; -var MESSAGE_REACTION_COUNT_UPDATED_KEYS = { - reactions: REACTION_KEYS -}; -var CALLBACK_QUERY_KEYS = { - data: {}, - game_short_name: {} -}; -var CHAT_MEMBER_UPDATED_KEYS = { - from: USER_KEYS -}; -var UPDATE_KEYS = { - message: MESSAGE_KEYS, - edited_message: MESSAGE_KEYS, - channel_post: CHANNEL_POST_KEYS, - edited_channel_post: CHANNEL_POST_KEYS, - business_connection: BUSINESS_CONNECTION_KEYS, - business_message: MESSAGE_KEYS, - edited_business_message: MESSAGE_KEYS, - deleted_business_messages: {}, - inline_query: {}, - chosen_inline_result: {}, - callback_query: CALLBACK_QUERY_KEYS, - shipping_query: {}, - pre_checkout_query: {}, - poll: {}, - poll_answer: {}, - my_chat_member: CHAT_MEMBER_UPDATED_KEYS, - chat_member: CHAT_MEMBER_UPDATED_KEYS, - chat_join_request: {}, - message_reaction: MESSAGE_REACTION_KEYS, - message_reaction_count: MESSAGE_REACTION_COUNT_UPDATED_KEYS, - chat_boost: {}, - removed_chat_boost: {}, - purchased_paid_media: {} -}; -var L1_SHORTCUTS = { - "": [ - "message", - "channel_post" - ], - msg: [ - "message", - "channel_post" - ], - edit: [ - "edited_message", - "edited_channel_post" - ] -}; -var L2_SHORTCUTS = { - "": [ - "entities", - "caption_entities" - ], - media: [ - "photo", - "video" - ], - file: [ - "photo", - "animation", - "audio", - "document", - "video", - "video_note", - "voice", - "sticker" - ] -}; -var checker = { - filterQuery(filter) { - const pred = matchFilter(filter); - return (ctx) => pred(ctx); - }, - text(trigger) { - const hasText = checker.filterQuery([ - ":text", - ":caption" - ]); - const trg = triggerFn(trigger); - return (ctx) => { - if (!hasText(ctx)) return false; - const msg = ctx.message ?? ctx.channelPost; - const txt = msg.text ?? msg.caption; - return match2(ctx, txt, trg); - }; - }, - command(command) { - const hasEntities = checker.filterQuery(":entities:bot_command"); - const atCommands = /* @__PURE__ */ new Set(); - const noAtCommands = /* @__PURE__ */ new Set(); - toArray(command).forEach((cmd) => { - if (cmd.startsWith("/")) { - throw new Error(`Do not include '/' when registering command handlers (use '${cmd.substring(1)}' not '${cmd}')`); - } - const set = cmd.includes("@") ? atCommands : noAtCommands; - set.add(cmd); - }); - return (ctx) => { - if (!hasEntities(ctx)) return false; - const msg = ctx.message ?? ctx.channelPost; - const txt = msg.text ?? msg.caption; - return msg.entities.some((e) => { - if (e.type !== "bot_command") return false; - if (e.offset !== 0) return false; - const cmd = txt.substring(1, e.length); - if (noAtCommands.has(cmd) || atCommands.has(cmd)) { - ctx.match = txt.substring(cmd.length + 1).trimStart(); - return true; - } - const index = cmd.indexOf("@"); - if (index === -1) return false; - const atTarget = cmd.substring(index + 1).toLowerCase(); - const username = ctx.me.username.toLowerCase(); - if (atTarget !== username) return false; - const atCommand = cmd.substring(0, index); - if (noAtCommands.has(atCommand)) { - ctx.match = txt.substring(cmd.length + 1).trimStart(); - return true; - } - return false; - }); - }; - }, - reaction(reaction) { - const hasMessageReaction = checker.filterQuery("message_reaction"); - const normalized = typeof reaction === "string" ? [ - { - type: "emoji", - emoji: reaction - } - ] : (Array.isArray(reaction) ? reaction : [ - reaction - ]).map((emoji2) => typeof emoji2 === "string" ? { - type: "emoji", - emoji: emoji2 - } : emoji2); - const emoji = new Set(normalized.filter((r) => r.type === "emoji").map((r) => r.emoji)); - const customEmoji = new Set(normalized.filter((r) => r.type === "custom_emoji").map((r) => r.custom_emoji_id)); - const paid = normalized.some((r) => r.type === "paid"); - return (ctx) => { - if (!hasMessageReaction(ctx)) return false; - const { old_reaction, new_reaction } = ctx.messageReaction; - for (const reaction2 of new_reaction) { - let isOld = false; - if (reaction2.type === "emoji") { - for (const old of old_reaction) { - if (old.type !== "emoji") continue; - if (old.emoji === reaction2.emoji) { - isOld = true; - break; - } - } - } else if (reaction2.type === "custom_emoji") { - for (const old of old_reaction) { - if (old.type !== "custom_emoji") continue; - if (old.custom_emoji_id === reaction2.custom_emoji_id) { - isOld = true; - break; - } - } - } else if (reaction2.type === "paid") { - for (const old of old_reaction) { - if (old.type !== "paid") continue; - isOld = true; - break; - } - } else { - } - if (isOld) continue; - if (reaction2.type === "emoji") { - if (emoji.has(reaction2.emoji)) return true; - } else if (reaction2.type === "custom_emoji") { - if (customEmoji.has(reaction2.custom_emoji_id)) return true; - } else if (reaction2.type === "paid") { - if (paid) return true; - } else { - return true; - } - } - return false; - }; - }, - chatType(chatType) { - const set = new Set(toArray(chatType)); - return (ctx) => ctx.chat?.type !== void 0 && set.has(ctx.chat.type); - }, - callbackQuery(trigger) { - const hasCallbackQuery = checker.filterQuery("callback_query:data"); - const trg = triggerFn(trigger); - return (ctx) => hasCallbackQuery(ctx) && match2(ctx, ctx.callbackQuery.data, trg); - }, - gameQuery(trigger) { - const hasGameQuery = checker.filterQuery("callback_query:game_short_name"); - const trg = triggerFn(trigger); - return (ctx) => hasGameQuery(ctx) && match2(ctx, ctx.callbackQuery.game_short_name, trg); - }, - inlineQuery(trigger) { - const hasInlineQuery = checker.filterQuery("inline_query"); - const trg = triggerFn(trigger); - return (ctx) => hasInlineQuery(ctx) && match2(ctx, ctx.inlineQuery.query, trg); - }, - chosenInlineResult(trigger) { - const hasChosenInlineResult = checker.filterQuery("chosen_inline_result"); - const trg = triggerFn(trigger); - return (ctx) => hasChosenInlineResult(ctx) && match2(ctx, ctx.chosenInlineResult.result_id, trg); - }, - preCheckoutQuery(trigger) { - const hasPreCheckoutQuery = checker.filterQuery("pre_checkout_query"); - const trg = triggerFn(trigger); - return (ctx) => hasPreCheckoutQuery(ctx) && match2(ctx, ctx.preCheckoutQuery.invoice_payload, trg); - }, - shippingQuery(trigger) { - const hasShippingQuery = checker.filterQuery("shipping_query"); - const trg = triggerFn(trigger); - return (ctx) => hasShippingQuery(ctx) && match2(ctx, ctx.shippingQuery.invoice_payload, trg); - } -}; -var Context2 = class _Context { - static { - __name(this, "Context"); - } - update; - api; - me; - match; - constructor(update, api, me) { - this.update = update; - this.api = api; - this.me = me; - } - get message() { - return this.update.message; - } - get editedMessage() { - return this.update.edited_message; - } - get channelPost() { - return this.update.channel_post; - } - get editedChannelPost() { - return this.update.edited_channel_post; - } - get businessConnection() { - return this.update.business_connection; - } - get businessMessage() { - return this.update.business_message; - } - get editedBusinessMessage() { - return this.update.edited_business_message; - } - get deletedBusinessMessages() { - return this.update.deleted_business_messages; - } - get messageReaction() { - return this.update.message_reaction; - } - get messageReactionCount() { - return this.update.message_reaction_count; - } - get inlineQuery() { - return this.update.inline_query; - } - get chosenInlineResult() { - return this.update.chosen_inline_result; - } - get callbackQuery() { - return this.update.callback_query; - } - get shippingQuery() { - return this.update.shipping_query; - } - get preCheckoutQuery() { - return this.update.pre_checkout_query; - } - get poll() { - return this.update.poll; - } - get pollAnswer() { - return this.update.poll_answer; - } - get myChatMember() { - return this.update.my_chat_member; - } - get chatMember() { - return this.update.chat_member; - } - get chatJoinRequest() { - return this.update.chat_join_request; - } - get chatBoost() { - return this.update.chat_boost; - } - get removedChatBoost() { - return this.update.removed_chat_boost; - } - get purchasedPaidMedia() { - return this.update.purchased_paid_media; - } - get msg() { - return this.message ?? this.editedMessage ?? this.channelPost ?? this.editedChannelPost ?? this.businessMessage ?? this.editedBusinessMessage ?? this.callbackQuery?.message; - } - get chat() { - return (this.msg ?? this.deletedBusinessMessages ?? this.messageReaction ?? this.messageReactionCount ?? this.myChatMember ?? this.chatMember ?? this.chatJoinRequest ?? this.chatBoost ?? this.removedChatBoost)?.chat; - } - get senderChat() { - return this.msg?.sender_chat; - } - get from() { - return (this.businessConnection ?? this.messageReaction ?? (this.chatBoost?.boost ?? this.removedChatBoost)?.source)?.user ?? (this.callbackQuery ?? this.msg ?? this.inlineQuery ?? this.chosenInlineResult ?? this.shippingQuery ?? this.preCheckoutQuery ?? this.myChatMember ?? this.chatMember ?? this.chatJoinRequest ?? this.purchasedPaidMedia)?.from; - } - get msgId() { - return this.msg?.message_id ?? this.messageReaction?.message_id ?? this.messageReactionCount?.message_id; - } - get chatId() { - return this.chat?.id ?? this.businessConnection?.user_chat_id; - } - get inlineMessageId() { - return this.callbackQuery?.inline_message_id ?? this.chosenInlineResult?.inline_message_id; - } - get businessConnectionId() { - return this.msg?.business_connection_id ?? this.businessConnection?.id ?? this.deletedBusinessMessages?.business_connection_id; - } - entities(types) { - const message = this.msg; - if (message === void 0) return []; - const text2 = message.text ?? message.caption; - if (text2 === void 0) return []; - let entities = message.entities ?? message.caption_entities; - if (entities === void 0) return []; - if (types !== void 0) { - const filters = new Set(toArray(types)); - entities = entities.filter((entity) => filters.has(entity.type)); - } - return entities.map((entity) => ({ - ...entity, - text: text2.substring(entity.offset, entity.offset + entity.length) - })); - } - reactions() { - const emoji = []; - const emojiAdded = []; - const emojiKept = []; - const emojiRemoved = []; - const customEmoji = []; - const customEmojiAdded = []; - const customEmojiKept = []; - const customEmojiRemoved = []; - let paid = false; - let paidAdded = false; - const r = this.messageReaction; - if (r !== void 0) { - const { old_reaction, new_reaction } = r; - for (const reaction of new_reaction) { - if (reaction.type === "emoji") { - emoji.push(reaction.emoji); - } else if (reaction.type === "custom_emoji") { - customEmoji.push(reaction.custom_emoji_id); - } else if (reaction.type === "paid") { - paid = paidAdded = true; - } - } - for (const reaction of old_reaction) { - if (reaction.type === "emoji") { - emojiRemoved.push(reaction.emoji); - } else if (reaction.type === "custom_emoji") { - customEmojiRemoved.push(reaction.custom_emoji_id); - } else if (reaction.type === "paid") { - paidAdded = false; - } - } - emojiAdded.push(...emoji); - customEmojiAdded.push(...customEmoji); - for (let i = 0; i < emojiRemoved.length; i++) { - const len = emojiAdded.length; - if (len === 0) break; - const rem = emojiRemoved[i]; - for (let j = 0; j < len; j++) { - if (rem === emojiAdded[j]) { - emojiKept.push(rem); - emojiRemoved.splice(i, 1); - emojiAdded.splice(j, 1); - i--; - break; - } - } - } - for (let i = 0; i < customEmojiRemoved.length; i++) { - const len = customEmojiAdded.length; - if (len === 0) break; - const rem = customEmojiRemoved[i]; - for (let j = 0; j < len; j++) { - if (rem === customEmojiAdded[j]) { - customEmojiKept.push(rem); - customEmojiRemoved.splice(i, 1); - customEmojiAdded.splice(j, 1); - i--; - break; - } - } - } - } - return { - emoji, - emojiAdded, - emojiKept, - emojiRemoved, - customEmoji, - customEmojiAdded, - customEmojiKept, - customEmojiRemoved, - paid, - paidAdded - }; - } - static has = checker; - has(filter) { - return _Context.has.filterQuery(filter)(this); - } - hasText(trigger) { - return _Context.has.text(trigger)(this); - } - hasCommand(command) { - return _Context.has.command(command)(this); - } - hasReaction(reaction) { - return _Context.has.reaction(reaction)(this); - } - hasChatType(chatType) { - return _Context.has.chatType(chatType)(this); - } - hasCallbackQuery(trigger) { - return _Context.has.callbackQuery(trigger)(this); - } - hasGameQuery(trigger) { - return _Context.has.gameQuery(trigger)(this); - } - hasInlineQuery(trigger) { - return _Context.has.inlineQuery(trigger)(this); - } - hasChosenInlineResult(trigger) { - return _Context.has.chosenInlineResult(trigger)(this); - } - hasPreCheckoutQuery(trigger) { - return _Context.has.preCheckoutQuery(trigger)(this); - } - hasShippingQuery(trigger) { - return _Context.has.shippingQuery(trigger)(this); - } - reply(text2, other, signal) { - const msg = this.msg; - return this.api.sendMessage(orThrow(this.chatId, "sendMessage"), text2, { - business_connection_id: this.businessConnectionId, - ...msg?.is_topic_message ? { - message_thread_id: msg.message_thread_id - } : {}, - direct_messages_topic_id: msg?.direct_messages_topic?.topic_id, - ...other - }, signal); - } - replyWithDraft(text2, other, signal) { - const msg = this.msg; - return this.api.sendMessageDraft(orThrow(this.chatId, "sendMessageDraft"), this.update.update_id, text2, { - ...msg?.is_topic_message ? { - message_thread_id: msg?.message_thread_id - } : {}, - ...other - }, signal); - } - forwardMessage(chat_id, other, signal) { - const msg = this.msg; - return this.api.forwardMessage(chat_id, orThrow(this.chatId, "forwardMessage"), orThrow(this.msgId, "forwardMessage"), { - direct_messages_topic_id: msg?.direct_messages_topic?.topic_id, - ...other - }, signal); - } - forwardMessages(chat_id, message_ids, other, signal) { - const msg = this.msg; - return this.api.forwardMessages(chat_id, orThrow(this.chatId, "forwardMessages"), message_ids, { - direct_messages_topic_id: msg?.direct_messages_topic?.topic_id, - ...other - }, signal); - } - copyMessage(chat_id, other, signal) { - const msg = this.msg; - return this.api.copyMessage(chat_id, orThrow(this.chatId, "copyMessage"), orThrow(this.msgId, "copyMessage"), { - direct_messages_topic_id: msg?.direct_messages_topic?.topic_id, - ...other - }, signal); - } - copyMessages(chat_id, message_ids, other, signal) { - const msg = this.msg; - return this.api.copyMessages(chat_id, orThrow(this.chatId, "copyMessages"), message_ids, { - direct_messages_topic_id: msg?.direct_messages_topic?.topic_id, - ...other - }, signal); - } - replyWithPhoto(photo, other, signal) { - const msg = this.msg; - return this.api.sendPhoto(orThrow(this.chatId, "sendPhoto"), photo, { - business_connection_id: this.businessConnectionId, - ...msg?.is_topic_message ? { - message_thread_id: msg.message_thread_id - } : {}, - direct_messages_topic_id: msg?.direct_messages_topic?.topic_id, - ...other - }, signal); - } - replyWithAudio(audio, other, signal) { - const msg = this.msg; - return this.api.sendAudio(orThrow(this.chatId, "sendAudio"), audio, { - business_connection_id: this.businessConnectionId, - ...msg?.is_topic_message ? { - message_thread_id: msg.message_thread_id - } : {}, - direct_messages_topic_id: msg?.direct_messages_topic?.topic_id, - ...other - }, signal); - } - replyWithDocument(document1, other, signal) { - const msg = this.msg; - return this.api.sendDocument(orThrow(this.chatId, "sendDocument"), document1, { - business_connection_id: this.businessConnectionId, - ...msg?.is_topic_message ? { - message_thread_id: msg.message_thread_id - } : {}, - direct_messages_topic_id: msg?.direct_messages_topic?.topic_id, - ...other - }, signal); - } - replyWithVideo(video, other, signal) { - const msg = this.msg; - return this.api.sendVideo(orThrow(this.chatId, "sendVideo"), video, { - business_connection_id: this.businessConnectionId, - ...msg?.is_topic_message ? { - message_thread_id: msg.message_thread_id - } : {}, - direct_messages_topic_id: msg?.direct_messages_topic?.topic_id, - ...other - }, signal); - } - replyWithAnimation(animation, other, signal) { - const msg = this.msg; - return this.api.sendAnimation(orThrow(this.chatId, "sendAnimation"), animation, { - business_connection_id: this.businessConnectionId, - ...msg?.is_topic_message ? { - message_thread_id: msg.message_thread_id - } : {}, - direct_messages_topic_id: msg?.direct_messages_topic?.topic_id, - ...other - }, signal); - } - replyWithVoice(voice, other, signal) { - const msg = this.msg; - return this.api.sendVoice(orThrow(this.chatId, "sendVoice"), voice, { - business_connection_id: this.businessConnectionId, - ...msg?.is_topic_message ? { - message_thread_id: msg.message_thread_id - } : {}, - direct_messages_topic_id: msg?.direct_messages_topic?.topic_id, - ...other - }, signal); - } - replyWithVideoNote(video_note, other, signal) { - const msg = this.msg; - return this.api.sendVideoNote(orThrow(this.chatId, "sendVideoNote"), video_note, { - business_connection_id: this.businessConnectionId, - ...msg?.is_topic_message ? { - message_thread_id: msg.message_thread_id - } : {}, - direct_messages_topic_id: msg?.direct_messages_topic?.topic_id, - ...other - }, signal); - } - replyWithMediaGroup(media, other, signal) { - const msg = this.msg; - return this.api.sendMediaGroup(orThrow(this.chatId, "sendMediaGroup"), media, { - business_connection_id: this.businessConnectionId, - ...msg?.is_topic_message ? { - message_thread_id: msg.message_thread_id - } : {}, - direct_messages_topic_id: msg?.direct_messages_topic?.topic_id, - ...other - }, signal); - } - replyWithLocation(latitude, longitude, other, signal) { - const msg = this.msg; - return this.api.sendLocation(orThrow(this.chatId, "sendLocation"), latitude, longitude, { - business_connection_id: this.businessConnectionId, - ...msg?.is_topic_message ? { - message_thread_id: msg.message_thread_id - } : {}, - direct_messages_topic_id: msg?.direct_messages_topic?.topic_id, - ...other - }, signal); - } - editMessageLiveLocation(latitude, longitude, other, signal) { - const inlineId = this.inlineMessageId; - return inlineId !== void 0 ? this.api.editMessageLiveLocationInline(inlineId, latitude, longitude, { - business_connection_id: this.businessConnectionId, - ...other - }, signal) : this.api.editMessageLiveLocation(orThrow(this.chatId, "editMessageLiveLocation"), orThrow(this.msgId, "editMessageLiveLocation"), latitude, longitude, { - business_connection_id: this.businessConnectionId, - ...other - }, signal); - } - stopMessageLiveLocation(other, signal) { - const inlineId = this.inlineMessageId; - return inlineId !== void 0 ? this.api.stopMessageLiveLocationInline(inlineId, { - business_connection_id: this.businessConnectionId, - ...other - }, signal) : this.api.stopMessageLiveLocation(orThrow(this.chatId, "stopMessageLiveLocation"), orThrow(this.msgId, "stopMessageLiveLocation"), { - business_connection_id: this.businessConnectionId, - ...other - }, signal); - } - sendPaidMedia(star_count, media, other, signal) { - const msg = this.msg; - return this.api.sendPaidMedia(orThrow(this.chatId, "sendPaidMedia"), star_count, media, { - business_connection_id: this.businessConnectionId, - ...msg?.is_topic_message ? { - message_thread_id: msg.message_thread_id - } : {}, - direct_messages_topic_id: this.msg?.direct_messages_topic?.topic_id, - ...other - }, signal); - } - replyWithVenue(latitude, longitude, title2, address, other, signal) { - const msg = this.msg; - return this.api.sendVenue(orThrow(this.chatId, "sendVenue"), latitude, longitude, title2, address, { - business_connection_id: this.businessConnectionId, - ...msg?.is_topic_message ? { - message_thread_id: msg.message_thread_id - } : {}, - direct_messages_topic_id: msg?.direct_messages_topic?.topic_id, - ...other - }, signal); - } - replyWithContact(phone_number, first_name, other, signal) { - const msg = this.msg; - return this.api.sendContact(orThrow(this.chatId, "sendContact"), phone_number, first_name, { - business_connection_id: this.businessConnectionId, - ...msg?.is_topic_message ? { - message_thread_id: msg.message_thread_id - } : {}, - direct_messages_topic_id: msg?.direct_messages_topic?.topic_id, - ...other - }, signal); - } - replyWithPoll(question, options, other, signal) { - const msg = this.msg; - return this.api.sendPoll(orThrow(this.chatId, "sendPoll"), question, options, { - business_connection_id: this.businessConnectionId, - ...msg?.is_topic_message ? { - message_thread_id: msg.message_thread_id - } : {}, - ...other - }, signal); - } - replyWithChecklist(checklist, other, signal) { - return this.api.sendChecklist(orThrow(this.businessConnectionId, "sendChecklist"), orThrow(this.chatId, "sendChecklist"), checklist, other, signal); - } - editMessageChecklist(checklist, other, signal) { - const msg = orThrow(this.msg, "editMessageChecklist"); - const target = msg.checklist_tasks_done?.checklist_message ?? msg.checklist_tasks_added?.checklist_message ?? msg; - return this.api.editMessageChecklist(orThrow(this.businessConnectionId, "editMessageChecklist"), orThrow(target.chat.id, "editMessageChecklist"), orThrow(target.message_id, "editMessageChecklist"), checklist, other, signal); - } - replyWithDice(emoji, other, signal) { - const msg = this.msg; - return this.api.sendDice(orThrow(this.chatId, "sendDice"), emoji, { - business_connection_id: this.businessConnectionId, - ...msg?.is_topic_message ? { - message_thread_id: msg.message_thread_id - } : {}, - direct_messages_topic_id: msg?.direct_messages_topic?.topic_id, - ...other - }, signal); - } - replyWithChatAction(action, other, signal) { - const msg = this.msg; - return this.api.sendChatAction(orThrow(this.chatId, "sendChatAction"), action, { - business_connection_id: this.businessConnectionId, - message_thread_id: msg?.message_thread_id, - ...other - }, signal); - } - react(reaction, other, signal) { - return this.api.setMessageReaction(orThrow(this.chatId, "setMessageReaction"), orThrow(this.msgId, "setMessageReaction"), typeof reaction === "string" ? [ - { - type: "emoji", - emoji: reaction - } - ] : (Array.isArray(reaction) ? reaction : [ - reaction - ]).map((emoji) => typeof emoji === "string" ? { - type: "emoji", - emoji - } : emoji), other, signal); - } - getUserProfilePhotos(other, signal) { - return this.api.getUserProfilePhotos(orThrow(this.from, "getUserProfilePhotos").id, other, signal); - } - getUserProfileAudios(other, signal) { - return this.api.getUserProfileAudios(orThrow(this.from, "getUserProfileAudios").id, other, signal); - } - setUserEmojiStatus(other, signal) { - return this.api.setUserEmojiStatus(orThrow(this.from, "setUserEmojiStatus").id, other, signal); - } - getUserChatBoosts(chat_id, signal) { - return this.api.getUserChatBoosts(chat_id ?? orThrow(this.chatId, "getUserChatBoosts"), orThrow(this.from, "getUserChatBoosts").id, signal); - } - getUserGifts(other, signal) { - return this.api.getUserGifts(orThrow(this.from, "getUserGifts").id, other, signal); - } - getChatGifts(other, signal) { - return this.api.getChatGifts(orThrow(this.chatId, "getChatGifts"), other, signal); - } - getBusinessConnection(signal) { - return this.api.getBusinessConnection(orThrow(this.businessConnectionId, "getBusinessConnection"), signal); - } - getFile(signal) { - const m2 = orThrow(this.msg, "getFile"); - const file = m2.photo !== void 0 ? m2.photo[m2.photo.length - 1] : m2.animation ?? m2.audio ?? m2.document ?? m2.video ?? m2.video_note ?? m2.voice ?? m2.sticker; - return this.api.getFile(orThrow(file, "getFile").file_id, signal); - } - kickAuthor(...args) { - return this.banAuthor(...args); - } - banAuthor(other, signal) { - return this.api.banChatMember(orThrow(this.chatId, "banAuthor"), orThrow(this.from, "banAuthor").id, other, signal); - } - kickChatMember(...args) { - return this.banChatMember(...args); - } - banChatMember(user_id, other, signal) { - return this.api.banChatMember(orThrow(this.chatId, "banChatMember"), user_id, other, signal); - } - unbanChatMember(user_id, other, signal) { - return this.api.unbanChatMember(orThrow(this.chatId, "unbanChatMember"), user_id, other, signal); - } - restrictAuthor(permissions, other, signal) { - return this.api.restrictChatMember(orThrow(this.chatId, "restrictAuthor"), orThrow(this.from, "restrictAuthor").id, permissions, other, signal); - } - restrictChatMember(user_id, permissions, other, signal) { - return this.api.restrictChatMember(orThrow(this.chatId, "restrictChatMember"), user_id, permissions, other, signal); - } - promoteAuthor(other, signal) { - return this.api.promoteChatMember(orThrow(this.chatId, "promoteAuthor"), orThrow(this.from, "promoteAuthor").id, other, signal); - } - promoteChatMember(user_id, other, signal) { - return this.api.promoteChatMember(orThrow(this.chatId, "promoteChatMember"), user_id, other, signal); - } - setChatAdministratorAuthorCustomTitle(custom_title, signal) { - return this.api.setChatAdministratorCustomTitle(orThrow(this.chatId, "setChatAdministratorAuthorCustomTitle"), orThrow(this.from, "setChatAdministratorAuthorCustomTitle").id, custom_title, signal); - } - setChatAdministratorCustomTitle(user_id, custom_title, signal) { - return this.api.setChatAdministratorCustomTitle(orThrow(this.chatId, "setChatAdministratorCustomTitle"), user_id, custom_title, signal); - } - setAuthorTag(tag, signal) { - return this.api.setChatMemberTag(orThrow(this.chatId, "setChatMemberTag"), orThrow(this.from, "setChatMemberTag").id, tag, signal); - } - setChatMemberTag(user_id, tag, signal) { - return this.api.setChatMemberTag(orThrow(this.chatId, "setChatMemberTag"), user_id, tag, signal); - } - banChatSenderChat(sender_chat_id, signal) { - return this.api.banChatSenderChat(orThrow(this.chatId, "banChatSenderChat"), sender_chat_id, signal); - } - unbanChatSenderChat(sender_chat_id, signal) { - return this.api.unbanChatSenderChat(orThrow(this.chatId, "unbanChatSenderChat"), sender_chat_id, signal); - } - setChatPermissions(permissions, other, signal) { - return this.api.setChatPermissions(orThrow(this.chatId, "setChatPermissions"), permissions, other, signal); - } - exportChatInviteLink(signal) { - return this.api.exportChatInviteLink(orThrow(this.chatId, "exportChatInviteLink"), signal); - } - createChatInviteLink(other, signal) { - return this.api.createChatInviteLink(orThrow(this.chatId, "createChatInviteLink"), other, signal); - } - editChatInviteLink(invite_link, other, signal) { - return this.api.editChatInviteLink(orThrow(this.chatId, "editChatInviteLink"), invite_link, other, signal); - } - createChatSubscriptionInviteLink(subscription_period, subscription_price, other, signal) { - return this.api.createChatSubscriptionInviteLink(orThrow(this.chatId, "createChatSubscriptionInviteLink"), subscription_period, subscription_price, other, signal); - } - editChatSubscriptionInviteLink(invite_link, other, signal) { - return this.api.editChatSubscriptionInviteLink(orThrow(this.chatId, "editChatSubscriptionInviteLink"), invite_link, other, signal); - } - revokeChatInviteLink(invite_link, signal) { - return this.api.revokeChatInviteLink(orThrow(this.chatId, "editChatInviteLink"), invite_link, signal); - } - approveChatJoinRequest(user_id, signal) { - return this.api.approveChatJoinRequest(orThrow(this.chatId, "approveChatJoinRequest"), user_id, signal); - } - declineChatJoinRequest(user_id, signal) { - return this.api.declineChatJoinRequest(orThrow(this.chatId, "declineChatJoinRequest"), user_id, signal); - } - approveSuggestedPost(other, signal) { - return this.api.approveSuggestedPost(orThrow(this.chatId, "approveSuggestedPost"), orThrow(this.msgId, "approveSuggestedPost"), other, signal); - } - declineSuggestedPost(other, signal) { - return this.api.declineSuggestedPost(orThrow(this.chatId, "declineSuggestedPost"), orThrow(this.msgId, "declineSuggestedPost"), other, signal); - } - setChatPhoto(photo, signal) { - return this.api.setChatPhoto(orThrow(this.chatId, "setChatPhoto"), photo, signal); - } - deleteChatPhoto(signal) { - return this.api.deleteChatPhoto(orThrow(this.chatId, "deleteChatPhoto"), signal); - } - setChatTitle(title2, signal) { - return this.api.setChatTitle(orThrow(this.chatId, "setChatTitle"), title2, signal); - } - setChatDescription(description, signal) { - return this.api.setChatDescription(orThrow(this.chatId, "setChatDescription"), description, signal); - } - pinChatMessage(message_id, other, signal) { - return this.api.pinChatMessage(orThrow(this.chatId, "pinChatMessage"), message_id, { - business_connection_id: this.businessConnectionId, - ...other - }, signal); - } - unpinChatMessage(message_id, other, signal) { - return this.api.unpinChatMessage(orThrow(this.chatId, "unpinChatMessage"), message_id, { - business_connection_id: this.businessConnectionId, - ...other - }, signal); - } - unpinAllChatMessages(signal) { - return this.api.unpinAllChatMessages(orThrow(this.chatId, "unpinAllChatMessages"), signal); - } - leaveChat(signal) { - return this.api.leaveChat(orThrow(this.chatId, "leaveChat"), signal); - } - getChat(signal) { - return this.api.getChat(orThrow(this.chatId, "getChat"), signal); - } - getChatAdministrators(signal) { - return this.api.getChatAdministrators(orThrow(this.chatId, "getChatAdministrators"), signal); - } - getChatMembersCount(...args) { - return this.getChatMemberCount(...args); - } - getChatMemberCount(signal) { - return this.api.getChatMemberCount(orThrow(this.chatId, "getChatMemberCount"), signal); - } - getAuthor(signal) { - return this.api.getChatMember(orThrow(this.chatId, "getAuthor"), orThrow(this.from, "getAuthor").id, signal); - } - getChatMember(user_id, signal) { - return this.api.getChatMember(orThrow(this.chatId, "getChatMember"), user_id, signal); - } - setChatStickerSet(sticker_set_name, signal) { - return this.api.setChatStickerSet(orThrow(this.chatId, "setChatStickerSet"), sticker_set_name, signal); - } - deleteChatStickerSet(signal) { - return this.api.deleteChatStickerSet(orThrow(this.chatId, "deleteChatStickerSet"), signal); - } - createForumTopic(name, other, signal) { - return this.api.createForumTopic(orThrow(this.chatId, "createForumTopic"), name, other, signal); - } - editForumTopic(other, signal) { - const message = orThrow(this.msg, "editForumTopic"); - const thread = orThrow(message.message_thread_id, "editForumTopic"); - return this.api.editForumTopic(message.chat.id, thread, other, signal); - } - closeForumTopic(signal) { - const message = orThrow(this.msg, "closeForumTopic"); - const thread = orThrow(message.message_thread_id, "closeForumTopic"); - return this.api.closeForumTopic(message.chat.id, thread, signal); - } - reopenForumTopic(signal) { - const message = orThrow(this.msg, "reopenForumTopic"); - const thread = orThrow(message.message_thread_id, "reopenForumTopic"); - return this.api.reopenForumTopic(message.chat.id, thread, signal); - } - deleteForumTopic(signal) { - const message = orThrow(this.msg, "deleteForumTopic"); - const thread = orThrow(message.message_thread_id, "deleteForumTopic"); - return this.api.deleteForumTopic(message.chat.id, thread, signal); - } - unpinAllForumTopicMessages(signal) { - const message = orThrow(this.msg, "unpinAllForumTopicMessages"); - const thread = orThrow(message.message_thread_id, "unpinAllForumTopicMessages"); - return this.api.unpinAllForumTopicMessages(message.chat.id, thread, signal); - } - editGeneralForumTopic(name, signal) { - return this.api.editGeneralForumTopic(orThrow(this.chatId, "editGeneralForumTopic"), name, signal); - } - closeGeneralForumTopic(signal) { - return this.api.closeGeneralForumTopic(orThrow(this.chatId, "closeGeneralForumTopic"), signal); - } - reopenGeneralForumTopic(signal) { - return this.api.reopenGeneralForumTopic(orThrow(this.chatId, "reopenGeneralForumTopic"), signal); - } - hideGeneralForumTopic(signal) { - return this.api.hideGeneralForumTopic(orThrow(this.chatId, "hideGeneralForumTopic"), signal); - } - unhideGeneralForumTopic(signal) { - return this.api.unhideGeneralForumTopic(orThrow(this.chatId, "unhideGeneralForumTopic"), signal); - } - unpinAllGeneralForumTopicMessages(signal) { - return this.api.unpinAllGeneralForumTopicMessages(orThrow(this.chatId, "unpinAllGeneralForumTopicMessages"), signal); - } - answerCallbackQuery(other, signal) { - return this.api.answerCallbackQuery(orThrow(this.callbackQuery, "answerCallbackQuery").id, typeof other === "string" ? { - text: other - } : other, signal); - } - setChatMenuButton(other, signal) { - return this.api.setChatMenuButton(other, signal); - } - getChatMenuButton(other, signal) { - return this.api.getChatMenuButton(other, signal); - } - setMyDefaultAdministratorRights(other, signal) { - return this.api.setMyDefaultAdministratorRights(other, signal); - } - getMyDefaultAdministratorRights(other, signal) { - return this.api.getMyDefaultAdministratorRights(other, signal); - } - editMessageText(text2, other, signal) { - const inlineId = this.inlineMessageId; - return inlineId !== void 0 ? this.api.editMessageTextInline(inlineId, text2, { - business_connection_id: this.businessConnectionId, - ...other - }, signal) : this.api.editMessageText(orThrow(this.chatId, "editMessageText"), orThrow(this.msg?.message_id ?? this.messageReaction?.message_id ?? this.messageReactionCount?.message_id, "editMessageText"), text2, { - business_connection_id: this.businessConnectionId, - ...other - }, signal); - } - editMessageCaption(other, signal) { - const inlineId = this.inlineMessageId; - return inlineId !== void 0 ? this.api.editMessageCaptionInline(inlineId, { - business_connection_id: this.businessConnectionId, - ...other - }, signal) : this.api.editMessageCaption(orThrow(this.chatId, "editMessageCaption"), orThrow(this.msg?.message_id ?? this.messageReaction?.message_id ?? this.messageReactionCount?.message_id, "editMessageCaption"), { - business_connection_id: this.businessConnectionId, - ...other - }, signal); - } - editMessageMedia(media, other, signal) { - const inlineId = this.inlineMessageId; - return inlineId !== void 0 ? this.api.editMessageMediaInline(inlineId, media, { - business_connection_id: this.businessConnectionId, - ...other - }, signal) : this.api.editMessageMedia(orThrow(this.chatId, "editMessageMedia"), orThrow(this.msg?.message_id ?? this.messageReaction?.message_id ?? this.messageReactionCount?.message_id, "editMessageMedia"), media, { - business_connection_id: this.businessConnectionId, - ...other - }, signal); - } - editMessageReplyMarkup(other, signal) { - const inlineId = this.inlineMessageId; - return inlineId !== void 0 ? this.api.editMessageReplyMarkupInline(inlineId, { - business_connection_id: this.businessConnectionId, - ...other - }, signal) : this.api.editMessageReplyMarkup(orThrow(this.chatId, "editMessageReplyMarkup"), orThrow(this.msg?.message_id ?? this.messageReaction?.message_id ?? this.messageReactionCount?.message_id, "editMessageReplyMarkup"), { - business_connection_id: this.businessConnectionId, - ...other - }, signal); - } - stopPoll(other, signal) { - return this.api.stopPoll(orThrow(this.chatId, "stopPoll"), orThrow(this.msg?.message_id ?? this.messageReaction?.message_id ?? this.messageReactionCount?.message_id, "stopPoll"), { - business_connection_id: this.businessConnectionId, - ...other - }, signal); - } - deleteMessage(signal) { - return this.api.deleteMessage(orThrow(this.chatId, "deleteMessage"), orThrow(this.msg?.message_id ?? this.messageReaction?.message_id ?? this.messageReactionCount?.message_id, "deleteMessage"), signal); - } - deleteMessages(message_ids, signal) { - return this.api.deleteMessages(orThrow(this.chatId, "deleteMessages"), message_ids, signal); - } - deleteBusinessMessages(message_ids, signal) { - return this.api.deleteBusinessMessages(orThrow(this.businessConnectionId, "deleteBusinessMessages"), message_ids, signal); - } - setBusinessAccountName(first_name, other, signal) { - return this.api.setBusinessAccountName(orThrow(this.businessConnectionId, "setBusinessAccountName"), first_name, other, signal); - } - setBusinessAccountUsername(username, signal) { - return this.api.setBusinessAccountUsername(orThrow(this.businessConnectionId, "setBusinessAccountUsername"), username, signal); - } - setBusinessAccountBio(bio, signal) { - return this.api.setBusinessAccountBio(orThrow(this.businessConnectionId, "setBusinessAccountBio"), bio, signal); - } - setBusinessAccountProfilePhoto(photo, other, signal) { - return this.api.setBusinessAccountProfilePhoto(orThrow(this.businessConnectionId, "setBusinessAccountProfilePhoto"), photo, other, signal); - } - removeBusinessAccountProfilePhoto(other, signal) { - return this.api.removeBusinessAccountProfilePhoto(orThrow(this.businessConnectionId, "removeBusinessAccountProfilePhoto"), other, signal); - } - setBusinessAccountGiftSettings(show_gift_button, accepted_gift_types, signal) { - return this.api.setBusinessAccountGiftSettings(orThrow(this.businessConnectionId, "setBusinessAccountGiftSettings"), show_gift_button, accepted_gift_types, signal); - } - getBusinessAccountStarBalance(signal) { - return this.api.getBusinessAccountStarBalance(orThrow(this.businessConnectionId, "getBusinessAccountStarBalance"), signal); - } - transferBusinessAccountStars(star_count, signal) { - return this.api.transferBusinessAccountStars(orThrow(this.businessConnectionId, "transferBusinessAccountStars"), star_count, signal); - } - getBusinessAccountGifts(other, signal) { - return this.api.getBusinessAccountGifts(orThrow(this.businessConnectionId, "getBusinessAccountGifts"), other, signal); - } - convertGiftToStars(owned_gift_id, signal) { - return this.api.convertGiftToStars(orThrow(this.businessConnectionId, "convertGiftToStars"), owned_gift_id, signal); - } - upgradeGift(owned_gift_id, other, signal) { - return this.api.upgradeGift(orThrow(this.businessConnectionId, "upgradeGift"), owned_gift_id, other, signal); - } - transferGift(owned_gift_id, new_owner_chat_id, star_count, signal) { - return this.api.transferGift(orThrow(this.businessConnectionId, "transferGift"), owned_gift_id, new_owner_chat_id, star_count, signal); - } - postStory(content, active_period, other, signal) { - return this.api.postStory(orThrow(this.businessConnectionId, "postStory"), content, active_period, other, signal); - } - repostStory(active_period, other, signal) { - const story = orThrow(this.msg?.story, "repostStory"); - return this.api.repostStory(orThrow(this.businessConnectionId, "repostStory"), story.chat.id, story.id, active_period, other, signal); - } - editStory(story_id, content, other, signal) { - return this.api.editStory(orThrow(this.businessConnectionId, "editStory"), story_id, content, other, signal); - } - deleteStory(story_id, signal) { - return this.api.deleteStory(orThrow(this.businessConnectionId, "deleteStory"), story_id, signal); - } - replyWithSticker(sticker, other, signal) { - const msg = this.msg; - return this.api.sendSticker(orThrow(this.chatId, "sendSticker"), sticker, { - business_connection_id: this.businessConnectionId, - ...msg?.is_topic_message ? { - message_thread_id: msg.message_thread_id - } : {}, - direct_messages_topic_id: msg?.direct_messages_topic?.topic_id, - ...other - }, signal); - } - getCustomEmojiStickers(signal) { - return this.api.getCustomEmojiStickers((this.msg?.entities ?? []).filter((e) => e.type === "custom_emoji").map((e) => e.custom_emoji_id), signal); - } - replyWithGift(gift_id, other, signal) { - return this.api.sendGift(orThrow(this.from, "sendGift").id, gift_id, other, signal); - } - giftPremiumSubscription(month_count, star_count, other, signal) { - return this.api.giftPremiumSubscription(orThrow(this.from, "giftPremiumSubscription").id, month_count, star_count, other, signal); - } - replyWithGiftToChannel(gift_id, other, signal) { - return this.api.sendGiftToChannel(orThrow(this.chat, "sendGift").id, gift_id, other, signal); - } - answerInlineQuery(results, other, signal) { - return this.api.answerInlineQuery(orThrow(this.inlineQuery, "answerInlineQuery").id, results, other, signal); - } - savePreparedInlineMessage(result, other, signal) { - return this.api.savePreparedInlineMessage(orThrow(this.from, "savePreparedInlineMessage").id, result, other, signal); - } - replyWithInvoice(title2, description, payload, currency, prices, other, signal) { - const msg = this.msg; - return this.api.sendInvoice(orThrow(this.chatId, "sendInvoice"), title2, description, payload, currency, prices, { - ...msg?.is_topic_message ? { - message_thread_id: msg.message_thread_id - } : {}, - direct_messages_topic_id: msg?.direct_messages_topic?.topic_id, - ...other - }, signal); - } - answerShippingQuery(ok2, other, signal) { - return this.api.answerShippingQuery(orThrow(this.shippingQuery, "answerShippingQuery").id, ok2, other, signal); - } - answerPreCheckoutQuery(ok2, other, signal) { - return this.api.answerPreCheckoutQuery(orThrow(this.preCheckoutQuery, "answerPreCheckoutQuery").id, ok2, typeof other === "string" ? { - error_message: other - } : other, signal); - } - refundStarPayment(signal) { - return this.api.refundStarPayment(orThrow(this.from, "refundStarPayment").id, orThrow(this.msg?.successful_payment, "refundStarPayment").telegram_payment_charge_id, signal); - } - editUserStarSubscription(telegram_payment_charge_id, is_canceled, signal) { - return this.api.editUserStarSubscription(orThrow(this.from, "editUserStarSubscription").id, telegram_payment_charge_id, is_canceled, signal); - } - verifyUser(other, signal) { - return this.api.verifyUser(orThrow(this.from, "verifyUser").id, other, signal); - } - verifyChat(other, signal) { - return this.api.verifyChat(orThrow(this.chatId, "verifyChat"), other, signal); - } - removeUserVerification(signal) { - return this.api.removeUserVerification(orThrow(this.from, "removeUserVerification").id, signal); - } - removeChatVerification(signal) { - return this.api.removeChatVerification(orThrow(this.chatId, "removeChatVerification"), signal); - } - readBusinessMessage(signal) { - return this.api.readBusinessMessage(orThrow(this.businessConnectionId, "readBusinessMessage"), orThrow(this.chatId, "readBusinessMessage"), orThrow(this.msgId, "readBusinessMessage"), signal); - } - setPassportDataErrors(errors, signal) { - return this.api.setPassportDataErrors(orThrow(this.from, "setPassportDataErrors").id, errors, signal); - } - replyWithGame(game_short_name, other, signal) { - const msg = this.msg; - return this.api.sendGame(orThrow(this.chatId, "sendGame"), game_short_name, { - business_connection_id: this.businessConnectionId, - ...msg?.is_topic_message ? { - message_thread_id: msg.message_thread_id - } : {}, - ...other - }, signal); - } -}; -function orThrow(value, method) { - if (value === void 0) { - throw new Error(`Missing information for API call to ${method}`); - } - return value; -} -__name(orThrow, "orThrow"); -function triggerFn(trigger) { - return toArray(trigger).map((t2) => typeof t2 === "string" ? (txt) => txt === t2 ? t2 : null : (txt) => txt.match(t2)); -} -__name(triggerFn, "triggerFn"); -function match2(ctx, content, triggers) { - for (const t2 of triggers) { - const res = t2(content); - if (res) { - ctx.match = res; - return true; - } - } - return false; -} -__name(match2, "match"); -function toArray(e) { - return Array.isArray(e) ? e : [ - e - ]; -} -__name(toArray, "toArray"); -var BotError = class extends Error { - static { - __name(this, "BotError"); - } - error; - ctx; - constructor(error, ctx) { - super(generateBotErrorMessage(error)); - this.error = error; - this.ctx = ctx; - this.name = "BotError"; - if (error instanceof Error) this.stack = error.stack; - } -}; -function generateBotErrorMessage(error) { - let msg; - if (error instanceof Error) { - msg = `${error.name} in middleware: ${error.message}`; - } else { - const type = typeof error; - msg = `Non-error value of type ${type} thrown in middleware`; - switch (type) { - case "bigint": - case "boolean": - case "number": - case "symbol": - msg += `: ${error}`; - break; - case "string": - msg += `: ${String(error).substring(0, 50)}`; - break; - default: - msg += "!"; - break; - } - } - return msg; -} -__name(generateBotErrorMessage, "generateBotErrorMessage"); -function flatten(mw) { - return typeof mw === "function" ? mw : (ctx, next) => mw.middleware()(ctx, next); -} -__name(flatten, "flatten"); -function concat1(first, andThen) { - return async (ctx, next) => { - let nextCalled = false; - await first(ctx, async () => { - if (nextCalled) throw new Error("`next` already called before!"); - else nextCalled = true; - await andThen(ctx, next); - }); - }; -} -__name(concat1, "concat1"); -function pass(_ctx, next) { - return next(); -} -__name(pass, "pass"); -var leaf1 = /* @__PURE__ */ __name(() => Promise.resolve(), "leaf1"); -async function run(middleware, ctx) { - await middleware(ctx, leaf1); -} -__name(run, "run"); -var Composer = class _Composer { - static { - __name(this, "Composer"); - } - handler; - constructor(...middleware) { - this.handler = middleware.length === 0 ? pass : middleware.map(flatten).reduce(concat1); - } - middleware() { - return this.handler; - } - use(...middleware) { - const composer = new _Composer(...middleware); - this.handler = concat1(this.handler, flatten(composer)); - return composer; - } - on(filter, ...middleware) { - return this.filter(Context2.has.filterQuery(filter), ...middleware); - } - hears(trigger, ...middleware) { - return this.filter(Context2.has.text(trigger), ...middleware); - } - command(command, ...middleware) { - return this.filter(Context2.has.command(command), ...middleware); - } - reaction(reaction, ...middleware) { - return this.filter(Context2.has.reaction(reaction), ...middleware); - } - chatType(chatType, ...middleware) { - return this.filter(Context2.has.chatType(chatType), ...middleware); - } - callbackQuery(trigger, ...middleware) { - return this.filter(Context2.has.callbackQuery(trigger), ...middleware); - } - gameQuery(trigger, ...middleware) { - return this.filter(Context2.has.gameQuery(trigger), ...middleware); - } - inlineQuery(trigger, ...middleware) { - return this.filter(Context2.has.inlineQuery(trigger), ...middleware); - } - chosenInlineResult(resultId, ...middleware) { - return this.filter(Context2.has.chosenInlineResult(resultId), ...middleware); - } - preCheckoutQuery(trigger, ...middleware) { - return this.filter(Context2.has.preCheckoutQuery(trigger), ...middleware); - } - shippingQuery(trigger, ...middleware) { - return this.filter(Context2.has.shippingQuery(trigger), ...middleware); - } - filter(predicate, ...middleware) { - const composer = new _Composer(...middleware); - this.branch(predicate, composer, pass); - return composer; - } - drop(predicate, ...middleware) { - return this.filter(async (ctx) => !await predicate(ctx), ...middleware); - } - fork(...middleware) { - const composer = new _Composer(...middleware); - const fork = flatten(composer); - this.use((ctx, next) => Promise.all([ - next(), - run(fork, ctx) - ])); - return composer; - } - lazy(middlewareFactory) { - return this.use(async (ctx, next) => { - const middleware = await middlewareFactory(ctx); - const arr = Array.isArray(middleware) ? middleware : [ - middleware - ]; - await flatten(new _Composer(...arr))(ctx, next); - }); - } - route(router, routeHandlers, fallback = pass) { - return this.lazy(async (ctx) => { - const route = await router(ctx); - return (route === void 0 || !routeHandlers[route] ? fallback : routeHandlers[route]) ?? []; - }); - } - branch(predicate, trueMiddleware, falseMiddleware) { - return this.lazy(async (ctx) => await predicate(ctx) ? trueMiddleware : falseMiddleware); - } - errorBoundary(errorHandler2, ...middleware) { - const composer = new _Composer(...middleware); - const bound = flatten(composer); - this.use(async (ctx, next) => { - let nextCalled = false; - const cont = /* @__PURE__ */ __name(() => (nextCalled = true, Promise.resolve()), "cont"); - try { - await bound(ctx, cont); - } catch (err) { - nextCalled = false; - await errorHandler2(new BotError(err, ctx), cont); - } - if (nextCalled) await next(); - }); - return composer; - } -}; -var s = 1e3; -var m = s * 60; -var h = m * 60; -var d = h * 24; -var w = d * 7; -var y = d * 365.25; -var ms = /* @__PURE__ */ __name(function(val, options) { - options = options || {}; - var type = typeof val; - if (type === "string" && val.length > 0) { - return parse1(val); - } else if (type === "number" && isFinite(val)) { - return options.long ? fmtLong(val) : fmtShort(val); - } - throw new Error("val is not a non-empty string or a valid number. val=" + JSON.stringify(val)); -}, "ms"); -function parse1(str2) { - str2 = String(str2); - if (str2.length > 100) { - return; - } - var match3 = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(str2); - if (!match3) { - return; - } - var n = parseFloat(match3[1]); - var type = (match3[2] || "ms").toLowerCase(); - switch (type) { - case "years": - case "year": - case "yrs": - case "yr": - case "y": - return n * y; - case "weeks": - case "week": - case "w": - return n * w; - case "days": - case "day": - case "d": - return n * d; - case "hours": - case "hour": - case "hrs": - case "hr": - case "h": - return n * h; - case "minutes": - case "minute": - case "mins": - case "min": - case "m": - return n * m; - case "seconds": - case "second": - case "secs": - case "sec": - case "s": - return n * s; - case "milliseconds": - case "millisecond": - case "msecs": - case "msec": - case "ms": - return n; - default: - return void 0; - } -} -__name(parse1, "parse1"); -function fmtShort(ms2) { - var msAbs = Math.abs(ms2); - if (msAbs >= d) { - return Math.round(ms2 / d) + "d"; - } - if (msAbs >= h) { - return Math.round(ms2 / h) + "h"; - } - if (msAbs >= m) { - return Math.round(ms2 / m) + "m"; - } - if (msAbs >= s) { - return Math.round(ms2 / s) + "s"; - } - return ms2 + "ms"; -} -__name(fmtShort, "fmtShort"); -function fmtLong(ms2) { - var msAbs = Math.abs(ms2); - if (msAbs >= d) { - return plural(ms2, msAbs, d, "day"); - } - if (msAbs >= h) { - return plural(ms2, msAbs, h, "hour"); - } - if (msAbs >= m) { - return plural(ms2, msAbs, m, "minute"); - } - if (msAbs >= s) { - return plural(ms2, msAbs, s, "second"); - } - return ms2 + " ms"; -} -__name(fmtLong, "fmtLong"); -function plural(ms2, msAbs, n, name) { - var isPlural = msAbs >= n * 1.5; - return Math.round(ms2 / n) + " " + name + (isPlural ? "s" : ""); -} -__name(plural, "plural"); -function defaultSetTimout() { - throw new Error("setTimeout has not been defined"); -} -__name(defaultSetTimout, "defaultSetTimout"); -function defaultClearTimeout() { - throw new Error("clearTimeout has not been defined"); -} -__name(defaultClearTimeout, "defaultClearTimeout"); -var cachedSetTimeout = defaultSetTimout; -var cachedClearTimeout = defaultClearTimeout; -var globalContext; -if (typeof window !== "undefined") { - globalContext = window; -} else if (typeof self !== "undefined") { - globalContext = self; -} else { - globalContext = {}; -} -if (typeof globalContext.setTimeout === "function") { - cachedSetTimeout = setTimeout; -} -if (typeof globalContext.clearTimeout === "function") { - cachedClearTimeout = clearTimeout; -} -function runTimeout(fun) { - if (cachedSetTimeout === setTimeout) { - return setTimeout(fun, 0); - } - if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { - cachedSetTimeout = setTimeout; - return setTimeout(fun, 0); - } - try { - return cachedSetTimeout(fun, 0); - } catch (e) { - try { - return cachedSetTimeout.call(null, fun, 0); - } catch (e2) { - return cachedSetTimeout.call(this, fun, 0); - } - } -} -__name(runTimeout, "runTimeout"); -function runClearTimeout(marker) { - if (cachedClearTimeout === clearTimeout) { - return clearTimeout(marker); - } - if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { - cachedClearTimeout = clearTimeout; - return clearTimeout(marker); - } - try { - return cachedClearTimeout(marker); - } catch (e) { - try { - return cachedClearTimeout.call(null, marker); - } catch (e2) { - return cachedClearTimeout.call(this, marker); - } - } -} -__name(runClearTimeout, "runClearTimeout"); -var queue = []; -var draining = false; -var currentQueue; -var queueIndex = -1; -function cleanUpNextTick() { - if (!draining || !currentQueue) { - return; - } - draining = false; - if (currentQueue.length) { - queue = currentQueue.concat(queue); - } else { - queueIndex = -1; - } - if (queue.length) { - drainQueue(); - } -} -__name(cleanUpNextTick, "cleanUpNextTick"); -function drainQueue() { - if (draining) { - return; - } - var timeout = runTimeout(cleanUpNextTick); - draining = true; - var len = queue.length; - while (len) { - currentQueue = queue; - queue = []; - while (++queueIndex < len) { - if (currentQueue) { - currentQueue[queueIndex].run(); - } - } - queueIndex = -1; - len = queue.length; - } - currentQueue = null; - draining = false; - runClearTimeout(timeout); -} -__name(drainQueue, "drainQueue"); -function nextTick(fun) { - var args = new Array(arguments.length - 1); - if (arguments.length > 1) { - for (var i = 1; i < arguments.length; i++) { - args[i - 1] = arguments[i]; - } - } - queue.push(new Item(fun, args)); - if (queue.length === 1 && !draining) { - runTimeout(drainQueue); - } -} -__name(nextTick, "nextTick"); -function Item(fun, array) { - this.fun = fun; - this.array = array; -} -__name(Item, "Item"); -Item.prototype.run = function() { - this.fun.apply(null, this.array); -}; -var title = "browser"; -var platform = "browser"; -var browser = true; -var argv = []; -var version = ""; -var versions = {}; -var release = {}; -var config = {}; -function noop() { -} -__name(noop, "noop"); -var on = noop; -var addListener = noop; -var once = noop; -var off = noop; -var removeListener = noop; -var removeAllListeners = noop; -var emit = noop; -function binding(name) { - throw new Error("process.binding is not supported"); -} -__name(binding, "binding"); -function cwd() { - return "/"; -} -__name(cwd, "cwd"); -function chdir(dir2) { - throw new Error("process.chdir is not supported"); -} -__name(chdir, "chdir"); -function umask() { - return 0; -} -__name(umask, "umask"); -var performance2 = globalContext.performance || {}; -var performanceNow = performance2.now || performance2.mozNow || performance2.msNow || performance2.oNow || performance2.webkitNow || function() { - return (/* @__PURE__ */ new Date()).getTime(); -}; -function hrtime(previousTimestamp) { - var clocktime = performanceNow.call(performance2) * 1e-3; - var seconds = Math.floor(clocktime); - var nanoseconds = Math.floor(clocktime % 1 * 1e9); - if (previousTimestamp) { - seconds = seconds - previousTimestamp[0]; - nanoseconds = nanoseconds - previousTimestamp[1]; - if (nanoseconds < 0) { - seconds--; - nanoseconds += 1e9; - } - } - return [ - seconds, - nanoseconds - ]; -} -__name(hrtime, "hrtime"); -var startTime = /* @__PURE__ */ new Date(); -function uptime() { - var currentTime = /* @__PURE__ */ new Date(); - var dif = currentTime - startTime; - return dif / 1e3; -} -__name(uptime, "uptime"); -var process2 = { - nextTick, - title, - browser, - env: { - NODE_ENV: "production" - }, - argv, - version, - versions, - on, - addListener, - once, - off, - removeListener, - removeAllListeners, - emit, - binding, - cwd, - chdir, - umask, - hrtime, - platform, - release, - config, - uptime -}; -function createCommonjsModule(fn, basedir, module) { - return module = { - path: basedir, - exports: {}, - require: /* @__PURE__ */ __name(function(path, base) { - return commonjsRequire(path, base === void 0 || base === null ? module.path : base); - }, "require") - }, fn(module, module.exports), module.exports; -} -__name(createCommonjsModule, "createCommonjsModule"); -function commonjsRequire() { - throw new Error("Dynamic requires are not currently supported by @rollup/plugin-commonjs"); -} -__name(commonjsRequire, "commonjsRequire"); -function setup(env) { - createDebug.debug = createDebug; - createDebug.default = createDebug; - createDebug.coerce = coerce; - createDebug.disable = disable; - createDebug.enable = enable; - createDebug.enabled = enabled; - createDebug.humanize = ms; - createDebug.destroy = destroy2; - Object.keys(env).forEach((key) => { - createDebug[key] = env[key]; - }); - createDebug.names = []; - createDebug.skips = []; - createDebug.formatters = {}; - function selectColor(namespace) { - let hash = 0; - for (let i = 0; i < namespace.length; i++) { - hash = (hash << 5) - hash + namespace.charCodeAt(i); - hash |= 0; - } - return createDebug.colors[Math.abs(hash) % createDebug.colors.length]; - } - __name(selectColor, "selectColor"); - createDebug.selectColor = selectColor; - function createDebug(namespace) { - let prevTime; - let enableOverride = null; - let namespacesCache; - let enabledCache; - function debug4(...args) { - if (!debug4.enabled) { - return; - } - const self2 = debug4; - const curr = Number(/* @__PURE__ */ new Date()); - const ms2 = curr - (prevTime || curr); - self2.diff = ms2; - self2.prev = prevTime; - self2.curr = curr; - prevTime = curr; - args[0] = createDebug.coerce(args[0]); - if (typeof args[0] !== "string") { - args.unshift("%O"); - } - let index = 0; - args[0] = args[0].replace(/%([a-zA-Z%])/g, (match3, format) => { - if (match3 === "%%") { - return "%"; - } - index++; - const formatter = createDebug.formatters[format]; - if (typeof formatter === "function") { - const val = args[index]; - match3 = formatter.call(self2, val); - args.splice(index, 1); - index--; - } - return match3; - }); - createDebug.formatArgs.call(self2, args); - const logFn = self2.log || createDebug.log; - logFn.apply(self2, args); - } - __name(debug4, "debug"); - debug4.namespace = namespace; - debug4.useColors = createDebug.useColors(); - debug4.color = createDebug.selectColor(namespace); - debug4.extend = extend; - debug4.destroy = createDebug.destroy; - Object.defineProperty(debug4, "enabled", { - enumerable: true, - configurable: false, - get: /* @__PURE__ */ __name(() => { - if (enableOverride !== null) { - return enableOverride; - } - if (namespacesCache !== createDebug.namespaces) { - namespacesCache = createDebug.namespaces; - enabledCache = createDebug.enabled(namespace); - } - return enabledCache; - }, "get"), - set: /* @__PURE__ */ __name((v) => { - enableOverride = v; - }, "set") - }); - if (typeof createDebug.init === "function") { - createDebug.init(debug4); - } - return debug4; - } - __name(createDebug, "createDebug"); - function extend(namespace, delimiter) { - const newDebug = createDebug(this.namespace + (typeof delimiter === "undefined" ? ":" : delimiter) + namespace); - newDebug.log = this.log; - return newDebug; - } - __name(extend, "extend"); - function enable(namespaces) { - createDebug.save(namespaces); - createDebug.namespaces = namespaces; - createDebug.names = []; - createDebug.skips = []; - const split = (typeof namespaces === "string" ? namespaces : "").trim().replace(/\s+/g, ",").split(",").filter(Boolean); - for (const ns of split) { - if (ns[0] === "-") { - createDebug.skips.push(ns.slice(1)); - } else { - createDebug.names.push(ns); - } - } - } - __name(enable, "enable"); - function matchesTemplate(search, template) { - let searchIndex = 0; - let templateIndex = 0; - let starIndex = -1; - let matchIndex = 0; - while (searchIndex < search.length) { - if (templateIndex < template.length && (template[templateIndex] === search[searchIndex] || template[templateIndex] === "*")) { - if (template[templateIndex] === "*") { - starIndex = templateIndex; - matchIndex = searchIndex; - templateIndex++; - } else { - searchIndex++; - templateIndex++; - } - } else if (starIndex !== -1) { - templateIndex = starIndex + 1; - matchIndex++; - searchIndex = matchIndex; - } else { - return false; - } - } - while (templateIndex < template.length && template[templateIndex] === "*") { - templateIndex++; - } - return templateIndex === template.length; - } - __name(matchesTemplate, "matchesTemplate"); - function disable() { - const namespaces = [ - ...createDebug.names, - ...createDebug.skips.map((namespace) => "-" + namespace) - ].join(","); - createDebug.enable(""); - return namespaces; - } - __name(disable, "disable"); - function enabled(name) { - for (const skip of createDebug.skips) { - if (matchesTemplate(name, skip)) { - return false; - } - } - for (const ns of createDebug.names) { - if (matchesTemplate(name, ns)) { - return true; - } - } - return false; - } - __name(enabled, "enabled"); - function coerce(val) { - if (val instanceof Error) { - return val.stack || val.message; - } - return val; - } - __name(coerce, "coerce"); - function destroy2() { - console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."); - } - __name(destroy2, "destroy2"); - createDebug.enable(createDebug.load()); - return createDebug; -} -__name(setup, "setup"); -var common = setup; -var browser$1 = createCommonjsModule(function(module, exports) { - exports.formatArgs = formatArgs2; - exports.save = save2; - exports.load = load2; - exports.useColors = useColors2; - exports.storage = localstorage(); - exports.destroy = /* @__PURE__ */ (() => { - let warned = false; - return () => { - if (!warned) { - warned = true; - console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."); - } - }; - })(); - exports.colors = [ - "#0000CC", - "#0000FF", - "#0033CC", - "#0033FF", - "#0066CC", - "#0066FF", - "#0099CC", - "#0099FF", - "#00CC00", - "#00CC33", - "#00CC66", - "#00CC99", - "#00CCCC", - "#00CCFF", - "#3300CC", - "#3300FF", - "#3333CC", - "#3333FF", - "#3366CC", - "#3366FF", - "#3399CC", - "#3399FF", - "#33CC00", - "#33CC33", - "#33CC66", - "#33CC99", - "#33CCCC", - "#33CCFF", - "#6600CC", - "#6600FF", - "#6633CC", - "#6633FF", - "#66CC00", - "#66CC33", - "#9900CC", - "#9900FF", - "#9933CC", - "#9933FF", - "#99CC00", - "#99CC33", - "#CC0000", - "#CC0033", - "#CC0066", - "#CC0099", - "#CC00CC", - "#CC00FF", - "#CC3300", - "#CC3333", - "#CC3366", - "#CC3399", - "#CC33CC", - "#CC33FF", - "#CC6600", - "#CC6633", - "#CC9900", - "#CC9933", - "#CCCC00", - "#CCCC33", - "#FF0000", - "#FF0033", - "#FF0066", - "#FF0099", - "#FF00CC", - "#FF00FF", - "#FF3300", - "#FF3333", - "#FF3366", - "#FF3399", - "#FF33CC", - "#FF33FF", - "#FF6600", - "#FF6633", - "#FF9900", - "#FF9933", - "#FFCC00", - "#FFCC33" - ]; - function useColors2() { - if (typeof window !== "undefined" && window.process && (window.process.type === "renderer" || window.process.__nwjs)) { - return true; - } - if (typeof navigator !== "undefined" && "Cloudflare-Workers" && "Cloudflare-Workers".toLowerCase().match(/(edge|trident)\/(\d+)/)) { - return false; - } - let m2; - return typeof document !== "undefined" && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance || typeof window !== "undefined" && window.console && (window.console.firebug || window.console.exception && window.console.table) || typeof navigator !== "undefined" && "Cloudflare-Workers" && (m2 = "Cloudflare-Workers".toLowerCase().match(/firefox\/(\d+)/)) && parseInt(m2[1], 10) >= 31 || typeof navigator !== "undefined" && "Cloudflare-Workers" && "Cloudflare-Workers".toLowerCase().match(/applewebkit\/(\d+)/); - } - __name(useColors2, "useColors2"); - function formatArgs2(args) { - args[0] = (this.useColors ? "%c" : "") + this.namespace + (this.useColors ? " %c" : " ") + args[0] + (this.useColors ? "%c " : " ") + "+" + module.exports.humanize(this.diff); - if (!this.useColors) { - return; - } - const c = "color: " + this.color; - args.splice(1, 0, c, "color: inherit"); - let index = 0; - let lastC = 0; - args[0].replace(/%[a-zA-Z%]/g, (match3) => { - if (match3 === "%%") { - return; - } - index++; - if (match3 === "%c") { - lastC = index; - } - }); - args.splice(lastC, 0, c); - } - __name(formatArgs2, "formatArgs2"); - exports.log = console.debug || console.log || (() => { - }); - function save2(namespaces) { - try { - if (namespaces) { - exports.storage.setItem("debug", namespaces); - } else { - exports.storage.removeItem("debug"); - } - } catch (error) { - } - } - __name(save2, "save2"); - function load2() { - let r; - try { - r = exports.storage.getItem("debug") || exports.storage.getItem("DEBUG"); - } catch (error) { - } - if (!r && typeof process2 !== "undefined" && "env" in process2) { - r = process2.env.DEBUG; - } - return r; - } - __name(load2, "load2"); - function localstorage() { - try { - return localStorage; - } catch (error) { - } - } - __name(localstorage, "localstorage"); - module.exports = common(exports); - const { formatters } = module.exports; - formatters.j = function(v) { - try { - return JSON.stringify(v); - } catch (error) { - return "[UnexpectedJSONParseError]: " + error.message; - } - }; -}); -browser$1.colors; -browser$1.destroy; -browser$1.formatArgs; -browser$1.load; -browser$1.log; -browser$1.save; -browser$1.storage; -browser$1.useColors; -var itrToStream = /* @__PURE__ */ __name((itr) => { - const it = itr[Symbol.asyncIterator](); - return new ReadableStream({ - async pull(controller) { - const chunk = await it.next(); - if (chunk.done) controller.close(); - else controller.enqueue(chunk.value); - } - }); -}, "itrToStream"); -var baseFetchConfig = /* @__PURE__ */ __name((_apiRoot) => ({}), "baseFetchConfig"); -var defaultAdapter = "cloudflare"; -var debug = browser$1("grammy:warn"); -var GrammyError = class extends Error { - static { - __name(this, "GrammyError"); - } - method; - payload; - ok; - error_code; - description; - parameters; - constructor(message, err, method, payload) { - super(`${message} (${err.error_code}: ${err.description})`); - this.method = method; - this.payload = payload; - this.ok = false; - this.name = "GrammyError"; - this.error_code = err.error_code; - this.description = err.description; - this.parameters = err.parameters ?? {}; - } -}; -function toGrammyError(err, method, payload) { - switch (err.error_code) { - case 401: - debug("Error 401 means that your bot token is wrong, talk to https://t.me/BotFather to check it."); - break; - case 409: - debug("Error 409 means that you are running your bot several times on long polling. Consider revoking the bot token if you believe that no other instance is running."); - break; - } - return new GrammyError(`Call to '${method}' failed!`, err, method, payload); -} -__name(toGrammyError, "toGrammyError"); -var HttpError = class extends Error { - static { - __name(this, "HttpError"); - } - error; - constructor(message, error) { - super(message); - this.error = error; - this.name = "HttpError"; - } -}; -function isTelegramError(err) { - return typeof err === "object" && err !== null && "status" in err && "statusText" in err; -} -__name(isTelegramError, "isTelegramError"); -function toHttpError(method, sensitiveLogs, err) { - let msg = `Network request for '${method}' failed!`; - if (isTelegramError(err)) msg += ` (${err.status}: ${err.statusText})`; - if (sensitiveLogs && err instanceof Error) msg += ` ${err.message}`; - return new HttpError(msg, err); -} -__name(toHttpError, "toHttpError"); -function checkWindows() { - const global = globalThis; - const os = global.Deno?.build?.os; - return typeof os === "string" ? os === "windows" : global.navigator?.platform?.startsWith("Win") ?? global.process?.platform?.startsWith("win") ?? false; -} -__name(checkWindows, "checkWindows"); -var isWindows = checkWindows(); -function assertPath(path) { - if (typeof path !== "string") { - throw new TypeError(`Path must be a string, received "${JSON.stringify(path)}"`); - } -} -__name(assertPath, "assertPath"); -function stripSuffix(name, suffix) { - if (suffix.length >= name.length) { - return name; - } - const lenDiff = name.length - suffix.length; - for (let i = suffix.length - 1; i >= 0; --i) { - if (name.charCodeAt(lenDiff + i) !== suffix.charCodeAt(i)) { - return name; - } - } - return name.slice(0, -suffix.length); -} -__name(stripSuffix, "stripSuffix"); -function lastPathSegment(path, isSep, start = 0) { - let matchedNonSeparator = false; - let end = path.length; - for (let i = path.length - 1; i >= start; --i) { - if (isSep(path.charCodeAt(i))) { - if (matchedNonSeparator) { - start = i + 1; - break; - } - } else if (!matchedNonSeparator) { - matchedNonSeparator = true; - end = i + 1; - } - } - return path.slice(start, end); -} -__name(lastPathSegment, "lastPathSegment"); -function assertArgs(path, suffix) { - assertPath(path); - if (path.length === 0) return path; - if (typeof suffix !== "string") { - throw new TypeError(`Suffix must be a string, received "${JSON.stringify(suffix)}"`); - } -} -__name(assertArgs, "assertArgs"); -function assertArg(url) { - url = url instanceof URL ? url : new URL(url); - if (url.protocol !== "file:") { - throw new TypeError(`URL must be a file URL: received "${url.protocol}"`); - } - return url; -} -__name(assertArg, "assertArg"); -function fromFileUrl(url) { - url = assertArg(url); - return decodeURIComponent(url.pathname.replace(/%(?![0-9A-Fa-f]{2})/g, "%25")); -} -__name(fromFileUrl, "fromFileUrl"); -function stripTrailingSeparators(segment, isSep) { - if (segment.length <= 1) { - return segment; - } - let end = segment.length; - for (let i = segment.length - 1; i > 0; i--) { - if (isSep(segment.charCodeAt(i))) { - end = i; - } else { - break; - } - } - return segment.slice(0, end); -} -__name(stripTrailingSeparators, "stripTrailingSeparators"); -function isPosixPathSeparator(code) { - return code === 47; -} -__name(isPosixPathSeparator, "isPosixPathSeparator"); -function basename(path, suffix = "") { - if (path instanceof URL) { - path = fromFileUrl(path); - } - assertArgs(path, suffix); - const lastSegment = lastPathSegment(path, isPosixPathSeparator); - const strippedSegment = stripTrailingSeparators(lastSegment, isPosixPathSeparator); - return suffix ? stripSuffix(strippedSegment, suffix) : strippedSegment; -} -__name(basename, "basename"); -function isPathSeparator(code) { - return code === 47 || code === 92; -} -__name(isPathSeparator, "isPathSeparator"); -function isWindowsDeviceRoot(code) { - return code >= 97 && code <= 122 || code >= 65 && code <= 90; -} -__name(isWindowsDeviceRoot, "isWindowsDeviceRoot"); -function fromFileUrl1(url) { - url = assertArg(url); - let path = decodeURIComponent(url.pathname.replace(/\//g, "\\").replace(/%(?![0-9A-Fa-f]{2})/g, "%25")).replace(/^\\*([A-Za-z]:)(\\|$)/, "$1\\"); - if (url.hostname !== "") { - path = `\\\\${url.hostname}${path}`; - } - return path; -} -__name(fromFileUrl1, "fromFileUrl1"); -function basename1(path, suffix = "") { - if (path instanceof URL) { - path = fromFileUrl1(path); - } - assertArgs(path, suffix); - let start = 0; - if (path.length >= 2) { - const drive = path.charCodeAt(0); - if (isWindowsDeviceRoot(drive)) { - if (path.charCodeAt(1) === 58) start = 2; - } - } - const lastSegment = lastPathSegment(path, isPathSeparator, start); - const strippedSegment = stripTrailingSeparators(lastSegment, isPathSeparator); - return suffix ? stripSuffix(strippedSegment, suffix) : strippedSegment; -} -__name(basename1, "basename1"); -function basename2(path, suffix = "") { - return isWindows ? basename1(path, suffix) : basename(path, suffix); -} -__name(basename2, "basename2"); -var InputFile = class { - static { - __name(this, "InputFile"); - } - consumed = false; - fileData; - filename; - constructor(file, filename) { - this.fileData = file; - filename ??= this.guessFilename(file); - this.filename = filename; - } - guessFilename(file) { - if (typeof file === "string") return basename2(file); - if (typeof file !== "object") return void 0; - if ("url" in file) return basename2(file.url); - if (!(file instanceof URL)) return void 0; - return basename2(file.pathname) || basename2(file.hostname); - } - toRaw() { - if (this.consumed) { - throw new Error("Cannot reuse InputFile data source!"); - } - const data2 = this.fileData; - if (data2 instanceof Blob) return data2.stream(); - if (data2 instanceof URL) return fetchFile(data2); - if ("url" in data2) return fetchFile(data2.url); - if (!(data2 instanceof Uint8Array)) this.consumed = true; - return data2; - } - toJSON() { - throw new Error("InputFile instances must be sent via grammY"); - } -}; -async function* fetchFile(url) { - const { body } = await fetch(url); - if (body === null) { - throw new Error(`Download failed, no response body from '${url}'`); - } - yield* body; -} -__name(fetchFile, "fetchFile"); -function requiresFormDataUpload(payload) { - return payload instanceof InputFile || typeof payload === "object" && payload !== null && Object.values(payload).some((v) => Array.isArray(v) ? v.some(requiresFormDataUpload) : v instanceof InputFile || requiresFormDataUpload(v)); -} -__name(requiresFormDataUpload, "requiresFormDataUpload"); -function str(value) { - return JSON.stringify(value, (_, v) => v ?? void 0); -} -__name(str, "str"); -function createJsonPayload(payload) { - return { - method: "POST", - headers: { - "content-type": "application/json", - connection: "keep-alive" - }, - body: str(payload) - }; -} -__name(createJsonPayload, "createJsonPayload"); -async function* protectItr(itr, onError) { - try { - yield* itr; - } catch (err) { - onError(err); - } -} -__name(protectItr, "protectItr"); -function createFormDataPayload(payload, onError) { - const boundary = createBoundary(); - const itr = payloadToMultipartItr(payload, boundary); - const safeItr = protectItr(itr, onError); - const stream = itrToStream(safeItr); - return { - method: "POST", - headers: { - "content-type": `multipart/form-data; boundary=${boundary}`, - connection: "keep-alive" - }, - body: stream - }; -} -__name(createFormDataPayload, "createFormDataPayload"); -function createBoundary() { - return "----------" + randomId(32); -} -__name(createBoundary, "createBoundary"); -function randomId(length = 16) { - return Array.from(Array(length)).map(() => Math.random().toString(36)[2] || 0).join(""); -} -__name(randomId, "randomId"); -var enc = new TextEncoder(); -async function* payloadToMultipartItr(payload, boundary) { - const files = collectFiles(payload); - yield enc.encode(`--${boundary}\r -`); - const separator = enc.encode(`\r ---${boundary}\r -`); - let first = true; - for (const [key, value] of Object.entries(payload)) { - if (value == null) continue; - if (!first) yield separator; - yield valuePart(key, value instanceof InputFile ? value.toJSON() : typeof value === "object" ? str(value) : value); - first = false; - } - for (const { id, origin, file } of files) { - if (!first) yield separator; - yield* filePart(id, origin, file); - first = false; - } - yield enc.encode(`\r ---${boundary}--\r -`); -} -__name(payloadToMultipartItr, "payloadToMultipartItr"); -function collectFiles(value) { - if (typeof value !== "object" || value === null) return []; - return Object.entries(value).flatMap(([k, v]) => { - if (Array.isArray(v)) return v.flatMap((p) => collectFiles(p)); - else if (v instanceof InputFile) { - const id = randomId(); - Object.assign(v, { - toJSON: /* @__PURE__ */ __name(() => `attach://${id}`, "toJSON") - }); - const origin = k === "media" && "type" in value && typeof value.type === "string" ? value.type : k; - return { - id, - origin, - file: v - }; - } else return collectFiles(v); - }); -} -__name(collectFiles, "collectFiles"); -function valuePart(key, value) { - return enc.encode(`content-disposition:form-data;name="${key}"\r -\r -${value}`); -} -__name(valuePart, "valuePart"); -async function* filePart(id, origin, input) { - const filename = input.filename || `${origin}.${getExt(origin)}`; - if (filename.includes("\r") || filename.includes("\n")) { - throw new Error(`File paths cannot contain carriage-return (\\r) or newline (\\n) characters! Filename for property '${origin}' was: -""" -${filename} -"""`); - } - yield enc.encode(`content-disposition:form-data;name="${id}";filename=${filename}\r -content-type:application/octet-stream\r -\r -`); - const data2 = await input.toRaw(); - if (data2 instanceof Uint8Array) yield data2; - else yield* data2; -} -__name(filePart, "filePart"); -function getExt(key) { - switch (key) { - case "certificate": - return "pem"; - case "photo": - case "thumbnail": - return "jpg"; - case "voice": - return "ogg"; - case "audio": - return "mp3"; - case "animation": - case "video": - case "video_note": - return "mp4"; - case "sticker": - return "webp"; - default: - return "dat"; - } -} -__name(getExt, "getExt"); -var debug1 = browser$1("grammy:core"); -function concatTransformer(prev, trans) { - return (method, payload, signal) => trans(prev, method, payload, signal); -} -__name(concatTransformer, "concatTransformer"); -var ApiClient = class { - static { - __name(this, "ApiClient"); - } - token; - webhookReplyEnvelope; - options; - fetch; - hasUsedWebhookReply; - installedTransformers; - constructor(token, options = {}, webhookReplyEnvelope = {}) { - this.token = token; - this.webhookReplyEnvelope = webhookReplyEnvelope; - this.hasUsedWebhookReply = false; - this.installedTransformers = []; - this.call = async (method, p, signal) => { - const payload = p ?? {}; - debug1(`Calling ${method}`); - if (signal !== void 0) validateSignal(method, payload, signal); - const opts = this.options; - const formDataRequired = requiresFormDataUpload(payload); - if (this.webhookReplyEnvelope.send !== void 0 && !this.hasUsedWebhookReply && !formDataRequired && opts.canUseWebhookReply(method)) { - this.hasUsedWebhookReply = true; - const config3 = createJsonPayload({ - ...payload, - method - }); - await this.webhookReplyEnvelope.send(config3.body); - return { - ok: true, - result: true - }; - } - const controller = createAbortControllerFromSignal(signal); - const timeout = createTimeout(controller, opts.timeoutSeconds, method); - const streamErr = createStreamError(controller); - const url = opts.buildUrl(opts.apiRoot, this.token, method, opts.environment); - const config2 = formDataRequired ? createFormDataPayload(payload, (err) => streamErr.catch(err)) : createJsonPayload(payload); - const sig = controller.signal; - const options2 = { - ...opts.baseFetchConfig, - signal: sig, - ...config2 - }; - const successPromise = this.fetch(url, options2).then((res) => res.json()); - const operations = [ - successPromise, - streamErr.promise, - timeout.promise - ]; - try { - return await Promise.race(operations); - } catch (error) { - throw toHttpError(method, opts.sensitiveLogs, error); - } finally { - if (timeout.handle !== void 0) clearTimeout(timeout.handle); - } - }; - const apiRoot = options.apiRoot ?? "https://api.telegram.org"; - const environment = options.environment ?? "prod"; - const { fetch: customFetch } = options; - const fetchFn = customFetch ?? fetch; - this.options = { - apiRoot, - environment, - buildUrl: options.buildUrl ?? defaultBuildUrl, - timeoutSeconds: options.timeoutSeconds ?? 500, - baseFetchConfig: { - ...baseFetchConfig(apiRoot), - ...options.baseFetchConfig - }, - canUseWebhookReply: options.canUseWebhookReply ?? (() => false), - sensitiveLogs: options.sensitiveLogs ?? false, - fetch: /* @__PURE__ */ __name((...args) => fetchFn(...args), "fetch") - }; - this.fetch = this.options.fetch; - if (this.options.apiRoot.endsWith("/")) { - throw new Error(`Remove the trailing '/' from the 'apiRoot' option (use '${this.options.apiRoot.substring(0, this.options.apiRoot.length - 1)}' instead of '${this.options.apiRoot}')`); - } - } - call; - use(...transformers) { - this.call = transformers.reduce(concatTransformer, this.call); - this.installedTransformers.push(...transformers); - return this; - } - async callApi(method, payload, signal) { - const data2 = await this.call(method, payload, signal); - if (data2.ok) return data2.result; - else throw toGrammyError(data2, method, payload); - } -}; -function createRawApi(token, options, webhookReplyEnvelope) { - const client = new ApiClient(token, options, webhookReplyEnvelope); - const proxyHandler = { - get(_, m2) { - return m2 === "toJSON" ? "__internal" : m2 === "getMe" || m2 === "getWebhookInfo" || m2 === "getForumTopicIconStickers" || m2 === "getAvailableGifts" || m2 === "logOut" || m2 === "close" || m2 === "getMyStarBalance" || m2 === "removeMyProfilePhoto" ? client.callApi.bind(client, m2, {}) : client.callApi.bind(client, m2); - }, - ...proxyMethods - }; - const raw2 = new Proxy({}, proxyHandler); - const installedTransformers = client.installedTransformers; - const api = { - raw: raw2, - installedTransformers, - use: /* @__PURE__ */ __name((...t2) => { - client.use(...t2); - return api; - }, "use") - }; - return api; -} -__name(createRawApi, "createRawApi"); -var defaultBuildUrl = /* @__PURE__ */ __name((root, token, method, env) => { - const prefix = env === "test" ? "test/" : ""; - return `${root}/bot${token}/${prefix}${method}`; -}, "defaultBuildUrl"); -var proxyMethods = { - set() { - return false; - }, - defineProperty() { - return false; - }, - deleteProperty() { - return false; - }, - ownKeys() { - return []; - } -}; -function createTimeout(controller, seconds, method) { - let handle = void 0; - const promise = new Promise((_, reject) => { - handle = setTimeout(() => { - const msg = `Request to '${method}' timed out after ${seconds} seconds`; - reject(new Error(msg)); - controller.abort(); - }, 1e3 * seconds); - }); - return { - promise, - handle - }; -} -__name(createTimeout, "createTimeout"); -function createStreamError(abortController) { - let onError = /* @__PURE__ */ __name((err) => { - throw err; - }, "onError"); - const promise = new Promise((_, reject) => { - onError = /* @__PURE__ */ __name((err) => { - reject(err); - abortController.abort(); - }, "onError"); - }); - return { - promise, - catch: onError - }; -} -__name(createStreamError, "createStreamError"); -function createAbortControllerFromSignal(signal) { - const abortController = new AbortController(); - if (signal === void 0) return abortController; - const sig = signal; - function abort() { - abortController.abort(); - sig.removeEventListener("abort", abort); - } - __name(abort, "abort"); - if (sig.aborted) abort(); - else sig.addEventListener("abort", abort); - return { - abort, - signal: abortController.signal - }; -} -__name(createAbortControllerFromSignal, "createAbortControllerFromSignal"); -function validateSignal(method, payload, signal) { - if (typeof signal?.addEventListener === "function") { - return; - } - let payload0 = JSON.stringify(payload); - if (payload0.length > 20) { - payload0 = payload0.substring(0, 16) + " ..."; - } - let payload1 = JSON.stringify(signal); - if (payload1.length > 20) { - payload1 = payload1.substring(0, 16) + " ..."; - } - throw new Error(`Incorrect abort signal instance found! You passed two payloads to '${method}' but you should merge the second one containing '${payload1}' into the first one containing '${payload0}'! If you are using context shortcuts, you may want to use a method on 'ctx.api' instead. - -If you want to prevent such mistakes in the future, consider using TypeScript. https://www.typescriptlang.org/`); -} -__name(validateSignal, "validateSignal"); -var Api = class { - static { - __name(this, "Api"); - } - token; - options; - raw; - config; - constructor(token, options, webhookReplyEnvelope) { - this.token = token; - this.options = options; - const { raw: raw2, use: use2, installedTransformers } = createRawApi(token, options, webhookReplyEnvelope); - this.raw = raw2; - this.config = { - use: use2, - installedTransformers: /* @__PURE__ */ __name(() => installedTransformers.slice(), "installedTransformers") - }; - } - getUpdates(other, signal) { - return this.raw.getUpdates({ - ...other - }, signal); - } - setWebhook(url, other, signal) { - return this.raw.setWebhook({ - url, - ...other - }, signal); - } - deleteWebhook(other, signal) { - return this.raw.deleteWebhook({ - ...other - }, signal); - } - getWebhookInfo(signal) { - return this.raw.getWebhookInfo(signal); - } - getMe(signal) { - return this.raw.getMe(signal); - } - logOut(signal) { - return this.raw.logOut(signal); - } - close(signal) { - return this.raw.close(signal); - } - sendMessage(chat_id, text2, other, signal) { - return this.raw.sendMessage({ - chat_id, - text: text2, - ...other - }, signal); - } - sendMessageDraft(chat_id, draft_id, text2, other, signal) { - return this.raw.sendMessageDraft({ - chat_id, - draft_id, - text: text2, - ...other - }, signal); - } - forwardMessage(chat_id, from_chat_id, message_id, other, signal) { - return this.raw.forwardMessage({ - chat_id, - from_chat_id, - message_id, - ...other - }, signal); - } - forwardMessages(chat_id, from_chat_id, message_ids, other, signal) { - return this.raw.forwardMessages({ - chat_id, - from_chat_id, - message_ids, - ...other - }, signal); - } - copyMessage(chat_id, from_chat_id, message_id, other, signal) { - return this.raw.copyMessage({ - chat_id, - from_chat_id, - message_id, - ...other - }, signal); - } - copyMessages(chat_id, from_chat_id, message_ids, other, signal) { - return this.raw.copyMessages({ - chat_id, - from_chat_id, - message_ids, - ...other - }, signal); - } - sendPhoto(chat_id, photo, other, signal) { - return this.raw.sendPhoto({ - chat_id, - photo, - ...other - }, signal); - } - sendAudio(chat_id, audio, other, signal) { - return this.raw.sendAudio({ - chat_id, - audio, - ...other - }, signal); - } - sendDocument(chat_id, document1, other, signal) { - return this.raw.sendDocument({ - chat_id, - document: document1, - ...other - }, signal); - } - sendVideo(chat_id, video, other, signal) { - return this.raw.sendVideo({ - chat_id, - video, - ...other - }, signal); - } - sendAnimation(chat_id, animation, other, signal) { - return this.raw.sendAnimation({ - chat_id, - animation, - ...other - }, signal); - } - sendVoice(chat_id, voice, other, signal) { - return this.raw.sendVoice({ - chat_id, - voice, - ...other - }, signal); - } - sendVideoNote(chat_id, video_note, other, signal) { - return this.raw.sendVideoNote({ - chat_id, - video_note, - ...other - }, signal); - } - sendMediaGroup(chat_id, media, other, signal) { - return this.raw.sendMediaGroup({ - chat_id, - media, - ...other - }, signal); - } - sendLocation(chat_id, latitude, longitude, other, signal) { - return this.raw.sendLocation({ - chat_id, - latitude, - longitude, - ...other - }, signal); - } - editMessageLiveLocation(chat_id, message_id, latitude, longitude, other, signal) { - return this.raw.editMessageLiveLocation({ - chat_id, - message_id, - latitude, - longitude, - ...other - }, signal); - } - editMessageLiveLocationInline(inline_message_id, latitude, longitude, other, signal) { - return this.raw.editMessageLiveLocation({ - inline_message_id, - latitude, - longitude, - ...other - }, signal); - } - stopMessageLiveLocation(chat_id, message_id, other, signal) { - return this.raw.stopMessageLiveLocation({ - chat_id, - message_id, - ...other - }, signal); - } - stopMessageLiveLocationInline(inline_message_id, other, signal) { - return this.raw.stopMessageLiveLocation({ - inline_message_id, - ...other - }, signal); - } - sendPaidMedia(chat_id, star_count, media, other, signal) { - return this.raw.sendPaidMedia({ - chat_id, - star_count, - media, - ...other - }, signal); - } - sendVenue(chat_id, latitude, longitude, title2, address, other, signal) { - return this.raw.sendVenue({ - chat_id, - latitude, - longitude, - title: title2, - address, - ...other - }, signal); - } - sendContact(chat_id, phone_number, first_name, other, signal) { - return this.raw.sendContact({ - chat_id, - phone_number, - first_name, - ...other - }, signal); - } - sendPoll(chat_id, question, options, other, signal) { - const opts = options.map((o) => typeof o === "string" ? { - text: o - } : o); - return this.raw.sendPoll({ - chat_id, - question, - options: opts, - ...other - }, signal); - } - sendChecklist(business_connection_id, chat_id, checklist, other, signal) { - return this.raw.sendChecklist({ - business_connection_id, - chat_id, - checklist, - ...other - }, signal); - } - editMessageChecklist(business_connection_id, chat_id, message_id, checklist, other, signal) { - return this.raw.editMessageChecklist({ - business_connection_id, - chat_id, - message_id, - checklist, - ...other - }, signal); - } - sendDice(chat_id, emoji, other, signal) { - return this.raw.sendDice({ - chat_id, - emoji, - ...other - }, signal); - } - setMessageReaction(chat_id, message_id, reaction, other, signal) { - return this.raw.setMessageReaction({ - chat_id, - message_id, - reaction, - ...other - }, signal); - } - sendChatAction(chat_id, action, other, signal) { - return this.raw.sendChatAction({ - chat_id, - action, - ...other - }, signal); - } - getUserProfilePhotos(user_id, other, signal) { - return this.raw.getUserProfilePhotos({ - user_id, - ...other - }, signal); - } - getUserProfileAudios(user_id, other, signal) { - return this.raw.getUserProfileAudios({ - user_id, - ...other - }, signal); - } - setUserEmojiStatus(user_id, other, signal) { - return this.raw.setUserEmojiStatus({ - user_id, - ...other - }, signal); - } - getUserChatBoosts(chat_id, user_id, signal) { - return this.raw.getUserChatBoosts({ - chat_id, - user_id - }, signal); - } - getUserGifts(user_id, other, signal) { - return this.raw.getUserGifts({ - user_id, - ...other - }, signal); - } - getChatGifts(chat_id, other, signal) { - return this.raw.getChatGifts({ - chat_id, - ...other - }, signal); - } - getBusinessConnection(business_connection_id, signal) { - return this.raw.getBusinessConnection({ - business_connection_id - }, signal); - } - getFile(file_id, signal) { - return this.raw.getFile({ - file_id - }, signal); - } - kickChatMember(...args) { - return this.banChatMember(...args); - } - banChatMember(chat_id, user_id, other, signal) { - return this.raw.banChatMember({ - chat_id, - user_id, - ...other - }, signal); - } - unbanChatMember(chat_id, user_id, other, signal) { - return this.raw.unbanChatMember({ - chat_id, - user_id, - ...other - }, signal); - } - restrictChatMember(chat_id, user_id, permissions, other, signal) { - return this.raw.restrictChatMember({ - chat_id, - user_id, - permissions, - ...other - }, signal); - } - promoteChatMember(chat_id, user_id, other, signal) { - return this.raw.promoteChatMember({ - chat_id, - user_id, - ...other - }, signal); - } - setChatAdministratorCustomTitle(chat_id, user_id, custom_title, signal) { - return this.raw.setChatAdministratorCustomTitle({ - chat_id, - user_id, - custom_title - }, signal); - } - setChatMemberTag(chat_id, user_id, tag, signal) { - return this.raw.setChatMemberTag({ - chat_id, - user_id, - tag - }, signal); - } - banChatSenderChat(chat_id, sender_chat_id, signal) { - return this.raw.banChatSenderChat({ - chat_id, - sender_chat_id - }, signal); - } - unbanChatSenderChat(chat_id, sender_chat_id, signal) { - return this.raw.unbanChatSenderChat({ - chat_id, - sender_chat_id - }, signal); - } - setChatPermissions(chat_id, permissions, other, signal) { - return this.raw.setChatPermissions({ - chat_id, - permissions, - ...other - }, signal); - } - exportChatInviteLink(chat_id, signal) { - return this.raw.exportChatInviteLink({ - chat_id - }, signal); - } - createChatInviteLink(chat_id, other, signal) { - return this.raw.createChatInviteLink({ - chat_id, - ...other - }, signal); - } - editChatInviteLink(chat_id, invite_link, other, signal) { - return this.raw.editChatInviteLink({ - chat_id, - invite_link, - ...other - }, signal); - } - createChatSubscriptionInviteLink(chat_id, subscription_period, subscription_price, other, signal) { - return this.raw.createChatSubscriptionInviteLink({ - chat_id, - subscription_period, - subscription_price, - ...other - }, signal); - } - editChatSubscriptionInviteLink(chat_id, invite_link, other, signal) { - return this.raw.editChatSubscriptionInviteLink({ - chat_id, - invite_link, - ...other - }, signal); - } - revokeChatInviteLink(chat_id, invite_link, signal) { - return this.raw.revokeChatInviteLink({ - chat_id, - invite_link - }, signal); - } - approveChatJoinRequest(chat_id, user_id, signal) { - return this.raw.approveChatJoinRequest({ - chat_id, - user_id - }, signal); - } - declineChatJoinRequest(chat_id, user_id, signal) { - return this.raw.declineChatJoinRequest({ - chat_id, - user_id - }, signal); - } - approveSuggestedPost(chat_id, message_id, other, signal) { - return this.raw.approveSuggestedPost({ - chat_id, - message_id, - ...other - }, signal); - } - declineSuggestedPost(chat_id, message_id, other, signal) { - return this.raw.declineSuggestedPost({ - chat_id, - message_id, - ...other - }, signal); - } - setChatPhoto(chat_id, photo, signal) { - return this.raw.setChatPhoto({ - chat_id, - photo - }, signal); - } - deleteChatPhoto(chat_id, signal) { - return this.raw.deleteChatPhoto({ - chat_id - }, signal); - } - setChatTitle(chat_id, title2, signal) { - return this.raw.setChatTitle({ - chat_id, - title: title2 - }, signal); - } - setChatDescription(chat_id, description, signal) { - return this.raw.setChatDescription({ - chat_id, - description - }, signal); - } - pinChatMessage(chat_id, message_id, other, signal) { - return this.raw.pinChatMessage({ - chat_id, - message_id, - ...other - }, signal); - } - unpinChatMessage(chat_id, message_id, other, signal) { - return this.raw.unpinChatMessage({ - chat_id, - message_id, - ...other - }, signal); - } - unpinAllChatMessages(chat_id, signal) { - return this.raw.unpinAllChatMessages({ - chat_id - }, signal); - } - leaveChat(chat_id, signal) { - return this.raw.leaveChat({ - chat_id - }, signal); - } - getChat(chat_id, signal) { - return this.raw.getChat({ - chat_id - }, signal); - } - getChatAdministrators(chat_id, signal) { - return this.raw.getChatAdministrators({ - chat_id - }, signal); - } - getChatMembersCount(...args) { - return this.getChatMemberCount(...args); - } - getChatMemberCount(chat_id, signal) { - return this.raw.getChatMemberCount({ - chat_id - }, signal); - } - getChatMember(chat_id, user_id, signal) { - return this.raw.getChatMember({ - chat_id, - user_id - }, signal); - } - setChatStickerSet(chat_id, sticker_set_name, signal) { - return this.raw.setChatStickerSet({ - chat_id, - sticker_set_name - }, signal); - } - deleteChatStickerSet(chat_id, signal) { - return this.raw.deleteChatStickerSet({ - chat_id - }, signal); - } - getForumTopicIconStickers(signal) { - return this.raw.getForumTopicIconStickers(signal); - } - createForumTopic(chat_id, name, other, signal) { - return this.raw.createForumTopic({ - chat_id, - name, - ...other - }, signal); - } - editForumTopic(chat_id, message_thread_id, other, signal) { - return this.raw.editForumTopic({ - chat_id, - message_thread_id, - ...other - }, signal); - } - closeForumTopic(chat_id, message_thread_id, signal) { - return this.raw.closeForumTopic({ - chat_id, - message_thread_id - }, signal); - } - reopenForumTopic(chat_id, message_thread_id, signal) { - return this.raw.reopenForumTopic({ - chat_id, - message_thread_id - }, signal); - } - deleteForumTopic(chat_id, message_thread_id, signal) { - return this.raw.deleteForumTopic({ - chat_id, - message_thread_id - }, signal); - } - unpinAllForumTopicMessages(chat_id, message_thread_id, signal) { - return this.raw.unpinAllForumTopicMessages({ - chat_id, - message_thread_id - }, signal); - } - editGeneralForumTopic(chat_id, name, signal) { - return this.raw.editGeneralForumTopic({ - chat_id, - name - }, signal); - } - closeGeneralForumTopic(chat_id, signal) { - return this.raw.closeGeneralForumTopic({ - chat_id - }, signal); - } - reopenGeneralForumTopic(chat_id, signal) { - return this.raw.reopenGeneralForumTopic({ - chat_id - }, signal); - } - hideGeneralForumTopic(chat_id, signal) { - return this.raw.hideGeneralForumTopic({ - chat_id - }, signal); - } - unhideGeneralForumTopic(chat_id, signal) { - return this.raw.unhideGeneralForumTopic({ - chat_id - }, signal); - } - unpinAllGeneralForumTopicMessages(chat_id, signal) { - return this.raw.unpinAllGeneralForumTopicMessages({ - chat_id - }, signal); - } - answerCallbackQuery(callback_query_id, other, signal) { - return this.raw.answerCallbackQuery({ - callback_query_id, - ...other - }, signal); - } - setMyName(name, other, signal) { - return this.raw.setMyName({ - name, - ...other - }, signal); - } - getMyName(other, signal) { - return this.raw.getMyName(other ?? {}, signal); - } - setMyCommands(commands, other, signal) { - return this.raw.setMyCommands({ - commands, - ...other - }, signal); - } - deleteMyCommands(other, signal) { - return this.raw.deleteMyCommands({ - ...other - }, signal); - } - getMyCommands(other, signal) { - return this.raw.getMyCommands({ - ...other - }, signal); - } - setMyDescription(description, other, signal) { - return this.raw.setMyDescription({ - description, - ...other - }, signal); - } - getMyDescription(other, signal) { - return this.raw.getMyDescription({ - ...other - }, signal); - } - setMyShortDescription(short_description, other, signal) { - return this.raw.setMyShortDescription({ - short_description, - ...other - }, signal); - } - getMyShortDescription(other, signal) { - return this.raw.getMyShortDescription({ - ...other - }, signal); - } - setMyProfilePhoto(photo, signal) { - return this.raw.setMyProfilePhoto({ - photo - }, signal); - } - removeMyProfilePhoto(signal) { - return this.raw.removeMyProfilePhoto(signal); - } - setChatMenuButton(other, signal) { - return this.raw.setChatMenuButton({ - ...other - }, signal); - } - getChatMenuButton(other, signal) { - return this.raw.getChatMenuButton({ - ...other - }, signal); - } - setMyDefaultAdministratorRights(other, signal) { - return this.raw.setMyDefaultAdministratorRights({ - ...other - }, signal); - } - getMyDefaultAdministratorRights(other, signal) { - return this.raw.getMyDefaultAdministratorRights({ - ...other - }, signal); - } - getMyStarBalance(signal) { - return this.raw.getMyStarBalance(signal); - } - editMessageText(chat_id, message_id, text2, other, signal) { - return this.raw.editMessageText({ - chat_id, - message_id, - text: text2, - ...other - }, signal); - } - editMessageTextInline(inline_message_id, text2, other, signal) { - return this.raw.editMessageText({ - inline_message_id, - text: text2, - ...other - }, signal); - } - editMessageCaption(chat_id, message_id, other, signal) { - return this.raw.editMessageCaption({ - chat_id, - message_id, - ...other - }, signal); - } - editMessageCaptionInline(inline_message_id, other, signal) { - return this.raw.editMessageCaption({ - inline_message_id, - ...other - }, signal); - } - editMessageMedia(chat_id, message_id, media, other, signal) { - return this.raw.editMessageMedia({ - chat_id, - message_id, - media, - ...other - }, signal); - } - editMessageMediaInline(inline_message_id, media, other, signal) { - return this.raw.editMessageMedia({ - inline_message_id, - media, - ...other - }, signal); - } - editMessageReplyMarkup(chat_id, message_id, other, signal) { - return this.raw.editMessageReplyMarkup({ - chat_id, - message_id, - ...other - }, signal); - } - editMessageReplyMarkupInline(inline_message_id, other, signal) { - return this.raw.editMessageReplyMarkup({ - inline_message_id, - ...other - }, signal); - } - stopPoll(chat_id, message_id, other, signal) { - return this.raw.stopPoll({ - chat_id, - message_id, - ...other - }, signal); - } - deleteMessage(chat_id, message_id, signal) { - return this.raw.deleteMessage({ - chat_id, - message_id - }, signal); - } - deleteMessages(chat_id, message_ids, signal) { - return this.raw.deleteMessages({ - chat_id, - message_ids - }, signal); - } - deleteBusinessMessages(business_connection_id, message_ids, signal) { - return this.raw.deleteBusinessMessages({ - business_connection_id, - message_ids - }, signal); - } - setBusinessAccountName(business_connection_id, first_name, other, signal) { - return this.raw.setBusinessAccountName({ - business_connection_id, - first_name, - ...other - }, signal); - } - setBusinessAccountUsername(business_connection_id, username, signal) { - return this.raw.setBusinessAccountUsername({ - business_connection_id, - username - }, signal); - } - setBusinessAccountBio(business_connection_id, bio, signal) { - return this.raw.setBusinessAccountBio({ - business_connection_id, - bio - }, signal); - } - setBusinessAccountProfilePhoto(business_connection_id, photo, other, signal) { - return this.raw.setBusinessAccountProfilePhoto({ - business_connection_id, - photo, - ...other - }, signal); - } - removeBusinessAccountProfilePhoto(business_connection_id, other, signal) { - return this.raw.removeBusinessAccountProfilePhoto({ - business_connection_id, - ...other - }, signal); - } - setBusinessAccountGiftSettings(business_connection_id, show_gift_button, accepted_gift_types, signal) { - return this.raw.setBusinessAccountGiftSettings({ - business_connection_id, - show_gift_button, - accepted_gift_types - }, signal); - } - getBusinessAccountStarBalance(business_connection_id, signal) { - return this.raw.getBusinessAccountStarBalance({ - business_connection_id - }, signal); - } - transferBusinessAccountStars(business_connection_id, star_count, signal) { - return this.raw.transferBusinessAccountStars({ - business_connection_id, - star_count - }, signal); - } - getBusinessAccountGifts(business_connection_id, other, signal) { - return this.raw.getBusinessAccountGifts({ - business_connection_id, - ...other - }, signal); - } - convertGiftToStars(business_connection_id, owned_gift_id, signal) { - return this.raw.convertGiftToStars({ - business_connection_id, - owned_gift_id - }, signal); - } - upgradeGift(business_connection_id, owned_gift_id, other, signal) { - return this.raw.upgradeGift({ - business_connection_id, - owned_gift_id, - ...other - }, signal); - } - transferGift(business_connection_id, owned_gift_id, new_owner_chat_id, star_count, signal) { - return this.raw.transferGift({ - business_connection_id, - owned_gift_id, - new_owner_chat_id, - star_count - }, signal); - } - postStory(business_connection_id, content, active_period, other, signal) { - return this.raw.postStory({ - business_connection_id, - content, - active_period, - ...other - }, signal); - } - repostStory(business_connection_id, from_chat_id, from_story_id, active_period, other, signal) { - return this.raw.repostStory({ - business_connection_id, - from_chat_id, - from_story_id, - active_period, - ...other - }, signal); - } - editStory(business_connection_id, story_id, content, other, signal) { - return this.raw.editStory({ - business_connection_id, - story_id, - content, - ...other - }, signal); - } - deleteStory(business_connection_id, story_id, signal) { - return this.raw.deleteStory({ - business_connection_id, - story_id - }, signal); - } - sendSticker(chat_id, sticker, other, signal) { - return this.raw.sendSticker({ - chat_id, - sticker, - ...other - }, signal); - } - getStickerSet(name, signal) { - return this.raw.getStickerSet({ - name - }, signal); - } - getCustomEmojiStickers(custom_emoji_ids, signal) { - return this.raw.getCustomEmojiStickers({ - custom_emoji_ids - }, signal); - } - uploadStickerFile(user_id, sticker_format, sticker, signal) { - return this.raw.uploadStickerFile({ - user_id, - sticker_format, - sticker - }, signal); - } - createNewStickerSet(user_id, name, title2, stickers, other, signal) { - return this.raw.createNewStickerSet({ - user_id, - name, - title: title2, - stickers, - ...other - }, signal); - } - addStickerToSet(user_id, name, sticker, signal) { - return this.raw.addStickerToSet({ - user_id, - name, - sticker - }, signal); - } - setStickerPositionInSet(sticker, position, signal) { - return this.raw.setStickerPositionInSet({ - sticker, - position - }, signal); - } - deleteStickerFromSet(sticker, signal) { - return this.raw.deleteStickerFromSet({ - sticker - }, signal); - } - replaceStickerInSet(user_id, name, old_sticker, sticker, signal) { - return this.raw.replaceStickerInSet({ - user_id, - name, - old_sticker, - sticker - }, signal); - } - setStickerEmojiList(sticker, emoji_list, signal) { - return this.raw.setStickerEmojiList({ - sticker, - emoji_list - }, signal); - } - setStickerKeywords(sticker, keywords, signal) { - return this.raw.setStickerKeywords({ - sticker, - keywords - }, signal); - } - setStickerMaskPosition(sticker, mask_position, signal) { - return this.raw.setStickerMaskPosition({ - sticker, - mask_position - }, signal); - } - setStickerSetTitle(name, title2, signal) { - return this.raw.setStickerSetTitle({ - name, - title: title2 - }, signal); - } - deleteStickerSet(name, signal) { - return this.raw.deleteStickerSet({ - name - }, signal); - } - setStickerSetThumbnail(name, user_id, thumbnail, format, signal) { - return this.raw.setStickerSetThumbnail({ - name, - user_id, - thumbnail, - format - }, signal); - } - setCustomEmojiStickerSetThumbnail(name, custom_emoji_id, signal) { - return this.raw.setCustomEmojiStickerSetThumbnail({ - name, - custom_emoji_id - }, signal); - } - getAvailableGifts(signal) { - return this.raw.getAvailableGifts(signal); - } - sendGift(user_id, gift_id, other, signal) { - return this.raw.sendGift({ - user_id, - gift_id, - ...other - }, signal); - } - giftPremiumSubscription(user_id, month_count, star_count, other, signal) { - return this.raw.giftPremiumSubscription({ - user_id, - month_count, - star_count, - ...other - }, signal); - } - sendGiftToChannel(chat_id, gift_id, other, signal) { - return this.raw.sendGift({ - chat_id, - gift_id, - ...other - }, signal); - } - answerInlineQuery(inline_query_id, results, other, signal) { - return this.raw.answerInlineQuery({ - inline_query_id, - results, - ...other - }, signal); - } - answerWebAppQuery(web_app_query_id, result, signal) { - return this.raw.answerWebAppQuery({ - web_app_query_id, - result - }, signal); - } - savePreparedInlineMessage(user_id, result, other, signal) { - return this.raw.savePreparedInlineMessage({ - user_id, - result, - ...other - }, signal); - } - sendInvoice(chat_id, title2, description, payload, currency, prices, other, signal) { - return this.raw.sendInvoice({ - chat_id, - title: title2, - description, - payload, - currency, - prices, - ...other - }, signal); - } - createInvoiceLink(title2, description, payload, provider_token, currency, prices, other, signal) { - return this.raw.createInvoiceLink({ - title: title2, - description, - payload, - provider_token, - currency, - prices, - ...other - }, signal); - } - answerShippingQuery(shipping_query_id, ok2, other, signal) { - return this.raw.answerShippingQuery({ - shipping_query_id, - ok: ok2, - ...other - }, signal); - } - answerPreCheckoutQuery(pre_checkout_query_id, ok2, other, signal) { - return this.raw.answerPreCheckoutQuery({ - pre_checkout_query_id, - ok: ok2, - ...other - }, signal); - } - getStarTransactions(other, signal) { - return this.raw.getStarTransactions({ - ...other - }, signal); - } - refundStarPayment(user_id, telegram_payment_charge_id, signal) { - return this.raw.refundStarPayment({ - user_id, - telegram_payment_charge_id - }, signal); - } - editUserStarSubscription(user_id, telegram_payment_charge_id, is_canceled, signal) { - return this.raw.editUserStarSubscription({ - user_id, - telegram_payment_charge_id, - is_canceled - }, signal); - } - verifyUser(user_id, other, signal) { - return this.raw.verifyUser({ - user_id, - ...other - }, signal); - } - verifyChat(chat_id, other, signal) { - return this.raw.verifyChat({ - chat_id, - ...other - }, signal); - } - removeUserVerification(user_id, signal) { - return this.raw.removeUserVerification({ - user_id - }, signal); - } - removeChatVerification(chat_id, signal) { - return this.raw.removeChatVerification({ - chat_id - }, signal); - } - readBusinessMessage(business_connection_id, chat_id, message_id, signal) { - return this.raw.readBusinessMessage({ - business_connection_id, - chat_id, - message_id - }, signal); - } - setPassportDataErrors(user_id, errors, signal) { - return this.raw.setPassportDataErrors({ - user_id, - errors - }, signal); - } - sendGame(chat_id, game_short_name, other, signal) { - return this.raw.sendGame({ - chat_id, - game_short_name, - ...other - }, signal); - } - setGameScore(chat_id, message_id, user_id, score, other, signal) { - return this.raw.setGameScore({ - chat_id, - message_id, - user_id, - score, - ...other - }, signal); - } - setGameScoreInline(inline_message_id, user_id, score, other, signal) { - return this.raw.setGameScore({ - inline_message_id, - user_id, - score, - ...other - }, signal); - } - getGameHighScores(chat_id, message_id, user_id, signal) { - return this.raw.getGameHighScores({ - chat_id, - message_id, - user_id - }, signal); - } - getGameHighScoresInline(inline_message_id, user_id, signal) { - return this.raw.getGameHighScores({ - inline_message_id, - user_id - }, signal); - } -}; -var debug2 = browser$1("grammy:bot"); -var debugWarn = browser$1("grammy:warn"); -var debugErr = browser$1("grammy:error"); -var DEFAULT_UPDATE_TYPES = [ - "message", - "edited_message", - "channel_post", - "edited_channel_post", - "business_connection", - "business_message", - "edited_business_message", - "deleted_business_messages", - "inline_query", - "chosen_inline_result", - "callback_query", - "shipping_query", - "pre_checkout_query", - "purchased_paid_media", - "poll", - "poll_answer", - "my_chat_member", - "chat_join_request", - "chat_boost", - "removed_chat_boost" -]; -var Bot = class extends Composer { - static { - __name(this, "Bot"); - } - token; - pollingRunning; - pollingAbortController; - lastTriedUpdateId; - api; - me; - mePromise; - clientConfig; - ContextConstructor; - observedUpdateTypes; - errorHandler; - constructor(token, config2) { - super(); - this.token = token; - this.pollingRunning = false; - this.lastTriedUpdateId = 0; - this.observedUpdateTypes = /* @__PURE__ */ new Set(); - this.errorHandler = async (err) => { - console.error("Error in middleware while handling update", err.ctx?.update?.update_id, err.error); - console.error("No error handler was set!"); - console.error("Set your own error handler with `bot.catch = ...`"); - if (this.pollingRunning) { - console.error("Stopping bot"); - await this.stop(); - } - throw err; - }; - if (!token) throw new Error("Empty token!"); - this.me = config2?.botInfo; - this.clientConfig = config2?.client; - this.ContextConstructor = config2?.ContextConstructor ?? Context2; - this.api = new Api(token, this.clientConfig); - } - set botInfo(botInfo) { - this.me = botInfo; - } - get botInfo() { - if (this.me === void 0) { - throw new Error("Bot information unavailable! Make sure to call `await bot.init()` before accessing `bot.botInfo`!"); - } - return this.me; - } - on(filter, ...middleware) { - for (const [u] of parse(filter).flatMap(preprocess)) { - this.observedUpdateTypes.add(u); - } - return super.on(filter, ...middleware); - } - reaction(reaction, ...middleware) { - this.observedUpdateTypes.add("message_reaction"); - return super.reaction(reaction, ...middleware); - } - isInited() { - return this.me !== void 0; - } - async init(signal) { - if (!this.isInited()) { - debug2("Initializing bot"); - this.mePromise ??= withRetries(() => this.api.getMe(signal), signal); - let me; - try { - me = await this.mePromise; - } finally { - this.mePromise = void 0; - } - if (this.me === void 0) this.me = me; - else debug2("Bot info was set by now, will not overwrite"); - } - debug2(`I am ${this.me.username}!`); - } - async handleUpdates(updates) { - for (const update of updates) { - this.lastTriedUpdateId = update.update_id; - try { - await this.handleUpdate(update); - } catch (err) { - if (err instanceof BotError) { - await this.errorHandler(err); - } else { - console.error("FATAL: grammY unable to handle:", err); - throw err; - } - } - } - } - async handleUpdate(update, webhookReplyEnvelope) { - if (this.me === void 0) { - throw new Error("Bot not initialized! Either call `await bot.init()`, or directly set the `botInfo` option in the `Bot` constructor to specify a known bot info object."); - } - debug2(`Processing update ${update.update_id}`); - const api = new Api(this.token, this.clientConfig, webhookReplyEnvelope); - const t2 = this.api.config.installedTransformers(); - if (t2.length > 0) api.config.use(...t2); - const ctx = new this.ContextConstructor(update, api, this.me); - try { - await run(this.middleware(), ctx); - } catch (err) { - debugErr(`Error in middleware for update ${update.update_id}`); - throw new BotError(err, ctx); - } - } - async start(options) { - const setup2 = []; - if (!this.isInited()) { - setup2.push(this.init(this.pollingAbortController?.signal)); - } - if (this.pollingRunning) { - await Promise.all(setup2); - debug2("Simple long polling already running!"); - return; - } - this.pollingRunning = true; - this.pollingAbortController = new AbortController(); - try { - setup2.push(withRetries(async () => { - await this.api.deleteWebhook({ - drop_pending_updates: options?.drop_pending_updates - }, this.pollingAbortController?.signal); - }, this.pollingAbortController?.signal)); - await Promise.all(setup2); - await options?.onStart?.(this.botInfo); - } catch (err) { - this.pollingRunning = false; - this.pollingAbortController = void 0; - throw err; - } - if (!this.pollingRunning) return; - validateAllowedUpdates(this.observedUpdateTypes, options?.allowed_updates); - this.use = noUseFunction; - debug2("Starting simple long polling"); - await this.loop(options); - debug2("Middleware is done running"); - } - async stop() { - if (this.pollingRunning) { - debug2("Stopping bot, saving update offset"); - this.pollingRunning = false; - this.pollingAbortController?.abort(); - const offset = this.lastTriedUpdateId + 1; - await this.api.getUpdates({ - offset, - limit: 1 - }).finally(() => this.pollingAbortController = void 0); - } else { - debug2("Bot is not running!"); - } - } - isRunning() { - return this.pollingRunning; - } - catch(errorHandler2) { - this.errorHandler = errorHandler2; - } - async loop(options) { - const limit = options?.limit; - const timeout = options?.timeout ?? 30; - let allowed_updates = options?.allowed_updates ?? []; - try { - while (this.pollingRunning) { - const updates = await this.fetchUpdates({ - limit, - timeout, - allowed_updates - }); - if (updates === void 0) break; - await this.handleUpdates(updates); - allowed_updates = void 0; - } - } finally { - this.pollingRunning = false; - } - } - async fetchUpdates({ limit, timeout, allowed_updates }) { - const offset = this.lastTriedUpdateId + 1; - let updates = void 0; - do { - try { - updates = await this.api.getUpdates({ - offset, - limit, - timeout, - allowed_updates - }, this.pollingAbortController?.signal); - } catch (error) { - await this.handlePollingError(error); - } - } while (updates === void 0 && this.pollingRunning); - return updates; - } - async handlePollingError(error) { - if (!this.pollingRunning) { - debug2("Pending getUpdates request cancelled"); - return; - } - let sleepSeconds = 3; - if (error instanceof GrammyError) { - debugErr(error.message); - if (error.error_code === 401 || error.error_code === 409) { - throw error; - } else if (error.error_code === 429) { - debugErr("Bot API server is closing."); - sleepSeconds = error.parameters.retry_after ?? sleepSeconds; - } - } else debugErr(error); - debugErr(`Call to getUpdates failed, retrying in ${sleepSeconds} seconds ...`); - await sleep(sleepSeconds); - } -}; -async function withRetries(task, signal) { - const INITIAL_DELAY = 50; - let lastDelay = 50; - async function handleError(error) { - let delay = false; - let strategy = "rethrow"; - if (error instanceof HttpError) { - delay = true; - strategy = "retry"; - } else if (error instanceof GrammyError) { - if (error.error_code >= 500) { - delay = true; - strategy = "retry"; - } else if (error.error_code === 429) { - const retryAfter = error.parameters.retry_after; - if (typeof retryAfter === "number") { - await sleep(retryAfter, signal); - lastDelay = INITIAL_DELAY; - } else { - delay = true; - } - strategy = "retry"; - } - } - if (delay) { - if (lastDelay !== 50) { - await sleep(lastDelay, signal); - } - const TWENTY_MINUTES = 20 * 60 * 1e3; - lastDelay = Math.min(TWENTY_MINUTES, 2 * lastDelay); - } - return strategy; - } - __name(handleError, "handleError"); - let result = { - ok: false - }; - while (!result.ok) { - try { - result = { - ok: true, - value: await task() - }; - } catch (error) { - debugErr(error); - const strategy = await handleError(error); - switch (strategy) { - case "retry": - continue; - case "rethrow": - throw error; - } - } - } - return result.value; -} -__name(withRetries, "withRetries"); -async function sleep(seconds, signal) { - let handle; - let reject; - function abort() { - reject?.(new Error("Aborted delay")); - if (handle !== void 0) clearTimeout(handle); - } - __name(abort, "abort"); - try { - await new Promise((res, rej) => { - reject = rej; - if (signal?.aborted) { - abort(); - return; - } - signal?.addEventListener("abort", abort); - handle = setTimeout(res, 1e3 * seconds); - }); - } finally { - signal?.removeEventListener("abort", abort); - } -} -__name(sleep, "sleep"); -function validateAllowedUpdates(updates, allowed = DEFAULT_UPDATE_TYPES) { - const impossible = Array.from(updates).filter((u) => !allowed.includes(u)); - if (impossible.length > 0) { - debugWarn(`You registered listeners for the following update types, but you did not specify them in \`allowed_updates\` so they may not be received: ${impossible.map((u) => `'${u}'`).join(", ")}`); - } -} -__name(validateAllowedUpdates, "validateAllowedUpdates"); -function noUseFunction() { - throw new Error(`It looks like you are registering more listeners on your bot from within other listeners! This means that every time your bot handles a message like this one, new listeners will be added. This list grows until your machine crashes, so grammY throws this error to tell you that you should probably do things a bit differently. If you're unsure how to resolve this problem, you can ask in the group chat: https://telegram.me/grammyjs - -On the other hand, if you actually know what you're doing and you do need to install further middleware while your bot is running, consider installing a composer instance on your bot, and in turn augment the composer after the fact. This way, you can circumvent this protection against memory leaks.`); -} -__name(noUseFunction, "noUseFunction"); -var ALL_UPDATE_TYPES = [ - ...DEFAULT_UPDATE_TYPES, - "chat_member", - "message_reaction", - "message_reaction_count" -]; -var ALL_CHAT_PERMISSIONS = { - can_send_messages: true, - can_send_audios: true, - can_send_documents: true, - can_send_photos: true, - can_send_videos: true, - can_send_video_notes: true, - can_send_voice_notes: true, - can_send_polls: true, - can_send_other_messages: true, - can_add_web_page_previews: true, - can_change_info: true, - can_invite_users: true, - can_edit_tag: true, - can_pin_messages: true, - can_manage_topics: true -}; -var API_CONSTANTS = { - DEFAULT_UPDATE_TYPES, - ALL_UPDATE_TYPES, - ALL_CHAT_PERMISSIONS -}; -Object.freeze(API_CONSTANTS); -var InlineKeyboard = class _InlineKeyboard { - static { - __name(this, "InlineKeyboard"); - } - inline_keyboard; - constructor(inline_keyboard = [ - [] - ]) { - this.inline_keyboard = inline_keyboard; - } - add(...buttons) { - this.inline_keyboard[this.inline_keyboard.length - 1]?.push(...buttons); - return this; - } - row(...buttons) { - this.inline_keyboard.push(buttons); - return this; - } - url(text2, url) { - return this.add(_InlineKeyboard.url(text2, url)); - } - static url(text2, url) { - return typeof text2 === "string" ? { - text: text2, - url - } : { - ...text2, - url - }; - } - text(text2, data2 = typeof text2 === "string" ? text2 : text2.text) { - return this.add(_InlineKeyboard.text(text2, data2)); - } - static text(text2, data2 = typeof text2 === "string" ? text2 : text2.text) { - return typeof text2 === "string" ? { - text: text2, - callback_data: data2 - } : { - ...text2, - callback_data: data2 - }; - } - webApp(text2, url) { - return this.add(_InlineKeyboard.webApp(text2, url)); - } - static webApp(text2, url) { - const web_app = typeof url === "string" ? { - url - } : url; - return typeof text2 === "string" ? { - text: text2, - web_app - } : { - ...text2, - web_app - }; - } - login(text2, loginUrl) { - return this.add(_InlineKeyboard.login(text2, loginUrl)); - } - static login(text2, loginUrl) { - const login_url = typeof loginUrl === "string" ? { - url: loginUrl - } : loginUrl; - return typeof text2 === "string" ? { - text: text2, - login_url - } : { - ...text2, - login_url - }; - } - switchInline(text2, query = "") { - return this.add(_InlineKeyboard.switchInline(text2, query)); - } - static switchInline(text2, query = "") { - return typeof text2 === "string" ? { - text: text2, - switch_inline_query: query - } : { - ...text2, - switch_inline_query: query - }; - } - switchInlineCurrent(text2, query = "") { - return this.add(_InlineKeyboard.switchInlineCurrent(text2, query)); - } - static switchInlineCurrent(text2, query = "") { - return typeof text2 === "string" ? { - text: text2, - switch_inline_query_current_chat: query - } : { - ...text2, - switch_inline_query_current_chat: query - }; - } - switchInlineChosen(text2, query = {}) { - return this.add(_InlineKeyboard.switchInlineChosen(text2, query)); - } - static switchInlineChosen(text2, query = {}) { - return typeof text2 === "string" ? { - text: text2, - switch_inline_query_chosen_chat: query - } : { - ...text2, - switch_inline_query_chosen_chat: query - }; - } - copyText(text2, copyText) { - return this.add(_InlineKeyboard.copyText(text2, copyText)); - } - static copyText(text2, copyText) { - const copy_text = typeof copyText === "string" ? { - text: copyText - } : copyText; - return typeof text2 === "string" ? { - text: text2, - copy_text - } : { - ...text2, - copy_text - }; - } - game(text2) { - return this.add(_InlineKeyboard.game(text2)); - } - static game(text2) { - const callback_game = {}; - return typeof text2 === "string" ? { - text: text2, - callback_game - } : { - ...text2, - callback_game - }; - } - pay(text2) { - return this.add(_InlineKeyboard.pay(text2)); - } - static pay(text2) { - return typeof text2 === "string" ? { - text: text2, - pay: true - } : { - ...text2, - pay: true - }; - } - style(style) { - const rows = this.inline_keyboard.length; - if (rows === 0) { - throw new Error("Need to add a button before applying a style!"); - } - const lastRow = this.inline_keyboard[rows - 1]; - const cols = lastRow.length; - if (cols === 0) { - throw new Error("Need to add a button before applying a style!"); - } - lastRow[cols - 1].style = style; - return this; - } - danger() { - return this.style("danger"); - } - success() { - return this.style("success"); - } - primary() { - return this.style("primary"); - } - icon(icon) { - const rows = this.inline_keyboard.length; - if (rows === 0) { - throw new Error("Need to add a button before adding an icon!"); - } - const lastRow = this.inline_keyboard[rows - 1]; - const cols = lastRow.length; - if (cols === 0) { - throw new Error("Need to add a button before adding an icon!"); - } - lastRow[cols - 1].icon_custom_emoji_id = icon; - return this; - } - toTransposed() { - const original = this.inline_keyboard; - const transposed = transpose(original); - return new _InlineKeyboard(transposed); - } - toFlowed(columns, options = {}) { - const original = this.inline_keyboard; - const flowed = reflow(original, columns, options); - return new _InlineKeyboard(flowed); - } - clone() { - return new _InlineKeyboard(this.inline_keyboard.map((row) => row.slice())); - } - append(...sources) { - for (const source of sources) { - const keyboard = _InlineKeyboard.from(source); - this.inline_keyboard.push(...keyboard.inline_keyboard.map((row) => row.slice())); - } - return this; - } - static from(source) { - if (source instanceof _InlineKeyboard) return source.clone(); - return new _InlineKeyboard(source.map((row) => row.slice())); - } -}; -function transpose(grid) { - const transposed = []; - for (let i = 0; i < grid.length; i++) { - const row = grid[i]; - for (let j = 0; j < row.length; j++) { - const button = row[j]; - (transposed[j] ??= []).push(button); - } - } - return transposed; -} -__name(transpose, "transpose"); -function reflow(grid, columns, { fillLastRow = false }) { - let first = columns; - if (fillLastRow) { - const buttonCount = grid.map((row) => row.length).reduce((a, b) => a + b, 0); - first = buttonCount % columns; - } - const reflowed = []; - for (const row of grid) { - for (const button of row) { - const at = Math.max(0, reflowed.length - 1); - const max = at === 0 ? first : columns; - let next = reflowed[at] ??= []; - if (next.length === max) { - next = []; - reflowed.push(next); - } - next.push(button); - } - } - return reflowed; -} -__name(reflow, "reflow"); -var debug3 = browser$1("grammy:session"); -function session(options = {}) { - return options.type === "multi" ? strictMultiSession(options) : strictSingleSession(options); -} -__name(session, "session"); -function strictSingleSession(options) { - const { initial, storage, getSessionKey, custom } = fillDefaults(options); - return async (ctx, next) => { - const propSession = new PropertySession(storage, ctx, "session", initial); - const key = await getSessionKey(ctx); - await propSession.init(key, { - custom, - lazy: false - }); - await next(); - await propSession.finish(); - }; -} -__name(strictSingleSession, "strictSingleSession"); -function strictMultiSession(options) { - const props = Object.keys(options).filter((k) => k !== "type"); - const defaults = Object.fromEntries(props.map((prop) => [ - prop, - fillDefaults(options[prop]) - ])); - return async (ctx, next) => { - ctx.session = {}; - const propSessions = await Promise.all(props.map(async (prop) => { - const { initial, storage, getSessionKey, custom } = defaults[prop]; - const s2 = new PropertySession(storage, ctx.session, prop, initial); - const key = await getSessionKey(ctx); - await s2.init(key, { - custom, - lazy: false - }); - return s2; - })); - await next(); - if (ctx.session == null) propSessions.forEach((s2) => s2.delete()); - await Promise.all(propSessions.map((s2) => s2.finish())); - }; -} -__name(strictMultiSession, "strictMultiSession"); -var PropertySession = class { - static { - __name(this, "PropertySession"); - } - storage; - obj; - prop; - initial; - key; - value; - promise; - fetching; - read; - wrote; - constructor(storage, obj, prop, initial) { - this.storage = storage; - this.obj = obj; - this.prop = prop; - this.initial = initial; - this.fetching = false; - this.read = false; - this.wrote = false; - } - load() { - if (this.key === void 0) { - return; - } - if (this.wrote) { - return; - } - if (this.promise === void 0) { - this.fetching = true; - this.promise = Promise.resolve(this.storage.read(this.key)).then((val) => { - this.fetching = false; - if (this.wrote) { - return this.value; - } - if (val !== void 0) { - this.value = val; - return val; - } - val = this.initial?.(); - if (val !== void 0) { - this.wrote = true; - this.value = val; - } - return val; - }); - } - return this.promise; - } - async init(key, opts) { - this.key = key; - if (!opts.lazy) await this.load(); - Object.defineProperty(this.obj, this.prop, { - enumerable: true, - get: /* @__PURE__ */ __name(() => { - if (key === void 0) { - const msg = undef("access", opts); - throw new Error(msg); - } - this.read = true; - if (!opts.lazy || this.wrote) return this.value; - this.load(); - return this.fetching ? this.promise : this.value; - }, "get"), - set: /* @__PURE__ */ __name((v) => { - if (key === void 0) { - const msg = undef("assign", opts); - throw new Error(msg); - } - this.wrote = true; - this.fetching = false; - this.value = v; - }, "set") - }); - } - delete() { - Object.assign(this.obj, { - [this.prop]: void 0 - }); - } - async finish() { - if (this.key !== void 0) { - if (this.read) await this.load(); - if (this.read || this.wrote) { - const value = await this.value; - if (value == null) await this.storage.delete(this.key); - else await this.storage.write(this.key, value); - } - } - } -}; -function fillDefaults(opts = {}) { - let { prefix = "", getSessionKey = defaultGetSessionKey, initial, storage } = opts; - if (storage == null) { - debug3("Storing session data in memory, all data will be lost when the bot restarts."); - storage = new MemorySessionStorage(); - } - const custom = getSessionKey !== defaultGetSessionKey; - return { - initial, - storage, - getSessionKey: /* @__PURE__ */ __name(async (ctx) => { - const key = await getSessionKey(ctx); - return key === void 0 ? void 0 : prefix + key; - }, "getSessionKey"), - custom - }; -} -__name(fillDefaults, "fillDefaults"); -function defaultGetSessionKey(ctx) { - return ctx.chatId?.toString(); -} -__name(defaultGetSessionKey, "defaultGetSessionKey"); -function undef(op, opts) { - const { lazy = false, custom } = opts; - const reason = custom ? "the custom `getSessionKey` function returned undefined for this update" : "this update does not belong to a chat, so the session key is undefined"; - return `Cannot ${op} ${lazy ? "lazy " : ""}session data because ${reason}!`; -} -__name(undef, "undef"); -var MemorySessionStorage = class { - static { - __name(this, "MemorySessionStorage"); - } - timeToLive; - storage; - constructor(timeToLive) { - this.timeToLive = timeToLive; - this.storage = /* @__PURE__ */ new Map(); - } - read(key) { - const value = this.storage.get(key); - if (value === void 0) return void 0; - if (value.expires !== void 0 && value.expires < Date.now()) { - this.delete(key); - return void 0; - } - return value.session; - } - readAll() { - return this.readAllValues(); - } - readAllKeys() { - return Array.from(this.storage.keys()); - } - readAllValues() { - return Array.from(this.storage.keys()).map((key) => this.read(key)).filter((value) => value !== void 0); - } - readAllEntries() { - return Array.from(this.storage.keys()).map((key) => [ - key, - this.read(key) - ]).filter((pair) => pair[1] !== void 0); - } - has(key) { - return this.storage.has(key); - } - write(key, value) { - this.storage.set(key, addExpiryDate(value, this.timeToLive)); - } - delete(key) { - this.storage.delete(key); - } -}; -function addExpiryDate(value, ttl) { - if (ttl !== void 0 && ttl < Infinity) { - const now = Date.now(); - return { - session: value, - expires: now + ttl - }; - } else { - return { - session: value - }; - } -} -__name(addExpiryDate, "addExpiryDate"); -var SECRET_HEADER = "X-Telegram-Bot-Api-Secret-Token"; -var SECRET_HEADER_LOWERCASE = SECRET_HEADER.toLowerCase(); -var WRONG_TOKEN_ERROR = "secret token is wrong"; -var ok = /* @__PURE__ */ __name(() => new Response(null, { - status: 200 -}), "ok"); -var okJson = /* @__PURE__ */ __name((json) => new Response(json, { - status: 200, - headers: { - "Content-Type": "application/json" - } -}), "okJson"); -var unauthorized = /* @__PURE__ */ __name(() => new Response('"unauthorized"', { - status: 401, - statusText: WRONG_TOKEN_ERROR -}), "unauthorized"); -var awsLambda = /* @__PURE__ */ __name((event, _context, callback) => ({ - get update() { - return JSON.parse(event.body ?? "{}"); - }, - header: event.headers[SECRET_HEADER], - end: /* @__PURE__ */ __name(() => callback(null, { - statusCode: 200 - }), "end"), - respond: /* @__PURE__ */ __name((json) => callback(null, { - statusCode: 200, - headers: { - "Content-Type": "application/json" - }, - body: json - }), "respond"), - unauthorized: /* @__PURE__ */ __name(() => callback(null, { - statusCode: 401 - }), "unauthorized") -}), "awsLambda"); -var awsLambdaAsync = /* @__PURE__ */ __name((event, _context) => { - let resolveResponse; - return { - get update() { - return JSON.parse(event.body ?? "{}"); - }, - header: event.headers[SECRET_HEADER], - end: /* @__PURE__ */ __name(() => resolveResponse({ - statusCode: 200 - }), "end"), - respond: /* @__PURE__ */ __name((json) => resolveResponse({ - statusCode: 200, - headers: { - "Content-Type": "application/json" - }, - body: json - }), "respond"), - unauthorized: /* @__PURE__ */ __name(() => resolveResponse({ - statusCode: 401 - }), "unauthorized"), - handlerReturn: new Promise((res) => resolveResponse = res) - }; -}, "awsLambdaAsync"); -var azure = /* @__PURE__ */ __name((context, request) => ({ - get update() { - return request.body; - }, - header: context.res?.headers?.[SECRET_HEADER], - end: /* @__PURE__ */ __name(() => context.res = { - status: 200, - body: "" - }, "end"), - respond: /* @__PURE__ */ __name((json) => { - context.res?.set?.("Content-Type", "application/json"); - context.res?.send?.(json); - }, "respond"), - unauthorized: /* @__PURE__ */ __name(() => { - context.res?.send?.(401, WRONG_TOKEN_ERROR); - }, "unauthorized") -}), "azure"); -var azureV4 = /* @__PURE__ */ __name((request) => { - let resolveResponse; - return { - get update() { - return request.json(); - }, - header: request.headers.get(SECRET_HEADER) || void 0, - end: /* @__PURE__ */ __name(() => resolveResponse({ - status: 204 - }), "end"), - respond: /* @__PURE__ */ __name((json) => resolveResponse({ - jsonBody: json - }), "respond"), - unauthorized: /* @__PURE__ */ __name(() => resolveResponse({ - status: 401, - body: WRONG_TOKEN_ERROR - }), "unauthorized"), - handlerReturn: new Promise((resolve) => resolveResponse = resolve) - }; -}, "azureV4"); -var bun = /* @__PURE__ */ __name((request) => { - let resolveResponse; - return { - get update() { - return request.json(); - }, - header: request.headers.get(SECRET_HEADER) || void 0, - end: /* @__PURE__ */ __name(() => { - resolveResponse(ok()); - }, "end"), - respond: /* @__PURE__ */ __name((json) => { - resolveResponse(okJson(json)); - }, "respond"), - unauthorized: /* @__PURE__ */ __name(() => { - resolveResponse(unauthorized()); - }, "unauthorized"), - handlerReturn: new Promise((res) => resolveResponse = res) - }; -}, "bun"); -var cloudflare = /* @__PURE__ */ __name((event) => { - let resolveResponse; - event.respondWith(new Promise((resolve) => { - resolveResponse = resolve; - })); - return { - get update() { - return event.request.json(); - }, - header: event.request.headers.get(SECRET_HEADER) || void 0, - end: /* @__PURE__ */ __name(() => { - resolveResponse(ok()); - }, "end"), - respond: /* @__PURE__ */ __name((json) => { - resolveResponse(okJson(json)); - }, "respond"), - unauthorized: /* @__PURE__ */ __name(() => { - resolveResponse(unauthorized()); - }, "unauthorized") - }; -}, "cloudflare"); -var cloudflareModule = /* @__PURE__ */ __name((request) => { - let resolveResponse; - return { - get update() { - return request.json(); - }, - header: request.headers.get(SECRET_HEADER) || void 0, - end: /* @__PURE__ */ __name(() => { - resolveResponse(ok()); - }, "end"), - respond: /* @__PURE__ */ __name((json) => { - resolveResponse(okJson(json)); - }, "respond"), - unauthorized: /* @__PURE__ */ __name(() => { - resolveResponse(unauthorized()); - }, "unauthorized"), - handlerReturn: new Promise((res) => resolveResponse = res) - }; -}, "cloudflareModule"); -var express = /* @__PURE__ */ __name((req, res) => ({ - get update() { - return req.body; - }, - header: req.header(SECRET_HEADER), - end: /* @__PURE__ */ __name(() => res.end(), "end"), - respond: /* @__PURE__ */ __name((json) => { - res.set("Content-Type", "application/json"); - res.send(json); - }, "respond"), - unauthorized: /* @__PURE__ */ __name(() => { - res.status(401).send(WRONG_TOKEN_ERROR); - }, "unauthorized") -}), "express"); -var fastify = /* @__PURE__ */ __name((request, reply) => ({ - get update() { - return request.body; - }, - header: request.headers[SECRET_HEADER_LOWERCASE], - end: /* @__PURE__ */ __name(() => reply.send(""), "end"), - respond: /* @__PURE__ */ __name((json) => reply.headers({ - "Content-Type": "application/json" - }).send(json), "respond"), - unauthorized: /* @__PURE__ */ __name(() => reply.code(401).send(WRONG_TOKEN_ERROR), "unauthorized") -}), "fastify"); -var hono = /* @__PURE__ */ __name((c) => { - let resolveResponse; - return { - get update() { - return c.req.json(); - }, - header: c.req.header(SECRET_HEADER), - end: /* @__PURE__ */ __name(() => { - resolveResponse(c.body("")); - }, "end"), - respond: /* @__PURE__ */ __name((json) => { - resolveResponse(c.json(json)); - }, "respond"), - unauthorized: /* @__PURE__ */ __name(() => { - c.status(401); - resolveResponse(c.body("")); - }, "unauthorized"), - handlerReturn: new Promise((res) => resolveResponse = res) - }; -}, "hono"); -var http = /* @__PURE__ */ __name((req, res) => { - const secretHeaderFromRequest = req.headers[SECRET_HEADER_LOWERCASE]; - return { - get update() { - return new Promise((resolve, reject) => { - const chunks = []; - req.on("data", (chunk) => chunks.push(chunk)).once("end", () => { - const raw2 = Buffer.concat(chunks).toString("utf-8"); - try { - resolve(JSON.parse(raw2)); - } catch (err) { - reject(err); - } - }).once("error", reject); - }); - }, - header: Array.isArray(secretHeaderFromRequest) ? secretHeaderFromRequest[0] : secretHeaderFromRequest, - end: /* @__PURE__ */ __name(() => res.end(), "end"), - respond: /* @__PURE__ */ __name((json) => res.writeHead(200, { - "Content-Type": "application/json" - }).end(json), "respond"), - unauthorized: /* @__PURE__ */ __name(() => res.writeHead(401).end(WRONG_TOKEN_ERROR), "unauthorized") - }; -}, "http"); -var koa = /* @__PURE__ */ __name((ctx) => ({ - get update() { - return ctx.request.body; - }, - header: ctx.get(SECRET_HEADER) || void 0, - end: /* @__PURE__ */ __name(() => { - ctx.body = ""; - }, "end"), - respond: /* @__PURE__ */ __name((json) => { - ctx.set("Content-Type", "application/json"); - ctx.response.body = json; - }, "respond"), - unauthorized: /* @__PURE__ */ __name(() => { - ctx.status = 401; - }, "unauthorized") -}), "koa"); -var nextJs = /* @__PURE__ */ __name((request, response) => ({ - get update() { - return request.body; - }, - header: request.headers[SECRET_HEADER_LOWERCASE], - end: /* @__PURE__ */ __name(() => response.end(), "end"), - respond: /* @__PURE__ */ __name((json) => response.status(200).json(json), "respond"), - unauthorized: /* @__PURE__ */ __name(() => response.status(401).send(WRONG_TOKEN_ERROR), "unauthorized") -}), "nextJs"); -var nhttp = /* @__PURE__ */ __name((rev) => ({ - get update() { - return rev.body; - }, - header: rev.headers.get(SECRET_HEADER) || void 0, - end: /* @__PURE__ */ __name(() => rev.response.sendStatus(200), "end"), - respond: /* @__PURE__ */ __name((json) => rev.response.status(200).send(json), "respond"), - unauthorized: /* @__PURE__ */ __name(() => rev.response.status(401).send(WRONG_TOKEN_ERROR), "unauthorized") -}), "nhttp"); -var oak = /* @__PURE__ */ __name((ctx) => ({ - get update() { - return ctx.request.body.json(); - }, - header: ctx.request.headers.get(SECRET_HEADER) || void 0, - end: /* @__PURE__ */ __name(() => { - ctx.response.status = 200; - }, "end"), - respond: /* @__PURE__ */ __name((json) => { - ctx.response.type = "json"; - ctx.response.body = json; - }, "respond"), - unauthorized: /* @__PURE__ */ __name(() => { - ctx.response.status = 401; - }, "unauthorized") -}), "oak"); -var serveHttp = /* @__PURE__ */ __name((requestEvent) => ({ - get update() { - return requestEvent.request.json(); - }, - header: requestEvent.request.headers.get(SECRET_HEADER) || void 0, - end: /* @__PURE__ */ __name(() => requestEvent.respondWith(ok()), "end"), - respond: /* @__PURE__ */ __name((json) => requestEvent.respondWith(okJson(json)), "respond"), - unauthorized: /* @__PURE__ */ __name(() => requestEvent.respondWith(unauthorized()), "unauthorized") -}), "serveHttp"); -var stdHttp = /* @__PURE__ */ __name((req) => { - let resolveResponse; - return { - get update() { - return req.json(); - }, - header: req.headers.get(SECRET_HEADER) || void 0, - end: /* @__PURE__ */ __name(() => { - if (resolveResponse) resolveResponse(ok()); - }, "end"), - respond: /* @__PURE__ */ __name((json) => { - if (resolveResponse) resolveResponse(okJson(json)); - }, "respond"), - unauthorized: /* @__PURE__ */ __name(() => { - if (resolveResponse) resolveResponse(unauthorized()); - }, "unauthorized"), - handlerReturn: new Promise((res) => resolveResponse = res) - }; -}, "stdHttp"); -var sveltekit = /* @__PURE__ */ __name(({ request }) => { - let resolveResponse; - return { - get update() { - return request.json(); - }, - header: request.headers.get(SECRET_HEADER) || void 0, - end: /* @__PURE__ */ __name(() => { - if (resolveResponse) resolveResponse(ok()); - }, "end"), - respond: /* @__PURE__ */ __name((json) => { - if (resolveResponse) resolveResponse(okJson(json)); - }, "respond"), - unauthorized: /* @__PURE__ */ __name(() => { - if (resolveResponse) resolveResponse(unauthorized()); - }, "unauthorized"), - handlerReturn: new Promise((res) => resolveResponse = res) - }; -}, "sveltekit"); -var worktop = /* @__PURE__ */ __name((req, res) => ({ - get update() { - return req.json(); - }, - header: req.headers.get(SECRET_HEADER) ?? void 0, - end: /* @__PURE__ */ __name(() => res.end(null), "end"), - respond: /* @__PURE__ */ __name((json) => res.send(200, json), "respond"), - unauthorized: /* @__PURE__ */ __name(() => res.send(401, WRONG_TOKEN_ERROR), "unauthorized") -}), "worktop"); -var elysia = /* @__PURE__ */ __name((ctx) => { - let resolveResponse; - return { - get update() { - return ctx.body; - }, - header: ctx.headers[SECRET_HEADER_LOWERCASE], - end() { - resolveResponse(""); - }, - respond(json) { - ctx.set.headers["content-type"] = "application/json"; - resolveResponse(json); - }, - unauthorized() { - ctx.set.status = 401; - resolveResponse(""); - }, - handlerReturn: new Promise((res) => resolveResponse = res) - }; -}, "elysia"); -var adapters = { - "aws-lambda": awsLambda, - "aws-lambda-async": awsLambdaAsync, - azure, - "azure-v4": azureV4, - bun, - cloudflare, - "cloudflare-mod": cloudflareModule, - elysia, - express, - fastify, - hono, - http, - https: http, - koa, - "next-js": nextJs, - nhttp, - oak, - serveHttp, - "std/http": stdHttp, - sveltekit, - worktop -}; -var debugErr1 = browser$1("grammy:error"); -var callbackAdapter = /* @__PURE__ */ __name((update, callback, header, unauthorized2 = () => callback('"unauthorized"')) => ({ - update: Promise.resolve(update), - respond: callback, - header, - unauthorized: unauthorized2 -}), "callbackAdapter"); -var adapters1 = { - ...adapters, - callback: callbackAdapter -}; -function compareSecretToken(header, token) { - if (token === void 0) { - return true; - } - if (header === void 0) { - return false; - } - const encoder = new TextEncoder(); - const headerBytes = encoder.encode(header); - const tokenBytes = encoder.encode(token); - if (headerBytes.length !== tokenBytes.length) { - return false; - } - let hasDifference = 0; - for (let i = 0; i < tokenBytes.length; i++) { - const headerByte = i < headerBytes.length ? headerBytes[i] : 0; - const tokenByte = tokenBytes[i]; - hasDifference |= headerByte ^ tokenByte; - } - return hasDifference === 0; -} -__name(compareSecretToken, "compareSecretToken"); -function webhookCallback(bot, adapter = defaultAdapter, onTimeout, timeoutMilliseconds, secretToken) { - if (bot.isRunning()) { - throw new Error("Bot is already running via long polling, the webhook setup won't receive any updates!"); - } else { - bot.start = () => { - throw new Error("You already started the bot via webhooks, calling `bot.start()` starts the bot with long polling and this will prevent your webhook setup from receiving any updates!"); - }; - } - const { onTimeout: timeout = "throw", timeoutMilliseconds: ms2 = 1e4, secretToken: token } = typeof onTimeout === "object" ? onTimeout : { - onTimeout, - timeoutMilliseconds, - secretToken - }; - let initialized = false; - const server = typeof adapter === "string" ? adapters1[adapter] : adapter; - return async (...args) => { - const handler = server(...args); - if (!initialized) { - await bot.init(); - initialized = true; - } - if (!compareSecretToken(handler.header, token)) { - await handler.unauthorized(); - return handler.handlerReturn; - } - let usedWebhookReply = false; - const webhookReplyEnvelope = { - async send(json) { - usedWebhookReply = true; - await handler.respond(json); - } - }; - await timeoutIfNecessary(bot.handleUpdate(await handler.update, webhookReplyEnvelope), typeof timeout === "function" ? () => timeout(...args) : timeout, ms2); - if (!usedWebhookReply) handler.end?.(); - return handler.handlerReturn; - }; -} -__name(webhookCallback, "webhookCallback"); -function timeoutIfNecessary(task, onTimeout, timeout) { - if (timeout === Infinity) return task; - return new Promise((resolve, reject) => { - const handle = setTimeout(() => { - debugErr1(`Request timed out after ${timeout} ms`); - if (onTimeout === "throw") { - reject(new Error(`Request timed out after ${timeout} ms`)); - } else { - if (typeof onTimeout === "function") onTimeout(); - resolve(); - } - const now = Date.now(); - task.finally(() => { - const diff = Date.now() - now; - debugErr1(`Request completed ${diff} ms after timeout!`); - }); - }, timeout); - task.then(resolve).catch(reject).finally(() => clearTimeout(handle)); - }); -} -__name(timeoutIfNecessary, "timeoutIfNecessary"); - -// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/d1/driver.js -init_modules_watch_stub(); -init_performance2(); - -// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/entity.js -init_modules_watch_stub(); -init_performance2(); -var entityKind = /* @__PURE__ */ Symbol.for("drizzle:entityKind"); -function is(value, type) { - if (!value || typeof value !== "object") { - return false; - } - if (value instanceof type) { - return true; - } - if (!Object.prototype.hasOwnProperty.call(type, entityKind)) { - throw new Error( - `Class "${type.name ?? ""}" doesn't look like a Drizzle entity. If this is incorrect and the class is provided by Drizzle, please report this as a bug.` - ); - } - let cls = Object.getPrototypeOf(value).constructor; - if (cls) { - while (cls) { - if (entityKind in cls && cls[entityKind] === type[entityKind]) { - return true; - } - cls = Object.getPrototypeOf(cls); - } - } - return false; -} -__name(is, "is"); - -// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/logger.js -init_modules_watch_stub(); -init_performance2(); -var ConsoleLogWriter = class { - static { - __name(this, "ConsoleLogWriter"); - } - static [entityKind] = "ConsoleLogWriter"; - write(message) { - console.log(message); - } -}; -var DefaultLogger = class { - static { - __name(this, "DefaultLogger"); - } - static [entityKind] = "DefaultLogger"; - writer; - constructor(config2) { - this.writer = config2?.writer ?? new ConsoleLogWriter(); - } - logQuery(query, params) { - const stringifiedParams = params.map((p) => { - try { - return JSON.stringify(p); - } catch { - return String(p); - } - }); - const paramsStr = stringifiedParams.length ? ` -- params: [${stringifiedParams.join(", ")}]` : ""; - this.writer.write(`Query: ${query}${paramsStr}`); - } -}; -var NoopLogger = class { - static { - __name(this, "NoopLogger"); - } - static [entityKind] = "NoopLogger"; - logQuery() { - } -}; - -// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/relations.js -init_modules_watch_stub(); -init_performance2(); - -// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/table.js -init_modules_watch_stub(); -init_performance2(); - -// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/table.utils.js -init_modules_watch_stub(); -init_performance2(); -var TableName = /* @__PURE__ */ Symbol.for("drizzle:Name"); - -// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/table.js -var Schema = /* @__PURE__ */ Symbol.for("drizzle:Schema"); -var Columns = /* @__PURE__ */ Symbol.for("drizzle:Columns"); -var ExtraConfigColumns = /* @__PURE__ */ Symbol.for("drizzle:ExtraConfigColumns"); -var OriginalName = /* @__PURE__ */ Symbol.for("drizzle:OriginalName"); -var BaseName = /* @__PURE__ */ Symbol.for("drizzle:BaseName"); -var IsAlias = /* @__PURE__ */ Symbol.for("drizzle:IsAlias"); -var ExtraConfigBuilder = /* @__PURE__ */ Symbol.for("drizzle:ExtraConfigBuilder"); -var IsDrizzleTable = /* @__PURE__ */ Symbol.for("drizzle:IsDrizzleTable"); -var Table = class { - static { - __name(this, "Table"); - } - static [entityKind] = "Table"; - /** @internal */ - static Symbol = { - Name: TableName, - Schema, - OriginalName, - Columns, - ExtraConfigColumns, - BaseName, - IsAlias, - ExtraConfigBuilder - }; - /** - * @internal - * Can be changed if the table is aliased. - */ - [TableName]; - /** - * @internal - * Used to store the original name of the table, before any aliasing. - */ - [OriginalName]; - /** @internal */ - [Schema]; - /** @internal */ - [Columns]; - /** @internal */ - [ExtraConfigColumns]; - /** - * @internal - * Used to store the table name before the transformation via the `tableCreator` functions. - */ - [BaseName]; - /** @internal */ - [IsAlias] = false; - /** @internal */ - [IsDrizzleTable] = true; - /** @internal */ - [ExtraConfigBuilder] = void 0; - constructor(name, schema, baseName) { - this[TableName] = this[OriginalName] = name; - this[Schema] = schema; - this[BaseName] = baseName; - } -}; -function getTableName(table) { - return table[TableName]; -} -__name(getTableName, "getTableName"); -function getTableUniqueName(table) { - return `${table[Schema] ?? "public"}.${table[TableName]}`; -} -__name(getTableUniqueName, "getTableUniqueName"); - -// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/column.js -init_modules_watch_stub(); -init_performance2(); -var Column = class { - static { - __name(this, "Column"); - } - constructor(table, config2) { - this.table = table; - this.config = config2; - this.name = config2.name; - this.keyAsName = config2.keyAsName; - this.notNull = config2.notNull; - this.default = config2.default; - this.defaultFn = config2.defaultFn; - this.onUpdateFn = config2.onUpdateFn; - this.hasDefault = config2.hasDefault; - this.primary = config2.primaryKey; - this.isUnique = config2.isUnique; - this.uniqueName = config2.uniqueName; - this.uniqueType = config2.uniqueType; - this.dataType = config2.dataType; - this.columnType = config2.columnType; - this.generated = config2.generated; - this.generatedIdentity = config2.generatedIdentity; - } - static [entityKind] = "Column"; - name; - keyAsName; - primary; - notNull; - default; - defaultFn; - onUpdateFn; - hasDefault; - isUnique; - uniqueName; - uniqueType; - dataType; - columnType; - enumValues = void 0; - generated = void 0; - generatedIdentity = void 0; - config; - mapFromDriverValue(value) { - return value; - } - mapToDriverValue(value) { - return value; - } - // ** @internal */ - shouldDisableInsert() { - return this.config.generated !== void 0 && this.config.generated.type !== "byDefault"; - } -}; - -// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/pg-core/primary-keys.js -init_modules_watch_stub(); -init_performance2(); - -// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/pg-core/table.js -init_modules_watch_stub(); -init_performance2(); - -// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/utils.js -init_modules_watch_stub(); -init_performance2(); - -// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/sql/sql.js -init_modules_watch_stub(); -init_performance2(); - -// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/pg-core/columns/enum.js -init_modules_watch_stub(); -init_performance2(); - -// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/pg-core/columns/common.js -init_modules_watch_stub(); -init_performance2(); - -// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/column-builder.js -init_modules_watch_stub(); -init_performance2(); -var ColumnBuilder = class { - static { - __name(this, "ColumnBuilder"); - } - static [entityKind] = "ColumnBuilder"; - config; - constructor(name, dataType, columnType) { - this.config = { - name, - keyAsName: name === "", - notNull: false, - default: void 0, - hasDefault: false, - primaryKey: false, - isUnique: false, - uniqueName: void 0, - uniqueType: void 0, - dataType, - columnType, - generated: void 0 - }; - } - /** - * Changes the data type of the column. Commonly used with `json` columns. Also, useful for branded types. - * - * @example - * ```ts - * const users = pgTable('users', { - * id: integer('id').$type().primaryKey(), - * details: json('details').$type().notNull(), - * }); - * ``` - */ - $type() { - return this; - } - /** - * Adds a `not null` clause to the column definition. - * - * Affects the `select` model of the table - columns *without* `not null` will be nullable on select. - */ - notNull() { - this.config.notNull = true; - return this; - } - /** - * Adds a `default ` clause to the column definition. - * - * Affects the `insert` model of the table - columns *with* `default` are optional on insert. - * - * If you need to set a dynamic default value, use {@link $defaultFn} instead. - */ - default(value) { - this.config.default = value; - this.config.hasDefault = true; - return this; - } - /** - * Adds a dynamic default value to the column. - * The function will be called when the row is inserted, and the returned value will be used as the column value. - * - * **Note:** This value does not affect the `drizzle-kit` behavior, it is only used at runtime in `drizzle-orm`. - */ - $defaultFn(fn) { - this.config.defaultFn = fn; - this.config.hasDefault = true; - return this; - } - /** - * Alias for {@link $defaultFn}. - */ - $default = this.$defaultFn; - /** - * Adds a dynamic update value to the column. - * The function will be called when the row is updated, and the returned value will be used as the column value if none is provided. - * If no `default` (or `$defaultFn`) value is provided, the function will be called when the row is inserted as well, and the returned value will be used as the column value. - * - * **Note:** This value does not affect the `drizzle-kit` behavior, it is only used at runtime in `drizzle-orm`. - */ - $onUpdateFn(fn) { - this.config.onUpdateFn = fn; - this.config.hasDefault = true; - return this; - } - /** - * Alias for {@link $onUpdateFn}. - */ - $onUpdate = this.$onUpdateFn; - /** - * Adds a `primary key` clause to the column definition. This implicitly makes the column `not null`. - * - * In SQLite, `integer primary key` implicitly makes the column auto-incrementing. - */ - primaryKey() { - this.config.primaryKey = true; - this.config.notNull = true; - return this; - } - /** @internal Sets the name of the column to the key within the table definition if a name was not given. */ - setName(name) { - if (this.config.name !== "") return; - this.config.name = name; - } -}; - -// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/pg-core/foreign-keys.js -init_modules_watch_stub(); -init_performance2(); -var ForeignKeyBuilder = class { - static { - __name(this, "ForeignKeyBuilder"); - } - static [entityKind] = "PgForeignKeyBuilder"; - /** @internal */ - reference; - /** @internal */ - _onUpdate = "no action"; - /** @internal */ - _onDelete = "no action"; - constructor(config2, actions) { - this.reference = () => { - const { name, columns, foreignColumns } = config2(); - return { name, columns, foreignTable: foreignColumns[0].table, foreignColumns }; - }; - if (actions) { - this._onUpdate = actions.onUpdate; - this._onDelete = actions.onDelete; - } - } - onUpdate(action) { - this._onUpdate = action === void 0 ? "no action" : action; - return this; - } - onDelete(action) { - this._onDelete = action === void 0 ? "no action" : action; - return this; - } - /** @internal */ - build(table) { - return new ForeignKey(table, this); - } -}; -var ForeignKey = class { - static { - __name(this, "ForeignKey"); - } - constructor(table, builder) { - this.table = table; - this.reference = builder.reference; - this.onUpdate = builder._onUpdate; - this.onDelete = builder._onDelete; - } - static [entityKind] = "PgForeignKey"; - reference; - onUpdate; - onDelete; - getName() { - const { name, columns, foreignColumns } = this.reference(); - const columnNames = columns.map((column) => column.name); - const foreignColumnNames = foreignColumns.map((column) => column.name); - const chunks = [ - this.table[TableName], - ...columnNames, - foreignColumns[0].table[TableName], - ...foreignColumnNames - ]; - return name ?? `${chunks.join("_")}_fk`; - } -}; - -// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/tracing-utils.js -init_modules_watch_stub(); -init_performance2(); -function iife(fn, ...args) { - return fn(...args); -} -__name(iife, "iife"); - -// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/pg-core/unique-constraint.js -init_modules_watch_stub(); -init_performance2(); -function uniqueKeyName(table, columns) { - return `${table[TableName]}_${columns.join("_")}_unique`; -} -__name(uniqueKeyName, "uniqueKeyName"); -var UniqueConstraintBuilder = class { - static { - __name(this, "UniqueConstraintBuilder"); - } - constructor(columns, name) { - this.name = name; - this.columns = columns; - } - static [entityKind] = "PgUniqueConstraintBuilder"; - /** @internal */ - columns; - /** @internal */ - nullsNotDistinctConfig = false; - nullsNotDistinct() { - this.nullsNotDistinctConfig = true; - return this; - } - /** @internal */ - build(table) { - return new UniqueConstraint(table, this.columns, this.nullsNotDistinctConfig, this.name); - } -}; -var UniqueOnConstraintBuilder = class { - static { - __name(this, "UniqueOnConstraintBuilder"); - } - static [entityKind] = "PgUniqueOnConstraintBuilder"; - /** @internal */ - name; - constructor(name) { - this.name = name; - } - on(...columns) { - return new UniqueConstraintBuilder(columns, this.name); - } -}; -var UniqueConstraint = class { - static { - __name(this, "UniqueConstraint"); - } - constructor(table, columns, nullsNotDistinct, name) { - this.table = table; - this.columns = columns; - this.name = name ?? uniqueKeyName(this.table, this.columns.map((column) => column.name)); - this.nullsNotDistinct = nullsNotDistinct; - } - static [entityKind] = "PgUniqueConstraint"; - columns; - name; - nullsNotDistinct = false; - getName() { - return this.name; - } -}; - -// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/pg-core/utils/array.js -init_modules_watch_stub(); -init_performance2(); -function parsePgArrayValue(arrayString, startFrom, inQuotes) { - for (let i = startFrom; i < arrayString.length; i++) { - const char = arrayString[i]; - if (char === "\\") { - i++; - continue; - } - if (char === '"') { - return [arrayString.slice(startFrom, i).replace(/\\/g, ""), i + 1]; - } - if (inQuotes) { - continue; - } - if (char === "," || char === "}") { - return [arrayString.slice(startFrom, i).replace(/\\/g, ""), i]; - } - } - return [arrayString.slice(startFrom).replace(/\\/g, ""), arrayString.length]; -} -__name(parsePgArrayValue, "parsePgArrayValue"); -function parsePgNestedArray(arrayString, startFrom = 0) { - const result = []; - let i = startFrom; - let lastCharIsComma = false; - while (i < arrayString.length) { - const char = arrayString[i]; - if (char === ",") { - if (lastCharIsComma || i === startFrom) { - result.push(""); - } - lastCharIsComma = true; - i++; - continue; - } - lastCharIsComma = false; - if (char === "\\") { - i += 2; - continue; - } - if (char === '"') { - const [value2, startFrom2] = parsePgArrayValue(arrayString, i + 1, true); - result.push(value2); - i = startFrom2; - continue; - } - if (char === "}") { - return [result, i + 1]; - } - if (char === "{") { - const [value2, startFrom2] = parsePgNestedArray(arrayString, i + 1); - result.push(value2); - i = startFrom2; - continue; - } - const [value, newStartFrom] = parsePgArrayValue(arrayString, i, false); - result.push(value); - i = newStartFrom; - } - return [result, i]; -} -__name(parsePgNestedArray, "parsePgNestedArray"); -function parsePgArray(arrayString) { - const [result] = parsePgNestedArray(arrayString, 1); - return result; -} -__name(parsePgArray, "parsePgArray"); -function makePgArray(array) { - return `{${array.map((item) => { - if (Array.isArray(item)) { - return makePgArray(item); - } - if (typeof item === "string") { - return `"${item.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`; - } - return `${item}`; - }).join(",")}}`; -} -__name(makePgArray, "makePgArray"); - -// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/pg-core/columns/common.js -var PgColumnBuilder = class extends ColumnBuilder { - static { - __name(this, "PgColumnBuilder"); - } - foreignKeyConfigs = []; - static [entityKind] = "PgColumnBuilder"; - array(size) { - return new PgArrayBuilder(this.config.name, this, size); - } - references(ref, actions = {}) { - this.foreignKeyConfigs.push({ ref, actions }); - return this; - } - unique(name, config2) { - this.config.isUnique = true; - this.config.uniqueName = name; - this.config.uniqueType = config2?.nulls; - return this; - } - generatedAlwaysAs(as) { - this.config.generated = { - as, - type: "always", - mode: "stored" - }; - return this; - } - /** @internal */ - buildForeignKeys(column, table) { - return this.foreignKeyConfigs.map(({ ref, actions }) => { - return iife( - (ref2, actions2) => { - const builder = new ForeignKeyBuilder(() => { - const foreignColumn = ref2(); - return { columns: [column], foreignColumns: [foreignColumn] }; - }); - if (actions2.onUpdate) { - builder.onUpdate(actions2.onUpdate); - } - if (actions2.onDelete) { - builder.onDelete(actions2.onDelete); - } - return builder.build(table); - }, - ref, - actions - ); - }); - } - /** @internal */ - buildExtraConfigColumn(table) { - return new ExtraConfigColumn(table, this.config); - } -}; -var PgColumn = class extends Column { - static { - __name(this, "PgColumn"); - } - constructor(table, config2) { - if (!config2.uniqueName) { - config2.uniqueName = uniqueKeyName(table, [config2.name]); - } - super(table, config2); - this.table = table; - } - static [entityKind] = "PgColumn"; -}; -var ExtraConfigColumn = class extends PgColumn { - static { - __name(this, "ExtraConfigColumn"); - } - static [entityKind] = "ExtraConfigColumn"; - getSQLType() { - return this.getSQLType(); - } - indexConfig = { - order: this.config.order ?? "asc", - nulls: this.config.nulls ?? "last", - opClass: this.config.opClass - }; - defaultConfig = { - order: "asc", - nulls: "last", - opClass: void 0 - }; - asc() { - this.indexConfig.order = "asc"; - return this; - } - desc() { - this.indexConfig.order = "desc"; - return this; - } - nullsFirst() { - this.indexConfig.nulls = "first"; - return this; - } - nullsLast() { - this.indexConfig.nulls = "last"; - return this; - } - /** - * ### PostgreSQL documentation quote - * - * > An operator class with optional parameters can be specified for each column of an index. - * The operator class identifies the operators to be used by the index for that column. - * For example, a B-tree index on four-byte integers would use the int4_ops class; - * this operator class includes comparison functions for four-byte integers. - * In practice the default operator class for the column's data type is usually sufficient. - * The main point of having operator classes is that for some data types, there could be more than one meaningful ordering. - * For example, we might want to sort a complex-number data type either by absolute value or by real part. - * We could do this by defining two operator classes for the data type and then selecting the proper class when creating an index. - * More information about operator classes check: - * - * ### Useful links - * https://www.postgresql.org/docs/current/sql-createindex.html - * - * https://www.postgresql.org/docs/current/indexes-opclass.html - * - * https://www.postgresql.org/docs/current/xindex.html - * - * ### Additional types - * If you have the `pg_vector` extension installed in your database, you can use the - * `vector_l2_ops`, `vector_ip_ops`, `vector_cosine_ops`, `vector_l1_ops`, `bit_hamming_ops`, `bit_jaccard_ops`, `halfvec_l2_ops`, `sparsevec_l2_ops` options, which are predefined types. - * - * **You can always specify any string you want in the operator class, in case Drizzle doesn't have it natively in its types** - * - * @param opClass - * @returns - */ - op(opClass) { - this.indexConfig.opClass = opClass; - return this; - } -}; -var IndexedColumn = class { - static { - __name(this, "IndexedColumn"); - } - static [entityKind] = "IndexedColumn"; - constructor(name, keyAsName, type, indexConfig) { - this.name = name; - this.keyAsName = keyAsName; - this.type = type; - this.indexConfig = indexConfig; - } - name; - keyAsName; - type; - indexConfig; -}; -var PgArrayBuilder = class extends PgColumnBuilder { - static { - __name(this, "PgArrayBuilder"); - } - static [entityKind] = "PgArrayBuilder"; - constructor(name, baseBuilder, size) { - super(name, "array", "PgArray"); - this.config.baseBuilder = baseBuilder; - this.config.size = size; - } - /** @internal */ - build(table) { - const baseColumn = this.config.baseBuilder.build(table); - return new PgArray( - table, - this.config, - baseColumn - ); - } -}; -var PgArray = class _PgArray extends PgColumn { - static { - __name(this, "PgArray"); - } - constructor(table, config2, baseColumn, range) { - super(table, config2); - this.baseColumn = baseColumn; - this.range = range; - this.size = config2.size; - } - size; - static [entityKind] = "PgArray"; - getSQLType() { - return `${this.baseColumn.getSQLType()}[${typeof this.size === "number" ? this.size : ""}]`; - } - mapFromDriverValue(value) { - if (typeof value === "string") { - value = parsePgArray(value); - } - return value.map((v) => this.baseColumn.mapFromDriverValue(v)); - } - mapToDriverValue(value, isNestedArray = false) { - const a = value.map( - (v) => v === null ? null : is(this.baseColumn, _PgArray) ? this.baseColumn.mapToDriverValue(v, true) : this.baseColumn.mapToDriverValue(v) - ); - if (isNestedArray) return a; - return makePgArray(a); - } -}; - -// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/pg-core/columns/enum.js -var PgEnumObjectColumnBuilder = class extends PgColumnBuilder { - static { - __name(this, "PgEnumObjectColumnBuilder"); - } - static [entityKind] = "PgEnumObjectColumnBuilder"; - constructor(name, enumInstance) { - super(name, "string", "PgEnumObjectColumn"); - this.config.enum = enumInstance; - } - /** @internal */ - build(table) { - return new PgEnumObjectColumn( - table, - this.config - ); - } -}; -var PgEnumObjectColumn = class extends PgColumn { - static { - __name(this, "PgEnumObjectColumn"); - } - static [entityKind] = "PgEnumObjectColumn"; - enum; - enumValues = this.config.enum.enumValues; - constructor(table, config2) { - super(table, config2); - this.enum = config2.enum; - } - getSQLType() { - return this.enum.enumName; - } -}; -var isPgEnumSym = /* @__PURE__ */ Symbol.for("drizzle:isPgEnum"); -function isPgEnum(obj) { - return !!obj && typeof obj === "function" && isPgEnumSym in obj && obj[isPgEnumSym] === true; -} -__name(isPgEnum, "isPgEnum"); -var PgEnumColumnBuilder = class extends PgColumnBuilder { - static { - __name(this, "PgEnumColumnBuilder"); - } - static [entityKind] = "PgEnumColumnBuilder"; - constructor(name, enumInstance) { - super(name, "string", "PgEnumColumn"); - this.config.enum = enumInstance; - } - /** @internal */ - build(table) { - return new PgEnumColumn( - table, - this.config - ); - } -}; -var PgEnumColumn = class extends PgColumn { - static { - __name(this, "PgEnumColumn"); - } - static [entityKind] = "PgEnumColumn"; - enum = this.config.enum; - enumValues = this.config.enum.enumValues; - constructor(table, config2) { - super(table, config2); - this.enum = config2.enum; - } - getSQLType() { - return this.enum.enumName; - } -}; - -// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/subquery.js -init_modules_watch_stub(); -init_performance2(); -var Subquery = class { - static { - __name(this, "Subquery"); - } - static [entityKind] = "Subquery"; - constructor(sql2, fields, alias, isWith = false, usedTables = []) { - this._ = { - brand: "Subquery", - sql: sql2, - selectedFields: fields, - alias, - isWith, - usedTables - }; - } - // getSQL(): SQL { - // return new SQL([this]); - // } -}; -var WithSubquery = class extends Subquery { - static { - __name(this, "WithSubquery"); - } - static [entityKind] = "WithSubquery"; -}; - -// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/tracing.js -init_modules_watch_stub(); -init_performance2(); - -// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/version.js -init_modules_watch_stub(); -init_performance2(); -var version2 = "0.45.1"; - -// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/tracing.js -var otel; -var rawTracer; -var tracer = { - startActiveSpan(name, fn) { - if (!otel) { - return fn(); - } - if (!rawTracer) { - rawTracer = otel.trace.getTracer("drizzle-orm", version2); - } - return iife( - (otel2, rawTracer2) => rawTracer2.startActiveSpan( - name, - (span) => { - try { - return fn(span); - } catch (e) { - span.setStatus({ - code: otel2.SpanStatusCode.ERROR, - message: e instanceof Error ? e.message : "Unknown error" - // eslint-disable-line no-instanceof/no-instanceof - }); - throw e; - } finally { - span.end(); - } - } - ), - otel, - rawTracer - ); - } -}; - -// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/view-common.js -init_modules_watch_stub(); -init_performance2(); -var ViewBaseConfig = /* @__PURE__ */ Symbol.for("drizzle:ViewBaseConfig"); - -// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/sql/sql.js -var FakePrimitiveParam = class { - static { - __name(this, "FakePrimitiveParam"); - } - static [entityKind] = "FakePrimitiveParam"; -}; -function isSQLWrapper(value) { - return value !== null && value !== void 0 && typeof value.getSQL === "function"; -} -__name(isSQLWrapper, "isSQLWrapper"); -function mergeQueries(queries) { - const result = { sql: "", params: [] }; - for (const query of queries) { - result.sql += query.sql; - result.params.push(...query.params); - if (query.typings?.length) { - if (!result.typings) { - result.typings = []; - } - result.typings.push(...query.typings); - } - } - return result; -} -__name(mergeQueries, "mergeQueries"); -var StringChunk = class { - static { - __name(this, "StringChunk"); - } - static [entityKind] = "StringChunk"; - value; - constructor(value) { - this.value = Array.isArray(value) ? value : [value]; - } - getSQL() { - return new SQL([this]); - } -}; -var SQL = class _SQL { - static { - __name(this, "SQL"); - } - constructor(queryChunks) { - this.queryChunks = queryChunks; - for (const chunk of queryChunks) { - if (is(chunk, Table)) { - const schemaName = chunk[Table.Symbol.Schema]; - this.usedTables.push( - schemaName === void 0 ? chunk[Table.Symbol.Name] : schemaName + "." + chunk[Table.Symbol.Name] - ); - } - } - } - static [entityKind] = "SQL"; - /** @internal */ - decoder = noopDecoder; - shouldInlineParams = false; - /** @internal */ - usedTables = []; - append(query) { - this.queryChunks.push(...query.queryChunks); - return this; - } - toQuery(config2) { - return tracer.startActiveSpan("drizzle.buildSQL", (span) => { - const query = this.buildQueryFromSourceParams(this.queryChunks, config2); - span?.setAttributes({ - "drizzle.query.text": query.sql, - "drizzle.query.params": JSON.stringify(query.params) - }); - return query; - }); - } - buildQueryFromSourceParams(chunks, _config) { - const config2 = Object.assign({}, _config, { - inlineParams: _config.inlineParams || this.shouldInlineParams, - paramStartIndex: _config.paramStartIndex || { value: 0 } - }); - const { - casing, - escapeName, - escapeParam, - prepareTyping, - inlineParams, - paramStartIndex - } = config2; - return mergeQueries(chunks.map((chunk) => { - if (is(chunk, StringChunk)) { - return { sql: chunk.value.join(""), params: [] }; - } - if (is(chunk, Name)) { - return { sql: escapeName(chunk.value), params: [] }; - } - if (chunk === void 0) { - return { sql: "", params: [] }; - } - if (Array.isArray(chunk)) { - const result = [new StringChunk("(")]; - for (const [i, p] of chunk.entries()) { - result.push(p); - if (i < chunk.length - 1) { - result.push(new StringChunk(", ")); - } - } - result.push(new StringChunk(")")); - return this.buildQueryFromSourceParams(result, config2); - } - if (is(chunk, _SQL)) { - return this.buildQueryFromSourceParams(chunk.queryChunks, { - ...config2, - inlineParams: inlineParams || chunk.shouldInlineParams - }); - } - if (is(chunk, Table)) { - const schemaName = chunk[Table.Symbol.Schema]; - const tableName = chunk[Table.Symbol.Name]; - return { - sql: schemaName === void 0 || chunk[IsAlias] ? escapeName(tableName) : escapeName(schemaName) + "." + escapeName(tableName), - params: [] - }; - } - if (is(chunk, Column)) { - const columnName = casing.getColumnCasing(chunk); - if (_config.invokeSource === "indexes") { - return { sql: escapeName(columnName), params: [] }; - } - const schemaName = chunk.table[Table.Symbol.Schema]; - return { - sql: chunk.table[IsAlias] || schemaName === void 0 ? escapeName(chunk.table[Table.Symbol.Name]) + "." + escapeName(columnName) : escapeName(schemaName) + "." + escapeName(chunk.table[Table.Symbol.Name]) + "." + escapeName(columnName), - params: [] - }; - } - if (is(chunk, View)) { - const schemaName = chunk[ViewBaseConfig].schema; - const viewName = chunk[ViewBaseConfig].name; - return { - sql: schemaName === void 0 || chunk[ViewBaseConfig].isAlias ? escapeName(viewName) : escapeName(schemaName) + "." + escapeName(viewName), - params: [] - }; - } - if (is(chunk, Param)) { - if (is(chunk.value, Placeholder)) { - return { sql: escapeParam(paramStartIndex.value++, chunk), params: [chunk], typings: ["none"] }; - } - const mappedValue = chunk.value === null ? null : chunk.encoder.mapToDriverValue(chunk.value); - if (is(mappedValue, _SQL)) { - return this.buildQueryFromSourceParams([mappedValue], config2); - } - if (inlineParams) { - return { sql: this.mapInlineParam(mappedValue, config2), params: [] }; - } - let typings = ["none"]; - if (prepareTyping) { - typings = [prepareTyping(chunk.encoder)]; - } - return { sql: escapeParam(paramStartIndex.value++, mappedValue), params: [mappedValue], typings }; - } - if (is(chunk, Placeholder)) { - return { sql: escapeParam(paramStartIndex.value++, chunk), params: [chunk], typings: ["none"] }; - } - if (is(chunk, _SQL.Aliased) && chunk.fieldAlias !== void 0) { - return { sql: escapeName(chunk.fieldAlias), params: [] }; - } - if (is(chunk, Subquery)) { - if (chunk._.isWith) { - return { sql: escapeName(chunk._.alias), params: [] }; - } - return this.buildQueryFromSourceParams([ - new StringChunk("("), - chunk._.sql, - new StringChunk(") "), - new Name(chunk._.alias) - ], config2); - } - if (isPgEnum(chunk)) { - if (chunk.schema) { - return { sql: escapeName(chunk.schema) + "." + escapeName(chunk.enumName), params: [] }; - } - return { sql: escapeName(chunk.enumName), params: [] }; - } - if (isSQLWrapper(chunk)) { - if (chunk.shouldOmitSQLParens?.()) { - return this.buildQueryFromSourceParams([chunk.getSQL()], config2); - } - return this.buildQueryFromSourceParams([ - new StringChunk("("), - chunk.getSQL(), - new StringChunk(")") - ], config2); - } - if (inlineParams) { - return { sql: this.mapInlineParam(chunk, config2), params: [] }; - } - return { sql: escapeParam(paramStartIndex.value++, chunk), params: [chunk], typings: ["none"] }; - })); - } - mapInlineParam(chunk, { escapeString }) { - if (chunk === null) { - return "null"; - } - if (typeof chunk === "number" || typeof chunk === "boolean") { - return chunk.toString(); - } - if (typeof chunk === "string") { - return escapeString(chunk); - } - if (typeof chunk === "object") { - const mappedValueAsString = chunk.toString(); - if (mappedValueAsString === "[object Object]") { - return escapeString(JSON.stringify(chunk)); - } - return escapeString(mappedValueAsString); - } - throw new Error("Unexpected param value: " + chunk); - } - getSQL() { - return this; - } - as(alias) { - if (alias === void 0) { - return this; - } - return new _SQL.Aliased(this, alias); - } - mapWith(decoder) { - this.decoder = typeof decoder === "function" ? { mapFromDriverValue: decoder } : decoder; - return this; - } - inlineParams() { - this.shouldInlineParams = true; - return this; - } - /** - * This method is used to conditionally include a part of the query. - * - * @param condition - Condition to check - * @returns itself if the condition is `true`, otherwise `undefined` - */ - if(condition) { - return condition ? this : void 0; - } -}; -var Name = class { - static { - __name(this, "Name"); - } - constructor(value) { - this.value = value; - } - static [entityKind] = "Name"; - brand; - getSQL() { - return new SQL([this]); - } -}; -function isDriverValueEncoder(value) { - return typeof value === "object" && value !== null && "mapToDriverValue" in value && typeof value.mapToDriverValue === "function"; -} -__name(isDriverValueEncoder, "isDriverValueEncoder"); -var noopDecoder = { - mapFromDriverValue: /* @__PURE__ */ __name((value) => value, "mapFromDriverValue") -}; -var noopEncoder = { - mapToDriverValue: /* @__PURE__ */ __name((value) => value, "mapToDriverValue") -}; -var noopMapper = { - ...noopDecoder, - ...noopEncoder -}; -var Param = class { - static { - __name(this, "Param"); - } - /** - * @param value - Parameter value - * @param encoder - Encoder to convert the value to a driver parameter - */ - constructor(value, encoder = noopEncoder) { - this.value = value; - this.encoder = encoder; - } - static [entityKind] = "Param"; - brand; - getSQL() { - return new SQL([this]); - } -}; -function sql(strings, ...params) { - const queryChunks = []; - if (params.length > 0 || strings.length > 0 && strings[0] !== "") { - queryChunks.push(new StringChunk(strings[0])); - } - for (const [paramIndex, param2] of params.entries()) { - queryChunks.push(param2, new StringChunk(strings[paramIndex + 1])); - } - return new SQL(queryChunks); -} -__name(sql, "sql"); -((sql2) => { - function empty() { - return new SQL([]); - } - __name(empty, "empty"); - sql2.empty = empty; - function fromList(list) { - return new SQL(list); - } - __name(fromList, "fromList"); - sql2.fromList = fromList; - function raw2(str2) { - return new SQL([new StringChunk(str2)]); - } - __name(raw2, "raw"); - sql2.raw = raw2; - function join(chunks, separator) { - const result = []; - for (const [i, chunk] of chunks.entries()) { - if (i > 0 && separator !== void 0) { - result.push(separator); - } - result.push(chunk); - } - return new SQL(result); - } - __name(join, "join"); - sql2.join = join; - function identifier(value) { - return new Name(value); - } - __name(identifier, "identifier"); - sql2.identifier = identifier; - function placeholder2(name2) { - return new Placeholder(name2); - } - __name(placeholder2, "placeholder2"); - sql2.placeholder = placeholder2; - function param2(value, encoder) { - return new Param(value, encoder); - } - __name(param2, "param2"); - sql2.param = param2; -})(sql || (sql = {})); -((SQL2) => { - class Aliased { - static { - __name(this, "Aliased"); - } - constructor(sql2, fieldAlias) { - this.sql = sql2; - this.fieldAlias = fieldAlias; - } - static [entityKind] = "SQL.Aliased"; - /** @internal */ - isSelectionField = false; - getSQL() { - return this.sql; - } - /** @internal */ - clone() { - return new Aliased(this.sql, this.fieldAlias); - } - } - SQL2.Aliased = Aliased; -})(SQL || (SQL = {})); -var Placeholder = class { - static { - __name(this, "Placeholder"); - } - constructor(name2) { - this.name = name2; - } - static [entityKind] = "Placeholder"; - getSQL() { - return new SQL([this]); - } -}; -function fillPlaceholders(params, values) { - return params.map((p) => { - if (is(p, Placeholder)) { - if (!(p.name in values)) { - throw new Error(`No value for placeholder "${p.name}" was provided`); - } - return values[p.name]; - } - if (is(p, Param) && is(p.value, Placeholder)) { - if (!(p.value.name in values)) { - throw new Error(`No value for placeholder "${p.value.name}" was provided`); - } - return p.encoder.mapToDriverValue(values[p.value.name]); - } - return p; - }); -} -__name(fillPlaceholders, "fillPlaceholders"); -var IsDrizzleView = /* @__PURE__ */ Symbol.for("drizzle:IsDrizzleView"); -var View = class { - static { - __name(this, "View"); - } - static [entityKind] = "View"; - /** @internal */ - [ViewBaseConfig]; - /** @internal */ - [IsDrizzleView] = true; - constructor({ name: name2, schema, selectedFields, query }) { - this[ViewBaseConfig] = { - name: name2, - originalName: name2, - schema, - selectedFields, - query, - isExisting: !query, - isAlias: false - }; - } - getSQL() { - return new SQL([this]); - } -}; -Column.prototype.getSQL = function() { - return new SQL([this]); -}; -Table.prototype.getSQL = function() { - return new SQL([this]); -}; -Subquery.prototype.getSQL = function() { - return new SQL([this]); -}; - -// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/utils.js -function mapResultRow(columns, row, joinsNotNullableMap) { - const nullifyMap = {}; - const result = columns.reduce( - (result2, { path, field }, columnIndex) => { - let decoder; - if (is(field, Column)) { - decoder = field; - } else if (is(field, SQL)) { - decoder = field.decoder; - } else if (is(field, Subquery)) { - decoder = field._.sql.decoder; - } else { - decoder = field.sql.decoder; - } - let node = result2; - for (const [pathChunkIndex, pathChunk] of path.entries()) { - if (pathChunkIndex < path.length - 1) { - if (!(pathChunk in node)) { - node[pathChunk] = {}; - } - node = node[pathChunk]; - } else { - const rawValue = row[columnIndex]; - const value = node[pathChunk] = rawValue === null ? null : decoder.mapFromDriverValue(rawValue); - if (joinsNotNullableMap && is(field, Column) && path.length === 2) { - const objectName = path[0]; - if (!(objectName in nullifyMap)) { - nullifyMap[objectName] = value === null ? getTableName(field.table) : false; - } else if (typeof nullifyMap[objectName] === "string" && nullifyMap[objectName] !== getTableName(field.table)) { - nullifyMap[objectName] = false; - } - } - } - } - return result2; - }, - {} - ); - if (joinsNotNullableMap && Object.keys(nullifyMap).length > 0) { - for (const [objectName, tableName] of Object.entries(nullifyMap)) { - if (typeof tableName === "string" && !joinsNotNullableMap[tableName]) { - result[objectName] = null; - } - } - } - return result; -} -__name(mapResultRow, "mapResultRow"); -function orderSelectedFields(fields, pathPrefix) { - return Object.entries(fields).reduce((result, [name, field]) => { - if (typeof name !== "string") { - return result; - } - const newPath = pathPrefix ? [...pathPrefix, name] : [name]; - if (is(field, Column) || is(field, SQL) || is(field, SQL.Aliased) || is(field, Subquery)) { - result.push({ path: newPath, field }); - } else if (is(field, Table)) { - result.push(...orderSelectedFields(field[Table.Symbol.Columns], newPath)); - } else { - result.push(...orderSelectedFields(field, newPath)); - } - return result; - }, []); -} -__name(orderSelectedFields, "orderSelectedFields"); -function haveSameKeys(left, right) { - const leftKeys = Object.keys(left); - const rightKeys = Object.keys(right); - if (leftKeys.length !== rightKeys.length) { - return false; - } - for (const [index, key] of leftKeys.entries()) { - if (key !== rightKeys[index]) { - return false; - } - } - return true; -} -__name(haveSameKeys, "haveSameKeys"); -function mapUpdateSet(table, values) { - const entries = Object.entries(values).filter(([, value]) => value !== void 0).map(([key, value]) => { - if (is(value, SQL) || is(value, Column)) { - return [key, value]; - } else { - return [key, new Param(value, table[Table.Symbol.Columns][key])]; - } - }); - if (entries.length === 0) { - throw new Error("No values to set"); - } - return Object.fromEntries(entries); -} -__name(mapUpdateSet, "mapUpdateSet"); -function applyMixins(baseClass, extendedClasses) { - for (const extendedClass of extendedClasses) { - for (const name of Object.getOwnPropertyNames(extendedClass.prototype)) { - if (name === "constructor") continue; - Object.defineProperty( - baseClass.prototype, - name, - Object.getOwnPropertyDescriptor(extendedClass.prototype, name) || /* @__PURE__ */ Object.create(null) - ); - } - } -} -__name(applyMixins, "applyMixins"); -function getTableColumns(table) { - return table[Table.Symbol.Columns]; -} -__name(getTableColumns, "getTableColumns"); -function getTableLikeName(table) { - return is(table, Subquery) ? table._.alias : is(table, View) ? table[ViewBaseConfig].name : is(table, SQL) ? void 0 : table[Table.Symbol.IsAlias] ? table[Table.Symbol.Name] : table[Table.Symbol.BaseName]; -} -__name(getTableLikeName, "getTableLikeName"); -function getColumnNameAndConfig(a, b) { - return { - name: typeof a === "string" && a.length > 0 ? a : "", - config: typeof a === "object" ? a : b - }; -} -__name(getColumnNameAndConfig, "getColumnNameAndConfig"); -var textDecoder = typeof TextDecoder === "undefined" ? null : new TextDecoder(); - -// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/pg-core/table.js -var InlineForeignKeys = /* @__PURE__ */ Symbol.for("drizzle:PgInlineForeignKeys"); -var EnableRLS = /* @__PURE__ */ Symbol.for("drizzle:EnableRLS"); -var PgTable = class extends Table { - static { - __name(this, "PgTable"); - } - static [entityKind] = "PgTable"; - /** @internal */ - static Symbol = Object.assign({}, Table.Symbol, { - InlineForeignKeys, - EnableRLS - }); - /**@internal */ - [InlineForeignKeys] = []; - /** @internal */ - [EnableRLS] = false; - /** @internal */ - [Table.Symbol.ExtraConfigBuilder] = void 0; - /** @internal */ - [Table.Symbol.ExtraConfigColumns] = {}; -}; - -// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/pg-core/primary-keys.js -var PrimaryKeyBuilder = class { - static { - __name(this, "PrimaryKeyBuilder"); - } - static [entityKind] = "PgPrimaryKeyBuilder"; - /** @internal */ - columns; - /** @internal */ - name; - constructor(columns, name) { - this.columns = columns; - this.name = name; - } - /** @internal */ - build(table) { - return new PrimaryKey(table, this.columns, this.name); - } -}; -var PrimaryKey = class { - static { - __name(this, "PrimaryKey"); - } - constructor(table, columns, name) { - this.table = table; - this.columns = columns; - this.name = name; - } - static [entityKind] = "PgPrimaryKey"; - columns; - name; - getName() { - return this.name ?? `${this.table[PgTable.Symbol.Name]}_${this.columns.map((column) => column.name).join("_")}_pk`; - } -}; - -// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/sql/expressions/conditions.js -init_modules_watch_stub(); -init_performance2(); -function bindIfParam(value, column) { - if (isDriverValueEncoder(column) && !isSQLWrapper(value) && !is(value, Param) && !is(value, Placeholder) && !is(value, Column) && !is(value, Table) && !is(value, View)) { - return new Param(value, column); - } - return value; -} -__name(bindIfParam, "bindIfParam"); -var eq = /* @__PURE__ */ __name((left, right) => { - return sql`${left} = ${bindIfParam(right, left)}`; -}, "eq"); -var ne = /* @__PURE__ */ __name((left, right) => { - return sql`${left} <> ${bindIfParam(right, left)}`; -}, "ne"); -function and(...unfilteredConditions) { - const conditions = unfilteredConditions.filter( - (c) => c !== void 0 - ); - if (conditions.length === 0) { - return void 0; - } - if (conditions.length === 1) { - return new SQL(conditions); - } - return new SQL([ - new StringChunk("("), - sql.join(conditions, new StringChunk(" and ")), - new StringChunk(")") - ]); -} -__name(and, "and"); -function or2(...unfilteredConditions) { - const conditions = unfilteredConditions.filter( - (c) => c !== void 0 - ); - if (conditions.length === 0) { - return void 0; - } - if (conditions.length === 1) { - return new SQL(conditions); - } - return new SQL([ - new StringChunk("("), - sql.join(conditions, new StringChunk(" or ")), - new StringChunk(")") - ]); -} -__name(or2, "or"); -function not(condition) { - return sql`not ${condition}`; -} -__name(not, "not"); -var gt = /* @__PURE__ */ __name((left, right) => { - return sql`${left} > ${bindIfParam(right, left)}`; -}, "gt"); -var gte = /* @__PURE__ */ __name((left, right) => { - return sql`${left} >= ${bindIfParam(right, left)}`; -}, "gte"); -var lt = /* @__PURE__ */ __name((left, right) => { - return sql`${left} < ${bindIfParam(right, left)}`; -}, "lt"); -var lte = /* @__PURE__ */ __name((left, right) => { - return sql`${left} <= ${bindIfParam(right, left)}`; -}, "lte"); -function inArray(column, values) { - if (Array.isArray(values)) { - if (values.length === 0) { - return sql`false`; - } - return sql`${column} in ${values.map((v) => bindIfParam(v, column))}`; - } - return sql`${column} in ${bindIfParam(values, column)}`; -} -__name(inArray, "inArray"); -function notInArray(column, values) { - if (Array.isArray(values)) { - if (values.length === 0) { - return sql`true`; - } - return sql`${column} not in ${values.map((v) => bindIfParam(v, column))}`; - } - return sql`${column} not in ${bindIfParam(values, column)}`; -} -__name(notInArray, "notInArray"); -function isNull(value) { - return sql`${value} is null`; -} -__name(isNull, "isNull"); -function isNotNull(value) { - return sql`${value} is not null`; -} -__name(isNotNull, "isNotNull"); -function exists(subquery) { - return sql`exists ${subquery}`; -} -__name(exists, "exists"); -function notExists(subquery) { - return sql`not exists ${subquery}`; -} -__name(notExists, "notExists"); -function between(column, min, max) { - return sql`${column} between ${bindIfParam(min, column)} and ${bindIfParam( - max, - column - )}`; -} -__name(between, "between"); -function notBetween(column, min, max) { - return sql`${column} not between ${bindIfParam( - min, - column - )} and ${bindIfParam(max, column)}`; -} -__name(notBetween, "notBetween"); -function like(column, value) { - return sql`${column} like ${value}`; -} -__name(like, "like"); -function notLike(column, value) { - return sql`${column} not like ${value}`; -} -__name(notLike, "notLike"); -function ilike(column, value) { - return sql`${column} ilike ${value}`; -} -__name(ilike, "ilike"); -function notIlike(column, value) { - return sql`${column} not ilike ${value}`; -} -__name(notIlike, "notIlike"); - -// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/sql/expressions/select.js -init_modules_watch_stub(); -init_performance2(); -function asc(column) { - return sql`${column} asc`; -} -__name(asc, "asc"); -function desc(column) { - return sql`${column} desc`; -} -__name(desc, "desc"); - -// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/relations.js -var Relation = class { - static { - __name(this, "Relation"); - } - constructor(sourceTable, referencedTable, relationName) { - this.sourceTable = sourceTable; - this.referencedTable = referencedTable; - this.relationName = relationName; - this.referencedTableName = referencedTable[Table.Symbol.Name]; - } - static [entityKind] = "Relation"; - referencedTableName; - fieldName; -}; -var Relations = class { - static { - __name(this, "Relations"); - } - constructor(table, config2) { - this.table = table; - this.config = config2; - } - static [entityKind] = "Relations"; -}; -var One = class _One extends Relation { - static { - __name(this, "One"); - } - constructor(sourceTable, referencedTable, config2, isNullable) { - super(sourceTable, referencedTable, config2?.relationName); - this.config = config2; - this.isNullable = isNullable; - } - static [entityKind] = "One"; - withFieldName(fieldName) { - const relation = new _One( - this.sourceTable, - this.referencedTable, - this.config, - this.isNullable - ); - relation.fieldName = fieldName; - return relation; - } -}; -var Many = class _Many extends Relation { - static { - __name(this, "Many"); - } - constructor(sourceTable, referencedTable, config2) { - super(sourceTable, referencedTable, config2?.relationName); - this.config = config2; - } - static [entityKind] = "Many"; - withFieldName(fieldName) { - const relation = new _Many( - this.sourceTable, - this.referencedTable, - this.config - ); - relation.fieldName = fieldName; - return relation; - } -}; -function getOperators() { - return { - and, - between, - eq, - exists, - gt, - gte, - ilike, - inArray, - isNull, - isNotNull, - like, - lt, - lte, - ne, - not, - notBetween, - notExists, - notLike, - notIlike, - notInArray, - or: or2, - sql - }; -} -__name(getOperators, "getOperators"); -function getOrderByOperators() { - return { - sql, - asc, - desc - }; -} -__name(getOrderByOperators, "getOrderByOperators"); -function extractTablesRelationalConfig(schema, configHelpers) { - if (Object.keys(schema).length === 1 && "default" in schema && !is(schema["default"], Table)) { - schema = schema["default"]; - } - const tableNamesMap = {}; - const relationsBuffer = {}; - const tablesConfig = {}; - for (const [key, value] of Object.entries(schema)) { - if (is(value, Table)) { - const dbName = getTableUniqueName(value); - const bufferedRelations = relationsBuffer[dbName]; - tableNamesMap[dbName] = key; - tablesConfig[key] = { - tsName: key, - dbName: value[Table.Symbol.Name], - schema: value[Table.Symbol.Schema], - columns: value[Table.Symbol.Columns], - relations: bufferedRelations?.relations ?? {}, - primaryKey: bufferedRelations?.primaryKey ?? [] - }; - for (const column of Object.values( - value[Table.Symbol.Columns] - )) { - if (column.primary) { - tablesConfig[key].primaryKey.push(column); - } - } - const extraConfig = value[Table.Symbol.ExtraConfigBuilder]?.(value[Table.Symbol.ExtraConfigColumns]); - if (extraConfig) { - for (const configEntry of Object.values(extraConfig)) { - if (is(configEntry, PrimaryKeyBuilder)) { - tablesConfig[key].primaryKey.push(...configEntry.columns); - } - } - } - } else if (is(value, Relations)) { - const dbName = getTableUniqueName(value.table); - const tableName = tableNamesMap[dbName]; - const relations2 = value.config( - configHelpers(value.table) - ); - let primaryKey; - for (const [relationName, relation] of Object.entries(relations2)) { - if (tableName) { - const tableConfig = tablesConfig[tableName]; - tableConfig.relations[relationName] = relation; - if (primaryKey) { - tableConfig.primaryKey.push(...primaryKey); - } - } else { - if (!(dbName in relationsBuffer)) { - relationsBuffer[dbName] = { - relations: {}, - primaryKey - }; - } - relationsBuffer[dbName].relations[relationName] = relation; - } - } - } - } - return { tables: tablesConfig, tableNamesMap }; -} -__name(extractTablesRelationalConfig, "extractTablesRelationalConfig"); -function relations(table, relations2) { - return new Relations( - table, - (helpers) => Object.fromEntries( - Object.entries(relations2(helpers)).map(([key, value]) => [ - key, - value.withFieldName(key) - ]) - ) - ); -} -__name(relations, "relations"); -function createOne(sourceTable) { - return /* @__PURE__ */ __name(function one(table, config2) { - return new One( - sourceTable, - table, - config2, - config2?.fields.reduce((res, f) => res && f.notNull, true) ?? false - ); - }, "one"); -} -__name(createOne, "createOne"); -function createMany(sourceTable) { - return /* @__PURE__ */ __name(function many(referencedTable, config2) { - return new Many(sourceTable, referencedTable, config2); - }, "many"); -} -__name(createMany, "createMany"); -function normalizeRelation(schema, tableNamesMap, relation) { - if (is(relation, One) && relation.config) { - return { - fields: relation.config.fields, - references: relation.config.references - }; - } - const referencedTableTsName = tableNamesMap[getTableUniqueName(relation.referencedTable)]; - if (!referencedTableTsName) { - throw new Error( - `Table "${relation.referencedTable[Table.Symbol.Name]}" not found in schema` - ); - } - const referencedTableConfig = schema[referencedTableTsName]; - if (!referencedTableConfig) { - throw new Error(`Table "${referencedTableTsName}" not found in schema`); - } - const sourceTable = relation.sourceTable; - const sourceTableTsName = tableNamesMap[getTableUniqueName(sourceTable)]; - if (!sourceTableTsName) { - throw new Error( - `Table "${sourceTable[Table.Symbol.Name]}" not found in schema` - ); - } - const reverseRelations = []; - for (const referencedTableRelation of Object.values( - referencedTableConfig.relations - )) { - if (relation.relationName && relation !== referencedTableRelation && referencedTableRelation.relationName === relation.relationName || !relation.relationName && referencedTableRelation.referencedTable === relation.sourceTable) { - reverseRelations.push(referencedTableRelation); - } - } - if (reverseRelations.length > 1) { - throw relation.relationName ? new Error( - `There are multiple relations with name "${relation.relationName}" in table "${referencedTableTsName}"` - ) : new Error( - `There are multiple relations between "${referencedTableTsName}" and "${relation.sourceTable[Table.Symbol.Name]}". Please specify relation name` - ); - } - if (reverseRelations[0] && is(reverseRelations[0], One) && reverseRelations[0].config) { - return { - fields: reverseRelations[0].config.references, - references: reverseRelations[0].config.fields - }; - } - throw new Error( - `There is not enough information to infer relation "${sourceTableTsName}.${relation.fieldName}"` - ); -} -__name(normalizeRelation, "normalizeRelation"); -function createTableRelationsHelpers(sourceTable) { - return { - one: createOne(sourceTable), - many: createMany(sourceTable) - }; -} -__name(createTableRelationsHelpers, "createTableRelationsHelpers"); -function mapRelationalRow(tablesConfig, tableConfig, row, buildQueryResultSelection, mapColumnValue = (value) => value) { - const result = {}; - for (const [ - selectionItemIndex, - selectionItem - ] of buildQueryResultSelection.entries()) { - if (selectionItem.isJson) { - const relation = tableConfig.relations[selectionItem.tsKey]; - const rawSubRows = row[selectionItemIndex]; - const subRows = typeof rawSubRows === "string" ? JSON.parse(rawSubRows) : rawSubRows; - result[selectionItem.tsKey] = is(relation, One) ? subRows && mapRelationalRow( - tablesConfig, - tablesConfig[selectionItem.relationTableTsKey], - subRows, - selectionItem.selection, - mapColumnValue - ) : subRows.map( - (subRow) => mapRelationalRow( - tablesConfig, - tablesConfig[selectionItem.relationTableTsKey], - subRow, - selectionItem.selection, - mapColumnValue - ) - ); - } else { - const value = mapColumnValue(row[selectionItemIndex]); - const field = selectionItem.field; - let decoder; - if (is(field, Column)) { - decoder = field; - } else if (is(field, SQL)) { - decoder = field.decoder; - } else { - decoder = field.sql.decoder; - } - result[selectionItem.tsKey] = value === null ? null : decoder.mapFromDriverValue(value); - } - } - return result; -} -__name(mapRelationalRow, "mapRelationalRow"); - -// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/sqlite-core/db.js -init_modules_watch_stub(); -init_performance2(); - -// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/selection-proxy.js -init_modules_watch_stub(); -init_performance2(); - -// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/alias.js -init_modules_watch_stub(); -init_performance2(); -var ColumnAliasProxyHandler = class { - static { - __name(this, "ColumnAliasProxyHandler"); - } - constructor(table) { - this.table = table; - } - static [entityKind] = "ColumnAliasProxyHandler"; - get(columnObj, prop) { - if (prop === "table") { - return this.table; - } - return columnObj[prop]; - } -}; -var TableAliasProxyHandler = class { - static { - __name(this, "TableAliasProxyHandler"); - } - constructor(alias, replaceOriginalName) { - this.alias = alias; - this.replaceOriginalName = replaceOriginalName; - } - static [entityKind] = "TableAliasProxyHandler"; - get(target, prop) { - if (prop === Table.Symbol.IsAlias) { - return true; - } - if (prop === Table.Symbol.Name) { - return this.alias; - } - if (this.replaceOriginalName && prop === Table.Symbol.OriginalName) { - return this.alias; - } - if (prop === ViewBaseConfig) { - return { - ...target[ViewBaseConfig], - name: this.alias, - isAlias: true - }; - } - if (prop === Table.Symbol.Columns) { - const columns = target[Table.Symbol.Columns]; - if (!columns) { - return columns; - } - const proxiedColumns = {}; - Object.keys(columns).map((key) => { - proxiedColumns[key] = new Proxy( - columns[key], - new ColumnAliasProxyHandler(new Proxy(target, this)) - ); - }); - return proxiedColumns; - } - const value = target[prop]; - if (is(value, Column)) { - return new Proxy(value, new ColumnAliasProxyHandler(new Proxy(target, this))); - } - return value; - } -}; -var RelationTableAliasProxyHandler = class { - static { - __name(this, "RelationTableAliasProxyHandler"); - } - constructor(alias) { - this.alias = alias; - } - static [entityKind] = "RelationTableAliasProxyHandler"; - get(target, prop) { - if (prop === "sourceTable") { - return aliasedTable(target.sourceTable, this.alias); - } - return target[prop]; - } -}; -function aliasedTable(table, tableAlias) { - return new Proxy(table, new TableAliasProxyHandler(tableAlias, false)); -} -__name(aliasedTable, "aliasedTable"); -function aliasedTableColumn(column, tableAlias) { - return new Proxy( - column, - new ColumnAliasProxyHandler(new Proxy(column.table, new TableAliasProxyHandler(tableAlias, false))) - ); -} -__name(aliasedTableColumn, "aliasedTableColumn"); -function mapColumnsInAliasedSQLToAlias(query, alias) { - return new SQL.Aliased(mapColumnsInSQLToAlias(query.sql, alias), query.fieldAlias); -} -__name(mapColumnsInAliasedSQLToAlias, "mapColumnsInAliasedSQLToAlias"); -function mapColumnsInSQLToAlias(query, alias) { - return sql.join(query.queryChunks.map((c) => { - if (is(c, Column)) { - return aliasedTableColumn(c, alias); - } - if (is(c, SQL)) { - return mapColumnsInSQLToAlias(c, alias); - } - if (is(c, SQL.Aliased)) { - return mapColumnsInAliasedSQLToAlias(c, alias); - } - return c; - })); -} -__name(mapColumnsInSQLToAlias, "mapColumnsInSQLToAlias"); - -// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/selection-proxy.js -var SelectionProxyHandler = class _SelectionProxyHandler { - static { - __name(this, "SelectionProxyHandler"); - } - static [entityKind] = "SelectionProxyHandler"; - config; - constructor(config2) { - this.config = { ...config2 }; - } - get(subquery, prop) { - if (prop === "_") { - return { - ...subquery["_"], - selectedFields: new Proxy( - subquery._.selectedFields, - this - ) - }; - } - if (prop === ViewBaseConfig) { - return { - ...subquery[ViewBaseConfig], - selectedFields: new Proxy( - subquery[ViewBaseConfig].selectedFields, - this - ) - }; - } - if (typeof prop === "symbol") { - return subquery[prop]; - } - const columns = is(subquery, Subquery) ? subquery._.selectedFields : is(subquery, View) ? subquery[ViewBaseConfig].selectedFields : subquery; - const value = columns[prop]; - if (is(value, SQL.Aliased)) { - if (this.config.sqlAliasedBehavior === "sql" && !value.isSelectionField) { - return value.sql; - } - const newValue = value.clone(); - newValue.isSelectionField = true; - return newValue; - } - if (is(value, SQL)) { - if (this.config.sqlBehavior === "sql") { - return value; - } - throw new Error( - `You tried to reference "${prop}" field from a subquery, which is a raw SQL field, but it doesn't have an alias declared. Please add an alias to the field using ".as('alias')" method.` - ); - } - if (is(value, Column)) { - if (this.config.alias) { - return new Proxy( - value, - new ColumnAliasProxyHandler( - new Proxy( - value.table, - new TableAliasProxyHandler(this.config.alias, this.config.replaceOriginalName ?? false) - ) - ) - ); - } - return value; - } - if (typeof value !== "object" || value === null) { - return value; - } - return new Proxy(value, new _SelectionProxyHandler(this.config)); - } -}; - -// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/sqlite-core/query-builders/delete.js -init_modules_watch_stub(); -init_performance2(); - -// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/query-promise.js -init_modules_watch_stub(); -init_performance2(); -var QueryPromise = class { - static { - __name(this, "QueryPromise"); - } - static [entityKind] = "QueryPromise"; - [Symbol.toStringTag] = "QueryPromise"; - catch(onRejected) { - return this.then(void 0, onRejected); - } - finally(onFinally) { - return this.then( - (value) => { - onFinally?.(); - return value; - }, - (reason) => { - onFinally?.(); - throw reason; - } - ); - } - then(onFulfilled, onRejected) { - return this.execute().then(onFulfilled, onRejected); - } -}; - -// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/sqlite-core/table.js -init_modules_watch_stub(); -init_performance2(); - -// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/sqlite-core/columns/all.js -init_modules_watch_stub(); -init_performance2(); - -// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/sqlite-core/columns/blob.js -init_modules_watch_stub(); -init_performance2(); - -// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/sqlite-core/columns/common.js -init_modules_watch_stub(); -init_performance2(); - -// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/sqlite-core/foreign-keys.js -init_modules_watch_stub(); -init_performance2(); -var ForeignKeyBuilder2 = class { - static { - __name(this, "ForeignKeyBuilder"); - } - static [entityKind] = "SQLiteForeignKeyBuilder"; - /** @internal */ - reference; - /** @internal */ - _onUpdate; - /** @internal */ - _onDelete; - constructor(config2, actions) { - this.reference = () => { - const { name, columns, foreignColumns } = config2(); - return { name, columns, foreignTable: foreignColumns[0].table, foreignColumns }; - }; - if (actions) { - this._onUpdate = actions.onUpdate; - this._onDelete = actions.onDelete; - } - } - onUpdate(action) { - this._onUpdate = action; - return this; - } - onDelete(action) { - this._onDelete = action; - return this; - } - /** @internal */ - build(table) { - return new ForeignKey2(table, this); - } -}; -var ForeignKey2 = class { - static { - __name(this, "ForeignKey"); - } - constructor(table, builder) { - this.table = table; - this.reference = builder.reference; - this.onUpdate = builder._onUpdate; - this.onDelete = builder._onDelete; - } - static [entityKind] = "SQLiteForeignKey"; - reference; - onUpdate; - onDelete; - getName() { - const { name, columns, foreignColumns } = this.reference(); - const columnNames = columns.map((column) => column.name); - const foreignColumnNames = foreignColumns.map((column) => column.name); - const chunks = [ - this.table[TableName], - ...columnNames, - foreignColumns[0].table[TableName], - ...foreignColumnNames - ]; - return name ?? `${chunks.join("_")}_fk`; - } -}; - -// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/sqlite-core/unique-constraint.js -init_modules_watch_stub(); -init_performance2(); -function uniqueKeyName2(table, columns) { - return `${table[TableName]}_${columns.join("_")}_unique`; -} -__name(uniqueKeyName2, "uniqueKeyName"); -var UniqueConstraintBuilder2 = class { - static { - __name(this, "UniqueConstraintBuilder"); - } - constructor(columns, name) { - this.name = name; - this.columns = columns; - } - static [entityKind] = "SQLiteUniqueConstraintBuilder"; - /** @internal */ - columns; - /** @internal */ - build(table) { - return new UniqueConstraint2(table, this.columns, this.name); - } -}; -var UniqueOnConstraintBuilder2 = class { - static { - __name(this, "UniqueOnConstraintBuilder"); - } - static [entityKind] = "SQLiteUniqueOnConstraintBuilder"; - /** @internal */ - name; - constructor(name) { - this.name = name; - } - on(...columns) { - return new UniqueConstraintBuilder2(columns, this.name); - } -}; -var UniqueConstraint2 = class { - static { - __name(this, "UniqueConstraint"); - } - constructor(table, columns, name) { - this.table = table; - this.columns = columns; - this.name = name ?? uniqueKeyName2(this.table, this.columns.map((column) => column.name)); - } - static [entityKind] = "SQLiteUniqueConstraint"; - columns; - name; - getName() { - return this.name; - } -}; - -// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/sqlite-core/columns/common.js -var SQLiteColumnBuilder = class extends ColumnBuilder { - static { - __name(this, "SQLiteColumnBuilder"); - } - static [entityKind] = "SQLiteColumnBuilder"; - foreignKeyConfigs = []; - references(ref, actions = {}) { - this.foreignKeyConfigs.push({ ref, actions }); - return this; - } - unique(name) { - this.config.isUnique = true; - this.config.uniqueName = name; - return this; - } - generatedAlwaysAs(as, config2) { - this.config.generated = { - as, - type: "always", - mode: config2?.mode ?? "virtual" - }; - return this; - } - /** @internal */ - buildForeignKeys(column, table) { - return this.foreignKeyConfigs.map(({ ref, actions }) => { - return ((ref2, actions2) => { - const builder = new ForeignKeyBuilder2(() => { - const foreignColumn = ref2(); - return { columns: [column], foreignColumns: [foreignColumn] }; - }); - if (actions2.onUpdate) { - builder.onUpdate(actions2.onUpdate); - } - if (actions2.onDelete) { - builder.onDelete(actions2.onDelete); - } - return builder.build(table); - })(ref, actions); - }); - } -}; -var SQLiteColumn = class extends Column { - static { - __name(this, "SQLiteColumn"); - } - constructor(table, config2) { - if (!config2.uniqueName) { - config2.uniqueName = uniqueKeyName2(table, [config2.name]); - } - super(table, config2); - this.table = table; - } - static [entityKind] = "SQLiteColumn"; -}; - -// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/sqlite-core/columns/blob.js -var SQLiteBigIntBuilder = class extends SQLiteColumnBuilder { - static { - __name(this, "SQLiteBigIntBuilder"); - } - static [entityKind] = "SQLiteBigIntBuilder"; - constructor(name) { - super(name, "bigint", "SQLiteBigInt"); - } - /** @internal */ - build(table) { - return new SQLiteBigInt(table, this.config); - } -}; -var SQLiteBigInt = class extends SQLiteColumn { - static { - __name(this, "SQLiteBigInt"); - } - static [entityKind] = "SQLiteBigInt"; - getSQLType() { - return "blob"; - } - mapFromDriverValue(value) { - if (typeof Buffer !== "undefined" && Buffer.from) { - const buf = Buffer.isBuffer(value) ? value : value instanceof ArrayBuffer ? Buffer.from(value) : value.buffer ? Buffer.from(value.buffer, value.byteOffset, value.byteLength) : Buffer.from(value); - return BigInt(buf.toString("utf8")); - } - return BigInt(textDecoder.decode(value)); - } - mapToDriverValue(value) { - return Buffer.from(value.toString()); - } -}; -var SQLiteBlobJsonBuilder = class extends SQLiteColumnBuilder { - static { - __name(this, "SQLiteBlobJsonBuilder"); - } - static [entityKind] = "SQLiteBlobJsonBuilder"; - constructor(name) { - super(name, "json", "SQLiteBlobJson"); - } - /** @internal */ - build(table) { - return new SQLiteBlobJson( - table, - this.config - ); - } -}; -var SQLiteBlobJson = class extends SQLiteColumn { - static { - __name(this, "SQLiteBlobJson"); - } - static [entityKind] = "SQLiteBlobJson"; - getSQLType() { - return "blob"; - } - mapFromDriverValue(value) { - if (typeof Buffer !== "undefined" && Buffer.from) { - const buf = Buffer.isBuffer(value) ? value : value instanceof ArrayBuffer ? Buffer.from(value) : value.buffer ? Buffer.from(value.buffer, value.byteOffset, value.byteLength) : Buffer.from(value); - return JSON.parse(buf.toString("utf8")); - } - return JSON.parse(textDecoder.decode(value)); - } - mapToDriverValue(value) { - return Buffer.from(JSON.stringify(value)); - } -}; -var SQLiteBlobBufferBuilder = class extends SQLiteColumnBuilder { - static { - __name(this, "SQLiteBlobBufferBuilder"); - } - static [entityKind] = "SQLiteBlobBufferBuilder"; - constructor(name) { - super(name, "buffer", "SQLiteBlobBuffer"); - } - /** @internal */ - build(table) { - return new SQLiteBlobBuffer(table, this.config); - } -}; -var SQLiteBlobBuffer = class extends SQLiteColumn { - static { - __name(this, "SQLiteBlobBuffer"); - } - static [entityKind] = "SQLiteBlobBuffer"; - mapFromDriverValue(value) { - if (Buffer.isBuffer(value)) { - return value; - } - return Buffer.from(value); - } - getSQLType() { - return "blob"; - } -}; -function blob(a, b) { - const { name, config: config2 } = getColumnNameAndConfig(a, b); - if (config2?.mode === "json") { - return new SQLiteBlobJsonBuilder(name); - } - if (config2?.mode === "bigint") { - return new SQLiteBigIntBuilder(name); - } - return new SQLiteBlobBufferBuilder(name); -} -__name(blob, "blob"); - -// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/sqlite-core/columns/custom.js -init_modules_watch_stub(); -init_performance2(); -var SQLiteCustomColumnBuilder = class extends SQLiteColumnBuilder { - static { - __name(this, "SQLiteCustomColumnBuilder"); - } - static [entityKind] = "SQLiteCustomColumnBuilder"; - constructor(name, fieldConfig, customTypeParams) { - super(name, "custom", "SQLiteCustomColumn"); - this.config.fieldConfig = fieldConfig; - this.config.customTypeParams = customTypeParams; - } - /** @internal */ - build(table) { - return new SQLiteCustomColumn( - table, - this.config - ); - } -}; -var SQLiteCustomColumn = class extends SQLiteColumn { - static { - __name(this, "SQLiteCustomColumn"); - } - static [entityKind] = "SQLiteCustomColumn"; - sqlName; - mapTo; - mapFrom; - constructor(table, config2) { - super(table, config2); - this.sqlName = config2.customTypeParams.dataType(config2.fieldConfig); - this.mapTo = config2.customTypeParams.toDriver; - this.mapFrom = config2.customTypeParams.fromDriver; - } - getSQLType() { - return this.sqlName; - } - mapFromDriverValue(value) { - return typeof this.mapFrom === "function" ? this.mapFrom(value) : value; - } - mapToDriverValue(value) { - return typeof this.mapTo === "function" ? this.mapTo(value) : value; - } -}; -function customType(customTypeParams) { - return (a, b) => { - const { name, config: config2 } = getColumnNameAndConfig(a, b); - return new SQLiteCustomColumnBuilder( - name, - config2, - customTypeParams - ); - }; -} -__name(customType, "customType"); - -// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/sqlite-core/columns/integer.js -init_modules_watch_stub(); -init_performance2(); -var SQLiteBaseIntegerBuilder = class extends SQLiteColumnBuilder { - static { - __name(this, "SQLiteBaseIntegerBuilder"); - } - static [entityKind] = "SQLiteBaseIntegerBuilder"; - constructor(name, dataType, columnType) { - super(name, dataType, columnType); - this.config.autoIncrement = false; - } - primaryKey(config2) { - if (config2?.autoIncrement) { - this.config.autoIncrement = true; - } - this.config.hasDefault = true; - return super.primaryKey(); - } -}; -var SQLiteBaseInteger = class extends SQLiteColumn { - static { - __name(this, "SQLiteBaseInteger"); - } - static [entityKind] = "SQLiteBaseInteger"; - autoIncrement = this.config.autoIncrement; - getSQLType() { - return "integer"; - } -}; -var SQLiteIntegerBuilder = class extends SQLiteBaseIntegerBuilder { - static { - __name(this, "SQLiteIntegerBuilder"); - } - static [entityKind] = "SQLiteIntegerBuilder"; - constructor(name) { - super(name, "number", "SQLiteInteger"); - } - build(table) { - return new SQLiteInteger( - table, - this.config - ); - } -}; -var SQLiteInteger = class extends SQLiteBaseInteger { - static { - __name(this, "SQLiteInteger"); - } - static [entityKind] = "SQLiteInteger"; -}; -var SQLiteTimestampBuilder = class extends SQLiteBaseIntegerBuilder { - static { - __name(this, "SQLiteTimestampBuilder"); - } - static [entityKind] = "SQLiteTimestampBuilder"; - constructor(name, mode) { - super(name, "date", "SQLiteTimestamp"); - this.config.mode = mode; - } - /** - * @deprecated Use `default()` with your own expression instead. - * - * Adds `DEFAULT (cast((julianday('now') - 2440587.5)*86400000 as integer))` to the column, which is the current epoch timestamp in milliseconds. - */ - defaultNow() { - return this.default(sql`(cast((julianday('now') - 2440587.5)*86400000 as integer))`); - } - build(table) { - return new SQLiteTimestamp( - table, - this.config - ); - } -}; -var SQLiteTimestamp = class extends SQLiteBaseInteger { - static { - __name(this, "SQLiteTimestamp"); - } - static [entityKind] = "SQLiteTimestamp"; - mode = this.config.mode; - mapFromDriverValue(value) { - if (this.config.mode === "timestamp") { - return new Date(value * 1e3); - } - return new Date(value); - } - mapToDriverValue(value) { - const unix = value.getTime(); - if (this.config.mode === "timestamp") { - return Math.floor(unix / 1e3); - } - return unix; - } -}; -var SQLiteBooleanBuilder = class extends SQLiteBaseIntegerBuilder { - static { - __name(this, "SQLiteBooleanBuilder"); - } - static [entityKind] = "SQLiteBooleanBuilder"; - constructor(name, mode) { - super(name, "boolean", "SQLiteBoolean"); - this.config.mode = mode; - } - build(table) { - return new SQLiteBoolean( - table, - this.config - ); - } -}; -var SQLiteBoolean = class extends SQLiteBaseInteger { - static { - __name(this, "SQLiteBoolean"); - } - static [entityKind] = "SQLiteBoolean"; - mode = this.config.mode; - mapFromDriverValue(value) { - return Number(value) === 1; - } - mapToDriverValue(value) { - return value ? 1 : 0; - } -}; -function integer(a, b) { - const { name, config: config2 } = getColumnNameAndConfig(a, b); - if (config2?.mode === "timestamp" || config2?.mode === "timestamp_ms") { - return new SQLiteTimestampBuilder(name, config2.mode); - } - if (config2?.mode === "boolean") { - return new SQLiteBooleanBuilder(name, config2.mode); - } - return new SQLiteIntegerBuilder(name); -} -__name(integer, "integer"); - -// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/sqlite-core/columns/numeric.js -init_modules_watch_stub(); -init_performance2(); -var SQLiteNumericBuilder = class extends SQLiteColumnBuilder { - static { - __name(this, "SQLiteNumericBuilder"); - } - static [entityKind] = "SQLiteNumericBuilder"; - constructor(name) { - super(name, "string", "SQLiteNumeric"); - } - /** @internal */ - build(table) { - return new SQLiteNumeric( - table, - this.config - ); - } -}; -var SQLiteNumeric = class extends SQLiteColumn { - static { - __name(this, "SQLiteNumeric"); - } - static [entityKind] = "SQLiteNumeric"; - mapFromDriverValue(value) { - if (typeof value === "string") return value; - return String(value); - } - getSQLType() { - return "numeric"; - } -}; -var SQLiteNumericNumberBuilder = class extends SQLiteColumnBuilder { - static { - __name(this, "SQLiteNumericNumberBuilder"); - } - static [entityKind] = "SQLiteNumericNumberBuilder"; - constructor(name) { - super(name, "number", "SQLiteNumericNumber"); - } - /** @internal */ - build(table) { - return new SQLiteNumericNumber( - table, - this.config - ); - } -}; -var SQLiteNumericNumber = class extends SQLiteColumn { - static { - __name(this, "SQLiteNumericNumber"); - } - static [entityKind] = "SQLiteNumericNumber"; - mapFromDriverValue(value) { - if (typeof value === "number") return value; - return Number(value); - } - mapToDriverValue = String; - getSQLType() { - return "numeric"; - } -}; -var SQLiteNumericBigIntBuilder = class extends SQLiteColumnBuilder { - static { - __name(this, "SQLiteNumericBigIntBuilder"); - } - static [entityKind] = "SQLiteNumericBigIntBuilder"; - constructor(name) { - super(name, "bigint", "SQLiteNumericBigInt"); - } - /** @internal */ - build(table) { - return new SQLiteNumericBigInt( - table, - this.config - ); - } -}; -var SQLiteNumericBigInt = class extends SQLiteColumn { - static { - __name(this, "SQLiteNumericBigInt"); - } - static [entityKind] = "SQLiteNumericBigInt"; - mapFromDriverValue = BigInt; - mapToDriverValue = String; - getSQLType() { - return "numeric"; - } -}; -function numeric(a, b) { - const { name, config: config2 } = getColumnNameAndConfig(a, b); - const mode = config2?.mode; - return mode === "number" ? new SQLiteNumericNumberBuilder(name) : mode === "bigint" ? new SQLiteNumericBigIntBuilder(name) : new SQLiteNumericBuilder(name); -} -__name(numeric, "numeric"); - -// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/sqlite-core/columns/real.js -init_modules_watch_stub(); -init_performance2(); -var SQLiteRealBuilder = class extends SQLiteColumnBuilder { - static { - __name(this, "SQLiteRealBuilder"); - } - static [entityKind] = "SQLiteRealBuilder"; - constructor(name) { - super(name, "number", "SQLiteReal"); - } - /** @internal */ - build(table) { - return new SQLiteReal(table, this.config); - } -}; -var SQLiteReal = class extends SQLiteColumn { - static { - __name(this, "SQLiteReal"); - } - static [entityKind] = "SQLiteReal"; - getSQLType() { - return "real"; - } -}; -function real(name) { - return new SQLiteRealBuilder(name ?? ""); -} -__name(real, "real"); - -// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/sqlite-core/columns/text.js -init_modules_watch_stub(); -init_performance2(); -var SQLiteTextBuilder = class extends SQLiteColumnBuilder { - static { - __name(this, "SQLiteTextBuilder"); - } - static [entityKind] = "SQLiteTextBuilder"; - constructor(name, config2) { - super(name, "string", "SQLiteText"); - this.config.enumValues = config2.enum; - this.config.length = config2.length; - } - /** @internal */ - build(table) { - return new SQLiteText( - table, - this.config - ); - } -}; -var SQLiteText = class extends SQLiteColumn { - static { - __name(this, "SQLiteText"); - } - static [entityKind] = "SQLiteText"; - enumValues = this.config.enumValues; - length = this.config.length; - constructor(table, config2) { - super(table, config2); - } - getSQLType() { - return `text${this.config.length ? `(${this.config.length})` : ""}`; - } -}; -var SQLiteTextJsonBuilder = class extends SQLiteColumnBuilder { - static { - __name(this, "SQLiteTextJsonBuilder"); - } - static [entityKind] = "SQLiteTextJsonBuilder"; - constructor(name) { - super(name, "json", "SQLiteTextJson"); - } - /** @internal */ - build(table) { - return new SQLiteTextJson( - table, - this.config - ); - } -}; -var SQLiteTextJson = class extends SQLiteColumn { - static { - __name(this, "SQLiteTextJson"); - } - static [entityKind] = "SQLiteTextJson"; - getSQLType() { - return "text"; - } - mapFromDriverValue(value) { - return JSON.parse(value); - } - mapToDriverValue(value) { - return JSON.stringify(value); - } -}; -function text(a, b = {}) { - const { name, config: config2 } = getColumnNameAndConfig(a, b); - if (config2.mode === "json") { - return new SQLiteTextJsonBuilder(name); - } - return new SQLiteTextBuilder(name, config2); -} -__name(text, "text"); - -// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/sqlite-core/columns/all.js -function getSQLiteColumnBuilders() { - return { - blob, - customType, - integer, - numeric, - real, - text - }; -} -__name(getSQLiteColumnBuilders, "getSQLiteColumnBuilders"); - -// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/sqlite-core/table.js -var InlineForeignKeys2 = /* @__PURE__ */ Symbol.for("drizzle:SQLiteInlineForeignKeys"); -var SQLiteTable = class extends Table { - static { - __name(this, "SQLiteTable"); - } - static [entityKind] = "SQLiteTable"; - /** @internal */ - static Symbol = Object.assign({}, Table.Symbol, { - InlineForeignKeys: InlineForeignKeys2 - }); - /** @internal */ - [Table.Symbol.Columns]; - /** @internal */ - [InlineForeignKeys2] = []; - /** @internal */ - [Table.Symbol.ExtraConfigBuilder] = void 0; -}; -function sqliteTableBase(name, columns, extraConfig, schema, baseName = name) { - const rawTable = new SQLiteTable(name, schema, baseName); - const parsedColumns = typeof columns === "function" ? columns(getSQLiteColumnBuilders()) : columns; - const builtColumns = Object.fromEntries( - Object.entries(parsedColumns).map(([name2, colBuilderBase]) => { - const colBuilder = colBuilderBase; - colBuilder.setName(name2); - const column = colBuilder.build(rawTable); - rawTable[InlineForeignKeys2].push(...colBuilder.buildForeignKeys(column, rawTable)); - return [name2, column]; - }) - ); - const table = Object.assign(rawTable, builtColumns); - table[Table.Symbol.Columns] = builtColumns; - table[Table.Symbol.ExtraConfigColumns] = builtColumns; - if (extraConfig) { - table[SQLiteTable.Symbol.ExtraConfigBuilder] = extraConfig; - } - return table; -} -__name(sqliteTableBase, "sqliteTableBase"); -var sqliteTable = /* @__PURE__ */ __name((name, columns, extraConfig) => { - return sqliteTableBase(name, columns, extraConfig); -}, "sqliteTable"); - -// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/sqlite-core/utils.js -init_modules_watch_stub(); -init_performance2(); -function extractUsedTable(table) { - if (is(table, SQLiteTable)) { - return [`${table[Table.Symbol.BaseName]}`]; - } - if (is(table, Subquery)) { - return table._.usedTables ?? []; - } - if (is(table, SQL)) { - return table.usedTables ?? []; - } - return []; -} -__name(extractUsedTable, "extractUsedTable"); - -// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/sqlite-core/query-builders/delete.js -var SQLiteDeleteBase = class extends QueryPromise { - static { - __name(this, "SQLiteDeleteBase"); - } - constructor(table, session2, dialect, withList) { - super(); - this.table = table; - this.session = session2; - this.dialect = dialect; - this.config = { table, withList }; - } - static [entityKind] = "SQLiteDelete"; - /** @internal */ - config; - /** - * Adds a `where` clause to the query. - * - * Calling this method will delete only those rows that fulfill a specified condition. - * - * See docs: {@link https://orm.drizzle.team/docs/delete} - * - * @param where the `where` clause. - * - * @example - * You can use conditional operators and `sql function` to filter the rows to be deleted. - * - * ```ts - * // Delete all cars with green color - * db.delete(cars).where(eq(cars.color, 'green')); - * // or - * db.delete(cars).where(sql`${cars.color} = 'green'`) - * ``` - * - * You can logically combine conditional operators with `and()` and `or()` operators: - * - * ```ts - * // Delete all BMW cars with a green color - * db.delete(cars).where(and(eq(cars.color, 'green'), eq(cars.brand, 'BMW'))); - * - * // Delete all cars with the green or blue color - * db.delete(cars).where(or(eq(cars.color, 'green'), eq(cars.color, 'blue'))); - * ``` - */ - where(where) { - this.config.where = where; - return this; - } - orderBy(...columns) { - if (typeof columns[0] === "function") { - const orderBy = columns[0]( - new Proxy( - this.config.table[Table.Symbol.Columns], - new SelectionProxyHandler({ sqlAliasedBehavior: "alias", sqlBehavior: "sql" }) - ) - ); - const orderByArray = Array.isArray(orderBy) ? orderBy : [orderBy]; - this.config.orderBy = orderByArray; - } else { - const orderByArray = columns; - this.config.orderBy = orderByArray; - } - return this; - } - limit(limit) { - this.config.limit = limit; - return this; - } - returning(fields = this.table[SQLiteTable.Symbol.Columns]) { - this.config.returning = orderSelectedFields(fields); - return this; - } - /** @internal */ - getSQL() { - return this.dialect.buildDeleteQuery(this.config); - } - toSQL() { - const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL()); - return rest; - } - /** @internal */ - _prepare(isOneTimeQuery = true) { - return this.session[isOneTimeQuery ? "prepareOneTimeQuery" : "prepareQuery"]( - this.dialect.sqlToQuery(this.getSQL()), - this.config.returning, - this.config.returning ? "all" : "run", - true, - void 0, - { - type: "delete", - tables: extractUsedTable(this.config.table) - } - ); - } - prepare() { - return this._prepare(false); - } - run = /* @__PURE__ */ __name((placeholderValues) => { - return this._prepare().run(placeholderValues); - }, "run"); - all = /* @__PURE__ */ __name((placeholderValues) => { - return this._prepare().all(placeholderValues); - }, "all"); - get = /* @__PURE__ */ __name((placeholderValues) => { - return this._prepare().get(placeholderValues); - }, "get"); - values = /* @__PURE__ */ __name((placeholderValues) => { - return this._prepare().values(placeholderValues); - }, "values"); - async execute(placeholderValues) { - return this._prepare().execute(placeholderValues); - } - $dynamic() { - return this; - } -}; - -// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/sqlite-core/query-builders/insert.js -init_modules_watch_stub(); -init_performance2(); - -// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/sqlite-core/query-builders/query-builder.js -init_modules_watch_stub(); -init_performance2(); - -// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/sqlite-core/dialect.js -init_modules_watch_stub(); -init_performance2(); - -// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/casing.js -init_modules_watch_stub(); -init_performance2(); -function toSnakeCase(input) { - const words = input.replace(/['\u2019]/g, "").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g) ?? []; - return words.map((word) => word.toLowerCase()).join("_"); -} -__name(toSnakeCase, "toSnakeCase"); -function toCamelCase(input) { - const words = input.replace(/['\u2019]/g, "").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g) ?? []; - return words.reduce((acc, word, i) => { - const formattedWord = i === 0 ? word.toLowerCase() : `${word[0].toUpperCase()}${word.slice(1)}`; - return acc + formattedWord; - }, ""); -} -__name(toCamelCase, "toCamelCase"); -function noopCase(input) { - return input; -} -__name(noopCase, "noopCase"); -var CasingCache = class { - static { - __name(this, "CasingCache"); - } - static [entityKind] = "CasingCache"; - /** @internal */ - cache = {}; - cachedTables = {}; - convert; - constructor(casing) { - this.convert = casing === "snake_case" ? toSnakeCase : casing === "camelCase" ? toCamelCase : noopCase; - } - getColumnCasing(column) { - if (!column.keyAsName) return column.name; - const schema = column.table[Table.Symbol.Schema] ?? "public"; - const tableName = column.table[Table.Symbol.OriginalName]; - const key = `${schema}.${tableName}.${column.name}`; - if (!this.cache[key]) { - this.cacheTable(column.table); - } - return this.cache[key]; - } - cacheTable(table) { - const schema = table[Table.Symbol.Schema] ?? "public"; - const tableName = table[Table.Symbol.OriginalName]; - const tableKey = `${schema}.${tableName}`; - if (!this.cachedTables[tableKey]) { - for (const column of Object.values(table[Table.Symbol.Columns])) { - const columnKey = `${tableKey}.${column.name}`; - this.cache[columnKey] = this.convert(column.name); - } - this.cachedTables[tableKey] = true; - } - } - clearCache() { - this.cache = {}; - this.cachedTables = {}; - } -}; - -// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/errors.js -init_modules_watch_stub(); -init_performance2(); -var DrizzleError = class extends Error { - static { - __name(this, "DrizzleError"); - } - static [entityKind] = "DrizzleError"; - constructor({ message, cause }) { - super(message); - this.name = "DrizzleError"; - this.cause = cause; - } -}; -var DrizzleQueryError = class _DrizzleQueryError extends Error { - static { - __name(this, "DrizzleQueryError"); - } - constructor(query, params, cause) { - super(`Failed query: ${query} -params: ${params}`); - this.query = query; - this.params = params; - this.cause = cause; - Error.captureStackTrace(this, _DrizzleQueryError); - if (cause) this.cause = cause; - } -}; -var TransactionRollbackError = class extends DrizzleError { - static { - __name(this, "TransactionRollbackError"); - } - static [entityKind] = "TransactionRollbackError"; - constructor() { - super({ message: "Rollback" }); - } -}; - -// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/sql/functions/aggregate.js -init_modules_watch_stub(); -init_performance2(); -function count(expression) { - return sql`count(${expression || sql.raw("*")})`.mapWith(Number); -} -__name(count, "count"); - -// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/sqlite-core/view-base.js -init_modules_watch_stub(); -init_performance2(); -var SQLiteViewBase = class extends View { - static { - __name(this, "SQLiteViewBase"); - } - static [entityKind] = "SQLiteViewBase"; -}; - -// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/sqlite-core/dialect.js -var SQLiteDialect = class { - static { - __name(this, "SQLiteDialect"); - } - static [entityKind] = "SQLiteDialect"; - /** @internal */ - casing; - constructor(config2) { - this.casing = new CasingCache(config2?.casing); - } - escapeName(name) { - return `"${name}"`; - } - escapeParam(_num) { - return "?"; - } - escapeString(str2) { - return `'${str2.replace(/'/g, "''")}'`; - } - buildWithCTE(queries) { - if (!queries?.length) return void 0; - const withSqlChunks = [sql`with `]; - for (const [i, w2] of queries.entries()) { - withSqlChunks.push(sql`${sql.identifier(w2._.alias)} as (${w2._.sql})`); - if (i < queries.length - 1) { - withSqlChunks.push(sql`, `); - } - } - withSqlChunks.push(sql` `); - return sql.join(withSqlChunks); - } - buildDeleteQuery({ table, where, returning, withList, limit, orderBy }) { - const withSql = this.buildWithCTE(withList); - const returningSql = returning ? sql` returning ${this.buildSelection(returning, { isSingleTable: true })}` : void 0; - const whereSql = where ? sql` where ${where}` : void 0; - const orderBySql = this.buildOrderBy(orderBy); - const limitSql = this.buildLimit(limit); - return sql`${withSql}delete from ${table}${whereSql}${returningSql}${orderBySql}${limitSql}`; - } - buildUpdateSet(table, set) { - const tableColumns = table[Table.Symbol.Columns]; - const columnNames = Object.keys(tableColumns).filter( - (colName) => set[colName] !== void 0 || tableColumns[colName]?.onUpdateFn !== void 0 - ); - const setSize = columnNames.length; - return sql.join(columnNames.flatMap((colName, i) => { - const col = tableColumns[colName]; - const onUpdateFnResult = col.onUpdateFn?.(); - const value = set[colName] ?? (is(onUpdateFnResult, SQL) ? onUpdateFnResult : sql.param(onUpdateFnResult, col)); - const res = sql`${sql.identifier(this.casing.getColumnCasing(col))} = ${value}`; - if (i < setSize - 1) { - return [res, sql.raw(", ")]; - } - return [res]; - })); - } - buildUpdateQuery({ table, set, where, returning, withList, joins, from, limit, orderBy }) { - const withSql = this.buildWithCTE(withList); - const setSql = this.buildUpdateSet(table, set); - const fromSql = from && sql.join([sql.raw(" from "), this.buildFromTable(from)]); - const joinsSql = this.buildJoins(joins); - const returningSql = returning ? sql` returning ${this.buildSelection(returning, { isSingleTable: true })}` : void 0; - const whereSql = where ? sql` where ${where}` : void 0; - const orderBySql = this.buildOrderBy(orderBy); - const limitSql = this.buildLimit(limit); - return sql`${withSql}update ${table} set ${setSql}${fromSql}${joinsSql}${whereSql}${returningSql}${orderBySql}${limitSql}`; - } - /** - * Builds selection SQL with provided fields/expressions - * - * Examples: - * - * `select from` - * - * `insert ... returning ` - * - * If `isSingleTable` is true, then columns won't be prefixed with table name - */ - buildSelection(fields, { isSingleTable = false } = {}) { - const columnsLen = fields.length; - const chunks = fields.flatMap(({ field }, i) => { - const chunk = []; - if (is(field, SQL.Aliased) && field.isSelectionField) { - chunk.push(sql.identifier(field.fieldAlias)); - } else if (is(field, SQL.Aliased) || is(field, SQL)) { - const query = is(field, SQL.Aliased) ? field.sql : field; - if (isSingleTable) { - chunk.push( - new SQL( - query.queryChunks.map((c) => { - if (is(c, Column)) { - return sql.identifier(this.casing.getColumnCasing(c)); - } - return c; - }) - ) - ); - } else { - chunk.push(query); - } - if (is(field, SQL.Aliased)) { - chunk.push(sql` as ${sql.identifier(field.fieldAlias)}`); - } - } else if (is(field, Column)) { - const tableName = field.table[Table.Symbol.Name]; - if (field.columnType === "SQLiteNumericBigInt") { - if (isSingleTable) { - chunk.push(sql`cast(${sql.identifier(this.casing.getColumnCasing(field))} as text)`); - } else { - chunk.push( - sql`cast(${sql.identifier(tableName)}.${sql.identifier(this.casing.getColumnCasing(field))} as text)` - ); - } - } else { - if (isSingleTable) { - chunk.push(sql.identifier(this.casing.getColumnCasing(field))); - } else { - chunk.push(sql`${sql.identifier(tableName)}.${sql.identifier(this.casing.getColumnCasing(field))}`); - } - } - } else if (is(field, Subquery)) { - const entries = Object.entries(field._.selectedFields); - if (entries.length === 1) { - const entry = entries[0][1]; - const fieldDecoder = is(entry, SQL) ? entry.decoder : is(entry, Column) ? { mapFromDriverValue: /* @__PURE__ */ __name((v) => entry.mapFromDriverValue(v), "mapFromDriverValue") } : entry.sql.decoder; - if (fieldDecoder) field._.sql.decoder = fieldDecoder; - } - chunk.push(field); - } - if (i < columnsLen - 1) { - chunk.push(sql`, `); - } - return chunk; - }); - return sql.join(chunks); - } - buildJoins(joins) { - if (!joins || joins.length === 0) { - return void 0; - } - const joinsArray = []; - if (joins) { - for (const [index, joinMeta] of joins.entries()) { - if (index === 0) { - joinsArray.push(sql` `); - } - const table = joinMeta.table; - const onSql = joinMeta.on ? sql` on ${joinMeta.on}` : void 0; - if (is(table, SQLiteTable)) { - const tableName = table[SQLiteTable.Symbol.Name]; - const tableSchema = table[SQLiteTable.Symbol.Schema]; - const origTableName = table[SQLiteTable.Symbol.OriginalName]; - const alias = tableName === origTableName ? void 0 : joinMeta.alias; - joinsArray.push( - sql`${sql.raw(joinMeta.joinType)} join ${tableSchema ? sql`${sql.identifier(tableSchema)}.` : void 0}${sql.identifier(origTableName)}${alias && sql` ${sql.identifier(alias)}`}${onSql}` - ); - } else { - joinsArray.push( - sql`${sql.raw(joinMeta.joinType)} join ${table}${onSql}` - ); - } - if (index < joins.length - 1) { - joinsArray.push(sql` `); - } - } - } - return sql.join(joinsArray); - } - buildLimit(limit) { - return typeof limit === "object" || typeof limit === "number" && limit >= 0 ? sql` limit ${limit}` : void 0; - } - buildOrderBy(orderBy) { - const orderByList = []; - if (orderBy) { - for (const [index, orderByValue] of orderBy.entries()) { - orderByList.push(orderByValue); - if (index < orderBy.length - 1) { - orderByList.push(sql`, `); - } - } - } - return orderByList.length > 0 ? sql` order by ${sql.join(orderByList)}` : void 0; - } - buildFromTable(table) { - if (is(table, Table) && table[Table.Symbol.IsAlias]) { - return sql`${sql`${sql.identifier(table[Table.Symbol.Schema] ?? "")}.`.if(table[Table.Symbol.Schema])}${sql.identifier(table[Table.Symbol.OriginalName])} ${sql.identifier(table[Table.Symbol.Name])}`; - } - return table; - } - buildSelectQuery({ - withList, - fields, - fieldsFlat, - where, - having, - table, - joins, - orderBy, - groupBy, - limit, - offset, - distinct, - setOperators - }) { - const fieldsList = fieldsFlat ?? orderSelectedFields(fields); - for (const f of fieldsList) { - if (is(f.field, Column) && getTableName(f.field.table) !== (is(table, Subquery) ? table._.alias : is(table, SQLiteViewBase) ? table[ViewBaseConfig].name : is(table, SQL) ? void 0 : getTableName(table)) && !((table2) => joins?.some( - ({ alias }) => alias === (table2[Table.Symbol.IsAlias] ? getTableName(table2) : table2[Table.Symbol.BaseName]) - ))(f.field.table)) { - const tableName = getTableName(f.field.table); - throw new Error( - `Your "${f.path.join("->")}" field references a column "${tableName}"."${f.field.name}", but the table "${tableName}" is not part of the query! Did you forget to join it?` - ); - } - } - const isSingleTable = !joins || joins.length === 0; - const withSql = this.buildWithCTE(withList); - const distinctSql = distinct ? sql` distinct` : void 0; - const selection = this.buildSelection(fieldsList, { isSingleTable }); - const tableSql = this.buildFromTable(table); - const joinsSql = this.buildJoins(joins); - const whereSql = where ? sql` where ${where}` : void 0; - const havingSql = having ? sql` having ${having}` : void 0; - const groupByList = []; - if (groupBy) { - for (const [index, groupByValue] of groupBy.entries()) { - groupByList.push(groupByValue); - if (index < groupBy.length - 1) { - groupByList.push(sql`, `); - } - } - } - const groupBySql = groupByList.length > 0 ? sql` group by ${sql.join(groupByList)}` : void 0; - const orderBySql = this.buildOrderBy(orderBy); - const limitSql = this.buildLimit(limit); - const offsetSql = offset ? sql` offset ${offset}` : void 0; - const finalQuery = sql`${withSql}select${distinctSql} ${selection} from ${tableSql}${joinsSql}${whereSql}${groupBySql}${havingSql}${orderBySql}${limitSql}${offsetSql}`; - if (setOperators.length > 0) { - return this.buildSetOperations(finalQuery, setOperators); - } - return finalQuery; - } - buildSetOperations(leftSelect, setOperators) { - const [setOperator, ...rest] = setOperators; - if (!setOperator) { - throw new Error("Cannot pass undefined values to any set operator"); - } - if (rest.length === 0) { - return this.buildSetOperationQuery({ leftSelect, setOperator }); - } - return this.buildSetOperations( - this.buildSetOperationQuery({ leftSelect, setOperator }), - rest - ); - } - buildSetOperationQuery({ - leftSelect, - setOperator: { type, isAll, rightSelect, limit, orderBy, offset } - }) { - const leftChunk = sql`${leftSelect.getSQL()} `; - const rightChunk = sql`${rightSelect.getSQL()}`; - let orderBySql; - if (orderBy && orderBy.length > 0) { - const orderByValues = []; - for (const singleOrderBy of orderBy) { - if (is(singleOrderBy, SQLiteColumn)) { - orderByValues.push(sql.identifier(singleOrderBy.name)); - } else if (is(singleOrderBy, SQL)) { - for (let i = 0; i < singleOrderBy.queryChunks.length; i++) { - const chunk = singleOrderBy.queryChunks[i]; - if (is(chunk, SQLiteColumn)) { - singleOrderBy.queryChunks[i] = sql.identifier(this.casing.getColumnCasing(chunk)); - } - } - orderByValues.push(sql`${singleOrderBy}`); - } else { - orderByValues.push(sql`${singleOrderBy}`); - } - } - orderBySql = sql` order by ${sql.join(orderByValues, sql`, `)}`; - } - const limitSql = typeof limit === "object" || typeof limit === "number" && limit >= 0 ? sql` limit ${limit}` : void 0; - const operatorChunk = sql.raw(`${type} ${isAll ? "all " : ""}`); - const offsetSql = offset ? sql` offset ${offset}` : void 0; - return sql`${leftChunk}${operatorChunk}${rightChunk}${orderBySql}${limitSql}${offsetSql}`; - } - buildInsertQuery({ table, values: valuesOrSelect, onConflict, returning, withList, select }) { - const valuesSqlList = []; - const columns = table[Table.Symbol.Columns]; - const colEntries = Object.entries(columns).filter( - ([_, col]) => !col.shouldDisableInsert() - ); - const insertOrder = colEntries.map(([, column]) => sql.identifier(this.casing.getColumnCasing(column))); - if (select) { - const select2 = valuesOrSelect; - if (is(select2, SQL)) { - valuesSqlList.push(select2); - } else { - valuesSqlList.push(select2.getSQL()); - } - } else { - const values = valuesOrSelect; - valuesSqlList.push(sql.raw("values ")); - for (const [valueIndex, value] of values.entries()) { - const valueList = []; - for (const [fieldName, col] of colEntries) { - const colValue = value[fieldName]; - if (colValue === void 0 || is(colValue, Param) && colValue.value === void 0) { - let defaultValue; - if (col.default !== null && col.default !== void 0) { - defaultValue = is(col.default, SQL) ? col.default : sql.param(col.default, col); - } else if (col.defaultFn !== void 0) { - const defaultFnResult = col.defaultFn(); - defaultValue = is(defaultFnResult, SQL) ? defaultFnResult : sql.param(defaultFnResult, col); - } else if (!col.default && col.onUpdateFn !== void 0) { - const onUpdateFnResult = col.onUpdateFn(); - defaultValue = is(onUpdateFnResult, SQL) ? onUpdateFnResult : sql.param(onUpdateFnResult, col); - } else { - defaultValue = sql`null`; - } - valueList.push(defaultValue); - } else { - valueList.push(colValue); - } - } - valuesSqlList.push(valueList); - if (valueIndex < values.length - 1) { - valuesSqlList.push(sql`, `); - } - } - } - const withSql = this.buildWithCTE(withList); - const valuesSql = sql.join(valuesSqlList); - const returningSql = returning ? sql` returning ${this.buildSelection(returning, { isSingleTable: true })}` : void 0; - const onConflictSql = onConflict?.length ? sql.join(onConflict) : void 0; - return sql`${withSql}insert into ${table} ${insertOrder} ${valuesSql}${onConflictSql}${returningSql}`; - } - sqlToQuery(sql2, invokeSource) { - return sql2.toQuery({ - casing: this.casing, - escapeName: this.escapeName, - escapeParam: this.escapeParam, - escapeString: this.escapeString, - invokeSource - }); - } - buildRelationalQuery({ - fullSchema, - schema, - tableNamesMap, - table, - tableConfig, - queryConfig: config2, - tableAlias, - nestedQueryRelation, - joinOn - }) { - let selection = []; - let limit, offset, orderBy = [], where; - const joins = []; - if (config2 === true) { - const selectionEntries = Object.entries(tableConfig.columns); - selection = selectionEntries.map(([key, value]) => ({ - dbKey: value.name, - tsKey: key, - field: aliasedTableColumn(value, tableAlias), - relationTableTsKey: void 0, - isJson: false, - selection: [] - })); - } else { - const aliasedColumns = Object.fromEntries( - Object.entries(tableConfig.columns).map(([key, value]) => [key, aliasedTableColumn(value, tableAlias)]) - ); - if (config2.where) { - const whereSql = typeof config2.where === "function" ? config2.where(aliasedColumns, getOperators()) : config2.where; - where = whereSql && mapColumnsInSQLToAlias(whereSql, tableAlias); - } - const fieldsSelection = []; - let selectedColumns = []; - if (config2.columns) { - let isIncludeMode = false; - for (const [field, value] of Object.entries(config2.columns)) { - if (value === void 0) { - continue; - } - if (field in tableConfig.columns) { - if (!isIncludeMode && value === true) { - isIncludeMode = true; - } - selectedColumns.push(field); - } - } - if (selectedColumns.length > 0) { - selectedColumns = isIncludeMode ? selectedColumns.filter((c) => config2.columns?.[c] === true) : Object.keys(tableConfig.columns).filter((key) => !selectedColumns.includes(key)); - } - } else { - selectedColumns = Object.keys(tableConfig.columns); - } - for (const field of selectedColumns) { - const column = tableConfig.columns[field]; - fieldsSelection.push({ tsKey: field, value: column }); - } - let selectedRelations = []; - if (config2.with) { - selectedRelations = Object.entries(config2.with).filter((entry) => !!entry[1]).map(([tsKey, queryConfig]) => ({ tsKey, queryConfig, relation: tableConfig.relations[tsKey] })); - } - let extras; - if (config2.extras) { - extras = typeof config2.extras === "function" ? config2.extras(aliasedColumns, { sql }) : config2.extras; - for (const [tsKey, value] of Object.entries(extras)) { - fieldsSelection.push({ - tsKey, - value: mapColumnsInAliasedSQLToAlias(value, tableAlias) - }); - } - } - for (const { tsKey, value } of fieldsSelection) { - selection.push({ - dbKey: is(value, SQL.Aliased) ? value.fieldAlias : tableConfig.columns[tsKey].name, - tsKey, - field: is(value, Column) ? aliasedTableColumn(value, tableAlias) : value, - relationTableTsKey: void 0, - isJson: false, - selection: [] - }); - } - let orderByOrig = typeof config2.orderBy === "function" ? config2.orderBy(aliasedColumns, getOrderByOperators()) : config2.orderBy ?? []; - if (!Array.isArray(orderByOrig)) { - orderByOrig = [orderByOrig]; - } - orderBy = orderByOrig.map((orderByValue) => { - if (is(orderByValue, Column)) { - return aliasedTableColumn(orderByValue, tableAlias); - } - return mapColumnsInSQLToAlias(orderByValue, tableAlias); - }); - limit = config2.limit; - offset = config2.offset; - for (const { - tsKey: selectedRelationTsKey, - queryConfig: selectedRelationConfigValue, - relation - } of selectedRelations) { - const normalizedRelation = normalizeRelation(schema, tableNamesMap, relation); - const relationTableName = getTableUniqueName(relation.referencedTable); - const relationTableTsName = tableNamesMap[relationTableName]; - const relationTableAlias = `${tableAlias}_${selectedRelationTsKey}`; - const joinOn2 = and( - ...normalizedRelation.fields.map( - (field2, i) => eq( - aliasedTableColumn(normalizedRelation.references[i], relationTableAlias), - aliasedTableColumn(field2, tableAlias) - ) - ) - ); - const builtRelation = this.buildRelationalQuery({ - fullSchema, - schema, - tableNamesMap, - table: fullSchema[relationTableTsName], - tableConfig: schema[relationTableTsName], - queryConfig: is(relation, One) ? selectedRelationConfigValue === true ? { limit: 1 } : { ...selectedRelationConfigValue, limit: 1 } : selectedRelationConfigValue, - tableAlias: relationTableAlias, - joinOn: joinOn2, - nestedQueryRelation: relation - }); - const field = sql`(${builtRelation.sql})`.as(selectedRelationTsKey); - selection.push({ - dbKey: selectedRelationTsKey, - tsKey: selectedRelationTsKey, - field, - relationTableTsKey: relationTableTsName, - isJson: true, - selection: builtRelation.selection - }); - } - } - if (selection.length === 0) { - throw new DrizzleError({ - message: `No fields selected for table "${tableConfig.tsName}" ("${tableAlias}"). You need to have at least one item in "columns", "with" or "extras". If you need to select all columns, omit the "columns" key or set it to undefined.` - }); - } - let result; - where = and(joinOn, where); - if (nestedQueryRelation) { - let field = sql`json_array(${sql.join( - selection.map( - ({ field: field2 }) => is(field2, SQLiteColumn) ? sql.identifier(this.casing.getColumnCasing(field2)) : is(field2, SQL.Aliased) ? field2.sql : field2 - ), - sql`, ` - )})`; - if (is(nestedQueryRelation, Many)) { - field = sql`coalesce(json_group_array(${field}), json_array())`; - } - const nestedSelection = [{ - dbKey: "data", - tsKey: "data", - field: field.as("data"), - isJson: true, - relationTableTsKey: tableConfig.tsName, - selection - }]; - const needsSubquery = limit !== void 0 || offset !== void 0 || orderBy.length > 0; - if (needsSubquery) { - result = this.buildSelectQuery({ - table: aliasedTable(table, tableAlias), - fields: {}, - fieldsFlat: [ - { - path: [], - field: sql.raw("*") - } - ], - where, - limit, - offset, - orderBy, - setOperators: [] - }); - where = void 0; - limit = void 0; - offset = void 0; - orderBy = void 0; - } else { - result = aliasedTable(table, tableAlias); - } - result = this.buildSelectQuery({ - table: is(result, SQLiteTable) ? result : new Subquery(result, {}, tableAlias), - fields: {}, - fieldsFlat: nestedSelection.map(({ field: field2 }) => ({ - path: [], - field: is(field2, Column) ? aliasedTableColumn(field2, tableAlias) : field2 - })), - joins, - where, - limit, - offset, - orderBy, - setOperators: [] - }); - } else { - result = this.buildSelectQuery({ - table: aliasedTable(table, tableAlias), - fields: {}, - fieldsFlat: selection.map(({ field }) => ({ - path: [], - field: is(field, Column) ? aliasedTableColumn(field, tableAlias) : field - })), - joins, - where, - limit, - offset, - orderBy, - setOperators: [] - }); - } - return { - tableTsKey: tableConfig.tsName, - sql: result, - selection - }; - } -}; -var SQLiteSyncDialect = class extends SQLiteDialect { - static { - __name(this, "SQLiteSyncDialect"); - } - static [entityKind] = "SQLiteSyncDialect"; - migrate(migrations, session2, config2) { - const migrationsTable = config2 === void 0 ? "__drizzle_migrations" : typeof config2 === "string" ? "__drizzle_migrations" : config2.migrationsTable ?? "__drizzle_migrations"; - const migrationTableCreate = sql` - CREATE TABLE IF NOT EXISTS ${sql.identifier(migrationsTable)} ( - id SERIAL PRIMARY KEY, - hash text NOT NULL, - created_at numeric - ) - `; - session2.run(migrationTableCreate); - const dbMigrations = session2.values( - sql`SELECT id, hash, created_at FROM ${sql.identifier(migrationsTable)} ORDER BY created_at DESC LIMIT 1` - ); - const lastDbMigration = dbMigrations[0] ?? void 0; - session2.run(sql`BEGIN`); - try { - for (const migration of migrations) { - if (!lastDbMigration || Number(lastDbMigration[2]) < migration.folderMillis) { - for (const stmt of migration.sql) { - session2.run(sql.raw(stmt)); - } - session2.run( - sql`INSERT INTO ${sql.identifier(migrationsTable)} ("hash", "created_at") VALUES(${migration.hash}, ${migration.folderMillis})` - ); - } - } - session2.run(sql`COMMIT`); - } catch (e) { - session2.run(sql`ROLLBACK`); - throw e; - } - } -}; -var SQLiteAsyncDialect = class extends SQLiteDialect { - static { - __name(this, "SQLiteAsyncDialect"); - } - static [entityKind] = "SQLiteAsyncDialect"; - async migrate(migrations, session2, config2) { - const migrationsTable = config2 === void 0 ? "__drizzle_migrations" : typeof config2 === "string" ? "__drizzle_migrations" : config2.migrationsTable ?? "__drizzle_migrations"; - const migrationTableCreate = sql` - CREATE TABLE IF NOT EXISTS ${sql.identifier(migrationsTable)} ( - id SERIAL PRIMARY KEY, - hash text NOT NULL, - created_at numeric - ) - `; - await session2.run(migrationTableCreate); - const dbMigrations = await session2.values( - sql`SELECT id, hash, created_at FROM ${sql.identifier(migrationsTable)} ORDER BY created_at DESC LIMIT 1` - ); - const lastDbMigration = dbMigrations[0] ?? void 0; - await session2.transaction(async (tx) => { - for (const migration of migrations) { - if (!lastDbMigration || Number(lastDbMigration[2]) < migration.folderMillis) { - for (const stmt of migration.sql) { - await tx.run(sql.raw(stmt)); - } - await tx.run( - sql`INSERT INTO ${sql.identifier(migrationsTable)} ("hash", "created_at") VALUES(${migration.hash}, ${migration.folderMillis})` - ); - } - } - }); - } -}; - -// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/sqlite-core/query-builders/select.js -init_modules_watch_stub(); -init_performance2(); - -// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/query-builders/query-builder.js -init_modules_watch_stub(); -init_performance2(); -var TypedQueryBuilder = class { - static { - __name(this, "TypedQueryBuilder"); - } - static [entityKind] = "TypedQueryBuilder"; - /** @internal */ - getSelectedFields() { - return this._.selectedFields; - } -}; - -// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/sqlite-core/query-builders/select.js -var SQLiteSelectBuilder = class { - static { - __name(this, "SQLiteSelectBuilder"); - } - static [entityKind] = "SQLiteSelectBuilder"; - fields; - session; - dialect; - withList; - distinct; - constructor(config2) { - this.fields = config2.fields; - this.session = config2.session; - this.dialect = config2.dialect; - this.withList = config2.withList; - this.distinct = config2.distinct; - } - from(source) { - const isPartialSelect = !!this.fields; - let fields; - if (this.fields) { - fields = this.fields; - } else if (is(source, Subquery)) { - fields = Object.fromEntries( - Object.keys(source._.selectedFields).map((key) => [key, source[key]]) - ); - } else if (is(source, SQLiteViewBase)) { - fields = source[ViewBaseConfig].selectedFields; - } else if (is(source, SQL)) { - fields = {}; - } else { - fields = getTableColumns(source); - } - return new SQLiteSelectBase({ - table: source, - fields, - isPartialSelect, - session: this.session, - dialect: this.dialect, - withList: this.withList, - distinct: this.distinct - }); - } -}; -var SQLiteSelectQueryBuilderBase = class extends TypedQueryBuilder { - static { - __name(this, "SQLiteSelectQueryBuilderBase"); - } - static [entityKind] = "SQLiteSelectQueryBuilder"; - _; - /** @internal */ - config; - joinsNotNullableMap; - tableName; - isPartialSelect; - session; - dialect; - cacheConfig = void 0; - usedTables = /* @__PURE__ */ new Set(); - constructor({ table, fields, isPartialSelect, session: session2, dialect, withList, distinct }) { - super(); - this.config = { - withList, - table, - fields: { ...fields }, - distinct, - setOperators: [] - }; - this.isPartialSelect = isPartialSelect; - this.session = session2; - this.dialect = dialect; - this._ = { - selectedFields: fields, - config: this.config - }; - this.tableName = getTableLikeName(table); - this.joinsNotNullableMap = typeof this.tableName === "string" ? { [this.tableName]: true } : {}; - for (const item of extractUsedTable(table)) this.usedTables.add(item); - } - /** @internal */ - getUsedTables() { - return [...this.usedTables]; - } - createJoin(joinType) { - return (table, on2) => { - const baseTableName = this.tableName; - const tableName = getTableLikeName(table); - for (const item of extractUsedTable(table)) this.usedTables.add(item); - if (typeof tableName === "string" && this.config.joins?.some((join) => join.alias === tableName)) { - throw new Error(`Alias "${tableName}" is already used in this query`); - } - if (!this.isPartialSelect) { - if (Object.keys(this.joinsNotNullableMap).length === 1 && typeof baseTableName === "string") { - this.config.fields = { - [baseTableName]: this.config.fields - }; - } - if (typeof tableName === "string" && !is(table, SQL)) { - const selection = is(table, Subquery) ? table._.selectedFields : is(table, View) ? table[ViewBaseConfig].selectedFields : table[Table.Symbol.Columns]; - this.config.fields[tableName] = selection; - } - } - if (typeof on2 === "function") { - on2 = on2( - new Proxy( - this.config.fields, - new SelectionProxyHandler({ sqlAliasedBehavior: "sql", sqlBehavior: "sql" }) - ) - ); - } - if (!this.config.joins) { - this.config.joins = []; - } - this.config.joins.push({ on: on2, table, joinType, alias: tableName }); - if (typeof tableName === "string") { - switch (joinType) { - case "left": { - this.joinsNotNullableMap[tableName] = false; - break; - } - case "right": { - this.joinsNotNullableMap = Object.fromEntries( - Object.entries(this.joinsNotNullableMap).map(([key]) => [key, false]) - ); - this.joinsNotNullableMap[tableName] = true; - break; - } - case "cross": - case "inner": { - this.joinsNotNullableMap[tableName] = true; - break; - } - case "full": { - this.joinsNotNullableMap = Object.fromEntries( - Object.entries(this.joinsNotNullableMap).map(([key]) => [key, false]) - ); - this.joinsNotNullableMap[tableName] = false; - break; - } - } - } - return this; - }; - } - /** - * Executes a `left join` operation by adding another table to the current query. - * - * Calling this method associates each row of the table with the corresponding row from the joined table, if a match is found. If no matching row exists, it sets all columns of the joined table to null. - * - * See docs: {@link https://orm.drizzle.team/docs/joins#left-join} - * - * @param table the table to join. - * @param on the `on` clause. - * - * @example - * - * ```ts - * // Select all users and their pets - * const usersWithPets: { user: User; pets: Pet | null; }[] = await db.select() - * .from(users) - * .leftJoin(pets, eq(users.id, pets.ownerId)) - * - * // Select userId and petId - * const usersIdsAndPetIds: { userId: number; petId: number | null; }[] = await db.select({ - * userId: users.id, - * petId: pets.id, - * }) - * .from(users) - * .leftJoin(pets, eq(users.id, pets.ownerId)) - * ``` - */ - leftJoin = this.createJoin("left"); - /** - * Executes a `right join` operation by adding another table to the current query. - * - * Calling this method associates each row of the joined table with the corresponding row from the main table, if a match is found. If no matching row exists, it sets all columns of the main table to null. - * - * See docs: {@link https://orm.drizzle.team/docs/joins#right-join} - * - * @param table the table to join. - * @param on the `on` clause. - * - * @example - * - * ```ts - * // Select all users and their pets - * const usersWithPets: { user: User | null; pets: Pet; }[] = await db.select() - * .from(users) - * .rightJoin(pets, eq(users.id, pets.ownerId)) - * - * // Select userId and petId - * const usersIdsAndPetIds: { userId: number | null; petId: number; }[] = await db.select({ - * userId: users.id, - * petId: pets.id, - * }) - * .from(users) - * .rightJoin(pets, eq(users.id, pets.ownerId)) - * ``` - */ - rightJoin = this.createJoin("right"); - /** - * Executes an `inner join` operation, creating a new table by combining rows from two tables that have matching values. - * - * Calling this method retrieves rows that have corresponding entries in both joined tables. Rows without matching entries in either table are excluded, resulting in a table that includes only matching pairs. - * - * See docs: {@link https://orm.drizzle.team/docs/joins#inner-join} - * - * @param table the table to join. - * @param on the `on` clause. - * - * @example - * - * ```ts - * // Select all users and their pets - * const usersWithPets: { user: User; pets: Pet; }[] = await db.select() - * .from(users) - * .innerJoin(pets, eq(users.id, pets.ownerId)) - * - * // Select userId and petId - * const usersIdsAndPetIds: { userId: number; petId: number; }[] = await db.select({ - * userId: users.id, - * petId: pets.id, - * }) - * .from(users) - * .innerJoin(pets, eq(users.id, pets.ownerId)) - * ``` - */ - innerJoin = this.createJoin("inner"); - /** - * Executes a `full join` operation by combining rows from two tables into a new table. - * - * Calling this method retrieves all rows from both main and joined tables, merging rows with matching values and filling in `null` for non-matching columns. - * - * See docs: {@link https://orm.drizzle.team/docs/joins#full-join} - * - * @param table the table to join. - * @param on the `on` clause. - * - * @example - * - * ```ts - * // Select all users and their pets - * const usersWithPets: { user: User | null; pets: Pet | null; }[] = await db.select() - * .from(users) - * .fullJoin(pets, eq(users.id, pets.ownerId)) - * - * // Select userId and petId - * const usersIdsAndPetIds: { userId: number | null; petId: number | null; }[] = await db.select({ - * userId: users.id, - * petId: pets.id, - * }) - * .from(users) - * .fullJoin(pets, eq(users.id, pets.ownerId)) - * ``` - */ - fullJoin = this.createJoin("full"); - /** - * Executes a `cross join` operation by combining rows from two tables into a new table. - * - * Calling this method retrieves all rows from both main and joined tables, merging all rows from each table. - * - * See docs: {@link https://orm.drizzle.team/docs/joins#cross-join} - * - * @param table the table to join. - * - * @example - * - * ```ts - * // Select all users, each user with every pet - * const usersWithPets: { user: User; pets: Pet; }[] = await db.select() - * .from(users) - * .crossJoin(pets) - * - * // Select userId and petId - * const usersIdsAndPetIds: { userId: number; petId: number; }[] = await db.select({ - * userId: users.id, - * petId: pets.id, - * }) - * .from(users) - * .crossJoin(pets) - * ``` - */ - crossJoin = this.createJoin("cross"); - createSetOperator(type, isAll) { - return (rightSelection) => { - const rightSelect = typeof rightSelection === "function" ? rightSelection(getSQLiteSetOperators()) : rightSelection; - if (!haveSameKeys(this.getSelectedFields(), rightSelect.getSelectedFields())) { - throw new Error( - "Set operator error (union / intersect / except): selected fields are not the same or are in a different order" - ); - } - this.config.setOperators.push({ type, isAll, rightSelect }); - return this; - }; - } - /** - * Adds `union` set operator to the query. - * - * Calling this method will combine the result sets of the `select` statements and remove any duplicate rows that appear across them. - * - * See docs: {@link https://orm.drizzle.team/docs/set-operations#union} - * - * @example - * - * ```ts - * // Select all unique names from customers and users tables - * await db.select({ name: users.name }) - * .from(users) - * .union( - * db.select({ name: customers.name }).from(customers) - * ); - * // or - * import { union } from 'drizzle-orm/sqlite-core' - * - * await union( - * db.select({ name: users.name }).from(users), - * db.select({ name: customers.name }).from(customers) - * ); - * ``` - */ - union = this.createSetOperator("union", false); - /** - * Adds `union all` set operator to the query. - * - * Calling this method will combine the result-set of the `select` statements and keep all duplicate rows that appear across them. - * - * See docs: {@link https://orm.drizzle.team/docs/set-operations#union-all} - * - * @example - * - * ```ts - * // Select all transaction ids from both online and in-store sales - * await db.select({ transaction: onlineSales.transactionId }) - * .from(onlineSales) - * .unionAll( - * db.select({ transaction: inStoreSales.transactionId }).from(inStoreSales) - * ); - * // or - * import { unionAll } from 'drizzle-orm/sqlite-core' - * - * await unionAll( - * db.select({ transaction: onlineSales.transactionId }).from(onlineSales), - * db.select({ transaction: inStoreSales.transactionId }).from(inStoreSales) - * ); - * ``` - */ - unionAll = this.createSetOperator("union", true); - /** - * Adds `intersect` set operator to the query. - * - * Calling this method will retain only the rows that are present in both result sets and eliminate duplicates. - * - * See docs: {@link https://orm.drizzle.team/docs/set-operations#intersect} - * - * @example - * - * ```ts - * // Select course names that are offered in both departments A and B - * await db.select({ courseName: depA.courseName }) - * .from(depA) - * .intersect( - * db.select({ courseName: depB.courseName }).from(depB) - * ); - * // or - * import { intersect } from 'drizzle-orm/sqlite-core' - * - * await intersect( - * db.select({ courseName: depA.courseName }).from(depA), - * db.select({ courseName: depB.courseName }).from(depB) - * ); - * ``` - */ - intersect = this.createSetOperator("intersect", false); - /** - * Adds `except` set operator to the query. - * - * Calling this method will retrieve all unique rows from the left query, except for the rows that are present in the result set of the right query. - * - * See docs: {@link https://orm.drizzle.team/docs/set-operations#except} - * - * @example - * - * ```ts - * // Select all courses offered in department A but not in department B - * await db.select({ courseName: depA.courseName }) - * .from(depA) - * .except( - * db.select({ courseName: depB.courseName }).from(depB) - * ); - * // or - * import { except } from 'drizzle-orm/sqlite-core' - * - * await except( - * db.select({ courseName: depA.courseName }).from(depA), - * db.select({ courseName: depB.courseName }).from(depB) - * ); - * ``` - */ - except = this.createSetOperator("except", false); - /** @internal */ - addSetOperators(setOperators) { - this.config.setOperators.push(...setOperators); - return this; - } - /** - * Adds a `where` clause to the query. - * - * Calling this method will select only those rows that fulfill a specified condition. - * - * See docs: {@link https://orm.drizzle.team/docs/select#filtering} - * - * @param where the `where` clause. - * - * @example - * You can use conditional operators and `sql function` to filter the rows to be selected. - * - * ```ts - * // Select all cars with green color - * await db.select().from(cars).where(eq(cars.color, 'green')); - * // or - * await db.select().from(cars).where(sql`${cars.color} = 'green'`) - * ``` - * - * You can logically combine conditional operators with `and()` and `or()` operators: - * - * ```ts - * // Select all BMW cars with a green color - * await db.select().from(cars).where(and(eq(cars.color, 'green'), eq(cars.brand, 'BMW'))); - * - * // Select all cars with the green or blue color - * await db.select().from(cars).where(or(eq(cars.color, 'green'), eq(cars.color, 'blue'))); - * ``` - */ - where(where) { - if (typeof where === "function") { - where = where( - new Proxy( - this.config.fields, - new SelectionProxyHandler({ sqlAliasedBehavior: "sql", sqlBehavior: "sql" }) - ) - ); - } - this.config.where = where; - return this; - } - /** - * Adds a `having` clause to the query. - * - * Calling this method will select only those rows that fulfill a specified condition. It is typically used with aggregate functions to filter the aggregated data based on a specified condition. - * - * See docs: {@link https://orm.drizzle.team/docs/select#aggregations} - * - * @param having the `having` clause. - * - * @example - * - * ```ts - * // Select all brands with more than one car - * await db.select({ - * brand: cars.brand, - * count: sql`cast(count(${cars.id}) as int)`, - * }) - * .from(cars) - * .groupBy(cars.brand) - * .having(({ count }) => gt(count, 1)); - * ``` - */ - having(having) { - if (typeof having === "function") { - having = having( - new Proxy( - this.config.fields, - new SelectionProxyHandler({ sqlAliasedBehavior: "sql", sqlBehavior: "sql" }) - ) - ); - } - this.config.having = having; - return this; - } - groupBy(...columns) { - if (typeof columns[0] === "function") { - const groupBy = columns[0]( - new Proxy( - this.config.fields, - new SelectionProxyHandler({ sqlAliasedBehavior: "alias", sqlBehavior: "sql" }) - ) - ); - this.config.groupBy = Array.isArray(groupBy) ? groupBy : [groupBy]; - } else { - this.config.groupBy = columns; - } - return this; - } - orderBy(...columns) { - if (typeof columns[0] === "function") { - const orderBy = columns[0]( - new Proxy( - this.config.fields, - new SelectionProxyHandler({ sqlAliasedBehavior: "alias", sqlBehavior: "sql" }) - ) - ); - const orderByArray = Array.isArray(orderBy) ? orderBy : [orderBy]; - if (this.config.setOperators.length > 0) { - this.config.setOperators.at(-1).orderBy = orderByArray; - } else { - this.config.orderBy = orderByArray; - } - } else { - const orderByArray = columns; - if (this.config.setOperators.length > 0) { - this.config.setOperators.at(-1).orderBy = orderByArray; - } else { - this.config.orderBy = orderByArray; - } - } - return this; - } - /** - * Adds a `limit` clause to the query. - * - * Calling this method will set the maximum number of rows that will be returned by this query. - * - * See docs: {@link https://orm.drizzle.team/docs/select#limit--offset} - * - * @param limit the `limit` clause. - * - * @example - * - * ```ts - * // Get the first 10 people from this query. - * await db.select().from(people).limit(10); - * ``` - */ - limit(limit) { - if (this.config.setOperators.length > 0) { - this.config.setOperators.at(-1).limit = limit; - } else { - this.config.limit = limit; - } - return this; - } - /** - * Adds an `offset` clause to the query. - * - * Calling this method will skip a number of rows when returning results from this query. - * - * See docs: {@link https://orm.drizzle.team/docs/select#limit--offset} - * - * @param offset the `offset` clause. - * - * @example - * - * ```ts - * // Get the 10th-20th people from this query. - * await db.select().from(people).offset(10).limit(10); - * ``` - */ - offset(offset) { - if (this.config.setOperators.length > 0) { - this.config.setOperators.at(-1).offset = offset; - } else { - this.config.offset = offset; - } - return this; - } - /** @internal */ - getSQL() { - return this.dialect.buildSelectQuery(this.config); - } - toSQL() { - const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL()); - return rest; - } - as(alias) { - const usedTables = []; - usedTables.push(...extractUsedTable(this.config.table)); - if (this.config.joins) { - for (const it of this.config.joins) usedTables.push(...extractUsedTable(it.table)); - } - return new Proxy( - new Subquery(this.getSQL(), this.config.fields, alias, false, [...new Set(usedTables)]), - new SelectionProxyHandler({ alias, sqlAliasedBehavior: "alias", sqlBehavior: "error" }) - ); - } - /** @internal */ - getSelectedFields() { - return new Proxy( - this.config.fields, - new SelectionProxyHandler({ alias: this.tableName, sqlAliasedBehavior: "alias", sqlBehavior: "error" }) - ); - } - $dynamic() { - return this; - } -}; -var SQLiteSelectBase = class extends SQLiteSelectQueryBuilderBase { - static { - __name(this, "SQLiteSelectBase"); - } - static [entityKind] = "SQLiteSelect"; - /** @internal */ - _prepare(isOneTimeQuery = true) { - if (!this.session) { - throw new Error("Cannot execute a query on a query builder. Please use a database instance instead."); - } - const fieldsList = orderSelectedFields(this.config.fields); - const query = this.session[isOneTimeQuery ? "prepareOneTimeQuery" : "prepareQuery"]( - this.dialect.sqlToQuery(this.getSQL()), - fieldsList, - "all", - true, - void 0, - { - type: "select", - tables: [...this.usedTables] - }, - this.cacheConfig - ); - query.joinsNotNullableMap = this.joinsNotNullableMap; - return query; - } - $withCache(config2) { - this.cacheConfig = config2 === void 0 ? { config: {}, enable: true, autoInvalidate: true } : config2 === false ? { enable: false } : { enable: true, autoInvalidate: true, ...config2 }; - return this; - } - prepare() { - return this._prepare(false); - } - run = /* @__PURE__ */ __name((placeholderValues) => { - return this._prepare().run(placeholderValues); - }, "run"); - all = /* @__PURE__ */ __name((placeholderValues) => { - return this._prepare().all(placeholderValues); - }, "all"); - get = /* @__PURE__ */ __name((placeholderValues) => { - return this._prepare().get(placeholderValues); - }, "get"); - values = /* @__PURE__ */ __name((placeholderValues) => { - return this._prepare().values(placeholderValues); - }, "values"); - async execute() { - return this.all(); - } -}; -applyMixins(SQLiteSelectBase, [QueryPromise]); -function createSetOperator(type, isAll) { - return (leftSelect, rightSelect, ...restSelects) => { - const setOperators = [rightSelect, ...restSelects].map((select) => ({ - type, - isAll, - rightSelect: select - })); - for (const setOperator of setOperators) { - if (!haveSameKeys(leftSelect.getSelectedFields(), setOperator.rightSelect.getSelectedFields())) { - throw new Error( - "Set operator error (union / intersect / except): selected fields are not the same or are in a different order" - ); - } - } - return leftSelect.addSetOperators(setOperators); - }; -} -__name(createSetOperator, "createSetOperator"); -var getSQLiteSetOperators = /* @__PURE__ */ __name(() => ({ - union, - unionAll, - intersect, - except -}), "getSQLiteSetOperators"); -var union = createSetOperator("union", false); -var unionAll = createSetOperator("union", true); -var intersect = createSetOperator("intersect", false); -var except = createSetOperator("except", false); - -// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/sqlite-core/query-builders/query-builder.js -var QueryBuilder = class { - static { - __name(this, "QueryBuilder"); - } - static [entityKind] = "SQLiteQueryBuilder"; - dialect; - dialectConfig; - constructor(dialect) { - this.dialect = is(dialect, SQLiteDialect) ? dialect : void 0; - this.dialectConfig = is(dialect, SQLiteDialect) ? void 0 : dialect; - } - $with = /* @__PURE__ */ __name((alias, selection) => { - const queryBuilder = this; - const as = /* @__PURE__ */ __name((qb) => { - if (typeof qb === "function") { - qb = qb(queryBuilder); - } - return new Proxy( - new WithSubquery( - qb.getSQL(), - selection ?? ("getSelectedFields" in qb ? qb.getSelectedFields() ?? {} : {}), - alias, - true - ), - new SelectionProxyHandler({ alias, sqlAliasedBehavior: "alias", sqlBehavior: "error" }) - ); - }, "as"); - return { as }; - }, "$with"); - with(...queries) { - const self2 = this; - function select(fields) { - return new SQLiteSelectBuilder({ - fields: fields ?? void 0, - session: void 0, - dialect: self2.getDialect(), - withList: queries - }); - } - __name(select, "select"); - function selectDistinct(fields) { - return new SQLiteSelectBuilder({ - fields: fields ?? void 0, - session: void 0, - dialect: self2.getDialect(), - withList: queries, - distinct: true - }); - } - __name(selectDistinct, "selectDistinct"); - return { select, selectDistinct }; - } - select(fields) { - return new SQLiteSelectBuilder({ fields: fields ?? void 0, session: void 0, dialect: this.getDialect() }); - } - selectDistinct(fields) { - return new SQLiteSelectBuilder({ - fields: fields ?? void 0, - session: void 0, - dialect: this.getDialect(), - distinct: true - }); - } - // Lazy load dialect to avoid circular dependency - getDialect() { - if (!this.dialect) { - this.dialect = new SQLiteSyncDialect(this.dialectConfig); - } - return this.dialect; - } -}; - -// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/sqlite-core/query-builders/insert.js -var SQLiteInsertBuilder = class { - static { - __name(this, "SQLiteInsertBuilder"); - } - constructor(table, session2, dialect, withList) { - this.table = table; - this.session = session2; - this.dialect = dialect; - this.withList = withList; - } - static [entityKind] = "SQLiteInsertBuilder"; - values(values) { - values = Array.isArray(values) ? values : [values]; - if (values.length === 0) { - throw new Error("values() must be called with at least one value"); - } - const mappedValues = values.map((entry) => { - const result = {}; - const cols = this.table[Table.Symbol.Columns]; - for (const colKey of Object.keys(entry)) { - const colValue = entry[colKey]; - result[colKey] = is(colValue, SQL) ? colValue : new Param(colValue, cols[colKey]); - } - return result; - }); - return new SQLiteInsertBase(this.table, mappedValues, this.session, this.dialect, this.withList); - } - select(selectQuery) { - const select = typeof selectQuery === "function" ? selectQuery(new QueryBuilder()) : selectQuery; - if (!is(select, SQL) && !haveSameKeys(this.table[Columns], select._.selectedFields)) { - throw new Error( - "Insert select error: selected fields are not the same or are in a different order compared to the table definition" - ); - } - return new SQLiteInsertBase(this.table, select, this.session, this.dialect, this.withList, true); - } -}; -var SQLiteInsertBase = class extends QueryPromise { - static { - __name(this, "SQLiteInsertBase"); - } - constructor(table, values, session2, dialect, withList, select) { - super(); - this.session = session2; - this.dialect = dialect; - this.config = { table, values, withList, select }; - } - static [entityKind] = "SQLiteInsert"; - /** @internal */ - config; - returning(fields = this.config.table[SQLiteTable.Symbol.Columns]) { - this.config.returning = orderSelectedFields(fields); - return this; - } - /** - * Adds an `on conflict do nothing` clause to the query. - * - * Calling this method simply avoids inserting a row as its alternative action. - * - * See docs: {@link https://orm.drizzle.team/docs/insert#on-conflict-do-nothing} - * - * @param config The `target` and `where` clauses. - * - * @example - * ```ts - * // Insert one row and cancel the insert if there's a conflict - * await db.insert(cars) - * .values({ id: 1, brand: 'BMW' }) - * .onConflictDoNothing(); - * - * // Explicitly specify conflict target - * await db.insert(cars) - * .values({ id: 1, brand: 'BMW' }) - * .onConflictDoNothing({ target: cars.id }); - * ``` - */ - onConflictDoNothing(config2 = {}) { - if (!this.config.onConflict) this.config.onConflict = []; - if (config2.target === void 0) { - this.config.onConflict.push(sql` on conflict do nothing`); - } else { - const targetSql = Array.isArray(config2.target) ? sql`${config2.target}` : sql`${[config2.target]}`; - const whereSql = config2.where ? sql` where ${config2.where}` : sql``; - this.config.onConflict.push(sql` on conflict ${targetSql} do nothing${whereSql}`); - } - return this; - } - /** - * Adds an `on conflict do update` clause to the query. - * - * Calling this method will update the existing row that conflicts with the row proposed for insertion as its alternative action. - * - * See docs: {@link https://orm.drizzle.team/docs/insert#upserts-and-conflicts} - * - * @param config The `target`, `set` and `where` clauses. - * - * @example - * ```ts - * // Update the row if there's a conflict - * await db.insert(cars) - * .values({ id: 1, brand: 'BMW' }) - * .onConflictDoUpdate({ - * target: cars.id, - * set: { brand: 'Porsche' } - * }); - * - * // Upsert with 'where' clause - * await db.insert(cars) - * .values({ id: 1, brand: 'BMW' }) - * .onConflictDoUpdate({ - * target: cars.id, - * set: { brand: 'newBMW' }, - * where: sql`${cars.createdAt} > '2023-01-01'::date`, - * }); - * ``` - */ - onConflictDoUpdate(config2) { - if (config2.where && (config2.targetWhere || config2.setWhere)) { - throw new Error( - 'You cannot use both "where" and "targetWhere"/"setWhere" at the same time - "where" is deprecated, use "targetWhere" or "setWhere" instead.' - ); - } - if (!this.config.onConflict) this.config.onConflict = []; - const whereSql = config2.where ? sql` where ${config2.where}` : void 0; - const targetWhereSql = config2.targetWhere ? sql` where ${config2.targetWhere}` : void 0; - const setWhereSql = config2.setWhere ? sql` where ${config2.setWhere}` : void 0; - const targetSql = Array.isArray(config2.target) ? sql`${config2.target}` : sql`${[config2.target]}`; - const setSql = this.dialect.buildUpdateSet(this.config.table, mapUpdateSet(this.config.table, config2.set)); - this.config.onConflict.push( - sql` on conflict ${targetSql}${targetWhereSql} do update set ${setSql}${whereSql}${setWhereSql}` - ); - return this; - } - /** @internal */ - getSQL() { - return this.dialect.buildInsertQuery(this.config); - } - toSQL() { - const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL()); - return rest; - } - /** @internal */ - _prepare(isOneTimeQuery = true) { - return this.session[isOneTimeQuery ? "prepareOneTimeQuery" : "prepareQuery"]( - this.dialect.sqlToQuery(this.getSQL()), - this.config.returning, - this.config.returning ? "all" : "run", - true, - void 0, - { - type: "insert", - tables: extractUsedTable(this.config.table) - } - ); - } - prepare() { - return this._prepare(false); - } - run = /* @__PURE__ */ __name((placeholderValues) => { - return this._prepare().run(placeholderValues); - }, "run"); - all = /* @__PURE__ */ __name((placeholderValues) => { - return this._prepare().all(placeholderValues); - }, "all"); - get = /* @__PURE__ */ __name((placeholderValues) => { - return this._prepare().get(placeholderValues); - }, "get"); - values = /* @__PURE__ */ __name((placeholderValues) => { - return this._prepare().values(placeholderValues); - }, "values"); - async execute() { - return this.config.returning ? this.all() : this.run(); - } - $dynamic() { - return this; - } -}; - -// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/sqlite-core/query-builders/update.js -init_modules_watch_stub(); -init_performance2(); -var SQLiteUpdateBuilder = class { - static { - __name(this, "SQLiteUpdateBuilder"); - } - constructor(table, session2, dialect, withList) { - this.table = table; - this.session = session2; - this.dialect = dialect; - this.withList = withList; - } - static [entityKind] = "SQLiteUpdateBuilder"; - set(values) { - return new SQLiteUpdateBase( - this.table, - mapUpdateSet(this.table, values), - this.session, - this.dialect, - this.withList - ); - } -}; -var SQLiteUpdateBase = class extends QueryPromise { - static { - __name(this, "SQLiteUpdateBase"); - } - constructor(table, set, session2, dialect, withList) { - super(); - this.session = session2; - this.dialect = dialect; - this.config = { set, table, withList, joins: [] }; - } - static [entityKind] = "SQLiteUpdate"; - /** @internal */ - config; - from(source) { - this.config.from = source; - return this; - } - createJoin(joinType) { - return (table, on2) => { - const tableName = getTableLikeName(table); - if (typeof tableName === "string" && this.config.joins.some((join) => join.alias === tableName)) { - throw new Error(`Alias "${tableName}" is already used in this query`); - } - if (typeof on2 === "function") { - const from = this.config.from ? is(table, SQLiteTable) ? table[Table.Symbol.Columns] : is(table, Subquery) ? table._.selectedFields : is(table, SQLiteViewBase) ? table[ViewBaseConfig].selectedFields : void 0 : void 0; - on2 = on2( - new Proxy( - this.config.table[Table.Symbol.Columns], - new SelectionProxyHandler({ sqlAliasedBehavior: "sql", sqlBehavior: "sql" }) - ), - from && new Proxy( - from, - new SelectionProxyHandler({ sqlAliasedBehavior: "sql", sqlBehavior: "sql" }) - ) - ); - } - this.config.joins.push({ on: on2, table, joinType, alias: tableName }); - return this; - }; - } - leftJoin = this.createJoin("left"); - rightJoin = this.createJoin("right"); - innerJoin = this.createJoin("inner"); - fullJoin = this.createJoin("full"); - /** - * Adds a 'where' clause to the query. - * - * Calling this method will update only those rows that fulfill a specified condition. - * - * See docs: {@link https://orm.drizzle.team/docs/update} - * - * @param where the 'where' clause. - * - * @example - * You can use conditional operators and `sql function` to filter the rows to be updated. - * - * ```ts - * // Update all cars with green color - * db.update(cars).set({ color: 'red' }) - * .where(eq(cars.color, 'green')); - * // or - * db.update(cars).set({ color: 'red' }) - * .where(sql`${cars.color} = 'green'`) - * ``` - * - * You can logically combine conditional operators with `and()` and `or()` operators: - * - * ```ts - * // Update all BMW cars with a green color - * db.update(cars).set({ color: 'red' }) - * .where(and(eq(cars.color, 'green'), eq(cars.brand, 'BMW'))); - * - * // Update all cars with the green or blue color - * db.update(cars).set({ color: 'red' }) - * .where(or(eq(cars.color, 'green'), eq(cars.color, 'blue'))); - * ``` - */ - where(where) { - this.config.where = where; - return this; - } - orderBy(...columns) { - if (typeof columns[0] === "function") { - const orderBy = columns[0]( - new Proxy( - this.config.table[Table.Symbol.Columns], - new SelectionProxyHandler({ sqlAliasedBehavior: "alias", sqlBehavior: "sql" }) - ) - ); - const orderByArray = Array.isArray(orderBy) ? orderBy : [orderBy]; - this.config.orderBy = orderByArray; - } else { - const orderByArray = columns; - this.config.orderBy = orderByArray; - } - return this; - } - limit(limit) { - this.config.limit = limit; - return this; - } - returning(fields = this.config.table[SQLiteTable.Symbol.Columns]) { - this.config.returning = orderSelectedFields(fields); - return this; - } - /** @internal */ - getSQL() { - return this.dialect.buildUpdateQuery(this.config); - } - toSQL() { - const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL()); - return rest; - } - /** @internal */ - _prepare(isOneTimeQuery = true) { - return this.session[isOneTimeQuery ? "prepareOneTimeQuery" : "prepareQuery"]( - this.dialect.sqlToQuery(this.getSQL()), - this.config.returning, - this.config.returning ? "all" : "run", - true, - void 0, - { - type: "insert", - tables: extractUsedTable(this.config.table) - } - ); - } - prepare() { - return this._prepare(false); - } - run = /* @__PURE__ */ __name((placeholderValues) => { - return this._prepare().run(placeholderValues); - }, "run"); - all = /* @__PURE__ */ __name((placeholderValues) => { - return this._prepare().all(placeholderValues); - }, "all"); - get = /* @__PURE__ */ __name((placeholderValues) => { - return this._prepare().get(placeholderValues); - }, "get"); - values = /* @__PURE__ */ __name((placeholderValues) => { - return this._prepare().values(placeholderValues); - }, "values"); - async execute() { - return this.config.returning ? this.all() : this.run(); - } - $dynamic() { - return this; - } -}; - -// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/sqlite-core/query-builders/count.js -init_modules_watch_stub(); -init_performance2(); -var SQLiteCountBuilder = class _SQLiteCountBuilder extends SQL { - static { - __name(this, "SQLiteCountBuilder"); - } - constructor(params) { - super(_SQLiteCountBuilder.buildEmbeddedCount(params.source, params.filters).queryChunks); - this.params = params; - this.session = params.session; - this.sql = _SQLiteCountBuilder.buildCount( - params.source, - params.filters - ); - } - sql; - static [entityKind] = "SQLiteCountBuilderAsync"; - [Symbol.toStringTag] = "SQLiteCountBuilderAsync"; - session; - static buildEmbeddedCount(source, filters) { - return sql`(select count(*) from ${source}${sql.raw(" where ").if(filters)}${filters})`; - } - static buildCount(source, filters) { - return sql`select count(*) from ${source}${sql.raw(" where ").if(filters)}${filters}`; - } - then(onfulfilled, onrejected) { - return Promise.resolve(this.session.count(this.sql)).then( - onfulfilled, - onrejected - ); - } - catch(onRejected) { - return this.then(void 0, onRejected); - } - finally(onFinally) { - return this.then( - (value) => { - onFinally?.(); - return value; - }, - (reason) => { - onFinally?.(); - throw reason; - } - ); - } -}; - -// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/sqlite-core/query-builders/query.js -init_modules_watch_stub(); -init_performance2(); -var RelationalQueryBuilder = class { - static { - __name(this, "RelationalQueryBuilder"); - } - constructor(mode, fullSchema, schema, tableNamesMap, table, tableConfig, dialect, session2) { - this.mode = mode; - this.fullSchema = fullSchema; - this.schema = schema; - this.tableNamesMap = tableNamesMap; - this.table = table; - this.tableConfig = tableConfig; - this.dialect = dialect; - this.session = session2; - } - static [entityKind] = "SQLiteAsyncRelationalQueryBuilder"; - findMany(config2) { - return this.mode === "sync" ? new SQLiteSyncRelationalQuery( - this.fullSchema, - this.schema, - this.tableNamesMap, - this.table, - this.tableConfig, - this.dialect, - this.session, - config2 ? config2 : {}, - "many" - ) : new SQLiteRelationalQuery( - this.fullSchema, - this.schema, - this.tableNamesMap, - this.table, - this.tableConfig, - this.dialect, - this.session, - config2 ? config2 : {}, - "many" - ); - } - findFirst(config2) { - return this.mode === "sync" ? new SQLiteSyncRelationalQuery( - this.fullSchema, - this.schema, - this.tableNamesMap, - this.table, - this.tableConfig, - this.dialect, - this.session, - config2 ? { ...config2, limit: 1 } : { limit: 1 }, - "first" - ) : new SQLiteRelationalQuery( - this.fullSchema, - this.schema, - this.tableNamesMap, - this.table, - this.tableConfig, - this.dialect, - this.session, - config2 ? { ...config2, limit: 1 } : { limit: 1 }, - "first" - ); - } -}; -var SQLiteRelationalQuery = class extends QueryPromise { - static { - __name(this, "SQLiteRelationalQuery"); - } - constructor(fullSchema, schema, tableNamesMap, table, tableConfig, dialect, session2, config2, mode) { - super(); - this.fullSchema = fullSchema; - this.schema = schema; - this.tableNamesMap = tableNamesMap; - this.table = table; - this.tableConfig = tableConfig; - this.dialect = dialect; - this.session = session2; - this.config = config2; - this.mode = mode; - } - static [entityKind] = "SQLiteAsyncRelationalQuery"; - /** @internal */ - mode; - /** @internal */ - getSQL() { - return this.dialect.buildRelationalQuery({ - fullSchema: this.fullSchema, - schema: this.schema, - tableNamesMap: this.tableNamesMap, - table: this.table, - tableConfig: this.tableConfig, - queryConfig: this.config, - tableAlias: this.tableConfig.tsName - }).sql; - } - /** @internal */ - _prepare(isOneTimeQuery = false) { - const { query, builtQuery } = this._toSQL(); - return this.session[isOneTimeQuery ? "prepareOneTimeQuery" : "prepareQuery"]( - builtQuery, - void 0, - this.mode === "first" ? "get" : "all", - true, - (rawRows, mapColumnValue) => { - const rows = rawRows.map( - (row) => mapRelationalRow(this.schema, this.tableConfig, row, query.selection, mapColumnValue) - ); - if (this.mode === "first") { - return rows[0]; - } - return rows; - } - ); - } - prepare() { - return this._prepare(false); - } - _toSQL() { - const query = this.dialect.buildRelationalQuery({ - fullSchema: this.fullSchema, - schema: this.schema, - tableNamesMap: this.tableNamesMap, - table: this.table, - tableConfig: this.tableConfig, - queryConfig: this.config, - tableAlias: this.tableConfig.tsName - }); - const builtQuery = this.dialect.sqlToQuery(query.sql); - return { query, builtQuery }; - } - toSQL() { - return this._toSQL().builtQuery; - } - /** @internal */ - executeRaw() { - if (this.mode === "first") { - return this._prepare(false).get(); - } - return this._prepare(false).all(); - } - async execute() { - return this.executeRaw(); - } -}; -var SQLiteSyncRelationalQuery = class extends SQLiteRelationalQuery { - static { - __name(this, "SQLiteSyncRelationalQuery"); - } - static [entityKind] = "SQLiteSyncRelationalQuery"; - sync() { - return this.executeRaw(); - } -}; - -// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/sqlite-core/query-builders/raw.js -init_modules_watch_stub(); -init_performance2(); -var SQLiteRaw = class extends QueryPromise { - static { - __name(this, "SQLiteRaw"); - } - constructor(execute, getSQL, action, dialect, mapBatchResult) { - super(); - this.execute = execute; - this.getSQL = getSQL; - this.dialect = dialect; - this.mapBatchResult = mapBatchResult; - this.config = { action }; - } - static [entityKind] = "SQLiteRaw"; - /** @internal */ - config; - getQuery() { - return { ...this.dialect.sqlToQuery(this.getSQL()), method: this.config.action }; - } - mapResult(result, isFromBatch) { - return isFromBatch ? this.mapBatchResult(result) : result; - } - _prepare() { - return this; - } - /** @internal */ - isResponseInArrayMode() { - return false; - } -}; - -// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/sqlite-core/db.js -var BaseSQLiteDatabase = class { - static { - __name(this, "BaseSQLiteDatabase"); - } - constructor(resultKind, dialect, session2, schema) { - this.resultKind = resultKind; - this.dialect = dialect; - this.session = session2; - this._ = schema ? { - schema: schema.schema, - fullSchema: schema.fullSchema, - tableNamesMap: schema.tableNamesMap - } : { - schema: void 0, - fullSchema: {}, - tableNamesMap: {} - }; - this.query = {}; - const query = this.query; - if (this._.schema) { - for (const [tableName, columns] of Object.entries(this._.schema)) { - query[tableName] = new RelationalQueryBuilder( - resultKind, - schema.fullSchema, - this._.schema, - this._.tableNamesMap, - schema.fullSchema[tableName], - columns, - dialect, - session2 - ); - } - } - this.$cache = { invalidate: /* @__PURE__ */ __name(async (_params) => { - }, "invalidate") }; - } - static [entityKind] = "BaseSQLiteDatabase"; - query; - /** - * Creates a subquery that defines a temporary named result set as a CTE. - * - * It is useful for breaking down complex queries into simpler parts and for reusing the result set in subsequent parts of the query. - * - * See docs: {@link https://orm.drizzle.team/docs/select#with-clause} - * - * @param alias The alias for the subquery. - * - * Failure to provide an alias will result in a DrizzleTypeError, preventing the subquery from being referenced in other queries. - * - * @example - * - * ```ts - * // Create a subquery with alias 'sq' and use it in the select query - * const sq = db.$with('sq').as(db.select().from(users).where(eq(users.id, 42))); - * - * const result = await db.with(sq).select().from(sq); - * ``` - * - * To select arbitrary SQL values as fields in a CTE and reference them in other CTEs or in the main query, you need to add aliases to them: - * - * ```ts - * // Select an arbitrary SQL value as a field in a CTE and reference it in the main query - * const sq = db.$with('sq').as(db.select({ - * name: sql`upper(${users.name})`.as('name'), - * }) - * .from(users)); - * - * const result = await db.with(sq).select({ name: sq.name }).from(sq); - * ``` - */ - $with = /* @__PURE__ */ __name((alias, selection) => { - const self2 = this; - const as = /* @__PURE__ */ __name((qb) => { - if (typeof qb === "function") { - qb = qb(new QueryBuilder(self2.dialect)); - } - return new Proxy( - new WithSubquery( - qb.getSQL(), - selection ?? ("getSelectedFields" in qb ? qb.getSelectedFields() ?? {} : {}), - alias, - true - ), - new SelectionProxyHandler({ alias, sqlAliasedBehavior: "alias", sqlBehavior: "error" }) - ); - }, "as"); - return { as }; - }, "$with"); - $count(source, filters) { - return new SQLiteCountBuilder({ source, filters, session: this.session }); - } - /** - * Incorporates a previously defined CTE (using `$with`) into the main query. - * - * This method allows the main query to reference a temporary named result set. - * - * See docs: {@link https://orm.drizzle.team/docs/select#with-clause} - * - * @param queries The CTEs to incorporate into the main query. - * - * @example - * - * ```ts - * // Define a subquery 'sq' as a CTE using $with - * const sq = db.$with('sq').as(db.select().from(users).where(eq(users.id, 42))); - * - * // Incorporate the CTE 'sq' into the main query and select from it - * const result = await db.with(sq).select().from(sq); - * ``` - */ - with(...queries) { - const self2 = this; - function select(fields) { - return new SQLiteSelectBuilder({ - fields: fields ?? void 0, - session: self2.session, - dialect: self2.dialect, - withList: queries - }); - } - __name(select, "select"); - function selectDistinct(fields) { - return new SQLiteSelectBuilder({ - fields: fields ?? void 0, - session: self2.session, - dialect: self2.dialect, - withList: queries, - distinct: true - }); - } - __name(selectDistinct, "selectDistinct"); - function update(table) { - return new SQLiteUpdateBuilder(table, self2.session, self2.dialect, queries); - } - __name(update, "update"); - function insert(into) { - return new SQLiteInsertBuilder(into, self2.session, self2.dialect, queries); - } - __name(insert, "insert"); - function delete_(from) { - return new SQLiteDeleteBase(from, self2.session, self2.dialect, queries); - } - __name(delete_, "delete_"); - return { select, selectDistinct, update, insert, delete: delete_ }; - } - select(fields) { - return new SQLiteSelectBuilder({ fields: fields ?? void 0, session: this.session, dialect: this.dialect }); - } - selectDistinct(fields) { - return new SQLiteSelectBuilder({ - fields: fields ?? void 0, - session: this.session, - dialect: this.dialect, - distinct: true - }); - } - /** - * Creates an update query. - * - * Calling this method without `.where()` clause will update all rows in a table. The `.where()` clause specifies which rows should be updated. - * - * Use `.set()` method to specify which values to update. - * - * See docs: {@link https://orm.drizzle.team/docs/update} - * - * @param table The table to update. - * - * @example - * - * ```ts - * // Update all rows in the 'cars' table - * await db.update(cars).set({ color: 'red' }); - * - * // Update rows with filters and conditions - * await db.update(cars).set({ color: 'red' }).where(eq(cars.brand, 'BMW')); - * - * // Update with returning clause - * const updatedCar: Car[] = await db.update(cars) - * .set({ color: 'red' }) - * .where(eq(cars.id, 1)) - * .returning(); - * ``` - */ - update(table) { - return new SQLiteUpdateBuilder(table, this.session, this.dialect); - } - $cache; - /** - * Creates an insert query. - * - * Calling this method will create new rows in a table. Use `.values()` method to specify which values to insert. - * - * See docs: {@link https://orm.drizzle.team/docs/insert} - * - * @param table The table to insert into. - * - * @example - * - * ```ts - * // Insert one row - * await db.insert(cars).values({ brand: 'BMW' }); - * - * // Insert multiple rows - * await db.insert(cars).values([{ brand: 'BMW' }, { brand: 'Porsche' }]); - * - * // Insert with returning clause - * const insertedCar: Car[] = await db.insert(cars) - * .values({ brand: 'BMW' }) - * .returning(); - * ``` - */ - insert(into) { - return new SQLiteInsertBuilder(into, this.session, this.dialect); - } - /** - * Creates a delete query. - * - * Calling this method without `.where()` clause will delete all rows in a table. The `.where()` clause specifies which rows should be deleted. - * - * See docs: {@link https://orm.drizzle.team/docs/delete} - * - * @param table The table to delete from. - * - * @example - * - * ```ts - * // Delete all rows in the 'cars' table - * await db.delete(cars); - * - * // Delete rows with filters and conditions - * await db.delete(cars).where(eq(cars.color, 'green')); - * - * // Delete with returning clause - * const deletedCar: Car[] = await db.delete(cars) - * .where(eq(cars.id, 1)) - * .returning(); - * ``` - */ - delete(from) { - return new SQLiteDeleteBase(from, this.session, this.dialect); - } - run(query) { - const sequel = typeof query === "string" ? sql.raw(query) : query.getSQL(); - if (this.resultKind === "async") { - return new SQLiteRaw( - async () => this.session.run(sequel), - () => sequel, - "run", - this.dialect, - this.session.extractRawRunValueFromBatchResult.bind(this.session) - ); - } - return this.session.run(sequel); - } - all(query) { - const sequel = typeof query === "string" ? sql.raw(query) : query.getSQL(); - if (this.resultKind === "async") { - return new SQLiteRaw( - async () => this.session.all(sequel), - () => sequel, - "all", - this.dialect, - this.session.extractRawAllValueFromBatchResult.bind(this.session) - ); - } - return this.session.all(sequel); - } - get(query) { - const sequel = typeof query === "string" ? sql.raw(query) : query.getSQL(); - if (this.resultKind === "async") { - return new SQLiteRaw( - async () => this.session.get(sequel), - () => sequel, - "get", - this.dialect, - this.session.extractRawGetValueFromBatchResult.bind(this.session) - ); - } - return this.session.get(sequel); - } - values(query) { - const sequel = typeof query === "string" ? sql.raw(query) : query.getSQL(); - if (this.resultKind === "async") { - return new SQLiteRaw( - async () => this.session.values(sequel), - () => sequel, - "values", - this.dialect, - this.session.extractRawValuesValueFromBatchResult.bind(this.session) - ); - } - return this.session.values(sequel); - } - transaction(transaction, config2) { - return this.session.transaction(transaction, config2); - } -}; - -// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/d1/session.js -init_modules_watch_stub(); -init_performance2(); - -// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/cache/core/cache.js -init_modules_watch_stub(); -init_performance2(); -var Cache = class { - static { - __name(this, "Cache"); - } - static [entityKind] = "Cache"; -}; -var NoopCache = class extends Cache { - static { - __name(this, "NoopCache"); - } - strategy() { - return "all"; - } - static [entityKind] = "NoopCache"; - async get(_key) { - return void 0; - } - async put(_hashedQuery, _response, _tables, _config) { - } - async onMutate(_params) { - } -}; -async function hashQuery(sql2, params) { - const dataToHash = `${sql2}-${JSON.stringify(params)}`; - const encoder = new TextEncoder(); - const data2 = encoder.encode(dataToHash); - const hashBuffer = await crypto.subtle.digest("SHA-256", data2); - const hashArray = [...new Uint8Array(hashBuffer)]; - const hashHex = hashArray.map((b) => b.toString(16).padStart(2, "0")).join(""); - return hashHex; -} -__name(hashQuery, "hashQuery"); - -// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/sqlite-core/session.js -init_modules_watch_stub(); -init_performance2(); -var ExecuteResultSync = class extends QueryPromise { - static { - __name(this, "ExecuteResultSync"); - } - constructor(resultCb) { - super(); - this.resultCb = resultCb; - } - static [entityKind] = "ExecuteResultSync"; - async execute() { - return this.resultCb(); - } - sync() { - return this.resultCb(); - } -}; -var SQLitePreparedQuery = class { - static { - __name(this, "SQLitePreparedQuery"); - } - constructor(mode, executeMethod, query, cache, queryMetadata, cacheConfig) { - this.mode = mode; - this.executeMethod = executeMethod; - this.query = query; - this.cache = cache; - this.queryMetadata = queryMetadata; - this.cacheConfig = cacheConfig; - if (cache && cache.strategy() === "all" && cacheConfig === void 0) { - this.cacheConfig = { enable: true, autoInvalidate: true }; - } - if (!this.cacheConfig?.enable) { - this.cacheConfig = void 0; - } - } - static [entityKind] = "PreparedQuery"; - /** @internal */ - joinsNotNullableMap; - /** @internal */ - async queryWithCache(queryString, params, query) { - if (this.cache === void 0 || is(this.cache, NoopCache) || this.queryMetadata === void 0) { - try { - return await query(); - } catch (e) { - throw new DrizzleQueryError(queryString, params, e); - } - } - if (this.cacheConfig && !this.cacheConfig.enable) { - try { - return await query(); - } catch (e) { - throw new DrizzleQueryError(queryString, params, e); - } - } - if ((this.queryMetadata.type === "insert" || this.queryMetadata.type === "update" || this.queryMetadata.type === "delete") && this.queryMetadata.tables.length > 0) { - try { - const [res] = await Promise.all([ - query(), - this.cache.onMutate({ tables: this.queryMetadata.tables }) - ]); - return res; - } catch (e) { - throw new DrizzleQueryError(queryString, params, e); - } - } - if (!this.cacheConfig) { - try { - return await query(); - } catch (e) { - throw new DrizzleQueryError(queryString, params, e); - } - } - if (this.queryMetadata.type === "select") { - const fromCache = await this.cache.get( - this.cacheConfig.tag ?? await hashQuery(queryString, params), - this.queryMetadata.tables, - this.cacheConfig.tag !== void 0, - this.cacheConfig.autoInvalidate - ); - if (fromCache === void 0) { - let result; - try { - result = await query(); - } catch (e) { - throw new DrizzleQueryError(queryString, params, e); - } - await this.cache.put( - this.cacheConfig.tag ?? await hashQuery(queryString, params), - result, - // make sure we send tables that were used in a query only if user wants to invalidate it on each write - this.cacheConfig.autoInvalidate ? this.queryMetadata.tables : [], - this.cacheConfig.tag !== void 0, - this.cacheConfig.config - ); - return result; - } - return fromCache; - } - try { - return await query(); - } catch (e) { - throw new DrizzleQueryError(queryString, params, e); - } - } - getQuery() { - return this.query; - } - mapRunResult(result, _isFromBatch) { - return result; - } - mapAllResult(_result, _isFromBatch) { - throw new Error("Not implemented"); - } - mapGetResult(_result, _isFromBatch) { - throw new Error("Not implemented"); - } - execute(placeholderValues) { - if (this.mode === "async") { - return this[this.executeMethod](placeholderValues); - } - return new ExecuteResultSync(() => this[this.executeMethod](placeholderValues)); - } - mapResult(response, isFromBatch) { - switch (this.executeMethod) { - case "run": { - return this.mapRunResult(response, isFromBatch); - } - case "all": { - return this.mapAllResult(response, isFromBatch); - } - case "get": { - return this.mapGetResult(response, isFromBatch); - } - } - } -}; -var SQLiteSession = class { - static { - __name(this, "SQLiteSession"); - } - constructor(dialect) { - this.dialect = dialect; - } - static [entityKind] = "SQLiteSession"; - prepareOneTimeQuery(query, fields, executeMethod, isResponseInArrayMode, customResultMapper, queryMetadata, cacheConfig) { - return this.prepareQuery( - query, - fields, - executeMethod, - isResponseInArrayMode, - customResultMapper, - queryMetadata, - cacheConfig - ); - } - run(query) { - const staticQuery = this.dialect.sqlToQuery(query); - try { - return this.prepareOneTimeQuery(staticQuery, void 0, "run", false).run(); - } catch (err) { - throw new DrizzleError({ cause: err, message: `Failed to run the query '${staticQuery.sql}'` }); - } - } - /** @internal */ - extractRawRunValueFromBatchResult(result) { - return result; - } - all(query) { - return this.prepareOneTimeQuery(this.dialect.sqlToQuery(query), void 0, "run", false).all(); - } - /** @internal */ - extractRawAllValueFromBatchResult(_result) { - throw new Error("Not implemented"); - } - get(query) { - return this.prepareOneTimeQuery(this.dialect.sqlToQuery(query), void 0, "run", false).get(); - } - /** @internal */ - extractRawGetValueFromBatchResult(_result) { - throw new Error("Not implemented"); - } - values(query) { - return this.prepareOneTimeQuery(this.dialect.sqlToQuery(query), void 0, "run", false).values(); - } - async count(sql2) { - const result = await this.values(sql2); - return result[0][0]; - } - /** @internal */ - extractRawValuesValueFromBatchResult(_result) { - throw new Error("Not implemented"); - } -}; -var SQLiteTransaction = class extends BaseSQLiteDatabase { - static { - __name(this, "SQLiteTransaction"); - } - constructor(resultType, dialect, session2, schema, nestedIndex = 0) { - super(resultType, dialect, session2, schema); - this.schema = schema; - this.nestedIndex = nestedIndex; - } - static [entityKind] = "SQLiteTransaction"; - rollback() { - throw new TransactionRollbackError(); - } -}; - -// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/d1/session.js -var SQLiteD1Session = class extends SQLiteSession { - static { - __name(this, "SQLiteD1Session"); - } - constructor(client, dialect, schema, options = {}) { - super(dialect); - this.client = client; - this.schema = schema; - this.options = options; - this.logger = options.logger ?? new NoopLogger(); - this.cache = options.cache ?? new NoopCache(); - } - static [entityKind] = "SQLiteD1Session"; - logger; - cache; - prepareQuery(query, fields, executeMethod, isResponseInArrayMode, customResultMapper, queryMetadata, cacheConfig) { - const stmt = this.client.prepare(query.sql); - return new D1PreparedQuery( - stmt, - query, - this.logger, - this.cache, - queryMetadata, - cacheConfig, - fields, - executeMethod, - isResponseInArrayMode, - customResultMapper - ); - } - async batch(queries) { - const preparedQueries = []; - const builtQueries = []; - for (const query of queries) { - const preparedQuery = query._prepare(); - const builtQuery = preparedQuery.getQuery(); - preparedQueries.push(preparedQuery); - if (builtQuery.params.length > 0) { - builtQueries.push(preparedQuery.stmt.bind(...builtQuery.params)); - } else { - const builtQuery2 = preparedQuery.getQuery(); - builtQueries.push( - this.client.prepare(builtQuery2.sql).bind(...builtQuery2.params) - ); - } - } - const batchResults = await this.client.batch(builtQueries); - return batchResults.map((result, i) => preparedQueries[i].mapResult(result, true)); - } - extractRawAllValueFromBatchResult(result) { - return result.results; - } - extractRawGetValueFromBatchResult(result) { - return result.results[0]; - } - extractRawValuesValueFromBatchResult(result) { - return d1ToRawMapping(result.results); - } - async transaction(transaction, config2) { - const tx = new D1Transaction("async", this.dialect, this, this.schema); - await this.run(sql.raw(`begin${config2?.behavior ? " " + config2.behavior : ""}`)); - try { - const result = await transaction(tx); - await this.run(sql`commit`); - return result; - } catch (err) { - await this.run(sql`rollback`); - throw err; - } - } -}; -var D1Transaction = class _D1Transaction extends SQLiteTransaction { - static { - __name(this, "D1Transaction"); - } - static [entityKind] = "D1Transaction"; - async transaction(transaction) { - const savepointName = `sp${this.nestedIndex}`; - const tx = new _D1Transaction("async", this.dialect, this.session, this.schema, this.nestedIndex + 1); - await this.session.run(sql.raw(`savepoint ${savepointName}`)); - try { - const result = await transaction(tx); - await this.session.run(sql.raw(`release savepoint ${savepointName}`)); - return result; - } catch (err) { - await this.session.run(sql.raw(`rollback to savepoint ${savepointName}`)); - throw err; - } - } -}; -function d1ToRawMapping(results) { - const rows = []; - for (const row of results) { - const entry = Object.keys(row).map((k) => row[k]); - rows.push(entry); - } - return rows; -} -__name(d1ToRawMapping, "d1ToRawMapping"); -var D1PreparedQuery = class extends SQLitePreparedQuery { - static { - __name(this, "D1PreparedQuery"); - } - constructor(stmt, query, logger, cache, queryMetadata, cacheConfig, fields, executeMethod, _isResponseInArrayMode, customResultMapper) { - super("async", executeMethod, query, cache, queryMetadata, cacheConfig); - this.logger = logger; - this._isResponseInArrayMode = _isResponseInArrayMode; - this.customResultMapper = customResultMapper; - this.fields = fields; - this.stmt = stmt; - } - static [entityKind] = "D1PreparedQuery"; - /** @internal */ - customResultMapper; - /** @internal */ - fields; - /** @internal */ - stmt; - async run(placeholderValues) { - const params = fillPlaceholders(this.query.params, placeholderValues ?? {}); - this.logger.logQuery(this.query.sql, params); - return await this.queryWithCache(this.query.sql, params, async () => { - return this.stmt.bind(...params).run(); - }); - } - async all(placeholderValues) { - const { fields, query, logger, stmt, customResultMapper } = this; - if (!fields && !customResultMapper) { - const params = fillPlaceholders(query.params, placeholderValues ?? {}); - logger.logQuery(query.sql, params); - return await this.queryWithCache(query.sql, params, async () => { - return stmt.bind(...params).all().then(({ results }) => this.mapAllResult(results)); - }); - } - const rows = await this.values(placeholderValues); - return this.mapAllResult(rows); - } - mapAllResult(rows, isFromBatch) { - if (isFromBatch) { - rows = d1ToRawMapping(rows.results); - } - if (!this.fields && !this.customResultMapper) { - return rows; - } - if (this.customResultMapper) { - return this.customResultMapper(rows); - } - return rows.map((row) => mapResultRow(this.fields, row, this.joinsNotNullableMap)); - } - async get(placeholderValues) { - const { fields, joinsNotNullableMap, query, logger, stmt, customResultMapper } = this; - if (!fields && !customResultMapper) { - const params = fillPlaceholders(query.params, placeholderValues ?? {}); - logger.logQuery(query.sql, params); - return await this.queryWithCache(query.sql, params, async () => { - return stmt.bind(...params).all().then(({ results }) => results[0]); - }); - } - const rows = await this.values(placeholderValues); - if (!rows[0]) { - return void 0; - } - if (customResultMapper) { - return customResultMapper(rows); - } - return mapResultRow(fields, rows[0], joinsNotNullableMap); - } - mapGetResult(result, isFromBatch) { - if (isFromBatch) { - result = d1ToRawMapping(result.results)[0]; - } - if (!this.fields && !this.customResultMapper) { - return result; - } - if (this.customResultMapper) { - return this.customResultMapper([result]); - } - return mapResultRow(this.fields, result, this.joinsNotNullableMap); - } - async values(placeholderValues) { - const params = fillPlaceholders(this.query.params, placeholderValues ?? {}); - this.logger.logQuery(this.query.sql, params); - return await this.queryWithCache(this.query.sql, params, async () => { - return this.stmt.bind(...params).raw(); - }); - } - /** @internal */ - isResponseInArrayMode() { - return this._isResponseInArrayMode; - } -}; - -// node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/d1/driver.js -var DrizzleD1Database = class extends BaseSQLiteDatabase { - static { - __name(this, "DrizzleD1Database"); - } - static [entityKind] = "D1Database"; - async batch(batch) { - return this.session.batch(batch); - } -}; -function drizzle(client, config2 = {}) { - const dialect = new SQLiteAsyncDialect({ casing: config2.casing }); - let logger; - if (config2.logger === true) { - logger = new DefaultLogger(); - } else if (config2.logger !== false) { - logger = config2.logger; - } - let schema; - if (config2.schema) { - const tablesConfig = extractTablesRelationalConfig( - config2.schema, - createTableRelationsHelpers - ); - schema = { - fullSchema: config2.schema, - schema: tablesConfig.tables, - tableNamesMap: tablesConfig.tableNamesMap - }; - } - const session2 = new SQLiteD1Session(client, dialect, schema, { logger, cache: config2.cache }); - const db = new DrizzleD1Database("async", dialect, session2, schema); - db.$client = client; - db.$cache = config2.cache; - if (db.$cache) { - db.$cache["invalidate"] = config2.cache?.onMutate; - } - return db; -} -__name(drizzle, "drizzle"); - -// src/bot/index.ts -init_modules_watch_stub(); -init_performance2(); - -// src/bot/storage.ts -init_modules_watch_stub(); -init_performance2(); -var DatabaseSessionStorage = class { - constructor(sessionRepo, ttl) { - this.sessionRepo = sessionRepo; - this.ttl = ttl; - } - static { - __name(this, "DatabaseSessionStorage"); - } - async read(key) { - const value = await this.sessionRepo.get(key); - if (!value) return void 0; - try { - return JSON.parse(value); - } catch (error) { - console.error("Failed to parse session data:", error); - return void 0; - } - } - async write(key, value) { - const expiresAt = this.ttl ? Date.now() + this.ttl * 1e3 : void 0; - await this.sessionRepo.set(key, JSON.stringify(value), expiresAt); - } - async delete(key) { - await this.sessionRepo.delete(key); - } - async has(key) { - const value = await this.sessionRepo.get(key); - return value !== void 0; - } - /** - * Clean up expired sessions - * Should be called periodically (e.g., via cron job) - */ - async cleanup() { - await this.sessionRepo.cleanup(); - } -}; - -// src/bot/commands/index.ts -init_modules_watch_stub(); -init_performance2(); - -// src/bot/commands/start.command.ts -init_modules_watch_stub(); -init_performance2(); - -// src/bot/helpers.ts -init_modules_watch_stub(); -init_performance2(); -async function sendSettingsMenu(ctx, chat) { - const settings = chat.settings; - if (!settings) return; - const createCheckmark = /* @__PURE__ */ __name((value) => value ? "\u2705" : "\u274C", "createCheckmark"); - const keyboard = new InlineKeyboard().text( - `${createCheckmark(settings.gameChangeNotification)} ${ctx.t("commands.start.game_change_notification_setting.button")}`, - "toggle_game_change" - ).row().text( - `${createCheckmark(settings.offlineNotification)} ${ctx.t("commands.start.offline_notification.button")}`, - "toggle_offline" - ).row().text( - `${createCheckmark(settings.titleChangeNotification)} ${ctx.t("commands.start.title_change_notification_setting.button")}`, - "toggle_title_change" - ).row().text( - `${createCheckmark(settings.gameAndTitleChangeNotification)} ${ctx.t("commands.start.game_and_title_change_notification_setting.button")}`, - "toggle_game_and_title" - ).row().text( - `${createCheckmark(settings.imageInNotification)} ${ctx.t("commands.start.image_in_notification_setting.button")}`, - "toggle_image" - ).row().text( - ctx.t("commands.start.language.button"), - "language_picker" - ).row().url("Github", "https://github.com/Satont/twitch-notifier"); - const description = ctx.t("bot.description"); - if (ctx.callbackQuery) { - await ctx.editMessageText(description, { reply_markup: keyboard }); - } else { - await ctx.reply(description, { reply_markup: keyboard }); - } -} -__name(sendSettingsMenu, "sendSettingsMenu"); -async function sendLanguagePicker(ctx) { - const keyboard = new InlineKeyboard(); - const locales = ctx.services.i18n.getAvailableLocales(); - for (const locale of locales) { - const emoji = ctx.services.i18n.t(locale, "language.emoji"); - const name = ctx.services.i18n.t(locale, "language.name"); - keyboard.text(`${emoji} ${name}`, `language_picker_set_${locale}`).row(); - } - keyboard.text("\xAB", "start_command_menu"); - const text2 = ctx.t("language.select"); - if (ctx.callbackQuery) { - await ctx.editMessageText(text2, { reply_markup: keyboard }); - } else { - await ctx.reply(text2, { reply_markup: keyboard }); - } -} -__name(sendLanguagePicker, "sendLanguagePicker"); -async function buildFollowsKeyboard(ctx, chatId) { - const follows2 = await ctx.services.followRepo.findByChatId(chatId); - const keyboard = new InlineKeyboard(); - for (const follow of follows2) { - const channel = await ctx.services.channelRepo.findById(follow.channelId); - if (!channel) continue; - const twitchUser = await ctx.services.twitch.getUserById(channel.channelId); - if (!twitchUser) continue; - keyboard.text(twitchUser.displayName, `channels_unfollow_${channel.channelId}`).row(); - } - if (ctx.session.followsMenu) { - const { currentPage, totalPages } = ctx.session.followsMenu; - if (totalPages > 1) { - keyboard.text("\xAB", "channels_unfollow_prev_page"); - keyboard.text("\xBB", "channels_unfollow_next_page"); - } - } - return keyboard; -} -__name(buildFollowsKeyboard, "buildFollowsKeyboard"); -async function handleToggleSetting(ctx, data2, chat) { - const chatId = ctx.chat?.id; - if (!chatId || !chat.settings) return; - const updates = {}; - switch (data2) { - case "toggle_game_change": - updates.gameChangeNotification = !chat.settings.gameChangeNotification; - chat.settings.gameChangeNotification = updates.gameChangeNotification; - break; - case "toggle_offline": - updates.offlineNotification = !chat.settings.offlineNotification; - chat.settings.offlineNotification = updates.offlineNotification; - break; - case "toggle_title_change": - updates.titleChangeNotification = !chat.settings.titleChangeNotification; - chat.settings.titleChangeNotification = updates.titleChangeNotification; - break; - case "toggle_game_and_title": - updates.gameAndTitleChangeNotification = !chat.settings.gameAndTitleChangeNotification; - chat.settings.gameAndTitleChangeNotification = updates.gameAndTitleChangeNotification; - break; - case "toggle_image": - updates.imageInNotification = !chat.settings.imageInNotification; - chat.settings.imageInNotification = updates.imageInNotification; - break; - } - if (Object.keys(updates).length > 0) { - await ctx.services.chatRepo.updateSettings(chat.settings.id, updates); - } -} -__name(handleToggleSetting, "handleToggleSetting"); -async function handleUnfollow(ctx, chat, channelIdFromCallback) { - const channel = await ctx.services.channelRepo.findById(channelIdFromCallback); - if (!channel) { - await ctx.answerCallbackQuery("Channel not found"); - return; - } - const follow = await ctx.services.followRepo.findByChatAndChannel(chat.id, channel.id); - if (!follow) { - await ctx.answerCallbackQuery("Already unfollowed"); - return; - } - const twitchUser = await ctx.services.twitch.getUserById(channel.channelId); - const streamerName = twitchUser?.displayName || channel.channelId; - await ctx.services.followRepo.delete(follow.id); - const remainingFollows = await ctx.services.followRepo.findByChannelId(channel.id); - if (remainingFollows.length === 0) { - try { - await ctx.services.eventsub.unsubscribeFromChannel(channel.channelId); - console.log(`Unsubscribed from EventSub for channel ${channel.channelId}`); - } catch (error) { - console.error(`Failed to unsubscribe from EventSub for ${channel.channelId}:`, error); - } - } - await ctx.answerCallbackQuery( - ctx.t("commands.unfollow.success", { - streamer: streamerName - }) - ); - const totalFollows = await ctx.services.followRepo.countByChatId(chat.id); - if (totalFollows === 0) { - await ctx.editMessageText("You are not following any channels."); - await ctx.editMessageReplyMarkup({ reply_markup: new InlineKeyboard() }); - return; - } - const keyboard = await buildFollowsKeyboard(ctx, chat.id); - await ctx.editMessageText( - ctx.t("commands.follows.total", { - count: totalFollows.toString() - }), - { - reply_markup: keyboard - } - ); -} -__name(handleUnfollow, "handleUnfollow"); - -// src/bot/commands/start.command.ts -var startCommand = new Composer(); -startCommand.command(["start", "help", "info", "settings"], async (ctx) => { - const chatId = ctx.chat?.id; - if (!chatId) return; - let chat = await ctx.services.chatRepo.findByChatId(chatId, "telegram"); - if (!chat) { - await ctx.services.chatRepo.create(chatId.toString(), "telegram"); - chat = await ctx.services.chatRepo.findByChatId(chatId, "telegram"); - } - if (chat?.settings) { - ctx.session.language = chat.settings.language; - } - if (chat) { - await sendSettingsMenu(ctx, chat); - } -}); - -// src/bot/commands/follow.command.ts -init_modules_watch_stub(); -init_performance2(); -var followCommand = new Composer(); -followCommand.command("follow", async (ctx) => { - const text2 = ctx.message?.text?.replace("/follow", "").trim(); - if (!text2) { - await ctx.reply( - ctx.t("commands.follow.enter") - ); - ctx.session.scene = "follow"; - return; - } - await handleFollow(ctx, text2); -}); -followCommand.on("message:text", async (ctx, next) => { - if (ctx.session.scene === "follow") { - await handleFollow(ctx, ctx.message.text); - ctx.session.scene = void 0; - return; - } - await next(); -}); -async function handleFollow(ctx, text2) { - const chatId = ctx.chat?.id; - if (!chatId) return; - const chat = await ctx.services.chatRepo.findByChatId(chatId, "telegram"); - if (!chat) return; - const twitchLinkRegex = /(?:https?:\/\/)?(?:www\.)?twitch\.tv\/(\w+)/g; - const matches = Array.from(text2.matchAll(twitchLinkRegex)); - const usernames = matches.length > 0 ? matches.map((m2) => m2[1]) : [text2.trim()]; - const results = []; - for (const username of usernames) { - if (!/^[a-zA-Z0-9_]{3,25}$/.test(username)) { - results.push( - ctx.t( - "commands.follow.errors.badUsername", - { streamer: username } - ) - ); - continue; - } - try { - const twitchUser = await ctx.services.twitch.getUserByLogin(username); - if (!twitchUser) { - results.push( - ctx.t( - "commands.follow.errors.streamerNotFound", - { streamer: username } - ) - ); - continue; - } - let channel = await ctx.services.channelRepo.findByChannelId(twitchUser.id, "twitch"); - if (!channel) { - channel = await ctx.services.channelRepo.create(twitchUser.id, "twitch"); - } - try { - await ctx.services.followRepo.create(chat.id, channel.id); - const hasSubscriptions = await ctx.services.eventsub.hasActiveSubscriptions(twitchUser.id); - if (!hasSubscriptions) { - try { - await ctx.services.eventsub.subscribeToChannel(twitchUser.id); - console.log(`Subscribed to EventSub for channel ${twitchUser.id}`); - } catch (eventSubError) { - console.error(`Failed to subscribe to EventSub for ${twitchUser.id}:`, eventSubError); - } - } - results.push( - ctx.t( - "commands.follow.success", - { streamer: username } - ) - ); - } catch (error) { - if (error.message?.includes("UNIQUE constraint failed")) { - results.push( - ctx.t( - "commands.follow.errors.alreadyFollowed", - { streamer: username } - ) - ); - } else { - throw error; - } - } - } catch (error) { - console.error("Error following user:", error); - results.push(`${username} - internal error`); - } - } - await ctx.reply(results.join("\n")); -} -__name(handleFollow, "handleFollow"); - -// src/bot/commands/follows.command.ts -init_modules_watch_stub(); -init_performance2(); -var followsCommand = new Composer(); -followsCommand.command(["follows", "unfollow"], async (ctx) => { - const chatId = ctx.chat?.id; - if (!chatId) return; - const chat = await ctx.services.chatRepo.findByChatId(chatId, "telegram"); - if (!chat) return; - ctx.session.followsMenu = { - currentPage: 1, - totalPages: 1 - }; - const totalFollows = await ctx.services.followRepo.countByChatId(chat.id); - if (totalFollows === 0) { - await ctx.reply("You are not following any channels."); - return; - } - const keyboard = await buildFollowsKeyboard(ctx, chat.id); - await ctx.reply( - ctx.t( - "commands.follows.total", - { count: totalFollows.toString() } - ), - { - reply_markup: keyboard - } - ); -}); - -// src/bot/commands/live.command.ts -init_modules_watch_stub(); -init_performance2(); -var liveCommand = new Composer(); -liveCommand.command("live", async (ctx) => { - const chatId = ctx.chat?.id; - if (!chatId) return; - const chat = await ctx.services.chatRepo.findByChatId(chatId, "telegram"); - if (!chat) return; - const follows2 = await ctx.services.followRepo.findByChatId(chat.id); - if (follows2.length === 0) { - await ctx.reply("You are not following any channels."); - return; - } - const channelIds = []; - for (const follow of follows2) { - const channel = await ctx.services.channelRepo.findById(follow.channelId); - if (channel) { - channelIds.push(channel.channelId); - } - } - if (channelIds.length === 0) { - await ctx.reply("No channels found."); - return; - } - const liveChannels = []; - for (const channelId of channelIds) { - const stream = await ctx.services.twitch.getStreamByUserId(channelId); - if (stream) { - const user = await ctx.services.twitch.getUserById(channelId); - if (user) { - liveChannels.push({ - name: user.displayName, - login: user.name, - startedAt: stream.startDate, - title: stream.title, - category: stream.gameName, - viewers: stream.viewers - }); - } - } - } - if (liveChannels.length === 0) { - await ctx.reply("No one is online."); - return; - } - const messages = []; - for (const channel of liveChannels) { - const channelMessage = []; - channelMessage.push( - `\u{1F7E2} ${channel.name} - ${channel.viewers} \u{1F441}\uFE0F\uFE0F` - ); - if (channel.category) { - channelMessage.push(`\u{1F3AE} ${channel.category}`); - } - if (channel.title) { - channelMessage.push(`\u{1F4DD} ${channel.title}`); - } - const uptime2 = Date.now() - channel.startedAt.getTime(); - const hours = Math.floor(uptime2 / 36e5); - const minutes = Math.floor(uptime2 % 36e5 / 6e4); - const seconds = Math.floor(uptime2 % 6e4 / 1e3); - let uptimeStr = "\u231B "; - if (hours > 0) uptimeStr += `${hours}h `; - if (minutes > 0) uptimeStr += `${minutes}m `; - if (seconds > 0) uptimeStr += `${seconds}s `; - channelMessage.push(uptimeStr); - messages.push(channelMessage.join("\n")); - } - await ctx.reply(messages.join("\n\n"), { - parse_mode: "HTML", - link_preview_options: { is_disabled: true } - }); -}); - -// src/bot/commands/broadcast.command.ts -init_modules_watch_stub(); -init_performance2(); -function createBroadcastCommand(env) { - const broadcast = new Composer(); - const isAdmin = /* @__PURE__ */ __name((userId) => { - const admins = env.TELEGRAM_BOT_ADMINS.split(",").map((id) => parseInt(id.trim())); - return admins.includes(userId); - }, "isAdmin"); - broadcast.command("broadcast", async (ctx) => { - const userId = ctx.from?.id; - if (!userId || !isAdmin(userId)) { - return; - } - const text2 = ctx.message?.text?.replace("/broadcast", "").trim(); - if (!text2) { - await ctx.reply("Usage: /broadcast "); - return; - } - const allChats = await ctx.services.chatRepo.findAllByService("telegram"); - let sent = 0; - let failed = 0; - for (const chat of allChats) { - const chatIdNum = parseInt(chat.chatId); - if (chatIdNum <= 0) continue; - try { - await ctx.api.sendMessage(chatIdNum, text2); - sent++; - } catch (error) { - console.error(`Failed to send to ${chat.chatId}:`, error); - failed++; - } - } - await ctx.reply(`Broadcast completed! -Sent: ${sent} -Failed: ${failed}`); - }); - return broadcast; -} -__name(createBroadcastCommand, "createBroadcastCommand"); - -// src/bot/commands/change-channel-id.command.ts -init_modules_watch_stub(); -init_performance2(); -function createChangeChannelIdCommand(env) { - const changeChannelId = new Composer(); - const isAdmin = /* @__PURE__ */ __name((userId) => { - const admins = env.TELEGRAM_BOT_ADMINS.split(",").map((id) => parseInt(id.trim())); - return admins.includes(userId); - }, "isAdmin"); - changeChannelId.command("change_channel_id", async (ctx) => { - const userId = ctx.from?.id; - if (!userId || !isAdmin(userId)) { - return; - } - const text2 = ctx.message?.text?.replace("/change_channel_id", "").trim(); - if (!text2) { - await ctx.reply("Usage: /change_channel_id "); - return; - } - const parts = text2.split(" "); - if (parts.length !== 2) { - await ctx.reply("Usage: /change_channel_id "); - return; - } - const [oldId, newId] = parts; - try { - await ctx.services.channelRepo.updateChannelId(oldId, newId, "twitch"); - await ctx.reply("Channel ID updated successfully!"); - } catch (error) { - console.error("Error updating channel ID:", error); - await ctx.reply("Error updating channel ID."); - } - }); - return changeChannelId; -} -__name(createChangeChannelIdCommand, "createChangeChannelIdCommand"); - -// src/bot/commands/callback.handler.ts -init_modules_watch_stub(); -init_performance2(); -var callbackQueryHandler = new Composer(); -callbackQueryHandler.on("callback_query:data", async (ctx) => { - const data2 = ctx.callbackQuery.data; - const chatId = ctx.chat?.id; - if (!chatId) return; - const chat = await ctx.services.chatRepo.findByChatId(chatId, "telegram"); - if (!chat || !chat.settings) return; - if (data2.startsWith("toggle_")) { - await handleToggleSetting(ctx, data2, chat); - await sendSettingsMenu(ctx, chat); - } else if (data2 === "language_picker") { - await sendLanguagePicker(ctx); - } else if (data2.startsWith("language_picker_set_")) { - const lang = data2.replace("language_picker_set_", ""); - if (ctx.services.i18n.isValidLocale(lang)) { - await ctx.services.chatRepo.updateSettings(chat.settings.id, { language: lang }); - ctx.session.language = lang; - await ctx.answerCallbackQuery( - ctx.services.i18n.t(lang, "language.changed") - ); - await sendLanguagePicker(ctx); - } - } else if (data2 === "start_command_menu") { - await sendSettingsMenu(ctx, chat); - } else if (data2.startsWith("channels_unfollow_")) { - const channelId = data2.replace("channels_unfollow_", ""); - await handleUnfollow(ctx, chat, channelId); - } else if (data2 === "channels_unfollow_prev_page") { - if (ctx.session.followsMenu && ctx.session.followsMenu.currentPage > 1) { - ctx.session.followsMenu.currentPage--; - } - const keyboard = await buildFollowsKeyboard(ctx, chat.id); - await ctx.editMessageReplyMarkup({ reply_markup: keyboard }); - } else if (data2 === "channels_unfollow_next_page") { - if (ctx.session.followsMenu && ctx.session.followsMenu.currentPage < ctx.session.followsMenu.totalPages) { - ctx.session.followsMenu.currentPage++; - } - const keyboard = await buildFollowsKeyboard(ctx, chat.id); - await ctx.editMessageReplyMarkup({ reply_markup: keyboard }); - } - await ctx.answerCallbackQuery(); -}); - -// src/bot/index.ts -function createBot(env, services) { - const bot = new Bot(env.TELEGRAM_TOKEN); - const sessionStorage = new DatabaseSessionStorage( - services.sessionRepo, - 86400 - // 24 hours TTL - ); - bot.use(session({ - initial: /* @__PURE__ */ __name(() => ({ - language: "en", - followsMenu: { - currentPage: 1, - totalPages: 1 - } - }), "initial"), - storage: sessionStorage - })); - bot.use(async (ctx, next) => { - ctx.env = env; - ctx.services = services; - await next(); - }); - bot.use(services.i18n.middleware()); - bot.use(startCommand); - bot.use(followCommand); - bot.use(followsCommand); - bot.use(liveCommand); - bot.use(createBroadcastCommand(env)); - bot.use(createChangeChannelIdCommand(env)); - bot.use(callbackQueryHandler); - return bot; -} -__name(createBot, "createBot"); - -// src/services/i18n.service.ts -init_modules_watch_stub(); -init_performance2(); - -// node_modules/.pnpm/i18next@25.8.14_typescript@5.9.3/node_modules/i18next/dist/esm/i18next.js -init_modules_watch_stub(); -init_performance2(); -var isString = /* @__PURE__ */ __name((obj) => typeof obj === "string", "isString"); -var defer = /* @__PURE__ */ __name(() => { - let res; - let rej; - const promise = new Promise((resolve, reject) => { - res = resolve; - rej = reject; - }); - promise.resolve = res; - promise.reject = rej; - return promise; -}, "defer"); -var makeString = /* @__PURE__ */ __name((object) => { - if (object == null) return ""; - return "" + object; -}, "makeString"); -var copy = /* @__PURE__ */ __name((a, s2, t2) => { - a.forEach((m2) => { - if (s2[m2]) t2[m2] = s2[m2]; - }); -}, "copy"); -var lastOfPathSeparatorRegExp = /###/g; -var cleanKey = /* @__PURE__ */ __name((key) => key && key.indexOf("###") > -1 ? key.replace(lastOfPathSeparatorRegExp, ".") : key, "cleanKey"); -var canNotTraverseDeeper = /* @__PURE__ */ __name((object) => !object || isString(object), "canNotTraverseDeeper"); -var getLastOfPath = /* @__PURE__ */ __name((object, path, Empty) => { - const stack = !isString(path) ? path : path.split("."); - let stackIndex = 0; - while (stackIndex < stack.length - 1) { - if (canNotTraverseDeeper(object)) return {}; - const key = cleanKey(stack[stackIndex]); - if (!object[key] && Empty) object[key] = new Empty(); - if (Object.prototype.hasOwnProperty.call(object, key)) { - object = object[key]; - } else { - object = {}; - } - ++stackIndex; - } - if (canNotTraverseDeeper(object)) return {}; - return { - obj: object, - k: cleanKey(stack[stackIndex]) - }; -}, "getLastOfPath"); -var setPath = /* @__PURE__ */ __name((object, path, newValue) => { - const { - obj, - k - } = getLastOfPath(object, path, Object); - if (obj !== void 0 || path.length === 1) { - obj[k] = newValue; - return; - } - let e = path[path.length - 1]; - let p = path.slice(0, path.length - 1); - let last = getLastOfPath(object, p, Object); - while (last.obj === void 0 && p.length) { - e = `${p[p.length - 1]}.${e}`; - p = p.slice(0, p.length - 1); - last = getLastOfPath(object, p, Object); - if (last?.obj && typeof last.obj[`${last.k}.${e}`] !== "undefined") { - last.obj = void 0; - } - } - last.obj[`${last.k}.${e}`] = newValue; -}, "setPath"); -var pushPath = /* @__PURE__ */ __name((object, path, newValue, concat2) => { - const { - obj, - k - } = getLastOfPath(object, path, Object); - obj[k] = obj[k] || []; - obj[k].push(newValue); -}, "pushPath"); -var getPath2 = /* @__PURE__ */ __name((object, path) => { - const { - obj, - k - } = getLastOfPath(object, path); - if (!obj) return void 0; - if (!Object.prototype.hasOwnProperty.call(obj, k)) return void 0; - return obj[k]; -}, "getPath"); -var getPathWithDefaults = /* @__PURE__ */ __name((data2, defaultData, key) => { - const value = getPath2(data2, key); - if (value !== void 0) { - return value; - } - return getPath2(defaultData, key); -}, "getPathWithDefaults"); -var deepExtend = /* @__PURE__ */ __name((target, source, overwrite) => { - for (const prop in source) { - if (prop !== "__proto__" && prop !== "constructor") { - if (prop in target) { - if (isString(target[prop]) || target[prop] instanceof String || isString(source[prop]) || source[prop] instanceof String) { - if (overwrite) target[prop] = source[prop]; - } else { - deepExtend(target[prop], source[prop], overwrite); - } - } else { - target[prop] = source[prop]; - } - } - } - return target; -}, "deepExtend"); -var regexEscape = /* @__PURE__ */ __name((str2) => str2.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"), "regexEscape"); -var _entityMap = { - "&": "&", - "<": "<", - ">": ">", - '"': """, - "'": "'", - "/": "/" -}; -var escape = /* @__PURE__ */ __name((data2) => { - if (isString(data2)) { - return data2.replace(/[&<>"'\/]/g, (s2) => _entityMap[s2]); - } - return data2; -}, "escape"); -var RegExpCache = class { - static { - __name(this, "RegExpCache"); - } - constructor(capacity) { - this.capacity = capacity; - this.regExpMap = /* @__PURE__ */ new Map(); - this.regExpQueue = []; - } - getRegExp(pattern) { - const regExpFromCache = this.regExpMap.get(pattern); - if (regExpFromCache !== void 0) { - return regExpFromCache; - } - const regExpNew = new RegExp(pattern); - if (this.regExpQueue.length === this.capacity) { - this.regExpMap.delete(this.regExpQueue.shift()); - } - this.regExpMap.set(pattern, regExpNew); - this.regExpQueue.push(pattern); - return regExpNew; - } -}; -var chars = [" ", ",", "?", "!", ";"]; -var looksLikeObjectPathRegExpCache = new RegExpCache(20); -var looksLikeObjectPath = /* @__PURE__ */ __name((key, nsSeparator, keySeparator) => { - nsSeparator = nsSeparator || ""; - keySeparator = keySeparator || ""; - const possibleChars = chars.filter((c) => nsSeparator.indexOf(c) < 0 && keySeparator.indexOf(c) < 0); - if (possibleChars.length === 0) return true; - const r = looksLikeObjectPathRegExpCache.getRegExp(`(${possibleChars.map((c) => c === "?" ? "\\?" : c).join("|")})`); - let matched = !r.test(key); - if (!matched) { - const ki = key.indexOf(keySeparator); - if (ki > 0 && !r.test(key.substring(0, ki))) { - matched = true; - } - } - return matched; -}, "looksLikeObjectPath"); -var deepFind = /* @__PURE__ */ __name((obj, path, keySeparator = ".") => { - if (!obj) return void 0; - if (obj[path]) { - if (!Object.prototype.hasOwnProperty.call(obj, path)) return void 0; - return obj[path]; - } - const tokens = path.split(keySeparator); - let current = obj; - for (let i = 0; i < tokens.length; ) { - if (!current || typeof current !== "object") { - return void 0; - } - let next; - let nextPath = ""; - for (let j = i; j < tokens.length; ++j) { - if (j !== i) { - nextPath += keySeparator; - } - nextPath += tokens[j]; - next = current[nextPath]; - if (next !== void 0) { - if (["string", "number", "boolean"].indexOf(typeof next) > -1 && j < tokens.length - 1) { - continue; - } - i += j - i + 1; - break; - } - } - current = next; - } - return current; -}, "deepFind"); -var getCleanedCode = /* @__PURE__ */ __name((code) => code?.replace(/_/g, "-"), "getCleanedCode"); -var consoleLogger = { - type: "logger", - log(args) { - this.output("log", args); - }, - warn(args) { - this.output("warn", args); - }, - error(args) { - this.output("error", args); - }, - output(type, args) { - console?.[type]?.apply?.(console, args); - } -}; -var Logger = class _Logger { - static { - __name(this, "Logger"); - } - constructor(concreteLogger, options = {}) { - this.init(concreteLogger, options); - } - init(concreteLogger, options = {}) { - this.prefix = options.prefix || "i18next:"; - this.logger = concreteLogger || consoleLogger; - this.options = options; - this.debug = options.debug; - } - log(...args) { - return this.forward(args, "log", "", true); - } - warn(...args) { - return this.forward(args, "warn", "", true); - } - error(...args) { - return this.forward(args, "error", ""); - } - deprecate(...args) { - return this.forward(args, "warn", "WARNING DEPRECATED: ", true); - } - forward(args, lvl, prefix, debugOnly) { - if (debugOnly && !this.debug) return null; - if (isString(args[0])) args[0] = `${prefix}${this.prefix} ${args[0]}`; - return this.logger[lvl](args); - } - create(moduleName) { - return new _Logger(this.logger, { - ...{ - prefix: `${this.prefix}:${moduleName}:` - }, - ...this.options - }); - } - clone(options) { - options = options || this.options; - options.prefix = options.prefix || this.prefix; - return new _Logger(this.logger, options); - } -}; -var baseLogger = new Logger(); -var EventEmitter = class { - static { - __name(this, "EventEmitter"); - } - constructor() { - this.observers = {}; - } - on(events, listener) { - events.split(" ").forEach((event) => { - if (!this.observers[event]) this.observers[event] = /* @__PURE__ */ new Map(); - const numListeners = this.observers[event].get(listener) || 0; - this.observers[event].set(listener, numListeners + 1); - }); - return this; - } - off(event, listener) { - if (!this.observers[event]) return; - if (!listener) { - delete this.observers[event]; - return; - } - this.observers[event].delete(listener); - } - emit(event, ...args) { - if (this.observers[event]) { - const cloned = Array.from(this.observers[event].entries()); - cloned.forEach(([observer, numTimesAdded]) => { - for (let i = 0; i < numTimesAdded; i++) { - observer(...args); - } - }); - } - if (this.observers["*"]) { - const cloned = Array.from(this.observers["*"].entries()); - cloned.forEach(([observer, numTimesAdded]) => { - for (let i = 0; i < numTimesAdded; i++) { - observer.apply(observer, [event, ...args]); - } - }); - } - } -}; -var ResourceStore = class extends EventEmitter { - static { - __name(this, "ResourceStore"); - } - constructor(data2, options = { - ns: ["translation"], - defaultNS: "translation" - }) { - super(); - this.data = data2 || {}; - this.options = options; - if (this.options.keySeparator === void 0) { - this.options.keySeparator = "."; - } - if (this.options.ignoreJSONStructure === void 0) { - this.options.ignoreJSONStructure = true; - } - } - addNamespaces(ns) { - if (this.options.ns.indexOf(ns) < 0) { - this.options.ns.push(ns); - } - } - removeNamespaces(ns) { - const index = this.options.ns.indexOf(ns); - if (index > -1) { - this.options.ns.splice(index, 1); - } - } - getResource(lng, ns, key, options = {}) { - const keySeparator = options.keySeparator !== void 0 ? options.keySeparator : this.options.keySeparator; - const ignoreJSONStructure = options.ignoreJSONStructure !== void 0 ? options.ignoreJSONStructure : this.options.ignoreJSONStructure; - let path; - if (lng.indexOf(".") > -1) { - path = lng.split("."); - } else { - path = [lng, ns]; - if (key) { - if (Array.isArray(key)) { - path.push(...key); - } else if (isString(key) && keySeparator) { - path.push(...key.split(keySeparator)); - } else { - path.push(key); - } - } - } - const result = getPath2(this.data, path); - if (!result && !ns && !key && lng.indexOf(".") > -1) { - lng = path[0]; - ns = path[1]; - key = path.slice(2).join("."); - } - if (result || !ignoreJSONStructure || !isString(key)) return result; - return deepFind(this.data?.[lng]?.[ns], key, keySeparator); - } - addResource(lng, ns, key, value, options = { - silent: false - }) { - const keySeparator = options.keySeparator !== void 0 ? options.keySeparator : this.options.keySeparator; - let path = [lng, ns]; - if (key) path = path.concat(keySeparator ? key.split(keySeparator) : key); - if (lng.indexOf(".") > -1) { - path = lng.split("."); - value = ns; - ns = path[1]; - } - this.addNamespaces(ns); - setPath(this.data, path, value); - if (!options.silent) this.emit("added", lng, ns, key, value); - } - addResources(lng, ns, resources, options = { - silent: false - }) { - for (const m2 in resources) { - if (isString(resources[m2]) || Array.isArray(resources[m2])) this.addResource(lng, ns, m2, resources[m2], { - silent: true - }); - } - if (!options.silent) this.emit("added", lng, ns, resources); - } - addResourceBundle(lng, ns, resources, deep, overwrite, options = { - silent: false, - skipCopy: false - }) { - let path = [lng, ns]; - if (lng.indexOf(".") > -1) { - path = lng.split("."); - deep = resources; - resources = ns; - ns = path[1]; - } - this.addNamespaces(ns); - let pack = getPath2(this.data, path) || {}; - if (!options.skipCopy) resources = JSON.parse(JSON.stringify(resources)); - if (deep) { - deepExtend(pack, resources, overwrite); - } else { - pack = { - ...pack, - ...resources - }; - } - setPath(this.data, path, pack); - if (!options.silent) this.emit("added", lng, ns, resources); - } - removeResourceBundle(lng, ns) { - if (this.hasResourceBundle(lng, ns)) { - delete this.data[lng][ns]; - } - this.removeNamespaces(ns); - this.emit("removed", lng, ns); - } - hasResourceBundle(lng, ns) { - return this.getResource(lng, ns) !== void 0; - } - getResourceBundle(lng, ns) { - if (!ns) ns = this.options.defaultNS; - return this.getResource(lng, ns); - } - getDataByLanguage(lng) { - return this.data[lng]; - } - hasLanguageSomeTranslations(lng) { - const data2 = this.getDataByLanguage(lng); - const n = data2 && Object.keys(data2) || []; - return !!n.find((v) => data2[v] && Object.keys(data2[v]).length > 0); - } - toJSON() { - return this.data; - } -}; -var postProcessor = { - processors: {}, - addPostProcessor(module) { - this.processors[module.name] = module; - }, - handle(processors, value, key, options, translator) { - processors.forEach((processor) => { - value = this.processors[processor]?.process(value, key, options, translator) ?? value; - }); - return value; - } -}; -var PATH_KEY = /* @__PURE__ */ Symbol("i18next/PATH_KEY"); -function createProxy() { - const state = []; - const handler = /* @__PURE__ */ Object.create(null); - let proxy; - handler.get = (target, key) => { - proxy?.revoke?.(); - if (key === PATH_KEY) return state; - state.push(key); - proxy = Proxy.revocable(target, handler); - return proxy.proxy; - }; - return Proxy.revocable(/* @__PURE__ */ Object.create(null), handler).proxy; -} -__name(createProxy, "createProxy"); -function keysFromSelector(selector, opts) { - const { - [PATH_KEY]: path - } = selector(createProxy()); - return path.join(opts?.keySeparator ?? "."); -} -__name(keysFromSelector, "keysFromSelector"); -var checkedLoadedFor = {}; -var shouldHandleAsObject = /* @__PURE__ */ __name((res) => !isString(res) && typeof res !== "boolean" && typeof res !== "number", "shouldHandleAsObject"); -var Translator = class _Translator extends EventEmitter { - static { - __name(this, "Translator"); - } - constructor(services, options = {}) { - super(); - copy(["resourceStore", "languageUtils", "pluralResolver", "interpolator", "backendConnector", "i18nFormat", "utils"], services, this); - this.options = options; - if (this.options.keySeparator === void 0) { - this.options.keySeparator = "."; - } - this.logger = baseLogger.create("translator"); - } - changeLanguage(lng) { - if (lng) this.language = lng; - } - exists(key, o = { - interpolation: {} - }) { - const opt = { - ...o - }; - if (key == null) return false; - const resolved = this.resolve(key, opt); - if (resolved?.res === void 0) return false; - const isObject = shouldHandleAsObject(resolved.res); - if (opt.returnObjects === false && isObject) { - return false; - } - return true; - } - extractFromKey(key, opt) { - let nsSeparator = opt.nsSeparator !== void 0 ? opt.nsSeparator : this.options.nsSeparator; - if (nsSeparator === void 0) nsSeparator = ":"; - const keySeparator = opt.keySeparator !== void 0 ? opt.keySeparator : this.options.keySeparator; - let namespaces = opt.ns || this.options.defaultNS || []; - const wouldCheckForNsInKey = nsSeparator && key.indexOf(nsSeparator) > -1; - const seemsNaturalLanguage = !this.options.userDefinedKeySeparator && !opt.keySeparator && !this.options.userDefinedNsSeparator && !opt.nsSeparator && !looksLikeObjectPath(key, nsSeparator, keySeparator); - if (wouldCheckForNsInKey && !seemsNaturalLanguage) { - const m2 = key.match(this.interpolator.nestingRegexp); - if (m2 && m2.length > 0) { - return { - key, - namespaces: isString(namespaces) ? [namespaces] : namespaces - }; - } - const parts = key.split(nsSeparator); - if (nsSeparator !== keySeparator || nsSeparator === keySeparator && this.options.ns.indexOf(parts[0]) > -1) namespaces = parts.shift(); - key = parts.join(keySeparator); - } - return { - key, - namespaces: isString(namespaces) ? [namespaces] : namespaces - }; - } - translate(keys, o, lastKey) { - let opt = typeof o === "object" ? { - ...o - } : o; - if (typeof opt !== "object" && this.options.overloadTranslationOptionHandler) { - opt = this.options.overloadTranslationOptionHandler(arguments); - } - if (typeof opt === "object") opt = { - ...opt - }; - if (!opt) opt = {}; - if (keys == null) return ""; - if (typeof keys === "function") keys = keysFromSelector(keys, { - ...this.options, - ...opt - }); - if (!Array.isArray(keys)) keys = [String(keys)]; - const returnDetails = opt.returnDetails !== void 0 ? opt.returnDetails : this.options.returnDetails; - const keySeparator = opt.keySeparator !== void 0 ? opt.keySeparator : this.options.keySeparator; - const { - key, - namespaces - } = this.extractFromKey(keys[keys.length - 1], opt); - const namespace = namespaces[namespaces.length - 1]; - let nsSeparator = opt.nsSeparator !== void 0 ? opt.nsSeparator : this.options.nsSeparator; - if (nsSeparator === void 0) nsSeparator = ":"; - const lng = opt.lng || this.language; - const appendNamespaceToCIMode = opt.appendNamespaceToCIMode || this.options.appendNamespaceToCIMode; - if (lng?.toLowerCase() === "cimode") { - if (appendNamespaceToCIMode) { - if (returnDetails) { - return { - res: `${namespace}${nsSeparator}${key}`, - usedKey: key, - exactUsedKey: key, - usedLng: lng, - usedNS: namespace, - usedParams: this.getUsedParamsDetails(opt) - }; - } - return `${namespace}${nsSeparator}${key}`; - } - if (returnDetails) { - return { - res: key, - usedKey: key, - exactUsedKey: key, - usedLng: lng, - usedNS: namespace, - usedParams: this.getUsedParamsDetails(opt) - }; - } - return key; - } - const resolved = this.resolve(keys, opt); - let res = resolved?.res; - const resUsedKey = resolved?.usedKey || key; - const resExactUsedKey = resolved?.exactUsedKey || key; - const noObject = ["[object Number]", "[object Function]", "[object RegExp]"]; - const joinArrays = opt.joinArrays !== void 0 ? opt.joinArrays : this.options.joinArrays; - const handleAsObjectInI18nFormat = !this.i18nFormat || this.i18nFormat.handleAsObject; - const needsPluralHandling = opt.count !== void 0 && !isString(opt.count); - const hasDefaultValue = _Translator.hasDefaultValue(opt); - const defaultValueSuffix = needsPluralHandling ? this.pluralResolver.getSuffix(lng, opt.count, opt) : ""; - const defaultValueSuffixOrdinalFallback = opt.ordinal && needsPluralHandling ? this.pluralResolver.getSuffix(lng, opt.count, { - ordinal: false - }) : ""; - const needsZeroSuffixLookup = needsPluralHandling && !opt.ordinal && opt.count === 0; - const defaultValue = needsZeroSuffixLookup && opt[`defaultValue${this.options.pluralSeparator}zero`] || opt[`defaultValue${defaultValueSuffix}`] || opt[`defaultValue${defaultValueSuffixOrdinalFallback}`] || opt.defaultValue; - let resForObjHndl = res; - if (handleAsObjectInI18nFormat && !res && hasDefaultValue) { - resForObjHndl = defaultValue; - } - const handleAsObject = shouldHandleAsObject(resForObjHndl); - const resType = Object.prototype.toString.apply(resForObjHndl); - if (handleAsObjectInI18nFormat && resForObjHndl && handleAsObject && noObject.indexOf(resType) < 0 && !(isString(joinArrays) && Array.isArray(resForObjHndl))) { - if (!opt.returnObjects && !this.options.returnObjects) { - if (!this.options.returnedObjectHandler) { - this.logger.warn("accessing an object - but returnObjects options is not enabled!"); - } - const r = this.options.returnedObjectHandler ? this.options.returnedObjectHandler(resUsedKey, resForObjHndl, { - ...opt, - ns: namespaces - }) : `key '${key} (${this.language})' returned an object instead of string.`; - if (returnDetails) { - resolved.res = r; - resolved.usedParams = this.getUsedParamsDetails(opt); - return resolved; - } - return r; - } - if (keySeparator) { - const resTypeIsArray = Array.isArray(resForObjHndl); - const copy2 = resTypeIsArray ? [] : {}; - const newKeyToUse = resTypeIsArray ? resExactUsedKey : resUsedKey; - for (const m2 in resForObjHndl) { - if (Object.prototype.hasOwnProperty.call(resForObjHndl, m2)) { - const deepKey = `${newKeyToUse}${keySeparator}${m2}`; - if (hasDefaultValue && !res) { - copy2[m2] = this.translate(deepKey, { - ...opt, - defaultValue: shouldHandleAsObject(defaultValue) ? defaultValue[m2] : void 0, - ...{ - joinArrays: false, - ns: namespaces - } - }); - } else { - copy2[m2] = this.translate(deepKey, { - ...opt, - ...{ - joinArrays: false, - ns: namespaces - } - }); - } - if (copy2[m2] === deepKey) copy2[m2] = resForObjHndl[m2]; - } - } - res = copy2; - } - } else if (handleAsObjectInI18nFormat && isString(joinArrays) && Array.isArray(res)) { - res = res.join(joinArrays); - if (res) res = this.extendTranslation(res, keys, opt, lastKey); - } else { - let usedDefault = false; - let usedKey = false; - if (!this.isValidLookup(res) && hasDefaultValue) { - usedDefault = true; - res = defaultValue; - } - if (!this.isValidLookup(res)) { - usedKey = true; - res = key; - } - const missingKeyNoValueFallbackToKey = opt.missingKeyNoValueFallbackToKey || this.options.missingKeyNoValueFallbackToKey; - const resForMissing = missingKeyNoValueFallbackToKey && usedKey ? void 0 : res; - const updateMissing = hasDefaultValue && defaultValue !== res && this.options.updateMissing; - if (usedKey || usedDefault || updateMissing) { - this.logger.log(updateMissing ? "updateKey" : "missingKey", lng, namespace, key, updateMissing ? defaultValue : res); - if (keySeparator) { - const fk = this.resolve(key, { - ...opt, - keySeparator: false - }); - if (fk && fk.res) this.logger.warn("Seems the loaded translations were in flat JSON format instead of nested. Either set keySeparator: false on init or make sure your translations are published in nested format."); - } - let lngs = []; - const fallbackLngs = this.languageUtils.getFallbackCodes(this.options.fallbackLng, opt.lng || this.language); - if (this.options.saveMissingTo === "fallback" && fallbackLngs && fallbackLngs[0]) { - for (let i = 0; i < fallbackLngs.length; i++) { - lngs.push(fallbackLngs[i]); - } - } else if (this.options.saveMissingTo === "all") { - lngs = this.languageUtils.toResolveHierarchy(opt.lng || this.language); - } else { - lngs.push(opt.lng || this.language); - } - const send = /* @__PURE__ */ __name((l, k, specificDefaultValue) => { - const defaultForMissing = hasDefaultValue && specificDefaultValue !== res ? specificDefaultValue : resForMissing; - if (this.options.missingKeyHandler) { - this.options.missingKeyHandler(l, namespace, k, defaultForMissing, updateMissing, opt); - } else if (this.backendConnector?.saveMissing) { - this.backendConnector.saveMissing(l, namespace, k, defaultForMissing, updateMissing, opt); - } - this.emit("missingKey", l, namespace, k, res); - }, "send"); - if (this.options.saveMissing) { - if (this.options.saveMissingPlurals && needsPluralHandling) { - lngs.forEach((language) => { - const suffixes = this.pluralResolver.getSuffixes(language, opt); - if (needsZeroSuffixLookup && opt[`defaultValue${this.options.pluralSeparator}zero`] && suffixes.indexOf(`${this.options.pluralSeparator}zero`) < 0) { - suffixes.push(`${this.options.pluralSeparator}zero`); - } - suffixes.forEach((suffix) => { - send([language], key + suffix, opt[`defaultValue${suffix}`] || defaultValue); - }); - }); - } else { - send(lngs, key, defaultValue); - } - } - } - res = this.extendTranslation(res, keys, opt, resolved, lastKey); - if (usedKey && res === key && this.options.appendNamespaceToMissingKey) { - res = `${namespace}${nsSeparator}${key}`; - } - if ((usedKey || usedDefault) && this.options.parseMissingKeyHandler) { - res = this.options.parseMissingKeyHandler(this.options.appendNamespaceToMissingKey ? `${namespace}${nsSeparator}${key}` : key, usedDefault ? res : void 0, opt); - } - } - if (returnDetails) { - resolved.res = res; - resolved.usedParams = this.getUsedParamsDetails(opt); - return resolved; - } - return res; - } - extendTranslation(res, key, opt, resolved, lastKey) { - if (this.i18nFormat?.parse) { - res = this.i18nFormat.parse(res, { - ...this.options.interpolation.defaultVariables, - ...opt - }, opt.lng || this.language || resolved.usedLng, resolved.usedNS, resolved.usedKey, { - resolved - }); - } else if (!opt.skipInterpolation) { - if (opt.interpolation) this.interpolator.init({ - ...opt, - ...{ - interpolation: { - ...this.options.interpolation, - ...opt.interpolation - } - } - }); - const skipOnVariables = isString(res) && (opt?.interpolation?.skipOnVariables !== void 0 ? opt.interpolation.skipOnVariables : this.options.interpolation.skipOnVariables); - let nestBef; - if (skipOnVariables) { - const nb = res.match(this.interpolator.nestingRegexp); - nestBef = nb && nb.length; - } - let data2 = opt.replace && !isString(opt.replace) ? opt.replace : opt; - if (this.options.interpolation.defaultVariables) data2 = { - ...this.options.interpolation.defaultVariables, - ...data2 - }; - res = this.interpolator.interpolate(res, data2, opt.lng || this.language || resolved.usedLng, opt); - if (skipOnVariables) { - const na = res.match(this.interpolator.nestingRegexp); - const nestAft = na && na.length; - if (nestBef < nestAft) opt.nest = false; - } - if (!opt.lng && resolved && resolved.res) opt.lng = this.language || resolved.usedLng; - if (opt.nest !== false) res = this.interpolator.nest(res, (...args) => { - if (lastKey?.[0] === args[0] && !opt.context) { - this.logger.warn(`It seems you are nesting recursively key: ${args[0]} in key: ${key[0]}`); - return null; - } - return this.translate(...args, key); - }, opt); - if (opt.interpolation) this.interpolator.reset(); - } - const postProcess = opt.postProcess || this.options.postProcess; - const postProcessorNames = isString(postProcess) ? [postProcess] : postProcess; - if (res != null && postProcessorNames?.length && opt.applyPostProcessor !== false) { - res = postProcessor.handle(postProcessorNames, res, key, this.options && this.options.postProcessPassResolved ? { - i18nResolved: { - ...resolved, - usedParams: this.getUsedParamsDetails(opt) - }, - ...opt - } : opt, this); - } - return res; - } - resolve(keys, opt = {}) { - let found; - let usedKey; - let exactUsedKey; - let usedLng; - let usedNS; - if (isString(keys)) keys = [keys]; - keys.forEach((k) => { - if (this.isValidLookup(found)) return; - const extracted = this.extractFromKey(k, opt); - const key = extracted.key; - usedKey = key; - let namespaces = extracted.namespaces; - if (this.options.fallbackNS) namespaces = namespaces.concat(this.options.fallbackNS); - const needsPluralHandling = opt.count !== void 0 && !isString(opt.count); - const needsZeroSuffixLookup = needsPluralHandling && !opt.ordinal && opt.count === 0; - const needsContextHandling = opt.context !== void 0 && (isString(opt.context) || typeof opt.context === "number") && opt.context !== ""; - const codes = opt.lngs ? opt.lngs : this.languageUtils.toResolveHierarchy(opt.lng || this.language, opt.fallbackLng); - namespaces.forEach((ns) => { - if (this.isValidLookup(found)) return; - usedNS = ns; - if (!checkedLoadedFor[`${codes[0]}-${ns}`] && this.utils?.hasLoadedNamespace && !this.utils?.hasLoadedNamespace(usedNS)) { - checkedLoadedFor[`${codes[0]}-${ns}`] = true; - this.logger.warn(`key "${usedKey}" for languages "${codes.join(", ")}" won't get resolved as namespace "${usedNS}" was not yet loaded`, "This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!"); - } - codes.forEach((code) => { - if (this.isValidLookup(found)) return; - usedLng = code; - const finalKeys = [key]; - if (this.i18nFormat?.addLookupKeys) { - this.i18nFormat.addLookupKeys(finalKeys, key, code, ns, opt); - } else { - let pluralSuffix; - if (needsPluralHandling) pluralSuffix = this.pluralResolver.getSuffix(code, opt.count, opt); - const zeroSuffix = `${this.options.pluralSeparator}zero`; - const ordinalPrefix = `${this.options.pluralSeparator}ordinal${this.options.pluralSeparator}`; - if (needsPluralHandling) { - if (opt.ordinal && pluralSuffix.indexOf(ordinalPrefix) === 0) { - finalKeys.push(key + pluralSuffix.replace(ordinalPrefix, this.options.pluralSeparator)); - } - finalKeys.push(key + pluralSuffix); - if (needsZeroSuffixLookup) { - finalKeys.push(key + zeroSuffix); - } - } - if (needsContextHandling) { - const contextKey = `${key}${this.options.contextSeparator || "_"}${opt.context}`; - finalKeys.push(contextKey); - if (needsPluralHandling) { - if (opt.ordinal && pluralSuffix.indexOf(ordinalPrefix) === 0) { - finalKeys.push(contextKey + pluralSuffix.replace(ordinalPrefix, this.options.pluralSeparator)); - } - finalKeys.push(contextKey + pluralSuffix); - if (needsZeroSuffixLookup) { - finalKeys.push(contextKey + zeroSuffix); - } - } - } - } - let possibleKey; - while (possibleKey = finalKeys.pop()) { - if (!this.isValidLookup(found)) { - exactUsedKey = possibleKey; - found = this.getResource(code, ns, possibleKey, opt); - } - } - }); - }); - }); - return { - res: found, - usedKey, - exactUsedKey, - usedLng, - usedNS - }; - } - isValidLookup(res) { - return res !== void 0 && !(!this.options.returnNull && res === null) && !(!this.options.returnEmptyString && res === ""); - } - getResource(code, ns, key, options = {}) { - if (this.i18nFormat?.getResource) return this.i18nFormat.getResource(code, ns, key, options); - return this.resourceStore.getResource(code, ns, key, options); - } - getUsedParamsDetails(options = {}) { - const optionsKeys = ["defaultValue", "ordinal", "context", "replace", "lng", "lngs", "fallbackLng", "ns", "keySeparator", "nsSeparator", "returnObjects", "returnDetails", "joinArrays", "postProcess", "interpolation"]; - const useOptionsReplaceForData = options.replace && !isString(options.replace); - let data2 = useOptionsReplaceForData ? options.replace : options; - if (useOptionsReplaceForData && typeof options.count !== "undefined") { - data2.count = options.count; - } - if (this.options.interpolation.defaultVariables) { - data2 = { - ...this.options.interpolation.defaultVariables, - ...data2 - }; - } - if (!useOptionsReplaceForData) { - data2 = { - ...data2 - }; - for (const key of optionsKeys) { - delete data2[key]; - } - } - return data2; - } - static hasDefaultValue(options) { - const prefix = "defaultValue"; - for (const option in options) { - if (Object.prototype.hasOwnProperty.call(options, option) && prefix === option.substring(0, prefix.length) && void 0 !== options[option]) { - return true; - } - } - return false; - } -}; -var LanguageUtil = class { - static { - __name(this, "LanguageUtil"); - } - constructor(options) { - this.options = options; - this.supportedLngs = this.options.supportedLngs || false; - this.logger = baseLogger.create("languageUtils"); - } - getScriptPartFromCode(code) { - code = getCleanedCode(code); - if (!code || code.indexOf("-") < 0) return null; - const p = code.split("-"); - if (p.length === 2) return null; - p.pop(); - if (p[p.length - 1].toLowerCase() === "x") return null; - return this.formatLanguageCode(p.join("-")); - } - getLanguagePartFromCode(code) { - code = getCleanedCode(code); - if (!code || code.indexOf("-") < 0) return code; - const p = code.split("-"); - return this.formatLanguageCode(p[0]); - } - formatLanguageCode(code) { - if (isString(code) && code.indexOf("-") > -1) { - let formattedCode; - try { - formattedCode = Intl.getCanonicalLocales(code)[0]; - } catch (e) { - } - if (formattedCode && this.options.lowerCaseLng) { - formattedCode = formattedCode.toLowerCase(); - } - if (formattedCode) return formattedCode; - if (this.options.lowerCaseLng) { - return code.toLowerCase(); - } - return code; - } - return this.options.cleanCode || this.options.lowerCaseLng ? code.toLowerCase() : code; - } - isSupportedCode(code) { - if (this.options.load === "languageOnly" || this.options.nonExplicitSupportedLngs) { - code = this.getLanguagePartFromCode(code); - } - return !this.supportedLngs || !this.supportedLngs.length || this.supportedLngs.indexOf(code) > -1; - } - getBestMatchFromCodes(codes) { - if (!codes) return null; - let found; - codes.forEach((code) => { - if (found) return; - const cleanedLng = this.formatLanguageCode(code); - if (!this.options.supportedLngs || this.isSupportedCode(cleanedLng)) found = cleanedLng; - }); - if (!found && this.options.supportedLngs) { - codes.forEach((code) => { - if (found) return; - const lngScOnly = this.getScriptPartFromCode(code); - if (this.isSupportedCode(lngScOnly)) return found = lngScOnly; - const lngOnly = this.getLanguagePartFromCode(code); - if (this.isSupportedCode(lngOnly)) return found = lngOnly; - found = this.options.supportedLngs.find((supportedLng) => { - if (supportedLng === lngOnly) return supportedLng; - if (supportedLng.indexOf("-") < 0 && lngOnly.indexOf("-") < 0) return; - if (supportedLng.indexOf("-") > 0 && lngOnly.indexOf("-") < 0 && supportedLng.substring(0, supportedLng.indexOf("-")) === lngOnly) return supportedLng; - if (supportedLng.indexOf(lngOnly) === 0 && lngOnly.length > 1) return supportedLng; - }); - }); - } - if (!found) found = this.getFallbackCodes(this.options.fallbackLng)[0]; - return found; - } - getFallbackCodes(fallbacks, code) { - if (!fallbacks) return []; - if (typeof fallbacks === "function") fallbacks = fallbacks(code); - if (isString(fallbacks)) fallbacks = [fallbacks]; - if (Array.isArray(fallbacks)) return fallbacks; - if (!code) return fallbacks.default || []; - let found = fallbacks[code]; - if (!found) found = fallbacks[this.getScriptPartFromCode(code)]; - if (!found) found = fallbacks[this.formatLanguageCode(code)]; - if (!found) found = fallbacks[this.getLanguagePartFromCode(code)]; - if (!found) found = fallbacks.default; - return found || []; - } - toResolveHierarchy(code, fallbackCode) { - const fallbackCodes = this.getFallbackCodes((fallbackCode === false ? [] : fallbackCode) || this.options.fallbackLng || [], code); - const codes = []; - const addCode = /* @__PURE__ */ __name((c) => { - if (!c) return; - if (this.isSupportedCode(c)) { - codes.push(c); - } else { - this.logger.warn(`rejecting language code not found in supportedLngs: ${c}`); - } - }, "addCode"); - if (isString(code) && (code.indexOf("-") > -1 || code.indexOf("_") > -1)) { - if (this.options.load !== "languageOnly") addCode(this.formatLanguageCode(code)); - if (this.options.load !== "languageOnly" && this.options.load !== "currentOnly") addCode(this.getScriptPartFromCode(code)); - if (this.options.load !== "currentOnly") addCode(this.getLanguagePartFromCode(code)); - } else if (isString(code)) { - addCode(this.formatLanguageCode(code)); - } - fallbackCodes.forEach((fc) => { - if (codes.indexOf(fc) < 0) addCode(this.formatLanguageCode(fc)); - }); - return codes; - } -}; -var suffixesOrder = { - zero: 0, - one: 1, - two: 2, - few: 3, - many: 4, - other: 5 -}; -var dummyRule = { - select: /* @__PURE__ */ __name((count2) => count2 === 1 ? "one" : "other", "select"), - resolvedOptions: /* @__PURE__ */ __name(() => ({ - pluralCategories: ["one", "other"] - }), "resolvedOptions") -}; -var PluralResolver = class { - static { - __name(this, "PluralResolver"); - } - constructor(languageUtils, options = {}) { - this.languageUtils = languageUtils; - this.options = options; - this.logger = baseLogger.create("pluralResolver"); - this.pluralRulesCache = {}; - } - clearCache() { - this.pluralRulesCache = {}; - } - getRule(code, options = {}) { - const cleanedCode = getCleanedCode(code === "dev" ? "en" : code); - const type = options.ordinal ? "ordinal" : "cardinal"; - const cacheKey = JSON.stringify({ - cleanedCode, - type - }); - if (cacheKey in this.pluralRulesCache) { - return this.pluralRulesCache[cacheKey]; - } - let rule; - try { - rule = new Intl.PluralRules(cleanedCode, { - type - }); - } catch (err) { - if (typeof Intl === "undefined") { - this.logger.error("No Intl support, please use an Intl polyfill!"); - return dummyRule; - } - if (!code.match(/-|_/)) return dummyRule; - const lngPart = this.languageUtils.getLanguagePartFromCode(code); - rule = this.getRule(lngPart, options); - } - this.pluralRulesCache[cacheKey] = rule; - return rule; - } - needsPlural(code, options = {}) { - let rule = this.getRule(code, options); - if (!rule) rule = this.getRule("dev", options); - return rule?.resolvedOptions().pluralCategories.length > 1; - } - getPluralFormsOfKey(code, key, options = {}) { - return this.getSuffixes(code, options).map((suffix) => `${key}${suffix}`); - } - getSuffixes(code, options = {}) { - let rule = this.getRule(code, options); - if (!rule) rule = this.getRule("dev", options); - if (!rule) return []; - return rule.resolvedOptions().pluralCategories.sort((pluralCategory1, pluralCategory2) => suffixesOrder[pluralCategory1] - suffixesOrder[pluralCategory2]).map((pluralCategory) => `${this.options.prepend}${options.ordinal ? `ordinal${this.options.prepend}` : ""}${pluralCategory}`); - } - getSuffix(code, count2, options = {}) { - const rule = this.getRule(code, options); - if (rule) { - return `${this.options.prepend}${options.ordinal ? `ordinal${this.options.prepend}` : ""}${rule.select(count2)}`; - } - this.logger.warn(`no plural rule found for: ${code}`); - return this.getSuffix("dev", count2, options); - } -}; -var deepFindWithDefaults = /* @__PURE__ */ __name((data2, defaultData, key, keySeparator = ".", ignoreJSONStructure = true) => { - let path = getPathWithDefaults(data2, defaultData, key); - if (!path && ignoreJSONStructure && isString(key)) { - path = deepFind(data2, key, keySeparator); - if (path === void 0) path = deepFind(defaultData, key, keySeparator); - } - return path; -}, "deepFindWithDefaults"); -var regexSafe = /* @__PURE__ */ __name((val) => val.replace(/\$/g, "$$$$"), "regexSafe"); -var Interpolator = class { - static { - __name(this, "Interpolator"); - } - constructor(options = {}) { - this.logger = baseLogger.create("interpolator"); - this.options = options; - this.format = options?.interpolation?.format || ((value) => value); - this.init(options); - } - init(options = {}) { - if (!options.interpolation) options.interpolation = { - escapeValue: true - }; - const { - escape: escape$1, - escapeValue, - useRawValueToEscape, - prefix, - prefixEscaped, - suffix, - suffixEscaped, - formatSeparator, - unescapeSuffix, - unescapePrefix, - nestingPrefix, - nestingPrefixEscaped, - nestingSuffix, - nestingSuffixEscaped, - nestingOptionsSeparator, - maxReplaces, - alwaysFormat - } = options.interpolation; - this.escape = escape$1 !== void 0 ? escape$1 : escape; - this.escapeValue = escapeValue !== void 0 ? escapeValue : true; - this.useRawValueToEscape = useRawValueToEscape !== void 0 ? useRawValueToEscape : false; - this.prefix = prefix ? regexEscape(prefix) : prefixEscaped || "{{"; - this.suffix = suffix ? regexEscape(suffix) : suffixEscaped || "}}"; - this.formatSeparator = formatSeparator || ","; - this.unescapePrefix = unescapeSuffix ? "" : unescapePrefix || "-"; - this.unescapeSuffix = this.unescapePrefix ? "" : unescapeSuffix || ""; - this.nestingPrefix = nestingPrefix ? regexEscape(nestingPrefix) : nestingPrefixEscaped || regexEscape("$t("); - this.nestingSuffix = nestingSuffix ? regexEscape(nestingSuffix) : nestingSuffixEscaped || regexEscape(")"); - this.nestingOptionsSeparator = nestingOptionsSeparator || ","; - this.maxReplaces = maxReplaces || 1e3; - this.alwaysFormat = alwaysFormat !== void 0 ? alwaysFormat : false; - this.resetRegExp(); - } - reset() { - if (this.options) this.init(this.options); - } - resetRegExp() { - const getOrResetRegExp = /* @__PURE__ */ __name((existingRegExp, pattern) => { - if (existingRegExp?.source === pattern) { - existingRegExp.lastIndex = 0; - return existingRegExp; - } - return new RegExp(pattern, "g"); - }, "getOrResetRegExp"); - this.regexp = getOrResetRegExp(this.regexp, `${this.prefix}(.+?)${this.suffix}`); - this.regexpUnescape = getOrResetRegExp(this.regexpUnescape, `${this.prefix}${this.unescapePrefix}(.+?)${this.unescapeSuffix}${this.suffix}`); - this.nestingRegexp = getOrResetRegExp(this.nestingRegexp, `${this.nestingPrefix}((?:[^()"']+|"[^"]*"|'[^']*'|\\((?:[^()]|"[^"]*"|'[^']*')*\\))*?)${this.nestingSuffix}`); - } - interpolate(str2, data2, lng, options) { - let match3; - let value; - let replaces; - const defaultData = this.options && this.options.interpolation && this.options.interpolation.defaultVariables || {}; - const handleFormat = /* @__PURE__ */ __name((key) => { - if (key.indexOf(this.formatSeparator) < 0) { - const path = deepFindWithDefaults(data2, defaultData, key, this.options.keySeparator, this.options.ignoreJSONStructure); - return this.alwaysFormat ? this.format(path, void 0, lng, { - ...options, - ...data2, - interpolationkey: key - }) : path; - } - const p = key.split(this.formatSeparator); - const k = p.shift().trim(); - const f = p.join(this.formatSeparator).trim(); - return this.format(deepFindWithDefaults(data2, defaultData, k, this.options.keySeparator, this.options.ignoreJSONStructure), f, lng, { - ...options, - ...data2, - interpolationkey: k - }); - }, "handleFormat"); - this.resetRegExp(); - const missingInterpolationHandler = options?.missingInterpolationHandler || this.options.missingInterpolationHandler; - const skipOnVariables = options?.interpolation?.skipOnVariables !== void 0 ? options.interpolation.skipOnVariables : this.options.interpolation.skipOnVariables; - const todos = [{ - regex: this.regexpUnescape, - safeValue: /* @__PURE__ */ __name((val) => regexSafe(val), "safeValue") - }, { - regex: this.regexp, - safeValue: /* @__PURE__ */ __name((val) => this.escapeValue ? regexSafe(this.escape(val)) : regexSafe(val), "safeValue") - }]; - todos.forEach((todo) => { - replaces = 0; - while (match3 = todo.regex.exec(str2)) { - const matchedVar = match3[1].trim(); - value = handleFormat(matchedVar); - if (value === void 0) { - if (typeof missingInterpolationHandler === "function") { - const temp = missingInterpolationHandler(str2, match3, options); - value = isString(temp) ? temp : ""; - } else if (options && Object.prototype.hasOwnProperty.call(options, matchedVar)) { - value = ""; - } else if (skipOnVariables) { - value = match3[0]; - continue; - } else { - this.logger.warn(`missed to pass in variable ${matchedVar} for interpolating ${str2}`); - value = ""; - } - } else if (!isString(value) && !this.useRawValueToEscape) { - value = makeString(value); - } - const safeValue = todo.safeValue(value); - str2 = str2.replace(match3[0], safeValue); - if (skipOnVariables) { - todo.regex.lastIndex += value.length; - todo.regex.lastIndex -= match3[0].length; - } else { - todo.regex.lastIndex = 0; - } - replaces++; - if (replaces >= this.maxReplaces) { - break; - } - } - }); - return str2; - } - nest(str2, fc, options = {}) { - let match3; - let value; - let clonedOptions; - const handleHasOptions = /* @__PURE__ */ __name((key, inheritedOptions) => { - const sep = this.nestingOptionsSeparator; - if (key.indexOf(sep) < 0) return key; - const c = key.split(new RegExp(`${regexEscape(sep)}[ ]*{`)); - let optionsString = `{${c[1]}`; - key = c[0]; - optionsString = this.interpolate(optionsString, clonedOptions); - const matchedSingleQuotes = optionsString.match(/'/g); - const matchedDoubleQuotes = optionsString.match(/"/g); - if ((matchedSingleQuotes?.length ?? 0) % 2 === 0 && !matchedDoubleQuotes || (matchedDoubleQuotes?.length ?? 0) % 2 !== 0) { - optionsString = optionsString.replace(/'/g, '"'); - } - try { - clonedOptions = JSON.parse(optionsString); - if (inheritedOptions) clonedOptions = { - ...inheritedOptions, - ...clonedOptions - }; - } catch (e) { - this.logger.warn(`failed parsing options string in nesting for key ${key}`, e); - return `${key}${sep}${optionsString}`; - } - if (clonedOptions.defaultValue && clonedOptions.defaultValue.indexOf(this.prefix) > -1) delete clonedOptions.defaultValue; - return key; - }, "handleHasOptions"); - while (match3 = this.nestingRegexp.exec(str2)) { - let formatters = []; - clonedOptions = { - ...options - }; - clonedOptions = clonedOptions.replace && !isString(clonedOptions.replace) ? clonedOptions.replace : clonedOptions; - clonedOptions.applyPostProcessor = false; - delete clonedOptions.defaultValue; - const keyEndIndex = /{.*}/.test(match3[1]) ? match3[1].lastIndexOf("}") + 1 : match3[1].indexOf(this.formatSeparator); - if (keyEndIndex !== -1) { - formatters = match3[1].slice(keyEndIndex).split(this.formatSeparator).map((elem) => elem.trim()).filter(Boolean); - match3[1] = match3[1].slice(0, keyEndIndex); - } - value = fc(handleHasOptions.call(this, match3[1].trim(), clonedOptions), clonedOptions); - if (value && match3[0] === str2 && !isString(value)) return value; - if (!isString(value)) value = makeString(value); - if (!value) { - this.logger.warn(`missed to resolve ${match3[1]} for nesting ${str2}`); - value = ""; - } - if (formatters.length) { - value = formatters.reduce((v, f) => this.format(v, f, options.lng, { - ...options, - interpolationkey: match3[1].trim() - }), value.trim()); - } - str2 = str2.replace(match3[0], value); - this.regexp.lastIndex = 0; - } - return str2; - } -}; -var parseFormatStr = /* @__PURE__ */ __name((formatStr) => { - let formatName = formatStr.toLowerCase().trim(); - const formatOptions = {}; - if (formatStr.indexOf("(") > -1) { - const p = formatStr.split("("); - formatName = p[0].toLowerCase().trim(); - const optStr = p[1].substring(0, p[1].length - 1); - if (formatName === "currency" && optStr.indexOf(":") < 0) { - if (!formatOptions.currency) formatOptions.currency = optStr.trim(); - } else if (formatName === "relativetime" && optStr.indexOf(":") < 0) { - if (!formatOptions.range) formatOptions.range = optStr.trim(); - } else { - const opts = optStr.split(";"); - opts.forEach((opt) => { - if (opt) { - const [key, ...rest] = opt.split(":"); - const val = rest.join(":").trim().replace(/^'+|'+$/g, ""); - const trimmedKey = key.trim(); - if (!formatOptions[trimmedKey]) formatOptions[trimmedKey] = val; - if (val === "false") formatOptions[trimmedKey] = false; - if (val === "true") formatOptions[trimmedKey] = true; - if (!isNaN(val)) formatOptions[trimmedKey] = parseInt(val, 10); - } - }); - } - } - return { - formatName, - formatOptions - }; -}, "parseFormatStr"); -var createCachedFormatter = /* @__PURE__ */ __name((fn) => { - const cache = {}; - return (v, l, o) => { - let optForCache = o; - if (o && o.interpolationkey && o.formatParams && o.formatParams[o.interpolationkey] && o[o.interpolationkey]) { - optForCache = { - ...optForCache, - [o.interpolationkey]: void 0 - }; - } - const key = l + JSON.stringify(optForCache); - let frm = cache[key]; - if (!frm) { - frm = fn(getCleanedCode(l), o); - cache[key] = frm; - } - return frm(v); - }; -}, "createCachedFormatter"); -var createNonCachedFormatter = /* @__PURE__ */ __name((fn) => (v, l, o) => fn(getCleanedCode(l), o)(v), "createNonCachedFormatter"); -var Formatter = class { - static { - __name(this, "Formatter"); - } - constructor(options = {}) { - this.logger = baseLogger.create("formatter"); - this.options = options; - this.init(options); - } - init(services, options = { - interpolation: {} - }) { - this.formatSeparator = options.interpolation.formatSeparator || ","; - const cf = options.cacheInBuiltFormats ? createCachedFormatter : createNonCachedFormatter; - this.formats = { - number: cf((lng, opt) => { - const formatter = new Intl.NumberFormat(lng, { - ...opt - }); - return (val) => formatter.format(val); - }), - currency: cf((lng, opt) => { - const formatter = new Intl.NumberFormat(lng, { - ...opt, - style: "currency" - }); - return (val) => formatter.format(val); - }), - datetime: cf((lng, opt) => { - const formatter = new Intl.DateTimeFormat(lng, { - ...opt - }); - return (val) => formatter.format(val); - }), - relativetime: cf((lng, opt) => { - const formatter = new Intl.RelativeTimeFormat(lng, { - ...opt - }); - return (val) => formatter.format(val, opt.range || "day"); - }), - list: cf((lng, opt) => { - const formatter = new Intl.ListFormat(lng, { - ...opt - }); - return (val) => formatter.format(val); - }) - }; - } - add(name, fc) { - this.formats[name.toLowerCase().trim()] = fc; - } - addCached(name, fc) { - this.formats[name.toLowerCase().trim()] = createCachedFormatter(fc); - } - format(value, format, lng, options = {}) { - const formats = format.split(this.formatSeparator); - if (formats.length > 1 && formats[0].indexOf("(") > 1 && formats[0].indexOf(")") < 0 && formats.find((f) => f.indexOf(")") > -1)) { - const lastIndex = formats.findIndex((f) => f.indexOf(")") > -1); - formats[0] = [formats[0], ...formats.splice(1, lastIndex)].join(this.formatSeparator); - } - const result = formats.reduce((mem, f) => { - const { - formatName, - formatOptions - } = parseFormatStr(f); - if (this.formats[formatName]) { - let formatted = mem; - try { - const valOptions = options?.formatParams?.[options.interpolationkey] || {}; - const l = valOptions.locale || valOptions.lng || options.locale || options.lng || lng; - formatted = this.formats[formatName](mem, l, { - ...formatOptions, - ...options, - ...valOptions - }); - } catch (error) { - this.logger.warn(error); - } - return formatted; - } else { - this.logger.warn(`there was no format function for ${formatName}`); - } - return mem; - }, value); - return result; - } -}; -var removePending = /* @__PURE__ */ __name((q, name) => { - if (q.pending[name] !== void 0) { - delete q.pending[name]; - q.pendingCount--; - } -}, "removePending"); -var Connector = class extends EventEmitter { - static { - __name(this, "Connector"); - } - constructor(backend, store, services, options = {}) { - super(); - this.backend = backend; - this.store = store; - this.services = services; - this.languageUtils = services.languageUtils; - this.options = options; - this.logger = baseLogger.create("backendConnector"); - this.waitingReads = []; - this.maxParallelReads = options.maxParallelReads || 10; - this.readingCalls = 0; - this.maxRetries = options.maxRetries >= 0 ? options.maxRetries : 5; - this.retryTimeout = options.retryTimeout >= 1 ? options.retryTimeout : 350; - this.state = {}; - this.queue = []; - this.backend?.init?.(services, options.backend, options); - } - queueLoad(languages, namespaces, options, callback) { - const toLoad = {}; - const pending = {}; - const toLoadLanguages = {}; - const toLoadNamespaces = {}; - languages.forEach((lng) => { - let hasAllNamespaces = true; - namespaces.forEach((ns) => { - const name = `${lng}|${ns}`; - if (!options.reload && this.store.hasResourceBundle(lng, ns)) { - this.state[name] = 2; - } else if (this.state[name] < 0) ; - else if (this.state[name] === 1) { - if (pending[name] === void 0) pending[name] = true; - } else { - this.state[name] = 1; - hasAllNamespaces = false; - if (pending[name] === void 0) pending[name] = true; - if (toLoad[name] === void 0) toLoad[name] = true; - if (toLoadNamespaces[ns] === void 0) toLoadNamespaces[ns] = true; - } - }); - if (!hasAllNamespaces) toLoadLanguages[lng] = true; - }); - if (Object.keys(toLoad).length || Object.keys(pending).length) { - this.queue.push({ - pending, - pendingCount: Object.keys(pending).length, - loaded: {}, - errors: [], - callback - }); - } - return { - toLoad: Object.keys(toLoad), - pending: Object.keys(pending), - toLoadLanguages: Object.keys(toLoadLanguages), - toLoadNamespaces: Object.keys(toLoadNamespaces) - }; - } - loaded(name, err, data2) { - const s2 = name.split("|"); - const lng = s2[0]; - const ns = s2[1]; - if (err) this.emit("failedLoading", lng, ns, err); - if (!err && data2) { - this.store.addResourceBundle(lng, ns, data2, void 0, void 0, { - skipCopy: true - }); - } - this.state[name] = err ? -1 : 2; - if (err && data2) this.state[name] = 0; - const loaded = {}; - this.queue.forEach((q) => { - pushPath(q.loaded, [lng], ns); - removePending(q, name); - if (err) q.errors.push(err); - if (q.pendingCount === 0 && !q.done) { - Object.keys(q.loaded).forEach((l) => { - if (!loaded[l]) loaded[l] = {}; - const loadedKeys = q.loaded[l]; - if (loadedKeys.length) { - loadedKeys.forEach((n) => { - if (loaded[l][n] === void 0) loaded[l][n] = true; - }); - } - }); - q.done = true; - if (q.errors.length) { - q.callback(q.errors); - } else { - q.callback(); - } - } - }); - this.emit("loaded", loaded); - this.queue = this.queue.filter((q) => !q.done); - } - read(lng, ns, fcName, tried = 0, wait = this.retryTimeout, callback) { - if (!lng.length) return callback(null, {}); - if (this.readingCalls >= this.maxParallelReads) { - this.waitingReads.push({ - lng, - ns, - fcName, - tried, - wait, - callback - }); - return; - } - this.readingCalls++; - const resolver = /* @__PURE__ */ __name((err, data2) => { - this.readingCalls--; - if (this.waitingReads.length > 0) { - const next = this.waitingReads.shift(); - this.read(next.lng, next.ns, next.fcName, next.tried, next.wait, next.callback); - } - if (err && data2 && tried < this.maxRetries) { - setTimeout(() => { - this.read.call(this, lng, ns, fcName, tried + 1, wait * 2, callback); - }, wait); - return; - } - callback(err, data2); - }, "resolver"); - const fc = this.backend[fcName].bind(this.backend); - if (fc.length === 2) { - try { - const r = fc(lng, ns); - if (r && typeof r.then === "function") { - r.then((data2) => resolver(null, data2)).catch(resolver); - } else { - resolver(null, r); - } - } catch (err) { - resolver(err); - } - return; - } - return fc(lng, ns, resolver); - } - prepareLoading(languages, namespaces, options = {}, callback) { - if (!this.backend) { - this.logger.warn("No backend was added via i18next.use. Will not load resources."); - return callback && callback(); - } - if (isString(languages)) languages = this.languageUtils.toResolveHierarchy(languages); - if (isString(namespaces)) namespaces = [namespaces]; - const toLoad = this.queueLoad(languages, namespaces, options, callback); - if (!toLoad.toLoad.length) { - if (!toLoad.pending.length) callback(); - return null; - } - toLoad.toLoad.forEach((name) => { - this.loadOne(name); - }); - } - load(languages, namespaces, callback) { - this.prepareLoading(languages, namespaces, {}, callback); - } - reload(languages, namespaces, callback) { - this.prepareLoading(languages, namespaces, { - reload: true - }, callback); - } - loadOne(name, prefix = "") { - const s2 = name.split("|"); - const lng = s2[0]; - const ns = s2[1]; - this.read(lng, ns, "read", void 0, void 0, (err, data2) => { - if (err) this.logger.warn(`${prefix}loading namespace ${ns} for language ${lng} failed`, err); - if (!err && data2) this.logger.log(`${prefix}loaded namespace ${ns} for language ${lng}`, data2); - this.loaded(name, err, data2); - }); - } - saveMissing(languages, namespace, key, fallbackValue, isUpdate, options = {}, clb = () => { - }) { - if (this.services?.utils?.hasLoadedNamespace && !this.services?.utils?.hasLoadedNamespace(namespace)) { - this.logger.warn(`did not save key "${key}" as the namespace "${namespace}" was not yet loaded`, "This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!"); - return; - } - if (key === void 0 || key === null || key === "") return; - if (this.backend?.create) { - const opts = { - ...options, - isUpdate - }; - const fc = this.backend.create.bind(this.backend); - if (fc.length < 6) { - try { - let r; - if (fc.length === 5) { - r = fc(languages, namespace, key, fallbackValue, opts); - } else { - r = fc(languages, namespace, key, fallbackValue); - } - if (r && typeof r.then === "function") { - r.then((data2) => clb(null, data2)).catch(clb); - } else { - clb(null, r); - } - } catch (err) { - clb(err); - } - } else { - fc(languages, namespace, key, fallbackValue, clb, opts); - } - } - if (!languages || !languages[0]) return; - this.store.addResource(languages[0], namespace, key, fallbackValue); - } -}; -var get = /* @__PURE__ */ __name(() => ({ - debug: false, - initAsync: true, - ns: ["translation"], - defaultNS: ["translation"], - fallbackLng: ["dev"], - fallbackNS: false, - supportedLngs: false, - nonExplicitSupportedLngs: false, - load: "all", - preload: false, - simplifyPluralSuffix: true, - keySeparator: ".", - nsSeparator: ":", - pluralSeparator: "_", - contextSeparator: "_", - partialBundledLanguages: false, - saveMissing: false, - updateMissing: false, - saveMissingTo: "fallback", - saveMissingPlurals: true, - missingKeyHandler: false, - missingInterpolationHandler: false, - postProcess: false, - postProcessPassResolved: false, - returnNull: false, - returnEmptyString: true, - returnObjects: false, - joinArrays: false, - returnedObjectHandler: false, - parseMissingKeyHandler: false, - appendNamespaceToMissingKey: false, - appendNamespaceToCIMode: false, - overloadTranslationOptionHandler: /* @__PURE__ */ __name((args) => { - let ret = {}; - if (typeof args[1] === "object") ret = args[1]; - if (isString(args[1])) ret.defaultValue = args[1]; - if (isString(args[2])) ret.tDescription = args[2]; - if (typeof args[2] === "object" || typeof args[3] === "object") { - const options = args[3] || args[2]; - Object.keys(options).forEach((key) => { - ret[key] = options[key]; - }); - } - return ret; - }, "overloadTranslationOptionHandler"), - interpolation: { - escapeValue: true, - format: /* @__PURE__ */ __name((value) => value, "format"), - prefix: "{{", - suffix: "}}", - formatSeparator: ",", - unescapePrefix: "-", - nestingPrefix: "$t(", - nestingSuffix: ")", - nestingOptionsSeparator: ",", - maxReplaces: 1e3, - skipOnVariables: true - }, - cacheInBuiltFormats: true -}), "get"); -var transformOptions = /* @__PURE__ */ __name((options) => { - if (isString(options.ns)) options.ns = [options.ns]; - if (isString(options.fallbackLng)) options.fallbackLng = [options.fallbackLng]; - if (isString(options.fallbackNS)) options.fallbackNS = [options.fallbackNS]; - if (options.supportedLngs?.indexOf?.("cimode") < 0) { - options.supportedLngs = options.supportedLngs.concat(["cimode"]); - } - if (typeof options.initImmediate === "boolean") options.initAsync = options.initImmediate; - return options; -}, "transformOptions"); -var noop2 = /* @__PURE__ */ __name(() => { -}, "noop"); -var bindMemberFunctions = /* @__PURE__ */ __name((inst) => { - const mems = Object.getOwnPropertyNames(Object.getPrototypeOf(inst)); - mems.forEach((mem) => { - if (typeof inst[mem] === "function") { - inst[mem] = inst[mem].bind(inst); - } - }); -}, "bindMemberFunctions"); -var SUPPORT_NOTICE_KEY = "__i18next_supportNoticeShown"; -var getSupportNoticeShown = /* @__PURE__ */ __name(() => typeof globalThis !== "undefined" && !!globalThis[SUPPORT_NOTICE_KEY], "getSupportNoticeShown"); -var setSupportNoticeShown = /* @__PURE__ */ __name(() => { - if (typeof globalThis !== "undefined") globalThis[SUPPORT_NOTICE_KEY] = true; -}, "setSupportNoticeShown"); -var usesLocize = /* @__PURE__ */ __name((inst) => { - if (inst?.modules?.backend?.name?.indexOf("Locize") > 0) return true; - if (inst?.modules?.backend?.constructor?.name?.indexOf("Locize") > 0) return true; - if (inst?.options?.backend?.backends) { - if (inst.options.backend.backends.some((b) => b?.name?.indexOf("Locize") > 0 || b?.constructor?.name?.indexOf("Locize") > 0)) return true; - } - if (inst?.options?.backend?.projectId) return true; - if (inst?.options?.backend?.backendOptions) { - if (inst.options.backend.backendOptions.some((b) => b?.projectId)) return true; - } - return false; -}, "usesLocize"); -var I18n = class _I18n extends EventEmitter { - static { - __name(this, "I18n"); - } - constructor(options = {}, callback) { - super(); - this.options = transformOptions(options); - this.services = {}; - this.logger = baseLogger; - this.modules = { - external: [] - }; - bindMemberFunctions(this); - if (callback && !this.isInitialized && !options.isClone) { - if (!this.options.initAsync) { - this.init(options, callback); - return this; - } - setTimeout(() => { - this.init(options, callback); - }, 0); - } - } - init(options = {}, callback) { - this.isInitializing = true; - if (typeof options === "function") { - callback = options; - options = {}; - } - if (options.defaultNS == null && options.ns) { - if (isString(options.ns)) { - options.defaultNS = options.ns; - } else if (options.ns.indexOf("translation") < 0) { - options.defaultNS = options.ns[0]; - } - } - const defOpts = get(); - this.options = { - ...defOpts, - ...this.options, - ...transformOptions(options) - }; - this.options.interpolation = { - ...defOpts.interpolation, - ...this.options.interpolation - }; - if (options.keySeparator !== void 0) { - this.options.userDefinedKeySeparator = options.keySeparator; - } - if (options.nsSeparator !== void 0) { - this.options.userDefinedNsSeparator = options.nsSeparator; - } - if (typeof this.options.overloadTranslationOptionHandler !== "function") { - this.options.overloadTranslationOptionHandler = defOpts.overloadTranslationOptionHandler; - } - if (this.options.showSupportNotice !== false && !usesLocize(this) && !getSupportNoticeShown()) { - if (typeof console !== "undefined" && typeof console.info !== "undefined") console.info("\u{1F310} i18next is maintained with support from Locize \u2014 consider powering your project with managed localization (AI, CDN, integrations): https://locize.com \u{1F499}"); - setSupportNoticeShown(); - } - const createClassOnDemand = /* @__PURE__ */ __name((ClassOrObject) => { - if (!ClassOrObject) return null; - if (typeof ClassOrObject === "function") return new ClassOrObject(); - return ClassOrObject; - }, "createClassOnDemand"); - if (!this.options.isClone) { - if (this.modules.logger) { - baseLogger.init(createClassOnDemand(this.modules.logger), this.options); - } else { - baseLogger.init(null, this.options); - } - let formatter; - if (this.modules.formatter) { - formatter = this.modules.formatter; - } else { - formatter = Formatter; - } - const lu = new LanguageUtil(this.options); - this.store = new ResourceStore(this.options.resources, this.options); - const s2 = this.services; - s2.logger = baseLogger; - s2.resourceStore = this.store; - s2.languageUtils = lu; - s2.pluralResolver = new PluralResolver(lu, { - prepend: this.options.pluralSeparator, - simplifyPluralSuffix: this.options.simplifyPluralSuffix - }); - const usingLegacyFormatFunction = this.options.interpolation.format && this.options.interpolation.format !== defOpts.interpolation.format; - if (usingLegacyFormatFunction) { - this.logger.deprecate(`init: you are still using the legacy format function, please use the new approach: https://www.i18next.com/translation-function/formatting`); - } - if (formatter && (!this.options.interpolation.format || this.options.interpolation.format === defOpts.interpolation.format)) { - s2.formatter = createClassOnDemand(formatter); - if (s2.formatter.init) s2.formatter.init(s2, this.options); - this.options.interpolation.format = s2.formatter.format.bind(s2.formatter); - } - s2.interpolator = new Interpolator(this.options); - s2.utils = { - hasLoadedNamespace: this.hasLoadedNamespace.bind(this) - }; - s2.backendConnector = new Connector(createClassOnDemand(this.modules.backend), s2.resourceStore, s2, this.options); - s2.backendConnector.on("*", (event, ...args) => { - this.emit(event, ...args); - }); - if (this.modules.languageDetector) { - s2.languageDetector = createClassOnDemand(this.modules.languageDetector); - if (s2.languageDetector.init) s2.languageDetector.init(s2, this.options.detection, this.options); - } - if (this.modules.i18nFormat) { - s2.i18nFormat = createClassOnDemand(this.modules.i18nFormat); - if (s2.i18nFormat.init) s2.i18nFormat.init(this); - } - this.translator = new Translator(this.services, this.options); - this.translator.on("*", (event, ...args) => { - this.emit(event, ...args); - }); - this.modules.external.forEach((m2) => { - if (m2.init) m2.init(this); - }); - } - this.format = this.options.interpolation.format; - if (!callback) callback = noop2; - if (this.options.fallbackLng && !this.services.languageDetector && !this.options.lng) { - const codes = this.services.languageUtils.getFallbackCodes(this.options.fallbackLng); - if (codes.length > 0 && codes[0] !== "dev") this.options.lng = codes[0]; - } - if (!this.services.languageDetector && !this.options.lng) { - this.logger.warn("init: no languageDetector is used and no lng is defined"); - } - const storeApi = ["getResource", "hasResourceBundle", "getResourceBundle", "getDataByLanguage"]; - storeApi.forEach((fcName) => { - this[fcName] = (...args) => this.store[fcName](...args); - }); - const storeApiChained = ["addResource", "addResources", "addResourceBundle", "removeResourceBundle"]; - storeApiChained.forEach((fcName) => { - this[fcName] = (...args) => { - this.store[fcName](...args); - return this; - }; - }); - const deferred = defer(); - const load = /* @__PURE__ */ __name(() => { - const finish = /* @__PURE__ */ __name((err, t2) => { - this.isInitializing = false; - if (this.isInitialized && !this.initializedStoreOnce) this.logger.warn("init: i18next is already initialized. You should call init just once!"); - this.isInitialized = true; - if (!this.options.isClone) this.logger.log("initialized", this.options); - this.emit("initialized", this.options); - deferred.resolve(t2); - callback(err, t2); - }, "finish"); - if (this.languages && !this.isInitialized) return finish(null, this.t.bind(this)); - this.changeLanguage(this.options.lng, finish); - }, "load"); - if (this.options.resources || !this.options.initAsync) { - load(); - } else { - setTimeout(load, 0); - } - return deferred; - } - loadResources(language, callback = noop2) { - let usedCallback = callback; - const usedLng = isString(language) ? language : this.language; - if (typeof language === "function") usedCallback = language; - if (!this.options.resources || this.options.partialBundledLanguages) { - if (usedLng?.toLowerCase() === "cimode" && (!this.options.preload || this.options.preload.length === 0)) return usedCallback(); - const toLoad = []; - const append = /* @__PURE__ */ __name((lng) => { - if (!lng) return; - if (lng === "cimode") return; - const lngs = this.services.languageUtils.toResolveHierarchy(lng); - lngs.forEach((l) => { - if (l === "cimode") return; - if (toLoad.indexOf(l) < 0) toLoad.push(l); - }); - }, "append"); - if (!usedLng) { - const fallbacks = this.services.languageUtils.getFallbackCodes(this.options.fallbackLng); - fallbacks.forEach((l) => append(l)); - } else { - append(usedLng); - } - this.options.preload?.forEach?.((l) => append(l)); - this.services.backendConnector.load(toLoad, this.options.ns, (e) => { - if (!e && !this.resolvedLanguage && this.language) this.setResolvedLanguage(this.language); - usedCallback(e); - }); - } else { - usedCallback(null); - } - } - reloadResources(lngs, ns, callback) { - const deferred = defer(); - if (typeof lngs === "function") { - callback = lngs; - lngs = void 0; - } - if (typeof ns === "function") { - callback = ns; - ns = void 0; - } - if (!lngs) lngs = this.languages; - if (!ns) ns = this.options.ns; - if (!callback) callback = noop2; - this.services.backendConnector.reload(lngs, ns, (err) => { - deferred.resolve(); - callback(err); - }); - return deferred; - } - use(module) { - if (!module) throw new Error("You are passing an undefined module! Please check the object you are passing to i18next.use()"); - if (!module.type) throw new Error("You are passing a wrong module! Please check the object you are passing to i18next.use()"); - if (module.type === "backend") { - this.modules.backend = module; - } - if (module.type === "logger" || module.log && module.warn && module.error) { - this.modules.logger = module; - } - if (module.type === "languageDetector") { - this.modules.languageDetector = module; - } - if (module.type === "i18nFormat") { - this.modules.i18nFormat = module; - } - if (module.type === "postProcessor") { - postProcessor.addPostProcessor(module); - } - if (module.type === "formatter") { - this.modules.formatter = module; - } - if (module.type === "3rdParty") { - this.modules.external.push(module); - } - return this; - } - setResolvedLanguage(l) { - if (!l || !this.languages) return; - if (["cimode", "dev"].indexOf(l) > -1) return; - for (let li = 0; li < this.languages.length; li++) { - const lngInLngs = this.languages[li]; - if (["cimode", "dev"].indexOf(lngInLngs) > -1) continue; - if (this.store.hasLanguageSomeTranslations(lngInLngs)) { - this.resolvedLanguage = lngInLngs; - break; - } - } - if (!this.resolvedLanguage && this.languages.indexOf(l) < 0 && this.store.hasLanguageSomeTranslations(l)) { - this.resolvedLanguage = l; - this.languages.unshift(l); - } - } - changeLanguage(lng, callback) { - this.isLanguageChangingTo = lng; - const deferred = defer(); - this.emit("languageChanging", lng); - const setLngProps = /* @__PURE__ */ __name((l) => { - this.language = l; - this.languages = this.services.languageUtils.toResolveHierarchy(l); - this.resolvedLanguage = void 0; - this.setResolvedLanguage(l); - }, "setLngProps"); - const done = /* @__PURE__ */ __name((err, l) => { - if (l) { - if (this.isLanguageChangingTo === lng) { - setLngProps(l); - this.translator.changeLanguage(l); - this.isLanguageChangingTo = void 0; - this.emit("languageChanged", l); - this.logger.log("languageChanged", l); - } - } else { - this.isLanguageChangingTo = void 0; - } - deferred.resolve((...args) => this.t(...args)); - if (callback) callback(err, (...args) => this.t(...args)); - }, "done"); - const setLng = /* @__PURE__ */ __name((lngs) => { - if (!lng && !lngs && this.services.languageDetector) lngs = []; - const fl = isString(lngs) ? lngs : lngs && lngs[0]; - const l = this.store.hasLanguageSomeTranslations(fl) ? fl : this.services.languageUtils.getBestMatchFromCodes(isString(lngs) ? [lngs] : lngs); - if (l) { - if (!this.language) { - setLngProps(l); - } - if (!this.translator.language) this.translator.changeLanguage(l); - this.services.languageDetector?.cacheUserLanguage?.(l); - } - this.loadResources(l, (err) => { - done(err, l); - }); - }, "setLng"); - if (!lng && this.services.languageDetector && !this.services.languageDetector.async) { - setLng(this.services.languageDetector.detect()); - } else if (!lng && this.services.languageDetector && this.services.languageDetector.async) { - if (this.services.languageDetector.detect.length === 0) { - this.services.languageDetector.detect().then(setLng); - } else { - this.services.languageDetector.detect(setLng); - } - } else { - setLng(lng); - } - return deferred; - } - getFixedT(lng, ns, keyPrefix) { - const fixedT = /* @__PURE__ */ __name((key, opts, ...rest) => { - let o; - if (typeof opts !== "object") { - o = this.options.overloadTranslationOptionHandler([key, opts].concat(rest)); - } else { - o = { - ...opts - }; - } - o.lng = o.lng || fixedT.lng; - o.lngs = o.lngs || fixedT.lngs; - o.ns = o.ns || fixedT.ns; - if (o.keyPrefix !== "") o.keyPrefix = o.keyPrefix || keyPrefix || fixedT.keyPrefix; - const keySeparator = this.options.keySeparator || "."; - let resultKey; - if (o.keyPrefix && Array.isArray(key)) { - resultKey = key.map((k) => { - if (typeof k === "function") k = keysFromSelector(k, { - ...this.options, - ...opts - }); - return `${o.keyPrefix}${keySeparator}${k}`; - }); - } else { - if (typeof key === "function") key = keysFromSelector(key, { - ...this.options, - ...opts - }); - resultKey = o.keyPrefix ? `${o.keyPrefix}${keySeparator}${key}` : key; - } - return this.t(resultKey, o); - }, "fixedT"); - if (isString(lng)) { - fixedT.lng = lng; - } else { - fixedT.lngs = lng; - } - fixedT.ns = ns; - fixedT.keyPrefix = keyPrefix; - return fixedT; - } - t(...args) { - return this.translator?.translate(...args); - } - exists(...args) { - return this.translator?.exists(...args); - } - setDefaultNamespace(ns) { - this.options.defaultNS = ns; - } - hasLoadedNamespace(ns, options = {}) { - if (!this.isInitialized) { - this.logger.warn("hasLoadedNamespace: i18next was not initialized", this.languages); - return false; - } - if (!this.languages || !this.languages.length) { - this.logger.warn("hasLoadedNamespace: i18n.languages were undefined or empty", this.languages); - return false; - } - const lng = options.lng || this.resolvedLanguage || this.languages[0]; - const fallbackLng = this.options ? this.options.fallbackLng : false; - const lastLng = this.languages[this.languages.length - 1]; - if (lng.toLowerCase() === "cimode") return true; - const loadNotPending = /* @__PURE__ */ __name((l, n) => { - const loadState = this.services.backendConnector.state[`${l}|${n}`]; - return loadState === -1 || loadState === 0 || loadState === 2; - }, "loadNotPending"); - if (options.precheck) { - const preResult = options.precheck(this, loadNotPending); - if (preResult !== void 0) return preResult; - } - if (this.hasResourceBundle(lng, ns)) return true; - if (!this.services.backendConnector.backend || this.options.resources && !this.options.partialBundledLanguages) return true; - if (loadNotPending(lng, ns) && (!fallbackLng || loadNotPending(lastLng, ns))) return true; - return false; - } - loadNamespaces(ns, callback) { - const deferred = defer(); - if (!this.options.ns) { - if (callback) callback(); - return Promise.resolve(); - } - if (isString(ns)) ns = [ns]; - ns.forEach((n) => { - if (this.options.ns.indexOf(n) < 0) this.options.ns.push(n); - }); - this.loadResources((err) => { - deferred.resolve(); - if (callback) callback(err); - }); - return deferred; - } - loadLanguages(lngs, callback) { - const deferred = defer(); - if (isString(lngs)) lngs = [lngs]; - const preloaded = this.options.preload || []; - const newLngs = lngs.filter((lng) => preloaded.indexOf(lng) < 0 && this.services.languageUtils.isSupportedCode(lng)); - if (!newLngs.length) { - if (callback) callback(); - return Promise.resolve(); - } - this.options.preload = preloaded.concat(newLngs); - this.loadResources((err) => { - deferred.resolve(); - if (callback) callback(err); - }); - return deferred; - } - dir(lng) { - if (!lng) lng = this.resolvedLanguage || (this.languages?.length > 0 ? this.languages[0] : this.language); - if (!lng) return "rtl"; - try { - const l = new Intl.Locale(lng); - if (l && l.getTextInfo) { - const ti = l.getTextInfo(); - if (ti && ti.direction) return ti.direction; - } - } catch (e) { - } - const rtlLngs = ["ar", "shu", "sqr", "ssh", "xaa", "yhd", "yud", "aao", "abh", "abv", "acm", "acq", "acw", "acx", "acy", "adf", "ads", "aeb", "aec", "afb", "ajp", "apc", "apd", "arb", "arq", "ars", "ary", "arz", "auz", "avl", "ayh", "ayl", "ayn", "ayp", "bbz", "pga", "he", "iw", "ps", "pbt", "pbu", "pst", "prp", "prd", "ug", "ur", "ydd", "yds", "yih", "ji", "yi", "hbo", "men", "xmn", "fa", "jpr", "peo", "pes", "prs", "dv", "sam", "ckb"]; - const languageUtils = this.services?.languageUtils || new LanguageUtil(get()); - if (lng.toLowerCase().indexOf("-latn") > 1) return "ltr"; - return rtlLngs.indexOf(languageUtils.getLanguagePartFromCode(lng)) > -1 || lng.toLowerCase().indexOf("-arab") > 1 ? "rtl" : "ltr"; - } - static createInstance(options = {}, callback) { - const instance2 = new _I18n(options, callback); - instance2.createInstance = _I18n.createInstance; - return instance2; - } - cloneInstance(options = {}, callback = noop2) { - const forkResourceStore = options.forkResourceStore; - if (forkResourceStore) delete options.forkResourceStore; - const mergedOptions = { - ...this.options, - ...options, - ...{ - isClone: true - } - }; - const clone = new _I18n(mergedOptions); - if (options.debug !== void 0 || options.prefix !== void 0) { - clone.logger = clone.logger.clone(options); - } - const membersToCopy = ["store", "services", "language"]; - membersToCopy.forEach((m2) => { - clone[m2] = this[m2]; - }); - clone.services = { - ...this.services - }; - clone.services.utils = { - hasLoadedNamespace: clone.hasLoadedNamespace.bind(clone) - }; - if (forkResourceStore) { - const clonedData = Object.keys(this.store.data).reduce((prev, l) => { - prev[l] = { - ...this.store.data[l] - }; - prev[l] = Object.keys(prev[l]).reduce((acc, n) => { - acc[n] = { - ...prev[l][n] - }; - return acc; - }, prev[l]); - return prev; - }, {}); - clone.store = new ResourceStore(clonedData, mergedOptions); - clone.services.resourceStore = clone.store; - } - if (options.interpolation) { - const defOpts = get(); - const mergedInterpolation = { - ...defOpts.interpolation, - ...this.options.interpolation, - ...options.interpolation - }; - const mergedForInterpolator = { - ...mergedOptions, - interpolation: mergedInterpolation - }; - clone.services.interpolator = new Interpolator(mergedForInterpolator); - } - clone.translator = new Translator(clone.services, mergedOptions); - clone.translator.on("*", (event, ...args) => { - clone.emit(event, ...args); - }); - clone.init(mergedOptions, callback); - clone.translator.options = mergedOptions; - clone.translator.backendConnector.services.utils = { - hasLoadedNamespace: clone.hasLoadedNamespace.bind(clone) - }; - return clone; - } - toJSON() { - return { - options: this.options, - store: this.store, - language: this.language, - languages: this.languages, - resolvedLanguage: this.resolvedLanguage - }; - } -}; -var instance = I18n.createInstance(); -var createInstance = instance.createInstance; -var dir = instance.dir; -var init = instance.init; -var loadResources = instance.loadResources; -var reloadResources = instance.reloadResources; -var use = instance.use; -var changeLanguage = instance.changeLanguage; -var getFixedT = instance.getFixedT; -var t = instance.t; -var exists2 = instance.exists; -var setDefaultNamespace = instance.setDefaultNamespace; -var hasLoadedNamespace = instance.hasLoadedNamespace; -var loadNamespaces = instance.loadNamespaces; -var loadLanguages = instance.loadLanguages; - -// locales/en.json -var en_default = { - language: { - name: "English", - changed: "Language is set to english.", - emoji: "\u{1F1EC}\u{1F1E7}" - }, - bot: { - description: "Hello! I will notify you when Twitch broadcasts start." - }, - enable: "Enable", - disable: "Disable", - enabled: "Enabled", - disabled: "Disabled", - commands: { - follow: { - errors: { - badUsername: '{{ streamer }} - username can only contain "a-z", "0-9" and "_" symbols.', - streamerNotFound: "{{ streamer }} - not found on twitch.", - alreadyFollowed: "{{ streamer }} - already followed." - }, - success: "{{ streamer }} - now followed.", - enter: "Enter username of streamer you want to follow.\nYou can use multiple links to streamers.\n\nType /cancel for cancel action." - }, - follows: { - total: "You followed to notifications from {{ count }} channels. Click on streamer nickname to unfollow from notifications." - }, - unfollow: { - callbackButton: "Unfollow {{ streamer }}", - success: "Unfollowed from {{ streamer }}" - }, - start: { - game_change_notification_setting: { - button: "Game change notification" - }, - language: { - button: "\u{1F30D} Language" - }, - offline_notification: { - button: "Offline notification" - }, - title_change_notification_setting: { - button: "Title change notification" - }, - image_in_notification_setting: { - button: "Show images in notifications" - }, - game_and_title_change_notification_setting: { - button: "Game and title change notification" - } - } - }, - notifications: { - streams: { - nowOffline: "\u{1F534} {{ channelLink }} now offline.\n{{ categories }}\n{{ duration }}", - nowOnline: "\u{1F7E2} {{ channelLink }} now online.\nCategory: {{ category }}\nTitle: {{ title }}", - newCategory: "\u{1F504} {{ channelLink }} updated category from {{ oldCategory }} to {{ category }}", - titleChanged: "\u{1F504} {{ channelLink }} updated title from {{ oldTitle }} to {{ title }}", - titleAndCategoryChanged: "\u{1F504} {{ channelLink }} updated title from {{ oldTitle }} to {{ title }} and category from {{ oldCategory }} to {{ category }}" - } - } -}; - -// locales/ru.json -var ru_default = { - language: { - name: "\u0420\u0443\u0441\u0441\u043A\u0438\u0439", - changed: "\u042F\u0437\u044B\u043A \u0443\u0441\u0442\u0430\u043D\u043E\u0432\u043B\u0435\u043D \u043D\u0430 \u0440\u0443\u0441\u0441\u043A\u0438\u0439.", - emoji: "\u{1F1F7}\u{1F1FA}" - }, - bot: { - description: "\u0417\u0434\u0440\u0430\u0432\u0441\u0442\u0432\u0443\u0439\u0442\u0435! \u042F \u0431\u0443\u0434\u0443 \u0443\u0432\u0435\u0434\u043E\u043C\u043B\u044F\u0442\u044C \u0432\u0430\u0441 \u043E \u043D\u0430\u0447\u0430\u043B\u0435 \u0442\u0440\u0430\u043D\u0441\u043B\u044F\u0446\u0438\u0439 Twitch." - }, - enable: "\u0412\u043A\u043B\u044E\u0447\u0438\u0442\u044C", - disable: "\u0412\u044B\u043A\u043B\u044E\u0447\u0438\u0442\u044C", - enabled: "\u0412\u043A\u043B\u044E\u0447\u0435\u043D\u043E", - disabled: "\u0412\u044B\u043A\u043B\u044E\u0447\u0435\u043D\u043E", - commands: { - follow: { - errors: { - badUsername: '\u0418\u043C\u044F \u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044F \u043C\u043E\u0436\u0435\u0442 \u0441\u043E\u0434\u0435\u0440\u0436\u0430\u0442\u044C \u0442\u043E\u043B\u044C\u043A\u043E "a-z", "0-9" and "_" \u0441\u0438\u043C\u0432\u043E\u043B\u044B.', - streamerNotFound: "{{ streamer }} - \u043D\u0435 \u043D\u0430\u0439\u0434\u0435\u043D \u043D\u0430 \u0442\u0432\u0438\u0447\u0435.", - alreadyFollowed: "{{ streamer }} - \u0432\u044B \u0443\u0436\u0435 \u043F\u043E\u0434\u043F\u0438\u0441\u0430\u043D\u044B." - }, - success: "{{ streamer }} - \u0442\u0435\u043F\u0435\u0440\u044C \u043E\u0442\u0441\u043B\u0435\u0436\u0438\u0432\u0430\u0435\u0442\u0441\u044F.", - enter: "\u0412\u0432\u0435\u0434\u0438\u0442\u0435 \u0438\u043C\u044F \u0441\u0442\u0440\u0438\u043C\u0435\u0440\u0430, \u0443\u0432\u0435\u0434\u043E\u043C\u043B\u0435\u043D\u0438\u044F \u043E\u0442 \u043A\u043E\u0442\u043E\u0440\u043E\u0433\u043E \u0445\u043E\u0442\u0438\u0442\u0435 \u043F\u043E\u043B\u0443\u0447\u0430\u0442\u044C.\n\u0412\u044B \u043C\u043E\u0436\u0435\u0442\u0435 \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u044C \u0441\u0441\u044B\u043B\u043A\u0438.\n\n\u0412\u0432\u0435\u0434\u0438\u0442\u0435 /cancel \u0434\u043B\u044F \u043E\u0442\u043C\u0435\u043D\u044B \u0434\u0435\u0439\u0441\u0442\u0432\u0438\u044F." - }, - follows: { - total: "\u0412\u044B \u043F\u043E\u0434\u043F\u0438\u0441\u0430\u043D\u044B \u043D\u0430 \u0443\u0432\u0435\u0434\u043E\u043C\u043B\u0435\u043D\u0438\u044F {{ count }} \u043A\u0430\u043D\u0430\u043B\u043E\u0432. \u041A\u043B\u0438\u043A\u043D\u0438\u0442\u0435 \u043D\u0430 \u043D\u0438\u043A\u043D\u0435\u0439\u043C \u0441\u0442\u0440\u0438\u043C\u0435\u0440\u0430, \u0447\u0442\u043E\u0431\u044B \u043E\u0442\u043F\u0438\u0441\u0430\u0442\u044C\u0441\u044F \u043E\u0442 \u0443\u0432\u0435\u0434\u043E\u043C\u043B\u0435\u043D\u0438\u0439." - }, - unfollow: { - callbackButton: "\u041E\u0442\u043F\u0438\u0441\u0430\u0442\u044C\u0441\u044F \u043E\u0442 {{ streamer }}", - success: "\u0412\u044B \u043E\u0442\u043F\u0438\u0441\u0430\u043B\u0438\u0441\u044C \u043E\u0442 {{ streamer }}" - }, - start: { - game_change_notification_setting: { - button: "\u0423\u0432\u0435\u0434\u043E\u043C\u043B\u0435\u043D\u0438\u0435 \u043E \u0441\u043C\u0435\u043D\u0435 \u043A\u0430\u0442\u0435\u0433\u043E\u0440\u0438\u0438" - }, - language: { - button: "\u{1F30D} \u042F\u0437\u044B\u043A" - }, - offline_notification: { - button: "\u0423\u0432\u0435\u0434\u043E\u043C\u043B\u0435\u043D\u0438\u0435 \u043E\u0431 \u0443\u0445\u043E\u0434\u0435 \u0432 \u043E\u0444\u0444\u043B\u0430\u0439\u043D" - }, - title_change_notification_setting: { - button: "\u0423\u0432\u0435\u0434\u043E\u043C\u043B\u0435\u043D\u0438\u0435 \u043E \u0441\u043C\u0435\u043D\u0435 \u043D\u0430\u0437\u0432\u0430\u043D\u0438\u044F" - }, - image_in_notification_setting: { - button: "\u041F\u043E\u043A\u0430\u0437\u044B\u0432\u0430\u0442\u044C \u0438\u0437\u043E\u0431\u0440\u0430\u0436\u0435\u043D\u0438\u044F \u0432 \u0443\u0432\u0435\u0434\u043E\u043C\u043B\u0435\u043D\u0438\u044F\u0445" - }, - game_and_title_change_notification_setting: { - button: "\u0423\u0432\u0435\u0434\u043E\u043C\u0435\u043B\u043D\u0438\u0435 \u043E \u0441\u043C\u0435\u043D\u0435 \u043A\u0430\u0442\u0435\u0433\u043E\u0440\u0438\u0438 \u0438 \u043D\u0430\u0437\u0432\u0430\u043D\u0438\u044F" - } - } - }, - notifications: { - streams: { - nowOffline: "\u{1F534} {{ channelLink }} \u0442\u0435\u043F\u0435\u0440\u044C \u043E\u0444\u0444\u043B\u0430\u0439\u043D.\n{{ categories }}\n{{ duration }}", - nowOnline: "\u{1F7E2} {{ channelLink }} \u0442\u0435\u043F\u0435\u0440\u044C \u043E\u043D\u043B\u0430\u0439\u043D.\n\u041A\u0430\u0442\u0435\u0433\u043E\u0440\u0438\u044F: {{ category }}\n\u041D\u0430\u0437\u0432\u0430\u043D\u0438\u0435: {{ title }}", - newCategory: "\u{1F504} \u041D\u0430 \u043A\u0430\u043D\u0430\u043B\u0435 {{ channelLink }} \u0438\u0437\u043C\u0435\u043D\u0430\u043B\u0430\u0441\u044C \u043A\u0430\u0442\u0435\u0433\u043E\u0440\u0438\u044F \u0441 {{ oldCategory }} \u043D\u0430 {{ category }}", - titleChanged: "\u{1F504} \u041D\u0430 \u043A\u0430\u043D\u0430\u043B\u0435 {{ channelLink }} \u0438\u0437\u043C\u0435\u043D\u0438\u043B\u043E\u0441\u044C \u043D\u0430\u0437\u0432\u0430\u043D\u0438\u0435 \u0441 {{ oldTitle }} \u043D\u0430 {{ title }}", - titleAndCategoryChanged: "\u{1F504} \u041D\u0430 \u043A\u0430\u043D\u0430\u043B\u0435 {{ channelLink }} \u0438\u0437\u043C\u0435\u043D\u0438\u043B\u0438\u0441\u044C \u043D\u0430\u0437\u0432\u0430\u043D\u0438\u0435 \u0441 {{ oldTitle }} \u043D\u0430 {{ title }} \u0438 \u043A\u0430\u0442\u0435\u0433\u043E\u0440\u0438\u044F \u0441 {{ oldCategory }} \u043D\u0430 {{ category }}" - } - } -}; - -// locales/uk.json -var uk_default = { - language: { - name: "\u0423\u043A\u0440\u0430\u0457\u043D\u0441\u044C\u043A\u0430", - changed: "\u041C\u043E\u0432\u0430 \u0437\u043C\u0456\u043D\u0435\u043D\u0430 \u043D\u0430 \u0443\u043A\u0440\u0430\u0457\u043D\u0441\u044C\u043A\u0443.", - emoji: "\u{1F1FA}\u{1F1E6}" - }, - bot: { - description: "\u0417\u0434\u0440\u0430\u0441\u0442\u0432\u0443\u0439\u0442\u0435! \u042F \u0431\u0443\u0434\u0443 \u0441\u043F\u043E\u0432\u0456\u0449\u0430\u0442\u0438 \u0432\u0430\u0441 \u043F\u0440\u043E \u043F\u043E\u0447\u0430\u0442\u043E\u043A Twitch \u0442\u0440\u0430\u043D\u0441\u043B\u044F\u0446\u0456\u0439." - }, - enable: "\u0423\u0432\u0456\u043C\u043A\u043D\u0443\u0442\u0438", - disable: "\u0412\u0438\u043C\u043A\u043D\u0443\u0442\u0438", - enabled: "\u0423\u0432\u0456\u043C\u043A\u043D\u0435\u043D\u043E", - disabled: "\u0412\u0456\u043C\u043A\u043D\u0435\u043D\u043E", - commands: { - follow: { - errors: { - badUsername: '\u0406\u043C\u02BC\u044F \u043A\u043E\u0440\u0438\u0441\u0442\u0443\u0432\u0430\u0447\u0430 \u043C\u043E\u0436\u0435 \u043C\u0430\u0442\u0438 \u0442\u0456\u043B\u044C\u043A\u0438 "a-z", "0-9" \u0442\u0430 "_" \u0441\u0438\u043C\u0432\u043E\u043B\u0438.', - streamerNotFound: "{{ streamer }} - \u043D\u0435 \u0437\u043D\u0430\u0439\u0434\u0435\u043D\u0438\u0439 \u043D\u0430 \u0442\u0432\u0456\u0447\u0456.", - alreadyFollowed: "{{ streamer }} - \u0432\u0438 \u0432\u0436\u0435 \u043F\u0456\u0434\u043F\u0438\u0441\u0430\u043D\u0456." - }, - success: "{{ streamer }} - \u0442\u0435\u043F\u0435\u0440 \u0432\u0456\u0434\u0441\u043B\u0456\u0434\u043A\u043E\u0432\u0443\u0454\u0442\u044C\u0441\u044F.", - enter: "\u0412\u0432\u0435\u0434\u0456\u0442\u044C \u0456\u043C\u02BC\u044F \u0441\u0442\u0440\u0456\u043C\u0435\u0440\u0430, \u0441\u043F\u043E\u0432\u0456\u0449\u0435\u043D\u043D\u044F \u0432\u0456\u0434 \u044F\u043A\u043E\u0433\u043E \u0432\u0438 \u0445\u043E\u0447\u0435\u0442\u0435 \u043E\u0442\u0440\u0438\u043C\u0443\u0432\u0430\u0442\u0438.\n\u0412\u0438 \u043C\u043E\u0436\u0435\u0442\u0435 \u0432\u0438\u043A\u043E\u0440\u0438\u0441\u0442\u043E\u0432\u0443\u0432\u0430\u0442\u0438 \u043F\u043E\u0441\u0438\u043B\u0430\u043D\u043D\u044F.\n\n\u0412\u0432\u0435\u0434\u0456\u0442\u044C /cancel \u0434\u043B\u044F \u0441\u043A\u0430\u0441\u0443\u0432\u0430\u043D\u043D\u044F \u0434\u0456\u0457." - }, - follows: { - total: "\u0412\u0438 \u043F\u0456\u0434\u043F\u0438\u0441\u0430\u043D\u0456 \u043D\u0430 \u0441\u043F\u043E\u0432\u0456\u0449\u0435\u043D\u043D\u044F \u0432\u0456\u0434 {{ count }} \u043A\u0430\u043D\u0430\u043B\u0456\u0432. \u041A\u043B\u0430\u0446\u043D\u0456\u0442\u044C \u043D\u0430 \u043D\u0456\u043A\u043D\u0435\u0439\u043C \u0441\u0442\u0440\u0456\u043C\u0435\u0440\u0430, \u0449\u043E\u0431 \u0432\u0456\u0434\u043F\u0438\u0441\u0430\u0442\u0438\u0441\u044C \u0432\u0456\u0434 \u0441\u043F\u043E\u0432\u0456\u0449\u0435\u043D\u044C." - }, - unfollow: { - callbackButton: "\u0412\u0456\u0434\u043F\u0438\u0441\u0430\u0442\u0438\u0441\u044C \u0432\u0456\u0434 {{ streamer }}", - success: "\u0412\u0438 \u0432\u0456\u0434\u043F\u0438\u0441\u0430\u043B\u0438\u0441\u044C \u0432\u0456\u0434 {{ streamer }}" - }, - start: { - game_change_notification_setting: { - button: "\u0421\u043F\u043E\u0432\u0456\u0449\u0435\u043D\u043D\u044F \u043F\u0440\u043E \u0437\u043C\u0456\u043D\u0443 \u043A\u0430\u0442\u0435\u0433\u043E\u0440\u0456\u0457" - }, - language: { - button: "\u{1F30D} \u041C\u043E\u0432\u0430" - }, - offline_notification: { - button: "\u0421\u043F\u043E\u0432\u0456\u0449\u0435\u043D\u043D\u044F \u043F\u0440\u0438 \u0443\u0445\u043E\u0434\u0456 \u0432 \u043E\u0444\u0444\u043B\u0430\u0439\u043D" - }, - title_change_notification_setting: { - button: "\u0421\u043F\u043E\u0432\u0456\u0449\u0435\u043D\u043D\u044F \u043F\u0440\u043E \u0437\u043C\u0456\u043D\u0443 \u043D\u0430\u0437\u0432\u0438" - }, - image_in_notification_setting: { - button: "\u041F\u043E\u043A\u0430\u0437\u0443\u0432\u0430\u0442\u0438 \u0437\u043E\u0431\u0440\u0430\u0436\u0435\u043D\u043D\u044F \u0432 \u0441\u043F\u043E\u0432\u0456\u0449\u0435\u043D\u043D\u044F\u0445" - }, - game_and_title_change_notification_setting: { - button: "\u0421\u043F\u043E\u0432\u0456\u0449\u0435\u043D\u043D\u044F \u043F\u0440\u043E \u0437\u043C\u0456\u043D\u0443 \u043A\u0430\u0442\u0435\u0433\u043E\u0440\u0456\u0457 \u0442\u0430 \u043D\u0430\u0437\u0432\u0438" - } - } - }, - notifications: { - streams: { - nowOffline: "\u{1F534} {{ channelLink }} \u0442\u0435\u043F\u0435\u0440 \u043E\u0444\u0444\u043B\u0430\u0439\u043D.\n{{ categories }}\n{{ duration }}", - nowOnline: "\u{1F7E2} {{ channelLink }} \u0442\u0435\u043F\u0435\u0440 \u043E\u043D\u043B\u0430\u0439\u043D.\n\u041A\u0430\u0442\u0435\u0433\u043E\u0440\u0456\u044F: {{ category }}\n\u041D\u0430\u0437\u0432\u0430: {{ title }}", - newCategory: "\u{1F504} \u041D\u0430 \u043A\u0430\u043D\u0430\u043B\u0456 {{ channelLink }} \u0431\u0443\u043B\u0430 \u0437\u043C\u0456\u043D\u0435\u043D\u0430 \u043A\u0430\u0442\u0435\u0433\u043E\u0440\u0456\u044F \u0437 {{ oldCategory }} \u043D\u0430 {{ category }}", - titleChanged: "\u{1F504} \u041D\u0430 \u043A\u0430\u043D\u0430\u043B\u0456{{ channelLink }} \u0431\u0443\u043B\u0430 \u0437\u043C\u0456\u043D\u0435\u043D\u0430 \u043D\u0430\u0437\u0432\u0430 \u0437 {{ oldTitle }} \u043D\u0430 {{ title }}", - titleAndCategoryChanged: "\u{1F504} \u041D\u0430 \u043A\u0430\u043D\u0430\u043B\u0456 {{ channelLink }} \u0431\u0443\u043B\u0430 \u0437\u043C\u0456\u043D\u0435\u043D\u0430 \u043D\u0430\u0437\u0432\u0430 \u0437 {{ oldTitle }} \u043D\u0430 {{ title }} \u0442\u0430 \u043A\u0430\u0442\u0435\u0433\u043E\u0440\u0456\u044F \u0437 {{ oldCategory }} \u043D\u0430 {{ category }}" - } - } -}; - -// src/services/i18n.service.ts -var I18nService = class { - static { - __name(this, "I18nService"); - } - i18n; - initialized = false; - constructor() { - this.i18n = instance.createInstance(); - } - /** - * Initialize i18next instance with locales - * Must be called before using the service - */ - async init() { - if (this.initialized) return; - await this.i18n.init({ - lng: "en", - fallbackLng: "en", - defaultNS: "translation", - ns: ["translation"], - resources: { - en: { translation: en_default }, - ru: { translation: ru_default }, - uk: { translation: uk_default } - }, - interpolation: { - escapeValue: false - // Not needed for Telegram (no XSS risk) - } - }); - this.initialized = true; - } - /** - * Get translated string - * @param locale - Language code - * @param key - Translation key (dot notation) - * @param params - Template parameters - */ - t(locale, key, params) { - if (!this.initialized) { - throw new Error("I18nService not initialized. Call init() first."); - } - return this.i18n.t(key, { ...params, lng: locale }); - } - /** - * Get Grammy middleware that attaches t() function to context - */ - middleware() { - return async (ctx, next) => { - const language = ctx.session?.language || "en"; - ctx.t = (key, params) => { - return this.t(language, key, params); - }; - await next(); - }; - } - /** - * Get all available locales - */ - getAvailableLocales() { - return ["en", "ru", "uk"]; - } - /** - * Check if locale is supported - */ - isValidLocale(locale) { - return ["en", "ru", "uk"].includes(locale); - } -}; - -// src/services/twitch.service.ts -init_modules_watch_stub(); -init_performance2(); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/index.js -init_modules_watch_stub(); -init_performance2(); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/client/ApiClient.js -init_modules_watch_stub(); -init_performance2(); - -// node_modules/.pnpm/tslib@2.8.1/node_modules/tslib/tslib.es6.mjs -init_modules_watch_stub(); -init_performance2(); -var extendStatics = /* @__PURE__ */ __name(function(d2, b) { - extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d3, b2) { - d3.__proto__ = b2; - } || function(d3, b2) { - for (var p in b2) if (Object.prototype.hasOwnProperty.call(b2, p)) d3[p] = b2[p]; - }; - return extendStatics(d2, b); -}, "extendStatics"); -function __extends(d2, b) { - if (typeof b !== "function" && b !== null) - throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); - extendStatics(d2, b); - function __() { - this.constructor = d2; - } - __name(__, "__"); - d2.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); -} -__name(__extends, "__extends"); -function __decorate(decorators, target, key, desc2) { - var c = arguments.length, r = c < 3 ? target : desc2 === null ? desc2 = Object.getOwnPropertyDescriptor(target, key) : desc2, d2; - if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc2); - else for (var i = decorators.length - 1; i >= 0; i--) if (d2 = decorators[i]) r = (c < 3 ? d2(r) : c > 3 ? d2(target, key, r) : d2(target, key)) || r; - return c > 3 && r && Object.defineProperty(target, key, r), r; -} -__name(__decorate, "__decorate"); -function __read(o, n) { - var m2 = typeof Symbol === "function" && o[Symbol.iterator]; - if (!m2) return o; - var i = m2.call(o), r, ar = [], e; - try { - while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); - } catch (error) { - e = { error }; - } finally { - try { - if (r && !r.done && (m2 = i["return"])) m2.call(i); - } finally { - if (e) throw e.error; - } - } - return ar; -} -__name(__read, "__read"); -function __spreadArray(to, from, pack) { - if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { - if (ar || !(i in from)) { - if (!ar) ar = Array.prototype.slice.call(from, 0, i); - ar[i] = from[i]; - } - } - return to.concat(ar || Array.prototype.slice.call(from)); -} -__name(__spreadArray, "__spreadArray"); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/client/ApiClient.js -var import_detect_node4 = __toESM(require_browser(), 1); - -// node_modules/.pnpm/@d-fischer+logger@4.2.4/node_modules/@d-fischer/logger/es/index.mjs -init_modules_watch_stub(); -init_performance2(); - -// node_modules/.pnpm/@d-fischer+logger@4.2.4/node_modules/@d-fischer/logger/es/createLogger.mjs -init_modules_watch_stub(); -init_performance2(); -var import_detect_node3 = __toESM(require_browser(), 1); - -// node_modules/.pnpm/@d-fischer+logger@4.2.4/node_modules/@d-fischer/logger/es/BrowserLogger.mjs -init_modules_watch_stub(); -init_performance2(); - -// node_modules/.pnpm/@d-fischer+logger@4.2.4/node_modules/@d-fischer/logger/es/LogLevel.mjs -init_modules_watch_stub(); -init_performance2(); -var import_detect_node = __toESM(require_browser(), 1); -var _a; -var LogLevel; -(function(LogLevel2) { - LogLevel2[LogLevel2["CRITICAL"] = 0] = "CRITICAL"; - LogLevel2[LogLevel2["ERROR"] = 1] = "ERROR"; - LogLevel2[LogLevel2["WARNING"] = 2] = "WARNING"; - LogLevel2[LogLevel2["INFO"] = 3] = "INFO"; - LogLevel2[LogLevel2["DEBUG"] = 4] = "DEBUG"; - LogLevel2[LogLevel2["TRACE"] = 7] = "TRACE"; -})(LogLevel || (LogLevel = {})); -function resolveLogLevel(level) { - if (typeof level === "number") { - if (Object.prototype.hasOwnProperty.call(LogLevel, level)) { - return level; - } - var eligibleLevels = Object.keys(LogLevel).map(function(k) { - return parseInt(k, 10); - }).filter(function(k) { - return !isNaN(k) && k < level; - }); - if (!eligibleLevels.length) { - return LogLevel.WARNING; - } - return Math.max.apply(Math, eligibleLevels); - } - var strLevel = level.replace(/\d+$/, "").toUpperCase(); - if (!Object.prototype.hasOwnProperty.call(LogLevel, strLevel)) { - throw new Error("Unknown log level string: ".concat(level)); - } - return LogLevel[strLevel]; -} -__name(resolveLogLevel, "resolveLogLevel"); -var debugFunction = import_detect_node.isNode ? console.log.bind(console) : console.debug.bind(console); -var LogLevelToConsoleFunction = (_a = {}, _a[LogLevel.CRITICAL] = console.error.bind(console), _a[LogLevel.ERROR] = console.error.bind(console), _a[LogLevel.WARNING] = console.warn.bind(console), _a[LogLevel.INFO] = console.info.bind(console), _a[LogLevel.DEBUG] = debugFunction.bind(console), _a[LogLevel.TRACE] = console.trace.bind(console), _a); - -// node_modules/.pnpm/@d-fischer+logger@4.2.4/node_modules/@d-fischer/logger/es/BaseLogger.mjs -init_modules_watch_stub(); -init_performance2(); - -// node_modules/.pnpm/@d-fischer+shared-utils@3.6.4/node_modules/@d-fischer/shared-utils/es/index.mjs -init_modules_watch_stub(); -init_performance2(); - -// node_modules/.pnpm/@d-fischer+shared-utils@3.6.4/node_modules/@d-fischer/shared-utils/es/decorators/Enumerable.mjs -init_modules_watch_stub(); -init_performance2(); -function Enumerable(enumerable) { - if (enumerable === void 0) { - enumerable = true; - } - return function(target, key) { - Object.defineProperty(target, key, { - get: /* @__PURE__ */ __name(function() { - return; - }, "get"), - // eslint-disable-next-line @typescript-eslint/no-explicit-any - set: /* @__PURE__ */ __name(function(val) { - Object.defineProperty(this, key, { - value: val, - writable: true, - enumerable - }); - }, "set"), - enumerable - }); - }; -} -__name(Enumerable, "Enumerable"); - -// node_modules/.pnpm/@d-fischer+shared-utils@3.6.4/node_modules/@d-fischer/shared-utils/es/functions/array/flatten.mjs -init_modules_watch_stub(); -init_performance2(); -function flatten2(arr) { - var _a4; - return (_a4 = []).concat.apply(_a4, __spreadArray([], __read(arr), false)); -} -__name(flatten2, "flatten"); - -// node_modules/.pnpm/@d-fischer+shared-utils@3.6.4/node_modules/@d-fischer/shared-utils/es/functions/object/arrayToObject.mjs -init_modules_watch_stub(); -init_performance2(); -function arrayToObject(arr, fn) { - return Object.assign.apply(Object, __spreadArray([{}], __read(arr.map(fn)), false)); -} -__name(arrayToObject, "arrayToObject"); - -// node_modules/.pnpm/@d-fischer+shared-utils@3.6.4/node_modules/@d-fischer/shared-utils/es/functions/object/indexBy.mjs -init_modules_watch_stub(); -init_performance2(); -function indexBy(arr, keyFn) { - if (typeof keyFn !== "function") { - var key_1 = keyFn; - keyFn = /* @__PURE__ */ __name((function(value) { - return value[key_1].toString(); - }), "keyFn"); - } - return arrayToObject(arr, function(val) { - var _a4; - return _a4 = {}, _a4[keyFn(val)] = val, _a4; - }); -} -__name(indexBy, "indexBy"); - -// node_modules/.pnpm/@d-fischer+shared-utils@3.6.4/node_modules/@d-fischer/shared-utils/es/functions/optional/mapOptional.mjs -init_modules_watch_stub(); -init_performance2(); -function isNullish(value) { - return value == null; -} -__name(isNullish, "isNullish"); -function mapNullable(value, cb) { - return isNullish(value) ? null : cb(value); -} -__name(mapNullable, "mapNullable"); -function mapOptional(value, cb) { - return isNullish(value) ? void 0 : cb(value); -} -__name(mapOptional, "mapOptional"); - -// node_modules/.pnpm/@d-fischer+shared-utils@3.6.4/node_modules/@d-fischer/shared-utils/es/functions/promise/withResolvers.mjs -init_modules_watch_stub(); -init_performance2(); -function promiseWithResolvers() { - var resolve; - var reject; - var promise = new Promise(function(_resolve, _reject) { - resolve = _resolve; - reject = _reject; - }); - return { promise, resolve, reject }; -} -__name(promiseWithResolvers, "promiseWithResolvers"); - -// node_modules/.pnpm/@d-fischer+logger@4.2.4/node_modules/@d-fischer/logger/es/BaseLogger.mjs -var import_detect_node2 = __toESM(require_browser(), 1); - -// node_modules/.pnpm/@d-fischer+logger@4.2.4/node_modules/@d-fischer/logger/es/getMinLogLevelFromEnv.mjs -init_modules_watch_stub(); -init_performance2(); -var _a2; -var _b; -var data = typeof process === "undefined" ? [] : (_b = (_a2 = process.env.LOGGING) === null || _a2 === void 0 ? void 0 : _a2.split(";").map(function(part) { - var _a4 = part.split("=", 2), namespace = _a4[0], strLevel = _a4[1]; - if (strLevel) { - return [namespace === "default" ? void 0 : namespace.split(":"), resolveLogLevel(strLevel)]; - } - return null; -}).filter(function(v) { - return !!v; -}).sort(function(_a4, _b3) { - var _c2, _d; - var a = _a4[0]; - var b = _b3[0]; - return ((_c2 = b === null || b === void 0 ? void 0 : b.length) !== null && _c2 !== void 0 ? _c2 : 0) - ((_d = a === null || a === void 0 ? void 0 : a.length) !== null && _d !== void 0 ? _d : 0); -})) !== null && _b !== void 0 ? _b : []; -var defaultIndex = data.findIndex(function(_a4) { - var nsParts = _a4[0]; - return !nsParts; -}); -var defaultLevel = void 0; -if (defaultIndex !== -1) { - defaultLevel = data[defaultIndex][1]; - data.splice(defaultIndex); -} -function isPrefix(value, prefix) { - return prefix.length <= value.length && prefix.every(function(item, i) { - return item === value[i]; - }); -} -__name(isPrefix, "isPrefix"); -function getMinLogLevelFromEnv(name) { - var nameSplit = name.split(":"); - for (var _i = 0, data_1 = data; _i < data_1.length; _i++) { - var _a4 = data_1[_i], nsParts = _a4[0], level = _a4[1]; - if (isPrefix(nameSplit, nsParts)) { - return level; - } - } - return defaultLevel; -} -__name(getMinLogLevelFromEnv, "getMinLogLevelFromEnv"); - -// node_modules/.pnpm/@d-fischer+logger@4.2.4/node_modules/@d-fischer/logger/es/BaseLogger.mjs -var BaseLogger = ( - /** @class */ - (function() { - function BaseLogger2(_a4) { - var name = _a4.name, minLevel = _a4.minLevel, _b3 = _a4.emoji, emoji = _b3 === void 0 ? false : _b3, colors2 = _a4.colors, _c2 = _a4.timestamps, timestamps = _c2 === void 0 ? import_detect_node2.isNode : _c2; - var _d, _e; - this._name = name; - this._minLevel = (_e = (_d = mapOptional(minLevel, function(lv) { - return resolveLogLevel(lv); - })) !== null && _d !== void 0 ? _d : getMinLogLevelFromEnv(name)) !== null && _e !== void 0 ? _e : LogLevel.WARNING; - this._emoji = emoji; - this._colors = colors2; - this._timestamps = timestamps; - } - __name(BaseLogger2, "BaseLogger"); - BaseLogger2.prototype.crit = function(message) { - this.log(LogLevel.CRITICAL, message); - }; - BaseLogger2.prototype.error = function(message) { - this.log(LogLevel.ERROR, message); - }; - BaseLogger2.prototype.warn = function(message) { - this.log(LogLevel.WARNING, message); - }; - BaseLogger2.prototype.info = function(message) { - this.log(LogLevel.INFO, message); - }; - BaseLogger2.prototype.debug = function(message) { - this.log(LogLevel.DEBUG, message); - }; - BaseLogger2.prototype.trace = function(message) { - this.log(LogLevel.TRACE, message); - }; - return BaseLogger2; - })() -); - -// node_modules/.pnpm/@d-fischer+logger@4.2.4/node_modules/@d-fischer/logger/es/BrowserLogger.mjs -var BrowserLogger = ( - /** @class */ - (function(_super) { - __extends(BrowserLogger2, _super); - function BrowserLogger2() { - return _super !== null && _super.apply(this, arguments) || this; - } - __name(BrowserLogger2, "BrowserLogger"); - BrowserLogger2.prototype.log = function(level, message) { - if (level > this._minLevel) { - return; - } - var logFn = LogLevelToConsoleFunction[level]; - var formattedMessage = "[".concat(this._name, "] ").concat(message); - if (this._timestamps) { - formattedMessage = "[".concat((/* @__PURE__ */ new Date()).toISOString(), "] ").concat(message); - } - logFn(formattedMessage); - }; - return BrowserLogger2; - })(BaseLogger) -); - -// node_modules/.pnpm/@d-fischer+logger@4.2.4/node_modules/@d-fischer/logger/es/CustomLoggerWrapper.mjs -init_modules_watch_stub(); -init_performance2(); -var CustomLoggerWrapper = ( - /** @class */ - (function() { - function CustomLoggerWrapper2(_a4) { - var name = _a4.name, minLevel = _a4.minLevel, custom = _a4.custom; - var _b3; - this._minLevel = (_b3 = mapOptional(minLevel, function(lv) { - return resolveLogLevel(lv); - })) !== null && _b3 !== void 0 ? _b3 : getMinLogLevelFromEnv(name); - this._override = typeof custom === "function" ? { log: custom } : custom; - } - __name(CustomLoggerWrapper2, "CustomLoggerWrapper"); - CustomLoggerWrapper2.prototype.log = function(level, message) { - if (this._shouldLog(level)) { - this._override.log(level, message); - } - }; - CustomLoggerWrapper2.prototype.crit = function(message) { - if (!this._override.crit) { - this.log(LogLevel.CRITICAL, message); - } else if (this._shouldLog(LogLevel.CRITICAL)) { - this._override.crit(message); - } - }; - CustomLoggerWrapper2.prototype.error = function(message) { - if (!this._override.error) { - this.log(LogLevel.ERROR, message); - } else if (this._shouldLog(LogLevel.ERROR)) { - this._override.error(message); - } - }; - CustomLoggerWrapper2.prototype.warn = function(message) { - if (!this._override.warn) { - this.log(LogLevel.WARNING, message); - } else if (this._shouldLog(LogLevel.WARNING)) { - this._override.warn(message); - } - }; - CustomLoggerWrapper2.prototype.info = function(message) { - if (!this._override.info) { - this.log(LogLevel.INFO, message); - } else if (this._shouldLog(LogLevel.INFO)) { - this._override.info(message); - } - }; - CustomLoggerWrapper2.prototype.debug = function(message) { - if (!this._override.debug) { - this.log(LogLevel.DEBUG, message); - } else if (this._shouldLog(LogLevel.DEBUG)) { - this._override.debug(message); - } - }; - CustomLoggerWrapper2.prototype.trace = function(message) { - if (!this._override.trace) { - this.log(LogLevel.TRACE, message); - } else if (this._shouldLog(LogLevel.TRACE)) { - this._override.trace(message); - } - }; - CustomLoggerWrapper2.prototype._shouldLog = function(level) { - return this._minLevel === void 0 || this._minLevel >= level; - }; - return CustomLoggerWrapper2; - })() -); - -// node_modules/.pnpm/@d-fischer+logger@4.2.4/node_modules/@d-fischer/logger/es/NodeLogger.mjs -init_modules_watch_stub(); -init_performance2(); -var _a3; -var _b2; -var _c; -var LogLevelToEmoji = (_a3 = {}, _a3[LogLevel.CRITICAL] = "\u{1F6D1}", _a3[LogLevel.ERROR] = "\u274C", // these following two need extra spaces at the end because somehow they consume less space in a terminal than they should... -_a3[LogLevel.WARNING] = "\u26A0\uFE0F ", _a3[LogLevel.INFO] = "\u2139\uFE0F ", _a3[LogLevel.DEBUG] = "\u{1F41E}", _a3[LogLevel.TRACE] = "\u{1F43E}", _a3); -var colors = { - black: 30, - red: 31, - green: 32, - yellow: 33, - blue: 34, - magenta: 35, - cyan: 36, - white: 37, - blackBright: 90, - redBright: 91, - greenBright: 92, - yellowBright: 93, - blueBright: 94, - magentaBright: 95, - cyanBright: 96, - whiteBright: 97 -}; -var bgColors = { - bgBlack: 40, - bgRed: 41, - bgGreen: 42, - bgYellow: 43, - bgBlue: 44, - bgMagenta: 45, - bgCyan: 46, - bgWhite: 47, - bgBlackBright: 100, - bgRedBright: 101, - bgGreenBright: 102, - bgYellowBright: 103, - bgBlueBright: 104, - bgMagentaBright: 105, - bgCyanBright: 106, - bgWhiteBright: 107 -}; -function createGenericWrapper(color, ending, inner) { - return function(str2) { - return "\x1B[".concat(color, "m").concat(inner ? inner(str2) : str2, "\x1B[").concat(ending, "m"); - }; -} -__name(createGenericWrapper, "createGenericWrapper"); -function createColorWrapper(color) { - return createGenericWrapper(colors[color], 39); -} -__name(createColorWrapper, "createColorWrapper"); -function createBgWrapper(color, fgWrapper) { - return createGenericWrapper(bgColors[color], 49, fgWrapper); -} -__name(createBgWrapper, "createBgWrapper"); -var LogLevelToColor = (_b2 = {}, _b2[LogLevel.CRITICAL] = createColorWrapper("red"), _b2[LogLevel.ERROR] = createColorWrapper("redBright"), _b2[LogLevel.WARNING] = createColorWrapper("yellow"), _b2[LogLevel.INFO] = createColorWrapper("blue"), _b2[LogLevel.DEBUG] = createColorWrapper("magenta"), _b2[LogLevel.TRACE] = createGenericWrapper(0, 0), _b2); -var LogLevelToBackgroundColor = (_c = {}, _c[LogLevel.CRITICAL] = createBgWrapper("bgRed", createColorWrapper("white")), _c[LogLevel.ERROR] = createBgWrapper("bgRedBright", createColorWrapper("white")), _c[LogLevel.WARNING] = createBgWrapper("bgYellow", createColorWrapper("black")), _c[LogLevel.INFO] = createBgWrapper("bgBlue", createColorWrapper("white")), _c[LogLevel.DEBUG] = createBgWrapper("bgMagenta", createColorWrapper("black")), _c[LogLevel.TRACE] = createGenericWrapper(7, 27), _c); -var NodeLogger = ( - /** @class */ - (function(_super) { - __extends(NodeLogger2, _super); - function NodeLogger2() { - return _super !== null && _super.apply(this, arguments) || this; - } - __name(NodeLogger2, "NodeLogger"); - NodeLogger2.prototype.log = function(level, message) { - var _a4, _b3, _c2; - if (level > this._minLevel) { - return; - } - var logFn = LogLevelToConsoleFunction[level]; - var builtMessage = ""; - if (this._timestamps) { - builtMessage += "[".concat((/* @__PURE__ */ new Date()).toISOString(), "] "); - } - if (this._emoji) { - var emoji = LogLevelToEmoji[level]; - builtMessage += "".concat(emoji, " "); - } - var useColors = (_c2 = (_a4 = this._colors) !== null && _a4 !== void 0 ? _a4 : (_b3 = process.stdout) === null || _b3 === void 0 ? void 0 : _b3.isTTY) !== null && _c2 !== void 0 ? _c2 : true; - if (useColors) { - builtMessage += "".concat(LogLevelToBackgroundColor[level](this._name), " ").concat(LogLevelToBackgroundColor[level](LogLevel[level]), " ").concat(LogLevelToColor[level](message)); - } else { - builtMessage += "[".concat(this._name, ":").concat(LogLevel[level].toLowerCase(), "] ").concat(message); - } - logFn(builtMessage); - }; - return NodeLogger2; - })(BaseLogger) -); - -// node_modules/.pnpm/@d-fischer+logger@4.2.4/node_modules/@d-fischer/logger/es/createLogger.mjs -function createLogger(options) { - if (options.custom) { - return new CustomLoggerWrapper(options); - } - if (import_detect_node3.isNode) { - return new NodeLogger(options); - } - return new BrowserLogger(options); -} -__name(createLogger, "createLogger"); - -// node_modules/.pnpm/@d-fischer+rate-limiter@1.1.0/node_modules/@d-fischer/rate-limiter/es/index.mjs -init_modules_watch_stub(); -init_performance2(); - -// node_modules/.pnpm/@d-fischer+rate-limiter@1.1.0/node_modules/@d-fischer/rate-limiter/es/errors/RateLimiterDestroyedError.mjs -init_modules_watch_stub(); -init_performance2(); - -// node_modules/.pnpm/@d-fischer+rate-limiter@1.1.0/node_modules/@d-fischer/rate-limiter/es/errors/CustomError.mjs -init_modules_watch_stub(); -init_performance2(); -var CustomError = class extends Error { - static { - __name(this, "CustomError"); - } - constructor(...params) { - var _a4; - super(...params); - Object.setPrototypeOf(this, new.target.prototype); - (_a4 = Error.captureStackTrace) === null || _a4 === void 0 ? void 0 : _a4.call(Error, this, new.target.constructor); - } - get name() { - return this.constructor.name; - } -}; - -// node_modules/.pnpm/@d-fischer+rate-limiter@1.1.0/node_modules/@d-fischer/rate-limiter/es/errors/RateLimiterDestroyedError.mjs -var RateLimiterDestroyedError = class extends CustomError { - static { - __name(this, "RateLimiterDestroyedError"); - } -}; - -// node_modules/.pnpm/@d-fischer+rate-limiter@1.1.0/node_modules/@d-fischer/rate-limiter/es/errors/RateLimitReachedError.mjs -init_modules_watch_stub(); -init_performance2(); -var RateLimitReachedError = class extends CustomError { - static { - __name(this, "RateLimitReachedError"); - } -}; - -// node_modules/.pnpm/@d-fischer+rate-limiter@1.1.0/node_modules/@d-fischer/rate-limiter/es/errors/RetryAfterError.mjs -init_modules_watch_stub(); -init_performance2(); -var RetryAfterError = class extends CustomError { - static { - __name(this, "RetryAfterError"); - } - constructor(after) { - super(`Need to retry after ${after} ms`); - this._retryAt = Date.now() + after; - } - get retryAt() { - return this._retryAt; - } -}; - -// node_modules/.pnpm/@d-fischer+rate-limiter@1.1.0/node_modules/@d-fischer/rate-limiter/es/limiters/PartitionedRateLimiter.mjs -init_modules_watch_stub(); -init_performance2(); - -// node_modules/.pnpm/@d-fischer+rate-limiter@1.1.0/node_modules/@d-fischer/rate-limiter/es/limiters/ResponseBasedRateLimiter.mjs -init_modules_watch_stub(); -init_performance2(); -var ResponseBasedRateLimiter = class { - static { - __name(this, "ResponseBasedRateLimiter"); - } - constructor({ logger }) { - this._queue = []; - this._batchRunning = false; - this._paused = false; - this._logger = createLogger({ name: "rate-limiter", emoji: true, ...logger }); - } - async request(req, options) { - this._logger.trace("request start"); - return await new Promise((resolve, reject) => { - var _a4; - const reqSpec = { - req, - resolve, - reject, - limitReachedBehavior: (_a4 = options === null || options === void 0 ? void 0 : options.limitReachedBehavior) !== null && _a4 !== void 0 ? _a4 : "enqueue" - }; - if (this._batchRunning || !!this._nextBatchTimer || this._paused) { - this._logger.trace(`request queued batchRunning:${this._batchRunning.toString()} hasNextBatchTimer:${(!!this._nextBatchTimer).toString()} paused:${this._paused.toString()}`); - this._queue.push(reqSpec); - } else { - void this._runRequestBatch([reqSpec]); - } - }); - } - clear() { - this._queue = []; - } - pause() { - this._paused = true; - } - resume() { - this._paused = false; - this._runNextBatch(); - } - get stats() { - var _a4, _b3, _c2, _d, _e; - return { - lastKnownLimit: (_b3 = (_a4 = this._parameters) === null || _a4 === void 0 ? void 0 : _a4.limit) !== null && _b3 !== void 0 ? _b3 : null, - lastKnownRemainingRequests: (_d = (_c2 = this._parameters) === null || _c2 === void 0 ? void 0 : _c2.remaining) !== null && _d !== void 0 ? _d : null, - lastKnownResetDate: mapNullable((_e = this._parameters) === null || _e === void 0 ? void 0 : _e.resetsAt, (v) => new Date(v)) - }; - } - async _runRequestBatch(reqSpecs) { - this._logger.trace(`runRequestBatch start specs:${reqSpecs.length}`); - this._batchRunning = true; - if (this._parameters) { - this._logger.debug(`Remaining requests: ${this._parameters.remaining}`); - } - this._logger.debug(`Doing ${reqSpecs.length} requests, new queue length is ${this._queue.length}`); - const promises = reqSpecs.map(async (reqSpec) => { - const { req, resolve, reject } = reqSpec; - try { - const result = await this.doRequest(req); - const retry2 = this.needsToRetryAfter(result); - if (retry2 !== null) { - this._queue.unshift(reqSpec); - this._logger.info(`Retrying after ${retry2} ms`); - throw new RetryAfterError(retry2); - } - const params = this.getParametersFromResponse(result); - resolve(result); - return params; - } catch (e) { - if (e instanceof RetryAfterError) { - throw e; - } - reject(e); - return void 0; - } - }); - const settledPromises = await Promise.allSettled(promises); - const rejectedPromises = settledPromises.filter((p) => p.status === "rejected"); - const now = Date.now(); - if (rejectedPromises.length) { - this._logger.trace("runRequestBatch some rejected"); - const retryAt = Math.max(now, ...rejectedPromises.map((p) => p.reason.retryAt)); - const retryAfter = retryAt - now; - this._logger.warn(`Waiting for ${retryAfter} ms because the rate limit was exceeded`); - this._nextBatchTimer = setTimeout(() => { - this._parameters = void 0; - this._runNextBatch(); - }, retryAfter); - } else { - this._logger.trace("runRequestBatch none rejected"); - const params = settledPromises.filter((p) => p.status === "fulfilled" && p.value !== void 0).map((p) => p.value).reduce((carry, v) => { - if (!carry) { - return v; - } - return v.remaining < carry.remaining ? v : carry; - }, void 0); - this._batchRunning = false; - if (params) { - this._parameters = params; - if (params.resetsAt < now || params.remaining > 0) { - this._logger.trace("runRequestBatch canRunMore"); - this._runNextBatch(); - } else { - const delay = params.resetsAt - now; - this._logger.trace(`runRequestBatch delay:${delay}`); - this._logger.warn(`Waiting for ${delay} ms because the rate limit was reached`); - this._queue = this._queue.filter((entry) => { - switch (entry.limitReachedBehavior) { - case "enqueue": { - return true; - } - case "null": { - entry.resolve(null); - return false; - } - case "throw": { - entry.reject(new RateLimitReachedError("Request removed from queue because the rate limit was reached")); - return false; - } - default: { - throw new Error("this should never happen"); - } - } - }); - this._nextBatchTimer = setTimeout(() => { - this._parameters = void 0; - this._runNextBatch(); - }, delay); - } - } - } - this._logger.trace("runRequestBatch end"); - } - _runNextBatch() { - if (this._paused) { - return; - } - this._logger.trace("runNextBatch start"); - if (this._nextBatchTimer) { - clearTimeout(this._nextBatchTimer); - this._nextBatchTimer = void 0; - } - const amount = this._parameters ? Math.min(this._parameters.remaining, this._parameters.limit / 10) : 1; - const reqSpecs = this._queue.splice(0, amount); - if (reqSpecs.length) { - void this._runRequestBatch(reqSpecs); - } - this._logger.trace("runNextBatch end"); - } -}; - -// node_modules/.pnpm/@d-fischer+rate-limiter@1.1.0/node_modules/@d-fischer/rate-limiter/es/limiters/PartitionedRateLimiter.mjs -var PartitionedRateLimiter = class { - static { - __name(this, "PartitionedRateLimiter"); - } - constructor(options) { - this._children = /* @__PURE__ */ new Map(); - this._paused = false; - this._partitionKeyCallback = options.getPartitionKey; - this._createChildCallback = options.createChild; - } - async request(req, options) { - const partitionKey = this._partitionKeyCallback(req); - const partitionChild = this._getChild(partitionKey); - return await partitionChild.request(req, options); - } - clear() { - for (const child of this._children.values()) { - child.clear(); - } - } - pause() { - this._paused = true; - for (const child of this._children.values()) { - child.pause(); - } - } - resume() { - this._paused = false; - for (const child of this._children.values()) { - child.resume(); - } - } - getChildStats(partitionKey) { - if (!this._children.has(partitionKey)) { - return null; - } - const child = this._children.get(partitionKey); - if (!(child instanceof ResponseBasedRateLimiter)) { - return null; - } - return child.stats; - } - _getChild(partitionKey) { - if (this._children.has(partitionKey)) { - return this._children.get(partitionKey); - } - const result = this._createChildCallback(partitionKey); - if (this._paused) { - result.pause(); - } - this._children.set(partitionKey, result); - return result; - } -}; - -// node_modules/.pnpm/@d-fischer+rate-limiter@1.1.0/node_modules/@d-fischer/rate-limiter/es/limiters/PartitionedTimeBasedRateLimiter.mjs -init_modules_watch_stub(); -init_performance2(); -var PartitionedTimeBasedRateLimiter = class { - static { - __name(this, "PartitionedTimeBasedRateLimiter"); - } - constructor({ logger, bucketSize, timeFrame, doRequest, getPartitionKey }) { - this._partitionedQueue = /* @__PURE__ */ new Map(); - this._usedFromBucket = /* @__PURE__ */ new Map(); - this._counterTimers = /* @__PURE__ */ new Set(); - this._paused = false; - this._destroyed = false; - this._logger = createLogger({ name: "rate-limiter", emoji: true, ...logger }); - this._bucketSize = bucketSize; - this._timeFrame = timeFrame; - this._callback = doRequest; - this._partitionKeyCallback = getPartitionKey; - } - async request(req, options) { - return await new Promise((resolve, reject) => { - var _a4, _b3; - if (this._destroyed) { - reject(new RateLimiterDestroyedError("Rate limiter was destroyed")); - return; - } - const reqSpec = { - req, - resolve, - reject, - limitReachedBehavior: (_a4 = options === null || options === void 0 ? void 0 : options.limitReachedBehavior) !== null && _a4 !== void 0 ? _a4 : "enqueue" - }; - const partitionKey = this._partitionKeyCallback(req); - const usedFromBucket = (_b3 = this._usedFromBucket.get(partitionKey)) !== null && _b3 !== void 0 ? _b3 : 0; - if (usedFromBucket >= this._bucketSize || this._paused) { - switch (reqSpec.limitReachedBehavior) { - case "enqueue": { - const queue2 = this._getPartitionedQueue(partitionKey); - queue2.push(reqSpec); - if (usedFromBucket + queue2.length >= this._bucketSize) { - this._logger.warn(`Rate limit of ${this._bucketSize} for ${partitionKey ? `partition ${partitionKey}` : "default partition"} was reached, waiting for ${this._paused ? "the limiter to be unpaused" : "a free bucket entry"}; queue size is ${queue2.length}`); - } else { - this._logger.info(`Enqueueing request for ${partitionKey ? `partition ${partitionKey}` : "default partition"} because the rate limiter is paused; queue size is ${queue2.length}`); - } - break; - } - case "null": { - reqSpec.resolve(null); - if (this._paused) { - this._logger.info(`Returning null for request for ${partitionKey ? `partition ${partitionKey}` : "default partition"} because the rate limiter is paused`); - } else { - this._logger.warn(`Rate limit of ${this._bucketSize} for ${partitionKey ? `partition ${partitionKey}` : "default partition"} was reached, dropping request and returning null`); - } - break; - } - case "throw": { - reqSpec.reject(new RateLimitReachedError(`Request dropped because ${this._paused ? "the rate limiter is paused" : `the rate limit for ${partitionKey ? `partition ${partitionKey}` : "default partition"} was reached`}`)); - break; - } - default: { - throw new Error("this should never happen"); - } - } - } else { - void this._runRequest(reqSpec, partitionKey); - } - }); - } - clear() { - this._partitionedQueue.clear(); - } - pause() { - this._paused = true; - } - resume() { - this._paused = false; - for (const partitionKey of this._partitionedQueue.keys()) { - this._runNextRequest(partitionKey); - } - } - destroy() { - this._paused = false; - this._destroyed = true; - this._counterTimers.forEach((timer) => { - clearTimeout(timer); - }); - for (const queue2 of this._partitionedQueue.values()) { - for (const req of queue2) { - req.reject(new RateLimiterDestroyedError("Rate limiter was destroyed")); - } - } - this._partitionedQueue.clear(); - } - _getPartitionedQueue(partitionKey) { - if (this._partitionedQueue.has(partitionKey)) { - return this._partitionedQueue.get(partitionKey); - } - const newQueue = []; - this._partitionedQueue.set(partitionKey, newQueue); - return newQueue; - } - async _runRequest(reqSpec, partitionKey) { - var _a4; - const queue2 = this._getPartitionedQueue(partitionKey); - this._logger.debug(`doing a request for ${partitionKey ? `partition ${partitionKey}` : "default partition"}, new queue length is ${queue2.length}`); - this._usedFromBucket.set(partitionKey, ((_a4 = this._usedFromBucket.get(partitionKey)) !== null && _a4 !== void 0 ? _a4 : 0) + 1); - const { req, resolve, reject } = reqSpec; - try { - resolve(await this._callback(req)); - } catch (e) { - reject(e); - } finally { - const counterTimer = setTimeout(() => { - this._counterTimers.delete(counterTimer); - const newUsed = this._usedFromBucket.get(partitionKey) - 1; - this._usedFromBucket.set(partitionKey, newUsed); - if (queue2.length && newUsed < this._bucketSize) { - this._runNextRequest(partitionKey); - } - }, this._timeFrame); - this._counterTimers.add(counterTimer); - } - } - _runNextRequest(partitionKey) { - if (this._paused) { - return; - } - const queue2 = this._getPartitionedQueue(partitionKey); - const reqSpec = queue2.shift(); - if (reqSpec) { - void this._runRequest(reqSpec, partitionKey); - } - } -}; - -// node_modules/.pnpm/@twurple+api-call@8.0.3/node_modules/@twurple/api-call/lib/index.js -init_modules_watch_stub(); -init_performance2(); - -// node_modules/.pnpm/@twurple+api-call@8.0.3/node_modules/@twurple/api-call/lib/apiCall.js -init_modules_watch_stub(); -init_performance2(); - -// node_modules/.pnpm/@twurple+common@8.0.3/node_modules/@twurple/common/lib/index.js -init_modules_watch_stub(); -init_performance2(); - -// node_modules/.pnpm/@twurple+common@8.0.3/node_modules/@twurple/common/lib/DataObject.js -init_modules_watch_stub(); -init_performance2(); - -// node_modules/.pnpm/klona@2.0.6/node_modules/klona/dist/index.mjs -init_modules_watch_stub(); -init_performance2(); - -// node_modules/.pnpm/@twurple+common@8.0.3/node_modules/@twurple/common/lib/DataObject.js -var rawDataSymbol = /* @__PURE__ */ Symbol("twurpleRawData"); -var DataObject = class { - static { - __name(this, "DataObject"); - } - /** @private */ - [rawDataSymbol]; - /** @private */ - constructor(data2) { - this[rawDataSymbol] = data2; - } -}; - -// node_modules/.pnpm/@twurple+common@8.0.3/node_modules/@twurple/common/lib/mockApiPort.js -init_modules_watch_stub(); -init_performance2(); -function getMockApiPort() { - try { - return process.env.TWURPLE_MOCK_API_PORT ?? null; - } catch { - try { - return import.meta.env.TWURPLE_MOCK_API_PORT ?? null; - } catch { - return null; - } - } -} -__name(getMockApiPort, "getMockApiPort"); - -// node_modules/.pnpm/@twurple+common@8.0.3/node_modules/@twurple/common/lib/qs.js -init_modules_watch_stub(); -init_performance2(); -function qsStringify(obj) { - if (!obj) { - return ""; - } - const params = new URLSearchParams(); - for (const [key, value] of Object.entries(obj)) { - if (value === null) { - params.append(key, ""); - } else if (Array.isArray(value)) { - for (const v of value) { - params.append(key, v.toString()); - } - } else if (value !== void 0) { - params.append(key, value.toString()); - } - } - const result = params.toString(); - return result ? `?${result}` : ""; -} -__name(qsStringify, "qsStringify"); - -// node_modules/.pnpm/@twurple+common@8.0.3/node_modules/@twurple/common/lib/relations.js -init_modules_watch_stub(); -init_performance2(); - -// node_modules/.pnpm/@twurple+common@8.0.3/node_modules/@twurple/common/lib/errors/RelationAssertionError.js -init_modules_watch_stub(); -init_performance2(); - -// node_modules/.pnpm/@twurple+common@8.0.3/node_modules/@twurple/common/lib/errors/CustomError.js -init_modules_watch_stub(); -init_performance2(); -var CustomError2 = class extends Error { - static { - __name(this, "CustomError"); - } - constructor(message, options) { - super(message, options); - Object.setPrototypeOf(this, new.target.prototype); - Error.captureStackTrace?.(this, new.target.constructor); - } - get name() { - return this.constructor.name; - } -}; - -// node_modules/.pnpm/@twurple+common@8.0.3/node_modules/@twurple/common/lib/errors/RelationAssertionError.js -var RelationAssertionError = class extends CustomError2 { - static { - __name(this, "RelationAssertionError"); - } - constructor() { - super("Relation returned null - this may be a library bug or a race condition in your own code"); - } -}; - -// node_modules/.pnpm/@twurple+common@8.0.3/node_modules/@twurple/common/lib/relations.js -function checkRelationAssertion(value) { - if (value == null) { - throw new RelationAssertionError(); - } - return value; -} -__name(checkRelationAssertion, "checkRelationAssertion"); - -// node_modules/.pnpm/@twurple+common@8.0.3/node_modules/@twurple/common/lib/rtfm.js -init_modules_watch_stub(); -init_performance2(); -function rtfm(pkg, name, idKey) { - return (clazz) => { - const fn = idKey ? function() { - return `[${name}#${this[idKey]} - please check https://twurple.js.org/reference/${pkg}/classes/${name}.html for available properties]`; - } : function() { - return `[${name} - please check https://twurple.js.org/reference/${pkg}/classes/${name}.html for available properties]`; - }; - Object.defineProperty(clazz.prototype, /* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom"), { - value: fn, - enumerable: false - }); - }; -} -__name(rtfm, "rtfm"); - -// node_modules/.pnpm/@twurple+common@8.0.3/node_modules/@twurple/common/lib/extensions/HelixExtension.js -init_modules_watch_stub(); -init_performance2(); -var HelixExtension = class HelixExtension2 extends DataObject { - static { - __name(this, "HelixExtension"); - } - /** - * The name of the extension's author. - */ - get authorName() { - return this[rawDataSymbol].author_name; - } - /** - * Whether bits are enabled for the extension. - */ - get bitsEnabled() { - return this[rawDataSymbol].bits_enabled; - } - /** - * Whether the extension can be installed. - */ - get installable() { - return this[rawDataSymbol].can_install; - } - /** - * The location of the extension's configuration. - */ - get configurationLocation() { - return this[rawDataSymbol].configuration_location; - } - /** - * The extension's description. - */ - get description() { - return this[rawDataSymbol].description; - } - /** - * The URL of the extension's terms of service. - */ - get tosUrl() { - return this[rawDataSymbol].eula_tos_url; - } - /** - * Whether the extension has support for sending chat messages. - */ - get hasChatSupport() { - return this[rawDataSymbol].has_chat_support; - } - /** - * The URL of the extension's default sized icon. - */ - get iconUrl() { - return this[rawDataSymbol].icon_url; - } - /** - * Gets the URL of the extension's icon in the given size. - * - * @param size The size of the icon. - */ - getIconUrl(size) { - return this[rawDataSymbol].icon_urls[size]; - } - /** - * The extension's ID. - */ - get id() { - return this[rawDataSymbol].id; - } - /** - * The extension's name. - */ - get name() { - return this[rawDataSymbol].name; - } - /** - * The URL of the extension's privacy policy. - */ - get privacyPolicyUrl() { - return this[rawDataSymbol].privacy_policy_url; - } - /** - * Whether the extension requests its users to share their identity with it. - */ - get requestsIdentityLink() { - return this[rawDataSymbol].request_identity_link; - } - /** - * The URLs of the extension's screenshots. - */ - get screenshotUrls() { - return this[rawDataSymbol].screenshot_urls; - } - /** - * The extension's activity state. - */ - get state() { - return this[rawDataSymbol].state; - } - /** - * The extension's level of support for subscriptions. - */ - get subscriptionsSupportLevel() { - return this[rawDataSymbol].subscriptions_support_level; - } - /** - * The extension's feature summary. - */ - get summary() { - return this[rawDataSymbol].summary; - } - /** - * The extension's support email address. - */ - get supportEmail() { - return this[rawDataSymbol].support_email; - } - /** - * The extension's version. - */ - get version() { - return this[rawDataSymbol].version; - } - /** - * The extension's feature summary for viewers. - */ - get viewerSummary() { - return this[rawDataSymbol].viewer_summary; - } - /** - * The extension's feature summary for viewers. - * - * @deprecated Use `viewerSummary` instead. - */ - get viewerSummery() { - return this[rawDataSymbol].viewer_summary; - } - /** - * The extension's allowed configuration URLs. - */ - get allowedConfigUrls() { - return this[rawDataSymbol].allowlisted_config_urls; - } - /** - * The extension's allowed panel URLs. - */ - get allowedPanelUrls() { - return this[rawDataSymbol].allowlisted_panel_urls; - } - /** - * The URL shown when a viewer opens the extension on a mobile device. - * - * If the extension does not have a mobile view, this is null. - */ - get mobileViewerUrl() { - return this[rawDataSymbol].views.mobile?.viewer_url ?? null; - } - /** - * The URL shown to the viewer when the extension is shown as a panel. - * - * If the extension does not have a panel view, this is null. - */ - get panelViewerUrl() { - return this[rawDataSymbol].views.panel?.viewer_url ?? null; - } - /** - * The height of the extension panel. - * - * If the extension does not have a panel view, this is null. - */ - get panelHeight() { - return this[rawDataSymbol].views.panel?.height ?? null; - } - /** - * Whether the extension can link to external content from its panel view. - * - * If the extension does not have a panel view, this is null. - */ - get panelCanLinkExternalContent() { - return this[rawDataSymbol].views.panel?.can_link_external_content ?? null; - } - /** - * The URL shown to the viewer when the extension is shown as a video overlay. - * - * If the extension does not have a overlay view, this is null. - */ - get overlayViewerUrl() { - return this[rawDataSymbol].views.video_overlay?.viewer_url ?? null; - } - /** - * Whether the extension can link to external content from its overlay view. - * - * If the extension does not have a overlay view, this is null. - */ - get overlayCanLinkExternalContent() { - return this[rawDataSymbol].views.video_overlay?.can_link_external_content ?? null; - } - /** - * The URL shown to the viewer when the extension is shown as a video component. - * - * If the extension does not have a component view, this is null. - */ - get componentViewerUrl() { - return this[rawDataSymbol].views.component?.viewer_url ?? null; - } - /** - * The aspect width of the extension's component view. - * - * If the extension does not have a component view, this is null. - */ - get componentAspectWidth() { - return this[rawDataSymbol].views.component?.aspect_width ?? null; - } - /** - * The aspect height of the extension's component view. - * - * If the extension does not have a component view, this is null. - */ - get componentAspectHeight() { - return this[rawDataSymbol].views.component?.aspect_height ?? null; - } - /** - * The horizontal aspect ratio of the extension's component view. - * - * If the extension does not have a component view, this is null. - */ - get componentAspectRatioX() { - return this[rawDataSymbol].views.component?.aspect_ratio_x ?? null; - } - /** - * The vertical aspect ratio of the extension's component view. - * - * If the extension does not have a component view, this is null. - */ - get componentAspectRatioY() { - return this[rawDataSymbol].views.component?.aspect_ratio_y ?? null; - } - /** - * Whether the extension's component view should automatically scale. - * - * If the extension does not have a component view, this is null. - */ - get componentAutoScales() { - return this[rawDataSymbol].views.component?.autoscale ?? null; - } - /** - * The base width of the extension's component view to use for scaling. - * - * If the extension does not have a component view, this is null. - */ - get componentScalePixels() { - return this[rawDataSymbol].views.component?.scale_pixels ?? null; - } - /** - * The target height of the extension's component view. - * - * If the extension does not have a component view, this is null. - */ - get componentTargetHeight() { - return this[rawDataSymbol].views.component?.target_height ?? null; - } - /** - * The size of the extension's component view. - * - * If the extension does not have a component view, this is null. - */ - get componentSize() { - return this[rawDataSymbol].views.component?.size ?? null; - } - /** - * Whether zooming is enabled for the extension's component view. - * - * If the extension does not have a component view, this is null. - */ - get componentZoom() { - return this[rawDataSymbol].views.component?.zoom ?? null; - } - /** - * The zoom pixels of the extension's component view. - * - * If the extension does not have a component view, this is null. - */ - get componentZoomPixels() { - return this[rawDataSymbol].views.component?.zoom_pixels ?? null; - } - /** - * Whether the extension can link to external content from its component view. - * - * If the extension does not have a component view, this is null. - */ - get componentCanLinkExternalContent() { - return this[rawDataSymbol].views.component?.can_link_external_content ?? null; - } - /** - * The URL shown to the viewer when the extension's configuration page is shown. - * - * If the extension does not have a config view, this is null. - */ - get configViewerUrl() { - return this[rawDataSymbol].views.config?.viewer_url ?? null; - } - /** - * Whether the extension can link to external content from its config view. - * - * If the extension does not have a config view, this is null. - */ - get configCanLinkExternalContent() { - return this[rawDataSymbol].views.config?.can_link_external_content ?? null; - } -}; -HelixExtension = __decorate([ - rtfm("api", "HelixExtension", "id") -], HelixExtension); - -// node_modules/.pnpm/@twurple+common@8.0.3/node_modules/@twurple/common/lib/errors/HellFreezesOverError.js -init_modules_watch_stub(); -init_performance2(); -var HellFreezesOverError = class extends CustomError2 { - static { - __name(this, "HellFreezesOverError"); - } - constructor(message) { - super(`${message} - this should never happen, please file a bug in the GitHub issue tracker`); - } -}; - -// node_modules/.pnpm/@twurple+common@8.0.3/node_modules/@twurple/common/lib/userResolvers.js -init_modules_watch_stub(); -init_performance2(); -function extractUserId(user) { - if (typeof user === "string") { - return user; - } - if (typeof user === "number") { - return user.toString(10); - } - return user.id; -} -__name(extractUserId, "extractUserId"); -function extractUserName(user) { - return typeof user === "string" ? user : user.name; -} -__name(extractUserName, "extractUserName"); - -// node_modules/.pnpm/@twurple+api-call@8.0.3/node_modules/@twurple/api-call/lib/helpers/transform.js -init_modules_watch_stub(); -init_performance2(); - -// node_modules/.pnpm/@twurple+api-call@8.0.3/node_modules/@twurple/api-call/lib/errors/HttpStatusCodeError.js -init_modules_watch_stub(); -init_performance2(); -var HttpStatusCodeError = class extends CustomError2 { - static { - __name(this, "HttpStatusCodeError"); - } - _statusCode; - _url; - _method; - _body; - /** @private */ - constructor(_statusCode, statusText, _url, _method, _body, isJson) { - super(`Encountered HTTP status code ${_statusCode}: ${statusText} - -URL: ${_url} -Method: ${_method} -Body: -${!isJson && _body.length > 150 ? `${_body.slice(0, 147)}...` : _body}`); - this._statusCode = _statusCode; - this._url = _url; - this._method = _method; - this._body = _body; - } - /** - * The HTTP status code of the error. - */ - get statusCode() { - return this._statusCode; - } - /** - * The URL that was requested. - */ - get url() { - return this._url; - } - /** - * The HTTP method that was used for the request. - */ - get method() { - return this._method; - } - /** - * The body that was used for the request, as a string. - */ - get body() { - return this._body; - } -}; - -// node_modules/.pnpm/@twurple+api-call@8.0.3/node_modules/@twurple/api-call/lib/helpers/transform.js -async function handleTwitchApiResponseError(response, options) { - if (!response.ok) { - const isJson = response.headers.get("Content-Type") === "application/json"; - const text2 = isJson ? JSON.stringify(await response.json(), null, 2) : await response.text(); - const params = qsStringify(options.query); - const fullUrl = `${options.url}${params}`; - throw new HttpStatusCodeError(response.status, response.statusText, fullUrl, options.method ?? "GET", text2, isJson); - } -} -__name(handleTwitchApiResponseError, "handleTwitchApiResponseError"); -async function transformTwitchApiResponse(response) { - if (response.status === 204) { - return void 0; - } - const text2 = await response.text(); - if (!text2) { - return void 0; - } - return JSON.parse(text2); -} -__name(transformTwitchApiResponse, "transformTwitchApiResponse"); - -// node_modules/.pnpm/@twurple+api-call@8.0.3/node_modules/@twurple/api-call/lib/helpers/url.js -init_modules_watch_stub(); -init_performance2(); -function getTwitchApiUrl(url, type) { - const mockServerPort = getMockApiPort(); - switch (type) { - case "helix": { - const unprefixedUrl = url.replace(/^\//, ""); - return mockServerPort ? unprefixedUrl === "eventsub/subscriptions" ? `http://localhost:${mockServerPort}/${unprefixedUrl}` : `http://localhost:${mockServerPort}/mock/${unprefixedUrl}` : `https://api.twitch.tv/helix/${unprefixedUrl}`; - } - case "auth": { - const unprefixedUrl = url.replace(/^\//, ""); - return mockServerPort ? `http://localhost:${mockServerPort}/auth/${unprefixedUrl}` : `https://id.twitch.tv/oauth2/${unprefixedUrl}`; - } - case "custom": - return url; - default: - return url; - } -} -__name(getTwitchApiUrl, "getTwitchApiUrl"); - -// node_modules/.pnpm/@twurple+api-call@8.0.3/node_modules/@twurple/api-call/lib/apiCall.js -async function callTwitchApiRaw(options, clientId, accessToken, authorizationType, fetchOptions = {}) { - const type = options.type ?? "helix"; - const url = getTwitchApiUrl(options.url, type); - const params = qsStringify(options.query); - const headers = new Headers({ Accept: "application/json" }); - let body = void 0; - if (options.jsonBody) { - body = JSON.stringify(options.jsonBody); - headers.append("Content-Type", "application/json"); - } - if (clientId && type !== "auth") { - headers.append("Client-ID", clientId); - } - if (accessToken) { - headers.append("Authorization", `${type === "helix" ? authorizationType ?? "Bearer" : "OAuth"} ${accessToken}`); - } - const requestOptions = { - ...fetchOptions, - method: options.method ?? "GET", - headers, - body - }; - return await fetch(`${url}${params}`, requestOptions); -} -__name(callTwitchApiRaw, "callTwitchApiRaw"); -async function callTwitchApi(options, clientId, accessToken, authorizationType, fetchOptions = {}) { - const response = await callTwitchApiRaw(options, clientId, accessToken, authorizationType, fetchOptions); - await handleTwitchApiResponseError(response, options); - return await transformTwitchApiResponse(response); -} -__name(callTwitchApi, "callTwitchApi"); - -// node_modules/.pnpm/@twurple+api-call@8.0.3/node_modules/@twurple/api-call/lib/helpers/queries.external.js -init_modules_watch_stub(); -init_performance2(); -function createBroadcasterQuery(user) { - return { - broadcaster_id: extractUserId(user) - }; -} -__name(createBroadcasterQuery, "createBroadcasterQuery"); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/errors/ConfigError.js -init_modules_watch_stub(); -init_performance2(); -var ConfigError = class extends CustomError2 { - static { - __name(this, "ConfigError"); - } -}; - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/utils/HelixRateLimiter.js -init_modules_watch_stub(); -init_performance2(); -var HelixRateLimiter = class extends ResponseBasedRateLimiter { - static { - __name(this, "HelixRateLimiter"); - } - async doRequest({ options, clientId, accessToken, authorizationType, fetchOptions }) { - return await callTwitchApiRaw(options, clientId, accessToken, authorizationType, fetchOptions); - } - needsToRetryAfter(res) { - if (res.status === 429 && (!res.headers.has("ratelimit-remaining") || Number(res.headers.get("ratelimit-remaining")) === 0)) { - return +res.headers.get("ratelimit-reset") * 1e3 - Date.now(); - } - return null; - } - getParametersFromResponse(res) { - const { headers } = res; - return { - limit: +headers.get("ratelimit-limit"), - remaining: +headers.get("ratelimit-remaining"), - resetsAt: +headers.get("ratelimit-reset") * 1e3 - }; - } -}; - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/client/BaseApiClient.js -init_modules_watch_stub(); -init_performance2(); - -// node_modules/.pnpm/@d-fischer+cache-decorators@4.0.1/node_modules/@d-fischer/cache-decorators/es/index.mjs -init_modules_watch_stub(); -init_performance2(); - -// node_modules/.pnpm/@d-fischer+cache-decorators@4.0.1/node_modules/@d-fischer/cache-decorators/es/decorators/Cacheable.mjs -init_modules_watch_stub(); -init_performance2(); - -// node_modules/.pnpm/@d-fischer+cache-decorators@4.0.1/node_modules/@d-fischer/cache-decorators/es/utils/createCacheKey.mjs -init_modules_watch_stub(); -init_performance2(); -function createSingleCacheKey(param) { - switch (typeof param) { - case "undefined": { - return ""; - } - case "object": { - if (param === null) { - return ""; - } - if ("cacheKey" in param) { - return param.cacheKey; - } - const objKey = JSON.stringify(param); - if (objKey !== "{}") { - return objKey; - } - } - // fallthrough - default: { - return param.toString(); - } - } -} -__name(createSingleCacheKey, "createSingleCacheKey"); -function createCacheKey(propName, params, prefix) { - return [propName, ...params.map(createSingleCacheKey)].join("/") + (prefix ? "/" : ""); -} -__name(createCacheKey, "createCacheKey"); - -// node_modules/.pnpm/@d-fischer+cache-decorators@4.0.1/node_modules/@d-fischer/cache-decorators/es/decorators/Cacheable.mjs -var cacheSymbol = /* @__PURE__ */ Symbol("cache"); -function Cacheable(cls) { - var _a4, _b3; - return _b3 = class extends cls { - static { - __name(this, "_b"); - } - constructor() { - super(...arguments); - this[_a4] = /* @__PURE__ */ new Map(); - } - getFromCache(cacheKey) { - this._cleanCache(); - if (this[cacheSymbol].has(cacheKey)) { - const entry = this[cacheSymbol].get(cacheKey); - if (entry) { - return entry.value; - } - } - return void 0; - } - setCache(cacheKey, value, timeInSeconds) { - this[cacheSymbol].set(cacheKey, { - value, - expires: Date.now() + timeInSeconds * 1e3 - }); - } - removeFromCache(cacheKey, prefix) { - const internalCacheKey = this._getInternalCacheKey(cacheKey, prefix); - if (prefix) { - this[cacheSymbol].forEach((val, key) => { - if (key.startsWith(internalCacheKey)) { - this[cacheSymbol].delete(key); - } - }); - } else { - this[cacheSymbol].delete(internalCacheKey); - } - } - _cleanCache() { - const now = Date.now(); - this[cacheSymbol].forEach((val, key) => { - if (val.expires < now) { - this[cacheSymbol].delete(key); - } - }); - } - _getInternalCacheKey(cacheKey, prefix) { - if (typeof cacheKey === "string") { - let internalCacheKey = cacheKey; - if (!internalCacheKey.endsWith("/")) { - internalCacheKey += "/"; - } - return internalCacheKey; - } else { - const propName = cacheKey.shift(); - return createCacheKey(propName, cacheKey, prefix); - } - } - }, _a4 = cacheSymbol, _b3; -} -__name(Cacheable, "Cacheable"); - -// node_modules/.pnpm/@d-fischer+cache-decorators@4.0.1/node_modules/@d-fischer/cache-decorators/es/decorators/CachedGetter.mjs -init_modules_watch_stub(); -init_performance2(); -function CachedGetter(timeInSeconds = Infinity) { - return function(target, propName, descriptor) { - if (descriptor.get) { - const origFn = descriptor.get; - descriptor.get = function() { - const cacheKey = createCacheKey(propName, []); - const cachedValue = this.getFromCache(cacheKey); - if (cachedValue) { - return cachedValue; - } - const result = origFn.call(this); - this.setCache(cacheKey, result, timeInSeconds); - return result; - }; - } - return descriptor; - }; -} -__name(CachedGetter, "CachedGetter"); - -// node_modules/.pnpm/@d-fischer+typed-event-emitter@3.3.3/node_modules/@d-fischer/typed-event-emitter/es/index.mjs -init_modules_watch_stub(); -init_performance2(); - -// node_modules/.pnpm/@d-fischer+typed-event-emitter@3.3.3/node_modules/@d-fischer/typed-event-emitter/es/EventEmitter.mjs -init_modules_watch_stub(); -init_performance2(); - -// node_modules/.pnpm/@d-fischer+typed-event-emitter@3.3.3/node_modules/@d-fischer/typed-event-emitter/es/Listener.mjs -init_modules_watch_stub(); -init_performance2(); -var Listener = class { - static { - __name(this, "Listener"); - } - /** @private */ - constructor(owner, event, listener, _internal = false) { - this.owner = owner; - this.event = event; - this.listener = listener; - this._internal = _internal; - } - unbind() { - this.owner.removeListener(this); - } -}; - -// node_modules/.pnpm/@d-fischer+typed-event-emitter@3.3.3/node_modules/@d-fischer/typed-event-emitter/es/EventEmitter.mjs -var EventEmitter2 = class { - static { - __name(this, "EventEmitter"); - } - constructor() { - this._eventListeners = /* @__PURE__ */ new Map(); - this._internalEventListeners = /* @__PURE__ */ new Map(); - } - on(event, listener) { - return this._addListener(false, event, listener); - } - addListener(event, listener) { - return this._addListener(false, event, listener); - } - removeListener(idOrEvent, listener) { - this._removeListener(false, idOrEvent, listener); - } - registerEvent() { - const eventBinder = /* @__PURE__ */ __name((handler) => this.addListener(eventBinder, handler), "eventBinder"); - return eventBinder; - } - emit(event, ...args) { - if (this._eventListeners.has(event)) { - for (const listener of this._eventListeners.get(event)) { - listener(...args); - } - } - if (this._internalEventListeners.has(event)) { - for (const listener of this._internalEventListeners.get(event)) { - listener(...args); - } - } - } - registerInternalEvent() { - const eventBinder = /* @__PURE__ */ __name((handler) => this.addInternalListener(eventBinder, handler), "eventBinder"); - return eventBinder; - } - addInternalListener(event, listener) { - return this._addListener(true, event, listener); - } - removeInternalListener(idOrEvent, listener) { - this._removeListener(true, idOrEvent, listener); - } - _addListener(internal, event, listener) { - const listenerMap = internal ? this._eventListeners : this._internalEventListeners; - if (listenerMap.has(event)) { - listenerMap.get(event).push(listener); - } else { - listenerMap.set(event, [listener]); - } - return new Listener(this, event, listener, internal); - } - _removeListener(internal, idOrEvent, listener) { - const listenerMap = internal ? this._eventListeners : this._internalEventListeners; - if (!idOrEvent) { - listenerMap.clear(); - } else if (typeof idOrEvent === "object") { - const id = idOrEvent; - this._removeListener(id._internal, id.event, id.listener); - } else { - const event = idOrEvent; - if (listenerMap.has(event)) { - if (listener) { - const listeners = listenerMap.get(event); - let idx = 0; - while ((idx = listeners.indexOf(listener)) !== -1) { - listeners.splice(idx, 1); - } - } else { - listenerMap.delete(event); - } - } - } - } -}; - -// node_modules/.pnpm/@twurple+auth@8.0.3/node_modules/@twurple/auth/lib/index.js -init_modules_watch_stub(); -init_performance2(); - -// node_modules/.pnpm/@twurple+auth@8.0.3/node_modules/@twurple/auth/lib/AccessToken.js -init_modules_watch_stub(); -init_performance2(); -var EXPIRY_GRACE_PERIOD = 6e4; -function getExpiryMillis(token) { - return mapNullable(token.expiresIn, (_) => token.obtainmentTimestamp + _ * 1e3 - EXPIRY_GRACE_PERIOD); -} -__name(getExpiryMillis, "getExpiryMillis"); -function accessTokenIsExpired(token) { - return mapNullable(getExpiryMillis(token), (_) => Date.now() > _) ?? false; -} -__name(accessTokenIsExpired, "accessTokenIsExpired"); - -// node_modules/.pnpm/@twurple+auth@8.0.3/node_modules/@twurple/auth/lib/helpers.js -init_modules_watch_stub(); -init_performance2(); - -// node_modules/.pnpm/@twurple+auth@8.0.3/node_modules/@twurple/auth/lib/errors/InvalidTokenError.js -init_modules_watch_stub(); -init_performance2(); -var InvalidTokenError = class extends CustomError2 { - static { - __name(this, "InvalidTokenError"); - } - /** @private */ - constructor(options) { - super("Invalid token supplied", options); - } -}; - -// node_modules/.pnpm/@twurple+auth@8.0.3/node_modules/@twurple/auth/lib/helpers.external.js -init_modules_watch_stub(); -init_performance2(); -function createGetAppTokenQuery(clientId, clientSecret) { - return { - grant_type: "client_credentials", - client_id: clientId, - client_secret: clientSecret - }; -} -__name(createGetAppTokenQuery, "createGetAppTokenQuery"); - -// node_modules/.pnpm/@twurple+auth@8.0.3/node_modules/@twurple/auth/lib/TokenInfo.js -init_modules_watch_stub(); -init_performance2(); -var TokenInfo = class TokenInfo2 extends DataObject { - static { - __name(this, "TokenInfo"); - } - _obtainmentDate; - /** @internal */ - constructor(data2) { - super(data2); - this._obtainmentDate = /* @__PURE__ */ new Date(); - } - /** - * The client ID. - */ - get clientId() { - return this[rawDataSymbol].client_id; - } - /** - * The ID of the authenticated user. - */ - get userId() { - return this[rawDataSymbol].user_id ?? null; - } - /** - * The name of the authenticated user. - */ - get userName() { - return this[rawDataSymbol].login ?? null; - } - /** - * The scopes for which the token is valid. - */ - get scopes() { - return this[rawDataSymbol].scopes; - } - /** - * The time when the token will expire. - * - * If this returns null, it means that the token never expires (happens with some old client IDs). - */ - get expiryDate() { - return mapNullable(this[rawDataSymbol].expires_in, (v) => new Date(this._obtainmentDate.getTime() + v * 1e3)); - } -}; -TokenInfo = __decorate([ - rtfm("auth", "TokenInfo", "clientId") -], TokenInfo); - -// node_modules/.pnpm/@twurple+auth@8.0.3/node_modules/@twurple/auth/lib/helpers.js -function createAccessTokenFromData(data2) { - return { - accessToken: data2.access_token, - refreshToken: data2.refresh_token || null, - scope: data2.scope ?? [], - expiresIn: data2.expires_in ?? null, - obtainmentTimestamp: Date.now() - }; -} -__name(createAccessTokenFromData, "createAccessTokenFromData"); -async function getAppToken(clientId, clientSecret) { - return createAccessTokenFromData(await callTwitchApi({ - type: "auth", - url: "token", - method: "POST", - query: createGetAppTokenQuery(clientId, clientSecret) - })); -} -__name(getAppToken, "getAppToken"); - -// node_modules/.pnpm/@twurple+auth@8.0.3/node_modules/@twurple/auth/lib/TokenFetcher.js -init_modules_watch_stub(); -init_performance2(); -var TokenFetcher = class { - static { - __name(this, "TokenFetcher"); - } - _executor; - _newTokenScopeSets = []; - _newTokenPromise = null; - _queuedScopeSets = []; - _queueExecutor = null; - _queuePromise = null; - constructor(executor) { - this._executor = executor; - } - async fetch(...scopeSets) { - const filteredScopeSets = scopeSets.filter((val) => Boolean(val)); - if (this._newTokenPromise) { - if (!filteredScopeSets.length) { - return await this._newTokenPromise; - } - if (this._queueExecutor) { - this._queuedScopeSets.push(...filteredScopeSets); - } else { - this._queuedScopeSets = [...filteredScopeSets]; - } - if (!this._queuePromise) { - const { promise: promise2, resolve: resolve2, reject: reject2 } = promiseWithResolvers(); - this._queuePromise = promise2; - this._queueExecutor = async () => { - if (!this._queuePromise) { - return; - } - this._newTokenScopeSets = this._queuedScopeSets; - this._queuedScopeSets = []; - this._newTokenPromise = this._queuePromise; - this._queuePromise = null; - this._queueExecutor = null; - try { - resolve2(await this._executor(this._newTokenScopeSets)); - } catch (e) { - reject2(e); - } finally { - this._newTokenPromise = null; - this._newTokenScopeSets = []; - this._queueExecutor?.(); - } - }; - } - return await this._queuePromise; - } - this._newTokenScopeSets = [...filteredScopeSets]; - const { promise, resolve, reject } = promiseWithResolvers(); - this._newTokenPromise = promise; - try { - resolve(await this._executor(this._newTokenScopeSets)); - } catch (e) { - reject(e); - } finally { - this._newTokenPromise = null; - this._newTokenScopeSets = []; - this._queueExecutor?.(); - } - return await promise; - } -}; - -// node_modules/.pnpm/@twurple+auth@8.0.3/node_modules/@twurple/auth/lib/providers/AppTokenAuthProvider.js -init_modules_watch_stub(); -init_performance2(); -var AppTokenAuthProvider = class AppTokenAuthProvider2 { - static { - __name(this, "AppTokenAuthProvider"); - } - _clientId; - /** @internal */ - _clientSecret; - /** @internal */ - _token; - /** @internal */ - _fetcher; - _impliedScopes; - /** - * Creates a new auth provider to receive an application token with using the client ID and secret. - * - * @param clientId The client ID of your application. - * @param clientSecret The client secret of your application. - * @param impliedScopes The scopes that are implied for your application, - * for example an extension that is allowed to access subscriptions. - */ - constructor(clientId, clientSecret, impliedScopes = []) { - this._clientId = clientId; - this._clientSecret = clientSecret; - this._impliedScopes = impliedScopes; - this._fetcher = new TokenFetcher(async (scopes) => await this._fetch(scopes)); - } - /** - * The client ID. - */ - get clientId() { - return this._clientId; - } - /** - * The scopes that are currently available using the access token. - */ - get currentScopes() { - return this._impliedScopes; - } - /** - * Can only get tokens for implied scopes (i.e. extension subscription support). - * - * The consumer is expected to take care that this is actually set up in the Twitch developer console. - * - * @param user The user to get an access token for. - * @param scopeSets The requested scopes. - */ - async getAccessTokenForUser(user, ...scopeSets) { - if (scopeSets.every((scopeSet) => scopeSet?.some((scope) => this._impliedScopes.includes(scope)) ?? true)) { - const appToken = await this.getAppAccessToken(); - return { - ...appToken, - userId: extractUserId(user) - }; - } - throw new Error("Can not get user access token for AppTokenAuthProvider"); - } - /** - * Throws, because this auth provider does not support user authentication. - */ - getCurrentScopesForUser() { - return this._impliedScopes; - } - /** - * Fetches an app access token. - */ - async getAnyAccessToken() { - return await this._fetcher.fetch(); - } - /** - * Fetches an app access token. - * - * @param forceNew Whether to always get a new token, even if the old one is still deemed valid internally. - */ - async getAppAccessToken(forceNew = false) { - if (forceNew) { - this._token = void 0; - } - return await this._fetcher.fetch(); - } - async _fetch(scopeSets) { - if (scopeSets.length > 0) { - for (const scopes of scopeSets) { - if (this._impliedScopes.length) { - if (scopes.every((scope) => !this._impliedScopes.includes(scope))) { - throw new Error(`One of the scopes ${scopes.join(", ")} requested but only the scope ${this._impliedScopes.join(", ")} is implied`); - } - } else { - throw new Error(`One of the scopes ${scopes.join(", ")} requested but the client credentials flow does not support scopes`); - } - } - } - if (!this._token || accessTokenIsExpired(this._token)) { - return this._token = await getAppToken(this._clientId, this._clientSecret); - } - return this._token; - } -}; -__decorate([ - Enumerable(false) -], AppTokenAuthProvider.prototype, "_clientSecret", void 0); -__decorate([ - Enumerable(false) -], AppTokenAuthProvider.prototype, "_token", void 0); -__decorate([ - Enumerable(false) -], AppTokenAuthProvider.prototype, "_fetcher", void 0); -AppTokenAuthProvider = __decorate([ - rtfm("auth", "AppTokenAuthProvider", "clientId") -], AppTokenAuthProvider); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/client/BaseApiClient.js -var retry = __toESM(require_retry2(), 1); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/bits/HelixBitsApi.js -init_modules_watch_stub(); -init_performance2(); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/interfaces/endpoints/bits.external.js -init_modules_watch_stub(); -init_performance2(); -function createBitsLeaderboardQuery(params = {}) { - const { count: count2 = 10, period = "all", startDate, contextUserId } = params; - return { - count: count2.toString(), - period, - started_at: startDate?.toISOString(), - user_id: contextUserId - }; -} -__name(createBitsLeaderboardQuery, "createBitsLeaderboardQuery"); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/BaseApi.js -init_modules_watch_stub(); -init_performance2(); -var BaseApi = class { - static { - __name(this, "BaseApi"); - } - /** @internal */ - _client; - /** @internal */ - constructor(client) { - this._client = client; - } - /** @internal */ - _getUserContextIdWithDefault(userId) { - return this._client._getUserIdFromRequestContext(userId) ?? userId; - } -}; -__decorate([ - Enumerable(false) -], BaseApi.prototype, "_client", void 0); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/bits/HelixBitsLeaderboard.js -init_modules_watch_stub(); -init_performance2(); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/bits/HelixBitsLeaderboardEntry.js -init_modules_watch_stub(); -init_performance2(); -var HelixBitsLeaderboardEntry = class HelixBitsLeaderboardEntry2 extends DataObject { - static { - __name(this, "HelixBitsLeaderboardEntry"); - } - /** @internal */ - _client; - /** @internal */ - constructor(data2, client) { - super(data2); - this._client = client; - } - /** - * The ID of the user on the leaderboard. - */ - get userId() { - return this[rawDataSymbol].user_id; - } - /** - * The name of the user on the leaderboard. - */ - get userName() { - return this[rawDataSymbol].user_login; - } - /** - * The display name of the user on the leaderboard. - */ - get userDisplayName() { - return this[rawDataSymbol].user_name; - } - /** - * The position of the user on the leaderboard. - */ - get rank() { - return this[rawDataSymbol].rank; - } - /** - * The amount of bits used in the given period of time. - */ - get amount() { - return this[rawDataSymbol].score; - } - /** - * Gets the user of entry on the leaderboard. - */ - async getUser() { - return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].user_id)); - } -}; -__decorate([ - Enumerable(false) -], HelixBitsLeaderboardEntry.prototype, "_client", void 0); -HelixBitsLeaderboardEntry = __decorate([ - rtfm("api", "HelixBitsLeaderboardEntry", "userId") -], HelixBitsLeaderboardEntry); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/bits/HelixBitsLeaderboard.js -var HelixBitsLeaderboard = class HelixBitsLeaderboard2 extends DataObject { - static { - __name(this, "HelixBitsLeaderboard"); - } - /** @internal */ - _client; - /** @internal */ - constructor(data2, client) { - super(data2); - this._client = client; - } - /** - * The entries of the leaderboard. - */ - get entries() { - return this[rawDataSymbol].data.map((entry) => new HelixBitsLeaderboardEntry(entry, this._client)); - } - /** - * The total amount of people on the requested leaderboard. - */ - get totalCount() { - return this[rawDataSymbol].total; - } -}; -__decorate([ - Enumerable(false) -], HelixBitsLeaderboard.prototype, "_client", void 0); -__decorate([ - CachedGetter() -], HelixBitsLeaderboard.prototype, "entries", null); -HelixBitsLeaderboard = __decorate([ - Cacheable, - rtfm("api", "HelixBitsLeaderboard") -], HelixBitsLeaderboard); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/bits/HelixCheermoteList.js -init_modules_watch_stub(); -init_performance2(); -var HelixCheermoteList = class HelixCheermoteList2 extends DataObject { - static { - __name(this, "HelixCheermoteList"); - } - /** @internal */ - constructor(data2) { - super(indexBy(data2, (action) => action.prefix.toLowerCase())); - } - /** - * Gets the URL and color needed to properly represent a cheer of the given amount of bits with the given prefix. - * - * @param name The name/prefix of the cheermote. - * @param bits The amount of bits cheered. - * @param format The format of the cheermote you want to request. - */ - getCheermoteDisplayInfo(name, bits, format) { - name = name.toLowerCase(); - const { background, state, scale } = format; - const { tiers } = this[rawDataSymbol][name]; - const correctTier = tiers.sort((a, b) => b.min_bits - a.min_bits).find((tier) => tier.min_bits <= bits); - if (!correctTier) { - throw new HellFreezesOverError(`Cheermote "${name}" does not have an applicable tier for ${bits} bits`); - } - return { - url: correctTier.images[background][state][scale], - color: correctTier.color - }; - } - /** - * Gets all possible cheermote names. - */ - getPossibleNames() { - return Object.keys(this[rawDataSymbol]); - } -}; -HelixCheermoteList = __decorate([ - rtfm("api", "HelixCheermoteList") -], HelixCheermoteList); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/bits/HelixBitsApi.js -var HelixBitsApi = class HelixBitsApi2 extends BaseApi { - static { - __name(this, "HelixBitsApi"); - } - /** - * Gets a bits leaderboard of your channel. - * - * @param broadcaster The user to get the leaderboard of. - * @param params - * @expandParams - */ - async getLeaderboard(broadcaster, params = {}) { - const result = await this._client.callApi({ - type: "helix", - url: "bits/leaderboard", - userId: extractUserId(broadcaster), - scopes: ["bits:read"], - query: createBitsLeaderboardQuery(params) - }); - return new HelixBitsLeaderboard(result, this._client); - } - /** - * Gets all available cheermotes. - * - * @param broadcaster The broadcaster to include custom cheermotes of. - * - * If not given, only get global cheermotes. - */ - async getCheermotes(broadcaster) { - const result = await this._client.callApi({ - type: "helix", - url: "bits/cheermotes", - userId: mapOptional(broadcaster, extractUserId), - query: mapOptional(broadcaster, createBroadcasterQuery) - }); - return new HelixCheermoteList(result.data); - } -}; -HelixBitsApi = __decorate([ - rtfm("api", "HelixBitsApi") -], HelixBitsApi); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/channel/HelixChannelApi.js -init_modules_watch_stub(); -init_performance2(); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/interfaces/endpoints/channel.external.js -init_modules_watch_stub(); -init_performance2(); -function createChannelUpdateBody(data2) { - return { - game_id: data2.gameId, - broadcaster_language: data2.language, - title: data2.title, - delay: data2.delay?.toString(), - tags: data2.tags, - content_classification_labels: data2.contentClassificationLabels, - is_branded_content: data2.isBrandedContent - }; -} -__name(createChannelUpdateBody, "createChannelUpdateBody"); -function createChannelCommercialBody(broadcaster, length) { - return { - broadcaster_id: extractUserId(broadcaster), - length - }; -} -__name(createChannelCommercialBody, "createChannelCommercialBody"); -function createChannelVipUpdateQuery(broadcaster, user) { - return { - broadcaster_id: extractUserId(broadcaster), - user_id: extractUserId(user) - }; -} -__name(createChannelVipUpdateQuery, "createChannelVipUpdateQuery"); -function createChannelFollowerQuery(broadcaster, user) { - return { - broadcaster_id: extractUserId(broadcaster), - user_id: mapOptional(user, extractUserId) - }; -} -__name(createChannelFollowerQuery, "createChannelFollowerQuery"); -function createFollowedChannelQuery(user, broadcaster) { - return { - broadcaster_id: mapOptional(broadcaster, extractUserId), - user_id: extractUserId(user) - }; -} -__name(createFollowedChannelQuery, "createFollowedChannelQuery"); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/interfaces/endpoints/generic.external.js -init_modules_watch_stub(); -init_performance2(); -function createSingleKeyQuery(key, value) { - return { [key]: value }; -} -__name(createSingleKeyQuery, "createSingleKeyQuery"); -function createUserQuery(user) { - return { - user_id: extractUserId(user) - }; -} -__name(createUserQuery, "createUserQuery"); -function createModeratorActionQuery(broadcaster, moderatorId) { - return { - broadcaster_id: broadcaster, - moderator_id: moderatorId - }; -} -__name(createModeratorActionQuery, "createModeratorActionQuery"); -function createGetByIdsQuery(broadcaster, rewardIds) { - return { - broadcaster_id: extractUserId(broadcaster), - id: rewardIds - }; -} -__name(createGetByIdsQuery, "createGetByIdsQuery"); -function createChannelUsersCheckQuery(broadcaster, users) { - return { - broadcaster_id: extractUserId(broadcaster), - user_id: users.map(extractUserId) - }; -} -__name(createChannelUsersCheckQuery, "createChannelUsersCheckQuery"); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/relations/HelixUserRelation.js -init_modules_watch_stub(); -init_performance2(); -var HelixUserRelation = class HelixUserRelation2 extends DataObject { - static { - __name(this, "HelixUserRelation"); - } - /** @internal */ - _client; - /** @internal */ - constructor(data2, client) { - super(data2); - this._client = client; - } - /** - * The ID of the user. - */ - get id() { - return this[rawDataSymbol].user_id; - } - /** - * The name of the user. - */ - get name() { - return this[rawDataSymbol].user_login; - } - /** - * The display name of the user. - */ - get displayName() { - return this[rawDataSymbol].user_name; - } - /** - * Gets additional information about the user. - */ - async getUser() { - return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].user_id)); - } -}; -__decorate([ - Enumerable(false) -], HelixUserRelation.prototype, "_client", void 0); -HelixUserRelation = __decorate([ - rtfm("api", "HelixUserRelation", "id") -], HelixUserRelation); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/utils/HelixRequestBatcher.js -init_modules_watch_stub(); -init_performance2(); -var HelixRequestBatcher = class { - static { - __name(this, "HelixRequestBatcher"); - } - _callOptions; - _queryParamName; - _matchKey; - _mapper; - _limitPerRequest; - _client; - _requestedIds = []; - _requestResolversById = /* @__PURE__ */ new Map(); - _delay; - _waitTimer = null; - constructor(_callOptions, _queryParamName, _matchKey, client, _mapper, _limitPerRequest = 100) { - this._callOptions = _callOptions; - this._queryParamName = _queryParamName; - this._matchKey = _matchKey; - this._mapper = _mapper; - this._limitPerRequest = _limitPerRequest; - this._client = client; - this._delay = client._batchDelay; - } - async request(id) { - const { promise, resolve, reject } = promiseWithResolvers(); - if (!this._requestedIds.includes(id)) { - this._requestedIds.push(id); - } - if (this._requestResolversById.has(id)) { - this._requestResolversById.get(id).push({ resolve, reject }); - } else { - this._requestResolversById.set(id, [{ resolve, reject }]); - } - if (this._waitTimer) { - clearTimeout(this._waitTimer); - this._waitTimer = null; - } - if (this._requestedIds.length >= this._limitPerRequest) { - void this._handleBatch(this._requestedIds.splice(0, this._limitPerRequest)); - } else { - this._waitTimer = setTimeout(() => { - void this._handleBatch(this._requestedIds.splice(0, this._limitPerRequest)); - }, this._delay); - } - return await promise; - } - async _handleBatch(ids) { - try { - const { data: data2 } = await this._doRequest(ids); - const dataById = indexBy(data2, this._matchKey); - for (const id of ids) { - for (const resolver of this._requestResolversById.get(id) ?? []) { - if (Object.prototype.hasOwnProperty.call(dataById, id)) { - resolver.resolve(this._mapper(dataById[id])); - } else { - resolver.resolve(null); - } - } - this._requestResolversById.delete(id); - } - } catch (e) { - await Promise.all(ids.map(async (id) => { - try { - const result = await this._doRequest([id]); - for (const resolver of this._requestResolversById.get(id) ?? []) { - resolver.resolve(result.data.length ? this._mapper(result.data[0]) : null); - } - } catch (e_) { - for (const resolver of this._requestResolversById.get(id) ?? []) { - resolver.reject(e_); - } - } - this._requestResolversById.delete(id); - })); - } - } - async _doRequest(ids) { - return await this._client.callApi({ - type: "helix", - ...this._callOptions, - query: { - ...this._callOptions.query, - [this._queryParamName]: ids - } - }); - } -}; -__decorate([ - Enumerable(false) -], HelixRequestBatcher.prototype, "_client", void 0); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/utils/pagination/HelixPaginatedRequest.js -init_modules_watch_stub(); -init_performance2(); -if (!Object.prototype.hasOwnProperty.call(Symbol, "asyncIterator")) { - Symbol.asyncIterator = Symbol.asyncIterator ?? /* @__PURE__ */ Symbol.for("Symbol.asyncIterator"); -} -var HelixPaginatedRequest = class HelixPaginatedRequest2 { - static { - __name(this, "HelixPaginatedRequest"); - } - _callOptions; - _mapper; - _limitPerPage; - /** @internal */ - _client; - /** @internal */ - _currentCursor; - /** @internal */ - _isFinished = false; - /** @internal */ - _currentData; - /** @internal */ - constructor(_callOptions, client, _mapper, _limitPerPage = 100) { - this._callOptions = _callOptions; - this._mapper = _mapper; - this._limitPerPage = _limitPerPage; - this._client = client; - } - /** - * The last fetched page of data associated to the requested resource. - * - * Only works with {@link HelixPaginatedRequest#getNext} and not with any other methods of data fetching. - */ - get current() { - return this._currentData?.data; - } - /** - * Gets the next available page of data associated to the requested resource, or an empty array if there are no more available pages. - */ - async getNext() { - if (this._isFinished) { - return []; - } - const result = await this._fetchData(); - if (!result.data?.length) { - this._isFinished = true; - return []; - } - return this._processResult(result); - } - /** - * Gets all data associated to the requested resource. - * - * Be aware that this makes multiple calls to the Twitch API. Due to this, you might be more suspectible to rate limits. - * - * Also be aware that this resets the internal cursor, so avoid using this and {@link HelixPaginatedRequest#getNext}} together. - */ - async getAll() { - this.reset(); - const result = []; - do { - const data2 = await this.getNext(); - if (!data2.length) { - break; - } - result.push(...data2); - } while (this._currentCursor); - this.reset(); - return result; - } - /** - * Gets the current cursor. - * - * Only useful if you want to make manual requests to the API. - */ - get currentCursor() { - return this._currentCursor; - } - /** - * Resets the internal cursor. - * - * This will make {@link HelixPaginatedRequest#getNext}} start from the first page again. - */ - reset() { - this._currentCursor = void 0; - this._isFinished = false; - this._currentData = void 0; - } - async *[Symbol.asyncIterator]() { - this.reset(); - while (true) { - const data2 = await this.getNext(); - if (!data2.length) { - break; - } - yield* data2[Symbol.iterator](); - } - } - /** @internal */ - async _fetchData(additionalOptions = {}) { - return await this._client.callApi({ - type: "helix", - ...this._callOptions, - ...additionalOptions, - query: { - ...this._callOptions.query, - after: this._currentCursor, - first: this._limitPerPage.toString(), - ...additionalOptions.query - } - }); - } - /** @internal */ - _processResult(result) { - this._currentCursor = typeof result.pagination === "string" ? result.pagination : result.pagination?.cursor; - if (this._currentCursor === void 0) { - this._isFinished = true; - } - this._currentData = result; - return result.data.reduce((acc, elem) => { - const mapped = this._mapper(elem); - return Array.isArray(mapped) ? [...acc, ...mapped] : [...acc, mapped]; - }, []); - } -}; -__decorate([ - Enumerable(false) -], HelixPaginatedRequest.prototype, "_client", void 0); -HelixPaginatedRequest = __decorate([ - rtfm("api", "HelixPaginatedRequest") -], HelixPaginatedRequest); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/utils/pagination/HelixPaginatedRequestWithTotal.js -init_modules_watch_stub(); -init_performance2(); -var HelixPaginatedRequestWithTotal = class HelixPaginatedRequestWithTotal2 extends HelixPaginatedRequest { - static { - __name(this, "HelixPaginatedRequestWithTotal"); - } - /** - * Gets the total number of entities existing in the queried result set. - */ - async getTotalCount() { - const data2 = this._currentData ?? await this._fetchData({ query: { after: void 0 } }); - return data2.total; - } -}; -HelixPaginatedRequestWithTotal = __decorate([ - rtfm("api", "HelixPaginatedRequestWithTotal") -], HelixPaginatedRequestWithTotal); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/utils/pagination/HelixPaginatedResult.js -init_modules_watch_stub(); -init_performance2(); -function createPaginatedResult(response, type, client) { - let dataCache = void 0; - return { - get data() { - return dataCache ??= response.data?.map((data2) => new type(data2, client)) ?? []; - }, - cursor: typeof response.pagination === "string" ? response.pagination : response.pagination?.cursor - }; -} -__name(createPaginatedResult, "createPaginatedResult"); -function createPaginatedResultWithTotal(response, type, client) { - let dataCache = void 0; - return { - get data() { - return dataCache ??= response.data?.map((data2) => new type(data2, client)) ?? []; - }, - cursor: response.pagination.cursor, - total: response.total - }; -} -__name(createPaginatedResultWithTotal, "createPaginatedResultWithTotal"); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/utils/pagination/HelixPagination.js -init_modules_watch_stub(); -init_performance2(); -function createPaginationQuery({ after, before, limit } = {}) { - return { - after, - before, - first: limit?.toString() - }; -} -__name(createPaginationQuery, "createPaginationQuery"); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/channel/HelixChannel.js -init_modules_watch_stub(); -init_performance2(); -var HelixChannel = class HelixChannel2 extends DataObject { - static { - __name(this, "HelixChannel"); - } - /** @internal */ - _client; - /** @internal */ - constructor(data2, client) { - super(data2); - this._client = client; - } - /** - * The ID of the channel. - */ - get id() { - return this[rawDataSymbol].broadcaster_id; - } - /** - * The name of the channel. - */ - get name() { - return this[rawDataSymbol].broadcaster_login; - } - /** - * The display name of the channel. - */ - get displayName() { - return this[rawDataSymbol].broadcaster_name; - } - /** - * Gets more information about the broadcaster of the channel. - */ - async getBroadcaster() { - return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].broadcaster_id)); - } - /** - * The language of the channel. - */ - get language() { - return this[rawDataSymbol].broadcaster_language; - } - /** - * The ID of the game currently played on the channel. - */ - get gameId() { - return this[rawDataSymbol].game_id; - } - /** - * The name of the game currently played on the channel. - */ - get gameName() { - return this[rawDataSymbol].game_name; - } - /** - * Gets information about the game that is being played on the stream. - */ - async getGame() { - return this[rawDataSymbol].game_id ? checkRelationAssertion(await this._client.games.getGameById(this[rawDataSymbol].game_id)) : null; - } - /** - * The title of the channel. - */ - get title() { - return this[rawDataSymbol].title; - } - /** - * The stream delay of the channel, in seconds. - * - * If you didn't request this with broadcaster access, this is always zero. - */ - get delay() { - return this[rawDataSymbol].delay; - } - /** - * The tags applied to the channel. - */ - get tags() { - return this[rawDataSymbol].tags; - } - /** - * The content classification labels applied to the channel. - */ - get contentClassificationLabels() { - return this[rawDataSymbol].content_classification_labels; - } - /** - * Whether the channel currently displays branded content (as specified by the broadcaster). - */ - get isBrandedContent() { - return this[rawDataSymbol].is_branded_content; - } -}; -__decorate([ - Enumerable(false) -], HelixChannel.prototype, "_client", void 0); -HelixChannel = __decorate([ - rtfm("api", "HelixChannel", "id") -], HelixChannel); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/channel/HelixChannelEditor.js -init_modules_watch_stub(); -init_performance2(); -var HelixChannelEditor = class HelixChannelEditor2 extends DataObject { - static { - __name(this, "HelixChannelEditor"); - } - /** @internal */ - _client; - /** @internal */ - constructor(data2, client) { - super(data2); - this._client = client; - } - /** - * The ID of the user. - */ - get userId() { - return this[rawDataSymbol].user_id; - } - /** - * The display name of the user. - */ - get userDisplayName() { - return this[rawDataSymbol].user_name; - } - /** - * Gets additional information about the user. - */ - async getUser() { - return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].user_id)); - } - /** - * The date when the user was given editor status. - */ - get creationDate() { - return new Date(this[rawDataSymbol].created_at); - } -}; -__decorate([ - Enumerable(false) -], HelixChannelEditor.prototype, "_client", void 0); -HelixChannelEditor = __decorate([ - rtfm("api", "HelixChannelEditor", "userId") -], HelixChannelEditor); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/channel/HelixChannelFollower.js -init_modules_watch_stub(); -init_performance2(); -var HelixChannelFollower = class HelixChannelFollower2 extends DataObject { - static { - __name(this, "HelixChannelFollower"); - } - /** @internal */ - _client; - /** @internal */ - constructor(data2, client) { - super(data2); - this._client = client; - } - /** - * The ID of the user. - */ - get userId() { - return this[rawDataSymbol].user_id; - } - /** - * The name of the user. - */ - get userName() { - return this[rawDataSymbol].user_login; - } - /** - * The display name of the user. - */ - get userDisplayName() { - return this[rawDataSymbol].user_name; - } - /** - * Gets additional information about the user. - */ - async getUser() { - return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].user_id)); - } - /** - * The date when the user followed the broadcaster. - */ - get followDate() { - return new Date(this[rawDataSymbol].followed_at); - } -}; -__decorate([ - Enumerable(false) -], HelixChannelFollower.prototype, "_client", void 0); -HelixChannelFollower = __decorate([ - rtfm("api", "HelixChannelFollower", "userId") -], HelixChannelFollower); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/channel/HelixFollowedChannel.js -init_modules_watch_stub(); -init_performance2(); -var HelixFollowedChannel = class HelixFollowedChannel2 extends DataObject { - static { - __name(this, "HelixFollowedChannel"); - } - /** @internal */ - _client; - /** @internal */ - constructor(data2, client) { - super(data2); - this._client = client; - } - /** - * The ID of the broadcaster. - */ - get broadcasterId() { - return this[rawDataSymbol].broadcaster_id; - } - /** - * The name of the broadcaster. - */ - get broadcasterName() { - return this[rawDataSymbol].broadcaster_login; - } - /** - * The display name of the broadcaster. - */ - get broadcasterDisplayName() { - return this[rawDataSymbol].broadcaster_name; - } - /** - * Gets additional information about the broadcaster. - */ - async getBroadcaster() { - return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].broadcaster_id)); - } - /** - * The date when the user followed the broadcaster. - */ - get followDate() { - return new Date(this[rawDataSymbol].followed_at); - } -}; -__decorate([ - Enumerable(false) -], HelixFollowedChannel.prototype, "_client", void 0); -HelixFollowedChannel = __decorate([ - rtfm("api", "HelixFollowedChannel", "broadcasterId") -], HelixFollowedChannel); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/channel/HelixAdSchedule.js -init_modules_watch_stub(); -init_performance2(); -var HelixAdSchedule = class HelixAdSchedule2 extends DataObject { - static { - __name(this, "HelixAdSchedule"); - } - /** - * The number of snoozes available for the broadcaster. - */ - get snoozeCount() { - return this[rawDataSymbol].snooze_count; - } - /** - * The date and time when the broadcaster will gain an additional snooze. - * Returns `null` if all snoozes are already available. - */ - get snoozeRefreshDate() { - return this[rawDataSymbol].snooze_refresh_at ? new Date(this[rawDataSymbol].snooze_refresh_at * 1e3) : null; - } - /** - * The date and time of the broadcaster's next scheduled ad. - * Returns `null` if channel is not live or has no ad scheduled. - */ - get nextAdDate() { - return this[rawDataSymbol].next_ad_at ? new Date(this[rawDataSymbol].next_ad_at * 1e3) : null; - } - /** - * The length in seconds of the scheduled upcoming ad break. - */ - get duration() { - return this[rawDataSymbol].duration; - } - /** - * The date and time of the broadcaster's last ad-break. - * Returns `null` if channel is not live or has not run an ad. - */ - get lastAdDate() { - return this[rawDataSymbol].last_ad_at ? new Date(this[rawDataSymbol].last_ad_at * 1e3) : null; - } - /** - * The amount of pre-roll free time remaining for the channel in seconds. - */ - get prerollFreeTime() { - return this[rawDataSymbol].preroll_free_time; - } -}; -HelixAdSchedule = __decorate([ - rtfm("api", "HelixAdSchedule") -], HelixAdSchedule); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/channel/HelixSnoozeNextAdResult.js -init_modules_watch_stub(); -init_performance2(); -var HelixSnoozeNextAdResult = class HelixSnoozeNextAdResult2 extends DataObject { - static { - __name(this, "HelixSnoozeNextAdResult"); - } - /** - * The number of snoozes remaining for the broadcaster. - */ - get snoozeCount() { - return this[rawDataSymbol].snooze_count; - } - /** - * The date and time when the broadcaster will gain an additional snooze. - */ - get snoozeRefreshDate() { - return new Date(this[rawDataSymbol].snooze_refresh_at * 1e3); - } - /** - * The date and time of the broadcaster's next scheduled ad. - */ - get nextAdDate() { - return new Date(this[rawDataSymbol].next_ad_at * 1e3); - } -}; -HelixSnoozeNextAdResult = __decorate([ - rtfm("api", "HelixSnoozeNextAdResult") -], HelixSnoozeNextAdResult); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/channel/HelixChannelApi.js -var HelixChannelApi = class HelixChannelApi2 extends BaseApi { - static { - __name(this, "HelixChannelApi"); - } - /** @internal */ - _getChannelByIdBatcher = new HelixRequestBatcher({ - url: "channels" - }, "broadcaster_id", "broadcaster_id", this._client, (data2) => new HelixChannel(data2, this._client)); - /** - * Gets the channel data for the given user. - * - * @param user The user you want to get channel info for. - */ - async getChannelInfoById(user) { - const userId = extractUserId(user); - const result = await this._client.callApi({ - type: "helix", - url: "channels", - userId, - query: createBroadcasterQuery(userId) - }); - return mapNullable(result.data[0], (data2) => new HelixChannel(data2, this._client)); - } - /** - * Gets the channel data for the given user, batching multiple calls into fewer requests as the API allows. - * - * @param user The user you want to get channel info for. - */ - async getChannelInfoByIdBatched(user) { - return await this._getChannelByIdBatcher.request(extractUserId(user)); - } - /** - * Gets the channel data for the given users. - * - * @param users The users you want to get channel info for. - */ - async getChannelInfoByIds(users) { - const userIds = users.map(extractUserId); - const result = await this._client.callApi({ - type: "helix", - url: "channels", - query: createSingleKeyQuery("broadcaster_id", userIds) - }); - return result.data.map((data2) => new HelixChannel(data2, this._client)); - } - /** - * Updates the given user's channel data. - * - * @param user The user you want to update channel info for. - * @param data The channel info to set. - */ - async updateChannelInfo(user, data2) { - await this._client.callApi({ - type: "helix", - url: "channels", - method: "PATCH", - userId: extractUserId(user), - scopes: ["channel:manage:broadcast"], - query: createBroadcasterQuery(user), - jsonBody: createChannelUpdateBody(data2) - }); - } - /** - * Starts a commercial on a channel. - * - * @param broadcaster The broadcaster on whose channel the commercial is started. - * @param length The length of the commercial, in seconds. - */ - async startChannelCommercial(broadcaster, length) { - await this._client.callApi({ - type: "helix", - url: "channels/commercial", - method: "POST", - userId: extractUserId(broadcaster), - scopes: ["channel:edit:commercial"], - jsonBody: createChannelCommercialBody(broadcaster, length) - }); - } - /** - * Gets a list of users who have editor permissions on your channel. - * - * @param broadcaster The broadcaster to retreive the editors for. - */ - async getChannelEditors(broadcaster) { - const result = await this._client.callApi({ - type: "helix", - url: "channels/editors", - userId: extractUserId(broadcaster), - scopes: ["channel:read:editors"], - query: createBroadcasterQuery(broadcaster) - }); - return result.data.map((data2) => new HelixChannelEditor(data2, this._client)); - } - /** - * Gets a list of VIPs in a channel. - * - * @param broadcaster The owner of the channel to get VIPs for. - * @param pagination - * - * @expandParams - */ - async getVips(broadcaster, pagination) { - const response = await this._client.callApi({ - type: "helix", - url: "channels/vips", - userId: extractUserId(broadcaster), - scopes: ["channel:read:vips", "channel:manage:vips"], - query: { - ...createBroadcasterQuery(broadcaster), - ...createPaginationQuery(pagination) - } - }); - return createPaginatedResult(response, HelixUserRelation, this._client); - } - /** - * Creates a paginator for VIPs in a channel. - * - * @param broadcaster The owner of the channel to get VIPs for. - */ - getVipsPaginated(broadcaster) { - return new HelixPaginatedRequest({ - url: "channels/vips", - userId: extractUserId(broadcaster), - scopes: ["channel:read:vips", "channel:manage:vips"], - query: createBroadcasterQuery(broadcaster) - }, this._client, (data2) => new HelixUserRelation(data2, this._client)); - } - /** - * Checks the VIP status of a list of users in a channel. - * - * @param broadcaster The owner of the channel to check VIP status in. - * @param users The users to check. - */ - async checkVipForUsers(broadcaster, users) { - const response = await this._client.callApi({ - type: "helix", - url: "channels/vips", - userId: extractUserId(broadcaster), - scopes: ["channel:read:vips", "channel:manage:vips"], - query: createChannelUsersCheckQuery(broadcaster, users) - }); - return response.data.map((data2) => new HelixUserRelation(data2, this._client)); - } - /** - * Checks the VIP status of a user in a channel. - * - * @param broadcaster The owner of the channel to check VIP status in. - * @param user The user to check. - */ - async checkVipForUser(broadcaster, user) { - const userId = extractUserId(user); - const result = await this.checkVipForUsers(broadcaster, [userId]); - return result.some((rel) => rel.id === userId); - } - /** - * Adds a VIP to the broadcaster’s chat room. - * - * @param broadcaster The broadcaster that’s granting VIP status to the user. This ID must match the user ID in the access token. - * @param user The user to add as a VIP in the broadcaster’s chat room. - */ - async addVip(broadcaster, user) { - await this._client.callApi({ - type: "helix", - url: "channels/vips", - method: "POST", - userId: extractUserId(broadcaster), - scopes: ["channel:manage:vips"], - query: createChannelVipUpdateQuery(broadcaster, user) - }); - } - /** - * Removes a VIP from the broadcaster’s chat room. - * - * @param broadcaster The broadcaster that’s removing VIP status from the user. This ID must match the user ID in the access token. - * @param user The user to remove as a VIP from the broadcaster’s chat room. - */ - async removeVip(broadcaster, user) { - await this._client.callApi({ - type: "helix", - url: "channels/vips", - method: "DELETE", - userId: extractUserId(broadcaster), - scopes: ["channel:manage:vips"], - query: createChannelVipUpdateQuery(broadcaster, user) - }); - } - /** - * Gets the total number of users that follow the specified broadcaster. - * - * @param broadcaster The broadcaster you want to get the number of followers of. - */ - async getChannelFollowerCount(broadcaster) { - const result = await this._client.callApi({ - type: "helix", - url: "channels/followers", - method: "GET", - userId: extractUserId(broadcaster), - query: { - ...createChannelFollowerQuery(broadcaster), - ...createPaginationQuery({ limit: 1 }) - } - }); - return result.total; - } - /** - * Gets a list of users that follow the specified broadcaster. - * You can also use this endpoint to see whether a specific user follows the broadcaster. - * - * This uses the token of the broadcaster by default. - * If you want to execute this in the context of another user (who has to be moderator of the channel) - * you can do so using [user context overrides](/docs/auth/concepts/context-switching). - * - * @param broadcaster The broadcaster you want to get a list of followers for. - * @param user An optional user to determine if this user follows the broadcaster. - * If specified, the response contains this user if they follow the broadcaster. - * If not specified, the response contains all users that follow the broadcaster. - * @param pagination - * - * @expandParams - */ - async getChannelFollowers(broadcaster, user, pagination) { - const result = await this._client.callApi({ - type: "helix", - url: "channels/followers", - method: "GET", - userId: extractUserId(broadcaster), - canOverrideScopedUserContext: true, - scopes: ["moderator:read:followers"], - query: { - ...createChannelFollowerQuery(broadcaster, user), - ...createPaginationQuery(pagination) - } - }); - return createPaginatedResultWithTotal(result, HelixChannelFollower, this._client); - } - /** - * Creates a paginator for users that follow the specified broadcaster. - * - * This uses the token of the broadcaster by default. - * If you want to execute this in the context of another user (who has to be moderator of the channel) - * you can do so using [user context overrides](/docs/auth/concepts/context-switching). - * - * @param broadcaster The broadcaster for whom you are getting a list of followers. - * - * @expandParams - */ - getChannelFollowersPaginated(broadcaster) { - return new HelixPaginatedRequestWithTotal({ - url: "channels/followers", - method: "GET", - userId: extractUserId(broadcaster), - canOverrideScopedUserContext: true, - scopes: ["moderator:read:followers"], - query: createChannelFollowerQuery(broadcaster) - }, this._client, (data2) => new HelixChannelFollower(data2, this._client)); - } - /** - * Gets a list of broadcasters that the specified user follows. - * You can also use this endpoint to see whether the user follows a specific broadcaster. - * - * @param user The user that's getting a list of followed channels. - * This ID must match the user ID in the access token. - * @param broadcaster An optional broadcaster to determine if the user follows this broadcaster. - * If specified, the response contains this broadcaster if the user follows them. - * If not specified, the response contains all broadcasters that the user follows. - * @param pagination - * @returns - */ - async getFollowedChannels(user, broadcaster, pagination) { - const result = await this._client.callApi({ - type: "helix", - url: "channels/followed", - method: "GET", - userId: extractUserId(user), - scopes: ["user:read:follows"], - query: { - ...createFollowedChannelQuery(user, broadcaster), - ...createPaginationQuery(pagination) - } - }); - return createPaginatedResultWithTotal(result, HelixFollowedChannel, this._client); - } - /** - * Creates a paginator for broadcasters that the specified user follows. - * - * @param user The user that's getting a list of followed channels. - * The token of this user will be used to get the list of followed channels. - * @param broadcaster An optional broadcaster to determine if the user follows this broadcaster. - * If specified, the response contains this broadcaster if the user follows them. - * If not specified, the response contains all broadcasters that the user follows. - * @returns - */ - getFollowedChannelsPaginated(user, broadcaster) { - return new HelixPaginatedRequestWithTotal({ - url: "channels/followed", - method: "GET", - userId: extractUserId(user), - scopes: ["user:read:follows"], - query: createFollowedChannelQuery(user, broadcaster) - }, this._client, (data2) => new HelixFollowedChannel(data2, this._client)); - } - /** - * Gets information about the broadcaster's ad schedule. - * - * @param broadcaster The broadcaster to get ad schedule information about. - */ - async getAdSchedule(broadcaster) { - const response = await this._client.callApi({ - type: "helix", - url: "channels/ads", - method: "GET", - userId: extractUserId(broadcaster), - scopes: ["channel:read:ads"], - query: createBroadcasterQuery(broadcaster) - }); - return new HelixAdSchedule(response.data[0]); - } - /** - * Snoozes the broadcaster's next ad, if a snooze is available. - * - * @param broadcaster The broadcaster to get ad schedule information about. - */ - async snoozeNextAd(broadcaster) { - const response = await this._client.callApi({ - type: "helix", - url: "channels/ads/schedule/snooze", - method: "POST", - userId: extractUserId(broadcaster), - scopes: ["channel:manage:ads"], - query: createBroadcasterQuery(broadcaster) - }); - return new HelixSnoozeNextAdResult(response.data[0]); - } -}; -__decorate([ - Enumerable(false) -], HelixChannelApi.prototype, "_getChannelByIdBatcher", void 0); -HelixChannelApi = __decorate([ - rtfm("api", "HelixChannelApi") -], HelixChannelApi); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/channelPoints/HelixChannelPointsApi.js -init_modules_watch_stub(); -init_performance2(); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/interfaces/endpoints/channelPoints.external.js -init_modules_watch_stub(); -init_performance2(); -function createCustomRewardsQuery(broadcaster, onlyManageable) { - return { - broadcaster_id: extractUserId(broadcaster), - only_manageable_rewards: onlyManageable?.toString() - }; -} -__name(createCustomRewardsQuery, "createCustomRewardsQuery"); -function createCustomRewardChangeQuery(broadcaster, rewardId) { - return { - broadcaster_id: extractUserId(broadcaster), - id: rewardId - }; -} -__name(createCustomRewardChangeQuery, "createCustomRewardChangeQuery"); -function createCustomRewardBody(data2) { - const result = { - title: data2.title, - cost: data2.cost, - prompt: data2.prompt, - background_color: data2.backgroundColor, - is_enabled: data2.isEnabled, - is_user_input_required: data2.userInputRequired, - should_redemptions_skip_request_queue: data2.autoFulfill - }; - if (data2.maxRedemptionsPerStream !== void 0) { - result.is_max_per_stream_enabled = !!data2.maxRedemptionsPerStream; - result.max_per_stream = data2.maxRedemptionsPerStream ?? 0; - } - if (data2.maxRedemptionsPerUserPerStream !== void 0) { - result.is_max_per_user_per_stream_enabled = !!data2.maxRedemptionsPerUserPerStream; - result.max_per_user_per_stream = data2.maxRedemptionsPerUserPerStream ?? 0; - } - if (data2.globalCooldown !== void 0) { - result.is_global_cooldown_enabled = !!data2.globalCooldown; - result.global_cooldown_seconds = data2.globalCooldown ?? 0; - } - if ("isPaused" in data2) { - result.is_paused = data2.isPaused; - } - return result; -} -__name(createCustomRewardBody, "createCustomRewardBody"); -function createRewardRedemptionsByIdsQuery(broadcaster, rewardId, redemptionIds) { - return { - broadcaster_id: extractUserId(broadcaster), - reward_id: rewardId, - id: redemptionIds - }; -} -__name(createRewardRedemptionsByIdsQuery, "createRewardRedemptionsByIdsQuery"); -function createRedemptionsForBroadcasterQuery(broadcaster, rewardId, status, filter) { - return { - broadcaster_id: extractUserId(broadcaster), - reward_id: rewardId, - status, - sort: filter.newestFirst ? "NEWEST" : "OLDEST" - }; -} -__name(createRedemptionsForBroadcasterQuery, "createRedemptionsForBroadcasterQuery"); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/channelPoints/HelixCustomReward.js -init_modules_watch_stub(); -init_performance2(); -var HelixCustomReward = class HelixCustomReward2 extends DataObject { - static { - __name(this, "HelixCustomReward"); - } - /** @internal */ - _client; - /** @internal */ - constructor(data2, client) { - super(data2); - this._client = client; - } - /** - * The ID of the reward. - */ - get id() { - return this[rawDataSymbol].id; - } - /** - * The ID of the broadcaster the reward belongs to. - */ - get broadcasterId() { - return this[rawDataSymbol].broadcaster_id; - } - /** - * The name of the broadcaster the reward belongs to. - */ - get broadcasterName() { - return this[rawDataSymbol].broadcaster_login; - } - /** - * The display name of the broadcaster the reward belongs to. - */ - get broadcasterDisplayName() { - return this[rawDataSymbol].broadcaster_name; - } - /** - * Gets more information about the reward's broadcaster. - */ - async getBroadcaster() { - return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].broadcaster_id)); - } - /** - * Gets the URL of the image of the reward in the given scale. - * - * @param scale The scale of the image. - */ - getImageUrl(scale) { - const urlProp = `url_${scale}x`; - return this[rawDataSymbol].image?.[urlProp] ?? this[rawDataSymbol].default_image[urlProp]; - } - /** - * The background color of the reward. - */ - get backgroundColor() { - return this[rawDataSymbol].background_color; - } - /** - * Whether the reward is enabled (shown to users). - */ - get isEnabled() { - return this[rawDataSymbol].is_enabled; - } - /** - * The channel points cost of the reward. - */ - get cost() { - return this[rawDataSymbol].cost; - } - /** - * The title of the reward. - */ - get title() { - return this[rawDataSymbol].title; - } - /** - * The prompt shown to users when redeeming the reward. - */ - get prompt() { - return this[rawDataSymbol].prompt; - } - /** - * Whether the reward requires user input to be redeemed. - */ - get userInputRequired() { - return this[rawDataSymbol].is_user_input_required; - } - /** - * The maximum number of redemptions of the reward per stream. `null` means no limit. - */ - get maxRedemptionsPerStream() { - return this[rawDataSymbol].max_per_stream_setting.is_enabled ? this[rawDataSymbol].max_per_stream_setting.max_per_stream : null; - } - /** - * The maximum number of redemptions of the reward per stream for each user. `null` means no limit. - */ - get maxRedemptionsPerUserPerStream() { - return this[rawDataSymbol].max_per_user_per_stream_setting.is_enabled ? this[rawDataSymbol].max_per_user_per_stream_setting.max_per_user_per_stream : null; - } - /** - * The cooldown between two redemptions of the reward, in seconds. `null` means no cooldown. - */ - get globalCooldown() { - return this[rawDataSymbol].global_cooldown_setting.is_enabled ? this[rawDataSymbol].global_cooldown_setting.global_cooldown_seconds : null; - } - /** - * Whether the reward is paused. If true, users can't redeem it. - */ - get isPaused() { - return this[rawDataSymbol].is_paused; - } - /** - * Whether the reward is currently in stock. - */ - get isInStock() { - return this[rawDataSymbol].is_in_stock; - } - /** - * How often the reward was already redeemed this stream. - * - * Only available when the stream is live and `maxRedemptionsPerStream` is set. Otherwise, this is `null`. - */ - get redemptionsThisStream() { - return this[rawDataSymbol].redemptions_redeemed_current_stream; - } - /** - * Whether redemptions should automatically be marked as fulfilled. - */ - get autoFulfill() { - return this[rawDataSymbol].should_redemptions_skip_request_queue; - } - /** - * The time when the cooldown ends. `null` means there is currently no cooldown. - */ - get cooldownExpiryDate() { - return this[rawDataSymbol].cooldown_expires_at ? new Date(this[rawDataSymbol].cooldown_expires_at) : null; - } -}; -__decorate([ - Enumerable(false) -], HelixCustomReward.prototype, "_client", void 0); -HelixCustomReward = __decorate([ - rtfm("api", "HelixCustomReward", "id") -], HelixCustomReward); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/channelPoints/HelixCustomRewardRedemption.js -init_modules_watch_stub(); -init_performance2(); -var HelixCustomRewardRedemption = class HelixCustomRewardRedemption2 extends DataObject { - static { - __name(this, "HelixCustomRewardRedemption"); - } - /** @internal */ - _client; - /** @internal */ - constructor(data2, client) { - super(data2); - this._client = client; - } - /** - * The ID of the redemption. - */ - get id() { - return this[rawDataSymbol].id; - } - /** - * The ID of the broadcaster where the reward was redeemed. - */ - get broadcasterId() { - return this[rawDataSymbol].broadcaster_id; - } - /** - * The name of the broadcaster where the reward was redeemed. - */ - get broadcasterName() { - return this[rawDataSymbol].broadcaster_login; - } - /** - * The display name of the broadcaster where the reward was redeemed. - */ - get broadcasterDisplayName() { - return this[rawDataSymbol].broadcaster_name; - } - /** - * Gets more information about the broadcaster where the reward was redeemed. - */ - async getBroadcaster() { - return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].broadcaster_id)); - } - /** - * The ID of the user that redeemed the reward. - */ - get userId() { - return this[rawDataSymbol].user_id; - } - /** - * The name of the user that redeemed the reward. - */ - get userName() { - return this[rawDataSymbol].user_login; - } - /** - * The display name of the user that redeemed the reward. - */ - get userDisplayName() { - return this[rawDataSymbol].user_name; - } - /** - * Gets more information about the user that redeemed the reward. - */ - async getUser() { - return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].user_id)); - } - /** - * The text the user wrote when redeeming the reward. - */ - get userInput() { - return this[rawDataSymbol].user_input; - } - /** - * Whether the redemption was fulfilled. - */ - get isFulfilled() { - return this[rawDataSymbol].status === "FULFILLED"; - } - /** - * Whether the redemption was canceled. - */ - get isCanceled() { - return this[rawDataSymbol].status === "CANCELED"; - } - /** - * The date and time when the reward was redeemed. - */ - get redemptionDate() { - return new Date(this[rawDataSymbol].redeemed_at); - } - /** - * The ID of the reward that was redeemed. - */ - get rewardId() { - return this[rawDataSymbol].reward.id; - } - /** - * The title of the reward that was redeemed. - */ - get rewardTitle() { - return this[rawDataSymbol].reward.title; - } - /** - * The prompt of the reward that was redeemed. - */ - get rewardPrompt() { - return this[rawDataSymbol].reward.prompt; - } - /** - * The cost of the reward that was redeemed. - */ - get rewardCost() { - return this[rawDataSymbol].reward.cost; - } - /** - * Gets more information about the reward that was redeemed. - */ - async getReward() { - return checkRelationAssertion(await this._client.channelPoints.getCustomRewardById(this[rawDataSymbol].broadcaster_id, this[rawDataSymbol].reward.id)); - } - /** - * Updates the redemption's status. - * - * @param newStatus The status the redemption should have. - */ - async updateStatus(newStatus) { - const result = await this._client.channelPoints.updateRedemptionStatusByIds(this[rawDataSymbol].broadcaster_id, this[rawDataSymbol].reward.id, [this[rawDataSymbol].id], newStatus); - return result[0]; - } -}; -__decorate([ - Enumerable(false) -], HelixCustomRewardRedemption.prototype, "_client", void 0); -HelixCustomRewardRedemption = __decorate([ - rtfm("api", "HelixCustomRewardRedemption", "id") -], HelixCustomRewardRedemption); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/channelPoints/HelixChannelPointsApi.js -var HelixChannelPointsApi = class HelixChannelPointsApi2 extends BaseApi { - static { - __name(this, "HelixChannelPointsApi"); - } - /** - * Gets all custom rewards for the given broadcaster. - * - * @param broadcaster The broadcaster to get the rewards for. - * @param onlyManageable Whether to only get rewards that can be managed by the API. - */ - async getCustomRewards(broadcaster, onlyManageable) { - const result = await this._client.callApi({ - type: "helix", - url: "channel_points/custom_rewards", - userId: extractUserId(broadcaster), - scopes: ["channel:read:redemptions", "channel:manage:redemptions"], - query: createCustomRewardsQuery(broadcaster, onlyManageable) - }); - return result.data.map((data2) => new HelixCustomReward(data2, this._client)); - } - /** - * Gets custom rewards by IDs. - * - * @param broadcaster The broadcaster to get the rewards for. - * @param rewardIds The IDs of the rewards. - */ - async getCustomRewardsByIds(broadcaster, rewardIds) { - if (!rewardIds.length) { - return []; - } - const result = await this._client.callApi({ - type: "helix", - url: "channel_points/custom_rewards", - userId: extractUserId(broadcaster), - scopes: ["channel:read:redemptions", "channel:manage:redemptions"], - query: createGetByIdsQuery(broadcaster, rewardIds) - }); - return result.data.map((data2) => new HelixCustomReward(data2, this._client)); - } - /** - * Gets a custom reward by ID. - * - * @param broadcaster The broadcaster to get the reward for. - * @param rewardId The ID of the reward. - */ - async getCustomRewardById(broadcaster, rewardId) { - const rewards = await this.getCustomRewardsByIds(broadcaster, [rewardId]); - return rewards.length ? rewards[0] : null; - } - /** - * Creates a new custom reward. - * - * @param broadcaster The broadcaster to create the reward for. - * @param data The reward data. - * - * @expandParams - */ - async createCustomReward(broadcaster, data2) { - const result = await this._client.callApi({ - type: "helix", - url: "channel_points/custom_rewards", - method: "POST", - userId: extractUserId(broadcaster), - scopes: ["channel:manage:redemptions"], - query: createBroadcasterQuery(broadcaster), - jsonBody: createCustomRewardBody(data2) - }); - return new HelixCustomReward(result.data[0], this._client); - } - /** - * Updates a custom reward. - * - * @param broadcaster The broadcaster to update the reward for. - * @param rewardId The ID of the reward. - * @param data The reward data. - */ - async updateCustomReward(broadcaster, rewardId, data2) { - const result = await this._client.callApi({ - type: "helix", - url: "channel_points/custom_rewards", - method: "PATCH", - userId: extractUserId(broadcaster), - scopes: ["channel:manage:redemptions"], - query: createCustomRewardChangeQuery(broadcaster, rewardId), - jsonBody: createCustomRewardBody(data2) - }); - return new HelixCustomReward(result.data[0], this._client); - } - /** - * Deletes a custom reward. - * - * @param broadcaster The broadcaster to delete the reward for. - * @param rewardId The ID of the reward. - */ - async deleteCustomReward(broadcaster, rewardId) { - await this._client.callApi({ - type: "helix", - url: "channel_points/custom_rewards", - method: "DELETE", - userId: extractUserId(broadcaster), - scopes: ["channel:manage:redemptions"], - query: createCustomRewardChangeQuery(broadcaster, rewardId) - }); - } - /** - * Gets custom reward redemptions by IDs. - * - * @param broadcaster The broadcaster to get the redemptions for. - * @param rewardId The ID of the reward. - * @param redemptionIds The IDs of the redemptions. - */ - async getRedemptionsByIds(broadcaster, rewardId, redemptionIds) { - if (!redemptionIds.length) { - return []; - } - const result = await this._client.callApi({ - type: "helix", - url: "channel_points/custom_rewards/redemptions", - userId: extractUserId(broadcaster), - scopes: ["channel:read:redemptions", "channel:manage:redemptions"], - query: createRewardRedemptionsByIdsQuery(broadcaster, rewardId, redemptionIds) - }); - return result.data.map((data2) => new HelixCustomRewardRedemption(data2, this._client)); - } - /** - * Gets a custom reward redemption by ID. - * - * @param broadcaster The broadcaster to get the redemption for. - * @param rewardId The ID of the reward. - * @param redemptionId The ID of the redemption. - */ - async getRedemptionById(broadcaster, rewardId, redemptionId) { - const redemptions = await this.getRedemptionsByIds(broadcaster, rewardId, [redemptionId]); - return redemptions.length ? redemptions[0] : null; - } - /** - * Gets custom reward redemptions for the given broadcaster. - * - * @param broadcaster The broadcaster to get the redemptions for. - * @param rewardId The ID of the reward. - * @param status The status of the redemptions to get. - * @param filter - * - * @expandParams - */ - async getRedemptionsForBroadcaster(broadcaster, rewardId, status, filter) { - const result = await this._client.callApi({ - type: "helix", - url: "channel_points/custom_rewards/redemptions", - userId: extractUserId(broadcaster), - scopes: ["channel:read:redemptions", "channel:manage:redemptions"], - query: { - ...createRedemptionsForBroadcasterQuery(broadcaster, rewardId, status, filter), - ...createPaginationQuery(filter) - } - }); - return createPaginatedResult(result, HelixCustomRewardRedemption, this._client); - } - /** - * Creates a paginator for custom reward redemptions for the given broadcaster. - * - * @param broadcaster The broadcaster to get the redemptions for. - * @param rewardId The ID of the reward. - * @param status The status of the redemptions to get. - * @param filter - * - * @expandParams - */ - getRedemptionsForBroadcasterPaginated(broadcaster, rewardId, status, filter) { - return new HelixPaginatedRequest({ - url: "channel_points/custom_rewards/redemptions", - userId: extractUserId(broadcaster), - scopes: ["channel:read:redemptions", "channel:manage:redemptions"], - query: createRedemptionsForBroadcasterQuery(broadcaster, rewardId, status, filter) - }, this._client, (data2) => new HelixCustomRewardRedemption(data2, this._client), 50); - } - /** - * Updates the status of the given redemptions by IDs. - * - * @param broadcaster The broadcaster to update the redemptions for. - * @param rewardId The ID of the reward. - * @param redemptionIds The IDs of the redemptions to update. - * @param status The status to set for the redemptions. - */ - async updateRedemptionStatusByIds(broadcaster, rewardId, redemptionIds, status) { - if (!redemptionIds.length) { - return []; - } - const result = await this._client.callApi({ - type: "helix", - url: "channel_points/custom_rewards/redemptions", - method: "PATCH", - userId: extractUserId(broadcaster), - scopes: ["channel:manage:redemptions"], - query: createRewardRedemptionsByIdsQuery(broadcaster, rewardId, redemptionIds), - jsonBody: { - status - } - }); - return result.data.map((data2) => new HelixCustomRewardRedemption(data2, this._client)); - } -}; -HelixChannelPointsApi = __decorate([ - rtfm("api", "HelixChannelPointsApi") -], HelixChannelPointsApi); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/charity/HelixCharityApi.js -init_modules_watch_stub(); -init_performance2(); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/charity/HelixCharityCampaign.js -init_modules_watch_stub(); -init_performance2(); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/charity/HelixCharityCampaignAmount.js -init_modules_watch_stub(); -init_performance2(); -var HelixCharityCampaignAmount = class HelixCharityCampaignAmount2 extends DataObject { - static { - __name(this, "HelixCharityCampaignAmount"); - } - /** - * The monetary amount. The amount is specified in the currency’s minor unit. - * For example, the minor units for USD is cents, so if the amount is $5.50 USD, `value` is set to 550. - */ - get value() { - return this[rawDataSymbol].value; - } - /** - * The number of decimal places used by the currency. For example, USD uses two decimal places. - * Use this number to translate `value` from minor units to major units by using the formula: - * - * `value / 10^decimalPlaces` - */ - get decimalPlaces() { - return this[rawDataSymbol].decimal_places; - } - /** - * The localized monetary amount based on the value and the decimal places of the currency. - * For example, the minor units for USD is cents which uses two decimal places, so if `value` is 550, `localizedValue` is set to 5.50. - */ - get localizedValue() { - return this.value / 10 ** this.decimalPlaces; - } - /** - * The ISO-4217 three-letter currency code that identifies the type of currency in `value`. - */ - get currency() { - return this[rawDataSymbol].currency; - } -}; -HelixCharityCampaignAmount = __decorate([ - rtfm("api", "HelixCharityCampaignAmount") -], HelixCharityCampaignAmount); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/charity/HelixCharityCampaign.js -var HelixCharityCampaign = class HelixCharityCampaign2 extends DataObject { - static { - __name(this, "HelixCharityCampaign"); - } - /** @internal */ - _client; - /** @internal */ - constructor(data2, client) { - super(data2); - this._client = client; - } - /** - * An ID that identifies the charity campaign. - */ - get id() { - return this[rawDataSymbol].id; - } - /** - * The ID of the broadcaster. - */ - get broadcasterId() { - return this[rawDataSymbol].broadcaster_id; - } - /** - * The name of the broadcaster. - */ - get broadcasterName() { - return this[rawDataSymbol].broadcaster_login; - } - /** - * The display name of the broadcaster. - */ - get broadcasterDisplayName() { - return this[rawDataSymbol].broadcaster_name; - } - /** - * Gets more information about the broadcaster. - */ - async getBroadcaster() { - return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].broadcaster_id)); - } - /** - * The name of the charity. - */ - get charityName() { - return this[rawDataSymbol].charity_name; - } - /** - * A description of the charity. - */ - get charityDescription() { - return this[rawDataSymbol].charity_description; - } - /** - * A URL to an image of the charity's logo. The image’s type is PNG and its size is 100px X 100px. - */ - get charityLogo() { - return this[rawDataSymbol].charity_logo; - } - /** - * A URL to the charity’s website. - */ - get charityWebsite() { - return this[rawDataSymbol].charity_website; - } - /** - * An object that contains the current amount of donations that the campaign has received. - */ - get currentAmount() { - return new HelixCharityCampaignAmount(this[rawDataSymbol].current_amount); - } - /** - * An object that contains the campaign’s target fundraising goal. - */ - get targetAmount() { - return new HelixCharityCampaignAmount(this[rawDataSymbol].target_amount); - } -}; -__decorate([ - Enumerable(false) -], HelixCharityCampaign.prototype, "_client", void 0); -HelixCharityCampaign = __decorate([ - rtfm("api", "HelixCharityCampaign", "id") -], HelixCharityCampaign); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/charity/HelixCharityCampaignDonation.js -init_modules_watch_stub(); -init_performance2(); -var HelixCharityCampaignDonation = class HelixCharityCampaignDonation2 extends DataObject { - static { - __name(this, "HelixCharityCampaignDonation"); - } - /** @internal */ - _client; - /** @internal */ - constructor(data2, client) { - super(data2); - this._client = client; - } - /** - * An ID that identifies the charity campaign. - */ - get campaignId() { - return this[rawDataSymbol].campaign_id; - } - /** - * The ID of the donating user. - */ - get donorId() { - return this[rawDataSymbol].user_id; - } - /** - * The name of the donating user. - */ - get donorName() { - return this[rawDataSymbol].user_login; - } - /** - * The display name of the donating user. - */ - get donorDisplayName() { - return this[rawDataSymbol].user_name; - } - /** - * Gets more information about the donating user. - */ - async getDonor() { - return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].user_id)); - } - /** - * An object that contains the amount of money that the user donated. - */ - get amount() { - return new HelixCharityCampaignAmount(this[rawDataSymbol].amount); - } -}; -__decorate([ - Enumerable(false) -], HelixCharityCampaignDonation.prototype, "_client", void 0); -HelixCharityCampaignDonation = __decorate([ - rtfm("api", "HelixCharityCampaignDonation") -], HelixCharityCampaignDonation); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/charity/HelixCharityApi.js -var HelixCharityApi = class HelixCharityApi2 extends BaseApi { - static { - __name(this, "HelixCharityApi"); - } - /** - * Gets information about the charity campaign that a broadcaster is running. - * Returns null if the specified broadcaster has no active charity campaign. - * - * @param broadcaster The broadcaster to get charity campaign information about. - */ - async getCharityCampaign(broadcaster) { - const response = await this._client.callApi({ - type: "helix", - url: "charity/campaigns", - method: "GET", - userId: extractUserId(broadcaster), - scopes: ["channel:read:charity"], - query: createBroadcasterQuery(broadcaster) - }); - return new HelixCharityCampaign(response.data[0], this._client); - } - /** - * Gets the list of donations that users have made to the broadcaster’s active charity campaign. - * - * @param broadcaster The broadcaster to get charity campaign donation information about. - * @param pagination - * - * @expandParams - */ - async getCharityCampaignDonations(broadcaster, pagination) { - const response = await this._client.callApi({ - type: "helix", - url: "charity/donations", - userId: extractUserId(broadcaster), - scopes: ["channel:read:charity"], - query: { - ...createBroadcasterQuery(broadcaster), - ...createPaginationQuery(pagination) - } - }); - return createPaginatedResult(response, HelixCharityCampaignDonation, this._client); - } -}; -HelixCharityApi = __decorate([ - rtfm("api", "HelixCharityApi") -], HelixCharityApi); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/chat/HelixChatApi.js -init_modules_watch_stub(); -init_performance2(); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/errors/ChatMessageDroppedError.js -init_modules_watch_stub(); -init_performance2(); -var ChatMessageDroppedError = class extends CustomError2 { - static { - __name(this, "ChatMessageDroppedError"); - } - _code; - constructor(broadcasterId, message, code) { - super(`Chat message to channel ${broadcasterId} dropped: ${message ?? "unknown reason"}`); - this._code = code; - } - get code() { - return this._code; - } -}; - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/interfaces/endpoints/chat.external.js -init_modules_watch_stub(); -init_performance2(); -function createChatSettingsUpdateBody(settings) { - return { - slow_mode: settings.slowModeEnabled, - slow_mode_wait_time: settings.slowModeDelay, - follower_mode: settings.followerOnlyModeEnabled, - follower_mode_duration: settings.followerOnlyModeDelay, - subscriber_mode: settings.subscriberOnlyModeEnabled, - emote_mode: settings.emoteOnlyModeEnabled, - unique_chat_mode: settings.uniqueChatModeEnabled, - non_moderator_chat_delay: settings.nonModeratorChatDelayEnabled, - non_moderator_chat_delay_duration: settings.nonModeratorChatDelay - }; -} -__name(createChatSettingsUpdateBody, "createChatSettingsUpdateBody"); -function createChatColorUpdateQuery(user, color) { - return { - user_id: extractUserId(user), - color - }; -} -__name(createChatColorUpdateQuery, "createChatColorUpdateQuery"); -function createShoutoutQuery(from, to, moderatorId) { - return { - from_broadcaster_id: extractUserId(from), - to_broadcaster_id: extractUserId(to), - moderator_id: moderatorId - }; -} -__name(createShoutoutQuery, "createShoutoutQuery"); -function createSendChatMessageQuery(broadcaster, sender) { - return { - broadcaster_id: broadcaster, - sender_id: sender - }; -} -__name(createSendChatMessageQuery, "createSendChatMessageQuery"); -function createSendChatMessageBody(message, params) { - return { - message, - reply_parent_message_id: params?.replyParentMessageId - }; -} -__name(createSendChatMessageBody, "createSendChatMessageBody"); -function createSendChatMessageAsAppBody(message, params) { - return { - message, - reply_parent_message_id: params?.replyParentMessageId, - for_source_only: params?.forSourceOnly - }; -} -__name(createSendChatMessageAsAppBody, "createSendChatMessageAsAppBody"); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/interfaces/endpoints/shared-chat-session.external.js -init_modules_watch_stub(); -init_performance2(); -function createSharedChatSessionQuery(broadcaster) { - return { - broadcaster_id: extractUserId(broadcaster) - }; -} -__name(createSharedChatSessionQuery, "createSharedChatSessionQuery"); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/chat/HelixChannelEmote.js -init_modules_watch_stub(); -init_performance2(); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/chat/HelixEmote.js -init_modules_watch_stub(); -init_performance2(); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/chat/HelixEmoteBase.js -init_modules_watch_stub(); -init_performance2(); -var HelixEmoteBase = class extends DataObject { - static { - __name(this, "HelixEmoteBase"); - } - /** - * The ID of the emote. - */ - get id() { - return this[rawDataSymbol].id; - } - /** - * The name of the emote. - */ - get name() { - return this[rawDataSymbol].name; - } - /** - * The formats that the emote is available in. - */ - get formats() { - return this[rawDataSymbol].format; - } - /** - * The scales that the emote is available in. - */ - get scales() { - return this[rawDataSymbol].scale; - } - /** - * The theme modes that the emote is available in. - */ - get themeModes() { - return this[rawDataSymbol].theme_mode; - } - /** - * Gets the URL of the emote image in static format at the given scale and theme mode, or null if a static emote image at that scale/theme mode doesn't exist. - * - * @param scale The scale of the image. - * @param themeMode The theme mode of the image, either `light` or `dark`. - */ - getStaticImageUrl(scale = "1.0", themeMode = "light") { - if (this[rawDataSymbol].format.includes("static") && this[rawDataSymbol].scale.includes(scale)) { - return this.getFormattedImageUrl(scale, "static", themeMode); - } - return null; - } - /** - * Gets the URL of the emote image in animated format at the given scale and theme mode, or null if an animated emote image at that scale/theme mode doesn't exist. - * - * @param scale The scale of the image. - * @param themeMode The theme mode of the image, either `light` or `dark`. - */ - getAnimatedImageUrl(scale = "1.0", themeMode = "light") { - if (this[rawDataSymbol].format.includes("animated") && this[rawDataSymbol].scale.includes(scale)) { - return this.getFormattedImageUrl(scale, "animated", themeMode); - } - return null; - } - /** - * Gets the URL of the emote image in the given scale, format, and theme mode. - * - * @param scale The scale of the image, either `1.0` (small), `2.0` (medium), or `3.0` (large). - * @param format The format of the image, either `static` or `animated`. - * @param themeMode The theme mode of the image, either `light` or `dark`. - */ - getFormattedImageUrl(scale = "1.0", format = "static", themeMode = "light") { - return `https://static-cdn.jtvnw.net/emoticons/v2/${this[rawDataSymbol].id}/${format}/${themeMode}/${scale}`; - } -}; - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/chat/HelixEmote.js -var HelixEmote = class HelixEmote2 extends HelixEmoteBase { - static { - __name(this, "HelixEmote"); - } - /** - * Gets the URL of the emote image in the given scale. - * - * @param scale The scale of the image. - */ - getImageUrl(scale) { - return this[rawDataSymbol].images[`url_${scale}x`]; - } -}; -HelixEmote = __decorate([ - rtfm("api", "HelixEmote", "id") -], HelixEmote); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/chat/HelixChannelEmote.js -var HelixChannelEmote = class HelixChannelEmote2 extends HelixEmote { - static { - __name(this, "HelixChannelEmote"); - } - /** @internal */ - _client; - constructor(data2, client) { - super(data2); - this._client = client; - } - /** - * The subscription tier necessary to unlock the emote, or null if the emote is not a subscription emote. - */ - get tier() { - return this[rawDataSymbol].tier || null; - } - /** - * The type of the emote. - * - * There are many types of emotes that Twitch seems to arbitrarily assign. Do not rely on this value. - */ - get type() { - return this[rawDataSymbol].emote_type; - } - /** - * The ID of the emote set the emote is part of. - */ - get emoteSetId() { - return this[rawDataSymbol].emote_set_id; - } - /** - * Gets all emotes from the emote's set. - */ - async getAllEmotesFromSet() { - return await this._client.chat.getEmotesFromSets([this[rawDataSymbol].emote_set_id]); - } -}; -__decorate([ - Enumerable(false) -], HelixChannelEmote.prototype, "_client", void 0); -HelixChannelEmote = __decorate([ - rtfm("api", "HelixChannelEmote", "id") -], HelixChannelEmote); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/chat/HelixChatBadgeSet.js -init_modules_watch_stub(); -init_performance2(); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/chat/HelixChatBadgeVersion.js -init_modules_watch_stub(); -init_performance2(); -var HelixChatBadgeVersion = class HelixChatBadgeVersion2 extends DataObject { - static { - __name(this, "HelixChatBadgeVersion"); - } - /** - * The badge version ID. - */ - get id() { - return this[rawDataSymbol].id; - } - /** - * Gets an image URL for the given scale. - * - * @param scale The scale of the badge image. - */ - getImageUrl(scale) { - return this[rawDataSymbol][`image_url_${scale}x`]; - } - /** - * The title of the badge. - */ - get title() { - return this[rawDataSymbol].title; - } - /** - * The description of the badge. - */ - get description() { - return this[rawDataSymbol].description; - } - /** - * The action to take when clicking on the badge. Set to `null` if no action is specified. - */ - get clickAction() { - return this[rawDataSymbol].click_action; - } - /** - * The URL to navigate to when clicking on the badge. Set to `null` if no URL is specified. - */ - get clickUrl() { - return this[rawDataSymbol].click_url; - } -}; -HelixChatBadgeVersion = __decorate([ - rtfm("api", "HelixChatBadgeVersion", "id") -], HelixChatBadgeVersion); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/chat/HelixChatBadgeSet.js -var HelixChatBadgeSet = class HelixChatBadgeSet2 extends DataObject { - static { - __name(this, "HelixChatBadgeSet"); - } - /** - * The badge set ID. - */ - get id() { - return this[rawDataSymbol].set_id; - } - /** - * All versions of the badge. - */ - get versions() { - return this[rawDataSymbol].versions.map((data2) => new HelixChatBadgeVersion(data2)); - } - /** - * Gets a specific version of the badge. - * - * @param versionId The ID of the version. - */ - getVersion(versionId) { - return this.versions.find((v) => v.id === versionId) ?? null; - } -}; -__decorate([ - CachedGetter() -], HelixChatBadgeSet.prototype, "versions", null); -HelixChatBadgeSet = __decorate([ - Cacheable, - rtfm("api", "HelixChatBadgeSet", "id") -], HelixChatBadgeSet); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/chat/HelixChatChatter.js -init_modules_watch_stub(); -init_performance2(); -var HelixChatChatter = class HelixChatChatter2 extends DataObject { - static { - __name(this, "HelixChatChatter"); - } - /** @internal */ - _client; - /** @internal */ - constructor(data2, client) { - super(data2); - this._client = client; - } - /** - * The ID of the user. - */ - get userId() { - return this[rawDataSymbol].user_id; - } - /** - * The name of the user. - */ - get userName() { - return this[rawDataSymbol].user_login; - } - /** - * The display name of the user. - */ - get userDisplayName() { - return this[rawDataSymbol].user_name; - } - /** - * Gets more information about the user. - */ - async getUser() { - return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].user_id)); - } -}; -__decorate([ - Enumerable(false) -], HelixChatChatter.prototype, "_client", void 0); -HelixChatChatter = __decorate([ - rtfm("api", "HelixChatChatter") -], HelixChatChatter); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/chat/HelixChatSettings.js -init_modules_watch_stub(); -init_performance2(); -var HelixChatSettings = class HelixChatSettings2 extends DataObject { - static { - __name(this, "HelixChatSettings"); - } - /** - * The ID of the broadcaster. - */ - get broadcasterId() { - return this[rawDataSymbol].broadcaster_id; - } - /** - * Whether slow mode is enabled. - */ - get slowModeEnabled() { - return this[rawDataSymbol].slow_mode; - } - /** - * The time to wait between messages in slow mode, in seconds. - * - * Is `null` if slow mode is not enabled. - */ - get slowModeDelay() { - return this[rawDataSymbol].slow_mode_wait_time; - } - /** - * Whether follower only mode is enabled. - */ - get followerOnlyModeEnabled() { - return this[rawDataSymbol].follower_mode; - } - /** - * The time after which users are able to send messages after following, in minutes. - * - * Is `null` if follower only mode is not enabled, - * but may also be `0` if you can send messages immediately after following. - */ - get followerOnlyModeDelay() { - return this[rawDataSymbol].follower_mode_duration; - } - /** - * Whether subscriber only mode is enabled. - */ - get subscriberOnlyModeEnabled() { - return this[rawDataSymbol].subscriber_mode; - } - /** - * Whether emote only mode is enabled. - */ - get emoteOnlyModeEnabled() { - return this[rawDataSymbol].emote_mode; - } - /** - * Whether unique chat mode is enabled. - */ - get uniqueChatModeEnabled() { - return this[rawDataSymbol].unique_chat_mode; - } -}; -HelixChatSettings = __decorate([ - rtfm("api", "HelixChatSettings", "broadcasterId") -], HelixChatSettings); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/chat/HelixEmoteFromSet.js -init_modules_watch_stub(); -init_performance2(); -var HelixEmoteFromSet = class HelixEmoteFromSet2 extends HelixEmote { - static { - __name(this, "HelixEmoteFromSet"); - } - /** @internal */ - _client; - constructor(data2, client) { - super(data2); - this._client = client; - } - /** - * The type of the emote. - * - * Known values are: `subscriptions`, `bitstier`, `follower`, `rewards`, `globals`, `smilies`, `prime`, `limitedtime`. - * - * This list may be non-exhaustive. - */ - get type() { - return this[rawDataSymbol].emote_type; - } - /** - * The ID of the emote set the emote is part of. - */ - get emoteSetId() { - return this[rawDataSymbol].emote_set_id; - } - /** - * The ID of the user that owns the emote, or null if the emote is not owned by a user. - */ - get ownerId() { - switch (this[rawDataSymbol].owner_id) { - case "0": - case "twitch": { - return null; - } - default: { - return this[rawDataSymbol].owner_id; - } - } - } - /** - * Gets more information about the user that owns the emote, or null if the emote is not owned by a user. - */ - async getOwner() { - switch (this[rawDataSymbol].owner_id) { - case "0": - case "twitch": { - return null; - } - default: { - return await this._client.users.getUserById(this[rawDataSymbol].owner_id); - } - } - } -}; -__decorate([ - Enumerable(false) -], HelixEmoteFromSet.prototype, "_client", void 0); -HelixEmoteFromSet = __decorate([ - rtfm("api", "HelixEmoteFromSet", "id") -], HelixEmoteFromSet); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/chat/HelixPrivilegedChatSettings.js -init_modules_watch_stub(); -init_performance2(); -var HelixPrivilegedChatSettings = class HelixPrivilegedChatSettings2 extends HelixChatSettings { - static { - __name(this, "HelixPrivilegedChatSettings"); - } - /** - * Whether non-moderator messages are delayed. - */ - get nonModeratorChatDelayEnabled() { - return this[rawDataSymbol].non_moderator_chat_delay; - } - /** - * The delay of non-moderator messages, in seconds. - * - * Is `null` if non-moderator message delay is disabled. - */ - get nonModeratorChatDelay() { - return this[rawDataSymbol].non_moderator_chat_delay_duration; - } -}; -HelixPrivilegedChatSettings = __decorate([ - rtfm("api", "HelixPrivilegedChatSettings", "broadcasterId") -], HelixPrivilegedChatSettings); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/chat/HelixSentChatMessage.js -init_modules_watch_stub(); -init_performance2(); -var HelixSentChatMessage = class HelixSentChatMessage2 extends DataObject { - static { - __name(this, "HelixSentChatMessage"); - } - /** - * The message ID of the sent message. - */ - get id() { - return this[rawDataSymbol].message_id; - } - /** - * If the message passed all checks and was sent. - */ - get isSent() { - return this[rawDataSymbol].is_sent; - } - /** - * The reason code for why the chat message was dropped, if dropped. - */ - get dropReasonCode() { - return this[rawDataSymbol].drop_reason?.code; - } - /** - * The reason message for why the chat message was dropped, if dropped. - */ - get dropReasonMessage() { - return this[rawDataSymbol].drop_reason?.message; - } -}; -HelixSentChatMessage = __decorate([ - rtfm("api", "HelixSentChatMessage", "id") -], HelixSentChatMessage); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/chat/HelixSharedChatSession.js -init_modules_watch_stub(); -init_performance2(); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/chat/HelixSharedChatSessionParticipant.js -init_modules_watch_stub(); -init_performance2(); -var HelixSharedChatSessionParticipant = class HelixSharedChatSessionParticipant2 extends DataObject { - static { - __name(this, "HelixSharedChatSessionParticipant"); - } - /** @internal */ - _client; - /** @internal */ - constructor(data2, client) { - super(data2); - this._client = client; - } - /** - * The ID of the participant broadcaster. - */ - get broadcasterId() { - return this[rawDataSymbol].broadcaster_id; - } - /** - * Gets information about the participant broadcaster. - */ - async getBroadcaster() { - return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].broadcaster_id)); - } -}; -__decorate([ - Enumerable(false) -], HelixSharedChatSessionParticipant.prototype, "_client", void 0); -HelixSharedChatSessionParticipant = __decorate([ - rtfm("api", "HelixSharedChatSessionParticipant", "broadcasterId") -], HelixSharedChatSessionParticipant); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/chat/HelixSharedChatSession.js -var HelixSharedChatSession = class HelixSharedChatSession2 extends DataObject { - static { - __name(this, "HelixSharedChatSession"); - } - /** @internal */ - _client; - /** @internal */ - constructor(data2, client) { - super(data2); - this._client = client; - } - /** - * The unique identifier for the shared chat session. - */ - get sessionId() { - return this[rawDataSymbol].session_id; - } - /** - * The ID of the host broadcaster. - */ - get hostBroadcasterId() { - return this[rawDataSymbol].host_broadcaster_id; - } - /** - * Gets information about the host broadcaster. - */ - async getHostBroadcaster() { - return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].host_broadcaster_id)); - } - /** - * The list of participants in the session. - */ - get participants() { - return this[rawDataSymbol].participants.map((data2) => new HelixSharedChatSessionParticipant(data2, this._client)); - } - /** - * The date for when the session was created. - */ - get createdDate() { - return new Date(this[rawDataSymbol].created_at); - } - /** - * The date for when the session was updated. - */ - get updatedDate() { - return new Date(this[rawDataSymbol].updated_at); - } -}; -__decorate([ - Enumerable(false) -], HelixSharedChatSession.prototype, "_client", void 0); -HelixSharedChatSession = __decorate([ - rtfm("api", "HelixSharedChatSession", "sessionId") -], HelixSharedChatSession); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/chat/HelixUserEmote.js -init_modules_watch_stub(); -init_performance2(); -var HelixUserEmote = class HelixUserEmote2 extends HelixEmoteBase { - static { - __name(this, "HelixUserEmote"); - } - /** @internal */ - _client; - constructor(data2, client) { - super(data2); - this._client = client; - } - /** - * The type of the emote. - * - * There are many types of emotes that Twitch seems to arbitrarily assign. - * Check the relevant values in the official documentation. - * - * @see https://dev.twitch.tv/docs/api/reference/#get-user-emotes - */ - get type() { - return this[rawDataSymbol].emote_type; - } - /** - * The ID that identifies the emote set that the emote belongs to, or `null` if the emote is not from any set. - */ - get emoteSetId() { - return this[rawDataSymbol].emote_set_id || null; - } - /** - * The ID of the broadcaster who owns the emote, or `null` if the emote has no owner, e.g. it's a global emote. - */ - get ownerId() { - return this[rawDataSymbol].owner_id || null; - } - /** - * Gets all emotes from the emotes set, or `null` if emote is not from any set. - */ - async getAllEmotesFromSet() { - return this[rawDataSymbol].emote_set_id ? await this._client.chat.getEmotesFromSets([this[rawDataSymbol].emote_set_id]) : null; - } - /** - * Gets more information about the user that owns the emote, or `null` if the emote is not owned by a user. - */ - async getOwner() { - return this[rawDataSymbol].owner_id ? await this._client.users.getUserById(this[rawDataSymbol].owner_id) : null; - } -}; -__decorate([ - Enumerable(false) -], HelixUserEmote.prototype, "_client", void 0); -HelixUserEmote = __decorate([ - rtfm("api", "HelixUserEmote", "id") -], HelixUserEmote); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/chat/HelixChatApi.js -var HelixChatApi = class HelixChatApi2 extends BaseApi { - static { - __name(this, "HelixChatApi"); - } - /** - * Gets the list of users that are connected to the broadcaster’s chat session. - * - * This uses the token of the broadcaster by default. - * If you want to execute this in the context of another user (who has to be moderator of the channel) - * you can do so using [user context overrides](/docs/auth/concepts/context-switching). - * - * @param broadcaster The broadcaster whose list of chatters you want to get. - * @param pagination - * - * @expandParams - */ - async getChatters(broadcaster, pagination) { - const broadcasterId = extractUserId(broadcaster); - const result = await this._client.callApi({ - type: "helix", - url: "chat/chatters", - userId: broadcasterId, - canOverrideScopedUserContext: true, - scopes: ["moderator:read:chatters"], - query: { - ...this._createModeratorActionQuery(broadcasterId), - ...createPaginationQuery(pagination) - } - }); - return createPaginatedResultWithTotal(result, HelixChatChatter, this._client); - } - /** - * Creates a paginator for users that are connected to the broadcaster’s chat session. - * - * This uses the token of the broadcaster by default. - * If you want to execute this in the context of another user (who has to be moderator of the channel) - * you can do so using [user context overrides](/docs/auth/concepts/context-switching). - * - * @param broadcaster The broadcaster whose list of chatters you want to get. - * - * @expandParams - */ - getChattersPaginated(broadcaster) { - const broadcasterId = extractUserId(broadcaster); - return new HelixPaginatedRequestWithTotal({ - url: "chat/chatters", - userId: broadcasterId, - canOverrideScopedUserContext: true, - scopes: ["moderator:read:chatters"], - query: this._createModeratorActionQuery(broadcasterId) - }, this._client, (data2) => new HelixChatChatter(data2, this._client), 1e3); - } - /** - * Gets all global badges. - */ - async getGlobalBadges() { - const result = await this._client.callApi({ - type: "helix", - url: "chat/badges/global" - }); - return result.data.map((data2) => new HelixChatBadgeSet(data2)); - } - /** - * Gets all badges specific to the given broadcaster. - * - * @param broadcaster The broadcaster to get badges for. - */ - async getChannelBadges(broadcaster) { - const result = await this._client.callApi({ - type: "helix", - url: "chat/badges", - userId: extractUserId(broadcaster), - query: createBroadcasterQuery(broadcaster) - }); - return result.data.map((data2) => new HelixChatBadgeSet(data2)); - } - /** - * Gets all global emotes. - */ - async getGlobalEmotes() { - const result = await this._client.callApi({ - type: "helix", - url: "chat/emotes/global" - }); - return result.data.map((data2) => new HelixEmote(data2)); - } - /** - * Gets all emotes specific to the given broadcaster. - * - * @param broadcaster The broadcaster to get emotes for. - */ - async getChannelEmotes(broadcaster) { - const result = await this._client.callApi({ - type: "helix", - url: "chat/emotes", - userId: extractUserId(broadcaster), - query: createBroadcasterQuery(broadcaster) - }); - return result.data.map((data2) => new HelixChannelEmote(data2, this._client)); - } - /** - * Gets all emotes from a list of emote sets. - * - * @param setIds The IDs of the emote sets to get emotes from. - */ - async getEmotesFromSets(setIds) { - const result = await this._client.callApi({ - type: "helix", - url: "chat/emotes/set", - query: createSingleKeyQuery("emote_set_id", setIds) - }); - return result.data.map((data2) => new HelixEmoteFromSet(data2, this._client)); - } - /** - * Gets emotes available to the user across all channels. - * - * @param user The ID of the user to get available emotes of. - * @param filter Additional query filters. - */ - async getUserEmotes(user, filter) { - const userId = extractUserId(user); - const result = await this._client.callApi({ - type: "helix", - url: "chat/emotes/user", - userId: extractUserId(user), - scopes: ["user:read:emotes"], - query: { - ...createSingleKeyQuery("user_id", userId), - ...createSingleKeyQuery("broadcasterId", filter?.broadcaster ? extractUserId(filter.broadcaster) : void 0), - ...createPaginationQuery(filter) - } - }); - return createPaginatedResult(result, HelixUserEmote, this._client); - } - /** - * Creates a paginator for emotes available to the user across all channels. - * - * @param user The ID of the user to get available emotes of. - * @param broadcaster The ID of a broadcaster you wish to get follower emotes of. Using this query parameter will - * guarantee inclusion of the broadcaster’s follower emotes in the response body. - * - * If the user who retrieves their emotes is subscribed to the broadcaster specified, their follower emotes will - * appear in the response body regardless of whether this query parameter is used. - */ - getUserEmotesPaginated(user, broadcaster) { - const userId = extractUserId(user); - return new HelixPaginatedRequest({ - url: "chat/emotes/user", - userId, - scopes: ["user:read:emotes"], - query: { - ...createSingleKeyQuery("user_id", userId), - ...createSingleKeyQuery("broadcasterId", broadcaster ? extractUserId(broadcaster) : void 0) - } - }, this._client, (data2) => new HelixUserEmote(data2, this._client)); - } - /** - * Gets the settings of a broadcaster's chat. - * - * @param broadcaster The broadcaster the chat belongs to. - */ - async getSettings(broadcaster) { - const result = await this._client.callApi({ - type: "helix", - url: "chat/settings", - userId: extractUserId(broadcaster), - query: createBroadcasterQuery(broadcaster) - }); - return new HelixChatSettings(result.data[0]); - } - /** - * Gets the settings of a broadcaster's chat, including the delay settings. - * - * This uses the token of the broadcaster by default. - * If you want to execute this in the context of another user (who has to be moderator of the channel) - * you can do so using [user context overrides](/docs/auth/concepts/context-switching). - * - * @param broadcaster The broadcaster the chat belongs to. - */ - async getSettingsPrivileged(broadcaster) { - const broadcasterId = extractUserId(broadcaster); - const result = await this._client.callApi({ - type: "helix", - url: "chat/settings", - userId: broadcasterId, - canOverrideScopedUserContext: true, - scopes: ["moderator:read:chat_settings"], - query: this._createModeratorActionQuery(broadcasterId) - }); - return new HelixPrivilegedChatSettings(result.data[0]); - } - /** - * Updates the settings of a broadcaster's chat. - * - * This uses the token of the broadcaster by default. - * If you want to execute this in the context of another user (who has to be moderator of the channel) - * you can do so using [user context overrides](/docs/auth/concepts/context-switching). - * - * @expandParams - * - * @param broadcaster The broadcaster the chat belongs to. - * @param settings The settings to change. - */ - async updateSettings(broadcaster, settings) { - const broadcasterId = extractUserId(broadcaster); - const result = await this._client.callApi({ - type: "helix", - url: "chat/settings", - method: "PATCH", - userId: broadcasterId, - canOverrideScopedUserContext: true, - scopes: ["moderator:manage:chat_settings"], - query: this._createModeratorActionQuery(broadcasterId), - jsonBody: createChatSettingsUpdateBody(settings) - }); - return new HelixPrivilegedChatSettings(result.data[0]); - } - /** - * Sends a chat message to a broadcaster's chat. - * - * This uses the token of the broadcaster by default. - * If you want to execute this in the context of another user - * you can do so using [user context overrides](/docs/auth/concepts/context-switching). - * - * @expandParams - * - * @param broadcaster The broadcaster the chat belongs to. - * @param message The message to send. - * @param params - */ - async sendChatMessage(broadcaster, message, params) { - const broadcasterId = extractUserId(broadcaster); - const result = await this._client.callApi({ - type: "helix", - url: "chat/messages", - method: "POST", - userId: broadcasterId, - canOverrideScopedUserContext: true, - scopes: ["user:write:chat"], - query: createSendChatMessageQuery(broadcasterId, this._getUserContextIdWithDefault(broadcasterId)), - jsonBody: createSendChatMessageBody(message, params) - }); - const msg = new HelixSentChatMessage(result.data[0]); - this._handleUnsentChatMessage(broadcasterId, msg); - return msg; - } - /** - * Sends a chat message to a broadcaster's chat, using an app token. - * - * This requires the scopes `user:write:chat` and `user:bot` for the `user` and `channel:bot` for the `broadcaster`. - * `channel:bot` is not required if the `user` has moderator privileges in the `broadcaster`'s channel. - * - * These scope requirements can not be checked by the library, so they are just assumed. - * Make sure to catch authorization errors yourself. - * - * @expandParams - * - * @param user The user to send the chat message from. - * @param broadcaster The broadcaster the chat belongs to. - * @param message The message to send. - * @param params - */ - async sendChatMessageAsApp(user, broadcaster, message, params) { - const userId = extractUserId(user); - const broadcasterId = extractUserId(broadcaster); - const result = await this._client.callApi({ - type: "helix", - url: "chat/messages", - method: "POST", - forceType: "app", - query: createSendChatMessageQuery(broadcasterId, userId), - jsonBody: createSendChatMessageAsAppBody(message, params) - }); - const msg = new HelixSentChatMessage(result.data[0]); - this._handleUnsentChatMessage(broadcasterId, msg); - return msg; - } - /** - * Sends an announcement to a broadcaster's chat. - * - * This uses the token of the broadcaster by default. - * If you want to execute this in the context of another user (who has to be moderator of the channel) - * you can do so using [user context overrides](/docs/auth/concepts/context-switching). - * - * @param broadcaster The broadcaster the chat belongs to. - * @param announcement The announcement to send. - */ - async sendAnnouncement(broadcaster, announcement) { - const broadcasterId = extractUserId(broadcaster); - await this._client.callApi({ - type: "helix", - url: "chat/announcements", - method: "POST", - userId: broadcasterId, - canOverrideScopedUserContext: true, - scopes: ["moderator:manage:announcements"], - query: this._createModeratorActionQuery(broadcasterId), - jsonBody: { - message: announcement.message, - color: announcement.color - } - }); - } - /** - * Gets the chat colors for a list of users. - * - * Returns a Map with user IDs as keys and their colors as values. - * The value is a color hex code, or `null` if the user did not set a color, - * and unknown users will not be present in the map. - * - * @param users The users to get the chat colors of. - */ - async getColorsForUsers(users) { - const response = await this._client.callApi({ - type: "helix", - url: "chat/color", - query: createSingleKeyQuery("user_id", users.map(extractUserId)) - }); - return new Map(response.data.map((data2) => [data2.user_id, data2.color || null])); - } - /** - * Gets the chat color for a user. - * - * Returns the color as hex code, `null` if the user did not set a color, or `undefined` if the user is unknown. - * - * @param user The user to get the chat color of. - */ - async getColorForUser(user) { - const response = await this._client.callApi({ - type: "helix", - url: "chat/color", - userId: extractUserId(user), - query: createSingleKeyQuery("user_id", extractUserId(user)) - }); - if (!response.data.length) { - return void 0; - } - return response.data[0].color || null; - } - /** - * Changes the chat color for a user. - * - * @param user The user to change the color of. - * @param color The color to set. - * - * Note that hex codes can only be used by users that have a Prime or Turbo subscription. - */ - async setColorForUser(user, color) { - await this._client.callApi({ - type: "helix", - url: "chat/color", - method: "PUT", - userId: extractUserId(user), - scopes: ["user:manage:chat_color"], - query: createChatColorUpdateQuery(user, color) - }); - } - /** - * Sends a shoutout to the specified broadcaster. - * The broadcaster may send a shoutout once every 2 minutes. They may send the same broadcaster a shoutout once every 60 minutes. - * - * This uses the token of the broadcaster by default. - * If you want to execute this in the context of another user (who has to be moderator of the channel) - * you can do so using [user context overrides](/docs/auth/concepts/context-switching). - * - * @param from The ID of the broadcaster that’s sending the shoutout. - * @param to The ID of the broadcaster that’s receiving the shoutout. - */ - async shoutoutUser(from, to) { - const fromId = extractUserId(from); - await this._client.callApi({ - type: "helix", - url: "chat/shoutouts", - method: "POST", - userId: fromId, - canOverrideScopedUserContext: true, - scopes: ["moderator:manage:shoutouts"], - query: createShoutoutQuery(from, to, this._getUserContextIdWithDefault(fromId)) - }); - } - /** - * Gets the active shared chat session for a channel. - * - * Returns `null` if there is no active shared chat session in the channel. - * - * @param broadcaster The broadcaster to get the active shared chat session for. - */ - async getSharedChatSession(broadcaster) { - const broadcasterId = extractUserId(broadcaster); - const response = await this._client.callApi({ - type: "helix", - url: "shared_chat/session", - userId: broadcasterId, - query: createSharedChatSessionQuery(broadcasterId) - }); - if (response.data.length === 0) { - return null; - } - return new HelixSharedChatSession(response.data[0], this._client); - } - _createModeratorActionQuery(broadcasterId) { - return createModeratorActionQuery(broadcasterId, this._getUserContextIdWithDefault(broadcasterId)); - } - _handleUnsentChatMessage(broadcasterId, msg) { - if (!msg.isSent) { - throw new ChatMessageDroppedError(broadcasterId, msg.dropReasonMessage, msg.dropReasonCode); - } - } -}; -HelixChatApi = __decorate([ - rtfm("api", "HelixChatApi") -], HelixChatApi); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/clip/HelixClipApi.js -init_modules_watch_stub(); -init_performance2(); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/interfaces/endpoints/clip.external.js -init_modules_watch_stub(); -init_performance2(); -function createClipCreateQuery(params) { - const { channel, createAfterDelay = false, title: title2, duration } = params; - return { - broadcaster_id: extractUserId(channel), - has_delay: createAfterDelay.toString(), - title: title2, - duration: duration?.toFixed(1) - }; -} -__name(createClipCreateQuery, "createClipCreateQuery"); -function createClipCreateFromVodQuery(params, editorId) { - const { channel, title: title2, duration, vodId, vodOffset } = params; - return { - broadcaster_id: extractUserId(channel), - editor_id: editorId, - title: title2, - duration: duration?.toFixed(1), - vod_id: vodId, - vod_offset: vodOffset.toString() - }; -} -__name(createClipCreateFromVodQuery, "createClipCreateFromVodQuery"); -function createClipQuery(params) { - const { filterType, ids, startDate, endDate, isFeatured } = params; - return { - [filterType]: ids, - started_at: startDate, - ended_at: endDate, - is_featured: isFeatured?.toString() - }; -} -__name(createClipQuery, "createClipQuery"); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/clip/HelixClip.js -init_modules_watch_stub(); -init_performance2(); -var HelixClip = class HelixClip2 extends DataObject { - static { - __name(this, "HelixClip"); - } - /** @internal */ - _client; - /** @internal */ - constructor(data2, client) { - super(data2); - this._client = client; - } - /** - * The clip ID. - */ - get id() { - return this[rawDataSymbol].id; - } - /** - * The URL of the clip. - */ - get url() { - return this[rawDataSymbol].url; - } - /** - * The embed URL of the clip. - */ - get embedUrl() { - return this[rawDataSymbol].embed_url; - } - /** - * The user ID of the broadcaster of the stream where the clip was created. - */ - get broadcasterId() { - return this[rawDataSymbol].broadcaster_id; - } - /** - * The display name of the broadcaster of the stream where the clip was created. - */ - get broadcasterDisplayName() { - return this[rawDataSymbol].broadcaster_name; - } - /** - * Gets information about the broadcaster of the stream where the clip was created. - */ - async getBroadcaster() { - return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].broadcaster_id)); - } - /** - * The user ID of the creator of the clip. - */ - get creatorId() { - return this[rawDataSymbol].creator_id; - } - /** - * The display name of the creator of the clip. - */ - get creatorDisplayName() { - return this[rawDataSymbol].creator_name; - } - /** - * Gets information about the creator of the clip. - */ - async getCreator() { - return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].creator_id)); - } - /** - * The ID of the video the clip is taken from. - */ - get videoId() { - return this[rawDataSymbol].video_id; - } - /** - * Gets information about the video the clip is taken from. - */ - async getVideo() { - return checkRelationAssertion(await this._client.videos.getVideoById(this[rawDataSymbol].video_id)); - } - /** - * The ID of the game that was being played when the clip was created. - */ - get gameId() { - return this[rawDataSymbol].game_id; - } - /** - * Gets information about the game that was being played when the clip was created. - */ - async getGame() { - return this[rawDataSymbol].game_id ? checkRelationAssertion(await this._client.games.getGameById(this[rawDataSymbol].game_id)) : null; - } - /** - * The language of the stream where the clip was created. - */ - get language() { - return this[rawDataSymbol].language; - } - /** - * The title of the clip. - */ - get title() { - return this[rawDataSymbol].title; - } - /** - * The number of views of the clip. - */ - get views() { - return this[rawDataSymbol].view_count; - } - /** - * The date when the clip was created. - */ - get creationDate() { - return new Date(this[rawDataSymbol].created_at); - } - /** - * The URL of the thumbnail of the clip. - */ - get thumbnailUrl() { - return this[rawDataSymbol].thumbnail_url; - } - /** - * The duration of the clip in seconds (up to 0.1 precision). - */ - get duration() { - return this[rawDataSymbol].duration; - } - /** - * The offset of the clip from the start of the corresponding VOD, in seconds. - * - * This may be null if there is no VOD or if the clip is created from a live broadcast, - * in which case it may take a few minutes to associate with the VOD. - */ - get vodOffset() { - return this[rawDataSymbol].vod_offset; - } - /** - * Whether the clip is featured. - */ - get isFeatured() { - return this[rawDataSymbol].is_featured; - } -}; -__decorate([ - Enumerable(false) -], HelixClip.prototype, "_client", void 0); -HelixClip = __decorate([ - rtfm("api", "HelixClip", "id") -], HelixClip); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/clip/HelixClipApi.js -var HelixClipApi = class HelixClipApi2 extends BaseApi { - static { - __name(this, "HelixClipApi"); - } - /** @internal */ - _getClipByIdBatcher = new HelixRequestBatcher({ - url: "clips" - }, "id", "id", this._client, (data2) => new HelixClip(data2, this._client)); - /** - * Gets clips for the specified broadcaster in descending order of views. - * - * @param broadcaster The broadcaster to fetch clips for. - * @param filter - * - * @expandParams - */ - async getClipsForBroadcaster(broadcaster, filter = {}) { - return await this._getClips({ - ...filter, - filterType: "broadcaster_id", - ids: extractUserId(broadcaster), - userId: extractUserId(broadcaster) - }); - } - /** - * Creates a paginator for clips for the specified broadcaster. - * - * @param broadcaster The broadcaster to fetch clips for. - * @param filter - * - * @expandParams - */ - getClipsForBroadcasterPaginated(broadcaster, filter = {}) { - return this._getClipsPaginated({ - ...filter, - filterType: "broadcaster_id", - ids: extractUserId(broadcaster), - userId: extractUserId(broadcaster) - }); - } - /** - * Gets clips for the specified game in descending order of views. - * - * @param gameId The game ID. - * @param filter - * - * @expandParams - */ - async getClipsForGame(gameId, filter = {}) { - return await this._getClips({ - ...filter, - filterType: "game_id", - ids: gameId - }); - } - /** - * Creates a paginator for clips for the specified game. - * - * @param gameId The game ID. - * @param filter - * - * @expandParams - */ - getClipsForGamePaginated(gameId, filter = {}) { - return this._getClipsPaginated({ - ...filter, - filterType: "game_id", - ids: gameId - }); - } - /** - * Gets the clips identified by the given IDs. - * - * @param ids The clip IDs. - */ - async getClipsByIds(ids) { - const result = await this._getClips({ - filterType: "id", - ids - }); - return result.data; - } - /** - * Gets the clip identified by the given ID. - * - * @param id The clip ID. - */ - async getClipById(id) { - const clips = await this.getClipsByIds([id]); - return clips.length ? clips[0] : null; - } - /** - * Gets the clip identified by the given ID, batching multiple calls into fewer requests as the API allows. - * - * @param id The clip ID. - */ - async getClipByIdBatched(id) { - return await this._getClipByIdBatcher.request(id); - } - /** - * Creates a clip of a running stream. - * - * Returns the ID of the clip. - * - * @param params - * @expandParams - */ - async createClip(params) { - const result = await this._client.callApi({ - type: "helix", - url: "clips", - method: "POST", - userId: extractUserId(params.channel), - scopes: ["clips:edit"], - canOverrideScopedUserContext: true, - query: createClipCreateQuery(params) - }); - return result.data[0].id; - } - /** - * Creates a clip of a VOD. - * - * Returns the ID of the clip. - * - * @param params - * @expandParams - */ - async createClipFromVod(params) { - const broadcasterId = extractUserId(params.channel); - const result = await this._client.callApi({ - type: "helix", - url: "videos/clips", - method: "POST", - userId: broadcasterId, - scopes: ["editor:manage:clips", "channel:manage:clips"], - canOverrideScopedUserContext: true, - query: createClipCreateFromVodQuery(params, this._getUserContextIdWithDefault(broadcasterId)) - }); - return result.data[0].id; - } - async _getClips(params) { - if (!params.ids.length) { - return { data: [] }; - } - const result = await this._client.callApi({ - type: "helix", - url: "clips", - userId: params.userId, - query: { - ...createClipQuery(params), - ...createPaginationQuery(params) - } - }); - return createPaginatedResult(result, HelixClip, this._client); - } - _getClipsPaginated(params) { - return new HelixPaginatedRequest({ - url: "clips", - userId: params.userId, - query: createClipQuery(params) - }, this._client, (data2) => new HelixClip(data2, this._client)); - } -}; -__decorate([ - Enumerable(false) -], HelixClipApi.prototype, "_getClipByIdBatcher", void 0); -HelixClipApi = __decorate([ - rtfm("api", "HelixClipApi") -], HelixClipApi); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/contentClassificationLabels/HelixContentClassificationLabelApi.js -init_modules_watch_stub(); -init_performance2(); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/contentClassificationLabels/HelixContentClassificationLabel.js -init_modules_watch_stub(); -init_performance2(); -var HelixContentClassificationLabel = class extends DataObject { - static { - __name(this, "HelixContentClassificationLabel"); - } - /** - * The ID of the content classification label. - */ - get id() { - return this[rawDataSymbol].id; - } - /** - * The name of the content classification label. - */ - get name() { - return this[rawDataSymbol].name; - } - /** - * The description of the content classification label. - */ - get description() { - return this[rawDataSymbol].description; - } -}; - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/contentClassificationLabels/HelixContentClassificationLabelApi.js -var HelixContentClassificationLabelApi = class HelixContentClassificationLabelApi2 extends BaseApi { - static { - __name(this, "HelixContentClassificationLabelApi"); - } - /** - * Fetches a list of all content classification labels. - * - * @param locale The locale for the content classification labels. - */ - async getAll(locale) { - const result = await this._client.callApi({ - url: "content_classification_labels", - query: { - locale - } - }); - return result.data.map((data2) => new HelixContentClassificationLabel(data2)); - } -}; -HelixContentClassificationLabelApi = __decorate([ - rtfm("api", "HelixContentClassificationLabelApi") -], HelixContentClassificationLabelApi); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/entitlements/HelixEntitlementApi.js -init_modules_watch_stub(); -init_performance2(); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/interfaces/endpoints/entitlement.external.js -init_modules_watch_stub(); -init_performance2(); -function createDropsEntitlementQuery(filters, alwaysApp) { - return { - user_id: alwaysApp ? mapOptional(filters.user, extractUserId) : void 0, - game_id: filters.gameId, - fulfillment_status: filters.fulfillmentStatus - }; -} -__name(createDropsEntitlementQuery, "createDropsEntitlementQuery"); -function createDropsEntitlementUpdateBody(ids, fulfillmentStatus) { - return { - fulfillment_status: fulfillmentStatus, - entitlement_ids: ids - }; -} -__name(createDropsEntitlementUpdateBody, "createDropsEntitlementUpdateBody"); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/entitlements/HelixDropsEntitlement.js -init_modules_watch_stub(); -init_performance2(); -var HelixDropsEntitlement = class HelixDropsEntitlement2 extends DataObject { - static { - __name(this, "HelixDropsEntitlement"); - } - /** @internal */ - _client; - /** @internal */ - constructor(data2, client) { - super(data2); - this._client = client; - } - /** - * The ID of the entitlement. - */ - get id() { - return this[rawDataSymbol].id; - } - /** - * The ID of the reward. - */ - get rewardId() { - return this[rawDataSymbol].benefit_id; - } - /** - * The date when the entitlement was granted. - */ - get grantDate() { - return new Date(this[rawDataSymbol].timestamp); - } - /** - * The ID of the entitled user. - */ - get userId() { - return this[rawDataSymbol].user_id; - } - /** - * Gets more information about the entitled user. - */ - async getUser() { - return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].user_id)); - } - /** - * The ID of the game the entitlement was granted for. - */ - get gameId() { - return this[rawDataSymbol].game_id; - } - /** - * Gets more information about the game the entitlement was granted for. - */ - async getGame() { - return checkRelationAssertion(await this._client.games.getGameById(this[rawDataSymbol].game_id)); - } - /** - * The fulfillment status of the entitlement. - */ - get fulfillmentStatus() { - return this[rawDataSymbol].fulfillment_status; - } - /** - * The date when the entitlement was last updated. - */ - get updateDate() { - return new Date(this[rawDataSymbol].last_updated); - } -}; -__decorate([ - Enumerable(false) -], HelixDropsEntitlement.prototype, "_client", void 0); -HelixDropsEntitlement = __decorate([ - rtfm("api", "HelixDropsEntitlement") -], HelixDropsEntitlement); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/entitlements/HelixEntitlementApi.js -var HelixEntitlementApi = class HelixEntitlementApi2 extends BaseApi { - static { - __name(this, "HelixEntitlementApi"); - } - /** @internal */ - _getDropsEntitlementByIdBatcher = new HelixRequestBatcher({ - url: "entitlements/drops" - }, "id", "id", this._client, (data2) => new HelixDropsEntitlement(data2, this._client)); - /** - * Gets the drops entitlements for the given filter. - * - * @expandParams - * - * @param filter - * @param alwaysApp Whether an app token should always be used, even if a user filter is given. - */ - async getDropsEntitlements(filter, alwaysApp = false) { - const response = await this._client.callApi({ - type: "helix", - url: "entitlements/drops", - userId: mapOptional(filter.user, extractUserId), - forceType: filter.user && alwaysApp ? "app" : void 0, - query: { - ...createDropsEntitlementQuery(filter, alwaysApp), - ...createPaginationQuery(filter) - } - }); - return createPaginatedResult(response, HelixDropsEntitlement, this._client); - } - /** - * Creates a paginator for drops entitlements for the given filter. - * - * @expandParams - * - * @param filter - * @param alwaysApp Whether an app token should always be used, even if a user filter is given. - */ - getDropsEntitlementsPaginated(filter, alwaysApp = false) { - return new HelixPaginatedRequest({ - url: "entitlements/drops", - userId: mapOptional(filter.user, extractUserId), - forceType: filter.user && alwaysApp ? "app" : void 0, - query: createDropsEntitlementQuery(filter, alwaysApp) - }, this._client, (data2) => new HelixDropsEntitlement(data2, this._client)); - } - /** - * Gets the drops entitlements for the given IDs. - * - * @param ids The IDs to fetch. - */ - async getDropsEntitlementsByIds(ids) { - const response = await this._client.callApi({ - type: "helix", - url: "entitlements/drops", - query: { - id: ids - } - }); - return response.data.map((data2) => new HelixDropsEntitlement(data2, this._client)); - } - /** - * Gets the drops entitlement for the given ID. - * - * @param id The ID to fetch. - */ - async getDropsEntitlementById(id) { - const result = await this.getDropsEntitlementsByIds([id]); - return result[0] ?? null; - } - /** - * Gets the drops entitlement for the given ID, batching multiple calls into fewer requests as the API allows. - * - * @param id The ID to fetch. - */ - async getDropsEntitlementByIdBatched(id) { - return await this._getDropsEntitlementByIdBatcher.request(id); - } - /** - * Updates the status of a list of drops entitlements. - * - * Returns a map that associates each given ID with its update status. - * - * @param ids The IDs of the entitlements. - * @param fulfillmentStatus The fulfillment status to set the entitlements to. - */ - async updateDropsEntitlements(ids, fulfillmentStatus) { - const response = await this._client.callApi({ - type: "helix", - url: "entitlements/drops", - method: "PATCH", - jsonBody: createDropsEntitlementUpdateBody(ids, fulfillmentStatus) - }); - return new Map(response.data.flatMap((entry) => entry.ids.map((id) => [id, entry.status]))); - } -}; -__decorate([ - Enumerable(false) -], HelixEntitlementApi.prototype, "_getDropsEntitlementByIdBatcher", void 0); -HelixEntitlementApi = __decorate([ - rtfm("api", "HelixEntitlementApi") -], HelixEntitlementApi); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/eventSub/HelixEventSubApi.js -init_modules_watch_stub(); -init_performance2(); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/interfaces/endpoints/eventSub.external.js -init_modules_watch_stub(); -init_performance2(); -function createEventSubBroadcasterCondition(broadcaster) { - return { - broadcaster_user_id: extractUserId(broadcaster) - }; -} -__name(createEventSubBroadcasterCondition, "createEventSubBroadcasterCondition"); -function createEventSubRewardCondition(broadcaster, rewardId) { - return { broadcaster_user_id: extractUserId(broadcaster), reward_id: rewardId }; -} -__name(createEventSubRewardCondition, "createEventSubRewardCondition"); -function createEventSubModeratorCondition(broadcasterId, moderatorId) { - return { - broadcaster_user_id: broadcasterId, - moderator_user_id: moderatorId - }; -} -__name(createEventSubModeratorCondition, "createEventSubModeratorCondition"); -function createEventSubUserCondition(broadcasterId, userId) { - return { - broadcaster_user_id: broadcasterId, - user_id: userId - }; -} -__name(createEventSubUserCondition, "createEventSubUserCondition"); -function createEventSubDropEntitlementGrantCondition(filter) { - return { - organization_id: filter.organizationId, - category_id: filter.categoryId, - campaign_id: filter.campaignId - }; -} -__name(createEventSubDropEntitlementGrantCondition, "createEventSubDropEntitlementGrantCondition"); -function createEventSubConduitCondition(conduitId, status) { - return { - conduit_id: conduitId, - status - }; -} -__name(createEventSubConduitCondition, "createEventSubConduitCondition"); -function createEventSubConduitUpdateCondition(conduitId, shardCount) { - return { - id: conduitId, - shard_count: shardCount.toString() - }; -} -__name(createEventSubConduitUpdateCondition, "createEventSubConduitUpdateCondition"); -function createEventSubConduitShardsUpdateCondition(conduitId, shards) { - return { - conduit_id: conduitId, - shards - }; -} -__name(createEventSubConduitShardsUpdateCondition, "createEventSubConduitShardsUpdateCondition"); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/eventSub/HelixEventSubSubscription.js -init_modules_watch_stub(); -init_performance2(); -var HelixEventSubSubscription = class HelixEventSubSubscription2 extends DataObject { - static { - __name(this, "HelixEventSubSubscription"); - } - /** @internal */ - _client; - /** @internal */ - constructor(data2, client) { - super(data2); - this._client = client; - } - /** - * The ID of the subscription. - */ - get id() { - return this[rawDataSymbol].id; - } - /** - * The status of the subscription. - */ - get status() { - return this[rawDataSymbol].status; - } - /** - * The event type that the subscription is listening to. - */ - get type() { - return this[rawDataSymbol].type; - } - /** - * The cost of the subscription. - */ - get cost() { - return this[rawDataSymbol].cost; - } - /** - * The condition of the subscription. - */ - get condition() { - return this[rawDataSymbol].condition; - } - /** - * The date and time of creation of the subscription. - */ - get creationDate() { - return new Date(this[rawDataSymbol].created_at); - } - /** - * The transport method of the subscription. - */ - get transportMethod() { - return this[rawDataSymbol].transport.method; - } - /** - * End the EventSub subscription. - */ - async unsubscribe() { - await this._client.eventSub.deleteSubscription(this[rawDataSymbol].id); - } - /** @private */ - get _transport() { - return this[rawDataSymbol].transport; - } - /** @private */ - set _status(status) { - this[rawDataSymbol].status = status; - } -}; -__decorate([ - Enumerable(false) -], HelixEventSubSubscription.prototype, "_client", void 0); -HelixEventSubSubscription = __decorate([ - rtfm("api", "HelixEventSubSubscription", "id") -], HelixEventSubSubscription); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/eventSub/HelixPaginatedEventSubSubscriptionsRequest.js -init_modules_watch_stub(); -init_performance2(); -var HelixPaginatedEventSubSubscriptionsRequest = class HelixPaginatedEventSubSubscriptionsRequest2 extends HelixPaginatedRequestWithTotal { - static { - __name(this, "HelixPaginatedEventSubSubscriptionsRequest"); - } - /** @internal */ - constructor(query, userId, client) { - super({ - url: "eventsub/subscriptions", - userId, - query - }, client, (data2) => new HelixEventSubSubscription(data2, client)); - } - /** - * Gets the total cost of EventSub subscriptions. - */ - async getTotalCost() { - const data2 = this._currentData ?? await this._fetchData({ query: { after: void 0 } }); - return data2.total_cost; - } - /** - * Gets the cost limit of EventSub subscriptions. - */ - async getMaxTotalCost() { - const data2 = this._currentData ?? await this._fetchData({ query: { after: void 0 } }); - return data2.max_total_cost; - } -}; -HelixPaginatedEventSubSubscriptionsRequest = __decorate([ - rtfm("api", "HelixPaginatedEventSubSubscriptionsRequest") -], HelixPaginatedEventSubSubscriptionsRequest); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/eventSub/HelixEventSubConduit.js -init_modules_watch_stub(); -init_performance2(); -var HelixEventSubConduit = class HelixEventSubConduit2 extends DataObject { - static { - __name(this, "HelixEventSubConduit"); - } - /** @internal */ - _client; - /** @internal */ - constructor(data2, client) { - super(data2); - this._client = client; - } - /** - * The ID of the conduit. - */ - get id() { - return this[rawDataSymbol].id; - } - /** - * The shard count of the conduit. - */ - get shardCount() { - return this[rawDataSymbol].shard_count; - } - /** - * Update the conduit. - * - * @param shardCount The new shard count. - */ - async update(shardCount) { - return await this._client.eventSub.updateConduit(this[rawDataSymbol].id, shardCount); - } - /** - * Delete the conduit. - */ - async delete() { - await this._client.eventSub.deleteConduit(this[rawDataSymbol].id); - } - /** - * Get the conduit shards. - */ - async getShards() { - return await this._client.eventSub.getConduitShards(this[rawDataSymbol].id); - } -}; -__decorate([ - Enumerable(false) -], HelixEventSubConduit.prototype, "_client", void 0); -HelixEventSubConduit = __decorate([ - rtfm("api", "HelixEventSubConduit") -], HelixEventSubConduit); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/eventSub/HelixEventSubConduitShard.js -init_modules_watch_stub(); -init_performance2(); -var HelixEventSubConduitShard = class HelixEventSubConduitShard2 extends DataObject { - static { - __name(this, "HelixEventSubConduitShard"); - } - /** - * The ID of the shard. - */ - get id() { - return this[rawDataSymbol].id; - } - /** - * The status of the shard. - */ - get status() { - return this[rawDataSymbol].status; - } - /** - * The transport method of the shard. - */ - get transportMethod() { - return this[rawDataSymbol].transport.method; - } -}; -HelixEventSubConduitShard = __decorate([ - rtfm("api", "HelixEventSubConduitShard") -], HelixEventSubConduitShard); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/eventSub/HelixEventSubApi.js -var HelixEventSubApi = class HelixEventSubApi2 extends BaseApi { - static { - __name(this, "HelixEventSubApi"); - } - /** - * Gets the current EventSub subscriptions for the current client. - * - * @param pagination - * - * @expandParams - */ - async getSubscriptions(pagination) { - const result = await this._client.callApi({ - type: "helix", - url: "eventsub/subscriptions", - query: createPaginationQuery(pagination) - }); - return { - ...createPaginatedResultWithTotal(result, HelixEventSubSubscription, this._client), - totalCost: result.total_cost, - maxTotalCost: result.max_total_cost - }; - } - /** - * Creates a paginator for the current EventSub subscriptions for the current client. - */ - getSubscriptionsPaginated() { - return new HelixPaginatedEventSubSubscriptionsRequest({}, void 0, this._client); - } - /** - * Gets the current EventSub subscriptions with the given status for the current client. - * - * @param status The status of the subscriptions to get. - * @param pagination - * - * @expandParams - */ - async getSubscriptionsForStatus(status, pagination) { - const result = await this._client.callApi({ - type: "helix", - url: "eventsub/subscriptions", - query: { - ...createPaginationQuery(pagination), - status - } - }); - return { - ...createPaginatedResultWithTotal(result, HelixEventSubSubscription, this._client), - totalCost: result.total_cost, - maxTotalCost: result.max_total_cost - }; - } - /** - * Creates a paginator for the current EventSub subscriptions with the given status for the current client. - * - * @param status The status of the subscriptions to get. - */ - getSubscriptionsForStatusPaginated(status) { - return new HelixPaginatedEventSubSubscriptionsRequest({ status }, void 0, this._client); - } - /** - * Gets the current EventSub subscriptions with the given type for the current client. - * - * @param type The type of the subscriptions to get. - * @param pagination - * - * @expandParams - */ - async getSubscriptionsForType(type, pagination) { - const result = await this._client.callApi({ - type: "helix", - url: "eventsub/subscriptions", - query: { - ...createPaginationQuery(pagination), - type - } - }); - return { - ...createPaginatedResultWithTotal(result, HelixEventSubSubscription, this._client), - totalCost: result.total_cost, - maxTotalCost: result.max_total_cost - }; - } - /** - * Creates a paginator for the current EventSub subscriptions with the given type for the current client. - * - * @param type The type of the subscriptions to get. - */ - getSubscriptionsForTypePaginated(type) { - return new HelixPaginatedEventSubSubscriptionsRequest({ type }, void 0, this._client); - } - /** - * Gets the current EventSub subscriptions for the current user and client. - * - * @param user The user to get subscriptions for. - * @param pagination - * - * @expandParams - */ - async getSubscriptionsForUser(user, pagination) { - const result = await this._client.callApi({ - type: "helix", - url: "eventsub/subscriptions", - userId: extractUserId(user), - query: { - ...createSingleKeyQuery("user_id", extractUserId(user)), - ...createPaginationQuery(pagination) - } - }); - return { - ...createPaginatedResultWithTotal(result, HelixEventSubSubscription, this._client), - totalCost: result.total_cost, - maxTotalCost: result.max_total_cost - }; - } - /** - * Creates a paginator for the current EventSub subscriptions with the given type for the current client. - * - * @param user The user to get subscriptions for. - */ - getSubscriptionsForUserPaginated(user) { - const userId = extractUserId(user); - return new HelixPaginatedEventSubSubscriptionsRequest(createSingleKeyQuery("user_id", userId), userId, this._client); - } - /** - * Sends an arbitrary request to subscribe to an event. - * - * You can only create WebHook transport subscriptions using app tokens - * and WebSocket transport subscriptions using user tokens. - * - * @param type The type of the event. - * @param version The version of the event. - * @param condition The condition of the subscription. - * @param transport The transport of the subscription. - * @param user The user to create the subscription in context of. - * @param requiredScopeSet The scope set required by the subscription. Will only be checked for applicable transports. - * @param canOverrideScopedUserContext Whether the auth user context can be overridden. - * @param isBatched Whether to enable batching for the subscription. Is only supported for select topics. - */ - async createSubscription(type, version3, condition, transport, user, requiredScopeSet, canOverrideScopedUserContext, isBatched) { - const usesAppAuth = transport.method === "webhook" || transport.method === "conduit"; - const scopes = usesAppAuth ? void 0 : requiredScopeSet; - if (!usesAppAuth && !user) { - throw new Error(`Transport ${transport.method} can only handle subscriptions with user context`); - } - const jsonBody = { - type, - version: version3, - condition, - transport - }; - if (isBatched) { - jsonBody.is_batching_enabled = true; - } - const result = await this._client.callApi({ - type: "helix", - url: "eventsub/subscriptions", - method: "POST", - scopes, - userId: mapOptional(user, extractUserId), - canOverrideScopedUserContext, - forceType: usesAppAuth ? "app" : "user", - jsonBody - }); - return new HelixEventSubSubscription(result.data[0], this._client); - } - /** - * Deletes a subscription. - * - * @param id The ID of the subscription. - */ - async deleteSubscription(id) { - await this._client.callApi({ - type: "helix", - url: "eventsub/subscriptions", - method: "DELETE", - query: { - id - } - }); - } - /** - * Deletes *all* subscriptions. - */ - async deleteAllSubscriptions() { - await this._deleteSubscriptionsWithCondition(); - } - /** - * Deletes all broken subscriptions, i.e. all that are not enabled or pending verification. - */ - async deleteBrokenSubscriptions() { - await this._deleteSubscriptionsWithCondition((sub) => sub.status !== "enabled" && sub.status !== "webhook_callback_verification_pending"); - } - /** - * Subscribe to events that represent a stream going live. - * - * @param broadcaster The broadcaster you want to listen to online events for. - * @param transport The transport options. - */ - async subscribeToStreamOnlineEvents(broadcaster, transport) { - return await this.createSubscription("stream.online", "1", createEventSubBroadcasterCondition(broadcaster), transport, broadcaster); - } - /** - * Subscribe to events that represent a stream going offline. - * - * @param broadcaster The broadcaster you want to listen to online events for. - * @param transport The transport options. - */ - async subscribeToStreamOfflineEvents(broadcaster, transport) { - return await this.createSubscription("stream.offline", "1", createEventSubBroadcasterCondition(broadcaster), transport, broadcaster); - } - /** - * Subscribe to events that represent a channel updating their metadata. - * - * @param broadcaster The broadcaster you want to listen to update events for. - * @param transport The transport options. - */ - async subscribeToChannelUpdateEvents(broadcaster, transport) { - return await this.createSubscription("channel.update", "2", createEventSubBroadcasterCondition(broadcaster), transport, broadcaster); - } - /** - * Subscribe to events that represent a user following a channel. - * - * @param broadcaster The broadcaster you want to listen to follow events for. - * @param transport The transport options. - */ - async subscribeToChannelFollowEvents(broadcaster, transport) { - const broadcasterId = extractUserId(broadcaster); - return await this.createSubscription("channel.follow", "2", createEventSubModeratorCondition(broadcasterId, this._getUserContextIdWithDefault(broadcasterId)), transport, broadcasterId, ["moderator:read:followers"], true); - } - /** - * Subscribe to events that represent a user subscribing to a channel. - * - * @param broadcaster The broadcaster you want to listen to subscribe events for. - * @param transport The transport options. - */ - async subscribeToChannelSubscriptionEvents(broadcaster, transport) { - return await this.createSubscription("channel.subscribe", "1", createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ["channel:read:subscriptions"]); - } - /** - * Subscribe to events that represent a user gifting another user a subscription to a channel. - * - * @param broadcaster The broadcaster you want to listen to subscription gift events for. - * @param transport The transport options. - */ - async subscribeToChannelSubscriptionGiftEvents(broadcaster, transport) { - return await this.createSubscription("channel.subscription.gift", "1", createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ["channel:read:subscriptions"]); - } - /** - * Subscribe to events that represent a user's subscription to a channel being announced. - * - * @param broadcaster The broadcaster you want to listen to subscription message events for. - * @param transport The transport options. - */ - async subscribeToChannelSubscriptionMessageEvents(broadcaster, transport) { - return await this.createSubscription("channel.subscription.message", "1", createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ["channel:read:subscriptions"]); - } - /** - * Subscribe to events that represent a user's subscription to a channel ending. - * - * @param broadcaster The broadcaster you want to listen to subscription end events for. - * @param transport The transport options. - */ - async subscribeToChannelSubscriptionEndEvents(broadcaster, transport) { - return await this.createSubscription("channel.subscription.end", "1", createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ["channel:read:subscriptions"]); - } - /** - * Subscribe to events that represent a user cheering bits to a channel. - * - * @param broadcaster The broadcaster you want to listen to cheer events for. - * @param transport The transport options. - */ - async subscribeToChannelCheerEvents(broadcaster, transport) { - return await this.createSubscription("channel.cheer", "1", createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ["bits:read"]); - } - /** - * Subscribe to events that represent a charity campaign starting in a channel. - * - * @param broadcaster The broadcaster you want to listen to charity donation events for. - * @param transport The transport options. - */ - async subscribeToChannelCharityCampaignStartEvents(broadcaster, transport) { - return await this.createSubscription("channel.charity_campaign.start", "1", createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ["channel:read:charity"]); - } - /** - * Subscribe to events that represent a charity campaign ending in a channel. - * - * @param broadcaster The broadcaster you want to listen to charity donation events for. - * @param transport The transport options. - */ - async subscribeToChannelCharityCampaignStopEvents(broadcaster, transport) { - return await this.createSubscription("channel.charity_campaign.stop", "1", createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ["channel:read:charity"]); - } - /** - * Subscribe to events that represent a user donating to a charity campaign in a channel. - * - * @param broadcaster The broadcaster you want to listen to charity donation events for. - * @param transport The transport options. - */ - async subscribeToChannelCharityDonationEvents(broadcaster, transport) { - return await this.createSubscription("channel.charity_campaign.donate", "1", createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ["channel:read:charity"]); - } - /** - * Subscribe to events that represent a charity campaign progressing in a channel. - * - * @param broadcaster The broadcaster you want to listen to charity donation events for. - * @param transport The transport options. - */ - async subscribeToChannelCharityCampaignProgressEvents(broadcaster, transport) { - return await this.createSubscription("channel.charity_campaign.progress", "1", createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ["channel:read:charity"]); - } - /** - * Subscribe to events that represent a user being banned in a channel. - * - * @param broadcaster The broadcaster you want to listen to ban events for. - * @param transport The transport options. - */ - async subscribeToChannelBanEvents(broadcaster, transport) { - return await this.createSubscription("channel.ban", "1", createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ["channel:moderate"]); - } - /** - * Subscribe to events that represent a user being unbanned in a channel. - * - * @param broadcaster The broadcaster you want to listen to unban events for. - * @param transport The transport options. - */ - async subscribeToChannelUnbanEvents(broadcaster, transport) { - return await this.createSubscription("channel.unban", "1", createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ["channel:moderate"]); - } - /** - * Subscribe to events that represent Shield Mode being activated in a channel. - * - * @param broadcaster The broadcaster you want to listen to Shield Mode activation events for. - * @param transport The transport options. - */ - async subscribeToChannelShieldModeBeginEvents(broadcaster, transport) { - const broadcasterId = extractUserId(broadcaster); - return await this.createSubscription("channel.shield_mode.begin", "1", createEventSubModeratorCondition(broadcasterId, this._getUserContextIdWithDefault(broadcasterId)), transport, broadcasterId, ["moderator:read:shield_mode", "moderator:manage:shield_mode"], true); - } - /** - * Subscribe to events that represent Shield Mode being deactivated in a channel. - * - * @param broadcaster The broadcaster you want to listen to Shield Mode deactivation events for. - * @param transport The transport options. - */ - async subscribeToChannelShieldModeEndEvents(broadcaster, transport) { - const broadcasterId = extractUserId(broadcaster); - return await this.createSubscription("channel.shield_mode.end", "1", createEventSubModeratorCondition(broadcasterId, this._getUserContextIdWithDefault(broadcasterId)), transport, broadcasterId, ["moderator:read:shield_mode", "moderator:manage:shield_mode"], true); - } - /** - * Subscribe to events that represent a moderator being added to a channel. - * - * @param broadcaster The broadcaster you want to listen for moderator add events for. - * @param transport The transport options. - */ - async subscribeToChannelModeratorAddEvents(broadcaster, transport) { - return await this.createSubscription("channel.moderator.add", "1", createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ["moderation:read"]); - } - /** - * Subscribe to events that represent a moderator being removed from a channel. - * - * @param broadcaster The broadcaster you want to listen for moderator remove events for. - * @param transport The transport options. - */ - async subscribeToChannelModeratorRemoveEvents(broadcaster, transport) { - return await this.createSubscription("channel.moderator.remove", "1", createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ["moderation:read"]); - } - /** - * Subscribe to events that represent a broadcaster raiding another broadcaster. - * - * @param broadcaster The broadcaster you want to listen to outgoing raid events for. - * @param transport The transport options. - */ - async subscribeToChannelRaidEventsFrom(broadcaster, transport) { - return await this.createSubscription("channel.raid", "1", createSingleKeyQuery("from_broadcaster_user_id", extractUserId(broadcaster)), transport, broadcaster); - } - /** - * Subscribe to events that represent a broadcaster being raided by another broadcaster. - * - * @param broadcaster The broadcaster you want to listen to incoming raid events for. - * @param transport The transport options. - */ - async subscribeToChannelRaidEventsTo(broadcaster, transport) { - return await this.createSubscription("channel.raid", "1", createSingleKeyQuery("to_broadcaster_user_id", extractUserId(broadcaster)), transport, broadcaster); - } - /** - * Subscribe to events that represent a Channel Points reward being added to a channel. - * - * @param broadcaster The broadcaster you want to listen to reward add events for. - * @param transport The transport options. - */ - async subscribeToChannelRewardAddEvents(broadcaster, transport) { - return await this.createSubscription("channel.channel_points_custom_reward.add", "1", createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ["channel:read:redemptions", "channel:manage:redemptions"]); - } - /** - * Subscribe to events that represent a Channel Points reward being updated in a channel. - * - * @param broadcaster The broadcaster you want to listen to reward update events for. - * @param transport The transport options. - */ - async subscribeToChannelRewardUpdateEvents(broadcaster, transport) { - return await this.createSubscription("channel.channel_points_custom_reward.update", "1", createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ["channel:read:redemptions", "channel:manage:redemptions"]); - } - /** - * Subscribe to events that represent a specific Channel Points reward being updated. - * - * @param broadcaster The broadcaster you want to listen to reward update events for. - * @param rewardId The ID of the reward you want to listen to update events for. - * @param transport The transport options. - */ - async subscribeToChannelRewardUpdateEventsForReward(broadcaster, rewardId, transport) { - return await this.createSubscription("channel.channel_points_custom_reward.update", "1", createEventSubRewardCondition(broadcaster, rewardId), transport, broadcaster, ["channel:read:redemptions", "channel:manage:redemptions"]); - } - /** - * Subscribe to events that represent a Channel Points reward being removed from a channel. - * - * @param broadcaster The broadcaster you want to listen to reward remove events for. - * @param transport The transport options. - */ - async subscribeToChannelRewardRemoveEvents(broadcaster, transport) { - return await this.createSubscription("channel.channel_points_custom_reward.remove", "1", createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ["channel:read:redemptions", "channel:manage:redemptions"]); - } - /** - * Subscribe to events that represent a specific Channel Points reward being removed from a channel. - * - * @param broadcaster The broadcaster you want to listen to reward remove events for. - * @param rewardId The ID of the reward you want to listen to remove events for. - * @param transport The transport options. - */ - async subscribeToChannelRewardRemoveEventsForReward(broadcaster, rewardId, transport) { - return await this.createSubscription("channel.channel_points_custom_reward.remove", "1", createEventSubRewardCondition(broadcaster, rewardId), transport, broadcaster, ["channel:read:redemptions", "channel:manage:redemptions"]); - } - /** - * Subscribe to events that represent a Channel Points reward being redeemed. - * - * @param broadcaster The broadcaster you want to listen to redemption events for. - * @param transport The transport options. - */ - async subscribeToChannelRedemptionAddEvents(broadcaster, transport) { - return await this.createSubscription("channel.channel_points_custom_reward_redemption.add", "1", createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ["channel:read:redemptions", "channel:manage:redemptions"]); - } - /** - * Subscribe to events that represent a specific Channel Points reward being redeemed. - * - * @param broadcaster The broadcaster you want to listen to redemption events for. - * @param rewardId The ID of the reward you want to listen to redemption events for. - * @param transport The transport options. - */ - async subscribeToChannelRedemptionAddEventsForReward(broadcaster, rewardId, transport) { - return await this.createSubscription("channel.channel_points_custom_reward_redemption.add", "1", createEventSubRewardCondition(broadcaster, rewardId), transport, broadcaster, ["channel:read:redemptions", "channel:manage:redemptions"]); - } - /** - * Subscribe to events that represent a Channel Points redemption being updated. - * - * @param broadcaster The broadcaster you want to listen to redemption update events for. - * @param transport The transport options. - */ - async subscribeToChannelRedemptionUpdateEvents(broadcaster, transport) { - return await this.createSubscription("channel.channel_points_custom_reward_redemption.update", "1", createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ["channel:read:redemptions", "channel:manage:redemptions"]); - } - /** - * Subscribe to events that represent a specific Channel Points reward's redemption being updated. - * - * @param broadcaster The broadcaster you want to listen to redemption update events for. - * @param rewardId The ID of the reward you want to listen to redemption updates for. - * @param transport The transport options. - */ - async subscribeToChannelRedemptionUpdateEventsForReward(broadcaster, rewardId, transport) { - return await this.createSubscription("channel.channel_points_custom_reward_redemption.update", "1", createEventSubRewardCondition(broadcaster, rewardId), transport, broadcaster, ["channel:read:redemptions", "channel:manage:redemptions"]); - } - /** - * Subscribe to events that represent a Channel Points automatic reward being redeemed. - * - * @param broadcaster The broadcaster you want to listen to automatic reward redemption events for. - * @param transport The transport options. - */ - async subscribeToChannelAutomaticRewardRedemptionAddEvents(broadcaster, transport) { - return await this.createSubscription("channel.channel_points_automatic_reward_redemption.add", "1", createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ["channel:read:redemptions", "channel:manage:redemptions"]); - } - /** - * Subscribe to events that represent a Channel Points automatic reward being redeemed. - * - * @param broadcaster The broadcaster you want to listen to automatic reward redemption events for. - * @param transport The transport options. - */ - async subscribeToChannelAutomaticRewardRedemptionAddV2Events(broadcaster, transport) { - return await this.createSubscription("channel.channel_points_automatic_reward_redemption.add", "2", createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ["channel:read:redemptions", "channel:manage:redemptions"]); - } - /** - * Subscribe to events that represent a poll starting in a channel. - * - * @param broadcaster The broadcaster you want to listen to poll begin events for. - * @param transport The transport options. - */ - async subscribeToChannelPollBeginEvents(broadcaster, transport) { - return await this.createSubscription("channel.poll.begin", "1", createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ["channel:read:polls", "channel:manage:polls"]); - } - /** - * Subscribe to events that represent a poll being voted on in a channel. - * - * @param broadcaster The broadcaster you want to listen to poll progress events for. - * @param transport The transport options. - */ - async subscribeToChannelPollProgressEvents(broadcaster, transport) { - return await this.createSubscription("channel.poll.progress", "1", createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ["channel:read:polls", "channel:manage:polls"]); - } - /** - * Subscribe to events that represent a poll ending in a channel. - * - * @param broadcaster The broadcaster you want to listen to poll end events for. - * @param transport The transport options. - */ - async subscribeToChannelPollEndEvents(broadcaster, transport) { - return await this.createSubscription("channel.poll.end", "1", createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ["channel:read:polls", "channel:manage:polls"]); - } - /** - * Subscribe to events that represent a prediction starting in a channel. - * - * @param broadcaster The broadcaster you want to listen to prediction begin events for. - * @param transport The transport options. - */ - async subscribeToChannelPredictionBeginEvents(broadcaster, transport) { - return await this.createSubscription("channel.prediction.begin", "1", createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ["channel:read:predictions", "channel:manage:predictions"]); - } - /** - * Subscribe to events that represent a prediction being voted on in a channel. - * - * @param broadcaster The broadcaster you want to listen to prediction preogress events for. - * @param transport The transport options. - */ - async subscribeToChannelPredictionProgressEvents(broadcaster, transport) { - return await this.createSubscription("channel.prediction.progress", "1", createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ["channel:read:predictions", "channel:manage:predictions"]); - } - /** - * Subscribe to events that represent a prediction being locked in a channel. - * - * @param broadcaster The broadcaster you want to listen to prediction lock events for. - * @param transport The transport options. - */ - async subscribeToChannelPredictionLockEvents(broadcaster, transport) { - return await this.createSubscription("channel.prediction.lock", "1", createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ["channel:read:predictions", "channel:manage:predictions"]); - } - /** - * Subscribe to events that represent a prediction ending in a channel. - * - * @param broadcaster The broadcaster you want to listen to prediction end events for. - * @param transport The transport options. - */ - async subscribeToChannelPredictionEndEvents(broadcaster, transport) { - return await this.createSubscription("channel.prediction.end", "1", createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ["channel:read:predictions", "channel:manage:predictions"]); - } - /** - * Subscribe to events that represent the beginning of a creator goal event in a channel. - * - * @param broadcaster The broadcaster you want to listen to goal begin events for. - * @param transport The transport options. - */ - async subscribeToChannelGoalBeginEvents(broadcaster, transport) { - return await this.createSubscription("channel.goal.begin", "1", createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ["channel:read:goals"]); - } - /** - * Subscribe to events that represent progress towards a creator goal. - * - * @param broadcaster The broadcaster for which you want to listen to goal progress events. - * @param transport The transport options. - */ - async subscribeToChannelGoalProgressEvents(broadcaster, transport) { - return await this.createSubscription("channel.goal.progress", "1", createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ["channel:read:goals"]); - } - /** - * Subscribe to events that represent the end of a creator goal event. - * - * @param broadcaster The broadcaster for which you want to listen to goal end events. - * @param transport The transport options. - */ - async subscribeToChannelGoalEndEvents(broadcaster, transport) { - return await this.createSubscription("channel.goal.end", "1", createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ["channel:read:goals"]); - } - /** - * Subscribe to events that represent the beginning of a Hype Train event in a channel. - * - * @param broadcaster The broadcaster you want to listen to Hype train begin events for. - * @param transport The transport options. - */ - async subscribeToChannelHypeTrainBeginEvents(broadcaster, transport) { - return await this.createSubscription("channel.hype_train.begin", "1", createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ["channel:read:hype_train"]); - } - /** - * Subscribe to events that represent progress towards the Hype Train goal. - * - * @param broadcaster The broadcaster for which you want to listen to Hype Train progress events. - * @param transport The transport options. - */ - async subscribeToChannelHypeTrainProgressEvents(broadcaster, transport) { - return await this.createSubscription("channel.hype_train.progress", "1", createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ["channel:read:hype_train"]); - } - /** - * Subscribe to events that represent the end of a Hype Train event. - * - * @param broadcaster The broadcaster for which you want to listen to Hype Train end events. - * @param transport The transport options. - */ - async subscribeToChannelHypeTrainEndEvents(broadcaster, transport) { - return await this.createSubscription("channel.hype_train.end", "1", createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ["channel:read:hype_train"]); - } - /** - * Subscribe to events that represent the beginning of a Hype Train event in a channel. - * - * @param broadcaster The broadcaster you want to listen to Hype train begin events for. - * @param transport The transport options. - */ - async subscribeToChannelHypeTrainBeginV2Events(broadcaster, transport) { - return await this.createSubscription("channel.hype_train.begin", "2", createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ["channel:read:hype_train"]); - } - /** - * Subscribe to events that represent progress towards the Hype Train goal. - * - * @param broadcaster The broadcaster for which you want to listen to Hype Train progress events. - * @param transport The transport options. - */ - async subscribeToChannelHypeTrainProgressV2Events(broadcaster, transport) { - return await this.createSubscription("channel.hype_train.progress", "2", createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ["channel:read:hype_train"]); - } - /** - * Subscribe to events that represent the end of a Hype Train event. - * - * @param broadcaster The broadcaster for which you want to listen to Hype Train end events. - * @param transport The transport options. - */ - async subscribeToChannelHypeTrainEndV2Events(broadcaster, transport) { - return await this.createSubscription("channel.hype_train.end", "2", createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ["channel:read:hype_train"]); - } - /** - * Subscribe to events that represent a broadcaster shouting out another broadcaster. - * - * @param broadcaster The broadcaster for which you want to listen to outgoing shoutout events. - * @param transport The transport options. - */ - async subscribeToChannelShoutoutCreateEvents(broadcaster, transport) { - const broadcasterId = extractUserId(broadcaster); - return await this.createSubscription("channel.shoutout.create", "1", createEventSubModeratorCondition(broadcasterId, this._getUserContextIdWithDefault(broadcasterId)), transport, broadcasterId, ["moderator:read:shoutouts", "moderator:manage:shoutouts"], true); - } - /** - * Subscribe to events that represent a broadcaster being shouting out by another broadcaster. - * - * @param broadcaster The broadcaster for which you want to listen to incoming shoutout events. - * @param transport The transport options. - */ - async subscribeToChannelShoutoutReceiveEvents(broadcaster, transport) { - const broadcasterId = extractUserId(broadcaster); - return await this.createSubscription("channel.shoutout.receive", "1", createEventSubModeratorCondition(broadcasterId, this._getUserContextIdWithDefault(broadcasterId)), transport, broadcasterId, ["moderator:read:shoutouts", "moderator:manage:shoutouts"], true); - } - /** - * Subscribe to events that represent an ad break beginning in a channel. - * - * @param broadcaster The broadcaster for which you want to listen to ad break begin events. - * @param transport The transport options. - */ - async subscribeToChannelAdBreakBeginEvents(broadcaster, transport) { - return await this.createSubscription("channel.ad_break.begin", "1", createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ["channel:read:ads"]); - } - /** - * Subscribe to events that represent a channel's chat being cleared. - * - * @param broadcaster The broadcaster for which you want to listen to chat clear events. - * @param transport The transport options. - */ - async subscribeToChannelChatClearEvents(broadcaster, transport) { - const broadcasterId = extractUserId(broadcaster); - return await this.createSubscription("channel.chat.clear", "1", createEventSubUserCondition(broadcasterId, this._getUserContextIdWithDefault(broadcasterId)), transport, broadcaster, ["user:read:chat"], true); - } - /** - * Subscribe to events that represent a user's chat messages being cleared in a channel. - * - * @param broadcaster The broadcaster for which you want to listen to user chat message clear events. - * @param transport The transport options. - */ - async subscribeToChannelChatClearUserMessagesEvents(broadcaster, transport) { - const broadcasterId = extractUserId(broadcaster); - return await this.createSubscription("channel.chat.clear_user_messages", "1", createEventSubUserCondition(broadcasterId, this._getUserContextIdWithDefault(broadcasterId)), transport, broadcaster, ["user:read:chat"], true); - } - /** - * Subscribe to events that represent a chat message being deleted in a channel. - * - * @param broadcaster The broadcaster for which you want to listen to chat message delete events. - * @param transport The transport options. - */ - async subscribeToChannelChatMessageDeleteEvents(broadcaster, transport) { - const broadcasterId = extractUserId(broadcaster); - return await this.createSubscription("channel.chat.message_delete", "1", createEventSubUserCondition(broadcasterId, this._getUserContextIdWithDefault(broadcasterId)), transport, broadcaster, ["user:read:chat"], true); - } - /** - * Subscribe to events that represent a chat notification in a channel. - * - * @param broadcaster The broadcaster for which you want to listen to chat notification events. - * @param transport The transport options. - */ - async subscribeToChannelChatNotificationEvents(broadcaster, transport) { - const broadcasterId = extractUserId(broadcaster); - return await this.createSubscription("channel.chat.notification", "1", createEventSubUserCondition(broadcasterId, this._getUserContextIdWithDefault(broadcasterId)), transport, broadcaster, ["user:read:chat"], true); - } - /** - * Subscribe to events that represent a chat message in a channel. - * - * @param broadcaster The broadcaster for which you want to listen to chat message events. - * @param transport The transport options. - */ - async subscribeToChannelChatMessageEvents(broadcaster, transport) { - const broadcasterId = extractUserId(broadcaster); - return await this.createSubscription("channel.chat.message", "1", createEventSubUserCondition(broadcasterId, this._getUserContextIdWithDefault(broadcasterId)), transport, broadcaster, ["user:read:chat"], true); - } - /** - * Subscribe to events that represent chat settings being updated in a channel. - * - * @param broadcaster The broadcaster for which you want to listen to chat settings update events. - * @param transport The transport options. - */ - async subscribeToChannelChatSettingsUpdateEvents(broadcaster, transport) { - const broadcasterId = extractUserId(broadcaster); - return await this.createSubscription("channel.chat_settings.update", "1", createEventSubUserCondition(broadcasterId, this._getUserContextIdWithDefault(broadcasterId)), transport, broadcaster, ["user:read:chat"], true); - } - /** - * Subscribe to events that represent a created unban requests in a channel. - * - * @param broadcaster The broadcaster for which you want to listen to unban requests. - * @param transport The transport options. - */ - async subscribeToChannelUnbanRequestCreateEvents(broadcaster, transport) { - const broadcasterId = extractUserId(broadcaster); - return await this.createSubscription("channel.unban_request.create", "1", createEventSubModeratorCondition(broadcasterId, this._getUserContextIdWithDefault(broadcasterId)), transport, broadcaster, ["moderator:read:unban_requests", "moderator:manage:unban_requests"], true); - } - /** - * Subscribe to events that represent a resolved unban requests in a channel. - * - * @param broadcaster The broadcaster for which you want to listen to unban requests. - * @param transport The transport options. - */ - async subscribeToChannelUnbanRequestResolveEvents(broadcaster, transport) { - const broadcasterId = extractUserId(broadcaster); - return await this.createSubscription("channel.unban_request.resolve", "1", createEventSubModeratorCondition(broadcasterId, this._getUserContextIdWithDefault(broadcasterId)), transport, broadcaster, ["moderator:read:unban_requests", "moderator:manage:unban_requests"], true); - } - /** - * Subscribe to events that represent a moderator performing an action on a channel. - * - * This requires the following scopes: - * - `moderator:read:blocked_terms` OR `moderator:manage:blocked_terms` - * - `moderator:read:chat_settings` OR `moderator:manage:chat_settings` - * - `moderator:read:unban_requests` OR `moderator:manage:unban_requests` - * - `moderator:read:banned_users` OR `moderator:manage:banned_users` - * - `moderator:read:chat_messages` OR `moderator:manage:chat_messages` - * - `moderator:read:warnings` OR `moderator:manage:warnings` - * - `moderator:read:moderators` - * - `moderator:read:vips` - * - * These scope requirements cannot be checked by the library, so they are just assumed. - * Make sure to catch authorization errors yourself. - * - * @param broadcaster The broadcaster for which you want to listen to moderation events. - * @param transport The transport options. - */ - async subscribeToChannelModerateEvents(broadcaster, transport) { - const broadcasterId = extractUserId(broadcaster); - return await this.createSubscription("channel.moderate", "2", createEventSubModeratorCondition(broadcasterId, this._getUserContextIdWithDefault(broadcasterId)), transport, broadcaster, [], true); - } - /** - * Subscribe to events that represent a warning being acknowledged by a user. - * - * @param broadcaster The broadcaster for whom you want to listen to warnings. - * @param transport The transport options. - */ - async subscribeToChannelWarningAcknowledgeEvents(broadcaster, transport) { - const broadcasterId = extractUserId(broadcaster); - return await this.createSubscription("channel.warning.acknowledge", "1", createEventSubModeratorCondition(broadcasterId, this._getUserContextIdWithDefault(broadcasterId)), transport, broadcaster, ["moderator:read:warnings", "moderator:manage:warnings"], true); - } - /** - * Subscribe to events that represent a warning sent to a user. - * - * @param broadcaster The broadcaster for whom you want to listen to warnings. - * @param transport The transport options. - */ - async subscribeToChannelWarningSendEvents(broadcaster, transport) { - const broadcasterId = extractUserId(broadcaster); - return await this.createSubscription("channel.warning.send", "1", createEventSubModeratorCondition(broadcasterId, this._getUserContextIdWithDefault(broadcasterId)), transport, broadcaster, ["moderator:read:warnings", "moderator:manage:warnings"], true); - } - /** - * Subscribe to events that represent a VIP being added to a channel. - * - * @param broadcaster The broadcaster you want to listen for VIP add events for. - * @param transport The transport options. - */ - async subscribeToChannelVipAddEvents(broadcaster, transport) { - return await this.createSubscription("channel.vip.add", "1", createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ["channel:read:vips", "channel:manage:vips"]); - } - /** - * Subscribe to events that represent a VIP being removed from a channel. - * - * @param broadcaster The broadcaster you want to listen for VIP remove events for. - * @param transport The transport options. - */ - async subscribeToChannelVipRemoveEvents(broadcaster, transport) { - return await this.createSubscription("channel.vip.remove", "1", createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ["channel:read:vips", "channel:manage:vips"]); - } - /** - * Subscribe to events that represent an extension Bits transaction. - * - * @param clientId The Client ID for the extension you want to listen to Bits transactions for. - * @param transport The transport options. - */ - async subscribeToExtensionBitsTransactionCreateEvents(clientId, transport) { - return await this.createSubscription("extension.bits_transaction.create", "1", createSingleKeyQuery("extension_client_id", clientId), transport); - } - /** - * Subscribe to events that represent a user granting authorization to an application. - * - * @param clientId The Client ID for the application you want to listen to authorization grant events for. - * @param transport The transport options. - */ - async subscribeToUserAuthorizationGrantEvents(clientId, transport) { - return await this.createSubscription("user.authorization.grant", "1", createSingleKeyQuery("client_id", clientId), transport); - } - /** - * Subscribe to events that represent a user revoking their authorization from an application. - * - * @param clientId The Client ID for the application you want to listen to authorization revoke events for. - * @param transport The transport options. - */ - async subscribeToUserAuthorizationRevokeEvents(clientId, transport) { - return await this.createSubscription("user.authorization.revoke", "1", createSingleKeyQuery("client_id", clientId), transport); - } - /** - * Subscribe to events that represent a user updating their account details. - * - * @param user The user you want to listen to user update events for. - * @param transport The transport options. - * @param withEmail Whether to request adding the email address of the user to the notification. - * - * Only has an effect with the websocket transport. - * With the webhook transport, this depends solely on the previous authorization given by the user. - */ - async subscribeToUserUpdateEvents(user, transport, withEmail) { - return await this.createSubscription("user.update", "1", createSingleKeyQuery("user_id", extractUserId(user)), transport, user, withEmail ? ["user:read:email"] : void 0); - } - /** - * Subscribe to events that represent a user receiving a whisper message from another user. - * - * @param user The user you want to listen to whisper message events for. - * @param transport The transport options. - */ - async subscribeToUserWhisperMessageEvents(user, transport) { - return await this.createSubscription("user.whisper.message", "1", createSingleKeyQuery("user_id", extractUserId(user)), transport, user, ["user:read:whispers", "user:manage:whispers"]); - } - /** - * Subscribe to events that represent a drop entitlement being granted. - * - * @expandParams - * - * @param filter - * @param transport The transport options. - */ - async subscribeToDropEntitlementGrantEvents(filter, transport) { - return await this.createSubscription("drop.entitlement.grant", "1", createEventSubDropEntitlementGrantCondition(filter), transport, void 0, void 0, false, true); - } - /** - * Subscribes to events that represent a chat message being held by AutoMod. - * - * @param broadcaster The broadcaster you want to listen to AutoMod message hold events for. - * @param transport The transport options. - */ - async subscribeToAutoModMessageHoldEvents(broadcaster, transport) { - const broadcasterId = extractUserId(broadcaster); - return await this.createSubscription("automod.message.hold", "1", createEventSubModeratorCondition(broadcasterId, this._getUserContextIdWithDefault(broadcasterId)), transport, broadcaster, ["moderator:manage:automod"], true); - } - /** - * Subscribes to events that represent a held chat message by AutoMod being resolved. - * - * @param broadcaster The broadcaster you want to listen to AutoMod message resolution events for. - * @param transport The transport options. - */ - async subscribeToAutoModMessageUpdateEvents(broadcaster, transport) { - const broadcasterId = extractUserId(broadcaster); - return await this.createSubscription("automod.message.update", "1", createEventSubModeratorCondition(broadcasterId, this._getUserContextIdWithDefault(broadcasterId)), transport, broadcaster, ["moderator:manage:automod"], true); - } - /** - * Subscribes to events (v2) that represent a chat message being held by AutoMod. - * - * @param broadcaster The broadcaster you want to listen to AutoMod message hold events for. - * @param transport The transport options. - */ - async subscribeToAutoModMessageHoldV2Events(broadcaster, transport) { - const broadcasterId = extractUserId(broadcaster); - return await this.createSubscription("automod.message.hold", "2", createEventSubModeratorCondition(broadcasterId, this._getUserContextIdWithDefault(broadcasterId)), transport, broadcaster, ["moderator:manage:automod"], true); - } - /** - * Subscribes to events (v2) that represent a held chat message by AutoMod being resolved. - * - * @param broadcaster The broadcaster you want to listen to AutoMod message resolution events for. - * @param transport The transport options. - */ - async subscribeToAutoModMessageUpdateV2Events(broadcaster, transport) { - const broadcasterId = extractUserId(broadcaster); - return await this.createSubscription("automod.message.update", "2", createEventSubModeratorCondition(broadcasterId, this._getUserContextIdWithDefault(broadcasterId)), transport, broadcaster, ["moderator:manage:automod"], true); - } - /** - * Subscribes to events that represent the AutoMod settings being updated. - * - * @param broadcaster The broadcaster you want to listen to AutoMod settings update events. - * @param transport The transport options. - */ - async subscribeToAutoModSettingsUpdateEvents(broadcaster, transport) { - const broadcasterId = extractUserId(broadcaster); - return await this.createSubscription("automod.settings.update", "1", createEventSubModeratorCondition(broadcasterId, this._getUserContextIdWithDefault(broadcasterId)), transport, broadcaster, ["moderator:read:automod_settings"], true); - } - /** - * Subscribes to events that represent the AutoMod terms being updated. - * - * @param broadcaster The broadcaster you want to listen to AutoMod terms update events. - * @param transport The transport options. - */ - async subscribeToAutoModTermsUpdateEvents(broadcaster, transport) { - const broadcasterId = extractUserId(broadcaster); - return await this.createSubscription("automod.terms.update", "1", createEventSubModeratorCondition(broadcasterId, this._getUserContextIdWithDefault(broadcasterId)), transport, broadcaster, ["moderator:manage:automod"], true); - } - /** - * Subscribes to events that represent a user's notification about their message being held by AutoMod. - * - * @param broadcaster The broadcaster you want to listen to AutoMod message hold events for. - * @param transport The transport options. - */ - async subscribeToChannelChatUserMessageHoldEvents(broadcaster, transport) { - const broadcasterId = extractUserId(broadcaster); - return await this.createSubscription("channel.chat.user_message_hold", "1", createEventSubUserCondition(broadcasterId, this._getUserContextIdWithDefault(broadcasterId)), transport, broadcaster, ["user:read:chat"], true); - } - /** - * Subscribes to events that represent a user's notification about a held chat message by AutoMod being resolved. - * - * @param broadcaster The broadcaster you want to listen to AutoMod message resolution events for. - * @param transport The transport options. - */ - async subscribeToChannelChatUserMessageUpdateEvents(broadcaster, transport) { - const broadcasterId = extractUserId(broadcaster); - return await this.createSubscription("channel.chat.user_message_update", "1", createEventSubUserCondition(broadcasterId, this._getUserContextIdWithDefault(broadcasterId)), transport, broadcaster, ["user:read:chat"], true); - } - /** - * Subscribes to events that represent a suspicious user updated in a channel. - * - * @param broadcaster The broadcaster you want to listen for suspicious user update events. - * @param transport The transport options. - */ - async subscribeToChannelSuspiciousUserUpdateEvents(broadcaster, transport) { - const broadcasterId = extractUserId(broadcaster); - return await this.createSubscription("channel.suspicious_user.update", "1", createEventSubModeratorCondition(broadcasterId, this._getUserContextIdWithDefault(broadcasterId)), transport, broadcaster, ["moderator:read:suspicious_users"], true); - } - /** - * Subscribes to events that represent a message sent by a suspicious user. - * - * @param broadcaster The broadcaster you want to listen for messages sent by suspicious users. - * @param transport The transport options. - */ - async subscribeToChannelSuspiciousUserMessageEvents(broadcaster, transport) { - const broadcasterId = extractUserId(broadcaster); - return await this.createSubscription("channel.suspicious_user.message", "1", createEventSubModeratorCondition(broadcasterId, this._getUserContextIdWithDefault(broadcasterId)), transport, broadcaster, ["moderator:read:suspicious_users"], true); - } - /** - * Subscribes to events indicating that a shared chat session has begun in a channel. - * - * @param broadcaster The broadcaster for whom shared chat session begin events should be listened to. - * @param transport The transport options to use for the subscription. - */ - async subscribeToChannelSharedChatSessionBeginEvents(broadcaster, transport) { - const broadcasterId = extractUserId(broadcaster); - return await this.createSubscription("channel.shared_chat.begin", "1", createEventSubBroadcasterCondition(broadcasterId), transport, broadcasterId); - } - /** - * Subscribes to events indicating that a shared chat session has been updated in a channel. - * - * @param broadcaster The broadcaster for whom shared chat session update events should be listened to. - * @param transport The transport options to use for the subscription. - */ - async subscribeToChannelSharedChatSessionUpdateEvents(broadcaster, transport) { - const broadcasterId = extractUserId(broadcaster); - return await this.createSubscription("channel.shared_chat.update", "1", createEventSubBroadcasterCondition(broadcasterId), transport, broadcasterId); - } - /** - * Subscribes to events indicating that a shared chat session has ended in a channel. - * - * @param broadcaster The broadcaster for whom shared chat session end events should be listened to. - * @param transport The transport options to use for the subscription. - */ - async subscribeToChannelSharedChatSessionEndEvents(broadcaster, transport) { - const broadcasterId = extractUserId(broadcaster); - return await this.createSubscription("channel.shared_chat.end", "1", createEventSubBroadcasterCondition(broadcasterId), transport, broadcasterId); - } - /** - * Subscribes to events indicating that bits are used in a channel. - * - * @param broadcaster The broadcaster for whom you want to listen to bits usage events. - * @param transport The transport options to use for the subscription. - */ - async subscribeToChannelBitsUseEvents(broadcaster, transport) { - const broadcasterId = extractUserId(broadcaster); - return await this.createSubscription("channel.bits.use", "1", createEventSubBroadcasterCondition(broadcasterId), transport, broadcasterId, ["bits:read"]); - } - /** - * Gets the current EventSub conduits for the current client. - * - */ - async getConduits() { - const result = await this._client.callApi({ - type: "helix", - url: "eventsub/conduits" - }); - return result.data.map((data2) => new HelixEventSubConduit(data2, this._client)); - } - /** - * Creates a new EventSub conduit for the current client. - * - * @param shardCount The number of shards to create for this conduit. - */ - async createConduit(shardCount) { - const result = await this._client.callApi({ - type: "helix", - url: "eventsub/conduits", - method: "POST", - query: { - ...createSingleKeyQuery("shard_count", shardCount.toString()) - } - }); - return new HelixEventSubConduit(result.data[0], this._client); - } - /** - * Updates an EventSub conduit for the current client. - * - * @param id The ID of the conduit to update. - * @param shardCount The number of shards to update for this conduit. - */ - async updateConduit(id, shardCount) { - const result = await this._client.callApi({ - type: "helix", - url: "eventsub/conduits", - method: "PATCH", - query: createEventSubConduitUpdateCondition(id, shardCount) - }); - return new HelixEventSubConduit(result.data[0], this._client); - } - /** - * Deletes an EventSub conduit for the current client. - * - * @param id The ID of the conduit to delete. - */ - async deleteConduit(id) { - await this._client.callApi({ - type: "helix", - url: "eventsub/conduits", - method: "DELETE", - query: { - ...createSingleKeyQuery("id", id) - } - }); - } - /** - * Gets the shards of an EventSub conduit for the current client. - * - * @param conduitId The ID of the conduit to get shards for. - * @param status The status of the shards to filter by. - * @param pagination - */ - async getConduitShards(conduitId, status, pagination) { - const result = await this._client.callApi({ - type: "helix", - url: "eventsub/conduits/shards", - query: { - ...createEventSubConduitCondition(conduitId, status), - ...createPaginationQuery(pagination) - } - }); - return { - ...createPaginatedResult(result, HelixEventSubConduitShard, this._client) - }; - } - /** - * Creates a paginator for the shards of an EventSub conduit for the current client. - * - * @param conduitId The ID of the conduit to get shards for. - * @param status The status of the shards to filter by. - */ - getConduitShardsPaginated(conduitId, status) { - return new HelixPaginatedRequest({ - url: "eventsub/conduits/shards", - query: createEventSubConduitCondition(conduitId, status) - }, this._client, (data2) => new HelixEventSubConduitShard(data2)); - } - /** - * Updates shards of an EventSub conduit for the current client. - * - * @param conduitId The ID of the conduit to update shards for. - * @param shards List of shards to update - */ - async updateConduitShards(conduitId, shards) { - const result = await this._client.callApi({ - type: "helix", - url: "eventsub/conduits/shards", - method: "PATCH", - jsonBody: createEventSubConduitShardsUpdateCondition(conduitId, shards) - }); - return result.data.map((data2) => new HelixEventSubConduitShard(data2)); - } - async _deleteSubscriptionsWithCondition(cond) { - const subsPaginator = this.getSubscriptionsPaginated(); - for await (const sub of subsPaginator) { - if (!cond || cond(sub)) { - await sub.unsubscribe(); - } - } - } -}; -HelixEventSubApi = __decorate([ - rtfm("api", "HelixEventSubApi") -], HelixEventSubApi); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/extensions/HelixExtensionsApi.js -init_modules_watch_stub(); -init_performance2(); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/interfaces/endpoints/extensions.external.js -init_modules_watch_stub(); -init_performance2(); -function createReleasedExtensionFilter(extensionId, version3) { - return { - extension_id: extensionId, - extension_version: version3 - }; -} -__name(createReleasedExtensionFilter, "createReleasedExtensionFilter"); -function createExtensionProductBody(data2) { - return { - sku: data2.sku, - cost: { - amount: data2.cost, - type: "bits" - }, - display_name: data2.displayName, - in_development: data2.inDevelopment, - expiration: data2.expirationDate, - is_broadcast: data2.broadcast - }; -} -__name(createExtensionProductBody, "createExtensionProductBody"); -function createExtensionTransactionQuery(extensionId, filter) { - return { - extension_id: extensionId, - id: filter.transactionIds - }; -} -__name(createExtensionTransactionQuery, "createExtensionTransactionQuery"); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/channel/HelixChannelReference.js -init_modules_watch_stub(); -init_performance2(); -var HelixChannelReference = class HelixChannelReference2 extends DataObject { - static { - __name(this, "HelixChannelReference"); - } - /** @internal */ - _client; - /** @internal */ - constructor(data2, client) { - super(data2); - this._client = client; - } - /** - * The ID of the channel. - */ - get id() { - return this[rawDataSymbol].broadcaster_id; - } - /** - * The display name of the channel. - */ - get displayName() { - return this[rawDataSymbol].broadcaster_name; - } - /** - * Gets more information about the channel. - */ - async getChannel() { - return checkRelationAssertion(await this._client.channels.getChannelInfoById(this[rawDataSymbol].broadcaster_id)); - } - /** - * Gets more information about the broadcaster of the channel. - */ - async getBroadcaster() { - return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].broadcaster_id)); - } - /** - * The ID of the game currently played on the channel. - */ - get gameId() { - return this[rawDataSymbol].game_id; - } - /** - * The name of the game currently played on the channel. - */ - get gameName() { - return this[rawDataSymbol].game_name; - } - /** - * Gets information about the game that is being played on the stream. - */ - async getGame() { - return this[rawDataSymbol].game_id ? checkRelationAssertion(await this._client.games.getGameById(this[rawDataSymbol].game_id)) : null; - } - /** - * The title of the channel. - */ - get title() { - return this[rawDataSymbol].title; - } -}; -__decorate([ - Enumerable(false) -], HelixChannelReference.prototype, "_client", void 0); -HelixChannelReference = __decorate([ - rtfm("api", "HelixChannelReference", "id") -], HelixChannelReference); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/extensions/HelixExtensionBitsProduct.js -init_modules_watch_stub(); -init_performance2(); -var HelixExtensionBitsProduct = class HelixExtensionBitsProduct2 extends DataObject { - static { - __name(this, "HelixExtensionBitsProduct"); - } - /** - * The product's unique identifier. - */ - get sku() { - return this[rawDataSymbol].sku; - } - /** - * The product's cost, in bits. - */ - get cost() { - return this[rawDataSymbol].cost.amount; - } - /** - * The product's display name. - */ - get displayName() { - return this[rawDataSymbol].display_name; - } - /** - * Whether the product is in development. - */ - get inDevelopment() { - return this[rawDataSymbol].in_development; - } - /** - * Whether the product's purchases is broadcast to all users. - */ - get isBroadcast() { - return this[rawDataSymbol].is_broadcast; - } - /** - * The product's expiration date. If the product never expires, this is null. - */ - get expirationDate() { - return mapNullable(this[rawDataSymbol].expiration, (exp) => new Date(exp)); - } -}; -HelixExtensionBitsProduct = __decorate([ - rtfm("api", "HelixExtensionBitsProduct", "sku") -], HelixExtensionBitsProduct); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/extensions/HelixExtensionTransaction.js -init_modules_watch_stub(); -init_performance2(); -var HelixExtensionTransaction = class HelixExtensionTransaction2 extends DataObject { - static { - __name(this, "HelixExtensionTransaction"); - } - /** @internal */ - _client; - /** @internal */ - constructor(data2, client) { - super(data2); - this._client = client; - } - /** - * The ID of the transaction. - */ - get id() { - return this[rawDataSymbol].id; - } - /** - * The time when the transaction was made. - */ - get transactionDate() { - return new Date(this[rawDataSymbol].timestamp); - } - /** - * The ID of the broadcaster that runs the extension on their channel. - */ - get broadcasterId() { - return this[rawDataSymbol].broadcaster_id; - } - /** - * The name of the broadcaster that runs the extension on their channel. - */ - get broadcasterName() { - return this[rawDataSymbol].broadcaster_name; - } - /** - * The display name of the broadcaster that runs the extension on their channel. - */ - get broadcasterDisplayName() { - return this[rawDataSymbol].broadcaster_name; - } - /** - * Gets information about the broadcaster that runs the extension on their channel. - */ - async getBroadcaster() { - return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].broadcaster_id)); - } - /** - * The ID of the user that made the transaction. - */ - get userId() { - return this[rawDataSymbol].user_id; - } - /** - * The name of the user that made the transaction. - */ - get userName() { - return this[rawDataSymbol].user_login; - } - /** - * The display name of the user that made the transaction. - */ - get userDisplayName() { - return this[rawDataSymbol].user_name; - } - /** - * Gets information about the user that made the transaction. - */ - async getUser() { - return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].user_id)); - } - /** - * The product type. Currently always BITS_IN_EXTENSION. - */ - get productType() { - return this[rawDataSymbol].product_type; - } - /** - * The product SKU. - */ - get productSku() { - return this[rawDataSymbol].product_data.sku; - } - /** - * The cost of the product, in bits. - */ - get productCost() { - return this[rawDataSymbol].product_data.cost.amount; - } - /** - * The display name of the product. - */ - get productDisplayName() { - return this[rawDataSymbol].product_data.displayName; - } - /** - * Whether the product is in development. - */ - get productInDevelopment() { - return this[rawDataSymbol].product_data.inDevelopment; - } -}; -__decorate([ - Enumerable(false) -], HelixExtensionTransaction.prototype, "_client", void 0); -HelixExtensionTransaction = __decorate([ - rtfm("api", "HelixExtensionTransaction", "id") -], HelixExtensionTransaction); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/extensions/HelixExtensionsApi.js -var HelixExtensionsApi = class HelixExtensionsApi2 extends BaseApi { - static { - __name(this, "HelixExtensionsApi"); - } - /** - * Gets a released extension by ID. - * - * @param extensionId The ID of the extension. - * @param version The version of the extension. If not given, gets the latest version. - */ - async getReleasedExtension(extensionId, version3) { - const result = await this._client.callApi({ - type: "helix", - url: "extensions/released", - query: createReleasedExtensionFilter(extensionId, version3) - }); - return new HelixExtension(result.data[0]); - } - /** - * Gets a list of channels that are currently live and have the given extension installed. - * - * @param extensionId The ID of the extension. - * @param pagination - * - * @expandParams - */ - async getLiveChannelsWithExtension(extensionId, pagination) { - const result = await this._client.callApi({ - type: "helix", - url: "extensions/live", - query: { - ...createSingleKeyQuery("extension_id", extensionId), - ...createPaginationQuery(pagination) - } - }); - return createPaginatedResult(result, HelixChannelReference, this._client); - } - /** - * Creates a paginator for channels that are currently live and have the given extension installed. - * - * @param extensionId The ID of the extension. - */ - getLiveChannelsWithExtensionPaginated(extensionId) { - return new HelixPaginatedRequest({ - url: "extensions/live", - query: createSingleKeyQuery("extension_id", extensionId) - }, this._client, (data2) => new HelixChannelReference(data2, this._client)); - } - /** - * Gets an extension's Bits products. - * - * This only works if the provided token belongs to an extension's client ID, - * and will return the products for that extension. - * - * @param includeDisabled Whether to include disabled/expired products. - */ - async getExtensionBitsProducts(includeDisabled) { - const result = await this._client.callApi({ - type: "helix", - url: "bits/extensions", - forceType: "app", - query: createSingleKeyQuery("should_include_all", includeDisabled?.toString()) - }); - return result.data.map((data2) => new HelixExtensionBitsProduct(data2)); - } - /** - * Creates or updates a Bits product of an extension. - * - * This only works if the provided token belongs to an extension's client ID, - * and will create/update a product for that extension. - * - * @param data - * - * @expandParams - */ - async putExtensionBitsProduct(data2) { - const result = await this._client.callApi({ - type: "helix", - url: "bits/extensions", - method: "PUT", - forceType: "app", - jsonBody: createExtensionProductBody(data2) - }); - return new HelixExtensionBitsProduct(result.data[0]); - } - /** - * Gets a list of transactions for the given extension. - * - * @param extensionId The ID of the extension to get transactions for. - * @param filter Additional filters. - */ - async getExtensionTransactions(extensionId, filter = {}) { - const result = await this._client.callApi({ - type: "helix", - url: "extensions/transactions", - forceType: "app", - query: { - ...createExtensionTransactionQuery(extensionId, filter), - ...createPaginationQuery(filter) - } - }); - return createPaginatedResult(result, HelixExtensionTransaction, this._client); - } - /** - * Creates a paginator for transactions for the given extension. - * - * @param extensionId The ID of the extension to get transactions for. - * @param filter Additional filters. - */ - getExtensionTransactionsPaginated(extensionId, filter = {}) { - return new HelixPaginatedRequest({ - url: "extensions/transactions", - forceType: "app", - query: createExtensionTransactionQuery(extensionId, filter) - }, this._client, (data2) => new HelixExtensionTransaction(data2, this._client)); - } -}; -HelixExtensionsApi = __decorate([ - rtfm("api", "HelixExtensionsApi") -], HelixExtensionsApi); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/game/HelixGameApi.js -init_modules_watch_stub(); -init_performance2(); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/game/HelixGame.js -init_modules_watch_stub(); -init_performance2(); -var HelixGame = class HelixGame2 extends DataObject { - static { - __name(this, "HelixGame"); - } - /** @internal */ - _client; - /** @internal */ - constructor(data2, client) { - super(data2); - this._client = client; - } - /** - * The ID of the game. - */ - get id() { - return this[rawDataSymbol].id; - } - /** - * The name of the game. - */ - get name() { - return this[rawDataSymbol].name; - } - /** - * The URL of the box art of the game. - */ - get boxArtUrl() { - return this[rawDataSymbol].box_art_url; - } - /** - * The IGDB ID of the game, or null if the game doesn't have an IGDB ID assigned at Twitch. - */ - get igdbId() { - return this[rawDataSymbol].igdb_id || null; - } - /** - * Builds the URL of the box art of the game using the given dimensions. - * - * @param width The width of the box art. - * @param height The height of the box art. - */ - getBoxArtUrl(width, height) { - return this[rawDataSymbol].box_art_url.replace("{width}", width.toString()).replace("{height}", height.toString()); - } - /** - * Gets streams that are currently playing the game. - * - * @param pagination - * @expandParams - */ - async getStreams(pagination) { - return await this._client.streams.getStreams({ ...pagination, game: this[rawDataSymbol].id }); - } - /** - * Creates a paginator for streams that are currently playing the game. - */ - getStreamsPaginated() { - return this._client.streams.getStreamsPaginated({ game: this[rawDataSymbol].id }); - } -}; -__decorate([ - Enumerable(false) -], HelixGame.prototype, "_client", void 0); -HelixGame = __decorate([ - rtfm("api", "HelixGame", "id") -], HelixGame); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/game/HelixGameApi.js -var HelixGameApi = class HelixGameApi2 extends BaseApi { - static { - __name(this, "HelixGameApi"); - } - /** @internal */ - _getGameByIdBatcher = new HelixRequestBatcher({ - url: "games" - }, "id", "id", this._client, (data2) => new HelixGame(data2, this._client)); - /** @internal */ - _getGameByNameBatcher = new HelixRequestBatcher({ - url: "games" - }, "name", "name", this._client, (data2) => new HelixGame(data2, this._client)); - /** @internal */ - _getGameByIgdbIdBatcher = new HelixRequestBatcher({ - url: "games" - }, "igdb_id", "igdb_id", this._client, (data2) => new HelixGame(data2, this._client)); - /** - * Gets the game data for the given list of game IDs. - * - * @param ids The game IDs you want to look up. - */ - async getGamesByIds(ids) { - return await this._getGames("id", ids); - } - /** - * Gets the game data for the given list of game names. - * - * @param names The game names you want to look up. - */ - async getGamesByNames(names) { - return await this._getGames("name", names); - } - /** - * Gets the game data for the given list of IGDB IDs. - * - * @param igdbIds The IGDB IDs you want to look up. - */ - async getGamesByIgdbIds(igdbIds) { - return await this._getGames("igdb_id", igdbIds); - } - /** - * Gets the game data for the given game ID. - * - * @param id The game ID you want to look up. - */ - async getGameById(id) { - const games = await this._getGames("id", [id]); - return games[0] ?? null; - } - /** - * Gets the game data for the given game name. - * - * @param name The game name you want to look up. - */ - async getGameByName(name) { - const games = await this._getGames("name", [name]); - return games[0] ?? null; - } - /** - * Gets the game data for the given IGDB ID. - * - * @param igdbId The IGDB ID you want to look up. - */ - async getGameByIgdbId(igdbId) { - const games = await this._getGames("igdb_id", [igdbId]); - return games[0] ?? null; - } - /** - * Gets the game data for the given game ID, batching multiple calls into fewer requests as the API allows. - * - * @param id The game ID you want to look up. - */ - async getGameByIdBatched(id) { - return await this._getGameByIdBatcher.request(id); - } - /** - * Gets the game data for the given game name, batching multiple calls into fewer requests as the API allows. - * - * @param name The game name you want to look up. - */ - async getGameByNameBatched(name) { - return await this._getGameByNameBatcher.request(name); - } - /** - * Gets the game data for the given IGDB ID, batching multiple calls into fewer requests as the API allows. - * - * @param igdbId The IGDB ID you want to look up. - */ - async getGameByIgdbIdBatched(igdbId) { - return await this._getGameByIgdbIdBatcher.request(igdbId); - } - /** - * Gets a list of the most viewed games at the moment. - * - * @param pagination - * - * @expandParams - */ - async getTopGames(pagination) { - const result = await this._client.callApi({ - type: "helix", - url: "games/top", - query: createPaginationQuery(pagination) - }); - return createPaginatedResult(result, HelixGame, this._client); - } - /** - * Creates a paginator for the most viewed games at the moment. - */ - getTopGamesPaginated() { - return new HelixPaginatedRequest({ - url: "games/top" - }, this._client, (data2) => new HelixGame(data2, this._client)); - } - /** @internal */ - async _getGames(filterType, filterValues) { - if (!filterValues.length) { - return []; - } - const result = await this._client.callApi({ - type: "helix", - url: "games", - query: { - [filterType]: filterValues - } - }); - return result.data.map((entry) => new HelixGame(entry, this._client)); - } -}; -__decorate([ - Enumerable(false) -], HelixGameApi.prototype, "_getGameByIdBatcher", void 0); -__decorate([ - Enumerable(false) -], HelixGameApi.prototype, "_getGameByNameBatcher", void 0); -__decorate([ - Enumerable(false) -], HelixGameApi.prototype, "_getGameByIgdbIdBatcher", void 0); -HelixGameApi = __decorate([ - rtfm("api", "HelixGameApi") -], HelixGameApi); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/goals/HelixGoalApi.js -init_modules_watch_stub(); -init_performance2(); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/goals/HelixGoal.js -init_modules_watch_stub(); -init_performance2(); -var HelixGoal = class HelixGoal2 extends DataObject { - static { - __name(this, "HelixGoal"); - } - /** @internal */ - _client; - /** @internal */ - constructor(data2, client) { - super(data2); - this._client = client; - } - /** - * The ID of the goal. - */ - get id() { - return this[rawDataSymbol].id; - } - /** - * The ID of the broadcaster the goal belongs to. - */ - get broadcasterId() { - return this[rawDataSymbol].broadcaster_id; - } - /** - * The display name of the broadcaster the goal belongs to. - */ - get broadcasterDisplayName() { - return this[rawDataSymbol].broadcaster_name; - } - /** - * The name of the broadcaster the goal belongs to. - */ - get broadcasterName() { - return this[rawDataSymbol].broadcaster_login; - } - /** - * Gets more information about the broadcaster. - */ - async getBroadcaster() { - return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].broadcaster_id)); - } - /** - * The type of the goal. - */ - get type() { - return this[rawDataSymbol].type; - } - /** - * The description of the goal. - */ - get description() { - return this[rawDataSymbol].description; - } - /** - * The current value of the goal. - */ - get currentAmount() { - return this[rawDataSymbol].current_amount; - } - /** - * The target value of the goal. - */ - get targetAmount() { - return this[rawDataSymbol].target_amount; - } - /** - * The date and time when the goal was created. - */ - get creationDate() { - return this[rawDataSymbol].created_at; - } -}; -__decorate([ - Enumerable(false) -], HelixGoal.prototype, "_client", void 0); -HelixGoal = __decorate([ - rtfm("api", "HelixGoal", "id") -], HelixGoal); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/goals/HelixGoalApi.js -var HelixGoalApi = class HelixGoalApi2 extends BaseApi { - static { - __name(this, "HelixGoalApi"); - } - async getGoals(broadcaster) { - const result = await this._client.callApi({ - type: "helix", - url: "goals", - userId: extractUserId(broadcaster), - scopes: ["channel:read:goals"], - query: createBroadcasterQuery(broadcaster) - }); - return result.data.map((data2) => new HelixGoal(data2, this._client)); - } -}; -HelixGoalApi = __decorate([ - rtfm("api", "HelixGoalApi") -], HelixGoalApi); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/hypeTrain/HelixHypeTrainApi.js -init_modules_watch_stub(); -init_performance2(); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/hypeTrain/HelixHypeTrainStatus.js -init_modules_watch_stub(); -init_performance2(); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/hypeTrain/HelixHypeTrain.js -init_modules_watch_stub(); -init_performance2(); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/hypeTrain/HelixHypeTrainContribution.js -init_modules_watch_stub(); -init_performance2(); -var HelixHypeTrainContribution = class HelixHypeTrainContribution2 extends DataObject { - static { - __name(this, "HelixHypeTrainContribution"); - } - /** @internal */ - _client; - /** @internal */ - constructor(data2, client) { - super(data2); - this._client = client; - } - /** - * The ID of the user contributing to the Hype Train. - */ - get userId() { - return this[rawDataSymbol].user_id; - } - /** - * The name of the user contributing to the Hype Train. - */ - get userName() { - return this[rawDataSymbol].user_login; - } - /** - * The display name of the user contributing to the Hype Train. - */ - get userDisplayName() { - return this[rawDataSymbol].user_name; - } - /** - * Gets additional information about the user contributing to the Hype Train. - */ - async getUser() { - return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].user_id)); - } - /** - * The type of the Hype Train contribution. - */ - get type() { - return this[rawDataSymbol].type; - } - /** - * The total contribution amount in subs or bits. - */ - get total() { - return this[rawDataSymbol].total; - } -}; -__decorate([ - Enumerable(false) -], HelixHypeTrainContribution.prototype, "_client", void 0); -HelixHypeTrainContribution = __decorate([ - rtfm("api", "HelixHypeTrainContribution", "userId") -], HelixHypeTrainContribution); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/hypeTrain/HelixHypeTrain.js -var HelixHypeTrain = class HelixHypeTrain2 extends DataObject { - static { - __name(this, "HelixHypeTrain"); - } - /** @internal */ - _client; - /** @internal */ - constructor(data2, client) { - super(data2); - this._client = client; - } - /** - * The unique ID of the Hype Train event. - */ - get eventId() { - return this[rawDataSymbol].id; - } - /** - * The unique ID of the Hype Train. - */ - get id() { - return this[rawDataSymbol].id; - } - /** - * The user ID of the broadcaster where the Hype Train is happening. - */ - get broadcasterId() { - return this[rawDataSymbol].broadcaster_user_id; - } - /** - * The name of the broadcaster where the Hype Train is happening. - */ - get broadcasterName() { - return this[rawDataSymbol].broadcaster_user_login; - } - /** - * The display name of the broadcaster where the Hype Train is happening. - */ - get broadcasterDisplayName() { - return this[rawDataSymbol].broadcaster_user_name; - } - /** - * Gets more information about the broadcaster where the Hype Train is happening. - */ - async getBroadcaster() { - return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].broadcaster_user_id)); - } - /** - * The level of the Hype Train. - */ - get level() { - return this[rawDataSymbol].level; - } - /** - * The total amount of progress points of the Hype Train. - */ - get total() { - return this[rawDataSymbol].total; - } - /** - * The amount progress points for the current level of the Hype Train. - */ - get progress() { - return this[rawDataSymbol].progress; - } - /** - * The progress points goal to reach the next Hype Train level. - */ - get goal() { - return this[rawDataSymbol].goal; - } - /** - * Array list of the top contributions to the Hype Train event for bits and subs. - */ - get topContributions() { - return this[rawDataSymbol].top_contributions.map((cont) => new HelixHypeTrainContribution(cont, this._client)); - } - /** - * The time when the Hype Train started. - */ - get startDate() { - return new Date(this[rawDataSymbol].started_at); - } - /** - * The time when the Hype Train is set to expire. - */ - get expiryDate() { - return new Date(this[rawDataSymbol].expires_at); - } - /** - * The type of the Hype Train. - */ - get type() { - return this[rawDataSymbol].type; - } - /** - * Whether the Hype Train is a shared train. - */ - get isSharedTrain() { - return this[rawDataSymbol].is_shared_train; - } -}; -__decorate([ - Enumerable(false) -], HelixHypeTrain.prototype, "_client", void 0); -HelixHypeTrain = __decorate([ - rtfm("api", "HelixHypeTrain", "id") -], HelixHypeTrain); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/hypeTrain/HelixHypeTrainAllTimeHigh.js -init_modules_watch_stub(); -init_performance2(); -var HelixHypeTrainAllTimeHigh = class HelixHypeTrainAllTimeHigh2 extends DataObject { - static { - __name(this, "HelixHypeTrainAllTimeHigh"); - } - /** - * The level reached by the all-time-high Hype Train. - */ - get level() { - return this[rawDataSymbol].level; - } - /** - * The total amount of contribution points reached by the all-time-high Hype Train. - */ - get total() { - return this[rawDataSymbol].total; - } - /** - * The time when the all-time-high Hype Train was achieved. - */ - get achievementDate() { - return new Date(this[rawDataSymbol].achieved_at); - } -}; -HelixHypeTrainAllTimeHigh = __decorate([ - rtfm("api", "HelixHypeTrainAllTimeHigh") -], HelixHypeTrainAllTimeHigh); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/hypeTrain/HelixHypeTrainStatus.js -var HelixHypeTrainStatus = class HelixHypeTrainStatus2 extends DataObject { - static { - __name(this, "HelixHypeTrainStatus"); - } - /** @internal */ - _client; - /** @internal */ - constructor(data2, client) { - super(data2); - this._client = client; - } - /** - * The current Hype Train, or null if there is no ongoing Hype Train. - */ - get current() { - return mapNullable(this[rawDataSymbol].current, (data2) => new HelixHypeTrain(data2, this._client)); - } - /** - * The all-time-high Hype Train statistics for this channel, or null if there was no Hype Train yet. - */ - get allTimeHigh() { - return mapNullable(this[rawDataSymbol].all_time_high, (data2) => new HelixHypeTrainAllTimeHigh(data2)); - } - /** - * The all-time-high shared Hype Train statistics for this channel, or null if there was no shared Hype Train yet. - */ - get sharedAllTimeHigh() { - return mapNullable(this[rawDataSymbol].shared_all_time_high, (data2) => new HelixHypeTrainAllTimeHigh(data2)); - } -}; -__decorate([ - Enumerable(false) -], HelixHypeTrainStatus.prototype, "_client", void 0); -HelixHypeTrainStatus = __decorate([ - rtfm("api", "HelixHypeTrainStatus") -], HelixHypeTrainStatus); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/hypeTrain/HelixHypeTrainApi.js -var HelixHypeTrainApi = class extends BaseApi { - static { - __name(this, "HelixHypeTrainApi"); - } - /** - * Gets the Hype Train status and statistics for the specified broadcaster. - * - * @param broadcaster The broadcaster to fetch Hype Train info for. - */ - async getHypeTrainStatusForBroadcaster(broadcaster) { - const result = await this._client.callApi({ - type: "helix", - url: "hypetrain/status", - userId: extractUserId(broadcaster), - scopes: ["channel:read:hype_train"], - query: { - ...createBroadcasterQuery(broadcaster) - } - }); - return new HelixHypeTrainStatus(result.data[0], this._client); - } -}; - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/moderation/HelixModerationApi.js -init_modules_watch_stub(); -init_performance2(); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/interfaces/endpoints/moderation.external.js -init_modules_watch_stub(); -init_performance2(); -function createModerationUserListQuery(channel, filter) { - return { - broadcaster_id: extractUserId(channel), - user_id: filter?.userId - }; -} -__name(createModerationUserListQuery, "createModerationUserListQuery"); -function createModeratorModifyQuery(broadcaster, user) { - return { - broadcaster_id: extractUserId(broadcaster), - user_id: extractUserId(user) - }; -} -__name(createModeratorModifyQuery, "createModeratorModifyQuery"); -function createResolveUnbanRequestQuery(broadcaster, moderator, unbanRequestId, approved, resolutionMessage) { - return { - unban_request_id: unbanRequestId, - broadcaster_id: extractUserId(broadcaster), - moderator_id: extractUserId(moderator), - status: approved ? "approved" : "denied", - resolution_text: resolutionMessage - }; -} -__name(createResolveUnbanRequestQuery, "createResolveUnbanRequestQuery"); -function createAutoModProcessBody(user, msgId, allow) { - return { - user_id: extractUserId(user), - msg_id: msgId, - action: allow ? "ALLOW" : "DENY" - }; -} -__name(createAutoModProcessBody, "createAutoModProcessBody"); -function createAutoModSettingsBody(data2) { - return { - overall_level: data2.overallLevel, - aggression: data2.aggression, - bullying: data2.bullying, - disability: data2.disability, - misogyny: data2.misogyny, - race_ethnicity_or_religion: data2.raceEthnicityOrReligion, - sex_based_terms: data2.sexBasedTerms, - sexuality_sex_or_gender: data2.sexualitySexOrGender, - swearing: data2.swearing - }; -} -__name(createAutoModSettingsBody, "createAutoModSettingsBody"); -function createBanUserBody(data2) { - return { - data: { - duration: data2.duration, - reason: data2.reason, - user_id: extractUserId(data2.user) - } - }; -} -__name(createBanUserBody, "createBanUserBody"); -function createUpdateShieldModeStatusBody(activate) { - return { - is_active: activate - }; -} -__name(createUpdateShieldModeStatusBody, "createUpdateShieldModeStatusBody"); -function createCheckAutoModStatusBody(data2) { - return { - data: data2.map((entry) => ({ - msg_id: entry.messageId, - msg_text: entry.messageText - })) - }; -} -__name(createCheckAutoModStatusBody, "createCheckAutoModStatusBody"); -function createWarnUserBody(user, reason) { - return { - data: { - user_id: extractUserId(user), - reason - } - }; -} -__name(createWarnUserBody, "createWarnUserBody"); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/moderation/HelixAutoModSettings.js -init_modules_watch_stub(); -init_performance2(); -var HelixAutoModSettings = class HelixAutoModSettings2 extends DataObject { - static { - __name(this, "HelixAutoModSettings"); - } - /** - * The ID of the broadcaster for which the AutoMod settings were fetched. - */ - get broadcasterId() { - return this[rawDataSymbol].broadcaster_id; - } - /** - * The ID of a user that has permission to moderate the broadcaster's chat room. - */ - get moderatorId() { - return this[rawDataSymbol].moderator_id; - } - /** - * The default AutoMod level for the broadcaster. This is null if the broadcaster changed individual settings. - */ - get overallLevel() { - return this[rawDataSymbol].overall_level ? this[rawDataSymbol].overall_level : null; - } - /** - * The AutoMod level for discrimination against disability. - */ - get disability() { - return this[rawDataSymbol].disability; - } - /** - * The AutoMod level for hostility involving aggression. - */ - get aggression() { - return this[rawDataSymbol].aggression; - } - /** - * The AutoMod level for discrimination based on sexuality, sex, or gender. - */ - get sexualitySexOrGender() { - return this[rawDataSymbol].sexuality_sex_or_gender; - } - /** - * The AutoMod level for discrimination against women. - */ - get misogyny() { - return this[rawDataSymbol].misogyny; - } - /** - * The AutoMod level for hostility involving name calling or insults. - */ - get bullying() { - return this[rawDataSymbol].bullying; - } - /** - * The AutoMod level for profanity. - */ - get swearing() { - return this[rawDataSymbol].swearing; - } - /** - * The AutoMod level for racial discrimination. - */ - get raceEthnicityOrReligion() { - return this[rawDataSymbol].race_ethnicity_or_religion; - } - /** - * The AutoMod level for sexual content. - */ - get sexBasedTerms() { - return this[rawDataSymbol].sex_based_terms; - } -}; -HelixAutoModSettings = __decorate([ - rtfm("api", "HelixAutoModSettings", "broadcasterId") -], HelixAutoModSettings); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/moderation/HelixAutoModStatus.js -init_modules_watch_stub(); -init_performance2(); -var HelixAutoModStatus = class HelixAutoModStatus2 extends DataObject { - static { - __name(this, "HelixAutoModStatus"); - } - /** - * The developer-generated ID that was sent with the request data. - */ - get messageId() { - return this[rawDataSymbol].msg_id; - } - /** - * Whether the message is permitted by AutoMod or not. - */ - get isPermitted() { - return this[rawDataSymbol].is_permitted; - } -}; -HelixAutoModStatus = __decorate([ - rtfm("api", "HelixAutoModStatus", "messageId") -], HelixAutoModStatus); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/moderation/HelixBan.js -init_modules_watch_stub(); -init_performance2(); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/moderation/HelixBanUser.js -init_modules_watch_stub(); -init_performance2(); -var HelixBanUser = class HelixBanUser2 extends DataObject { - static { - __name(this, "HelixBanUser"); - } - /** @internal */ - _client; - /** @internal */ - _expiryTimestamp; - /** @internal */ - constructor(data2, expiryTimestamp, client) { - super(data2); - this._expiryTimestamp = expiryTimestamp; - this._client = client; - } - /** - * The date and time that the ban/timeout was created. - */ - get creationDate() { - return new Date(this[rawDataSymbol].created_at); - } - /** - * The date and time that the timeout will end. Is `null` if the user was banned instead of put in a timeout. - */ - get expiryDate() { - return mapNullable(this._expiryTimestamp, (ts) => new Date(ts)); - } - /** - * The ID of the moderator that banned or put the user in the timeout. - */ - get moderatorId() { - return this[rawDataSymbol].moderator_id; - } - /** - * Gets more information about the moderator that banned or put the user in the timeout. - */ - async getModerator() { - return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].moderator_id)); - } - /** - * The ID of the user that was banned or put in a timeout. - */ - get userId() { - return this[rawDataSymbol].user_id; - } - /** - * Gets more information about the user that was banned or put in a timeout. - */ - async getUser() { - return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].user_id)); - } -}; -__decorate([ - Enumerable(false) -], HelixBanUser.prototype, "_client", void 0); -__decorate([ - Enumerable(false) -], HelixBanUser.prototype, "_expiryTimestamp", void 0); -HelixBanUser = __decorate([ - rtfm("api", "HelixBanUser", "userId") -], HelixBanUser); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/moderation/HelixBan.js -var HelixBan = class HelixBan2 extends HelixBanUser { - static { - __name(this, "HelixBan"); - } - /** @internal */ - constructor(data2, client) { - super(data2, data2.expires_at || null, client); - } - /** - * The name of the user that was banned or put in a timeout. - */ - get userName() { - return this[rawDataSymbol].user_login; - } - /** - * The display name of the user that was banned or put in a timeout. - */ - get userDisplayName() { - return this[rawDataSymbol].user_name; - } - /** - * The name of the moderator that banned or put the user in the timeout. - */ - get moderatorName() { - return this[rawDataSymbol].moderator_login; - } - /** - * The display name of the moderator that banned or put the user in the timeout. - */ - get moderatorDisplayName() { - return this[rawDataSymbol].moderator_name; - } - /** - * The reason why the user was banned or timed out. Returns `null` if no reason was given. - */ - get reason() { - return this[rawDataSymbol].reason || null; - } -}; -HelixBan = __decorate([ - rtfm("api", "HelixBan", "userId") -], HelixBan); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/moderation/HelixBlockedTerm.js -init_modules_watch_stub(); -init_performance2(); -var HelixBlockedTerm = class HelixBlockedTerm2 extends DataObject { - static { - __name(this, "HelixBlockedTerm"); - } - /** - * The ID of the broadcaster that owns the list of blocked terms. - */ - get broadcasterId() { - return this[rawDataSymbol].broadcaster_id; - } - /** - * The date and time of when the term was blocked. - */ - get creationDate() { - return new Date(this[rawDataSymbol].created_at); - } - /** - * The date and time of when the blocked term is set to expire. After the block expires, users will be able to use the term in the broadcaster’s chat room. - * Is `null` if the term was added manually or permanently blocked by AutoMod. - */ - get expirationDate() { - return this[rawDataSymbol].expires_at ? new Date(this[rawDataSymbol].expires_at) : null; - } - /** - * An ID that uniquely identifies this blocked term. - */ - get id() { - return this[rawDataSymbol].id; - } - /** - * The ID of the moderator that blocked the word or phrase from being used in the broadcaster’s chat room. - */ - get moderatorId() { - return this[rawDataSymbol].moderator_id; - } - /** - * The blocked word or phrase. - */ - get text() { - return this[rawDataSymbol].text; - } - /** - * The date and time of when the term was updated. - */ - get updatedDate() { - return new Date(this[rawDataSymbol].updated_at); - } -}; -HelixBlockedTerm = __decorate([ - rtfm("api", "HelixBlockedTerm", "id") -], HelixBlockedTerm); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/moderation/HelixModeratedChannel.js -init_modules_watch_stub(); -init_performance2(); -var HelixModeratedChannel = class HelixModeratedChannel2 extends DataObject { - static { - __name(this, "HelixModeratedChannel"); - } - /** @internal */ - _client; - /** @internal */ - constructor(data2, client) { - super(data2); - this._client = client; - } - /** - * The ID of the channel. - */ - get id() { - return this[rawDataSymbol].broadcaster_id; - } - /** - * The name of the channel. - */ - get name() { - return this[rawDataSymbol].broadcaster_login; - } - /** - * The display name of the channel. - */ - get displayName() { - return this[rawDataSymbol].broadcaster_name; - } - /** - * Gets more information about the channel. - */ - async getChannel() { - return checkRelationAssertion(await this._client.channels.getChannelInfoById(this[rawDataSymbol].broadcaster_id)); - } - /** - * Gets more information about the broadcaster of the channel. - */ - async getBroadcaster() { - return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].broadcaster_id)); - } -}; -__decorate([ - Enumerable(false) -], HelixModeratedChannel.prototype, "_client", void 0); -HelixModeratedChannel = __decorate([ - rtfm("api", "HelixModeratedChannel", "id") -], HelixModeratedChannel); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/moderation/HelixModerator.js -init_modules_watch_stub(); -init_performance2(); -var HelixModerator = class HelixModerator2 extends DataObject { - static { - __name(this, "HelixModerator"); - } - /** @internal */ - _client; - /** @internal */ - constructor(data2, client) { - super(data2); - this._client = client; - } - /** - * The ID of the user. - */ - get userId() { - return this[rawDataSymbol].user_id; - } - /** - * The name of the user. - */ - get userName() { - return this[rawDataSymbol].user_login; - } - /** - * The display name of the user. - */ - get userDisplayName() { - return this[rawDataSymbol].user_name; - } - /** - * Gets more information about the user. - */ - async getUser() { - return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].user_id)); - } -}; -__decorate([ - Enumerable(false) -], HelixModerator.prototype, "_client", void 0); -HelixModerator = __decorate([ - rtfm("api", "HelixModerator", "userId") -], HelixModerator); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/moderation/HelixShieldModeStatus.js -init_modules_watch_stub(); -init_performance2(); -var HelixShieldModeStatus = class HelixShieldModeStatus2 extends DataObject { - static { - __name(this, "HelixShieldModeStatus"); - } - /** @internal */ - _client; - /** @internal */ - constructor(data2, client) { - super(data2); - this._client = client; - } - /** - * Whether Shield Mode is active. - */ - get isActive() { - return this[rawDataSymbol].is_active; - } - /** - * The ID of the moderator that last activated Shield Mode. - */ - get moderatorId() { - return this[rawDataSymbol].moderator_id; - } - /** - * The name of the moderator that last activated Shield Mode. - */ - get moderatorName() { - return this[rawDataSymbol].moderator_login; - } - /** - * The display name of the moderator that last activated Shield Mode. - */ - get moderatorDisplayName() { - return this[rawDataSymbol].moderator_name; - } - /** - * Gets more information about the moderator that last activated Shield Mode. - */ - async getModerator() { - return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].moderator_id)); - } - /** - * The date when Shield Mode was last activated. `null` indicates Shield Mode hasn't been previously activated. - */ - get lastActivationDate() { - return this[rawDataSymbol].last_activated_at === "" ? null : new Date(this[rawDataSymbol].last_activated_at); - } -}; -__decorate([ - Enumerable(false) -], HelixShieldModeStatus.prototype, "_client", void 0); -HelixShieldModeStatus = __decorate([ - rtfm("api", "HelixShieldModeStatus") -], HelixShieldModeStatus); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/moderation/HelixUnbanRequest.js -init_modules_watch_stub(); -init_performance2(); -var HelixUnbanRequest = class HelixUnbanRequest2 extends DataObject { - static { - __name(this, "HelixUnbanRequest"); - } - /** @internal */ - _client; - /** @internal */ - constructor(data2, client) { - super(data2); - this._client = client; - } - /** - * Unban request ID. - */ - get id() { - return this[rawDataSymbol].id; - } - /** - * The ID of the broadcaster whose channel is receiving the unban request. - */ - get broadcasterId() { - return this[rawDataSymbol].broadcaster_id; - } - /** - * The name of the broadcaster whose channel is receiving the unban request. - */ - get broadcasterName() { - return this[rawDataSymbol].broadcaster_id; - } - /** - * The display name of the broadcaster whose channel is receiving the unban request. - */ - get broadcasterDisplayName() { - return this[rawDataSymbol].broadcaster_id; - } - /** - * Gets more information about the broadcaster. - */ - async getBroadcaster() { - return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].broadcaster_id)); - } - /** - * The ID of the moderator who resolved the unban request. - * - * Can be `null` if the request is not resolved. - */ - get moderatorId() { - return this[rawDataSymbol].moderator_id; - } - /** - * The name of the moderator who resolved the unban request. - * - * Can be `null` if the request is not resolved. - */ - get moderatorName() { - return this[rawDataSymbol].moderator_login; - } - /** - * The display name of the moderator who resolved the unban request. - * - * Can be `null` if the request is not resolved. - */ - get moderatorDisplayName() { - return this[rawDataSymbol].moderator_name; - } - /** - * Gets more information about the moderator. - */ - async getModerator() { - return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].moderator_id)); - } - /** - * The ID of the user who requested to be unbanned. - */ - get userId() { - return this[rawDataSymbol].user_id; - } - /** - * The name of the user who requested to be unbanned. - */ - get userName() { - return this[rawDataSymbol].user_login; - } - /** - * The display name of the user who requested to be unbanned. - */ - get userDisplayName() { - return this[rawDataSymbol].user_name; - } - /** - * Gets more information about the user. - */ - async getUser() { - return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].user_id)); - } - /** - * Text message of the unban request from the requesting user. - */ - get message() { - return this[rawDataSymbol].text; - } - /** - * The date of when the unban request was created. - */ - get creationDate() { - return new Date(this[rawDataSymbol].created_at); - } - /** - * The message written by the moderator who resolved the unban request, or `null` if it has not been resolved yet. - */ - get resolutionMessage() { - return this[rawDataSymbol].resolution_text || null; - } - /** - * The date when the unban request was resolved, or `null` if it has not been resolved yet. - */ - get resolutionDate() { - return mapNullable(this[rawDataSymbol].resolved_at, (val) => new Date(val)); - } -}; -__decorate([ - Enumerable(false) -], HelixUnbanRequest.prototype, "_client", void 0); -HelixUnbanRequest = __decorate([ - rtfm("api", "HelixUnbanRequest", "id") -], HelixUnbanRequest); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/moderation/HelixWarning.js -init_modules_watch_stub(); -init_performance2(); -var HelixWarning = class HelixWarning2 extends DataObject { - static { - __name(this, "HelixWarning"); - } - /** @internal */ - _client; - /** @internal */ - constructor(data2, client) { - super(data2); - this._client = client; - } - /** - * The ID of the channel in which the warning will take effect. - */ - get broadcasterId() { - return this[rawDataSymbol].user_id; - } - /** - * Gets more information about the broadcaster. - */ - async getBroadcaster() { - return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].broadcaster_id)); - } - /** - * The ID of the user who applied the warning. - */ - get moderatorId() { - return this[rawDataSymbol].moderator_id; - } - /** - * Gets more information about the moderator. - */ - async getModerator() { - return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].moderator_id)); - } - /** - * The ID of the warned user. - */ - get userId() { - return this[rawDataSymbol].user_id; - } - /** - * Gets more information about the user. - */ - async getUser() { - return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].user_id)); - } - /** - * The reason provided for the warning. - */ - get reason() { - return this[rawDataSymbol].reason; - } -}; -__decorate([ - Enumerable(false) -], HelixWarning.prototype, "_client", void 0); -HelixWarning = __decorate([ - rtfm("api", "HelixWarning", "userId") -], HelixWarning); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/moderation/HelixModerationApi.js -var HelixModerationApi = class HelixModerationApi2 extends BaseApi { - static { - __name(this, "HelixModerationApi"); - } - /** - * Gets a list of banned users in a given channel. - * - * @param channel The channel to get the banned users from. - * @param filter Additional filters for the result set. - * - * @expandParams - */ - async getBannedUsers(channel, filter) { - const result = await this._client.callApi({ - type: "helix", - url: "moderation/banned", - userId: extractUserId(channel), - scopes: ["moderation:read"], - query: { - ...createModerationUserListQuery(channel, filter), - ...createPaginationQuery(filter) - } - }); - return createPaginatedResult(result, HelixBan, this._client); - } - /** - * Creates a paginator for banned users in a given channel. - * - * @param channel The channel to get the banned users from. - */ - getBannedUsersPaginated(channel) { - return new HelixPaginatedRequest({ - url: "moderation/banned", - userId: extractUserId(channel), - scopes: ["moderation:read"], - query: createBroadcasterQuery(channel) - }, this._client, (data2) => new HelixBan(data2, this._client), 50); - } - /** - * Checks whether a given user is banned in a given channel. - * - * @param channel The channel to check for a ban of the given user. - * @param user The user to check for a ban in the given channel. - */ - async checkUserBan(channel, user) { - const userId = extractUserId(user); - const result = await this.getBannedUsers(channel, { userId }); - return result.data.some((ban) => ban.userId === userId); - } - /** - * Gets a list of moderators in a given channel. - * - * @param channel The channel to get moderators from. - * @param filter Additional filters for the result set. - * - * @expandParams - */ - async getModerators(channel, filter) { - const result = await this._client.callApi({ - type: "helix", - url: "moderation/moderators", - userId: extractUserId(channel), - scopes: ["moderation:read", "channel:manage:moderators"], - query: { - ...createModerationUserListQuery(channel, filter), - ...createPaginationQuery(filter) - } - }); - return createPaginatedResult(result, HelixModerator, this._client); - } - /** - * Creates a paginator for moderators in a given channel. - * - * @param channel The channel to get moderators from. - */ - getModeratorsPaginated(channel) { - return new HelixPaginatedRequest({ - url: "moderation/moderators", - userId: extractUserId(channel), - scopes: ["moderation:read", "channel:manage:moderators"], - query: createBroadcasterQuery(channel) - }, this._client, (data2) => new HelixModerator(data2, this._client)); - } - /** - * Gets a list of channels where the specified user has moderator privileges. - * - * @param user The user for whom to return a list of channels where they have moderator privileges. - * This ID must match the user ID in the access token. - * @param filter - * - * @expandParams - * - * @returns A paginated list of channels where the user has moderator privileges. - */ - async getModeratedChannels(user, filter) { - const userId = extractUserId(user); - const result = await this._client.callApi({ - type: "helix", - url: "moderation/channels", - userId, - scopes: ["user:read:moderated_channels"], - query: { - ...createSingleKeyQuery("user_id", userId), - ...createPaginationQuery(filter) - } - }); - return createPaginatedResult(result, HelixModeratedChannel, this._client); - } - /** - * Creates a paginator for channels where the specified user has moderator privileges. - * - * @param user The user for whom to return the list of channels where they have moderator privileges. - * This ID must match the user ID in the access token. - */ - getModeratedChannelsPaginated(user) { - const userId = extractUserId(user); - return new HelixPaginatedRequest({ - url: "moderation/channels", - userId, - scopes: ["user:read:moderated_channels"], - query: createSingleKeyQuery("user_id", userId) - }, this._client, (data2) => new HelixModeratedChannel(data2, this._client)); - } - /** - * Checks whether a given user is a moderator of a given channel. - * - * @param channel The channel to check. - * @param user The user to check. - */ - async checkUserMod(channel, user) { - const userId = extractUserId(user); - const result = await this.getModerators(channel, { userId }); - return result.data.some((mod) => mod.userId === userId); - } - /** - * Adds a moderator to the broadcaster’s chat room. - * - * @param broadcaster The broadcaster that owns the chat room. This ID must match the user ID in the access token. - * @param user The user to add as a moderator in the broadcaster’s chat room. - */ - async addModerator(broadcaster, user) { - await this._client.callApi({ - type: "helix", - url: "moderation/moderators", - method: "POST", - userId: extractUserId(broadcaster), - scopes: ["channel:manage:moderators"], - query: createModeratorModifyQuery(broadcaster, user) - }); - } - /** - * Removes a moderator from the broadcaster’s chat room. - * - * @param broadcaster The broadcaster that owns the chat room. This ID must match the user ID in the access token. - * @param user The user to remove as a moderator from the broadcaster’s chat room. - */ - async removeModerator(broadcaster, user) { - await this._client.callApi({ - type: "helix", - url: "moderation/moderators", - method: "DELETE", - userId: extractUserId(broadcaster), - scopes: ["channel:manage:moderators"], - query: createModeratorModifyQuery(broadcaster, user) - }); - } - /** - * Determines whether a string message meets the channel's AutoMod requirements. - * - * @param channel The channel in which the messages to check are posted. - * @param data An array of message data objects. - */ - async checkAutoModStatus(channel, data2) { - const result = await this._client.callApi({ - type: "helix", - url: "moderation/enforcements/status", - method: "POST", - userId: extractUserId(channel), - scopes: ["moderation:read"], - query: createBroadcasterQuery(channel), - jsonBody: createCheckAutoModStatusBody(data2) - }); - return result.data.map((statusData) => new HelixAutoModStatus(statusData)); - } - /** - * Processes a message held by AutoMod. - * - * @param user The user who is processing the message. - * @param msgId The ID of the message. - * @param allow Whether to allow the message - `true` allows, and `false` denies. - */ - async processHeldAutoModMessage(user, msgId, allow) { - await this._client.callApi({ - type: "helix", - url: "moderation/automod/message", - method: "POST", - userId: extractUserId(user), - scopes: ["moderator:manage:automod"], - jsonBody: createAutoModProcessBody(user, msgId, allow) - }); - } - /** - * Gets the AutoMod settings for a broadcaster. - * - * This uses the token of the broadcaster by default. - * If you want to execute this in the context of another user (who has to be moderator of the channel) - * you can do so using [user context overrides](/docs/auth/concepts/context-switching). - * - * @param broadcaster The broadcaster to get the AutoMod settings for. - */ - async getAutoModSettings(broadcaster) { - const broadcasterId = extractUserId(broadcaster); - const result = await this._client.callApi({ - type: "helix", - url: "moderation/automod/settings", - userId: broadcasterId, - scopes: ["moderator:read:automod_settings"], - canOverrideScopedUserContext: true, - query: this._createModeratorActionQuery(broadcasterId) - }); - return result.data.map((data2) => new HelixAutoModSettings(data2)); - } - /** - * Updates the AutoMod settings for a broadcaster. - * - * This uses the token of the broadcaster by default. - * If you want to execute this in the context of another user (who has to be moderator of the channel) - * you can do so using [user context overrides](/docs/auth/concepts/context-switching). - * - * @param broadcaster The broadcaster for which the AutoMod settings are updated. - * @param data The updated AutoMod settings that replace the current AutoMod settings. - */ - async updateAutoModSettings(broadcaster, data2) { - const broadcasterId = extractUserId(broadcaster); - const result = await this._client.callApi({ - type: "helix", - url: "moderation/automod/settings", - method: "PUT", - userId: broadcasterId, - scopes: ["moderator:manage:automod_settings"], - canOverrideScopedUserContext: true, - query: this._createModeratorActionQuery(broadcasterId), - jsonBody: createAutoModSettingsBody(data2) - }); - return result.data.map((settingsData) => new HelixAutoModSettings(settingsData)); - } - /** - * Bans or times out a user in a channel. - * - * This uses the token of the broadcaster by default. - * If you want to execute this in the context of another user (who has to be moderator of the channel) - * you can do so using [user context overrides](/docs/auth/concepts/context-switching). - * - * @param broadcaster The broadcaster in whose channel the user will be banned/timed out. - * @param data - * - * @expandParams - * - * @returns The result data from the ban/timeout request. - */ - async banUser(broadcaster, data2) { - const broadcasterId = extractUserId(broadcaster); - const result = await this._client.callApi({ - type: "helix", - url: "moderation/bans", - method: "POST", - userId: broadcasterId, - scopes: ["moderator:manage:banned_users"], - canOverrideScopedUserContext: true, - query: this._createModeratorActionQuery(broadcasterId), - jsonBody: createBanUserBody(data2) - }); - return result.data.map((banData) => new HelixBanUser(banData, banData.end_time, this._client)); - } - /** - * Unbans/removes the timeout for a user in a channel. - * - * This uses the token of the broadcaster by default. - * If you want to execute this in the context of another user (who has to be moderator of the channel) - * you can do so using [user context overrides](/docs/auth/concepts/context-switching). - * - * @param broadcaster The broadcaster in whose channel the user will be unbanned/removed from timeout. - * @param user The user who will be unbanned/removed from timeout. - */ - async unbanUser(broadcaster, user) { - const broadcasterId = extractUserId(broadcaster); - await this._client.callApi({ - type: "helix", - url: "moderation/bans", - method: "DELETE", - userId: broadcasterId, - scopes: ["moderator:manage:banned_users"], - canOverrideScopedUserContext: true, - query: { - ...this._createModeratorActionQuery(broadcasterId), - ...createSingleKeyQuery("user_id", extractUserId(user)) - } - }); - } - /** - * Gets the broadcaster’s list of non-private, blocked words or phrases. - * - * This uses the token of the broadcaster by default. - * If you want to execute this in the context of another user (who has to be moderator of the channel) - * you can do so using [user context overrides](/docs/auth/concepts/context-switching). - * - * @param broadcaster The broadcaster to get their channel's blocked terms for. - * @param pagination - * - * @expandParams - * - * @returns A paginated list of blocked term data in the broadcaster's channel. - */ - async getBlockedTerms(broadcaster, pagination) { - const broadcasterId = extractUserId(broadcaster); - const result = await this._client.callApi({ - type: "helix", - url: "moderation/blocked_terms", - userId: broadcasterId, - scopes: ["moderator:read:blocked_terms"], - canOverrideScopedUserContext: true, - query: { - ...this._createModeratorActionQuery(broadcasterId), - ...createPaginationQuery(pagination) - } - }); - return createPaginatedResult(result, HelixBlockedTerm, this._client); - } - /** - * Adds a blocked term to the broadcaster's channel. - * - * This uses the token of the broadcaster by default. - * If you want to execute this in the context of another user (who has to be moderator of the channel) - * you can do so using [user context overrides](/docs/auth/concepts/context-switching). - * - * @param broadcaster The broadcaster in whose channel the term will be blocked. - * @param text The word or phrase to block from being used in the broadcaster's channel. - * - * @returns Information about the term that has been blocked. - */ - async addBlockedTerm(broadcaster, text2) { - const broadcasterId = extractUserId(broadcaster); - const result = await this._client.callApi({ - type: "helix", - url: "moderation/blocked_terms", - method: "POST", - userId: broadcasterId, - scopes: ["moderator:manage:blocked_terms"], - canOverrideScopedUserContext: true, - query: this._createModeratorActionQuery(broadcasterId), - jsonBody: { - text: text2 - } - }); - return result.data.map((blockedTermData) => new HelixBlockedTerm(blockedTermData)); - } - /** - * Removes a blocked term from the broadcaster's channel. - * - * @param broadcaster The broadcaster in whose channel the term will be unblocked. - * @param moderator A user that has permission to unblock terms in the broadcaster's channel. - * The token of this user will be used to remove the blocked term. - * @param id The ID of the term that should be unblocked. - */ - async removeBlockedTerm(broadcaster, moderator, id) { - const broadcasterId = extractUserId(broadcaster); - await this._client.callApi({ - type: "helix", - url: "moderation/blocked_terms", - method: "DELETE", - userId: broadcasterId, - scopes: ["moderator:manage:blocked_terms"], - canOverrideScopedUserContext: true, - query: { - ...this._createModeratorActionQuery(broadcasterId), - id - } - }); - } - /** - * Removes a single chat message or all chat messages from the broadcaster’s chat room. - * - * This uses the token of the broadcaster by default. - * If you want to execute this in the context of another user (who has to be moderator of the channel) - * you can do so using [user context overrides](/docs/auth/concepts/context-switching). - * - * @param broadcaster The broadcaster the chat belongs to. - * @param messageId The ID of the message to remove. If not specified, the request removes all messages in the broadcaster’s chat room. - */ - async deleteChatMessages(broadcaster, messageId) { - const broadcasterId = extractUserId(broadcaster); - await this._client.callApi({ - type: "helix", - url: "moderation/chat", - method: "DELETE", - userId: broadcasterId, - scopes: ["moderator:manage:chat_messages"], - canOverrideScopedUserContext: true, - query: { - ...this._createModeratorActionQuery(broadcasterId), - ...createSingleKeyQuery("message_id", messageId) - } - }); - } - /** - * Gets the broadcaster's Shield Mode activation status. - * - * @param broadcaster The broadcaster whose Shield Mode activation status you want to get. - */ - async getShieldModeStatus(broadcaster) { - const broadcasterId = extractUserId(broadcaster); - const result = await this._client.callApi({ - type: "helix", - url: "moderation/shield_mode", - method: "GET", - userId: broadcasterId, - scopes: ["moderator:read:shield_mode", "moderator:manage:shield_mode"], - canOverrideScopedUserContext: true, - query: this._createModeratorActionQuery(broadcasterId) - }); - return new HelixShieldModeStatus(result.data[0], this._client); - } - /** - * Activates or deactivates the broadcaster's Shield Mode. - * - * This uses the token of the broadcaster by default. - * If you want to execute this in the context of another user (who has to be moderator of the channel) - * you can do so using [user context overrides](/docs/auth/concepts/context-switching). - * - * @param broadcaster The broadcaster whose Shield Mode you want to activate or deactivate. - * @param activate The desired Shield Mode status on the broadcaster's channel. - */ - async updateShieldModeStatus(broadcaster, activate) { - const broadcasterId = extractUserId(broadcaster); - const result = await this._client.callApi({ - type: "helix", - url: "moderation/shield_mode", - method: "PUT", - userId: broadcasterId, - scopes: ["moderator:manage:shield_mode"], - canOverrideScopedUserContext: true, - query: this._createModeratorActionQuery(broadcasterId), - jsonBody: createUpdateShieldModeStatusBody(activate) - }); - return new HelixShieldModeStatus(result.data[0], this._client); - } - /** - * Gets a list of unban requests. - * - * @param broadcaster The broadcaster to get unban requests of. - * @param status The status of unban requests to retrieve. - * @param filter Additional filters for the result set. - */ - async getUnbanRequests(broadcaster, status, filter) { - const broadcasterId = extractUserId(broadcaster); - const result = await this._client.callApi({ - type: "helix", - url: "moderation/unban_requests", - method: "GET", - userId: broadcasterId, - scopes: ["moderator:read:unban_requests", "moderator:manage:unban_requests"], - canOverrideScopedUserContext: true, - query: { - ...this._createModeratorActionQuery(broadcasterId), - ...createSingleKeyQuery("status", status), - ...createPaginationQuery(filter) - } - }); - return createPaginatedResult(result, HelixUnbanRequest, this._client); - } - /** - * Creates a paginator for unban requests. - * - * @param broadcaster The broadcaster to get unban requests of. - * @param status The status of unban requests to retrieve. - */ - getUnbanRequestsPaginated(broadcaster, status) { - const broadcasterId = extractUserId(broadcaster); - return new HelixPaginatedRequest({ - url: "moderation/unban_requests", - method: "GET", - userId: broadcasterId, - scopes: ["moderator:read:unban_requests", "moderator:manage:unban_requests"], - canOverrideScopedUserContext: true, - query: { - ...this._createModeratorActionQuery(broadcasterId), - ...createSingleKeyQuery("status", status) - } - }, this._client, (data2) => new HelixUnbanRequest(data2, this._client)); - } - /** - * Resolves an unban request by approving or denying it. - * - * This uses the token of the broadcaster by default. - * If you want to execute this in the context of another user (who has to be moderator of the channel) - * you can do so using [user context overrides](/docs/auth/concepts/context-switching). - * - * @param broadcaster The ID of the broadcaster whose channel is approving or denying the unban request. - * @param unbanRequestId The ID of the unban request to resolve. - * @param approved Whether to approve or deny the unban request. - * @param resolutionMessage Message supplied by the unban request resolver. - * - * The message is limited to a maximum of 500 characters. - */ - async resolveUnbanRequest(broadcaster, unbanRequestId, approved, resolutionMessage) { - const broadcasterId = extractUserId(broadcaster); - const result = await this._client.callApi({ - type: "helix", - url: "moderation/unban_requests", - method: "PATCH", - userId: broadcasterId, - scopes: ["moderator:manage:unban_requests"], - canOverrideScopedUserContext: true, - query: createResolveUnbanRequestQuery(broadcasterId, this._getUserContextIdWithDefault(broadcasterId), unbanRequestId, approved, resolutionMessage?.slice(0, 500)) - }); - return new HelixUnbanRequest(result.data[0], this._client); - } - /** - * Warns a user in the specified broadcaster’s chat room, preventing them from chat interaction until the - * warning is acknowledged. - * - * New warnings can be issued to a user when they already have a warning in the channel - * (new warning will replace old warning). - * - * @param broadcaster The ID of the broadcaster in which channel the warning will take effect. - * @param user The ID of the user to be warned. - * @param reason A custom reason for the warning. Max 500 chars. - */ - async warnUser(broadcaster, user, reason) { - const broadcasterId = extractUserId(broadcaster); - const result = await this._client.callApi({ - type: "helix", - url: "moderation/warnings", - method: "POST", - userId: broadcasterId, - scopes: ["moderator:manage:warnings"], - canOverrideScopedUserContext: true, - query: this._createModeratorActionQuery(broadcasterId), - jsonBody: createWarnUserBody(user, reason.slice(0, 500)) - }); - return new HelixWarning(result.data[0], this._client); - } - _createModeratorActionQuery(broadcasterId) { - return createModeratorActionQuery(broadcasterId, this._getUserContextIdWithDefault(broadcasterId)); - } -}; -HelixModerationApi = __decorate([ - rtfm("api", "HelixModerationApi") -], HelixModerationApi); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/poll/HelixPollApi.js -init_modules_watch_stub(); -init_performance2(); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/interfaces/endpoints/poll.external.js -init_modules_watch_stub(); -init_performance2(); -function createPollBody(broadcaster, data2) { - return { - broadcaster_id: extractUserId(broadcaster), - title: data2.title, - choices: data2.choices.map((title2) => ({ title: title2 })), - duration: data2.duration, - channel_points_voting_enabled: data2.channelPointsPerVote != null, - channel_points_per_vote: data2.channelPointsPerVote ?? 0 - }; -} -__name(createPollBody, "createPollBody"); -function createPollEndBody(broadcaster, id, showResult) { - return { - broadcaster_id: extractUserId(broadcaster), - id, - status: showResult ? "TERMINATED" : "ARCHIVED" - }; -} -__name(createPollEndBody, "createPollEndBody"); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/poll/HelixPoll.js -init_modules_watch_stub(); -init_performance2(); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/poll/HelixPollChoice.js -init_modules_watch_stub(); -init_performance2(); -var HelixPollChoice = class HelixPollChoice2 extends DataObject { - static { - __name(this, "HelixPollChoice"); - } - /** - * The ID of the choice. - */ - get id() { - return this[rawDataSymbol].id; - } - /** - * The title of the choice. - */ - get title() { - return this[rawDataSymbol].title; - } - /** - * The total votes the choice received. - */ - get totalVotes() { - return this[rawDataSymbol].votes; - } - /** - * The votes the choice received by spending channel points. - */ - get channelPointsVotes() { - return this[rawDataSymbol].channel_points_votes; - } -}; -HelixPollChoice = __decorate([ - rtfm("api", "HelixPollChoice", "id") -], HelixPollChoice); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/poll/HelixPoll.js -var HelixPoll = class HelixPoll2 extends DataObject { - static { - __name(this, "HelixPoll"); - } - /** @internal */ - _client; - /** @internal */ - constructor(data2, client) { - super(data2); - this._client = client; - } - /** - * The ID of the poll. - */ - get id() { - return this[rawDataSymbol].id; - } - /** - * The ID of the broadcaster. - */ - get broadcasterId() { - return this[rawDataSymbol].broadcaster_id; - } - /** - * The name of the broadcaster. - */ - get broadcasterName() { - return this[rawDataSymbol].broadcaster_login; - } - /** - * The display name of the broadcaster. - */ - get broadcasterDisplayName() { - return this[rawDataSymbol].broadcaster_name; - } - /** - * Gets more information about the broadcaster. - */ - async getBroadcaster() { - return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].broadcaster_id)); - } - /** - * The title of the poll. - */ - get title() { - return this[rawDataSymbol].title; - } - /** - * Whether voting with channel points is enabled for the poll. - */ - get isChannelPointsVotingEnabled() { - return this[rawDataSymbol].channel_points_voting_enabled; - } - /** - * The amount of channel points that a vote costs. - */ - get channelPointsPerVote() { - return this[rawDataSymbol].channel_points_per_vote; - } - /** - * The status of the poll. - */ - get status() { - return this[rawDataSymbol].status; - } - /** - * The duration of the poll, in seconds. - */ - get durationInSeconds() { - return this[rawDataSymbol].duration; - } - /** - * The date when the poll started. - */ - get startDate() { - return new Date(this[rawDataSymbol].started_at); - } - /** - * The date when the poll ended or will end. - */ - get endDate() { - return new Date(this.startDate.getTime() + this[rawDataSymbol].duration * 1e3); - } - /** - * The choices of the poll. - */ - get choices() { - return this[rawDataSymbol].choices.map((data2) => new HelixPollChoice(data2)); - } -}; -__decorate([ - Enumerable(false) -], HelixPoll.prototype, "_client", void 0); -HelixPoll = __decorate([ - rtfm("api", "HelixPoll", "id") -], HelixPoll); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/poll/HelixPollApi.js -var HelixPollApi = class HelixPollApi2 extends BaseApi { - static { - __name(this, "HelixPollApi"); - } - /** - * Gets a list of polls for the given broadcaster. - * - * @param broadcaster The broadcaster to get polls for. - * @param pagination - * - * @expandParams - */ - async getPolls(broadcaster, pagination) { - const result = await this._client.callApi({ - type: "helix", - url: "polls", - userId: extractUserId(broadcaster), - scopes: ["channel:read:polls", "channel:manage:polls"], - query: { - ...createBroadcasterQuery(broadcaster), - ...createPaginationQuery(pagination) - } - }); - return createPaginatedResult(result, HelixPoll, this._client); - } - /** - * Creates a paginator for polls for the given broadcaster. - * - * @param broadcaster The broadcaster to get polls for. - */ - getPollsPaginated(broadcaster) { - return new HelixPaginatedRequest({ - url: "polls", - userId: extractUserId(broadcaster), - scopes: ["channel:read:polls", "channel:manage:polls"], - query: createBroadcasterQuery(broadcaster) - }, this._client, (data2) => new HelixPoll(data2, this._client), 20); - } - /** - * Gets polls by IDs. - * - * @param broadcaster The broadcaster to get the polls for. - * @param ids The IDs of the polls. - */ - async getPollsByIds(broadcaster, ids) { - if (!ids.length) { - return []; - } - const result = await this._client.callApi({ - type: "helix", - url: "polls", - userId: extractUserId(broadcaster), - scopes: ["channel:read:polls", "channel:manage:polls"], - query: createGetByIdsQuery(broadcaster, ids) - }); - return result.data.map((data2) => new HelixPoll(data2, this._client)); - } - /** - * Gets a poll by ID. - * - * @param broadcaster The broadcaster to get the poll for. - * @param id The ID of the poll. - */ - async getPollById(broadcaster, id) { - const polls = await this.getPollsByIds(broadcaster, [id]); - return polls.length ? polls[0] : null; - } - /** - * Creates a new poll. - * - * @param broadcaster The broadcaster to create the poll for. - * @param data - * - * @expandParams - */ - async createPoll(broadcaster, data2) { - const result = await this._client.callApi({ - type: "helix", - url: "polls", - method: "POST", - userId: extractUserId(broadcaster), - scopes: ["channel:manage:polls"], - jsonBody: createPollBody(broadcaster, data2) - }); - return new HelixPoll(result.data[0], this._client); - } - /** - * Ends a poll. - * - * @param broadcaster The broadcaster to end the poll for. - * @param id The ID of the poll to end. - * @param showResult Whether to allow the result to be viewed publicly. - */ - async endPoll(broadcaster, id, showResult = true) { - const result = await this._client.callApi({ - type: "helix", - url: "polls", - method: "PATCH", - userId: extractUserId(broadcaster), - scopes: ["channel:manage:polls"], - jsonBody: createPollEndBody(broadcaster, id, showResult) - }); - return new HelixPoll(result.data[0], this._client); - } -}; -HelixPollApi = __decorate([ - rtfm("api", "HelixPollApi") -], HelixPollApi); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/prediction/HelixPredictionApi.js -init_modules_watch_stub(); -init_performance2(); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/interfaces/endpoints/prediction.external.js -init_modules_watch_stub(); -init_performance2(); -function createPredictionBody(broadcaster, data2) { - return { - broadcaster_id: extractUserId(broadcaster), - title: data2.title, - outcomes: data2.outcomes.map((title2) => ({ title: title2 })), - prediction_window: data2.autoLockAfter - }; -} -__name(createPredictionBody, "createPredictionBody"); -function createEndPredictionBody(broadcaster, id, status, outcomeId) { - return { - broadcaster_id: extractUserId(broadcaster), - id, - status, - winning_outcome_id: outcomeId - }; -} -__name(createEndPredictionBody, "createEndPredictionBody"); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/prediction/HelixPrediction.js -init_modules_watch_stub(); -init_performance2(); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/prediction/HelixPredictionOutcome.js -init_modules_watch_stub(); -init_performance2(); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/prediction/HelixPredictor.js -init_modules_watch_stub(); -init_performance2(); -var HelixPredictor = class HelixPredictor2 extends DataObject { - static { - __name(this, "HelixPredictor"); - } - /** @internal */ - _client; - /** @internal */ - constructor(data2, client) { - super(data2); - this._client = client; - } - /** - * The user ID of the predictor. - */ - get userId() { - return this[rawDataSymbol].user_id; - } - /** - * The name of the predictor. - */ - get userName() { - return this[rawDataSymbol].user_login; - } - /** - * The display name of the predictor. - */ - get userDisplayName() { - return this[rawDataSymbol].user_name; - } - /** - * Gets more information about the predictor. - */ - async getUser() { - return await this._client.users.getUserById(this[rawDataSymbol].user_id); - } - /** - * The amount of channel points the predictor used for the prediction. - */ - get channelPointsUsed() { - return this[rawDataSymbol].channel_points_used; - } - /** - * The amount of channel points the predictor won for the prediction, or null if the prediction is not resolved yet, was cancelled or lost. - */ - get channelPointsWon() { - return this[rawDataSymbol].channel_points_won; - } -}; -__decorate([ - Enumerable(false) -], HelixPredictor.prototype, "_client", void 0); -HelixPredictor = __decorate([ - rtfm("api", "HelixPredictor", "userId") -], HelixPredictor); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/prediction/HelixPredictionOutcome.js -var HelixPredictionOutcome = class HelixPredictionOutcome2 extends DataObject { - static { - __name(this, "HelixPredictionOutcome"); - } - /** @internal */ - _client; - /** @internal */ - constructor(data2, client) { - super(data2); - this._client = client; - } - /** - * The ID of the outcome. - */ - get id() { - return this[rawDataSymbol].id; - } - /** - * The title of the outcome. - */ - get title() { - return this[rawDataSymbol].title; - } - /** - * The number of users that guessed the outcome. - */ - get users() { - return this[rawDataSymbol].users; - } - /** - * The total number of channel points that were spent on guessing the outcome. - */ - get totalChannelPoints() { - return this[rawDataSymbol].channel_points; - } - /** - * The color of the outcome. - */ - get color() { - return this[rawDataSymbol].color; - } - /** - * The top predictors of the outcome. - */ - get topPredictors() { - return this[rawDataSymbol].top_predictors?.map((data2) => new HelixPredictor(data2, this._client)) ?? []; - } -}; -__decorate([ - Enumerable(false) -], HelixPredictionOutcome.prototype, "_client", void 0); -HelixPredictionOutcome = __decorate([ - rtfm("api", "HelixPredictionOutcome", "id") -], HelixPredictionOutcome); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/prediction/HelixPrediction.js -var HelixPrediction = class HelixPrediction2 extends DataObject { - static { - __name(this, "HelixPrediction"); - } - /** @internal */ - _client; - /** @internal */ - constructor(data2, client) { - super(data2); - this._client = client; - } - /** - * The ID of the prediction. - */ - get id() { - return this[rawDataSymbol].id; - } - /** - * The ID of the broadcaster. - */ - get broadcasterId() { - return this[rawDataSymbol].broadcaster_id; - } - /** - * The name of the broadcaster. - */ - get broadcasterName() { - return this[rawDataSymbol].broadcaster_login; - } - /** - * The display name of the broadcaster. - */ - get broadcasterDisplayName() { - return this[rawDataSymbol].broadcaster_name; - } - /** - * Gets more information about the broadcaster. - */ - async getBroadcaster() { - return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].broadcaster_id)); - } - /** - * The title of the prediction. - */ - get title() { - return this[rawDataSymbol].title; - } - /** - * The status of the prediction. - */ - get status() { - return this[rawDataSymbol].status; - } - /** - * The time after which the prediction will be automatically locked, in seconds from creation. - */ - get autoLockAfter() { - return this[rawDataSymbol].prediction_window; - } - /** - * The date when the prediction started. - */ - get creationDate() { - return new Date(this[rawDataSymbol].created_at); - } - /** - * The date when the prediction ended, or null if it didn't end yet. - */ - get endDate() { - return this[rawDataSymbol].ended_at ? new Date(this[rawDataSymbol].ended_at) : null; - } - /** - * The date when the prediction was locked, or null if it wasn't locked yet. - */ - get lockDate() { - return this[rawDataSymbol].locked_at ? new Date(this[rawDataSymbol].locked_at) : null; - } - /** - * The possible outcomes of the prediction. - */ - get outcomes() { - return this[rawDataSymbol].outcomes.map((data2) => new HelixPredictionOutcome(data2, this._client)); - } - /** - * The ID of the winning outcome, or null if the prediction is currently running or was canceled. - */ - get winningOutcomeId() { - return this[rawDataSymbol].winning_outcome_id || null; - } - /** - * The winning outcome, or null if the prediction is currently running or was canceled. - */ - get winningOutcome() { - if (!this[rawDataSymbol].winning_outcome_id) { - return null; - } - const found = this[rawDataSymbol].outcomes.find((o) => o.id === this[rawDataSymbol].winning_outcome_id); - if (!found) { - throw new HellFreezesOverError("Winning outcome not found in outcomes array"); - } - return new HelixPredictionOutcome(found, this._client); - } -}; -__decorate([ - Enumerable(false) -], HelixPrediction.prototype, "_client", void 0); -HelixPrediction = __decorate([ - rtfm("api", "HelixPrediction", "id") -], HelixPrediction); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/prediction/HelixPredictionApi.js -var HelixPredictionApi = class HelixPredictionApi2 extends BaseApi { - static { - __name(this, "HelixPredictionApi"); - } - /** - * Gets a list of predictions for the given broadcaster. - * - * @param broadcaster The broadcaster to get predictions for. - * @param pagination - * - * @expandParams - */ - async getPredictions(broadcaster, pagination) { - const result = await this._client.callApi({ - type: "helix", - url: "predictions", - userId: extractUserId(broadcaster), - scopes: ["channel:read:predictions"], - query: { - ...createBroadcasterQuery(broadcaster), - ...createPaginationQuery(pagination) - } - }); - return createPaginatedResult(result, HelixPrediction, this._client); - } - /** - * Creates a paginator for predictions for the given broadcaster. - * - * @param broadcaster The broadcaster to get predictions for. - */ - getPredictionsPaginated(broadcaster) { - return new HelixPaginatedRequest({ - url: "predictions", - userId: extractUserId(broadcaster), - scopes: ["channel:read:predictions"], - query: createBroadcasterQuery(broadcaster) - }, this._client, (data2) => new HelixPrediction(data2, this._client), 20); - } - /** - * Gets predictions by IDs. - * - * @param broadcaster The broadcaster to get the predictions for. - * @param ids The IDs of the predictions. - */ - async getPredictionsByIds(broadcaster, ids) { - if (!ids.length) { - return []; - } - const result = await this._client.callApi({ - type: "helix", - url: "predictions", - userId: extractUserId(broadcaster), - scopes: ["channel:read:predictions"], - query: createGetByIdsQuery(broadcaster, ids) - }); - return result.data.map((data2) => new HelixPrediction(data2, this._client)); - } - /** - * Gets a prediction by ID. - * - * @param broadcaster The broadcaster to get the prediction for. - * @param id The ID of the prediction. - */ - async getPredictionById(broadcaster, id) { - const predictions = await this.getPredictionsByIds(broadcaster, [id]); - return predictions.length ? predictions[0] : null; - } - /** - * Creates a new prediction. - * - * @param broadcaster The broadcaster to create the prediction for. - * @param data - * - * @expandParams - */ - async createPrediction(broadcaster, data2) { - const result = await this._client.callApi({ - type: "helix", - url: "predictions", - method: "POST", - userId: extractUserId(broadcaster), - scopes: ["channel:manage:predictions"], - jsonBody: createPredictionBody(broadcaster, data2) - }); - return new HelixPrediction(result.data[0], this._client); - } - /** - * Locks a prediction. - * - * @param broadcaster The broadcaster to lock the prediction for. - * @param id The ID of the prediction to lock. - */ - async lockPrediction(broadcaster, id) { - return await this._endPrediction(broadcaster, id, "LOCKED"); - } - /** - * Resolves a prediction. - * - * @param broadcaster The broadcaster to resolve the prediction for. - * @param id The ID of the prediction to resolve. - * @param outcomeId The ID of the winning outcome. - */ - async resolvePrediction(broadcaster, id, outcomeId) { - return await this._endPrediction(broadcaster, id, "RESOLVED", outcomeId); - } - /** - * Cancels a prediction. - * - * @param broadcaster The broadcaster to cancel the prediction for. - * @param id The ID of the prediction to cancel. - */ - async cancelPrediction(broadcaster, id) { - return await this._endPrediction(broadcaster, id, "CANCELED"); - } - async _endPrediction(broadcaster, id, status, outcomeId) { - const result = await this._client.callApi({ - type: "helix", - url: "predictions", - method: "PATCH", - userId: extractUserId(broadcaster), - scopes: ["channel:manage:predictions"], - jsonBody: createEndPredictionBody(broadcaster, id, status, outcomeId) - }); - return new HelixPrediction(result.data[0], this._client); - } -}; -HelixPredictionApi = __decorate([ - rtfm("api", "HelixPredictionApi") -], HelixPredictionApi); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/raids/HelixRaidApi.js -init_modules_watch_stub(); -init_performance2(); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/interfaces/endpoints/raid.external.js -init_modules_watch_stub(); -init_performance2(); -function createRaidStartQuery(from, to) { - return { - from_broadcaster_id: extractUserId(from), - to_broadcaster_id: extractUserId(to) - }; -} -__name(createRaidStartQuery, "createRaidStartQuery"); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/raids/HelixRaid.js -init_modules_watch_stub(); -init_performance2(); -var HelixRaid = class HelixRaid2 extends DataObject { - static { - __name(this, "HelixRaid"); - } - /** - * The date when the raid was initiated. - */ - get creationDate() { - return new Date(this[rawDataSymbol].created_at); - } - /** - * Whether the raid target channel is intended for mature audiences. - */ - get targetIsMature() { - return this[rawDataSymbol].is_mature; - } -}; -HelixRaid = __decorate([ - rtfm("api", "HelixRaid") -], HelixRaid); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/raids/HelixRaidApi.js -var HelixRaidApi = class HelixRaidApi2 extends BaseApi { - static { - __name(this, "HelixRaidApi"); - } - /** - * Initiate a raid from a live broadcaster to another live broadcaster. - * - * @param from The raiding broadcaster. - * @param to The raid target. - */ - async startRaid(from, to) { - const result = await this._client.callApi({ - type: "helix", - url: "raids", - method: "POST", - userId: extractUserId(from), - scopes: ["channel:manage:raids"], - query: createRaidStartQuery(from, to) - }); - return new HelixRaid(result.data[0]); - } - /** - * Cancels an initiated raid. - * - * @param from The raiding broadcaster. - */ - async cancelRaid(from) { - await this._client.callApi({ - type: "helix", - url: "raids", - method: "DELETE", - userId: extractUserId(from), - scopes: ["channel:manage:raids"], - query: createBroadcasterQuery(from) - }); - } -}; -HelixRaidApi = __decorate([ - rtfm("api", "HelixRaidApi") -], HelixRaidApi); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/schedule/HelixScheduleApi.js -init_modules_watch_stub(); -init_performance2(); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/interfaces/endpoints/schedule.external.js -init_modules_watch_stub(); -init_performance2(); -function createScheduleQuery(broadcaster, filter) { - return { - broadcaster_id: extractUserId(broadcaster), - start_time: filter?.startDate, - utc_offset: filter?.utcOffset?.toString() - }; -} -__name(createScheduleQuery, "createScheduleQuery"); -function createScheduleSettingsUpdateQuery(broadcaster, settings) { - if (settings.vacation) { - return { - broadcaster_id: extractUserId(broadcaster), - is_vacation_enabled: "true", - vacation_start_time: settings.vacation.startDate, - vacation_end_time: settings.vacation.endDate, - timezone: settings.vacation.timezone - }; - } - return { - broadcaster_id: extractUserId(broadcaster), - is_vacation_enabled: "false" - }; -} -__name(createScheduleSettingsUpdateQuery, "createScheduleSettingsUpdateQuery"); -function createScheduleSegmentBody(data2) { - return { - start_time: data2.startDate, - timezone: data2.timezone, - is_recurring: data2.isRecurring, - duration: data2.duration, - category_id: data2.categoryId, - title: data2.title - }; -} -__name(createScheduleSegmentBody, "createScheduleSegmentBody"); -function createScheduleSegmentModifyQuery(broadcaster, segmentId) { - return { - broadcaster_id: extractUserId(broadcaster), - id: segmentId - }; -} -__name(createScheduleSegmentModifyQuery, "createScheduleSegmentModifyQuery"); -function createScheduleSegmentUpdateBody(data2) { - return { - start_time: data2.startDate, - timezone: data2.timezone, - is_canceled: data2.isCanceled, - duration: data2.duration, - category_id: data2.categoryId, - title: data2.title - }; -} -__name(createScheduleSegmentUpdateBody, "createScheduleSegmentUpdateBody"); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/schedule/HelixPaginatedScheduleSegmentRequest.js -init_modules_watch_stub(); -init_performance2(); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/schedule/HelixScheduleSegment.js -init_modules_watch_stub(); -init_performance2(); -var HelixScheduleSegment = class HelixScheduleSegment2 extends DataObject { - static { - __name(this, "HelixScheduleSegment"); - } - /** @internal */ - _client; - /** @internal */ - constructor(data2, client) { - super(data2); - this._client = client; - } - /** - * The ID of the segment. - */ - get id() { - return this[rawDataSymbol].id; - } - /** - * The date when the segment starts. - */ - get startDate() { - return new Date(this[rawDataSymbol].start_time); - } - /** - * The date when the segment ends. - */ - get endDate() { - return new Date(this[rawDataSymbol].end_time); - } - /** - * The title of the segment. - */ - get title() { - return this[rawDataSymbol].title; - } - /** - * The date up to which the segment is canceled. - */ - get cancelEndDate() { - return mapNullable(this[rawDataSymbol].canceled_until, (v) => new Date(v)); - } - /** - * The ID of the category the segment is scheduled for, or null if no category is specified. - */ - get categoryId() { - return this[rawDataSymbol].category?.id ?? null; - } - /** - * The name of the category the segment is scheduled for, or null if no category is specified. - */ - get categoryName() { - return this[rawDataSymbol].category?.name ?? null; - } - /** - * Gets more information about the category the segment is scheduled for, or null if no category is specified. - */ - async getCategory() { - const categoryId = this[rawDataSymbol].category?.id; - return categoryId ? await this._client.games.getGameById(categoryId) : null; - } - /** - * Whether the segment is recurring every week. - */ - get isRecurring() { - return this[rawDataSymbol].is_recurring; - } -}; -__decorate([ - Enumerable(false) -], HelixScheduleSegment.prototype, "_client", void 0); -HelixScheduleSegment = __decorate([ - rtfm("api", "HelixScheduleSegment", "id") -], HelixScheduleSegment); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/schedule/HelixPaginatedScheduleSegmentRequest.js -var HelixPaginatedScheduleSegmentRequest = class HelixPaginatedScheduleSegmentRequest2 extends HelixPaginatedRequest { - static { - __name(this, "HelixPaginatedScheduleSegmentRequest"); - } - /** @internal */ - constructor(broadcaster, client, filter) { - super({ - url: "schedule", - query: createScheduleQuery(broadcaster, filter) - }, client, (data2) => new HelixScheduleSegment(data2, client), 25); - } - // sadly, this hack is necessary to work around the weird data model of schedules - // while still keeping the pagination code as generic as possible - /** @internal */ - async _fetchData(additionalOptions = {}) { - const origData = await super._fetchData(additionalOptions); - return { - data: origData.data.segments ?? [], - pagination: origData.pagination - }; - } -}; -HelixPaginatedScheduleSegmentRequest = __decorate([ - rtfm("api", "HelixPaginatedScheduleSegmentRequest") -], HelixPaginatedScheduleSegmentRequest); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/schedule/HelixSchedule.js -init_modules_watch_stub(); -init_performance2(); -var HelixSchedule = class HelixSchedule2 extends DataObject { - static { - __name(this, "HelixSchedule"); - } - /** @internal */ - _client; - /** @internal */ - constructor(data2, client) { - super(data2); - this._client = client; - } - /** - * The segments of the schedule. - */ - get segments() { - return this[rawDataSymbol].segments?.map((data2) => new HelixScheduleSegment(data2, this._client)) ?? []; - } - /** - * The ID of the broadcaster. - */ - get broadcasterId() { - return this[rawDataSymbol].broadcaster_id; - } - /** - * The name of the broadcaster. - */ - get broadcasterName() { - return this[rawDataSymbol].broadcaster_login; - } - /** - * The display name of the broadcaster. - */ - get broadcasterDisplayName() { - return this[rawDataSymbol].broadcaster_name; - } - /** - * Gets more information about the broadcaster. - */ - async getBroadcaster() { - return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].broadcaster_id)); - } - /** - * The date when the current vacation started, or null if the schedule is not in vacation mode. - */ - get vacationStartDate() { - const timestamp = this[rawDataSymbol].vacation?.start_time; - return timestamp ? new Date(timestamp) : null; - } - /** - * The date when the current vacation ends, or null if the schedule is not in vacation mode. - */ - get vacationEndDate() { - const timestamp = this[rawDataSymbol].vacation?.end_time; - return timestamp ? new Date(timestamp) : null; - } -}; -__decorate([ - Enumerable(false) -], HelixSchedule.prototype, "_client", void 0); -HelixSchedule = __decorate([ - rtfm("api", "HelixSchedule", "broadcasterId") -], HelixSchedule); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/schedule/HelixScheduleApi.js -var HelixScheduleApi = class extends BaseApi { - static { - __name(this, "HelixScheduleApi"); - } - /** - * Gets the schedule for a given broadcaster. - * - * @param broadcaster The broadcaster to get the schedule of. - * @param filter - * - * @expandParams - */ - async getSchedule(broadcaster, filter) { - const result = await this._client.callApi({ - type: "helix", - url: "schedule", - userId: extractUserId(broadcaster), - query: { - ...createScheduleQuery(broadcaster, filter), - ...createPaginationQuery(filter) - } - }); - return { - data: new HelixSchedule(result.data, this._client), - cursor: result.pagination.cursor - }; - } - /** - * Creates a paginator for schedule segments for a given broadcaster. - * - * @param broadcaster The broadcaster to get the schedule segments of. - * @param filter - * - * @expandParams - */ - getScheduleSegmentsPaginated(broadcaster, filter) { - return new HelixPaginatedScheduleSegmentRequest(broadcaster, this._client, filter); - } - /** - * Gets a set of schedule segments by IDs. - * - * @param broadcaster The broadcaster to get schedule segments of. - * @param ids The IDs of the schedule segments. - */ - async getScheduleSegmentsByIds(broadcaster, ids) { - const result = await this._client.callApi({ - type: "helix", - url: "schedule", - userId: extractUserId(broadcaster), - query: createGetByIdsQuery(broadcaster, ids) - }); - return result.data.segments?.map((data2) => new HelixScheduleSegment(data2, this._client)) ?? []; - } - /** - * Gets a single schedule segment by ID. - * - * @param broadcaster The broadcaster to get a schedule segment of. - * @param id The ID of the schedule segment. - */ - async getScheduleSegmentById(broadcaster, id) { - const segments = await this.getScheduleSegmentsByIds(broadcaster, [id]); - return segments.length ? segments[0] : null; - } - /** - * Gets the schedule for a given broadcaster in iCal format. - * - * @param broadcaster The broadcaster to get the schedule for. - */ - async getScheduleAsIcal(broadcaster) { - return await this._client.callApi({ - type: "helix", - url: "schedule/icalendar", - query: createBroadcasterQuery(broadcaster) - }); - } - /** - * Updates the schedule settings of a given broadcaster. - * - * @param broadcaster The broadcaster to update the schedule settings for. - * @param settings - * - * @expandParams - */ - async updateScheduleSettings(broadcaster, settings) { - await this._client.callApi({ - type: "helix", - url: "schedule/settings", - method: "PATCH", - userId: extractUserId(broadcaster), - scopes: ["channel:manage:schedule"], - query: createScheduleSettingsUpdateQuery(broadcaster, settings) - }); - } - /** - * Creates a new segment in a given broadcaster's schedule. - * - * @param broadcaster The broadcaster to create a new schedule segment for. - * @param data - * - * @expandParams - */ - async createScheduleSegment(broadcaster, data2) { - const result = await this._client.callApi({ - type: "helix", - url: "schedule/segment", - method: "POST", - userId: extractUserId(broadcaster), - scopes: ["channel:manage:schedule"], - query: createBroadcasterQuery(broadcaster), - jsonBody: createScheduleSegmentBody(data2) - }); - return new HelixScheduleSegment(result.data.segments[0], this._client); - } - /** - * Updates a segment in a given broadcaster's schedule. - * - * @param broadcaster The broadcaster to create a new schedule segment for. - * @param segmentId The ID of the segment to update. - * @param data - * - * @expandParams - */ - async updateScheduleSegment(broadcaster, segmentId, data2) { - const result = await this._client.callApi({ - type: "helix", - url: "schedule/segment", - method: "PATCH", - userId: extractUserId(broadcaster), - scopes: ["channel:manage:schedule"], - query: createScheduleSegmentModifyQuery(broadcaster, segmentId), - jsonBody: createScheduleSegmentUpdateBody(data2) - }); - return new HelixScheduleSegment(result.data.segments[0], this._client); - } - /** - * Deletes a segment in a given broadcaster's schedule. - * - * @param broadcaster The broadcaster to create a new schedule segment for. - * @param segmentId The ID of the segment to update. - */ - async deleteScheduleSegment(broadcaster, segmentId) { - await this._client.callApi({ - type: "helix", - url: "schedule/segment", - method: "DELETE", - userId: extractUserId(broadcaster), - scopes: ["channel:manage:schedule"], - query: createScheduleSegmentModifyQuery(broadcaster, segmentId) - }); - } -}; - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/search/HelixSearchApi.js -init_modules_watch_stub(); -init_performance2(); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/interfaces/endpoints/search.external.js -init_modules_watch_stub(); -init_performance2(); -function createSearchChannelsQuery(query, filter) { - return { - query, - live_only: filter.liveOnly?.toString() - }; -} -__name(createSearchChannelsQuery, "createSearchChannelsQuery"); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/search/HelixChannelSearchResult.js -init_modules_watch_stub(); -init_performance2(); -var HelixChannelSearchResult = class HelixChannelSearchResult2 extends DataObject { - static { - __name(this, "HelixChannelSearchResult"); - } - /** @internal */ - _client; - /** @internal */ - constructor(data2, client) { - super(data2); - this._client = client; - } - /** - * The language of the channel. - */ - get language() { - return this[rawDataSymbol].broadcaster_language; - } - /** - * The ID of the channel. - */ - get id() { - return this[rawDataSymbol].id; - } - /** - * The name of the channel. - */ - get name() { - return this[rawDataSymbol].broadcaster_login; - } - /** - * The display name of the channel. - */ - get displayName() { - return this[rawDataSymbol].display_name; - } - /** - * Gets additional information about the owner of the channel. - */ - async getUser() { - return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].id)); - } - /** - * The ID of the game currently played on the channel. - */ - get gameId() { - return this[rawDataSymbol].game_id; - } - /** - * The name of the game currently played on the channel. - */ - get gameName() { - return this[rawDataSymbol].game_name; - } - /** - * Gets information about the game that is being played on the stream. - */ - async getGame() { - return this[rawDataSymbol].game_id ? checkRelationAssertion(await this._client.games.getGameById(this[rawDataSymbol].game_id)) : null; - } - /** - * Whether the channel is currently live. - */ - get isLive() { - return this[rawDataSymbol].is_live; - } - /** - * The tags applied to the channel. - */ - get tags() { - return this[rawDataSymbol].tags; - } - /** - * The thumbnail URL of the stream. - */ - get thumbnailUrl() { - return this[rawDataSymbol].thumbnail_url; - } - /** - * The start date of the stream. Returns `null` if the stream is not live. - */ - get startDate() { - return this[rawDataSymbol].is_live ? new Date(this[rawDataSymbol].started_at) : null; - } -}; -__decorate([ - Enumerable(false) -], HelixChannelSearchResult.prototype, "_client", void 0); -HelixChannelSearchResult = __decorate([ - rtfm("api", "HelixChannelSearchResult", "id") -], HelixChannelSearchResult); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/search/HelixSearchApi.js -var HelixSearchApi = class HelixSearchApi2 extends BaseApi { - static { - __name(this, "HelixSearchApi"); - } - /** - * Search categories/games for an exact or partial match. - * - * @param query The search term. - * @param pagination - * - * @expandParams - */ - async searchCategories(query, pagination) { - const result = await this._client.callApi({ - type: "helix", - url: "search/categories", - query: { - query, - ...createPaginationQuery(pagination) - } - }); - return createPaginatedResult(result, HelixGame, this._client); - } - /** - * Creates a paginator for a category/game search. - * - * @param query The search term. - */ - searchCategoriesPaginated(query) { - return new HelixPaginatedRequest({ - url: "search/categories", - query: { - query - } - }, this._client, (data2) => new HelixGame(data2, this._client)); - } - /** - * Search channels for an exact or partial match. - * - * @param query The search term. - * @param filter - * - * @expandParams - */ - async searchChannels(query, filter = {}) { - const result = await this._client.callApi({ - type: "helix", - url: "search/channels", - query: { - ...createSearchChannelsQuery(query, filter), - ...createPaginationQuery(filter) - } - }); - return createPaginatedResult(result, HelixChannelSearchResult, this._client); - } - /** - * Creates a paginator for a channel search. - * - * @param query The search term. - * @param filter - * - * @expandParams - */ - searchChannelsPaginated(query, filter = {}) { - return new HelixPaginatedRequest({ - url: "search/channels", - query: createSearchChannelsQuery(query, filter) - }, this._client, (data2) => new HelixChannelSearchResult(data2, this._client)); - } -}; -HelixSearchApi = __decorate([ - rtfm("api", "HelixSearchApi") -], HelixSearchApi); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/stream/HelixStreamApi.js -init_modules_watch_stub(); -init_performance2(); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/errors/StreamNotLiveError.js -init_modules_watch_stub(); -init_performance2(); -var StreamNotLiveError = class extends CustomError2 { - static { - __name(this, "StreamNotLiveError"); - } - /** @private */ - constructor(options) { - super("Your stream needs to be live to do this", options); - } -}; - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/interfaces/endpoints/stream.external.js -init_modules_watch_stub(); -init_performance2(); -function createStreamQuery(filter) { - return { - game_id: filter.game, - language: filter.language, - type: filter.type, - user_id: filter.userId, - user_login: filter.userName - }; -} -__name(createStreamQuery, "createStreamQuery"); -function createStreamMarkerBody(broadcaster, description) { - return { - user_id: extractUserId(broadcaster), - description - }; -} -__name(createStreamMarkerBody, "createStreamMarkerBody"); -function createVideoQuery(id) { - return { - video_id: id - }; -} -__name(createVideoQuery, "createVideoQuery"); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/stream/HelixStream.js -init_modules_watch_stub(); -init_performance2(); -var HelixStream = class HelixStream2 extends DataObject { - static { - __name(this, "HelixStream"); - } - /** @internal */ - _client; - /** @internal */ - constructor(data2, client) { - super(data2); - this._client = client; - } - /** - * The stream ID. - */ - get id() { - return this[rawDataSymbol].id; - } - /** - * The user ID. - */ - get userId() { - return this[rawDataSymbol].user_id; - } - /** - * The user's name. - */ - get userName() { - return this[rawDataSymbol].user_login; - } - /** - * The user's display name. - */ - get userDisplayName() { - return this[rawDataSymbol].user_name; - } - /** - * Gets information about the user broadcasting the stream. - */ - async getUser() { - return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].user_id)); - } - /** - * The game ID, or an empty string if the stream doesn't currently have a game. - */ - get gameId() { - return this[rawDataSymbol].game_id; - } - /** - * The game name, or an empty string if the stream doesn't currently have a game. - */ - get gameName() { - return this[rawDataSymbol].game_name; - } - /** - * Gets information about the game that is being played on the stream. - * - * Returns null if the stream doesn't currently have a game. - */ - async getGame() { - return this[rawDataSymbol].game_id ? checkRelationAssertion(await this._client.games.getGameById(this[rawDataSymbol].game_id)) : null; - } - /** - * The type of the stream. - */ - get type() { - return this[rawDataSymbol].type; - } - /** - * The title of the stream. - */ - get title() { - return this[rawDataSymbol].title; - } - /** - * The number of viewers the stream currently has. - */ - get viewers() { - return this[rawDataSymbol].viewer_count; - } - /** - * The time when the stream started. - */ - get startDate() { - return new Date(this[rawDataSymbol].started_at); - } - /** - * The language of the stream. - */ - get language() { - return this[rawDataSymbol].language; - } - /** - * The URL of the thumbnail of the stream. - * - * This URL includes the placeholders `{width}` and `{height}` - * which you must replace with the desired dimensions of the thumbnail (in pixels). - * - * You can also use {@link HelixStream#getThumbnailUrl} to do this replacement. - */ - get thumbnailUrl() { - return this[rawDataSymbol].thumbnail_url; - } - /** - * Builds the thumbnail URL of the stream using the given dimensions. - * - * @param width The width of the thumbnail. - * @param height The height of the thumbnail. - */ - getThumbnailUrl(width, height) { - return this[rawDataSymbol].thumbnail_url.replace("{width}", width.toString()).replace("{height}", height.toString()); - } - /** - * The tags applied to the stream. - */ - get tags() { - return this[rawDataSymbol].tags; - } - /** - * Whether the stream is set to be targeted to mature audiences only. - */ - get isMature() { - return this[rawDataSymbol].is_mature; - } -}; -__decorate([ - Enumerable(false) -], HelixStream.prototype, "_client", void 0); -HelixStream = __decorate([ - rtfm("api", "HelixStream", "id") -], HelixStream); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/stream/HelixStreamMarker.js -init_modules_watch_stub(); -init_performance2(); -var HelixStreamMarker = class HelixStreamMarker2 extends DataObject { - static { - __name(this, "HelixStreamMarker"); - } - /** @internal */ - _client; - /** @internal */ - constructor(data2, client) { - super(data2); - this._client = client; - } - /** - * The ID of the marker. - */ - get id() { - return this[rawDataSymbol].id; - } - /** - * The date and time when the marker was created. - */ - get creationDate() { - return new Date(this[rawDataSymbol].created_at); - } - /** - * The description of the marker. - */ - get description() { - return this[rawDataSymbol].description; - } - /** - * The position in the stream when the marker was created, in seconds. - */ - get positionInSeconds() { - return this[rawDataSymbol].position_seconds; - } -}; -__decorate([ - Enumerable(false) -], HelixStreamMarker.prototype, "_client", void 0); -HelixStreamMarker = __decorate([ - rtfm("api", "HelixStreamMarker", "id") -], HelixStreamMarker); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/stream/HelixStreamMarkerWithVideo.js -init_modules_watch_stub(); -init_performance2(); -var HelixStreamMarkerWithVideo = class HelixStreamMarkerWithVideo2 extends HelixStreamMarker { - static { - __name(this, "HelixStreamMarkerWithVideo"); - } - _videoId; - /** @internal */ - constructor(data2, _videoId, client) { - super(data2, client); - this._videoId = _videoId; - } - /** - * The URL of the video, which will start playing at the position of the stream marker. - */ - get url() { - return this[rawDataSymbol].URL; - } - /** - * The ID of the video. - */ - get videoId() { - return this._videoId; - } - /** - * Gets the video data of the video the marker was set in. - */ - async getVideo() { - return checkRelationAssertion(await this._client.videos.getVideoById(this._videoId)); - } -}; -HelixStreamMarkerWithVideo = __decorate([ - rtfm("api", "HelixStreamMarkerWithVideo", "id") -], HelixStreamMarkerWithVideo); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/stream/HelixStreamApi.js -var HelixStreamApi_1; -var HelixStreamApi = HelixStreamApi_1 = class HelixStreamApi2 extends BaseApi { - static { - __name(this, "HelixStreamApi"); - } - /** @internal */ - _getStreamByUserIdBatcher = new HelixRequestBatcher({ - url: "streams" - }, "user_id", "user_id", this._client, (data2) => new HelixStream(data2, this._client)); - /** @internal */ - _getStreamByUserNameBatcher = new HelixRequestBatcher({ - url: "streams" - }, "user_login", "user_login", this._client, (data2) => new HelixStream(data2, this._client)); - /** - * Gets a list of streams. - * - * @param filter - * @expandParams - */ - async getStreams(filter = {}) { - const result = await this._client.callApi({ - url: "streams", - type: "helix", - query: { - ...createStreamQuery(filter), - ...createPaginationQuery(filter) - } - }); - return createPaginatedResult(result, HelixStream, this._client); - } - /** - * Creates a paginator for streams. - * - * @param filter - * @expandParams - */ - getStreamsPaginated(filter = {}) { - return new HelixPaginatedRequest({ - url: "streams", - query: createStreamQuery(filter) - }, this._client, (data2) => new HelixStream(data2, this._client)); - } - /** - * Gets the current streams for the given usernames. - * - * @param users The username to get the streams for. - */ - async getStreamsByUserNames(users) { - const result = await this.getStreams({ userName: users.map(extractUserName) }); - return result.data; - } - /** - * Gets the current stream for the given username. - * - * @param user The username to get the stream for. - */ - async getStreamByUserName(user) { - const result = await this.getStreamsByUserNames([user]); - return result[0] ?? null; - } - /** - * Gets the current stream for the given username, batching multiple calls into fewer requests as the API allows. - * - * @param user The username to get the stream for. - */ - async getStreamByUserNameBatched(user) { - return await this._getStreamByUserNameBatcher.request(extractUserName(user)); - } - /** - * Gets the current streams for the given user IDs. - * - * @param users The user IDs to get the streams for. - */ - async getStreamsByUserIds(users) { - const result = await this.getStreams({ userId: users.map(extractUserId) }); - return result.data; - } - /** - * Gets the current stream for the given user ID. - * - * @param user The user ID to get the stream for. - */ - async getStreamByUserId(user) { - const userId = extractUserId(user); - const result = await this._client.callApi({ - url: "streams", - type: "helix", - userId, - query: createStreamQuery({ userId }) - }); - return mapNullable(result.data[0], (data2) => new HelixStream(data2, this._client)); - } - /** - * Gets the current stream for the given user ID, batching multiple calls into fewer requests as the API allows. - * - * @param user The user ID to get the stream for. - */ - async getStreamByUserIdBatched(user) { - return await this._getStreamByUserIdBatcher.request(extractUserId(user)); - } - /** - * Gets a list of all stream markers for a user. - * - * @param user The user to list the stream markers for. - * @param pagination - * - * @expandParams - */ - async getStreamMarkersForUser(user, pagination) { - const result = await this._client.callApi({ - url: "streams/markers", - type: "helix", - query: { - ...createUserQuery(user), - ...createPaginationQuery(pagination) - }, - userId: extractUserId(user), - scopes: ["user:read:broadcast"], - canOverrideScopedUserContext: true - }); - return { - data: flatten2(result.data.map((data2) => HelixStreamApi_1._mapGetStreamMarkersResult(data2, this._client))), - cursor: result.pagination?.cursor - }; - } - /** - * Creates a paginator for all stream markers for a user. - * - * @param user The user to list the stream markers for. - */ - getStreamMarkersForUserPaginated(user) { - return new HelixPaginatedRequest({ - url: "streams/markers", - query: createUserQuery(user), - userId: extractUserId(user), - scopes: ["user:read:broadcast"], - canOverrideScopedUserContext: true - }, this._client, (data2) => HelixStreamApi_1._mapGetStreamMarkersResult(data2, this._client)); - } - /** - * Gets a list of all stream markers for a video. - * - * @param user The user the video belongs to. - * @param videoId The video to list the stream markers for. - * @param pagination - * - * @expandParams - */ - async getStreamMarkersForVideo(user, videoId, pagination) { - const result = await this._client.callApi({ - url: "streams/markers", - type: "helix", - query: { - ...createVideoQuery(videoId), - ...createPaginationQuery(pagination) - }, - userId: extractUserId(user), - scopes: ["user:read:broadcast"], - canOverrideScopedUserContext: true - }); - return { - data: flatten2(result.data.map((data2) => HelixStreamApi_1._mapGetStreamMarkersResult(data2, this._client))), - cursor: result.pagination?.cursor - }; - } - /** - * Creates a paginator for all stream markers for a video. - * - * @param user The user the video belongs to. - * @param videoId The video to list the stream markers for. - */ - getStreamMarkersForVideoPaginated(user, videoId) { - return new HelixPaginatedRequest({ - url: "streams/markers", - query: createVideoQuery(videoId), - userId: extractUserId(user), - scopes: ["user:read:broadcast"], - canOverrideScopedUserContext: true - }, this._client, (data2) => HelixStreamApi_1._mapGetStreamMarkersResult(data2, this._client)); - } - /** - * Creates a new stream marker. - * - * Only works while the specified user's stream is live. - * - * @param broadcaster The broadcaster to create a stream marker for. - * @param description The description of the marker. - */ - async createStreamMarker(broadcaster, description) { - try { - const result = await this._client.callApi({ - url: "streams/markers", - method: "POST", - type: "helix", - userId: extractUserId(broadcaster), - scopes: ["channel:manage:broadcast"], - canOverrideScopedUserContext: true, - jsonBody: createStreamMarkerBody(broadcaster, description) - }); - return new HelixStreamMarker(result.data[0], this._client); - } catch (e) { - if (e instanceof HttpStatusCodeError && e.statusCode === 404) { - throw new StreamNotLiveError({ cause: e }); - } - throw e; - } - } - /** - * Gets the stream key of a stream. - * - * @param broadcaster The broadcaster to get the stream key for. - */ - async getStreamKey(broadcaster) { - const userId = extractUserId(broadcaster); - const result = await this._client.callApi({ - type: "helix", - url: "streams/key", - userId, - scopes: ["channel:read:stream_key"], - query: createBroadcasterQuery(broadcaster) - }); - return result.data[0].stream_key; - } - /** - * Gets the streams that are currently live and are followed by the given user. - * - * @param user The user to check followed streams for. - * @param pagination - * - * @expandParams - */ - async getFollowedStreams(user, pagination) { - const userId = extractUserId(user); - const result = await this._client.callApi({ - type: "helix", - url: "streams/followed", - userId, - scopes: ["user:read:follows"], - query: { - ...createSingleKeyQuery("user_id", userId), - ...createPaginationQuery(pagination) - } - }); - return createPaginatedResult(result, HelixStream, this._client); - } - /** - * Creates a paginator for the streams that are currently live and are followed by the given user. - * - * @param user The user to check followed streams for. - */ - getFollowedStreamsPaginated(user) { - const userId = extractUserId(user); - return new HelixPaginatedRequest({ - url: "streams/followed", - userId, - scopes: ["user:read:follows"], - query: createSingleKeyQuery("user_id", userId) - }, this._client, (data2) => new HelixStream(data2, this._client)); - } - static _mapGetStreamMarkersResult(data2, client) { - return data2.videos.reduce((result, video) => [ - ...result, - ...video.markers.map((marker) => new HelixStreamMarkerWithVideo(marker, video.video_id, client)) - ], []); - } -}; -__decorate([ - Enumerable(false) -], HelixStreamApi.prototype, "_getStreamByUserIdBatcher", void 0); -__decorate([ - Enumerable(false) -], HelixStreamApi.prototype, "_getStreamByUserNameBatcher", void 0); -HelixStreamApi = HelixStreamApi_1 = __decorate([ - rtfm("api", "HelixStreamApi") -], HelixStreamApi); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/subscriptions/HelixSubscriptionApi.js -init_modules_watch_stub(); -init_performance2(); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/interfaces/endpoints/subscription.external.js -init_modules_watch_stub(); -init_performance2(); -function createSubscriptionCheckQuery(broadcaster, user) { - return { - broadcaster_id: extractUserId(broadcaster), - user_id: extractUserId(user) - }; -} -__name(createSubscriptionCheckQuery, "createSubscriptionCheckQuery"); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/subscriptions/HelixPaginatedSubscriptionsRequest.js -init_modules_watch_stub(); -init_performance2(); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/subscriptions/HelixSubscription.js -init_modules_watch_stub(); -init_performance2(); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/subscriptions/HelixUserSubscription.js -init_modules_watch_stub(); -init_performance2(); -var HelixUserSubscription = class HelixUserSubscription2 extends DataObject { - static { - __name(this, "HelixUserSubscription"); - } - /** @internal */ - _client; - /** @internal */ - constructor(data2, client) { - super(data2); - this._client = client; - } - /** - * The user ID of the broadcaster. - */ - get broadcasterId() { - return this[rawDataSymbol].broadcaster_id; - } - /** - * The name of the broadcaster. - */ - get broadcasterName() { - return this[rawDataSymbol].broadcaster_login; - } - /** - * The display name of the broadcaster. - */ - get broadcasterDisplayName() { - return this[rawDataSymbol].broadcaster_name; - } - /** - * Gets more information about the broadcaster. - */ - async getBroadcaster() { - return await this._client.users.getUserById(this[rawDataSymbol].broadcaster_id); - } - /** - * Whether the subscription has been gifted by another user. - */ - get isGift() { - return this[rawDataSymbol].is_gift; - } - /** - * The tier of the subscription. - */ - get tier() { - return this[rawDataSymbol].tier; - } -}; -__decorate([ - Enumerable(false) -], HelixUserSubscription.prototype, "_client", void 0); -HelixUserSubscription = __decorate([ - rtfm("api", "HelixUserSubscription", "broadcasterId") -], HelixUserSubscription); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/subscriptions/HelixSubscription.js -var HelixSubscription = class HelixSubscription2 extends HelixUserSubscription { - static { - __name(this, "HelixSubscription"); - } - /** - * The user ID of the broadcaster. - */ - get broadcasterId() { - return this[rawDataSymbol].broadcaster_id; - } - /** - * The name of the broadcaster. - */ - get broadcasterName() { - return this[rawDataSymbol].broadcaster_login; - } - /** - * The display name of the broadcaster. - */ - get broadcasterDisplayName() { - return this[rawDataSymbol].broadcaster_name; - } - /** - * Gets more information about the broadcaster. - */ - async getBroadcaster() { - return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].broadcaster_id)); - } - /** - * The user ID of the gifter. - */ - get gifterId() { - return this[rawDataSymbol].is_gift ? this[rawDataSymbol].gifter_id : null; - } - /** - * The name of the gifter. - */ - get gifterName() { - return this[rawDataSymbol].is_gift ? this[rawDataSymbol].gifter_login : null; - } - /** - * The display name of the gifter. - */ - get gifterDisplayName() { - return this[rawDataSymbol].is_gift ? this[rawDataSymbol].gifter_name : null; - } - /** - * Gets more information about the gifter. - */ - async getGifter() { - return this[rawDataSymbol].is_gift ? checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].gifter_id)) : null; - } - /** - * The user ID of the subscribed user. - */ - get userId() { - return this[rawDataSymbol].user_id; - } - /** - * The name of the subscribed user. - */ - get userName() { - return this[rawDataSymbol].user_login; - } - /** - * The display name of the subscribed user. - */ - get userDisplayName() { - return this[rawDataSymbol].user_name; - } - /** - * Gets more information about the subscribed user. - */ - async getUser() { - return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].user_id)); - } -}; -HelixSubscription = __decorate([ - rtfm("api", "HelixSubscription", "userId") -], HelixSubscription); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/subscriptions/HelixPaginatedSubscriptionsRequest.js -var HelixPaginatedSubscriptionsRequest = class HelixPaginatedSubscriptionsRequest2 extends HelixPaginatedRequestWithTotal { - static { - __name(this, "HelixPaginatedSubscriptionsRequest"); - } - /** @internal */ - constructor(broadcaster, client) { - super({ - url: "subscriptions", - scopes: ["channel:read:subscriptions"], - userId: extractUserId(broadcaster), - query: createBroadcasterQuery(broadcaster) - }, client, (data2) => new HelixSubscription(data2, client)); - } - /** - * Gets the total sub points of the broadcaster. - */ - async getPoints() { - const data2 = this._currentData ?? await this._fetchData({ query: { after: void 0 } }); - return data2.points; - } -}; -HelixPaginatedSubscriptionsRequest = __decorate([ - rtfm("api", "HelixPaginatedSubscriptionsRequest") -], HelixPaginatedSubscriptionsRequest); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/subscriptions/HelixSubscriptionApi.js -var HelixSubscriptionApi = class HelixSubscriptionApi2 extends BaseApi { - static { - __name(this, "HelixSubscriptionApi"); - } - /** - * Gets a list of all subscriptions to a given broadcaster. - * - * @param broadcaster The broadcaster to list subscriptions to. - * @param pagination - * - * @expandParams - */ - async getSubscriptions(broadcaster, pagination) { - const result = await this._client.callApi({ - url: "subscriptions", - scopes: ["channel:read:subscriptions"], - type: "helix", - userId: extractUserId(broadcaster), - query: { - ...createBroadcasterQuery(broadcaster), - ...createPaginationQuery(pagination) - } - }); - return { - ...createPaginatedResultWithTotal(result, HelixSubscription, this._client), - points: result.points - }; - } - /** - * Creates a paginator for all subscriptions to a given broadcaster. - * - * @param broadcaster The broadcaster to list subscriptions to. - */ - getSubscriptionsPaginated(broadcaster) { - return new HelixPaginatedSubscriptionsRequest(broadcaster, this._client); - } - /** - * Gets the subset of the given user list that is subscribed to the given broadcaster. - * - * @param broadcaster The broadcaster to find subscriptions to. - * @param users The users that should be checked for subscriptions. - */ - async getSubscriptionsForUsers(broadcaster, users) { - const result = await this._client.callApi({ - type: "helix", - url: "subscriptions", - userId: extractUserId(broadcaster), - scopes: ["channel:read:subscriptions"], - query: createChannelUsersCheckQuery(broadcaster, users) - }); - return result.data.map((data2) => new HelixSubscription(data2, this._client)); - } - /** - * Gets the subscription data for a given user to a given broadcaster. - * - * This checks with the authorization of a broadcaster. - * If you only have the authorization of a user, check {@link HelixSubscriptionApi#checkUserSubscription}}. - * - * @param broadcaster The broadcaster to check. - * @param user The user to check. - */ - async getSubscriptionForUser(broadcaster, user) { - const list = await this.getSubscriptionsForUsers(broadcaster, [user]); - return list.length ? list[0] : null; - } - /** - * Checks if a given user is subscribed to a given broadcaster. Returns null if not subscribed. - * - * This checks with the authorization of a user. - * If you only have the authorization of a broadcaster, check {@link HelixSubscriptionApi#getSubscriptionForUser}}. - * - * @param user The user to check. - * @param broadcaster The broadcaster to check the user's subscription for. - */ - async checkUserSubscription(user, broadcaster) { - try { - const result = await this._client.callApi({ - type: "helix", - url: "subscriptions/user", - userId: extractUserId(user), - scopes: ["user:read:subscriptions"], - query: createSubscriptionCheckQuery(broadcaster, user) - }); - return new HelixUserSubscription(result.data[0], this._client); - } catch (e) { - if (e instanceof HttpStatusCodeError && e.statusCode === 404) { - return null; - } - throw e; - } - } -}; -HelixSubscriptionApi = __decorate([ - rtfm("api", "HelixSubscriptionApi") -], HelixSubscriptionApi); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/team/HelixTeamApi.js -init_modules_watch_stub(); -init_performance2(); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/team/HelixTeam.js -init_modules_watch_stub(); -init_performance2(); -var HelixTeam = class HelixTeam2 extends DataObject { - static { - __name(this, "HelixTeam"); - } - /** @internal */ - _client; - /** @internal */ - constructor(data2, client) { - super(data2); - this._client = client; - } - /** - * The ID of the team. - */ - get id() { - return this[rawDataSymbol].id; - } - /** - * The name of the team. - */ - get name() { - return this[rawDataSymbol].team_name; - } - /** - * The display name of the team. - */ - get displayName() { - return this[rawDataSymbol].team_display_name; - } - /** - * The URL of the background image of the team. - */ - get backgroundImageUrl() { - return this[rawDataSymbol].background_image_url; - } - /** - * The URL of the banner of the team. - */ - get bannerUrl() { - return this[rawDataSymbol].banner; - } - /** - * The date when the team was created. - */ - get creationDate() { - return new Date(this[rawDataSymbol].created_at); - } - /** - * The date when the team was last updated. - */ - get updateDate() { - return new Date(this[rawDataSymbol].updated_at); - } - /** - * The info of the team. - * - * May contain HTML tags. - */ - get info() { - return this[rawDataSymbol].info; - } - /** - * The URL of the thumbnail of the team's logo. - */ - get logoThumbnailUrl() { - return this[rawDataSymbol].thumbnail_url; - } - /** - * Gets the relations to the members of the team. - */ - async getUserRelations() { - const teamWithUsers = await this._client.teams.getTeamById(this.id); - return teamWithUsers.userRelations; - } -}; -__decorate([ - Enumerable(false) -], HelixTeam.prototype, "_client", void 0); -HelixTeam = __decorate([ - rtfm("api", "HelixTeam", "id") -], HelixTeam); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/team/HelixTeamWithUsers.js -init_modules_watch_stub(); -init_performance2(); -var HelixTeamWithUsers = class HelixTeamWithUsers2 extends HelixTeam { - static { - __name(this, "HelixTeamWithUsers"); - } - /** - * The relations to the members of the team. - */ - get userRelations() { - return this[rawDataSymbol].users.map((data2) => new HelixUserRelation(data2, this._client)); - } -}; -HelixTeamWithUsers = __decorate([ - rtfm("api", "HelixTeamWithUsers", "id") -], HelixTeamWithUsers); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/team/HelixTeamApi.js -var HelixTeamApi = class HelixTeamApi2 extends BaseApi { - static { - __name(this, "HelixTeamApi"); - } - /** - * Gets a list of all teams a broadcaster is a member of. - * - * @param broadcaster The broadcaster to get the teams of. - */ - async getTeamsForBroadcaster(broadcaster) { - const result = await this._client.callApi({ - type: "helix", - url: "teams/channel", - userId: extractUserId(broadcaster), - query: createBroadcasterQuery(broadcaster) - }); - return result.data?.map((data2) => new HelixTeam(data2, this._client)) ?? []; - } - /** - * Gets a team by ID. - * - * Returns null if there is no team with the given ID. - * - * @param id The ID of the team. - */ - async getTeamById(id) { - try { - const result = await this._client.callApi({ - type: "helix", - url: "teams", - query: { - id - } - }); - return new HelixTeamWithUsers(result.data[0], this._client); - } catch (e) { - if (e instanceof HttpStatusCodeError && e.statusCode === 500) { - return null; - } - throw e; - } - } - /** - * Gets a team by name. - * - * Returns null if there is no team with the given name. - * - * @param name The name of the team. - */ - async getTeamByName(name) { - try { - const result = await this._client.callApi({ - type: "helix", - url: "teams", - query: { - name - } - }); - return new HelixTeamWithUsers(result.data[0], this._client); - } catch (e) { - if (e instanceof HttpStatusCodeError && e.statusCode === 404) { - return null; - } - throw e; - } - } -}; -HelixTeamApi = __decorate([ - rtfm("api", "HelixTeamApi") -], HelixTeamApi); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/user/HelixUserApi.js -init_modules_watch_stub(); -init_performance2(); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/interfaces/endpoints/user.external.js -init_modules_watch_stub(); -init_performance2(); -function createUserBlockCreateQuery(target, additionalInfo) { - return { - target_user_id: extractUserId(target), - source_context: additionalInfo.sourceContext, - reason: additionalInfo.reason - }; -} -__name(createUserBlockCreateQuery, "createUserBlockCreateQuery"); -function createUserBlockDeleteQuery(target) { - return { - target_user_id: extractUserId(target) - }; -} -__name(createUserBlockDeleteQuery, "createUserBlockDeleteQuery"); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/user/extensions/HelixInstalledExtensionList.js -init_modules_watch_stub(); -init_performance2(); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/user/extensions/HelixInstalledExtension.js -init_modules_watch_stub(); -init_performance2(); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/user/extensions/HelixBaseExtension.js -init_modules_watch_stub(); -init_performance2(); -var HelixBaseExtension = class extends DataObject { - static { - __name(this, "HelixBaseExtension"); - } - /** - * The ID of the extension. - */ - get id() { - return this[rawDataSymbol].id; - } - /** - * The version of the extension. - */ - get version() { - return this[rawDataSymbol].version; - } - /** - * The name of the extension. - */ - get name() { - return this[rawDataSymbol].name; - } -}; - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/user/extensions/HelixInstalledExtension.js -var HelixInstalledExtension = class HelixInstalledExtension2 extends HelixBaseExtension { - static { - __name(this, "HelixInstalledExtension"); - } - _slotType; - _slotId; - /** @internal */ - constructor(slotType, slotId, data2) { - super(data2); - this._slotType = slotType; - this._slotId = slotId; - } - /** - * The type of the slot the extension is in. - */ - get slotType() { - return this._slotType; - } - /** - * The ID of the slot the extension is in. - */ - get slotId() { - return this._slotId; - } -}; -HelixInstalledExtension = __decorate([ - rtfm("api", "HelixInstalledExtension", "id") -], HelixInstalledExtension); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/user/extensions/HelixInstalledExtensionList.js -var HelixInstalledExtensionList = class HelixInstalledExtensionList2 extends DataObject { - static { - __name(this, "HelixInstalledExtensionList"); - } - getExtensionAtSlot(type, slotId) { - const data2 = this[rawDataSymbol][type][slotId]; - return data2.active ? new HelixInstalledExtension(type, slotId, data2) : null; - } - getExtensionsForSlotType(type) { - return [...Object.entries(this[rawDataSymbol][type])].filter((entry) => entry[1].active).map(([slotId, slotData]) => new HelixInstalledExtension(type, slotId, slotData)); - } - getAllExtensions() { - return [...Object.entries(this[rawDataSymbol])].flatMap(([type, typeEntries]) => [...Object.entries(typeEntries)].filter((entry) => entry[1].active).map(([slotId, slotData]) => new HelixInstalledExtension(type, slotId, slotData))); - } -}; -HelixInstalledExtensionList = __decorate([ - rtfm("api", "HelixInstalledExtensionList") -], HelixInstalledExtensionList); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/user/extensions/HelixUserExtension.js -init_modules_watch_stub(); -init_performance2(); -var HelixUserExtension = class HelixUserExtension2 extends HelixBaseExtension { - static { - __name(this, "HelixUserExtension"); - } - /** - * Whether the user has configured the extension to be able to activate it. - */ - get canActivate() { - return this[rawDataSymbol].can_activate; - } - /** - * The available types of the extension. - */ - get types() { - return this[rawDataSymbol].type; - } -}; -HelixUserExtension = __decorate([ - rtfm("api", "HelixUserExtension", "id") -], HelixUserExtension); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/user/HelixPrivilegedUser.js -init_modules_watch_stub(); -init_performance2(); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/user/HelixUser.js -init_modules_watch_stub(); -init_performance2(); -var HelixUser = class HelixUser2 extends DataObject { - static { - __name(this, "HelixUser"); - } - /** @internal */ - _client; - /** @internal */ - constructor(data2, client) { - super(data2); - this._client = client; - } - /** - * The ID of the user. - */ - get id() { - return this[rawDataSymbol].id; - } - /** - * The name of the user. - */ - get name() { - return this[rawDataSymbol].login; - } - /** - * The display name of the user. - */ - get displayName() { - return this[rawDataSymbol].display_name; - } - /** - * The description of the user. - */ - get description() { - return this[rawDataSymbol].description; - } - /** - * The type of the user. - */ - get type() { - return this[rawDataSymbol].type; - } - /** - * The type of the broadcaster. - */ - get broadcasterType() { - return this[rawDataSymbol].broadcaster_type; - } - /** - * The URL of the profile picture of the user. - */ - get profilePictureUrl() { - return this[rawDataSymbol].profile_image_url; - } - /** - * The URL of the offline video placeholder of the user. - */ - get offlinePlaceholderUrl() { - return this[rawDataSymbol].offline_image_url; - } - /** - * The date when the user was created, i.e. when they registered on Twitch. - */ - get creationDate() { - return new Date(this[rawDataSymbol].created_at); - } - /** - * Gets the channel's stream data. - */ - async getStream() { - return await this._client.streams.getStreamByUserId(this); - } - /** - * Gets a list of broadcasters the user follows. - */ - async getFollowedChannels() { - return await this._client.channels.getFollowedChannels(this); - } - /** - * Gets the follow data of the user to the given broadcaster, or `null` if the user doesn't follow the broadcaster. - * - * This requires user authentication. - * For broadcaster authentication, you can use `getChannelFollower` while switching `this` and the parameter. - * - * @param broadcaster The broadcaster to check the follow to. - */ - async getFollowedChannel(broadcaster) { - const result = await this._client.channels.getFollowedChannels(this, broadcaster); - return result.data[0] ?? null; - } - /** - * Checks whether the user is following the given broadcaster. - * - * This requires user authentication. - * For broadcaster authentication, you can use `isFollowedBy` while switching `this` and the parameter. - * - * @param broadcaster The broadcaster to check the user's follow to. - */ - async follows(broadcaster) { - return await this.getFollowedChannel(broadcaster) !== null; - } - /** - * Gets a list of users that follow the broadcaster. - */ - async getChannelFollowers() { - return await this._client.channels.getChannelFollowers(this); - } - /** - * Gets the follow data of the given user to the broadcaster, or `null` if the user doesn't follow the broadcaster. - * - * This requires broadcaster authentication. - * For user authentication, you can use `getFollowedChannel` while switching `this` and the parameter. - * - * @param user The user to check the follow from. - */ - async getChannelFollower(user) { - const result = await this._client.channels.getChannelFollowers(this, user); - return result.data[0] ?? null; - } - /** - * Checks whether the given user is following the broadcaster. - * - * This requires broadcaster authentication. - * For user authentication, you can use `follows` while switching `this` and the parameter. - * - * @param user The user to check the broadcaster's follow from. - */ - async isFollowedBy(user) { - return await this.getChannelFollower(user) !== null; - } - /** - * Gets the subscription data for the user to the given broadcaster, or `null` if the user is not subscribed. - * - * This requires user authentication. - * For broadcaster authentication, you can use `getSubscriber` while switching `this` and the parameter. - * - * @param broadcaster The broadcaster you want to get the subscription data for. - */ - async getSubscriptionTo(broadcaster) { - return await this._client.subscriptions.checkUserSubscription(this, broadcaster); - } - /** - * Checks whether the user is subscribed to the given broadcaster. - * - * This requires user authentication. - * For broadcaster authentication, you can use `hasSubscriber` while switching `this` and the parameter. - * - * @param broadcaster The broadcaster you want to check the subscription for. - */ - async isSubscribedTo(broadcaster) { - return await this.getSubscriptionTo(broadcaster) !== null; - } - /** - * Gets the subscription data for the given user to the broadcaster, or `null` if the user is not subscribed. - * - * This requires broadcaster authentication. - * For user authentication, you can use `getSubscriptionTo` while switching `this` and the parameter. - * - * @param user The user you want to get the subscription data for. - */ - async getSubscriber(user) { - return await this._client.subscriptions.getSubscriptionForUser(this, user); - } - /** - * Checks whether the given user is subscribed to the broadcaster. - * - * This requires broadcaster authentication. - * For user authentication, you can use `isSubscribedTo` while switching `this` and the parameter. - * - * @param user The user you want to check the subscription for. - */ - async hasSubscriber(user) { - return await this.getSubscriber(user) !== null; - } -}; -__decorate([ - Enumerable(false) -], HelixUser.prototype, "_client", void 0); -HelixUser = __decorate([ - rtfm("api", "HelixUser", "id") -], HelixUser); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/user/HelixPrivilegedUser.js -var HelixPrivilegedUser = class HelixPrivilegedUser2 extends HelixUser { - static { - __name(this, "HelixPrivilegedUser"); - } - /** - * The email address of the user. - */ - get email() { - return this[rawDataSymbol].email; - } - /** - * Changes the description of the user. - * - * @param description The new description. - */ - async setDescription(description) { - return await this._client.users.updateAuthenticatedUser(this, { description }); - } -}; -HelixPrivilegedUser = __decorate([ - rtfm("api", "HelixPrivilegedUser", "id") -], HelixPrivilegedUser); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/user/HelixUserBlock.js -init_modules_watch_stub(); -init_performance2(); -var HelixUserBlock = class HelixUserBlock2 extends DataObject { - static { - __name(this, "HelixUserBlock"); - } - /** @internal */ - _client; - /** @internal */ - constructor(data2, client) { - super(data2); - this._client = client; - } - /** - * The ID of the blocked user. - */ - get userId() { - return this[rawDataSymbol].user_id; - } - /** - * The name of the blocked user. - */ - get userName() { - return this[rawDataSymbol].user_login; - } - /** - * The display name of the blocked user. - */ - get userDisplayName() { - return this[rawDataSymbol].display_name; - } - /** - * Gets additional information about the blocked user. - */ - async getUser() { - return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].user_id)); - } -}; -__decorate([ - Enumerable(false) -], HelixUserBlock.prototype, "_client", void 0); -HelixUserBlock = __decorate([ - rtfm("api", "HelixUserBlock", "userId") -], HelixUserBlock); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/user/HelixUserApi.js -var HelixUserApi = class HelixUserApi2 extends BaseApi { - static { - __name(this, "HelixUserApi"); - } - /** @internal */ - _getUserByIdBatcher = new HelixRequestBatcher({ - url: "users" - }, "id", "id", this._client, (data2) => new HelixUser(data2, this._client)); - /** @internal */ - _getUserByNameBatcher = new HelixRequestBatcher({ - url: "users" - }, "login", "login", this._client, (data2) => new HelixUser(data2, this._client)); - /** - * Gets the user data for the given list of user IDs. - * - * @param userIds The user IDs you want to look up. - */ - async getUsersByIds(userIds) { - return await this._getUsers("id", userIds.map(extractUserId)); - } - /** - * Gets the user data for the given list of usernames. - * - * @param userNames The usernames you want to look up. - */ - async getUsersByNames(userNames) { - return await this._getUsers("login", userNames.map(extractUserName)); - } - /** - * Gets the user data for the given user ID. - * - * @param user The user ID you want to look up. - */ - async getUserById(user) { - const userId = extractUserId(user); - const result = await this._client.callApi({ - type: "helix", - url: "users", - userId, - query: { - id: userId - } - }); - return mapNullable(result.data[0], (data2) => new HelixUser(data2, this._client)); - } - /** - * Gets the user data for the given user ID, batching multiple calls into fewer requests as the API allows. - * - * @param user The user ID you want to look up. - */ - async getUserByIdBatched(user) { - return await this._getUserByIdBatcher.request(extractUserId(user)); - } - /** - * Gets the user data for the given username. - * - * @param userName The username you want to look up. - */ - async getUserByName(userName) { - const users = await this._getUsers("login", [extractUserName(userName)]); - return users.length ? users[0] : null; - } - /** - * Gets the user data for the given username, batching multiple calls into fewer requests as the API allows. - * - * @param user The username you want to look up. - */ - async getUserByNameBatched(user) { - return await this._getUserByNameBatcher.request(extractUserName(user)); - } - /** - * Gets the user data of the given authenticated user. - * - * @param user The user to get data for. - * @param withEmail Whether you need the user's email address. - */ - async getAuthenticatedUser(user, withEmail = false) { - const result = await this._client.callApi({ - type: "helix", - url: "users", - forceType: "user", - userId: extractUserId(user), - scopes: withEmail ? ["user:read:email"] : void 0 - }); - if (!result.data?.length) { - throw new HellFreezesOverError("Could not get authenticated user"); - } - return new HelixPrivilegedUser(result.data[0], this._client); - } - /** - * Updates the given authenticated user's data. - * - * @param user The user to update. - * @param data The data to update. - */ - async updateAuthenticatedUser(user, data2) { - const result = await this._client.callApi({ - type: "helix", - url: "users", - method: "PUT", - userId: extractUserId(user), - scopes: ["user:edit"], - query: { - description: data2.description - } - }); - return new HelixPrivilegedUser(result.data[0], this._client); - } - /** - * Gets a list of users blocked by the given user. - * - * @param user The user to get blocks for. - * @param pagination - * - * @expandParams - */ - async getBlocks(user, pagination) { - const result = await this._client.callApi({ - type: "helix", - url: "users/blocks", - userId: extractUserId(user), - scopes: ["user:read:blocked_users"], - query: { - ...createBroadcasterQuery(user), - ...createPaginationQuery(pagination) - } - }); - return createPaginatedResult(result, HelixUserBlock, this._client); - } - /** - * Creates a paginator for users blocked by the given user. - * - * @param user The user to get blocks for. - */ - getBlocksPaginated(user) { - return new HelixPaginatedRequest({ - url: "users/blocks", - userId: extractUserId(user), - scopes: ["user:read:blocked_users"], - query: createBroadcasterQuery(user) - }, this._client, (data2) => new HelixUserBlock(data2, this._client)); - } - /** - * Blocks the given user. - * - * @param broadcaster The user to add the block to. - * @param target The user to block. - * @param additionalInfo Additional info to give context to the block. - * - * @expandParams - */ - async createBlock(broadcaster, target, additionalInfo = {}) { - await this._client.callApi({ - type: "helix", - url: "users/blocks", - method: "PUT", - userId: extractUserId(broadcaster), - scopes: ["user:manage:blocked_users"], - query: createUserBlockCreateQuery(target, additionalInfo) - }); - } - /** - * Unblocks the given user. - * - * @param broadcaster The user to remove the block from. - * @param target The user to unblock. - */ - async deleteBlock(broadcaster, target) { - await this._client.callApi({ - type: "helix", - url: "users/blocks", - method: "DELETE", - userId: extractUserId(broadcaster), - scopes: ["user:manage:blocked_users"], - query: createUserBlockDeleteQuery(target) - }); - } - /** - * Gets a list of all extensions for the given authenticated user. - * - * @param broadcaster The broadcaster to get the list of extensions for. - * @param withInactive Whether to include inactive extensions. - */ - async getExtensionsForAuthenticatedUser(broadcaster, withInactive = false) { - const result = await this._client.callApi({ - type: "helix", - url: "users/extensions/list", - userId: extractUserId(broadcaster), - scopes: withInactive ? ["channel:manage:extensions"] : ["user:read:broadcast", "channel:manage:extensions"] - }); - return result.data.map((data2) => new HelixUserExtension(data2)); - } - /** - * Gets a list of all installed extensions for the given user. - * - * @param user The user to get the installed extensions for. - * @param withDev Whether to include extensions that are in development. - */ - async getActiveExtensions(user, withDev = false) { - const userId = extractUserId(user); - const result = await this._client.callApi({ - type: "helix", - url: "users/extensions", - userId, - scopes: withDev ? ["user:read:broadcast", "channel:manage:extensions"] : void 0, - query: createSingleKeyQuery("user_id", userId) - }); - return new HelixInstalledExtensionList(result.data); - } - /** - * Updates the installed extensions for the given authenticated user. - * - * @param broadcaster The user to update the installed extensions for. - * @param data The extension installation payload. - * - * The format is shown on the [Twitch documentation](https://dev.twitch.tv/docs/api/reference#update-user-extensions). - * Don't use the "data" wrapper though. - */ - async updateActiveExtensionsForAuthenticatedUser(broadcaster, data2) { - const result = await this._client.callApi({ - type: "helix", - url: "users/extensions", - method: "PUT", - userId: extractUserId(broadcaster), - scopes: ["channel:manage:extensions"], - jsonBody: { data: data2 } - }); - return new HelixInstalledExtensionList(result.data); - } - async _getUsers(lookupType, param) { - if (param.length === 0) { - return []; - } - const query = { [lookupType]: param }; - const result = await this._client.callApi({ - type: "helix", - url: "users", - query - }); - return result.data.map((userData) => new HelixUser(userData, this._client)); - } -}; -__decorate([ - Enumerable(false) -], HelixUserApi.prototype, "_getUserByIdBatcher", void 0); -__decorate([ - Enumerable(false) -], HelixUserApi.prototype, "_getUserByNameBatcher", void 0); -HelixUserApi = __decorate([ - rtfm("api", "HelixUserApi") -], HelixUserApi); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/video/HelixVideoApi.js -init_modules_watch_stub(); -init_performance2(); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/video/HelixVideo.js -init_modules_watch_stub(); -init_performance2(); -var HelixVideo = class HelixVideo2 extends DataObject { - static { - __name(this, "HelixVideo"); - } - /** @internal */ - _client; - /** @internal */ - constructor(data2, client) { - super(data2); - this._client = client; - } - /** - * The ID of the video. - */ - get id() { - return this[rawDataSymbol].id; - } - /** - * The ID of the user who created the video. - */ - get userId() { - return this[rawDataSymbol].user_id; - } - /** - * The name of the user who created the video. - */ - get userName() { - return this[rawDataSymbol].user_login; - } - /** - * The display name of the user who created the video. - */ - get userDisplayName() { - return this[rawDataSymbol].user_name; - } - /** - * Gets information about the user who created the video. - */ - async getUser() { - return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].user_id)); - } - /** - * The title of the video. - */ - get title() { - return this[rawDataSymbol].title; - } - /** - * The description of the video. - */ - get description() { - return this[rawDataSymbol].description; - } - /** - * The date when the video was created. - */ - get creationDate() { - return new Date(this[rawDataSymbol].created_at); - } - /** - * The date when the video was published. - */ - get publishDate() { - return new Date(this[rawDataSymbol].published_at); - } - /** - * The URL of the video. - */ - get url() { - return this[rawDataSymbol].url; - } - /** - * The URL of the thumbnail of the video. - */ - get thumbnailUrl() { - return this[rawDataSymbol].thumbnail_url; - } - /** - * Builds the thumbnail URL of the video using the given dimensions. - * - * @param width The width of the thumbnail. - * @param height The height of the thumbnail. - */ - getThumbnailUrl(width, height) { - return this[rawDataSymbol].thumbnail_url.replace("%{width}", width.toString()).replace("%{height}", height.toString()); - } - /** - * Whether the video is public or not. - */ - get isPublic() { - return this[rawDataSymbol].viewable === "public"; - } - /** - * The number of views of the video. - */ - get views() { - return this[rawDataSymbol].view_count; - } - /** - * The language of the video. - */ - get language() { - return this[rawDataSymbol].language; - } - /** - * The type of the video. - */ - get type() { - return this[rawDataSymbol].type; - } - /** - * The duration of the video, as formatted by Twitch. - */ - get duration() { - return this[rawDataSymbol].duration; - } - /** - * The duration of the video, in seconds. - */ - get durationInSeconds() { - const parts = this[rawDataSymbol].duration.match(/\d+[hms]/g); - if (!parts) { - throw new HellFreezesOverError(`Could not parse duration string: ${this[rawDataSymbol].duration}`); - } - return parts.map((part) => { - const partialMatch = /(\d+)([hms])/.exec(part); - if (!partialMatch) { - throw new HellFreezesOverError(`Could not parse partial duration string: ${part}`); - } - const [, num, unit] = partialMatch; - return parseInt(num, 10) * { h: 3600, m: 60, s: 1 }[unit]; - }).reduce((a, b) => a + b); - } - /** - * The ID of the stream this video belongs to. - * - * Returns null if the video is not an archived stream. - */ - get streamId() { - return this[rawDataSymbol].stream_id; - } - /** - * The raw data of muted segments of the video. - */ - get mutedSegmentData() { - return this[rawDataSymbol].muted_segments?.slice() ?? []; - } - /** - * Checks whether the video is muted at a given offset or range. - * - * @param offset The start of your range, in seconds from the start of the video, - * or if no duration is given, the exact offset that is checked. - * @param duration The duration of your range, in seconds. - * @param partial Whether the range check is only partial. - * - * By default, this function returns true only if the passed range is entirely contained in a muted segment. - */ - isMutedAt(offset, duration, partial = false) { - if (this[rawDataSymbol].muted_segments === null) { - return false; - } - if (duration == null) { - return this[rawDataSymbol].muted_segments.some((seg) => seg.offset <= offset && offset <= seg.offset + seg.duration); - } - const end = offset + duration; - if (partial) { - return this[rawDataSymbol].muted_segments.some((seg) => { - const segEnd = seg.offset + seg.duration; - return offset < segEnd && seg.offset < end; - }); - } - return this[rawDataSymbol].muted_segments.some((seg) => { - const segEnd = seg.offset + seg.duration; - return seg.offset <= offset && end <= segEnd; - }); - } -}; -__decorate([ - Enumerable(false) -], HelixVideo.prototype, "_client", void 0); -__decorate([ - CachedGetter() -], HelixVideo.prototype, "durationInSeconds", null); -HelixVideo = __decorate([ - Cacheable, - rtfm("api", "HelixVideo", "id") -], HelixVideo); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/video/HelixVideoApi.js -var HelixVideoApi_1; -var HelixVideoApi = HelixVideoApi_1 = class HelixVideoApi2 extends BaseApi { - static { - __name(this, "HelixVideoApi"); - } - /** @internal */ - _getVideoByIdBatcher = new HelixRequestBatcher({ - url: "videos" - }, "id", "id", this._client, (data2) => new HelixVideo(data2, this._client)); - /** - * Gets the video data for the given list of video IDs. - * - * @param ids The video IDs you want to look up. - */ - async getVideosByIds(ids) { - const result = await this._getVideos("id", ids); - return result.data; - } - /** - * Gets the video data for the given video ID. - * - * @param id The video ID you want to look up. - */ - async getVideoById(id) { - const videos = await this.getVideosByIds([id]); - return videos.length ? videos[0] : null; - } - /** - * Gets the video data for the given video ID, batching multiple calls into fewer requests as the API allows. - * - * @param id The video ID you want to look up. - */ - async getVideoByIdBatched(id) { - return await this._getVideoByIdBatcher.request(id); - } - /** - * Gets the videos of the given user. - * - * @param user The user you want to get videos from. - * @param filter - * - * @expandParams - */ - async getVideosByUser(user, filter = {}) { - const userId = extractUserId(user); - return await this._getVideos("user_id", [userId], filter); - } - /** - * Creates a paginator for videos of the given user. - * - * @param user The user you want to get videos from. - * @param filter - * - * @expandParams - */ - getVideosByUserPaginated(user, filter = {}) { - const userId = extractUserId(user); - return this._getVideosPaginated("user_id", [userId], filter); - } - /** - * Gets the videos of the given game. - * - * @param gameId The game you want to get videos from. - * @param filter - * - * @expandParams - */ - async getVideosByGame(gameId, filter = {}) { - return await this._getVideos("game_id", [gameId], filter); - } - /** - * Creates a paginator for videos of the given game. - * - * @param gameId The game you want to get videos from. - * @param filter - * - * @expandParams - */ - getVideosByGamePaginated(gameId, filter = {}) { - return this._getVideosPaginated("game_id", [gameId], filter); - } - /** - * Deletes videos by its IDs. - * - * @param broadcaster The broadcaster to delete the videos for. - * @param ids The IDs of the videos to delete. - */ - async deleteVideosByIds(broadcaster, ids) { - await this._client.callApi({ - type: "helix", - url: "videos", - method: "DELETE", - scopes: ["channel:manage:videos"], - userId: extractUserId(broadcaster), - query: { - id: ids - } - }); - } - /** @internal */ - async _getVideos(filterType, filterValues, filter = {}) { - if (!filterValues.length) { - return { data: [] }; - } - const result = await this._client.callApi({ - type: "helix", - url: "videos", - userId: filterType === "user_id" ? filterValues[0] : void 0, - query: { - ...HelixVideoApi_1._makeVideosQuery(filterType, filterValues, filter), - ...createPaginationQuery(filter) - } - }); - return createPaginatedResult(result, HelixVideo, this._client); - } - /** @internal */ - _getVideosPaginated(filterType, filterValues, filter = {}) { - return new HelixPaginatedRequest({ - url: "videos", - userId: filterType === "user_id" ? filterValues[0] : void 0, - query: HelixVideoApi_1._makeVideosQuery(filterType, filterValues, filter) - }, this._client, (data2) => new HelixVideo(data2, this._client)); - } - /** @internal */ - static _makeVideosQuery(filterType, filterValues, filter = {}) { - const { language, period, orderBy, type } = filter; - return { - [filterType]: filterValues, - language, - period, - sort: orderBy, - type - }; - } -}; -__decorate([ - Enumerable(false) -], HelixVideoApi.prototype, "_getVideoByIdBatcher", void 0); -HelixVideoApi = HelixVideoApi_1 = __decorate([ - rtfm("api", "HelixVideoApi") -], HelixVideoApi); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/whisper/HelixWhisperApi.js -init_modules_watch_stub(); -init_performance2(); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/interfaces/endpoints/whisper.external.js -init_modules_watch_stub(); -init_performance2(); -function createWhisperQuery(from, to) { - return { - from_user_id: extractUserId(from), - to_user_id: extractUserId(to) - }; -} -__name(createWhisperQuery, "createWhisperQuery"); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/whisper/HelixWhisperApi.js -var HelixWhisperApi = class HelixWhisperApi2 extends BaseApi { - static { - __name(this, "HelixWhisperApi"); - } - /** - * Sends a whisper message to the specified user. - * - * NOTE: The API may silently drop whispers that it suspects of violating Twitch policies. (The API does not indicate that it dropped the whisper; it returns a 204 status code as if it succeeded). - * - * @param from The user sending the whisper. This user must have a verified phone number and must match the user in the access token. - * @param to The user to receive the whisper. - * @param message The whisper message to send. The message must not be empty. - * - * The maximum message lengths are: - * - * 500 characters if the user you're sending the message to hasn't whispered you before. - * 10,000 characters if the user you're sending the message to has whispered you before. - * - * Messages that exceed the maximum length are truncated. - */ - async sendWhisper(from, to, message) { - await this._client.callApi({ - type: "helix", - url: "whispers", - method: "POST", - userId: extractUserId(from), - scopes: ["user:manage:whispers"], - query: createWhisperQuery(from, to), - jsonBody: { - message - } - }); - } -}; -HelixWhisperApi = __decorate([ - rtfm("api", "HelixWhisperApi") -], HelixWhisperApi); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/reporting/ApiReportedRequest.js -init_modules_watch_stub(); -init_performance2(); -var ApiReportedRequest = class { - static { - __name(this, "ApiReportedRequest"); - } - _options; - _httpStatus; - _resolvedUserId; - /** @internal */ - constructor(_options, _httpStatus, _resolvedUserId) { - this._options = _options; - this._httpStatus = _httpStatus; - this._resolvedUserId = _resolvedUserId; - } - /** - * The options used to call the API. - */ - get options() { - return this._options; - } - /** - * The HTTP status code returned by Twitch for the request. - */ - get httpStatus() { - return this._httpStatus; - } - /** - * The ID of the user that was used for authentication, or `null` if an app access token was used. - */ - get resolvedUserId() { - return this._resolvedUserId; - } -}; - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/client/BaseApiClient.js -var BaseApiClient = class BaseApiClient2 extends EventEmitter2 { - static { - __name(this, "BaseApiClient"); - } - _config; - _logger; - _rateLimiter; - onRequest = this.registerEvent(); - /** @internal */ - constructor(config2, logger, rateLimiter) { - super(); - this._config = config2; - this._logger = logger; - this._rateLimiter = rateLimiter; - } - /** - * Requests scopes from the auth provider for the given user. - * - * @param user The user to request scopes for. - * @param scopes The scopes to request. - */ - async requestScopesForUser(user, scopes) { - await this._config.authProvider.getAccessTokenForUser(user, ...scopes.map((scope) => [scope])); - } - /** - * Gets information about your access token. - */ - async getTokenInfo() { - try { - const data2 = await this.callApi({ type: "auth", url: "validate" }); - return new TokenInfo(data2); - } catch (e) { - if (e instanceof HttpStatusCodeError && e.statusCode === 401) { - throw new InvalidTokenError({ cause: e }); - } - throw e; - } - } - /** - * Makes a call to the Twitch API using your access token. - * - * @param options The configuration of the call. - */ - async callApi(options) { - const { authProvider } = this._config; - const shouldAuth = options.auth ?? true; - if (!shouldAuth) { - return await callTwitchApi(options, authProvider.clientId, void 0, void 0, this._config.fetchOptions); - } - let forceUser = false; - if (options.forceType) { - switch (options.forceType) { - case "app": { - if (!authProvider.getAppAccessToken) { - throw new Error("Tried to make an API call that requires an app access token but your auth provider does not support that"); - } - const accessToken2 = await authProvider.getAppAccessToken(); - return await this._callApiUsingInitialToken(options, accessToken2); - } - case "user": { - forceUser = true; - break; - } - default: { - throw new HellFreezesOverError(`Unknown forced token type: ${options.forceType}`); - } - } - } - if (options.scopes) { - forceUser = true; - } - if (forceUser) { - const contextUserId = options.canOverrideScopedUserContext ? this._getUserIdFromRequestContext(options.userId) : options.userId; - if (!contextUserId) { - throw new Error("Tried to make an API call with a user context but no context user ID"); - } - const accessToken2 = await authProvider.getAccessTokenForUser(contextUserId, options.scopes); - if (!accessToken2) { - throw new Error(`Tried to make an API call with a user context for user ID ${contextUserId} but no token was found`); - } - if (accessTokenIsExpired(accessToken2) && authProvider.refreshAccessTokenForUser) { - const newAccessToken = await authProvider.refreshAccessTokenForUser(contextUserId); - return await this._callApiUsingInitialToken(options, newAccessToken, true); - } - return await this._callApiUsingInitialToken(options, accessToken2); - } - const requestContextUserId = this._getUserIdFromRequestContext(options.userId); - const accessToken = requestContextUserId === null ? await authProvider.getAnyAccessToken() : await authProvider.getAnyAccessToken(requestContextUserId ?? options.userId); - if (accessTokenIsExpired(accessToken) && accessToken.userId && authProvider.refreshAccessTokenForUser) { - const newAccessToken = await authProvider.refreshAccessTokenForUser(accessToken.userId); - return await this._callApiUsingInitialToken(options, newAccessToken, true); - } - return await this._callApiUsingInitialToken(options, accessToken); - } - /** - * The Helix bits API methods. - */ - get bits() { - return new HelixBitsApi(this); - } - /** - * The Helix channels API methods. - */ - get channels() { - return new HelixChannelApi(this); - } - /** - * The Helix channel points API methods. - */ - get channelPoints() { - return new HelixChannelPointsApi(this); - } - /** - * The Helix charity API methods. - */ - get charity() { - return new HelixCharityApi(this); - } - /** - * The Helix chat API methods. - */ - get chat() { - return new HelixChatApi(this); - } - /** - * The Helix clips API methods. - */ - get clips() { - return new HelixClipApi(this); - } - /** - * The Helix content classification label API methods. - */ - get contentClassificationLabels() { - return new HelixContentClassificationLabelApi(this); - } - /** - * The Helix entitlement API methods. - */ - get entitlements() { - return new HelixEntitlementApi(this); - } - /** - * The Helix EventSub API methods. - */ - get eventSub() { - return new HelixEventSubApi(this); - } - /** - * The Helix extensions API methods. - */ - get extensions() { - return new HelixExtensionsApi(this); - } - /** - * The Helix game API methods. - */ - get games() { - return new HelixGameApi(this); - } - /** - * The Helix Hype Train API methods. - */ - get hypeTrain() { - return new HelixHypeTrainApi(this); - } - /** - * The Helix goal API methods. - */ - get goals() { - return new HelixGoalApi(this); - } - /** - * The Helix moderation API methods. - */ - get moderation() { - return new HelixModerationApi(this); - } - /** - * The Helix poll API methods. - */ - get polls() { - return new HelixPollApi(this); - } - /** - * The Helix prediction API methods. - */ - get predictions() { - return new HelixPredictionApi(this); - } - /** - * The Helix raid API methods. - */ - get raids() { - return new HelixRaidApi(this); - } - /** - * The Helix schedule API methods. - */ - get schedule() { - return new HelixScheduleApi(this); - } - /** - * The Helix search API methods. - */ - get search() { - return new HelixSearchApi(this); - } - /** - * The Helix stream API methods. - */ - get streams() { - return new HelixStreamApi(this); - } - /** - * The Helix subscription API methods. - */ - get subscriptions() { - return new HelixSubscriptionApi(this); - } - /** - * The Helix team API methods. - */ - get teams() { - return new HelixTeamApi(this); - } - /** - * The Helix user API methods. - */ - get users() { - return new HelixUserApi(this); - } - /** - * The Helix video API methods. - */ - get videos() { - return new HelixVideoApi(this); - } - /** - * The API methods that deal with whispers. - */ - get whispers() { - return new HelixWhisperApi(this); - } - /** - * Statistics on the rate limiter for the Helix API. - */ - get rateLimiterStats() { - if (this._rateLimiter instanceof ResponseBasedRateLimiter) { - return this._rateLimiter.stats; - } - return null; - } - /** @private */ - get _authProvider() { - return this._config.authProvider; - } - /** @internal */ - get _batchDelay() { - return this._config.batchDelay ?? 0; - } - // null means app access, undefined means none specified - /** @internal */ - _getUserIdFromRequestContext(contextUserId) { - return contextUserId; - } - async _callApiUsingInitialToken(options, accessToken, wasRefreshed = false) { - const { authProvider } = this._config; - const { authorizationType } = authProvider; - let response = await this._callApiInternal(options, authProvider.clientId, accessToken.accessToken, authorizationType); - if (response.status === 401 && !wasRefreshed) { - if (accessToken.userId) { - if (authProvider.refreshAccessTokenForUser) { - const token = await authProvider.refreshAccessTokenForUser(accessToken.userId); - response = await this._callApiInternal(options, authProvider.clientId, token.accessToken, authorizationType); - } - } else if (authProvider.getAppAccessToken) { - const token = await authProvider.getAppAccessToken(true); - response = await this._callApiInternal(options, authProvider.clientId, token.accessToken, authorizationType); - } - } - this.emit(this.onRequest, new ApiReportedRequest(options, response.status, accessToken.userId ?? null)); - await handleTwitchApiResponseError(response, options); - return await transformTwitchApiResponse(response); - } - async _callApiInternal(options, clientId, accessToken, authorizationType) { - const { fetchOptions } = this._config; - const type = options.type ?? "helix"; - this._logger.debug(`Calling ${type} API: ${options.method ?? "GET"} ${options.url}`); - this._logger.trace(`Query: ${JSON.stringify(options.query)}`); - if (options.jsonBody) { - this._logger.trace(`Request body: ${JSON.stringify(options.jsonBody)}`); - } - const op = retry.operation({ - retries: 3, - minTimeout: 500, - factor: 2 - }); - const { promise, resolve, reject } = promiseWithResolvers(); - op.attempt(async () => { - try { - const response = type === "helix" ? await this._rateLimiter.request({ - options, - clientId, - accessToken, - authorizationType, - fetchOptions - }) : await callTwitchApiRaw(options, clientId, accessToken, authorizationType, fetchOptions); - if (!response.ok && response.status >= 500 && response.status < 600) { - await handleTwitchApiResponseError(response, options); - } - resolve(response); - } catch (e) { - if (op.retry(e)) { - return; - } - reject(op.mainError()); - } - }); - const result = await promise; - this._logger.debug(`Called ${type} API: ${options.method ?? "GET"} ${options.url} - result: ${result.status}`); - return result; - } -}; -__decorate([ - CachedGetter() -], BaseApiClient.prototype, "bits", null); -__decorate([ - CachedGetter() -], BaseApiClient.prototype, "channels", null); -__decorate([ - CachedGetter() -], BaseApiClient.prototype, "channelPoints", null); -__decorate([ - CachedGetter() -], BaseApiClient.prototype, "charity", null); -__decorate([ - CachedGetter() -], BaseApiClient.prototype, "chat", null); -__decorate([ - CachedGetter() -], BaseApiClient.prototype, "clips", null); -__decorate([ - CachedGetter() -], BaseApiClient.prototype, "contentClassificationLabels", null); -__decorate([ - CachedGetter() -], BaseApiClient.prototype, "entitlements", null); -__decorate([ - CachedGetter() -], BaseApiClient.prototype, "eventSub", null); -__decorate([ - CachedGetter() -], BaseApiClient.prototype, "extensions", null); -__decorate([ - CachedGetter() -], BaseApiClient.prototype, "games", null); -__decorate([ - CachedGetter() -], BaseApiClient.prototype, "hypeTrain", null); -__decorate([ - CachedGetter() -], BaseApiClient.prototype, "goals", null); -__decorate([ - CachedGetter() -], BaseApiClient.prototype, "moderation", null); -__decorate([ - CachedGetter() -], BaseApiClient.prototype, "polls", null); -__decorate([ - CachedGetter() -], BaseApiClient.prototype, "predictions", null); -__decorate([ - CachedGetter() -], BaseApiClient.prototype, "raids", null); -__decorate([ - CachedGetter() -], BaseApiClient.prototype, "schedule", null); -__decorate([ - CachedGetter() -], BaseApiClient.prototype, "search", null); -__decorate([ - CachedGetter() -], BaseApiClient.prototype, "streams", null); -__decorate([ - CachedGetter() -], BaseApiClient.prototype, "subscriptions", null); -__decorate([ - CachedGetter() -], BaseApiClient.prototype, "teams", null); -__decorate([ - CachedGetter() -], BaseApiClient.prototype, "users", null); -__decorate([ - CachedGetter() -], BaseApiClient.prototype, "videos", null); -__decorate([ - CachedGetter() -], BaseApiClient.prototype, "whispers", null); -BaseApiClient = __decorate([ - Cacheable, - rtfm("api", "ApiClient") -], BaseApiClient); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/client/NoContextApiClient.js -init_modules_watch_stub(); -init_performance2(); -var NoContextApiClient = class NoContextApiClient2 extends BaseApiClient { - static { - __name(this, "NoContextApiClient"); - } - /** @internal */ - _getUserIdFromRequestContext() { - return null; - } -}; -NoContextApiClient = __decorate([ - rtfm("api", "ApiClient") -], NoContextApiClient); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/client/UserContextApiClient.js -init_modules_watch_stub(); -init_performance2(); -var UserContextApiClient = class UserContextApiClient2 extends BaseApiClient { - static { - __name(this, "UserContextApiClient"); - } - _userId; - /** @internal */ - constructor(config2, logger, rateLimiter, _userId) { - super(config2, logger, rateLimiter); - this._userId = _userId; - } - /** @internal */ - _getUserIdFromRequestContext() { - return this._userId; - } -}; -UserContextApiClient = __decorate([ - rtfm("api", "ApiClient") -], UserContextApiClient); - -// node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/client/ApiClient.js -var ApiClient2 = class ApiClient3 extends BaseApiClient { - static { - __name(this, "ApiClient"); - } - /** - * Creates a new API client instance. - * - * @param config Configuration for the client instance. - */ - constructor(config2) { - if (!config2.authProvider) { - throw new ConfigError("No auth provider given. Please supply the `authProvider` option."); - } - const rateLimitLoggerOptions = { name: "twurple:api:rate-limiter", ...config2.logger }; - super(config2, createLogger({ name: "twurple:api:client", ...config2.logger }), import_detect_node4.isNode ? new PartitionedRateLimiter({ - getPartitionKey: /* @__PURE__ */ __name((req) => req.userId ?? null, "getPartitionKey"), - createChild: /* @__PURE__ */ __name(() => new HelixRateLimiter({ logger: rateLimitLoggerOptions }), "createChild") - }) : new PartitionedTimeBasedRateLimiter({ - logger: rateLimitLoggerOptions, - bucketSize: 800, - timeFrame: 64e3, - doRequest: /* @__PURE__ */ __name(async ({ options, clientId, accessToken, authorizationType, fetchOptions }) => await callTwitchApiRaw(options, clientId, accessToken, authorizationType, fetchOptions), "doRequest"), - getPartitionKey: /* @__PURE__ */ __name((req) => req.userId ?? null, "getPartitionKey") - })); - } - /** - * Creates a contextualized ApiClient that can be used to call the API in the context of a given user. - * - * @param user The user to use as context. - * @param runner The callback to execute. - * - * A parameter is passed that should be used in place of the normal `ApiClient` - * to ensure that all requests are executed in the given user's context. - * - * Please note that requests which require scope authorization ignore this context. - * - * The return value of your callback will be propagated to the return value of this method. - */ - async asUser(user, runner) { - const ctx = new UserContextApiClient(this._config, this._logger, this._rateLimiter, extractUserId(user)); - return await runner(ctx); - } - /** - * Creates a contextualized ApiClient that can be used to call the API in the context of a given intent. - * - * @param intents A list of intents. The first one that is found in your auth provider will be used. - * @param runner The callback to execute. - * - * A parameter is passed that should be used in place of the normal `ApiClient` - * to ensure that all requests are executed in the given user's context. - * - * Please note that requests which require scope authorization ignore this context. - * - * The return value of your callback will be propagated to the return value of this method. - */ - async asIntent(intents, runner) { - if (!this._authProvider.getAccessTokenForIntent) { - throw new Error("Trying to use intents with an auth provider that does not support them"); - } - for (const intent of intents) { - const user = await this._authProvider.getAccessTokenForIntent(intent); - if (user) { - const ctx = new UserContextApiClient(this._config, this._logger, this._rateLimiter, user.userId); - return await runner(ctx); - } - } - throw new Error(`Intents [${intents.join(", ")}] not found in auth provider`); - } - /** - * Creates a contextualized ApiClient that can be used to call the API without the context of any user. - * - * This usually means that an app access token is used. - * - * @param runner The callback to execute. - * - * A parameter is passed that should be used in place of the normal `ApiClient` - * to ensure that all requests are executed without user context. - * - * Please note that requests which require scope authorization ignore this context erasure. - * - * The return value of your callback will be propagated to the return value of this method. - */ - async withoutUser(runner) { - const ctx = new NoContextApiClient(this._config, this._logger, this._rateLimiter); - return await runner(ctx); - } -}; -ApiClient2 = __decorate([ - rtfm("api", "ApiClient") -], ApiClient2); - -// src/services/twitch.service.ts -var TwitchService = class { - static { - __name(this, "TwitchService"); - } - apiClient; - authProvider; - constructor(env) { - this.authProvider = new AppTokenAuthProvider( - env.TWITCH_CLIENT_ID, - env.TWITCH_CLIENT_SECRET - ); - this.apiClient = new ApiClient2({ authProvider: this.authProvider }); - } - async getUserByLogin(login) { - try { - return await this.apiClient.users.getUserByName(login); - } catch (error) { - return null; - } - } - async getUserById(id) { - try { - return await this.apiClient.users.getUserById(id); - } catch (error) { - return null; - } - } - async getStreamByUserId(userId) { - try { - return await this.apiClient.streams.getStreamByUserId(userId); - } catch (error) { - return null; - } - } - async getGameById(gameId) { - try { - return await this.apiClient.games.getGameById(gameId); - } catch (error) { - return null; - } - } - getApiClient() { - return this.apiClient; - } - getAuthProvider() { - return this.authProvider; - } -}; - -// src/services/telegram.service.ts -init_modules_watch_stub(); -init_performance2(); - -// src/utils/thumbnail.ts -init_modules_watch_stub(); -init_performance2(); -var ThumbnailBuilder = class { - static { - __name(this, "ThumbnailBuilder"); - } - /** - * Build thumbnail URL from Twitch template URL - * @param thumbnailUrl - Twitch thumbnail URL with {width} and {height} placeholders - * @param checkValidity - Whether to check if the URL is accessible (with retry logic) - * @returns Final thumbnail URL - */ - async build(thumbnailUrl, checkValidity = false) { - let thumbnail = thumbnailUrl.replace("{width}", "1920").replace("{height}", "1080"); - if (!checkValidity) { - return thumbnail; - } - const isValid = await this.checkValidity(thumbnail, 0); - if (!isValid) { - thumbnail = thumbnail.replace("1920", "1280").replace("1080", "720"); - } - return thumbnail; - } - /** - * Check if thumbnail URL is accessible with retry logic - * @param url - URL to check - * @param attempt - Current attempt number (max 5) - * @returns Whether the URL is valid - */ - async checkValidity(url, attempt) { - try { - const response = await fetch(url, { - method: "HEAD", - redirect: "manual" - }); - if (response.status === 200) { - return true; - } - if (attempt >= 5) { - return false; - } - await new Promise((resolve) => setTimeout(resolve, 5e3)); - return this.checkValidity(url, attempt + 1); - } catch (error) { - if (attempt >= 5) { - return false; - } - await new Promise((resolve) => setTimeout(resolve, 5e3)); - return this.checkValidity(url, attempt + 1); - } - } -}; - -// src/services/telegram.service.ts -var TelegramService = class { - static { - __name(this, "TelegramService"); - } - bot; - i18n; - thumbnailBuilder; - constructor(env, i18n) { - this.bot = new Bot(env.TELEGRAM_TOKEN); - this.i18n = i18n; - this.thumbnailBuilder = new ThumbnailBuilder(); - } - async sendStreamOnlineNotification(notification) { - const channelLink = `${notification.channelName}`; - const text2 = this.i18n.t(notification.language, "notifications.streams.nowOnline", { - channelLink, - category: notification.category, - title: notification.title - }); - if (notification.showImage && notification.thumbnailUrl) { - try { - const thumbnailUrl = await this.thumbnailBuilder.build(notification.thumbnailUrl, true); - await this.bot.api.sendPhoto(notification.chatId, new InputFile(new URL(thumbnailUrl)), { - caption: text2, - parse_mode: "HTML" - }); - return; - } catch (error) { - console.error("Failed to send photo:", error); - } - } - await this.bot.api.sendMessage(notification.chatId, text2, { - parse_mode: "HTML", - link_preview_options: { is_disabled: false } - }); - } - async sendStreamOfflineNotification(notification) { - const channelLink = `${notification.channelName}`; - const categories = notification.categories.join(", "); - const text2 = this.i18n.t(notification.language, "notifications.streams.nowOffline", { - channelLink, - categories, - duration: notification.duration - }); - await this.bot.api.sendMessage(notification.chatId, text2, { - parse_mode: "HTML", - link_preview_options: { is_disabled: true } - }); - } - async sendCategoryChangeNotification(notification) { - const channelLink = `${notification.channelName}`; - const text2 = this.i18n.t(notification.language, "notifications.streams.newCategory", { - channelLink, - oldCategory: notification.oldCategory, - category: notification.category - }); - await this.bot.api.sendMessage(notification.chatId, text2, { - parse_mode: "HTML", - link_preview_options: { is_disabled: true } - }); - } - async sendTitleChangeNotification(notification) { - const channelLink = `${notification.channelName}`; - const text2 = this.i18n.t(notification.language, "notifications.streams.titleChanged", { - channelLink, - oldTitle: notification.oldTitle, - title: notification.title - }); - await this.bot.api.sendMessage(notification.chatId, text2, { - parse_mode: "HTML", - link_preview_options: { is_disabled: true } - }); - } - async sendTitleAndCategoryChangeNotification(notification) { - const channelLink = `${notification.channelName}`; - const text2 = this.i18n.t(notification.language, "notifications.streams.titleAndCategoryChanged", { - channelLink, - oldTitle: notification.oldTitle, - title: notification.title, - oldCategory: notification.oldCategory, - category: notification.category - }); - await this.bot.api.sendMessage(notification.chatId, text2, { - parse_mode: "HTML", - link_preview_options: { is_disabled: true } - }); - } - getBot() { - return this.bot; - } -}; - -// src/services/eventsub.service.ts -init_modules_watch_stub(); -init_performance2(); -var EventSubService = class { - static { - __name(this, "EventSubService"); - } - apiClient; - webhookUrl; - secret; - constructor(apiClient, env, baseUrl) { - this.apiClient = apiClient; - this.webhookUrl = `${baseUrl}/twitch-webhook`; - this.secret = env.TWITCH_EVENTSUB_SECRET; - } - /** - * Subscribe to all events for a broadcaster (stream.online, stream.offline, channel.update) - */ - async subscribeToChannel(broadcasterId) { - try { - await this.apiClient.eventSub.subscribeToStreamOnlineEvents( - broadcasterId, - { - method: "webhook", - callback: this.webhookUrl, - secret: this.secret - } - ); - await this.apiClient.eventSub.subscribeToStreamOfflineEvents( - broadcasterId, - { - method: "webhook", - callback: this.webhookUrl, - secret: this.secret - } - ); - await this.apiClient.eventSub.subscribeToChannelUpdateEvents( - broadcasterId, - { - method: "webhook", - callback: this.webhookUrl, - secret: this.secret - } - ); - } catch (error) { - console.error(`Failed to subscribe to events for broadcaster ${broadcasterId}:`, error); - throw error; - } - } - /** - * Unsubscribe from all events for a broadcaster - */ - async unsubscribeFromChannel(broadcasterId) { - try { - const subscriptions = await this.apiClient.eventSub.getSubscriptions(); - const broadcasterSubs = subscriptions.data.filter( - (sub) => { - const transportMethod = sub.transport?.callback || sub._transport?.callback; - const broadcastId = sub.condition.broadcaster_user_id; - return transportMethod === this.webhookUrl && broadcastId === broadcasterId; - } - ); - for (const sub of broadcasterSubs) { - await this.apiClient.eventSub.deleteSubscription(sub.id); - } - } catch (error) { - console.error(`Failed to unsubscribe from events for broadcaster ${broadcasterId}:`, error); - throw error; - } - } - /** - * Check if we already have active subscriptions for a broadcaster - */ - async hasActiveSubscriptions(broadcasterId) { - try { - const subscriptions = await this.apiClient.eventSub.getSubscriptions(); - return subscriptions.data.some( - (sub) => { - const transportMethod = sub.transport?.callback || sub._transport?.callback; - const broadcastId = sub.condition.broadcaster_user_id; - return transportMethod === this.webhookUrl && broadcastId === broadcasterId && sub.status === "enabled"; - } - ); - } catch (error) { - console.error(`Failed to check subscriptions for broadcaster ${broadcasterId}:`, error); - return false; - } - } - /** - * Delete a specific subscription by ID - */ - async deleteSubscription(subscriptionId) { - try { - await this.apiClient.eventSub.deleteSubscription(subscriptionId); - } catch (error) { - console.error(`Failed to delete subscription ${subscriptionId}:`, error); - throw error; - } - } - /** - * Get all active subscriptions for our webhook - */ - async getActiveSubscriptions() { - try { - const subscriptions = await this.apiClient.eventSub.getSubscriptions(); - return subscriptions.data.filter((sub) => { - const transportMethod = sub.transport?.callback || sub._transport?.callback; - return transportMethod === this.webhookUrl; - }); - } catch (error) { - console.error("Failed to get active subscriptions:", error); - return []; - } - } -}; - -// src/db/connection.ts -init_modules_watch_stub(); -init_performance2(); -var CloudflareD1Connection = class { - constructor(client) { - this.client = client; - } - static { - __name(this, "CloudflareD1Connection"); - } - getClient() { - return this.client; - } -}; - -// src/db/repository.factory.ts -init_modules_watch_stub(); -init_performance2(); - -// src/db/repositories/drizzle/index.ts -init_modules_watch_stub(); -init_performance2(); - -// src/db/repositories/drizzle/chat.drizzle.repository.ts -init_modules_watch_stub(); -init_performance2(); -import { randomUUID as randomUUID2 } from "node:crypto"; - -// src/db/schema.ts -init_modules_watch_stub(); -init_performance2(); -import { randomUUID } from "node:crypto"; -var chats = sqliteTable("chats", { - id: text("id").primaryKey().$defaultFn(() => randomUUID()), - chatId: text("chat_id").notNull(), - service: text("service", { enum: ["telegram"] }).notNull().default("telegram") -}); -var chatsRelations = relations(chats, ({ one, many }) => ({ - settings: one(chatSettings, { - fields: [chats.id], - references: [chatSettings.chatId] - }), - follows: many(follows) -})); -var chatSettings = sqliteTable("chat_settings", { - id: text("id").primaryKey().$defaultFn(() => randomUUID()), - chatId: text("chat_id").notNull().unique().references(() => chats.id, { onDelete: "cascade" }), - gameChangeNotification: integer("game_change_notification", { mode: "boolean" }).notNull().default(true), - titleChangeNotification: integer("title_change_notification", { mode: "boolean" }).notNull().default(false), - gameAndTitleChangeNotification: integer("game_and_title_change_notification", { mode: "boolean" }).notNull().default(false), - offlineNotification: integer("offline_notification", { mode: "boolean" }).notNull().default(true), - imageInNotification: integer("image_in_notification", { mode: "boolean" }).notNull().default(true), - language: text("language", { enum: ["ru", "en", "uk"] }).notNull().default("en") -}); -var chatSettingsRelations = relations(chatSettings, ({ one }) => ({ - chat: one(chats, { - fields: [chatSettings.chatId], - references: [chats.id] - }) -})); -var channels = sqliteTable("channels", { - id: text("id").primaryKey().$defaultFn(() => randomUUID()), - channelId: text("channel_id").notNull(), - service: text("service", { enum: ["twitch"] }).notNull().default("twitch"), - isLive: integer("is_live", { mode: "boolean" }).notNull().default(false), - title: text("title"), - category: text("category"), - updatedAt: text("updated_at").$defaultFn(() => (/* @__PURE__ */ new Date()).toISOString()) -}); -var channelsRelations = relations(channels, ({ many }) => ({ - follows: many(follows), - streams: many(streams) -})); -var follows = sqliteTable("follows", { - id: text("id").primaryKey().$defaultFn(() => randomUUID()), - channelId: text("channel_id").notNull().references(() => channels.id, { onDelete: "cascade" }), - chatId: text("chat_id").notNull().references(() => chats.id, { onDelete: "cascade" }) -}); -var followsRelations = relations(follows, ({ one }) => ({ - channel: one(channels, { - fields: [follows.channelId], - references: [channels.id] - }), - chat: one(chats, { - fields: [follows.chatId], - references: [chats.id] - }) -})); -var streams = sqliteTable("streams", { - id: text("id").primaryKey(), - // Twitch stream ID - channelId: text("channel_id").notNull().references(() => channels.id, { onDelete: "cascade" }), - isLive: integer("is_live", { mode: "boolean" }).notNull().default(true), - title: text("title"), - category: text("category"), - titles: text("titles", { mode: "json" }).$type().notNull().default([]), - categories: text("categories", { mode: "json" }).$type().notNull().default([]), - startedAt: text("started_at").$defaultFn(() => (/* @__PURE__ */ new Date()).toISOString()), - updatedAt: text("updated_at").$defaultFn(() => (/* @__PURE__ */ new Date()).toISOString()), - endedAt: text("ended_at") -}); -var streamsRelations = relations(streams, ({ one }) => ({ - channel: one(channels, { - fields: [streams.channelId], - references: [channels.id] - }) -})); - -// src/domain/mapper.ts -init_modules_watch_stub(); -init_performance2(); - -// src/domain/models.ts -init_modules_watch_stub(); -init_performance2(); -var Chat = class { - static { - __name(this, "Chat"); - } - id; - chatId; - service; - settings; - follows; - constructor(data2) { - this.id = data2.id; - this.chatId = data2.chatId; - this.service = data2.service; - this.settings = data2.settings; - this.follows = data2.follows; - } -}; -var ChatSettings = class { - static { - __name(this, "ChatSettings"); - } - id; - chatId; - gameChangeNotification; - titleChangeNotification; - gameAndTitleChangeNotification; - offlineNotification; - imageInNotification; - language; - constructor(data2) { - this.id = data2.id; - this.chatId = data2.chatId; - this.gameChangeNotification = data2.gameChangeNotification; - this.titleChangeNotification = data2.titleChangeNotification; - this.gameAndTitleChangeNotification = data2.gameAndTitleChangeNotification; - this.offlineNotification = data2.offlineNotification; - this.imageInNotification = data2.imageInNotification; - this.language = data2.language; - } -}; -var Channel = class { - static { - __name(this, "Channel"); - } - id; - channelId; - service; - isLive; - title; - category; - updatedAt; - follows; - streams; - constructor(data2) { - this.id = data2.id; - this.channelId = data2.channelId; - this.service = data2.service; - this.isLive = data2.isLive; - this.title = data2.title; - this.category = data2.category; - this.updatedAt = data2.updatedAt; - this.follows = data2.follows; - this.streams = data2.streams; - } -}; -var Follow = class { - static { - __name(this, "Follow"); - } - id; - channelId; - chatId; - channel; - chat; - constructor(data2) { - this.id = data2.id; - this.channelId = data2.channelId; - this.chatId = data2.chatId; - this.channel = data2.channel; - this.chat = data2.chat; - } -}; -var Stream = class { - static { - __name(this, "Stream"); - } - id; - channelId; - isLive; - title; - category; - titles; - categories; - startedAt; - updatedAt; - endedAt; - constructor(data2) { - this.id = data2.id; - this.channelId = data2.channelId; - this.isLive = data2.isLive; - this.title = data2.title; - this.category = data2.category; - this.titles = data2.titles; - this.categories = data2.categories; - this.startedAt = data2.startedAt; - this.updatedAt = data2.updatedAt; - this.endedAt = data2.endedAt; - } -}; -var FollowAlreadyExistsError = class extends Error { - static { - __name(this, "FollowAlreadyExistsError"); - } - constructor() { - super("Follow already exists"); - this.name = "FollowAlreadyExistsError"; - } -}; -var FollowNotFoundError = class extends Error { - static { - __name(this, "FollowNotFoundError"); - } - constructor() { - super("Follow not found"); - this.name = "FollowNotFoundError"; - } -}; -var ChannelNotFoundError = class extends Error { - static { - __name(this, "ChannelNotFoundError"); - } - constructor() { - super("Channel not found"); - this.name = "ChannelNotFoundError"; - } -}; - -// src/domain/mapper.ts -var DomainMapper = class { - static { - __name(this, "DomainMapper"); - } - static toDomainChat(dbChat) { - return new Chat({ - id: dbChat.id, - chatId: dbChat.chatId, - service: dbChat.service, - settings: dbChat.settings ? this.toDomainChatSettings(dbChat.settings) : void 0 - }); - } - static toDomainChatSettings(dbSettings) { - return new ChatSettings({ - id: dbSettings.id, - chatId: dbSettings.chatId, - gameChangeNotification: dbSettings.gameChangeNotification, - titleChangeNotification: dbSettings.titleChangeNotification, - gameAndTitleChangeNotification: dbSettings.gameAndTitleChangeNotification, - offlineNotification: dbSettings.offlineNotification, - imageInNotification: dbSettings.imageInNotification, - language: dbSettings.language - }); - } - static toDomainChannel(dbChannel) { - return new Channel({ - id: dbChannel.id, - channelId: dbChannel.channelId, - service: dbChannel.service, - isLive: dbChannel.isLive, - title: dbChannel.title ?? void 0, - category: dbChannel.category ?? void 0, - updatedAt: dbChannel.updatedAt ? new Date(dbChannel.updatedAt) : void 0 - }); - } - static toDomainFollow(dbFollow) { - return new Follow({ - id: dbFollow.id, - channelId: dbFollow.channelId, - chatId: dbFollow.chatId - }); - } - static toDomainStream(dbStream) { - return new Stream({ - id: dbStream.id, - channelId: dbStream.channelId, - isLive: dbStream.isLive, - title: dbStream.title ?? void 0, - category: dbStream.category ?? void 0, - titles: dbStream.titles, - categories: dbStream.categories, - startedAt: new Date(dbStream.startedAt), - updatedAt: dbStream.updatedAt ? new Date(dbStream.updatedAt) : void 0, - endedAt: dbStream.endedAt ? new Date(dbStream.endedAt) : void 0 - }); - } -}; - -// src/db/repositories/drizzle/chat.drizzle.repository.ts -var ChatDrizzleRepository = class { - constructor(db) { - this.db = db; - } - static { - __name(this, "ChatDrizzleRepository"); - } - async findByChatId(chatId, service = "telegram") { - const chatIdStr = chatId.toString(); - const chatResult = await this.db.select().from(chats).where(eq(chats.chatId, chatIdStr)).limit(1); - if (!chatResult[0]) return void 0; - const settingsResult = await this.db.select().from(chatSettings).where(eq(chatSettings.chatId, chatResult[0].id)).limit(1); - return DomainMapper.toDomainChat({ - ...chatResult[0], - settings: settingsResult[0] || null - }); - } - async findById(id) { - const chatResult = await this.db.select().from(chats).where(eq(chats.id, id)).limit(1); - if (!chatResult[0]) return void 0; - const settingsResult = await this.db.select().from(chatSettings).where(eq(chatSettings.chatId, chatResult[0].id)).limit(1); - return DomainMapper.toDomainChat({ - ...chatResult[0], - settings: settingsResult[0] || null - }); - } - async findAllByService(service = "telegram") { - const chatResults = await this.db.select().from(chats).where(eq(chats.service, service)); - const chatsWithSettings = []; - for (const chat of chatResults) { - const settingsResult = await this.db.select().from(chatSettings).where(eq(chatSettings.chatId, chat.id)).limit(1); - chatsWithSettings.push(DomainMapper.toDomainChat({ - ...chat, - settings: settingsResult[0] || null - })); - } - return chatsWithSettings; - } - async create(chatId, service = "telegram") { - const id = randomUUID2(); - await this.db.insert(chats).values({ id, chatId, service }); - await this.db.insert(chatSettings).values({ - chatId: id, - language: "en", - offlineNotification: true, - gameChangeNotification: false, - titleChangeNotification: false, - gameAndTitleChangeNotification: false, - imageInNotification: true - }); - return id; - } - async updateSettings(chatId, settings) { - await this.db.update(chatSettings).set(settings).where(eq(chatSettings.chatId, chatId)); - } -}; - -// src/db/repositories/drizzle/channel.drizzle.repository.ts -init_modules_watch_stub(); -init_performance2(); -import { randomUUID as randomUUID3 } from "node:crypto"; -var ChannelDrizzleRepository = class { - constructor(db) { - this.db = db; - } - static { - __name(this, "ChannelDrizzleRepository"); - } - async findByChannelId(channelId, service = "twitch") { - const result = await this.db.select().from(channels).where(and(eq(channels.channelId, channelId), eq(channels.service, service))).limit(1); - return result[0] ? DomainMapper.toDomainChannel(result[0]) : void 0; - } - async findById(id) { - const result = await this.db.select().from(channels).where(eq(channels.id, id)).limit(1); - return result[0] ? DomainMapper.toDomainChannel(result[0]) : void 0; - } - async create(channelId, service = "twitch") { - const id = randomUUID3(); - const result = await this.db.insert(channels).values({ - id, - channelId, - service, - isLive: false - }).returning(); - return DomainMapper.toDomainChannel(result[0]); - } - async update(id, data2) { - const result = await this.db.update(channels).set({ ...data2, updatedAt: (/* @__PURE__ */ new Date()).toISOString() }).where(eq(channels.id, id)).returning(); - if (!result[0]) { - throw new ChannelNotFoundError(); - } - return DomainMapper.toDomainChannel(result[0]); - } - async updateChannelId(oldChannelId, newChannelId, service = "twitch") { - await this.db.update(channels).set({ channelId: newChannelId, updatedAt: (/* @__PURE__ */ new Date()).toISOString() }).where(and(eq(channels.channelId, oldChannelId), eq(channels.service, service))); - } -}; - -// src/db/repositories/drizzle/follow.drizzle.repository.ts -init_modules_watch_stub(); -init_performance2(); -import { randomUUID as randomUUID4 } from "node:crypto"; -var FollowDrizzleRepository = class { - constructor(db) { - this.db = db; - } - static { - __name(this, "FollowDrizzleRepository"); - } - async findByChatAndChannel(chatId, channelId) { - const result = await this.db.select().from(follows).where(and(eq(follows.chatId, chatId), eq(follows.channelId, channelId))).limit(1); - return result[0] ? DomainMapper.toDomainFollow(result[0]) : void 0; - } - async findByChatId(chatId) { - const results = await this.db.select().from(follows).where(eq(follows.chatId, chatId)); - return results.map((r) => DomainMapper.toDomainFollow(r)); - } - async create(chatId, channelId) { - const existing = await this.findByChatAndChannel(chatId, channelId); - if (existing) { - throw new FollowAlreadyExistsError(); - } - const id = randomUUID4(); - await this.db.insert(follows).values({ id, chatId, channelId }); - return id; - } - async delete(id) { - const result = await this.db.delete(follows).where(eq(follows.id, id)).returning(); - if (result.length === 0) { - throw new FollowNotFoundError(); - } - } - async findByChannelId(channelId) { - const results = await this.db.select().from(follows).where(eq(follows.channelId, channelId)); - return results.map((r) => DomainMapper.toDomainFollow(r)); - } - async findByChatIdPaginated(chatId, limit, offset) { - const results = await this.db.select().from(follows).where(eq(follows.chatId, chatId)).limit(limit).offset(offset); - return results.map((r) => DomainMapper.toDomainFollow(r)); - } - async countByChatId(chatId) { - const result = await this.db.select({ count: count() }).from(follows).where(eq(follows.chatId, chatId)); - return result[0]?.count ?? 0; - } -}; - -// src/db/repositories/drizzle/stream.drizzle.repository.ts -init_modules_watch_stub(); -init_performance2(); -var StreamDrizzleRepository = class { - constructor(db) { - this.db = db; - } - static { - __name(this, "StreamDrizzleRepository"); - } - async findLatestByChannelId(channelId) { - const result = await this.db.select().from(streams).where(eq(streams.channelId, channelId)).orderBy(desc(streams.startedAt)).limit(1); - return result[0] ? DomainMapper.toDomainStream(result[0]) : void 0; - } - async create(id, channelId, category, title2) { - await this.db.insert(streams).values({ - id, - channelId, - isLive: true, - category, - title: title2, - startedAt: (/* @__PURE__ */ new Date()).toISOString(), - titles: [title2], - categories: [category] - }); - return id; - } - async update(id, data2) { - const result = await this.db.update(streams).set(data2).where(eq(streams.id, id)).returning(); - if (!result[0]) { - throw new Error("Stream not found"); - } - return DomainMapper.toDomainStream(result[0]); - } - async findById(id) { - const result = await this.db.select().from(streams).where(eq(streams.id, id)).limit(1); - return result[0] ? DomainMapper.toDomainStream(result[0]) : void 0; - } -}; - -// src/db/repository.factory.ts -var DrizzleRepositoryFactory = class { - constructor(connection) { - this.connection = connection; - } - static { - __name(this, "DrizzleRepositoryFactory"); - } - createChatRepository() { - return new ChatDrizzleRepository(this.connection.getClient()); - } - createChannelRepository() { - return new ChannelDrizzleRepository(this.connection.getClient()); - } - createFollowRepository() { - return new FollowDrizzleRepository(this.connection.getClient()); - } - createStreamRepository() { - return new StreamDrizzleRepository(this.connection.getClient()); - } -}; - -// src/db/repositories/cloudflare-kv/index.ts -init_modules_watch_stub(); -init_performance2(); - -// src/db/repositories/cloudflare-kv/session.kv.repository.ts -init_modules_watch_stub(); -init_performance2(); -var CloudflareKVSessionRepository = class { - constructor(kv) { - this.kv = kv; - } - static { - __name(this, "CloudflareKVSessionRepository"); - } - async get(key) { - const value = await this.kv.get(key); - return value ?? void 0; - } - async set(key, value, expiresAt) { - const options = {}; - if (expiresAt) { - const ttl = Math.floor((expiresAt - Date.now()) / 1e3); - if (ttl > 0) { - options.expirationTtl = ttl; - } - } - await this.kv.put(key, value, options); - } - async delete(key) { - await this.kv.delete(key); - } - async cleanup() { - return; - } -}; - -// src/webhooks/twitch.ts -init_modules_watch_stub(); -init_performance2(); - -// src/services/notification.service.ts -init_modules_watch_stub(); -init_performance2(); -var NotificationService = class { - constructor(env, db, telegramService, twitchService, i18nService, chatRepo, channelRepo, followRepo, streamRepo) { - this.env = env; - this.db = db; - this.telegramService = telegramService; - this.twitchService = twitchService; - this.i18nService = i18nService; - this.chatRepo = chatRepo; - this.channelRepo = channelRepo; - this.followRepo = followRepo; - this.streamRepo = streamRepo; - } - static { - __name(this, "NotificationService"); - } - async handleStreamOnline(data2) { - let channel = await this.channelRepo.findByChannelId(data2.channelId, "twitch"); - if (!channel) { - channel = await this.channelRepo.create(data2.channelId, "twitch"); - } - await this.streamRepo.create( - data2.streamId, - channel.id, - data2.category, - data2.title - ); - const follows2 = await this.followRepo.findByChannelId(channel.id); - for (const follow of follows2) { - try { - const chat = await this.chatRepo.findById(follow.chatId); - if (!chat || !chat.settings) continue; - await this.telegramService.sendStreamOnlineNotification({ - chatId: parseInt(chat.chatId), - language: chat.settings.language, - channelName: data2.channelName, - channelUrl: `https://twitch.tv/${data2.channelName}`, - category: data2.category, - title: data2.title, - thumbnailUrl: data2.thumbnailUrl, - showImage: chat.settings.imageInNotification - }); - } catch (error) { - console.error("Failed to send online notification:", error); - } - } - } - async handleStreamOffline(data2) { - const channel = await this.channelRepo.findByChannelId(data2.channelId, "twitch"); - if (!channel) return; - const stream = await this.streamRepo.findLatestByChannelId(channel.id); - if (!stream || !stream.isLive) return; - await this.streamRepo.update(stream.id, { - isLive: false, - endedAt: (/* @__PURE__ */ new Date()).toISOString() - }); - const follows2 = await this.followRepo.findByChannelId(channel.id); - for (const follow of follows2) { - try { - const chat = await this.chatRepo.findById(follow.chatId); - if (!chat || !chat.settings || !chat.settings.offlineNotification) continue; - const duration = stream.startedAt ? Math.floor((Date.now() - new Date(stream.startedAt).getTime()) / 1e3) : 0; - const hours = Math.floor(duration / 3600); - const minutes = Math.floor(duration % 3600 / 60); - const seconds = duration % 60; - const durationStr = `${hours}h ${minutes}m ${seconds}s`; - await this.telegramService.sendStreamOfflineNotification({ - chatId: parseInt(chat.chatId), - language: chat.settings.language, - channelName: data2.channelName, - channelUrl: `https://twitch.tv/${data2.channelName}`, - categories: stream.categories || [], - duration: durationStr - }); - } catch (error) { - console.error("Failed to send offline notification:", error); - } - } - } - async handleCategoryChange(data2) { - const channel = await this.channelRepo.findByChannelId(data2.channelId, "twitch"); - if (!channel) return; - const stream = await this.streamRepo.findLatestByChannelId(channel.id); - if (!stream || !stream.isLive) return; - const categories = [...stream.categories || [], data2.newCategory]; - await this.streamRepo.update(stream.id, { - category: data2.newCategory, - categories - }); - const follows2 = await this.followRepo.findByChannelId(channel.id); - for (const follow of follows2) { - try { - const chat = await this.chatRepo.findById(follow.chatId); - if (!chat || !chat.settings || !chat.settings.gameChangeNotification) continue; - await this.telegramService.sendCategoryChangeNotification({ - chatId: parseInt(chat.chatId), - language: chat.settings.language, - channelName: data2.channelName, - channelUrl: `https://twitch.tv/${data2.channelName}`, - oldCategory: data2.oldCategory, - category: data2.newCategory - }); - } catch (error) { - console.error("Failed to send category change notification:", error); - } - } - } - async handleTitleChange(data2) { - const channel = await this.channelRepo.findByChannelId(data2.channelId, "twitch"); - if (!channel) return; - const stream = await this.streamRepo.findLatestByChannelId(channel.id); - if (!stream || !stream.isLive) return; - const titles = [...stream.titles || [], data2.newTitle]; - await this.streamRepo.update(stream.id, { - title: data2.newTitle, - titles - }); - const follows2 = await this.followRepo.findByChannelId(channel.id); - for (const follow of follows2) { - try { - const chat = await this.chatRepo.findById(follow.chatId); - if (!chat || !chat.settings || !chat.settings.titleChangeNotification) continue; - await this.telegramService.sendTitleChangeNotification({ - chatId: parseInt(chat.chatId), - language: chat.settings.language, - channelName: data2.channelName, - channelUrl: `https://twitch.tv/${data2.channelName}`, - oldTitle: data2.oldTitle, - title: data2.newTitle - }); - } catch (error) { - console.error("Failed to send title change notification:", error); - } - } - } -}; - -// src/webhooks/twitch.ts -import { createHmac } from "node:crypto"; -async function handleTwitchWebhook(request, env, db) { - try { - const messageId = request.headers.get("Twitch-Eventsub-Message-Id"); - const timestamp = request.headers.get("Twitch-Eventsub-Message-Timestamp"); - const signature = request.headers.get("Twitch-Eventsub-Message-Signature"); - const messageType = request.headers.get("Twitch-Eventsub-Message-Type"); - if (!messageId || !timestamp || !signature) { - return new Response("Missing required headers", { status: 400 }); - } - const body = await request.text(); - const hmac = createHmac("sha256", env.TWITCH_EVENTSUB_SECRET); - hmac.update(messageId + timestamp + body); - const expectedSignature = "sha256=" + hmac.digest("hex"); - if (signature !== expectedSignature) { - return new Response("Invalid signature", { status: 403 }); - } - const payload = JSON.parse(body); - if (messageType === "webhook_callback_verification") { - const verification = payload; - return new Response(verification.challenge, { - status: 200, - headers: { "Content-Type": "text/plain" } - }); - } - if (messageType === "notification") { - const notification = payload; - const i18nService = new I18nService(); - const twitchService = new TwitchService(env); - const telegramService = new TelegramService(env, i18nService); - const dbConnection = new CloudflareD1Connection(db); - const repositoryFactory = new DrizzleRepositoryFactory(dbConnection); - const chatRepo = repositoryFactory.createChatRepository(); - const channelRepo = repositoryFactory.createChannelRepository(); - const followRepo = repositoryFactory.createFollowRepository(); - const streamRepo = repositoryFactory.createStreamRepository(); - const notificationService = new NotificationService( - env, - db, - telegramService, - twitchService, - i18nService, - chatRepo, - channelRepo, - followRepo, - streamRepo - ); - switch (notification.subscription.type) { - case "stream.online": { - const event = notification.event; - const stream = await twitchService.getStreamByUserId(event.broadcaster_user_id); - if (stream) { - await notificationService.handleStreamOnline({ - channelId: event.broadcaster_user_id, - channelName: event.broadcaster_user_name, - streamId: stream.id, - category: stream.gameName, - title: stream.title, - thumbnailUrl: stream.thumbnailUrl - }); - } - break; - } - case "stream.offline": { - const event = notification.event; - await notificationService.handleStreamOffline({ - channelId: event.broadcaster_user_id, - channelName: event.broadcaster_user_name - }); - break; - } - case "channel.update": { - const event = notification.event; - const channel = await channelRepo.findByChannelId(event.broadcaster_user_id, "twitch"); - if (!channel) break; - const stream = await streamRepo.findLatestByChannelId(channel.id); - if (!stream || !stream.isLive) break; - if (stream.category && event.category_name !== stream.category) { - await notificationService.handleCategoryChange({ - channelId: event.broadcaster_user_id, - channelName: event.broadcaster_user_name, - oldCategory: stream.category, - newCategory: event.category_name - }); - } - if (stream.title && event.title !== stream.title) { - await notificationService.handleTitleChange({ - channelId: event.broadcaster_user_id, - channelName: event.broadcaster_user_name, - oldTitle: stream.title, - newTitle: event.title - }); - } - break; - } - } - return new Response("OK", { status: 200 }); - } - if (messageType === "revocation") { - console.log("Subscription revoked:", payload); - return new Response("OK", { status: 200 }); - } - return new Response("Unknown message type", { status: 400 }); - } catch (error) { - console.error("Error handling Twitch webhook:", error); - return new Response("Internal Server Error", { status: 500 }); - } -} -__name(handleTwitchWebhook, "handleTwitchWebhook"); - -// src/index.ts -var app = new Hono2(); -app.get("/", (c) => { - return c.json({ status: "ok", service: "twitch-notifier" }); -}); -app.post("/telegram-webhook", async (c) => { - const env = c.env; - const dbClient = drizzle(env.DB); - const dbConnection = new CloudflareD1Connection(dbClient); - const repositoryFactory = new DrizzleRepositoryFactory(dbConnection); - const chatRepo = repositoryFactory.createChatRepository(); - const channelRepo = repositoryFactory.createChannelRepository(); - const followRepo = repositoryFactory.createFollowRepository(); - const streamRepo = repositoryFactory.createStreamRepository(); - const sessionRepo = new CloudflareKVSessionRepository(env.SESSIONS_KV); - const i18nService = new I18nService(); - await i18nService.init(); - const twitchService = new TwitchService(env); - const telegramService = new TelegramService(env, i18nService); - const eventSubService = new EventSubService( - twitchService.getApiClient(), - env, - env.BASE_URL - ); - const bot = createBot(env, { - i18n: i18nService, - twitch: twitchService, - eventsub: eventSubService, - chatRepo, - channelRepo, - followRepo, - sessionRepo - }); - const handler = webhookCallback(bot, "hono"); - return handler(c); -}); -app.post("/twitch-webhook", async (c) => { - const env = c.env; - const db = drizzle(env.DB); - return await handleTwitchWebhook(c.req.raw, env, db); -}); -var src_default = app; - -// node_modules/.pnpm/wrangler@4.71.0_@cloudflare+workers-types@4.20260307.1/node_modules/wrangler/templates/middleware/middleware-ensure-req-body-drained.ts -init_modules_watch_stub(); -init_performance2(); -var drainBody = /* @__PURE__ */ __name(async (request, env, _ctx, middlewareCtx) => { - try { - return await middlewareCtx.next(request, env); - } finally { - try { - if (request.body !== null && !request.bodyUsed) { - const reader = request.body.getReader(); - while (!(await reader.read()).done) { - } - } - } catch (e) { - console.error("Failed to drain the unused request body.", e); - } - } -}, "drainBody"); -var middleware_ensure_req_body_drained_default = drainBody; - -// node_modules/.pnpm/wrangler@4.71.0_@cloudflare+workers-types@4.20260307.1/node_modules/wrangler/templates/middleware/middleware-miniflare3-json-error.ts -init_modules_watch_stub(); -init_performance2(); -function reduceError(e) { - return { - name: e?.name, - message: e?.message ?? String(e), - stack: e?.stack, - cause: e?.cause === void 0 ? void 0 : reduceError(e.cause) - }; -} -__name(reduceError, "reduceError"); -var jsonError = /* @__PURE__ */ __name(async (request, env, _ctx, middlewareCtx) => { - try { - return await middlewareCtx.next(request, env); - } catch (e) { - const error = reduceError(e); - return Response.json(error, { - status: 500, - headers: { "MF-Experimental-Error-Stack": "true" } - }); - } -}, "jsonError"); -var middleware_miniflare3_json_error_default = jsonError; - -// .wrangler/tmp/bundle-ldhBcJ/middleware-insertion-facade.js -var __INTERNAL_WRANGLER_MIDDLEWARE__ = [ - middleware_ensure_req_body_drained_default, - middleware_miniflare3_json_error_default -]; -var middleware_insertion_facade_default = src_default; - -// node_modules/.pnpm/wrangler@4.71.0_@cloudflare+workers-types@4.20260307.1/node_modules/wrangler/templates/middleware/common.ts -init_modules_watch_stub(); -init_performance2(); -var __facade_middleware__ = []; -function __facade_register__(...args) { - __facade_middleware__.push(...args.flat()); -} -__name(__facade_register__, "__facade_register__"); -function __facade_invokeChain__(request, env, ctx, dispatch, middlewareChain) { - const [head, ...tail] = middlewareChain; - const middlewareCtx = { - dispatch, - next(newRequest, newEnv) { - return __facade_invokeChain__(newRequest, newEnv, ctx, dispatch, tail); - } - }; - return head(request, env, ctx, middlewareCtx); -} -__name(__facade_invokeChain__, "__facade_invokeChain__"); -function __facade_invoke__(request, env, ctx, dispatch, finalMiddleware) { - return __facade_invokeChain__(request, env, ctx, dispatch, [ - ...__facade_middleware__, - finalMiddleware - ]); -} -__name(__facade_invoke__, "__facade_invoke__"); - -// .wrangler/tmp/bundle-ldhBcJ/middleware-loader.entry.ts -var __Facade_ScheduledController__ = class ___Facade_ScheduledController__ { - constructor(scheduledTime, cron, noRetry) { - this.scheduledTime = scheduledTime; - this.cron = cron; - this.#noRetry = noRetry; - } - static { - __name(this, "__Facade_ScheduledController__"); - } - #noRetry; - noRetry() { - if (!(this instanceof ___Facade_ScheduledController__)) { - throw new TypeError("Illegal invocation"); - } - this.#noRetry(); - } -}; -function wrapExportedHandler(worker) { - if (__INTERNAL_WRANGLER_MIDDLEWARE__ === void 0 || __INTERNAL_WRANGLER_MIDDLEWARE__.length === 0) { - return worker; - } - for (const middleware of __INTERNAL_WRANGLER_MIDDLEWARE__) { - __facade_register__(middleware); - } - const fetchDispatcher = /* @__PURE__ */ __name(function(request, env, ctx) { - if (worker.fetch === void 0) { - throw new Error("Handler does not export a fetch() function."); - } - return worker.fetch(request, env, ctx); - }, "fetchDispatcher"); - return { - ...worker, - fetch(request, env, ctx) { - const dispatcher = /* @__PURE__ */ __name(function(type, init2) { - if (type === "scheduled" && worker.scheduled !== void 0) { - const controller = new __Facade_ScheduledController__( - Date.now(), - init2.cron ?? "", - () => { - } - ); - return worker.scheduled(controller, env, ctx); - } - }, "dispatcher"); - return __facade_invoke__(request, env, ctx, dispatcher, fetchDispatcher); - } - }; -} -__name(wrapExportedHandler, "wrapExportedHandler"); -function wrapWorkerEntrypoint(klass) { - if (__INTERNAL_WRANGLER_MIDDLEWARE__ === void 0 || __INTERNAL_WRANGLER_MIDDLEWARE__.length === 0) { - return klass; - } - for (const middleware of __INTERNAL_WRANGLER_MIDDLEWARE__) { - __facade_register__(middleware); - } - return class extends klass { - #fetchDispatcher = /* @__PURE__ */ __name((request, env, ctx) => { - this.env = env; - this.ctx = ctx; - if (super.fetch === void 0) { - throw new Error("Entrypoint class does not define a fetch() function."); - } - return super.fetch(request); - }, "#fetchDispatcher"); - #dispatcher = /* @__PURE__ */ __name((type, init2) => { - if (type === "scheduled" && super.scheduled !== void 0) { - const controller = new __Facade_ScheduledController__( - Date.now(), - init2.cron ?? "", - () => { - } - ); - return super.scheduled(controller); - } - }, "#dispatcher"); - fetch(request) { - return __facade_invoke__( - request, - this.env, - this.ctx, - this.#dispatcher, - this.#fetchDispatcher - ); - } - }; -} -__name(wrapWorkerEntrypoint, "wrapWorkerEntrypoint"); -var WRAPPED_ENTRY; -if (typeof middleware_insertion_facade_default === "object") { - WRAPPED_ENTRY = wrapExportedHandler(middleware_insertion_facade_default); -} else if (typeof middleware_insertion_facade_default === "function") { - WRAPPED_ENTRY = wrapWorkerEntrypoint(middleware_insertion_facade_default); -} -var middleware_loader_entry_default = WRAPPED_ENTRY; -export { - __INTERNAL_WRANGLER_MIDDLEWARE__, - middleware_loader_entry_default as default -}; -//# sourceMappingURL=index.js.map diff --git a/.wrangler/tmp/dev-FVjRI2/index.js.map b/.wrangler/tmp/dev-FVjRI2/index.js.map deleted file mode 100644 index cdc1a00e..00000000 --- a/.wrangler/tmp/dev-FVjRI2/index.js.map +++ /dev/null @@ -1,8 +0,0 @@ -{ - "version": 3, - "sources": ["../../../node_modules/.pnpm/unenv@2.0.0-rc.24/node_modules/unenv/dist/runtime/_internal/utils.mjs", "../../../node_modules/.pnpm/unenv@2.0.0-rc.24/node_modules/unenv/dist/runtime/node/internal/perf_hooks/performance.mjs", "../../../node_modules/.pnpm/unenv@2.0.0-rc.24/node_modules/unenv/dist/runtime/node/perf_hooks.mjs", "../../../node_modules/.pnpm/@cloudflare+unenv-preset@2.15.0_unenv@2.0.0-rc.24_workerd@1.20260301.1/node_modules/@cloudflare/unenv-preset/dist/runtime/polyfill/performance.mjs", "wrangler-modules-watch:wrangler:modules-watch", "../../../node_modules/.pnpm/wrangler@4.71.0_@cloudflare+workers-types@4.20260307.1/node_modules/wrangler/templates/modules-watch-stub.js", "../../../node_modules/.pnpm/@d-fischer+detect-node@3.0.1/node_modules/@d-fischer/detect-node/browser.js", "../../../node_modules/.pnpm/retry@0.13.1/node_modules/retry/lib/retry_operation.js", "../../../node_modules/.pnpm/retry@0.13.1/node_modules/retry/lib/retry.js", "../../../node_modules/.pnpm/retry@0.13.1/node_modules/retry/index.js", "../bundle-ldhBcJ/middleware-loader.entry.ts", "../bundle-ldhBcJ/middleware-insertion-facade.js", "../../../src/index.ts", "../../../node_modules/.pnpm/hono@4.12.5/node_modules/hono/dist/index.js", "../../../node_modules/.pnpm/hono@4.12.5/node_modules/hono/dist/hono.js", "../../../node_modules/.pnpm/hono@4.12.5/node_modules/hono/dist/hono-base.js", "../../../node_modules/.pnpm/hono@4.12.5/node_modules/hono/dist/compose.js", "../../../node_modules/.pnpm/hono@4.12.5/node_modules/hono/dist/context.js", "../../../node_modules/.pnpm/hono@4.12.5/node_modules/hono/dist/request.js", "../../../node_modules/.pnpm/hono@4.12.5/node_modules/hono/dist/http-exception.js", "../../../node_modules/.pnpm/hono@4.12.5/node_modules/hono/dist/request/constants.js", "../../../node_modules/.pnpm/hono@4.12.5/node_modules/hono/dist/utils/body.js", "../../../node_modules/.pnpm/hono@4.12.5/node_modules/hono/dist/utils/url.js", "../../../node_modules/.pnpm/hono@4.12.5/node_modules/hono/dist/utils/html.js", "../../../node_modules/.pnpm/hono@4.12.5/node_modules/hono/dist/router.js", "../../../node_modules/.pnpm/hono@4.12.5/node_modules/hono/dist/utils/constants.js", "../../../node_modules/.pnpm/hono@4.12.5/node_modules/hono/dist/router/reg-exp-router/index.js", "../../../node_modules/.pnpm/hono@4.12.5/node_modules/hono/dist/router/reg-exp-router/router.js", "../../../node_modules/.pnpm/hono@4.12.5/node_modules/hono/dist/router/reg-exp-router/matcher.js", "../../../node_modules/.pnpm/hono@4.12.5/node_modules/hono/dist/router/reg-exp-router/node.js", "../../../node_modules/.pnpm/hono@4.12.5/node_modules/hono/dist/router/reg-exp-router/trie.js", "../../../node_modules/.pnpm/hono@4.12.5/node_modules/hono/dist/router/reg-exp-router/prepared-router.js", "../../../node_modules/.pnpm/hono@4.12.5/node_modules/hono/dist/router/smart-router/index.js", "../../../node_modules/.pnpm/hono@4.12.5/node_modules/hono/dist/router/smart-router/router.js", "../../../node_modules/.pnpm/hono@4.12.5/node_modules/hono/dist/router/trie-router/index.js", "../../../node_modules/.pnpm/hono@4.12.5/node_modules/hono/dist/router/trie-router/router.js", "../../../node_modules/.pnpm/hono@4.12.5/node_modules/hono/dist/router/trie-router/node.js", "../../../node_modules/.pnpm/grammy@1.41.1/node_modules/grammy/out/web.mjs", "../../../node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/src/d1/driver.ts", "../../../node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/src/entity.ts", "../../../node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/src/logger.ts", "../../../node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/src/relations.ts", "../../../node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/src/table.ts", "../../../node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/src/table.utils.ts", "../../../node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/src/column.ts", "../../../node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/src/pg-core/primary-keys.ts", "../../../node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/src/pg-core/table.ts", "../../../node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/src/utils.ts", "../../../node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/src/sql/sql.ts", "../../../node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/src/pg-core/columns/enum.ts", "../../../node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/src/pg-core/columns/common.ts", "../../../node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/src/column-builder.ts", "../../../node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/src/pg-core/foreign-keys.ts", "../../../node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/src/tracing-utils.ts", "../../../node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/src/pg-core/unique-constraint.ts", "../../../node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/src/pg-core/utils/array.ts", "../../../node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/src/subquery.ts", "../../../node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/src/tracing.ts", "../../../node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/drizzle-orm/version.js", "../../../node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/src/view-common.ts", "../../../node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/src/sql/expressions/conditions.ts", "../../../node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/src/sql/expressions/select.ts", "../../../node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/src/sqlite-core/db.ts", "../../../node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/src/selection-proxy.ts", "../../../node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/src/alias.ts", "../../../node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/src/sqlite-core/query-builders/delete.ts", "../../../node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/src/query-promise.ts", "../../../node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/src/sqlite-core/table.ts", "../../../node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/src/sqlite-core/columns/all.ts", "../../../node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/src/sqlite-core/columns/blob.ts", "../../../node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/src/sqlite-core/columns/common.ts", "../../../node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/src/sqlite-core/foreign-keys.ts", "../../../node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/src/sqlite-core/unique-constraint.ts", "../../../node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/src/sqlite-core/columns/custom.ts", "../../../node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/src/sqlite-core/columns/integer.ts", "../../../node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/src/sqlite-core/columns/numeric.ts", "../../../node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/src/sqlite-core/columns/real.ts", "../../../node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/src/sqlite-core/columns/text.ts", "../../../node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/src/sqlite-core/utils.ts", "../../../node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/src/sqlite-core/query-builders/insert.ts", "../../../node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/src/sqlite-core/query-builders/query-builder.ts", "../../../node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/src/sqlite-core/dialect.ts", "../../../node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/src/casing.ts", "../../../node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/src/errors.ts", "../../../node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/src/sql/functions/aggregate.ts", "../../../node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/src/sqlite-core/view-base.ts", "../../../node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/src/sqlite-core/query-builders/select.ts", "../../../node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/src/query-builders/query-builder.ts", "../../../node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/src/sqlite-core/query-builders/update.ts", "../../../node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/src/sqlite-core/query-builders/count.ts", "../../../node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/src/sqlite-core/query-builders/query.ts", "../../../node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/src/sqlite-core/query-builders/raw.ts", "../../../node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/src/d1/session.ts", "../../../node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/src/cache/core/cache.ts", "../../../node_modules/.pnpm/drizzle-orm@0.45.1_@cloudflare+workers-types@4.20260307.1/node_modules/src/sqlite-core/session.ts", "../../../src/bot/index.ts", "../../../src/bot/storage.ts", "../../../src/bot/commands/index.ts", "../../../src/bot/commands/start.command.ts", "../../../src/bot/helpers.ts", "../../../src/bot/commands/follow.command.ts", "../../../src/bot/commands/follows.command.ts", "../../../src/bot/commands/live.command.ts", "../../../src/bot/commands/broadcast.command.ts", "../../../src/bot/commands/change-channel-id.command.ts", "../../../src/bot/commands/callback.handler.ts", "../../../src/services/i18n.service.ts", "../../../node_modules/.pnpm/i18next@25.8.14_typescript@5.9.3/node_modules/i18next/dist/esm/i18next.js", "../../../locales/en.json", "../../../locales/ru.json", "../../../locales/uk.json", "../../../src/services/twitch.service.ts", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/index.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/client/ApiClient.js", "../../../node_modules/.pnpm/tslib@2.8.1/node_modules/tslib/tslib.es6.mjs", "../../../node_modules/.pnpm/@d-fischer+logger@4.2.4/node_modules/@d-fischer/logger/es/index.mjs", "../../../node_modules/.pnpm/@d-fischer+logger@4.2.4/node_modules/@d-fischer/logger/es/createLogger.mjs", "../../../node_modules/.pnpm/@d-fischer+logger@4.2.4/node_modules/@d-fischer/logger/es/BrowserLogger.mjs", "../../../node_modules/.pnpm/@d-fischer+logger@4.2.4/node_modules/@d-fischer/logger/es/LogLevel.mjs", "../../../node_modules/.pnpm/@d-fischer+logger@4.2.4/node_modules/@d-fischer/logger/es/BaseLogger.mjs", "../../../node_modules/.pnpm/@d-fischer+shared-utils@3.6.4/node_modules/@d-fischer/shared-utils/es/index.mjs", "../../../node_modules/.pnpm/@d-fischer+shared-utils@3.6.4/node_modules/@d-fischer/shared-utils/es/decorators/Enumerable.mjs", "../../../node_modules/.pnpm/@d-fischer+shared-utils@3.6.4/node_modules/@d-fischer/shared-utils/es/functions/array/flatten.mjs", "../../../node_modules/.pnpm/@d-fischer+shared-utils@3.6.4/node_modules/@d-fischer/shared-utils/es/functions/object/arrayToObject.mjs", "../../../node_modules/.pnpm/@d-fischer+shared-utils@3.6.4/node_modules/@d-fischer/shared-utils/es/functions/object/indexBy.mjs", "../../../node_modules/.pnpm/@d-fischer+shared-utils@3.6.4/node_modules/@d-fischer/shared-utils/es/functions/optional/mapOptional.mjs", "../../../node_modules/.pnpm/@d-fischer+shared-utils@3.6.4/node_modules/@d-fischer/shared-utils/es/functions/promise/withResolvers.mjs", "../../../node_modules/.pnpm/@d-fischer+logger@4.2.4/node_modules/@d-fischer/logger/es/getMinLogLevelFromEnv.mjs", "../../../node_modules/.pnpm/@d-fischer+logger@4.2.4/node_modules/@d-fischer/logger/es/CustomLoggerWrapper.mjs", "../../../node_modules/.pnpm/@d-fischer+logger@4.2.4/node_modules/@d-fischer/logger/es/NodeLogger.mjs", "../../../node_modules/.pnpm/@d-fischer+rate-limiter@1.1.0/node_modules/@d-fischer/rate-limiter/es/index.mjs", "../../../node_modules/.pnpm/@d-fischer+rate-limiter@1.1.0/node_modules/@d-fischer/rate-limiter/es/errors/RateLimiterDestroyedError.mjs", "../../../node_modules/.pnpm/@d-fischer+rate-limiter@1.1.0/node_modules/@d-fischer/rate-limiter/es/errors/CustomError.mjs", "../../../node_modules/.pnpm/@d-fischer+rate-limiter@1.1.0/node_modules/@d-fischer/rate-limiter/es/errors/RateLimitReachedError.mjs", "../../../node_modules/.pnpm/@d-fischer+rate-limiter@1.1.0/node_modules/@d-fischer/rate-limiter/es/errors/RetryAfterError.mjs", "../../../node_modules/.pnpm/@d-fischer+rate-limiter@1.1.0/node_modules/@d-fischer/rate-limiter/es/limiters/PartitionedRateLimiter.mjs", "../../../node_modules/.pnpm/@d-fischer+rate-limiter@1.1.0/node_modules/@d-fischer/rate-limiter/es/limiters/ResponseBasedRateLimiter.mjs", "../../../node_modules/.pnpm/@d-fischer+rate-limiter@1.1.0/node_modules/@d-fischer/rate-limiter/es/limiters/PartitionedTimeBasedRateLimiter.mjs", "../../../node_modules/.pnpm/@twurple+api-call@8.0.3/node_modules/@twurple/api-call/lib/index.js", "../../../node_modules/.pnpm/@twurple+api-call@8.0.3/node_modules/@twurple/api-call/lib/apiCall.js", "../../../node_modules/.pnpm/@twurple+common@8.0.3/node_modules/@twurple/common/lib/index.js", "../../../node_modules/.pnpm/@twurple+common@8.0.3/node_modules/@twurple/common/lib/DataObject.js", "../../../node_modules/.pnpm/klona@2.0.6/node_modules/klona/dist/index.mjs", "../../../node_modules/.pnpm/@twurple+common@8.0.3/node_modules/@twurple/common/lib/mockApiPort.js", "../../../node_modules/.pnpm/@twurple+common@8.0.3/node_modules/@twurple/common/lib/qs.js", "../../../node_modules/.pnpm/@twurple+common@8.0.3/node_modules/@twurple/common/lib/relations.js", "../../../node_modules/.pnpm/@twurple+common@8.0.3/node_modules/@twurple/common/lib/errors/RelationAssertionError.js", "../../../node_modules/.pnpm/@twurple+common@8.0.3/node_modules/@twurple/common/lib/errors/CustomError.js", "../../../node_modules/.pnpm/@twurple+common@8.0.3/node_modules/@twurple/common/lib/rtfm.js", "../../../node_modules/.pnpm/@twurple+common@8.0.3/node_modules/@twurple/common/lib/extensions/HelixExtension.js", "../../../node_modules/.pnpm/@twurple+common@8.0.3/node_modules/@twurple/common/lib/errors/HellFreezesOverError.js", "../../../node_modules/.pnpm/@twurple+common@8.0.3/node_modules/@twurple/common/lib/userResolvers.js", "../../../node_modules/.pnpm/@twurple+api-call@8.0.3/node_modules/@twurple/api-call/lib/helpers/transform.js", "../../../node_modules/.pnpm/@twurple+api-call@8.0.3/node_modules/@twurple/api-call/lib/errors/HttpStatusCodeError.js", "../../../node_modules/.pnpm/@twurple+api-call@8.0.3/node_modules/@twurple/api-call/lib/helpers/url.js", "../../../node_modules/.pnpm/@twurple+api-call@8.0.3/node_modules/@twurple/api-call/lib/helpers/queries.external.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/errors/ConfigError.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/utils/HelixRateLimiter.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/client/BaseApiClient.js", "../../../node_modules/.pnpm/@d-fischer+cache-decorators@4.0.1/node_modules/@d-fischer/cache-decorators/es/index.mjs", "../../../node_modules/.pnpm/@d-fischer+cache-decorators@4.0.1/node_modules/@d-fischer/cache-decorators/es/decorators/Cacheable.mjs", "../../../node_modules/.pnpm/@d-fischer+cache-decorators@4.0.1/node_modules/@d-fischer/cache-decorators/es/utils/createCacheKey.mjs", "../../../node_modules/.pnpm/@d-fischer+cache-decorators@4.0.1/node_modules/@d-fischer/cache-decorators/es/decorators/CachedGetter.mjs", "../../../node_modules/.pnpm/@d-fischer+typed-event-emitter@3.3.3/node_modules/@d-fischer/typed-event-emitter/es/index.mjs", "../../../node_modules/.pnpm/@d-fischer+typed-event-emitter@3.3.3/node_modules/@d-fischer/typed-event-emitter/es/EventEmitter.mjs", "../../../node_modules/.pnpm/@d-fischer+typed-event-emitter@3.3.3/node_modules/@d-fischer/typed-event-emitter/es/Listener.mjs", "../../../node_modules/.pnpm/@twurple+auth@8.0.3/node_modules/@twurple/auth/lib/index.js", "../../../node_modules/.pnpm/@twurple+auth@8.0.3/node_modules/@twurple/auth/lib/AccessToken.js", "../../../node_modules/.pnpm/@twurple+auth@8.0.3/node_modules/@twurple/auth/lib/helpers.js", "../../../node_modules/.pnpm/@twurple+auth@8.0.3/node_modules/@twurple/auth/lib/errors/InvalidTokenError.js", "../../../node_modules/.pnpm/@twurple+auth@8.0.3/node_modules/@twurple/auth/lib/helpers.external.js", "../../../node_modules/.pnpm/@twurple+auth@8.0.3/node_modules/@twurple/auth/lib/TokenInfo.js", "../../../node_modules/.pnpm/@twurple+auth@8.0.3/node_modules/@twurple/auth/lib/TokenFetcher.js", "../../../node_modules/.pnpm/@twurple+auth@8.0.3/node_modules/@twurple/auth/lib/providers/AppTokenAuthProvider.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/bits/HelixBitsApi.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/interfaces/endpoints/bits.external.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/BaseApi.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/bits/HelixBitsLeaderboard.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/bits/HelixBitsLeaderboardEntry.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/bits/HelixCheermoteList.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/channel/HelixChannelApi.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/interfaces/endpoints/channel.external.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/interfaces/endpoints/generic.external.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/relations/HelixUserRelation.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/utils/HelixRequestBatcher.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/utils/pagination/HelixPaginatedRequest.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/utils/pagination/HelixPaginatedRequestWithTotal.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/utils/pagination/HelixPaginatedResult.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/utils/pagination/HelixPagination.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/channel/HelixChannel.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/channel/HelixChannelEditor.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/channel/HelixChannelFollower.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/channel/HelixFollowedChannel.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/channel/HelixAdSchedule.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/channel/HelixSnoozeNextAdResult.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/channelPoints/HelixChannelPointsApi.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/interfaces/endpoints/channelPoints.external.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/channelPoints/HelixCustomReward.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/channelPoints/HelixCustomRewardRedemption.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/charity/HelixCharityApi.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/charity/HelixCharityCampaign.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/charity/HelixCharityCampaignAmount.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/charity/HelixCharityCampaignDonation.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/chat/HelixChatApi.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/errors/ChatMessageDroppedError.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/interfaces/endpoints/chat.external.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/interfaces/endpoints/shared-chat-session.external.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/chat/HelixChannelEmote.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/chat/HelixEmote.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/chat/HelixEmoteBase.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/chat/HelixChatBadgeSet.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/chat/HelixChatBadgeVersion.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/chat/HelixChatChatter.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/chat/HelixChatSettings.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/chat/HelixEmoteFromSet.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/chat/HelixPrivilegedChatSettings.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/chat/HelixSentChatMessage.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/chat/HelixSharedChatSession.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/chat/HelixSharedChatSessionParticipant.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/chat/HelixUserEmote.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/clip/HelixClipApi.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/interfaces/endpoints/clip.external.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/clip/HelixClip.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/contentClassificationLabels/HelixContentClassificationLabelApi.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/contentClassificationLabels/HelixContentClassificationLabel.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/entitlements/HelixEntitlementApi.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/interfaces/endpoints/entitlement.external.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/entitlements/HelixDropsEntitlement.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/eventSub/HelixEventSubApi.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/interfaces/endpoints/eventSub.external.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/eventSub/HelixEventSubSubscription.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/eventSub/HelixPaginatedEventSubSubscriptionsRequest.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/eventSub/HelixEventSubConduit.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/eventSub/HelixEventSubConduitShard.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/extensions/HelixExtensionsApi.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/interfaces/endpoints/extensions.external.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/channel/HelixChannelReference.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/extensions/HelixExtensionBitsProduct.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/extensions/HelixExtensionTransaction.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/game/HelixGameApi.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/game/HelixGame.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/goals/HelixGoalApi.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/goals/HelixGoal.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/hypeTrain/HelixHypeTrainApi.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/hypeTrain/HelixHypeTrainStatus.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/hypeTrain/HelixHypeTrain.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/hypeTrain/HelixHypeTrainContribution.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/hypeTrain/HelixHypeTrainAllTimeHigh.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/moderation/HelixModerationApi.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/interfaces/endpoints/moderation.external.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/moderation/HelixAutoModSettings.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/moderation/HelixAutoModStatus.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/moderation/HelixBan.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/moderation/HelixBanUser.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/moderation/HelixBlockedTerm.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/moderation/HelixModeratedChannel.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/moderation/HelixModerator.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/moderation/HelixShieldModeStatus.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/moderation/HelixUnbanRequest.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/moderation/HelixWarning.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/poll/HelixPollApi.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/interfaces/endpoints/poll.external.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/poll/HelixPoll.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/poll/HelixPollChoice.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/prediction/HelixPredictionApi.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/interfaces/endpoints/prediction.external.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/prediction/HelixPrediction.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/prediction/HelixPredictionOutcome.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/prediction/HelixPredictor.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/raids/HelixRaidApi.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/interfaces/endpoints/raid.external.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/raids/HelixRaid.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/schedule/HelixScheduleApi.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/interfaces/endpoints/schedule.external.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/schedule/HelixPaginatedScheduleSegmentRequest.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/schedule/HelixScheduleSegment.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/schedule/HelixSchedule.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/search/HelixSearchApi.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/interfaces/endpoints/search.external.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/search/HelixChannelSearchResult.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/stream/HelixStreamApi.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/errors/StreamNotLiveError.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/interfaces/endpoints/stream.external.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/stream/HelixStream.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/stream/HelixStreamMarker.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/stream/HelixStreamMarkerWithVideo.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/subscriptions/HelixSubscriptionApi.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/interfaces/endpoints/subscription.external.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/subscriptions/HelixPaginatedSubscriptionsRequest.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/subscriptions/HelixSubscription.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/subscriptions/HelixUserSubscription.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/team/HelixTeamApi.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/team/HelixTeam.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/team/HelixTeamWithUsers.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/user/HelixUserApi.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/interfaces/endpoints/user.external.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/user/extensions/HelixInstalledExtensionList.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/user/extensions/HelixInstalledExtension.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/user/extensions/HelixBaseExtension.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/user/extensions/HelixUserExtension.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/user/HelixPrivilegedUser.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/user/HelixUser.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/user/HelixUserBlock.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/video/HelixVideoApi.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/video/HelixVideo.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/endpoints/whisper/HelixWhisperApi.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/interfaces/endpoints/whisper.external.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/reporting/ApiReportedRequest.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/client/NoContextApiClient.js", "../../../node_modules/.pnpm/@twurple+api@8.0.3_@twurple+auth@8.0.3/node_modules/@twurple/api/lib/client/UserContextApiClient.js", "../../../src/services/telegram.service.ts", "../../../src/utils/thumbnail.ts", "../../../src/services/eventsub.service.ts", "../../../src/db/connection.ts", "../../../src/db/repository.factory.ts", "../../../src/db/repositories/drizzle/index.ts", "../../../src/db/repositories/drizzle/chat.drizzle.repository.ts", "../../../src/db/schema.ts", "../../../src/domain/mapper.ts", "../../../src/domain/models.ts", "../../../src/db/repositories/drizzle/channel.drizzle.repository.ts", "../../../src/db/repositories/drizzle/follow.drizzle.repository.ts", "../../../src/db/repositories/drizzle/stream.drizzle.repository.ts", "../../../src/db/repositories/cloudflare-kv/index.ts", "../../../src/db/repositories/cloudflare-kv/session.kv.repository.ts", "../../../src/webhooks/twitch.ts", "../../../src/services/notification.service.ts", "../../../node_modules/.pnpm/wrangler@4.71.0_@cloudflare+workers-types@4.20260307.1/node_modules/wrangler/templates/middleware/middleware-ensure-req-body-drained.ts", "../../../node_modules/.pnpm/wrangler@4.71.0_@cloudflare+workers-types@4.20260307.1/node_modules/wrangler/templates/middleware/middleware-miniflare3-json-error.ts", "../../../node_modules/.pnpm/wrangler@4.71.0_@cloudflare+workers-types@4.20260307.1/node_modules/wrangler/templates/middleware/common.ts"], - "sourceRoot": "/home/satont/Projects/twitch-notifier/.wrangler/tmp/dev-FVjRI2", - "sourcesContent": ["/* @__NO_SIDE_EFFECTS__ */\nexport function rawHeaders(headers) {\n\tconst rawHeaders = [];\n\tfor (const key in headers) {\n\t\tif (Array.isArray(headers[key])) {\n\t\t\tfor (const h of headers[key]) {\n\t\t\t\trawHeaders.push(key, h);\n\t\t\t}\n\t\t} else {\n\t\t\trawHeaders.push(key, headers[key]);\n\t\t}\n\t}\n\treturn rawHeaders;\n}\n/* @__NO_SIDE_EFFECTS__ */\nexport function mergeFns(...functions) {\n\treturn function(...args) {\n\t\tfor (const fn of functions) {\n\t\t\tfn(...args);\n\t\t}\n\t};\n}\n/* @__NO_SIDE_EFFECTS__ */\nexport function createNotImplementedError(name) {\n\treturn new Error(`[unenv] ${name} is not implemented yet!`);\n}\n/* @__NO_SIDE_EFFECTS__ */\nexport function notImplemented(name) {\n\tconst fn = () => {\n\t\tthrow createNotImplementedError(name);\n\t};\n\treturn Object.assign(fn, { __unenv__: true });\n}\n/* @__NO_SIDE_EFFECTS__ */\nexport function notImplementedAsync(name) {\n\tconst fn = notImplemented(name);\n\tfn.__promisify__ = () => notImplemented(name + \".__promisify__\");\n\tfn.native = fn;\n\treturn fn;\n}\n/* @__NO_SIDE_EFFECTS__ */\nexport function notImplementedClass(name) {\n\treturn class {\n\t\t__unenv__ = true;\n\t\tconstructor() {\n\t\t\tthrow new Error(`[unenv] ${name} is not implemented yet!`);\n\t\t}\n\t};\n}\n", "import { createNotImplementedError } from \"../../../_internal/utils.mjs\";\nconst _timeOrigin = globalThis.performance?.timeOrigin ?? Date.now();\nconst _performanceNow = globalThis.performance?.now ? globalThis.performance.now.bind(globalThis.performance) : () => Date.now() - _timeOrigin;\nconst nodeTiming = {\n\tname: \"node\",\n\tentryType: \"node\",\n\tstartTime: 0,\n\tduration: 0,\n\tnodeStart: 0,\n\tv8Start: 0,\n\tbootstrapComplete: 0,\n\tenvironment: 0,\n\tloopStart: 0,\n\tloopExit: 0,\n\tidleTime: 0,\n\tuvMetricsInfo: {\n\t\tloopCount: 0,\n\t\tevents: 0,\n\t\teventsWaiting: 0\n\t},\n\tdetail: undefined,\n\ttoJSON() {\n\t\treturn this;\n\t}\n};\n// PerformanceEntry\nexport class PerformanceEntry {\n\t__unenv__ = true;\n\tdetail;\n\tentryType = \"event\";\n\tname;\n\tstartTime;\n\tconstructor(name, options) {\n\t\tthis.name = name;\n\t\tthis.startTime = options?.startTime || _performanceNow();\n\t\tthis.detail = options?.detail;\n\t}\n\tget duration() {\n\t\treturn _performanceNow() - this.startTime;\n\t}\n\ttoJSON() {\n\t\treturn {\n\t\t\tname: this.name,\n\t\t\tentryType: this.entryType,\n\t\t\tstartTime: this.startTime,\n\t\t\tduration: this.duration,\n\t\t\tdetail: this.detail\n\t\t};\n\t}\n}\n// PerformanceMark\nexport const PerformanceMark = class PerformanceMark extends PerformanceEntry {\n\tentryType = \"mark\";\n\tconstructor() {\n\t\t// @ts-ignore\n\t\tsuper(...arguments);\n\t}\n\tget duration() {\n\t\treturn 0;\n\t}\n};\n// PerformanceMark\nexport class PerformanceMeasure extends PerformanceEntry {\n\tentryType = \"measure\";\n}\n// PerformanceResourceTiming\nexport class PerformanceResourceTiming extends PerformanceEntry {\n\tentryType = \"resource\";\n\tserverTiming = [];\n\tconnectEnd = 0;\n\tconnectStart = 0;\n\tdecodedBodySize = 0;\n\tdomainLookupEnd = 0;\n\tdomainLookupStart = 0;\n\tencodedBodySize = 0;\n\tfetchStart = 0;\n\tinitiatorType = \"\";\n\tname = \"\";\n\tnextHopProtocol = \"\";\n\tredirectEnd = 0;\n\tredirectStart = 0;\n\trequestStart = 0;\n\tresponseEnd = 0;\n\tresponseStart = 0;\n\tsecureConnectionStart = 0;\n\tstartTime = 0;\n\ttransferSize = 0;\n\tworkerStart = 0;\n\tresponseStatus = 0;\n}\n// PerformanceObserverEntryList\nexport class PerformanceObserverEntryList {\n\t__unenv__ = true;\n\tgetEntries() {\n\t\treturn [];\n\t}\n\tgetEntriesByName(_name, _type) {\n\t\treturn [];\n\t}\n\tgetEntriesByType(type) {\n\t\treturn [];\n\t}\n}\n// Performance\nexport class Performance {\n\t__unenv__ = true;\n\ttimeOrigin = _timeOrigin;\n\teventCounts = new Map();\n\t_entries = [];\n\t_resourceTimingBufferSize = 0;\n\tnavigation = undefined;\n\ttiming = undefined;\n\ttimerify(_fn, _options) {\n\t\tthrow createNotImplementedError(\"Performance.timerify\");\n\t}\n\tget nodeTiming() {\n\t\treturn nodeTiming;\n\t}\n\teventLoopUtilization() {\n\t\treturn {};\n\t}\n\tmarkResourceTiming() {\n\t\t// TODO: create a new PerformanceResourceTiming entry\n\t\t// so that performance.getEntries, getEntriesByName, and getEntriesByType return it\n\t\t// see: https://nodejs.org/api/perf_hooks.html#performancemarkresourcetimingtiminginfo-requestedurl-initiatortype-global-cachemode-bodyinfo-responsestatus-deliverytype\n\t\treturn new PerformanceResourceTiming(\"\");\n\t}\n\tonresourcetimingbufferfull = null;\n\tnow() {\n\t\t// https://developer.mozilla.org/en-US/docs/Web/API/Performance/now\n\t\tif (this.timeOrigin === _timeOrigin) {\n\t\t\treturn _performanceNow();\n\t\t}\n\t\treturn Date.now() - this.timeOrigin;\n\t}\n\tclearMarks(markName) {\n\t\tthis._entries = markName ? this._entries.filter((e) => e.name !== markName) : this._entries.filter((e) => e.entryType !== \"mark\");\n\t}\n\tclearMeasures(measureName) {\n\t\tthis._entries = measureName ? this._entries.filter((e) => e.name !== measureName) : this._entries.filter((e) => e.entryType !== \"measure\");\n\t}\n\tclearResourceTimings() {\n\t\tthis._entries = this._entries.filter((e) => e.entryType !== \"resource\" || e.entryType !== \"navigation\");\n\t}\n\tgetEntries() {\n\t\treturn this._entries;\n\t}\n\tgetEntriesByName(name, type) {\n\t\treturn this._entries.filter((e) => e.name === name && (!type || e.entryType === type));\n\t}\n\tgetEntriesByType(type) {\n\t\treturn this._entries.filter((e) => e.entryType === type);\n\t}\n\tmark(name, options) {\n\t\t// @ts-expect-error constructor is not protected\n\t\tconst entry = new PerformanceMark(name, options);\n\t\tthis._entries.push(entry);\n\t\treturn entry;\n\t}\n\tmeasure(measureName, startOrMeasureOptions, endMark) {\n\t\tlet start;\n\t\tlet end;\n\t\tif (typeof startOrMeasureOptions === \"string\") {\n\t\t\tstart = this.getEntriesByName(startOrMeasureOptions, \"mark\")[0]?.startTime;\n\t\t\tend = this.getEntriesByName(endMark, \"mark\")[0]?.startTime;\n\t\t} else {\n\t\t\tstart = Number.parseFloat(startOrMeasureOptions?.start) || this.now();\n\t\t\tend = Number.parseFloat(startOrMeasureOptions?.end) || this.now();\n\t\t}\n\t\tconst entry = new PerformanceMeasure(measureName, {\n\t\t\tstartTime: start,\n\t\t\tdetail: {\n\t\t\t\tstart,\n\t\t\t\tend\n\t\t\t}\n\t\t});\n\t\tthis._entries.push(entry);\n\t\treturn entry;\n\t}\n\tsetResourceTimingBufferSize(maxSize) {\n\t\tthis._resourceTimingBufferSize = maxSize;\n\t}\n\taddEventListener(type, listener, options) {\n\t\tthrow createNotImplementedError(\"Performance.addEventListener\");\n\t}\n\tremoveEventListener(type, listener, options) {\n\t\tthrow createNotImplementedError(\"Performance.removeEventListener\");\n\t}\n\tdispatchEvent(event) {\n\t\tthrow createNotImplementedError(\"Performance.dispatchEvent\");\n\t}\n\ttoJSON() {\n\t\treturn this;\n\t}\n}\n// PerformanceObserver\nexport class PerformanceObserver {\n\t__unenv__ = true;\n\tstatic supportedEntryTypes = [];\n\t_callback = null;\n\tconstructor(callback) {\n\t\tthis._callback = callback;\n\t}\n\ttakeRecords() {\n\t\treturn [];\n\t}\n\tdisconnect() {\n\t\tthrow createNotImplementedError(\"PerformanceObserver.disconnect\");\n\t}\n\tobserve(options) {\n\t\tthrow createNotImplementedError(\"PerformanceObserver.observe\");\n\t}\n\tbind(fn) {\n\t\treturn fn;\n\t}\n\trunInAsyncScope(fn, thisArg, ...args) {\n\t\treturn fn.call(thisArg, ...args);\n\t}\n\tasyncId() {\n\t\treturn 0;\n\t}\n\ttriggerAsyncId() {\n\t\treturn 0;\n\t}\n\temitDestroy() {\n\t\treturn this;\n\t}\n}\n// workerd implements a subset of globalThis.performance (as of last check, only timeOrigin set to 0 + now() implemented)\n// We already use performance.now() from globalThis.performance, if provided (see top of this file)\n// If we detect this condition, we can just use polyfill instead.\nexport const performance = globalThis.performance && \"addEventListener\" in globalThis.performance ? globalThis.performance : new Performance();\n", "import { IntervalHistogram, RecordableHistogram } from \"./internal/perf_hooks/histogram.mjs\";\nimport { performance, Performance, PerformanceEntry, PerformanceMark, PerformanceMeasure, PerformanceObserverEntryList, PerformanceObserver, PerformanceResourceTiming } from \"./internal/perf_hooks/performance.mjs\";\nexport * from \"./internal/perf_hooks/performance.mjs\";\n// prettier-ignore\nimport { NODE_PERFORMANCE_GC_MAJOR, NODE_PERFORMANCE_GC_MINOR, NODE_PERFORMANCE_GC_INCREMENTAL, NODE_PERFORMANCE_GC_WEAKCB, NODE_PERFORMANCE_GC_FLAGS_NO, NODE_PERFORMANCE_GC_FLAGS_CONSTRUCT_RETAINED, NODE_PERFORMANCE_GC_FLAGS_FORCED, NODE_PERFORMANCE_GC_FLAGS_SYNCHRONOUS_PHANTOM_PROCESSING, NODE_PERFORMANCE_GC_FLAGS_ALL_AVAILABLE_GARBAGE, NODE_PERFORMANCE_GC_FLAGS_ALL_EXTERNAL_MEMORY, NODE_PERFORMANCE_GC_FLAGS_SCHEDULE_IDLE, NODE_PERFORMANCE_ENTRY_TYPE_GC, NODE_PERFORMANCE_ENTRY_TYPE_HTTP, NODE_PERFORMANCE_ENTRY_TYPE_HTTP2, NODE_PERFORMANCE_ENTRY_TYPE_NET, NODE_PERFORMANCE_ENTRY_TYPE_DNS, NODE_PERFORMANCE_MILESTONE_TIME_ORIGIN_TIMESTAMP, NODE_PERFORMANCE_MILESTONE_TIME_ORIGIN, NODE_PERFORMANCE_MILESTONE_ENVIRONMENT, NODE_PERFORMANCE_MILESTONE_NODE_START, NODE_PERFORMANCE_MILESTONE_V8_START, NODE_PERFORMANCE_MILESTONE_LOOP_START, NODE_PERFORMANCE_MILESTONE_LOOP_EXIT, NODE_PERFORMANCE_MILESTONE_BOOTSTRAP_COMPLETE } from \"./internal/perf_hooks/constants.mjs\";\n// prettier-ignore\nexport const constants = {\n\tNODE_PERFORMANCE_GC_MAJOR,\n\tNODE_PERFORMANCE_GC_MINOR,\n\tNODE_PERFORMANCE_GC_INCREMENTAL,\n\tNODE_PERFORMANCE_GC_WEAKCB,\n\tNODE_PERFORMANCE_GC_FLAGS_NO,\n\tNODE_PERFORMANCE_GC_FLAGS_CONSTRUCT_RETAINED,\n\tNODE_PERFORMANCE_GC_FLAGS_FORCED,\n\tNODE_PERFORMANCE_GC_FLAGS_SYNCHRONOUS_PHANTOM_PROCESSING,\n\tNODE_PERFORMANCE_GC_FLAGS_ALL_AVAILABLE_GARBAGE,\n\tNODE_PERFORMANCE_GC_FLAGS_ALL_EXTERNAL_MEMORY,\n\tNODE_PERFORMANCE_GC_FLAGS_SCHEDULE_IDLE,\n\tNODE_PERFORMANCE_ENTRY_TYPE_GC,\n\tNODE_PERFORMANCE_ENTRY_TYPE_HTTP,\n\tNODE_PERFORMANCE_ENTRY_TYPE_HTTP2,\n\tNODE_PERFORMANCE_ENTRY_TYPE_NET,\n\tNODE_PERFORMANCE_ENTRY_TYPE_DNS,\n\tNODE_PERFORMANCE_MILESTONE_TIME_ORIGIN_TIMESTAMP,\n\tNODE_PERFORMANCE_MILESTONE_TIME_ORIGIN,\n\tNODE_PERFORMANCE_MILESTONE_ENVIRONMENT,\n\tNODE_PERFORMANCE_MILESTONE_NODE_START,\n\tNODE_PERFORMANCE_MILESTONE_V8_START,\n\tNODE_PERFORMANCE_MILESTONE_LOOP_START,\n\tNODE_PERFORMANCE_MILESTONE_LOOP_EXIT,\n\tNODE_PERFORMANCE_MILESTONE_BOOTSTRAP_COMPLETE\n};\nexport const monitorEventLoopDelay = function(_options) {\n\treturn new IntervalHistogram();\n};\nexport const createHistogram = function(_options) {\n\treturn new RecordableHistogram();\n};\nexport default {\n\tPerformance,\n\tPerformanceMark,\n\tPerformanceEntry,\n\tPerformanceMeasure,\n\tPerformanceObserverEntryList,\n\tPerformanceObserver,\n\tPerformanceResourceTiming,\n\tperformance,\n\tconstants,\n\tcreateHistogram,\n\tmonitorEventLoopDelay\n};\n", "import {\n performance,\n Performance,\n PerformanceEntry,\n PerformanceMark,\n PerformanceMeasure,\n PerformanceObserver,\n PerformanceObserverEntryList,\n PerformanceResourceTiming\n} from \"node:perf_hooks\";\nglobalThis.performance = performance;\nglobalThis.Performance = Performance;\nglobalThis.PerformanceEntry = PerformanceEntry;\nglobalThis.PerformanceMark = PerformanceMark;\nglobalThis.PerformanceMeasure = PerformanceMeasure;\nglobalThis.PerformanceObserver = PerformanceObserver;\nglobalThis.PerformanceObserverEntryList = PerformanceObserverEntryList;\nglobalThis.PerformanceResourceTiming = PerformanceResourceTiming;\n", "", "// `esbuild` doesn't support returning `watch*` options from `onStart()`\n// plugin callbacks. Instead, we define an empty virtual module that is\n// imported by this injected file. Importing the module registers watchers.\nimport \"wrangler:modules-watch\";\n", "module.exports.isNode = false;\n\n", "function RetryOperation(timeouts, options) {\n // Compatibility for the old (timeouts, retryForever) signature\n if (typeof options === 'boolean') {\n options = { forever: options };\n }\n\n this._originalTimeouts = JSON.parse(JSON.stringify(timeouts));\n this._timeouts = timeouts;\n this._options = options || {};\n this._maxRetryTime = options && options.maxRetryTime || Infinity;\n this._fn = null;\n this._errors = [];\n this._attempts = 1;\n this._operationTimeout = null;\n this._operationTimeoutCb = null;\n this._timeout = null;\n this._operationStart = null;\n this._timer = null;\n\n if (this._options.forever) {\n this._cachedTimeouts = this._timeouts.slice(0);\n }\n}\nmodule.exports = RetryOperation;\n\nRetryOperation.prototype.reset = function() {\n this._attempts = 1;\n this._timeouts = this._originalTimeouts.slice(0);\n}\n\nRetryOperation.prototype.stop = function() {\n if (this._timeout) {\n clearTimeout(this._timeout);\n }\n if (this._timer) {\n clearTimeout(this._timer);\n }\n\n this._timeouts = [];\n this._cachedTimeouts = null;\n};\n\nRetryOperation.prototype.retry = function(err) {\n if (this._timeout) {\n clearTimeout(this._timeout);\n }\n\n if (!err) {\n return false;\n }\n var currentTime = new Date().getTime();\n if (err && currentTime - this._operationStart >= this._maxRetryTime) {\n this._errors.push(err);\n this._errors.unshift(new Error('RetryOperation timeout occurred'));\n return false;\n }\n\n this._errors.push(err);\n\n var timeout = this._timeouts.shift();\n if (timeout === undefined) {\n if (this._cachedTimeouts) {\n // retry forever, only keep last error\n this._errors.splice(0, this._errors.length - 1);\n timeout = this._cachedTimeouts.slice(-1);\n } else {\n return false;\n }\n }\n\n var self = this;\n this._timer = setTimeout(function() {\n self._attempts++;\n\n if (self._operationTimeoutCb) {\n self._timeout = setTimeout(function() {\n self._operationTimeoutCb(self._attempts);\n }, self._operationTimeout);\n\n if (self._options.unref) {\n self._timeout.unref();\n }\n }\n\n self._fn(self._attempts);\n }, timeout);\n\n if (this._options.unref) {\n this._timer.unref();\n }\n\n return true;\n};\n\nRetryOperation.prototype.attempt = function(fn, timeoutOps) {\n this._fn = fn;\n\n if (timeoutOps) {\n if (timeoutOps.timeout) {\n this._operationTimeout = timeoutOps.timeout;\n }\n if (timeoutOps.cb) {\n this._operationTimeoutCb = timeoutOps.cb;\n }\n }\n\n var self = this;\n if (this._operationTimeoutCb) {\n this._timeout = setTimeout(function() {\n self._operationTimeoutCb();\n }, self._operationTimeout);\n }\n\n this._operationStart = new Date().getTime();\n\n this._fn(this._attempts);\n};\n\nRetryOperation.prototype.try = function(fn) {\n console.log('Using RetryOperation.try() is deprecated');\n this.attempt(fn);\n};\n\nRetryOperation.prototype.start = function(fn) {\n console.log('Using RetryOperation.start() is deprecated');\n this.attempt(fn);\n};\n\nRetryOperation.prototype.start = RetryOperation.prototype.try;\n\nRetryOperation.prototype.errors = function() {\n return this._errors;\n};\n\nRetryOperation.prototype.attempts = function() {\n return this._attempts;\n};\n\nRetryOperation.prototype.mainError = function() {\n if (this._errors.length === 0) {\n return null;\n }\n\n var counts = {};\n var mainError = null;\n var mainErrorCount = 0;\n\n for (var i = 0; i < this._errors.length; i++) {\n var error = this._errors[i];\n var message = error.message;\n var count = (counts[message] || 0) + 1;\n\n counts[message] = count;\n\n if (count >= mainErrorCount) {\n mainError = error;\n mainErrorCount = count;\n }\n }\n\n return mainError;\n};\n", "var RetryOperation = require('./retry_operation');\n\nexports.operation = function(options) {\n var timeouts = exports.timeouts(options);\n return new RetryOperation(timeouts, {\n forever: options && (options.forever || options.retries === Infinity),\n unref: options && options.unref,\n maxRetryTime: options && options.maxRetryTime\n });\n};\n\nexports.timeouts = function(options) {\n if (options instanceof Array) {\n return [].concat(options);\n }\n\n var opts = {\n retries: 10,\n factor: 2,\n minTimeout: 1 * 1000,\n maxTimeout: Infinity,\n randomize: false\n };\n for (var key in options) {\n opts[key] = options[key];\n }\n\n if (opts.minTimeout > opts.maxTimeout) {\n throw new Error('minTimeout is greater than maxTimeout');\n }\n\n var timeouts = [];\n for (var i = 0; i < opts.retries; i++) {\n timeouts.push(this.createTimeout(i, opts));\n }\n\n if (options && options.forever && !timeouts.length) {\n timeouts.push(this.createTimeout(i, opts));\n }\n\n // sort the array numerically ascending\n timeouts.sort(function(a,b) {\n return a - b;\n });\n\n return timeouts;\n};\n\nexports.createTimeout = function(attempt, opts) {\n var random = (opts.randomize)\n ? (Math.random() + 1)\n : 1;\n\n var timeout = Math.round(random * Math.max(opts.minTimeout, 1) * Math.pow(opts.factor, attempt));\n timeout = Math.min(timeout, opts.maxTimeout);\n\n return timeout;\n};\n\nexports.wrap = function(obj, options, methods) {\n if (options instanceof Array) {\n methods = options;\n options = null;\n }\n\n if (!methods) {\n methods = [];\n for (var key in obj) {\n if (typeof obj[key] === 'function') {\n methods.push(key);\n }\n }\n }\n\n for (var i = 0; i < methods.length; i++) {\n var method = methods[i];\n var original = obj[method];\n\n obj[method] = function retryWrapper(original) {\n var op = exports.operation(options);\n var args = Array.prototype.slice.call(arguments, 1);\n var callback = args.pop();\n\n args.push(function(err) {\n if (op.retry(err)) {\n return;\n }\n if (err) {\n arguments[0] = op.mainError();\n }\n callback.apply(this, arguments);\n });\n\n op.attempt(function() {\n original.apply(obj, args);\n });\n }.bind(obj, original);\n obj[method].options = options;\n }\n};\n", "module.exports = require('./lib/retry');", "// This loads all middlewares exposed on the middleware object and then starts\n// the invocation chain. The big idea is that we can add these to the middleware\n// export dynamically through wrangler, or we can potentially let users directly\n// add them as a sort of \"plugin\" system.\n\nimport ENTRY, { __INTERNAL_WRANGLER_MIDDLEWARE__ } from \"/home/satont/Projects/twitch-notifier/.wrangler/tmp/bundle-ldhBcJ/middleware-insertion-facade.js\";\nimport { __facade_invoke__, __facade_register__, Dispatcher } from \"/home/satont/Projects/twitch-notifier/node_modules/.pnpm/wrangler@4.71.0_@cloudflare+workers-types@4.20260307.1/node_modules/wrangler/templates/middleware/common.ts\";\nimport type { WorkerEntrypointConstructor } from \"/home/satont/Projects/twitch-notifier/.wrangler/tmp/bundle-ldhBcJ/middleware-insertion-facade.js\";\n\n// Preserve all the exports from the worker\nexport * from \"/home/satont/Projects/twitch-notifier/.wrangler/tmp/bundle-ldhBcJ/middleware-insertion-facade.js\";\n\nclass __Facade_ScheduledController__ implements ScheduledController {\n\treadonly #noRetry: ScheduledController[\"noRetry\"];\n\n\tconstructor(\n\t\treadonly scheduledTime: number,\n\t\treadonly cron: string,\n\t\tnoRetry: ScheduledController[\"noRetry\"]\n\t) {\n\t\tthis.#noRetry = noRetry;\n\t}\n\n\tnoRetry() {\n\t\tif (!(this instanceof __Facade_ScheduledController__)) {\n\t\t\tthrow new TypeError(\"Illegal invocation\");\n\t\t}\n\t\t// Need to call native method immediately in case uncaught error thrown\n\t\tthis.#noRetry();\n\t}\n}\n\nfunction wrapExportedHandler(worker: ExportedHandler): ExportedHandler {\n\t// If we don't have any middleware defined, just return the handler as is\n\tif (\n\t\t__INTERNAL_WRANGLER_MIDDLEWARE__ === undefined ||\n\t\t__INTERNAL_WRANGLER_MIDDLEWARE__.length === 0\n\t) {\n\t\treturn worker;\n\t}\n\t// Otherwise, register all middleware once\n\tfor (const middleware of __INTERNAL_WRANGLER_MIDDLEWARE__) {\n\t\t__facade_register__(middleware);\n\t}\n\n\tconst fetchDispatcher: ExportedHandlerFetchHandler = function (\n\t\trequest,\n\t\tenv,\n\t\tctx\n\t) {\n\t\tif (worker.fetch === undefined) {\n\t\t\tthrow new Error(\"Handler does not export a fetch() function.\");\n\t\t}\n\t\treturn worker.fetch(request, env, ctx);\n\t};\n\n\treturn {\n\t\t...worker,\n\t\tfetch(request, env, ctx) {\n\t\t\tconst dispatcher: Dispatcher = function (type, init) {\n\t\t\t\tif (type === \"scheduled\" && worker.scheduled !== undefined) {\n\t\t\t\t\tconst controller = new __Facade_ScheduledController__(\n\t\t\t\t\t\tDate.now(),\n\t\t\t\t\t\tinit.cron ?? \"\",\n\t\t\t\t\t\t() => {}\n\t\t\t\t\t);\n\t\t\t\t\treturn worker.scheduled(controller, env, ctx);\n\t\t\t\t}\n\t\t\t};\n\t\t\treturn __facade_invoke__(request, env, ctx, dispatcher, fetchDispatcher);\n\t\t},\n\t};\n}\n\nfunction wrapWorkerEntrypoint(\n\tklass: WorkerEntrypointConstructor\n): WorkerEntrypointConstructor {\n\t// If we don't have any middleware defined, just return the handler as is\n\tif (\n\t\t__INTERNAL_WRANGLER_MIDDLEWARE__ === undefined ||\n\t\t__INTERNAL_WRANGLER_MIDDLEWARE__.length === 0\n\t) {\n\t\treturn klass;\n\t}\n\t// Otherwise, register all middleware once\n\tfor (const middleware of __INTERNAL_WRANGLER_MIDDLEWARE__) {\n\t\t__facade_register__(middleware);\n\t}\n\n\t// `extend`ing `klass` here so other RPC methods remain callable\n\treturn class extends klass {\n\t\t#fetchDispatcher: ExportedHandlerFetchHandler> = (\n\t\t\trequest,\n\t\t\tenv,\n\t\t\tctx\n\t\t) => {\n\t\t\tthis.env = env;\n\t\t\tthis.ctx = ctx;\n\t\t\tif (super.fetch === undefined) {\n\t\t\t\tthrow new Error(\"Entrypoint class does not define a fetch() function.\");\n\t\t\t}\n\t\t\treturn super.fetch(request);\n\t\t};\n\n\t\t#dispatcher: Dispatcher = (type, init) => {\n\t\t\tif (type === \"scheduled\" && super.scheduled !== undefined) {\n\t\t\t\tconst controller = new __Facade_ScheduledController__(\n\t\t\t\t\tDate.now(),\n\t\t\t\t\tinit.cron ?? \"\",\n\t\t\t\t\t() => {}\n\t\t\t\t);\n\t\t\t\treturn super.scheduled(controller);\n\t\t\t}\n\t\t};\n\n\t\tfetch(request: Request) {\n\t\t\treturn __facade_invoke__(\n\t\t\t\trequest,\n\t\t\t\tthis.env,\n\t\t\t\tthis.ctx,\n\t\t\t\tthis.#dispatcher,\n\t\t\t\tthis.#fetchDispatcher\n\t\t\t);\n\t\t}\n\t};\n}\n\nlet WRAPPED_ENTRY: ExportedHandler | WorkerEntrypointConstructor | undefined;\nif (typeof ENTRY === \"object\") {\n\tWRAPPED_ENTRY = wrapExportedHandler(ENTRY);\n} else if (typeof ENTRY === \"function\") {\n\tWRAPPED_ENTRY = wrapWorkerEntrypoint(ENTRY);\n}\nexport default WRAPPED_ENTRY;\n", "\t\t\t\timport worker, * as OTHER_EXPORTS from \"/home/satont/Projects/twitch-notifier/src/index.ts\";\n\t\t\t\timport * as __MIDDLEWARE_0__ from \"/home/satont/Projects/twitch-notifier/node_modules/.pnpm/wrangler@4.71.0_@cloudflare+workers-types@4.20260307.1/node_modules/wrangler/templates/middleware/middleware-ensure-req-body-drained.ts\";\nimport * as __MIDDLEWARE_1__ from \"/home/satont/Projects/twitch-notifier/node_modules/.pnpm/wrangler@4.71.0_@cloudflare+workers-types@4.20260307.1/node_modules/wrangler/templates/middleware/middleware-miniflare3-json-error.ts\";\n\n\t\t\t\texport * from \"/home/satont/Projects/twitch-notifier/src/index.ts\";\n\t\t\t\tconst MIDDLEWARE_TEST_INJECT = \"__INJECT_FOR_TESTING_WRANGLER_MIDDLEWARE__\";\n\t\t\t\texport const __INTERNAL_WRANGLER_MIDDLEWARE__ = [\n\t\t\t\t\t\n\t\t\t\t\t__MIDDLEWARE_0__.default,__MIDDLEWARE_1__.default\n\t\t\t\t]\n\t\t\t\texport default worker;", "import { Hono } from 'hono';\nimport { webhookCallback } from 'grammy';\nimport { drizzle } from 'drizzle-orm/d1';\nimport type { Env } from './types';\nimport { createBot } from './bot';\nimport { I18nService } from './services/i18n.service';\nimport { TwitchService } from './services/twitch.service';\nimport { TelegramService } from './services/telegram.service';\nimport { EventSubService } from './services/eventsub.service';\nimport { CloudflareD1Connection } from './db/connection';\nimport { DrizzleRepositoryFactory } from './db/repository.factory';\nimport { CloudflareKVSessionRepository } from './db/repositories/cloudflare-kv';\nimport { handleTwitchWebhook } from './webhooks/twitch';\n\nconst app = new Hono<{ Bindings: Env }>();\n\n// Health check\napp.get('/', (c) => {\n return c.json({ status: 'ok', service: 'twitch-notifier' });\n});\n\n// Telegram webhook endpoint\napp.post('/telegram-webhook', async (c) => {\n const env = c.env;\n\n // Create database connection (serverless-agnostic)\n const dbClient = drizzle(env.DB);\n const dbConnection = new CloudflareD1Connection(dbClient);\n\n // Create repository factory\n const repositoryFactory = new DrizzleRepositoryFactory(dbConnection);\n\n // Create repositories\n const chatRepo = repositoryFactory.createChatRepository();\n const channelRepo = repositoryFactory.createChannelRepository();\n const followRepo = repositoryFactory.createFollowRepository();\n const streamRepo = repositoryFactory.createStreamRepository();\n\n // Create session repository using Cloudflare KV\n const sessionRepo = new CloudflareKVSessionRepository(env.SESSIONS_KV);\n\n // Initialize services\n const i18nService = new I18nService();\n await i18nService.init(); // Initialize i18next\n const twitchService = new TwitchService(env);\n const telegramService = new TelegramService(env, i18nService);\n const eventSubService = new EventSubService(\n twitchService.getApiClient(),\n env,\n env.BASE_URL\n );\n\n // Create bot instance\n const bot = createBot(env, {\n i18n: i18nService,\n twitch: twitchService,\n eventsub: eventSubService,\n chatRepo,\n channelRepo,\n followRepo,\n sessionRepo,\n });\n\n // Handle webhook\n const handler = webhookCallback(bot, 'hono');\n return handler(c);\n});\n\n// Twitch EventSub webhook endpoint\napp.post('/twitch-webhook', async (c) => {\n const env = c.env;\n const db = drizzle(env.DB);\n\n return await handleTwitchWebhook(c.req.raw, env, db);\n});\n\nexport default app;\n", "// src/index.ts\nimport { Hono } from \"./hono.js\";\nexport {\n Hono\n};\n", "// src/hono.ts\nimport { HonoBase } from \"./hono-base.js\";\nimport { RegExpRouter } from \"./router/reg-exp-router/index.js\";\nimport { SmartRouter } from \"./router/smart-router/index.js\";\nimport { TrieRouter } from \"./router/trie-router/index.js\";\nvar Hono = class extends HonoBase {\n /**\n * Creates an instance of the Hono class.\n *\n * @param options - Optional configuration options for the Hono instance.\n */\n constructor(options = {}) {\n super(options);\n this.router = options.router ?? new SmartRouter({\n routers: [new RegExpRouter(), new TrieRouter()]\n });\n }\n};\nexport {\n Hono\n};\n", "// src/hono-base.ts\nimport { compose } from \"./compose.js\";\nimport { Context } from \"./context.js\";\nimport { METHODS, METHOD_NAME_ALL, METHOD_NAME_ALL_LOWERCASE } from \"./router.js\";\nimport { COMPOSED_HANDLER } from \"./utils/constants.js\";\nimport { getPath, getPathNoStrict, mergePath } from \"./utils/url.js\";\nvar notFoundHandler = (c) => {\n return c.text(\"404 Not Found\", 404);\n};\nvar errorHandler = (err, c) => {\n if (\"getResponse\" in err) {\n const res = err.getResponse();\n return c.newResponse(res.body, res);\n }\n console.error(err);\n return c.text(\"Internal Server Error\", 500);\n};\nvar Hono = class _Hono {\n get;\n post;\n put;\n delete;\n options;\n patch;\n all;\n on;\n use;\n /*\n This class is like an abstract class and does not have a router.\n To use it, inherit the class and implement router in the constructor.\n */\n router;\n getPath;\n // Cannot use `#` because it requires visibility at JavaScript runtime.\n _basePath = \"/\";\n #path = \"/\";\n routes = [];\n constructor(options = {}) {\n const allMethods = [...METHODS, METHOD_NAME_ALL_LOWERCASE];\n allMethods.forEach((method) => {\n this[method] = (args1, ...args) => {\n if (typeof args1 === \"string\") {\n this.#path = args1;\n } else {\n this.#addRoute(method, this.#path, args1);\n }\n args.forEach((handler) => {\n this.#addRoute(method, this.#path, handler);\n });\n return this;\n };\n });\n this.on = (method, path, ...handlers) => {\n for (const p of [path].flat()) {\n this.#path = p;\n for (const m of [method].flat()) {\n handlers.map((handler) => {\n this.#addRoute(m.toUpperCase(), this.#path, handler);\n });\n }\n }\n return this;\n };\n this.use = (arg1, ...handlers) => {\n if (typeof arg1 === \"string\") {\n this.#path = arg1;\n } else {\n this.#path = \"*\";\n handlers.unshift(arg1);\n }\n handlers.forEach((handler) => {\n this.#addRoute(METHOD_NAME_ALL, this.#path, handler);\n });\n return this;\n };\n const { strict, ...optionsWithoutStrict } = options;\n Object.assign(this, optionsWithoutStrict);\n this.getPath = strict ?? true ? options.getPath ?? getPath : getPathNoStrict;\n }\n #clone() {\n const clone = new _Hono({\n router: this.router,\n getPath: this.getPath\n });\n clone.errorHandler = this.errorHandler;\n clone.#notFoundHandler = this.#notFoundHandler;\n clone.routes = this.routes;\n return clone;\n }\n #notFoundHandler = notFoundHandler;\n // Cannot use `#` because it requires visibility at JavaScript runtime.\n errorHandler = errorHandler;\n /**\n * `.route()` allows grouping other Hono instance in routes.\n *\n * @see {@link https://hono.dev/docs/api/routing#grouping}\n *\n * @param {string} path - base Path\n * @param {Hono} app - other Hono instance\n * @returns {Hono} routed Hono instance\n *\n * @example\n * ```ts\n * const app = new Hono()\n * const app2 = new Hono()\n *\n * app2.get(\"/user\", (c) => c.text(\"user\"))\n * app.route(\"/api\", app2) // GET /api/user\n * ```\n */\n route(path, app) {\n const subApp = this.basePath(path);\n app.routes.map((r) => {\n let handler;\n if (app.errorHandler === errorHandler) {\n handler = r.handler;\n } else {\n handler = async (c, next) => (await compose([], app.errorHandler)(c, () => r.handler(c, next))).res;\n handler[COMPOSED_HANDLER] = r.handler;\n }\n subApp.#addRoute(r.method, r.path, handler);\n });\n return this;\n }\n /**\n * `.basePath()` allows base paths to be specified.\n *\n * @see {@link https://hono.dev/docs/api/routing#base-path}\n *\n * @param {string} path - base Path\n * @returns {Hono} changed Hono instance\n *\n * @example\n * ```ts\n * const api = new Hono().basePath('/api')\n * ```\n */\n basePath(path) {\n const subApp = this.#clone();\n subApp._basePath = mergePath(this._basePath, path);\n return subApp;\n }\n /**\n * `.onError()` handles an error and returns a customized Response.\n *\n * @see {@link https://hono.dev/docs/api/hono#error-handling}\n *\n * @param {ErrorHandler} handler - request Handler for error\n * @returns {Hono} changed Hono instance\n *\n * @example\n * ```ts\n * app.onError((err, c) => {\n * console.error(`${err}`)\n * return c.text('Custom Error Message', 500)\n * })\n * ```\n */\n onError = (handler) => {\n this.errorHandler = handler;\n return this;\n };\n /**\n * `.notFound()` allows you to customize a Not Found Response.\n *\n * @see {@link https://hono.dev/docs/api/hono#not-found}\n *\n * @param {NotFoundHandler} handler - request handler for not-found\n * @returns {Hono} changed Hono instance\n *\n * @example\n * ```ts\n * app.notFound((c) => {\n * return c.text('Custom 404 Message', 404)\n * })\n * ```\n */\n notFound = (handler) => {\n this.#notFoundHandler = handler;\n return this;\n };\n /**\n * `.mount()` allows you to mount applications built with other frameworks into your Hono application.\n *\n * @see {@link https://hono.dev/docs/api/hono#mount}\n *\n * @param {string} path - base Path\n * @param {Function} applicationHandler - other Request Handler\n * @param {MountOptions} [options] - options of `.mount()`\n * @returns {Hono} mounted Hono instance\n *\n * @example\n * ```ts\n * import { Router as IttyRouter } from 'itty-router'\n * import { Hono } from 'hono'\n * // Create itty-router application\n * const ittyRouter = IttyRouter()\n * // GET /itty-router/hello\n * ittyRouter.get('/hello', () => new Response('Hello from itty-router'))\n *\n * const app = new Hono()\n * app.mount('/itty-router', ittyRouter.handle)\n * ```\n *\n * @example\n * ```ts\n * const app = new Hono()\n * // Send the request to another application without modification.\n * app.mount('/app', anotherApp, {\n * replaceRequest: (req) => req,\n * })\n * ```\n */\n mount(path, applicationHandler, options) {\n let replaceRequest;\n let optionHandler;\n if (options) {\n if (typeof options === \"function\") {\n optionHandler = options;\n } else {\n optionHandler = options.optionHandler;\n if (options.replaceRequest === false) {\n replaceRequest = (request) => request;\n } else {\n replaceRequest = options.replaceRequest;\n }\n }\n }\n const getOptions = optionHandler ? (c) => {\n const options2 = optionHandler(c);\n return Array.isArray(options2) ? options2 : [options2];\n } : (c) => {\n let executionContext = void 0;\n try {\n executionContext = c.executionCtx;\n } catch {\n }\n return [c.env, executionContext];\n };\n replaceRequest ||= (() => {\n const mergedPath = mergePath(this._basePath, path);\n const pathPrefixLength = mergedPath === \"/\" ? 0 : mergedPath.length;\n return (request) => {\n const url = new URL(request.url);\n url.pathname = url.pathname.slice(pathPrefixLength) || \"/\";\n return new Request(url, request);\n };\n })();\n const handler = async (c, next) => {\n const res = await applicationHandler(replaceRequest(c.req.raw), ...getOptions(c));\n if (res) {\n return res;\n }\n await next();\n };\n this.#addRoute(METHOD_NAME_ALL, mergePath(path, \"*\"), handler);\n return this;\n }\n #addRoute(method, path, handler) {\n method = method.toUpperCase();\n path = mergePath(this._basePath, path);\n const r = { basePath: this._basePath, path, method, handler };\n this.router.add(method, path, [handler, r]);\n this.routes.push(r);\n }\n #handleError(err, c) {\n if (err instanceof Error) {\n return this.errorHandler(err, c);\n }\n throw err;\n }\n #dispatch(request, executionCtx, env, method) {\n if (method === \"HEAD\") {\n return (async () => new Response(null, await this.#dispatch(request, executionCtx, env, \"GET\")))();\n }\n const path = this.getPath(request, { env });\n const matchResult = this.router.match(method, path);\n const c = new Context(request, {\n path,\n matchResult,\n env,\n executionCtx,\n notFoundHandler: this.#notFoundHandler\n });\n if (matchResult[0].length === 1) {\n let res;\n try {\n res = matchResult[0][0][0][0](c, async () => {\n c.res = await this.#notFoundHandler(c);\n });\n } catch (err) {\n return this.#handleError(err, c);\n }\n return res instanceof Promise ? res.then(\n (resolved) => resolved || (c.finalized ? c.res : this.#notFoundHandler(c))\n ).catch((err) => this.#handleError(err, c)) : res ?? this.#notFoundHandler(c);\n }\n const composed = compose(matchResult[0], this.errorHandler, this.#notFoundHandler);\n return (async () => {\n try {\n const context = await composed(c);\n if (!context.finalized) {\n throw new Error(\n \"Context is not finalized. Did you forget to return a Response object or `await next()`?\"\n );\n }\n return context.res;\n } catch (err) {\n return this.#handleError(err, c);\n }\n })();\n }\n /**\n * `.fetch()` will be entry point of your app.\n *\n * @see {@link https://hono.dev/docs/api/hono#fetch}\n *\n * @param {Request} request - request Object of request\n * @param {Env} Env - env Object\n * @param {ExecutionContext} - context of execution\n * @returns {Response | Promise} response of request\n *\n */\n fetch = (request, ...rest) => {\n return this.#dispatch(request, rest[1], rest[0], request.method);\n };\n /**\n * `.request()` is a useful method for testing.\n * You can pass a URL or pathname to send a GET request.\n * app will return a Response object.\n * ```ts\n * test('GET /hello is ok', async () => {\n * const res = await app.request('/hello')\n * expect(res.status).toBe(200)\n * })\n * ```\n * @see https://hono.dev/docs/api/hono#request\n */\n request = (input, requestInit, Env, executionCtx) => {\n if (input instanceof Request) {\n return this.fetch(requestInit ? new Request(input, requestInit) : input, Env, executionCtx);\n }\n input = input.toString();\n return this.fetch(\n new Request(\n /^https?:\\/\\//.test(input) ? input : `http://localhost${mergePath(\"/\", input)}`,\n requestInit\n ),\n Env,\n executionCtx\n );\n };\n /**\n * `.fire()` automatically adds a global fetch event listener.\n * This can be useful for environments that adhere to the Service Worker API, such as non-ES module Cloudflare Workers.\n * @deprecated\n * Use `fire` from `hono/service-worker` instead.\n * ```ts\n * import { Hono } from 'hono'\n * import { fire } from 'hono/service-worker'\n *\n * const app = new Hono()\n * // ...\n * fire(app)\n * ```\n * @see https://hono.dev/docs/api/hono#fire\n * @see https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API\n * @see https://developers.cloudflare.com/workers/reference/migrate-to-module-workers/\n */\n fire = () => {\n addEventListener(\"fetch\", (event) => {\n event.respondWith(this.#dispatch(event.request, event, void 0, event.request.method));\n });\n };\n};\nexport {\n Hono as HonoBase\n};\n", "// src/compose.ts\nvar compose = (middleware, onError, onNotFound) => {\n return (context, next) => {\n let index = -1;\n return dispatch(0);\n async function dispatch(i) {\n if (i <= index) {\n throw new Error(\"next() called multiple times\");\n }\n index = i;\n let res;\n let isError = false;\n let handler;\n if (middleware[i]) {\n handler = middleware[i][0][0];\n context.req.routeIndex = i;\n } else {\n handler = i === middleware.length && next || void 0;\n }\n if (handler) {\n try {\n res = await handler(context, () => dispatch(i + 1));\n } catch (err) {\n if (err instanceof Error && onError) {\n context.error = err;\n res = await onError(err, context);\n isError = true;\n } else {\n throw err;\n }\n }\n } else {\n if (context.finalized === false && onNotFound) {\n res = await onNotFound(context);\n }\n }\n if (res && (context.finalized === false || isError)) {\n context.res = res;\n }\n return context;\n }\n };\n};\nexport {\n compose\n};\n", "// src/context.ts\nimport { HonoRequest } from \"./request.js\";\nimport { HtmlEscapedCallbackPhase, resolveCallback } from \"./utils/html.js\";\nvar TEXT_PLAIN = \"text/plain; charset=UTF-8\";\nvar setDefaultContentType = (contentType, headers) => {\n return {\n \"Content-Type\": contentType,\n ...headers\n };\n};\nvar createResponseInstance = (body, init) => new Response(body, init);\nvar Context = class {\n #rawRequest;\n #req;\n /**\n * `.env` can get bindings (environment variables, secrets, KV namespaces, D1 database, R2 bucket etc.) in Cloudflare Workers.\n *\n * @see {@link https://hono.dev/docs/api/context#env}\n *\n * @example\n * ```ts\n * // Environment object for Cloudflare Workers\n * app.get('*', async c => {\n * const counter = c.env.COUNTER\n * })\n * ```\n */\n env = {};\n #var;\n finalized = false;\n /**\n * `.error` can get the error object from the middleware if the Handler throws an error.\n *\n * @see {@link https://hono.dev/docs/api/context#error}\n *\n * @example\n * ```ts\n * app.use('*', async (c, next) => {\n * await next()\n * if (c.error) {\n * // do something...\n * }\n * })\n * ```\n */\n error;\n #status;\n #executionCtx;\n #res;\n #layout;\n #renderer;\n #notFoundHandler;\n #preparedHeaders;\n #matchResult;\n #path;\n /**\n * Creates an instance of the Context class.\n *\n * @param req - The Request object.\n * @param options - Optional configuration options for the context.\n */\n constructor(req, options) {\n this.#rawRequest = req;\n if (options) {\n this.#executionCtx = options.executionCtx;\n this.env = options.env;\n this.#notFoundHandler = options.notFoundHandler;\n this.#path = options.path;\n this.#matchResult = options.matchResult;\n }\n }\n /**\n * `.req` is the instance of {@link HonoRequest}.\n */\n get req() {\n this.#req ??= new HonoRequest(this.#rawRequest, this.#path, this.#matchResult);\n return this.#req;\n }\n /**\n * @see {@link https://hono.dev/docs/api/context#event}\n * The FetchEvent associated with the current request.\n *\n * @throws Will throw an error if the context does not have a FetchEvent.\n */\n get event() {\n if (this.#executionCtx && \"respondWith\" in this.#executionCtx) {\n return this.#executionCtx;\n } else {\n throw Error(\"This context has no FetchEvent\");\n }\n }\n /**\n * @see {@link https://hono.dev/docs/api/context#executionctx}\n * The ExecutionContext associated with the current request.\n *\n * @throws Will throw an error if the context does not have an ExecutionContext.\n */\n get executionCtx() {\n if (this.#executionCtx) {\n return this.#executionCtx;\n } else {\n throw Error(\"This context has no ExecutionContext\");\n }\n }\n /**\n * @see {@link https://hono.dev/docs/api/context#res}\n * The Response object for the current request.\n */\n get res() {\n return this.#res ||= createResponseInstance(null, {\n headers: this.#preparedHeaders ??= new Headers()\n });\n }\n /**\n * Sets the Response object for the current request.\n *\n * @param _res - The Response object to set.\n */\n set res(_res) {\n if (this.#res && _res) {\n _res = createResponseInstance(_res.body, _res);\n for (const [k, v] of this.#res.headers.entries()) {\n if (k === \"content-type\") {\n continue;\n }\n if (k === \"set-cookie\") {\n const cookies = this.#res.headers.getSetCookie();\n _res.headers.delete(\"set-cookie\");\n for (const cookie of cookies) {\n _res.headers.append(\"set-cookie\", cookie);\n }\n } else {\n _res.headers.set(k, v);\n }\n }\n }\n this.#res = _res;\n this.finalized = true;\n }\n /**\n * `.render()` can create a response within a layout.\n *\n * @see {@link https://hono.dev/docs/api/context#render-setrenderer}\n *\n * @example\n * ```ts\n * app.get('/', (c) => {\n * return c.render('Hello!')\n * })\n * ```\n */\n render = (...args) => {\n this.#renderer ??= (content) => this.html(content);\n return this.#renderer(...args);\n };\n /**\n * Sets the layout for the response.\n *\n * @param layout - The layout to set.\n * @returns The layout function.\n */\n setLayout = (layout) => this.#layout = layout;\n /**\n * Gets the current layout for the response.\n *\n * @returns The current layout function.\n */\n getLayout = () => this.#layout;\n /**\n * `.setRenderer()` can set the layout in the custom middleware.\n *\n * @see {@link https://hono.dev/docs/api/context#render-setrenderer}\n *\n * @example\n * ```tsx\n * app.use('*', async (c, next) => {\n * c.setRenderer((content) => {\n * return c.html(\n * \n * \n *

{content}

\n * \n * \n * )\n * })\n * await next()\n * })\n * ```\n */\n setRenderer = (renderer) => {\n this.#renderer = renderer;\n };\n /**\n * `.header()` can set headers.\n *\n * @see {@link https://hono.dev/docs/api/context#header}\n *\n * @example\n * ```ts\n * app.get('/welcome', (c) => {\n * // Set headers\n * c.header('X-Message', 'Hello!')\n * c.header('Content-Type', 'text/plain')\n *\n * return c.body('Thank you for coming')\n * })\n * ```\n */\n header = (name, value, options) => {\n if (this.finalized) {\n this.#res = createResponseInstance(this.#res.body, this.#res);\n }\n const headers = this.#res ? this.#res.headers : this.#preparedHeaders ??= new Headers();\n if (value === void 0) {\n headers.delete(name);\n } else if (options?.append) {\n headers.append(name, value);\n } else {\n headers.set(name, value);\n }\n };\n status = (status) => {\n this.#status = status;\n };\n /**\n * `.set()` can set the value specified by the key.\n *\n * @see {@link https://hono.dev/docs/api/context#set-get}\n *\n * @example\n * ```ts\n * app.use('*', async (c, next) => {\n * c.set('message', 'Hono is hot!!')\n * await next()\n * })\n * ```\n */\n set = (key, value) => {\n this.#var ??= /* @__PURE__ */ new Map();\n this.#var.set(key, value);\n };\n /**\n * `.get()` can use the value specified by the key.\n *\n * @see {@link https://hono.dev/docs/api/context#set-get}\n *\n * @example\n * ```ts\n * app.get('/', (c) => {\n * const message = c.get('message')\n * return c.text(`The message is \"${message}\"`)\n * })\n * ```\n */\n get = (key) => {\n return this.#var ? this.#var.get(key) : void 0;\n };\n /**\n * `.var` can access the value of a variable.\n *\n * @see {@link https://hono.dev/docs/api/context#var}\n *\n * @example\n * ```ts\n * const result = c.var.client.oneMethod()\n * ```\n */\n // c.var.propName is a read-only\n get var() {\n if (!this.#var) {\n return {};\n }\n return Object.fromEntries(this.#var);\n }\n #newResponse(data, arg, headers) {\n const responseHeaders = this.#res ? new Headers(this.#res.headers) : this.#preparedHeaders ?? new Headers();\n if (typeof arg === \"object\" && \"headers\" in arg) {\n const argHeaders = arg.headers instanceof Headers ? arg.headers : new Headers(arg.headers);\n for (const [key, value] of argHeaders) {\n if (key.toLowerCase() === \"set-cookie\") {\n responseHeaders.append(key, value);\n } else {\n responseHeaders.set(key, value);\n }\n }\n }\n if (headers) {\n for (const [k, v] of Object.entries(headers)) {\n if (typeof v === \"string\") {\n responseHeaders.set(k, v);\n } else {\n responseHeaders.delete(k);\n for (const v2 of v) {\n responseHeaders.append(k, v2);\n }\n }\n }\n }\n const status = typeof arg === \"number\" ? arg : arg?.status ?? this.#status;\n return createResponseInstance(data, { status, headers: responseHeaders });\n }\n newResponse = (...args) => this.#newResponse(...args);\n /**\n * `.body()` can return the HTTP response.\n * You can set headers with `.header()` and set HTTP status code with `.status`.\n * This can also be set in `.text()`, `.json()` and so on.\n *\n * @see {@link https://hono.dev/docs/api/context#body}\n *\n * @example\n * ```ts\n * app.get('/welcome', (c) => {\n * // Set headers\n * c.header('X-Message', 'Hello!')\n * c.header('Content-Type', 'text/plain')\n * // Set HTTP status code\n * c.status(201)\n *\n * // Return the response body\n * return c.body('Thank you for coming')\n * })\n * ```\n */\n body = (data, arg, headers) => this.#newResponse(data, arg, headers);\n /**\n * `.text()` can render text as `Content-Type:text/plain`.\n *\n * @see {@link https://hono.dev/docs/api/context#text}\n *\n * @example\n * ```ts\n * app.get('/say', (c) => {\n * return c.text('Hello!')\n * })\n * ```\n */\n text = (text, arg, headers) => {\n return !this.#preparedHeaders && !this.#status && !arg && !headers && !this.finalized ? new Response(text) : this.#newResponse(\n text,\n arg,\n setDefaultContentType(TEXT_PLAIN, headers)\n );\n };\n /**\n * `.json()` can render JSON as `Content-Type:application/json`.\n *\n * @see {@link https://hono.dev/docs/api/context#json}\n *\n * @example\n * ```ts\n * app.get('/api', (c) => {\n * return c.json({ message: 'Hello!' })\n * })\n * ```\n */\n json = (object, arg, headers) => {\n return this.#newResponse(\n JSON.stringify(object),\n arg,\n setDefaultContentType(\"application/json\", headers)\n );\n };\n html = (html, arg, headers) => {\n const res = (html2) => this.#newResponse(html2, arg, setDefaultContentType(\"text/html; charset=UTF-8\", headers));\n return typeof html === \"object\" ? resolveCallback(html, HtmlEscapedCallbackPhase.Stringify, false, {}).then(res) : res(html);\n };\n /**\n * `.redirect()` can Redirect, default status code is 302.\n *\n * @see {@link https://hono.dev/docs/api/context#redirect}\n *\n * @example\n * ```ts\n * app.get('/redirect', (c) => {\n * return c.redirect('/')\n * })\n * app.get('/redirect-permanently', (c) => {\n * return c.redirect('/', 301)\n * })\n * ```\n */\n redirect = (location, status) => {\n const locationString = String(location);\n this.header(\n \"Location\",\n // Multibyes should be encoded\n // eslint-disable-next-line no-control-regex\n !/[^\\x00-\\xFF]/.test(locationString) ? locationString : encodeURI(locationString)\n );\n return this.newResponse(null, status ?? 302);\n };\n /**\n * `.notFound()` can return the Not Found Response.\n *\n * @see {@link https://hono.dev/docs/api/context#notfound}\n *\n * @example\n * ```ts\n * app.get('/notfound', (c) => {\n * return c.notFound()\n * })\n * ```\n */\n notFound = () => {\n this.#notFoundHandler ??= () => createResponseInstance();\n return this.#notFoundHandler(this);\n };\n};\nexport {\n Context,\n TEXT_PLAIN\n};\n", "// src/request.ts\nimport { HTTPException } from \"./http-exception.js\";\nimport { GET_MATCH_RESULT } from \"./request/constants.js\";\nimport { parseBody } from \"./utils/body.js\";\nimport { decodeURIComponent_, getQueryParam, getQueryParams, tryDecode } from \"./utils/url.js\";\nvar tryDecodeURIComponent = (str) => tryDecode(str, decodeURIComponent_);\nvar HonoRequest = class {\n /**\n * `.raw` can get the raw Request object.\n *\n * @see {@link https://hono.dev/docs/api/request#raw}\n *\n * @example\n * ```ts\n * // For Cloudflare Workers\n * app.post('/', async (c) => {\n * const metadata = c.req.raw.cf?.hostMetadata?\n * ...\n * })\n * ```\n */\n raw;\n #validatedData;\n // Short name of validatedData\n #matchResult;\n routeIndex = 0;\n /**\n * `.path` can get the pathname of the request.\n *\n * @see {@link https://hono.dev/docs/api/request#path}\n *\n * @example\n * ```ts\n * app.get('/about/me', (c) => {\n * const pathname = c.req.path // `/about/me`\n * })\n * ```\n */\n path;\n bodyCache = {};\n constructor(request, path = \"/\", matchResult = [[]]) {\n this.raw = request;\n this.path = path;\n this.#matchResult = matchResult;\n this.#validatedData = {};\n }\n param(key) {\n return key ? this.#getDecodedParam(key) : this.#getAllDecodedParams();\n }\n #getDecodedParam(key) {\n const paramKey = this.#matchResult[0][this.routeIndex][1][key];\n const param = this.#getParamValue(paramKey);\n return param && /\\%/.test(param) ? tryDecodeURIComponent(param) : param;\n }\n #getAllDecodedParams() {\n const decoded = {};\n const keys = Object.keys(this.#matchResult[0][this.routeIndex][1]);\n for (const key of keys) {\n const value = this.#getParamValue(this.#matchResult[0][this.routeIndex][1][key]);\n if (value !== void 0) {\n decoded[key] = /\\%/.test(value) ? tryDecodeURIComponent(value) : value;\n }\n }\n return decoded;\n }\n #getParamValue(paramKey) {\n return this.#matchResult[1] ? this.#matchResult[1][paramKey] : paramKey;\n }\n query(key) {\n return getQueryParam(this.url, key);\n }\n queries(key) {\n return getQueryParams(this.url, key);\n }\n header(name) {\n if (name) {\n return this.raw.headers.get(name) ?? void 0;\n }\n const headerData = {};\n this.raw.headers.forEach((value, key) => {\n headerData[key] = value;\n });\n return headerData;\n }\n async parseBody(options) {\n return this.bodyCache.parsedBody ??= await parseBody(this, options);\n }\n #cachedBody = (key) => {\n const { bodyCache, raw } = this;\n const cachedBody = bodyCache[key];\n if (cachedBody) {\n return cachedBody;\n }\n const anyCachedKey = Object.keys(bodyCache)[0];\n if (anyCachedKey) {\n return bodyCache[anyCachedKey].then((body) => {\n if (anyCachedKey === \"json\") {\n body = JSON.stringify(body);\n }\n return new Response(body)[key]();\n });\n }\n return bodyCache[key] = raw[key]();\n };\n /**\n * `.json()` can parse Request body of type `application/json`\n *\n * @see {@link https://hono.dev/docs/api/request#json}\n *\n * @example\n * ```ts\n * app.post('/entry', async (c) => {\n * const body = await c.req.json()\n * })\n * ```\n */\n json() {\n return this.#cachedBody(\"text\").then((text) => JSON.parse(text));\n }\n /**\n * `.text()` can parse Request body of type `text/plain`\n *\n * @see {@link https://hono.dev/docs/api/request#text}\n *\n * @example\n * ```ts\n * app.post('/entry', async (c) => {\n * const body = await c.req.text()\n * })\n * ```\n */\n text() {\n return this.#cachedBody(\"text\");\n }\n /**\n * `.arrayBuffer()` parse Request body as an `ArrayBuffer`\n *\n * @see {@link https://hono.dev/docs/api/request#arraybuffer}\n *\n * @example\n * ```ts\n * app.post('/entry', async (c) => {\n * const body = await c.req.arrayBuffer()\n * })\n * ```\n */\n arrayBuffer() {\n return this.#cachedBody(\"arrayBuffer\");\n }\n /**\n * Parses the request body as a `Blob`.\n * @example\n * ```ts\n * app.post('/entry', async (c) => {\n * const body = await c.req.blob();\n * });\n * ```\n * @see https://hono.dev/docs/api/request#blob\n */\n blob() {\n return this.#cachedBody(\"blob\");\n }\n /**\n * Parses the request body as `FormData`.\n * @example\n * ```ts\n * app.post('/entry', async (c) => {\n * const body = await c.req.formData();\n * });\n * ```\n * @see https://hono.dev/docs/api/request#formdata\n */\n formData() {\n return this.#cachedBody(\"formData\");\n }\n /**\n * Adds validated data to the request.\n *\n * @param target - The target of the validation.\n * @param data - The validated data to add.\n */\n addValidatedData(target, data) {\n this.#validatedData[target] = data;\n }\n valid(target) {\n return this.#validatedData[target];\n }\n /**\n * `.url()` can get the request url strings.\n *\n * @see {@link https://hono.dev/docs/api/request#url}\n *\n * @example\n * ```ts\n * app.get('/about/me', (c) => {\n * const url = c.req.url // `http://localhost:8787/about/me`\n * ...\n * })\n * ```\n */\n get url() {\n return this.raw.url;\n }\n /**\n * `.method()` can get the method name of the request.\n *\n * @see {@link https://hono.dev/docs/api/request#method}\n *\n * @example\n * ```ts\n * app.get('/about/me', (c) => {\n * const method = c.req.method // `GET`\n * })\n * ```\n */\n get method() {\n return this.raw.method;\n }\n get [GET_MATCH_RESULT]() {\n return this.#matchResult;\n }\n /**\n * `.matchedRoutes()` can return a matched route in the handler\n *\n * @deprecated\n *\n * Use matchedRoutes helper defined in \"hono/route\" instead.\n *\n * @see {@link https://hono.dev/docs/api/request#matchedroutes}\n *\n * @example\n * ```ts\n * app.use('*', async function logger(c, next) {\n * await next()\n * c.req.matchedRoutes.forEach(({ handler, method, path }, i) => {\n * const name = handler.name || (handler.length < 2 ? '[handler]' : '[middleware]')\n * console.log(\n * method,\n * ' ',\n * path,\n * ' '.repeat(Math.max(10 - path.length, 0)),\n * name,\n * i === c.req.routeIndex ? '<- respond from here' : ''\n * )\n * })\n * })\n * ```\n */\n get matchedRoutes() {\n return this.#matchResult[0].map(([[, route]]) => route);\n }\n /**\n * `routePath()` can retrieve the path registered within the handler\n *\n * @deprecated\n *\n * Use routePath helper defined in \"hono/route\" instead.\n *\n * @see {@link https://hono.dev/docs/api/request#routepath}\n *\n * @example\n * ```ts\n * app.get('/posts/:id', (c) => {\n * return c.json({ path: c.req.routePath })\n * })\n * ```\n */\n get routePath() {\n return this.#matchResult[0].map(([[, route]]) => route)[this.routeIndex].path;\n }\n};\nvar cloneRawRequest = async (req) => {\n if (!req.raw.bodyUsed) {\n return req.raw.clone();\n }\n const cacheKey = Object.keys(req.bodyCache)[0];\n if (!cacheKey) {\n throw new HTTPException(500, {\n message: \"Cannot clone request: body was already consumed and not cached. Please use HonoRequest methods (e.g., req.json(), req.text()) instead of consuming req.raw directly.\"\n });\n }\n const requestInit = {\n body: await req[cacheKey](),\n cache: req.raw.cache,\n credentials: req.raw.credentials,\n headers: req.header(),\n integrity: req.raw.integrity,\n keepalive: req.raw.keepalive,\n method: req.method,\n mode: req.raw.mode,\n redirect: req.raw.redirect,\n referrer: req.raw.referrer,\n referrerPolicy: req.raw.referrerPolicy,\n signal: req.raw.signal\n };\n return new Request(req.url, requestInit);\n};\nexport {\n HonoRequest,\n cloneRawRequest\n};\n", "// src/http-exception.ts\nvar HTTPException = class extends Error {\n res;\n status;\n /**\n * Creates an instance of `HTTPException`.\n * @param status - HTTP status code for the exception. Defaults to 500.\n * @param options - Additional options for the exception.\n */\n constructor(status = 500, options) {\n super(options?.message, { cause: options?.cause });\n this.res = options?.res;\n this.status = status;\n }\n /**\n * Returns the response object associated with the exception.\n * If a response object is not provided, a new response is created with the error message and status code.\n * @returns The response object.\n */\n getResponse() {\n if (this.res) {\n const newResponse = new Response(this.res.body, {\n status: this.status,\n headers: this.res.headers\n });\n return newResponse;\n }\n return new Response(this.message, {\n status: this.status\n });\n }\n};\nexport {\n HTTPException\n};\n", "// src/request/constants.ts\nvar GET_MATCH_RESULT = /* @__PURE__ */ Symbol();\nexport {\n GET_MATCH_RESULT\n};\n", "// src/utils/body.ts\nimport { HonoRequest } from \"../request.js\";\nvar parseBody = async (request, options = /* @__PURE__ */ Object.create(null)) => {\n const { all = false, dot = false } = options;\n const headers = request instanceof HonoRequest ? request.raw.headers : request.headers;\n const contentType = headers.get(\"Content-Type\");\n if (contentType?.startsWith(\"multipart/form-data\") || contentType?.startsWith(\"application/x-www-form-urlencoded\")) {\n return parseFormData(request, { all, dot });\n }\n return {};\n};\nasync function parseFormData(request, options) {\n const formData = await request.formData();\n if (formData) {\n return convertFormDataToBodyData(formData, options);\n }\n return {};\n}\nfunction convertFormDataToBodyData(formData, options) {\n const form = /* @__PURE__ */ Object.create(null);\n formData.forEach((value, key) => {\n const shouldParseAllValues = options.all || key.endsWith(\"[]\");\n if (!shouldParseAllValues) {\n form[key] = value;\n } else {\n handleParsingAllValues(form, key, value);\n }\n });\n if (options.dot) {\n Object.entries(form).forEach(([key, value]) => {\n const shouldParseDotValues = key.includes(\".\");\n if (shouldParseDotValues) {\n handleParsingNestedValues(form, key, value);\n delete form[key];\n }\n });\n }\n return form;\n}\nvar handleParsingAllValues = (form, key, value) => {\n if (form[key] !== void 0) {\n if (Array.isArray(form[key])) {\n ;\n form[key].push(value);\n } else {\n form[key] = [form[key], value];\n }\n } else {\n if (!key.endsWith(\"[]\")) {\n form[key] = value;\n } else {\n form[key] = [value];\n }\n }\n};\nvar handleParsingNestedValues = (form, key, value) => {\n let nestedForm = form;\n const keys = key.split(\".\");\n keys.forEach((key2, index) => {\n if (index === keys.length - 1) {\n nestedForm[key2] = value;\n } else {\n if (!nestedForm[key2] || typeof nestedForm[key2] !== \"object\" || Array.isArray(nestedForm[key2]) || nestedForm[key2] instanceof File) {\n nestedForm[key2] = /* @__PURE__ */ Object.create(null);\n }\n nestedForm = nestedForm[key2];\n }\n });\n};\nexport {\n parseBody\n};\n", "// src/utils/url.ts\nvar splitPath = (path) => {\n const paths = path.split(\"/\");\n if (paths[0] === \"\") {\n paths.shift();\n }\n return paths;\n};\nvar splitRoutingPath = (routePath) => {\n const { groups, path } = extractGroupsFromPath(routePath);\n const paths = splitPath(path);\n return replaceGroupMarks(paths, groups);\n};\nvar extractGroupsFromPath = (path) => {\n const groups = [];\n path = path.replace(/\\{[^}]+\\}/g, (match, index) => {\n const mark = `@${index}`;\n groups.push([mark, match]);\n return mark;\n });\n return { groups, path };\n};\nvar replaceGroupMarks = (paths, groups) => {\n for (let i = groups.length - 1; i >= 0; i--) {\n const [mark] = groups[i];\n for (let j = paths.length - 1; j >= 0; j--) {\n if (paths[j].includes(mark)) {\n paths[j] = paths[j].replace(mark, groups[i][1]);\n break;\n }\n }\n }\n return paths;\n};\nvar patternCache = {};\nvar getPattern = (label, next) => {\n if (label === \"*\") {\n return \"*\";\n }\n const match = label.match(/^\\:([^\\{\\}]+)(?:\\{(.+)\\})?$/);\n if (match) {\n const cacheKey = `${label}#${next}`;\n if (!patternCache[cacheKey]) {\n if (match[2]) {\n patternCache[cacheKey] = next && next[0] !== \":\" && next[0] !== \"*\" ? [cacheKey, match[1], new RegExp(`^${match[2]}(?=/${next})`)] : [label, match[1], new RegExp(`^${match[2]}$`)];\n } else {\n patternCache[cacheKey] = [label, match[1], true];\n }\n }\n return patternCache[cacheKey];\n }\n return null;\n};\nvar tryDecode = (str, decoder) => {\n try {\n return decoder(str);\n } catch {\n return str.replace(/(?:%[0-9A-Fa-f]{2})+/g, (match) => {\n try {\n return decoder(match);\n } catch {\n return match;\n }\n });\n }\n};\nvar tryDecodeURI = (str) => tryDecode(str, decodeURI);\nvar getPath = (request) => {\n const url = request.url;\n const start = url.indexOf(\"/\", url.indexOf(\":\") + 4);\n let i = start;\n for (; i < url.length; i++) {\n const charCode = url.charCodeAt(i);\n if (charCode === 37) {\n const queryIndex = url.indexOf(\"?\", i);\n const hashIndex = url.indexOf(\"#\", i);\n const end = queryIndex === -1 ? hashIndex === -1 ? void 0 : hashIndex : hashIndex === -1 ? queryIndex : Math.min(queryIndex, hashIndex);\n const path = url.slice(start, end);\n return tryDecodeURI(path.includes(\"%25\") ? path.replace(/%25/g, \"%2525\") : path);\n } else if (charCode === 63 || charCode === 35) {\n break;\n }\n }\n return url.slice(start, i);\n};\nvar getQueryStrings = (url) => {\n const queryIndex = url.indexOf(\"?\", 8);\n return queryIndex === -1 ? \"\" : \"?\" + url.slice(queryIndex + 1);\n};\nvar getPathNoStrict = (request) => {\n const result = getPath(request);\n return result.length > 1 && result.at(-1) === \"/\" ? result.slice(0, -1) : result;\n};\nvar mergePath = (base, sub, ...rest) => {\n if (rest.length) {\n sub = mergePath(sub, ...rest);\n }\n return `${base?.[0] === \"/\" ? \"\" : \"/\"}${base}${sub === \"/\" ? \"\" : `${base?.at(-1) === \"/\" ? \"\" : \"/\"}${sub?.[0] === \"/\" ? sub.slice(1) : sub}`}`;\n};\nvar checkOptionalParameter = (path) => {\n if (path.charCodeAt(path.length - 1) !== 63 || !path.includes(\":\")) {\n return null;\n }\n const segments = path.split(\"/\");\n const results = [];\n let basePath = \"\";\n segments.forEach((segment) => {\n if (segment !== \"\" && !/\\:/.test(segment)) {\n basePath += \"/\" + segment;\n } else if (/\\:/.test(segment)) {\n if (/\\?/.test(segment)) {\n if (results.length === 0 && basePath === \"\") {\n results.push(\"/\");\n } else {\n results.push(basePath);\n }\n const optionalSegment = segment.replace(\"?\", \"\");\n basePath += \"/\" + optionalSegment;\n results.push(basePath);\n } else {\n basePath += \"/\" + segment;\n }\n }\n });\n return results.filter((v, i, a) => a.indexOf(v) === i);\n};\nvar _decodeURI = (value) => {\n if (!/[%+]/.test(value)) {\n return value;\n }\n if (value.indexOf(\"+\") !== -1) {\n value = value.replace(/\\+/g, \" \");\n }\n return value.indexOf(\"%\") !== -1 ? tryDecode(value, decodeURIComponent_) : value;\n};\nvar _getQueryParam = (url, key, multiple) => {\n let encoded;\n if (!multiple && key && !/[%+]/.test(key)) {\n let keyIndex2 = url.indexOf(\"?\", 8);\n if (keyIndex2 === -1) {\n return void 0;\n }\n if (!url.startsWith(key, keyIndex2 + 1)) {\n keyIndex2 = url.indexOf(`&${key}`, keyIndex2 + 1);\n }\n while (keyIndex2 !== -1) {\n const trailingKeyCode = url.charCodeAt(keyIndex2 + key.length + 1);\n if (trailingKeyCode === 61) {\n const valueIndex = keyIndex2 + key.length + 2;\n const endIndex = url.indexOf(\"&\", valueIndex);\n return _decodeURI(url.slice(valueIndex, endIndex === -1 ? void 0 : endIndex));\n } else if (trailingKeyCode == 38 || isNaN(trailingKeyCode)) {\n return \"\";\n }\n keyIndex2 = url.indexOf(`&${key}`, keyIndex2 + 1);\n }\n encoded = /[%+]/.test(url);\n if (!encoded) {\n return void 0;\n }\n }\n const results = {};\n encoded ??= /[%+]/.test(url);\n let keyIndex = url.indexOf(\"?\", 8);\n while (keyIndex !== -1) {\n const nextKeyIndex = url.indexOf(\"&\", keyIndex + 1);\n let valueIndex = url.indexOf(\"=\", keyIndex);\n if (valueIndex > nextKeyIndex && nextKeyIndex !== -1) {\n valueIndex = -1;\n }\n let name = url.slice(\n keyIndex + 1,\n valueIndex === -1 ? nextKeyIndex === -1 ? void 0 : nextKeyIndex : valueIndex\n );\n if (encoded) {\n name = _decodeURI(name);\n }\n keyIndex = nextKeyIndex;\n if (name === \"\") {\n continue;\n }\n let value;\n if (valueIndex === -1) {\n value = \"\";\n } else {\n value = url.slice(valueIndex + 1, nextKeyIndex === -1 ? void 0 : nextKeyIndex);\n if (encoded) {\n value = _decodeURI(value);\n }\n }\n if (multiple) {\n if (!(results[name] && Array.isArray(results[name]))) {\n results[name] = [];\n }\n ;\n results[name].push(value);\n } else {\n results[name] ??= value;\n }\n }\n return key ? results[key] : results;\n};\nvar getQueryParam = _getQueryParam;\nvar getQueryParams = (url, key) => {\n return _getQueryParam(url, key, true);\n};\nvar decodeURIComponent_ = decodeURIComponent;\nexport {\n checkOptionalParameter,\n decodeURIComponent_,\n getPath,\n getPathNoStrict,\n getPattern,\n getQueryParam,\n getQueryParams,\n getQueryStrings,\n mergePath,\n splitPath,\n splitRoutingPath,\n tryDecode,\n tryDecodeURI\n};\n", "// src/utils/html.ts\nvar HtmlEscapedCallbackPhase = {\n Stringify: 1,\n BeforeStream: 2,\n Stream: 3\n};\nvar raw = (value, callbacks) => {\n const escapedString = new String(value);\n escapedString.isEscaped = true;\n escapedString.callbacks = callbacks;\n return escapedString;\n};\nvar escapeRe = /[&<>'\"]/;\nvar stringBufferToString = async (buffer, callbacks) => {\n let str = \"\";\n callbacks ||= [];\n const resolvedBuffer = await Promise.all(buffer);\n for (let i = resolvedBuffer.length - 1; ; i--) {\n str += resolvedBuffer[i];\n i--;\n if (i < 0) {\n break;\n }\n let r = resolvedBuffer[i];\n if (typeof r === \"object\") {\n callbacks.push(...r.callbacks || []);\n }\n const isEscaped = r.isEscaped;\n r = await (typeof r === \"object\" ? r.toString() : r);\n if (typeof r === \"object\") {\n callbacks.push(...r.callbacks || []);\n }\n if (r.isEscaped ?? isEscaped) {\n str += r;\n } else {\n const buf = [str];\n escapeToBuffer(r, buf);\n str = buf[0];\n }\n }\n return raw(str, callbacks);\n};\nvar escapeToBuffer = (str, buffer) => {\n const match = str.search(escapeRe);\n if (match === -1) {\n buffer[0] += str;\n return;\n }\n let escape;\n let index;\n let lastIndex = 0;\n for (index = match; index < str.length; index++) {\n switch (str.charCodeAt(index)) {\n case 34:\n escape = \""\";\n break;\n case 39:\n escape = \"'\";\n break;\n case 38:\n escape = \"&\";\n break;\n case 60:\n escape = \"<\";\n break;\n case 62:\n escape = \">\";\n break;\n default:\n continue;\n }\n buffer[0] += str.substring(lastIndex, index) + escape;\n lastIndex = index + 1;\n }\n buffer[0] += str.substring(lastIndex, index);\n};\nvar resolveCallbackSync = (str) => {\n const callbacks = str.callbacks;\n if (!callbacks?.length) {\n return str;\n }\n const buffer = [str];\n const context = {};\n callbacks.forEach((c) => c({ phase: HtmlEscapedCallbackPhase.Stringify, buffer, context }));\n return buffer[0];\n};\nvar resolveCallback = async (str, phase, preserveCallbacks, context, buffer) => {\n if (typeof str === \"object\" && !(str instanceof String)) {\n if (!(str instanceof Promise)) {\n str = str.toString();\n }\n if (str instanceof Promise) {\n str = await str;\n }\n }\n const callbacks = str.callbacks;\n if (!callbacks?.length) {\n return Promise.resolve(str);\n }\n if (buffer) {\n buffer[0] += str;\n } else {\n buffer = [str];\n }\n const resStr = Promise.all(callbacks.map((c) => c({ phase, buffer, context }))).then(\n (res) => Promise.all(\n res.filter(Boolean).map((str2) => resolveCallback(str2, phase, false, context, buffer))\n ).then(() => buffer[0])\n );\n if (preserveCallbacks) {\n return raw(await resStr, callbacks);\n } else {\n return resStr;\n }\n};\nexport {\n HtmlEscapedCallbackPhase,\n escapeToBuffer,\n raw,\n resolveCallback,\n resolveCallbackSync,\n stringBufferToString\n};\n", "// src/router.ts\nvar METHOD_NAME_ALL = \"ALL\";\nvar METHOD_NAME_ALL_LOWERCASE = \"all\";\nvar METHODS = [\"get\", \"post\", \"put\", \"delete\", \"options\", \"patch\"];\nvar MESSAGE_MATCHER_IS_ALREADY_BUILT = \"Can not add a route since the matcher is already built.\";\nvar UnsupportedPathError = class extends Error {\n};\nexport {\n MESSAGE_MATCHER_IS_ALREADY_BUILT,\n METHODS,\n METHOD_NAME_ALL,\n METHOD_NAME_ALL_LOWERCASE,\n UnsupportedPathError\n};\n", "// src/utils/constants.ts\nvar COMPOSED_HANDLER = \"__COMPOSED_HANDLER\";\nexport {\n COMPOSED_HANDLER\n};\n", "// src/router/reg-exp-router/index.ts\nimport { RegExpRouter } from \"./router.js\";\nimport { PreparedRegExpRouter, buildInitParams, serializeInitParams } from \"./prepared-router.js\";\nexport {\n PreparedRegExpRouter,\n RegExpRouter,\n buildInitParams,\n serializeInitParams\n};\n", "// src/router/reg-exp-router/router.ts\nimport {\n MESSAGE_MATCHER_IS_ALREADY_BUILT,\n METHOD_NAME_ALL,\n UnsupportedPathError\n} from \"../../router.js\";\nimport { checkOptionalParameter } from \"../../utils/url.js\";\nimport { match, emptyParam } from \"./matcher.js\";\nimport { PATH_ERROR } from \"./node.js\";\nimport { Trie } from \"./trie.js\";\nvar nullMatcher = [/^$/, [], /* @__PURE__ */ Object.create(null)];\nvar wildcardRegExpCache = /* @__PURE__ */ Object.create(null);\nfunction buildWildcardRegExp(path) {\n return wildcardRegExpCache[path] ??= new RegExp(\n path === \"*\" ? \"\" : `^${path.replace(\n /\\/\\*$|([.\\\\+*[^\\]$()])/g,\n (_, metaChar) => metaChar ? `\\\\${metaChar}` : \"(?:|/.*)\"\n )}$`\n );\n}\nfunction clearWildcardRegExpCache() {\n wildcardRegExpCache = /* @__PURE__ */ Object.create(null);\n}\nfunction buildMatcherFromPreprocessedRoutes(routes) {\n const trie = new Trie();\n const handlerData = [];\n if (routes.length === 0) {\n return nullMatcher;\n }\n const routesWithStaticPathFlag = routes.map(\n (route) => [!/\\*|\\/:/.test(route[0]), ...route]\n ).sort(\n ([isStaticA, pathA], [isStaticB, pathB]) => isStaticA ? 1 : isStaticB ? -1 : pathA.length - pathB.length\n );\n const staticMap = /* @__PURE__ */ Object.create(null);\n for (let i = 0, j = -1, len = routesWithStaticPathFlag.length; i < len; i++) {\n const [pathErrorCheckOnly, path, handlers] = routesWithStaticPathFlag[i];\n if (pathErrorCheckOnly) {\n staticMap[path] = [handlers.map(([h]) => [h, /* @__PURE__ */ Object.create(null)]), emptyParam];\n } else {\n j++;\n }\n let paramAssoc;\n try {\n paramAssoc = trie.insert(path, j, pathErrorCheckOnly);\n } catch (e) {\n throw e === PATH_ERROR ? new UnsupportedPathError(path) : e;\n }\n if (pathErrorCheckOnly) {\n continue;\n }\n handlerData[j] = handlers.map(([h, paramCount]) => {\n const paramIndexMap = /* @__PURE__ */ Object.create(null);\n paramCount -= 1;\n for (; paramCount >= 0; paramCount--) {\n const [key, value] = paramAssoc[paramCount];\n paramIndexMap[key] = value;\n }\n return [h, paramIndexMap];\n });\n }\n const [regexp, indexReplacementMap, paramReplacementMap] = trie.buildRegExp();\n for (let i = 0, len = handlerData.length; i < len; i++) {\n for (let j = 0, len2 = handlerData[i].length; j < len2; j++) {\n const map = handlerData[i][j]?.[1];\n if (!map) {\n continue;\n }\n const keys = Object.keys(map);\n for (let k = 0, len3 = keys.length; k < len3; k++) {\n map[keys[k]] = paramReplacementMap[map[keys[k]]];\n }\n }\n }\n const handlerMap = [];\n for (const i in indexReplacementMap) {\n handlerMap[i] = handlerData[indexReplacementMap[i]];\n }\n return [regexp, handlerMap, staticMap];\n}\nfunction findMiddleware(middleware, path) {\n if (!middleware) {\n return void 0;\n }\n for (const k of Object.keys(middleware).sort((a, b) => b.length - a.length)) {\n if (buildWildcardRegExp(k).test(path)) {\n return [...middleware[k]];\n }\n }\n return void 0;\n}\nvar RegExpRouter = class {\n name = \"RegExpRouter\";\n #middleware;\n #routes;\n constructor() {\n this.#middleware = { [METHOD_NAME_ALL]: /* @__PURE__ */ Object.create(null) };\n this.#routes = { [METHOD_NAME_ALL]: /* @__PURE__ */ Object.create(null) };\n }\n add(method, path, handler) {\n const middleware = this.#middleware;\n const routes = this.#routes;\n if (!middleware || !routes) {\n throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);\n }\n if (!middleware[method]) {\n ;\n [middleware, routes].forEach((handlerMap) => {\n handlerMap[method] = /* @__PURE__ */ Object.create(null);\n Object.keys(handlerMap[METHOD_NAME_ALL]).forEach((p) => {\n handlerMap[method][p] = [...handlerMap[METHOD_NAME_ALL][p]];\n });\n });\n }\n if (path === \"/*\") {\n path = \"*\";\n }\n const paramCount = (path.match(/\\/:/g) || []).length;\n if (/\\*$/.test(path)) {\n const re = buildWildcardRegExp(path);\n if (method === METHOD_NAME_ALL) {\n Object.keys(middleware).forEach((m) => {\n middleware[m][path] ||= findMiddleware(middleware[m], path) || findMiddleware(middleware[METHOD_NAME_ALL], path) || [];\n });\n } else {\n middleware[method][path] ||= findMiddleware(middleware[method], path) || findMiddleware(middleware[METHOD_NAME_ALL], path) || [];\n }\n Object.keys(middleware).forEach((m) => {\n if (method === METHOD_NAME_ALL || method === m) {\n Object.keys(middleware[m]).forEach((p) => {\n re.test(p) && middleware[m][p].push([handler, paramCount]);\n });\n }\n });\n Object.keys(routes).forEach((m) => {\n if (method === METHOD_NAME_ALL || method === m) {\n Object.keys(routes[m]).forEach(\n (p) => re.test(p) && routes[m][p].push([handler, paramCount])\n );\n }\n });\n return;\n }\n const paths = checkOptionalParameter(path) || [path];\n for (let i = 0, len = paths.length; i < len; i++) {\n const path2 = paths[i];\n Object.keys(routes).forEach((m) => {\n if (method === METHOD_NAME_ALL || method === m) {\n routes[m][path2] ||= [\n ...findMiddleware(middleware[m], path2) || findMiddleware(middleware[METHOD_NAME_ALL], path2) || []\n ];\n routes[m][path2].push([handler, paramCount - len + i + 1]);\n }\n });\n }\n }\n match = match;\n buildAllMatchers() {\n const matchers = /* @__PURE__ */ Object.create(null);\n Object.keys(this.#routes).concat(Object.keys(this.#middleware)).forEach((method) => {\n matchers[method] ||= this.#buildMatcher(method);\n });\n this.#middleware = this.#routes = void 0;\n clearWildcardRegExpCache();\n return matchers;\n }\n #buildMatcher(method) {\n const routes = [];\n let hasOwnRoute = method === METHOD_NAME_ALL;\n [this.#middleware, this.#routes].forEach((r) => {\n const ownRoute = r[method] ? Object.keys(r[method]).map((path) => [path, r[method][path]]) : [];\n if (ownRoute.length !== 0) {\n hasOwnRoute ||= true;\n routes.push(...ownRoute);\n } else if (method !== METHOD_NAME_ALL) {\n routes.push(\n ...Object.keys(r[METHOD_NAME_ALL]).map((path) => [path, r[METHOD_NAME_ALL][path]])\n );\n }\n });\n if (!hasOwnRoute) {\n return null;\n } else {\n return buildMatcherFromPreprocessedRoutes(routes);\n }\n }\n};\nexport {\n RegExpRouter\n};\n", "// src/router/reg-exp-router/matcher.ts\nimport { METHOD_NAME_ALL } from \"../../router.js\";\nvar emptyParam = [];\nfunction match(method, path) {\n const matchers = this.buildAllMatchers();\n const match2 = ((method2, path2) => {\n const matcher = matchers[method2] || matchers[METHOD_NAME_ALL];\n const staticMatch = matcher[2][path2];\n if (staticMatch) {\n return staticMatch;\n }\n const match3 = path2.match(matcher[0]);\n if (!match3) {\n return [[], emptyParam];\n }\n const index = match3.indexOf(\"\", 1);\n return [matcher[1][index], match3];\n });\n this.match = match2;\n return match2(method, path);\n}\nexport {\n emptyParam,\n match\n};\n", "// src/router/reg-exp-router/node.ts\nvar LABEL_REG_EXP_STR = \"[^/]+\";\nvar ONLY_WILDCARD_REG_EXP_STR = \".*\";\nvar TAIL_WILDCARD_REG_EXP_STR = \"(?:|/.*)\";\nvar PATH_ERROR = /* @__PURE__ */ Symbol();\nvar regExpMetaChars = new Set(\".\\\\+*[^]$()\");\nfunction compareKey(a, b) {\n if (a.length === 1) {\n return b.length === 1 ? a < b ? -1 : 1 : -1;\n }\n if (b.length === 1) {\n return 1;\n }\n if (a === ONLY_WILDCARD_REG_EXP_STR || a === TAIL_WILDCARD_REG_EXP_STR) {\n return 1;\n } else if (b === ONLY_WILDCARD_REG_EXP_STR || b === TAIL_WILDCARD_REG_EXP_STR) {\n return -1;\n }\n if (a === LABEL_REG_EXP_STR) {\n return 1;\n } else if (b === LABEL_REG_EXP_STR) {\n return -1;\n }\n return a.length === b.length ? a < b ? -1 : 1 : b.length - a.length;\n}\nvar Node = class _Node {\n #index;\n #varIndex;\n #children = /* @__PURE__ */ Object.create(null);\n insert(tokens, index, paramMap, context, pathErrorCheckOnly) {\n if (tokens.length === 0) {\n if (this.#index !== void 0) {\n throw PATH_ERROR;\n }\n if (pathErrorCheckOnly) {\n return;\n }\n this.#index = index;\n return;\n }\n const [token, ...restTokens] = tokens;\n const pattern = token === \"*\" ? restTokens.length === 0 ? [\"\", \"\", ONLY_WILDCARD_REG_EXP_STR] : [\"\", \"\", LABEL_REG_EXP_STR] : token === \"/*\" ? [\"\", \"\", TAIL_WILDCARD_REG_EXP_STR] : token.match(/^\\:([^\\{\\}]+)(?:\\{(.+)\\})?$/);\n let node;\n if (pattern) {\n const name = pattern[1];\n let regexpStr = pattern[2] || LABEL_REG_EXP_STR;\n if (name && pattern[2]) {\n if (regexpStr === \".*\") {\n throw PATH_ERROR;\n }\n regexpStr = regexpStr.replace(/^\\((?!\\?:)(?=[^)]+\\)$)/, \"(?:\");\n if (/\\((?!\\?:)/.test(regexpStr)) {\n throw PATH_ERROR;\n }\n }\n node = this.#children[regexpStr];\n if (!node) {\n if (Object.keys(this.#children).some(\n (k) => k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR\n )) {\n throw PATH_ERROR;\n }\n if (pathErrorCheckOnly) {\n return;\n }\n node = this.#children[regexpStr] = new _Node();\n if (name !== \"\") {\n node.#varIndex = context.varIndex++;\n }\n }\n if (!pathErrorCheckOnly && name !== \"\") {\n paramMap.push([name, node.#varIndex]);\n }\n } else {\n node = this.#children[token];\n if (!node) {\n if (Object.keys(this.#children).some(\n (k) => k.length > 1 && k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR\n )) {\n throw PATH_ERROR;\n }\n if (pathErrorCheckOnly) {\n return;\n }\n node = this.#children[token] = new _Node();\n }\n }\n node.insert(restTokens, index, paramMap, context, pathErrorCheckOnly);\n }\n buildRegExpStr() {\n const childKeys = Object.keys(this.#children).sort(compareKey);\n const strList = childKeys.map((k) => {\n const c = this.#children[k];\n return (typeof c.#varIndex === \"number\" ? `(${k})@${c.#varIndex}` : regExpMetaChars.has(k) ? `\\\\${k}` : k) + c.buildRegExpStr();\n });\n if (typeof this.#index === \"number\") {\n strList.unshift(`#${this.#index}`);\n }\n if (strList.length === 0) {\n return \"\";\n }\n if (strList.length === 1) {\n return strList[0];\n }\n return \"(?:\" + strList.join(\"|\") + \")\";\n }\n};\nexport {\n Node,\n PATH_ERROR\n};\n", "// src/router/reg-exp-router/trie.ts\nimport { Node } from \"./node.js\";\nvar Trie = class {\n #context = { varIndex: 0 };\n #root = new Node();\n insert(path, index, pathErrorCheckOnly) {\n const paramAssoc = [];\n const groups = [];\n for (let i = 0; ; ) {\n let replaced = false;\n path = path.replace(/\\{[^}]+\\}/g, (m) => {\n const mark = `@\\\\${i}`;\n groups[i] = [mark, m];\n i++;\n replaced = true;\n return mark;\n });\n if (!replaced) {\n break;\n }\n }\n const tokens = path.match(/(?::[^\\/]+)|(?:\\/\\*$)|./g) || [];\n for (let i = groups.length - 1; i >= 0; i--) {\n const [mark] = groups[i];\n for (let j = tokens.length - 1; j >= 0; j--) {\n if (tokens[j].indexOf(mark) !== -1) {\n tokens[j] = tokens[j].replace(mark, groups[i][1]);\n break;\n }\n }\n }\n this.#root.insert(tokens, index, paramAssoc, this.#context, pathErrorCheckOnly);\n return paramAssoc;\n }\n buildRegExp() {\n let regexp = this.#root.buildRegExpStr();\n if (regexp === \"\") {\n return [/^$/, [], []];\n }\n let captureIndex = 0;\n const indexReplacementMap = [];\n const paramReplacementMap = [];\n regexp = regexp.replace(/#(\\d+)|@(\\d+)|\\.\\*\\$/g, (_, handlerIndex, paramIndex) => {\n if (handlerIndex !== void 0) {\n indexReplacementMap[++captureIndex] = Number(handlerIndex);\n return \"$()\";\n }\n if (paramIndex !== void 0) {\n paramReplacementMap[Number(paramIndex)] = ++captureIndex;\n return \"\";\n }\n return \"\";\n });\n return [new RegExp(`^${regexp}`), indexReplacementMap, paramReplacementMap];\n }\n};\nexport {\n Trie\n};\n", "// src/router/reg-exp-router/prepared-router.ts\nimport { METHOD_NAME_ALL } from \"../../router.js\";\nimport { match, emptyParam } from \"./matcher.js\";\nimport { RegExpRouter } from \"./router.js\";\nvar PreparedRegExpRouter = class {\n name = \"PreparedRegExpRouter\";\n #matchers;\n #relocateMap;\n constructor(matchers, relocateMap) {\n this.#matchers = matchers;\n this.#relocateMap = relocateMap;\n }\n #addWildcard(method, handlerData) {\n const matcher = this.#matchers[method];\n matcher[1].forEach((list) => list && list.push(handlerData));\n Object.values(matcher[2]).forEach((list) => list[0].push(handlerData));\n }\n #addPath(method, path, handler, indexes, map) {\n const matcher = this.#matchers[method];\n if (!map) {\n matcher[2][path][0].push([handler, {}]);\n } else {\n indexes.forEach((index) => {\n if (typeof index === \"number\") {\n matcher[1][index].push([handler, map]);\n } else {\n ;\n matcher[2][index || path][0].push([handler, map]);\n }\n });\n }\n }\n add(method, path, handler) {\n if (!this.#matchers[method]) {\n const all = this.#matchers[METHOD_NAME_ALL];\n const staticMap = {};\n for (const key in all[2]) {\n staticMap[key] = [all[2][key][0].slice(), emptyParam];\n }\n this.#matchers[method] = [\n all[0],\n all[1].map((list) => Array.isArray(list) ? list.slice() : 0),\n staticMap\n ];\n }\n if (path === \"/*\" || path === \"*\") {\n const handlerData = [handler, {}];\n if (method === METHOD_NAME_ALL) {\n for (const m in this.#matchers) {\n this.#addWildcard(m, handlerData);\n }\n } else {\n this.#addWildcard(method, handlerData);\n }\n return;\n }\n const data = this.#relocateMap[path];\n if (!data) {\n throw new Error(`Path ${path} is not registered`);\n }\n for (const [indexes, map] of data) {\n if (method === METHOD_NAME_ALL) {\n for (const m in this.#matchers) {\n this.#addPath(m, path, handler, indexes, map);\n }\n } else {\n this.#addPath(method, path, handler, indexes, map);\n }\n }\n }\n buildAllMatchers() {\n return this.#matchers;\n }\n match = match;\n};\nvar buildInitParams = ({ paths }) => {\n const RegExpRouterWithMatcherExport = class extends RegExpRouter {\n buildAndExportAllMatchers() {\n return this.buildAllMatchers();\n }\n };\n const router = new RegExpRouterWithMatcherExport();\n for (const path of paths) {\n router.add(METHOD_NAME_ALL, path, path);\n }\n const matchers = router.buildAndExportAllMatchers();\n const all = matchers[METHOD_NAME_ALL];\n const relocateMap = {};\n for (const path of paths) {\n if (path === \"/*\" || path === \"*\") {\n continue;\n }\n all[1].forEach((list, i) => {\n list.forEach(([p, map]) => {\n if (p === path) {\n if (relocateMap[path]) {\n relocateMap[path][0][1] = {\n ...relocateMap[path][0][1],\n ...map\n };\n } else {\n relocateMap[path] = [[[], map]];\n }\n if (relocateMap[path][0][0].findIndex((j) => j === i) === -1) {\n relocateMap[path][0][0].push(i);\n }\n }\n });\n });\n for (const path2 in all[2]) {\n all[2][path2][0].forEach(([p]) => {\n if (p === path) {\n relocateMap[path] ||= [[[]]];\n const value = path2 === path ? \"\" : path2;\n if (relocateMap[path][0][0].findIndex((v) => v === value) === -1) {\n relocateMap[path][0][0].push(value);\n }\n }\n });\n }\n }\n for (let i = 0, len = all[1].length; i < len; i++) {\n all[1][i] = all[1][i] ? [] : 0;\n }\n for (const path in all[2]) {\n all[2][path][0] = [];\n }\n return [matchers, relocateMap];\n};\nvar serializeInitParams = ([matchers, relocateMap]) => {\n const matchersStr = JSON.stringify(\n matchers,\n (_, value) => value instanceof RegExp ? `##${value.toString()}##` : value\n ).replace(/\"##(.+?)##\"/g, (_, str) => str.replace(/\\\\\\\\/g, \"\\\\\"));\n const relocateMapStr = JSON.stringify(relocateMap);\n return `[${matchersStr},${relocateMapStr}]`;\n};\nexport {\n PreparedRegExpRouter,\n buildInitParams,\n serializeInitParams\n};\n", "// src/router/smart-router/index.ts\nimport { SmartRouter } from \"./router.js\";\nexport {\n SmartRouter\n};\n", "// src/router/smart-router/router.ts\nimport { MESSAGE_MATCHER_IS_ALREADY_BUILT, UnsupportedPathError } from \"../../router.js\";\nvar SmartRouter = class {\n name = \"SmartRouter\";\n #routers = [];\n #routes = [];\n constructor(init) {\n this.#routers = init.routers;\n }\n add(method, path, handler) {\n if (!this.#routes) {\n throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);\n }\n this.#routes.push([method, path, handler]);\n }\n match(method, path) {\n if (!this.#routes) {\n throw new Error(\"Fatal error\");\n }\n const routers = this.#routers;\n const routes = this.#routes;\n const len = routers.length;\n let i = 0;\n let res;\n for (; i < len; i++) {\n const router = routers[i];\n try {\n for (let i2 = 0, len2 = routes.length; i2 < len2; i2++) {\n router.add(...routes[i2]);\n }\n res = router.match(method, path);\n } catch (e) {\n if (e instanceof UnsupportedPathError) {\n continue;\n }\n throw e;\n }\n this.match = router.match.bind(router);\n this.#routers = [router];\n this.#routes = void 0;\n break;\n }\n if (i === len) {\n throw new Error(\"Fatal error\");\n }\n this.name = `SmartRouter + ${this.activeRouter.name}`;\n return res;\n }\n get activeRouter() {\n if (this.#routes || this.#routers.length !== 1) {\n throw new Error(\"No active router has been determined yet.\");\n }\n return this.#routers[0];\n }\n};\nexport {\n SmartRouter\n};\n", "// src/router/trie-router/index.ts\nimport { TrieRouter } from \"./router.js\";\nexport {\n TrieRouter\n};\n", "// src/router/trie-router/router.ts\nimport { checkOptionalParameter } from \"../../utils/url.js\";\nimport { Node } from \"./node.js\";\nvar TrieRouter = class {\n name = \"TrieRouter\";\n #node;\n constructor() {\n this.#node = new Node();\n }\n add(method, path, handler) {\n const results = checkOptionalParameter(path);\n if (results) {\n for (let i = 0, len = results.length; i < len; i++) {\n this.#node.insert(method, results[i], handler);\n }\n return;\n }\n this.#node.insert(method, path, handler);\n }\n match(method, path) {\n return this.#node.search(method, path);\n }\n};\nexport {\n TrieRouter\n};\n", "// src/router/trie-router/node.ts\nimport { METHOD_NAME_ALL } from \"../../router.js\";\nimport { getPattern, splitPath, splitRoutingPath } from \"../../utils/url.js\";\nvar emptyParams = /* @__PURE__ */ Object.create(null);\nvar hasChildren = (children) => {\n for (const _ in children) {\n return true;\n }\n return false;\n};\nvar Node = class _Node {\n #methods;\n #children;\n #patterns;\n #order = 0;\n #params = emptyParams;\n constructor(method, handler, children) {\n this.#children = children || /* @__PURE__ */ Object.create(null);\n this.#methods = [];\n if (method && handler) {\n const m = /* @__PURE__ */ Object.create(null);\n m[method] = { handler, possibleKeys: [], score: 0 };\n this.#methods = [m];\n }\n this.#patterns = [];\n }\n insert(method, path, handler) {\n this.#order = ++this.#order;\n let curNode = this;\n const parts = splitRoutingPath(path);\n const possibleKeys = [];\n for (let i = 0, len = parts.length; i < len; i++) {\n const p = parts[i];\n const nextP = parts[i + 1];\n const pattern = getPattern(p, nextP);\n const key = Array.isArray(pattern) ? pattern[0] : p;\n if (key in curNode.#children) {\n curNode = curNode.#children[key];\n if (pattern) {\n possibleKeys.push(pattern[1]);\n }\n continue;\n }\n curNode.#children[key] = new _Node();\n if (pattern) {\n curNode.#patterns.push(pattern);\n possibleKeys.push(pattern[1]);\n }\n curNode = curNode.#children[key];\n }\n curNode.#methods.push({\n [method]: {\n handler,\n possibleKeys: possibleKeys.filter((v, i, a) => a.indexOf(v) === i),\n score: this.#order\n }\n });\n return curNode;\n }\n #pushHandlerSets(handlerSets, node, method, nodeParams, params) {\n for (let i = 0, len = node.#methods.length; i < len; i++) {\n const m = node.#methods[i];\n const handlerSet = m[method] || m[METHOD_NAME_ALL];\n const processedSet = {};\n if (handlerSet !== void 0) {\n handlerSet.params = /* @__PURE__ */ Object.create(null);\n handlerSets.push(handlerSet);\n if (nodeParams !== emptyParams || params && params !== emptyParams) {\n for (let i2 = 0, len2 = handlerSet.possibleKeys.length; i2 < len2; i2++) {\n const key = handlerSet.possibleKeys[i2];\n const processed = processedSet[handlerSet.score];\n handlerSet.params[key] = params?.[key] && !processed ? params[key] : nodeParams[key] ?? params?.[key];\n processedSet[handlerSet.score] = true;\n }\n }\n }\n }\n }\n search(method, path) {\n const handlerSets = [];\n this.#params = emptyParams;\n const curNode = this;\n let curNodes = [curNode];\n const parts = splitPath(path);\n const curNodesQueue = [];\n const len = parts.length;\n let partOffsets = null;\n for (let i = 0; i < len; i++) {\n const part = parts[i];\n const isLast = i === len - 1;\n const tempNodes = [];\n for (let j = 0, len2 = curNodes.length; j < len2; j++) {\n const node = curNodes[j];\n const nextNode = node.#children[part];\n if (nextNode) {\n nextNode.#params = node.#params;\n if (isLast) {\n if (nextNode.#children[\"*\"]) {\n this.#pushHandlerSets(handlerSets, nextNode.#children[\"*\"], method, node.#params);\n }\n this.#pushHandlerSets(handlerSets, nextNode, method, node.#params);\n } else {\n tempNodes.push(nextNode);\n }\n }\n for (let k = 0, len3 = node.#patterns.length; k < len3; k++) {\n const pattern = node.#patterns[k];\n const params = node.#params === emptyParams ? {} : { ...node.#params };\n if (pattern === \"*\") {\n const astNode = node.#children[\"*\"];\n if (astNode) {\n this.#pushHandlerSets(handlerSets, astNode, method, node.#params);\n astNode.#params = params;\n tempNodes.push(astNode);\n }\n continue;\n }\n const [key, name, matcher] = pattern;\n if (!part && !(matcher instanceof RegExp)) {\n continue;\n }\n const child = node.#children[key];\n if (matcher instanceof RegExp) {\n if (partOffsets === null) {\n partOffsets = new Array(len);\n let offset = path[0] === \"/\" ? 1 : 0;\n for (let p = 0; p < len; p++) {\n partOffsets[p] = offset;\n offset += parts[p].length + 1;\n }\n }\n const restPathString = path.substring(partOffsets[i]);\n const m = matcher.exec(restPathString);\n if (m) {\n params[name] = m[0];\n this.#pushHandlerSets(handlerSets, child, method, node.#params, params);\n if (hasChildren(child.#children)) {\n child.#params = params;\n const componentCount = m[0].match(/\\//)?.length ?? 0;\n const targetCurNodes = curNodesQueue[componentCount] ||= [];\n targetCurNodes.push(child);\n }\n continue;\n }\n }\n if (matcher === true || matcher.test(part)) {\n params[name] = part;\n if (isLast) {\n this.#pushHandlerSets(handlerSets, child, method, params, node.#params);\n if (child.#children[\"*\"]) {\n this.#pushHandlerSets(\n handlerSets,\n child.#children[\"*\"],\n method,\n params,\n node.#params\n );\n }\n } else {\n child.#params = params;\n tempNodes.push(child);\n }\n }\n }\n }\n const shifted = curNodesQueue.shift();\n curNodes = shifted ? tempNodes.concat(shifted) : tempNodes;\n }\n if (handlerSets.length > 1) {\n handlerSets.sort((a, b) => {\n return a.score - b.score;\n });\n }\n return [handlerSets.map(({ handler, params }) => [handler, params])];\n }\n};\nexport {\n Node\n};\n", "const filterQueryCache = new Map();\nfunction matchFilter(filter) {\n const queries = Array.isArray(filter) ? filter : [\n filter\n ];\n const key = queries.join(\",\");\n const predicate = filterQueryCache.get(key) ?? (()=>{\n const parsed = parse(queries);\n const pred = compile(parsed);\n filterQueryCache.set(key, pred);\n return pred;\n })();\n return (ctx)=>predicate(ctx);\n}\nfunction parse(filter) {\n return Array.isArray(filter) ? filter.map((q)=>q.split(\":\")) : [\n filter.split(\":\")\n ];\n}\nfunction compile(parsed) {\n const preprocessed = parsed.flatMap((q)=>check(q, preprocess(q)));\n const ltree = treeify(preprocessed);\n const predicate = arborist(ltree);\n return (ctx)=>!!predicate(ctx.update, ctx);\n}\nfunction preprocess(filter) {\n const valid = UPDATE_KEYS;\n const expanded = [\n filter\n ].flatMap((q)=>{\n const [l1, l2, l3] = q;\n if (!(l1 in L1_SHORTCUTS)) return [\n q\n ];\n if (!l1 && !l2 && !l3) return [\n q\n ];\n const targets = L1_SHORTCUTS[l1];\n const expanded = targets.map((s)=>[\n s,\n l2,\n l3\n ]);\n if (l2 === undefined) return expanded;\n if (l2 in L2_SHORTCUTS && (l2 || l3)) return expanded;\n return expanded.filter(([s])=>!!valid[s]?.[l2]);\n }).flatMap((q)=>{\n const [l1, l2, l3] = q;\n if (!(l2 in L2_SHORTCUTS)) return [\n q\n ];\n if (!l2 && !l3) return [\n q\n ];\n const targets = L2_SHORTCUTS[l2];\n const expanded = targets.map((s)=>[\n l1,\n s,\n l3\n ]);\n if (l3 === undefined) return expanded;\n return expanded.filter(([, s])=>!!valid[l1]?.[s]?.[l3]);\n });\n if (expanded.length === 0) {\n throw new Error(`Shortcuts in '${filter.join(\":\")}' do not expand to any valid filter query`);\n }\n return expanded;\n}\nfunction check(original, preprocessed) {\n if (preprocessed.length === 0) throw new Error(\"Empty filter query given\");\n const errors = preprocessed.map(checkOne).filter((r)=>r !== true);\n if (errors.length === 0) return preprocessed;\n else if (errors.length === 1) throw new Error(errors[0]);\n else {\n throw new Error(`Invalid filter query '${original.join(\":\")}'. There are ${errors.length} errors after expanding the contained shortcuts: ${errors.join(\"; \")}`);\n }\n}\nfunction checkOne(filter) {\n const [l1, l2, l3, ...n] = filter;\n if (l1 === undefined) return \"Empty filter query given\";\n if (!(l1 in UPDATE_KEYS)) {\n const permitted = Object.keys(UPDATE_KEYS);\n return `Invalid L1 filter '${l1}' given in '${filter.join(\":\")}'. \\\nPermitted values are: ${permitted.map((k)=>`'${k}'`).join(\", \")}.`;\n }\n if (l2 === undefined) return true;\n const l1Obj = UPDATE_KEYS[l1];\n if (!(l2 in l1Obj)) {\n const permitted = Object.keys(l1Obj);\n return `Invalid L2 filter '${l2}' given in '${filter.join(\":\")}'. \\\nPermitted values are: ${permitted.map((k)=>`'${k}'`).join(\", \")}.`;\n }\n if (l3 === undefined) return true;\n const l2Obj = l1Obj[l2];\n if (!(l3 in l2Obj)) {\n const permitted = Object.keys(l2Obj);\n return `Invalid L3 filter '${l3}' given in '${filter.join(\":\")}'. ${permitted.length === 0 ? `No further filtering is possible after '${l1}:${l2}'.` : `Permitted values are: ${permitted.map((k)=>`'${k}'`).join(\", \")}.`}`;\n }\n if (n.length === 0) return true;\n return `Cannot filter further than three levels, ':${n.join(\":\")}' is invalid!`;\n}\nfunction treeify(paths) {\n const tree = {};\n for (const [l1, l2, l3] of paths){\n const subtree = tree[l1] ??= {};\n if (l2 !== undefined) {\n const set = subtree[l2] ??= new Set();\n if (l3 !== undefined) set.add(l3);\n }\n }\n return tree;\n}\nfunction or(left, right) {\n return (obj, ctx)=>left(obj, ctx) || right(obj, ctx);\n}\nfunction concat(get, test) {\n return (obj, ctx)=>{\n const nextObj = get(obj, ctx);\n return nextObj && test(nextObj, ctx);\n };\n}\nfunction leaf(pred) {\n return (obj, ctx)=>pred(obj, ctx) != null;\n}\nfunction arborist(tree) {\n const l1Predicates = Object.entries(tree).map(([l1, subtree])=>{\n const l1Pred = (obj)=>obj[l1];\n const l2Predicates = Object.entries(subtree).map(([l2, set])=>{\n const l2Pred = (obj)=>obj[l2];\n const l3Predicates = Array.from(set).map((l3)=>{\n const l3Pred = l3 === \"me\" ? (obj, ctx)=>{\n const me = ctx.me.id;\n return testMaybeArray(obj, (u)=>u.id === me);\n } : (obj)=>testMaybeArray(obj, (e)=>e[l3] || e.type === l3);\n return l3Pred;\n });\n return l3Predicates.length === 0 ? leaf(l2Pred) : concat(l2Pred, l3Predicates.reduce(or));\n });\n return l2Predicates.length === 0 ? leaf(l1Pred) : concat(l1Pred, l2Predicates.reduce(or));\n });\n if (l1Predicates.length === 0) {\n throw new Error(\"Cannot create filter function for empty query\");\n }\n return l1Predicates.reduce(or);\n}\nfunction testMaybeArray(t, pred) {\n const p = (x)=>x != null && pred(x);\n return Array.isArray(t) ? t.some(p) : p(t);\n}\nconst ENTITY_KEYS = {\n mention: {},\n hashtag: {},\n cashtag: {},\n bot_command: {},\n url: {},\n email: {},\n phone_number: {},\n bold: {},\n italic: {},\n underline: {},\n strikethrough: {},\n spoiler: {},\n blockquote: {},\n expandable_blockquote: {},\n code: {},\n pre: {},\n text_link: {},\n text_mention: {},\n custom_emoji: {}\n};\nconst USER_KEYS = {\n me: {},\n is_bot: {},\n is_premium: {},\n added_to_attachment_menu: {}\n};\nconst FORWARD_ORIGIN_KEYS = {\n user: {},\n hidden_user: {},\n chat: {},\n channel: {}\n};\nconst STICKER_KEYS = {\n is_video: {},\n is_animated: {},\n premium_animation: {}\n};\nconst REACTION_KEYS = {\n emoji: {},\n custom_emoji: {},\n paid: {}\n};\nconst GIFT_INFO_KEYS = {\n can_be_upgraded: {},\n is_upgrade_separate: {},\n is_private: {}\n};\nconst COMMON_MESSAGE_KEYS = {\n forward_origin: FORWARD_ORIGIN_KEYS,\n is_topic_message: {},\n is_automatic_forward: {},\n business_connection_id: {},\n text: {},\n animation: {},\n audio: {},\n document: {},\n paid_media: {},\n photo: {},\n sticker: STICKER_KEYS,\n story: {},\n video: {},\n video_note: {},\n voice: {},\n contact: {},\n dice: {},\n game: {},\n poll: {},\n venue: {},\n location: {},\n entities: ENTITY_KEYS,\n caption_entities: ENTITY_KEYS,\n caption: {},\n link_preview_options: {\n url: {},\n prefer_small_media: {},\n prefer_large_media: {},\n show_above_text: {}\n },\n effect_id: {},\n paid_star_count: {},\n has_media_spoiler: {},\n new_chat_title: {},\n new_chat_photo: {},\n delete_chat_photo: {},\n message_auto_delete_timer_changed: {},\n pinned_message: {},\n invoice: {},\n proximity_alert_triggered: {},\n chat_background_set: {},\n giveaway_created: {},\n giveaway: {\n only_new_members: {},\n has_public_winners: {}\n },\n giveaway_winners: {\n only_new_members: {},\n was_refunded: {}\n },\n giveaway_completed: {},\n gift: GIFT_INFO_KEYS,\n gift_upgrade_sent: GIFT_INFO_KEYS,\n unique_gift: {\n transfer_star_count: {}\n },\n paid_message_price_changed: {},\n video_chat_scheduled: {},\n video_chat_started: {},\n video_chat_ended: {},\n video_chat_participants_invited: {},\n web_app_data: {}\n};\nconst MESSAGE_KEYS = {\n ...COMMON_MESSAGE_KEYS,\n direct_messages_topic: {},\n chat_owner_left: {\n new_owner: {}\n },\n chat_owner_changd: {},\n new_chat_members: USER_KEYS,\n left_chat_member: USER_KEYS,\n group_chat_created: {},\n supergroup_chat_created: {},\n migrate_to_chat_id: {},\n migrate_from_chat_id: {},\n successful_payment: {},\n refunded_payment: {},\n users_shared: {},\n chat_shared: {},\n connected_website: {},\n write_access_allowed: {},\n passport_data: {},\n boost_added: {},\n forum_topic_created: {\n is_name_implicit: {}\n },\n forum_topic_edited: {\n name: {},\n icon_custom_emoji_id: {}\n },\n forum_topic_closed: {},\n forum_topic_reopened: {},\n general_forum_topic_hidden: {},\n general_forum_topic_unhidden: {},\n checklist: {\n others_can_add_tasks: {},\n others_can_mark_tasks_as_done: {}\n },\n checklist_tasks_done: {},\n checklist_tasks_added: {},\n suggested_post_info: {},\n suggested_post_approved: {},\n suggested_post_approval_failed: {},\n suggested_post_declined: {},\n suggested_post_paid: {},\n suggested_post_refunded: {},\n sender_boost_count: {}\n};\nconst CHANNEL_POST_KEYS = {\n ...COMMON_MESSAGE_KEYS,\n channel_chat_created: {},\n direct_message_price_changed: {},\n is_paid_post: {}\n};\nconst BUSINESS_CONNECTION_KEYS = {\n can_reply: {},\n is_enabled: {}\n};\nconst MESSAGE_REACTION_KEYS = {\n old_reaction: REACTION_KEYS,\n new_reaction: REACTION_KEYS\n};\nconst MESSAGE_REACTION_COUNT_UPDATED_KEYS = {\n reactions: REACTION_KEYS\n};\nconst CALLBACK_QUERY_KEYS = {\n data: {},\n game_short_name: {}\n};\nconst CHAT_MEMBER_UPDATED_KEYS = {\n from: USER_KEYS\n};\nconst UPDATE_KEYS = {\n message: MESSAGE_KEYS,\n edited_message: MESSAGE_KEYS,\n channel_post: CHANNEL_POST_KEYS,\n edited_channel_post: CHANNEL_POST_KEYS,\n business_connection: BUSINESS_CONNECTION_KEYS,\n business_message: MESSAGE_KEYS,\n edited_business_message: MESSAGE_KEYS,\n deleted_business_messages: {},\n inline_query: {},\n chosen_inline_result: {},\n callback_query: CALLBACK_QUERY_KEYS,\n shipping_query: {},\n pre_checkout_query: {},\n poll: {},\n poll_answer: {},\n my_chat_member: CHAT_MEMBER_UPDATED_KEYS,\n chat_member: CHAT_MEMBER_UPDATED_KEYS,\n chat_join_request: {},\n message_reaction: MESSAGE_REACTION_KEYS,\n message_reaction_count: MESSAGE_REACTION_COUNT_UPDATED_KEYS,\n chat_boost: {},\n removed_chat_boost: {},\n purchased_paid_media: {}\n};\nconst L1_SHORTCUTS = {\n \"\": [\n \"message\",\n \"channel_post\"\n ],\n msg: [\n \"message\",\n \"channel_post\"\n ],\n edit: [\n \"edited_message\",\n \"edited_channel_post\"\n ]\n};\nconst L2_SHORTCUTS = {\n \"\": [\n \"entities\",\n \"caption_entities\"\n ],\n media: [\n \"photo\",\n \"video\"\n ],\n file: [\n \"photo\",\n \"animation\",\n \"audio\",\n \"document\",\n \"video\",\n \"video_note\",\n \"voice\",\n \"sticker\"\n ]\n};\nconst checker = {\n filterQuery (filter) {\n const pred = matchFilter(filter);\n return (ctx)=>pred(ctx);\n },\n text (trigger) {\n const hasText = checker.filterQuery([\n \":text\",\n \":caption\"\n ]);\n const trg = triggerFn(trigger);\n return (ctx)=>{\n if (!hasText(ctx)) return false;\n const msg = ctx.message ?? ctx.channelPost;\n const txt = msg.text ?? msg.caption;\n return match(ctx, txt, trg);\n };\n },\n command (command) {\n const hasEntities = checker.filterQuery(\":entities:bot_command\");\n const atCommands = new Set();\n const noAtCommands = new Set();\n toArray(command).forEach((cmd)=>{\n if (cmd.startsWith(\"/\")) {\n throw new Error(`Do not include '/' when registering command handlers (use '${cmd.substring(1)}' not '${cmd}')`);\n }\n const set = cmd.includes(\"@\") ? atCommands : noAtCommands;\n set.add(cmd);\n });\n return (ctx)=>{\n if (!hasEntities(ctx)) return false;\n const msg = ctx.message ?? ctx.channelPost;\n const txt = msg.text ?? msg.caption;\n return msg.entities.some((e)=>{\n if (e.type !== \"bot_command\") return false;\n if (e.offset !== 0) return false;\n const cmd = txt.substring(1, e.length);\n if (noAtCommands.has(cmd) || atCommands.has(cmd)) {\n ctx.match = txt.substring(cmd.length + 1).trimStart();\n return true;\n }\n const index = cmd.indexOf(\"@\");\n if (index === -1) return false;\n const atTarget = cmd.substring(index + 1).toLowerCase();\n const username = ctx.me.username.toLowerCase();\n if (atTarget !== username) return false;\n const atCommand = cmd.substring(0, index);\n if (noAtCommands.has(atCommand)) {\n ctx.match = txt.substring(cmd.length + 1).trimStart();\n return true;\n }\n return false;\n });\n };\n },\n reaction (reaction) {\n const hasMessageReaction = checker.filterQuery(\"message_reaction\");\n const normalized = typeof reaction === \"string\" ? [\n {\n type: \"emoji\",\n emoji: reaction\n }\n ] : (Array.isArray(reaction) ? reaction : [\n reaction\n ]).map((emoji)=>typeof emoji === \"string\" ? {\n type: \"emoji\",\n emoji\n } : emoji);\n const emoji = new Set(normalized.filter((r)=>r.type === \"emoji\").map((r)=>r.emoji));\n const customEmoji = new Set(normalized.filter((r)=>r.type === \"custom_emoji\").map((r)=>r.custom_emoji_id));\n const paid = normalized.some((r)=>r.type === \"paid\");\n return (ctx)=>{\n if (!hasMessageReaction(ctx)) return false;\n const { old_reaction, new_reaction } = ctx.messageReaction;\n for (const reaction of new_reaction){\n let isOld = false;\n if (reaction.type === \"emoji\") {\n for (const old of old_reaction){\n if (old.type !== \"emoji\") continue;\n if (old.emoji === reaction.emoji) {\n isOld = true;\n break;\n }\n }\n } else if (reaction.type === \"custom_emoji\") {\n for (const old of old_reaction){\n if (old.type !== \"custom_emoji\") continue;\n if (old.custom_emoji_id === reaction.custom_emoji_id) {\n isOld = true;\n break;\n }\n }\n } else if (reaction.type === \"paid\") {\n for (const old of old_reaction){\n if (old.type !== \"paid\") continue;\n isOld = true;\n break;\n }\n } else {}\n if (isOld) continue;\n if (reaction.type === \"emoji\") {\n if (emoji.has(reaction.emoji)) return true;\n } else if (reaction.type === \"custom_emoji\") {\n if (customEmoji.has(reaction.custom_emoji_id)) return true;\n } else if (reaction.type === \"paid\") {\n if (paid) return true;\n } else {\n return true;\n }\n }\n return false;\n };\n },\n chatType (chatType) {\n const set = new Set(toArray(chatType));\n return (ctx)=>ctx.chat?.type !== undefined && set.has(ctx.chat.type);\n },\n callbackQuery (trigger) {\n const hasCallbackQuery = checker.filterQuery(\"callback_query:data\");\n const trg = triggerFn(trigger);\n return (ctx)=>hasCallbackQuery(ctx) && match(ctx, ctx.callbackQuery.data, trg);\n },\n gameQuery (trigger) {\n const hasGameQuery = checker.filterQuery(\"callback_query:game_short_name\");\n const trg = triggerFn(trigger);\n return (ctx)=>hasGameQuery(ctx) && match(ctx, ctx.callbackQuery.game_short_name, trg);\n },\n inlineQuery (trigger) {\n const hasInlineQuery = checker.filterQuery(\"inline_query\");\n const trg = triggerFn(trigger);\n return (ctx)=>hasInlineQuery(ctx) && match(ctx, ctx.inlineQuery.query, trg);\n },\n chosenInlineResult (trigger) {\n const hasChosenInlineResult = checker.filterQuery(\"chosen_inline_result\");\n const trg = triggerFn(trigger);\n return (ctx)=>hasChosenInlineResult(ctx) && match(ctx, ctx.chosenInlineResult.result_id, trg);\n },\n preCheckoutQuery (trigger) {\n const hasPreCheckoutQuery = checker.filterQuery(\"pre_checkout_query\");\n const trg = triggerFn(trigger);\n return (ctx)=>hasPreCheckoutQuery(ctx) && match(ctx, ctx.preCheckoutQuery.invoice_payload, trg);\n },\n shippingQuery (trigger) {\n const hasShippingQuery = checker.filterQuery(\"shipping_query\");\n const trg = triggerFn(trigger);\n return (ctx)=>hasShippingQuery(ctx) && match(ctx, ctx.shippingQuery.invoice_payload, trg);\n }\n};\nclass Context {\n update;\n api;\n me;\n match;\n constructor(update, api, me){\n this.update = update;\n this.api = api;\n this.me = me;\n }\n get message() {\n return this.update.message;\n }\n get editedMessage() {\n return this.update.edited_message;\n }\n get channelPost() {\n return this.update.channel_post;\n }\n get editedChannelPost() {\n return this.update.edited_channel_post;\n }\n get businessConnection() {\n return this.update.business_connection;\n }\n get businessMessage() {\n return this.update.business_message;\n }\n get editedBusinessMessage() {\n return this.update.edited_business_message;\n }\n get deletedBusinessMessages() {\n return this.update.deleted_business_messages;\n }\n get messageReaction() {\n return this.update.message_reaction;\n }\n get messageReactionCount() {\n return this.update.message_reaction_count;\n }\n get inlineQuery() {\n return this.update.inline_query;\n }\n get chosenInlineResult() {\n return this.update.chosen_inline_result;\n }\n get callbackQuery() {\n return this.update.callback_query;\n }\n get shippingQuery() {\n return this.update.shipping_query;\n }\n get preCheckoutQuery() {\n return this.update.pre_checkout_query;\n }\n get poll() {\n return this.update.poll;\n }\n get pollAnswer() {\n return this.update.poll_answer;\n }\n get myChatMember() {\n return this.update.my_chat_member;\n }\n get chatMember() {\n return this.update.chat_member;\n }\n get chatJoinRequest() {\n return this.update.chat_join_request;\n }\n get chatBoost() {\n return this.update.chat_boost;\n }\n get removedChatBoost() {\n return this.update.removed_chat_boost;\n }\n get purchasedPaidMedia() {\n return this.update.purchased_paid_media;\n }\n get msg() {\n return this.message ?? this.editedMessage ?? this.channelPost ?? this.editedChannelPost ?? this.businessMessage ?? this.editedBusinessMessage ?? this.callbackQuery?.message;\n }\n get chat() {\n return (this.msg ?? this.deletedBusinessMessages ?? this.messageReaction ?? this.messageReactionCount ?? this.myChatMember ?? this.chatMember ?? this.chatJoinRequest ?? this.chatBoost ?? this.removedChatBoost)?.chat;\n }\n get senderChat() {\n return this.msg?.sender_chat;\n }\n get from() {\n return (this.businessConnection ?? this.messageReaction ?? (this.chatBoost?.boost ?? this.removedChatBoost)?.source)?.user ?? (this.callbackQuery ?? this.msg ?? this.inlineQuery ?? this.chosenInlineResult ?? this.shippingQuery ?? this.preCheckoutQuery ?? this.myChatMember ?? this.chatMember ?? this.chatJoinRequest ?? this.purchasedPaidMedia)?.from;\n }\n get msgId() {\n return this.msg?.message_id ?? this.messageReaction?.message_id ?? this.messageReactionCount?.message_id;\n }\n get chatId() {\n return this.chat?.id ?? this.businessConnection?.user_chat_id;\n }\n get inlineMessageId() {\n return this.callbackQuery?.inline_message_id ?? this.chosenInlineResult?.inline_message_id;\n }\n get businessConnectionId() {\n return this.msg?.business_connection_id ?? this.businessConnection?.id ?? this.deletedBusinessMessages?.business_connection_id;\n }\n entities(types) {\n const message = this.msg;\n if (message === undefined) return [];\n const text = message.text ?? message.caption;\n if (text === undefined) return [];\n let entities = message.entities ?? message.caption_entities;\n if (entities === undefined) return [];\n if (types !== undefined) {\n const filters = new Set(toArray(types));\n entities = entities.filter((entity)=>filters.has(entity.type));\n }\n return entities.map((entity)=>({\n ...entity,\n text: text.substring(entity.offset, entity.offset + entity.length)\n }));\n }\n reactions() {\n const emoji = [];\n const emojiAdded = [];\n const emojiKept = [];\n const emojiRemoved = [];\n const customEmoji = [];\n const customEmojiAdded = [];\n const customEmojiKept = [];\n const customEmojiRemoved = [];\n let paid = false;\n let paidAdded = false;\n const r = this.messageReaction;\n if (r !== undefined) {\n const { old_reaction, new_reaction } = r;\n for (const reaction of new_reaction){\n if (reaction.type === \"emoji\") {\n emoji.push(reaction.emoji);\n } else if (reaction.type === \"custom_emoji\") {\n customEmoji.push(reaction.custom_emoji_id);\n } else if (reaction.type === \"paid\") {\n paid = paidAdded = true;\n }\n }\n for (const reaction of old_reaction){\n if (reaction.type === \"emoji\") {\n emojiRemoved.push(reaction.emoji);\n } else if (reaction.type === \"custom_emoji\") {\n customEmojiRemoved.push(reaction.custom_emoji_id);\n } else if (reaction.type === \"paid\") {\n paidAdded = false;\n }\n }\n emojiAdded.push(...emoji);\n customEmojiAdded.push(...customEmoji);\n for(let i = 0; i < emojiRemoved.length; i++){\n const len = emojiAdded.length;\n if (len === 0) break;\n const rem = emojiRemoved[i];\n for(let j = 0; j < len; j++){\n if (rem === emojiAdded[j]) {\n emojiKept.push(rem);\n emojiRemoved.splice(i, 1);\n emojiAdded.splice(j, 1);\n i--;\n break;\n }\n }\n }\n for(let i = 0; i < customEmojiRemoved.length; i++){\n const len = customEmojiAdded.length;\n if (len === 0) break;\n const rem = customEmojiRemoved[i];\n for(let j = 0; j < len; j++){\n if (rem === customEmojiAdded[j]) {\n customEmojiKept.push(rem);\n customEmojiRemoved.splice(i, 1);\n customEmojiAdded.splice(j, 1);\n i--;\n break;\n }\n }\n }\n }\n return {\n emoji,\n emojiAdded,\n emojiKept,\n emojiRemoved,\n customEmoji,\n customEmojiAdded,\n customEmojiKept,\n customEmojiRemoved,\n paid,\n paidAdded\n };\n }\n static has = checker;\n has(filter) {\n return Context.has.filterQuery(filter)(this);\n }\n hasText(trigger) {\n return Context.has.text(trigger)(this);\n }\n hasCommand(command) {\n return Context.has.command(command)(this);\n }\n hasReaction(reaction) {\n return Context.has.reaction(reaction)(this);\n }\n hasChatType(chatType) {\n return Context.has.chatType(chatType)(this);\n }\n hasCallbackQuery(trigger) {\n return Context.has.callbackQuery(trigger)(this);\n }\n hasGameQuery(trigger) {\n return Context.has.gameQuery(trigger)(this);\n }\n hasInlineQuery(trigger) {\n return Context.has.inlineQuery(trigger)(this);\n }\n hasChosenInlineResult(trigger) {\n return Context.has.chosenInlineResult(trigger)(this);\n }\n hasPreCheckoutQuery(trigger) {\n return Context.has.preCheckoutQuery(trigger)(this);\n }\n hasShippingQuery(trigger) {\n return Context.has.shippingQuery(trigger)(this);\n }\n reply(text, other, signal) {\n const msg = this.msg;\n return this.api.sendMessage(orThrow(this.chatId, \"sendMessage\"), text, {\n business_connection_id: this.businessConnectionId,\n ...msg?.is_topic_message ? {\n message_thread_id: msg.message_thread_id\n } : {},\n direct_messages_topic_id: msg?.direct_messages_topic?.topic_id,\n ...other\n }, signal);\n }\n replyWithDraft(text, other, signal) {\n const msg = this.msg;\n return this.api.sendMessageDraft(orThrow(this.chatId, \"sendMessageDraft\"), this.update.update_id, text, {\n ...msg?.is_topic_message ? {\n message_thread_id: msg?.message_thread_id\n } : {},\n ...other\n }, signal);\n }\n forwardMessage(chat_id, other, signal) {\n const msg = this.msg;\n return this.api.forwardMessage(chat_id, orThrow(this.chatId, \"forwardMessage\"), orThrow(this.msgId, \"forwardMessage\"), {\n direct_messages_topic_id: msg?.direct_messages_topic?.topic_id,\n ...other\n }, signal);\n }\n forwardMessages(chat_id, message_ids, other, signal) {\n const msg = this.msg;\n return this.api.forwardMessages(chat_id, orThrow(this.chatId, \"forwardMessages\"), message_ids, {\n direct_messages_topic_id: msg?.direct_messages_topic?.topic_id,\n ...other\n }, signal);\n }\n copyMessage(chat_id, other, signal) {\n const msg = this.msg;\n return this.api.copyMessage(chat_id, orThrow(this.chatId, \"copyMessage\"), orThrow(this.msgId, \"copyMessage\"), {\n direct_messages_topic_id: msg?.direct_messages_topic?.topic_id,\n ...other\n }, signal);\n }\n copyMessages(chat_id, message_ids, other, signal) {\n const msg = this.msg;\n return this.api.copyMessages(chat_id, orThrow(this.chatId, \"copyMessages\"), message_ids, {\n direct_messages_topic_id: msg?.direct_messages_topic?.topic_id,\n ...other\n }, signal);\n }\n replyWithPhoto(photo, other, signal) {\n const msg = this.msg;\n return this.api.sendPhoto(orThrow(this.chatId, \"sendPhoto\"), photo, {\n business_connection_id: this.businessConnectionId,\n ...msg?.is_topic_message ? {\n message_thread_id: msg.message_thread_id\n } : {},\n direct_messages_topic_id: msg?.direct_messages_topic?.topic_id,\n ...other\n }, signal);\n }\n replyWithAudio(audio, other, signal) {\n const msg = this.msg;\n return this.api.sendAudio(orThrow(this.chatId, \"sendAudio\"), audio, {\n business_connection_id: this.businessConnectionId,\n ...msg?.is_topic_message ? {\n message_thread_id: msg.message_thread_id\n } : {},\n direct_messages_topic_id: msg?.direct_messages_topic?.topic_id,\n ...other\n }, signal);\n }\n replyWithDocument(document1, other, signal) {\n const msg = this.msg;\n return this.api.sendDocument(orThrow(this.chatId, \"sendDocument\"), document1, {\n business_connection_id: this.businessConnectionId,\n ...msg?.is_topic_message ? {\n message_thread_id: msg.message_thread_id\n } : {},\n direct_messages_topic_id: msg?.direct_messages_topic?.topic_id,\n ...other\n }, signal);\n }\n replyWithVideo(video, other, signal) {\n const msg = this.msg;\n return this.api.sendVideo(orThrow(this.chatId, \"sendVideo\"), video, {\n business_connection_id: this.businessConnectionId,\n ...msg?.is_topic_message ? {\n message_thread_id: msg.message_thread_id\n } : {},\n direct_messages_topic_id: msg?.direct_messages_topic?.topic_id,\n ...other\n }, signal);\n }\n replyWithAnimation(animation, other, signal) {\n const msg = this.msg;\n return this.api.sendAnimation(orThrow(this.chatId, \"sendAnimation\"), animation, {\n business_connection_id: this.businessConnectionId,\n ...msg?.is_topic_message ? {\n message_thread_id: msg.message_thread_id\n } : {},\n direct_messages_topic_id: msg?.direct_messages_topic?.topic_id,\n ...other\n }, signal);\n }\n replyWithVoice(voice, other, signal) {\n const msg = this.msg;\n return this.api.sendVoice(orThrow(this.chatId, \"sendVoice\"), voice, {\n business_connection_id: this.businessConnectionId,\n ...msg?.is_topic_message ? {\n message_thread_id: msg.message_thread_id\n } : {},\n direct_messages_topic_id: msg?.direct_messages_topic?.topic_id,\n ...other\n }, signal);\n }\n replyWithVideoNote(video_note, other, signal) {\n const msg = this.msg;\n return this.api.sendVideoNote(orThrow(this.chatId, \"sendVideoNote\"), video_note, {\n business_connection_id: this.businessConnectionId,\n ...msg?.is_topic_message ? {\n message_thread_id: msg.message_thread_id\n } : {},\n direct_messages_topic_id: msg?.direct_messages_topic?.topic_id,\n ...other\n }, signal);\n }\n replyWithMediaGroup(media, other, signal) {\n const msg = this.msg;\n return this.api.sendMediaGroup(orThrow(this.chatId, \"sendMediaGroup\"), media, {\n business_connection_id: this.businessConnectionId,\n ...msg?.is_topic_message ? {\n message_thread_id: msg.message_thread_id\n } : {},\n direct_messages_topic_id: msg?.direct_messages_topic?.topic_id,\n ...other\n }, signal);\n }\n replyWithLocation(latitude, longitude, other, signal) {\n const msg = this.msg;\n return this.api.sendLocation(orThrow(this.chatId, \"sendLocation\"), latitude, longitude, {\n business_connection_id: this.businessConnectionId,\n ...msg?.is_topic_message ? {\n message_thread_id: msg.message_thread_id\n } : {},\n direct_messages_topic_id: msg?.direct_messages_topic?.topic_id,\n ...other\n }, signal);\n }\n editMessageLiveLocation(latitude, longitude, other, signal) {\n const inlineId = this.inlineMessageId;\n return inlineId !== undefined ? this.api.editMessageLiveLocationInline(inlineId, latitude, longitude, {\n business_connection_id: this.businessConnectionId,\n ...other\n }, signal) : this.api.editMessageLiveLocation(orThrow(this.chatId, \"editMessageLiveLocation\"), orThrow(this.msgId, \"editMessageLiveLocation\"), latitude, longitude, {\n business_connection_id: this.businessConnectionId,\n ...other\n }, signal);\n }\n stopMessageLiveLocation(other, signal) {\n const inlineId = this.inlineMessageId;\n return inlineId !== undefined ? this.api.stopMessageLiveLocationInline(inlineId, {\n business_connection_id: this.businessConnectionId,\n ...other\n }, signal) : this.api.stopMessageLiveLocation(orThrow(this.chatId, \"stopMessageLiveLocation\"), orThrow(this.msgId, \"stopMessageLiveLocation\"), {\n business_connection_id: this.businessConnectionId,\n ...other\n }, signal);\n }\n sendPaidMedia(star_count, media, other, signal) {\n const msg = this.msg;\n return this.api.sendPaidMedia(orThrow(this.chatId, \"sendPaidMedia\"), star_count, media, {\n business_connection_id: this.businessConnectionId,\n ...msg?.is_topic_message ? {\n message_thread_id: msg.message_thread_id\n } : {},\n direct_messages_topic_id: this.msg?.direct_messages_topic?.topic_id,\n ...other\n }, signal);\n }\n replyWithVenue(latitude, longitude, title, address, other, signal) {\n const msg = this.msg;\n return this.api.sendVenue(orThrow(this.chatId, \"sendVenue\"), latitude, longitude, title, address, {\n business_connection_id: this.businessConnectionId,\n ...msg?.is_topic_message ? {\n message_thread_id: msg.message_thread_id\n } : {},\n direct_messages_topic_id: msg?.direct_messages_topic?.topic_id,\n ...other\n }, signal);\n }\n replyWithContact(phone_number, first_name, other, signal) {\n const msg = this.msg;\n return this.api.sendContact(orThrow(this.chatId, \"sendContact\"), phone_number, first_name, {\n business_connection_id: this.businessConnectionId,\n ...msg?.is_topic_message ? {\n message_thread_id: msg.message_thread_id\n } : {},\n direct_messages_topic_id: msg?.direct_messages_topic?.topic_id,\n ...other\n }, signal);\n }\n replyWithPoll(question, options, other, signal) {\n const msg = this.msg;\n return this.api.sendPoll(orThrow(this.chatId, \"sendPoll\"), question, options, {\n business_connection_id: this.businessConnectionId,\n ...msg?.is_topic_message ? {\n message_thread_id: msg.message_thread_id\n } : {},\n ...other\n }, signal);\n }\n replyWithChecklist(checklist, other, signal) {\n return this.api.sendChecklist(orThrow(this.businessConnectionId, \"sendChecklist\"), orThrow(this.chatId, \"sendChecklist\"), checklist, other, signal);\n }\n editMessageChecklist(checklist, other, signal) {\n const msg = orThrow(this.msg, \"editMessageChecklist\");\n const target = msg.checklist_tasks_done?.checklist_message ?? msg.checklist_tasks_added?.checklist_message ?? msg;\n return this.api.editMessageChecklist(orThrow(this.businessConnectionId, \"editMessageChecklist\"), orThrow(target.chat.id, \"editMessageChecklist\"), orThrow(target.message_id, \"editMessageChecklist\"), checklist, other, signal);\n }\n replyWithDice(emoji, other, signal) {\n const msg = this.msg;\n return this.api.sendDice(orThrow(this.chatId, \"sendDice\"), emoji, {\n business_connection_id: this.businessConnectionId,\n ...msg?.is_topic_message ? {\n message_thread_id: msg.message_thread_id\n } : {},\n direct_messages_topic_id: msg?.direct_messages_topic?.topic_id,\n ...other\n }, signal);\n }\n replyWithChatAction(action, other, signal) {\n const msg = this.msg;\n return this.api.sendChatAction(orThrow(this.chatId, \"sendChatAction\"), action, {\n business_connection_id: this.businessConnectionId,\n message_thread_id: msg?.message_thread_id,\n ...other\n }, signal);\n }\n react(reaction, other, signal) {\n return this.api.setMessageReaction(orThrow(this.chatId, \"setMessageReaction\"), orThrow(this.msgId, \"setMessageReaction\"), typeof reaction === \"string\" ? [\n {\n type: \"emoji\",\n emoji: reaction\n }\n ] : (Array.isArray(reaction) ? reaction : [\n reaction\n ]).map((emoji)=>typeof emoji === \"string\" ? {\n type: \"emoji\",\n emoji\n } : emoji), other, signal);\n }\n getUserProfilePhotos(other, signal) {\n return this.api.getUserProfilePhotos(orThrow(this.from, \"getUserProfilePhotos\").id, other, signal);\n }\n getUserProfileAudios(other, signal) {\n return this.api.getUserProfileAudios(orThrow(this.from, \"getUserProfileAudios\").id, other, signal);\n }\n setUserEmojiStatus(other, signal) {\n return this.api.setUserEmojiStatus(orThrow(this.from, \"setUserEmojiStatus\").id, other, signal);\n }\n getUserChatBoosts(chat_id, signal) {\n return this.api.getUserChatBoosts(chat_id ?? orThrow(this.chatId, \"getUserChatBoosts\"), orThrow(this.from, \"getUserChatBoosts\").id, signal);\n }\n getUserGifts(other, signal) {\n return this.api.getUserGifts(orThrow(this.from, \"getUserGifts\").id, other, signal);\n }\n getChatGifts(other, signal) {\n return this.api.getChatGifts(orThrow(this.chatId, \"getChatGifts\"), other, signal);\n }\n getBusinessConnection(signal) {\n return this.api.getBusinessConnection(orThrow(this.businessConnectionId, \"getBusinessConnection\"), signal);\n }\n getFile(signal) {\n const m = orThrow(this.msg, \"getFile\");\n const file = m.photo !== undefined ? m.photo[m.photo.length - 1] : m.animation ?? m.audio ?? m.document ?? m.video ?? m.video_note ?? m.voice ?? m.sticker;\n return this.api.getFile(orThrow(file, \"getFile\").file_id, signal);\n }\n kickAuthor(...args) {\n return this.banAuthor(...args);\n }\n banAuthor(other, signal) {\n return this.api.banChatMember(orThrow(this.chatId, \"banAuthor\"), orThrow(this.from, \"banAuthor\").id, other, signal);\n }\n kickChatMember(...args) {\n return this.banChatMember(...args);\n }\n banChatMember(user_id, other, signal) {\n return this.api.banChatMember(orThrow(this.chatId, \"banChatMember\"), user_id, other, signal);\n }\n unbanChatMember(user_id, other, signal) {\n return this.api.unbanChatMember(orThrow(this.chatId, \"unbanChatMember\"), user_id, other, signal);\n }\n restrictAuthor(permissions, other, signal) {\n return this.api.restrictChatMember(orThrow(this.chatId, \"restrictAuthor\"), orThrow(this.from, \"restrictAuthor\").id, permissions, other, signal);\n }\n restrictChatMember(user_id, permissions, other, signal) {\n return this.api.restrictChatMember(orThrow(this.chatId, \"restrictChatMember\"), user_id, permissions, other, signal);\n }\n promoteAuthor(other, signal) {\n return this.api.promoteChatMember(orThrow(this.chatId, \"promoteAuthor\"), orThrow(this.from, \"promoteAuthor\").id, other, signal);\n }\n promoteChatMember(user_id, other, signal) {\n return this.api.promoteChatMember(orThrow(this.chatId, \"promoteChatMember\"), user_id, other, signal);\n }\n setChatAdministratorAuthorCustomTitle(custom_title, signal) {\n return this.api.setChatAdministratorCustomTitle(orThrow(this.chatId, \"setChatAdministratorAuthorCustomTitle\"), orThrow(this.from, \"setChatAdministratorAuthorCustomTitle\").id, custom_title, signal);\n }\n setChatAdministratorCustomTitle(user_id, custom_title, signal) {\n return this.api.setChatAdministratorCustomTitle(orThrow(this.chatId, \"setChatAdministratorCustomTitle\"), user_id, custom_title, signal);\n }\n setAuthorTag(tag, signal) {\n return this.api.setChatMemberTag(orThrow(this.chatId, \"setChatMemberTag\"), orThrow(this.from, \"setChatMemberTag\").id, tag, signal);\n }\n setChatMemberTag(user_id, tag, signal) {\n return this.api.setChatMemberTag(orThrow(this.chatId, \"setChatMemberTag\"), user_id, tag, signal);\n }\n banChatSenderChat(sender_chat_id, signal) {\n return this.api.banChatSenderChat(orThrow(this.chatId, \"banChatSenderChat\"), sender_chat_id, signal);\n }\n unbanChatSenderChat(sender_chat_id, signal) {\n return this.api.unbanChatSenderChat(orThrow(this.chatId, \"unbanChatSenderChat\"), sender_chat_id, signal);\n }\n setChatPermissions(permissions, other, signal) {\n return this.api.setChatPermissions(orThrow(this.chatId, \"setChatPermissions\"), permissions, other, signal);\n }\n exportChatInviteLink(signal) {\n return this.api.exportChatInviteLink(orThrow(this.chatId, \"exportChatInviteLink\"), signal);\n }\n createChatInviteLink(other, signal) {\n return this.api.createChatInviteLink(orThrow(this.chatId, \"createChatInviteLink\"), other, signal);\n }\n editChatInviteLink(invite_link, other, signal) {\n return this.api.editChatInviteLink(orThrow(this.chatId, \"editChatInviteLink\"), invite_link, other, signal);\n }\n createChatSubscriptionInviteLink(subscription_period, subscription_price, other, signal) {\n return this.api.createChatSubscriptionInviteLink(orThrow(this.chatId, \"createChatSubscriptionInviteLink\"), subscription_period, subscription_price, other, signal);\n }\n editChatSubscriptionInviteLink(invite_link, other, signal) {\n return this.api.editChatSubscriptionInviteLink(orThrow(this.chatId, \"editChatSubscriptionInviteLink\"), invite_link, other, signal);\n }\n revokeChatInviteLink(invite_link, signal) {\n return this.api.revokeChatInviteLink(orThrow(this.chatId, \"editChatInviteLink\"), invite_link, signal);\n }\n approveChatJoinRequest(user_id, signal) {\n return this.api.approveChatJoinRequest(orThrow(this.chatId, \"approveChatJoinRequest\"), user_id, signal);\n }\n declineChatJoinRequest(user_id, signal) {\n return this.api.declineChatJoinRequest(orThrow(this.chatId, \"declineChatJoinRequest\"), user_id, signal);\n }\n approveSuggestedPost(other, signal) {\n return this.api.approveSuggestedPost(orThrow(this.chatId, \"approveSuggestedPost\"), orThrow(this.msgId, \"approveSuggestedPost\"), other, signal);\n }\n declineSuggestedPost(other, signal) {\n return this.api.declineSuggestedPost(orThrow(this.chatId, \"declineSuggestedPost\"), orThrow(this.msgId, \"declineSuggestedPost\"), other, signal);\n }\n setChatPhoto(photo, signal) {\n return this.api.setChatPhoto(orThrow(this.chatId, \"setChatPhoto\"), photo, signal);\n }\n deleteChatPhoto(signal) {\n return this.api.deleteChatPhoto(orThrow(this.chatId, \"deleteChatPhoto\"), signal);\n }\n setChatTitle(title, signal) {\n return this.api.setChatTitle(orThrow(this.chatId, \"setChatTitle\"), title, signal);\n }\n setChatDescription(description, signal) {\n return this.api.setChatDescription(orThrow(this.chatId, \"setChatDescription\"), description, signal);\n }\n pinChatMessage(message_id, other, signal) {\n return this.api.pinChatMessage(orThrow(this.chatId, \"pinChatMessage\"), message_id, {\n business_connection_id: this.businessConnectionId,\n ...other\n }, signal);\n }\n unpinChatMessage(message_id, other, signal) {\n return this.api.unpinChatMessage(orThrow(this.chatId, \"unpinChatMessage\"), message_id, {\n business_connection_id: this.businessConnectionId,\n ...other\n }, signal);\n }\n unpinAllChatMessages(signal) {\n return this.api.unpinAllChatMessages(orThrow(this.chatId, \"unpinAllChatMessages\"), signal);\n }\n leaveChat(signal) {\n return this.api.leaveChat(orThrow(this.chatId, \"leaveChat\"), signal);\n }\n getChat(signal) {\n return this.api.getChat(orThrow(this.chatId, \"getChat\"), signal);\n }\n getChatAdministrators(signal) {\n return this.api.getChatAdministrators(orThrow(this.chatId, \"getChatAdministrators\"), signal);\n }\n getChatMembersCount(...args) {\n return this.getChatMemberCount(...args);\n }\n getChatMemberCount(signal) {\n return this.api.getChatMemberCount(orThrow(this.chatId, \"getChatMemberCount\"), signal);\n }\n getAuthor(signal) {\n return this.api.getChatMember(orThrow(this.chatId, \"getAuthor\"), orThrow(this.from, \"getAuthor\").id, signal);\n }\n getChatMember(user_id, signal) {\n return this.api.getChatMember(orThrow(this.chatId, \"getChatMember\"), user_id, signal);\n }\n setChatStickerSet(sticker_set_name, signal) {\n return this.api.setChatStickerSet(orThrow(this.chatId, \"setChatStickerSet\"), sticker_set_name, signal);\n }\n deleteChatStickerSet(signal) {\n return this.api.deleteChatStickerSet(orThrow(this.chatId, \"deleteChatStickerSet\"), signal);\n }\n createForumTopic(name, other, signal) {\n return this.api.createForumTopic(orThrow(this.chatId, \"createForumTopic\"), name, other, signal);\n }\n editForumTopic(other, signal) {\n const message = orThrow(this.msg, \"editForumTopic\");\n const thread = orThrow(message.message_thread_id, \"editForumTopic\");\n return this.api.editForumTopic(message.chat.id, thread, other, signal);\n }\n closeForumTopic(signal) {\n const message = orThrow(this.msg, \"closeForumTopic\");\n const thread = orThrow(message.message_thread_id, \"closeForumTopic\");\n return this.api.closeForumTopic(message.chat.id, thread, signal);\n }\n reopenForumTopic(signal) {\n const message = orThrow(this.msg, \"reopenForumTopic\");\n const thread = orThrow(message.message_thread_id, \"reopenForumTopic\");\n return this.api.reopenForumTopic(message.chat.id, thread, signal);\n }\n deleteForumTopic(signal) {\n const message = orThrow(this.msg, \"deleteForumTopic\");\n const thread = orThrow(message.message_thread_id, \"deleteForumTopic\");\n return this.api.deleteForumTopic(message.chat.id, thread, signal);\n }\n unpinAllForumTopicMessages(signal) {\n const message = orThrow(this.msg, \"unpinAllForumTopicMessages\");\n const thread = orThrow(message.message_thread_id, \"unpinAllForumTopicMessages\");\n return this.api.unpinAllForumTopicMessages(message.chat.id, thread, signal);\n }\n editGeneralForumTopic(name, signal) {\n return this.api.editGeneralForumTopic(orThrow(this.chatId, \"editGeneralForumTopic\"), name, signal);\n }\n closeGeneralForumTopic(signal) {\n return this.api.closeGeneralForumTopic(orThrow(this.chatId, \"closeGeneralForumTopic\"), signal);\n }\n reopenGeneralForumTopic(signal) {\n return this.api.reopenGeneralForumTopic(orThrow(this.chatId, \"reopenGeneralForumTopic\"), signal);\n }\n hideGeneralForumTopic(signal) {\n return this.api.hideGeneralForumTopic(orThrow(this.chatId, \"hideGeneralForumTopic\"), signal);\n }\n unhideGeneralForumTopic(signal) {\n return this.api.unhideGeneralForumTopic(orThrow(this.chatId, \"unhideGeneralForumTopic\"), signal);\n }\n unpinAllGeneralForumTopicMessages(signal) {\n return this.api.unpinAllGeneralForumTopicMessages(orThrow(this.chatId, \"unpinAllGeneralForumTopicMessages\"), signal);\n }\n answerCallbackQuery(other, signal) {\n return this.api.answerCallbackQuery(orThrow(this.callbackQuery, \"answerCallbackQuery\").id, typeof other === \"string\" ? {\n text: other\n } : other, signal);\n }\n setChatMenuButton(other, signal) {\n return this.api.setChatMenuButton(other, signal);\n }\n getChatMenuButton(other, signal) {\n return this.api.getChatMenuButton(other, signal);\n }\n setMyDefaultAdministratorRights(other, signal) {\n return this.api.setMyDefaultAdministratorRights(other, signal);\n }\n getMyDefaultAdministratorRights(other, signal) {\n return this.api.getMyDefaultAdministratorRights(other, signal);\n }\n editMessageText(text, other, signal) {\n const inlineId = this.inlineMessageId;\n return inlineId !== undefined ? this.api.editMessageTextInline(inlineId, text, {\n business_connection_id: this.businessConnectionId,\n ...other\n }, signal) : this.api.editMessageText(orThrow(this.chatId, \"editMessageText\"), orThrow(this.msg?.message_id ?? this.messageReaction?.message_id ?? this.messageReactionCount?.message_id, \"editMessageText\"), text, {\n business_connection_id: this.businessConnectionId,\n ...other\n }, signal);\n }\n editMessageCaption(other, signal) {\n const inlineId = this.inlineMessageId;\n return inlineId !== undefined ? this.api.editMessageCaptionInline(inlineId, {\n business_connection_id: this.businessConnectionId,\n ...other\n }, signal) : this.api.editMessageCaption(orThrow(this.chatId, \"editMessageCaption\"), orThrow(this.msg?.message_id ?? this.messageReaction?.message_id ?? this.messageReactionCount?.message_id, \"editMessageCaption\"), {\n business_connection_id: this.businessConnectionId,\n ...other\n }, signal);\n }\n editMessageMedia(media, other, signal) {\n const inlineId = this.inlineMessageId;\n return inlineId !== undefined ? this.api.editMessageMediaInline(inlineId, media, {\n business_connection_id: this.businessConnectionId,\n ...other\n }, signal) : this.api.editMessageMedia(orThrow(this.chatId, \"editMessageMedia\"), orThrow(this.msg?.message_id ?? this.messageReaction?.message_id ?? this.messageReactionCount?.message_id, \"editMessageMedia\"), media, {\n business_connection_id: this.businessConnectionId,\n ...other\n }, signal);\n }\n editMessageReplyMarkup(other, signal) {\n const inlineId = this.inlineMessageId;\n return inlineId !== undefined ? this.api.editMessageReplyMarkupInline(inlineId, {\n business_connection_id: this.businessConnectionId,\n ...other\n }, signal) : this.api.editMessageReplyMarkup(orThrow(this.chatId, \"editMessageReplyMarkup\"), orThrow(this.msg?.message_id ?? this.messageReaction?.message_id ?? this.messageReactionCount?.message_id, \"editMessageReplyMarkup\"), {\n business_connection_id: this.businessConnectionId,\n ...other\n }, signal);\n }\n stopPoll(other, signal) {\n return this.api.stopPoll(orThrow(this.chatId, \"stopPoll\"), orThrow(this.msg?.message_id ?? this.messageReaction?.message_id ?? this.messageReactionCount?.message_id, \"stopPoll\"), {\n business_connection_id: this.businessConnectionId,\n ...other\n }, signal);\n }\n deleteMessage(signal) {\n return this.api.deleteMessage(orThrow(this.chatId, \"deleteMessage\"), orThrow(this.msg?.message_id ?? this.messageReaction?.message_id ?? this.messageReactionCount?.message_id, \"deleteMessage\"), signal);\n }\n deleteMessages(message_ids, signal) {\n return this.api.deleteMessages(orThrow(this.chatId, \"deleteMessages\"), message_ids, signal);\n }\n deleteBusinessMessages(message_ids, signal) {\n return this.api.deleteBusinessMessages(orThrow(this.businessConnectionId, \"deleteBusinessMessages\"), message_ids, signal);\n }\n setBusinessAccountName(first_name, other, signal) {\n return this.api.setBusinessAccountName(orThrow(this.businessConnectionId, \"setBusinessAccountName\"), first_name, other, signal);\n }\n setBusinessAccountUsername(username, signal) {\n return this.api.setBusinessAccountUsername(orThrow(this.businessConnectionId, \"setBusinessAccountUsername\"), username, signal);\n }\n setBusinessAccountBio(bio, signal) {\n return this.api.setBusinessAccountBio(orThrow(this.businessConnectionId, \"setBusinessAccountBio\"), bio, signal);\n }\n setBusinessAccountProfilePhoto(photo, other, signal) {\n return this.api.setBusinessAccountProfilePhoto(orThrow(this.businessConnectionId, \"setBusinessAccountProfilePhoto\"), photo, other, signal);\n }\n removeBusinessAccountProfilePhoto(other, signal) {\n return this.api.removeBusinessAccountProfilePhoto(orThrow(this.businessConnectionId, \"removeBusinessAccountProfilePhoto\"), other, signal);\n }\n setBusinessAccountGiftSettings(show_gift_button, accepted_gift_types, signal) {\n return this.api.setBusinessAccountGiftSettings(orThrow(this.businessConnectionId, \"setBusinessAccountGiftSettings\"), show_gift_button, accepted_gift_types, signal);\n }\n getBusinessAccountStarBalance(signal) {\n return this.api.getBusinessAccountStarBalance(orThrow(this.businessConnectionId, \"getBusinessAccountStarBalance\"), signal);\n }\n transferBusinessAccountStars(star_count, signal) {\n return this.api.transferBusinessAccountStars(orThrow(this.businessConnectionId, \"transferBusinessAccountStars\"), star_count, signal);\n }\n getBusinessAccountGifts(other, signal) {\n return this.api.getBusinessAccountGifts(orThrow(this.businessConnectionId, \"getBusinessAccountGifts\"), other, signal);\n }\n convertGiftToStars(owned_gift_id, signal) {\n return this.api.convertGiftToStars(orThrow(this.businessConnectionId, \"convertGiftToStars\"), owned_gift_id, signal);\n }\n upgradeGift(owned_gift_id, other, signal) {\n return this.api.upgradeGift(orThrow(this.businessConnectionId, \"upgradeGift\"), owned_gift_id, other, signal);\n }\n transferGift(owned_gift_id, new_owner_chat_id, star_count, signal) {\n return this.api.transferGift(orThrow(this.businessConnectionId, \"transferGift\"), owned_gift_id, new_owner_chat_id, star_count, signal);\n }\n postStory(content, active_period, other, signal) {\n return this.api.postStory(orThrow(this.businessConnectionId, \"postStory\"), content, active_period, other, signal);\n }\n repostStory(active_period, other, signal) {\n const story = orThrow(this.msg?.story, \"repostStory\");\n return this.api.repostStory(orThrow(this.businessConnectionId, \"repostStory\"), story.chat.id, story.id, active_period, other, signal);\n }\n editStory(story_id, content, other, signal) {\n return this.api.editStory(orThrow(this.businessConnectionId, \"editStory\"), story_id, content, other, signal);\n }\n deleteStory(story_id, signal) {\n return this.api.deleteStory(orThrow(this.businessConnectionId, \"deleteStory\"), story_id, signal);\n }\n replyWithSticker(sticker, other, signal) {\n const msg = this.msg;\n return this.api.sendSticker(orThrow(this.chatId, \"sendSticker\"), sticker, {\n business_connection_id: this.businessConnectionId,\n ...msg?.is_topic_message ? {\n message_thread_id: msg.message_thread_id\n } : {},\n direct_messages_topic_id: msg?.direct_messages_topic?.topic_id,\n ...other\n }, signal);\n }\n getCustomEmojiStickers(signal) {\n return this.api.getCustomEmojiStickers((this.msg?.entities ?? []).filter((e)=>e.type === \"custom_emoji\").map((e)=>e.custom_emoji_id), signal);\n }\n replyWithGift(gift_id, other, signal) {\n return this.api.sendGift(orThrow(this.from, \"sendGift\").id, gift_id, other, signal);\n }\n giftPremiumSubscription(month_count, star_count, other, signal) {\n return this.api.giftPremiumSubscription(orThrow(this.from, \"giftPremiumSubscription\").id, month_count, star_count, other, signal);\n }\n replyWithGiftToChannel(gift_id, other, signal) {\n return this.api.sendGiftToChannel(orThrow(this.chat, \"sendGift\").id, gift_id, other, signal);\n }\n answerInlineQuery(results, other, signal) {\n return this.api.answerInlineQuery(orThrow(this.inlineQuery, \"answerInlineQuery\").id, results, other, signal);\n }\n savePreparedInlineMessage(result, other, signal) {\n return this.api.savePreparedInlineMessage(orThrow(this.from, \"savePreparedInlineMessage\").id, result, other, signal);\n }\n replyWithInvoice(title, description, payload, currency, prices, other, signal) {\n const msg = this.msg;\n return this.api.sendInvoice(orThrow(this.chatId, \"sendInvoice\"), title, description, payload, currency, prices, {\n ...msg?.is_topic_message ? {\n message_thread_id: msg.message_thread_id\n } : {},\n direct_messages_topic_id: msg?.direct_messages_topic?.topic_id,\n ...other\n }, signal);\n }\n answerShippingQuery(ok, other, signal) {\n return this.api.answerShippingQuery(orThrow(this.shippingQuery, \"answerShippingQuery\").id, ok, other, signal);\n }\n answerPreCheckoutQuery(ok, other, signal) {\n return this.api.answerPreCheckoutQuery(orThrow(this.preCheckoutQuery, \"answerPreCheckoutQuery\").id, ok, typeof other === \"string\" ? {\n error_message: other\n } : other, signal);\n }\n refundStarPayment(signal) {\n return this.api.refundStarPayment(orThrow(this.from, \"refundStarPayment\").id, orThrow(this.msg?.successful_payment, \"refundStarPayment\").telegram_payment_charge_id, signal);\n }\n editUserStarSubscription(telegram_payment_charge_id, is_canceled, signal) {\n return this.api.editUserStarSubscription(orThrow(this.from, \"editUserStarSubscription\").id, telegram_payment_charge_id, is_canceled, signal);\n }\n verifyUser(other, signal) {\n return this.api.verifyUser(orThrow(this.from, \"verifyUser\").id, other, signal);\n }\n verifyChat(other, signal) {\n return this.api.verifyChat(orThrow(this.chatId, \"verifyChat\"), other, signal);\n }\n removeUserVerification(signal) {\n return this.api.removeUserVerification(orThrow(this.from, \"removeUserVerification\").id, signal);\n }\n removeChatVerification(signal) {\n return this.api.removeChatVerification(orThrow(this.chatId, \"removeChatVerification\"), signal);\n }\n readBusinessMessage(signal) {\n return this.api.readBusinessMessage(orThrow(this.businessConnectionId, \"readBusinessMessage\"), orThrow(this.chatId, \"readBusinessMessage\"), orThrow(this.msgId, \"readBusinessMessage\"), signal);\n }\n setPassportDataErrors(errors, signal) {\n return this.api.setPassportDataErrors(orThrow(this.from, \"setPassportDataErrors\").id, errors, signal);\n }\n replyWithGame(game_short_name, other, signal) {\n const msg = this.msg;\n return this.api.sendGame(orThrow(this.chatId, \"sendGame\"), game_short_name, {\n business_connection_id: this.businessConnectionId,\n ...msg?.is_topic_message ? {\n message_thread_id: msg.message_thread_id\n } : {},\n ...other\n }, signal);\n }\n}\nfunction orThrow(value, method) {\n if (value === undefined) {\n throw new Error(`Missing information for API call to ${method}`);\n }\n return value;\n}\nfunction triggerFn(trigger) {\n return toArray(trigger).map((t)=>typeof t === \"string\" ? (txt)=>txt === t ? t : null : (txt)=>txt.match(t));\n}\nfunction match(ctx, content, triggers) {\n for (const t of triggers){\n const res = t(content);\n if (res) {\n ctx.match = res;\n return true;\n }\n }\n return false;\n}\nfunction toArray(e) {\n return Array.isArray(e) ? e : [\n e\n ];\n}\nclass BotError extends Error {\n error;\n ctx;\n constructor(error, ctx){\n super(generateBotErrorMessage(error));\n this.error = error;\n this.ctx = ctx;\n this.name = \"BotError\";\n if (error instanceof Error) this.stack = error.stack;\n }\n}\nfunction generateBotErrorMessage(error) {\n let msg;\n if (error instanceof Error) {\n msg = `${error.name} in middleware: ${error.message}`;\n } else {\n const type = typeof error;\n msg = `Non-error value of type ${type} thrown in middleware`;\n switch(type){\n case \"bigint\":\n case \"boolean\":\n case \"number\":\n case \"symbol\":\n msg += `: ${error}`;\n break;\n case \"string\":\n msg += `: ${String(error).substring(0, 50)}`;\n break;\n default:\n msg += \"!\";\n break;\n }\n }\n return msg;\n}\nfunction flatten(mw) {\n return typeof mw === \"function\" ? mw : (ctx, next)=>mw.middleware()(ctx, next);\n}\nfunction concat1(first, andThen) {\n return async (ctx, next)=>{\n let nextCalled = false;\n await first(ctx, async ()=>{\n if (nextCalled) throw new Error(\"`next` already called before!\");\n else nextCalled = true;\n await andThen(ctx, next);\n });\n };\n}\nfunction pass(_ctx, next) {\n return next();\n}\nconst leaf1 = ()=>Promise.resolve();\nasync function run(middleware, ctx) {\n await middleware(ctx, leaf1);\n}\nclass Composer {\n handler;\n constructor(...middleware){\n this.handler = middleware.length === 0 ? pass : middleware.map(flatten).reduce(concat1);\n }\n middleware() {\n return this.handler;\n }\n use(...middleware) {\n const composer = new Composer(...middleware);\n this.handler = concat1(this.handler, flatten(composer));\n return composer;\n }\n on(filter, ...middleware) {\n return this.filter(Context.has.filterQuery(filter), ...middleware);\n }\n hears(trigger, ...middleware) {\n return this.filter(Context.has.text(trigger), ...middleware);\n }\n command(command, ...middleware) {\n return this.filter(Context.has.command(command), ...middleware);\n }\n reaction(reaction, ...middleware) {\n return this.filter(Context.has.reaction(reaction), ...middleware);\n }\n chatType(chatType, ...middleware) {\n return this.filter(Context.has.chatType(chatType), ...middleware);\n }\n callbackQuery(trigger, ...middleware) {\n return this.filter(Context.has.callbackQuery(trigger), ...middleware);\n }\n gameQuery(trigger, ...middleware) {\n return this.filter(Context.has.gameQuery(trigger), ...middleware);\n }\n inlineQuery(trigger, ...middleware) {\n return this.filter(Context.has.inlineQuery(trigger), ...middleware);\n }\n chosenInlineResult(resultId, ...middleware) {\n return this.filter(Context.has.chosenInlineResult(resultId), ...middleware);\n }\n preCheckoutQuery(trigger, ...middleware) {\n return this.filter(Context.has.preCheckoutQuery(trigger), ...middleware);\n }\n shippingQuery(trigger, ...middleware) {\n return this.filter(Context.has.shippingQuery(trigger), ...middleware);\n }\n filter(predicate, ...middleware) {\n const composer = new Composer(...middleware);\n this.branch(predicate, composer, pass);\n return composer;\n }\n drop(predicate, ...middleware) {\n return this.filter(async (ctx)=>!await predicate(ctx), ...middleware);\n }\n fork(...middleware) {\n const composer = new Composer(...middleware);\n const fork = flatten(composer);\n this.use((ctx, next)=>Promise.all([\n next(),\n run(fork, ctx)\n ]));\n return composer;\n }\n lazy(middlewareFactory) {\n return this.use(async (ctx, next)=>{\n const middleware = await middlewareFactory(ctx);\n const arr = Array.isArray(middleware) ? middleware : [\n middleware\n ];\n await flatten(new Composer(...arr))(ctx, next);\n });\n }\n route(router, routeHandlers, fallback = pass) {\n return this.lazy(async (ctx)=>{\n const route = await router(ctx);\n return (route === undefined || !routeHandlers[route] ? fallback : routeHandlers[route]) ?? [];\n });\n }\n branch(predicate, trueMiddleware, falseMiddleware) {\n return this.lazy(async (ctx)=>await predicate(ctx) ? trueMiddleware : falseMiddleware);\n }\n errorBoundary(errorHandler, ...middleware) {\n const composer = new Composer(...middleware);\n const bound = flatten(composer);\n this.use(async (ctx, next)=>{\n let nextCalled = false;\n const cont = ()=>(nextCalled = true, Promise.resolve());\n try {\n await bound(ctx, cont);\n } catch (err) {\n nextCalled = false;\n await errorHandler(new BotError(err, ctx), cont);\n }\n if (nextCalled) await next();\n });\n return composer;\n }\n}\nvar s = 1e3;\nvar m = s * 60;\nvar h = m * 60;\nvar d = h * 24;\nvar w = d * 7;\nvar y = d * 365.25;\nvar ms = function(val, options) {\n options = options || {};\n var type = typeof val;\n if (type === \"string\" && val.length > 0) {\n return parse1(val);\n } else if (type === \"number\" && isFinite(val)) {\n return options.long ? fmtLong(val) : fmtShort(val);\n }\n throw new Error(\"val is not a non-empty string or a valid number. val=\" + JSON.stringify(val));\n};\nfunction parse1(str) {\n str = String(str);\n if (str.length > 100) {\n return;\n }\n var match = /^(-?(?:\\d+)?\\.?\\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(str);\n if (!match) {\n return;\n }\n var n = parseFloat(match[1]);\n var type = (match[2] || \"ms\").toLowerCase();\n switch(type){\n case \"years\":\n case \"year\":\n case \"yrs\":\n case \"yr\":\n case \"y\":\n return n * y;\n case \"weeks\":\n case \"week\":\n case \"w\":\n return n * w;\n case \"days\":\n case \"day\":\n case \"d\":\n return n * d;\n case \"hours\":\n case \"hour\":\n case \"hrs\":\n case \"hr\":\n case \"h\":\n return n * h;\n case \"minutes\":\n case \"minute\":\n case \"mins\":\n case \"min\":\n case \"m\":\n return n * m;\n case \"seconds\":\n case \"second\":\n case \"secs\":\n case \"sec\":\n case \"s\":\n return n * s;\n case \"milliseconds\":\n case \"millisecond\":\n case \"msecs\":\n case \"msec\":\n case \"ms\":\n return n;\n default:\n return void 0;\n }\n}\nfunction fmtShort(ms2) {\n var msAbs = Math.abs(ms2);\n if (msAbs >= d) {\n return Math.round(ms2 / d) + \"d\";\n }\n if (msAbs >= h) {\n return Math.round(ms2 / h) + \"h\";\n }\n if (msAbs >= m) {\n return Math.round(ms2 / m) + \"m\";\n }\n if (msAbs >= s) {\n return Math.round(ms2 / s) + \"s\";\n }\n return ms2 + \"ms\";\n}\nfunction fmtLong(ms2) {\n var msAbs = Math.abs(ms2);\n if (msAbs >= d) {\n return plural(ms2, msAbs, d, \"day\");\n }\n if (msAbs >= h) {\n return plural(ms2, msAbs, h, \"hour\");\n }\n if (msAbs >= m) {\n return plural(ms2, msAbs, m, \"minute\");\n }\n if (msAbs >= s) {\n return plural(ms2, msAbs, s, \"second\");\n }\n return ms2 + \" ms\";\n}\nfunction plural(ms2, msAbs, n, name) {\n var isPlural = msAbs >= n * 1.5;\n return Math.round(ms2 / n) + \" \" + name + (isPlural ? \"s\" : \"\");\n}\nfunction defaultSetTimout() {\n throw new Error(\"setTimeout has not been defined\");\n}\nfunction defaultClearTimeout() {\n throw new Error(\"clearTimeout has not been defined\");\n}\nvar cachedSetTimeout = defaultSetTimout;\nvar cachedClearTimeout = defaultClearTimeout;\nvar globalContext;\nif (typeof window !== \"undefined\") {\n globalContext = window;\n} else if (typeof self !== \"undefined\") {\n globalContext = self;\n} else {\n globalContext = {};\n}\nif (typeof globalContext.setTimeout === \"function\") {\n cachedSetTimeout = setTimeout;\n}\nif (typeof globalContext.clearTimeout === \"function\") {\n cachedClearTimeout = clearTimeout;\n}\nfunction runTimeout(fun) {\n if (cachedSetTimeout === setTimeout) {\n return setTimeout(fun, 0);\n }\n if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {\n cachedSetTimeout = setTimeout;\n return setTimeout(fun, 0);\n }\n try {\n return cachedSetTimeout(fun, 0);\n } catch (e) {\n try {\n return cachedSetTimeout.call(null, fun, 0);\n } catch (e2) {\n return cachedSetTimeout.call(this, fun, 0);\n }\n }\n}\nfunction runClearTimeout(marker) {\n if (cachedClearTimeout === clearTimeout) {\n return clearTimeout(marker);\n }\n if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {\n cachedClearTimeout = clearTimeout;\n return clearTimeout(marker);\n }\n try {\n return cachedClearTimeout(marker);\n } catch (e) {\n try {\n return cachedClearTimeout.call(null, marker);\n } catch (e2) {\n return cachedClearTimeout.call(this, marker);\n }\n }\n}\nvar queue = [];\nvar draining = false;\nvar currentQueue;\nvar queueIndex = -1;\nfunction cleanUpNextTick() {\n if (!draining || !currentQueue) {\n return;\n }\n draining = false;\n if (currentQueue.length) {\n queue = currentQueue.concat(queue);\n } else {\n queueIndex = -1;\n }\n if (queue.length) {\n drainQueue();\n }\n}\nfunction drainQueue() {\n if (draining) {\n return;\n }\n var timeout = runTimeout(cleanUpNextTick);\n draining = true;\n var len = queue.length;\n while(len){\n currentQueue = queue;\n queue = [];\n while(++queueIndex < len){\n if (currentQueue) {\n currentQueue[queueIndex].run();\n }\n }\n queueIndex = -1;\n len = queue.length;\n }\n currentQueue = null;\n draining = false;\n runClearTimeout(timeout);\n}\nfunction nextTick(fun) {\n var args = new Array(arguments.length - 1);\n if (arguments.length > 1) {\n for(var i = 1; i < arguments.length; i++){\n args[i - 1] = arguments[i];\n }\n }\n queue.push(new Item(fun, args));\n if (queue.length === 1 && !draining) {\n runTimeout(drainQueue);\n }\n}\nfunction Item(fun, array) {\n this.fun = fun;\n this.array = array;\n}\nItem.prototype.run = function() {\n this.fun.apply(null, this.array);\n};\nvar title = \"browser\";\nvar platform = \"browser\";\nvar browser = true;\nvar argv = [];\nvar version = \"\";\nvar versions = {};\nvar release = {};\nvar config = {};\nfunction noop() {}\nvar on = noop;\nvar addListener = noop;\nvar once = noop;\nvar off = noop;\nvar removeListener = noop;\nvar removeAllListeners = noop;\nvar emit = noop;\nfunction binding(name) {\n throw new Error(\"process.binding is not supported\");\n}\nfunction cwd() {\n return \"/\";\n}\nfunction chdir(dir) {\n throw new Error(\"process.chdir is not supported\");\n}\nfunction umask() {\n return 0;\n}\nvar performance = globalContext.performance || {};\nvar performanceNow = performance.now || performance.mozNow || performance.msNow || performance.oNow || performance.webkitNow || function() {\n return new Date().getTime();\n};\nfunction hrtime(previousTimestamp) {\n var clocktime = performanceNow.call(performance) * 1e-3;\n var seconds = Math.floor(clocktime);\n var nanoseconds = Math.floor(clocktime % 1 * 1e9);\n if (previousTimestamp) {\n seconds = seconds - previousTimestamp[0];\n nanoseconds = nanoseconds - previousTimestamp[1];\n if (nanoseconds < 0) {\n seconds--;\n nanoseconds += 1e9;\n }\n }\n return [\n seconds,\n nanoseconds\n ];\n}\nvar startTime = new Date();\nfunction uptime() {\n var currentTime = new Date();\n var dif = currentTime - startTime;\n return dif / 1e3;\n}\nvar process = {\n nextTick,\n title,\n browser,\n env: {\n NODE_ENV: \"production\"\n },\n argv,\n version,\n versions,\n on,\n addListener,\n once,\n off,\n removeListener,\n removeAllListeners,\n emit,\n binding,\n cwd,\n chdir,\n umask,\n hrtime,\n platform,\n release,\n config,\n uptime\n};\nfunction createCommonjsModule(fn, basedir, module) {\n return module = {\n path: basedir,\n exports: {},\n require: function(path, base) {\n return commonjsRequire(path, base === void 0 || base === null ? module.path : base);\n }\n }, fn(module, module.exports), module.exports;\n}\nfunction commonjsRequire() {\n throw new Error(\"Dynamic requires are not currently supported by @rollup/plugin-commonjs\");\n}\nfunction setup(env) {\n createDebug.debug = createDebug;\n createDebug.default = createDebug;\n createDebug.coerce = coerce;\n createDebug.disable = disable;\n createDebug.enable = enable;\n createDebug.enabled = enabled;\n createDebug.humanize = ms;\n createDebug.destroy = destroy2;\n Object.keys(env).forEach((key)=>{\n createDebug[key] = env[key];\n });\n createDebug.names = [];\n createDebug.skips = [];\n createDebug.formatters = {};\n function selectColor(namespace) {\n let hash = 0;\n for(let i = 0; i < namespace.length; i++){\n hash = (hash << 5) - hash + namespace.charCodeAt(i);\n hash |= 0;\n }\n return createDebug.colors[Math.abs(hash) % createDebug.colors.length];\n }\n createDebug.selectColor = selectColor;\n function createDebug(namespace) {\n let prevTime;\n let enableOverride = null;\n let namespacesCache;\n let enabledCache;\n function debug(...args) {\n if (!debug.enabled) {\n return;\n }\n const self2 = debug;\n const curr = Number(new Date());\n const ms2 = curr - (prevTime || curr);\n self2.diff = ms2;\n self2.prev = prevTime;\n self2.curr = curr;\n prevTime = curr;\n args[0] = createDebug.coerce(args[0]);\n if (typeof args[0] !== \"string\") {\n args.unshift(\"%O\");\n }\n let index = 0;\n args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format)=>{\n if (match === \"%%\") {\n return \"%\";\n }\n index++;\n const formatter = createDebug.formatters[format];\n if (typeof formatter === \"function\") {\n const val = args[index];\n match = formatter.call(self2, val);\n args.splice(index, 1);\n index--;\n }\n return match;\n });\n createDebug.formatArgs.call(self2, args);\n const logFn = self2.log || createDebug.log;\n logFn.apply(self2, args);\n }\n debug.namespace = namespace;\n debug.useColors = createDebug.useColors();\n debug.color = createDebug.selectColor(namespace);\n debug.extend = extend;\n debug.destroy = createDebug.destroy;\n Object.defineProperty(debug, \"enabled\", {\n enumerable: true,\n configurable: false,\n get: ()=>{\n if (enableOverride !== null) {\n return enableOverride;\n }\n if (namespacesCache !== createDebug.namespaces) {\n namespacesCache = createDebug.namespaces;\n enabledCache = createDebug.enabled(namespace);\n }\n return enabledCache;\n },\n set: (v)=>{\n enableOverride = v;\n }\n });\n if (typeof createDebug.init === \"function\") {\n createDebug.init(debug);\n }\n return debug;\n }\n function extend(namespace, delimiter) {\n const newDebug = createDebug(this.namespace + (typeof delimiter === \"undefined\" ? \":\" : delimiter) + namespace);\n newDebug.log = this.log;\n return newDebug;\n }\n function enable(namespaces) {\n createDebug.save(namespaces);\n createDebug.namespaces = namespaces;\n createDebug.names = [];\n createDebug.skips = [];\n const split = (typeof namespaces === \"string\" ? namespaces : \"\").trim().replace(/\\s+/g, \",\").split(\",\").filter(Boolean);\n for (const ns of split){\n if (ns[0] === \"-\") {\n createDebug.skips.push(ns.slice(1));\n } else {\n createDebug.names.push(ns);\n }\n }\n }\n function matchesTemplate(search, template) {\n let searchIndex = 0;\n let templateIndex = 0;\n let starIndex = -1;\n let matchIndex = 0;\n while(searchIndex < search.length){\n if (templateIndex < template.length && (template[templateIndex] === search[searchIndex] || template[templateIndex] === \"*\")) {\n if (template[templateIndex] === \"*\") {\n starIndex = templateIndex;\n matchIndex = searchIndex;\n templateIndex++;\n } else {\n searchIndex++;\n templateIndex++;\n }\n } else if (starIndex !== -1) {\n templateIndex = starIndex + 1;\n matchIndex++;\n searchIndex = matchIndex;\n } else {\n return false;\n }\n }\n while(templateIndex < template.length && template[templateIndex] === \"*\"){\n templateIndex++;\n }\n return templateIndex === template.length;\n }\n function disable() {\n const namespaces = [\n ...createDebug.names,\n ...createDebug.skips.map((namespace)=>\"-\" + namespace)\n ].join(\",\");\n createDebug.enable(\"\");\n return namespaces;\n }\n function enabled(name) {\n for (const skip of createDebug.skips){\n if (matchesTemplate(name, skip)) {\n return false;\n }\n }\n for (const ns of createDebug.names){\n if (matchesTemplate(name, ns)) {\n return true;\n }\n }\n return false;\n }\n function coerce(val) {\n if (val instanceof Error) {\n return val.stack || val.message;\n }\n return val;\n }\n function destroy2() {\n console.warn(\"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.\");\n }\n createDebug.enable(createDebug.load());\n return createDebug;\n}\nvar common = setup;\nvar browser$1 = createCommonjsModule(function(module, exports) {\n exports.formatArgs = formatArgs2;\n exports.save = save2;\n exports.load = load2;\n exports.useColors = useColors2;\n exports.storage = localstorage();\n exports.destroy = (()=>{\n let warned = false;\n return ()=>{\n if (!warned) {\n warned = true;\n console.warn(\"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.\");\n }\n };\n })();\n exports.colors = [\n \"#0000CC\",\n \"#0000FF\",\n \"#0033CC\",\n \"#0033FF\",\n \"#0066CC\",\n \"#0066FF\",\n \"#0099CC\",\n \"#0099FF\",\n \"#00CC00\",\n \"#00CC33\",\n \"#00CC66\",\n \"#00CC99\",\n \"#00CCCC\",\n \"#00CCFF\",\n \"#3300CC\",\n \"#3300FF\",\n \"#3333CC\",\n \"#3333FF\",\n \"#3366CC\",\n \"#3366FF\",\n \"#3399CC\",\n \"#3399FF\",\n \"#33CC00\",\n \"#33CC33\",\n \"#33CC66\",\n \"#33CC99\",\n \"#33CCCC\",\n \"#33CCFF\",\n \"#6600CC\",\n \"#6600FF\",\n \"#6633CC\",\n \"#6633FF\",\n \"#66CC00\",\n \"#66CC33\",\n \"#9900CC\",\n \"#9900FF\",\n \"#9933CC\",\n \"#9933FF\",\n \"#99CC00\",\n \"#99CC33\",\n \"#CC0000\",\n \"#CC0033\",\n \"#CC0066\",\n \"#CC0099\",\n \"#CC00CC\",\n \"#CC00FF\",\n \"#CC3300\",\n \"#CC3333\",\n \"#CC3366\",\n \"#CC3399\",\n \"#CC33CC\",\n \"#CC33FF\",\n \"#CC6600\",\n \"#CC6633\",\n \"#CC9900\",\n \"#CC9933\",\n \"#CCCC00\",\n \"#CCCC33\",\n \"#FF0000\",\n \"#FF0033\",\n \"#FF0066\",\n \"#FF0099\",\n \"#FF00CC\",\n \"#FF00FF\",\n \"#FF3300\",\n \"#FF3333\",\n \"#FF3366\",\n \"#FF3399\",\n \"#FF33CC\",\n \"#FF33FF\",\n \"#FF6600\",\n \"#FF6633\",\n \"#FF9900\",\n \"#FF9933\",\n \"#FFCC00\",\n \"#FFCC33\"\n ];\n function useColors2() {\n if (typeof window !== \"undefined\" && window.process && (window.process.type === \"renderer\" || window.process.__nwjs)) {\n return true;\n }\n if (typeof navigator !== \"undefined\" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\\/(\\d+)/)) {\n return false;\n }\n let m;\n return typeof document !== \"undefined\" && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance || typeof window !== \"undefined\" && window.console && (window.console.firebug || window.console.exception && window.console.table) || typeof navigator !== \"undefined\" && navigator.userAgent && (m = navigator.userAgent.toLowerCase().match(/firefox\\/(\\d+)/)) && parseInt(m[1], 10) >= 31 || typeof navigator !== \"undefined\" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\\/(\\d+)/);\n }\n function formatArgs2(args) {\n args[0] = (this.useColors ? \"%c\" : \"\") + this.namespace + (this.useColors ? \" %c\" : \" \") + args[0] + (this.useColors ? \"%c \" : \" \") + \"+\" + module.exports.humanize(this.diff);\n if (!this.useColors) {\n return;\n }\n const c = \"color: \" + this.color;\n args.splice(1, 0, c, \"color: inherit\");\n let index = 0;\n let lastC = 0;\n args[0].replace(/%[a-zA-Z%]/g, (match)=>{\n if (match === \"%%\") {\n return;\n }\n index++;\n if (match === \"%c\") {\n lastC = index;\n }\n });\n args.splice(lastC, 0, c);\n }\n exports.log = console.debug || console.log || (()=>{});\n function save2(namespaces) {\n try {\n if (namespaces) {\n exports.storage.setItem(\"debug\", namespaces);\n } else {\n exports.storage.removeItem(\"debug\");\n }\n } catch (error) {}\n }\n function load2() {\n let r;\n try {\n r = exports.storage.getItem(\"debug\") || exports.storage.getItem(\"DEBUG\");\n } catch (error) {}\n if (!r && typeof process !== \"undefined\" && \"env\" in process) {\n r = process.env.DEBUG;\n }\n return r;\n }\n function localstorage() {\n try {\n return localStorage;\n } catch (error) {}\n }\n module.exports = common(exports);\n const { formatters } = module.exports;\n formatters.j = function(v) {\n try {\n return JSON.stringify(v);\n } catch (error) {\n return \"[UnexpectedJSONParseError]: \" + error.message;\n }\n };\n});\nbrowser$1.colors;\nbrowser$1.destroy;\nbrowser$1.formatArgs;\nbrowser$1.load;\nbrowser$1.log;\nbrowser$1.save;\nbrowser$1.storage;\nbrowser$1.useColors;\nconst itrToStream = (itr)=>{\n const it = itr[Symbol.asyncIterator]();\n return new ReadableStream({\n async pull (controller) {\n const chunk = await it.next();\n if (chunk.done) controller.close();\n else controller.enqueue(chunk.value);\n }\n });\n};\nconst baseFetchConfig = (_apiRoot)=>({});\nconst defaultAdapter = \"cloudflare\";\nconst debug = browser$1(\"grammy:warn\");\nclass GrammyError extends Error {\n method;\n payload;\n ok;\n error_code;\n description;\n parameters;\n constructor(message, err, method, payload){\n super(`${message} (${err.error_code}: ${err.description})`);\n this.method = method;\n this.payload = payload;\n this.ok = false;\n this.name = \"GrammyError\";\n this.error_code = err.error_code;\n this.description = err.description;\n this.parameters = err.parameters ?? {};\n }\n}\nfunction toGrammyError(err, method, payload) {\n switch(err.error_code){\n case 401:\n debug(\"Error 401 means that your bot token is wrong, talk to https://t.me/BotFather to check it.\");\n break;\n case 409:\n debug(\"Error 409 means that you are running your bot several times on long polling. Consider revoking the bot token if you believe that no other instance is running.\");\n break;\n }\n return new GrammyError(`Call to '${method}' failed!`, err, method, payload);\n}\nclass HttpError extends Error {\n error;\n constructor(message, error){\n super(message);\n this.error = error;\n this.name = \"HttpError\";\n }\n}\nfunction isTelegramError(err) {\n return typeof err === \"object\" && err !== null && \"status\" in err && \"statusText\" in err;\n}\nfunction toHttpError(method, sensitiveLogs, err) {\n let msg = `Network request for '${method}' failed!`;\n if (isTelegramError(err)) msg += ` (${err.status}: ${err.statusText})`;\n if (sensitiveLogs && err instanceof Error) msg += ` ${err.message}`;\n return new HttpError(msg, err);\n}\nfunction checkWindows() {\n const global = globalThis;\n const os = global.Deno?.build?.os;\n return typeof os === \"string\" ? os === \"windows\" : global.navigator?.platform?.startsWith(\"Win\") ?? global.process?.platform?.startsWith(\"win\") ?? false;\n}\nconst isWindows = checkWindows();\nfunction assertPath(path) {\n if (typeof path !== \"string\") {\n throw new TypeError(`Path must be a string, received \"${JSON.stringify(path)}\"`);\n }\n}\nfunction stripSuffix(name, suffix) {\n if (suffix.length >= name.length) {\n return name;\n }\n const lenDiff = name.length - suffix.length;\n for(let i = suffix.length - 1; i >= 0; --i){\n if (name.charCodeAt(lenDiff + i) !== suffix.charCodeAt(i)) {\n return name;\n }\n }\n return name.slice(0, -suffix.length);\n}\nfunction lastPathSegment(path, isSep, start = 0) {\n let matchedNonSeparator = false;\n let end = path.length;\n for(let i = path.length - 1; i >= start; --i){\n if (isSep(path.charCodeAt(i))) {\n if (matchedNonSeparator) {\n start = i + 1;\n break;\n }\n } else if (!matchedNonSeparator) {\n matchedNonSeparator = true;\n end = i + 1;\n }\n }\n return path.slice(start, end);\n}\nfunction assertArgs(path, suffix) {\n assertPath(path);\n if (path.length === 0) return path;\n if (typeof suffix !== \"string\") {\n throw new TypeError(`Suffix must be a string, received \"${JSON.stringify(suffix)}\"`);\n }\n}\nfunction assertArg(url) {\n url = url instanceof URL ? url : new URL(url);\n if (url.protocol !== \"file:\") {\n throw new TypeError(`URL must be a file URL: received \"${url.protocol}\"`);\n }\n return url;\n}\nfunction fromFileUrl(url) {\n url = assertArg(url);\n return decodeURIComponent(url.pathname.replace(/%(?![0-9A-Fa-f]{2})/g, \"%25\"));\n}\nfunction stripTrailingSeparators(segment, isSep) {\n if (segment.length <= 1) {\n return segment;\n }\n let end = segment.length;\n for(let i = segment.length - 1; i > 0; i--){\n if (isSep(segment.charCodeAt(i))) {\n end = i;\n } else {\n break;\n }\n }\n return segment.slice(0, end);\n}\nfunction isPosixPathSeparator(code) {\n return code === 47;\n}\nfunction basename(path, suffix = \"\") {\n if (path instanceof URL) {\n path = fromFileUrl(path);\n }\n assertArgs(path, suffix);\n const lastSegment = lastPathSegment(path, isPosixPathSeparator);\n const strippedSegment = stripTrailingSeparators(lastSegment, isPosixPathSeparator);\n return suffix ? stripSuffix(strippedSegment, suffix) : strippedSegment;\n}\nfunction isPathSeparator(code) {\n return code === 47 || code === 92;\n}\nfunction isWindowsDeviceRoot(code) {\n return code >= 97 && code <= 122 || code >= 65 && code <= 90;\n}\nfunction fromFileUrl1(url) {\n url = assertArg(url);\n let path = decodeURIComponent(url.pathname.replace(/\\//g, \"\\\\\").replace(/%(?![0-9A-Fa-f]{2})/g, \"%25\")).replace(/^\\\\*([A-Za-z]:)(\\\\|$)/, \"$1\\\\\");\n if (url.hostname !== \"\") {\n path = `\\\\\\\\${url.hostname}${path}`;\n }\n return path;\n}\nfunction basename1(path, suffix = \"\") {\n if (path instanceof URL) {\n path = fromFileUrl1(path);\n }\n assertArgs(path, suffix);\n let start = 0;\n if (path.length >= 2) {\n const drive = path.charCodeAt(0);\n if (isWindowsDeviceRoot(drive)) {\n if (path.charCodeAt(1) === 58) start = 2;\n }\n }\n const lastSegment = lastPathSegment(path, isPathSeparator, start);\n const strippedSegment = stripTrailingSeparators(lastSegment, isPathSeparator);\n return suffix ? stripSuffix(strippedSegment, suffix) : strippedSegment;\n}\nfunction basename2(path, suffix = \"\") {\n return isWindows ? basename1(path, suffix) : basename(path, suffix);\n}\nclass InputFile {\n consumed = false;\n fileData;\n filename;\n constructor(file, filename){\n this.fileData = file;\n filename ??= this.guessFilename(file);\n this.filename = filename;\n }\n guessFilename(file) {\n if (typeof file === \"string\") return basename2(file);\n if (typeof file !== \"object\") return undefined;\n if (\"url\" in file) return basename2(file.url);\n if (!(file instanceof URL)) return undefined;\n return basename2(file.pathname) || basename2(file.hostname);\n }\n toRaw() {\n if (this.consumed) {\n throw new Error(\"Cannot reuse InputFile data source!\");\n }\n const data = this.fileData;\n if (data instanceof Blob) return data.stream();\n if (data instanceof URL) return fetchFile(data);\n if (\"url\" in data) return fetchFile(data.url);\n if (!(data instanceof Uint8Array)) this.consumed = true;\n return data;\n }\n toJSON() {\n throw new Error(\"InputFile instances must be sent via grammY\");\n }\n}\nasync function* fetchFile(url) {\n const { body } = await fetch(url);\n if (body === null) {\n throw new Error(`Download failed, no response body from '${url}'`);\n }\n yield* body;\n}\nfunction requiresFormDataUpload(payload) {\n return payload instanceof InputFile || typeof payload === \"object\" && payload !== null && Object.values(payload).some((v)=>Array.isArray(v) ? v.some(requiresFormDataUpload) : v instanceof InputFile || requiresFormDataUpload(v));\n}\nfunction str(value) {\n return JSON.stringify(value, (_, v)=>v ?? undefined);\n}\nfunction createJsonPayload(payload) {\n return {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n connection: \"keep-alive\"\n },\n body: str(payload)\n };\n}\nasync function* protectItr(itr, onError) {\n try {\n yield* itr;\n } catch (err) {\n onError(err);\n }\n}\nfunction createFormDataPayload(payload, onError) {\n const boundary = createBoundary();\n const itr = payloadToMultipartItr(payload, boundary);\n const safeItr = protectItr(itr, onError);\n const stream = itrToStream(safeItr);\n return {\n method: \"POST\",\n headers: {\n \"content-type\": `multipart/form-data; boundary=${boundary}`,\n connection: \"keep-alive\"\n },\n body: stream\n };\n}\nfunction createBoundary() {\n return \"----------\" + randomId(32);\n}\nfunction randomId(length = 16) {\n return Array.from(Array(length)).map(()=>Math.random().toString(36)[2] || 0).join(\"\");\n}\nconst enc = new TextEncoder();\nasync function* payloadToMultipartItr(payload, boundary) {\n const files = collectFiles(payload);\n yield enc.encode(`--${boundary}\\r\\n`);\n const separator = enc.encode(`\\r\\n--${boundary}\\r\\n`);\n let first = true;\n for (const [key, value] of Object.entries(payload)){\n if (value == null) continue;\n if (!first) yield separator;\n yield valuePart(key, value instanceof InputFile ? value.toJSON() : typeof value === \"object\" ? str(value) : value);\n first = false;\n }\n for (const { id, origin, file } of files){\n if (!first) yield separator;\n yield* filePart(id, origin, file);\n first = false;\n }\n yield enc.encode(`\\r\\n--${boundary}--\\r\\n`);\n}\nfunction collectFiles(value) {\n if (typeof value !== \"object\" || value === null) return [];\n return Object.entries(value).flatMap(([k, v])=>{\n if (Array.isArray(v)) return v.flatMap((p)=>collectFiles(p));\n else if (v instanceof InputFile) {\n const id = randomId();\n Object.assign(v, {\n toJSON: ()=>`attach://${id}`\n });\n const origin = k === \"media\" && \"type\" in value && typeof value.type === \"string\" ? value.type : k;\n return {\n id,\n origin,\n file: v\n };\n } else return collectFiles(v);\n });\n}\nfunction valuePart(key, value) {\n return enc.encode(`content-disposition:form-data;name=\"${key}\"\\r\\n\\r\\n${value}`);\n}\nasync function* filePart(id, origin, input) {\n const filename = input.filename || `${origin}.${getExt(origin)}`;\n if (filename.includes(\"\\r\") || filename.includes(\"\\n\")) {\n throw new Error(`File paths cannot contain carriage-return (\\\\r) \\\nor newline (\\\\n) characters! Filename for property '${origin}' was:\n\"\"\"\n${filename}\n\"\"\"`);\n }\n yield enc.encode(`content-disposition:form-data;name=\"${id}\";filename=${filename}\\r\\ncontent-type:application/octet-stream\\r\\n\\r\\n`);\n const data = await input.toRaw();\n if (data instanceof Uint8Array) yield data;\n else yield* data;\n}\nfunction getExt(key) {\n switch(key){\n case \"certificate\":\n return \"pem\";\n case \"photo\":\n case \"thumbnail\":\n return \"jpg\";\n case \"voice\":\n return \"ogg\";\n case \"audio\":\n return \"mp3\";\n case \"animation\":\n case \"video\":\n case \"video_note\":\n return \"mp4\";\n case \"sticker\":\n return \"webp\";\n default:\n return \"dat\";\n }\n}\nconst debug1 = browser$1(\"grammy:core\");\nfunction concatTransformer(prev, trans) {\n return (method, payload, signal)=>trans(prev, method, payload, signal);\n}\nclass ApiClient {\n token;\n webhookReplyEnvelope;\n options;\n fetch;\n hasUsedWebhookReply;\n installedTransformers;\n constructor(token, options = {}, webhookReplyEnvelope = {}){\n this.token = token;\n this.webhookReplyEnvelope = webhookReplyEnvelope;\n this.hasUsedWebhookReply = false;\n this.installedTransformers = [];\n this.call = async (method, p, signal)=>{\n const payload = p ?? {};\n debug1(`Calling ${method}`);\n if (signal !== undefined) validateSignal(method, payload, signal);\n const opts = this.options;\n const formDataRequired = requiresFormDataUpload(payload);\n if (this.webhookReplyEnvelope.send !== undefined && !this.hasUsedWebhookReply && !formDataRequired && opts.canUseWebhookReply(method)) {\n this.hasUsedWebhookReply = true;\n const config = createJsonPayload({\n ...payload,\n method\n });\n await this.webhookReplyEnvelope.send(config.body);\n return {\n ok: true,\n result: true\n };\n }\n const controller = createAbortControllerFromSignal(signal);\n const timeout = createTimeout(controller, opts.timeoutSeconds, method);\n const streamErr = createStreamError(controller);\n const url = opts.buildUrl(opts.apiRoot, this.token, method, opts.environment);\n const config = formDataRequired ? createFormDataPayload(payload, (err)=>streamErr.catch(err)) : createJsonPayload(payload);\n const sig = controller.signal;\n const options = {\n ...opts.baseFetchConfig,\n signal: sig,\n ...config\n };\n const successPromise = this.fetch(url, options).then((res)=>res.json());\n const operations = [\n successPromise,\n streamErr.promise,\n timeout.promise\n ];\n try {\n return await Promise.race(operations);\n } catch (error) {\n throw toHttpError(method, opts.sensitiveLogs, error);\n } finally{\n if (timeout.handle !== undefined) clearTimeout(timeout.handle);\n }\n };\n const apiRoot = options.apiRoot ?? \"https://api.telegram.org\";\n const environment = options.environment ?? \"prod\";\n const { fetch: customFetch } = options;\n const fetchFn = customFetch ?? fetch;\n this.options = {\n apiRoot,\n environment,\n buildUrl: options.buildUrl ?? defaultBuildUrl,\n timeoutSeconds: options.timeoutSeconds ?? 500,\n baseFetchConfig: {\n ...baseFetchConfig(apiRoot),\n ...options.baseFetchConfig\n },\n canUseWebhookReply: options.canUseWebhookReply ?? (()=>false),\n sensitiveLogs: options.sensitiveLogs ?? false,\n fetch: (...args)=>fetchFn(...args)\n };\n this.fetch = this.options.fetch;\n if (this.options.apiRoot.endsWith(\"/\")) {\n throw new Error(`Remove the trailing '/' from the 'apiRoot' option (use '${this.options.apiRoot.substring(0, this.options.apiRoot.length - 1)}' instead of '${this.options.apiRoot}')`);\n }\n }\n call;\n use(...transformers) {\n this.call = transformers.reduce(concatTransformer, this.call);\n this.installedTransformers.push(...transformers);\n return this;\n }\n async callApi(method, payload, signal) {\n const data = await this.call(method, payload, signal);\n if (data.ok) return data.result;\n else throw toGrammyError(data, method, payload);\n }\n}\nfunction createRawApi(token, options, webhookReplyEnvelope) {\n const client = new ApiClient(token, options, webhookReplyEnvelope);\n const proxyHandler = {\n get (_, m) {\n return m === \"toJSON\" ? \"__internal\" : m === \"getMe\" || m === \"getWebhookInfo\" || m === \"getForumTopicIconStickers\" || m === \"getAvailableGifts\" || m === \"logOut\" || m === \"close\" || m === \"getMyStarBalance\" || m === \"removeMyProfilePhoto\" ? client.callApi.bind(client, m, {}) : client.callApi.bind(client, m);\n },\n ...proxyMethods\n };\n const raw = new Proxy({}, proxyHandler);\n const installedTransformers = client.installedTransformers;\n const api = {\n raw,\n installedTransformers,\n use: (...t)=>{\n client.use(...t);\n return api;\n }\n };\n return api;\n}\nconst defaultBuildUrl = (root, token, method, env)=>{\n const prefix = env === \"test\" ? \"test/\" : \"\";\n return `${root}/bot${token}/${prefix}${method}`;\n};\nconst proxyMethods = {\n set () {\n return false;\n },\n defineProperty () {\n return false;\n },\n deleteProperty () {\n return false;\n },\n ownKeys () {\n return [];\n }\n};\nfunction createTimeout(controller, seconds, method) {\n let handle = undefined;\n const promise = new Promise((_, reject)=>{\n handle = setTimeout(()=>{\n const msg = `Request to '${method}' timed out after ${seconds} seconds`;\n reject(new Error(msg));\n controller.abort();\n }, 1000 * seconds);\n });\n return {\n promise,\n handle\n };\n}\nfunction createStreamError(abortController) {\n let onError = (err)=>{\n throw err;\n };\n const promise = new Promise((_, reject)=>{\n onError = (err)=>{\n reject(err);\n abortController.abort();\n };\n });\n return {\n promise,\n catch: onError\n };\n}\nfunction createAbortControllerFromSignal(signal) {\n const abortController = new AbortController();\n if (signal === undefined) return abortController;\n const sig = signal;\n function abort() {\n abortController.abort();\n sig.removeEventListener(\"abort\", abort);\n }\n if (sig.aborted) abort();\n else sig.addEventListener(\"abort\", abort);\n return {\n abort,\n signal: abortController.signal\n };\n}\nfunction validateSignal(method, payload, signal) {\n if (typeof signal?.addEventListener === \"function\") {\n return;\n }\n let payload0 = JSON.stringify(payload);\n if (payload0.length > 20) {\n payload0 = payload0.substring(0, 16) + \" ...\";\n }\n let payload1 = JSON.stringify(signal);\n if (payload1.length > 20) {\n payload1 = payload1.substring(0, 16) + \" ...\";\n }\n throw new Error(`Incorrect abort signal instance found! \\\nYou passed two payloads to '${method}' but you should merge \\\nthe second one containing '${payload1}' into the first one \\\ncontaining '${payload0}'! If you are using context shortcuts, \\\nyou may want to use a method on 'ctx.api' instead.\n\nIf you want to prevent such mistakes in the future, \\\nconsider using TypeScript. https://www.typescriptlang.org/`);\n}\nclass Api {\n token;\n options;\n raw;\n config;\n constructor(token, options, webhookReplyEnvelope){\n this.token = token;\n this.options = options;\n const { raw, use, installedTransformers } = createRawApi(token, options, webhookReplyEnvelope);\n this.raw = raw;\n this.config = {\n use,\n installedTransformers: ()=>installedTransformers.slice()\n };\n }\n getUpdates(other, signal) {\n return this.raw.getUpdates({\n ...other\n }, signal);\n }\n setWebhook(url, other, signal) {\n return this.raw.setWebhook({\n url,\n ...other\n }, signal);\n }\n deleteWebhook(other, signal) {\n return this.raw.deleteWebhook({\n ...other\n }, signal);\n }\n getWebhookInfo(signal) {\n return this.raw.getWebhookInfo(signal);\n }\n getMe(signal) {\n return this.raw.getMe(signal);\n }\n logOut(signal) {\n return this.raw.logOut(signal);\n }\n close(signal) {\n return this.raw.close(signal);\n }\n sendMessage(chat_id, text, other, signal) {\n return this.raw.sendMessage({\n chat_id,\n text,\n ...other\n }, signal);\n }\n sendMessageDraft(chat_id, draft_id, text, other, signal) {\n return this.raw.sendMessageDraft({\n chat_id,\n draft_id,\n text,\n ...other\n }, signal);\n }\n forwardMessage(chat_id, from_chat_id, message_id, other, signal) {\n return this.raw.forwardMessage({\n chat_id,\n from_chat_id,\n message_id,\n ...other\n }, signal);\n }\n forwardMessages(chat_id, from_chat_id, message_ids, other, signal) {\n return this.raw.forwardMessages({\n chat_id,\n from_chat_id,\n message_ids,\n ...other\n }, signal);\n }\n copyMessage(chat_id, from_chat_id, message_id, other, signal) {\n return this.raw.copyMessage({\n chat_id,\n from_chat_id,\n message_id,\n ...other\n }, signal);\n }\n copyMessages(chat_id, from_chat_id, message_ids, other, signal) {\n return this.raw.copyMessages({\n chat_id,\n from_chat_id,\n message_ids,\n ...other\n }, signal);\n }\n sendPhoto(chat_id, photo, other, signal) {\n return this.raw.sendPhoto({\n chat_id,\n photo,\n ...other\n }, signal);\n }\n sendAudio(chat_id, audio, other, signal) {\n return this.raw.sendAudio({\n chat_id,\n audio,\n ...other\n }, signal);\n }\n sendDocument(chat_id, document1, other, signal) {\n return this.raw.sendDocument({\n chat_id,\n document: document1,\n ...other\n }, signal);\n }\n sendVideo(chat_id, video, other, signal) {\n return this.raw.sendVideo({\n chat_id,\n video,\n ...other\n }, signal);\n }\n sendAnimation(chat_id, animation, other, signal) {\n return this.raw.sendAnimation({\n chat_id,\n animation,\n ...other\n }, signal);\n }\n sendVoice(chat_id, voice, other, signal) {\n return this.raw.sendVoice({\n chat_id,\n voice,\n ...other\n }, signal);\n }\n sendVideoNote(chat_id, video_note, other, signal) {\n return this.raw.sendVideoNote({\n chat_id,\n video_note,\n ...other\n }, signal);\n }\n sendMediaGroup(chat_id, media, other, signal) {\n return this.raw.sendMediaGroup({\n chat_id,\n media,\n ...other\n }, signal);\n }\n sendLocation(chat_id, latitude, longitude, other, signal) {\n return this.raw.sendLocation({\n chat_id,\n latitude,\n longitude,\n ...other\n }, signal);\n }\n editMessageLiveLocation(chat_id, message_id, latitude, longitude, other, signal) {\n return this.raw.editMessageLiveLocation({\n chat_id,\n message_id,\n latitude,\n longitude,\n ...other\n }, signal);\n }\n editMessageLiveLocationInline(inline_message_id, latitude, longitude, other, signal) {\n return this.raw.editMessageLiveLocation({\n inline_message_id,\n latitude,\n longitude,\n ...other\n }, signal);\n }\n stopMessageLiveLocation(chat_id, message_id, other, signal) {\n return this.raw.stopMessageLiveLocation({\n chat_id,\n message_id,\n ...other\n }, signal);\n }\n stopMessageLiveLocationInline(inline_message_id, other, signal) {\n return this.raw.stopMessageLiveLocation({\n inline_message_id,\n ...other\n }, signal);\n }\n sendPaidMedia(chat_id, star_count, media, other, signal) {\n return this.raw.sendPaidMedia({\n chat_id,\n star_count,\n media,\n ...other\n }, signal);\n }\n sendVenue(chat_id, latitude, longitude, title, address, other, signal) {\n return this.raw.sendVenue({\n chat_id,\n latitude,\n longitude,\n title,\n address,\n ...other\n }, signal);\n }\n sendContact(chat_id, phone_number, first_name, other, signal) {\n return this.raw.sendContact({\n chat_id,\n phone_number,\n first_name,\n ...other\n }, signal);\n }\n sendPoll(chat_id, question, options, other, signal) {\n const opts = options.map((o)=>typeof o === \"string\" ? {\n text: o\n } : o);\n return this.raw.sendPoll({\n chat_id,\n question,\n options: opts,\n ...other\n }, signal);\n }\n sendChecklist(business_connection_id, chat_id, checklist, other, signal) {\n return this.raw.sendChecklist({\n business_connection_id,\n chat_id,\n checklist,\n ...other\n }, signal);\n }\n editMessageChecklist(business_connection_id, chat_id, message_id, checklist, other, signal) {\n return this.raw.editMessageChecklist({\n business_connection_id,\n chat_id,\n message_id,\n checklist,\n ...other\n }, signal);\n }\n sendDice(chat_id, emoji, other, signal) {\n return this.raw.sendDice({\n chat_id,\n emoji,\n ...other\n }, signal);\n }\n setMessageReaction(chat_id, message_id, reaction, other, signal) {\n return this.raw.setMessageReaction({\n chat_id,\n message_id,\n reaction,\n ...other\n }, signal);\n }\n sendChatAction(chat_id, action, other, signal) {\n return this.raw.sendChatAction({\n chat_id,\n action,\n ...other\n }, signal);\n }\n getUserProfilePhotos(user_id, other, signal) {\n return this.raw.getUserProfilePhotos({\n user_id,\n ...other\n }, signal);\n }\n getUserProfileAudios(user_id, other, signal) {\n return this.raw.getUserProfileAudios({\n user_id,\n ...other\n }, signal);\n }\n setUserEmojiStatus(user_id, other, signal) {\n return this.raw.setUserEmojiStatus({\n user_id,\n ...other\n }, signal);\n }\n getUserChatBoosts(chat_id, user_id, signal) {\n return this.raw.getUserChatBoosts({\n chat_id,\n user_id\n }, signal);\n }\n getUserGifts(user_id, other, signal) {\n return this.raw.getUserGifts({\n user_id,\n ...other\n }, signal);\n }\n getChatGifts(chat_id, other, signal) {\n return this.raw.getChatGifts({\n chat_id,\n ...other\n }, signal);\n }\n getBusinessConnection(business_connection_id, signal) {\n return this.raw.getBusinessConnection({\n business_connection_id\n }, signal);\n }\n getFile(file_id, signal) {\n return this.raw.getFile({\n file_id\n }, signal);\n }\n kickChatMember(...args) {\n return this.banChatMember(...args);\n }\n banChatMember(chat_id, user_id, other, signal) {\n return this.raw.banChatMember({\n chat_id,\n user_id,\n ...other\n }, signal);\n }\n unbanChatMember(chat_id, user_id, other, signal) {\n return this.raw.unbanChatMember({\n chat_id,\n user_id,\n ...other\n }, signal);\n }\n restrictChatMember(chat_id, user_id, permissions, other, signal) {\n return this.raw.restrictChatMember({\n chat_id,\n user_id,\n permissions,\n ...other\n }, signal);\n }\n promoteChatMember(chat_id, user_id, other, signal) {\n return this.raw.promoteChatMember({\n chat_id,\n user_id,\n ...other\n }, signal);\n }\n setChatAdministratorCustomTitle(chat_id, user_id, custom_title, signal) {\n return this.raw.setChatAdministratorCustomTitle({\n chat_id,\n user_id,\n custom_title\n }, signal);\n }\n setChatMemberTag(chat_id, user_id, tag, signal) {\n return this.raw.setChatMemberTag({\n chat_id,\n user_id,\n tag\n }, signal);\n }\n banChatSenderChat(chat_id, sender_chat_id, signal) {\n return this.raw.banChatSenderChat({\n chat_id,\n sender_chat_id\n }, signal);\n }\n unbanChatSenderChat(chat_id, sender_chat_id, signal) {\n return this.raw.unbanChatSenderChat({\n chat_id,\n sender_chat_id\n }, signal);\n }\n setChatPermissions(chat_id, permissions, other, signal) {\n return this.raw.setChatPermissions({\n chat_id,\n permissions,\n ...other\n }, signal);\n }\n exportChatInviteLink(chat_id, signal) {\n return this.raw.exportChatInviteLink({\n chat_id\n }, signal);\n }\n createChatInviteLink(chat_id, other, signal) {\n return this.raw.createChatInviteLink({\n chat_id,\n ...other\n }, signal);\n }\n editChatInviteLink(chat_id, invite_link, other, signal) {\n return this.raw.editChatInviteLink({\n chat_id,\n invite_link,\n ...other\n }, signal);\n }\n createChatSubscriptionInviteLink(chat_id, subscription_period, subscription_price, other, signal) {\n return this.raw.createChatSubscriptionInviteLink({\n chat_id,\n subscription_period,\n subscription_price,\n ...other\n }, signal);\n }\n editChatSubscriptionInviteLink(chat_id, invite_link, other, signal) {\n return this.raw.editChatSubscriptionInviteLink({\n chat_id,\n invite_link,\n ...other\n }, signal);\n }\n revokeChatInviteLink(chat_id, invite_link, signal) {\n return this.raw.revokeChatInviteLink({\n chat_id,\n invite_link\n }, signal);\n }\n approveChatJoinRequest(chat_id, user_id, signal) {\n return this.raw.approveChatJoinRequest({\n chat_id,\n user_id\n }, signal);\n }\n declineChatJoinRequest(chat_id, user_id, signal) {\n return this.raw.declineChatJoinRequest({\n chat_id,\n user_id\n }, signal);\n }\n approveSuggestedPost(chat_id, message_id, other, signal) {\n return this.raw.approveSuggestedPost({\n chat_id,\n message_id,\n ...other\n }, signal);\n }\n declineSuggestedPost(chat_id, message_id, other, signal) {\n return this.raw.declineSuggestedPost({\n chat_id,\n message_id,\n ...other\n }, signal);\n }\n setChatPhoto(chat_id, photo, signal) {\n return this.raw.setChatPhoto({\n chat_id,\n photo\n }, signal);\n }\n deleteChatPhoto(chat_id, signal) {\n return this.raw.deleteChatPhoto({\n chat_id\n }, signal);\n }\n setChatTitle(chat_id, title, signal) {\n return this.raw.setChatTitle({\n chat_id,\n title\n }, signal);\n }\n setChatDescription(chat_id, description, signal) {\n return this.raw.setChatDescription({\n chat_id,\n description\n }, signal);\n }\n pinChatMessage(chat_id, message_id, other, signal) {\n return this.raw.pinChatMessage({\n chat_id,\n message_id,\n ...other\n }, signal);\n }\n unpinChatMessage(chat_id, message_id, other, signal) {\n return this.raw.unpinChatMessage({\n chat_id,\n message_id,\n ...other\n }, signal);\n }\n unpinAllChatMessages(chat_id, signal) {\n return this.raw.unpinAllChatMessages({\n chat_id\n }, signal);\n }\n leaveChat(chat_id, signal) {\n return this.raw.leaveChat({\n chat_id\n }, signal);\n }\n getChat(chat_id, signal) {\n return this.raw.getChat({\n chat_id\n }, signal);\n }\n getChatAdministrators(chat_id, signal) {\n return this.raw.getChatAdministrators({\n chat_id\n }, signal);\n }\n getChatMembersCount(...args) {\n return this.getChatMemberCount(...args);\n }\n getChatMemberCount(chat_id, signal) {\n return this.raw.getChatMemberCount({\n chat_id\n }, signal);\n }\n getChatMember(chat_id, user_id, signal) {\n return this.raw.getChatMember({\n chat_id,\n user_id\n }, signal);\n }\n setChatStickerSet(chat_id, sticker_set_name, signal) {\n return this.raw.setChatStickerSet({\n chat_id,\n sticker_set_name\n }, signal);\n }\n deleteChatStickerSet(chat_id, signal) {\n return this.raw.deleteChatStickerSet({\n chat_id\n }, signal);\n }\n getForumTopicIconStickers(signal) {\n return this.raw.getForumTopicIconStickers(signal);\n }\n createForumTopic(chat_id, name, other, signal) {\n return this.raw.createForumTopic({\n chat_id,\n name,\n ...other\n }, signal);\n }\n editForumTopic(chat_id, message_thread_id, other, signal) {\n return this.raw.editForumTopic({\n chat_id,\n message_thread_id,\n ...other\n }, signal);\n }\n closeForumTopic(chat_id, message_thread_id, signal) {\n return this.raw.closeForumTopic({\n chat_id,\n message_thread_id\n }, signal);\n }\n reopenForumTopic(chat_id, message_thread_id, signal) {\n return this.raw.reopenForumTopic({\n chat_id,\n message_thread_id\n }, signal);\n }\n deleteForumTopic(chat_id, message_thread_id, signal) {\n return this.raw.deleteForumTopic({\n chat_id,\n message_thread_id\n }, signal);\n }\n unpinAllForumTopicMessages(chat_id, message_thread_id, signal) {\n return this.raw.unpinAllForumTopicMessages({\n chat_id,\n message_thread_id\n }, signal);\n }\n editGeneralForumTopic(chat_id, name, signal) {\n return this.raw.editGeneralForumTopic({\n chat_id,\n name\n }, signal);\n }\n closeGeneralForumTopic(chat_id, signal) {\n return this.raw.closeGeneralForumTopic({\n chat_id\n }, signal);\n }\n reopenGeneralForumTopic(chat_id, signal) {\n return this.raw.reopenGeneralForumTopic({\n chat_id\n }, signal);\n }\n hideGeneralForumTopic(chat_id, signal) {\n return this.raw.hideGeneralForumTopic({\n chat_id\n }, signal);\n }\n unhideGeneralForumTopic(chat_id, signal) {\n return this.raw.unhideGeneralForumTopic({\n chat_id\n }, signal);\n }\n unpinAllGeneralForumTopicMessages(chat_id, signal) {\n return this.raw.unpinAllGeneralForumTopicMessages({\n chat_id\n }, signal);\n }\n answerCallbackQuery(callback_query_id, other, signal) {\n return this.raw.answerCallbackQuery({\n callback_query_id,\n ...other\n }, signal);\n }\n setMyName(name, other, signal) {\n return this.raw.setMyName({\n name,\n ...other\n }, signal);\n }\n getMyName(other, signal) {\n return this.raw.getMyName(other ?? {}, signal);\n }\n setMyCommands(commands, other, signal) {\n return this.raw.setMyCommands({\n commands,\n ...other\n }, signal);\n }\n deleteMyCommands(other, signal) {\n return this.raw.deleteMyCommands({\n ...other\n }, signal);\n }\n getMyCommands(other, signal) {\n return this.raw.getMyCommands({\n ...other\n }, signal);\n }\n setMyDescription(description, other, signal) {\n return this.raw.setMyDescription({\n description,\n ...other\n }, signal);\n }\n getMyDescription(other, signal) {\n return this.raw.getMyDescription({\n ...other\n }, signal);\n }\n setMyShortDescription(short_description, other, signal) {\n return this.raw.setMyShortDescription({\n short_description,\n ...other\n }, signal);\n }\n getMyShortDescription(other, signal) {\n return this.raw.getMyShortDescription({\n ...other\n }, signal);\n }\n setMyProfilePhoto(photo, signal) {\n return this.raw.setMyProfilePhoto({\n photo\n }, signal);\n }\n removeMyProfilePhoto(signal) {\n return this.raw.removeMyProfilePhoto(signal);\n }\n setChatMenuButton(other, signal) {\n return this.raw.setChatMenuButton({\n ...other\n }, signal);\n }\n getChatMenuButton(other, signal) {\n return this.raw.getChatMenuButton({\n ...other\n }, signal);\n }\n setMyDefaultAdministratorRights(other, signal) {\n return this.raw.setMyDefaultAdministratorRights({\n ...other\n }, signal);\n }\n getMyDefaultAdministratorRights(other, signal) {\n return this.raw.getMyDefaultAdministratorRights({\n ...other\n }, signal);\n }\n getMyStarBalance(signal) {\n return this.raw.getMyStarBalance(signal);\n }\n editMessageText(chat_id, message_id, text, other, signal) {\n return this.raw.editMessageText({\n chat_id,\n message_id,\n text,\n ...other\n }, signal);\n }\n editMessageTextInline(inline_message_id, text, other, signal) {\n return this.raw.editMessageText({\n inline_message_id,\n text,\n ...other\n }, signal);\n }\n editMessageCaption(chat_id, message_id, other, signal) {\n return this.raw.editMessageCaption({\n chat_id,\n message_id,\n ...other\n }, signal);\n }\n editMessageCaptionInline(inline_message_id, other, signal) {\n return this.raw.editMessageCaption({\n inline_message_id,\n ...other\n }, signal);\n }\n editMessageMedia(chat_id, message_id, media, other, signal) {\n return this.raw.editMessageMedia({\n chat_id,\n message_id,\n media,\n ...other\n }, signal);\n }\n editMessageMediaInline(inline_message_id, media, other, signal) {\n return this.raw.editMessageMedia({\n inline_message_id,\n media,\n ...other\n }, signal);\n }\n editMessageReplyMarkup(chat_id, message_id, other, signal) {\n return this.raw.editMessageReplyMarkup({\n chat_id,\n message_id,\n ...other\n }, signal);\n }\n editMessageReplyMarkupInline(inline_message_id, other, signal) {\n return this.raw.editMessageReplyMarkup({\n inline_message_id,\n ...other\n }, signal);\n }\n stopPoll(chat_id, message_id, other, signal) {\n return this.raw.stopPoll({\n chat_id,\n message_id,\n ...other\n }, signal);\n }\n deleteMessage(chat_id, message_id, signal) {\n return this.raw.deleteMessage({\n chat_id,\n message_id\n }, signal);\n }\n deleteMessages(chat_id, message_ids, signal) {\n return this.raw.deleteMessages({\n chat_id,\n message_ids\n }, signal);\n }\n deleteBusinessMessages(business_connection_id, message_ids, signal) {\n return this.raw.deleteBusinessMessages({\n business_connection_id,\n message_ids\n }, signal);\n }\n setBusinessAccountName(business_connection_id, first_name, other, signal) {\n return this.raw.setBusinessAccountName({\n business_connection_id,\n first_name,\n ...other\n }, signal);\n }\n setBusinessAccountUsername(business_connection_id, username, signal) {\n return this.raw.setBusinessAccountUsername({\n business_connection_id,\n username\n }, signal);\n }\n setBusinessAccountBio(business_connection_id, bio, signal) {\n return this.raw.setBusinessAccountBio({\n business_connection_id,\n bio\n }, signal);\n }\n setBusinessAccountProfilePhoto(business_connection_id, photo, other, signal) {\n return this.raw.setBusinessAccountProfilePhoto({\n business_connection_id,\n photo,\n ...other\n }, signal);\n }\n removeBusinessAccountProfilePhoto(business_connection_id, other, signal) {\n return this.raw.removeBusinessAccountProfilePhoto({\n business_connection_id,\n ...other\n }, signal);\n }\n setBusinessAccountGiftSettings(business_connection_id, show_gift_button, accepted_gift_types, signal) {\n return this.raw.setBusinessAccountGiftSettings({\n business_connection_id,\n show_gift_button,\n accepted_gift_types\n }, signal);\n }\n getBusinessAccountStarBalance(business_connection_id, signal) {\n return this.raw.getBusinessAccountStarBalance({\n business_connection_id\n }, signal);\n }\n transferBusinessAccountStars(business_connection_id, star_count, signal) {\n return this.raw.transferBusinessAccountStars({\n business_connection_id,\n star_count\n }, signal);\n }\n getBusinessAccountGifts(business_connection_id, other, signal) {\n return this.raw.getBusinessAccountGifts({\n business_connection_id,\n ...other\n }, signal);\n }\n convertGiftToStars(business_connection_id, owned_gift_id, signal) {\n return this.raw.convertGiftToStars({\n business_connection_id,\n owned_gift_id\n }, signal);\n }\n upgradeGift(business_connection_id, owned_gift_id, other, signal) {\n return this.raw.upgradeGift({\n business_connection_id,\n owned_gift_id,\n ...other\n }, signal);\n }\n transferGift(business_connection_id, owned_gift_id, new_owner_chat_id, star_count, signal) {\n return this.raw.transferGift({\n business_connection_id,\n owned_gift_id,\n new_owner_chat_id,\n star_count\n }, signal);\n }\n postStory(business_connection_id, content, active_period, other, signal) {\n return this.raw.postStory({\n business_connection_id,\n content,\n active_period,\n ...other\n }, signal);\n }\n repostStory(business_connection_id, from_chat_id, from_story_id, active_period, other, signal) {\n return this.raw.repostStory({\n business_connection_id,\n from_chat_id,\n from_story_id,\n active_period,\n ...other\n }, signal);\n }\n editStory(business_connection_id, story_id, content, other, signal) {\n return this.raw.editStory({\n business_connection_id,\n story_id,\n content,\n ...other\n }, signal);\n }\n deleteStory(business_connection_id, story_id, signal) {\n return this.raw.deleteStory({\n business_connection_id,\n story_id\n }, signal);\n }\n sendSticker(chat_id, sticker, other, signal) {\n return this.raw.sendSticker({\n chat_id,\n sticker,\n ...other\n }, signal);\n }\n getStickerSet(name, signal) {\n return this.raw.getStickerSet({\n name\n }, signal);\n }\n getCustomEmojiStickers(custom_emoji_ids, signal) {\n return this.raw.getCustomEmojiStickers({\n custom_emoji_ids\n }, signal);\n }\n uploadStickerFile(user_id, sticker_format, sticker, signal) {\n return this.raw.uploadStickerFile({\n user_id,\n sticker_format,\n sticker\n }, signal);\n }\n createNewStickerSet(user_id, name, title, stickers, other, signal) {\n return this.raw.createNewStickerSet({\n user_id,\n name,\n title,\n stickers,\n ...other\n }, signal);\n }\n addStickerToSet(user_id, name, sticker, signal) {\n return this.raw.addStickerToSet({\n user_id,\n name,\n sticker\n }, signal);\n }\n setStickerPositionInSet(sticker, position, signal) {\n return this.raw.setStickerPositionInSet({\n sticker,\n position\n }, signal);\n }\n deleteStickerFromSet(sticker, signal) {\n return this.raw.deleteStickerFromSet({\n sticker\n }, signal);\n }\n replaceStickerInSet(user_id, name, old_sticker, sticker, signal) {\n return this.raw.replaceStickerInSet({\n user_id,\n name,\n old_sticker,\n sticker\n }, signal);\n }\n setStickerEmojiList(sticker, emoji_list, signal) {\n return this.raw.setStickerEmojiList({\n sticker,\n emoji_list\n }, signal);\n }\n setStickerKeywords(sticker, keywords, signal) {\n return this.raw.setStickerKeywords({\n sticker,\n keywords\n }, signal);\n }\n setStickerMaskPosition(sticker, mask_position, signal) {\n return this.raw.setStickerMaskPosition({\n sticker,\n mask_position\n }, signal);\n }\n setStickerSetTitle(name, title, signal) {\n return this.raw.setStickerSetTitle({\n name,\n title\n }, signal);\n }\n deleteStickerSet(name, signal) {\n return this.raw.deleteStickerSet({\n name\n }, signal);\n }\n setStickerSetThumbnail(name, user_id, thumbnail, format, signal) {\n return this.raw.setStickerSetThumbnail({\n name,\n user_id,\n thumbnail,\n format\n }, signal);\n }\n setCustomEmojiStickerSetThumbnail(name, custom_emoji_id, signal) {\n return this.raw.setCustomEmojiStickerSetThumbnail({\n name,\n custom_emoji_id\n }, signal);\n }\n getAvailableGifts(signal) {\n return this.raw.getAvailableGifts(signal);\n }\n sendGift(user_id, gift_id, other, signal) {\n return this.raw.sendGift({\n user_id,\n gift_id,\n ...other\n }, signal);\n }\n giftPremiumSubscription(user_id, month_count, star_count, other, signal) {\n return this.raw.giftPremiumSubscription({\n user_id,\n month_count,\n star_count,\n ...other\n }, signal);\n }\n sendGiftToChannel(chat_id, gift_id, other, signal) {\n return this.raw.sendGift({\n chat_id,\n gift_id,\n ...other\n }, signal);\n }\n answerInlineQuery(inline_query_id, results, other, signal) {\n return this.raw.answerInlineQuery({\n inline_query_id,\n results,\n ...other\n }, signal);\n }\n answerWebAppQuery(web_app_query_id, result, signal) {\n return this.raw.answerWebAppQuery({\n web_app_query_id,\n result\n }, signal);\n }\n savePreparedInlineMessage(user_id, result, other, signal) {\n return this.raw.savePreparedInlineMessage({\n user_id,\n result,\n ...other\n }, signal);\n }\n sendInvoice(chat_id, title, description, payload, currency, prices, other, signal) {\n return this.raw.sendInvoice({\n chat_id,\n title,\n description,\n payload,\n currency,\n prices,\n ...other\n }, signal);\n }\n createInvoiceLink(title, description, payload, provider_token, currency, prices, other, signal) {\n return this.raw.createInvoiceLink({\n title,\n description,\n payload,\n provider_token,\n currency,\n prices,\n ...other\n }, signal);\n }\n answerShippingQuery(shipping_query_id, ok, other, signal) {\n return this.raw.answerShippingQuery({\n shipping_query_id,\n ok,\n ...other\n }, signal);\n }\n answerPreCheckoutQuery(pre_checkout_query_id, ok, other, signal) {\n return this.raw.answerPreCheckoutQuery({\n pre_checkout_query_id,\n ok,\n ...other\n }, signal);\n }\n getStarTransactions(other, signal) {\n return this.raw.getStarTransactions({\n ...other\n }, signal);\n }\n refundStarPayment(user_id, telegram_payment_charge_id, signal) {\n return this.raw.refundStarPayment({\n user_id,\n telegram_payment_charge_id\n }, signal);\n }\n editUserStarSubscription(user_id, telegram_payment_charge_id, is_canceled, signal) {\n return this.raw.editUserStarSubscription({\n user_id,\n telegram_payment_charge_id,\n is_canceled\n }, signal);\n }\n verifyUser(user_id, other, signal) {\n return this.raw.verifyUser({\n user_id,\n ...other\n }, signal);\n }\n verifyChat(chat_id, other, signal) {\n return this.raw.verifyChat({\n chat_id,\n ...other\n }, signal);\n }\n removeUserVerification(user_id, signal) {\n return this.raw.removeUserVerification({\n user_id\n }, signal);\n }\n removeChatVerification(chat_id, signal) {\n return this.raw.removeChatVerification({\n chat_id\n }, signal);\n }\n readBusinessMessage(business_connection_id, chat_id, message_id, signal) {\n return this.raw.readBusinessMessage({\n business_connection_id,\n chat_id,\n message_id\n }, signal);\n }\n setPassportDataErrors(user_id, errors, signal) {\n return this.raw.setPassportDataErrors({\n user_id,\n errors\n }, signal);\n }\n sendGame(chat_id, game_short_name, other, signal) {\n return this.raw.sendGame({\n chat_id,\n game_short_name,\n ...other\n }, signal);\n }\n setGameScore(chat_id, message_id, user_id, score, other, signal) {\n return this.raw.setGameScore({\n chat_id,\n message_id,\n user_id,\n score,\n ...other\n }, signal);\n }\n setGameScoreInline(inline_message_id, user_id, score, other, signal) {\n return this.raw.setGameScore({\n inline_message_id,\n user_id,\n score,\n ...other\n }, signal);\n }\n getGameHighScores(chat_id, message_id, user_id, signal) {\n return this.raw.getGameHighScores({\n chat_id,\n message_id,\n user_id\n }, signal);\n }\n getGameHighScoresInline(inline_message_id, user_id, signal) {\n return this.raw.getGameHighScores({\n inline_message_id,\n user_id\n }, signal);\n }\n}\nconst debug2 = browser$1(\"grammy:bot\");\nconst debugWarn = browser$1(\"grammy:warn\");\nconst debugErr = browser$1(\"grammy:error\");\nconst DEFAULT_UPDATE_TYPES = [\n \"message\",\n \"edited_message\",\n \"channel_post\",\n \"edited_channel_post\",\n \"business_connection\",\n \"business_message\",\n \"edited_business_message\",\n \"deleted_business_messages\",\n \"inline_query\",\n \"chosen_inline_result\",\n \"callback_query\",\n \"shipping_query\",\n \"pre_checkout_query\",\n \"purchased_paid_media\",\n \"poll\",\n \"poll_answer\",\n \"my_chat_member\",\n \"chat_join_request\",\n \"chat_boost\",\n \"removed_chat_boost\"\n];\nclass Bot extends Composer {\n token;\n pollingRunning;\n pollingAbortController;\n lastTriedUpdateId;\n api;\n me;\n mePromise;\n clientConfig;\n ContextConstructor;\n observedUpdateTypes;\n errorHandler;\n constructor(token, config){\n super();\n this.token = token;\n this.pollingRunning = false;\n this.lastTriedUpdateId = 0;\n this.observedUpdateTypes = new Set();\n this.errorHandler = async (err)=>{\n console.error(\"Error in middleware while handling update\", err.ctx?.update?.update_id, err.error);\n console.error(\"No error handler was set!\");\n console.error(\"Set your own error handler with `bot.catch = ...`\");\n if (this.pollingRunning) {\n console.error(\"Stopping bot\");\n await this.stop();\n }\n throw err;\n };\n if (!token) throw new Error(\"Empty token!\");\n this.me = config?.botInfo;\n this.clientConfig = config?.client;\n this.ContextConstructor = config?.ContextConstructor ?? Context;\n this.api = new Api(token, this.clientConfig);\n }\n set botInfo(botInfo) {\n this.me = botInfo;\n }\n get botInfo() {\n if (this.me === undefined) {\n throw new Error(\"Bot information unavailable! Make sure to call `await bot.init()` before accessing `bot.botInfo`!\");\n }\n return this.me;\n }\n on(filter, ...middleware) {\n for (const [u] of parse(filter).flatMap(preprocess)){\n this.observedUpdateTypes.add(u);\n }\n return super.on(filter, ...middleware);\n }\n reaction(reaction, ...middleware) {\n this.observedUpdateTypes.add(\"message_reaction\");\n return super.reaction(reaction, ...middleware);\n }\n isInited() {\n return this.me !== undefined;\n }\n async init(signal) {\n if (!this.isInited()) {\n debug2(\"Initializing bot\");\n this.mePromise ??= withRetries(()=>this.api.getMe(signal), signal);\n let me;\n try {\n me = await this.mePromise;\n } finally{\n this.mePromise = undefined;\n }\n if (this.me === undefined) this.me = me;\n else debug2(\"Bot info was set by now, will not overwrite\");\n }\n debug2(`I am ${this.me.username}!`);\n }\n async handleUpdates(updates) {\n for (const update of updates){\n this.lastTriedUpdateId = update.update_id;\n try {\n await this.handleUpdate(update);\n } catch (err) {\n if (err instanceof BotError) {\n await this.errorHandler(err);\n } else {\n console.error(\"FATAL: grammY unable to handle:\", err);\n throw err;\n }\n }\n }\n }\n async handleUpdate(update, webhookReplyEnvelope) {\n if (this.me === undefined) {\n throw new Error(\"Bot not initialized! Either call `await bot.init()`, \\\nor directly set the `botInfo` option in the `Bot` constructor to specify \\\na known bot info object.\");\n }\n debug2(`Processing update ${update.update_id}`);\n const api = new Api(this.token, this.clientConfig, webhookReplyEnvelope);\n const t = this.api.config.installedTransformers();\n if (t.length > 0) api.config.use(...t);\n const ctx = new this.ContextConstructor(update, api, this.me);\n try {\n await run(this.middleware(), ctx);\n } catch (err) {\n debugErr(`Error in middleware for update ${update.update_id}`);\n throw new BotError(err, ctx);\n }\n }\n async start(options) {\n const setup = [];\n if (!this.isInited()) {\n setup.push(this.init(this.pollingAbortController?.signal));\n }\n if (this.pollingRunning) {\n await Promise.all(setup);\n debug2(\"Simple long polling already running!\");\n return;\n }\n this.pollingRunning = true;\n this.pollingAbortController = new AbortController();\n try {\n setup.push(withRetries(async ()=>{\n await this.api.deleteWebhook({\n drop_pending_updates: options?.drop_pending_updates\n }, this.pollingAbortController?.signal);\n }, this.pollingAbortController?.signal));\n await Promise.all(setup);\n await options?.onStart?.(this.botInfo);\n } catch (err) {\n this.pollingRunning = false;\n this.pollingAbortController = undefined;\n throw err;\n }\n if (!this.pollingRunning) return;\n validateAllowedUpdates(this.observedUpdateTypes, options?.allowed_updates);\n this.use = noUseFunction;\n debug2(\"Starting simple long polling\");\n await this.loop(options);\n debug2(\"Middleware is done running\");\n }\n async stop() {\n if (this.pollingRunning) {\n debug2(\"Stopping bot, saving update offset\");\n this.pollingRunning = false;\n this.pollingAbortController?.abort();\n const offset = this.lastTriedUpdateId + 1;\n await this.api.getUpdates({\n offset,\n limit: 1\n }).finally(()=>this.pollingAbortController = undefined);\n } else {\n debug2(\"Bot is not running!\");\n }\n }\n isRunning() {\n return this.pollingRunning;\n }\n catch(errorHandler) {\n this.errorHandler = errorHandler;\n }\n async loop(options) {\n const limit = options?.limit;\n const timeout = options?.timeout ?? 30;\n let allowed_updates = options?.allowed_updates ?? [];\n try {\n while(this.pollingRunning){\n const updates = await this.fetchUpdates({\n limit,\n timeout,\n allowed_updates\n });\n if (updates === undefined) break;\n await this.handleUpdates(updates);\n allowed_updates = undefined;\n }\n } finally{\n this.pollingRunning = false;\n }\n }\n async fetchUpdates({ limit, timeout, allowed_updates }) {\n const offset = this.lastTriedUpdateId + 1;\n let updates = undefined;\n do {\n try {\n updates = await this.api.getUpdates({\n offset,\n limit,\n timeout,\n allowed_updates\n }, this.pollingAbortController?.signal);\n } catch (error) {\n await this.handlePollingError(error);\n }\n }while (updates === undefined && this.pollingRunning)\n return updates;\n }\n async handlePollingError(error) {\n if (!this.pollingRunning) {\n debug2(\"Pending getUpdates request cancelled\");\n return;\n }\n let sleepSeconds = 3;\n if (error instanceof GrammyError) {\n debugErr(error.message);\n if (error.error_code === 401 || error.error_code === 409) {\n throw error;\n } else if (error.error_code === 429) {\n debugErr(\"Bot API server is closing.\");\n sleepSeconds = error.parameters.retry_after ?? sleepSeconds;\n }\n } else debugErr(error);\n debugErr(`Call to getUpdates failed, retrying in ${sleepSeconds} seconds ...`);\n await sleep(sleepSeconds);\n }\n}\nasync function withRetries(task, signal) {\n const INITIAL_DELAY = 50;\n let lastDelay = 50;\n async function handleError(error) {\n let delay = false;\n let strategy = \"rethrow\";\n if (error instanceof HttpError) {\n delay = true;\n strategy = \"retry\";\n } else if (error instanceof GrammyError) {\n if (error.error_code >= 500) {\n delay = true;\n strategy = \"retry\";\n } else if (error.error_code === 429) {\n const retryAfter = error.parameters.retry_after;\n if (typeof retryAfter === \"number\") {\n await sleep(retryAfter, signal);\n lastDelay = INITIAL_DELAY;\n } else {\n delay = true;\n }\n strategy = \"retry\";\n }\n }\n if (delay) {\n if (lastDelay !== 50) {\n await sleep(lastDelay, signal);\n }\n const TWENTY_MINUTES = 20 * 60 * 1000;\n lastDelay = Math.min(TWENTY_MINUTES, 2 * lastDelay);\n }\n return strategy;\n }\n let result = {\n ok: false\n };\n while(!result.ok){\n try {\n result = {\n ok: true,\n value: await task()\n };\n } catch (error) {\n debugErr(error);\n const strategy = await handleError(error);\n switch(strategy){\n case \"retry\":\n continue;\n case \"rethrow\":\n throw error;\n }\n }\n }\n return result.value;\n}\nasync function sleep(seconds, signal) {\n let handle;\n let reject;\n function abort() {\n reject?.(new Error(\"Aborted delay\"));\n if (handle !== undefined) clearTimeout(handle);\n }\n try {\n await new Promise((res, rej)=>{\n reject = rej;\n if (signal?.aborted) {\n abort();\n return;\n }\n signal?.addEventListener(\"abort\", abort);\n handle = setTimeout(res, 1000 * seconds);\n });\n } finally{\n signal?.removeEventListener(\"abort\", abort);\n }\n}\nfunction validateAllowedUpdates(updates, allowed = DEFAULT_UPDATE_TYPES) {\n const impossible = Array.from(updates).filter((u)=>!allowed.includes(u));\n if (impossible.length > 0) {\n debugWarn(`You registered listeners for the following update types, \\\nbut you did not specify them in \\`allowed_updates\\` \\\nso they may not be received: ${impossible.map((u)=>`'${u}'`).join(\", \")}`);\n }\n}\nfunction noUseFunction() {\n throw new Error(`It looks like you are registering more listeners \\\non your bot from within other listeners! This means that every time your bot \\\nhandles a message like this one, new listeners will be added. This list grows until \\\nyour machine crashes, so grammY throws this error to tell you that you should \\\nprobably do things a bit differently. If you're unsure how to resolve this problem, \\\nyou can ask in the group chat: https://telegram.me/grammyjs\n\nOn the other hand, if you actually know what you're doing and you do need to install \\\nfurther middleware while your bot is running, consider installing a composer \\\ninstance on your bot, and in turn augment the composer after the fact. This way, \\\nyou can circumvent this protection against memory leaks.`);\n}\nconst ALL_UPDATE_TYPES = [\n ...DEFAULT_UPDATE_TYPES,\n \"chat_member\",\n \"message_reaction\",\n \"message_reaction_count\"\n];\nconst ALL_CHAT_PERMISSIONS = {\n can_send_messages: true,\n can_send_audios: true,\n can_send_documents: true,\n can_send_photos: true,\n can_send_videos: true,\n can_send_video_notes: true,\n can_send_voice_notes: true,\n can_send_polls: true,\n can_send_other_messages: true,\n can_add_web_page_previews: true,\n can_change_info: true,\n can_invite_users: true,\n can_edit_tag: true,\n can_pin_messages: true,\n can_manage_topics: true\n};\nconst API_CONSTANTS = {\n DEFAULT_UPDATE_TYPES,\n ALL_UPDATE_TYPES,\n ALL_CHAT_PERMISSIONS\n};\nObject.freeze(API_CONSTANTS);\nexport { API_CONSTANTS as API_CONSTANTS };\nfunction inputMessage(queryTemplate) {\n return {\n ...queryTemplate,\n ...inputMessageMethods(queryTemplate)\n };\n}\nfunction inputMessageMethods(queryTemplate) {\n return {\n text (message_text, options = {}) {\n const content = {\n message_text,\n ...options\n };\n return {\n ...queryTemplate,\n input_message_content: content\n };\n },\n location (latitude, longitude, options = {}) {\n const content = {\n latitude,\n longitude,\n ...options\n };\n return {\n ...queryTemplate,\n input_message_content: content\n };\n },\n venue (title, latitude, longitude, address, options) {\n const content = {\n title,\n latitude,\n longitude,\n address,\n ...options\n };\n return {\n ...queryTemplate,\n input_message_content: content\n };\n },\n contact (first_name, phone_number, options = {}) {\n const content = {\n first_name,\n phone_number,\n ...options\n };\n return {\n ...queryTemplate,\n input_message_content: content\n };\n },\n invoice (title, description, payload, provider_token, currency, prices, options = {}) {\n const content = {\n title,\n description,\n payload,\n provider_token,\n currency,\n prices,\n ...options\n };\n return {\n ...queryTemplate,\n input_message_content: content\n };\n }\n };\n}\nconst InlineQueryResultBuilder = {\n article (id, title, options = {}) {\n return inputMessageMethods({\n type: \"article\",\n id,\n title,\n ...options\n });\n },\n audio (id, title, audio_url, options = {}) {\n return inputMessage({\n type: \"audio\",\n id,\n title,\n audio_url: typeof audio_url === \"string\" ? audio_url : audio_url.href,\n ...options\n });\n },\n audioCached (id, audio_file_id, options = {}) {\n return inputMessage({\n type: \"audio\",\n id,\n audio_file_id,\n ...options\n });\n },\n contact (id, phone_number, first_name, options = {}) {\n return inputMessage({\n type: \"contact\",\n id,\n phone_number,\n first_name,\n ...options\n });\n },\n documentPdf (id, title, document_url, options = {}) {\n return inputMessage({\n type: \"document\",\n mime_type: \"application/pdf\",\n id,\n title,\n document_url: typeof document_url === \"string\" ? document_url : document_url.href,\n ...options\n });\n },\n documentZip (id, title, document_url, options = {}) {\n return inputMessage({\n type: \"document\",\n mime_type: \"application/zip\",\n id,\n title,\n document_url: typeof document_url === \"string\" ? document_url : document_url.href,\n ...options\n });\n },\n documentCached (id, title, document_file_id, options = {}) {\n return inputMessage({\n type: \"document\",\n id,\n title,\n document_file_id,\n ...options\n });\n },\n game (id, game_short_name, options = {}) {\n return {\n type: \"game\",\n id,\n game_short_name,\n ...options\n };\n },\n gif (id, gif_url, thumbnail_url, options = {}) {\n return inputMessage({\n type: \"gif\",\n id,\n gif_url: typeof gif_url === \"string\" ? gif_url : gif_url.href,\n thumbnail_url: typeof thumbnail_url === \"string\" ? thumbnail_url : thumbnail_url.href,\n ...options\n });\n },\n gifCached (id, gif_file_id, options = {}) {\n return inputMessage({\n type: \"gif\",\n id,\n gif_file_id,\n ...options\n });\n },\n location (id, title, latitude, longitude, options = {}) {\n return inputMessage({\n type: \"location\",\n id,\n title,\n latitude,\n longitude,\n ...options\n });\n },\n mpeg4gif (id, mpeg4_url, thumbnail_url, options = {}) {\n return inputMessage({\n type: \"mpeg4_gif\",\n id,\n mpeg4_url: typeof mpeg4_url === \"string\" ? mpeg4_url : mpeg4_url.href,\n thumbnail_url: typeof thumbnail_url === \"string\" ? thumbnail_url : thumbnail_url.href,\n ...options\n });\n },\n mpeg4gifCached (id, mpeg4_file_id, options = {}) {\n return inputMessage({\n type: \"mpeg4_gif\",\n id,\n mpeg4_file_id,\n ...options\n });\n },\n photo (id, photo_url, options = {}) {\n const photoUrl = typeof photo_url === \"string\" ? photo_url : photo_url.href;\n return inputMessage({\n type: \"photo\",\n id,\n photo_url: photoUrl,\n thumbnail_url: photoUrl,\n ...options\n });\n },\n photoCached (id, photo_file_id, options = {}) {\n return inputMessage({\n type: \"photo\",\n id,\n photo_file_id,\n ...options\n });\n },\n stickerCached (id, sticker_file_id, options = {}) {\n return inputMessage({\n type: \"sticker\",\n id,\n sticker_file_id,\n ...options\n });\n },\n venue (id, title, latitude, longitude, address, options = {}) {\n return inputMessage({\n type: \"venue\",\n id,\n title,\n latitude,\n longitude,\n address,\n ...options\n });\n },\n videoHtml (id, title, video_url, thumbnail_url, options = {}) {\n return inputMessageMethods({\n type: \"video\",\n mime_type: \"text/html\",\n id,\n title,\n video_url: typeof video_url === \"string\" ? video_url : video_url.href,\n thumbnail_url: typeof thumbnail_url === \"string\" ? thumbnail_url : thumbnail_url.href,\n ...options\n });\n },\n videoMp4 (id, title, video_url, thumbnail_url, options = {}) {\n return inputMessage({\n type: \"video\",\n mime_type: \"video/mp4\",\n id,\n title,\n video_url: typeof video_url === \"string\" ? video_url : video_url.href,\n thumbnail_url: typeof thumbnail_url === \"string\" ? thumbnail_url : thumbnail_url.href,\n ...options\n });\n },\n videoCached (id, title, video_file_id, options = {}) {\n return inputMessage({\n type: \"video\",\n id,\n title,\n video_file_id,\n ...options\n });\n },\n voice (id, title, voice_url, options = {}) {\n return inputMessage({\n type: \"voice\",\n id,\n title,\n voice_url: typeof voice_url === \"string\" ? voice_url : voice_url.href,\n ...options\n });\n },\n voiceCached (id, title, voice_file_id, options = {}) {\n return inputMessage({\n type: \"voice\",\n id,\n title,\n voice_file_id,\n ...options\n });\n }\n};\nexport { InlineQueryResultBuilder as InlineQueryResultBuilder };\nconst InputMediaBuilder = {\n photo (media, options = {}) {\n return {\n type: \"photo\",\n media,\n ...options\n };\n },\n video (media, options = {}) {\n return {\n type: \"video\",\n media,\n ...options\n };\n },\n animation (media, options = {}) {\n return {\n type: \"animation\",\n media,\n ...options\n };\n },\n audio (media, options = {}) {\n return {\n type: \"audio\",\n media,\n ...options\n };\n },\n document (media, options = {}) {\n return {\n type: \"document\",\n media,\n ...options\n };\n }\n};\nexport { InputMediaBuilder as InputMediaBuilder };\nclass Keyboard {\n keyboard;\n is_persistent;\n selective;\n one_time_keyboard;\n resize_keyboard;\n input_field_placeholder;\n constructor(keyboard = [\n []\n ]){\n this.keyboard = keyboard;\n }\n add(...buttons) {\n this.keyboard[this.keyboard.length - 1]?.push(...buttons);\n return this;\n }\n row(...buttons) {\n this.keyboard.push(buttons);\n return this;\n }\n text(text, options) {\n return this.add(Keyboard.text(text, options));\n }\n static text(text, options) {\n return typeof options === \"string\" ? {\n text,\n style: options\n } : {\n text,\n ...options\n };\n }\n requestUsers(text, requestId, options = {}) {\n return this.add(Keyboard.requestUsers(text, requestId, options));\n }\n static requestUsers(text, requestId, options = {}) {\n return typeof text === \"string\" ? {\n text,\n request_users: {\n request_id: requestId,\n ...options\n }\n } : {\n ...text,\n request_users: {\n request_id: requestId,\n ...options\n }\n };\n }\n requestChat(text, requestId, options = {\n chat_is_channel: false\n }) {\n return this.add(Keyboard.requestChat(text, requestId, options));\n }\n static requestChat(text, requestId, options = {\n chat_is_channel: false\n }) {\n const request_chat = {\n request_id: requestId,\n ...options\n };\n return typeof text === \"string\" ? {\n text,\n request_chat\n } : {\n ...text,\n request_chat\n };\n }\n requestContact(text) {\n return this.add(Keyboard.requestContact(text));\n }\n static requestContact(text) {\n return typeof text === \"string\" ? {\n text,\n request_contact: true\n } : {\n ...text,\n request_contact: true\n };\n }\n requestLocation(text) {\n return this.add(Keyboard.requestLocation(text));\n }\n static requestLocation(text) {\n return typeof text === \"string\" ? {\n text,\n request_location: true\n } : {\n ...text,\n request_location: true\n };\n }\n requestPoll(text, type) {\n return this.add(Keyboard.requestPoll(text, type));\n }\n static requestPoll(text, type) {\n const request_poll = {\n type\n };\n return typeof text === \"string\" ? {\n text,\n request_poll\n } : {\n ...text,\n request_poll\n };\n }\n webApp(text, url) {\n return this.add(Keyboard.webApp(text, url));\n }\n static webApp(text, url) {\n const web_app = {\n url\n };\n return typeof text === \"string\" ? {\n text,\n web_app\n } : {\n ...text,\n web_app\n };\n }\n style(style) {\n const rows = this.keyboard.length;\n if (rows === 0) {\n throw new Error(\"Need to add a button before applying a style!\");\n }\n const lastRow = this.keyboard[rows - 1];\n const cols = lastRow.length;\n if (cols === 0) {\n throw new Error(\"Need to add a button before applying a style!\");\n }\n let lastButton = lastRow[cols - 1];\n if (typeof lastButton === \"string\") {\n lastButton = {\n text: lastButton\n };\n lastRow[cols - 1] = lastButton;\n }\n lastButton.style = style;\n return this;\n }\n danger() {\n return this.style(\"danger\");\n }\n success() {\n return this.style(\"success\");\n }\n primary() {\n return this.style(\"primary\");\n }\n icon(icon) {\n const rows = this.keyboard.length;\n if (rows === 0) {\n throw new Error(\"Need to add a button before adding an icon!\");\n }\n const lastRow = this.keyboard[rows - 1];\n const cols = lastRow.length;\n if (cols === 0) {\n throw new Error(\"Need to add a button before adding an icon!\");\n }\n let lastButton = lastRow[cols - 1];\n if (typeof lastButton === \"string\") {\n lastButton = {\n text: lastButton\n };\n lastRow[cols - 1] = lastButton;\n }\n lastButton.icon_custom_emoji_id = icon;\n return this;\n }\n persistent(isEnabled = true) {\n this.is_persistent = isEnabled;\n return this;\n }\n selected(isEnabled = true) {\n this.selective = isEnabled;\n return this;\n }\n oneTime(isEnabled = true) {\n this.one_time_keyboard = isEnabled;\n return this;\n }\n resized(isEnabled = true) {\n this.resize_keyboard = isEnabled;\n return this;\n }\n placeholder(value) {\n this.input_field_placeholder = value;\n return this;\n }\n toTransposed() {\n const original = this.keyboard;\n const transposed = transpose(original);\n return this.clone(transposed);\n }\n toFlowed(columns, options = {}) {\n const original = this.keyboard;\n const flowed = reflow(original, columns, options);\n return this.clone(flowed);\n }\n clone(keyboard = this.keyboard) {\n const clone = new Keyboard(keyboard.map((row)=>row.slice()));\n clone.is_persistent = this.is_persistent;\n clone.selective = this.selective;\n clone.one_time_keyboard = this.one_time_keyboard;\n clone.resize_keyboard = this.resize_keyboard;\n clone.input_field_placeholder = this.input_field_placeholder;\n return clone;\n }\n append(...sources) {\n for (const source of sources){\n const keyboard = Keyboard.from(source);\n this.keyboard.push(...keyboard.keyboard.map((row)=>row.slice()));\n }\n return this;\n }\n build() {\n return this.keyboard;\n }\n static from(source) {\n if (source instanceof Keyboard) return source.clone();\n function toButton(btn) {\n return typeof btn === \"string\" ? Keyboard.text(btn) : btn;\n }\n return new Keyboard(source.map((row)=>row.map(toButton)));\n }\n}\nclass InlineKeyboard {\n inline_keyboard;\n constructor(inline_keyboard = [\n []\n ]){\n this.inline_keyboard = inline_keyboard;\n }\n add(...buttons) {\n this.inline_keyboard[this.inline_keyboard.length - 1]?.push(...buttons);\n return this;\n }\n row(...buttons) {\n this.inline_keyboard.push(buttons);\n return this;\n }\n url(text, url) {\n return this.add(InlineKeyboard.url(text, url));\n }\n static url(text, url) {\n return typeof text === \"string\" ? {\n text,\n url\n } : {\n ...text,\n url\n };\n }\n text(text, data = typeof text === \"string\" ? text : text.text) {\n return this.add(InlineKeyboard.text(text, data));\n }\n static text(text, data = typeof text === \"string\" ? text : text.text) {\n return typeof text === \"string\" ? {\n text,\n callback_data: data\n } : {\n ...text,\n callback_data: data\n };\n }\n webApp(text, url) {\n return this.add(InlineKeyboard.webApp(text, url));\n }\n static webApp(text, url) {\n const web_app = typeof url === \"string\" ? {\n url\n } : url;\n return typeof text === \"string\" ? {\n text,\n web_app\n } : {\n ...text,\n web_app\n };\n }\n login(text, loginUrl) {\n return this.add(InlineKeyboard.login(text, loginUrl));\n }\n static login(text, loginUrl) {\n const login_url = typeof loginUrl === \"string\" ? {\n url: loginUrl\n } : loginUrl;\n return typeof text === \"string\" ? {\n text,\n login_url\n } : {\n ...text,\n login_url\n };\n }\n switchInline(text, query = \"\") {\n return this.add(InlineKeyboard.switchInline(text, query));\n }\n static switchInline(text, query = \"\") {\n return typeof text === \"string\" ? {\n text,\n switch_inline_query: query\n } : {\n ...text,\n switch_inline_query: query\n };\n }\n switchInlineCurrent(text, query = \"\") {\n return this.add(InlineKeyboard.switchInlineCurrent(text, query));\n }\n static switchInlineCurrent(text, query = \"\") {\n return typeof text === \"string\" ? {\n text,\n switch_inline_query_current_chat: query\n } : {\n ...text,\n switch_inline_query_current_chat: query\n };\n }\n switchInlineChosen(text, query = {}) {\n return this.add(InlineKeyboard.switchInlineChosen(text, query));\n }\n static switchInlineChosen(text, query = {}) {\n return typeof text === \"string\" ? {\n text,\n switch_inline_query_chosen_chat: query\n } : {\n ...text,\n switch_inline_query_chosen_chat: query\n };\n }\n copyText(text, copyText) {\n return this.add(InlineKeyboard.copyText(text, copyText));\n }\n static copyText(text, copyText) {\n const copy_text = typeof copyText === \"string\" ? {\n text: copyText\n } : copyText;\n return typeof text === \"string\" ? {\n text,\n copy_text\n } : {\n ...text,\n copy_text\n };\n }\n game(text) {\n return this.add(InlineKeyboard.game(text));\n }\n static game(text) {\n const callback_game = {};\n return typeof text === \"string\" ? {\n text,\n callback_game\n } : {\n ...text,\n callback_game\n };\n }\n pay(text) {\n return this.add(InlineKeyboard.pay(text));\n }\n static pay(text) {\n return typeof text === \"string\" ? {\n text,\n pay: true\n } : {\n ...text,\n pay: true\n };\n }\n style(style) {\n const rows = this.inline_keyboard.length;\n if (rows === 0) {\n throw new Error(\"Need to add a button before applying a style!\");\n }\n const lastRow = this.inline_keyboard[rows - 1];\n const cols = lastRow.length;\n if (cols === 0) {\n throw new Error(\"Need to add a button before applying a style!\");\n }\n lastRow[cols - 1].style = style;\n return this;\n }\n danger() {\n return this.style(\"danger\");\n }\n success() {\n return this.style(\"success\");\n }\n primary() {\n return this.style(\"primary\");\n }\n icon(icon) {\n const rows = this.inline_keyboard.length;\n if (rows === 0) {\n throw new Error(\"Need to add a button before adding an icon!\");\n }\n const lastRow = this.inline_keyboard[rows - 1];\n const cols = lastRow.length;\n if (cols === 0) {\n throw new Error(\"Need to add a button before adding an icon!\");\n }\n lastRow[cols - 1].icon_custom_emoji_id = icon;\n return this;\n }\n toTransposed() {\n const original = this.inline_keyboard;\n const transposed = transpose(original);\n return new InlineKeyboard(transposed);\n }\n toFlowed(columns, options = {}) {\n const original = this.inline_keyboard;\n const flowed = reflow(original, columns, options);\n return new InlineKeyboard(flowed);\n }\n clone() {\n return new InlineKeyboard(this.inline_keyboard.map((row)=>row.slice()));\n }\n append(...sources) {\n for (const source of sources){\n const keyboard = InlineKeyboard.from(source);\n this.inline_keyboard.push(...keyboard.inline_keyboard.map((row)=>row.slice()));\n }\n return this;\n }\n static from(source) {\n if (source instanceof InlineKeyboard) return source.clone();\n return new InlineKeyboard(source.map((row)=>row.slice()));\n }\n}\nfunction transpose(grid) {\n const transposed = [];\n for(let i = 0; i < grid.length; i++){\n const row = grid[i];\n for(let j = 0; j < row.length; j++){\n const button = row[j];\n (transposed[j] ??= []).push(button);\n }\n }\n return transposed;\n}\nfunction reflow(grid, columns, { fillLastRow = false }) {\n let first = columns;\n if (fillLastRow) {\n const buttonCount = grid.map((row)=>row.length).reduce((a, b)=>a + b, 0);\n first = buttonCount % columns;\n }\n const reflowed = [];\n for (const row of grid){\n for (const button of row){\n const at = Math.max(0, reflowed.length - 1);\n const max = at === 0 ? first : columns;\n let next = reflowed[at] ??= [];\n if (next.length === max) {\n next = [];\n reflowed.push(next);\n }\n next.push(button);\n }\n }\n return reflowed;\n}\nexport { Keyboard as Keyboard };\nexport { InlineKeyboard as InlineKeyboard };\nconst debug3 = browser$1(\"grammy:session\");\nfunction session(options = {}) {\n return options.type === \"multi\" ? strictMultiSession(options) : strictSingleSession(options);\n}\nfunction strictSingleSession(options) {\n const { initial, storage, getSessionKey, custom } = fillDefaults(options);\n return async (ctx, next)=>{\n const propSession = new PropertySession(storage, ctx, \"session\", initial);\n const key = await getSessionKey(ctx);\n await propSession.init(key, {\n custom,\n lazy: false\n });\n await next();\n await propSession.finish();\n };\n}\nfunction strictMultiSession(options) {\n const props = Object.keys(options).filter((k)=>k !== \"type\");\n const defaults = Object.fromEntries(props.map((prop)=>[\n prop,\n fillDefaults(options[prop])\n ]));\n return async (ctx, next)=>{\n ctx.session = {};\n const propSessions = await Promise.all(props.map(async (prop)=>{\n const { initial, storage, getSessionKey, custom } = defaults[prop];\n const s = new PropertySession(storage, ctx.session, prop, initial);\n const key = await getSessionKey(ctx);\n await s.init(key, {\n custom,\n lazy: false\n });\n return s;\n }));\n await next();\n if (ctx.session == null) propSessions.forEach((s)=>s.delete());\n await Promise.all(propSessions.map((s)=>s.finish()));\n };\n}\nfunction lazySession(options = {}) {\n if (options.type !== undefined && options.type !== \"single\") {\n throw new Error(\"Cannot use lazy multi sessions!\");\n }\n const { initial, storage, getSessionKey, custom } = fillDefaults(options);\n return async (ctx, next)=>{\n const propSession = new PropertySession(storage, ctx, \"session\", initial);\n const key = await getSessionKey(ctx);\n await propSession.init(key, {\n custom,\n lazy: true\n });\n await next();\n await propSession.finish();\n };\n}\nclass PropertySession {\n storage;\n obj;\n prop;\n initial;\n key;\n value;\n promise;\n fetching;\n read;\n wrote;\n constructor(storage, obj, prop, initial){\n this.storage = storage;\n this.obj = obj;\n this.prop = prop;\n this.initial = initial;\n this.fetching = false;\n this.read = false;\n this.wrote = false;\n }\n load() {\n if (this.key === undefined) {\n return;\n }\n if (this.wrote) {\n return;\n }\n if (this.promise === undefined) {\n this.fetching = true;\n this.promise = Promise.resolve(this.storage.read(this.key)).then((val)=>{\n this.fetching = false;\n if (this.wrote) {\n return this.value;\n }\n if (val !== undefined) {\n this.value = val;\n return val;\n }\n val = this.initial?.();\n if (val !== undefined) {\n this.wrote = true;\n this.value = val;\n }\n return val;\n });\n }\n return this.promise;\n }\n async init(key, opts) {\n this.key = key;\n if (!opts.lazy) await this.load();\n Object.defineProperty(this.obj, this.prop, {\n enumerable: true,\n get: ()=>{\n if (key === undefined) {\n const msg = undef(\"access\", opts);\n throw new Error(msg);\n }\n this.read = true;\n if (!opts.lazy || this.wrote) return this.value;\n this.load();\n return this.fetching ? this.promise : this.value;\n },\n set: (v)=>{\n if (key === undefined) {\n const msg = undef(\"assign\", opts);\n throw new Error(msg);\n }\n this.wrote = true;\n this.fetching = false;\n this.value = v;\n }\n });\n }\n delete() {\n Object.assign(this.obj, {\n [this.prop]: undefined\n });\n }\n async finish() {\n if (this.key !== undefined) {\n if (this.read) await this.load();\n if (this.read || this.wrote) {\n const value = await this.value;\n if (value == null) await this.storage.delete(this.key);\n else await this.storage.write(this.key, value);\n }\n }\n }\n}\nfunction fillDefaults(opts = {}) {\n let { prefix = \"\", getSessionKey = defaultGetSessionKey, initial, storage } = opts;\n if (storage == null) {\n debug3(\"Storing session data in memory, all data will be lost when the bot restarts.\");\n storage = new MemorySessionStorage();\n }\n const custom = getSessionKey !== defaultGetSessionKey;\n return {\n initial,\n storage,\n getSessionKey: async (ctx)=>{\n const key = await getSessionKey(ctx);\n return key === undefined ? undefined : prefix + key;\n },\n custom\n };\n}\nfunction defaultGetSessionKey(ctx) {\n return ctx.chatId?.toString();\n}\nfunction undef(op, opts) {\n const { lazy = false, custom } = opts;\n const reason = custom ? \"the custom `getSessionKey` function returned undefined for this update\" : \"this update does not belong to a chat, so the session key is undefined\";\n return `Cannot ${op} ${lazy ? \"lazy \" : \"\"}session data because ${reason}!`;\n}\nfunction isEnhance(value) {\n return value === undefined || typeof value === \"object\" && value !== null && \"__d\" in value;\n}\nfunction enhanceStorage(options) {\n let { storage, millisecondsToLive, migrations } = options;\n storage = compatStorage(storage);\n if (millisecondsToLive !== undefined) {\n storage = timeoutStorage(storage, millisecondsToLive);\n }\n if (migrations !== undefined) {\n storage = migrationStorage(storage, migrations);\n }\n return wrapStorage(storage);\n}\nfunction compatStorage(storage) {\n return {\n read: async (k)=>{\n const v = await storage.read(k);\n return isEnhance(v) ? v : {\n __d: v\n };\n },\n write: (k, v)=>storage.write(k, v),\n delete: (k)=>storage.delete(k)\n };\n}\nfunction timeoutStorage(storage, millisecondsToLive) {\n const ttlStorage = {\n read: async (k)=>{\n const value = await storage.read(k);\n if (value === undefined) return undefined;\n if (value.e === undefined) {\n await ttlStorage.write(k, value);\n return value;\n }\n if (value.e < Date.now()) {\n await ttlStorage.delete(k);\n return undefined;\n }\n return value;\n },\n write: async (k, v)=>{\n v.e = addExpiryDate(v, millisecondsToLive).expires;\n await storage.write(k, v);\n },\n delete: (k)=>storage.delete(k)\n };\n return ttlStorage;\n}\nfunction migrationStorage(storage, migrations) {\n const versions = Object.keys(migrations).map((v)=>parseInt(v)).sort((a, b)=>a - b);\n const count = versions.length;\n if (count === 0) throw new Error(\"No migrations given!\");\n const earliest = versions[0];\n const last = count - 1;\n const latest = versions[last];\n const index = new Map();\n versions.forEach((v, i)=>index.set(v, i));\n function nextAfter(current) {\n let i = last;\n while(current <= versions[i])i--;\n return i;\n }\n return {\n read: async (k)=>{\n const val = await storage.read(k);\n if (val === undefined) return val;\n let { __d: value, v: current = earliest - 1 } = val;\n let i = 1 + (index.get(current) ?? nextAfter(current));\n for(; i < count; i++)value = migrations[versions[i]](value);\n return {\n ...val,\n v: latest,\n __d: value\n };\n },\n write: (k, v)=>storage.write(k, {\n v: latest,\n ...v\n }),\n delete: (k)=>storage.delete(k)\n };\n}\nfunction wrapStorage(storage) {\n return {\n read: (k)=>Promise.resolve(storage.read(k)).then((v)=>v?.__d),\n write: (k, v)=>storage.write(k, {\n __d: v\n }),\n delete: (k)=>storage.delete(k)\n };\n}\nclass MemorySessionStorage {\n timeToLive;\n storage;\n constructor(timeToLive){\n this.timeToLive = timeToLive;\n this.storage = new Map();\n }\n read(key) {\n const value = this.storage.get(key);\n if (value === undefined) return undefined;\n if (value.expires !== undefined && value.expires < Date.now()) {\n this.delete(key);\n return undefined;\n }\n return value.session;\n }\n readAll() {\n return this.readAllValues();\n }\n readAllKeys() {\n return Array.from(this.storage.keys());\n }\n readAllValues() {\n return Array.from(this.storage.keys()).map((key)=>this.read(key)).filter((value)=>value !== undefined);\n }\n readAllEntries() {\n return Array.from(this.storage.keys()).map((key)=>[\n key,\n this.read(key)\n ]).filter((pair)=>pair[1] !== undefined);\n }\n has(key) {\n return this.storage.has(key);\n }\n write(key, value) {\n this.storage.set(key, addExpiryDate(value, this.timeToLive));\n }\n delete(key) {\n this.storage.delete(key);\n }\n}\nfunction addExpiryDate(value, ttl) {\n if (ttl !== undefined && ttl < Infinity) {\n const now = Date.now();\n return {\n session: value,\n expires: now + ttl\n };\n } else {\n return {\n session: value\n };\n }\n}\nexport { session as session };\nexport { lazySession as lazySession };\nexport { enhanceStorage as enhanceStorage };\nexport { MemorySessionStorage as MemorySessionStorage };\nconst SECRET_HEADER = \"X-Telegram-Bot-Api-Secret-Token\";\nconst SECRET_HEADER_LOWERCASE = SECRET_HEADER.toLowerCase();\nconst WRONG_TOKEN_ERROR = \"secret token is wrong\";\nconst ok = ()=>new Response(null, {\n status: 200\n });\nconst okJson = (json)=>new Response(json, {\n status: 200,\n headers: {\n \"Content-Type\": \"application/json\"\n }\n });\nconst unauthorized = ()=>new Response('\"unauthorized\"', {\n status: 401,\n statusText: WRONG_TOKEN_ERROR\n });\nconst awsLambda = (event, _context, callback)=>({\n get update () {\n return JSON.parse(event.body ?? \"{}\");\n },\n header: event.headers[SECRET_HEADER],\n end: ()=>callback(null, {\n statusCode: 200\n }),\n respond: (json)=>callback(null, {\n statusCode: 200,\n headers: {\n \"Content-Type\": \"application/json\"\n },\n body: json\n }),\n unauthorized: ()=>callback(null, {\n statusCode: 401\n })\n });\nconst awsLambdaAsync = (event, _context)=>{\n let resolveResponse;\n return {\n get update () {\n return JSON.parse(event.body ?? \"{}\");\n },\n header: event.headers[SECRET_HEADER],\n end: ()=>resolveResponse({\n statusCode: 200\n }),\n respond: (json)=>resolveResponse({\n statusCode: 200,\n headers: {\n \"Content-Type\": \"application/json\"\n },\n body: json\n }),\n unauthorized: ()=>resolveResponse({\n statusCode: 401\n }),\n handlerReturn: new Promise((res)=>resolveResponse = res)\n };\n};\nconst azure = (context, request)=>({\n get update () {\n return request.body;\n },\n header: context.res?.headers?.[SECRET_HEADER],\n end: ()=>context.res = {\n status: 200,\n body: \"\"\n },\n respond: (json)=>{\n context.res?.set?.(\"Content-Type\", \"application/json\");\n context.res?.send?.(json);\n },\n unauthorized: ()=>{\n context.res?.send?.(401, WRONG_TOKEN_ERROR);\n }\n });\nconst azureV4 = (request)=>{\n let resolveResponse;\n return {\n get update () {\n return request.json();\n },\n header: request.headers.get(SECRET_HEADER) || undefined,\n end: ()=>resolveResponse({\n status: 204\n }),\n respond: (json)=>resolveResponse({\n jsonBody: json\n }),\n unauthorized: ()=>resolveResponse({\n status: 401,\n body: WRONG_TOKEN_ERROR\n }),\n handlerReturn: new Promise((resolve)=>resolveResponse = resolve)\n };\n};\nconst bun = (request)=>{\n let resolveResponse;\n return {\n get update () {\n return request.json();\n },\n header: request.headers.get(SECRET_HEADER) || undefined,\n end: ()=>{\n resolveResponse(ok());\n },\n respond: (json)=>{\n resolveResponse(okJson(json));\n },\n unauthorized: ()=>{\n resolveResponse(unauthorized());\n },\n handlerReturn: new Promise((res)=>resolveResponse = res)\n };\n};\nconst cloudflare = (event)=>{\n let resolveResponse;\n event.respondWith(new Promise((resolve)=>{\n resolveResponse = resolve;\n }));\n return {\n get update () {\n return event.request.json();\n },\n header: event.request.headers.get(SECRET_HEADER) || undefined,\n end: ()=>{\n resolveResponse(ok());\n },\n respond: (json)=>{\n resolveResponse(okJson(json));\n },\n unauthorized: ()=>{\n resolveResponse(unauthorized());\n }\n };\n};\nconst cloudflareModule = (request)=>{\n let resolveResponse;\n return {\n get update () {\n return request.json();\n },\n header: request.headers.get(SECRET_HEADER) || undefined,\n end: ()=>{\n resolveResponse(ok());\n },\n respond: (json)=>{\n resolveResponse(okJson(json));\n },\n unauthorized: ()=>{\n resolveResponse(unauthorized());\n },\n handlerReturn: new Promise((res)=>resolveResponse = res)\n };\n};\nconst express = (req, res)=>({\n get update () {\n return req.body;\n },\n header: req.header(SECRET_HEADER),\n end: ()=>res.end(),\n respond: (json)=>{\n res.set(\"Content-Type\", \"application/json\");\n res.send(json);\n },\n unauthorized: ()=>{\n res.status(401).send(WRONG_TOKEN_ERROR);\n }\n });\nconst fastify = (request, reply)=>({\n get update () {\n return request.body;\n },\n header: request.headers[SECRET_HEADER_LOWERCASE],\n end: ()=>reply.send(\"\"),\n respond: (json)=>reply.headers({\n \"Content-Type\": \"application/json\"\n }).send(json),\n unauthorized: ()=>reply.code(401).send(WRONG_TOKEN_ERROR)\n });\nconst hono = (c)=>{\n let resolveResponse;\n return {\n get update () {\n return c.req.json();\n },\n header: c.req.header(SECRET_HEADER),\n end: ()=>{\n resolveResponse(c.body(\"\"));\n },\n respond: (json)=>{\n resolveResponse(c.json(json));\n },\n unauthorized: ()=>{\n c.status(401);\n resolveResponse(c.body(\"\"));\n },\n handlerReturn: new Promise((res)=>resolveResponse = res)\n };\n};\nconst http = (req, res)=>{\n const secretHeaderFromRequest = req.headers[SECRET_HEADER_LOWERCASE];\n return {\n get update () {\n return new Promise((resolve, reject)=>{\n const chunks = [];\n req.on(\"data\", (chunk)=>chunks.push(chunk)).once(\"end\", ()=>{\n const raw = Buffer.concat(chunks).toString(\"utf-8\");\n try {\n resolve(JSON.parse(raw));\n } catch (err) {\n reject(err);\n }\n }).once(\"error\", reject);\n });\n },\n header: Array.isArray(secretHeaderFromRequest) ? secretHeaderFromRequest[0] : secretHeaderFromRequest,\n end: ()=>res.end(),\n respond: (json)=>res.writeHead(200, {\n \"Content-Type\": \"application/json\"\n }).end(json),\n unauthorized: ()=>res.writeHead(401).end(WRONG_TOKEN_ERROR)\n };\n};\nconst koa = (ctx)=>({\n get update () {\n return ctx.request.body;\n },\n header: ctx.get(SECRET_HEADER) || undefined,\n end: ()=>{\n ctx.body = \"\";\n },\n respond: (json)=>{\n ctx.set(\"Content-Type\", \"application/json\");\n ctx.response.body = json;\n },\n unauthorized: ()=>{\n ctx.status = 401;\n }\n });\nconst nextJs = (request, response)=>({\n get update () {\n return request.body;\n },\n header: request.headers[SECRET_HEADER_LOWERCASE],\n end: ()=>response.end(),\n respond: (json)=>response.status(200).json(json),\n unauthorized: ()=>response.status(401).send(WRONG_TOKEN_ERROR)\n });\nconst nhttp = (rev)=>({\n get update () {\n return rev.body;\n },\n header: rev.headers.get(SECRET_HEADER) || undefined,\n end: ()=>rev.response.sendStatus(200),\n respond: (json)=>rev.response.status(200).send(json),\n unauthorized: ()=>rev.response.status(401).send(WRONG_TOKEN_ERROR)\n });\nconst oak = (ctx)=>({\n get update () {\n return ctx.request.body.json();\n },\n header: ctx.request.headers.get(SECRET_HEADER) || undefined,\n end: ()=>{\n ctx.response.status = 200;\n },\n respond: (json)=>{\n ctx.response.type = \"json\";\n ctx.response.body = json;\n },\n unauthorized: ()=>{\n ctx.response.status = 401;\n }\n });\nconst serveHttp = (requestEvent)=>({\n get update () {\n return requestEvent.request.json();\n },\n header: requestEvent.request.headers.get(SECRET_HEADER) || undefined,\n end: ()=>requestEvent.respondWith(ok()),\n respond: (json)=>requestEvent.respondWith(okJson(json)),\n unauthorized: ()=>requestEvent.respondWith(unauthorized())\n });\nconst stdHttp = (req)=>{\n let resolveResponse;\n return {\n get update () {\n return req.json();\n },\n header: req.headers.get(SECRET_HEADER) || undefined,\n end: ()=>{\n if (resolveResponse) resolveResponse(ok());\n },\n respond: (json)=>{\n if (resolveResponse) resolveResponse(okJson(json));\n },\n unauthorized: ()=>{\n if (resolveResponse) resolveResponse(unauthorized());\n },\n handlerReturn: new Promise((res)=>resolveResponse = res)\n };\n};\nconst sveltekit = ({ request })=>{\n let resolveResponse;\n return {\n get update () {\n return request.json();\n },\n header: request.headers.get(SECRET_HEADER) || undefined,\n end: ()=>{\n if (resolveResponse) resolveResponse(ok());\n },\n respond: (json)=>{\n if (resolveResponse) resolveResponse(okJson(json));\n },\n unauthorized: ()=>{\n if (resolveResponse) resolveResponse(unauthorized());\n },\n handlerReturn: new Promise((res)=>resolveResponse = res)\n };\n};\nconst worktop = (req, res)=>({\n get update () {\n return req.json();\n },\n header: req.headers.get(SECRET_HEADER) ?? undefined,\n end: ()=>res.end(null),\n respond: (json)=>res.send(200, json),\n unauthorized: ()=>res.send(401, WRONG_TOKEN_ERROR)\n });\nconst elysia = (ctx)=>{\n let resolveResponse;\n return {\n get update () {\n return ctx.body;\n },\n header: ctx.headers[SECRET_HEADER_LOWERCASE],\n end () {\n resolveResponse(\"\");\n },\n respond (json) {\n ctx.set.headers[\"content-type\"] = \"application/json\";\n resolveResponse(json);\n },\n unauthorized () {\n ctx.set.status = 401;\n resolveResponse(\"\");\n },\n handlerReturn: new Promise((res)=>resolveResponse = res)\n };\n};\nconst adapters = {\n \"aws-lambda\": awsLambda,\n \"aws-lambda-async\": awsLambdaAsync,\n azure,\n \"azure-v4\": azureV4,\n bun,\n cloudflare,\n \"cloudflare-mod\": cloudflareModule,\n elysia,\n express,\n fastify,\n hono,\n http,\n https: http,\n koa,\n \"next-js\": nextJs,\n nhttp,\n oak,\n serveHttp,\n \"std/http\": stdHttp,\n sveltekit,\n worktop\n};\nconst debugErr1 = browser$1(\"grammy:error\");\nconst callbackAdapter = (update, callback, header, unauthorized = ()=>callback('\"unauthorized\"'))=>({\n update: Promise.resolve(update),\n respond: callback,\n header,\n unauthorized\n });\nconst adapters1 = {\n ...adapters,\n callback: callbackAdapter\n};\nfunction compareSecretToken(header, token) {\n if (token === undefined) {\n return true;\n }\n if (header === undefined) {\n return false;\n }\n const encoder = new TextEncoder();\n const headerBytes = encoder.encode(header);\n const tokenBytes = encoder.encode(token);\n if (headerBytes.length !== tokenBytes.length) {\n return false;\n }\n let hasDifference = 0;\n for(let i = 0; i < tokenBytes.length; i++){\n const headerByte = i < headerBytes.length ? headerBytes[i] : 0;\n const tokenByte = tokenBytes[i];\n hasDifference |= headerByte ^ tokenByte;\n }\n return hasDifference === 0;\n}\nfunction webhookCallback(bot, adapter = defaultAdapter, onTimeout, timeoutMilliseconds, secretToken) {\n if (bot.isRunning()) {\n throw new Error(\"Bot is already running via long polling, the webhook setup won't receive any updates!\");\n } else {\n bot.start = ()=>{\n throw new Error(\"You already started the bot via webhooks, calling `bot.start()` starts the bot with long polling and this will prevent your webhook setup from receiving any updates!\");\n };\n }\n const { onTimeout: timeout = \"throw\", timeoutMilliseconds: ms = 10_000, secretToken: token } = typeof onTimeout === \"object\" ? onTimeout : {\n onTimeout,\n timeoutMilliseconds,\n secretToken\n };\n let initialized = false;\n const server = typeof adapter === \"string\" ? adapters1[adapter] : adapter;\n return async (...args)=>{\n const handler = server(...args);\n if (!initialized) {\n await bot.init();\n initialized = true;\n }\n if (!compareSecretToken(handler.header, token)) {\n await handler.unauthorized();\n return handler.handlerReturn;\n }\n let usedWebhookReply = false;\n const webhookReplyEnvelope = {\n async send (json) {\n usedWebhookReply = true;\n await handler.respond(json);\n }\n };\n await timeoutIfNecessary(bot.handleUpdate(await handler.update, webhookReplyEnvelope), typeof timeout === \"function\" ? ()=>timeout(...args) : timeout, ms);\n if (!usedWebhookReply) handler.end?.();\n return handler.handlerReturn;\n };\n}\nfunction timeoutIfNecessary(task, onTimeout, timeout) {\n if (timeout === Infinity) return task;\n return new Promise((resolve, reject)=>{\n const handle = setTimeout(()=>{\n debugErr1(`Request timed out after ${timeout} ms`);\n if (onTimeout === \"throw\") {\n reject(new Error(`Request timed out after ${timeout} ms`));\n } else {\n if (typeof onTimeout === \"function\") onTimeout();\n resolve();\n }\n const now = Date.now();\n task.finally(()=>{\n const diff = Date.now() - now;\n debugErr1(`Request completed ${diff} ms after timeout!`);\n });\n }, timeout);\n task.then(resolve).catch(reject).finally(()=>clearTimeout(handle));\n });\n}\nexport { webhookCallback as webhookCallback };\nexport { Bot as Bot, BotError as BotError };\nexport { InputFile as InputFile };\nexport { Context as Context };\nexport { Composer as Composer };\nexport { matchFilter as matchFilter };\nexport { Api as Api };\nexport { GrammyError as GrammyError, HttpError as HttpError };\n", "/// \nimport type { D1Database as MiniflareD1Database } from '@miniflare/d1';\nimport type { BatchItem, BatchResponse } from '~/batch.ts';\nimport { entityKind } from '~/entity.ts';\nimport { DefaultLogger } from '~/logger.ts';\nimport {\n\tcreateTableRelationsHelpers,\n\textractTablesRelationalConfig,\n\ttype ExtractTablesWithRelations,\n\ttype RelationalSchemaConfig,\n\ttype TablesRelationalConfig,\n} from '~/relations.ts';\nimport { BaseSQLiteDatabase } from '~/sqlite-core/db.ts';\nimport { SQLiteAsyncDialect } from '~/sqlite-core/dialect.ts';\nimport type { DrizzleConfig, IfNotImported } from '~/utils.ts';\nimport { SQLiteD1Session } from './session.ts';\n\nexport type AnyD1Database = IfNotImported<\n\tD1Database,\n\tMiniflareD1Database,\n\tD1Database | IfNotImported\n>;\n\nexport class DrizzleD1Database<\n\tTSchema extends Record = Record,\n> extends BaseSQLiteDatabase<'async', D1Result, TSchema> {\n\tstatic override readonly [entityKind]: string = 'D1Database';\n\n\t/** @internal */\n\tdeclare readonly session: SQLiteD1Session>;\n\n\tasync batch, T extends Readonly<[U, ...U[]]>>(\n\t\tbatch: T,\n\t): Promise> {\n\t\treturn this.session.batch(batch) as Promise>;\n\t}\n}\n\nexport function drizzle<\n\tTSchema extends Record = Record,\n\tTClient extends AnyD1Database = AnyD1Database,\n>(\n\tclient: TClient,\n\tconfig: DrizzleConfig = {},\n): DrizzleD1Database & {\n\t$client: TClient;\n} {\n\tconst dialect = new SQLiteAsyncDialect({ casing: config.casing });\n\tlet logger;\n\tif (config.logger === true) {\n\t\tlogger = new DefaultLogger();\n\t} else if (config.logger !== false) {\n\t\tlogger = config.logger;\n\t}\n\n\tlet schema: RelationalSchemaConfig | undefined;\n\tif (config.schema) {\n\t\tconst tablesConfig = extractTablesRelationalConfig(\n\t\t\tconfig.schema,\n\t\t\tcreateTableRelationsHelpers,\n\t\t);\n\t\tschema = {\n\t\t\tfullSchema: config.schema,\n\t\t\tschema: tablesConfig.tables,\n\t\t\ttableNamesMap: tablesConfig.tableNamesMap,\n\t\t};\n\t}\n\n\tconst session = new SQLiteD1Session(client as D1Database, dialect, schema, { logger, cache: config.cache });\n\tconst db = new DrizzleD1Database('async', dialect, session, schema) as DrizzleD1Database;\n\t( db).$client = client;\n\t( db).$cache = config.cache;\n\tif (( db).$cache) {\n\t\t( db).$cache['invalidate'] = config.cache?.onMutate;\n\t}\n\n\treturn db as any;\n}\n", "export const entityKind = Symbol.for('drizzle:entityKind');\nexport const hasOwnEntityKind = Symbol.for('drizzle:hasOwnEntityKind');\n\nexport interface DrizzleEntity {\n\t[entityKind]: string;\n}\n\nexport type DrizzleEntityClass =\n\t& ((abstract new(...args: any[]) => T) | (new(...args: any[]) => T))\n\t& DrizzleEntity;\n\nexport function is>(value: any, type: T): value is InstanceType {\n\tif (!value || typeof value !== 'object') {\n\t\treturn false;\n\t}\n\n\tif (value instanceof type) { // eslint-disable-line no-instanceof/no-instanceof\n\t\treturn true;\n\t}\n\n\tif (!Object.prototype.hasOwnProperty.call(type, entityKind)) {\n\t\tthrow new Error(\n\t\t\t`Class \"${\n\t\t\t\ttype.name ?? ''\n\t\t\t}\" doesn't look like a Drizzle entity. If this is incorrect and the class is provided by Drizzle, please report this as a bug.`,\n\t\t);\n\t}\n\n\tlet cls = Object.getPrototypeOf(value).constructor;\n\tif (cls) {\n\t\t// Traverse the prototype chain to find the entityKind\n\t\twhile (cls) {\n\t\t\tif (entityKind in cls && cls[entityKind] === type[entityKind]) {\n\t\t\t\treturn true;\n\t\t\t}\n\n\t\t\tcls = Object.getPrototypeOf(cls);\n\t\t}\n\t}\n\n\treturn false;\n}\n", "import { entityKind } from '~/entity.ts';\n\nexport interface Logger {\n\tlogQuery(query: string, params: unknown[]): void;\n}\n\nexport interface LogWriter {\n\twrite(message: string): void;\n}\n\nexport class ConsoleLogWriter implements LogWriter {\n\tstatic readonly [entityKind]: string = 'ConsoleLogWriter';\n\n\twrite(message: string) {\n\t\tconsole.log(message);\n\t}\n}\n\nexport class DefaultLogger implements Logger {\n\tstatic readonly [entityKind]: string = 'DefaultLogger';\n\n\treadonly writer: LogWriter;\n\n\tconstructor(config?: { writer: LogWriter }) {\n\t\tthis.writer = config?.writer ?? new ConsoleLogWriter();\n\t}\n\n\tlogQuery(query: string, params: unknown[]): void {\n\t\tconst stringifiedParams = params.map((p) => {\n\t\t\ttry {\n\t\t\t\treturn JSON.stringify(p);\n\t\t\t} catch {\n\t\t\t\treturn String(p);\n\t\t\t}\n\t\t});\n\t\tconst paramsStr = stringifiedParams.length ? ` -- params: [${stringifiedParams.join(', ')}]` : '';\n\t\tthis.writer.write(`Query: ${query}${paramsStr}`);\n\t}\n}\n\nexport class NoopLogger implements Logger {\n\tstatic readonly [entityKind]: string = 'NoopLogger';\n\n\tlogQuery(): void {\n\t\t// noop\n\t}\n}\n", "import { type AnyTable, getTableUniqueName, type InferModelFromColumns, Table } from '~/table.ts';\nimport { type AnyColumn, Column } from './column.ts';\nimport { entityKind, is } from './entity.ts';\nimport { PrimaryKeyBuilder } from './pg-core/primary-keys.ts';\nimport {\n\tand,\n\tasc,\n\tbetween,\n\tdesc,\n\teq,\n\texists,\n\tgt,\n\tgte,\n\tilike,\n\tinArray,\n\tisNotNull,\n\tisNull,\n\tlike,\n\tlt,\n\tlte,\n\tne,\n\tnot,\n\tnotBetween,\n\tnotExists,\n\tnotIlike,\n\tnotInArray,\n\tnotLike,\n\tor,\n} from './sql/expressions/index.ts';\nimport { type Placeholder, SQL, sql } from './sql/sql.ts';\nimport type { Assume, ColumnsWithTable, Equal, Simplify, ValueOrArray } from './utils.ts';\n\nexport abstract class Relation {\n\tstatic readonly [entityKind]: string = 'Relation';\n\n\tdeclare readonly $brand: 'Relation';\n\treadonly referencedTableName: TTableName;\n\tfieldName!: string;\n\n\tconstructor(\n\t\treadonly sourceTable: Table,\n\t\treadonly referencedTable: AnyTable<{ name: TTableName }>,\n\t\treadonly relationName: string | undefined,\n\t) {\n\t\tthis.referencedTableName = referencedTable[Table.Symbol.Name] as TTableName;\n\t}\n\n\tabstract withFieldName(fieldName: string): Relation;\n}\n\nexport class Relations<\n\tTTableName extends string = string,\n\tTConfig extends Record = Record,\n> {\n\tstatic readonly [entityKind]: string = 'Relations';\n\n\tdeclare readonly $brand: 'Relations';\n\n\tconstructor(\n\t\treadonly table: AnyTable<{ name: TTableName }>,\n\t\treadonly config: (helpers: TableRelationsHelpers) => TConfig,\n\t) {}\n}\n\nexport class One<\n\tTTableName extends string = string,\n\tTIsNullable extends boolean = boolean,\n> extends Relation {\n\tstatic override readonly [entityKind]: string = 'One';\n\n\tdeclare protected $relationBrand: 'One';\n\n\tconstructor(\n\t\tsourceTable: Table,\n\t\treferencedTable: AnyTable<{ name: TTableName }>,\n\t\treadonly config:\n\t\t\t| RelationConfig<\n\t\t\t\tTTableName,\n\t\t\t\tstring,\n\t\t\t\tAnyColumn<{ tableName: TTableName }>[]\n\t\t\t>\n\t\t\t| undefined,\n\t\treadonly isNullable: TIsNullable,\n\t) {\n\t\tsuper(sourceTable, referencedTable, config?.relationName);\n\t}\n\n\twithFieldName(fieldName: string): One {\n\t\tconst relation = new One(\n\t\t\tthis.sourceTable,\n\t\t\tthis.referencedTable,\n\t\t\tthis.config,\n\t\t\tthis.isNullable,\n\t\t);\n\t\trelation.fieldName = fieldName;\n\t\treturn relation;\n\t}\n}\n\nexport class Many extends Relation {\n\tstatic override readonly [entityKind]: string = 'Many';\n\n\tdeclare protected $relationBrand: 'Many';\n\n\tconstructor(\n\t\tsourceTable: Table,\n\t\treferencedTable: AnyTable<{ name: TTableName }>,\n\t\treadonly config: { relationName: string } | undefined,\n\t) {\n\t\tsuper(sourceTable, referencedTable, config?.relationName);\n\t}\n\n\twithFieldName(fieldName: string): Many {\n\t\tconst relation = new Many(\n\t\t\tthis.sourceTable,\n\t\t\tthis.referencedTable,\n\t\t\tthis.config,\n\t\t);\n\t\trelation.fieldName = fieldName;\n\t\treturn relation;\n\t}\n}\n\nexport type TableRelationsKeysOnly<\n\tTSchema extends Record,\n\tTTableName extends string,\n\tK extends keyof TSchema,\n> = TSchema[K] extends Relations ? K : never;\n\nexport type ExtractTableRelationsFromSchema<\n\tTSchema extends Record,\n\tTTableName extends string,\n> = ExtractObjectValues<\n\t{\n\t\t[\n\t\t\tK in keyof TSchema as TableRelationsKeysOnly<\n\t\t\t\tTSchema,\n\t\t\t\tTTableName,\n\t\t\t\tK\n\t\t\t>\n\t\t]: TSchema[K] extends Relations ? TConfig : never;\n\t}\n>;\n\nexport type ExtractObjectValues = T[keyof T];\n\nexport type ExtractRelationsFromTableExtraConfigSchema<\n\tTConfig extends unknown[],\n> = ExtractObjectValues<\n\t{\n\t\t[\n\t\t\tK in keyof TConfig as TConfig[K] extends Relations ? K\n\t\t\t\t: never\n\t\t]: TConfig[K] extends Relations ? TRelationConfig\n\t\t\t: never;\n\t}\n>;\n\nexport function getOperators() {\n\treturn {\n\t\tand,\n\t\tbetween,\n\t\teq,\n\t\texists,\n\t\tgt,\n\t\tgte,\n\t\tilike,\n\t\tinArray,\n\t\tisNull,\n\t\tisNotNull,\n\t\tlike,\n\t\tlt,\n\t\tlte,\n\t\tne,\n\t\tnot,\n\t\tnotBetween,\n\t\tnotExists,\n\t\tnotLike,\n\t\tnotIlike,\n\t\tnotInArray,\n\t\tor,\n\t\tsql,\n\t};\n}\n\nexport type Operators = ReturnType;\n\nexport function getOrderByOperators() {\n\treturn {\n\t\tsql,\n\t\tasc,\n\t\tdesc,\n\t};\n}\n\nexport type OrderByOperators = ReturnType;\n\nexport type FindTableByDBName<\n\tTSchema extends TablesRelationalConfig,\n\tTTableName extends string,\n> = ExtractObjectValues<\n\t{\n\t\t[\n\t\t\tK in keyof TSchema as TSchema[K]['dbName'] extends TTableName ? K\n\t\t\t\t: never\n\t\t]: TSchema[K];\n\t}\n>;\n\nexport type DBQueryConfig<\n\tTRelationType extends 'one' | 'many' = 'one' | 'many',\n\tTIsRoot extends boolean = boolean,\n\tTSchema extends TablesRelationalConfig = TablesRelationalConfig,\n\tTTableConfig extends TableRelationalConfig = TableRelationalConfig,\n> =\n\t& {\n\t\tcolumns?:\n\t\t\t| {\n\t\t\t\t[K in keyof TTableConfig['columns']]?: boolean;\n\t\t\t}\n\t\t\t| undefined;\n\t\twith?:\n\t\t\t| {\n\t\t\t\t[K in keyof TTableConfig['relations']]?:\n\t\t\t\t\t| true\n\t\t\t\t\t| DBQueryConfig<\n\t\t\t\t\t\tTTableConfig['relations'][K] extends One ? 'one' : 'many',\n\t\t\t\t\t\tfalse,\n\t\t\t\t\t\tTSchema,\n\t\t\t\t\t\tFindTableByDBName<\n\t\t\t\t\t\t\tTSchema,\n\t\t\t\t\t\t\tTTableConfig['relations'][K]['referencedTableName']\n\t\t\t\t\t\t>\n\t\t\t\t\t>\n\t\t\t\t\t| undefined;\n\t\t\t}\n\t\t\t| undefined;\n\t\textras?:\n\t\t\t| Record\n\t\t\t| ((\n\t\t\t\tfields: Simplify<\n\t\t\t\t\t[TTableConfig['columns']] extends [never] ? {}\n\t\t\t\t\t\t: TTableConfig['columns']\n\t\t\t\t>,\n\t\t\t\toperators: { sql: Operators['sql'] },\n\t\t\t) => Record)\n\t\t\t| undefined;\n\t}\n\t& (TRelationType extends 'many' ?\n\t\t\t& {\n\t\t\t\twhere?:\n\t\t\t\t\t| SQL\n\t\t\t\t\t| undefined\n\t\t\t\t\t| ((\n\t\t\t\t\t\tfields: Simplify<\n\t\t\t\t\t\t\t[TTableConfig['columns']] extends [never] ? {}\n\t\t\t\t\t\t\t\t: TTableConfig['columns']\n\t\t\t\t\t\t>,\n\t\t\t\t\t\toperators: Operators,\n\t\t\t\t\t) => SQL | undefined);\n\t\t\t\torderBy?:\n\t\t\t\t\t| ValueOrArray\n\t\t\t\t\t| ((\n\t\t\t\t\t\tfields: Simplify<\n\t\t\t\t\t\t\t[TTableConfig['columns']] extends [never] ? {}\n\t\t\t\t\t\t\t\t: TTableConfig['columns']\n\t\t\t\t\t\t>,\n\t\t\t\t\t\toperators: OrderByOperators,\n\t\t\t\t\t) => ValueOrArray)\n\t\t\t\t\t| undefined;\n\t\t\t\tlimit?: number | Placeholder | undefined;\n\t\t\t}\n\t\t\t& (TIsRoot extends true ? {\n\t\t\t\t\toffset?: number | Placeholder | undefined;\n\t\t\t\t}\n\t\t\t\t: {})\n\t\t: {});\n\nexport interface TableRelationalConfig {\n\ttsName: string;\n\tdbName: string;\n\tcolumns: Record;\n\trelations: Record;\n\tprimaryKey: AnyColumn[];\n\tschema?: string;\n}\n\nexport type TablesRelationalConfig = Record;\n\nexport interface RelationalSchemaConfig<\n\tTSchema extends TablesRelationalConfig,\n> {\n\tfullSchema: Record;\n\tschema: TSchema;\n\ttableNamesMap: Record;\n}\n\nexport type ExtractTablesWithRelations<\n\tTSchema extends Record,\n> = {\n\t[\n\t\tK in keyof TSchema as TSchema[K] extends Table ? K\n\t\t\t: never\n\t]: TSchema[K] extends Table ? {\n\t\t\ttsName: K & string;\n\t\t\tdbName: TSchema[K]['_']['name'];\n\t\t\tcolumns: TSchema[K]['_']['columns'];\n\t\t\trelations: ExtractTableRelationsFromSchema<\n\t\t\t\tTSchema,\n\t\t\t\tTSchema[K]['_']['name']\n\t\t\t>;\n\t\t\tprimaryKey: AnyColumn[];\n\t\t}\n\t\t: never;\n};\n\nexport type ReturnTypeOrValue = T extends (...args: any[]) => infer R ? R\n\t: T;\n\nexport type BuildRelationResult<\n\tTSchema extends TablesRelationalConfig,\n\tTInclude,\n\tTRelations extends Record,\n> = {\n\t[\n\t\tK in\n\t\t\t& NonUndefinedKeysOnly\n\t\t\t& keyof TRelations\n\t]: TRelations[K] extends infer TRel extends Relation ? BuildQueryResult<\n\t\t\tTSchema,\n\t\t\tFindTableByDBName,\n\t\t\tAssume>\n\t\t> extends infer TResult ? TRel extends One ?\n\t\t\t\t\t| TResult\n\t\t\t\t\t| (Equal extends true ? null : never)\n\t\t\t: TResult[]\n\t\t: never\n\t\t: never;\n};\n\nexport type NonUndefinedKeysOnly =\n\t& ExtractObjectValues<\n\t\t{\n\t\t\t[K in keyof T as T[K] extends undefined ? never : K]: K;\n\t\t}\n\t>\n\t& keyof T;\n\nexport type BuildQueryResult<\n\tTSchema extends TablesRelationalConfig,\n\tTTableConfig extends TableRelationalConfig,\n\tTFullSelection extends true | Record,\n> = Equal extends true ? InferModelFromColumns\n\t: TFullSelection extends Record ? Simplify<\n\t\t\t& (TFullSelection['columns'] extends Record ? InferModelFromColumns<\n\t\t\t\t\t{\n\t\t\t\t\t\t[\n\t\t\t\t\t\t\tK in Equal<\n\t\t\t\t\t\t\t\tExclude<\n\t\t\t\t\t\t\t\t\tTFullSelection['columns'][\n\t\t\t\t\t\t\t\t\t\t& keyof TFullSelection['columns']\n\t\t\t\t\t\t\t\t\t\t& keyof TTableConfig['columns']\n\t\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t\t\tundefined\n\t\t\t\t\t\t\t\t>,\n\t\t\t\t\t\t\t\tfalse\n\t\t\t\t\t\t\t> extends true ? Exclude<\n\t\t\t\t\t\t\t\t\tkeyof TTableConfig['columns'],\n\t\t\t\t\t\t\t\t\tNonUndefinedKeysOnly\n\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t:\n\t\t\t\t\t\t\t\t\t& {\n\t\t\t\t\t\t\t\t\t\t[K in keyof TFullSelection['columns']]: Equal<\n\t\t\t\t\t\t\t\t\t\t\tTFullSelection['columns'][K],\n\t\t\t\t\t\t\t\t\t\t\ttrue\n\t\t\t\t\t\t\t\t\t\t> extends true ? K\n\t\t\t\t\t\t\t\t\t\t\t: never;\n\t\t\t\t\t\t\t\t\t}[keyof TFullSelection['columns']]\n\t\t\t\t\t\t\t\t\t& keyof TTableConfig['columns']\n\t\t\t\t\t\t]: TTableConfig['columns'][K];\n\t\t\t\t\t}\n\t\t\t\t>\n\t\t\t\t: InferModelFromColumns)\n\t\t\t& (TFullSelection['extras'] extends\n\t\t\t\t| Record\n\t\t\t\t| ((...args: any[]) => Record) ? {\n\t\t\t\t\t[\n\t\t\t\t\t\tK in NonUndefinedKeysOnly<\n\t\t\t\t\t\t\tReturnTypeOrValue\n\t\t\t\t\t\t>\n\t\t\t\t\t]: Assume<\n\t\t\t\t\t\tReturnTypeOrValue[K],\n\t\t\t\t\t\tSQL.Aliased\n\t\t\t\t\t>['_']['type'];\n\t\t\t\t}\n\t\t\t\t: {})\n\t\t\t& (TFullSelection['with'] extends Record ? BuildRelationResult<\n\t\t\t\t\tTSchema,\n\t\t\t\t\tTFullSelection['with'],\n\t\t\t\t\tTTableConfig['relations']\n\t\t\t\t>\n\t\t\t\t: {})\n\t\t>\n\t: never;\n\nexport interface RelationConfig<\n\tTTableName extends string,\n\tTForeignTableName extends string,\n\tTColumns extends AnyColumn<{ tableName: TTableName }>[],\n> {\n\trelationName?: string;\n\tfields: TColumns;\n\treferences: ColumnsWithTable;\n}\n\nexport function extractTablesRelationalConfig<\n\tTTables extends TablesRelationalConfig,\n>(\n\tschema: Record,\n\tconfigHelpers: (table: Table) => any,\n): { tables: TTables; tableNamesMap: Record } {\n\tif (\n\t\tObject.keys(schema).length === 1\n\t\t&& 'default' in schema\n\t\t&& !is(schema['default'], Table)\n\t) {\n\t\tschema = schema['default'] as Record;\n\t}\n\n\t// table DB name -> schema table key\n\tconst tableNamesMap: Record = {};\n\t// Table relations found before their tables - need to buffer them until we know the schema table key\n\tconst relationsBuffer: Record<\n\t\tstring,\n\t\t{ relations: Record; primaryKey?: AnyColumn[] }\n\t> = {};\n\tconst tablesConfig: TablesRelationalConfig = {};\n\tfor (const [key, value] of Object.entries(schema)) {\n\t\tif (is(value, Table)) {\n\t\t\tconst dbName = getTableUniqueName(value);\n\t\t\tconst bufferedRelations = relationsBuffer[dbName];\n\t\t\ttableNamesMap[dbName] = key;\n\t\t\ttablesConfig[key] = {\n\t\t\t\ttsName: key,\n\t\t\t\tdbName: value[Table.Symbol.Name],\n\t\t\t\tschema: value[Table.Symbol.Schema],\n\t\t\t\tcolumns: value[Table.Symbol.Columns],\n\t\t\t\trelations: bufferedRelations?.relations ?? {},\n\t\t\t\tprimaryKey: bufferedRelations?.primaryKey ?? [],\n\t\t\t};\n\n\t\t\t// Fill in primary keys\n\t\t\tfor (\n\t\t\t\tconst column of Object.values(\n\t\t\t\t\t(value as Table)[Table.Symbol.Columns],\n\t\t\t\t)\n\t\t\t) {\n\t\t\t\tif (column.primary) {\n\t\t\t\t\ttablesConfig[key]!.primaryKey.push(column);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst extraConfig = value[Table.Symbol.ExtraConfigBuilder]?.((value as Table)[Table.Symbol.ExtraConfigColumns]);\n\t\t\tif (extraConfig) {\n\t\t\t\tfor (const configEntry of Object.values(extraConfig)) {\n\t\t\t\t\tif (is(configEntry, PrimaryKeyBuilder)) {\n\t\t\t\t\t\ttablesConfig[key]!.primaryKey.push(...configEntry.columns);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t} else if (is(value, Relations)) {\n\t\t\tconst dbName = getTableUniqueName(value.table);\n\t\t\tconst tableName = tableNamesMap[dbName];\n\t\t\tconst relations: Record = value.config(\n\t\t\t\tconfigHelpers(value.table),\n\t\t\t);\n\t\t\tlet primaryKey: AnyColumn[] | undefined;\n\n\t\t\tfor (const [relationName, relation] of Object.entries(relations)) {\n\t\t\t\tif (tableName) {\n\t\t\t\t\tconst tableConfig = tablesConfig[tableName]!;\n\t\t\t\t\ttableConfig.relations[relationName] = relation;\n\t\t\t\t\tif (primaryKey) {\n\t\t\t\t\t\ttableConfig.primaryKey.push(...primaryKey);\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tif (!(dbName in relationsBuffer)) {\n\t\t\t\t\t\trelationsBuffer[dbName] = {\n\t\t\t\t\t\t\trelations: {},\n\t\t\t\t\t\t\tprimaryKey,\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t\trelationsBuffer[dbName]!.relations[relationName] = relation;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn { tables: tablesConfig as TTables, tableNamesMap };\n}\n\nexport function relations<\n\tTTableName extends string,\n\tTRelations extends Record>,\n>(\n\ttable: AnyTable<{ name: TTableName }>,\n\trelations: (helpers: TableRelationsHelpers) => TRelations,\n): Relations {\n\treturn new Relations(\n\t\ttable,\n\t\t(helpers: TableRelationsHelpers) =>\n\t\t\tObject.fromEntries(\n\t\t\t\tObject.entries(relations(helpers)).map(([key, value]) => [\n\t\t\t\t\tkey,\n\t\t\t\t\tvalue.withFieldName(key),\n\t\t\t\t]),\n\t\t\t) as TRelations,\n\t);\n}\n\nexport function createOne(sourceTable: Table) {\n\treturn function one<\n\t\tTForeignTable extends Table,\n\t\tTColumns extends [\n\t\t\tAnyColumn<{ tableName: TTableName }>,\n\t\t\t...AnyColumn<{ tableName: TTableName }>[],\n\t\t],\n\t>(\n\t\ttable: TForeignTable,\n\t\tconfig?: RelationConfig,\n\t): One<\n\t\tTForeignTable['_']['name'],\n\t\tEqual\n\t> {\n\t\treturn new One(\n\t\t\tsourceTable,\n\t\t\ttable,\n\t\t\tconfig,\n\t\t\t(config?.fields.reduce((res, f) => res && f.notNull, true)\n\t\t\t\t?? false) as Equal,\n\t\t);\n\t};\n}\n\nexport function createMany(sourceTable: Table) {\n\treturn function many(\n\t\treferencedTable: TForeignTable,\n\t\tconfig?: { relationName: string },\n\t): Many {\n\t\treturn new Many(sourceTable, referencedTable, config);\n\t};\n}\n\nexport interface NormalizedRelation {\n\tfields: AnyColumn[];\n\treferences: AnyColumn[];\n}\n\nexport function normalizeRelation(\n\tschema: TablesRelationalConfig,\n\ttableNamesMap: Record,\n\trelation: Relation,\n): NormalizedRelation {\n\tif (is(relation, One) && relation.config) {\n\t\treturn {\n\t\t\tfields: relation.config.fields,\n\t\t\treferences: relation.config.references,\n\t\t};\n\t}\n\n\tconst referencedTableTsName = tableNamesMap[getTableUniqueName(relation.referencedTable)];\n\tif (!referencedTableTsName) {\n\t\tthrow new Error(\n\t\t\t`Table \"${relation.referencedTable[Table.Symbol.Name]}\" not found in schema`,\n\t\t);\n\t}\n\n\tconst referencedTableConfig = schema[referencedTableTsName];\n\tif (!referencedTableConfig) {\n\t\tthrow new Error(`Table \"${referencedTableTsName}\" not found in schema`);\n\t}\n\n\tconst sourceTable = relation.sourceTable;\n\tconst sourceTableTsName = tableNamesMap[getTableUniqueName(sourceTable)];\n\tif (!sourceTableTsName) {\n\t\tthrow new Error(\n\t\t\t`Table \"${sourceTable[Table.Symbol.Name]}\" not found in schema`,\n\t\t);\n\t}\n\n\tconst reverseRelations: Relation[] = [];\n\tfor (\n\t\tconst referencedTableRelation of Object.values(\n\t\t\treferencedTableConfig.relations,\n\t\t)\n\t) {\n\t\tif (\n\t\t\t(relation.relationName\n\t\t\t\t&& relation !== referencedTableRelation\n\t\t\t\t&& referencedTableRelation.relationName === relation.relationName)\n\t\t\t|| (!relation.relationName\n\t\t\t\t&& referencedTableRelation.referencedTable === relation.sourceTable)\n\t\t) {\n\t\t\treverseRelations.push(referencedTableRelation);\n\t\t}\n\t}\n\n\tif (reverseRelations.length > 1) {\n\t\tthrow relation.relationName\n\t\t\t? new Error(\n\t\t\t\t`There are multiple relations with name \"${relation.relationName}\" in table \"${referencedTableTsName}\"`,\n\t\t\t)\n\t\t\t: new Error(\n\t\t\t\t`There are multiple relations between \"${referencedTableTsName}\" and \"${\n\t\t\t\t\trelation.sourceTable[Table.Symbol.Name]\n\t\t\t\t}\". Please specify relation name`,\n\t\t\t);\n\t}\n\n\tif (\n\t\treverseRelations[0]\n\t\t&& is(reverseRelations[0], One)\n\t\t&& reverseRelations[0].config\n\t) {\n\t\treturn {\n\t\t\tfields: reverseRelations[0].config.references,\n\t\t\treferences: reverseRelations[0].config.fields,\n\t\t};\n\t}\n\n\tthrow new Error(\n\t\t`There is not enough information to infer relation \"${sourceTableTsName}.${relation.fieldName}\"`,\n\t);\n}\n\nexport function createTableRelationsHelpers(\n\tsourceTable: AnyTable<{ name: TTableName }>,\n) {\n\treturn {\n\t\tone: createOne(sourceTable),\n\t\tmany: createMany(sourceTable),\n\t};\n}\n\nexport type TableRelationsHelpers = ReturnType<\n\ttypeof createTableRelationsHelpers\n>;\n\nexport interface BuildRelationalQueryResult<\n\tTTable extends Table = Table,\n\tTColumn extends Column = Column,\n> {\n\ttableTsKey: string;\n\tselection: {\n\t\tdbKey: string;\n\t\ttsKey: string;\n\t\tfield: TColumn | SQL | SQL.Aliased;\n\t\trelationTableTsKey: string | undefined;\n\t\tisJson: boolean;\n\t\tisExtra?: boolean;\n\t\tselection: BuildRelationalQueryResult['selection'];\n\t}[];\n\tsql: TTable | SQL;\n}\n\nexport function mapRelationalRow(\n\ttablesConfig: TablesRelationalConfig,\n\ttableConfig: TableRelationalConfig,\n\trow: unknown[],\n\tbuildQueryResultSelection: BuildRelationalQueryResult['selection'],\n\tmapColumnValue: (value: unknown) => unknown = (value) => value,\n): Record {\n\tconst result: Record = {};\n\n\tfor (\n\t\tconst [\n\t\t\tselectionItemIndex,\n\t\t\tselectionItem,\n\t\t] of buildQueryResultSelection.entries()\n\t) {\n\t\tif (selectionItem.isJson) {\n\t\t\tconst relation = tableConfig.relations[selectionItem.tsKey]!;\n\t\t\tconst rawSubRows = row[selectionItemIndex] as\n\t\t\t\t| unknown[]\n\t\t\t\t| null\n\t\t\t\t| [null]\n\t\t\t\t| string;\n\t\t\tconst subRows = typeof rawSubRows === 'string'\n\t\t\t\t? (JSON.parse(rawSubRows) as unknown[])\n\t\t\t\t: rawSubRows;\n\t\t\tresult[selectionItem.tsKey] = is(relation, One)\n\t\t\t\t? subRows\n\t\t\t\t\t&& mapRelationalRow(\n\t\t\t\t\t\ttablesConfig,\n\t\t\t\t\t\ttablesConfig[selectionItem.relationTableTsKey!]!,\n\t\t\t\t\t\tsubRows,\n\t\t\t\t\t\tselectionItem.selection,\n\t\t\t\t\t\tmapColumnValue,\n\t\t\t\t\t)\n\t\t\t\t: (subRows as unknown[][]).map((subRow) =>\n\t\t\t\t\tmapRelationalRow(\n\t\t\t\t\t\ttablesConfig,\n\t\t\t\t\t\ttablesConfig[selectionItem.relationTableTsKey!]!,\n\t\t\t\t\t\tsubRow,\n\t\t\t\t\t\tselectionItem.selection,\n\t\t\t\t\t\tmapColumnValue,\n\t\t\t\t\t)\n\t\t\t\t);\n\t\t} else {\n\t\t\tconst value = mapColumnValue(row[selectionItemIndex]);\n\t\t\tconst field = selectionItem.field!;\n\t\t\tlet decoder;\n\t\t\tif (is(field, Column)) {\n\t\t\t\tdecoder = field;\n\t\t\t} else if (is(field, SQL)) {\n\t\t\t\tdecoder = field.decoder;\n\t\t\t} else {\n\t\t\t\tdecoder = field.sql.decoder;\n\t\t\t}\n\t\t\tresult[selectionItem.tsKey] = value === null ? null : decoder.mapFromDriverValue(value);\n\t\t}\n\t}\n\n\treturn result;\n}\n", "import type { Column, GetColumnData } from './column.ts';\nimport { entityKind } from './entity.ts';\nimport type { OptionalKeyOnly, RequiredKeyOnly } from './operations.ts';\nimport type { SQLWrapper } from './sql/sql.ts';\nimport { TableName } from './table.utils.ts';\nimport type { Simplify, Update } from './utils.ts';\n\nexport interface TableConfig> {\n\tname: string;\n\tschema: string | undefined;\n\tcolumns: Record;\n\tdialect: string;\n}\n\nexport type UpdateTableConfig> = Required<\n\tUpdate\n>;\n\n/** @internal */\nexport const Schema = Symbol.for('drizzle:Schema');\n\n/** @internal */\nexport const Columns = Symbol.for('drizzle:Columns');\n\n/** @internal */\nexport const ExtraConfigColumns = Symbol.for('drizzle:ExtraConfigColumns');\n\n/** @internal */\nexport const OriginalName = Symbol.for('drizzle:OriginalName');\n\n/** @internal */\nexport const BaseName = Symbol.for('drizzle:BaseName');\n\n/** @internal */\nexport const IsAlias = Symbol.for('drizzle:IsAlias');\n\n/** @internal */\nexport const ExtraConfigBuilder = Symbol.for('drizzle:ExtraConfigBuilder');\n\nconst IsDrizzleTable = Symbol.for('drizzle:IsDrizzleTable');\n\nexport interface Table<\n\t// eslint-disable-next-line @typescript-eslint/no-unused-vars\n\tT extends TableConfig = TableConfig,\n> extends SQLWrapper {\n\t// SQLWrapper runtime implementation is defined in 'sql/sql.ts'\n}\n\nexport class Table implements SQLWrapper {\n\tstatic readonly [entityKind]: string = 'Table';\n\n\tdeclare readonly _: {\n\t\treadonly brand: 'Table';\n\t\treadonly config: T;\n\t\treadonly name: T['name'];\n\t\treadonly schema: T['schema'];\n\t\treadonly columns: T['columns'];\n\t\treadonly inferSelect: InferSelectModel>;\n\t\treadonly inferInsert: InferInsertModel>;\n\t};\n\n\tdeclare readonly $inferSelect: InferSelectModel>;\n\tdeclare readonly $inferInsert: InferInsertModel>;\n\n\t/** @internal */\n\tstatic readonly Symbol = {\n\t\tName: TableName as typeof TableName,\n\t\tSchema: Schema as typeof Schema,\n\t\tOriginalName: OriginalName as typeof OriginalName,\n\t\tColumns: Columns as typeof Columns,\n\t\tExtraConfigColumns: ExtraConfigColumns as typeof ExtraConfigColumns,\n\t\tBaseName: BaseName as typeof BaseName,\n\t\tIsAlias: IsAlias as typeof IsAlias,\n\t\tExtraConfigBuilder: ExtraConfigBuilder as typeof ExtraConfigBuilder,\n\t};\n\n\t/**\n\t * @internal\n\t * Can be changed if the table is aliased.\n\t */\n\t[TableName]: string;\n\n\t/**\n\t * @internal\n\t * Used to store the original name of the table, before any aliasing.\n\t */\n\t[OriginalName]: string;\n\n\t/** @internal */\n\t[Schema]: string | undefined;\n\n\t/** @internal */\n\t[Columns]!: T['columns'];\n\n\t/** @internal */\n\t[ExtraConfigColumns]!: Record;\n\n\t/**\n\t * @internal\n\t * Used to store the table name before the transformation via the `tableCreator` functions.\n\t */\n\t[BaseName]: string;\n\n\t/** @internal */\n\t[IsAlias] = false;\n\n\t/** @internal */\n\t[IsDrizzleTable] = true;\n\n\t/** @internal */\n\t[ExtraConfigBuilder]: ((self: any) => Record | unknown[]) | undefined = undefined;\n\n\tconstructor(name: string, schema: string | undefined, baseName: string) {\n\t\tthis[TableName] = this[OriginalName] = name;\n\t\tthis[Schema] = schema;\n\t\tthis[BaseName] = baseName;\n\t}\n}\n\nexport function isTable(table: unknown): table is Table {\n\treturn typeof table === 'object' && table !== null && IsDrizzleTable in table;\n}\n\n/**\n * Any table with a specified boundary.\n *\n * @example\n\t```ts\n\t// Any table with a specific name\n\ttype AnyUsersTable = AnyTable<{ name: 'users' }>;\n\t```\n *\n * To describe any table with any config, simply use `Table` without any type arguments, like this:\n *\n\t```ts\n\tfunction needsTable(table: Table) {\n\t\t...\n\t}\n\t```\n */\nexport type AnyTable> = Table>;\n\nexport function getTableName(table: T): T['_']['name'] {\n\treturn table[TableName];\n}\n\nexport function getTableUniqueName(table: T): `${T['_']['schema']}.${T['_']['name']}` {\n\treturn `${table[Schema] ?? 'public'}.${table[TableName]}`;\n}\n\nexport type MapColumnName =\n\tTDBColumNames extends true ? TColumn['_']['name']\n\t\t: TName;\n\nexport type InferModelFromColumns<\n\tTColumns extends Record,\n\tTInferMode extends 'select' | 'insert' = 'select',\n\tTConfig extends { dbColumnNames: boolean; override?: boolean } = { dbColumnNames: false; override: false },\n> = Simplify<\n\tTInferMode extends 'insert' ?\n\t\t\t& {\n\t\t\t\t[\n\t\t\t\t\tKey in keyof TColumns & string as RequiredKeyOnly<\n\t\t\t\t\t\tMapColumnName,\n\t\t\t\t\t\tTColumns[Key]\n\t\t\t\t\t>\n\t\t\t\t]: GetColumnData;\n\t\t\t}\n\t\t\t& {\n\t\t\t\t[\n\t\t\t\t\tKey in keyof TColumns & string as OptionalKeyOnly<\n\t\t\t\t\t\tMapColumnName,\n\t\t\t\t\t\tTColumns[Key],\n\t\t\t\t\t\tTConfig['override']\n\t\t\t\t\t>\n\t\t\t\t]?: GetColumnData | undefined;\n\t\t\t}\n\t\t: {\n\t\t\t[\n\t\t\t\tKey in keyof TColumns & string as MapColumnName<\n\t\t\t\t\tKey,\n\t\t\t\t\tTColumns[Key],\n\t\t\t\t\tTConfig['dbColumnNames']\n\t\t\t\t>\n\t\t\t]: GetColumnData;\n\t\t}\n>;\n\n/** @deprecated Use one of the alternatives: {@link InferSelectModel} / {@link InferInsertModel}, or `table.$inferSelect` / `table.$inferInsert`\n */\nexport type InferModel<\n\tTTable extends Table,\n\tTInferMode extends 'select' | 'insert' = 'select',\n\tTConfig extends { dbColumnNames: boolean } = { dbColumnNames: false },\n> = InferModelFromColumns;\n\nexport type InferSelectModel<\n\tTTable extends Table,\n\tTConfig extends { dbColumnNames: boolean } = { dbColumnNames: false },\n> = InferModelFromColumns;\n\nexport type InferInsertModel<\n\tTTable extends Table,\n\tTConfig extends { dbColumnNames: boolean; override?: boolean } = { dbColumnNames: false; override: false },\n> = InferModelFromColumns;\n\nexport type InferEnum = T extends { enumValues: readonly (infer U)[] } ? U\n\t: never;\n", "/** @internal */\nexport const TableName = Symbol.for('drizzle:Name');\n", "import type {\n\tColumnBuilderBaseConfig,\n\tColumnBuilderRuntimeConfig,\n\tColumnDataType,\n\tGeneratedColumnConfig,\n\tGeneratedIdentityConfig,\n} from './column-builder.ts';\nimport { entityKind } from './entity.ts';\nimport type { DriverValueMapper, SQL, SQLWrapper } from './sql/sql.ts';\nimport type { Table } from './table.ts';\nimport type { Update } from './utils.ts';\n\nexport interface ColumnBaseConfig<\n\tTDataType extends ColumnDataType,\n\tTColumnType extends string,\n> extends ColumnBuilderBaseConfig {\n\ttableName: string;\n\tnotNull: boolean;\n\thasDefault: boolean;\n\tisPrimaryKey: boolean;\n\tisAutoincrement: boolean;\n\thasRuntimeDefault: boolean;\n}\n\nexport type ColumnTypeConfig, TTypeConfig extends object> = T & {\n\tbrand: 'Column';\n\ttableName: T['tableName'];\n\tname: T['name'];\n\tdataType: T['dataType'];\n\tcolumnType: T['columnType'];\n\tdata: T['data'];\n\tdriverParam: T['driverParam'];\n\tnotNull: T['notNull'];\n\thasDefault: T['hasDefault'];\n\tisPrimaryKey: T['isPrimaryKey'];\n\tisAutoincrement: T['isAutoincrement'];\n\thasRuntimeDefault: T['hasRuntimeDefault'];\n\tenumValues: T['enumValues'];\n\tbaseColumn: T extends { baseColumn: infer U } ? U : unknown;\n\tgenerated: GeneratedColumnConfig | undefined;\n\tidentity: undefined | 'always' | 'byDefault';\n} & TTypeConfig;\n\nexport type ColumnRuntimeConfig = ColumnBuilderRuntimeConfig<\n\tTData,\n\tTRuntimeConfig\n>;\n\nexport interface Column<\n\tT extends ColumnBaseConfig = ColumnBaseConfig,\n\t// eslint-disable-next-line @typescript-eslint/no-unused-vars\n\tTRuntimeConfig extends object = object,\n\t// eslint-disable-next-line @typescript-eslint/no-unused-vars\n\tTTypeConfig extends object = object,\n> extends DriverValueMapper, SQLWrapper {\n\t// SQLWrapper runtime implementation is defined in 'sql/sql.ts'\n}\n/*\n\t`Column` only accepts a full `ColumnConfig` as its generic.\n\tTo infer parts of the config, use `AnyColumn` that accepts a partial config.\n\tSee `GetColumnData` for example usage of inferring.\n*/\nexport abstract class Column<\n\tT extends ColumnBaseConfig = ColumnBaseConfig,\n\tTRuntimeConfig extends object = object,\n\tTTypeConfig extends object = object,\n> implements DriverValueMapper, SQLWrapper {\n\tstatic readonly [entityKind]: string = 'Column';\n\n\tdeclare readonly _: ColumnTypeConfig;\n\n\treadonly name: string;\n\treadonly keyAsName: boolean;\n\treadonly primary: boolean;\n\treadonly notNull: boolean;\n\treadonly default: T['data'] | SQL | undefined;\n\treadonly defaultFn: (() => T['data'] | SQL) | undefined;\n\treadonly onUpdateFn: (() => T['data'] | SQL) | undefined;\n\treadonly hasDefault: boolean;\n\treadonly isUnique: boolean;\n\treadonly uniqueName: string | undefined;\n\treadonly uniqueType: string | undefined;\n\treadonly dataType: T['dataType'];\n\treadonly columnType: T['columnType'];\n\treadonly enumValues: T['enumValues'] = undefined;\n\treadonly generated: GeneratedColumnConfig | undefined = undefined;\n\treadonly generatedIdentity: GeneratedIdentityConfig | undefined = undefined;\n\n\tprotected config: ColumnRuntimeConfig;\n\n\tconstructor(\n\t\treadonly table: Table,\n\t\tconfig: ColumnRuntimeConfig,\n\t) {\n\t\tthis.config = config;\n\t\tthis.name = config.name;\n\t\tthis.keyAsName = config.keyAsName;\n\t\tthis.notNull = config.notNull;\n\t\tthis.default = config.default;\n\t\tthis.defaultFn = config.defaultFn;\n\t\tthis.onUpdateFn = config.onUpdateFn;\n\t\tthis.hasDefault = config.hasDefault;\n\t\tthis.primary = config.primaryKey;\n\t\tthis.isUnique = config.isUnique;\n\t\tthis.uniqueName = config.uniqueName;\n\t\tthis.uniqueType = config.uniqueType;\n\t\tthis.dataType = config.dataType as T['dataType'];\n\t\tthis.columnType = config.columnType;\n\t\tthis.generated = config.generated;\n\t\tthis.generatedIdentity = config.generatedIdentity;\n\t}\n\n\tabstract getSQLType(): string;\n\n\tmapFromDriverValue(value: unknown): unknown {\n\t\treturn value;\n\t}\n\n\tmapToDriverValue(value: unknown): unknown {\n\t\treturn value;\n\t}\n\n\t// ** @internal */\n\tshouldDisableInsert(): boolean {\n\t\treturn this.config.generated !== undefined && this.config.generated.type !== 'byDefault';\n\t}\n}\n\nexport type UpdateColConfig<\n\tT extends ColumnBaseConfig,\n\tTUpdate extends Partial>,\n> = Update;\n\nexport type AnyColumn> = {}> = Column<\n\tRequired, TPartial>>\n>;\n\nexport type GetColumnData =\n\t// dprint-ignore\n\tTInferMode extends 'raw' // Raw mode\n\t\t? TColumn['_']['data'] // Just return the underlying type\n\t\t: TColumn['_']['notNull'] extends true // Query mode\n\t\t? TColumn['_']['data'] // Query mode, not null\n\t\t: TColumn['_']['data'] | null; // Query mode, nullable\n\nexport type InferColumnsDataTypes> = {\n\t[Key in keyof TColumns]: GetColumnData;\n};\n", "import { entityKind } from '~/entity.ts';\nimport type { AnyPgColumn, PgColumn } from './columns/index.ts';\nimport { PgTable } from './table.ts';\n\nexport function primaryKey<\n\tTTableName extends string,\n\tTColumn extends AnyPgColumn<{ tableName: TTableName }>,\n\tTColumns extends AnyPgColumn<{ tableName: TTableName }>[],\n>(config: { name?: string; columns: [TColumn, ...TColumns] }): PrimaryKeyBuilder;\n/**\n * @deprecated: Please use primaryKey({ columns: [] }) instead of this function\n * @param columns\n */\nexport function primaryKey<\n\tTTableName extends string,\n\tTColumns extends AnyPgColumn<{ tableName: TTableName }>[],\n>(...columns: TColumns): PrimaryKeyBuilder;\nexport function primaryKey(...config: any) {\n\tif (config[0].columns) {\n\t\treturn new PrimaryKeyBuilder(config[0].columns, config[0].name);\n\t}\n\treturn new PrimaryKeyBuilder(config);\n}\n\nexport class PrimaryKeyBuilder {\n\tstatic readonly [entityKind]: string = 'PgPrimaryKeyBuilder';\n\n\t/** @internal */\n\tcolumns: PgColumn[];\n\n\t/** @internal */\n\tname?: string;\n\n\tconstructor(\n\t\tcolumns: PgColumn[],\n\t\tname?: string,\n\t) {\n\t\tthis.columns = columns;\n\t\tthis.name = name;\n\t}\n\n\t/** @internal */\n\tbuild(table: PgTable): PrimaryKey {\n\t\treturn new PrimaryKey(table, this.columns, this.name);\n\t}\n}\n\nexport class PrimaryKey {\n\tstatic readonly [entityKind]: string = 'PgPrimaryKey';\n\n\treadonly columns: AnyPgColumn<{}>[];\n\treadonly name?: string;\n\n\tconstructor(readonly table: PgTable, columns: AnyPgColumn<{}>[], name?: string) {\n\t\tthis.columns = columns;\n\t\tthis.name = name;\n\t}\n\n\tgetName(): string {\n\t\treturn this.name ?? `${this.table[PgTable.Symbol.Name]}_${this.columns.map((column) => column.name).join('_')}_pk`;\n\t}\n}\n", "import type { BuildColumns, BuildExtraConfigColumns } from '~/column-builder.ts';\nimport { entityKind } from '~/entity.ts';\nimport { Table, type TableConfig as TableConfigBase, type UpdateTableConfig } from '~/table.ts';\nimport type { CheckBuilder } from './checks.ts';\nimport { getPgColumnBuilders, type PgColumnsBuilders } from './columns/all.ts';\nimport type { ExtraConfigColumn, PgColumn, PgColumnBuilder, PgColumnBuilderBase } from './columns/common.ts';\nimport type { ForeignKey, ForeignKeyBuilder } from './foreign-keys.ts';\nimport type { AnyIndexBuilder } from './indexes.ts';\nimport type { PgPolicy } from './policies.ts';\nimport type { PrimaryKeyBuilder } from './primary-keys.ts';\nimport type { UniqueConstraintBuilder } from './unique-constraint.ts';\n\nexport type PgTableExtraConfigValue =\n\t| AnyIndexBuilder\n\t| CheckBuilder\n\t| ForeignKeyBuilder\n\t| PrimaryKeyBuilder\n\t| UniqueConstraintBuilder\n\t| PgPolicy;\n\nexport type PgTableExtraConfig = Record<\n\tstring,\n\tPgTableExtraConfigValue\n>;\n\nexport type TableConfig = TableConfigBase;\n\n/** @internal */\nexport const InlineForeignKeys = Symbol.for('drizzle:PgInlineForeignKeys');\n/** @internal */\nexport const EnableRLS = Symbol.for('drizzle:EnableRLS');\n\nexport class PgTable extends Table {\n\tstatic override readonly [entityKind]: string = 'PgTable';\n\n\t/** @internal */\n\tstatic override readonly Symbol = Object.assign({}, Table.Symbol, {\n\t\tInlineForeignKeys: InlineForeignKeys as typeof InlineForeignKeys,\n\t\tEnableRLS: EnableRLS as typeof EnableRLS,\n\t});\n\n\t/**@internal */\n\t[InlineForeignKeys]: ForeignKey[] = [];\n\n\t/** @internal */\n\t[EnableRLS]: boolean = false;\n\n\t/** @internal */\n\toverride [Table.Symbol.ExtraConfigBuilder]: ((self: Record) => PgTableExtraConfig) | undefined =\n\t\tundefined;\n\n\t/** @internal */\n\toverride [Table.Symbol.ExtraConfigColumns]: Record = {};\n}\n\nexport type AnyPgTable = {}> = PgTable>;\n\nexport type PgTableWithColumns =\n\t& PgTable\n\t& {\n\t\t[Key in keyof T['columns']]: T['columns'][Key];\n\t}\n\t& {\n\t\tenableRLS: () => Omit<\n\t\t\tPgTableWithColumns,\n\t\t\t'enableRLS'\n\t\t>;\n\t};\n\n/** @internal */\nexport function pgTableWithSchema<\n\tTTableName extends string,\n\tTSchemaName extends string | undefined,\n\tTColumnsMap extends Record,\n>(\n\tname: TTableName,\n\tcolumns: TColumnsMap | ((columnTypes: PgColumnsBuilders) => TColumnsMap),\n\textraConfig:\n\t\t| ((self: BuildExtraConfigColumns) => PgTableExtraConfig | PgTableExtraConfigValue[])\n\t\t| undefined,\n\tschema: TSchemaName,\n\tbaseName = name,\n): PgTableWithColumns<{\n\tname: TTableName;\n\tschema: TSchemaName;\n\tcolumns: BuildColumns;\n\tdialect: 'pg';\n}> {\n\tconst rawTable = new PgTable<{\n\t\tname: TTableName;\n\t\tschema: TSchemaName;\n\t\tcolumns: BuildColumns;\n\t\tdialect: 'pg';\n\t}>(name, schema, baseName);\n\n\tconst parsedColumns: TColumnsMap = typeof columns === 'function' ? columns(getPgColumnBuilders()) : columns;\n\n\tconst builtColumns = Object.fromEntries(\n\t\tObject.entries(parsedColumns).map(([name, colBuilderBase]) => {\n\t\t\tconst colBuilder = colBuilderBase as PgColumnBuilder;\n\t\t\tcolBuilder.setName(name);\n\t\t\tconst column = colBuilder.build(rawTable);\n\t\t\trawTable[InlineForeignKeys].push(...colBuilder.buildForeignKeys(column, rawTable));\n\t\t\treturn [name, column];\n\t\t}),\n\t) as unknown as BuildColumns;\n\n\tconst builtColumnsForExtraConfig = Object.fromEntries(\n\t\tObject.entries(parsedColumns).map(([name, colBuilderBase]) => {\n\t\t\tconst colBuilder = colBuilderBase as PgColumnBuilder;\n\t\t\tcolBuilder.setName(name);\n\t\t\tconst column = colBuilder.buildExtraConfigColumn(rawTable);\n\t\t\treturn [name, column];\n\t\t}),\n\t) as unknown as BuildExtraConfigColumns;\n\n\tconst table = Object.assign(rawTable, builtColumns);\n\n\ttable[Table.Symbol.Columns] = builtColumns;\n\ttable[Table.Symbol.ExtraConfigColumns] = builtColumnsForExtraConfig;\n\n\tif (extraConfig) {\n\t\ttable[PgTable.Symbol.ExtraConfigBuilder] = extraConfig as any;\n\t}\n\n\treturn Object.assign(table, {\n\t\tenableRLS: () => {\n\t\t\ttable[PgTable.Symbol.EnableRLS] = true;\n\t\t\treturn table as PgTableWithColumns<{\n\t\t\t\tname: TTableName;\n\t\t\t\tschema: TSchemaName;\n\t\t\t\tcolumns: BuildColumns;\n\t\t\t\tdialect: 'pg';\n\t\t\t}>;\n\t\t},\n\t});\n}\n\nexport interface PgTableFn {\n\t<\n\t\tTTableName extends string,\n\t\tTColumnsMap extends Record,\n\t>(\n\t\tname: TTableName,\n\t\tcolumns: TColumnsMap,\n\t\textraConfig?: (\n\t\t\tself: BuildExtraConfigColumns,\n\t\t) => PgTableExtraConfigValue[],\n\t): PgTableWithColumns<{\n\t\tname: TTableName;\n\t\tschema: TSchema;\n\t\tcolumns: BuildColumns;\n\t\tdialect: 'pg';\n\t}>;\n\n\t<\n\t\tTTableName extends string,\n\t\tTColumnsMap extends Record,\n\t>(\n\t\tname: TTableName,\n\t\tcolumns: (columnTypes: PgColumnsBuilders) => TColumnsMap,\n\t\textraConfig?: (self: BuildExtraConfigColumns) => PgTableExtraConfigValue[],\n\t): PgTableWithColumns<{\n\t\tname: TTableName;\n\t\tschema: TSchema;\n\t\tcolumns: BuildColumns;\n\t\tdialect: 'pg';\n\t}>;\n\t/**\n\t * @deprecated The third parameter of pgTable is changing and will only accept an array instead of an object\n\t *\n\t * @example\n\t * Deprecated version:\n\t * ```ts\n\t * export const users = pgTable(\"users\", {\n\t * \tid: integer(),\n\t * }, (t) => ({\n\t * \tidx: index('custom_name').on(t.id)\n\t * }));\n\t * ```\n\t *\n\t * New API:\n\t * ```ts\n\t * export const users = pgTable(\"users\", {\n\t * \tid: integer(),\n\t * }, (t) => [\n\t * \tindex('custom_name').on(t.id)\n\t * ]);\n\t * ```\n\t */\n\t<\n\t\tTTableName extends string,\n\t\tTColumnsMap extends Record,\n\t>(\n\t\tname: TTableName,\n\t\tcolumns: TColumnsMap,\n\t\textraConfig: (\n\t\t\tself: BuildExtraConfigColumns,\n\t\t) => PgTableExtraConfig,\n\t): PgTableWithColumns<{\n\t\tname: TTableName;\n\t\tschema: TSchema;\n\t\tcolumns: BuildColumns;\n\t\tdialect: 'pg';\n\t}>;\n\n\t/**\n\t * @deprecated The third parameter of pgTable is changing and will only accept an array instead of an object\n\t *\n\t * @example\n\t * Deprecated version:\n\t * ```ts\n\t * export const users = pgTable(\"users\", {\n\t * \tid: integer(),\n\t * }, (t) => ({\n\t * \tidx: index('custom_name').on(t.id)\n\t * }));\n\t * ```\n\t *\n\t * New API:\n\t * ```ts\n\t * export const users = pgTable(\"users\", {\n\t * \tid: integer(),\n\t * }, (t) => [\n\t * \tindex('custom_name').on(t.id)\n\t * ]);\n\t * ```\n\t */\n\t<\n\t\tTTableName extends string,\n\t\tTColumnsMap extends Record,\n\t>(\n\t\tname: TTableName,\n\t\tcolumns: (columnTypes: PgColumnsBuilders) => TColumnsMap,\n\t\textraConfig: (self: BuildExtraConfigColumns) => PgTableExtraConfig,\n\t): PgTableWithColumns<{\n\t\tname: TTableName;\n\t\tschema: TSchema;\n\t\tcolumns: BuildColumns;\n\t\tdialect: 'pg';\n\t}>;\n}\n\nexport const pgTable: PgTableFn = (name, columns, extraConfig) => {\n\treturn pgTableWithSchema(name, columns, extraConfig, undefined);\n};\n\nexport function pgTableCreator(customizeTableName: (name: string) => string): PgTableFn {\n\treturn (name, columns, extraConfig) => {\n\t\treturn pgTableWithSchema(customizeTableName(name) as typeof name, columns, extraConfig, undefined, name);\n\t};\n}\n", "import type { Cache } from './cache/core/cache.ts';\nimport type { AnyColumn } from './column.ts';\nimport { Column } from './column.ts';\nimport { is } from './entity.ts';\nimport type { Logger } from './logger.ts';\nimport type { SelectedFieldsOrdered } from './operations.ts';\nimport type { TableLike } from './query-builders/select.types.ts';\nimport { Param, SQL, View } from './sql/sql.ts';\nimport type { DriverValueDecoder } from './sql/sql.ts';\nimport { Subquery } from './subquery.ts';\nimport { getTableName, Table } from './table.ts';\nimport { ViewBaseConfig } from './view-common.ts';\n\n/** @internal */\nexport function mapResultRow(\n\tcolumns: SelectedFieldsOrdered,\n\trow: unknown[],\n\tjoinsNotNullableMap: Record | undefined,\n): TResult {\n\t// Key -> nested object key, value -> table name if all fields in the nested object are from the same table, false otherwise\n\tconst nullifyMap: Record = {};\n\n\tconst result = columns.reduce>(\n\t\t(result, { path, field }, columnIndex) => {\n\t\t\tlet decoder: DriverValueDecoder;\n\t\t\tif (is(field, Column)) {\n\t\t\t\tdecoder = field;\n\t\t\t} else if (is(field, SQL)) {\n\t\t\t\tdecoder = field.decoder;\n\t\t\t} else if (is(field, Subquery)) {\n\t\t\t\tdecoder = field._.sql.decoder;\n\t\t\t} else {\n\t\t\t\tdecoder = field.sql.decoder;\n\t\t\t}\n\t\t\tlet node = result;\n\t\t\tfor (const [pathChunkIndex, pathChunk] of path.entries()) {\n\t\t\t\tif (pathChunkIndex < path.length - 1) {\n\t\t\t\t\tif (!(pathChunk in node)) {\n\t\t\t\t\t\tnode[pathChunk] = {};\n\t\t\t\t\t}\n\t\t\t\t\tnode = node[pathChunk];\n\t\t\t\t} else {\n\t\t\t\t\tconst rawValue = row[columnIndex]!;\n\t\t\t\t\tconst value = node[pathChunk] = rawValue === null ? null : decoder.mapFromDriverValue(rawValue);\n\n\t\t\t\t\tif (joinsNotNullableMap && is(field, Column) && path.length === 2) {\n\t\t\t\t\t\tconst objectName = path[0]!;\n\t\t\t\t\t\tif (!(objectName in nullifyMap)) {\n\t\t\t\t\t\t\tnullifyMap[objectName] = value === null ? getTableName(field.table) : false;\n\t\t\t\t\t\t} else if (\n\t\t\t\t\t\t\ttypeof nullifyMap[objectName] === 'string' && nullifyMap[objectName] !== getTableName(field.table)\n\t\t\t\t\t\t) {\n\t\t\t\t\t\t\tnullifyMap[objectName] = false;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn result;\n\t\t},\n\t\t{},\n\t);\n\n\t// Nullify all nested objects from nullifyMap that are nullable\n\tif (joinsNotNullableMap && Object.keys(nullifyMap).length > 0) {\n\t\tfor (const [objectName, tableName] of Object.entries(nullifyMap)) {\n\t\t\tif (typeof tableName === 'string' && !joinsNotNullableMap[tableName]) {\n\t\t\t\tresult[objectName] = null;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn result as TResult;\n}\n\n/** @internal */\nexport function orderSelectedFields(\n\tfields: Record,\n\tpathPrefix?: string[],\n): SelectedFieldsOrdered {\n\treturn Object.entries(fields).reduce>((result, [name, field]) => {\n\t\tif (typeof name !== 'string') {\n\t\t\treturn result;\n\t\t}\n\n\t\tconst newPath = pathPrefix ? [...pathPrefix, name] : [name];\n\t\tif (is(field, Column) || is(field, SQL) || is(field, SQL.Aliased) || is(field, Subquery)) {\n\t\t\tresult.push({ path: newPath, field });\n\t\t} else if (is(field, Table)) {\n\t\t\tresult.push(...orderSelectedFields(field[Table.Symbol.Columns], newPath));\n\t\t} else {\n\t\t\tresult.push(...orderSelectedFields(field as Record, newPath));\n\t\t}\n\t\treturn result;\n\t}, []) as SelectedFieldsOrdered;\n}\n\nexport function haveSameKeys(left: Record, right: Record) {\n\tconst leftKeys = Object.keys(left);\n\tconst rightKeys = Object.keys(right);\n\n\tif (leftKeys.length !== rightKeys.length) {\n\t\treturn false;\n\t}\n\n\tfor (const [index, key] of leftKeys.entries()) {\n\t\tif (key !== rightKeys[index]) {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\treturn true;\n}\n\n/** @internal */\nexport function mapUpdateSet(table: Table, values: Record): UpdateSet {\n\tconst entries: [string, UpdateSet[string]][] = Object.entries(values)\n\t\t.filter(([, value]) => value !== undefined)\n\t\t.map(([key, value]) => {\n\t\t\t// eslint-disable-next-line unicorn/prefer-ternary\n\t\t\tif (is(value, SQL) || is(value, Column)) {\n\t\t\t\treturn [key, value];\n\t\t\t} else {\n\t\t\t\treturn [key, new Param(value, table[Table.Symbol.Columns][key])];\n\t\t\t}\n\t\t});\n\n\tif (entries.length === 0) {\n\t\tthrow new Error('No values to set');\n\t}\n\n\treturn Object.fromEntries(entries);\n}\n\nexport type UpdateSet = Record;\n\nexport type OneOrMany = T | T[];\n\nexport type Update =\n\t& {\n\t\t[K in Exclude]: T[K];\n\t}\n\t& TUpdate;\n\nexport type Simplify =\n\t& {\n\t\t// @ts-ignore - \"Type parameter 'K' has a circular constraint\", not sure why\n\t\t[K in keyof T]: T[K];\n\t}\n\t& {};\n\nexport type Not = T extends true ? false : true;\n\nexport type IsNever = [T] extends [never] ? true : false;\n\nexport type IsUnion = (T extends any ? (U extends T ? false : true) : never) extends false ? false\n\t: true;\n\nexport type SingleKeyObject = IsNever extends true ? never\n\t: IsUnion extends true ? DrizzleTypeError\n\t: T;\n\nexport type FromSingleKeyObject = IsNever extends true ? never\n\t: IsUnion extends true ? DrizzleTypeError\n\t: Result;\n\nexport type SimplifyMappedType = [T] extends [unknown] ? T : never;\n\nexport type ShallowRecord = SimplifyMappedType<{ [P in K]: T }>;\n\nexport type Assume = T extends U ? T : U;\n\nexport type Equal = (() => T extends X ? 1 : 2) extends (() => T extends Y ? 1 : 2) ? true : false;\n\nexport interface DrizzleTypeError {\n\t$drizzleTypeError: T;\n}\n\nexport type ValueOrArray = T | T[];\n\n/** @internal */\nexport function applyMixins(baseClass: any, extendedClasses: any[]) {\n\tfor (const extendedClass of extendedClasses) {\n\t\tfor (const name of Object.getOwnPropertyNames(extendedClass.prototype)) {\n\t\t\tif (name === 'constructor') continue;\n\n\t\t\tObject.defineProperty(\n\t\t\t\tbaseClass.prototype,\n\t\t\t\tname,\n\t\t\t\tObject.getOwnPropertyDescriptor(extendedClass.prototype, name) || Object.create(null),\n\t\t\t);\n\t\t}\n\t}\n}\n\nexport type Or = T1 extends true ? true : T2 extends true ? true : false;\n\nexport type IfThenElse = If extends true ? Then : Else;\n\nexport type PromiseOf = T extends Promise ? U : T;\n\nexport type Writable = {\n\t-readonly [P in keyof T]: T[P];\n};\n\nexport type NonArray = T extends any[] ? never : T;\n\nexport function getTableColumns(table: T): T['_']['columns'] {\n\treturn table[Table.Symbol.Columns];\n}\n\nexport function getViewSelectedFields(view: T): T['_']['selectedFields'] {\n\treturn view[ViewBaseConfig].selectedFields;\n}\n\n/** @internal */\nexport function getTableLikeName(table: TableLike): string | undefined {\n\treturn is(table, Subquery)\n\t\t? table._.alias\n\t\t: is(table, View)\n\t\t? table[ViewBaseConfig].name\n\t\t: is(table, SQL)\n\t\t? undefined\n\t\t: table[Table.Symbol.IsAlias]\n\t\t? table[Table.Symbol.Name]\n\t\t: table[Table.Symbol.BaseName];\n}\n\nexport type ColumnsWithTable<\n\tTTableName extends string,\n\tTForeignTableName extends string,\n\tTColumns extends AnyColumn<{ tableName: TTableName }>[],\n> = { [Key in keyof TColumns]: AnyColumn<{ tableName: TForeignTableName }> };\n\nexport type Casing = 'snake_case' | 'camelCase';\n\nexport interface DrizzleConfig = Record> {\n\tlogger?: boolean | Logger;\n\tschema?: TSchema;\n\tcasing?: Casing;\n\tcache?: Cache;\n}\nexport type ValidateShape = T extends ValidShape\n\t? Exclude extends never ? TResult\n\t: DrizzleTypeError<\n\t\t`Invalid key(s): ${Exclude<(keyof T) & (string | number | bigint | boolean | null | undefined), keyof ValidShape>}`\n\t>\n\t: never;\n\nexport type KnownKeysOnly = {\n\t[K in keyof T]: K extends keyof U ? T[K] : never;\n};\n\nexport type IsAny = 0 extends (1 & T) ? true : false;\n\n/** @internal */\nexport function getColumnNameAndConfig<\n\tTConfig extends Record | undefined,\n>(a: string | TConfig | undefined, b: TConfig | undefined) {\n\treturn {\n\t\tname: typeof a === 'string' && a.length > 0 ? a : '' as string,\n\t\tconfig: typeof a === 'object' ? a : b as TConfig,\n\t};\n}\n\nexport type IfNotImported = unknown extends T ? Y : N;\n\nexport type ImportTypeError =\n\t`Please install \\`${TPackageName}\\` to allow Drizzle ORM to connect to the database`;\n\nexport type RequireAtLeastOne = Keys extends any\n\t? Required> & Partial>\n\t: never;\n\ntype ExpectedConfigShape = {\n\tlogger?: boolean | {\n\t\tlogQuery(query: string, params: unknown[]): void;\n\t};\n\tschema?: Record;\n\tcasing?: 'snake_case' | 'camelCase';\n};\n\n// If this errors, you must update config shape checker function with new config specs\nconst _: DrizzleConfig = {} as ExpectedConfigShape;\nconst __: ExpectedConfigShape = {} as DrizzleConfig;\n\nexport function isConfig(data: any): boolean {\n\tif (typeof data !== 'object' || data === null) return false;\n\n\tif (data.constructor.name !== 'Object') return false;\n\n\tif ('logger' in data) {\n\t\tconst type = typeof data['logger'];\n\t\tif (\n\t\t\ttype !== 'boolean' && (type !== 'object' || typeof data['logger']['logQuery'] !== 'function')\n\t\t\t&& type !== 'undefined'\n\t\t) return false;\n\n\t\treturn true;\n\t}\n\n\tif ('schema' in data) {\n\t\tconst type = typeof data['schema'];\n\t\tif (type !== 'object' && type !== 'undefined') return false;\n\n\t\treturn true;\n\t}\n\n\tif ('casing' in data) {\n\t\tconst type = typeof data['casing'];\n\t\tif (type !== 'string' && type !== 'undefined') return false;\n\n\t\treturn true;\n\t}\n\n\tif ('mode' in data) {\n\t\tif (data['mode'] !== 'default' || data['mode'] !== 'planetscale' || data['mode'] !== undefined) return false;\n\n\t\treturn true;\n\t}\n\n\tif ('connection' in data) {\n\t\tconst type = typeof data['connection'];\n\t\tif (type !== 'string' && type !== 'object' && type !== 'undefined') return false;\n\n\t\treturn true;\n\t}\n\n\tif ('client' in data) {\n\t\tconst type = typeof data['client'];\n\t\tif (type !== 'object' && type !== 'function' && type !== 'undefined') return false;\n\n\t\treturn true;\n\t}\n\n\tif (Object.keys(data).length === 0) return true;\n\n\treturn false;\n}\n\nexport type NeonAuthToken = string | (() => string | Promise);\n\nexport const textDecoder = typeof TextDecoder === 'undefined' ? null : new TextDecoder();\n", "import type { CasingCache } from '~/casing.ts';\nimport { entityKind, is } from '~/entity.ts';\nimport { isPgEnum } from '~/pg-core/columns/enum.ts';\nimport type { SelectResult } from '~/query-builders/select.types.ts';\nimport { Subquery } from '~/subquery.ts';\nimport { tracer } from '~/tracing.ts';\nimport type { Assume, Equal } from '~/utils.ts';\nimport { ViewBaseConfig } from '~/view-common.ts';\nimport type { AnyColumn } from '../column.ts';\nimport { Column } from '../column.ts';\nimport { IsAlias, Table } from '../table.ts';\n\n/**\n * This class is used to indicate a primitive param value that is used in `sql` tag.\n * It is only used on type level and is never instantiated at runtime.\n * If you see a value of this type in the code, its runtime value is actually the primitive param value.\n */\nexport class FakePrimitiveParam {\n\tstatic readonly [entityKind]: string = 'FakePrimitiveParam';\n}\n\nexport type Chunk =\n\t| string\n\t| Table\n\t| View\n\t| AnyColumn\n\t| Name\n\t| Param\n\t| Placeholder\n\t| SQL;\n\nexport interface BuildQueryConfig {\n\tcasing: CasingCache;\n\tescapeName(name: string): string;\n\tescapeParam(num: number, value: unknown): string;\n\tescapeString(str: string): string;\n\tprepareTyping?: (encoder: DriverValueEncoder) => QueryTypingsValue;\n\tparamStartIndex?: { value: number };\n\tinlineParams?: boolean;\n\tinvokeSource?: 'indexes' | undefined;\n}\n\nexport type QueryTypingsValue = 'json' | 'decimal' | 'time' | 'timestamp' | 'uuid' | 'date' | 'none';\n\nexport interface Query {\n\tsql: string;\n\tparams: unknown[];\n}\n\nexport interface QueryWithTypings extends Query {\n\ttypings?: QueryTypingsValue[];\n}\n\n/**\n * Any value that implements the `getSQL` method. The implementations include:\n * - `Table`\n * - `Column`\n * - `View`\n * - `Subquery`\n * - `SQL`\n * - `SQL.Aliased`\n * - `Placeholder`\n * - `Param`\n */\nexport interface SQLWrapper {\n\tgetSQL(): SQL;\n\tshouldOmitSQLParens?(): boolean;\n}\n\nexport function isSQLWrapper(value: unknown): value is SQLWrapper {\n\treturn value !== null && value !== undefined && typeof (value as any).getSQL === 'function';\n}\n\nfunction mergeQueries(queries: QueryWithTypings[]): QueryWithTypings {\n\tconst result: QueryWithTypings = { sql: '', params: [] };\n\tfor (const query of queries) {\n\t\tresult.sql += query.sql;\n\t\tresult.params.push(...query.params);\n\t\tif (query.typings?.length) {\n\t\t\tif (!result.typings) {\n\t\t\t\tresult.typings = [];\n\t\t\t}\n\t\t\tresult.typings.push(...query.typings);\n\t\t}\n\t}\n\treturn result;\n}\n\nexport class StringChunk implements SQLWrapper {\n\tstatic readonly [entityKind]: string = 'StringChunk';\n\n\treadonly value: string[];\n\n\tconstructor(value: string | string[]) {\n\t\tthis.value = Array.isArray(value) ? value : [value];\n\t}\n\n\tgetSQL(): SQL {\n\t\treturn new SQL([this]);\n\t}\n}\n\nexport class SQL implements SQLWrapper {\n\tstatic readonly [entityKind]: string = 'SQL';\n\n\tdeclare _: {\n\t\tbrand: 'SQL';\n\t\ttype: T;\n\t};\n\n\t/** @internal */\n\tdecoder: DriverValueDecoder = noopDecoder;\n\tprivate shouldInlineParams = false;\n\n\t/** @internal */\n\tusedTables: string[] = [];\n\n\tconstructor(readonly queryChunks: SQLChunk[]) {\n\t\tfor (const chunk of queryChunks) {\n\t\t\tif (is(chunk, Table)) {\n\t\t\t\tconst schemaName = chunk[Table.Symbol.Schema];\n\n\t\t\t\tthis.usedTables.push(\n\t\t\t\t\tschemaName === undefined\n\t\t\t\t\t\t? chunk[Table.Symbol.Name]\n\t\t\t\t\t\t: schemaName + '.' + chunk[Table.Symbol.Name],\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\n\tappend(query: SQL): this {\n\t\tthis.queryChunks.push(...query.queryChunks);\n\t\treturn this;\n\t}\n\n\ttoQuery(config: BuildQueryConfig): QueryWithTypings {\n\t\treturn tracer.startActiveSpan('drizzle.buildSQL', (span) => {\n\t\t\tconst query = this.buildQueryFromSourceParams(this.queryChunks, config);\n\t\t\tspan?.setAttributes({\n\t\t\t\t'drizzle.query.text': query.sql,\n\t\t\t\t'drizzle.query.params': JSON.stringify(query.params),\n\t\t\t});\n\t\t\treturn query;\n\t\t});\n\t}\n\n\tbuildQueryFromSourceParams(chunks: SQLChunk[], _config: BuildQueryConfig): Query {\n\t\tconst config = Object.assign({}, _config, {\n\t\t\tinlineParams: _config.inlineParams || this.shouldInlineParams,\n\t\t\tparamStartIndex: _config.paramStartIndex || { value: 0 },\n\t\t});\n\n\t\tconst {\n\t\t\tcasing,\n\t\t\tescapeName,\n\t\t\tescapeParam,\n\t\t\tprepareTyping,\n\t\t\tinlineParams,\n\t\t\tparamStartIndex,\n\t\t} = config;\n\n\t\treturn mergeQueries(chunks.map((chunk): QueryWithTypings => {\n\t\t\tif (is(chunk, StringChunk)) {\n\t\t\t\treturn { sql: chunk.value.join(''), params: [] };\n\t\t\t}\n\n\t\t\tif (is(chunk, Name)) {\n\t\t\t\treturn { sql: escapeName(chunk.value), params: [] };\n\t\t\t}\n\n\t\t\tif (chunk === undefined) {\n\t\t\t\treturn { sql: '', params: [] };\n\t\t\t}\n\n\t\t\tif (Array.isArray(chunk)) {\n\t\t\t\tconst result: SQLChunk[] = [new StringChunk('(')];\n\t\t\t\tfor (const [i, p] of chunk.entries()) {\n\t\t\t\t\tresult.push(p);\n\t\t\t\t\tif (i < chunk.length - 1) {\n\t\t\t\t\t\tresult.push(new StringChunk(', '));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tresult.push(new StringChunk(')'));\n\t\t\t\treturn this.buildQueryFromSourceParams(result, config);\n\t\t\t}\n\n\t\t\tif (is(chunk, SQL)) {\n\t\t\t\treturn this.buildQueryFromSourceParams(chunk.queryChunks, {\n\t\t\t\t\t...config,\n\t\t\t\t\tinlineParams: inlineParams || chunk.shouldInlineParams,\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tif (is(chunk, Table)) {\n\t\t\t\tconst schemaName = chunk[Table.Symbol.Schema];\n\t\t\t\tconst tableName = chunk[Table.Symbol.Name];\n\t\t\t\treturn {\n\t\t\t\t\tsql: schemaName === undefined || chunk[IsAlias]\n\t\t\t\t\t\t? escapeName(tableName)\n\t\t\t\t\t\t: escapeName(schemaName) + '.' + escapeName(tableName),\n\t\t\t\t\tparams: [],\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tif (is(chunk, Column)) {\n\t\t\t\tconst columnName = casing.getColumnCasing(chunk);\n\t\t\t\tif (_config.invokeSource === 'indexes') {\n\t\t\t\t\treturn { sql: escapeName(columnName), params: [] };\n\t\t\t\t}\n\n\t\t\t\tconst schemaName = chunk.table[Table.Symbol.Schema];\n\t\t\t\treturn {\n\t\t\t\t\tsql: chunk.table[IsAlias] || schemaName === undefined\n\t\t\t\t\t\t? escapeName(chunk.table[Table.Symbol.Name]) + '.' + escapeName(columnName)\n\t\t\t\t\t\t: escapeName(schemaName) + '.' + escapeName(chunk.table[Table.Symbol.Name]) + '.'\n\t\t\t\t\t\t\t+ escapeName(columnName),\n\t\t\t\t\tparams: [],\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tif (is(chunk, View)) {\n\t\t\t\tconst schemaName = chunk[ViewBaseConfig].schema;\n\t\t\t\tconst viewName = chunk[ViewBaseConfig].name;\n\t\t\t\treturn {\n\t\t\t\t\tsql: schemaName === undefined || chunk[ViewBaseConfig].isAlias\n\t\t\t\t\t\t? escapeName(viewName)\n\t\t\t\t\t\t: escapeName(schemaName) + '.' + escapeName(viewName),\n\t\t\t\t\tparams: [],\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tif (is(chunk, Param)) {\n\t\t\t\tif (is(chunk.value, Placeholder)) {\n\t\t\t\t\treturn { sql: escapeParam(paramStartIndex.value++, chunk), params: [chunk], typings: ['none'] };\n\t\t\t\t}\n\n\t\t\t\tconst mappedValue = chunk.value === null ? null : chunk.encoder.mapToDriverValue(chunk.value);\n\n\t\t\t\tif (is(mappedValue, SQL)) {\n\t\t\t\t\treturn this.buildQueryFromSourceParams([mappedValue], config);\n\t\t\t\t}\n\n\t\t\t\tif (inlineParams) {\n\t\t\t\t\treturn { sql: this.mapInlineParam(mappedValue, config), params: [] };\n\t\t\t\t}\n\n\t\t\t\tlet typings: QueryTypingsValue[] = ['none'];\n\t\t\t\tif (prepareTyping) {\n\t\t\t\t\ttypings = [prepareTyping(chunk.encoder)];\n\t\t\t\t}\n\n\t\t\t\treturn { sql: escapeParam(paramStartIndex.value++, mappedValue), params: [mappedValue], typings };\n\t\t\t}\n\n\t\t\tif (is(chunk, Placeholder)) {\n\t\t\t\treturn { sql: escapeParam(paramStartIndex.value++, chunk), params: [chunk], typings: ['none'] };\n\t\t\t}\n\n\t\t\tif (is(chunk, SQL.Aliased) && chunk.fieldAlias !== undefined) {\n\t\t\t\treturn { sql: escapeName(chunk.fieldAlias), params: [] };\n\t\t\t}\n\n\t\t\tif (is(chunk, Subquery)) {\n\t\t\t\tif (chunk._.isWith) {\n\t\t\t\t\treturn { sql: escapeName(chunk._.alias), params: [] };\n\t\t\t\t}\n\t\t\t\treturn this.buildQueryFromSourceParams([\n\t\t\t\t\tnew StringChunk('('),\n\t\t\t\t\tchunk._.sql,\n\t\t\t\t\tnew StringChunk(') '),\n\t\t\t\t\tnew Name(chunk._.alias),\n\t\t\t\t], config);\n\t\t\t}\n\n\t\t\tif (isPgEnum(chunk)) {\n\t\t\t\tif (chunk.schema) {\n\t\t\t\t\treturn { sql: escapeName(chunk.schema) + '.' + escapeName(chunk.enumName), params: [] };\n\t\t\t\t}\n\t\t\t\treturn { sql: escapeName(chunk.enumName), params: [] };\n\t\t\t}\n\n\t\t\tif (isSQLWrapper(chunk)) {\n\t\t\t\tif (chunk.shouldOmitSQLParens?.()) {\n\t\t\t\t\treturn this.buildQueryFromSourceParams([chunk.getSQL()], config);\n\t\t\t\t}\n\t\t\t\treturn this.buildQueryFromSourceParams([\n\t\t\t\t\tnew StringChunk('('),\n\t\t\t\t\tchunk.getSQL(),\n\t\t\t\t\tnew StringChunk(')'),\n\t\t\t\t], config);\n\t\t\t}\n\n\t\t\tif (inlineParams) {\n\t\t\t\treturn { sql: this.mapInlineParam(chunk, config), params: [] };\n\t\t\t}\n\n\t\t\treturn { sql: escapeParam(paramStartIndex.value++, chunk), params: [chunk], typings: ['none'] };\n\t\t}));\n\t}\n\n\tprivate mapInlineParam(\n\t\tchunk: unknown,\n\t\t{ escapeString }: BuildQueryConfig,\n\t): string {\n\t\tif (chunk === null) {\n\t\t\treturn 'null';\n\t\t}\n\t\tif (typeof chunk === 'number' || typeof chunk === 'boolean') {\n\t\t\treturn chunk.toString();\n\t\t}\n\t\tif (typeof chunk === 'string') {\n\t\t\treturn escapeString(chunk);\n\t\t}\n\t\tif (typeof chunk === 'object') {\n\t\t\tconst mappedValueAsString = chunk.toString();\n\t\t\tif (mappedValueAsString === '[object Object]') {\n\t\t\t\treturn escapeString(JSON.stringify(chunk));\n\t\t\t}\n\t\t\treturn escapeString(mappedValueAsString);\n\t\t}\n\t\tthrow new Error('Unexpected param value: ' + chunk);\n\t}\n\n\tgetSQL(): SQL {\n\t\treturn this;\n\t}\n\n\tas(alias: string): SQL.Aliased;\n\t/**\n\t * @deprecated\n\t * Use ``sql`query`.as(alias)`` instead.\n\t */\n\tas(): SQL;\n\t/**\n\t * @deprecated\n\t * Use ``sql`query`.as(alias)`` instead.\n\t */\n\tas(alias: string): SQL.Aliased;\n\tas(alias?: string): SQL | SQL.Aliased {\n\t\t// TODO: remove with deprecated overloads\n\t\tif (alias === undefined) {\n\t\t\treturn this;\n\t\t}\n\n\t\treturn new SQL.Aliased(this, alias);\n\t}\n\n\tmapWith<\n\t\tTDecoder extends\n\t\t\t| DriverValueDecoder\n\t\t\t| DriverValueDecoder['mapFromDriverValue'],\n\t>(decoder: TDecoder): SQL> {\n\t\tthis.decoder = typeof decoder === 'function' ? { mapFromDriverValue: decoder } : decoder;\n\t\treturn this as SQL>;\n\t}\n\n\tinlineParams(): this {\n\t\tthis.shouldInlineParams = true;\n\t\treturn this;\n\t}\n\n\t/**\n\t * This method is used to conditionally include a part of the query.\n\t *\n\t * @param condition - Condition to check\n\t * @returns itself if the condition is `true`, otherwise `undefined`\n\t */\n\tif(condition: any | undefined): this | undefined {\n\t\treturn condition ? this : undefined;\n\t}\n}\n\nexport type GetDecoderResult = T extends Column ? T['_']['data'] : T extends\n\t| DriverValueDecoder\n\t| DriverValueDecoder['mapFromDriverValue'] ? TData\n: never;\n\n/**\n * Any DB name (table, column, index etc.)\n */\nexport class Name implements SQLWrapper {\n\tstatic readonly [entityKind]: string = 'Name';\n\n\tprotected brand!: 'Name';\n\n\tconstructor(readonly value: string) {}\n\n\tgetSQL(): SQL {\n\t\treturn new SQL([this]);\n\t}\n}\n\n/**\n * Any DB name (table, column, index etc.)\n * @deprecated Use `sql.identifier` instead.\n */\nexport function name(value: string): Name {\n\treturn new Name(value);\n}\n\nexport interface DriverValueDecoder {\n\tmapFromDriverValue(value: TDriverParam): TData;\n}\n\nexport interface DriverValueEncoder {\n\tmapToDriverValue(value: TData): TDriverParam | SQL;\n}\n\nexport function isDriverValueEncoder(value: unknown): value is DriverValueEncoder {\n\treturn typeof value === 'object' && value !== null && 'mapToDriverValue' in value\n\t\t&& typeof (value as any).mapToDriverValue === 'function';\n}\n\nexport const noopDecoder: DriverValueDecoder = {\n\tmapFromDriverValue: (value) => value,\n};\n\nexport const noopEncoder: DriverValueEncoder = {\n\tmapToDriverValue: (value) => value,\n};\n\nexport interface DriverValueMapper\n\textends DriverValueDecoder, DriverValueEncoder\n{}\n\nexport const noopMapper: DriverValueMapper = {\n\t...noopDecoder,\n\t...noopEncoder,\n};\n\n/** Parameter value that is optionally bound to an encoder (for example, a column). */\nexport class Param implements SQLWrapper {\n\tstatic readonly [entityKind]: string = 'Param';\n\n\tprotected brand!: 'BoundParamValue';\n\n\t/**\n\t * @param value - Parameter value\n\t * @param encoder - Encoder to convert the value to a driver parameter\n\t */\n\tconstructor(\n\t\treadonly value: TDataType,\n\t\treadonly encoder: DriverValueEncoder = noopEncoder,\n\t) {}\n\n\tgetSQL(): SQL {\n\t\treturn new SQL([this]);\n\t}\n}\n\n/** @deprecated Use `sql.param` instead. */\nexport function param(\n\tvalue: TData,\n\tencoder?: DriverValueEncoder,\n): Param {\n\treturn new Param(value, encoder);\n}\n\n/**\n * Anything that can be passed to the `` sql`...` `` tagged function.\n */\nexport type SQLChunk =\n\t| StringChunk\n\t| SQLChunk[]\n\t| SQLWrapper\n\t| SQL\n\t| Table\n\t| View\n\t| Subquery\n\t| AnyColumn\n\t| Param\n\t| Name\n\t| undefined\n\t| FakePrimitiveParam\n\t| Placeholder;\n\nexport function sql(strings: TemplateStringsArray, ...params: any[]): SQL;\n/*\n\tThe type of `params` is specified as `SQLChunk[]`, but that's slightly incorrect -\n\tin runtime, users won't pass `FakePrimitiveParam` instances as `params` - they will pass primitive values\n\twhich will be wrapped in `Param`. That's why the overload specifies `params` as `any[]` and not as `SQLSourceParam[]`.\n\tThis type is used to make our lives easier and the type checker happy.\n*/\nexport function sql(strings: TemplateStringsArray, ...params: SQLChunk[]): SQL {\n\tconst queryChunks: SQLChunk[] = [];\n\tif (params.length > 0 || (strings.length > 0 && strings[0] !== '')) {\n\t\tqueryChunks.push(new StringChunk(strings[0]!));\n\t}\n\tfor (const [paramIndex, param] of params.entries()) {\n\t\tqueryChunks.push(param, new StringChunk(strings[paramIndex + 1]!));\n\t}\n\n\treturn new SQL(queryChunks);\n}\n\nexport namespace sql {\n\texport function empty(): SQL {\n\t\treturn new SQL([]);\n\t}\n\n\t/** @deprecated - use `sql.join()` */\n\texport function fromList(list: SQLChunk[]): SQL {\n\t\treturn new SQL(list);\n\t}\n\n\t/**\n\t * Convenience function to create an SQL query from a raw string.\n\t * @param str The raw SQL query string.\n\t */\n\texport function raw(str: string): SQL {\n\t\treturn new SQL([new StringChunk(str)]);\n\t}\n\n\t/**\n\t * Join a list of SQL chunks with a separator.\n\t * @example\n\t * ```ts\n\t * const query = sql.join([sql`a`, sql`b`, sql`c`]);\n\t * // sql`abc`\n\t * ```\n\t * @example\n\t * ```ts\n\t * const query = sql.join([sql`a`, sql`b`, sql`c`], sql`, `);\n\t * // sql`a, b, c`\n\t * ```\n\t */\n\texport function join(chunks: SQLChunk[], separator?: SQLChunk): SQL {\n\t\tconst result: SQLChunk[] = [];\n\t\tfor (const [i, chunk] of chunks.entries()) {\n\t\t\tif (i > 0 && separator !== undefined) {\n\t\t\t\tresult.push(separator);\n\t\t\t}\n\t\t\tresult.push(chunk);\n\t\t}\n\t\treturn new SQL(result);\n\t}\n\n\t/**\n\t * Create a SQL chunk that represents a DB identifier (table, column, index etc.).\n\t * When used in a query, the identifier will be escaped based on the DB engine.\n\t * For example, in PostgreSQL, identifiers are escaped with double quotes.\n\t *\n\t * **WARNING: This function does not offer any protection against SQL injections, so you must validate any user input beforehand.**\n\t *\n\t * @example ```ts\n\t * const query = sql`SELECT * FROM ${sql.identifier('my-table')}`;\n\t * // 'SELECT * FROM \"my-table\"'\n\t * ```\n\t */\n\texport function identifier(value: string): Name {\n\t\treturn new Name(value);\n\t}\n\n\texport function placeholder(name: TName): Placeholder {\n\t\treturn new Placeholder(name);\n\t}\n\n\texport function param(\n\t\tvalue: TData,\n\t\tencoder?: DriverValueEncoder,\n\t): Param {\n\t\treturn new Param(value, encoder);\n\t}\n}\n\nexport namespace SQL {\n\texport class Aliased implements SQLWrapper {\n\t\tstatic readonly [entityKind]: string = 'SQL.Aliased';\n\n\t\tdeclare _: {\n\t\t\tbrand: 'SQL.Aliased';\n\t\t\ttype: T;\n\t\t};\n\n\t\t/** @internal */\n\t\tisSelectionField = false;\n\n\t\tconstructor(\n\t\t\treadonly sql: SQL,\n\t\t\treadonly fieldAlias: string,\n\t\t) {}\n\n\t\tgetSQL(): SQL {\n\t\t\treturn this.sql;\n\t\t}\n\n\t\t/** @internal */\n\t\tclone() {\n\t\t\treturn new Aliased(this.sql, this.fieldAlias);\n\t\t}\n\t}\n}\n\nexport class Placeholder implements SQLWrapper {\n\tstatic readonly [entityKind]: string = 'Placeholder';\n\n\tdeclare protected: TValue;\n\n\tconstructor(readonly name: TName) {}\n\n\tgetSQL(): SQL {\n\t\treturn new SQL([this]);\n\t}\n}\n\n/** @deprecated Use `sql.placeholder` instead. */\nexport function placeholder(name: TName): Placeholder {\n\treturn new Placeholder(name);\n}\n\nexport function fillPlaceholders(params: unknown[], values: Record): unknown[] {\n\treturn params.map((p) => {\n\t\tif (is(p, Placeholder)) {\n\t\t\tif (!(p.name in values)) {\n\t\t\t\tthrow new Error(`No value for placeholder \"${p.name}\" was provided`);\n\t\t\t}\n\n\t\t\treturn values[p.name];\n\t\t}\n\n\t\tif (is(p, Param) && is(p.value, Placeholder)) {\n\t\t\tif (!(p.value.name in values)) {\n\t\t\t\tthrow new Error(`No value for placeholder \"${p.value.name}\" was provided`);\n\t\t\t}\n\n\t\t\treturn p.encoder.mapToDriverValue(values[p.value.name]);\n\t\t}\n\n\t\treturn p;\n\t});\n}\n\nexport type ColumnsSelection = Record;\n\nconst IsDrizzleView = Symbol.for('drizzle:IsDrizzleView');\n\nexport abstract class View<\n\tTName extends string = string,\n\tTExisting extends boolean = boolean,\n\tTSelection extends ColumnsSelection = ColumnsSelection,\n> implements SQLWrapper {\n\tstatic readonly [entityKind]: string = 'View';\n\n\tdeclare _: {\n\t\tbrand: 'View';\n\t\tviewBrand: string;\n\t\tname: TName;\n\t\texisting: TExisting;\n\t\tselectedFields: TSelection;\n\t};\n\n\t/** @internal */\n\t[ViewBaseConfig]: {\n\t\tname: TName;\n\t\toriginalName: TName;\n\t\tschema: string | undefined;\n\t\tselectedFields: ColumnsSelection;\n\t\tisExisting: TExisting;\n\t\tquery: TExisting extends true ? undefined : SQL;\n\t\tisAlias: boolean;\n\t};\n\n\t/** @internal */\n\t[IsDrizzleView] = true;\n\n\tdeclare readonly $inferSelect: InferSelectViewModel, TExisting, TSelection>>;\n\n\tconstructor(\n\t\t{ name, schema, selectedFields, query }: {\n\t\t\tname: TName;\n\t\t\tschema: string | undefined;\n\t\t\tselectedFields: ColumnsSelection;\n\t\t\tquery: SQL | undefined;\n\t\t},\n\t) {\n\t\tthis[ViewBaseConfig] = {\n\t\t\tname,\n\t\t\toriginalName: name,\n\t\t\tschema,\n\t\t\tselectedFields,\n\t\t\tquery: query as (TExisting extends true ? undefined : SQL),\n\t\t\tisExisting: !query as TExisting,\n\t\t\tisAlias: false,\n\t\t};\n\t}\n\n\tgetSQL(): SQL {\n\t\treturn new SQL([this]);\n\t}\n}\n\nexport function isView(view: unknown): view is View {\n\treturn typeof view === 'object' && view !== null && IsDrizzleView in view;\n}\n\nexport function getViewName(view: T): T['_']['name'] {\n\treturn view[ViewBaseConfig].name;\n}\n\nexport type InferSelectViewModel =\n\tEqual extends true ? { [x: string]: unknown }\n\t\t: SelectResult<\n\t\t\tTView['_']['selectedFields'],\n\t\t\t'single',\n\t\t\tRecord\n\t\t>;\n\n// Defined separately from the Column class to resolve circular dependency\nColumn.prototype.getSQL = function() {\n\treturn new SQL([this]);\n};\n\n// Defined separately from the Table class to resolve circular dependency\nTable.prototype.getSQL = function() {\n\treturn new SQL([this]);\n};\n\n// Defined separately from the Column class to resolve circular dependency\nSubquery.prototype.getSQL = function() {\n\treturn new SQL([this]);\n};\n", "import type { ColumnBuilderBaseConfig, ColumnBuilderRuntimeConfig, MakeColumnConfig } from '~/column-builder.ts';\nimport type { ColumnBaseConfig } from '~/column.ts';\nimport { entityKind } from '~/entity.ts';\nimport type { AnyPgTable } from '~/pg-core/table.ts';\nimport type { NonArray, Writable } from '~/utils.ts';\nimport { PgColumn, PgColumnBuilder } from './common.ts';\n\n// Enum as ts enum\n\nexport type PgEnumObjectColumnBuilderInitial = PgEnumObjectColumnBuilder<{\n\tname: TName;\n\tdataType: 'string';\n\tcolumnType: 'PgEnumObjectColumn';\n\tdata: TValues[keyof TValues];\n\tenumValues: string[];\n\tdriverParam: string;\n}>;\n\nexport interface PgEnumObject {\n\t(): PgEnumObjectColumnBuilderInitial<'', TValues>;\n\t(name: TName): PgEnumObjectColumnBuilderInitial;\n\t(name?: TName): PgEnumObjectColumnBuilderInitial;\n\n\treadonly enumName: string;\n\treadonly enumValues: string[];\n\treadonly schema: string | undefined;\n\t/** @internal */\n\t[isPgEnumSym]: true;\n}\n\nexport class PgEnumObjectColumnBuilder<\n\tT extends ColumnBuilderBaseConfig<'string', 'PgEnumObjectColumn'> & { enumValues: string[] },\n> extends PgColumnBuilder }> {\n\tstatic override readonly [entityKind]: string = 'PgEnumObjectColumnBuilder';\n\n\tconstructor(name: T['name'], enumInstance: PgEnumObject) {\n\t\tsuper(name, 'string', 'PgEnumObjectColumn');\n\t\tthis.config.enum = enumInstance;\n\t}\n\n\t/** @internal */\n\toverride build(\n\t\ttable: AnyPgTable<{ name: TTableName }>,\n\t): PgEnumObjectColumn> {\n\t\treturn new PgEnumObjectColumn>(\n\t\t\ttable,\n\t\t\tthis.config as ColumnBuilderRuntimeConfig,\n\t\t);\n\t}\n}\n\nexport class PgEnumObjectColumn & { enumValues: object }>\n\textends PgColumn }>\n{\n\tstatic override readonly [entityKind]: string = 'PgEnumObjectColumn';\n\n\treadonly enum;\n\toverride readonly enumValues = this.config.enum.enumValues;\n\n\tconstructor(\n\t\ttable: AnyPgTable<{ name: T['tableName'] }>,\n\t\tconfig: PgEnumObjectColumnBuilder['config'],\n\t) {\n\t\tsuper(table, config);\n\t\tthis.enum = config.enum;\n\t}\n\n\tgetSQLType(): string {\n\t\treturn this.enum.enumName;\n\t}\n}\n\n// Enum as string union\n\nexport type PgEnumColumnBuilderInitial =\n\tPgEnumColumnBuilder<{\n\t\tname: TName;\n\t\tdataType: 'string';\n\t\tcolumnType: 'PgEnumColumn';\n\t\tdata: TValues[number];\n\t\tenumValues: TValues;\n\t\tdriverParam: string;\n\t}>;\n\nconst isPgEnumSym = Symbol.for('drizzle:isPgEnum');\nexport interface PgEnum {\n\t(): PgEnumColumnBuilderInitial<'', TValues>;\n\t(name: TName): PgEnumColumnBuilderInitial;\n\t(name?: TName): PgEnumColumnBuilderInitial;\n\n\treadonly enumName: string;\n\treadonly enumValues: TValues;\n\treadonly schema: string | undefined;\n\t/** @internal */\n\t[isPgEnumSym]: true;\n}\n\nexport function isPgEnum(obj: unknown): obj is PgEnum<[string, ...string[]]> {\n\treturn !!obj && typeof obj === 'function' && isPgEnumSym in obj && obj[isPgEnumSym] === true;\n}\n\nexport class PgEnumColumnBuilder<\n\tT extends ColumnBuilderBaseConfig<'string', 'PgEnumColumn'> & { enumValues: [string, ...string[]] },\n> extends PgColumnBuilder }> {\n\tstatic override readonly [entityKind]: string = 'PgEnumColumnBuilder';\n\n\tconstructor(name: T['name'], enumInstance: PgEnum) {\n\t\tsuper(name, 'string', 'PgEnumColumn');\n\t\tthis.config.enum = enumInstance;\n\t}\n\n\t/** @internal */\n\toverride build(\n\t\ttable: AnyPgTable<{ name: TTableName }>,\n\t): PgEnumColumn> {\n\t\treturn new PgEnumColumn>(\n\t\t\ttable,\n\t\t\tthis.config as ColumnBuilderRuntimeConfig,\n\t\t);\n\t}\n}\n\nexport class PgEnumColumn & { enumValues: [string, ...string[]] }>\n\textends PgColumn }>\n{\n\tstatic override readonly [entityKind]: string = 'PgEnumColumn';\n\n\treadonly enum = this.config.enum;\n\toverride readonly enumValues = this.config.enum.enumValues;\n\n\tconstructor(\n\t\ttable: AnyPgTable<{ name: T['tableName'] }>,\n\t\tconfig: PgEnumColumnBuilder['config'],\n\t) {\n\t\tsuper(table, config);\n\t\tthis.enum = config.enum;\n\t}\n\n\tgetSQLType(): string {\n\t\treturn this.enum.enumName;\n\t}\n}\n\nexport function pgEnum>(\n\tenumName: string,\n\tvalues: T | Writable,\n): PgEnum>;\n\nexport function pgEnum>(\n\tenumName: string,\n\tenumObj: NonArray,\n): PgEnumObject;\n\nexport function pgEnum(\n\tenumName: any,\n\tinput: any,\n): any {\n\treturn Array.isArray(input)\n\t\t? pgEnumWithSchema(enumName, [...input] as [string, ...string[]], undefined)\n\t\t: pgEnumObjectWithSchema(enumName, input, undefined);\n}\n\n/** @internal */\nexport function pgEnumWithSchema>(\n\tenumName: string,\n\tvalues: T | Writable,\n\tschema?: string,\n): PgEnum> {\n\tconst enumInstance: PgEnum> = Object.assign(\n\t\t(name?: TName): PgEnumColumnBuilderInitial> =>\n\t\t\tnew PgEnumColumnBuilder(name ?? '' as TName, enumInstance),\n\t\t{\n\t\t\tenumName,\n\t\t\tenumValues: values,\n\t\t\tschema,\n\t\t\t[isPgEnumSym]: true,\n\t\t} as const,\n\t);\n\n\treturn enumInstance;\n}\n\n/** @internal */\nexport function pgEnumObjectWithSchema(\n\tenumName: string,\n\tvalues: T,\n\tschema?: string,\n): PgEnumObject {\n\tconst enumInstance: PgEnumObject = Object.assign(\n\t\t(name?: TName): PgEnumObjectColumnBuilderInitial =>\n\t\t\tnew PgEnumObjectColumnBuilder(name ?? '' as TName, enumInstance),\n\t\t{\n\t\t\tenumName,\n\t\t\tenumValues: Object.values(values),\n\t\t\tschema,\n\t\t\t[isPgEnumSym]: true,\n\t\t} as const,\n\t);\n\n\treturn enumInstance;\n}\n", "import type {\n\tColumnBuilderBase,\n\tColumnBuilderBaseConfig,\n\tColumnBuilderExtraConfig,\n\tColumnBuilderRuntimeConfig,\n\tColumnDataType,\n\tHasGenerated,\n\tMakeColumnConfig,\n} from '~/column-builder.ts';\nimport { ColumnBuilder } from '~/column-builder.ts';\nimport type { ColumnBaseConfig } from '~/column.ts';\nimport { Column } from '~/column.ts';\nimport { entityKind, is } from '~/entity.ts';\nimport type { Simplify, Update } from '~/utils.ts';\n\nimport type { ForeignKey, UpdateDeleteAction } from '~/pg-core/foreign-keys.ts';\nimport { ForeignKeyBuilder } from '~/pg-core/foreign-keys.ts';\nimport type { AnyPgTable, PgTable } from '~/pg-core/table.ts';\nimport type { SQL } from '~/sql/sql.ts';\nimport { iife } from '~/tracing-utils.ts';\nimport type { PgIndexOpClass } from '../indexes.ts';\nimport { uniqueKeyName } from '../unique-constraint.ts';\nimport { makePgArray, parsePgArray } from '../utils/array.ts';\n\nexport interface ReferenceConfig {\n\tref: () => PgColumn;\n\tactions: {\n\t\tonUpdate?: UpdateDeleteAction;\n\t\tonDelete?: UpdateDeleteAction;\n\t};\n}\n\nexport interface PgColumnBuilderBase<\n\tT extends ColumnBuilderBaseConfig = ColumnBuilderBaseConfig,\n\tTTypeConfig extends object = object,\n> extends ColumnBuilderBase {}\n\nexport abstract class PgColumnBuilder<\n\tT extends ColumnBuilderBaseConfig = ColumnBuilderBaseConfig,\n\tTRuntimeConfig extends object = object,\n\tTTypeConfig extends object = object,\n\tTExtraConfig extends ColumnBuilderExtraConfig = ColumnBuilderExtraConfig,\n> extends ColumnBuilder\n\timplements PgColumnBuilderBase\n{\n\tprivate foreignKeyConfigs: ReferenceConfig[] = [];\n\n\tstatic override readonly [entityKind]: string = 'PgColumnBuilder';\n\n\tarray(size?: TSize): PgArrayBuilder<\n\t\t& {\n\t\t\tname: T['name'];\n\t\t\tdataType: 'array';\n\t\t\tcolumnType: 'PgArray';\n\t\t\tdata: T['data'][];\n\t\t\tdriverParam: T['driverParam'][] | string;\n\t\t\tenumValues: T['enumValues'];\n\t\t\tsize: TSize;\n\t\t\tbaseBuilder: T;\n\t\t}\n\t\t& (T extends { notNull: true } ? { notNull: true } : {})\n\t\t& (T extends { hasDefault: true } ? { hasDefault: true } : {}),\n\t\tT\n\t> {\n\t\treturn new PgArrayBuilder(this.config.name, this as PgColumnBuilder, size as any);\n\t}\n\n\treferences(\n\t\tref: ReferenceConfig['ref'],\n\t\tactions: ReferenceConfig['actions'] = {},\n\t): this {\n\t\tthis.foreignKeyConfigs.push({ ref, actions });\n\t\treturn this;\n\t}\n\n\tunique(\n\t\tname?: string,\n\t\tconfig?: { nulls: 'distinct' | 'not distinct' },\n\t): this {\n\t\tthis.config.isUnique = true;\n\t\tthis.config.uniqueName = name;\n\t\tthis.config.uniqueType = config?.nulls;\n\t\treturn this;\n\t}\n\n\tgeneratedAlwaysAs(as: SQL | T['data'] | (() => SQL)): HasGenerated {\n\t\tthis.config.generated = {\n\t\t\tas,\n\t\t\ttype: 'always',\n\t\t\tmode: 'stored',\n\t\t};\n\t\treturn this as HasGenerated;\n\t}\n\n\t/** @internal */\n\tbuildForeignKeys(column: PgColumn, table: PgTable): ForeignKey[] {\n\t\treturn this.foreignKeyConfigs.map(({ ref, actions }) => {\n\t\t\treturn iife(\n\t\t\t\t(ref, actions) => {\n\t\t\t\t\tconst builder = new ForeignKeyBuilder(() => {\n\t\t\t\t\t\tconst foreignColumn = ref();\n\t\t\t\t\t\treturn { columns: [column], foreignColumns: [foreignColumn] };\n\t\t\t\t\t});\n\t\t\t\t\tif (actions.onUpdate) {\n\t\t\t\t\t\tbuilder.onUpdate(actions.onUpdate);\n\t\t\t\t\t}\n\t\t\t\t\tif (actions.onDelete) {\n\t\t\t\t\t\tbuilder.onDelete(actions.onDelete);\n\t\t\t\t\t}\n\t\t\t\t\treturn builder.build(table);\n\t\t\t\t},\n\t\t\t\tref,\n\t\t\t\tactions,\n\t\t\t);\n\t\t});\n\t}\n\n\t/** @internal */\n\tabstract build(\n\t\ttable: AnyPgTable<{ name: TTableName }>,\n\t): PgColumn>;\n\n\t/** @internal */\n\tbuildExtraConfigColumn(\n\t\ttable: AnyPgTable<{ name: TTableName }>,\n\t): ExtraConfigColumn {\n\t\treturn new ExtraConfigColumn(table, this.config);\n\t}\n}\n\n// To understand how to use `PgColumn` and `PgColumn`, see `Column` and `AnyColumn` documentation.\nexport abstract class PgColumn<\n\tT extends ColumnBaseConfig = ColumnBaseConfig,\n\tTRuntimeConfig extends object = {},\n\tTTypeConfig extends object = {},\n> extends Column {\n\tstatic override readonly [entityKind]: string = 'PgColumn';\n\n\tconstructor(\n\t\toverride readonly table: PgTable,\n\t\tconfig: ColumnBuilderRuntimeConfig,\n\t) {\n\t\tif (!config.uniqueName) {\n\t\t\tconfig.uniqueName = uniqueKeyName(table, [config.name]);\n\t\t}\n\t\tsuper(table, config);\n\t}\n}\n\nexport type IndexedExtraConfigType = { order?: 'asc' | 'desc'; nulls?: 'first' | 'last'; opClass?: string };\n\nexport class ExtraConfigColumn<\n\tT extends ColumnBaseConfig = ColumnBaseConfig,\n> extends PgColumn {\n\tstatic override readonly [entityKind]: string = 'ExtraConfigColumn';\n\n\toverride getSQLType(): string {\n\t\treturn this.getSQLType();\n\t}\n\n\tindexConfig: IndexedExtraConfigType = {\n\t\torder: this.config.order ?? 'asc',\n\t\tnulls: this.config.nulls ?? 'last',\n\t\topClass: this.config.opClass,\n\t};\n\tdefaultConfig: IndexedExtraConfigType = {\n\t\torder: 'asc',\n\t\tnulls: 'last',\n\t\topClass: undefined,\n\t};\n\n\tasc(): Omit {\n\t\tthis.indexConfig.order = 'asc';\n\t\treturn this;\n\t}\n\n\tdesc(): Omit {\n\t\tthis.indexConfig.order = 'desc';\n\t\treturn this;\n\t}\n\n\tnullsFirst(): Omit {\n\t\tthis.indexConfig.nulls = 'first';\n\t\treturn this;\n\t}\n\n\tnullsLast(): Omit {\n\t\tthis.indexConfig.nulls = 'last';\n\t\treturn this;\n\t}\n\n\t/**\n\t * ### PostgreSQL documentation quote\n\t *\n\t * > An operator class with optional parameters can be specified for each column of an index.\n\t * The operator class identifies the operators to be used by the index for that column.\n\t * For example, a B-tree index on four-byte integers would use the int4_ops class;\n\t * this operator class includes comparison functions for four-byte integers.\n\t * In practice the default operator class for the column's data type is usually sufficient.\n\t * The main point of having operator classes is that for some data types, there could be more than one meaningful ordering.\n\t * For example, we might want to sort a complex-number data type either by absolute value or by real part.\n\t * We could do this by defining two operator classes for the data type and then selecting the proper class when creating an index.\n\t * More information about operator classes check:\n\t *\n\t * ### Useful links\n\t * https://www.postgresql.org/docs/current/sql-createindex.html\n\t *\n\t * https://www.postgresql.org/docs/current/indexes-opclass.html\n\t *\n\t * https://www.postgresql.org/docs/current/xindex.html\n\t *\n\t * ### Additional types\n\t * If you have the `pg_vector` extension installed in your database, you can use the\n\t * `vector_l2_ops`, `vector_ip_ops`, `vector_cosine_ops`, `vector_l1_ops`, `bit_hamming_ops`, `bit_jaccard_ops`, `halfvec_l2_ops`, `sparsevec_l2_ops` options, which are predefined types.\n\t *\n\t * **You can always specify any string you want in the operator class, in case Drizzle doesn't have it natively in its types**\n\t *\n\t * @param opClass\n\t * @returns\n\t */\n\top(opClass: PgIndexOpClass): Omit {\n\t\tthis.indexConfig.opClass = opClass;\n\t\treturn this;\n\t}\n}\n\nexport class IndexedColumn {\n\tstatic readonly [entityKind]: string = 'IndexedColumn';\n\tconstructor(\n\t\tname: string | undefined,\n\t\tkeyAsName: boolean,\n\t\ttype: string,\n\t\tindexConfig: IndexedExtraConfigType,\n\t) {\n\t\tthis.name = name;\n\t\tthis.keyAsName = keyAsName;\n\t\tthis.type = type;\n\t\tthis.indexConfig = indexConfig;\n\t}\n\n\tname: string | undefined;\n\tkeyAsName: boolean;\n\ttype: string;\n\tindexConfig: IndexedExtraConfigType;\n}\n\nexport type AnyPgColumn> = {}> = PgColumn<\n\tRequired, TPartial>>\n>;\n\nexport type PgArrayColumnBuilderBaseConfig = ColumnBuilderBaseConfig<'array', 'PgArray'> & {\n\tsize: number | undefined;\n\tbaseBuilder: ColumnBuilderBaseConfig;\n};\n\nexport class PgArrayBuilder<\n\tT extends PgArrayColumnBuilderBaseConfig,\n\tTBase extends ColumnBuilderBaseConfig | PgArrayColumnBuilderBaseConfig,\n> extends PgColumnBuilder<\n\tT,\n\t{\n\t\tbaseBuilder: TBase extends PgArrayColumnBuilderBaseConfig ? PgArrayBuilder<\n\t\t\t\tTBase,\n\t\t\t\tTBase extends { baseBuilder: infer TBaseBuilder extends ColumnBuilderBaseConfig } ? TBaseBuilder\n\t\t\t\t\t: never\n\t\t\t>\n\t\t\t: PgColumnBuilder>>>;\n\t\tsize: T['size'];\n\t},\n\t{\n\t\tbaseBuilder: TBase extends PgArrayColumnBuilderBaseConfig ? PgArrayBuilder<\n\t\t\t\tTBase,\n\t\t\t\tTBase extends { baseBuilder: infer TBaseBuilder extends ColumnBuilderBaseConfig } ? TBaseBuilder\n\t\t\t\t\t: never\n\t\t\t>\n\t\t\t: PgColumnBuilder>>>;\n\t\tsize: T['size'];\n\t}\n> {\n\tstatic override readonly [entityKind] = 'PgArrayBuilder';\n\n\tconstructor(\n\t\tname: string,\n\t\tbaseBuilder: PgArrayBuilder['config']['baseBuilder'],\n\t\tsize: T['size'],\n\t) {\n\t\tsuper(name, 'array', 'PgArray');\n\t\tthis.config.baseBuilder = baseBuilder;\n\t\tthis.config.size = size;\n\t}\n\n\t/** @internal */\n\toverride build(\n\t\ttable: AnyPgTable<{ name: TTableName }>,\n\t): PgArray & { size: T['size']; baseBuilder: T['baseBuilder'] }, TBase> {\n\t\tconst baseColumn = this.config.baseBuilder.build(table);\n\t\treturn new PgArray & { size: T['size']; baseBuilder: T['baseBuilder'] }, TBase>(\n\t\t\ttable as AnyPgTable<{ name: MakeColumnConfig['tableName'] }>,\n\t\t\tthis.config as ColumnBuilderRuntimeConfig,\n\t\t\tbaseColumn,\n\t\t);\n\t}\n}\n\nexport class PgArray<\n\tT extends ColumnBaseConfig<'array', 'PgArray'> & {\n\t\tsize: number | undefined;\n\t\tbaseBuilder: ColumnBuilderBaseConfig;\n\t},\n\tTBase extends ColumnBuilderBaseConfig,\n> extends PgColumn {\n\treadonly size: T['size'];\n\n\tstatic override readonly [entityKind]: string = 'PgArray';\n\n\tconstructor(\n\t\ttable: AnyPgTable<{ name: T['tableName'] }>,\n\t\tconfig: PgArrayBuilder['config'],\n\t\treadonly baseColumn: PgColumn,\n\t\treadonly range?: [number | undefined, number | undefined],\n\t) {\n\t\tsuper(table, config);\n\t\tthis.size = config.size;\n\t}\n\n\tgetSQLType(): string {\n\t\treturn `${this.baseColumn.getSQLType()}[${typeof this.size === 'number' ? this.size : ''}]`;\n\t}\n\n\toverride mapFromDriverValue(value: unknown[] | string): T['data'] {\n\t\tif (typeof value === 'string') {\n\t\t\t// Thank you node-postgres for not parsing enum arrays\n\t\t\tvalue = parsePgArray(value);\n\t\t}\n\t\treturn value.map((v) => this.baseColumn.mapFromDriverValue(v));\n\t}\n\n\toverride mapToDriverValue(value: unknown[], isNestedArray = false): unknown[] | string {\n\t\tconst a = value.map((v) =>\n\t\t\tv === null\n\t\t\t\t? null\n\t\t\t\t: is(this.baseColumn, PgArray)\n\t\t\t\t? this.baseColumn.mapToDriverValue(v as unknown[], true)\n\t\t\t\t: this.baseColumn.mapToDriverValue(v)\n\t\t);\n\t\tif (isNestedArray) return a;\n\t\treturn makePgArray(a);\n\t}\n}\n", "import { entityKind } from '~/entity.ts';\nimport type { Column } from './column.ts';\nimport type { GelColumn, GelExtraConfigColumn } from './gel-core/index.ts';\nimport type { MySqlColumn } from './mysql-core/index.ts';\nimport type { ExtraConfigColumn, PgColumn, PgSequenceOptions } from './pg-core/index.ts';\nimport type { SingleStoreColumn } from './singlestore-core/index.ts';\nimport type { SQL } from './sql/sql.ts';\nimport type { SQLiteColumn } from './sqlite-core/index.ts';\nimport type { Assume, Simplify } from './utils.ts';\n\nexport type ColumnDataType =\n\t| 'string'\n\t| 'number'\n\t| 'boolean'\n\t| 'array'\n\t| 'json'\n\t| 'date'\n\t| 'bigint'\n\t| 'custom'\n\t| 'buffer'\n\t| 'dateDuration'\n\t| 'duration'\n\t| 'relDuration'\n\t| 'localTime'\n\t| 'localDate'\n\t| 'localDateTime';\n\nexport type Dialect = 'pg' | 'mysql' | 'sqlite' | 'singlestore' | 'common' | 'gel';\n\nexport type GeneratedStorageMode = 'virtual' | 'stored';\n\nexport type GeneratedType = 'always' | 'byDefault';\n\nexport type GeneratedColumnConfig = {\n\tas: TDataType | SQL | (() => SQL);\n\ttype?: GeneratedType;\n\tmode?: GeneratedStorageMode;\n};\n\nexport type GeneratedIdentityConfig = {\n\tsequenceName?: string;\n\tsequenceOptions?: PgSequenceOptions;\n\ttype: 'always' | 'byDefault';\n};\n\nexport interface ColumnBuilderBaseConfig {\n\tname: string;\n\tdataType: TDataType;\n\tcolumnType: TColumnType;\n\tdata: unknown;\n\tdriverParam: unknown;\n\tenumValues: string[] | undefined;\n}\n\nexport type MakeColumnConfig<\n\tT extends ColumnBuilderBaseConfig,\n\tTTableName extends string,\n\tTData = T extends { $type: infer U } ? U : T['data'],\n> = {\n\tname: T['name'];\n\ttableName: TTableName;\n\tdataType: T['dataType'];\n\tcolumnType: T['columnType'];\n\tdata: TData;\n\tdriverParam: T['driverParam'];\n\tnotNull: T extends { notNull: true } ? true : false;\n\thasDefault: T extends { hasDefault: true } ? true : false;\n\tisPrimaryKey: T extends { isPrimaryKey: true } ? true : false;\n\tisAutoincrement: T extends { isAutoincrement: true } ? true : false;\n\thasRuntimeDefault: T extends { hasRuntimeDefault: true } ? true : false;\n\tenumValues: T['enumValues'];\n\tbaseColumn: T extends { baseBuilder: infer U extends ColumnBuilderBase } ? BuildColumn\n\t\t: never;\n\tidentity: T extends { identity: 'always' } ? 'always' : T extends { identity: 'byDefault' } ? 'byDefault' : undefined;\n\tgenerated: T extends { generated: infer G } ? unknown extends G ? undefined\n\t\t: G extends undefined ? undefined\n\t\t: G\n\t\t: undefined;\n} & {};\n\nexport type ColumnBuilderTypeConfig<\n\t// eslint-disable-next-line @typescript-eslint/no-unused-vars\n\tT extends ColumnBuilderBaseConfig,\n\tTTypeConfig extends object = object,\n> = Simplify<\n\t& {\n\t\tbrand: 'ColumnBuilder';\n\t\tname: T['name'];\n\t\tdataType: T['dataType'];\n\t\tcolumnType: T['columnType'];\n\t\tdata: T['data'];\n\t\tdriverParam: T['driverParam'];\n\t\tnotNull: T extends { notNull: infer U } ? U : boolean;\n\t\thasDefault: T extends { hasDefault: infer U } ? U : boolean;\n\t\tenumValues: T['enumValues'];\n\t\tidentity: T extends { identity: infer U } ? U : unknown;\n\t\tgenerated: T extends { generated: infer G } ? G extends undefined ? unknown : G : unknown;\n\t}\n\t& TTypeConfig\n>;\n\nexport type ColumnBuilderRuntimeConfig = {\n\tname: string;\n\tkeyAsName: boolean;\n\tnotNull: boolean;\n\tdefault: TData | SQL | undefined;\n\tdefaultFn: (() => TData | SQL) | undefined;\n\tonUpdateFn: (() => TData | SQL) | undefined;\n\thasDefault: boolean;\n\tprimaryKey: boolean;\n\tisUnique: boolean;\n\tuniqueName: string | undefined;\n\tuniqueType: string | undefined;\n\tdataType: string;\n\tcolumnType: string;\n\tgenerated: GeneratedColumnConfig | undefined;\n\tgeneratedIdentity: GeneratedIdentityConfig | undefined;\n} & TRuntimeConfig;\n\nexport interface ColumnBuilderExtraConfig {\n\tprimaryKeyHasDefault?: boolean;\n}\n\nexport type NotNull = T & {\n\t_: {\n\t\tnotNull: true;\n\t};\n};\n\nexport type HasDefault = T & {\n\t_: {\n\t\thasDefault: true;\n\t};\n};\n\nexport type IsPrimaryKey = T & {\n\t_: {\n\t\tisPrimaryKey: true;\n\t};\n};\n\nexport type IsAutoincrement = T & {\n\t_: {\n\t\tisAutoincrement: true;\n\t};\n};\n\nexport type HasRuntimeDefault = T & {\n\t_: {\n\t\thasRuntimeDefault: true;\n\t};\n};\n\nexport type $Type = T & {\n\t_: {\n\t\t$type: TType;\n\t};\n};\n\nexport type HasGenerated = T & {\n\t_: {\n\t\thasDefault: true;\n\t\tgenerated: TGenerated;\n\t};\n};\n\nexport type IsIdentity<\n\tT extends ColumnBuilderBase,\n\tTType extends 'always' | 'byDefault',\n> = T & {\n\t_: {\n\t\tnotNull: true;\n\t\thasDefault: true;\n\t\tidentity: TType;\n\t};\n};\nexport interface ColumnBuilderBase<\n\tT extends ColumnBuilderBaseConfig = ColumnBuilderBaseConfig,\n\tTTypeConfig extends object = object,\n> {\n\t_: ColumnBuilderTypeConfig;\n}\n\n// To understand how to use `ColumnBuilder` and `AnyColumnBuilder`, see `Column` and `AnyColumn` documentation.\nexport abstract class ColumnBuilder<\n\tT extends ColumnBuilderBaseConfig = ColumnBuilderBaseConfig,\n\tTRuntimeConfig extends object = object,\n\tTTypeConfig extends object = object,\n\tTExtraConfig extends ColumnBuilderExtraConfig = ColumnBuilderExtraConfig,\n> implements ColumnBuilderBase {\n\tstatic readonly [entityKind]: string = 'ColumnBuilder';\n\n\tdeclare _: ColumnBuilderTypeConfig;\n\n\tprotected config: ColumnBuilderRuntimeConfig;\n\n\tconstructor(name: T['name'], dataType: T['dataType'], columnType: T['columnType']) {\n\t\tthis.config = {\n\t\t\tname,\n\t\t\tkeyAsName: name === '',\n\t\t\tnotNull: false,\n\t\t\tdefault: undefined,\n\t\t\thasDefault: false,\n\t\t\tprimaryKey: false,\n\t\t\tisUnique: false,\n\t\t\tuniqueName: undefined,\n\t\t\tuniqueType: undefined,\n\t\t\tdataType,\n\t\t\tcolumnType,\n\t\t\tgenerated: undefined,\n\t\t} as ColumnBuilderRuntimeConfig;\n\t}\n\n\t/**\n\t * Changes the data type of the column. Commonly used with `json` columns. Also, useful for branded types.\n\t *\n\t * @example\n\t * ```ts\n\t * const users = pgTable('users', {\n\t * \tid: integer('id').$type().primaryKey(),\n\t * \tdetails: json('details').$type().notNull(),\n\t * });\n\t * ```\n\t */\n\t$type(): $Type {\n\t\treturn this as $Type;\n\t}\n\n\t/**\n\t * Adds a `not null` clause to the column definition.\n\t *\n\t * Affects the `select` model of the table - columns *without* `not null` will be nullable on select.\n\t */\n\tnotNull(): NotNull {\n\t\tthis.config.notNull = true;\n\t\treturn this as NotNull;\n\t}\n\n\t/**\n\t * Adds a `default ` clause to the column definition.\n\t *\n\t * Affects the `insert` model of the table - columns *with* `default` are optional on insert.\n\t *\n\t * If you need to set a dynamic default value, use {@link $defaultFn} instead.\n\t */\n\tdefault(value: (this['_'] extends { $type: infer U } ? U : this['_']['data']) | SQL): HasDefault {\n\t\tthis.config.default = value;\n\t\tthis.config.hasDefault = true;\n\t\treturn this as HasDefault;\n\t}\n\n\t/**\n\t * Adds a dynamic default value to the column.\n\t * The function will be called when the row is inserted, and the returned value will be used as the column value.\n\t *\n\t * **Note:** This value does not affect the `drizzle-kit` behavior, it is only used at runtime in `drizzle-orm`.\n\t */\n\t$defaultFn(\n\t\tfn: () => (this['_'] extends { $type: infer U } ? U : this['_']['data']) | SQL,\n\t): HasRuntimeDefault> {\n\t\tthis.config.defaultFn = fn;\n\t\tthis.config.hasDefault = true;\n\t\treturn this as HasRuntimeDefault>;\n\t}\n\n\t/**\n\t * Alias for {@link $defaultFn}.\n\t */\n\t$default = this.$defaultFn;\n\n\t/**\n\t * Adds a dynamic update value to the column.\n\t * The function will be called when the row is updated, and the returned value will be used as the column value if none is provided.\n\t * If no `default` (or `$defaultFn`) value is provided, the function will be called when the row is inserted as well, and the returned value will be used as the column value.\n\t *\n\t * **Note:** This value does not affect the `drizzle-kit` behavior, it is only used at runtime in `drizzle-orm`.\n\t */\n\t$onUpdateFn(\n\t\tfn: () => (this['_'] extends { $type: infer U } ? U : this['_']['data']) | SQL,\n\t): HasDefault {\n\t\tthis.config.onUpdateFn = fn;\n\t\tthis.config.hasDefault = true;\n\t\treturn this as HasDefault;\n\t}\n\n\t/**\n\t * Alias for {@link $onUpdateFn}.\n\t */\n\t$onUpdate = this.$onUpdateFn;\n\n\t/**\n\t * Adds a `primary key` clause to the column definition. This implicitly makes the column `not null`.\n\t *\n\t * In SQLite, `integer primary key` implicitly makes the column auto-incrementing.\n\t */\n\tprimaryKey(): TExtraConfig['primaryKeyHasDefault'] extends true ? IsPrimaryKey>>\n\t\t: IsPrimaryKey>\n\t{\n\t\tthis.config.primaryKey = true;\n\t\tthis.config.notNull = true;\n\t\treturn this as TExtraConfig['primaryKeyHasDefault'] extends true ? IsPrimaryKey>>\n\t\t\t: IsPrimaryKey>;\n\t}\n\n\tabstract generatedAlwaysAs(\n\t\tas: SQL | T['data'] | (() => SQL),\n\t\tconfig?: Partial>,\n\t): HasGenerated;\n\n\t/** @internal Sets the name of the column to the key within the table definition if a name was not given. */\n\tsetName(name: string) {\n\t\tif (this.config.name !== '') return;\n\t\tthis.config.name = name;\n\t}\n}\n\nexport type BuildColumn<\n\tTTableName extends string,\n\tTBuilder extends ColumnBuilderBase,\n\tTDialect extends Dialect,\n> = TDialect extends 'pg' ? PgColumn<\n\t\tMakeColumnConfig,\n\t\t{},\n\t\tSimplify | 'brand' | 'dialect'>>\n\t>\n\t: TDialect extends 'mysql' ? MySqlColumn<\n\t\t\tMakeColumnConfig,\n\t\t\t{},\n\t\t\tSimplify<\n\t\t\t\tOmit<\n\t\t\t\t\tTBuilder['_'],\n\t\t\t\t\t| keyof MakeColumnConfig\n\t\t\t\t\t| 'brand'\n\t\t\t\t\t| 'dialect'\n\t\t\t\t\t| 'primaryKeyHasDefault'\n\t\t\t\t\t| 'mysqlColumnBuilderBrand'\n\t\t\t\t>\n\t\t\t>\n\t\t>\n\t: TDialect extends 'sqlite' ? SQLiteColumn<\n\t\t\tMakeColumnConfig,\n\t\t\t{},\n\t\t\tSimplify | 'brand' | 'dialect'>>\n\t\t>\n\t: TDialect extends 'common' ? Column<\n\t\t\tMakeColumnConfig,\n\t\t\t{},\n\t\t\tSimplify | 'brand' | 'dialect'>>\n\t\t>\n\t: TDialect extends 'singlestore' ? SingleStoreColumn<\n\t\t\tMakeColumnConfig,\n\t\t\t{},\n\t\t\tSimplify<\n\t\t\t\tOmit<\n\t\t\t\t\tTBuilder['_'],\n\t\t\t\t\t| keyof MakeColumnConfig\n\t\t\t\t\t| 'brand'\n\t\t\t\t\t| 'dialect'\n\t\t\t\t\t| 'primaryKeyHasDefault'\n\t\t\t\t\t| 'singlestoreColumnBuilderBrand'\n\t\t\t\t>\n\t\t\t>\n\t\t>\n\t: TDialect extends 'gel' ? GelColumn<\n\t\t\tMakeColumnConfig,\n\t\t\t{},\n\t\t\tSimplify | 'brand' | 'dialect'>>\n\t\t>\n\t: never;\n\nexport type BuildIndexColumn<\n\tTDialect extends Dialect,\n> = TDialect extends 'pg' ? ExtraConfigColumn\n\t: TDialect extends 'gel' ? GelExtraConfigColumn\n\t: never;\n\n// TODO\n// try to make sql as well + indexRaw\n\n// optional after everything will be working as expected\n// also try to leave only needed methods for extraConfig\n// make an error if I pass .asc() to fk and so on\n\nexport type BuildColumns<\n\tTTableName extends string,\n\tTConfigMap extends Record,\n\tTDialect extends Dialect,\n> =\n\t& {\n\t\t[Key in keyof TConfigMap]: BuildColumn\n\t\t\t\t& { name: TConfigMap[Key]['_']['name'] extends '' ? Assume : TConfigMap[Key]['_']['name'] };\n\t\t}, TDialect>;\n\t}\n\t& {};\n\nexport type BuildExtraConfigColumns<\n\t_TTableName extends string,\n\tTConfigMap extends Record,\n\tTDialect extends Dialect,\n> =\n\t& {\n\t\t[Key in keyof TConfigMap]: BuildIndexColumn;\n\t}\n\t& {};\n\nexport type ChangeColumnTableName =\n\tTDialect extends 'pg' ? PgColumn>\n\t\t: TDialect extends 'mysql' ? MySqlColumn>\n\t\t: TDialect extends 'singlestore' ? SingleStoreColumn>\n\t\t: TDialect extends 'sqlite' ? SQLiteColumn>\n\t\t: TDialect extends 'gel' ? GelColumn>\n\t\t: never;\n", "import { entityKind } from '~/entity.ts';\nimport { TableName } from '~/table.utils.ts';\nimport type { AnyPgColumn, PgColumn } from './columns/index.ts';\nimport type { PgTable } from './table.ts';\n\nexport type UpdateDeleteAction = 'cascade' | 'restrict' | 'no action' | 'set null' | 'set default';\n\nexport type Reference = () => {\n\treadonly name?: string;\n\treadonly columns: PgColumn[];\n\treadonly foreignTable: PgTable;\n\treadonly foreignColumns: PgColumn[];\n};\n\nexport class ForeignKeyBuilder {\n\tstatic readonly [entityKind]: string = 'PgForeignKeyBuilder';\n\n\t/** @internal */\n\treference: Reference;\n\n\t/** @internal */\n\t_onUpdate: UpdateDeleteAction | undefined = 'no action';\n\n\t/** @internal */\n\t_onDelete: UpdateDeleteAction | undefined = 'no action';\n\n\tconstructor(\n\t\tconfig: () => {\n\t\t\tname?: string;\n\t\t\tcolumns: PgColumn[];\n\t\t\tforeignColumns: PgColumn[];\n\t\t},\n\t\tactions?: {\n\t\t\tonUpdate?: UpdateDeleteAction;\n\t\t\tonDelete?: UpdateDeleteAction;\n\t\t} | undefined,\n\t) {\n\t\tthis.reference = () => {\n\t\t\tconst { name, columns, foreignColumns } = config();\n\t\t\treturn { name, columns, foreignTable: foreignColumns[0]!.table as PgTable, foreignColumns };\n\t\t};\n\t\tif (actions) {\n\t\t\tthis._onUpdate = actions.onUpdate;\n\t\t\tthis._onDelete = actions.onDelete;\n\t\t}\n\t}\n\n\tonUpdate(action: UpdateDeleteAction): this {\n\t\tthis._onUpdate = action === undefined ? 'no action' : action;\n\t\treturn this;\n\t}\n\n\tonDelete(action: UpdateDeleteAction): this {\n\t\tthis._onDelete = action === undefined ? 'no action' : action;\n\t\treturn this;\n\t}\n\n\t/** @internal */\n\tbuild(table: PgTable): ForeignKey {\n\t\treturn new ForeignKey(table, this);\n\t}\n}\n\nexport type AnyForeignKeyBuilder = ForeignKeyBuilder;\n\nexport class ForeignKey {\n\tstatic readonly [entityKind]: string = 'PgForeignKey';\n\n\treadonly reference: Reference;\n\treadonly onUpdate: UpdateDeleteAction | undefined;\n\treadonly onDelete: UpdateDeleteAction | undefined;\n\n\tconstructor(readonly table: PgTable, builder: ForeignKeyBuilder) {\n\t\tthis.reference = builder.reference;\n\t\tthis.onUpdate = builder._onUpdate;\n\t\tthis.onDelete = builder._onDelete;\n\t}\n\n\tgetName(): string {\n\t\tconst { name, columns, foreignColumns } = this.reference();\n\t\tconst columnNames = columns.map((column) => column.name);\n\t\tconst foreignColumnNames = foreignColumns.map((column) => column.name);\n\t\tconst chunks = [\n\t\t\tthis.table[TableName],\n\t\t\t...columnNames,\n\t\t\tforeignColumns[0]!.table[TableName],\n\t\t\t...foreignColumnNames,\n\t\t];\n\t\treturn name ?? `${chunks.join('_')}_fk`;\n\t}\n}\n\ntype ColumnsWithTable<\n\tTTableName extends string,\n\tTColumns extends PgColumn[],\n> = { [Key in keyof TColumns]: AnyPgColumn<{ tableName: TTableName }> };\n\nexport function foreignKey<\n\tTTableName extends string,\n\tTForeignTableName extends string,\n\tTColumns extends [AnyPgColumn<{ tableName: TTableName }>, ...AnyPgColumn<{ tableName: TTableName }>[]],\n>(\n\tconfig: {\n\t\tname?: string;\n\t\tcolumns: TColumns;\n\t\tforeignColumns: ColumnsWithTable;\n\t},\n): ForeignKeyBuilder {\n\tfunction mappedConfig() {\n\t\tconst { name, columns, foreignColumns } = config;\n\t\treturn {\n\t\t\tname,\n\t\t\tcolumns,\n\t\t\tforeignColumns,\n\t\t};\n\t}\n\n\treturn new ForeignKeyBuilder(mappedConfig);\n}\n", "export function iife(fn: (...args: T) => U, ...args: T): U {\n\treturn fn(...args);\n}\n", "import { entityKind } from '~/entity.ts';\nimport { TableName } from '~/table.utils.ts';\nimport type { PgColumn } from './columns/index.ts';\nimport type { PgTable } from './table.ts';\n\nexport function unique(name?: string): UniqueOnConstraintBuilder {\n\treturn new UniqueOnConstraintBuilder(name);\n}\n\nexport function uniqueKeyName(table: PgTable, columns: string[]) {\n\treturn `${table[TableName]}_${columns.join('_')}_unique`;\n}\n\nexport class UniqueConstraintBuilder {\n\tstatic readonly [entityKind]: string = 'PgUniqueConstraintBuilder';\n\n\t/** @internal */\n\tcolumns: PgColumn[];\n\t/** @internal */\n\tnullsNotDistinctConfig = false;\n\n\tconstructor(\n\t\tcolumns: PgColumn[],\n\t\tprivate name?: string,\n\t) {\n\t\tthis.columns = columns;\n\t}\n\n\tnullsNotDistinct() {\n\t\tthis.nullsNotDistinctConfig = true;\n\t\treturn this;\n\t}\n\n\t/** @internal */\n\tbuild(table: PgTable): UniqueConstraint {\n\t\treturn new UniqueConstraint(table, this.columns, this.nullsNotDistinctConfig, this.name);\n\t}\n}\n\nexport class UniqueOnConstraintBuilder {\n\tstatic readonly [entityKind]: string = 'PgUniqueOnConstraintBuilder';\n\n\t/** @internal */\n\tname?: string;\n\n\tconstructor(\n\t\tname?: string,\n\t) {\n\t\tthis.name = name;\n\t}\n\n\ton(...columns: [PgColumn, ...PgColumn[]]) {\n\t\treturn new UniqueConstraintBuilder(columns, this.name);\n\t}\n}\n\nexport class UniqueConstraint {\n\tstatic readonly [entityKind]: string = 'PgUniqueConstraint';\n\n\treadonly columns: PgColumn[];\n\treadonly name?: string;\n\treadonly nullsNotDistinct: boolean = false;\n\n\tconstructor(readonly table: PgTable, columns: PgColumn[], nullsNotDistinct: boolean, name?: string) {\n\t\tthis.columns = columns;\n\t\tthis.name = name ?? uniqueKeyName(this.table, this.columns.map((column) => column.name));\n\t\tthis.nullsNotDistinct = nullsNotDistinct;\n\t}\n\n\tgetName() {\n\t\treturn this.name;\n\t}\n}\n", "function parsePgArrayValue(arrayString: string, startFrom: number, inQuotes: boolean): [string, number] {\n\tfor (let i = startFrom; i < arrayString.length; i++) {\n\t\tconst char = arrayString[i];\n\n\t\tif (char === '\\\\') {\n\t\t\ti++;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (char === '\"') {\n\t\t\treturn [arrayString.slice(startFrom, i).replace(/\\\\/g, ''), i + 1];\n\t\t}\n\n\t\tif (inQuotes) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (char === ',' || char === '}') {\n\t\t\treturn [arrayString.slice(startFrom, i).replace(/\\\\/g, ''), i];\n\t\t}\n\t}\n\n\treturn [arrayString.slice(startFrom).replace(/\\\\/g, ''), arrayString.length];\n}\n\nexport function parsePgNestedArray(arrayString: string, startFrom = 0): [any[], number] {\n\tconst result: any[] = [];\n\tlet i = startFrom;\n\tlet lastCharIsComma = false;\n\n\twhile (i < arrayString.length) {\n\t\tconst char = arrayString[i];\n\n\t\tif (char === ',') {\n\t\t\tif (lastCharIsComma || i === startFrom) {\n\t\t\t\tresult.push('');\n\t\t\t}\n\t\t\tlastCharIsComma = true;\n\t\t\ti++;\n\t\t\tcontinue;\n\t\t}\n\n\t\tlastCharIsComma = false;\n\n\t\tif (char === '\\\\') {\n\t\t\ti += 2;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (char === '\"') {\n\t\t\tconst [value, startFrom] = parsePgArrayValue(arrayString, i + 1, true);\n\t\t\tresult.push(value);\n\t\t\ti = startFrom;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (char === '}') {\n\t\t\treturn [result, i + 1];\n\t\t}\n\n\t\tif (char === '{') {\n\t\t\tconst [value, startFrom] = parsePgNestedArray(arrayString, i + 1);\n\t\t\tresult.push(value);\n\t\t\ti = startFrom;\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst [value, newStartFrom] = parsePgArrayValue(arrayString, i, false);\n\t\tresult.push(value);\n\t\ti = newStartFrom;\n\t}\n\n\treturn [result, i];\n}\n\nexport function parsePgArray(arrayString: string): any[] {\n\tconst [result] = parsePgNestedArray(arrayString, 1);\n\treturn result;\n}\n\nexport function makePgArray(array: any[]): string {\n\treturn `{${\n\t\tarray.map((item) => {\n\t\t\tif (Array.isArray(item)) {\n\t\t\t\treturn makePgArray(item);\n\t\t\t}\n\n\t\t\tif (typeof item === 'string') {\n\t\t\t\treturn `\"${item.replace(/\\\\/g, '\\\\\\\\').replace(/\"/g, '\\\\\"')}\"`;\n\t\t\t}\n\n\t\t\treturn `${item}`;\n\t\t}).join(',')\n\t}}`;\n}\n", "import { entityKind } from './entity.ts';\nimport type { SQL, SQLWrapper } from './sql/sql.ts';\n\nexport interface Subquery<\n\t// eslint-disable-next-line @typescript-eslint/no-unused-vars\n\tTAlias extends string = string,\n\t// eslint-disable-next-line @typescript-eslint/no-unused-vars\n\tTSelectedFields extends Record = Record,\n> extends SQLWrapper {\n\t// SQLWrapper runtime implementation is defined in 'sql/sql.ts'\n}\nexport class Subquery<\n\tTAlias extends string = string,\n\tTSelectedFields extends Record = Record,\n> implements SQLWrapper {\n\tstatic readonly [entityKind]: string = 'Subquery';\n\n\tdeclare _: {\n\t\tbrand: 'Subquery';\n\t\tsql: SQL;\n\t\tselectedFields: TSelectedFields;\n\t\talias: TAlias;\n\t\tisWith: boolean;\n\t\tusedTables?: string[];\n\t};\n\n\tconstructor(sql: SQL, fields: TSelectedFields, alias: string, isWith = false, usedTables: string[] = []) {\n\t\tthis._ = {\n\t\t\tbrand: 'Subquery',\n\t\t\tsql,\n\t\t\tselectedFields: fields as TSelectedFields,\n\t\t\talias: alias as TAlias,\n\t\t\tisWith,\n\t\t\tusedTables,\n\t\t};\n\t}\n\n\t// getSQL(): SQL {\n\t// \treturn new SQL([this]);\n\t// }\n}\n\nexport class WithSubquery<\n\tTAlias extends string = string,\n\tTSelection extends Record = Record,\n> extends Subquery {\n\tstatic override readonly [entityKind]: string = 'WithSubquery';\n}\n\nexport type WithSubqueryWithoutSelection = WithSubquery;\n", "import type { Span, Tracer } from '@opentelemetry/api';\nimport { iife } from '~/tracing-utils.ts';\nimport { npmVersion } from '~/version.ts';\n\nlet otel: typeof import('@opentelemetry/api') | undefined;\nlet rawTracer: Tracer | undefined;\n// try {\n// \totel = await import('@opentelemetry/api');\n// } catch (err: any) {\n// \tif (err.code !== 'MODULE_NOT_FOUND' && err.code !== 'ERR_MODULE_NOT_FOUND') {\n// \t\tthrow err;\n// \t}\n// }\n\ntype SpanName =\n\t| 'drizzle.operation'\n\t| 'drizzle.prepareQuery'\n\t| 'drizzle.buildSQL'\n\t| 'drizzle.execute'\n\t| 'drizzle.driver.execute'\n\t| 'drizzle.mapResponse';\n\n/** @internal */\nexport const tracer = {\n\tstartActiveSpan unknown>(name: SpanName, fn: F): ReturnType {\n\t\tif (!otel) {\n\t\t\treturn fn() as ReturnType;\n\t\t}\n\n\t\tif (!rawTracer) {\n\t\t\trawTracer = otel.trace.getTracer('drizzle-orm', npmVersion);\n\t\t}\n\n\t\treturn iife(\n\t\t\t(otel, rawTracer) =>\n\t\t\t\trawTracer.startActiveSpan(\n\t\t\t\t\tname,\n\t\t\t\t\t((span: Span) => {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\treturn fn(span);\n\t\t\t\t\t\t} catch (e) {\n\t\t\t\t\t\t\tspan.setStatus({\n\t\t\t\t\t\t\t\tcode: otel.SpanStatusCode.ERROR,\n\t\t\t\t\t\t\t\tmessage: e instanceof Error ? e.message : 'Unknown error', // eslint-disable-line no-instanceof/no-instanceof\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tthrow e;\n\t\t\t\t\t\t} finally {\n\t\t\t\t\t\t\tspan.end();\n\t\t\t\t\t\t}\n\t\t\t\t\t}) as F,\n\t\t\t\t),\n\t\t\totel,\n\t\t\trawTracer,\n\t\t);\n\t},\n};\n", "// package.json\nvar version = \"0.45.1\";\n\n// src/version.ts\nvar compatibilityVersion = 10;\nexport {\n compatibilityVersion,\n version as npmVersion\n};\n", "export const ViewBaseConfig = Symbol.for('drizzle:ViewBaseConfig');\n", "import { type AnyColumn, Column, type GetColumnData } from '~/column.ts';\nimport { is } from '~/entity.ts';\nimport { Table } from '~/table.ts';\nimport {\n\tisDriverValueEncoder,\n\tisSQLWrapper,\n\tParam,\n\tPlaceholder,\n\tSQL,\n\tsql,\n\ttype SQLChunk,\n\ttype SQLWrapper,\n\tStringChunk,\n\tView,\n} from '../sql.ts';\n\nexport function bindIfParam(value: unknown, column: SQLWrapper): SQLChunk {\n\tif (\n\t\tisDriverValueEncoder(column)\n\t\t&& !isSQLWrapper(value)\n\t\t&& !is(value, Param)\n\t\t&& !is(value, Placeholder)\n\t\t&& !is(value, Column)\n\t\t&& !is(value, Table)\n\t\t&& !is(value, View)\n\t) {\n\t\treturn new Param(value, column);\n\t}\n\treturn value as SQLChunk;\n}\n\nexport interface BinaryOperator {\n\t(\n\t\tleft: TColumn,\n\t\tright: GetColumnData | SQLWrapper,\n\t): SQL;\n\t(left: SQL.Aliased, right: T | SQLWrapper): SQL;\n\t(\n\t\tleft: Exclude,\n\t\tright: unknown,\n\t): SQL;\n}\n\n/**\n * Test that two values are equal.\n *\n * Remember that the SQL standard dictates that\n * two NULL values are not equal, so if you want to test\n * whether a value is null, you may want to use\n * `isNull` instead.\n *\n * ## Examples\n *\n * ```ts\n * // Select cars made by Ford\n * db.select().from(cars)\n * .where(eq(cars.make, 'Ford'))\n * ```\n *\n * @see isNull for a way to test equality to NULL.\n */\nexport const eq: BinaryOperator = (left: SQLWrapper, right: unknown): SQL => {\n\treturn sql`${left} = ${bindIfParam(right, left)}`;\n};\n\n/**\n * Test that two values are not equal.\n *\n * Remember that the SQL standard dictates that\n * two NULL values are not equal, so if you want to test\n * whether a value is not null, you may want to use\n * `isNotNull` instead.\n *\n * ## Examples\n *\n * ```ts\n * // Select cars not made by Ford\n * db.select().from(cars)\n * .where(ne(cars.make, 'Ford'))\n * ```\n *\n * @see isNotNull for a way to test whether a value is not null.\n */\nexport const ne: BinaryOperator = (left: SQLWrapper, right: unknown): SQL => {\n\treturn sql`${left} <> ${bindIfParam(right, left)}`;\n};\n\n/**\n * Combine a list of conditions with the `and` operator. Conditions\n * that are equal `undefined` are automatically ignored.\n *\n * ## Examples\n *\n * ```ts\n * db.select().from(cars)\n * .where(\n * and(\n * eq(cars.make, 'Volvo'),\n * eq(cars.year, 1950),\n * )\n * )\n * ```\n */\nexport function and(...conditions: (SQLWrapper | undefined)[]): SQL | undefined;\nexport function and(\n\t...unfilteredConditions: (SQLWrapper | undefined)[]\n): SQL | undefined {\n\tconst conditions = unfilteredConditions.filter(\n\t\t(c): c is Exclude => c !== undefined,\n\t);\n\n\tif (conditions.length === 0) {\n\t\treturn undefined;\n\t}\n\n\tif (conditions.length === 1) {\n\t\treturn new SQL(conditions);\n\t}\n\n\treturn new SQL([\n\t\tnew StringChunk('('),\n\t\tsql.join(conditions, new StringChunk(' and ')),\n\t\tnew StringChunk(')'),\n\t]);\n}\n\n/**\n * Combine a list of conditions with the `or` operator. Conditions\n * that are equal `undefined` are automatically ignored.\n *\n * ## Examples\n *\n * ```ts\n * db.select().from(cars)\n * .where(\n * or(\n * eq(cars.make, 'GM'),\n * eq(cars.make, 'Ford'),\n * )\n * )\n * ```\n */\nexport function or(...conditions: (SQLWrapper | undefined)[]): SQL | undefined;\nexport function or(\n\t...unfilteredConditions: (SQLWrapper | undefined)[]\n): SQL | undefined {\n\tconst conditions = unfilteredConditions.filter(\n\t\t(c): c is Exclude => c !== undefined,\n\t);\n\n\tif (conditions.length === 0) {\n\t\treturn undefined;\n\t}\n\n\tif (conditions.length === 1) {\n\t\treturn new SQL(conditions);\n\t}\n\n\treturn new SQL([\n\t\tnew StringChunk('('),\n\t\tsql.join(conditions, new StringChunk(' or ')),\n\t\tnew StringChunk(')'),\n\t]);\n}\n\n/**\n * Negate the meaning of an expression using the `not` keyword.\n *\n * ## Examples\n *\n * ```ts\n * // Select cars _not_ made by GM or Ford.\n * db.select().from(cars)\n * .where(not(inArray(cars.make, ['GM', 'Ford'])))\n * ```\n */\nexport function not(condition: SQLWrapper): SQL {\n\treturn sql`not ${condition}`;\n}\n\n/**\n * Test that the first expression passed is greater than\n * the second expression.\n *\n * ## Examples\n *\n * ```ts\n * // Select cars made after 2000.\n * db.select().from(cars)\n * .where(gt(cars.year, 2000))\n * ```\n *\n * @see gte for greater-than-or-equal\n */\nexport const gt: BinaryOperator = (left: SQLWrapper, right: unknown): SQL => {\n\treturn sql`${left} > ${bindIfParam(right, left)}`;\n};\n\n/**\n * Test that the first expression passed is greater than\n * or equal to the second expression. Use `gt` to\n * test whether an expression is strictly greater\n * than another.\n *\n * ## Examples\n *\n * ```ts\n * // Select cars made on or after 2000.\n * db.select().from(cars)\n * .where(gte(cars.year, 2000))\n * ```\n *\n * @see gt for a strictly greater-than condition\n */\nexport const gte: BinaryOperator = (left: SQLWrapper, right: unknown): SQL => {\n\treturn sql`${left} >= ${bindIfParam(right, left)}`;\n};\n\n/**\n * Test that the first expression passed is less than\n * the second expression.\n *\n * ## Examples\n *\n * ```ts\n * // Select cars made before 2000.\n * db.select().from(cars)\n * .where(lt(cars.year, 2000))\n * ```\n *\n * @see lte for less-than-or-equal\n */\nexport const lt: BinaryOperator = (left: SQLWrapper, right: unknown): SQL => {\n\treturn sql`${left} < ${bindIfParam(right, left)}`;\n};\n\n/**\n * Test that the first expression passed is less than\n * or equal to the second expression.\n *\n * ## Examples\n *\n * ```ts\n * // Select cars made before 2000.\n * db.select().from(cars)\n * .where(lte(cars.year, 2000))\n * ```\n *\n * @see lt for a strictly less-than condition\n */\nexport const lte: BinaryOperator = (left: SQLWrapper, right: unknown): SQL => {\n\treturn sql`${left} <= ${bindIfParam(right, left)}`;\n};\n\n/**\n * Test whether the first parameter, a column or expression,\n * has a value from a list passed as the second argument.\n *\n * ## Examples\n *\n * ```ts\n * // Select cars made by Ford or GM.\n * db.select().from(cars)\n * .where(inArray(cars.make, ['Ford', 'GM']))\n * ```\n *\n * @see notInArray for the inverse of this test\n */\nexport function inArray(\n\tcolumn: SQL.Aliased,\n\tvalues: (T | Placeholder)[] | SQLWrapper,\n): SQL;\nexport function inArray(\n\tcolumn: TColumn,\n\tvalues: ReadonlyArray | Placeholder> | SQLWrapper,\n): SQL;\nexport function inArray(\n\tcolumn: Exclude,\n\tvalues: ReadonlyArray | SQLWrapper,\n): SQL;\nexport function inArray(\n\tcolumn: SQLWrapper,\n\tvalues: ReadonlyArray | SQLWrapper,\n): SQL {\n\tif (Array.isArray(values)) {\n\t\tif (values.length === 0) {\n\t\t\treturn sql`false`;\n\t\t}\n\t\treturn sql`${column} in ${values.map((v) => bindIfParam(v, column))}`;\n\t}\n\n\treturn sql`${column} in ${bindIfParam(values, column)}`;\n}\n\n/**\n * Test whether the first parameter, a column or expression,\n * has a value that is not present in a list passed as the\n * second argument.\n *\n * ## Examples\n *\n * ```ts\n * // Select cars made by any company except Ford or GM.\n * db.select().from(cars)\n * .where(notInArray(cars.make, ['Ford', 'GM']))\n * ```\n *\n * @see inArray for the inverse of this test\n */\nexport function notInArray(\n\tcolumn: SQL.Aliased,\n\tvalues: (T | Placeholder)[] | SQLWrapper,\n): SQL;\nexport function notInArray(\n\tcolumn: TColumn,\n\tvalues: (GetColumnData | Placeholder)[] | SQLWrapper,\n): SQL;\nexport function notInArray(\n\tcolumn: Exclude,\n\tvalues: (unknown | Placeholder)[] | SQLWrapper,\n): SQL;\nexport function notInArray(\n\tcolumn: SQLWrapper,\n\tvalues: (unknown | Placeholder)[] | SQLWrapper,\n): SQL {\n\tif (Array.isArray(values)) {\n\t\tif (values.length === 0) {\n\t\t\treturn sql`true`;\n\t\t}\n\t\treturn sql`${column} not in ${values.map((v) => bindIfParam(v, column))}`;\n\t}\n\n\treturn sql`${column} not in ${bindIfParam(values, column)}`;\n}\n\n/**\n * Test whether an expression is NULL. By the SQL standard,\n * NULL is neither equal nor not equal to itself, so\n * it's recommended to use `isNull` and `notIsNull` for\n * comparisons to NULL.\n *\n * ## Examples\n *\n * ```ts\n * // Select cars that have no discontinuedAt date.\n * db.select().from(cars)\n * .where(isNull(cars.discontinuedAt))\n * ```\n *\n * @see isNotNull for the inverse of this test\n */\nexport function isNull(value: SQLWrapper): SQL {\n\treturn sql`${value} is null`;\n}\n\n/**\n * Test whether an expression is not NULL. By the SQL standard,\n * NULL is neither equal nor not equal to itself, so\n * it's recommended to use `isNull` and `notIsNull` for\n * comparisons to NULL.\n *\n * ## Examples\n *\n * ```ts\n * // Select cars that have been discontinued.\n * db.select().from(cars)\n * .where(isNotNull(cars.discontinuedAt))\n * ```\n *\n * @see isNull for the inverse of this test\n */\nexport function isNotNull(value: SQLWrapper): SQL {\n\treturn sql`${value} is not null`;\n}\n\n/**\n * Test whether a subquery evaluates to have any rows.\n *\n * ## Examples\n *\n * ```ts\n * // Users whose `homeCity` column has a match in a cities\n * // table.\n * db\n * .select()\n * .from(users)\n * .where(\n * exists(db.select()\n * .from(cities)\n * .where(eq(users.homeCity, cities.id))),\n * );\n * ```\n *\n * @see notExists for the inverse of this test\n */\nexport function exists(subquery: SQLWrapper): SQL {\n\treturn sql`exists ${subquery}`;\n}\n\n/**\n * Test whether a subquery doesn't include any result\n * rows.\n *\n * ## Examples\n *\n * ```ts\n * // Users whose `homeCity` column doesn't match\n * // a row in the cities table.\n * db\n * .select()\n * .from(users)\n * .where(\n * notExists(db.select()\n * .from(cities)\n * .where(eq(users.homeCity, cities.id))),\n * );\n * ```\n *\n * @see exists for the inverse of this test\n */\nexport function notExists(subquery: SQLWrapper): SQL {\n\treturn sql`not exists ${subquery}`;\n}\n\n/**\n * Test whether an expression is between two values. This\n * is an easier way to express range tests, which would be\n * expressed mathematically as `x <= a <= y` but in SQL\n * would have to be like `a >= x AND a <= y`.\n *\n * Between is inclusive of the endpoints: if `column`\n * is equal to `min` or `max`, it will be TRUE.\n *\n * ## Examples\n *\n * ```ts\n * // Select cars made between 1990 and 2000\n * db.select().from(cars)\n * .where(between(cars.year, 1990, 2000))\n * ```\n *\n * @see notBetween for the inverse of this test\n */\nexport function between(\n\tcolumn: SQL.Aliased,\n\tmin: T | SQLWrapper,\n\tmax: T | SQLWrapper,\n): SQL;\nexport function between(\n\tcolumn: TColumn,\n\tmin: GetColumnData | SQLWrapper,\n\tmax: GetColumnData | SQLWrapper,\n): SQL;\nexport function between(\n\tcolumn: Exclude,\n\tmin: unknown,\n\tmax: unknown,\n): SQL;\nexport function between(column: SQLWrapper, min: unknown, max: unknown): SQL {\n\treturn sql`${column} between ${bindIfParam(min, column)} and ${\n\t\tbindIfParam(\n\t\t\tmax,\n\t\t\tcolumn,\n\t\t)\n\t}`;\n}\n\n/**\n * Test whether an expression is not between two values.\n *\n * This, like `between`, includes its endpoints, so if\n * the `column` is equal to `min` or `max`, in this case\n * it will evaluate to FALSE.\n *\n * ## Examples\n *\n * ```ts\n * // Exclude cars made in the 1970s\n * db.select().from(cars)\n * .where(notBetween(cars.year, 1970, 1979))\n * ```\n *\n * @see between for the inverse of this test\n */\nexport function notBetween(\n\tcolumn: SQL.Aliased,\n\tmin: T | SQLWrapper,\n\tmax: T | SQLWrapper,\n): SQL;\nexport function notBetween(\n\tcolumn: TColumn,\n\tmin: GetColumnData | SQLWrapper,\n\tmax: GetColumnData | SQLWrapper,\n): SQL;\nexport function notBetween(\n\tcolumn: Exclude,\n\tmin: unknown,\n\tmax: unknown,\n): SQL;\nexport function notBetween(\n\tcolumn: SQLWrapper,\n\tmin: unknown,\n\tmax: unknown,\n): SQL {\n\treturn sql`${column} not between ${\n\t\tbindIfParam(\n\t\t\tmin,\n\t\t\tcolumn,\n\t\t)\n\t} and ${bindIfParam(max, column)}`;\n}\n\n/**\n * Compare a column to a pattern, which can include `%` and `_`\n * characters to match multiple variations. Including `%`\n * in the pattern matches zero or more characters, and including\n * `_` will match a single character.\n *\n * ## Examples\n *\n * ```ts\n * // Select all cars with 'Turbo' in their names.\n * db.select().from(cars)\n * .where(like(cars.name, '%Turbo%'))\n * ```\n *\n * @see ilike for a case-insensitive version of this condition\n */\nexport function like(column: Column | SQL.Aliased | SQL, value: string | SQLWrapper): SQL {\n\treturn sql`${column} like ${value}`;\n}\n\n/**\n * The inverse of like - this tests that a given column\n * does not match a pattern, which can include `%` and `_`\n * characters to match multiple variations. Including `%`\n * in the pattern matches zero or more characters, and including\n * `_` will match a single character.\n *\n * ## Examples\n *\n * ```ts\n * // Select all cars that don't have \"ROver\" in their name.\n * db.select().from(cars)\n * .where(notLike(cars.name, '%Rover%'))\n * ```\n *\n * @see like for the inverse condition\n * @see notIlike for a case-insensitive version of this condition\n */\nexport function notLike(column: Column | SQL.Aliased | SQL, value: string | SQLWrapper): SQL {\n\treturn sql`${column} not like ${value}`;\n}\n\n/**\n * Case-insensitively compare a column to a pattern,\n * which can include `%` and `_`\n * characters to match multiple variations. Including `%`\n * in the pattern matches zero or more characters, and including\n * `_` will match a single character.\n *\n * Unlike like, this performs a case-insensitive comparison.\n *\n * ## Examples\n *\n * ```ts\n * // Select all cars with 'Turbo' in their names.\n * db.select().from(cars)\n * .where(ilike(cars.name, '%Turbo%'))\n * ```\n *\n * @see like for a case-sensitive version of this condition\n */\nexport function ilike(column: Column | SQL.Aliased | SQL, value: string | SQLWrapper): SQL {\n\treturn sql`${column} ilike ${value}`;\n}\n\n/**\n * The inverse of ilike - this case-insensitively tests that a given column\n * does not match a pattern, which can include `%` and `_`\n * characters to match multiple variations. Including `%`\n * in the pattern matches zero or more characters, and including\n * `_` will match a single character.\n *\n * ## Examples\n *\n * ```ts\n * // Select all cars that don't have \"Rover\" in their name.\n * db.select().from(cars)\n * .where(notLike(cars.name, '%Rover%'))\n * ```\n *\n * @see ilike for the inverse condition\n * @see notLike for a case-sensitive version of this condition\n */\nexport function notIlike(column: Column | SQL.Aliased | SQL, value: string | SQLWrapper): SQL {\n\treturn sql`${column} not ilike ${value}`;\n}\n\n/**\n * Test that a column or expression contains all elements of\n * the list passed as the second argument.\n *\n * ## Throws\n *\n * The argument passed in the second array can't be empty:\n * if an empty is provided, this method will throw.\n *\n * ## Examples\n *\n * ```ts\n * // Select posts where its tags contain \"Typescript\" and \"ORM\".\n * db.select().from(posts)\n * .where(arrayContains(posts.tags, ['Typescript', 'ORM']))\n * ```\n *\n * @see arrayContained to find if an array contains all elements of a column or expression\n * @see arrayOverlaps to find if a column or expression contains any elements of an array\n */\nexport function arrayContains(\n\tcolumn: SQL.Aliased,\n\tvalues: (T | Placeholder) | SQLWrapper,\n): SQL;\nexport function arrayContains(\n\tcolumn: TColumn,\n\tvalues: (GetColumnData | Placeholder) | SQLWrapper,\n): SQL;\nexport function arrayContains(\n\tcolumn: Exclude,\n\tvalues: (unknown | Placeholder)[] | SQLWrapper,\n): SQL;\nexport function arrayContains(\n\tcolumn: SQLWrapper,\n\tvalues: (unknown | Placeholder)[] | SQLWrapper,\n): SQL {\n\tif (Array.isArray(values)) {\n\t\tif (values.length === 0) {\n\t\t\tthrow new Error('arrayContains requires at least one value');\n\t\t}\n\t\tconst array = sql`${bindIfParam(values, column)}`;\n\t\treturn sql`${column} @> ${array}`;\n\t}\n\n\treturn sql`${column} @> ${bindIfParam(values, column)}`;\n}\n\n/**\n * Test that the list passed as the second argument contains\n * all elements of a column or expression.\n *\n * ## Throws\n *\n * The argument passed in the second array can't be empty:\n * if an empty is provided, this method will throw.\n *\n * ## Examples\n *\n * ```ts\n * // Select posts where its tags contain \"Typescript\", \"ORM\" or both,\n * // but filtering posts that have additional tags.\n * db.select().from(posts)\n * .where(arrayContained(posts.tags, ['Typescript', 'ORM']))\n * ```\n *\n * @see arrayContains to find if a column or expression contains all elements of an array\n * @see arrayOverlaps to find if a column or expression contains any elements of an array\n */\nexport function arrayContained(\n\tcolumn: SQL.Aliased,\n\tvalues: (T | Placeholder) | SQLWrapper,\n): SQL;\nexport function arrayContained(\n\tcolumn: TColumn,\n\tvalues: (GetColumnData | Placeholder) | SQLWrapper,\n): SQL;\nexport function arrayContained(\n\tcolumn: Exclude,\n\tvalues: (unknown | Placeholder)[] | SQLWrapper,\n): SQL;\nexport function arrayContained(\n\tcolumn: SQLWrapper,\n\tvalues: (unknown | Placeholder)[] | SQLWrapper,\n): SQL {\n\tif (Array.isArray(values)) {\n\t\tif (values.length === 0) {\n\t\t\tthrow new Error('arrayContained requires at least one value');\n\t\t}\n\t\tconst array = sql`${bindIfParam(values, column)}`;\n\t\treturn sql`${column} <@ ${array}`;\n\t}\n\n\treturn sql`${column} <@ ${bindIfParam(values, column)}`;\n}\n\n/**\n * Test that a column or expression contains any elements of\n * the list passed as the second argument.\n *\n * ## Throws\n *\n * The argument passed in the second array can't be empty:\n * if an empty is provided, this method will throw.\n *\n * ## Examples\n *\n * ```ts\n * // Select posts where its tags contain \"Typescript\", \"ORM\" or both.\n * db.select().from(posts)\n * .where(arrayOverlaps(posts.tags, ['Typescript', 'ORM']))\n * ```\n *\n * @see arrayContains to find if a column or expression contains all elements of an array\n * @see arrayContained to find if an array contains all elements of a column or expression\n */\nexport function arrayOverlaps(\n\tcolumn: SQL.Aliased,\n\tvalues: (T | Placeholder) | SQLWrapper,\n): SQL;\nexport function arrayOverlaps(\n\tcolumn: TColumn,\n\tvalues: (GetColumnData | Placeholder) | SQLWrapper,\n): SQL;\nexport function arrayOverlaps(\n\tcolumn: Exclude,\n\tvalues: (unknown | Placeholder)[] | SQLWrapper,\n): SQL;\nexport function arrayOverlaps(\n\tcolumn: SQLWrapper,\n\tvalues: (unknown | Placeholder)[] | SQLWrapper,\n): SQL {\n\tif (Array.isArray(values)) {\n\t\tif (values.length === 0) {\n\t\t\tthrow new Error('arrayOverlaps requires at least one value');\n\t\t}\n\t\tconst array = sql`${bindIfParam(values, column)}`;\n\t\treturn sql`${column} && ${array}`;\n\t}\n\n\treturn sql`${column} && ${bindIfParam(values, column)}`;\n}\n", "import type { AnyColumn } from '../../column.ts';\nimport type { SQL, SQLWrapper } from '../sql.ts';\nimport { sql } from '../sql.ts';\n\n/**\n * Used in sorting, this specifies that the given\n * column or expression should be sorted in ascending\n * order. By the SQL standard, ascending order is the\n * default, so it is not usually necessary to specify\n * ascending sort order.\n *\n * ## Examples\n *\n * ```ts\n * // Return cars, starting with the oldest models\n * // and going in ascending order to the newest.\n * db.select().from(cars)\n * .orderBy(asc(cars.year));\n * ```\n *\n * @see desc to sort in descending order\n */\nexport function asc(column: AnyColumn | SQLWrapper): SQL {\n\treturn sql`${column} asc`;\n}\n\n/**\n * Used in sorting, this specifies that the given\n * column or expression should be sorted in descending\n * order.\n *\n * ## Examples\n *\n * ```ts\n * // Select users, with the most recently created\n * // records coming first.\n * db.select().from(users)\n * .orderBy(desc(users.createdAt));\n * ```\n *\n * @see asc to sort in ascending order\n */\nexport function desc(column: AnyColumn | SQLWrapper): SQL {\n\treturn sql`${column} desc`;\n}\n", "import type { Cache } from '~/cache/core/cache.ts';\nimport { entityKind } from '~/entity.ts';\nimport type { TypedQueryBuilder } from '~/query-builders/query-builder.ts';\nimport type { ExtractTablesWithRelations, RelationalSchemaConfig, TablesRelationalConfig } from '~/relations.ts';\nimport { SelectionProxyHandler } from '~/selection-proxy.ts';\nimport { type ColumnsSelection, type SQL, sql, type SQLWrapper } from '~/sql/sql.ts';\nimport type { SQLiteAsyncDialect, SQLiteSyncDialect } from '~/sqlite-core/dialect.ts';\nimport {\n\tQueryBuilder,\n\tSQLiteDeleteBase,\n\tSQLiteInsertBuilder,\n\tSQLiteSelectBuilder,\n\tSQLiteUpdateBuilder,\n} from '~/sqlite-core/query-builders/index.ts';\nimport type {\n\tDBResult,\n\tResult,\n\tSQLiteSession,\n\tSQLiteTransaction,\n\tSQLiteTransactionConfig,\n} from '~/sqlite-core/session.ts';\nimport type { SQLiteTable } from '~/sqlite-core/table.ts';\nimport { WithSubquery } from '~/subquery.ts';\nimport type { DrizzleTypeError } from '~/utils.ts';\nimport { SQLiteCountBuilder } from './query-builders/count.ts';\nimport { RelationalQueryBuilder } from './query-builders/query.ts';\nimport { SQLiteRaw } from './query-builders/raw.ts';\nimport type { SelectedFields } from './query-builders/select.types.ts';\nimport type { WithBuilder } from './subquery.ts';\nimport type { SQLiteViewBase } from './view-base.ts';\n\nexport class BaseSQLiteDatabase<\n\tTResultKind extends 'sync' | 'async',\n\tTRunResult,\n\tTFullSchema extends Record = Record,\n\tTSchema extends TablesRelationalConfig = ExtractTablesWithRelations,\n> {\n\tstatic readonly [entityKind]: string = 'BaseSQLiteDatabase';\n\n\tdeclare readonly _: {\n\t\treadonly schema: TSchema | undefined;\n\t\treadonly fullSchema: TFullSchema;\n\t\treadonly tableNamesMap: Record;\n\t};\n\n\tquery: TFullSchema extends Record\n\t\t? DrizzleTypeError<'Seems like the schema generic is missing - did you forget to add it to your DB type?'>\n\t\t: {\n\t\t\t[K in keyof TSchema]: RelationalQueryBuilder;\n\t\t};\n\n\tconstructor(\n\t\tprivate resultKind: TResultKind,\n\t\t/** @internal */\n\t\treadonly dialect: { sync: SQLiteSyncDialect; async: SQLiteAsyncDialect }[TResultKind],\n\t\t/** @internal */\n\t\treadonly session: SQLiteSession,\n\t\tschema: RelationalSchemaConfig | undefined,\n\t) {\n\t\tthis._ = schema\n\t\t\t? {\n\t\t\t\tschema: schema.schema,\n\t\t\t\tfullSchema: schema.fullSchema as TFullSchema,\n\t\t\t\ttableNamesMap: schema.tableNamesMap,\n\t\t\t}\n\t\t\t: {\n\t\t\t\tschema: undefined,\n\t\t\t\tfullSchema: {} as TFullSchema,\n\t\t\t\ttableNamesMap: {},\n\t\t\t};\n\t\tthis.query = {} as typeof this['query'];\n\t\tconst query = this.query as {\n\t\t\t[K in keyof TSchema]: RelationalQueryBuilder;\n\t\t};\n\t\tif (this._.schema) {\n\t\t\tfor (const [tableName, columns] of Object.entries(this._.schema)) {\n\t\t\t\tquery[tableName as keyof TSchema] = new RelationalQueryBuilder(\n\t\t\t\t\tresultKind,\n\t\t\t\t\tschema!.fullSchema,\n\t\t\t\t\tthis._.schema,\n\t\t\t\t\tthis._.tableNamesMap,\n\t\t\t\t\tschema!.fullSchema[tableName] as SQLiteTable,\n\t\t\t\t\tcolumns,\n\t\t\t\t\tdialect,\n\t\t\t\t\tsession as SQLiteSession as any,\n\t\t\t\t) as typeof query[keyof TSchema];\n\t\t\t}\n\t\t}\n\t\tthis.$cache = { invalidate: async (_params: any) => {} };\n\t}\n\n\t/**\n\t * Creates a subquery that defines a temporary named result set as a CTE.\n\t *\n\t * It is useful for breaking down complex queries into simpler parts and for reusing the result set in subsequent parts of the query.\n\t *\n\t * See docs: {@link https://orm.drizzle.team/docs/select#with-clause}\n\t *\n\t * @param alias The alias for the subquery.\n\t *\n\t * Failure to provide an alias will result in a DrizzleTypeError, preventing the subquery from being referenced in other queries.\n\t *\n\t * @example\n\t *\n\t * ```ts\n\t * // Create a subquery with alias 'sq' and use it in the select query\n\t * const sq = db.$with('sq').as(db.select().from(users).where(eq(users.id, 42)));\n\t *\n\t * const result = await db.with(sq).select().from(sq);\n\t * ```\n\t *\n\t * To select arbitrary SQL values as fields in a CTE and reference them in other CTEs or in the main query, you need to add aliases to them:\n\t *\n\t * ```ts\n\t * // Select an arbitrary SQL value as a field in a CTE and reference it in the main query\n\t * const sq = db.$with('sq').as(db.select({\n\t * name: sql`upper(${users.name})`.as('name'),\n\t * })\n\t * .from(users));\n\t *\n\t * const result = await db.with(sq).select({ name: sq.name }).from(sq);\n\t * ```\n\t */\n\t$with: WithBuilder = (alias: string, selection?: ColumnsSelection) => {\n\t\tconst self = this;\n\t\tconst as = (\n\t\t\tqb:\n\t\t\t\t| TypedQueryBuilder\n\t\t\t\t| SQL\n\t\t\t\t| ((qb: QueryBuilder) => TypedQueryBuilder | SQL),\n\t\t) => {\n\t\t\tif (typeof qb === 'function') {\n\t\t\t\tqb = qb(new QueryBuilder(self.dialect));\n\t\t\t}\n\n\t\t\treturn new Proxy(\n\t\t\t\tnew WithSubquery(\n\t\t\t\t\tqb.getSQL(),\n\t\t\t\t\tselection ?? ('getSelectedFields' in qb ? qb.getSelectedFields() ?? {} : {}) as SelectedFields,\n\t\t\t\t\talias,\n\t\t\t\t\ttrue,\n\t\t\t\t),\n\t\t\t\tnew SelectionProxyHandler({ alias, sqlAliasedBehavior: 'alias', sqlBehavior: 'error' }),\n\t\t\t);\n\t\t};\n\t\treturn { as };\n\t};\n\n\t$count(\n\t\tsource: SQLiteTable | SQLiteViewBase | SQL | SQLWrapper,\n\t\tfilters?: SQL,\n\t) {\n\t\treturn new SQLiteCountBuilder({ source, filters, session: this.session });\n\t}\n\n\t/**\n\t * Incorporates a previously defined CTE (using `$with`) into the main query.\n\t *\n\t * This method allows the main query to reference a temporary named result set.\n\t *\n\t * See docs: {@link https://orm.drizzle.team/docs/select#with-clause}\n\t *\n\t * @param queries The CTEs to incorporate into the main query.\n\t *\n\t * @example\n\t *\n\t * ```ts\n\t * // Define a subquery 'sq' as a CTE using $with\n\t * const sq = db.$with('sq').as(db.select().from(users).where(eq(users.id, 42)));\n\t *\n\t * // Incorporate the CTE 'sq' into the main query and select from it\n\t * const result = await db.with(sq).select().from(sq);\n\t * ```\n\t */\n\twith(...queries: WithSubquery[]) {\n\t\tconst self = this;\n\n\t\t/**\n\t\t * Creates a select query.\n\t\t *\n\t\t * Calling this method with no arguments will select all columns from the table. Pass a selection object to specify the columns you want to select.\n\t\t *\n\t\t * Use `.from()` method to specify which table to select from.\n\t\t *\n\t\t * See docs: {@link https://orm.drizzle.team/docs/select}\n\t\t *\n\t\t * @param fields The selection object.\n\t\t *\n\t\t * @example\n\t\t *\n\t\t * ```ts\n\t\t * // Select all columns and all rows from the 'cars' table\n\t\t * const allCars: Car[] = await db.select().from(cars);\n\t\t *\n\t\t * // Select specific columns and all rows from the 'cars' table\n\t\t * const carsIdsAndBrands: { id: number; brand: string }[] = await db.select({\n\t\t * id: cars.id,\n\t\t * brand: cars.brand\n\t\t * })\n\t\t * .from(cars);\n\t\t * ```\n\t\t *\n\t\t * Like in SQL, you can use arbitrary expressions as selection fields, not just table columns:\n\t\t *\n\t\t * ```ts\n\t\t * // Select specific columns along with expression and all rows from the 'cars' table\n\t\t * const carsIdsAndLowerNames: { id: number; lowerBrand: string }[] = await db.select({\n\t\t * id: cars.id,\n\t\t * lowerBrand: sql`lower(${cars.brand})`,\n\t\t * })\n\t\t * .from(cars);\n\t\t * ```\n\t\t */\n\t\tfunction select(): SQLiteSelectBuilder;\n\t\tfunction select(\n\t\t\tfields: TSelection,\n\t\t): SQLiteSelectBuilder;\n\t\tfunction select(\n\t\t\tfields?: SelectedFields,\n\t\t): SQLiteSelectBuilder {\n\t\t\treturn new SQLiteSelectBuilder({\n\t\t\t\tfields: fields ?? undefined,\n\t\t\t\tsession: self.session,\n\t\t\t\tdialect: self.dialect,\n\t\t\t\twithList: queries,\n\t\t\t});\n\t\t}\n\n\t\t/**\n\t\t * Adds `distinct` expression to the select query.\n\t\t *\n\t\t * Calling this method will return only unique values. When multiple columns are selected, it returns rows with unique combinations of values in these columns.\n\t\t *\n\t\t * Use `.from()` method to specify which table to select from.\n\t\t *\n\t\t * See docs: {@link https://orm.drizzle.team/docs/select#distinct}\n\t\t *\n\t\t * @param fields The selection object.\n\t\t *\n\t\t * @example\n\t\t *\n\t\t * ```ts\n\t\t * // Select all unique rows from the 'cars' table\n\t\t * await db.selectDistinct()\n\t\t * .from(cars)\n\t\t * .orderBy(cars.id, cars.brand, cars.color);\n\t\t *\n\t\t * // Select all unique brands from the 'cars' table\n\t\t * await db.selectDistinct({ brand: cars.brand })\n\t\t * .from(cars)\n\t\t * .orderBy(cars.brand);\n\t\t * ```\n\t\t */\n\t\tfunction selectDistinct(): SQLiteSelectBuilder;\n\t\tfunction selectDistinct(\n\t\t\tfields: TSelection,\n\t\t): SQLiteSelectBuilder;\n\t\tfunction selectDistinct(\n\t\t\tfields?: SelectedFields,\n\t\t): SQLiteSelectBuilder {\n\t\t\treturn new SQLiteSelectBuilder({\n\t\t\t\tfields: fields ?? undefined,\n\t\t\t\tsession: self.session,\n\t\t\t\tdialect: self.dialect,\n\t\t\t\twithList: queries,\n\t\t\t\tdistinct: true,\n\t\t\t});\n\t\t}\n\n\t\t/**\n\t\t * Creates an update query.\n\t\t *\n\t\t * Calling this method without `.where()` clause will update all rows in a table. The `.where()` clause specifies which rows should be updated.\n\t\t *\n\t\t * Use `.set()` method to specify which values to update.\n\t\t *\n\t\t * See docs: {@link https://orm.drizzle.team/docs/update}\n\t\t *\n\t\t * @param table The table to update.\n\t\t *\n\t\t * @example\n\t\t *\n\t\t * ```ts\n\t\t * // Update all rows in the 'cars' table\n\t\t * await db.update(cars).set({ color: 'red' });\n\t\t *\n\t\t * // Update rows with filters and conditions\n\t\t * await db.update(cars).set({ color: 'red' }).where(eq(cars.brand, 'BMW'));\n\t\t *\n\t\t * // Update with returning clause\n\t\t * const updatedCar: Car[] = await db.update(cars)\n\t\t * .set({ color: 'red' })\n\t\t * .where(eq(cars.id, 1))\n\t\t * .returning();\n\t\t * ```\n\t\t */\n\t\tfunction update(table: TTable): SQLiteUpdateBuilder {\n\t\t\treturn new SQLiteUpdateBuilder(table, self.session, self.dialect, queries);\n\t\t}\n\n\t\t/**\n\t\t * Creates an insert query.\n\t\t *\n\t\t * Calling this method will create new rows in a table. Use `.values()` method to specify which values to insert.\n\t\t *\n\t\t * See docs: {@link https://orm.drizzle.team/docs/insert}\n\t\t *\n\t\t * @param table The table to insert into.\n\t\t *\n\t\t * @example\n\t\t *\n\t\t * ```ts\n\t\t * // Insert one row\n\t\t * await db.insert(cars).values({ brand: 'BMW' });\n\t\t *\n\t\t * // Insert multiple rows\n\t\t * await db.insert(cars).values([{ brand: 'BMW' }, { brand: 'Porsche' }]);\n\t\t *\n\t\t * // Insert with returning clause\n\t\t * const insertedCar: Car[] = await db.insert(cars)\n\t\t * .values({ brand: 'BMW' })\n\t\t * .returning();\n\t\t * ```\n\t\t */\n\t\tfunction insert(into: TTable): SQLiteInsertBuilder {\n\t\t\treturn new SQLiteInsertBuilder(into, self.session, self.dialect, queries);\n\t\t}\n\n\t\t/**\n\t\t * Creates a delete query.\n\t\t *\n\t\t * Calling this method without `.where()` clause will delete all rows in a table. The `.where()` clause specifies which rows should be deleted.\n\t\t *\n\t\t * See docs: {@link https://orm.drizzle.team/docs/delete}\n\t\t *\n\t\t * @param table The table to delete from.\n\t\t *\n\t\t * @example\n\t\t *\n\t\t * ```ts\n\t\t * // Delete all rows in the 'cars' table\n\t\t * await db.delete(cars);\n\t\t *\n\t\t * // Delete rows with filters and conditions\n\t\t * await db.delete(cars).where(eq(cars.color, 'green'));\n\t\t *\n\t\t * // Delete with returning clause\n\t\t * const deletedCar: Car[] = await db.delete(cars)\n\t\t * .where(eq(cars.id, 1))\n\t\t * .returning();\n\t\t * ```\n\t\t */\n\t\tfunction delete_(from: TTable): SQLiteDeleteBase {\n\t\t\treturn new SQLiteDeleteBase(from, self.session, self.dialect, queries);\n\t\t}\n\n\t\treturn { select, selectDistinct, update, insert, delete: delete_ };\n\t}\n\n\t/**\n\t * Creates a select query.\n\t *\n\t * Calling this method with no arguments will select all columns from the table. Pass a selection object to specify the columns you want to select.\n\t *\n\t * Use `.from()` method to specify which table to select from.\n\t *\n\t * See docs: {@link https://orm.drizzle.team/docs/select}\n\t *\n\t * @param fields The selection object.\n\t *\n\t * @example\n\t *\n\t * ```ts\n\t * // Select all columns and all rows from the 'cars' table\n\t * const allCars: Car[] = await db.select().from(cars);\n\t *\n\t * // Select specific columns and all rows from the 'cars' table\n\t * const carsIdsAndBrands: { id: number; brand: string }[] = await db.select({\n\t * id: cars.id,\n\t * brand: cars.brand\n\t * })\n\t * .from(cars);\n\t * ```\n\t *\n\t * Like in SQL, you can use arbitrary expressions as selection fields, not just table columns:\n\t *\n\t * ```ts\n\t * // Select specific columns along with expression and all rows from the 'cars' table\n\t * const carsIdsAndLowerNames: { id: number; lowerBrand: string }[] = await db.select({\n\t * id: cars.id,\n\t * lowerBrand: sql`lower(${cars.brand})`,\n\t * })\n\t * .from(cars);\n\t * ```\n\t */\n\tselect(): SQLiteSelectBuilder;\n\tselect(\n\t\tfields: TSelection,\n\t): SQLiteSelectBuilder;\n\tselect(fields?: SelectedFields): SQLiteSelectBuilder {\n\t\treturn new SQLiteSelectBuilder({ fields: fields ?? undefined, session: this.session, dialect: this.dialect });\n\t}\n\n\t/**\n\t * Adds `distinct` expression to the select query.\n\t *\n\t * Calling this method will return only unique values. When multiple columns are selected, it returns rows with unique combinations of values in these columns.\n\t *\n\t * Use `.from()` method to specify which table to select from.\n\t *\n\t * See docs: {@link https://orm.drizzle.team/docs/select#distinct}\n\t *\n\t * @param fields The selection object.\n\t *\n\t * @example\n\t *\n\t * ```ts\n\t * // Select all unique rows from the 'cars' table\n\t * await db.selectDistinct()\n\t * .from(cars)\n\t * .orderBy(cars.id, cars.brand, cars.color);\n\t *\n\t * // Select all unique brands from the 'cars' table\n\t * await db.selectDistinct({ brand: cars.brand })\n\t * .from(cars)\n\t * .orderBy(cars.brand);\n\t * ```\n\t */\n\tselectDistinct(): SQLiteSelectBuilder;\n\tselectDistinct(\n\t\tfields: TSelection,\n\t): SQLiteSelectBuilder;\n\tselectDistinct(\n\t\tfields?: SelectedFields,\n\t): SQLiteSelectBuilder {\n\t\treturn new SQLiteSelectBuilder({\n\t\t\tfields: fields ?? undefined,\n\t\t\tsession: this.session,\n\t\t\tdialect: this.dialect,\n\t\t\tdistinct: true,\n\t\t});\n\t}\n\n\t/**\n\t * Creates an update query.\n\t *\n\t * Calling this method without `.where()` clause will update all rows in a table. The `.where()` clause specifies which rows should be updated.\n\t *\n\t * Use `.set()` method to specify which values to update.\n\t *\n\t * See docs: {@link https://orm.drizzle.team/docs/update}\n\t *\n\t * @param table The table to update.\n\t *\n\t * @example\n\t *\n\t * ```ts\n\t * // Update all rows in the 'cars' table\n\t * await db.update(cars).set({ color: 'red' });\n\t *\n\t * // Update rows with filters and conditions\n\t * await db.update(cars).set({ color: 'red' }).where(eq(cars.brand, 'BMW'));\n\t *\n\t * // Update with returning clause\n\t * const updatedCar: Car[] = await db.update(cars)\n\t * .set({ color: 'red' })\n\t * .where(eq(cars.id, 1))\n\t * .returning();\n\t * ```\n\t */\n\tupdate(table: TTable): SQLiteUpdateBuilder {\n\t\treturn new SQLiteUpdateBuilder(table, this.session, this.dialect);\n\t}\n\n\t$cache: { invalidate: Cache['onMutate'] };\n\n\t/**\n\t * Creates an insert query.\n\t *\n\t * Calling this method will create new rows in a table. Use `.values()` method to specify which values to insert.\n\t *\n\t * See docs: {@link https://orm.drizzle.team/docs/insert}\n\t *\n\t * @param table The table to insert into.\n\t *\n\t * @example\n\t *\n\t * ```ts\n\t * // Insert one row\n\t * await db.insert(cars).values({ brand: 'BMW' });\n\t *\n\t * // Insert multiple rows\n\t * await db.insert(cars).values([{ brand: 'BMW' }, { brand: 'Porsche' }]);\n\t *\n\t * // Insert with returning clause\n\t * const insertedCar: Car[] = await db.insert(cars)\n\t * .values({ brand: 'BMW' })\n\t * .returning();\n\t * ```\n\t */\n\tinsert(into: TTable): SQLiteInsertBuilder {\n\t\treturn new SQLiteInsertBuilder(into, this.session, this.dialect);\n\t}\n\n\t/**\n\t * Creates a delete query.\n\t *\n\t * Calling this method without `.where()` clause will delete all rows in a table. The `.where()` clause specifies which rows should be deleted.\n\t *\n\t * See docs: {@link https://orm.drizzle.team/docs/delete}\n\t *\n\t * @param table The table to delete from.\n\t *\n\t * @example\n\t *\n\t * ```ts\n\t * // Delete all rows in the 'cars' table\n\t * await db.delete(cars);\n\t *\n\t * // Delete rows with filters and conditions\n\t * await db.delete(cars).where(eq(cars.color, 'green'));\n\t *\n\t * // Delete with returning clause\n\t * const deletedCar: Car[] = await db.delete(cars)\n\t * .where(eq(cars.id, 1))\n\t * .returning();\n\t * ```\n\t */\n\tdelete(from: TTable): SQLiteDeleteBase {\n\t\treturn new SQLiteDeleteBase(from, this.session, this.dialect);\n\t}\n\n\trun(query: SQLWrapper | string): DBResult {\n\t\tconst sequel = typeof query === 'string' ? sql.raw(query) : query.getSQL();\n\t\tif (this.resultKind === 'async') {\n\t\t\treturn new SQLiteRaw(\n\t\t\t\tasync () => this.session.run(sequel),\n\t\t\t\t() => sequel,\n\t\t\t\t'run',\n\t\t\t\tthis.dialect as SQLiteAsyncDialect,\n\t\t\t\tthis.session.extractRawRunValueFromBatchResult.bind(this.session),\n\t\t\t) as DBResult;\n\t\t}\n\t\treturn this.session.run(sequel) as DBResult;\n\t}\n\n\tall(query: SQLWrapper | string): DBResult {\n\t\tconst sequel = typeof query === 'string' ? sql.raw(query) : query.getSQL();\n\t\tif (this.resultKind === 'async') {\n\t\t\treturn new SQLiteRaw(\n\t\t\t\tasync () => this.session.all(sequel),\n\t\t\t\t() => sequel,\n\t\t\t\t'all',\n\t\t\t\tthis.dialect as SQLiteAsyncDialect,\n\t\t\t\tthis.session.extractRawAllValueFromBatchResult.bind(this.session),\n\t\t\t) as any;\n\t\t}\n\t\treturn this.session.all(sequel) as DBResult;\n\t}\n\n\tget(query: SQLWrapper | string): DBResult {\n\t\tconst sequel = typeof query === 'string' ? sql.raw(query) : query.getSQL();\n\t\tif (this.resultKind === 'async') {\n\t\t\treturn new SQLiteRaw(\n\t\t\t\tasync () => this.session.get(sequel),\n\t\t\t\t() => sequel,\n\t\t\t\t'get',\n\t\t\t\tthis.dialect as SQLiteAsyncDialect,\n\t\t\t\tthis.session.extractRawGetValueFromBatchResult.bind(this.session),\n\t\t\t) as DBResult;\n\t\t}\n\t\treturn this.session.get(sequel) as DBResult;\n\t}\n\n\tvalues(query: SQLWrapper | string): DBResult {\n\t\tconst sequel = typeof query === 'string' ? sql.raw(query) : query.getSQL();\n\t\tif (this.resultKind === 'async') {\n\t\t\treturn new SQLiteRaw(\n\t\t\t\tasync () => this.session.values(sequel),\n\t\t\t\t() => sequel,\n\t\t\t\t'values',\n\t\t\t\tthis.dialect as SQLiteAsyncDialect,\n\t\t\t\tthis.session.extractRawValuesValueFromBatchResult.bind(this.session),\n\t\t\t) as any;\n\t\t}\n\t\treturn this.session.values(sequel) as DBResult;\n\t}\n\n\ttransaction(\n\t\ttransaction: (tx: SQLiteTransaction) => Result,\n\t\tconfig?: SQLiteTransactionConfig,\n\t): Result {\n\t\treturn this.session.transaction(transaction, config);\n\t}\n}\n\nexport type SQLiteWithReplicas = Q & { $primary: Q; $replicas: Q[] };\n\nexport const withReplicas = <\n\tTResultKind extends 'sync' | 'async',\n\tTRunResult,\n\tTFullSchema extends Record,\n\tTSchema extends TablesRelationalConfig,\n\tQ extends BaseSQLiteDatabase<\n\t\tTResultKind,\n\t\tTRunResult,\n\t\tTFullSchema,\n\t\tTSchema extends Record ? ExtractTablesWithRelations : TSchema\n\t>,\n>(\n\tprimary: Q,\n\treplicas: [Q, ...Q[]],\n\tgetReplica: (replicas: Q[]) => Q = () => replicas[Math.floor(Math.random() * replicas.length)]!,\n): SQLiteWithReplicas => {\n\tconst select: Q['select'] = (...args: []) => getReplica(replicas).select(...args);\n\tconst selectDistinct: Q['selectDistinct'] = (...args: []) => getReplica(replicas).selectDistinct(...args);\n\tconst $count: Q['$count'] = (...args: [any]) => getReplica(replicas).$count(...args);\n\tconst $with: Q['with'] = (...args: []) => getReplica(replicas).with(...args);\n\n\tconst update: Q['update'] = (...args: [any]) => primary.update(...args);\n\tconst insert: Q['insert'] = (...args: [any]) => primary.insert(...args);\n\tconst $delete: Q['delete'] = (...args: [any]) => primary.delete(...args);\n\tconst run: Q['run'] = (...args: [any]) => primary.run(...args);\n\tconst all: Q['all'] = (...args: [any]) => primary.all(...args);\n\tconst get: Q['get'] = (...args: [any]) => primary.get(...args);\n\tconst values: Q['values'] = (...args: [any]) => primary.values(...args);\n\tconst transaction: Q['transaction'] = (...args: [any]) => primary.transaction(...args);\n\n\treturn {\n\t\t...primary,\n\t\tupdate,\n\t\tinsert,\n\t\tdelete: $delete,\n\t\trun,\n\t\tall,\n\t\tget,\n\t\tvalues,\n\t\ttransaction,\n\t\t$primary: primary,\n\t\t$replicas: replicas,\n\t\tselect,\n\t\tselectDistinct,\n\t\t$count,\n\t\twith: $with,\n\t\tget query() {\n\t\t\treturn getReplica(replicas).query;\n\t\t},\n\t};\n};\n", "import { ColumnAliasProxyHandler, TableAliasProxyHandler } from './alias.ts';\nimport { Column } from './column.ts';\nimport { entityKind, is } from './entity.ts';\nimport { SQL, View } from './sql/sql.ts';\nimport { Subquery } from './subquery.ts';\nimport { ViewBaseConfig } from './view-common.ts';\n\nexport class SelectionProxyHandler | View>\n\timplements ProxyHandler | View>\n{\n\tstatic readonly [entityKind]: string = 'SelectionProxyHandler';\n\n\tprivate config: {\n\t\t/**\n\t\t * Table alias for the columns\n\t\t */\n\t\talias?: string;\n\t\t/**\n\t\t * What to do when a field is an instance of `SQL.Aliased` and it's not a selection field (from a subquery)\n\t\t *\n\t\t * `sql` - return the underlying SQL expression\n\t\t *\n\t\t * `alias` - return the field alias\n\t\t */\n\t\tsqlAliasedBehavior: 'sql' | 'alias';\n\t\t/**\n\t\t * What to do when a field is an instance of `SQL` and it doesn't have an alias declared\n\t\t *\n\t\t * `sql` - return the underlying SQL expression\n\t\t *\n\t\t * `error` - return a DrizzleTypeError on type level and throw an error on runtime\n\t\t */\n\t\tsqlBehavior: 'sql' | 'error';\n\n\t\t/**\n\t\t * Whether to replace the original name of the column with the alias\n\t\t * Should be set to `true` for views creation\n\t\t * @default false\n\t\t */\n\t\treplaceOriginalName?: boolean;\n\t};\n\n\tconstructor(config: SelectionProxyHandler['config']) {\n\t\tthis.config = { ...config };\n\t}\n\n\tget(subquery: T, prop: string | symbol): any {\n\t\tif (prop === '_') {\n\t\t\treturn {\n\t\t\t\t...subquery['_' as keyof typeof subquery],\n\t\t\t\tselectedFields: new Proxy(\n\t\t\t\t\t(subquery as Subquery)._.selectedFields,\n\t\t\t\t\tthis as ProxyHandler>,\n\t\t\t\t),\n\t\t\t};\n\t\t}\n\n\t\tif (prop === ViewBaseConfig) {\n\t\t\treturn {\n\t\t\t\t...subquery[ViewBaseConfig as keyof typeof subquery],\n\t\t\t\tselectedFields: new Proxy(\n\t\t\t\t\t(subquery as View)[ViewBaseConfig].selectedFields,\n\t\t\t\t\tthis as ProxyHandler>,\n\t\t\t\t),\n\t\t\t};\n\t\t}\n\n\t\tif (typeof prop === 'symbol') {\n\t\t\treturn subquery[prop as keyof typeof subquery];\n\t\t}\n\n\t\tconst columns = is(subquery, Subquery)\n\t\t\t? subquery._.selectedFields\n\t\t\t: is(subquery, View)\n\t\t\t? subquery[ViewBaseConfig].selectedFields\n\t\t\t: subquery;\n\t\tconst value: unknown = columns[prop as keyof typeof columns];\n\n\t\tif (is(value, SQL.Aliased)) {\n\t\t\t// Never return the underlying SQL expression for a field previously selected in a subquery\n\t\t\tif (this.config.sqlAliasedBehavior === 'sql' && !value.isSelectionField) {\n\t\t\t\treturn value.sql;\n\t\t\t}\n\n\t\t\tconst newValue = value.clone();\n\t\t\tnewValue.isSelectionField = true;\n\t\t\treturn newValue;\n\t\t}\n\n\t\tif (is(value, SQL)) {\n\t\t\tif (this.config.sqlBehavior === 'sql') {\n\t\t\t\treturn value;\n\t\t\t}\n\n\t\t\tthrow new Error(\n\t\t\t\t`You tried to reference \"${prop}\" field from a subquery, which is a raw SQL field, but it doesn't have an alias declared. Please add an alias to the field using \".as('alias')\" method.`,\n\t\t\t);\n\t\t}\n\n\t\tif (is(value, Column)) {\n\t\t\tif (this.config.alias) {\n\t\t\t\treturn new Proxy(\n\t\t\t\t\tvalue,\n\t\t\t\t\tnew ColumnAliasProxyHandler(\n\t\t\t\t\t\tnew Proxy(\n\t\t\t\t\t\t\tvalue.table,\n\t\t\t\t\t\t\tnew TableAliasProxyHandler(this.config.alias, this.config.replaceOriginalName ?? false),\n\t\t\t\t\t\t),\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn value;\n\t\t}\n\n\t\tif (typeof value !== 'object' || value === null) {\n\t\t\treturn value;\n\t\t}\n\n\t\treturn new Proxy(value, new SelectionProxyHandler(this.config));\n\t}\n}\n", "import type { AnyColumn } from './column.ts';\nimport { Column } from './column.ts';\nimport { entityKind, is } from './entity.ts';\nimport type { Relation } from './relations.ts';\nimport type { View } from './sql/sql.ts';\nimport { SQL, sql } from './sql/sql.ts';\nimport { Table } from './table.ts';\nimport { ViewBaseConfig } from './view-common.ts';\n\nexport class ColumnAliasProxyHandler implements ProxyHandler {\n\tstatic readonly [entityKind]: string = 'ColumnAliasProxyHandler';\n\n\tconstructor(private table: Table | View) {}\n\n\tget(columnObj: TColumn, prop: string | symbol): any {\n\t\tif (prop === 'table') {\n\t\t\treturn this.table;\n\t\t}\n\n\t\treturn columnObj[prop as keyof TColumn];\n\t}\n}\n\nexport class TableAliasProxyHandler implements ProxyHandler {\n\tstatic readonly [entityKind]: string = 'TableAliasProxyHandler';\n\n\tconstructor(private alias: string, private replaceOriginalName: boolean) {}\n\n\tget(target: T, prop: string | symbol): any {\n\t\tif (prop === Table.Symbol.IsAlias) {\n\t\t\treturn true;\n\t\t}\n\n\t\tif (prop === Table.Symbol.Name) {\n\t\t\treturn this.alias;\n\t\t}\n\n\t\tif (this.replaceOriginalName && prop === Table.Symbol.OriginalName) {\n\t\t\treturn this.alias;\n\t\t}\n\n\t\tif (prop === ViewBaseConfig) {\n\t\t\treturn {\n\t\t\t\t...target[ViewBaseConfig as keyof typeof target],\n\t\t\t\tname: this.alias,\n\t\t\t\tisAlias: true,\n\t\t\t};\n\t\t}\n\n\t\tif (prop === Table.Symbol.Columns) {\n\t\t\tconst columns = (target as Table)[Table.Symbol.Columns];\n\t\t\tif (!columns) {\n\t\t\t\treturn columns;\n\t\t\t}\n\n\t\t\tconst proxiedColumns: { [key: string]: any } = {};\n\n\t\t\tObject.keys(columns).map((key) => {\n\t\t\t\tproxiedColumns[key] = new Proxy(\n\t\t\t\t\tcolumns[key]!,\n\t\t\t\t\tnew ColumnAliasProxyHandler(new Proxy(target, this)),\n\t\t\t\t);\n\t\t\t});\n\n\t\t\treturn proxiedColumns;\n\t\t}\n\n\t\tconst value = target[prop as keyof typeof target];\n\t\tif (is(value, Column)) {\n\t\t\treturn new Proxy(value as AnyColumn, new ColumnAliasProxyHandler(new Proxy(target, this)));\n\t\t}\n\n\t\treturn value;\n\t}\n}\n\nexport class RelationTableAliasProxyHandler implements ProxyHandler {\n\tstatic readonly [entityKind]: string = 'RelationTableAliasProxyHandler';\n\n\tconstructor(private alias: string) {}\n\n\tget(target: T, prop: string | symbol): any {\n\t\tif (prop === 'sourceTable') {\n\t\t\treturn aliasedTable(target.sourceTable, this.alias);\n\t\t}\n\n\t\treturn target[prop as keyof typeof target];\n\t}\n}\n\nexport function aliasedTable(\n\ttable: T,\n\ttableAlias: string,\n): T {\n\treturn new Proxy(table, new TableAliasProxyHandler(tableAlias, false)) as any;\n}\n\nexport function aliasedRelation(relation: T, tableAlias: string): T {\n\treturn new Proxy(relation, new RelationTableAliasProxyHandler(tableAlias));\n}\n\nexport function aliasedTableColumn(column: T, tableAlias: string): T {\n\treturn new Proxy(\n\t\tcolumn,\n\t\tnew ColumnAliasProxyHandler(new Proxy(column.table, new TableAliasProxyHandler(tableAlias, false))),\n\t);\n}\n\nexport function mapColumnsInAliasedSQLToAlias(query: SQL.Aliased, alias: string): SQL.Aliased {\n\treturn new SQL.Aliased(mapColumnsInSQLToAlias(query.sql, alias), query.fieldAlias);\n}\n\nexport function mapColumnsInSQLToAlias(query: SQL, alias: string): SQL {\n\treturn sql.join(query.queryChunks.map((c) => {\n\t\tif (is(c, Column)) {\n\t\t\treturn aliasedTableColumn(c, alias);\n\t\t}\n\t\tif (is(c, SQL)) {\n\t\t\treturn mapColumnsInSQLToAlias(c, alias);\n\t\t}\n\t\tif (is(c, SQL.Aliased)) {\n\t\t\treturn mapColumnsInAliasedSQLToAlias(c, alias);\n\t\t}\n\t\treturn c;\n\t}));\n}\n", "import { entityKind } from '~/entity.ts';\nimport type { SelectResultFields } from '~/query-builders/select.types.ts';\nimport { QueryPromise } from '~/query-promise.ts';\nimport type { RunnableQuery } from '~/runnable-query.ts';\nimport { SelectionProxyHandler } from '~/selection-proxy.ts';\nimport type { Placeholder, Query, SQL, SQLWrapper } from '~/sql/sql.ts';\nimport type { SQLiteDialect } from '~/sqlite-core/dialect.ts';\nimport type { SQLitePreparedQuery, SQLiteSession } from '~/sqlite-core/session.ts';\nimport { SQLiteTable } from '~/sqlite-core/table.ts';\nimport type { Subquery } from '~/subquery.ts';\nimport { Table } from '~/table.ts';\nimport { type DrizzleTypeError, orderSelectedFields, type ValueOrArray } from '~/utils.ts';\nimport type { SQLiteColumn } from '../columns/common.ts';\nimport { extractUsedTable } from '../utils.ts';\nimport type { SelectedFieldsFlat, SelectedFieldsOrdered } from './select.types.ts';\n\nexport type SQLiteDeleteWithout<\n\tT extends AnySQLiteDeleteBase,\n\tTDynamic extends boolean,\n\tK extends keyof T & string,\n> = TDynamic extends true ? T\n\t: Omit<\n\t\tSQLiteDeleteBase<\n\t\t\tT['_']['table'],\n\t\t\tT['_']['resultType'],\n\t\t\tT['_']['runResult'],\n\t\t\tT['_']['returning'],\n\t\t\tTDynamic,\n\t\t\tT['_']['excludedMethods'] | K\n\t\t>,\n\t\tT['_']['excludedMethods'] | K\n\t>;\n\nexport type SQLiteDelete<\n\tTTable extends SQLiteTable = SQLiteTable,\n\tTResultType extends 'sync' | 'async' = 'sync' | 'async',\n\tTRunResult = unknown,\n\tTReturning extends Record | undefined = undefined,\n> = SQLiteDeleteBase;\n\nexport interface SQLiteDeleteConfig {\n\twhere?: SQL | undefined;\n\tlimit?: number | Placeholder;\n\torderBy?: (SQLiteColumn | SQL | SQL.Aliased)[];\n\ttable: SQLiteTable;\n\treturning?: SelectedFieldsOrdered;\n\twithList?: Subquery[];\n}\n\nexport type SQLiteDeleteReturningAll<\n\tT extends AnySQLiteDeleteBase,\n\tTDynamic extends boolean,\n> = SQLiteDeleteWithout<\n\tSQLiteDeleteBase<\n\t\tT['_']['table'],\n\t\tT['_']['resultType'],\n\t\tT['_']['runResult'],\n\t\tT['_']['table']['$inferSelect'],\n\t\tT['_']['dynamic'],\n\t\tT['_']['excludedMethods']\n\t>,\n\tTDynamic,\n\t'returning'\n>;\n\nexport type SQLiteDeleteReturning<\n\tT extends AnySQLiteDeleteBase,\n\tTDynamic extends boolean,\n\tTSelectedFields extends SelectedFieldsFlat,\n> = SQLiteDeleteWithout<\n\tSQLiteDeleteBase<\n\t\tT['_']['table'],\n\t\tT['_']['resultType'],\n\t\tT['_']['runResult'],\n\t\tSelectResultFields,\n\t\tT['_']['dynamic'],\n\t\tT['_']['excludedMethods']\n\t>,\n\tTDynamic,\n\t'returning'\n>;\n\nexport type SQLiteDeleteExecute = T['_']['returning'] extends undefined\n\t? T['_']['runResult']\n\t: T['_']['returning'][];\n\nexport type SQLiteDeletePrepare = SQLitePreparedQuery<{\n\ttype: T['_']['resultType'];\n\trun: T['_']['runResult'];\n\tall: T['_']['returning'] extends undefined ? DrizzleTypeError<'.all() cannot be used without .returning()'>\n\t\t: T['_']['returning'][];\n\tget: T['_']['returning'] extends undefined ? DrizzleTypeError<'.get() cannot be used without .returning()'>\n\t\t: T['_']['returning'] | undefined;\n\tvalues: T['_']['returning'] extends undefined ? DrizzleTypeError<'.values() cannot be used without .returning()'>\n\t\t: any[][];\n\texecute: SQLiteDeleteExecute;\n}>;\n\nexport type SQLiteDeleteDynamic = SQLiteDelete<\n\tT['_']['table'],\n\tT['_']['resultType'],\n\tT['_']['runResult'],\n\tT['_']['returning']\n>;\n\nexport type AnySQLiteDeleteBase = SQLiteDeleteBase;\n\nexport interface SQLiteDeleteBase<\n\tTTable extends SQLiteTable,\n\tTResultType extends 'sync' | 'async',\n\tTRunResult,\n\tTReturning extends Record | undefined = undefined,\n\tTDynamic extends boolean = false,\n\tTExcludedMethods extends string = never,\n> extends\n\tQueryPromise,\n\tRunnableQuery,\n\tSQLWrapper\n{\n\treadonly _: {\n\t\tdialect: 'sqlite';\n\t\treadonly table: TTable;\n\t\treadonly resultType: TResultType;\n\t\treadonly runResult: TRunResult;\n\t\treadonly returning: TReturning;\n\t\treadonly dynamic: TDynamic;\n\t\treadonly excludedMethods: TExcludedMethods;\n\t\treadonly result: TReturning extends undefined ? TRunResult : TReturning[];\n\t};\n}\n\nexport class SQLiteDeleteBase<\n\tTTable extends SQLiteTable,\n\t// eslint-disable-next-line @typescript-eslint/no-unused-vars\n\tTResultType extends 'sync' | 'async',\n\tTRunResult,\n\tTReturning extends Record | undefined = undefined,\n\tTDynamic extends boolean = false,\n\t// eslint-disable-next-line @typescript-eslint/no-unused-vars\n\tTExcludedMethods extends string = never,\n> extends QueryPromise\n\timplements RunnableQuery, SQLWrapper\n{\n\tstatic override readonly [entityKind]: string = 'SQLiteDelete';\n\n\t/** @internal */\n\tconfig: SQLiteDeleteConfig;\n\n\tconstructor(\n\t\tprivate table: TTable,\n\t\tprivate session: SQLiteSession,\n\t\tprivate dialect: SQLiteDialect,\n\t\twithList?: Subquery[],\n\t) {\n\t\tsuper();\n\t\tthis.config = { table, withList };\n\t}\n\n\t/**\n\t * Adds a `where` clause to the query.\n\t *\n\t * Calling this method will delete only those rows that fulfill a specified condition.\n\t *\n\t * See docs: {@link https://orm.drizzle.team/docs/delete}\n\t *\n\t * @param where the `where` clause.\n\t *\n\t * @example\n\t * You can use conditional operators and `sql function` to filter the rows to be deleted.\n\t *\n\t * ```ts\n\t * // Delete all cars with green color\n\t * db.delete(cars).where(eq(cars.color, 'green'));\n\t * // or\n\t * db.delete(cars).where(sql`${cars.color} = 'green'`)\n\t * ```\n\t *\n\t * You can logically combine conditional operators with `and()` and `or()` operators:\n\t *\n\t * ```ts\n\t * // Delete all BMW cars with a green color\n\t * db.delete(cars).where(and(eq(cars.color, 'green'), eq(cars.brand, 'BMW')));\n\t *\n\t * // Delete all cars with the green or blue color\n\t * db.delete(cars).where(or(eq(cars.color, 'green'), eq(cars.color, 'blue')));\n\t * ```\n\t */\n\twhere(where: SQL | undefined): SQLiteDeleteWithout {\n\t\tthis.config.where = where;\n\t\treturn this as any;\n\t}\n\n\torderBy(\n\t\tbuilder: (deleteTable: TTable) => ValueOrArray,\n\t): SQLiteDeleteWithout;\n\torderBy(...columns: (SQLiteColumn | SQL | SQL.Aliased)[]): SQLiteDeleteWithout;\n\torderBy(\n\t\t...columns:\n\t\t\t| [(deleteTable: TTable) => ValueOrArray]\n\t\t\t| (SQLiteColumn | SQL | SQL.Aliased)[]\n\t): SQLiteDeleteWithout {\n\t\tif (typeof columns[0] === 'function') {\n\t\t\tconst orderBy = columns[0](\n\t\t\t\tnew Proxy(\n\t\t\t\t\tthis.config.table[Table.Symbol.Columns],\n\t\t\t\t\tnew SelectionProxyHandler({ sqlAliasedBehavior: 'alias', sqlBehavior: 'sql' }),\n\t\t\t\t) as any,\n\t\t\t);\n\n\t\t\tconst orderByArray = Array.isArray(orderBy) ? orderBy : [orderBy];\n\t\t\tthis.config.orderBy = orderByArray;\n\t\t} else {\n\t\t\tconst orderByArray = columns as (SQLiteColumn | SQL | SQL.Aliased)[];\n\t\t\tthis.config.orderBy = orderByArray;\n\t\t}\n\t\treturn this as any;\n\t}\n\n\tlimit(limit: number | Placeholder): SQLiteDeleteWithout {\n\t\tthis.config.limit = limit;\n\t\treturn this as any;\n\t}\n\n\t/**\n\t * Adds a `returning` clause to the query.\n\t *\n\t * Calling this method will return the specified fields of the deleted rows. If no fields are specified, all fields will be returned.\n\t *\n\t * See docs: {@link https://orm.drizzle.team/docs/delete#delete-with-return}\n\t *\n\t * @example\n\t * ```ts\n\t * // Delete all cars with the green color and return all fields\n\t * const deletedCars: Car[] = await db.delete(cars)\n\t * .where(eq(cars.color, 'green'))\n\t * .returning();\n\t *\n\t * // Delete all cars with the green color and return only their id and brand fields\n\t * const deletedCarsIdsAndBrands: { id: number, brand: string }[] = await db.delete(cars)\n\t * .where(eq(cars.color, 'green'))\n\t * .returning({ id: cars.id, brand: cars.brand });\n\t * ```\n\t */\n\treturning(): SQLiteDeleteReturningAll;\n\treturning(\n\t\tfields: TSelectedFields,\n\t): SQLiteDeleteReturning;\n\treturning(\n\t\tfields: SelectedFieldsFlat = this.table[SQLiteTable.Symbol.Columns],\n\t): SQLiteDeleteReturning {\n\t\tthis.config.returning = orderSelectedFields(fields);\n\t\treturn this as any;\n\t}\n\n\t/** @internal */\n\tgetSQL(): SQL {\n\t\treturn this.dialect.buildDeleteQuery(this.config);\n\t}\n\n\ttoSQL(): Query {\n\t\tconst { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());\n\t\treturn rest;\n\t}\n\n\t/** @internal */\n\t_prepare(isOneTimeQuery = true): SQLiteDeletePrepare {\n\t\treturn this.session[isOneTimeQuery ? 'prepareOneTimeQuery' : 'prepareQuery'](\n\t\t\tthis.dialect.sqlToQuery(this.getSQL()),\n\t\t\tthis.config.returning,\n\t\t\tthis.config.returning ? 'all' : 'run',\n\t\t\ttrue,\n\t\t\tundefined,\n\t\t\t{\n\t\t\t\ttype: 'delete',\n\t\t\t\ttables: extractUsedTable(this.config.table),\n\t\t\t},\n\t\t) as SQLiteDeletePrepare;\n\t}\n\n\tprepare(): SQLiteDeletePrepare {\n\t\treturn this._prepare(false);\n\t}\n\n\trun: ReturnType['run'] = (placeholderValues) => {\n\t\treturn this._prepare().run(placeholderValues);\n\t};\n\n\tall: ReturnType['all'] = (placeholderValues) => {\n\t\treturn this._prepare().all(placeholderValues);\n\t};\n\n\tget: ReturnType['get'] = (placeholderValues) => {\n\t\treturn this._prepare().get(placeholderValues);\n\t};\n\n\tvalues: ReturnType['values'] = (placeholderValues) => {\n\t\treturn this._prepare().values(placeholderValues);\n\t};\n\n\toverride async execute(placeholderValues?: Record): Promise> {\n\t\treturn this._prepare().execute(placeholderValues) as SQLiteDeleteExecute;\n\t}\n\n\t$dynamic(): SQLiteDeleteDynamic {\n\t\treturn this as any;\n\t}\n}\n", "import { entityKind } from '~/entity.ts';\n\nexport abstract class QueryPromise implements Promise {\n\tstatic readonly [entityKind]: string = 'QueryPromise';\n\n\t[Symbol.toStringTag] = 'QueryPromise';\n\n\tcatch(\n\t\tonRejected?: ((reason: any) => TResult | PromiseLike) | null | undefined,\n\t): Promise {\n\t\treturn this.then(undefined, onRejected);\n\t}\n\n\tfinally(onFinally?: (() => void) | null | undefined): Promise {\n\t\treturn this.then(\n\t\t\t(value) => {\n\t\t\t\tonFinally?.();\n\t\t\t\treturn value;\n\t\t\t},\n\t\t\t(reason) => {\n\t\t\t\tonFinally?.();\n\t\t\t\tthrow reason;\n\t\t\t},\n\t\t);\n\t}\n\n\tthen(\n\t\tonFulfilled?: ((value: T) => TResult1 | PromiseLike) | undefined | null,\n\t\tonRejected?: ((reason: any) => TResult2 | PromiseLike) | undefined | null,\n\t): Promise {\n\t\treturn this.execute().then(onFulfilled, onRejected);\n\t}\n\n\tabstract execute(): Promise;\n}\n", "import type { BuildColumns, BuildExtraConfigColumns } from '~/column-builder.ts';\nimport { entityKind } from '~/entity.ts';\nimport { Table, type TableConfig as TableConfigBase, type UpdateTableConfig } from '~/table.ts';\nimport type { CheckBuilder } from './checks.ts';\nimport { getSQLiteColumnBuilders, type SQLiteColumnBuilders } from './columns/all.ts';\nimport type { SQLiteColumn, SQLiteColumnBuilder, SQLiteColumnBuilderBase } from './columns/common.ts';\nimport type { ForeignKey, ForeignKeyBuilder } from './foreign-keys.ts';\nimport type { IndexBuilder } from './indexes.ts';\nimport type { PrimaryKeyBuilder } from './primary-keys.ts';\nimport type { UniqueConstraintBuilder } from './unique-constraint.ts';\n\nexport type SQLiteTableExtraConfigValue =\n\t| IndexBuilder\n\t| CheckBuilder\n\t| ForeignKeyBuilder\n\t| PrimaryKeyBuilder\n\t| UniqueConstraintBuilder;\n\nexport type SQLiteTableExtraConfig = Record<\n\tstring,\n\tSQLiteTableExtraConfigValue\n>;\n\nexport type TableConfig = TableConfigBase>;\n\n/** @internal */\nexport const InlineForeignKeys = Symbol.for('drizzle:SQLiteInlineForeignKeys');\n\nexport class SQLiteTable extends Table {\n\tstatic override readonly [entityKind]: string = 'SQLiteTable';\n\n\t/** @internal */\n\tstatic override readonly Symbol = Object.assign({}, Table.Symbol, {\n\t\tInlineForeignKeys: InlineForeignKeys as typeof InlineForeignKeys,\n\t});\n\n\t/** @internal */\n\toverride [Table.Symbol.Columns]!: NonNullable;\n\n\t/** @internal */\n\t[InlineForeignKeys]: ForeignKey[] = [];\n\n\t/** @internal */\n\toverride [Table.Symbol.ExtraConfigBuilder]:\n\t\t| ((self: Record) => SQLiteTableExtraConfig)\n\t\t| undefined = undefined;\n}\n\nexport type AnySQLiteTable = {}> = SQLiteTable<\n\tUpdateTableConfig\n>;\n\nexport type SQLiteTableWithColumns =\n\t& SQLiteTable\n\t& {\n\t\t[Key in keyof T['columns']]: T['columns'][Key];\n\t};\n\nexport interface SQLiteTableFn {\n\t<\n\t\tTTableName extends string,\n\t\tTColumnsMap extends Record,\n\t>(\n\t\tname: TTableName,\n\t\tcolumns: TColumnsMap,\n\t\textraConfig?: (\n\t\t\tself: BuildColumns,\n\t\t) => SQLiteTableExtraConfigValue[],\n\t): SQLiteTableWithColumns<{\n\t\tname: TTableName;\n\t\tschema: TSchema;\n\t\tcolumns: BuildColumns;\n\t\tdialect: 'sqlite';\n\t}>;\n\n\t<\n\t\tTTableName extends string,\n\t\tTColumnsMap extends Record,\n\t>(\n\t\tname: TTableName,\n\t\tcolumns: (columnTypes: SQLiteColumnBuilders) => TColumnsMap,\n\t\textraConfig?: (self: BuildColumns) => SQLiteTableExtraConfigValue[],\n\t): SQLiteTableWithColumns<{\n\t\tname: TTableName;\n\t\tschema: TSchema;\n\t\tcolumns: BuildColumns;\n\t\tdialect: 'sqlite';\n\t}>;\n\t/**\n\t * @deprecated The third parameter of sqliteTable is changing and will only accept an array instead of an object\n\t *\n\t * @example\n\t * Deprecated version:\n\t * ```ts\n\t * export const users = sqliteTable(\"users\", {\n\t * \tid: int(),\n\t * }, (t) => ({\n\t * \tidx: index('custom_name').on(t.id)\n\t * }));\n\t * ```\n\t *\n\t * New API:\n\t * ```ts\n\t * export const users = sqliteTable(\"users\", {\n\t * \tid: int(),\n\t * }, (t) => [\n\t * \tindex('custom_name').on(t.id)\n\t * ]);\n\t * ```\n\t */\n\t<\n\t\tTTableName extends string,\n\t\tTColumnsMap extends Record,\n\t>(\n\t\tname: TTableName,\n\t\tcolumns: TColumnsMap,\n\t\textraConfig?: (self: BuildColumns) => SQLiteTableExtraConfig,\n\t): SQLiteTableWithColumns<{\n\t\tname: TTableName;\n\t\tschema: TSchema;\n\t\tcolumns: BuildColumns;\n\t\tdialect: 'sqlite';\n\t}>;\n\n\t/**\n\t * @deprecated The third parameter of sqliteTable is changing and will only accept an array instead of an object\n\t *\n\t * @example\n\t * Deprecated version:\n\t * ```ts\n\t * export const users = sqliteTable(\"users\", {\n\t * \tid: int(),\n\t * }, (t) => ({\n\t * \tidx: index('custom_name').on(t.id)\n\t * }));\n\t * ```\n\t *\n\t * New API:\n\t * ```ts\n\t * export const users = sqliteTable(\"users\", {\n\t * \tid: int(),\n\t * }, (t) => [\n\t * \tindex('custom_name').on(t.id)\n\t * ]);\n\t * ```\n\t */\n\t<\n\t\tTTableName extends string,\n\t\tTColumnsMap extends Record,\n\t>(\n\t\tname: TTableName,\n\t\tcolumns: (columnTypes: SQLiteColumnBuilders) => TColumnsMap,\n\t\textraConfig?: (self: BuildColumns) => SQLiteTableExtraConfig,\n\t): SQLiteTableWithColumns<{\n\t\tname: TTableName;\n\t\tschema: TSchema;\n\t\tcolumns: BuildColumns;\n\t\tdialect: 'sqlite';\n\t}>;\n}\n\nfunction sqliteTableBase<\n\tTTableName extends string,\n\tTColumnsMap extends Record,\n\tTSchema extends string | undefined,\n>(\n\tname: TTableName,\n\tcolumns: TColumnsMap | ((columnTypes: SQLiteColumnBuilders) => TColumnsMap),\n\textraConfig:\n\t\t| ((\n\t\t\tself: BuildColumns,\n\t\t) => SQLiteTableExtraConfig | SQLiteTableExtraConfigValue[])\n\t\t| undefined,\n\tschema?: TSchema,\n\tbaseName = name,\n): SQLiteTableWithColumns<{\n\tname: TTableName;\n\tschema: TSchema;\n\tcolumns: BuildColumns;\n\tdialect: 'sqlite';\n}> {\n\tconst rawTable = new SQLiteTable<{\n\t\tname: TTableName;\n\t\tschema: TSchema;\n\t\tcolumns: BuildColumns;\n\t\tdialect: 'sqlite';\n\t}>(name, schema, baseName);\n\n\tconst parsedColumns: TColumnsMap = typeof columns === 'function' ? columns(getSQLiteColumnBuilders()) : columns;\n\n\tconst builtColumns = Object.fromEntries(\n\t\tObject.entries(parsedColumns).map(([name, colBuilderBase]) => {\n\t\t\tconst colBuilder = colBuilderBase as SQLiteColumnBuilder;\n\t\t\tcolBuilder.setName(name);\n\t\t\tconst column = colBuilder.build(rawTable);\n\t\t\trawTable[InlineForeignKeys].push(...colBuilder.buildForeignKeys(column, rawTable));\n\t\t\treturn [name, column];\n\t\t}),\n\t) as unknown as BuildColumns;\n\n\tconst table = Object.assign(rawTable, builtColumns);\n\n\ttable[Table.Symbol.Columns] = builtColumns;\n\ttable[Table.Symbol.ExtraConfigColumns] = builtColumns as unknown as BuildExtraConfigColumns<\n\t\tTTableName,\n\t\tTColumnsMap,\n\t\t'sqlite'\n\t>;\n\n\tif (extraConfig) {\n\t\ttable[SQLiteTable.Symbol.ExtraConfigBuilder] = extraConfig as (\n\t\t\tself: Record,\n\t\t) => SQLiteTableExtraConfig;\n\t}\n\n\treturn table;\n}\n\nexport const sqliteTable: SQLiteTableFn = (name, columns, extraConfig) => {\n\treturn sqliteTableBase(name, columns, extraConfig);\n};\n\nexport function sqliteTableCreator(customizeTableName: (name: string) => string): SQLiteTableFn {\n\treturn (name, columns, extraConfig) => {\n\t\treturn sqliteTableBase(customizeTableName(name) as typeof name, columns, extraConfig, undefined, name);\n\t};\n}\n", "import { blob } from './blob.ts';\nimport { customType } from './custom.ts';\nimport { integer } from './integer.ts';\nimport { numeric } from './numeric.ts';\nimport { real } from './real.ts';\nimport { text } from './text.ts';\n\nexport function getSQLiteColumnBuilders() {\n\treturn {\n\t\tblob,\n\t\tcustomType,\n\t\tinteger,\n\t\tnumeric,\n\t\treal,\n\t\ttext,\n\t};\n}\n\nexport type SQLiteColumnBuilders = ReturnType;\n", "import type { ColumnBuilderBaseConfig, ColumnBuilderRuntimeConfig, MakeColumnConfig } from '~/column-builder.ts';\nimport type { ColumnBaseConfig } from '~/column.ts';\nimport { entityKind } from '~/entity.ts';\nimport type { AnySQLiteTable } from '~/sqlite-core/table.ts';\nimport { type Equal, getColumnNameAndConfig, textDecoder } from '~/utils.ts';\nimport { SQLiteColumn, SQLiteColumnBuilder } from './common.ts';\n\ntype BlobMode = 'buffer' | 'json' | 'bigint';\n\nexport type SQLiteBigIntBuilderInitial = SQLiteBigIntBuilder<{\n\tname: TName;\n\tdataType: 'bigint';\n\tcolumnType: 'SQLiteBigInt';\n\tdata: bigint;\n\tdriverParam: Buffer;\n\tenumValues: undefined;\n}>;\n\nexport class SQLiteBigIntBuilder>\n\textends SQLiteColumnBuilder\n{\n\tstatic override readonly [entityKind]: string = 'SQLiteBigIntBuilder';\n\n\tconstructor(name: T['name']) {\n\t\tsuper(name, 'bigint', 'SQLiteBigInt');\n\t}\n\n\t/** @internal */\n\toverride build(\n\t\ttable: AnySQLiteTable<{ name: TTableName }>,\n\t): SQLiteBigInt> {\n\t\treturn new SQLiteBigInt>(table, this.config as ColumnBuilderRuntimeConfig);\n\t}\n}\n\nexport class SQLiteBigInt> extends SQLiteColumn {\n\tstatic override readonly [entityKind]: string = 'SQLiteBigInt';\n\n\tgetSQLType(): string {\n\t\treturn 'blob';\n\t}\n\n\toverride mapFromDriverValue(value: Buffer | Uint8Array | ArrayBuffer): bigint {\n\t\tif (typeof Buffer !== 'undefined' && Buffer.from) {\n\t\t\tconst buf = Buffer.isBuffer(value)\n\t\t\t\t? value\n\t\t\t\t// eslint-disable-next-line no-instanceof/no-instanceof\n\t\t\t\t: value instanceof ArrayBuffer\n\t\t\t\t? Buffer.from(value)\n\t\t\t\t: value.buffer\n\t\t\t\t? Buffer.from(value.buffer, value.byteOffset, value.byteLength)\n\t\t\t\t: Buffer.from(value);\n\t\t\treturn BigInt(buf.toString('utf8'));\n\t\t}\n\n\t\treturn BigInt(textDecoder!.decode(value));\n\t}\n\n\toverride mapToDriverValue(value: bigint): Buffer {\n\t\treturn Buffer.from(value.toString());\n\t}\n}\n\nexport type SQLiteBlobJsonBuilderInitial = SQLiteBlobJsonBuilder<{\n\tname: TName;\n\tdataType: 'json';\n\tcolumnType: 'SQLiteBlobJson';\n\tdata: unknown;\n\tdriverParam: Buffer;\n\tenumValues: undefined;\n}>;\n\nexport class SQLiteBlobJsonBuilder>\n\textends SQLiteColumnBuilder\n{\n\tstatic override readonly [entityKind]: string = 'SQLiteBlobJsonBuilder';\n\n\tconstructor(name: T['name']) {\n\t\tsuper(name, 'json', 'SQLiteBlobJson');\n\t}\n\n\t/** @internal */\n\toverride build(\n\t\ttable: AnySQLiteTable<{ name: TTableName }>,\n\t): SQLiteBlobJson> {\n\t\treturn new SQLiteBlobJson>(\n\t\t\ttable,\n\t\t\tthis.config as ColumnBuilderRuntimeConfig,\n\t\t);\n\t}\n}\n\nexport class SQLiteBlobJson> extends SQLiteColumn {\n\tstatic override readonly [entityKind]: string = 'SQLiteBlobJson';\n\n\tgetSQLType(): string {\n\t\treturn 'blob';\n\t}\n\n\toverride mapFromDriverValue(value: Buffer | Uint8Array | ArrayBuffer): T['data'] {\n\t\tif (typeof Buffer !== 'undefined' && Buffer.from) {\n\t\t\tconst buf = Buffer.isBuffer(value)\n\t\t\t\t? value\n\t\t\t\t// eslint-disable-next-line no-instanceof/no-instanceof\n\t\t\t\t: value instanceof ArrayBuffer\n\t\t\t\t? Buffer.from(value)\n\t\t\t\t: value.buffer\n\t\t\t\t? Buffer.from(value.buffer, value.byteOffset, value.byteLength)\n\t\t\t\t: Buffer.from(value);\n\t\t\treturn JSON.parse(buf.toString('utf8'));\n\t\t}\n\n\t\treturn JSON.parse(textDecoder!.decode(value));\n\t}\n\n\toverride mapToDriverValue(value: T['data']): Buffer {\n\t\treturn Buffer.from(JSON.stringify(value));\n\t}\n}\n\nexport type SQLiteBlobBufferBuilderInitial = SQLiteBlobBufferBuilder<{\n\tname: TName;\n\tdataType: 'buffer';\n\tcolumnType: 'SQLiteBlobBuffer';\n\tdata: Buffer;\n\tdriverParam: Buffer;\n\tenumValues: undefined;\n}>;\n\nexport class SQLiteBlobBufferBuilder>\n\textends SQLiteColumnBuilder\n{\n\tstatic override readonly [entityKind]: string = 'SQLiteBlobBufferBuilder';\n\n\tconstructor(name: T['name']) {\n\t\tsuper(name, 'buffer', 'SQLiteBlobBuffer');\n\t}\n\n\t/** @internal */\n\toverride build(\n\t\ttable: AnySQLiteTable<{ name: TTableName }>,\n\t): SQLiteBlobBuffer> {\n\t\treturn new SQLiteBlobBuffer>(table, this.config as ColumnBuilderRuntimeConfig);\n\t}\n}\n\nexport class SQLiteBlobBuffer> extends SQLiteColumn {\n\tstatic override readonly [entityKind]: string = 'SQLiteBlobBuffer';\n\n\toverride mapFromDriverValue(value: Buffer | Uint8Array | ArrayBuffer): T['data'] {\n\t\tif (Buffer.isBuffer(value)) {\n\t\t\treturn value;\n\t\t}\n\n\t\treturn Buffer.from(value as Uint8Array);\n\t}\n\n\tgetSQLType(): string {\n\t\treturn 'blob';\n\t}\n}\n\nexport interface BlobConfig {\n\tmode: TMode;\n}\n\n/**\n * It's recommended to use `text('...', { mode: 'json' })` instead of `blob` in JSON mode, because it supports JSON functions:\n * >All JSON functions currently throw an error if any of their arguments are BLOBs because BLOBs are reserved for a future enhancement in which BLOBs will store the binary encoding for JSON.\n *\n * https://www.sqlite.org/json1.html\n */\nexport function blob(): SQLiteBlobJsonBuilderInitial<''>;\nexport function blob(\n\tconfig?: BlobConfig,\n): Equal extends true ? SQLiteBigIntBuilderInitial<''>\n\t: Equal extends true ? SQLiteBlobBufferBuilderInitial<''>\n\t: SQLiteBlobJsonBuilderInitial<''>;\nexport function blob(\n\tname: TName,\n\tconfig?: BlobConfig,\n): Equal extends true ? SQLiteBigIntBuilderInitial\n\t: Equal extends true ? SQLiteBlobBufferBuilderInitial\n\t: SQLiteBlobJsonBuilderInitial;\nexport function blob(a?: string | BlobConfig, b?: BlobConfig) {\n\tconst { name, config } = getColumnNameAndConfig(a, b);\n\tif (config?.mode === 'json') {\n\t\treturn new SQLiteBlobJsonBuilder(name);\n\t}\n\tif (config?.mode === 'bigint') {\n\t\treturn new SQLiteBigIntBuilder(name);\n\t}\n\treturn new SQLiteBlobBufferBuilder(name);\n}\n", "import type {\n\tColumnBuilderBase,\n\tColumnBuilderBaseConfig,\n\tColumnBuilderExtraConfig,\n\tColumnBuilderRuntimeConfig,\n\tColumnDataType,\n\tHasGenerated,\n\tMakeColumnConfig,\n} from '~/column-builder.ts';\nimport { ColumnBuilder } from '~/column-builder.ts';\nimport { Column } from '~/column.ts';\nimport type { ColumnBaseConfig } from '~/column.ts';\nimport { entityKind } from '~/entity.ts';\nimport type { SQL } from '~/sql/sql.ts';\nimport type { ForeignKey, UpdateDeleteAction } from '~/sqlite-core/foreign-keys.ts';\nimport { ForeignKeyBuilder } from '~/sqlite-core/foreign-keys.ts';\nimport type { AnySQLiteTable, SQLiteTable } from '~/sqlite-core/table.ts';\nimport type { Update } from '~/utils.ts';\nimport { uniqueKeyName } from '../unique-constraint.ts';\n\nexport interface ReferenceConfig {\n\tref: () => SQLiteColumn;\n\tactions: {\n\t\tonUpdate?: UpdateDeleteAction;\n\t\tonDelete?: UpdateDeleteAction;\n\t};\n}\n\nexport interface SQLiteColumnBuilderBase<\n\tT extends ColumnBuilderBaseConfig = ColumnBuilderBaseConfig,\n\tTTypeConfig extends object = object,\n> extends ColumnBuilderBase {}\n\nexport interface SQLiteGeneratedColumnConfig {\n\tmode?: 'virtual' | 'stored';\n}\n\nexport abstract class SQLiteColumnBuilder<\n\tT extends ColumnBuilderBaseConfig = ColumnBuilderBaseConfig,\n\tTRuntimeConfig extends object = object,\n\tTTypeConfig extends object = object,\n\tTExtraConfig extends ColumnBuilderExtraConfig = object,\n> extends ColumnBuilder\n\timplements SQLiteColumnBuilderBase\n{\n\tstatic override readonly [entityKind]: string = 'SQLiteColumnBuilder';\n\n\tprivate foreignKeyConfigs: ReferenceConfig[] = [];\n\n\treferences(\n\t\tref: ReferenceConfig['ref'],\n\t\tactions: ReferenceConfig['actions'] = {},\n\t): this {\n\t\tthis.foreignKeyConfigs.push({ ref, actions });\n\t\treturn this;\n\t}\n\n\tunique(\n\t\tname?: string,\n\t): this {\n\t\tthis.config.isUnique = true;\n\t\tthis.config.uniqueName = name;\n\t\treturn this;\n\t}\n\n\tgeneratedAlwaysAs(as: SQL | T['data'] | (() => SQL), config?: SQLiteGeneratedColumnConfig): HasGenerated {\n\t\tthis.config.generated = {\n\t\t\tas,\n\t\t\ttype: 'always',\n\t\t\tmode: config?.mode ?? 'virtual',\n\t\t};\n\t\treturn this as any;\n\t}\n\n\t/** @internal */\n\tbuildForeignKeys(column: SQLiteColumn, table: SQLiteTable): ForeignKey[] {\n\t\treturn this.foreignKeyConfigs.map(({ ref, actions }) => {\n\t\t\treturn ((ref, actions) => {\n\t\t\t\tconst builder = new ForeignKeyBuilder(() => {\n\t\t\t\t\tconst foreignColumn = ref();\n\t\t\t\t\treturn { columns: [column], foreignColumns: [foreignColumn] };\n\t\t\t\t});\n\t\t\t\tif (actions.onUpdate) {\n\t\t\t\t\tbuilder.onUpdate(actions.onUpdate);\n\t\t\t\t}\n\t\t\t\tif (actions.onDelete) {\n\t\t\t\t\tbuilder.onDelete(actions.onDelete);\n\t\t\t\t}\n\t\t\t\treturn builder.build(table);\n\t\t\t})(ref, actions);\n\t\t});\n\t}\n\n\t/** @internal */\n\tabstract build(\n\t\ttable: AnySQLiteTable<{ name: TTableName }>,\n\t): SQLiteColumn>;\n}\n\n// To understand how to use `SQLiteColumn` and `AnySQLiteColumn`, see `Column` and `AnyColumn` documentation.\nexport abstract class SQLiteColumn<\n\tT extends ColumnBaseConfig = ColumnBaseConfig,\n\tTRuntimeConfig extends object = {},\n\tTTypeConfig extends object = {},\n> extends Column {\n\tstatic override readonly [entityKind]: string = 'SQLiteColumn';\n\n\tconstructor(\n\t\toverride readonly table: SQLiteTable,\n\t\tconfig: ColumnBuilderRuntimeConfig,\n\t) {\n\t\tif (!config.uniqueName) {\n\t\t\tconfig.uniqueName = uniqueKeyName(table, [config.name]);\n\t\t}\n\t\tsuper(table, config);\n\t}\n}\n\nexport type AnySQLiteColumn> = {}> = SQLiteColumn<\n\tRequired, TPartial>>\n>;\n", "import { entityKind } from '~/entity.ts';\nimport { TableName } from '~/table.utils.ts';\nimport type { AnySQLiteColumn, SQLiteColumn } from './columns/index.ts';\nimport type { SQLiteTable } from './table.ts';\n\nexport type UpdateDeleteAction = 'cascade' | 'restrict' | 'no action' | 'set null' | 'set default';\n\nexport type Reference = () => {\n\treadonly name?: string;\n\treadonly columns: SQLiteColumn[];\n\treadonly foreignTable: SQLiteTable;\n\treadonly foreignColumns: SQLiteColumn[];\n};\n\nexport class ForeignKeyBuilder {\n\tstatic readonly [entityKind]: string = 'SQLiteForeignKeyBuilder';\n\n\tdeclare _: {\n\t\tbrand: 'SQLiteForeignKeyBuilder';\n\t\tforeignTableName: 'TForeignTableName';\n\t};\n\n\t/** @internal */\n\treference: Reference;\n\n\t/** @internal */\n\t_onUpdate: UpdateDeleteAction | undefined;\n\n\t/** @internal */\n\t_onDelete: UpdateDeleteAction | undefined;\n\n\tconstructor(\n\t\tconfig: () => {\n\t\t\tname?: string;\n\t\t\tcolumns: SQLiteColumn[];\n\t\t\tforeignColumns: SQLiteColumn[];\n\t\t},\n\t\tactions?: {\n\t\t\tonUpdate?: UpdateDeleteAction;\n\t\t\tonDelete?: UpdateDeleteAction;\n\t\t} | undefined,\n\t) {\n\t\tthis.reference = () => {\n\t\t\tconst { name, columns, foreignColumns } = config();\n\t\t\treturn { name, columns, foreignTable: foreignColumns[0]!.table as SQLiteTable, foreignColumns };\n\t\t};\n\t\tif (actions) {\n\t\t\tthis._onUpdate = actions.onUpdate;\n\t\t\tthis._onDelete = actions.onDelete;\n\t\t}\n\t}\n\n\tonUpdate(action: UpdateDeleteAction): this {\n\t\tthis._onUpdate = action;\n\t\treturn this;\n\t}\n\n\tonDelete(action: UpdateDeleteAction): this {\n\t\tthis._onDelete = action;\n\t\treturn this;\n\t}\n\n\t/** @internal */\n\tbuild(table: SQLiteTable): ForeignKey {\n\t\treturn new ForeignKey(table, this);\n\t}\n}\n\nexport class ForeignKey {\n\tstatic readonly [entityKind]: string = 'SQLiteForeignKey';\n\n\treadonly reference: Reference;\n\treadonly onUpdate: UpdateDeleteAction | undefined;\n\treadonly onDelete: UpdateDeleteAction | undefined;\n\n\tconstructor(readonly table: SQLiteTable, builder: ForeignKeyBuilder) {\n\t\tthis.reference = builder.reference;\n\t\tthis.onUpdate = builder._onUpdate;\n\t\tthis.onDelete = builder._onDelete;\n\t}\n\n\tgetName(): string {\n\t\tconst { name, columns, foreignColumns } = this.reference();\n\t\tconst columnNames = columns.map((column) => column.name);\n\t\tconst foreignColumnNames = foreignColumns.map((column) => column.name);\n\t\tconst chunks = [\n\t\t\tthis.table[TableName],\n\t\t\t...columnNames,\n\t\t\tforeignColumns[0]!.table[TableName],\n\t\t\t...foreignColumnNames,\n\t\t];\n\t\treturn name ?? `${chunks.join('_')}_fk`;\n\t}\n}\n\ntype ColumnsWithTable<\n\tTTableName extends string,\n\tTColumns extends SQLiteColumn[],\n> = { [Key in keyof TColumns]: AnySQLiteColumn<{ tableName: TTableName }> };\n\n/**\n * @deprecated please use `foreignKey({ columns: [], foreignColumns: [] })` syntax without callback\n * @param config\n * @returns\n */\nexport function foreignKey<\n\tTTableName extends string,\n\tTForeignTableName extends string,\n\tTColumns extends [AnySQLiteColumn<{ tableName: TTableName }>, ...AnySQLiteColumn<{ tableName: TTableName }>[]],\n>(\n\tconfig: () => {\n\t\tname?: string;\n\t\tcolumns: TColumns;\n\t\tforeignColumns: ColumnsWithTable;\n\t},\n): ForeignKeyBuilder;\nexport function foreignKey<\n\tTTableName extends string,\n\tTForeignTableName extends string,\n\tTColumns extends [AnySQLiteColumn<{ tableName: TTableName }>, ...AnySQLiteColumn<{ tableName: TTableName }>[]],\n>(\n\tconfig: {\n\t\tname?: string;\n\t\tcolumns: TColumns;\n\t\tforeignColumns: ColumnsWithTable;\n\t},\n): ForeignKeyBuilder;\nexport function foreignKey(\n\tconfig: any,\n): ForeignKeyBuilder {\n\tfunction mappedConfig() {\n\t\tif (typeof config === 'function') {\n\t\t\tconst { name, columns, foreignColumns } = config();\n\t\t\treturn {\n\t\t\t\tname,\n\t\t\t\tcolumns,\n\t\t\t\tforeignColumns,\n\t\t\t};\n\t\t}\n\t\treturn config;\n\t}\n\n\treturn new ForeignKeyBuilder(mappedConfig);\n}\n", "import { entityKind } from '~/entity.ts';\nimport { TableName } from '~/table.utils.ts';\nimport type { SQLiteColumn } from './columns/common.ts';\nimport type { SQLiteTable } from './table.ts';\n\nexport function uniqueKeyName(table: SQLiteTable, columns: string[]) {\n\treturn `${table[TableName]}_${columns.join('_')}_unique`;\n}\n\nexport function unique(name?: string): UniqueOnConstraintBuilder {\n\treturn new UniqueOnConstraintBuilder(name);\n}\n\nexport class UniqueConstraintBuilder {\n\tstatic readonly [entityKind]: string = 'SQLiteUniqueConstraintBuilder';\n\n\t/** @internal */\n\tcolumns: SQLiteColumn[];\n\n\tconstructor(\n\t\tcolumns: SQLiteColumn[],\n\t\tprivate name?: string,\n\t) {\n\t\tthis.columns = columns;\n\t}\n\n\t/** @internal */\n\tbuild(table: SQLiteTable): UniqueConstraint {\n\t\treturn new UniqueConstraint(table, this.columns, this.name);\n\t}\n}\n\nexport class UniqueOnConstraintBuilder {\n\tstatic readonly [entityKind]: string = 'SQLiteUniqueOnConstraintBuilder';\n\n\t/** @internal */\n\tname?: string;\n\n\tconstructor(\n\t\tname?: string,\n\t) {\n\t\tthis.name = name;\n\t}\n\n\ton(...columns: [SQLiteColumn, ...SQLiteColumn[]]) {\n\t\treturn new UniqueConstraintBuilder(columns, this.name);\n\t}\n}\n\nexport class UniqueConstraint {\n\tstatic readonly [entityKind]: string = 'SQLiteUniqueConstraint';\n\n\treadonly columns: SQLiteColumn[];\n\treadonly name?: string;\n\n\tconstructor(readonly table: SQLiteTable, columns: SQLiteColumn[], name?: string) {\n\t\tthis.columns = columns;\n\t\tthis.name = name ?? uniqueKeyName(this.table, this.columns.map((column) => column.name));\n\t}\n\n\tgetName() {\n\t\treturn this.name;\n\t}\n}\n", "import type { ColumnBuilderBaseConfig, ColumnBuilderRuntimeConfig, MakeColumnConfig } from '~/column-builder.ts';\nimport type { ColumnBaseConfig } from '~/column.ts';\nimport { entityKind } from '~/entity.ts';\nimport type { SQL } from '~/sql/sql.ts';\nimport type { AnySQLiteTable } from '~/sqlite-core/table.ts';\nimport { type Equal, getColumnNameAndConfig } from '~/utils.ts';\nimport { SQLiteColumn, SQLiteColumnBuilder } from './common.ts';\n\nexport type ConvertCustomConfig> =\n\t& {\n\t\tname: TName;\n\t\tdataType: 'custom';\n\t\tcolumnType: 'SQLiteCustomColumn';\n\t\tdata: T['data'];\n\t\tdriverParam: T['driverData'];\n\t\tenumValues: undefined;\n\t}\n\t& (T['notNull'] extends true ? { notNull: true } : {})\n\t& (T['default'] extends true ? { hasDefault: true } : {});\n\nexport interface SQLiteCustomColumnInnerConfig {\n\tcustomTypeValues: CustomTypeValues;\n}\n\nexport class SQLiteCustomColumnBuilder>\n\textends SQLiteColumnBuilder<\n\t\tT,\n\t\t{\n\t\t\tfieldConfig: CustomTypeValues['config'];\n\t\t\tcustomTypeParams: CustomTypeParams;\n\t\t},\n\t\t{\n\t\t\tsqliteColumnBuilderBrand: 'SQLiteCustomColumnBuilderBrand';\n\t\t}\n\t>\n{\n\tstatic override readonly [entityKind]: string = 'SQLiteCustomColumnBuilder';\n\n\tconstructor(\n\t\tname: T['name'],\n\t\tfieldConfig: CustomTypeValues['config'],\n\t\tcustomTypeParams: CustomTypeParams,\n\t) {\n\t\tsuper(name, 'custom', 'SQLiteCustomColumn');\n\t\tthis.config.fieldConfig = fieldConfig;\n\t\tthis.config.customTypeParams = customTypeParams;\n\t}\n\n\t/** @internal */\n\tbuild(\n\t\ttable: AnySQLiteTable<{ name: TTableName }>,\n\t): SQLiteCustomColumn> {\n\t\treturn new SQLiteCustomColumn>(\n\t\t\ttable,\n\t\t\tthis.config as ColumnBuilderRuntimeConfig,\n\t\t);\n\t}\n}\n\nexport class SQLiteCustomColumn> extends SQLiteColumn {\n\tstatic override readonly [entityKind]: string = 'SQLiteCustomColumn';\n\n\tprivate sqlName: string;\n\tprivate mapTo?: (value: T['data']) => T['driverParam'];\n\tprivate mapFrom?: (value: T['driverParam']) => T['data'];\n\n\tconstructor(\n\t\ttable: AnySQLiteTable<{ name: T['tableName'] }>,\n\t\tconfig: SQLiteCustomColumnBuilder['config'],\n\t) {\n\t\tsuper(table, config);\n\t\tthis.sqlName = config.customTypeParams.dataType(config.fieldConfig);\n\t\tthis.mapTo = config.customTypeParams.toDriver;\n\t\tthis.mapFrom = config.customTypeParams.fromDriver;\n\t}\n\n\tgetSQLType(): string {\n\t\treturn this.sqlName;\n\t}\n\n\toverride mapFromDriverValue(value: T['driverParam']): T['data'] {\n\t\treturn typeof this.mapFrom === 'function' ? this.mapFrom(value) : value as T['data'];\n\t}\n\n\toverride mapToDriverValue(value: T['data']): T['driverParam'] {\n\t\treturn typeof this.mapTo === 'function' ? this.mapTo(value) : value as T['data'];\n\t}\n}\n\nexport type CustomTypeValues = {\n\t/**\n\t * Required type for custom column, that will infer proper type model\n\t *\n\t * Examples:\n\t *\n\t * If you want your column to be `string` type after selecting/or on inserting - use `data: string`. Like `text`, `varchar`\n\t *\n\t * If you want your column to be `number` type after selecting/or on inserting - use `data: number`. Like `integer`\n\t */\n\tdata: unknown;\n\n\t/**\n\t * Type helper, that represents what type database driver is accepting for specific database data type\n\t */\n\tdriverData?: unknown;\n\n\t/**\n\t * What config type should be used for {@link CustomTypeParams} `dataType` generation\n\t */\n\tconfig?: Record;\n\n\t/**\n\t * Whether the config argument should be required or not\n\t * @default false\n\t */\n\tconfigRequired?: boolean;\n\n\t/**\n\t * If your custom data type should be notNull by default you can use `notNull: true`\n\t *\n\t * @example\n\t * const customSerial = customType<{ data: number, notNull: true, default: true }>({\n\t * \t dataType() {\n\t * \t return 'serial';\n\t * },\n\t * });\n\t */\n\tnotNull?: boolean;\n\n\t/**\n\t * If your custom data type has default you can use `default: true`\n\t *\n\t * @example\n\t * const customSerial = customType<{ data: number, notNull: true, default: true }>({\n\t * \t dataType() {\n\t * \t return 'serial';\n\t * },\n\t * });\n\t */\n\tdefault?: boolean;\n};\n\nexport interface CustomTypeParams {\n\t/**\n\t * Database data type string representation, that is used for migrations\n\t * @example\n\t * ```\n\t * `jsonb`, `text`\n\t * ```\n\t *\n\t * If database data type needs additional params you can use them from `config` param\n\t * @example\n\t * ```\n\t * `varchar(256)`, `numeric(2,3)`\n\t * ```\n\t *\n\t * To make `config` be of specific type please use config generic in {@link CustomTypeValues}\n\t *\n\t * @example\n\t * Usage example\n\t * ```\n\t * dataType() {\n\t * return 'boolean';\n\t * },\n\t * ```\n\t * Or\n\t * ```\n\t * dataType(config) {\n\t * \t return typeof config.length !== 'undefined' ? `varchar(${config.length})` : `varchar`;\n\t * \t }\n\t * ```\n\t */\n\tdataType: (config: T['config'] | (Equal extends true ? never : undefined)) => string;\n\n\t/**\n\t * Optional mapping function, between user input and driver\n\t * @example\n\t * For example, when using jsonb we need to map JS/TS object to string before writing to database\n\t * ```\n\t * toDriver(value: TData): string {\n\t * \t return JSON.stringify(value);\n\t * }\n\t * ```\n\t */\n\ttoDriver?: (value: T['data']) => T['driverData'] | SQL;\n\n\t/**\n\t * Optional mapping function, that is responsible for data mapping from database to JS/TS code\n\t * @example\n\t * For example, when using timestamp we need to map string Date representation to JS Date\n\t * ```\n\t * fromDriver(value: string): Date {\n\t * \treturn new Date(value);\n\t * },\n\t * ```\n\t */\n\tfromDriver?: (value: T['driverData']) => T['data'];\n}\n\n/**\n * Custom sqlite database data type generator\n */\nexport function customType(\n\tcustomTypeParams: CustomTypeParams,\n): Equal extends true ? {\n\t\t & T['config']>(\n\t\t\tfieldConfig: TConfig,\n\t\t): SQLiteCustomColumnBuilder>;\n\t\t(\n\t\t\tdbName: TName,\n\t\t\tfieldConfig: T['config'],\n\t\t): SQLiteCustomColumnBuilder>;\n\t}\n\t: {\n\t\t(): SQLiteCustomColumnBuilder>;\n\t\t & T['config']>(\n\t\t\tfieldConfig?: TConfig,\n\t\t): SQLiteCustomColumnBuilder>;\n\t\t(\n\t\t\tdbName: TName,\n\t\t\tfieldConfig?: T['config'],\n\t\t): SQLiteCustomColumnBuilder>;\n\t}\n{\n\treturn (\n\t\ta?: TName | T['config'],\n\t\tb?: T['config'],\n\t): SQLiteCustomColumnBuilder> => {\n\t\tconst { name, config } = getColumnNameAndConfig(a, b);\n\t\treturn new SQLiteCustomColumnBuilder(\n\t\t\tname as ConvertCustomConfig['name'],\n\t\t\tconfig,\n\t\t\tcustomTypeParams,\n\t\t);\n\t};\n}\n", "import type {\n\tColumnBuilderBaseConfig,\n\tColumnBuilderRuntimeConfig,\n\tColumnDataType,\n\tHasDefault,\n\tIsPrimaryKey,\n\tMakeColumnConfig,\n\tNotNull,\n} from '~/column-builder.ts';\nimport type { ColumnBaseConfig } from '~/column.ts';\nimport { entityKind } from '~/entity.ts';\nimport { sql } from '~/sql/sql.ts';\nimport type { OnConflict } from '~/sqlite-core/utils.ts';\nimport { type Equal, getColumnNameAndConfig, type Or } from '~/utils.ts';\nimport type { AnySQLiteTable } from '../table.ts';\nimport { SQLiteColumn, SQLiteColumnBuilder } from './common.ts';\n\nexport interface PrimaryKeyConfig {\n\tautoIncrement?: boolean;\n\tonConflict?: OnConflict;\n}\n\nexport abstract class SQLiteBaseIntegerBuilder<\n\tT extends ColumnBuilderBaseConfig,\n\tTRuntimeConfig extends object = object,\n> extends SQLiteColumnBuilder<\n\tT,\n\tTRuntimeConfig & { autoIncrement: boolean },\n\t{},\n\t{ primaryKeyHasDefault: true }\n> {\n\tstatic override readonly [entityKind]: string = 'SQLiteBaseIntegerBuilder';\n\n\tconstructor(name: T['name'], dataType: T['dataType'], columnType: T['columnType']) {\n\t\tsuper(name, dataType, columnType);\n\t\tthis.config.autoIncrement = false;\n\t}\n\n\toverride primaryKey(config?: PrimaryKeyConfig): IsPrimaryKey>> {\n\t\tif (config?.autoIncrement) {\n\t\t\tthis.config.autoIncrement = true;\n\t\t}\n\t\tthis.config.hasDefault = true;\n\t\treturn super.primaryKey() as IsPrimaryKey>>;\n\t}\n\n\t/** @internal */\n\tabstract override build(\n\t\ttable: AnySQLiteTable<{ name: TTableName }>,\n\t): SQLiteBaseInteger>;\n}\n\nexport abstract class SQLiteBaseInteger<\n\tT extends ColumnBaseConfig,\n\tTRuntimeConfig extends object = object,\n> extends SQLiteColumn {\n\tstatic override readonly [entityKind]: string = 'SQLiteBaseInteger';\n\n\treadonly autoIncrement: boolean = this.config.autoIncrement;\n\n\tgetSQLType(): string {\n\t\treturn 'integer';\n\t}\n}\n\nexport type SQLiteIntegerBuilderInitial = SQLiteIntegerBuilder<{\n\tname: TName;\n\tdataType: 'number';\n\tcolumnType: 'SQLiteInteger';\n\tdata: number;\n\tdriverParam: number;\n\tenumValues: undefined;\n}>;\n\nexport class SQLiteIntegerBuilder>\n\textends SQLiteBaseIntegerBuilder\n{\n\tstatic override readonly [entityKind]: string = 'SQLiteIntegerBuilder';\n\n\tconstructor(name: T['name']) {\n\t\tsuper(name, 'number', 'SQLiteInteger');\n\t}\n\n\tbuild(\n\t\ttable: AnySQLiteTable<{ name: TTableName }>,\n\t): SQLiteInteger> {\n\t\treturn new SQLiteInteger>(\n\t\t\ttable,\n\t\t\tthis.config as ColumnBuilderRuntimeConfig,\n\t\t);\n\t}\n}\n\nexport class SQLiteInteger> extends SQLiteBaseInteger {\n\tstatic override readonly [entityKind]: string = 'SQLiteInteger';\n}\n\nexport type SQLiteTimestampBuilderInitial = SQLiteTimestampBuilder<{\n\tname: TName;\n\tdataType: 'date';\n\tcolumnType: 'SQLiteTimestamp';\n\tdata: Date;\n\tdriverParam: number;\n\tenumValues: undefined;\n}>;\n\nexport class SQLiteTimestampBuilder>\n\textends SQLiteBaseIntegerBuilder\n{\n\tstatic override readonly [entityKind]: string = 'SQLiteTimestampBuilder';\n\n\tconstructor(name: T['name'], mode: 'timestamp' | 'timestamp_ms') {\n\t\tsuper(name, 'date', 'SQLiteTimestamp');\n\t\tthis.config.mode = mode;\n\t}\n\n\t/**\n\t * @deprecated Use `default()` with your own expression instead.\n\t *\n\t * Adds `DEFAULT (cast((julianday('now') - 2440587.5)*86400000 as integer))` to the column, which is the current epoch timestamp in milliseconds.\n\t */\n\tdefaultNow(): HasDefault {\n\t\treturn this.default(sql`(cast((julianday('now') - 2440587.5)*86400000 as integer))`) as any;\n\t}\n\n\tbuild(\n\t\ttable: AnySQLiteTable<{ name: TTableName }>,\n\t): SQLiteTimestamp> {\n\t\treturn new SQLiteTimestamp>(\n\t\t\ttable,\n\t\t\tthis.config as ColumnBuilderRuntimeConfig,\n\t\t);\n\t}\n}\n\nexport class SQLiteTimestamp>\n\textends SQLiteBaseInteger\n{\n\tstatic override readonly [entityKind]: string = 'SQLiteTimestamp';\n\n\treadonly mode: 'timestamp' | 'timestamp_ms' = this.config.mode;\n\n\toverride mapFromDriverValue(value: number): Date {\n\t\tif (this.config.mode === 'timestamp') {\n\t\t\treturn new Date(value * 1000);\n\t\t}\n\t\treturn new Date(value);\n\t}\n\n\toverride mapToDriverValue(value: Date): number {\n\t\tconst unix = value.getTime();\n\t\tif (this.config.mode === 'timestamp') {\n\t\t\treturn Math.floor(unix / 1000);\n\t\t}\n\t\treturn unix;\n\t}\n}\n\nexport type SQLiteBooleanBuilderInitial = SQLiteBooleanBuilder<{\n\tname: TName;\n\tdataType: 'boolean';\n\tcolumnType: 'SQLiteBoolean';\n\tdata: boolean;\n\tdriverParam: number;\n\tenumValues: undefined;\n}>;\n\nexport class SQLiteBooleanBuilder>\n\textends SQLiteBaseIntegerBuilder\n{\n\tstatic override readonly [entityKind]: string = 'SQLiteBooleanBuilder';\n\n\tconstructor(name: T['name'], mode: 'boolean') {\n\t\tsuper(name, 'boolean', 'SQLiteBoolean');\n\t\tthis.config.mode = mode;\n\t}\n\n\tbuild(\n\t\ttable: AnySQLiteTable<{ name: TTableName }>,\n\t): SQLiteBoolean> {\n\t\treturn new SQLiteBoolean>(\n\t\t\ttable,\n\t\t\tthis.config as ColumnBuilderRuntimeConfig,\n\t\t);\n\t}\n}\n\nexport class SQLiteBoolean>\n\textends SQLiteBaseInteger\n{\n\tstatic override readonly [entityKind]: string = 'SQLiteBoolean';\n\n\treadonly mode: 'boolean' = this.config.mode;\n\n\toverride mapFromDriverValue(value: number): boolean {\n\t\treturn Number(value) === 1;\n\t}\n\n\toverride mapToDriverValue(value: boolean): number {\n\t\treturn value ? 1 : 0;\n\t}\n}\n\nexport interface IntegerConfig<\n\tTMode extends 'number' | 'timestamp' | 'timestamp_ms' | 'boolean' =\n\t\t| 'number'\n\t\t| 'timestamp'\n\t\t| 'timestamp_ms'\n\t\t| 'boolean',\n> {\n\tmode: TMode;\n}\n\nexport function integer(): SQLiteIntegerBuilderInitial<''>;\nexport function integer(\n\tconfig?: IntegerConfig,\n): Or, Equal> extends true ? SQLiteTimestampBuilderInitial<''>\n\t: Equal extends true ? SQLiteBooleanBuilderInitial<''>\n\t: SQLiteIntegerBuilderInitial<''>;\nexport function integer(\n\tname: TName,\n\tconfig?: IntegerConfig,\n): Or, Equal> extends true ? SQLiteTimestampBuilderInitial\n\t: Equal extends true ? SQLiteBooleanBuilderInitial\n\t: SQLiteIntegerBuilderInitial;\nexport function integer(a?: string | IntegerConfig, b?: IntegerConfig) {\n\tconst { name, config } = getColumnNameAndConfig(a, b);\n\tif (config?.mode === 'timestamp' || config?.mode === 'timestamp_ms') {\n\t\treturn new SQLiteTimestampBuilder(name, config.mode);\n\t}\n\tif (config?.mode === 'boolean') {\n\t\treturn new SQLiteBooleanBuilder(name, config.mode);\n\t}\n\treturn new SQLiteIntegerBuilder(name);\n}\n\nexport const int = integer;\n", "import type { ColumnBuilderBaseConfig, ColumnBuilderRuntimeConfig, MakeColumnConfig } from '~/column-builder.ts';\nimport type { ColumnBaseConfig } from '~/column.ts';\nimport { entityKind } from '~/entity.ts';\nimport type { AnySQLiteTable } from '~/sqlite-core/table.ts';\nimport { type Equal, getColumnNameAndConfig } from '~/utils.ts';\nimport { SQLiteColumn, SQLiteColumnBuilder } from './common.ts';\n\nexport type SQLiteNumericBuilderInitial = SQLiteNumericBuilder<{\n\tname: TName;\n\tdataType: 'string';\n\tcolumnType: 'SQLiteNumeric';\n\tdata: string;\n\tdriverParam: string;\n\tenumValues: undefined;\n}>;\n\nexport class SQLiteNumericBuilder>\n\textends SQLiteColumnBuilder\n{\n\tstatic override readonly [entityKind]: string = 'SQLiteNumericBuilder';\n\n\tconstructor(name: T['name']) {\n\t\tsuper(name, 'string', 'SQLiteNumeric');\n\t}\n\n\t/** @internal */\n\toverride build(\n\t\ttable: AnySQLiteTable<{ name: TTableName }>,\n\t): SQLiteNumeric> {\n\t\treturn new SQLiteNumeric>(\n\t\t\ttable,\n\t\t\tthis.config as ColumnBuilderRuntimeConfig,\n\t\t);\n\t}\n}\n\nexport class SQLiteNumeric> extends SQLiteColumn {\n\tstatic override readonly [entityKind]: string = 'SQLiteNumeric';\n\n\toverride mapFromDriverValue(value: unknown): string {\n\t\tif (typeof value === 'string') return value;\n\n\t\treturn String(value);\n\t}\n\n\tgetSQLType(): string {\n\t\treturn 'numeric';\n\t}\n}\n\nexport type SQLiteNumericNumberBuilderInitial = SQLiteNumericNumberBuilder<{\n\tname: TName;\n\tdataType: 'number';\n\tcolumnType: 'SQLiteNumericNumber';\n\tdata: number;\n\tdriverParam: string;\n\tenumValues: undefined;\n}>;\n\nexport class SQLiteNumericNumberBuilder>\n\textends SQLiteColumnBuilder\n{\n\tstatic override readonly [entityKind]: string = 'SQLiteNumericNumberBuilder';\n\n\tconstructor(name: T['name']) {\n\t\tsuper(name, 'number', 'SQLiteNumericNumber');\n\t}\n\n\t/** @internal */\n\toverride build(\n\t\ttable: AnySQLiteTable<{ name: TTableName }>,\n\t): SQLiteNumericNumber> {\n\t\treturn new SQLiteNumericNumber>(\n\t\t\ttable,\n\t\t\tthis.config as ColumnBuilderRuntimeConfig,\n\t\t);\n\t}\n}\n\nexport class SQLiteNumericNumber> extends SQLiteColumn {\n\tstatic override readonly [entityKind]: string = 'SQLiteNumericNumber';\n\n\toverride mapFromDriverValue(value: unknown): number {\n\t\tif (typeof value === 'number') return value;\n\n\t\treturn Number(value);\n\t}\n\n\toverride mapToDriverValue = String;\n\n\tgetSQLType(): string {\n\t\treturn 'numeric';\n\t}\n}\n\nexport type SQLiteNumericBigIntBuilderInitial = SQLiteNumericBigIntBuilder<{\n\tname: TName;\n\tdataType: 'bigint';\n\tcolumnType: 'SQLiteNumericBigInt';\n\tdata: bigint;\n\tdriverParam: string;\n\tenumValues: undefined;\n}>;\n\nexport class SQLiteNumericBigIntBuilder>\n\textends SQLiteColumnBuilder\n{\n\tstatic override readonly [entityKind]: string = 'SQLiteNumericBigIntBuilder';\n\n\tconstructor(name: T['name']) {\n\t\tsuper(name, 'bigint', 'SQLiteNumericBigInt');\n\t}\n\n\t/** @internal */\n\toverride build(\n\t\ttable: AnySQLiteTable<{ name: TTableName }>,\n\t): SQLiteNumericBigInt> {\n\t\treturn new SQLiteNumericBigInt>(\n\t\t\ttable,\n\t\t\tthis.config as ColumnBuilderRuntimeConfig,\n\t\t);\n\t}\n}\n\nexport class SQLiteNumericBigInt> extends SQLiteColumn {\n\tstatic override readonly [entityKind]: string = 'SQLiteNumericBigInt';\n\n\toverride mapFromDriverValue = BigInt;\n\n\toverride mapToDriverValue = String;\n\n\tgetSQLType(): string {\n\t\treturn 'numeric';\n\t}\n}\n\nexport type SQLiteNumericConfig = {\n\tmode: T;\n};\n\nexport function numeric(\n\tconfig?: SQLiteNumericConfig,\n): Equal extends true ? SQLiteNumericNumberBuilderInitial<''>\n\t: Equal extends true ? SQLiteNumericBigIntBuilderInitial<''>\n\t: SQLiteNumericBuilderInitial<''>;\nexport function numeric(\n\tname: TName,\n\tconfig?: SQLiteNumericConfig,\n): Equal extends true ? SQLiteNumericNumberBuilderInitial\n\t: Equal extends true ? SQLiteNumericBigIntBuilderInitial\n\t: SQLiteNumericBuilderInitial;\nexport function numeric(a?: string | SQLiteNumericConfig, b?: SQLiteNumericConfig) {\n\tconst { name, config } = getColumnNameAndConfig(a, b);\n\tconst mode = config?.mode;\n\treturn mode === 'number'\n\t\t? new SQLiteNumericNumberBuilder(name)\n\t\t: mode === 'bigint'\n\t\t? new SQLiteNumericBigIntBuilder(name)\n\t\t: new SQLiteNumericBuilder(name);\n}\n", "import type { ColumnBuilderBaseConfig, ColumnBuilderRuntimeConfig, MakeColumnConfig } from '~/column-builder.ts';\nimport type { ColumnBaseConfig } from '~/column.ts';\nimport { entityKind } from '~/entity.ts';\nimport type { AnySQLiteTable } from '../table.ts';\nimport { SQLiteColumn, SQLiteColumnBuilder } from './common.ts';\n\nexport type SQLiteRealBuilderInitial = SQLiteRealBuilder<{\n\tname: TName;\n\tdataType: 'number';\n\tcolumnType: 'SQLiteReal';\n\tdata: number;\n\tdriverParam: number;\n\tenumValues: undefined;\n}>;\n\nexport class SQLiteRealBuilder>\n\textends SQLiteColumnBuilder\n{\n\tstatic override readonly [entityKind]: string = 'SQLiteRealBuilder';\n\n\tconstructor(name: T['name']) {\n\t\tsuper(name, 'number', 'SQLiteReal');\n\t}\n\n\t/** @internal */\n\toverride build(\n\t\ttable: AnySQLiteTable<{ name: TTableName }>,\n\t): SQLiteReal> {\n\t\treturn new SQLiteReal>(table, this.config as ColumnBuilderRuntimeConfig);\n\t}\n}\n\nexport class SQLiteReal> extends SQLiteColumn {\n\tstatic override readonly [entityKind]: string = 'SQLiteReal';\n\n\tgetSQLType(): string {\n\t\treturn 'real';\n\t}\n}\n\nexport function real(): SQLiteRealBuilderInitial<''>;\nexport function real(name: TName): SQLiteRealBuilderInitial;\nexport function real(name?: string) {\n\treturn new SQLiteRealBuilder(name ?? '');\n}\n", "import type { ColumnBuilderBaseConfig, ColumnBuilderRuntimeConfig, MakeColumnConfig } from '~/column-builder.ts';\nimport type { ColumnBaseConfig } from '~/column.ts';\nimport { entityKind } from '~/entity.ts';\nimport type { AnySQLiteTable } from '~/sqlite-core/table.ts';\nimport { type Equal, getColumnNameAndConfig, type Writable } from '~/utils.ts';\nimport { SQLiteColumn, SQLiteColumnBuilder } from './common.ts';\n\nexport type SQLiteTextBuilderInitial<\n\tTName extends string,\n\tTEnum extends [string, ...string[]],\n\tTLength extends number | undefined,\n> = SQLiteTextBuilder<{\n\tname: TName;\n\tdataType: 'string';\n\tcolumnType: 'SQLiteText';\n\tdata: TEnum[number];\n\tdriverParam: string;\n\tenumValues: TEnum;\n\tlength: TLength;\n}>;\n\nexport class SQLiteTextBuilder<\n\tT extends ColumnBuilderBaseConfig<'string', 'SQLiteText'> & { length?: number | undefined },\n> extends SQLiteColumnBuilder<\n\tT,\n\t{ length: T['length']; enumValues: T['enumValues'] },\n\t{ length: T['length'] }\n> {\n\tstatic override readonly [entityKind]: string = 'SQLiteTextBuilder';\n\n\tconstructor(name: T['name'], config: SQLiteTextConfig<'text', T['enumValues'], T['length']>) {\n\t\tsuper(name, 'string', 'SQLiteText');\n\t\tthis.config.enumValues = config.enum;\n\t\tthis.config.length = config.length;\n\t}\n\n\t/** @internal */\n\toverride build(\n\t\ttable: AnySQLiteTable<{ name: TTableName }>,\n\t): SQLiteText & { length: T['length'] }> {\n\t\treturn new SQLiteText & { length: T['length'] }>(\n\t\t\ttable,\n\t\t\tthis.config as ColumnBuilderRuntimeConfig,\n\t\t);\n\t}\n}\n\nexport class SQLiteText & { length?: number | undefined }>\n\textends SQLiteColumn\n{\n\tstatic override readonly [entityKind]: string = 'SQLiteText';\n\n\toverride readonly enumValues = this.config.enumValues;\n\n\treadonly length: T['length'] = this.config.length;\n\n\tconstructor(\n\t\ttable: AnySQLiteTable<{ name: T['tableName'] }>,\n\t\tconfig: SQLiteTextBuilder['config'],\n\t) {\n\t\tsuper(table, config);\n\t}\n\n\tgetSQLType(): string {\n\t\treturn `text${this.config.length ? `(${this.config.length})` : ''}`;\n\t}\n}\n\nexport type SQLiteTextJsonBuilderInitial = SQLiteTextJsonBuilder<{\n\tname: TName;\n\tdataType: 'json';\n\tcolumnType: 'SQLiteTextJson';\n\tdata: unknown;\n\tdriverParam: string;\n\tenumValues: undefined;\n\tgenerated: undefined;\n}>;\n\nexport class SQLiteTextJsonBuilder>\n\textends SQLiteColumnBuilder\n{\n\tstatic override readonly [entityKind]: string = 'SQLiteTextJsonBuilder';\n\n\tconstructor(name: T['name']) {\n\t\tsuper(name, 'json', 'SQLiteTextJson');\n\t}\n\n\t/** @internal */\n\toverride build(\n\t\ttable: AnySQLiteTable<{ name: TTableName }>,\n\t): SQLiteTextJson> {\n\t\treturn new SQLiteTextJson>(\n\t\t\ttable,\n\t\t\tthis.config as ColumnBuilderRuntimeConfig,\n\t\t);\n\t}\n}\n\nexport class SQLiteTextJson>\n\textends SQLiteColumn\n{\n\tstatic override readonly [entityKind]: string = 'SQLiteTextJson';\n\n\tgetSQLType(): string {\n\t\treturn 'text';\n\t}\n\n\toverride mapFromDriverValue(value: string): T['data'] {\n\t\treturn JSON.parse(value);\n\t}\n\n\toverride mapToDriverValue(value: T['data']): string {\n\t\treturn JSON.stringify(value);\n\t}\n}\n\nexport type SQLiteTextConfig<\n\tTMode extends 'text' | 'json' = 'text' | 'json',\n\tTEnum extends readonly string[] | string[] | undefined = readonly string[] | string[] | undefined,\n\tTLength extends number | undefined = number | undefined,\n> = TMode extends 'text' ? {\n\t\tmode?: TMode;\n\t\tlength?: TLength;\n\t\tenum?: TEnum;\n\t}\n\t: {\n\t\tmode?: TMode;\n\t};\n\nexport function text(): SQLiteTextBuilderInitial<'', [string, ...string[]], undefined>;\nexport function text<\n\tU extends string,\n\tT extends Readonly<[U, ...U[]]>,\n\tL extends number | undefined,\n\tTMode extends 'text' | 'json' = 'text' | 'json',\n>(\n\tconfig?: SQLiteTextConfig, L>,\n): Equal extends true ? SQLiteTextJsonBuilderInitial<''>\n\t: SQLiteTextBuilderInitial<'', Writable, L>;\nexport function text<\n\tTName extends string,\n\tU extends string,\n\tT extends Readonly<[U, ...U[]]>,\n\tL extends number | undefined,\n\tTMode extends 'text' | 'json' = 'text' | 'json',\n>(\n\tname: TName,\n\tconfig?: SQLiteTextConfig, L>,\n): Equal extends true ? SQLiteTextJsonBuilderInitial\n\t: SQLiteTextBuilderInitial, L>;\nexport function text(a?: string | SQLiteTextConfig, b: SQLiteTextConfig = {}): any {\n\tconst { name, config } = getColumnNameAndConfig(a, b);\n\tif (config.mode === 'json') {\n\t\treturn new SQLiteTextJsonBuilder(name);\n\t}\n\treturn new SQLiteTextBuilder(name, config as any);\n}\n", "import { is } from '~/entity.ts';\nimport { SQL } from '~/sql/sql.ts';\nimport { Subquery } from '~/subquery.ts';\nimport { Table } from '~/table.ts';\nimport { ViewBaseConfig } from '~/view-common.ts';\nimport type { Check } from './checks.ts';\nimport { CheckBuilder } from './checks.ts';\nimport type { ForeignKey } from './foreign-keys.ts';\nimport { ForeignKeyBuilder } from './foreign-keys.ts';\nimport type { Index } from './indexes.ts';\nimport { IndexBuilder } from './indexes.ts';\nimport type { PrimaryKey } from './primary-keys.ts';\nimport { PrimaryKeyBuilder } from './primary-keys.ts';\nimport { SQLiteTable } from './table.ts';\nimport { type UniqueConstraint, UniqueConstraintBuilder } from './unique-constraint.ts';\nimport type { SQLiteViewBase } from './view-base.ts';\nimport type { SQLiteView } from './view.ts';\n\nexport function getTableConfig(table: TTable) {\n\tconst columns = Object.values(table[SQLiteTable.Symbol.Columns]);\n\tconst indexes: Index[] = [];\n\tconst checks: Check[] = [];\n\tconst primaryKeys: PrimaryKey[] = [];\n\tconst uniqueConstraints: UniqueConstraint[] = [];\n\tconst foreignKeys: ForeignKey[] = Object.values(table[SQLiteTable.Symbol.InlineForeignKeys]);\n\tconst name = table[Table.Symbol.Name];\n\n\tconst extraConfigBuilder = table[SQLiteTable.Symbol.ExtraConfigBuilder];\n\n\tif (extraConfigBuilder !== undefined) {\n\t\tconst extraConfig = extraConfigBuilder(table[SQLiteTable.Symbol.Columns]);\n\t\tconst extraValues = Array.isArray(extraConfig) ? extraConfig.flat(1) as any[] : Object.values(extraConfig);\n\t\tfor (const builder of Object.values(extraValues)) {\n\t\t\tif (is(builder, IndexBuilder)) {\n\t\t\t\tindexes.push(builder.build(table));\n\t\t\t} else if (is(builder, CheckBuilder)) {\n\t\t\t\tchecks.push(builder.build(table));\n\t\t\t} else if (is(builder, UniqueConstraintBuilder)) {\n\t\t\t\tuniqueConstraints.push(builder.build(table));\n\t\t\t} else if (is(builder, PrimaryKeyBuilder)) {\n\t\t\t\tprimaryKeys.push(builder.build(table));\n\t\t\t} else if (is(builder, ForeignKeyBuilder)) {\n\t\t\t\tforeignKeys.push(builder.build(table));\n\t\t\t}\n\t\t}\n\t}\n\n\treturn {\n\t\tcolumns,\n\t\tindexes,\n\t\tforeignKeys,\n\t\tchecks,\n\t\tprimaryKeys,\n\t\tuniqueConstraints,\n\t\tname,\n\t};\n}\n\nexport function extractUsedTable(table: SQLiteTable | Subquery | SQLiteViewBase | SQL): string[] {\n\tif (is(table, SQLiteTable)) {\n\t\treturn [`${table[Table.Symbol.BaseName]}`];\n\t}\n\tif (is(table, Subquery)) {\n\t\treturn table._.usedTables ?? [];\n\t}\n\tif (is(table, SQL)) {\n\t\treturn table.usedTables ?? [];\n\t}\n\treturn [];\n}\n\nexport type OnConflict = 'rollback' | 'abort' | 'fail' | 'ignore' | 'replace';\n\nexport function getViewConfig<\n\tTName extends string = string,\n\tTExisting extends boolean = boolean,\n>(view: SQLiteView) {\n\treturn {\n\t\t...view[ViewBaseConfig],\n\t\t// ...view[SQLiteViewConfig],\n\t};\n}\n", "import { entityKind, is } from '~/entity.ts';\nimport type { TypedQueryBuilder } from '~/query-builders/query-builder.ts';\nimport type { SelectResultFields } from '~/query-builders/select.types.ts';\nimport { QueryPromise } from '~/query-promise.ts';\nimport type { RunnableQuery } from '~/runnable-query.ts';\nimport type { Placeholder, Query, SQLWrapper } from '~/sql/sql.ts';\nimport { Param, SQL, sql } from '~/sql/sql.ts';\nimport type { SQLiteDialect } from '~/sqlite-core/dialect.ts';\nimport type { IndexColumn } from '~/sqlite-core/indexes.ts';\nimport type { SQLitePreparedQuery, SQLiteSession } from '~/sqlite-core/session.ts';\nimport { SQLiteTable } from '~/sqlite-core/table.ts';\nimport type { Subquery } from '~/subquery.ts';\nimport { Columns, Table } from '~/table.ts';\nimport { type DrizzleTypeError, haveSameKeys, mapUpdateSet, orderSelectedFields, type Simplify } from '~/utils.ts';\nimport type { AnySQLiteColumn, SQLiteColumn } from '../columns/common.ts';\nimport { extractUsedTable } from '../utils.ts';\nimport { QueryBuilder } from './query-builder.ts';\nimport type { SelectedFieldsFlat, SelectedFieldsOrdered } from './select.types.ts';\nimport type { SQLiteUpdateSetSource } from './update.ts';\n\nexport interface SQLiteInsertConfig {\n\ttable: TTable;\n\tvalues: Record[] | SQLiteInsertSelectQueryBuilder | SQL;\n\twithList?: Subquery[];\n\tonConflict?: SQL[];\n\treturning?: SelectedFieldsOrdered;\n\tselect?: boolean;\n}\n\nexport type SQLiteInsertValue = Simplify<\n\t{\n\t\t[Key in keyof TTable['$inferInsert']]: TTable['$inferInsert'][Key] | SQL | Placeholder;\n\t}\n>;\n\nexport type SQLiteInsertSelectQueryBuilder = TypedQueryBuilder<\n\t{ [K in keyof TTable['$inferInsert']]: AnySQLiteColumn | SQL | SQL.Aliased | TTable['$inferInsert'][K] }\n>;\n\nexport class SQLiteInsertBuilder<\n\tTTable extends SQLiteTable,\n\tTResultType extends 'sync' | 'async',\n\tTRunResult,\n> {\n\tstatic readonly [entityKind]: string = 'SQLiteInsertBuilder';\n\n\tconstructor(\n\t\tprotected table: TTable,\n\t\tprotected session: SQLiteSession,\n\t\tprotected dialect: SQLiteDialect,\n\t\tprivate withList?: Subquery[],\n\t) {}\n\n\tvalues(value: SQLiteInsertValue): SQLiteInsertBase;\n\tvalues(values: SQLiteInsertValue[]): SQLiteInsertBase;\n\tvalues(\n\t\tvalues: SQLiteInsertValue | SQLiteInsertValue[],\n\t): SQLiteInsertBase {\n\t\tvalues = Array.isArray(values) ? values : [values];\n\t\tif (values.length === 0) {\n\t\t\tthrow new Error('values() must be called with at least one value');\n\t\t}\n\t\tconst mappedValues = values.map((entry) => {\n\t\t\tconst result: Record = {};\n\t\t\tconst cols = this.table[Table.Symbol.Columns];\n\t\t\tfor (const colKey of Object.keys(entry)) {\n\t\t\t\tconst colValue = entry[colKey as keyof typeof entry];\n\t\t\t\tresult[colKey] = is(colValue, SQL) ? colValue : new Param(colValue, cols[colKey]);\n\t\t\t}\n\t\t\treturn result;\n\t\t});\n\n\t\t// if (mappedValues.length > 1 && mappedValues.some((t) => Object.keys(t).length === 0)) {\n\t\t// \tthrow new Error(\n\t\t// \t\t`One of the values you want to insert is empty. In SQLite you can insert only one empty object per statement. For this case Drizzle with use \"INSERT INTO ... DEFAULT VALUES\" syntax`,\n\t\t// \t);\n\t\t// }\n\n\t\treturn new SQLiteInsertBase(this.table, mappedValues, this.session, this.dialect, this.withList);\n\t}\n\n\tselect(\n\t\tselectQuery: (qb: QueryBuilder) => SQLiteInsertSelectQueryBuilder,\n\t): SQLiteInsertBase;\n\tselect(selectQuery: (qb: QueryBuilder) => SQL): SQLiteInsertBase;\n\tselect(selectQuery: SQL): SQLiteInsertBase;\n\tselect(selectQuery: SQLiteInsertSelectQueryBuilder): SQLiteInsertBase;\n\tselect(\n\t\tselectQuery:\n\t\t\t| SQL\n\t\t\t| SQLiteInsertSelectQueryBuilder\n\t\t\t| ((qb: QueryBuilder) => SQLiteInsertSelectQueryBuilder | SQL),\n\t): SQLiteInsertBase {\n\t\tconst select = typeof selectQuery === 'function' ? selectQuery(new QueryBuilder()) : selectQuery;\n\n\t\tif (\n\t\t\t!is(select, SQL)\n\t\t\t&& !haveSameKeys(this.table[Columns], select._.selectedFields)\n\t\t) {\n\t\t\tthrow new Error(\n\t\t\t\t'Insert select error: selected fields are not the same or are in a different order compared to the table definition',\n\t\t\t);\n\t\t}\n\n\t\treturn new SQLiteInsertBase(this.table, select, this.session, this.dialect, this.withList, true);\n\t}\n}\n\nexport type SQLiteInsertWithout =\n\tTDynamic extends true ? T\n\t\t: Omit<\n\t\t\tSQLiteInsertBase<\n\t\t\t\tT['_']['table'],\n\t\t\t\tT['_']['resultType'],\n\t\t\t\tT['_']['runResult'],\n\t\t\t\tT['_']['returning'],\n\t\t\t\tTDynamic,\n\t\t\t\tT['_']['excludedMethods'] | K\n\t\t\t>,\n\t\t\tT['_']['excludedMethods'] | K\n\t\t>;\n\nexport type SQLiteInsertReturning<\n\tT extends AnySQLiteInsert,\n\tTDynamic extends boolean,\n\tTSelectedFields extends SelectedFieldsFlat,\n> = SQLiteInsertWithout<\n\tSQLiteInsertBase<\n\t\tT['_']['table'],\n\t\tT['_']['resultType'],\n\t\tT['_']['runResult'],\n\t\tSelectResultFields,\n\t\tTDynamic,\n\t\tT['_']['excludedMethods']\n\t>,\n\tTDynamic,\n\t'returning'\n>;\n\nexport type SQLiteInsertReturningAll<\n\tT extends AnySQLiteInsert,\n\tTDynamic extends boolean,\n> = SQLiteInsertWithout<\n\tSQLiteInsertBase<\n\t\tT['_']['table'],\n\t\tT['_']['resultType'],\n\t\tT['_']['runResult'],\n\t\tT['_']['table']['$inferSelect'],\n\t\tTDynamic,\n\t\tT['_']['excludedMethods']\n\t>,\n\tTDynamic,\n\t'returning'\n>;\n\nexport type SQLiteInsertOnConflictDoUpdateConfig = {\n\ttarget: IndexColumn | IndexColumn[];\n\t/** @deprecated - use either `targetWhere` or `setWhere` */\n\twhere?: SQL;\n\t// TODO: add tests for targetWhere and setWhere\n\ttargetWhere?: SQL;\n\tsetWhere?: SQL;\n\tset: SQLiteUpdateSetSource;\n};\n\nexport type SQLiteInsertDynamic = SQLiteInsert<\n\tT['_']['table'],\n\tT['_']['resultType'],\n\tT['_']['runResult'],\n\tT['_']['returning']\n>;\n\nexport type SQLiteInsertExecute = T['_']['returning'] extends undefined ? T['_']['runResult']\n\t: T['_']['returning'][];\n\nexport type SQLiteInsertPrepare = SQLitePreparedQuery<\n\t{\n\t\ttype: T['_']['resultType'];\n\t\trun: T['_']['runResult'];\n\t\tall: T['_']['returning'] extends undefined ? DrizzleTypeError<'.all() cannot be used without .returning()'>\n\t\t\t: T['_']['returning'][];\n\t\tget: T['_']['returning'] extends undefined ? DrizzleTypeError<'.get() cannot be used without .returning()'>\n\t\t\t: T['_']['returning'];\n\t\tvalues: T['_']['returning'] extends undefined ? DrizzleTypeError<'.values() cannot be used without .returning()'>\n\t\t\t: any[][];\n\t\texecute: SQLiteInsertExecute;\n\t}\n>;\n\nexport type AnySQLiteInsert = SQLiteInsertBase;\n\nexport type SQLiteInsert<\n\tTTable extends SQLiteTable = SQLiteTable,\n\tTResultType extends 'sync' | 'async' = 'sync' | 'async',\n\tTRunResult = unknown,\n\tTReturning = any,\n> = SQLiteInsertBase;\n\nexport interface SQLiteInsertBase<\n\tTTable extends SQLiteTable,\n\tTResultType extends 'sync' | 'async',\n\tTRunResult,\n\tTReturning = undefined,\n\tTDynamic extends boolean = false,\n\tTExcludedMethods extends string = never,\n> extends\n\tSQLWrapper,\n\tQueryPromise,\n\tRunnableQuery\n{\n\treadonly _: {\n\t\treadonly dialect: 'sqlite';\n\t\treadonly table: TTable;\n\t\treadonly resultType: TResultType;\n\t\treadonly runResult: TRunResult;\n\t\treadonly returning: TReturning;\n\t\treadonly dynamic: TDynamic;\n\t\treadonly excludedMethods: TExcludedMethods;\n\t\treadonly result: TReturning extends undefined ? TRunResult : TReturning[];\n\t};\n}\n\nexport class SQLiteInsertBase<\n\tTTable extends SQLiteTable,\n\t// eslint-disable-next-line @typescript-eslint/no-unused-vars\n\tTResultType extends 'sync' | 'async',\n\tTRunResult,\n\tTReturning = undefined,\n\t// eslint-disable-next-line @typescript-eslint/no-unused-vars\n\tTDynamic extends boolean = false,\n\t// eslint-disable-next-line @typescript-eslint/no-unused-vars\n\tTExcludedMethods extends string = never,\n> extends QueryPromise\n\timplements RunnableQuery, SQLWrapper\n{\n\tstatic override readonly [entityKind]: string = 'SQLiteInsert';\n\n\t/** @internal */\n\tconfig: SQLiteInsertConfig;\n\n\tconstructor(\n\t\ttable: TTable,\n\t\tvalues: SQLiteInsertConfig['values'],\n\t\tprivate session: SQLiteSession,\n\t\tprivate dialect: SQLiteDialect,\n\t\twithList?: Subquery[],\n\t\tselect?: boolean,\n\t) {\n\t\tsuper();\n\t\tthis.config = { table, values: values as any, withList, select };\n\t}\n\n\t/**\n\t * Adds a `returning` clause to the query.\n\t *\n\t * Calling this method will return the specified fields of the inserted rows. If no fields are specified, all fields will be returned.\n\t *\n\t * See docs: {@link https://orm.drizzle.team/docs/insert#insert-returning}\n\t *\n\t * @example\n\t * ```ts\n\t * // Insert one row and return all fields\n\t * const insertedCar: Car[] = await db.insert(cars)\n\t * .values({ brand: 'BMW' })\n\t * .returning();\n\t *\n\t * // Insert one row and return only the id\n\t * const insertedCarId: { id: number }[] = await db.insert(cars)\n\t * .values({ brand: 'BMW' })\n\t * .returning({ id: cars.id });\n\t * ```\n\t */\n\treturning(): SQLiteInsertReturningAll;\n\treturning(\n\t\tfields: TSelectedFields,\n\t): SQLiteInsertReturning;\n\treturning(\n\t\tfields: SelectedFieldsFlat = this.config.table[SQLiteTable.Symbol.Columns],\n\t): SQLiteInsertWithout {\n\t\tthis.config.returning = orderSelectedFields(fields);\n\t\treturn this as any;\n\t}\n\n\t/**\n\t * Adds an `on conflict do nothing` clause to the query.\n\t *\n\t * Calling this method simply avoids inserting a row as its alternative action.\n\t *\n\t * See docs: {@link https://orm.drizzle.team/docs/insert#on-conflict-do-nothing}\n\t *\n\t * @param config The `target` and `where` clauses.\n\t *\n\t * @example\n\t * ```ts\n\t * // Insert one row and cancel the insert if there's a conflict\n\t * await db.insert(cars)\n\t * .values({ id: 1, brand: 'BMW' })\n\t * .onConflictDoNothing();\n\t *\n\t * // Explicitly specify conflict target\n\t * await db.insert(cars)\n\t * .values({ id: 1, brand: 'BMW' })\n\t * .onConflictDoNothing({ target: cars.id });\n\t * ```\n\t */\n\tonConflictDoNothing(config: { target?: IndexColumn | IndexColumn[]; where?: SQL } = {}): this {\n\t\tif (!this.config.onConflict) this.config.onConflict = [];\n\n\t\tif (config.target === undefined) {\n\t\t\tthis.config.onConflict.push(sql` on conflict do nothing`);\n\t\t} else {\n\t\t\tconst targetSql = Array.isArray(config.target) ? sql`${config.target}` : sql`${[config.target]}`;\n\t\t\tconst whereSql = config.where ? sql` where ${config.where}` : sql``;\n\t\t\tthis.config.onConflict.push(sql` on conflict ${targetSql} do nothing${whereSql}`);\n\t\t}\n\t\treturn this;\n\t}\n\n\t/**\n\t * Adds an `on conflict do update` clause to the query.\n\t *\n\t * Calling this method will update the existing row that conflicts with the row proposed for insertion as its alternative action.\n\t *\n\t * See docs: {@link https://orm.drizzle.team/docs/insert#upserts-and-conflicts}\n\t *\n\t * @param config The `target`, `set` and `where` clauses.\n\t *\n\t * @example\n\t * ```ts\n\t * // Update the row if there's a conflict\n\t * await db.insert(cars)\n\t * .values({ id: 1, brand: 'BMW' })\n\t * .onConflictDoUpdate({\n\t * target: cars.id,\n\t * set: { brand: 'Porsche' }\n\t * });\n\t *\n\t * // Upsert with 'where' clause\n\t * await db.insert(cars)\n\t * .values({ id: 1, brand: 'BMW' })\n\t * .onConflictDoUpdate({\n\t * target: cars.id,\n\t * set: { brand: 'newBMW' },\n\t * where: sql`${cars.createdAt} > '2023-01-01'::date`,\n\t * });\n\t * ```\n\t */\n\tonConflictDoUpdate(config: SQLiteInsertOnConflictDoUpdateConfig): this {\n\t\tif (config.where && (config.targetWhere || config.setWhere)) {\n\t\t\tthrow new Error(\n\t\t\t\t'You cannot use both \"where\" and \"targetWhere\"/\"setWhere\" at the same time - \"where\" is deprecated, use \"targetWhere\" or \"setWhere\" instead.',\n\t\t\t);\n\t\t}\n\n\t\tif (!this.config.onConflict) this.config.onConflict = [];\n\n\t\tconst whereSql = config.where ? sql` where ${config.where}` : undefined;\n\t\tconst targetWhereSql = config.targetWhere ? sql` where ${config.targetWhere}` : undefined;\n\t\tconst setWhereSql = config.setWhere ? sql` where ${config.setWhere}` : undefined;\n\t\tconst targetSql = Array.isArray(config.target) ? sql`${config.target}` : sql`${[config.target]}`;\n\t\tconst setSql = this.dialect.buildUpdateSet(this.config.table, mapUpdateSet(this.config.table, config.set));\n\t\tthis.config.onConflict.push(\n\t\t\tsql` on conflict ${targetSql}${targetWhereSql} do update set ${setSql}${whereSql}${setWhereSql}`,\n\t\t);\n\t\treturn this;\n\t}\n\n\t/** @internal */\n\tgetSQL(): SQL {\n\t\treturn this.dialect.buildInsertQuery(this.config);\n\t}\n\n\ttoSQL(): Query {\n\t\tconst { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());\n\t\treturn rest;\n\t}\n\n\t/** @internal */\n\t_prepare(isOneTimeQuery = true): SQLiteInsertPrepare {\n\t\treturn this.session[isOneTimeQuery ? 'prepareOneTimeQuery' : 'prepareQuery'](\n\t\t\tthis.dialect.sqlToQuery(this.getSQL()),\n\t\t\tthis.config.returning,\n\t\t\tthis.config.returning ? 'all' : 'run',\n\t\t\ttrue,\n\t\t\tundefined,\n\t\t\t{\n\t\t\t\ttype: 'insert',\n\t\t\t\ttables: extractUsedTable(this.config.table),\n\t\t\t},\n\t\t) as SQLiteInsertPrepare;\n\t}\n\n\tprepare(): SQLiteInsertPrepare {\n\t\treturn this._prepare(false);\n\t}\n\n\trun: ReturnType['run'] = (placeholderValues) => {\n\t\treturn this._prepare().run(placeholderValues);\n\t};\n\n\tall: ReturnType['all'] = (placeholderValues) => {\n\t\treturn this._prepare().all(placeholderValues);\n\t};\n\n\tget: ReturnType['get'] = (placeholderValues) => {\n\t\treturn this._prepare().get(placeholderValues);\n\t};\n\n\tvalues: ReturnType['values'] = (placeholderValues) => {\n\t\treturn this._prepare().values(placeholderValues);\n\t};\n\n\toverride async execute(): Promise> {\n\t\treturn (this.config.returning ? this.all() : this.run()) as SQLiteInsertExecute;\n\t}\n\n\t$dynamic(): SQLiteInsertDynamic {\n\t\treturn this as any;\n\t}\n}\n", "import { entityKind, is } from '~/entity.ts';\nimport type { TypedQueryBuilder } from '~/query-builders/query-builder.ts';\nimport { SelectionProxyHandler } from '~/selection-proxy.ts';\nimport type { ColumnsSelection, SQL } from '~/sql/sql.ts';\nimport type { SQLiteDialectConfig } from '~/sqlite-core/dialect.ts';\nimport { SQLiteDialect, SQLiteSyncDialect } from '~/sqlite-core/dialect.ts';\nimport type { WithBuilder } from '~/sqlite-core/subquery.ts';\nimport { WithSubquery } from '~/subquery.ts';\nimport { SQLiteSelectBuilder } from './select.ts';\nimport type { SelectedFields } from './select.types.ts';\n\nexport class QueryBuilder {\n\tstatic readonly [entityKind]: string = 'SQLiteQueryBuilder';\n\n\tprivate dialect: SQLiteDialect | undefined;\n\tprivate dialectConfig: SQLiteDialectConfig | undefined;\n\n\tconstructor(dialect?: SQLiteDialect | SQLiteDialectConfig) {\n\t\tthis.dialect = is(dialect, SQLiteDialect) ? dialect : undefined;\n\t\tthis.dialectConfig = is(dialect, SQLiteDialect) ? undefined : dialect;\n\t}\n\n\t$with: WithBuilder = (alias: string, selection?: ColumnsSelection) => {\n\t\tconst queryBuilder = this;\n\t\tconst as = (\n\t\t\tqb:\n\t\t\t\t| TypedQueryBuilder\n\t\t\t\t| SQL\n\t\t\t\t| ((qb: QueryBuilder) => TypedQueryBuilder | SQL),\n\t\t) => {\n\t\t\tif (typeof qb === 'function') {\n\t\t\t\tqb = qb(queryBuilder);\n\t\t\t}\n\n\t\t\treturn new Proxy(\n\t\t\t\tnew WithSubquery(\n\t\t\t\t\tqb.getSQL(),\n\t\t\t\t\tselection ?? ('getSelectedFields' in qb ? qb.getSelectedFields() ?? {} : {}) as SelectedFields,\n\t\t\t\t\talias,\n\t\t\t\t\ttrue,\n\t\t\t\t),\n\t\t\t\tnew SelectionProxyHandler({ alias, sqlAliasedBehavior: 'alias', sqlBehavior: 'error' }),\n\t\t\t) as any;\n\t\t};\n\t\treturn { as };\n\t};\n\n\twith(...queries: WithSubquery[]) {\n\t\tconst self = this;\n\n\t\tfunction select(): SQLiteSelectBuilder;\n\t\tfunction select(\n\t\t\tfields: TSelection,\n\t\t): SQLiteSelectBuilder;\n\t\tfunction select(\n\t\t\tfields?: TSelection,\n\t\t): SQLiteSelectBuilder {\n\t\t\treturn new SQLiteSelectBuilder({\n\t\t\t\tfields: fields ?? undefined,\n\t\t\t\tsession: undefined,\n\t\t\t\tdialect: self.getDialect(),\n\t\t\t\twithList: queries,\n\t\t\t});\n\t\t}\n\n\t\tfunction selectDistinct(): SQLiteSelectBuilder;\n\t\tfunction selectDistinct(\n\t\t\tfields: TSelection,\n\t\t): SQLiteSelectBuilder;\n\t\tfunction selectDistinct(\n\t\t\tfields?: TSelection,\n\t\t): SQLiteSelectBuilder {\n\t\t\treturn new SQLiteSelectBuilder({\n\t\t\t\tfields: fields ?? undefined,\n\t\t\t\tsession: undefined,\n\t\t\t\tdialect: self.getDialect(),\n\t\t\t\twithList: queries,\n\t\t\t\tdistinct: true,\n\t\t\t});\n\t\t}\n\n\t\treturn { select, selectDistinct };\n\t}\n\n\tselect(): SQLiteSelectBuilder;\n\tselect(\n\t\tfields: TSelection,\n\t): SQLiteSelectBuilder;\n\tselect(\n\t\tfields?: TSelection,\n\t): SQLiteSelectBuilder {\n\t\treturn new SQLiteSelectBuilder({ fields: fields ?? undefined, session: undefined, dialect: this.getDialect() });\n\t}\n\n\tselectDistinct(): SQLiteSelectBuilder;\n\tselectDistinct(\n\t\tfields: TSelection,\n\t): SQLiteSelectBuilder;\n\tselectDistinct(\n\t\tfields?: TSelection,\n\t): SQLiteSelectBuilder {\n\t\treturn new SQLiteSelectBuilder({\n\t\t\tfields: fields ?? undefined,\n\t\t\tsession: undefined,\n\t\t\tdialect: this.getDialect(),\n\t\t\tdistinct: true,\n\t\t});\n\t}\n\n\t// Lazy load dialect to avoid circular dependency\n\tprivate getDialect() {\n\t\tif (!this.dialect) {\n\t\t\tthis.dialect = new SQLiteSyncDialect(this.dialectConfig);\n\t\t}\n\n\t\treturn this.dialect;\n\t}\n}\n", "import { aliasedTable, aliasedTableColumn, mapColumnsInAliasedSQLToAlias, mapColumnsInSQLToAlias } from '~/alias.ts';\nimport { CasingCache } from '~/casing.ts';\nimport type { AnyColumn } from '~/column.ts';\nimport { Column } from '~/column.ts';\nimport { entityKind, is } from '~/entity.ts';\nimport { DrizzleError } from '~/errors.ts';\nimport type { MigrationConfig, MigrationMeta } from '~/migrator.ts';\nimport {\n\ttype BuildRelationalQueryResult,\n\ttype DBQueryConfig,\n\tgetOperators,\n\tgetOrderByOperators,\n\tMany,\n\tnormalizeRelation,\n\tOne,\n\ttype Relation,\n\ttype TableRelationalConfig,\n\ttype TablesRelationalConfig,\n} from '~/relations.ts';\nimport type { Name, Placeholder } from '~/sql/index.ts';\nimport { and, eq } from '~/sql/index.ts';\nimport { Param, type QueryWithTypings, SQL, sql, type SQLChunk } from '~/sql/sql.ts';\nimport { SQLiteColumn } from '~/sqlite-core/columns/index.ts';\nimport type {\n\tAnySQLiteSelectQueryBuilder,\n\tSQLiteDeleteConfig,\n\tSQLiteInsertConfig,\n\tSQLiteUpdateConfig,\n} from '~/sqlite-core/query-builders/index.ts';\nimport { SQLiteTable } from '~/sqlite-core/table.ts';\nimport { Subquery } from '~/subquery.ts';\nimport { getTableName, getTableUniqueName, Table } from '~/table.ts';\nimport { type Casing, orderSelectedFields, type UpdateSet } from '~/utils.ts';\nimport { ViewBaseConfig } from '~/view-common.ts';\nimport type {\n\tSelectedFieldsOrdered,\n\tSQLiteSelectConfig,\n\tSQLiteSelectJoinConfig,\n} from './query-builders/select.types.ts';\nimport type { SQLiteSession } from './session.ts';\nimport { SQLiteViewBase } from './view-base.ts';\n\nexport interface SQLiteDialectConfig {\n\tcasing?: Casing;\n}\n\nexport abstract class SQLiteDialect {\n\tstatic readonly [entityKind]: string = 'SQLiteDialect';\n\n\t/** @internal */\n\treadonly casing: CasingCache;\n\n\tconstructor(config?: SQLiteDialectConfig) {\n\t\tthis.casing = new CasingCache(config?.casing);\n\t}\n\n\tescapeName(name: string): string {\n\t\treturn `\"${name}\"`;\n\t}\n\n\tescapeParam(_num: number): string {\n\t\treturn '?';\n\t}\n\n\tescapeString(str: string): string {\n\t\treturn `'${str.replace(/'/g, \"''\")}'`;\n\t}\n\n\tprivate buildWithCTE(queries: Subquery[] | undefined): SQL | undefined {\n\t\tif (!queries?.length) return undefined;\n\n\t\tconst withSqlChunks = [sql`with `];\n\t\tfor (const [i, w] of queries.entries()) {\n\t\t\twithSqlChunks.push(sql`${sql.identifier(w._.alias)} as (${w._.sql})`);\n\t\t\tif (i < queries.length - 1) {\n\t\t\t\twithSqlChunks.push(sql`, `);\n\t\t\t}\n\t\t}\n\t\twithSqlChunks.push(sql` `);\n\t\treturn sql.join(withSqlChunks);\n\t}\n\n\tbuildDeleteQuery({ table, where, returning, withList, limit, orderBy }: SQLiteDeleteConfig): SQL {\n\t\tconst withSql = this.buildWithCTE(withList);\n\n\t\tconst returningSql = returning\n\t\t\t? sql` returning ${this.buildSelection(returning, { isSingleTable: true })}`\n\t\t\t: undefined;\n\n\t\tconst whereSql = where ? sql` where ${where}` : undefined;\n\n\t\tconst orderBySql = this.buildOrderBy(orderBy);\n\n\t\tconst limitSql = this.buildLimit(limit);\n\n\t\treturn sql`${withSql}delete from ${table}${whereSql}${returningSql}${orderBySql}${limitSql}`;\n\t}\n\n\tbuildUpdateSet(table: SQLiteTable, set: UpdateSet): SQL {\n\t\tconst tableColumns = table[Table.Symbol.Columns];\n\n\t\tconst columnNames = Object.keys(tableColumns).filter((colName) =>\n\t\t\tset[colName] !== undefined || tableColumns[colName]?.onUpdateFn !== undefined\n\t\t);\n\n\t\tconst setSize = columnNames.length;\n\t\treturn sql.join(columnNames.flatMap((colName, i) => {\n\t\t\tconst col = tableColumns[colName]!;\n\n\t\t\tconst onUpdateFnResult = col.onUpdateFn?.();\n\t\t\tconst value = set[colName] ?? (is(onUpdateFnResult, SQL) ? onUpdateFnResult : sql.param(onUpdateFnResult, col));\n\t\t\tconst res = sql`${sql.identifier(this.casing.getColumnCasing(col))} = ${value}`;\n\n\t\t\tif (i < setSize - 1) {\n\t\t\t\treturn [res, sql.raw(', ')];\n\t\t\t}\n\t\t\treturn [res];\n\t\t}));\n\t}\n\n\tbuildUpdateQuery({ table, set, where, returning, withList, joins, from, limit, orderBy }: SQLiteUpdateConfig): SQL {\n\t\tconst withSql = this.buildWithCTE(withList);\n\n\t\tconst setSql = this.buildUpdateSet(table, set);\n\n\t\tconst fromSql = from && sql.join([sql.raw(' from '), this.buildFromTable(from)]);\n\n\t\tconst joinsSql = this.buildJoins(joins);\n\n\t\tconst returningSql = returning\n\t\t\t? sql` returning ${this.buildSelection(returning, { isSingleTable: true })}`\n\t\t\t: undefined;\n\n\t\tconst whereSql = where ? sql` where ${where}` : undefined;\n\n\t\tconst orderBySql = this.buildOrderBy(orderBy);\n\n\t\tconst limitSql = this.buildLimit(limit);\n\n\t\treturn sql`${withSql}update ${table} set ${setSql}${fromSql}${joinsSql}${whereSql}${returningSql}${orderBySql}${limitSql}`;\n\t}\n\n\t/**\n\t * Builds selection SQL with provided fields/expressions\n\t *\n\t * Examples:\n\t *\n\t * `select from`\n\t *\n\t * `insert ... returning `\n\t *\n\t * If `isSingleTable` is true, then columns won't be prefixed with table name\n\t */\n\tprivate buildSelection(\n\t\tfields: SelectedFieldsOrdered,\n\t\t{ isSingleTable = false }: { isSingleTable?: boolean } = {},\n\t): SQL {\n\t\tconst columnsLen = fields.length;\n\n\t\tconst chunks = fields\n\t\t\t.flatMap(({ field }, i) => {\n\t\t\t\tconst chunk: SQLChunk[] = [];\n\n\t\t\t\tif (is(field, SQL.Aliased) && field.isSelectionField) {\n\t\t\t\t\tchunk.push(sql.identifier(field.fieldAlias));\n\t\t\t\t} else if (is(field, SQL.Aliased) || is(field, SQL)) {\n\t\t\t\t\tconst query = is(field, SQL.Aliased) ? field.sql : field;\n\n\t\t\t\t\tif (isSingleTable) {\n\t\t\t\t\t\tchunk.push(\n\t\t\t\t\t\t\tnew SQL(\n\t\t\t\t\t\t\t\tquery.queryChunks.map((c) => {\n\t\t\t\t\t\t\t\t\tif (is(c, Column)) {\n\t\t\t\t\t\t\t\t\t\treturn sql.identifier(this.casing.getColumnCasing(c));\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\treturn c;\n\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tchunk.push(query);\n\t\t\t\t\t}\n\n\t\t\t\t\tif (is(field, SQL.Aliased)) {\n\t\t\t\t\t\tchunk.push(sql` as ${sql.identifier(field.fieldAlias)}`);\n\t\t\t\t\t}\n\t\t\t\t} else if (is(field, Column)) {\n\t\t\t\t\tconst tableName = field.table[Table.Symbol.Name];\n\t\t\t\t\tif (field.columnType === 'SQLiteNumericBigInt') {\n\t\t\t\t\t\tif (isSingleTable) {\n\t\t\t\t\t\t\tchunk.push(sql`cast(${sql.identifier(this.casing.getColumnCasing(field))} as text)`);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tchunk.push(\n\t\t\t\t\t\t\t\tsql`cast(${sql.identifier(tableName)}.${sql.identifier(this.casing.getColumnCasing(field))} as text)`,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tif (isSingleTable) {\n\t\t\t\t\t\t\tchunk.push(sql.identifier(this.casing.getColumnCasing(field)));\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tchunk.push(sql`${sql.identifier(tableName)}.${sql.identifier(this.casing.getColumnCasing(field))}`);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else if (is(field, Subquery)) {\n\t\t\t\t\tconst entries = Object.entries(field._.selectedFields) as [string, SQL.Aliased | Column | SQL][];\n\n\t\t\t\t\tif (entries.length === 1) {\n\t\t\t\t\t\tconst entry = entries[0]![1];\n\n\t\t\t\t\t\tconst fieldDecoder = is(entry, SQL)\n\t\t\t\t\t\t\t? entry.decoder\n\t\t\t\t\t\t\t: is(entry, Column)\n\t\t\t\t\t\t\t? { mapFromDriverValue: (v: any) => entry.mapFromDriverValue(v) }\n\t\t\t\t\t\t\t: entry.sql.decoder;\n\t\t\t\t\t\tif (fieldDecoder) field._.sql.decoder = fieldDecoder;\n\t\t\t\t\t}\n\t\t\t\t\tchunk.push(field);\n\t\t\t\t}\n\n\t\t\t\tif (i < columnsLen - 1) {\n\t\t\t\t\tchunk.push(sql`, `);\n\t\t\t\t}\n\n\t\t\t\treturn chunk;\n\t\t\t});\n\n\t\treturn sql.join(chunks);\n\t}\n\n\tprivate buildJoins(joins: SQLiteSelectJoinConfig[] | undefined): SQL | undefined {\n\t\tif (!joins || joins.length === 0) {\n\t\t\treturn undefined;\n\t\t}\n\n\t\tconst joinsArray: SQL[] = [];\n\n\t\tif (joins) {\n\t\t\tfor (const [index, joinMeta] of joins.entries()) {\n\t\t\t\tif (index === 0) {\n\t\t\t\t\tjoinsArray.push(sql` `);\n\t\t\t\t}\n\t\t\t\tconst table = joinMeta.table;\n\t\t\t\tconst onSql = joinMeta.on ? sql` on ${joinMeta.on}` : undefined;\n\n\t\t\t\tif (is(table, SQLiteTable)) {\n\t\t\t\t\tconst tableName = table[SQLiteTable.Symbol.Name];\n\t\t\t\t\tconst tableSchema = table[SQLiteTable.Symbol.Schema];\n\t\t\t\t\tconst origTableName = table[SQLiteTable.Symbol.OriginalName];\n\t\t\t\t\tconst alias = tableName === origTableName ? undefined : joinMeta.alias;\n\t\t\t\t\tjoinsArray.push(\n\t\t\t\t\t\tsql`${sql.raw(joinMeta.joinType)} join ${tableSchema ? sql`${sql.identifier(tableSchema)}.` : undefined}${\n\t\t\t\t\t\t\tsql.identifier(origTableName)\n\t\t\t\t\t\t}${alias && sql` ${sql.identifier(alias)}`}${onSql}`,\n\t\t\t\t\t);\n\t\t\t\t} else {\n\t\t\t\t\tjoinsArray.push(\n\t\t\t\t\t\tsql`${sql.raw(joinMeta.joinType)} join ${table}${onSql}`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tif (index < joins.length - 1) {\n\t\t\t\t\tjoinsArray.push(sql` `);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn sql.join(joinsArray);\n\t}\n\n\tprivate buildLimit(limit: number | Placeholder | undefined): SQL | undefined {\n\t\treturn typeof limit === 'object' || (typeof limit === 'number' && limit >= 0)\n\t\t\t? sql` limit ${limit}`\n\t\t\t: undefined;\n\t}\n\n\tprivate buildOrderBy(orderBy: (SQLiteColumn | SQL | SQL.Aliased)[] | undefined): SQL | undefined {\n\t\tconst orderByList: (SQLiteColumn | SQL | SQL.Aliased)[] = [];\n\n\t\tif (orderBy) {\n\t\t\tfor (const [index, orderByValue] of orderBy.entries()) {\n\t\t\t\torderByList.push(orderByValue);\n\n\t\t\t\tif (index < orderBy.length - 1) {\n\t\t\t\t\torderByList.push(sql`, `);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn orderByList.length > 0 ? sql` order by ${sql.join(orderByList)}` : undefined;\n\t}\n\n\tprivate buildFromTable(\n\t\ttable: SQL | Subquery | SQLiteViewBase | SQLiteTable | undefined,\n\t): SQL | Subquery | SQLiteViewBase | SQLiteTable | undefined {\n\t\tif (is(table, Table) && table[Table.Symbol.IsAlias]) {\n\t\t\treturn sql`${sql`${sql.identifier(table[Table.Symbol.Schema] ?? '')}.`.if(table[Table.Symbol.Schema])}${\n\t\t\t\tsql.identifier(table[Table.Symbol.OriginalName])\n\t\t\t} ${sql.identifier(table[Table.Symbol.Name])}`;\n\t\t}\n\n\t\treturn table;\n\t}\n\n\tbuildSelectQuery(\n\t\t{\n\t\t\twithList,\n\t\t\tfields,\n\t\t\tfieldsFlat,\n\t\t\twhere,\n\t\t\thaving,\n\t\t\ttable,\n\t\t\tjoins,\n\t\t\torderBy,\n\t\t\tgroupBy,\n\t\t\tlimit,\n\t\t\toffset,\n\t\t\tdistinct,\n\t\t\tsetOperators,\n\t\t}: SQLiteSelectConfig,\n\t): SQL {\n\t\tconst fieldsList = fieldsFlat ?? orderSelectedFields(fields);\n\t\tfor (const f of fieldsList) {\n\t\t\tif (\n\t\t\t\tis(f.field, Column)\n\t\t\t\t&& getTableName(f.field.table)\n\t\t\t\t\t!== (is(table, Subquery)\n\t\t\t\t\t\t? table._.alias\n\t\t\t\t\t\t: is(table, SQLiteViewBase)\n\t\t\t\t\t\t? table[ViewBaseConfig].name\n\t\t\t\t\t\t: is(table, SQL)\n\t\t\t\t\t\t? undefined\n\t\t\t\t\t\t: getTableName(table))\n\t\t\t\t&& !((table) =>\n\t\t\t\t\tjoins?.some(({ alias }) =>\n\t\t\t\t\t\talias === (table[Table.Symbol.IsAlias] ? getTableName(table) : table[Table.Symbol.BaseName])\n\t\t\t\t\t))(f.field.table)\n\t\t\t) {\n\t\t\t\tconst tableName = getTableName(f.field.table);\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Your \"${\n\t\t\t\t\t\tf.path.join('->')\n\t\t\t\t\t}\" field references a column \"${tableName}\".\"${f.field.name}\", but the table \"${tableName}\" is not part of the query! Did you forget to join it?`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\tconst isSingleTable = !joins || joins.length === 0;\n\n\t\tconst withSql = this.buildWithCTE(withList);\n\n\t\tconst distinctSql = distinct ? sql` distinct` : undefined;\n\n\t\tconst selection = this.buildSelection(fieldsList, { isSingleTable });\n\n\t\tconst tableSql = this.buildFromTable(table);\n\n\t\tconst joinsSql = this.buildJoins(joins);\n\n\t\tconst whereSql = where ? sql` where ${where}` : undefined;\n\n\t\tconst havingSql = having ? sql` having ${having}` : undefined;\n\n\t\tconst groupByList: (SQL | AnyColumn | SQL.Aliased)[] = [];\n\t\tif (groupBy) {\n\t\t\tfor (const [index, groupByValue] of groupBy.entries()) {\n\t\t\t\tgroupByList.push(groupByValue);\n\n\t\t\t\tif (index < groupBy.length - 1) {\n\t\t\t\t\tgroupByList.push(sql`, `);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tconst groupBySql = groupByList.length > 0 ? sql` group by ${sql.join(groupByList)}` : undefined;\n\n\t\tconst orderBySql = this.buildOrderBy(orderBy);\n\n\t\tconst limitSql = this.buildLimit(limit);\n\n\t\tconst offsetSql = offset ? sql` offset ${offset}` : undefined;\n\n\t\tconst finalQuery =\n\t\t\tsql`${withSql}select${distinctSql} ${selection} from ${tableSql}${joinsSql}${whereSql}${groupBySql}${havingSql}${orderBySql}${limitSql}${offsetSql}`;\n\n\t\tif (setOperators.length > 0) {\n\t\t\treturn this.buildSetOperations(finalQuery, setOperators);\n\t\t}\n\n\t\treturn finalQuery;\n\t}\n\n\tbuildSetOperations(leftSelect: SQL, setOperators: SQLiteSelectConfig['setOperators']): SQL {\n\t\tconst [setOperator, ...rest] = setOperators;\n\n\t\tif (!setOperator) {\n\t\t\tthrow new Error('Cannot pass undefined values to any set operator');\n\t\t}\n\n\t\tif (rest.length === 0) {\n\t\t\treturn this.buildSetOperationQuery({ leftSelect, setOperator });\n\t\t}\n\n\t\t// Some recursive magic here\n\t\treturn this.buildSetOperations(\n\t\t\tthis.buildSetOperationQuery({ leftSelect, setOperator }),\n\t\t\trest,\n\t\t);\n\t}\n\n\tbuildSetOperationQuery({\n\t\tleftSelect,\n\t\tsetOperator: { type, isAll, rightSelect, limit, orderBy, offset },\n\t}: { leftSelect: SQL; setOperator: SQLiteSelectConfig['setOperators'][number] }): SQL {\n\t\t// SQLite doesn't support parenthesis in set operations\n\t\tconst leftChunk = sql`${leftSelect.getSQL()} `;\n\t\tconst rightChunk = sql`${rightSelect.getSQL()}`;\n\n\t\tlet orderBySql;\n\t\tif (orderBy && orderBy.length > 0) {\n\t\t\tconst orderByValues: (SQL | Name)[] = [];\n\n\t\t\t// The next bit is necessary because the sql operator replaces ${table.column} with `table`.`column`\n\t\t\t// which is invalid Sql syntax, Table from one of the SELECTs cannot be used in global ORDER clause\n\t\t\tfor (const singleOrderBy of orderBy) {\n\t\t\t\tif (is(singleOrderBy, SQLiteColumn)) {\n\t\t\t\t\torderByValues.push(sql.identifier(singleOrderBy.name));\n\t\t\t\t} else if (is(singleOrderBy, SQL)) {\n\t\t\t\t\tfor (let i = 0; i < singleOrderBy.queryChunks.length; i++) {\n\t\t\t\t\t\tconst chunk = singleOrderBy.queryChunks[i];\n\n\t\t\t\t\t\tif (is(chunk, SQLiteColumn)) {\n\t\t\t\t\t\t\tsingleOrderBy.queryChunks[i] = sql.identifier(this.casing.getColumnCasing(chunk));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\torderByValues.push(sql`${singleOrderBy}`);\n\t\t\t\t} else {\n\t\t\t\t\torderByValues.push(sql`${singleOrderBy}`);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\torderBySql = sql` order by ${sql.join(orderByValues, sql`, `)}`;\n\t\t}\n\n\t\tconst limitSql = typeof limit === 'object' || (typeof limit === 'number' && limit >= 0)\n\t\t\t? sql` limit ${limit}`\n\t\t\t: undefined;\n\n\t\tconst operatorChunk = sql.raw(`${type} ${isAll ? 'all ' : ''}`);\n\n\t\tconst offsetSql = offset ? sql` offset ${offset}` : undefined;\n\n\t\treturn sql`${leftChunk}${operatorChunk}${rightChunk}${orderBySql}${limitSql}${offsetSql}`;\n\t}\n\n\tbuildInsertQuery(\n\t\t{ table, values: valuesOrSelect, onConflict, returning, withList, select }: SQLiteInsertConfig,\n\t): SQL {\n\t\t// const isSingleValue = values.length === 1;\n\t\tconst valuesSqlList: ((SQLChunk | SQL)[] | SQL)[] = [];\n\t\tconst columns: Record = table[Table.Symbol.Columns];\n\n\t\tconst colEntries: [string, SQLiteColumn][] = Object.entries(columns).filter(([_, col]) =>\n\t\t\t!col.shouldDisableInsert()\n\t\t);\n\t\tconst insertOrder = colEntries.map(([, column]) => sql.identifier(this.casing.getColumnCasing(column)));\n\n\t\tif (select) {\n\t\t\tconst select = valuesOrSelect as AnySQLiteSelectQueryBuilder | SQL;\n\n\t\t\tif (is(select, SQL)) {\n\t\t\t\tvaluesSqlList.push(select);\n\t\t\t} else {\n\t\t\t\tvaluesSqlList.push(select.getSQL());\n\t\t\t}\n\t\t} else {\n\t\t\tconst values = valuesOrSelect as Record[];\n\t\t\tvaluesSqlList.push(sql.raw('values '));\n\n\t\t\tfor (const [valueIndex, value] of values.entries()) {\n\t\t\t\tconst valueList: (SQLChunk | SQL)[] = [];\n\t\t\t\tfor (const [fieldName, col] of colEntries) {\n\t\t\t\t\tconst colValue = value[fieldName];\n\t\t\t\t\tif (colValue === undefined || (is(colValue, Param) && colValue.value === undefined)) {\n\t\t\t\t\t\tlet defaultValue;\n\t\t\t\t\t\tif (col.default !== null && col.default !== undefined) {\n\t\t\t\t\t\t\tdefaultValue = is(col.default, SQL) ? col.default : sql.param(col.default, col);\n\t\t\t\t\t\t\t// eslint-disable-next-line unicorn/no-negated-condition\n\t\t\t\t\t\t} else if (col.defaultFn !== undefined) {\n\t\t\t\t\t\t\tconst defaultFnResult = col.defaultFn();\n\t\t\t\t\t\t\tdefaultValue = is(defaultFnResult, SQL) ? defaultFnResult : sql.param(defaultFnResult, col);\n\t\t\t\t\t\t\t// eslint-disable-next-line unicorn/no-negated-condition\n\t\t\t\t\t\t} else if (!col.default && col.onUpdateFn !== undefined) {\n\t\t\t\t\t\t\tconst onUpdateFnResult = col.onUpdateFn();\n\t\t\t\t\t\t\tdefaultValue = is(onUpdateFnResult, SQL) ? onUpdateFnResult : sql.param(onUpdateFnResult, col);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tdefaultValue = sql`null`;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tvalueList.push(defaultValue);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tvalueList.push(colValue);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tvaluesSqlList.push(valueList);\n\t\t\t\tif (valueIndex < values.length - 1) {\n\t\t\t\t\tvaluesSqlList.push(sql`, `);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tconst withSql = this.buildWithCTE(withList);\n\n\t\tconst valuesSql = sql.join(valuesSqlList);\n\n\t\tconst returningSql = returning\n\t\t\t? sql` returning ${this.buildSelection(returning, { isSingleTable: true })}`\n\t\t\t: undefined;\n\n\t\tconst onConflictSql = onConflict?.length\n\t\t\t? sql.join(onConflict)\n\t\t\t: undefined;\n\n\t\t// if (isSingleValue && valuesSqlList.length === 0){\n\t\t// \treturn sql`insert into ${table} default values ${onConflictSql}${returningSql}`;\n\t\t// }\n\n\t\treturn sql`${withSql}insert into ${table} ${insertOrder} ${valuesSql}${onConflictSql}${returningSql}`;\n\t}\n\n\tsqlToQuery(sql: SQL, invokeSource?: 'indexes' | undefined): QueryWithTypings {\n\t\treturn sql.toQuery({\n\t\t\tcasing: this.casing,\n\t\t\tescapeName: this.escapeName,\n\t\t\tescapeParam: this.escapeParam,\n\t\t\tescapeString: this.escapeString,\n\t\t\tinvokeSource,\n\t\t});\n\t}\n\n\tbuildRelationalQuery({\n\t\tfullSchema,\n\t\tschema,\n\t\ttableNamesMap,\n\t\ttable,\n\t\ttableConfig,\n\t\tqueryConfig: config,\n\t\ttableAlias,\n\t\tnestedQueryRelation,\n\t\tjoinOn,\n\t}: {\n\t\tfullSchema: Record;\n\t\tschema: TablesRelationalConfig;\n\t\ttableNamesMap: Record;\n\t\ttable: SQLiteTable;\n\t\ttableConfig: TableRelationalConfig;\n\t\tqueryConfig: true | DBQueryConfig<'many', true>;\n\t\ttableAlias: string;\n\t\tnestedQueryRelation?: Relation;\n\t\tjoinOn?: SQL;\n\t}): BuildRelationalQueryResult {\n\t\tlet selection: BuildRelationalQueryResult['selection'] = [];\n\t\tlet limit, offset, orderBy: SQLiteSelectConfig['orderBy'] = [], where;\n\t\tconst joins: SQLiteSelectJoinConfig[] = [];\n\n\t\tif (config === true) {\n\t\t\tconst selectionEntries = Object.entries(tableConfig.columns);\n\t\t\tselection = selectionEntries.map((\n\t\t\t\t[key, value],\n\t\t\t) => ({\n\t\t\t\tdbKey: value.name,\n\t\t\t\ttsKey: key,\n\t\t\t\tfield: aliasedTableColumn(value as SQLiteColumn, tableAlias),\n\t\t\t\trelationTableTsKey: undefined,\n\t\t\t\tisJson: false,\n\t\t\t\tselection: [],\n\t\t\t}));\n\t\t} else {\n\t\t\tconst aliasedColumns = Object.fromEntries(\n\t\t\t\tObject.entries(tableConfig.columns).map(([key, value]) => [key, aliasedTableColumn(value, tableAlias)]),\n\t\t\t);\n\n\t\t\tif (config.where) {\n\t\t\t\tconst whereSql = typeof config.where === 'function'\n\t\t\t\t\t? config.where(aliasedColumns, getOperators())\n\t\t\t\t\t: config.where;\n\t\t\t\twhere = whereSql && mapColumnsInSQLToAlias(whereSql, tableAlias);\n\t\t\t}\n\n\t\t\tconst fieldsSelection: { tsKey: string; value: SQLiteColumn | SQL.Aliased }[] = [];\n\t\t\tlet selectedColumns: string[] = [];\n\n\t\t\t// Figure out which columns to select\n\t\t\tif (config.columns) {\n\t\t\t\tlet isIncludeMode = false;\n\n\t\t\t\tfor (const [field, value] of Object.entries(config.columns)) {\n\t\t\t\t\tif (value === undefined) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (field in tableConfig.columns) {\n\t\t\t\t\t\tif (!isIncludeMode && value === true) {\n\t\t\t\t\t\t\tisIncludeMode = true;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tselectedColumns.push(field);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (selectedColumns.length > 0) {\n\t\t\t\t\tselectedColumns = isIncludeMode\n\t\t\t\t\t\t? selectedColumns.filter((c) => config.columns?.[c] === true)\n\t\t\t\t\t\t: Object.keys(tableConfig.columns).filter((key) => !selectedColumns.includes(key));\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// Select all columns if selection is not specified\n\t\t\t\tselectedColumns = Object.keys(tableConfig.columns);\n\t\t\t}\n\n\t\t\tfor (const field of selectedColumns) {\n\t\t\t\tconst column = tableConfig.columns[field]! as SQLiteColumn;\n\t\t\t\tfieldsSelection.push({ tsKey: field, value: column });\n\t\t\t}\n\n\t\t\tlet selectedRelations: {\n\t\t\t\ttsKey: string;\n\t\t\t\tqueryConfig: true | DBQueryConfig<'many', false>;\n\t\t\t\trelation: Relation;\n\t\t\t}[] = [];\n\n\t\t\t// Figure out which relations to select\n\t\t\tif (config.with) {\n\t\t\t\tselectedRelations = Object.entries(config.with)\n\t\t\t\t\t.filter((entry): entry is [typeof entry[0], NonNullable] => !!entry[1])\n\t\t\t\t\t.map(([tsKey, queryConfig]) => ({ tsKey, queryConfig, relation: tableConfig.relations[tsKey]! }));\n\t\t\t}\n\n\t\t\tlet extras;\n\n\t\t\t// Figure out which extras to select\n\t\t\tif (config.extras) {\n\t\t\t\textras = typeof config.extras === 'function'\n\t\t\t\t\t? config.extras(aliasedColumns, { sql })\n\t\t\t\t\t: config.extras;\n\t\t\t\tfor (const [tsKey, value] of Object.entries(extras)) {\n\t\t\t\t\tfieldsSelection.push({\n\t\t\t\t\t\ttsKey,\n\t\t\t\t\t\tvalue: mapColumnsInAliasedSQLToAlias(value, tableAlias),\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Transform `fieldsSelection` into `selection`\n\t\t\t// `fieldsSelection` shouldn't be used after this point\n\t\t\tfor (const { tsKey, value } of fieldsSelection) {\n\t\t\t\tselection.push({\n\t\t\t\t\tdbKey: is(value, SQL.Aliased) ? value.fieldAlias : tableConfig.columns[tsKey]!.name,\n\t\t\t\t\ttsKey,\n\t\t\t\t\tfield: is(value, Column) ? aliasedTableColumn(value, tableAlias) : value,\n\t\t\t\t\trelationTableTsKey: undefined,\n\t\t\t\t\tisJson: false,\n\t\t\t\t\tselection: [],\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tlet orderByOrig = typeof config.orderBy === 'function'\n\t\t\t\t? config.orderBy(aliasedColumns, getOrderByOperators())\n\t\t\t\t: config.orderBy ?? [];\n\t\t\tif (!Array.isArray(orderByOrig)) {\n\t\t\t\torderByOrig = [orderByOrig];\n\t\t\t}\n\t\t\torderBy = orderByOrig.map((orderByValue) => {\n\t\t\t\tif (is(orderByValue, Column)) {\n\t\t\t\t\treturn aliasedTableColumn(orderByValue, tableAlias) as SQLiteColumn;\n\t\t\t\t}\n\t\t\t\treturn mapColumnsInSQLToAlias(orderByValue, tableAlias);\n\t\t\t});\n\n\t\t\tlimit = config.limit;\n\t\t\toffset = config.offset;\n\n\t\t\t// Process all relations\n\t\t\tfor (\n\t\t\t\tconst {\n\t\t\t\t\ttsKey: selectedRelationTsKey,\n\t\t\t\t\tqueryConfig: selectedRelationConfigValue,\n\t\t\t\t\trelation,\n\t\t\t\t} of selectedRelations\n\t\t\t) {\n\t\t\t\tconst normalizedRelation = normalizeRelation(schema, tableNamesMap, relation);\n\t\t\t\tconst relationTableName = getTableUniqueName(relation.referencedTable);\n\t\t\t\tconst relationTableTsName = tableNamesMap[relationTableName]!;\n\t\t\t\tconst relationTableAlias = `${tableAlias}_${selectedRelationTsKey}`;\n\t\t\t\t// const relationTable = schema[relationTableTsName]!;\n\t\t\t\tconst joinOn = and(\n\t\t\t\t\t...normalizedRelation.fields.map((field, i) =>\n\t\t\t\t\t\teq(\n\t\t\t\t\t\t\taliasedTableColumn(normalizedRelation.references[i]!, relationTableAlias),\n\t\t\t\t\t\t\taliasedTableColumn(field, tableAlias),\n\t\t\t\t\t\t)\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t\tconst builtRelation = this.buildRelationalQuery({\n\t\t\t\t\tfullSchema,\n\t\t\t\t\tschema,\n\t\t\t\t\ttableNamesMap,\n\t\t\t\t\ttable: fullSchema[relationTableTsName] as SQLiteTable,\n\t\t\t\t\ttableConfig: schema[relationTableTsName]!,\n\t\t\t\t\tqueryConfig: is(relation, One)\n\t\t\t\t\t\t? (selectedRelationConfigValue === true\n\t\t\t\t\t\t\t? { limit: 1 }\n\t\t\t\t\t\t\t: { ...selectedRelationConfigValue, limit: 1 })\n\t\t\t\t\t\t: selectedRelationConfigValue,\n\t\t\t\t\ttableAlias: relationTableAlias,\n\t\t\t\t\tjoinOn,\n\t\t\t\t\tnestedQueryRelation: relation,\n\t\t\t\t});\n\t\t\t\tconst field = (sql`(${builtRelation.sql})`).as(selectedRelationTsKey);\n\t\t\t\tselection.push({\n\t\t\t\t\tdbKey: selectedRelationTsKey,\n\t\t\t\t\ttsKey: selectedRelationTsKey,\n\t\t\t\t\tfield,\n\t\t\t\t\trelationTableTsKey: relationTableTsName,\n\t\t\t\t\tisJson: true,\n\t\t\t\t\tselection: builtRelation.selection,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\n\t\tif (selection.length === 0) {\n\t\t\tthrow new DrizzleError({\n\t\t\t\tmessage:\n\t\t\t\t\t`No fields selected for table \"${tableConfig.tsName}\" (\"${tableAlias}\"). You need to have at least one item in \"columns\", \"with\" or \"extras\". If you need to select all columns, omit the \"columns\" key or set it to undefined.`,\n\t\t\t});\n\t\t}\n\n\t\tlet result;\n\n\t\twhere = and(joinOn, where);\n\n\t\tif (nestedQueryRelation) {\n\t\t\tlet field = sql`json_array(${\n\t\t\t\tsql.join(\n\t\t\t\t\tselection.map(({ field }) =>\n\t\t\t\t\t\tis(field, SQLiteColumn)\n\t\t\t\t\t\t\t? sql.identifier(this.casing.getColumnCasing(field))\n\t\t\t\t\t\t\t: is(field, SQL.Aliased)\n\t\t\t\t\t\t\t? field.sql\n\t\t\t\t\t\t\t: field\n\t\t\t\t\t),\n\t\t\t\t\tsql`, `,\n\t\t\t\t)\n\t\t\t})`;\n\t\t\tif (is(nestedQueryRelation, Many)) {\n\t\t\t\tfield = sql`coalesce(json_group_array(${field}), json_array())`;\n\t\t\t}\n\t\t\tconst nestedSelection = [{\n\t\t\t\tdbKey: 'data',\n\t\t\t\ttsKey: 'data',\n\t\t\t\tfield: field.as('data'),\n\t\t\t\tisJson: true,\n\t\t\t\trelationTableTsKey: tableConfig.tsName,\n\t\t\t\tselection,\n\t\t\t}];\n\n\t\t\tconst needsSubquery = limit !== undefined || offset !== undefined || orderBy.length > 0;\n\n\t\t\tif (needsSubquery) {\n\t\t\t\tresult = this.buildSelectQuery({\n\t\t\t\t\ttable: aliasedTable(table, tableAlias),\n\t\t\t\t\tfields: {},\n\t\t\t\t\tfieldsFlat: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tpath: [],\n\t\t\t\t\t\t\tfield: sql.raw('*'),\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t\twhere,\n\t\t\t\t\tlimit,\n\t\t\t\t\toffset,\n\t\t\t\t\torderBy,\n\t\t\t\t\tsetOperators: [],\n\t\t\t\t});\n\n\t\t\t\twhere = undefined;\n\t\t\t\tlimit = undefined;\n\t\t\t\toffset = undefined;\n\t\t\t\torderBy = undefined;\n\t\t\t} else {\n\t\t\t\tresult = aliasedTable(table, tableAlias);\n\t\t\t}\n\n\t\t\tresult = this.buildSelectQuery({\n\t\t\t\ttable: is(result, SQLiteTable) ? result : new Subquery(result, {}, tableAlias),\n\t\t\t\tfields: {},\n\t\t\t\tfieldsFlat: nestedSelection.map(({ field }) => ({\n\t\t\t\t\tpath: [],\n\t\t\t\t\tfield: is(field, Column) ? aliasedTableColumn(field, tableAlias) : field,\n\t\t\t\t})),\n\t\t\t\tjoins,\n\t\t\t\twhere,\n\t\t\t\tlimit,\n\t\t\t\toffset,\n\t\t\t\torderBy,\n\t\t\t\tsetOperators: [],\n\t\t\t});\n\t\t} else {\n\t\t\tresult = this.buildSelectQuery({\n\t\t\t\ttable: aliasedTable(table, tableAlias),\n\t\t\t\tfields: {},\n\t\t\t\tfieldsFlat: selection.map(({ field }) => ({\n\t\t\t\t\tpath: [],\n\t\t\t\t\tfield: is(field, Column) ? aliasedTableColumn(field, tableAlias) : field,\n\t\t\t\t})),\n\t\t\t\tjoins,\n\t\t\t\twhere,\n\t\t\t\tlimit,\n\t\t\t\toffset,\n\t\t\t\torderBy,\n\t\t\t\tsetOperators: [],\n\t\t\t});\n\t\t}\n\n\t\treturn {\n\t\t\ttableTsKey: tableConfig.tsName,\n\t\t\tsql: result,\n\t\t\tselection,\n\t\t};\n\t}\n}\n\nexport class SQLiteSyncDialect extends SQLiteDialect {\n\tstatic override readonly [entityKind]: string = 'SQLiteSyncDialect';\n\n\tmigrate(\n\t\tmigrations: MigrationMeta[],\n\t\tsession: SQLiteSession<'sync', unknown, Record, TablesRelationalConfig>,\n\t\tconfig?: string | MigrationConfig,\n\t): void {\n\t\tconst migrationsTable = config === undefined\n\t\t\t? '__drizzle_migrations'\n\t\t\t: typeof config === 'string'\n\t\t\t? '__drizzle_migrations'\n\t\t\t: config.migrationsTable ?? '__drizzle_migrations';\n\n\t\tconst migrationTableCreate = sql`\n\t\t\tCREATE TABLE IF NOT EXISTS ${sql.identifier(migrationsTable)} (\n\t\t\t\tid SERIAL PRIMARY KEY,\n\t\t\t\thash text NOT NULL,\n\t\t\t\tcreated_at numeric\n\t\t\t)\n\t\t`;\n\t\tsession.run(migrationTableCreate);\n\n\t\tconst dbMigrations = session.values<[number, string, string]>(\n\t\t\tsql`SELECT id, hash, created_at FROM ${sql.identifier(migrationsTable)} ORDER BY created_at DESC LIMIT 1`,\n\t\t);\n\n\t\tconst lastDbMigration = dbMigrations[0] ?? undefined;\n\t\tsession.run(sql`BEGIN`);\n\n\t\ttry {\n\t\t\tfor (const migration of migrations) {\n\t\t\t\tif (!lastDbMigration || Number(lastDbMigration[2])! < migration.folderMillis) {\n\t\t\t\t\tfor (const stmt of migration.sql) {\n\t\t\t\t\t\tsession.run(sql.raw(stmt));\n\t\t\t\t\t}\n\t\t\t\t\tsession.run(\n\t\t\t\t\t\tsql`INSERT INTO ${\n\t\t\t\t\t\t\tsql.identifier(migrationsTable)\n\t\t\t\t\t\t} (\"hash\", \"created_at\") VALUES(${migration.hash}, ${migration.folderMillis})`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tsession.run(sql`COMMIT`);\n\t\t} catch (e) {\n\t\t\tsession.run(sql`ROLLBACK`);\n\t\t\tthrow e;\n\t\t}\n\t}\n}\n\nexport class SQLiteAsyncDialect extends SQLiteDialect {\n\tstatic override readonly [entityKind]: string = 'SQLiteAsyncDialect';\n\n\tasync migrate(\n\t\tmigrations: MigrationMeta[],\n\t\tsession: SQLiteSession<'async', any, any, any>,\n\t\tconfig?: string | MigrationConfig,\n\t): Promise {\n\t\tconst migrationsTable = config === undefined\n\t\t\t? '__drizzle_migrations'\n\t\t\t: typeof config === 'string'\n\t\t\t? '__drizzle_migrations'\n\t\t\t: config.migrationsTable ?? '__drizzle_migrations';\n\n\t\tconst migrationTableCreate = sql`\n\t\t\tCREATE TABLE IF NOT EXISTS ${sql.identifier(migrationsTable)} (\n\t\t\t\tid SERIAL PRIMARY KEY,\n\t\t\t\thash text NOT NULL,\n\t\t\t\tcreated_at numeric\n\t\t\t)\n\t\t`;\n\t\tawait session.run(migrationTableCreate);\n\n\t\tconst dbMigrations = await session.values<[number, string, string]>(\n\t\t\tsql`SELECT id, hash, created_at FROM ${sql.identifier(migrationsTable)} ORDER BY created_at DESC LIMIT 1`,\n\t\t);\n\n\t\tconst lastDbMigration = dbMigrations[0] ?? undefined;\n\n\t\tawait session.transaction(async (tx) => {\n\t\t\tfor (const migration of migrations) {\n\t\t\t\tif (!lastDbMigration || Number(lastDbMigration[2])! < migration.folderMillis) {\n\t\t\t\t\tfor (const stmt of migration.sql) {\n\t\t\t\t\t\tawait tx.run(sql.raw(stmt));\n\t\t\t\t\t}\n\t\t\t\t\tawait tx.run(\n\t\t\t\t\t\tsql`INSERT INTO ${\n\t\t\t\t\t\t\tsql.identifier(migrationsTable)\n\t\t\t\t\t\t} (\"hash\", \"created_at\") VALUES(${migration.hash}, ${migration.folderMillis})`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t}\n}\n", "import type { Column } from '~/column.ts';\nimport { entityKind } from './entity.ts';\nimport { Table } from './table.ts';\nimport type { Casing } from './utils.ts';\n\nexport function toSnakeCase(input: string) {\n\tconst words = input\n\t\t.replace(/['\\u2019]/g, '')\n\t\t.match(/[\\da-z]+|[A-Z]+(?![a-z])|[A-Z][\\da-z]+/g) ?? [];\n\n\treturn words.map((word) => word.toLowerCase()).join('_');\n}\n\nexport function toCamelCase(input: string) {\n\tconst words = input\n\t\t.replace(/['\\u2019]/g, '')\n\t\t.match(/[\\da-z]+|[A-Z]+(?![a-z])|[A-Z][\\da-z]+/g) ?? [];\n\n\treturn words.reduce((acc, word, i) => {\n\t\tconst formattedWord = i === 0 ? word.toLowerCase() : `${word[0]!.toUpperCase()}${word.slice(1)}`;\n\t\treturn acc + formattedWord;\n\t}, '');\n}\n\nfunction noopCase(input: string) {\n\treturn input;\n}\n\nexport class CasingCache {\n\tstatic readonly [entityKind]: string = 'CasingCache';\n\n\t/** @internal */\n\tcache: Record = {};\n\tprivate cachedTables: Record = {};\n\tprivate convert: (input: string) => string;\n\n\tconstructor(casing?: Casing) {\n\t\tthis.convert = casing === 'snake_case'\n\t\t\t? toSnakeCase\n\t\t\t: casing === 'camelCase'\n\t\t\t? toCamelCase\n\t\t\t: noopCase;\n\t}\n\n\tgetColumnCasing(column: Column): string {\n\t\tif (!column.keyAsName) return column.name;\n\n\t\tconst schema = column.table[Table.Symbol.Schema] ?? 'public';\n\t\tconst tableName = column.table[Table.Symbol.OriginalName];\n\t\tconst key = `${schema}.${tableName}.${column.name}`;\n\n\t\tif (!this.cache[key]) {\n\t\t\tthis.cacheTable(column.table);\n\t\t}\n\t\treturn this.cache[key]!;\n\t}\n\n\tprivate cacheTable(table: Table) {\n\t\tconst schema = table[Table.Symbol.Schema] ?? 'public';\n\t\tconst tableName = table[Table.Symbol.OriginalName];\n\t\tconst tableKey = `${schema}.${tableName}`;\n\n\t\tif (!this.cachedTables[tableKey]) {\n\t\t\tfor (const column of Object.values(table[Table.Symbol.Columns])) {\n\t\t\t\tconst columnKey = `${tableKey}.${column.name}`;\n\t\t\t\tthis.cache[columnKey] = this.convert(column.name);\n\t\t\t}\n\t\t\tthis.cachedTables[tableKey] = true;\n\t\t}\n\t}\n\n\tclearCache() {\n\t\tthis.cache = {};\n\t\tthis.cachedTables = {};\n\t}\n}\n", "import { entityKind } from '~/entity.ts';\n\nexport class DrizzleError extends Error {\n\tstatic readonly [entityKind]: string = 'DrizzleError';\n\n\tconstructor({ message, cause }: { message?: string; cause?: unknown }) {\n\t\tsuper(message);\n\t\tthis.name = 'DrizzleError';\n\t\tthis.cause = cause;\n\t}\n}\n\nexport class DrizzleQueryError extends Error {\n\tconstructor(\n\t\tpublic query: string,\n\t\tpublic params: any[],\n\t\tpublic override cause?: Error,\n\t) {\n\t\tsuper(`Failed query: ${query}\\nparams: ${params}`);\n\t\tError.captureStackTrace(this, DrizzleQueryError);\n\n\t\t// ES2022+: preserves original error on `.cause`\n\t\tif (cause) (this as any).cause = cause;\n\t}\n}\n\nexport class TransactionRollbackError extends DrizzleError {\n\tstatic override readonly [entityKind]: string = 'TransactionRollbackError';\n\n\tconstructor() {\n\t\tsuper({ message: 'Rollback' });\n\t}\n}\n", "import { type AnyColumn, Column } from '~/column.ts';\nimport { is } from '~/entity.ts';\nimport { type SQL, sql, type SQLWrapper } from '../sql.ts';\n\n/**\n * Returns the number of values in `expression`.\n *\n * ## Examples\n *\n * ```ts\n * // Number employees with null values\n * db.select({ value: count() }).from(employees)\n * // Number of employees where `name` is not null\n * db.select({ value: count(employees.name) }).from(employees)\n * ```\n *\n * @see countDistinct to get the number of non-duplicate values in `expression`\n */\nexport function count(expression?: SQLWrapper): SQL {\n\treturn sql`count(${expression || sql.raw('*')})`.mapWith(Number);\n}\n\n/**\n * Returns the number of non-duplicate values in `expression`.\n *\n * ## Examples\n *\n * ```ts\n * // Number of employees where `name` is distinct\n * db.select({ value: countDistinct(employees.name) }).from(employees)\n * ```\n *\n * @see count to get the number of values in `expression`, including duplicates\n */\nexport function countDistinct(expression: SQLWrapper): SQL {\n\treturn sql`count(distinct ${expression})`.mapWith(Number);\n}\n\n/**\n * Returns the average (arithmetic mean) of all non-null values in `expression`.\n *\n * ## Examples\n *\n * ```ts\n * // Average salary of an employee\n * db.select({ value: avg(employees.salary) }).from(employees)\n * ```\n *\n * @see avgDistinct to get the average of all non-null and non-duplicate values in `expression`\n */\nexport function avg(expression: SQLWrapper): SQL {\n\treturn sql`avg(${expression})`.mapWith(String);\n}\n\n/**\n * Returns the average (arithmetic mean) of all non-null and non-duplicate values in `expression`.\n *\n * ## Examples\n *\n * ```ts\n * // Average salary of an employee where `salary` is distinct\n * db.select({ value: avgDistinct(employees.salary) }).from(employees)\n * ```\n *\n * @see avg to get the average of all non-null values in `expression`, including duplicates\n */\nexport function avgDistinct(expression: SQLWrapper): SQL {\n\treturn sql`avg(distinct ${expression})`.mapWith(String);\n}\n\n/**\n * Returns the sum of all non-null values in `expression`.\n *\n * ## Examples\n *\n * ```ts\n * // Sum of every employee's salary\n * db.select({ value: sum(employees.salary) }).from(employees)\n * ```\n *\n * @see sumDistinct to get the sum of all non-null and non-duplicate values in `expression`\n */\nexport function sum(expression: SQLWrapper): SQL {\n\treturn sql`sum(${expression})`.mapWith(String);\n}\n\n/**\n * Returns the sum of all non-null and non-duplicate values in `expression`.\n *\n * ## Examples\n *\n * ```ts\n * // Sum of every employee's salary where `salary` is distinct (no duplicates)\n * db.select({ value: sumDistinct(employees.salary) }).from(employees)\n * ```\n *\n * @see sum to get the sum of all non-null values in `expression`, including duplicates\n */\nexport function sumDistinct(expression: SQLWrapper): SQL {\n\treturn sql`sum(distinct ${expression})`.mapWith(String);\n}\n\n/**\n * Returns the maximum value in `expression`.\n *\n * ## Examples\n *\n * ```ts\n * // The employee with the highest salary\n * db.select({ value: max(employees.salary) }).from(employees)\n * ```\n */\nexport function max(expression: T): SQL<(T extends AnyColumn ? T['_']['data'] : string) | null> {\n\treturn sql`max(${expression})`.mapWith(is(expression, Column) ? expression : String) as any;\n}\n\n/**\n * Returns the minimum value in `expression`.\n *\n * ## Examples\n *\n * ```ts\n * // The employee with the lowest salary\n * db.select({ value: min(employees.salary) }).from(employees)\n * ```\n */\nexport function min(expression: T): SQL<(T extends AnyColumn ? T['_']['data'] : string) | null> {\n\treturn sql`min(${expression})`.mapWith(is(expression, Column) ? expression : String) as any;\n}\n", "import { entityKind } from '~/entity.ts';\nimport type { ColumnsSelection } from '~/sql/sql.ts';\nimport { View } from '~/sql/sql.ts';\n\nexport abstract class SQLiteViewBase<\n\tTName extends string = string,\n\tTExisting extends boolean = boolean,\n\tTSelection extends ColumnsSelection = ColumnsSelection,\n> extends View {\n\tstatic override readonly [entityKind]: string = 'SQLiteViewBase';\n\n\tdeclare _: View['_'] & {\n\t\tviewBrand: 'SQLiteView';\n\t};\n}\n", "import type { CacheConfig, WithCacheConfig } from '~/cache/core/types.ts';\nimport { entityKind, is } from '~/entity.ts';\nimport { TypedQueryBuilder } from '~/query-builders/query-builder.ts';\nimport type {\n\tBuildSubquerySelection,\n\tGetSelectTableName,\n\tGetSelectTableSelection,\n\tJoinNullability,\n\tJoinType,\n\tSelectMode,\n\tSelectResult,\n\tSetOperator,\n} from '~/query-builders/select.types.ts';\nimport { QueryPromise } from '~/query-promise.ts';\nimport type { RunnableQuery } from '~/runnable-query.ts';\nimport { SelectionProxyHandler } from '~/selection-proxy.ts';\nimport { SQL, View } from '~/sql/sql.ts';\nimport type { ColumnsSelection, Placeholder, Query, SQLWrapper } from '~/sql/sql.ts';\nimport type { SQLiteColumn } from '~/sqlite-core/columns/index.ts';\nimport type { SQLiteDialect } from '~/sqlite-core/dialect.ts';\nimport type { SQLiteSession } from '~/sqlite-core/session.ts';\nimport type { SubqueryWithSelection } from '~/sqlite-core/subquery.ts';\nimport type { SQLiteTable } from '~/sqlite-core/table.ts';\nimport { Subquery } from '~/subquery.ts';\nimport { Table } from '~/table.ts';\nimport {\n\tapplyMixins,\n\tgetTableColumns,\n\tgetTableLikeName,\n\thaveSameKeys,\n\torderSelectedFields,\n\ttype ValueOrArray,\n} from '~/utils.ts';\nimport { ViewBaseConfig } from '~/view-common.ts';\nimport { extractUsedTable } from '../utils.ts';\nimport { SQLiteViewBase } from '../view-base.ts';\nimport type {\n\tAnySQLiteSelect,\n\tCreateSQLiteSelectFromBuilderMode,\n\tGetSQLiteSetOperators,\n\tSelectedFields,\n\tSetOperatorRightSelect,\n\tSQLiteCreateSetOperatorFn,\n\tSQLiteSelectConfig,\n\tSQLiteSelectCrossJoinFn,\n\tSQLiteSelectDynamic,\n\tSQLiteSelectExecute,\n\tSQLiteSelectHKT,\n\tSQLiteSelectHKTBase,\n\tSQLiteSelectJoinFn,\n\tSQLiteSelectPrepare,\n\tSQLiteSelectWithout,\n\tSQLiteSetOperatorExcludedMethods,\n\tSQLiteSetOperatorWithResult,\n} from './select.types.ts';\n\nexport class SQLiteSelectBuilder<\n\tTSelection extends SelectedFields | undefined,\n\tTResultType extends 'sync' | 'async',\n\tTRunResult,\n\tTBuilderMode extends 'db' | 'qb' = 'db',\n> {\n\tstatic readonly [entityKind]: string = 'SQLiteSelectBuilder';\n\n\tprivate fields: TSelection;\n\tprivate session: SQLiteSession | undefined;\n\tprivate dialect: SQLiteDialect;\n\tprivate withList: Subquery[] | undefined;\n\tprivate distinct: boolean | undefined;\n\n\tconstructor(\n\t\tconfig: {\n\t\t\tfields: TSelection;\n\t\t\tsession: SQLiteSession | undefined;\n\t\t\tdialect: SQLiteDialect;\n\t\t\twithList?: Subquery[];\n\t\t\tdistinct?: boolean;\n\t\t},\n\t) {\n\t\tthis.fields = config.fields;\n\t\tthis.session = config.session;\n\t\tthis.dialect = config.dialect;\n\t\tthis.withList = config.withList;\n\t\tthis.distinct = config.distinct;\n\t}\n\n\tfrom(\n\t\tsource: TFrom,\n\t): CreateSQLiteSelectFromBuilderMode<\n\t\tTBuilderMode,\n\t\tGetSelectTableName,\n\t\tTResultType,\n\t\tTRunResult,\n\t\tTSelection extends undefined ? GetSelectTableSelection : TSelection,\n\t\tTSelection extends undefined ? 'single' : 'partial'\n\t> {\n\t\tconst isPartialSelect = !!this.fields;\n\n\t\tlet fields: SelectedFields;\n\t\tif (this.fields) {\n\t\t\tfields = this.fields;\n\t\t} else if (is(source, Subquery)) {\n\t\t\t// This is required to use the proxy handler to get the correct field values from the subquery\n\t\t\tfields = Object.fromEntries(\n\t\t\t\tObject.keys(source._.selectedFields).map((\n\t\t\t\t\tkey,\n\t\t\t\t) => [key, source[key as unknown as keyof typeof source] as unknown as SelectedFields[string]]),\n\t\t\t);\n\t\t} else if (is(source, SQLiteViewBase)) {\n\t\t\tfields = source[ViewBaseConfig].selectedFields as SelectedFields;\n\t\t} else if (is(source, SQL)) {\n\t\t\tfields = {};\n\t\t} else {\n\t\t\tfields = getTableColumns(source);\n\t\t}\n\n\t\treturn new SQLiteSelectBase({\n\t\t\ttable: source,\n\t\t\tfields,\n\t\t\tisPartialSelect,\n\t\t\tsession: this.session,\n\t\t\tdialect: this.dialect,\n\t\t\twithList: this.withList,\n\t\t\tdistinct: this.distinct,\n\t\t}) as any;\n\t}\n}\n\nexport abstract class SQLiteSelectQueryBuilderBase<\n\tTHKT extends SQLiteSelectHKTBase,\n\tTTableName extends string | undefined,\n\tTResultType extends 'sync' | 'async',\n\tTRunResult,\n\tTSelection extends ColumnsSelection,\n\tTSelectMode extends SelectMode,\n\tTNullabilityMap extends Record = TTableName extends string ? Record\n\t\t: {},\n\tTDynamic extends boolean = false,\n\tTExcludedMethods extends string = never,\n\tTResult extends any[] = SelectResult[],\n\tTSelectedFields extends ColumnsSelection = BuildSubquerySelection,\n> extends TypedQueryBuilder {\n\tstatic override readonly [entityKind]: string = 'SQLiteSelectQueryBuilder';\n\n\toverride readonly _: {\n\t\treadonly dialect: 'sqlite';\n\t\treadonly hkt: THKT;\n\t\treadonly tableName: TTableName;\n\t\treadonly resultType: TResultType;\n\t\treadonly runResult: TRunResult;\n\t\treadonly selection: TSelection;\n\t\treadonly selectMode: TSelectMode;\n\t\treadonly nullabilityMap: TNullabilityMap;\n\t\treadonly dynamic: TDynamic;\n\t\treadonly excludedMethods: TExcludedMethods;\n\t\treadonly result: TResult;\n\t\treadonly selectedFields: TSelectedFields;\n\t\treadonly config: SQLiteSelectConfig;\n\t};\n\n\t/** @internal */\n\tconfig: SQLiteSelectConfig;\n\tprotected joinsNotNullableMap: Record;\n\tprivate tableName: string | undefined;\n\tprivate isPartialSelect: boolean;\n\tprotected session: SQLiteSession | undefined;\n\tprotected dialect: SQLiteDialect;\n\tprotected cacheConfig?: WithCacheConfig = undefined;\n\tprotected usedTables: Set = new Set();\n\n\tconstructor(\n\t\t{ table, fields, isPartialSelect, session, dialect, withList, distinct }: {\n\t\t\ttable: SQLiteSelectConfig['table'];\n\t\t\tfields: SQLiteSelectConfig['fields'];\n\t\t\tisPartialSelect: boolean;\n\t\t\tsession: SQLiteSession | undefined;\n\t\t\tdialect: SQLiteDialect;\n\t\t\twithList: Subquery[] | undefined;\n\t\t\tdistinct: boolean | undefined;\n\t\t},\n\t) {\n\t\tsuper();\n\t\tthis.config = {\n\t\t\twithList,\n\t\t\ttable,\n\t\t\tfields: { ...fields },\n\t\t\tdistinct,\n\t\t\tsetOperators: [],\n\t\t};\n\t\tthis.isPartialSelect = isPartialSelect;\n\t\tthis.session = session;\n\t\tthis.dialect = dialect;\n\t\tthis._ = {\n\t\t\tselectedFields: fields as TSelectedFields,\n\t\t\tconfig: this.config,\n\t\t} as this['_'];\n\t\tthis.tableName = getTableLikeName(table);\n\t\tthis.joinsNotNullableMap = typeof this.tableName === 'string' ? { [this.tableName]: true } : {};\n\t\tfor (const item of extractUsedTable(table)) this.usedTables.add(item);\n\t}\n\n\t/** @internal */\n\tgetUsedTables() {\n\t\treturn [...this.usedTables];\n\t}\n\n\tprivate createJoin(\n\t\tjoinType: TJoinType,\n\t): 'cross' extends TJoinType ? SQLiteSelectCrossJoinFn\n\t\t: SQLiteSelectJoinFn\n\t{\n\t\treturn (\n\t\t\ttable: SQLiteTable | Subquery | SQLiteViewBase | SQL,\n\t\t\ton?: ((aliases: TSelection) => SQL | undefined) | SQL | undefined,\n\t\t) => {\n\t\t\tconst baseTableName = this.tableName;\n\t\t\tconst tableName = getTableLikeName(table);\n\n\t\t\t// store all tables used in a query\n\t\t\tfor (const item of extractUsedTable(table)) this.usedTables.add(item);\n\n\t\t\tif (typeof tableName === 'string' && this.config.joins?.some((join) => join.alias === tableName)) {\n\t\t\t\tthrow new Error(`Alias \"${tableName}\" is already used in this query`);\n\t\t\t}\n\n\t\t\tif (!this.isPartialSelect) {\n\t\t\t\t// If this is the first join and this is not a partial select and we're not selecting from raw SQL, \"move\" the fields from the main table to the nested object\n\t\t\t\tif (Object.keys(this.joinsNotNullableMap).length === 1 && typeof baseTableName === 'string') {\n\t\t\t\t\tthis.config.fields = {\n\t\t\t\t\t\t[baseTableName]: this.config.fields,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tif (typeof tableName === 'string' && !is(table, SQL)) {\n\t\t\t\t\tconst selection = is(table, Subquery)\n\t\t\t\t\t\t? table._.selectedFields\n\t\t\t\t\t\t: is(table, View)\n\t\t\t\t\t\t? table[ViewBaseConfig].selectedFields\n\t\t\t\t\t\t: table[Table.Symbol.Columns];\n\t\t\t\t\tthis.config.fields[tableName] = selection;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (typeof on === 'function') {\n\t\t\t\ton = on(\n\t\t\t\t\tnew Proxy(\n\t\t\t\t\t\tthis.config.fields,\n\t\t\t\t\t\tnew SelectionProxyHandler({ sqlAliasedBehavior: 'sql', sqlBehavior: 'sql' }),\n\t\t\t\t\t) as TSelection,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tif (!this.config.joins) {\n\t\t\t\tthis.config.joins = [];\n\t\t\t}\n\t\t\tthis.config.joins.push({ on, table, joinType, alias: tableName });\n\n\t\t\tif (typeof tableName === 'string') {\n\t\t\t\tswitch (joinType) {\n\t\t\t\t\tcase 'left': {\n\t\t\t\t\t\tthis.joinsNotNullableMap[tableName] = false;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tcase 'right': {\n\t\t\t\t\t\tthis.joinsNotNullableMap = Object.fromEntries(\n\t\t\t\t\t\t\tObject.entries(this.joinsNotNullableMap).map(([key]) => [key, false]),\n\t\t\t\t\t\t);\n\t\t\t\t\t\tthis.joinsNotNullableMap[tableName] = true;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tcase 'cross':\n\t\t\t\t\tcase 'inner': {\n\t\t\t\t\t\tthis.joinsNotNullableMap[tableName] = true;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tcase 'full': {\n\t\t\t\t\t\tthis.joinsNotNullableMap = Object.fromEntries(\n\t\t\t\t\t\t\tObject.entries(this.joinsNotNullableMap).map(([key]) => [key, false]),\n\t\t\t\t\t\t);\n\t\t\t\t\t\tthis.joinsNotNullableMap[tableName] = false;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn this as any;\n\t\t};\n\t}\n\n\t/**\n\t * Executes a `left join` operation by adding another table to the current query.\n\t *\n\t * Calling this method associates each row of the table with the corresponding row from the joined table, if a match is found. If no matching row exists, it sets all columns of the joined table to null.\n\t *\n\t * See docs: {@link https://orm.drizzle.team/docs/joins#left-join}\n\t *\n\t * @param table the table to join.\n\t * @param on the `on` clause.\n\t *\n\t * @example\n\t *\n\t * ```ts\n\t * // Select all users and their pets\n\t * const usersWithPets: { user: User; pets: Pet | null; }[] = await db.select()\n\t * .from(users)\n\t * .leftJoin(pets, eq(users.id, pets.ownerId))\n\t *\n\t * // Select userId and petId\n\t * const usersIdsAndPetIds: { userId: number; petId: number | null; }[] = await db.select({\n\t * userId: users.id,\n\t * petId: pets.id,\n\t * })\n\t * .from(users)\n\t * .leftJoin(pets, eq(users.id, pets.ownerId))\n\t * ```\n\t */\n\tleftJoin = this.createJoin('left');\n\n\t/**\n\t * Executes a `right join` operation by adding another table to the current query.\n\t *\n\t * Calling this method associates each row of the joined table with the corresponding row from the main table, if a match is found. If no matching row exists, it sets all columns of the main table to null.\n\t *\n\t * See docs: {@link https://orm.drizzle.team/docs/joins#right-join}\n\t *\n\t * @param table the table to join.\n\t * @param on the `on` clause.\n\t *\n\t * @example\n\t *\n\t * ```ts\n\t * // Select all users and their pets\n\t * const usersWithPets: { user: User | null; pets: Pet; }[] = await db.select()\n\t * .from(users)\n\t * .rightJoin(pets, eq(users.id, pets.ownerId))\n\t *\n\t * // Select userId and petId\n\t * const usersIdsAndPetIds: { userId: number | null; petId: number; }[] = await db.select({\n\t * userId: users.id,\n\t * petId: pets.id,\n\t * })\n\t * .from(users)\n\t * .rightJoin(pets, eq(users.id, pets.ownerId))\n\t * ```\n\t */\n\trightJoin = this.createJoin('right');\n\n\t/**\n\t * Executes an `inner join` operation, creating a new table by combining rows from two tables that have matching values.\n\t *\n\t * Calling this method retrieves rows that have corresponding entries in both joined tables. Rows without matching entries in either table are excluded, resulting in a table that includes only matching pairs.\n\t *\n\t * See docs: {@link https://orm.drizzle.team/docs/joins#inner-join}\n\t *\n\t * @param table the table to join.\n\t * @param on the `on` clause.\n\t *\n\t * @example\n\t *\n\t * ```ts\n\t * // Select all users and their pets\n\t * const usersWithPets: { user: User; pets: Pet; }[] = await db.select()\n\t * .from(users)\n\t * .innerJoin(pets, eq(users.id, pets.ownerId))\n\t *\n\t * // Select userId and petId\n\t * const usersIdsAndPetIds: { userId: number; petId: number; }[] = await db.select({\n\t * userId: users.id,\n\t * petId: pets.id,\n\t * })\n\t * .from(users)\n\t * .innerJoin(pets, eq(users.id, pets.ownerId))\n\t * ```\n\t */\n\tinnerJoin = this.createJoin('inner');\n\n\t/**\n\t * Executes a `full join` operation by combining rows from two tables into a new table.\n\t *\n\t * Calling this method retrieves all rows from both main and joined tables, merging rows with matching values and filling in `null` for non-matching columns.\n\t *\n\t * See docs: {@link https://orm.drizzle.team/docs/joins#full-join}\n\t *\n\t * @param table the table to join.\n\t * @param on the `on` clause.\n\t *\n\t * @example\n\t *\n\t * ```ts\n\t * // Select all users and their pets\n\t * const usersWithPets: { user: User | null; pets: Pet | null; }[] = await db.select()\n\t * .from(users)\n\t * .fullJoin(pets, eq(users.id, pets.ownerId))\n\t *\n\t * // Select userId and petId\n\t * const usersIdsAndPetIds: { userId: number | null; petId: number | null; }[] = await db.select({\n\t * userId: users.id,\n\t * petId: pets.id,\n\t * })\n\t * .from(users)\n\t * .fullJoin(pets, eq(users.id, pets.ownerId))\n\t * ```\n\t */\n\tfullJoin = this.createJoin('full');\n\n\t/**\n\t * Executes a `cross join` operation by combining rows from two tables into a new table.\n\t *\n\t * Calling this method retrieves all rows from both main and joined tables, merging all rows from each table.\n\t *\n\t * See docs: {@link https://orm.drizzle.team/docs/joins#cross-join}\n\t *\n\t * @param table the table to join.\n\t *\n\t * @example\n\t *\n\t * ```ts\n\t * // Select all users, each user with every pet\n\t * const usersWithPets: { user: User; pets: Pet; }[] = await db.select()\n\t * .from(users)\n\t * .crossJoin(pets)\n\t *\n\t * // Select userId and petId\n\t * const usersIdsAndPetIds: { userId: number; petId: number; }[] = await db.select({\n\t * userId: users.id,\n\t * petId: pets.id,\n\t * })\n\t * .from(users)\n\t * .crossJoin(pets)\n\t * ```\n\t */\n\tcrossJoin = this.createJoin('cross');\n\n\tprivate createSetOperator(\n\t\ttype: SetOperator,\n\t\tisAll: boolean,\n\t): >(\n\t\trightSelection:\n\t\t\t| ((setOperators: GetSQLiteSetOperators) => SetOperatorRightSelect)\n\t\t\t| SetOperatorRightSelect,\n\t) => SQLiteSelectWithout<\n\t\tthis,\n\t\tTDynamic,\n\t\tSQLiteSetOperatorExcludedMethods,\n\t\ttrue\n\t> {\n\t\treturn (rightSelection) => {\n\t\t\tconst rightSelect = (typeof rightSelection === 'function'\n\t\t\t\t? rightSelection(getSQLiteSetOperators())\n\t\t\t\t: rightSelection) as TypedQueryBuilder<\n\t\t\t\t\tany,\n\t\t\t\t\tTResult\n\t\t\t\t>;\n\n\t\t\tif (!haveSameKeys(this.getSelectedFields(), rightSelect.getSelectedFields())) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t'Set operator error (union / intersect / except): selected fields are not the same or are in a different order',\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tthis.config.setOperators.push({ type, isAll, rightSelect });\n\t\t\treturn this as any;\n\t\t};\n\t}\n\n\t/**\n\t * Adds `union` set operator to the query.\n\t *\n\t * Calling this method will combine the result sets of the `select` statements and remove any duplicate rows that appear across them.\n\t *\n\t * See docs: {@link https://orm.drizzle.team/docs/set-operations#union}\n\t *\n\t * @example\n\t *\n\t * ```ts\n\t * // Select all unique names from customers and users tables\n\t * await db.select({ name: users.name })\n\t * .from(users)\n\t * .union(\n\t * db.select({ name: customers.name }).from(customers)\n\t * );\n\t * // or\n\t * import { union } from 'drizzle-orm/sqlite-core'\n\t *\n\t * await union(\n\t * db.select({ name: users.name }).from(users),\n\t * db.select({ name: customers.name }).from(customers)\n\t * );\n\t * ```\n\t */\n\tunion = this.createSetOperator('union', false);\n\n\t/**\n\t * Adds `union all` set operator to the query.\n\t *\n\t * Calling this method will combine the result-set of the `select` statements and keep all duplicate rows that appear across them.\n\t *\n\t * See docs: {@link https://orm.drizzle.team/docs/set-operations#union-all}\n\t *\n\t * @example\n\t *\n\t * ```ts\n\t * // Select all transaction ids from both online and in-store sales\n\t * await db.select({ transaction: onlineSales.transactionId })\n\t * .from(onlineSales)\n\t * .unionAll(\n\t * db.select({ transaction: inStoreSales.transactionId }).from(inStoreSales)\n\t * );\n\t * // or\n\t * import { unionAll } from 'drizzle-orm/sqlite-core'\n\t *\n\t * await unionAll(\n\t * db.select({ transaction: onlineSales.transactionId }).from(onlineSales),\n\t * db.select({ transaction: inStoreSales.transactionId }).from(inStoreSales)\n\t * );\n\t * ```\n\t */\n\tunionAll = this.createSetOperator('union', true);\n\n\t/**\n\t * Adds `intersect` set operator to the query.\n\t *\n\t * Calling this method will retain only the rows that are present in both result sets and eliminate duplicates.\n\t *\n\t * See docs: {@link https://orm.drizzle.team/docs/set-operations#intersect}\n\t *\n\t * @example\n\t *\n\t * ```ts\n\t * // Select course names that are offered in both departments A and B\n\t * await db.select({ courseName: depA.courseName })\n\t * .from(depA)\n\t * .intersect(\n\t * db.select({ courseName: depB.courseName }).from(depB)\n\t * );\n\t * // or\n\t * import { intersect } from 'drizzle-orm/sqlite-core'\n\t *\n\t * await intersect(\n\t * db.select({ courseName: depA.courseName }).from(depA),\n\t * db.select({ courseName: depB.courseName }).from(depB)\n\t * );\n\t * ```\n\t */\n\tintersect = this.createSetOperator('intersect', false);\n\n\t/**\n\t * Adds `except` set operator to the query.\n\t *\n\t * Calling this method will retrieve all unique rows from the left query, except for the rows that are present in the result set of the right query.\n\t *\n\t * See docs: {@link https://orm.drizzle.team/docs/set-operations#except}\n\t *\n\t * @example\n\t *\n\t * ```ts\n\t * // Select all courses offered in department A but not in department B\n\t * await db.select({ courseName: depA.courseName })\n\t * .from(depA)\n\t * .except(\n\t * db.select({ courseName: depB.courseName }).from(depB)\n\t * );\n\t * // or\n\t * import { except } from 'drizzle-orm/sqlite-core'\n\t *\n\t * await except(\n\t * db.select({ courseName: depA.courseName }).from(depA),\n\t * db.select({ courseName: depB.courseName }).from(depB)\n\t * );\n\t * ```\n\t */\n\texcept = this.createSetOperator('except', false);\n\n\t/** @internal */\n\taddSetOperators(setOperators: SQLiteSelectConfig['setOperators']): SQLiteSelectWithout<\n\t\tthis,\n\t\tTDynamic,\n\t\tSQLiteSetOperatorExcludedMethods,\n\t\ttrue\n\t> {\n\t\tthis.config.setOperators.push(...setOperators);\n\t\treturn this as any;\n\t}\n\n\t/**\n\t * Adds a `where` clause to the query.\n\t *\n\t * Calling this method will select only those rows that fulfill a specified condition.\n\t *\n\t * See docs: {@link https://orm.drizzle.team/docs/select#filtering}\n\t *\n\t * @param where the `where` clause.\n\t *\n\t * @example\n\t * You can use conditional operators and `sql function` to filter the rows to be selected.\n\t *\n\t * ```ts\n\t * // Select all cars with green color\n\t * await db.select().from(cars).where(eq(cars.color, 'green'));\n\t * // or\n\t * await db.select().from(cars).where(sql`${cars.color} = 'green'`)\n\t * ```\n\t *\n\t * You can logically combine conditional operators with `and()` and `or()` operators:\n\t *\n\t * ```ts\n\t * // Select all BMW cars with a green color\n\t * await db.select().from(cars).where(and(eq(cars.color, 'green'), eq(cars.brand, 'BMW')));\n\t *\n\t * // Select all cars with the green or blue color\n\t * await db.select().from(cars).where(or(eq(cars.color, 'green'), eq(cars.color, 'blue')));\n\t * ```\n\t */\n\twhere(\n\t\twhere: ((aliases: TSelection) => SQL | undefined) | SQL | undefined,\n\t): SQLiteSelectWithout {\n\t\tif (typeof where === 'function') {\n\t\t\twhere = where(\n\t\t\t\tnew Proxy(\n\t\t\t\t\tthis.config.fields,\n\t\t\t\t\tnew SelectionProxyHandler({ sqlAliasedBehavior: 'sql', sqlBehavior: 'sql' }),\n\t\t\t\t) as TSelection,\n\t\t\t);\n\t\t}\n\t\tthis.config.where = where;\n\t\treturn this as any;\n\t}\n\n\t/**\n\t * Adds a `having` clause to the query.\n\t *\n\t * Calling this method will select only those rows that fulfill a specified condition. It is typically used with aggregate functions to filter the aggregated data based on a specified condition.\n\t *\n\t * See docs: {@link https://orm.drizzle.team/docs/select#aggregations}\n\t *\n\t * @param having the `having` clause.\n\t *\n\t * @example\n\t *\n\t * ```ts\n\t * // Select all brands with more than one car\n\t * await db.select({\n\t * \tbrand: cars.brand,\n\t * \tcount: sql`cast(count(${cars.id}) as int)`,\n\t * })\n\t * .from(cars)\n\t * .groupBy(cars.brand)\n\t * .having(({ count }) => gt(count, 1));\n\t * ```\n\t */\n\thaving(\n\t\thaving: ((aliases: this['_']['selection']) => SQL | undefined) | SQL | undefined,\n\t): SQLiteSelectWithout {\n\t\tif (typeof having === 'function') {\n\t\t\thaving = having(\n\t\t\t\tnew Proxy(\n\t\t\t\t\tthis.config.fields,\n\t\t\t\t\tnew SelectionProxyHandler({ sqlAliasedBehavior: 'sql', sqlBehavior: 'sql' }),\n\t\t\t\t) as TSelection,\n\t\t\t);\n\t\t}\n\t\tthis.config.having = having;\n\t\treturn this as any;\n\t}\n\n\t/**\n\t * Adds a `group by` clause to the query.\n\t *\n\t * Calling this method will group rows that have the same values into summary rows, often used for aggregation purposes.\n\t *\n\t * See docs: {@link https://orm.drizzle.team/docs/select#aggregations}\n\t *\n\t * @example\n\t *\n\t * ```ts\n\t * // Group and count people by their last names\n\t * await db.select({\n\t * lastName: people.lastName,\n\t * count: sql`cast(count(*) as int)`\n\t * })\n\t * .from(people)\n\t * .groupBy(people.lastName);\n\t * ```\n\t */\n\tgroupBy(\n\t\tbuilder: (aliases: this['_']['selection']) => ValueOrArray,\n\t): SQLiteSelectWithout;\n\tgroupBy(...columns: (SQLiteColumn | SQL)[]): SQLiteSelectWithout;\n\tgroupBy(\n\t\t...columns:\n\t\t\t| [(aliases: this['_']['selection']) => ValueOrArray]\n\t\t\t| (SQLiteColumn | SQL | SQL.Aliased)[]\n\t): SQLiteSelectWithout {\n\t\tif (typeof columns[0] === 'function') {\n\t\t\tconst groupBy = columns[0](\n\t\t\t\tnew Proxy(\n\t\t\t\t\tthis.config.fields,\n\t\t\t\t\tnew SelectionProxyHandler({ sqlAliasedBehavior: 'alias', sqlBehavior: 'sql' }),\n\t\t\t\t) as TSelection,\n\t\t\t);\n\t\t\tthis.config.groupBy = Array.isArray(groupBy) ? groupBy : [groupBy];\n\t\t} else {\n\t\t\tthis.config.groupBy = columns as (SQLiteColumn | SQL | SQL.Aliased)[];\n\t\t}\n\t\treturn this as any;\n\t}\n\n\t/**\n\t * Adds an `order by` clause to the query.\n\t *\n\t * Calling this method will sort the result-set in ascending or descending order. By default, the sort order is ascending.\n\t *\n\t * See docs: {@link https://orm.drizzle.team/docs/select#order-by}\n\t *\n\t * @example\n\t *\n\t * ```\n\t * // Select cars ordered by year\n\t * await db.select().from(cars).orderBy(cars.year);\n\t * ```\n\t *\n\t * You can specify whether results are in ascending or descending order with the `asc()` and `desc()` operators.\n\t *\n\t * ```ts\n\t * // Select cars ordered by year in descending order\n\t * await db.select().from(cars).orderBy(desc(cars.year));\n\t *\n\t * // Select cars ordered by year and price\n\t * await db.select().from(cars).orderBy(asc(cars.year), desc(cars.price));\n\t * ```\n\t */\n\torderBy(\n\t\tbuilder: (aliases: this['_']['selection']) => ValueOrArray,\n\t): SQLiteSelectWithout;\n\torderBy(...columns: (SQLiteColumn | SQL)[]): SQLiteSelectWithout;\n\torderBy(\n\t\t...columns:\n\t\t\t| [(aliases: this['_']['selection']) => ValueOrArray]\n\t\t\t| (SQLiteColumn | SQL | SQL.Aliased)[]\n\t): SQLiteSelectWithout {\n\t\tif (typeof columns[0] === 'function') {\n\t\t\tconst orderBy = columns[0](\n\t\t\t\tnew Proxy(\n\t\t\t\t\tthis.config.fields,\n\t\t\t\t\tnew SelectionProxyHandler({ sqlAliasedBehavior: 'alias', sqlBehavior: 'sql' }),\n\t\t\t\t) as TSelection,\n\t\t\t);\n\n\t\t\tconst orderByArray = Array.isArray(orderBy) ? orderBy : [orderBy];\n\n\t\t\tif (this.config.setOperators.length > 0) {\n\t\t\t\tthis.config.setOperators.at(-1)!.orderBy = orderByArray;\n\t\t\t} else {\n\t\t\t\tthis.config.orderBy = orderByArray;\n\t\t\t}\n\t\t} else {\n\t\t\tconst orderByArray = columns as (SQLiteColumn | SQL | SQL.Aliased)[];\n\n\t\t\tif (this.config.setOperators.length > 0) {\n\t\t\t\tthis.config.setOperators.at(-1)!.orderBy = orderByArray;\n\t\t\t} else {\n\t\t\t\tthis.config.orderBy = orderByArray;\n\t\t\t}\n\t\t}\n\t\treturn this as any;\n\t}\n\n\t/**\n\t * Adds a `limit` clause to the query.\n\t *\n\t * Calling this method will set the maximum number of rows that will be returned by this query.\n\t *\n\t * See docs: {@link https://orm.drizzle.team/docs/select#limit--offset}\n\t *\n\t * @param limit the `limit` clause.\n\t *\n\t * @example\n\t *\n\t * ```ts\n\t * // Get the first 10 people from this query.\n\t * await db.select().from(people).limit(10);\n\t * ```\n\t */\n\tlimit(limit: number | Placeholder): SQLiteSelectWithout {\n\t\tif (this.config.setOperators.length > 0) {\n\t\t\tthis.config.setOperators.at(-1)!.limit = limit;\n\t\t} else {\n\t\t\tthis.config.limit = limit;\n\t\t}\n\t\treturn this as any;\n\t}\n\n\t/**\n\t * Adds an `offset` clause to the query.\n\t *\n\t * Calling this method will skip a number of rows when returning results from this query.\n\t *\n\t * See docs: {@link https://orm.drizzle.team/docs/select#limit--offset}\n\t *\n\t * @param offset the `offset` clause.\n\t *\n\t * @example\n\t *\n\t * ```ts\n\t * // Get the 10th-20th people from this query.\n\t * await db.select().from(people).offset(10).limit(10);\n\t * ```\n\t */\n\toffset(offset: number | Placeholder): SQLiteSelectWithout {\n\t\tif (this.config.setOperators.length > 0) {\n\t\t\tthis.config.setOperators.at(-1)!.offset = offset;\n\t\t} else {\n\t\t\tthis.config.offset = offset;\n\t\t}\n\t\treturn this as any;\n\t}\n\n\t/** @internal */\n\tgetSQL(): SQL {\n\t\treturn this.dialect.buildSelectQuery(this.config);\n\t}\n\n\ttoSQL(): Query {\n\t\tconst { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());\n\t\treturn rest;\n\t}\n\n\tas(\n\t\talias: TAlias,\n\t): SubqueryWithSelection {\n\t\tconst usedTables: string[] = [];\n\t\tusedTables.push(...extractUsedTable(this.config.table));\n\t\tif (this.config.joins) { for (const it of this.config.joins) usedTables.push(...extractUsedTable(it.table)); }\n\n\t\treturn new Proxy(\n\t\t\tnew Subquery(this.getSQL(), this.config.fields, alias, false, [...new Set(usedTables)]),\n\t\t\tnew SelectionProxyHandler({ alias, sqlAliasedBehavior: 'alias', sqlBehavior: 'error' }),\n\t\t) as SubqueryWithSelection;\n\t}\n\n\t/** @internal */\n\toverride getSelectedFields(): this['_']['selectedFields'] {\n\t\treturn new Proxy(\n\t\t\tthis.config.fields,\n\t\t\tnew SelectionProxyHandler({ alias: this.tableName, sqlAliasedBehavior: 'alias', sqlBehavior: 'error' }),\n\t\t) as this['_']['selectedFields'];\n\t}\n\n\t$dynamic(): SQLiteSelectDynamic {\n\t\treturn this;\n\t}\n}\n\n// eslint-disable-next-line @typescript-eslint/no-empty-interface\nexport interface SQLiteSelectBase<\n\tTTableName extends string | undefined,\n\tTResultType extends 'sync' | 'async',\n\tTRunResult,\n\tTSelection extends ColumnsSelection,\n\tTSelectMode extends SelectMode = 'single',\n\tTNullabilityMap extends Record = TTableName extends string ? Record\n\t\t: {},\n\tTDynamic extends boolean = false,\n\tTExcludedMethods extends string = never,\n\tTResult extends any[] = SelectResult[],\n\tTSelectedFields extends ColumnsSelection = BuildSubquerySelection,\n> extends\n\tSQLiteSelectQueryBuilderBase<\n\t\tSQLiteSelectHKT,\n\t\tTTableName,\n\t\tTResultType,\n\t\tTRunResult,\n\t\tTSelection,\n\t\tTSelectMode,\n\t\tTNullabilityMap,\n\t\tTDynamic,\n\t\tTExcludedMethods,\n\t\tTResult,\n\t\tTSelectedFields\n\t>,\n\tQueryPromise\n{}\n\nexport class SQLiteSelectBase<\n\tTTableName extends string | undefined,\n\tTResultType extends 'sync' | 'async',\n\tTRunResult,\n\tTSelection,\n\tTSelectMode extends SelectMode = 'single',\n\tTNullabilityMap extends Record = TTableName extends string ? Record\n\t\t: {},\n\tTDynamic extends boolean = false,\n\tTExcludedMethods extends string = never,\n\tTResult = SelectResult[],\n\tTSelectedFields extends ColumnsSelection = BuildSubquerySelection,\n> extends SQLiteSelectQueryBuilderBase<\n\tSQLiteSelectHKT,\n\tTTableName,\n\tTResultType,\n\tTRunResult,\n\tTSelection,\n\tTSelectMode,\n\tTNullabilityMap,\n\tTDynamic,\n\tTExcludedMethods,\n\tTResult,\n\tTSelectedFields\n> implements RunnableQuery, SQLWrapper {\n\tstatic override readonly [entityKind]: string = 'SQLiteSelect';\n\n\t/** @internal */\n\t_prepare(isOneTimeQuery = true): SQLiteSelectPrepare {\n\t\tif (!this.session) {\n\t\t\tthrow new Error('Cannot execute a query on a query builder. Please use a database instance instead.');\n\t\t}\n\t\tconst fieldsList = orderSelectedFields(this.config.fields);\n\t\tconst query = this.session[isOneTimeQuery ? 'prepareOneTimeQuery' : 'prepareQuery'](\n\t\t\tthis.dialect.sqlToQuery(this.getSQL()),\n\t\t\tfieldsList,\n\t\t\t'all',\n\t\t\ttrue,\n\t\t\tundefined,\n\t\t\t{\n\t\t\t\ttype: 'select',\n\t\t\t\ttables: [...this.usedTables],\n\t\t\t},\n\t\t\tthis.cacheConfig,\n\t\t);\n\t\tquery.joinsNotNullableMap = this.joinsNotNullableMap;\n\t\treturn query as ReturnType;\n\t}\n\n\t$withCache(config?: { config?: CacheConfig; tag?: string; autoInvalidate?: boolean } | false) {\n\t\tthis.cacheConfig = config === undefined\n\t\t\t? { config: {}, enable: true, autoInvalidate: true }\n\t\t\t: config === false\n\t\t\t? { enable: false }\n\t\t\t: { enable: true, autoInvalidate: true, ...config };\n\t\treturn this;\n\t}\n\n\tprepare(): SQLiteSelectPrepare {\n\t\treturn this._prepare(false);\n\t}\n\n\trun: ReturnType['run'] = (placeholderValues) => {\n\t\treturn this._prepare().run(placeholderValues);\n\t};\n\n\tall: ReturnType['all'] = (placeholderValues) => {\n\t\treturn this._prepare().all(placeholderValues);\n\t};\n\n\tget: ReturnType['get'] = (placeholderValues) => {\n\t\treturn this._prepare().get(placeholderValues);\n\t};\n\n\tvalues: ReturnType['values'] = (placeholderValues) => {\n\t\treturn this._prepare().values(placeholderValues);\n\t};\n\n\tasync execute(): Promise> {\n\t\treturn this.all() as SQLiteSelectExecute;\n\t}\n}\n\napplyMixins(SQLiteSelectBase, [QueryPromise]);\n\nfunction createSetOperator(type: SetOperator, isAll: boolean): SQLiteCreateSetOperatorFn {\n\treturn (leftSelect, rightSelect, ...restSelects) => {\n\t\tconst setOperators = [rightSelect, ...restSelects].map((select) => ({\n\t\t\ttype,\n\t\t\tisAll,\n\t\t\trightSelect: select as AnySQLiteSelect,\n\t\t}));\n\n\t\tfor (const setOperator of setOperators) {\n\t\t\tif (!haveSameKeys((leftSelect as any).getSelectedFields(), setOperator.rightSelect.getSelectedFields())) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t'Set operator error (union / intersect / except): selected fields are not the same or are in a different order',\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\treturn (leftSelect as AnySQLiteSelect).addSetOperators(setOperators) as any;\n\t};\n}\n\nconst getSQLiteSetOperators = () => ({\n\tunion,\n\tunionAll,\n\tintersect,\n\texcept,\n});\n\n/**\n * Adds `union` set operator to the query.\n *\n * Calling this method will combine the result sets of the `select` statements and remove any duplicate rows that appear across them.\n *\n * See docs: {@link https://orm.drizzle.team/docs/set-operations#union}\n *\n * @example\n *\n * ```ts\n * // Select all unique names from customers and users tables\n * import { union } from 'drizzle-orm/sqlite-core'\n *\n * await union(\n * db.select({ name: users.name }).from(users),\n * db.select({ name: customers.name }).from(customers)\n * );\n * // or\n * await db.select({ name: users.name })\n * .from(users)\n * .union(\n * db.select({ name: customers.name }).from(customers)\n * );\n * ```\n */\nexport const union = createSetOperator('union', false);\n\n/**\n * Adds `union all` set operator to the query.\n *\n * Calling this method will combine the result-set of the `select` statements and keep all duplicate rows that appear across them.\n *\n * See docs: {@link https://orm.drizzle.team/docs/set-operations#union-all}\n *\n * @example\n *\n * ```ts\n * // Select all transaction ids from both online and in-store sales\n * import { unionAll } from 'drizzle-orm/sqlite-core'\n *\n * await unionAll(\n * db.select({ transaction: onlineSales.transactionId }).from(onlineSales),\n * db.select({ transaction: inStoreSales.transactionId }).from(inStoreSales)\n * );\n * // or\n * await db.select({ transaction: onlineSales.transactionId })\n * .from(onlineSales)\n * .unionAll(\n * db.select({ transaction: inStoreSales.transactionId }).from(inStoreSales)\n * );\n * ```\n */\nexport const unionAll = createSetOperator('union', true);\n\n/**\n * Adds `intersect` set operator to the query.\n *\n * Calling this method will retain only the rows that are present in both result sets and eliminate duplicates.\n *\n * See docs: {@link https://orm.drizzle.team/docs/set-operations#intersect}\n *\n * @example\n *\n * ```ts\n * // Select course names that are offered in both departments A and B\n * import { intersect } from 'drizzle-orm/sqlite-core'\n *\n * await intersect(\n * db.select({ courseName: depA.courseName }).from(depA),\n * db.select({ courseName: depB.courseName }).from(depB)\n * );\n * // or\n * await db.select({ courseName: depA.courseName })\n * .from(depA)\n * .intersect(\n * db.select({ courseName: depB.courseName }).from(depB)\n * );\n * ```\n */\nexport const intersect = createSetOperator('intersect', false);\n\n/**\n * Adds `except` set operator to the query.\n *\n * Calling this method will retrieve all unique rows from the left query, except for the rows that are present in the result set of the right query.\n *\n * See docs: {@link https://orm.drizzle.team/docs/set-operations#except}\n *\n * @example\n *\n * ```ts\n * // Select all courses offered in department A but not in department B\n * import { except } from 'drizzle-orm/sqlite-core'\n *\n * await except(\n * db.select({ courseName: depA.courseName }).from(depA),\n * db.select({ courseName: depB.courseName }).from(depB)\n * );\n * // or\n * await db.select({ courseName: depA.courseName })\n * .from(depA)\n * .except(\n * db.select({ courseName: depB.courseName }).from(depB)\n * );\n * ```\n */\nexport const except = createSetOperator('except', false);\n", "import { entityKind } from '~/entity.ts';\nimport type { SQL, SQLWrapper } from '~/sql/index.ts';\n\nexport abstract class TypedQueryBuilder implements SQLWrapper {\n\tstatic readonly [entityKind]: string = 'TypedQueryBuilder';\n\n\tdeclare _: {\n\t\tselectedFields: TSelection;\n\t\tresult: TResult;\n\t\tconfig?: TConfig;\n\t};\n\n\t/** @internal */\n\tgetSelectedFields(): TSelection {\n\t\treturn this._.selectedFields;\n\t}\n\n\tabstract getSQL(): SQL;\n}\n", "import type { GetColumnData } from '~/column.ts';\nimport { entityKind, is } from '~/entity.ts';\nimport type { JoinType, SelectResultFields } from '~/query-builders/select.types.ts';\nimport { QueryPromise } from '~/query-promise.ts';\nimport type { RunnableQuery } from '~/runnable-query.ts';\nimport { SelectionProxyHandler } from '~/selection-proxy.ts';\nimport type { Placeholder, Query, SQL, SQLWrapper } from '~/sql/sql.ts';\nimport type { SQLiteDialect } from '~/sqlite-core/dialect.ts';\nimport type { SQLitePreparedQuery, SQLiteSession } from '~/sqlite-core/session.ts';\nimport { SQLiteTable } from '~/sqlite-core/table.ts';\nimport { Subquery } from '~/subquery.ts';\nimport { Table } from '~/table.ts';\nimport {\n\ttype DrizzleTypeError,\n\tgetTableLikeName,\n\tmapUpdateSet,\n\torderSelectedFields,\n\ttype UpdateSet,\n\ttype ValueOrArray,\n} from '~/utils.ts';\nimport { ViewBaseConfig } from '~/view-common.ts';\nimport type { SQLiteColumn } from '../columns/common.ts';\nimport { extractUsedTable } from '../utils.ts';\nimport { SQLiteViewBase } from '../view-base.ts';\nimport type { SelectedFields, SelectedFieldsOrdered, SQLiteSelectJoinConfig } from './select.types.ts';\n\nexport interface SQLiteUpdateConfig {\n\twhere?: SQL | undefined;\n\tlimit?: number | Placeholder;\n\torderBy?: (SQLiteColumn | SQL | SQL.Aliased)[];\n\tset: UpdateSet;\n\ttable: SQLiteTable;\n\tfrom?: SQLiteTable | Subquery | SQLiteViewBase | SQL;\n\tjoins: SQLiteSelectJoinConfig[];\n\treturning?: SelectedFieldsOrdered;\n\twithList?: Subquery[];\n}\n\nexport type SQLiteUpdateSetSource =\n\t& {\n\t\t[Key in keyof TTable['$inferInsert']]?:\n\t\t\t| GetColumnData\n\t\t\t| SQL\n\t\t\t| SQLiteColumn\n\t\t\t| undefined;\n\t}\n\t& {};\n\nexport class SQLiteUpdateBuilder<\n\tTTable extends SQLiteTable,\n\tTResultType extends 'sync' | 'async',\n\tTRunResult,\n> {\n\tstatic readonly [entityKind]: string = 'SQLiteUpdateBuilder';\n\n\tdeclare readonly _: {\n\t\treadonly table: TTable;\n\t};\n\n\tconstructor(\n\t\tprotected table: TTable,\n\t\tprotected session: SQLiteSession,\n\t\tprotected dialect: SQLiteDialect,\n\t\tprivate withList?: Subquery[],\n\t) {}\n\n\tset(\n\t\tvalues: SQLiteUpdateSetSource,\n\t): SQLiteUpdateWithout<\n\t\tSQLiteUpdateBase,\n\t\tfalse,\n\t\t'leftJoin' | 'rightJoin' | 'innerJoin' | 'fullJoin'\n\t> {\n\t\treturn new SQLiteUpdateBase(\n\t\t\tthis.table,\n\t\t\tmapUpdateSet(this.table, values),\n\t\t\tthis.session,\n\t\t\tthis.dialect,\n\t\t\tthis.withList,\n\t\t) as any;\n\t}\n}\n\nexport type SQLiteUpdateWithout<\n\tT extends AnySQLiteUpdate,\n\tTDynamic extends boolean,\n\tK extends keyof T & string,\n> = TDynamic extends true ? T : Omit<\n\tSQLiteUpdateBase<\n\t\tT['_']['table'],\n\t\tT['_']['resultType'],\n\t\tT['_']['runResult'],\n\t\tT['_']['from'],\n\t\tT['_']['returning'],\n\t\tTDynamic,\n\t\tT['_']['excludedMethods'] | K\n\t>,\n\tT['_']['excludedMethods'] | K\n>;\n\nexport type SQLiteUpdateWithJoins<\n\tT extends AnySQLiteUpdate,\n\tTDynamic extends boolean,\n\tTFrom extends SQLiteTable | Subquery | SQLiteViewBase | SQL,\n> = TDynamic extends true ? T : Omit<\n\tSQLiteUpdateBase<\n\t\tT['_']['table'],\n\t\tT['_']['resultType'],\n\t\tT['_']['runResult'],\n\t\tTFrom,\n\t\tT['_']['returning'],\n\t\tTDynamic,\n\t\tExclude\n\t>,\n\tExclude\n>;\n\nexport type SQLiteUpdateReturningAll = SQLiteUpdateWithout<\n\tSQLiteUpdateBase<\n\t\tT['_']['table'],\n\t\tT['_']['resultType'],\n\t\tT['_']['runResult'],\n\t\tT['_']['from'],\n\t\tT['_']['table']['$inferSelect'],\n\t\tTDynamic,\n\t\tT['_']['excludedMethods']\n\t>,\n\tTDynamic,\n\t'returning'\n>;\n\nexport type SQLiteUpdateReturning<\n\tT extends AnySQLiteUpdate,\n\tTDynamic extends boolean,\n\tTSelectedFields extends SelectedFields,\n> = SQLiteUpdateWithout<\n\tSQLiteUpdateBase<\n\t\tT['_']['table'],\n\t\tT['_']['resultType'],\n\t\tT['_']['runResult'],\n\t\tT['_']['from'],\n\t\tSelectResultFields,\n\t\tTDynamic,\n\t\tT['_']['excludedMethods']\n\t>,\n\tTDynamic,\n\t'returning'\n>;\n\nexport type SQLiteUpdateExecute = T['_']['returning'] extends undefined ? T['_']['runResult']\n\t: T['_']['returning'][];\n\nexport type SQLiteUpdatePrepare = SQLitePreparedQuery<\n\t{\n\t\ttype: T['_']['resultType'];\n\t\trun: T['_']['runResult'];\n\t\tall: T['_']['returning'] extends undefined ? DrizzleTypeError<'.all() cannot be used without .returning()'>\n\t\t\t: T['_']['returning'][];\n\t\tget: T['_']['returning'] extends undefined ? DrizzleTypeError<'.get() cannot be used without .returning()'>\n\t\t\t: T['_']['returning'];\n\t\tvalues: T['_']['returning'] extends undefined ? DrizzleTypeError<'.values() cannot be used without .returning()'>\n\t\t\t: any[][];\n\t\texecute: SQLiteUpdateExecute;\n\t}\n>;\n\nexport type SQLiteUpdateJoinFn<\n\tT extends AnySQLiteUpdate,\n> = <\n\tTJoinedTable extends SQLiteTable | Subquery | SQLiteViewBase | SQL,\n>(\n\ttable: TJoinedTable,\n\ton:\n\t\t| (\n\t\t\t(\n\t\t\t\tupdateTable: T['_']['table']['_']['columns'],\n\t\t\t\tfrom: T['_']['from'] extends SQLiteTable ? T['_']['from']['_']['columns']\n\t\t\t\t\t: T['_']['from'] extends Subquery | SQLiteViewBase ? T['_']['from']['_']['selectedFields']\n\t\t\t\t\t: never,\n\t\t\t) => SQL | undefined\n\t\t)\n\t\t| SQL\n\t\t| undefined,\n) => T;\n\nexport type SQLiteUpdateDynamic = SQLiteUpdate<\n\tT['_']['table'],\n\tT['_']['resultType'],\n\tT['_']['runResult'],\n\tT['_']['returning']\n>;\n\nexport type SQLiteUpdate<\n\tTTable extends SQLiteTable = SQLiteTable,\n\tTResultType extends 'sync' | 'async' = 'sync' | 'async',\n\tTRunResult = any,\n\tTFrom extends SQLiteTable | Subquery | SQLiteViewBase | SQL | undefined = undefined,\n\tTReturning extends Record | undefined = Record | undefined,\n> = SQLiteUpdateBase;\n\nexport type AnySQLiteUpdate = SQLiteUpdateBase;\n\nexport interface SQLiteUpdateBase<\n\tTTable extends SQLiteTable = SQLiteTable,\n\tTResultType extends 'sync' | 'async' = 'sync' | 'async',\n\tTRunResult = unknown,\n\tTFrom extends SQLiteTable | Subquery | SQLiteViewBase | SQL | undefined = undefined,\n\tTReturning = undefined,\n\tTDynamic extends boolean = false,\n\tTExcludedMethods extends string = never,\n> extends SQLWrapper, QueryPromise {\n\treadonly _: {\n\t\treadonly dialect: 'sqlite';\n\t\treadonly table: TTable;\n\t\treadonly resultType: TResultType;\n\t\treadonly runResult: TRunResult;\n\t\treadonly from: TFrom;\n\t\treadonly returning: TReturning;\n\t\treadonly dynamic: TDynamic;\n\t\treadonly excludedMethods: TExcludedMethods;\n\t\treadonly result: TReturning extends undefined ? TRunResult : TReturning[];\n\t};\n}\n\nexport class SQLiteUpdateBase<\n\tTTable extends SQLiteTable = SQLiteTable,\n\t// eslint-disable-next-line @typescript-eslint/no-unused-vars\n\tTResultType extends 'sync' | 'async' = 'sync' | 'async',\n\tTRunResult = unknown,\n\tTFrom extends SQLiteTable | Subquery | SQLiteViewBase | SQL | undefined = undefined,\n\tTReturning = undefined,\n\t// eslint-disable-next-line @typescript-eslint/no-unused-vars\n\tTDynamic extends boolean = false,\n\t// eslint-disable-next-line @typescript-eslint/no-unused-vars\n\tTExcludedMethods extends string = never,\n> extends QueryPromise\n\timplements RunnableQuery, SQLWrapper\n{\n\tstatic override readonly [entityKind]: string = 'SQLiteUpdate';\n\n\t/** @internal */\n\tconfig: SQLiteUpdateConfig;\n\n\tconstructor(\n\t\ttable: TTable,\n\t\tset: UpdateSet,\n\t\tprivate session: SQLiteSession,\n\t\tprivate dialect: SQLiteDialect,\n\t\twithList?: Subquery[],\n\t) {\n\t\tsuper();\n\t\tthis.config = { set, table, withList, joins: [] };\n\t}\n\n\tfrom(\n\t\tsource: TFrom,\n\t): SQLiteUpdateWithJoins {\n\t\tthis.config.from = source;\n\t\treturn this as any;\n\t}\n\n\tprivate createJoin(\n\t\tjoinType: TJoinType,\n\t): SQLiteUpdateJoinFn {\n\t\treturn ((\n\t\t\ttable: SQLiteTable | Subquery | SQLiteViewBase | SQL,\n\t\t\ton: ((updateTable: TTable, from: TFrom) => SQL | undefined) | SQL | undefined,\n\t\t) => {\n\t\t\tconst tableName = getTableLikeName(table);\n\n\t\t\tif (typeof tableName === 'string' && this.config.joins.some((join) => join.alias === tableName)) {\n\t\t\t\tthrow new Error(`Alias \"${tableName}\" is already used in this query`);\n\t\t\t}\n\n\t\t\tif (typeof on === 'function') {\n\t\t\t\tconst from = this.config.from\n\t\t\t\t\t? is(table, SQLiteTable)\n\t\t\t\t\t\t? table[Table.Symbol.Columns]\n\t\t\t\t\t\t: is(table, Subquery)\n\t\t\t\t\t\t? table._.selectedFields\n\t\t\t\t\t\t: is(table, SQLiteViewBase)\n\t\t\t\t\t\t? table[ViewBaseConfig].selectedFields\n\t\t\t\t\t\t: undefined\n\t\t\t\t\t: undefined;\n\t\t\t\ton = on(\n\t\t\t\t\tnew Proxy(\n\t\t\t\t\t\tthis.config.table[Table.Symbol.Columns],\n\t\t\t\t\t\tnew SelectionProxyHandler({ sqlAliasedBehavior: 'sql', sqlBehavior: 'sql' }),\n\t\t\t\t\t) as any,\n\t\t\t\t\tfrom && new Proxy(\n\t\t\t\t\t\tfrom,\n\t\t\t\t\t\tnew SelectionProxyHandler({ sqlAliasedBehavior: 'sql', sqlBehavior: 'sql' }),\n\t\t\t\t\t) as any,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tthis.config.joins.push({ on, table, joinType, alias: tableName });\n\n\t\t\treturn this as any;\n\t\t}) as any;\n\t}\n\n\tleftJoin = this.createJoin('left');\n\n\trightJoin = this.createJoin('right');\n\n\tinnerJoin = this.createJoin('inner');\n\n\tfullJoin = this.createJoin('full');\n\n\t/**\n\t * Adds a 'where' clause to the query.\n\t *\n\t * Calling this method will update only those rows that fulfill a specified condition.\n\t *\n\t * See docs: {@link https://orm.drizzle.team/docs/update}\n\t *\n\t * @param where the 'where' clause.\n\t *\n\t * @example\n\t * You can use conditional operators and `sql function` to filter the rows to be updated.\n\t *\n\t * ```ts\n\t * // Update all cars with green color\n\t * db.update(cars).set({ color: 'red' })\n\t * .where(eq(cars.color, 'green'));\n\t * // or\n\t * db.update(cars).set({ color: 'red' })\n\t * .where(sql`${cars.color} = 'green'`)\n\t * ```\n\t *\n\t * You can logically combine conditional operators with `and()` and `or()` operators:\n\t *\n\t * ```ts\n\t * // Update all BMW cars with a green color\n\t * db.update(cars).set({ color: 'red' })\n\t * .where(and(eq(cars.color, 'green'), eq(cars.brand, 'BMW')));\n\t *\n\t * // Update all cars with the green or blue color\n\t * db.update(cars).set({ color: 'red' })\n\t * .where(or(eq(cars.color, 'green'), eq(cars.color, 'blue')));\n\t * ```\n\t */\n\twhere(where: SQL | undefined): SQLiteUpdateWithout {\n\t\tthis.config.where = where;\n\t\treturn this as any;\n\t}\n\n\torderBy(\n\t\tbuilder: (updateTable: TTable) => ValueOrArray,\n\t): SQLiteUpdateWithout;\n\torderBy(...columns: (SQLiteColumn | SQL | SQL.Aliased)[]): SQLiteUpdateWithout;\n\torderBy(\n\t\t...columns:\n\t\t\t| [(updateTable: TTable) => ValueOrArray]\n\t\t\t| (SQLiteColumn | SQL | SQL.Aliased)[]\n\t): SQLiteUpdateWithout {\n\t\tif (typeof columns[0] === 'function') {\n\t\t\tconst orderBy = columns[0](\n\t\t\t\tnew Proxy(\n\t\t\t\t\tthis.config.table[Table.Symbol.Columns],\n\t\t\t\t\tnew SelectionProxyHandler({ sqlAliasedBehavior: 'alias', sqlBehavior: 'sql' }),\n\t\t\t\t) as any,\n\t\t\t);\n\n\t\t\tconst orderByArray = Array.isArray(orderBy) ? orderBy : [orderBy];\n\t\t\tthis.config.orderBy = orderByArray;\n\t\t} else {\n\t\t\tconst orderByArray = columns as (SQLiteColumn | SQL | SQL.Aliased)[];\n\t\t\tthis.config.orderBy = orderByArray;\n\t\t}\n\t\treturn this as any;\n\t}\n\n\tlimit(limit: number | Placeholder): SQLiteUpdateWithout {\n\t\tthis.config.limit = limit;\n\t\treturn this as any;\n\t}\n\n\t/**\n\t * Adds a `returning` clause to the query.\n\t *\n\t * Calling this method will return the specified fields of the updated rows. If no fields are specified, all fields will be returned.\n\t *\n\t * See docs: {@link https://orm.drizzle.team/docs/update#update-with-returning}\n\t *\n\t * @example\n\t * ```ts\n\t * // Update all cars with the green color and return all fields\n\t * const updatedCars: Car[] = await db.update(cars)\n\t * .set({ color: 'red' })\n\t * .where(eq(cars.color, 'green'))\n\t * .returning();\n\t *\n\t * // Update all cars with the green color and return only their id and brand fields\n\t * const updatedCarsIdsAndBrands: { id: number, brand: string }[] = await db.update(cars)\n\t * .set({ color: 'red' })\n\t * .where(eq(cars.color, 'green'))\n\t * .returning({ id: cars.id, brand: cars.brand });\n\t * ```\n\t */\n\treturning(): SQLiteUpdateReturningAll;\n\treturning(\n\t\tfields: TSelectedFields,\n\t): SQLiteUpdateReturning;\n\treturning(\n\t\tfields: SelectedFields = this.config.table[SQLiteTable.Symbol.Columns],\n\t): SQLiteUpdateWithout {\n\t\tthis.config.returning = orderSelectedFields(fields);\n\t\treturn this as any;\n\t}\n\n\t/** @internal */\n\tgetSQL(): SQL {\n\t\treturn this.dialect.buildUpdateQuery(this.config);\n\t}\n\n\ttoSQL(): Query {\n\t\tconst { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());\n\t\treturn rest;\n\t}\n\n\t/** @internal */\n\t_prepare(isOneTimeQuery = true): SQLiteUpdatePrepare {\n\t\treturn this.session[isOneTimeQuery ? 'prepareOneTimeQuery' : 'prepareQuery'](\n\t\t\tthis.dialect.sqlToQuery(this.getSQL()),\n\t\t\tthis.config.returning,\n\t\t\tthis.config.returning ? 'all' : 'run',\n\t\t\ttrue,\n\t\t\tundefined,\n\t\t\t{\n\t\t\t\ttype: 'insert',\n\t\t\t\ttables: extractUsedTable(this.config.table),\n\t\t\t},\n\t\t) as SQLiteUpdatePrepare;\n\t}\n\n\tprepare(): SQLiteUpdatePrepare {\n\t\treturn this._prepare(false);\n\t}\n\n\trun: ReturnType['run'] = (placeholderValues) => {\n\t\treturn this._prepare().run(placeholderValues);\n\t};\n\n\tall: ReturnType['all'] = (placeholderValues) => {\n\t\treturn this._prepare().all(placeholderValues);\n\t};\n\n\tget: ReturnType['get'] = (placeholderValues) => {\n\t\treturn this._prepare().get(placeholderValues);\n\t};\n\n\tvalues: ReturnType['values'] = (placeholderValues) => {\n\t\treturn this._prepare().values(placeholderValues);\n\t};\n\n\toverride async execute(): Promise> {\n\t\treturn (this.config.returning ? this.all() : this.run()) as SQLiteUpdateExecute;\n\t}\n\n\t$dynamic(): SQLiteUpdateDynamic {\n\t\treturn this as any;\n\t}\n}\n", "import { entityKind } from '~/entity.ts';\nimport { SQL, sql, type SQLWrapper } from '~/sql/sql.ts';\nimport type { SQLiteSession } from '../session.ts';\nimport type { SQLiteTable } from '../table.ts';\nimport type { SQLiteView } from '../view.ts';\n\nexport class SQLiteCountBuilder<\n\tTSession extends SQLiteSession,\n> extends SQL implements Promise, SQLWrapper {\n\tprivate sql: SQL;\n\n\tstatic override readonly [entityKind] = 'SQLiteCountBuilderAsync';\n\t[Symbol.toStringTag] = 'SQLiteCountBuilderAsync';\n\n\tprivate session: TSession;\n\n\tprivate static buildEmbeddedCount(\n\t\tsource: SQLiteTable | SQLiteView | SQL | SQLWrapper,\n\t\tfilters?: SQL,\n\t): SQL {\n\t\treturn sql`(select count(*) from ${source}${sql.raw(' where ').if(filters)}${filters})`;\n\t}\n\n\tprivate static buildCount(\n\t\tsource: SQLiteTable | SQLiteView | SQL | SQLWrapper,\n\t\tfilters?: SQL,\n\t): SQL {\n\t\treturn sql`select count(*) from ${source}${sql.raw(' where ').if(filters)}${filters}`;\n\t}\n\n\tconstructor(\n\t\treadonly params: {\n\t\t\tsource: SQLiteTable | SQLiteView | SQL | SQLWrapper;\n\t\t\tfilters?: SQL;\n\t\t\tsession: TSession;\n\t\t},\n\t) {\n\t\tsuper(SQLiteCountBuilder.buildEmbeddedCount(params.source, params.filters).queryChunks);\n\n\t\tthis.session = params.session;\n\n\t\tthis.sql = SQLiteCountBuilder.buildCount(\n\t\t\tparams.source,\n\t\t\tparams.filters,\n\t\t);\n\t}\n\n\tthen(\n\t\tonfulfilled?: ((value: number) => TResult1 | PromiseLike) | null | undefined,\n\t\tonrejected?: ((reason: any) => TResult2 | PromiseLike) | null | undefined,\n\t): Promise {\n\t\treturn Promise.resolve(this.session.count(this.sql)).then(\n\t\t\tonfulfilled,\n\t\t\tonrejected,\n\t\t);\n\t}\n\n\tcatch(\n\t\tonRejected?: ((reason: any) => never | PromiseLike) | null | undefined,\n\t): Promise {\n\t\treturn this.then(undefined, onRejected);\n\t}\n\n\tfinally(onFinally?: (() => void) | null | undefined): Promise {\n\t\treturn this.then(\n\t\t\t(value) => {\n\t\t\t\tonFinally?.();\n\t\t\t\treturn value;\n\t\t\t},\n\t\t\t(reason) => {\n\t\t\t\tonFinally?.();\n\t\t\t\tthrow reason;\n\t\t\t},\n\t\t);\n\t}\n}\n", "import { entityKind } from '~/entity.ts';\nimport { QueryPromise } from '~/query-promise.ts';\nimport {\n\ttype BuildQueryResult,\n\ttype BuildRelationalQueryResult,\n\ttype DBQueryConfig,\n\tmapRelationalRow,\n\ttype TableRelationalConfig,\n\ttype TablesRelationalConfig,\n} from '~/relations.ts';\nimport type { RunnableQuery } from '~/runnable-query.ts';\nimport type { Query, QueryWithTypings, SQL, SQLWrapper } from '~/sql/sql.ts';\nimport type { KnownKeysOnly } from '~/utils.ts';\nimport type { SQLiteDialect } from '../dialect.ts';\nimport type { PreparedQueryConfig, SQLitePreparedQuery, SQLiteSession } from '../session.ts';\nimport type { SQLiteTable } from '../table.ts';\n\nexport type SQLiteRelationalQueryKind = TMode extends 'async'\n\t? SQLiteRelationalQuery\n\t: SQLiteSyncRelationalQuery;\n\nexport class RelationalQueryBuilder<\n\tTMode extends 'sync' | 'async',\n\tTFullSchema extends Record,\n\tTSchema extends TablesRelationalConfig,\n\tTFields extends TableRelationalConfig,\n> {\n\tstatic readonly [entityKind]: string = 'SQLiteAsyncRelationalQueryBuilder';\n\n\tconstructor(\n\t\tprotected mode: TMode,\n\t\tprotected fullSchema: Record,\n\t\tprotected schema: TSchema,\n\t\tprotected tableNamesMap: Record,\n\t\tprotected table: SQLiteTable,\n\t\tprotected tableConfig: TableRelationalConfig,\n\t\tprotected dialect: SQLiteDialect,\n\t\tprotected session: SQLiteSession<'async', unknown, TFullSchema, TSchema>,\n\t) {}\n\n\tfindMany>(\n\t\tconfig?: KnownKeysOnly>,\n\t): SQLiteRelationalQueryKind[]> {\n\t\treturn (this.mode === 'sync'\n\t\t\t? new SQLiteSyncRelationalQuery(\n\t\t\t\tthis.fullSchema,\n\t\t\t\tthis.schema,\n\t\t\t\tthis.tableNamesMap,\n\t\t\t\tthis.table,\n\t\t\t\tthis.tableConfig,\n\t\t\t\tthis.dialect,\n\t\t\t\tthis.session,\n\t\t\t\tconfig ? (config as DBQueryConfig<'many', true>) : {},\n\t\t\t\t'many',\n\t\t\t)\n\t\t\t: new SQLiteRelationalQuery(\n\t\t\t\tthis.fullSchema,\n\t\t\t\tthis.schema,\n\t\t\t\tthis.tableNamesMap,\n\t\t\t\tthis.table,\n\t\t\t\tthis.tableConfig,\n\t\t\t\tthis.dialect,\n\t\t\t\tthis.session,\n\t\t\t\tconfig ? (config as DBQueryConfig<'many', true>) : {},\n\t\t\t\t'many',\n\t\t\t)) as SQLiteRelationalQueryKind[]>;\n\t}\n\n\tfindFirst, 'limit'>>(\n\t\tconfig?: KnownKeysOnly, 'limit'>>,\n\t): SQLiteRelationalQueryKind | undefined> {\n\t\treturn (this.mode === 'sync'\n\t\t\t? new SQLiteSyncRelationalQuery(\n\t\t\t\tthis.fullSchema,\n\t\t\t\tthis.schema,\n\t\t\t\tthis.tableNamesMap,\n\t\t\t\tthis.table,\n\t\t\t\tthis.tableConfig,\n\t\t\t\tthis.dialect,\n\t\t\t\tthis.session,\n\t\t\t\tconfig ? { ...(config as DBQueryConfig<'many', true> | undefined), limit: 1 } : { limit: 1 },\n\t\t\t\t'first',\n\t\t\t)\n\t\t\t: new SQLiteRelationalQuery(\n\t\t\t\tthis.fullSchema,\n\t\t\t\tthis.schema,\n\t\t\t\tthis.tableNamesMap,\n\t\t\t\tthis.table,\n\t\t\t\tthis.tableConfig,\n\t\t\t\tthis.dialect,\n\t\t\t\tthis.session,\n\t\t\t\tconfig ? { ...(config as DBQueryConfig<'many', true> | undefined), limit: 1 } : { limit: 1 },\n\t\t\t\t'first',\n\t\t\t)) as SQLiteRelationalQueryKind | undefined>;\n\t}\n}\n\nexport class SQLiteRelationalQuery extends QueryPromise\n\timplements RunnableQuery, SQLWrapper\n{\n\tstatic override readonly [entityKind]: string = 'SQLiteAsyncRelationalQuery';\n\n\tdeclare readonly _: {\n\t\treadonly dialect: 'sqlite';\n\t\treadonly type: TType;\n\t\treadonly result: TResult;\n\t};\n\n\t/** @internal */\n\tmode: 'many' | 'first';\n\n\tconstructor(\n\t\tprivate fullSchema: Record,\n\t\tprivate schema: TablesRelationalConfig,\n\t\tprivate tableNamesMap: Record,\n\t\t/** @internal */\n\t\tpublic table: SQLiteTable,\n\t\tprivate tableConfig: TableRelationalConfig,\n\t\tprivate dialect: SQLiteDialect,\n\t\tprivate session: SQLiteSession<'sync' | 'async', unknown, Record, TablesRelationalConfig>,\n\t\tprivate config: DBQueryConfig<'many', true> | true,\n\t\tmode: 'many' | 'first',\n\t) {\n\t\tsuper();\n\t\tthis.mode = mode;\n\t}\n\n\t/** @internal */\n\tgetSQL(): SQL {\n\t\treturn this.dialect.buildRelationalQuery({\n\t\t\tfullSchema: this.fullSchema,\n\t\t\tschema: this.schema,\n\t\t\ttableNamesMap: this.tableNamesMap,\n\t\t\ttable: this.table,\n\t\t\ttableConfig: this.tableConfig,\n\t\t\tqueryConfig: this.config,\n\t\t\ttableAlias: this.tableConfig.tsName,\n\t\t}).sql as SQL;\n\t}\n\n\t/** @internal */\n\t_prepare(\n\t\tisOneTimeQuery = false,\n\t): SQLitePreparedQuery {\n\t\tconst { query, builtQuery } = this._toSQL();\n\n\t\treturn this.session[isOneTimeQuery ? 'prepareOneTimeQuery' : 'prepareQuery'](\n\t\t\tbuiltQuery,\n\t\t\tundefined,\n\t\t\tthis.mode === 'first' ? 'get' : 'all',\n\t\t\ttrue,\n\t\t\t(rawRows, mapColumnValue) => {\n\t\t\t\tconst rows = rawRows.map((row) =>\n\t\t\t\t\tmapRelationalRow(this.schema, this.tableConfig, row, query.selection, mapColumnValue)\n\t\t\t\t);\n\t\t\t\tif (this.mode === 'first') {\n\t\t\t\t\treturn rows[0] as TResult;\n\t\t\t\t}\n\t\t\t\treturn rows as TResult;\n\t\t\t},\n\t\t) as SQLitePreparedQuery;\n\t}\n\n\tprepare(): SQLitePreparedQuery {\n\t\treturn this._prepare(false);\n\t}\n\n\tprivate _toSQL(): { query: BuildRelationalQueryResult; builtQuery: QueryWithTypings } {\n\t\tconst query = this.dialect.buildRelationalQuery({\n\t\t\tfullSchema: this.fullSchema,\n\t\t\tschema: this.schema,\n\t\t\ttableNamesMap: this.tableNamesMap,\n\t\t\ttable: this.table,\n\t\t\ttableConfig: this.tableConfig,\n\t\t\tqueryConfig: this.config,\n\t\t\ttableAlias: this.tableConfig.tsName,\n\t\t});\n\n\t\tconst builtQuery = this.dialect.sqlToQuery(query.sql as SQL);\n\n\t\treturn { query, builtQuery };\n\t}\n\n\ttoSQL(): Query {\n\t\treturn this._toSQL().builtQuery;\n\t}\n\n\t/** @internal */\n\texecuteRaw(): TResult {\n\t\tif (this.mode === 'first') {\n\t\t\treturn this._prepare(false).get() as TResult;\n\t\t}\n\t\treturn this._prepare(false).all() as TResult;\n\t}\n\n\toverride async execute(): Promise {\n\t\treturn this.executeRaw();\n\t}\n}\n\nexport class SQLiteSyncRelationalQuery extends SQLiteRelationalQuery<'sync', TResult> {\n\tstatic override readonly [entityKind]: string = 'SQLiteSyncRelationalQuery';\n\n\tsync(): TResult {\n\t\treturn this.executeRaw();\n\t}\n}\n", "import { entityKind } from '~/entity.ts';\nimport { QueryPromise } from '~/query-promise.ts';\nimport type { RunnableQuery } from '~/runnable-query.ts';\nimport type { PreparedQuery } from '~/session.ts';\nimport type { SQL, SQLWrapper } from '~/sql/sql.ts';\nimport type { SQLiteAsyncDialect } from '../dialect.ts';\n\ntype SQLiteRawAction = 'all' | 'get' | 'values' | 'run';\nexport interface SQLiteRawConfig {\n\taction: SQLiteRawAction;\n}\n\nexport interface SQLiteRaw extends QueryPromise, RunnableQuery, SQLWrapper {}\n\nexport class SQLiteRaw extends QueryPromise\n\timplements RunnableQuery, SQLWrapper, PreparedQuery\n{\n\tstatic override readonly [entityKind]: string = 'SQLiteRaw';\n\n\tdeclare readonly _: {\n\t\treadonly dialect: 'sqlite';\n\t\treadonly result: TResult;\n\t};\n\n\t/** @internal */\n\tconfig: SQLiteRawConfig;\n\n\tconstructor(\n\t\tpublic execute: () => Promise,\n\t\t/** @internal */\n\t\tpublic getSQL: () => SQL,\n\t\taction: SQLiteRawAction,\n\t\tprivate dialect: SQLiteAsyncDialect,\n\t\tprivate mapBatchResult: (result: unknown) => unknown,\n\t) {\n\t\tsuper();\n\t\tthis.config = { action };\n\t}\n\n\tgetQuery() {\n\t\treturn { ...this.dialect.sqlToQuery(this.getSQL()), method: this.config.action };\n\t}\n\n\tmapResult(result: unknown, isFromBatch?: boolean) {\n\t\treturn isFromBatch ? this.mapBatchResult(result) : result;\n\t}\n\n\t_prepare(): PreparedQuery {\n\t\treturn this;\n\t}\n\n\t/** @internal */\n\tisResponseInArrayMode(): boolean {\n\t\treturn false;\n\t}\n}\n", "/// \n\nimport type { BatchItem } from '~/batch.ts';\nimport { type Cache, NoopCache } from '~/cache/core/index.ts';\nimport type { WithCacheConfig } from '~/cache/core/types.ts';\nimport { entityKind } from '~/entity.ts';\nimport type { Logger } from '~/logger.ts';\nimport { NoopLogger } from '~/logger.ts';\nimport type { RelationalSchemaConfig, TablesRelationalConfig } from '~/relations.ts';\nimport type { PreparedQuery } from '~/session.ts';\nimport { fillPlaceholders, type Query, sql } from '~/sql/sql.ts';\nimport type { SQLiteAsyncDialect } from '~/sqlite-core/dialect.ts';\nimport { SQLiteTransaction } from '~/sqlite-core/index.ts';\nimport type { SelectedFieldsOrdered } from '~/sqlite-core/query-builders/select.types.ts';\nimport type {\n\tPreparedQueryConfig as PreparedQueryConfigBase,\n\tSQLiteExecuteMethod,\n\tSQLiteTransactionConfig,\n} from '~/sqlite-core/session.ts';\nimport { SQLitePreparedQuery, SQLiteSession } from '~/sqlite-core/session.ts';\nimport { mapResultRow } from '~/utils.ts';\n\nexport interface SQLiteD1SessionOptions {\n\tlogger?: Logger;\n\tcache?: Cache;\n}\n\ntype PreparedQueryConfig = Omit;\n\nexport class SQLiteD1Session<\n\tTFullSchema extends Record,\n\tTSchema extends TablesRelationalConfig,\n> extends SQLiteSession<'async', D1Result, TFullSchema, TSchema> {\n\tstatic override readonly [entityKind]: string = 'SQLiteD1Session';\n\n\tprivate logger: Logger;\n\tprivate cache: Cache;\n\n\tconstructor(\n\t\tprivate client: D1Database,\n\t\tdialect: SQLiteAsyncDialect,\n\t\tprivate schema: RelationalSchemaConfig | undefined,\n\t\tprivate options: SQLiteD1SessionOptions = {},\n\t) {\n\t\tsuper(dialect);\n\t\tthis.logger = options.logger ?? new NoopLogger();\n\t\tthis.cache = options.cache ?? new NoopCache();\n\t}\n\n\tprepareQuery(\n\t\tquery: Query,\n\t\tfields: SelectedFieldsOrdered | undefined,\n\t\texecuteMethod: SQLiteExecuteMethod,\n\t\tisResponseInArrayMode: boolean,\n\t\tcustomResultMapper?: (rows: unknown[][]) => unknown,\n\t\tqueryMetadata?: {\n\t\t\ttype: 'select' | 'update' | 'delete' | 'insert';\n\t\t\ttables: string[];\n\t\t},\n\t\tcacheConfig?: WithCacheConfig,\n\t): D1PreparedQuery {\n\t\tconst stmt = this.client.prepare(query.sql);\n\t\treturn new D1PreparedQuery(\n\t\t\tstmt,\n\t\t\tquery,\n\t\t\tthis.logger,\n\t\t\tthis.cache,\n\t\t\tqueryMetadata,\n\t\t\tcacheConfig,\n\t\t\tfields,\n\t\t\texecuteMethod,\n\t\t\tisResponseInArrayMode,\n\t\t\tcustomResultMapper,\n\t\t);\n\t}\n\n\tasync batch[] | readonly BatchItem<'sqlite'>[]>(queries: T) {\n\t\tconst preparedQueries: PreparedQuery[] = [];\n\t\tconst builtQueries: D1PreparedStatement[] = [];\n\n\t\tfor (const query of queries) {\n\t\t\tconst preparedQuery = query._prepare();\n\t\t\tconst builtQuery = preparedQuery.getQuery();\n\t\t\tpreparedQueries.push(preparedQuery);\n\t\t\tif (builtQuery.params.length > 0) {\n\t\t\t\tbuiltQueries.push((preparedQuery as D1PreparedQuery).stmt.bind(...builtQuery.params));\n\t\t\t} else {\n\t\t\t\tconst builtQuery = preparedQuery.getQuery();\n\t\t\t\tbuiltQueries.push(\n\t\t\t\t\tthis.client.prepare(builtQuery.sql).bind(...builtQuery.params),\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\tconst batchResults = await this.client.batch(builtQueries);\n\t\treturn batchResults.map((result, i) => preparedQueries[i]!.mapResult(result, true));\n\t}\n\n\toverride extractRawAllValueFromBatchResult(result: unknown): unknown {\n\t\treturn (result as D1Result).results;\n\t}\n\n\toverride extractRawGetValueFromBatchResult(result: unknown): unknown {\n\t\treturn (result as D1Result).results[0];\n\t}\n\n\toverride extractRawValuesValueFromBatchResult(result: unknown): unknown {\n\t\treturn d1ToRawMapping((result as D1Result).results);\n\t}\n\n\toverride async transaction(\n\t\ttransaction: (tx: D1Transaction) => T | Promise,\n\t\tconfig?: SQLiteTransactionConfig,\n\t): Promise {\n\t\tconst tx = new D1Transaction('async', this.dialect, this, this.schema);\n\t\tawait this.run(sql.raw(`begin${config?.behavior ? ' ' + config.behavior : ''}`));\n\t\ttry {\n\t\t\tconst result = await transaction(tx);\n\t\t\tawait this.run(sql`commit`);\n\t\t\treturn result;\n\t\t} catch (err) {\n\t\t\tawait this.run(sql`rollback`);\n\t\t\tthrow err;\n\t\t}\n\t}\n}\n\nexport class D1Transaction<\n\tTFullSchema extends Record,\n\tTSchema extends TablesRelationalConfig,\n> extends SQLiteTransaction<'async', D1Result, TFullSchema, TSchema> {\n\tstatic override readonly [entityKind]: string = 'D1Transaction';\n\n\toverride async transaction(transaction: (tx: D1Transaction) => Promise): Promise {\n\t\tconst savepointName = `sp${this.nestedIndex}`;\n\t\tconst tx = new D1Transaction('async', this.dialect, this.session, this.schema, this.nestedIndex + 1);\n\t\tawait this.session.run(sql.raw(`savepoint ${savepointName}`));\n\t\ttry {\n\t\t\tconst result = await transaction(tx);\n\t\t\tawait this.session.run(sql.raw(`release savepoint ${savepointName}`));\n\t\t\treturn result;\n\t\t} catch (err) {\n\t\t\tawait this.session.run(sql.raw(`rollback to savepoint ${savepointName}`));\n\t\t\tthrow err;\n\t\t}\n\t}\n}\n\n/**\n * This function was taken from the D1 implementation: https://github.com/cloudflare/workerd/blob/4aae9f4c7ae30a59a88ca868c4aff88bda85c956/src/cloudflare/internal/d1-api.ts#L287\n * It may cause issues with duplicated column names in join queries, which should be fixed on the D1 side.\n * @param results\n * @returns\n */\nfunction d1ToRawMapping(results: any) {\n\tconst rows: unknown[][] = [];\n\tfor (const row of results) {\n\t\tconst entry = Object.keys(row).map((k) => row[k]);\n\t\trows.push(entry);\n\t}\n\treturn rows;\n}\n\nexport class D1PreparedQuery extends SQLitePreparedQuery<\n\t{ type: 'async'; run: D1Response; all: T['all']; get: T['get']; values: T['values']; execute: T['execute'] }\n> {\n\tstatic override readonly [entityKind]: string = 'D1PreparedQuery';\n\n\t/** @internal */\n\tcustomResultMapper?: (rows: unknown[][], mapColumnValue?: (value: unknown) => unknown) => unknown;\n\n\t/** @internal */\n\tfields?: SelectedFieldsOrdered;\n\n\t/** @internal */\n\tstmt: D1PreparedStatement;\n\n\tconstructor(\n\t\tstmt: D1PreparedStatement,\n\t\tquery: Query,\n\t\tprivate logger: Logger,\n\t\tcache: Cache,\n\t\tqueryMetadata: {\n\t\t\ttype: 'select' | 'update' | 'delete' | 'insert';\n\t\t\ttables: string[];\n\t\t} | undefined,\n\t\tcacheConfig: WithCacheConfig | undefined,\n\t\tfields: SelectedFieldsOrdered | undefined,\n\t\texecuteMethod: SQLiteExecuteMethod,\n\t\tprivate _isResponseInArrayMode: boolean,\n\t\tcustomResultMapper?: (rows: unknown[][]) => unknown,\n\t) {\n\t\tsuper('async', executeMethod, query, cache, queryMetadata, cacheConfig);\n\t\tthis.customResultMapper = customResultMapper;\n\t\tthis.fields = fields;\n\t\tthis.stmt = stmt;\n\t}\n\n\tasync run(placeholderValues?: Record): Promise {\n\t\tconst params = fillPlaceholders(this.query.params, placeholderValues ?? {});\n\t\tthis.logger.logQuery(this.query.sql, params);\n\t\treturn await this.queryWithCache(this.query.sql, params, async () => {\n\t\t\treturn this.stmt.bind(...params).run();\n\t\t});\n\t}\n\n\tasync all(placeholderValues?: Record): Promise {\n\t\tconst { fields, query, logger, stmt, customResultMapper } = this;\n\t\tif (!fields && !customResultMapper) {\n\t\t\tconst params = fillPlaceholders(query.params, placeholderValues ?? {});\n\t\t\tlogger.logQuery(query.sql, params);\n\t\t\treturn await this.queryWithCache(query.sql, params, async () => {\n\t\t\t\treturn stmt.bind(...params).all().then(({ results }) => this.mapAllResult(results!));\n\t\t\t});\n\t\t}\n\n\t\tconst rows = await this.values(placeholderValues);\n\n\t\treturn this.mapAllResult(rows);\n\t}\n\n\toverride mapAllResult(rows: unknown, isFromBatch?: boolean): unknown {\n\t\tif (isFromBatch) {\n\t\t\trows = d1ToRawMapping((rows as D1Result).results);\n\t\t}\n\n\t\tif (!this.fields && !this.customResultMapper) {\n\t\t\treturn rows;\n\t\t}\n\n\t\tif (this.customResultMapper) {\n\t\t\treturn this.customResultMapper(rows as unknown[][]);\n\t\t}\n\n\t\treturn (rows as unknown[][]).map((row) => mapResultRow(this.fields!, row, this.joinsNotNullableMap));\n\t}\n\n\tasync get(placeholderValues?: Record): Promise {\n\t\tconst { fields, joinsNotNullableMap, query, logger, stmt, customResultMapper } = this;\n\t\tif (!fields && !customResultMapper) {\n\t\t\tconst params = fillPlaceholders(query.params, placeholderValues ?? {});\n\t\t\tlogger.logQuery(query.sql, params);\n\t\t\treturn await this.queryWithCache(query.sql, params, async () => {\n\t\t\t\treturn stmt.bind(...params).all().then(({ results }) => results![0]);\n\t\t\t});\n\t\t}\n\n\t\tconst rows = await this.values(placeholderValues);\n\n\t\tif (!rows[0]) {\n\t\t\treturn undefined;\n\t\t}\n\n\t\tif (customResultMapper) {\n\t\t\treturn customResultMapper(rows) as T['all'];\n\t\t}\n\n\t\treturn mapResultRow(fields!, rows[0], joinsNotNullableMap);\n\t}\n\n\toverride mapGetResult(result: unknown, isFromBatch?: boolean): unknown {\n\t\tif (isFromBatch) {\n\t\t\tresult = d1ToRawMapping((result as D1Result).results)[0];\n\t\t}\n\n\t\tif (!this.fields && !this.customResultMapper) {\n\t\t\treturn result;\n\t\t}\n\n\t\tif (this.customResultMapper) {\n\t\t\treturn this.customResultMapper([result as unknown[]]) as T['all'];\n\t\t}\n\n\t\treturn mapResultRow(this.fields!, result as unknown[], this.joinsNotNullableMap);\n\t}\n\n\tasync values(placeholderValues?: Record): Promise {\n\t\tconst params = fillPlaceholders(this.query.params, placeholderValues ?? {});\n\t\tthis.logger.logQuery(this.query.sql, params);\n\t\treturn await this.queryWithCache(this.query.sql, params, async () => {\n\t\t\treturn this.stmt.bind(...params).raw();\n\t\t});\n\t}\n\n\t/** @internal */\n\tisResponseInArrayMode(): boolean {\n\t\treturn this._isResponseInArrayMode;\n\t}\n}\n", "import { entityKind } from '~/entity.ts';\nimport type { Table } from '~/index.ts';\nimport type { CacheConfig } from './types.ts';\n\nexport abstract class Cache {\n\tstatic readonly [entityKind]: string = 'Cache';\n\n\tabstract strategy(): 'explicit' | 'all';\n\n\t/**\n\t * Invoked if we should check cache for cached response\n\t * @param sql\n\t * @param tables\n\t */\n\tabstract get(\n\t\tkey: string,\n\t\ttables: string[],\n\t\tisTag: boolean,\n\t\tisAutoInvalidate?: boolean,\n\t): Promise;\n\n\t/**\n\t * Invoked if new query should be inserted to cache\n\t * @param sql\n\t * @param tables\n\t */\n\tabstract put(\n\t\thashedQuery: string,\n\t\tresponse: any,\n\t\ttables: string[],\n\t\tisTag: boolean,\n\t\tconfig?: CacheConfig,\n\t): Promise;\n\n\t/**\n\t * Invoked if insert, update, delete was invoked\n\t * @param tables\n\t */\n\tabstract onMutate(\n\t\tparams: MutationOption,\n\t): Promise;\n}\n\nexport class NoopCache extends Cache {\n\toverride strategy() {\n\t\treturn 'all' as const;\n\t}\n\n\tstatic override readonly [entityKind]: string = 'NoopCache';\n\n\toverride async get(_key: string): Promise {\n\t\treturn undefined;\n\t}\n\toverride async put(\n\t\t_hashedQuery: string,\n\t\t_response: any,\n\t\t_tables: string[],\n\t\t_config?: any,\n\t): Promise {\n\t\t// noop\n\t}\n\toverride async onMutate(_params: MutationOption): Promise {\n\t\t// noop\n\t}\n}\n\nexport type MutationOption = { tags?: string | string[]; tables?: Table | Table[] | string | string[] };\n\nexport async function hashQuery(sql: string, params?: any[]) {\n\tconst dataToHash = `${sql}-${JSON.stringify(params)}`;\n\tconst encoder = new TextEncoder();\n\tconst data = encoder.encode(dataToHash);\n\tconst hashBuffer = await crypto.subtle.digest('SHA-256', data);\n\tconst hashArray = [...new Uint8Array(hashBuffer)];\n\tconst hashHex = hashArray.map((b) => b.toString(16).padStart(2, '0')).join('');\n\n\treturn hashHex;\n}\n", "import { type Cache, hashQuery, NoopCache } from '~/cache/core/cache.ts';\nimport type { WithCacheConfig } from '~/cache/core/types.ts';\nimport { entityKind, is } from '~/entity.ts';\nimport { DrizzleError, DrizzleQueryError, TransactionRollbackError } from '~/errors.ts';\nimport { QueryPromise } from '~/query-promise.ts';\nimport type { TablesRelationalConfig } from '~/relations.ts';\nimport type { PreparedQuery } from '~/session.ts';\nimport type { Query, SQL } from '~/sql/sql.ts';\nimport type { SQLiteAsyncDialect, SQLiteSyncDialect } from '~/sqlite-core/dialect.ts';\nimport { BaseSQLiteDatabase } from './db.ts';\nimport type { SQLiteRaw } from './query-builders/raw.ts';\nimport type { SelectedFieldsOrdered } from './query-builders/select.types.ts';\n\nexport interface PreparedQueryConfig {\n\ttype: 'sync' | 'async';\n\trun: unknown;\n\tall: unknown;\n\tget: unknown;\n\tvalues: unknown;\n\texecute: unknown;\n}\n\nexport class ExecuteResultSync extends QueryPromise {\n\tstatic override readonly [entityKind]: string = 'ExecuteResultSync';\n\n\tconstructor(private resultCb: () => T) {\n\t\tsuper();\n\t}\n\n\toverride async execute(): Promise {\n\t\treturn this.resultCb();\n\t}\n\n\tsync(): T {\n\t\treturn this.resultCb();\n\t}\n}\n\nexport type ExecuteResult = TType extends 'async' ? Promise\n\t: ExecuteResultSync;\n\nexport abstract class SQLitePreparedQuery implements PreparedQuery {\n\tstatic readonly [entityKind]: string = 'PreparedQuery';\n\n\t/** @internal */\n\tjoinsNotNullableMap?: Record;\n\n\tconstructor(\n\t\tprivate mode: 'sync' | 'async',\n\t\tprivate executeMethod: SQLiteExecuteMethod,\n\t\tprotected query: Query,\n\t\tprivate cache?: Cache,\n\t\t// per query related metadata\n\t\tprivate queryMetadata?: {\n\t\t\ttype: 'select' | 'update' | 'delete' | 'insert';\n\t\t\ttables: string[];\n\t\t} | undefined,\n\t\t// config that was passed through $withCache\n\t\tprivate cacheConfig?: WithCacheConfig,\n\t) {\n\t\t// it means that no $withCache options were passed and it should be just enabled\n\t\tif (cache && cache.strategy() === 'all' && cacheConfig === undefined) {\n\t\t\tthis.cacheConfig = { enable: true, autoInvalidate: true };\n\t\t}\n\t\tif (!this.cacheConfig?.enable) {\n\t\t\tthis.cacheConfig = undefined;\n\t\t}\n\t}\n\n\t/** @internal */\n\tprotected async queryWithCache(\n\t\tqueryString: string,\n\t\tparams: any[],\n\t\tquery: () => Promise,\n\t): Promise {\n\t\tif (this.cache === undefined || is(this.cache, NoopCache) || this.queryMetadata === undefined) {\n\t\t\ttry {\n\t\t\t\treturn await query();\n\t\t\t} catch (e) {\n\t\t\t\tthrow new DrizzleQueryError(queryString, params, e as Error);\n\t\t\t}\n\t\t}\n\n\t\t// don't do any mutations, if globally is false\n\t\tif (this.cacheConfig && !this.cacheConfig.enable) {\n\t\t\ttry {\n\t\t\t\treturn await query();\n\t\t\t} catch (e) {\n\t\t\t\tthrow new DrizzleQueryError(queryString, params, e as Error);\n\t\t\t}\n\t\t}\n\n\t\t// For mutate queries, we should query the database, wait for a response, and then perform invalidation\n\t\tif (\n\t\t\t(\n\t\t\t\tthis.queryMetadata.type === 'insert' || this.queryMetadata.type === 'update'\n\t\t\t\t|| this.queryMetadata.type === 'delete'\n\t\t\t) && this.queryMetadata.tables.length > 0\n\t\t) {\n\t\t\ttry {\n\t\t\t\tconst [res] = await Promise.all([\n\t\t\t\t\tquery(),\n\t\t\t\t\tthis.cache.onMutate({ tables: this.queryMetadata.tables }),\n\t\t\t\t]);\n\t\t\t\treturn res;\n\t\t\t} catch (e) {\n\t\t\t\tthrow new DrizzleQueryError(queryString, params, e as Error);\n\t\t\t}\n\t\t}\n\n\t\t// don't do any reads if globally disabled\n\t\tif (!this.cacheConfig) {\n\t\t\ttry {\n\t\t\t\treturn await query();\n\t\t\t} catch (e) {\n\t\t\t\tthrow new DrizzleQueryError(queryString, params, e as Error);\n\t\t\t}\n\t\t}\n\n\t\tif (this.queryMetadata.type === 'select') {\n\t\t\tconst fromCache = await this.cache.get(\n\t\t\t\tthis.cacheConfig.tag ?? await hashQuery(queryString, params),\n\t\t\t\tthis.queryMetadata.tables,\n\t\t\t\tthis.cacheConfig.tag !== undefined,\n\t\t\t\tthis.cacheConfig.autoInvalidate,\n\t\t\t);\n\t\t\tif (fromCache === undefined) {\n\t\t\t\tlet result;\n\t\t\t\ttry {\n\t\t\t\t\tresult = await query();\n\t\t\t\t} catch (e) {\n\t\t\t\t\tthrow new DrizzleQueryError(queryString, params, e as Error);\n\t\t\t\t}\n\n\t\t\t\t// put actual key\n\t\t\t\tawait this.cache.put(\n\t\t\t\t\tthis.cacheConfig.tag ?? await hashQuery(queryString, params),\n\t\t\t\t\tresult,\n\t\t\t\t\t// make sure we send tables that were used in a query only if user wants to invalidate it on each write\n\t\t\t\t\tthis.cacheConfig.autoInvalidate ? this.queryMetadata.tables : [],\n\t\t\t\t\tthis.cacheConfig.tag !== undefined,\n\t\t\t\t\tthis.cacheConfig.config,\n\t\t\t\t);\n\t\t\t\t// put flag if we should invalidate or not\n\t\t\t\treturn result;\n\t\t\t}\n\n\t\t\treturn fromCache as unknown as T;\n\t\t}\n\t\ttry {\n\t\t\treturn await query();\n\t\t} catch (e) {\n\t\t\tthrow new DrizzleQueryError(queryString, params, e as Error);\n\t\t}\n\t}\n\n\tgetQuery(): Query {\n\t\treturn this.query;\n\t}\n\n\tabstract run(placeholderValues?: Record): Result;\n\n\tmapRunResult(result: unknown, _isFromBatch?: boolean): unknown {\n\t\treturn result;\n\t}\n\n\tabstract all(placeholderValues?: Record): Result;\n\n\tmapAllResult(_result: unknown, _isFromBatch?: boolean): unknown {\n\t\tthrow new Error('Not implemented');\n\t}\n\n\tabstract get(placeholderValues?: Record): Result;\n\n\tmapGetResult(_result: unknown, _isFromBatch?: boolean): unknown {\n\t\tthrow new Error('Not implemented');\n\t}\n\n\tabstract values(placeholderValues?: Record): Result;\n\n\texecute(placeholderValues?: Record): ExecuteResult {\n\t\tif (this.mode === 'async') {\n\t\t\treturn this[this.executeMethod](placeholderValues) as ExecuteResult;\n\t\t}\n\t\treturn new ExecuteResultSync(() => this[this.executeMethod](placeholderValues));\n\t}\n\n\tmapResult(response: unknown, isFromBatch?: boolean) {\n\t\tswitch (this.executeMethod) {\n\t\t\tcase 'run': {\n\t\t\t\treturn this.mapRunResult(response, isFromBatch);\n\t\t\t}\n\t\t\tcase 'all': {\n\t\t\t\treturn this.mapAllResult(response, isFromBatch);\n\t\t\t}\n\t\t\tcase 'get': {\n\t\t\t\treturn this.mapGetResult(response, isFromBatch);\n\t\t\t}\n\t\t}\n\t}\n\n\t/** @internal */\n\tabstract isResponseInArrayMode(): boolean;\n}\n\nexport interface SQLiteTransactionConfig {\n\tbehavior?: 'deferred' | 'immediate' | 'exclusive';\n}\n\nexport type SQLiteExecuteMethod = 'run' | 'all' | 'get';\n\nexport abstract class SQLiteSession<\n\tTResultKind extends 'sync' | 'async',\n\tTRunResult,\n\tTFullSchema extends Record,\n\tTSchema extends TablesRelationalConfig,\n> {\n\tstatic readonly [entityKind]: string = 'SQLiteSession';\n\n\tconstructor(\n\t\t/** @internal */\n\t\treadonly dialect: { sync: SQLiteSyncDialect; async: SQLiteAsyncDialect }[TResultKind],\n\t) {}\n\n\tabstract prepareQuery(\n\t\tquery: Query,\n\t\tfields: SelectedFieldsOrdered | undefined,\n\t\texecuteMethod: SQLiteExecuteMethod,\n\t\tisResponseInArrayMode: boolean,\n\t\tcustomResultMapper?: (rows: unknown[][], mapColumnValue?: (value: unknown) => unknown) => unknown,\n\t\tqueryMetadata?: {\n\t\t\ttype: 'select' | 'update' | 'delete' | 'insert';\n\t\t\ttables: string[];\n\t\t},\n\t\tcacheConfig?: WithCacheConfig,\n\t): SQLitePreparedQuery;\n\n\tprepareOneTimeQuery(\n\t\tquery: Query,\n\t\tfields: SelectedFieldsOrdered | undefined,\n\t\texecuteMethod: SQLiteExecuteMethod,\n\t\tisResponseInArrayMode: boolean,\n\t\tcustomResultMapper?: (rows: unknown[][], mapColumnValue?: (value: unknown) => unknown) => unknown,\n\t\tqueryMetadata?: {\n\t\t\ttype: 'select' | 'update' | 'delete' | 'insert';\n\t\t\ttables: string[];\n\t\t},\n\t\tcacheConfig?: WithCacheConfig,\n\t): SQLitePreparedQuery {\n\t\treturn this.prepareQuery(\n\t\t\tquery,\n\t\t\tfields,\n\t\t\texecuteMethod,\n\t\t\tisResponseInArrayMode,\n\t\t\tcustomResultMapper,\n\t\t\tqueryMetadata,\n\t\t\tcacheConfig,\n\t\t);\n\t}\n\n\tabstract transaction(\n\t\ttransaction: (tx: SQLiteTransaction) => Result,\n\t\tconfig?: SQLiteTransactionConfig,\n\t): Result;\n\n\trun(query: SQL): Result {\n\t\tconst staticQuery = this.dialect.sqlToQuery(query);\n\t\ttry {\n\t\t\treturn this.prepareOneTimeQuery(staticQuery, undefined, 'run', false).run() as Result;\n\t\t} catch (err) {\n\t\t\tthrow new DrizzleError({ cause: err, message: `Failed to run the query '${staticQuery.sql}'` });\n\t\t}\n\t}\n\n\t/** @internal */\n\textractRawRunValueFromBatchResult(result: unknown) {\n\t\treturn result;\n\t}\n\n\tall(query: SQL): Result {\n\t\treturn this.prepareOneTimeQuery(this.dialect.sqlToQuery(query), undefined, 'run', false).all() as Result<\n\t\t\tTResultKind,\n\t\t\tT[]\n\t\t>;\n\t}\n\n\t/** @internal */\n\textractRawAllValueFromBatchResult(_result: unknown): unknown {\n\t\tthrow new Error('Not implemented');\n\t}\n\n\tget(query: SQL): Result {\n\t\treturn this.prepareOneTimeQuery(this.dialect.sqlToQuery(query), undefined, 'run', false).get() as Result<\n\t\t\tTResultKind,\n\t\t\tT\n\t\t>;\n\t}\n\n\t/** @internal */\n\textractRawGetValueFromBatchResult(_result: unknown): unknown {\n\t\tthrow new Error('Not implemented');\n\t}\n\n\tvalues(\n\t\tquery: SQL,\n\t): Result {\n\t\treturn this.prepareOneTimeQuery(this.dialect.sqlToQuery(query), undefined, 'run', false).values() as Result<\n\t\t\tTResultKind,\n\t\t\tT[]\n\t\t>;\n\t}\n\n\tasync count(sql: SQL) {\n\t\tconst result = await this.values(sql) as [[number]];\n\n\t\treturn result[0][0];\n\t}\n\n\t/** @internal */\n\textractRawValuesValueFromBatchResult(_result: unknown): unknown {\n\t\tthrow new Error('Not implemented');\n\t}\n}\n\nexport type Result = { sync: TResult; async: Promise }[TKind];\n\nexport type DBResult = { sync: TResult; async: SQLiteRaw }[TKind];\n\nexport abstract class SQLiteTransaction<\n\tTResultType extends 'sync' | 'async',\n\tTRunResult,\n\tTFullSchema extends Record,\n\tTSchema extends TablesRelationalConfig,\n> extends BaseSQLiteDatabase {\n\tstatic override readonly [entityKind]: string = 'SQLiteTransaction';\n\n\tconstructor(\n\t\tresultType: TResultType,\n\t\tdialect: { sync: SQLiteSyncDialect; async: SQLiteAsyncDialect }[TResultType],\n\t\tsession: SQLiteSession,\n\t\tprotected schema: {\n\t\t\tfullSchema: Record;\n\t\t\tschema: TSchema;\n\t\t\ttableNamesMap: Record;\n\t\t} | undefined,\n\t\tprotected readonly nestedIndex = 0,\n\t) {\n\t\tsuper(resultType, dialect, session, schema);\n\t}\n\n\trollback(): never {\n\t\tthrow new TransactionRollbackError();\n\t}\n}\n", "import { Bot } from 'grammy';\nimport { session } from 'grammy'\nimport type { Env } from '../types/env';\nimport type { BotSession, BotContext } from './types';\nimport { I18nService } from '../services/i18n.service';\nimport { TwitchService } from '../services/twitch.service';\nimport { EventSubService } from '../services/eventsub.service';\nimport { DatabaseSessionStorage } from './storage';\nimport type { IChatRepository, IChannelRepository, IFollowRepository, ISessionRepository } from '../db/repositories/interfaces';\nimport {\n startCommand,\n followCommand,\n followsCommand,\n liveCommand,\n createBroadcastCommand,\n createChangeChannelIdCommand,\n callbackQueryHandler\n} from './commands';\n\nexport function createBot(\n env: Env,\n services: {\n i18n: I18nService;\n twitch: TwitchService;\n eventsub: EventSubService;\n chatRepo: IChatRepository;\n channelRepo: IChannelRepository;\n followRepo: IFollowRepository;\n sessionRepo: ISessionRepository;\n }\n): Bot {\n const bot = new Bot(env.TELEGRAM_TOKEN);\n\n // Use database session storage\n const sessionStorage = new DatabaseSessionStorage(\n services.sessionRepo,\n 86400 // 24 hours TTL\n );\n\n\tbot.use(session({\n\t\tinitial: (): BotSession => ({\n\t\t\tlanguage: 'en',\n\t\t\tfollowsMenu: {\n\t\t\t\tcurrentPage: 1,\n\t\t\t\ttotalPages: 1,\n\t\t\t},\n\t\t}),\n\t\tstorage: sessionStorage,\n\t}))\n\n // Attach environment and services to context\n bot.use(async (ctx, next) => {\n ctx.env = env;\n ctx.services = services;\n await next();\n });\n\n // Use i18n middleware\n bot.use(services.i18n.middleware());\n\n // Register commands\n bot.use(startCommand);\n bot.use(followCommand);\n bot.use(followsCommand);\n bot.use(liveCommand);\n bot.use(createBroadcastCommand(env));\n bot.use(createChangeChannelIdCommand(env));\n bot.use(callbackQueryHandler);\n\n return bot;\n}\n", "import type { StorageAdapter } from 'grammy';\nimport type { ISessionRepository } from '../db/repositories/interfaces';\n\n/**\n * Storage adapter for Grammy sessions using database persistence\n * Works with any ISessionRepository implementation (D1, PostgreSQL, etc.)\n */\nexport class DatabaseSessionStorage implements StorageAdapter {\n constructor(\n private sessionRepo: ISessionRepository,\n private ttl?: number // Time to live in seconds\n ) {}\n\n async read(key: string): Promise {\n const value = await this.sessionRepo.get(key);\n if (!value) return undefined;\n\n try {\n return JSON.parse(value) as T;\n } catch (error) {\n console.error('Failed to parse session data:', error);\n return undefined;\n }\n }\n\n async write(key: string, value: T): Promise {\n const expiresAt = this.ttl ? Date.now() + this.ttl * 1000 : undefined;\n await this.sessionRepo.set(key, JSON.stringify(value), expiresAt);\n }\n\n async delete(key: string): Promise {\n await this.sessionRepo.delete(key);\n }\n\n async has(key: string): Promise {\n const value = await this.sessionRepo.get(key);\n return value !== undefined;\n }\n\n /**\n * Clean up expired sessions\n * Should be called periodically (e.g., via cron job)\n */\n async cleanup(): Promise {\n await this.sessionRepo.cleanup();\n }\n}\n", "export { startCommand } from './start.command';\nexport { followCommand } from './follow.command';\nexport { followsCommand } from './follows.command';\nexport { liveCommand } from './live.command';\nexport { createBroadcastCommand } from './broadcast.command';\nexport { createChangeChannelIdCommand } from './change-channel-id.command';\nexport { callbackQueryHandler } from './callback.handler';\n", "import { Composer } from 'grammy';\nimport type { BotContext } from '../types';\nimport type { SupportedLanguage } from '../../services/i18n.service';\nimport { sendSettingsMenu } from '../helpers';\n\nexport const startCommand = new Composer();\n\nstartCommand.command(['start', 'help', 'info', 'settings'], async (ctx) => {\n const chatId = ctx.chat?.id;\n if (!chatId) return;\n\n // Get or create chat in database\n let chat = await ctx.services.chatRepo.findByChatId(chatId, 'telegram');\n if (!chat) {\n await ctx.services.chatRepo.create(chatId.toString(), 'telegram');\n // Fetch the chat again to get it with settings\n chat = await ctx.services.chatRepo.findByChatId(chatId, 'telegram');\n }\n\n // Update session language\n if (chat?.settings) {\n ctx.session.language = chat.settings.language as SupportedLanguage;\n }\n\n if (chat) {\n await sendSettingsMenu(ctx, chat);\n }\n});\n", "import type { BotContext } from './types';\nimport type { Chat } from '../domain/models';\nimport { InlineKeyboard } from 'grammy';\n\nexport async function sendSettingsMenu(ctx: BotContext, chat: Chat) {\n const settings = chat.settings;\n if (!settings) return;\n\n const createCheckmark = (value: boolean) => value ? '\u2705' : '\u274C';\n\n const keyboard = new InlineKeyboard()\n .text(\n `${createCheckmark(settings.gameChangeNotification)} ${ctx.t('commands.start.game_change_notification_setting.button')}`,\n 'toggle_game_change'\n ).row()\n .text(\n `${createCheckmark(settings.offlineNotification)} ${ctx.t('commands.start.offline_notification.button')}`,\n 'toggle_offline'\n ).row()\n .text(\n `${createCheckmark(settings.titleChangeNotification)} ${ctx.t('commands.start.title_change_notification_setting.button')}`,\n 'toggle_title_change'\n ).row()\n .text(\n `${createCheckmark(settings.gameAndTitleChangeNotification)} ${ctx.t('commands.start.game_and_title_change_notification_setting.button')}`,\n 'toggle_game_and_title'\n ).row()\n .text(\n `${createCheckmark(settings.imageInNotification)} ${ctx.t('commands.start.image_in_notification_setting.button')}`,\n 'toggle_image'\n ).row()\n .text(\n ctx.t('commands.start.language.button'),\n 'language_picker'\n ).row()\n .url('Github', 'https://github.com/Satont/twitch-notifier');\n\n const description = ctx.t('bot.description');\n\n if (ctx.callbackQuery) {\n await ctx.editMessageText(description, { reply_markup: keyboard });\n } else {\n await ctx.reply(description, { reply_markup: keyboard });\n }\n}\n\nexport async function sendLanguagePicker(ctx: BotContext) {\n const keyboard = new InlineKeyboard();\n\n const locales = ctx.services.i18n.getAvailableLocales();\n for (const locale of locales) {\n const emoji = ctx.services.i18n.t(locale, 'language.emoji');\n const name = ctx.services.i18n.t(locale, 'language.name');\n keyboard.text(`${emoji} ${name}`, `language_picker_set_${locale}`).row();\n }\n keyboard.text('\u00AB', 'start_command_menu');\n\n const text = ctx.t('language.select');\n\n if (ctx.callbackQuery) {\n await ctx.editMessageText(text, { reply_markup: keyboard });\n } else {\n await ctx.reply(text, { reply_markup: keyboard });\n }\n}\n\nexport async function buildFollowsKeyboard(ctx: BotContext, chatId: string): Promise {\n const follows = await ctx.services.followRepo.findByChatId(chatId);\n const keyboard = new InlineKeyboard();\n\n for (const follow of follows) {\n const channel = await ctx.services.channelRepo.findById(follow.channelId);\n if (!channel) continue;\n\n const twitchUser = await ctx.services.twitch.getUserById(channel.channelId);\n if (!twitchUser) continue;\n\n keyboard.text(twitchUser.displayName, `channels_unfollow_${channel.channelId}`).row();\n }\n\n // Add pagination buttons if needed\n if (ctx.session.followsMenu) {\n const { currentPage, totalPages } = ctx.session.followsMenu;\n if (totalPages > 1) {\n keyboard.text('\u00AB', 'channels_unfollow_prev_page');\n keyboard.text('\u00BB', 'channels_unfollow_next_page');\n }\n }\n\n return keyboard;\n}\n\nexport async function handleToggleSetting(ctx: BotContext, data: string, chat: Chat) {\n const chatId = ctx.chat?.id;\n if (!chatId || !chat.settings) return;\n\n const updates: any = {};\n\n switch (data) {\n case 'toggle_game_change':\n updates.gameChangeNotification = !chat.settings.gameChangeNotification;\n chat.settings.gameChangeNotification = updates.gameChangeNotification;\n break;\n case 'toggle_offline':\n updates.offlineNotification = !chat.settings.offlineNotification;\n chat.settings.offlineNotification = updates.offlineNotification;\n break;\n case 'toggle_title_change':\n updates.titleChangeNotification = !chat.settings.titleChangeNotification;\n chat.settings.titleChangeNotification = updates.titleChangeNotification;\n break;\n case 'toggle_game_and_title':\n updates.gameAndTitleChangeNotification = !chat.settings.gameAndTitleChangeNotification;\n chat.settings.gameAndTitleChangeNotification = updates.gameAndTitleChangeNotification;\n break;\n case 'toggle_image':\n updates.imageInNotification = !chat.settings.imageInNotification;\n chat.settings.imageInNotification = updates.imageInNotification;\n break;\n }\n\n if (Object.keys(updates).length > 0) {\n await ctx.services.chatRepo.updateSettings(chat.settings.id, updates);\n }\n}\n\nexport async function handleUnfollow(ctx: BotContext, chat: Chat, channelIdFromCallback: string) {\n const channel = await ctx.services.channelRepo.findById(channelIdFromCallback);\n if (!channel) {\n await ctx.answerCallbackQuery('Channel not found');\n return;\n }\n\n const follow = await ctx.services.followRepo.findByChatAndChannel(chat.id, channel.id);\n if (!follow) {\n await ctx.answerCallbackQuery('Already unfollowed');\n return;\n }\n\n const twitchUser = await ctx.services.twitch.getUserById(channel.channelId);\n const streamerName = twitchUser?.displayName || channel.channelId;\n\n await ctx.services.followRepo.delete(follow.id);\n\n // Check if this channel still has followers\n const remainingFollows = await ctx.services.followRepo.findByChannelId(channel.id);\n\n // If no followers remain, unsubscribe from EventSub\n if (remainingFollows.length === 0) {\n try {\n await ctx.services.eventsub.unsubscribeFromChannel(channel.channelId);\n console.log(`Unsubscribed from EventSub for channel ${channel.channelId}`);\n } catch (error) {\n console.error(`Failed to unsubscribe from EventSub for ${channel.channelId}:`, error);\n // Don't fail the unfollow if EventSub unsubscription fails\n }\n }\n\n await ctx.answerCallbackQuery(\n ctx.t('commands.unfollow.success', {\n streamer: streamerName,\n })\n );\n\n // Update keyboard\n const totalFollows = await ctx.services.followRepo.countByChatId(chat.id);\n\n if (totalFollows === 0) {\n await ctx.editMessageText('You are not following any channels.');\n await ctx.editMessageReplyMarkup({ reply_markup: new InlineKeyboard() });\n return;\n }\n\n const keyboard = await buildFollowsKeyboard(ctx, chat.id);\n\n await ctx.editMessageText(\n ctx.t('commands.follows.total', {\n count: totalFollows.toString(),\n }),\n {\n reply_markup: keyboard,\n }\n );\n}\n", "import { Composer } from 'grammy';\nimport type { BotContext } from '../types';\n\nexport const followCommand = new Composer();\n\nfollowCommand.command('follow', async (ctx) => {\n const text = ctx.message?.text?.replace('/follow', '').trim();\n\n if (!text) {\n await ctx.reply(\n ctx.t('commands.follow.enter')\n );\n ctx.session.scene = 'follow';\n return;\n }\n\n await handleFollow(ctx, text);\n});\n\n// Handle follow scene\nfollowCommand.on('message:text', async (ctx, next) => {\n if (ctx.session.scene === 'follow') {\n await handleFollow(ctx, ctx.message.text);\n ctx.session.scene = undefined;\n return;\n }\n await next();\n});\n\nasync function handleFollow(ctx: BotContext, text: string) {\n const chatId = ctx.chat?.id;\n if (!chatId) return;\n\n const chat = await ctx.services.chatRepo.findByChatId(chatId, 'telegram');\n if (!chat) return;\n\n // Extract Twitch username from text or URL\n const twitchLinkRegex = /(?:https?:\\/\\/)?(?:www\\.)?twitch\\.tv\\/(\\w+)/g;\n const matches = Array.from(text.matchAll(twitchLinkRegex));\n\n const usernames = matches.length > 0\n ? matches.map(m => m[1])\n : [text.trim()];\n\n const results: string[] = [];\n\n for (const username of usernames) {\n // Validate username\n if (!/^[a-zA-Z0-9_]{3,25}$/.test(username)) {\n results.push(\n ctx.t(\n 'commands.follow.errors.badUsername',\n { streamer: username }\n )\n );\n continue;\n }\n\n try {\n // Get Twitch user\n const twitchUser = await ctx.services.twitch.getUserByLogin(username);\n\n if (!twitchUser) {\n results.push(\n ctx.t(\n 'commands.follow.errors.streamerNotFound',\n { streamer: username }\n )\n );\n continue;\n }\n\n // Get or create channel\n let channel = await ctx.services.channelRepo.findByChannelId(twitchUser.id, 'twitch');\n if (!channel) {\n channel = await ctx.services.channelRepo.create(twitchUser.id, 'twitch');\n }\n\n // Create follow\n try {\n await ctx.services.followRepo.create(chat.id, channel.id);\n\n // Subscribe to EventSub events for this channel\n // Check if we already have subscriptions for this channel\n const hasSubscriptions = await ctx.services.eventsub.hasActiveSubscriptions(twitchUser.id);\n if (!hasSubscriptions) {\n try {\n await ctx.services.eventsub.subscribeToChannel(twitchUser.id);\n console.log(`Subscribed to EventSub for channel ${twitchUser.id}`);\n } catch (eventSubError) {\n console.error(`Failed to subscribe to EventSub for ${twitchUser.id}:`, eventSubError);\n // Don't fail the follow if EventSub subscription fails\n }\n }\n\n results.push(\n ctx.t(\n 'commands.follow.success',\n { streamer: username }\n )\n );\n } catch (error: any) {\n if (error.message?.includes('UNIQUE constraint failed')) {\n results.push(\n ctx.t(\n 'commands.follow.errors.alreadyFollowed',\n { streamer: username }\n )\n );\n } else {\n throw error;\n }\n }\n } catch (error) {\n console.error('Error following user:', error);\n results.push(`${username} - internal error`);\n }\n }\n\n await ctx.reply(results.join('\\n'));\n}\n", "import { Composer } from 'grammy';\nimport type { BotContext } from '../types';\nimport { buildFollowsKeyboard } from '../helpers';\n\nexport const followsCommand = new Composer();\n\nfollowsCommand.command(['follows', 'unfollow'], async (ctx) => {\n const chatId = ctx.chat?.id;\n if (!chatId) return;\n\n const chat = await ctx.services.chatRepo.findByChatId(chatId, 'telegram');\n if (!chat) return;\n\n ctx.session.followsMenu = {\n currentPage: 1,\n totalPages: 1,\n };\n\n const totalFollows = await ctx.services.followRepo.countByChatId(chat.id);\n\n if (totalFollows === 0) {\n await ctx.reply('You are not following any channels.');\n return;\n }\n\n const keyboard = await buildFollowsKeyboard(ctx, chat.id);\n\n await ctx.reply(\n ctx.t(\n 'commands.follows.total',\n { count: totalFollows.toString() }\n ),\n {\n reply_markup: keyboard,\n }\n );\n});\n", "import { Composer } from 'grammy';\nimport type { BotContext } from '../types';\n\nexport const liveCommand = new Composer();\n\nliveCommand.command('live', async (ctx) => {\n const chatId = ctx.chat?.id;\n if (!chatId) return;\n\n const chat = await ctx.services.chatRepo.findByChatId(chatId, 'telegram');\n if (!chat) return;\n\n const follows = await ctx.services.followRepo.findByChatId(chat.id);\n\n if (follows.length === 0) {\n await ctx.reply('You are not following any channels.');\n return;\n }\n\n // Get all followed channel IDs\n const channelIds: string[] = [];\n for (const follow of follows) {\n const channel = await ctx.services.channelRepo.findById(follow.channelId);\n if (channel) {\n channelIds.push(channel.channelId);\n }\n }\n\n if (channelIds.length === 0) {\n await ctx.reply('No channels found.');\n return;\n }\n\n // Get live streams\n const liveChannels: Array<{\n name: string;\n login: string;\n startedAt: Date;\n title: string;\n category: string;\n viewers: number;\n }> = [];\n\n for (const channelId of channelIds) {\n const stream = await ctx.services.twitch.getStreamByUserId(channelId);\n if (stream) {\n const user = await ctx.services.twitch.getUserById(channelId);\n if (user) {\n liveChannels.push({\n name: user.displayName,\n login: user.name,\n startedAt: stream.startDate,\n title: stream.title,\n category: stream.gameName,\n viewers: stream.viewers,\n });\n }\n }\n }\n\n if (liveChannels.length === 0) {\n await ctx.reply('No one is online.');\n return;\n }\n\n // Build message\n const messages: string[] = [];\n for (const channel of liveChannels) {\n const channelMessage: string[] = [];\n\n channelMessage.push(\n `\uD83D\uDFE2 ${channel.name} - ${channel.viewers} \uD83D\uDC41\uFE0F\uFE0F`\n );\n\n if (channel.category) {\n channelMessage.push(`\uD83C\uDFAE ${channel.category}`);\n }\n\n if (channel.title) {\n channelMessage.push(`\uD83D\uDCDD ${channel.title}`);\n }\n\n // Calculate uptime\n const uptime = Date.now() - channel.startedAt.getTime();\n const hours = Math.floor(uptime / 3600000);\n const minutes = Math.floor((uptime % 3600000) / 60000);\n const seconds = Math.floor((uptime % 60000) / 1000);\n\n let uptimeStr = '\u231B ';\n if (hours > 0) uptimeStr += `${hours}h `;\n if (minutes > 0) uptimeStr += `${minutes}m `;\n if (seconds > 0) uptimeStr += `${seconds}s `;\n\n channelMessage.push(uptimeStr);\n messages.push(channelMessage.join('\\n'));\n }\n\n await ctx.reply(messages.join('\\n\\n'), {\n parse_mode: 'HTML',\n link_preview_options: { is_disabled: true },\n });\n});\n", "import { Composer } from 'grammy';\nimport type { BotContext } from '../types';\nimport type { Env } from '../../types/env';\n\nexport function createBroadcastCommand(env: Env) {\n const broadcast = new Composer();\n\n const isAdmin = (userId: number): boolean => {\n const admins = env.TELEGRAM_BOT_ADMINS.split(',').map(id => parseInt(id.trim()));\n return admins.includes(userId);\n };\n\n broadcast.command('broadcast', async (ctx) => {\n const userId = ctx.from?.id;\n if (!userId || !isAdmin(userId)) {\n return;\n }\n\n const text = ctx.message?.text?.replace('/broadcast', '').trim();\n if (!text) {\n await ctx.reply('Usage: /broadcast ');\n return;\n }\n\n // Get all chats (only positive IDs = private chats/groups)\n const allChats = await ctx.services.chatRepo.findAllByService('telegram');\n\n let sent = 0;\n let failed = 0;\n\n for (const chat of allChats) {\n const chatIdNum = parseInt(chat.chatId);\n if (chatIdNum <= 0) continue; // Skip channels/supergroups\n\n try {\n await ctx.api.sendMessage(chatIdNum, text);\n sent++;\n } catch (error) {\n console.error(`Failed to send to ${chat.chatId}:`, error);\n failed++;\n }\n }\n\n await ctx.reply(`Broadcast completed!\\nSent: ${sent}\\nFailed: ${failed}`);\n });\n\n return broadcast;\n}\n", "import { Composer } from 'grammy';\nimport type { BotContext } from '../types';\nimport type { Env } from '../../types/env';\n\nexport function createChangeChannelIdCommand(env: Env) {\n const changeChannelId = new Composer();\n\n const isAdmin = (userId: number): boolean => {\n const admins = env.TELEGRAM_BOT_ADMINS.split(',').map(id => parseInt(id.trim()));\n return admins.includes(userId);\n };\n\n changeChannelId.command('change_channel_id', async (ctx) => {\n const userId = ctx.from?.id;\n if (!userId || !isAdmin(userId)) {\n return;\n }\n\n const text = ctx.message?.text?.replace('/change_channel_id', '').trim();\n\n if (!text) {\n await ctx.reply('Usage: /change_channel_id ');\n return;\n }\n\n const parts = text.split(' ');\n\n if (parts.length !== 2) {\n await ctx.reply('Usage: /change_channel_id ');\n return;\n }\n\n const [oldId, newId] = parts;\n\n try {\n await ctx.services.channelRepo.updateChannelId(oldId, newId, 'twitch');\n await ctx.reply('Channel ID updated successfully!');\n } catch (error) {\n console.error('Error updating channel ID:', error);\n await ctx.reply('Error updating channel ID.');\n }\n });\n\n return changeChannelId;\n}\n", "import { Composer } from 'grammy';\nimport type { BotContext } from '../types';\nimport type { SupportedLanguage } from '../../services/i18n.service';\nimport {\n sendSettingsMenu,\n sendLanguagePicker,\n handleToggleSetting,\n handleUnfollow,\n buildFollowsKeyboard\n} from '../helpers';\n\nexport const callbackQueryHandler = new Composer();\n\ncallbackQueryHandler.on('callback_query:data', async (ctx) => {\n const data = ctx.callbackQuery.data;\n const chatId = ctx.chat?.id;\n if (!chatId) return;\n\n const chat = await ctx.services.chatRepo.findByChatId(chatId, 'telegram');\n if (!chat || !chat.settings) return;\n\n // Handle toggle settings\n if (data.startsWith('toggle_')) {\n await handleToggleSetting(ctx, data, chat);\n await sendSettingsMenu(ctx, chat);\n }\n\n // Handle language picker\n else if (data === 'language_picker') {\n await sendLanguagePicker(ctx);\n }\n\n // Handle language selection\n else if (data.startsWith('language_picker_set_')) {\n const lang = data.replace('language_picker_set_', '') as SupportedLanguage;\n if (ctx.services.i18n.isValidLocale(lang)) {\n await ctx.services.chatRepo.updateSettings(chat.settings.id, { language: lang });\n ctx.session.language = lang;\n await ctx.answerCallbackQuery(\n ctx.services.i18n.t(lang, 'language.changed')\n );\n await sendLanguagePicker(ctx);\n }\n }\n\n // Handle back to main menu\n else if (data === 'start_command_menu') {\n await sendSettingsMenu(ctx, chat);\n }\n\n // Handle unfollow\n else if (data.startsWith('channels_unfollow_')) {\n const channelId = data.replace('channels_unfollow_', '');\n await handleUnfollow(ctx, chat, channelId);\n }\n\n // Handle pagination\n else if (data === 'channels_unfollow_prev_page') {\n if (ctx.session.followsMenu && ctx.session.followsMenu.currentPage > 1) {\n ctx.session.followsMenu.currentPage--;\n }\n const keyboard = await buildFollowsKeyboard(ctx, chat.id);\n await ctx.editMessageReplyMarkup({ reply_markup: keyboard });\n }\n else if (data === 'channels_unfollow_next_page') {\n if (ctx.session.followsMenu && ctx.session.followsMenu.currentPage < ctx.session.followsMenu.totalPages) {\n ctx.session.followsMenu.currentPage++;\n }\n const keyboard = await buildFollowsKeyboard(ctx, chat.id);\n await ctx.editMessageReplyMarkup({ reply_markup: keyboard });\n }\n\n await ctx.answerCallbackQuery();\n});\n", "import i18next from 'i18next';\nimport type { MiddlewareFn } from 'grammy';\nimport enLocale from '../../locales/en.json';\nimport ruLocale from '../../locales/ru.json';\nimport ukLocale from '../../locales/uk.json';\n\nexport type SupportedLanguage = 'en' | 'ru' | 'uk';\n\nexport class I18nService {\n private i18n: typeof i18next;\n private initialized = false;\n\n constructor() {\n this.i18n = i18next.createInstance();\n }\n\n /**\n * Initialize i18next instance with locales\n * Must be called before using the service\n */\n async init(): Promise {\n if (this.initialized) return;\n\n await this.i18n.init({\n lng: 'en',\n fallbackLng: 'en',\n defaultNS: 'translation',\n ns: ['translation'],\n resources: {\n en: { translation: enLocale },\n ru: { translation: ruLocale },\n uk: { translation: ukLocale },\n },\n interpolation: {\n escapeValue: false, // Not needed for Telegram (no XSS risk)\n },\n });\n\n this.initialized = true;\n }\n\n /**\n * Get translated string\n * @param locale - Language code\n * @param key - Translation key (dot notation)\n * @param params - Template parameters\n */\n t(locale: SupportedLanguage, key: string, params?: Record): string {\n if (!this.initialized) {\n throw new Error('I18nService not initialized. Call init() first.');\n }\n return this.i18n.t(key, { ...params, lng: locale });\n }\n\n /**\n * Get Grammy middleware that attaches t() function to context\n */\n middleware(): MiddlewareFn {\n return async (ctx, next) => {\n const language = ctx.session?.language || 'en';\n \n // Attach t() function to context that uses session language\n ctx.t = (key: string, params?: Record) => {\n return this.t(language, key, params);\n };\n\n await next();\n };\n }\n\n /**\n * Get all available locales\n */\n getAvailableLocales(): SupportedLanguage[] {\n return ['en', 'ru', 'uk'];\n }\n\n /**\n * Check if locale is supported\n */\n isValidLocale(locale: string): locale is SupportedLanguage {\n return ['en', 'ru', 'uk'].includes(locale);\n }\n}\n", "const isString = obj => typeof obj === 'string';\nconst defer = () => {\n let res;\n let rej;\n const promise = new Promise((resolve, reject) => {\n res = resolve;\n rej = reject;\n });\n promise.resolve = res;\n promise.reject = rej;\n return promise;\n};\nconst makeString = object => {\n if (object == null) return '';\n return '' + object;\n};\nconst copy = (a, s, t) => {\n a.forEach(m => {\n if (s[m]) t[m] = s[m];\n });\n};\nconst lastOfPathSeparatorRegExp = /###/g;\nconst cleanKey = key => key && key.indexOf('###') > -1 ? key.replace(lastOfPathSeparatorRegExp, '.') : key;\nconst canNotTraverseDeeper = object => !object || isString(object);\nconst getLastOfPath = (object, path, Empty) => {\n const stack = !isString(path) ? path : path.split('.');\n let stackIndex = 0;\n while (stackIndex < stack.length - 1) {\n if (canNotTraverseDeeper(object)) return {};\n const key = cleanKey(stack[stackIndex]);\n if (!object[key] && Empty) object[key] = new Empty();\n if (Object.prototype.hasOwnProperty.call(object, key)) {\n object = object[key];\n } else {\n object = {};\n }\n ++stackIndex;\n }\n if (canNotTraverseDeeper(object)) return {};\n return {\n obj: object,\n k: cleanKey(stack[stackIndex])\n };\n};\nconst setPath = (object, path, newValue) => {\n const {\n obj,\n k\n } = getLastOfPath(object, path, Object);\n if (obj !== undefined || path.length === 1) {\n obj[k] = newValue;\n return;\n }\n let e = path[path.length - 1];\n let p = path.slice(0, path.length - 1);\n let last = getLastOfPath(object, p, Object);\n while (last.obj === undefined && p.length) {\n e = `${p[p.length - 1]}.${e}`;\n p = p.slice(0, p.length - 1);\n last = getLastOfPath(object, p, Object);\n if (last?.obj && typeof last.obj[`${last.k}.${e}`] !== 'undefined') {\n last.obj = undefined;\n }\n }\n last.obj[`${last.k}.${e}`] = newValue;\n};\nconst pushPath = (object, path, newValue, concat) => {\n const {\n obj,\n k\n } = getLastOfPath(object, path, Object);\n obj[k] = obj[k] || [];\n obj[k].push(newValue);\n};\nconst getPath = (object, path) => {\n const {\n obj,\n k\n } = getLastOfPath(object, path);\n if (!obj) return undefined;\n if (!Object.prototype.hasOwnProperty.call(obj, k)) return undefined;\n return obj[k];\n};\nconst getPathWithDefaults = (data, defaultData, key) => {\n const value = getPath(data, key);\n if (value !== undefined) {\n return value;\n }\n return getPath(defaultData, key);\n};\nconst deepExtend = (target, source, overwrite) => {\n for (const prop in source) {\n if (prop !== '__proto__' && prop !== 'constructor') {\n if (prop in target) {\n if (isString(target[prop]) || target[prop] instanceof String || isString(source[prop]) || source[prop] instanceof String) {\n if (overwrite) target[prop] = source[prop];\n } else {\n deepExtend(target[prop], source[prop], overwrite);\n }\n } else {\n target[prop] = source[prop];\n }\n }\n }\n return target;\n};\nconst regexEscape = str => str.replace(/[\\-\\[\\]\\/\\{\\}\\(\\)\\*\\+\\?\\.\\\\\\^\\$\\|]/g, '\\\\$&');\nvar _entityMap = {\n '&': '&',\n '<': '<',\n '>': '>',\n '\"': '"',\n \"'\": ''',\n '/': '/'\n};\nconst escape = data => {\n if (isString(data)) {\n return data.replace(/[&<>\"'\\/]/g, s => _entityMap[s]);\n }\n return data;\n};\nclass RegExpCache {\n constructor(capacity) {\n this.capacity = capacity;\n this.regExpMap = new Map();\n this.regExpQueue = [];\n }\n getRegExp(pattern) {\n const regExpFromCache = this.regExpMap.get(pattern);\n if (regExpFromCache !== undefined) {\n return regExpFromCache;\n }\n const regExpNew = new RegExp(pattern);\n if (this.regExpQueue.length === this.capacity) {\n this.regExpMap.delete(this.regExpQueue.shift());\n }\n this.regExpMap.set(pattern, regExpNew);\n this.regExpQueue.push(pattern);\n return regExpNew;\n }\n}\nconst chars = [' ', ',', '?', '!', ';'];\nconst looksLikeObjectPathRegExpCache = new RegExpCache(20);\nconst looksLikeObjectPath = (key, nsSeparator, keySeparator) => {\n nsSeparator = nsSeparator || '';\n keySeparator = keySeparator || '';\n const possibleChars = chars.filter(c => nsSeparator.indexOf(c) < 0 && keySeparator.indexOf(c) < 0);\n if (possibleChars.length === 0) return true;\n const r = looksLikeObjectPathRegExpCache.getRegExp(`(${possibleChars.map(c => c === '?' ? '\\\\?' : c).join('|')})`);\n let matched = !r.test(key);\n if (!matched) {\n const ki = key.indexOf(keySeparator);\n if (ki > 0 && !r.test(key.substring(0, ki))) {\n matched = true;\n }\n }\n return matched;\n};\nconst deepFind = (obj, path, keySeparator = '.') => {\n if (!obj) return undefined;\n if (obj[path]) {\n if (!Object.prototype.hasOwnProperty.call(obj, path)) return undefined;\n return obj[path];\n }\n const tokens = path.split(keySeparator);\n let current = obj;\n for (let i = 0; i < tokens.length;) {\n if (!current || typeof current !== 'object') {\n return undefined;\n }\n let next;\n let nextPath = '';\n for (let j = i; j < tokens.length; ++j) {\n if (j !== i) {\n nextPath += keySeparator;\n }\n nextPath += tokens[j];\n next = current[nextPath];\n if (next !== undefined) {\n if (['string', 'number', 'boolean'].indexOf(typeof next) > -1 && j < tokens.length - 1) {\n continue;\n }\n i += j - i + 1;\n break;\n }\n }\n current = next;\n }\n return current;\n};\nconst getCleanedCode = code => code?.replace(/_/g, '-');\n\nconst consoleLogger = {\n type: 'logger',\n log(args) {\n this.output('log', args);\n },\n warn(args) {\n this.output('warn', args);\n },\n error(args) {\n this.output('error', args);\n },\n output(type, args) {\n console?.[type]?.apply?.(console, args);\n }\n};\nclass Logger {\n constructor(concreteLogger, options = {}) {\n this.init(concreteLogger, options);\n }\n init(concreteLogger, options = {}) {\n this.prefix = options.prefix || 'i18next:';\n this.logger = concreteLogger || consoleLogger;\n this.options = options;\n this.debug = options.debug;\n }\n log(...args) {\n return this.forward(args, 'log', '', true);\n }\n warn(...args) {\n return this.forward(args, 'warn', '', true);\n }\n error(...args) {\n return this.forward(args, 'error', '');\n }\n deprecate(...args) {\n return this.forward(args, 'warn', 'WARNING DEPRECATED: ', true);\n }\n forward(args, lvl, prefix, debugOnly) {\n if (debugOnly && !this.debug) return null;\n if (isString(args[0])) args[0] = `${prefix}${this.prefix} ${args[0]}`;\n return this.logger[lvl](args);\n }\n create(moduleName) {\n return new Logger(this.logger, {\n ...{\n prefix: `${this.prefix}:${moduleName}:`\n },\n ...this.options\n });\n }\n clone(options) {\n options = options || this.options;\n options.prefix = options.prefix || this.prefix;\n return new Logger(this.logger, options);\n }\n}\nvar baseLogger = new Logger();\n\nclass EventEmitter {\n constructor() {\n this.observers = {};\n }\n on(events, listener) {\n events.split(' ').forEach(event => {\n if (!this.observers[event]) this.observers[event] = new Map();\n const numListeners = this.observers[event].get(listener) || 0;\n this.observers[event].set(listener, numListeners + 1);\n });\n return this;\n }\n off(event, listener) {\n if (!this.observers[event]) return;\n if (!listener) {\n delete this.observers[event];\n return;\n }\n this.observers[event].delete(listener);\n }\n emit(event, ...args) {\n if (this.observers[event]) {\n const cloned = Array.from(this.observers[event].entries());\n cloned.forEach(([observer, numTimesAdded]) => {\n for (let i = 0; i < numTimesAdded; i++) {\n observer(...args);\n }\n });\n }\n if (this.observers['*']) {\n const cloned = Array.from(this.observers['*'].entries());\n cloned.forEach(([observer, numTimesAdded]) => {\n for (let i = 0; i < numTimesAdded; i++) {\n observer.apply(observer, [event, ...args]);\n }\n });\n }\n }\n}\n\nclass ResourceStore extends EventEmitter {\n constructor(data, options = {\n ns: ['translation'],\n defaultNS: 'translation'\n }) {\n super();\n this.data = data || {};\n this.options = options;\n if (this.options.keySeparator === undefined) {\n this.options.keySeparator = '.';\n }\n if (this.options.ignoreJSONStructure === undefined) {\n this.options.ignoreJSONStructure = true;\n }\n }\n addNamespaces(ns) {\n if (this.options.ns.indexOf(ns) < 0) {\n this.options.ns.push(ns);\n }\n }\n removeNamespaces(ns) {\n const index = this.options.ns.indexOf(ns);\n if (index > -1) {\n this.options.ns.splice(index, 1);\n }\n }\n getResource(lng, ns, key, options = {}) {\n const keySeparator = options.keySeparator !== undefined ? options.keySeparator : this.options.keySeparator;\n const ignoreJSONStructure = options.ignoreJSONStructure !== undefined ? options.ignoreJSONStructure : this.options.ignoreJSONStructure;\n let path;\n if (lng.indexOf('.') > -1) {\n path = lng.split('.');\n } else {\n path = [lng, ns];\n if (key) {\n if (Array.isArray(key)) {\n path.push(...key);\n } else if (isString(key) && keySeparator) {\n path.push(...key.split(keySeparator));\n } else {\n path.push(key);\n }\n }\n }\n const result = getPath(this.data, path);\n if (!result && !ns && !key && lng.indexOf('.') > -1) {\n lng = path[0];\n ns = path[1];\n key = path.slice(2).join('.');\n }\n if (result || !ignoreJSONStructure || !isString(key)) return result;\n return deepFind(this.data?.[lng]?.[ns], key, keySeparator);\n }\n addResource(lng, ns, key, value, options = {\n silent: false\n }) {\n const keySeparator = options.keySeparator !== undefined ? options.keySeparator : this.options.keySeparator;\n let path = [lng, ns];\n if (key) path = path.concat(keySeparator ? key.split(keySeparator) : key);\n if (lng.indexOf('.') > -1) {\n path = lng.split('.');\n value = ns;\n ns = path[1];\n }\n this.addNamespaces(ns);\n setPath(this.data, path, value);\n if (!options.silent) this.emit('added', lng, ns, key, value);\n }\n addResources(lng, ns, resources, options = {\n silent: false\n }) {\n for (const m in resources) {\n if (isString(resources[m]) || Array.isArray(resources[m])) this.addResource(lng, ns, m, resources[m], {\n silent: true\n });\n }\n if (!options.silent) this.emit('added', lng, ns, resources);\n }\n addResourceBundle(lng, ns, resources, deep, overwrite, options = {\n silent: false,\n skipCopy: false\n }) {\n let path = [lng, ns];\n if (lng.indexOf('.') > -1) {\n path = lng.split('.');\n deep = resources;\n resources = ns;\n ns = path[1];\n }\n this.addNamespaces(ns);\n let pack = getPath(this.data, path) || {};\n if (!options.skipCopy) resources = JSON.parse(JSON.stringify(resources));\n if (deep) {\n deepExtend(pack, resources, overwrite);\n } else {\n pack = {\n ...pack,\n ...resources\n };\n }\n setPath(this.data, path, pack);\n if (!options.silent) this.emit('added', lng, ns, resources);\n }\n removeResourceBundle(lng, ns) {\n if (this.hasResourceBundle(lng, ns)) {\n delete this.data[lng][ns];\n }\n this.removeNamespaces(ns);\n this.emit('removed', lng, ns);\n }\n hasResourceBundle(lng, ns) {\n return this.getResource(lng, ns) !== undefined;\n }\n getResourceBundle(lng, ns) {\n if (!ns) ns = this.options.defaultNS;\n return this.getResource(lng, ns);\n }\n getDataByLanguage(lng) {\n return this.data[lng];\n }\n hasLanguageSomeTranslations(lng) {\n const data = this.getDataByLanguage(lng);\n const n = data && Object.keys(data) || [];\n return !!n.find(v => data[v] && Object.keys(data[v]).length > 0);\n }\n toJSON() {\n return this.data;\n }\n}\n\nvar postProcessor = {\n processors: {},\n addPostProcessor(module) {\n this.processors[module.name] = module;\n },\n handle(processors, value, key, options, translator) {\n processors.forEach(processor => {\n value = this.processors[processor]?.process(value, key, options, translator) ?? value;\n });\n return value;\n }\n};\n\nconst PATH_KEY = Symbol('i18next/PATH_KEY');\nfunction createProxy() {\n const state = [];\n const handler = Object.create(null);\n let proxy;\n handler.get = (target, key) => {\n proxy?.revoke?.();\n if (key === PATH_KEY) return state;\n state.push(key);\n proxy = Proxy.revocable(target, handler);\n return proxy.proxy;\n };\n return Proxy.revocable(Object.create(null), handler).proxy;\n}\nfunction keysFromSelector(selector, opts) {\n const {\n [PATH_KEY]: path\n } = selector(createProxy());\n return path.join(opts?.keySeparator ?? '.');\n}\n\nconst checkedLoadedFor = {};\nconst shouldHandleAsObject = res => !isString(res) && typeof res !== 'boolean' && typeof res !== 'number';\nclass Translator extends EventEmitter {\n constructor(services, options = {}) {\n super();\n copy(['resourceStore', 'languageUtils', 'pluralResolver', 'interpolator', 'backendConnector', 'i18nFormat', 'utils'], services, this);\n this.options = options;\n if (this.options.keySeparator === undefined) {\n this.options.keySeparator = '.';\n }\n this.logger = baseLogger.create('translator');\n }\n changeLanguage(lng) {\n if (lng) this.language = lng;\n }\n exists(key, o = {\n interpolation: {}\n }) {\n const opt = {\n ...o\n };\n if (key == null) return false;\n const resolved = this.resolve(key, opt);\n if (resolved?.res === undefined) return false;\n const isObject = shouldHandleAsObject(resolved.res);\n if (opt.returnObjects === false && isObject) {\n return false;\n }\n return true;\n }\n extractFromKey(key, opt) {\n let nsSeparator = opt.nsSeparator !== undefined ? opt.nsSeparator : this.options.nsSeparator;\n if (nsSeparator === undefined) nsSeparator = ':';\n const keySeparator = opt.keySeparator !== undefined ? opt.keySeparator : this.options.keySeparator;\n let namespaces = opt.ns || this.options.defaultNS || [];\n const wouldCheckForNsInKey = nsSeparator && key.indexOf(nsSeparator) > -1;\n const seemsNaturalLanguage = !this.options.userDefinedKeySeparator && !opt.keySeparator && !this.options.userDefinedNsSeparator && !opt.nsSeparator && !looksLikeObjectPath(key, nsSeparator, keySeparator);\n if (wouldCheckForNsInKey && !seemsNaturalLanguage) {\n const m = key.match(this.interpolator.nestingRegexp);\n if (m && m.length > 0) {\n return {\n key,\n namespaces: isString(namespaces) ? [namespaces] : namespaces\n };\n }\n const parts = key.split(nsSeparator);\n if (nsSeparator !== keySeparator || nsSeparator === keySeparator && this.options.ns.indexOf(parts[0]) > -1) namespaces = parts.shift();\n key = parts.join(keySeparator);\n }\n return {\n key,\n namespaces: isString(namespaces) ? [namespaces] : namespaces\n };\n }\n translate(keys, o, lastKey) {\n let opt = typeof o === 'object' ? {\n ...o\n } : o;\n if (typeof opt !== 'object' && this.options.overloadTranslationOptionHandler) {\n opt = this.options.overloadTranslationOptionHandler(arguments);\n }\n if (typeof opt === 'object') opt = {\n ...opt\n };\n if (!opt) opt = {};\n if (keys == null) return '';\n if (typeof keys === 'function') keys = keysFromSelector(keys, {\n ...this.options,\n ...opt\n });\n if (!Array.isArray(keys)) keys = [String(keys)];\n const returnDetails = opt.returnDetails !== undefined ? opt.returnDetails : this.options.returnDetails;\n const keySeparator = opt.keySeparator !== undefined ? opt.keySeparator : this.options.keySeparator;\n const {\n key,\n namespaces\n } = this.extractFromKey(keys[keys.length - 1], opt);\n const namespace = namespaces[namespaces.length - 1];\n let nsSeparator = opt.nsSeparator !== undefined ? opt.nsSeparator : this.options.nsSeparator;\n if (nsSeparator === undefined) nsSeparator = ':';\n const lng = opt.lng || this.language;\n const appendNamespaceToCIMode = opt.appendNamespaceToCIMode || this.options.appendNamespaceToCIMode;\n if (lng?.toLowerCase() === 'cimode') {\n if (appendNamespaceToCIMode) {\n if (returnDetails) {\n return {\n res: `${namespace}${nsSeparator}${key}`,\n usedKey: key,\n exactUsedKey: key,\n usedLng: lng,\n usedNS: namespace,\n usedParams: this.getUsedParamsDetails(opt)\n };\n }\n return `${namespace}${nsSeparator}${key}`;\n }\n if (returnDetails) {\n return {\n res: key,\n usedKey: key,\n exactUsedKey: key,\n usedLng: lng,\n usedNS: namespace,\n usedParams: this.getUsedParamsDetails(opt)\n };\n }\n return key;\n }\n const resolved = this.resolve(keys, opt);\n let res = resolved?.res;\n const resUsedKey = resolved?.usedKey || key;\n const resExactUsedKey = resolved?.exactUsedKey || key;\n const noObject = ['[object Number]', '[object Function]', '[object RegExp]'];\n const joinArrays = opt.joinArrays !== undefined ? opt.joinArrays : this.options.joinArrays;\n const handleAsObjectInI18nFormat = !this.i18nFormat || this.i18nFormat.handleAsObject;\n const needsPluralHandling = opt.count !== undefined && !isString(opt.count);\n const hasDefaultValue = Translator.hasDefaultValue(opt);\n const defaultValueSuffix = needsPluralHandling ? this.pluralResolver.getSuffix(lng, opt.count, opt) : '';\n const defaultValueSuffixOrdinalFallback = opt.ordinal && needsPluralHandling ? this.pluralResolver.getSuffix(lng, opt.count, {\n ordinal: false\n }) : '';\n const needsZeroSuffixLookup = needsPluralHandling && !opt.ordinal && opt.count === 0;\n const defaultValue = needsZeroSuffixLookup && opt[`defaultValue${this.options.pluralSeparator}zero`] || opt[`defaultValue${defaultValueSuffix}`] || opt[`defaultValue${defaultValueSuffixOrdinalFallback}`] || opt.defaultValue;\n let resForObjHndl = res;\n if (handleAsObjectInI18nFormat && !res && hasDefaultValue) {\n resForObjHndl = defaultValue;\n }\n const handleAsObject = shouldHandleAsObject(resForObjHndl);\n const resType = Object.prototype.toString.apply(resForObjHndl);\n if (handleAsObjectInI18nFormat && resForObjHndl && handleAsObject && noObject.indexOf(resType) < 0 && !(isString(joinArrays) && Array.isArray(resForObjHndl))) {\n if (!opt.returnObjects && !this.options.returnObjects) {\n if (!this.options.returnedObjectHandler) {\n this.logger.warn('accessing an object - but returnObjects options is not enabled!');\n }\n const r = this.options.returnedObjectHandler ? this.options.returnedObjectHandler(resUsedKey, resForObjHndl, {\n ...opt,\n ns: namespaces\n }) : `key '${key} (${this.language})' returned an object instead of string.`;\n if (returnDetails) {\n resolved.res = r;\n resolved.usedParams = this.getUsedParamsDetails(opt);\n return resolved;\n }\n return r;\n }\n if (keySeparator) {\n const resTypeIsArray = Array.isArray(resForObjHndl);\n const copy = resTypeIsArray ? [] : {};\n const newKeyToUse = resTypeIsArray ? resExactUsedKey : resUsedKey;\n for (const m in resForObjHndl) {\n if (Object.prototype.hasOwnProperty.call(resForObjHndl, m)) {\n const deepKey = `${newKeyToUse}${keySeparator}${m}`;\n if (hasDefaultValue && !res) {\n copy[m] = this.translate(deepKey, {\n ...opt,\n defaultValue: shouldHandleAsObject(defaultValue) ? defaultValue[m] : undefined,\n ...{\n joinArrays: false,\n ns: namespaces\n }\n });\n } else {\n copy[m] = this.translate(deepKey, {\n ...opt,\n ...{\n joinArrays: false,\n ns: namespaces\n }\n });\n }\n if (copy[m] === deepKey) copy[m] = resForObjHndl[m];\n }\n }\n res = copy;\n }\n } else if (handleAsObjectInI18nFormat && isString(joinArrays) && Array.isArray(res)) {\n res = res.join(joinArrays);\n if (res) res = this.extendTranslation(res, keys, opt, lastKey);\n } else {\n let usedDefault = false;\n let usedKey = false;\n if (!this.isValidLookup(res) && hasDefaultValue) {\n usedDefault = true;\n res = defaultValue;\n }\n if (!this.isValidLookup(res)) {\n usedKey = true;\n res = key;\n }\n const missingKeyNoValueFallbackToKey = opt.missingKeyNoValueFallbackToKey || this.options.missingKeyNoValueFallbackToKey;\n const resForMissing = missingKeyNoValueFallbackToKey && usedKey ? undefined : res;\n const updateMissing = hasDefaultValue && defaultValue !== res && this.options.updateMissing;\n if (usedKey || usedDefault || updateMissing) {\n this.logger.log(updateMissing ? 'updateKey' : 'missingKey', lng, namespace, key, updateMissing ? defaultValue : res);\n if (keySeparator) {\n const fk = this.resolve(key, {\n ...opt,\n keySeparator: false\n });\n if (fk && fk.res) this.logger.warn('Seems the loaded translations were in flat JSON format instead of nested. Either set keySeparator: false on init or make sure your translations are published in nested format.');\n }\n let lngs = [];\n const fallbackLngs = this.languageUtils.getFallbackCodes(this.options.fallbackLng, opt.lng || this.language);\n if (this.options.saveMissingTo === 'fallback' && fallbackLngs && fallbackLngs[0]) {\n for (let i = 0; i < fallbackLngs.length; i++) {\n lngs.push(fallbackLngs[i]);\n }\n } else if (this.options.saveMissingTo === 'all') {\n lngs = this.languageUtils.toResolveHierarchy(opt.lng || this.language);\n } else {\n lngs.push(opt.lng || this.language);\n }\n const send = (l, k, specificDefaultValue) => {\n const defaultForMissing = hasDefaultValue && specificDefaultValue !== res ? specificDefaultValue : resForMissing;\n if (this.options.missingKeyHandler) {\n this.options.missingKeyHandler(l, namespace, k, defaultForMissing, updateMissing, opt);\n } else if (this.backendConnector?.saveMissing) {\n this.backendConnector.saveMissing(l, namespace, k, defaultForMissing, updateMissing, opt);\n }\n this.emit('missingKey', l, namespace, k, res);\n };\n if (this.options.saveMissing) {\n if (this.options.saveMissingPlurals && needsPluralHandling) {\n lngs.forEach(language => {\n const suffixes = this.pluralResolver.getSuffixes(language, opt);\n if (needsZeroSuffixLookup && opt[`defaultValue${this.options.pluralSeparator}zero`] && suffixes.indexOf(`${this.options.pluralSeparator}zero`) < 0) {\n suffixes.push(`${this.options.pluralSeparator}zero`);\n }\n suffixes.forEach(suffix => {\n send([language], key + suffix, opt[`defaultValue${suffix}`] || defaultValue);\n });\n });\n } else {\n send(lngs, key, defaultValue);\n }\n }\n }\n res = this.extendTranslation(res, keys, opt, resolved, lastKey);\n if (usedKey && res === key && this.options.appendNamespaceToMissingKey) {\n res = `${namespace}${nsSeparator}${key}`;\n }\n if ((usedKey || usedDefault) && this.options.parseMissingKeyHandler) {\n res = this.options.parseMissingKeyHandler(this.options.appendNamespaceToMissingKey ? `${namespace}${nsSeparator}${key}` : key, usedDefault ? res : undefined, opt);\n }\n }\n if (returnDetails) {\n resolved.res = res;\n resolved.usedParams = this.getUsedParamsDetails(opt);\n return resolved;\n }\n return res;\n }\n extendTranslation(res, key, opt, resolved, lastKey) {\n if (this.i18nFormat?.parse) {\n res = this.i18nFormat.parse(res, {\n ...this.options.interpolation.defaultVariables,\n ...opt\n }, opt.lng || this.language || resolved.usedLng, resolved.usedNS, resolved.usedKey, {\n resolved\n });\n } else if (!opt.skipInterpolation) {\n if (opt.interpolation) this.interpolator.init({\n ...opt,\n ...{\n interpolation: {\n ...this.options.interpolation,\n ...opt.interpolation\n }\n }\n });\n const skipOnVariables = isString(res) && (opt?.interpolation?.skipOnVariables !== undefined ? opt.interpolation.skipOnVariables : this.options.interpolation.skipOnVariables);\n let nestBef;\n if (skipOnVariables) {\n const nb = res.match(this.interpolator.nestingRegexp);\n nestBef = nb && nb.length;\n }\n let data = opt.replace && !isString(opt.replace) ? opt.replace : opt;\n if (this.options.interpolation.defaultVariables) data = {\n ...this.options.interpolation.defaultVariables,\n ...data\n };\n res = this.interpolator.interpolate(res, data, opt.lng || this.language || resolved.usedLng, opt);\n if (skipOnVariables) {\n const na = res.match(this.interpolator.nestingRegexp);\n const nestAft = na && na.length;\n if (nestBef < nestAft) opt.nest = false;\n }\n if (!opt.lng && resolved && resolved.res) opt.lng = this.language || resolved.usedLng;\n if (opt.nest !== false) res = this.interpolator.nest(res, (...args) => {\n if (lastKey?.[0] === args[0] && !opt.context) {\n this.logger.warn(`It seems you are nesting recursively key: ${args[0]} in key: ${key[0]}`);\n return null;\n }\n return this.translate(...args, key);\n }, opt);\n if (opt.interpolation) this.interpolator.reset();\n }\n const postProcess = opt.postProcess || this.options.postProcess;\n const postProcessorNames = isString(postProcess) ? [postProcess] : postProcess;\n if (res != null && postProcessorNames?.length && opt.applyPostProcessor !== false) {\n res = postProcessor.handle(postProcessorNames, res, key, this.options && this.options.postProcessPassResolved ? {\n i18nResolved: {\n ...resolved,\n usedParams: this.getUsedParamsDetails(opt)\n },\n ...opt\n } : opt, this);\n }\n return res;\n }\n resolve(keys, opt = {}) {\n let found;\n let usedKey;\n let exactUsedKey;\n let usedLng;\n let usedNS;\n if (isString(keys)) keys = [keys];\n keys.forEach(k => {\n if (this.isValidLookup(found)) return;\n const extracted = this.extractFromKey(k, opt);\n const key = extracted.key;\n usedKey = key;\n let namespaces = extracted.namespaces;\n if (this.options.fallbackNS) namespaces = namespaces.concat(this.options.fallbackNS);\n const needsPluralHandling = opt.count !== undefined && !isString(opt.count);\n const needsZeroSuffixLookup = needsPluralHandling && !opt.ordinal && opt.count === 0;\n const needsContextHandling = opt.context !== undefined && (isString(opt.context) || typeof opt.context === 'number') && opt.context !== '';\n const codes = opt.lngs ? opt.lngs : this.languageUtils.toResolveHierarchy(opt.lng || this.language, opt.fallbackLng);\n namespaces.forEach(ns => {\n if (this.isValidLookup(found)) return;\n usedNS = ns;\n if (!checkedLoadedFor[`${codes[0]}-${ns}`] && this.utils?.hasLoadedNamespace && !this.utils?.hasLoadedNamespace(usedNS)) {\n checkedLoadedFor[`${codes[0]}-${ns}`] = true;\n this.logger.warn(`key \"${usedKey}\" for languages \"${codes.join(', ')}\" won't get resolved as namespace \"${usedNS}\" was not yet loaded`, 'This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!');\n }\n codes.forEach(code => {\n if (this.isValidLookup(found)) return;\n usedLng = code;\n const finalKeys = [key];\n if (this.i18nFormat?.addLookupKeys) {\n this.i18nFormat.addLookupKeys(finalKeys, key, code, ns, opt);\n } else {\n let pluralSuffix;\n if (needsPluralHandling) pluralSuffix = this.pluralResolver.getSuffix(code, opt.count, opt);\n const zeroSuffix = `${this.options.pluralSeparator}zero`;\n const ordinalPrefix = `${this.options.pluralSeparator}ordinal${this.options.pluralSeparator}`;\n if (needsPluralHandling) {\n if (opt.ordinal && pluralSuffix.indexOf(ordinalPrefix) === 0) {\n finalKeys.push(key + pluralSuffix.replace(ordinalPrefix, this.options.pluralSeparator));\n }\n finalKeys.push(key + pluralSuffix);\n if (needsZeroSuffixLookup) {\n finalKeys.push(key + zeroSuffix);\n }\n }\n if (needsContextHandling) {\n const contextKey = `${key}${this.options.contextSeparator || '_'}${opt.context}`;\n finalKeys.push(contextKey);\n if (needsPluralHandling) {\n if (opt.ordinal && pluralSuffix.indexOf(ordinalPrefix) === 0) {\n finalKeys.push(contextKey + pluralSuffix.replace(ordinalPrefix, this.options.pluralSeparator));\n }\n finalKeys.push(contextKey + pluralSuffix);\n if (needsZeroSuffixLookup) {\n finalKeys.push(contextKey + zeroSuffix);\n }\n }\n }\n }\n let possibleKey;\n while (possibleKey = finalKeys.pop()) {\n if (!this.isValidLookup(found)) {\n exactUsedKey = possibleKey;\n found = this.getResource(code, ns, possibleKey, opt);\n }\n }\n });\n });\n });\n return {\n res: found,\n usedKey,\n exactUsedKey,\n usedLng,\n usedNS\n };\n }\n isValidLookup(res) {\n return res !== undefined && !(!this.options.returnNull && res === null) && !(!this.options.returnEmptyString && res === '');\n }\n getResource(code, ns, key, options = {}) {\n if (this.i18nFormat?.getResource) return this.i18nFormat.getResource(code, ns, key, options);\n return this.resourceStore.getResource(code, ns, key, options);\n }\n getUsedParamsDetails(options = {}) {\n const optionsKeys = ['defaultValue', 'ordinal', 'context', 'replace', 'lng', 'lngs', 'fallbackLng', 'ns', 'keySeparator', 'nsSeparator', 'returnObjects', 'returnDetails', 'joinArrays', 'postProcess', 'interpolation'];\n const useOptionsReplaceForData = options.replace && !isString(options.replace);\n let data = useOptionsReplaceForData ? options.replace : options;\n if (useOptionsReplaceForData && typeof options.count !== 'undefined') {\n data.count = options.count;\n }\n if (this.options.interpolation.defaultVariables) {\n data = {\n ...this.options.interpolation.defaultVariables,\n ...data\n };\n }\n if (!useOptionsReplaceForData) {\n data = {\n ...data\n };\n for (const key of optionsKeys) {\n delete data[key];\n }\n }\n return data;\n }\n static hasDefaultValue(options) {\n const prefix = 'defaultValue';\n for (const option in options) {\n if (Object.prototype.hasOwnProperty.call(options, option) && prefix === option.substring(0, prefix.length) && undefined !== options[option]) {\n return true;\n }\n }\n return false;\n }\n}\n\nclass LanguageUtil {\n constructor(options) {\n this.options = options;\n this.supportedLngs = this.options.supportedLngs || false;\n this.logger = baseLogger.create('languageUtils');\n }\n getScriptPartFromCode(code) {\n code = getCleanedCode(code);\n if (!code || code.indexOf('-') < 0) return null;\n const p = code.split('-');\n if (p.length === 2) return null;\n p.pop();\n if (p[p.length - 1].toLowerCase() === 'x') return null;\n return this.formatLanguageCode(p.join('-'));\n }\n getLanguagePartFromCode(code) {\n code = getCleanedCode(code);\n if (!code || code.indexOf('-') < 0) return code;\n const p = code.split('-');\n return this.formatLanguageCode(p[0]);\n }\n formatLanguageCode(code) {\n if (isString(code) && code.indexOf('-') > -1) {\n let formattedCode;\n try {\n formattedCode = Intl.getCanonicalLocales(code)[0];\n } catch (e) {}\n if (formattedCode && this.options.lowerCaseLng) {\n formattedCode = formattedCode.toLowerCase();\n }\n if (formattedCode) return formattedCode;\n if (this.options.lowerCaseLng) {\n return code.toLowerCase();\n }\n return code;\n }\n return this.options.cleanCode || this.options.lowerCaseLng ? code.toLowerCase() : code;\n }\n isSupportedCode(code) {\n if (this.options.load === 'languageOnly' || this.options.nonExplicitSupportedLngs) {\n code = this.getLanguagePartFromCode(code);\n }\n return !this.supportedLngs || !this.supportedLngs.length || this.supportedLngs.indexOf(code) > -1;\n }\n getBestMatchFromCodes(codes) {\n if (!codes) return null;\n let found;\n codes.forEach(code => {\n if (found) return;\n const cleanedLng = this.formatLanguageCode(code);\n if (!this.options.supportedLngs || this.isSupportedCode(cleanedLng)) found = cleanedLng;\n });\n if (!found && this.options.supportedLngs) {\n codes.forEach(code => {\n if (found) return;\n const lngScOnly = this.getScriptPartFromCode(code);\n if (this.isSupportedCode(lngScOnly)) return found = lngScOnly;\n const lngOnly = this.getLanguagePartFromCode(code);\n if (this.isSupportedCode(lngOnly)) return found = lngOnly;\n found = this.options.supportedLngs.find(supportedLng => {\n if (supportedLng === lngOnly) return supportedLng;\n if (supportedLng.indexOf('-') < 0 && lngOnly.indexOf('-') < 0) return;\n if (supportedLng.indexOf('-') > 0 && lngOnly.indexOf('-') < 0 && supportedLng.substring(0, supportedLng.indexOf('-')) === lngOnly) return supportedLng;\n if (supportedLng.indexOf(lngOnly) === 0 && lngOnly.length > 1) return supportedLng;\n });\n });\n }\n if (!found) found = this.getFallbackCodes(this.options.fallbackLng)[0];\n return found;\n }\n getFallbackCodes(fallbacks, code) {\n if (!fallbacks) return [];\n if (typeof fallbacks === 'function') fallbacks = fallbacks(code);\n if (isString(fallbacks)) fallbacks = [fallbacks];\n if (Array.isArray(fallbacks)) return fallbacks;\n if (!code) return fallbacks.default || [];\n let found = fallbacks[code];\n if (!found) found = fallbacks[this.getScriptPartFromCode(code)];\n if (!found) found = fallbacks[this.formatLanguageCode(code)];\n if (!found) found = fallbacks[this.getLanguagePartFromCode(code)];\n if (!found) found = fallbacks.default;\n return found || [];\n }\n toResolveHierarchy(code, fallbackCode) {\n const fallbackCodes = this.getFallbackCodes((fallbackCode === false ? [] : fallbackCode) || this.options.fallbackLng || [], code);\n const codes = [];\n const addCode = c => {\n if (!c) return;\n if (this.isSupportedCode(c)) {\n codes.push(c);\n } else {\n this.logger.warn(`rejecting language code not found in supportedLngs: ${c}`);\n }\n };\n if (isString(code) && (code.indexOf('-') > -1 || code.indexOf('_') > -1)) {\n if (this.options.load !== 'languageOnly') addCode(this.formatLanguageCode(code));\n if (this.options.load !== 'languageOnly' && this.options.load !== 'currentOnly') addCode(this.getScriptPartFromCode(code));\n if (this.options.load !== 'currentOnly') addCode(this.getLanguagePartFromCode(code));\n } else if (isString(code)) {\n addCode(this.formatLanguageCode(code));\n }\n fallbackCodes.forEach(fc => {\n if (codes.indexOf(fc) < 0) addCode(this.formatLanguageCode(fc));\n });\n return codes;\n }\n}\n\nconst suffixesOrder = {\n zero: 0,\n one: 1,\n two: 2,\n few: 3,\n many: 4,\n other: 5\n};\nconst dummyRule = {\n select: count => count === 1 ? 'one' : 'other',\n resolvedOptions: () => ({\n pluralCategories: ['one', 'other']\n })\n};\nclass PluralResolver {\n constructor(languageUtils, options = {}) {\n this.languageUtils = languageUtils;\n this.options = options;\n this.logger = baseLogger.create('pluralResolver');\n this.pluralRulesCache = {};\n }\n clearCache() {\n this.pluralRulesCache = {};\n }\n getRule(code, options = {}) {\n const cleanedCode = getCleanedCode(code === 'dev' ? 'en' : code);\n const type = options.ordinal ? 'ordinal' : 'cardinal';\n const cacheKey = JSON.stringify({\n cleanedCode,\n type\n });\n if (cacheKey in this.pluralRulesCache) {\n return this.pluralRulesCache[cacheKey];\n }\n let rule;\n try {\n rule = new Intl.PluralRules(cleanedCode, {\n type\n });\n } catch (err) {\n if (typeof Intl === 'undefined') {\n this.logger.error('No Intl support, please use an Intl polyfill!');\n return dummyRule;\n }\n if (!code.match(/-|_/)) return dummyRule;\n const lngPart = this.languageUtils.getLanguagePartFromCode(code);\n rule = this.getRule(lngPart, options);\n }\n this.pluralRulesCache[cacheKey] = rule;\n return rule;\n }\n needsPlural(code, options = {}) {\n let rule = this.getRule(code, options);\n if (!rule) rule = this.getRule('dev', options);\n return rule?.resolvedOptions().pluralCategories.length > 1;\n }\n getPluralFormsOfKey(code, key, options = {}) {\n return this.getSuffixes(code, options).map(suffix => `${key}${suffix}`);\n }\n getSuffixes(code, options = {}) {\n let rule = this.getRule(code, options);\n if (!rule) rule = this.getRule('dev', options);\n if (!rule) return [];\n return rule.resolvedOptions().pluralCategories.sort((pluralCategory1, pluralCategory2) => suffixesOrder[pluralCategory1] - suffixesOrder[pluralCategory2]).map(pluralCategory => `${this.options.prepend}${options.ordinal ? `ordinal${this.options.prepend}` : ''}${pluralCategory}`);\n }\n getSuffix(code, count, options = {}) {\n const rule = this.getRule(code, options);\n if (rule) {\n return `${this.options.prepend}${options.ordinal ? `ordinal${this.options.prepend}` : ''}${rule.select(count)}`;\n }\n this.logger.warn(`no plural rule found for: ${code}`);\n return this.getSuffix('dev', count, options);\n }\n}\n\nconst deepFindWithDefaults = (data, defaultData, key, keySeparator = '.', ignoreJSONStructure = true) => {\n let path = getPathWithDefaults(data, defaultData, key);\n if (!path && ignoreJSONStructure && isString(key)) {\n path = deepFind(data, key, keySeparator);\n if (path === undefined) path = deepFind(defaultData, key, keySeparator);\n }\n return path;\n};\nconst regexSafe = val => val.replace(/\\$/g, '$$$$');\nclass Interpolator {\n constructor(options = {}) {\n this.logger = baseLogger.create('interpolator');\n this.options = options;\n this.format = options?.interpolation?.format || (value => value);\n this.init(options);\n }\n init(options = {}) {\n if (!options.interpolation) options.interpolation = {\n escapeValue: true\n };\n const {\n escape: escape$1,\n escapeValue,\n useRawValueToEscape,\n prefix,\n prefixEscaped,\n suffix,\n suffixEscaped,\n formatSeparator,\n unescapeSuffix,\n unescapePrefix,\n nestingPrefix,\n nestingPrefixEscaped,\n nestingSuffix,\n nestingSuffixEscaped,\n nestingOptionsSeparator,\n maxReplaces,\n alwaysFormat\n } = options.interpolation;\n this.escape = escape$1 !== undefined ? escape$1 : escape;\n this.escapeValue = escapeValue !== undefined ? escapeValue : true;\n this.useRawValueToEscape = useRawValueToEscape !== undefined ? useRawValueToEscape : false;\n this.prefix = prefix ? regexEscape(prefix) : prefixEscaped || '{{';\n this.suffix = suffix ? regexEscape(suffix) : suffixEscaped || '}}';\n this.formatSeparator = formatSeparator || ',';\n this.unescapePrefix = unescapeSuffix ? '' : unescapePrefix || '-';\n this.unescapeSuffix = this.unescapePrefix ? '' : unescapeSuffix || '';\n this.nestingPrefix = nestingPrefix ? regexEscape(nestingPrefix) : nestingPrefixEscaped || regexEscape('$t(');\n this.nestingSuffix = nestingSuffix ? regexEscape(nestingSuffix) : nestingSuffixEscaped || regexEscape(')');\n this.nestingOptionsSeparator = nestingOptionsSeparator || ',';\n this.maxReplaces = maxReplaces || 1000;\n this.alwaysFormat = alwaysFormat !== undefined ? alwaysFormat : false;\n this.resetRegExp();\n }\n reset() {\n if (this.options) this.init(this.options);\n }\n resetRegExp() {\n const getOrResetRegExp = (existingRegExp, pattern) => {\n if (existingRegExp?.source === pattern) {\n existingRegExp.lastIndex = 0;\n return existingRegExp;\n }\n return new RegExp(pattern, 'g');\n };\n this.regexp = getOrResetRegExp(this.regexp, `${this.prefix}(.+?)${this.suffix}`);\n this.regexpUnescape = getOrResetRegExp(this.regexpUnescape, `${this.prefix}${this.unescapePrefix}(.+?)${this.unescapeSuffix}${this.suffix}`);\n this.nestingRegexp = getOrResetRegExp(this.nestingRegexp, `${this.nestingPrefix}((?:[^()\"']+|\"[^\"]*\"|'[^']*'|\\\\((?:[^()]|\"[^\"]*\"|'[^']*')*\\\\))*?)${this.nestingSuffix}`);\n }\n interpolate(str, data, lng, options) {\n let match;\n let value;\n let replaces;\n const defaultData = this.options && this.options.interpolation && this.options.interpolation.defaultVariables || {};\n const handleFormat = key => {\n if (key.indexOf(this.formatSeparator) < 0) {\n const path = deepFindWithDefaults(data, defaultData, key, this.options.keySeparator, this.options.ignoreJSONStructure);\n return this.alwaysFormat ? this.format(path, undefined, lng, {\n ...options,\n ...data,\n interpolationkey: key\n }) : path;\n }\n const p = key.split(this.formatSeparator);\n const k = p.shift().trim();\n const f = p.join(this.formatSeparator).trim();\n return this.format(deepFindWithDefaults(data, defaultData, k, this.options.keySeparator, this.options.ignoreJSONStructure), f, lng, {\n ...options,\n ...data,\n interpolationkey: k\n });\n };\n this.resetRegExp();\n const missingInterpolationHandler = options?.missingInterpolationHandler || this.options.missingInterpolationHandler;\n const skipOnVariables = options?.interpolation?.skipOnVariables !== undefined ? options.interpolation.skipOnVariables : this.options.interpolation.skipOnVariables;\n const todos = [{\n regex: this.regexpUnescape,\n safeValue: val => regexSafe(val)\n }, {\n regex: this.regexp,\n safeValue: val => this.escapeValue ? regexSafe(this.escape(val)) : regexSafe(val)\n }];\n todos.forEach(todo => {\n replaces = 0;\n while (match = todo.regex.exec(str)) {\n const matchedVar = match[1].trim();\n value = handleFormat(matchedVar);\n if (value === undefined) {\n if (typeof missingInterpolationHandler === 'function') {\n const temp = missingInterpolationHandler(str, match, options);\n value = isString(temp) ? temp : '';\n } else if (options && Object.prototype.hasOwnProperty.call(options, matchedVar)) {\n value = '';\n } else if (skipOnVariables) {\n value = match[0];\n continue;\n } else {\n this.logger.warn(`missed to pass in variable ${matchedVar} for interpolating ${str}`);\n value = '';\n }\n } else if (!isString(value) && !this.useRawValueToEscape) {\n value = makeString(value);\n }\n const safeValue = todo.safeValue(value);\n str = str.replace(match[0], safeValue);\n if (skipOnVariables) {\n todo.regex.lastIndex += value.length;\n todo.regex.lastIndex -= match[0].length;\n } else {\n todo.regex.lastIndex = 0;\n }\n replaces++;\n if (replaces >= this.maxReplaces) {\n break;\n }\n }\n });\n return str;\n }\n nest(str, fc, options = {}) {\n let match;\n let value;\n let clonedOptions;\n const handleHasOptions = (key, inheritedOptions) => {\n const sep = this.nestingOptionsSeparator;\n if (key.indexOf(sep) < 0) return key;\n const c = key.split(new RegExp(`${regexEscape(sep)}[ ]*{`));\n let optionsString = `{${c[1]}`;\n key = c[0];\n optionsString = this.interpolate(optionsString, clonedOptions);\n const matchedSingleQuotes = optionsString.match(/'/g);\n const matchedDoubleQuotes = optionsString.match(/\"/g);\n if ((matchedSingleQuotes?.length ?? 0) % 2 === 0 && !matchedDoubleQuotes || (matchedDoubleQuotes?.length ?? 0) % 2 !== 0) {\n optionsString = optionsString.replace(/'/g, '\"');\n }\n try {\n clonedOptions = JSON.parse(optionsString);\n if (inheritedOptions) clonedOptions = {\n ...inheritedOptions,\n ...clonedOptions\n };\n } catch (e) {\n this.logger.warn(`failed parsing options string in nesting for key ${key}`, e);\n return `${key}${sep}${optionsString}`;\n }\n if (clonedOptions.defaultValue && clonedOptions.defaultValue.indexOf(this.prefix) > -1) delete clonedOptions.defaultValue;\n return key;\n };\n while (match = this.nestingRegexp.exec(str)) {\n let formatters = [];\n clonedOptions = {\n ...options\n };\n clonedOptions = clonedOptions.replace && !isString(clonedOptions.replace) ? clonedOptions.replace : clonedOptions;\n clonedOptions.applyPostProcessor = false;\n delete clonedOptions.defaultValue;\n const keyEndIndex = /{.*}/.test(match[1]) ? match[1].lastIndexOf('}') + 1 : match[1].indexOf(this.formatSeparator);\n if (keyEndIndex !== -1) {\n formatters = match[1].slice(keyEndIndex).split(this.formatSeparator).map(elem => elem.trim()).filter(Boolean);\n match[1] = match[1].slice(0, keyEndIndex);\n }\n value = fc(handleHasOptions.call(this, match[1].trim(), clonedOptions), clonedOptions);\n if (value && match[0] === str && !isString(value)) return value;\n if (!isString(value)) value = makeString(value);\n if (!value) {\n this.logger.warn(`missed to resolve ${match[1]} for nesting ${str}`);\n value = '';\n }\n if (formatters.length) {\n value = formatters.reduce((v, f) => this.format(v, f, options.lng, {\n ...options,\n interpolationkey: match[1].trim()\n }), value.trim());\n }\n str = str.replace(match[0], value);\n this.regexp.lastIndex = 0;\n }\n return str;\n }\n}\n\nconst parseFormatStr = formatStr => {\n let formatName = formatStr.toLowerCase().trim();\n const formatOptions = {};\n if (formatStr.indexOf('(') > -1) {\n const p = formatStr.split('(');\n formatName = p[0].toLowerCase().trim();\n const optStr = p[1].substring(0, p[1].length - 1);\n if (formatName === 'currency' && optStr.indexOf(':') < 0) {\n if (!formatOptions.currency) formatOptions.currency = optStr.trim();\n } else if (formatName === 'relativetime' && optStr.indexOf(':') < 0) {\n if (!formatOptions.range) formatOptions.range = optStr.trim();\n } else {\n const opts = optStr.split(';');\n opts.forEach(opt => {\n if (opt) {\n const [key, ...rest] = opt.split(':');\n const val = rest.join(':').trim().replace(/^'+|'+$/g, '');\n const trimmedKey = key.trim();\n if (!formatOptions[trimmedKey]) formatOptions[trimmedKey] = val;\n if (val === 'false') formatOptions[trimmedKey] = false;\n if (val === 'true') formatOptions[trimmedKey] = true;\n if (!isNaN(val)) formatOptions[trimmedKey] = parseInt(val, 10);\n }\n });\n }\n }\n return {\n formatName,\n formatOptions\n };\n};\nconst createCachedFormatter = fn => {\n const cache = {};\n return (v, l, o) => {\n let optForCache = o;\n if (o && o.interpolationkey && o.formatParams && o.formatParams[o.interpolationkey] && o[o.interpolationkey]) {\n optForCache = {\n ...optForCache,\n [o.interpolationkey]: undefined\n };\n }\n const key = l + JSON.stringify(optForCache);\n let frm = cache[key];\n if (!frm) {\n frm = fn(getCleanedCode(l), o);\n cache[key] = frm;\n }\n return frm(v);\n };\n};\nconst createNonCachedFormatter = fn => (v, l, o) => fn(getCleanedCode(l), o)(v);\nclass Formatter {\n constructor(options = {}) {\n this.logger = baseLogger.create('formatter');\n this.options = options;\n this.init(options);\n }\n init(services, options = {\n interpolation: {}\n }) {\n this.formatSeparator = options.interpolation.formatSeparator || ',';\n const cf = options.cacheInBuiltFormats ? createCachedFormatter : createNonCachedFormatter;\n this.formats = {\n number: cf((lng, opt) => {\n const formatter = new Intl.NumberFormat(lng, {\n ...opt\n });\n return val => formatter.format(val);\n }),\n currency: cf((lng, opt) => {\n const formatter = new Intl.NumberFormat(lng, {\n ...opt,\n style: 'currency'\n });\n return val => formatter.format(val);\n }),\n datetime: cf((lng, opt) => {\n const formatter = new Intl.DateTimeFormat(lng, {\n ...opt\n });\n return val => formatter.format(val);\n }),\n relativetime: cf((lng, opt) => {\n const formatter = new Intl.RelativeTimeFormat(lng, {\n ...opt\n });\n return val => formatter.format(val, opt.range || 'day');\n }),\n list: cf((lng, opt) => {\n const formatter = new Intl.ListFormat(lng, {\n ...opt\n });\n return val => formatter.format(val);\n })\n };\n }\n add(name, fc) {\n this.formats[name.toLowerCase().trim()] = fc;\n }\n addCached(name, fc) {\n this.formats[name.toLowerCase().trim()] = createCachedFormatter(fc);\n }\n format(value, format, lng, options = {}) {\n const formats = format.split(this.formatSeparator);\n if (formats.length > 1 && formats[0].indexOf('(') > 1 && formats[0].indexOf(')') < 0 && formats.find(f => f.indexOf(')') > -1)) {\n const lastIndex = formats.findIndex(f => f.indexOf(')') > -1);\n formats[0] = [formats[0], ...formats.splice(1, lastIndex)].join(this.formatSeparator);\n }\n const result = formats.reduce((mem, f) => {\n const {\n formatName,\n formatOptions\n } = parseFormatStr(f);\n if (this.formats[formatName]) {\n let formatted = mem;\n try {\n const valOptions = options?.formatParams?.[options.interpolationkey] || {};\n const l = valOptions.locale || valOptions.lng || options.locale || options.lng || lng;\n formatted = this.formats[formatName](mem, l, {\n ...formatOptions,\n ...options,\n ...valOptions\n });\n } catch (error) {\n this.logger.warn(error);\n }\n return formatted;\n } else {\n this.logger.warn(`there was no format function for ${formatName}`);\n }\n return mem;\n }, value);\n return result;\n }\n}\n\nconst removePending = (q, name) => {\n if (q.pending[name] !== undefined) {\n delete q.pending[name];\n q.pendingCount--;\n }\n};\nclass Connector extends EventEmitter {\n constructor(backend, store, services, options = {}) {\n super();\n this.backend = backend;\n this.store = store;\n this.services = services;\n this.languageUtils = services.languageUtils;\n this.options = options;\n this.logger = baseLogger.create('backendConnector');\n this.waitingReads = [];\n this.maxParallelReads = options.maxParallelReads || 10;\n this.readingCalls = 0;\n this.maxRetries = options.maxRetries >= 0 ? options.maxRetries : 5;\n this.retryTimeout = options.retryTimeout >= 1 ? options.retryTimeout : 350;\n this.state = {};\n this.queue = [];\n this.backend?.init?.(services, options.backend, options);\n }\n queueLoad(languages, namespaces, options, callback) {\n const toLoad = {};\n const pending = {};\n const toLoadLanguages = {};\n const toLoadNamespaces = {};\n languages.forEach(lng => {\n let hasAllNamespaces = true;\n namespaces.forEach(ns => {\n const name = `${lng}|${ns}`;\n if (!options.reload && this.store.hasResourceBundle(lng, ns)) {\n this.state[name] = 2;\n } else if (this.state[name] < 0) ; else if (this.state[name] === 1) {\n if (pending[name] === undefined) pending[name] = true;\n } else {\n this.state[name] = 1;\n hasAllNamespaces = false;\n if (pending[name] === undefined) pending[name] = true;\n if (toLoad[name] === undefined) toLoad[name] = true;\n if (toLoadNamespaces[ns] === undefined) toLoadNamespaces[ns] = true;\n }\n });\n if (!hasAllNamespaces) toLoadLanguages[lng] = true;\n });\n if (Object.keys(toLoad).length || Object.keys(pending).length) {\n this.queue.push({\n pending,\n pendingCount: Object.keys(pending).length,\n loaded: {},\n errors: [],\n callback\n });\n }\n return {\n toLoad: Object.keys(toLoad),\n pending: Object.keys(pending),\n toLoadLanguages: Object.keys(toLoadLanguages),\n toLoadNamespaces: Object.keys(toLoadNamespaces)\n };\n }\n loaded(name, err, data) {\n const s = name.split('|');\n const lng = s[0];\n const ns = s[1];\n if (err) this.emit('failedLoading', lng, ns, err);\n if (!err && data) {\n this.store.addResourceBundle(lng, ns, data, undefined, undefined, {\n skipCopy: true\n });\n }\n this.state[name] = err ? -1 : 2;\n if (err && data) this.state[name] = 0;\n const loaded = {};\n this.queue.forEach(q => {\n pushPath(q.loaded, [lng], ns);\n removePending(q, name);\n if (err) q.errors.push(err);\n if (q.pendingCount === 0 && !q.done) {\n Object.keys(q.loaded).forEach(l => {\n if (!loaded[l]) loaded[l] = {};\n const loadedKeys = q.loaded[l];\n if (loadedKeys.length) {\n loadedKeys.forEach(n => {\n if (loaded[l][n] === undefined) loaded[l][n] = true;\n });\n }\n });\n q.done = true;\n if (q.errors.length) {\n q.callback(q.errors);\n } else {\n q.callback();\n }\n }\n });\n this.emit('loaded', loaded);\n this.queue = this.queue.filter(q => !q.done);\n }\n read(lng, ns, fcName, tried = 0, wait = this.retryTimeout, callback) {\n if (!lng.length) return callback(null, {});\n if (this.readingCalls >= this.maxParallelReads) {\n this.waitingReads.push({\n lng,\n ns,\n fcName,\n tried,\n wait,\n callback\n });\n return;\n }\n this.readingCalls++;\n const resolver = (err, data) => {\n this.readingCalls--;\n if (this.waitingReads.length > 0) {\n const next = this.waitingReads.shift();\n this.read(next.lng, next.ns, next.fcName, next.tried, next.wait, next.callback);\n }\n if (err && data && tried < this.maxRetries) {\n setTimeout(() => {\n this.read.call(this, lng, ns, fcName, tried + 1, wait * 2, callback);\n }, wait);\n return;\n }\n callback(err, data);\n };\n const fc = this.backend[fcName].bind(this.backend);\n if (fc.length === 2) {\n try {\n const r = fc(lng, ns);\n if (r && typeof r.then === 'function') {\n r.then(data => resolver(null, data)).catch(resolver);\n } else {\n resolver(null, r);\n }\n } catch (err) {\n resolver(err);\n }\n return;\n }\n return fc(lng, ns, resolver);\n }\n prepareLoading(languages, namespaces, options = {}, callback) {\n if (!this.backend) {\n this.logger.warn('No backend was added via i18next.use. Will not load resources.');\n return callback && callback();\n }\n if (isString(languages)) languages = this.languageUtils.toResolveHierarchy(languages);\n if (isString(namespaces)) namespaces = [namespaces];\n const toLoad = this.queueLoad(languages, namespaces, options, callback);\n if (!toLoad.toLoad.length) {\n if (!toLoad.pending.length) callback();\n return null;\n }\n toLoad.toLoad.forEach(name => {\n this.loadOne(name);\n });\n }\n load(languages, namespaces, callback) {\n this.prepareLoading(languages, namespaces, {}, callback);\n }\n reload(languages, namespaces, callback) {\n this.prepareLoading(languages, namespaces, {\n reload: true\n }, callback);\n }\n loadOne(name, prefix = '') {\n const s = name.split('|');\n const lng = s[0];\n const ns = s[1];\n this.read(lng, ns, 'read', undefined, undefined, (err, data) => {\n if (err) this.logger.warn(`${prefix}loading namespace ${ns} for language ${lng} failed`, err);\n if (!err && data) this.logger.log(`${prefix}loaded namespace ${ns} for language ${lng}`, data);\n this.loaded(name, err, data);\n });\n }\n saveMissing(languages, namespace, key, fallbackValue, isUpdate, options = {}, clb = () => {}) {\n if (this.services?.utils?.hasLoadedNamespace && !this.services?.utils?.hasLoadedNamespace(namespace)) {\n this.logger.warn(`did not save key \"${key}\" as the namespace \"${namespace}\" was not yet loaded`, 'This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!');\n return;\n }\n if (key === undefined || key === null || key === '') return;\n if (this.backend?.create) {\n const opts = {\n ...options,\n isUpdate\n };\n const fc = this.backend.create.bind(this.backend);\n if (fc.length < 6) {\n try {\n let r;\n if (fc.length === 5) {\n r = fc(languages, namespace, key, fallbackValue, opts);\n } else {\n r = fc(languages, namespace, key, fallbackValue);\n }\n if (r && typeof r.then === 'function') {\n r.then(data => clb(null, data)).catch(clb);\n } else {\n clb(null, r);\n }\n } catch (err) {\n clb(err);\n }\n } else {\n fc(languages, namespace, key, fallbackValue, clb, opts);\n }\n }\n if (!languages || !languages[0]) return;\n this.store.addResource(languages[0], namespace, key, fallbackValue);\n }\n}\n\nconst get = () => ({\n debug: false,\n initAsync: true,\n ns: ['translation'],\n defaultNS: ['translation'],\n fallbackLng: ['dev'],\n fallbackNS: false,\n supportedLngs: false,\n nonExplicitSupportedLngs: false,\n load: 'all',\n preload: false,\n simplifyPluralSuffix: true,\n keySeparator: '.',\n nsSeparator: ':',\n pluralSeparator: '_',\n contextSeparator: '_',\n partialBundledLanguages: false,\n saveMissing: false,\n updateMissing: false,\n saveMissingTo: 'fallback',\n saveMissingPlurals: true,\n missingKeyHandler: false,\n missingInterpolationHandler: false,\n postProcess: false,\n postProcessPassResolved: false,\n returnNull: false,\n returnEmptyString: true,\n returnObjects: false,\n joinArrays: false,\n returnedObjectHandler: false,\n parseMissingKeyHandler: false,\n appendNamespaceToMissingKey: false,\n appendNamespaceToCIMode: false,\n overloadTranslationOptionHandler: args => {\n let ret = {};\n if (typeof args[1] === 'object') ret = args[1];\n if (isString(args[1])) ret.defaultValue = args[1];\n if (isString(args[2])) ret.tDescription = args[2];\n if (typeof args[2] === 'object' || typeof args[3] === 'object') {\n const options = args[3] || args[2];\n Object.keys(options).forEach(key => {\n ret[key] = options[key];\n });\n }\n return ret;\n },\n interpolation: {\n escapeValue: true,\n format: value => value,\n prefix: '{{',\n suffix: '}}',\n formatSeparator: ',',\n unescapePrefix: '-',\n nestingPrefix: '$t(',\n nestingSuffix: ')',\n nestingOptionsSeparator: ',',\n maxReplaces: 1000,\n skipOnVariables: true\n },\n cacheInBuiltFormats: true\n});\nconst transformOptions = options => {\n if (isString(options.ns)) options.ns = [options.ns];\n if (isString(options.fallbackLng)) options.fallbackLng = [options.fallbackLng];\n if (isString(options.fallbackNS)) options.fallbackNS = [options.fallbackNS];\n if (options.supportedLngs?.indexOf?.('cimode') < 0) {\n options.supportedLngs = options.supportedLngs.concat(['cimode']);\n }\n if (typeof options.initImmediate === 'boolean') options.initAsync = options.initImmediate;\n return options;\n};\n\nconst noop = () => {};\nconst bindMemberFunctions = inst => {\n const mems = Object.getOwnPropertyNames(Object.getPrototypeOf(inst));\n mems.forEach(mem => {\n if (typeof inst[mem] === 'function') {\n inst[mem] = inst[mem].bind(inst);\n }\n });\n};\nconst SUPPORT_NOTICE_KEY = '__i18next_supportNoticeShown';\nconst getSupportNoticeShown = () => typeof globalThis !== 'undefined' && !!globalThis[SUPPORT_NOTICE_KEY];\nconst setSupportNoticeShown = () => {\n if (typeof globalThis !== 'undefined') globalThis[SUPPORT_NOTICE_KEY] = true;\n};\nconst usesLocize = inst => {\n if (inst?.modules?.backend?.name?.indexOf('Locize') > 0) return true;\n if (inst?.modules?.backend?.constructor?.name?.indexOf('Locize') > 0) return true;\n if (inst?.options?.backend?.backends) {\n if (inst.options.backend.backends.some(b => b?.name?.indexOf('Locize') > 0 || b?.constructor?.name?.indexOf('Locize') > 0)) return true;\n }\n if (inst?.options?.backend?.projectId) return true;\n if (inst?.options?.backend?.backendOptions) {\n if (inst.options.backend.backendOptions.some(b => b?.projectId)) return true;\n }\n return false;\n};\nclass I18n extends EventEmitter {\n constructor(options = {}, callback) {\n super();\n this.options = transformOptions(options);\n this.services = {};\n this.logger = baseLogger;\n this.modules = {\n external: []\n };\n bindMemberFunctions(this);\n if (callback && !this.isInitialized && !options.isClone) {\n if (!this.options.initAsync) {\n this.init(options, callback);\n return this;\n }\n setTimeout(() => {\n this.init(options, callback);\n }, 0);\n }\n }\n init(options = {}, callback) {\n this.isInitializing = true;\n if (typeof options === 'function') {\n callback = options;\n options = {};\n }\n if (options.defaultNS == null && options.ns) {\n if (isString(options.ns)) {\n options.defaultNS = options.ns;\n } else if (options.ns.indexOf('translation') < 0) {\n options.defaultNS = options.ns[0];\n }\n }\n const defOpts = get();\n this.options = {\n ...defOpts,\n ...this.options,\n ...transformOptions(options)\n };\n this.options.interpolation = {\n ...defOpts.interpolation,\n ...this.options.interpolation\n };\n if (options.keySeparator !== undefined) {\n this.options.userDefinedKeySeparator = options.keySeparator;\n }\n if (options.nsSeparator !== undefined) {\n this.options.userDefinedNsSeparator = options.nsSeparator;\n }\n if (typeof this.options.overloadTranslationOptionHandler !== 'function') {\n this.options.overloadTranslationOptionHandler = defOpts.overloadTranslationOptionHandler;\n }\n if (this.options.showSupportNotice !== false && !usesLocize(this) && !getSupportNoticeShown()) {\n if (typeof console !== 'undefined' && typeof console.info !== 'undefined') console.info('\uD83C\uDF10 i18next is maintained with support from Locize \u2014 consider powering your project with managed localization (AI, CDN, integrations): https://locize.com \uD83D\uDC99');\n setSupportNoticeShown();\n }\n const createClassOnDemand = ClassOrObject => {\n if (!ClassOrObject) return null;\n if (typeof ClassOrObject === 'function') return new ClassOrObject();\n return ClassOrObject;\n };\n if (!this.options.isClone) {\n if (this.modules.logger) {\n baseLogger.init(createClassOnDemand(this.modules.logger), this.options);\n } else {\n baseLogger.init(null, this.options);\n }\n let formatter;\n if (this.modules.formatter) {\n formatter = this.modules.formatter;\n } else {\n formatter = Formatter;\n }\n const lu = new LanguageUtil(this.options);\n this.store = new ResourceStore(this.options.resources, this.options);\n const s = this.services;\n s.logger = baseLogger;\n s.resourceStore = this.store;\n s.languageUtils = lu;\n s.pluralResolver = new PluralResolver(lu, {\n prepend: this.options.pluralSeparator,\n simplifyPluralSuffix: this.options.simplifyPluralSuffix\n });\n const usingLegacyFormatFunction = this.options.interpolation.format && this.options.interpolation.format !== defOpts.interpolation.format;\n if (usingLegacyFormatFunction) {\n this.logger.deprecate(`init: you are still using the legacy format function, please use the new approach: https://www.i18next.com/translation-function/formatting`);\n }\n if (formatter && (!this.options.interpolation.format || this.options.interpolation.format === defOpts.interpolation.format)) {\n s.formatter = createClassOnDemand(formatter);\n if (s.formatter.init) s.formatter.init(s, this.options);\n this.options.interpolation.format = s.formatter.format.bind(s.formatter);\n }\n s.interpolator = new Interpolator(this.options);\n s.utils = {\n hasLoadedNamespace: this.hasLoadedNamespace.bind(this)\n };\n s.backendConnector = new Connector(createClassOnDemand(this.modules.backend), s.resourceStore, s, this.options);\n s.backendConnector.on('*', (event, ...args) => {\n this.emit(event, ...args);\n });\n if (this.modules.languageDetector) {\n s.languageDetector = createClassOnDemand(this.modules.languageDetector);\n if (s.languageDetector.init) s.languageDetector.init(s, this.options.detection, this.options);\n }\n if (this.modules.i18nFormat) {\n s.i18nFormat = createClassOnDemand(this.modules.i18nFormat);\n if (s.i18nFormat.init) s.i18nFormat.init(this);\n }\n this.translator = new Translator(this.services, this.options);\n this.translator.on('*', (event, ...args) => {\n this.emit(event, ...args);\n });\n this.modules.external.forEach(m => {\n if (m.init) m.init(this);\n });\n }\n this.format = this.options.interpolation.format;\n if (!callback) callback = noop;\n if (this.options.fallbackLng && !this.services.languageDetector && !this.options.lng) {\n const codes = this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);\n if (codes.length > 0 && codes[0] !== 'dev') this.options.lng = codes[0];\n }\n if (!this.services.languageDetector && !this.options.lng) {\n this.logger.warn('init: no languageDetector is used and no lng is defined');\n }\n const storeApi = ['getResource', 'hasResourceBundle', 'getResourceBundle', 'getDataByLanguage'];\n storeApi.forEach(fcName => {\n this[fcName] = (...args) => this.store[fcName](...args);\n });\n const storeApiChained = ['addResource', 'addResources', 'addResourceBundle', 'removeResourceBundle'];\n storeApiChained.forEach(fcName => {\n this[fcName] = (...args) => {\n this.store[fcName](...args);\n return this;\n };\n });\n const deferred = defer();\n const load = () => {\n const finish = (err, t) => {\n this.isInitializing = false;\n if (this.isInitialized && !this.initializedStoreOnce) this.logger.warn('init: i18next is already initialized. You should call init just once!');\n this.isInitialized = true;\n if (!this.options.isClone) this.logger.log('initialized', this.options);\n this.emit('initialized', this.options);\n deferred.resolve(t);\n callback(err, t);\n };\n if (this.languages && !this.isInitialized) return finish(null, this.t.bind(this));\n this.changeLanguage(this.options.lng, finish);\n };\n if (this.options.resources || !this.options.initAsync) {\n load();\n } else {\n setTimeout(load, 0);\n }\n return deferred;\n }\n loadResources(language, callback = noop) {\n let usedCallback = callback;\n const usedLng = isString(language) ? language : this.language;\n if (typeof language === 'function') usedCallback = language;\n if (!this.options.resources || this.options.partialBundledLanguages) {\n if (usedLng?.toLowerCase() === 'cimode' && (!this.options.preload || this.options.preload.length === 0)) return usedCallback();\n const toLoad = [];\n const append = lng => {\n if (!lng) return;\n if (lng === 'cimode') return;\n const lngs = this.services.languageUtils.toResolveHierarchy(lng);\n lngs.forEach(l => {\n if (l === 'cimode') return;\n if (toLoad.indexOf(l) < 0) toLoad.push(l);\n });\n };\n if (!usedLng) {\n const fallbacks = this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);\n fallbacks.forEach(l => append(l));\n } else {\n append(usedLng);\n }\n this.options.preload?.forEach?.(l => append(l));\n this.services.backendConnector.load(toLoad, this.options.ns, e => {\n if (!e && !this.resolvedLanguage && this.language) this.setResolvedLanguage(this.language);\n usedCallback(e);\n });\n } else {\n usedCallback(null);\n }\n }\n reloadResources(lngs, ns, callback) {\n const deferred = defer();\n if (typeof lngs === 'function') {\n callback = lngs;\n lngs = undefined;\n }\n if (typeof ns === 'function') {\n callback = ns;\n ns = undefined;\n }\n if (!lngs) lngs = this.languages;\n if (!ns) ns = this.options.ns;\n if (!callback) callback = noop;\n this.services.backendConnector.reload(lngs, ns, err => {\n deferred.resolve();\n callback(err);\n });\n return deferred;\n }\n use(module) {\n if (!module) throw new Error('You are passing an undefined module! Please check the object you are passing to i18next.use()');\n if (!module.type) throw new Error('You are passing a wrong module! Please check the object you are passing to i18next.use()');\n if (module.type === 'backend') {\n this.modules.backend = module;\n }\n if (module.type === 'logger' || module.log && module.warn && module.error) {\n this.modules.logger = module;\n }\n if (module.type === 'languageDetector') {\n this.modules.languageDetector = module;\n }\n if (module.type === 'i18nFormat') {\n this.modules.i18nFormat = module;\n }\n if (module.type === 'postProcessor') {\n postProcessor.addPostProcessor(module);\n }\n if (module.type === 'formatter') {\n this.modules.formatter = module;\n }\n if (module.type === '3rdParty') {\n this.modules.external.push(module);\n }\n return this;\n }\n setResolvedLanguage(l) {\n if (!l || !this.languages) return;\n if (['cimode', 'dev'].indexOf(l) > -1) return;\n for (let li = 0; li < this.languages.length; li++) {\n const lngInLngs = this.languages[li];\n if (['cimode', 'dev'].indexOf(lngInLngs) > -1) continue;\n if (this.store.hasLanguageSomeTranslations(lngInLngs)) {\n this.resolvedLanguage = lngInLngs;\n break;\n }\n }\n if (!this.resolvedLanguage && this.languages.indexOf(l) < 0 && this.store.hasLanguageSomeTranslations(l)) {\n this.resolvedLanguage = l;\n this.languages.unshift(l);\n }\n }\n changeLanguage(lng, callback) {\n this.isLanguageChangingTo = lng;\n const deferred = defer();\n this.emit('languageChanging', lng);\n const setLngProps = l => {\n this.language = l;\n this.languages = this.services.languageUtils.toResolveHierarchy(l);\n this.resolvedLanguage = undefined;\n this.setResolvedLanguage(l);\n };\n const done = (err, l) => {\n if (l) {\n if (this.isLanguageChangingTo === lng) {\n setLngProps(l);\n this.translator.changeLanguage(l);\n this.isLanguageChangingTo = undefined;\n this.emit('languageChanged', l);\n this.logger.log('languageChanged', l);\n }\n } else {\n this.isLanguageChangingTo = undefined;\n }\n deferred.resolve((...args) => this.t(...args));\n if (callback) callback(err, (...args) => this.t(...args));\n };\n const setLng = lngs => {\n if (!lng && !lngs && this.services.languageDetector) lngs = [];\n const fl = isString(lngs) ? lngs : lngs && lngs[0];\n const l = this.store.hasLanguageSomeTranslations(fl) ? fl : this.services.languageUtils.getBestMatchFromCodes(isString(lngs) ? [lngs] : lngs);\n if (l) {\n if (!this.language) {\n setLngProps(l);\n }\n if (!this.translator.language) this.translator.changeLanguage(l);\n this.services.languageDetector?.cacheUserLanguage?.(l);\n }\n this.loadResources(l, err => {\n done(err, l);\n });\n };\n if (!lng && this.services.languageDetector && !this.services.languageDetector.async) {\n setLng(this.services.languageDetector.detect());\n } else if (!lng && this.services.languageDetector && this.services.languageDetector.async) {\n if (this.services.languageDetector.detect.length === 0) {\n this.services.languageDetector.detect().then(setLng);\n } else {\n this.services.languageDetector.detect(setLng);\n }\n } else {\n setLng(lng);\n }\n return deferred;\n }\n getFixedT(lng, ns, keyPrefix) {\n const fixedT = (key, opts, ...rest) => {\n let o;\n if (typeof opts !== 'object') {\n o = this.options.overloadTranslationOptionHandler([key, opts].concat(rest));\n } else {\n o = {\n ...opts\n };\n }\n o.lng = o.lng || fixedT.lng;\n o.lngs = o.lngs || fixedT.lngs;\n o.ns = o.ns || fixedT.ns;\n if (o.keyPrefix !== '') o.keyPrefix = o.keyPrefix || keyPrefix || fixedT.keyPrefix;\n const keySeparator = this.options.keySeparator || '.';\n let resultKey;\n if (o.keyPrefix && Array.isArray(key)) {\n resultKey = key.map(k => {\n if (typeof k === 'function') k = keysFromSelector(k, {\n ...this.options,\n ...opts\n });\n return `${o.keyPrefix}${keySeparator}${k}`;\n });\n } else {\n if (typeof key === 'function') key = keysFromSelector(key, {\n ...this.options,\n ...opts\n });\n resultKey = o.keyPrefix ? `${o.keyPrefix}${keySeparator}${key}` : key;\n }\n return this.t(resultKey, o);\n };\n if (isString(lng)) {\n fixedT.lng = lng;\n } else {\n fixedT.lngs = lng;\n }\n fixedT.ns = ns;\n fixedT.keyPrefix = keyPrefix;\n return fixedT;\n }\n t(...args) {\n return this.translator?.translate(...args);\n }\n exists(...args) {\n return this.translator?.exists(...args);\n }\n setDefaultNamespace(ns) {\n this.options.defaultNS = ns;\n }\n hasLoadedNamespace(ns, options = {}) {\n if (!this.isInitialized) {\n this.logger.warn('hasLoadedNamespace: i18next was not initialized', this.languages);\n return false;\n }\n if (!this.languages || !this.languages.length) {\n this.logger.warn('hasLoadedNamespace: i18n.languages were undefined or empty', this.languages);\n return false;\n }\n const lng = options.lng || this.resolvedLanguage || this.languages[0];\n const fallbackLng = this.options ? this.options.fallbackLng : false;\n const lastLng = this.languages[this.languages.length - 1];\n if (lng.toLowerCase() === 'cimode') return true;\n const loadNotPending = (l, n) => {\n const loadState = this.services.backendConnector.state[`${l}|${n}`];\n return loadState === -1 || loadState === 0 || loadState === 2;\n };\n if (options.precheck) {\n const preResult = options.precheck(this, loadNotPending);\n if (preResult !== undefined) return preResult;\n }\n if (this.hasResourceBundle(lng, ns)) return true;\n if (!this.services.backendConnector.backend || this.options.resources && !this.options.partialBundledLanguages) return true;\n if (loadNotPending(lng, ns) && (!fallbackLng || loadNotPending(lastLng, ns))) return true;\n return false;\n }\n loadNamespaces(ns, callback) {\n const deferred = defer();\n if (!this.options.ns) {\n if (callback) callback();\n return Promise.resolve();\n }\n if (isString(ns)) ns = [ns];\n ns.forEach(n => {\n if (this.options.ns.indexOf(n) < 0) this.options.ns.push(n);\n });\n this.loadResources(err => {\n deferred.resolve();\n if (callback) callback(err);\n });\n return deferred;\n }\n loadLanguages(lngs, callback) {\n const deferred = defer();\n if (isString(lngs)) lngs = [lngs];\n const preloaded = this.options.preload || [];\n const newLngs = lngs.filter(lng => preloaded.indexOf(lng) < 0 && this.services.languageUtils.isSupportedCode(lng));\n if (!newLngs.length) {\n if (callback) callback();\n return Promise.resolve();\n }\n this.options.preload = preloaded.concat(newLngs);\n this.loadResources(err => {\n deferred.resolve();\n if (callback) callback(err);\n });\n return deferred;\n }\n dir(lng) {\n if (!lng) lng = this.resolvedLanguage || (this.languages?.length > 0 ? this.languages[0] : this.language);\n if (!lng) return 'rtl';\n try {\n const l = new Intl.Locale(lng);\n if (l && l.getTextInfo) {\n const ti = l.getTextInfo();\n if (ti && ti.direction) return ti.direction;\n }\n } catch (e) {}\n const rtlLngs = ['ar', 'shu', 'sqr', 'ssh', 'xaa', 'yhd', 'yud', 'aao', 'abh', 'abv', 'acm', 'acq', 'acw', 'acx', 'acy', 'adf', 'ads', 'aeb', 'aec', 'afb', 'ajp', 'apc', 'apd', 'arb', 'arq', 'ars', 'ary', 'arz', 'auz', 'avl', 'ayh', 'ayl', 'ayn', 'ayp', 'bbz', 'pga', 'he', 'iw', 'ps', 'pbt', 'pbu', 'pst', 'prp', 'prd', 'ug', 'ur', 'ydd', 'yds', 'yih', 'ji', 'yi', 'hbo', 'men', 'xmn', 'fa', 'jpr', 'peo', 'pes', 'prs', 'dv', 'sam', 'ckb'];\n const languageUtils = this.services?.languageUtils || new LanguageUtil(get());\n if (lng.toLowerCase().indexOf('-latn') > 1) return 'ltr';\n return rtlLngs.indexOf(languageUtils.getLanguagePartFromCode(lng)) > -1 || lng.toLowerCase().indexOf('-arab') > 1 ? 'rtl' : 'ltr';\n }\n static createInstance(options = {}, callback) {\n const instance = new I18n(options, callback);\n instance.createInstance = I18n.createInstance;\n return instance;\n }\n cloneInstance(options = {}, callback = noop) {\n const forkResourceStore = options.forkResourceStore;\n if (forkResourceStore) delete options.forkResourceStore;\n const mergedOptions = {\n ...this.options,\n ...options,\n ...{\n isClone: true\n }\n };\n const clone = new I18n(mergedOptions);\n if (options.debug !== undefined || options.prefix !== undefined) {\n clone.logger = clone.logger.clone(options);\n }\n const membersToCopy = ['store', 'services', 'language'];\n membersToCopy.forEach(m => {\n clone[m] = this[m];\n });\n clone.services = {\n ...this.services\n };\n clone.services.utils = {\n hasLoadedNamespace: clone.hasLoadedNamespace.bind(clone)\n };\n if (forkResourceStore) {\n const clonedData = Object.keys(this.store.data).reduce((prev, l) => {\n prev[l] = {\n ...this.store.data[l]\n };\n prev[l] = Object.keys(prev[l]).reduce((acc, n) => {\n acc[n] = {\n ...prev[l][n]\n };\n return acc;\n }, prev[l]);\n return prev;\n }, {});\n clone.store = new ResourceStore(clonedData, mergedOptions);\n clone.services.resourceStore = clone.store;\n }\n if (options.interpolation) {\n const defOpts = get();\n const mergedInterpolation = {\n ...defOpts.interpolation,\n ...this.options.interpolation,\n ...options.interpolation\n };\n const mergedForInterpolator = {\n ...mergedOptions,\n interpolation: mergedInterpolation\n };\n clone.services.interpolator = new Interpolator(mergedForInterpolator);\n }\n clone.translator = new Translator(clone.services, mergedOptions);\n clone.translator.on('*', (event, ...args) => {\n clone.emit(event, ...args);\n });\n clone.init(mergedOptions, callback);\n clone.translator.options = mergedOptions;\n clone.translator.backendConnector.services.utils = {\n hasLoadedNamespace: clone.hasLoadedNamespace.bind(clone)\n };\n return clone;\n }\n toJSON() {\n return {\n options: this.options,\n store: this.store,\n language: this.language,\n languages: this.languages,\n resolvedLanguage: this.resolvedLanguage\n };\n }\n}\nconst instance = I18n.createInstance();\n\nconst createInstance = instance.createInstance;\nconst dir = instance.dir;\nconst init = instance.init;\nconst loadResources = instance.loadResources;\nconst reloadResources = instance.reloadResources;\nconst use = instance.use;\nconst changeLanguage = instance.changeLanguage;\nconst getFixedT = instance.getFixedT;\nconst t = instance.t;\nconst exists = instance.exists;\nconst setDefaultNamespace = instance.setDefaultNamespace;\nconst hasLoadedNamespace = instance.hasLoadedNamespace;\nconst loadNamespaces = instance.loadNamespaces;\nconst loadLanguages = instance.loadLanguages;\n\nexport { changeLanguage, createInstance, instance as default, dir, exists, getFixedT, hasLoadedNamespace, init, keysFromSelector as keyFromSelector, loadLanguages, loadNamespaces, loadResources, reloadResources, setDefaultNamespace, t, use };\n", "{\n\t\"language\": {\n\t\t\"name\": \"English\",\n\t\t\"changed\": \"Language is set to english.\",\n\t\t\"emoji\": \"\uD83C\uDDEC\uD83C\uDDE7\"\n\t},\n\n\t\"bot\": {\n\t\t\"description\": \"Hello! I will notify you when Twitch broadcasts start.\"\n\t},\n\n\t\"enable\": \"Enable\",\n\t\"disable\": \"Disable\",\n\t\"enabled\": \"Enabled\",\n\t\"disabled\": \"Disabled\",\n\n\t\"commands\": {\n\t\t\"follow\": {\n\t\t\t\"errors\": {\n\t\t\t\t\"badUsername\": \"{{ streamer }} - username can only contain \\\"a-z\\\", \\\"0-9\\\" and \\\"_\\\" symbols.\",\n\t\t\t\t\"streamerNotFound\": \"{{ streamer }} - not found on twitch.\",\n\t\t\t\t\"alreadyFollowed\": \"{{ streamer }} - already followed.\"\n\t\t\t},\n\t\t\t\"success\": \"{{ streamer }} - now followed.\",\n\t\t\t\"enter\": \"Enter username of streamer you want to follow.\\nYou can use multiple links to streamers.\\n\\nType /cancel for cancel action.\"\n\t\t},\n\n\t\t\"follows\": {\n\t\t\t\"total\": \"You followed to notifications from {{ count }} channels. Click on streamer nickname to unfollow from notifications.\"\n\t\t},\n\n\t\"unfollow\": {\n\t\t\"callbackButton\": \"Unfollow {{ streamer }}\",\n\t\t\"success\": \"Unfollowed from {{ streamer }}\"\n\t},\n\n\t\t\"start\": {\n\t\t\t\"game_change_notification_setting\": {\n\t\t\t\t\"button\": \"Game change notification\"\n\t\t\t},\n\t\t\t\"language\": {\n\t\t\t\t\"button\": \"\uD83C\uDF0D Language\"\n\t\t\t},\n\t\t\t\"offline_notification\": {\n\t\t\t\t\"button\": \"Offline notification\"\n\t\t\t},\n\t\t\t\"title_change_notification_setting\": {\n\t\t\t\t\"button\": \"Title change notification\"\n\t\t\t},\n\t\t\t\"image_in_notification_setting\": {\n\t\t\t\t\"button\": \"Show images in notifications\"\n\t\t\t},\n\t\t\t\"game_and_title_change_notification_setting\": {\n\t\t\t\t\"button\": \"Game and title change notification\"\n\t\t\t}\n\t\t}\n\t},\n\n\t\"notifications\": {\n\t\t\"streams\": {\n\t\t\t\"nowOffline\": \"\\uD83D\\uDD34 {{ channelLink }} now offline.\\n{{ categories }}\\n{{ duration }}\",\n\t\t\t\"nowOnline\": \"\\uD83D\\uDFE2 {{ channelLink }} now online.\\nCategory: {{ category }}\\nTitle: {{ title }}\",\n\t\t\t\"newCategory\": \"\\uD83D\\uDD04 {{ channelLink }} updated category from {{ oldCategory }} to {{ category }}\",\n\t\t\t\"titleChanged\": \"\\uD83D\\uDD04 {{ channelLink }} updated title from {{ oldTitle }} to {{ title }}\",\n\t\t\t\"titleAndCategoryChanged\": \"\\uD83D\\uDD04 {{ channelLink }} updated title from {{ oldTitle }} to {{ title }} and category from {{ oldCategory }} to {{ category }}\"\n\t\t}\n\t}\n}\n", "{\n \"language\": {\n \"name\": \"\u0420\u0443\u0441\u0441\u043A\u0438\u0439\",\n \"changed\": \"\u042F\u0437\u044B\u043A \u0443\u0441\u0442\u0430\u043D\u043E\u0432\u043B\u0435\u043D \u043D\u0430 \u0440\u0443\u0441\u0441\u043A\u0438\u0439.\",\n \"emoji\": \"\uD83C\uDDF7\uD83C\uDDFA\"\n },\n \"bot\": {\n \"description\": \"\u0417\u0434\u0440\u0430\u0432\u0441\u0442\u0432\u0443\u0439\u0442\u0435! \u042F \u0431\u0443\u0434\u0443 \u0443\u0432\u0435\u0434\u043E\u043C\u043B\u044F\u0442\u044C \u0432\u0430\u0441 \u043E \u043D\u0430\u0447\u0430\u043B\u0435 \u0442\u0440\u0430\u043D\u0441\u043B\u044F\u0446\u0438\u0439 Twitch.\"\n },\n \"enable\": \"\u0412\u043A\u043B\u044E\u0447\u0438\u0442\u044C\",\n \"disable\": \"\u0412\u044B\u043A\u043B\u044E\u0447\u0438\u0442\u044C\",\n \"enabled\": \"\u0412\u043A\u043B\u044E\u0447\u0435\u043D\u043E\",\n \"disabled\": \"\u0412\u044B\u043A\u043B\u044E\u0447\u0435\u043D\u043E\",\n \"commands\": {\n \"follow\": {\n \"errors\": {\n \"badUsername\": \"\u0418\u043C\u044F \u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044F \u043C\u043E\u0436\u0435\u0442 \u0441\u043E\u0434\u0435\u0440\u0436\u0430\u0442\u044C \u0442\u043E\u043B\u044C\u043A\u043E \\\"a-z\\\", \\\"0-9\\\" and \\\"_\\\" \u0441\u0438\u043C\u0432\u043E\u043B\u044B.\",\n \"streamerNotFound\": \"{{ streamer }} - \u043D\u0435 \u043D\u0430\u0439\u0434\u0435\u043D \u043D\u0430 \u0442\u0432\u0438\u0447\u0435.\",\n \"alreadyFollowed\": \"{{ streamer }} - \u0432\u044B \u0443\u0436\u0435 \u043F\u043E\u0434\u043F\u0438\u0441\u0430\u043D\u044B.\"\n },\n \"success\": \"{{ streamer }} - \u0442\u0435\u043F\u0435\u0440\u044C \u043E\u0442\u0441\u043B\u0435\u0436\u0438\u0432\u0430\u0435\u0442\u0441\u044F.\",\n \"enter\": \"\u0412\u0432\u0435\u0434\u0438\u0442\u0435 \u0438\u043C\u044F \u0441\u0442\u0440\u0438\u043C\u0435\u0440\u0430, \u0443\u0432\u0435\u0434\u043E\u043C\u043B\u0435\u043D\u0438\u044F \u043E\u0442 \u043A\u043E\u0442\u043E\u0440\u043E\u0433\u043E \u0445\u043E\u0442\u0438\u0442\u0435 \u043F\u043E\u043B\u0443\u0447\u0430\u0442\u044C.\\n\u0412\u044B \u043C\u043E\u0436\u0435\u0442\u0435 \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u044C \u0441\u0441\u044B\u043B\u043A\u0438.\\n\\n\u0412\u0432\u0435\u0434\u0438\u0442\u0435 /cancel \u0434\u043B\u044F \u043E\u0442\u043C\u0435\u043D\u044B \u0434\u0435\u0439\u0441\u0442\u0432\u0438\u044F.\"\n },\n \"follows\": {\n \"total\": \"\u0412\u044B \u043F\u043E\u0434\u043F\u0438\u0441\u0430\u043D\u044B \u043D\u0430 \u0443\u0432\u0435\u0434\u043E\u043C\u043B\u0435\u043D\u0438\u044F {{ count }} \u043A\u0430\u043D\u0430\u043B\u043E\u0432. \u041A\u043B\u0438\u043A\u043D\u0438\u0442\u0435 \u043D\u0430 \u043D\u0438\u043A\u043D\u0435\u0439\u043C \u0441\u0442\u0440\u0438\u043C\u0435\u0440\u0430, \u0447\u0442\u043E\u0431\u044B \u043E\u0442\u043F\u0438\u0441\u0430\u0442\u044C\u0441\u044F \u043E\u0442 \u0443\u0432\u0435\u0434\u043E\u043C\u043B\u0435\u043D\u0438\u0439.\"\n },\n \"unfollow\": {\n \"callbackButton\": \"\u041E\u0442\u043F\u0438\u0441\u0430\u0442\u044C\u0441\u044F \u043E\u0442 {{ streamer }}\",\n \"success\": \"\u0412\u044B \u043E\u0442\u043F\u0438\u0441\u0430\u043B\u0438\u0441\u044C \u043E\u0442 {{ streamer }}\"\n },\n \"start\": {\n \"game_change_notification_setting\": {\n \"button\": \"\u0423\u0432\u0435\u0434\u043E\u043C\u043B\u0435\u043D\u0438\u0435 \u043E \u0441\u043C\u0435\u043D\u0435 \u043A\u0430\u0442\u0435\u0433\u043E\u0440\u0438\u0438\"\n },\n \"language\": {\n \"button\": \"\uD83C\uDF0D \u042F\u0437\u044B\u043A\"\n },\n \"offline_notification\": {\n \"button\": \"\u0423\u0432\u0435\u0434\u043E\u043C\u043B\u0435\u043D\u0438\u0435 \u043E\u0431 \u0443\u0445\u043E\u0434\u0435 \u0432 \u043E\u0444\u0444\u043B\u0430\u0439\u043D\"\n },\n \"title_change_notification_setting\": {\n \"button\": \"\u0423\u0432\u0435\u0434\u043E\u043C\u043B\u0435\u043D\u0438\u0435 \u043E \u0441\u043C\u0435\u043D\u0435 \u043D\u0430\u0437\u0432\u0430\u043D\u0438\u044F\"\n },\n \"image_in_notification_setting\": {\n \"button\": \"\u041F\u043E\u043A\u0430\u0437\u044B\u0432\u0430\u0442\u044C \u0438\u0437\u043E\u0431\u0440\u0430\u0436\u0435\u043D\u0438\u044F \u0432 \u0443\u0432\u0435\u0434\u043E\u043C\u043B\u0435\u043D\u0438\u044F\u0445\"\n },\n \"game_and_title_change_notification_setting\": {\n \"button\": \"\u0423\u0432\u0435\u0434\u043E\u043C\u0435\u043B\u043D\u0438\u0435 \u043E \u0441\u043C\u0435\u043D\u0435 \u043A\u0430\u0442\u0435\u0433\u043E\u0440\u0438\u0438 \u0438 \u043D\u0430\u0437\u0432\u0430\u043D\u0438\u044F\"\n }\n }\n },\n \"notifications\": {\n \"streams\": {\n \"nowOffline\": \"\uD83D\uDD34 {{ channelLink }} \u0442\u0435\u043F\u0435\u0440\u044C \u043E\u0444\u0444\u043B\u0430\u0439\u043D.\\n{{ categories }}\\n{{ duration }}\",\n \"nowOnline\": \"\uD83D\uDFE2 {{ channelLink }} \u0442\u0435\u043F\u0435\u0440\u044C \u043E\u043D\u043B\u0430\u0439\u043D.\\n\u041A\u0430\u0442\u0435\u0433\u043E\u0440\u0438\u044F: {{ category }}\\n\u041D\u0430\u0437\u0432\u0430\u043D\u0438\u0435: {{ title }}\",\n \"newCategory\": \"\uD83D\uDD04 \u041D\u0430 \u043A\u0430\u043D\u0430\u043B\u0435 {{ channelLink }} \u0438\u0437\u043C\u0435\u043D\u0430\u043B\u0430\u0441\u044C \u043A\u0430\u0442\u0435\u0433\u043E\u0440\u0438\u044F \u0441 {{ oldCategory }} \u043D\u0430 {{ category }}\",\n \"titleChanged\": \"\uD83D\uDD04 \u041D\u0430 \u043A\u0430\u043D\u0430\u043B\u0435 {{ channelLink }} \u0438\u0437\u043C\u0435\u043D\u0438\u043B\u043E\u0441\u044C \u043D\u0430\u0437\u0432\u0430\u043D\u0438\u0435 \u0441 {{ oldTitle }} \u043D\u0430 {{ title }}\",\n \"titleAndCategoryChanged\": \"\uD83D\uDD04 \u041D\u0430 \u043A\u0430\u043D\u0430\u043B\u0435 {{ channelLink }} \u0438\u0437\u043C\u0435\u043D\u0438\u043B\u0438\u0441\u044C \u043D\u0430\u0437\u0432\u0430\u043D\u0438\u0435 \u0441 {{ oldTitle }} \u043D\u0430 {{ title }} \u0438 \u043A\u0430\u0442\u0435\u0433\u043E\u0440\u0438\u044F \u0441 {{ oldCategory }} \u043D\u0430 {{ category }}\"\n }\n }\n}\n", "{\n \"language\": {\n \"name\": \"\u0423\u043A\u0440\u0430\u0457\u043D\u0441\u044C\u043A\u0430\",\n \"changed\": \"\u041C\u043E\u0432\u0430 \u0437\u043C\u0456\u043D\u0435\u043D\u0430 \u043D\u0430 \u0443\u043A\u0440\u0430\u0457\u043D\u0441\u044C\u043A\u0443.\",\n \"emoji\": \"\uD83C\uDDFA\uD83C\uDDE6\"\n },\n \"bot\": {\n \"description\": \"\u0417\u0434\u0440\u0430\u0441\u0442\u0432\u0443\u0439\u0442\u0435! \u042F \u0431\u0443\u0434\u0443 \u0441\u043F\u043E\u0432\u0456\u0449\u0430\u0442\u0438 \u0432\u0430\u0441 \u043F\u0440\u043E \u043F\u043E\u0447\u0430\u0442\u043E\u043A Twitch \u0442\u0440\u0430\u043D\u0441\u043B\u044F\u0446\u0456\u0439.\"\n },\n \"enable\": \"\u0423\u0432\u0456\u043C\u043A\u043D\u0443\u0442\u0438\",\n \"disable\": \"\u0412\u0438\u043C\u043A\u043D\u0443\u0442\u0438\",\n \"enabled\": \"\u0423\u0432\u0456\u043C\u043A\u043D\u0435\u043D\u043E\",\n \"disabled\": \"\u0412\u0456\u043C\u043A\u043D\u0435\u043D\u043E\",\n \"commands\": {\n \"follow\": {\n \"errors\": {\n \"badUsername\": \"\u0406\u043C\u02BC\u044F \u043A\u043E\u0440\u0438\u0441\u0442\u0443\u0432\u0430\u0447\u0430 \u043C\u043E\u0436\u0435 \u043C\u0430\u0442\u0438 \u0442\u0456\u043B\u044C\u043A\u0438 \\\"a-z\\\", \\\"0-9\\\" \u0442\u0430 \\\"_\\\" \u0441\u0438\u043C\u0432\u043E\u043B\u0438.\",\n \"streamerNotFound\": \"{{ streamer }} - \u043D\u0435 \u0437\u043D\u0430\u0439\u0434\u0435\u043D\u0438\u0439 \u043D\u0430 \u0442\u0432\u0456\u0447\u0456.\",\n \"alreadyFollowed\": \"{{ streamer }} - \u0432\u0438 \u0432\u0436\u0435 \u043F\u0456\u0434\u043F\u0438\u0441\u0430\u043D\u0456.\"\n },\n \"success\": \"{{ streamer }} - \u0442\u0435\u043F\u0435\u0440 \u0432\u0456\u0434\u0441\u043B\u0456\u0434\u043A\u043E\u0432\u0443\u0454\u0442\u044C\u0441\u044F.\",\n \"enter\": \"\u0412\u0432\u0435\u0434\u0456\u0442\u044C \u0456\u043C\u02BC\u044F \u0441\u0442\u0440\u0456\u043C\u0435\u0440\u0430, \u0441\u043F\u043E\u0432\u0456\u0449\u0435\u043D\u043D\u044F \u0432\u0456\u0434 \u044F\u043A\u043E\u0433\u043E \u0432\u0438 \u0445\u043E\u0447\u0435\u0442\u0435 \u043E\u0442\u0440\u0438\u043C\u0443\u0432\u0430\u0442\u0438.\\n\u0412\u0438 \u043C\u043E\u0436\u0435\u0442\u0435 \u0432\u0438\u043A\u043E\u0440\u0438\u0441\u0442\u043E\u0432\u0443\u0432\u0430\u0442\u0438 \u043F\u043E\u0441\u0438\u043B\u0430\u043D\u043D\u044F.\\n\\n\u0412\u0432\u0435\u0434\u0456\u0442\u044C /cancel \u0434\u043B\u044F \u0441\u043A\u0430\u0441\u0443\u0432\u0430\u043D\u043D\u044F \u0434\u0456\u0457.\"\n },\n \"follows\": {\n \"total\": \"\u0412\u0438 \u043F\u0456\u0434\u043F\u0438\u0441\u0430\u043D\u0456 \u043D\u0430 \u0441\u043F\u043E\u0432\u0456\u0449\u0435\u043D\u043D\u044F \u0432\u0456\u0434 {{ count }} \u043A\u0430\u043D\u0430\u043B\u0456\u0432. \u041A\u043B\u0430\u0446\u043D\u0456\u0442\u044C \u043D\u0430 \u043D\u0456\u043A\u043D\u0435\u0439\u043C \u0441\u0442\u0440\u0456\u043C\u0435\u0440\u0430, \u0449\u043E\u0431 \u0432\u0456\u0434\u043F\u0438\u0441\u0430\u0442\u0438\u0441\u044C \u0432\u0456\u0434 \u0441\u043F\u043E\u0432\u0456\u0449\u0435\u043D\u044C.\"\n },\n \"unfollow\": {\n \"callbackButton\": \"\u0412\u0456\u0434\u043F\u0438\u0441\u0430\u0442\u0438\u0441\u044C \u0432\u0456\u0434 {{ streamer }}\",\n \"success\": \"\u0412\u0438 \u0432\u0456\u0434\u043F\u0438\u0441\u0430\u043B\u0438\u0441\u044C \u0432\u0456\u0434 {{ streamer }}\"\n },\n \"start\": {\n \"game_change_notification_setting\": {\n \"button\": \"\u0421\u043F\u043E\u0432\u0456\u0449\u0435\u043D\u043D\u044F \u043F\u0440\u043E \u0437\u043C\u0456\u043D\u0443 \u043A\u0430\u0442\u0435\u0433\u043E\u0440\u0456\u0457\"\n },\n \"language\": {\n \"button\": \"\uD83C\uDF0D \u041C\u043E\u0432\u0430\"\n },\n \"offline_notification\": {\n \"button\": \"\u0421\u043F\u043E\u0432\u0456\u0449\u0435\u043D\u043D\u044F \u043F\u0440\u0438 \u0443\u0445\u043E\u0434\u0456 \u0432 \u043E\u0444\u0444\u043B\u0430\u0439\u043D\"\n },\n \"title_change_notification_setting\": {\n \"button\": \"\u0421\u043F\u043E\u0432\u0456\u0449\u0435\u043D\u043D\u044F \u043F\u0440\u043E \u0437\u043C\u0456\u043D\u0443 \u043D\u0430\u0437\u0432\u0438\"\n },\n \"image_in_notification_setting\": {\n \"button\": \"\u041F\u043E\u043A\u0430\u0437\u0443\u0432\u0430\u0442\u0438 \u0437\u043E\u0431\u0440\u0430\u0436\u0435\u043D\u043D\u044F \u0432 \u0441\u043F\u043E\u0432\u0456\u0449\u0435\u043D\u043D\u044F\u0445\"\n },\n \"game_and_title_change_notification_setting\": {\n \"button\": \"\u0421\u043F\u043E\u0432\u0456\u0449\u0435\u043D\u043D\u044F \u043F\u0440\u043E \u0437\u043C\u0456\u043D\u0443 \u043A\u0430\u0442\u0435\u0433\u043E\u0440\u0456\u0457 \u0442\u0430 \u043D\u0430\u0437\u0432\u0438\"\n }\n }\n },\n \"notifications\": {\n \"streams\": {\n \"nowOffline\": \"\uD83D\uDD34 {{ channelLink }} \u0442\u0435\u043F\u0435\u0440 \u043E\u0444\u0444\u043B\u0430\u0439\u043D.\\n{{ categories }}\\n{{ duration }}\",\n \"nowOnline\": \"\uD83D\uDFE2 {{ channelLink }} \u0442\u0435\u043F\u0435\u0440 \u043E\u043D\u043B\u0430\u0439\u043D.\\n\u041A\u0430\u0442\u0435\u0433\u043E\u0440\u0456\u044F: {{ category }}\\n\u041D\u0430\u0437\u0432\u0430: {{ title }}\",\n \"newCategory\": \"\uD83D\uDD04 \u041D\u0430 \u043A\u0430\u043D\u0430\u043B\u0456 {{ channelLink }} \u0431\u0443\u043B\u0430 \u0437\u043C\u0456\u043D\u0435\u043D\u0430 \u043A\u0430\u0442\u0435\u0433\u043E\u0440\u0456\u044F \u0437 {{ oldCategory }} \u043D\u0430 {{ category }}\",\n \"titleChanged\": \"\uD83D\uDD04 \u041D\u0430 \u043A\u0430\u043D\u0430\u043B\u0456{{ channelLink }} \u0431\u0443\u043B\u0430 \u0437\u043C\u0456\u043D\u0435\u043D\u0430 \u043D\u0430\u0437\u0432\u0430 \u0437 {{ oldTitle }} \u043D\u0430 {{ title }}\",\n \"titleAndCategoryChanged\": \"\uD83D\uDD04 \u041D\u0430 \u043A\u0430\u043D\u0430\u043B\u0456 {{ channelLink }} \u0431\u0443\u043B\u0430 \u0437\u043C\u0456\u043D\u0435\u043D\u0430 \u043D\u0430\u0437\u0432\u0430 \u0437 {{ oldTitle }} \u043D\u0430 {{ title }} \u0442\u0430 \u043A\u0430\u0442\u0435\u0433\u043E\u0440\u0456\u044F \u0437 {{ oldCategory }} \u043D\u0430 {{ category }}\"\n }\n }\n}\n", "import { ApiClient } from '@twurple/api';\nimport { AppTokenAuthProvider } from '@twurple/auth';\nimport type { Env } from '../types/env';\n\nexport class TwitchService {\n private apiClient: ApiClient;\n private authProvider: AppTokenAuthProvider;\n\n constructor(env: Env) {\n this.authProvider = new AppTokenAuthProvider(\n env.TWITCH_CLIENT_ID,\n env.TWITCH_CLIENT_SECRET\n );\n this.apiClient = new ApiClient({ authProvider: this.authProvider });\n }\n\n async getUserByLogin(login: string) {\n try {\n return await this.apiClient.users.getUserByName(login);\n } catch (error) {\n return null;\n }\n }\n\n async getUserById(id: string) {\n try {\n return await this.apiClient.users.getUserById(id);\n } catch (error) {\n return null;\n }\n }\n\n async getStreamByUserId(userId: string) {\n try {\n return await this.apiClient.streams.getStreamByUserId(userId);\n } catch (error) {\n return null;\n }\n }\n\n async getGameById(gameId: string) {\n try {\n return await this.apiClient.games.getGameById(gameId);\n } catch (error) {\n return null;\n }\n }\n\n getApiClient() {\n return this.apiClient;\n }\n\n getAuthProvider() {\n return this.authProvider;\n }\n}\n", "export { ApiClient } from './client/ApiClient.js';\nexport { HelixBitsApi } from './endpoints/bits/HelixBitsApi.js';\nexport { HelixBitsLeaderboard } from './endpoints/bits/HelixBitsLeaderboard.js';\nexport { HelixBitsLeaderboardEntry } from './endpoints/bits/HelixBitsLeaderboardEntry.js';\nexport { HelixCheermoteList } from './endpoints/bits/HelixCheermoteList.js';\nexport { HelixChannelApi } from './endpoints/channel/HelixChannelApi.js';\nexport { HelixAdSchedule } from './endpoints/channel/HelixAdSchedule.js';\nexport { HelixChannel } from './endpoints/channel/HelixChannel.js';\nexport { HelixChannelEditor } from './endpoints/channel/HelixChannelEditor.js';\nexport { HelixChannelFollower } from './endpoints/channel/HelixChannelFollower.js';\nexport { HelixFollowedChannel } from './endpoints/channel/HelixFollowedChannel.js';\nexport { HelixChannelReference } from './endpoints/channel/HelixChannelReference.js';\nexport { HelixChannelPointsApi } from './endpoints/channelPoints/HelixChannelPointsApi.js';\nexport { HelixCustomReward } from './endpoints/channelPoints/HelixCustomReward.js';\nexport { HelixCustomRewardRedemption } from './endpoints/channelPoints/HelixCustomRewardRedemption.js';\nexport { HelixCharityApi } from './endpoints/charity/HelixCharityApi.js';\nexport { HelixCharityCampaign } from './endpoints/charity/HelixCharityCampaign.js';\nexport { HelixCharityCampaignDonation } from './endpoints/charity/HelixCharityCampaignDonation.js';\nexport { HelixCharityCampaignAmount } from './endpoints/charity/HelixCharityCampaignAmount.js';\nexport { HelixChatApi } from './endpoints/chat/HelixChatApi.js';\nexport { HelixChatBadgeSet } from './endpoints/chat/HelixChatBadgeSet.js';\nexport { HelixChatBadgeVersion } from './endpoints/chat/HelixChatBadgeVersion.js';\nexport { HelixChatSettings } from './endpoints/chat/HelixChatSettings.js';\nexport { HelixChatChatter } from './endpoints/chat/HelixChatChatter.js';\nexport { HelixEmote } from './endpoints/chat/HelixEmote.js';\nexport { HelixChannelEmote } from './endpoints/chat/HelixChannelEmote.js';\nexport { HelixEmoteFromSet } from './endpoints/chat/HelixEmoteFromSet.js';\nexport { HelixUserEmote } from './endpoints/chat/HelixUserEmote.js';\nexport { HelixPrivilegedChatSettings } from './endpoints/chat/HelixPrivilegedChatSettings.js';\nexport { HelixSentChatMessage } from './endpoints/chat/HelixSentChatMessage.js';\nexport { HelixSharedChatSessionParticipant } from './endpoints/chat/HelixSharedChatSessionParticipant.js';\nexport { HelixSharedChatSession } from './endpoints/chat/HelixSharedChatSession.js';\nexport { HelixClipApi } from './endpoints/clip/HelixClipApi.js';\nexport { HelixClip } from './endpoints/clip/HelixClip.js';\nexport { HelixContentClassificationLabelApi } from './endpoints/contentClassificationLabels/HelixContentClassificationLabelApi.js';\nexport { HelixContentClassificationLabel } from './endpoints/contentClassificationLabels/HelixContentClassificationLabel.js';\nexport { HelixEntitlementApi } from './endpoints/entitlements/HelixEntitlementApi.js';\nexport { HelixDropsEntitlement } from './endpoints/entitlements/HelixDropsEntitlement.js';\nexport { HelixEventSubApi } from './endpoints/eventSub/HelixEventSubApi.js';\nexport { HelixEventSubConduit } from './endpoints/eventSub/HelixEventSubConduit.js';\nexport { HelixEventSubConduitShard } from './endpoints/eventSub/HelixEventSubConduitShard.js';\nexport { HelixEventSubSubscription } from './endpoints/eventSub/HelixEventSubSubscription.js';\nexport { HelixPaginatedEventSubSubscriptionsRequest } from './endpoints/eventSub/HelixPaginatedEventSubSubscriptionsRequest.js';\nexport { HelixExtensionsApi } from './endpoints/extensions/HelixExtensionsApi.js';\nexport { HelixExtensionBitsProduct } from './endpoints/extensions/HelixExtensionBitsProduct.js';\nexport { HelixExtensionTransaction } from './endpoints/extensions/HelixExtensionTransaction.js';\nexport { HelixGameApi } from './endpoints/game/HelixGameApi.js';\nexport { HelixGame } from './endpoints/game/HelixGame.js';\nexport { HelixGoalApi } from './endpoints/goals/HelixGoalApi.js';\nexport { HelixGoal } from './endpoints/goals/HelixGoal.js';\nexport { HelixHypeTrainApi } from './endpoints/hypeTrain/HelixHypeTrainApi.js';\nexport { HelixHypeTrain } from './endpoints/hypeTrain/HelixHypeTrain.js';\nexport { HelixHypeTrainAllTimeHigh } from './endpoints/hypeTrain/HelixHypeTrainAllTimeHigh.js';\nexport { HelixHypeTrainContribution } from './endpoints/hypeTrain/HelixHypeTrainContribution.js';\nexport { HelixHypeTrainSharedParticipant } from './endpoints/hypeTrain/HelixHypeTrainSharedParticipant.js';\nexport { HelixHypeTrainStatus } from './endpoints/hypeTrain/HelixHypeTrainStatus.js';\nexport { HelixModerationApi } from './endpoints/moderation/HelixModerationApi.js';\nexport { HelixBan } from './endpoints/moderation/HelixBan.js';\nexport { HelixModerator } from './endpoints/moderation/HelixModerator.js';\nexport { HelixModeratedChannel } from './endpoints/moderation/HelixModeratedChannel.js';\nexport { HelixBanUser } from './endpoints/moderation/HelixBanUser.js';\nexport { HelixBlockedTerm } from './endpoints/moderation/HelixBlockedTerm.js';\nexport { HelixShieldModeStatus } from './endpoints/moderation/HelixShieldModeStatus.js';\nexport { HelixUnbanRequest } from './endpoints/moderation/HelixUnbanRequest.js';\nexport { HelixWarning } from './endpoints/moderation/HelixWarning.js';\nexport { HelixPollApi } from './endpoints/poll/HelixPollApi.js';\nexport { HelixPoll } from './endpoints/poll/HelixPoll.js';\nexport { HelixPollChoice } from './endpoints/poll/HelixPollChoice.js';\nexport { HelixPredictionApi } from './endpoints/prediction/HelixPredictionApi.js';\nexport { HelixPrediction } from './endpoints/prediction/HelixPrediction.js';\nexport { HelixPredictionOutcome } from './endpoints/prediction/HelixPredictionOutcome.js';\nexport { HelixPredictor } from './endpoints/prediction/HelixPredictor.js';\nexport { HelixRaidApi } from './endpoints/raids/HelixRaidApi.js';\nexport { HelixRaid } from './endpoints/raids/HelixRaid.js';\nexport { HelixUserRelation } from './relations/HelixUserRelation.js';\nexport { HelixScheduleApi } from './endpoints/schedule/HelixScheduleApi.js';\nexport { HelixSchedule } from './endpoints/schedule/HelixSchedule.js';\nexport { HelixScheduleSegment } from './endpoints/schedule/HelixScheduleSegment.js';\nexport { HelixPaginatedScheduleSegmentRequest } from './endpoints/schedule/HelixPaginatedScheduleSegmentRequest.js';\nexport { HelixSearchApi } from './endpoints/search/HelixSearchApi.js';\nexport { HelixChannelSearchResult } from './endpoints/search/HelixChannelSearchResult.js';\nexport { HelixStreamApi } from './endpoints/stream/HelixStreamApi.js';\nexport { HelixStream } from './endpoints/stream/HelixStream.js';\nexport { HelixStreamMarker } from './endpoints/stream/HelixStreamMarker.js';\nexport { HelixStreamMarkerWithVideo } from './endpoints/stream/HelixStreamMarkerWithVideo.js';\nexport { HelixPaginatedSubscriptionsRequest } from './endpoints/subscriptions/HelixPaginatedSubscriptionsRequest.js';\nexport { HelixSubscriptionApi } from './endpoints/subscriptions/HelixSubscriptionApi.js';\nexport { HelixSubscription } from './endpoints/subscriptions/HelixSubscription.js';\nexport { HelixUserSubscription } from './endpoints/subscriptions/HelixUserSubscription.js';\nexport { HelixTeamApi } from './endpoints/team/HelixTeamApi.js';\nexport { HelixTeam } from './endpoints/team/HelixTeam.js';\nexport { HelixTeamWithUsers } from './endpoints/team/HelixTeamWithUsers.js';\nexport { HelixUserApi } from './endpoints/user/HelixUserApi.js';\nexport { HelixUserBlock } from './endpoints/user/HelixUserBlock.js';\nexport { HelixFollow } from './endpoints/user/HelixFollow.js';\nexport { HelixPrivilegedUser } from './endpoints/user/HelixPrivilegedUser.js';\nexport { HelixUser } from './endpoints/user/HelixUser.js';\nexport { HelixBaseExtension } from './endpoints/user/extensions/HelixBaseExtension.js';\nexport { HelixInstalledExtension } from './endpoints/user/extensions/HelixInstalledExtension.js';\nexport { HelixInstalledExtensionList } from './endpoints/user/extensions/HelixInstalledExtensionList.js';\nexport { HelixUserExtension } from './endpoints/user/extensions/HelixUserExtension.js';\nexport { HelixVideoApi } from './endpoints/video/HelixVideoApi.js';\nexport { HelixVideo } from './endpoints/video/HelixVideo.js';\nexport { HelixWhisperApi } from './endpoints/whisper/HelixWhisperApi.js';\nexport { ChatMessageDroppedError } from './errors/ChatMessageDroppedError.js';\nexport { ConfigError } from './errors/ConfigError.js';\nexport { StreamNotLiveError } from './errors/StreamNotLiveError.js';\nexport { ApiReportedRequest } from './reporting/ApiReportedRequest.js';\nexport { HelixPaginatedRequest } from './utils/pagination/HelixPaginatedRequest.js';\nexport { HelixPaginatedRequestWithTotal } from './utils/pagination/HelixPaginatedRequestWithTotal.js';\nexport { extractUserId, extractUserName, HelixExtension, HellFreezesOverError } from '@twurple/common';\n", "import { __decorate } from \"tslib\";\nimport { isNode } from '@d-fischer/detect-node';\nimport { createLogger } from '@d-fischer/logger';\nimport { PartitionedRateLimiter, PartitionedTimeBasedRateLimiter } from '@d-fischer/rate-limiter';\nimport { callTwitchApiRaw } from '@twurple/api-call';\nimport { extractUserId, rtfm } from '@twurple/common';\nimport { ConfigError } from '../errors/ConfigError.js';\nimport { HelixRateLimiter } from '../utils/HelixRateLimiter.js';\nimport { BaseApiClient } from './BaseApiClient.js';\nimport { NoContextApiClient } from './NoContextApiClient.js';\nimport { UserContextApiClient } from './UserContextApiClient.js';\n/**\n * An API client for the Twitch Helix API and other miscellaneous endpoints.\n *\n * @meta category main\n * @hideProtected\n */\nlet ApiClient = class ApiClient extends BaseApiClient {\n /**\n * Creates a new API client instance.\n *\n * @param config Configuration for the client instance.\n */\n constructor(config) {\n if (!config.authProvider) {\n throw new ConfigError('No auth provider given. Please supply the `authProvider` option.');\n }\n const rateLimitLoggerOptions = { name: 'twurple:api:rate-limiter', ...config.logger };\n super(config, createLogger({ name: 'twurple:api:client', ...config.logger }), isNode\n ? new PartitionedRateLimiter({\n getPartitionKey: req => req.userId ?? null,\n createChild: () => new HelixRateLimiter({ logger: rateLimitLoggerOptions }),\n })\n : new PartitionedTimeBasedRateLimiter({\n logger: rateLimitLoggerOptions,\n bucketSize: 800,\n timeFrame: 64000,\n doRequest: async ({ options, clientId, accessToken, authorizationType, fetchOptions, }) => await callTwitchApiRaw(options, clientId, accessToken, authorizationType, fetchOptions),\n getPartitionKey: req => req.userId ?? null,\n }));\n }\n /**\n * Creates a contextualized ApiClient that can be used to call the API in the context of a given user.\n *\n * @param user The user to use as context.\n * @param runner The callback to execute.\n *\n * A parameter is passed that should be used in place of the normal `ApiClient`\n * to ensure that all requests are executed in the given user's context.\n *\n * Please note that requests which require scope authorization ignore this context.\n *\n * The return value of your callback will be propagated to the return value of this method.\n */\n async asUser(user, runner) {\n const ctx = new UserContextApiClient(this._config, this._logger, this._rateLimiter, extractUserId(user));\n return await runner(ctx);\n }\n /**\n * Creates a contextualized ApiClient that can be used to call the API in the context of a given intent.\n *\n * @param intents A list of intents. The first one that is found in your auth provider will be used.\n * @param runner The callback to execute.\n *\n * A parameter is passed that should be used in place of the normal `ApiClient`\n * to ensure that all requests are executed in the given user's context.\n *\n * Please note that requests which require scope authorization ignore this context.\n *\n * The return value of your callback will be propagated to the return value of this method.\n */\n async asIntent(intents, runner) {\n if (!this._authProvider.getAccessTokenForIntent) {\n throw new Error('Trying to use intents with an auth provider that does not support them');\n }\n for (const intent of intents) {\n const user = await this._authProvider.getAccessTokenForIntent(intent);\n if (user) {\n const ctx = new UserContextApiClient(this._config, this._logger, this._rateLimiter, user.userId);\n return await runner(ctx);\n }\n }\n throw new Error(`Intents [${intents.join(', ')}] not found in auth provider`);\n }\n /**\n * Creates a contextualized ApiClient that can be used to call the API without the context of any user.\n *\n * This usually means that an app access token is used.\n *\n * @param runner The callback to execute.\n *\n * A parameter is passed that should be used in place of the normal `ApiClient`\n * to ensure that all requests are executed without user context.\n *\n * Please note that requests which require scope authorization ignore this context erasure.\n *\n * The return value of your callback will be propagated to the return value of this method.\n */\n async withoutUser(runner) {\n const ctx = new NoContextApiClient(this._config, this._logger, this._rateLimiter);\n return await runner(ctx);\n }\n};\nApiClient = __decorate([\n rtfm('api', 'ApiClient')\n], ApiClient);\nexport { ApiClient };\n", "/******************************************************************************\nCopyright (c) Microsoft Corporation.\n\nPermission to use, copy, modify, and/or distribute this software for any\npurpose with or without fee is hereby granted.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\nPERFORMANCE OF THIS SOFTWARE.\n***************************************************************************** */\n/* global Reflect, Promise, SuppressedError, Symbol, Iterator */\n\nvar extendStatics = function(d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\n return extendStatics(d, b);\n};\n\nexport function __extends(d, b) {\n if (typeof b !== \"function\" && b !== null)\n throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n}\n\nexport var __assign = function() {\n __assign = Object.assign || function __assign(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\n }\n return t;\n }\n return __assign.apply(this, arguments);\n}\n\nexport function __rest(s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\n t[p[i]] = s[p[i]];\n }\n return t;\n}\n\nexport function __decorate(decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n}\n\nexport function __param(paramIndex, decorator) {\n return function (target, key) { decorator(target, key, paramIndex); }\n}\n\nexport function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {\n function accept(f) { if (f !== void 0 && typeof f !== \"function\") throw new TypeError(\"Function expected\"); return f; }\n var kind = contextIn.kind, key = kind === \"getter\" ? \"get\" : kind === \"setter\" ? \"set\" : \"value\";\n var target = !descriptorIn && ctor ? contextIn[\"static\"] ? ctor : ctor.prototype : null;\n var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});\n var _, done = false;\n for (var i = decorators.length - 1; i >= 0; i--) {\n var context = {};\n for (var p in contextIn) context[p] = p === \"access\" ? {} : contextIn[p];\n for (var p in contextIn.access) context.access[p] = contextIn.access[p];\n context.addInitializer = function (f) { if (done) throw new TypeError(\"Cannot add initializers after decoration has completed\"); extraInitializers.push(accept(f || null)); };\n var result = (0, decorators[i])(kind === \"accessor\" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);\n if (kind === \"accessor\") {\n if (result === void 0) continue;\n if (result === null || typeof result !== \"object\") throw new TypeError(\"Object expected\");\n if (_ = accept(result.get)) descriptor.get = _;\n if (_ = accept(result.set)) descriptor.set = _;\n if (_ = accept(result.init)) initializers.unshift(_);\n }\n else if (_ = accept(result)) {\n if (kind === \"field\") initializers.unshift(_);\n else descriptor[key] = _;\n }\n }\n if (target) Object.defineProperty(target, contextIn.name, descriptor);\n done = true;\n};\n\nexport function __runInitializers(thisArg, initializers, value) {\n var useValue = arguments.length > 2;\n for (var i = 0; i < initializers.length; i++) {\n value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);\n }\n return useValue ? value : void 0;\n};\n\nexport function __propKey(x) {\n return typeof x === \"symbol\" ? x : \"\".concat(x);\n};\n\nexport function __setFunctionName(f, name, prefix) {\n if (typeof name === \"symbol\") name = name.description ? \"[\".concat(name.description, \"]\") : \"\";\n return Object.defineProperty(f, \"name\", { configurable: true, value: prefix ? \"\".concat(prefix, \" \", name) : name });\n};\n\nexport function __metadata(metadataKey, metadataValue) {\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\n}\n\nexport function __awaiter(thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n}\n\nexport function __generator(thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === \"function\" ? Iterator : Object).prototype);\n return g.next = verb(0), g[\"throw\"] = verb(1), g[\"return\"] = verb(2), typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (g && (g = 0, op[0] && (_ = 0)), _) try {\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [op[0] & 2, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n}\n\nexport var __createBinding = Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n});\n\nexport function __exportStar(m, o) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);\n}\n\nexport function __values(o) {\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\n if (m) return m.call(o);\n if (o && typeof o.length === \"number\") return {\n next: function () {\n if (o && i >= o.length) o = void 0;\n return { value: o && o[i++], done: !o };\n }\n };\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\n}\n\nexport function __read(o, n) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n if (!m) return o;\n var i = m.call(o), r, ar = [], e;\n try {\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n }\n catch (error) { e = { error: error }; }\n finally {\n try {\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\n }\n finally { if (e) throw e.error; }\n }\n return ar;\n}\n\n/** @deprecated */\nexport function __spread() {\n for (var ar = [], i = 0; i < arguments.length; i++)\n ar = ar.concat(__read(arguments[i]));\n return ar;\n}\n\n/** @deprecated */\nexport function __spreadArrays() {\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\n r[k] = a[j];\n return r;\n}\n\nexport function __spreadArray(to, from, pack) {\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\n if (ar || !(i in from)) {\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\n ar[i] = from[i];\n }\n }\n return to.concat(ar || Array.prototype.slice.call(from));\n}\n\nexport function __await(v) {\n return this instanceof __await ? (this.v = v, this) : new __await(v);\n}\n\nexport function __asyncGenerator(thisArg, _arguments, generator) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\n return i = Object.create((typeof AsyncIterator === \"function\" ? AsyncIterator : Object).prototype), verb(\"next\"), verb(\"throw\"), verb(\"return\", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i;\n function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; }\n function verb(n, f) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; if (f) i[n] = f(i[n]); } }\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\n function fulfill(value) { resume(\"next\", value); }\n function reject(value) { resume(\"throw\", value); }\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\n}\n\nexport function __asyncDelegator(o) {\n var i, p;\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; }\n}\n\nexport function __asyncValues(o) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var m = o[Symbol.asyncIterator], i;\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\n}\n\nexport function __makeTemplateObject(cooked, raw) {\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\n return cooked;\n};\n\nvar __setModuleDefault = Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n};\n\nvar ownKeys = function(o) {\n ownKeys = Object.getOwnPropertyNames || function (o) {\n var ar = [];\n for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;\n return ar;\n };\n return ownKeys(o);\n};\n\nexport function __importStar(mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== \"default\") __createBinding(result, mod, k[i]);\n __setModuleDefault(result, mod);\n return result;\n}\n\nexport function __importDefault(mod) {\n return (mod && mod.__esModule) ? mod : { default: mod };\n}\n\nexport function __classPrivateFieldGet(receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n}\n\nexport function __classPrivateFieldSet(receiver, state, value, kind, f) {\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n}\n\nexport function __classPrivateFieldIn(state, receiver) {\n if (receiver === null || (typeof receiver !== \"object\" && typeof receiver !== \"function\")) throw new TypeError(\"Cannot use 'in' operator on non-object\");\n return typeof state === \"function\" ? receiver === state : state.has(receiver);\n}\n\nexport function __addDisposableResource(env, value, async) {\n if (value !== null && value !== void 0) {\n if (typeof value !== \"object\" && typeof value !== \"function\") throw new TypeError(\"Object expected.\");\n var dispose, inner;\n if (async) {\n if (!Symbol.asyncDispose) throw new TypeError(\"Symbol.asyncDispose is not defined.\");\n dispose = value[Symbol.asyncDispose];\n }\n if (dispose === void 0) {\n if (!Symbol.dispose) throw new TypeError(\"Symbol.dispose is not defined.\");\n dispose = value[Symbol.dispose];\n if (async) inner = dispose;\n }\n if (typeof dispose !== \"function\") throw new TypeError(\"Object not disposable.\");\n if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } };\n env.stack.push({ value: value, dispose: dispose, async: async });\n }\n else if (async) {\n env.stack.push({ async: true });\n }\n return value;\n}\n\nvar _SuppressedError = typeof SuppressedError === \"function\" ? SuppressedError : function (error, suppressed, message) {\n var e = new Error(message);\n return e.name = \"SuppressedError\", e.error = error, e.suppressed = suppressed, e;\n};\n\nexport function __disposeResources(env) {\n function fail(e) {\n env.error = env.hasError ? new _SuppressedError(e, env.error, \"An error was suppressed during disposal.\") : e;\n env.hasError = true;\n }\n var r, s = 0;\n function next() {\n while (r = env.stack.pop()) {\n try {\n if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);\n if (r.dispose) {\n var result = r.dispose.call(r.value);\n if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { fail(e); return next(); });\n }\n else s |= 1;\n }\n catch (e) {\n fail(e);\n }\n }\n if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();\n if (env.hasError) throw env.error;\n }\n return next();\n}\n\nexport function __rewriteRelativeImportExtension(path, preserveJsx) {\n if (typeof path === \"string\" && /^\\.\\.?\\//.test(path)) {\n return path.replace(/\\.(tsx)$|((?:\\.d)?)((?:\\.[^./]+?)?)\\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {\n return tsx ? preserveJsx ? \".jsx\" : \".js\" : d && (!ext || !cm) ? m : (d + ext + \".\" + cm.toLowerCase() + \"js\");\n });\n }\n return path;\n}\n\nexport default {\n __extends,\n __assign,\n __rest,\n __decorate,\n __param,\n __esDecorate,\n __runInitializers,\n __propKey,\n __setFunctionName,\n __metadata,\n __awaiter,\n __generator,\n __createBinding,\n __exportStar,\n __values,\n __read,\n __spread,\n __spreadArrays,\n __spreadArray,\n __await,\n __asyncGenerator,\n __asyncDelegator,\n __asyncValues,\n __makeTemplateObject,\n __importStar,\n __importDefault,\n __classPrivateFieldGet,\n __classPrivateFieldSet,\n __classPrivateFieldIn,\n __addDisposableResource,\n __disposeResources,\n __rewriteRelativeImportExtension,\n};\n", "export { createLogger } from \"./createLogger.mjs\";\nexport { LogLevel } from \"./LogLevel.mjs\";\n", "import { isNode } from '@d-fischer/detect-node';\nimport { BrowserLogger } from \"./BrowserLogger.mjs\";\nimport { CustomLoggerWrapper } from \"./CustomLoggerWrapper.mjs\";\nimport { NodeLogger } from \"./NodeLogger.mjs\";\nexport function createLogger(options) {\n if (options.custom) {\n return new CustomLoggerWrapper(options);\n }\n if (isNode) {\n return new NodeLogger(options);\n }\n return new BrowserLogger(options);\n}\n", "import { __extends } from \"tslib\";\nimport { LogLevelToConsoleFunction } from \"./LogLevel.mjs\";\nimport { BaseLogger } from \"./BaseLogger.mjs\";\nvar BrowserLogger = /** @class */ (function (_super) {\n __extends(BrowserLogger, _super);\n function BrowserLogger() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n BrowserLogger.prototype.log = function (level, message) {\n if (level > this._minLevel) {\n return;\n }\n var logFn = LogLevelToConsoleFunction[level];\n var formattedMessage = \"[\".concat(this._name, \"] \").concat(message);\n if (this._timestamps) {\n formattedMessage = \"[\".concat(new Date().toISOString(), \"] \").concat(message);\n }\n logFn(formattedMessage);\n };\n return BrowserLogger;\n}(BaseLogger));\nexport { BrowserLogger };\n", "var _a;\nimport { isNode } from '@d-fischer/detect-node';\nexport var LogLevel;\n(function (LogLevel) {\n LogLevel[LogLevel[\"CRITICAL\"] = 0] = \"CRITICAL\";\n LogLevel[LogLevel[\"ERROR\"] = 1] = \"ERROR\";\n LogLevel[LogLevel[\"WARNING\"] = 2] = \"WARNING\";\n LogLevel[LogLevel[\"INFO\"] = 3] = \"INFO\";\n LogLevel[LogLevel[\"DEBUG\"] = 4] = \"DEBUG\";\n LogLevel[LogLevel[\"TRACE\"] = 7] = \"TRACE\";\n})(LogLevel || (LogLevel = {}));\nexport function resolveLogLevel(level) {\n if (typeof level === 'number') {\n if (Object.prototype.hasOwnProperty.call(LogLevel, level)) {\n return level;\n }\n var eligibleLevels = Object.keys(LogLevel)\n .map(function (k) { return parseInt(k, 10); })\n .filter(function (k) { return !isNaN(k) && k < level; });\n if (!eligibleLevels.length) {\n return LogLevel.WARNING;\n }\n return Math.max.apply(Math, eligibleLevels);\n }\n // TODO drop the replace for next major, it keeps the old deprecated debug1/2/3 levels running\n var strLevel = level.replace(/\\d+$/, '').toUpperCase();\n if (!Object.prototype.hasOwnProperty.call(LogLevel, strLevel)) {\n throw new Error(\"Unknown log level string: \".concat(level));\n }\n return LogLevel[strLevel];\n}\n// Node 8+ defines console.debug as noop, and earlier versions don't define it at all\nvar debugFunction = isNode ? console.log.bind(console) : console.debug.bind(console);\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport var LogLevelToConsoleFunction = (_a = {},\n _a[LogLevel.CRITICAL] = console.error.bind(console),\n _a[LogLevel.ERROR] = console.error.bind(console),\n _a[LogLevel.WARNING] = console.warn.bind(console),\n _a[LogLevel.INFO] = console.info.bind(console),\n _a[LogLevel.DEBUG] = debugFunction.bind(console),\n _a[LogLevel.TRACE] = console.trace.bind(console),\n _a);\n", "import { mapOptional } from '@d-fischer/shared-utils';\nimport { isNode } from '@d-fischer/detect-node';\nimport { getMinLogLevelFromEnv } from \"./getMinLogLevelFromEnv.mjs\";\nimport { LogLevel, resolveLogLevel } from \"./LogLevel.mjs\";\nvar BaseLogger = /** @class */ (function () {\n function BaseLogger(_a) {\n var name = _a.name, minLevel = _a.minLevel, _b = _a.emoji, emoji = _b === void 0 ? false : _b, colors = _a.colors, _c = _a.timestamps, timestamps = _c === void 0 ? isNode : _c;\n var _d, _e;\n this._name = name;\n this._minLevel =\n (_e = (_d = mapOptional(minLevel, function (lv) { return resolveLogLevel(lv); })) !== null && _d !== void 0 ? _d : getMinLogLevelFromEnv(name)) !== null && _e !== void 0 ? _e : LogLevel.WARNING;\n this._emoji = emoji;\n this._colors = colors;\n this._timestamps = timestamps;\n }\n // region convenience methods\n BaseLogger.prototype.crit = function (message) {\n this.log(LogLevel.CRITICAL, message);\n };\n BaseLogger.prototype.error = function (message) {\n this.log(LogLevel.ERROR, message);\n };\n BaseLogger.prototype.warn = function (message) {\n this.log(LogLevel.WARNING, message);\n };\n BaseLogger.prototype.info = function (message) {\n this.log(LogLevel.INFO, message);\n };\n BaseLogger.prototype.debug = function (message) {\n this.log(LogLevel.DEBUG, message);\n };\n BaseLogger.prototype.trace = function (message) {\n this.log(LogLevel.TRACE, message);\n };\n return BaseLogger;\n}());\nexport { BaseLogger };\n", "export { Enumerable } from \"./decorators/Enumerable.mjs\";\nexport { flatten } from \"./functions/array/flatten.mjs\";\nexport { immutableSplice } from \"./functions/array/immutableSplice.mjs\";\nexport { partitionedFlatMap } from \"./functions/array/partitionedFlatMap.mjs\";\nexport { resolveConfigValue, resolveConfigValueSync } from \"./functions/config/resolveConfigValue.mjs\";\nexport { deprecateClass } from \"./functions/deprecate/deprecateClass.mjs\";\nexport { match, eq } from \"./functions/match/match.mjs\";\nexport { fibWithLimit } from \"./functions/math/fib.mjs\";\nexport { arrayToObject } from \"./functions/object/arrayToObject.mjs\";\nexport { entriesToObject } from \"./functions/object/entriesToObject.mjs\";\nexport { forEachObjectEntry } from \"./functions/object/forEachObjectEntry.mjs\";\nexport { groupBy } from \"./functions/object/groupBy.mjs\";\nexport { indexBy } from \"./functions/object/indexBy.mjs\";\nexport { mapObject } from \"./functions/object/mapObject.mjs\";\nexport { omit } from \"./functions/object/omit.mjs\";\nexport { pick } from \"./functions/object/pick.mjs\";\nexport { isNullish, mapNullable, mapOptional } from \"./functions/optional/mapOptional.mjs\";\nexport { delay } from \"./functions/promise/delay.mjs\";\nexport { promiseWithResolvers } from \"./functions/promise/withResolvers.mjs\";\nexport { padLeft } from \"./functions/string/padLeft.mjs\";\nexport { splitWithLimit } from \"./functions/string/splitWithLimit.mjs\";\nexport { utf8Length, utf8Substring } from \"./functions/string/utf8.mjs\";\n", "/* eslint-disable @typescript-eslint/naming-convention */\nexport function Enumerable(enumerable) {\n if (enumerable === void 0) { enumerable = true; }\n return function (target, key) {\n // first property defined in prototype, that's why we use getters/setters\n // (otherwise assignment in object will override property in prototype)\n Object.defineProperty(target, key, {\n get: function () {\n return;\n },\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n set: function (val) {\n // here we have a reference to the instance and can set property directly to it\n Object.defineProperty(this, key, {\n value: val,\n writable: true,\n enumerable: enumerable\n });\n },\n enumerable: enumerable\n });\n };\n}\n", "import { __read, __spreadArray } from \"tslib\";\nexport function flatten(arr) {\n var _a;\n return (_a = []).concat.apply(_a, __spreadArray([], __read(arr), false));\n}\n", "import { __read, __spreadArray } from \"tslib\";\nexport function arrayToObject(arr, fn) {\n return Object.assign.apply(Object, __spreadArray([{}], __read(arr.map(fn)), false));\n}\n", "import { arrayToObject } from \"./arrayToObject.mjs\";\nexport function indexBy(arr, keyFn) {\n if (typeof keyFn !== 'function') {\n var key_1 = keyFn;\n // eslint-disable-next-line @typescript-eslint/ban-types,@typescript-eslint/no-base-to-string\n keyFn = (function (value) { return value[key_1].toString(); });\n }\n return arrayToObject(arr, function (val) {\n var _a;\n return (_a = {}, _a[keyFn(val)] = val, _a);\n });\n}\n", "export function isNullish(value) {\n return value == null;\n}\nexport function mapNullable(value, cb) {\n return isNullish(value) ? null : cb(value);\n}\nexport function mapOptional(value, cb) {\n return isNullish(value) ? undefined : cb(value);\n}\n", "export function promiseWithResolvers() {\n // eslint-disable-next-line @typescript-eslint/init-declarations\n var resolve;\n // eslint-disable-next-line @typescript-eslint/init-declarations\n var reject;\n var promise = new Promise(function (_resolve, _reject) {\n resolve = _resolve;\n reject = _reject;\n });\n return { promise: promise, resolve: resolve, reject: reject };\n}\n", "var _a, _b;\nimport { resolveLogLevel } from \"./LogLevel.mjs\";\nvar data = typeof process === 'undefined'\n ? []\n : (_b = (_a = process.env.LOGGING) === null || _a === void 0 ? void 0 : _a.split(';').map(function (part) {\n var _a = part.split('=', 2), namespace = _a[0], strLevel = _a[1];\n if (strLevel) {\n return [namespace === 'default' ? undefined : namespace.split(':'), resolveLogLevel(strLevel)];\n }\n return null;\n }).filter(function (v) { return !!v; }).sort(function (_a, _b) {\n var _c, _d;\n var a = _a[0];\n var b = _b[0];\n return ((_c = b === null || b === void 0 ? void 0 : b.length) !== null && _c !== void 0 ? _c : 0) - ((_d = a === null || a === void 0 ? void 0 : a.length) !== null && _d !== void 0 ? _d : 0);\n })) !== null && _b !== void 0 ? _b : [];\nvar defaultIndex = data.findIndex(function (_a) {\n var nsParts = _a[0];\n return !nsParts;\n});\nvar defaultLevel = undefined;\nif (defaultIndex !== -1) {\n defaultLevel = data[defaultIndex][1];\n data.splice(defaultIndex);\n}\nfunction isPrefix(value, prefix) {\n return prefix.length <= value.length && prefix.every(function (item, i) { return item === value[i]; });\n}\nexport function getMinLogLevelFromEnv(name) {\n var nameSplit = name.split(':');\n for (var _i = 0, data_1 = data; _i < data_1.length; _i++) {\n var _a = data_1[_i], nsParts = _a[0], level = _a[1];\n if (isPrefix(nameSplit, nsParts)) {\n return level;\n }\n }\n return defaultLevel;\n}\n", "import { mapOptional } from '@d-fischer/shared-utils';\nimport { getMinLogLevelFromEnv } from \"./getMinLogLevelFromEnv.mjs\";\nimport { LogLevel, resolveLogLevel } from \"./LogLevel.mjs\";\nvar CustomLoggerWrapper = /** @class */ (function () {\n function CustomLoggerWrapper(_a) {\n var name = _a.name, minLevel = _a.minLevel, custom = _a.custom;\n var _b;\n this._minLevel = (_b = mapOptional(minLevel, function (lv) { return resolveLogLevel(lv); })) !== null && _b !== void 0 ? _b : getMinLogLevelFromEnv(name);\n this._override = typeof custom === 'function' ? { log: custom } : custom;\n }\n CustomLoggerWrapper.prototype.log = function (level, message) {\n if (this._shouldLog(level)) {\n this._override.log(level, message);\n }\n };\n CustomLoggerWrapper.prototype.crit = function (message) {\n if (!this._override.crit) {\n this.log(LogLevel.CRITICAL, message);\n }\n else if (this._shouldLog(LogLevel.CRITICAL)) {\n this._override.crit(message);\n }\n };\n CustomLoggerWrapper.prototype.error = function (message) {\n if (!this._override.error) {\n this.log(LogLevel.ERROR, message);\n }\n else if (this._shouldLog(LogLevel.ERROR)) {\n this._override.error(message);\n }\n };\n CustomLoggerWrapper.prototype.warn = function (message) {\n if (!this._override.warn) {\n this.log(LogLevel.WARNING, message);\n }\n else if (this._shouldLog(LogLevel.WARNING)) {\n this._override.warn(message);\n }\n };\n CustomLoggerWrapper.prototype.info = function (message) {\n if (!this._override.info) {\n this.log(LogLevel.INFO, message);\n }\n else if (this._shouldLog(LogLevel.INFO)) {\n this._override.info(message);\n }\n };\n CustomLoggerWrapper.prototype.debug = function (message) {\n if (!this._override.debug) {\n this.log(LogLevel.DEBUG, message);\n }\n else if (this._shouldLog(LogLevel.DEBUG)) {\n this._override.debug(message);\n }\n };\n CustomLoggerWrapper.prototype.trace = function (message) {\n if (!this._override.trace) {\n this.log(LogLevel.TRACE, message);\n }\n else if (this._shouldLog(LogLevel.TRACE)) {\n this._override.trace(message);\n }\n };\n CustomLoggerWrapper.prototype._shouldLog = function (level) {\n return this._minLevel === undefined || this._minLevel >= level;\n };\n return CustomLoggerWrapper;\n}());\nexport { CustomLoggerWrapper };\n", "var _a, _b, _c;\nimport { __extends } from \"tslib\";\nimport { LogLevel, LogLevelToConsoleFunction } from \"./LogLevel.mjs\";\nimport { BaseLogger } from \"./BaseLogger.mjs\";\nexport var LogLevelToEmoji = (_a = {},\n _a[LogLevel.CRITICAL] = \"\\uD83D\\uDED1\",\n _a[LogLevel.ERROR] = \"\\u274C\",\n // these following two need extra spaces at the end because somehow they consume less space in a terminal than they should...\n _a[LogLevel.WARNING] = \"\\u26A0\\uFE0F \",\n _a[LogLevel.INFO] = \"\\u2139\\uFE0F \",\n _a[LogLevel.DEBUG] = \"\\uD83D\\uDC1E\",\n _a[LogLevel.TRACE] = \"\\uD83D\\uDC3E\",\n _a);\nvar colors = {\n black: 30,\n red: 31,\n green: 32,\n yellow: 33,\n blue: 34,\n magenta: 35,\n cyan: 36,\n white: 37,\n blackBright: 90,\n redBright: 91,\n greenBright: 92,\n yellowBright: 93,\n blueBright: 94,\n magentaBright: 95,\n cyanBright: 96,\n whiteBright: 97\n};\nvar bgColors = {\n bgBlack: 40,\n bgRed: 41,\n bgGreen: 42,\n bgYellow: 43,\n bgBlue: 44,\n bgMagenta: 45,\n bgCyan: 46,\n bgWhite: 47,\n bgBlackBright: 100,\n bgRedBright: 101,\n bgGreenBright: 102,\n bgYellowBright: 103,\n bgBlueBright: 104,\n bgMagentaBright: 105,\n bgCyanBright: 106,\n bgWhiteBright: 107\n};\nfunction createGenericWrapper(color, ending, inner) {\n return function (str) { return \"\\u001B[\".concat(color, \"m\").concat(inner ? inner(str) : str, \"\\u001B[\").concat(ending, \"m\"); };\n}\nfunction createColorWrapper(color) {\n return createGenericWrapper(colors[color], 39);\n}\nfunction createBgWrapper(color, fgWrapper) {\n return createGenericWrapper(bgColors[color], 49, fgWrapper);\n}\nexport var LogLevelToColor = (_b = {},\n _b[LogLevel.CRITICAL] = createColorWrapper('red'),\n _b[LogLevel.ERROR] = createColorWrapper('redBright'),\n _b[LogLevel.WARNING] = createColorWrapper('yellow'),\n _b[LogLevel.INFO] = createColorWrapper('blue'),\n _b[LogLevel.DEBUG] = createColorWrapper('magenta'),\n _b[LogLevel.TRACE] = createGenericWrapper(0, 0),\n _b);\nexport var LogLevelToBackgroundColor = (_c = {},\n _c[LogLevel.CRITICAL] = createBgWrapper('bgRed', createColorWrapper('white')),\n _c[LogLevel.ERROR] = createBgWrapper('bgRedBright', createColorWrapper('white')),\n _c[LogLevel.WARNING] = createBgWrapper('bgYellow', createColorWrapper('black')),\n _c[LogLevel.INFO] = createBgWrapper('bgBlue', createColorWrapper('white')),\n _c[LogLevel.DEBUG] = createBgWrapper('bgMagenta', createColorWrapper('black')),\n _c[LogLevel.TRACE] = createGenericWrapper(7, 27),\n _c);\nvar NodeLogger = /** @class */ (function (_super) {\n __extends(NodeLogger, _super);\n function NodeLogger() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n NodeLogger.prototype.log = function (level, message) {\n var _a, _b, _c;\n if (level > this._minLevel) {\n return;\n }\n var logFn = LogLevelToConsoleFunction[level];\n var builtMessage = '';\n if (this._timestamps) {\n builtMessage += \"[\".concat(new Date().toISOString(), \"] \");\n }\n if (this._emoji) {\n var emoji = LogLevelToEmoji[level];\n builtMessage += \"\".concat(emoji, \" \");\n }\n var useColors = (_c = (_a = this._colors) !== null && _a !== void 0 ? _a : (_b = process.stdout) === null || _b === void 0 ? void 0 : _b.isTTY) !== null && _c !== void 0 ? _c : true;\n if (useColors) {\n builtMessage += \"\".concat(LogLevelToBackgroundColor[level](this._name), \" \").concat(LogLevelToBackgroundColor[level](LogLevel[level]), \" \").concat(LogLevelToColor[level](message));\n }\n else {\n builtMessage += \"[\".concat(this._name, \":\").concat(LogLevel[level].toLowerCase(), \"] \").concat(message);\n }\n logFn(builtMessage);\n };\n return NodeLogger;\n}(BaseLogger));\nexport { NodeLogger };\n", "export { RateLimiterDestroyedError } from \"./errors/RateLimiterDestroyedError.mjs\";\nexport { RateLimitReachedError } from \"./errors/RateLimitReachedError.mjs\";\nexport { RetryAfterError } from \"./errors/RetryAfterError.mjs\";\nexport { NullRateLimiter } from \"./limiters/NullRateLimiter.mjs\";\nexport { PartitionedRateLimiter } from \"./limiters/PartitionedRateLimiter.mjs\";\nexport { PartitionedTimeBasedRateLimiter } from \"./limiters/PartitionedTimeBasedRateLimiter.mjs\";\nexport { ResponseBasedRateLimiter } from \"./limiters/ResponseBasedRateLimiter.mjs\";\nexport { TimeBasedRateLimiter } from \"./limiters/TimeBasedRateLimiter.mjs\";\nexport { TimedPassthruRateLimiter } from \"./limiters/TimedPassthruRateLimiter.mjs\";\n", "import { CustomError } from \"./CustomError.mjs\";\nexport class RateLimiterDestroyedError extends CustomError {\n}\n", "/** @private */\nexport class CustomError extends Error {\n constructor(...params) {\n var _a;\n // @ts-ignore\n super(...params);\n // restore prototype chain\n Object.setPrototypeOf(this, new.target.prototype);\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n (_a = Error.captureStackTrace) === null || _a === void 0 ? void 0 : _a.call(Error, this, new.target.constructor);\n }\n get name() {\n return this.constructor.name;\n }\n}\n", "import { CustomError } from \"./CustomError.mjs\";\nexport class RateLimitReachedError extends CustomError {\n}\n", "import { CustomError } from \"./CustomError.mjs\";\nexport class RetryAfterError extends CustomError {\n constructor(after) {\n super(`Need to retry after ${after} ms`);\n this._retryAt = Date.now() + after;\n }\n get retryAt() {\n return this._retryAt;\n }\n}\n", "import { ResponseBasedRateLimiter } from \"./ResponseBasedRateLimiter.mjs\";\nexport class PartitionedRateLimiter {\n constructor(options) {\n this._children = new Map();\n this._paused = false;\n this._partitionKeyCallback = options.getPartitionKey;\n this._createChildCallback = options.createChild;\n }\n async request(req, options) {\n const partitionKey = this._partitionKeyCallback(req);\n const partitionChild = this._getChild(partitionKey);\n return await partitionChild.request(req, options);\n }\n clear() {\n for (const child of this._children.values()) {\n child.clear();\n }\n }\n pause() {\n this._paused = true;\n for (const child of this._children.values()) {\n child.pause();\n }\n }\n resume() {\n this._paused = false;\n for (const child of this._children.values()) {\n child.resume();\n }\n }\n getChildStats(partitionKey) {\n if (!this._children.has(partitionKey)) {\n return null;\n }\n const child = this._children.get(partitionKey);\n if (!(child instanceof ResponseBasedRateLimiter)) {\n return null;\n }\n return child.stats;\n }\n _getChild(partitionKey) {\n if (this._children.has(partitionKey)) {\n return this._children.get(partitionKey);\n }\n const result = this._createChildCallback(partitionKey);\n if (this._paused) {\n result.pause();\n }\n this._children.set(partitionKey, result);\n return result;\n }\n}\n", "import { createLogger } from '@d-fischer/logger';\nimport { mapNullable } from '@d-fischer/shared-utils';\nimport { RateLimitReachedError } from \"../errors/RateLimitReachedError.mjs\";\nimport { RetryAfterError } from \"../errors/RetryAfterError.mjs\";\nexport class ResponseBasedRateLimiter {\n constructor({ logger }) {\n this._queue = [];\n this._batchRunning = false;\n this._paused = false;\n this._logger = createLogger({ name: 'rate-limiter', emoji: true, ...logger });\n }\n async request(req, options) {\n this._logger.trace('request start');\n return await new Promise((resolve, reject) => {\n var _a;\n const reqSpec = {\n req,\n resolve,\n reject,\n limitReachedBehavior: (_a = options === null || options === void 0 ? void 0 : options.limitReachedBehavior) !== null && _a !== void 0 ? _a : 'enqueue'\n };\n if (this._batchRunning || !!this._nextBatchTimer || this._paused) {\n this._logger.trace(`request queued batchRunning:${this._batchRunning.toString()} hasNextBatchTimer:${(!!this\n ._nextBatchTimer).toString()} paused:${this._paused.toString()}`);\n this._queue.push(reqSpec);\n }\n else {\n void this._runRequestBatch([reqSpec]);\n }\n });\n }\n clear() {\n this._queue = [];\n }\n pause() {\n this._paused = true;\n }\n resume() {\n this._paused = false;\n this._runNextBatch();\n }\n get stats() {\n var _a, _b, _c, _d, _e;\n return {\n lastKnownLimit: (_b = (_a = this._parameters) === null || _a === void 0 ? void 0 : _a.limit) !== null && _b !== void 0 ? _b : null,\n lastKnownRemainingRequests: (_d = (_c = this._parameters) === null || _c === void 0 ? void 0 : _c.remaining) !== null && _d !== void 0 ? _d : null,\n lastKnownResetDate: mapNullable((_e = this._parameters) === null || _e === void 0 ? void 0 : _e.resetsAt, v => new Date(v))\n };\n }\n async _runRequestBatch(reqSpecs) {\n this._logger.trace(`runRequestBatch start specs:${reqSpecs.length}`);\n this._batchRunning = true;\n if (this._parameters) {\n this._logger.debug(`Remaining requests: ${this._parameters.remaining}`);\n }\n this._logger.debug(`Doing ${reqSpecs.length} requests, new queue length is ${this._queue.length}`);\n const promises = reqSpecs.map(async (reqSpec) => {\n const { req, resolve, reject } = reqSpec;\n try {\n const result = await this.doRequest(req);\n const retry = this.needsToRetryAfter(result);\n if (retry !== null) {\n this._queue.unshift(reqSpec);\n this._logger.info(`Retrying after ${retry} ms`);\n throw new RetryAfterError(retry);\n }\n const params = this.getParametersFromResponse(result);\n resolve(result);\n return params;\n }\n catch (e) {\n if (e instanceof RetryAfterError) {\n throw e;\n }\n reject(e);\n return undefined;\n }\n });\n // downleveling problem hack, see https://github.com/es-shims/Promise.allSettled/issues/5\n const settledPromises = await Promise.allSettled(promises);\n const rejectedPromises = settledPromises.filter((p) => p.status === 'rejected');\n const now = Date.now();\n if (rejectedPromises.length) {\n this._logger.trace('runRequestBatch some rejected');\n const retryAt = Math.max(now, ...rejectedPromises.map((p) => p.reason.retryAt));\n const retryAfter = retryAt - now;\n this._logger.warn(`Waiting for ${retryAfter} ms because the rate limit was exceeded`);\n this._nextBatchTimer = setTimeout(() => {\n this._parameters = undefined;\n this._runNextBatch();\n }, retryAfter);\n }\n else {\n this._logger.trace('runRequestBatch none rejected');\n const params = settledPromises\n .filter((p) => p.status === 'fulfilled' && p.value !== undefined)\n .map(p => p.value)\n .reduce((carry, v) => {\n if (!carry) {\n return v;\n }\n // return v.resetsAt > carry.resetsAt ? v : carry;\n return v.remaining < carry.remaining ? v : carry;\n }, undefined);\n this._batchRunning = false;\n if (params) {\n this._parameters = params;\n if (params.resetsAt < now || params.remaining > 0) {\n this._logger.trace('runRequestBatch canRunMore');\n this._runNextBatch();\n }\n else {\n const delay = params.resetsAt - now;\n this._logger.trace(`runRequestBatch delay:${delay}`);\n this._logger.warn(`Waiting for ${delay} ms because the rate limit was reached`);\n this._queue = this._queue.filter(entry => {\n switch (entry.limitReachedBehavior) {\n case 'enqueue': {\n return true;\n }\n case 'null': {\n entry.resolve(null);\n return false;\n }\n case 'throw': {\n entry.reject(new RateLimitReachedError('Request removed from queue because the rate limit was reached'));\n return false;\n }\n default: {\n throw new Error('this should never happen');\n }\n }\n });\n this._nextBatchTimer = setTimeout(() => {\n this._parameters = undefined;\n this._runNextBatch();\n }, delay);\n }\n }\n }\n this._logger.trace('runRequestBatch end');\n }\n _runNextBatch() {\n if (this._paused) {\n return;\n }\n this._logger.trace('runNextBatch start');\n if (this._nextBatchTimer) {\n clearTimeout(this._nextBatchTimer);\n this._nextBatchTimer = undefined;\n }\n const amount = this._parameters ? Math.min(this._parameters.remaining, this._parameters.limit / 10) : 1;\n const reqSpecs = this._queue.splice(0, amount);\n if (reqSpecs.length) {\n void this._runRequestBatch(reqSpecs);\n }\n this._logger.trace('runNextBatch end');\n }\n}\n", "import { createLogger } from '@d-fischer/logger';\nimport { RateLimitReachedError } from \"../errors/RateLimitReachedError.mjs\";\nimport { RateLimiterDestroyedError } from \"../errors/RateLimiterDestroyedError.mjs\";\nexport class PartitionedTimeBasedRateLimiter {\n constructor({ logger, bucketSize, timeFrame, doRequest, getPartitionKey }) {\n this._partitionedQueue = new Map();\n this._usedFromBucket = new Map();\n this._counterTimers = new Set();\n this._paused = false;\n this._destroyed = false;\n this._logger = createLogger({ name: 'rate-limiter', emoji: true, ...logger });\n this._bucketSize = bucketSize;\n this._timeFrame = timeFrame;\n this._callback = doRequest;\n this._partitionKeyCallback = getPartitionKey;\n }\n async request(req, options) {\n return await new Promise((resolve, reject) => {\n var _a, _b;\n if (this._destroyed) {\n reject(new RateLimiterDestroyedError('Rate limiter was destroyed'));\n return;\n }\n const reqSpec = {\n req,\n resolve,\n reject,\n limitReachedBehavior: (_a = options === null || options === void 0 ? void 0 : options.limitReachedBehavior) !== null && _a !== void 0 ? _a : 'enqueue'\n };\n const partitionKey = this._partitionKeyCallback(req);\n const usedFromBucket = (_b = this._usedFromBucket.get(partitionKey)) !== null && _b !== void 0 ? _b : 0;\n if (usedFromBucket >= this._bucketSize || this._paused) {\n switch (reqSpec.limitReachedBehavior) {\n case 'enqueue': {\n const queue = this._getPartitionedQueue(partitionKey);\n queue.push(reqSpec);\n if (usedFromBucket + queue.length >= this._bucketSize) {\n this._logger.warn(`Rate limit of ${this._bucketSize} for ${partitionKey ? `partition ${partitionKey}` : 'default partition'} was reached, waiting for ${this._paused ? 'the limiter to be unpaused' : 'a free bucket entry'}; queue size is ${queue.length}`);\n }\n else {\n this._logger.info(`Enqueueing request for ${partitionKey ? `partition ${partitionKey}` : 'default partition'} because the rate limiter is paused; queue size is ${queue.length}`);\n }\n break;\n }\n case 'null': {\n reqSpec.resolve(null);\n if (this._paused) {\n this._logger.info(`Returning null for request for ${partitionKey ? `partition ${partitionKey}` : 'default partition'} because the rate limiter is paused`);\n }\n else {\n this._logger.warn(`Rate limit of ${this._bucketSize} for ${partitionKey ? `partition ${partitionKey}` : 'default partition'} was reached, dropping request and returning null`);\n }\n break;\n }\n case 'throw': {\n reqSpec.reject(new RateLimitReachedError(`Request dropped because ${this._paused\n ? 'the rate limiter is paused'\n : `the rate limit for ${partitionKey ? `partition ${partitionKey}` : 'default partition'} was reached`}`));\n break;\n }\n default: {\n throw new Error('this should never happen');\n }\n }\n }\n else {\n void this._runRequest(reqSpec, partitionKey);\n }\n });\n }\n clear() {\n this._partitionedQueue.clear();\n }\n pause() {\n this._paused = true;\n }\n resume() {\n this._paused = false;\n for (const partitionKey of this._partitionedQueue.keys()) {\n this._runNextRequest(partitionKey);\n }\n }\n destroy() {\n this._paused = false;\n this._destroyed = true;\n this._counterTimers.forEach(timer => {\n clearTimeout(timer);\n });\n for (const queue of this._partitionedQueue.values()) {\n for (const req of queue) {\n req.reject(new RateLimiterDestroyedError('Rate limiter was destroyed'));\n }\n }\n this._partitionedQueue.clear();\n }\n _getPartitionedQueue(partitionKey) {\n if (this._partitionedQueue.has(partitionKey)) {\n return this._partitionedQueue.get(partitionKey);\n }\n const newQueue = [];\n this._partitionedQueue.set(partitionKey, newQueue);\n return newQueue;\n }\n async _runRequest(reqSpec, partitionKey) {\n var _a;\n const queue = this._getPartitionedQueue(partitionKey);\n this._logger.debug(`doing a request for ${partitionKey ? `partition ${partitionKey}` : 'default partition'}, new queue length is ${queue.length}`);\n this._usedFromBucket.set(partitionKey, ((_a = this._usedFromBucket.get(partitionKey)) !== null && _a !== void 0 ? _a : 0) + 1);\n const { req, resolve, reject } = reqSpec;\n try {\n resolve(await this._callback(req));\n }\n catch (e) {\n reject(e);\n }\n finally {\n const counterTimer = setTimeout(() => {\n this._counterTimers.delete(counterTimer);\n const newUsed = this._usedFromBucket.get(partitionKey) - 1;\n this._usedFromBucket.set(partitionKey, newUsed);\n if (queue.length && newUsed < this._bucketSize) {\n this._runNextRequest(partitionKey);\n }\n }, this._timeFrame);\n this._counterTimers.add(counterTimer);\n }\n }\n _runNextRequest(partitionKey) {\n if (this._paused) {\n return;\n }\n const queue = this._getPartitionedQueue(partitionKey);\n const reqSpec = queue.shift();\n if (reqSpec) {\n void this._runRequest(reqSpec, partitionKey);\n }\n }\n}\n", "export { callTwitchApi, callTwitchApiRaw } from './apiCall.js';\nexport { createBroadcasterQuery } from './helpers/queries.external.js';\nexport { handleTwitchApiResponseError, transformTwitchApiResponse } from './helpers/transform.js';\nexport { HttpStatusCodeError } from './errors/HttpStatusCodeError.js';\n", "import { qsStringify } from '@twurple/common';\nimport { handleTwitchApiResponseError, transformTwitchApiResponse } from './helpers/transform.js';\nimport { getTwitchApiUrl } from './helpers/url.js';\n/**\n * Makes a call to the Twitch API using the given credentials, returning the raw Response object.\n *\n * @param options The configuration of the call.\n * @param clientId The client ID of your application.\n * @param accessToken The access token to call the API with.\n *\n * You need to obtain one using one of the [Twitch OAuth flows](https://dev.twitch.tv/docs/authentication/getting-tokens-oauth/).\n * @param authorizationType The type of Authorization header to send.\n *\n * Defaults to \"Bearer\" for Helix and \"OAuth\" for everything else.\n * @param fetchOptions Additional options to be passed to the `fetch` function.\n */\nexport async function callTwitchApiRaw(options, clientId, accessToken, authorizationType, fetchOptions = {}) {\n const type = options.type ?? 'helix';\n const url = getTwitchApiUrl(options.url, type);\n const params = qsStringify(options.query);\n // eslint-disable-next-line @typescript-eslint/naming-convention\n const headers = new Headers({ Accept: 'application/json' });\n let body = undefined;\n if (options.jsonBody) {\n body = JSON.stringify(options.jsonBody);\n headers.append('Content-Type', 'application/json');\n }\n if (clientId && type !== 'auth') {\n headers.append('Client-ID', clientId);\n }\n if (accessToken) {\n headers.append('Authorization', `${type === 'helix' ? authorizationType ?? 'Bearer' : 'OAuth'} ${accessToken}`);\n }\n const requestOptions = {\n ...fetchOptions,\n method: options.method ?? 'GET',\n headers,\n body,\n };\n return await fetch(`${url}${params}`, requestOptions);\n}\n/**\n * Makes a call to the Twitch API using given credentials.\n *\n * @param options The configuration of the call.\n * @param clientId The client ID of your application.\n * @param accessToken The access token to call the API with.\n *\n * You need to obtain one using one of the [Twitch OAuth flows](https://dev.twitch.tv/docs/authentication/getting-tokens-oauth/).\n * @param authorizationType The type of Authorization header to send.\n *\n * Defaults to \"Bearer\" for Helix and \"OAuth\" for everything else.\n * @param fetchOptions Additional options to be passed to the `fetch` function.\n */\nexport async function callTwitchApi(options, clientId, accessToken, authorizationType, fetchOptions = {}) {\n const response = await callTwitchApiRaw(options, clientId, accessToken, authorizationType, fetchOptions);\n await handleTwitchApiResponseError(response, options);\n return await transformTwitchApiResponse(response);\n}\n", "export { DataObject, getRawData, rawDataSymbol } from './DataObject.js';\nexport { getMockApiPort } from './mockApiPort.js';\nexport { qsStringify } from './qs.js';\nexport { checkRelationAssertion } from './relations.js';\nexport { rtfm } from './rtfm.js';\nexport { HelixExtension } from './extensions/HelixExtension.js';\nexport { CustomError } from './errors/CustomError.js';\nexport { HellFreezesOverError } from './errors/HellFreezesOverError.js';\nexport { RelationAssertionError } from './errors/RelationAssertionError.js';\nexport { extractUserId, extractUserName } from './userResolvers.js';\n", "import { klona } from 'klona';\n/** @private */\nexport const rawDataSymbol = Symbol('twurpleRawData');\n/**\n * Gets the raw data of a data object.\n *\n * @param obj The data object to get the raw data of.\n */\nexport function getRawData(obj) {\n return klona(obj[rawDataSymbol]);\n}\n/** @private */\nexport class DataObject {\n /** @private */ [rawDataSymbol];\n /** @private */\n constructor(data) {\n this[rawDataSymbol] = data;\n }\n}\n", "export function klona(x) {\n\tif (typeof x !== 'object') return x;\n\n\tvar k, tmp, str=Object.prototype.toString.call(x);\n\n\tif (str === '[object Object]') {\n\t\tif (x.constructor !== Object && typeof x.constructor === 'function') {\n\t\t\ttmp = new x.constructor();\n\t\t\tfor (k in x) {\n\t\t\t\tif (x.hasOwnProperty(k) && tmp[k] !== x[k]) {\n\t\t\t\t\ttmp[k] = klona(x[k]);\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\ttmp = {}; // null\n\t\t\tfor (k in x) {\n\t\t\t\tif (k === '__proto__') {\n\t\t\t\t\tObject.defineProperty(tmp, k, {\n\t\t\t\t\t\tvalue: klona(x[k]),\n\t\t\t\t\t\tconfigurable: true,\n\t\t\t\t\t\tenumerable: true,\n\t\t\t\t\t\twritable: true,\n\t\t\t\t\t});\n\t\t\t\t} else {\n\t\t\t\t\ttmp[k] = klona(x[k]);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn tmp;\n\t}\n\n\tif (str === '[object Array]') {\n\t\tk = x.length;\n\t\tfor (tmp=Array(k); k--;) {\n\t\t\ttmp[k] = klona(x[k]);\n\t\t}\n\t\treturn tmp;\n\t}\n\n\tif (str === '[object Set]') {\n\t\ttmp = new Set;\n\t\tx.forEach(function (val) {\n\t\t\ttmp.add(klona(val));\n\t\t});\n\t\treturn tmp;\n\t}\n\n\tif (str === '[object Map]') {\n\t\ttmp = new Map;\n\t\tx.forEach(function (val, key) {\n\t\t\ttmp.set(klona(key), klona(val));\n\t\t});\n\t\treturn tmp;\n\t}\n\n\tif (str === '[object Date]') {\n\t\treturn new Date(+x);\n\t}\n\n\tif (str === '[object RegExp]') {\n\t\ttmp = new RegExp(x.source, x.flags);\n\t\ttmp.lastIndex = x.lastIndex;\n\t\treturn tmp;\n\t}\n\n\tif (str === '[object DataView]') {\n\t\treturn new x.constructor( klona(x.buffer) );\n\t}\n\n\tif (str === '[object ArrayBuffer]') {\n\t\treturn x.slice(0);\n\t}\n\n\t// ArrayBuffer.isView(x)\n\t// ~> `new` bcuz `Buffer.slice` => ref\n\tif (str.slice(-6) === 'Array]') {\n\t\treturn new x.constructor(x);\n\t}\n\n\treturn x;\n}\n", "/** @private */\nexport function getMockApiPort() {\n try {\n return process.env.TWURPLE_MOCK_API_PORT ?? null;\n }\n catch {\n try {\n // @ts-ignore\n return import.meta.env.TWURPLE_MOCK_API_PORT ?? null; // eslint-disable-line @typescript-eslint/no-unsafe-return,@typescript-eslint/no-unsafe-member-access\n }\n catch {\n return null;\n }\n }\n}\n", "export function qsStringify(obj) {\n if (!obj) {\n return '';\n }\n const params = new URLSearchParams();\n for (const [key, value] of Object.entries(obj)) {\n if (value === null) {\n params.append(key, '');\n }\n else if (Array.isArray(value)) {\n for (const v of value) {\n params.append(key, v.toString());\n }\n }\n else if (value !== undefined) {\n params.append(key, value.toString());\n }\n }\n const result = params.toString();\n return result ? `?${result}` : '';\n}\n", "import { RelationAssertionError } from './errors/RelationAssertionError.js';\n/** @private */\nexport function checkRelationAssertion(value) {\n if (value == null) {\n throw new RelationAssertionError();\n }\n return value;\n}\n", "import { CustomError } from './CustomError.js';\n/**\n * Thrown when a relation that is expected to never be null does return null.\n */\nexport class RelationAssertionError extends CustomError {\n constructor() {\n super('Relation returned null - this may be a library bug or a race condition in your own code');\n }\n}\n", "/** @private */\nexport class CustomError extends Error {\n constructor(message, options) {\n super(message, options);\n // restore prototype chain\n Object.setPrototypeOf(this, new.target.prototype);\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n Error.captureStackTrace?.(this, new.target.constructor);\n }\n get name() {\n return this.constructor.name;\n }\n}\n", "/** @private */\nexport function rtfm(pkg, name, idKey) {\n return clazz => {\n const fn = idKey\n ? function () {\n // eslint-disable-next-line @typescript-eslint/restrict-template-expressions\n return `[${name}#${this[idKey]} - please check https://twurple.js.org/reference/${pkg}/classes/${name}.html for available properties]`;\n }\n : function () {\n return `[${name} - please check https://twurple.js.org/reference/${pkg}/classes/${name}.html for available properties]`;\n };\n Object.defineProperty(clazz.prototype, Symbol.for('nodejs.util.inspect.custom'), {\n value: fn,\n enumerable: false,\n });\n };\n}\n", "import { __decorate } from \"tslib\";\nimport { DataObject, rawDataSymbol } from '../DataObject.js';\nimport { rtfm } from '../rtfm.js';\n/**\n * A Twitch Extension.\n */\nlet HelixExtension = class HelixExtension extends DataObject {\n /**\n * The name of the extension's author.\n */\n get authorName() {\n return this[rawDataSymbol].author_name;\n }\n /**\n * Whether bits are enabled for the extension.\n */\n get bitsEnabled() {\n return this[rawDataSymbol].bits_enabled;\n }\n /**\n * Whether the extension can be installed.\n */\n get installable() {\n return this[rawDataSymbol].can_install;\n }\n /**\n * The location of the extension's configuration.\n */\n get configurationLocation() {\n return this[rawDataSymbol].configuration_location;\n }\n /**\n * The extension's description.\n */\n get description() {\n return this[rawDataSymbol].description;\n }\n /**\n * The URL of the extension's terms of service.\n */\n get tosUrl() {\n return this[rawDataSymbol].eula_tos_url;\n }\n /**\n * Whether the extension has support for sending chat messages.\n */\n get hasChatSupport() {\n return this[rawDataSymbol].has_chat_support;\n }\n /**\n * The URL of the extension's default sized icon.\n */\n get iconUrl() {\n return this[rawDataSymbol].icon_url;\n }\n /**\n * Gets the URL of the extension's icon in the given size.\n *\n * @param size The size of the icon.\n */\n getIconUrl(size) {\n return this[rawDataSymbol].icon_urls[size];\n }\n /**\n * The extension's ID.\n */\n get id() {\n return this[rawDataSymbol].id;\n }\n /**\n * The extension's name.\n */\n get name() {\n return this[rawDataSymbol].name;\n }\n /**\n * The URL of the extension's privacy policy.\n */\n get privacyPolicyUrl() {\n return this[rawDataSymbol].privacy_policy_url;\n }\n /**\n * Whether the extension requests its users to share their identity with it.\n */\n get requestsIdentityLink() {\n return this[rawDataSymbol].request_identity_link;\n }\n /**\n * The URLs of the extension's screenshots.\n */\n get screenshotUrls() {\n return this[rawDataSymbol].screenshot_urls;\n }\n /**\n * The extension's activity state.\n */\n get state() {\n return this[rawDataSymbol].state;\n }\n /**\n * The extension's level of support for subscriptions.\n */\n get subscriptionsSupportLevel() {\n return this[rawDataSymbol].subscriptions_support_level;\n }\n /**\n * The extension's feature summary.\n */\n get summary() {\n return this[rawDataSymbol].summary;\n }\n /**\n * The extension's support email address.\n */\n get supportEmail() {\n return this[rawDataSymbol].support_email;\n }\n /**\n * The extension's version.\n */\n get version() {\n return this[rawDataSymbol].version;\n }\n /**\n * The extension's feature summary for viewers.\n */\n get viewerSummary() {\n return this[rawDataSymbol].viewer_summary;\n }\n /**\n * The extension's feature summary for viewers.\n *\n * @deprecated Use `viewerSummary` instead.\n */\n get viewerSummery() {\n return this[rawDataSymbol].viewer_summary;\n }\n /**\n * The extension's allowed configuration URLs.\n */\n get allowedConfigUrls() {\n return this[rawDataSymbol].allowlisted_config_urls;\n }\n /**\n * The extension's allowed panel URLs.\n */\n get allowedPanelUrls() {\n return this[rawDataSymbol].allowlisted_panel_urls;\n }\n /**\n * The URL shown when a viewer opens the extension on a mobile device.\n *\n * If the extension does not have a mobile view, this is null.\n */\n get mobileViewerUrl() {\n return this[rawDataSymbol].views.mobile?.viewer_url ?? null;\n }\n /**\n * The URL shown to the viewer when the extension is shown as a panel.\n *\n * If the extension does not have a panel view, this is null.\n */\n get panelViewerUrl() {\n return this[rawDataSymbol].views.panel?.viewer_url ?? null;\n }\n /**\n * The height of the extension panel.\n *\n * If the extension does not have a panel view, this is null.\n */\n get panelHeight() {\n return this[rawDataSymbol].views.panel?.height ?? null;\n }\n /**\n * Whether the extension can link to external content from its panel view.\n *\n * If the extension does not have a panel view, this is null.\n */\n get panelCanLinkExternalContent() {\n return this[rawDataSymbol].views.panel?.can_link_external_content ?? null;\n }\n /**\n * The URL shown to the viewer when the extension is shown as a video overlay.\n *\n * If the extension does not have a overlay view, this is null.\n */\n get overlayViewerUrl() {\n return this[rawDataSymbol].views.video_overlay?.viewer_url ?? null;\n }\n /**\n * Whether the extension can link to external content from its overlay view.\n *\n * If the extension does not have a overlay view, this is null.\n */\n get overlayCanLinkExternalContent() {\n return this[rawDataSymbol].views.video_overlay?.can_link_external_content ?? null;\n }\n /**\n * The URL shown to the viewer when the extension is shown as a video component.\n *\n * If the extension does not have a component view, this is null.\n */\n get componentViewerUrl() {\n return this[rawDataSymbol].views.component?.viewer_url ?? null;\n }\n /**\n * The aspect width of the extension's component view.\n *\n * If the extension does not have a component view, this is null.\n */\n get componentAspectWidth() {\n return this[rawDataSymbol].views.component?.aspect_width ?? null;\n }\n /**\n * The aspect height of the extension's component view.\n *\n * If the extension does not have a component view, this is null.\n */\n get componentAspectHeight() {\n return this[rawDataSymbol].views.component?.aspect_height ?? null;\n }\n /**\n * The horizontal aspect ratio of the extension's component view.\n *\n * If the extension does not have a component view, this is null.\n */\n get componentAspectRatioX() {\n return this[rawDataSymbol].views.component?.aspect_ratio_x ?? null;\n }\n /**\n * The vertical aspect ratio of the extension's component view.\n *\n * If the extension does not have a component view, this is null.\n */\n get componentAspectRatioY() {\n return this[rawDataSymbol].views.component?.aspect_ratio_y ?? null;\n }\n /**\n * Whether the extension's component view should automatically scale.\n *\n * If the extension does not have a component view, this is null.\n */\n get componentAutoScales() {\n return this[rawDataSymbol].views.component?.autoscale ?? null;\n }\n /**\n * The base width of the extension's component view to use for scaling.\n *\n * If the extension does not have a component view, this is null.\n */\n get componentScalePixels() {\n return this[rawDataSymbol].views.component?.scale_pixels ?? null;\n }\n /**\n * The target height of the extension's component view.\n *\n * If the extension does not have a component view, this is null.\n */\n get componentTargetHeight() {\n return this[rawDataSymbol].views.component?.target_height ?? null;\n }\n /**\n * The size of the extension's component view.\n *\n * If the extension does not have a component view, this is null.\n */\n get componentSize() {\n return this[rawDataSymbol].views.component?.size ?? null;\n }\n /**\n * Whether zooming is enabled for the extension's component view.\n *\n * If the extension does not have a component view, this is null.\n */\n get componentZoom() {\n return this[rawDataSymbol].views.component?.zoom ?? null;\n }\n /**\n * The zoom pixels of the extension's component view.\n *\n * If the extension does not have a component view, this is null.\n */\n get componentZoomPixels() {\n return this[rawDataSymbol].views.component?.zoom_pixels ?? null;\n }\n /**\n * Whether the extension can link to external content from its component view.\n *\n * If the extension does not have a component view, this is null.\n */\n get componentCanLinkExternalContent() {\n return this[rawDataSymbol].views.component?.can_link_external_content ?? null;\n }\n /**\n * The URL shown to the viewer when the extension's configuration page is shown.\n *\n * If the extension does not have a config view, this is null.\n */\n get configViewerUrl() {\n return this[rawDataSymbol].views.config?.viewer_url ?? null;\n }\n /**\n * Whether the extension can link to external content from its config view.\n *\n * If the extension does not have a config view, this is null.\n */\n get configCanLinkExternalContent() {\n return this[rawDataSymbol].views.config?.can_link_external_content ?? null;\n }\n};\nHelixExtension = __decorate([\n rtfm('api', 'HelixExtension', 'id')\n], HelixExtension);\nexport { HelixExtension };\n", "import { CustomError } from './CustomError.js';\n/**\n * These are the kind of errors that should never happen.\n *\n * If you see one thrown, please file a bug in the GitHub issue tracker.\n */\nexport class HellFreezesOverError extends CustomError {\n constructor(message) {\n super(`${message} - this should never happen, please file a bug in the GitHub issue tracker`);\n }\n}\n", "/**\n * Extracts the user ID from an argument that is possibly an object containing that ID.\n *\n * @param user The user ID or object.\n */\nexport function extractUserId(user) {\n if (typeof user === 'string') {\n return user;\n }\n if (typeof user === 'number') {\n return user.toString(10);\n }\n return user.id;\n}\n/**\n * Extracts the username from an argument that is possibly an object containing that name.\n *\n * @param user The username or object.\n */\nexport function extractUserName(user) {\n return typeof user === 'string' ? user : user.name;\n}\n", "import { qsStringify } from '@twurple/common';\nimport { HttpStatusCodeError } from '../errors/HttpStatusCodeError.js';\n/** @private */\nexport async function handleTwitchApiResponseError(response, options) {\n if (!response.ok) {\n const isJson = response.headers.get('Content-Type') === 'application/json';\n const text = isJson ? JSON.stringify(await response.json(), null, 2) : await response.text();\n const params = qsStringify(options.query);\n const fullUrl = `${options.url}${params}`;\n throw new HttpStatusCodeError(response.status, response.statusText, fullUrl, options.method ?? 'GET', text, isJson);\n }\n}\n/** @private */\nexport async function transformTwitchApiResponse(response) {\n if (response.status === 204) {\n return undefined; // oof\n }\n const text = await response.text();\n if (!text) {\n return undefined; // mega oof - Twitch doesn't return a response when it should\n }\n return JSON.parse(text);\n}\n", "import { CustomError } from '@twurple/common';\n/**\n * Thrown whenever a HTTP error occurs. Some HTTP errors are handled in the library when they're expected.\n */\nexport class HttpStatusCodeError extends CustomError {\n _statusCode;\n _url;\n _method;\n _body;\n /** @private */\n constructor(_statusCode, statusText, _url, _method, _body, isJson) {\n super(`Encountered HTTP status code ${_statusCode}: ${statusText}\\n\\nURL: ${_url}\\nMethod: ${_method}\\nBody:\\n${!isJson && _body.length > 150 ? `${_body.slice(0, 147)}...` : _body}`);\n this._statusCode = _statusCode;\n this._url = _url;\n this._method = _method;\n this._body = _body;\n }\n /**\n * The HTTP status code of the error.\n */\n get statusCode() {\n return this._statusCode;\n }\n /**\n * The URL that was requested.\n */\n get url() {\n return this._url;\n }\n /**\n * The HTTP method that was used for the request.\n */\n get method() {\n return this._method;\n }\n /**\n * The body that was used for the request, as a string.\n */\n get body() {\n return this._body;\n }\n}\n", "import { getMockApiPort } from '@twurple/common';\n/** @internal */\nexport function getTwitchApiUrl(url, type) {\n const mockServerPort = getMockApiPort();\n switch (type) {\n case 'helix': {\n const unprefixedUrl = url.replace(/^\\//, '');\n return mockServerPort\n ? unprefixedUrl === 'eventsub/subscriptions'\n ? `http://localhost:${mockServerPort}/${unprefixedUrl}`\n : `http://localhost:${mockServerPort}/mock/${unprefixedUrl}`\n : `https://api.twitch.tv/helix/${unprefixedUrl}`;\n }\n case 'auth': {\n const unprefixedUrl = url.replace(/^\\//, '');\n return mockServerPort\n ? `http://localhost:${mockServerPort}/auth/${unprefixedUrl}`\n : `https://id.twitch.tv/oauth2/${unprefixedUrl}`;\n }\n case 'custom':\n return url;\n default:\n return url; // wat\n }\n}\n", "import { extractUserId } from '@twurple/common';\nexport function createBroadcasterQuery(user) {\n return {\n broadcaster_id: extractUserId(user),\n };\n}\n", "import { CustomError } from '@twurple/common';\n/**\n * Thrown whenever you try using invalid values in the client configuration.\n */\nexport class ConfigError extends CustomError {\n}\n", "import { ResponseBasedRateLimiter } from '@d-fischer/rate-limiter';\nimport { callTwitchApiRaw } from '@twurple/api-call';\n/** @internal */\nexport class HelixRateLimiter extends ResponseBasedRateLimiter {\n async doRequest({ options, clientId, accessToken, authorizationType, fetchOptions, }) {\n return await callTwitchApiRaw(options, clientId, accessToken, authorizationType, fetchOptions);\n }\n needsToRetryAfter(res) {\n if (res.status === 429 &&\n (!res.headers.has('ratelimit-remaining') || Number(res.headers.get('ratelimit-remaining')) === 0)) {\n return +res.headers.get('ratelimit-reset') * 1000 - Date.now();\n }\n return null;\n }\n getParametersFromResponse(res) {\n const { headers } = res;\n return {\n limit: +headers.get('ratelimit-limit'),\n remaining: +headers.get('ratelimit-remaining'),\n resetsAt: +headers.get('ratelimit-reset') * 1000,\n };\n }\n}\n", "import { __decorate } from \"tslib\";\nimport { Cacheable, CachedGetter } from '@d-fischer/cache-decorators';\nimport { ResponseBasedRateLimiter } from '@d-fischer/rate-limiter';\nimport { promiseWithResolvers } from '@d-fischer/shared-utils';\nimport { EventEmitter } from '@d-fischer/typed-event-emitter';\nimport { callTwitchApi, callTwitchApiRaw, handleTwitchApiResponseError, HttpStatusCodeError, transformTwitchApiResponse, } from '@twurple/api-call';\nimport { accessTokenIsExpired, InvalidTokenError, TokenInfo, } from '@twurple/auth';\nimport { HellFreezesOverError, rtfm } from '@twurple/common';\nimport * as retry from 'retry';\nimport { HelixBitsApi } from '../endpoints/bits/HelixBitsApi.js';\nimport { HelixChannelApi } from '../endpoints/channel/HelixChannelApi.js';\nimport { HelixChannelPointsApi } from '../endpoints/channelPoints/HelixChannelPointsApi.js';\nimport { HelixCharityApi } from '../endpoints/charity/HelixCharityApi.js';\nimport { HelixChatApi } from '../endpoints/chat/HelixChatApi.js';\nimport { HelixClipApi } from '../endpoints/clip/HelixClipApi.js';\nimport { HelixContentClassificationLabelApi } from '../endpoints/contentClassificationLabels/HelixContentClassificationLabelApi.js';\nimport { HelixEntitlementApi } from '../endpoints/entitlements/HelixEntitlementApi.js';\nimport { HelixEventSubApi } from '../endpoints/eventSub/HelixEventSubApi.js';\nimport { HelixExtensionsApi } from '../endpoints/extensions/HelixExtensionsApi.js';\nimport { HelixGameApi } from '../endpoints/game/HelixGameApi.js';\nimport { HelixGoalApi } from '../endpoints/goals/HelixGoalApi.js';\nimport { HelixHypeTrainApi } from '../endpoints/hypeTrain/HelixHypeTrainApi.js';\nimport { HelixModerationApi } from '../endpoints/moderation/HelixModerationApi.js';\nimport { HelixPollApi } from '../endpoints/poll/HelixPollApi.js';\nimport { HelixPredictionApi } from '../endpoints/prediction/HelixPredictionApi.js';\nimport { HelixRaidApi } from '../endpoints/raids/HelixRaidApi.js';\nimport { HelixScheduleApi } from '../endpoints/schedule/HelixScheduleApi.js';\nimport { HelixSearchApi } from '../endpoints/search/HelixSearchApi.js';\nimport { HelixStreamApi } from '../endpoints/stream/HelixStreamApi.js';\nimport { HelixSubscriptionApi } from '../endpoints/subscriptions/HelixSubscriptionApi.js';\nimport { HelixTeamApi } from '../endpoints/team/HelixTeamApi.js';\nimport { HelixUserApi } from '../endpoints/user/HelixUserApi.js';\nimport { HelixVideoApi } from '../endpoints/video/HelixVideoApi.js';\nimport { HelixWhisperApi } from '../endpoints/whisper/HelixWhisperApi.js';\nimport { ApiReportedRequest } from '../reporting/ApiReportedRequest.js';\n/** @private */\nlet BaseApiClient = class BaseApiClient extends EventEmitter {\n _config;\n _logger;\n _rateLimiter;\n onRequest = this.registerEvent();\n /** @internal */\n constructor(config, logger, rateLimiter) {\n super();\n this._config = config;\n this._logger = logger;\n this._rateLimiter = rateLimiter;\n }\n /**\n * Requests scopes from the auth provider for the given user.\n *\n * @param user The user to request scopes for.\n * @param scopes The scopes to request.\n */\n async requestScopesForUser(user, scopes) {\n await this._config.authProvider.getAccessTokenForUser(user, ...scopes.map(scope => [scope]));\n }\n /**\n * Gets information about your access token.\n */\n async getTokenInfo() {\n try {\n const data = await this.callApi({ type: 'auth', url: 'validate' });\n return new TokenInfo(data);\n }\n catch (e) {\n if (e instanceof HttpStatusCodeError && e.statusCode === 401) {\n throw new InvalidTokenError({ cause: e });\n }\n throw e;\n }\n }\n /**\n * Makes a call to the Twitch API using your access token.\n *\n * @param options The configuration of the call.\n */\n async callApi(options) {\n const { authProvider } = this._config;\n const shouldAuth = options.auth ?? true;\n if (!shouldAuth) {\n return await callTwitchApi(options, authProvider.clientId, undefined, undefined, this._config.fetchOptions);\n }\n let forceUser = false;\n if (options.forceType) {\n switch (options.forceType) {\n case 'app': {\n if (!authProvider.getAppAccessToken) {\n throw new Error('Tried to make an API call that requires an app access token but your auth provider does not support that');\n }\n const accessToken = await authProvider.getAppAccessToken();\n return await this._callApiUsingInitialToken(options, accessToken);\n }\n case 'user': {\n forceUser = true;\n break;\n }\n default: {\n throw new HellFreezesOverError(`Unknown forced token type: ${options.forceType}`);\n }\n }\n }\n if (options.scopes) {\n forceUser = true;\n }\n if (forceUser) {\n const contextUserId = options.canOverrideScopedUserContext\n ? this._getUserIdFromRequestContext(options.userId)\n : options.userId;\n if (!contextUserId) {\n throw new Error('Tried to make an API call with a user context but no context user ID');\n }\n const accessToken = await authProvider.getAccessTokenForUser(contextUserId, options.scopes);\n if (!accessToken) {\n throw new Error(`Tried to make an API call with a user context for user ID ${contextUserId} but no token was found`);\n }\n if (accessTokenIsExpired(accessToken) && authProvider.refreshAccessTokenForUser) {\n const newAccessToken = await authProvider.refreshAccessTokenForUser(contextUserId);\n return await this._callApiUsingInitialToken(options, newAccessToken, true);\n }\n return await this._callApiUsingInitialToken(options, accessToken);\n }\n const requestContextUserId = this._getUserIdFromRequestContext(options.userId);\n const accessToken = requestContextUserId === null\n ? await authProvider.getAnyAccessToken()\n : await authProvider.getAnyAccessToken(requestContextUserId ?? options.userId);\n if (accessTokenIsExpired(accessToken) && accessToken.userId && authProvider.refreshAccessTokenForUser) {\n const newAccessToken = await authProvider.refreshAccessTokenForUser(accessToken.userId);\n return await this._callApiUsingInitialToken(options, newAccessToken, true);\n }\n return await this._callApiUsingInitialToken(options, accessToken);\n }\n /**\n * The Helix bits API methods.\n */\n get bits() {\n return new HelixBitsApi(this);\n }\n /**\n * The Helix channels API methods.\n */\n get channels() {\n return new HelixChannelApi(this);\n }\n /**\n * The Helix channel points API methods.\n */\n get channelPoints() {\n return new HelixChannelPointsApi(this);\n }\n /**\n * The Helix charity API methods.\n */\n get charity() {\n return new HelixCharityApi(this);\n }\n /**\n * The Helix chat API methods.\n */\n get chat() {\n return new HelixChatApi(this);\n }\n /**\n * The Helix clips API methods.\n */\n get clips() {\n return new HelixClipApi(this);\n }\n /**\n * The Helix content classification label API methods.\n */\n get contentClassificationLabels() {\n return new HelixContentClassificationLabelApi(this);\n }\n /**\n * The Helix entitlement API methods.\n */\n get entitlements() {\n return new HelixEntitlementApi(this);\n }\n /**\n * The Helix EventSub API methods.\n */\n get eventSub() {\n return new HelixEventSubApi(this);\n }\n /**\n * The Helix extensions API methods.\n */\n get extensions() {\n return new HelixExtensionsApi(this);\n }\n /**\n * The Helix game API methods.\n */\n get games() {\n return new HelixGameApi(this);\n }\n /**\n * The Helix Hype Train API methods.\n */\n get hypeTrain() {\n return new HelixHypeTrainApi(this);\n }\n /**\n * The Helix goal API methods.\n */\n get goals() {\n return new HelixGoalApi(this);\n }\n /**\n * The Helix moderation API methods.\n */\n get moderation() {\n return new HelixModerationApi(this);\n }\n /**\n * The Helix poll API methods.\n */\n get polls() {\n return new HelixPollApi(this);\n }\n /**\n * The Helix prediction API methods.\n */\n get predictions() {\n return new HelixPredictionApi(this);\n }\n /**\n * The Helix raid API methods.\n */\n get raids() {\n return new HelixRaidApi(this);\n }\n /**\n * The Helix schedule API methods.\n */\n get schedule() {\n return new HelixScheduleApi(this);\n }\n /**\n * The Helix search API methods.\n */\n get search() {\n return new HelixSearchApi(this);\n }\n /**\n * The Helix stream API methods.\n */\n get streams() {\n return new HelixStreamApi(this);\n }\n /**\n * The Helix subscription API methods.\n */\n get subscriptions() {\n return new HelixSubscriptionApi(this);\n }\n /**\n * The Helix team API methods.\n */\n get teams() {\n return new HelixTeamApi(this);\n }\n /**\n * The Helix user API methods.\n */\n get users() {\n return new HelixUserApi(this);\n }\n /**\n * The Helix video API methods.\n */\n get videos() {\n return new HelixVideoApi(this);\n }\n /**\n * The API methods that deal with whispers.\n */\n get whispers() {\n return new HelixWhisperApi(this);\n }\n /**\n * Statistics on the rate limiter for the Helix API.\n */\n get rateLimiterStats() {\n if (this._rateLimiter instanceof ResponseBasedRateLimiter) {\n return this._rateLimiter.stats;\n }\n return null;\n }\n /** @private */\n get _authProvider() {\n return this._config.authProvider;\n }\n /** @internal */\n get _batchDelay() {\n return this._config.batchDelay ?? 0;\n }\n // null means app access, undefined means none specified\n /** @internal */\n _getUserIdFromRequestContext(contextUserId) {\n return contextUserId;\n }\n async _callApiUsingInitialToken(options, accessToken, wasRefreshed = false) {\n const { authProvider } = this._config;\n const { authorizationType } = authProvider;\n let response = await this._callApiInternal(options, authProvider.clientId, accessToken.accessToken, authorizationType);\n if (response.status === 401 && !wasRefreshed) {\n if (accessToken.userId) {\n if (authProvider.refreshAccessTokenForUser) {\n const token = await authProvider.refreshAccessTokenForUser(accessToken.userId);\n response = await this._callApiInternal(options, authProvider.clientId, token.accessToken, authorizationType);\n }\n }\n else if (authProvider.getAppAccessToken) {\n const token = await authProvider.getAppAccessToken(true);\n response = await this._callApiInternal(options, authProvider.clientId, token.accessToken, authorizationType);\n }\n }\n this.emit(this.onRequest, new ApiReportedRequest(options, response.status, accessToken.userId ?? null));\n await handleTwitchApiResponseError(response, options);\n return await transformTwitchApiResponse(response);\n }\n async _callApiInternal(options, clientId, accessToken, authorizationType) {\n const { fetchOptions } = this._config;\n const type = options.type ?? 'helix';\n this._logger.debug(`Calling ${type} API: ${options.method ?? 'GET'} ${options.url}`);\n this._logger.trace(`Query: ${JSON.stringify(options.query)}`);\n if (options.jsonBody) {\n this._logger.trace(`Request body: ${JSON.stringify(options.jsonBody)}`);\n }\n const op = retry.operation({\n retries: 3,\n minTimeout: 500,\n factor: 2,\n });\n const { promise, resolve, reject } = promiseWithResolvers();\n op.attempt(async () => {\n try {\n const response = type === 'helix'\n ? await this._rateLimiter.request({\n options,\n clientId,\n accessToken,\n authorizationType,\n fetchOptions,\n })\n : await callTwitchApiRaw(options, clientId, accessToken, authorizationType, fetchOptions);\n if (!response.ok && response.status >= 500 && response.status < 600) {\n await handleTwitchApiResponseError(response, options);\n }\n resolve(response);\n }\n catch (e) {\n if (op.retry(e)) {\n return;\n }\n reject(op.mainError());\n }\n });\n const result = await promise;\n this._logger.debug(`Called ${type} API: ${options.method ?? 'GET'} ${options.url} - result: ${result.status}`);\n return result;\n }\n};\n__decorate([\n CachedGetter()\n], BaseApiClient.prototype, \"bits\", null);\n__decorate([\n CachedGetter()\n], BaseApiClient.prototype, \"channels\", null);\n__decorate([\n CachedGetter()\n], BaseApiClient.prototype, \"channelPoints\", null);\n__decorate([\n CachedGetter()\n], BaseApiClient.prototype, \"charity\", null);\n__decorate([\n CachedGetter()\n], BaseApiClient.prototype, \"chat\", null);\n__decorate([\n CachedGetter()\n], BaseApiClient.prototype, \"clips\", null);\n__decorate([\n CachedGetter()\n], BaseApiClient.prototype, \"contentClassificationLabels\", null);\n__decorate([\n CachedGetter()\n], BaseApiClient.prototype, \"entitlements\", null);\n__decorate([\n CachedGetter()\n], BaseApiClient.prototype, \"eventSub\", null);\n__decorate([\n CachedGetter()\n], BaseApiClient.prototype, \"extensions\", null);\n__decorate([\n CachedGetter()\n], BaseApiClient.prototype, \"games\", null);\n__decorate([\n CachedGetter()\n], BaseApiClient.prototype, \"hypeTrain\", null);\n__decorate([\n CachedGetter()\n], BaseApiClient.prototype, \"goals\", null);\n__decorate([\n CachedGetter()\n], BaseApiClient.prototype, \"moderation\", null);\n__decorate([\n CachedGetter()\n], BaseApiClient.prototype, \"polls\", null);\n__decorate([\n CachedGetter()\n], BaseApiClient.prototype, \"predictions\", null);\n__decorate([\n CachedGetter()\n], BaseApiClient.prototype, \"raids\", null);\n__decorate([\n CachedGetter()\n], BaseApiClient.prototype, \"schedule\", null);\n__decorate([\n CachedGetter()\n], BaseApiClient.prototype, \"search\", null);\n__decorate([\n CachedGetter()\n], BaseApiClient.prototype, \"streams\", null);\n__decorate([\n CachedGetter()\n], BaseApiClient.prototype, \"subscriptions\", null);\n__decorate([\n CachedGetter()\n], BaseApiClient.prototype, \"teams\", null);\n__decorate([\n CachedGetter()\n], BaseApiClient.prototype, \"users\", null);\n__decorate([\n CachedGetter()\n], BaseApiClient.prototype, \"videos\", null);\n__decorate([\n CachedGetter()\n], BaseApiClient.prototype, \"whispers\", null);\nBaseApiClient = __decorate([\n Cacheable,\n rtfm('api', 'ApiClient')\n], BaseApiClient);\nexport { BaseApiClient };\n", "export { Cacheable } from \"./decorators/Cacheable.mjs\";\nexport { Cached } from \"./decorators/Cached.mjs\";\nexport { CachedGetter } from \"./decorators/CachedGetter.mjs\";\nexport { ClearsCache } from \"./decorators/ClearsCache.mjs\";\nexport { createCacheKey } from \"./utils/createCacheKey.mjs\";\n", "import { createCacheKey } from \"../utils/createCacheKey.mjs\";\nconst cacheSymbol = Symbol('cache');\nexport function Cacheable(cls) {\n var _a, _b;\n return _b = class extends cls {\n constructor() {\n super(...arguments);\n this[_a] = new Map();\n }\n getFromCache(cacheKey) {\n this._cleanCache();\n if (this[cacheSymbol].has(cacheKey)) {\n const entry = this[cacheSymbol].get(cacheKey);\n if (entry) {\n return entry.value;\n }\n }\n return undefined;\n }\n setCache(cacheKey, value, timeInSeconds) {\n this[cacheSymbol].set(cacheKey, {\n value,\n expires: Date.now() + timeInSeconds * 1000\n });\n }\n removeFromCache(cacheKey, prefix) {\n const internalCacheKey = this._getInternalCacheKey(cacheKey, prefix);\n if (prefix) {\n this[cacheSymbol].forEach((val, key) => {\n if (key.startsWith(internalCacheKey)) {\n this[cacheSymbol].delete(key);\n }\n });\n }\n else {\n this[cacheSymbol].delete(internalCacheKey);\n }\n }\n _cleanCache() {\n const now = Date.now();\n this[cacheSymbol].forEach((val, key) => {\n if (val.expires < now) {\n this[cacheSymbol].delete(key);\n }\n });\n }\n _getInternalCacheKey(cacheKey, prefix) {\n if (typeof cacheKey === 'string') {\n let internalCacheKey = cacheKey;\n if (!internalCacheKey.endsWith('/')) {\n internalCacheKey += '/';\n }\n return internalCacheKey;\n }\n else {\n const propName = cacheKey.shift();\n return createCacheKey(propName, cacheKey, prefix);\n }\n }\n },\n _a = cacheSymbol,\n _b;\n}\n", "function createSingleCacheKey(param) {\n // noinspection FallThroughInSwitchStatementJS\n switch (typeof param) {\n case 'undefined': {\n return '';\n }\n case 'object': {\n if (param === null) {\n return '';\n }\n if ('cacheKey' in param) {\n return param.cacheKey;\n }\n const objKey = JSON.stringify(param);\n if (objKey !== '{}') {\n return objKey;\n }\n }\n // fallthrough\n default: {\n return param.toString();\n }\n }\n}\nexport function createCacheKey(propName, params, prefix) {\n return [propName, ...params.map(createSingleCacheKey)].join('/') + (prefix ? '/' : '');\n}\n", "import { createCacheKey } from \"../utils/createCacheKey.mjs\";\nexport function CachedGetter(timeInSeconds = Infinity) {\n return function (target, propName, descriptor) {\n if (descriptor.get) {\n // eslint-disable-next-line @typescript-eslint/unbound-method\n const origFn = descriptor.get;\n descriptor.get = function () {\n const cacheKey = createCacheKey(propName, []);\n const cachedValue = this.getFromCache(cacheKey);\n if (cachedValue) {\n return cachedValue;\n }\n const result = origFn.call(this);\n this.setCache(cacheKey, result, timeInSeconds);\n return result;\n };\n }\n return descriptor;\n };\n}\n", "export { EventEmitter } from \"./EventEmitter.mjs\";\nexport { Listener } from \"./Listener.mjs\";\n", "import { Listener } from \"./Listener.mjs\";\nexport class EventEmitter {\n constructor() {\n this._eventListeners = new Map();\n this._internalEventListeners = new Map();\n }\n on(event, listener) {\n return this._addListener(false, event, listener);\n }\n addListener(event, listener) {\n return this._addListener(false, event, listener);\n }\n removeListener(idOrEvent, listener) {\n this._removeListener(false, idOrEvent, listener);\n }\n registerEvent() {\n const eventBinder = (handler) => this.addListener(eventBinder, handler);\n return eventBinder;\n }\n emit(event, ...args) {\n if (this._eventListeners.has(event)) {\n for (const listener of this._eventListeners.get(event)) {\n listener(...args);\n }\n }\n if (this._internalEventListeners.has(event)) {\n for (const listener of this._internalEventListeners.get(event)) {\n listener(...args);\n }\n }\n }\n registerInternalEvent() {\n const eventBinder = (handler) => this.addInternalListener(eventBinder, handler);\n return eventBinder;\n }\n addInternalListener(event, listener) {\n return this._addListener(true, event, listener);\n }\n removeInternalListener(idOrEvent, listener) {\n this._removeListener(true, idOrEvent, listener);\n }\n _addListener(internal, event, listener) {\n const listenerMap = internal ? this._eventListeners : this._internalEventListeners;\n if (listenerMap.has(event)) {\n listenerMap.get(event).push(listener);\n }\n else {\n listenerMap.set(event, [listener]);\n }\n return new Listener(this, event, listener, internal);\n }\n _removeListener(internal, idOrEvent, listener) {\n const listenerMap = internal ? this._eventListeners : this._internalEventListeners;\n if (!idOrEvent) {\n listenerMap.clear();\n }\n else if (typeof idOrEvent === 'object') {\n const id = idOrEvent;\n this._removeListener(id._internal, id.event, id.listener);\n }\n else {\n const event = idOrEvent;\n if (listenerMap.has(event)) {\n if (listener) {\n const listeners = listenerMap.get(event);\n let idx = 0;\n while ((idx = listeners.indexOf(listener)) !== -1) {\n listeners.splice(idx, 1);\n }\n }\n else {\n listenerMap.delete(event);\n }\n }\n }\n }\n}\n", "export class Listener {\n /** @private */\n constructor(owner, event, listener, \n /** @private */ _internal = false) {\n this.owner = owner;\n this.event = event;\n this.listener = listener;\n this._internal = _internal;\n }\n unbind() {\n this.owner.removeListener(this);\n }\n}\n", "export { accessTokenIsExpired, getExpiryDateOfAccessToken } from './AccessToken.js';\nexport { exchangeCode, getAppToken, getTokenInfo, getValidTokenFromProviderForUser, getValidTokenFromProviderForIntent, refreshUserToken, revokeToken, } from './helpers.js';\nexport { TokenFetcher } from './TokenFetcher.js';\nexport { TokenInfo } from './TokenInfo.js';\nexport { AppTokenAuthProvider } from './providers/AppTokenAuthProvider.js';\nexport { RefreshingAuthProvider } from './providers/RefreshingAuthProvider.js';\nexport { StaticAuthProvider } from './providers/StaticAuthProvider.js';\nexport { CachedRefreshFailureError } from './errors/CachedRefreshFailureError.js';\nexport { IntermediateUserRemovalError } from './errors/IntermediateUserRemovalError.js';\nexport { InvalidTokenError } from './errors/InvalidTokenError.js';\nexport { InvalidTokenTypeError } from './errors/InvalidTokenTypeError.js';\nexport { UnknownIntentError } from './errors/UnknownIntentError.js';\n", "import { mapNullable } from '@d-fischer/shared-utils';\n// one minute\nconst EXPIRY_GRACE_PERIOD = 60000;\nfunction getExpiryMillis(token) {\n return mapNullable(token.expiresIn, _ => token.obtainmentTimestamp + _ * 1000 - EXPIRY_GRACE_PERIOD);\n}\n/**\n * Calculates the date when the access token will expire.\n *\n * A one-minute grace period is applied for smooth handling of API latency.\n *\n * May be `null`, in which case the token does not expire.\n * This can only be the case with very old Client IDs.\n *\n * @param token The access token.\n */\nexport function getExpiryDateOfAccessToken(token) {\n return mapNullable(getExpiryMillis(token), _ => new Date(_));\n}\n/**\n * Calculates whether the given access token is expired.\n *\n * A one-minute grace period is applied for smooth handling of API latency.\n *\n * @param token The access token.\n */\nexport function accessTokenIsExpired(token) {\n return mapNullable(getExpiryMillis(token), _ => Date.now() > _) ?? false;\n}\n", "import { callTwitchApi, HttpStatusCodeError } from '@twurple/api-call';\nimport { InvalidTokenError } from './errors/InvalidTokenError.js';\nimport { InvalidTokenTypeError } from './errors/InvalidTokenTypeError.js';\nimport { createExchangeCodeQuery, createGetAppTokenQuery, createRefreshTokenQuery, createRevokeTokenQuery, } from './helpers.external.js';\nimport { TokenInfo } from './TokenInfo.js';\n/** @internal */\nfunction createAccessTokenFromData(data) {\n return {\n accessToken: data.access_token,\n refreshToken: data.refresh_token || null,\n scope: data.scope ?? [],\n expiresIn: data.expires_in ?? null,\n obtainmentTimestamp: Date.now(),\n };\n}\n/**\n * Gets an access token with your client credentials and an authorization code.\n *\n * @param clientId The client ID of your application.\n * @param clientSecret The client secret of your application.\n * @param code The authorization code.\n * @param redirectUri The redirect URI.\n *\n * This serves no real purpose here, but must still match one of the redirect URIs you configured in the Twitch Developer dashboard.\n */\nexport async function exchangeCode(clientId, clientSecret, code, redirectUri) {\n return createAccessTokenFromData(await callTwitchApi({\n type: 'auth',\n url: 'token',\n method: 'POST',\n query: createExchangeCodeQuery(clientId, clientSecret, code, redirectUri),\n }));\n}\n/**\n * Gets an app access token with your client credentials.\n *\n * @param clientId The client ID of your application.\n * @param clientSecret The client secret of your application.\n */\nexport async function getAppToken(clientId, clientSecret) {\n return createAccessTokenFromData(await callTwitchApi({\n type: 'auth',\n url: 'token',\n method: 'POST',\n query: createGetAppTokenQuery(clientId, clientSecret),\n }));\n}\n/**\n * Refreshes an expired access token with your client credentials and the refresh token that was given by the initial authentication.\n *\n * @param clientId The client ID of your application.\n * @param clientSecret The client secret of your application.\n * @param refreshToken The refresh token.\n */\nexport async function refreshUserToken(clientId, clientSecret, refreshToken) {\n return createAccessTokenFromData(await callTwitchApi({\n type: 'auth',\n url: 'token',\n method: 'POST',\n query: createRefreshTokenQuery(clientId, clientSecret, refreshToken),\n }));\n}\n/**\n * Revokes an access token.\n *\n * @param clientId The client ID of your application.\n * @param accessToken The access token.\n */\nexport async function revokeToken(clientId, accessToken) {\n await callTwitchApi({\n type: 'auth',\n url: 'revoke',\n method: 'POST',\n query: createRevokeTokenQuery(clientId, accessToken),\n });\n}\n/**\n * Gets information about an access token.\n *\n * @param accessToken The access token to get the information of.\n * @param clientId The client ID of your application.\n *\n * You need to obtain one using one of the [Twitch OAuth flows](https://dev.twitch.tv/docs/authentication/getting-tokens-oauth/).\n */\nexport async function getTokenInfo(accessToken, clientId) {\n try {\n const data = await callTwitchApi({ type: 'auth', url: 'validate' }, clientId, accessToken);\n return new TokenInfo(data);\n }\n catch (e) {\n if (e instanceof HttpStatusCodeError && e.statusCode === 401) {\n throw new InvalidTokenError({ cause: e });\n }\n throw e;\n }\n}\n/** @private */\nexport async function getValidTokenFromProviderForUser(provider, userId, scopes, logger) {\n let lastTokenError = null;\n let foundUser = false;\n try {\n const accessToken = await provider.getAccessTokenForUser(userId, scopes);\n if (accessToken) {\n foundUser = true;\n // check validity\n const tokenInfo = await getTokenInfo(accessToken.accessToken);\n return { accessToken, tokenInfo };\n }\n }\n catch (e) {\n if (e instanceof InvalidTokenError) {\n lastTokenError = e;\n }\n else {\n logger?.error(`Retrieving an access token failed: ${e.message}`);\n }\n }\n if (foundUser) {\n logger?.warn('No valid token available; trying to refresh');\n if (provider.refreshAccessTokenForUser) {\n try {\n const newToken = await provider.refreshAccessTokenForUser(userId);\n // check validity\n const tokenInfo = await getTokenInfo(newToken.accessToken);\n return { accessToken: newToken, tokenInfo };\n }\n catch (e) {\n if (e instanceof InvalidTokenError) {\n lastTokenError = e;\n }\n else {\n logger?.error(`Refreshing the access token failed: ${e.message}`);\n }\n }\n }\n }\n throw lastTokenError ?? new Error('Could not retrieve a valid token');\n}\n/** @private */\nexport async function getValidTokenFromProviderForIntent(provider, intent, scopes, logger) {\n let lastTokenError = null;\n let foundUser = false;\n if (!provider.getAccessTokenForIntent) {\n throw new InvalidTokenTypeError(`This call requires an AuthProvider that supports intents.\nPlease use an auth provider that does, such as \\`RefreshingAuthProvider\\`.`);\n }\n try {\n const accessToken = await provider.getAccessTokenForIntent(intent, scopes);\n if (accessToken) {\n foundUser = true;\n // check validity\n const tokenInfo = await getTokenInfo(accessToken.accessToken);\n return { accessToken, tokenInfo };\n }\n }\n catch (e) {\n if (e instanceof InvalidTokenError) {\n lastTokenError = e;\n }\n else {\n logger?.error(`Retrieving an access token failed: ${e.message}`);\n }\n }\n if (foundUser) {\n logger?.warn('No valid token available; trying to refresh');\n if (provider.refreshAccessTokenForIntent) {\n try {\n const newToken = await provider.refreshAccessTokenForIntent(intent);\n // check validity\n const tokenInfo = await getTokenInfo(newToken.accessToken);\n return { accessToken: newToken, tokenInfo };\n }\n catch (e) {\n if (e instanceof InvalidTokenError) {\n lastTokenError = e;\n }\n else {\n logger?.error(`Refreshing the access token failed: ${e.message}`);\n }\n }\n }\n }\n throw lastTokenError ?? new Error('Could not retrieve a valid token');\n}\nconst scopeEquivalencies = new Map([\n ['channel_commercial', ['channel:edit:commercial']],\n ['channel_editor', ['channel:manage:broadcast']],\n ['channel_read', ['channel:read:stream_key']],\n ['channel_subscriptions', ['channel:read:subscriptions']],\n ['user_blocks_read', ['user:read:blocked_users']],\n ['user_blocks_edit', ['user:manage:blocked_users']],\n ['user_follows_edit', ['user:edit:follows']],\n ['user_read', ['user:read:email']],\n ['user_subscriptions', ['user:read:subscriptions']],\n ['user:edit:broadcast', ['channel:manage:broadcast', 'channel:manage:extensions']],\n]);\n/**\n * Compares scopes for a non-upgradable {@link AuthProvider} instance.\n *\n * @param scopesToCompare The scopes to compare against.\n * @param requestedScopes The scopes you requested.\n */\nexport function compareScopes(scopesToCompare, requestedScopes) {\n if (requestedScopes?.length) {\n const scopes = new Set(scopesToCompare.flatMap(scope => [scope, ...(scopeEquivalencies.get(scope) ?? [])]));\n if (requestedScopes.every(scope => !scopes.has(scope))) {\n const scopesStr = requestedScopes.join(', ');\n throw new Error(`This token does not have any of the requested scopes (${scopesStr}) and can not be upgraded.\nIf you need dynamically upgrading scopes, please implement the AuthProvider interface accordingly:\n\n\\thttps://twurple.js.org/reference/auth/interfaces/AuthProvider.html`);\n }\n }\n}\n/**\n * Compares scope sets for a non-upgradable {@link AuthProvider} instance.\n *\n * @param scopesToCompare The scopes to compare against.\n * @param requestedScopeSets The scope sets you requested.\n */\nexport function compareScopeSets(scopesToCompare, requestedScopeSets) {\n for (const requestedScopes of requestedScopeSets) {\n compareScopes(scopesToCompare, requestedScopes);\n }\n}\n/**\n * Compares scopes for a non-upgradable `AuthProvider` instance, loading them from the token if necessary,\n * and returns them together with the user ID.\n *\n * @param clientId The client ID of your application.\n * @param token The access token.\n * @param userId The user ID that was already loaded.\n * @param loadedScopes The scopes that were already loaded.\n * @param requestedScopeSets The scope sets you requested.\n */\nexport async function loadAndCompareTokenInfo(clientId, token, userId, loadedScopes, requestedScopeSets) {\n // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing\n if (requestedScopeSets?.length || !userId) {\n const userInfo = await getTokenInfo(token, clientId);\n if (!userInfo.userId) {\n throw new Error('Trying to use an app access token as a user access token');\n }\n const scopesToCompare = loadedScopes ?? userInfo.scopes;\n if (requestedScopeSets) {\n compareScopeSets(scopesToCompare, requestedScopeSets.filter((val) => Boolean(val)));\n }\n return [scopesToCompare, userInfo.userId];\n }\n return [loadedScopes, userId];\n}\n", "import { CustomError } from '@twurple/common';\n/**\n * Thrown whenever an invalid token is supplied.\n */\nexport class InvalidTokenError extends CustomError {\n /** @private */\n constructor(options) {\n super('Invalid token supplied', options);\n }\n}\n", "/** @internal */\nexport function createExchangeCodeQuery(clientId, clientSecret, code, redirectUri) {\n return {\n grant_type: 'authorization_code',\n client_id: clientId,\n client_secret: clientSecret,\n code,\n redirect_uri: redirectUri,\n };\n}\n/** @internal */\nexport function createGetAppTokenQuery(clientId, clientSecret) {\n return {\n grant_type: 'client_credentials',\n client_id: clientId,\n client_secret: clientSecret,\n };\n}\n/** @internal */\nexport function createRefreshTokenQuery(clientId, clientSecret, refreshToken) {\n return {\n grant_type: 'refresh_token',\n client_id: clientId,\n client_secret: clientSecret,\n refresh_token: refreshToken,\n };\n}\n/** @internal */\nexport function createRevokeTokenQuery(clientId, accessToken) {\n return {\n client_id: clientId,\n token: accessToken,\n };\n}\n", "import { __decorate } from \"tslib\";\nimport { mapNullable } from '@d-fischer/shared-utils';\nimport { DataObject, rawDataSymbol, rtfm } from '@twurple/common';\n/**\n * Information about an access token.\n */\nlet TokenInfo = class TokenInfo extends DataObject {\n _obtainmentDate;\n /** @internal */\n constructor(data) {\n super(data);\n this._obtainmentDate = new Date();\n }\n /**\n * The client ID.\n */\n get clientId() {\n return this[rawDataSymbol].client_id;\n }\n /**\n * The ID of the authenticated user.\n */\n get userId() {\n return this[rawDataSymbol].user_id ?? null;\n }\n /**\n * The name of the authenticated user.\n */\n get userName() {\n return this[rawDataSymbol].login ?? null;\n }\n /**\n * The scopes for which the token is valid.\n */\n get scopes() {\n return this[rawDataSymbol].scopes;\n }\n /**\n * The time when the token will expire.\n *\n * If this returns null, it means that the token never expires (happens with some old client IDs).\n */\n get expiryDate() {\n return mapNullable(this[rawDataSymbol].expires_in, v => new Date(this._obtainmentDate.getTime() + v * 1000));\n }\n};\nTokenInfo = __decorate([\n rtfm('auth', 'TokenInfo', 'clientId')\n], TokenInfo);\nexport { TokenInfo };\n", "import { promiseWithResolvers } from '@d-fischer/shared-utils';\nexport class TokenFetcher {\n _executor;\n _newTokenScopeSets = [];\n _newTokenPromise = null;\n _queuedScopeSets = [];\n _queueExecutor = null;\n _queuePromise = null;\n constructor(executor) {\n this._executor = executor;\n }\n async fetch(...scopeSets) {\n const filteredScopeSets = scopeSets.filter((val) => Boolean(val));\n if (this._newTokenPromise) {\n if (!filteredScopeSets.length) {\n return await this._newTokenPromise;\n }\n if (this._queueExecutor) {\n this._queuedScopeSets.push(...filteredScopeSets);\n }\n else {\n this._queuedScopeSets = [...filteredScopeSets];\n }\n if (!this._queuePromise) {\n const { promise, resolve, reject } = promiseWithResolvers();\n this._queuePromise = promise;\n this._queueExecutor = async () => {\n if (!this._queuePromise) {\n return;\n }\n this._newTokenScopeSets = this._queuedScopeSets;\n this._queuedScopeSets = [];\n this._newTokenPromise = this._queuePromise;\n this._queuePromise = null;\n this._queueExecutor = null;\n try {\n resolve(await this._executor(this._newTokenScopeSets));\n }\n catch (e) {\n reject(e);\n }\n finally {\n this._newTokenPromise = null;\n this._newTokenScopeSets = [];\n this._queueExecutor?.();\n }\n };\n }\n return await this._queuePromise;\n }\n this._newTokenScopeSets = [...filteredScopeSets];\n const { promise, resolve, reject } = promiseWithResolvers();\n this._newTokenPromise = promise;\n try {\n resolve(await this._executor(this._newTokenScopeSets));\n }\n catch (e) {\n reject(e);\n }\n finally {\n this._newTokenPromise = null;\n this._newTokenScopeSets = [];\n this._queueExecutor?.();\n }\n return await promise;\n }\n}\n", "import { __decorate } from \"tslib\";\nimport { Enumerable } from '@d-fischer/shared-utils';\nimport { extractUserId, rtfm } from '@twurple/common';\nimport { accessTokenIsExpired } from '../AccessToken.js';\nimport { getAppToken } from '../helpers.js';\nimport { TokenFetcher } from '../TokenFetcher.js';\n/**\n * An auth provider that gets tokens using client credentials.\n */\nlet AppTokenAuthProvider = class AppTokenAuthProvider {\n _clientId;\n /** @internal */ _clientSecret;\n /** @internal */ _token;\n /** @internal */ _fetcher;\n _impliedScopes;\n /**\n * Creates a new auth provider to receive an application token with using the client ID and secret.\n *\n * @param clientId The client ID of your application.\n * @param clientSecret The client secret of your application.\n * @param impliedScopes The scopes that are implied for your application,\n * for example an extension that is allowed to access subscriptions.\n */\n constructor(clientId, clientSecret, impliedScopes = []) {\n this._clientId = clientId;\n this._clientSecret = clientSecret;\n this._impliedScopes = impliedScopes;\n this._fetcher = new TokenFetcher(async (scopes) => await this._fetch(scopes));\n }\n /**\n * The client ID.\n */\n get clientId() {\n return this._clientId;\n }\n /**\n * The scopes that are currently available using the access token.\n */\n get currentScopes() {\n return this._impliedScopes;\n }\n /**\n * Can only get tokens for implied scopes (i.e. extension subscription support).\n *\n * The consumer is expected to take care that this is actually set up in the Twitch developer console.\n *\n * @param user The user to get an access token for.\n * @param scopeSets The requested scopes.\n */\n async getAccessTokenForUser(user, ...scopeSets) {\n if (scopeSets.every(scopeSet => scopeSet?.some(scope => this._impliedScopes.includes(scope)) ?? true)) {\n const appToken = await this.getAppAccessToken();\n return {\n ...appToken,\n userId: extractUserId(user),\n };\n }\n throw new Error('Can not get user access token for AppTokenAuthProvider');\n }\n /**\n * Throws, because this auth provider does not support user authentication.\n */\n getCurrentScopesForUser() {\n return this._impliedScopes;\n }\n /**\n * Fetches an app access token.\n */\n async getAnyAccessToken() {\n return await this._fetcher.fetch();\n }\n /**\n * Fetches an app access token.\n *\n * @param forceNew Whether to always get a new token, even if the old one is still deemed valid internally.\n */\n async getAppAccessToken(forceNew = false) {\n if (forceNew) {\n this._token = undefined;\n }\n return await this._fetcher.fetch();\n }\n async _fetch(scopeSets) {\n if (scopeSets.length > 0) {\n for (const scopes of scopeSets) {\n if (this._impliedScopes.length) {\n if (scopes.every(scope => !this._impliedScopes.includes(scope))) {\n throw new Error(`One of the scopes ${scopes.join(', ')} requested but only the scope ${this._impliedScopes.join(', ')} is implied`);\n }\n }\n else {\n throw new Error(`One of the scopes ${scopes.join(', ')} requested but the client credentials flow does not support scopes`);\n }\n }\n }\n if (!this._token || accessTokenIsExpired(this._token)) {\n return (this._token = await getAppToken(this._clientId, this._clientSecret));\n }\n return this._token;\n }\n};\n__decorate([\n Enumerable(false)\n], AppTokenAuthProvider.prototype, \"_clientSecret\", void 0);\n__decorate([\n Enumerable(false)\n], AppTokenAuthProvider.prototype, \"_token\", void 0);\n__decorate([\n Enumerable(false)\n], AppTokenAuthProvider.prototype, \"_fetcher\", void 0);\nAppTokenAuthProvider = __decorate([\n rtfm('auth', 'AppTokenAuthProvider', 'clientId')\n], AppTokenAuthProvider);\nexport { AppTokenAuthProvider };\n", "import { __decorate } from \"tslib\";\nimport { mapOptional } from '@d-fischer/shared-utils';\nimport { createBroadcasterQuery } from '@twurple/api-call';\nimport { extractUserId, rtfm } from '@twurple/common';\nimport { createBitsLeaderboardQuery, } from '../../interfaces/endpoints/bits.external.js';\nimport { BaseApi } from '../BaseApi.js';\nimport { HelixBitsLeaderboard } from './HelixBitsLeaderboard.js';\nimport { HelixCheermoteList } from './HelixCheermoteList.js';\n/**\n * The Helix API methods that deal with bits.\n *\n * Can be accessed using `client.bits` on an {@link ApiClient} instance.\n *\n * ## Example\n * ```ts\n * const api = new ApiClient({ authProvider });\n * const leaderboard = await api.bits.getLeaderboard({ period: 'day' });\n * ```\n *\n * @meta category helix\n * @meta categorizedTitle Bits\n */\nlet HelixBitsApi = class HelixBitsApi extends BaseApi {\n /**\n * Gets a bits leaderboard of your channel.\n *\n * @param broadcaster The user to get the leaderboard of.\n * @param params\n * @expandParams\n */\n async getLeaderboard(broadcaster, params = {}) {\n const result = await this._client.callApi({\n type: 'helix',\n url: 'bits/leaderboard',\n userId: extractUserId(broadcaster),\n scopes: ['bits:read'],\n query: createBitsLeaderboardQuery(params),\n });\n return new HelixBitsLeaderboard(result, this._client);\n }\n /**\n * Gets all available cheermotes.\n *\n * @param broadcaster The broadcaster to include custom cheermotes of.\n *\n * If not given, only get global cheermotes.\n */\n async getCheermotes(broadcaster) {\n const result = await this._client.callApi({\n type: 'helix',\n url: 'bits/cheermotes',\n userId: mapOptional(broadcaster, extractUserId),\n query: mapOptional(broadcaster, createBroadcasterQuery),\n });\n return new HelixCheermoteList(result.data);\n }\n};\nHelixBitsApi = __decorate([\n rtfm('api', 'HelixBitsApi')\n], HelixBitsApi);\nexport { HelixBitsApi };\n", "/** @internal */\nexport function createBitsLeaderboardQuery(params = {}) {\n const { count = 10, period = 'all', startDate, contextUserId } = params;\n return {\n count: count.toString(),\n period,\n started_at: startDate?.toISOString(),\n user_id: contextUserId,\n };\n}\n", "import { __decorate } from \"tslib\";\nimport { Enumerable } from '@d-fischer/shared-utils';\n/** @private */\nexport class BaseApi {\n /** @internal */ _client;\n /** @internal */\n constructor(client) {\n this._client = client;\n }\n /** @internal */\n _getUserContextIdWithDefault(userId) {\n return this._client._getUserIdFromRequestContext(userId) ?? userId;\n }\n}\n__decorate([\n Enumerable(false)\n], BaseApi.prototype, \"_client\", void 0);\n", "import { __decorate } from \"tslib\";\nimport { Cacheable, CachedGetter } from '@d-fischer/cache-decorators';\nimport { Enumerable } from '@d-fischer/shared-utils';\nimport { DataObject, rawDataSymbol, rtfm } from '@twurple/common';\nimport { HelixBitsLeaderboardEntry } from './HelixBitsLeaderboardEntry.js';\n/**\n * A leaderboard where the users who used the most bits to a broadcaster are listed.\n */\nlet HelixBitsLeaderboard = class HelixBitsLeaderboard extends DataObject {\n /** @internal */ _client;\n /** @internal */\n constructor(data, client) {\n super(data);\n this._client = client;\n }\n /**\n * The entries of the leaderboard.\n */\n get entries() {\n return this[rawDataSymbol].data.map(entry => new HelixBitsLeaderboardEntry(entry, this._client));\n }\n /**\n * The total amount of people on the requested leaderboard.\n */\n get totalCount() {\n return this[rawDataSymbol].total;\n }\n};\n__decorate([\n Enumerable(false)\n], HelixBitsLeaderboard.prototype, \"_client\", void 0);\n__decorate([\n CachedGetter()\n], HelixBitsLeaderboard.prototype, \"entries\", null);\nHelixBitsLeaderboard = __decorate([\n Cacheable,\n rtfm('api', 'HelixBitsLeaderboard')\n], HelixBitsLeaderboard);\nexport { HelixBitsLeaderboard };\n", "import { __decorate } from \"tslib\";\nimport { Enumerable } from '@d-fischer/shared-utils';\nimport { checkRelationAssertion, DataObject, rawDataSymbol, rtfm } from '@twurple/common';\n/**\n * A Bits leaderboard entry.\n */\nlet HelixBitsLeaderboardEntry = class HelixBitsLeaderboardEntry extends DataObject {\n /** @internal */ _client;\n /** @internal */\n constructor(data, client) {\n super(data);\n this._client = client;\n }\n /**\n * The ID of the user on the leaderboard.\n */\n get userId() {\n return this[rawDataSymbol].user_id;\n }\n /**\n * The name of the user on the leaderboard.\n */\n get userName() {\n return this[rawDataSymbol].user_login;\n }\n /**\n * The display name of the user on the leaderboard.\n */\n get userDisplayName() {\n return this[rawDataSymbol].user_name;\n }\n /**\n * The position of the user on the leaderboard.\n */\n get rank() {\n return this[rawDataSymbol].rank;\n }\n /**\n * The amount of bits used in the given period of time.\n */\n get amount() {\n return this[rawDataSymbol].score;\n }\n /**\n * Gets the user of entry on the leaderboard.\n */\n async getUser() {\n return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].user_id));\n }\n};\n__decorate([\n Enumerable(false)\n], HelixBitsLeaderboardEntry.prototype, \"_client\", void 0);\nHelixBitsLeaderboardEntry = __decorate([\n rtfm('api', 'HelixBitsLeaderboardEntry', 'userId')\n], HelixBitsLeaderboardEntry);\nexport { HelixBitsLeaderboardEntry };\n", "import { __decorate } from \"tslib\";\nimport { indexBy } from '@d-fischer/shared-utils';\nimport { DataObject, HellFreezesOverError, rawDataSymbol, rtfm } from '@twurple/common';\n/**\n * A list of cheermotes you can use globally or in a specific channel, depending on how you fetched the list.\n *\n * @inheritDoc\n */\nlet HelixCheermoteList = class HelixCheermoteList extends DataObject {\n /** @internal */\n constructor(data) {\n super(indexBy(data, action => action.prefix.toLowerCase()));\n }\n /**\n * Gets the URL and color needed to properly represent a cheer of the given amount of bits with the given prefix.\n *\n * @param name The name/prefix of the cheermote.\n * @param bits The amount of bits cheered.\n * @param format The format of the cheermote you want to request.\n */\n getCheermoteDisplayInfo(name, bits, format) {\n name = name.toLowerCase();\n const { background, state, scale } = format;\n const { tiers } = this[rawDataSymbol][name];\n const correctTier = tiers.sort((a, b) => b.min_bits - a.min_bits).find(tier => tier.min_bits <= bits);\n if (!correctTier) {\n throw new HellFreezesOverError(`Cheermote \"${name}\" does not have an applicable tier for ${bits} bits`);\n }\n return {\n url: correctTier.images[background][state][scale],\n color: correctTier.color,\n };\n }\n /**\n * Gets all possible cheermote names.\n */\n getPossibleNames() {\n return Object.keys(this[rawDataSymbol]);\n }\n};\nHelixCheermoteList = __decorate([\n rtfm('api', 'HelixCheermoteList')\n], HelixCheermoteList);\nexport { HelixCheermoteList };\n", "import { __decorate } from \"tslib\";\nimport { Enumerable, mapNullable } from '@d-fischer/shared-utils';\nimport { createBroadcasterQuery, } from '@twurple/api-call';\nimport { extractUserId, rtfm } from '@twurple/common';\nimport { createChannelCommercialBody, createChannelFollowerQuery, createChannelUpdateBody, createChannelVipUpdateQuery, createFollowedChannelQuery, } from '../../interfaces/endpoints/channel.external.js';\nimport { createChannelUsersCheckQuery, createSingleKeyQuery, } from '../../interfaces/endpoints/generic.external.js';\nimport { HelixUserRelation } from '../../relations/HelixUserRelation.js';\nimport { HelixRequestBatcher } from '../../utils/HelixRequestBatcher.js';\nimport { HelixPaginatedRequest } from '../../utils/pagination/HelixPaginatedRequest.js';\nimport { HelixPaginatedRequestWithTotal } from '../../utils/pagination/HelixPaginatedRequestWithTotal.js';\nimport { createPaginatedResult, createPaginatedResultWithTotal, } from '../../utils/pagination/HelixPaginatedResult.js';\nimport { createPaginationQuery } from '../../utils/pagination/HelixPagination.js';\nimport { BaseApi } from '../BaseApi.js';\nimport { HelixChannel } from './HelixChannel.js';\nimport { HelixChannelEditor } from './HelixChannelEditor.js';\nimport { HelixChannelFollower } from './HelixChannelFollower.js';\nimport { HelixFollowedChannel } from './HelixFollowedChannel.js';\nimport { HelixAdSchedule } from './HelixAdSchedule.js';\nimport { HelixSnoozeNextAdResult } from './HelixSnoozeNextAdResult.js';\n/**\n * The Helix API methods that deal with channels.\n *\n * Can be accessed using `client.channels` on an {@link ApiClient} instance.\n *\n * ## Example\n * ```ts\n * const api = new ApiClient({ authProvider });\n * const channel = await api.channels.getChannelInfoById('125328655');\n * ```\n *\n * @meta category helix\n * @meta categorizedTitle Channels\n */\nlet HelixChannelApi = class HelixChannelApi extends BaseApi {\n /** @internal */\n _getChannelByIdBatcher = new HelixRequestBatcher({\n url: 'channels',\n }, 'broadcaster_id', 'broadcaster_id', this._client, (data) => new HelixChannel(data, this._client));\n /**\n * Gets the channel data for the given user.\n *\n * @param user The user you want to get channel info for.\n */\n async getChannelInfoById(user) {\n const userId = extractUserId(user);\n const result = await this._client.callApi({\n type: 'helix',\n url: 'channels',\n userId,\n query: createBroadcasterQuery(userId),\n });\n return mapNullable(result.data[0], data => new HelixChannel(data, this._client));\n }\n /**\n * Gets the channel data for the given user, batching multiple calls into fewer requests as the API allows.\n *\n * @param user The user you want to get channel info for.\n */\n async getChannelInfoByIdBatched(user) {\n return await this._getChannelByIdBatcher.request(extractUserId(user));\n }\n /**\n * Gets the channel data for the given users.\n *\n * @param users The users you want to get channel info for.\n */\n async getChannelInfoByIds(users) {\n const userIds = users.map(extractUserId);\n const result = await this._client.callApi({\n type: 'helix',\n url: 'channels',\n query: createSingleKeyQuery('broadcaster_id', userIds),\n });\n return result.data.map(data => new HelixChannel(data, this._client));\n }\n /**\n * Updates the given user's channel data.\n *\n * @param user The user you want to update channel info for.\n * @param data The channel info to set.\n */\n async updateChannelInfo(user, data) {\n await this._client.callApi({\n type: 'helix',\n url: 'channels',\n method: 'PATCH',\n userId: extractUserId(user),\n scopes: ['channel:manage:broadcast'],\n query: createBroadcasterQuery(user),\n jsonBody: createChannelUpdateBody(data),\n });\n }\n /**\n * Starts a commercial on a channel.\n *\n * @param broadcaster The broadcaster on whose channel the commercial is started.\n * @param length The length of the commercial, in seconds.\n */\n async startChannelCommercial(broadcaster, length) {\n await this._client.callApi({\n type: 'helix',\n url: 'channels/commercial',\n method: 'POST',\n userId: extractUserId(broadcaster),\n scopes: ['channel:edit:commercial'],\n jsonBody: createChannelCommercialBody(broadcaster, length),\n });\n }\n /**\n * Gets a list of users who have editor permissions on your channel.\n *\n * @param broadcaster The broadcaster to retreive the editors for.\n */\n async getChannelEditors(broadcaster) {\n const result = await this._client.callApi({\n type: 'helix',\n url: 'channels/editors',\n userId: extractUserId(broadcaster),\n scopes: ['channel:read:editors'],\n query: createBroadcasterQuery(broadcaster),\n });\n return result.data.map(data => new HelixChannelEditor(data, this._client));\n }\n /**\n * Gets a list of VIPs in a channel.\n *\n * @param broadcaster The owner of the channel to get VIPs for.\n * @param pagination\n *\n * @expandParams\n */\n async getVips(broadcaster, pagination) {\n const response = await this._client.callApi({\n type: 'helix',\n url: 'channels/vips',\n userId: extractUserId(broadcaster),\n scopes: ['channel:read:vips', 'channel:manage:vips'],\n query: {\n ...createBroadcasterQuery(broadcaster),\n ...createPaginationQuery(pagination),\n },\n });\n return createPaginatedResult(response, HelixUserRelation, this._client);\n }\n /**\n * Creates a paginator for VIPs in a channel.\n *\n * @param broadcaster The owner of the channel to get VIPs for.\n */\n getVipsPaginated(broadcaster) {\n return new HelixPaginatedRequest({\n url: 'channels/vips',\n userId: extractUserId(broadcaster),\n scopes: ['channel:read:vips', 'channel:manage:vips'],\n query: createBroadcasterQuery(broadcaster),\n }, this._client, data => new HelixUserRelation(data, this._client));\n }\n /**\n * Checks the VIP status of a list of users in a channel.\n *\n * @param broadcaster The owner of the channel to check VIP status in.\n * @param users The users to check.\n */\n async checkVipForUsers(broadcaster, users) {\n const response = await this._client.callApi({\n type: 'helix',\n url: 'channels/vips',\n userId: extractUserId(broadcaster),\n scopes: ['channel:read:vips', 'channel:manage:vips'],\n query: createChannelUsersCheckQuery(broadcaster, users),\n });\n return response.data.map(data => new HelixUserRelation(data, this._client));\n }\n /**\n * Checks the VIP status of a user in a channel.\n *\n * @param broadcaster The owner of the channel to check VIP status in.\n * @param user The user to check.\n */\n async checkVipForUser(broadcaster, user) {\n const userId = extractUserId(user);\n const result = await this.checkVipForUsers(broadcaster, [userId]);\n return result.some(rel => rel.id === userId);\n }\n /**\n * Adds a VIP to the broadcaster\u2019s chat room.\n *\n * @param broadcaster The broadcaster that\u2019s granting VIP status to the user. This ID must match the user ID in the access token.\n * @param user The user to add as a VIP in the broadcaster\u2019s chat room.\n */\n async addVip(broadcaster, user) {\n await this._client.callApi({\n type: 'helix',\n url: 'channels/vips',\n method: 'POST',\n userId: extractUserId(broadcaster),\n scopes: ['channel:manage:vips'],\n query: createChannelVipUpdateQuery(broadcaster, user),\n });\n }\n /**\n * Removes a VIP from the broadcaster\u2019s chat room.\n *\n * @param broadcaster The broadcaster that\u2019s removing VIP status from the user. This ID must match the user ID in the access token.\n * @param user The user to remove as a VIP from the broadcaster\u2019s chat room.\n */\n async removeVip(broadcaster, user) {\n await this._client.callApi({\n type: 'helix',\n url: 'channels/vips',\n method: 'DELETE',\n userId: extractUserId(broadcaster),\n scopes: ['channel:manage:vips'],\n query: createChannelVipUpdateQuery(broadcaster, user),\n });\n }\n /**\n * Gets the total number of users that follow the specified broadcaster.\n *\n * @param broadcaster The broadcaster you want to get the number of followers of.\n */\n async getChannelFollowerCount(broadcaster) {\n const result = await this._client.callApi({\n type: 'helix',\n url: 'channels/followers',\n method: 'GET',\n userId: extractUserId(broadcaster),\n query: {\n ...createChannelFollowerQuery(broadcaster),\n ...createPaginationQuery({ limit: 1 }),\n },\n });\n return result.total;\n }\n /**\n * Gets a list of users that follow the specified broadcaster.\n * You can also use this endpoint to see whether a specific user follows the broadcaster.\n *\n * This uses the token of the broadcaster by default.\n * If you want to execute this in the context of another user (who has to be moderator of the channel)\n * you can do so using [user context overrides](/docs/auth/concepts/context-switching).\n *\n * @param broadcaster The broadcaster you want to get a list of followers for.\n * @param user An optional user to determine if this user follows the broadcaster.\n * If specified, the response contains this user if they follow the broadcaster.\n * If not specified, the response contains all users that follow the broadcaster.\n * @param pagination\n *\n * @expandParams\n */\n async getChannelFollowers(broadcaster, user, pagination) {\n const result = await this._client.callApi({\n type: 'helix',\n url: 'channels/followers',\n method: 'GET',\n userId: extractUserId(broadcaster),\n canOverrideScopedUserContext: true,\n scopes: ['moderator:read:followers'],\n query: {\n ...createChannelFollowerQuery(broadcaster, user),\n ...createPaginationQuery(pagination),\n },\n });\n return createPaginatedResultWithTotal(result, HelixChannelFollower, this._client);\n }\n /**\n * Creates a paginator for users that follow the specified broadcaster.\n *\n * This uses the token of the broadcaster by default.\n * If you want to execute this in the context of another user (who has to be moderator of the channel)\n * you can do so using [user context overrides](/docs/auth/concepts/context-switching).\n *\n * @param broadcaster The broadcaster for whom you are getting a list of followers.\n *\n * @expandParams\n */\n getChannelFollowersPaginated(broadcaster) {\n return new HelixPaginatedRequestWithTotal({\n url: 'channels/followers',\n method: 'GET',\n userId: extractUserId(broadcaster),\n canOverrideScopedUserContext: true,\n scopes: ['moderator:read:followers'],\n query: createChannelFollowerQuery(broadcaster),\n }, this._client, data => new HelixChannelFollower(data, this._client));\n }\n /**\n * Gets a list of broadcasters that the specified user follows.\n * You can also use this endpoint to see whether the user follows a specific broadcaster.\n *\n * @param user The user that's getting a list of followed channels.\n * This ID must match the user ID in the access token.\n * @param broadcaster An optional broadcaster to determine if the user follows this broadcaster.\n * If specified, the response contains this broadcaster if the user follows them.\n * If not specified, the response contains all broadcasters that the user follows.\n * @param pagination\n * @returns\n */\n async getFollowedChannels(user, broadcaster, pagination) {\n const result = await this._client.callApi({\n type: 'helix',\n url: 'channels/followed',\n method: 'GET',\n userId: extractUserId(user),\n scopes: ['user:read:follows'],\n query: {\n ...createFollowedChannelQuery(user, broadcaster),\n ...createPaginationQuery(pagination),\n },\n });\n return createPaginatedResultWithTotal(result, HelixFollowedChannel, this._client);\n }\n /**\n * Creates a paginator for broadcasters that the specified user follows.\n *\n * @param user The user that's getting a list of followed channels.\n * The token of this user will be used to get the list of followed channels.\n * @param broadcaster An optional broadcaster to determine if the user follows this broadcaster.\n * If specified, the response contains this broadcaster if the user follows them.\n * If not specified, the response contains all broadcasters that the user follows.\n * @returns\n */\n getFollowedChannelsPaginated(user, broadcaster) {\n return new HelixPaginatedRequestWithTotal({\n url: 'channels/followed',\n method: 'GET',\n userId: extractUserId(user),\n scopes: ['user:read:follows'],\n query: createFollowedChannelQuery(user, broadcaster),\n }, this._client, data => new HelixFollowedChannel(data, this._client));\n }\n /**\n * Gets information about the broadcaster's ad schedule.\n *\n * @param broadcaster The broadcaster to get ad schedule information about.\n */\n async getAdSchedule(broadcaster) {\n const response = await this._client.callApi({\n type: 'helix',\n url: 'channels/ads',\n method: 'GET',\n userId: extractUserId(broadcaster),\n scopes: ['channel:read:ads'],\n query: createBroadcasterQuery(broadcaster),\n });\n return new HelixAdSchedule(response.data[0]);\n }\n /**\n * Snoozes the broadcaster's next ad, if a snooze is available.\n *\n * @param broadcaster The broadcaster to get ad schedule information about.\n */\n async snoozeNextAd(broadcaster) {\n const response = await this._client.callApi({\n type: 'helix',\n url: 'channels/ads/schedule/snooze',\n method: 'POST',\n userId: extractUserId(broadcaster),\n scopes: ['channel:manage:ads'],\n query: createBroadcasterQuery(broadcaster),\n });\n return new HelixSnoozeNextAdResult(response.data[0]);\n }\n};\n__decorate([\n Enumerable(false)\n], HelixChannelApi.prototype, \"_getChannelByIdBatcher\", void 0);\nHelixChannelApi = __decorate([\n rtfm('api', 'HelixChannelApi')\n], HelixChannelApi);\nexport { HelixChannelApi };\n", "import { mapOptional } from '@d-fischer/shared-utils';\nimport { extractUserId } from '@twurple/common';\n/** @internal */\nexport function createChannelUpdateBody(data) {\n return {\n game_id: data.gameId,\n broadcaster_language: data.language,\n title: data.title,\n delay: data.delay?.toString(),\n tags: data.tags,\n content_classification_labels: data.contentClassificationLabels,\n is_branded_content: data.isBrandedContent,\n };\n}\n/** @internal */\nexport function createChannelCommercialBody(broadcaster, length) {\n return {\n broadcaster_id: extractUserId(broadcaster),\n length,\n };\n}\n/** @internal */\nexport function createChannelVipUpdateQuery(broadcaster, user) {\n return {\n broadcaster_id: extractUserId(broadcaster),\n user_id: extractUserId(user),\n };\n}\n/** @internal */\nexport function createChannelFollowerQuery(broadcaster, user) {\n return {\n broadcaster_id: extractUserId(broadcaster),\n user_id: mapOptional(user, extractUserId),\n };\n}\n/** @internal */\nexport function createFollowedChannelQuery(user, broadcaster) {\n return {\n broadcaster_id: mapOptional(broadcaster, extractUserId),\n user_id: extractUserId(user),\n };\n}\n", "import { extractUserId } from '@twurple/common';\n/** @internal */\nexport function createSingleKeyQuery(key, value) {\n return { [key]: value };\n}\n/** @internal */\nexport function createUserQuery(user) {\n return {\n user_id: extractUserId(user),\n };\n}\n/** @internal */\nexport function createModeratorActionQuery(broadcaster, moderatorId) {\n return {\n broadcaster_id: broadcaster,\n moderator_id: moderatorId,\n };\n}\n/** @internal */\nexport function createGetByIdsQuery(broadcaster, rewardIds) {\n return {\n broadcaster_id: extractUserId(broadcaster),\n id: rewardIds,\n };\n}\n/** @internal */\nexport function createChannelUsersCheckQuery(broadcaster, users) {\n return {\n broadcaster_id: extractUserId(broadcaster),\n user_id: users.map(extractUserId),\n };\n}\n", "import { __decorate } from \"tslib\";\nimport { Enumerable } from '@d-fischer/shared-utils';\nimport { checkRelationAssertion, DataObject, rawDataSymbol, rtfm } from '@twurple/common';\n/**\n * A relation of anything with a user.\n */\nlet HelixUserRelation = class HelixUserRelation extends DataObject {\n /** @internal */ _client;\n /** @internal */\n constructor(data, client) {\n super(data);\n this._client = client;\n }\n /**\n * The ID of the user.\n */\n get id() {\n return this[rawDataSymbol].user_id;\n }\n /**\n * The name of the user.\n */\n get name() {\n return this[rawDataSymbol].user_login;\n }\n /**\n * The display name of the user.\n */\n get displayName() {\n return this[rawDataSymbol].user_name;\n }\n /**\n * Gets additional information about the user.\n */\n async getUser() {\n return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].user_id));\n }\n};\n__decorate([\n Enumerable(false)\n], HelixUserRelation.prototype, \"_client\", void 0);\nHelixUserRelation = __decorate([\n rtfm('api', 'HelixUserRelation', 'id')\n], HelixUserRelation);\nexport { HelixUserRelation };\n", "import { __decorate } from \"tslib\";\nimport { Enumerable, indexBy, promiseWithResolvers } from '@d-fischer/shared-utils';\n/** @internal */\nexport class HelixRequestBatcher {\n _callOptions;\n _queryParamName;\n _matchKey;\n _mapper;\n _limitPerRequest;\n _client;\n _requestedIds = [];\n _requestResolversById = new Map();\n _delay;\n _waitTimer = null;\n constructor(_callOptions, _queryParamName, _matchKey, client, _mapper, _limitPerRequest = 100) {\n this._callOptions = _callOptions;\n this._queryParamName = _queryParamName;\n this._matchKey = _matchKey;\n this._mapper = _mapper;\n this._limitPerRequest = _limitPerRequest;\n this._client = client;\n this._delay = client._batchDelay;\n }\n async request(id) {\n const { promise, resolve, reject } = promiseWithResolvers();\n if (!this._requestedIds.includes(id)) {\n this._requestedIds.push(id);\n }\n if (this._requestResolversById.has(id)) {\n this._requestResolversById.get(id).push({ resolve, reject });\n }\n else {\n this._requestResolversById.set(id, [{ resolve, reject }]);\n }\n if (this._waitTimer) {\n clearTimeout(this._waitTimer);\n this._waitTimer = null;\n }\n if (this._requestedIds.length >= this._limitPerRequest) {\n void this._handleBatch(this._requestedIds.splice(0, this._limitPerRequest));\n }\n else {\n this._waitTimer = setTimeout(() => {\n void this._handleBatch(this._requestedIds.splice(0, this._limitPerRequest));\n }, this._delay);\n }\n return await promise;\n }\n async _handleBatch(ids) {\n try {\n const { data } = await this._doRequest(ids);\n const dataById = indexBy(data, this._matchKey);\n for (const id of ids) {\n for (const resolver of this._requestResolversById.get(id) ?? []) {\n if (Object.prototype.hasOwnProperty.call(dataById, id)) {\n resolver.resolve(this._mapper(dataById[id]));\n }\n else {\n resolver.resolve(null);\n }\n }\n this._requestResolversById.delete(id);\n }\n }\n catch (e) {\n await Promise.all(ids.map(async (id) => {\n try {\n const result = await this._doRequest([id]);\n for (const resolver of this._requestResolversById.get(id) ?? []) {\n resolver.resolve(result.data.length ? this._mapper(result.data[0]) : null);\n }\n }\n catch (e_) {\n for (const resolver of this._requestResolversById.get(id) ?? []) {\n resolver.reject(e_);\n }\n }\n this._requestResolversById.delete(id);\n }));\n }\n }\n async _doRequest(ids) {\n return await this._client.callApi({\n type: 'helix',\n ...this._callOptions,\n query: {\n ...this._callOptions.query,\n [this._queryParamName]: ids,\n },\n });\n }\n}\n__decorate([\n Enumerable(false)\n], HelixRequestBatcher.prototype, \"_client\", void 0);\n", "import { __decorate } from \"tslib\";\nimport { Enumerable } from '@d-fischer/shared-utils';\nimport { rtfm } from '@twurple/common';\nif (!Object.prototype.hasOwnProperty.call(Symbol, 'asyncIterator')) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any,@typescript-eslint/no-unnecessary-condition,@typescript-eslint/no-unsafe-member-access\n Symbol.asyncIterator = Symbol.asyncIterator ?? Symbol.for('Symbol.asyncIterator');\n}\n/**\n * Represents a request to the new Twitch API (Helix) that utilizes a cursor to paginate through its results.\n *\n * Aside from the methods described below, you can also utilize the async iterator using `for await .. of`:\n *\n * ```ts\n * const result = client.videos.getVideosByUserPaginated('125328655');\n * for await (const video of result) {\n * console.log(video.title);\n * }\n * ```\n */\nlet HelixPaginatedRequest = class HelixPaginatedRequest {\n _callOptions;\n _mapper;\n _limitPerPage;\n /** @internal */ _client;\n /** @internal */ _currentCursor;\n /** @internal */ _isFinished = false;\n /** @internal */ _currentData;\n /** @internal */\n constructor(_callOptions, client, _mapper, _limitPerPage = 100) {\n this._callOptions = _callOptions;\n this._mapper = _mapper;\n this._limitPerPage = _limitPerPage;\n this._client = client;\n }\n /**\n * The last fetched page of data associated to the requested resource.\n *\n * Only works with {@link HelixPaginatedRequest#getNext} and not with any other methods of data fetching.\n */\n get current() {\n return this._currentData?.data;\n }\n /**\n * Gets the next available page of data associated to the requested resource, or an empty array if there are no more available pages.\n */\n async getNext() {\n if (this._isFinished) {\n return [];\n }\n const result = await this._fetchData();\n // should never be null, but in practice is sometimes\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (!result.data?.length) {\n this._isFinished = true;\n return [];\n }\n return this._processResult(result);\n }\n /**\n * Gets all data associated to the requested resource.\n *\n * Be aware that this makes multiple calls to the Twitch API. Due to this, you might be more suspectible to rate limits.\n *\n * Also be aware that this resets the internal cursor, so avoid using this and {@link HelixPaginatedRequest#getNext}} together.\n */\n async getAll() {\n this.reset();\n const result = [];\n do {\n const data = await this.getNext();\n if (!data.length) {\n break;\n }\n result.push(...data);\n } while (this._currentCursor);\n this.reset();\n return result;\n }\n /**\n * Gets the current cursor.\n *\n * Only useful if you want to make manual requests to the API.\n */\n get currentCursor() {\n return this._currentCursor;\n }\n /**\n * Resets the internal cursor.\n *\n * This will make {@link HelixPaginatedRequest#getNext}} start from the first page again.\n */\n reset() {\n this._currentCursor = undefined;\n this._isFinished = false;\n this._currentData = undefined;\n }\n async *[Symbol.asyncIterator]() {\n this.reset();\n while (true) {\n const data = await this.getNext();\n if (!data.length) {\n break;\n }\n yield* data[Symbol.iterator]();\n }\n }\n /** @internal */\n async _fetchData(additionalOptions = {}) {\n return await this._client.callApi({\n type: 'helix',\n ...this._callOptions,\n ...additionalOptions,\n query: {\n ...this._callOptions.query,\n after: this._currentCursor,\n first: this._limitPerPage.toString(),\n ...additionalOptions.query,\n },\n });\n }\n /** @internal */\n _processResult(result) {\n this._currentCursor = typeof result.pagination === 'string' ? result.pagination : result.pagination?.cursor;\n if (this._currentCursor === undefined) {\n this._isFinished = true;\n }\n this._currentData = result;\n return result.data.reduce((acc, elem) => {\n const mapped = this._mapper(elem);\n return Array.isArray(mapped) ? [...acc, ...mapped] : [...acc, mapped];\n }, []);\n }\n};\n__decorate([\n Enumerable(false)\n], HelixPaginatedRequest.prototype, \"_client\", void 0);\nHelixPaginatedRequest = __decorate([\n rtfm('api', 'HelixPaginatedRequest')\n], HelixPaginatedRequest);\nexport { HelixPaginatedRequest };\n", "import { __decorate } from \"tslib\";\nimport { rtfm } from '@twurple/common';\nimport { HelixPaginatedRequest } from './HelixPaginatedRequest.js';\n/**\n * A special case of {@link HelixPaginatedRequest} with support for fetching the total number of entities, whenever an endpoint supports it.\n *\n * @inheritDoc\n */\nlet HelixPaginatedRequestWithTotal = class HelixPaginatedRequestWithTotal extends HelixPaginatedRequest {\n /**\n * Gets the total number of entities existing in the queried result set.\n */\n async getTotalCount() {\n const data = this._currentData ??\n (await this._fetchData({ query: { after: undefined } }));\n return data.total;\n }\n};\nHelixPaginatedRequestWithTotal = __decorate([\n rtfm('api', 'HelixPaginatedRequestWithTotal')\n], HelixPaginatedRequestWithTotal);\nexport { HelixPaginatedRequestWithTotal };\n", "/** @internal */ export function createPaginatedResult(response, type, client) {\n let dataCache = undefined;\n return {\n get data() {\n return (dataCache ??= response.data?.map(data => new type(data, client)) ?? []);\n },\n cursor: typeof response.pagination === 'string' ? response.pagination : response.pagination?.cursor,\n };\n}\n/** @internal */ export function createPaginatedResultWithTotal(response, type, client) {\n let dataCache = undefined;\n return {\n get data() {\n return (dataCache ??= response.data?.map(data => new type(data, client)) ?? []);\n },\n cursor: response.pagination.cursor,\n total: response.total,\n };\n}\n", "/** @internal */\nexport function createPaginationQuery({ after, before, limit } = {}) {\n return {\n after,\n before,\n first: limit?.toString(),\n };\n}\n", "import { __decorate } from \"tslib\";\nimport { Enumerable } from '@d-fischer/shared-utils';\nimport { checkRelationAssertion, DataObject, rawDataSymbol, rtfm } from '@twurple/common';\n/**\n * A Twitch channel.\n */\nlet HelixChannel = class HelixChannel extends DataObject {\n /** @internal */ _client;\n /** @internal */\n constructor(data, client) {\n super(data);\n this._client = client;\n }\n /**\n * The ID of the channel.\n */\n get id() {\n return this[rawDataSymbol].broadcaster_id;\n }\n /**\n * The name of the channel.\n */\n get name() {\n return this[rawDataSymbol].broadcaster_login;\n }\n /**\n * The display name of the channel.\n */\n get displayName() {\n return this[rawDataSymbol].broadcaster_name;\n }\n /**\n * Gets more information about the broadcaster of the channel.\n */\n async getBroadcaster() {\n return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].broadcaster_id));\n }\n /**\n * The language of the channel.\n */\n get language() {\n return this[rawDataSymbol].broadcaster_language;\n }\n /**\n * The ID of the game currently played on the channel.\n */\n get gameId() {\n return this[rawDataSymbol].game_id;\n }\n /**\n * The name of the game currently played on the channel.\n */\n get gameName() {\n return this[rawDataSymbol].game_name;\n }\n /**\n * Gets information about the game that is being played on the stream.\n */\n async getGame() {\n return this[rawDataSymbol].game_id\n ? checkRelationAssertion(await this._client.games.getGameById(this[rawDataSymbol].game_id))\n : null;\n }\n /**\n * The title of the channel.\n */\n get title() {\n return this[rawDataSymbol].title;\n }\n /**\n * The stream delay of the channel, in seconds.\n *\n * If you didn't request this with broadcaster access, this is always zero.\n */\n get delay() {\n return this[rawDataSymbol].delay;\n }\n /**\n * The tags applied to the channel.\n */\n get tags() {\n return this[rawDataSymbol].tags;\n }\n /**\n * The content classification labels applied to the channel.\n */\n get contentClassificationLabels() {\n return this[rawDataSymbol].content_classification_labels;\n }\n /**\n * Whether the channel currently displays branded content (as specified by the broadcaster).\n */\n get isBrandedContent() {\n return this[rawDataSymbol].is_branded_content;\n }\n};\n__decorate([\n Enumerable(false)\n], HelixChannel.prototype, \"_client\", void 0);\nHelixChannel = __decorate([\n rtfm('api', 'HelixChannel', 'id')\n], HelixChannel);\nexport { HelixChannel };\n", "import { __decorate } from \"tslib\";\nimport { Enumerable } from '@d-fischer/shared-utils';\nimport { checkRelationAssertion, DataObject, rawDataSymbol, rtfm } from '@twurple/common';\n/**\n * An editor of a previously given channel.\n */\nlet HelixChannelEditor = class HelixChannelEditor extends DataObject {\n /** @internal */ _client;\n /** @internal */\n constructor(data, client) {\n super(data);\n this._client = client;\n }\n /**\n * The ID of the user.\n */\n get userId() {\n return this[rawDataSymbol].user_id;\n }\n /**\n * The display name of the user.\n */\n get userDisplayName() {\n return this[rawDataSymbol].user_name;\n }\n /**\n * Gets additional information about the user.\n */\n async getUser() {\n return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].user_id));\n }\n /**\n * The date when the user was given editor status.\n */\n get creationDate() {\n return new Date(this[rawDataSymbol].created_at);\n }\n};\n__decorate([\n Enumerable(false)\n], HelixChannelEditor.prototype, \"_client\", void 0);\nHelixChannelEditor = __decorate([\n rtfm('api', 'HelixChannelEditor', 'userId')\n], HelixChannelEditor);\nexport { HelixChannelEditor };\n", "import { __decorate } from \"tslib\";\nimport { Enumerable } from '@d-fischer/shared-utils';\nimport { checkRelationAssertion, DataObject, rawDataSymbol, rtfm } from '@twurple/common';\n/**\n * Represents a user that follows a channel.\n */\nlet HelixChannelFollower = class HelixChannelFollower extends DataObject {\n /** @internal */ _client;\n /** @internal */\n constructor(data, client) {\n super(data);\n this._client = client;\n }\n /**\n * The ID of the user.\n */\n get userId() {\n return this[rawDataSymbol].user_id;\n }\n /**\n * The name of the user.\n */\n get userName() {\n return this[rawDataSymbol].user_login;\n }\n /**\n * The display name of the user.\n */\n get userDisplayName() {\n return this[rawDataSymbol].user_name;\n }\n /**\n * Gets additional information about the user.\n */\n async getUser() {\n return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].user_id));\n }\n /**\n * The date when the user followed the broadcaster.\n */\n get followDate() {\n return new Date(this[rawDataSymbol].followed_at);\n }\n};\n__decorate([\n Enumerable(false)\n], HelixChannelFollower.prototype, \"_client\", void 0);\nHelixChannelFollower = __decorate([\n rtfm('api', 'HelixChannelFollower', 'userId')\n], HelixChannelFollower);\nexport { HelixChannelFollower };\n", "import { __decorate } from \"tslib\";\nimport { Enumerable } from '@d-fischer/shared-utils';\nimport { checkRelationAssertion, DataObject, rawDataSymbol, rtfm } from '@twurple/common';\n/**\n * Represents a broadcaster that a user follows.\n */\nlet HelixFollowedChannel = class HelixFollowedChannel extends DataObject {\n /** @internal */ _client;\n /** @internal */\n constructor(data, client) {\n super(data);\n this._client = client;\n }\n /**\n * The ID of the broadcaster.\n */\n get broadcasterId() {\n return this[rawDataSymbol].broadcaster_id;\n }\n /**\n * The name of the broadcaster.\n */\n get broadcasterName() {\n return this[rawDataSymbol].broadcaster_login;\n }\n /**\n * The display name of the broadcaster.\n */\n get broadcasterDisplayName() {\n return this[rawDataSymbol].broadcaster_name;\n }\n /**\n * Gets additional information about the broadcaster.\n */\n async getBroadcaster() {\n return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].broadcaster_id));\n }\n /**\n * The date when the user followed the broadcaster.\n */\n get followDate() {\n return new Date(this[rawDataSymbol].followed_at);\n }\n};\n__decorate([\n Enumerable(false)\n], HelixFollowedChannel.prototype, \"_client\", void 0);\nHelixFollowedChannel = __decorate([\n rtfm('api', 'HelixFollowedChannel', 'broadcasterId')\n], HelixFollowedChannel);\nexport { HelixFollowedChannel };\n", "import { __decorate } from \"tslib\";\nimport { DataObject, rawDataSymbol, rtfm } from '@twurple/common';\n/**\n * Represents a broadcaster's ad schedule.\n */\nlet HelixAdSchedule = class HelixAdSchedule extends DataObject {\n /**\n * The number of snoozes available for the broadcaster.\n */\n get snoozeCount() {\n return this[rawDataSymbol].snooze_count;\n }\n /**\n * The date and time when the broadcaster will gain an additional snooze.\n * Returns `null` if all snoozes are already available.\n */\n get snoozeRefreshDate() {\n return this[rawDataSymbol].snooze_refresh_at ? new Date(this[rawDataSymbol].snooze_refresh_at * 1000) : null;\n }\n /**\n * The date and time of the broadcaster's next scheduled ad.\n * Returns `null` if channel is not live or has no ad scheduled.\n */\n get nextAdDate() {\n return this[rawDataSymbol].next_ad_at ? new Date(this[rawDataSymbol].next_ad_at * 1000) : null;\n }\n /**\n * The length in seconds of the scheduled upcoming ad break.\n */\n get duration() {\n return this[rawDataSymbol].duration;\n }\n /**\n * The date and time of the broadcaster's last ad-break.\n * Returns `null` if channel is not live or has not run an ad.\n */\n get lastAdDate() {\n return this[rawDataSymbol].last_ad_at ? new Date(this[rawDataSymbol].last_ad_at * 1000) : null;\n }\n /**\n * The amount of pre-roll free time remaining for the channel in seconds.\n */\n get prerollFreeTime() {\n return this[rawDataSymbol].preroll_free_time;\n }\n};\nHelixAdSchedule = __decorate([\n rtfm('api', 'HelixAdSchedule')\n], HelixAdSchedule);\nexport { HelixAdSchedule };\n", "import { __decorate } from \"tslib\";\nimport { DataObject, rawDataSymbol, rtfm } from '@twurple/common';\n/**\n * Represents the result after a call to snooze the broadcaster's ad schedule.\n */\nlet HelixSnoozeNextAdResult = class HelixSnoozeNextAdResult extends DataObject {\n /**\n * The number of snoozes remaining for the broadcaster.\n */\n get snoozeCount() {\n return this[rawDataSymbol].snooze_count;\n }\n /**\n * The date and time when the broadcaster will gain an additional snooze.\n */\n get snoozeRefreshDate() {\n return new Date(this[rawDataSymbol].snooze_refresh_at * 1000);\n }\n /**\n * The date and time of the broadcaster's next scheduled ad.\n */\n get nextAdDate() {\n return new Date(this[rawDataSymbol].next_ad_at * 1000);\n }\n};\nHelixSnoozeNextAdResult = __decorate([\n rtfm('api', 'HelixSnoozeNextAdResult')\n], HelixSnoozeNextAdResult);\nexport { HelixSnoozeNextAdResult };\n", "import { __decorate } from \"tslib\";\nimport { createBroadcasterQuery } from '@twurple/api-call';\nimport { extractUserId, rtfm } from '@twurple/common';\nimport { createCustomRewardBody, createCustomRewardChangeQuery, createCustomRewardsQuery, createRedemptionsForBroadcasterQuery, createRewardRedemptionsByIdsQuery, } from '../../interfaces/endpoints/channelPoints.external.js';\nimport { createGetByIdsQuery } from '../../interfaces/endpoints/generic.external.js';\nimport { HelixPaginatedRequest } from '../../utils/pagination/HelixPaginatedRequest.js';\nimport { createPaginatedResult } from '../../utils/pagination/HelixPaginatedResult.js';\nimport { createPaginationQuery } from '../../utils/pagination/HelixPagination.js';\nimport { BaseApi } from '../BaseApi.js';\nimport { HelixCustomReward } from './HelixCustomReward.js';\nimport { HelixCustomRewardRedemption } from './HelixCustomRewardRedemption.js';\n/**\n * The Helix API methods that deal with channel points.\n *\n * Can be accessed using `client.channelPoints` on an {@link ApiClient} instance.\n *\n * ## Example\n * ```ts\n * const api = new ApiClient({ authProvider });\n * const rewards = await api.channelPoints.getCustomRewards('125328655');\n * ```\n *\n * @meta category helix\n * @meta categorizedTitle Channel points\n */\nlet HelixChannelPointsApi = class HelixChannelPointsApi extends BaseApi {\n /**\n * Gets all custom rewards for the given broadcaster.\n *\n * @param broadcaster The broadcaster to get the rewards for.\n * @param onlyManageable Whether to only get rewards that can be managed by the API.\n */\n async getCustomRewards(broadcaster, onlyManageable) {\n const result = await this._client.callApi({\n type: 'helix',\n url: 'channel_points/custom_rewards',\n userId: extractUserId(broadcaster),\n scopes: ['channel:read:redemptions', 'channel:manage:redemptions'],\n query: createCustomRewardsQuery(broadcaster, onlyManageable),\n });\n return result.data.map(data => new HelixCustomReward(data, this._client));\n }\n /**\n * Gets custom rewards by IDs.\n *\n * @param broadcaster The broadcaster to get the rewards for.\n * @param rewardIds The IDs of the rewards.\n */\n async getCustomRewardsByIds(broadcaster, rewardIds) {\n if (!rewardIds.length) {\n return [];\n }\n const result = await this._client.callApi({\n type: 'helix',\n url: 'channel_points/custom_rewards',\n userId: extractUserId(broadcaster),\n scopes: ['channel:read:redemptions', 'channel:manage:redemptions'],\n query: createGetByIdsQuery(broadcaster, rewardIds),\n });\n return result.data.map(data => new HelixCustomReward(data, this._client));\n }\n /**\n * Gets a custom reward by ID.\n *\n * @param broadcaster The broadcaster to get the reward for.\n * @param rewardId The ID of the reward.\n */\n async getCustomRewardById(broadcaster, rewardId) {\n const rewards = await this.getCustomRewardsByIds(broadcaster, [rewardId]);\n return rewards.length ? rewards[0] : null;\n }\n /**\n * Creates a new custom reward.\n *\n * @param broadcaster The broadcaster to create the reward for.\n * @param data The reward data.\n *\n * @expandParams\n */\n async createCustomReward(broadcaster, data) {\n const result = await this._client.callApi({\n type: 'helix',\n url: 'channel_points/custom_rewards',\n method: 'POST',\n userId: extractUserId(broadcaster),\n scopes: ['channel:manage:redemptions'],\n query: createBroadcasterQuery(broadcaster),\n jsonBody: createCustomRewardBody(data),\n });\n return new HelixCustomReward(result.data[0], this._client);\n }\n /**\n * Updates a custom reward.\n *\n * @param broadcaster The broadcaster to update the reward for.\n * @param rewardId The ID of the reward.\n * @param data The reward data.\n */\n async updateCustomReward(broadcaster, rewardId, data) {\n const result = await this._client.callApi({\n type: 'helix',\n url: 'channel_points/custom_rewards',\n method: 'PATCH',\n userId: extractUserId(broadcaster),\n scopes: ['channel:manage:redemptions'],\n query: createCustomRewardChangeQuery(broadcaster, rewardId),\n jsonBody: createCustomRewardBody(data),\n });\n return new HelixCustomReward(result.data[0], this._client);\n }\n /**\n * Deletes a custom reward.\n *\n * @param broadcaster The broadcaster to delete the reward for.\n * @param rewardId The ID of the reward.\n */\n async deleteCustomReward(broadcaster, rewardId) {\n await this._client.callApi({\n type: 'helix',\n url: 'channel_points/custom_rewards',\n method: 'DELETE',\n userId: extractUserId(broadcaster),\n scopes: ['channel:manage:redemptions'],\n query: createCustomRewardChangeQuery(broadcaster, rewardId),\n });\n }\n /**\n * Gets custom reward redemptions by IDs.\n *\n * @param broadcaster The broadcaster to get the redemptions for.\n * @param rewardId The ID of the reward.\n * @param redemptionIds The IDs of the redemptions.\n */\n async getRedemptionsByIds(broadcaster, rewardId, redemptionIds) {\n if (!redemptionIds.length) {\n return [];\n }\n const result = await this._client.callApi({\n type: 'helix',\n url: 'channel_points/custom_rewards/redemptions',\n userId: extractUserId(broadcaster),\n scopes: ['channel:read:redemptions', 'channel:manage:redemptions'],\n query: createRewardRedemptionsByIdsQuery(broadcaster, rewardId, redemptionIds),\n });\n return result.data.map(data => new HelixCustomRewardRedemption(data, this._client));\n }\n /**\n * Gets a custom reward redemption by ID.\n *\n * @param broadcaster The broadcaster to get the redemption for.\n * @param rewardId The ID of the reward.\n * @param redemptionId The ID of the redemption.\n */\n async getRedemptionById(broadcaster, rewardId, redemptionId) {\n const redemptions = await this.getRedemptionsByIds(broadcaster, rewardId, [redemptionId]);\n return redemptions.length ? redemptions[0] : null;\n }\n /**\n * Gets custom reward redemptions for the given broadcaster.\n *\n * @param broadcaster The broadcaster to get the redemptions for.\n * @param rewardId The ID of the reward.\n * @param status The status of the redemptions to get.\n * @param filter\n *\n * @expandParams\n */\n async getRedemptionsForBroadcaster(broadcaster, rewardId, status, filter) {\n const result = await this._client.callApi({\n type: 'helix',\n url: 'channel_points/custom_rewards/redemptions',\n userId: extractUserId(broadcaster),\n scopes: ['channel:read:redemptions', 'channel:manage:redemptions'],\n query: {\n ...createRedemptionsForBroadcasterQuery(broadcaster, rewardId, status, filter),\n ...createPaginationQuery(filter),\n },\n });\n return createPaginatedResult(result, HelixCustomRewardRedemption, this._client);\n }\n /**\n * Creates a paginator for custom reward redemptions for the given broadcaster.\n *\n * @param broadcaster The broadcaster to get the redemptions for.\n * @param rewardId The ID of the reward.\n * @param status The status of the redemptions to get.\n * @param filter\n *\n * @expandParams\n */\n getRedemptionsForBroadcasterPaginated(broadcaster, rewardId, status, filter) {\n return new HelixPaginatedRequest({\n url: 'channel_points/custom_rewards/redemptions',\n userId: extractUserId(broadcaster),\n scopes: ['channel:read:redemptions', 'channel:manage:redemptions'],\n query: createRedemptionsForBroadcasterQuery(broadcaster, rewardId, status, filter),\n }, this._client, data => new HelixCustomRewardRedemption(data, this._client), 50);\n }\n /**\n * Updates the status of the given redemptions by IDs.\n *\n * @param broadcaster The broadcaster to update the redemptions for.\n * @param rewardId The ID of the reward.\n * @param redemptionIds The IDs of the redemptions to update.\n * @param status The status to set for the redemptions.\n */\n async updateRedemptionStatusByIds(broadcaster, rewardId, redemptionIds, status) {\n if (!redemptionIds.length) {\n return [];\n }\n const result = await this._client.callApi({\n type: 'helix',\n url: 'channel_points/custom_rewards/redemptions',\n method: 'PATCH',\n userId: extractUserId(broadcaster),\n scopes: ['channel:manage:redemptions'],\n query: createRewardRedemptionsByIdsQuery(broadcaster, rewardId, redemptionIds),\n jsonBody: {\n status,\n },\n });\n return result.data.map(data => new HelixCustomRewardRedemption(data, this._client));\n }\n};\nHelixChannelPointsApi = __decorate([\n rtfm('api', 'HelixChannelPointsApi')\n], HelixChannelPointsApi);\nexport { HelixChannelPointsApi };\n", "import { extractUserId } from '@twurple/common';\n/** @internal */\nexport function createCustomRewardsQuery(broadcaster, onlyManageable) {\n return {\n broadcaster_id: extractUserId(broadcaster),\n only_manageable_rewards: onlyManageable?.toString(),\n };\n}\n/** @internal */\nexport function createCustomRewardChangeQuery(broadcaster, rewardId) {\n return {\n broadcaster_id: extractUserId(broadcaster),\n id: rewardId,\n };\n}\n/** @internal */\nexport function createCustomRewardBody(data) {\n const result = {\n title: data.title,\n cost: data.cost,\n prompt: data.prompt,\n background_color: data.backgroundColor,\n is_enabled: data.isEnabled,\n is_user_input_required: data.userInputRequired,\n should_redemptions_skip_request_queue: data.autoFulfill,\n };\n if (data.maxRedemptionsPerStream !== undefined) {\n result.is_max_per_stream_enabled = !!data.maxRedemptionsPerStream;\n result.max_per_stream = data.maxRedemptionsPerStream ?? 0;\n }\n if (data.maxRedemptionsPerUserPerStream !== undefined) {\n result.is_max_per_user_per_stream_enabled = !!data.maxRedemptionsPerUserPerStream;\n result.max_per_user_per_stream = data.maxRedemptionsPerUserPerStream ?? 0;\n }\n if (data.globalCooldown !== undefined) {\n result.is_global_cooldown_enabled = !!data.globalCooldown;\n result.global_cooldown_seconds = data.globalCooldown ?? 0;\n }\n if ('isPaused' in data) {\n result.is_paused = data.isPaused;\n }\n return result;\n}\n/** @internal */\nexport function createRewardRedemptionsByIdsQuery(broadcaster, rewardId, redemptionIds) {\n return {\n broadcaster_id: extractUserId(broadcaster),\n reward_id: rewardId,\n id: redemptionIds,\n };\n}\n/** @internal */\nexport function createRedemptionsForBroadcasterQuery(broadcaster, rewardId, status, filter) {\n return {\n broadcaster_id: extractUserId(broadcaster),\n reward_id: rewardId,\n status,\n sort: filter.newestFirst ? 'NEWEST' : 'OLDEST',\n };\n}\n", "import { __decorate } from \"tslib\";\nimport { Enumerable } from '@d-fischer/shared-utils';\nimport { checkRelationAssertion, DataObject, rawDataSymbol, rtfm } from '@twurple/common';\n/**\n * A custom Channel Points reward.\n */\nlet HelixCustomReward = class HelixCustomReward extends DataObject {\n /** @internal */ _client;\n /** @internal */\n constructor(data, client) {\n super(data);\n this._client = client;\n }\n /**\n * The ID of the reward.\n */\n get id() {\n return this[rawDataSymbol].id;\n }\n /**\n * The ID of the broadcaster the reward belongs to.\n */\n get broadcasterId() {\n return this[rawDataSymbol].broadcaster_id;\n }\n /**\n * The name of the broadcaster the reward belongs to.\n */\n get broadcasterName() {\n return this[rawDataSymbol].broadcaster_login;\n }\n /**\n * The display name of the broadcaster the reward belongs to.\n */\n get broadcasterDisplayName() {\n return this[rawDataSymbol].broadcaster_name;\n }\n /**\n * Gets more information about the reward's broadcaster.\n */\n async getBroadcaster() {\n return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].broadcaster_id));\n }\n /**\n * Gets the URL of the image of the reward in the given scale.\n *\n * @param scale The scale of the image.\n */\n getImageUrl(scale) {\n const urlProp = `url_${scale}x`;\n return this[rawDataSymbol].image?.[urlProp] ?? this[rawDataSymbol].default_image[urlProp];\n }\n /**\n * The background color of the reward.\n */\n get backgroundColor() {\n return this[rawDataSymbol].background_color;\n }\n /**\n * Whether the reward is enabled (shown to users).\n */\n get isEnabled() {\n return this[rawDataSymbol].is_enabled;\n }\n /**\n * The channel points cost of the reward.\n */\n get cost() {\n return this[rawDataSymbol].cost;\n }\n /**\n * The title of the reward.\n */\n get title() {\n return this[rawDataSymbol].title;\n }\n /**\n * The prompt shown to users when redeeming the reward.\n */\n get prompt() {\n return this[rawDataSymbol].prompt;\n }\n /**\n * Whether the reward requires user input to be redeemed.\n */\n get userInputRequired() {\n return this[rawDataSymbol].is_user_input_required;\n }\n /**\n * The maximum number of redemptions of the reward per stream. `null` means no limit.\n */\n get maxRedemptionsPerStream() {\n return this[rawDataSymbol].max_per_stream_setting.is_enabled\n ? this[rawDataSymbol].max_per_stream_setting.max_per_stream\n : null;\n }\n /**\n * The maximum number of redemptions of the reward per stream for each user. `null` means no limit.\n */\n get maxRedemptionsPerUserPerStream() {\n return this[rawDataSymbol].max_per_user_per_stream_setting.is_enabled\n ? this[rawDataSymbol].max_per_user_per_stream_setting.max_per_user_per_stream\n : null;\n }\n /**\n * The cooldown between two redemptions of the reward, in seconds. `null` means no cooldown.\n */\n get globalCooldown() {\n return this[rawDataSymbol].global_cooldown_setting.is_enabled\n ? this[rawDataSymbol].global_cooldown_setting.global_cooldown_seconds\n : null;\n }\n /**\n * Whether the reward is paused. If true, users can't redeem it.\n */\n get isPaused() {\n return this[rawDataSymbol].is_paused;\n }\n /**\n * Whether the reward is currently in stock.\n */\n get isInStock() {\n return this[rawDataSymbol].is_in_stock;\n }\n /**\n * How often the reward was already redeemed this stream.\n *\n * Only available when the stream is live and `maxRedemptionsPerStream` is set. Otherwise, this is `null`.\n */\n get redemptionsThisStream() {\n return this[rawDataSymbol].redemptions_redeemed_current_stream;\n }\n /**\n * Whether redemptions should automatically be marked as fulfilled.\n */\n get autoFulfill() {\n return this[rawDataSymbol].should_redemptions_skip_request_queue;\n }\n /**\n * The time when the cooldown ends. `null` means there is currently no cooldown.\n */\n get cooldownExpiryDate() {\n return this[rawDataSymbol].cooldown_expires_at ? new Date(this[rawDataSymbol].cooldown_expires_at) : null;\n }\n};\n__decorate([\n Enumerable(false)\n], HelixCustomReward.prototype, \"_client\", void 0);\nHelixCustomReward = __decorate([\n rtfm('api', 'HelixCustomReward', 'id')\n], HelixCustomReward);\nexport { HelixCustomReward };\n", "import { __decorate } from \"tslib\";\nimport { Enumerable } from '@d-fischer/shared-utils';\nimport { checkRelationAssertion, DataObject, rawDataSymbol, rtfm } from '@twurple/common';\n/**\n * A redemption of a custom Channel Points reward.\n */\nlet HelixCustomRewardRedemption = class HelixCustomRewardRedemption extends DataObject {\n /** @internal */ _client;\n /** @internal */\n constructor(data, client) {\n super(data);\n this._client = client;\n }\n /**\n * The ID of the redemption.\n */\n get id() {\n return this[rawDataSymbol].id;\n }\n /**\n * The ID of the broadcaster where the reward was redeemed.\n */\n get broadcasterId() {\n return this[rawDataSymbol].broadcaster_id;\n }\n /**\n * The name of the broadcaster where the reward was redeemed.\n */\n get broadcasterName() {\n return this[rawDataSymbol].broadcaster_login;\n }\n /**\n * The display name of the broadcaster where the reward was redeemed.\n */\n get broadcasterDisplayName() {\n return this[rawDataSymbol].broadcaster_name;\n }\n /**\n * Gets more information about the broadcaster where the reward was redeemed.\n */\n async getBroadcaster() {\n return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].broadcaster_id));\n }\n /**\n * The ID of the user that redeemed the reward.\n */\n get userId() {\n return this[rawDataSymbol].user_id;\n }\n /**\n * The name of the user that redeemed the reward.\n */\n get userName() {\n return this[rawDataSymbol].user_login;\n }\n /**\n * The display name of the user that redeemed the reward.\n */\n get userDisplayName() {\n return this[rawDataSymbol].user_name;\n }\n /**\n * Gets more information about the user that redeemed the reward.\n */\n async getUser() {\n return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].user_id));\n }\n /**\n * The text the user wrote when redeeming the reward.\n */\n get userInput() {\n return this[rawDataSymbol].user_input;\n }\n /**\n * Whether the redemption was fulfilled.\n */\n get isFulfilled() {\n return this[rawDataSymbol].status === 'FULFILLED';\n }\n /**\n * Whether the redemption was canceled.\n */\n get isCanceled() {\n return this[rawDataSymbol].status === 'CANCELED';\n }\n /**\n * The date and time when the reward was redeemed.\n */\n get redemptionDate() {\n return new Date(this[rawDataSymbol].redeemed_at);\n }\n /**\n * The ID of the reward that was redeemed.\n */\n get rewardId() {\n return this[rawDataSymbol].reward.id;\n }\n /**\n * The title of the reward that was redeemed.\n */\n get rewardTitle() {\n return this[rawDataSymbol].reward.title;\n }\n /**\n * The prompt of the reward that was redeemed.\n */\n get rewardPrompt() {\n return this[rawDataSymbol].reward.prompt;\n }\n /**\n * The cost of the reward that was redeemed.\n */\n get rewardCost() {\n return this[rawDataSymbol].reward.cost;\n }\n /**\n * Gets more information about the reward that was redeemed.\n */\n async getReward() {\n return checkRelationAssertion(await this._client.channelPoints.getCustomRewardById(this[rawDataSymbol].broadcaster_id, this[rawDataSymbol].reward.id));\n }\n /**\n * Updates the redemption's status.\n *\n * @param newStatus The status the redemption should have.\n */\n async updateStatus(newStatus) {\n const result = await this._client.channelPoints.updateRedemptionStatusByIds(this[rawDataSymbol].broadcaster_id, this[rawDataSymbol].reward.id, [this[rawDataSymbol].id], newStatus);\n return result[0];\n }\n};\n__decorate([\n Enumerable(false)\n], HelixCustomRewardRedemption.prototype, \"_client\", void 0);\nHelixCustomRewardRedemption = __decorate([\n rtfm('api', 'HelixCustomRewardRedemption', 'id')\n], HelixCustomRewardRedemption);\nexport { HelixCustomRewardRedemption };\n", "import { __decorate } from \"tslib\";\nimport { createBroadcasterQuery } from '@twurple/api-call';\nimport { extractUserId, rtfm } from '@twurple/common';\nimport { createPaginatedResult } from '../../utils/pagination/HelixPaginatedResult.js';\nimport { createPaginationQuery } from '../../utils/pagination/HelixPagination.js';\nimport { BaseApi } from '../BaseApi.js';\nimport { HelixCharityCampaign } from './HelixCharityCampaign.js';\nimport { HelixCharityCampaignDonation } from './HelixCharityCampaignDonation.js';\n/**\n * The Helix API methods that deal with charity campaigns.\n *\n * Can be accessed using `client.charity` on an {@link ApiClient} instance.\n *\n * ## Example\n * ```ts\n * const api = new ApiClient({ authProvider });\n * const charityCampaign = await api.charity.getCharityCampaign('125328655');\n * ```\n *\n * @meta category helix\n * @meta categorizedTitle Charity Campaigns\n */\nlet HelixCharityApi = class HelixCharityApi extends BaseApi {\n /**\n * Gets information about the charity campaign that a broadcaster is running.\n * Returns null if the specified broadcaster has no active charity campaign.\n *\n * @param broadcaster The broadcaster to get charity campaign information about.\n */\n async getCharityCampaign(broadcaster) {\n const response = await this._client.callApi({\n type: 'helix',\n url: 'charity/campaigns',\n method: 'GET',\n userId: extractUserId(broadcaster),\n scopes: ['channel:read:charity'],\n query: createBroadcasterQuery(broadcaster),\n });\n return new HelixCharityCampaign(response.data[0], this._client);\n }\n /**\n * Gets the list of donations that users have made to the broadcaster\u2019s active charity campaign.\n *\n * @param broadcaster The broadcaster to get charity campaign donation information about.\n * @param pagination\n *\n * @expandParams\n */\n async getCharityCampaignDonations(broadcaster, pagination) {\n const response = await this._client.callApi({\n type: 'helix',\n url: 'charity/donations',\n userId: extractUserId(broadcaster),\n scopes: ['channel:read:charity'],\n query: {\n ...createBroadcasterQuery(broadcaster),\n ...createPaginationQuery(pagination),\n },\n });\n return createPaginatedResult(response, HelixCharityCampaignDonation, this._client);\n }\n};\nHelixCharityApi = __decorate([\n rtfm('api', 'HelixCharityApi')\n], HelixCharityApi);\nexport { HelixCharityApi };\n", "import { __decorate } from \"tslib\";\nimport { Enumerable } from '@d-fischer/shared-utils';\nimport { checkRelationAssertion, DataObject, rawDataSymbol, rtfm } from '@twurple/common';\nimport { HelixCharityCampaignAmount } from './HelixCharityCampaignAmount.js';\n/**\n * A charity campaign in a Twitch channel.\n */\nlet HelixCharityCampaign = class HelixCharityCampaign extends DataObject {\n /** @internal */ _client;\n /** @internal */\n constructor(data, client) {\n super(data);\n this._client = client;\n }\n /**\n * An ID that identifies the charity campaign.\n */\n get id() {\n return this[rawDataSymbol].id;\n }\n /**\n * The ID of the broadcaster.\n */\n get broadcasterId() {\n return this[rawDataSymbol].broadcaster_id;\n }\n /**\n * The name of the broadcaster.\n */\n get broadcasterName() {\n return this[rawDataSymbol].broadcaster_login;\n }\n /**\n * The display name of the broadcaster.\n */\n get broadcasterDisplayName() {\n return this[rawDataSymbol].broadcaster_name;\n }\n /**\n * Gets more information about the broadcaster.\n */\n async getBroadcaster() {\n return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].broadcaster_id));\n }\n /**\n * The name of the charity.\n */\n get charityName() {\n return this[rawDataSymbol].charity_name;\n }\n /**\n * A description of the charity.\n */\n get charityDescription() {\n return this[rawDataSymbol].charity_description;\n }\n /**\n * A URL to an image of the charity's logo. The image\u2019s type is PNG and its size is 100px X 100px.\n */\n get charityLogo() {\n return this[rawDataSymbol].charity_logo;\n }\n /**\n * A URL to the charity\u2019s website.\n */\n get charityWebsite() {\n return this[rawDataSymbol].charity_website;\n }\n /**\n * An object that contains the current amount of donations that the campaign has received.\n */\n get currentAmount() {\n return new HelixCharityCampaignAmount(this[rawDataSymbol].current_amount);\n }\n /**\n * An object that contains the campaign\u2019s target fundraising goal.\n */\n get targetAmount() {\n return new HelixCharityCampaignAmount(this[rawDataSymbol].target_amount);\n }\n};\n__decorate([\n Enumerable(false)\n], HelixCharityCampaign.prototype, \"_client\", void 0);\nHelixCharityCampaign = __decorate([\n rtfm('api', 'HelixCharityCampaign', 'id')\n], HelixCharityCampaign);\nexport { HelixCharityCampaign };\n", "import { __decorate } from \"tslib\";\nimport { DataObject, rawDataSymbol, rtfm } from '@twurple/common';\n/**\n * An object representing monetary amount and currency information for charity donations/goals.\n */\nlet HelixCharityCampaignAmount = class HelixCharityCampaignAmount extends DataObject {\n /**\n * The monetary amount. The amount is specified in the currency\u2019s minor unit.\n * For example, the minor units for USD is cents, so if the amount is $5.50 USD, `value` is set to 550.\n */\n get value() {\n return this[rawDataSymbol].value;\n }\n /**\n * The number of decimal places used by the currency. For example, USD uses two decimal places.\n * Use this number to translate `value` from minor units to major units by using the formula:\n *\n * `value / 10^decimalPlaces`\n */\n get decimalPlaces() {\n return this[rawDataSymbol].decimal_places;\n }\n /**\n * The localized monetary amount based on the value and the decimal places of the currency.\n * For example, the minor units for USD is cents which uses two decimal places, so if `value` is 550, `localizedValue` is set to 5.50.\n */\n get localizedValue() {\n return this.value / 10 ** this.decimalPlaces;\n }\n /**\n * The ISO-4217 three-letter currency code that identifies the type of currency in `value`.\n */\n get currency() {\n return this[rawDataSymbol].currency;\n }\n};\nHelixCharityCampaignAmount = __decorate([\n rtfm('api', 'HelixCharityCampaignAmount')\n], HelixCharityCampaignAmount);\nexport { HelixCharityCampaignAmount };\n", "import { __decorate } from \"tslib\";\nimport { Enumerable } from '@d-fischer/shared-utils';\nimport { checkRelationAssertion, DataObject, rawDataSymbol, rtfm } from '@twurple/common';\nimport { HelixCharityCampaignAmount } from './HelixCharityCampaignAmount.js';\n/**\n * A donation to a charity campaign in a Twitch channel.\n */\nlet HelixCharityCampaignDonation = class HelixCharityCampaignDonation extends DataObject {\n /** @internal */ _client;\n /** @internal */\n constructor(data, client) {\n super(data);\n this._client = client;\n }\n /**\n * An ID that identifies the charity campaign.\n */\n get campaignId() {\n return this[rawDataSymbol].campaign_id;\n }\n /**\n * The ID of the donating user.\n */\n get donorId() {\n return this[rawDataSymbol].user_id;\n }\n /**\n * The name of the donating user.\n */\n get donorName() {\n return this[rawDataSymbol].user_login;\n }\n /**\n * The display name of the donating user.\n */\n get donorDisplayName() {\n return this[rawDataSymbol].user_name;\n }\n /**\n * Gets more information about the donating user.\n */\n async getDonor() {\n return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].user_id));\n }\n /**\n * An object that contains the amount of money that the user donated.\n */\n get amount() {\n return new HelixCharityCampaignAmount(this[rawDataSymbol].amount);\n }\n};\n__decorate([\n Enumerable(false)\n], HelixCharityCampaignDonation.prototype, \"_client\", void 0);\nHelixCharityCampaignDonation = __decorate([\n rtfm('api', 'HelixCharityCampaignDonation')\n], HelixCharityCampaignDonation);\nexport { HelixCharityCampaignDonation };\n", "import { __decorate } from \"tslib\";\nimport { createBroadcasterQuery } from '@twurple/api-call';\nimport { extractUserId, rtfm } from '@twurple/common';\nimport { ChatMessageDroppedError } from '../../errors/ChatMessageDroppedError.js';\nimport { createChatColorUpdateQuery, createChatSettingsUpdateBody, createSendChatMessageAsAppBody, createSendChatMessageBody, createSendChatMessageQuery, createShoutoutQuery, } from '../../interfaces/endpoints/chat.external.js';\nimport { createModeratorActionQuery, createSingleKeyQuery } from '../../interfaces/endpoints/generic.external.js';\nimport { createSharedChatSessionQuery, } from '../../interfaces/endpoints/shared-chat-session.external.js';\nimport { HelixPaginatedRequest } from '../../utils/pagination/HelixPaginatedRequest.js';\nimport { HelixPaginatedRequestWithTotal } from '../../utils/pagination/HelixPaginatedRequestWithTotal.js';\nimport { createPaginatedResult, createPaginatedResultWithTotal, } from '../../utils/pagination/HelixPaginatedResult.js';\nimport { createPaginationQuery } from '../../utils/pagination/HelixPagination.js';\nimport { BaseApi } from '../BaseApi.js';\nimport { HelixChannelEmote } from './HelixChannelEmote.js';\nimport { HelixChatBadgeSet } from './HelixChatBadgeSet.js';\nimport { HelixChatChatter } from './HelixChatChatter.js';\nimport { HelixChatSettings } from './HelixChatSettings.js';\nimport { HelixEmote } from './HelixEmote.js';\nimport { HelixEmoteFromSet } from './HelixEmoteFromSet.js';\nimport { HelixPrivilegedChatSettings } from './HelixPrivilegedChatSettings.js';\nimport { HelixSentChatMessage } from './HelixSentChatMessage.js';\nimport { HelixSharedChatSession } from './HelixSharedChatSession.js';\nimport { HelixUserEmote } from './HelixUserEmote.js';\n/**\n * The Helix API methods that deal with chat.\n *\n * Can be accessed using `client.chat` on an {@link ApiClient} instance.\n *\n * ## Example\n * ```ts\n * const api = new ApiClient({ authProvider });\n * const rewards = await api.chat.getChannelBadges('125328655');\n * ```\n *\n * @meta category helix\n * @meta categorizedTitle Chat\n */\nlet HelixChatApi = class HelixChatApi extends BaseApi {\n /**\n * Gets the list of users that are connected to the broadcaster\u2019s chat session.\n *\n * This uses the token of the broadcaster by default.\n * If you want to execute this in the context of another user (who has to be moderator of the channel)\n * you can do so using [user context overrides](/docs/auth/concepts/context-switching).\n *\n * @param broadcaster The broadcaster whose list of chatters you want to get.\n * @param pagination\n *\n * @expandParams\n */\n async getChatters(broadcaster, pagination) {\n const broadcasterId = extractUserId(broadcaster);\n const result = await this._client.callApi({\n type: 'helix',\n url: 'chat/chatters',\n userId: broadcasterId,\n canOverrideScopedUserContext: true,\n scopes: ['moderator:read:chatters'],\n query: {\n ...this._createModeratorActionQuery(broadcasterId),\n ...createPaginationQuery(pagination),\n },\n });\n return createPaginatedResultWithTotal(result, HelixChatChatter, this._client);\n }\n /**\n * Creates a paginator for users that are connected to the broadcaster\u2019s chat session.\n *\n * This uses the token of the broadcaster by default.\n * If you want to execute this in the context of another user (who has to be moderator of the channel)\n * you can do so using [user context overrides](/docs/auth/concepts/context-switching).\n *\n * @param broadcaster The broadcaster whose list of chatters you want to get.\n *\n * @expandParams\n */\n getChattersPaginated(broadcaster) {\n const broadcasterId = extractUserId(broadcaster);\n return new HelixPaginatedRequestWithTotal({\n url: 'chat/chatters',\n userId: broadcasterId,\n canOverrideScopedUserContext: true,\n scopes: ['moderator:read:chatters'],\n query: this._createModeratorActionQuery(broadcasterId),\n }, this._client, data => new HelixChatChatter(data, this._client), 1000);\n }\n /**\n * Gets all global badges.\n */\n async getGlobalBadges() {\n const result = await this._client.callApi({\n type: 'helix',\n url: 'chat/badges/global',\n });\n return result.data.map(data => new HelixChatBadgeSet(data));\n }\n /**\n * Gets all badges specific to the given broadcaster.\n *\n * @param broadcaster The broadcaster to get badges for.\n */\n async getChannelBadges(broadcaster) {\n const result = await this._client.callApi({\n type: 'helix',\n url: 'chat/badges',\n userId: extractUserId(broadcaster),\n query: createBroadcasterQuery(broadcaster),\n });\n return result.data.map(data => new HelixChatBadgeSet(data));\n }\n /**\n * Gets all global emotes.\n */\n async getGlobalEmotes() {\n const result = await this._client.callApi({\n type: 'helix',\n url: 'chat/emotes/global',\n });\n return result.data.map(data => new HelixEmote(data));\n }\n /**\n * Gets all emotes specific to the given broadcaster.\n *\n * @param broadcaster The broadcaster to get emotes for.\n */\n async getChannelEmotes(broadcaster) {\n const result = await this._client.callApi({\n type: 'helix',\n url: 'chat/emotes',\n userId: extractUserId(broadcaster),\n query: createBroadcasterQuery(broadcaster),\n });\n return result.data.map(data => new HelixChannelEmote(data, this._client));\n }\n /**\n * Gets all emotes from a list of emote sets.\n *\n * @param setIds The IDs of the emote sets to get emotes from.\n */\n async getEmotesFromSets(setIds) {\n const result = await this._client.callApi({\n type: 'helix',\n url: 'chat/emotes/set',\n query: createSingleKeyQuery('emote_set_id', setIds),\n });\n return result.data.map(data => new HelixEmoteFromSet(data, this._client));\n }\n /**\n * Gets emotes available to the user across all channels.\n *\n * @param user The ID of the user to get available emotes of.\n * @param filter Additional query filters.\n */\n async getUserEmotes(user, filter) {\n const userId = extractUserId(user);\n const result = await this._client.callApi({\n type: 'helix',\n url: 'chat/emotes/user',\n userId: extractUserId(user),\n scopes: ['user:read:emotes'],\n query: {\n ...createSingleKeyQuery('user_id', userId),\n ...createSingleKeyQuery('broadcasterId', filter?.broadcaster ? extractUserId(filter.broadcaster) : undefined),\n ...createPaginationQuery(filter),\n },\n });\n return createPaginatedResult(result, HelixUserEmote, this._client);\n }\n /**\n * Creates a paginator for emotes available to the user across all channels.\n *\n * @param user The ID of the user to get available emotes of.\n * @param broadcaster The ID of a broadcaster you wish to get follower emotes of. Using this query parameter will\n * guarantee inclusion of the broadcaster\u2019s follower emotes in the response body.\n *\n * If the user who retrieves their emotes is subscribed to the broadcaster specified, their follower emotes will\n * appear in the response body regardless of whether this query parameter is used.\n */\n getUserEmotesPaginated(user, broadcaster) {\n const userId = extractUserId(user);\n return new HelixPaginatedRequest({\n url: 'chat/emotes/user',\n userId,\n scopes: ['user:read:emotes'],\n query: {\n ...createSingleKeyQuery('user_id', userId),\n ...createSingleKeyQuery('broadcasterId', broadcaster ? extractUserId(broadcaster) : undefined),\n },\n }, this._client, (data) => new HelixUserEmote(data, this._client));\n }\n /**\n * Gets the settings of a broadcaster's chat.\n *\n * @param broadcaster The broadcaster the chat belongs to.\n */\n async getSettings(broadcaster) {\n const result = await this._client.callApi({\n type: 'helix',\n url: 'chat/settings',\n userId: extractUserId(broadcaster),\n query: createBroadcasterQuery(broadcaster),\n });\n return new HelixChatSettings(result.data[0]);\n }\n /**\n * Gets the settings of a broadcaster's chat, including the delay settings.\n *\n * This uses the token of the broadcaster by default.\n * If you want to execute this in the context of another user (who has to be moderator of the channel)\n * you can do so using [user context overrides](/docs/auth/concepts/context-switching).\n *\n * @param broadcaster The broadcaster the chat belongs to.\n */\n async getSettingsPrivileged(broadcaster) {\n const broadcasterId = extractUserId(broadcaster);\n const result = await this._client.callApi({\n type: 'helix',\n url: 'chat/settings',\n userId: broadcasterId,\n canOverrideScopedUserContext: true,\n scopes: ['moderator:read:chat_settings'],\n query: this._createModeratorActionQuery(broadcasterId),\n });\n return new HelixPrivilegedChatSettings(result.data[0]);\n }\n /**\n * Updates the settings of a broadcaster's chat.\n *\n * This uses the token of the broadcaster by default.\n * If you want to execute this in the context of another user (who has to be moderator of the channel)\n * you can do so using [user context overrides](/docs/auth/concepts/context-switching).\n *\n * @expandParams\n *\n * @param broadcaster The broadcaster the chat belongs to.\n * @param settings The settings to change.\n */\n async updateSettings(broadcaster, settings) {\n const broadcasterId = extractUserId(broadcaster);\n const result = await this._client.callApi({\n type: 'helix',\n url: 'chat/settings',\n method: 'PATCH',\n userId: broadcasterId,\n canOverrideScopedUserContext: true,\n scopes: ['moderator:manage:chat_settings'],\n query: this._createModeratorActionQuery(broadcasterId),\n jsonBody: createChatSettingsUpdateBody(settings),\n });\n return new HelixPrivilegedChatSettings(result.data[0]);\n }\n /**\n * Sends a chat message to a broadcaster's chat.\n *\n * This uses the token of the broadcaster by default.\n * If you want to execute this in the context of another user\n * you can do so using [user context overrides](/docs/auth/concepts/context-switching).\n *\n * @expandParams\n *\n * @param broadcaster The broadcaster the chat belongs to.\n * @param message The message to send.\n * @param params\n */\n async sendChatMessage(broadcaster, message, params) {\n const broadcasterId = extractUserId(broadcaster);\n const result = await this._client.callApi({\n type: 'helix',\n url: 'chat/messages',\n method: 'POST',\n userId: broadcasterId,\n canOverrideScopedUserContext: true,\n scopes: ['user:write:chat'],\n query: createSendChatMessageQuery(broadcasterId, this._getUserContextIdWithDefault(broadcasterId)),\n jsonBody: createSendChatMessageBody(message, params),\n });\n const msg = new HelixSentChatMessage(result.data[0]);\n this._handleUnsentChatMessage(broadcasterId, msg);\n return msg;\n }\n /**\n * Sends a chat message to a broadcaster's chat, using an app token.\n *\n * This requires the scopes `user:write:chat` and `user:bot` for the `user` and `channel:bot` for the `broadcaster`.\n * `channel:bot` is not required if the `user` has moderator privileges in the `broadcaster`'s channel.\n *\n * These scope requirements can not be checked by the library, so they are just assumed.\n * Make sure to catch authorization errors yourself.\n *\n * @expandParams\n *\n * @param user The user to send the chat message from.\n * @param broadcaster The broadcaster the chat belongs to.\n * @param message The message to send.\n * @param params\n */\n async sendChatMessageAsApp(user, broadcaster, message, params) {\n const userId = extractUserId(user);\n const broadcasterId = extractUserId(broadcaster);\n const result = await this._client.callApi({\n type: 'helix',\n url: 'chat/messages',\n method: 'POST',\n forceType: 'app',\n query: createSendChatMessageQuery(broadcasterId, userId),\n jsonBody: createSendChatMessageAsAppBody(message, params),\n });\n const msg = new HelixSentChatMessage(result.data[0]);\n this._handleUnsentChatMessage(broadcasterId, msg);\n return msg;\n }\n /**\n * Sends an announcement to a broadcaster's chat.\n *\n * This uses the token of the broadcaster by default.\n * If you want to execute this in the context of another user (who has to be moderator of the channel)\n * you can do so using [user context overrides](/docs/auth/concepts/context-switching).\n *\n * @param broadcaster The broadcaster the chat belongs to.\n * @param announcement The announcement to send.\n */\n async sendAnnouncement(broadcaster, announcement) {\n const broadcasterId = extractUserId(broadcaster);\n await this._client.callApi({\n type: 'helix',\n url: 'chat/announcements',\n method: 'POST',\n userId: broadcasterId,\n canOverrideScopedUserContext: true,\n scopes: ['moderator:manage:announcements'],\n query: this._createModeratorActionQuery(broadcasterId),\n jsonBody: {\n message: announcement.message,\n color: announcement.color,\n },\n });\n }\n /**\n * Gets the chat colors for a list of users.\n *\n * Returns a Map with user IDs as keys and their colors as values.\n * The value is a color hex code, or `null` if the user did not set a color,\n * and unknown users will not be present in the map.\n *\n * @param users The users to get the chat colors of.\n */\n async getColorsForUsers(users) {\n const response = await this._client.callApi({\n type: 'helix',\n url: 'chat/color',\n query: createSingleKeyQuery('user_id', users.map(extractUserId)),\n });\n return new Map(response.data.map(data => [data.user_id, data.color || null]));\n }\n /**\n * Gets the chat color for a user.\n *\n * Returns the color as hex code, `null` if the user did not set a color, or `undefined` if the user is unknown.\n *\n * @param user The user to get the chat color of.\n */\n async getColorForUser(user) {\n const response = await this._client.callApi({\n type: 'helix',\n url: 'chat/color',\n userId: extractUserId(user),\n query: createSingleKeyQuery('user_id', extractUserId(user)),\n });\n if (!response.data.length) {\n return undefined;\n }\n return response.data[0].color || null;\n }\n /**\n * Changes the chat color for a user.\n *\n * @param user The user to change the color of.\n * @param color The color to set.\n *\n * Note that hex codes can only be used by users that have a Prime or Turbo subscription.\n */\n async setColorForUser(user, color) {\n await this._client.callApi({\n type: 'helix',\n url: 'chat/color',\n method: 'PUT',\n userId: extractUserId(user),\n scopes: ['user:manage:chat_color'],\n query: createChatColorUpdateQuery(user, color),\n });\n }\n /**\n * Sends a shoutout to the specified broadcaster.\n * The broadcaster may send a shoutout once every 2 minutes. They may send the same broadcaster a shoutout once every 60 minutes.\n *\n * This uses the token of the broadcaster by default.\n * If you want to execute this in the context of another user (who has to be moderator of the channel)\n * you can do so using [user context overrides](/docs/auth/concepts/context-switching).\n *\n * @param from The ID of the broadcaster that\u2019s sending the shoutout.\n * @param to The ID of the broadcaster that\u2019s receiving the shoutout.\n */\n async shoutoutUser(from, to) {\n const fromId = extractUserId(from);\n await this._client.callApi({\n type: 'helix',\n url: 'chat/shoutouts',\n method: 'POST',\n userId: fromId,\n canOverrideScopedUserContext: true,\n scopes: ['moderator:manage:shoutouts'],\n query: createShoutoutQuery(from, to, this._getUserContextIdWithDefault(fromId)),\n });\n }\n /**\n * Gets the active shared chat session for a channel.\n *\n * Returns `null` if there is no active shared chat session in the channel.\n *\n * @param broadcaster The broadcaster to get the active shared chat session for.\n */\n async getSharedChatSession(broadcaster) {\n const broadcasterId = extractUserId(broadcaster);\n const response = await this._client.callApi({\n type: 'helix',\n url: 'shared_chat/session',\n userId: broadcasterId,\n query: createSharedChatSessionQuery(broadcasterId),\n });\n if (response.data.length === 0) {\n return null;\n }\n return new HelixSharedChatSession(response.data[0], this._client);\n }\n _createModeratorActionQuery(broadcasterId) {\n return createModeratorActionQuery(broadcasterId, this._getUserContextIdWithDefault(broadcasterId));\n }\n _handleUnsentChatMessage(broadcasterId, msg) {\n if (!msg.isSent) {\n throw new ChatMessageDroppedError(broadcasterId, msg.dropReasonMessage, msg.dropReasonCode);\n }\n }\n};\nHelixChatApi = __decorate([\n rtfm('api', 'HelixChatApi')\n], HelixChatApi);\nexport { HelixChatApi };\n", "import { CustomError } from '@twurple/common';\n/**\n * Thrown when a chat message is dropped and not delivered to the target channel.\n */\nexport class ChatMessageDroppedError extends CustomError {\n _code;\n constructor(broadcasterId, message, code) {\n super(`Chat message to channel ${broadcasterId} dropped: ${message ?? 'unknown reason'}`);\n this._code = code;\n }\n get code() {\n return this._code;\n }\n}\n", "import { extractUserId } from '@twurple/common';\n/** @internal */\nexport function createChatSettingsUpdateBody(settings) {\n return {\n slow_mode: settings.slowModeEnabled,\n slow_mode_wait_time: settings.slowModeDelay,\n follower_mode: settings.followerOnlyModeEnabled,\n follower_mode_duration: settings.followerOnlyModeDelay,\n subscriber_mode: settings.subscriberOnlyModeEnabled,\n emote_mode: settings.emoteOnlyModeEnabled,\n unique_chat_mode: settings.uniqueChatModeEnabled,\n non_moderator_chat_delay: settings.nonModeratorChatDelayEnabled,\n non_moderator_chat_delay_duration: settings.nonModeratorChatDelay,\n };\n}\n/** @internal */\nexport function createChatColorUpdateQuery(user, color) {\n return {\n user_id: extractUserId(user),\n color,\n };\n}\n/** @internal */\nexport function createShoutoutQuery(from, to, moderatorId) {\n return {\n from_broadcaster_id: extractUserId(from),\n to_broadcaster_id: extractUserId(to),\n moderator_id: moderatorId,\n };\n}\n/** @internal */\nexport function createSendChatMessageQuery(broadcaster, sender) {\n return {\n broadcaster_id: broadcaster,\n sender_id: sender,\n };\n}\n/** @internal */\nexport function createSendChatMessageBody(message, params) {\n return {\n message,\n reply_parent_message_id: params?.replyParentMessageId,\n };\n}\n/** @internal */\nexport function createSendChatMessageAsAppBody(message, params) {\n return {\n message,\n reply_parent_message_id: params?.replyParentMessageId,\n for_source_only: params?.forSourceOnly,\n };\n}\n", "import { extractUserId } from '@twurple/common';\n/** @internal */\nexport function createSharedChatSessionQuery(broadcaster) {\n return {\n broadcaster_id: extractUserId(broadcaster),\n };\n}\n", "import { __decorate } from \"tslib\";\nimport { Enumerable } from '@d-fischer/shared-utils';\nimport { rawDataSymbol, rtfm } from '@twurple/common';\nimport { HelixEmote } from './HelixEmote.js';\n/**\n * A Twitch Channel emote.\n *\n * @inheritDoc\n */\nlet HelixChannelEmote = class HelixChannelEmote extends HelixEmote {\n /** @internal */ _client;\n constructor(data, client) {\n super(data);\n this._client = client;\n }\n /**\n * The subscription tier necessary to unlock the emote, or null if the emote is not a subscription emote.\n */\n get tier() {\n return this[rawDataSymbol].tier || null;\n }\n /**\n * The type of the emote.\n *\n * There are many types of emotes that Twitch seems to arbitrarily assign. Do not rely on this value.\n */\n get type() {\n return this[rawDataSymbol].emote_type;\n }\n /**\n * The ID of the emote set the emote is part of.\n */\n get emoteSetId() {\n return this[rawDataSymbol].emote_set_id;\n }\n /**\n * Gets all emotes from the emote's set.\n */\n async getAllEmotesFromSet() {\n return await this._client.chat.getEmotesFromSets([this[rawDataSymbol].emote_set_id]);\n }\n};\n__decorate([\n Enumerable(false)\n], HelixChannelEmote.prototype, \"_client\", void 0);\nHelixChannelEmote = __decorate([\n rtfm('api', 'HelixChannelEmote', 'id')\n], HelixChannelEmote);\nexport { HelixChannelEmote };\n", "import { __decorate } from \"tslib\";\nimport { rawDataSymbol, rtfm } from '@twurple/common';\nimport { HelixEmoteBase } from './HelixEmoteBase.js';\n/**\n * A Twitch emote.\n */\nlet HelixEmote = class HelixEmote extends HelixEmoteBase {\n /**\n * Gets the URL of the emote image in the given scale.\n *\n * @param scale The scale of the image.\n */\n getImageUrl(scale) {\n return this[rawDataSymbol].images[`url_${scale}x`];\n }\n};\nHelixEmote = __decorate([\n rtfm('api', 'HelixEmote', 'id')\n], HelixEmote);\nexport { HelixEmote };\n", "import { DataObject, rawDataSymbol } from '@twurple/common';\n/** @private */\nexport class HelixEmoteBase extends DataObject {\n /**\n * The ID of the emote.\n */\n get id() {\n return this[rawDataSymbol].id;\n }\n /**\n * The name of the emote.\n */\n get name() {\n return this[rawDataSymbol].name;\n }\n /**\n * The formats that the emote is available in.\n */\n get formats() {\n return this[rawDataSymbol].format;\n }\n /**\n * The scales that the emote is available in.\n */\n get scales() {\n return this[rawDataSymbol].scale;\n }\n /**\n * The theme modes that the emote is available in.\n */\n get themeModes() {\n return this[rawDataSymbol].theme_mode;\n }\n /**\n * Gets the URL of the emote image in static format at the given scale and theme mode, or null if a static emote image at that scale/theme mode doesn't exist.\n *\n * @param scale The scale of the image.\n * @param themeMode The theme mode of the image, either `light` or `dark`.\n */\n getStaticImageUrl(scale = '1.0', themeMode = 'light') {\n if (this[rawDataSymbol].format.includes('static') && this[rawDataSymbol].scale.includes(scale)) {\n return this.getFormattedImageUrl(scale, 'static', themeMode);\n }\n return null;\n }\n /**\n * Gets the URL of the emote image in animated format at the given scale and theme mode, or null if an animated emote image at that scale/theme mode doesn't exist.\n *\n * @param scale The scale of the image.\n * @param themeMode The theme mode of the image, either `light` or `dark`.\n */\n getAnimatedImageUrl(scale = '1.0', themeMode = 'light') {\n if (this[rawDataSymbol].format.includes('animated') && this[rawDataSymbol].scale.includes(scale)) {\n return this.getFormattedImageUrl(scale, 'animated', themeMode);\n }\n return null;\n }\n /**\n * Gets the URL of the emote image in the given scale, format, and theme mode.\n *\n * @param scale The scale of the image, either `1.0` (small), `2.0` (medium), or `3.0` (large).\n * @param format The format of the image, either `static` or `animated`.\n * @param themeMode The theme mode of the image, either `light` or `dark`.\n */\n getFormattedImageUrl(scale = '1.0', format = 'static', themeMode = 'light') {\n return `https://static-cdn.jtvnw.net/emoticons/v2/${this[rawDataSymbol].id}/${format}/${themeMode}/${scale}`;\n }\n}\n", "import { __decorate } from \"tslib\";\nimport { Cacheable, CachedGetter } from '@d-fischer/cache-decorators';\nimport { DataObject, rawDataSymbol, rtfm } from '@twurple/common';\nimport { HelixChatBadgeVersion } from './HelixChatBadgeVersion.js';\n/**\n * A version of a chat badge.\n */\nlet HelixChatBadgeSet = class HelixChatBadgeSet extends DataObject {\n /**\n * The badge set ID.\n */\n get id() {\n return this[rawDataSymbol].set_id;\n }\n /**\n * All versions of the badge.\n */\n get versions() {\n return this[rawDataSymbol].versions.map(data => new HelixChatBadgeVersion(data));\n }\n /**\n * Gets a specific version of the badge.\n *\n * @param versionId The ID of the version.\n */\n getVersion(versionId) {\n return this.versions.find(v => v.id === versionId) ?? null;\n }\n};\n__decorate([\n CachedGetter()\n], HelixChatBadgeSet.prototype, \"versions\", null);\nHelixChatBadgeSet = __decorate([\n Cacheable,\n rtfm('api', 'HelixChatBadgeSet', 'id')\n], HelixChatBadgeSet);\nexport { HelixChatBadgeSet };\n", "import { __decorate } from \"tslib\";\nimport { DataObject, rawDataSymbol, rtfm } from '@twurple/common';\n/**\n * A version of a chat badge.\n */\nlet HelixChatBadgeVersion = class HelixChatBadgeVersion extends DataObject {\n /**\n * The badge version ID.\n */\n get id() {\n return this[rawDataSymbol].id;\n }\n /**\n * Gets an image URL for the given scale.\n *\n * @param scale The scale of the badge image.\n */\n getImageUrl(scale) {\n return this[rawDataSymbol][`image_url_${scale}x`];\n }\n /**\n * The title of the badge.\n */\n get title() {\n return this[rawDataSymbol].title;\n }\n /**\n * The description of the badge.\n */\n get description() {\n return this[rawDataSymbol].description;\n }\n /**\n * The action to take when clicking on the badge. Set to `null` if no action is specified.\n */\n get clickAction() {\n return this[rawDataSymbol].click_action;\n }\n /**\n * The URL to navigate to when clicking on the badge. Set to `null` if no URL is specified.\n */\n get clickUrl() {\n return this[rawDataSymbol].click_url;\n }\n};\nHelixChatBadgeVersion = __decorate([\n rtfm('api', 'HelixChatBadgeVersion', 'id')\n], HelixChatBadgeVersion);\nexport { HelixChatBadgeVersion };\n", "import { __decorate } from \"tslib\";\nimport { Enumerable } from '@d-fischer/shared-utils';\nimport { checkRelationAssertion, DataObject, rawDataSymbol, rtfm } from '@twurple/common';\n/**\n * A user connected to a Twitch channel's chat session.\n */\nlet HelixChatChatter = class HelixChatChatter extends DataObject {\n /** @internal */ _client;\n /** @internal */\n constructor(data, client) {\n super(data);\n this._client = client;\n }\n /**\n * The ID of the user.\n */\n get userId() {\n return this[rawDataSymbol].user_id;\n }\n /**\n * The name of the user.\n */\n get userName() {\n return this[rawDataSymbol].user_login;\n }\n /**\n * The display name of the user.\n */\n get userDisplayName() {\n return this[rawDataSymbol].user_name;\n }\n /**\n * Gets more information about the user.\n */\n async getUser() {\n return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].user_id));\n }\n};\n__decorate([\n Enumerable(false)\n], HelixChatChatter.prototype, \"_client\", void 0);\nHelixChatChatter = __decorate([\n rtfm('api', 'HelixChatChatter')\n], HelixChatChatter);\nexport { HelixChatChatter };\n", "import { __decorate } from \"tslib\";\nimport { DataObject, rawDataSymbol, rtfm } from '@twurple/common';\n/**\n * The settings of a broadcaster's chat.\n */\nlet HelixChatSettings = class HelixChatSettings extends DataObject {\n /**\n * The ID of the broadcaster.\n */\n get broadcasterId() {\n return this[rawDataSymbol].broadcaster_id;\n }\n /**\n * Whether slow mode is enabled.\n */\n get slowModeEnabled() {\n return this[rawDataSymbol].slow_mode;\n }\n /**\n * The time to wait between messages in slow mode, in seconds.\n *\n * Is `null` if slow mode is not enabled.\n */\n get slowModeDelay() {\n return this[rawDataSymbol].slow_mode_wait_time;\n }\n /**\n * Whether follower only mode is enabled.\n */\n get followerOnlyModeEnabled() {\n return this[rawDataSymbol].follower_mode;\n }\n /**\n * The time after which users are able to send messages after following, in minutes.\n *\n * Is `null` if follower only mode is not enabled,\n * but may also be `0` if you can send messages immediately after following.\n */\n get followerOnlyModeDelay() {\n return this[rawDataSymbol].follower_mode_duration;\n }\n /**\n * Whether subscriber only mode is enabled.\n */\n get subscriberOnlyModeEnabled() {\n return this[rawDataSymbol].subscriber_mode;\n }\n /**\n * Whether emote only mode is enabled.\n */\n get emoteOnlyModeEnabled() {\n return this[rawDataSymbol].emote_mode;\n }\n /**\n * Whether unique chat mode is enabled.\n */\n get uniqueChatModeEnabled() {\n return this[rawDataSymbol].unique_chat_mode;\n }\n};\nHelixChatSettings = __decorate([\n rtfm('api', 'HelixChatSettings', 'broadcasterId')\n], HelixChatSettings);\nexport { HelixChatSettings };\n", "import { __decorate } from \"tslib\";\nimport { Enumerable } from '@d-fischer/shared-utils';\nimport { rawDataSymbol, rtfm } from '@twurple/common';\nimport { HelixEmote } from './HelixEmote.js';\n/**\n * A Twitch Channel emote.\n *\n * @inheritDoc\n */\nlet HelixEmoteFromSet = class HelixEmoteFromSet extends HelixEmote {\n /** @internal */ _client;\n constructor(data, client) {\n super(data);\n this._client = client;\n }\n /**\n * The type of the emote.\n *\n * Known values are: `subscriptions`, `bitstier`, `follower`, `rewards`, `globals`, `smilies`, `prime`, `limitedtime`.\n *\n * This list may be non-exhaustive.\n */\n get type() {\n return this[rawDataSymbol].emote_type;\n }\n /**\n * The ID of the emote set the emote is part of.\n */\n get emoteSetId() {\n return this[rawDataSymbol].emote_set_id;\n }\n /**\n * The ID of the user that owns the emote, or null if the emote is not owned by a user.\n */\n get ownerId() {\n switch (this[rawDataSymbol].owner_id) {\n case '0':\n case 'twitch': {\n return null;\n }\n default: {\n return this[rawDataSymbol].owner_id;\n }\n }\n }\n /**\n * Gets more information about the user that owns the emote, or null if the emote is not owned by a user.\n */\n async getOwner() {\n switch (this[rawDataSymbol].owner_id) {\n case '0':\n case 'twitch': {\n return null;\n }\n default: {\n return await this._client.users.getUserById(this[rawDataSymbol].owner_id);\n }\n }\n }\n};\n__decorate([\n Enumerable(false)\n], HelixEmoteFromSet.prototype, \"_client\", void 0);\nHelixEmoteFromSet = __decorate([\n rtfm('api', 'HelixEmoteFromSet', 'id')\n], HelixEmoteFromSet);\nexport { HelixEmoteFromSet };\n", "import { __decorate } from \"tslib\";\nimport { rawDataSymbol, rtfm } from '@twurple/common';\nimport { HelixChatSettings } from './HelixChatSettings.js';\n/**\n * The settings of a broadcaster's chat, with additional privileged data.\n */\nlet HelixPrivilegedChatSettings = class HelixPrivilegedChatSettings extends HelixChatSettings {\n /**\n * Whether non-moderator messages are delayed.\n */\n get nonModeratorChatDelayEnabled() {\n return this[rawDataSymbol].non_moderator_chat_delay;\n }\n /**\n * The delay of non-moderator messages, in seconds.\n *\n * Is `null` if non-moderator message delay is disabled.\n */\n get nonModeratorChatDelay() {\n return this[rawDataSymbol].non_moderator_chat_delay_duration;\n }\n};\nHelixPrivilegedChatSettings = __decorate([\n rtfm('api', 'HelixPrivilegedChatSettings', 'broadcasterId')\n], HelixPrivilegedChatSettings);\nexport { HelixPrivilegedChatSettings };\n", "import { __decorate } from \"tslib\";\nimport { DataObject, rawDataSymbol, rtfm } from '@twurple/common';\n/**\n * Information about a sent Twitch chat message.\n */\nlet HelixSentChatMessage = class HelixSentChatMessage extends DataObject {\n /**\n * The message ID of the sent message.\n */\n get id() {\n return this[rawDataSymbol].message_id;\n }\n /**\n * If the message passed all checks and was sent.\n */\n get isSent() {\n return this[rawDataSymbol].is_sent;\n }\n /**\n * The reason code for why the chat message was dropped, if dropped.\n */\n get dropReasonCode() {\n return this[rawDataSymbol].drop_reason?.code;\n }\n /**\n * The reason message for why the chat message was dropped, if dropped.\n */\n get dropReasonMessage() {\n return this[rawDataSymbol].drop_reason?.message;\n }\n};\nHelixSentChatMessage = __decorate([\n rtfm('api', 'HelixSentChatMessage', 'id')\n], HelixSentChatMessage);\nexport { HelixSentChatMessage };\n", "import { __decorate } from \"tslib\";\nimport { Enumerable } from '@d-fischer/shared-utils';\nimport { checkRelationAssertion, DataObject, rawDataSymbol, rtfm } from '@twurple/common';\nimport { HelixSharedChatSessionParticipant } from './HelixSharedChatSessionParticipant.js';\n/**\n * A shared chat session.\n */\nlet HelixSharedChatSession = class HelixSharedChatSession extends DataObject {\n /** @internal */ _client;\n /** @internal */\n constructor(data, client) {\n super(data);\n this._client = client;\n }\n /**\n * The unique identifier for the shared chat session.\n */\n get sessionId() {\n return this[rawDataSymbol].session_id;\n }\n /**\n * The ID of the host broadcaster.\n */\n get hostBroadcasterId() {\n return this[rawDataSymbol].host_broadcaster_id;\n }\n /**\n * Gets information about the host broadcaster.\n */\n async getHostBroadcaster() {\n return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].host_broadcaster_id));\n }\n /**\n * The list of participants in the session.\n */\n get participants() {\n return this[rawDataSymbol].participants.map(data => new HelixSharedChatSessionParticipant(data, this._client));\n }\n /**\n * The date for when the session was created.\n */\n get createdDate() {\n return new Date(this[rawDataSymbol].created_at);\n }\n /**\n * The date for when the session was updated.\n */\n get updatedDate() {\n return new Date(this[rawDataSymbol].updated_at);\n }\n};\n__decorate([\n Enumerable(false)\n], HelixSharedChatSession.prototype, \"_client\", void 0);\nHelixSharedChatSession = __decorate([\n rtfm('api', 'HelixSharedChatSession', 'sessionId')\n], HelixSharedChatSession);\nexport { HelixSharedChatSession };\n", "import { __decorate } from \"tslib\";\nimport { Enumerable } from '@d-fischer/shared-utils';\nimport { checkRelationAssertion, DataObject, rawDataSymbol, rtfm } from '@twurple/common';\n/**\n * A shared chat session participant.\n */\nlet HelixSharedChatSessionParticipant = class HelixSharedChatSessionParticipant extends DataObject {\n /** @internal */ _client;\n /** @internal */\n constructor(data, client) {\n super(data);\n this._client = client;\n }\n /**\n * The ID of the participant broadcaster.\n */\n get broadcasterId() {\n return this[rawDataSymbol].broadcaster_id;\n }\n /**\n * Gets information about the participant broadcaster.\n */\n async getBroadcaster() {\n return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].broadcaster_id));\n }\n};\n__decorate([\n Enumerable(false)\n], HelixSharedChatSessionParticipant.prototype, \"_client\", void 0);\nHelixSharedChatSessionParticipant = __decorate([\n rtfm('api', 'HelixSharedChatSessionParticipant', 'broadcasterId')\n], HelixSharedChatSessionParticipant);\nexport { HelixSharedChatSessionParticipant };\n", "import { __decorate } from \"tslib\";\nimport { rawDataSymbol, rtfm } from '@twurple/common';\nimport { HelixEmoteBase } from './HelixEmoteBase.js';\nimport { Enumerable } from '@d-fischer/shared-utils';\n/**\n * A Twitch user emote.\n */\nlet HelixUserEmote = class HelixUserEmote extends HelixEmoteBase {\n /** @internal */ _client;\n constructor(data, client) {\n super(data);\n this._client = client;\n }\n /**\n * The type of the emote.\n *\n * There are many types of emotes that Twitch seems to arbitrarily assign.\n * Check the relevant values in the official documentation.\n *\n * @see https://dev.twitch.tv/docs/api/reference/#get-user-emotes\n */\n get type() {\n return this[rawDataSymbol].emote_type;\n }\n /**\n * The ID that identifies the emote set that the emote belongs to, or `null` if the emote is not from any set.\n */\n get emoteSetId() {\n return this[rawDataSymbol].emote_set_id || null;\n }\n /**\n * The ID of the broadcaster who owns the emote, or `null` if the emote has no owner, e.g. it's a global emote.\n */\n get ownerId() {\n return this[rawDataSymbol].owner_id || null;\n }\n /**\n * Gets all emotes from the emotes set, or `null` if emote is not from any set.\n */\n async getAllEmotesFromSet() {\n return this[rawDataSymbol].emote_set_id\n ? await this._client.chat.getEmotesFromSets([this[rawDataSymbol].emote_set_id])\n : null;\n }\n /**\n * Gets more information about the user that owns the emote, or `null` if the emote is not owned by a user.\n */\n async getOwner() {\n return this[rawDataSymbol].owner_id ? await this._client.users.getUserById(this[rawDataSymbol].owner_id) : null;\n }\n};\n__decorate([\n Enumerable(false)\n], HelixUserEmote.prototype, \"_client\", void 0);\nHelixUserEmote = __decorate([\n rtfm('api', 'HelixUserEmote', 'id')\n], HelixUserEmote);\nexport { HelixUserEmote };\n", "import { __decorate } from \"tslib\";\nimport { Enumerable } from '@d-fischer/shared-utils';\nimport { extractUserId, rtfm } from '@twurple/common';\nimport { createClipCreateFromVodQuery, createClipCreateQuery, createClipQuery, } from '../../interfaces/endpoints/clip.external.js';\nimport { HelixRequestBatcher } from '../../utils/HelixRequestBatcher.js';\nimport { HelixPaginatedRequest } from '../../utils/pagination/HelixPaginatedRequest.js';\nimport { createPaginatedResult } from '../../utils/pagination/HelixPaginatedResult.js';\nimport { createPaginationQuery } from '../../utils/pagination/HelixPagination.js';\nimport { BaseApi } from '../BaseApi.js';\nimport { HelixClip } from './HelixClip.js';\n/**\n * The Helix API methods that deal with clips.\n *\n * Can be accessed using `client.clips` on an {@link ApiClient} instance.\n *\n * ## Example\n * ```ts\n * const api = new ApiClient({ authProvider });\n * const clipId = await api.clips.createClip({ channel: '125328655' });\n * ```\n *\n * @meta category helix\n * @meta categorizedTitle Clips\n */\nlet HelixClipApi = class HelixClipApi extends BaseApi {\n /** @internal */\n _getClipByIdBatcher = new HelixRequestBatcher({\n url: 'clips',\n }, 'id', 'id', this._client, (data) => new HelixClip(data, this._client));\n /**\n * Gets clips for the specified broadcaster in descending order of views.\n *\n * @param broadcaster The broadcaster to fetch clips for.\n * @param filter\n *\n * @expandParams\n */\n async getClipsForBroadcaster(broadcaster, filter = {}) {\n return await this._getClips({\n ...filter,\n filterType: 'broadcaster_id',\n ids: extractUserId(broadcaster),\n userId: extractUserId(broadcaster),\n });\n }\n /**\n * Creates a paginator for clips for the specified broadcaster.\n *\n * @param broadcaster The broadcaster to fetch clips for.\n * @param filter\n *\n * @expandParams\n */\n getClipsForBroadcasterPaginated(broadcaster, filter = {}) {\n return this._getClipsPaginated({\n ...filter,\n filterType: 'broadcaster_id',\n ids: extractUserId(broadcaster),\n userId: extractUserId(broadcaster),\n });\n }\n /**\n * Gets clips for the specified game in descending order of views.\n *\n * @param gameId The game ID.\n * @param filter\n *\n * @expandParams\n */\n async getClipsForGame(gameId, filter = {}) {\n return await this._getClips({\n ...filter,\n filterType: 'game_id',\n ids: gameId,\n });\n }\n /**\n * Creates a paginator for clips for the specified game.\n *\n * @param gameId The game ID.\n * @param filter\n *\n * @expandParams\n */\n getClipsForGamePaginated(gameId, filter = {}) {\n return this._getClipsPaginated({\n ...filter,\n filterType: 'game_id',\n ids: gameId,\n });\n }\n /**\n * Gets the clips identified by the given IDs.\n *\n * @param ids The clip IDs.\n */\n async getClipsByIds(ids) {\n const result = await this._getClips({\n filterType: 'id',\n ids,\n });\n return result.data;\n }\n /**\n * Gets the clip identified by the given ID.\n *\n * @param id The clip ID.\n */\n async getClipById(id) {\n const clips = await this.getClipsByIds([id]);\n return clips.length ? clips[0] : null;\n }\n /**\n * Gets the clip identified by the given ID, batching multiple calls into fewer requests as the API allows.\n *\n * @param id The clip ID.\n */\n async getClipByIdBatched(id) {\n return await this._getClipByIdBatcher.request(id);\n }\n /**\n * Creates a clip of a running stream.\n *\n * Returns the ID of the clip.\n *\n * @param params\n * @expandParams\n */\n async createClip(params) {\n const result = await this._client.callApi({\n type: 'helix',\n url: 'clips',\n method: 'POST',\n userId: extractUserId(params.channel),\n scopes: ['clips:edit'],\n canOverrideScopedUserContext: true,\n query: createClipCreateQuery(params),\n });\n return result.data[0].id;\n }\n /**\n * Creates a clip of a VOD.\n *\n * Returns the ID of the clip.\n *\n * @param params\n * @expandParams\n */\n async createClipFromVod(params) {\n const broadcasterId = extractUserId(params.channel);\n const result = await this._client.callApi({\n type: 'helix',\n url: 'videos/clips',\n method: 'POST',\n userId: broadcasterId,\n scopes: ['editor:manage:clips', 'channel:manage:clips'],\n canOverrideScopedUserContext: true,\n query: createClipCreateFromVodQuery(params, this._getUserContextIdWithDefault(broadcasterId)),\n });\n return result.data[0].id;\n }\n async _getClips(params) {\n if (!params.ids.length) {\n return { data: [] };\n }\n const result = await this._client.callApi({\n type: 'helix',\n url: 'clips',\n userId: params.userId,\n query: {\n ...createClipQuery(params),\n ...createPaginationQuery(params),\n },\n });\n return createPaginatedResult(result, HelixClip, this._client);\n }\n _getClipsPaginated(params) {\n return new HelixPaginatedRequest({\n url: 'clips',\n userId: params.userId,\n query: createClipQuery(params),\n }, this._client, data => new HelixClip(data, this._client));\n }\n};\n__decorate([\n Enumerable(false)\n], HelixClipApi.prototype, \"_getClipByIdBatcher\", void 0);\nHelixClipApi = __decorate([\n rtfm('api', 'HelixClipApi')\n], HelixClipApi);\nexport { HelixClipApi };\n", "import { extractUserId } from '@twurple/common';\n/** @internal */\nexport function createClipCreateQuery(params) {\n const { channel, createAfterDelay = false, title, duration } = params;\n return {\n broadcaster_id: extractUserId(channel),\n has_delay: createAfterDelay.toString(),\n title,\n duration: duration?.toFixed(1),\n };\n}\n/** @internal */\nexport function createClipCreateFromVodQuery(params, editorId) {\n const { channel, title, duration, vodId, vodOffset } = params;\n return {\n broadcaster_id: extractUserId(channel),\n editor_id: editorId,\n title,\n duration: duration?.toFixed(1),\n vod_id: vodId,\n vod_offset: vodOffset.toString(),\n };\n}\n/** @internal */\nexport function createClipQuery(params) {\n const { filterType, ids, startDate, endDate, isFeatured } = params;\n return {\n [filterType]: ids,\n started_at: startDate,\n ended_at: endDate,\n is_featured: isFeatured?.toString(),\n };\n}\n", "import { __decorate } from \"tslib\";\nimport { Enumerable } from '@d-fischer/shared-utils';\nimport { checkRelationAssertion, DataObject, rawDataSymbol, rtfm } from '@twurple/common';\n/**\n * A clip from a Twitch stream.\n */\nlet HelixClip = class HelixClip extends DataObject {\n /** @internal */ _client;\n /** @internal */\n constructor(data, client) {\n super(data);\n this._client = client;\n }\n /**\n * The clip ID.\n */\n get id() {\n return this[rawDataSymbol].id;\n }\n /**\n * The URL of the clip.\n */\n get url() {\n return this[rawDataSymbol].url;\n }\n /**\n * The embed URL of the clip.\n */\n get embedUrl() {\n return this[rawDataSymbol].embed_url;\n }\n /**\n * The user ID of the broadcaster of the stream where the clip was created.\n */\n get broadcasterId() {\n return this[rawDataSymbol].broadcaster_id;\n }\n /**\n * The display name of the broadcaster of the stream where the clip was created.\n */\n get broadcasterDisplayName() {\n return this[rawDataSymbol].broadcaster_name;\n }\n /**\n * Gets information about the broadcaster of the stream where the clip was created.\n */\n async getBroadcaster() {\n return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].broadcaster_id));\n }\n /**\n * The user ID of the creator of the clip.\n */\n get creatorId() {\n return this[rawDataSymbol].creator_id;\n }\n /**\n * The display name of the creator of the clip.\n */\n get creatorDisplayName() {\n return this[rawDataSymbol].creator_name;\n }\n /**\n * Gets information about the creator of the clip.\n */\n async getCreator() {\n return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].creator_id));\n }\n /**\n * The ID of the video the clip is taken from.\n */\n get videoId() {\n return this[rawDataSymbol].video_id;\n }\n /**\n * Gets information about the video the clip is taken from.\n */\n async getVideo() {\n return checkRelationAssertion(await this._client.videos.getVideoById(this[rawDataSymbol].video_id));\n }\n /**\n * The ID of the game that was being played when the clip was created.\n */\n get gameId() {\n return this[rawDataSymbol].game_id;\n }\n /**\n * Gets information about the game that was being played when the clip was created.\n */\n async getGame() {\n return this[rawDataSymbol].game_id\n ? checkRelationAssertion(await this._client.games.getGameById(this[rawDataSymbol].game_id))\n : null;\n }\n /**\n * The language of the stream where the clip was created.\n */\n get language() {\n return this[rawDataSymbol].language;\n }\n /**\n * The title of the clip.\n */\n get title() {\n return this[rawDataSymbol].title;\n }\n /**\n * The number of views of the clip.\n */\n get views() {\n return this[rawDataSymbol].view_count;\n }\n /**\n * The date when the clip was created.\n */\n get creationDate() {\n return new Date(this[rawDataSymbol].created_at);\n }\n /**\n * The URL of the thumbnail of the clip.\n */\n get thumbnailUrl() {\n return this[rawDataSymbol].thumbnail_url;\n }\n /**\n * The duration of the clip in seconds (up to 0.1 precision).\n */\n get duration() {\n return this[rawDataSymbol].duration;\n }\n /**\n * The offset of the clip from the start of the corresponding VOD, in seconds.\n *\n * This may be null if there is no VOD or if the clip is created from a live broadcast,\n * in which case it may take a few minutes to associate with the VOD.\n */\n get vodOffset() {\n return this[rawDataSymbol].vod_offset;\n }\n /**\n * Whether the clip is featured.\n */\n get isFeatured() {\n return this[rawDataSymbol].is_featured;\n }\n};\n__decorate([\n Enumerable(false)\n], HelixClip.prototype, \"_client\", void 0);\nHelixClip = __decorate([\n rtfm('api', 'HelixClip', 'id')\n], HelixClip);\nexport { HelixClip };\n", "import { __decorate } from \"tslib\";\nimport { rtfm } from '@twurple/common';\nimport { BaseApi } from '../BaseApi.js';\nimport { HelixContentClassificationLabel } from './HelixContentClassificationLabel.js';\n/**\n * The Helix API methods that deal with content classification labels.\n *\n * Can be accessed using `client.contentClassificationLabels` on an {@link ApiClient} instance.\n *\n * ## Example\n * ```ts\n * const api = new ApiClient({ authProvider });\n * const labels = await api.contentClassificationLabels.getAll();\n * ```\n *\n * @meta category helix\n * @meta categorizedTitle Content classification labels\n */\nlet HelixContentClassificationLabelApi = class HelixContentClassificationLabelApi extends BaseApi {\n /**\n * Fetches a list of all content classification labels.\n *\n * @param locale The locale for the content classification labels.\n */\n async getAll(locale) {\n const result = await this._client.callApi({\n url: 'content_classification_labels',\n query: {\n locale,\n },\n });\n return result.data.map(data => new HelixContentClassificationLabel(data));\n }\n};\nHelixContentClassificationLabelApi = __decorate([\n rtfm('api', 'HelixContentClassificationLabelApi')\n], HelixContentClassificationLabelApi);\nexport { HelixContentClassificationLabelApi };\n", "import { DataObject, rawDataSymbol } from '@twurple/common';\n/**\n * A content classification label that can be applied to a Twitch stream.\n */\nexport class HelixContentClassificationLabel extends DataObject {\n /**\n * The ID of the content classification label.\n */\n get id() {\n return this[rawDataSymbol].id;\n }\n /**\n * The name of the content classification label.\n */\n get name() {\n return this[rawDataSymbol].name;\n }\n /**\n * The description of the content classification label.\n */\n get description() {\n return this[rawDataSymbol].description;\n }\n}\n", "import { __decorate } from \"tslib\";\nimport { Enumerable, mapOptional } from '@d-fischer/shared-utils';\nimport { extractUserId, rtfm } from '@twurple/common';\nimport { createDropsEntitlementQuery, createDropsEntitlementUpdateBody, } from '../../interfaces/endpoints/entitlement.external.js';\nimport { HelixRequestBatcher } from '../../utils/HelixRequestBatcher.js';\nimport { HelixPaginatedRequest } from '../../utils/pagination/HelixPaginatedRequest.js';\nimport { createPaginatedResult } from '../../utils/pagination/HelixPaginatedResult.js';\nimport { createPaginationQuery } from '../../utils/pagination/HelixPagination.js';\nimport { BaseApi } from '../BaseApi.js';\nimport { HelixDropsEntitlement } from './HelixDropsEntitlement.js';\n/**\n * The Helix API methods that deal with entitlements (drops).\n *\n * Can be accessed using `client.entitlements` on an {@link ApiClient} instance.\n *\n * ## Example\n * ```ts\n * const api = new ApiClient({ authProvider });\n * const clipId = await api.entitlements.getDropsEntitlements();\n * ```\n *\n * @meta category helix\n * @meta categorizedTitle Entitlements (Drops)\n */\nlet HelixEntitlementApi = class HelixEntitlementApi extends BaseApi {\n /** @internal */ _getDropsEntitlementByIdBatcher = new HelixRequestBatcher({\n url: 'entitlements/drops',\n }, 'id', 'id', this._client, (data) => new HelixDropsEntitlement(data, this._client));\n /**\n * Gets the drops entitlements for the given filter.\n *\n * @expandParams\n *\n * @param filter\n * @param alwaysApp Whether an app token should always be used, even if a user filter is given.\n */\n async getDropsEntitlements(filter, alwaysApp = false) {\n const response = await this._client.callApi({\n type: 'helix',\n url: 'entitlements/drops',\n userId: mapOptional(filter.user, extractUserId),\n forceType: filter.user && alwaysApp ? 'app' : undefined,\n query: {\n ...createDropsEntitlementQuery(filter, alwaysApp),\n ...createPaginationQuery(filter),\n },\n });\n return createPaginatedResult(response, HelixDropsEntitlement, this._client);\n }\n /**\n * Creates a paginator for drops entitlements for the given filter.\n *\n * @expandParams\n *\n * @param filter\n * @param alwaysApp Whether an app token should always be used, even if a user filter is given.\n */\n getDropsEntitlementsPaginated(filter, alwaysApp = false) {\n return new HelixPaginatedRequest({\n url: 'entitlements/drops',\n userId: mapOptional(filter.user, extractUserId),\n forceType: filter.user && alwaysApp ? 'app' : undefined,\n query: createDropsEntitlementQuery(filter, alwaysApp),\n }, this._client, data => new HelixDropsEntitlement(data, this._client));\n }\n /**\n * Gets the drops entitlements for the given IDs.\n *\n * @param ids The IDs to fetch.\n */\n async getDropsEntitlementsByIds(ids) {\n const response = await this._client.callApi({\n type: 'helix',\n url: 'entitlements/drops',\n query: {\n id: ids,\n },\n });\n return response.data.map(data => new HelixDropsEntitlement(data, this._client));\n }\n /**\n * Gets the drops entitlement for the given ID.\n *\n * @param id The ID to fetch.\n */\n async getDropsEntitlementById(id) {\n const result = await this.getDropsEntitlementsByIds([id]);\n return result[0] ?? null;\n }\n /**\n * Gets the drops entitlement for the given ID, batching multiple calls into fewer requests as the API allows.\n *\n * @param id The ID to fetch.\n */\n async getDropsEntitlementByIdBatched(id) {\n return await this._getDropsEntitlementByIdBatcher.request(id);\n }\n /**\n * Updates the status of a list of drops entitlements.\n *\n * Returns a map that associates each given ID with its update status.\n *\n * @param ids The IDs of the entitlements.\n * @param fulfillmentStatus The fulfillment status to set the entitlements to.\n */\n async updateDropsEntitlements(ids, fulfillmentStatus) {\n const response = await this._client.callApi({\n type: 'helix',\n url: 'entitlements/drops',\n method: 'PATCH',\n jsonBody: createDropsEntitlementUpdateBody(ids, fulfillmentStatus),\n });\n return new Map(response.data.flatMap(entry => entry.ids.map(id => [id, entry.status])));\n }\n};\n__decorate([\n Enumerable(false)\n], HelixEntitlementApi.prototype, \"_getDropsEntitlementByIdBatcher\", void 0);\nHelixEntitlementApi = __decorate([\n rtfm('api', 'HelixEntitlementApi')\n], HelixEntitlementApi);\nexport { HelixEntitlementApi };\n", "import { mapOptional } from '@d-fischer/shared-utils';\nimport { extractUserId } from '@twurple/common';\n/** @internal */\nexport function createDropsEntitlementQuery(filters, alwaysApp) {\n return {\n user_id: alwaysApp ? mapOptional(filters.user, extractUserId) : undefined,\n game_id: filters.gameId,\n fulfillment_status: filters.fulfillmentStatus,\n };\n}\n/** @internal */\nexport function createDropsEntitlementUpdateBody(ids, fulfillmentStatus) {\n return {\n fulfillment_status: fulfillmentStatus,\n entitlement_ids: ids,\n };\n}\n", "import { __decorate } from \"tslib\";\nimport { Enumerable } from '@d-fischer/shared-utils';\nimport { checkRelationAssertion, DataObject, rawDataSymbol, rtfm } from '@twurple/common';\n/**\n * An entitlement for a drop.\n */\nlet HelixDropsEntitlement = class HelixDropsEntitlement extends DataObject {\n /** @internal */ _client;\n /** @internal */\n constructor(data, client) {\n super(data);\n this._client = client;\n }\n /**\n * The ID of the entitlement.\n */\n get id() {\n return this[rawDataSymbol].id;\n }\n /**\n * The ID of the reward.\n */\n get rewardId() {\n return this[rawDataSymbol].benefit_id;\n }\n /**\n * The date when the entitlement was granted.\n */\n get grantDate() {\n return new Date(this[rawDataSymbol].timestamp);\n }\n /**\n * The ID of the entitled user.\n */\n get userId() {\n return this[rawDataSymbol].user_id;\n }\n /**\n * Gets more information about the entitled user.\n */\n async getUser() {\n return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].user_id));\n }\n /**\n * The ID of the game the entitlement was granted for.\n */\n get gameId() {\n return this[rawDataSymbol].game_id;\n }\n /**\n * Gets more information about the game the entitlement was granted for.\n */\n async getGame() {\n return checkRelationAssertion(await this._client.games.getGameById(this[rawDataSymbol].game_id));\n }\n /**\n * The fulfillment status of the entitlement.\n */\n get fulfillmentStatus() {\n return this[rawDataSymbol].fulfillment_status;\n }\n /**\n * The date when the entitlement was last updated.\n */\n get updateDate() {\n return new Date(this[rawDataSymbol].last_updated);\n }\n};\n__decorate([\n Enumerable(false)\n], HelixDropsEntitlement.prototype, \"_client\", void 0);\nHelixDropsEntitlement = __decorate([\n rtfm('api', 'HelixDropsEntitlement')\n], HelixDropsEntitlement);\nexport { HelixDropsEntitlement };\n", "import { __decorate } from \"tslib\";\nimport { mapOptional } from '@d-fischer/shared-utils';\nimport { extractUserId, rtfm } from '@twurple/common';\nimport { createEventSubBroadcasterCondition, createEventSubDropEntitlementGrantCondition, createEventSubModeratorCondition, createEventSubRewardCondition, createEventSubUserCondition, createEventSubConduitCondition, createEventSubConduitUpdateCondition, createEventSubConduitShardsUpdateCondition, } from '../../interfaces/endpoints/eventSub.external.js';\nimport { createSingleKeyQuery } from '../../interfaces/endpoints/generic.external.js';\nimport { HelixPaginatedRequest } from '../../utils/pagination/HelixPaginatedRequest.js';\nimport { createPaginatedResultWithTotal, createPaginatedResult } from '../../utils/pagination/HelixPaginatedResult.js';\nimport { createPaginationQuery } from '../../utils/pagination/HelixPagination.js';\nimport { BaseApi } from '../BaseApi.js';\nimport { HelixEventSubSubscription } from './HelixEventSubSubscription.js';\nimport { HelixPaginatedEventSubSubscriptionsRequest } from './HelixPaginatedEventSubSubscriptionsRequest.js';\nimport { HelixEventSubConduit } from './HelixEventSubConduit.js';\nimport { HelixEventSubConduitShard } from './HelixEventSubConduitShard.js';\n/**\n * The API methods that deal with EventSub.\n *\n * Can be accessed using `client.eventSub` on an {@link ApiClient} instance.\n *\n * ## Before using these methods...\n *\n * All methods in this class assume that you are already running a working EventSub listener reachable using the given transport.\n *\n * If you don't already have one, we recommend use of the `@twurple/eventsub-http` or `@twurple/eventsub-ws` libraries,\n * which handle subscribing and unsubscribing to these topics automatically.\n *\n * ## Example\n * ```ts\n * const api = new ApiClient({ authProvider });\n * await api.eventSub.subscribeToUserFollowsTo('125328655', { callbackUrl: 'https://example.com' });\n * ```\n *\n * @meta category helix\n * @meta categorizedTitle EventSub\n */\nlet HelixEventSubApi = class HelixEventSubApi extends BaseApi {\n /**\n * Gets the current EventSub subscriptions for the current client.\n *\n * @param pagination\n *\n * @expandParams\n */\n async getSubscriptions(pagination) {\n const result = await this._client.callApi({\n type: 'helix',\n url: 'eventsub/subscriptions',\n query: createPaginationQuery(pagination),\n });\n return {\n ...createPaginatedResultWithTotal(result, HelixEventSubSubscription, this._client),\n totalCost: result.total_cost,\n maxTotalCost: result.max_total_cost,\n };\n }\n /**\n * Creates a paginator for the current EventSub subscriptions for the current client.\n */\n getSubscriptionsPaginated() {\n return new HelixPaginatedEventSubSubscriptionsRequest({}, undefined, this._client);\n }\n /**\n * Gets the current EventSub subscriptions with the given status for the current client.\n *\n * @param status The status of the subscriptions to get.\n * @param pagination\n *\n * @expandParams\n */\n async getSubscriptionsForStatus(status, pagination) {\n const result = await this._client.callApi({\n type: 'helix',\n url: 'eventsub/subscriptions',\n query: {\n ...createPaginationQuery(pagination),\n status,\n },\n });\n return {\n ...createPaginatedResultWithTotal(result, HelixEventSubSubscription, this._client),\n totalCost: result.total_cost,\n maxTotalCost: result.max_total_cost,\n };\n }\n /**\n * Creates a paginator for the current EventSub subscriptions with the given status for the current client.\n *\n * @param status The status of the subscriptions to get.\n */\n getSubscriptionsForStatusPaginated(status) {\n return new HelixPaginatedEventSubSubscriptionsRequest({ status }, undefined, this._client);\n }\n /**\n * Gets the current EventSub subscriptions with the given type for the current client.\n *\n * @param type The type of the subscriptions to get.\n * @param pagination\n *\n * @expandParams\n */\n async getSubscriptionsForType(type, pagination) {\n const result = await this._client.callApi({\n type: 'helix',\n url: 'eventsub/subscriptions',\n query: {\n ...createPaginationQuery(pagination),\n type,\n },\n });\n return {\n ...createPaginatedResultWithTotal(result, HelixEventSubSubscription, this._client),\n totalCost: result.total_cost,\n maxTotalCost: result.max_total_cost,\n };\n }\n /**\n * Creates a paginator for the current EventSub subscriptions with the given type for the current client.\n *\n * @param type The type of the subscriptions to get.\n */\n getSubscriptionsForTypePaginated(type) {\n return new HelixPaginatedEventSubSubscriptionsRequest({ type }, undefined, this._client);\n }\n /**\n * Gets the current EventSub subscriptions for the current user and client.\n *\n * @param user The user to get subscriptions for.\n * @param pagination\n *\n * @expandParams\n */\n async getSubscriptionsForUser(user, pagination) {\n const result = await this._client.callApi({\n type: 'helix',\n url: 'eventsub/subscriptions',\n userId: extractUserId(user),\n query: {\n ...createSingleKeyQuery('user_id', extractUserId(user)),\n ...createPaginationQuery(pagination),\n },\n });\n return {\n ...createPaginatedResultWithTotal(result, HelixEventSubSubscription, this._client),\n totalCost: result.total_cost,\n maxTotalCost: result.max_total_cost,\n };\n }\n /**\n * Creates a paginator for the current EventSub subscriptions with the given type for the current client.\n *\n * @param user The user to get subscriptions for.\n */\n getSubscriptionsForUserPaginated(user) {\n const userId = extractUserId(user);\n return new HelixPaginatedEventSubSubscriptionsRequest(createSingleKeyQuery('user_id', userId), userId, this._client);\n }\n /**\n * Sends an arbitrary request to subscribe to an event.\n *\n * You can only create WebHook transport subscriptions using app tokens\n * and WebSocket transport subscriptions using user tokens.\n *\n * @param type The type of the event.\n * @param version The version of the event.\n * @param condition The condition of the subscription.\n * @param transport The transport of the subscription.\n * @param user The user to create the subscription in context of.\n * @param requiredScopeSet The scope set required by the subscription. Will only be checked for applicable transports.\n * @param canOverrideScopedUserContext Whether the auth user context can be overridden.\n * @param isBatched Whether to enable batching for the subscription. Is only supported for select topics.\n */\n async createSubscription(type, version, condition, transport, user, requiredScopeSet, canOverrideScopedUserContext, isBatched) {\n const usesAppAuth = transport.method === 'webhook' || transport.method === 'conduit';\n const scopes = usesAppAuth ? undefined : requiredScopeSet;\n if (!usesAppAuth && !user) {\n throw new Error(`Transport ${transport.method} can only handle subscriptions with user context`);\n }\n const jsonBody = {\n type,\n version,\n condition,\n transport,\n };\n if (isBatched) {\n jsonBody.is_batching_enabled = true;\n }\n const result = await this._client.callApi({\n type: 'helix',\n url: 'eventsub/subscriptions',\n method: 'POST',\n scopes,\n userId: mapOptional(user, extractUserId),\n canOverrideScopedUserContext,\n forceType: usesAppAuth ? 'app' : 'user',\n jsonBody,\n });\n return new HelixEventSubSubscription(result.data[0], this._client);\n }\n /**\n * Deletes a subscription.\n *\n * @param id The ID of the subscription.\n */\n async deleteSubscription(id) {\n await this._client.callApi({\n type: 'helix',\n url: 'eventsub/subscriptions',\n method: 'DELETE',\n query: {\n id,\n },\n });\n }\n /**\n * Deletes *all* subscriptions.\n */\n async deleteAllSubscriptions() {\n await this._deleteSubscriptionsWithCondition();\n }\n /**\n * Deletes all broken subscriptions, i.e. all that are not enabled or pending verification.\n */\n async deleteBrokenSubscriptions() {\n await this._deleteSubscriptionsWithCondition(sub => sub.status !== 'enabled' && sub.status !== 'webhook_callback_verification_pending');\n }\n /**\n * Subscribe to events that represent a stream going live.\n *\n * @param broadcaster The broadcaster you want to listen to online events for.\n * @param transport The transport options.\n */\n async subscribeToStreamOnlineEvents(broadcaster, transport) {\n return await this.createSubscription('stream.online', '1', createEventSubBroadcasterCondition(broadcaster), transport, broadcaster);\n }\n /**\n * Subscribe to events that represent a stream going offline.\n *\n * @param broadcaster The broadcaster you want to listen to online events for.\n * @param transport The transport options.\n */\n async subscribeToStreamOfflineEvents(broadcaster, transport) {\n return await this.createSubscription('stream.offline', '1', createEventSubBroadcasterCondition(broadcaster), transport, broadcaster);\n }\n /**\n * Subscribe to events that represent a channel updating their metadata.\n *\n * @param broadcaster The broadcaster you want to listen to update events for.\n * @param transport The transport options.\n */\n async subscribeToChannelUpdateEvents(broadcaster, transport) {\n return await this.createSubscription('channel.update', '2', createEventSubBroadcasterCondition(broadcaster), transport, broadcaster);\n }\n /**\n * Subscribe to events that represent a user following a channel.\n *\n * @param broadcaster The broadcaster you want to listen to follow events for.\n * @param transport The transport options.\n */\n async subscribeToChannelFollowEvents(broadcaster, transport) {\n const broadcasterId = extractUserId(broadcaster);\n return await this.createSubscription('channel.follow', '2', createEventSubModeratorCondition(broadcasterId, this._getUserContextIdWithDefault(broadcasterId)), transport, broadcasterId, ['moderator:read:followers'], true);\n }\n /**\n * Subscribe to events that represent a user subscribing to a channel.\n *\n * @param broadcaster The broadcaster you want to listen to subscribe events for.\n * @param transport The transport options.\n */\n async subscribeToChannelSubscriptionEvents(broadcaster, transport) {\n return await this.createSubscription('channel.subscribe', '1', createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ['channel:read:subscriptions']);\n }\n /**\n * Subscribe to events that represent a user gifting another user a subscription to a channel.\n *\n * @param broadcaster The broadcaster you want to listen to subscription gift events for.\n * @param transport The transport options.\n */\n async subscribeToChannelSubscriptionGiftEvents(broadcaster, transport) {\n return await this.createSubscription('channel.subscription.gift', '1', createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ['channel:read:subscriptions']);\n }\n /**\n * Subscribe to events that represent a user's subscription to a channel being announced.\n *\n * @param broadcaster The broadcaster you want to listen to subscription message events for.\n * @param transport The transport options.\n */\n async subscribeToChannelSubscriptionMessageEvents(broadcaster, transport) {\n return await this.createSubscription('channel.subscription.message', '1', createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ['channel:read:subscriptions']);\n }\n /**\n * Subscribe to events that represent a user's subscription to a channel ending.\n *\n * @param broadcaster The broadcaster you want to listen to subscription end events for.\n * @param transport The transport options.\n */\n async subscribeToChannelSubscriptionEndEvents(broadcaster, transport) {\n return await this.createSubscription('channel.subscription.end', '1', createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ['channel:read:subscriptions']);\n }\n /**\n * Subscribe to events that represent a user cheering bits to a channel.\n *\n * @param broadcaster The broadcaster you want to listen to cheer events for.\n * @param transport The transport options.\n */\n async subscribeToChannelCheerEvents(broadcaster, transport) {\n return await this.createSubscription('channel.cheer', '1', createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ['bits:read']);\n }\n /**\n * Subscribe to events that represent a charity campaign starting in a channel.\n *\n * @param broadcaster The broadcaster you want to listen to charity donation events for.\n * @param transport The transport options.\n */\n async subscribeToChannelCharityCampaignStartEvents(broadcaster, transport) {\n return await this.createSubscription('channel.charity_campaign.start', '1', createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ['channel:read:charity']);\n }\n /**\n * Subscribe to events that represent a charity campaign ending in a channel.\n *\n * @param broadcaster The broadcaster you want to listen to charity donation events for.\n * @param transport The transport options.\n */\n async subscribeToChannelCharityCampaignStopEvents(broadcaster, transport) {\n return await this.createSubscription('channel.charity_campaign.stop', '1', createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ['channel:read:charity']);\n }\n /**\n * Subscribe to events that represent a user donating to a charity campaign in a channel.\n *\n * @param broadcaster The broadcaster you want to listen to charity donation events for.\n * @param transport The transport options.\n */\n async subscribeToChannelCharityDonationEvents(broadcaster, transport) {\n return await this.createSubscription('channel.charity_campaign.donate', '1', createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ['channel:read:charity']);\n }\n /**\n * Subscribe to events that represent a charity campaign progressing in a channel.\n *\n * @param broadcaster The broadcaster you want to listen to charity donation events for.\n * @param transport The transport options.\n */\n async subscribeToChannelCharityCampaignProgressEvents(broadcaster, transport) {\n return await this.createSubscription('channel.charity_campaign.progress', '1', createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ['channel:read:charity']);\n }\n /**\n * Subscribe to events that represent a user being banned in a channel.\n *\n * @param broadcaster The broadcaster you want to listen to ban events for.\n * @param transport The transport options.\n */\n async subscribeToChannelBanEvents(broadcaster, transport) {\n return await this.createSubscription('channel.ban', '1', createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ['channel:moderate']);\n }\n /**\n * Subscribe to events that represent a user being unbanned in a channel.\n *\n * @param broadcaster The broadcaster you want to listen to unban events for.\n * @param transport The transport options.\n */\n async subscribeToChannelUnbanEvents(broadcaster, transport) {\n return await this.createSubscription('channel.unban', '1', createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ['channel:moderate']);\n }\n /**\n * Subscribe to events that represent Shield Mode being activated in a channel.\n *\n * @param broadcaster The broadcaster you want to listen to Shield Mode activation events for.\n * @param transport The transport options.\n */\n async subscribeToChannelShieldModeBeginEvents(broadcaster, transport) {\n const broadcasterId = extractUserId(broadcaster);\n return await this.createSubscription('channel.shield_mode.begin', '1', createEventSubModeratorCondition(broadcasterId, this._getUserContextIdWithDefault(broadcasterId)), transport, broadcasterId, ['moderator:read:shield_mode', 'moderator:manage:shield_mode'], true);\n }\n /**\n * Subscribe to events that represent Shield Mode being deactivated in a channel.\n *\n * @param broadcaster The broadcaster you want to listen to Shield Mode deactivation events for.\n * @param transport The transport options.\n */\n async subscribeToChannelShieldModeEndEvents(broadcaster, transport) {\n const broadcasterId = extractUserId(broadcaster);\n return await this.createSubscription('channel.shield_mode.end', '1', createEventSubModeratorCondition(broadcasterId, this._getUserContextIdWithDefault(broadcasterId)), transport, broadcasterId, ['moderator:read:shield_mode', 'moderator:manage:shield_mode'], true);\n }\n /**\n * Subscribe to events that represent a moderator being added to a channel.\n *\n * @param broadcaster The broadcaster you want to listen for moderator add events for.\n * @param transport The transport options.\n */\n async subscribeToChannelModeratorAddEvents(broadcaster, transport) {\n return await this.createSubscription('channel.moderator.add', '1', createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ['moderation:read']);\n }\n /**\n * Subscribe to events that represent a moderator being removed from a channel.\n *\n * @param broadcaster The broadcaster you want to listen for moderator remove events for.\n * @param transport The transport options.\n */\n async subscribeToChannelModeratorRemoveEvents(broadcaster, transport) {\n return await this.createSubscription('channel.moderator.remove', '1', createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ['moderation:read']);\n }\n /**\n * Subscribe to events that represent a broadcaster raiding another broadcaster.\n *\n * @param broadcaster The broadcaster you want to listen to outgoing raid events for.\n * @param transport The transport options.\n */\n async subscribeToChannelRaidEventsFrom(broadcaster, transport) {\n return await this.createSubscription('channel.raid', '1', createSingleKeyQuery('from_broadcaster_user_id', extractUserId(broadcaster)), transport, broadcaster);\n }\n /**\n * Subscribe to events that represent a broadcaster being raided by another broadcaster.\n *\n * @param broadcaster The broadcaster you want to listen to incoming raid events for.\n * @param transport The transport options.\n */\n async subscribeToChannelRaidEventsTo(broadcaster, transport) {\n return await this.createSubscription('channel.raid', '1', createSingleKeyQuery('to_broadcaster_user_id', extractUserId(broadcaster)), transport, broadcaster);\n }\n /**\n * Subscribe to events that represent a Channel Points reward being added to a channel.\n *\n * @param broadcaster The broadcaster you want to listen to reward add events for.\n * @param transport The transport options.\n */\n async subscribeToChannelRewardAddEvents(broadcaster, transport) {\n return await this.createSubscription('channel.channel_points_custom_reward.add', '1', createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ['channel:read:redemptions', 'channel:manage:redemptions']);\n }\n /**\n * Subscribe to events that represent a Channel Points reward being updated in a channel.\n *\n * @param broadcaster The broadcaster you want to listen to reward update events for.\n * @param transport The transport options.\n */\n async subscribeToChannelRewardUpdateEvents(broadcaster, transport) {\n return await this.createSubscription('channel.channel_points_custom_reward.update', '1', createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ['channel:read:redemptions', 'channel:manage:redemptions']);\n }\n /**\n * Subscribe to events that represent a specific Channel Points reward being updated.\n *\n * @param broadcaster The broadcaster you want to listen to reward update events for.\n * @param rewardId The ID of the reward you want to listen to update events for.\n * @param transport The transport options.\n */\n async subscribeToChannelRewardUpdateEventsForReward(broadcaster, rewardId, transport) {\n return await this.createSubscription('channel.channel_points_custom_reward.update', '1', createEventSubRewardCondition(broadcaster, rewardId), transport, broadcaster, ['channel:read:redemptions', 'channel:manage:redemptions']);\n }\n /**\n * Subscribe to events that represent a Channel Points reward being removed from a channel.\n *\n * @param broadcaster The broadcaster you want to listen to reward remove events for.\n * @param transport The transport options.\n */\n async subscribeToChannelRewardRemoveEvents(broadcaster, transport) {\n return await this.createSubscription('channel.channel_points_custom_reward.remove', '1', createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ['channel:read:redemptions', 'channel:manage:redemptions']);\n }\n /**\n * Subscribe to events that represent a specific Channel Points reward being removed from a channel.\n *\n * @param broadcaster The broadcaster you want to listen to reward remove events for.\n * @param rewardId The ID of the reward you want to listen to remove events for.\n * @param transport The transport options.\n */\n async subscribeToChannelRewardRemoveEventsForReward(broadcaster, rewardId, transport) {\n return await this.createSubscription('channel.channel_points_custom_reward.remove', '1', createEventSubRewardCondition(broadcaster, rewardId), transport, broadcaster, ['channel:read:redemptions', 'channel:manage:redemptions']);\n }\n /**\n * Subscribe to events that represent a Channel Points reward being redeemed.\n *\n * @param broadcaster The broadcaster you want to listen to redemption events for.\n * @param transport The transport options.\n */\n async subscribeToChannelRedemptionAddEvents(broadcaster, transport) {\n return await this.createSubscription('channel.channel_points_custom_reward_redemption.add', '1', createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ['channel:read:redemptions', 'channel:manage:redemptions']);\n }\n /**\n * Subscribe to events that represent a specific Channel Points reward being redeemed.\n *\n * @param broadcaster The broadcaster you want to listen to redemption events for.\n * @param rewardId The ID of the reward you want to listen to redemption events for.\n * @param transport The transport options.\n */\n async subscribeToChannelRedemptionAddEventsForReward(broadcaster, rewardId, transport) {\n return await this.createSubscription('channel.channel_points_custom_reward_redemption.add', '1', createEventSubRewardCondition(broadcaster, rewardId), transport, broadcaster, ['channel:read:redemptions', 'channel:manage:redemptions']);\n }\n /**\n * Subscribe to events that represent a Channel Points redemption being updated.\n *\n * @param broadcaster The broadcaster you want to listen to redemption update events for.\n * @param transport The transport options.\n */\n async subscribeToChannelRedemptionUpdateEvents(broadcaster, transport) {\n return await this.createSubscription('channel.channel_points_custom_reward_redemption.update', '1', createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ['channel:read:redemptions', 'channel:manage:redemptions']);\n }\n /**\n * Subscribe to events that represent a specific Channel Points reward's redemption being updated.\n *\n * @param broadcaster The broadcaster you want to listen to redemption update events for.\n * @param rewardId The ID of the reward you want to listen to redemption updates for.\n * @param transport The transport options.\n */\n async subscribeToChannelRedemptionUpdateEventsForReward(broadcaster, rewardId, transport) {\n return await this.createSubscription('channel.channel_points_custom_reward_redemption.update', '1', createEventSubRewardCondition(broadcaster, rewardId), transport, broadcaster, ['channel:read:redemptions', 'channel:manage:redemptions']);\n }\n /**\n * Subscribe to events that represent a Channel Points automatic reward being redeemed.\n *\n * @param broadcaster The broadcaster you want to listen to automatic reward redemption events for.\n * @param transport The transport options.\n */\n async subscribeToChannelAutomaticRewardRedemptionAddEvents(broadcaster, transport) {\n return await this.createSubscription('channel.channel_points_automatic_reward_redemption.add', '1', createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ['channel:read:redemptions', 'channel:manage:redemptions']);\n }\n /**\n * Subscribe to events that represent a Channel Points automatic reward being redeemed.\n *\n * @param broadcaster The broadcaster you want to listen to automatic reward redemption events for.\n * @param transport The transport options.\n */\n async subscribeToChannelAutomaticRewardRedemptionAddV2Events(broadcaster, transport) {\n return await this.createSubscription('channel.channel_points_automatic_reward_redemption.add', '2', createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ['channel:read:redemptions', 'channel:manage:redemptions']);\n }\n /**\n * Subscribe to events that represent a poll starting in a channel.\n *\n * @param broadcaster The broadcaster you want to listen to poll begin events for.\n * @param transport The transport options.\n */\n async subscribeToChannelPollBeginEvents(broadcaster, transport) {\n return await this.createSubscription('channel.poll.begin', '1', createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ['channel:read:polls', 'channel:manage:polls']);\n }\n /**\n * Subscribe to events that represent a poll being voted on in a channel.\n *\n * @param broadcaster The broadcaster you want to listen to poll progress events for.\n * @param transport The transport options.\n */\n async subscribeToChannelPollProgressEvents(broadcaster, transport) {\n return await this.createSubscription('channel.poll.progress', '1', createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ['channel:read:polls', 'channel:manage:polls']);\n }\n /**\n * Subscribe to events that represent a poll ending in a channel.\n *\n * @param broadcaster The broadcaster you want to listen to poll end events for.\n * @param transport The transport options.\n */\n async subscribeToChannelPollEndEvents(broadcaster, transport) {\n return await this.createSubscription('channel.poll.end', '1', createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ['channel:read:polls', 'channel:manage:polls']);\n }\n /**\n * Subscribe to events that represent a prediction starting in a channel.\n *\n * @param broadcaster The broadcaster you want to listen to prediction begin events for.\n * @param transport The transport options.\n */\n async subscribeToChannelPredictionBeginEvents(broadcaster, transport) {\n return await this.createSubscription('channel.prediction.begin', '1', createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ['channel:read:predictions', 'channel:manage:predictions']);\n }\n /**\n * Subscribe to events that represent a prediction being voted on in a channel.\n *\n * @param broadcaster The broadcaster you want to listen to prediction preogress events for.\n * @param transport The transport options.\n */\n async subscribeToChannelPredictionProgressEvents(broadcaster, transport) {\n return await this.createSubscription('channel.prediction.progress', '1', createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ['channel:read:predictions', 'channel:manage:predictions']);\n }\n /**\n * Subscribe to events that represent a prediction being locked in a channel.\n *\n * @param broadcaster The broadcaster you want to listen to prediction lock events for.\n * @param transport The transport options.\n */\n async subscribeToChannelPredictionLockEvents(broadcaster, transport) {\n return await this.createSubscription('channel.prediction.lock', '1', createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ['channel:read:predictions', 'channel:manage:predictions']);\n }\n /**\n * Subscribe to events that represent a prediction ending in a channel.\n *\n * @param broadcaster The broadcaster you want to listen to prediction end events for.\n * @param transport The transport options.\n */\n async subscribeToChannelPredictionEndEvents(broadcaster, transport) {\n return await this.createSubscription('channel.prediction.end', '1', createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ['channel:read:predictions', 'channel:manage:predictions']);\n }\n /**\n * Subscribe to events that represent the beginning of a creator goal event in a channel.\n *\n * @param broadcaster The broadcaster you want to listen to goal begin events for.\n * @param transport The transport options.\n */\n async subscribeToChannelGoalBeginEvents(broadcaster, transport) {\n return await this.createSubscription('channel.goal.begin', '1', createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ['channel:read:goals']);\n }\n /**\n * Subscribe to events that represent progress towards a creator goal.\n *\n * @param broadcaster The broadcaster for which you want to listen to goal progress events.\n * @param transport The transport options.\n */\n async subscribeToChannelGoalProgressEvents(broadcaster, transport) {\n return await this.createSubscription('channel.goal.progress', '1', createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ['channel:read:goals']);\n }\n /**\n * Subscribe to events that represent the end of a creator goal event.\n *\n * @param broadcaster The broadcaster for which you want to listen to goal end events.\n * @param transport The transport options.\n */\n async subscribeToChannelGoalEndEvents(broadcaster, transport) {\n return await this.createSubscription('channel.goal.end', '1', createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ['channel:read:goals']);\n }\n /**\n * Subscribe to events that represent the beginning of a Hype Train event in a channel.\n *\n * @param broadcaster The broadcaster you want to listen to Hype train begin events for.\n * @param transport The transport options.\n */\n async subscribeToChannelHypeTrainBeginEvents(broadcaster, transport) {\n return await this.createSubscription('channel.hype_train.begin', '1', createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ['channel:read:hype_train']);\n }\n /**\n * Subscribe to events that represent progress towards the Hype Train goal.\n *\n * @param broadcaster The broadcaster for which you want to listen to Hype Train progress events.\n * @param transport The transport options.\n */\n async subscribeToChannelHypeTrainProgressEvents(broadcaster, transport) {\n return await this.createSubscription('channel.hype_train.progress', '1', createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ['channel:read:hype_train']);\n }\n /**\n * Subscribe to events that represent the end of a Hype Train event.\n *\n * @param broadcaster The broadcaster for which you want to listen to Hype Train end events.\n * @param transport The transport options.\n */\n async subscribeToChannelHypeTrainEndEvents(broadcaster, transport) {\n return await this.createSubscription('channel.hype_train.end', '1', createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ['channel:read:hype_train']);\n }\n /**\n * Subscribe to events that represent the beginning of a Hype Train event in a channel.\n *\n * @param broadcaster The broadcaster you want to listen to Hype train begin events for.\n * @param transport The transport options.\n */\n async subscribeToChannelHypeTrainBeginV2Events(broadcaster, transport) {\n return await this.createSubscription('channel.hype_train.begin', '2', createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ['channel:read:hype_train']);\n }\n /**\n * Subscribe to events that represent progress towards the Hype Train goal.\n *\n * @param broadcaster The broadcaster for which you want to listen to Hype Train progress events.\n * @param transport The transport options.\n */\n async subscribeToChannelHypeTrainProgressV2Events(broadcaster, transport) {\n return await this.createSubscription('channel.hype_train.progress', '2', createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ['channel:read:hype_train']);\n }\n /**\n * Subscribe to events that represent the end of a Hype Train event.\n *\n * @param broadcaster The broadcaster for which you want to listen to Hype Train end events.\n * @param transport The transport options.\n */\n async subscribeToChannelHypeTrainEndV2Events(broadcaster, transport) {\n return await this.createSubscription('channel.hype_train.end', '2', createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ['channel:read:hype_train']);\n }\n /**\n * Subscribe to events that represent a broadcaster shouting out another broadcaster.\n *\n * @param broadcaster The broadcaster for which you want to listen to outgoing shoutout events.\n * @param transport The transport options.\n */\n async subscribeToChannelShoutoutCreateEvents(broadcaster, transport) {\n const broadcasterId = extractUserId(broadcaster);\n return await this.createSubscription('channel.shoutout.create', '1', createEventSubModeratorCondition(broadcasterId, this._getUserContextIdWithDefault(broadcasterId)), transport, broadcasterId, ['moderator:read:shoutouts', 'moderator:manage:shoutouts'], true);\n }\n /**\n * Subscribe to events that represent a broadcaster being shouting out by another broadcaster.\n *\n * @param broadcaster The broadcaster for which you want to listen to incoming shoutout events.\n * @param transport The transport options.\n */\n async subscribeToChannelShoutoutReceiveEvents(broadcaster, transport) {\n const broadcasterId = extractUserId(broadcaster);\n return await this.createSubscription('channel.shoutout.receive', '1', createEventSubModeratorCondition(broadcasterId, this._getUserContextIdWithDefault(broadcasterId)), transport, broadcasterId, ['moderator:read:shoutouts', 'moderator:manage:shoutouts'], true);\n }\n /**\n * Subscribe to events that represent an ad break beginning in a channel.\n *\n * @param broadcaster The broadcaster for which you want to listen to ad break begin events.\n * @param transport The transport options.\n */\n async subscribeToChannelAdBreakBeginEvents(broadcaster, transport) {\n return await this.createSubscription('channel.ad_break.begin', '1', createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ['channel:read:ads']);\n }\n /**\n * Subscribe to events that represent a channel's chat being cleared.\n *\n * @param broadcaster The broadcaster for which you want to listen to chat clear events.\n * @param transport The transport options.\n */\n async subscribeToChannelChatClearEvents(broadcaster, transport) {\n const broadcasterId = extractUserId(broadcaster);\n return await this.createSubscription('channel.chat.clear', '1', createEventSubUserCondition(broadcasterId, this._getUserContextIdWithDefault(broadcasterId)), transport, broadcaster, ['user:read:chat'], true);\n }\n /**\n * Subscribe to events that represent a user's chat messages being cleared in a channel.\n *\n * @param broadcaster The broadcaster for which you want to listen to user chat message clear events.\n * @param transport The transport options.\n */\n async subscribeToChannelChatClearUserMessagesEvents(broadcaster, transport) {\n const broadcasterId = extractUserId(broadcaster);\n return await this.createSubscription('channel.chat.clear_user_messages', '1', createEventSubUserCondition(broadcasterId, this._getUserContextIdWithDefault(broadcasterId)), transport, broadcaster, ['user:read:chat'], true);\n }\n /**\n * Subscribe to events that represent a chat message being deleted in a channel.\n *\n * @param broadcaster The broadcaster for which you want to listen to chat message delete events.\n * @param transport The transport options.\n */\n async subscribeToChannelChatMessageDeleteEvents(broadcaster, transport) {\n const broadcasterId = extractUserId(broadcaster);\n return await this.createSubscription('channel.chat.message_delete', '1', createEventSubUserCondition(broadcasterId, this._getUserContextIdWithDefault(broadcasterId)), transport, broadcaster, ['user:read:chat'], true);\n }\n /**\n * Subscribe to events that represent a chat notification in a channel.\n *\n * @param broadcaster The broadcaster for which you want to listen to chat notification events.\n * @param transport The transport options.\n */\n async subscribeToChannelChatNotificationEvents(broadcaster, transport) {\n const broadcasterId = extractUserId(broadcaster);\n return await this.createSubscription('channel.chat.notification', '1', createEventSubUserCondition(broadcasterId, this._getUserContextIdWithDefault(broadcasterId)), transport, broadcaster, ['user:read:chat'], true);\n }\n /**\n * Subscribe to events that represent a chat message in a channel.\n *\n * @param broadcaster The broadcaster for which you want to listen to chat message events.\n * @param transport The transport options.\n */\n async subscribeToChannelChatMessageEvents(broadcaster, transport) {\n const broadcasterId = extractUserId(broadcaster);\n return await this.createSubscription('channel.chat.message', '1', createEventSubUserCondition(broadcasterId, this._getUserContextIdWithDefault(broadcasterId)), transport, broadcaster, ['user:read:chat'], true);\n }\n /**\n * Subscribe to events that represent chat settings being updated in a channel.\n *\n * @param broadcaster The broadcaster for which you want to listen to chat settings update events.\n * @param transport The transport options.\n */\n async subscribeToChannelChatSettingsUpdateEvents(broadcaster, transport) {\n const broadcasterId = extractUserId(broadcaster);\n return await this.createSubscription('channel.chat_settings.update', '1', createEventSubUserCondition(broadcasterId, this._getUserContextIdWithDefault(broadcasterId)), transport, broadcaster, ['user:read:chat'], true);\n }\n /**\n * Subscribe to events that represent a created unban requests in a channel.\n *\n * @param broadcaster The broadcaster for which you want to listen to unban requests.\n * @param transport The transport options.\n */\n async subscribeToChannelUnbanRequestCreateEvents(broadcaster, transport) {\n const broadcasterId = extractUserId(broadcaster);\n return await this.createSubscription('channel.unban_request.create', '1', createEventSubModeratorCondition(broadcasterId, this._getUserContextIdWithDefault(broadcasterId)), transport, broadcaster, ['moderator:read:unban_requests', 'moderator:manage:unban_requests'], true);\n }\n /**\n * Subscribe to events that represent a resolved unban requests in a channel.\n *\n * @param broadcaster The broadcaster for which you want to listen to unban requests.\n * @param transport The transport options.\n */\n async subscribeToChannelUnbanRequestResolveEvents(broadcaster, transport) {\n const broadcasterId = extractUserId(broadcaster);\n return await this.createSubscription('channel.unban_request.resolve', '1', createEventSubModeratorCondition(broadcasterId, this._getUserContextIdWithDefault(broadcasterId)), transport, broadcaster, ['moderator:read:unban_requests', 'moderator:manage:unban_requests'], true);\n }\n /**\n * Subscribe to events that represent a moderator performing an action on a channel.\n *\n * This requires the following scopes:\n * - `moderator:read:blocked_terms` OR `moderator:manage:blocked_terms`\n * - `moderator:read:chat_settings` OR `moderator:manage:chat_settings`\n * - `moderator:read:unban_requests` OR `moderator:manage:unban_requests`\n * - `moderator:read:banned_users` OR `moderator:manage:banned_users`\n * - `moderator:read:chat_messages` OR `moderator:manage:chat_messages`\n * - `moderator:read:warnings` OR `moderator:manage:warnings`\n * - `moderator:read:moderators`\n * - `moderator:read:vips`\n *\n * These scope requirements cannot be checked by the library, so they are just assumed.\n * Make sure to catch authorization errors yourself.\n *\n * @param broadcaster The broadcaster for which you want to listen to moderation events.\n * @param transport The transport options.\n */\n async subscribeToChannelModerateEvents(broadcaster, transport) {\n const broadcasterId = extractUserId(broadcaster);\n return await this.createSubscription('channel.moderate', '2', createEventSubModeratorCondition(broadcasterId, this._getUserContextIdWithDefault(broadcasterId)), transport, broadcaster, [], true);\n }\n /**\n * Subscribe to events that represent a warning being acknowledged by a user.\n *\n * @param broadcaster The broadcaster for whom you want to listen to warnings.\n * @param transport The transport options.\n */\n async subscribeToChannelWarningAcknowledgeEvents(broadcaster, transport) {\n const broadcasterId = extractUserId(broadcaster);\n return await this.createSubscription('channel.warning.acknowledge', '1', createEventSubModeratorCondition(broadcasterId, this._getUserContextIdWithDefault(broadcasterId)), transport, broadcaster, ['moderator:read:warnings', 'moderator:manage:warnings'], true);\n }\n /**\n * Subscribe to events that represent a warning sent to a user.\n *\n * @param broadcaster The broadcaster for whom you want to listen to warnings.\n * @param transport The transport options.\n */\n async subscribeToChannelWarningSendEvents(broadcaster, transport) {\n const broadcasterId = extractUserId(broadcaster);\n return await this.createSubscription('channel.warning.send', '1', createEventSubModeratorCondition(broadcasterId, this._getUserContextIdWithDefault(broadcasterId)), transport, broadcaster, ['moderator:read:warnings', 'moderator:manage:warnings'], true);\n }\n /**\n * Subscribe to events that represent a VIP being added to a channel.\n *\n * @param broadcaster The broadcaster you want to listen for VIP add events for.\n * @param transport The transport options.\n */\n async subscribeToChannelVipAddEvents(broadcaster, transport) {\n return await this.createSubscription('channel.vip.add', '1', createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ['channel:read:vips', 'channel:manage:vips']);\n }\n /**\n * Subscribe to events that represent a VIP being removed from a channel.\n *\n * @param broadcaster The broadcaster you want to listen for VIP remove events for.\n * @param transport The transport options.\n */\n async subscribeToChannelVipRemoveEvents(broadcaster, transport) {\n return await this.createSubscription('channel.vip.remove', '1', createEventSubBroadcasterCondition(broadcaster), transport, broadcaster, ['channel:read:vips', 'channel:manage:vips']);\n }\n /**\n * Subscribe to events that represent an extension Bits transaction.\n *\n * @param clientId The Client ID for the extension you want to listen to Bits transactions for.\n * @param transport The transport options.\n */\n async subscribeToExtensionBitsTransactionCreateEvents(clientId, transport) {\n return await this.createSubscription('extension.bits_transaction.create', '1', createSingleKeyQuery('extension_client_id', clientId), transport);\n }\n /**\n * Subscribe to events that represent a user granting authorization to an application.\n *\n * @param clientId The Client ID for the application you want to listen to authorization grant events for.\n * @param transport The transport options.\n */\n async subscribeToUserAuthorizationGrantEvents(clientId, transport) {\n return await this.createSubscription('user.authorization.grant', '1', createSingleKeyQuery('client_id', clientId), transport);\n }\n /**\n * Subscribe to events that represent a user revoking their authorization from an application.\n *\n * @param clientId The Client ID for the application you want to listen to authorization revoke events for.\n * @param transport The transport options.\n */\n async subscribeToUserAuthorizationRevokeEvents(clientId, transport) {\n return await this.createSubscription('user.authorization.revoke', '1', createSingleKeyQuery('client_id', clientId), transport);\n }\n /**\n * Subscribe to events that represent a user updating their account details.\n *\n * @param user The user you want to listen to user update events for.\n * @param transport The transport options.\n * @param withEmail Whether to request adding the email address of the user to the notification.\n *\n * Only has an effect with the websocket transport.\n * With the webhook transport, this depends solely on the previous authorization given by the user.\n */\n async subscribeToUserUpdateEvents(user, transport, withEmail) {\n return await this.createSubscription('user.update', '1', createSingleKeyQuery('user_id', extractUserId(user)), transport, user, withEmail ? ['user:read:email'] : undefined);\n }\n /**\n * Subscribe to events that represent a user receiving a whisper message from another user.\n *\n * @param user The user you want to listen to whisper message events for.\n * @param transport The transport options.\n */\n async subscribeToUserWhisperMessageEvents(user, transport) {\n return await this.createSubscription('user.whisper.message', '1', createSingleKeyQuery('user_id', extractUserId(user)), transport, user, ['user:read:whispers', 'user:manage:whispers']);\n }\n /**\n * Subscribe to events that represent a drop entitlement being granted.\n *\n * @expandParams\n *\n * @param filter\n * @param transport The transport options.\n */\n async subscribeToDropEntitlementGrantEvents(filter, transport) {\n return await this.createSubscription('drop.entitlement.grant', '1', createEventSubDropEntitlementGrantCondition(filter), transport, undefined, undefined, false, true);\n }\n /**\n * Subscribes to events that represent a chat message being held by AutoMod.\n *\n * @param broadcaster The broadcaster you want to listen to AutoMod message hold events for.\n * @param transport The transport options.\n */\n async subscribeToAutoModMessageHoldEvents(broadcaster, transport) {\n const broadcasterId = extractUserId(broadcaster);\n return await this.createSubscription('automod.message.hold', '1', createEventSubModeratorCondition(broadcasterId, this._getUserContextIdWithDefault(broadcasterId)), transport, broadcaster, ['moderator:manage:automod'], true);\n }\n /**\n * Subscribes to events that represent a held chat message by AutoMod being resolved.\n *\n * @param broadcaster The broadcaster you want to listen to AutoMod message resolution events for.\n * @param transport The transport options.\n */\n async subscribeToAutoModMessageUpdateEvents(broadcaster, transport) {\n const broadcasterId = extractUserId(broadcaster);\n return await this.createSubscription('automod.message.update', '1', createEventSubModeratorCondition(broadcasterId, this._getUserContextIdWithDefault(broadcasterId)), transport, broadcaster, ['moderator:manage:automod'], true);\n }\n /**\n * Subscribes to events (v2) that represent a chat message being held by AutoMod.\n *\n * @param broadcaster The broadcaster you want to listen to AutoMod message hold events for.\n * @param transport The transport options.\n */\n async subscribeToAutoModMessageHoldV2Events(broadcaster, transport) {\n const broadcasterId = extractUserId(broadcaster);\n return await this.createSubscription('automod.message.hold', '2', createEventSubModeratorCondition(broadcasterId, this._getUserContextIdWithDefault(broadcasterId)), transport, broadcaster, ['moderator:manage:automod'], true);\n }\n /**\n * Subscribes to events (v2) that represent a held chat message by AutoMod being resolved.\n *\n * @param broadcaster The broadcaster you want to listen to AutoMod message resolution events for.\n * @param transport The transport options.\n */\n async subscribeToAutoModMessageUpdateV2Events(broadcaster, transport) {\n const broadcasterId = extractUserId(broadcaster);\n return await this.createSubscription('automod.message.update', '2', createEventSubModeratorCondition(broadcasterId, this._getUserContextIdWithDefault(broadcasterId)), transport, broadcaster, ['moderator:manage:automod'], true);\n }\n /**\n * Subscribes to events that represent the AutoMod settings being updated.\n *\n * @param broadcaster The broadcaster you want to listen to AutoMod settings update events.\n * @param transport The transport options.\n */\n async subscribeToAutoModSettingsUpdateEvents(broadcaster, transport) {\n const broadcasterId = extractUserId(broadcaster);\n return await this.createSubscription('automod.settings.update', '1', createEventSubModeratorCondition(broadcasterId, this._getUserContextIdWithDefault(broadcasterId)), transport, broadcaster, ['moderator:read:automod_settings'], true);\n }\n /**\n * Subscribes to events that represent the AutoMod terms being updated.\n *\n * @param broadcaster The broadcaster you want to listen to AutoMod terms update events.\n * @param transport The transport options.\n */\n async subscribeToAutoModTermsUpdateEvents(broadcaster, transport) {\n const broadcasterId = extractUserId(broadcaster);\n return await this.createSubscription('automod.terms.update', '1', createEventSubModeratorCondition(broadcasterId, this._getUserContextIdWithDefault(broadcasterId)), transport, broadcaster, ['moderator:manage:automod'], true);\n }\n /**\n * Subscribes to events that represent a user's notification about their message being held by AutoMod.\n *\n * @param broadcaster The broadcaster you want to listen to AutoMod message hold events for.\n * @param transport The transport options.\n */\n async subscribeToChannelChatUserMessageHoldEvents(broadcaster, transport) {\n const broadcasterId = extractUserId(broadcaster);\n return await this.createSubscription('channel.chat.user_message_hold', '1', createEventSubUserCondition(broadcasterId, this._getUserContextIdWithDefault(broadcasterId)), transport, broadcaster, ['user:read:chat'], true);\n }\n /**\n * Subscribes to events that represent a user's notification about a held chat message by AutoMod being resolved.\n *\n * @param broadcaster The broadcaster you want to listen to AutoMod message resolution events for.\n * @param transport The transport options.\n */\n async subscribeToChannelChatUserMessageUpdateEvents(broadcaster, transport) {\n const broadcasterId = extractUserId(broadcaster);\n return await this.createSubscription('channel.chat.user_message_update', '1', createEventSubUserCondition(broadcasterId, this._getUserContextIdWithDefault(broadcasterId)), transport, broadcaster, ['user:read:chat'], true);\n }\n /**\n * Subscribes to events that represent a suspicious user updated in a channel.\n *\n * @param broadcaster The broadcaster you want to listen for suspicious user update events.\n * @param transport The transport options.\n */\n async subscribeToChannelSuspiciousUserUpdateEvents(broadcaster, transport) {\n const broadcasterId = extractUserId(broadcaster);\n return await this.createSubscription('channel.suspicious_user.update', '1', createEventSubModeratorCondition(broadcasterId, this._getUserContextIdWithDefault(broadcasterId)), transport, broadcaster, ['moderator:read:suspicious_users'], true);\n }\n /**\n * Subscribes to events that represent a message sent by a suspicious user.\n *\n * @param broadcaster The broadcaster you want to listen for messages sent by suspicious users.\n * @param transport The transport options.\n */\n async subscribeToChannelSuspiciousUserMessageEvents(broadcaster, transport) {\n const broadcasterId = extractUserId(broadcaster);\n return await this.createSubscription('channel.suspicious_user.message', '1', createEventSubModeratorCondition(broadcasterId, this._getUserContextIdWithDefault(broadcasterId)), transport, broadcaster, ['moderator:read:suspicious_users'], true);\n }\n /**\n * Subscribes to events indicating that a shared chat session has begun in a channel.\n *\n * @param broadcaster The broadcaster for whom shared chat session begin events should be listened to.\n * @param transport The transport options to use for the subscription.\n */\n async subscribeToChannelSharedChatSessionBeginEvents(broadcaster, transport) {\n const broadcasterId = extractUserId(broadcaster);\n return await this.createSubscription('channel.shared_chat.begin', '1', createEventSubBroadcasterCondition(broadcasterId), transport, broadcasterId);\n }\n /**\n * Subscribes to events indicating that a shared chat session has been updated in a channel.\n *\n * @param broadcaster The broadcaster for whom shared chat session update events should be listened to.\n * @param transport The transport options to use for the subscription.\n */\n async subscribeToChannelSharedChatSessionUpdateEvents(broadcaster, transport) {\n const broadcasterId = extractUserId(broadcaster);\n return await this.createSubscription('channel.shared_chat.update', '1', createEventSubBroadcasterCondition(broadcasterId), transport, broadcasterId);\n }\n /**\n * Subscribes to events indicating that a shared chat session has ended in a channel.\n *\n * @param broadcaster The broadcaster for whom shared chat session end events should be listened to.\n * @param transport The transport options to use for the subscription.\n */\n async subscribeToChannelSharedChatSessionEndEvents(broadcaster, transport) {\n const broadcasterId = extractUserId(broadcaster);\n return await this.createSubscription('channel.shared_chat.end', '1', createEventSubBroadcasterCondition(broadcasterId), transport, broadcasterId);\n }\n /**\n * Subscribes to events indicating that bits are used in a channel.\n *\n * @param broadcaster The broadcaster for whom you want to listen to bits usage events.\n * @param transport The transport options to use for the subscription.\n */\n async subscribeToChannelBitsUseEvents(broadcaster, transport) {\n const broadcasterId = extractUserId(broadcaster);\n return await this.createSubscription('channel.bits.use', '1', createEventSubBroadcasterCondition(broadcasterId), transport, broadcasterId, ['bits:read']);\n }\n /**\n * Gets the current EventSub conduits for the current client.\n *\n */\n async getConduits() {\n const result = await this._client.callApi({\n type: 'helix',\n url: 'eventsub/conduits',\n });\n return result.data.map(data => new HelixEventSubConduit(data, this._client));\n }\n /**\n * Creates a new EventSub conduit for the current client.\n *\n * @param shardCount The number of shards to create for this conduit.\n */\n async createConduit(shardCount) {\n const result = await this._client.callApi({\n type: 'helix',\n url: 'eventsub/conduits',\n method: 'POST',\n query: {\n ...createSingleKeyQuery('shard_count', shardCount.toString()),\n },\n });\n return new HelixEventSubConduit(result.data[0], this._client);\n }\n /**\n * Updates an EventSub conduit for the current client.\n *\n * @param id The ID of the conduit to update.\n * @param shardCount The number of shards to update for this conduit.\n */\n async updateConduit(id, shardCount) {\n const result = await this._client.callApi({\n type: 'helix',\n url: 'eventsub/conduits',\n method: 'PATCH',\n query: createEventSubConduitUpdateCondition(id, shardCount),\n });\n return new HelixEventSubConduit(result.data[0], this._client);\n }\n /**\n * Deletes an EventSub conduit for the current client.\n *\n * @param id The ID of the conduit to delete.\n */\n async deleteConduit(id) {\n await this._client.callApi({\n type: 'helix',\n url: 'eventsub/conduits',\n method: 'DELETE',\n query: {\n ...createSingleKeyQuery('id', id),\n },\n });\n }\n /**\n * Gets the shards of an EventSub conduit for the current client.\n *\n * @param conduitId The ID of the conduit to get shards for.\n * @param status The status of the shards to filter by.\n * @param pagination\n */\n async getConduitShards(conduitId, status, pagination) {\n const result = await this._client.callApi({\n type: 'helix',\n url: 'eventsub/conduits/shards',\n query: {\n ...createEventSubConduitCondition(conduitId, status),\n ...createPaginationQuery(pagination),\n },\n });\n return {\n ...createPaginatedResult(result, HelixEventSubConduitShard, this._client),\n };\n }\n /**\n * Creates a paginator for the shards of an EventSub conduit for the current client.\n *\n * @param conduitId The ID of the conduit to get shards for.\n * @param status The status of the shards to filter by.\n */\n getConduitShardsPaginated(conduitId, status) {\n return new HelixPaginatedRequest({\n url: 'eventsub/conduits/shards',\n query: createEventSubConduitCondition(conduitId, status),\n }, this._client, data => new HelixEventSubConduitShard(data));\n }\n /**\n * Updates shards of an EventSub conduit for the current client.\n *\n * @param conduitId The ID of the conduit to update shards for.\n * @param shards List of shards to update\n */\n async updateConduitShards(conduitId, shards) {\n const result = await this._client.callApi({\n type: 'helix',\n url: 'eventsub/conduits/shards',\n method: 'PATCH',\n jsonBody: createEventSubConduitShardsUpdateCondition(conduitId, shards),\n });\n return result.data.map(data => new HelixEventSubConduitShard(data));\n }\n async _deleteSubscriptionsWithCondition(cond) {\n const subsPaginator = this.getSubscriptionsPaginated();\n for await (const sub of subsPaginator) {\n if (!cond || cond(sub)) {\n await sub.unsubscribe();\n }\n }\n }\n};\nHelixEventSubApi = __decorate([\n rtfm('api', 'HelixEventSubApi')\n], HelixEventSubApi);\nexport { HelixEventSubApi };\n", "import { extractUserId } from '@twurple/common';\n/** @internal */\nexport function createEventSubBroadcasterCondition(broadcaster) {\n return {\n broadcaster_user_id: extractUserId(broadcaster),\n };\n}\n/** @internal */\nexport function createEventSubRewardCondition(broadcaster, rewardId) {\n return { broadcaster_user_id: extractUserId(broadcaster), reward_id: rewardId };\n}\n/** @internal */\nexport function createEventSubModeratorCondition(broadcasterId, moderatorId) {\n return {\n broadcaster_user_id: broadcasterId,\n moderator_user_id: moderatorId,\n };\n}\n/** @internal */\nexport function createEventSubUserCondition(broadcasterId, userId) {\n return {\n broadcaster_user_id: broadcasterId,\n user_id: userId,\n };\n}\n/** @internal */\nexport function createEventSubDropEntitlementGrantCondition(filter) {\n return {\n organization_id: filter.organizationId,\n category_id: filter.categoryId,\n campaign_id: filter.campaignId,\n };\n}\n/** @internal */\nexport function createEventSubConduitCondition(conduitId, status) {\n return {\n conduit_id: conduitId,\n status,\n };\n}\n/** @internal */\nexport function createEventSubConduitUpdateCondition(conduitId, shardCount) {\n return {\n id: conduitId,\n shard_count: shardCount.toString(),\n };\n}\n/** @internal */\nexport function createEventSubConduitShardsUpdateCondition(conduitId, shards) {\n return {\n conduit_id: conduitId,\n shards,\n };\n}\n", "import { __decorate } from \"tslib\";\nimport { Enumerable } from '@d-fischer/shared-utils';\nimport { DataObject, rawDataSymbol, rtfm } from '@twurple/common';\n/**\n * An EventSub subscription.\n */\nlet HelixEventSubSubscription = class HelixEventSubSubscription extends DataObject {\n /** @internal */ _client;\n /** @internal */\n constructor(data, client) {\n super(data);\n this._client = client;\n }\n /**\n * The ID of the subscription.\n */\n get id() {\n return this[rawDataSymbol].id;\n }\n /**\n * The status of the subscription.\n */\n get status() {\n return this[rawDataSymbol].status;\n }\n /**\n * The event type that the subscription is listening to.\n */\n get type() {\n return this[rawDataSymbol].type;\n }\n /**\n * The cost of the subscription.\n */\n get cost() {\n return this[rawDataSymbol].cost;\n }\n /**\n * The condition of the subscription.\n */\n get condition() {\n return this[rawDataSymbol].condition;\n }\n /**\n * The date and time of creation of the subscription.\n */\n get creationDate() {\n return new Date(this[rawDataSymbol].created_at);\n }\n /**\n * The transport method of the subscription.\n */\n get transportMethod() {\n return this[rawDataSymbol].transport.method;\n }\n /**\n * End the EventSub subscription.\n */\n async unsubscribe() {\n await this._client.eventSub.deleteSubscription(this[rawDataSymbol].id);\n }\n /** @private */\n get _transport() {\n return this[rawDataSymbol].transport;\n }\n /** @private */\n set _status(status) {\n this[rawDataSymbol].status = status;\n }\n};\n__decorate([\n Enumerable(false)\n], HelixEventSubSubscription.prototype, \"_client\", void 0);\nHelixEventSubSubscription = __decorate([\n rtfm('api', 'HelixEventSubSubscription', 'id')\n], HelixEventSubSubscription);\nexport { HelixEventSubSubscription };\n", "import { __decorate } from \"tslib\";\nimport { rtfm } from '@twurple/common';\nimport { HelixPaginatedRequestWithTotal } from '../../utils/pagination/HelixPaginatedRequestWithTotal.js';\nimport { HelixEventSubSubscription } from './HelixEventSubSubscription.js';\n/**\n * A special case of {@link HelixPaginatedRequestWithTotal} with support for fetching the total cost and cost limit\n * of EventSub subscriptions.\n *\n * @inheritDoc\n */\nlet HelixPaginatedEventSubSubscriptionsRequest = class HelixPaginatedEventSubSubscriptionsRequest extends HelixPaginatedRequestWithTotal {\n /** @internal */\n constructor(query, userId, client) {\n super({\n url: 'eventsub/subscriptions',\n userId,\n query,\n }, client, data => new HelixEventSubSubscription(data, client));\n }\n /**\n * Gets the total cost of EventSub subscriptions.\n */\n async getTotalCost() {\n const data = this._currentData ??\n (await this._fetchData({ query: { after: undefined } }));\n return data.total_cost;\n }\n /**\n * Gets the cost limit of EventSub subscriptions.\n */\n async getMaxTotalCost() {\n const data = this._currentData ??\n (await this._fetchData({ query: { after: undefined } }));\n return data.max_total_cost;\n }\n};\nHelixPaginatedEventSubSubscriptionsRequest = __decorate([\n rtfm('api', 'HelixPaginatedEventSubSubscriptionsRequest')\n], HelixPaginatedEventSubSubscriptionsRequest);\nexport { HelixPaginatedEventSubSubscriptionsRequest };\n", "import { __decorate } from \"tslib\";\nimport { Enumerable } from '@d-fischer/shared-utils';\nimport { DataObject, rawDataSymbol, rtfm } from '@twurple/common';\n/**\n * Represents an EventSub conduit.\n */\nlet HelixEventSubConduit = class HelixEventSubConduit extends DataObject {\n /** @internal */ _client;\n /** @internal */\n constructor(data, client) {\n super(data);\n this._client = client;\n }\n /**\n * The ID of the conduit.\n */\n get id() {\n return this[rawDataSymbol].id;\n }\n /**\n * The shard count of the conduit.\n */\n get shardCount() {\n return this[rawDataSymbol].shard_count;\n }\n /**\n * Update the conduit.\n *\n * @param shardCount The new shard count.\n */\n async update(shardCount) {\n return await this._client.eventSub.updateConduit(this[rawDataSymbol].id, shardCount);\n }\n /**\n * Delete the conduit.\n */\n async delete() {\n await this._client.eventSub.deleteConduit(this[rawDataSymbol].id);\n }\n /**\n * Get the conduit shards.\n */\n async getShards() {\n return await this._client.eventSub.getConduitShards(this[rawDataSymbol].id);\n }\n};\n__decorate([\n Enumerable(false)\n], HelixEventSubConduit.prototype, \"_client\", void 0);\nHelixEventSubConduit = __decorate([\n rtfm('api', 'HelixEventSubConduit')\n], HelixEventSubConduit);\nexport { HelixEventSubConduit };\n", "import { __decorate } from \"tslib\";\nimport { DataObject, rawDataSymbol, rtfm } from '@twurple/common';\n/**\n * Represents an EventSub conduit shard.\n */\nlet HelixEventSubConduitShard = class HelixEventSubConduitShard extends DataObject {\n /**\n * The ID of the shard.\n */\n get id() {\n return this[rawDataSymbol].id;\n }\n /**\n * The status of the shard.\n */\n get status() {\n return this[rawDataSymbol].status;\n }\n /**\n * The transport method of the shard.\n */\n get transportMethod() {\n return this[rawDataSymbol].transport.method;\n }\n};\nHelixEventSubConduitShard = __decorate([\n rtfm('api', 'HelixEventSubConduitShard')\n], HelixEventSubConduitShard);\nexport { HelixEventSubConduitShard };\n", "import { __decorate } from \"tslib\";\nimport { HelixExtension, rtfm } from '@twurple/common';\nimport { createExtensionProductBody, createExtensionTransactionQuery, createReleasedExtensionFilter, } from '../../interfaces/endpoints/extensions.external.js';\nimport { createSingleKeyQuery } from '../../interfaces/endpoints/generic.external.js';\nimport { HelixPaginatedRequest } from '../../utils/pagination/HelixPaginatedRequest.js';\nimport { createPaginatedResult } from '../../utils/pagination/HelixPaginatedResult.js';\nimport { createPaginationQuery } from '../../utils/pagination/HelixPagination.js';\nimport { BaseApi } from '../BaseApi.js';\nimport { HelixChannelReference } from '../channel/HelixChannelReference.js';\nimport { HelixExtensionBitsProduct } from './HelixExtensionBitsProduct.js';\nimport { HelixExtensionTransaction } from './HelixExtensionTransaction.js';\n/**\n * The Helix API methods that deal with extensions.\n *\n * Can be accessed using `client.extensions` on an {@link ApiClient} instance.\n *\n * ## Example\n * ```ts\n * const api = new ApiClient({ authProvider });\n * const transactions = await api.extionsions.getExtensionTransactions('abcd');\n * ```\n *\n * @meta category helix\n * @meta categorizedTitle Extensions\n */\nlet HelixExtensionsApi = class HelixExtensionsApi extends BaseApi {\n /**\n * Gets a released extension by ID.\n *\n * @param extensionId The ID of the extension.\n * @param version The version of the extension. If not given, gets the latest version.\n */\n async getReleasedExtension(extensionId, version) {\n const result = await this._client.callApi({\n type: 'helix',\n url: 'extensions/released',\n query: createReleasedExtensionFilter(extensionId, version),\n });\n return new HelixExtension(result.data[0]);\n }\n /**\n * Gets a list of channels that are currently live and have the given extension installed.\n *\n * @param extensionId The ID of the extension.\n * @param pagination\n *\n * @expandParams\n */\n async getLiveChannelsWithExtension(extensionId, pagination) {\n const result = await this._client.callApi({\n type: 'helix',\n url: 'extensions/live',\n query: {\n ...createSingleKeyQuery('extension_id', extensionId),\n ...createPaginationQuery(pagination),\n },\n });\n return createPaginatedResult(result, HelixChannelReference, this._client);\n }\n /**\n * Creates a paginator for channels that are currently live and have the given extension installed.\n *\n * @param extensionId The ID of the extension.\n */\n getLiveChannelsWithExtensionPaginated(extensionId) {\n return new HelixPaginatedRequest({\n url: 'extensions/live',\n query: createSingleKeyQuery('extension_id', extensionId),\n }, this._client, data => new HelixChannelReference(data, this._client));\n }\n /**\n * Gets an extension's Bits products.\n *\n * This only works if the provided token belongs to an extension's client ID,\n * and will return the products for that extension.\n *\n * @param includeDisabled Whether to include disabled/expired products.\n */\n async getExtensionBitsProducts(includeDisabled) {\n const result = await this._client.callApi({\n type: 'helix',\n url: 'bits/extensions',\n forceType: 'app',\n query: createSingleKeyQuery('should_include_all', includeDisabled?.toString()),\n });\n return result.data.map(data => new HelixExtensionBitsProduct(data));\n }\n /**\n * Creates or updates a Bits product of an extension.\n *\n * This only works if the provided token belongs to an extension's client ID,\n * and will create/update a product for that extension.\n *\n * @param data\n *\n * @expandParams\n */\n async putExtensionBitsProduct(data) {\n const result = await this._client.callApi({\n type: 'helix',\n url: 'bits/extensions',\n method: 'PUT',\n forceType: 'app',\n jsonBody: createExtensionProductBody(data),\n });\n return new HelixExtensionBitsProduct(result.data[0]);\n }\n /**\n * Gets a list of transactions for the given extension.\n *\n * @param extensionId The ID of the extension to get transactions for.\n * @param filter Additional filters.\n */\n async getExtensionTransactions(extensionId, filter = {}) {\n const result = await this._client.callApi({\n type: 'helix',\n url: 'extensions/transactions',\n forceType: 'app',\n query: {\n ...createExtensionTransactionQuery(extensionId, filter),\n ...createPaginationQuery(filter),\n },\n });\n return createPaginatedResult(result, HelixExtensionTransaction, this._client);\n }\n /**\n * Creates a paginator for transactions for the given extension.\n *\n * @param extensionId The ID of the extension to get transactions for.\n * @param filter Additional filters.\n */\n getExtensionTransactionsPaginated(extensionId, filter = {}) {\n return new HelixPaginatedRequest({\n url: 'extensions/transactions',\n forceType: 'app',\n query: createExtensionTransactionQuery(extensionId, filter),\n }, this._client, data => new HelixExtensionTransaction(data, this._client));\n }\n};\nHelixExtensionsApi = __decorate([\n rtfm('api', 'HelixExtensionsApi')\n], HelixExtensionsApi);\nexport { HelixExtensionsApi };\n", "/** @internal */\nexport function createReleasedExtensionFilter(extensionId, version) {\n return {\n extension_id: extensionId,\n extension_version: version,\n };\n}\n/** @internal */\nexport function createExtensionProductBody(data) {\n return {\n sku: data.sku,\n cost: {\n amount: data.cost,\n type: 'bits',\n },\n display_name: data.displayName,\n in_development: data.inDevelopment,\n expiration: data.expirationDate,\n is_broadcast: data.broadcast,\n };\n}\n/** @internal */\nexport function createExtensionTransactionQuery(extensionId, filter) {\n return {\n extension_id: extensionId,\n id: filter.transactionIds,\n };\n}\n", "import { __decorate } from \"tslib\";\nimport { Enumerable } from '@d-fischer/shared-utils';\nimport { checkRelationAssertion, DataObject, rawDataSymbol, rtfm } from '@twurple/common';\n/**\n * A reference to a Twitch channel.\n */\nlet HelixChannelReference = class HelixChannelReference extends DataObject {\n /** @internal */ _client;\n /** @internal */\n constructor(data, client) {\n super(data);\n this._client = client;\n }\n /**\n * The ID of the channel.\n */\n get id() {\n return this[rawDataSymbol].broadcaster_id;\n }\n /**\n * The display name of the channel.\n */\n get displayName() {\n return this[rawDataSymbol].broadcaster_name;\n }\n /**\n * Gets more information about the channel.\n */\n async getChannel() {\n return checkRelationAssertion(await this._client.channels.getChannelInfoById(this[rawDataSymbol].broadcaster_id));\n }\n /**\n * Gets more information about the broadcaster of the channel.\n */\n async getBroadcaster() {\n return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].broadcaster_id));\n }\n /**\n * The ID of the game currently played on the channel.\n */\n get gameId() {\n return this[rawDataSymbol].game_id;\n }\n /**\n * The name of the game currently played on the channel.\n */\n get gameName() {\n return this[rawDataSymbol].game_name;\n }\n /**\n * Gets information about the game that is being played on the stream.\n */\n async getGame() {\n return this[rawDataSymbol].game_id\n ? checkRelationAssertion(await this._client.games.getGameById(this[rawDataSymbol].game_id))\n : null;\n }\n /**\n * The title of the channel.\n */\n get title() {\n return this[rawDataSymbol].title;\n }\n};\n__decorate([\n Enumerable(false)\n], HelixChannelReference.prototype, \"_client\", void 0);\nHelixChannelReference = __decorate([\n rtfm('api', 'HelixChannelReference', 'id')\n], HelixChannelReference);\nexport { HelixChannelReference };\n", "import { __decorate } from \"tslib\";\nimport { mapNullable } from '@d-fischer/shared-utils';\nimport { DataObject, rawDataSymbol, rtfm } from '@twurple/common';\n/**\n * An extension's product to purchase with Bits.\n */\nlet HelixExtensionBitsProduct = class HelixExtensionBitsProduct extends DataObject {\n /**\n * The product's unique identifier.\n */\n get sku() {\n return this[rawDataSymbol].sku;\n }\n /**\n * The product's cost, in bits.\n */\n get cost() {\n return this[rawDataSymbol].cost.amount;\n }\n /**\n * The product's display name.\n */\n get displayName() {\n return this[rawDataSymbol].display_name;\n }\n /**\n * Whether the product is in development.\n */\n get inDevelopment() {\n return this[rawDataSymbol].in_development;\n }\n /**\n * Whether the product's purchases is broadcast to all users.\n */\n get isBroadcast() {\n return this[rawDataSymbol].is_broadcast;\n }\n /**\n * The product's expiration date. If the product never expires, this is null.\n */\n get expirationDate() {\n return mapNullable(this[rawDataSymbol].expiration, exp => new Date(exp));\n }\n};\nHelixExtensionBitsProduct = __decorate([\n rtfm('api', 'HelixExtensionBitsProduct', 'sku')\n], HelixExtensionBitsProduct);\nexport { HelixExtensionBitsProduct };\n", "import { __decorate } from \"tslib\";\nimport { Enumerable } from '@d-fischer/shared-utils';\nimport { checkRelationAssertion, DataObject, rawDataSymbol, rtfm } from '@twurple/common';\n/**\n * A bits transaction made inside an extension.\n */\nlet HelixExtensionTransaction = class HelixExtensionTransaction extends DataObject {\n /** @internal */ _client;\n /** @internal */\n constructor(data, client) {\n super(data);\n this._client = client;\n }\n /**\n * The ID of the transaction.\n */\n get id() {\n return this[rawDataSymbol].id;\n }\n /**\n * The time when the transaction was made.\n */\n get transactionDate() {\n return new Date(this[rawDataSymbol].timestamp);\n }\n /**\n * The ID of the broadcaster that runs the extension on their channel.\n */\n get broadcasterId() {\n return this[rawDataSymbol].broadcaster_id;\n }\n /**\n * The name of the broadcaster that runs the extension on their channel.\n */\n get broadcasterName() {\n return this[rawDataSymbol].broadcaster_name;\n }\n /**\n * The display name of the broadcaster that runs the extension on their channel.\n */\n get broadcasterDisplayName() {\n return this[rawDataSymbol].broadcaster_name;\n }\n /**\n * Gets information about the broadcaster that runs the extension on their channel.\n */\n async getBroadcaster() {\n return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].broadcaster_id));\n }\n /**\n * The ID of the user that made the transaction.\n */\n get userId() {\n return this[rawDataSymbol].user_id;\n }\n /**\n * The name of the user that made the transaction.\n */\n get userName() {\n return this[rawDataSymbol].user_login;\n }\n /**\n * The display name of the user that made the transaction.\n */\n get userDisplayName() {\n return this[rawDataSymbol].user_name;\n }\n /**\n * Gets information about the user that made the transaction.\n */\n async getUser() {\n return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].user_id));\n }\n /**\n * The product type. Currently always BITS_IN_EXTENSION.\n */\n get productType() {\n return this[rawDataSymbol].product_type;\n }\n /**\n * The product SKU.\n */\n get productSku() {\n return this[rawDataSymbol].product_data.sku;\n }\n /**\n * The cost of the product, in bits.\n */\n get productCost() {\n return this[rawDataSymbol].product_data.cost.amount;\n }\n /**\n * The display name of the product.\n */\n get productDisplayName() {\n return this[rawDataSymbol].product_data.displayName;\n }\n /**\n * Whether the product is in development.\n */\n get productInDevelopment() {\n return this[rawDataSymbol].product_data.inDevelopment;\n }\n};\n__decorate([\n Enumerable(false)\n], HelixExtensionTransaction.prototype, \"_client\", void 0);\nHelixExtensionTransaction = __decorate([\n rtfm('api', 'HelixExtensionTransaction', 'id')\n], HelixExtensionTransaction);\nexport { HelixExtensionTransaction };\n", "import { __decorate } from \"tslib\";\nimport { Enumerable } from '@d-fischer/shared-utils';\nimport { rtfm } from '@twurple/common';\nimport { HelixRequestBatcher } from '../../utils/HelixRequestBatcher.js';\nimport { HelixPaginatedRequest } from '../../utils/pagination/HelixPaginatedRequest.js';\nimport { createPaginatedResult } from '../../utils/pagination/HelixPaginatedResult.js';\nimport { createPaginationQuery } from '../../utils/pagination/HelixPagination.js';\nimport { BaseApi } from '../BaseApi.js';\nimport { HelixGame } from './HelixGame.js';\n/**\n * The Helix API methods that deal with games.\n *\n * Can be accessed using `client.games` on an {@link ApiClient} instance.\n *\n * ## Example\n * ```ts\n * const api = new ApiClient({ authProvider });\n * const game = await api.games.getGameByName('Hearthstone');\n * ```\n *\n * @meta category helix\n * @meta categorizedTitle Games\n */\nlet HelixGameApi = class HelixGameApi extends BaseApi {\n /** @internal */\n _getGameByIdBatcher = new HelixRequestBatcher({\n url: 'games',\n }, 'id', 'id', this._client, (data) => new HelixGame(data, this._client));\n /** @internal */\n _getGameByNameBatcher = new HelixRequestBatcher({\n url: 'games',\n }, 'name', 'name', this._client, (data) => new HelixGame(data, this._client));\n /** @internal */\n _getGameByIgdbIdBatcher = new HelixRequestBatcher({\n url: 'games',\n }, 'igdb_id', 'igdb_id', this._client, (data) => new HelixGame(data, this._client));\n /**\n * Gets the game data for the given list of game IDs.\n *\n * @param ids The game IDs you want to look up.\n */\n async getGamesByIds(ids) {\n return await this._getGames('id', ids);\n }\n /**\n * Gets the game data for the given list of game names.\n *\n * @param names The game names you want to look up.\n */\n async getGamesByNames(names) {\n return await this._getGames('name', names);\n }\n /**\n * Gets the game data for the given list of IGDB IDs.\n *\n * @param igdbIds The IGDB IDs you want to look up.\n */\n async getGamesByIgdbIds(igdbIds) {\n return await this._getGames('igdb_id', igdbIds);\n }\n /**\n * Gets the game data for the given game ID.\n *\n * @param id The game ID you want to look up.\n */\n async getGameById(id) {\n const games = await this._getGames('id', [id]);\n return games[0] ?? null;\n }\n /**\n * Gets the game data for the given game name.\n *\n * @param name The game name you want to look up.\n */\n async getGameByName(name) {\n const games = await this._getGames('name', [name]);\n return games[0] ?? null;\n }\n /**\n * Gets the game data for the given IGDB ID.\n *\n * @param igdbId The IGDB ID you want to look up.\n */\n async getGameByIgdbId(igdbId) {\n const games = await this._getGames('igdb_id', [igdbId]);\n return games[0] ?? null;\n }\n /**\n * Gets the game data for the given game ID, batching multiple calls into fewer requests as the API allows.\n *\n * @param id The game ID you want to look up.\n */\n async getGameByIdBatched(id) {\n return await this._getGameByIdBatcher.request(id);\n }\n /**\n * Gets the game data for the given game name, batching multiple calls into fewer requests as the API allows.\n *\n * @param name The game name you want to look up.\n */\n async getGameByNameBatched(name) {\n return await this._getGameByNameBatcher.request(name);\n }\n /**\n * Gets the game data for the given IGDB ID, batching multiple calls into fewer requests as the API allows.\n *\n * @param igdbId The IGDB ID you want to look up.\n */\n async getGameByIgdbIdBatched(igdbId) {\n return await this._getGameByIgdbIdBatcher.request(igdbId);\n }\n /**\n * Gets a list of the most viewed games at the moment.\n *\n * @param pagination\n *\n * @expandParams\n */\n async getTopGames(pagination) {\n const result = await this._client.callApi({\n type: 'helix',\n url: 'games/top',\n query: createPaginationQuery(pagination),\n });\n return createPaginatedResult(result, HelixGame, this._client);\n }\n /**\n * Creates a paginator for the most viewed games at the moment.\n */\n getTopGamesPaginated() {\n return new HelixPaginatedRequest({\n url: 'games/top',\n }, this._client, data => new HelixGame(data, this._client));\n }\n /** @internal */\n async _getGames(filterType, filterValues) {\n if (!filterValues.length) {\n return [];\n }\n const result = await this._client.callApi({\n type: 'helix',\n url: 'games',\n query: {\n [filterType]: filterValues,\n },\n });\n return result.data.map(entry => new HelixGame(entry, this._client));\n }\n};\n__decorate([\n Enumerable(false)\n], HelixGameApi.prototype, \"_getGameByIdBatcher\", void 0);\n__decorate([\n Enumerable(false)\n], HelixGameApi.prototype, \"_getGameByNameBatcher\", void 0);\n__decorate([\n Enumerable(false)\n], HelixGameApi.prototype, \"_getGameByIgdbIdBatcher\", void 0);\nHelixGameApi = __decorate([\n rtfm('api', 'HelixGameApi')\n], HelixGameApi);\nexport { HelixGameApi };\n", "import { __decorate } from \"tslib\";\nimport { Enumerable } from '@d-fischer/shared-utils';\nimport { DataObject, rawDataSymbol, rtfm } from '@twurple/common';\n/**\n * A game as displayed on Twitch.\n */\nlet HelixGame = class HelixGame extends DataObject {\n /** @internal */ _client;\n /** @internal */\n constructor(data, client) {\n super(data);\n this._client = client;\n }\n /**\n * The ID of the game.\n */\n get id() {\n return this[rawDataSymbol].id;\n }\n /**\n * The name of the game.\n */\n get name() {\n return this[rawDataSymbol].name;\n }\n /**\n * The URL of the box art of the game.\n */\n get boxArtUrl() {\n return this[rawDataSymbol].box_art_url;\n }\n /**\n * The IGDB ID of the game, or null if the game doesn't have an IGDB ID assigned at Twitch.\n */\n get igdbId() {\n return this[rawDataSymbol].igdb_id || null;\n }\n /**\n * Builds the URL of the box art of the game using the given dimensions.\n *\n * @param width The width of the box art.\n * @param height The height of the box art.\n */\n getBoxArtUrl(width, height) {\n return this[rawDataSymbol].box_art_url\n .replace('{width}', width.toString())\n .replace('{height}', height.toString());\n }\n /**\n * Gets streams that are currently playing the game.\n *\n * @param pagination\n * @expandParams\n */\n async getStreams(pagination) {\n return await this._client.streams.getStreams({ ...pagination, game: this[rawDataSymbol].id });\n }\n /**\n * Creates a paginator for streams that are currently playing the game.\n */\n getStreamsPaginated() {\n return this._client.streams.getStreamsPaginated({ game: this[rawDataSymbol].id });\n }\n};\n__decorate([\n Enumerable(false)\n], HelixGame.prototype, \"_client\", void 0);\nHelixGame = __decorate([\n rtfm('api', 'HelixGame', 'id')\n], HelixGame);\nexport { HelixGame };\n", "import { __decorate } from \"tslib\";\nimport { createBroadcasterQuery } from '@twurple/api-call';\nimport { extractUserId, rtfm } from '@twurple/common';\nimport { BaseApi } from '../BaseApi.js';\nimport { HelixGoal } from './HelixGoal.js';\n/**\n * The Helix API methods that deal with creator goals.\n *\n * Can be accessed using `client.goals` on an {@link ApiClient} instance.\n *\n * ## Example\n * ```ts\n * const api = new ApiClient({ authProvider });\n * const { data: goals } = await api.helix.goals.getGoals('61369223');\n *\n * @meta category helix\n * @meta categorizedTitle Goals\n */\nlet HelixGoalApi = class HelixGoalApi extends BaseApi {\n async getGoals(broadcaster) {\n const result = await this._client.callApi({\n type: 'helix',\n url: 'goals',\n userId: extractUserId(broadcaster),\n scopes: ['channel:read:goals'],\n query: createBroadcasterQuery(broadcaster),\n });\n return result.data.map(data => new HelixGoal(data, this._client));\n }\n};\nHelixGoalApi = __decorate([\n rtfm('api', 'HelixGoalApi')\n], HelixGoalApi);\nexport { HelixGoalApi };\n", "import { __decorate } from \"tslib\";\nimport { Enumerable } from '@d-fischer/shared-utils';\nimport { checkRelationAssertion, DataObject, rawDataSymbol, rtfm } from '@twurple/common';\n/**\n * A creator goal.\n */\nlet HelixGoal = class HelixGoal extends DataObject {\n /** @internal */ _client;\n /** @internal */\n constructor(data, client) {\n super(data);\n this._client = client;\n }\n /**\n * The ID of the goal.\n */\n get id() {\n return this[rawDataSymbol].id;\n }\n /**\n * The ID of the broadcaster the goal belongs to.\n */\n get broadcasterId() {\n return this[rawDataSymbol].broadcaster_id;\n }\n /**\n * The display name of the broadcaster the goal belongs to.\n */\n get broadcasterDisplayName() {\n return this[rawDataSymbol].broadcaster_name;\n }\n /**\n * The name of the broadcaster the goal belongs to.\n */\n get broadcasterName() {\n return this[rawDataSymbol].broadcaster_login;\n }\n /**\n * Gets more information about the broadcaster.\n */\n async getBroadcaster() {\n return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].broadcaster_id));\n }\n /**\n * The type of the goal.\n */\n get type() {\n return this[rawDataSymbol].type;\n }\n /**\n * The description of the goal.\n */\n get description() {\n return this[rawDataSymbol].description;\n }\n /**\n * The current value of the goal.\n */\n get currentAmount() {\n return this[rawDataSymbol].current_amount;\n }\n /**\n * The target value of the goal.\n */\n get targetAmount() {\n return this[rawDataSymbol].target_amount;\n }\n /**\n * The date and time when the goal was created.\n */\n get creationDate() {\n return this[rawDataSymbol].created_at;\n }\n};\n__decorate([\n Enumerable(false)\n], HelixGoal.prototype, \"_client\", void 0);\nHelixGoal = __decorate([\n rtfm('api', 'HelixGoal', 'id')\n], HelixGoal);\nexport { HelixGoal };\n", "import { createBroadcasterQuery } from '@twurple/api-call';\nimport { extractUserId } from '@twurple/common';\nimport { BaseApi } from '../BaseApi.js';\nimport { HelixHypeTrainStatus } from './HelixHypeTrainStatus.js';\n/**\n * The Helix API methods that deal with Hype Trains.\n *\n * Can be accessed using `client.hypeTrain` on an {@link ApiClient} instance.\n *\n * ## Example\n * ```ts\n * const api = new ApiClient({ authProvider });\n * const hypeTrainStatus = await api.hypeTrain.getHypeTrainStatusForBroadcaster('125328655');\n * ```\n *\n * @meta category helix\n * @meta categorizedTitle Hype Trains\n */\nexport class HelixHypeTrainApi extends BaseApi {\n /**\n * Gets the Hype Train status and statistics for the specified broadcaster.\n *\n * @param broadcaster The broadcaster to fetch Hype Train info for.\n */\n async getHypeTrainStatusForBroadcaster(broadcaster) {\n const result = await this._client.callApi({\n type: 'helix',\n url: 'hypetrain/status',\n userId: extractUserId(broadcaster),\n scopes: ['channel:read:hype_train'],\n query: {\n ...createBroadcasterQuery(broadcaster),\n },\n });\n return new HelixHypeTrainStatus(result.data[0], this._client);\n }\n}\n", "import { __decorate } from \"tslib\";\nimport { Enumerable, mapNullable } from '@d-fischer/shared-utils';\nimport { DataObject, rawDataSymbol, rtfm } from '@twurple/common';\nimport { HelixHypeTrain } from './HelixHypeTrain.js';\nimport { HelixHypeTrainAllTimeHigh } from './HelixHypeTrainAllTimeHigh.js';\n/**\n * Statistics of Hype Trains on a channel.\n */\nlet HelixHypeTrainStatus = class HelixHypeTrainStatus extends DataObject {\n /** @internal */ _client;\n /** @internal */\n constructor(data, client) {\n super(data);\n this._client = client;\n }\n /**\n * The current Hype Train, or null if there is no ongoing Hype Train.\n */\n get current() {\n return mapNullable(this[rawDataSymbol].current, data => new HelixHypeTrain(data, this._client));\n }\n /**\n * The all-time-high Hype Train statistics for this channel, or null if there was no Hype Train yet.\n */\n get allTimeHigh() {\n return mapNullable(this[rawDataSymbol].all_time_high, data => new HelixHypeTrainAllTimeHigh(data));\n }\n /**\n * The all-time-high shared Hype Train statistics for this channel, or null if there was no shared Hype Train yet.\n */\n get sharedAllTimeHigh() {\n return mapNullable(this[rawDataSymbol].shared_all_time_high, data => new HelixHypeTrainAllTimeHigh(data));\n }\n};\n__decorate([\n Enumerable(false)\n], HelixHypeTrainStatus.prototype, \"_client\", void 0);\nHelixHypeTrainStatus = __decorate([\n rtfm('api', 'HelixHypeTrainStatus')\n], HelixHypeTrainStatus);\nexport { HelixHypeTrainStatus };\n", "import { __decorate } from \"tslib\";\nimport { Enumerable } from '@d-fischer/shared-utils';\nimport { checkRelationAssertion, DataObject, rawDataSymbol, rtfm } from '@twurple/common';\nimport { HelixHypeTrainContribution } from './HelixHypeTrainContribution.js';\n/**\n * Data about the currently running Hype Train.\n */\nlet HelixHypeTrain = class HelixHypeTrain extends DataObject {\n /** @internal */ _client;\n /** @internal */\n constructor(data, client) {\n super(data);\n this._client = client;\n }\n /**\n * The unique ID of the Hype Train event.\n */\n get eventId() {\n return this[rawDataSymbol].id;\n }\n /**\n * The unique ID of the Hype Train.\n */\n get id() {\n return this[rawDataSymbol].id;\n }\n /**\n * The user ID of the broadcaster where the Hype Train is happening.\n */\n get broadcasterId() {\n return this[rawDataSymbol].broadcaster_user_id;\n }\n /**\n * The name of the broadcaster where the Hype Train is happening.\n */\n get broadcasterName() {\n return this[rawDataSymbol].broadcaster_user_login;\n }\n /**\n * The display name of the broadcaster where the Hype Train is happening.\n */\n get broadcasterDisplayName() {\n return this[rawDataSymbol].broadcaster_user_name;\n }\n /**\n * Gets more information about the broadcaster where the Hype Train is happening.\n */\n async getBroadcaster() {\n return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].broadcaster_user_id));\n }\n /**\n * The level of the Hype Train.\n */\n get level() {\n return this[rawDataSymbol].level;\n }\n /**\n * The total amount of progress points of the Hype Train.\n */\n get total() {\n return this[rawDataSymbol].total;\n }\n /**\n * The amount progress points for the current level of the Hype Train.\n */\n get progress() {\n return this[rawDataSymbol].progress;\n }\n /**\n * The progress points goal to reach the next Hype Train level.\n */\n get goal() {\n return this[rawDataSymbol].goal;\n }\n /**\n * Array list of the top contributions to the Hype Train event for bits and subs.\n */\n get topContributions() {\n return this[rawDataSymbol].top_contributions.map(cont => new HelixHypeTrainContribution(cont, this._client));\n }\n /**\n * The time when the Hype Train started.\n */\n get startDate() {\n return new Date(this[rawDataSymbol].started_at);\n }\n /**\n * The time when the Hype Train is set to expire.\n */\n get expiryDate() {\n return new Date(this[rawDataSymbol].expires_at);\n }\n /**\n * The type of the Hype Train.\n */\n get type() {\n return this[rawDataSymbol].type;\n }\n /**\n * Whether the Hype Train is a shared train.\n */\n get isSharedTrain() {\n return this[rawDataSymbol].is_shared_train;\n }\n};\n__decorate([\n Enumerable(false)\n], HelixHypeTrain.prototype, \"_client\", void 0);\nHelixHypeTrain = __decorate([\n rtfm('api', 'HelixHypeTrain', 'id')\n], HelixHypeTrain);\nexport { HelixHypeTrain };\n", "import { __decorate } from \"tslib\";\nimport { Enumerable } from '@d-fischer/shared-utils';\nimport { checkRelationAssertion, DataObject, rawDataSymbol, rtfm } from '@twurple/common';\n/**\n * A Hype Train contributor.\n */\nlet HelixHypeTrainContribution = class HelixHypeTrainContribution extends DataObject {\n /** @internal */ _client;\n /** @internal */\n constructor(data, client) {\n super(data);\n this._client = client;\n }\n /**\n * The ID of the user contributing to the Hype Train.\n */\n get userId() {\n return this[rawDataSymbol].user_id;\n }\n /**\n * The name of the user contributing to the Hype Train.\n */\n get userName() {\n return this[rawDataSymbol].user_login;\n }\n /**\n * The display name of the user contributing to the Hype Train.\n */\n get userDisplayName() {\n return this[rawDataSymbol].user_name;\n }\n /**\n * Gets additional information about the user contributing to the Hype Train.\n */\n async getUser() {\n return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].user_id));\n }\n /**\n * The type of the Hype Train contribution.\n */\n get type() {\n return this[rawDataSymbol].type;\n }\n /**\n * The total contribution amount in subs or bits.\n */\n get total() {\n return this[rawDataSymbol].total;\n }\n};\n__decorate([\n Enumerable(false)\n], HelixHypeTrainContribution.prototype, \"_client\", void 0);\nHelixHypeTrainContribution = __decorate([\n rtfm('api', 'HelixHypeTrainContribution', 'userId')\n], HelixHypeTrainContribution);\nexport { HelixHypeTrainContribution };\n", "import { __decorate } from \"tslib\";\nimport { DataObject, rawDataSymbol, rtfm } from '@twurple/common';\n/**\n * All-time-high Hype Train statistics.\n */\nlet HelixHypeTrainAllTimeHigh = class HelixHypeTrainAllTimeHigh extends DataObject {\n /**\n * The level reached by the all-time-high Hype Train.\n */\n get level() {\n return this[rawDataSymbol].level;\n }\n /**\n * The total amount of contribution points reached by the all-time-high Hype Train.\n */\n get total() {\n return this[rawDataSymbol].total;\n }\n /**\n * The time when the all-time-high Hype Train was achieved.\n */\n get achievementDate() {\n return new Date(this[rawDataSymbol].achieved_at);\n }\n};\nHelixHypeTrainAllTimeHigh = __decorate([\n rtfm('api', 'HelixHypeTrainAllTimeHigh')\n], HelixHypeTrainAllTimeHigh);\nexport { HelixHypeTrainAllTimeHigh };\n", "import { __decorate } from \"tslib\";\nimport { createBroadcasterQuery } from '@twurple/api-call';\nimport { extractUserId, rtfm } from '@twurple/common';\nimport { createModeratorActionQuery, createSingleKeyQuery } from '../../interfaces/endpoints/generic.external.js';\nimport { createAutoModProcessBody, createAutoModSettingsBody, createBanUserBody, createCheckAutoModStatusBody, createModerationUserListQuery, createModeratorModifyQuery, createResolveUnbanRequestQuery, createUpdateShieldModeStatusBody, createWarnUserBody, } from '../../interfaces/endpoints/moderation.external.js';\nimport { HelixPaginatedRequest } from '../../utils/pagination/HelixPaginatedRequest.js';\nimport { createPaginatedResult } from '../../utils/pagination/HelixPaginatedResult.js';\nimport { createPaginationQuery } from '../../utils/pagination/HelixPagination.js';\nimport { BaseApi } from '../BaseApi.js';\nimport { HelixAutoModSettings } from './HelixAutoModSettings.js';\nimport { HelixAutoModStatus } from './HelixAutoModStatus.js';\nimport { HelixBan } from './HelixBan.js';\nimport { HelixBanUser } from './HelixBanUser.js';\nimport { HelixBlockedTerm } from './HelixBlockedTerm.js';\nimport { HelixModeratedChannel } from './HelixModeratedChannel.js';\nimport { HelixModerator } from './HelixModerator.js';\nimport { HelixShieldModeStatus } from './HelixShieldModeStatus.js';\nimport { HelixUnbanRequest } from './HelixUnbanRequest.js';\nimport { HelixWarning } from './HelixWarning.js';\n/**\n * The Helix API methods that deal with moderation.\n *\n * Can be accessed using `client.moderation` on an {@link ApiClient} instance.\n *\n * ## Example\n * ```ts\n * const api = new ApiClient({ authProvider });\n * const { data: users } = await api.moderation.getBannedUsers('61369223');\n * ```\n *\n * @meta category helix\n * @meta categorizedTitle Moderation\n */\nlet HelixModerationApi = class HelixModerationApi extends BaseApi {\n /**\n * Gets a list of banned users in a given channel.\n *\n * @param channel The channel to get the banned users from.\n * @param filter Additional filters for the result set.\n *\n * @expandParams\n */\n async getBannedUsers(channel, filter) {\n const result = await this._client.callApi({\n type: 'helix',\n url: 'moderation/banned',\n userId: extractUserId(channel),\n scopes: ['moderation:read'],\n query: {\n ...createModerationUserListQuery(channel, filter),\n ...createPaginationQuery(filter),\n },\n });\n return createPaginatedResult(result, HelixBan, this._client);\n }\n /**\n * Creates a paginator for banned users in a given channel.\n *\n * @param channel The channel to get the banned users from.\n */\n getBannedUsersPaginated(channel) {\n return new HelixPaginatedRequest({\n url: 'moderation/banned',\n userId: extractUserId(channel),\n scopes: ['moderation:read'],\n query: createBroadcasterQuery(channel),\n }, this._client, data => new HelixBan(data, this._client), 50);\n }\n /**\n * Checks whether a given user is banned in a given channel.\n *\n * @param channel The channel to check for a ban of the given user.\n * @param user The user to check for a ban in the given channel.\n */\n async checkUserBan(channel, user) {\n const userId = extractUserId(user);\n const result = await this.getBannedUsers(channel, { userId });\n return result.data.some(ban => ban.userId === userId);\n }\n /**\n * Gets a list of moderators in a given channel.\n *\n * @param channel The channel to get moderators from.\n * @param filter Additional filters for the result set.\n *\n * @expandParams\n */\n async getModerators(channel, filter) {\n const result = await this._client.callApi({\n type: 'helix',\n url: 'moderation/moderators',\n userId: extractUserId(channel),\n scopes: ['moderation:read', 'channel:manage:moderators'],\n query: {\n ...createModerationUserListQuery(channel, filter),\n ...createPaginationQuery(filter),\n },\n });\n return createPaginatedResult(result, HelixModerator, this._client);\n }\n /**\n * Creates a paginator for moderators in a given channel.\n *\n * @param channel The channel to get moderators from.\n */\n getModeratorsPaginated(channel) {\n return new HelixPaginatedRequest({\n url: 'moderation/moderators',\n userId: extractUserId(channel),\n scopes: ['moderation:read', 'channel:manage:moderators'],\n query: createBroadcasterQuery(channel),\n }, this._client, data => new HelixModerator(data, this._client));\n }\n /**\n * Gets a list of channels where the specified user has moderator privileges.\n *\n * @param user The user for whom to return a list of channels where they have moderator privileges.\n * This ID must match the user ID in the access token.\n * @param filter\n *\n * @expandParams\n *\n * @returns A paginated list of channels where the user has moderator privileges.\n */\n async getModeratedChannels(user, filter) {\n const userId = extractUserId(user);\n const result = await this._client.callApi({\n type: 'helix',\n url: 'moderation/channels',\n userId,\n scopes: ['user:read:moderated_channels'],\n query: {\n ...createSingleKeyQuery('user_id', userId),\n ...createPaginationQuery(filter),\n },\n });\n return createPaginatedResult(result, HelixModeratedChannel, this._client);\n }\n /**\n * Creates a paginator for channels where the specified user has moderator privileges.\n *\n * @param user The user for whom to return the list of channels where they have moderator privileges.\n * This ID must match the user ID in the access token.\n */\n getModeratedChannelsPaginated(user) {\n const userId = extractUserId(user);\n return new HelixPaginatedRequest({\n url: 'moderation/channels',\n userId,\n scopes: ['user:read:moderated_channels'],\n query: createSingleKeyQuery('user_id', userId),\n }, this._client, data => new HelixModeratedChannel(data, this._client));\n }\n /**\n * Checks whether a given user is a moderator of a given channel.\n *\n * @param channel The channel to check.\n * @param user The user to check.\n */\n async checkUserMod(channel, user) {\n const userId = extractUserId(user);\n const result = await this.getModerators(channel, { userId });\n return result.data.some(mod => mod.userId === userId);\n }\n /**\n * Adds a moderator to the broadcaster\u2019s chat room.\n *\n * @param broadcaster The broadcaster that owns the chat room. This ID must match the user ID in the access token.\n * @param user The user to add as a moderator in the broadcaster\u2019s chat room.\n */\n async addModerator(broadcaster, user) {\n await this._client.callApi({\n type: 'helix',\n url: 'moderation/moderators',\n method: 'POST',\n userId: extractUserId(broadcaster),\n scopes: ['channel:manage:moderators'],\n query: createModeratorModifyQuery(broadcaster, user),\n });\n }\n /**\n * Removes a moderator from the broadcaster\u2019s chat room.\n *\n * @param broadcaster The broadcaster that owns the chat room. This ID must match the user ID in the access token.\n * @param user The user to remove as a moderator from the broadcaster\u2019s chat room.\n */\n async removeModerator(broadcaster, user) {\n await this._client.callApi({\n type: 'helix',\n url: 'moderation/moderators',\n method: 'DELETE',\n userId: extractUserId(broadcaster),\n scopes: ['channel:manage:moderators'],\n query: createModeratorModifyQuery(broadcaster, user),\n });\n }\n /**\n * Determines whether a string message meets the channel's AutoMod requirements.\n *\n * @param channel The channel in which the messages to check are posted.\n * @param data An array of message data objects.\n */\n async checkAutoModStatus(channel, data) {\n const result = await this._client.callApi({\n type: 'helix',\n url: 'moderation/enforcements/status',\n method: 'POST',\n userId: extractUserId(channel),\n scopes: ['moderation:read'],\n query: createBroadcasterQuery(channel),\n jsonBody: createCheckAutoModStatusBody(data),\n });\n return result.data.map(statusData => new HelixAutoModStatus(statusData));\n }\n /**\n * Processes a message held by AutoMod.\n *\n * @param user The user who is processing the message.\n * @param msgId The ID of the message.\n * @param allow Whether to allow the message - `true` allows, and `false` denies.\n */\n async processHeldAutoModMessage(user, msgId, allow) {\n await this._client.callApi({\n type: 'helix',\n url: 'moderation/automod/message',\n method: 'POST',\n userId: extractUserId(user),\n scopes: ['moderator:manage:automod'],\n jsonBody: createAutoModProcessBody(user, msgId, allow),\n });\n }\n /**\n * Gets the AutoMod settings for a broadcaster.\n *\n * This uses the token of the broadcaster by default.\n * If you want to execute this in the context of another user (who has to be moderator of the channel)\n * you can do so using [user context overrides](/docs/auth/concepts/context-switching).\n *\n * @param broadcaster The broadcaster to get the AutoMod settings for.\n */\n async getAutoModSettings(broadcaster) {\n const broadcasterId = extractUserId(broadcaster);\n const result = await this._client.callApi({\n type: 'helix',\n url: 'moderation/automod/settings',\n userId: broadcasterId,\n scopes: ['moderator:read:automod_settings'],\n canOverrideScopedUserContext: true,\n query: this._createModeratorActionQuery(broadcasterId),\n });\n return result.data.map(data => new HelixAutoModSettings(data));\n }\n /**\n * Updates the AutoMod settings for a broadcaster.\n *\n * This uses the token of the broadcaster by default.\n * If you want to execute this in the context of another user (who has to be moderator of the channel)\n * you can do so using [user context overrides](/docs/auth/concepts/context-switching).\n *\n * @param broadcaster The broadcaster for which the AutoMod settings are updated.\n * @param data The updated AutoMod settings that replace the current AutoMod settings.\n */\n async updateAutoModSettings(broadcaster, data) {\n const broadcasterId = extractUserId(broadcaster);\n const result = await this._client.callApi({\n type: 'helix',\n url: 'moderation/automod/settings',\n method: 'PUT',\n userId: broadcasterId,\n scopes: ['moderator:manage:automod_settings'],\n canOverrideScopedUserContext: true,\n query: this._createModeratorActionQuery(broadcasterId),\n jsonBody: createAutoModSettingsBody(data),\n });\n return result.data.map(settingsData => new HelixAutoModSettings(settingsData));\n }\n /**\n * Bans or times out a user in a channel.\n *\n * This uses the token of the broadcaster by default.\n * If you want to execute this in the context of another user (who has to be moderator of the channel)\n * you can do so using [user context overrides](/docs/auth/concepts/context-switching).\n *\n * @param broadcaster The broadcaster in whose channel the user will be banned/timed out.\n * @param data\n *\n * @expandParams\n *\n * @returns The result data from the ban/timeout request.\n */\n async banUser(broadcaster, data) {\n const broadcasterId = extractUserId(broadcaster);\n const result = await this._client.callApi({\n type: 'helix',\n url: 'moderation/bans',\n method: 'POST',\n userId: broadcasterId,\n scopes: ['moderator:manage:banned_users'],\n canOverrideScopedUserContext: true,\n query: this._createModeratorActionQuery(broadcasterId),\n jsonBody: createBanUserBody(data),\n });\n return result.data.map(banData => new HelixBanUser(banData, banData.end_time, this._client));\n }\n /**\n * Unbans/removes the timeout for a user in a channel.\n *\n * This uses the token of the broadcaster by default.\n * If you want to execute this in the context of another user (who has to be moderator of the channel)\n * you can do so using [user context overrides](/docs/auth/concepts/context-switching).\n *\n * @param broadcaster The broadcaster in whose channel the user will be unbanned/removed from timeout.\n * @param user The user who will be unbanned/removed from timeout.\n */\n async unbanUser(broadcaster, user) {\n const broadcasterId = extractUserId(broadcaster);\n await this._client.callApi({\n type: 'helix',\n url: 'moderation/bans',\n method: 'DELETE',\n userId: broadcasterId,\n scopes: ['moderator:manage:banned_users'],\n canOverrideScopedUserContext: true,\n query: {\n ...this._createModeratorActionQuery(broadcasterId),\n ...createSingleKeyQuery('user_id', extractUserId(user)),\n },\n });\n }\n /**\n * Gets the broadcaster\u2019s list of non-private, blocked words or phrases.\n *\n * This uses the token of the broadcaster by default.\n * If you want to execute this in the context of another user (who has to be moderator of the channel)\n * you can do so using [user context overrides](/docs/auth/concepts/context-switching).\n *\n * @param broadcaster The broadcaster to get their channel's blocked terms for.\n * @param pagination\n *\n * @expandParams\n *\n * @returns A paginated list of blocked term data in the broadcaster's channel.\n */\n async getBlockedTerms(broadcaster, pagination) {\n const broadcasterId = extractUserId(broadcaster);\n const result = await this._client.callApi({\n type: 'helix',\n url: 'moderation/blocked_terms',\n userId: broadcasterId,\n scopes: ['moderator:read:blocked_terms'],\n canOverrideScopedUserContext: true,\n query: {\n ...this._createModeratorActionQuery(broadcasterId),\n ...createPaginationQuery(pagination),\n },\n });\n return createPaginatedResult(result, HelixBlockedTerm, this._client);\n }\n /**\n * Adds a blocked term to the broadcaster's channel.\n *\n * This uses the token of the broadcaster by default.\n * If you want to execute this in the context of another user (who has to be moderator of the channel)\n * you can do so using [user context overrides](/docs/auth/concepts/context-switching).\n *\n * @param broadcaster The broadcaster in whose channel the term will be blocked.\n * @param text The word or phrase to block from being used in the broadcaster's channel.\n *\n * @returns Information about the term that has been blocked.\n */\n async addBlockedTerm(broadcaster, text) {\n const broadcasterId = extractUserId(broadcaster);\n const result = await this._client.callApi({\n type: 'helix',\n url: 'moderation/blocked_terms',\n method: 'POST',\n userId: broadcasterId,\n scopes: ['moderator:manage:blocked_terms'],\n canOverrideScopedUserContext: true,\n query: this._createModeratorActionQuery(broadcasterId),\n jsonBody: {\n text,\n },\n });\n return result.data.map(blockedTermData => new HelixBlockedTerm(blockedTermData));\n }\n /**\n * Removes a blocked term from the broadcaster's channel.\n *\n * @param broadcaster The broadcaster in whose channel the term will be unblocked.\n * @param moderator A user that has permission to unblock terms in the broadcaster's channel.\n * The token of this user will be used to remove the blocked term.\n * @param id The ID of the term that should be unblocked.\n */\n async removeBlockedTerm(broadcaster, moderator, id) {\n const broadcasterId = extractUserId(broadcaster);\n await this._client.callApi({\n type: 'helix',\n url: 'moderation/blocked_terms',\n method: 'DELETE',\n userId: broadcasterId,\n scopes: ['moderator:manage:blocked_terms'],\n canOverrideScopedUserContext: true,\n query: {\n ...this._createModeratorActionQuery(broadcasterId),\n id,\n },\n });\n }\n /**\n * Removes a single chat message or all chat messages from the broadcaster\u2019s chat room.\n *\n * This uses the token of the broadcaster by default.\n * If you want to execute this in the context of another user (who has to be moderator of the channel)\n * you can do so using [user context overrides](/docs/auth/concepts/context-switching).\n *\n * @param broadcaster The broadcaster the chat belongs to.\n * @param messageId The ID of the message to remove. If not specified, the request removes all messages in the broadcaster\u2019s chat room.\n */\n async deleteChatMessages(broadcaster, messageId) {\n const broadcasterId = extractUserId(broadcaster);\n await this._client.callApi({\n type: 'helix',\n url: 'moderation/chat',\n method: 'DELETE',\n userId: broadcasterId,\n scopes: ['moderator:manage:chat_messages'],\n canOverrideScopedUserContext: true,\n query: {\n ...this._createModeratorActionQuery(broadcasterId),\n ...createSingleKeyQuery('message_id', messageId),\n },\n });\n }\n /**\n * Gets the broadcaster's Shield Mode activation status.\n *\n * @param broadcaster The broadcaster whose Shield Mode activation status you want to get.\n */\n async getShieldModeStatus(broadcaster) {\n const broadcasterId = extractUserId(broadcaster);\n const result = await this._client.callApi({\n type: 'helix',\n url: 'moderation/shield_mode',\n method: 'GET',\n userId: broadcasterId,\n scopes: ['moderator:read:shield_mode', 'moderator:manage:shield_mode'],\n canOverrideScopedUserContext: true,\n query: this._createModeratorActionQuery(broadcasterId),\n });\n return new HelixShieldModeStatus(result.data[0], this._client);\n }\n /**\n * Activates or deactivates the broadcaster's Shield Mode.\n *\n * This uses the token of the broadcaster by default.\n * If you want to execute this in the context of another user (who has to be moderator of the channel)\n * you can do so using [user context overrides](/docs/auth/concepts/context-switching).\n *\n * @param broadcaster The broadcaster whose Shield Mode you want to activate or deactivate.\n * @param activate The desired Shield Mode status on the broadcaster's channel.\n */\n async updateShieldModeStatus(broadcaster, activate) {\n const broadcasterId = extractUserId(broadcaster);\n const result = await this._client.callApi({\n type: 'helix',\n url: 'moderation/shield_mode',\n method: 'PUT',\n userId: broadcasterId,\n scopes: ['moderator:manage:shield_mode'],\n canOverrideScopedUserContext: true,\n query: this._createModeratorActionQuery(broadcasterId),\n jsonBody: createUpdateShieldModeStatusBody(activate),\n });\n return new HelixShieldModeStatus(result.data[0], this._client);\n }\n /**\n * Gets a list of unban requests.\n *\n * @param broadcaster The broadcaster to get unban requests of.\n * @param status The status of unban requests to retrieve.\n * @param filter Additional filters for the result set.\n */\n async getUnbanRequests(broadcaster, status, filter) {\n const broadcasterId = extractUserId(broadcaster);\n const result = await this._client.callApi({\n type: 'helix',\n url: 'moderation/unban_requests',\n method: 'GET',\n userId: broadcasterId,\n scopes: ['moderator:read:unban_requests', 'moderator:manage:unban_requests'],\n canOverrideScopedUserContext: true,\n query: {\n ...this._createModeratorActionQuery(broadcasterId),\n ...createSingleKeyQuery('status', status),\n ...createPaginationQuery(filter),\n },\n });\n return createPaginatedResult(result, HelixUnbanRequest, this._client);\n }\n /**\n * Creates a paginator for unban requests.\n *\n * @param broadcaster The broadcaster to get unban requests of.\n * @param status The status of unban requests to retrieve.\n */\n getUnbanRequestsPaginated(broadcaster, status) {\n const broadcasterId = extractUserId(broadcaster);\n return new HelixPaginatedRequest({\n url: 'moderation/unban_requests',\n method: 'GET',\n userId: broadcasterId,\n scopes: ['moderator:read:unban_requests', 'moderator:manage:unban_requests'],\n canOverrideScopedUserContext: true,\n query: {\n ...this._createModeratorActionQuery(broadcasterId),\n ...createSingleKeyQuery('status', status),\n },\n }, this._client, data => new HelixUnbanRequest(data, this._client));\n }\n /**\n * Resolves an unban request by approving or denying it.\n *\n * This uses the token of the broadcaster by default.\n * If you want to execute this in the context of another user (who has to be moderator of the channel)\n * you can do so using [user context overrides](/docs/auth/concepts/context-switching).\n *\n * @param broadcaster The ID of the broadcaster whose channel is approving or denying the unban request.\n * @param unbanRequestId The ID of the unban request to resolve.\n * @param approved Whether to approve or deny the unban request.\n * @param resolutionMessage Message supplied by the unban request resolver.\n *\n * The message is limited to a maximum of 500 characters.\n */\n async resolveUnbanRequest(broadcaster, unbanRequestId, approved, resolutionMessage) {\n const broadcasterId = extractUserId(broadcaster);\n const result = await this._client.callApi({\n type: 'helix',\n url: 'moderation/unban_requests',\n method: 'PATCH',\n userId: broadcasterId,\n scopes: ['moderator:manage:unban_requests'],\n canOverrideScopedUserContext: true,\n query: createResolveUnbanRequestQuery(broadcasterId, this._getUserContextIdWithDefault(broadcasterId), unbanRequestId, approved, resolutionMessage?.slice(0, 500)),\n });\n return new HelixUnbanRequest(result.data[0], this._client);\n }\n /**\n * Warns a user in the specified broadcaster\u2019s chat room, preventing them from chat interaction until the\n * warning is acknowledged.\n *\n * New warnings can be issued to a user when they already have a warning in the channel\n * (new warning will replace old warning).\n *\n * @param broadcaster The ID of the broadcaster in which channel the warning will take effect.\n * @param user The ID of the user to be warned.\n * @param reason A custom reason for the warning. Max 500 chars.\n */\n async warnUser(broadcaster, user, reason) {\n const broadcasterId = extractUserId(broadcaster);\n const result = await this._client.callApi({\n type: 'helix',\n url: 'moderation/warnings',\n method: 'POST',\n userId: broadcasterId,\n scopes: ['moderator:manage:warnings'],\n canOverrideScopedUserContext: true,\n query: this._createModeratorActionQuery(broadcasterId),\n jsonBody: createWarnUserBody(user, reason.slice(0, 500)),\n });\n return new HelixWarning(result.data[0], this._client);\n }\n _createModeratorActionQuery(broadcasterId) {\n return createModeratorActionQuery(broadcasterId, this._getUserContextIdWithDefault(broadcasterId));\n }\n};\nHelixModerationApi = __decorate([\n rtfm('api', 'HelixModerationApi')\n], HelixModerationApi);\nexport { HelixModerationApi };\n", "import { extractUserId } from '@twurple/common';\n/** @internal */\nexport function createModerationUserListQuery(channel, filter) {\n return {\n broadcaster_id: extractUserId(channel),\n user_id: filter?.userId,\n };\n}\n/** @internal */\nexport function createModeratorModifyQuery(broadcaster, user) {\n return {\n broadcaster_id: extractUserId(broadcaster),\n user_id: extractUserId(user),\n };\n}\n/** @internal */\nexport function createResolveUnbanRequestQuery(broadcaster, moderator, unbanRequestId, approved, resolutionMessage) {\n return {\n unban_request_id: unbanRequestId,\n broadcaster_id: extractUserId(broadcaster),\n moderator_id: extractUserId(moderator),\n status: approved ? 'approved' : 'denied',\n resolution_text: resolutionMessage,\n };\n}\n/** @internal */\nexport function createAutoModProcessBody(user, msgId, allow) {\n return {\n user_id: extractUserId(user),\n msg_id: msgId,\n action: allow ? 'ALLOW' : 'DENY',\n };\n}\n/** @internal */\nexport function createAutoModSettingsBody(data) {\n return {\n overall_level: data.overallLevel,\n aggression: data.aggression,\n bullying: data.bullying,\n disability: data.disability,\n misogyny: data.misogyny,\n race_ethnicity_or_religion: data.raceEthnicityOrReligion,\n sex_based_terms: data.sexBasedTerms,\n sexuality_sex_or_gender: data.sexualitySexOrGender,\n swearing: data.swearing,\n };\n}\n/** @internal */\nexport function createBanUserBody(data) {\n return {\n data: {\n duration: data.duration,\n reason: data.reason,\n user_id: extractUserId(data.user),\n },\n };\n}\n/** @internal */\nexport function createUpdateShieldModeStatusBody(activate) {\n return {\n is_active: activate,\n };\n}\n/** @internal */\nexport function createCheckAutoModStatusBody(data) {\n return {\n data: data.map(entry => ({\n msg_id: entry.messageId,\n msg_text: entry.messageText,\n })),\n };\n}\n/** @internal */\nexport function createWarnUserBody(user, reason) {\n return {\n data: {\n user_id: extractUserId(user),\n reason,\n },\n };\n}\n", "import { __decorate } from \"tslib\";\nimport { DataObject, rawDataSymbol, rtfm } from '@twurple/common';\n/**\n * The AutoMod settings of a channel.\n */\nlet HelixAutoModSettings = class HelixAutoModSettings extends DataObject {\n /**\n * The ID of the broadcaster for which the AutoMod settings were fetched.\n */\n get broadcasterId() {\n return this[rawDataSymbol].broadcaster_id;\n }\n /**\n * The ID of a user that has permission to moderate the broadcaster's chat room.\n */\n get moderatorId() {\n return this[rawDataSymbol].moderator_id;\n }\n /**\n * The default AutoMod level for the broadcaster. This is null if the broadcaster changed individual settings.\n */\n get overallLevel() {\n return this[rawDataSymbol].overall_level ? this[rawDataSymbol].overall_level : null;\n }\n /**\n * The AutoMod level for discrimination against disability.\n */\n get disability() {\n return this[rawDataSymbol].disability;\n }\n /**\n * The AutoMod level for hostility involving aggression.\n */\n get aggression() {\n return this[rawDataSymbol].aggression;\n }\n /**\n * The AutoMod level for discrimination based on sexuality, sex, or gender.\n */\n get sexualitySexOrGender() {\n return this[rawDataSymbol].sexuality_sex_or_gender;\n }\n /**\n * The AutoMod level for discrimination against women.\n */\n get misogyny() {\n return this[rawDataSymbol].misogyny;\n }\n /**\n * The AutoMod level for hostility involving name calling or insults.\n */\n get bullying() {\n return this[rawDataSymbol].bullying;\n }\n /**\n * The AutoMod level for profanity.\n */\n get swearing() {\n return this[rawDataSymbol].swearing;\n }\n /**\n * The AutoMod level for racial discrimination.\n */\n get raceEthnicityOrReligion() {\n return this[rawDataSymbol].race_ethnicity_or_religion;\n }\n /**\n * The AutoMod level for sexual content.\n */\n get sexBasedTerms() {\n return this[rawDataSymbol].sex_based_terms;\n }\n};\nHelixAutoModSettings = __decorate([\n rtfm('api', 'HelixAutoModSettings', 'broadcasterId')\n], HelixAutoModSettings);\nexport { HelixAutoModSettings };\n", "import { __decorate } from \"tslib\";\nimport { DataObject, rawDataSymbol, rtfm } from '@twurple/common';\n/**\n * The status of a message that says whether it is permitted by AutoMod or not.\n */\nlet HelixAutoModStatus = class HelixAutoModStatus extends DataObject {\n /**\n * The developer-generated ID that was sent with the request data.\n */\n get messageId() {\n return this[rawDataSymbol].msg_id;\n }\n /**\n * Whether the message is permitted by AutoMod or not.\n */\n get isPermitted() {\n return this[rawDataSymbol].is_permitted;\n }\n};\nHelixAutoModStatus = __decorate([\n rtfm('api', 'HelixAutoModStatus', 'messageId')\n], HelixAutoModStatus);\nexport { HelixAutoModStatus };\n", "import { __decorate } from \"tslib\";\nimport { rawDataSymbol, rtfm } from '@twurple/common';\nimport { HelixBanUser } from './HelixBanUser.js';\n/**\n * Information about the ban of a user.\n *\n * @inheritDoc\n */\nlet HelixBan = class HelixBan extends HelixBanUser {\n /** @internal */\n constructor(data, client) {\n super(data, data.expires_at || null, client);\n }\n /**\n * The name of the user that was banned or put in a timeout.\n */\n get userName() {\n return this[rawDataSymbol].user_login;\n }\n /**\n * The display name of the user that was banned or put in a timeout.\n */\n get userDisplayName() {\n return this[rawDataSymbol].user_name;\n }\n /**\n * The name of the moderator that banned or put the user in the timeout.\n */\n get moderatorName() {\n return this[rawDataSymbol].moderator_login;\n }\n /**\n * The display name of the moderator that banned or put the user in the timeout.\n */\n get moderatorDisplayName() {\n return this[rawDataSymbol].moderator_name;\n }\n /**\n * The reason why the user was banned or timed out. Returns `null` if no reason was given.\n */\n get reason() {\n return this[rawDataSymbol].reason || null;\n }\n};\nHelixBan = __decorate([\n rtfm('api', 'HelixBan', 'userId')\n], HelixBan);\nexport { HelixBan };\n", "import { __decorate } from \"tslib\";\nimport { Enumerable, mapNullable } from '@d-fischer/shared-utils';\nimport { checkRelationAssertion, DataObject, rawDataSymbol, rtfm } from '@twurple/common';\n/**\n * Information about a user who has been banned/timed out.\n *\n * @hideProtected\n */\nlet HelixBanUser = class HelixBanUser extends DataObject {\n /** @internal */ _client;\n /** @internal */ _expiryTimestamp;\n /** @internal */\n constructor(data, expiryTimestamp, client) {\n super(data);\n this._expiryTimestamp = expiryTimestamp;\n this._client = client;\n }\n /**\n * The date and time that the ban/timeout was created.\n */\n get creationDate() {\n return new Date(this[rawDataSymbol].created_at);\n }\n /**\n * The date and time that the timeout will end. Is `null` if the user was banned instead of put in a timeout.\n */\n get expiryDate() {\n return mapNullable(this._expiryTimestamp, ts => new Date(ts));\n }\n /**\n * The ID of the moderator that banned or put the user in the timeout.\n */\n get moderatorId() {\n return this[rawDataSymbol].moderator_id;\n }\n /**\n * Gets more information about the moderator that banned or put the user in the timeout.\n */\n async getModerator() {\n return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].moderator_id));\n }\n /**\n * The ID of the user that was banned or put in a timeout.\n */\n get userId() {\n return this[rawDataSymbol].user_id;\n }\n /**\n * Gets more information about the user that was banned or put in a timeout.\n */\n async getUser() {\n return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].user_id));\n }\n};\n__decorate([\n Enumerable(false)\n], HelixBanUser.prototype, \"_client\", void 0);\n__decorate([\n Enumerable(false)\n], HelixBanUser.prototype, \"_expiryTimestamp\", void 0);\nHelixBanUser = __decorate([\n rtfm('api', 'HelixBanUser', 'userId')\n], HelixBanUser);\nexport { HelixBanUser };\n", "import { __decorate } from \"tslib\";\nimport { DataObject, rawDataSymbol, rtfm } from '@twurple/common';\n/**\n * Information about a word or phrase blocked in a broadcaster's channel.\n */\nlet HelixBlockedTerm = class HelixBlockedTerm extends DataObject {\n /**\n * The ID of the broadcaster that owns the list of blocked terms.\n */\n get broadcasterId() {\n return this[rawDataSymbol].broadcaster_id;\n }\n /**\n * The date and time of when the term was blocked.\n */\n get creationDate() {\n return new Date(this[rawDataSymbol].created_at);\n }\n /**\n * The date and time of when the blocked term is set to expire. After the block expires, users will be able to use the term in the broadcaster\u2019s chat room.\n * Is `null` if the term was added manually or permanently blocked by AutoMod.\n */\n get expirationDate() {\n return this[rawDataSymbol].expires_at ? new Date(this[rawDataSymbol].expires_at) : null;\n }\n /**\n * An ID that uniquely identifies this blocked term.\n */\n get id() {\n return this[rawDataSymbol].id;\n }\n /**\n * The ID of the moderator that blocked the word or phrase from being used in the broadcaster\u2019s chat room.\n */\n get moderatorId() {\n return this[rawDataSymbol].moderator_id;\n }\n /**\n * The blocked word or phrase.\n */\n get text() {\n return this[rawDataSymbol].text;\n }\n /**\n * The date and time of when the term was updated.\n */\n get updatedDate() {\n return new Date(this[rawDataSymbol].updated_at);\n }\n};\nHelixBlockedTerm = __decorate([\n rtfm('api', 'HelixBlockedTerm', 'id')\n], HelixBlockedTerm);\nexport { HelixBlockedTerm };\n", "import { __decorate } from \"tslib\";\nimport { Enumerable } from '@d-fischer/shared-utils';\nimport { checkRelationAssertion, DataObject, rawDataSymbol, rtfm } from '@twurple/common';\n/**\n * A reference to a Twitch channel where a user is a moderator.\n */\nlet HelixModeratedChannel = class HelixModeratedChannel extends DataObject {\n /** @internal */ _client;\n /** @internal */\n constructor(data, client) {\n super(data);\n this._client = client;\n }\n /**\n * The ID of the channel.\n */\n get id() {\n return this[rawDataSymbol].broadcaster_id;\n }\n /**\n * The name of the channel.\n */\n get name() {\n return this[rawDataSymbol].broadcaster_login;\n }\n /**\n * The display name of the channel.\n */\n get displayName() {\n return this[rawDataSymbol].broadcaster_name;\n }\n /**\n * Gets more information about the channel.\n */\n async getChannel() {\n return checkRelationAssertion(await this._client.channels.getChannelInfoById(this[rawDataSymbol].broadcaster_id));\n }\n /**\n * Gets more information about the broadcaster of the channel.\n */\n async getBroadcaster() {\n return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].broadcaster_id));\n }\n};\n__decorate([\n Enumerable(false)\n], HelixModeratedChannel.prototype, \"_client\", void 0);\nHelixModeratedChannel = __decorate([\n rtfm('api', 'HelixModeratedChannel', 'id')\n], HelixModeratedChannel);\nexport { HelixModeratedChannel };\n", "import { __decorate } from \"tslib\";\nimport { Enumerable } from '@d-fischer/shared-utils';\nimport { checkRelationAssertion, DataObject, rawDataSymbol, rtfm } from '@twurple/common';\n/**\n * Information about the moderator status of a user.\n */\nlet HelixModerator = class HelixModerator extends DataObject {\n /** @internal */ _client;\n /** @internal */\n constructor(data, client) {\n super(data);\n this._client = client;\n }\n /**\n * The ID of the user.\n */\n get userId() {\n return this[rawDataSymbol].user_id;\n }\n /**\n * The name of the user.\n */\n get userName() {\n return this[rawDataSymbol].user_login;\n }\n /**\n * The display name of the user.\n */\n get userDisplayName() {\n return this[rawDataSymbol].user_name;\n }\n /**\n * Gets more information about the user.\n */\n async getUser() {\n return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].user_id));\n }\n};\n__decorate([\n Enumerable(false)\n], HelixModerator.prototype, \"_client\", void 0);\nHelixModerator = __decorate([\n rtfm('api', 'HelixModerator', 'userId')\n], HelixModerator);\nexport { HelixModerator };\n", "import { __decorate } from \"tslib\";\nimport { Enumerable } from '@d-fischer/shared-utils';\nimport { checkRelationAssertion, DataObject, rawDataSymbol, rtfm } from '@twurple/common';\n/**\n * Information about the Shield Mode status of a channel.\n */\nlet HelixShieldModeStatus = class HelixShieldModeStatus extends DataObject {\n /** @internal */ _client;\n /** @internal */\n constructor(data, client) {\n super(data);\n this._client = client;\n }\n /**\n * Whether Shield Mode is active.\n */\n get isActive() {\n return this[rawDataSymbol].is_active;\n }\n /**\n * The ID of the moderator that last activated Shield Mode.\n */\n get moderatorId() {\n return this[rawDataSymbol].moderator_id;\n }\n /**\n * The name of the moderator that last activated Shield Mode.\n */\n get moderatorName() {\n return this[rawDataSymbol].moderator_login;\n }\n /**\n * The display name of the moderator that last activated Shield Mode.\n */\n get moderatorDisplayName() {\n return this[rawDataSymbol].moderator_name;\n }\n /**\n * Gets more information about the moderator that last activated Shield Mode.\n */\n async getModerator() {\n return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].moderator_id));\n }\n /**\n * The date when Shield Mode was last activated. `null` indicates Shield Mode hasn't been previously activated.\n */\n get lastActivationDate() {\n return this[rawDataSymbol].last_activated_at === '' ? null : new Date(this[rawDataSymbol].last_activated_at);\n }\n};\n__decorate([\n Enumerable(false)\n], HelixShieldModeStatus.prototype, \"_client\", void 0);\nHelixShieldModeStatus = __decorate([\n rtfm('api', 'HelixShieldModeStatus')\n], HelixShieldModeStatus);\nexport { HelixShieldModeStatus };\n", "import { __decorate } from \"tslib\";\nimport { Enumerable, mapNullable } from '@d-fischer/shared-utils';\nimport { checkRelationAssertion, DataObject, rawDataSymbol, rtfm } from '@twurple/common';\n/**\n * A request from a user to be unbanned from a channel.\n */\nlet HelixUnbanRequest = class HelixUnbanRequest extends DataObject {\n /** @internal */ _client;\n /** @internal */\n constructor(data, client) {\n super(data);\n this._client = client;\n }\n /**\n * Unban request ID.\n */\n get id() {\n return this[rawDataSymbol].id;\n }\n /**\n * The ID of the broadcaster whose channel is receiving the unban request.\n */\n get broadcasterId() {\n return this[rawDataSymbol].broadcaster_id;\n }\n /**\n * The name of the broadcaster whose channel is receiving the unban request.\n */\n get broadcasterName() {\n return this[rawDataSymbol].broadcaster_id;\n }\n /**\n * The display name of the broadcaster whose channel is receiving the unban request.\n */\n get broadcasterDisplayName() {\n return this[rawDataSymbol].broadcaster_id;\n }\n /**\n * Gets more information about the broadcaster.\n */\n async getBroadcaster() {\n return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].broadcaster_id));\n }\n /**\n * The ID of the moderator who resolved the unban request.\n *\n * Can be `null` if the request is not resolved.\n */\n get moderatorId() {\n return this[rawDataSymbol].moderator_id;\n }\n /**\n * The name of the moderator who resolved the unban request.\n *\n * Can be `null` if the request is not resolved.\n */\n get moderatorName() {\n return this[rawDataSymbol].moderator_login;\n }\n /**\n * The display name of the moderator who resolved the unban request.\n *\n * Can be `null` if the request is not resolved.\n */\n get moderatorDisplayName() {\n return this[rawDataSymbol].moderator_name;\n }\n /**\n * Gets more information about the moderator.\n */\n async getModerator() {\n return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].moderator_id));\n }\n /**\n * The ID of the user who requested to be unbanned.\n */\n get userId() {\n return this[rawDataSymbol].user_id;\n }\n /**\n * The name of the user who requested to be unbanned.\n */\n get userName() {\n return this[rawDataSymbol].user_login;\n }\n /**\n * The display name of the user who requested to be unbanned.\n */\n get userDisplayName() {\n return this[rawDataSymbol].user_name;\n }\n /**\n * Gets more information about the user.\n */\n async getUser() {\n return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].user_id));\n }\n /**\n * Text message of the unban request from the requesting user.\n */\n get message() {\n return this[rawDataSymbol].text;\n }\n /**\n * The date of when the unban request was created.\n */\n get creationDate() {\n return new Date(this[rawDataSymbol].created_at);\n }\n /**\n * The message written by the moderator who resolved the unban request, or `null` if it has not been resolved yet.\n */\n get resolutionMessage() {\n // Can be empty string and null\n // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing\n return this[rawDataSymbol].resolution_text || null;\n }\n /**\n * The date when the unban request was resolved, or `null` if it has not been resolved yet.\n */\n get resolutionDate() {\n return mapNullable(this[rawDataSymbol].resolved_at, val => new Date(val));\n }\n};\n__decorate([\n Enumerable(false)\n], HelixUnbanRequest.prototype, \"_client\", void 0);\nHelixUnbanRequest = __decorate([\n rtfm('api', 'HelixUnbanRequest', 'id')\n], HelixUnbanRequest);\nexport { HelixUnbanRequest };\n", "import { __decorate } from \"tslib\";\nimport { Enumerable } from '@d-fischer/shared-utils';\nimport { checkRelationAssertion, DataObject, rawDataSymbol, rtfm } from '@twurple/common';\n/**\n * Information about the warning.\n */\nlet HelixWarning = class HelixWarning extends DataObject {\n /** @internal */ _client;\n /** @internal */\n constructor(data, client) {\n super(data);\n this._client = client;\n }\n /**\n * The ID of the channel in which the warning will take effect.\n */\n get broadcasterId() {\n return this[rawDataSymbol].user_id;\n }\n /**\n * Gets more information about the broadcaster.\n */\n async getBroadcaster() {\n return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].broadcaster_id));\n }\n /**\n * The ID of the user who applied the warning.\n */\n get moderatorId() {\n return this[rawDataSymbol].moderator_id;\n }\n /**\n * Gets more information about the moderator.\n */\n async getModerator() {\n return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].moderator_id));\n }\n /**\n * The ID of the warned user.\n */\n get userId() {\n return this[rawDataSymbol].user_id;\n }\n /**\n * Gets more information about the user.\n */\n async getUser() {\n return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].user_id));\n }\n /**\n * The reason provided for the warning.\n */\n get reason() {\n return this[rawDataSymbol].reason;\n }\n};\n__decorate([\n Enumerable(false)\n], HelixWarning.prototype, \"_client\", void 0);\nHelixWarning = __decorate([\n rtfm('api', 'HelixWarning', 'userId')\n], HelixWarning);\nexport { HelixWarning };\n", "import { __decorate } from \"tslib\";\nimport { createBroadcasterQuery } from '@twurple/api-call';\nimport { extractUserId, rtfm } from '@twurple/common';\nimport { createGetByIdsQuery } from '../../interfaces/endpoints/generic.external.js';\nimport { createPollBody, createPollEndBody } from '../../interfaces/endpoints/poll.external.js';\nimport { HelixPaginatedRequest } from '../../utils/pagination/HelixPaginatedRequest.js';\nimport { createPaginatedResult } from '../../utils/pagination/HelixPaginatedResult.js';\nimport { createPaginationQuery } from '../../utils/pagination/HelixPagination.js';\nimport { BaseApi } from '../BaseApi.js';\nimport { HelixPoll } from './HelixPoll.js';\n/**\n * The Helix API methods that deal with polls.\n *\n * Can be accessed using `client.polls` on an {@link ApiClient} instance.\n *\n * ## Example\n * ```ts\n * const api = new ApiClient({ authProvider });\n * const { data: polls } = await api.helix.polls.getPolls('61369223');\n * ```\n *\n * @meta category helix\n * @meta categorizedTitle Polls\n */\nlet HelixPollApi = class HelixPollApi extends BaseApi {\n /**\n * Gets a list of polls for the given broadcaster.\n *\n * @param broadcaster The broadcaster to get polls for.\n * @param pagination\n *\n * @expandParams\n */\n async getPolls(broadcaster, pagination) {\n const result = await this._client.callApi({\n type: 'helix',\n url: 'polls',\n userId: extractUserId(broadcaster),\n scopes: ['channel:read:polls', 'channel:manage:polls'],\n query: {\n ...createBroadcasterQuery(broadcaster),\n ...createPaginationQuery(pagination),\n },\n });\n return createPaginatedResult(result, HelixPoll, this._client);\n }\n /**\n * Creates a paginator for polls for the given broadcaster.\n *\n * @param broadcaster The broadcaster to get polls for.\n */\n getPollsPaginated(broadcaster) {\n return new HelixPaginatedRequest({\n url: 'polls',\n userId: extractUserId(broadcaster),\n scopes: ['channel:read:polls', 'channel:manage:polls'],\n query: createBroadcasterQuery(broadcaster),\n }, this._client, data => new HelixPoll(data, this._client), 20);\n }\n /**\n * Gets polls by IDs.\n *\n * @param broadcaster The broadcaster to get the polls for.\n * @param ids The IDs of the polls.\n */\n async getPollsByIds(broadcaster, ids) {\n if (!ids.length) {\n return [];\n }\n const result = await this._client.callApi({\n type: 'helix',\n url: 'polls',\n userId: extractUserId(broadcaster),\n scopes: ['channel:read:polls', 'channel:manage:polls'],\n query: createGetByIdsQuery(broadcaster, ids),\n });\n return result.data.map(data => new HelixPoll(data, this._client));\n }\n /**\n * Gets a poll by ID.\n *\n * @param broadcaster The broadcaster to get the poll for.\n * @param id The ID of the poll.\n */\n async getPollById(broadcaster, id) {\n const polls = await this.getPollsByIds(broadcaster, [id]);\n return polls.length ? polls[0] : null;\n }\n /**\n * Creates a new poll.\n *\n * @param broadcaster The broadcaster to create the poll for.\n * @param data\n *\n * @expandParams\n */\n async createPoll(broadcaster, data) {\n const result = await this._client.callApi({\n type: 'helix',\n url: 'polls',\n method: 'POST',\n userId: extractUserId(broadcaster),\n scopes: ['channel:manage:polls'],\n jsonBody: createPollBody(broadcaster, data),\n });\n return new HelixPoll(result.data[0], this._client);\n }\n /**\n * Ends a poll.\n *\n * @param broadcaster The broadcaster to end the poll for.\n * @param id The ID of the poll to end.\n * @param showResult Whether to allow the result to be viewed publicly.\n */\n async endPoll(broadcaster, id, showResult = true) {\n const result = await this._client.callApi({\n type: 'helix',\n url: 'polls',\n method: 'PATCH',\n userId: extractUserId(broadcaster),\n scopes: ['channel:manage:polls'],\n jsonBody: createPollEndBody(broadcaster, id, showResult),\n });\n return new HelixPoll(result.data[0], this._client);\n }\n};\nHelixPollApi = __decorate([\n rtfm('api', 'HelixPollApi')\n], HelixPollApi);\nexport { HelixPollApi };\n", "import { extractUserId } from '@twurple/common';\n/** @internal */\nexport function createPollBody(broadcaster, data) {\n return {\n broadcaster_id: extractUserId(broadcaster),\n title: data.title,\n choices: data.choices.map(title => ({ title })),\n duration: data.duration,\n channel_points_voting_enabled: data.channelPointsPerVote != null,\n channel_points_per_vote: data.channelPointsPerVote ?? 0,\n };\n}\n/** @internal */\nexport function createPollEndBody(broadcaster, id, showResult) {\n return {\n broadcaster_id: extractUserId(broadcaster),\n id,\n status: showResult ? 'TERMINATED' : 'ARCHIVED',\n };\n}\n", "import { __decorate } from \"tslib\";\nimport { Enumerable } from '@d-fischer/shared-utils';\nimport { checkRelationAssertion, DataObject, rawDataSymbol, rtfm } from '@twurple/common';\nimport { HelixPollChoice } from './HelixPollChoice.js';\n/**\n * A channel poll.\n */\nlet HelixPoll = class HelixPoll extends DataObject {\n /** @internal */ _client;\n /** @internal */\n constructor(data, client) {\n super(data);\n this._client = client;\n }\n /**\n * The ID of the poll.\n */\n get id() {\n return this[rawDataSymbol].id;\n }\n /**\n * The ID of the broadcaster.\n */\n get broadcasterId() {\n return this[rawDataSymbol].broadcaster_id;\n }\n /**\n * The name of the broadcaster.\n */\n get broadcasterName() {\n return this[rawDataSymbol].broadcaster_login;\n }\n /**\n * The display name of the broadcaster.\n */\n get broadcasterDisplayName() {\n return this[rawDataSymbol].broadcaster_name;\n }\n /**\n * Gets more information about the broadcaster.\n */\n async getBroadcaster() {\n return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].broadcaster_id));\n }\n /**\n * The title of the poll.\n */\n get title() {\n return this[rawDataSymbol].title;\n }\n /**\n * Whether voting with channel points is enabled for the poll.\n */\n get isChannelPointsVotingEnabled() {\n return this[rawDataSymbol].channel_points_voting_enabled;\n }\n /**\n * The amount of channel points that a vote costs.\n */\n get channelPointsPerVote() {\n return this[rawDataSymbol].channel_points_per_vote;\n }\n /**\n * The status of the poll.\n */\n get status() {\n return this[rawDataSymbol].status;\n }\n /**\n * The duration of the poll, in seconds.\n */\n get durationInSeconds() {\n return this[rawDataSymbol].duration;\n }\n /**\n * The date when the poll started.\n */\n get startDate() {\n return new Date(this[rawDataSymbol].started_at);\n }\n /**\n * The date when the poll ended or will end.\n */\n get endDate() {\n return new Date(this.startDate.getTime() + this[rawDataSymbol].duration * 1000);\n }\n /**\n * The choices of the poll.\n */\n get choices() {\n return this[rawDataSymbol].choices.map(data => new HelixPollChoice(data));\n }\n};\n__decorate([\n Enumerable(false)\n], HelixPoll.prototype, \"_client\", void 0);\nHelixPoll = __decorate([\n rtfm('api', 'HelixPoll', 'id')\n], HelixPoll);\nexport { HelixPoll };\n", "import { __decorate } from \"tslib\";\nimport { DataObject, rawDataSymbol, rtfm } from '@twurple/common';\n/**\n * A choice in a channel poll.\n */\nlet HelixPollChoice = class HelixPollChoice extends DataObject {\n /**\n * The ID of the choice.\n */\n get id() {\n return this[rawDataSymbol].id;\n }\n /**\n * The title of the choice.\n */\n get title() {\n return this[rawDataSymbol].title;\n }\n /**\n * The total votes the choice received.\n */\n get totalVotes() {\n return this[rawDataSymbol].votes;\n }\n /**\n * The votes the choice received by spending channel points.\n */\n get channelPointsVotes() {\n return this[rawDataSymbol].channel_points_votes;\n }\n};\nHelixPollChoice = __decorate([\n rtfm('api', 'HelixPollChoice', 'id')\n], HelixPollChoice);\nexport { HelixPollChoice };\n", "import { __decorate } from \"tslib\";\nimport { createBroadcasterQuery } from '@twurple/api-call';\nimport { extractUserId, rtfm } from '@twurple/common';\nimport { createGetByIdsQuery } from '../../interfaces/endpoints/generic.external.js';\nimport { createEndPredictionBody, createPredictionBody, } from '../../interfaces/endpoints/prediction.external.js';\nimport { HelixPaginatedRequest } from '../../utils/pagination/HelixPaginatedRequest.js';\nimport { createPaginatedResult } from '../../utils/pagination/HelixPaginatedResult.js';\nimport { createPaginationQuery } from '../../utils/pagination/HelixPagination.js';\nimport { BaseApi } from '../BaseApi.js';\nimport { HelixPrediction } from './HelixPrediction.js';\n/**\n * The Helix API methods that deal with predictions.\n *\n * Can be accessed using `client.predictions` on an {@link ApiClient} instance.\n *\n * ## Example\n * ```ts\n * const api = new ApiClient({ authProvider });\n * const { data: predictions } = await api.helix.predictions.getPredictions('61369223');\n * ```\n *\n * @meta category helix\n * @meta categorizedTitle Predictions\n */\nlet HelixPredictionApi = class HelixPredictionApi extends BaseApi {\n /**\n * Gets a list of predictions for the given broadcaster.\n *\n * @param broadcaster The broadcaster to get predictions for.\n * @param pagination\n *\n * @expandParams\n */\n async getPredictions(broadcaster, pagination) {\n const result = await this._client.callApi({\n type: 'helix',\n url: 'predictions',\n userId: extractUserId(broadcaster),\n scopes: ['channel:read:predictions'],\n query: {\n ...createBroadcasterQuery(broadcaster),\n ...createPaginationQuery(pagination),\n },\n });\n return createPaginatedResult(result, HelixPrediction, this._client);\n }\n /**\n * Creates a paginator for predictions for the given broadcaster.\n *\n * @param broadcaster The broadcaster to get predictions for.\n */\n getPredictionsPaginated(broadcaster) {\n return new HelixPaginatedRequest({\n url: 'predictions',\n userId: extractUserId(broadcaster),\n scopes: ['channel:read:predictions'],\n query: createBroadcasterQuery(broadcaster),\n }, this._client, data => new HelixPrediction(data, this._client), 20);\n }\n /**\n * Gets predictions by IDs.\n *\n * @param broadcaster The broadcaster to get the predictions for.\n * @param ids The IDs of the predictions.\n */\n async getPredictionsByIds(broadcaster, ids) {\n if (!ids.length) {\n return [];\n }\n const result = await this._client.callApi({\n type: 'helix',\n url: 'predictions',\n userId: extractUserId(broadcaster),\n scopes: ['channel:read:predictions'],\n query: createGetByIdsQuery(broadcaster, ids),\n });\n return result.data.map(data => new HelixPrediction(data, this._client));\n }\n /**\n * Gets a prediction by ID.\n *\n * @param broadcaster The broadcaster to get the prediction for.\n * @param id The ID of the prediction.\n */\n async getPredictionById(broadcaster, id) {\n const predictions = await this.getPredictionsByIds(broadcaster, [id]);\n return predictions.length ? predictions[0] : null;\n }\n /**\n * Creates a new prediction.\n *\n * @param broadcaster The broadcaster to create the prediction for.\n * @param data\n *\n * @expandParams\n */\n async createPrediction(broadcaster, data) {\n const result = await this._client.callApi({\n type: 'helix',\n url: 'predictions',\n method: 'POST',\n userId: extractUserId(broadcaster),\n scopes: ['channel:manage:predictions'],\n jsonBody: createPredictionBody(broadcaster, data),\n });\n return new HelixPrediction(result.data[0], this._client);\n }\n /**\n * Locks a prediction.\n *\n * @param broadcaster The broadcaster to lock the prediction for.\n * @param id The ID of the prediction to lock.\n */\n async lockPrediction(broadcaster, id) {\n return await this._endPrediction(broadcaster, id, 'LOCKED');\n }\n /**\n * Resolves a prediction.\n *\n * @param broadcaster The broadcaster to resolve the prediction for.\n * @param id The ID of the prediction to resolve.\n * @param outcomeId The ID of the winning outcome.\n */\n async resolvePrediction(broadcaster, id, outcomeId) {\n return await this._endPrediction(broadcaster, id, 'RESOLVED', outcomeId);\n }\n /**\n * Cancels a prediction.\n *\n * @param broadcaster The broadcaster to cancel the prediction for.\n * @param id The ID of the prediction to cancel.\n */\n async cancelPrediction(broadcaster, id) {\n return await this._endPrediction(broadcaster, id, 'CANCELED');\n }\n async _endPrediction(broadcaster, id, status, outcomeId) {\n const result = await this._client.callApi({\n type: 'helix',\n url: 'predictions',\n method: 'PATCH',\n userId: extractUserId(broadcaster),\n scopes: ['channel:manage:predictions'],\n jsonBody: createEndPredictionBody(broadcaster, id, status, outcomeId),\n });\n return new HelixPrediction(result.data[0], this._client);\n }\n};\nHelixPredictionApi = __decorate([\n rtfm('api', 'HelixPredictionApi')\n], HelixPredictionApi);\nexport { HelixPredictionApi };\n", "import { extractUserId } from '@twurple/common';\n/** @internal */\nexport function createPredictionBody(broadcaster, data) {\n return {\n broadcaster_id: extractUserId(broadcaster),\n title: data.title,\n outcomes: data.outcomes.map(title => ({ title })),\n prediction_window: data.autoLockAfter,\n };\n}\n/** @internal */\nexport function createEndPredictionBody(broadcaster, id, status, outcomeId) {\n return {\n broadcaster_id: extractUserId(broadcaster),\n id,\n status,\n winning_outcome_id: outcomeId,\n };\n}\n", "import { __decorate } from \"tslib\";\nimport { Enumerable } from '@d-fischer/shared-utils';\nimport { checkRelationAssertion, DataObject, HellFreezesOverError, rawDataSymbol, rtfm } from '@twurple/common';\nimport { HelixPredictionOutcome } from './HelixPredictionOutcome.js';\n/**\n * A channel prediction.\n */\nlet HelixPrediction = class HelixPrediction extends DataObject {\n /** @internal */ _client;\n /** @internal */\n constructor(data, client) {\n super(data);\n this._client = client;\n }\n /**\n * The ID of the prediction.\n */\n get id() {\n return this[rawDataSymbol].id;\n }\n /**\n * The ID of the broadcaster.\n */\n get broadcasterId() {\n return this[rawDataSymbol].broadcaster_id;\n }\n /**\n * The name of the broadcaster.\n */\n get broadcasterName() {\n return this[rawDataSymbol].broadcaster_login;\n }\n /**\n * The display name of the broadcaster.\n */\n get broadcasterDisplayName() {\n return this[rawDataSymbol].broadcaster_name;\n }\n /**\n * Gets more information about the broadcaster.\n */\n async getBroadcaster() {\n return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].broadcaster_id));\n }\n /**\n * The title of the prediction.\n */\n get title() {\n return this[rawDataSymbol].title;\n }\n /**\n * The status of the prediction.\n */\n get status() {\n return this[rawDataSymbol].status;\n }\n /**\n * The time after which the prediction will be automatically locked, in seconds from creation.\n */\n get autoLockAfter() {\n return this[rawDataSymbol].prediction_window;\n }\n /**\n * The date when the prediction started.\n */\n get creationDate() {\n return new Date(this[rawDataSymbol].created_at);\n }\n /**\n * The date when the prediction ended, or null if it didn't end yet.\n */\n get endDate() {\n return this[rawDataSymbol].ended_at ? new Date(this[rawDataSymbol].ended_at) : null;\n }\n /**\n * The date when the prediction was locked, or null if it wasn't locked yet.\n */\n get lockDate() {\n return this[rawDataSymbol].locked_at ? new Date(this[rawDataSymbol].locked_at) : null;\n }\n /**\n * The possible outcomes of the prediction.\n */\n get outcomes() {\n return this[rawDataSymbol].outcomes.map(data => new HelixPredictionOutcome(data, this._client));\n }\n /**\n * The ID of the winning outcome, or null if the prediction is currently running or was canceled.\n */\n get winningOutcomeId() {\n // can apparently be empty string\n // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing\n return this[rawDataSymbol].winning_outcome_id || null;\n }\n /**\n * The winning outcome, or null if the prediction is currently running or was canceled.\n */\n get winningOutcome() {\n if (!this[rawDataSymbol].winning_outcome_id) {\n return null;\n }\n const found = this[rawDataSymbol].outcomes.find(o => o.id === this[rawDataSymbol].winning_outcome_id);\n if (!found) {\n throw new HellFreezesOverError('Winning outcome not found in outcomes array');\n }\n return new HelixPredictionOutcome(found, this._client);\n }\n};\n__decorate([\n Enumerable(false)\n], HelixPrediction.prototype, \"_client\", void 0);\nHelixPrediction = __decorate([\n rtfm('api', 'HelixPrediction', 'id')\n], HelixPrediction);\nexport { HelixPrediction };\n", "import { __decorate } from \"tslib\";\nimport { Enumerable } from '@d-fischer/shared-utils';\nimport { DataObject, rawDataSymbol, rtfm } from '@twurple/common';\nimport { HelixPredictor } from './HelixPredictor.js';\n/**\n * A possible outcome in a channel prediction.\n */\nlet HelixPredictionOutcome = class HelixPredictionOutcome extends DataObject {\n /** @internal */ _client;\n /** @internal */\n constructor(data, client) {\n super(data);\n this._client = client;\n }\n /**\n * The ID of the outcome.\n */\n get id() {\n return this[rawDataSymbol].id;\n }\n /**\n * The title of the outcome.\n */\n get title() {\n return this[rawDataSymbol].title;\n }\n /**\n * The number of users that guessed the outcome.\n */\n get users() {\n return this[rawDataSymbol].users;\n }\n /**\n * The total number of channel points that were spent on guessing the outcome.\n */\n get totalChannelPoints() {\n return this[rawDataSymbol].channel_points;\n }\n /**\n * The color of the outcome.\n */\n get color() {\n return this[rawDataSymbol].color;\n }\n /**\n * The top predictors of the outcome.\n */\n get topPredictors() {\n return this[rawDataSymbol].top_predictors?.map(data => new HelixPredictor(data, this._client)) ?? [];\n }\n};\n__decorate([\n Enumerable(false)\n], HelixPredictionOutcome.prototype, \"_client\", void 0);\nHelixPredictionOutcome = __decorate([\n rtfm('api', 'HelixPredictionOutcome', 'id')\n], HelixPredictionOutcome);\nexport { HelixPredictionOutcome };\n", "import { __decorate } from \"tslib\";\nimport { Enumerable } from '@d-fischer/shared-utils';\nimport { DataObject, rawDataSymbol, rtfm } from '@twurple/common';\n/**\n * A user that took part in a prediction.\n */\nlet HelixPredictor = class HelixPredictor extends DataObject {\n /** @internal */ _client;\n /** @internal */\n constructor(data, client) {\n super(data);\n this._client = client;\n }\n /**\n * The user ID of the predictor.\n */\n get userId() {\n return this[rawDataSymbol].user_id;\n }\n /**\n * The name of the predictor.\n */\n get userName() {\n return this[rawDataSymbol].user_login;\n }\n /**\n * The display name of the predictor.\n */\n get userDisplayName() {\n return this[rawDataSymbol].user_name;\n }\n /**\n * Gets more information about the predictor.\n */\n async getUser() {\n return await this._client.users.getUserById(this[rawDataSymbol].user_id);\n }\n /**\n * The amount of channel points the predictor used for the prediction.\n */\n get channelPointsUsed() {\n return this[rawDataSymbol].channel_points_used;\n }\n /**\n * The amount of channel points the predictor won for the prediction, or null if the prediction is not resolved yet, was cancelled or lost.\n */\n get channelPointsWon() {\n return this[rawDataSymbol].channel_points_won;\n }\n};\n__decorate([\n Enumerable(false)\n], HelixPredictor.prototype, \"_client\", void 0);\nHelixPredictor = __decorate([\n rtfm('api', 'HelixPredictor', 'userId')\n], HelixPredictor);\nexport { HelixPredictor };\n", "import { __decorate } from \"tslib\";\nimport { createBroadcasterQuery } from '@twurple/api-call';\nimport { extractUserId, rtfm } from '@twurple/common';\nimport { createRaidStartQuery } from '../../interfaces/endpoints/raid.external.js';\nimport { BaseApi } from '../BaseApi.js';\nimport { HelixRaid } from './HelixRaid.js';\n/**\n * The Helix API methods that deal with raids.\n *\n * Can be accessed using `client.raids` on an {@link ApiClient} instance.\n *\n * ## Example\n * ```ts\n * const api = new ApiClient({ authProvider });\n * const raid = await api.raids.startRaid('125328655', '61369223');\n * ```\n *\n * @meta category helix\n * @meta categorizedTitle Raids\n */\nlet HelixRaidApi = class HelixRaidApi extends BaseApi {\n /**\n * Initiate a raid from a live broadcaster to another live broadcaster.\n *\n * @param from The raiding broadcaster.\n * @param to The raid target.\n */\n async startRaid(from, to) {\n const result = await this._client.callApi({\n type: 'helix',\n url: 'raids',\n method: 'POST',\n userId: extractUserId(from),\n scopes: ['channel:manage:raids'],\n query: createRaidStartQuery(from, to),\n });\n return new HelixRaid(result.data[0]);\n }\n /**\n * Cancels an initiated raid.\n *\n * @param from The raiding broadcaster.\n */\n async cancelRaid(from) {\n await this._client.callApi({\n type: 'helix',\n url: 'raids',\n method: 'DELETE',\n userId: extractUserId(from),\n scopes: ['channel:manage:raids'],\n query: createBroadcasterQuery(from),\n });\n }\n};\nHelixRaidApi = __decorate([\n rtfm('api', 'HelixRaidApi')\n], HelixRaidApi);\nexport { HelixRaidApi };\n", "import { extractUserId } from '@twurple/common';\n/** @internal */\nexport function createRaidStartQuery(from, to) {\n return {\n from_broadcaster_id: extractUserId(from),\n to_broadcaster_id: extractUserId(to),\n };\n}\n", "import { __decorate } from \"tslib\";\nimport { DataObject, rawDataSymbol, rtfm } from '@twurple/common';\n/**\n * A result of a successful raid initiation.\n */\nlet HelixRaid = class HelixRaid extends DataObject {\n /**\n * The date when the raid was initiated.\n */\n get creationDate() {\n return new Date(this[rawDataSymbol].created_at);\n }\n /**\n * Whether the raid target channel is intended for mature audiences.\n */\n get targetIsMature() {\n return this[rawDataSymbol].is_mature;\n }\n};\nHelixRaid = __decorate([\n rtfm('api', 'HelixRaid')\n], HelixRaid);\nexport { HelixRaid };\n", "import { createBroadcasterQuery } from '@twurple/api-call';\nimport { extractUserId } from '@twurple/common';\nimport { createGetByIdsQuery } from '../../interfaces/endpoints/generic.external.js';\nimport { createScheduleQuery, createScheduleSegmentBody, createScheduleSegmentModifyQuery, createScheduleSegmentUpdateBody, createScheduleSettingsUpdateQuery, } from '../../interfaces/endpoints/schedule.external.js';\nimport { createPaginationQuery } from '../../utils/pagination/HelixPagination.js';\nimport { BaseApi } from '../BaseApi.js';\nimport { HelixPaginatedScheduleSegmentRequest } from './HelixPaginatedScheduleSegmentRequest.js';\nimport { HelixSchedule } from './HelixSchedule.js';\nimport { HelixScheduleSegment } from './HelixScheduleSegment.js';\n/**\n * The Helix API methods that deal with schedules.\n *\n * Can be accessed using `client.schedule` on an {@link ApiClient} instance.\n *\n * ## Example\n * ```ts\n * const api = new ApiClient({ authProvider });\n * const { data: schedule } = await api.helix.schedule.getSchedule('61369223');\n * ```\n *\n * @meta category helix\n * @meta categorizedTitle Schedule\n */\nexport class HelixScheduleApi extends BaseApi {\n /**\n * Gets the schedule for a given broadcaster.\n *\n * @param broadcaster The broadcaster to get the schedule of.\n * @param filter\n *\n * @expandParams\n */\n async getSchedule(broadcaster, filter) {\n const result = await this._client.callApi({\n type: 'helix',\n url: 'schedule',\n userId: extractUserId(broadcaster),\n query: {\n ...createScheduleQuery(broadcaster, filter),\n ...createPaginationQuery(filter),\n },\n });\n return {\n data: new HelixSchedule(result.data, this._client),\n cursor: result.pagination.cursor,\n };\n }\n /**\n * Creates a paginator for schedule segments for a given broadcaster.\n *\n * @param broadcaster The broadcaster to get the schedule segments of.\n * @param filter\n *\n * @expandParams\n */\n getScheduleSegmentsPaginated(broadcaster, filter) {\n return new HelixPaginatedScheduleSegmentRequest(broadcaster, this._client, filter);\n }\n /**\n * Gets a set of schedule segments by IDs.\n *\n * @param broadcaster The broadcaster to get schedule segments of.\n * @param ids The IDs of the schedule segments.\n */\n async getScheduleSegmentsByIds(broadcaster, ids) {\n const result = await this._client.callApi({\n type: 'helix',\n url: 'schedule',\n userId: extractUserId(broadcaster),\n query: createGetByIdsQuery(broadcaster, ids),\n });\n return result.data.segments?.map(data => new HelixScheduleSegment(data, this._client)) ?? [];\n }\n /**\n * Gets a single schedule segment by ID.\n *\n * @param broadcaster The broadcaster to get a schedule segment of.\n * @param id The ID of the schedule segment.\n */\n async getScheduleSegmentById(broadcaster, id) {\n const segments = await this.getScheduleSegmentsByIds(broadcaster, [id]);\n return segments.length ? segments[0] : null;\n }\n /**\n * Gets the schedule for a given broadcaster in iCal format.\n *\n * @param broadcaster The broadcaster to get the schedule for.\n */\n async getScheduleAsIcal(broadcaster) {\n return await this._client.callApi({\n type: 'helix',\n url: 'schedule/icalendar',\n query: createBroadcasterQuery(broadcaster),\n });\n }\n /**\n * Updates the schedule settings of a given broadcaster.\n *\n * @param broadcaster The broadcaster to update the schedule settings for.\n * @param settings\n *\n * @expandParams\n */\n async updateScheduleSettings(broadcaster, settings) {\n await this._client.callApi({\n type: 'helix',\n url: 'schedule/settings',\n method: 'PATCH',\n userId: extractUserId(broadcaster),\n scopes: ['channel:manage:schedule'],\n query: createScheduleSettingsUpdateQuery(broadcaster, settings),\n });\n }\n /**\n * Creates a new segment in a given broadcaster's schedule.\n *\n * @param broadcaster The broadcaster to create a new schedule segment for.\n * @param data\n *\n * @expandParams\n */\n async createScheduleSegment(broadcaster, data) {\n const result = await this._client.callApi({\n type: 'helix',\n url: 'schedule/segment',\n method: 'POST',\n userId: extractUserId(broadcaster),\n scopes: ['channel:manage:schedule'],\n query: createBroadcasterQuery(broadcaster),\n jsonBody: createScheduleSegmentBody(data),\n });\n return new HelixScheduleSegment(result.data.segments[0], this._client);\n }\n /**\n * Updates a segment in a given broadcaster's schedule.\n *\n * @param broadcaster The broadcaster to create a new schedule segment for.\n * @param segmentId The ID of the segment to update.\n * @param data\n *\n * @expandParams\n */\n async updateScheduleSegment(broadcaster, segmentId, data) {\n const result = await this._client.callApi({\n type: 'helix',\n url: 'schedule/segment',\n method: 'PATCH',\n userId: extractUserId(broadcaster),\n scopes: ['channel:manage:schedule'],\n query: createScheduleSegmentModifyQuery(broadcaster, segmentId),\n jsonBody: createScheduleSegmentUpdateBody(data),\n });\n return new HelixScheduleSegment(result.data.segments[0], this._client);\n }\n /**\n * Deletes a segment in a given broadcaster's schedule.\n *\n * @param broadcaster The broadcaster to create a new schedule segment for.\n * @param segmentId The ID of the segment to update.\n */\n async deleteScheduleSegment(broadcaster, segmentId) {\n await this._client.callApi({\n type: 'helix',\n url: 'schedule/segment',\n method: 'DELETE',\n userId: extractUserId(broadcaster),\n scopes: ['channel:manage:schedule'],\n query: createScheduleSegmentModifyQuery(broadcaster, segmentId),\n });\n }\n}\n", "import { extractUserId } from '@twurple/common';\n/** @internal */\nexport function createScheduleQuery(broadcaster, filter) {\n return {\n broadcaster_id: extractUserId(broadcaster),\n start_time: filter?.startDate,\n utc_offset: filter?.utcOffset?.toString(),\n };\n}\n/** @internal */\nexport function createScheduleSettingsUpdateQuery(broadcaster, settings) {\n if (settings.vacation) {\n return {\n broadcaster_id: extractUserId(broadcaster),\n is_vacation_enabled: 'true',\n vacation_start_time: settings.vacation.startDate,\n vacation_end_time: settings.vacation.endDate,\n timezone: settings.vacation.timezone,\n };\n }\n return {\n broadcaster_id: extractUserId(broadcaster),\n is_vacation_enabled: 'false',\n };\n}\n/** @internal */\nexport function createScheduleSegmentBody(data) {\n return {\n start_time: data.startDate,\n timezone: data.timezone,\n is_recurring: data.isRecurring,\n duration: data.duration,\n category_id: data.categoryId,\n title: data.title,\n };\n}\n/** @internal */\nexport function createScheduleSegmentModifyQuery(broadcaster, segmentId) {\n return {\n broadcaster_id: extractUserId(broadcaster),\n id: segmentId,\n };\n}\n/** @internal */\nexport function createScheduleSegmentUpdateBody(data) {\n return {\n start_time: data.startDate,\n timezone: data.timezone,\n is_canceled: data.isCanceled,\n duration: data.duration,\n category_id: data.categoryId,\n title: data.title,\n };\n}\n", "import { __decorate } from \"tslib\";\nimport { rtfm } from '@twurple/common';\nimport { createScheduleQuery, } from '../../interfaces/endpoints/schedule.external.js';\nimport { HelixPaginatedRequest } from '../../utils/pagination/HelixPaginatedRequest.js';\nimport { HelixScheduleSegment } from './HelixScheduleSegment.js';\n/**\n * A paginator specifically for schedule segments.\n */\nlet HelixPaginatedScheduleSegmentRequest = class HelixPaginatedScheduleSegmentRequest extends HelixPaginatedRequest {\n /** @internal */\n constructor(broadcaster, client, filter) {\n super({\n url: 'schedule',\n query: createScheduleQuery(broadcaster, filter),\n }, client, data => new HelixScheduleSegment(data, client), 25);\n }\n // sadly, this hack is necessary to work around the weird data model of schedules\n // while still keeping the pagination code as generic as possible\n /** @internal */\n async _fetchData(additionalOptions = {}) {\n const origData = (await super._fetchData(additionalOptions));\n return {\n data: origData.data.segments ?? [],\n pagination: origData.pagination,\n };\n }\n};\nHelixPaginatedScheduleSegmentRequest = __decorate([\n rtfm('api', 'HelixPaginatedScheduleSegmentRequest')\n], HelixPaginatedScheduleSegmentRequest);\nexport { HelixPaginatedScheduleSegmentRequest };\n", "import { __decorate } from \"tslib\";\nimport { Enumerable, mapNullable } from '@d-fischer/shared-utils';\nimport { DataObject, rawDataSymbol, rtfm } from '@twurple/common';\n/**\n * A segment of a schedule.\n */\nlet HelixScheduleSegment = class HelixScheduleSegment extends DataObject {\n /** @internal */ _client;\n /** @internal */\n constructor(data, client) {\n super(data);\n this._client = client;\n }\n /**\n * The ID of the segment.\n */\n get id() {\n return this[rawDataSymbol].id;\n }\n /**\n * The date when the segment starts.\n */\n get startDate() {\n return new Date(this[rawDataSymbol].start_time);\n }\n /**\n * The date when the segment ends.\n */\n get endDate() {\n return new Date(this[rawDataSymbol].end_time);\n }\n /**\n * The title of the segment.\n */\n get title() {\n return this[rawDataSymbol].title;\n }\n /**\n * The date up to which the segment is canceled.\n */\n get cancelEndDate() {\n return mapNullable(this[rawDataSymbol].canceled_until, v => new Date(v));\n }\n /**\n * The ID of the category the segment is scheduled for, or null if no category is specified.\n */\n get categoryId() {\n return this[rawDataSymbol].category?.id ?? null;\n }\n /**\n * The name of the category the segment is scheduled for, or null if no category is specified.\n */\n get categoryName() {\n return this[rawDataSymbol].category?.name ?? null;\n }\n /**\n * Gets more information about the category the segment is scheduled for, or null if no category is specified.\n */\n async getCategory() {\n const categoryId = this[rawDataSymbol].category?.id;\n return categoryId ? await this._client.games.getGameById(categoryId) : null;\n }\n /**\n * Whether the segment is recurring every week.\n */\n get isRecurring() {\n return this[rawDataSymbol].is_recurring;\n }\n};\n__decorate([\n Enumerable(false)\n], HelixScheduleSegment.prototype, \"_client\", void 0);\nHelixScheduleSegment = __decorate([\n rtfm('api', 'HelixScheduleSegment', 'id')\n], HelixScheduleSegment);\nexport { HelixScheduleSegment };\n", "import { __decorate } from \"tslib\";\nimport { Enumerable } from '@d-fischer/shared-utils';\nimport { checkRelationAssertion, DataObject, rawDataSymbol, rtfm } from '@twurple/common';\nimport { HelixScheduleSegment } from './HelixScheduleSegment.js';\n/**\n * A schedule of a channel.\n */\nlet HelixSchedule = class HelixSchedule extends DataObject {\n /** @internal */ _client;\n /** @internal */\n constructor(data, client) {\n super(data);\n this._client = client;\n }\n /**\n * The segments of the schedule.\n */\n get segments() {\n return this[rawDataSymbol].segments?.map(data => new HelixScheduleSegment(data, this._client)) ?? [];\n }\n /**\n * The ID of the broadcaster.\n */\n get broadcasterId() {\n return this[rawDataSymbol].broadcaster_id;\n }\n /**\n * The name of the broadcaster.\n */\n get broadcasterName() {\n return this[rawDataSymbol].broadcaster_login;\n }\n /**\n * The display name of the broadcaster.\n */\n get broadcasterDisplayName() {\n return this[rawDataSymbol].broadcaster_name;\n }\n /**\n * Gets more information about the broadcaster.\n */\n async getBroadcaster() {\n return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].broadcaster_id));\n }\n /**\n * The date when the current vacation started, or null if the schedule is not in vacation mode.\n */\n get vacationStartDate() {\n const timestamp = this[rawDataSymbol].vacation?.start_time;\n return timestamp ? new Date(timestamp) : null;\n }\n /**\n * The date when the current vacation ends, or null if the schedule is not in vacation mode.\n */\n get vacationEndDate() {\n const timestamp = this[rawDataSymbol].vacation?.end_time;\n return timestamp ? new Date(timestamp) : null;\n }\n};\n__decorate([\n Enumerable(false)\n], HelixSchedule.prototype, \"_client\", void 0);\nHelixSchedule = __decorate([\n rtfm('api', 'HelixSchedule', 'broadcasterId')\n], HelixSchedule);\nexport { HelixSchedule };\n", "import { __decorate } from \"tslib\";\nimport { rtfm } from '@twurple/common';\nimport { createSearchChannelsQuery, } from '../../interfaces/endpoints/search.external.js';\nimport { HelixPaginatedRequest } from '../../utils/pagination/HelixPaginatedRequest.js';\nimport { createPaginatedResult } from '../../utils/pagination/HelixPaginatedResult.js';\nimport { createPaginationQuery } from '../../utils/pagination/HelixPagination.js';\nimport { BaseApi } from '../BaseApi.js';\nimport { HelixGame } from '../game/HelixGame.js';\nimport { HelixChannelSearchResult } from './HelixChannelSearchResult.js';\n/**\n * The Helix API methods that run searches.\n *\n * Can be accessed using `client.search` on an {@link ApiClient} instance.\n *\n * ## Example\n * ```ts\n * const api = new ApiClient({ authProvider });\n * const channels = await api.search.searchChannels('pear');\n * ```\n *\n * @meta category helix\n * @meta categorizedTitle Search\n */\nlet HelixSearchApi = class HelixSearchApi extends BaseApi {\n /**\n * Search categories/games for an exact or partial match.\n *\n * @param query The search term.\n * @param pagination\n *\n * @expandParams\n */\n async searchCategories(query, pagination) {\n const result = await this._client.callApi({\n type: 'helix',\n url: 'search/categories',\n query: {\n query,\n ...createPaginationQuery(pagination),\n },\n });\n return createPaginatedResult(result, HelixGame, this._client);\n }\n /**\n * Creates a paginator for a category/game search.\n *\n * @param query The search term.\n */\n searchCategoriesPaginated(query) {\n return new HelixPaginatedRequest({\n url: 'search/categories',\n query: {\n query,\n },\n }, this._client, data => new HelixGame(data, this._client));\n }\n /**\n * Search channels for an exact or partial match.\n *\n * @param query The search term.\n * @param filter\n *\n * @expandParams\n */\n async searchChannels(query, filter = {}) {\n const result = await this._client.callApi({\n type: 'helix',\n url: 'search/channels',\n query: {\n ...createSearchChannelsQuery(query, filter),\n ...createPaginationQuery(filter),\n },\n });\n return createPaginatedResult(result, HelixChannelSearchResult, this._client);\n }\n /**\n * Creates a paginator for a channel search.\n *\n * @param query The search term.\n * @param filter\n *\n * @expandParams\n */\n searchChannelsPaginated(query, filter = {}) {\n return new HelixPaginatedRequest({\n url: 'search/channels',\n query: createSearchChannelsQuery(query, filter),\n }, this._client, data => new HelixChannelSearchResult(data, this._client));\n }\n};\nHelixSearchApi = __decorate([\n rtfm('api', 'HelixSearchApi')\n], HelixSearchApi);\nexport { HelixSearchApi };\n", "/** @internal */\nexport function createSearchChannelsQuery(query, filter) {\n return {\n query,\n live_only: filter.liveOnly?.toString(),\n };\n}\n", "import { __decorate } from \"tslib\";\nimport { Enumerable } from '@d-fischer/shared-utils';\nimport { checkRelationAssertion, DataObject, rawDataSymbol, rtfm } from '@twurple/common';\n/**\n * The result of a channel search.\n */\nlet HelixChannelSearchResult = class HelixChannelSearchResult extends DataObject {\n /** @internal */ _client;\n /** @internal */\n constructor(data, client) {\n super(data);\n this._client = client;\n }\n /**\n * The language of the channel.\n */\n get language() {\n return this[rawDataSymbol].broadcaster_language;\n }\n /**\n * The ID of the channel.\n */\n get id() {\n return this[rawDataSymbol].id;\n }\n /**\n * The name of the channel.\n */\n get name() {\n return this[rawDataSymbol].broadcaster_login;\n }\n /**\n * The display name of the channel.\n */\n get displayName() {\n return this[rawDataSymbol].display_name;\n }\n /**\n * Gets additional information about the owner of the channel.\n */\n async getUser() {\n return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].id));\n }\n /**\n * The ID of the game currently played on the channel.\n */\n get gameId() {\n return this[rawDataSymbol].game_id;\n }\n /**\n * The name of the game currently played on the channel.\n */\n get gameName() {\n return this[rawDataSymbol].game_name;\n }\n /**\n * Gets information about the game that is being played on the stream.\n */\n async getGame() {\n return this[rawDataSymbol].game_id\n ? checkRelationAssertion(await this._client.games.getGameById(this[rawDataSymbol].game_id))\n : null;\n }\n /**\n * Whether the channel is currently live.\n */\n get isLive() {\n return this[rawDataSymbol].is_live;\n }\n /**\n * The tags applied to the channel.\n */\n get tags() {\n return this[rawDataSymbol].tags;\n }\n /**\n * The thumbnail URL of the stream.\n */\n get thumbnailUrl() {\n return this[rawDataSymbol].thumbnail_url;\n }\n /**\n * The start date of the stream. Returns `null` if the stream is not live.\n */\n get startDate() {\n return this[rawDataSymbol].is_live ? new Date(this[rawDataSymbol].started_at) : null;\n }\n};\n__decorate([\n Enumerable(false)\n], HelixChannelSearchResult.prototype, \"_client\", void 0);\nHelixChannelSearchResult = __decorate([\n rtfm('api', 'HelixChannelSearchResult', 'id')\n], HelixChannelSearchResult);\nexport { HelixChannelSearchResult };\n", "var HelixStreamApi_1;\nimport { __decorate } from \"tslib\";\nimport { Enumerable, flatten, mapNullable } from '@d-fischer/shared-utils';\nimport { createBroadcasterQuery, HttpStatusCodeError, } from '@twurple/api-call';\nimport { extractUserId, extractUserName, rtfm } from '@twurple/common';\nimport { StreamNotLiveError } from '../../errors/StreamNotLiveError.js';\nimport { createSingleKeyQuery, createUserQuery } from '../../interfaces/endpoints/generic.external.js';\nimport { createStreamMarkerBody, createStreamQuery, createVideoQuery, } from '../../interfaces/endpoints/stream.external.js';\nimport { HelixRequestBatcher } from '../../utils/HelixRequestBatcher.js';\nimport { HelixPaginatedRequest } from '../../utils/pagination/HelixPaginatedRequest.js';\nimport { createPaginatedResult } from '../../utils/pagination/HelixPaginatedResult.js';\nimport { createPaginationQuery, } from '../../utils/pagination/HelixPagination.js';\nimport { BaseApi } from '../BaseApi.js';\nimport { HelixStream } from './HelixStream.js';\nimport { HelixStreamMarker } from './HelixStreamMarker.js';\nimport { HelixStreamMarkerWithVideo } from './HelixStreamMarkerWithVideo.js';\n/**\n * The Helix API methods that deal with streams.\n *\n * Can be accessed using `client.streams` on an {@link ApiClient} instance.\n *\n * ## Example\n * ```ts\n * const api = new ApiClient({ authProvider });\n * const stream = await api.streams.getStreamByUserId('125328655');\n * ```\n *\n * @meta category helix\n * @meta categorizedTitle Streams\n */\nlet HelixStreamApi = HelixStreamApi_1 = class HelixStreamApi extends BaseApi {\n /** @internal */\n _getStreamByUserIdBatcher = new HelixRequestBatcher({\n url: 'streams',\n }, 'user_id', 'user_id', this._client, (data) => new HelixStream(data, this._client));\n /** @internal */\n _getStreamByUserNameBatcher = new HelixRequestBatcher({\n url: 'streams',\n }, 'user_login', 'user_login', this._client, (data) => new HelixStream(data, this._client));\n /**\n * Gets a list of streams.\n *\n * @param filter\n * @expandParams\n */\n async getStreams(filter = {}) {\n const result = await this._client.callApi({\n url: 'streams',\n type: 'helix',\n query: {\n ...createStreamQuery(filter),\n ...createPaginationQuery(filter),\n },\n });\n return createPaginatedResult(result, HelixStream, this._client);\n }\n /**\n * Creates a paginator for streams.\n *\n * @param filter\n * @expandParams\n */\n getStreamsPaginated(filter = {}) {\n return new HelixPaginatedRequest({\n url: 'streams',\n query: createStreamQuery(filter),\n }, this._client, data => new HelixStream(data, this._client));\n }\n /**\n * Gets the current streams for the given usernames.\n *\n * @param users The username to get the streams for.\n */\n async getStreamsByUserNames(users) {\n const result = await this.getStreams({ userName: users.map(extractUserName) });\n return result.data;\n }\n /**\n * Gets the current stream for the given username.\n *\n * @param user The username to get the stream for.\n */\n async getStreamByUserName(user) {\n const result = await this.getStreamsByUserNames([user]);\n return result[0] ?? null;\n }\n /**\n * Gets the current stream for the given username, batching multiple calls into fewer requests as the API allows.\n *\n * @param user The username to get the stream for.\n */\n async getStreamByUserNameBatched(user) {\n return await this._getStreamByUserNameBatcher.request(extractUserName(user));\n }\n /**\n * Gets the current streams for the given user IDs.\n *\n * @param users The user IDs to get the streams for.\n */\n async getStreamsByUserIds(users) {\n const result = await this.getStreams({ userId: users.map(extractUserId) });\n return result.data;\n }\n /**\n * Gets the current stream for the given user ID.\n *\n * @param user The user ID to get the stream for.\n */\n async getStreamByUserId(user) {\n const userId = extractUserId(user);\n const result = await this._client.callApi({\n url: 'streams',\n type: 'helix',\n userId,\n query: createStreamQuery({ userId }),\n });\n return mapNullable(result.data[0], data => new HelixStream(data, this._client));\n }\n /**\n * Gets the current stream for the given user ID, batching multiple calls into fewer requests as the API allows.\n *\n * @param user The user ID to get the stream for.\n */\n async getStreamByUserIdBatched(user) {\n return await this._getStreamByUserIdBatcher.request(extractUserId(user));\n }\n /**\n * Gets a list of all stream markers for a user.\n *\n * @param user The user to list the stream markers for.\n * @param pagination\n *\n * @expandParams\n */\n async getStreamMarkersForUser(user, pagination) {\n const result = await this._client.callApi({\n url: 'streams/markers',\n type: 'helix',\n query: {\n ...createUserQuery(user),\n ...createPaginationQuery(pagination),\n },\n userId: extractUserId(user),\n scopes: ['user:read:broadcast'],\n canOverrideScopedUserContext: true,\n });\n return {\n data: flatten(result.data.map(data => HelixStreamApi_1._mapGetStreamMarkersResult(data, this._client))),\n cursor: result.pagination?.cursor,\n };\n }\n /**\n * Creates a paginator for all stream markers for a user.\n *\n * @param user The user to list the stream markers for.\n */\n getStreamMarkersForUserPaginated(user) {\n return new HelixPaginatedRequest({\n url: 'streams/markers',\n query: createUserQuery(user),\n userId: extractUserId(user),\n scopes: ['user:read:broadcast'],\n canOverrideScopedUserContext: true,\n }, this._client, data => HelixStreamApi_1._mapGetStreamMarkersResult(data, this._client));\n }\n /**\n * Gets a list of all stream markers for a video.\n *\n * @param user The user the video belongs to.\n * @param videoId The video to list the stream markers for.\n * @param pagination\n *\n * @expandParams\n */\n async getStreamMarkersForVideo(user, videoId, pagination) {\n const result = await this._client.callApi({\n url: 'streams/markers',\n type: 'helix',\n query: {\n ...createVideoQuery(videoId),\n ...createPaginationQuery(pagination),\n },\n userId: extractUserId(user),\n scopes: ['user:read:broadcast'],\n canOverrideScopedUserContext: true,\n });\n return {\n data: flatten(result.data.map(data => HelixStreamApi_1._mapGetStreamMarkersResult(data, this._client))),\n cursor: result.pagination?.cursor,\n };\n }\n /**\n * Creates a paginator for all stream markers for a video.\n *\n * @param user The user the video belongs to.\n * @param videoId The video to list the stream markers for.\n */\n getStreamMarkersForVideoPaginated(user, videoId) {\n return new HelixPaginatedRequest({\n url: 'streams/markers',\n query: createVideoQuery(videoId),\n userId: extractUserId(user),\n scopes: ['user:read:broadcast'],\n canOverrideScopedUserContext: true,\n }, this._client, data => HelixStreamApi_1._mapGetStreamMarkersResult(data, this._client));\n }\n /**\n * Creates a new stream marker.\n *\n * Only works while the specified user's stream is live.\n *\n * @param broadcaster The broadcaster to create a stream marker for.\n * @param description The description of the marker.\n */\n async createStreamMarker(broadcaster, description) {\n try {\n const result = await this._client.callApi({\n url: 'streams/markers',\n method: 'POST',\n type: 'helix',\n userId: extractUserId(broadcaster),\n scopes: ['channel:manage:broadcast'],\n canOverrideScopedUserContext: true,\n jsonBody: createStreamMarkerBody(broadcaster, description),\n });\n return new HelixStreamMarker(result.data[0], this._client);\n }\n catch (e) {\n if (e instanceof HttpStatusCodeError && e.statusCode === 404) {\n throw new StreamNotLiveError({ cause: e });\n }\n throw e;\n }\n }\n /**\n * Gets the stream key of a stream.\n *\n * @param broadcaster The broadcaster to get the stream key for.\n */\n async getStreamKey(broadcaster) {\n const userId = extractUserId(broadcaster);\n const result = await this._client.callApi({\n type: 'helix',\n url: 'streams/key',\n userId,\n scopes: ['channel:read:stream_key'],\n query: createBroadcasterQuery(broadcaster),\n });\n return result.data[0].stream_key;\n }\n /**\n * Gets the streams that are currently live and are followed by the given user.\n *\n * @param user The user to check followed streams for.\n * @param pagination\n *\n * @expandParams\n */\n async getFollowedStreams(user, pagination) {\n const userId = extractUserId(user);\n const result = await this._client.callApi({\n type: 'helix',\n url: 'streams/followed',\n userId,\n scopes: ['user:read:follows'],\n query: {\n ...createSingleKeyQuery('user_id', userId),\n ...createPaginationQuery(pagination),\n },\n });\n return createPaginatedResult(result, HelixStream, this._client);\n }\n /**\n * Creates a paginator for the streams that are currently live and are followed by the given user.\n *\n * @param user The user to check followed streams for.\n */\n getFollowedStreamsPaginated(user) {\n const userId = extractUserId(user);\n return new HelixPaginatedRequest({\n url: 'streams/followed',\n userId,\n scopes: ['user:read:follows'],\n query: createSingleKeyQuery('user_id', userId),\n }, this._client, data => new HelixStream(data, this._client));\n }\n static _mapGetStreamMarkersResult(data, client) {\n return data.videos.reduce((result, video) => [\n ...result,\n ...video.markers.map(marker => new HelixStreamMarkerWithVideo(marker, video.video_id, client)),\n ], []);\n }\n};\n__decorate([\n Enumerable(false)\n], HelixStreamApi.prototype, \"_getStreamByUserIdBatcher\", void 0);\n__decorate([\n Enumerable(false)\n], HelixStreamApi.prototype, \"_getStreamByUserNameBatcher\", void 0);\nHelixStreamApi = HelixStreamApi_1 = __decorate([\n rtfm('api', 'HelixStreamApi')\n], HelixStreamApi);\nexport { HelixStreamApi };\n", "import { CustomError } from '@twurple/common';\n/**\n * Thrown whenever you try something that requires your own stream to be live.\n */\nexport class StreamNotLiveError extends CustomError {\n /** @private */\n constructor(options) {\n super('Your stream needs to be live to do this', options);\n }\n}\n", "import { extractUserId } from '@twurple/common';\n/** @internal */\nexport function createStreamQuery(filter) {\n return {\n game_id: filter.game,\n language: filter.language,\n type: filter.type,\n user_id: filter.userId,\n user_login: filter.userName,\n };\n}\n/** @internal */\nexport function createStreamMarkerBody(broadcaster, description) {\n return {\n user_id: extractUserId(broadcaster),\n description,\n };\n}\n/** @internal */\nexport function createVideoQuery(id) {\n return {\n video_id: id,\n };\n}\n", "import { __decorate } from \"tslib\";\nimport { Enumerable } from '@d-fischer/shared-utils';\nimport { checkRelationAssertion, DataObject, rawDataSymbol, rtfm } from '@twurple/common';\n/**\n * A Twitch stream.\n */\nlet HelixStream = class HelixStream extends DataObject {\n /** @internal */ _client;\n /** @internal */\n constructor(data, client) {\n super(data);\n this._client = client;\n }\n /**\n * The stream ID.\n */\n get id() {\n return this[rawDataSymbol].id;\n }\n /**\n * The user ID.\n */\n get userId() {\n return this[rawDataSymbol].user_id;\n }\n /**\n * The user's name.\n */\n get userName() {\n return this[rawDataSymbol].user_login;\n }\n /**\n * The user's display name.\n */\n get userDisplayName() {\n return this[rawDataSymbol].user_name;\n }\n /**\n * Gets information about the user broadcasting the stream.\n */\n async getUser() {\n return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].user_id));\n }\n /**\n * The game ID, or an empty string if the stream doesn't currently have a game.\n */\n get gameId() {\n return this[rawDataSymbol].game_id;\n }\n /**\n * The game name, or an empty string if the stream doesn't currently have a game.\n */\n get gameName() {\n return this[rawDataSymbol].game_name;\n }\n /**\n * Gets information about the game that is being played on the stream.\n *\n * Returns null if the stream doesn't currently have a game.\n */\n async getGame() {\n return this[rawDataSymbol].game_id\n ? checkRelationAssertion(await this._client.games.getGameById(this[rawDataSymbol].game_id))\n : null;\n }\n /**\n * The type of the stream.\n */\n get type() {\n return this[rawDataSymbol].type;\n }\n /**\n * The title of the stream.\n */\n get title() {\n return this[rawDataSymbol].title;\n }\n /**\n * The number of viewers the stream currently has.\n */\n get viewers() {\n return this[rawDataSymbol].viewer_count;\n }\n /**\n * The time when the stream started.\n */\n get startDate() {\n return new Date(this[rawDataSymbol].started_at);\n }\n /**\n * The language of the stream.\n */\n get language() {\n return this[rawDataSymbol].language;\n }\n /**\n * The URL of the thumbnail of the stream.\n *\n * This URL includes the placeholders `{width}` and `{height}`\n * which you must replace with the desired dimensions of the thumbnail (in pixels).\n *\n * You can also use {@link HelixStream#getThumbnailUrl} to do this replacement.\n */\n get thumbnailUrl() {\n return this[rawDataSymbol].thumbnail_url;\n }\n /**\n * Builds the thumbnail URL of the stream using the given dimensions.\n *\n * @param width The width of the thumbnail.\n * @param height The height of the thumbnail.\n */\n getThumbnailUrl(width, height) {\n return this[rawDataSymbol].thumbnail_url\n .replace('{width}', width.toString())\n .replace('{height}', height.toString());\n }\n /**\n * The tags applied to the stream.\n */\n get tags() {\n return this[rawDataSymbol].tags;\n }\n /**\n * Whether the stream is set to be targeted to mature audiences only.\n */\n get isMature() {\n return this[rawDataSymbol].is_mature;\n }\n};\n__decorate([\n Enumerable(false)\n], HelixStream.prototype, \"_client\", void 0);\nHelixStream = __decorate([\n rtfm('api', 'HelixStream', 'id')\n], HelixStream);\nexport { HelixStream };\n", "import { __decorate } from \"tslib\";\nimport { Enumerable } from '@d-fischer/shared-utils';\nimport { DataObject, rawDataSymbol, rtfm } from '@twurple/common';\n/**\n * A stream marker.\n */\nlet HelixStreamMarker = class HelixStreamMarker extends DataObject {\n /** @internal */ _client;\n /** @internal */\n constructor(data, client) {\n super(data);\n this._client = client;\n }\n /**\n * The ID of the marker.\n */\n get id() {\n return this[rawDataSymbol].id;\n }\n /**\n * The date and time when the marker was created.\n */\n get creationDate() {\n return new Date(this[rawDataSymbol].created_at);\n }\n /**\n * The description of the marker.\n */\n get description() {\n return this[rawDataSymbol].description;\n }\n /**\n * The position in the stream when the marker was created, in seconds.\n */\n get positionInSeconds() {\n return this[rawDataSymbol].position_seconds;\n }\n};\n__decorate([\n Enumerable(false)\n], HelixStreamMarker.prototype, \"_client\", void 0);\nHelixStreamMarker = __decorate([\n rtfm('api', 'HelixStreamMarker', 'id')\n], HelixStreamMarker);\nexport { HelixStreamMarker };\n", "import { __decorate } from \"tslib\";\nimport { checkRelationAssertion, rawDataSymbol, rtfm } from '@twurple/common';\nimport { HelixStreamMarker } from './HelixStreamMarker.js';\n/**\n * A stream marker, also containing some video data.\n *\n * @inheritDoc\n */\nlet HelixStreamMarkerWithVideo = class HelixStreamMarkerWithVideo extends HelixStreamMarker {\n _videoId;\n /** @internal */\n constructor(data, _videoId, client) {\n super(data, client);\n this._videoId = _videoId;\n }\n /**\n * The URL of the video, which will start playing at the position of the stream marker.\n */\n get url() {\n return this[rawDataSymbol].URL;\n }\n /**\n * The ID of the video.\n */\n get videoId() {\n return this._videoId;\n }\n /**\n * Gets the video data of the video the marker was set in.\n */\n async getVideo() {\n return checkRelationAssertion(await this._client.videos.getVideoById(this._videoId));\n }\n};\nHelixStreamMarkerWithVideo = __decorate([\n rtfm('api', 'HelixStreamMarkerWithVideo', 'id')\n], HelixStreamMarkerWithVideo);\nexport { HelixStreamMarkerWithVideo };\n", "import { __decorate } from \"tslib\";\nimport { createBroadcasterQuery, HttpStatusCodeError } from '@twurple/api-call';\nimport { extractUserId, rtfm } from '@twurple/common';\nimport { createChannelUsersCheckQuery } from '../../interfaces/endpoints/generic.external.js';\nimport { createSubscriptionCheckQuery, } from '../../interfaces/endpoints/subscription.external.js';\nimport { createPaginatedResultWithTotal } from '../../utils/pagination/HelixPaginatedResult.js';\nimport { createPaginationQuery } from '../../utils/pagination/HelixPagination.js';\nimport { BaseApi } from '../BaseApi.js';\nimport { HelixPaginatedSubscriptionsRequest } from './HelixPaginatedSubscriptionsRequest.js';\nimport { HelixSubscription } from './HelixSubscription.js';\nimport { HelixUserSubscription } from './HelixUserSubscription.js';\n/**\n * The Helix API methods that deal with subscriptions.\n *\n * Can be accessed using `client.subscriptions` on an {@link ApiClient} instance.\n *\n * ## Example\n * ```ts\n * const api = new ApiClient({ authProvider });\n * const subscription = await api.subscriptions.getSubscriptionForUser('61369223', '125328655');\n * ```\n *\n * @meta category helix\n * @meta categorizedTitle Subscriptions\n */\nlet HelixSubscriptionApi = class HelixSubscriptionApi extends BaseApi {\n /**\n * Gets a list of all subscriptions to a given broadcaster.\n *\n * @param broadcaster The broadcaster to list subscriptions to.\n * @param pagination\n *\n * @expandParams\n */\n async getSubscriptions(broadcaster, pagination) {\n const result = await this._client.callApi({\n url: 'subscriptions',\n scopes: ['channel:read:subscriptions'],\n type: 'helix',\n userId: extractUserId(broadcaster),\n query: {\n ...createBroadcasterQuery(broadcaster),\n ...createPaginationQuery(pagination),\n },\n });\n return {\n ...createPaginatedResultWithTotal(result, HelixSubscription, this._client),\n points: result.points,\n };\n }\n /**\n * Creates a paginator for all subscriptions to a given broadcaster.\n *\n * @param broadcaster The broadcaster to list subscriptions to.\n */\n getSubscriptionsPaginated(broadcaster) {\n return new HelixPaginatedSubscriptionsRequest(broadcaster, this._client);\n }\n /**\n * Gets the subset of the given user list that is subscribed to the given broadcaster.\n *\n * @param broadcaster The broadcaster to find subscriptions to.\n * @param users The users that should be checked for subscriptions.\n */\n async getSubscriptionsForUsers(broadcaster, users) {\n const result = await this._client.callApi({\n type: 'helix',\n url: 'subscriptions',\n userId: extractUserId(broadcaster),\n scopes: ['channel:read:subscriptions'],\n query: createChannelUsersCheckQuery(broadcaster, users),\n });\n return result.data.map(data => new HelixSubscription(data, this._client));\n }\n /**\n * Gets the subscription data for a given user to a given broadcaster.\n *\n * This checks with the authorization of a broadcaster.\n * If you only have the authorization of a user, check {@link HelixSubscriptionApi#checkUserSubscription}}.\n *\n * @param broadcaster The broadcaster to check.\n * @param user The user to check.\n */\n async getSubscriptionForUser(broadcaster, user) {\n const list = await this.getSubscriptionsForUsers(broadcaster, [user]);\n return list.length ? list[0] : null;\n }\n /**\n * Checks if a given user is subscribed to a given broadcaster. Returns null if not subscribed.\n *\n * This checks with the authorization of a user.\n * If you only have the authorization of a broadcaster, check {@link HelixSubscriptionApi#getSubscriptionForUser}}.\n *\n * @param user The user to check.\n * @param broadcaster The broadcaster to check the user's subscription for.\n */\n async checkUserSubscription(user, broadcaster) {\n try {\n const result = await this._client.callApi({\n type: 'helix',\n url: 'subscriptions/user',\n userId: extractUserId(user),\n scopes: ['user:read:subscriptions'],\n query: createSubscriptionCheckQuery(broadcaster, user),\n });\n return new HelixUserSubscription(result.data[0], this._client);\n }\n catch (e) {\n if (e instanceof HttpStatusCodeError && e.statusCode === 404) {\n return null;\n }\n throw e;\n }\n }\n};\nHelixSubscriptionApi = __decorate([\n rtfm('api', 'HelixSubscriptionApi')\n], HelixSubscriptionApi);\nexport { HelixSubscriptionApi };\n", "import { extractUserId } from '@twurple/common';\n/** @internal */\nexport function createSubscriptionCheckQuery(broadcaster, user) {\n return {\n broadcaster_id: extractUserId(broadcaster),\n user_id: extractUserId(user),\n };\n}\n", "import { __decorate } from \"tslib\";\nimport { createBroadcasterQuery } from '@twurple/api-call';\nimport { extractUserId, rtfm } from '@twurple/common';\nimport { HelixPaginatedRequestWithTotal } from '../../utils/pagination/HelixPaginatedRequestWithTotal.js';\nimport { HelixSubscription } from './HelixSubscription.js';\n/**\n * A special case of {@link HelixPaginatedRequestWithTotal}\n * with support for fetching the total sub points of a broadcaster.\n *\n * @inheritDoc\n */\nlet HelixPaginatedSubscriptionsRequest = class HelixPaginatedSubscriptionsRequest extends HelixPaginatedRequestWithTotal {\n /** @internal */\n constructor(broadcaster, client) {\n super({\n url: 'subscriptions',\n scopes: ['channel:read:subscriptions'],\n userId: extractUserId(broadcaster),\n query: createBroadcasterQuery(broadcaster),\n }, client, data => new HelixSubscription(data, client));\n }\n /**\n * Gets the total sub points of the broadcaster.\n */\n async getPoints() {\n const data = this._currentData ??\n (await this._fetchData({ query: { after: undefined } }));\n return data.points;\n }\n};\nHelixPaginatedSubscriptionsRequest = __decorate([\n rtfm('api', 'HelixPaginatedSubscriptionsRequest')\n], HelixPaginatedSubscriptionsRequest);\nexport { HelixPaginatedSubscriptionsRequest };\n", "import { __decorate } from \"tslib\";\nimport { checkRelationAssertion, rawDataSymbol, rtfm } from '@twurple/common';\nimport { HelixUserSubscription } from './HelixUserSubscription.js';\n/**\n * A (paid) subscription of a user to a broadcaster.\n *\n * @inheritDoc\n */\nlet HelixSubscription = class HelixSubscription extends HelixUserSubscription {\n /**\n * The user ID of the broadcaster.\n */\n get broadcasterId() {\n return this[rawDataSymbol].broadcaster_id;\n }\n /**\n * The name of the broadcaster.\n */\n get broadcasterName() {\n return this[rawDataSymbol].broadcaster_login;\n }\n /**\n * The display name of the broadcaster.\n */\n get broadcasterDisplayName() {\n return this[rawDataSymbol].broadcaster_name;\n }\n /**\n * Gets more information about the broadcaster.\n */\n async getBroadcaster() {\n return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].broadcaster_id));\n }\n /**\n * The user ID of the gifter.\n */\n get gifterId() {\n return this[rawDataSymbol].is_gift ? this[rawDataSymbol].gifter_id : null;\n }\n /**\n * The name of the gifter.\n */\n get gifterName() {\n return this[rawDataSymbol].is_gift ? this[rawDataSymbol].gifter_login : null;\n }\n /**\n * The display name of the gifter.\n */\n get gifterDisplayName() {\n return this[rawDataSymbol].is_gift ? this[rawDataSymbol].gifter_name : null;\n }\n /**\n * Gets more information about the gifter.\n */\n async getGifter() {\n return this[rawDataSymbol].is_gift\n ? checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].gifter_id))\n : null;\n }\n /**\n * The user ID of the subscribed user.\n */\n get userId() {\n return this[rawDataSymbol].user_id;\n }\n /**\n * The name of the subscribed user.\n */\n get userName() {\n return this[rawDataSymbol].user_login;\n }\n /**\n * The display name of the subscribed user.\n */\n get userDisplayName() {\n return this[rawDataSymbol].user_name;\n }\n /**\n * Gets more information about the subscribed user.\n */\n async getUser() {\n return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].user_id));\n }\n};\nHelixSubscription = __decorate([\n rtfm('api', 'HelixSubscription', 'userId')\n], HelixSubscription);\nexport { HelixSubscription };\n", "import { __decorate } from \"tslib\";\nimport { Enumerable } from '@d-fischer/shared-utils';\nimport { DataObject, rawDataSymbol, rtfm } from '@twurple/common';\n/**\n * The user info about a (paid) subscription to a broadcaster.\n */\nlet HelixUserSubscription = class HelixUserSubscription extends DataObject {\n /** @internal */ _client;\n /** @internal */\n constructor(data, client) {\n super(data);\n this._client = client;\n }\n /**\n * The user ID of the broadcaster.\n */\n get broadcasterId() {\n return this[rawDataSymbol].broadcaster_id;\n }\n /**\n * The name of the broadcaster.\n */\n get broadcasterName() {\n return this[rawDataSymbol].broadcaster_login;\n }\n /**\n * The display name of the broadcaster.\n */\n get broadcasterDisplayName() {\n return this[rawDataSymbol].broadcaster_name;\n }\n /**\n * Gets more information about the broadcaster.\n */\n async getBroadcaster() {\n return await this._client.users.getUserById(this[rawDataSymbol].broadcaster_id);\n }\n /**\n * Whether the subscription has been gifted by another user.\n */\n get isGift() {\n return this[rawDataSymbol].is_gift;\n }\n /**\n * The tier of the subscription.\n */\n get tier() {\n return this[rawDataSymbol].tier;\n }\n};\n__decorate([\n Enumerable(false)\n], HelixUserSubscription.prototype, \"_client\", void 0);\nHelixUserSubscription = __decorate([\n rtfm('api', 'HelixUserSubscription', 'broadcasterId')\n], HelixUserSubscription);\nexport { HelixUserSubscription };\n", "import { __decorate } from \"tslib\";\nimport { createBroadcasterQuery, HttpStatusCodeError } from '@twurple/api-call';\nimport { extractUserId, rtfm } from '@twurple/common';\nimport { BaseApi } from '../BaseApi.js';\nimport { HelixTeam } from './HelixTeam.js';\nimport { HelixTeamWithUsers } from './HelixTeamWithUsers.js';\n/**\n * The Helix API methods that deal with teams.\n *\n * Can be accessed using `client.teams` on an {@link ApiClient} instance.\n *\n * ## Example\n * ```ts\n * const api = new ApiClient({ authProvider });\n * const tags = await api.teams.getChannelTeams('125328655');\n * ```\n *\n * @meta category helix\n * @meta categorizedTitle Teams\n */\nlet HelixTeamApi = class HelixTeamApi extends BaseApi {\n /**\n * Gets a list of all teams a broadcaster is a member of.\n *\n * @param broadcaster The broadcaster to get the teams of.\n */\n async getTeamsForBroadcaster(broadcaster) {\n const result = await this._client.callApi({\n type: 'helix',\n url: 'teams/channel',\n userId: extractUserId(broadcaster),\n query: createBroadcasterQuery(broadcaster),\n });\n return result.data?.map(data => new HelixTeam(data, this._client)) ?? [];\n }\n /**\n * Gets a team by ID.\n *\n * Returns null if there is no team with the given ID.\n *\n * @param id The ID of the team.\n */\n async getTeamById(id) {\n try {\n const result = await this._client.callApi({\n type: 'helix',\n url: 'teams',\n query: {\n id,\n },\n });\n return new HelixTeamWithUsers(result.data[0], this._client);\n }\n catch (e) {\n // Twitch, please...\n if (e instanceof HttpStatusCodeError && e.statusCode === 500) {\n return null;\n }\n throw e;\n }\n }\n /**\n * Gets a team by name.\n *\n * Returns null if there is no team with the given name.\n *\n * @param name The name of the team.\n */\n async getTeamByName(name) {\n try {\n const result = await this._client.callApi({\n type: 'helix',\n url: 'teams',\n query: {\n name,\n },\n });\n return new HelixTeamWithUsers(result.data[0], this._client);\n }\n catch (e) {\n // ...but this one is fine\n if (e instanceof HttpStatusCodeError && e.statusCode === 404) {\n return null;\n }\n throw e;\n }\n }\n};\nHelixTeamApi = __decorate([\n rtfm('api', 'HelixTeamApi')\n], HelixTeamApi);\nexport { HelixTeamApi };\n", "import { __decorate } from \"tslib\";\nimport { Enumerable } from '@d-fischer/shared-utils';\nimport { DataObject, rawDataSymbol, rtfm } from '@twurple/common';\n/**\n * A Stream Team.\n */\nlet HelixTeam = class HelixTeam extends DataObject {\n /** @internal */ _client;\n /** @internal */\n constructor(data, client) {\n super(data);\n this._client = client;\n }\n /**\n * The ID of the team.\n */\n get id() {\n return this[rawDataSymbol].id;\n }\n /**\n * The name of the team.\n */\n get name() {\n return this[rawDataSymbol].team_name;\n }\n /**\n * The display name of the team.\n */\n get displayName() {\n return this[rawDataSymbol].team_display_name;\n }\n /**\n * The URL of the background image of the team.\n */\n get backgroundImageUrl() {\n return this[rawDataSymbol].background_image_url;\n }\n /**\n * The URL of the banner of the team.\n */\n get bannerUrl() {\n return this[rawDataSymbol].banner;\n }\n /**\n * The date when the team was created.\n */\n get creationDate() {\n return new Date(this[rawDataSymbol].created_at);\n }\n /**\n * The date when the team was last updated.\n */\n get updateDate() {\n return new Date(this[rawDataSymbol].updated_at);\n }\n /**\n * The info of the team.\n *\n * May contain HTML tags.\n */\n get info() {\n return this[rawDataSymbol].info;\n }\n /**\n * The URL of the thumbnail of the team's logo.\n */\n get logoThumbnailUrl() {\n return this[rawDataSymbol].thumbnail_url;\n }\n /**\n * Gets the relations to the members of the team.\n */\n async getUserRelations() {\n const teamWithUsers = await this._client.teams.getTeamById(this.id);\n return teamWithUsers.userRelations;\n }\n};\n__decorate([\n Enumerable(false)\n], HelixTeam.prototype, \"_client\", void 0);\nHelixTeam = __decorate([\n rtfm('api', 'HelixTeam', 'id')\n], HelixTeam);\nexport { HelixTeam };\n", "import { __decorate } from \"tslib\";\nimport { rawDataSymbol, rtfm } from '@twurple/common';\nimport { HelixUserRelation } from '../../relations/HelixUserRelation.js';\nimport { HelixTeam } from './HelixTeam.js';\n/**\n * A Stream Team with its member relations.\n *\n * @inheritDoc\n */\nlet HelixTeamWithUsers = class HelixTeamWithUsers extends HelixTeam {\n /**\n * The relations to the members of the team.\n */\n get userRelations() {\n return this[rawDataSymbol].users.map(data => new HelixUserRelation(data, this._client));\n }\n};\nHelixTeamWithUsers = __decorate([\n rtfm('api', 'HelixTeamWithUsers', 'id')\n], HelixTeamWithUsers);\nexport { HelixTeamWithUsers };\n", "import { __decorate } from \"tslib\";\nimport { Enumerable, mapNullable } from '@d-fischer/shared-utils';\nimport { createBroadcasterQuery } from '@twurple/api-call';\nimport { extractUserId, extractUserName, HellFreezesOverError, rtfm, } from '@twurple/common';\nimport { createSingleKeyQuery } from '../../interfaces/endpoints/generic.external.js';\nimport { createUserBlockCreateQuery, createUserBlockDeleteQuery, } from '../../interfaces/endpoints/user.external.js';\nimport { HelixRequestBatcher } from '../../utils/HelixRequestBatcher.js';\nimport { HelixPaginatedRequest } from '../../utils/pagination/HelixPaginatedRequest.js';\nimport { createPaginatedResult } from '../../utils/pagination/HelixPaginatedResult.js';\nimport { createPaginationQuery } from '../../utils/pagination/HelixPagination.js';\nimport { BaseApi } from '../BaseApi.js';\nimport { HelixInstalledExtensionList } from './extensions/HelixInstalledExtensionList.js';\nimport { HelixUserExtension } from './extensions/HelixUserExtension.js';\nimport { HelixPrivilegedUser } from './HelixPrivilegedUser.js';\nimport { HelixUser } from './HelixUser.js';\nimport { HelixUserBlock } from './HelixUserBlock.js';\n/**\n * The Helix API methods that deal with users.\n *\n * Can be accessed using `client.users` on an {@link ApiClient} instance.\n *\n * ## Example\n * ```ts\n * const api = new ApiClient({ authProvider });\n * const user = await api.users.getUserById('125328655');\n * ```\n *\n * @meta category helix\n * @meta categorizedTitle Users\n */\nlet HelixUserApi = class HelixUserApi extends BaseApi {\n /** @internal */\n _getUserByIdBatcher = new HelixRequestBatcher({\n url: 'users',\n }, 'id', 'id', this._client, (data) => new HelixUser(data, this._client));\n /** @internal */\n _getUserByNameBatcher = new HelixRequestBatcher({\n url: 'users',\n }, 'login', 'login', this._client, (data) => new HelixUser(data, this._client));\n /**\n * Gets the user data for the given list of user IDs.\n *\n * @param userIds The user IDs you want to look up.\n */\n async getUsersByIds(userIds) {\n return await this._getUsers('id', userIds.map(extractUserId));\n }\n /**\n * Gets the user data for the given list of usernames.\n *\n * @param userNames The usernames you want to look up.\n */\n async getUsersByNames(userNames) {\n return await this._getUsers('login', userNames.map(extractUserName));\n }\n /**\n * Gets the user data for the given user ID.\n *\n * @param user The user ID you want to look up.\n */\n async getUserById(user) {\n const userId = extractUserId(user);\n const result = await this._client.callApi({\n type: 'helix',\n url: 'users',\n userId,\n query: {\n id: userId,\n },\n });\n return mapNullable(result.data[0], data => new HelixUser(data, this._client));\n }\n /**\n * Gets the user data for the given user ID, batching multiple calls into fewer requests as the API allows.\n *\n * @param user The user ID you want to look up.\n */\n async getUserByIdBatched(user) {\n return await this._getUserByIdBatcher.request(extractUserId(user));\n }\n /**\n * Gets the user data for the given username.\n *\n * @param userName The username you want to look up.\n */\n async getUserByName(userName) {\n const users = await this._getUsers('login', [extractUserName(userName)]);\n return users.length ? users[0] : null;\n }\n /**\n * Gets the user data for the given username, batching multiple calls into fewer requests as the API allows.\n *\n * @param user The username you want to look up.\n */\n async getUserByNameBatched(user) {\n return await this._getUserByNameBatcher.request(extractUserName(user));\n }\n /**\n * Gets the user data of the given authenticated user.\n *\n * @param user The user to get data for.\n * @param withEmail Whether you need the user's email address.\n */\n async getAuthenticatedUser(user, withEmail = false) {\n const result = await this._client.callApi({\n type: 'helix',\n url: 'users',\n forceType: 'user',\n userId: extractUserId(user),\n scopes: withEmail ? ['user:read:email'] : undefined,\n });\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (!result.data?.length) {\n throw new HellFreezesOverError('Could not get authenticated user');\n }\n return new HelixPrivilegedUser(result.data[0], this._client);\n }\n /**\n * Updates the given authenticated user's data.\n *\n * @param user The user to update.\n * @param data The data to update.\n */\n async updateAuthenticatedUser(user, data) {\n const result = await this._client.callApi({\n type: 'helix',\n url: 'users',\n method: 'PUT',\n userId: extractUserId(user),\n scopes: ['user:edit'],\n query: {\n description: data.description,\n },\n });\n return new HelixPrivilegedUser(result.data[0], this._client);\n }\n /**\n * Gets a list of users blocked by the given user.\n *\n * @param user The user to get blocks for.\n * @param pagination\n *\n * @expandParams\n */\n async getBlocks(user, pagination) {\n const result = await this._client.callApi({\n type: 'helix',\n url: 'users/blocks',\n userId: extractUserId(user),\n scopes: ['user:read:blocked_users'],\n query: {\n ...createBroadcasterQuery(user),\n ...createPaginationQuery(pagination),\n },\n });\n return createPaginatedResult(result, HelixUserBlock, this._client);\n }\n /**\n * Creates a paginator for users blocked by the given user.\n *\n * @param user The user to get blocks for.\n */\n getBlocksPaginated(user) {\n return new HelixPaginatedRequest({\n url: 'users/blocks',\n userId: extractUserId(user),\n scopes: ['user:read:blocked_users'],\n query: createBroadcasterQuery(user),\n }, this._client, data => new HelixUserBlock(data, this._client));\n }\n /**\n * Blocks the given user.\n *\n * @param broadcaster The user to add the block to.\n * @param target The user to block.\n * @param additionalInfo Additional info to give context to the block.\n *\n * @expandParams\n */\n async createBlock(broadcaster, target, additionalInfo = {}) {\n await this._client.callApi({\n type: 'helix',\n url: 'users/blocks',\n method: 'PUT',\n userId: extractUserId(broadcaster),\n scopes: ['user:manage:blocked_users'],\n query: createUserBlockCreateQuery(target, additionalInfo),\n });\n }\n /**\n * Unblocks the given user.\n *\n * @param broadcaster The user to remove the block from.\n * @param target The user to unblock.\n */\n async deleteBlock(broadcaster, target) {\n await this._client.callApi({\n type: 'helix',\n url: 'users/blocks',\n method: 'DELETE',\n userId: extractUserId(broadcaster),\n scopes: ['user:manage:blocked_users'],\n query: createUserBlockDeleteQuery(target),\n });\n }\n /**\n * Gets a list of all extensions for the given authenticated user.\n *\n * @param broadcaster The broadcaster to get the list of extensions for.\n * @param withInactive Whether to include inactive extensions.\n */\n async getExtensionsForAuthenticatedUser(broadcaster, withInactive = false) {\n const result = await this._client.callApi({\n type: 'helix',\n url: 'users/extensions/list',\n userId: extractUserId(broadcaster),\n scopes: withInactive ? ['channel:manage:extensions'] : ['user:read:broadcast', 'channel:manage:extensions'],\n });\n return result.data.map(data => new HelixUserExtension(data));\n }\n /**\n * Gets a list of all installed extensions for the given user.\n *\n * @param user The user to get the installed extensions for.\n * @param withDev Whether to include extensions that are in development.\n */\n async getActiveExtensions(user, withDev = false) {\n const userId = extractUserId(user);\n const result = await this._client.callApi({\n type: 'helix',\n url: 'users/extensions',\n userId,\n scopes: withDev ? ['user:read:broadcast', 'channel:manage:extensions'] : undefined,\n query: createSingleKeyQuery('user_id', userId),\n });\n return new HelixInstalledExtensionList(result.data);\n }\n /**\n * Updates the installed extensions for the given authenticated user.\n *\n * @param broadcaster The user to update the installed extensions for.\n * @param data The extension installation payload.\n *\n * The format is shown on the [Twitch documentation](https://dev.twitch.tv/docs/api/reference#update-user-extensions).\n * Don't use the \"data\" wrapper though.\n */\n async updateActiveExtensionsForAuthenticatedUser(broadcaster, data) {\n const result = await this._client.callApi({\n type: 'helix',\n url: 'users/extensions',\n method: 'PUT',\n userId: extractUserId(broadcaster),\n scopes: ['channel:manage:extensions'],\n jsonBody: { data },\n });\n return new HelixInstalledExtensionList(result.data);\n }\n async _getUsers(lookupType, param) {\n if (param.length === 0) {\n return [];\n }\n const query = { [lookupType]: param };\n const result = await this._client.callApi({\n type: 'helix',\n url: 'users',\n query,\n });\n return result.data.map(userData => new HelixUser(userData, this._client));\n }\n};\n__decorate([\n Enumerable(false)\n], HelixUserApi.prototype, \"_getUserByIdBatcher\", void 0);\n__decorate([\n Enumerable(false)\n], HelixUserApi.prototype, \"_getUserByNameBatcher\", void 0);\nHelixUserApi = __decorate([\n rtfm('api', 'HelixUserApi')\n], HelixUserApi);\nexport { HelixUserApi };\n", "import { extractUserId } from '@twurple/common';\n/** @internal */\nexport function createUserBlockCreateQuery(target, additionalInfo) {\n return {\n target_user_id: extractUserId(target),\n source_context: additionalInfo.sourceContext,\n reason: additionalInfo.reason,\n };\n}\n/** @internal */\nexport function createUserBlockDeleteQuery(target) {\n return {\n target_user_id: extractUserId(target),\n };\n}\n", "import { __decorate } from \"tslib\";\nimport { DataObject, rawDataSymbol, rtfm } from '@twurple/common';\nimport { HelixInstalledExtension } from './HelixInstalledExtension.js';\n/**\n * A list of extensions installed in a channel.\n */\nlet HelixInstalledExtensionList = class HelixInstalledExtensionList extends DataObject {\n getExtensionAtSlot(type, slotId) {\n const data = this[rawDataSymbol][type][slotId];\n return data.active ? new HelixInstalledExtension(type, slotId, data) : null;\n }\n getExtensionsForSlotType(type) {\n return [...Object.entries(this[rawDataSymbol][type])]\n .filter((entry) => entry[1].active)\n .map(([slotId, slotData]) => new HelixInstalledExtension(type, slotId, slotData));\n }\n getAllExtensions() {\n return [...Object.entries(this[rawDataSymbol])].flatMap(([type, typeEntries]) => [...Object.entries(typeEntries)]\n .filter((entry) => entry[1].active)\n .map(([slotId, slotData]) => new HelixInstalledExtension(type, slotId, slotData)));\n }\n};\nHelixInstalledExtensionList = __decorate([\n rtfm('api', 'HelixInstalledExtensionList')\n], HelixInstalledExtensionList);\nexport { HelixInstalledExtensionList };\n", "import { __decorate } from \"tslib\";\nimport { rtfm } from '@twurple/common';\nimport { HelixBaseExtension } from './HelixBaseExtension.js';\n/**\n * A Twitch Extension that is installed in a slot of a channel.\n *\n * @inheritDoc\n */\nlet HelixInstalledExtension = class HelixInstalledExtension extends HelixBaseExtension {\n _slotType;\n _slotId;\n /** @internal */\n constructor(slotType, slotId, data) {\n super(data);\n this._slotType = slotType;\n this._slotId = slotId;\n }\n /**\n * The type of the slot the extension is in.\n */\n get slotType() {\n return this._slotType;\n }\n /**\n * The ID of the slot the extension is in.\n */\n get slotId() {\n return this._slotId;\n }\n};\nHelixInstalledExtension = __decorate([\n rtfm('api', 'HelixInstalledExtension', 'id')\n], HelixInstalledExtension);\nexport { HelixInstalledExtension };\n", "import { DataObject, rawDataSymbol } from '@twurple/common';\n/** @protected */\nexport class HelixBaseExtension extends DataObject {\n /**\n * The ID of the extension.\n */\n get id() {\n return this[rawDataSymbol].id;\n }\n /**\n * The version of the extension.\n */\n get version() {\n return this[rawDataSymbol].version;\n }\n /**\n * The name of the extension.\n */\n get name() {\n return this[rawDataSymbol].name;\n }\n}\n", "import { __decorate } from \"tslib\";\nimport { rawDataSymbol, rtfm } from '@twurple/common';\nimport { HelixBaseExtension } from './HelixBaseExtension.js';\n/**\n * A Twitch Extension that was installed by a user.\n *\n * @inheritDoc\n */\nlet HelixUserExtension = class HelixUserExtension extends HelixBaseExtension {\n /**\n * Whether the user has configured the extension to be able to activate it.\n */\n get canActivate() {\n return this[rawDataSymbol].can_activate;\n }\n /**\n * The available types of the extension.\n */\n get types() {\n return this[rawDataSymbol].type;\n }\n};\nHelixUserExtension = __decorate([\n rtfm('api', 'HelixUserExtension', 'id')\n], HelixUserExtension);\nexport { HelixUserExtension };\n", "import { __decorate } from \"tslib\";\nimport { rawDataSymbol, rtfm } from '@twurple/common';\nimport { HelixUser } from './HelixUser.js';\n/**\n * A user you have extended privilges for, i.e. yourself.\n *\n * @inheritDoc\n */\nlet HelixPrivilegedUser = class HelixPrivilegedUser extends HelixUser {\n /**\n * The email address of the user.\n */\n get email() {\n return this[rawDataSymbol].email;\n }\n /**\n * Changes the description of the user.\n *\n * @param description The new description.\n */\n async setDescription(description) {\n return await this._client.users.updateAuthenticatedUser(this, { description });\n }\n};\nHelixPrivilegedUser = __decorate([\n rtfm('api', 'HelixPrivilegedUser', 'id')\n], HelixPrivilegedUser);\nexport { HelixPrivilegedUser };\n", "import { __decorate } from \"tslib\";\nimport { Enumerable } from '@d-fischer/shared-utils';\nimport { DataObject, rawDataSymbol, rtfm, } from '@twurple/common';\n/**\n * A Twitch user.\n */\nlet HelixUser = class HelixUser extends DataObject {\n /** @internal */ _client;\n /** @internal */\n constructor(data, client) {\n super(data);\n this._client = client;\n }\n /**\n * The ID of the user.\n */\n get id() {\n return this[rawDataSymbol].id;\n }\n /**\n * The name of the user.\n */\n get name() {\n return this[rawDataSymbol].login;\n }\n /**\n * The display name of the user.\n */\n get displayName() {\n return this[rawDataSymbol].display_name;\n }\n /**\n * The description of the user.\n */\n get description() {\n return this[rawDataSymbol].description;\n }\n /**\n * The type of the user.\n */\n get type() {\n return this[rawDataSymbol].type;\n }\n /**\n * The type of the broadcaster.\n */\n get broadcasterType() {\n return this[rawDataSymbol].broadcaster_type;\n }\n /**\n * The URL of the profile picture of the user.\n */\n get profilePictureUrl() {\n return this[rawDataSymbol].profile_image_url;\n }\n /**\n * The URL of the offline video placeholder of the user.\n */\n get offlinePlaceholderUrl() {\n return this[rawDataSymbol].offline_image_url;\n }\n /**\n * The date when the user was created, i.e. when they registered on Twitch.\n */\n get creationDate() {\n return new Date(this[rawDataSymbol].created_at);\n }\n /**\n * Gets the channel's stream data.\n */\n async getStream() {\n return await this._client.streams.getStreamByUserId(this);\n }\n /**\n * Gets a list of broadcasters the user follows.\n */\n async getFollowedChannels() {\n return await this._client.channels.getFollowedChannels(this);\n }\n /**\n * Gets the follow data of the user to the given broadcaster, or `null` if the user doesn't follow the broadcaster.\n *\n * This requires user authentication.\n * For broadcaster authentication, you can use `getChannelFollower` while switching `this` and the parameter.\n *\n * @param broadcaster The broadcaster to check the follow to.\n */\n async getFollowedChannel(broadcaster) {\n const result = await this._client.channels.getFollowedChannels(this, broadcaster);\n return result.data[0] ?? null;\n }\n /**\n * Checks whether the user is following the given broadcaster.\n *\n * This requires user authentication.\n * For broadcaster authentication, you can use `isFollowedBy` while switching `this` and the parameter.\n *\n * @param broadcaster The broadcaster to check the user's follow to.\n */\n async follows(broadcaster) {\n return (await this.getFollowedChannel(broadcaster)) !== null;\n }\n /**\n * Gets a list of users that follow the broadcaster.\n */\n async getChannelFollowers() {\n return await this._client.channels.getChannelFollowers(this);\n }\n /**\n * Gets the follow data of the given user to the broadcaster, or `null` if the user doesn't follow the broadcaster.\n *\n * This requires broadcaster authentication.\n * For user authentication, you can use `getFollowedChannel` while switching `this` and the parameter.\n *\n * @param user The user to check the follow from.\n */\n async getChannelFollower(user) {\n const result = await this._client.channels.getChannelFollowers(this, user);\n return result.data[0] ?? null;\n }\n /**\n * Checks whether the given user is following the broadcaster.\n *\n * This requires broadcaster authentication.\n * For user authentication, you can use `follows` while switching `this` and the parameter.\n *\n * @param user The user to check the broadcaster's follow from.\n */\n async isFollowedBy(user) {\n return (await this.getChannelFollower(user)) !== null;\n }\n /**\n * Gets the subscription data for the user to the given broadcaster, or `null` if the user is not subscribed.\n *\n * This requires user authentication.\n * For broadcaster authentication, you can use `getSubscriber` while switching `this` and the parameter.\n *\n * @param broadcaster The broadcaster you want to get the subscription data for.\n */\n async getSubscriptionTo(broadcaster) {\n return await this._client.subscriptions.checkUserSubscription(this, broadcaster);\n }\n /**\n * Checks whether the user is subscribed to the given broadcaster.\n *\n * This requires user authentication.\n * For broadcaster authentication, you can use `hasSubscriber` while switching `this` and the parameter.\n *\n * @param broadcaster The broadcaster you want to check the subscription for.\n */\n async isSubscribedTo(broadcaster) {\n return (await this.getSubscriptionTo(broadcaster)) !== null;\n }\n /**\n * Gets the subscription data for the given user to the broadcaster, or `null` if the user is not subscribed.\n *\n * This requires broadcaster authentication.\n * For user authentication, you can use `getSubscriptionTo` while switching `this` and the parameter.\n *\n * @param user The user you want to get the subscription data for.\n */\n async getSubscriber(user) {\n return await this._client.subscriptions.getSubscriptionForUser(this, user);\n }\n /**\n * Checks whether the given user is subscribed to the broadcaster.\n *\n * This requires broadcaster authentication.\n * For user authentication, you can use `isSubscribedTo` while switching `this` and the parameter.\n *\n * @param user The user you want to check the subscription for.\n */\n async hasSubscriber(user) {\n return (await this.getSubscriber(user)) !== null;\n }\n};\n__decorate([\n Enumerable(false)\n], HelixUser.prototype, \"_client\", void 0);\nHelixUser = __decorate([\n rtfm('api', 'HelixUser', 'id')\n], HelixUser);\nexport { HelixUser };\n", "import { __decorate } from \"tslib\";\nimport { Enumerable } from '@d-fischer/shared-utils';\nimport { checkRelationAssertion, DataObject, rawDataSymbol, rtfm } from '@twurple/common';\n/**\n * An user blocked by a previously given user.\n */\nlet HelixUserBlock = class HelixUserBlock extends DataObject {\n /** @internal */ _client;\n /** @internal */\n constructor(data, client) {\n super(data);\n this._client = client;\n }\n /**\n * The ID of the blocked user.\n */\n get userId() {\n return this[rawDataSymbol].user_id;\n }\n /**\n * The name of the blocked user.\n */\n get userName() {\n return this[rawDataSymbol].user_login;\n }\n /**\n * The display name of the blocked user.\n */\n get userDisplayName() {\n return this[rawDataSymbol].display_name;\n }\n /**\n * Gets additional information about the blocked user.\n */\n async getUser() {\n return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].user_id));\n }\n};\n__decorate([\n Enumerable(false)\n], HelixUserBlock.prototype, \"_client\", void 0);\nHelixUserBlock = __decorate([\n rtfm('api', 'HelixUserBlock', 'userId')\n], HelixUserBlock);\nexport { HelixUserBlock };\n", "var HelixVideoApi_1;\nimport { __decorate } from \"tslib\";\nimport { Enumerable } from '@d-fischer/shared-utils';\nimport { extractUserId, rtfm } from '@twurple/common';\nimport { HelixRequestBatcher } from '../../utils/HelixRequestBatcher.js';\nimport { HelixPaginatedRequest } from '../../utils/pagination/HelixPaginatedRequest.js';\nimport { createPaginatedResult } from '../../utils/pagination/HelixPaginatedResult.js';\nimport { createPaginationQuery } from '../../utils/pagination/HelixPagination.js';\nimport { BaseApi } from '../BaseApi.js';\nimport { HelixVideo } from './HelixVideo.js';\n/**\n * The Helix API methods that deal with videos.\n *\n * Can be accessed using `client.videos` on an {@link ApiClient} instance.\n *\n * ## Example\n * ```ts\n * const api = new ApiClient({ authProvider });\n * const { data: videos } = await api.videos.getVideosByUser('125328655');\n * ```\n *\n * @meta category helix\n * @meta categorizedTitle Videos\n */\nlet HelixVideoApi = HelixVideoApi_1 = class HelixVideoApi extends BaseApi {\n /** @internal */\n _getVideoByIdBatcher = new HelixRequestBatcher({\n url: 'videos',\n }, 'id', 'id', this._client, (data) => new HelixVideo(data, this._client));\n /**\n * Gets the video data for the given list of video IDs.\n *\n * @param ids The video IDs you want to look up.\n */\n async getVideosByIds(ids) {\n const result = await this._getVideos('id', ids);\n return result.data;\n }\n /**\n * Gets the video data for the given video ID.\n *\n * @param id The video ID you want to look up.\n */\n async getVideoById(id) {\n const videos = await this.getVideosByIds([id]);\n return videos.length ? videos[0] : null;\n }\n /**\n * Gets the video data for the given video ID, batching multiple calls into fewer requests as the API allows.\n *\n * @param id The video ID you want to look up.\n */\n async getVideoByIdBatched(id) {\n return await this._getVideoByIdBatcher.request(id);\n }\n /**\n * Gets the videos of the given user.\n *\n * @param user The user you want to get videos from.\n * @param filter\n *\n * @expandParams\n */\n async getVideosByUser(user, filter = {}) {\n const userId = extractUserId(user);\n return await this._getVideos('user_id', [userId], filter);\n }\n /**\n * Creates a paginator for videos of the given user.\n *\n * @param user The user you want to get videos from.\n * @param filter\n *\n * @expandParams\n */\n getVideosByUserPaginated(user, filter = {}) {\n const userId = extractUserId(user);\n return this._getVideosPaginated('user_id', [userId], filter);\n }\n /**\n * Gets the videos of the given game.\n *\n * @param gameId The game you want to get videos from.\n * @param filter\n *\n * @expandParams\n */\n async getVideosByGame(gameId, filter = {}) {\n return await this._getVideos('game_id', [gameId], filter);\n }\n /**\n * Creates a paginator for videos of the given game.\n *\n * @param gameId The game you want to get videos from.\n * @param filter\n *\n * @expandParams\n */\n getVideosByGamePaginated(gameId, filter = {}) {\n return this._getVideosPaginated('game_id', [gameId], filter);\n }\n /**\n * Deletes videos by its IDs.\n *\n * @param broadcaster The broadcaster to delete the videos for.\n * @param ids The IDs of the videos to delete.\n */\n async deleteVideosByIds(broadcaster, ids) {\n await this._client.callApi({\n type: 'helix',\n url: 'videos',\n method: 'DELETE',\n scopes: ['channel:manage:videos'],\n userId: extractUserId(broadcaster),\n query: {\n id: ids,\n },\n });\n }\n /** @internal */\n async _getVideos(filterType, filterValues, filter = {}) {\n if (!filterValues.length) {\n return { data: [] };\n }\n const result = await this._client.callApi({\n type: 'helix',\n url: 'videos',\n userId: filterType === 'user_id' ? filterValues[0] : undefined,\n query: {\n ...HelixVideoApi_1._makeVideosQuery(filterType, filterValues, filter),\n ...createPaginationQuery(filter),\n },\n });\n return createPaginatedResult(result, HelixVideo, this._client);\n }\n /** @internal */\n _getVideosPaginated(filterType, filterValues, filter = {}) {\n return new HelixPaginatedRequest({\n url: 'videos',\n userId: filterType === 'user_id' ? filterValues[0] : undefined,\n query: HelixVideoApi_1._makeVideosQuery(filterType, filterValues, filter),\n }, this._client, data => new HelixVideo(data, this._client));\n }\n /** @internal */\n static _makeVideosQuery(filterType, filterValues, filter = {}) {\n const { language, period, orderBy, type } = filter;\n return {\n [filterType]: filterValues,\n language,\n period,\n sort: orderBy,\n type,\n };\n }\n};\n__decorate([\n Enumerable(false)\n], HelixVideoApi.prototype, \"_getVideoByIdBatcher\", void 0);\nHelixVideoApi = HelixVideoApi_1 = __decorate([\n rtfm('api', 'HelixVideoApi')\n], HelixVideoApi);\nexport { HelixVideoApi };\n", "import { __decorate } from \"tslib\";\nimport { Cacheable, CachedGetter } from '@d-fischer/cache-decorators';\nimport { Enumerable } from '@d-fischer/shared-utils';\nimport { checkRelationAssertion, DataObject, HellFreezesOverError, rawDataSymbol, rtfm } from '@twurple/common';\n/**\n * A video on Twitch.\n */\nlet HelixVideo = class HelixVideo extends DataObject {\n /** @internal */ _client;\n /** @internal */\n constructor(data, client) {\n super(data);\n this._client = client;\n }\n /**\n * The ID of the video.\n */\n get id() {\n return this[rawDataSymbol].id;\n }\n /**\n * The ID of the user who created the video.\n */\n get userId() {\n return this[rawDataSymbol].user_id;\n }\n /**\n * The name of the user who created the video.\n */\n get userName() {\n return this[rawDataSymbol].user_login;\n }\n /**\n * The display name of the user who created the video.\n */\n get userDisplayName() {\n return this[rawDataSymbol].user_name;\n }\n /**\n * Gets information about the user who created the video.\n */\n async getUser() {\n return checkRelationAssertion(await this._client.users.getUserById(this[rawDataSymbol].user_id));\n }\n /**\n * The title of the video.\n */\n get title() {\n return this[rawDataSymbol].title;\n }\n /**\n * The description of the video.\n */\n get description() {\n return this[rawDataSymbol].description;\n }\n /**\n * The date when the video was created.\n */\n get creationDate() {\n return new Date(this[rawDataSymbol].created_at);\n }\n /**\n * The date when the video was published.\n */\n get publishDate() {\n return new Date(this[rawDataSymbol].published_at);\n }\n /**\n * The URL of the video.\n */\n get url() {\n return this[rawDataSymbol].url;\n }\n /**\n * The URL of the thumbnail of the video.\n */\n get thumbnailUrl() {\n return this[rawDataSymbol].thumbnail_url;\n }\n /**\n * Builds the thumbnail URL of the video using the given dimensions.\n *\n * @param width The width of the thumbnail.\n * @param height The height of the thumbnail.\n */\n getThumbnailUrl(width, height) {\n return this[rawDataSymbol].thumbnail_url\n .replace('%{width}', width.toString())\n .replace('%{height}', height.toString());\n }\n /**\n * Whether the video is public or not.\n */\n get isPublic() {\n return this[rawDataSymbol].viewable === 'public';\n }\n /**\n * The number of views of the video.\n */\n get views() {\n return this[rawDataSymbol].view_count;\n }\n /**\n * The language of the video.\n */\n get language() {\n return this[rawDataSymbol].language;\n }\n /**\n * The type of the video.\n */\n get type() {\n return this[rawDataSymbol].type;\n }\n /**\n * The duration of the video, as formatted by Twitch.\n */\n get duration() {\n return this[rawDataSymbol].duration;\n }\n /**\n * The duration of the video, in seconds.\n */\n get durationInSeconds() {\n const parts = this[rawDataSymbol].duration.match(/\\d+[hms]/g);\n if (!parts) {\n throw new HellFreezesOverError(`Could not parse duration string: ${this[rawDataSymbol].duration}`);\n }\n return parts\n .map(part => {\n const partialMatch = /(\\d+)([hms])/.exec(part);\n if (!partialMatch) {\n throw new HellFreezesOverError(`Could not parse partial duration string: ${part}`);\n }\n const [, num, unit] = partialMatch;\n return parseInt(num, 10) * { h: 3600, m: 60, s: 1 }[unit];\n })\n .reduce((a, b) => a + b);\n }\n /**\n * The ID of the stream this video belongs to.\n *\n * Returns null if the video is not an archived stream.\n */\n get streamId() {\n return this[rawDataSymbol].stream_id;\n }\n /**\n * The raw data of muted segments of the video.\n */\n get mutedSegmentData() {\n return this[rawDataSymbol].muted_segments?.slice() ?? [];\n }\n /**\n * Checks whether the video is muted at a given offset or range.\n *\n * @param offset The start of your range, in seconds from the start of the video,\n * or if no duration is given, the exact offset that is checked.\n * @param duration The duration of your range, in seconds.\n * @param partial Whether the range check is only partial.\n *\n * By default, this function returns true only if the passed range is entirely contained in a muted segment.\n */\n isMutedAt(offset, duration, partial = false) {\n if (this[rawDataSymbol].muted_segments === null) {\n return false;\n }\n if (duration == null) {\n return this[rawDataSymbol].muted_segments.some(seg => seg.offset <= offset && offset <= seg.offset + seg.duration);\n }\n const end = offset + duration;\n if (partial) {\n return this[rawDataSymbol].muted_segments.some(seg => {\n const segEnd = seg.offset + seg.duration;\n return offset < segEnd && seg.offset < end;\n });\n }\n return this[rawDataSymbol].muted_segments.some(seg => {\n const segEnd = seg.offset + seg.duration;\n return seg.offset <= offset && end <= segEnd;\n });\n }\n};\n__decorate([\n Enumerable(false)\n], HelixVideo.prototype, \"_client\", void 0);\n__decorate([\n CachedGetter()\n], HelixVideo.prototype, \"durationInSeconds\", null);\nHelixVideo = __decorate([\n Cacheable,\n rtfm('api', 'HelixVideo', 'id')\n], HelixVideo);\nexport { HelixVideo };\n", "import { __decorate } from \"tslib\";\nimport { extractUserId, rtfm } from '@twurple/common';\nimport { createWhisperQuery } from '../../interfaces/endpoints/whisper.external.js';\nimport { BaseApi } from '../BaseApi.js';\n/**\n * The API methods that deal with whispers.\n *\n * Can be accessed using 'client.whispers' on an {@link ApiClient} instance\n *\n * ## Example\n * ```ts\n * const api = new ApiClient({ authProvider });\n * await api.whispers.sendWhisper('61369223', '86753099', 'Howdy, partner!');\n * ```\n *\n * @meta category helix\n * @meta categorizedTitle Whispers\n */\nlet HelixWhisperApi = class HelixWhisperApi extends BaseApi {\n /**\n * Sends a whisper message to the specified user.\n *\n * NOTE: The API may silently drop whispers that it suspects of violating Twitch policies. (The API does not indicate that it dropped the whisper; it returns a 204 status code as if it succeeded).\n *\n * @param from The user sending the whisper. This user must have a verified phone number and must match the user in the access token.\n * @param to The user to receive the whisper.\n * @param message The whisper message to send. The message must not be empty.\n *\n * The maximum message lengths are:\n *\n * 500 characters if the user you're sending the message to hasn't whispered you before.\n * 10,000 characters if the user you're sending the message to has whispered you before.\n *\n * Messages that exceed the maximum length are truncated.\n */\n async sendWhisper(from, to, message) {\n await this._client.callApi({\n type: 'helix',\n url: 'whispers',\n method: 'POST',\n userId: extractUserId(from),\n scopes: ['user:manage:whispers'],\n query: createWhisperQuery(from, to),\n jsonBody: {\n message,\n },\n });\n }\n};\nHelixWhisperApi = __decorate([\n rtfm('api', 'HelixWhisperApi')\n], HelixWhisperApi);\nexport { HelixWhisperApi };\n", "import { extractUserId } from '@twurple/common';\n/** @internal */\nexport function createWhisperQuery(from, to) {\n return {\n from_user_id: extractUserId(from),\n to_user_id: extractUserId(to),\n };\n}\n", "/**\n * Reporting details for an API request.\n */\nexport class ApiReportedRequest {\n _options;\n _httpStatus;\n _resolvedUserId;\n /** @internal */\n constructor(_options, _httpStatus, _resolvedUserId) {\n this._options = _options;\n this._httpStatus = _httpStatus;\n this._resolvedUserId = _resolvedUserId;\n }\n /**\n * The options used to call the API.\n */\n get options() {\n return this._options;\n }\n /**\n * The HTTP status code returned by Twitch for the request.\n */\n get httpStatus() {\n return this._httpStatus;\n }\n /**\n * The ID of the user that was used for authentication, or `null` if an app access token was used.\n */\n get resolvedUserId() {\n return this._resolvedUserId;\n }\n}\n", "import { __decorate } from \"tslib\";\nimport { rtfm } from '@twurple/common';\nimport { BaseApiClient } from './BaseApiClient.js';\n/** @private */\nlet NoContextApiClient = class NoContextApiClient extends BaseApiClient {\n /** @internal */\n _getUserIdFromRequestContext() {\n return null;\n }\n};\nNoContextApiClient = __decorate([\n rtfm('api', 'ApiClient')\n], NoContextApiClient);\nexport { NoContextApiClient };\n", "import { __decorate } from \"tslib\";\nimport { rtfm } from '@twurple/common';\nimport { BaseApiClient } from './BaseApiClient.js';\n/** @private */\nlet UserContextApiClient = class UserContextApiClient extends BaseApiClient {\n _userId;\n /** @internal */\n constructor(config, logger, rateLimiter, _userId) {\n super(config, logger, rateLimiter);\n this._userId = _userId;\n }\n /** @internal */\n _getUserIdFromRequestContext() {\n return this._userId;\n }\n};\nUserContextApiClient = __decorate([\n rtfm('api', 'ApiClient')\n], UserContextApiClient);\nexport { UserContextApiClient };\n", "import { Bot, InputFile } from 'grammy';\nimport type { Env } from '../types/env';\nimport type { I18nService, SupportedLanguage } from './i18n.service';\nimport { ThumbnailBuilder } from '../utils/thumbnail';\n\nexport interface StreamOnlineNotification {\n chatId: number;\n language: SupportedLanguage;\n channelName: string;\n channelUrl: string;\n category: string;\n title: string;\n thumbnailUrl?: string;\n showImage: boolean;\n}\n\nexport interface StreamOfflineNotification {\n chatId: number;\n language: SupportedLanguage;\n channelName: string;\n channelUrl: string;\n categories: string[];\n duration: string;\n}\n\nexport interface CategoryChangeNotification {\n chatId: number;\n language: SupportedLanguage;\n channelName: string;\n channelUrl: string;\n oldCategory: string;\n category: string;\n}\n\nexport interface TitleChangeNotification {\n chatId: number;\n language: SupportedLanguage;\n channelName: string;\n channelUrl: string;\n oldTitle: string;\n title: string;\n}\n\nexport interface TitleAndCategoryChangeNotification {\n chatId: number;\n language: SupportedLanguage;\n channelName: string;\n channelUrl: string;\n oldTitle: string;\n title: string;\n oldCategory: string;\n category: string;\n}\n\nexport class TelegramService {\n private bot: Bot;\n private i18n: I18nService;\n private thumbnailBuilder: ThumbnailBuilder;\n\n constructor(env: Env, i18n: I18nService) {\n this.bot = new Bot(env.TELEGRAM_TOKEN);\n this.i18n = i18n;\n this.thumbnailBuilder = new ThumbnailBuilder();\n }\n\n async sendStreamOnlineNotification(notification: StreamOnlineNotification): Promise {\n const channelLink = `${notification.channelName}`;\n\n const text = this.i18n.t(notification.language, 'notifications.streams.nowOnline', {\n channelLink,\n category: notification.category,\n title: notification.title,\n });\n\n if (notification.showImage && notification.thumbnailUrl) {\n try {\n const thumbnailUrl = await this.thumbnailBuilder.build(notification.thumbnailUrl, true);\n await this.bot.api.sendPhoto(notification.chatId, new InputFile(new URL(thumbnailUrl)), {\n caption: text,\n parse_mode: 'HTML',\n });\n return;\n } catch (error) {\n // Fallback to text message if image fails\n console.error('Failed to send photo:', error);\n }\n }\n\n await this.bot.api.sendMessage(notification.chatId, text, {\n parse_mode: 'HTML',\n link_preview_options: { is_disabled: false },\n });\n }\n\n async sendStreamOfflineNotification(notification: StreamOfflineNotification): Promise {\n const channelLink = `${notification.channelName}`;\n const categories = notification.categories.join(', ');\n\n const text = this.i18n.t(notification.language, 'notifications.streams.nowOffline', {\n channelLink,\n categories,\n duration: notification.duration,\n });\n\n await this.bot.api.sendMessage(notification.chatId, text, {\n parse_mode: 'HTML',\n link_preview_options: { is_disabled: true },\n });\n }\n\n async sendCategoryChangeNotification(notification: CategoryChangeNotification): Promise {\n const channelLink = `${notification.channelName}`;\n\n const text = this.i18n.t(notification.language, 'notifications.streams.newCategory', {\n channelLink,\n oldCategory: notification.oldCategory,\n category: notification.category,\n });\n\n await this.bot.api.sendMessage(notification.chatId, text, {\n parse_mode: 'HTML',\n link_preview_options: { is_disabled: true },\n });\n }\n\n async sendTitleChangeNotification(notification: TitleChangeNotification): Promise {\n const channelLink = `${notification.channelName}`;\n\n const text = this.i18n.t(notification.language, 'notifications.streams.titleChanged', {\n channelLink,\n oldTitle: notification.oldTitle,\n title: notification.title,\n });\n\n await this.bot.api.sendMessage(notification.chatId, text, {\n parse_mode: 'HTML',\n link_preview_options: { is_disabled: true },\n });\n }\n\n async sendTitleAndCategoryChangeNotification(\n notification: TitleAndCategoryChangeNotification\n ): Promise {\n const channelLink = `${notification.channelName}`;\n\n const text = this.i18n.t(notification.language, 'notifications.streams.titleAndCategoryChanged', {\n channelLink,\n oldTitle: notification.oldTitle,\n title: notification.title,\n oldCategory: notification.oldCategory,\n category: notification.category,\n });\n\n await this.bot.api.sendMessage(notification.chatId, text, {\n parse_mode: 'HTML',\n link_preview_options: { is_disabled: true },\n });\n }\n\n getBot(): Bot {\n return this.bot;\n }\n}\n", "export class ThumbnailBuilder {\n /**\n * Build thumbnail URL from Twitch template URL\n * @param thumbnailUrl - Twitch thumbnail URL with {width} and {height} placeholders\n * @param checkValidity - Whether to check if the URL is accessible (with retry logic)\n * @returns Final thumbnail URL\n */\n async build(thumbnailUrl: string, checkValidity = false): Promise {\n let thumbnail = thumbnailUrl\n .replace('{width}', '1920')\n .replace('{height}', '1080');\n\n if (!checkValidity) {\n return thumbnail;\n }\n\n const isValid = await this.checkValidity(thumbnail, 0);\n\n if (!isValid) {\n // Fallback to lower resolution\n thumbnail = thumbnail\n .replace('1920', '1280')\n .replace('1080', '720');\n }\n\n return thumbnail;\n }\n\n /**\n * Check if thumbnail URL is accessible with retry logic\n * @param url - URL to check\n * @param attempt - Current attempt number (max 5)\n * @returns Whether the URL is valid\n */\n private async checkValidity(url: string, attempt: number): Promise {\n try {\n const response = await fetch(url, {\n method: 'HEAD',\n redirect: 'manual',\n });\n\n if (response.status === 200) {\n return true;\n }\n\n if (attempt >= 5) {\n return false;\n }\n\n // Wait 5 seconds before retry\n await new Promise(resolve => setTimeout(resolve, 5000));\n return this.checkValidity(url, attempt + 1);\n } catch (error) {\n if (attempt >= 5) {\n return false;\n }\n\n await new Promise(resolve => setTimeout(resolve, 5000));\n return this.checkValidity(url, attempt + 1);\n }\n }\n}\n", "import { ApiClient } from '@twurple/api';\nimport type { Env } from '../types/env';\n\nexport class EventSubService {\n private apiClient: ApiClient;\n private webhookUrl: string;\n private secret: string;\n\n constructor(apiClient: ApiClient, env: Env, baseUrl: string) {\n this.apiClient = apiClient;\n this.webhookUrl = `${baseUrl}/twitch-webhook`;\n this.secret = env.TWITCH_EVENTSUB_SECRET;\n }\n\n /**\n * Subscribe to all events for a broadcaster (stream.online, stream.offline, channel.update)\n */\n async subscribeToChannel(broadcasterId: string): Promise {\n try {\n // Subscribe to stream online events\n await this.apiClient.eventSub.subscribeToStreamOnlineEvents(\n broadcasterId,\n {\n method: 'webhook',\n callback: this.webhookUrl,\n secret: this.secret,\n }\n );\n\n // Subscribe to stream offline events\n await this.apiClient.eventSub.subscribeToStreamOfflineEvents(\n broadcasterId,\n {\n method: 'webhook',\n callback: this.webhookUrl,\n secret: this.secret,\n }\n );\n\n // Subscribe to channel update events (title/category changes)\n await this.apiClient.eventSub.subscribeToChannelUpdateEvents(\n broadcasterId,\n {\n method: 'webhook',\n callback: this.webhookUrl,\n secret: this.secret,\n }\n );\n } catch (error) {\n console.error(`Failed to subscribe to events for broadcaster ${broadcasterId}:`, error);\n throw error;\n }\n }\n\n /**\n * Unsubscribe from all events for a broadcaster\n */\n async unsubscribeFromChannel(broadcasterId: string): Promise {\n try {\n // Get all subscriptions\n const subscriptions = await this.apiClient.eventSub.getSubscriptions();\n \n // Filter subscriptions for this broadcaster and our webhook URL\n const broadcasterSubs = subscriptions.data.filter(\n (sub) => {\n const transportMethod = (sub as any).transport?.callback || (sub as any)._transport?.callback;\n const broadcastId = (sub.condition as any).broadcaster_user_id;\n return transportMethod === this.webhookUrl && broadcastId === broadcasterId;\n }\n );\n\n // Delete each subscription\n for (const sub of broadcasterSubs) {\n await this.apiClient.eventSub.deleteSubscription(sub.id);\n }\n } catch (error) {\n console.error(`Failed to unsubscribe from events for broadcaster ${broadcasterId}:`, error);\n throw error;\n }\n }\n\n /**\n * Check if we already have active subscriptions for a broadcaster\n */\n async hasActiveSubscriptions(broadcasterId: string): Promise {\n try {\n const subscriptions = await this.apiClient.eventSub.getSubscriptions();\n \n return subscriptions.data.some(\n (sub) => {\n const transportMethod = (sub as any).transport?.callback || (sub as any)._transport?.callback;\n const broadcastId = (sub.condition as any).broadcaster_user_id;\n return transportMethod === this.webhookUrl && broadcastId === broadcasterId && sub.status === 'enabled';\n }\n );\n } catch (error) {\n console.error(`Failed to check subscriptions for broadcaster ${broadcasterId}:`, error);\n return false;\n }\n }\n\n /**\n * Delete a specific subscription by ID\n */\n async deleteSubscription(subscriptionId: string): Promise {\n try {\n await this.apiClient.eventSub.deleteSubscription(subscriptionId);\n } catch (error) {\n console.error(`Failed to delete subscription ${subscriptionId}:`, error);\n throw error;\n }\n }\n\n /**\n * Get all active subscriptions for our webhook\n */\n async getActiveSubscriptions() {\n try {\n const subscriptions = await this.apiClient.eventSub.getSubscriptions();\n return subscriptions.data.filter((sub) => {\n const transportMethod = (sub as any).transport?.callback || (sub as any)._transport?.callback;\n return transportMethod === this.webhookUrl;\n });\n } catch (error) {\n console.error('Failed to get active subscriptions:', error);\n return [];\n }\n }\n}\n", "import type { DrizzleD1Database } from 'drizzle-orm/d1';\n\n/**\n * Database connection abstraction\n * This allows us to support different database implementations (D1, PostgreSQL, etc.)\n */\nexport interface IDatabaseConnection {\n getClient(): any; // Returns the underlying database client (DrizzleD1Database, etc.)\n}\n\n/**\n * Cloudflare D1 database connection\n */\nexport class CloudflareD1Connection implements IDatabaseConnection {\n constructor(private client: DrizzleD1Database) {}\n\n getClient(): DrizzleD1Database {\n return this.client;\n }\n}\n", "import type { \n IChatRepository,\n IChannelRepository,\n IFollowRepository,\n IStreamRepository\n} from './repositories/interfaces';\nimport {\n ChatDrizzleRepository,\n ChannelDrizzleRepository,\n FollowDrizzleRepository,\n StreamDrizzleRepository\n} from './repositories/drizzle';\nimport type { IDatabaseConnection } from './connection';\n\nexport interface IRepositoryFactory {\n createChatRepository(): IChatRepository;\n createChannelRepository(): IChannelRepository;\n createFollowRepository(): IFollowRepository;\n createStreamRepository(): IStreamRepository;\n}\n\n/**\n * Factory for creating Drizzle-based repositories\n * Works with any Drizzle-compatible database (D1, PostgreSQL, etc.)\n */\nexport class DrizzleRepositoryFactory implements IRepositoryFactory {\n constructor(private connection: IDatabaseConnection) {}\n\n createChatRepository(): IChatRepository {\n return new ChatDrizzleRepository(this.connection.getClient());\n }\n\n createChannelRepository(): IChannelRepository {\n return new ChannelDrizzleRepository(this.connection.getClient());\n }\n\n createFollowRepository(): IFollowRepository {\n return new FollowDrizzleRepository(this.connection.getClient());\n }\n\n createStreamRepository(): IStreamRepository {\n return new StreamDrizzleRepository(this.connection.getClient());\n }\n}\n", "export * from './chat.drizzle.repository';\nexport * from './channel.drizzle.repository';\nexport * from './follow.drizzle.repository';\nexport * from './stream.drizzle.repository';\n", "import type { DrizzleD1Database } from 'drizzle-orm/d1';\nimport { eq } from 'drizzle-orm';\nimport { randomUUID } from 'node:crypto';\nimport { chats, chatSettings } from '../../schema';\nimport { Chat, ChatSettings } from '../../../domain/models';\nimport { DomainMapper } from '../../../domain/mapper';\nimport type { IChatRepository } from '../interfaces';\n\nexport class ChatDrizzleRepository implements IChatRepository {\n constructor(private db: DrizzleD1Database) {}\n\n async findByChatId(chatId: number, service: 'telegram' = 'telegram'): Promise {\n const chatIdStr = chatId.toString();\n \n const chatResult = await this.db\n .select()\n .from(chats)\n .where(eq(chats.chatId, chatIdStr))\n .limit(1);\n \n if (!chatResult[0]) return undefined;\n\n const settingsResult = await this.db\n .select()\n .from(chatSettings)\n .where(eq(chatSettings.chatId, chatResult[0].id))\n .limit(1);\n \n return DomainMapper.toDomainChat({\n ...chatResult[0],\n settings: settingsResult[0] || null\n });\n }\n\n async findById(id: string): Promise {\n const chatResult = await this.db\n .select()\n .from(chats)\n .where(eq(chats.id, id))\n .limit(1);\n \n if (!chatResult[0]) return undefined;\n\n const settingsResult = await this.db\n .select()\n .from(chatSettings)\n .where(eq(chatSettings.chatId, chatResult[0].id))\n .limit(1);\n \n return DomainMapper.toDomainChat({\n ...chatResult[0],\n settings: settingsResult[0] || null\n });\n }\n\n async findAllByService(service: 'telegram' = 'telegram'): Promise {\n const chatResults = await this.db\n .select()\n .from(chats)\n .where(eq(chats.service, service));\n \n const chatsWithSettings: Chat[] = [];\n \n for (const chat of chatResults) {\n const settingsResult = await this.db\n .select()\n .from(chatSettings)\n .where(eq(chatSettings.chatId, chat.id))\n .limit(1);\n \n chatsWithSettings.push(DomainMapper.toDomainChat({\n ...chat,\n settings: settingsResult[0] || null\n }));\n }\n \n return chatsWithSettings;\n }\n\n async create(chatId: string, service: 'telegram' = 'telegram'): Promise {\n const id = randomUUID();\n await this.db.insert(chats).values({ id, chatId, service });\n \n // Create default settings\n await this.db.insert(chatSettings).values({\n chatId: id,\n language: 'en',\n offlineNotification: true,\n gameChangeNotification: false,\n titleChangeNotification: false,\n gameAndTitleChangeNotification: false,\n imageInNotification: true,\n });\n \n return id;\n }\n\n async updateSettings(chatId: string, settings: Partial): Promise {\n await this.db\n .update(chatSettings)\n .set(settings)\n .where(eq(chatSettings.chatId, chatId));\n }\n}\n", "import { sqliteTable, text, integer } from 'drizzle-orm/sqlite-core';\nimport { relations } from 'drizzle-orm';\nimport { randomUUID } from 'node:crypto';\n\n// Chat table\nexport const chats = sqliteTable('chats', {\n id: text('id').primaryKey().$defaultFn(() => randomUUID()),\n chatId: text('chat_id').notNull(),\n service: text('service', { enum: ['telegram'] }).notNull().default('telegram'),\n});\n\nexport const chatsRelations = relations(chats, ({ one, many }) => ({\n settings: one(chatSettings, {\n fields: [chats.id],\n references: [chatSettings.chatId],\n }),\n follows: many(follows),\n}));\n\n// Chat Settings table\nexport const chatSettings = sqliteTable('chat_settings', {\n id: text('id').primaryKey().$defaultFn(() => randomUUID()),\n chatId: text('chat_id').notNull().unique().references(() => chats.id, { onDelete: 'cascade' }),\n gameChangeNotification: integer('game_change_notification', { mode: 'boolean' }).notNull().default(true),\n titleChangeNotification: integer('title_change_notification', { mode: 'boolean' }).notNull().default(false),\n gameAndTitleChangeNotification: integer('game_and_title_change_notification', { mode: 'boolean' }).notNull().default(false),\n offlineNotification: integer('offline_notification', { mode: 'boolean' }).notNull().default(true),\n imageInNotification: integer('image_in_notification', { mode: 'boolean' }).notNull().default(true),\n language: text('language', { enum: ['ru', 'en', 'uk'] }).notNull().default('en'),\n});\n\nexport const chatSettingsRelations = relations(chatSettings, ({ one }) => ({\n chat: one(chats, {\n fields: [chatSettings.chatId],\n references: [chats.id],\n }),\n}));\n\n// Channel table\nexport const channels = sqliteTable('channels', {\n id: text('id').primaryKey().$defaultFn(() => randomUUID()),\n channelId: text('channel_id').notNull(),\n service: text('service', { enum: ['twitch'] }).notNull().default('twitch'),\n isLive: integer('is_live', { mode: 'boolean' }).notNull().default(false),\n title: text('title'),\n category: text('category'),\n updatedAt: text('updated_at').$defaultFn(() => new Date().toISOString()),\n});\n\nexport const channelsRelations = relations(channels, ({ many }) => ({\n follows: many(follows),\n streams: many(streams),\n}));\n\n// Follow table\nexport const follows = sqliteTable('follows', {\n id: text('id').primaryKey().$defaultFn(() => randomUUID()),\n channelId: text('channel_id').notNull().references(() => channels.id, { onDelete: 'cascade' }),\n chatId: text('chat_id').notNull().references(() => chats.id, { onDelete: 'cascade' }),\n});\n\nexport const followsRelations = relations(follows, ({ one }) => ({\n channel: one(channels, {\n fields: [follows.channelId],\n references: [channels.id],\n }),\n chat: one(chats, {\n fields: [follows.chatId],\n references: [chats.id],\n }),\n}));\n\n// Stream table\nexport const streams = sqliteTable('streams', {\n id: text('id').primaryKey(), // Twitch stream ID\n channelId: text('channel_id').notNull().references(() => channels.id, { onDelete: 'cascade' }),\n isLive: integer('is_live', { mode: 'boolean' }).notNull().default(true),\n title: text('title'),\n category: text('category'),\n titles: text('titles', { mode: 'json' }).$type().notNull().default([]),\n categories: text('categories', { mode: 'json' }).$type().notNull().default([]),\n startedAt: text('started_at').$defaultFn(() => new Date().toISOString()),\n updatedAt: text('updated_at').$defaultFn(() => new Date().toISOString()),\n endedAt: text('ended_at'),\n});\n\nexport const streamsRelations = relations(streams, ({ one }) => ({\n channel: one(channels, {\n fields: [streams.channelId],\n references: [channels.id],\n }),\n}));\n\n// Types for insert and select\nexport type Chat = typeof chats.$inferSelect;\nexport type NewChat = typeof chats.$inferInsert;\n\nexport type ChatSettings = typeof chatSettings.$inferSelect;\nexport type NewChatSettings = typeof chatSettings.$inferInsert;\n\nexport type Channel = typeof channels.$inferSelect;\nexport type NewChannel = typeof channels.$inferInsert;\n\nexport type Follow = typeof follows.$inferSelect;\nexport type NewFollow = typeof follows.$inferInsert;\n\nexport type Stream = typeof streams.$inferSelect;\nexport type NewStream = typeof streams.$inferInsert;\n", "// Mappers to convert between database schema and domain models\nimport type { Chat as DbChat, ChatSettings as DbChatSettings, Channel as DbChannel, Follow as DbFollow, Stream as DbStream } from '../db/schema';\nimport { Chat, ChatSettings, Channel, Follow, Stream } from './models';\nimport type { SupportedLanguage } from './models';\n\nexport class DomainMapper {\n static toDomainChat(dbChat: DbChat & { settings: DbChatSettings | null }): Chat {\n return new Chat({\n id: dbChat.id,\n chatId: dbChat.chatId,\n service: dbChat.service,\n settings: dbChat.settings ? this.toDomainChatSettings(dbChat.settings) : undefined,\n });\n }\n\n static toDomainChatSettings(dbSettings: DbChatSettings): ChatSettings {\n return new ChatSettings({\n id: dbSettings.id,\n chatId: dbSettings.chatId,\n gameChangeNotification: dbSettings.gameChangeNotification,\n titleChangeNotification: dbSettings.titleChangeNotification,\n gameAndTitleChangeNotification: dbSettings.gameAndTitleChangeNotification,\n offlineNotification: dbSettings.offlineNotification,\n imageInNotification: dbSettings.imageInNotification,\n language: dbSettings.language as SupportedLanguage,\n });\n }\n\n static toDomainChannel(dbChannel: DbChannel): Channel {\n return new Channel({\n id: dbChannel.id,\n channelId: dbChannel.channelId,\n service: dbChannel.service,\n isLive: dbChannel.isLive,\n title: dbChannel.title ?? undefined,\n category: dbChannel.category ?? undefined,\n updatedAt: dbChannel.updatedAt ? new Date(dbChannel.updatedAt) : undefined,\n });\n }\n\n static toDomainFollow(dbFollow: DbFollow): Follow {\n return new Follow({\n id: dbFollow.id,\n channelId: dbFollow.channelId,\n chatId: dbFollow.chatId,\n });\n }\n\n static toDomainStream(dbStream: DbStream): Stream {\n return new Stream({\n id: dbStream.id,\n channelId: dbStream.channelId,\n isLive: dbStream.isLive,\n title: dbStream.title ?? undefined,\n category: dbStream.category ?? undefined,\n titles: dbStream.titles,\n categories: dbStream.categories,\n startedAt: new Date(dbStream.startedAt!),\n updatedAt: dbStream.updatedAt ? new Date(dbStream.updatedAt) : undefined,\n endedAt: dbStream.endedAt ? new Date(dbStream.endedAt) : undefined,\n });\n }\n}\n", "// Domain models - business logic representations\n// These are separate from database schema to allow flexibility\n\nexport type ChatService = 'telegram';\nexport type ChannelService = 'twitch';\nexport type SupportedLanguage = 'en' | 'ru' | 'uk';\n\nexport class Chat {\n id: string;\n chatId: string;\n service: ChatService;\n settings?: ChatSettings;\n follows?: Follow[];\n\n constructor(data: {\n id: string;\n chatId: string;\n service: ChatService;\n settings?: ChatSettings;\n follows?: Follow[];\n }) {\n this.id = data.id;\n this.chatId = data.chatId;\n this.service = data.service;\n this.settings = data.settings;\n this.follows = data.follows;\n }\n}\n\nexport class ChatSettings {\n id: string;\n chatId: string;\n gameChangeNotification: boolean;\n titleChangeNotification: boolean;\n gameAndTitleChangeNotification: boolean;\n offlineNotification: boolean;\n imageInNotification: boolean;\n language: SupportedLanguage;\n\n constructor(data: {\n id: string;\n chatId: string;\n gameChangeNotification: boolean;\n titleChangeNotification: boolean;\n gameAndTitleChangeNotification: boolean;\n offlineNotification: boolean;\n imageInNotification: boolean;\n language: SupportedLanguage;\n }) {\n this.id = data.id;\n this.chatId = data.chatId;\n this.gameChangeNotification = data.gameChangeNotification;\n this.titleChangeNotification = data.titleChangeNotification;\n this.gameAndTitleChangeNotification = data.gameAndTitleChangeNotification;\n this.offlineNotification = data.offlineNotification;\n this.imageInNotification = data.imageInNotification;\n this.language = data.language;\n }\n}\n\nexport class Channel {\n id: string;\n channelId: string;\n service: ChannelService;\n isLive: boolean;\n title?: string;\n category?: string;\n updatedAt?: Date;\n follows?: Follow[];\n streams?: Stream[];\n\n constructor(data: {\n id: string;\n channelId: string;\n service: ChannelService;\n isLive: boolean;\n title?: string;\n category?: string;\n updatedAt?: Date;\n follows?: Follow[];\n streams?: Stream[];\n }) {\n this.id = data.id;\n this.channelId = data.channelId;\n this.service = data.service;\n this.isLive = data.isLive;\n this.title = data.title;\n this.category = data.category;\n this.updatedAt = data.updatedAt;\n this.follows = data.follows;\n this.streams = data.streams;\n }\n}\n\nexport class Follow {\n id: string;\n channelId: string;\n chatId: string;\n channel?: Channel;\n chat?: Chat;\n\n constructor(data: {\n id: string;\n channelId: string;\n chatId: string;\n channel?: Channel;\n chat?: Chat;\n }) {\n this.id = data.id;\n this.channelId = data.channelId;\n this.chatId = data.chatId;\n this.channel = data.channel;\n this.chat = data.chat;\n }\n}\n\nexport class Stream {\n id: string;\n channelId: string;\n isLive: boolean;\n title?: string;\n category?: string;\n titles: string[];\n categories: string[];\n startedAt: Date;\n updatedAt?: Date;\n endedAt?: Date;\n\n constructor(data: {\n id: string;\n channelId: string;\n isLive: boolean;\n title?: string;\n category?: string;\n titles: string[];\n categories: string[];\n startedAt: Date;\n updatedAt?: Date;\n endedAt?: Date;\n }) {\n this.id = data.id;\n this.channelId = data.channelId;\n this.isLive = data.isLive;\n this.title = data.title;\n this.category = data.category;\n this.titles = data.titles;\n this.categories = data.categories;\n this.startedAt = data.startedAt;\n this.updatedAt = data.updatedAt;\n this.endedAt = data.endedAt;\n }\n}\n\n// Errors\nexport class FollowAlreadyExistsError extends Error {\n constructor() {\n super('Follow already exists');\n this.name = 'FollowAlreadyExistsError';\n }\n}\n\nexport class FollowNotFoundError extends Error {\n constructor() {\n super('Follow not found');\n this.name = 'FollowNotFoundError';\n }\n}\n\nexport class ChannelNotFoundError extends Error {\n constructor() {\n super('Channel not found');\n this.name = 'ChannelNotFoundError';\n }\n}\n", "import type { DrizzleD1Database } from 'drizzle-orm/d1';\nimport { eq, and } from 'drizzle-orm';\nimport { randomUUID } from 'node:crypto';\nimport { channels } from '../../schema';\nimport type { NewChannel } from '../../schema';\nimport { Channel, ChannelNotFoundError } from '../../../domain/models';\nimport { DomainMapper } from '../../../domain/mapper';\nimport type { IChannelRepository } from '../interfaces';\n\nexport class ChannelDrizzleRepository implements IChannelRepository {\n constructor(private db: DrizzleD1Database) {}\n\n async findByChannelId(channelId: string, service: 'twitch' = 'twitch'): Promise {\n const result = await this.db\n .select()\n .from(channels)\n .where(and(eq(channels.channelId, channelId), eq(channels.service, service)))\n .limit(1);\n \n return result[0] ? DomainMapper.toDomainChannel(result[0]) : undefined;\n }\n\n async findById(id: string): Promise {\n const result = await this.db\n .select()\n .from(channels)\n .where(eq(channels.id, id))\n .limit(1);\n \n return result[0] ? DomainMapper.toDomainChannel(result[0]) : undefined;\n }\n\n async create(channelId: string, service: 'twitch' = 'twitch'): Promise {\n const id = randomUUID();\n const result = await this.db.insert(channels).values({\n id,\n channelId,\n service,\n isLive: false,\n }).returning();\n \n return DomainMapper.toDomainChannel(result[0]);\n }\n\n async update(id: string, data: Partial>): Promise {\n const result = await this.db\n .update(channels)\n .set({ ...data, updatedAt: new Date().toISOString() })\n .where(eq(channels.id, id))\n .returning();\n \n if (!result[0]) {\n throw new ChannelNotFoundError();\n }\n \n return DomainMapper.toDomainChannel(result[0]);\n }\n\n async updateChannelId(oldChannelId: string, newChannelId: string, service: 'twitch' = 'twitch'): Promise {\n await this.db\n .update(channels)\n .set({ channelId: newChannelId, updatedAt: new Date().toISOString() })\n .where(and(eq(channels.channelId, oldChannelId), eq(channels.service, service)));\n }\n}\n", "import type { DrizzleD1Database } from 'drizzle-orm/d1';\nimport { eq, and, count } from 'drizzle-orm';\nimport { randomUUID } from 'node:crypto';\nimport { follows } from '../../schema';\nimport { Follow, FollowAlreadyExistsError, FollowNotFoundError } from '../../../domain/models';\nimport { DomainMapper } from '../../../domain/mapper';\nimport type { IFollowRepository } from '../interfaces';\n\nexport class FollowDrizzleRepository implements IFollowRepository {\n constructor(private db: DrizzleD1Database) {}\n\n async findByChatAndChannel(chatId: string, channelId: string): Promise {\n const result = await this.db\n .select()\n .from(follows)\n .where(and(eq(follows.chatId, chatId), eq(follows.channelId, channelId)))\n .limit(1);\n \n return result[0] ? DomainMapper.toDomainFollow(result[0]) : undefined;\n }\n\n async findByChatId(chatId: string): Promise {\n const results = await this.db\n .select()\n .from(follows)\n .where(eq(follows.chatId, chatId));\n \n return results.map(r => DomainMapper.toDomainFollow(r));\n }\n\n async create(chatId: string, channelId: string): Promise {\n // Check if already exists\n const existing = await this.findByChatAndChannel(chatId, channelId);\n if (existing) {\n throw new FollowAlreadyExistsError();\n }\n \n const id = randomUUID();\n await this.db.insert(follows).values({ id, chatId, channelId });\n return id;\n }\n\n async delete(id: string): Promise {\n const result = await this.db\n .delete(follows)\n .where(eq(follows.id, id))\n .returning();\n \n if (result.length === 0) {\n throw new FollowNotFoundError();\n }\n }\n\n async findByChannelId(channelId: string): Promise {\n const results = await this.db\n .select()\n .from(follows)\n .where(eq(follows.channelId, channelId));\n \n return results.map(r => DomainMapper.toDomainFollow(r));\n }\n\n async findByChatIdPaginated(chatId: string, limit: number, offset: number): Promise {\n const results = await this.db\n .select()\n .from(follows)\n .where(eq(follows.chatId, chatId))\n .limit(limit)\n .offset(offset);\n \n return results.map(r => DomainMapper.toDomainFollow(r));\n }\n\n async countByChatId(chatId: string): Promise {\n const result = await this.db\n .select({ count: count() })\n .from(follows)\n .where(eq(follows.chatId, chatId));\n \n return result[0]?.count ?? 0;\n }\n}\n", "import type { DrizzleD1Database } from 'drizzle-orm/d1';\nimport { eq, desc } from 'drizzle-orm';\nimport { streams } from '../../schema';\nimport { Stream } from '../../../domain/models';\nimport { DomainMapper } from '../../../domain/mapper';\nimport type { IStreamRepository } from '../interfaces';\n\nexport class StreamDrizzleRepository implements IStreamRepository {\n constructor(private db: DrizzleD1Database) {}\n\n async findLatestByChannelId(channelId: string): Promise {\n const result = await this.db\n .select()\n .from(streams)\n .where(eq(streams.channelId, channelId))\n .orderBy(desc(streams.startedAt))\n .limit(1);\n \n return result[0] ? DomainMapper.toDomainStream(result[0]) : undefined;\n }\n\n async create(id: string, channelId: string, category: string, title: string): Promise {\n await this.db.insert(streams).values({\n id,\n channelId,\n isLive: true,\n category,\n title,\n startedAt: new Date().toISOString(),\n titles: [title] as any,\n categories: [category] as any,\n });\n \n return id;\n }\n\n async update(id: string, data: { isLive?: boolean; category?: string; title?: string; endedAt?: string }): Promise {\n const result = await this.db\n .update(streams)\n .set(data)\n .where(eq(streams.id, id))\n .returning();\n \n if (!result[0]) {\n throw new Error('Stream not found');\n }\n \n return DomainMapper.toDomainStream(result[0]);\n }\n\n async findById(id: string): Promise {\n const result = await this.db\n .select()\n .from(streams)\n .where(eq(streams.id, id))\n .limit(1);\n \n return result[0] ? DomainMapper.toDomainStream(result[0]) : undefined;\n }\n}\n", "export * from './session.kv.repository';\n", "import type { KVNamespace } from '@cloudflare/workers-types';\nimport type { ISessionRepository } from '../interfaces/session.repository.interface';\n\n/**\n * Cloudflare KV-based session repository\n * Fast, distributed key-value storage perfect for sessions\n */\nexport class CloudflareKVSessionRepository implements ISessionRepository {\n constructor(private readonly kv: KVNamespace) {}\n\n async get(key: string): Promise {\n const value = await this.kv.get(key);\n return value ?? undefined;\n }\n\n async set(key: string, value: string, expiresAt?: number): Promise {\n const options: { expirationTtl?: number } = {};\n\n // Convert expiresAt (unix timestamp) to TTL in seconds\n if (expiresAt) {\n const ttl = Math.floor((expiresAt - Date.now()) / 1000);\n if (ttl > 0) {\n options.expirationTtl = ttl;\n }\n }\n\n await this.kv.put(key, value, options);\n }\n\n async delete(key: string): Promise {\n await this.kv.delete(key);\n }\n\n async cleanup(): Promise {\n // KV automatically cleans up expired keys, no manual cleanup needed\n return;\n }\n}\n", "import type { Env } from '../types/env';\nimport type { DrizzleD1Database } from 'drizzle-orm/d1';\nimport { TwitchService } from '../services/twitch.service';\nimport { TelegramService } from '../services/telegram.service';\nimport { I18nService } from '../services/i18n.service';\nimport { NotificationService } from '../services/notification.service';\nimport { CloudflareD1Connection } from '../db/connection';\nimport { DrizzleRepositoryFactory } from '../db/repository.factory';\nimport { createHmac } from 'node:crypto';\n\ninterface EventSubNotification {\n subscription: {\n id: string;\n type: string;\n version: string;\n status: string;\n cost: number;\n condition: Record;\n transport: {\n method: string;\n callback: string;\n };\n created_at: string;\n };\n event: Record;\n}\n\ninterface EventSubVerification {\n challenge: string;\n subscription: {\n id: string;\n type: string;\n version: string;\n status: string;\n cost: number;\n condition: Record;\n transport: {\n method: string;\n callback: string;\n };\n created_at: string;\n };\n}\n\nexport async function handleTwitchWebhook(\n request: Request,\n env: Env,\n db: DrizzleD1Database\n): Promise {\n try {\n // Verify the signature\n const messageId = request.headers.get('Twitch-Eventsub-Message-Id');\n const timestamp = request.headers.get('Twitch-Eventsub-Message-Timestamp');\n const signature = request.headers.get('Twitch-Eventsub-Message-Signature');\n const messageType = request.headers.get('Twitch-Eventsub-Message-Type');\n\n if (!messageId || !timestamp || !signature) {\n return new Response('Missing required headers', { status: 400 });\n }\n\n const body = await request.text();\n\n // Verify signature\n const hmac = createHmac('sha256', env.TWITCH_EVENTSUB_SECRET);\n hmac.update(messageId + timestamp + body);\n const expectedSignature = 'sha256=' + hmac.digest('hex');\n\n if (signature !== expectedSignature) {\n return new Response('Invalid signature', { status: 403 });\n }\n\n const payload = JSON.parse(body);\n\n // Handle verification challenge\n if (messageType === 'webhook_callback_verification') {\n const verification = payload as EventSubVerification;\n return new Response(verification.challenge, {\n status: 200,\n headers: { 'Content-Type': 'text/plain' },\n });\n }\n\n // Handle notification\n if (messageType === 'notification') {\n const notification = payload as EventSubNotification;\n\n // Initialize services\n const i18nService = new I18nService();\n const twitchService = new TwitchService(env);\n const telegramService = new TelegramService(env, i18nService);\n\n // Initialize repositories via factory\n const dbConnection = new CloudflareD1Connection(db);\n const repositoryFactory = new DrizzleRepositoryFactory(dbConnection);\n \n const chatRepo = repositoryFactory.createChatRepository();\n const channelRepo = repositoryFactory.createChannelRepository();\n const followRepo = repositoryFactory.createFollowRepository();\n const streamRepo = repositoryFactory.createStreamRepository();\n\n // Initialize notification service\n const notificationService = new NotificationService(\n env,\n db,\n telegramService,\n twitchService,\n i18nService,\n chatRepo,\n channelRepo,\n followRepo,\n streamRepo\n );\n\n // Handle different event types\n switch (notification.subscription.type) {\n case 'stream.online': {\n const event = notification.event;\n const stream = await twitchService.getStreamByUserId(event.broadcaster_user_id);\n if (stream) {\n await notificationService.handleStreamOnline({\n channelId: event.broadcaster_user_id,\n channelName: event.broadcaster_user_name,\n streamId: stream.id,\n category: stream.gameName,\n title: stream.title,\n thumbnailUrl: stream.thumbnailUrl,\n });\n }\n break;\n }\n\n case 'stream.offline': {\n const event = notification.event;\n await notificationService.handleStreamOffline({\n channelId: event.broadcaster_user_id,\n channelName: event.broadcaster_user_name,\n });\n break;\n }\n\n case 'channel.update': {\n const event = notification.event;\n const channel = await channelRepo.findByChannelId(event.broadcaster_user_id, 'twitch');\n if (!channel) break;\n\n const stream = await streamRepo.findLatestByChannelId(channel.id);\n if (!stream || !stream.isLive) break;\n\n // Check if category changed\n if (stream.category && event.category_name !== stream.category) {\n await notificationService.handleCategoryChange({\n channelId: event.broadcaster_user_id,\n channelName: event.broadcaster_user_name,\n oldCategory: stream.category,\n newCategory: event.category_name,\n });\n }\n\n // Check if title changed\n if (stream.title && event.title !== stream.title) {\n await notificationService.handleTitleChange({\n channelId: event.broadcaster_user_id,\n channelName: event.broadcaster_user_name,\n oldTitle: stream.title,\n newTitle: event.title,\n });\n }\n break;\n }\n }\n\n return new Response('OK', { status: 200 });\n }\n\n // Handle revocation\n if (messageType === 'revocation') {\n console.log('Subscription revoked:', payload);\n return new Response('OK', { status: 200 });\n }\n\n return new Response('Unknown message type', { status: 400 });\n } catch (error) {\n console.error('Error handling Twitch webhook:', error);\n return new Response('Internal Server Error', { status: 500 });\n }\n}\n", "import type { DrizzleD1Database } from 'drizzle-orm/d1';\nimport type { Env } from '../types/env';\nimport { TelegramService } from './telegram.service';\nimport { TwitchService } from './twitch.service';\nimport { I18nService, type SupportedLanguage } from './i18n.service';\nimport type {\n IChatRepository,\n IChannelRepository,\n IFollowRepository,\n IStreamRepository,\n} from '../db/repositories/interfaces';\n\nexport interface StreamOnlineEventData {\n channelId: string;\n channelName: string;\n streamId: string;\n category: string;\n title: string;\n thumbnailUrl: string;\n}\n\nexport interface StreamOfflineEventData {\n channelId: string;\n channelName: string;\n}\n\nexport interface StreamCategoryChangeEventData {\n channelId: string;\n channelName: string;\n oldCategory: string;\n newCategory: string;\n}\n\nexport interface StreamTitleChangeEventData {\n channelId: string;\n channelName: string;\n oldTitle: string;\n newTitle: string;\n}\n\nexport class NotificationService {\n constructor(\n private env: Env,\n private db: DrizzleD1Database,\n private telegramService: TelegramService,\n private twitchService: TwitchService,\n private i18nService: I18nService,\n private chatRepo: IChatRepository,\n private channelRepo: IChannelRepository,\n private followRepo: IFollowRepository,\n private streamRepo: IStreamRepository\n ) {}\n\n async handleStreamOnline(data: StreamOnlineEventData): Promise {\n // Get or create channel\n let channel = await this.channelRepo.findByChannelId(data.channelId, 'twitch');\n if (!channel) {\n channel = await this.channelRepo.create(data.channelId, 'twitch');\n }\n\n // Create stream record\n await this.streamRepo.create(\n data.streamId,\n channel.id,\n data.category,\n data.title\n );\n\n // Get all followers of this channel\n const follows = await this.followRepo.findByChannelId(channel.id);\n\n // Send notifications to all followers\n for (const follow of follows) {\n try {\n const chat = await this.chatRepo.findById(follow.chatId);\n if (!chat || !chat.settings) continue;\n\n await this.telegramService.sendStreamOnlineNotification({\n chatId: parseInt(chat.chatId),\n language: chat.settings.language as SupportedLanguage,\n channelName: data.channelName,\n channelUrl: `https://twitch.tv/${data.channelName}`,\n category: data.category,\n title: data.title,\n thumbnailUrl: data.thumbnailUrl,\n showImage: chat.settings.imageInNotification,\n });\n } catch (error) {\n console.error('Failed to send online notification:', error);\n }\n }\n }\n\n async handleStreamOffline(data: StreamOfflineEventData): Promise {\n const channel = await this.channelRepo.findByChannelId(data.channelId, 'twitch');\n if (!channel) return;\n\n // Get latest stream\n const stream = await this.streamRepo.findLatestByChannelId(channel.id);\n if (!stream || !stream.isLive) return;\n\n // Update stream as offline\n await this.streamRepo.update(stream.id, {\n isLive: false,\n endedAt: new Date().toISOString(),\n });\n\n // Get all followers\n const follows = await this.followRepo.findByChannelId(channel.id);\n\n // Send notifications to followers who want offline notifications\n for (const follow of follows) {\n try {\n const chat = await this.chatRepo.findById(follow.chatId);\n if (!chat || !chat.settings || !chat.settings.offlineNotification) continue;\n\n const duration = stream.startedAt\n ? Math.floor((Date.now() - new Date(stream.startedAt).getTime()) / 1000)\n : 0;\n const hours = Math.floor(duration / 3600);\n const minutes = Math.floor((duration % 3600) / 60);\n const seconds = duration % 60;\n const durationStr = `${hours}h ${minutes}m ${seconds}s`;\n\n await this.telegramService.sendStreamOfflineNotification({\n chatId: parseInt(chat.chatId),\n language: chat.settings.language as SupportedLanguage,\n channelName: data.channelName,\n channelUrl: `https://twitch.tv/${data.channelName}`,\n categories: stream.categories || [],\n duration: durationStr,\n });\n } catch (error) {\n console.error('Failed to send offline notification:', error);\n }\n }\n }\n\n async handleCategoryChange(data: StreamCategoryChangeEventData): Promise {\n const channel = await this.channelRepo.findByChannelId(data.channelId, 'twitch');\n if (!channel) return;\n\n const stream = await this.streamRepo.findLatestByChannelId(channel.id);\n if (!stream || !stream.isLive) return;\n\n // Update stream categories\n const categories = [...(stream.categories || []), data.newCategory];\n await this.streamRepo.update(stream.id, {\n category: data.newCategory,\n categories,\n });\n\n // Get all followers\n const follows = await this.followRepo.findByChannelId(channel.id);\n\n for (const follow of follows) {\n try {\n const chat = await this.chatRepo.findById(follow.chatId);\n if (!chat || !chat.settings || !chat.settings.gameChangeNotification) continue;\n\n await this.telegramService.sendCategoryChangeNotification({\n chatId: parseInt(chat.chatId),\n language: chat.settings.language as SupportedLanguage,\n channelName: data.channelName,\n channelUrl: `https://twitch.tv/${data.channelName}`,\n oldCategory: data.oldCategory,\n category: data.newCategory,\n });\n } catch (error) {\n console.error('Failed to send category change notification:', error);\n }\n }\n }\n\n async handleTitleChange(data: StreamTitleChangeEventData): Promise {\n const channel = await this.channelRepo.findByChannelId(data.channelId, 'twitch');\n if (!channel) return;\n\n const stream = await this.streamRepo.findLatestByChannelId(channel.id);\n if (!stream || !stream.isLive) return;\n\n // Update stream titles\n const titles = [...(stream.titles || []), data.newTitle];\n await this.streamRepo.update(stream.id, {\n title: data.newTitle,\n titles,\n });\n\n // Get all followers\n const follows = await this.followRepo.findByChannelId(channel.id);\n\n for (const follow of follows) {\n try {\n const chat = await this.chatRepo.findById(follow.chatId);\n if (!chat || !chat.settings || !chat.settings.titleChangeNotification) continue;\n\n await this.telegramService.sendTitleChangeNotification({\n chatId: parseInt(chat.chatId),\n language: chat.settings.language as SupportedLanguage,\n channelName: data.channelName,\n channelUrl: `https://twitch.tv/${data.channelName}`,\n oldTitle: data.oldTitle,\n title: data.newTitle,\n });\n } catch (error) {\n console.error('Failed to send title change notification:', error);\n }\n }\n }\n}\n", "import type { Middleware } from \"./common\";\n\nconst drainBody: Middleware = async (request, env, _ctx, middlewareCtx) => {\n\ttry {\n\t\treturn await middlewareCtx.next(request, env);\n\t} finally {\n\t\ttry {\n\t\t\tif (request.body !== null && !request.bodyUsed) {\n\t\t\t\tconst reader = request.body.getReader();\n\t\t\t\twhile (!(await reader.read()).done) {}\n\t\t\t}\n\t\t} catch (e) {\n\t\t\tconsole.error(\"Failed to drain the unused request body.\", e);\n\t\t}\n\t}\n};\n\nexport default drainBody;\n", "import type { Middleware } from \"./common\";\n\ninterface JsonError {\n\tmessage?: string;\n\tname?: string;\n\tstack?: string;\n\tcause?: JsonError;\n}\n\nfunction reduceError(e: any): JsonError {\n\treturn {\n\t\tname: e?.name,\n\t\tmessage: e?.message ?? String(e),\n\t\tstack: e?.stack,\n\t\tcause: e?.cause === undefined ? undefined : reduceError(e.cause),\n\t};\n}\n\n// See comment in `bundle.ts` for details on why this is needed\nconst jsonError: Middleware = async (request, env, _ctx, middlewareCtx) => {\n\ttry {\n\t\treturn await middlewareCtx.next(request, env);\n\t} catch (e: any) {\n\t\tconst error = reduceError(e);\n\t\treturn Response.json(error, {\n\t\t\tstatus: 500,\n\t\t\theaders: { \"MF-Experimental-Error-Stack\": \"true\" },\n\t\t});\n\t}\n};\n\nexport default jsonError;\n", "export type Awaitable = T | Promise;\n// TODO: allow dispatching more events?\nexport type Dispatcher = (\n\ttype: \"scheduled\",\n\tinit: { cron?: string }\n) => Awaitable;\n\nexport type IncomingRequest = Request<\n\tunknown,\n\tIncomingRequestCfProperties\n>;\n\nexport interface MiddlewareContext {\n\tdispatch: Dispatcher;\n\tnext(request: IncomingRequest, env: any): Awaitable;\n}\n\nexport type Middleware = (\n\trequest: IncomingRequest,\n\tenv: any,\n\tctx: ExecutionContext,\n\tmiddlewareCtx: MiddlewareContext\n) => Awaitable;\n\nconst __facade_middleware__: Middleware[] = [];\n\n// The register functions allow for the insertion of one or many middleware,\n// We register internal middleware first in the stack, but have no way of controlling\n// the order that addMiddleware is run in service workers so need an internal function.\nexport function __facade_register__(...args: (Middleware | Middleware[])[]) {\n\t__facade_middleware__.push(...args.flat());\n}\nexport function __facade_registerInternal__(\n\t...args: (Middleware | Middleware[])[]\n) {\n\t__facade_middleware__.unshift(...args.flat());\n}\n\nfunction __facade_invokeChain__(\n\trequest: IncomingRequest,\n\tenv: any,\n\tctx: ExecutionContext,\n\tdispatch: Dispatcher,\n\tmiddlewareChain: Middleware[]\n): Awaitable {\n\tconst [head, ...tail] = middlewareChain;\n\tconst middlewareCtx: MiddlewareContext = {\n\t\tdispatch,\n\t\tnext(newRequest, newEnv) {\n\t\t\treturn __facade_invokeChain__(newRequest, newEnv, ctx, dispatch, tail);\n\t\t},\n\t};\n\treturn head(request, env, ctx, middlewareCtx);\n}\n\nexport function __facade_invoke__(\n\trequest: IncomingRequest,\n\tenv: any,\n\tctx: ExecutionContext,\n\tdispatch: Dispatcher,\n\tfinalMiddleware: Middleware\n): Awaitable {\n\treturn __facade_invokeChain__(request, env, ctx, dispatch, [\n\t\t...__facade_middleware__,\n\t\tfinalMiddleware,\n\t]);\n}\n"], - "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuBO,SAAS,0BAA0B,MAAM;AAC/C,SAAO,IAAI,MAAM,WAAW,IAAI,0BAA0B;AAC3D;AAzBA;AAAA;AAAA;AAAA,IAAAA;AAuBgB;AAAA;AAAA;;;ACvBhB,IACM,aACA,iBACA,YAuBO,kBAyBA,iBAWA,o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M;AAAA,UAAC;AAAA,QACR;AACA,eAAO,MAAM,UAAU,UAAU;AAAA,MAClC;AAAA,IACD,GAT0B;AAAA,IAW1B,MAAM,SAAwD;AAC7D,aAAO;AAAA,QACN;AAAA,QACA,KAAK;AAAA,QACL,KAAK;AAAA,QACL,KAAK;AAAA,QACL,KAAK;AAAA,MACN;AAAA,IACD;AAAA,EACD;AACD;AAnDS;AAqDT,IAAI;AACJ,IAAI,OAAO,wCAAU,UAAU;AAC9B,kBAAgB,oBAAoB,mCAAK;AAC1C,WAAW,OAAO,wCAAU,YAAY;AACvC,kBAAgB,qBAAqB,mCAAK;AAC3C;AACA,IAAO,kCAAQ;", - "names": ["init_performance", "init_performance", "PerformanceMark", "init_performance", "init_performance", "init_performance", "init_performance", "init_performance", "self", "count", "init_performance", "original", "require_retry", "init_performance", "init_performance", "init_performance", "init_performance", "init_performance", "init_performance", "init_performance", "init_performance", "init_performance", "init_performance", "init_performance", "init_performance", "init_performance", "init_performance", "match", "str", "str", "raw", "text", "data", "init_performance", "str", "str2", "init", "data", "text", "init_performance", "init_performance", "m", "app", "init_performance", "init_performance", "init_performance", "match2", "init_performance", "init_performance", "m", "h", "m", "init_performance", "init_performance", "init_performance", "init", "init_performance", "init_performance", "init_performance", "Node", "_Node", "m", "Node", "Hono", "init_performance", "expanded", "s", "get", "t", "match", "emoji", "reaction", "Context", "text", "title", "m", "ok", "errorHandler", "str", "dir", "performance", "process", "debug", "data", "config", "options", "raw", "use", "setup", "text", "data", "s", "raw", "unauthorized", "ms", "init_performance", "init_performance", "init_performance", "config", "init_performance", "init_performance", "init_performance", "init_performance", "config", "init_performance", "init_performance", "init_performance", "init_performance", "init_performance", "init_performance", "init_performance", "init_performance", "config", "init_performance", "init_performance", "init_performance", "value", "startFrom", "config", "ref", "actions", "config", "init_performance", "sql", "init_performance", "init_performance", "version", "version", "otel", "rawTracer", "init_performance", "config", "param", "sql", "raw", "str", "placeholder", "name", "SQL", "name", "result", "init_performance", "or", "init_performance", "config", "or", "relations", "init_performance", "init_performance", "init_performance", "config", "init_performance", "init_performance", "init_performance", "init_performance", "init_performance", "init_performance", "init_performance", "ForeignKeyBuilder", "config", "ForeignKey", "init_performance", "uniqueKeyName", "UniqueConstraintBuilder", "UniqueConstraint", "UniqueOnConstraintBuilder", "uniqueKeyName", "config", "ref", "actions", "ForeignKeyBuilder", "uniqueKeyName", "config", "init_performance", "config", "init_performance", "config", "init_performance", "config", "init_performance", "init_performance", "config", "InlineForeignKeys", "name", "init_performance", "session", "init_performance", "init_performance", "init_performance", "init_performance", "init_performance", "init_performance", "init_performance", "config", "str", "w", "table", "select", "sql", "joinOn", "field", "session", "init_performance", "init_performance", "config", "session", "on", "self", "session", "config", "init_performance", "session", "on", "init_performance", "init_performance", "session", "config", "init_performance", "session", "self", "config", "init_performance", "init_performance", "sql", "data", "init_performance", "sql", "session", "builtQuery", "config", "config", "session", "init_performance", "init_performance", "init_performance", "init_performance", "init_performance", "text", "follows", "data", "init_performance", "text", "m", "init_performance", "init_performance", "follows", "uptime", "init_performance", "text", "init_performance", "text", "init_performance", "data", "init_performance", "init_performance", "s", "t", "m", "concat", "getPath", "data", "str", "copy", "count", "match", "noop", "instance", "exists", "init_performance", "init_performance", "init_performance", "init_performance", "d", "b", "desc", "d", "m", "import_detect_node", "init_performance", "init_performance", "import_detect_node", "init_performance", "init_performance", "LogLevel", "init_performance", "init_performance", "init_performance", "init_performance", "flatten", "_a", "init_performance", "init_performance", "_a", "init_performance", "init_performance", "import_detect_node", "init_performance", "_a", "_b", "_c", "BaseLogger", "_a", "_b", "colors", "_c", "BrowserLogger", "init_performance", "CustomLoggerWrapper", "_a", "_b", "init_performance", "_a", "_b", "str", "NodeLogger", "_c", "init_performance", "init_performance", "init_performance", "_a", "init_performance", "init_performance", "init_performance", "init_performance", "_a", "_b", "_c", "retry", "init_performance", "_a", "_b", "queue", "init_performance", "init_performance", "init_performance", "init_performance", "init_performance", "data", "init_performance", "init_performance", "init_performance", "init_performance", "init_performance", "CustomError", "CustomError", "init_performance", "init_performance", "HelixExtension", "init_performance", "CustomError", "init_performance", "init_performance", "init_performance", "CustomError", "text", "init_performance", "init_performance", "init_performance", "CustomError", "init_performance", "init_performance", "init_performance", "init_performance", "init_performance", "_a", "_b", "init_performance", "init_performance", "init_performance", "init_performance", "EventEmitter", "init_performance", "init_performance", "init_performance", "init_performance", "CustomError", "init_performance", "init_performance", "TokenInfo", "data", "data", "init_performance", "promise", "resolve", "reject", "init_performance", "AppTokenAuthProvider", "init_performance", "init_performance", "count", "init_performance", "init_performance", "init_performance", "HelixBitsLeaderboardEntry", "data", "HelixBitsLeaderboard", "data", "init_performance", "HelixCheermoteList", "data", "HelixBitsApi", "init_performance", "init_performance", "data", "init_performance", "init_performance", "HelixUserRelation", "data", "init_performance", "data", "init_performance", "HelixPaginatedRequest", "data", "init_performance", "HelixPaginatedRequestWithTotal", "data", "init_performance", "data", "init_performance", "init_performance", "HelixChannel", "data", "init_performance", "HelixChannelEditor", "data", "init_performance", "HelixChannelFollower", "data", "init_performance", "HelixFollowedChannel", "data", "init_performance", "HelixAdSchedule", "init_performance", "HelixSnoozeNextAdResult", "HelixChannelApi", "data", "init_performance", "init_performance", "data", "init_performance", "HelixCustomReward", "data", "init_performance", "HelixCustomRewardRedemption", "data", "HelixChannelPointsApi", "data", "init_performance", "init_performance", "init_performance", "HelixCharityCampaignAmount", "HelixCharityCampaign", "data", "init_performance", "HelixCharityCampaignDonation", "data", "HelixCharityApi", "init_performance", "init_performance", "CustomError", "init_performance", "init_performance", "init_performance", "init_performance", "init_performance", "HelixEmote", "HelixChannelEmote", "data", "init_performance", "init_performance", "HelixChatBadgeVersion", "HelixChatBadgeSet", "data", "init_performance", "HelixChatChatter", "data", "init_performance", "HelixChatSettings", "init_performance", "HelixEmoteFromSet", "data", "init_performance", "HelixPrivilegedChatSettings", "init_performance", "HelixSentChatMessage", "init_performance", "init_performance", "HelixSharedChatSessionParticipant", "data", "HelixSharedChatSession", "data", "init_performance", "HelixUserEmote", "data", "HelixChatApi", "data", "init_performance", "init_performance", "title", "init_performance", "HelixClip", "data", "HelixClipApi", "data", "init_performance", "init_performance", "HelixContentClassificationLabelApi", "data", "init_performance", "init_performance", "init_performance", "HelixDropsEntitlement", "data", "HelixEntitlementApi", "data", "init_performance", "init_performance", "init_performance", "HelixEventSubSubscription", "data", "init_performance", "HelixPaginatedEventSubSubscriptionsRequest", "data", "init_performance", "HelixEventSubConduit", "data", "init_performance", "HelixEventSubConduitShard", "HelixEventSubApi", "version", "data", "init_performance", "init_performance", "version", "data", "init_performance", "HelixChannelReference", "data", "init_performance", "HelixExtensionBitsProduct", "init_performance", "HelixExtensionTransaction", "data", "HelixExtensionsApi", "version", "data", "init_performance", "init_performance", "HelixGame", "data", "HelixGameApi", "data", "init_performance", "init_performance", "HelixGoal", "data", "HelixGoalApi", "data", "init_performance", "init_performance", "init_performance", "init_performance", "HelixHypeTrainContribution", "data", "HelixHypeTrain", "data", "init_performance", "HelixHypeTrainAllTimeHigh", "HelixHypeTrainStatus", "data", "init_performance", "init_performance", "data", "init_performance", "HelixAutoModSettings", "init_performance", "HelixAutoModStatus", "init_performance", "init_performance", "HelixBanUser", "data", "HelixBan", "data", "init_performance", "HelixBlockedTerm", "init_performance", "HelixModeratedChannel", "data", "init_performance", "HelixModerator", "data", "init_performance", "HelixShieldModeStatus", "data", "init_performance", "HelixUnbanRequest", "data", "init_performance", "HelixWarning", "data", "HelixModerationApi", "data", "text", "init_performance", "init_performance", "data", "title", "init_performance", "init_performance", "HelixPollChoice", "HelixPoll", "data", "HelixPollApi", "data", "init_performance", "init_performance", "data", "title", "init_performance", "init_performance", "init_performance", "HelixPredictor", "data", "HelixPredictionOutcome", "data", "HelixPrediction", "data", "HelixPredictionApi", "data", "init_performance", "init_performance", "init_performance", "HelixRaid", "HelixRaidApi", "init_performance", "init_performance", "data", "init_performance", "init_performance", "HelixScheduleSegment", "data", "HelixPaginatedScheduleSegmentRequest", "data", "init_performance", "HelixSchedule", "data", "data", "init_performance", "init_performance", "init_performance", "HelixChannelSearchResult", "data", "HelixSearchApi", "data", "init_performance", "init_performance", "CustomError", "init_performance", "init_performance", "HelixStream", "data", "init_performance", "HelixStreamMarker", "data", "init_performance", "HelixStreamMarkerWithVideo", "data", "HelixStreamApi", "data", "flatten", "init_performance", "init_performance", "init_performance", "init_performance", "init_performance", "HelixUserSubscription", "data", "HelixSubscription", "HelixPaginatedSubscriptionsRequest", "data", "HelixSubscriptionApi", "data", "init_performance", "init_performance", "HelixTeam", "data", "init_performance", "HelixTeamWithUsers", "data", "HelixTeamApi", "data", "init_performance", "init_performance", "init_performance", "init_performance", "init_performance", "HelixInstalledExtension", "data", "HelixInstalledExtensionList", "data", "init_performance", "HelixUserExtension", "init_performance", "init_performance", "HelixUser", "data", "HelixPrivilegedUser", "init_performance", "HelixUserBlock", "data", "HelixUserApi", "data", "init_performance", "init_performance", "HelixVideo", "data", "HelixVideoApi", "data", "init_performance", "init_performance", "HelixWhisperApi", "init_performance", "BaseApiClient", "EventEmitter", "config", "data", "accessToken", "init_performance", "NoContextApiClient", "init_performance", "UserContextApiClient", "config", "ApiClient", "config", "ApiClient", "init_performance", "init_performance", "text", "init_performance", "init_performance", "init_performance", "init_performance", "init_performance", "randomUUID", "init_performance", "init_performance", "init_performance", "data", "randomUUID", "init_performance", "randomUUID", "randomUUID", "data", "init_performance", "randomUUID", "randomUUID", "init_performance", "title", "data", "init_performance", "init_performance", "init_performance", "init_performance", "data", "follows", "Hono", "init_performance", "init_performance", "init_performance", "init"] -} diff --git a/MIGRATION_PLAN.md b/MIGRATION_PLAN.md deleted file mode 100644 index a36ef2d1..00000000 --- a/MIGRATION_PLAN.md +++ /dev/null @@ -1,315 +0,0 @@ -# План миграции на Cloudflare Workers - -## Обзор проекта - -**Текущий стек:** -- Go 1.19+ -- PostgreSQL + Ent ORM -- Polling Telegram Bot -- Standalone приложение с собственным воркером проверки стримов - -**Целевой стек:** -- TypeScript/JavaScript -- Cloudflare Workers + D1 (SQLite) -- Grammy Bot (Telegram) -- Drizzle ORM с паттерном репозиториев -- pnpm как пакетный менеджер - -## Существующие фичи для сохранения - -### 1. База данных (5 таблиц) - -#### Chat -- `id` (UUID) -- `chat_id` (string) - ID чата в Telegram -- `service` (enum: "telegram") -- Уникальный индекс: `chat_id + service` - -#### ChatSettings -- `id` (UUID) -- `chat_id` (UUID FK -> Chat) -- `game_change_notification` (boolean, default: true) -- `title_change_notification` (boolean, default: false) -- `game_and_title_change_notification` (boolean, default: false) -- `offline_notification` (boolean, default: true) -- `image_in_notification` (boolean, default: true) -- `chat_language` (enum: "ru", "en", "uk", default: "en") - -#### Channel -- `id` (UUID) -- `channel_id` (string) - ID канала на Twitch -- `service` (enum: "twitch") -- `is_live` (boolean, default: false) -- `title` (string, nullable) -- `category` (string, nullable) -- `updated_at` (timestamp) -- Уникальный индекс: `channel_id + service` - -#### Follow -- `id` (UUID) -- `channel_id` (UUID FK -> Channel) -- `chat_id` (UUID FK -> Chat) -- Уникальный индекс: `channel_id + chat_id` - -#### Stream -- `id` (string, unique) - ID стрима от Twitch -- `channel_id` (UUID FK -> Channel) -- `titles` (string[], default: []) -- `categories` (string[], default: []) -- `started_at` (timestamp) -- `updated_at` (timestamp) -- `ended_at` (timestamp, nullable) - -### 2. Telegram команды - -#### Пользовательские команды: -- `/start` (aliases: /help, /info, /settings) - главное меню с настройками -- `/follow ` - подписка на Twitch канал -- `/follows` (alias: /unfollow) - список подписок с возможностью отписки (пагинация) -- `/live` - список онлайн стримов из подписок - -#### Административные команды: -- `/broadcast ` - массовая рассылка -- `/change_channel_id ` - изменение ID канала - -#### Интерактивные элементы: -- Callback buttons для настроек (в /start) -- Callback buttons для отписки (в /follows) -- Кнопки пагинации для списка подписок -- Выбор языка через inline-кнопки - -### 3. Система уведомлений - -Проверка стримов каждую минуту (в dev - 10 секунд) с уведомлениями: - -#### При запуске стрима: -- Сообщение с названием, категорией, стримером -- Превью (thumbnail) если включено -- Кнопка отписки - -#### При завершении стрима: -- Сообщение о завершении -- Список категорий за стрим -- Длительность стрима -- Кнопка отписки - -#### Изменения во время стрима: -- Смена категории (если включено) -- Смена названия (если включено) -- Смена категории И названия одновременно (если включено) - -### 4. Интернационализация (i18n) - -Поддержка языков: -- Русский (ru) -- Английский (en) -- Украинский (uk) - -Переводы хранятся в директории `locales/` - -### 5. Twitch API интеграция - -- Получение информации о каналах -- Получение информации о стримах -- Батчинг запросов (chunked requests) -- OAuth авторизация с автоматическим обновлением токена - -### 6. Конфигурация - -Переменные окружения: -- `TWITCH_CLIENTID` - ID приложения Twitch -- `TWITCH_CLIENTSECRET` - Secret приложения Twitch -- `TELEGRAM_TOKEN` - токен Telegram бота -- `TELEGRAM_BOT_ADMINS` - список ID администраторов (через запятую) -- `DATABASE_URL` - URL базы данных (старый PostgreSQL) -- `SENTRY_DSN` - (опционально) для мониторинга ошибок - -## Архитектура Cloudflare Workers решения - -### Workers - -#### 1. **bot-worker** (основной) -- Обработка Telegram Webhook -- Обработка всех команд -- Grammy bot + conversations для multi-step команд -- Использует KV для хранения session данных - -#### 2. **streams-checker-worker** (Cron Worker) -- Запускается каждую минуту (Cron Trigger) -- Проверяет статус стримов через Twitch API -- Отправляет уведомления через Telegram API -- Использует D1 для чтения/записи данных - -### Cloudflare сервисы - -- **D1** - SQLite база данных для всех таблиц -- **KV** (опционально) - для session storage Grammy -- **Cron Triggers** - для периодической проверки стримов -- **Workers Analytics** (опционально) - для мониторинга - -## Структура проекта - -``` -twitch-notifier/ -├── src/ -│ ├── bot/ # Telegram bot -│ │ ├── index.ts # Entry point для bot-worker -│ │ ├── bot.ts # Grammy bot инициализация -│ │ ├── commands/ # Команды -│ │ │ ├── start.ts -│ │ │ ├── follow.ts -│ │ │ ├── follows.ts -│ │ │ ├── live.ts -│ │ │ ├── broadcast.ts -│ │ │ └── change-channel-id.ts -│ │ ├── keyboards/ # Inline клавиатуры -│ │ │ ├── settings.ts -│ │ │ ├── language.ts -│ │ │ └── follows.ts -│ │ └── middlewares/ # Миддлвары -│ │ ├── logger.ts -│ │ ├── admin.ts -│ │ └── chat.ts -│ ├── checker/ # Streams checker -│ │ ├── index.ts # Entry point для checker-worker -│ │ └── checker.ts # Логика проверки стримов -│ ├── db/ # База данных -│ │ ├── schema.ts # Drizzle схемы -│ │ ├── migrations/ # SQL миграции -│ │ └── repositories/ # Паттерн репозиториев -│ │ ├── chat.repository.ts -│ │ ├── channel.repository.ts -│ │ ├── follow.repository.ts -│ │ └── stream.repository.ts -│ ├── services/ # Сервисы -│ │ ├── twitch.service.ts # Twitch API клиент -│ │ ├── telegram.service.ts # Telegram message sender -│ │ └── i18n.service.ts # Интернационализация -│ ├── types/ # TypeScript типы -│ │ ├── env.ts -│ │ └── index.ts -│ └── utils/ # Утилиты -│ ├── thumbnail.ts -│ └── helpers.ts -├── locales/ # Переводы (скопировать из Go проекта) -│ ├── en.json -│ ├── ru.json -│ └── uk.json -├── migrations/ # Скрипты миграции -│ └── migrate-users.ts # Скрипт миграции из PostgreSQL в D1 -├── drizzle.config.ts # Конфигурация Drizzle -├── wrangler.toml # Конфигурация Cloudflare Workers -├── package.json -├── tsconfig.json -└── README.md -``` - -## План реализации - -### Этап 1: Настройка проекта ✓ -1. Инициализация проекта с pnpm -2. Установка зависимостей: - - `wrangler` - Cloudflare CLI - - `grammy` + `@grammyjs/conversations` - Telegram bot - - `drizzle-orm` + `drizzle-kit` - ORM - - Другие зависимости -3. Создание структуры директорий -4. Настройка TypeScript -5. Настройка wrangler.toml для обоих workers - -### Этап 2: База данных ✓ -1. Создание Drizzle схем на основе Ent схем -2. Имплементация паттерна репозиториев -3. Создание D1 базы через Wrangler -4. Генерация и применение миграций - -### Этап 3: Сервисы ✓ -1. Twitch API клиент с OAuth -2. Telegram message sender -3. i18n сервис (адаптация с Go проекта) -4. Thumbnail builder - -### Этап 4: Telegram Bot ✓ -1. Настройка Grammy bot -2. Имплементация всех команд -3. Создание inline клавиатур -4. Настройка миддлваров (логгирование, admin check, chat persistence) -5. Настройка conversations для multi-step команд (/follow) - -### Этап 5: Streams Checker Worker ✓ -1. Имплементация логики проверки стримов -2. Отправка уведомлений -3. Настройка Cron Trigger - -### Этап 6: Деплой и тестирование ✓ -1. Деплой bot-worker -2. Деплой streams-checker-worker -3. Настройка Telegram Webhook -4. Тестирование всех команд -5. Тестирование уведомлений - -### Этап 7: Миграция данных ✓ -1. Создание скрипта миграции из PostgreSQL в D1 -2. Тестовая миграция -3. Продакшн миграция - -## Скрипт миграции данных - -Создать отдельный скрипт `migrations/migrate-users.ts` который: -1. Подключается к старой PostgreSQL базе -2. Читает все данные из таблиц (Chat, ChatSettings, Channel, Follow, Stream) -3. Трансформирует данные если нужно -4. Записывает в D1 через Wrangler API или D1 HTTP API - -Особенности миграции: -- UUID в PostgreSQL -> сохраняются как есть (D1 поддерживает текстовые UUID) -- Массивы (titles, categories) -> JSON в SQLite -- Timestamps -> ISO 8601 строки в SQLite -- Enum values -> остаются как есть - -## Отличия от Go версии - -### Архитектурные: -- **Polling -> Webhook**: Cloudflare Workers работает по модели request/response, используем Telegram Webhook вместо Long Polling -- **Отдельный воркер для проверки стримов**: вместо горутины - отдельный Worker с Cron Trigger -- **Serverless**: нет постоянно запущенного процесса, оплата за выполнение -- **SQLite вместо PostgreSQL**: D1 - управляемая SQLite база - -### Технические: -- **Grammy вместо go-tg**: официальная TypeScript библиотека для Telegram -- **Drizzle вместо Ent**: type-safe ORM для TypeScript -- **Паттерн репозиториев**: изоляция логики БД для простой замены ORM в будущем - -## Следующие шаги - -После прочтения этого плана: - -1. Убедитесь что у вас есть: - - Аккаунт Cloudflare (Workers Paid plan для Cron Triggers) - - Доступ к текущей PostgreSQL базе для миграции - -2. Дайте подтверждение для начала реализации: - ``` - Да, начинаем! Начни с Этапа 1. - ``` - -3. Я буду реализовывать каждый этап последовательно, показывая прогресс - -## Важные замечания - -- Cloudflare Workers Free tier имеет лимиты (100k запросов/день) -- Cron Triggers требуют Workers Paid plan ($5/месяц) -- D1 пока в beta, но стабильна для продакшн использования -- Webhook требует HTTPS домен (можно использовать workers.dev) -- Grammy conversations требуют хранилище для session (используем KV или D1) - -## Вопросы для уточнения - -1. Есть ли у вас уже Cloudflare аккаунт? -2. Сколько пользователей у текущего бота? (для оценки нагрузки) -3. Нужна ли интеграция с Sentry для мониторинга? -4. Хотите ли сохранить историю стримов (таблица Stream) или только активные? - ---- - -**Готовы начать миграцию?** Дайте команду и я начну с Этапа 1! diff --git a/drizzle/0000_init.sql b/drizzle/0000_init.sql deleted file mode 100644 index 2f0f7b67..00000000 --- a/drizzle/0000_init.sql +++ /dev/null @@ -1,50 +0,0 @@ -CREATE TABLE `channels` ( - `id` text PRIMARY KEY NOT NULL, - `channel_id` text NOT NULL, - `service` text DEFAULT 'twitch' NOT NULL, - `is_live` integer DEFAULT false NOT NULL, - `title` text, - `category` text, - `updated_at` text -); ---> statement-breakpoint -CREATE TABLE `chat_settings` ( - `id` text PRIMARY KEY NOT NULL, - `chat_id` text NOT NULL, - `game_change_notification` integer DEFAULT true NOT NULL, - `title_change_notification` integer DEFAULT false NOT NULL, - `game_and_title_change_notification` integer DEFAULT false NOT NULL, - `offline_notification` integer DEFAULT true NOT NULL, - `image_in_notification` integer DEFAULT true NOT NULL, - `language` text DEFAULT 'en' NOT NULL, - FOREIGN KEY (`chat_id`) REFERENCES `chats`(`id`) ON UPDATE no action ON DELETE cascade -); ---> statement-breakpoint -CREATE UNIQUE INDEX `chat_settings_chat_id_unique` ON `chat_settings` (`chat_id`);--> statement-breakpoint -CREATE TABLE `chats` ( - `id` text PRIMARY KEY NOT NULL, - `chat_id` text NOT NULL, - `service` text DEFAULT 'telegram' NOT NULL -); ---> statement-breakpoint -CREATE TABLE `follows` ( - `id` text PRIMARY KEY NOT NULL, - `channel_id` text NOT NULL, - `chat_id` text NOT NULL, - FOREIGN KEY (`channel_id`) REFERENCES `channels`(`id`) ON UPDATE no action ON DELETE cascade, - FOREIGN KEY (`chat_id`) REFERENCES `chats`(`id`) ON UPDATE no action ON DELETE cascade -); ---> statement-breakpoint -CREATE TABLE `streams` ( - `id` text PRIMARY KEY NOT NULL, - `channel_id` text NOT NULL, - `is_live` integer DEFAULT true NOT NULL, - `title` text, - `category` text, - `titles` text DEFAULT '[]' NOT NULL, - `categories` text DEFAULT '[]' NOT NULL, - `started_at` text, - `updated_at` text, - `ended_at` text, - FOREIGN KEY (`channel_id`) REFERENCES `channels`(`id`) ON UPDATE no action ON DELETE cascade -); diff --git a/drizzle/meta/0000_snapshot.json b/drizzle/meta/0000_snapshot.json deleted file mode 100644 index 5ce87c82..00000000 --- a/drizzle/meta/0000_snapshot.json +++ /dev/null @@ -1,360 +0,0 @@ -{ - "version": "6", - "dialect": "sqlite", - "id": "080aa910-8403-4fd5-8fb8-a1b4af4465dc", - "prevId": "00000000-0000-0000-0000-000000000000", - "tables": { - "channels": { - "name": "channels", - "columns": { - "id": { - "name": "id", - "type": "text", - "primaryKey": true, - "notNull": true, - "autoincrement": false - }, - "channel_id": { - "name": "channel_id", - "type": "text", - "primaryKey": false, - "notNull": true, - "autoincrement": false - }, - "service": { - "name": "service", - "type": "text", - "primaryKey": false, - "notNull": true, - "autoincrement": false, - "default": "'twitch'" - }, - "is_live": { - "name": "is_live", - "type": "integer", - "primaryKey": false, - "notNull": true, - "autoincrement": false, - "default": false - }, - "title": { - "name": "title", - "type": "text", - "primaryKey": false, - "notNull": false, - "autoincrement": false - }, - "category": { - "name": "category", - "type": "text", - "primaryKey": false, - "notNull": false, - "autoincrement": false - }, - "updated_at": { - "name": "updated_at", - "type": "text", - "primaryKey": false, - "notNull": false, - "autoincrement": false - } - }, - "indexes": {}, - "foreignKeys": {}, - "compositePrimaryKeys": {}, - "uniqueConstraints": {}, - "checkConstraints": {} - }, - "chat_settings": { - "name": "chat_settings", - "columns": { - "id": { - "name": "id", - "type": "text", - "primaryKey": true, - "notNull": true, - "autoincrement": false - }, - "chat_id": { - "name": "chat_id", - "type": "text", - "primaryKey": false, - "notNull": true, - "autoincrement": false - }, - "game_change_notification": { - "name": "game_change_notification", - "type": "integer", - "primaryKey": false, - "notNull": true, - "autoincrement": false, - "default": true - }, - "title_change_notification": { - "name": "title_change_notification", - "type": "integer", - "primaryKey": false, - "notNull": true, - "autoincrement": false, - "default": false - }, - "game_and_title_change_notification": { - "name": "game_and_title_change_notification", - "type": "integer", - "primaryKey": false, - "notNull": true, - "autoincrement": false, - "default": false - }, - "offline_notification": { - "name": "offline_notification", - "type": "integer", - "primaryKey": false, - "notNull": true, - "autoincrement": false, - "default": true - }, - "image_in_notification": { - "name": "image_in_notification", - "type": "integer", - "primaryKey": false, - "notNull": true, - "autoincrement": false, - "default": true - }, - "language": { - "name": "language", - "type": "text", - "primaryKey": false, - "notNull": true, - "autoincrement": false, - "default": "'en'" - } - }, - "indexes": { - "chat_settings_chat_id_unique": { - "name": "chat_settings_chat_id_unique", - "columns": [ - "chat_id" - ], - "isUnique": true - } - }, - "foreignKeys": { - "chat_settings_chat_id_chats_id_fk": { - "name": "chat_settings_chat_id_chats_id_fk", - "tableFrom": "chat_settings", - "tableTo": "chats", - "columnsFrom": [ - "chat_id" - ], - "columnsTo": [ - "id" - ], - "onDelete": "cascade", - "onUpdate": "no action" - } - }, - "compositePrimaryKeys": {}, - "uniqueConstraints": {}, - "checkConstraints": {} - }, - "chats": { - "name": "chats", - "columns": { - "id": { - "name": "id", - "type": "text", - "primaryKey": true, - "notNull": true, - "autoincrement": false - }, - "chat_id": { - "name": "chat_id", - "type": "text", - "primaryKey": false, - "notNull": true, - "autoincrement": false - }, - "service": { - "name": "service", - "type": "text", - "primaryKey": false, - "notNull": true, - "autoincrement": false, - "default": "'telegram'" - } - }, - "indexes": {}, - "foreignKeys": {}, - "compositePrimaryKeys": {}, - "uniqueConstraints": {}, - "checkConstraints": {} - }, - "follows": { - "name": "follows", - "columns": { - "id": { - "name": "id", - "type": "text", - "primaryKey": true, - "notNull": true, - "autoincrement": false - }, - "channel_id": { - "name": "channel_id", - "type": "text", - "primaryKey": false, - "notNull": true, - "autoincrement": false - }, - "chat_id": { - "name": "chat_id", - "type": "text", - "primaryKey": false, - "notNull": true, - "autoincrement": false - } - }, - "indexes": {}, - "foreignKeys": { - "follows_channel_id_channels_id_fk": { - "name": "follows_channel_id_channels_id_fk", - "tableFrom": "follows", - "tableTo": "channels", - "columnsFrom": [ - "channel_id" - ], - "columnsTo": [ - "id" - ], - "onDelete": "cascade", - "onUpdate": "no action" - }, - "follows_chat_id_chats_id_fk": { - "name": "follows_chat_id_chats_id_fk", - "tableFrom": "follows", - "tableTo": "chats", - "columnsFrom": [ - "chat_id" - ], - "columnsTo": [ - "id" - ], - "onDelete": "cascade", - "onUpdate": "no action" - } - }, - "compositePrimaryKeys": {}, - "uniqueConstraints": {}, - "checkConstraints": {} - }, - "streams": { - "name": "streams", - "columns": { - "id": { - "name": "id", - "type": "text", - "primaryKey": true, - "notNull": true, - "autoincrement": false - }, - "channel_id": { - "name": "channel_id", - "type": "text", - "primaryKey": false, - "notNull": true, - "autoincrement": false - }, - "is_live": { - "name": "is_live", - "type": "integer", - "primaryKey": false, - "notNull": true, - "autoincrement": false, - "default": true - }, - "title": { - "name": "title", - "type": "text", - "primaryKey": false, - "notNull": false, - "autoincrement": false - }, - "category": { - "name": "category", - "type": "text", - "primaryKey": false, - "notNull": false, - "autoincrement": false - }, - "titles": { - "name": "titles", - "type": "text", - "primaryKey": false, - "notNull": true, - "autoincrement": false, - "default": "'[]'" - }, - "categories": { - "name": "categories", - "type": "text", - "primaryKey": false, - "notNull": true, - "autoincrement": false, - "default": "'[]'" - }, - "started_at": { - "name": "started_at", - "type": "text", - "primaryKey": false, - "notNull": false, - "autoincrement": false - }, - "updated_at": { - "name": "updated_at", - "type": "text", - "primaryKey": false, - "notNull": false, - "autoincrement": false - }, - "ended_at": { - "name": "ended_at", - "type": "text", - "primaryKey": false, - "notNull": false, - "autoincrement": false - } - }, - "indexes": {}, - "foreignKeys": { - "streams_channel_id_channels_id_fk": { - "name": "streams_channel_id_channels_id_fk", - "tableFrom": "streams", - "tableTo": "channels", - "columnsFrom": [ - "channel_id" - ], - "columnsTo": [ - "id" - ], - "onDelete": "cascade", - "onUpdate": "no action" - } - }, - "compositePrimaryKeys": {}, - "uniqueConstraints": {}, - "checkConstraints": {} - } - }, - "views": {}, - "enums": {}, - "_meta": { - "schemas": {}, - "tables": {}, - "columns": {} - }, - "internal": { - "indexes": {} - } -} \ No newline at end of file diff --git a/drizzle/meta/0001_snapshot.json b/drizzle/meta/0001_snapshot.json deleted file mode 100644 index 5401acb4..00000000 --- a/drizzle/meta/0001_snapshot.json +++ /dev/null @@ -1,398 +0,0 @@ -{ - "version": "6", - "dialect": "sqlite", - "id": "8e53b4b2-0bbe-4525-8758-07164adab3f9", - "prevId": "080aa910-8403-4fd5-8fb8-a1b4af4465dc", - "tables": { - "channels": { - "name": "channels", - "columns": { - "id": { - "name": "id", - "type": "text", - "primaryKey": true, - "notNull": true, - "autoincrement": false - }, - "channel_id": { - "name": "channel_id", - "type": "text", - "primaryKey": false, - "notNull": true, - "autoincrement": false - }, - "service": { - "name": "service", - "type": "text", - "primaryKey": false, - "notNull": true, - "autoincrement": false, - "default": "'twitch'" - }, - "is_live": { - "name": "is_live", - "type": "integer", - "primaryKey": false, - "notNull": true, - "autoincrement": false, - "default": false - }, - "title": { - "name": "title", - "type": "text", - "primaryKey": false, - "notNull": false, - "autoincrement": false - }, - "category": { - "name": "category", - "type": "text", - "primaryKey": false, - "notNull": false, - "autoincrement": false - }, - "updated_at": { - "name": "updated_at", - "type": "text", - "primaryKey": false, - "notNull": false, - "autoincrement": false - } - }, - "indexes": {}, - "foreignKeys": {}, - "compositePrimaryKeys": {}, - "uniqueConstraints": {}, - "checkConstraints": {} - }, - "chat_settings": { - "name": "chat_settings", - "columns": { - "id": { - "name": "id", - "type": "text", - "primaryKey": true, - "notNull": true, - "autoincrement": false - }, - "chat_id": { - "name": "chat_id", - "type": "text", - "primaryKey": false, - "notNull": true, - "autoincrement": false - }, - "game_change_notification": { - "name": "game_change_notification", - "type": "integer", - "primaryKey": false, - "notNull": true, - "autoincrement": false, - "default": true - }, - "title_change_notification": { - "name": "title_change_notification", - "type": "integer", - "primaryKey": false, - "notNull": true, - "autoincrement": false, - "default": false - }, - "game_and_title_change_notification": { - "name": "game_and_title_change_notification", - "type": "integer", - "primaryKey": false, - "notNull": true, - "autoincrement": false, - "default": false - }, - "offline_notification": { - "name": "offline_notification", - "type": "integer", - "primaryKey": false, - "notNull": true, - "autoincrement": false, - "default": true - }, - "image_in_notification": { - "name": "image_in_notification", - "type": "integer", - "primaryKey": false, - "notNull": true, - "autoincrement": false, - "default": true - }, - "language": { - "name": "language", - "type": "text", - "primaryKey": false, - "notNull": true, - "autoincrement": false, - "default": "'en'" - } - }, - "indexes": { - "chat_settings_chat_id_unique": { - "name": "chat_settings_chat_id_unique", - "columns": [ - "chat_id" - ], - "isUnique": true - } - }, - "foreignKeys": { - "chat_settings_chat_id_chats_id_fk": { - "name": "chat_settings_chat_id_chats_id_fk", - "tableFrom": "chat_settings", - "tableTo": "chats", - "columnsFrom": [ - "chat_id" - ], - "columnsTo": [ - "id" - ], - "onDelete": "cascade", - "onUpdate": "no action" - } - }, - "compositePrimaryKeys": {}, - "uniqueConstraints": {}, - "checkConstraints": {} - }, - "chats": { - "name": "chats", - "columns": { - "id": { - "name": "id", - "type": "text", - "primaryKey": true, - "notNull": true, - "autoincrement": false - }, - "chat_id": { - "name": "chat_id", - "type": "text", - "primaryKey": false, - "notNull": true, - "autoincrement": false - }, - "service": { - "name": "service", - "type": "text", - "primaryKey": false, - "notNull": true, - "autoincrement": false, - "default": "'telegram'" - } - }, - "indexes": {}, - "foreignKeys": {}, - "compositePrimaryKeys": {}, - "uniqueConstraints": {}, - "checkConstraints": {} - }, - "follows": { - "name": "follows", - "columns": { - "id": { - "name": "id", - "type": "text", - "primaryKey": true, - "notNull": true, - "autoincrement": false - }, - "channel_id": { - "name": "channel_id", - "type": "text", - "primaryKey": false, - "notNull": true, - "autoincrement": false - }, - "chat_id": { - "name": "chat_id", - "type": "text", - "primaryKey": false, - "notNull": true, - "autoincrement": false - } - }, - "indexes": {}, - "foreignKeys": { - "follows_channel_id_channels_id_fk": { - "name": "follows_channel_id_channels_id_fk", - "tableFrom": "follows", - "tableTo": "channels", - "columnsFrom": [ - "channel_id" - ], - "columnsTo": [ - "id" - ], - "onDelete": "cascade", - "onUpdate": "no action" - }, - "follows_chat_id_chats_id_fk": { - "name": "follows_chat_id_chats_id_fk", - "tableFrom": "follows", - "tableTo": "chats", - "columnsFrom": [ - "chat_id" - ], - "columnsTo": [ - "id" - ], - "onDelete": "cascade", - "onUpdate": "no action" - } - }, - "compositePrimaryKeys": {}, - "uniqueConstraints": {}, - "checkConstraints": {} - }, - "sessions": { - "name": "sessions", - "columns": { - "key": { - "name": "key", - "type": "text", - "primaryKey": true, - "notNull": true, - "autoincrement": false - }, - "value": { - "name": "value", - "type": "text", - "primaryKey": false, - "notNull": true, - "autoincrement": false - }, - "expires_at": { - "name": "expires_at", - "type": "integer", - "primaryKey": false, - "notNull": false, - "autoincrement": false - }, - "updated_at": { - "name": "updated_at", - "type": "text", - "primaryKey": false, - "notNull": false, - "autoincrement": false - } - }, - "indexes": {}, - "foreignKeys": {}, - "compositePrimaryKeys": {}, - "uniqueConstraints": {}, - "checkConstraints": {} - }, - "streams": { - "name": "streams", - "columns": { - "id": { - "name": "id", - "type": "text", - "primaryKey": true, - "notNull": true, - "autoincrement": false - }, - "channel_id": { - "name": "channel_id", - "type": "text", - "primaryKey": false, - "notNull": true, - "autoincrement": false - }, - "is_live": { - "name": "is_live", - "type": "integer", - "primaryKey": false, - "notNull": true, - "autoincrement": false, - "default": true - }, - "title": { - "name": "title", - "type": "text", - "primaryKey": false, - "notNull": false, - "autoincrement": false - }, - "category": { - "name": "category", - "type": "text", - "primaryKey": false, - "notNull": false, - "autoincrement": false - }, - "titles": { - "name": "titles", - "type": "text", - "primaryKey": false, - "notNull": true, - "autoincrement": false, - "default": "'[]'" - }, - "categories": { - "name": "categories", - "type": "text", - "primaryKey": false, - "notNull": true, - "autoincrement": false, - "default": "'[]'" - }, - "started_at": { - "name": "started_at", - "type": "text", - "primaryKey": false, - "notNull": false, - "autoincrement": false - }, - "updated_at": { - "name": "updated_at", - "type": "text", - "primaryKey": false, - "notNull": false, - "autoincrement": false - }, - "ended_at": { - "name": "ended_at", - "type": "text", - "primaryKey": false, - "notNull": false, - "autoincrement": false - } - }, - "indexes": {}, - "foreignKeys": { - "streams_channel_id_channels_id_fk": { - "name": "streams_channel_id_channels_id_fk", - "tableFrom": "streams", - "tableTo": "channels", - "columnsFrom": [ - "channel_id" - ], - "columnsTo": [ - "id" - ], - "onDelete": "cascade", - "onUpdate": "no action" - } - }, - "compositePrimaryKeys": {}, - "uniqueConstraints": {}, - "checkConstraints": {} - } - }, - "views": {}, - "enums": {}, - "_meta": { - "schemas": {}, - "tables": {}, - "columns": {} - }, - "internal": { - "indexes": {} - } -} \ No newline at end of file diff --git a/drizzle/meta/_journal.json b/drizzle/meta/_journal.json deleted file mode 100644 index c15c5130..00000000 --- a/drizzle/meta/_journal.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "version": "7", - "dialect": "sqlite", - "entries": [ - { - "idx": 0, - "version": "6", - "when": 1773043588513, - "tag": "0000_init", - "breakpoints": true - }, - { - "idx": 1, - "version": "6", - "when": 1773045439236, - "tag": "0001_loose_crystal", - "breakpoints": true - } - ] -} \ No newline at end of file diff --git a/ent/generate.go b/ent/generate.go deleted file mode 100644 index 8d3fdfdc..00000000 --- a/ent/generate.go +++ /dev/null @@ -1,3 +0,0 @@ -package ent - -//go:generate go run -mod=mod entgo.io/ent/cmd/ent generate ./schema diff --git a/ent/migrate/migrations/20230327181912_initial.sql b/ent/migrate/migrations/20230327181912_initial.sql deleted file mode 100644 index 9a284d1b..00000000 --- a/ent/migrate/migrations/20230327181912_initial.sql +++ /dev/null @@ -1,62 +0,0 @@ --- create "chats" table -CREATE TABLE "chats" -( - "id" uuid NOT NULL, - "chat_id" character varying NOT NULL, - "service" character varying NOT NULL, - PRIMARY KEY ("id") -); --- create index "chat_chat_id_service" to table: "chats" -CREATE UNIQUE INDEX "chat_chat_id_service" ON "chats" ("chat_id", "service"); --- create "chat_settings" table -CREATE TABLE "chat_settings" -( - "id" uuid NOT NULL, - "game_change_notification" boolean NOT NULL DEFAULT true, - "offline_notification" boolean NOT NULL DEFAULT true, - "chat_language" character varying NOT NULL DEFAULT 'en', - "chat_id" uuid NOT NULL, - PRIMARY KEY ("id"), - CONSTRAINT "chat_settings_chats_settings" FOREIGN KEY ("chat_id") REFERENCES "chats" ("id") ON UPDATE NO ACTION ON DELETE NO ACTION -); --- create index "chat_settings_chat_id_key" to table: "chat_settings" -CREATE UNIQUE INDEX "chat_settings_chat_id_key" ON "chat_settings" ("chat_id"); --- create "channels" table -CREATE TABLE "channels" -( - "id" uuid NOT NULL, - "channel_id" character varying NOT NULL, - "service" character varying NOT NULL, - "is_live" boolean NOT NULL DEFAULT false, - "title" character varying NULL, - "category" character varying NULL, - "updated_at" timestamptz NULL, - PRIMARY KEY ("id") -); --- create index "channel_channel_id_service" to table: "channels" -CREATE UNIQUE INDEX "channel_channel_id_service" ON "channels" ("channel_id", "service"); --- create "follows" table -CREATE TABLE "follows" -( - "id" uuid NOT NULL, - "channel_id" uuid NOT NULL, - "chat_id" uuid NOT NULL, - PRIMARY KEY ("id"), - CONSTRAINT "follows_channels_follows" FOREIGN KEY ("channel_id") REFERENCES "channels" ("id") ON UPDATE NO ACTION ON DELETE NO ACTION, - CONSTRAINT "follows_chats_follows" FOREIGN KEY ("chat_id") REFERENCES "chats" ("id") ON UPDATE NO ACTION ON DELETE NO ACTION -); --- create index "follow_channel_id_chat_id" to table: "follows" -CREATE UNIQUE INDEX "follow_channel_id_chat_id" ON "follows" ("channel_id", "chat_id"); --- create "streams" table -CREATE TABLE "streams" -( - "id" character varying NOT NULL, - "titles" text[] NULL, - "categories" text[] NULL, - "started_at" timestamptz NULL, - "updated_at" timestamptz NULL, - "ended_at" timestamptz NULL, - "channel_id" uuid NOT NULL, - PRIMARY KEY ("id"), - CONSTRAINT "streams_channels_streams" FOREIGN KEY ("channel_id") REFERENCES "channels" ("id") ON UPDATE NO ACTION ON DELETE NO ACTION -); diff --git a/ent/migrate/migrations/20230401125338_TitleChangeNotification.sql b/ent/migrate/migrations/20230401125338_TitleChangeNotification.sql deleted file mode 100644 index 1310ab25..00000000 --- a/ent/migrate/migrations/20230401125338_TitleChangeNotification.sql +++ /dev/null @@ -1,2 +0,0 @@ --- Modify "chat_settings" table -ALTER TABLE "chat_settings" ADD COLUMN "title_change_notification" boolean NOT NULL DEFAULT false; diff --git a/ent/migrate/migrations/20230506114213_EnableImageInNotification.sql b/ent/migrate/migrations/20230506114213_EnableImageInNotification.sql deleted file mode 100644 index 1347b67a..00000000 --- a/ent/migrate/migrations/20230506114213_EnableImageInNotification.sql +++ /dev/null @@ -1,2 +0,0 @@ --- Modify "chat_settings" table -ALTER TABLE "chat_settings" ADD COLUMN "image_in_notification" boolean NOT NULL DEFAULT true; diff --git a/ent/migrate/migrations/20230521162457_GameAndTitleChangeNotificationSetting.sql b/ent/migrate/migrations/20230521162457_GameAndTitleChangeNotificationSetting.sql deleted file mode 100644 index 4a4a78f1..00000000 --- a/ent/migrate/migrations/20230521162457_GameAndTitleChangeNotificationSetting.sql +++ /dev/null @@ -1,2 +0,0 @@ --- Modify "chat_settings" table -ALTER TABLE "chat_settings" ADD COLUMN "game_and_title_change_notification" boolean NOT NULL DEFAULT false; diff --git a/ent/migrate/migrations/atlas.sum b/ent/migrate/migrations/atlas.sum deleted file mode 100644 index 63de8f2f..00000000 --- a/ent/migrate/migrations/atlas.sum +++ /dev/null @@ -1,5 +0,0 @@ -h1:5dIiqHm4gM6G6fF/AjBxNMcJBJYgK25xeMdiqHT0XMk= -20230327181912_initial.sql h1:L6nniWh3O35p6lwgIG+NrRkkU2n2iG48Be5/zfPAz0I= -20230401125338_TitleChangeNotification.sql h1:9u5qCYBNNL6RHtLdcW691tRhYyli7/pG2kBxYuHs1fA= -20230506114213_EnableImageInNotification.sql h1:cGbFYJRVhaB3swtBPyOmw627aemnTVRd6HByCSJa0OQ= -20230521162457_GameAndTitleChangeNotificationSetting.sql h1:g1bUjbU8y2uGqbiDh89URK3QWv+XBRYC4rwsW6Zu408= diff --git a/ent/schema/channel.go b/ent/schema/channel.go deleted file mode 100644 index 11764532..00000000 --- a/ent/schema/channel.go +++ /dev/null @@ -1,50 +0,0 @@ -package schema - -import ( - "entgo.io/ent" - "entgo.io/ent/schema/edge" - "entgo.io/ent/schema/field" - "entgo.io/ent/schema/index" - "github.com/google/uuid" - "time" -) - -type Channel struct { - ent.Schema -} - -type ChannelService string - -func (c ChannelService) String() string { - return string(c) -} - -const ( - Twitch ChannelService = "twitch" -) - -func (Channel) Fields() []ent.Field { - return []ent.Field{ - field.UUID("id", uuid.UUID{}).Default(uuid.New), - field.String("channel_id"), - field.Enum("service").Values(Twitch.String()), - field.Bool("is_live").Default(false), - field.String("title").Nillable().Optional(), - field.String("category").Nillable().Optional(), - field.Time("updated_at").Nillable().Optional().Default(nil).UpdateDefault(time.Now().UTC), - } -} - -func (Channel) Indexes() []ent.Index { - return []ent.Index{ - index.Fields("channel_id", "service"). - Unique(), - } -} - -func (Channel) Edges() []ent.Edge { - return []ent.Edge{ - edge.To("follows", Follow.Type), - edge.To("streams", Stream.Type), - } -} diff --git a/ent/schema/chat.go b/ent/schema/chat.go deleted file mode 100644 index 3bd9378e..00000000 --- a/ent/schema/chat.go +++ /dev/null @@ -1,50 +0,0 @@ -package schema - -import ( - "entgo.io/ent" - "entgo.io/ent/schema/edge" - "entgo.io/ent/schema/field" - "entgo.io/ent/schema/index" - "github.com/google/uuid" -) - -type Chat struct { - ent.Schema -} - -type ChatService string - -func (c ChatService) String() string { - return string(c) -} - -func (ChatService) Values() []string { - return []string{Telegram.String()} -} - -const ( - Telegram ChatService = "telegram" -) - -func (Chat) Fields() []ent.Field { - return []ent.Field{ - field.UUID("id", uuid.UUID{}).Default(uuid.New), - field.String("chat_id"), - field.Enum("service").Values(Telegram.String()), - } -} - -func (Chat) Indexes() []ent.Index { - return []ent.Index{ - index.Fields("chat_id", "service"). - Unique(), - } -} - -func (Chat) Edges() []ent.Edge { - return []ent.Edge{ - edge.To("settings", ChatSettings.Type).Unique(), - //edge.To("id", ChatSettings.Type).Unique().Required(), - edge.To("follows", Follow.Type), - } -} diff --git a/ent/schema/chat_settings.go b/ent/schema/chat_settings.go deleted file mode 100644 index 808b7bb2..00000000 --- a/ent/schema/chat_settings.go +++ /dev/null @@ -1,49 +0,0 @@ -package schema - -import ( - "entgo.io/ent" - "entgo.io/ent/schema/edge" - "entgo.io/ent/schema/field" - "github.com/google/uuid" -) - -type ChatSettings struct { - ent.Schema -} - -type ChatLanguage string - -const ( - ChatLanguageRu ChatLanguage = "ru" - ChatLanguageEn ChatLanguage = "en" - ChatLanguageUk ChatLanguage = "uk" -) - -func (c ChatLanguage) String() string { - return string(c) -} - -func (ChatSettings) Fields() []ent.Field { - return []ent.Field{ - field.UUID("id", uuid.UUID{}).Default(uuid.New), - field.Bool("game_change_notification").Default(true), - field.Bool("title_change_notification").Default(false), - field.Bool("game_and_title_change_notification").Default(false), - field.Bool("offline_notification").Default(true), - field.Bool("image_in_notification").Default(true), - field.Enum("chat_language"). - Values(ChatLanguageRu.String(), ChatLanguageEn.String(), ChatLanguageUk.String()). - Default(ChatLanguageEn.String()), - field.UUID("chat_id", uuid.UUID{}), - } -} - -func (ChatSettings) Edges() []ent.Edge { - return []ent.Edge{ - edge.From("chat", Chat.Type). - Ref("settings"). - Unique(). - Field("chat_id"). - Required(), - } -} diff --git a/ent/schema/follow.go b/ent/schema/follow.go deleted file mode 100644 index c49e10c2..00000000 --- a/ent/schema/follow.go +++ /dev/null @@ -1,43 +0,0 @@ -package schema - -import ( - "entgo.io/ent" - "entgo.io/ent/schema/edge" - "entgo.io/ent/schema/field" - "entgo.io/ent/schema/index" - "github.com/google/uuid" -) - -type Follow struct { - ent.Schema -} - -func (Follow) Fields() []ent.Field { - return []ent.Field{ - field.UUID("id", uuid.UUID{}).Default(uuid.New), - field.UUID("channel_id", uuid.UUID{}), - field.UUID("chat_id", uuid.UUID{}), - } -} - -func (Follow) Edges() []ent.Edge { - return []ent.Edge{ - edge.From("channel", Channel.Type). - Required(). - Ref("follows"). - Unique(). - Field("channel_id"), - edge.From("chat", Chat.Type). - Required(). - Ref("follows"). - Unique(). - Field("chat_id"), - } -} - -func (Follow) Indexes() []ent.Index { - return []ent.Index{ - index.Fields("channel_id", "chat_id"). - Unique(), - } -} diff --git a/ent/schema/stream.go b/ent/schema/stream.go deleted file mode 100644 index 2d8681b4..00000000 --- a/ent/schema/stream.go +++ /dev/null @@ -1,60 +0,0 @@ -package schema - -import ( - "entgo.io/ent" - "entgo.io/ent/dialect" - "entgo.io/ent/schema/edge" - "entgo.io/ent/schema/field" - "github.com/google/uuid" - "github.com/lib/pq" - "time" -) - -type Stream struct { - ent.Schema -} - -func (Stream) Fields() []ent.Field { - return []ent.Field{ - field.String("id").Unique().Immutable(), - field.UUID("channel_id", uuid.UUID{}), - - field.Other("titles", pq.StringArray{}). - SchemaType(map[string]string{ - dialect.Postgres: "text[]", - dialect.SQLite: "JSON", - }). - Default(pq.StringArray{}). - Optional(), - //SchemaType(map[string]string{ - // "postgres": "text[]", - // "sqlite": "text[]", - //}), - field.Other("categories", pq.StringArray{}). - SchemaType(map[string]string{ - dialect.Postgres: "text[]", - dialect.SQLite: "JSON", - }). - Default(pq.StringArray{}). - Optional(), - - //SchemaType(map[string]string{ - // "postgres": "text[]", - // "sqlite": "text[]", - //}), - - field.Time("started_at").Optional().Default(time.Now().UTC), - field.Time("updated_at").Nillable().Optional().Default(nil).UpdateDefault(time.Now().UTC), - field.Time("ended_at").Nillable().Optional().Default(nil), - } -} - -func (Stream) Edges() []ent.Edge { - return []ent.Edge{ - edge.From("channel", Channel.Type). - Ref("streams"). - Required(). - Unique(). - Field("channel_id"), - } -} diff --git a/internal/config/config.go b/internal/config/config.go deleted file mode 100644 index f45960a5..00000000 --- a/internal/config/config.go +++ /dev/null @@ -1,45 +0,0 @@ -package config - -import ( - "github.com/joho/godotenv" - "github.com/kelseyhightower/envconfig" - "os" - "path/filepath" -) - -type Config struct { - TwitchClientId string `required:"true" envconfig:"TWITCH_CLIENTID"` - TwitchClientSecret string `required:"true" envconfig:"TWITCH_CLIENTSECRET"` - TelegramToken string `required:"true" envconfig:"TELEGRAM_TOKEN"` - AppEnv string `required:"true" envconfig:"APP_ENV" default:"development"` - TelegramBotAdmins []string `required:"false" envconfig:"TELEGRAM_BOT_ADMINS"` - DatabaseUrl string `required:"true" envconfig:"DATABASE_URL"` - SentryDsn string `required:"false" envconfig:"SENTRY_DSN"` -} - -var getWd = os.Getwd -var processEnv = envconfig.Process - -func NewConfig(customPath *string) (*Config, error) { - var newCfg Config - - var err error - - wd, err := getWd() - if err != nil { - return nil, err - } - - envPath := filepath.Join(wd, ".env") - - if customPath != nil { - envPath = *customPath - } - - _ = godotenv.Overload(envPath) - if err = processEnv("", &newCfg); err != nil { - return nil, err - } - - return &newCfg, nil -} diff --git a/internal/config/config_test.go b/internal/config/config_test.go deleted file mode 100644 index 97b37365..00000000 --- a/internal/config/config_test.go +++ /dev/null @@ -1,102 +0,0 @@ -package config - -import ( - "os" - "testing" - - "github.com/kelseyhightower/envconfig" - "github.com/stretchr/testify/assert" -) - -var strConfig = ` -TWITCH_CLIENTID=1 -TWITCH_CLIENTSECRET=2 -TELEGRAM_TOKEN=3 -TELEGRAM_BOT_ADMINS=4 -DATABASE_URL=5 -` - -func Test_NewConfig(t *testing.T) { - t.Parallel() - - testCases := []struct { - name string - setupEnv func(t *testing.T) (*Config, error) - checkEnv func(t *testing.T, config *Config, err error) - }{ - { - name: "OK", - setupEnv: func(t *testing.T) (*Config, error) { - file, err := os.CreateTemp("", "temp-env") - assert.NoError(t, err) - - filepath := file.Name() - - _, err = file.Write([]byte(strConfig)) - assert.NoError(t, err) - - defer file.Close() - defer os.Remove(filepath) - - config, err := NewConfig(&filepath) - - return config, err - }, - checkEnv: func(t *testing.T, config *Config, err error) { - assert.NoError(t, err) - - assert.Equal(t, "1", config.TwitchClientId) - assert.Equal(t, "2", config.TwitchClientSecret) - assert.Equal(t, "3", config.TelegramToken) - assert.IsType(t, []string{}, config.TelegramBotAdmins) - assert.Contains(t, config.TelegramBotAdmins, "4") - assert.Equal(t, "5", config.DatabaseUrl) - }, - }, - { - name: "os.Getwd() provides some error", - setupEnv: func(t *testing.T) (*Config, error) { - getWd = func() (string, error) { - return "", os.ErrNotExist - } - defer func() { getWd = os.Getwd }() - - config, err := NewConfig(nil) - - return config, err - }, - checkEnv: func(t *testing.T, config *Config, err error) { - assert.Error(t, err) - assert.ErrorIs(t, err, os.ErrNotExist) - assert.Nil(t, config) - }, - }, - { - name: "envconfig.Process() provides some error", - setupEnv: func(t *testing.T) (*Config, error) { - processEnv = func(s string, i interface{}) error { - return os.ErrNotExist - } - defer func() { processEnv = envconfig.Process }() - - config, err := NewConfig(nil) - - return config, err - }, - checkEnv: func(t *testing.T, config *Config, err error) { - assert.Error(t, err) - assert.ErrorIs(t, err, os.ErrNotExist) - assert.Nil(t, config) - }, - }, - } - - for _, tt := range testCases { - t.Run(tt.name, func(t *testing.T) { - tt.setupEnv(t) - - cfg, err := tt.setupEnv(t) - tt.checkEnv(t, cfg, err) - }) - } -} diff --git a/internal/db/channel.go b/internal/db/channel.go deleted file mode 100644 index 9c9e531e..00000000 --- a/internal/db/channel.go +++ /dev/null @@ -1,41 +0,0 @@ -package db - -import ( - "context" - - "github.com/satont/twitch-notifier/internal/db/db_models" -) - -type ChannelUpdateQuery struct { - IsLive *bool - Category *string - Title *string - - DangerNewChannelId *string -} - -type ChannelInterface interface { - GetByID( - _ context.Context, - id string, - service db_models.ChannelService, - ) (*db_models.Channel, error) - GetByChannelID( - _ context.Context, - channelID string, - service db_models.ChannelService, - ) (*db_models.Channel, error) - Create(_ context.Context, channelID string, service db_models.ChannelService) (*db_models.Channel, error) - Update( - _ context.Context, - channelID string, - service db_models.ChannelService, - updateQuery *ChannelUpdateQuery, - ) (*db_models.Channel, error) - GetByIdOrCreate( - _ context.Context, - channelID string, - service db_models.ChannelService, - ) (*db_models.Channel, error) - GetAll(_ context.Context) ([]*db_models.Channel, error) -} diff --git a/internal/db/channel_impl_ent.go b/internal/db/channel_impl_ent.go deleted file mode 100644 index 91794682..00000000 --- a/internal/db/channel_impl_ent.go +++ /dev/null @@ -1,192 +0,0 @@ -package db - -import ( - "context" - - "github.com/google/uuid" - "github.com/satont/twitch-notifier/ent" - "github.com/satont/twitch-notifier/ent/channel" - "github.com/satont/twitch-notifier/internal/db/db_models" -) - -type channelEntService struct { - entClient *ent.Client -} - -func (c *channelEntService) convertEntity(ch *ent.Channel) *db_models.Channel { - return &db_models.Channel{ - ID: ch.ID, - ChannelID: ch.ChannelID, - Service: db_models.ChannelService(ch.Service.String()), - IsLive: ch.IsLive, - Title: ch.Title, - Category: ch.Category, - UpdatedAt: ch.UpdatedAt, - } -} - -func (c *channelEntService) GetByIdOrCreate( - ctx context.Context, - channelID string, - service db_models.ChannelService, -) (*db_models.Channel, error) { - channelService := channel.Service(service.String()) - - ch, err := c.entClient.Channel. - Query(). - Where(channel.ChannelID(channelID), channel.ServiceEQ(channelService)). - First(ctx) - - if ent.IsNotFound(err) { - newChannel, err := c.Create(ctx, channelID, service) - if err != nil { - return nil, err - } - return newChannel, nil - } else if err != nil { - return nil, err - } - - return c.convertEntity(ch), nil -} - -func (c *channelEntService) GetByID( - ctx context.Context, - id string, - service db_models.ChannelService, -) (*db_models.Channel, error) { - channelService := channel.Service(service.String()) - - idUUID, err := uuid.Parse(id) - if err != nil { - return nil, err - } - - ch, err := c.entClient.Channel. - Query(). - Where(channel.ID(idUUID), channel.ServiceEQ(channelService)). - Only(ctx) - - if err != nil { - if ent.IsNotFound(err) { - return nil, db_models.ChannelNotFoundError - } - - return nil, err - } - - if err != nil { - return nil, err - } - - return c.convertEntity(ch), nil -} - -func (c *channelEntService) GetByChannelID( - ctx context.Context, - channelID string, - service db_models.ChannelService, -) (*db_models.Channel, error) { - channelService := channel.Service(service.String()) - - ch, err := c.entClient.Channel. - Query(). - Where(channel.ChannelID(channelID), channel.ServiceEQ(channelService)). - Only(ctx) - - if err != nil { - if ent.IsNotFound(err) { - return nil, db_models.ChannelNotFoundError - } - - return nil, err - } - - if err != nil { - return nil, err - } - - return c.convertEntity(ch), nil -} - -func (c *channelEntService) Create( - ctx context.Context, - channelID string, - service db_models.ChannelService, -) (*db_models.Channel, error) { - channelService := channel.Service(service.String()) - - ch, err := c.entClient.Channel.Create(). - SetChannelID(channelID). - SetService(channelService).Save(ctx) - if err != nil { - return nil, err - } - - return c.convertEntity(ch), nil -} - -func (c *channelEntService) Update( - ctx context.Context, - channelID string, - service db_models.ChannelService, - query *ChannelUpdateQuery, -) (*db_models.Channel, error) { - channelService := channel.Service(service.String()) - ch, err := c.entClient.Channel. - Query(). - Where(channel.ChannelIDIn(channelID), channel.ServiceEQ(channelService)). - Only(ctx) - if err != nil { - return nil, err - } - - updateQuery := c.entClient.Channel.UpdateOne(ch) - - if query.IsLive != nil { - updateQuery.SetIsLive(*query.IsLive) - } - - if query.Category != nil { - updateQuery.SetCategory(*query.Category) - } - - if query.Title != nil { - updateQuery.SetTitle(*query.Title) - } - - if query.DangerNewChannelId != nil { - updateQuery.SetChannelID(*query.DangerNewChannelId) - } - - newChannel, err := updateQuery.Save(context.Background()) - - if err != nil { - return nil, err - } - - return c.convertEntity(newChannel), nil -} - -func (c *channelEntService) GetAll(ctx context.Context) ([]*db_models.Channel, error) { - channels, err := c.entClient.Channel. - Query(). - All(ctx) - - if err != nil { - return nil, err - } - - result := make([]*db_models.Channel, 0, len(channels)) - for _, ch := range channels { - result = append(result, c.convertEntity(ch)) - } - - return result, nil -} - -func NewChannelEntService(entClient *ent.Client) ChannelInterface { - return &channelEntService{ - entClient: entClient, - } -} diff --git a/internal/db/channel_impl_ent_test.go b/internal/db/channel_impl_ent_test.go deleted file mode 100644 index 09f34a8e..00000000 --- a/internal/db/channel_impl_ent_test.go +++ /dev/null @@ -1,236 +0,0 @@ -package db - -import ( - "context" - "strconv" - "testing" - - "github.com/satont/twitch-notifier/internal/db/db_models" - - "github.com/samber/lo" - "github.com/sourcegraph/conc" - "github.com/stretchr/testify/assert" -) - -func TestChannelEntService_GetByIdOrCreate(t *testing.T) { - t.Parallel() - - entClient, err := setupTest() - if err != nil { - t.Fatal(err) - } - defer teardownTest(entClient) - - channelService := NewChannelEntService(entClient) - - channel, err := channelService.GetByIdOrCreate(context.Background(), "123", db_models.ChannelServiceTwitch) - assert.NoError(t, err) - assert.Equal(t, "123", channel.ChannelID) - assert.Equal(t, db_models.ChannelServiceTwitch, channel.Service) - assert.False(t, channel.IsLive) - assert.Nil(t, channel.Title) - assert.Nil(t, channel.Category) - assert.Nil(t, channel.UpdatedAt) -} - -func TestChannelEntService_GetByID(t *testing.T) { - t.Parallel() - - entClient, err := setupTest() - if err != nil { - t.Fatal(err) - } - defer teardownTest(entClient) - - channelService := NewChannelEntService(entClient) - - table := []struct { - name string - channelID string - service db_models.ChannelService - wantErr bool - createChannel bool - }{ - { - name: "channel not found", - channelID: "123", - service: db_models.ChannelServiceTwitch, - wantErr: true, - }, - { - name: "channel found", - channelID: "321", - service: db_models.ChannelServiceTwitch, - wantErr: false, - createChannel: true, - }, - } - - for _, tt := range table { - t.Run( - tt.name, func(t *testing.T) { - if tt.createChannel { - _, err := channelService.Create(context.Background(), tt.channelID, tt.service) - assert.NoError(t, err) - } - - channel, err := channelService.GetByChannelID(context.Background(), tt.channelID, tt.service) - if tt.wantErr { - assert.Error(t, err) - assert.EqualError(t, err, db_models.ChannelNotFoundError.Error()) - } else { - assert.NoError(t, err) - assert.Equal(t, tt.channelID, channel.ChannelID) - assert.Equal(t, tt.service, channel.Service) - } - }, - ) - } -} - -func TestChannelEntService_Create(t *testing.T) { - t.Parallel() - - entClient, err := setupTest() - if err != nil { - t.Fatal(err) - } - defer teardownTest(entClient) - - channelService := NewChannelEntService(entClient) - - table := []struct { - name string - channel string - service db_models.ChannelService - wantErr bool - }{ - { - name: "channel should be created", - channel: "123", - service: db_models.ChannelServiceTwitch, - }, - { - name: "should fail create because channel exists", - channel: "123", - service: db_models.ChannelServiceTwitch, - wantErr: true, - }, - } - - for _, tt := range table { - t.Run( - tt.name, func(t *testing.T) { - channel, err := channelService.Create(context.Background(), tt.channel, tt.service) - if tt.wantErr { - assert.Error(t, err) - } else { - assert.NoError(t, err) - assert.Equal(t, tt.channel, channel.ChannelID) - assert.Equal(t, tt.service, channel.Service) - assert.False(t, channel.IsLive) - assert.Nil(t, channel.Title) - assert.Nil(t, channel.Category) - assert.Nil(t, channel.UpdatedAt) - } - }, - ) - } -} - -func TestChannelEntService_Update(t *testing.T) { - t.Parallel() - - entClient, err := setupTest() - if err != nil { - t.Fatal(err) - } - defer teardownTest(entClient) - - channelService := NewChannelEntService(entClient) - - table := []struct { - name string - channelID string - service db_models.ChannelService - wantErr bool - createChannel bool - }{ - { - name: "channel should be update", - channelID: "123", - service: db_models.ChannelServiceTwitch, - createChannel: true, - }, - { - name: "should fail update because channel not exists", - channelID: "321", - service: db_models.ChannelServiceTwitch, - wantErr: true, - }, - } - - for _, tt := range table { - t.Run( - tt.name, func(t *testing.T) { - if tt.createChannel { - _, err := channelService.Create(context.Background(), tt.channelID, tt.service) - assert.NoError(t, err) - } - - channel, err := channelService.Update( - context.Background(), - tt.channelID, - tt.service, - &ChannelUpdateQuery{ - IsLive: lo.ToPtr(true), - Category: lo.ToPtr("Category"), - Title: lo.ToPtr("Title"), - }, - ) - if tt.wantErr { - assert.Error(t, err) - } else { - assert.NoError(t, err) - assert.Equal(t, tt.channelID, channel.ChannelID) - assert.Equal(t, tt.service, channel.Service) - assert.True(t, channel.IsLive) - assert.Equal(t, "Title", *channel.Title) - assert.Equal(t, "Category", *channel.Category) - assert.NotNil(t, channel.UpdatedAt) - } - }, - ) - } -} - -func TestChannelEntService_GetAll(t *testing.T) { - t.Parallel() - - entClient, err := setupTest() - if err != nil { - t.Fatal(err) - } - defer teardownTest(entClient) - - channelService := NewChannelEntService(entClient) - - ctx := context.Background() - - wg := conc.NewWaitGroup() - for i := 0; i < 5; i++ { - i := i - wg.Go( - func() { - _, err = channelService.Create(ctx, strconv.Itoa(i), db_models.ChannelServiceTwitch) - assert.NoError(t, err) - }, - ) - } - wg.Wait() - - channels, err := channelService.GetAll(ctx) - assert.NoError(t, err) - - assert.Len(t, channels, 5) -} diff --git a/internal/db/chat.go b/internal/db/chat.go deleted file mode 100644 index d5a597c3..00000000 --- a/internal/db/chat.go +++ /dev/null @@ -1,40 +0,0 @@ -package db - -import ( - "context" - - "github.com/satont/twitch-notifier/internal/db/db_models" -) - -type ChatUpdateSettingsQuery struct { - GameChangeNotification *bool - OfflineNotification *bool - TitleChangeNotification *bool - GameAndTitleChangeNotification *bool - ImageInNotification *bool - ChatLanguage *db_models.ChatLanguage -} - -type ChatUpdateQuery struct { - Settings *ChatUpdateSettingsQuery -} - -type ChatInterface interface { - GetByID( - _ context.Context, - chatId string, - service db_models.ChatService, - ) (*db_models.Chat, error) - Create( - _ context.Context, - chatId string, - service db_models.ChatService, - ) (*db_models.Chat, error) - Update( - _ context.Context, - chatId string, - service db_models.ChatService, - query *ChatUpdateQuery, - ) (*db_models.Chat, error) - GetAllByService(_ context.Context, service db_models.ChatService) ([]*db_models.Chat, error) -} diff --git a/internal/db/chat_ent_impl.go b/internal/db/chat_ent_impl.go deleted file mode 100644 index cb353be0..00000000 --- a/internal/db/chat_ent_impl.go +++ /dev/null @@ -1,163 +0,0 @@ -package db - -import ( - "context" - - "github.com/satont/twitch-notifier/ent" - "github.com/satont/twitch-notifier/ent/chat" - "github.com/satont/twitch-notifier/ent/chatsettings" - "github.com/satont/twitch-notifier/internal/db/db_models" -) - -type chatService struct { - entClient *ent.Client -} - -func (c *chatService) convertEntity(entity *ent.Chat) *db_models.Chat { - settings := &db_models.ChatSettings{ - ID: entity.Edges.Settings.ID, - GameChangeNotification: entity.Edges.Settings.GameChangeNotification, - OfflineNotification: entity.Edges.Settings.OfflineNotification, - TitleChangeNotification: entity.Edges.Settings.TitleChangeNotification, - GameAndTitleChangeNotification: entity.Edges.Settings.GameAndTitleChangeNotification, - ImageInNotification: entity.Edges.Settings.ImageInNotification, - ChatLanguage: db_models.ChatLanguage(entity.Edges.Settings.ChatLanguage), - ChatID: entity.Edges.Settings.ChatID, - } - - return &db_models.Chat{ - ID: entity.ID, - ChatID: entity.ChatID, - Service: db_models.ChatService(entity.Service), - Settings: settings, - } -} - -func (c *chatService) Update( - ctx context.Context, - chatId string, - service db_models.ChatService, - settings *ChatUpdateQuery, -) (*db_models.Chat, error) { - ch, err := c.entClient.Chat. - Query(). - Where(chat.ChatID(chatId), chat.ServiceEQ(chat.Service(service))). - WithSettings(). - Only(ctx) - if err != nil { - return nil, err - } - - if settings.Settings != nil { - updater := ch.Edges.Settings.Update() - - if settings.Settings.ChatLanguage != nil { - updater.SetChatLanguage(chatsettings.ChatLanguage(*settings.Settings.ChatLanguage)) - } - - if settings.Settings.GameChangeNotification != nil { - updater.SetGameChangeNotification(*settings.Settings.GameChangeNotification) - } - - if settings.Settings.OfflineNotification != nil { - updater.SetOfflineNotification(*settings.Settings.OfflineNotification) - } - - if settings.Settings.TitleChangeNotification != nil { - updater.SetTitleChangeNotification(*settings.Settings.TitleChangeNotification) - } - - if settings.Settings.ImageInNotification != nil { - updater.SetImageInNotification(*settings.Settings.ImageInNotification) - } - - if settings.Settings.GameAndTitleChangeNotification != nil { - updater.SetGameAndTitleChangeNotification(*settings.Settings.GameAndTitleChangeNotification) - } - - _, err = updater.Save(ctx) - if err != nil { - return nil, err - } - } - - return c.GetByID(ctx, chatId, service) -} - -func (c *chatService) Create( - ctx context.Context, - chatId string, - service db_models.ChatService, -) (*db_models.Chat, error) { - ch, err := c.entClient.Chat. - Create(). - SetChatID(chatId). - SetService(chat.Service(service.String())). - Save(ctx) - if err != nil { - return nil, err - } - - settings, err := c.entClient.ChatSettings.Create().SetChatID(ch.ID).Save(ctx) - if err != nil { - return nil, err - } - - ch.Edges.Settings = settings - - return c.convertEntity(ch), nil -} - -func (c *chatService) GetByID( - ctx context.Context, - chatId string, - service db_models.ChatService, -) (*db_models.Chat, error) { - ch, err := c.entClient.Chat. - Query(). - Where(chat.ChatID(chatId), chat.ServiceEQ(chat.Service(service))). - WithSettings(). - Only(ctx) - - if err != nil { - if ent.IsNotFound(err) { - return nil, nil - } - - return nil, err - } - - if err != nil { - return nil, err - } - - return c.convertEntity(ch), nil -} - -func (c *chatService) GetAllByService( - ctx context.Context, - service db_models.ChatService, -) ([]*db_models.Chat, error) { - chats, err := c.entClient.Chat. - Query(). - Where(chat.ServiceEQ(chat.Service(service))). - Order(ent.Desc(chat.FieldChatID)). - WithSettings(). - All(ctx) - if err != nil { - return nil, err - } - - var result []*db_models.Chat - for _, ch := range chats { - result = append(result, c.convertEntity(ch)) - } - - return result, nil -} - -func NewChatEntRepository(entClient *ent.Client) ChatInterface { - return &chatService{ - entClient: entClient, - } -} diff --git a/internal/db/chat_ent_impl_test.go b/internal/db/chat_ent_impl_test.go deleted file mode 100644 index ae92382d..00000000 --- a/internal/db/chat_ent_impl_test.go +++ /dev/null @@ -1,280 +0,0 @@ -package db - -import ( - "context" - "strconv" - "testing" - - _ "github.com/mattn/go-sqlite3" - "github.com/samber/lo" - "github.com/satont/twitch-notifier/internal/db/db_models" - "github.com/stretchr/testify/assert" -) - -func TestChatService_GetByID(t *testing.T) { - t.Parallel() - - entClient, err := setupTest() - if err != nil { - t.Fatal(err) - } - defer teardownTest(entClient) - - chatService := NewChatEntRepository(entClient) - - _, err = chatService.Create( - context.Background(), - "123", - db_models.ChatServiceTelegram, - ) - assert.NoError(t, err) - - table := []struct { - name string - chatID string - wantNil bool - expects struct { - chatID string - service db_models.ChatService - language db_models.ChatLanguage - gameChangeNotification bool - streamStartNotification bool - titleChangeNotification bool - imageInNotification bool - } - }{ - { - name: "Get chat by id", - chatID: "123", - wantNil: false, - expects: struct { - chatID string - service db_models.ChatService - language db_models.ChatLanguage - gameChangeNotification bool - streamStartNotification bool - titleChangeNotification bool - imageInNotification bool - }{ - chatID: "123", - service: db_models.ChatServiceTelegram, - language: db_models.ChatLanguageEn, - gameChangeNotification: true, - streamStartNotification: true, - titleChangeNotification: false, - imageInNotification: true, - }, - }, - { - name: "Should fail if chat not found", - chatID: "321", - wantNil: true, - }, - } - - for _, tt := range table { - t.Run(tt.chatID, func(t *testing.T) { - chat, err := chatService.GetByID( - context.Background(), - tt.chatID, - db_models.ChatServiceTelegram, - ) - - if tt.wantNil { - assert.Nil(t, chat) - } else { - assert.NoError(t, err) - - assert.Equal(t, tt.expects.chatID, chat.ChatID) - assert.Equal(t, tt.expects.service, chat.Service) - assert.Equal(t, tt.expects.language, chat.Settings.ChatLanguage) - assert.Equal(t, tt.expects.gameChangeNotification, chat.Settings.GameChangeNotification) - assert.Equal(t, tt.expects.titleChangeNotification, chat.Settings.TitleChangeNotification) - assert.Equal(t, tt.expects.streamStartNotification, chat.Settings.OfflineNotification) - assert.Equal(t, tt.expects.imageInNotification, chat.Settings.ImageInNotification) - assert.Equal(t, chat.ID, chat.Settings.ChatID) - } - }) - } -} - -func TestChatService_Create(t *testing.T) { - t.Parallel() - - entClient, err := setupTest() - if err != nil { - t.Fatal(err) - } - defer teardownTest(entClient) - - chatService := NewChatEntRepository(entClient) - - table := []struct { - name string - chatID string - wantErr bool - }{ - { - name: "Create chat", - chatID: "123", - wantErr: false, - }, - { - name: "Should fail if chat already exists", - chatID: "123", - wantErr: true, - }, - } - - for _, tt := range table { - t.Run(tt.chatID, func(t *testing.T) { - chat, err := chatService.Create( - context.Background(), - tt.chatID, - db_models.ChatServiceTelegram, - ) - - if tt.wantErr { - assert.Error(t, err) - } else { - assert.NoError(t, err) - assert.Equal(t, tt.chatID, chat.ChatID) - assert.Equal(t, db_models.ChatServiceTelegram, chat.Service) - assert.NotEmpty(t, chat.Settings.ID) - assert.Equal(t, db_models.ChatLanguageEn, chat.Settings.ChatLanguage) - assert.Equal(t, true, chat.Settings.GameChangeNotification) - assert.Equal(t, true, chat.Settings.OfflineNotification) - assert.Equal(t, false, chat.Settings.TitleChangeNotification) - assert.Equal(t, true, chat.Settings.ImageInNotification) - assert.Equal(t, chat.ID, chat.Settings.ChatID) - } - }) - } -} - -func TestChatService_Update(t *testing.T) { - t.Parallel() - - entClient, err := setupTest() - if err != nil { - t.Fatal(err) - } - defer teardownTest(entClient) - - chatService := NewChatEntRepository(entClient) - - table := []struct { - name string - chatID string - wantErr bool - shouldCreate bool - newValues struct { - language db_models.ChatLanguage - gameChangeNotification bool - streamStartNotification bool - titleChaneNotification bool - imageInNotification bool - } - }{ - { - name: "Update chat", - chatID: "123", - wantErr: false, - shouldCreate: true, - newValues: struct { - language db_models.ChatLanguage - gameChangeNotification bool - streamStartNotification bool - titleChaneNotification bool - imageInNotification bool - }{ - language: db_models.ChatLanguageRu, - gameChangeNotification: false, - streamStartNotification: false, - titleChaneNotification: true, - imageInNotification: true, - }, - }, - { - name: "Should fail if chat not found", - chatID: "321", - wantErr: true, - shouldCreate: false, - }, - } - - for _, tt := range table { - t.Run(tt.chatID, func(t *testing.T) { - if tt.shouldCreate { - _, err = chatService.Create( - context.Background(), - tt.chatID, - db_models.ChatServiceTelegram, - ) - assert.NoError(t, err) - } - - newChat, err := chatService.Update( - context.Background(), - tt.chatID, - db_models.ChatServiceTelegram, - &ChatUpdateQuery{ - Settings: &ChatUpdateSettingsQuery{ - GameChangeNotification: lo.ToPtr(false), - OfflineNotification: lo.ToPtr(false), - TitleChangeNotification: lo.ToPtr(true), - ImageInNotification: lo.ToPtr(true), - ChatLanguage: lo.ToPtr(db_models.ChatLanguageRu), - }, - }, - ) - - if tt.wantErr { - assert.Error(t, err) - } else { - assert.NoError(t, err) - - assert.Equal(t, tt.chatID, newChat.ChatID) - assert.Equal(t, tt.newValues.language, newChat.Settings.ChatLanguage) - assert.Equal(t, tt.newValues.gameChangeNotification, newChat.Settings.GameChangeNotification) - assert.Equal(t, tt.newValues.streamStartNotification, newChat.Settings.OfflineNotification) - assert.Equal(t, tt.newValues.titleChaneNotification, newChat.Settings.TitleChangeNotification) - assert.Equal(t, tt.newValues.imageInNotification, newChat.Settings.ImageInNotification) - } - }) - } -} - -func TestChatService_GetAllByService(t *testing.T) { - t.Parallel() - - entClient, err := setupTest() - if err != nil { - t.Fatal(err) - } - defer teardownTest(entClient) - - ctx := context.Background() - - chatService := NewChatEntRepository(entClient) - - var created []*db_models.Chat - - for i := 0; i < 10; i++ { - newChat, err := chatService.Create( - ctx, - strconv.Itoa(i), - db_models.ChatServiceTelegram, - ) - assert.NoError(t, err) - created = append(created, newChat) - } - - chats, err := chatService.GetAllByService(ctx, db_models.ChatServiceTelegram) - assert.NoError(t, err) - assert.Len(t, chats, 10) - - for _, chat := range chats { - assert.Contains(t, created, chat) - } -} diff --git a/internal/db/db_models/channel.go b/internal/db/db_models/channel.go deleted file mode 100644 index 053b5122..00000000 --- a/internal/db/db_models/channel.go +++ /dev/null @@ -1,34 +0,0 @@ -package db_models - -import ( - "errors" - "github.com/google/uuid" - "time" -) - -var ( - ChannelNotFoundError = errors.New("channel not found") -) - -type ChannelService string - -const ( - ChannelServiceTwitch ChannelService = "twitch" -) - -func (s ChannelService) String() string { - return string(s) -} - -type Channel struct { - ID uuid.UUID `json:"id,omitempty"` - ChannelID string `json:"channel_id,omitempty"` - Service ChannelService `json:"service,omitempty"` - IsLive bool `json:"is_live,omitempty"` - Title *string `json:"title,omitempty"` - Category *string `json:"category,omitempty"` - UpdatedAt *time.Time `json:"updated_at,omitempty"` - - Follows []*Follow `json:"follows,omitempty"` - Streams []*Stream `json:"streams,omitempty"` -} diff --git a/internal/db/db_models/chat.go b/internal/db/db_models/chat.go deleted file mode 100644 index 801d9091..00000000 --- a/internal/db/db_models/chat.go +++ /dev/null @@ -1,58 +0,0 @@ -package db_models - -import ( - "github.com/google/uuid" -) - -type ChatService string - -const ( - ChatServiceTelegram ChatService = "telegram" -) - -func (s ChatService) String() string { - return string(s) -} - -func LanguageExists(l ChatLanguage) bool { - switch l { - case ChatLanguageRu, ChatLanguageEn, ChatLanguageUk: - return true - default: - return false - } -} - -type Chat struct { - ID uuid.UUID `json:"id,omitempty"` - ChatID string `json:"chat_id,omitempty"` - Service ChatService `json:"service,omitempty"` - - Follows []*Follow `json:"follows,omitempty"` - Settings *ChatSettings `json:"settings,omitempty"` -} - -type ChatLanguage string - -var DefaultChatLanguage = ChatLanguageEn - -var ( - ChatLanguageRu ChatLanguage = "ru" - ChatLanguageEn ChatLanguage = "en" - ChatLanguageUk ChatLanguage = "uk" -) - -func (cl ChatLanguage) String() string { - return string(cl) -} - -type ChatSettings struct { - ID uuid.UUID `json:"id,omitempty"` - GameChangeNotification bool `json:"game_change_notification,omitempty"` - TitleChangeNotification bool `json:"title_change_notification,omitempty"` - GameAndTitleChangeNotification bool `json:"game_and_title_change_notification,omitempty"` - OfflineNotification bool `json:"offline_notification,omitempty"` - ChatLanguage ChatLanguage `json:"chat_language,omitempty"` - ChatID uuid.UUID `json:"chat_id,omitempty"` - ImageInNotification bool `json:"image_in_notification,omitempty"` -} diff --git a/internal/db/db_models/follow.go b/internal/db/db_models/follow.go deleted file mode 100644 index 2fca9253..00000000 --- a/internal/db/db_models/follow.go +++ /dev/null @@ -1,20 +0,0 @@ -package db_models - -import ( - "errors" - "github.com/google/uuid" -) - -var ( - FollowAlreadyExistsError = errors.New("follow already exists") - FollowNotFoundError = errors.New("follow not found") -) - -type Follow struct { - ID uuid.UUID `json:"id,omitempty"` - ChannelID uuid.UUID `json:"channel_id,omitempty"` - ChatID uuid.UUID `json:"chat_id,omitempty"` - - Channel *Channel `json:"channel,omitempty"` - Chat *Chat `json:"chat,omitempty"` -} diff --git a/internal/db/db_models/stream.go b/internal/db/db_models/stream.go deleted file mode 100644 index b7b8323d..00000000 --- a/internal/db/db_models/stream.go +++ /dev/null @@ -1,16 +0,0 @@ -package db_models - -import ( - "github.com/google/uuid" - "time" -) - -type Stream struct { - ID string `json:"id,omitempty"` - ChannelID uuid.UUID `json:"channel_id,omitempty"` - Titles []string `json:"titles,omitempty"` - Categories []string `json:"categories,omitempty"` - StartedAt time.Time `json:"started_at,omitempty"` - UpdatedAt *time.Time `json:"updated_at,omitempty"` - EndedAt *time.Time `json:"ended_at,omitempty"` -} diff --git a/internal/db/follow.go b/internal/db/follow.go deleted file mode 100644 index 827bb216..00000000 --- a/internal/db/follow.go +++ /dev/null @@ -1,20 +0,0 @@ -package db - -import ( - "context" - "github.com/google/uuid" - "github.com/satont/twitch-notifier/internal/db/db_models" -) - -type FollowInterface interface { - Create(_ context.Context, channelID uuid.UUID, chatID uuid.UUID) (*db_models.Follow, error) - Delete(_ context.Context, id uuid.UUID) error - GetByChatAndChannel( - _ context.Context, - channelID uuid.UUID, - chatID uuid.UUID, - ) (*db_models.Follow, error) - GetByChannelID(_ context.Context, channelID uuid.UUID) ([]*db_models.Follow, error) - GetByChatID(_ context.Context, chatID uuid.UUID, limit, offset int) ([]*db_models.Follow, error) - CountByChatID(_ context.Context, chatID uuid.UUID) (int, error) -} diff --git a/internal/db/follow_ent_impl.go b/internal/db/follow_ent_impl.go deleted file mode 100644 index 17ca005a..00000000 --- a/internal/db/follow_ent_impl.go +++ /dev/null @@ -1,201 +0,0 @@ -package db - -import ( - "context" - - "github.com/google/uuid" - "github.com/satont/twitch-notifier/ent" - "github.com/satont/twitch-notifier/ent/channel" - "github.com/satont/twitch-notifier/ent/chat" - "github.com/satont/twitch-notifier/ent/follow" - "github.com/satont/twitch-notifier/internal/db/db_models" -) - -type followService struct { - entClient *ent.Client -} - -func (f *followService) convertEntity(follow *ent.Follow) *db_models.Follow { - convertedFollow := &db_models.Follow{ - ID: follow.ID, - } - - if follow.Edges.Channel != nil { - convertedFollow.ChannelID = follow.Edges.Channel.ID - - convertedFollow.Channel = &db_models.Channel{ - ID: follow.Edges.Channel.ID, - ChannelID: follow.Edges.Channel.ChannelID, - Service: db_models.ChannelService(follow.Edges.Channel.Service), - IsLive: false, - UpdatedAt: follow.Edges.Channel.UpdatedAt, - } - } - - if follow.Edges.Chat != nil { - convertedFollow.ChatID = follow.Edges.Chat.ID - chatSettings := &db_models.ChatSettings{} - - if follow.Edges.Chat.Edges.Settings != nil { - chatSettings.ID = follow.Edges.Chat.Edges.Settings.ID - chatSettings.ChatID = follow.Edges.Chat.Edges.Settings.ChatID - chatSettings.ChatLanguage = db_models.ChatLanguage( - follow.Edges.Chat.Edges.Settings.ChatLanguage, - ) - chatSettings.GameChangeNotification = follow.Edges.Chat.Edges.Settings.GameChangeNotification - chatSettings.TitleChangeNotification = follow.Edges.Chat.Edges.Settings.TitleChangeNotification - chatSettings.OfflineNotification = follow.Edges.Chat.Edges.Settings.OfflineNotification - chatSettings.ImageInNotification = follow.Edges.Chat.Edges.Settings.ImageInNotification - chatSettings.GameAndTitleChangeNotification = follow.Edges.Chat.Edges.Settings.GameAndTitleChangeNotification - } - - convertedFollow.Chat = &db_models.Chat{ - ID: follow.Edges.Chat.ID, - ChatID: follow.Edges.Chat.ChatID, - Service: db_models.ChatService(follow.Edges.Chat.Service), - Settings: chatSettings, - } - } - - return convertedFollow -} - -func (f *followService) Create( - ctx context.Context, - channelID uuid.UUID, - chatID uuid.UUID, -) (*db_models.Follow, error) { - _, err := f.entClient.Follow. - Create(). - SetChatID(chatID). - SetChannelID(channelID). - Save(ctx) - - if ent.IsConstraintError(err) { - return nil, db_models.FollowAlreadyExistsError - } else if err != nil { - return nil, err - } - - return f.GetByChatAndChannel(ctx, channelID, chatID) -} - -func (f *followService) Delete(ctx context.Context, followID uuid.UUID) error { - err := f.entClient.Follow. - DeleteOneID(followID). - Exec(ctx) - if err != nil { - return err - } - - return nil -} - -func (f *followService) GetByChatAndChannel( - ctx context.Context, - channelID uuid.UUID, - chatID uuid.UUID, -) (*db_models.Follow, error) { - fol, err := f.entClient.Follow. - Query(). - Where(follow.ChannelID(channelID), follow.ChatID(chatID)). - WithChannel(). - WithChat( - func(query *ent.ChatQuery) { - query.WithSettings() - }, - ). - First(ctx) - - if err != nil && ent.IsNotFound(err) { - return nil, db_models.FollowNotFoundError - } else if err != nil { - return nil, err - } - - if fol == nil { - return nil, nil - } - - return f.convertEntity(fol), err -} - -func (f *followService) GetByChannelID( - ctx context.Context, - channelID uuid.UUID, -) ([]*db_models.Follow, error) { - follows, err := f.entClient.Follow. - Query(). - Where(follow.HasChannelWith(channel.IDEQ(channelID))). - WithChannel(). - WithChat( - func(query *ent.ChatQuery) { - query.WithSettings() - }, - ). - All(ctx) - - if err != nil { - return nil, err - } - - result := make([]*db_models.Follow, 0, len(follows)) - for _, foll := range follows { - if foll != nil { - result = append(result, f.convertEntity(foll)) - } - } - - return result, nil -} - -func (f *followService) GetByChatID( - ctx context.Context, - chatID uuid.UUID, - limit, - offset int, -) ([]*db_models.Follow, error) { - query := f.entClient.Follow. - Query(). - Where(follow.HasChatWith(chat.IDEQ(chatID))). - WithChat( - func(query *ent.ChatQuery) { - query.WithSettings() - }, - ). - WithChannel(). - Order(ent.Desc(follow.FieldChannelID)) - - if limit > 0 { - query = query.Limit(limit) - } - query.Offset(offset) - - follows, err := query.All(ctx) - - if err != nil { - return nil, err - } - - result := make([]*db_models.Follow, len(follows)) - for i, foll := range follows { - result[i] = f.convertEntity(foll) - } - - return result, nil -} - -func (f *followService) CountByChatID(_ context.Context, chatID uuid.UUID) (int, error) { - count, err := f.entClient.Follow.Query(). - Where(follow.ChatIDEQ(chatID)). - Count(context.Background()) - if err != nil { - return 0, err - } - - return count, nil -} - -func NewFollowService(entClient *ent.Client) FollowInterface { - return &followService{entClient: entClient} -} diff --git a/internal/db/follow_ent_test.go b/internal/db/follow_ent_test.go deleted file mode 100644 index 1d8d48a2..00000000 --- a/internal/db/follow_ent_test.go +++ /dev/null @@ -1,269 +0,0 @@ -package db - -import ( - "context" - "fmt" - "github.com/google/uuid" - db_models2 "github.com/satont/twitch-notifier/internal/db/db_models" - "github.com/stretchr/testify/assert" - "testing" -) - -func TestFollowService_Create(t *testing.T) { - t.Parallel() - - entClient, err := setupTest() - assert.NoError(t, err) - defer teardownTest(entClient) - - ctx := context.Background() - - chService := NewChatEntRepository(entClient) - channelsService := NewChannelEntService(entClient) - service := NewFollowService(entClient) - - newChat, err := chService.Create(ctx, "1", db_models2.ChatServiceTelegram) - assert.NoError(t, err) - - newChannel, err := channelsService.Create(ctx, "1", db_models2.ChannelServiceTwitch) - assert.NoError(t, err) - - table := []struct { - name string - chatID uuid.UUID - channelID uuid.UUID - wantErr bool - }{ - { - name: "Create follow", - chatID: newChat.ID, - channelID: newChannel.ID, - wantErr: false, - }, - { - name: "Should fail if follow already exists", - chatID: newChat.ID, - channelID: newChannel.ID, - wantErr: true, - }, - } - - for _, tt := range table { - t.Run(tt.name, func(t *testing.T) { - f, err := service.Create(ctx, tt.channelID, tt.chatID) - if tt.wantErr { - assert.Error(t, err) - } else { - assert.NoError(t, err) - assert.Equal(t, newChannel.ID, f.ChannelID, "Expects channel_id to be equal.") - assert.Equal(t, newChat.ID, f.ChatID, "Expects chat_id to be equal.") - } - }) - } -} - -func TestFollowService_Delete(t *testing.T) { - t.Parallel() - - entClient, err := setupTest() - assert.NoError(t, err) - defer teardownTest(entClient) - - ctx := context.Background() - - chService := NewChatEntRepository(entClient) - channelsService := NewChannelEntService(entClient) - service := NewFollowService(entClient) - - newChat, err := chService.Create(ctx, "1", db_models2.ChatServiceTelegram) - assert.NoError(t, err) - - newChannel, err := channelsService.Create(ctx, "1", db_models2.ChannelServiceTwitch) - assert.NoError(t, err) - - foll, err := service.Create(ctx, newChannel.ID, newChat.ID) - - table := []struct { - name string - id uuid.UUID - wantErr bool - }{ - { - name: "Delete follow", - id: foll.ID, - wantErr: false, - }, - { - name: "Should fail if follow does not exist", - id: uuid.New(), - wantErr: true, - }, - } - - for _, tt := range table { - t.Run(tt.name, func(t *testing.T) { - err := service.Delete(ctx, tt.id) - if tt.wantErr { - assert.Error(t, err) - } else { - assert.NoError(t, err) - } - }) - } -} - -func TestFollowService_GetByChatAndChannel(t *testing.T) { - entClient, err := setupTest() - assert.NoError(t, err) - defer teardownTest(entClient) - - ctx := context.Background() - - chService := NewChatEntRepository(entClient) - channelsService := NewChannelEntService(entClient) - service := NewFollowService(entClient) - - newChat, err := chService.Create(ctx, "1", db_models2.ChatServiceTelegram) - assert.NoError(t, err) - - newChannel, err := channelsService.Create(ctx, "1", db_models2.ChannelServiceTwitch) - assert.NoError(t, err) - - _, err = service.Create(ctx, newChannel.ID, newChat.ID) - assert.NoError(t, err) - - table := []struct { - name string - chatID uuid.UUID - channelID uuid.UUID - wantNil bool - wantErr bool - }{ - { - name: "Get follow", - chatID: newChat.ID, - channelID: newChannel.ID, - wantNil: false, - }, - { - name: "Should fail if follow does not exist", - chatID: uuid.New(), - channelID: uuid.New(), - wantNil: true, - wantErr: true, - }, - } - - for _, tt := range table { - t.Run(tt.name, func(t *testing.T) { - f, err := service.GetByChatAndChannel(ctx, tt.channelID, tt.chatID) - - if tt.wantErr { - assert.Error(t, err) - } else { - assert.NoError(t, err) - - } - if tt.wantNil { - assert.Nil(t, f) - } else { - assert.Equal(t, newChannel.ID, f.ChannelID, "Expects channel_id to be equal.") - assert.Equal(t, newChat.ID, f.ChatID, "Expects chat_id to be equal.") - } - }) - } -} - -func TestFollowService_GetByChannelID(t *testing.T) { - t.Parallel() - - entClient, err := setupTest() - assert.NoError(t, err) - defer teardownTest(entClient) - - ctx := context.Background() - - chService := NewChatEntRepository(entClient) - channelsService := NewChannelEntService(entClient) - service := NewFollowService(entClient) - - newChat, err := chService.Create(ctx, "1", db_models2.ChatServiceTelegram) - assert.NoError(t, err) - - channelsIds := make([]uuid.UUID, 0) - - for i := 0; i < 5; i++ { - ch, err := channelsService.Create( - ctx, - fmt.Sprintf("%v", i), - db_models2.ChannelServiceTwitch, - ) - assert.NoError(t, err) - channelsIds = append(channelsIds, ch.ID) - } - - for _, channelID := range channelsIds { - f, err := service.Create(ctx, channelID, newChat.ID) - assert.NoError(t, err) - assert.Equal(t, channelID, f.ChannelID, "Expects channel_id to be equal.") - assert.Equal(t, newChat.ID, f.ChatID, "Expects chat_id to be equal.") - } - - for _, channelID := range channelsIds { - follows, err := service.GetByChannelID(ctx, channelID) - assert.NoError(t, err) - - for _, foll := range follows { - assert.Equal(t, channelID, foll.ChannelID, "Expects channel_id to be equal.") - assert.Equal(t, newChat.ID, foll.ChatID, "Expects chat_id to be equal.") - } - } -} - -func TestFollowService_GetByChatID(t *testing.T) { - t.Parallel() - - entClient, err := setupTest() - assert.NoError(t, err) - defer teardownTest(entClient) - - ctx := context.Background() - - chService := NewChatEntRepository(entClient) - channelsService := NewChannelEntService(entClient) - service := NewFollowService(entClient) - - newChat, err := chService.Create(ctx, "1", db_models2.ChatServiceTelegram) - assert.NoError(t, err) - - channelsIds := make([]uuid.UUID, 0) - - for i := 0; i < 5; i++ { - ch, err := channelsService.Create( - ctx, - fmt.Sprintf("%v", i), - db_models2.ChannelServiceTwitch, - ) - assert.NoError(t, err) - channelsIds = append(channelsIds, ch.ID) - } - - for _, channelID := range channelsIds { - f, err := service.Create(ctx, channelID, newChat.ID) - assert.NoError(t, err) - assert.Equal(t, channelID, f.ChannelID, "Expects channel_id to be equal.") - assert.Equal(t, newChat.ID, f.ChatID, "Expects chat_id to be equal.") - } - - follows, err := service.GetByChatID(ctx, newChat.ID, 0, 0) - assert.NoError(t, err) - assert.Len(t, follows, 5) - - for _, foll := range follows { - assert.Equal(t, newChat.ID, foll.ChatID, "Expects chat_id to be equal.") - } - - followsPaginated, err := service.GetByChatID(ctx, newChat.ID, 0, 2) - assert.NoError(t, err) - assert.Len(t, followsPaginated, 3) -} diff --git a/internal/db/mock_db.go b/internal/db/mock_db.go deleted file mode 100644 index d29e7be8..00000000 --- a/internal/db/mock_db.go +++ /dev/null @@ -1,26 +0,0 @@ -package db - -import ( - "context" - "fmt" - "github.com/satont/twitch-notifier/ent" - "time" -) - -func setupTest() (*ent.Client, error) { - source := fmt.Sprintf("file:tests%v?mode=memory&cache=shared&_fk=1", time.Now().UnixMicro()) - - entClient, err := ent.Open("sqlite3", source) - if err != nil { - return nil, err - } - if err := entClient.Schema.Create(context.Background()); err != nil { - fmt.Println(err) - return nil, err - } - return entClient, nil -} - -func teardownTest(entClient *ent.Client) { - _ = entClient.Close() -} diff --git a/internal/db/stream.go b/internal/db/stream.go deleted file mode 100644 index 51f0357e..00000000 --- a/internal/db/stream.go +++ /dev/null @@ -1,39 +0,0 @@ -package db - -import ( - "context" - "github.com/google/uuid" - "github.com/satont/twitch-notifier/internal/db/db_models" -) - -type StreamUpdateQuery struct { - StreamID string - IsLive *bool - Category *string - Title *string -} - -type StreamInterface interface { - GetByID(_ context.Context, streamId string) (*db_models.Stream, error) - - GetLatestByChannelID( - _ context.Context, - channelEntityID uuid.UUID, - ) (*db_models.Stream, error) - GetManyByChannelID( - _ context.Context, - channelEntityID uuid.UUID, - limit int, - ) ([]*db_models.Stream, error) - - UpdateOneByStreamID( - _ context.Context, - streamID string, - updateQuery *StreamUpdateQuery, - ) (*db_models.Stream, error) - CreateOneByChannelID( - _ context.Context, - channelEntityID uuid.UUID, - updateQuery *StreamUpdateQuery, - ) (*db_models.Stream, error) -} diff --git a/internal/db/stream_impl_ent.go b/internal/db/stream_impl_ent.go deleted file mode 100644 index 27e3dd21..00000000 --- a/internal/db/stream_impl_ent.go +++ /dev/null @@ -1,161 +0,0 @@ -package db - -import ( - "context" - "errors" - "github.com/google/uuid" - "github.com/lib/pq" - "github.com/satont/twitch-notifier/ent" - "github.com/satont/twitch-notifier/ent/channel" - "github.com/satont/twitch-notifier/ent/stream" - "github.com/satont/twitch-notifier/internal/db/db_models" - "time" -) - -type StreamEntService struct { - entClient *ent.Client -} - -func (s *StreamEntService) convertEntity(stream *ent.Stream) *db_models.Stream { - return &db_models.Stream{ - ID: stream.ID, - ChannelID: stream.ChannelID, - Titles: stream.Titles, - Categories: stream.Categories, - StartedAt: stream.StartedAt, - UpdatedAt: stream.UpdatedAt, - EndedAt: stream.EndedAt, - } -} - -func (s *StreamEntService) GetByID(ctx context.Context, streamID string) (*db_models.Stream, error) { - str, err := s.entClient.Stream.Query().Where(stream.IDEQ(streamID)).Only(ctx) - if err != nil { - if ent.IsNotFound(err) { - return nil, nil - } else { - return nil, err - } - } - - return s.convertEntity(str), nil -} - -func (s *StreamEntService) GetLatestByChannelID( - ctx context.Context, - channelEntityID uuid.UUID, -) (*db_models.Stream, error) { - str, err := s.entClient.Stream. - Query(). - Where(stream.ChannelIDEQ(channelEntityID), stream.EndedAtIsNil()). - Order(ent.Desc(stream.FieldStartedAt)). - First(ctx) - if err != nil { - if ent.IsNotFound(err) { - return nil, nil - } else { - return nil, err - } - } - - return s.convertEntity(str), nil -} - -func (s *StreamEntService) GetManyByChannelID( - ctx context.Context, - channelEntityID uuid.UUID, - limit int, -) ([]*db_models.Stream, error) { - streams, err := s.entClient.Stream. - Query(). - Where(stream.HasChannelWith(channel.IDEQ(channelEntityID))). - Order(ent.Desc(stream.FieldStartedAt)). - Limit(limit). - All(ctx) - - if err != nil { - return nil, err - } - - convertedStreams := make([]*db_models.Stream, len(streams)) - for i, str := range streams { - convertedStreams[i] = s.convertEntity(str) - } - - return convertedStreams, err -} - -func (s *StreamEntService) UpdateOneByStreamID( - ctx context.Context, - streamID string, - updateQuery *StreamUpdateQuery, -) (*db_models.Stream, error) { - str, err := s.GetByID(ctx, streamID) - if err != nil { - return nil, err - } - if str == nil { - return nil, errors.New("stream not found") - } - - query := s.entClient.Stream.UpdateOneID(str.ID) - - if updateQuery.IsLive != nil && *updateQuery.IsLive { - query.SetStartedAt(time.Now().UTC()) - } - - if updateQuery.IsLive != nil && !*updateQuery.IsLive { - query.SetEndedAt(time.Now().UTC()) - } - - if updateQuery.Category != nil { - str.Categories = append(str.Categories, *updateQuery.Category) - query.SetCategories(str.Categories) - } - - if updateQuery.Title != nil { - str.Titles = append(str.Titles, *updateQuery.Title) - query.SetTitles(str.Titles) - } - - newStream, err := query.Save(ctx) - if err != nil { - return nil, err - } - - return s.convertEntity(newStream), nil -} - -func (s *StreamEntService) CreateOneByChannelID( - ctx context.Context, - channelEntityID uuid.UUID, - data *StreamUpdateQuery, -) (*db_models.Stream, error) { - query := s.entClient.Stream.Create() - - query.SetChannelID(channelEntityID) - - query.SetStartedAt(time.Now().UTC()) - query.SetID(data.StreamID) - - if data.Title != nil { - query.SetTitles(pq.StringArray{*data.Title}) - } - - if data.Category != nil { - query.SetCategories(pq.StringArray{*data.Category}) - } - - str, err := query.Save(ctx) - if err != nil { - return nil, err - } - - return s.convertEntity(str), nil -} - -func NewStreamEntService(entClient *ent.Client) *StreamEntService { - return &StreamEntService{ - entClient: entClient, - } -} diff --git a/internal/db/stream_impl_ent_test.go b/internal/db/stream_impl_ent_test.go deleted file mode 100644 index 8fc7e384..00000000 --- a/internal/db/stream_impl_ent_test.go +++ /dev/null @@ -1,293 +0,0 @@ -package db - -import ( - "context" - "github.com/samber/lo" - "github.com/satont/twitch-notifier/internal/db/db_models" - "github.com/stretchr/testify/assert" - "testing" -) - -func TestStreamEntService_GetByID(t *testing.T) { - t.Parallel() - - entClient, err := setupTest() - assert.NoError(t, err) - defer teardownTest(entClient) - - ctx := context.Background() - - channelsService := NewChannelEntService(entClient) - service := NewStreamEntService(entClient) - - newChannel, err := channelsService.Create(ctx, "1", db_models.ChannelServiceTwitch) - assert.NoError(t, err) - assert.Equal(t, "1", newChannel.ChannelID, "Expects channel_id to be equal.") - - _, err = channelsService.Create(ctx, "2", db_models.ChannelServiceTwitch) - assert.NoError(t, err) - - table := []struct { - name string - channelID string - wantNil bool - create bool - streamID string - }{ - { - name: "Get stream by id", - channelID: newChannel.ChannelID, - wantNil: false, - create: true, - streamID: "1", - }, - { - name: "Should return nil if stream not found", - channelID: "2", - wantNil: true, - create: false, - streamID: "2", - }, - } - - for _, tt := range table { - t.Run(tt.name, func(t *testing.T) { - if tt.create { - _, err = service.CreateOneByChannelID(ctx, newChannel.ID, &StreamUpdateQuery{ - IsLive: nil, - Category: nil, - Title: nil, - StreamID: tt.streamID, - }) - assert.NoError(t, err) - } - - stream, err := service.GetByID(ctx, tt.streamID) - if tt.wantNil { - assert.Nil(t, stream) - } else { - assert.NoError(t, err) - assert.Equal(t, newChannel.ID, stream.ChannelID, "Expects channel_id to be equal.") - assert.Equal(t, tt.streamID, stream.ID, "Expects stream_id to be equal.") - } - }) - } -} - -func TestStreamEntService_GetLatestByChannelID(t *testing.T) { - t.Parallel() - - entClient, err := setupTest() - assert.NoError(t, err) - defer teardownTest(entClient) - - ctx := context.Background() - - channelsService := NewChannelEntService(entClient) - service := NewStreamEntService(entClient) - - newChannel, err := channelsService.Create(ctx, "1", db_models.ChannelServiceTwitch) - assert.NoError(t, err) - - table := []struct { - name string - channelID string - wantNil bool - wantedStreamID string - clearTable bool - before func() - }{ - { - name: "Get latest stream by channel id", - channelID: newChannel.ChannelID, - wantNil: false, - wantedStreamID: "321", - clearTable: true, - before: func() { - _, _ = service.CreateOneByChannelID(ctx, newChannel.ID, &StreamUpdateQuery{ - StreamID: "321", - IsLive: lo.ToPtr(true), - Category: lo.ToPtr("Category"), - Title: lo.ToPtr("Title"), - }) - }, - }, - { - name: "Should return nil if stream not found", - channelID: newChannel.ChannelID, - wantNil: true, - wantedStreamID: "2", - clearTable: true, - before: func() {}, - }, - { - name: "Should return correct stream", - channelID: newChannel.ChannelID, - wantNil: false, - before: func() { - _, _ = service.CreateOneByChannelID(ctx, newChannel.ID, &StreamUpdateQuery{ - StreamID: "321", - IsLive: lo.ToPtr(false), - Category: lo.ToPtr("Category"), - Title: lo.ToPtr("Title"), - }) - _, _ = service.CreateOneByChannelID(ctx, newChannel.ID, &StreamUpdateQuery{ - StreamID: "4321", - IsLive: lo.ToPtr(true), - Category: lo.ToPtr("Category"), - Title: lo.ToPtr("Title"), - }) - }, - wantedStreamID: "4321", - clearTable: true, - }, - } - - for _, tt := range table { - t.Run(tt.name, func(t *testing.T) { - tt.before() - - stream, err := service.GetLatestByChannelID(ctx, newChannel.ID) - assert.NoError(t, err) - - if tt.wantNil { - assert.Nil(t, stream) - } else { - assert.NotNil(t, stream) - assert.Equal(t, newChannel.ID, stream.ChannelID, "Expects channel_id to be equal.") - assert.Equal(t, tt.wantedStreamID, stream.ID, "Expects stream_id to be equal.") - assert.Nil(t, stream.EndedAt, "Expects is_live to be equal.") - assert.Contains(t, stream.Categories, "Category", "Expects category to be equal.") - assert.Contains(t, stream.Titles, "Title", "Expects title to be equal.") - } - - if tt.clearTable { - _, err = entClient.Stream.Delete().Exec(ctx) - assert.NoError(t, err) - } - }) - } - -} - -func TestStreamEntService_GetManyByChannelID(t *testing.T) { - t.Parallel() - - entClient, err := setupTest() - assert.NoError(t, err) - - defer teardownTest(entClient) - - ctx := context.Background() - - channelsService := NewChannelEntService(entClient) - service := NewStreamEntService(entClient) - - newChannel, err := channelsService.Create(ctx, "1", db_models.ChannelServiceTwitch) - - assert.NoError(t, err) - - _, err = service.CreateOneByChannelID(ctx, newChannel.ID, &StreamUpdateQuery{ - StreamID: "123", - IsLive: lo.ToPtr(true), - Category: nil, - Title: nil, - }) - assert.NoError(t, err) - - _, err = service.CreateOneByChannelID(ctx, newChannel.ID, &StreamUpdateQuery{ - StreamID: "321", - IsLive: lo.ToPtr(true), - Category: lo.ToPtr("Category"), - Title: nil, - }) - assert.NoError(t, err) - - streams, err := service.GetManyByChannelID(ctx, newChannel.ID, 100) - assert.NoError(t, err) - - assert.Len(t, streams, 2, "Expects streams length to be equal.") - assert.Equal(t, "321", streams[0].ID, "Expects stream_id to be equal.") - assert.Contains(t, streams[0].Categories, "Category", "Expects category to be equal.") - assert.Equal(t, "123", streams[1].ID, "Expects stream_id to be equal.") - - _, err = entClient.Stream.Delete().Exec(ctx) - assert.NoError(t, err) - - streams, err = service.GetManyByChannelID(ctx, newChannel.ID, 100) - assert.NoError(t, err) - assert.Len(t, streams, 0, "Expects streams length to be equal.") -} - -func TestStreamEntService_UpdateOneByStreamID(t *testing.T) { - t.Parallel() - - entClient, err := setupTest() - assert.NoError(t, err) - - defer teardownTest(entClient) - - ctx := context.Background() - - channelsService := NewChannelEntService(entClient) - service := NewStreamEntService(entClient) - - newChannel, err := channelsService.Create(ctx, "1", db_models.ChannelServiceTwitch) - assert.NoError(t, err) - - _, err = service.CreateOneByChannelID(ctx, newChannel.ID, &StreamUpdateQuery{ - StreamID: "123", - IsLive: lo.ToPtr(true), - Category: nil, - Title: nil, - }) - assert.NoError(t, err) - - newStream, err := service.UpdateOneByStreamID(ctx, "123", &StreamUpdateQuery{ - IsLive: lo.ToPtr(false), - Title: lo.ToPtr("Title"), - Category: lo.ToPtr("Category"), - }) - assert.NoError(t, err) - - assert.Equal(t, "123", newStream.ID, "Expects stream_id to be equal.") - assert.Equal(t, newChannel.ID, newStream.ChannelID, "Expects channel_id to be equal.") - assert.Equal(t, "Title", newStream.Titles[0], "Expects title to be equal.") - assert.Equal(t, "Category", newStream.Categories[0], "Expects category to be equal.") - assert.NotNil(t, newStream.EndedAt, "Expects ended_at to be not nil.") - - stream, err := service.UpdateOneByStreamID(ctx, "321", &StreamUpdateQuery{}) - assert.Error(t, err) - assert.Nil(t, stream) -} - -func TestStreamEntService_CreateOneByChannelID(t *testing.T) { - t.Parallel() - - entClient, err := setupTest() - assert.NoError(t, err) - - defer teardownTest(entClient) - - ctx := context.Background() - - channelsService := NewChannelEntService(entClient) - service := NewStreamEntService(entClient) - - newChannel, err := channelsService.Create(ctx, "1", db_models.ChannelServiceTwitch) - assert.NoError(t, err) - - newStream, err := service.CreateOneByChannelID(ctx, newChannel.ID, &StreamUpdateQuery{ - StreamID: "123", - IsLive: lo.ToPtr(true), - Category: nil, - Title: nil, - }) - assert.NoError(t, err) - - assert.Equal(t, "123", newStream.ID, "Expects stream_id to be equal.") - assert.Equal(t, newChannel.ID, newStream.ChannelID, "Expects channel_id to be equal.") - assert.Nil(t, newStream.EndedAt, "Expects ended_at to be nil.") - assert.NotNil(t, newStream.StartedAt, "Expects started_at to be not nil.") - assert.Len(t, newStream.Categories, 0, "Expects categories length to be equal.") -} diff --git a/internal/message_sender/message_sender.go b/internal/message_sender/message_sender.go deleted file mode 100644 index e177f143..00000000 --- a/internal/message_sender/message_sender.go +++ /dev/null @@ -1,36 +0,0 @@ -package message_sender - -import ( - "context" - - "github.com/mr-linch/go-tg" - "github.com/satont/twitch-notifier/internal/db/db_models" -) - -type MessageOpts struct { - Text string - ImageURL string - ParseMode *tg.ParseMode - Buttons [][]KeyboardButton - SkipButtons bool -} - -type KeyboardButton struct { - // kostil chto bi skipnut knopki v gruppah - SkipInGroup bool - - Text string `json:"text"` - CallbackData string `json:"callback_data,omitempty"` - // this is not needed currently - // URL string `json:"url,omitempty"` - // WebApp *WebAppInfo `json:"web_app,omitempty"` - // LoginURL *LoginURL `json:"login_url,omitempty"` - // SwitchInlineQuery string `json:"switch_inline_query,omitempty"` - // SwitchInlineQueryCurrentChat string `json:"switch_inline_query_current_chat,omitempty"` - // CallbackGame *CallbackGame `json:"callback_game,omitempty"` - // Pay bool `json:"pay,omitempty"` -} - -type MessageSenderInterface interface { - SendMessage(ctx context.Context, chat *db_models.Chat, opts *MessageOpts) error -} diff --git a/internal/message_sender/message_sender_impl.go b/internal/message_sender/message_sender_impl.go deleted file mode 100644 index 040a6e07..00000000 --- a/internal/message_sender/message_sender_impl.go +++ /dev/null @@ -1,89 +0,0 @@ -package message_sender - -import ( - "context" - "strconv" - - "github.com/mr-linch/go-tg" - "github.com/satont/twitch-notifier/internal/db/db_models" -) - -type MessageSender struct { - telegram *tg.Client -} - -func (m *MessageSender) SendMessage(ctx context.Context, chat *db_models.Chat, opts *MessageOpts) error { - if chat.Service == db_models.ChatServiceTelegram { - chatId, err := strconv.Atoi(chat.ChatID) - if err != nil { - return err - } - - var keyboard *tg.InlineKeyboardMarkup - if opts.Buttons != nil && len(opts.Buttons) > 0 { - keyboard = &tg.InlineKeyboardMarkup{ - InlineKeyboard: make([][]tg.InlineKeyboardButton, 0, len(opts.Buttons)), - } - - for _, row := range opts.Buttons { - var buttons []tg.InlineKeyboardButton - for _, button := range row { - if button.SkipInGroup && chatId < 0 { - continue - } - - buttons = append( - buttons, tg.InlineKeyboardButton{ - Text: button.Text, - CallbackData: button.CallbackData, - }, - ) - } - - if len(buttons) != 0 { - keyboard.InlineKeyboard = append(keyboard.InlineKeyboard, buttons) - } - } - } - - if opts.ImageURL != "" { - query := m.telegram. - SendPhoto(tg.ChatID(chatId), tg.FileArg{URL: opts.ImageURL}). - Caption(opts.Text) - - if opts.ParseMode != nil { - query = query.ParseMode(*opts.ParseMode) - } - - if keyboard != nil && keyboard.InlineKeyboard != nil && len(keyboard.InlineKeyboard) > 0 { - query = query.ReplyMarkup(keyboard) - } - - return query.DoVoid(ctx) - } else { - query := m.telegram. - SendMessage(tg.ChatID(chatId), opts.Text). - LinkPreviewOptions(tg.LinkPreviewOptions{ - IsDisabled: true, - }) - - if keyboard != nil && keyboard.InlineKeyboard != nil && len(keyboard.InlineKeyboard) > 0 { - query = query.ReplyMarkup(keyboard) - } - - if opts.ParseMode != nil { - query = query.ParseMode(*opts.ParseMode) - } - - return query.DoVoid(ctx) - } - } - - return nil -} - -func NewMessageSender(telegram *tg.Client) MessageSenderInterface { - return &MessageSender{ - telegram: telegram, - } -} diff --git a/internal/message_sender/message_sender_impl_test.go b/internal/message_sender/message_sender_impl_test.go deleted file mode 100644 index 1b0283bc..00000000 --- a/internal/message_sender/message_sender_impl_test.go +++ /dev/null @@ -1,240 +0,0 @@ -package message_sender - -import ( - "context" - "encoding/json" - "fmt" - "io" - "net/http" - "net/http/httptest" - "net/url" - "testing" - - "github.com/mr-linch/go-tg" - "github.com/satont/twitch-notifier/internal/db/db_models" - - "github.com/satont/twitch-notifier/internal/test_utils" - "github.com/stretchr/testify/assert" -) - -func TestMessageSender_SendMessage(t *testing.T) { - t.Parallel() - - chat := &db_models.Chat{ - ChatID: "-123", - Service: db_models.ChatServiceTelegram, - } - - table := []struct { - name string - chat *db_models.Chat - opts *MessageOpts - createServer func(*testing.T) *httptest.Server - }{ - { - name: "should call send message method", - chat: chat, - opts: &MessageOpts{ - Text: "test", - }, - createServer: func(t *testing.T) *httptest.Server { - return httptest.NewServer( - http.HandlerFunc( - func(w http.ResponseWriter, r *http.Request) { - body, err := io.ReadAll(r.Body) - assert.NoError(t, err) - query, err := url.ParseQuery(string(body)) - assert.NoError(t, err) - - assert.Equal(t, "test", query.Get("text")) - assert.Equal(t, "-123", query.Get("chat_id")) - - assert.Equal(t, http.MethodPost, r.Method) - assert.Equal( - t, - fmt.Sprintf("/bot%s/sendMessage", test_utils.TelegramClientToken), - r.URL.Path, - ) - - w.WriteHeader(http.StatusOK) - _, _ = w.Write([]byte(test_utils.TelegramOkResponse)) - }, - ), - ) - }, - }, - { - name: "should call send photo method", - chat: chat, - opts: &MessageOpts{ - Text: "test photo", - ImageURL: "https://example.com/image.jpg", - }, - createServer: func(t *testing.T) *httptest.Server { - return httptest.NewServer( - http.HandlerFunc( - func(w http.ResponseWriter, r *http.Request) { - body, err := io.ReadAll(r.Body) - assert.NoError(t, err) - query, err := url.ParseQuery(string(body)) - assert.NoError(t, err) - - assert.Equal(t, "test photo", query.Get("caption")) - assert.Equal(t, "https://example.com/image.jpg", query.Get("photo")) - assert.Equal(t, "-123", query.Get("chat_id")) - - assert.Equal(t, http.MethodPost, r.Method) - assert.Equal( - t, - fmt.Sprintf("/bot%s/sendPhoto", test_utils.TelegramClientToken), - r.URL.Path, - ) - - w.WriteHeader(http.StatusOK) - _, _ = w.Write([]byte(test_utils.TelegramOkResponse)) - }, - ), - ) - }, - }, - { - name: "should call send message method with parse mode", - chat: chat, - opts: &MessageOpts{ - Text: "test md", - ParseMode: &tg.MD, - }, - createServer: func(t *testing.T) *httptest.Server { - return httptest.NewServer( - http.HandlerFunc( - func(w http.ResponseWriter, r *http.Request) { - body, err := io.ReadAll(r.Body) - assert.NoError(t, err) - query, err := url.ParseQuery(string(body)) - assert.NoError(t, err) - - assert.Equal(t, "test md", query.Get("text")) - assert.Equal(t, "-123", query.Get("chat_id")) - assert.Equal(t, "Markdown", query.Get("parse_mode")) - - assert.Equal(t, http.MethodPost, r.Method) - assert.Equal( - t, - fmt.Sprintf("/bot%s/sendMessage", test_utils.TelegramClientToken), - r.URL.Path, - ) - - w.WriteHeader(http.StatusOK) - _, _ = w.Write([]byte(test_utils.TelegramOkResponse)) - }, - ), - ) - }, - }, - { - name: "should send keyboard buttons", - chat: chat, - opts: &MessageOpts{ - Text: "test buttons", - Buttons: [][]KeyboardButton{ - { - KeyboardButton{Text: "click me", CallbackData: "click"}, - }, - }, - }, - createServer: func(t *testing.T) *httptest.Server { - return httptest.NewServer( - http.HandlerFunc( - func(w http.ResponseWriter, r *http.Request) { - body, err := io.ReadAll(r.Body) - assert.NoError(t, err) - query, err := url.ParseQuery(string(body)) - assert.NoError(t, err) - - assert.Equal(t, "test buttons", query.Get("text")) - assert.Equal(t, "-123", query.Get("chat_id")) - - keyboard := map[string]any{} - - err = json.Unmarshal([]byte(query.Get("reply_markup")), &keyboard) - assert.NoError(t, err) - - assert.Equal( - t, - "click me", - keyboard["inline_keyboard"].([]interface{})[0].([]interface{})[0].(map[string]any)["text"], - ) - assert.Equal( - t, - "click", - keyboard["inline_keyboard"].([]interface{})[0].([]interface{})[0].(map[string]any)["callback_data"], - ) - - assert.Equal(t, http.MethodPost, r.Method) - assert.Equal( - t, - fmt.Sprintf("/bot%s/sendMessage", test_utils.TelegramClientToken), - r.URL.Path, - ) - - w.WriteHeader(http.StatusOK) - _, _ = w.Write([]byte(test_utils.TelegramOkResponse)) - }, - ), - ) - }, - }, - { - name: "should skip button", - chat: chat, - opts: &MessageOpts{ - Text: "test buttons", - Buttons: [][]KeyboardButton{ - { - KeyboardButton{Text: "click me", CallbackData: "click", SkipInGroup: true}, - }, - }, - }, - createServer: func(t *testing.T) *httptest.Server { - return httptest.NewServer( - http.HandlerFunc( - func(w http.ResponseWriter, r *http.Request) { - body, err := io.ReadAll(r.Body) - assert.NoError(t, err) - query, err := url.ParseQuery(string(body)) - assert.NoError(t, err) - - assert.Equal(t, "test buttons", query.Get("text")) - assert.Equal(t, "-123", query.Get("chat_id")) - assert.Empty(t, query.Get("reply_markup")) - - assert.Equal(t, http.MethodPost, r.Method) - assert.Equal( - t, - fmt.Sprintf("/bot%s/sendMessage", test_utils.TelegramClientToken), - r.URL.Path, - ) - - w.WriteHeader(http.StatusOK) - _, _ = w.Write([]byte(test_utils.TelegramOkResponse)) - }, - ), - ) - }, - }, - } - - for _, tt := range table { - t.Run( - tt.name, func(c *testing.T) { - server := tt.createServer(c) - tgClient := test_utils.NewTelegramClient(server) - sender := NewMessageSender(tgClient) - - err := sender.SendMessage(context.Background(), tt.chat, tt.opts) - assert.NoError(c, err) - assert.Nil(c, err) - }, - ) - } -} diff --git a/internal/telegram/commands/broadcast.go b/internal/telegram/commands/broadcast.go deleted file mode 100644 index 55582591..00000000 --- a/internal/telegram/commands/broadcast.go +++ /dev/null @@ -1,77 +0,0 @@ -package commands - -import ( - "context" - "strconv" - "strings" - "sync" - - "github.com/mr-linch/go-tg" - "github.com/mr-linch/go-tg/tgb" - "github.com/samber/lo" - "github.com/satont/twitch-notifier/internal/db/db_models" - tgtypes "github.com/satont/twitch-notifier/internal/telegram/types" - "github.com/satont/twitch-notifier/internal/types" - "go.uber.org/zap" -) - -type BroadcastCommand struct { - *tgtypes.CommandOpts -} - -func (c *BroadcastCommand) HandleCommand(ctx context.Context, msg *tgb.MessageUpdate) error { - chats, err := c.Services.Chat.GetAllByService(ctx, db_models.ChatServiceTelegram) - if err != nil { - zap.S().Error(err) - return msg.Answer("Error").DoVoid(ctx) - } - - wg := sync.WaitGroup{} - wg.Add(len(chats)) - - for _, chat := range chats { - go func(chat *db_models.Chat) { - defer wg.Done() - - chatId, _ := strconv.Atoi(chat.ChatID) - - // filter channels, thay have negative id. - if chatId <= 0 { - return - } - - err := msg.Client. - SendMessage( - tg.ChatID(chatId), - strings.Replace(msg.Message.Text, "/broadcast ", "", 1), - ).DoVoid(ctx) - if err != nil { - zap.S().Error(err) - } - }(chat) - } - - wg.Wait() - - return nil -} - -var ( - broadcastCommandFilter = tgb.Command("broadcast") - broadcastCommandAdminFilter = func(services *types.Services) tgb.Filter { - return tgb.FilterFunc(func(ctx context.Context, update *tgb.Update) (bool, error) { - return lo.Contains(services.Config.TelegramBotAdmins, update.Message.Chat.ID.PeerID()), nil - }) - } -) - -func NewBroadcastCommand(opts *tgtypes.CommandOpts) { - cmd := &BroadcastCommand{ - CommandOpts: opts, - } - opts.Router.Message( - cmd.HandleCommand, - broadcastCommandFilter, - broadcastCommandAdminFilter(opts.Services), - ) -} diff --git a/internal/telegram/commands/broadcast_test.go b/internal/telegram/commands/broadcast_test.go deleted file mode 100644 index 2debeb35..00000000 --- a/internal/telegram/commands/broadcast_test.go +++ /dev/null @@ -1,89 +0,0 @@ -package commands - -import ( - "context" - "fmt" - "github.com/satont/twitch-notifier/internal/db/db_models" - "github.com/satont/twitch-notifier/internal/telegram/types" - "github.com/satont/twitch-notifier/internal/types" - "io" - "net/http" - "net/http/httptest" - "net/url" - "testing" - - "github.com/mr-linch/go-tg" - "github.com/mr-linch/go-tg/tgb" - "github.com/satont/twitch-notifier/internal/test_utils" - "github.com/satont/twitch-notifier/internal/test_utils/mocks" - "github.com/stretchr/testify/assert" -) - -func TestBroadcastCommand_HandleCommand(t *testing.T) { - t.Parallel() - - ctx := context.Background() - chatMock := &mocks.DbChatMock{} - - table := []struct { - name string - message *tgb.MessageUpdate - serverMock *httptest.Server - setupMocks func() - }{ - { - name: "Should call SendMessage for each chat", - message: &tgb.MessageUpdate{ - Message: &tg.Message{ - Text: "/broadcast test", - }, - }, - serverMock: httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - body, err := io.ReadAll(r.Body) - assert.NoError(t, err) - query, err := url.ParseQuery(string(body)) - assert.NoError(t, err) - assert.Equal(t, http.MethodPost, r.Method) - assert.Equal( - t, - fmt.Sprintf("/bot%s/sendMessage", test_utils.TelegramClientToken), - r.URL.Path, - ) - assert.Equal(t, "test", query.Get("text")) - assert.Contains(t, []string{"1", "2"}, query.Get("chat_id")) - - w.WriteHeader(http.StatusOK) - _, _ = w.Write([]byte(test_utils.TelegramOkResponse)) - })), - setupMocks: func() { - chatMock. - On("GetAllByService", ctx, db_models.ChatServiceTelegram). - Return( - []*db_models.Chat{{ChatID: "1"}, {ChatID: "2"}}, - nil, - ) - }, - }, - } - - for _, tt := range table { - tt := tt - t.Run(tt.name, func(t *testing.T) { - defer tt.serverMock.Close() - tt.setupMocks() - client := test_utils.NewTelegramClient(tt.serverMock) - tt.message.Client = client - cmd := &BroadcastCommand{ - CommandOpts: &tg_types.CommandOpts{ - Services: &types.Services{ - Chat: chatMock, - }, - }, - } - err := cmd.HandleCommand(ctx, tt.message) - assert.NoError(t, err) - - chatMock.AssertExpectations(t) - }) - } -} diff --git a/internal/telegram/commands/change_channel_id.go b/internal/telegram/commands/change_channel_id.go deleted file mode 100644 index 2701a5e2..00000000 --- a/internal/telegram/commands/change_channel_id.go +++ /dev/null @@ -1,64 +0,0 @@ -package commands - -import ( - "context" - "github.com/mr-linch/go-tg/tgb" - "github.com/samber/lo" - "github.com/satont/twitch-notifier/internal/db" - "github.com/satont/twitch-notifier/internal/db/db_models" - tgtypes "github.com/satont/twitch-notifier/internal/telegram/types" - "github.com/satont/twitch-notifier/internal/types" - "go.uber.org/zap" - "strings" -) - -type ChangeChannelId struct { - *tgtypes.CommandOpts -} - -func (c *ChangeChannelId) HandleCommand(ctx context.Context, msg *tgb.MessageUpdate) error { - text := strings.ReplaceAll(msg.Message.Text, "/change_channel_id ", "") - splittedText := strings.Split(strings.TrimSpace(text), " ") - - if len(splittedText) != 2 { - return nil - } - - sourceChannelID := splittedText[0] - targetChannelID := splittedText[1] - - _, err := c.Services.Channel.Update( - ctx, - sourceChannelID, - db_models.ChannelServiceTwitch, - &db.ChannelUpdateQuery{ - DangerNewChannelId: &targetChannelID, - }, - ) - - if err != nil { - zap.S().Error(err) - } - - return msg.Answer("done").DoVoid(ctx) -} - -var ( - changeChannelIdFilter = tgb.Command("change_channel_id") - changeChannelIdFilterAdminFilter = func(services *types.Services) tgb.Filter { - return tgb.FilterFunc(func(ctx context.Context, update *tgb.Update) (bool, error) { - return lo.Contains(services.Config.TelegramBotAdmins, update.Message.Chat.ID.PeerID()), nil - }) - } -) - -func NewChangeChannelId(opts *tgtypes.CommandOpts) { - cmd := &ChangeChannelId{ - CommandOpts: opts, - } - opts.Router.Message( - cmd.HandleCommand, - changeChannelIdFilter, - changeChannelIdFilterAdminFilter(opts.Services), - ) -} diff --git a/internal/telegram/commands/filters.go b/internal/telegram/commands/filters.go deleted file mode 100644 index 028fb146..00000000 --- a/internal/telegram/commands/filters.go +++ /dev/null @@ -1,37 +0,0 @@ -package commands - -import ( - "context" - - "github.com/mr-linch/go-tg" - "github.com/mr-linch/go-tg/tgb" -) - -var channelsAdminFilter = tgb.FilterFunc(func(ctx context.Context, update *tgb.Update) (bool, error) { - if update.Chat().Type == tg.ChatTypePrivate || update.Chat().Type == tg.ChatTypeSender { - return true, nil - } - - admins, err := update.Client.GetChatAdministrators(update.Chat().ID).Do(ctx) - if err != nil { - return false, err - } - - if update.CallbackQuery != nil { - for _, admin := range admins { - if admin.User.ID == update.CallbackQuery.From.ID { - return true, nil - } - } - } else if update.Message != nil && update.Message.From != nil { - for _, admin := range admins { - if admin.User.ID == update.Message.From.ID { - return true, nil - } - } - } else { - return true, nil - } - - return false, nil -}) diff --git a/internal/telegram/commands/follow.go b/internal/telegram/commands/follow.go deleted file mode 100644 index bd834332..00000000 --- a/internal/telegram/commands/follow.go +++ /dev/null @@ -1,180 +0,0 @@ -package commands - -import ( - "context" - "errors" - "github.com/mr-linch/go-tg/tgb" - "github.com/satont/twitch-notifier/internal/db/db_models" - tgtypes "github.com/satont/twitch-notifier/internal/telegram/types" - "go.uber.org/zap" - "regexp" - "strings" -) - -type FollowCommand struct { - *tgtypes.CommandOpts -} - -var ( - twitchInvalidNamesString = "Invalid login names, emails or IDs in request" - channelNotFoundError = errors.New("channel not found") - invalidNameError = errors.New(twitchInvalidNamesString) - TwitchLinkRegular = regexp.MustCompile(`(?:https?://)?(?:www\.)?twitch\.tv/(\w+)`) -) - -func (c *FollowCommand) createFollow( - ctx context.Context, - chat *db_models.Chat, - input string, -) (*db_models.Follow, error) { - twitchChannel, err := c.Services.Twitch.GetUser("", input) - if err != nil { - if err.Error() == twitchInvalidNamesString { - return nil, invalidNameError - } - - return nil, err - } - - if twitchChannel == nil { - return nil, channelNotFoundError - } - - dbChannel, err := c.Services.Channel.GetByIdOrCreate( - ctx, - twitchChannel.ID, - db_models.ChannelServiceTwitch, - ) - if err != nil { - return nil, err - } - - follow, err := c.Services.Follow.Create(ctx, dbChannel.ID, chat.ID) - if err != nil { - return nil, err - } - - return follow, nil -} - -func (c *FollowCommand) handleScene(ctx context.Context, msg *tgb.MessageUpdate) error { - chat := c.SessionManager.Get(ctx).Chat - - nicknames := make([]string, 0) - - regularMatches := TwitchLinkRegular.FindAllStringSubmatch(msg.Text, -1) - - if len(regularMatches) > 0 { - for _, match := range regularMatches { - nicknames = append(nicknames, match[1]) - } - } else { - nicknames = append(nicknames, msg.Text) - } - - succeeded := make([]string, 0) - failed := make([]string, 0) - - for _, nickname := range nicknames { - _, err := c.createFollow(ctx, chat, nickname) - - if errors.Is(err, channelNotFoundError) { - message := c.Services.I18N.Translate( - "commands.follow.errors.streamerNotFound", - chat.Settings.ChatLanguage.String(), - map[string]string{ - "streamer": nickname, - }, - ) - failed = append(failed, message) - } else if errors.Is(err, db_models.FollowAlreadyExistsError) { - message := c.Services.I18N.Translate( - "commands.follow.errors.alreadyFollowed", - chat.Settings.ChatLanguage.String(), - map[string]string{ - "streamer": nickname, - }, - ) - failed = append(failed, message) - } else if errors.Is(err, invalidNameError) { - message := c.Services.I18N.Translate( - "commands.follow.errors.badUsername", - chat.Settings.ChatLanguage.String(), - map[string]string{ - "streamer": nickname, - }, - ) - failed = append(failed, message) - } else if err != nil { - zap.S().Error(err) - failed = append(failed, "internal error") - } else { - message := c.Services.I18N.Translate( - "commands.follow.success", - chat.Settings.ChatLanguage.String(), - map[string]string{ - "streamer": nickname, - }, - ) - succeeded = append(succeeded, message) - } - } - - c.SessionManager.Get(ctx).Scene = "" - - message := strings.Join(succeeded, "\n") - message += "\n\n" - message += strings.Join(failed, "\n") - - return msg.Answer(message).DoVoid(ctx) -} - -func (c *FollowCommand) HandleCommand(ctx context.Context, msg *tgb.MessageUpdate) error { - session := c.SessionManager.Get(ctx) - - text := strings.ReplaceAll(msg.Text, "/follow", "") - text = strings.TrimSpace(text) - - if text != "" { - msg.Text = text - return c.handleScene(ctx, msg) - } else { - c.SessionManager.Get(ctx).Scene = "follow" - return msg. - Answer(c.Services.I18N.Translate( - "commands.follow.enter", - session.Chat.Settings.ChatLanguage.String(), - nil, - )). - DoVoid(ctx) - } -} - -var ( - followCommandQuery = tgb.Command("follow") -) - -func NewFollowCommand(opts *tgtypes.CommandOpts) { - cmd := &FollowCommand{ - CommandOpts: opts, - } - - sceneFilter := []tgb.Filter{ - channelsAdminFilter, - tgb.FilterFunc(func(ctx context.Context, update *tgb.Update) (bool, error) { - session := opts.SessionManager.Get(ctx) - return session.Scene == "follow", nil - }), - } - - opts.Router.Message(cmd.handleScene, sceneFilter...) - opts.Router.ChannelPost(cmd.handleScene, sceneFilter...) - - messageFilter := []tgb.Filter{ - channelsAdminFilter, - followCommandQuery, - } - - opts.Router.Message(cmd.HandleCommand, messageFilter...) - opts.Router.ChannelPost(cmd.HandleCommand, messageFilter...) -} diff --git a/internal/telegram/commands/follow_test.go b/internal/telegram/commands/follow_test.go deleted file mode 100644 index 79afe2e5..00000000 --- a/internal/telegram/commands/follow_test.go +++ /dev/null @@ -1,424 +0,0 @@ -package commands - -import ( - "context" - "errors" - "fmt" - "github.com/satont/twitch-notifier/internal/db/db_models" - "github.com/satont/twitch-notifier/internal/telegram/types" - "github.com/satont/twitch-notifier/internal/types" - "github.com/satont/twitch-notifier/pkg/i18n/mocks" - "github.com/stretchr/testify/mock" - "net/http" - "net/http/httptest" - "testing" - - "github.com/google/uuid" - "github.com/mr-linch/go-tg" - "github.com/mr-linch/go-tg/tgb" - "github.com/nicklaw5/helix/v2" - "github.com/satont/twitch-notifier/internal/test_utils" - "github.com/satont/twitch-notifier/internal/test_utils/mocks" - "github.com/stretchr/testify/assert" -) - -func TestFollowService(t *testing.T) { - t.Parallel() - - mockedTwitch := &mocks.TwitchApiMock{} - channelsMock := &mocks.DbChannelMock{} - followsMock := &mocks.DbFollowMock{} - i18nMock := i18nmocks.NewI18nMock() - - userLogin := "fukushine" - user := &helix.User{ - ID: "1", - Login: userLogin, - DisplayName: "Fukushine", - } - - ctx := context.Background() - - chat := &db_models.Chat{ - ID: uuid.New(), - } - chann := &db_models.Channel{ - ID: uuid.New(), - ChannelID: "1", - } - f := &db_models.Follow{} - - follow := &FollowCommand{ - &tg_types.CommandOpts{ - Services: &types.Services{ - Twitch: mockedTwitch, - Channel: channelsMock, - Follow: followsMock, - I18N: i18nMock, - }, - }, - } - - // table tests - table := []struct { - name string - input string - want *db_models.Follow - wantErr bool - setupMocks func() - }{ - { - name: "Should fail because of GetUser error", - input: "fukushine2", - want: nil, - wantErr: true, - setupMocks: func() { - mockedTwitch.On("GetUser", "", "fukushine2").Return((*helix.User)(nil), nil) - }, - }, - { - name: "Should create", - input: userLogin, - want: f, - wantErr: false, - setupMocks: func() { - mockedTwitch. - On("GetUser", "", userLogin).Return(user, nil) - channelsMock. - On("GetByIdOrCreate", ctx, user.ID, db_models.ChannelServiceTwitch).Return(chann, nil) - followsMock. - On("Create", ctx, chann.ID, chat.ID).Return(f, nil) - }, - }, - { - name: "Should fail because follow exists", - input: userLogin, - want: nil, - wantErr: true, - setupMocks: func() { - mockedTwitch. - On("GetUser", "", userLogin).Return(user, nil) - channelsMock. - On("GetByIdOrCreate", ctx, user.ID, db_models.ChannelServiceTwitch).Return(chann, nil) - followsMock. - On("Create", ctx, chann.ID, chat.ID).Return((*db_models.Follow)(nil), db_models.FollowAlreadyExistsError) - }, - }, - } - - for _, tt := range table { - t.Run(tt.name, func(t *testing.T) { - tt.setupMocks() - - got, err := follow.createFollow(ctx, chat, tt.input) - if tt.wantErr { - assert.Error(t, err) - } else { - assert.NoError(t, err) - assert.Equal(t, tt.want, got) - } - - mockedTwitch.AssertExpectations(t) - channelsMock.AssertExpectations(t) - followsMock.AssertExpectations(t) - - mockedTwitch.ExpectedCalls = nil - channelsMock.ExpectedCalls = nil - followsMock.ExpectedCalls = nil - }) - } -} - -func TestFollowCommand_HandleCommand(t *testing.T) { - t.Parallel() - - ctx := context.Background() - - sessionService := tg_types.NewMockedSessionManager() - - sessionService.On("Get", ctx).Return(&tg_types.Session{ - Chat: &db_models.Chat{ - ChatID: "123", - Settings: &db_models.ChatSettings{ - ChatLanguage: db_models.ChatLanguageEn, - }, - }, - }) - - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, http.MethodPost, r.Method) - assert.Equal( - t, - fmt.Sprintf("/bot%s/sendMessage", test_utils.TelegramClientToken), - r.URL.Path, - ) - - w.WriteHeader(http.StatusOK) - _, _ = w.Write([]byte(test_utils.TelegramOkResponse)) - })) - - tgClient := test_utils.NewTelegramClient(server) - - i18nMock := i18nmocks.NewI18nMock() - i18nMock. - On( - "Translate", - "commands.follow.enter", - "en", - (map[string]string)(nil), - ). - Return("test") - - followCommand := &FollowCommand{ - &tg_types.CommandOpts{ - SessionManager: sessionService, - Services: &types.Services{ - I18N: i18nMock, - }, - }, - } - - assert.Equal(t, "", sessionService.Get(ctx).Scene) - err := followCommand.HandleCommand(ctx, &tgb.MessageUpdate{ - Client: tgClient, - Message: &tg.Message{ - Chat: tg.Chat{ - ID: 123, - }, - }, - }) - assert.NoError(t, err) - assert.Equal(t, "follow", sessionService.Get(ctx).Scene) - - sessionService.AssertExpectations(t) - i18nMock.AssertExpectations(t) -} - -func TestFollowCommand_HandleScene(t *testing.T) { - t.Parallel() - - mockedTwitch := &mocks.TwitchApiMock{} - channelsMock := &mocks.DbChannelMock{} - followsMock := &mocks.DbFollowMock{} - i18nMock := i18nmocks.NewI18nMock() - sessionMock := tg_types.NewMockedSessionManager() - - ctx := context.Background() - - userLogin := "satont" - helixUser := &helix.User{ - ID: "1", - Login: userLogin, - DisplayName: "Satont", - } - - dbChat := &db_models.Chat{ - ID: uuid.New(), - Settings: &db_models.ChatSettings{ - ChatLanguage: db_models.ChatLanguageEn, - }, - } - dbChannel := &db_models.Channel{ - ID: uuid.New(), - ChannelID: "1", - } - - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, http.MethodPost, r.Method) - assert.Equal( - t, - fmt.Sprintf("/bot%s/sendMessage", test_utils.TelegramClientToken), - r.URL.Path, - ) - - w.WriteHeader(http.StatusOK) - _, _ = w.Write([]byte(test_utils.TelegramOkResponse)) - })) - defer server.Close() - tgMockedServer := test_utils.NewTelegramClient(server) - - sessionMock.On("Get", ctx).Return(&tg_types.Session{ - Chat: dbChat, - }) - - var clearMocks = func() { - mockedTwitch.ExpectedCalls = nil - channelsMock.ExpectedCalls = nil - followsMock.ExpectedCalls = nil - i18nMock.ExpectedCalls = nil - - mockedTwitch.Calls = nil - channelsMock.Calls = nil - followsMock.Calls = nil - i18nMock.Calls = nil - } - - table := []struct { - name string - input string - setupMocks func() - asserts func(t *testing.T, err error) - }{ - { - name: "Should fail because of GetUser error", - input: "satont", - setupMocks: func() { - mockedTwitch. - On("GetUser", "", userLogin). - Return((*helix.User)(nil), nil) - i18nMock.On( - "Translate", - "commands.follow.errors.streamerNotFound", - "en", - map[string]string{"streamer": userLogin}, - ).Return("") - }, - asserts: func(t *testing.T, err error) { - assert.NoError(t, err) - - i18nMock.AssertExpectations(t) - mockedTwitch.AssertExpectations(t) - channelsMock.AssertExpectations(t) - followsMock.AssertExpectations(t) - - clearMocks() - }, - }, - { - name: "Should fail because db follow exists", - input: userLogin, - setupMocks: func() { - mockedTwitch.On("GetUser", "", userLogin).Return(helixUser, nil) - channelsMock. - On("GetByIdOrCreate", ctx, helixUser.ID, db_models.ChannelServiceTwitch). - Return(dbChannel, nil) - followsMock. - On("Create", ctx, dbChannel.ID, dbChat.ID). - Return((*db_models.Follow)(nil), db_models.FollowAlreadyExistsError) - i18nMock.On( - "Translate", - "commands.follow.errors.alreadyFollowed", - "en", - map[string]string{"streamer": userLogin}, - ).Return("") - }, - asserts: func(t *testing.T, err error) { - assert.NoError(t, err) - - i18nMock.AssertExpectations(t) - mockedTwitch.AssertExpectations(t) - channelsMock.AssertExpectations(t) - followsMock.AssertExpectations(t) - - clearMocks() - }, - }, - { - name: "Should fail because db channel cannot be created", - input: userLogin, - setupMocks: func() { - mockedTwitch.On("GetUser", "", userLogin).Return(helixUser, nil) - channelsMock. - On("GetByIdOrCreate", ctx, helixUser.ID, db_models.ChannelServiceTwitch). - Return(dbChannel, errors.New("some error")) - }, - asserts: func(t *testing.T, err error) { - assert.NoError(t, err) - - i18nMock.AssertExpectations(t) - mockedTwitch.AssertExpectations(t) - channelsMock.AssertExpectations(t) - followsMock.AssertExpectations(t) - - clearMocks() - }, - }, - { - name: "Should success", - input: userLogin, - setupMocks: func() { - mockedTwitch.On("GetUser", "", userLogin).Return(helixUser, nil) - channelsMock. - On("GetByIdOrCreate", ctx, helixUser.ID, db_models.ChannelServiceTwitch). - Return(dbChannel, nil) - followsMock. - On("Create", ctx, dbChannel.ID, dbChat.ID). - Return((*db_models.Follow)(nil), nil) - i18nMock.On( - "Translate", - "commands.follow.success", - "en", - map[string]string{"streamer": userLogin}, - ).Return("") - }, - asserts: func(t *testing.T, err error) { - assert.NoError(t, err) - - i18nMock.AssertExpectations(t) - mockedTwitch.AssertExpectations(t) - channelsMock.AssertExpectations(t) - followsMock.AssertExpectations(t) - - clearMocks() - }, - }, - { - name: "Should create multiple follows", - input: "https://www.twitch.tv/satont, https://www.twitch.tv/satont2", - setupMocks: func() { - mockedTwitch.On("GetUser", mock.Anything, mock.Anything).Return(helixUser, nil) - channelsMock. - On("GetByIdOrCreate", ctx, helixUser.ID, db_models.ChannelServiceTwitch). - Return(dbChannel, nil) - followsMock. - On("Create", ctx, dbChannel.ID, dbChat.ID). - Return((*db_models.Follow)(nil), nil) - i18nMock.On( - "Translate", - "commands.follow.success", - "en", - mock.Anything, - ).Return("") - }, - asserts: func(t *testing.T, err error) { - assert.NoError(t, err) - - mockedTwitch.AssertNumberOfCalls(t, "GetUser", 2) - channelsMock.AssertNumberOfCalls(t, "GetByIdOrCreate", 2) - followsMock.AssertNumberOfCalls(t, "Create", 2) - i18nMock.AssertNumberOfCalls(t, "Translate", 2) - - clearMocks() - }, - }, - } - - for _, tt := range table { - t.Run(tt.name, func(t *testing.T) { - tt.setupMocks() - - followCommand := &FollowCommand{ - &tg_types.CommandOpts{ - SessionManager: sessionMock, - Services: &types.Services{ - Twitch: mockedTwitch, - Channel: channelsMock, - Follow: followsMock, - I18N: i18nMock, - }, - }, - } - - tgMsg := &tgb.MessageUpdate{ - Client: tgMockedServer, - Message: &tg.Message{ - Chat: tg.Chat{ID: 1}, - Text: tt.input, - }, - } - - err := followCommand.handleScene(ctx, tgMsg) - tt.asserts(t, err) - }) - } -} diff --git a/internal/telegram/commands/follows.go b/internal/telegram/commands/follows.go deleted file mode 100644 index 626ec5cf..00000000 --- a/internal/telegram/commands/follows.go +++ /dev/null @@ -1,249 +0,0 @@ -package commands - -import ( - "context" - "errors" - "fmt" - "math" - "strings" - - "github.com/mr-linch/go-tg" - "github.com/mr-linch/go-tg/tgb" - "github.com/samber/lo" - "github.com/satont/twitch-notifier/internal/db/db_models" - tgtypes "github.com/satont/twitch-notifier/internal/telegram/types" - "go.uber.org/zap" -) - -type FollowsCommand struct { - *tgtypes.CommandOpts -} - -const followsMaxRows = 3 -const followsPerRow = 3 - -func (c *FollowsCommand) newKeyboard( - ctx context.Context, - maxRows, perRow int, -) (*tg.InlineKeyboardMarkup, error) { - session := c.SessionManager.Get(ctx) - - limit := maxRows * perRow - offset := (session.FollowsMenu.CurrentPage - 1) * limit - - if offset < 0 { - offset = 0 - } - - layout := tg.NewButtonLayout[tg.InlineKeyboardButton](perRow) - - follows, err := c.Services.Follow.GetByChatID( - ctx, - session.Chat.ID, - limit, - offset, - ) - if err != nil { - zap.S().Error(err) - return nil, err - } - if len(follows) == 0 { - markup := tg.NewInlineKeyboardMarkup(layout.Keyboard()...) - return &markup, nil - } - - totalFollows, err := c.Services.Follow.CountByChatID(ctx, session.Chat.ID) - if err != nil { - zap.S().Error(err) - return nil, err - } - - session.FollowsMenu.TotalPages = int(math.Ceil(float64(totalFollows) / float64(limit))) - // spew.Dump(totalFollows) - // spew.Dump(session.FollowsMenu) - // spew.Dump(session.FollowsMenu.CurrentPage) - - channelsIds := lo.Map( - follows, func(follow *db_models.Follow, _ int) string { - return follow.Channel.ChannelID - }, - ) - - channels, err := c.Services.Twitch.GetChannelsByUserIds(channelsIds) - - if err != nil { - return nil, err - } - - for _, channel := range channels { - internalChannel, _ := lo.Find( - follows, - func(follow *db_models.Follow) bool { - return follow.Channel.ChannelID == channel.BroadcasterID - }, - ) - - layout.Insert( - tg.NewInlineKeyboardButtonCallback( - channel.BroadcasterName, - fmt.Sprintf("channels_unfollow_%s", internalChannel.ChannelID), - ), - ) - } - - var paginationRow *tg.ButtonLayout[tg.InlineKeyboardButton] - - if session.FollowsMenu.CurrentPage > 1 || - session.FollowsMenu.CurrentPage < session.FollowsMenu.TotalPages { - paginationRow = layout.Row() - - // Add "Prev" button - if session.FollowsMenu.CurrentPage > 1 { - paginationRow.Insert( - tg.NewInlineKeyboardButtonCallback( - "«", - "channels_unfollow_prev_page", - ), - ) - } - - // Add "Next" button - if session.FollowsMenu.CurrentPage < session.FollowsMenu.TotalPages { - paginationRow.Insert( - tg.NewInlineKeyboardButtonCallback( - "»", - "channels_unfollow_next_page", - ), - ) - } - } - - markup := tg.NewInlineKeyboardMarkup(layout.Keyboard()...) - - return &markup, nil -} - -func (c *FollowsCommand) HandleCommand(ctx context.Context, msg *tgb.MessageUpdate) error { - session := c.SessionManager.Get(ctx) - - session.FollowsMenu.TotalPages = 1 - session.FollowsMenu.CurrentPage = 1 - - keyboard, err := c.newKeyboard(ctx, followsMaxRows, followsPerRow) - if err != nil { - zap.S().Error(err) - return msg.Answer("internal error").DoVoid(ctx) - } - - totalFollows, err := c.Services.Follow.CountByChatID(ctx, session.Chat.ID) - - return msg. - Answer( - c.Services.I18N.Translate( - "commands.follows.total", - session.Chat.Settings.ChatLanguage.String(), - map[string]string{"count": fmt.Sprintf("%v", totalFollows)}, - ), - ). - ReplyMarkup(keyboard).DoVoid(ctx) -} - -func (c *FollowsCommand) handleUnfollow( - ctx context.Context, - chat *db_models.Chat, - input string, -) error { - channelID := strings.Replace(input, "channels_unfollow_", "", 1) - - channel, err := c.Services.Channel.GetByID(ctx, channelID, db_models.ChannelServiceTwitch) - if err != nil { - return err - } - - follow, err := c.Services.Follow.GetByChatAndChannel(ctx, channel.ID, chat.ID) - if err != nil { - return err - } - - return c.Services.Follow.Delete(ctx, follow.ID) -} - -func (c *FollowsCommand) unfollowQuery(ctx context.Context, msg *tgb.CallbackQueryUpdate) error { - chat := c.SessionManager.Get(ctx).Chat - - if err := c.handleUnfollow(ctx, chat, msg.CallbackQuery.Data); err != nil { - if errors.Is(err, db_models.FollowNotFoundError) { - return msg.Answer().Text("already unfollowed").DoVoid(ctx) - } - - zap.S().Error(err) - - return msg.Answer().Text("internal error").DoVoid(ctx) - } - - return msg.Answer().Text("unfollowed").DoVoid(ctx) -} - -func (c *FollowsCommand) prevPageQuery(ctx context.Context, msg *tgb.CallbackQueryUpdate) error { - session := c.SessionManager.Get(ctx) - - if session.FollowsMenu.CurrentPage > 0 { - session.FollowsMenu.CurrentPage-- - } - - keyboard, err := c.newKeyboard(ctx, followsMaxRows, followsPerRow) - if err != nil { - zap.S().Error(err) - } - - return msg.Client. - EditMessageReplyMarkup(msg.Message.Chat().ID, msg.Message.MessageID()). - ReplyMarkup(*keyboard). - DoVoid(ctx) -} - -func (c *FollowsCommand) nextPageQuery(ctx context.Context, msg *tgb.CallbackQueryUpdate) error { - session := c.SessionManager.Get(ctx) - - if session.FollowsMenu.CurrentPage+1 <= session.FollowsMenu.TotalPages { - session.FollowsMenu.CurrentPage++ - } - - keyboard, err := c.newKeyboard(ctx, followsMaxRows, followsPerRow) - if err != nil { - zap.S().Error(err) - } - - return msg.Client. - EditMessageReplyMarkup(msg.Message.Chat().ID, msg.Message.MessageID()). - ReplyMarkup(*keyboard). - DoVoid(ctx) -} - -var ( - followsCommandFilter = tgb.Command( - "follows", - tgb.WithCommandAlias("unfollow"), - ) - followsPrevPageQuery = tgb.TextEqual("channels_unfollow_prev_page") - followsNextPageQuery = tgb.TextEqual("channels_unfollow_next_page") - followUnfollowQuery = tgb.TextHasPrefix("channels_unfollow_") -) - -func NewFollowsCommand(opts *tgtypes.CommandOpts) { - cmd := &FollowsCommand{ - CommandOpts: opts, - } - - messageFilter := []tgb.Filter{ - channelsAdminFilter, - followsCommandFilter, - } - - opts.Router.Message(cmd.HandleCommand, messageFilter...) - opts.Router.ChannelPost(cmd.HandleCommand, messageFilter...) - - opts.Router.CallbackQuery(cmd.prevPageQuery, channelsAdminFilter, followsPrevPageQuery) - opts.Router.CallbackQuery(cmd.nextPageQuery, channelsAdminFilter, followsNextPageQuery) - opts.Router.CallbackQuery(cmd.unfollowQuery, channelsAdminFilter, followUnfollowQuery) -} diff --git a/internal/telegram/commands/follows_test.go b/internal/telegram/commands/follows_test.go deleted file mode 100644 index 68f9293e..00000000 --- a/internal/telegram/commands/follows_test.go +++ /dev/null @@ -1,429 +0,0 @@ -package commands - -import ( - "context" - "io" - "net/http" - "net/http/httptest" - "net/url" - "strconv" - "testing" - - "github.com/mr-linch/go-tg" - "github.com/mr-linch/go-tg/tgb" - "github.com/nicklaw5/helix/v2" - "github.com/samber/lo" - db_models2 "github.com/satont/twitch-notifier/internal/db/db_models" - "github.com/satont/twitch-notifier/internal/telegram/types" - "github.com/satont/twitch-notifier/internal/test_utils" - "github.com/satont/twitch-notifier/internal/types" - i18nmocks "github.com/satont/twitch-notifier/pkg/i18n/mocks" - - "github.com/google/uuid" - "github.com/satont/twitch-notifier/internal/test_utils/mocks" - "github.com/stretchr/testify/assert" -) - -func TestFollowsCommand_handleUnfollow(t *testing.T) { - t.Parallel() - - type fields struct { - CommandOpts *tg_types.CommandOpts - } - type args struct { - ctx context.Context - chat *db_models2.Chat - input string - } - - // mockedTwitch := &twitch.MockedService{} - channelsMock := &mocks.DbChannelMock{} - followsMock := &mocks.DbFollowMock{} - - ctx := context.Background() - chat := &db_models2.Chat{ - ID: uuid.New(), - ChatID: "1", - } - - commandOpts := &tg_types.CommandOpts{ - Services: &types.Services{ - Channel: channelsMock, - Follow: followsMock, - }, - } - - tests := []struct { - name string - fields fields - args args - wantErr bool - wantedErr error - setupMocks func() - }{ - { - name: "should return error if channel not found", - fields: fields{CommandOpts: commandOpts}, - args: args{ - ctx: ctx, - chat: chat, - input: "channels_unfollow_1", - }, - wantErr: true, - wantedErr: db_models2.ChannelNotFoundError, - setupMocks: func() { - channelsMock. - On("GetByID", ctx, "1", db_models2.ChannelServiceTwitch). - Return((*db_models2.Channel)(nil), db_models2.ChannelNotFoundError) - }, - }, - { - name: "should return error if follow not found", - fields: fields{ - CommandOpts: commandOpts, - }, - args: args{ - ctx: ctx, - chat: chat, - input: "channels_unfollow_1", - }, - wantErr: true, - wantedErr: db_models2.FollowNotFoundError, - setupMocks: func() { - channelId := uuid.New() - channelsMock. - On("GetByID", ctx, "1", db_models2.ChannelServiceTwitch). - Return( - &db_models2.Channel{ - ID: channelId, - ChannelID: "1", - }, nil, - ) - followsMock. - On("GetByChatAndChannel", ctx, channelId, chat.ID). - Return((*db_models2.Follow)(nil), db_models2.FollowNotFoundError) - }, - }, - { - name: "should return nil", - fields: fields{ - CommandOpts: commandOpts, - }, - args: args{ - ctx: ctx, - chat: chat, - input: "channels_unfollow_1", - }, - wantErr: false, - wantedErr: nil, - setupMocks: func() { - channelID := uuid.New() - followID := uuid.New() - channelsMock. - On("GetByID", ctx, "1", db_models2.ChannelServiceTwitch). - Return( - &db_models2.Channel{ - ID: channelID, - ChannelID: "1", - }, nil, - ) - followsMock. - On("GetByChatAndChannel", ctx, channelID, chat.ID). - Return( - &db_models2.Follow{ - ID: followID, - }, nil, - ) - followsMock. - On("Delete", ctx, followID). - Return(nil) - }, - }, - } - for _, tt := range tests { - t.Run( - tt.name, func(t *testing.T) { - c := &FollowsCommand{ - CommandOpts: tt.fields.CommandOpts, - } - - tt.setupMocks() - - err := c.handleUnfollow(tt.args.ctx, tt.args.chat, tt.args.input) - if tt.wantErr { - assert.ErrorIs(t, err, tt.wantedErr) - } - - channelsMock.AssertExpectations(t) - - channelsMock.ExpectedCalls = nil - }, - ) - } -} - -func TestFollowsCommand_HandleCommand(t *testing.T) { - t.Parallel() - - sessionMock := tg_types.NewMockedSessionManager() - followsMock := &mocks.DbFollowMock{} - i18nMock := i18nmocks.NewI18nMock() - - ctx := context.Background() - chat := &db_models2.Chat{ - ID: uuid.New(), - ChatID: "1", - Settings: &db_models2.ChatSettings{ - ChatLanguage: db_models2.ChatLanguageEn, - }, - } - - session := &tg_types.Session{ - Chat: chat, - FollowsMenu: &tg_types.Menu{ - CurrentPage: 5, - TotalPages: 10, - }, - } - - sessionMock.On("Get", ctx).Return(session) - followsMock.On("GetByChatID", ctx, chat.ID, 9, 0).Return([]*db_models2.Follow{}, nil) - followsMock.On("CountByChatID", ctx, chat.ID).Return(1, nil) - i18nMock. - On( - "Translate", - "commands.follows.total", - "en", - map[string]string{"count": "1"}, - ).Return("Total: 1") - - commandOpts := &tg_types.CommandOpts{ - Services: &types.Services{ - Follow: followsMock, - I18N: i18nMock, - }, - SessionManager: sessionMock, - } - - cmd := &FollowsCommand{CommandOpts: commandOpts} - - server := httptest.NewServer( - http.HandlerFunc( - func(w http.ResponseWriter, r *http.Request) { - body, _ := io.ReadAll(r.Body) - query, _ := url.ParseQuery(string(body)) - - assert.Greater(t, len(query.Get("text")), 1) - - w.WriteHeader(http.StatusOK) - _, _ = w.Write([]byte(test_utils.TelegramOkResponse)) - }, - ), - ) - defer server.Close() - - msg := &tgb.MessageUpdate{ - Client: test_utils.NewTelegramClient(server), - Message: &tg.Message{ - Chat: tg.Chat{ID: 1}, - }, - } - - err := cmd.HandleCommand(ctx, msg) - assert.NoError(t, err) -} - -func TestFollowsCommand_newKeyboard(t *testing.T) { - t.Parallel() - - ctx := context.Background() - - followsMock := &mocks.DbFollowMock{} - sessionsMock := tg_types.NewMockedSessionManager() - twitchMock := &mocks.TwitchApiMock{} - - dbChat := &db_models2.Chat{ - ID: uuid.New(), - ChatID: "1", - Settings: &db_models2.ChatSettings{ - ChatLanguage: db_models2.ChatLanguageEn, - }, - } - - session := &tg_types.Session{ - Chat: dbChat, - FollowsMenu: &tg_types.Menu{ - CurrentPage: 1, - TotalPages: 0, - }, - } - - entityId := uuid.New() - channelId := uuid.New() - - table := []struct { - name string - setupMocks func() - asserts func(t *testing.T, keyboard *tg.InlineKeyboardMarkup) - }{ - { - name: "should return keyboard with 1 page and no next and prev buttons", - setupMocks: func() { - sessionsMock.On("Get", ctx).Return(session) - followsMock.On("GetByChatID", ctx, dbChat.ID, 9, 0). - Return( - []*db_models2.Follow{ - { - ID: entityId, - ChannelID: channelId, - ChatID: dbChat.ID, - Channel: &db_models2.Channel{ - ID: channelId, - ChannelID: "1", - }, - }, - }, nil, - ) - followsMock.On("CountByChatID", ctx, dbChat.ID). - Return(1, nil) - twitchMock.On("GetChannelsByUserIds", []string{"1"}). - Return( - []helix.ChannelInformation{ - {BroadcasterID: "1", BroadcasterName: "Satont"}, - }, nil, - ) - }, - asserts: func(t *testing.T, keyboard *tg.InlineKeyboardMarkup) { - assert.Len(t, keyboard.InlineKeyboard, 1) - assert.Len(t, keyboard.InlineKeyboard[0], 1) - assert.Equal(t, keyboard.InlineKeyboard[0][0].Text, "Satont") - assert.Equal(t, keyboard.InlineKeyboard[0][0].CallbackData, "channels_unfollow_"+channelId.String()) - }, - }, - { - name: "should return keyboard with 2 pages and next buttons", - setupMocks: func() { - sessionsMock.On("Get", ctx).Return(session) - follows := make([]*db_models2.Follow, 0, 20) - for i := 0; i < 20; i++ { - follows = append( - follows, &db_models2.Follow{ - ID: uuid.New(), - ChannelID: uuid.New(), - ChatID: dbChat.ID, - Channel: &db_models2.Channel{ - ID: uuid.New(), - ChannelID: strconv.Itoa(i), - }, - }, - ) - } - followsMock.On("GetByChatID", ctx, dbChat.ID, 9, 0). - Return(follows, nil) - followsMock.On("CountByChatID", ctx, dbChat.ID). - Return(len(follows), nil) - channelsIds := lo.Map( - follows, func(f *db_models2.Follow, _ int) string { - return f.Channel.ChannelID - }, - ) - twitchMock.On("GetChannelsByUserIds", channelsIds). - Return( - lo.Map( - follows, func(item *db_models2.Follow, _ int) helix.ChannelInformation { - return helix.ChannelInformation{ - BroadcasterID: item.Channel.ChannelID, - BroadcasterName: item.Channel.ChannelID, - } - }, - ), nil, - ) - }, - asserts: func(t *testing.T, keyboard *tg.InlineKeyboardMarkup) { - assert.Greater(t, len(keyboard.InlineKeyboard), 2) - assert.Contains( - t, - keyboard.InlineKeyboard[len(keyboard.InlineKeyboard)-1][0].CallbackData, - "channels_unfollow_next_page", - ) - }, - }, - { - name: "should return keyboard with few pages and next and prev buttons", - setupMocks: func() { - session.FollowsMenu.CurrentPage = 3 - sessionsMock.On("Get", ctx).Return(session) - follows := make([]*db_models2.Follow, 0, 15) - for i := 0; i < 15; i++ { - follows = append( - follows, &db_models2.Follow{ - ID: uuid.New(), - ChannelID: uuid.New(), - ChatID: dbChat.ID, - Channel: &db_models2.Channel{ - ID: uuid.New(), - ChannelID: strconv.Itoa(i), - }, - }, - ) - } - followsMock.On("GetByChatID", ctx, dbChat.ID, 9, 18). - Return(follows, nil) - followsMock.On("CountByChatID", ctx, dbChat.ID). - Return(100, nil) - channelsIds := lo.Map( - follows, func(f *db_models2.Follow, _ int) string { - return f.Channel.ChannelID - }, - ) - twitchMock.On("GetChannelsByUserIds", channelsIds). - Return( - lo.Map( - follows, func(item *db_models2.Follow, _ int) helix.ChannelInformation { - return helix.ChannelInformation{ - BroadcasterID: item.Channel.ChannelID, - BroadcasterName: item.Channel.ChannelID, - } - }, - ), nil, - ) - }, - asserts: func(t *testing.T, keyboard *tg.InlineKeyboardMarkup) { - assert.Greater(t, len(keyboard.InlineKeyboard), 2) - latestRow := keyboard.InlineKeyboard[len(keyboard.InlineKeyboard)-1] - assert.Equal(t, latestRow[0].CallbackData, "channels_unfollow_prev_page") - assert.Equal(t, latestRow[1].CallbackData, "channels_unfollow_next_page") - }, - }, - } - - for _, tt := range table { - t.Run( - tt.name, func(t *testing.T) { - tt.setupMocks() - - cmd := &FollowsCommand{ - CommandOpts: &tg_types.CommandOpts{ - Services: &types.Services{ - Follow: followsMock, - Twitch: twitchMock, - }, - SessionManager: sessionsMock, - }, - } - - keyboard, err := cmd.newKeyboard(ctx, followsMaxRows, followsPerRow) - assert.NoError(t, err) - tt.asserts(t, keyboard) - - sessionsMock.AssertExpectations(t) - followsMock.AssertExpectations(t) - twitchMock.AssertExpectations(t) - - sessionsMock.ExpectedCalls = nil - followsMock.ExpectedCalls = nil - twitchMock.ExpectedCalls = nil - }, - ) - } -} diff --git a/internal/telegram/commands/language_picker.go b/internal/telegram/commands/language_picker.go deleted file mode 100644 index b2ec16f6..00000000 --- a/internal/telegram/commands/language_picker.go +++ /dev/null @@ -1,109 +0,0 @@ -package commands - -import ( - "context" - "errors" - "fmt" - "strings" - - "github.com/mr-linch/go-tg" - "github.com/mr-linch/go-tg/tgb" - "github.com/satont/twitch-notifier/internal/db" - "github.com/satont/twitch-notifier/internal/db/db_models" - tgtypes "github.com/satont/twitch-notifier/internal/telegram/types" - "go.uber.org/zap" -) - -type LanguagePicker struct { - *tgtypes.CommandOpts -} - -func (c *LanguagePicker) buildKeyboard() (*tg.InlineKeyboardMarkup, error) { - layout := tg.NewButtonLayout[tg.InlineKeyboardButton](1) - - codes := c.Services.I18N.GetLanguagesCodes() - - for _, code := range codes { - layout.Add( - tg.NewInlineKeyboardButtonCallback( - fmt.Sprintf( - "%s %s", - c.Services.I18N.Translate("language.emoji", code, nil), - c.Services.I18N.Translate("language.name", code, nil), - ), - "language_picker_set_"+code, - ), - ) - } - - layout.Add(tg.NewInlineKeyboardButtonCallback("«", "start_command_menu")) - - markup := tg.NewInlineKeyboardMarkup(layout.Keyboard()...) - - return &markup, nil -} - -func (c *LanguagePicker) HandleCallback(ctx context.Context, msg *tgb.CallbackQueryUpdate) error { - keyboard, err := c.buildKeyboard() - if err != nil { - return msg.Answer().Text("internal error").DoVoid(ctx) - } - - return msg.Client. - EditMessageReplyMarkup(msg.Message.Chat().ID, msg.Message.Message.ID). - ReplyMarkup(*keyboard). - DoVoid(ctx) -} - -func (c *LanguagePicker) handleSetLanguage(ctx context.Context, msg *tgb.CallbackQueryUpdate) error { - chat := c.SessionManager.Get(ctx).Chat - if chat == nil { - return errors.New("no chat") - } - - lang := db_models.ChatLanguage( - strings.TrimPrefix(msg.CallbackQuery.Data, "language_picker_set_"), - ) - if !db_models.LanguageExists(lang) { - return errors.New("language not exists") - } - - _, err := c.Services.Chat.Update( - ctx, - msg.Message.Chat().ID.PeerID(), - db_models.ChatServiceTelegram, - &db.ChatUpdateQuery{ - Settings: &db.ChatUpdateSettingsQuery{ - ChatLanguage: &lang, - }, - }, - ) - if err != nil { - zap.S().Error(err) - return err - } - - chat.Settings.ChatLanguage = lang - - err = msg. - Answer(). - Text(c.Services.I18N.Translate("language.changed", lang.String(), nil)). - DoVoid(ctx) - if err != nil { - zap.S().Error(err) - return err - } - - return nil -} - -func NewLanguagePicker(opts *tgtypes.CommandOpts) { - picker := &LanguagePicker{opts} - - opts.Router.CallbackQuery(picker.HandleCallback, channelsAdminFilter, tgb.TextEqual("language_picker")) - opts.Router.CallbackQuery( - picker.handleSetLanguage, - channelsAdminFilter, - tgb.TextHasPrefix("language_picker_set_"), - ) -} diff --git a/internal/telegram/commands/language_picker_test.go b/internal/telegram/commands/language_picker_test.go deleted file mode 100644 index 7c8024f8..00000000 --- a/internal/telegram/commands/language_picker_test.go +++ /dev/null @@ -1,215 +0,0 @@ -package commands - -import ( - "context" - "fmt" - "io" - "net/http" - "net/http/httptest" - "net/url" - "testing" - - "github.com/satont/twitch-notifier/internal/db" - "github.com/satont/twitch-notifier/internal/db/db_models" - tg_types "github.com/satont/twitch-notifier/internal/telegram/types" - "github.com/satont/twitch-notifier/internal/types" - - "github.com/google/uuid" - "github.com/mr-linch/go-tg" - "github.com/mr-linch/go-tg/tgb" - "github.com/satont/twitch-notifier/internal/test_utils" - "github.com/satont/twitch-notifier/internal/test_utils/mocks" - i18nmocks "github.com/satont/twitch-notifier/pkg/i18n/mocks" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/mock" -) - -//func TestLanguagePicker_buildKeyboard(t *testing.T) { -// t.Parallel() -// -// i18nMock := i18n.NewI18nMock() -// -// cmd := &LanguagePicker{ -// CommandOpts: &tgtypes.CommandOpts{ -// Services: &types.Services{ -// I18N: i18nMock, -// }, -// }, -// } -// -// i18nMock.On("GetLanguagesCodes").Return([]string{"en", "ru"}) -// -// englishFlag := "🇬🇧" -// englishName := "English" -// -// russianFlag := "🇷🇺" -// russianName := "Русский" -// -// i18nMock. -// On("Translate", "language.emoji", "en", map[string]string(nil)). -// Return(englishFlag) -// i18nMock. -// On("Translate", "language.name", "en", map[string]string(nil)). -// Return(englishName) -// -// i18nMock. -// On("Translate", "language.emoji", "ru", map[string]string(nil)). -// Return(russianFlag) -// i18nMock. -// On("Translate", "language.name", "ru", map[string]string(nil)). -// Return(russianName) -// -// keyboard, err := cmd.buildKeyboard() -// assert.NoError(t, err) -// -// assert.Equal(t, -// fmt.Sprintf("%s %s", englishFlag, englishName), -// keyboard.InlineKeyboard[0][0].Text, -// ) -// assert.Equal(t, -// "language_picker_set_en", -// keyboard.InlineKeyboard[0][0].CallbackData, -// ) -// -// assert.Equal(t, -// fmt.Sprintf("%s %s", russianFlag, russianName), -// keyboard.InlineKeyboard[1][0].Text, -// ) -// assert.Equal(t, -// "language_picker_set_ru", -// keyboard.InlineKeyboard[1][0].CallbackData, -// ) -// -// assert.Equal(t, -// "«", -// keyboard.InlineKeyboard[2][0].Text, -// ) -// assert.Equal(t, "start_command_menu", keyboard.InlineKeyboard[2][0].CallbackData) -// -// i18nMock.AssertExpectations(t) -//} - -func TestLanguagePicker_HandleCallback(t *testing.T) { - t.Parallel() - - ctx := context.Background() - - i18nMock := i18nmocks.NewI18nMock() - i18nMock.On("GetLanguagesCodes").Return([]string{"en"}) - - englishFlag := "🇬🇧" - englishName := "English" - - i18nMock. - On("Translate", "language.emoji", "en", map[string]string(nil)). - Return(englishFlag) - i18nMock. - On("Translate", "language.name", "en", map[string]string(nil)). - Return(englishName) - - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - body, err := io.ReadAll(r.Body) - assert.NoError(t, err) - query, err := url.ParseQuery(string(body)) - assert.NoError(t, err) - - assert.Equal(t, http.MethodPost, r.Method) - assert.Equal( - t, - fmt.Sprintf("/bot%s/editMessageReplyMarkup", test_utils.TelegramClientToken), - r.URL.Path, - ) - assert.NotEmpty(t, query.Get("reply_markup")) - - w.WriteHeader(http.StatusOK) - _, _ = w.Write([]byte(test_utils.TelegramOkResponse)) - })) - - cmd := &LanguagePicker{ - CommandOpts: &tg_types.CommandOpts{ - Services: &types.Services{ - I18N: i18nMock, - }, - }, - } - - err := cmd.HandleCallback(ctx, &tgb.CallbackQueryUpdate{ - Client: test_utils.NewTelegramClient(server), - CallbackQuery: &tg.CallbackQuery{ - Message: &tg.MaybeInaccessibleMessage{ - InaccessibleMessage: &tg.InaccessibleMessage{MessageID: 1, Chat: tg.Chat{ID: tg.ChatID(1)}}, - }, - }, - }) - assert.NoError(t, err) -} - -func TestLanguagePicker_handleSetLanguage(t *testing.T) { - t.Parallel() - - ctx := context.Background() - - chat := &db_models.Chat{ - ID: uuid.New(), - ChatID: "1", - Settings: &db_models.ChatSettings{ - ChatLanguage: db_models.ChatLanguageEn, - }, - } - - sessionMock := tg_types.NewMockedSessionManager() - sessionMock.On("Get", ctx).Return(&tg_types.Session{ - Chat: chat, - }) - - i18nMock := i18nmocks.NewI18nMock() - i18nMock. - On("Translate", "language.changed", "ru", map[string]string(nil)). - Return("Now russian") - - chatService := &mocks.DbChatMock{} - chatService. - On("Update", ctx, "1", db_models.ChatServiceTelegram, mock.IsType(&db.ChatUpdateQuery{})). - Return((*db_models.Chat)(nil), nil) - - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - assert.Equal( - t, - fmt.Sprintf("/bot%s/answerCallbackQuery", test_utils.TelegramClientToken), - r.URL.Path, - ) - w.WriteHeader(http.StatusOK) - _, _ = w.Write([]byte(test_utils.TelegramOkResponse)) - })) - - cmd := &LanguagePicker{ - CommandOpts: &tg_types.CommandOpts{ - SessionManager: sessionMock, - Services: &types.Services{ - I18N: i18nMock, - Chat: chatService, - }, - }, - } - - err := cmd.handleSetLanguage(ctx, &tgb.CallbackQueryUpdate{ - Client: test_utils.NewTelegramClient(server), - CallbackQuery: &tg.CallbackQuery{ - Message: &tg.MaybeInaccessibleMessage{ - Message: &tg.Message{ - ID: 1, - Chat: tg.Chat{ - ID: tg.ChatID(1), - }, - }, - }, - Data: "language_picker_set_ru", - }, - }) - assert.NoError(t, err) - - assert.Equal(t, db_models.ChatLanguageRu, chat.Settings.ChatLanguage) - - sessionMock.AssertExpectations(t) - chatService.AssertExpectations(t) -} diff --git a/internal/telegram/commands/live.go b/internal/telegram/commands/live.go deleted file mode 100644 index 6d367550..00000000 --- a/internal/telegram/commands/live.go +++ /dev/null @@ -1,153 +0,0 @@ -package commands - -import ( - "context" - "fmt" - "strings" - "time" - - "github.com/mr-linch/go-tg" - "github.com/mr-linch/go-tg/tgb" - "github.com/samber/lo" - "github.com/satont/twitch-notifier/internal/db/db_models" - tgtypes "github.com/satont/twitch-notifier/internal/telegram/types" - "go.uber.org/zap" -) - -type LiveCommand struct { - *tgtypes.CommandOpts -} - -type liveChannel struct { - Name string - Login string - StartedAt time.Time - Title string - Category string - Viewers int -} - -func (c *LiveCommand) getList(ctx context.Context) ([]*liveChannel, error) { - chat := c.SessionManager.Get(ctx).Chat - - follows, err := c.Services.Follow.GetByChatID(ctx, chat.ID, 0, 0) - if err != nil { - return nil, err - } - - if len(follows) == 0 { - return nil, nil - } - - channelsIds := lo.Map(follows, func(follow *db_models.Follow, _ int) string { - return follow.Channel.ChannelID - }) - - streams, err := c.Services.Twitch.GetStreamsByUserIds(channelsIds) - if err != nil { - return nil, err - } - - if len(streams) == 0 { - return nil, nil - } - - result := make([]*liveChannel, 0, len(streams)) - - for _, stream := range streams { - result = append(result, &liveChannel{ - Name: stream.UserName, - Login: stream.UserLogin, - StartedAt: stream.StartedAt, - Title: stream.Title, - Category: stream.GameName, - Viewers: stream.ViewerCount, - }) - } - - return result, nil -} - -func (c *LiveCommand) HandleCommand(ctx context.Context, msg *tgb.MessageUpdate) error { - list, err := c.getList(ctx) - if err != nil { - zap.S().Error(err) - return msg.Answer("internal error").DoVoid(ctx) - } - - if len(list) == 0 { - return msg.Answer("No one online").DoVoid(ctx) - } - - message := make([]string, 0, len(list)) - - for _, channel := range list { - channelMessage := make([]string, 0) - - channelMessage = append( - channelMessage, - fmt.Sprintf( - "🟢 %s - %v 👁️️", - tg.MD.Link( - channel.Name, - fmt.Sprintf("https://twitch.tv/%s", channel.Login), - ), - channel.Viewers, - ), - ) - - if channel.Category != "" { - channelMessage = append(channelMessage, fmt.Sprintf("🎮 %s", channel.Category)) - } - - if channel.Title != "" { - channelMessage = append(channelMessage, fmt.Sprintf("📝 %s", channel.Title)) - } - - since := time.Since(channel.StartedAt) - hour := int(since.Seconds() / 3600) - minute := int(since.Seconds()/60) % 60 - second := int(since.Seconds()) % 60 - - uptime := "⌛ " - if hour > 0 { - uptime += fmt.Sprintf("%vh ", hour) - } - - if minute > 0 { - uptime += fmt.Sprintf("%vm ", minute) - } - - if second > 0 { - uptime += fmt.Sprintf("%vs ", second) - } - - channelMessage = append(channelMessage, uptime) - - message = append( - message, - strings.Join(channelMessage, "\n"), - ) - } - - return msg. - Answer(strings.Join(message, "\n\n")). - ParseMode(tg.MD). - LinkPreviewOptions(tg.LinkPreviewOptions{IsDisabled: true}). - DoVoid(ctx) -} - -var liveCommandFilter = tgb.Command("live") - -func NewLiveCommand(opts *tgtypes.CommandOpts) { - cmd := &LiveCommand{ - CommandOpts: opts, - } - - messageFilter := []tgb.Filter{ - channelsAdminFilter, - liveCommandFilter, - } - - opts.Router.Message(cmd.HandleCommand, messageFilter...) -} diff --git a/internal/telegram/commands/live_test.go b/internal/telegram/commands/live_test.go deleted file mode 100644 index 15355695..00000000 --- a/internal/telegram/commands/live_test.go +++ /dev/null @@ -1,273 +0,0 @@ -package commands - -import ( - "context" - "fmt" - db_models2 "github.com/satont/twitch-notifier/internal/db/db_models" - tg_types2 "github.com/satont/twitch-notifier/internal/telegram/types" - "github.com/satont/twitch-notifier/internal/types" - "io" - "net/http" - "net/http/httptest" - "net/url" - "testing" - "time" - - "github.com/mr-linch/go-tg" - "github.com/mr-linch/go-tg/tgb" - "github.com/satont/twitch-notifier/internal/test_utils" - "github.com/satont/twitch-notifier/internal/test_utils/mocks" - - "github.com/google/uuid" - "github.com/nicklaw5/helix/v2" - "github.com/stretchr/testify/assert" -) - -func TestLiveCommand_GetList(t *testing.T) { - t.Parallel() - - chat := &db_models2.Chat{ - ID: uuid.New(), - ChatID: "1", - } - - ctx := context.Background() - - sessionManager := tg_types2.NewMockedSessionManager() - sessionManager.On("Get", ctx).Return(&tg_types2.Session{ - Chat: chat, - }) - - followMock := &mocks.DbFollowMock{} - twitchMock := &mocks.TwitchApiMock{} - - var now = func() time.Time { - return time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC) - } - - follows := []*db_models2.Follow{ - { - ID: uuid.UUID{}, - ChannelID: uuid.UUID{}, - ChatID: uuid.UUID{}, - Channel: &db_models2.Channel{ - ChannelID: "1", - }, - Chat: nil, - }, - { - ID: uuid.UUID{}, - ChannelID: uuid.UUID{}, - ChatID: uuid.UUID{}, - Channel: &db_models2.Channel{ - ChannelID: "2", - }, - Chat: nil, - }, - } - - table := []struct { - name string - setupMocks func() - wantErr bool - wants any - }{ - { - name: "Should return empty list if no follows", - setupMocks: func() { - followMock.On("GetByChatID", ctx, chat.ID, 0, 0).Return([]*db_models2.Follow{}, nil) - }, - wantErr: false, - wants: []*liveChannel(nil), - }, - { - name: "Should return empty list if no channels online", - setupMocks: func() { - followMock.On("GetByChatID", ctx, chat.ID, 0, 0). - Return(follows, nil) - twitchMock. - On( - "GetStreamsByUserIds", - []string{"1", "2"}, - ).Return([]helix.Stream{}, nil) - }, - wantErr: false, - wants: []*liveChannel(nil), - }, - { - name: "Should return one channel", - setupMocks: func() { - followMock.On("GetByChatID", ctx, chat.ID, 0, 0). - Return(follows, nil) - twitchMock. - On( - "GetStreamsByUserIds", - []string{"1", "2"}, - ).Return([]helix.Stream{ - { - UserID: "1", - UserLogin: "satont", - UserName: "Satont", - GameName: "Dota 2", - Title: "Playing dota", - StartedAt: now(), - }, - }, nil) - }, - wantErr: false, - wants: []*liveChannel{ - { - Name: "Satont", - Login: "satont", - StartedAt: now(), - Title: "Playing dota", - Category: "Dota 2", - }, - }, - }, - } - - for _, tt := range table { - tt := tt - t.Run(tt.name, func(t *testing.T) { - tt.setupMocks() - - command := &LiveCommand{ - CommandOpts: &tg_types2.CommandOpts{ - SessionManager: sessionManager, - Services: &types.Services{ - Follow: followMock, - Twitch: twitchMock, - }, - }, - } - - list, err := command.getList(ctx) - assert.NoError(t, err) - assert.Equal(t, tt.wants, list) - - followMock.AssertExpectations(t) - twitchMock.AssertExpectations(t) - - followMock.ExpectedCalls = nil - twitchMock.ExpectedCalls = nil - }) - } -} - -func TestLiveCommand_HandleCommand(t *testing.T) { - t.Parallel() - - chat := &db_models2.Chat{ - ID: uuid.New(), - ChatID: "1", - } - - ctx := context.Background() - - sessionMock := tg_types2.NewMockedSessionManager() - followMock := &mocks.DbFollowMock{} - twitchMock := &mocks.TwitchApiMock{} - - var now = func() time.Time { - return time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC) - } - - follows := []*db_models2.Follow{ - { - ID: uuid.UUID{}, - ChannelID: uuid.UUID{}, - ChatID: uuid.UUID{}, - Channel: &db_models2.Channel{ - ChannelID: "1", - }, - Chat: nil, - }, - { - ID: uuid.UUID{}, - ChannelID: uuid.UUID{}, - ChatID: uuid.UUID{}, - Channel: &db_models2.Channel{ - ChannelID: "2", - }, - Chat: nil, - }, - } - - sessionMock.On("Get", ctx).Return(&tg_types2.Session{ - Chat: chat, - }) - followMock.On("GetByChatID", ctx, chat.ID, 0, 0). - Return(follows, nil) - twitchMock. - On( - "GetStreamsByUserIds", - []string{"1", "2"}, - ).Return([]helix.Stream{ - { - UserID: "1", - UserLogin: "satont", - UserName: "Satont", - GameName: "Dota 2", - Title: "Playing dota", - StartedAt: now(), - }, - { - UserID: "2", - UserLogin: "sadisnamenya", - UserName: "SadisNaMenya", - GameName: "Dota 2", - Title: "Dotka", - StartedAt: now(), - }, - }, nil) - - expectedString1 := "🟢 [Satont](https://twitch.tv/satont) - 0 👁️️\n🎮 Dota 2\n📝 Playing dota\n⌛" - expectedString2 := "🟢 [SadisNaMenya](https://twitch.tv/sadisnamenya) - 0 👁️️\n🎮 Dota 2\n📝 Dotka\n" - - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - body, err := io.ReadAll(r.Body) - assert.NoError(t, err) - query, err := url.ParseQuery(string(body)) - assert.NoError(t, err) - - assert.Equal(t, http.MethodPost, r.Method) - assert.Equal( - t, - fmt.Sprintf("/bot%s/sendMessage", test_utils.TelegramClientToken), - r.URL.Path, - ) - assert.Contains(t, query.Get("text"), expectedString1) - assert.Contains(t, query.Get("text"), expectedString2) - - w.WriteHeader(http.StatusOK) - _, _ = w.Write([]byte(test_utils.TelegramOkResponse)) - })) - defer server.Close() - - telegramClient := test_utils.NewTelegramClient(server) - - cmd := &LiveCommand{ - CommandOpts: &tg_types2.CommandOpts{ - SessionManager: sessionMock, - Services: &types.Services{ - Follow: followMock, - Twitch: twitchMock, - }, - }, - } - - err := cmd.HandleCommand(ctx, &tgb.MessageUpdate{ - Client: telegramClient, - Message: &tg.Message{ - Chat: tg.Chat{ - ID: 1, - }, - }, - }) - assert.NoError(t, err) - - sessionMock.AssertExpectations(t) - followMock.AssertExpectations(t) - twitchMock.AssertExpectations(t) -} diff --git a/internal/telegram/commands/start.go b/internal/telegram/commands/start.go deleted file mode 100644 index 3a59d977..00000000 --- a/internal/telegram/commands/start.go +++ /dev/null @@ -1,346 +0,0 @@ -package commands - -import ( - "context" - "fmt" - - "github.com/mr-linch/go-tg" - "github.com/mr-linch/go-tg/tgb" - "github.com/satont/twitch-notifier/internal/db" - "github.com/satont/twitch-notifier/internal/db/db_models" - tg_types "github.com/satont/twitch-notifier/internal/telegram/types" - "go.uber.org/zap" -) - -type StartCommand struct { - *tg_types.CommandOpts -} - -func (c *StartCommand) createCheckMark(value bool) string { - if value { - return "✅" - } - - return "❌" -} - -func (c *StartCommand) buildKeyboard(ctx context.Context) *tg.InlineKeyboardMarkup { - chat := c.SessionManager.Get(ctx).Chat - - layout := tg.NewButtonLayout[tg.InlineKeyboardButton](1) - - gameChangeNotificationsButton := c.Services.I18N.Translate( - "commands.start.game_change_notification_setting.button", - chat.Settings.ChatLanguage.String(), - nil, - ) - offlineNotificationsButton := c.Services.I18N.Translate( - "commands.start.offline_notification.button", - chat.Settings.ChatLanguage.String(), - nil, - ) - - titleChangeNotificationsButton := c.Services.I18N.Translate( - "commands.start.title_change_notification_setting.button", - chat.Settings.ChatLanguage.String(), - nil, - ) - - gameAndTitleChangeNotificationsButton := c.Services.I18N.Translate( - "commands.start.game_and_title_change_notification_setting.button", - chat.Settings.ChatLanguage.String(), - nil, - ) - - imageInNotificationButton := c.Services.I18N.Translate( - "commands.start.image_in_notification_setting.button", - chat.Settings.ChatLanguage.String(), - nil, - ) - - layout.Add( - tg.NewInlineKeyboardButtonCallback( - fmt.Sprintf( - "%s %s", - c.createCheckMark(chat.Settings.GameChangeNotification), - gameChangeNotificationsButton, - ), - "start_game_change_notification_setting", - ), - tg.NewInlineKeyboardButtonCallback( - fmt.Sprintf( - "%s %s", - c.createCheckMark(chat.Settings.OfflineNotification), - offlineNotificationsButton, - ), - "start_offline_notification", - ), - tg.NewInlineKeyboardButtonCallback( - fmt.Sprintf( - "%s %s", - c.createCheckMark(chat.Settings.TitleChangeNotification), - titleChangeNotificationsButton, - ), - "start_title_change_notification_setting", - ), - tg.NewInlineKeyboardButtonCallback( - fmt.Sprintf( - "%s %s", - c.createCheckMark(chat.Settings.GameAndTitleChangeNotification), - gameAndTitleChangeNotificationsButton, - ), - "start_game_and_title_change_notification_setting", - ), - tg.NewInlineKeyboardButtonCallback( - fmt.Sprintf( - "%s %s", - c.createCheckMark(chat.Settings.ImageInNotification), - imageInNotificationButton, - ), - "image_in_notification_setting", - ), - tg.NewInlineKeyboardButtonCallback( - c.Services.I18N.Translate( - "commands.start.language.button", - chat.Settings.ChatLanguage.String(), - nil, - ), - "language_picker", - ), - tg.NewInlineKeyboardButtonURL("Github", "https://github.com/Satont/twitch-notifier"), - ) - - markup := tg.NewInlineKeyboardMarkup(layout.Keyboard()...) - - return &markup -} - -func (c *StartCommand) HandleCommand(ctx context.Context, msg *tgb.MessageUpdate) error { - session := c.SessionManager.Get(ctx) - - keyBoard := c.buildKeyboard(ctx) - - description := c.Services.I18N.Translate( - "bot.description", - session.Chat.Settings.ChatLanguage.String(), - nil, - ) - - return msg.Answer(description).ReplyMarkup(keyBoard).DoVoid(ctx) -} - -func (c *StartCommand) handleCallback(ctx context.Context, msg *tgb.CallbackQueryUpdate) error { - keyboard := c.buildKeyboard(ctx) - - return msg.Client. - EditMessageReplyMarkup(msg.Message.Chat().ID, msg.Message.MessageID()). - ReplyMarkup(*keyboard). - DoVoid(ctx) -} - -func (c *StartCommand) handleImageInNotificationSettings( - ctx context.Context, - msg *tgb.CallbackQueryUpdate, -) error { - chat := c.SessionManager.Get(ctx).Chat - chat.Settings.ImageInNotification = !chat.Settings.ImageInNotification - - _, err := c.Services.Chat.Update( - ctx, - chat.ChatID, - db_models.ChatServiceTelegram, - &db.ChatUpdateQuery{ - Settings: &db.ChatUpdateSettingsQuery{ - ImageInNotification: &chat.Settings.ImageInNotification, - }, - }) - if err != nil { - zap.S().Error(err) - return msg.Answer().Text("internal error").DoVoid(ctx) - } - - keyboard := c.buildKeyboard(ctx) - - return msg.Client. - EditMessageReplyMarkup(msg.Message.Chat().ID, msg.Message.MessageID()). - ReplyMarkup(*keyboard). - DoVoid(ctx) -} - -func (c *StartCommand) handleTitleNotificationSettings( - ctx context.Context, - msg *tgb.CallbackQueryUpdate, -) error { - chat := c.SessionManager.Get(ctx).Chat - chat.Settings.TitleChangeNotification = !chat.Settings.TitleChangeNotification - - _, err := c.Services.Chat.Update( - ctx, - chat.ChatID, - db_models.ChatServiceTelegram, - &db.ChatUpdateQuery{ - Settings: &db.ChatUpdateSettingsQuery{ - TitleChangeNotification: &chat.Settings.TitleChangeNotification, - }, - }, - ) - - if err != nil { - zap.S().Error(err) - return msg.Answer().Text("internal error").DoVoid(ctx) - } - - keyboard := c.buildKeyboard(ctx) - - return msg.Client. - EditMessageReplyMarkup(msg.Message.Chat().ID, msg.Message.MessageID()). - ReplyMarkup(*keyboard). - DoVoid(ctx) -} - -func (c *StartCommand) handleGameNotificationSettings( - ctx context.Context, - msg *tgb.CallbackQueryUpdate, -) error { - chat := c.SessionManager.Get(ctx).Chat - - chat.Settings.GameChangeNotification = !chat.Settings.GameChangeNotification - - _, err := c.Services.Chat.Update( - ctx, - chat.ChatID, - db_models.ChatServiceTelegram, - &db.ChatUpdateQuery{ - Settings: &db.ChatUpdateSettingsQuery{ - GameChangeNotification: &chat.Settings.GameChangeNotification, - }, - }, - ) - if err != nil { - zap.S().Error(err) - return msg.Answer().Text("internal error").DoVoid(ctx) - } - - keyboard := c.buildKeyboard(ctx) - - return msg.Client. - EditMessageReplyMarkup(msg.Message.Chat().ID, msg.Message.MessageID()). - ReplyMarkup(*keyboard). - DoVoid(ctx) -} - -func (c *StartCommand) handleGameAndTitleNotificationSettings( - ctx context.Context, - msg *tgb.CallbackQueryUpdate, -) error { - chat := c.SessionManager.Get(ctx).Chat - chat.Settings.GameAndTitleChangeNotification = !chat.Settings.GameAndTitleChangeNotification - - _, err := c.Services.Chat.Update( - ctx, - chat.ChatID, - db_models.ChatServiceTelegram, - &db.ChatUpdateQuery{ - Settings: &db.ChatUpdateSettingsQuery{ - GameAndTitleChangeNotification: &chat.Settings.GameAndTitleChangeNotification, - }, - }, - ) - if err != nil { - zap.S().Error(err) - return msg.Answer().Text("internal error").DoVoid(ctx) - } - - keyboard := c.buildKeyboard(ctx) - - return msg.Client. - EditMessageReplyMarkup(msg.Message.Chat().ID, msg.Message.MessageID()). - ReplyMarkup(*keyboard). - DoVoid(ctx) -} - -func (c *StartCommand) handleOfflineNotificationSettings( - ctx context.Context, - msg *tgb.CallbackQueryUpdate, -) error { - chat := c.SessionManager.Get(ctx).Chat - - chat.Settings.OfflineNotification = !chat.Settings.OfflineNotification - - _, err := c.Services.Chat.Update( - ctx, - chat.ChatID, - db_models.ChatServiceTelegram, - &db.ChatUpdateQuery{ - Settings: &db.ChatUpdateSettingsQuery{ - OfflineNotification: &chat.Settings.OfflineNotification, - }, - }, - ) - if err != nil { - zap.S().Error(err) - return msg.Answer().Text("internal error").DoVoid(ctx) - } - - keyboard := c.buildKeyboard(ctx) - - return msg.Client. - EditMessageReplyMarkup(msg.Message.Chat().ID, msg.Message.MessageID()). - ReplyMarkup(*keyboard). - DoVoid(ctx) -} - -var ( - startCommandFilter = tgb.Command("start", - tgb.WithCommandAlias("help"), - tgb.WithCommandAlias("info"), - tgb.WithCommandAlias("settings"), - ) - startMenuFilter = tgb.TextEqual("start_command_menu") - gameChangeNotificationSettingFilter = tgb.TextEqual("start_game_change_notification_setting") - offlineNotificationSettingFilter = tgb.TextEqual("start_offline_notification") - titleNotificationSettingFilter = tgb.TextEqual("start_title_change_notification_setting") - gameAndTitleSettingFilter = tgb.TextEqual("start_game_and_title_change_notification_setting") - imageInNotificationSettingFilter = tgb.TextEqual("image_in_notification_setting") -) - -func NewStartCommand(opts *tg_types.CommandOpts) { - cmd := &StartCommand{ - CommandOpts: opts, - } - - messageFilter := []tgb.Filter{ - channelsAdminFilter, - startCommandFilter, - } - - opts.Router.Message(cmd.HandleCommand, messageFilter...) - opts.Router.ChannelPost(cmd.HandleCommand, messageFilter...) - - opts.Router.CallbackQuery(cmd.handleCallback, channelsAdminFilter, startMenuFilter) - opts.Router.CallbackQuery( - cmd.handleGameNotificationSettings, - channelsAdminFilter, - gameChangeNotificationSettingFilter, - ) - opts.Router.CallbackQuery( - cmd.handleOfflineNotificationSettings, - channelsAdminFilter, - offlineNotificationSettingFilter, - ) - opts.Router.CallbackQuery( - cmd.handleTitleNotificationSettings, - channelsAdminFilter, - titleNotificationSettingFilter, - ) - opts.Router.CallbackQuery( - cmd.handleGameAndTitleNotificationSettings, - channelsAdminFilter, - gameAndTitleSettingFilter, - ) - opts.Router.CallbackQuery( - cmd.handleImageInNotificationSettings, - channelsAdminFilter, - imageInNotificationSettingFilter, - ) -} diff --git a/internal/telegram/commands/start_test.go b/internal/telegram/commands/start_test.go deleted file mode 100644 index bf3a1f9a..00000000 --- a/internal/telegram/commands/start_test.go +++ /dev/null @@ -1,169 +0,0 @@ -package commands - -import ( - "context" - "fmt" - "io" - "net/http" - "net/http/httptest" - "net/url" - "testing" - - "github.com/satont/twitch-notifier/internal/db/db_models" - tg_types "github.com/satont/twitch-notifier/internal/telegram/types" - "github.com/satont/twitch-notifier/internal/types" - - "github.com/google/uuid" - "github.com/mr-linch/go-tg" - "github.com/mr-linch/go-tg/tgb" - "github.com/satont/twitch-notifier/internal/test_utils" - i18nmocks "github.com/satont/twitch-notifier/pkg/i18n/mocks" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/mock" -) - -func TestStartCommand_buildKeyboard(t *testing.T) { - t.Parallel() - - ctx := context.Background() - chat := &db_models.Chat{ - ID: uuid.New(), - ChatID: "1", - Settings: &db_models.ChatSettings{ - ChatLanguage: db_models.ChatLanguageEn, - }, - } - - i18 := i18nmocks.NewI18nMock() - i18. - On("Translate", mock.Anything, mock.Anything, mock.Anything). - Return("") - - sessionManager := tg_types.NewMockedSessionManager() - sessionManager.On("Get", ctx).Return(&tg_types.Session{ - Chat: chat, - }) - - cmd := &StartCommand{ - CommandOpts: &tg_types.CommandOpts{ - SessionManager: sessionManager, - Services: &types.Services{ - I18N: i18, - }, - }, - } - - keyboard := cmd.buildKeyboard(ctx) - - const buttons = 7 - assert.Equal(t, buttons, len(keyboard.InlineKeyboard)) - - assert.Equal( - t, - "start_game_change_notification_setting", - keyboard.InlineKeyboard[0][0].CallbackData, - ) - - assert.Equal( - t, - "start_offline_notification", - keyboard.InlineKeyboard[1][0].CallbackData, - ) - - assert.Equal( - t, - "start_title_change_notification_setting", - keyboard.InlineKeyboard[2][0].CallbackData, - ) - - assert.Equal( - t, - "start_game_and_title_change_notification_setting", - keyboard.InlineKeyboard[3][0].CallbackData, - ) - - assert.Equal( - t, - "image_in_notification_setting", - keyboard.InlineKeyboard[4][0].CallbackData, - ) - - assert.Equal( - t, - "language_picker", - keyboard.InlineKeyboard[5][0].CallbackData, - ) - - assert.Equal(t, "Github", keyboard.InlineKeyboard[6][0].Text) - assert.Equal(t, "https://github.com/Satont/twitch-notifier", keyboard.InlineKeyboard[6][0].URL) - - sessionManager.AssertExpectations(t) - i18.AssertNumberOfCalls(t, "Translate", buttons-1) -} - -func TestStartCommand_HandleCommand(t *testing.T) { - t.Parallel() - - ctx := context.Background() - chat := &db_models.Chat{ - ID: uuid.New(), - Settings: &db_models.ChatSettings{ - ChatLanguage: db_models.ChatLanguageEn, - }, - } - - i18 := i18nmocks.NewI18nMock() - i18. - On("Translate", mock.Anything, mock.Anything, mock.Anything). - Return("start command") - - sessionManager := tg_types.NewMockedSessionManager() - sessionManager.On("Get", ctx).Return(&tg_types.Session{ - Chat: chat, - }) - - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - body, err := io.ReadAll(r.Body) - assert.NoError(t, err) - query, err := url.ParseQuery(string(body)) - assert.NoError(t, err) - - assert.Equal(t, http.MethodPost, r.Method) - assert.Equal( - t, - fmt.Sprintf("/bot%s/sendMessage", test_utils.TelegramClientToken), - r.URL.Path, - ) - assert.Equal(t, "start command", query.Get("text")) - assert.NotEmpty(t, query.Get("reply_markup")) - - w.WriteHeader(http.StatusOK) - _, _ = w.Write([]byte(test_utils.TelegramOkResponse)) - })) - - cmd := &StartCommand{ - CommandOpts: &tg_types.CommandOpts{ - SessionManager: sessionManager, - Services: &types.Services{ - I18N: i18, - }, - }, - } - - err := cmd.HandleCommand(ctx, &tgb.MessageUpdate{ - Client: test_utils.NewTelegramClient(server), - Message: &tg.Message{ - Text: "/start", - }, - }) - assert.NoError(t, err) -} - -func TestStartCommand_createCheckMark(t *testing.T) { - t.Parallel() - - cmd := &StartCommand{} - - assert.Equal(t, "✅", cmd.createCheckMark(true)) - assert.Equal(t, "❌", cmd.createCheckMark(false)) -} diff --git a/internal/telegram/middlewares/chat.go b/internal/telegram/middlewares/chat.go deleted file mode 100644 index b6852527..00000000 --- a/internal/telegram/middlewares/chat.go +++ /dev/null @@ -1,37 +0,0 @@ -package middlewares - -import ( - "context" - "fmt" - "github.com/mr-linch/go-tg/tgb" - "github.com/satont/twitch-notifier/internal/db/db_models" - "github.com/satont/twitch-notifier/internal/telegram/types" - "go.uber.org/zap" -) - -type ChatMiddleware struct { - *tg_types.MiddlewareOpts -} - -func (c *ChatMiddleware) Wrap(next tgb.Handler) tgb.Handler { - return tgb.HandlerFunc(func(ctx context.Context, update *tgb.Update) error { - chatId := fmt.Sprintf("%v", update.Chat().ID) - user, err := c.Services.Chat.GetByID(ctx, chatId, db_models.ChatServiceTelegram) - if err != nil { - zap.L().Error("failed to get chat", zap.Error(err)) - return nil - } - - if user == nil { - user, err = c.Services.Chat.Create(ctx, chatId, db_models.ChatServiceTelegram) - if err != nil { - zap.L().Error("failed to create chat", zap.Error(err)) - return nil - } - } - - c.SessionManager.Get(ctx).Chat = user - - return next.Handle(ctx, update) - }) -} diff --git a/internal/telegram/middlewares/logg.go b/internal/telegram/middlewares/logg.go deleted file mode 100644 index a525d52f..00000000 --- a/internal/telegram/middlewares/logg.go +++ /dev/null @@ -1,24 +0,0 @@ -package middlewares - -import ( - "context" - "github.com/mr-linch/go-tg/tgb" - "github.com/satont/twitch-notifier/internal/types" - "go.uber.org/zap" - "time" -) - -type LoggMiddleware struct { - Services *types.Services -} - -func (c *LoggMiddleware) Wrap(next tgb.Handler) tgb.Handler { - return tgb.HandlerFunc(func(ctx context.Context, update *tgb.Update) error { - defer func(started time.Time) { - zap.L(). - Info("update handled", zap.Duration("duration", time.Since(started))) - }(time.Now()) - - return next.Handle(ctx, update) - }) -} diff --git a/internal/telegram/set_commands.go b/internal/telegram/set_commands.go deleted file mode 100644 index 93c4544f..00000000 --- a/internal/telegram/set_commands.go +++ /dev/null @@ -1,58 +0,0 @@ -package telegram - -import ( - "context" - "github.com/mr-linch/go-tg" - "go.uber.org/zap" - "strconv" -) - -var defaultCommands = []tg.BotCommand{ - { - Command: "follow", - Description: "Follow to notifications of some streamer", - }, - { - Command: "follows", - Description: "Show list of followed streamers", - }, - { - Command: "live", - Description: "Show list of live streamers", - }, - { - Command: "start", - Description: "Bot settings", - }, -} - -func (c *TelegramService) setMyCommands(ctx context.Context) { - err := c.Client. - SetMyCommands(defaultCommands). - Scope(tg.BotCommandScopeDefault{}). - DoVoid(ctx) - if err != nil { - zap.S().Fatalln("Can't set default commands", err) - } - - for _, admin := range c.services.Config.TelegramBotAdmins { - newCommands := append(defaultCommands, tg.BotCommand{ - Command: "broadcast", - Description: "Send message to all users", - }) - - chatID, err := strconv.Atoi(admin) - if err != nil { - zap.S().Errorw("Can't parse chat id", "chatID", admin) - return - } - - err = c.Client. - SetMyCommands(newCommands). - Scope(tg.BotCommandScopeChat{ChatID: tg.ChatID(chatID)}). - DoVoid(ctx) - if err != nil { - zap.S().Fatalln("Can't set admin commands", err) - } - } -} diff --git a/internal/telegram/telegram.go b/internal/telegram/telegram.go deleted file mode 100644 index 042fd3e6..00000000 --- a/internal/telegram/telegram.go +++ /dev/null @@ -1,92 +0,0 @@ -package telegram - -import ( - "context" - "github.com/hashicorp/go-retryablehttp" - "github.com/satont/twitch-notifier/internal/telegram/commands" - "github.com/satont/twitch-notifier/internal/telegram/middlewares" - "github.com/satont/twitch-notifier/internal/telegram/types" - "github.com/satont/twitch-notifier/internal/types" - "time" - - "github.com/mr-linch/go-tg" - "github.com/mr-linch/go-tg/tgb" - "github.com/mr-linch/go-tg/tgb/session" - "go.uber.org/zap" -) - -type TelegramService struct { - services *types.Services - poller *tgb.Poller - Client *tg.Client -} - -func NewTelegram(ctx context.Context, token string, services *types.Services) *TelegramService { - retryClient := retryablehttp.NewClient() - retryClient.RetryMax = 3 - retryClient.RetryWaitMax = 3600 * time.Second - retryClient.RetryWaitMin = 50 * time.Millisecond - retryClient.Logger = nil - - httpClient := retryClient.StandardClient() - - client := tg.New(token, tg.WithClientDoer(httpClient)) - - var sessionManager = session.NewManager(tg_types.Session{ - FollowsMenu: &tg_types.Menu{}, - Scene: "", - }) - - router := tgb.NewRouter(). - Use(sessionManager). - //Use(&middlewares.LoggMiddleware{ - // Services: services, - //}). - Use(&middlewares.ChatMiddleware{ - MiddlewareOpts: &tg_types.MiddlewareOpts{ - Services: services, - SessionManager: sessionManager, - }}) - - commandOpts := &tg_types.CommandOpts{ - Services: services, - Router: router, - SessionManager: sessionManager, - } - - router.Message(func(ctx context.Context, update *tgb.MessageUpdate) error { - sessionManager.Get(ctx).Scene = "" - return nil - }, tgb.Command("cancel")) - - commands.NewStartCommand(commandOpts) - commands.NewFollowCommand(commandOpts) - commands.NewFollowsCommand(commandOpts) - commands.NewLiveCommand(commandOpts) - commands.NewBroadcastCommand(commandOpts) - commands.NewLanguagePicker(commandOpts) - commands.NewChangeChannelId(commandOpts) - - poller := tgb.NewPoller(router, client) - - me, err := client.GetMe().Do(ctx) - if err != nil { - zap.S().Fatalw("failed to get bot info", "err", err) - } - - service := &TelegramService{ - poller: poller, - services: services, - Client: client, - } - - service.setMyCommands(ctx) - - zap.S().Infow("Telegram bot started", "id", me.ID, "username", me.Username) - - return service -} - -func (c *TelegramService) StartPolling(ctx context.Context) { - go c.poller.Run(ctx) -} diff --git a/internal/telegram/types/mocked_session.go b/internal/telegram/types/mocked_session.go deleted file mode 100644 index 1d5b07d8..00000000 --- a/internal/telegram/types/mocked_session.go +++ /dev/null @@ -1,48 +0,0 @@ -package tg_types - -import ( - "context" - - "github.com/mr-linch/go-tg/tgb" - "github.com/mr-linch/go-tg/tgb/session" - "github.com/stretchr/testify/mock" -) - -type MockedSessionManager[T Session] struct { - mock.Mock -} - -func (m *MockedSessionManager[T]) SetEqualFunc(fn func(t T, t2 T) bool) { - //TODO implement me - panic("implement me") -} - -func (m *MockedSessionManager[T]) Setup(opt session.ManagerOption, opts ...session.ManagerOption) { - //TODO implement me - panic("implement me") -} - -func (m *MockedSessionManager[T]) Get(ctx context.Context) *T { - args := m.Called(ctx) - - return args.Get(0).(*T) -} - -func (m *MockedSessionManager[T]) Reset(session *T) { - //TODO implement me - panic("implement me") -} - -func (m *MockedSessionManager[T]) Filter(fn func(t *T) bool) tgb.Filter { - //TODO implement me - panic("implement me") -} - -func (m *MockedSessionManager[T]) Wrap(next tgb.Handler) tgb.Handler { - //TODO implement me - panic("implement me") -} - -func NewMockedSessionManager() *MockedSessionManager[Session] { - return &MockedSessionManager[Session]{} -} diff --git a/internal/telegram/types/router.go b/internal/telegram/types/router.go deleted file mode 100644 index 6e57a30d..00000000 --- a/internal/telegram/types/router.go +++ /dev/null @@ -1,141 +0,0 @@ -package tg_types - -import ( - "context" - - "github.com/mr-linch/go-tg/tgb" - "github.com/stretchr/testify/mock" -) - -type Router interface { - Use(mws ...tgb.Middleware) *tgb.Router - Message(handler tgb.MessageHandler, filters ...tgb.Filter) *tgb.Router - EditedMessage(handler tgb.MessageHandler, filters ...tgb.Filter) *tgb.Router - ChannelPost(handler tgb.MessageHandler, filters ...tgb.Filter) *tgb.Router - EditedChannelPost(handler tgb.MessageHandler, filters ...tgb.Filter) *tgb.Router - InlineQuery(handler tgb.InlineQueryHandler, filters ...tgb.Filter) *tgb.Router - ChosenInlineResult(handler tgb.ChosenInlineResultHandler, filters ...tgb.Filter) *tgb.Router - CallbackQuery(handler tgb.CallbackQueryHandler, filters ...tgb.Filter) *tgb.Router - ShippingQuery(handler tgb.ShippingQueryHandler, filters ...tgb.Filter) *tgb.Router - PreCheckoutQuery(handler tgb.PreCheckoutQueryHandler, filters ...tgb.Filter) *tgb.Router - Poll(handler tgb.PollHandler, filters ...tgb.Filter) *tgb.Router - PollAnswer(handler tgb.PollAnswerHandler, filters ...tgb.Filter) *tgb.Router - MyChatMember(handler tgb.ChatMemberUpdatedHandler, filters ...tgb.Filter) *tgb.Router - ChatMember(handler tgb.ChatMemberUpdatedHandler, filters ...tgb.Filter) *tgb.Router - ChatJoinRequest(handler tgb.ChatJoinRequestHandler, filters ...tgb.Filter) *tgb.Router - Error(handler tgb.ErrorHandler) *tgb.Router - Update(handler tgb.HandlerFunc, filters ...tgb.Filter) *tgb.Router - Handle(ctx context.Context, update *tgb.Update) error -} - -type MockedRouter struct { - mock.Mock -} - -func (m *MockedRouter) Use(mws ...tgb.Middleware) *tgb.Router { - args := m.Called(mws) - - return args.Get(0).(*tgb.Router) -} - -func (m *MockedRouter) Message(handler tgb.MessageHandler, filters ...tgb.Filter) *tgb.Router { - args := m.Called(handler, filters) - - return args.Get(0).(*tgb.Router) -} - -func (m *MockedRouter) EditedMessage(handler tgb.MessageHandler, filters ...tgb.Filter) *tgb.Router { - args := m.Called(handler, filters) - - return args.Get(0).(*tgb.Router) -} - -func (m *MockedRouter) ChannelPost(handler tgb.MessageHandler, filters ...tgb.Filter) *tgb.Router { - args := m.Called(handler, filters) - - return args.Get(0).(*tgb.Router) -} - -func (m *MockedRouter) EditedChannelPost(handler tgb.MessageHandler, filters ...tgb.Filter) *tgb.Router { - args := m.Called(handler, filters) - - return args.Get(0).(*tgb.Router) -} - -func (m *MockedRouter) InlineQuery(handler tgb.InlineQueryHandler, filters ...tgb.Filter) *tgb.Router { - args := m.Called(handler, filters) - - return args.Get(0).(*tgb.Router) -} - -func (m *MockedRouter) ChosenInlineResult(handler tgb.ChosenInlineResultHandler, filters ...tgb.Filter) *tgb.Router { - args := m.Called(handler, filters) - - return args.Get(0).(*tgb.Router) -} - -func (m *MockedRouter) CallbackQuery(handler tgb.CallbackQueryHandler, filters ...tgb.Filter) *tgb.Router { - args := m.Called(handler, filters) - - return args.Get(0).(*tgb.Router) -} - -func (m *MockedRouter) ShippingQuery(handler tgb.ShippingQueryHandler, filters ...tgb.Filter) *tgb.Router { - args := m.Called(handler, filters) - - return args.Get(0).(*tgb.Router) -} - -func (m *MockedRouter) PreCheckoutQuery(handler tgb.PreCheckoutQueryHandler, filters ...tgb.Filter) *tgb.Router { - args := m.Called(handler, filters) - - return args.Get(0).(*tgb.Router) -} - -func (m *MockedRouter) Poll(handler tgb.PollHandler, filters ...tgb.Filter) *tgb.Router { - args := m.Called(handler, filters) - - return args.Get(0).(*tgb.Router) -} - -func (m *MockedRouter) PollAnswer(handler tgb.PollAnswerHandler, filters ...tgb.Filter) *tgb.Router { - args := m.Called(handler, filters) - - return args.Get(0).(*tgb.Router) -} - -func (m *MockedRouter) MyChatMember(handler tgb.ChatMemberUpdatedHandler, filters ...tgb.Filter) *tgb.Router { - args := m.Called(handler, filters) - - return args.Get(0).(*tgb.Router) -} - -func (m *MockedRouter) ChatMember(handler tgb.ChatMemberUpdatedHandler, filters ...tgb.Filter) *tgb.Router { - args := m.Called(handler, filters) - - return args.Get(0).(*tgb.Router) -} - -func (m *MockedRouter) ChatJoinRequest(handler tgb.ChatJoinRequestHandler, filters ...tgb.Filter) *tgb.Router { - args := m.Called(handler, filters) - - return args.Get(0).(*tgb.Router) -} - -func (m *MockedRouter) Error(handler tgb.ErrorHandler) *tgb.Router { - args := m.Called(handler) - - return args.Get(0).(*tgb.Router) -} - -func (m *MockedRouter) Update(handler tgb.HandlerFunc, filters ...tgb.Filter) *tgb.Router { - args := m.Called(handler, filters) - - return args.Get(0).(*tgb.Router) -} - -func (m *MockedRouter) Handle(ctx context.Context, update *tgb.Update) error { - args := m.Called(ctx, update) - - return args.Error(0) -} diff --git a/internal/telegram/types/session.go b/internal/telegram/types/session.go deleted file mode 100644 index bd8f3463..00000000 --- a/internal/telegram/types/session.go +++ /dev/null @@ -1,42 +0,0 @@ -package tg_types - -import ( - "context" - "github.com/satont/twitch-notifier/internal/db/db_models" - "github.com/satont/twitch-notifier/internal/types" - - "github.com/mr-linch/go-tg/tgb" - "github.com/mr-linch/go-tg/tgb/session" -) - -type SessionManager[T comparable] interface { - SetEqualFunc(fn func(t T, t2 T) bool) - Setup(opt session.ManagerOption, opts ...session.ManagerOption) - Get(ctx context.Context) *T - Reset(session *T) - Filter(fn func(t *T) bool) tgb.Filter - Wrap(next tgb.Handler) tgb.Handler -} - -type Menu struct { - CurrentPage int - TotalPages int -} - -type Session struct { - Chat *db_models.Chat - Scene string - - FollowsMenu *Menu -} - -type CommandOpts struct { - Services *types.Services - Router Router - SessionManager SessionManager[Session] -} - -type MiddlewareOpts struct { - Services *types.Services - SessionManager SessionManager[Session] -} diff --git a/internal/test_utils/mocks/db_channel.go b/internal/test_utils/mocks/db_channel.go deleted file mode 100644 index ea2c15cb..00000000 --- a/internal/test_utils/mocks/db_channel.go +++ /dev/null @@ -1,81 +0,0 @@ -package mocks - -import ( - "context" - - "github.com/satont/twitch-notifier/internal/db" - db_models2 "github.com/satont/twitch-notifier/internal/db/db_models" - - "github.com/stretchr/testify/mock" -) - -type DbChannelMock struct { - mock.Mock -} - -func (c *DbChannelMock) GetByID( - ctx context.Context, - id string, - service db_models2.ChannelService, -) (*db_models2.Channel, error) { - args := c.Called(ctx, id, service) - - return args.Get(0).(*db_models2.Channel), args.Error(1) -} - -func (c *DbChannelMock) GetByChannelID( - ctx context.Context, - channelID string, - service db_models2.ChannelService, -) (*db_models2.Channel, error) { - args := c.Called(ctx, channelID, service) - - return args.Get(0).(*db_models2.Channel), args.Error(1) -} - -func (c *DbChannelMock) GetFollowsByID( - ctx context.Context, - channelID string, - service db_models2.ChannelService, -) ([]*db_models2.Follow, error) { - args := c.Called(ctx, channelID, service) - - return args.Get(0).([]*db_models2.Follow), args.Error(1) -} - -func (c *DbChannelMock) Create( - ctx context.Context, - channelID string, - service db_models2.ChannelService, -) (*db_models2.Channel, error) { - args := c.Called(ctx, channelID, service) - - return args.Get(0).(*db_models2.Channel), args.Error(1) -} - -func (c *DbChannelMock) Update( - ctx context.Context, - channelID string, - service db_models2.ChannelService, - updateQuery *db.ChannelUpdateQuery, -) (*db_models2.Channel, error) { - args := c.Called(ctx, channelID, service, updateQuery) - - return args.Get(0).(*db_models2.Channel), args.Error(1) -} - -func (c *DbChannelMock) GetByIdOrCreate( - ctx context.Context, - channelID string, - service db_models2.ChannelService, -) (*db_models2.Channel, error) { - args := c.Called(ctx, channelID, service) - - return args.Get(0).(*db_models2.Channel), args.Error(1) -} - -func (c *DbChannelMock) GetAll(ctx context.Context) ([]*db_models2.Channel, error) { - args := c.Called(ctx) - - return args.Get(0).([]*db_models2.Channel), args.Error(1) -} diff --git a/internal/test_utils/mocks/db_chat.go b/internal/test_utils/mocks/db_chat.go deleted file mode 100644 index 933f6d9f..00000000 --- a/internal/test_utils/mocks/db_chat.go +++ /dev/null @@ -1,53 +0,0 @@ -package mocks - -import ( - "context" - "github.com/satont/twitch-notifier/internal/db" - "github.com/satont/twitch-notifier/internal/db/db_models" - - "github.com/stretchr/testify/mock" -) - -type DbChatMock struct { - mock.Mock -} - -func (c *DbChatMock) GetByID( - ctx context.Context, - chatId string, - service db_models.ChatService, -) (*db_models.Chat, error) { - args := c.Called(ctx, chatId, service) - - return args.Get(0).(*db_models.Chat), args.Error(1) -} - -func (c *DbChatMock) Create( - ctx context.Context, - chatId string, - service db_models.ChatService, -) (*db_models.Chat, error) { - args := c.Called(ctx, chatId, service) - - return args.Get(0).(*db_models.Chat), args.Error(1) -} - -func (c *DbChatMock) Update( - ctx context.Context, - chatId string, - service db_models.ChatService, - query *db.ChatUpdateQuery, -) (*db_models.Chat, error) { - args := c.Called(ctx, chatId, service, query) - - return args.Get(0).(*db_models.Chat), args.Error(1) -} - -func (c *DbChatMock) GetAllByService( - ctx context.Context, - service db_models.ChatService, -) ([]*db_models.Chat, error) { - args := c.Called(ctx, service) - - return args.Get(0).([]*db_models.Chat), args.Error(1) -} diff --git a/internal/test_utils/mocks/db_follow.go b/internal/test_utils/mocks/db_follow.go deleted file mode 100644 index 67ee25c9..00000000 --- a/internal/test_utils/mocks/db_follow.go +++ /dev/null @@ -1,57 +0,0 @@ -package mocks - -import ( - "context" - "github.com/satont/twitch-notifier/internal/db/db_models" - - "github.com/google/uuid" - "github.com/stretchr/testify/mock" -) - -type DbFollowMock struct { - mock.Mock -} - -func (f *DbFollowMock) Create( - ctx context.Context, - channelID uuid.UUID, - chatID uuid.UUID, -) (*db_models.Follow, error) { - args := f.Called(ctx, channelID, chatID) - - return args.Get(0).(*db_models.Follow), args.Error(1) -} - -func (f *DbFollowMock) Delete(ctx context.Context, id uuid.UUID) error { - args := f.Called(ctx, id) - - return args.Error(0) -} - -func (f *DbFollowMock) GetByChatAndChannel( - ctx context.Context, - channelId uuid.UUID, - chatId uuid.UUID, -) (*db_models.Follow, error) { - args := f.Called(ctx, channelId, chatId) - - return args.Get(0).(*db_models.Follow), args.Error(1) -} - -func (f *DbFollowMock) GetByChannelID(ctx context.Context, channelId uuid.UUID) ([]*db_models.Follow, error) { - args := f.Called(ctx, channelId) - - return args.Get(0).([]*db_models.Follow), args.Error(1) -} - -func (f *DbFollowMock) GetByChatID(ctx context.Context, chatID uuid.UUID, limit, offset int) ([]*db_models.Follow, error) { - args := f.Called(ctx, chatID, limit, offset) - - return args.Get(0).([]*db_models.Follow), args.Error(1) -} - -func (f *DbFollowMock) CountByChatID(ctx context.Context, chatID uuid.UUID) (int, error) { - args := f.Called(ctx, chatID) - - return args.Int(0), args.Error(1) -} diff --git a/internal/test_utils/mocks/db_stream.go b/internal/test_utils/mocks/db_stream.go deleted file mode 100644 index f35a7b8e..00000000 --- a/internal/test_utils/mocks/db_stream.go +++ /dev/null @@ -1,52 +0,0 @@ -package mocks - -import ( - "context" - "github.com/satont/twitch-notifier/internal/db" - "github.com/satont/twitch-notifier/internal/db/db_models" - - "github.com/google/uuid" - "github.com/stretchr/testify/mock" -) - -type DbStreamMock struct { - mock.Mock -} - -func (s *DbStreamMock) GetByID(ctx context.Context, streamId string) (*db_models.Stream, error) { - args := s.Called(ctx, streamId) - - return args.Get(0).(*db_models.Stream), args.Error(1) -} - -func (s *DbStreamMock) GetLatestByChannelID(ctx context.Context, channelEntityID uuid.UUID) (*db_models.Stream, error) { - args := s.Called(ctx, channelEntityID) - - return args.Get(0).(*db_models.Stream), args.Error(1) -} - -func (s *DbStreamMock) GetManyByChannelID(ctx context.Context, channelEntityID uuid.UUID, limit int) ([]*db_models.Stream, error) { - args := s.Called(ctx, channelEntityID, limit) - - return args.Get(0).([]*db_models.Stream), args.Error(1) -} - -func (s *DbStreamMock) UpdateOneByStreamID( - ctx context.Context, - streamID string, - updateQuery *db.StreamUpdateQuery, -) (*db_models.Stream, error) { - args := s.Called(ctx, streamID, updateQuery) - - return args.Get(0).(*db_models.Stream), args.Error(1) -} - -func (s *DbStreamMock) CreateOneByChannelID( - ctx context.Context, - channelEntityID uuid.UUID, - updateQuery *db.StreamUpdateQuery, -) (*db_models.Stream, error) { - args := s.Called(ctx, channelEntityID, updateQuery) - - return args.Get(0).(*db_models.Stream), args.Error(1) -} diff --git a/internal/test_utils/mocks/message_sender.go b/internal/test_utils/mocks/message_sender.go deleted file mode 100644 index 137256ad..00000000 --- a/internal/test_utils/mocks/message_sender.go +++ /dev/null @@ -1,19 +0,0 @@ -package mocks - -import ( - "context" - "github.com/satont/twitch-notifier/internal/db/db_models" - "github.com/satont/twitch-notifier/internal/message_sender" - - "github.com/stretchr/testify/mock" -) - -type MessageSenderMock struct { - mock.Mock -} - -func (m *MessageSenderMock) SendMessage(ctx context.Context, chat *db_models.Chat, opts *message_sender.MessageOpts) error { - args := m.Called(ctx, chat, opts) - - return args.Error(0) -} diff --git a/internal/test_utils/mocks/twitch_api_client.go b/internal/test_utils/mocks/twitch_api_client.go deleted file mode 100644 index 6128706f..00000000 --- a/internal/test_utils/mocks/twitch_api_client.go +++ /dev/null @@ -1,43 +0,0 @@ -package mocks - -import ( - "strings" - - "github.com/nicklaw5/helix/v2" - "github.com/stretchr/testify/mock" -) - -type TwitchApiMock struct { - mock.Mock -} - -func (m *TwitchApiMock) GetUser(id, login string) (*helix.User, error) { - args := m.Called(id, login) - return args.Get(0).(*helix.User), args.Error(1) -} - -func (m *TwitchApiMock) GetUsers(ids, logins []string) ([]helix.User, error) { - args := m.Called(ids, logins) - return args.Get(0).([]helix.User), args.Error(1) -} - -func (m *TwitchApiMock) GetStreamByUserId(id string) (*helix.Stream, error) { - args := m.Called(id) - return args.Get(0).(*helix.Stream), args.Error(1) -} - -func (m *TwitchApiMock) GetStreamsByUserIds(ids []string) ([]helix.Stream, error) { - args := m.Called(ids) - return args.Get(0).([]helix.Stream), args.Error(1) -} - -func (m *TwitchApiMock) GetChannelByUserId(id string) (*helix.ChannelInformation, error) { - strings.ReplaceAll(id, " ", "") - args := m.Called(id) - return args.Get(0).(*helix.ChannelInformation), args.Error(1) -} - -func (m *TwitchApiMock) GetChannelsByUserIds(ids []string) ([]helix.ChannelInformation, error) { - args := m.Called(ids) - return args.Get(0).([]helix.ChannelInformation), args.Error(1) -} diff --git a/internal/test_utils/telegram_client.go b/internal/test_utils/telegram_client.go deleted file mode 100644 index 0268445f..00000000 --- a/internal/test_utils/telegram_client.go +++ /dev/null @@ -1,21 +0,0 @@ -package test_utils - -import ( - "github.com/mr-linch/go-tg" - "net/http" - "net/http/httptest" -) - -const ( - TelegramClientToken = "1234:secret" - TelegramOkResponse = `{"ok":true}` -) - -func NewTelegramClient(server *httptest.Server) *tg.Client { - client := tg.New(TelegramClientToken, - tg.WithClientServerURL(server.URL), - tg.WithClientDoer(&http.Client{}), - ) - - return client -} diff --git a/internal/twitch/chunked_req.go b/internal/twitch/chunked_req.go deleted file mode 100644 index be48d3f0..00000000 --- a/internal/twitch/chunked_req.go +++ /dev/null @@ -1,63 +0,0 @@ -package twitch - -import ( - "errors" - "github.com/samber/lo" - "reflect" - "sync" -) - -type chunkedRequestData[Request any, Response any] struct { - ids []string - requestFn func(Request) (Response, error) - responseSelectorFn func(Response) interface{} - paramFn func(chunk []string) Request -} - -func getDataChunked[T, Req, Res any](req *chunkedRequestData[Req, Res]) ([]T, error) { - results := make([]T, 0, len(req.ids)) - - chunkedIds := lo.Chunk(req.ids, 100) - - wg := &sync.WaitGroup{} - mu := &sync.Mutex{} - errChan := make(chan error, len(chunkedIds)) - - for _, chunk := range chunkedIds { - wg.Add(1) - go func(chunk []string) { - defer wg.Done() - - data, err := req.requestFn(req.paramFn(chunk)) - - if err != nil { - errChan <- err - return - } - - resultValue := reflect.ValueOf(data) - - if reflect.Indirect(resultValue).FieldByName("ErrorMessage").String() != "" { - errChan <- errors.New(reflect.Indirect(resultValue).FieldByName("ErrorMessage").String()) - return - } - - selectedField := req.responseSelectorFn(data) - - mu.Lock() - results = append( - results, - selectedField.([]T)..., - ) - mu.Unlock() - }(chunk) - } - - wg.Wait() - - if len(errChan) > 0 { - return nil, <-errChan - } - - return results, nil -} diff --git a/internal/twitch/helpers/rate_limiter.go b/internal/twitch/helpers/rate_limiter.go deleted file mode 100644 index 0d4ac277..00000000 --- a/internal/twitch/helpers/rate_limiter.go +++ /dev/null @@ -1,28 +0,0 @@ -package helpers - -import ( - "fmt" - "github.com/nicklaw5/helix/v2" - "time" -) - -func RateLimitCallback(lastResponse *helix.Response) error { - if lastResponse.GetRateLimitRemaining() > 0 { - return nil - } - - var reset64 int64 - reset64 = int64(lastResponse.GetRateLimitReset()) - - currentTime := time.Now().Unix() - - if currentTime < reset64 { - timeDiff := time.Duration(reset64 - currentTime) - if timeDiff > 0 { - fmt.Printf("Waiting on rate limit to pass before sending next request (%d seconds)\n", timeDiff) - time.Sleep(timeDiff * time.Second) - } - } - - return nil -} diff --git a/internal/twitch/implementation.go b/internal/twitch/implementation.go deleted file mode 100644 index c33f16d4..00000000 --- a/internal/twitch/implementation.go +++ /dev/null @@ -1,165 +0,0 @@ -package twitch - -import ( - "github.com/nicklaw5/helix/v2" - "github.com/satont/twitch-notifier/internal/twitch/helpers" - "time" -) - -type twitchService struct { - apiClient *helix.Client -} - -func NewTwitchService(clientId string, clientSecret string) (Interface, error) { - apiClient, err := helix.NewClient(&helix.Options{ - ClientID: clientId, - ClientSecret: clientSecret, - RateLimitFunc: helpers.RateLimitCallback, - }) - - if err != nil { - return nil, err - } - - token, err := apiClient.RequestAppAccessToken([]string{}) - if err != nil { - panic(err) - } - apiClient.SetAppAccessToken(token.Data.AccessToken) - - go func() { - for { - newToken, tokenErr := apiClient.RequestAppAccessToken([]string{}) - if tokenErr != nil { - panic(tokenErr) - } - apiClient.SetAppAccessToken(newToken.Data.AccessToken) - time.Sleep(1 * time.Hour) - } - }() - - return &twitchService{ - apiClient: apiClient, - }, nil -} - -func (t *twitchService) GetUser(id, login string) (*helix.User, error) { - users, err := t.GetUsers([]string{id}, []string{login}) - if err != nil { - return nil, err - } - - if len(users) == 0 { - return nil, nil - } - - return &users[0], nil -} - -func (t *twitchService) GetUsers(ids, logins []string) ([]helix.User, error) { - var data []string - - isById := len(ids) > 0 && ids[0] != "" - - if isById { - data = ids - } else { - data = logins - } - - reqData := &chunkedRequestData[*helix.UsersParams, *helix.UsersResponse]{ - ids: data, - requestFn: t.apiClient.GetUsers, - responseSelectorFn: func(response *helix.UsersResponse) interface{} { - return response.Data.Users - }, - paramFn: func(chunk []string) *helix.UsersParams { - if isById { - return &helix.UsersParams{ - IDs: chunk, - } - } else { - return &helix.UsersParams{ - Logins: chunk, - } - } - }, - } - - users, err := getDataChunked[helix.User](reqData) - if err != nil { - return nil, err - } - - return users, nil -} - -func (t *twitchService) GetStreamByUserId(id string) (*helix.Stream, error) { - streams, err := t.GetStreamsByUserIds([]string{id}) - if err != nil { - return nil, err - } - - if len(streams) == 0 { - return nil, nil - } - - return &streams[0], nil -} - -func (t *twitchService) GetStreamsByUserIds(ids []string) ([]helix.Stream, error) { - reqData := &chunkedRequestData[*helix.StreamsParams, *helix.StreamsResponse]{ - ids: ids, - requestFn: t.apiClient.GetStreams, - responseSelectorFn: func(response *helix.StreamsResponse) interface{} { - return response.Data.Streams - }, - paramFn: func(chunk []string) *helix.StreamsParams { - return &helix.StreamsParams{ - UserIDs: chunk, - } - }, - } - - streams, err := getDataChunked[helix.Stream](reqData) - if err != nil { - return nil, err - } - - return streams, nil -} - -func (t *twitchService) GetChannelByUserId(id string) (*helix.ChannelInformation, error) { - channels, err := t.GetChannelsByUserIds([]string{id}) - if err != nil { - return nil, err - } - - if len(channels) == 0 { - return nil, nil - } - - return &channels[0], nil -} - -func (t *twitchService) GetChannelsByUserIds(ids []string) ([]helix.ChannelInformation, error) { - reqData := &chunkedRequestData[*helix.GetChannelInformationParams, *helix.GetChannelInformationResponse]{ - ids: ids, - requestFn: t.apiClient.GetChannelInformation, - responseSelectorFn: func(response *helix.GetChannelInformationResponse) interface{} { - return response.Data.Channels - }, - paramFn: func(chunk []string) *helix.GetChannelInformationParams { - return &helix.GetChannelInformationParams{ - BroadcasterIDs: chunk, - } - }, - } - - channels, err := getDataChunked[helix.ChannelInformation](reqData) - if err != nil { - return nil, err - } - - return channels, nil -} diff --git a/internal/twitch/implementation_test.go b/internal/twitch/implementation_test.go deleted file mode 100644 index 5e87d5ad..00000000 --- a/internal/twitch/implementation_test.go +++ /dev/null @@ -1,212 +0,0 @@ -package twitch - -import ( - "github.com/nicklaw5/helix/v2" - "github.com/stretchr/testify/assert" - "net/http" - "net/http/httptest" - "testing" -) - -func newMockedApi(server *httptest.Server) (*twitchService, error) { - apiClient, err := helix.NewClient(&helix.Options{ - ClientID: "test", - APIBaseURL: server.URL, - }) - if err != nil { - return nil, err - } - - apiClient.SetAppAccessToken("test") - - return &twitchService{ - apiClient: apiClient, - }, nil -} - -func TestTwitchService_GetUser(t *testing.T) { - t.Parallel() - - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(http.StatusOK) - _, _ = w.Write([]byte(`{"data":[{"id":"1","login":"test"}]}`)) - })) - defer server.Close() - - twitchService, err := newMockedApi(server) - assert.NoError(t, err) - - user, err := twitchService.GetUser("1", "") - assert.NoError(t, err) - - assert.Equal(t, "1", user.ID) - assert.Equal(t, "test", user.Login) -} - -func TestTwitchService_GetUsers(t *testing.T) { - t.Parallel() - - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(http.StatusOK) - _, _ = w.Write([]byte(`{"data":[{"id":"1","login":"test"},{"id":"2","login":"test2"}]}`)) - })) - defer server.Close() - - twitchService, err := newMockedApi(server) - assert.NoError(t, err) - - expectedUsers := []helix.User{ - {ID: "1", Login: "test"}, - {ID: "2", Login: "test2"}, - } - - table := []struct { - name string - ids []string - logins []string - }{ - { - name: "ids", - ids: []string{"1", "2"}, - logins: []string{}, - }, - { - name: "logins", - ids: []string{}, - logins: []string{"test", "test2"}, - }, - } - - for _, tt := range table { - t.Run(tt.name, func(t *testing.T) { - users, err := twitchService.GetUsers(tt.ids, tt.logins) - assert.NoError(t, err) - - assert.Equal(t, expectedUsers, users) - }) - } -} - -func TestTwitchService_GetStreamByUserId(t *testing.T) { - t.Parallel() - - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(http.StatusOK) - _, _ = w.Write([]byte(`{"data":[{"id":"1","user_name":"test","game_name": "Dota 2"}]}`)) - })) - defer server.Close() - - twitchService, err := newMockedApi(server) - assert.NoError(t, err) - - stream, err := twitchService.GetStreamByUserId("1") - assert.NoError(t, err) - - assert.Equal(t, "1", stream.ID) - assert.Equal(t, "test", stream.UserName) - assert.Equal(t, "Dota 2", stream.GameName) -} - -func TestTwitchService_GetStreamsByUserId(t *testing.T) { - t.Parallel() - - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(http.StatusOK) - _, _ = w.Write([]byte(`{"data":[{"id":"1","user_name":"test","game_name": "Dota 2"}, {"id":"2","user_name":"test2","game_name": "Dota 3"}]}`)) - })) - defer server.Close() - - twitchService, err := newMockedApi(server) - assert.NoError(t, err) - - streams, err := twitchService.GetStreamsByUserIds([]string{"1", "2"}) - assert.NoError(t, err) - - assert.Equal(t, []helix.Stream{ - {ID: "1", UserName: "test", GameName: "Dota 2"}, - {ID: "2", UserName: "test2", GameName: "Dota 3"}, - }, streams) -} - -func TestTwitchService_GetChannelByUserId(t *testing.T) { - t.Parallel() - - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(http.StatusOK) - _, _ = w.Write([]byte(`{"data":[ - {"broadcaster_id":"1","broadcaster_name":"test","game_name": "Dota 2", "title": "tiitle"} - ]}`)) - })) - defer server.Close() - - twitchService, err := newMockedApi(server) - assert.NoError(t, err) - - channel, err := twitchService.GetChannelByUserId("1") - assert.NoError(t, err) - - assert.Equal(t, "1", channel.BroadcasterID) - assert.Equal(t, "test", channel.BroadcasterName) - assert.Equal(t, "Dota 2", channel.GameName) - assert.Equal(t, "tiitle", channel.Title) -} - -func TestTwitchService_GetChannelsByUserId(t *testing.T) { - t.Parallel() - - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(http.StatusOK) - _, _ = w.Write([]byte(`{"data":[ - {"broadcaster_id":"1","broadcaster_name":"test","game_name": "Dota 2", "title": "tiitle"}, - {"broadcaster_id":"2","broadcaster_name":"test2","game_name": "Dota 3", "title": "tiitle2"} - ]}`)) - })) - defer server.Close() - - twitchService, err := newMockedApi(server) - assert.NoError(t, err) - - channels, err := twitchService.GetChannelsByUserIds([]string{"1", "2"}) - assert.NoError(t, err) - - assert.Equal(t, []helix.ChannelInformation{ - {BroadcasterID: "1", BroadcasterName: "test", GameName: "Dota 2", Title: "tiitle"}, - {BroadcasterID: "2", BroadcasterName: "test2", GameName: "Dota 3", Title: "tiitle2"}, - }, channels) -} - -func TestTwitchService_GetChunkerError(t *testing.T) { - t.Parallel() - - table := []struct { - name string - server *httptest.Server - expectedErrorMessage string - }{ - { - name: "fail because twitch returns error code", - server: httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(http.StatusForbidden) - data := `{ - "error": "Forbidden", - "status": 403, - "message": "test" - }` - _, _ = w.Write([]byte(data)) - })), - expectedErrorMessage: "test", - }, - } - - for _, tt := range table { - t.Run(tt.name, func(t *testing.T) { - twitchService, err := newMockedApi(tt.server) - assert.NoError(t, err) - - _, err = twitchService.GetChannelByUserId("1") - assert.Error(t, err) - assert.Equal(t, tt.expectedErrorMessage, err.Error()) - }) - } - -} diff --git a/internal/twitch/interface.go b/internal/twitch/interface.go deleted file mode 100644 index 289f1f76..00000000 --- a/internal/twitch/interface.go +++ /dev/null @@ -1,16 +0,0 @@ -package twitch - -import ( - "github.com/nicklaw5/helix/v2" -) - -type Interface interface { - GetUser(id, login string) (*helix.User, error) - GetUsers(ids, logins []string) ([]helix.User, error) - - GetStreamByUserId(id string) (*helix.Stream, error) - GetStreamsByUserIds(ids []string) ([]helix.Stream, error) - - GetChannelByUserId(id string) (*helix.ChannelInformation, error) - GetChannelsByUserIds(ids []string) ([]helix.ChannelInformation, error) -} diff --git a/internal/twitch_streams_cheker/thumbnail_builder.go b/internal/twitch_streams_cheker/thumbnail_builder.go deleted file mode 100644 index 53619739..00000000 --- a/internal/twitch_streams_cheker/thumbnail_builder.go +++ /dev/null @@ -1,60 +0,0 @@ -package twitch_streams_cheker - -import ( - "fmt" - "net/http" - "strings" - "time" -) - -type thumbNailBuilder struct { -} - -func newThumbNailBuilder() *thumbNailBuilder { - return &thumbNailBuilder{} -} - -func (c *thumbNailBuilder) checkValidity(url string, n int) (bool, error) { - client := &http.Client{ - CheckRedirect: func(req *http.Request, via []*http.Request) error { - return http.ErrUseLastResponse - }, - } - - req, err := client.Get(url) - if err != nil { - return false, err - } - - if req.StatusCode != 200 && n == 5 { - return false, fmt.Errorf("url %s is not valid", url) - } else if req.StatusCode != 200 { - time.Sleep(5 * time.Second) - return c.checkValidity(url, n+1) - } else { - return true, nil - } -} - -func (c *thumbNailBuilder) Build(thumbNailUrl string, checkValidity bool) (string, error) { - thumbNail := thumbNailUrl - thumbNail = strings.Replace(thumbNail, "{width}", "1920", 1) - thumbNail = strings.Replace(thumbNail, "{height}", "1080", 1) - - if !checkValidity { - return thumbNail, nil - } - - valid, err := c.checkValidity(thumbNail, 0) - - if !valid || err != nil { - thumbNail = strings.Replace(thumbNail, "1920", "1280", 1) - thumbNail = strings.Replace(thumbNail, "1080", "720", 1) - } - - if err != nil { - return thumbNail, err - } - - return thumbNail, nil -} diff --git a/internal/twitch_streams_cheker/twitch_streams_cheker.go b/internal/twitch_streams_cheker/twitch_streams_cheker.go deleted file mode 100644 index 5de41198..00000000 --- a/internal/twitch_streams_cheker/twitch_streams_cheker.go +++ /dev/null @@ -1,461 +0,0 @@ -package twitch_streams_cheker - -import ( - "context" - "fmt" - "strings" - "sync" - "time" - - "github.com/mr-linch/go-tg" - "github.com/nicklaw5/helix/v2" - "github.com/samber/lo" - "github.com/satont/twitch-notifier/internal/db" - "github.com/satont/twitch-notifier/internal/db/db_models" - "github.com/satont/twitch-notifier/internal/message_sender" - "github.com/satont/twitch-notifier/internal/types" - "go.uber.org/zap" -) - -type TwitchStreamChecker struct { - services *types.Services - ticks int - tickTime *time.Duration - sender message_sender.MessageSenderInterface - thumbNailBuilder *thumbNailBuilder -} - -func NewTwitchStreamChecker( - services *types.Services, - sender message_sender.MessageSenderInterface, - tickTime *time.Duration, -) *TwitchStreamChecker { - checker := &TwitchStreamChecker{ - services: services, - tickTime: tickTime, - sender: sender, - thumbNailBuilder: newThumbNailBuilder(), - } - - return checker -} - -func (t *TwitchStreamChecker) check(ctx context.Context) { - channels, err := t.services.Channel.GetAll(ctx) - if err != nil { - zap.S().Error(err) - return - } - - channelsIDs := make([]string, 0, len(channels)) - for _, channel := range channels { - channelsIDs = append(channelsIDs, channel.ChannelID) - } - - twitchChannels, err := t.services.Twitch.GetChannelsByUserIds(channelsIDs) - if err != nil { - zap.S().Error(err) - return - } - - currentTwitchStreams, err := t.services.Twitch.GetStreamsByUserIds(channelsIDs) - if err != nil { - zap.S().Error(err) - return - } - - wg := &sync.WaitGroup{} - for _, channel := range channels { - wg.Add(1) - - go func(channel *db_models.Channel) { - defer wg.Done() - twitchChannel, twitchChannelOk := lo.Find( - twitchChannels, - func(item helix.ChannelInformation) bool { - return item.BroadcasterID == channel.ChannelID - }, - ) - if !twitchChannelOk { - return - } - - currentDBStream, err := t.services.Stream.GetLatestByChannelID(ctx, channel.ID) - if err != nil { - zap.S().Error(err) - return - } - - followers, err := t.services.Follow.GetByChannelID(ctx, channel.ID) - if err != nil { - zap.S().Error(err) - return - } - - twitchCurrentStream, twitchCurrentStreamOk := lo.Find( - currentTwitchStreams, - func(stream helix.Stream) bool { - return stream.UserID == channel.ChannelID - }, - ) - - if twitchCurrentStreamOk && twitchCurrentStream.Type != "live" { - return - } - - // if stream becomes offline - if !twitchCurrentStreamOk && currentDBStream != nil && currentDBStream.EndedAt == nil { - _, err = t.services.Stream.UpdateOneByStreamID( - ctx, - currentDBStream.ID, - &db.StreamUpdateQuery{ - IsLive: lo.ToPtr(false), - }, - ) - if err != nil { - zap.S().Error(err) - return - } - - // send message to all followers - for _, follower := range followers { - if !follower.Chat.Settings.OfflineNotification { - continue - } - - message := t.services.I18N.Translate( - "notifications.streams.nowOffline", - follower.Chat.Settings.ChatLanguage.String(), - map[string]string{ - "channelLink": tg.MD.Link( - twitchChannel.BroadcasterName, - fmt.Sprintf("https://twitch.tv/%s", twitchChannel.BroadcasterName), - ), - "categories": strings.Join(currentDBStream.Categories, " -> "), - "duration": time.Now().UTC().Sub(currentDBStream.StartedAt). - Truncate(1 * time.Second). - String(), - }, - ) - unfollowButton := message_sender.KeyboardButton{ - Text: t.services.I18N.Translate( - "commands.unfollow.callbackButton", - follower.Chat.Settings.ChatLanguage.String(), - map[string]string{ - "streamer": twitchChannel.BroadcasterName, - }, - ), - CallbackData: fmt.Sprintf("channels_unfollow_%v", channel.ID), - SkipInGroup: true, - } - - err = t.sender.SendMessage( - ctx, follower.Chat, &message_sender.MessageOpts{ - Text: message, - ParseMode: &tg.MD, - Buttons: [][]message_sender.KeyboardButton{{unfollowButton}}, - }, - ) - if err != nil { - zap.S().Error(err) - continue - } - } - } - - // if stream becomes online - if twitchCurrentStreamOk && currentDBStream == nil { - _, err = t.services.Stream.CreateOneByChannelID( - ctx, - channel.ID, - &db.StreamUpdateQuery{ - StreamID: twitchCurrentStream.ID, - IsLive: lo.ToPtr(true), - Category: lo.ToPtr(twitchCurrentStream.GameName), - Title: lo.ToPtr(twitchCurrentStream.Title), - }, - ) - if err != nil { - zap.S().Error(err) - return - } - - for _, follower := range followers { - message := t.services.I18N.Translate( - "notifications.streams.nowOnline", - follower.Chat.Settings.ChatLanguage.String(), - map[string]string{ - "channelLink": tg.MD.Link( - twitchChannel.BroadcasterName, - fmt.Sprintf("https://twitch.tv/%s", twitchChannel.BroadcasterName), - ), - "category": twitchCurrentStream.GameName, - "title": twitchCurrentStream.Title, - }, - ) - - unfollowButton := message_sender.KeyboardButton{ - Text: t.services.I18N.Translate( - "commands.unfollow.callbackButton", - follower.Chat.Settings.ChatLanguage.String(), - map[string]string{ - "streamer": twitchChannel.BroadcasterName, - }, - ), - CallbackData: fmt.Sprintf("channels_unfollow_%v", channel.ID), - SkipInGroup: true, - } - - thumbNail, err := t.thumbNailBuilder.Build(twitchCurrentStream.ThumbnailURL, true) - if err != nil { - zap.S().Error(err) - } - - err = t.sender.SendMessage( - ctx, follower.Chat, &message_sender.MessageOpts{ - Text: message, - ImageURL: lo.If( - follower.Chat.Settings.ImageInNotification, - fmt.Sprintf("%s?%d", thumbNail, time.Now().Unix()), - ).Else(""), - ParseMode: &tg.MD, - Buttons: [][]message_sender.KeyboardButton{{unfollowButton}}, - }, - ) - if err != nil { - zap.S().Error(err) - continue - } - } - } - - // stream is still online, need to check do we need to update title or category - if twitchCurrentStreamOk && currentDBStream != nil && - currentDBStream.ID == twitchCurrentStream.ID { - latestTitle := "" - if len(currentDBStream.Titles) > 0 { - latestTitle = currentDBStream.Titles[len(currentDBStream.Titles)-1] - } - latestCategory := "" - if len(currentDBStream.Categories) > 0 { - latestCategory = currentDBStream.Categories[len(currentDBStream.Categories)-1] - } - - // stream is online, and both title and category changed, so we need to send a complex notification - if twitchCurrentStream.GameName != latestCategory && - twitchCurrentStream.Title != latestTitle { - _, err = t.services.Stream.UpdateOneByStreamID( - ctx, - currentDBStream.ID, - &db.StreamUpdateQuery{ - Category: lo.ToPtr(twitchCurrentStream.GameName), - Title: lo.ToPtr(twitchCurrentStream.Title), - }, - ) - if err != nil { - zap.S().Error(err) - return - } - - thumbNail, err := t.thumbNailBuilder.Build(twitchCurrentStream.ThumbnailURL, false) - if err != nil { - zap.S().Error(err) - } - - for _, follower := range followers { - if !follower.Chat.Settings.GameAndTitleChangeNotification { - continue - } - - unfollowButton := message_sender.KeyboardButton{ - Text: t.services.I18N.Translate( - "commands.unfollow.callbackButton", - follower.Chat.Settings.ChatLanguage.String(), - map[string]string{ - "streamer": twitchChannel.BroadcasterName, - }, - ), - CallbackData: fmt.Sprintf("channels_unfollow_%v", channel.ID), - SkipInGroup: true, - } - - err = t.sender.SendMessage( - ctx, follower.Chat, &message_sender.MessageOpts{ - Text: t.services.I18N.Translate( - "notifications.streams.titleAndCategoryChanged", - follower.Chat.Settings.ChatLanguage.String(), - map[string]string{ - "channelLink": tg.MD.Link( - twitchChannel.BroadcasterName, - fmt.Sprintf( - "https://twitch.tv/%s", - twitchChannel.BroadcasterName, - ), - ), - "category": tg.MD.Bold(twitchCurrentStream.GameName), - "oldCategory": tg.MD.Bold(latestCategory), - "title": tg.MD.Bold(twitchCurrentStream.Title), - "oldTitle": tg.MD.Bold(latestTitle), - }, - ), - ParseMode: &tg.MD, - ImageURL: lo.If( - follower.Chat.Settings.ImageInNotification, - fmt.Sprintf("%s?%d", thumbNail, time.Now().Unix()), - ).Else(""), - Buttons: [][]message_sender.KeyboardButton{{unfollowButton}}, - }, - ) - if err != nil { - zap.S().Error(err) - continue - } - } - return - } - - if twitchCurrentStream.GameName != latestCategory { - _, err = t.services.Stream.UpdateOneByStreamID( - ctx, - currentDBStream.ID, - &db.StreamUpdateQuery{ - Category: lo.ToPtr(twitchCurrentStream.GameName), - }, - ) - if err != nil { - zap.S().Error(err) - return - } - - for _, follower := range followers { - if !follower.Chat.Settings.GameChangeNotification { - continue - } - - thumbNail, err := t.thumbNailBuilder.Build(twitchCurrentStream.ThumbnailURL, true) - if err != nil { - zap.S().Error(err) - } - - err = t.sender.SendMessage( - ctx, follower.Chat, &message_sender.MessageOpts{ - Text: t.services.I18N.Translate( - "notifications.streams.newCategory", - follower.Chat.Settings.ChatLanguage.String(), - map[string]string{ - "channelLink": tg.MD.Link( - twitchChannel.BroadcasterName, - fmt.Sprintf( - "https://twitch.tv/%s", - twitchChannel.BroadcasterName, - ), - ), - "category": tg.MD.Bold(twitchCurrentStream.GameName), - "oldCategory": tg.MD.Bold(latestCategory), - }, - ), - ParseMode: &tg.MD, - ImageURL: lo.If( - follower.Chat.Settings.ImageInNotification, - fmt.Sprintf("%s?%d", thumbNail, time.Now().Unix()), - ).Else(""), - }, - ) - if err != nil { - zap.S().Error(err) - continue - } - } - return - } - - if twitchCurrentStream.Title != latestTitle { - _, err = t.services.Stream.UpdateOneByStreamID( - ctx, - currentDBStream.ID, - &db.StreamUpdateQuery{ - Title: lo.ToPtr(twitchCurrentStream.Title), - }, - ) - if err != nil { - zap.S().Error(err) - return - } - - for _, follower := range followers { - if !follower.Chat.Settings.TitleChangeNotification { - continue - } - - thumbNail, err := t.thumbNailBuilder.Build(twitchCurrentStream.ThumbnailURL, true) - if err != nil { - zap.S().Error(err) - } - - err = t.sender.SendMessage( - ctx, follower.Chat, &message_sender.MessageOpts{ - Text: t.services.I18N.Translate( - "notifications.streams.titleChanged", - follower.Chat.Settings.ChatLanguage.String(), - map[string]string{ - "channelLink": tg.MD.Link( - twitchChannel.BroadcasterName, - fmt.Sprintf( - "https://twitch.tv/%s", - twitchChannel.BroadcasterName, - ), - ), - "category": twitchCurrentStream.GameName, - "title": tg.MD.Bold(twitchCurrentStream.Title), - "oldTitle": tg.MD.Bold(latestTitle), - }, - ), - ParseMode: &tg.MD, - ImageURL: lo.If( - follower.Chat.Settings.ImageInNotification, - fmt.Sprintf("%s?%d", thumbNail, time.Now().Unix()), - ).Else(""), - }, - ) - if err != nil { - zap.S().Error(err) - continue - } - } - } - - } - }(channel) - } - wg.Wait() -} - -func (t *TwitchStreamChecker) StartPolling(ctx context.Context) { - tickTime := lo. - IfF( - t.tickTime != nil, func() time.Duration { - return *t.tickTime - }, - ). - Else( - lo. - If(t.services.Config.AppEnv == "development", 10*time.Second). - Else(1 * time.Minute), - ) - ticker := time.NewTicker(tickTime) - - t.check(ctx) - - go func() { - for { - select { - case <-ticker.C: - t.ticks++ - t.check(ctx) - case <-ctx.Done(): - ticker.Stop() - return - } - } - }() -} diff --git a/internal/twitch_streams_cheker/twitch_streams_cheker_test.go b/internal/twitch_streams_cheker/twitch_streams_cheker_test.go deleted file mode 100644 index dc927af8..00000000 --- a/internal/twitch_streams_cheker/twitch_streams_cheker_test.go +++ /dev/null @@ -1,323 +0,0 @@ -package twitch_streams_cheker - -import ( - "context" - "testing" - - "github.com/google/uuid" - "github.com/nicklaw5/helix/v2" - "github.com/samber/lo" - "github.com/satont/twitch-notifier/internal/db" - "github.com/satont/twitch-notifier/internal/db/db_models" - "github.com/satont/twitch-notifier/internal/test_utils/mocks" - "github.com/satont/twitch-notifier/internal/types" - i18nmocks "github.com/satont/twitch-notifier/pkg/i18n/mocks" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/mock" -) - -func TestNewTwitchStreamChecker(t *testing.T) { - t.Parallel() - - services := &types.Services{} - - checker := NewTwitchStreamChecker(services, &mocks.MessageSenderMock{}, nil) - assert.IsType(t, &TwitchStreamChecker{}, checker) -} - -func TestTwitchStreamChecker_check(t *testing.T) { - t.Parallel() - - channelsMock := &mocks.DbChannelMock{} - twitchMock := &mocks.TwitchApiMock{} - senderMock := &mocks.MessageSenderMock{} - streamMock := &mocks.DbStreamMock{} - followMock := &mocks.DbFollowMock{} - i18nMock := i18nmocks.NewI18nMock() - - i18nMock. - On("Translate", mock.Anything, mock.Anything, mock.Anything). - Return("translated") - - ctx := context.Background() - - dbChannel := &db_models.Channel{ID: uuid.New(), ChannelID: "1"} - dbStream := &db_models.Stream{ - ID: "123", - Titles: []string{"title"}, - Categories: []string{"Dota 2"}, - } - dbChat := &db_models.Chat{ - ID: uuid.New(), - ChatID: "1", - Settings: &db_models.ChatSettings{ - ChatLanguage: db_models.ChatLanguageEn, - GameChangeNotification: true, - OfflineNotification: true, - ImageInNotification: true, - GameAndTitleChangeNotification: false, - }, - } - dbFollow := &db_models.Follow{ - ID: uuid.New(), - ChatID: dbChat.ID, - Chat: dbChat, - Channel: dbChannel, - ChannelID: dbChannel.ID, - } - twitchChannelInfo := &helix.ChannelInformation{BroadcasterID: "1", BroadcasterName: "Satont"} - twitchStream := &helix.Stream{ - ID: "123", - GameName: "Dota 2", - Title: "title", - UserID: "1", - Type: "live", - } - - table := []struct { - name string - setupMocks func() - }{ - { - name: "stream becomes offline, should call UpdateOneByStreamID with correct args", - setupMocks: func() { - twitchMock.On("GetChannelsByUserIds", []string{"1"}). - Return([]helix.ChannelInformation{ - *twitchChannelInfo, - }, nil) - channelsMock.On("GetAll", ctx).Return([]*db_models.Channel{ - dbChannel, - }, nil) - followMock.On("GetByChannelID", ctx, dbChannel.ID). - Return([]*db_models.Follow{dbFollow}, nil) - twitchMock.On("GetStreamsByUserIds", []string{"1"}).Return([]helix.Stream{}, nil) - streamMock.On("GetLatestByChannelID", ctx, dbChannel.ID).Return(dbStream, nil) - followMock.On("GetByChannelID", ctx, dbChannel.ID). - Return([]*db_models.Follow{dbFollow}, nil) - streamMock.On("UpdateOneByStreamID", ctx, dbStream.ID, &db.StreamUpdateQuery{ - IsLive: lo.ToPtr(false), - }).Return((*db_models.Stream)(nil), nil) - senderMock. - On("SendMessage", - ctx, - dbChat, - mock.Anything, - ). - Return(nil) - }, - }, - { - name: "stream becomes online, should call CreateOneByChannelID with correct args", - setupMocks: func() { - twitchMock.On("GetChannelsByUserIds", []string{"1"}). - Return([]helix.ChannelInformation{ - *twitchChannelInfo, - }, nil) - channelsMock.On("GetAll", ctx).Return([]*db_models.Channel{ - dbChannel, - }, nil) - followMock.On("GetByChannelID", ctx, dbChannel.ID). - Return([]*db_models.Follow{dbFollow}, nil) - twitchMock.On("GetStreamsByUserIds", []string{"1"}).Return([]helix.Stream{ - *twitchStream, - }, nil) - streamMock.On("GetLatestByChannelID", ctx, dbChannel.ID). - Return((*db_models.Stream)(nil), nil) - streamMock.On("CreateOneByChannelID", ctx, dbChannel.ID, &db.StreamUpdateQuery{ - StreamID: "123", - IsLive: lo.ToPtr(true), - Category: lo.ToPtr("Dota 2"), - Title: lo.ToPtr("title"), - }).Return((*db_models.Stream)(nil), nil) - senderMock. - On("SendMessage", - ctx, - dbChat, - mock.Anything, - ). - Return(nil) - }, - }, - { - name: "stream is still online, we should update category", - setupMocks: func() { - newHelixStream := &helix.Stream{ - ID: "123", - GameName: "Just Chatting", - Title: "title", - UserID: "1", - Type: "live", - } - - twitchMock.On("GetChannelsByUserIds", []string{"1"}). - Return([]helix.ChannelInformation{ - *twitchChannelInfo, - }, nil) - channelsMock.On("GetAll", ctx).Return([]*db_models.Channel{ - dbChannel, - }, nil) - followMock.On("GetByChannelID", ctx, dbChannel.ID). - Return([]*db_models.Follow{dbFollow}, nil) - twitchMock.On("GetStreamsByUserIds", []string{"1"}).Return([]helix.Stream{ - *newHelixStream, - }, nil) - streamMock.On("GetLatestByChannelID", ctx, dbChannel.ID).Return(dbStream, nil) - streamMock.On("UpdateOneByStreamID", ctx, dbStream.ID, &db.StreamUpdateQuery{ - Category: lo.ToPtr("Just Chatting"), - }).Return((*db_models.Stream)(nil), nil) - senderMock. - On("SendMessage", - ctx, - dbChat, - mock.Anything, - ). - Return(nil) - }, - }, - { - name: "stream is still online, we should update title", - setupMocks: func() { - newHelixStream := &helix.Stream{ - ID: "123", - GameName: "Dota 2", - Title: "title1", - UserID: "1", - Type: "live", - } - - twitchMock.On("GetChannelsByUserIds", []string{"1"}). - Return([]helix.ChannelInformation{ - *twitchChannelInfo, - }, nil) - channelsMock.On("GetAll", ctx).Return([]*db_models.Channel{ - dbChannel, - }, nil) - followMock.On("GetByChannelID", ctx, dbChannel.ID). - Return([]*db_models.Follow{dbFollow}, nil) - twitchMock.On("GetStreamsByUserIds", []string{"1"}).Return([]helix.Stream{ - *newHelixStream, - }, nil) - streamMock.On("GetLatestByChannelID", ctx, dbChannel.ID).Return(dbStream, nil) - streamMock.On("UpdateOneByStreamID", ctx, dbStream.ID, &db.StreamUpdateQuery{ - Title: lo.ToPtr("title1"), - }).Return((*db_models.Stream)(nil), nil) - senderMock. - On("SendMessage", - ctx, - dbChat, - mock.Anything, - ). - Return(nil) - }, - }, - { - name: "stream is still online, we should update title and category", - setupMocks: func() { - newHelixStream := &helix.Stream{ - ID: "123", - GameName: "Dota 3", - Title: "title1", - UserID: "1", - Type: "live", - } - - twitchMock.On("GetChannelsByUserIds", []string{"1"}). - Return([]helix.ChannelInformation{ - *twitchChannelInfo, - }, nil) - channelsMock.On("GetAll", ctx).Return([]*db_models.Channel{ - dbChannel, - }, nil) - followMock.On("GetByChannelID", ctx, dbChannel.ID). - Return([]*db_models.Follow{dbFollow}, nil) - twitchMock.On("GetStreamsByUserIds", []string{"1"}).Return([]helix.Stream{ - *newHelixStream, - }, nil) - streamMock.On("GetLatestByChannelID", ctx, dbChannel.ID).Return(dbStream, nil) - streamMock.On("UpdateOneByStreamID", ctx, dbStream.ID, &db.StreamUpdateQuery{ - Title: lo.ToPtr("title1"), - Category: lo.ToPtr("Dota 3"), - }).Return((*db_models.Stream)(nil), nil) - senderMock. - On("SendMessage", - ctx, - dbChat, - mock.Anything, - ). - Return(nil) - }, - }, - { - name: "we have record in database with some stream, and got new one. We should call send message", - setupMocks: func() { - newHelixStream := &helix.Stream{ - ID: "123456", - GameName: "Dota 2", - Title: "title1", - UserID: "1", - Type: "live", - } - - twitchMock.On("GetChannelsByUserIds", []string{"1"}). - Return([]helix.ChannelInformation{ - *twitchChannelInfo, - }, nil) - channelsMock.On("GetAll", ctx).Return([]*db_models.Channel{ - dbChannel, - }, nil) - followMock.On("GetByChannelID", ctx, dbChannel.ID). - Return([]*db_models.Follow{dbFollow}, nil) - twitchMock.On("GetStreamsByUserIds", []string{"1"}).Return([]helix.Stream{ - *newHelixStream, - }, nil) - streamMock.On("GetLatestByChannelID", ctx, dbChannel.ID). - Return((*db_models.Stream)(nil), nil) - streamMock.On("CreateOneByChannelID", ctx, dbChannel.ID, &db.StreamUpdateQuery{ - StreamID: newHelixStream.ID, - IsLive: lo.ToPtr(true), - Category: lo.ToPtr("Dota 2"), - Title: lo.ToPtr("title1"), - }).Return((*db_models.Stream)(nil), nil) - senderMock. - On("SendMessage", - ctx, - dbChat, - mock.Anything, - ). - Return(nil) - }, - }, - } - - for _, tt := range table { - tt := tt - t.Run(tt.name, func(t *testing.T) { - tt.setupMocks() - - checker := &TwitchStreamChecker{ - services: &types.Services{ - Channel: channelsMock, - Twitch: twitchMock, - Stream: streamMock, - Follow: followMock, - I18N: i18nMock, - }, - sender: senderMock, - } - - checker.check(ctx) - - channelsMock.AssertExpectations(t) - twitchMock.AssertExpectations(t) - senderMock.AssertExpectations(t) - streamMock.AssertExpectations(t) - followMock.AssertExpectations(t) - - channelsMock.ExpectedCalls = nil - twitchMock.ExpectedCalls = nil - streamMock.ExpectedCalls = nil - senderMock.ExpectedCalls = nil - followMock.ExpectedCalls = nil - }) - } -} diff --git a/internal/types/types.go b/internal/types/types.go deleted file mode 100644 index 451a3bd3..00000000 --- a/internal/types/types.go +++ /dev/null @@ -1,20 +0,0 @@ -package types - -import ( - "github.com/satont/twitch-notifier/internal/config" - db2 "github.com/satont/twitch-notifier/internal/db" - "github.com/satont/twitch-notifier/internal/message_sender" - "github.com/satont/twitch-notifier/internal/twitch" - "github.com/satont/twitch-notifier/pkg/i18n" -) - -type Services struct { - Config *config.Config - Twitch twitch.Interface - Chat db2.ChatInterface - Channel db2.ChannelInterface - Follow db2.FollowInterface - Stream db2.StreamInterface - I18N i18n.Interface - MessageSender message_sender.MessageSenderInterface -} diff --git a/migrations/0001_initial.sql b/migrations/0001_initial.sql new file mode 100644 index 00000000..ccd637c8 --- /dev/null +++ b/migrations/0001_initial.sql @@ -0,0 +1,51 @@ +-- Migration number: 0001 2026-03-09T09:43:17.336Z +CREATE TABLE `channels` ( + `id` text PRIMARY KEY NOT NULL, + `channel_id` text NOT NULL, + `service` text DEFAULT 'twitch' NOT NULL, + `is_live` integer DEFAULT false NOT NULL, + `title` text, + `category` text, + `updated_at` text +); +--> statement-breakpoint +CREATE TABLE `chat_settings` ( + `id` text PRIMARY KEY NOT NULL, + `chat_id` text NOT NULL, + `game_change_notification` integer DEFAULT true NOT NULL, + `title_change_notification` integer DEFAULT false NOT NULL, + `game_and_title_change_notification` integer DEFAULT false NOT NULL, + `offline_notification` integer DEFAULT true NOT NULL, + `image_in_notification` integer DEFAULT true NOT NULL, + `language` text DEFAULT 'en' NOT NULL, + FOREIGN KEY (`chat_id`) REFERENCES `chats`(`id`) ON UPDATE no action ON DELETE cascade +); +--> statement-breakpoint +CREATE UNIQUE INDEX `chat_settings_chat_id_unique` ON `chat_settings` (`chat_id`);--> statement-breakpoint +CREATE TABLE `chats` ( + `id` text PRIMARY KEY NOT NULL, + `chat_id` text NOT NULL, + `service` text DEFAULT 'telegram' NOT NULL +); +--> statement-breakpoint +CREATE TABLE `follows` ( + `id` text PRIMARY KEY NOT NULL, + `channel_id` text NOT NULL, + `chat_id` text NOT NULL, + FOREIGN KEY (`channel_id`) REFERENCES `channels`(`id`) ON UPDATE no action ON DELETE cascade, + FOREIGN KEY (`chat_id`) REFERENCES `chats`(`id`) ON UPDATE no action ON DELETE cascade +); +--> statement-breakpoint +CREATE TABLE `streams` ( + `id` text PRIMARY KEY NOT NULL, + `channel_id` text NOT NULL, + `is_live` integer DEFAULT true NOT NULL, + `title` text, + `category` text, + `titles` text DEFAULT '[]' NOT NULL, + `categories` text DEFAULT '[]' NOT NULL, + `started_at` text, + `updated_at` text, + `ended_at` text, + FOREIGN KEY (`channel_id`) REFERENCES `channels`(`id`) ON UPDATE no action ON DELETE cascade +); diff --git a/package.json b/package.json index b40b977a..40111e60 100644 --- a/package.json +++ b/package.json @@ -5,9 +5,11 @@ "description": "Telegram bot for Twitch stream notifications on Cloudflare Workers", "main": "src/index.ts", "scripts": { - "dev": "wrangler dev", + "dev": "npm run db:migrate:local && wrangler dev", "deploy": "wrangler deploy", - "db:generate": "drizzle-kit generate", + "deploy:with-migrations": "./scripts/deploy.sh", + "postdeploy": "npm run db:migrate", + "db:create": "wrangler d1 migrations create", "db:migrate": "wrangler d1 migrations apply twitch-notifier-db", "db:migrate:local": "wrangler d1 migrations apply twitch-notifier-db --local", "db:studio": "drizzle-kit studio" diff --git a/pkg/i18n/helpers.go b/pkg/i18n/helpers.go deleted file mode 100644 index c53fdfef..00000000 --- a/pkg/i18n/helpers.go +++ /dev/null @@ -1,15 +0,0 @@ -package i18n - -func GetNested[T any](v any, keys ...string) (T, bool) { - res := v - for _, key := range keys { - mp, ok := res.(map[string]any) - if !ok { - var e T - return e, false - } - res = mp[key] - } - a, ok := res.(T) - return a, ok -} diff --git a/pkg/i18n/helpers_test.go b/pkg/i18n/helpers_test.go deleted file mode 100644 index f4d0e4e1..00000000 --- a/pkg/i18n/helpers_test.go +++ /dev/null @@ -1,26 +0,0 @@ -package i18n - -import ( - "github.com/stretchr/testify/assert" - "testing" -) - -func TestGetNested(t *testing.T) { - t.Parallel() - - data := map[string]any{ - "foo": "bar", - } - - res, ok := GetNested[string](data, "foo") - assert.True(t, ok, "expected to get a value") - assert.Equal(t, "bar", res, "expected to get a value") - - res, ok = GetNested[string](data, "bar") - assert.False(t, ok, "expected to be false") - assert.Equal(t, "", res, "expected to not get a value") - - res, ok = GetNested[string](nil, "foo") - assert.False(t, ok, "expected to be false") - assert.Equal(t, "", res, "expected to not get a value") -} diff --git a/pkg/i18n/i18n.go b/pkg/i18n/i18n.go deleted file mode 100644 index be5ec86f..00000000 --- a/pkg/i18n/i18n.go +++ /dev/null @@ -1,81 +0,0 @@ -package i18n - -import ( - "encoding/json" - "os" - "path/filepath" - "strings" - "text/template" -) - -type Interface interface { - Translate(key, language string, data map[string]string) string - GetLanguagesCodes() []string -} - -type I18n struct { - translations map[string]map[string]any -} - -var readFile = os.ReadFile -var readDir = os.ReadDir - -func NewI18n(localesPath string) (Interface, error) { - entries, err := os.ReadDir(localesPath) - if err != nil { - return nil, err - } - - translations := make(map[string]map[string]any) - - for _, entry := range entries { - if entry.IsDir() { - continue - } - - name := strings.Replace(entry.Name(), ".json", "", 1) - - fileContent := make(map[string]any) - f, err := readFile(filepath.Join(localesPath, entry.Name())) - if err != nil { - return nil, err - } - err = json.Unmarshal(f, &fileContent) - translations[name] = fileContent - } - - return &I18n{ - translations: translations, - }, nil -} - -func (i *I18n) Translate(key, language string, data map[string]string) string { - if data == nil { - data = make(map[string]string) - } - - str, _ := GetNested[string](i.translations[language], strings.Split(key, ".")...) - if str == "" { - str, _ = GetNested[string](i.translations["en"], strings.Split(key, ".")...) - } - - str = strings.ReplaceAll(str, "{{ ", "{{.") - - tmpl, err := template.New("t").Parse(str) - if err != nil { - return str - } - - res := &strings.Builder{} - _ = tmpl.Execute(res, data) - - return res.String() -} - -func (i *I18n) GetLanguagesCodes() []string { - var codes []string - for code, _ := range i.translations { - codes = append(codes, code) - } - return codes -} diff --git a/pkg/i18n/i18n_test.go b/pkg/i18n/i18n_test.go deleted file mode 100644 index 243429f0..00000000 --- a/pkg/i18n/i18n_test.go +++ /dev/null @@ -1,124 +0,0 @@ -package i18n - -import ( - "os" - "path/filepath" - "testing" - - "github.com/stretchr/testify/assert" -) - -func TestNewI18n(t *testing.T) { - t.Parallel() - - wd, err := os.Getwd() - if err != nil { - t.Fatal(err) - } - - localesPath := filepath.Join(wd, "test_locales") - - table := []struct { - translation string - lang string - data map[string]string - expected string - expectErr bool - localesPath string - patchReadFile bool - patchReadDir bool - }{ - { - translation: "hello", - lang: "en", - data: nil, - expected: "world", - localesPath: localesPath, - }, - { - translation: "nested.templated", - lang: "en", - data: map[string]string{ - "who": "world", - }, - expected: "hello world", - localesPath: localesPath, - }, - { - translation: "templated", - lang: "en", - data: map[string]string{ - "hello": "templated", - }, - expected: "hello templated", - localesPath: localesPath, - }, - { - translation: "expectEmptyString", - lang: "en", - data: nil, - expected: "", - localesPath: localesPath, - }, - { - translation: "expect error", - expectErr: true, - localesPath: "/tmp/somefreakingstupidnotifierlocalespath", - }, - { - translation: "expect readFile error", - expectErr: true, - patchReadFile: true, - }, - { - translation: "expect readDir error", - expectErr: true, - patchReadDir: true, - }, - } - - for _, tt := range table { - t.Run( - tt.translation, func(t *testing.T) { - if tt.patchReadFile { - readFile = func(string) ([]byte, error) { - return nil, os.ErrNotExist - } - defer func() { readFile = os.ReadFile }() - } - - if tt.patchReadDir { - readDir = func(string) ([]os.DirEntry, error) { - return nil, os.ErrNotExist - } - defer func() { readDir = os.ReadDir }() - } - - i18, err := NewI18n(tt.localesPath) - if tt.expectErr { - assert.Error(t, err) - return - } - - assert.Equal( - t, - tt.expected, - i18.Translate(tt.translation, tt.lang, tt.data), - ) - }, - ) - } -} - -func TestGetLanguagesCodes(t *testing.T) { - t.Parallel() - - wd, err := os.Getwd() - if err != nil { - t.Fatal(err) - } - i18, err := NewI18n(filepath.Join(wd, "test_locales")) - - assert.NoError(t, err) - assert.Equal(t, []string{"en"}, i18.GetLanguagesCodes()) -} diff --git a/pkg/i18n/mocks/i18_mock.go b/pkg/i18n/mocks/i18_mock.go deleted file mode 100644 index 2d90f8cd..00000000 --- a/pkg/i18n/mocks/i18_mock.go +++ /dev/null @@ -1,21 +0,0 @@ -package i18nmocks - -import "github.com/stretchr/testify/mock" - -type I18nMock struct { - mock.Mock -} - -func (m *I18nMock) Translate(key, language string, data map[string]string) string { - args := m.Called(key, language, data) - return args.String(0) -} - -func (m *I18nMock) GetLanguagesCodes() []string { - args := m.Called() - return args.Get(0).([]string) -} - -func NewI18nMock() *I18nMock { - return &I18nMock{} -} diff --git a/pkg/i18n/test_locales/en.json b/pkg/i18n/test_locales/en.json deleted file mode 100644 index 14a35c1d..00000000 --- a/pkg/i18n/test_locales/en.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "hello": "world", - "templated": "hello {{ hello }}", - "nested": { - "templated": "hello {{ who }}" - } -} diff --git a/src/bot/commands/callback.handler.ts b/src/bot/commands/callback.handler.ts index 1e6a14b9..81337aff 100644 --- a/src/bot/commands/callback.handler.ts +++ b/src/bot/commands/callback.handler.ts @@ -16,12 +16,15 @@ callbackQueryHandler.on('callback_query:data', async (ctx) => { const chatId = ctx.chat?.id; if (!chatId) return; - const chat = await ctx.services.chatRepo.findByChatId(chatId, 'telegram'); + let chat = await ctx.services.chatRepo.findByChatId(chatId, 'telegram'); if (!chat || !chat.settings) return; // Handle toggle settings if (data.startsWith('toggle_')) { await handleToggleSetting(ctx, data, chat); + // Перезагрузить чат из БД чтобы получить актуальные настройки + chat = await ctx.services.chatRepo.findByChatId(chatId, 'telegram'); + if (!chat) return; await sendSettingsMenu(ctx, chat); } @@ -36,10 +39,22 @@ callbackQueryHandler.on('callback_query:data', async (ctx) => { if (ctx.services.i18n.isValidLocale(lang)) { await ctx.services.chatRepo.updateSettings(chat.settings.id, { language: lang }); ctx.session.language = lang; + + // Обновляем ctx.t() для использования нового языка + ctx.t = (key: string, params?: Record) => { + return ctx.services.i18n.t(lang, key, params); + }; + + // Перезагрузить чат из БД + chat = await ctx.services.chatRepo.findByChatId(chatId, 'telegram'); + if (!chat) return; + await ctx.answerCallbackQuery( ctx.services.i18n.t(lang, 'language.changed') ); - await sendLanguagePicker(ctx); + + // Вернуться в главное меню с новым языком + await sendSettingsMenu(ctx, chat); } } diff --git a/src/bot/helpers.ts b/src/bot/helpers.ts index cce0cd30..6908623b 100644 --- a/src/bot/helpers.ts +++ b/src/bot/helpers.ts @@ -30,7 +30,7 @@ export async function sendSettingsMenu(ctx: BotContext, chat: Chat) { 'toggle_image' ).row() .text( - ctx.t('commands.start.language.button'), + `🌐 ${ctx.t('commands.start.language.button')}`, 'language_picker' ).row() .url('Github', 'https://github.com/Satont/twitch-notifier'); @@ -100,19 +100,60 @@ export async function handleToggleSetting(ctx: BotContext, data: string, chat: C case 'toggle_game_change': updates.gameChangeNotification = !chat.settings.gameChangeNotification; chat.settings.gameChangeNotification = updates.gameChangeNotification; + + // Если включили game change, а title change тоже включен, то включаем game_and_title + if (updates.gameChangeNotification && chat.settings.titleChangeNotification) { + updates.gameAndTitleChangeNotification = true; + chat.settings.gameAndTitleChangeNotification = true; + } + // Если выключили game change, то выключаем game_and_title + if (!updates.gameChangeNotification) { + updates.gameAndTitleChangeNotification = false; + chat.settings.gameAndTitleChangeNotification = false; + } break; + case 'toggle_offline': updates.offlineNotification = !chat.settings.offlineNotification; chat.settings.offlineNotification = updates.offlineNotification; break; + case 'toggle_title_change': updates.titleChangeNotification = !chat.settings.titleChangeNotification; chat.settings.titleChangeNotification = updates.titleChangeNotification; + + // Если включили title change, а game change тоже включен, то включаем game_and_title + if (updates.titleChangeNotification && chat.settings.gameChangeNotification) { + updates.gameAndTitleChangeNotification = true; + chat.settings.gameAndTitleChangeNotification = true; + } + // Если выключили title change, то выключаем game_and_title + if (!updates.titleChangeNotification) { + updates.gameAndTitleChangeNotification = false; + chat.settings.gameAndTitleChangeNotification = false; + } break; + case 'toggle_game_and_title': updates.gameAndTitleChangeNotification = !chat.settings.gameAndTitleChangeNotification; chat.settings.gameAndTitleChangeNotification = updates.gameAndTitleChangeNotification; + + // Если включили game_and_title, включаем оба + if (updates.gameAndTitleChangeNotification) { + updates.gameChangeNotification = true; + updates.titleChangeNotification = true; + chat.settings.gameChangeNotification = true; + chat.settings.titleChangeNotification = true; + } + // Если выключили game_and_title, выключаем оба + else { + updates.gameChangeNotification = false; + updates.titleChangeNotification = false; + chat.settings.gameChangeNotification = false; + chat.settings.titleChangeNotification = false; + } break; + case 'toggle_image': updates.imageInNotification = !chat.settings.imageInNotification; chat.settings.imageInNotification = updates.imageInNotification; diff --git a/src/index.ts b/src/index.ts index 6d719361..e2e0e755 100644 --- a/src/index.ts +++ b/src/index.ts @@ -24,7 +24,7 @@ app.post('/telegram-webhook', async (c) => { const env = c.env; // Create database connection (serverless-agnostic) - const dbClient = drizzle(env.DB); + const dbClient = drizzle(env.twitch_notifier_db); const dbConnection = new CloudflareD1Connection(dbClient); // Create repository factory @@ -69,7 +69,7 @@ app.post('/telegram-webhook', async (c) => { // Twitch EventSub webhook endpoint app.post('/twitch-webhook', async (c) => { const env = c.env; - const db = drizzle(env.DB); + const db = drizzle(env.twitch_notifier_db); return await handleTwitchWebhook(c.req.raw, env, db); }); From 4e5bb55caf807904bce7ff07371999229266575e Mon Sep 17 00:00:00 2001 From: Satont Date: Sat, 14 Mar 2026 10:11:20 +0300 Subject: [PATCH 3/4] upd --- .env.example | 18 +- .github/workflows/docker.yml | 35 ---- .github/workflows/migrations_lint.yml | 30 --- .github/workflows/pr_title_lint.yml | 16 -- .github/workflows/tests.yml | 38 ---- bun.lock | 42 ++-- cmd/main.go | 146 -------------- locales/en.json | 3 +- locales/ru.json | 3 +- locales/uk.json | 3 +- package.json | 8 +- src/bot/commands/callback.handler.ts | 8 +- src/bot/commands/follow.command.ts | 3 +- src/bot/helpers.ts | 11 +- src/bot/index.ts | 6 +- .../drizzle/stream.drizzle.repository.ts | 30 ++- src/index.ts | 14 +- src/services/telegram.service.ts | 4 +- src/utils/thumbnail.ts | 54 +----- src/webhooks/twitch.ts | 182 ++++++++++-------- wrangler.example.toml | 24 +-- 21 files changed, 191 insertions(+), 487 deletions(-) delete mode 100644 .github/workflows/docker.yml delete mode 100644 .github/workflows/migrations_lint.yml delete mode 100644 .github/workflows/pr_title_lint.yml delete mode 100644 .github/workflows/tests.yml delete mode 100644 cmd/main.go diff --git a/.env.example b/.env.example index ad3d4ac1..24dbabac 100644 --- a/.env.example +++ b/.env.example @@ -1,7 +1,11 @@ -# Environment variables template -TELEGRAM_TOKEN=your_telegram_bot_token -TWITCH_CLIENT_ID=your_twitch_client_id -TWITCH_CLIENT_SECRET=your_twitch_client_secret -TELEGRAM_BOT_ADMINS=123456789,987654321 -TWITCH_EVENTSUB_SECRET=your_random_secret_string -BASE_URL=https://your-worker.workers.dev +# Secrets (use wrangler secret put) +APP_ENV = "development" +BASE_URL = "http://localhost:8787" +TELEGRAM_TOKEN = "" +TWITCH_CLIENT_ID = "" +TWITCH_CLIENT_SECRET = "" +TELEGRAM_BOT_ADMINS = "comma-separated user IDs" +TWITCH_EVENTSUB_SECRET = "for webhook verification" + +# BOT INFO FOR SKIP /me REQUEST ON EACH REQUEST +BOT_INFO = """{"id": 1234567890,"is_bot": true,"first_name": "mybot","username": "MyBot","can_join_groups": true,"can_read_all_group_messages": false,"supports_inline_queries": true,"can_connect_to_business": false}""" diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml deleted file mode 100644 index 34252245..00000000 --- a/.github/workflows/docker.yml +++ /dev/null @@ -1,35 +0,0 @@ -name: Docker Image CI - latest - -on: - push: - branches: - - main - workflow_dispatch: - -jobs: - docker: - if: "! contains(toJSON(github.event.commits.*.message), '[skip-docker]')" - runs-on: ubuntu-latest - steps: - - name: Checkout - uses: actions/checkout@v4 - - name: Set up QEMU - uses: docker/setup-qemu-action@v3 - - name: Set up Docker Buildx - uses: docker/setup-buildx-action@v3 - - name: Login to Quay Container Registry - uses: docker/login-action@v3 - with: - registry: quay.io - username: ${{ secrets.QUAY_USERNAME }} - password: ${{ secrets.QUAY_ROBOT_TOKEN }} - - name: Build and push - uses: docker/build-push-action@v2 - with: - context: . - push: true - tags: | - quay.io/satont/twitch-notifier:latest - quay.io/satont/twitch-notifier:${{ github.sha }} - cache-from: type=gha - cache-to: type=gha,mode=max diff --git a/.github/workflows/migrations_lint.yml b/.github/workflows/migrations_lint.yml deleted file mode 100644 index 6bdb7a54..00000000 --- a/.github/workflows/migrations_lint.yml +++ /dev/null @@ -1,30 +0,0 @@ -name: Migrations lint - -on: - pull_request: - -jobs: - lint: - services: - postgres: - image: postgres:15 - env: - POSTGRES_DB: test - POSTGRES_PASSWORD: pass - ports: - - 5432:5432 - options: >- - --health-cmd pg_isready - --health-interval 10s - --health-timeout 5s - --health-retries 5 - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v3.0.1 - with: - fetch-depth: 0 - - uses: ariga/atlas-action@v0 - with: - dir: ent/migrate/migrations - dir-format: atlas - dev-url: postgres://postgres:pass@localhost:5432/test?sslmode=disable diff --git a/.github/workflows/pr_title_lint.yml b/.github/workflows/pr_title_lint.yml deleted file mode 100644 index 92933635..00000000 --- a/.github/workflows/pr_title_lint.yml +++ /dev/null @@ -1,16 +0,0 @@ -name: PR Title Lint - -on: - pull_request_target: - types: - - opened - - edited - - synchronize - -jobs: - pr_title_lint: - runs-on: ubuntu-latest - steps: - - uses: amannn/action-semantic-pull-request@v5 - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml deleted file mode 100644 index 5964f65e..00000000 --- a/.github/workflows/tests.yml +++ /dev/null @@ -1,38 +0,0 @@ -name: Tests - -on: - push: - branches: - - main - pull_request: - -jobs: - build: - runs-on: ubuntu-latest - strategy: - matrix: - go: - - 1.21.x - - 1.20.x - - 1.19.x - name: Test with Go v${{ matrix.go }} - steps: - - uses: actions/checkout@v2 - - name: Setup go - uses: actions/setup-go@v4 - with: - go-version: ${{ matrix.go }} - - name: Intall goveralls - run: | - go install github.com/mattn/goveralls@latest - - name: Generate ent - run: | - make generate - - name: Test - run: | - make tests - - name: Send coverage - env: - COVERALLS_TOKEN: ${{ secrets.GITHUB_TOKEN }} - run: | - goveralls -coverprofile=coverage.out -service=github diff --git a/bun.lock b/bun.lock index 76ef1789..064a7465 100644 --- a/bun.lock +++ b/bun.lock @@ -6,39 +6,41 @@ "name": "twitch-notifier", "dependencies": { "@grammyjs/conversations": "2.1.1", - "@grammyjs/i18n": "1.1.2", "@twurple/api": "8.0.3", "@twurple/auth": "8.0.3", "@twurple/eventsub-http": "8.0.3", "drizzle-orm": "0.45.1", "grammy": "1.41.1", "hono": "^4.7.11", + "i18next": "25.8.14", }, "devDependencies": { - "@cloudflare/workers-types": "4.20260307.1", + "@cloudflare/workers-types": "4.20260313.1", "@types/node": "^22.10.6", "drizzle-kit": "0.31.9", "typescript": "^5.7.3", - "wrangler": "4.71.0", + "wrangler": "4.73.0", }, }, }, "packages": { + "@babel/runtime": ["@babel/runtime@7.28.6", "", {}, "sha512-05WQkdpL9COIMz4LjTxGpPNCdlpyimKppYNoJ5Di5EUObifl8t4tuLuUBBZEpoLYOmfvIWrsp9fCl0HoPRVTdA=="], + "@cloudflare/kv-asset-handler": ["@cloudflare/kv-asset-handler@0.4.2", "", {}, "sha512-SIOD2DxrRRwQ+jgzlXCqoEFiKOFqaPjhnNTGKXSRLvp1HiOvapLaFG2kEr9dYQTYe8rKrd9uvDUzmAITeNyaHQ=="], "@cloudflare/unenv-preset": ["@cloudflare/unenv-preset@2.15.0", "", { "peerDependencies": { "unenv": "2.0.0-rc.24", "workerd": "1.20260301.1 || ~1.20260302.1 || ~1.20260303.1 || ~1.20260304.1 || >1.20260305.0 <2.0.0-0" }, "optionalPeers": ["workerd"] }, "sha512-EGYmJaGZKWl+X8tXxcnx4v2bOZSjQeNI5dWFeXivgX9+YCT69AkzHHwlNbVpqtEUTbew8eQurpyOpeN8fg00nw=="], - "@cloudflare/workerd-darwin-64": ["@cloudflare/workerd-darwin-64@1.20260301.1", "", { "os": "darwin", "cpu": "x64" }, "sha512-+kJvwociLrvy1JV9BAvoSVsMEIYD982CpFmo/yMEvBwxDIjltYsLTE8DLi0mCkGsQ8Ygidv2fD9wavzXeiY7OQ=="], + "@cloudflare/workerd-darwin-64": ["@cloudflare/workerd-darwin-64@1.20260312.1", "", { "os": "darwin", "cpu": "x64" }, "sha512-HUAtDWaqUduS6yasV6+NgsK7qBpP1qGU49ow/Wb117IHjYp+PZPUGReDYocpB4GOMRoQlvdd4L487iFxzdARpw=="], - "@cloudflare/workerd-darwin-arm64": ["@cloudflare/workerd-darwin-arm64@1.20260301.1", "", { "os": "darwin", "cpu": "arm64" }, "sha512-PPIetY3e67YBr9O4UhILK8nbm5TqUDl14qx4rwFNrRSBOvlzuczzbd4BqgpAtbGVFxKp1PWpjAnBvGU/OI/tLQ=="], + "@cloudflare/workerd-darwin-arm64": ["@cloudflare/workerd-darwin-arm64@1.20260312.1", "", { "os": "darwin", "cpu": "arm64" }, "sha512-DOn7TPTHSxJYfi4m4NYga/j32wOTqvJf/pY4Txz5SDKWIZHSTXFyGz2K4B+thoPWLop/KZxGoyTv7db0mk/qyw=="], - "@cloudflare/workerd-linux-64": ["@cloudflare/workerd-linux-64@1.20260301.1", "", { "os": "linux", "cpu": "x64" }, "sha512-Gu5vaVTZuYl3cHa+u5CDzSVDBvSkfNyuAHi6Mdfut7TTUdcb3V5CIcR/mXRSyMXzEy9YxEWIfdKMxOMBjupvYQ=="], + "@cloudflare/workerd-linux-64": ["@cloudflare/workerd-linux-64@1.20260312.1", "", { "os": "linux", "cpu": "x64" }, "sha512-TdkIh3WzPXYHuvz7phAtFEEvAxvFd30tHrm4gsgpw0R0F5b8PtoM3hfL2uY7EcBBWVYUBtkY2ahDYFfufnXw/g=="], - "@cloudflare/workerd-linux-arm64": ["@cloudflare/workerd-linux-arm64@1.20260301.1", "", { "os": "linux", "cpu": "arm64" }, "sha512-igL1pkyCXW6GiGpjdOAvqMi87UW0LMc/+yIQe/CSzuZJm5GzXoAMrwVTkCFnikk6JVGELrM5x0tGYlxa0sk5Iw=="], + "@cloudflare/workerd-linux-arm64": ["@cloudflare/workerd-linux-arm64@1.20260312.1", "", { "os": "linux", "cpu": "arm64" }, "sha512-kNauZhL569Iy94t844OMwa1zP6zKFiL3xiJ4tGLS+TFTEfZ3pZsRH6lWWOtkXkjTyCmBEOog0HSEKjIV4oAffw=="], - "@cloudflare/workerd-windows-64": ["@cloudflare/workerd-windows-64@1.20260301.1", "", { "os": "win32", "cpu": "x64" }, "sha512-Q0wMJ4kcujXILwQKQFc1jaYamVsNvjuECzvRrTI8OxGFMx2yq9aOsswViE4X1gaS2YQQ5u0JGwuGi5WdT1Lt7A=="], + "@cloudflare/workerd-windows-64": ["@cloudflare/workerd-windows-64@1.20260312.1", "", { "os": "win32", "cpu": "x64" }, "sha512-5dBrlSK+nMsZy5bYQpj8t9iiQNvCRlkm9GGvswJa9vVU/1BNO4BhJMlqOLWT24EmFyApZ+kaBiPJMV8847NDTg=="], - "@cloudflare/workers-types": ["@cloudflare/workers-types@4.20260307.1", "", {}, "sha512-0PvWLVVD6Q64V/XhollYtc8H35Vxm2rZi8bkZbEr3lK+mNgd2FBBVhlZ6A3saAUq3giRF4US/UfU/3a8i1PEcg=="], + "@cloudflare/workers-types": ["@cloudflare/workers-types@4.20260313.1", "", {}, "sha512-jMEeX3RKfOSVqqXRKr/ulgglcTloeMzSH3FdzIfqJHtvc12/ELKd5Ldsg8ZHahKX/4eRxYdw3kbzb8jLXbq/jQ=="], "@cspotcode/source-map-support": ["@cspotcode/source-map-support@0.8.1", "", { "dependencies": { "@jridgewell/trace-mapping": "0.3.9" } }, "sha512-IchNf6dN4tHoMFIn/7OE8LWZ19Y6q/67Bmf6vnGREv8RSbBVb9LPJxEcnwrcwX6ixSvaiGoomAUvu4YSxXrVgw=="], @@ -54,10 +56,6 @@ "@d-fischer/typed-event-emitter": ["@d-fischer/typed-event-emitter@3.3.3", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-OvSEOa8icfdWDqcRtjSEZtgJTFOFNgTjje7zaL0+nAtu2/kZtRCSK5wUMrI/aXtCH8o0Qz2vA8UqkhWUTARFQQ=="], - "@deno/shim-deno": ["@deno/shim-deno@0.18.2", "", { "dependencies": { "@deno/shim-deno-test": "^0.5.0", "which": "^4.0.0" } }, "sha512-oQ0CVmOio63wlhwQF75zA4ioolPvOwAoK0yuzcS5bDC1JUvH3y1GS8xPh8EOpcoDQRU4FTG8OQfxhpR+c6DrzA=="], - - "@deno/shim-deno-test": ["@deno/shim-deno-test@0.5.0", "", {}, "sha512-4nMhecpGlPi0cSzT67L+Tm+GOJqvuk8gqHBziqcUQOarnuIax1z96/gJHCSIz2Z0zhxE6Rzwb3IZXPtFh51j+w=="], - "@drizzle-team/brocli": ["@drizzle-team/brocli@0.10.2", "", {}, "sha512-z33Il7l5dKjUgGULTqBsQBQwckHh5AbIuxhdsIxDDiZAzBOrZO6q9ogcWC65kU382AfynTfgNumVcNIjuIua6w=="], "@emnapi/runtime": ["@emnapi/runtime@1.8.1", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-mehfKSMWjjNol8659Z8KxEMrdSJDDot5SXMq00dM8BN4o+CLNXQ0xH2V7EchNHV4RmbZLmmPdEaXZc5H2FXmDg=="], @@ -118,14 +116,8 @@ "@esbuild/win32-x64": ["@esbuild/win32-x64@0.25.12", "", { "os": "win32", "cpu": "x64" }, "sha512-alJC0uCZpTFrSL0CCDjcgleBXPnCrEAhTBILpeAp7M/OFgoqtAetfBzX0xM00MUsVVPpVjlPuMbREqnZCXaTnA=="], - "@fluent/bundle": ["@fluent/bundle@0.17.1", "", {}, "sha512-CRFNT9QcSFAeFDneTF59eyv3JXFGhIIN4boUO2y22YmsuuKLyDk+N1I/NQUYz9Ab63e6V7T6vItoZIG/2oOOuw=="], - - "@fluent/langneg": ["@fluent/langneg@0.6.2", "", {}, "sha512-YF4gZ4sLYRQfctpUR2uhb5UyPUYY5n/bi3OaED/Q4awKjPjlaF8tInO3uja7pnLQcmLTURkZL7L9zxv2Z5NDwg=="], - "@grammyjs/conversations": ["@grammyjs/conversations@2.1.1", "", { "peerDependencies": { "grammy": "^1.20.1" } }, "sha512-hoxqwSkaXDeU7mzXulpk3A4Cmd6UZO3HU4aPoITX5ekSHK7ZcUEmMl7RhKKkqw3z6zVbbAShQreJoVV5/dDSLA=="], - "@grammyjs/i18n": ["@grammyjs/i18n@1.1.2", "", { "dependencies": { "@deno/shim-deno": "~0.18.0", "@fluent/bundle": "^0.17.1", "@fluent/langneg": "^0.6.2" }, "peerDependencies": { "grammy": "^1.10.0" } }, "sha512-PcK06mxuDDZjxdZ5HywBhr+erEITsR816KP4DNIDDds1jpA45pfz/nS9FdZmzF8H6lMyPix3mV5WL1rT4q+BuA=="], - "@grammyjs/types": ["@grammyjs/types@3.25.0", "", {}, "sha512-iN9i5p+8ZOu9OMxWNcguojQfz4K/PDyMPOnL7PPCON+SoA/F8OKMH3uR7CVUkYfdNe0GCz8QOzAWrnqusQYFOg=="], "@img/colour": ["@img/colour@1.1.0", "", {}, "sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ=="], @@ -256,17 +248,17 @@ "httpanda": ["httpanda@0.4.7", "", { "dependencies": { "@types/node": "^14.11.2", "tslib": "^2.0.3" } }, "sha512-NieTiR7kfOheL9OeEi6+JKFmJ2JP9ZRqUQ4tiXZ9J+EMMKxApHUQlEM5l4gZ+l67lxE9Er6oigZnujmhlodNCg=="], + "i18next": ["i18next@25.8.14", "", { "dependencies": { "@babel/runtime": "^7.28.4" }, "peerDependencies": { "typescript": "^5" }, "optionalPeers": ["typescript"] }, "sha512-paMUYkfWJMsWPeE/Hejcw+XLhHrQPehem+4wMo+uELnvIwvCG019L9sAIljwjCmEMtFQQO3YeitJY8Kctei3iA=="], + "iconv-lite": ["iconv-lite@0.7.2", "", { "dependencies": { "safer-buffer": ">= 2.1.2 < 3.0.0" } }, "sha512-im9DjEDQ55s9fL4EYzOAv0yMqmMBSZp6G0VvFyTMPKWxiSBHUj9NW/qqLmXUwXrrM7AvqSlTCfvqRb0cM8yYqw=="], "inherits": ["inherits@2.0.4", "", {}, "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ=="], - "isexe": ["isexe@3.1.5", "", {}, "sha512-6B3tLtFqtQS4ekarvLVMZ+X+VlvQekbe4taUkf/rhVO3d/h0M2rfARm/pXLcPEsjjMsFgrFgSrhQIxcSVrBz8w=="], - "kleur": ["kleur@4.1.5", "", {}, "sha512-o+NO+8WrRiQEE4/7nwRJhN1HWpVmJm511pBHUxPLtp0BUISzlBplORYSmTclCnJvQq2tKu/sgl3xVpkc7ZWuQQ=="], "klona": ["klona@2.0.6", "", {}, "sha512-dhG34DXATL5hSxJbIexCft8FChFXtmskoZYnoPWjXQuebWYCNkVeV3KkGegCK9CP1oswI/vQibS2GY7Em/sJJA=="], - "miniflare": ["miniflare@4.20260301.1", "", { "dependencies": { "@cspotcode/source-map-support": "0.8.1", "sharp": "^0.34.5", "undici": "7.18.2", "workerd": "1.20260301.1", "ws": "8.18.0", "youch": "4.1.0-beta.10" }, "bin": { "miniflare": "bootstrap.js" } }, "sha512-fqkHx0QMKswRH9uqQQQOU/RoaS3Wjckxy3CUX3YGJr0ZIMu7ObvI+NovdYi6RIsSPthNtq+3TPmRNxjeRiasog=="], + "miniflare": ["miniflare@4.20260312.0", "", { "dependencies": { "@cspotcode/source-map-support": "0.8.1", "sharp": "^0.34.5", "undici": "7.18.2", "workerd": "1.20260312.1", "ws": "8.18.0", "youch": "4.1.0-beta.10" }, "bin": { "miniflare": "bootstrap.js" } }, "sha512-pieP2rfXynPT6VRINYaiHe/tfMJ4c5OIhqRlIdLF6iZ9g5xgpEmvimvIgMpgAdDJuFlrLcwDUi8MfAo2R6dt/w=="], "ms": ["ms@2.1.3", "", {}, "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="], @@ -318,11 +310,9 @@ "whatwg-url": ["whatwg-url@5.0.0", "", { "dependencies": { "tr46": "~0.0.3", "webidl-conversions": "^3.0.0" } }, "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw=="], - "which": ["which@4.0.0", "", { "dependencies": { "isexe": "^3.1.1" }, "bin": { "node-which": "bin/which.js" } }, "sha512-GlaYyEb07DPxYCKhKzplCWBJtvxZcZMrL+4UkrTSJHHPyZU4mYYTv3qaOe77H7EODLSSopAUFAc6W8U4yqvscg=="], - - "workerd": ["workerd@1.20260301.1", "", { "optionalDependencies": { "@cloudflare/workerd-darwin-64": "1.20260301.1", "@cloudflare/workerd-darwin-arm64": "1.20260301.1", "@cloudflare/workerd-linux-64": "1.20260301.1", "@cloudflare/workerd-linux-arm64": "1.20260301.1", "@cloudflare/workerd-windows-64": "1.20260301.1" }, "bin": { "workerd": "bin/workerd" } }, "sha512-oterQ1IFd3h7PjCfT4znSFOkJCvNQ6YMOyZ40YsnO3nrSpgB4TbJVYWFOnyJAw71/RQuupfVqZZWKvsy8GO3fw=="], + "workerd": ["workerd@1.20260312.1", "", { "optionalDependencies": { "@cloudflare/workerd-darwin-64": "1.20260312.1", "@cloudflare/workerd-darwin-arm64": "1.20260312.1", "@cloudflare/workerd-linux-64": "1.20260312.1", "@cloudflare/workerd-linux-arm64": "1.20260312.1", "@cloudflare/workerd-windows-64": "1.20260312.1" }, "bin": { "workerd": "bin/workerd" } }, "sha512-nNpPkw9jaqo79B+iBCOiksx+N62xC+ETIfyzofUEdY3cSOHJg6oNnVSHm7vHevzVblfV76c8Gr0cXHEapYMBEg=="], - "wrangler": ["wrangler@4.71.0", "", { "dependencies": { "@cloudflare/kv-asset-handler": "0.4.2", "@cloudflare/unenv-preset": "2.15.0", "blake3-wasm": "2.1.5", "esbuild": "0.27.3", "miniflare": "4.20260301.1", "path-to-regexp": "6.3.0", "unenv": "2.0.0-rc.24", "workerd": "1.20260301.1" }, "optionalDependencies": { "fsevents": "~2.3.2" }, "peerDependencies": { "@cloudflare/workers-types": "^4.20260226.1" }, "optionalPeers": ["@cloudflare/workers-types"], "bin": { "wrangler": "bin/wrangler.js", "wrangler2": "bin/wrangler.js" } }, "sha512-j6pSGAncOLNQDRzqtp0EqzYj52CldDP7uz/C9cxVrIgqa5p+cc0b4pIwnapZZAGv9E1Loa3tmPD0aXonH7KTkw=="], + "wrangler": ["wrangler@4.73.0", "", { "dependencies": { "@cloudflare/kv-asset-handler": "0.4.2", "@cloudflare/unenv-preset": "2.15.0", "blake3-wasm": "2.1.5", "esbuild": "0.27.3", "miniflare": "4.20260312.0", "path-to-regexp": "6.3.0", "unenv": "2.0.0-rc.24", "workerd": "1.20260312.1" }, "optionalDependencies": { "fsevents": "~2.3.2" }, "peerDependencies": { "@cloudflare/workers-types": "^4.20260312.1" }, "optionalPeers": ["@cloudflare/workers-types"], "bin": { "wrangler": "bin/wrangler.js", "wrangler2": "bin/wrangler.js" } }, "sha512-VJXsqKDFCp6OtFEHXITSOR5kh95JOknwPY8m7RyQuWJQguSybJy43m4vhoCSt42prutTef7eeuw7L4V4xiynGw=="], "ws": ["ws@8.18.0", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-8VbfWfHLbbwu3+N6OKsOMpBdT4kXPDDB9cJk2bJ6mh9ucxdlnNvH1e+roYkKmN9Nxw2yjz7VzeO9oOz2zJ04Pw=="], diff --git a/cmd/main.go b/cmd/main.go deleted file mode 100644 index 1d2b9030..00000000 --- a/cmd/main.go +++ /dev/null @@ -1,146 +0,0 @@ -package main - -import ( - "context" - "log" - "os" - "os/signal" - "path/filepath" - "syscall" - "time" - - "github.com/getsentry/sentry-go" - - "entgo.io/ent/dialect/sql" - "github.com/TheZeroSlave/zapsentry" - "github.com/lib/pq" - "github.com/satont/twitch-notifier/ent" - "github.com/satont/twitch-notifier/internal/config" - "github.com/satont/twitch-notifier/internal/db" - "github.com/satont/twitch-notifier/internal/message_sender" - "github.com/satont/twitch-notifier/internal/telegram" - "github.com/satont/twitch-notifier/internal/twitch" - "github.com/satont/twitch-notifier/internal/twitch_streams_cheker" - "github.com/satont/twitch-notifier/internal/types" - "github.com/satont/twitch-notifier/pkg/i18n" - "go.uber.org/zap" - "go.uber.org/zap/zapcore" -) - -func createEnt(cfg *config.Config) (*ent.Client, error) { - pgConnectionUrl, err := pq.ParseURL(cfg.DatabaseUrl) - if err != nil { - log.Fatalln(err) - } - - drv, err := sql.Open("postgres", pgConnectionUrl) - if err != nil { - return nil, err - } - - db := drv.DB() - db.SetMaxIdleConns(2) - db.SetMaxOpenConns(10) - db.SetConnMaxLifetime(time.Hour) - return ent.NewClient(ent.Driver(drv)), nil -} - -func main() { - wd, err := os.Getwd() - if err != nil { - log.Fatalln(err) - } - - cfg, err := config.NewConfig(nil) - if err != nil { - log.Fatalln(err) - } - - logger, _ := zap.NewDevelopment() - - if cfg.SentryDsn != "" { - sentryClient, err := sentry.NewClient( - sentry.ClientOptions{ - Dsn: cfg.SentryDsn, - EnableTracing: true, - }, - ) - if err != nil { - log.Fatalln(err) - } - logger = modifyToSentryLogger(logger, sentryClient) - defer sentry.Flush(2 * time.Second) - } - - zap.ReplaceGlobals(logger) - - client, err := createEnt(cfg) - if err != nil { - logger.Sugar().Fatalln("failed opening connection to postgres: %v", err) - } - // Run the auto migration tool. - // if err := client.Schema.Create(context.Background()); err != nil { - // log.Fatalf("failed creating schema resources: %v", err) - // } - - twitchService, err := twitch.NewTwitchService(cfg.TwitchClientId, cfg.TwitchClientSecret) - if err != nil { - logger.Sugar().Fatalln(err) - } - - i18, err := i18n.NewI18n(filepath.Join(wd, "locales")) - if err != nil { - logger.Sugar().Fatalln(err) - } - - services := &types.Services{ - Config: cfg, - Twitch: twitchService, - Chat: db.NewChatEntRepository(client), - Channel: db.NewChannelEntService(client), - Follow: db.NewFollowService(client), - Stream: db.NewStreamEntService(client), - I18N: i18, - } - - ctx, cancel := context.WithCancel(context.Background()) - - tg := telegram.NewTelegram(ctx, cfg.TelegramToken, services) - tg.StartPolling(ctx) - - sender := message_sender.NewMessageSender(tg.Client) - - checker := twitch_streams_cheker.NewTwitchStreamChecker(services, sender, nil) - checker.StartPolling(ctx) - - logger.Sugar().Info("Started") - exitSignal := make(chan os.Signal, 1) - signal.Notify(exitSignal, syscall.SIGINT, syscall.SIGTERM) - <-exitSignal - logger.Sugar().Info("Closing...") - cancel() - _ = client.Close() -} - -func modifyToSentryLogger(log *zap.Logger, client *sentry.Client) *zap.Logger { - cfg := zapsentry.Configuration{ - Level: zapcore.ErrorLevel, // when to send message to sentry - EnableBreadcrumbs: true, // enable sending breadcrumbs to Sentry - BreadcrumbLevel: zapcore.InfoLevel, // at what level should we sent breadcrumbs to sentry - Tags: map[string]string{ - "component": "system", - }, - } - core, err := zapsentry.NewCore(cfg, zapsentry.NewSentryClientFromClient(client)) - - // in case of err it will return noop core. so we can safely attach it - if err != nil { - log.Warn("failed to init zap", zap.Error(err)) - } - - log = zapsentry.AttachCoreToLogger(core, log) - - // to use breadcrumbs feature - create new scope explicitly - // and attach after attaching the core - return log.With(zapsentry.NewScope()) -} diff --git a/locales/en.json b/locales/en.json index 24d3ea04..c7d5efdc 100644 --- a/locales/en.json +++ b/locales/en.json @@ -2,7 +2,8 @@ "language": { "name": "English", "changed": "Language is set to english.", - "emoji": "🇬🇧" + "emoji": "🇬🇧", + "select": "Please select your language:" }, "bot": { diff --git a/locales/ru.json b/locales/ru.json index 085bccf9..a7e54405 100644 --- a/locales/ru.json +++ b/locales/ru.json @@ -2,7 +2,8 @@ "language": { "name": "Русский", "changed": "Язык установлен на русский.", - "emoji": "🇷🇺" + "emoji": "🇷🇺", + "select": "Пожалуйста, выберите ваш язык:" }, "bot": { "description": "Здравствуйте! Я буду уведомлять вас о начале трансляций Twitch." diff --git a/locales/uk.json b/locales/uk.json index e144e844..13219db7 100644 --- a/locales/uk.json +++ b/locales/uk.json @@ -2,7 +2,8 @@ "language": { "name": "Українська", "changed": "Мова змінена на українську.", - "emoji": "🇺🇦" + "emoji": "🇺🇦", + "select": "Будь ласка, оберіть вашу мову:" }, "bot": { "description": "Здраствуйте! Я буду сповіщати вас про початок Twitch трансляцій." diff --git a/package.json b/package.json index 40111e60..05d4d394 100644 --- a/package.json +++ b/package.json @@ -5,10 +5,10 @@ "description": "Telegram bot for Twitch stream notifications on Cloudflare Workers", "main": "src/index.ts", "scripts": { - "dev": "npm run db:migrate:local && wrangler dev", + "dev": "bun run db:migrate:local && wrangler dev", "deploy": "wrangler deploy", "deploy:with-migrations": "./scripts/deploy.sh", - "postdeploy": "npm run db:migrate", + "postdeploy": "bun run db:migrate", "db:create": "wrangler d1 migrations create", "db:migrate": "wrangler d1 migrations apply twitch-notifier-db", "db:migrate:local": "wrangler d1 migrations apply twitch-notifier-db --local", @@ -33,10 +33,10 @@ "i18next": "25.8.14" }, "devDependencies": { - "@cloudflare/workers-types": "4.20260307.1", + "@cloudflare/workers-types": "4.20260313.1", "@types/node": "^22.10.6", "drizzle-kit": "0.31.9", "typescript": "^5.7.3", - "wrangler": "4.71.0" + "wrangler": "4.73.0" } } diff --git a/src/bot/commands/callback.handler.ts b/src/bot/commands/callback.handler.ts index 81337aff..ac116206 100644 --- a/src/bot/commands/callback.handler.ts +++ b/src/bot/commands/callback.handler.ts @@ -21,11 +21,15 @@ callbackQueryHandler.on('callback_query:data', async (ctx) => { // Handle toggle settings if (data.startsWith('toggle_')) { + // Сразу отвечаем на callback, чтобы не было timeout + await ctx.answerCallbackQuery(); + await handleToggleSetting(ctx, data, chat); // Перезагрузить чат из БД чтобы получить актуальные настройки chat = await ctx.services.chatRepo.findByChatId(chatId, 'telegram'); if (!chat) return; await sendSettingsMenu(ctx, chat); + return; // Важно! Выходим, чтобы не вызывать answerCallbackQuery дважды } // Handle language picker @@ -37,7 +41,7 @@ callbackQueryHandler.on('callback_query:data', async (ctx) => { else if (data.startsWith('language_picker_set_')) { const lang = data.replace('language_picker_set_', '') as SupportedLanguage; if (ctx.services.i18n.isValidLocale(lang)) { - await ctx.services.chatRepo.updateSettings(chat.settings.id, { language: lang }); + await ctx.services.chatRepo.updateSettings(chat.id, { language: lang }); ctx.session.language = lang; // Обновляем ctx.t() для использования нового языка @@ -55,6 +59,7 @@ callbackQueryHandler.on('callback_query:data', async (ctx) => { // Вернуться в главное меню с новым языком await sendSettingsMenu(ctx, chat); + return; // Важно! Выходим, чтобы не вызывать answerCallbackQuery дважды } } @@ -67,6 +72,7 @@ callbackQueryHandler.on('callback_query:data', async (ctx) => { else if (data.startsWith('channels_unfollow_')) { const channelId = data.replace('channels_unfollow_', ''); await handleUnfollow(ctx, chat, channelId); + return; // handleUnfollow уже вызывает answerCallbackQuery } // Handle pagination diff --git a/src/bot/commands/follow.command.ts b/src/bot/commands/follow.command.ts index b1ea7945..88450528 100644 --- a/src/bot/commands/follow.command.ts +++ b/src/bot/commands/follow.command.ts @@ -100,7 +100,8 @@ async function handleFollow(ctx: BotContext, text: string) { ) ); } catch (error: any) { - if (error.message?.includes('UNIQUE constraint failed')) { + // Check if it's FollowAlreadyExistsError by checking error name or message + if (error.constructor.name === 'FollowAlreadyExistsError' || error.message === 'Follow already exists') { results.push( ctx.t( 'commands.follow.errors.alreadyFollowed', diff --git a/src/bot/helpers.ts b/src/bot/helpers.ts index 6908623b..df8d82eb 100644 --- a/src/bot/helpers.ts +++ b/src/bot/helpers.ts @@ -38,7 +38,14 @@ export async function sendSettingsMenu(ctx: BotContext, chat: Chat) { const description = ctx.t('bot.description'); if (ctx.callbackQuery) { - await ctx.editMessageText(description, { reply_markup: keyboard }); + try { + await ctx.editMessageText(description, { reply_markup: keyboard }); + } catch (error: any) { + // Игнорируем ошибку "message is not modified" + if (!error?.message?.includes('message is not modified')) { + throw error; + } + } } else { await ctx.reply(description, { reply_markup: keyboard }); } @@ -161,7 +168,7 @@ export async function handleToggleSetting(ctx: BotContext, data: string, chat: C } if (Object.keys(updates).length > 0) { - await ctx.services.chatRepo.updateSettings(chat.settings.id, updates); + await ctx.services.chatRepo.updateSettings(chat.id, updates); } } diff --git a/src/bot/index.ts b/src/bot/index.ts index 3a663672..686e5c58 100644 --- a/src/bot/index.ts +++ b/src/bot/index.ts @@ -29,7 +29,11 @@ export function createBot( sessionRepo: ISessionRepository; } ): Bot { - const bot = new Bot(env.TELEGRAM_TOKEN); + const bot = new Bot(env.TELEGRAM_TOKEN, { + client: { + timeoutSeconds: 60, // Увеличиваем timeout до 60 секунд + }, + }); // Use database session storage const sessionStorage = new DatabaseSessionStorage( diff --git a/src/db/repositories/drizzle/stream.drizzle.repository.ts b/src/db/repositories/drizzle/stream.drizzle.repository.ts index 1db49c8f..6bc2cc0a 100644 --- a/src/db/repositories/drizzle/stream.drizzle.repository.ts +++ b/src/db/repositories/drizzle/stream.drizzle.repository.ts @@ -20,16 +20,26 @@ export class StreamDrizzleRepository implements IStreamRepository { } async create(id: string, channelId: string, category: string, title: string): Promise { - await this.db.insert(streams).values({ - id, - channelId, - isLive: true, - category, - title, - startedAt: new Date().toISOString(), - titles: [title] as any, - categories: [category] as any, - }); + try { + await this.db.insert(streams).values({ + id, + channelId, + isLive: true, + category, + title, + startedAt: new Date().toISOString(), + titles: [title] as any, + categories: [category] as any, + }); + } catch (error: any) { + // If the stream already exists (duplicate webhook), just return the id + if (error?.message?.includes('UNIQUE constraint failed') || + error?.message?.includes('already exists')) { + console.log(`Stream ${id} already exists, skipping insert`); + return id; + } + throw error; + } return id; } diff --git a/src/index.ts b/src/index.ts index e2e0e755..3df2c98c 100644 --- a/src/index.ts +++ b/src/index.ts @@ -3,10 +3,12 @@ import { webhookCallback } from 'grammy'; import { drizzle } from 'drizzle-orm/d1'; import type { Env } from './types'; import { createBot } from './bot'; -import { I18nService } from './services/i18n.service'; -import { TwitchService } from './services/twitch.service'; -import { TelegramService } from './services/telegram.service'; -import { EventSubService } from './services/eventsub.service'; +import { + TelegramService, + I18nService, + TwitchService, + EventSubService, +} from '~/services'; import { CloudflareD1Connection } from './db/connection'; import { DrizzleRepositoryFactory } from './db/repository.factory'; import { CloudflareKVSessionRepository } from './db/repositories/cloudflare-kv'; @@ -71,7 +73,9 @@ app.post('/twitch-webhook', async (c) => { const env = c.env; const db = drizzle(env.twitch_notifier_db); - return await handleTwitchWebhook(c.req.raw, env, db); + return await handleTwitchWebhook(c.req.raw, env, db, c.executionCtx); }); +console.log('App initialized'); + export default app; diff --git a/src/services/telegram.service.ts b/src/services/telegram.service.ts index 60b0a294..8401f0f1 100644 --- a/src/services/telegram.service.ts +++ b/src/services/telegram.service.ts @@ -58,7 +58,7 @@ export class TelegramService { private thumbnailBuilder: ThumbnailBuilder; constructor(env: Env, i18n: I18nService) { - this.bot = new Bot(env.TELEGRAM_TOKEN); + this.bot = new Bot(env.TELEGRAM_TOKEN, { client: { timeoutSeconds: 60 } }); this.i18n = i18n; this.thumbnailBuilder = new ThumbnailBuilder(); } @@ -74,7 +74,7 @@ export class TelegramService { if (notification.showImage && notification.thumbnailUrl) { try { - const thumbnailUrl = await this.thumbnailBuilder.build(notification.thumbnailUrl, true); + const thumbnailUrl = this.thumbnailBuilder.build(notification.thumbnailUrl); await this.bot.api.sendPhoto(notification.chatId, new InputFile(new URL(thumbnailUrl)), { caption: text, parse_mode: 'HTML', diff --git a/src/utils/thumbnail.ts b/src/utils/thumbnail.ts index 8589eef5..a0f783be 100644 --- a/src/utils/thumbnail.ts +++ b/src/utils/thumbnail.ts @@ -2,61 +2,11 @@ export class ThumbnailBuilder { /** * Build thumbnail URL from Twitch template URL * @param thumbnailUrl - Twitch thumbnail URL with {width} and {height} placeholders - * @param checkValidity - Whether to check if the URL is accessible (with retry logic) * @returns Final thumbnail URL */ - async build(thumbnailUrl: string, checkValidity = false): Promise { - let thumbnail = thumbnailUrl + build(thumbnailUrl: string): string { + return thumbnailUrl .replace('{width}', '1920') .replace('{height}', '1080'); - - if (!checkValidity) { - return thumbnail; - } - - const isValid = await this.checkValidity(thumbnail, 0); - - if (!isValid) { - // Fallback to lower resolution - thumbnail = thumbnail - .replace('1920', '1280') - .replace('1080', '720'); - } - - return thumbnail; - } - - /** - * Check if thumbnail URL is accessible with retry logic - * @param url - URL to check - * @param attempt - Current attempt number (max 5) - * @returns Whether the URL is valid - */ - private async checkValidity(url: string, attempt: number): Promise { - try { - const response = await fetch(url, { - method: 'HEAD', - redirect: 'manual', - }); - - if (response.status === 200) { - return true; - } - - if (attempt >= 5) { - return false; - } - - // Wait 5 seconds before retry - await new Promise(resolve => setTimeout(resolve, 5000)); - return this.checkValidity(url, attempt + 1); - } catch (error) { - if (attempt >= 5) { - return false; - } - - await new Promise(resolve => setTimeout(resolve, 5000)); - return this.checkValidity(url, attempt + 1); - } } } diff --git a/src/webhooks/twitch.ts b/src/webhooks/twitch.ts index 0f8f48e4..4443e576 100644 --- a/src/webhooks/twitch.ts +++ b/src/webhooks/twitch.ts @@ -45,7 +45,8 @@ interface EventSubVerification { export async function handleTwitchWebhook( request: Request, env: Env, - db: DrizzleD1Database + db: DrizzleD1Database, + executionCtx: ExecutionContext ): Promise { try { // Verify the signature @@ -84,90 +85,8 @@ export async function handleTwitchWebhook( if (messageType === 'notification') { const notification = payload as EventSubNotification; - // Initialize services - const i18nService = new I18nService(); - const twitchService = new TwitchService(env); - const telegramService = new TelegramService(env, i18nService); - - // Initialize repositories via factory - const dbConnection = new CloudflareD1Connection(db); - const repositoryFactory = new DrizzleRepositoryFactory(dbConnection); - - const chatRepo = repositoryFactory.createChatRepository(); - const channelRepo = repositoryFactory.createChannelRepository(); - const followRepo = repositoryFactory.createFollowRepository(); - const streamRepo = repositoryFactory.createStreamRepository(); - - // Initialize notification service - const notificationService = new NotificationService( - env, - db, - telegramService, - twitchService, - i18nService, - chatRepo, - channelRepo, - followRepo, - streamRepo - ); - - // Handle different event types - switch (notification.subscription.type) { - case 'stream.online': { - const event = notification.event; - const stream = await twitchService.getStreamByUserId(event.broadcaster_user_id); - if (stream) { - await notificationService.handleStreamOnline({ - channelId: event.broadcaster_user_id, - channelName: event.broadcaster_user_name, - streamId: stream.id, - category: stream.gameName, - title: stream.title, - thumbnailUrl: stream.thumbnailUrl, - }); - } - break; - } - - case 'stream.offline': { - const event = notification.event; - await notificationService.handleStreamOffline({ - channelId: event.broadcaster_user_id, - channelName: event.broadcaster_user_name, - }); - break; - } - - case 'channel.update': { - const event = notification.event; - const channel = await channelRepo.findByChannelId(event.broadcaster_user_id, 'twitch'); - if (!channel) break; - - const stream = await streamRepo.findLatestByChannelId(channel.id); - if (!stream || !stream.isLive) break; - - // Check if category changed - if (stream.category && event.category_name !== stream.category) { - await notificationService.handleCategoryChange({ - channelId: event.broadcaster_user_id, - channelName: event.broadcaster_user_name, - oldCategory: stream.category, - newCategory: event.category_name, - }); - } - - // Check if title changed - if (stream.title && event.title !== stream.title) { - await notificationService.handleTitleChange({ - channelId: event.broadcaster_user_id, - channelName: event.broadcaster_user_name, - oldTitle: stream.title, - newTitle: event.title, - }); - } - break; - } - } + // Respond immediately to prevent Twitch from retrying due to timeout + executionCtx.waitUntil(processNotification(notification, env, db)); return new Response('OK', { status: 200 }); } @@ -184,3 +103,96 @@ export async function handleTwitchWebhook( return new Response('Internal Server Error', { status: 500 }); } } + +async function processNotification( + notification: EventSubNotification, + env: Env, + db: DrizzleD1Database +): Promise { + try { + console.log('Received Twitch EventSub notification:', notification.subscription.type, notification); + + const i18nService = new I18nService(); + await i18nService.init(); + + const twitchService = new TwitchService(env); + const telegramService = new TelegramService(env, i18nService); + + const dbConnection = new CloudflareD1Connection(db); + const repositoryFactory = new DrizzleRepositoryFactory(dbConnection); + + const chatRepo = repositoryFactory.createChatRepository(); + const channelRepo = repositoryFactory.createChannelRepository(); + const followRepo = repositoryFactory.createFollowRepository(); + const streamRepo = repositoryFactory.createStreamRepository(); + + const notificationService = new NotificationService( + env, + db, + telegramService, + twitchService, + i18nService, + chatRepo, + channelRepo, + followRepo, + streamRepo + ); + + switch (notification.subscription.type) { + case 'stream.online': { + const event = notification.event; + const stream = await twitchService.getStreamByUserId(event.broadcaster_user_id); + if (stream) { + await notificationService.handleStreamOnline({ + channelId: event.broadcaster_user_id, + channelName: event.broadcaster_user_name, + streamId: stream.id, + category: stream.gameName, + title: stream.title, + thumbnailUrl: stream.thumbnailUrl, + }); + } + break; + } + + case 'stream.offline': { + const event = notification.event; + await notificationService.handleStreamOffline({ + channelId: event.broadcaster_user_id, + channelName: event.broadcaster_user_name, + }); + break; + } + + case 'channel.update': { + const event = notification.event; + const channel = await channelRepo.findByChannelId(event.broadcaster_user_id, 'twitch'); + if (!channel) break; + + const stream = await streamRepo.findLatestByChannelId(channel.id); + if (!stream || !stream.isLive) break; + + if (stream.category && event.category_name !== stream.category) { + await notificationService.handleCategoryChange({ + channelId: event.broadcaster_user_id, + channelName: event.broadcaster_user_name, + oldCategory: stream.category, + newCategory: event.category_name, + }); + } + + if (stream.title && event.title !== stream.title) { + await notificationService.handleTitleChange({ + channelId: event.broadcaster_user_id, + channelName: event.broadcaster_user_name, + oldTitle: stream.title, + newTitle: event.title, + }); + } + break; + } + } + } catch (error) { + console.error('Error processing Twitch notification:', error); + } +} diff --git a/wrangler.example.toml b/wrangler.example.toml index e4710295..86ae1332 100644 --- a/wrangler.example.toml +++ b/wrangler.example.toml @@ -14,30 +14,8 @@ enabled = true binding = "DB" database_name = "twitch-notifier-db" database_id = "" # Will be filled after creating D1 database +migrations_dir = "./migrations" [[kv_namespaces]] binding = "twitch-notifier-kv" id = "1" - -# Environment Variables -[vars] -APP_ENV = "development" - -# Secrets (use wrangler secret put) -# TELEGRAM_TOKEN = "" -# TWITCH_CLIENT_ID = "" -# TWITCH_CLIENT_SECRET = "" -# TELEGRAM_BOT_ADMINS = "comma-separated user IDs" -# TWITCH_EVENTSUB_SECRET = "for webhook verification" - -# BOT INFO FOR SKIP /me REQUEST ON EACH REQUEST -#BOT_INFO = """{ -# "id": 1234567890, -# "is_bot": true, -# "first_name": "mybot", -# "username": "MyBot", -# "can_join_groups": true, -# "can_read_all_group_messages": false, -# "supports_inline_queries": true, -# "can_connect_to_business": false -#}""" From f81d899a152406c8c432ad1e948e289cf44bcb72 Mon Sep 17 00:00:00 2001 From: Satont Date: Sat, 14 Mar 2026 10:11:33 +0300 Subject: [PATCH 4/4] upd --- .github/workflows/deploy.yml | 35 ----------------------------------- 1 file changed, 35 deletions(-) delete mode 100644 .github/workflows/deploy.yml diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml deleted file mode 100644 index 11c58f05..00000000 --- a/.github/workflows/deploy.yml +++ /dev/null @@ -1,35 +0,0 @@ -name: Deploy to Cloudflare Workers - -on: - push: - branches: - - main - workflow_dispatch: - -jobs: - deploy: - runs-on: ubuntu-latest - name: Deploy - steps: - - uses: actions/checkout@v4 - - - name: Setup Node.js - uses: actions/setup-node@v4 - with: - node-version: '20' - cache: 'npm' - - - name: Install dependencies - run: npm ci - - - name: Run migrations - run: npm run db:migrate - env: - CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }} - CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }} - - - name: Deploy to Cloudflare Workers - run: npm run deploy - env: - CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }} - CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}