openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
1,530 lines (1,529 loc) • 45.1 kB
JavaScript
import { a as __require, t as __commonJSMin } from "../../rolldown-runtime-C_OpTf0N.mjs";
import { l as normalizeOptionalString } from "../../string-coerce-CCIiB4H7.mjs";
import { d as asPositiveFiniteNumber } from "../../number-coercion-D6u-4YD8.mjs";
import { a as asOptionalRecord } from "../../record-coerce-CVPuDqcc.mjs";
import { n as coerceErrorMessage } from "../../error-coercion-hDrHOSGy.mjs";
import { r as resolveStateDir } from "../../state-dir-DiG0gXzD.mjs";
import { o as getPluginRuntimeGatewayRequestScope } from "../../gateway-request-scope-BvvDhs5D.mjs";
import { t as _usingCtx } from "../../usingCtx-rhpPzaNq.mjs";
import { l as isPrivateOrLoopbackHost } from "../../net-BgRayX-P.mjs";
import { i as sendLengthFramedJson } from "../../http-json-ddGJz5CA.mjs";
import { t as readByteStreamWithLimit } from "../../read-byte-stream-with-limit-BjmaH2Xs.mjs";
import { d as tempFile } from "../../file-access-runtime-BD2Fjfbw.mjs";
import "../../state-paths-qdCZ9HDY.mjs";
import "../../string-coerce-runtime-BwAZZDf5.mjs";
import "../../ssrf-runtime-B6q6NM4E.mjs";
import "../../number-runtime-W4chuk8B.mjs";
import "../../error-runtime-BM740gJj.mjs";
import "../../response-limit-runtime-DkiFHsEX.mjs";
import { t as definePluginEntry } from "../../plugin-entry-CiJdaHtx.mjs";
import "../../plugin-runtime-z_iV2vts.mjs";
import path from "node:path";
import { createHash } from "node:crypto";
import fs from "node:fs/promises";
import { promisify } from "node:util";
import net from "node:net";
import { gunzip } from "node:zlib";
//#region extensions/geolocation/src/config.ts
const DEFAULT_DATABASE_URL = "https://download.db-ip.com/free/dbip-city-lite-{yyyy}-{mm}.mmdb.gz";
const DEFAULT_ATTRIBUTION_TEXT = "IP Geolocation by DB-IP";
const DEFAULT_ATTRIBUTION_URL = "https://db-ip.com";
const DEFAULT_REFRESH_DAYS = 30;
function resolveGeolocationSettings(e) {
const t = asOptionalRecord(e);
const n = asPositiveFiniteNumber(t?.refreshDays) ?? DEFAULT_REFRESH_DAYS;
return {
databaseUrl: normalizeOptionalString(t?.databaseUrl) ?? DEFAULT_DATABASE_URL,
attribution: {
text: normalizeOptionalString(t?.attributionText) ?? DEFAULT_ATTRIBUTION_TEXT,
url: normalizeOptionalString(t?.attributionUrl) ?? DEFAULT_ATTRIBUTION_URL
},
refreshMs: n * 24 * 60 * 60 * 1e3
};
}
/**
* Monthly builds appear a few days into the month, so the newest published
* release is either this month's or the previous one. Callers try in order.
*/
function expandDatabaseUrls(e, t) {
const n = [t, new Date(Date.UTC(t.getUTCFullYear(), t.getUTCMonth() - 1, 1))].map((t) => e.replaceAll("{yyyy}", String(t.getUTCFullYear())).replaceAll("{mm}", String(t.getUTCMonth() + 1).padStart(2, "0")));
return [...new Set(n)];
}
//#endregion
//#region node_modules/.pnpm/mmdb-lib@3.0.3/node_modules/mmdb-lib/lib/utils.js
var require_utils$1 = /* @__PURE__ */ __commonJSMin(((e) => {
Object.defineProperty(e, "__esModule", { value: true });
const t = `Maxmind v2 module has changed API.\n\
Upgrade instructions can be found here: \
https://github.com/runk/node-maxmind/wiki/Migration-guide\n\
If you want to use legacy library then explicitly install maxmind@1`;
const assert = (e, t) => {
if (!e) throw new Error(t);
};
e.default = {
assert,
legacyErrorMessage: t
};
}));
//#endregion
//#region node_modules/.pnpm/mmdb-lib@3.0.3/node_modules/mmdb-lib/lib/decoder.js
var require_decoder = /* @__PURE__ */ __commonJSMin(((e, t, n) => {
var r = n && n.__importDefault || function(e) {
return e && e.__esModule ? e : { "default": e };
};
Object.defineProperty(e, "__esModule", { value: true });
const i = r(require_utils$1());
i.default.assert(typeof BigInt !== "undefined", "Apparently you are using old version of node. Please upgrade to node 10.4.x or above.");
const a = 2147483647;
var o;
(function(e) {
e[e["Extended"] = 0] = "Extended";
e[e["Pointer"] = 1] = "Pointer";
e[e["Utf8String"] = 2] = "Utf8String";
e[e["Double"] = 3] = "Double";
e[e["Bytes"] = 4] = "Bytes";
e[e["Uint16"] = 5] = "Uint16";
e[e["Uint32"] = 6] = "Uint32";
e[e["Map"] = 7] = "Map";
e[e["Int32"] = 8] = "Int32";
e[e["Uint64"] = 9] = "Uint64";
e[e["Uint128"] = 10] = "Uint128";
e[e["Array"] = 11] = "Array";
e[e["Container"] = 12] = "Container";
e[e["EndMarker"] = 13] = "EndMarker";
e[e["Boolean"] = 14] = "Boolean";
e[e["Float"] = 15] = "Float";
})(o || (o = {}));
const s = [
0,
2048,
526336,
0
];
const c = {
get: () => void 0,
set: () => void 0
};
const cursor = (e, t) => ({
value: e,
offset: t
});
var Decoder = class {
constructor(e, t = 0, n = c) {
this.telemetry = {};
i.default.assert(Boolean(e), "Database buffer is required");
this.db = e;
this.baseOffset = t;
this.cache = n;
}
decode(e) {
let t;
const n = this.db[e++];
let r = n >> 5;
if (r === o.Pointer) {
t = this.decodePointer(n, e);
return cursor(this.decodeFast(t.value).value, t.offset);
}
if (r === o.Extended) {
t = this.db[e] + 7;
if (t < 8) throw new Error("Invalid Extended Type at offset " + e + " val " + t);
r = t;
e++;
}
const i = this.sizeFromCtrlByte(n, e);
return this.decodeByType(r, i.offset, i.value);
}
decodeFast(e) {
const t = this.cache.get(e);
if (t) return t;
const n = this.decode(e);
this.cache.set(e, n);
return n;
}
decodeByType(e, t, n) {
const r = t + n;
switch (e) {
case o.Utf8String: return cursor(this.decodeString(t, n), r);
case o.Map: return this.decodeMap(n, t);
case o.Uint32: return cursor(this.decodeUint(t, n), r);
case o.Double: return cursor(this.decodeDouble(t), r);
case o.Array: return this.decodeArray(n, t);
case o.Boolean: return cursor(this.decodeBoolean(n), t);
case o.Float: return cursor(this.decodeFloat(t), r);
case o.Bytes: return cursor(this.decodeBytes(t, n), r);
case o.Uint16: return cursor(this.decodeUint(t, n), r);
case o.Int32: return cursor(this.decodeInt32(t, n), r);
case o.Uint64: return cursor(this.decodeBigUint(t, n), r);
case o.Uint128: return cursor(this.decodeBigUint(t, n), r);
}
throw new Error("Unknown type " + e + " at offset " + t);
}
sizeFromCtrlByte(e, t) {
const n = e & 31;
if (n < 29) return cursor(n, t);
if (n === 29) return cursor(29 + this.db[t], t + 1);
if (n === 30) return cursor(285 + this.db.readUInt16BE(t), t + 2);
return cursor(65821 + this.db.readUIntBE(t, 3), t + 3);
}
decodeBytes(e, t) {
return this.db.subarray(e, e + t);
}
decodePointer(e, t) {
const n = e >> 3 & 3;
const r = this.baseOffset + s[n];
let i = 0;
if (n === 0) i = (e & 7) << 8 | this.db[t];
else if (n === 1) i = (e & 7) << 16 | this.db.readUInt16BE(t);
else if (n === 2) i = (e & 7) << 24 | this.db.readUIntBE(t, 3);
else i = this.db.readUInt32BE(t);
t += n + 1;
return cursor(r + i, t);
}
decodeArray(e, t) {
let n;
const r = new Array(e);
for (let i = 0; i < e; i++) {
n = this.decode(t);
t = n.offset;
r[i] = n.value;
}
return cursor(r, t);
}
decodeBoolean(e) {
return e !== 0;
}
decodeDouble(e) {
return this.db.readDoubleBE(e);
}
decodeFloat(e) {
return this.db.readFloatBE(e);
}
decodeMap(e, t) {
let n;
let r;
const i = {};
for (let a = 0; a < e; a++) {
n = this.decode(t);
r = n.value;
n = this.decode(n.offset);
t = n.offset;
i[r] = n.value;
}
return cursor(i, t);
}
decodeInt32(e, t) {
if (t === 0) return 0;
if (t < 4) return this.db.readUIntBE(e, t);
return this.db.readInt32BE(e);
}
decodeUint(e, t) {
if (t === 0) return 0;
if (t <= 4) return this.db.readUIntBE(e, t);
throw new Error(`Invalid size for unsigned integer: ${t}`);
}
decodeString(e, t) {
const n = e + t;
return n >= a ? this.db.subarray(e, n).toString("utf8") : this.db.toString("utf8", e, n);
}
decodeBigUint(e, t) {
if (t > 16) throw new Error(`Invalid size for big unsigned integer: ${t}`);
let n = 0n;
for (let r = 0; r < t; r++) {
n <<= 8n;
n |= BigInt(this.db.readUInt8(e + r));
}
return n;
}
};
e.default = Decoder;
}));
//#endregion
//#region node_modules/.pnpm/mmdb-lib@3.0.3/node_modules/mmdb-lib/lib/ip.js
var require_ip$1 = /* @__PURE__ */ __commonJSMin(((e) => {
Object.defineProperty(e, "__esModule", { value: true });
const t = "(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])";
const n = `(?:${t}\\.){3}${t}`;
const r = new RegExp(`^${n}$`);
const i = "(?:[0-9a-fA-F]{1,4})";
const a = new RegExp(`^(?:(?:${i}:){7}(?:${i}|:)|(?:${i}:){6}(?:${n}|:${i}|:)|(?:${i}:){5}(?::${n}|(?::${i}){1,2}|:)|(?:${i}:){4}(?:(?::${i}){0,1}:${n}|(?::${i}){1,3}|:)|(?:${i}:){3}(?:(?::${i}){0,2}:${n}|(?::${i}){1,4}|:)|(?:${i}:){2}(?:(?::${i}){0,3}:${n}|(?::${i}){1,5}|:)|(?:${i}:){1}(?:(?::${i}){0,4}:${n}|(?::${i}){1,6}|:)|(?::(?:(?::${i}){0,5}:${n}|(?::${i}){1,7}|:)))(?:%[0-9a-zA-Z-.:]{1,})?\$`);
const parseIPv4 = (e) => {
const t = e.split(".", 4);
return [
parseInt(t[0]),
parseInt(t[1]),
parseInt(t[2]),
parseInt(t[3])
];
};
const hex = (e) => {
const t = parseInt(e, 10).toString(16);
return t.length === 2 ? t : "0" + t;
};
const parseIPv6 = (e) => {
const t = [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
];
let n;
let r;
let i;
const [a, o] = (e.indexOf(".") > -1 ? e.replace(/(\d+)\.(\d+)\.(\d+)\.(\d+)/, (e, t, n, r, i) => {
return hex(t) + hex(n) + ":" + hex(r) + hex(i);
}) : e).split("::", 2);
if (a) {
r = a.split(":");
for (n = 0; n < r.length; n++) {
i = parseInt(r[n], 16);
t[n * 2] = i >> 8;
t[n * 2 + 1] = i & 255;
}
}
if (o) {
r = o.split(":");
const e = 16 - r.length * 2;
for (n = 0; n < r.length; n++) {
i = parseInt(r[n], 16);
t[e + n * 2] = i >> 8;
t[e + (n * 2 + 1)] = i & 255;
}
}
return t;
};
const parse = (e) => {
return e.indexOf(":") === -1 ? parseIPv4(e) : parseIPv6(e);
};
const bitAt = (e, t) => {
const n = t >> 3;
const r = 7 ^ t & 7;
return e[n] >>> r & 1;
};
const validate = (e) => r.test(e) || a.test(e);
e.default = {
bitAt,
parse,
validate
};
}));
//#endregion
//#region node_modules/.pnpm/mmdb-lib@3.0.3/node_modules/mmdb-lib/lib/metadata.js
var require_metadata = /* @__PURE__ */ __commonJSMin(((e, t, n) => {
var r = n && n.__importDefault || function(e) {
return e && e.__esModule ? e : { "default": e };
};
Object.defineProperty(e, "__esModule", { value: true });
e.isLegacyFormat = e.parseMetadata = void 0;
const i = r(require_decoder());
const a = r(require_utils$1());
const o = Buffer.from("ABCDEF4D61784D696E642E636F6D", "hex");
const parseMetadata = (t) => {
const n = findStart(t);
const r = new i.default(t, n).decode(n).value;
if (!r) throw new Error((0, e.isLegacyFormat)(t) ? a.default.legacyErrorMessage : "Cannot parse binary database");
a.default.assert([
24,
28,
32
].indexOf(r.record_size) > -1, "Unsupported record size");
return {
binaryFormatMajorVersion: r.binary_format_major_version,
binaryFormatMinorVersion: r.binary_format_minor_version,
buildEpoch: /* @__PURE__ */ new Date(Number(r.build_epoch) * 1e3),
databaseType: r.database_type,
description: r.description,
ipVersion: r.ip_version,
languages: r.languages,
nodeByteSize: r.record_size / 4,
nodeCount: r.node_count,
recordSize: r.record_size,
searchTreeSize: r.node_count * r.record_size / 4,
treeDepth: Math.pow(2, r.ip_version + 1)
};
};
e.parseMetadata = parseMetadata;
const findStart = (e) => {
let t = 0;
let n = e.length - 1;
const r = o.length - 1;
while (t <= r && n-- > 0) t += e[n] === o[r - t] ? 1 : -t;
return n + t;
};
const isLegacyFormat = (e) => {
const t = 20;
for (let n = 0; n < t; n++) {
const t = e.slice(e.length - 3 - n, e.length - n);
if (t[0] === 255 && t[1] === 255 && t[2] === 255) return true;
}
return false;
};
e.isLegacyFormat = isLegacyFormat;
}));
//#endregion
//#region node_modules/.pnpm/mmdb-lib@3.0.3/node_modules/mmdb-lib/lib/reader/walker.js
var require_walker = /* @__PURE__ */ __commonJSMin(((e) => {
Object.defineProperty(e, "__esModule", { value: true });
const readNodeRight24 = (e) => (t) => e.readUIntBE(t + 3, 3);
const readNodeLeft24 = (e) => (t) => e.readUIntBE(t, 3);
const readNodeLeft28 = (e) => (t) => (e[t + 3] & 240) << 20 | e.readUIntBE(t, 3);
const readNodeRight28 = (e) => (t) => (e[t + 3] & 15) << 24 | e.readUIntBE(t + 4, 3);
const readNodeLeft32 = (e) => (t) => e.readUInt32BE(t);
const readNodeRight32 = (e) => (t) => e.readUInt32BE(t + 4);
e.default = (e, t) => {
switch (t) {
case 24: return {
left: readNodeLeft24(e),
right: readNodeRight24(e)
};
case 28: return {
left: readNodeLeft28(e),
right: readNodeRight28(e)
};
case 32: return {
left: readNodeLeft32(e),
right: readNodeRight32(e)
};
}
throw new Error("Unsupported record size");
};
}));
//#endregion
//#region node_modules/.pnpm/mmdb-lib@3.0.3/node_modules/mmdb-lib/lib/reader/response.js
var require_response = /* @__PURE__ */ __commonJSMin(((e) => {
Object.defineProperty(e, "__esModule", { value: true });
}));
//#endregion
//#region node_modules/.pnpm/mmdb-lib@3.0.3/node_modules/mmdb-lib/lib/index.js
var require_lib$1 = /* @__PURE__ */ __commonJSMin(((e, t, n) => {
var r = n && n.__createBinding || (Object.create ? (function(e, t, n, r) {
if (r === void 0) r = n;
var i = Object.getOwnPropertyDescriptor(t, n);
if (!i || ("get" in i ? !t.__esModule : i.writable || i.configurable)) i = {
enumerable: true,
get: function() {
return t[n];
}
};
Object.defineProperty(e, r, i);
}) : (function(e, t, n, r) {
if (r === void 0) r = n;
e[r] = t[n];
}));
var i = n && n.__exportStar || function(e, t) {
for (var n in e) if (n !== "default" && !Object.prototype.hasOwnProperty.call(t, n)) r(t, e, n);
};
var a = n && n.__importDefault || function(e) {
return e && e.__esModule ? e : { "default": e };
};
Object.defineProperty(e, "__esModule", { value: true });
e.Reader = void 0;
const o = a(require_decoder());
const s = a(require_ip$1());
const c = require_metadata();
const l = a(require_walker());
const u = 16;
var Reader = class {
constructor(e, t = {}) {
this.opts = t;
this.load(e);
}
load(e) {
if (!Buffer.isBuffer(e)) throw new Error(`mmdb-lib expects an instance of Buffer, got: ${typeof e}`);
this.db = e;
this.metadata = (0, c.parseMetadata)(this.db);
this.decoder = new o.default(this.db, this.metadata.searchTreeSize + u, this.opts.cache);
this.walker = (0, l.default)(this.db, this.metadata.recordSize);
this.ipv4StartNodeNumber = this.ipv4Start();
}
get(e) {
const [t] = this.getWithPrefixLength(e);
return t;
}
getWithPrefixLength(e) {
const [t, n] = this.findAddressInTree(e);
return [t ? this.resolveDataPointer(t) : null, n];
}
findAddressInTree(e) {
const t = s.default.parse(e);
const n = this.metadata.nodeCount;
const r = t.length * 8;
let i;
let a = 0;
let o;
let c = 0;
if (t.length === 4) a = this.ipv4StartNodeNumber;
for (; c < r && a < n; c++) {
i = s.default.bitAt(t, c);
o = a * this.metadata.nodeByteSize;
a = i ? this.walker.right(o) : this.walker.left(o);
}
if (a > n) return [a, c];
return [null, c];
}
resolveDataPointer(e) {
const t = e - this.metadata.nodeCount + this.metadata.searchTreeSize;
return this.decoder.decodeFast(t).value;
}
ipv4Start() {
if (this.metadata.ipVersion === 4) return 0;
const e = this.metadata.nodeCount;
let t = 0;
let n = 0;
for (; n < 96 && t < e; n++) {
const e = t * this.metadata.nodeByteSize;
t = this.walker.left(e);
}
return t;
}
};
e.Reader = Reader;
i(require_response(), e);
}));
//#endregion
//#region node_modules/.pnpm/tiny-lru@13.0.0/node_modules/tiny-lru/dist/tiny-lru.cjs
/**
* tiny-lru
*
* @copyright 2026 Jason Mulligan <jason.mulligan@avoidwork.com>
* @license BSD-3-Clause
* @version 13.0.0
*/
var require_tiny_lru = /* @__PURE__ */ __commonJSMin(((e) => {
/**
* A high-performance Least Recently Used (LRU) cache implementation with optional TTL support.
* Items are automatically evicted when the cache reaches its maximum size,
* removing the least recently used items first. All core operations (get, set, delete) are O(1).
*
* @class LRU
*/
var LRU = class {
#e;
#t;
/**
* Creates a new LRU cache instance.
* Note: Constructor does not validate parameters. Use lru() factory function for parameter validation.
*
* @constructor
* @param {number} [max=0] - Maximum number of items to store. 0 means unlimited.
* @param {number} [ttl=0] - Time to live in milliseconds. 0 means no expiration.
* @param {boolean} [resetTTL=false] - Whether to reset TTL when updating existing items via set().
*/
constructor(e = 0, t = 0, n = false) {
this.first = null;
this.items = Object.create(null);
this.last = null;
this.max = e;
this.resetTTL = n;
this.size = 0;
this.ttl = t;
this.#e = {
hits: 0,
misses: 0,
sets: 0,
deletes: 0,
evictions: 0
};
this.#t = null;
}
/**
* Removes all items from the cache.
*
* @returns {LRU} The LRU instance for method chaining.
*/
clear() {
for (let e = this.first; e !== null;) {
const t = e.next;
e.prev = null;
e.next = null;
e = t;
}
this.first = null;
this.items = Object.create(null);
this.last = null;
this.size = 0;
this.#e.hits = 0;
this.#e.misses = 0;
this.#e.sets = 0;
this.#e.deletes = 0;
this.#e.evictions = 0;
return this;
}
/**
* Removes an item from the cache by key.
*
* @param {string} key - The key of the item to delete.
* @returns {LRU} The LRU instance for method chaining.
*/
delete(e) {
const t = this.items[e];
if (t !== void 0) {
delete this.items[e];
this.size--;
this.#e.deletes++;
this.#r(t);
t.prev = null;
t.next = null;
}
return this;
}
/**
* Returns an array of [key, value] pairs for the specified keys.
* When no keys provided, returns all entries in LRU order.
* When keys provided, order matches the input array.
*
* @param {string[]} [keys=this.keys()] - Array of keys to get entries for. Defaults to all keys.
* @returns {Array<Array<*>>} Array of [key, value] pairs.
*/
entries(e) {
if (e === void 0) e = this.keys();
const t = Array.from({ length: e.length });
for (let n = 0; n < e.length; n++) {
const r = e[n];
const i = this.items[r];
t[n] = [r, i !== void 0 ? i.value : void 0];
}
return t;
}
/**
* Removes the least recently used item from the cache.
*
* @returns {LRU} The LRU instance for method chaining.
*/
evict() {
if (this.size === 0) return this;
const e = this.first;
delete this.items[e.key];
this.#e.evictions++;
if (--this.size === 0) {
this.first = null;
this.last = null;
} else this.#r(e);
e.prev = null;
e.next = null;
if (this.#t !== null) this.#t({
key: e.key,
value: e.value,
expiry: e.expiry
});
return this;
}
/**
* Returns the expiration timestamp for a given key.
*
* @param {string} key - The key to check expiration for.
* @returns {number|undefined} The expiration timestamp in milliseconds, or undefined if key doesn't exist.
*/
expiresAt(e) {
const t = this.items[e];
return t !== void 0 ? t.expiry : void 0;
}
/**
* Checks if an item has expired.
*
* @param {Object} item - The cache item to check.
* @returns {boolean} True if the item has expired, false otherwise.
* @private
*/
#n(e) {
if (this.ttl === 0 || e.expiry === 0) return false;
return e.expiry <= Date.now();
}
/**
* Retrieves a value from the cache by key without updating LRU order.
* Note: Does not perform TTL checks or remove expired items.
*
* @param {string} key - The key to retrieve.
* @returns {*} The value associated with the key, or undefined if not found.
*/
peek(e) {
const t = this.items[e];
return t !== void 0 ? t.value : void 0;
}
/**
* Retrieves a value from the cache by key. Updates the item's position to most recently used.
*
* @param {string} key - The key to retrieve.
* @returns {*} The value associated with the key, or undefined if not found or expired.
*/
get(e) {
const t = this.items[e];
if (t !== void 0) {
if (!this.#n(t)) {
this.moveToEnd(t);
this.#e.hits++;
return t.value;
}
this.delete(e);
this.#e.misses++;
return;
}
this.#e.misses++;
}
/**
* Checks if a key exists in the cache.
*
* @param {string} key - The key to check for.
* @returns {boolean} True if the key exists and is not expired, false otherwise.
*/
has(e) {
const t = this.items[e];
return t !== void 0 && !this.#n(t);
}
/**
* Unlinks an item from the doubly-linked list.
* Updates first/last pointers if needed.
* Does NOT clear the item's prev/next pointers or delete from items map.
*
* @private
*/
#r(e) {
if (e.prev !== null) e.prev.next = e.next;
if (e.next !== null) e.next.prev = e.prev;
if (this.first === e) this.first = e.next;
if (this.last === e) this.last = e.prev;
}
/**
* Efficiently moves an item to the end of the LRU list (most recently used position).
* This is an internal optimization method that avoids the overhead of the full set() operation
* when only LRU position needs to be updated.
*
* @param {Object} item - The cache item with prev/next pointers to reposition.
* @private
*/
moveToEnd(e) {
if (this.last === e) return;
this.#r(e);
e.prev = this.last;
e.next = null;
this.last.next = e;
this.last = e;
}
/**
* Returns an array of all keys in the cache, ordered from least to most recently used.
*
* @returns {string[]} Array of keys in LRU order.
*/
keys() {
const e = Array.from({ length: this.size });
let t = this.first;
let n = 0;
while (t !== null) {
e[n++] = t.key;
t = t.next;
}
return e;
}
/**
* Sets a value in the cache and returns any evicted item.
*
* @param {string} key - The key to set.
* @param {*} value - The value to store.
* @returns {Object|null} The evicted item (if any) with shape {key, value, expiry}, or null.
*/
setWithEvicted(e, t) {
let n = null;
let r = this.items[e];
if (r !== void 0) {
r.value = t;
if (this.resetTTL) r.expiry = this.ttl > 0 ? Date.now() + this.ttl : this.ttl;
this.moveToEnd(r);
} else {
if (this.max > 0 && this.size === this.max) {
n = {
key: this.first.key,
value: this.first.value,
expiry: this.first.expiry
};
this.evict();
}
r = this.items[e] = {
expiry: this.ttl > 0 ? Date.now() + this.ttl : this.ttl,
key: e,
prev: this.last,
next: null,
value: t
};
if (++this.size === 1) this.first = r;
else this.last.next = r;
this.last = r;
}
this.#e.sets++;
return n;
}
/**
* Sets a value in the cache. Updates the item's position to most recently used.
*
* @param {string} key - The key to set.
* @param {*} value - The value to store.
* @returns {LRU} The LRU instance for method chaining.
*/
set(e, t) {
let n = this.items[e];
if (n !== void 0) {
n.value = t;
if (this.resetTTL) n.expiry = this.ttl > 0 ? Date.now() + this.ttl : this.ttl;
this.moveToEnd(n);
} else {
if (this.max > 0 && this.size === this.max) this.evict();
n = this.items[e] = {
expiry: this.ttl > 0 ? Date.now() + this.ttl : this.ttl,
key: e,
prev: this.last,
next: null,
value: t
};
if (++this.size === 1) this.first = n;
else this.last.next = n;
this.last = n;
}
this.#e.sets++;
return this;
}
/**
* Returns an array of all values in the cache for the specified keys.
* When no keys provided, returns all values in LRU order.
* When keys provided, order matches the input array.
*
* @param {string[]} [keys] - Array of keys to get values for. Defaults to all keys.
* @returns {Array<*>} Array of values corresponding to the keys.
*/
values(e) {
if (e === void 0) {
const e = Array.from({ length: this.size });
let t = 0;
for (let n = this.first; n !== null; n = n.next) e[t++] = n.value;
return e;
}
const t = Array.from({ length: e.length });
for (let n = 0; n < e.length; n++) {
const r = this.items[e[n]];
t[n] = r !== void 0 ? r.value : void 0;
}
return t;
}
/**
* Iterate over cache items in LRU order (least to most recent).
* Note: This method directly accesses items from the linked list without calling
* get() or peek(), so it does not update LRU order or check TTL expiration during iteration.
*
* @param {function(*, any, LRU): void} callback - Function to call for each item. Signature: callback(value, key, cache)
* @param {Object} [thisArg] - Value to use as `this` when executing callback.
* @returns {LRU} The LRU instance for method chaining.
*/
forEach(e, t) {
for (let n = this.first; n !== null; n = n.next) e.call(t, n.value, n.key, this);
return this;
}
/**
* Batch retrieve multiple items.
*
* @param {string[]} keys - Array of keys to retrieve.
* @returns {Object} Object mapping keys to values (undefined for missing/expired keys).
*/
getMany(e) {
const t = Object.create(null);
for (let n = 0; n < e.length; n++) {
const r = e[n];
t[r] = this.get(r);
}
return t;
}
/**
* Batch existence check - returns true if ALL keys exist.
*
* @param {string[]} keys - Array of keys to check.
* @returns {boolean} True if all keys exist and are not expired.
*/
hasAll(e) {
for (let t = 0; t < e.length; t++) if (!this.has(e[t])) return false;
return true;
}
/**
* Batch existence check - returns true if ANY key exists.
*
* @param {string[]} keys - Array of keys to check.
* @returns {boolean} True if any key exists and is not expired.
*/
hasAny(e) {
for (let t = 0; t < e.length; t++) if (this.has(e[t])) return true;
return false;
}
/**
* Remove expired items without affecting LRU order.
* Unlike get(), this does not move items to the end.
*
* @returns {number} Number of expired items removed.
*/
cleanup() {
if (this.ttl === 0 || this.size === 0) return 0;
let e = 0;
for (let t = this.first; t !== null;) {
const n = t.next;
if (this.#n(t)) {
const n = t.key;
if (this.items[n] !== void 0) {
delete this.items[n];
this.size--;
e++;
this.#r(t);
t.prev = null;
t.next = null;
}
}
t = n;
}
if (e > 0) this.#i();
return e;
}
/**
* Serialize cache to JSON-compatible format.
*
* @returns {Array<{key: any, value: *, expiry: number}>} Array of cache items.
*/
toJSON() {
const e = [];
for (let t = this.first; t !== null; t = t.next) e.push({
key: t.key,
value: t.value,
expiry: t.expiry
});
return e;
}
/**
* Get cache statistics.
*
* @returns {Object} Statistics object with hits, misses, sets, deletes, evictions counts.
*/
stats() {
return { ...this.#e };
}
/**
* Register callback for evicted items.
*
* @param {function(Object): void} callback - Function called when item is evicted. Receives {key, value, expiry}.
* @returns {LRU} The LRU instance for method chaining.
*/
onEvict(e) {
if (typeof e !== "function") throw new TypeError("onEvict callback must be a function");
this.#t = e;
return this;
}
/**
* Get counts of items by TTL status.
*
* @returns {Object} Object with valid, expired, and noTTL counts.
*/
sizeByTTL() {
if (this.ttl === 0) return {
valid: this.size,
expired: 0,
noTTL: this.size
};
const e = Date.now();
let t = 0;
let n = 0;
let r = 0;
for (let i = this.first; i !== null; i = i.next) if (i.expiry === 0) {
r++;
t++;
} else if (i.expiry > e) t++;
else n++;
return {
valid: t,
expired: n,
noTTL: r
};
}
/**
* Get keys filtered by TTL status.
*
* @returns {Object} Object with valid, expired, and noTTL arrays of keys.
*/
keysByTTL() {
if (this.ttl === 0) return {
valid: this.keys(),
expired: [],
noTTL: this.keys()
};
const e = Date.now();
const t = [];
const n = [];
const r = [];
for (let i = this.first; i !== null; i = i.next) if (i.expiry === 0) {
t.push(i.key);
r.push(i.key);
} else if (i.expiry > e) t.push(i.key);
else n.push(i.key);
return {
valid: t,
expired: n,
noTTL: r
};
}
/**
* Get values filtered by TTL status.
*
* @returns {Object} Object with valid, expired, and noTTL arrays of values.
*/
valuesByTTL() {
const e = this.keysByTTL();
return {
valid: this.values(e.valid),
expired: this.values(e.expired),
noTTL: this.values(e.noTTL)
};
}
/**
* Rebuild the doubly-linked list after cleanup by deleting expired items.
* This removes nodes that were deleted during cleanup.
*
* @private
*/
#i() {
if (this.size === 0) {
this.first = null;
this.last = null;
return;
}
const e = this.keys();
this.first = null;
this.last = null;
for (let t = 0; t < e.length; t++) {
const n = this.items[e[t]];
if (n !== null && n !== void 0) {
if (this.first === null) {
this.first = n;
n.prev = null;
} else {
n.prev = this.last;
this.last.next = n;
}
n.next = null;
this.last = n;
}
}
}
};
/**
* Factory function to create a new LRU cache instance with parameter validation.
*
* @function lru
* @param {number} [max=1000] - Maximum number of items to store. Must be >= 0. Use 0 for unlimited size.
* @param {number} [ttl=0] - Time to live in milliseconds. Must be >= 0. Use 0 for no expiration.
* @param {boolean} [resetTTL=false] - Whether to reset TTL when updating existing items via set().
* @returns {LRU} A new LRU cache instance.
* @throws {TypeError} When parameters are invalid (negative numbers or wrong types).
*/
function lru(e = 1e3, t = 0, n = false) {
if (isNaN(e) || e < 0) throw new TypeError("Invalid max value");
if (isNaN(t) || t < 0) throw new TypeError("Invalid ttl value");
if (typeof n !== "boolean") throw new TypeError("Invalid resetTTL value");
return new LRU(e, t, n);
}
e.LRU = LRU;
e.lru = lru;
}));
//#endregion
//#region node_modules/.pnpm/maxmind@5.0.7/node_modules/maxmind/lib/fs.js
var require_fs = /* @__PURE__ */ __commonJSMin(((e, t, n) => {
var r = n && n.__importDefault || function(e) {
return e && e.__esModule ? e : { "default": e };
};
Object.defineProperty(e, "__esModule", { value: true });
const i = r(__require("fs"));
const a = r(__require("util"));
e.default = {
existsSync: i.default.existsSync,
readFile: a.default.promisify(i.default.readFile),
watchFile: i.default.watchFile,
createReadStream: i.default.createReadStream,
stat: a.default.promisify(i.default.stat)
};
}));
//#endregion
//#region node_modules/.pnpm/maxmind@5.0.7/node_modules/maxmind/lib/ip.js
var require_ip = /* @__PURE__ */ __commonJSMin(((e, t, n) => {
var r = n && n.__importDefault || function(e) {
return e && e.__esModule ? e : { "default": e };
};
Object.defineProperty(e, "__esModule", { value: true });
const i = r(__require("net"));
const parseIPv4 = (e) => {
const t = e.split(".", 4);
return [
parseInt(t[0]),
parseInt(t[1]),
parseInt(t[2]),
parseInt(t[3])
];
};
const hex = (e) => {
e = parseInt(e, 10).toString(16);
return e.length === 2 ? e : "0" + e;
};
const parseIPv6 = (e) => {
const t = [
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
];
let n;
let r;
let i;
if (e.indexOf(".") > -1) e = e.replace(/(\d+)\.(\d+)\.(\d+)\.(\d+)/, (e, t, n, r, i) => {
return hex(t) + hex(n) + ":" + hex(r) + hex(i);
});
const [a, o] = e.split("::", 2);
if (a) {
r = a.split(":");
for (n = 0; n < r.length; n++) {
i = parseInt(r[n], 16);
t[n * 2] = i >> 8;
t[n * 2 + 1] = i & 255;
}
}
if (o) {
r = o.split(":");
const e = 16 - r.length * 2;
for (n = 0; n < r.length; n++) {
i = parseInt(r[n], 16);
t[e + n * 2] = i >> 8;
t[e + (n * 2 + 1)] = i & 255;
}
}
return t;
};
const parse = (e) => {
return e.indexOf(":") === -1 ? parseIPv4(e) : parseIPv6(e);
};
const bitAt = (e, t) => {
const n = t >> 3;
const r = 7 ^ t & 7;
return e[n] >>> r & 1;
};
const validate = (e) => {
const t = i.default.isIP(e);
return t === 4 || t === 6;
};
e.default = {
bitAt,
parse,
validate
};
}));
//#endregion
//#region node_modules/.pnpm/maxmind@5.0.7/node_modules/maxmind/lib/is-gzip.js
var require_is_gzip = /* @__PURE__ */ __commonJSMin(((e) => {
Object.defineProperty(e, "__esModule", { value: true });
e.default = (e) => {
if (!e || e.length < 3) return false;
return e[0] === 31 && e[1] === 139 && e[2] === 8;
};
}));
//#endregion
//#region node_modules/.pnpm/maxmind@5.0.7/node_modules/maxmind/lib/utils.js
var require_utils = /* @__PURE__ */ __commonJSMin(((e) => {
Object.defineProperty(e, "__esModule", { value: true });
const concat2 = (e, t) => {
return e << 8 | t;
};
const concat3 = (e, t, n) => {
return e << 16 | t << 8 | n;
};
const concat4 = (e, t, n, r) => {
return e << 24 | t << 16 | n << 8 | r;
};
const t = `Maxmind v2 module has changed API.\n\
Upgrade instructions can be found here: \
https://github.com/runk/node-maxmind/wiki/Migration-guide\n\
If you want to use legacy libary then explicitly install maxmind@1`;
e.default = {
concat2,
concat3,
concat4,
legacyErrorMessage: t
};
}));
//#endregion
//#region node_modules/.pnpm/maxmind@5.0.7/node_modules/maxmind/lib/index.js
var require_lib = /* @__PURE__ */ __commonJSMin(((e, t, n) => {
var r = n && n.__createBinding || (Object.create ? (function(e, t, n, r) {
if (r === void 0) r = n;
var i = Object.getOwnPropertyDescriptor(t, n);
if (!i || ("get" in i ? !t.__esModule : i.writable || i.configurable)) i = {
enumerable: true,
get: function() {
return t[n];
}
};
Object.defineProperty(e, r, i);
}) : (function(e, t, n, r) {
if (r === void 0) r = n;
e[r] = t[n];
}));
var i = n && n.__exportStar || function(e, t) {
for (var n in e) if (n !== "default" && !Object.prototype.hasOwnProperty.call(t, n)) r(t, e, n);
};
var a = n && n.__importDefault || function(e) {
return e && e.__esModule ? e : { "default": e };
};
Object.defineProperty(e, "__esModule", { value: true });
e.Reader = e.validate = e.init = e.openSync = e.open = void 0;
const o = a(__require("assert"));
const s = require_lib$1();
Object.defineProperty(e, "Reader", {
enumerable: true,
get: function() {
return s.Reader;
}
});
const c = require_tiny_lru();
const l = a(require_fs());
const u = a(require_ip());
const d = a(require_is_gzip());
const f = a(require_utils());
const p = 536870912;
const m = 8388608;
const readLargeFile = async (e, t) => new Promise((n, r) => {
let i = Buffer.allocUnsafe(t);
let a = 0;
const o = l.default.createReadStream(e, { highWaterMark: m });
o.on("data", (e) => {
if (Buffer.isBuffer(e)) {
e.copy(i, a);
a += e.length;
} else {
const t = Buffer.from(e);
t.copy(i, a);
a += t.length;
}
});
o.on("end", () => {
o.close();
n(i);
});
o.on("error", (e) => {
r(e);
});
});
const readFile = async (e) => {
const t = await l.default.stat(e);
return t.size < p ? l.default.readFile(e) : readLargeFile(e, t.size);
};
const open = async (e, t, n) => {
(0, o.default)(!n, f.default.legacyErrorMessage);
const r = await readFile(e);
if ((0, d.default)(r)) throw new Error("Looks like you are passing in a file in gzip format, please use mmdb database instead.");
const i = (0, c.lru)(t?.cache?.max || 1e4);
const a = new s.Reader(r, { cache: i });
if (t && !!t.watchForUpdates) {
if (t.watchForUpdatesHook && typeof t.watchForUpdatesHook !== "function") throw new Error("opts.watchForUpdatesHook should be a function");
const n = { persistent: t.watchForUpdatesNonPersistent !== true };
l.default.watchFile(e, n, async () => {
const waitExists = async () => {
for (let t = 0; t < 3; t++) {
if (l.default.existsSync(e)) return true;
await new Promise((e) => setTimeout(e, 500));
}
return false;
};
if (!await waitExists()) return;
const n = await readFile(e);
i.clear();
a.load(n);
if (t.watchForUpdatesHook) t.watchForUpdatesHook();
});
}
return a;
};
e.open = open;
const openSync = () => {
throw new Error(f.default.legacyErrorMessage);
};
e.openSync = openSync;
const init = () => {
throw new Error(f.default.legacyErrorMessage);
};
e.init = init;
e.validate = u.default.validate;
i(require_lib$1(), e);
e.default = {
init: e.init,
open: e.open,
openSync: e.openSync,
validate: u.default.validate
};
}));
//#endregion
//#region extensions/geolocation/src/database-store.ts
/**
* Owns the on-disk MMDB copy: downloads it on first use, reuses it until it
* ages past the refresh window, and releases the opened reader between bursts.
*/
var import_lib = require_lib();
const gunzipAsync = promisify(gunzip);
const MAX_COMPRESSED_BYTES = 268435456;
const MAX_DATABASE_BYTES = 536870912;
const DOWNLOAD_TIMEOUT_MS = 12e4;
const READER_IDLE_MS = 6e4;
function databasePath(e, t) {
const n = createHash("sha256").update(t).digest("hex").slice(0, 12);
return path.join(e, "geolocation", `ip-city-${n}.mmdb`);
}
async function readFileAge(e, t) {
try {
const n = await fs.stat(e);
return t.getTime() - n.mtimeMs;
} catch {
return;
}
}
async function downloadDatabase(e, t) {
const n = expandDatabaseUrls(e.settings.databaseUrl, /* @__PURE__ */ new Date());
const r = [];
for (const a of n) try {
const n = await e.fetchImpl(a, { signal: AbortSignal.timeout(DOWNLOAD_TIMEOUT_MS) });
if (!n.ok) {
r.push(`${a} -> HTTP ${n.status}`);
continue;
}
if (!n.body) throw new Error("response had no body");
const o = await readByteStreamWithLimit(n.body.values(), {
maxBytes: MAX_COMPRESSED_BYTES,
onOverflow: ({ maxBytes: e }) => /* @__PURE__ */ new Error(`response exceeded the ${e} byte cap`)
});
const s = new URL(a).pathname.endsWith(".gz") ? await gunzipAsync(o, { maxOutputLength: MAX_DATABASE_BYTES }) : o;
const c = new import_lib.Reader(s);
let l = false;
try {
try {
var i = _usingCtx();
await fs.mkdir(path.dirname(t), { recursive: true });
const e = await fs.realpath(path.dirname(t));
const n = i.a(await tempFile({
rootDir: e,
prefix: "ip-city",
onCleanupError: (e) => {
throw e;
}
}));
await fs.writeFile(n.path, s, { flag: "wx" });
await fs.rename(n.path, path.join(e, path.basename(t)));
l = true;
} catch (e) {
i.e = e;
} finally {
await i.d();
}
} catch (t) {
e.logger?.warn(`geolocation: could not cache the downloaded database, serving it from memory: ${coerceErrorMessage(t)}`);
}
e.logger?.info(`geolocation: downloaded ${s.byteLength} bytes from ${a}`);
return {
reader: c,
cached: l
};
} catch (e) {
r.push(`${a} -> ${coerceErrorMessage(e)}`);
}
throw new Error(`geolocation database download failed: ${r.join("; ")}`);
}
/**
* Returns a reader, downloading or refreshing the database as needed. A stale
* copy is preferred over failing: a refresh error must not take lookups down.
*/
function createGeolocationDatabaseStore(e) {
const t = databasePath(e.stateDir, e.settings.databaseUrl);
let n;
let r = Number.NEGATIVE_INFINITY;
let i;
let a;
const releaseReader = () => {
n = void 0;
a = void 0;
};
const openFromDisk = async () => {
const i = Date.now() > r;
const o = await readFileAge(t, /* @__PURE__ */ new Date());
let s;
if (o === void 0) s = await downloadDatabase(e, t);
else if (i && o > e.settings.refreshMs) try {
s = await downloadDatabase(e, t);
} catch (t) {
e.logger?.warn(`geolocation: refresh failed, serving the cached database: ${coerceErrorMessage(t)}`);
}
const { reader: c, cached: l } = s ?? {
reader: new import_lib.Reader(await fs.readFile(t)),
cached: true
};
n = c;
if (i) r = Date.now() + e.settings.refreshMs;
clearTimeout(a);
a = l ? setTimeout(releaseReader, READER_IDLE_MS).unref() : void 0;
return { lookup: (e) => c.get(e) };
};
return { async load() {
const e = n;
if (e && Date.now() <= r) {
a?.refresh();
return { lookup: (t) => e.get(t) };
}
i ??= openFromDisk().finally(() => {
i = void 0;
});
return await i;
} };
}
//#endregion
//#region extensions/geolocation/index.ts
/**
* Geolocation plugin entry. It exposes authenticated lookups and keeps
* the database download lazy, so an install that nobody queries costs nothing.
*/
function englishName(e) {
const t = e?.en?.trim();
return t ? t : void 0;
}
/**
* Returns undefined when the database has no usable placement for the address,
* so callers can distinguish "not found" from an empty-but-present answer.
*/
function projectGeolocationRecord(e) {
if (!e) return;
const t = {
...englishName(e.city?.names) ? { city: englishName(e.city?.names) } : {},
...englishName(e.subdivisions?.[0]?.names) ? { region: englishName(e.subdivisions?.[0]?.names) } : {},
...englishName(e.country?.names) ? { country: englishName(e.country?.names) } : {},
...e.country?.iso_code ? { countryCode: e.country.iso_code } : {}
};
return Object.keys(t).length > 0 ? t : void 0;
}
var geolocation_default = definePluginEntry({
id: "geolocation",
name: "Geolocation Plugin",
description: "Bundled geolocation plugin",
register(e) {
const t = resolveGeolocationSettings(e.pluginConfig);
const n = createGeolocationDatabaseStore({
stateDir: resolveStateDir(),
settings: t,
fetchImpl: fetch,
logger: e.logger
});
async function lookup(r, i) {
const a = typeof r === "string" ? [r] : r;
await i();
let o;
if (a.some((e) => !isPrivateOrLoopbackHost(e))) try {
o = await n.load();
} catch (t) {
e.logger?.warn(`geolocation: lookup unavailable: ${coerceErrorMessage(t)}`);
}
await i();
const lookupAddress = (n) => {
const r = t.attribution;
if (isPrivateOrLoopbackHost(n)) return {
ip: n,
status: "not-found",
attribution: r
};
if (!o) return {
ip: n,
status: "unavailable",
attribution: r
};
try {
const e = projectGeolocationRecord(o.lookup(n));
return {
ip: n,
status: e ? "found" : "not-found",
...e,
attribution: r
};
} catch (t) {
e.logger?.warn(`geolocation: lookup unavailable: ${coerceErrorMessage(t)}`);
return {
ip: n,
status: "unavailable",
attribution: r
};
}
};
return typeof r === "string" ? lookupAddress(r) : r.map(lookupAddress);
}
e.registerGatewayMethod("geolocation.lookup", async (e) => {
const { params: t, respond: n } = e;
if (Object.keys(t).some((e) => e !== "ips") || !Array.isArray(t.ips) || t.ips.length > 200 || !t.ips.every((e) => typeof e === "string" && net.isIP(e) !== 0)) {
const { ErrorCodes: e, errorShape: t } = await import("../../plugin-sdk/gateway-runtime.js");
n(false, void 0, t(e.INVALID_REQUEST, "ips must contain at most 200 IPv4 or IPv6 addresses"));
return;
}
const assertCurrent = () => {
e.signal?.throwIfAborted();
if (e.client?.invalidated || e.hasCurrentClientAuthority?.() === false) throw new Error("Gateway requester authority changed");
e.sessionMutationCommitGuard?.();
e.sessionMutationAuthorization?.assertCurrent();
};
const r = await lookup([...new Set(t.ips)], assertCurrent);
assertCurrent();
n(true, { results: r });
}, {
scope: "operator.read",
profileAccess: "independent"
});
e.registerHttpRoute({
path: "/plugins/geolocation",
auth: "gateway",
match: "prefix",
handler: async (e, t) => {
const n = new URL(e.url ?? "/", "http://localhost");
if (!n.pathname.endsWith("/lookup")) return false;
const r = n.searchParams.get("ip")?.trim() ?? "";
if (!net.isIP(r)) {
sendLengthFramedJson(t, 400, { error: "ip must be a valid IPv4 or IPv6 address" });
return true;
}
const i = getPluginRuntimeGatewayRequestScope();
const a = await lookup(r, async () => {
await i?.revalidate?.();
});
if (a.status === "unavailable") sendLengthFramedJson(t, 503, { error: "geolocation database unavailable" });
else {
const { ip: e, status: n, ...r } = a;
sendLengthFramedJson(t, 200, {
found: n === "found",
...r
});
}
return true;
}
});
}
});
//#endregion
export { geolocation_default as default };