| 1 | // generated by crates/engine/extension-host/build.mjs from src/shims/avatars.ts; do not edit. |
| 2 | |
| 3 | // node_modules/@deepseek-ai/cosmokit/lib/index.js |
| 4 | function isNullable(value) { |
| 5 | return value === null || value === void 0; |
| 6 | } |
| 7 | function defineProperty(object, key, value) { |
| 8 | return Object.defineProperty(object, key, { |
| 9 | writable: true, |
| 10 | value, |
| 11 | enumerable: false |
| 12 | }); |
| 13 | } |
| 14 | function is(type, value) { |
| 15 | if (arguments.length === 1) return (value2) => is(type, value2); |
| 16 | return type in globalThis && value instanceof globalThis[type] || Object.prototype.toString.call(value).slice(8, -1) === type; |
| 17 | } |
| 18 | function isArrayBufferLike(value) { |
| 19 | return is("ArrayBuffer", value) || is("SharedArrayBuffer", value); |
| 20 | } |
| 21 | function isArrayBufferSource(value) { |
| 22 | return isArrayBufferLike(value) || ArrayBuffer.isView(value); |
| 23 | } |
| 24 | var Binary; |
| 25 | (function(Binary2) { |
| 26 | Binary2.is = isArrayBufferLike; |
| 27 | Binary2.isSource = isArrayBufferSource; |
| 28 | function fromSource(source) { |
| 29 | if (ArrayBuffer.isView(source)) return source.buffer.slice(source.byteOffset, source.byteOffset + source.byteLength); |
| 30 | else return source; |
| 31 | } |
| 32 | Binary2.fromSource = fromSource; |
| 33 | function toBase64(source) { |
| 34 | source = fromSource(source); |
| 35 | if (typeof Buffer !== "undefined") return Buffer.from(source).toString("base64"); |
| 36 | let binary = ""; |
| 37 | const bytes = new Uint8Array(source); |
| 38 | for (let i = 0; i < bytes.byteLength; i++) binary += String.fromCharCode(bytes[i]); |
| 39 | return btoa(binary); |
| 40 | } |
| 41 | Binary2.toBase64 = toBase64; |
| 42 | function fromBase64(source) { |
| 43 | if (typeof Buffer !== "undefined") return fromSource(Buffer.from(source, "base64")); |
| 44 | return Uint8Array.from(atob(source), (c) => c.charCodeAt(0)); |
| 45 | } |
| 46 | Binary2.fromBase64 = fromBase64; |
| 47 | function toHex(source) { |
| 48 | source = fromSource(source); |
| 49 | if (typeof Buffer !== "undefined") return Buffer.from(source).toString("hex"); |
| 50 | return Array.from(new Uint8Array(source), (byte) => byte.toString(16).padStart(2, "0")).join(""); |
| 51 | } |
| 52 | Binary2.toHex = toHex; |
| 53 | function fromHex(source) { |
| 54 | if (typeof Buffer !== "undefined") return fromSource(Buffer.from(source, "hex")); |
| 55 | const hex = source.length % 2 === 0 ? source : source.slice(0, source.length - 1); |
| 56 | const buffer = []; |
| 57 | for (let i = 0; i < hex.length; i += 2) buffer.push(parseInt(`${hex[i]}${hex[i + 1]}`, 16)); |
| 58 | return Uint8Array.from(buffer).buffer; |
| 59 | } |
| 60 | Binary2.fromHex = fromHex; |
| 61 | })(Binary || (Binary = {})); |
| 62 | var base64ToArrayBuffer = Binary.fromBase64; |
| 63 | var arrayBufferToBase64 = Binary.toBase64; |
| 64 | var hexToArrayBuffer = Binary.fromHex; |
| 65 | var arrayBufferToHex = Binary.toHex; |
| 66 | function tokenize(source, delimiters, delimiter) { |
| 67 | const output = []; |
| 68 | let state = 0; |
| 69 | for (let i = 0; i < source.length; i++) { |
| 70 | const code = source.charCodeAt(i); |
| 71 | if (code >= 65 && code <= 90) { |
| 72 | if (state === 1) { |
| 73 | const next = source.charCodeAt(i + 1); |
| 74 | if (next >= 97 && next <= 122) output.push(delimiter); |
| 75 | output.push(code + 32); |
| 76 | } else { |
| 77 | if (state !== 0) output.push(delimiter); |
| 78 | output.push(code + 32); |
| 79 | } |
| 80 | state = 1; |
| 81 | } else if (code >= 97 && code <= 122) { |
| 82 | output.push(code); |
| 83 | state = 2; |
| 84 | } else if (delimiters.includes(code)) { |
| 85 | if (state !== 0) output.push(delimiter); |
| 86 | state = 0; |
| 87 | } else output.push(code); |
| 88 | } |
| 89 | return String.fromCharCode(...output); |
| 90 | } |
| 91 | function paramCase(source) { |
| 92 | return tokenize(source, [45, 95], 45); |
| 93 | } |
| 94 | var hyphenate = paramCase; |
| 95 | var Time; |
| 96 | (function(Time2) { |
| 97 | Time2.millisecond = 1; |
| 98 | Time2.second = 1e3; |
| 99 | Time2.minute = Time2.second * 60; |
| 100 | Time2.hour = Time2.minute * 60; |
| 101 | Time2.day = Time2.hour * 24; |
| 102 | Time2.week = Time2.day * 7; |
| 103 | let timezoneOffset = (/* @__PURE__ */ new Date()).getTimezoneOffset(); |
| 104 | function setTimezoneOffset(offset) { |
| 105 | timezoneOffset = offset; |
| 106 | } |
| 107 | Time2.setTimezoneOffset = setTimezoneOffset; |
| 108 | function getTimezoneOffset() { |
| 109 | return timezoneOffset; |
| 110 | } |
| 111 | Time2.getTimezoneOffset = getTimezoneOffset; |
| 112 | function getDateNumber(date = /* @__PURE__ */ new Date(), offset) { |
| 113 | if (typeof date === "number") date = new Date(date); |
| 114 | if (offset === void 0) offset = timezoneOffset; |
| 115 | return Math.floor((date.valueOf() / Time2.minute - offset) / 1440); |
| 116 | } |
| 117 | Time2.getDateNumber = getDateNumber; |
| 118 | function fromDateNumber(value, offset) { |
| 119 | const date = new Date(value * Time2.day); |
| 120 | if (offset === void 0) offset = timezoneOffset; |
| 121 | return new Date(+date + offset * Time2.minute); |
| 122 | } |
| 123 | Time2.fromDateNumber = fromDateNumber; |
| 124 | const numeric = /\d+(?:\.\d+)?/.source; |
| 125 | const timeRegExp = new RegExp(`^${[ |
| 126 | "w(?:eek(?:s)?)?", |
| 127 | "d(?:ay(?:s)?)?", |
| 128 | "h(?:our(?:s)?)?", |
| 129 | "m(?:in(?:ute)?(?:s)?)?", |
| 130 | "s(?:ec(?:ond)?(?:s)?)?" |
| 131 | ].map((unit) => `(${numeric}${unit})?`).join("")}$`); |
| 132 | function parseTime(source) { |
| 133 | const capture = timeRegExp.exec(source); |
| 134 | if (!capture) return 0; |
| 135 | return (parseFloat(capture[1]) * Time2.week || 0) + (parseFloat(capture[2]) * Time2.day || 0) + (parseFloat(capture[3]) * Time2.hour || 0) + (parseFloat(capture[4]) * Time2.minute || 0) + (parseFloat(capture[5]) * Time2.second || 0); |
| 136 | } |
| 137 | Time2.parseTime = parseTime; |
| 138 | function parseDate(date) { |
| 139 | const parsed = parseTime(date); |
| 140 | if (parsed) date = Date.now() + parsed; |
| 141 | else if (/^\d{1,2}(:\d{1,2}){1,2}$/.test(date)) date = `${(/* @__PURE__ */ new Date()).toLocaleDateString()}-${date}`; |
| 142 | else if (/^\d{1,2}-\d{1,2}-\d{1,2}(:\d{1,2}){1,2}$/.test(date)) date = `${(/* @__PURE__ */ new Date()).getFullYear()}-${date}`; |
| 143 | return date ? new Date(date) : /* @__PURE__ */ new Date(); |
| 144 | } |
| 145 | Time2.parseDate = parseDate; |
| 146 | function format(ms) { |
| 147 | const abs = Math.abs(ms); |
| 148 | if (abs >= Time2.day - Time2.hour / 2) return Math.round(ms / Time2.day) + "d"; |
| 149 | else if (abs >= Time2.hour - Time2.minute / 2) return Math.round(ms / Time2.hour) + "h"; |
| 150 | else if (abs >= Time2.minute - Time2.second / 2) return Math.round(ms / Time2.minute) + "m"; |
| 151 | else if (abs >= Time2.second) return Math.round(ms / Time2.second) + "s"; |
| 152 | return ms + "ms"; |
| 153 | } |
| 154 | Time2.format = format; |
| 155 | function toDigits(source, length = 2) { |
| 156 | return source.toString().padStart(length, "0"); |
| 157 | } |
| 158 | Time2.toDigits = toDigits; |
| 159 | function template(template2, time = /* @__PURE__ */ new Date()) { |
| 160 | return template2.replace("yyyy", time.getFullYear().toString()).replace("yy", time.getFullYear().toString().slice(2)).replace("MM", toDigits(time.getMonth() + 1)).replace("dd", toDigits(time.getDate())).replace("hh", toDigits(time.getHours())).replace("mm", toDigits(time.getMinutes())).replace("ss", toDigits(time.getSeconds())).replace("SSS", toDigits(time.getMilliseconds(), 3)); |
| 161 | } |
| 162 | Time2.template = template; |
| 163 | })(Time || (Time = {})); |
| 164 | |
| 165 | // node_modules/@deepseek-ai/cordis/lib/index.js |
| 166 | var DisposableList = class { |
| 167 | sn = 0; |
| 168 | map = /* @__PURE__ */ new Map(); |
| 169 | weak = /* @__PURE__ */ new WeakMap(); |
| 170 | get length() { |
| 171 | return this.map.size; |
| 172 | } |
| 173 | push(value) { |
| 174 | const sn = ++this.sn; |
| 175 | this.map.set(sn, value); |
| 176 | this.weak.set(value, sn); |
| 177 | return () => this.map.delete(sn); |
| 178 | } |
| 179 | delete(value) { |
| 180 | const sn = this.weak.get(value); |
| 181 | if (!sn) return false; |
| 182 | return this.map.delete(sn); |
| 183 | } |
| 184 | clear() { |
| 185 | const values = [...this.map.values()]; |
| 186 | this.map.clear(); |
| 187 | return values.reverse(); |
| 188 | } |
| 189 | [Symbol.iterator]() { |
| 190 | return this.map.values(); |
| 191 | } |
| 192 | [/* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom")]() { |
| 193 | return [...this]; |
| 194 | } |
| 195 | }; |
| 196 | var symbols = { |
| 197 | shadow: /* @__PURE__ */ Symbol.for("cordis.shadow"), |
| 198 | caller: /* @__PURE__ */ Symbol.for("cordis.caller"), |
| 199 | receiver: /* @__PURE__ */ Symbol.for("cordis.receiver"), |
| 200 | original: /* @__PURE__ */ Symbol.for("cordis.original"), |
| 201 | metadata: /* @__PURE__ */ Symbol.for("cordis.metadata"), |
| 202 | initHooks: /* @__PURE__ */ Symbol.for("cordis.initHooks"), |
| 203 | checkProto: /* @__PURE__ */ Symbol.for("cordis.checkProto"), |
| 204 | effect: /* @__PURE__ */ Symbol.for("cordis.effect"), |
| 205 | filter: /* @__PURE__ */ Symbol.for("cordis.filter"), |
| 206 | isolate: /* @__PURE__ */ Symbol.for("cordis.isolate"), |
| 207 | intercept: /* @__PURE__ */ Symbol.for("cordis.intercept"), |
| 208 | init: /* @__PURE__ */ Symbol.for("cordis.init"), |
| 209 | check: /* @__PURE__ */ Symbol.for("cordis.check"), |
| 210 | config: /* @__PURE__ */ Symbol.for("cordis.config"), |
| 211 | invoke: /* @__PURE__ */ Symbol.for("cordis.invoke"), |
| 212 | extend: /* @__PURE__ */ Symbol.for("cordis.extend"), |
| 213 | tracker: /* @__PURE__ */ Symbol.for("cordis.tracker"), |
| 214 | resolveConfig: /* @__PURE__ */ Symbol.for("cordis.resolveConfig") |
| 215 | }; |
| 216 | var GeneratorFunction = function* () { |
| 217 | }.constructor; |
| 218 | var AsyncGeneratorFunction = async function* () { |
| 219 | }.constructor; |
| 220 | function isConstructor(func) { |
| 221 | if (!func.prototype) return false; |
| 222 | if (func instanceof GeneratorFunction) return false; |
| 223 | if (AsyncGeneratorFunction !== Function && func instanceof AsyncGeneratorFunction) return false; |
| 224 | return true; |
| 225 | } |
| 226 | function joinPrototype(proto1, proto2) { |
| 227 | if (proto1 === Object.prototype) return proto2; |
| 228 | const result = Object.create(joinPrototype(Object.getPrototypeOf(proto1), proto2)); |
| 229 | for (const key of Reflect.ownKeys(proto1)) Object.defineProperty(result, key, Object.getOwnPropertyDescriptor(proto1, key)); |
| 230 | return result; |
| 231 | } |
| 232 | function isObject(value) { |
| 233 | return value && (typeof value === "object" || typeof value === "function"); |
| 234 | } |
| 235 | function getPropertyDescriptor(target, prop) { |
| 236 | let proto = target; |
| 237 | while (proto) { |
| 238 | const desc = Reflect.getOwnPropertyDescriptor(proto, prop); |
| 239 | if (desc) return desc; |
| 240 | proto = Object.getPrototypeOf(proto); |
| 241 | } |
| 242 | } |
| 243 | function getTraceable(ctx, value) { |
| 244 | if (!isObject(value)) return value; |
| 245 | if (Object.hasOwn(value, symbols.shadow)) return Object.getPrototypeOf(value); |
| 246 | const tracker = value[symbols.tracker]; |
| 247 | if (!tracker) return value; |
| 248 | return createTraceable(ctx, value, tracker); |
| 249 | } |
| 250 | function withProps(target, props) { |
| 251 | if (!props) return target; |
| 252 | return new Proxy(target, { |
| 253 | get: (target2, prop, receiver) => { |
| 254 | if (prop in props && prop !== "constructor") return Reflect.get(props, prop, receiver); |
| 255 | return Reflect.get(target2, prop, receiver); |
| 256 | }, |
| 257 | set: (target2, prop, value, receiver) => { |
| 258 | if (prop in props && prop !== "constructor") return Reflect.set(props, prop, value, receiver); |
| 259 | return Reflect.set(target2, prop, value, receiver); |
| 260 | } |
| 261 | }); |
| 262 | } |
| 263 | function withProp(target, prop, value) { |
| 264 | return withProps(target, Object.defineProperty(/* @__PURE__ */ Object.create(null), prop, { |
| 265 | value, |
| 266 | writable: false |
| 267 | })); |
| 268 | } |
| 269 | function createShadow(useSite, target, property, receiver) { |
| 270 | if (!property) return receiver; |
| 271 | const value = getPropertyDescriptor(target, property)?.value; |
| 272 | if (!value) return receiver; |
| 273 | const defSite = value[symbols.shadow] ?? value; |
| 274 | return withProp(receiver, property, useSite.extend({ [symbols.shadow]: defSite })); |
| 275 | } |
| 276 | function createShadowMethod(ctx, value, outer, shadow) { |
| 277 | return new Proxy(value, { apply: (target, thisArg, args) => { |
| 278 | if (thisArg === outer) thisArg = shadow; |
| 279 | return getTraceable(ctx, Reflect.apply(target, thisArg, args)); |
| 280 | } }); |
| 281 | } |
| 282 | function createTraceable(ctx, value, tracker) { |
| 283 | const defSite = ctx[symbols.shadow] ?? ctx; |
| 284 | const useSite = ctx[symbols.shadow] ? Object.getPrototypeOf(ctx) : ctx; |
| 285 | const proxy = new Proxy(value, { |
| 286 | get: (target, prop, receiver) => { |
| 287 | if (prop === symbols.original) return target; |
| 288 | if (prop === symbols.caller) return defSite; |
| 289 | if (prop === tracker.property) return useSite; |
| 290 | if (typeof prop === "symbol") return Reflect.get(target, prop, receiver); |
| 291 | if (tracker.associate && useSite.reflect.props[`${tracker.associate}.${prop}`]) return Reflect.get(ctx, `${tracker.associate}.${prop}`, withProp(ctx, symbols.receiver, receiver)); |
| 292 | let shadow, innerValue; |
| 293 | const desc = getPropertyDescriptor(target, prop); |
| 294 | if (desc && "value" in desc) innerValue = desc.value; |
| 295 | else { |
| 296 | shadow = createShadow(useSite, target, tracker.property, receiver); |
| 297 | innerValue = Reflect.get(target, prop, shadow); |
| 298 | } |
| 299 | const innerTracker = innerValue?.[symbols.tracker]; |
| 300 | if (innerTracker) return createTraceable(useSite, innerValue, innerTracker); |
| 301 | else if (!tracker.noShadow && typeof innerValue === "function") { |
| 302 | shadow ??= createShadow(useSite, target, tracker.property, receiver); |
| 303 | return createShadowMethod(useSite, innerValue, receiver, shadow); |
| 304 | } else return innerValue; |
| 305 | }, |
| 306 | set: (target, prop, value2, receiver) => { |
| 307 | if (prop === symbols.original) return false; |
| 308 | if (prop === symbols.caller) return false; |
| 309 | if (prop === tracker.property) return false; |
| 310 | if (typeof prop === "symbol") return Reflect.set(target, prop, value2, receiver); |
| 311 | if (tracker.associate && useSite.reflect.props[`${tracker.associate}.${prop}`]) return Reflect.set(ctx, `${tracker.associate}.${prop}`, value2, withProp(ctx, symbols.receiver, receiver)); |
| 312 | const shadow = createShadow(useSite, target, tracker.property, receiver); |
| 313 | return Reflect.set(target, prop, value2, shadow); |
| 314 | }, |
| 315 | apply: (target, thisArg, args) => { |
| 316 | return applyTraceable(tracker.noShadow ? proxy : createShadow(useSite, target, tracker.property, proxy), target, thisArg, args); |
| 317 | } |
| 318 | }); |
| 319 | return proxy; |
| 320 | } |
| 321 | function applyTraceable(proxy, value, thisArg, args) { |
| 322 | if (!value[symbols.invoke]) return Reflect.apply(value, thisArg, args); |
| 323 | return value[symbols.invoke].apply(proxy, args); |
| 324 | } |
| 325 | function createCallable(name, proto, tracker) { |
| 326 | const self = function(...args) { |
| 327 | const proxy = createTraceable(self["ctx"], self, tracker); |
| 328 | return Reflect.apply(proxy, this, args); |
| 329 | }; |
| 330 | defineProperty(self, "name", name); |
| 331 | return Object.setPrototypeOf(self, proto); |
| 332 | } |
| 333 | function handleError(info, reason, getOuterStack) { |
| 334 | const innerLines = info.error.stack.split("\n"); |
| 335 | if (typeof reason?.stack !== "string") { |
| 336 | const outerError = new Error(reason); |
| 337 | const lines2 = outerError.stack.split("\n"); |
| 338 | lines2.splice(1, Infinity, ...getOuterStack()); |
| 339 | outerError.stack = lines2.join("\n"); |
| 340 | throw outerError; |
| 341 | } |
| 342 | const lines = reason.stack.split("\n"); |
| 343 | let index = lines.indexOf(innerLines[2]); |
| 344 | if (index === -1) throw reason; |
| 345 | index -= info.offset; |
| 346 | while (index > 0) { |
| 347 | if (!lines[index - 1].endsWith(" (<anonymous>)")) break; |
| 348 | index -= 1; |
| 349 | } |
| 350 | lines.splice(index, Infinity, ...getOuterStack()); |
| 351 | reason.stack = lines.join("\n"); |
| 352 | throw reason; |
| 353 | } |
| 354 | function composeError(callback, getOuterStack = buildOuterStack()) { |
| 355 | const info = { |
| 356 | offset: 1, |
| 357 | error: /* @__PURE__ */ new Error() |
| 358 | }; |
| 359 | try { |
| 360 | const result = callback(info); |
| 361 | if (isObject(result) && "then" in result) return result.then(void 0, (reason) => handleError(info, reason, getOuterStack)); |
| 362 | else return result; |
| 363 | } catch (reason) { |
| 364 | handleError(info, reason, getOuterStack); |
| 365 | } |
| 366 | } |
| 367 | function buildOuterStack(offset = 0) { |
| 368 | const outerError = /* @__PURE__ */ new Error(); |
| 369 | return () => outerError.stack.split("\n").slice(3 + offset); |
| 370 | } |
| 371 | var kValidationError = /* @__PURE__ */ Symbol.for("ValidationError"); |
| 372 | var ValidationError = class extends TypeError { |
| 373 | name = "ValidationError"; |
| 374 | /** |
| 375 | * Build the aggregated message from schema issues. |
| 376 | * |
| 377 | * @param issues — the standard-schema issues, one message line each. |
| 378 | */ |
| 379 | constructor(issues) { |
| 380 | super(`invalid config: |
| 381 | ` + issues.map((issue) => { |
| 382 | if (issue.path) return ` - ${issue.message} (at ${issue.path.join(".")})`; |
| 383 | else return ` - ${issue.message}`; |
| 384 | }).join("\n")); |
| 385 | } |
| 386 | }; |
| 387 | Object.defineProperty(ValidationError.prototype, kValidationError, { value: true }); |
| 388 | function resolveConfig(runtime, config) { |
| 389 | if (!runtime.Config) return config; |
| 390 | const result = runtime.Config["~standard"].validate(config); |
| 391 | if ("then" in result) throw new TypeError("Async config validation is not supported"); |
| 392 | if (result.issues) throw new ValidationError(result.issues); |
| 393 | else return result.value; |
| 394 | } |
| 395 | var effectInertia = /* @__PURE__ */ new WeakMap(); |
| 396 | function runDisposable(dispose) { |
| 397 | const result = dispose(); |
| 398 | return effectInertia.get(dispose)?.() ?? result; |
| 399 | } |
| 400 | function emitPluginDisposed(context, fiber) { |
| 401 | const args = ["internal/plugin", fiber]; |
| 402 | let callbacks; |
| 403 | try { |
| 404 | callbacks = context.events.dispatch("emit", args); |
| 405 | } catch (error) { |
| 406 | context.logger.error(error); |
| 407 | return; |
| 408 | } |
| 409 | for (const callback of callbacks) try { |
| 410 | const returned = callback(...args); |
| 411 | Promise.resolve(returned).catch((error) => context.logger.error(error)); |
| 412 | } catch (error) { |
| 413 | context.logger.error(error); |
| 414 | } |
| 415 | } |
| 416 | var CordisError = class CordisError2 extends Error { |
| 417 | code; |
| 418 | /** |
| 419 | * @param code — the stable error code; also the default message. |
| 420 | * @param message — optional human-readable override. |
| 421 | */ |
| 422 | constructor(code, message) { |
| 423 | super(message ?? CordisError2.Code[code]); |
| 424 | this.code = code; |
| 425 | } |
| 426 | }; |
| 427 | (function(CordisError3) { |
| 428 | CordisError3.Code = { INACTIVE_EFFECT: "cannot create effect on inactive context" }; |
| 429 | })(CordisError || (CordisError = {})); |
| 430 | var INACTIVE = "__INACTIVE__"; |
| 431 | var Fiber = class { |
| 432 | parent; |
| 433 | inject; |
| 434 | runtime; |
| 435 | /** Unique id within the registry; 0 for the root fiber, `null` once disposed. */ |
| 436 | uid; |
| 437 | /** The context this fiber's plugin runs in (extends the parent context). */ |
| 438 | ctx; |
| 439 | /** Raw plugin input retained for the next activation. */ |
| 440 | config; |
| 441 | /** Current lifecycle state; transitions emit `internal/status`. */ |
| 442 | state = 0; |
| 443 | /** Dispose this fiber: unload the plugin, then settle once cleanup finished. */ |
| 444 | dispose; |
| 445 | /** Required implementations retained through dependent teardown. */ |
| 446 | committed; |
| 447 | /** Service implementations owned by this fiber, including isolated provisions. */ |
| 448 | provisions = /* @__PURE__ */ new Set(); |
| 449 | /** The in-flight load/unload transition, if one is currently running. */ |
| 450 | inertia; |
| 451 | _hooks = /* @__PURE__ */ Object.create(null); |
| 452 | _disposables = new DisposableList(); |
| 453 | context; |
| 454 | _error; |
| 455 | _revision = 0; |
| 456 | _configRevision = 0; |
| 457 | _effectiveConfig; |
| 458 | _runner; |
| 459 | _store = /* @__PURE__ */ Object.create(null); |
| 460 | _release; |
| 461 | /** |
| 462 | * Create a fiber. Plugin authors normally obtain fibers from `ctx.plugin()` |
| 463 | * rather than constructing them directly. |
| 464 | * |
| 465 | * @param parent — the context the plugin was loaded from. |
| 466 | * @param config — raw config, validated against the runtime's schema. |
| 467 | * @param inject — resolved dependency map (service name → intercept config). |
| 468 | * @param runtime — the shared plugin runtime, or `null` for the root fiber. |
| 469 | * @param getOuterStack — captures the caller stack for effect diagnostics. |
| 470 | */ |
| 471 | constructor(parent, config, inject, runtime, getOuterStack) { |
| 472 | this.parent = parent; |
| 473 | this.inject = inject; |
| 474 | this.runtime = runtime; |
| 475 | this.config = config; |
| 476 | const collect = (dispose) => { |
| 477 | this._disposables.push(dispose); |
| 478 | }; |
| 479 | if (runtime) { |
| 480 | this.uid = parent.registry.counter; |
| 481 | this.ctx = this.context = parent.extend({ fiber: this }); |
| 482 | const injectEntries = Object.entries(this.inject); |
| 483 | if (injectEntries.length) { |
| 484 | this.ctx[Context.intercept] = Object.create(parent[Context.intercept]); |
| 485 | for (const [name, config2] of injectEntries) { |
| 486 | if (isNullable(config2)) continue; |
| 487 | this.ctx[Context.intercept][name] = config2; |
| 488 | } |
| 489 | } |
| 490 | this._runner = { |
| 491 | epoch: INACTIVE, |
| 492 | getOuterStack, |
| 493 | execute: function() { |
| 494 | const config2 = this.resolveConfig(this.config); |
| 495 | this._effectiveConfig = config2; |
| 496 | if (isConstructor(runtime.callback)) { |
| 497 | const instance = new runtime.callback(this.ctx, config2); |
| 498 | for (const hook of instance?.[symbols.initHooks] ?? []) hook(); |
| 499 | return instance?.[symbols.init]?.(); |
| 500 | } else return runtime.callback(this.ctx, config2); |
| 501 | }, |
| 502 | collect |
| 503 | }; |
| 504 | this.dispose = parent.fiber.effect(() => { |
| 505 | const remove = runtime.fibers.push(this); |
| 506 | return async () => { |
| 507 | this.uid = null; |
| 508 | emitPluginDisposed(this.context, this); |
| 509 | if (this.ctx.registry.has(runtime.callback)) { |
| 510 | remove(); |
| 511 | if (!runtime.fibers.length) this.ctx.registry.delete(runtime.callback); |
| 512 | } |
| 513 | this._setEpoch(INACTIVE); |
| 514 | if (!this.inertia) this._updateState(() => { |
| 515 | this.inertia = this._unload(); |
| 516 | return 5; |
| 517 | }); |
| 518 | while (this.inertia) await this.inertia; |
| 519 | }; |
| 520 | }, "ctx.plugin()"); |
| 521 | try { |
| 522 | this.context.emit("internal/plugin", this); |
| 523 | } catch (error) { |
| 524 | Promise.resolve(this.dispose()).catch((reason) => this.ctx.logger.error(reason)); |
| 525 | throw error; |
| 526 | } |
| 527 | if (this.uid !== null && parent.fiber.state !== 5) { |
| 528 | for (const name of Object.keys(this.inject)) this._checkImpl(name); |
| 529 | this._refresh(); |
| 530 | } |
| 531 | } else { |
| 532 | this.uid = 0; |
| 533 | this.ctx = this.context = parent; |
| 534 | this.state = 2; |
| 535 | this.committed = /* @__PURE__ */ Object.create(null); |
| 536 | this._runner = { |
| 537 | epoch: "0", |
| 538 | getOuterStack, |
| 539 | execute: () => { |
| 540 | }, |
| 541 | collect |
| 542 | }; |
| 543 | this.dispose = () => this.restart(); |
| 544 | } |
| 545 | } |
| 546 | /** The plugin's display name, inherited from the nearest named ancestor, else `'root'`. */ |
| 547 | get name() { |
| 548 | let fiber = this; |
| 549 | do { |
| 550 | if (fiber.runtime?.name) return fiber.runtime.name; |
| 551 | fiber = fiber.parent.fiber; |
| 552 | } while (fiber !== fiber.parent.fiber); |
| 553 | return "root"; |
| 554 | } |
| 555 | /** |
| 556 | * Throw if the fiber has already been disposed. |
| 557 | * |
| 558 | * @returns nothing when the fiber is still active. |
| 559 | * @throws {CordisError} `INACTIVE_EFFECT` when the fiber's uid has been cleared. |
| 560 | */ |
| 561 | assertActive() { |
| 562 | if (this.uid !== null) return; |
| 563 | throw new CordisError("INACTIVE_EFFECT"); |
| 564 | } |
| 565 | _execute(runner) { |
| 566 | const oldEpoch = runner.epoch; |
| 567 | return composeError((info) => { |
| 568 | const safeCollect = (dispose) => { |
| 569 | if (typeof dispose === "function") runner.collect(dispose); |
| 570 | else if (!isNullable(dispose)) throw new TypeError("Invalid effect"); |
| 571 | }; |
| 572 | const effect = runner.execute.call(this); |
| 573 | if (typeof effect === "function") return runner.collect(effect); |
| 574 | else if (isNullable(effect)) { |
| 575 | } else if (!isObject(effect)) throw new TypeError("Invalid effect"); |
| 576 | else if ("then" in effect) return effect.then(safeCollect); |
| 577 | else if (Symbol.iterator in effect) { |
| 578 | info.error = /* @__PURE__ */ new Error(); |
| 579 | const iter = effect[Symbol.iterator](); |
| 580 | while (true) { |
| 581 | const result = iter.next(); |
| 582 | safeCollect(result.value); |
| 583 | if (result.done) return; |
| 584 | } |
| 585 | } else if (Symbol.asyncIterator in effect) { |
| 586 | const iter = effect[Symbol.asyncIterator](); |
| 587 | return (async () => { |
| 588 | await Promise.resolve(); |
| 589 | info.error = /* @__PURE__ */ new Error(); |
| 590 | while (true) { |
| 591 | if (runner.epoch !== oldEpoch) return; |
| 592 | const result = await iter.next(); |
| 593 | safeCollect(result.value); |
| 594 | if (result.done) return; |
| 595 | } |
| 596 | })(); |
| 597 | } else throw new TypeError("Invalid effect"); |
| 598 | }, runner.getOuterStack); |
| 599 | } |
| 600 | effect(execute, label = "anonymous") { |
| 601 | this.assertActive(); |
| 602 | if (this.state === 5) throw new CordisError("INACTIVE_EFFECT"); |
| 603 | const disposables = []; |
| 604 | let disposing = false; |
| 605 | let disposalTask; |
| 606 | const dispose = () => { |
| 607 | if (disposing) return disposalTask; |
| 608 | disposing = true; |
| 609 | let task2; |
| 610 | for (const disposable of disposables.splice(0).reverse()) if (task2) task2 = task2.then(() => runDisposable(disposable)); |
| 611 | else { |
| 612 | const result = runDisposable(disposable); |
| 613 | if (isObject(result) && "then" in result) task2 = result; |
| 614 | } |
| 615 | return disposalTask = task2; |
| 616 | }; |
| 617 | const meta = { |
| 618 | label, |
| 619 | children: [] |
| 620 | }; |
| 621 | const runner = { |
| 622 | execute, |
| 623 | epoch: true, |
| 624 | collect: (dispose2) => { |
| 625 | disposables.push(dispose2); |
| 626 | this._disposables.delete(dispose2); |
| 627 | if (dispose2[symbols.effect]) meta.children.push(dispose2[symbols.effect]); |
| 628 | }, |
| 629 | getOuterStack: buildOuterStack() |
| 630 | }; |
| 631 | let task; |
| 632 | let executing = true; |
| 633 | let resolveSetup; |
| 634 | let rejectSetup; |
| 635 | let setupBarrier; |
| 636 | let setupFailed = false; |
| 637 | let inFlight; |
| 638 | let removeWrapper = () => false; |
| 639 | const waitForSetup = () => { |
| 640 | setupBarrier ??= new Promise((resolve, reject) => { |
| 641 | resolveSetup = resolve; |
| 642 | rejectSetup = reject; |
| 643 | }); |
| 644 | return setupBarrier; |
| 645 | }; |
| 646 | const disposeAfter = (setup) => { |
| 647 | return Promise.resolve(setup).then(() => dispose(), async (reason) => { |
| 648 | await dispose(); |
| 649 | throw reason; |
| 650 | }); |
| 651 | }; |
| 652 | const finalizeDisposal = (callback) => { |
| 653 | let result; |
| 654 | try { |
| 655 | result = callback(); |
| 656 | } catch (error) { |
| 657 | removeWrapper(); |
| 658 | throw error; |
| 659 | } |
| 660 | if (isObject(result) && "then" in result) { |
| 661 | const pending = Promise.resolve(result).finally(() => { |
| 662 | removeWrapper(); |
| 663 | if (inFlight === pending) inFlight = void 0; |
| 664 | }); |
| 665 | return inFlight = pending; |
| 666 | } |
| 667 | removeWrapper(); |
| 668 | return result; |
| 669 | }; |
| 670 | const wrapper = defineProperty(() => { |
| 671 | if (!runner.epoch) return setupFailed ? inFlight : void 0; |
| 672 | runner.epoch = false; |
| 673 | return finalizeDisposal(() => { |
| 674 | if (executing) return disposeAfter(waitForSetup()); |
| 675 | return task ? disposeAfter(task) : dispose(); |
| 676 | }); |
| 677 | }, symbols.effect, meta); |
| 678 | effectInertia.set(wrapper, () => inFlight); |
| 679 | removeWrapper = this._disposables.push(wrapper); |
| 680 | try { |
| 681 | task = this._execute(runner); |
| 682 | } catch (reason) { |
| 683 | executing = false; |
| 684 | setupFailed = true; |
| 685 | runner.epoch = false; |
| 686 | let cleanup; |
| 687 | try { |
| 688 | cleanup = finalizeDisposal(dispose); |
| 689 | } finally { |
| 690 | rejectSetup?.(reason); |
| 691 | } |
| 692 | if (isObject(cleanup) && "then" in cleanup) cleanup.catch((error) => this.ctx.logger.error(error)); |
| 693 | throw reason; |
| 694 | } |
| 695 | executing = false; |
| 696 | if (setupBarrier) Promise.resolve(task).then(resolveSetup, rejectSetup); |
| 697 | task?.catch(() => { |
| 698 | if (!runner.epoch) return dispose(); |
| 699 | return finalizeDisposal(dispose); |
| 700 | }).catch((error) => this.ctx.logger.error(error)); |
| 701 | const disposeAsync = () => { |
| 702 | if (!runner.epoch) return; |
| 703 | runner.epoch = false; |
| 704 | return finalizeDisposal(dispose); |
| 705 | }; |
| 706 | wrapper.then = async (onFulfilled, onRejected) => { |
| 707 | return Promise.resolve(task).then(() => disposeAsync).then(onFulfilled, onRejected); |
| 708 | }; |
| 709 | return wrapper; |
| 710 | } |
| 711 | /** |
| 712 | * Return metadata for currently registered effects. |
| 713 | * |
| 714 | * @returns one {@link EffectMeta} tree per labeled live effect. |
| 715 | */ |
| 716 | getEffects() { |
| 717 | return [...this._disposables].map((dispose) => dispose[symbols.effect]).filter(Boolean); |
| 718 | } |
| 719 | _getState() { |
| 720 | if (this.uid === null) return 4; |
| 721 | if (this._error) return 3; |
| 722 | if (this._runner.epoch !== INACTIVE) return 2; |
| 723 | return 0; |
| 724 | } |
| 725 | _updateState(callback) { |
| 726 | const oldState = this.state; |
| 727 | this.state = callback() ?? this._getState(); |
| 728 | if (oldState === this.state) return; |
| 729 | this.context.emit("internal/status", this, oldState); |
| 730 | if (oldState !== 2 && this.state !== 2) return; |
| 731 | for (const key of Reflect.ownKeys(this.ctx.reflect.store)) { |
| 732 | const impl = this.ctx.reflect.store[key]; |
| 733 | if (impl.ctx.fiber !== this) continue; |
| 734 | this.ctx.isolate(impl.name, impl.isolate).reflect.notify([impl.name]); |
| 735 | } |
| 736 | } |
| 737 | _checkImpl(name) { |
| 738 | const impl = this.ctx.reflect._getImpl(name, true); |
| 739 | if (!impl) return delete this._store[name]; |
| 740 | try { |
| 741 | if (impl.check && !impl.check.call(getTraceable(this.ctx, impl.value))) return delete this._store[name]; |
| 742 | } catch (error) { |
| 743 | impl.ctx.logger.error(error); |
| 744 | return delete this._store[name]; |
| 745 | } |
| 746 | this._store[name] = impl; |
| 747 | } |
| 748 | _refresh() { |
| 749 | let epoch = `${this._revision}`; |
| 750 | for (const name of Object.keys(this.inject)) { |
| 751 | const impl = this._store[name]; |
| 752 | if (!impl) { |
| 753 | epoch = INACTIVE; |
| 754 | break; |
| 755 | } |
| 756 | epoch += ":" + impl.uid; |
| 757 | } |
| 758 | this._setEpoch(epoch); |
| 759 | } |
| 760 | _setEpoch(epoch) { |
| 761 | const oldEpoch = this._runner.epoch; |
| 762 | if (epoch === oldEpoch) return; |
| 763 | if (this._error) return; |
| 764 | this._runner.epoch = epoch; |
| 765 | if (this.inertia) return; |
| 766 | this._updateState(() => { |
| 767 | if (epoch !== INACTIVE && oldEpoch === INACTIVE) { |
| 768 | this.inertia = this._reload(); |
| 769 | return 1; |
| 770 | } else { |
| 771 | this.inertia = this._unload(); |
| 772 | return 5; |
| 773 | } |
| 774 | }); |
| 775 | } |
| 776 | /** Raw input retained for the next activation, without evaluating expressions or validating it. */ |
| 777 | get rawConfig() { |
| 778 | return this.ctx.fiber.config; |
| 779 | } |
| 780 | /** Retain raw input without changing the running config or triggering an update. */ |
| 781 | set rawConfig(config) { |
| 782 | this.ctx.fiber.config = config; |
| 783 | this.ctx.fiber._configRevision++; |
| 784 | } |
| 785 | /** |
| 786 | * The object passed to plugin activation or the latest successful update that retained the instance. |
| 787 | * Candidate resolution does not publish it; volatile updates retain its references. |
| 788 | * Undefined before activation and readable after unload; callers requiring a live instance check `state`. |
| 789 | */ |
| 790 | get effectiveConfig() { |
| 791 | return this.ctx.fiber._effectiveConfig; |
| 792 | } |
| 793 | /** |
| 794 | * Evaluate and validate a candidate using this fiber's `internal/config` hooks and runtime schema. |
| 795 | * Does not publish the result, replace raw input, or commit running volatile references. |
| 796 | * Required injections must be available when a hook uses them. |
| 797 | * @param config Raw candidate input. |
| 798 | * @returns The candidate's resolved config, retaining the schema's result identity. |
| 799 | * @throws {ValidationError} when the runtime schema rejects the candidate; hook errors propagate. |
| 800 | */ |
| 801 | resolveConfig(config) { |
| 802 | const fiber = this.ctx.fiber; |
| 803 | return fiber.context.waterfall("internal/config", fiber, () => config); |
| 804 | } |
| 805 | async _reload() { |
| 806 | this.committed = { ...this._store }; |
| 807 | for (const impl of Object.values(this.committed)) { |
| 808 | if (impl.ctx.fiber === this) continue; |
| 809 | impl.dependents.add(this); |
| 810 | } |
| 811 | const oldEpoch = this._runner.epoch; |
| 812 | try { |
| 813 | await Promise.resolve(); |
| 814 | if (this._runner.epoch === oldEpoch) await this._execute(this._runner); |
| 815 | } catch (reason) { |
| 816 | this.ctx.logger.error(reason); |
| 817 | if (this._runner.epoch === oldEpoch) { |
| 818 | this._error = reason; |
| 819 | this._runner.epoch = INACTIVE; |
| 820 | } |
| 821 | } |
| 822 | this._updateState(() => { |
| 823 | if (this._runner.epoch === oldEpoch) this.inertia = void 0; |
| 824 | else { |
| 825 | this.inertia = this._unload(); |
| 826 | return 5; |
| 827 | } |
| 828 | }); |
| 829 | } |
| 830 | async _unload() { |
| 831 | while ([...this.provisions].some((impl) => impl.dependents.size)) await new Promise((resolve) => this._release = resolve); |
| 832 | this._release = void 0; |
| 833 | await Promise.all(this._disposables.clear().map(async (dispose) => { |
| 834 | try { |
| 835 | await composeError(async (info) => { |
| 836 | await Promise.resolve(); |
| 837 | info.error = /* @__PURE__ */ new Error(); |
| 838 | await runDisposable(dispose); |
| 839 | }, this._runner.getOuterStack); |
| 840 | } catch (reason) { |
| 841 | this.ctx.logger.error(reason); |
| 842 | } |
| 843 | })); |
| 844 | for (const impl of Object.values(this.committed ?? {})) { |
| 845 | if (!impl.dependents.delete(this) || impl.dependents.size) continue; |
| 846 | impl.release?.(); |
| 847 | impl.ctx.fiber._release?.(); |
| 848 | } |
| 849 | this.committed = void 0; |
| 850 | this._updateState(() => { |
| 851 | if (this._runner.epoch === INACTIVE) this.inertia = void 0; |
| 852 | else { |
| 853 | this.inertia = this._reload(); |
| 854 | return 1; |
| 855 | } |
| 856 | }); |
| 857 | } |
| 858 | /** |
| 859 | * Wait for current lifecycle work and rethrow startup errors. |
| 860 | * |
| 861 | * @returns this fiber, once it has settled into a stable state. |
| 862 | * @throws the config-validation or plugin-startup error, if any. |
| 863 | */ |
| 864 | async await() { |
| 865 | while (this.inertia) await this.inertia; |
| 866 | if (this._error) throw this._error; |
| 867 | return this; |
| 868 | } |
| 869 | /** |
| 870 | * Dispose and immediately reload this plugin with its current config. |
| 871 | * |
| 872 | * @returns a promise resolving once the reload settled. |
| 873 | * @throws {CordisError} `INACTIVE_EFFECT` when the fiber is already disposed. |
| 874 | */ |
| 875 | async restart() { |
| 876 | const fiber = this.ctx.fiber; |
| 877 | fiber.assertActive(); |
| 878 | fiber._revision++; |
| 879 | fiber._refresh(); |
| 880 | await fiber.await(); |
| 881 | } |
| 882 | /** |
| 883 | * Resolve a candidate, retain its raw config and apply it through the update waterfall. |
| 884 | * @param config Raw config; pending fibers defer resolution until activation. |
| 885 | * @param noSave Suppress the persistence notification when true. |
| 886 | * @returns The awaited update/restart result, or undefined when a synchronous listener handles it. |
| 887 | * @throws {ValidationError} when an active fiber's candidate is invalid. |
| 888 | */ |
| 889 | update(config, noSave = false) { |
| 890 | const fiber = this.ctx.fiber; |
| 891 | fiber.assertActive(); |
| 892 | const loaded = fiber._runner.epoch !== INACTIVE; |
| 893 | const resolved = loaded ? fiber.resolveConfig(config) : void 0; |
| 894 | if (!noSave) fiber.context.emit("internal/commit", fiber, config); |
| 895 | fiber.config = config; |
| 896 | fiber._error = void 0; |
| 897 | const configRevision = ++fiber._configRevision; |
| 898 | const epoch = fiber._runner.epoch; |
| 899 | const committed = fiber.committed; |
| 900 | let restarted = false; |
| 901 | const restart = () => { |
| 902 | restarted = true; |
| 903 | return fiber.restart(); |
| 904 | }; |
| 905 | const publish = () => { |
| 906 | if (!restarted && fiber.uid !== null && fiber._configRevision === configRevision && fiber._runner.epoch === epoch && fiber.committed === committed) fiber._effectiveConfig = resolved; |
| 907 | }; |
| 908 | const result = loaded ? fiber.context.waterfall(fiber, "internal/update", resolved, restart) : restart(); |
| 909 | if (result === void 0) { |
| 910 | publish(); |
| 911 | return; |
| 912 | } |
| 913 | const task = Promise.resolve(result).then(publish); |
| 914 | task.catch(() => { |
| 915 | }); |
| 916 | return task; |
| 917 | } |
| 918 | }; |
| 919 | function isBailed(value) { |
| 920 | return value !== null && value !== false && value !== void 0; |
| 921 | } |
| 922 | var EventsService = class { |
| 923 | ctx; |
| 924 | _hooks = /* @__PURE__ */ Object.create(null); |
| 925 | constructor(ctx) { |
| 926 | this.ctx = ctx; |
| 927 | defineProperty(this, symbols.tracker, { |
| 928 | property: "ctx", |
| 929 | noShadow: true |
| 930 | }); |
| 931 | this.on("internal/listener", function(name, listener, options) { |
| 932 | if (name === "internal/update" && !options.global) { |
| 933 | const hooks = this.fiber._hooks["internal/update"] ??= new DisposableList(); |
| 934 | const method = options.prepend ? "unshift" : "push"; |
| 935 | return this.fiber.effect(() => hooks[method](listener), 'ctx.on("internal/update")'); |
| 936 | } |
| 937 | }); |
| 938 | this.on("internal/update", function(config, next) { |
| 939 | const cbs = [...this._hooks["internal/update"] || []]; |
| 940 | const _next = () => { |
| 941 | return (cbs.shift() ?? next).call(this, config, _next); |
| 942 | }; |
| 943 | return _next(); |
| 944 | }, { |
| 945 | global: true, |
| 946 | prepend: true |
| 947 | }); |
| 948 | this.on("internal/config", (fiber, next) => { |
| 949 | const config = next(); |
| 950 | return fiber.runtime ? resolveConfig(fiber.runtime, config) : config; |
| 951 | }); |
| 952 | } |
| 953 | _resolve(type, args) { |
| 954 | const thisArg = typeof args[0] === "object" || typeof args[0] === "function" ? args.shift() : null; |
| 955 | const name = args.shift(); |
| 956 | if ((typeof name !== "string" || !name.startsWith("internal/")) && this._hooks["internal/dispatch"]?.length) this.emit("internal/dispatch", type, name, args, thisArg); |
| 957 | const filter = thisArg?.[Context.filter]; |
| 958 | return [thisArg, (this._hooks[name] || []).filter((hook) => hook.global || !filter || filter.call(thisArg, hook.ctx)).map((hook) => hook.callback)]; |
| 959 | } |
| 960 | /** |
| 961 | * Resolve bound callbacks using the event's context filter. |
| 962 | * @param type Dispatch mode reported to observers. |
| 963 | * @param args Dispatch arguments, consumed through the event name. |
| 964 | * @returns Matching callbacks bound to the dispatch receiver. |
| 965 | * DSH retains callback enumeration for per-listener error containment. |
| 966 | */ |
| 967 | dispatch(type, args) { |
| 968 | const [thisArg, callbacks] = this._resolve(type, args); |
| 969 | return callbacks.map((callback) => callback.bind(thisArg)); |
| 970 | } |
| 971 | /** |
| 972 | * Run listeners concurrently and wait for all of them. |
| 973 | * |
| 974 | * @param args — optional `this`, the event name, then listener arguments. |
| 975 | * @returns a promise resolving once every listener has settled. |
| 976 | */ |
| 977 | async parallel(...args) { |
| 978 | const [thisArg, callbacks] = this._resolve("parallel", args); |
| 979 | const errors = (await Promise.allSettled(callbacks.map(async (callback) => Reflect.apply(callback, thisArg, args)))).filter((result) => result.status === "rejected"); |
| 980 | if (errors.length) throw new AggregateError(errors.map((error) => error.reason)); |
| 981 | } |
| 982 | /** |
| 983 | * Run listeners synchronously without waiting for returned promises. |
| 984 | * |
| 985 | * @param args — optional `this`, the event name, then listener arguments. |
| 986 | */ |
| 987 | emit(...args) { |
| 988 | const [thisArg, callbacks] = this._resolve("emit", args); |
| 989 | for (const callback of callbacks) Reflect.apply(callback, thisArg, args); |
| 990 | } |
| 991 | /** |
| 992 | * Run listeners in order, awaiting each, until one returns a bail value. |
| 993 | * |
| 994 | * @param args — optional `this`, the event name, then listener arguments. |
| 995 | * @returns the first bail value (see {@link isBailed}), if any. |
| 996 | */ |
| 997 | async serial(...args) { |
| 998 | const [thisArg, callbacks] = this._resolve("serial", args); |
| 999 | for (const callback of callbacks) { |
| 1000 | const result = await Reflect.apply(callback, thisArg, args); |
| 1001 | if (isBailed(result)) return result; |
| 1002 | } |
| 1003 | } |
| 1004 | /** |
| 1005 | * Run listeners synchronously until one returns a bail value. |
| 1006 | * |
| 1007 | * @param args — optional `this`, the event name, then listener arguments. |
| 1008 | * @returns the first bail value (see {@link isBailed}), if any. |
| 1009 | */ |
| 1010 | bail(...args) { |
| 1011 | const [thisArg, callbacks] = this._resolve("bail", args); |
| 1012 | for (const callback of callbacks) { |
| 1013 | const result = Reflect.apply(callback, thisArg, args); |
| 1014 | if (isBailed(result)) return result; |
| 1015 | } |
| 1016 | } |
| 1017 | /** |
| 1018 | * Compose listeners around the final `next` callback. |
| 1019 | * |
| 1020 | * The last dispatch argument is treated as the innermost `next`. Listeners |
| 1021 | * run outermost-first; a listener that does not call `next()` vetoes the |
| 1022 | * rest of the chain, including the built-in behavior. |
| 1023 | * |
| 1024 | * @param args — optional `this`, the event name, listener arguments, then `next`. |
| 1025 | * @returns the outermost listener's return value. |
| 1026 | */ |
| 1027 | waterfall(...args) { |
| 1028 | const [thisArg, callbacks] = this._resolve("waterfall", args); |
| 1029 | const inner = args.pop(); |
| 1030 | const dispatch = () => { |
| 1031 | const callback = callbacks.shift(); |
| 1032 | if (!callback) return inner(); |
| 1033 | let called = false; |
| 1034 | const next = () => { |
| 1035 | if (called) throw new Error("next() called multiple times"); |
| 1036 | called = true; |
| 1037 | return dispatch(); |
| 1038 | }; |
| 1039 | return Reflect.apply(callback, thisArg, [...args, next]); |
| 1040 | }; |
| 1041 | return dispatch(); |
| 1042 | } |
| 1043 | register(label, name, callback, options) { |
| 1044 | const method = options.prepend ? "unshift" : "push"; |
| 1045 | return this.ctx.fiber.effect(() => { |
| 1046 | (this._hooks[name] ??= [])[method]({ |
| 1047 | ctx: this.ctx, |
| 1048 | callback, |
| 1049 | ...options |
| 1050 | }); |
| 1051 | return () => this.unregister(name, callback); |
| 1052 | }, label); |
| 1053 | } |
| 1054 | unregister(name, callback) { |
| 1055 | const hooks = this._hooks[name]; |
| 1056 | if (!hooks) return; |
| 1057 | const index = hooks.findIndex((hook) => hook.callback === callback); |
| 1058 | if (index >= 0) { |
| 1059 | hooks.splice(index, 1); |
| 1060 | if (!hooks.length) delete this._hooks[name]; |
| 1061 | return true; |
| 1062 | } |
| 1063 | } |
| 1064 | /** |
| 1065 | * Register an event listener owned by the current fiber. |
| 1066 | * |
| 1067 | * The listener is removed automatically when the fiber unloads. Throws |
| 1068 | * `CordisError('INACTIVE_EFFECT')` if the fiber is already disposed. |
| 1069 | * |
| 1070 | * @param name — the event name to listen for. |
| 1071 | * @param listener — called with the dispatch arguments. |
| 1072 | * @param options — listener options; a boolean is shorthand for `prepend`. |
| 1073 | * @returns a disposer removing the listener; `true` if it was still registered. |
| 1074 | */ |
| 1075 | on(name, listener, options) { |
| 1076 | if (typeof options !== "object") options = { prepend: options }; |
| 1077 | this.ctx.fiber.assertActive(); |
| 1078 | listener = this.ctx.reflect.bind(listener); |
| 1079 | const result = this.bail(this.ctx, "internal/listener", name, listener, options); |
| 1080 | if (result) return result; |
| 1081 | const label = `ctx.on(${typeof name === "string" ? JSON.stringify(name) : name.toString()})`; |
| 1082 | return this.register(label, name, listener, options); |
| 1083 | } |
| 1084 | /** |
| 1085 | * Register an event listener that disposes itself after the first call. |
| 1086 | * |
| 1087 | * @param name — the event name to listen for. |
| 1088 | * @param listener — called at most once with the dispatch arguments. |
| 1089 | * @param options — listener options; a boolean is shorthand for `prepend`. |
| 1090 | * @returns a disposer removing the listener; `true` if it was still registered. |
| 1091 | */ |
| 1092 | once(name, listener, options) { |
| 1093 | const dispose = this.on(name, function(...args) { |
| 1094 | dispose(); |
| 1095 | return listener.apply(this, args); |
| 1096 | }, options); |
| 1097 | return dispose; |
| 1098 | } |
| 1099 | }; |
| 1100 | var defaultFormatters = { |
| 1101 | s: (value) => String(value), |
| 1102 | d: (value) => Math.trunc(Number(value)), |
| 1103 | i: (value) => Math.trunc(Number(value)), |
| 1104 | f: (value) => Number(value), |
| 1105 | o: (value) => JSON.stringify(value), |
| 1106 | O: (value) => JSON.stringify(value), |
| 1107 | c: () => "", |
| 1108 | C: (value, exporter, message) => { |
| 1109 | return Logger.color(exporter, Logger.code(message.name, exporter.colors), value); |
| 1110 | } |
| 1111 | }; |
| 1112 | function isAggregateError(error) { |
| 1113 | return error instanceof Error && Array.isArray(error["errors"]); |
| 1114 | } |
| 1115 | var Logger = class { |
| 1116 | service; |
| 1117 | static color(exporter, code, value, decoration = "") { |
| 1118 | if (!exporter.colors) return "" + value; |
| 1119 | return `\x1B[3${code < 8 ? code : "8;5;" + code}${exporter.colors >= 2 ? decoration : ""}m${value}\x1B[0m`; |
| 1120 | } |
| 1121 | static code(name, level) { |
| 1122 | let hash = 0; |
| 1123 | for (let i = 0; i < name.length; i++) { |
| 1124 | hash = (hash << 3) - hash + name.charCodeAt(i) + 13; |
| 1125 | hash |= 0; |
| 1126 | } |
| 1127 | const colors = !level ? [] : level >= 2 ? c256 : c16; |
| 1128 | return colors[Math.abs(hash) % colors.length]; |
| 1129 | } |
| 1130 | static format(exporter, message) { |
| 1131 | const args = message.args.slice(); |
| 1132 | if (args[0] instanceof Error) { |
| 1133 | args[0] = args[0].stack || args[0].message; |
| 1134 | args.unshift("%s"); |
| 1135 | } else if (typeof args[0] !== "string") args.unshift("%o"); |
| 1136 | let format = args.shift(); |
| 1137 | format = format.replace(/%([a-zA-Z%])/g, (match, char) => { |
| 1138 | if (match === "%%") return "%"; |
| 1139 | const formatter = exporter.formatters?.[char] ?? defaultFormatters[char]; |
| 1140 | if (typeof formatter === "function") return formatter(args.shift(), exporter, message); |
| 1141 | return match; |
| 1142 | }); |
| 1143 | const oFormatter = exporter.formatters?.o ?? defaultFormatters.o; |
| 1144 | for (let arg of args) { |
| 1145 | if (typeof arg === "object" && arg) arg = oFormatter(arg, exporter, message); |
| 1146 | format += " " + arg; |
| 1147 | } |
| 1148 | const { maxLength = 10240 } = exporter; |
| 1149 | return format.split(/\r?\n/g).map((line) => { |
| 1150 | return line.slice(0, maxLength) + (line.length > maxLength ? "..." : ""); |
| 1151 | }).join("\n"); |
| 1152 | } |
| 1153 | constructor(options, service) { |
| 1154 | this.service = service; |
| 1155 | Object.assign(this, options); |
| 1156 | this.error = this._method("error", 0); |
| 1157 | this.info = this._method("info", 2); |
| 1158 | this.warn = this._method("warn", 1); |
| 1159 | this.debug = this._method("debug", 3); |
| 1160 | } |
| 1161 | _method(type, level) { |
| 1162 | return (...args) => { |
| 1163 | if (args.length === 1 && args[0] instanceof Error) { |
| 1164 | if (args[0].cause) this[type](args[0].cause); |
| 1165 | else if (isAggregateError(args[0])) { |
| 1166 | args[0].errors.forEach((error) => this[type](error)); |
| 1167 | return; |
| 1168 | } |
| 1169 | } |
| 1170 | const sn = ++this.service._snMessage; |
| 1171 | const ts = Date.now(); |
| 1172 | for (const exporter of this.service.exporters.values()) { |
| 1173 | if ((exporter.levels?.[this.name] ?? exporter.levels?.default ?? this.level ?? 2) < level) continue; |
| 1174 | const message = { |
| 1175 | sn, |
| 1176 | ts, |
| 1177 | type, |
| 1178 | level, |
| 1179 | name: this.name, |
| 1180 | ...this.meta, |
| 1181 | args |
| 1182 | }; |
| 1183 | exporter.export(message); |
| 1184 | } |
| 1185 | }; |
| 1186 | } |
| 1187 | }; |
| 1188 | var c16 = [ |
| 1189 | 6, |
| 1190 | 2, |
| 1191 | 3, |
| 1192 | 4, |
| 1193 | 5, |
| 1194 | 1 |
| 1195 | ]; |
| 1196 | var c256 = [ |
| 1197 | 20, |
| 1198 | 21, |
| 1199 | 26, |
| 1200 | 27, |
| 1201 | 32, |
| 1202 | 33, |
| 1203 | 38, |
| 1204 | 39, |
| 1205 | 40, |
| 1206 | 41, |
| 1207 | 42, |
| 1208 | 43, |
| 1209 | 44, |
| 1210 | 45, |
| 1211 | 56, |
| 1212 | 57, |
| 1213 | 62, |
| 1214 | 63, |
| 1215 | 68, |
| 1216 | 69, |
| 1217 | 74, |
| 1218 | 75, |
| 1219 | 76, |
| 1220 | 77, |
| 1221 | 78, |
| 1222 | 79, |
| 1223 | 80, |
| 1224 | 81, |
| 1225 | 92, |
| 1226 | 93, |
| 1227 | 98, |
| 1228 | 99, |
| 1229 | 112, |
| 1230 | 113, |
| 1231 | 129, |
| 1232 | 134, |
| 1233 | 135, |
| 1234 | 148, |
| 1235 | 149, |
| 1236 | 160, |
| 1237 | 161, |
| 1238 | 162, |
| 1239 | 163, |
| 1240 | 164, |
| 1241 | 165, |
| 1242 | 166, |
| 1243 | 167, |
| 1244 | 168, |
| 1245 | 169, |
| 1246 | 170, |
| 1247 | 171, |
| 1248 | 172, |
| 1249 | 173, |
| 1250 | 178, |
| 1251 | 179, |
| 1252 | 184, |
| 1253 | 185, |
| 1254 | 196, |
| 1255 | 197, |
| 1256 | 198, |
| 1257 | 199, |
| 1258 | 200, |
| 1259 | 201, |
| 1260 | 202, |
| 1261 | 203, |
| 1262 | 204, |
| 1263 | 205, |
| 1264 | 206, |
| 1265 | 207, |
| 1266 | 208, |
| 1267 | 209, |
| 1268 | 214, |
| 1269 | 215, |
| 1270 | 220, |
| 1271 | 221 |
| 1272 | ]; |
| 1273 | var LoggerService = class LoggerService2 { |
| 1274 | bufferSize = 1e3; |
| 1275 | buffer = []; |
| 1276 | ctx; |
| 1277 | _snMessage = 0; |
| 1278 | _snExporter = 0; |
| 1279 | exporters = /* @__PURE__ */ new Map(); |
| 1280 | constructor(ctx) { |
| 1281 | const tracker = { |
| 1282 | property: "ctx", |
| 1283 | noShadow: true |
| 1284 | }; |
| 1285 | const self = createCallable("logger", joinPrototype(Object.getPrototypeOf(this), Function.prototype), tracker); |
| 1286 | Object.assign(self, this); |
| 1287 | self.ctx = ctx; |
| 1288 | defineProperty(self, symbols.tracker, tracker); |
| 1289 | self.exporter({ |
| 1290 | colors: 3, |
| 1291 | export: (message) => { |
| 1292 | self.buffer.push(message); |
| 1293 | const overflow = self.buffer.length - self.bufferSize; |
| 1294 | if (overflow === 1) self.buffer.shift(); |
| 1295 | else if (overflow > 1) self.buffer.splice(0, overflow); |
| 1296 | } |
| 1297 | }); |
| 1298 | return self; |
| 1299 | } |
| 1300 | /** |
| 1301 | * Register an exporter and dispose it with the current fiber. |
| 1302 | * |
| 1303 | * @param exporter — the sink that receives structured log messages. |
| 1304 | * @returns a disposer that removes the exporter. |
| 1305 | */ |
| 1306 | exporter(exporter) { |
| 1307 | return this.ctx.effect(() => { |
| 1308 | const id = ++this._snExporter; |
| 1309 | this.exporters.set(id, exporter); |
| 1310 | return () => this.exporters.delete(id); |
| 1311 | }, "ctx.logger.exporter()"); |
| 1312 | } |
| 1313 | _resolveConfig() { |
| 1314 | let intercept = this.ctx[symbols.intercept]; |
| 1315 | const configs = []; |
| 1316 | while ("logger" in intercept) { |
| 1317 | if (Object.hasOwn(intercept, "logger")) configs.unshift(intercept["logger"]); |
| 1318 | intercept = Object.getPrototypeOf(intercept); |
| 1319 | } |
| 1320 | return Object.assign({}, ...configs); |
| 1321 | } |
| 1322 | [symbols.invoke](name) { |
| 1323 | const config = this._resolveConfig(); |
| 1324 | const fiber = (this[symbols.caller] ?? this.ctx).fiber; |
| 1325 | name ??= config.name; |
| 1326 | name ??= hyphenate(fiber.name); |
| 1327 | return new Logger({ |
| 1328 | name, |
| 1329 | level: config.level, |
| 1330 | meta: { fiber: new WeakRef(fiber) } |
| 1331 | }, this); |
| 1332 | } |
| 1333 | static { |
| 1334 | for (const type of [ |
| 1335 | "error", |
| 1336 | "info", |
| 1337 | "warn", |
| 1338 | "debug" |
| 1339 | ]) LoggerService2.prototype[type] = function(...args) { |
| 1340 | return this()[type](...args); |
| 1341 | }; |
| 1342 | } |
| 1343 | }; |
| 1344 | function enhanceError(error) { |
| 1345 | const lines = error.stack.split("\n"); |
| 1346 | lines.splice(0, 2, `Error: ${error.message}`); |
| 1347 | error.stack = lines.join("\n"); |
| 1348 | return error; |
| 1349 | } |
| 1350 | var RESERVED_WORDS = ["prototype", "then"]; |
| 1351 | function isSpecialProperty(prop) { |
| 1352 | return typeof prop === "symbol" || RESERVED_WORDS.includes(prop) || parseInt(prop).toString() === prop || prop.startsWith("_"); |
| 1353 | } |
| 1354 | var ReflectService = class { |
| 1355 | ctx; |
| 1356 | /** Proxy traps implementing service resolution for every context object. */ |
| 1357 | static handler = { |
| 1358 | get: (target, prop, ctx) => { |
| 1359 | if (isSpecialProperty(prop)) return Reflect.get(target, prop, ctx); |
| 1360 | if (Reflect.has(target, prop)) return getTraceable(ctx, Reflect.get(target, prop, ctx)); |
| 1361 | const error = /* @__PURE__ */ new Error(`cannot get property "${prop}" without inject`); |
| 1362 | try { |
| 1363 | const def = target.reflect.props[prop]; |
| 1364 | if (def?.type === "accessor") return def.get.call(ctx, ctx[symbols.receiver], error); |
| 1365 | const defSite = ctx[symbols.shadow] ?? ctx; |
| 1366 | if (!defSite.fiber.runtime) return ctx.reflect.get(prop, false); |
| 1367 | return ctx.events.waterfall("internal/get", ctx, prop, error, () => { |
| 1368 | const key = defSite[symbols.isolate][prop]; |
| 1369 | let fiber = defSite.fiber; |
| 1370 | while (true) { |
| 1371 | let impl = fiber.committed?.[prop]; |
| 1372 | for (const provision of fiber.provisions) if (provision.name === prop && provision.ctx[symbols.isolate][prop] === key) impl = provision; |
| 1373 | if (impl) return getTraceable(ctx, impl.value); |
| 1374 | if (prop in fiber.inject) { |
| 1375 | error.message = `cannot get required service "${prop}" in inactive context`; |
| 1376 | throw error; |
| 1377 | } |
| 1378 | if (!fiber.runtime) throw error; |
| 1379 | if (fiber.parent[symbols.isolate][prop] !== key) throw error; |
| 1380 | fiber = fiber.parent.fiber; |
| 1381 | } |
| 1382 | }); |
| 1383 | } catch (e) { |
| 1384 | throw e === error ? enhanceError(e) : e; |
| 1385 | } |
| 1386 | }, |
| 1387 | set: (target, prop, value, ctx) => { |
| 1388 | if (isSpecialProperty(prop)) return Reflect.set(target, prop, value, ctx); |
| 1389 | const error = /* @__PURE__ */ new Error(`cannot set property "${prop}" without provide`); |
| 1390 | const def = target.reflect.props[prop]; |
| 1391 | if (!def) { |
| 1392 | if (!ctx.fiber.runtime) return Reflect.set(target, prop, value, ctx); |
| 1393 | throw enhanceError(error); |
| 1394 | } |
| 1395 | try { |
| 1396 | if (def.type === "accessor") { |
| 1397 | if (!def.set) return false; |
| 1398 | return def.set.call(ctx, value, ctx[symbols.receiver], error); |
| 1399 | } |
| 1400 | return ctx.events.waterfall("internal/set", ctx, prop, value, error, () => { |
| 1401 | return ctx.reflect.set(prop, value, error); |
| 1402 | }); |
| 1403 | } catch (e) { |
| 1404 | throw e === error ? enhanceError(e) : e; |
| 1405 | } |
| 1406 | }, |
| 1407 | has: (target, prop) => { |
| 1408 | if (isSpecialProperty(prop)) return Reflect.has(target, prop); |
| 1409 | if (Reflect.has(target, prop)) return true; |
| 1410 | return !!target.reflect.props[prop]; |
| 1411 | } |
| 1412 | }; |
| 1413 | /** Service implementations, keyed by isolation label. */ |
| 1414 | store = /* @__PURE__ */ Object.create(null); |
| 1415 | /** Declared context properties (services and accessors), by name. */ |
| 1416 | props = /* @__PURE__ */ Object.create(null); |
| 1417 | _implCounter = 0; |
| 1418 | constructor(ctx) { |
| 1419 | this.ctx = ctx; |
| 1420 | defineProperty(this, symbols.tracker, { |
| 1421 | property: "ctx", |
| 1422 | noShadow: true |
| 1423 | }); |
| 1424 | this.mixin("reflect", [ |
| 1425 | "get", |
| 1426 | "set", |
| 1427 | "provide", |
| 1428 | "accessor", |
| 1429 | "mixin" |
| 1430 | ]); |
| 1431 | this.mixin("fiber", ["runtime", "effect"]); |
| 1432 | this.mixin("registry", ["inject", "plugin"]); |
| 1433 | this.mixin("events", [ |
| 1434 | "on", |
| 1435 | "once", |
| 1436 | "parallel", |
| 1437 | "emit", |
| 1438 | "serial", |
| 1439 | "bail", |
| 1440 | "waterfall" |
| 1441 | ]); |
| 1442 | } |
| 1443 | /** |
| 1444 | * Read a service from the store without the inject requirement. |
| 1445 | * |
| 1446 | * @param name — the service name. |
| 1447 | * @param strict — when `true`, only return implementations whose providing |
| 1448 | * fiber is currently active. |
| 1449 | * @returns the service value, or `undefined` when not (yet) provided. |
| 1450 | */ |
| 1451 | get(name, strict = true) { |
| 1452 | return getTraceable(this.ctx, this._getImpl(name, strict)?.value); |
| 1453 | } |
| 1454 | _getImpl(name, strict = true) { |
| 1455 | const key = this.ctx[symbols.isolate][name]; |
| 1456 | const impl = key && this.store[key]; |
| 1457 | if (!impl) return; |
| 1458 | if (strict && impl.ctx.fiber.state !== 2) return; |
| 1459 | return impl; |
| 1460 | } |
| 1461 | /** |
| 1462 | * Overwrite a provided service's value. |
| 1463 | * |
| 1464 | * @param name — the service name. |
| 1465 | * @param value — the new service value. |
| 1466 | * @param error — carrier for the caller stack in diagnostics. |
| 1467 | * @returns `true` on success. |
| 1468 | * @throws when `name` was never provided, or was provided by another fiber. |
| 1469 | */ |
| 1470 | set(name, value, error) { |
| 1471 | const key = this.ctx[symbols.isolate][name]; |
| 1472 | const impl = this.store[key]; |
| 1473 | if (!impl) throw new Error(`cannot set property "${name}" without provide`); |
| 1474 | if (impl.ctx.fiber !== this.ctx.fiber) throw new Error(`cannot set property "${name}" in multiple fibers`); |
| 1475 | impl.value = value; |
| 1476 | return true; |
| 1477 | } |
| 1478 | /** |
| 1479 | * Register a service implementation owned by the current fiber. |
| 1480 | * |
| 1481 | * See the `ctx.provide()` overload above for the full contract. |
| 1482 | * |
| 1483 | * @param name — the service name. |
| 1484 | * @param value — the service value. |
| 1485 | * @param check — optional availability predicate for dependents. |
| 1486 | * @returns a disposer that unregisters the service. |
| 1487 | */ |
| 1488 | provide(name, value, check) { |
| 1489 | return this.ctx.fiber.effect(() => { |
| 1490 | if (!this.props[name]) this.props[name] ??= { type: "service" }; |
| 1491 | else if (this.props[name].type !== "service") throw new Error(`property "${name}" is already declared as ${this.props[name].type}`); |
| 1492 | this.props[name] = { type: "service" }; |
| 1493 | this.ctx.root[symbols.isolate][name] ??= Symbol(name); |
| 1494 | const key = this.ctx[symbols.isolate][name]; |
| 1495 | const impl = { |
| 1496 | uid: ++this._implCounter, |
| 1497 | name, |
| 1498 | value, |
| 1499 | ctx: this.ctx, |
| 1500 | check, |
| 1501 | isolate: key, |
| 1502 | dependents: /* @__PURE__ */ new Set() |
| 1503 | }; |
| 1504 | if (this.store[key]) throw new Error(`service "${name}" has been registered at <${this.store[key].ctx.fiber.name}>`); |
| 1505 | this.store[key] = impl; |
| 1506 | this.ctx.fiber.provisions.add(impl); |
| 1507 | if (this.ctx.fiber.state === 2) this.notify([name]); |
| 1508 | return async () => { |
| 1509 | if (this.store[impl.isolate] === impl) delete this.store[impl.isolate]; |
| 1510 | this.ctx.isolate(name, impl.isolate).reflect.notify([name]); |
| 1511 | await new Promise((resolve) => { |
| 1512 | impl.release = resolve; |
| 1513 | if (!impl.dependents.size) resolve(); |
| 1514 | }); |
| 1515 | impl.release = void 0; |
| 1516 | this.ctx.fiber.provisions.delete(impl); |
| 1517 | }; |
| 1518 | }, `ctx.provide(${JSON.stringify(name)})`); |
| 1519 | } |
| 1520 | /** |
| 1521 | * Re-evaluate every fiber that requires one of the given services. |
| 1522 | * |
| 1523 | * @param names — the service names that changed. |
| 1524 | * @param filter — restricts notification to matching isolation scopes. |
| 1525 | */ |
| 1526 | notify(names, filter = (ctx, name) => ctx[symbols.isolate][name] === this.ctx[symbols.isolate][name]) { |
| 1527 | for (const runtime of this.ctx.registry.values()) for (const fiber of runtime.fibers) { |
| 1528 | let hasUpdate = false; |
| 1529 | for (const name of names) { |
| 1530 | if (!(name in fiber.inject)) continue; |
| 1531 | if (!filter(fiber.ctx, name)) continue; |
| 1532 | hasUpdate = true; |
| 1533 | fiber._checkImpl(name); |
| 1534 | } |
| 1535 | if (!hasUpdate) continue; |
| 1536 | fiber._refresh(); |
| 1537 | } |
| 1538 | for (const name of names) { |
| 1539 | const self = Object.create(this.ctx); |
| 1540 | self[symbols.filter] = (target) => filter(target, name); |
| 1541 | this.ctx.events.emit(self, "internal/service", name, this._getImpl(name, false)?.value); |
| 1542 | } |
| 1543 | } |
| 1544 | /** |
| 1545 | * Define a computed context property backed by get/set hooks. |
| 1546 | * |
| 1547 | * @param name — the context property name. |
| 1548 | * @param options — the `get` hook and optional `set` hook. |
| 1549 | * @returns a disposer that removes the accessor. |
| 1550 | */ |
| 1551 | accessor(name, options) { |
| 1552 | return this.ctx.fiber.effect(() => { |
| 1553 | if (name in this.props) throw new Error(`property "${name}" is already declared as ${this.props[name].type}`); |
| 1554 | this.props[name] = { |
| 1555 | type: "accessor", |
| 1556 | ...options |
| 1557 | }; |
| 1558 | return () => delete this.props[name]; |
| 1559 | }, `ctx.accessor(${JSON.stringify(name)})`); |
| 1560 | } |
| 1561 | /** |
| 1562 | * Expose selected members of a service directly on `ctx`. |
| 1563 | * |
| 1564 | * See the `ctx.mixin()` overload above for the full contract. |
| 1565 | * |
| 1566 | * @param source — a context property name or a source object. |
| 1567 | * @param mixins — keys to forward, or a source-key → ctx-key map. |
| 1568 | * @returns a disposer that removes all created accessors. |
| 1569 | */ |
| 1570 | mixin(source, mixins) { |
| 1571 | const self = this; |
| 1572 | return this.ctx.fiber.effect(function* () { |
| 1573 | const entries = Array.isArray(mixins) ? mixins.map((key) => [key, key]) : Object.entries(mixins); |
| 1574 | const getTarget = (ctx, error) => { |
| 1575 | return ctx[source]; |
| 1576 | }; |
| 1577 | for (const [key, value] of entries) yield self.accessor(value, { |
| 1578 | get(receiver, error) { |
| 1579 | const service = getTarget(this, error); |
| 1580 | if (isNullable(service)) return service; |
| 1581 | const mixin = receiver ? withProps(receiver, service) : service; |
| 1582 | const value2 = Reflect.get(service, key, mixin); |
| 1583 | if (typeof value2 !== "function") return value2; |
| 1584 | return value2.bind(mixin ?? service); |
| 1585 | }, |
| 1586 | set(value2, receiver, error) { |
| 1587 | const service = getTarget(this, error); |
| 1588 | const mixin = receiver ? withProps(receiver, service) : service; |
| 1589 | return Reflect.set(service, key, value2, mixin); |
| 1590 | } |
| 1591 | }); |
| 1592 | }, `ctx.mixin(${JSON.stringify(source)})`); |
| 1593 | } |
| 1594 | /** |
| 1595 | * Attach this context's tracing wrapper to a value. |
| 1596 | * |
| 1597 | * @param value — the value to wrap. |
| 1598 | * @returns the traceable wrapper (or the value itself when not applicable). |
| 1599 | */ |
| 1600 | trace(value) { |
| 1601 | return getTraceable(this.ctx, value); |
| 1602 | } |
| 1603 | /** |
| 1604 | * Wrap a callback so calls trace `this` and arguments to this context. |
| 1605 | * |
| 1606 | * @param callback — the function to wrap. |
| 1607 | * @returns a proxy delegating to `callback` with traced values. |
| 1608 | */ |
| 1609 | bind(callback) { |
| 1610 | return new Proxy(callback, { |
| 1611 | apply: (target, thisArg, args) => { |
| 1612 | return Reflect.apply(target, this.trace(thisArg), args.map((arg) => this.trace(arg))); |
| 1613 | }, |
| 1614 | construct: (target, args, newTarget) => { |
| 1615 | return Reflect.construct(target, args.map((arg) => this.trace(arg)), newTarget); |
| 1616 | } |
| 1617 | }); |
| 1618 | } |
| 1619 | }; |
| 1620 | function isApplicable(object) { |
| 1621 | return object && typeof object === "object" && typeof object.apply === "function"; |
| 1622 | } |
| 1623 | function Inject(name, config) { |
| 1624 | return function(value, decorator) { |
| 1625 | if (decorator.kind === "class") { |
| 1626 | if (!Object.hasOwn(value, "inject")) { |
| 1627 | defineProperty(value, "inject", Object.create(Object.getPrototypeOf(value).inject ?? null)); |
| 1628 | defineProperty(value.inject, symbols.checkProto, true); |
| 1629 | } |
| 1630 | value.inject[name] = config; |
| 1631 | } else if (decorator.kind === "method") { |
| 1632 | const inject = (value[symbols.metadata] ??= {}).inject ??= /* @__PURE__ */ Object.create(null); |
| 1633 | inject[name] = config; |
| 1634 | decorator.addInitializer(function() { |
| 1635 | const property = this[symbols.tracker]?.property; |
| 1636 | (this[symbols.initHooks] ??= []).push(() => { |
| 1637 | this.ctx.inject(inject, (ctx) => { |
| 1638 | return value.call(property ? withProps(this, { [property]: ctx }) : this); |
| 1639 | }); |
| 1640 | }); |
| 1641 | }); |
| 1642 | } else throw new Error("@Inject() can only be used on class or class methods"); |
| 1643 | }; |
| 1644 | } |
| 1645 | (function(Inject2) { |
| 1646 | function resolve(inject, result = /* @__PURE__ */ Object.create(null)) { |
| 1647 | if (!inject) return result; |
| 1648 | if (Array.isArray(inject)) for (const name of inject) result[name] = null; |
| 1649 | else if (Reflect.has(inject, symbols.checkProto)) { |
| 1650 | Object.assign(result, resolve(Object.getPrototypeOf(inject))); |
| 1651 | for (const name of Object.keys(inject)) result[name] = inject[name] ?? null; |
| 1652 | } else for (const name of Object.keys(inject)) result[name] = inject[name] ?? null; |
| 1653 | return result; |
| 1654 | } |
| 1655 | Inject2.resolve = resolve; |
| 1656 | })(Inject || (Inject = {})); |
| 1657 | var RegistryService = class { |
| 1658 | ctx; |
| 1659 | _counter = 0; |
| 1660 | _internal = /* @__PURE__ */ new Map(); |
| 1661 | constructor(ctx) { |
| 1662 | this.ctx = ctx; |
| 1663 | defineProperty(this, symbols.tracker, { |
| 1664 | property: "ctx", |
| 1665 | noShadow: true |
| 1666 | }); |
| 1667 | } |
| 1668 | /** Allocate the next fiber uid (increments on every read). */ |
| 1669 | get counter() { |
| 1670 | return ++this._counter; |
| 1671 | } |
| 1672 | /** Number of registered plugin runtimes. */ |
| 1673 | get size() { |
| 1674 | return this._internal.size; |
| 1675 | } |
| 1676 | /** |
| 1677 | * Resolve a supported plugin shape to its executable callback. |
| 1678 | * |
| 1679 | * @param plugin — a function, class, or `{ apply }` object plugin. |
| 1680 | * @returns the callback identifying the plugin, or `undefined` if invalid. |
| 1681 | */ |
| 1682 | resolve(plugin) { |
| 1683 | try { |
| 1684 | if (typeof plugin === "function") return plugin; |
| 1685 | if (isApplicable(plugin)) return plugin.apply; |
| 1686 | } catch { |
| 1687 | } |
| 1688 | } |
| 1689 | /** |
| 1690 | * Look up the runtime record for a plugin. |
| 1691 | * |
| 1692 | * @param plugin — any supported plugin shape. |
| 1693 | * @returns the runtime, or `undefined` when the plugin is not registered. |
| 1694 | */ |
| 1695 | get(plugin) { |
| 1696 | const key = this.resolve(plugin); |
| 1697 | return key && this._internal.get(key); |
| 1698 | } |
| 1699 | /** |
| 1700 | * Check whether a plugin has a registered runtime. |
| 1701 | * |
| 1702 | * @param plugin — any supported plugin shape. |
| 1703 | * @returns `true` when at least one fiber of the plugin exists. |
| 1704 | */ |
| 1705 | has(plugin) { |
| 1706 | const key = this.resolve(plugin); |
| 1707 | return !!key && this._internal.has(key); |
| 1708 | } |
| 1709 | /** |
| 1710 | * Dispose every running fiber for a plugin and remove its runtime record. |
| 1711 | * |
| 1712 | * @param plugin — any supported plugin shape. |
| 1713 | * @returns the removed runtime, or `undefined` when none was registered. |
| 1714 | */ |
| 1715 | delete(plugin) { |
| 1716 | const key = this.resolve(plugin); |
| 1717 | const runtime = key && this._internal.get(key); |
| 1718 | if (!runtime) return; |
| 1719 | this._internal.delete(key); |
| 1720 | for (const fiber of runtime.fibers) fiber.dispose(); |
| 1721 | return runtime; |
| 1722 | } |
| 1723 | /** Iterate the registered plugin callbacks. */ |
| 1724 | keys() { |
| 1725 | return this._internal.keys(); |
| 1726 | } |
| 1727 | /** Iterate the registered plugin runtimes. */ |
| 1728 | values() { |
| 1729 | return this._internal.values(); |
| 1730 | } |
| 1731 | /** Iterate `[callback, runtime]` pairs. */ |
| 1732 | entries() { |
| 1733 | return this._internal.entries(); |
| 1734 | } |
| 1735 | /** |
| 1736 | * Visit every registered runtime. |
| 1737 | * |
| 1738 | * @param callback — receives each runtime and its identifying callback. |
| 1739 | */ |
| 1740 | forEach(callback) { |
| 1741 | return this._internal.forEach(callback); |
| 1742 | } |
| 1743 | /** |
| 1744 | * Start a callback once the requested dependencies are available. |
| 1745 | * |
| 1746 | * @param inject — required services, as an array or a name → config map. |
| 1747 | * @param callback — plugin body called with `(ctx, config)`. |
| 1748 | * @returns the fiber; awaiting it settles once loading finished. |
| 1749 | */ |
| 1750 | inject(inject, callback) { |
| 1751 | return this.plugin({ |
| 1752 | inject, |
| 1753 | apply: callback, |
| 1754 | name: callback.name |
| 1755 | }); |
| 1756 | } |
| 1757 | /** |
| 1758 | * Start a plugin in the current context and return its fiber. |
| 1759 | * |
| 1760 | * Creates (or reuses) the plugin's runtime record, then starts a new fiber |
| 1761 | * under the current context. Throws if `plugin` is not a supported shape or |
| 1762 | * if the current fiber is already disposed. |
| 1763 | * |
| 1764 | * @param plugin — a function, class, or `{ apply }` object plugin. |
| 1765 | * @param config — the plugin config, validated against its `Config` schema. |
| 1766 | * @param getOuterStack — captures the caller stack for effect diagnostics. |
| 1767 | * @returns the fiber; awaiting it settles once loading finished. |
| 1768 | */ |
| 1769 | plugin(plugin, config, getOuterStack = buildOuterStack()) { |
| 1770 | const callback = this.resolve(plugin); |
| 1771 | if (!callback) throw new Error('invalid plugin, expect function or object with an "apply" method, received ' + typeof plugin); |
| 1772 | this.ctx.fiber.assertActive(); |
| 1773 | let runtime = this._internal.get(callback); |
| 1774 | if (!runtime) { |
| 1775 | let name = plugin.name; |
| 1776 | if (name === "apply") name = void 0; |
| 1777 | runtime = { |
| 1778 | name, |
| 1779 | callback, |
| 1780 | fibers: new DisposableList(), |
| 1781 | Config: plugin.Config |
| 1782 | }; |
| 1783 | this._internal.set(callback, runtime); |
| 1784 | } |
| 1785 | const fiber = new Fiber(this.ctx, config, Inject.resolve(plugin.inject), runtime, getOuterStack); |
| 1786 | const wrapped = Object.create(fiber); |
| 1787 | wrapped.then = (onFulfilled, onRejected) => { |
| 1788 | return fiber.await().then(onFulfilled, onRejected); |
| 1789 | }; |
| 1790 | return wrapped; |
| 1791 | } |
| 1792 | }; |
| 1793 | var Context = class Context2 { |
| 1794 | /** Symbol key under which a disposer exposes its {@link EffectMeta} diagnostics tree. */ |
| 1795 | static effect = symbols.effect; |
| 1796 | /** Symbol key for a context's listener filter, consulted on every event dispatch. */ |
| 1797 | static filter = symbols.filter; |
| 1798 | /** Symbol key of the isolation map (see the `Context[symbols.isolate]` property). */ |
| 1799 | static isolate = symbols.isolate; |
| 1800 | /** Symbol key of the intercept map (see the `Context[symbols.intercept]` property). */ |
| 1801 | static intercept = symbols.intercept; |
| 1802 | /** |
| 1803 | * Returns true for Cordis context proxies and context prototypes. |
| 1804 | * |
| 1805 | * Works across realms and across multiple copies of cordis, because the |
| 1806 | * brand is keyed by a global symbol rather than by `instanceof`. |
| 1807 | * |
| 1808 | * @param value — the value to test. |
| 1809 | * @returns `true` if `value` is a Cordis context, narrowing its type. |
| 1810 | */ |
| 1811 | static is(value) { |
| 1812 | return !!value?.[Context2.is]; |
| 1813 | } |
| 1814 | static { |
| 1815 | Context2.is[Symbol.toPrimitive] = () => /* @__PURE__ */ Symbol.for("cordis.is"); |
| 1816 | Context2.prototype[Context2.is] = true; |
| 1817 | } |
| 1818 | /** Create the root context and install the built-in services. */ |
| 1819 | constructor() { |
| 1820 | this[symbols.isolate] = /* @__PURE__ */ Object.create(null); |
| 1821 | this[symbols.intercept] = /* @__PURE__ */ Object.create(null); |
| 1822 | const self = new Proxy(this, ReflectService.handler); |
| 1823 | this.root = self; |
| 1824 | this.baseUrl = void 0; |
| 1825 | this.fiber = new Fiber(self, {}, /* @__PURE__ */ Object.create(null), null, () => []); |
| 1826 | this.reflect = new ReflectService(self); |
| 1827 | this.registry = new RegistryService(self); |
| 1828 | this.events = new EventsService(self); |
| 1829 | this.logger = new LoggerService(self); |
| 1830 | this.fiber._disposables.clear(); |
| 1831 | return self; |
| 1832 | } |
| 1833 | [/* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom")]() { |
| 1834 | return `Context <${this.fiber.name}>`; |
| 1835 | } |
| 1836 | /** |
| 1837 | * Create a child context with extra metadata on top of the current scope. |
| 1838 | * |
| 1839 | * The child prototypally inherits every property of this context; own |
| 1840 | * properties of `meta` shadow the inherited ones. The parent is not mutated. |
| 1841 | * |
| 1842 | * @param meta — own properties (including symbol keys) to define on the child. |
| 1843 | * @returns a child context inheriting from this one. |
| 1844 | */ |
| 1845 | extend(meta = {}) { |
| 1846 | const shadow = Reflect.getOwnPropertyDescriptor(this, symbols.shadow)?.value; |
| 1847 | const self = Object.create(getTraceable(this, this)); |
| 1848 | for (const prop of Reflect.ownKeys(meta)) Object.defineProperty(self, prop, Reflect.getOwnPropertyDescriptor(meta, prop)); |
| 1849 | if (!shadow) return self; |
| 1850 | return Object.assign(Object.create(self), { [symbols.shadow]: shadow }); |
| 1851 | } |
| 1852 | /** |
| 1853 | * Create a child context with an independent service scope for `name`. |
| 1854 | * |
| 1855 | * Below the returned context, reads and writes of the service `name` |
| 1856 | * resolve against the new label instead of the parent's, so a different |
| 1857 | * implementation can be provided without affecting the parent scope. |
| 1858 | * Passing the same `label` to two `isolate()` calls joins their scopes. |
| 1859 | * |
| 1860 | * @param name — the service name to isolate. |
| 1861 | * @param label — scope label to join; defaults to a fresh unique symbol. |
| 1862 | * @returns a child context whose `name` service resolves in the new scope. |
| 1863 | */ |
| 1864 | isolate(name, label) { |
| 1865 | const shadow = Object.create(this[symbols.isolate]); |
| 1866 | shadow[name] = label ?? Symbol(name); |
| 1867 | return this.extend({ [symbols.isolate]: shadow }); |
| 1868 | } |
| 1869 | intercept(name, config) { |
| 1870 | const intercept = Object.create(this[symbols.intercept]); |
| 1871 | intercept[name] = config; |
| 1872 | return this.extend({ [symbols.intercept]: intercept }); |
| 1873 | } |
| 1874 | }; |
| 1875 | var Service = class Service2 { |
| 1876 | ctx; |
| 1877 | /** Symbol key of an instance method run after construction (class plugins). */ |
| 1878 | static init = symbols.init; |
| 1879 | /** Symbol key of the availability predicate passed to `ctx.provide()`. */ |
| 1880 | static check = symbols.check; |
| 1881 | /** Symbol key of the phantom intercept-config type parameter. */ |
| 1882 | static config = symbols.config; |
| 1883 | /** Symbol key of the call body making a service callable (e.g. `ctx.logger()`). */ |
| 1884 | static invoke = symbols.invoke; |
| 1885 | /** Symbol key of the helper deriving an extended service instance. */ |
| 1886 | static extend = symbols.extend; |
| 1887 | /** Symbol key of the tracker metadata used for context tracing. */ |
| 1888 | static tracker = symbols.tracker; |
| 1889 | /** Symbol key of the intercept-config resolution helper below. */ |
| 1890 | static resolveConfig = symbols.resolveConfig; |
| 1891 | /** The service name this instance is registered under. */ |
| 1892 | name; |
| 1893 | /** |
| 1894 | * Register this instance as `name` in the current context. |
| 1895 | * |
| 1896 | * Calls `ctx.reflect.provide(name, this, this[Service.check])`, so the |
| 1897 | * service is unregistered automatically when the owning fiber unloads. |
| 1898 | * Services with a `[Service.invoke]` body return a callable instance. |
| 1899 | * |
| 1900 | * @param ctx — the context to register in (stored as `this.ctx`). |
| 1901 | * @param name — the service name; defaults to the static `provide` field. |
| 1902 | */ |
| 1903 | constructor(ctx, name) { |
| 1904 | this.ctx = ctx; |
| 1905 | name ??= this.constructor["provide"]; |
| 1906 | let self = this; |
| 1907 | const tracker = { |
| 1908 | associate: name, |
| 1909 | property: "ctx" |
| 1910 | }; |
| 1911 | if (self[symbols.invoke]) self = createCallable(name, joinPrototype(Object.getPrototypeOf(this), Function.prototype), tracker); |
| 1912 | self.ctx = ctx; |
| 1913 | self.name = name; |
| 1914 | defineProperty(self, symbols.tracker, tracker); |
| 1915 | self.ctx.reflect.provide(name, self, this[symbols.check]); |
| 1916 | return self; |
| 1917 | } |
| 1918 | [symbols.filter](ctx) { |
| 1919 | return ctx[symbols.isolate][this.name] === this.ctx[symbols.isolate][this.name]; |
| 1920 | } |
| 1921 | [symbols.extend](props) { |
| 1922 | let self; |
| 1923 | if (this[Service2.invoke]) self = createCallable(this.name, this, this[symbols.tracker]); |
| 1924 | else self = Object.create(this); |
| 1925 | return Object.assign(self, props); |
| 1926 | } |
| 1927 | /** |
| 1928 | * Merge intercept config from ancestors with optional base and head values. |
| 1929 | * |
| 1930 | * Entries added closer to the root apply first; `base` is prepended and |
| 1931 | * `head` appended. Uses `Config.merge` when the service declares one, |
| 1932 | * otherwise a shallow `Object.assign`. |
| 1933 | * |
| 1934 | * @param base — lowest-precedence config merged before all intercepts. |
| 1935 | * @param head — highest-precedence config merged after all intercepts. |
| 1936 | * @returns the merged config. |
| 1937 | */ |
| 1938 | [symbols.resolveConfig](base, head) { |
| 1939 | let intercept = this.ctx[Context.intercept]; |
| 1940 | const configs = []; |
| 1941 | while (this.name in intercept) { |
| 1942 | if (Object.hasOwn(intercept, this.name)) configs.unshift(intercept[this.name]); |
| 1943 | intercept = Object.getPrototypeOf(intercept); |
| 1944 | } |
| 1945 | if (base) configs.unshift(base); |
| 1946 | if (head) configs.push(head); |
| 1947 | if (this["Config"]?.merge) return this["Config"].merge(...configs); |
| 1948 | else return Object.assign({}, ...configs); |
| 1949 | } |
| 1950 | static [Symbol.hasInstance](instance) { |
| 1951 | if (!instance) return false; |
| 1952 | let constructor = instance.constructor; |
| 1953 | while (constructor) { |
| 1954 | constructor = constructor.prototype?.constructor; |
| 1955 | if (constructor === this) return true; |
| 1956 | constructor &&= Object.getPrototypeOf(constructor); |
| 1957 | } |
| 1958 | return false; |
| 1959 | } |
| 1960 | }; |
| 1961 | |
| 1962 | // src/shims/owned.ts |
| 1963 | function describeError(error) { |
| 1964 | return error instanceof Error ? `${error.name}: ${error.message}` : String(error); |
| 1965 | } |
| 1966 | var OwnedRegistrations = class { |
| 1967 | /** Admitted entries by core handle. */ |
| 1968 | byHandle = /* @__PURE__ */ new Map(); |
| 1969 | rpc; |
| 1970 | kind; |
| 1971 | /** The owner's own index of this kind, for the leak report at deactivation. */ |
| 1972 | ownedBy; |
| 1973 | warn; |
| 1974 | constructor(rpc, kind, ownedBy, warn) { |
| 1975 | this.rpc = rpc; |
| 1976 | this.kind = kind; |
| 1977 | this.ownedBy = ownedBy; |
| 1978 | this.warn = warn; |
| 1979 | } |
| 1980 | /** Called inside the owner's effect; returns the effect's cleanup. */ |
| 1981 | add(entry, spec) { |
| 1982 | const owner = entry.owner; |
| 1983 | if (owner.state !== "activating" && owner.state !== "active") throw new Error("registration owner was disposed"); |
| 1984 | const registration = this.rpc.request("registry/register", { owner: owner.ref, ...owner.scope ? { scope: owner.scope } : {}, kind: this.kind, spec }).then( |
| 1985 | (result) => { |
| 1986 | if (typeof result?.handle === "number") { |
| 1987 | entry.handle = result.handle; |
| 1988 | if (entry.disposed || owner.state !== "activating" && owner.state !== "active") { |
| 1989 | return this.unregister(entry); |
| 1990 | } |
| 1991 | this.ownedBy(owner).set(result.handle, entry); |
| 1992 | this.byHandle.set(result.handle, entry); |
| 1993 | } else { |
| 1994 | const reason = typeof result?.refused === "string" ? result.refused : "refused without a reason"; |
| 1995 | owner.refusals.push(`${this.kind} \`${entry.name}\` refused: ${reason}`); |
| 1996 | if (owner.state === "active") this.warn(`${this.kind} \`${entry.name}\` refused: ${reason}`, owner); |
| 1997 | } |
| 1998 | }, |
| 1999 | (error) => { |
| 2000 | owner.refusals.push(`${this.kind} \`${entry.name}\` registration failed: ${describeError(error)}`); |
| 2001 | } |
| 2002 | ).finally(() => owner.pendingRegistrations.delete(registration)); |
| 2003 | owner.pendingRegistrations.add(registration); |
| 2004 | return () => { |
| 2005 | if (entry.disposed) return; |
| 2006 | entry.disposed = true; |
| 2007 | if (entry.handle !== void 0) void this.unregister(entry); |
| 2008 | }; |
| 2009 | } |
| 2010 | /** Undo exactly this entry. The core revokes first, so a failure here is expected after revocation. */ |
| 2011 | unregister(entry) { |
| 2012 | const handle = entry.handle; |
| 2013 | const owner = entry.owner; |
| 2014 | this.ownedBy(owner).delete(handle); |
| 2015 | this.byHandle.delete(handle); |
| 2016 | const cleanup = this.rpc.request("registry/unregister", { owner: owner.ref, handle }).then(() => void 0, () => void 0).finally(() => owner.pendingRegistrations.delete(cleanup)); |
| 2017 | owner.pendingRegistrations.add(cleanup); |
| 2018 | return cleanup; |
| 2019 | } |
| 2020 | /** Drop the host's index of everything `owner` registered (after its teardown). */ |
| 2021 | forget(owner) { |
| 2022 | for (const entry of this.ownedBy(owner).values()) this.byHandle.delete(entry.handle); |
| 2023 | } |
| 2024 | }; |
| 2025 | |
| 2026 | // src/shims/avatars.ts |
| 2027 | var MAX_AVATAR_PACKS_PER_OWNER = 4; |
| 2028 | var MAX_AVATAR_PACKS_PER_HOST = 16; |
| 2029 | function normalizeAvatarPack(value) { |
| 2030 | if (typeof value !== "object" || value === null || Array.isArray(value) || Object.keys(value).some((key) => key !== "path")) throw new TypeError("avatar pack supports only path"); |
| 2031 | const { path } = value; |
| 2032 | if (typeof path !== "string" || !path || Buffer.byteLength(path, "utf8") > 256 || !path.endsWith(".json") || /[\\:\u0000-\u001f\u007f-\u009f]/u.test(path) || path.split("/").some((part) => !part || part === "." || part === "..")) { |
| 2033 | throw new TypeError("avatar pack path must be a bounded bundle-relative path with normal slash-separated components"); |
| 2034 | } |
| 2035 | return Object.freeze({ path }); |
| 2036 | } |
| 2037 | var AvatarPacks = class { |
| 2038 | registrations; |
| 2039 | owners = /* @__PURE__ */ new Map(); |
| 2040 | count = 0; |
| 2041 | constructor(rpc, ownedBy, warn) { |
| 2042 | this.registrations = new OwnedRegistrations(rpc, "avatar_pack", ownedBy, warn); |
| 2043 | } |
| 2044 | register(owner, definition) { |
| 2045 | if (owner.state !== "activating" && owner.state !== "active") throw new Error("avatar owner is not live"); |
| 2046 | const { path } = normalizeAvatarPack(definition); |
| 2047 | const roots = this.owners.get(owner) ?? /* @__PURE__ */ new Map(); |
| 2048 | if (roots.has(path)) throw new Error("avatar pack is already registered; dispose it before registering it again"); |
| 2049 | if (roots.size >= MAX_AVATAR_PACKS_PER_OWNER || this.count >= MAX_AVATAR_PACKS_PER_HOST) throw new RangeError("avatar pack owner or host registration limit reached"); |
| 2050 | const undo = this.registrations.add({ owner, name: path, disposed: false }, { name: path, description: "" }); |
| 2051 | const dispose = () => { |
| 2052 | if (roots.get(path) !== dispose) return; |
| 2053 | roots.delete(path); |
| 2054 | this.count--; |
| 2055 | if (!roots.size) this.owners.delete(owner); |
| 2056 | undo(); |
| 2057 | }; |
| 2058 | roots.set(path, dispose); |
| 2059 | this.owners.set(owner, roots); |
| 2060 | this.count++; |
| 2061 | return dispose; |
| 2062 | } |
| 2063 | forget(owner) { |
| 2064 | for (const dispose of [...this.owners.get(owner)?.values() ?? []]) dispose(); |
| 2065 | this.registrations.forget(owner); |
| 2066 | } |
| 2067 | }; |
| 2068 | function defineAvatarsService(host) { |
| 2069 | class AvatarsShim extends Service { |
| 2070 | constructor(ctx) { |
| 2071 | super(ctx, "avatars"); |
| 2072 | } |
| 2073 | registerPack(definition) { |
| 2074 | const ctx = this.ctx; |
| 2075 | const owner = host.ownerOf(ctx); |
| 2076 | if (!owner) throw new Error("avatars.registerPack called outside a plugin owner"); |
| 2077 | const root = normalizeAvatarPack(definition); |
| 2078 | return ctx.effect(() => host.avatarPacks.register(owner, root), `avatars.registerPack(${JSON.stringify(root.path)})`); |
| 2079 | } |
| 2080 | } |
| 2081 | Object.freeze(AvatarsShim.prototype); |
| 2082 | return AvatarsShim; |
| 2083 | } |
| 2084 | export { |
| 2085 | AvatarPacks, |
| 2086 | MAX_AVATAR_PACKS_PER_HOST, |
| 2087 | MAX_AVATAR_PACKS_PER_OWNER, |
| 2088 | defineAvatarsService, |
| 2089 | normalizeAvatarPack |
| 2090 | }; |
| 2091 |