{"version":3,"file":"index.mjs","names":[],"sources":["../../src/context-disposed-error.ts","../../src/context.ts","../../src/promise-utils.ts","../../src/resource.ts","../../src/trace-context.ts"],"sourcesContent":["//\n// Copyright 2023 DXOS.org\n//\n\nexport class ContextDisposedError extends Error {\n  constructor() {\n    super('Context disposed.');\n  }\n}\n","//\n// Copyright 2022 DXOS.org\n//\n\nimport { inspect } from 'node:util';\n\nimport { StackTrace } from '@dxos/debug';\nimport { type CallMetadata, log } from '@dxos/log';\nimport { safeInstanceof } from '@dxos/util';\n\nimport { ContextDisposedError } from './context-disposed-error';\n\nexport type ContextErrorHandler = (error: Error, ctx: Context) => void;\n\nexport type DisposeCallback = () => any | Promise<any>;\n\nexport type CreateContextProps = {\n  name?: string;\n  parent?: Context;\n  attributes?: Record<string, any>;\n  onError?: ContextErrorHandler;\n};\n\nconst DEBUG_LOG_DISPOSE = false;\n\n/**\n * Maximum number of dispose callbacks before we start logging warnings.\n */\nconst MAX_SAFE_DISPOSE_CALLBACKS = 300;\n\nconst DEFAULT_ERROR_HANDLER: ContextErrorHandler = (error, ctx) => {\n  if (error instanceof ContextDisposedError) {\n    return;\n  }\n\n  void ctx.dispose();\n\n  // Will generate an unhandled rejection.\n  throw error;\n};\n\ntype ContextFlags = number;\n\nconst CONTEXT_FLAG_IS_DISPOSED: ContextFlags = 1 << 0;\n\n/**\n * Whether the dispose callback leak was detected.\n */\nconst CONTEXT_FLAG_LEAK_DETECTED: ContextFlags = 1 << 1;\n\n/**\n * NOTE: Context is not reusable after it is disposed.\n */\n@safeInstanceof('Context')\nexport class Context {\n  static default(): Context {\n    return new Context();\n  }\n\n  readonly #disposeCallbacks: DisposeCallback[] = [];\n\n  readonly #name?: string = undefined;\n  readonly #parent?: Context = undefined;\n  readonly #attributes: Record<string, any>;\n  readonly #onError: ContextErrorHandler;\n\n  #flags: ContextFlags = 0;\n  #disposePromise?: Promise<boolean> = undefined;\n\n  #signal: AbortSignal | undefined = undefined;\n\n  public maxSafeDisposeCallbacks = MAX_SAFE_DISPOSE_CALLBACKS;\n\n  constructor(params: CreateContextProps = {}, callMeta?: Partial<CallMetadata>) {\n    this.#name = getContextName(params, callMeta);\n    this.#parent = params.parent;\n    this.#attributes = params.attributes ?? {};\n    this.#onError = params.onError ?? DEFAULT_ERROR_HANDLER;\n  }\n\n  get #isDisposed() {\n    return !!(this.#flags & CONTEXT_FLAG_IS_DISPOSED);\n  }\n\n  set #isDisposed(value: boolean) {\n    this.#flags = value ? this.#flags | CONTEXT_FLAG_IS_DISPOSED : this.#flags & ~CONTEXT_FLAG_IS_DISPOSED;\n  }\n\n  get #leakDetected() {\n    return !!(this.#flags & CONTEXT_FLAG_LEAK_DETECTED);\n  }\n\n  set #leakDetected(value: boolean) {\n    this.#flags = value ? this.#flags | CONTEXT_FLAG_LEAK_DETECTED : this.#flags & ~CONTEXT_FLAG_LEAK_DETECTED;\n  }\n\n  get disposed() {\n    return this.#isDisposed;\n  }\n\n  get disposeCallbacksLength() {\n    return this.#disposeCallbacks.length;\n  }\n\n  get signal(): AbortSignal {\n    if (this.#signal) {\n      return this.#signal;\n    }\n    const controller = new AbortController();\n    this.#signal = controller.signal;\n    this.onDispose(() => controller.abort());\n    return this.#signal;\n  }\n\n  /**\n   * Schedules a callback to run when the context is disposed.\n   * May be async, in this case the disposer might choose to wait for all resource to released.\n   * Throwing an error inside the callback will result in the error being logged, but not re-thrown.\n   *\n   * NOTE: Will call the callback immediately if the context is already disposed.\n   *\n   * @returns A function that can be used to remove the callback from the dispose list.\n   */\n  onDispose(callback: DisposeCallback): () => void {\n    if (this.#isDisposed) {\n      // Call the callback immediately if the context is already disposed.\n      void (async () => {\n        try {\n          await callback();\n        } catch (error: any) {\n          log.catch(error, { context: this.#name });\n        }\n      })();\n    }\n\n    this.#disposeCallbacks.push(callback);\n    if (this.#disposeCallbacks.length > this.maxSafeDisposeCallbacks && !this.#leakDetected) {\n      this.#leakDetected = true;\n      const callSite = new StackTrace().getStackArray(1)[0].trim();\n      log.warn('Context has a large number of dispose callbacks (this might be a memory leak).', {\n        context: this.#name,\n        callSite,\n        count: this.#disposeCallbacks.length,\n      });\n    }\n\n    // Remove handler.\n    return () => {\n      const index = this.#disposeCallbacks.indexOf(callback);\n      if (index !== -1) {\n        this.#disposeCallbacks.splice(index, 1);\n      }\n    };\n  }\n\n  /**\n   * Runs all dispose callbacks.\n   * Callbacks are run in the reverse order they were added.\n   * This function never throws.\n   * It is safe to ignore the returned promise if the caller does not wish to wait for callbacks to complete.\n   * Disposing context means that onDispose will throw an error and any errors raised will be logged and not propagated.\n   * @returns true if there were no errors during the dispose process.\n   */\n  async dispose(throwOnError = false): Promise<boolean> {\n    if (this.#disposePromise) {\n      return this.#disposePromise;\n    }\n\n    // TODO(burdon): Probably should not be set until the dispose is complete, but causes tests to fail if moved.\n    this.#isDisposed = true;\n\n    // Set the promise before running the callbacks.\n    let resolveDispose!: (value: boolean) => void;\n    const promise = new Promise<boolean>((resolve) => {\n      resolveDispose = resolve;\n    });\n    this.#disposePromise = promise;\n\n    // Process last first.\n    // Clone the array so that any mutations to the original array don't affect the dispose process.\n    const callbacks = Array.from(this.#disposeCallbacks).reverse();\n    this.#disposeCallbacks.length = 0;\n\n    if (DEBUG_LOG_DISPOSE) {\n      log('disposing', { context: this.#name, count: callbacks.length });\n    }\n\n    let i = 0;\n    let clean = true;\n    const errors: Error[] = [];\n    for (const callback of callbacks) {\n      try {\n        await callback();\n        i++;\n      } catch (err: any) {\n        clean = false;\n        if (throwOnError) {\n          errors.push(err);\n        } else {\n          log.catch(err, { context: this.#name, callback: i, count: callbacks.length });\n        }\n      }\n    }\n\n    if (errors.length > 0) {\n      throw new AggregateError(errors);\n    }\n\n    resolveDispose(clean);\n    if (DEBUG_LOG_DISPOSE) {\n      log('disposed', { context: this.#name });\n    }\n\n    return clean;\n  }\n\n  /**\n   * Raise the error inside the context.\n   * The error will be propagated to the error handler.\n   * IF the error handler is not set, the error will dispose the context and cause an unhandled rejection.\n   */\n  raise(error: Error): void {\n    if (this.#isDisposed) {\n      // TODO(dmaretskyi): Don't log those.\n      // log.warn('Error in disposed context', error);\n      return;\n    }\n\n    try {\n      this.#onError(error, this);\n    } catch (err) {\n      // Generate an unhandled rejection and stop the error propagation.\n      void Promise.reject(err);\n    }\n  }\n\n  derive({ onError, attributes }: CreateContextProps = {}): Context {\n    const newCtx = new Context({\n      parent: this,\n      // TODO(dmaretskyi): Optimize to not require allocating a new closure for every context.\n      onError: async (error) => {\n        if (!onError) {\n          this.raise(error);\n        } else {\n          try {\n            await onError(error, this);\n          } catch {\n            this.raise(error);\n          }\n        }\n      },\n      attributes,\n    });\n\n    const clearDispose = this.onDispose(() => newCtx.dispose());\n    newCtx.onDispose(clearDispose);\n    return newCtx;\n  }\n\n  getAttribute(key: string): any {\n    if (key in this.#attributes) {\n      return this.#attributes[key];\n    }\n    if (this.#parent) {\n      return this.#parent.getAttribute(key);\n    }\n\n    return undefined;\n  }\n\n  [Symbol.toStringTag] = 'Context';\n  [inspect.custom] = () => this.toString();\n\n  toString(): string {\n    return `Context(${this.#isDisposed ? 'disposed' : 'active'})`;\n  }\n\n  async [Symbol.asyncDispose](): Promise<void> {\n    await this.dispose();\n  }\n}\n\nconst getContextName = (params: CreateContextProps, callMeta?: Partial<CallMetadata>): string | undefined => {\n  if (params.name) {\n    return params.name;\n  }\n  if (callMeta?.F?.length) {\n    const pathSegments = callMeta?.F.split('/');\n    return `${pathSegments[pathSegments.length - 1]}#${callMeta?.L ?? 0}`;\n  }\n  return undefined;\n};\n","//\n// Copyright 2023 DXOS.org\n//\n\nimport { type Context } from './context';\nimport { ContextDisposedError } from './context-disposed-error';\n\n/**\n * @returns A promise that rejects when the context is disposed.\n */\n// TODO(dmaretskyi): Memory leak.\nexport const rejectOnDispose = (ctx: Context, error = new ContextDisposedError()): Promise<never> =>\n  new Promise((resolve, reject) => {\n    ctx.onDispose(() => reject(error));\n  });\n\n/**\n * Rejects the promise if the context is disposed.\n */\nexport const cancelWithContext = <T>(ctx: Context, promise: Promise<T>): Promise<T> => {\n  let clearDispose: () => void;\n  return Promise.race([\n    promise,\n    new Promise<never>((resolve, reject) => {\n      // Will be called before .finally() handlers.\n      clearDispose = ctx.onDispose(() => reject(new ContextDisposedError()));\n    }),\n  ]).finally(() => clearDispose?.());\n};\n","//\n// Copyright 2024 DXOS.org\n//\n\nimport '@hazae41/symbol-dispose-polyfill';\n\nimport { throwUnhandledError } from '@dxos/util';\n\nimport { Context } from './context';\n\nexport enum LifecycleState {\n  CLOSED = 'CLOSED',\n  OPEN = 'OPEN',\n  ERROR = 'ERROR',\n}\n\nexport interface Lifecycle {\n  open?(ctx?: Context): Promise<any> | any;\n  close?(): Promise<any> | any;\n}\n\n// Feature flag to be enabled later.\nconst CLOSE_RESOURCE_ON_UNHANDLED_ERROR = false;\n\n/**\n * Base class for resources that need to be opened and closed.\n */\nexport abstract class Resource implements Lifecycle {\n  #lifecycleState = LifecycleState.CLOSED;\n\n  #openPromise: Promise<void> | null = null;\n  #closePromise: Promise<void> | null = null;\n\n  /**\n   * Managed internally by the resource.\n   * Recreated on close.\n   * Errors are propagated to the `_catch` method and the parent context.\n   */\n  #internalCtx: Context = this.#createContext();\n\n  /**\n   * Context that is used to bubble up errors that are not handled by the resource.\n   * Provided in the open method.\n   */\n  #parentCtx: Context = this.#createParentContext();\n\n  /**\n   * ```ts\n   * await using resource = new Resource();\n   * await resource.open();\n   * ```\n   * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/using\n   */\n  async [Symbol.asyncDispose](): Promise<void> {\n    await this.close();\n  }\n\n  get #name() {\n    return Object.getPrototypeOf(this).constructor.name;\n  }\n\n  get isOpen() {\n    return this.#lifecycleState === LifecycleState.OPEN && this.#closePromise == null;\n  }\n\n  protected get _lifecycleState() {\n    return this.#lifecycleState;\n  }\n\n  protected get _ctx() {\n    return this.#internalCtx;\n  }\n\n  /**\n   * To be overridden by subclasses.\n   */\n  protected async _open(_ctx: Context): Promise<void> {}\n\n  /**\n   * To be overridden by subclasses.\n   */\n  protected async _close(_ctx: Context): Promise<void> {}\n\n  /**\n   * Error handler for errors that are caught by the context.\n   * By default, errors are bubbled up to the parent context which is passed to the open method.\n   */\n  protected async _catch(err: Error): Promise<void> {\n    if (CLOSE_RESOURCE_ON_UNHANDLED_ERROR) {\n      try {\n        await this.close();\n      } catch (doubleErr: any) {\n        throwUnhandledError(doubleErr);\n      }\n    }\n    throw err;\n  }\n\n  /**\n   * Calls the provided function, opening and closing the resource.\n   * NOTE: Consider using `using` instead.\n   * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/using\n   */\n  async use<T>(fn: (resource: this) => Promise<T>): Promise<T> {\n    try {\n      await this.open();\n      return await fn(this);\n    } finally {\n      await this.close();\n    }\n  }\n\n  /**\n   * Opens the resource.\n   * If the resource is already open, it does nothing.\n   * If the resource is in an error state, it throws an error.\n   * If the resource is closed, it waits for it to close and then opens it.\n   * @param ctx - Context to use for opening the resource. This context will receive errors that are not handled in `_catch`.\n   */\n  async open(ctx?: Context): Promise<this> {\n    switch (this.#lifecycleState) {\n      case LifecycleState.OPEN:\n        return this;\n      case LifecycleState.ERROR:\n        throw new Error(`Invalid state: ${this.#lifecycleState}`);\n      default:\n    }\n\n    await this.#closePromise;\n    await (this.#openPromise ??= this.#open(ctx));\n    return this;\n  }\n\n  /**\n   * Closes the resource.\n   * If the resource is already closed, it does nothing.\n   */\n  async close(ctx?: Context): Promise<this> {\n    if (this.#lifecycleState === LifecycleState.CLOSED) {\n      return this;\n    }\n    await this.#openPromise;\n    await (this.#closePromise ??= this.#close(ctx));\n    return this;\n  }\n\n  /**\n   * Waits until the resource is open.\n   */\n  async waitUntilOpen(): Promise<void> {\n    switch (this.#lifecycleState) {\n      case LifecycleState.OPEN:\n        return;\n      case LifecycleState.ERROR:\n        throw new Error(`Invalid state: ${this.#lifecycleState}`);\n    }\n\n    if (!this.#openPromise) {\n      throw new Error('Resource is not being opened');\n    }\n    await this.#openPromise;\n  }\n\n  async #open(ctx?: Context): Promise<void> {\n    this.#closePromise = null;\n    this.#parentCtx = ctx?.derive({ name: this.#name }) ?? this.#createParentContext();\n    this.#internalCtx = this.#createContext(this.#parentCtx);\n    await this._open(this.#parentCtx);\n    this.#lifecycleState = LifecycleState.OPEN;\n  }\n\n  async #close(ctx = Context.default()): Promise<void> {\n    this.#openPromise = null;\n    await this.#internalCtx.dispose();\n    await this._close(ctx);\n    this.#internalCtx = this.#createContext();\n    this.#lifecycleState = LifecycleState.CLOSED;\n  }\n\n  #createContext(attributeParent?: Context): Context {\n    return new Context({\n      name: this.#name,\n      parent: attributeParent,\n      onError: (error) =>\n        queueMicrotask(async () => {\n          try {\n            await this._catch(error);\n          } catch (err: any) {\n            this.#lifecycleState = LifecycleState.ERROR;\n            this.#parentCtx.raise(err);\n          }\n        }),\n    });\n  }\n\n  #createParentContext(): Context {\n    return new Context({ name: this.#name });\n  }\n}\n\nexport const openInContext = async <T extends Lifecycle>(ctx: Context, resource: T): Promise<T> => {\n  await resource.open?.(ctx);\n  ctx.onDispose(() => resource.close?.());\n  return resource;\n};\n","//\n// Copyright 2026 DXOS.org\n//\n\nimport { Context } from './context';\n\n/**\n * Context attribute key for trace context data.\n * Stores {@link TraceContextData} (W3C traceparent/tracestate strings).\n */\nexport const TRACE_SPAN_ATTRIBUTE = 'dxos.trace-span';\n\n/**\n * W3C Trace Context wire format for propagating trace identity.\n * Stored on DXOS {@link Context} attributes and carried across RPC boundaries.\n *\n * Because these are plain strings (not live runtime objects), they remain valid\n * after the originating span ends — enabling long-lived contexts (`this._ctx`)\n * to serve as parents for later child spans without a retention cache.\n *\n * @see https://www.w3.org/TR/trace-context/\n */\nexport type TraceContextData = {\n  /**\n   * W3C `traceparent` header value.\n   * Format: `{version}-{traceId}-{spanId}-{traceFlags}` (e.g., `00-abc...def-012...789-01`).\n   */\n  traceparent: string;\n  /** Optional W3C `tracestate` header value carrying vendor-specific trace data. */\n  tracestate?: string;\n};\n\n/**\n * Codec for propagating trace identity across RPC boundaries.\n *\n * Hardcoded in `RpcPeer` — every outgoing request calls {@link encode} to\n * extract W3C trace context from the DXOS `Context`, and every incoming\n * request calls {@link decode} to reconstruct a DXOS `Context` carrying the\n * caller's trace context.\n *\n * This works because `TRACE_SPAN_ATTRIBUTE` stores serializable\n * {@link TraceContextData} strings, not opaque runtime objects.\n */\nexport class ContextRpcCodec {\n  /**\n   * Read the W3C trace context from a DXOS `Context` for an outgoing RPC.\n   *\n   * @returns `TraceContextData` to attach to the wire message, or `undefined`\n   *          if the context has no active trace.\n   */\n  static encode(ctx: Context): TraceContextData | undefined {\n    const traceCtx = ctx.getAttribute(TRACE_SPAN_ATTRIBUTE);\n    if (traceCtx == null || typeof traceCtx.traceparent !== 'string') {\n      return undefined;\n    }\n    return traceCtx as TraceContextData;\n  }\n\n  /**\n   * Reconstruct a DXOS `Context` from W3C trace context received in an\n   * incoming RPC request.\n   *\n   * @returns A `Context` carrying the trace context, or `Context.default()`\n   *          if the data is missing/invalid.\n   */\n  static decode(traceContext: TraceContextData): Context {\n    if (typeof traceContext.traceparent !== 'string' || traceContext.traceparent.length === 0) {\n      return Context.default();\n    }\n    return new Context({ attributes: { [TRACE_SPAN_ATTRIBUTE]: traceContext } });\n  }\n}\n"],"mappings":";;;;;;AAIA,IAAa,uBAAb,cAA0C,MAAM;CAC9C,cAAc;EACZ,MAAM,mBAAmB;CAC3B;AACF;;;;;;;;;;;;;;;;ACoBA,IAAM,6BAA6B;AAEnC,IAAM,yBAA8C,OAAO,QAAQ;CACjE,IAAI,iBAAiB,sBACnB;CAGF,IAAS,QAAQ;CAGjB,MAAM;AACR;AAIA,IAAM,2BAAyC;;;;AAK/C,IAAM,6BAA2C;AAM1C,IAAA,UAAA,WAAA,MAAM,QAAQ;CACnB,OAAO,UAAmB;EACxB,OAAO,IAAA,SAAY;CACrB;CAEA,oBAAgD,CAAC;CAEjD,QAA0B,KAAA;CAC1B,UAA6B,KAAA;CAC7B;CACA;CAEA,SAAuB;CACvB,kBAAqC,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