UNPKG

@liveblocks/emails

Version:

A set of functions and utilities to make sending emails based on Liveblocks notification events easy. Liveblocks is the all-in-one toolkit to build collaborative products like Figma, Notion, and more.

1,911 lines (1,884 loc) 247 kB
// src/index.ts import { detectDupes } from "@liveblocks/core"; // src/version.ts var PKG_NAME = "@liveblocks/emails"; var PKG_VERSION = "2.24.3"; var PKG_FORMAT = "esm"; // ../../node_modules/lib0/map.js var create = () => /* @__PURE__ */ new Map(); var copy = (m) => { const r = create(); m.forEach((v, k) => { r.set(k, v); }); return r; }; var setIfUndefined = (map, key, createT) => { let set = map.get(key); if (set === void 0) { map.set(key, set = createT()); } return set; }; var any = (m, f) => { for (const [key, value] of m) { if (f(value, key)) { return true; } } return false; }; // ../../node_modules/lib0/set.js var create2 = () => /* @__PURE__ */ new Set(); // ../../node_modules/lib0/array.js var last = (arr) => arr[arr.length - 1]; var appendTo = (dest, src) => { for (let i = 0; i < src.length; i++) { dest.push(src[i]); } }; var from = Array.from; var isArray = Array.isArray; // ../../node_modules/lib0/observable.js var ObservableV2 = class { constructor() { this._observers = create(); } /** * @template {keyof EVENTS & string} NAME * @param {NAME} name * @param {EVENTS[NAME]} f */ on(name, f) { setIfUndefined( this._observers, /** @type {string} */ name, create2 ).add(f); return f; } /** * @template {keyof EVENTS & string} NAME * @param {NAME} name * @param {EVENTS[NAME]} f */ once(name, f) { const _f = (...args2) => { this.off( name, /** @type {any} */ _f ); f(...args2); }; this.on( name, /** @type {any} */ _f ); } /** * @template {keyof EVENTS & string} NAME * @param {NAME} name * @param {EVENTS[NAME]} f */ off(name, f) { const observers = this._observers.get(name); if (observers !== void 0) { observers.delete(f); if (observers.size === 0) { this._observers.delete(name); } } } /** * Emit a named event. All registered event listeners that listen to the * specified name will receive the event. * * @todo This should catch exceptions * * @template {keyof EVENTS & string} NAME * @param {NAME} name The event name. * @param {Parameters<EVENTS[NAME]>} args The arguments that are applied to the event listener. */ emit(name, args2) { return from((this._observers.get(name) || create()).values()).forEach((f) => f(...args2)); } destroy() { this._observers = create(); } }; // ../../node_modules/lib0/math.js var floor = Math.floor; var abs = Math.abs; var min = (a, b) => a < b ? a : b; var max = (a, b) => a > b ? a : b; var isNaN = Number.isNaN; var isNegativeZero = (n) => n !== 0 ? n < 0 : 1 / n < 0; // ../../node_modules/lib0/binary.js var BIT1 = 1; var BIT2 = 2; var BIT3 = 4; var BIT4 = 8; var BIT6 = 32; var BIT7 = 64; var BIT8 = 128; var BIT18 = 1 << 17; var BIT19 = 1 << 18; var BIT20 = 1 << 19; var BIT21 = 1 << 20; var BIT22 = 1 << 21; var BIT23 = 1 << 22; var BIT24 = 1 << 23; var BIT25 = 1 << 24; var BIT26 = 1 << 25; var BIT27 = 1 << 26; var BIT28 = 1 << 27; var BIT29 = 1 << 28; var BIT30 = 1 << 29; var BIT31 = 1 << 30; var BIT32 = 1 << 31; var BITS5 = 31; var BITS6 = 63; var BITS7 = 127; var BITS17 = BIT18 - 1; var BITS18 = BIT19 - 1; var BITS19 = BIT20 - 1; var BITS20 = BIT21 - 1; var BITS21 = BIT22 - 1; var BITS22 = BIT23 - 1; var BITS23 = BIT24 - 1; var BITS24 = BIT25 - 1; var BITS25 = BIT26 - 1; var BITS26 = BIT27 - 1; var BITS27 = BIT28 - 1; var BITS28 = BIT29 - 1; var BITS29 = BIT30 - 1; var BITS30 = BIT31 - 1; var BITS31 = 2147483647; // ../../node_modules/lib0/number.js var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER; var MIN_SAFE_INTEGER = Number.MIN_SAFE_INTEGER; var LOWEST_INT32 = 1 << 31; var isInteger = Number.isInteger || ((num) => typeof num === "number" && isFinite(num) && floor(num) === num); var isNaN2 = Number.isNaN; var parseInt = Number.parseInt; // ../../node_modules/lib0/string.js var fromCharCode = String.fromCharCode; var fromCodePoint = String.fromCodePoint; var MAX_UTF16_CHARACTER = fromCharCode(65535); var toLowerCase = (s) => s.toLowerCase(); var trimLeftRegex = /^\s*/g; var trimLeft = (s) => s.replace(trimLeftRegex, ""); var fromCamelCaseRegex = /([A-Z])/g; var fromCamelCase = (s, separator) => trimLeft(s.replace(fromCamelCaseRegex, (match) => `${separator}${toLowerCase(match)}`)); var _encodeUtf8Polyfill = (str) => { const encodedString = unescape(encodeURIComponent(str)); const len = encodedString.length; const buf = new Uint8Array(len); for (let i = 0; i < len; i++) { buf[i] = /** @type {number} */ encodedString.codePointAt(i); } return buf; }; var utf8TextEncoder = ( /** @type {TextEncoder} */ typeof TextEncoder !== "undefined" ? new TextEncoder() : null ); var _encodeUtf8Native = (str) => utf8TextEncoder.encode(str); var encodeUtf8 = utf8TextEncoder ? _encodeUtf8Native : _encodeUtf8Polyfill; var utf8TextDecoder = typeof TextDecoder === "undefined" ? null : new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }); if (utf8TextDecoder && utf8TextDecoder.decode(new Uint8Array()).length === 1) { utf8TextDecoder = null; } // ../../node_modules/lib0/encoding.js var Encoder = class { constructor() { this.cpos = 0; this.cbuf = new Uint8Array(100); this.bufs = []; } }; var createEncoder = () => new Encoder(); var length = (encoder) => { let len = encoder.cpos; for (let i = 0; i < encoder.bufs.length; i++) { len += encoder.bufs[i].length; } return len; }; var toUint8Array = (encoder) => { const uint8arr = new Uint8Array(length(encoder)); let curPos = 0; for (let i = 0; i < encoder.bufs.length; i++) { const d = encoder.bufs[i]; uint8arr.set(d, curPos); curPos += d.length; } uint8arr.set(new Uint8Array(encoder.cbuf.buffer, 0, encoder.cpos), curPos); return uint8arr; }; var verifyLen = (encoder, len) => { const bufferLen = encoder.cbuf.length; if (bufferLen - encoder.cpos < len) { encoder.bufs.push(new Uint8Array(encoder.cbuf.buffer, 0, encoder.cpos)); encoder.cbuf = new Uint8Array(max(bufferLen, len) * 2); encoder.cpos = 0; } }; var write = (encoder, num) => { const bufferLen = encoder.cbuf.length; if (encoder.cpos === bufferLen) { encoder.bufs.push(encoder.cbuf); encoder.cbuf = new Uint8Array(bufferLen * 2); encoder.cpos = 0; } encoder.cbuf[encoder.cpos++] = num; }; var writeUint8 = write; var writeVarUint = (encoder, num) => { while (num > BITS7) { write(encoder, BIT8 | BITS7 & num); num = floor(num / 128); } write(encoder, BITS7 & num); }; var writeVarInt = (encoder, num) => { const isNegative = isNegativeZero(num); if (isNegative) { num = -num; } write(encoder, (num > BITS6 ? BIT8 : 0) | (isNegative ? BIT7 : 0) | BITS6 & num); num = floor(num / 64); while (num > 0) { write(encoder, (num > BITS7 ? BIT8 : 0) | BITS7 & num); num = floor(num / 128); } }; var _strBuffer = new Uint8Array(3e4); var _maxStrBSize = _strBuffer.length / 3; var _writeVarStringNative = (encoder, str) => { if (str.length < _maxStrBSize) { const written = utf8TextEncoder.encodeInto(str, _strBuffer).written || 0; writeVarUint(encoder, written); for (let i = 0; i < written; i++) { write(encoder, _strBuffer[i]); } } else { writeVarUint8Array(encoder, encodeUtf8(str)); } }; var _writeVarStringPolyfill = (encoder, str) => { const encodedString = unescape(encodeURIComponent(str)); const len = encodedString.length; writeVarUint(encoder, len); for (let i = 0; i < len; i++) { write( encoder, /** @type {number} */ encodedString.codePointAt(i) ); } }; var writeVarString = utf8TextEncoder && /** @type {any} */ utf8TextEncoder.encodeInto ? _writeVarStringNative : _writeVarStringPolyfill; var writeUint8Array = (encoder, uint8Array) => { const bufferLen = encoder.cbuf.length; const cpos = encoder.cpos; const leftCopyLen = min(bufferLen - cpos, uint8Array.length); const rightCopyLen = uint8Array.length - leftCopyLen; encoder.cbuf.set(uint8Array.subarray(0, leftCopyLen), cpos); encoder.cpos += leftCopyLen; if (rightCopyLen > 0) { encoder.bufs.push(encoder.cbuf); encoder.cbuf = new Uint8Array(max(bufferLen * 2, rightCopyLen)); encoder.cbuf.set(uint8Array.subarray(leftCopyLen)); encoder.cpos = rightCopyLen; } }; var writeVarUint8Array = (encoder, uint8Array) => { writeVarUint(encoder, uint8Array.byteLength); writeUint8Array(encoder, uint8Array); }; var writeOnDataView = (encoder, len) => { verifyLen(encoder, len); const dview = new DataView(encoder.cbuf.buffer, encoder.cpos, len); encoder.cpos += len; return dview; }; var writeFloat32 = (encoder, num) => writeOnDataView(encoder, 4).setFloat32(0, num, false); var writeFloat64 = (encoder, num) => writeOnDataView(encoder, 8).setFloat64(0, num, false); var writeBigInt64 = (encoder, num) => ( /** @type {any} */ writeOnDataView(encoder, 8).setBigInt64(0, num, false) ); var floatTestBed = new DataView(new ArrayBuffer(4)); var isFloat32 = (num) => { floatTestBed.setFloat32(0, num); return floatTestBed.getFloat32(0) === num; }; var writeAny = (encoder, data) => { switch (typeof data) { case "string": write(encoder, 119); writeVarString(encoder, data); break; case "number": if (isInteger(data) && abs(data) <= BITS31) { write(encoder, 125); writeVarInt(encoder, data); } else if (isFloat32(data)) { write(encoder, 124); writeFloat32(encoder, data); } else { write(encoder, 123); writeFloat64(encoder, data); } break; case "bigint": write(encoder, 122); writeBigInt64(encoder, data); break; case "object": if (data === null) { write(encoder, 126); } else if (isArray(data)) { write(encoder, 117); writeVarUint(encoder, data.length); for (let i = 0; i < data.length; i++) { writeAny(encoder, data[i]); } } else if (data instanceof Uint8Array) { write(encoder, 116); writeVarUint8Array(encoder, data); } else { write(encoder, 118); const keys2 = Object.keys(data); writeVarUint(encoder, keys2.length); for (let i = 0; i < keys2.length; i++) { const key = keys2[i]; writeVarString(encoder, key); writeAny(encoder, data[key]); } } break; case "boolean": write(encoder, data ? 120 : 121); break; default: write(encoder, 127); } }; var RleEncoder = class extends Encoder { /** * @param {function(Encoder, T):void} writer */ constructor(writer) { super(); this.w = writer; this.s = null; this.count = 0; } /** * @param {T} v */ write(v) { if (this.s === v) { this.count++; } else { if (this.count > 0) { writeVarUint(this, this.count - 1); } this.count = 1; this.w(this, v); this.s = v; } } }; var flushUintOptRleEncoder = (encoder) => { if (encoder.count > 0) { writeVarInt(encoder.encoder, encoder.count === 1 ? encoder.s : -encoder.s); if (encoder.count > 1) { writeVarUint(encoder.encoder, encoder.count - 2); } } }; var UintOptRleEncoder = class { constructor() { this.encoder = new Encoder(); this.s = 0; this.count = 0; } /** * @param {number} v */ write(v) { if (this.s === v) { this.count++; } else { flushUintOptRleEncoder(this); this.count = 1; this.s = v; } } /** * Flush the encoded state and transform this to a Uint8Array. * * Note that this should only be called once. */ toUint8Array() { flushUintOptRleEncoder(this); return toUint8Array(this.encoder); } }; var flushIntDiffOptRleEncoder = (encoder) => { if (encoder.count > 0) { const encodedDiff = encoder.diff * 2 + (encoder.count === 1 ? 0 : 1); writeVarInt(encoder.encoder, encodedDiff); if (encoder.count > 1) { writeVarUint(encoder.encoder, encoder.count - 2); } } }; var IntDiffOptRleEncoder = class { constructor() { this.encoder = new Encoder(); this.s = 0; this.count = 0; this.diff = 0; } /** * @param {number} v */ write(v) { if (this.diff === v - this.s) { this.s = v; this.count++; } else { flushIntDiffOptRleEncoder(this); this.count = 1; this.diff = v - this.s; this.s = v; } } /** * Flush the encoded state and transform this to a Uint8Array. * * Note that this should only be called once. */ toUint8Array() { flushIntDiffOptRleEncoder(this); return toUint8Array(this.encoder); } }; var StringEncoder = class { constructor() { this.sarr = []; this.s = ""; this.lensE = new UintOptRleEncoder(); } /** * @param {string} string */ write(string) { this.s += string; if (this.s.length > 19) { this.sarr.push(this.s); this.s = ""; } this.lensE.write(string.length); } toUint8Array() { const encoder = new Encoder(); this.sarr.push(this.s); this.s = ""; writeVarString(encoder, this.sarr.join("")); writeUint8Array(encoder, this.lensE.toUint8Array()); return toUint8Array(encoder); } }; // ../../node_modules/lib0/error.js var create3 = (s) => new Error(s); var methodUnimplemented = () => { throw create3("Method unimplemented"); }; var unexpectedCase = () => { throw create3("Unexpected case"); }; // ../../node_modules/lib0/decoding.js var errorUnexpectedEndOfArray = create3("Unexpected end of array"); var errorIntegerOutOfRange = create3("Integer out of Range"); var Decoder = class { /** * @param {Uint8Array} uint8Array Binary data to decode */ constructor(uint8Array) { this.arr = uint8Array; this.pos = 0; } }; var createDecoder = (uint8Array) => new Decoder(uint8Array); var hasContent = (decoder) => decoder.pos !== decoder.arr.length; var readUint8Array = (decoder, len) => { const view = new Uint8Array(decoder.arr.buffer, decoder.pos + decoder.arr.byteOffset, len); decoder.pos += len; return view; }; var readVarUint8Array = (decoder) => readUint8Array(decoder, readVarUint(decoder)); var readUint8 = (decoder) => decoder.arr[decoder.pos++]; var readVarUint = (decoder) => { let num = 0; let mult = 1; const len = decoder.arr.length; while (decoder.pos < len) { const r = decoder.arr[decoder.pos++]; num = num + (r & BITS7) * mult; mult *= 128; if (r < BIT8) { return num; } if (num > MAX_SAFE_INTEGER) { throw errorIntegerOutOfRange; } } throw errorUnexpectedEndOfArray; }; var readVarInt = (decoder) => { let r = decoder.arr[decoder.pos++]; let num = r & BITS6; let mult = 64; const sign = (r & BIT7) > 0 ? -1 : 1; if ((r & BIT8) === 0) { return sign * num; } const len = decoder.arr.length; while (decoder.pos < len) { r = decoder.arr[decoder.pos++]; num = num + (r & BITS7) * mult; mult *= 128; if (r < BIT8) { return sign * num; } if (num > MAX_SAFE_INTEGER) { throw errorIntegerOutOfRange; } } throw errorUnexpectedEndOfArray; }; var _readVarStringPolyfill = (decoder) => { let remainingLen = readVarUint(decoder); if (remainingLen === 0) { return ""; } else { let encodedString = String.fromCodePoint(readUint8(decoder)); if (--remainingLen < 100) { while (remainingLen--) { encodedString += String.fromCodePoint(readUint8(decoder)); } } else { while (remainingLen > 0) { const nextLen = remainingLen < 1e4 ? remainingLen : 1e4; const bytes = decoder.arr.subarray(decoder.pos, decoder.pos + nextLen); decoder.pos += nextLen; encodedString += String.fromCodePoint.apply( null, /** @type {any} */ bytes ); remainingLen -= nextLen; } } return decodeURIComponent(escape(encodedString)); } }; var _readVarStringNative = (decoder) => ( /** @type any */ utf8TextDecoder.decode(readVarUint8Array(decoder)) ); var readVarString = utf8TextDecoder ? _readVarStringNative : _readVarStringPolyfill; var readFromDataView = (decoder, len) => { const dv = new DataView(decoder.arr.buffer, decoder.arr.byteOffset + decoder.pos, len); decoder.pos += len; return dv; }; var readFloat32 = (decoder) => readFromDataView(decoder, 4).getFloat32(0, false); var readFloat64 = (decoder) => readFromDataView(decoder, 8).getFloat64(0, false); var readBigInt64 = (decoder) => ( /** @type {any} */ readFromDataView(decoder, 8).getBigInt64(0, false) ); var readAnyLookupTable = [ (decoder) => void 0, // CASE 127: undefined (decoder) => null, // CASE 126: null readVarInt, // CASE 125: integer readFloat32, // CASE 124: float32 readFloat64, // CASE 123: float64 readBigInt64, // CASE 122: bigint (decoder) => false, // CASE 121: boolean (false) (decoder) => true, // CASE 120: boolean (true) readVarString, // CASE 119: string (decoder) => { const len = readVarUint(decoder); const obj = {}; for (let i = 0; i < len; i++) { const key = readVarString(decoder); obj[key] = readAny(decoder); } return obj; }, (decoder) => { const len = readVarUint(decoder); const arr = []; for (let i = 0; i < len; i++) { arr.push(readAny(decoder)); } return arr; }, readVarUint8Array // CASE 116: Uint8Array ]; var readAny = (decoder) => readAnyLookupTable[127 - readUint8(decoder)](decoder); var RleDecoder = class extends Decoder { /** * @param {Uint8Array} uint8Array * @param {function(Decoder):T} reader */ constructor(uint8Array, reader) { super(uint8Array); this.reader = reader; this.s = null; this.count = 0; } read() { if (this.count === 0) { this.s = this.reader(this); if (hasContent(this)) { this.count = readVarUint(this) + 1; } else { this.count = -1; } } this.count--; return ( /** @type {T} */ this.s ); } }; var UintOptRleDecoder = class extends Decoder { /** * @param {Uint8Array} uint8Array */ constructor(uint8Array) { super(uint8Array); this.s = 0; this.count = 0; } read() { if (this.count === 0) { this.s = readVarInt(this); const isNegative = isNegativeZero(this.s); this.count = 1; if (isNegative) { this.s = -this.s; this.count = readVarUint(this) + 2; } } this.count--; return ( /** @type {number} */ this.s ); } }; var IntDiffOptRleDecoder = class extends Decoder { /** * @param {Uint8Array} uint8Array */ constructor(uint8Array) { super(uint8Array); this.s = 0; this.count = 0; this.diff = 0; } /** * @return {number} */ read() { if (this.count === 0) { const diff = readVarInt(this); const hasCount = diff & 1; this.diff = floor(diff / 2); this.count = 1; if (hasCount) { this.count = readVarUint(this) + 2; } } this.s += this.diff; this.count--; return this.s; } }; var StringDecoder = class { /** * @param {Uint8Array} uint8Array */ constructor(uint8Array) { this.decoder = new UintOptRleDecoder(uint8Array); this.str = readVarString(this.decoder); this.spos = 0; } /** * @return {string} */ read() { const end = this.spos + this.decoder.read(); const res = this.str.slice(this.spos, end); this.spos = end; return res; } }; // ../../node_modules/lib0/webcrypto.node.js import { webcrypto } from "node:crypto"; var subtle = ( /** @type {any} */ webcrypto.subtle ); var getRandomValues = ( /** @type {any} */ webcrypto.getRandomValues.bind(webcrypto) ); // ../../node_modules/lib0/random.js var uint32 = () => getRandomValues(new Uint32Array(1))[0]; var uuidv4Template = "10000000-1000-4000-8000" + -1e11; var uuidv4 = () => uuidv4Template.replace( /[018]/g, /** @param {number} c */ (c) => (c ^ uint32() & 15 >> c / 4).toString(16) ); // ../../node_modules/lib0/time.js var getUnixTime = Date.now; // ../../node_modules/lib0/promise.js var create4 = (f) => ( /** @type {Promise<T>} */ new Promise(f) ); var all = Promise.all.bind(Promise); // ../../node_modules/lib0/conditions.js var undefinedToNull = (v) => v === void 0 ? null : v; // ../../node_modules/lib0/storage.js var VarStoragePolyfill = class { constructor() { this.map = /* @__PURE__ */ new Map(); } /** * @param {string} key * @param {any} newValue */ setItem(key, newValue) { this.map.set(key, newValue); } /** * @param {string} key */ getItem(key) { return this.map.get(key); } }; var _localStorage = new VarStoragePolyfill(); var usePolyfill = true; try { if (typeof localStorage !== "undefined" && localStorage) { _localStorage = localStorage; usePolyfill = false; } } catch (e) { } var varStorage = _localStorage; // ../../node_modules/lib0/object.js var assign = Object.assign; var keys = Object.keys; var forEach = (obj, f) => { for (const key in obj) { f(obj[key], key); } }; var size = (obj) => keys(obj).length; var isEmpty = (obj) => { for (const _k in obj) { return false; } return true; }; var every = (obj, f) => { for (const key in obj) { if (!f(obj[key], key)) { return false; } } return true; }; var hasProperty = (obj, key) => Object.prototype.hasOwnProperty.call(obj, key); var equalFlat = (a, b) => a === b || size(a) === size(b) && every(a, (val, key) => (val !== void 0 || hasProperty(b, key)) && b[key] === val); var freeze = Object.freeze; var deepFreeze = (o) => { for (const key in o) { const c = o[key]; if (typeof c === "object" || typeof c === "function") { deepFreeze(o[key]); } } return freeze(o); }; // ../../node_modules/lib0/function.js var callAll = (fs, args2, i = 0) => { try { for (; i < fs.length; i++) { fs[i](...args2); } } finally { if (i < fs.length) { callAll(fs, args2, i + 1); } } }; var isOneOf = (value, options) => options.includes(value); // ../../node_modules/lib0/environment.js var isNode = typeof process !== "undefined" && process.release && /node|io\.js/.test(process.release.name) && Object.prototype.toString.call(typeof process !== "undefined" ? process : 0) === "[object process]"; var isMac = typeof navigator !== "undefined" ? /Mac/.test(navigator.platform) : false; var params; var args = []; var computeParams = () => { if (params === void 0) { if (isNode) { params = create(); const pargs = process.argv; let currParamName = null; for (let i = 0; i < pargs.length; i++) { const parg = pargs[i]; if (parg[0] === "-") { if (currParamName !== null) { params.set(currParamName, ""); } currParamName = parg; } else { if (currParamName !== null) { params.set(currParamName, parg); currParamName = null; } else { args.push(parg); } } } if (currParamName !== null) { params.set(currParamName, ""); } } else if (typeof location === "object") { params = create(); (location.search || "?").slice(1).split("&").forEach((kv) => { if (kv.length !== 0) { const [key, value] = kv.split("="); params.set(`--${fromCamelCase(key, "-")}`, value); params.set(`-${fromCamelCase(key, "-")}`, value); } }); } else { params = create(); } } return params; }; var hasParam = (name) => computeParams().has(name); var getVariable = (name) => isNode ? undefinedToNull(process.env[name.toUpperCase().replaceAll("-", "_")]) : undefinedToNull(varStorage.getItem(name)); var hasConf = (name) => hasParam("--" + name) || getVariable(name) !== null; var production = hasConf("production"); var forceColor = isNode && isOneOf(process.env.FORCE_COLOR, ["true", "1", "2"]); var supportsColor = forceColor || !hasParam("--no-colors") && // @todo deprecate --no-colors !hasConf("no-color") && (!isNode || process.stdout.isTTY) && (!isNode || hasParam("--color") || getVariable("COLORTERM") !== null || (getVariable("TERM") || "").includes("color")); // ../../node_modules/lib0/buffer.js var createUint8ArrayFromLen = (len) => new Uint8Array(len); var copyUint8Array = (uint8Array) => { const newBuf = createUint8ArrayFromLen(uint8Array.byteLength); newBuf.set(uint8Array); return newBuf; }; // ../../node_modules/lib0/symbol.js var create5 = Symbol; // ../../node_modules/lib0/logging.common.js var BOLD = create5(); var UNBOLD = create5(); var BLUE = create5(); var GREY = create5(); var GREEN = create5(); var RED = create5(); var PURPLE = create5(); var ORANGE = create5(); var UNCOLOR = create5(); var computeNoColorLoggingArgs = (args2) => { if (args2.length === 1 && args2[0]?.constructor === Function) { args2 = /** @type {Array<string|Symbol|Object|number>} */ /** @type {[function]} */ args2[0](); } const strBuilder = []; const logArgs = []; let i = 0; for (; i < args2.length; i++) { const arg = args2[i]; if (arg === void 0) { break; } else if (arg.constructor === String || arg.constructor === Number) { strBuilder.push(arg); } else if (arg.constructor === Object) { break; } } if (i > 0) { logArgs.push(strBuilder.join("")); } for (; i < args2.length; i++) { const arg = args2[i]; if (!(arg instanceof Symbol)) { logArgs.push(arg); } } return logArgs; }; var lastLoggingTime = getUnixTime(); // ../../node_modules/lib0/logging.node.js var _nodeStyleMap = { [BOLD]: "\x1B[1m", [UNBOLD]: "\x1B[2m", [BLUE]: "\x1B[34m", [GREEN]: "\x1B[32m", [GREY]: "\x1B[37m", [RED]: "\x1B[31m", [PURPLE]: "\x1B[35m", [ORANGE]: "\x1B[38;5;208m", [UNCOLOR]: "\x1B[0m" }; var computeNodeLoggingArgs = (args2) => { if (args2.length === 1 && args2[0]?.constructor === Function) { args2 = /** @type {Array<string|Symbol|Object|number>} */ /** @type {[function]} */ args2[0](); } const strBuilder = []; const logArgs = []; let i = 0; for (; i < args2.length; i++) { const arg = args2[i]; const style = _nodeStyleMap[arg]; if (style !== void 0) { strBuilder.push(style); } else { if (arg === void 0) { break; } else if (arg.constructor === String || arg.constructor === Number) { strBuilder.push(arg); } else { break; } } } if (i > 0) { strBuilder.push("\x1B[0m"); logArgs.push(strBuilder.join("")); } for (; i < args2.length; i++) { const arg = args2[i]; if (!(arg instanceof Symbol)) { logArgs.push(arg); } } return logArgs; }; var computeLoggingArgs = supportsColor ? computeNodeLoggingArgs : computeNoColorLoggingArgs; var print = (...args2) => { console.log(...computeLoggingArgs(args2)); }; var warn = (...args2) => { console.warn(...computeLoggingArgs(args2)); }; // ../../node_modules/lib0/iterator.js var createIterator = (next) => ({ /** * @return {IterableIterator<T>} */ [Symbol.iterator]() { return this; }, // @ts-ignore next }); var iteratorFilter = (iterator, filter) => createIterator(() => { let res; do { res = iterator.next(); } while (!res.done && !filter(res.value)); return res; }); var iteratorMap = (iterator, fmap) => createIterator(() => { const { done, value } = iterator.next(); return { done, value: done ? void 0 : fmap(value) }; }); // ../../node_modules/yjs/dist/yjs.mjs var DeleteItem = class { /** * @param {number} clock * @param {number} len */ constructor(clock, len) { this.clock = clock; this.len = len; } }; var DeleteSet = class { constructor() { this.clients = /* @__PURE__ */ new Map(); } }; var iterateDeletedStructs = (transaction, ds, f) => ds.clients.forEach((deletes, clientid) => { const structs = ( /** @type {Array<GC|Item>} */ transaction.doc.store.clients.get(clientid) ); for (let i = 0; i < deletes.length; i++) { const del = deletes[i]; iterateStructs(transaction, structs, del.clock, del.len, f); } }); var findIndexDS = (dis, clock) => { let left = 0; let right = dis.length - 1; while (left <= right) { const midindex = floor((left + right) / 2); const mid = dis[midindex]; const midclock = mid.clock; if (midclock <= clock) { if (clock < midclock + mid.len) { return midindex; } left = midindex + 1; } else { right = midindex - 1; } } return null; }; var isDeleted = (ds, id2) => { const dis = ds.clients.get(id2.client); return dis !== void 0 && findIndexDS(dis, id2.clock) !== null; }; var sortAndMergeDeleteSet = (ds) => { ds.clients.forEach((dels) => { dels.sort((a, b) => a.clock - b.clock); let i, j; for (i = 1, j = 1; i < dels.length; i++) { const left = dels[j - 1]; const right = dels[i]; if (left.clock + left.len >= right.clock) { left.len = max(left.len, right.clock + right.len - left.clock); } else { if (j < i) { dels[j] = right; } j++; } } dels.length = j; }); }; var mergeDeleteSets = (dss) => { const merged = new DeleteSet(); for (let dssI = 0; dssI < dss.length; dssI++) { dss[dssI].clients.forEach((delsLeft, client) => { if (!merged.clients.has(client)) { const dels = delsLeft.slice(); for (let i = dssI + 1; i < dss.length; i++) { appendTo(dels, dss[i].clients.get(client) || []); } merged.clients.set(client, dels); } }); } sortAndMergeDeleteSet(merged); return merged; }; var addToDeleteSet = (ds, client, clock, length2) => { setIfUndefined(ds.clients, client, () => ( /** @type {Array<DeleteItem>} */ [] )).push(new DeleteItem(clock, length2)); }; var createDeleteSet = () => new DeleteSet(); var writeDeleteSet = (encoder, ds) => { writeVarUint(encoder.restEncoder, ds.clients.size); from(ds.clients.entries()).sort((a, b) => b[0] - a[0]).forEach(([client, dsitems]) => { encoder.resetDsCurVal(); writeVarUint(encoder.restEncoder, client); const len = dsitems.length; writeVarUint(encoder.restEncoder, len); for (let i = 0; i < len; i++) { const item = dsitems[i]; encoder.writeDsClock(item.clock); encoder.writeDsLen(item.len); } }); }; var readDeleteSet = (decoder) => { const ds = new DeleteSet(); const numClients = readVarUint(decoder.restDecoder); for (let i = 0; i < numClients; i++) { decoder.resetDsCurVal(); const client = readVarUint(decoder.restDecoder); const numberOfDeletes = readVarUint(decoder.restDecoder); if (numberOfDeletes > 0) { const dsField = setIfUndefined(ds.clients, client, () => ( /** @type {Array<DeleteItem>} */ [] )); for (let i2 = 0; i2 < numberOfDeletes; i2++) { dsField.push(new DeleteItem(decoder.readDsClock(), decoder.readDsLen())); } } } return ds; }; var readAndApplyDeleteSet = (decoder, transaction, store) => { const unappliedDS = new DeleteSet(); const numClients = readVarUint(decoder.restDecoder); for (let i = 0; i < numClients; i++) { decoder.resetDsCurVal(); const client = readVarUint(decoder.restDecoder); const numberOfDeletes = readVarUint(decoder.restDecoder); const structs = store.clients.get(client) || []; const state = getState(store, client); for (let i2 = 0; i2 < numberOfDeletes; i2++) { const clock = decoder.readDsClock(); const clockEnd = clock + decoder.readDsLen(); if (clock < state) { if (state < clockEnd) { addToDeleteSet(unappliedDS, client, state, clockEnd - state); } let index = findIndexSS(structs, clock); let struct = structs[index]; if (!struct.deleted && struct.id.clock < clock) { structs.splice(index + 1, 0, splitItem(transaction, struct, clock - struct.id.clock)); index++; } while (index < structs.length) { struct = structs[index++]; if (struct.id.clock < clockEnd) { if (!struct.deleted) { if (clockEnd < struct.id.clock + struct.length) { structs.splice(index, 0, splitItem(transaction, struct, clockEnd - struct.id.clock)); } struct.delete(transaction); } } else { break; } } } else { addToDeleteSet(unappliedDS, client, clock, clockEnd - clock); } } } if (unappliedDS.clients.size > 0) { const ds = new UpdateEncoderV2(); writeVarUint(ds.restEncoder, 0); writeDeleteSet(ds, unappliedDS); return ds.toUint8Array(); } return null; }; var generateNewClientId = uint32; var Doc = class _Doc extends ObservableV2 { /** * @param {DocOpts} opts configuration */ constructor({ guid = uuidv4(), collectionid = null, gc = true, gcFilter = () => true, meta = null, autoLoad = false, shouldLoad = true } = {}) { super(); this.gc = gc; this.gcFilter = gcFilter; this.clientID = generateNewClientId(); this.guid = guid; this.collectionid = collectionid; this.share = /* @__PURE__ */ new Map(); this.store = new StructStore(); this._transaction = null; this._transactionCleanups = []; this.subdocs = /* @__PURE__ */ new Set(); this._item = null; this.shouldLoad = shouldLoad; this.autoLoad = autoLoad; this.meta = meta; this.isLoaded = false; this.isSynced = false; this.isDestroyed = false; this.whenLoaded = create4((resolve) => { this.on("load", () => { this.isLoaded = true; resolve(this); }); }); const provideSyncedPromise = () => create4((resolve) => { const eventHandler = (isSynced) => { if (isSynced === void 0 || isSynced === true) { this.off("sync", eventHandler); resolve(); } }; this.on("sync", eventHandler); }); this.on("sync", (isSynced) => { if (isSynced === false && this.isSynced) { this.whenSynced = provideSyncedPromise(); } this.isSynced = isSynced === void 0 || isSynced === true; if (this.isSynced && !this.isLoaded) { this.emit("load", [this]); } }); this.whenSynced = provideSyncedPromise(); } /** * Notify the parent document that you request to load data into this subdocument (if it is a subdocument). * * `load()` might be used in the future to request any provider to load the most current data. * * It is safe to call `load()` multiple times. */ load() { const item = this._item; if (item !== null && !this.shouldLoad) { transact( /** @type {any} */ item.parent.doc, (transaction) => { transaction.subdocsLoaded.add(this); }, null, true ); } this.shouldLoad = true; } getSubdocs() { return this.subdocs; } getSubdocGuids() { return new Set(from(this.subdocs).map((doc) => doc.guid)); } /** * Changes that happen inside of a transaction are bundled. This means that * the observer fires _after_ the transaction is finished and that all changes * that happened inside of the transaction are sent as one message to the * other peers. * * @template T * @param {function(Transaction):T} f The function that should be executed as a transaction * @param {any} [origin] Origin of who started the transaction. Will be stored on transaction.origin * @return T * * @public */ transact(f, origin = null) { return transact(this, f, origin); } /** * Define a shared data type. * * Multiple calls of `ydoc.get(name, TypeConstructor)` yield the same result * and do not overwrite each other. I.e. * `ydoc.get(name, Y.Array) === ydoc.get(name, Y.Array)` * * After this method is called, the type is also available on `ydoc.share.get(name)`. * * *Best Practices:* * Define all types right after the Y.Doc instance is created and store them in a separate object. * Also use the typed methods `getText(name)`, `getArray(name)`, .. * * @template {typeof AbstractType<any>} Type * @example * const ydoc = new Y.Doc(..) * const appState = { * document: ydoc.getText('document') * comments: ydoc.getArray('comments') * } * * @param {string} name * @param {Type} TypeConstructor The constructor of the type definition. E.g. Y.Text, Y.Array, Y.Map, ... * @return {InstanceType<Type>} The created type. Constructed with TypeConstructor * * @public */ get(name, TypeConstructor = ( /** @type {any} */ AbstractType )) { const type = setIfUndefined(this.share, name, () => { const t = new TypeConstructor(); t._integrate(this, null); return t; }); const Constr = type.constructor; if (TypeConstructor !== AbstractType && Constr !== TypeConstructor) { if (Constr === AbstractType) { const t = new TypeConstructor(); t._map = type._map; type._map.forEach( /** @param {Item?} n */ (n) => { for (; n !== null; n = n.left) { n.parent = t; } } ); t._start = type._start; for (let n = t._start; n !== null; n = n.right) { n.parent = t; } t._length = type._length; this.share.set(name, t); t._integrate(this, null); return ( /** @type {InstanceType<Type>} */ t ); } else { throw new Error(`Type with the name ${name} has already been defined with a different constructor`); } } return ( /** @type {InstanceType<Type>} */ type ); } /** * @template T * @param {string} [name] * @return {YArray<T>} * * @public */ getArray(name = "") { return ( /** @type {YArray<T>} */ this.get(name, YArray) ); } /** * @param {string} [name] * @return {YText} * * @public */ getText(name = "") { return this.get(name, YText); } /** * @template T * @param {string} [name] * @return {YMap<T>} * * @public */ getMap(name = "") { return ( /** @type {YMap<T>} */ this.get(name, YMap) ); } /** * @param {string} [name] * @return {YXmlElement} * * @public */ getXmlElement(name = "") { return ( /** @type {YXmlElement<{[key:string]:string}>} */ this.get(name, YXmlElement) ); } /** * @param {string} [name] * @return {YXmlFragment} * * @public */ getXmlFragment(name = "") { return this.get(name, YXmlFragment); } /** * Converts the entire document into a js object, recursively traversing each yjs type * Doesn't log types that have not been defined (using ydoc.getType(..)). * * @deprecated Do not use this method and rather call toJSON directly on the shared types. * * @return {Object<string, any>} */ toJSON() { const doc = {}; this.share.forEach((value, key) => { doc[key] = value.toJSON(); }); return doc; } /** * Emit `destroy` event and unregister all event handlers. */ destroy() { this.isDestroyed = true; from(this.subdocs).forEach((subdoc) => subdoc.destroy()); const item = this._item; if (item !== null) { this._item = null; const content = ( /** @type {ContentDoc} */ item.content ); content.doc = new _Doc({ guid: this.guid, ...content.opts, shouldLoad: false }); content.doc._item = item; transact( /** @type {any} */ item.parent.doc, (transaction) => { const doc = content.doc; if (!item.deleted) { transaction.subdocsAdded.add(doc); } transaction.subdocsRemoved.add(this); }, null, true ); } this.emit("destroyed", [true]); this.emit("destroy", [this]); super.destroy(); } }; var DSDecoderV1 = class { /** * @param {decoding.Decoder} decoder */ constructor(decoder) { this.restDecoder = decoder; } resetDsCurVal() { } /** * @return {number} */ readDsClock() { return readVarUint(this.restDecoder); } /** * @return {number} */ readDsLen() { return readVarUint(this.restDecoder); } }; var UpdateDecoderV1 = class extends DSDecoderV1 { /** * @return {ID} */ readLeftID() { return createID(readVarUint(this.restDecoder), readVarUint(this.restDecoder)); } /** * @return {ID} */ readRightID() { return createID(readVarUint(this.restDecoder), readVarUint(this.restDecoder)); } /** * Read the next client id. * Use this in favor of readID whenever possible to reduce the number of objects created. */ readClient() { return readVarUint(this.restDecoder); } /** * @return {number} info An unsigned 8-bit integer */ readInfo() { return readUint8(this.restDecoder); } /** * @return {string} */ readString() { return readVarString(this.restDecoder); } /** * @return {boolean} isKey */ readParentInfo() { return readVarUint(this.restDecoder) === 1; } /** * @return {number} info An unsigned 8-bit integer */ readTypeRef() { return readVarUint(this.restDecoder); } /** * Write len of a struct - well suited for Opt RLE encoder. * * @return {number} len */ readLen() { return readVarUint(this.restDecoder); } /** * @return {any} */ readAny() { return readAny(this.restDecoder); } /** * @return {Uint8Array} */ readBuf() { return copyUint8Array(readVarUint8Array(this.restDecoder)); } /** * Legacy implementation uses JSON parse. We use any-decoding in v2. * * @return {any} */ readJSON() { return JSON.parse(readVarString(this.restDecoder)); } /** * @return {string} */ readKey() { return readVarString(this.restDecoder); } }; var DSDecoderV2 = class { /** * @param {decoding.Decoder} decoder */ constructor(decoder) { this.dsCurrVal = 0; this.restDecoder = decoder; } resetDsCurVal() { this.dsCurrVal = 0; } /** * @return {number} */ readDsClock() { this.dsCurrVal += readVarUint(this.restDecoder); return this.dsCurrVal; } /** * @return {number} */ readDsLen() { const diff = readVarUint(this.restDecoder) + 1; this.dsCurrVal += diff; return diff; } }; var UpdateDecoderV2 = class extends DSDecoderV2 { /** * @param {decoding.Decoder} decoder */ constructor(decoder) { super(decoder); this.keys = []; readVarUint(decoder); this.keyClockDecoder = new IntDiffOptRleDecoder(readVarUint8Array(decoder)); this.clientDecoder = new UintOptRleDecoder(readVarUint8Array(decoder)); this.leftClockDecoder = new IntDiffOptRleDecoder(readVarUint8Array(decoder)); this.rightClockDecoder = new IntDiffOptRleDecoder(readVarUint8Array(decoder)); this.infoDecoder = new RleDecoder(readVarUint8Array(decoder), readUint8); this.stringDecoder = new StringDecoder(readVarUint8Array(decoder)); this.parentInfoDecoder = new RleDecoder(readVarUint8Array(decoder), readUint8); this.typeRefDecoder = new UintOptRleDecoder(readVarUint8Array(decoder)); this.lenDecoder = new UintOptRleDecoder(readVarUint8Array(decoder)); } /** * @return {ID} */ readLeftID() { return new ID(this.clientDecoder.read(), this.leftClockDecoder.read()); } /** * @return {ID} */ readRightID() { return new ID(this.clientDecoder.read(), this.rightClockDecoder.read()); } /** * Read the next client id. * Use this in favor of readID whenever possible to reduce the number of objects created. */ readClient() { return this.clientDecoder.read(); } /** * @return {number} info An unsigned 8-bit integer */ readInfo() { return ( /** @type {number} */ this.infoDecoder.read() ); } /** * @return {string} */ readString() { return this.stringDecoder.read(); } /** * @return {boolean} */ readParentInfo() { return this.parentInfoDecoder.read() === 1; } /** * @return {number} An unsigned 8-bit integer */ readTypeRef() { return this.typeRefDecoder.read(); } /** * Write len of a struct - well suited for Opt RLE encoder. * * @return {number} */ readLen() { return this.lenDecoder.read(); } /** * @return {any} */ readAny() { return readAny(this.restDecoder); } /** * @return {Uint8Array} */ readBuf() { return readVarUint8Array(this.restDecoder); } /** * This is mainly here for legacy purposes. * * Initial we incoded objects using JSON. Now we use the much faster lib0/any-encoder. This method mainly exists for legacy purposes for the v1 encoder. * * @return {any} */ readJSON() { return readAny(this.restDecoder); } /** * @return {string} */ readKey() { const keyClock = this.keyClockDecoder.read(); if (keyClock < this.keys.length) { return this.keys[keyClock]; } else { const key = this.stringDecoder.read(); this.keys.push(key); return key; } } }; var DSEncoderV1 = class { constructor() { this.restEncoder = createEncoder(); } toUint8Array() { return toUint8Array(this.restEncoder); } resetDsCurVal() { } /** * @param {number} clock */ writeDsClock(clock) { writeVarUint(this.restEncoder, clock); } /** * @param {number} len */ writeDsLen(len) { writeVarUint(this.restEncoder, len); } }; var UpdateEncoderV1 = class extends DSEncoderV1 { /** * @param {ID} id */ writeLeftID(id2) { writeVarUint(this.restEncoder, id2.client); writeVarUint(this.restEncoder, id2.clock); } /** * @param {ID} id */ writeRightID(id2) { writeVarUint(this.restEncoder, id2.client); writeVarUint(this.restEncoder, id2.clock); } /** * Use writeClient and writeClock instead of writeID if possible. * @param {number} client */ writeClient(client) { writeVarUint(this.restEncoder, client); } /** * @param {number} info An unsigned 8-bit integer */ writeInfo(info) { writeUint8(this.restEncoder, info); } /** * @param {string} s */ writeString(s) { writeVarString(this.restEncoder, s); } /** * @param {boolean} isYKey */ writeParentInfo(isYKey) { writeVarUint(this.restEncoder, isYKey ? 1 : 0); } /** * @param {number} info An unsigned 8-bit integer */ writeTypeRef(info) { writeVarUint(this.restEncoder, info); } /** * Write len of a struct - well suited for Opt RLE encoder. * * @param {number} len */ writeLen(len) { writeVarUint(this.restEncoder, len); } /** * @param {any} any */ writeAny(any2) { writeAny(this.restEncoder, any2); } /** * @param {Uint8Array} buf */ writeBuf(buf) { writeVarUint8Array(this.restEncoder, buf); } /** * @param {any} embed */ writeJSON(embed) { writeVarString(this.restEncoder, JSON.stringify(embed)); } /** * @param {string} key */ writeKey(key) { writeVarString(this.restEncoder, key); } }; var DSEncoderV2 = class { constructor() { this.restEncoder = createEncoder(); this.dsCurrVal = 0; } toUint8Array() { return toUint8Array(this.restEncoder); } resetDsCurVal() { this.dsCurrVal = 0; } /** * @param {number} clock */ writeDsClock(clock) { const diff = clock - this.dsCurrVal; this.dsCurrVal = clock; writeVarUint(this.restEncoder, diff); } /** * @param {number} len */ writeDsLen(len) { if (len === 0) { unexpectedCase(); } writeVarUint(this.restEncoder, len - 1); this.dsCurrVal += len; } }; var UpdateEncoderV2 = class extends DSEncoderV2 { constructor() { super(); this.keyMap = /* @__PURE__ */ new Map(); this.keyClock = 0; this.keyClockEncoder = new IntDiffOptRleEncoder(); this.clientEncoder = new UintOptRleEncoder(); this.leftClockEncoder = new IntDiffOptRleEncoder(); this.rightClockEncoder = new IntDiffOptRleEncoder(); this.infoEncoder = new RleEncoder(writeUint8); this.stringEncoder = new StringEncoder(); this.parentInfoEncoder = new RleEncoder(writeUint8); this.typeRefEncoder = new UintOptRleEncoder(); this.lenEncoder = new UintOptRleEncoder(); } toUint8Array() { const encoder = createEncoder(); writeVarUint(encoder, 0); writeVarUint8Array(encoder, this.keyClockEncoder.toUint8Array()); writeVarUint8Array(encoder, this.clientEncoder.toUint8Array()); writeVarUint8Array(encoder, this.leftClockEncoder.toUint8Array()); writeVarUint8Array(encoder, this.rightClockEncoder.toUint8Array()); writeVarUint8Array(encoder, toUint8Array(this.infoEncoder)); writeVarUint8Array(encoder, this.stringEncoder.toUint8Array()); writeVarUint8Array(encoder, toUint8Array(this.parentInfoEncoder)); writeVarUint8Array(encoder, this.typeRefEncoder.toUint8Array()); writeVarUint8Array(encoder, this.lenEncoder.toUint8Array()); writeUint8Array(encoder, toUint8Array(this.restEncoder)); return toUint8Array(encoder); } /** * @param {ID} id */ writeLeftID(id2) { this.clientEncoder.write(id2.client); this.leftClockEncoder.write(id2.clock); } /** * @param {ID} id */ writeRightID(id2) { this.clientEncoder.write(id2.client); this.rightClockEncod