{"version":3,"file":"context.cjs","sources":["@gensx/core/../../../../src/context.ts"],"sourcesContent":["import { ExecutionNode } from \"./checkpoint-types.js\";\nimport {\n  createWorkflowContext,\n  InputRequest,\n  WORKFLOW_CONTEXT_SYMBOL,\n  WorkflowExecutionContext,\n} from \"./workflow-context.js\";\nimport { WorkflowMessageListener } from \"./workflow-state.js\";\n\ntype WorkflowContext = Record<symbol, unknown>;\n\n// Define AsyncLocalStorage type based on Node.js definitions\ninterface AsyncLocalStorageType<T> {\n  disable(): void;\n  getStore(): T | undefined;\n  run<R>(store: T, callback: (...args: unknown[]) => R, ...args: unknown[]): R;\n  enterWith(store: T): void;\n}\n\nexport const CURRENT_NODE_SYMBOL = Symbol.for(\"gensx.currentNode\");\n\n// TODO(jeremy): I think this is due for a refactor now that we have simplified the context and provider stuff.\nexport class ExecutionContext {\n  constructor(\n    public context: WorkflowContext,\n    private parent?: ExecutionContext,\n    {\n      messageListener,\n      onRequestInput,\n      onRestoreCheckpoint,\n      checkpoint,\n      executionScope,\n    }: {\n      messageListener?: WorkflowMessageListener;\n      onRequestInput?: (inputRequest: InputRequest) => Promise<void>;\n      onRestoreCheckpoint?: (\n        node: ExecutionNode,\n        feedback: unknown,\n      ) => Promise<void>;\n      checkpoint?: ExecutionNode;\n      executionScope?: Record<string, unknown>;\n    } = {},\n  ) {\n    this.context[WORKFLOW_CONTEXT_SYMBOL] ??= createWorkflowContext({\n      onMessage:\n        messageListener ??\n        this.parent?.getWorkflowContext().sendWorkflowMessage,\n      onRequestInput:\n        onRequestInput ?? this.parent?.getWorkflowContext().onRequestInput,\n      onRestoreCheckpoint:\n        onRestoreCheckpoint ??\n        this.parent?.getWorkflowContext().onRestoreCheckpoint,\n      checkpoint,\n      executionScope:\n        executionScope ??\n        this.parent?.getWorkflowContext().executionScope ??\n        {},\n    });\n  }\n\n  init() {\n    return contextManager.init();\n  }\n\n  withContext(newContext: Partial<WorkflowContext>): ExecutionContext {\n    if (Object.getOwnPropertySymbols(newContext).length === 0) {\n      return this;\n    }\n\n    // Create a new context that inherits from the current one\n    const mergedContext = {} as WorkflowContext;\n    for (const key of Object.getOwnPropertySymbols(this.context)) {\n      mergedContext[key] = this.context[key];\n    }\n    // Override with new values\n    for (const key of Object.getOwnPropertySymbols(newContext)) {\n      mergedContext[key] = newContext[key];\n    }\n    return new ExecutionContext(mergedContext, this);\n  }\n\n  get<K extends keyof WorkflowContext>(key: K): WorkflowContext[K] | undefined {\n    if (key in this.context) {\n      return this.context[key];\n    }\n    return this.parent?.get(key);\n  }\n\n  getWorkflowContext(): WorkflowExecutionContext {\n    return this.get(WORKFLOW_CONTEXT_SYMBOL) as WorkflowExecutionContext;\n  }\n\n  getCurrentNode(): ExecutionNode | undefined {\n    return this.get(CURRENT_NODE_SYMBOL) as ExecutionNode | undefined;\n  }\n\n  withCurrentNode<T>(node: ExecutionNode, fn: () => T): T {\n    return withContext(this.withContext({ [CURRENT_NODE_SYMBOL]: node }), fn);\n  }\n}\n\n// Create a global symbol for contextStorage\nconst CONTEXT_STORAGE_SYMBOL = Symbol.for(\"gensx.contextStorage\");\n\n// Get the global object in a cross-platform way\ndeclare const globalThis: Record<symbol, unknown>;\ndeclare const window: Record<symbol, unknown>;\ndeclare const global: Record<symbol, unknown>;\ndeclare const self: Record<symbol, unknown>;\n\nconst globalObj: Record<symbol, unknown> =\n  typeof globalThis !== \"undefined\"\n    ? globalThis\n    : typeof window !== \"undefined\"\n      ? window\n      : typeof global !== \"undefined\"\n        ? global\n        : typeof self !== \"undefined\"\n          ? self\n          : {};\n\n// Initialize the global storage if it doesn't exist\nglobalObj[CONTEXT_STORAGE_SYMBOL] ??= null;\n\n// Try to import AsyncLocalStorage if available (Node.js environment)\nlet AsyncLocalStorage:\n  | {\n      new <T>(): AsyncLocalStorageType<T>;\n      snapshot: () => (fn: (...args: unknown[]) => unknown) => unknown;\n    }\n  | undefined;\n\nconst configureAsyncLocalStorage = (async () => {\n  try {\n    const asyncHooksModule = await import(\"node:async_hooks\");\n    AsyncLocalStorage = asyncHooksModule.AsyncLocalStorage;\n    globalObj[CONTEXT_STORAGE_SYMBOL] =\n      new AsyncLocalStorage<ExecutionContext>();\n  } catch {\n    // This is probably an environment without async_hooks, so just use global state and warn the developer\n    console.warn(\n      \"Running in an environment without async_hooks - using global context state. This will only cause issues if concurrent workflows are executed simultaneously.\",\n    );\n  }\n})();\n\nlet rootContextRef: { context: ExecutionContext | undefined } = {\n  context: undefined,\n};\n\n// Create a global symbol for the fallback context\nconst GLOBAL_CONTEXT_SYMBOL = Symbol.for(\"gensx.globalContext\");\n\n// Initialize the global fallback context if it doesn't exist\nglobalObj[GLOBAL_CONTEXT_SYMBOL] ??= rootContextRef;\n\n// Helper to get/set the global context\nconst getGlobalContext = (): ExecutionContext => {\n  const context = (\n    globalObj[GLOBAL_CONTEXT_SYMBOL] as {\n      context: ExecutionContext | undefined;\n    }\n  ).context;\n  if (context === undefined) {\n    const newContext = new ExecutionContext({});\n    setGlobalContext(newContext);\n    return newContext;\n  }\n  return context;\n};\n\nconst setGlobalContext = (context: ExecutionContext): void => {\n  (globalObj[GLOBAL_CONTEXT_SYMBOL] as { context: ExecutionContext }).context =\n    context;\n};\n\n// Update contextManager implementation\nconst contextManager = {\n  async init() {\n    await configureAsyncLocalStorage;\n    rootContextRef.context = new ExecutionContext({});\n  },\n\n  getCurrentContext(): ExecutionContext {\n    const storage = globalObj[\n      CONTEXT_STORAGE_SYMBOL\n    ] as AsyncLocalStorageType<ExecutionContext> | null;\n    if (storage) {\n      const store = storage.getStore();\n      return store ?? getGlobalContext();\n    }\n    return getGlobalContext();\n  },\n\n  run<T>(context: ExecutionContext, fn: () => T): T {\n    const storage = globalObj[\n      CONTEXT_STORAGE_SYMBOL\n    ] as AsyncLocalStorageType<ExecutionContext> | null;\n    if (storage) {\n      return storage.run(context, fn);\n    }\n    const prevContext = getGlobalContext();\n    setGlobalContext(context);\n    try {\n      return fn();\n    } finally {\n      setGlobalContext(prevContext);\n    }\n  },\n\n  getContextSnapshot(): RunInContext {\n    const storage = globalObj[\n      CONTEXT_STORAGE_SYMBOL\n    ] as AsyncLocalStorageType<ExecutionContext> | null;\n    if (storage) {\n      return AsyncLocalStorage?.snapshot() as RunInContext;\n    }\n    const context = getGlobalContext();\n    return ((fn: () => unknown) => {\n      return contextManager.run(context, fn);\n    }) as RunInContext;\n  },\n};\n\nexport type RunInContext = <T>(fn: () => T) => T;\n\n// Update withContext to use contextManager.run\nexport function withContext<T>(context: ExecutionContext, fn: () => T): T {\n  return contextManager.run(context, fn);\n}\n\n// Export for testing or advanced use cases\nexport function getCurrentContext(): ExecutionContext {\n  return contextManager.getCurrentContext();\n}\n\nexport function getContextSnapshot(): RunInContext {\n  return contextManager.getContextSnapshot();\n}\n\nexport function getCurrentNodeCheckpointManager() {\n  const context = getCurrentContext();\n  const workflowContext = context.getWorkflowContext();\n  const { checkpointManager } = workflowContext;\n  const currentNode = context.getCurrentNode();\n\n  if (!currentNode) {\n    console.warn(\"[GenSX] No current node found.\");\n    return {\n      node: undefined,\n      completeNode: () => {\n        // noop\n        console.warn(\"[GenSX] Cannot complete node - no current node found.\");\n      },\n      updateNode: () => {\n        // noop\n        console.warn(\"[GenSX] Cannot update node - no current node found.\");\n      },\n      addMetadata: () => {\n        // noop\n        console.warn(\"[GenSX] Cannot add metadata - no current node found.\");\n      },\n    };\n  }\n\n  return {\n    node: currentNode,\n    completeNode: (output: unknown, opts: { wrapInPromise?: boolean } = {}) => {\n      checkpointManager.completeNode(currentNode, output, opts);\n    },\n    updateNode: (updates: Partial<ExecutionNode>) => {\n      checkpointManager.updateNode(currentNode, updates);\n    },\n    addMetadata: (metadata: Record<string, unknown>) => {\n      checkpointManager.addMetadata(currentNode, metadata);\n    },\n  };\n}\n"],"names":["WORKFLOW_CONTEXT_SYMBOL","createWorkflowContext"],"mappings":";;;;;;;;;;AAmBa,MAAA,mBAAmB,GAAG,MAAM,CAAC,GAAG,CAAC,mBAAmB;AAEjE;MACa,gBAAgB,CAAA;AAElB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