@artooi/ag-ui-web-component 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +13 -0
- package/LICENSE +21 -0
- package/README.md +471 -0
- package/dist/ag-ui-web-component.bundle.js +319 -0
- package/dist/ag-ui-web-component.bundle.js.map +7 -0
- package/dist/ag_ui_chat.d.ts +85 -0
- package/dist/ag_ui_chat.d.ts.map +1 -0
- package/dist/agui_client.d.ts +99 -0
- package/dist/agui_client.d.ts.map +1 -0
- package/dist/animations.d.ts +33 -0
- package/dist/animations.d.ts.map +1 -0
- package/dist/client_tool_registry.d.ts +32 -0
- package/dist/client_tool_registry.d.ts.map +1 -0
- package/dist/confirmation_modal.d.ts +14 -0
- package/dist/confirmation_modal.d.ts.map +1 -0
- package/dist/constants.d.ts +40 -0
- package/dist/constants.d.ts.map +1 -0
- package/dist/conversation_store.d.ts +54 -0
- package/dist/conversation_store.d.ts.map +1 -0
- package/dist/create_http_agent.d.ts +22 -0
- package/dist/create_http_agent.d.ts.map +1 -0
- package/dist/define_ag_ui_chat.d.ts +9 -0
- package/dist/define_ag_ui_chat.d.ts.map +1 -0
- package/dist/dom_driver.d.ts +24 -0
- package/dist/dom_driver.d.ts.map +1 -0
- package/dist/index.d.ts +18 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +1159 -0
- package/dist/index.js.map +7 -0
- package/dist/is_destructive.d.ts +8 -0
- package/dist/is_destructive.d.ts.map +1 -0
- package/dist/is_navigates.d.ts +9 -0
- package/dist/is_navigates.d.ts.map +1 -0
- package/dist/page_map.d.ts +16 -0
- package/dist/page_map.d.ts.map +1 -0
- package/dist/route_map.d.ts +27 -0
- package/dist/route_map.d.ts.map +1 -0
- package/dist/state_hook.d.ts +23 -0
- package/dist/state_hook.d.ts.map +1 -0
- package/dist/styles.d.ts +2 -0
- package/dist/styles.d.ts.map +1 -0
- package/dist/tool_call_card.d.ts +29 -0
- package/dist/tool_call_card.d.ts.map +1 -0
- package/dist/version.d.ts +2 -0
- package/dist/version.d.ts.map +1 -0
- package/package.json +79 -0
- package/src/ag_ui_chat.ts +411 -0
- package/src/agui_client.ts +212 -0
- package/src/animations.ts +86 -0
- package/src/client_tool_registry.ts +56 -0
- package/src/confirmation_modal.ts +69 -0
- package/src/constants.ts +48 -0
- package/src/conversation_store.ts +103 -0
- package/src/create_http_agent.ts +40 -0
- package/src/define_ag_ui_chat.ts +15 -0
- package/src/dom_driver.ts +60 -0
- package/src/index.ts +60 -0
- package/src/is_destructive.ts +11 -0
- package/src/is_navigates.ts +12 -0
- package/src/page_map.ts +25 -0
- package/src/route_map.ts +83 -0
- package/src/state_hook.ts +44 -0
- package/src/styles.ts +296 -0
- package/src/tool_call_card.ts +95 -0
- package/src/version.ts +1 -0
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../node_modules/.pnpm/uuid@11.1.1/node_modules/uuid/dist/esm-browser/stringify.js", "../node_modules/.pnpm/uuid@11.1.1/node_modules/uuid/dist/esm-browser/rng.js", "../node_modules/.pnpm/uuid@11.1.1/node_modules/uuid/dist/esm-browser/native.js", "../node_modules/.pnpm/uuid@11.1.1/node_modules/uuid/dist/esm-browser/v4.js", "../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/external.js", "../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/helpers/util.js", "../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/ZodError.js", "../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/locales/en.js", "../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/errors.js", "../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/helpers/parseUtil.js", "../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/helpers/errorUtil.js", "../node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/types.js", "../node_modules/.pnpm/@ag-ui+core@0.0.54/node_modules/@ag-ui/core/src/types.ts", "../node_modules/.pnpm/@ag-ui+core@0.0.54/node_modules/@ag-ui/core/src/capabilities.ts", "../node_modules/.pnpm/@ag-ui+core@0.0.54/node_modules/@ag-ui/core/src/events.ts", "../node_modules/.pnpm/fast-json-patch@3.1.1/node_modules/fast-json-patch/module/core.mjs", "../node_modules/.pnpm/fast-json-patch@3.1.1/node_modules/fast-json-patch/module/helpers.mjs", "../node_modules/.pnpm/fast-json-patch@3.1.1/node_modules/fast-json-patch/module/duplex.mjs", "../node_modules/.pnpm/fast-json-patch@3.1.1/node_modules/fast-json-patch/index.mjs", "../node_modules/.pnpm/tslib@2.8.1/node_modules/tslib/tslib.es6.mjs", "../node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/src/internal/util/isFunction.ts", "../node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/src/internal/util/createErrorClass.ts", "../node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/src/internal/util/UnsubscriptionError.ts", "../node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/src/internal/util/arrRemove.ts", "../node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/src/internal/Subscription.ts", "../node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/src/internal/config.ts", "../node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/src/internal/scheduler/timeoutProvider.ts", "../node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/src/internal/util/reportUnhandledError.ts", "../node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/src/internal/util/noop.ts", "../node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/src/internal/NotificationFactories.ts", "../node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/src/internal/util/errorContext.ts", "../node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/src/internal/Subscriber.ts", "../node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/src/internal/symbol/observable.ts", "../node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/src/internal/util/identity.ts", "../node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/src/internal/util/pipe.ts", "../node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/src/internal/Observable.ts", "../node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/src/internal/util/lift.ts", "../node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/src/internal/operators/OperatorSubscriber.ts", "../node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/src/internal/util/ObjectUnsubscribedError.ts", "../node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/src/internal/Subject.ts", "../node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/src/internal/scheduler/dateTimestampProvider.ts", "../node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/src/internal/ReplaySubject.ts", "../node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/src/internal/observable/empty.ts", "../node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/src/internal/util/isScheduler.ts", "../node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/src/internal/util/args.ts", "../node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/src/internal/util/isArrayLike.ts", "../node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/src/internal/util/isPromise.ts", "../node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/src/internal/util/isInteropObservable.ts", "../node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/src/internal/util/isAsyncIterable.ts", "../node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/src/internal/util/throwUnobservableError.ts", "../node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/src/internal/symbol/iterator.ts", "../node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/src/internal/util/isIterable.ts", "../node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/src/internal/util/isReadableStreamLike.ts", "../node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/src/internal/observable/innerFrom.ts", "../node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/src/internal/util/executeSchedule.ts", "../node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/src/internal/operators/observeOn.ts", "../node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/src/internal/operators/subscribeOn.ts", "../node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/src/internal/scheduled/scheduleObservable.ts", "../node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/src/internal/scheduled/schedulePromise.ts", "../node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/src/internal/scheduled/scheduleArray.ts", "../node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/src/internal/scheduled/scheduleIterable.ts", "../node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/src/internal/scheduled/scheduleAsyncIterable.ts", "../node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/src/internal/scheduled/scheduleReadableStreamLike.ts", "../node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/src/internal/scheduled/scheduled.ts", "../node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/src/internal/observable/from.ts", "../node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/src/internal/observable/of.ts", "../node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/src/internal/observable/throwError.ts", "../node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/src/internal/util/EmptyError.ts", "../node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/src/internal/lastValueFrom.ts", "../node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/src/internal/operators/map.ts", "../node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/src/internal/operators/mergeInternals.ts", "../node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/src/internal/operators/mergeMap.ts", "../node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/src/internal/operators/mergeAll.ts", "../node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/src/internal/observable/defer.ts", "../node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/src/internal/operators/catchError.ts", "../node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/src/internal/operators/concatMap.ts", "../node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/src/internal/operators/defaultIfEmpty.ts", "../node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/src/internal/operators/finalize.ts", "../node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/src/internal/operators/switchMap.ts", "../node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/src/internal/operators/takeUntil.ts", "../node_modules/.pnpm/rxjs@7.8.1/node_modules/rxjs/src/internal/operators/tap.ts", "../node_modules/.pnpm/untruncate-json@0.0.1/node_modules/untruncate-json/src/index.ts", "../node_modules/.pnpm/@bufbuild+protobuf@2.12.0/node_modules/@bufbuild/protobuf/dist/esm/wire/varint.js", "../node_modules/.pnpm/@bufbuild+protobuf@2.12.0/node_modules/@bufbuild/protobuf/dist/esm/proto-int64.js", "../node_modules/.pnpm/@bufbuild+protobuf@2.12.0/node_modules/@bufbuild/protobuf/dist/esm/wire/text-encoding.js", "../node_modules/.pnpm/@bufbuild+protobuf@2.12.0/node_modules/@bufbuild/protobuf/dist/esm/wire/binary-encoding.js", "../node_modules/.pnpm/@ag-ui+proto@0.0.54/node_modules/@ag-ui/proto/src/generated/google/protobuf/struct.ts", "../node_modules/.pnpm/@ag-ui+proto@0.0.54/node_modules/@ag-ui/proto/src/generated/patch.ts", "../node_modules/.pnpm/@ag-ui+proto@0.0.54/node_modules/@ag-ui/proto/src/generated/types.ts", "../node_modules/.pnpm/@ag-ui+proto@0.0.54/node_modules/@ag-ui/proto/src/generated/events.ts", "../node_modules/.pnpm/@ag-ui+proto@0.0.54/node_modules/@ag-ui/proto/src/proto.ts", "../node_modules/.pnpm/@ag-ui+proto@0.0.54/node_modules/@ag-ui/proto/src/index.ts", "../node_modules/.pnpm/compare-versions@6.1.1/node_modules/compare-versions/src/utils.ts", "../node_modules/.pnpm/compare-versions@6.1.1/node_modules/compare-versions/src/compareVersions.ts", "../node_modules/.pnpm/@ag-ui+client@0.0.54/node_modules/@ag-ui/client/src/utils.ts", "../node_modules/.pnpm/@ag-ui+client@0.0.54/node_modules/@ag-ui/client/src/agent/subscriber.ts", "../node_modules/.pnpm/@ag-ui+client@0.0.54/node_modules/@ag-ui/client/src/agent/types.ts", "../node_modules/.pnpm/@ag-ui+client@0.0.54/node_modules/@ag-ui/client/src/debug-logger.ts", "../node_modules/.pnpm/@ag-ui+client@0.0.54/node_modules/@ag-ui/client/src/apply/default.ts", "../node_modules/.pnpm/@ag-ui+client@0.0.54/node_modules/@ag-ui/client/src/verify/verify.ts", "../node_modules/.pnpm/@ag-ui+client@0.0.54/node_modules/@ag-ui/client/src/run/http-request.ts", "../node_modules/.pnpm/@ag-ui+client@0.0.54/node_modules/@ag-ui/client/src/transform/sse.ts", "../node_modules/.pnpm/@ag-ui+client@0.0.54/node_modules/@ag-ui/client/src/transform/proto.ts", "../node_modules/.pnpm/@ag-ui+client@0.0.54/node_modules/@ag-ui/client/src/transform/http.ts", "../node_modules/.pnpm/@ag-ui+client@0.0.54/node_modules/@ag-ui/client/src/legacy/types.ts", "../node_modules/.pnpm/@ag-ui+client@0.0.54/node_modules/@ag-ui/client/src/legacy/convert.ts", "../node_modules/.pnpm/@ag-ui+client@0.0.54/node_modules/@ag-ui/client/src/chunks/transform.ts", "../node_modules/.pnpm/@ag-ui+client@0.0.54/node_modules/@ag-ui/client/src/interrupts/index.ts", "../node_modules/.pnpm/@ag-ui+client@0.0.54/node_modules/@ag-ui/client/src/middleware/middleware.ts", "../node_modules/.pnpm/@ag-ui+client@0.0.54/node_modules/@ag-ui/client/src/middleware/filter-tool-calls.ts", "../node_modules/.pnpm/@ag-ui+client@0.0.54/node_modules/@ag-ui/client/src/middleware/backward-compatibility-0-0-39.ts", "../node_modules/.pnpm/@ag-ui+client@0.0.54/node_modules/@ag-ui/client/src/middleware/backward-compatibility-0-0-45.ts", "../node_modules/.pnpm/@ag-ui+client@0.0.54/node_modules/@ag-ui/client/src/middleware/backward-compatibility-0-0-47.ts", "../node_modules/.pnpm/@ag-ui+client@0.0.54/node_modules/@ag-ui/client/package.json", "../node_modules/.pnpm/@ag-ui+client@0.0.54/node_modules/@ag-ui/client/src/agent/agent.ts", "../node_modules/.pnpm/@ag-ui+client@0.0.54/node_modules/@ag-ui/client/src/agent/http.ts", "../node_modules/.pnpm/@ag-ui+client@0.0.54/node_modules/@ag-ui/client/src/compact/compact.ts", "../src/constants.ts", "../src/agui_client.ts", "../src/client_tool_registry.ts", "../src/confirmation_modal.ts", "../src/conversation_store.ts", "../src/create_http_agent.ts", "../src/is_destructive.ts", "../src/is_navigates.ts", "../src/page_map.ts", "../src/route_map.ts", "../src/state_hook.ts", "../src/styles.ts", "../src/tool_call_card.ts", "../src/ag_ui_chat.ts", "../src/animations.ts", "../src/define_ag_ui_chat.ts", "../src/dom_driver.ts", "../src/version.ts"],
|
|
4
|
+
"sourcesContent": ["import validate from './validate.js';\nconst byteToHex = [];\nfor (let i = 0; i < 256; ++i) {\n byteToHex.push((i + 0x100).toString(16).slice(1));\n}\nexport function unsafeStringify(arr, offset = 0) {\n return (byteToHex[arr[offset + 0]] +\n byteToHex[arr[offset + 1]] +\n byteToHex[arr[offset + 2]] +\n byteToHex[arr[offset + 3]] +\n '-' +\n byteToHex[arr[offset + 4]] +\n byteToHex[arr[offset + 5]] +\n '-' +\n byteToHex[arr[offset + 6]] +\n byteToHex[arr[offset + 7]] +\n '-' +\n byteToHex[arr[offset + 8]] +\n byteToHex[arr[offset + 9]] +\n '-' +\n byteToHex[arr[offset + 10]] +\n byteToHex[arr[offset + 11]] +\n byteToHex[arr[offset + 12]] +\n byteToHex[arr[offset + 13]] +\n byteToHex[arr[offset + 14]] +\n byteToHex[arr[offset + 15]]).toLowerCase();\n}\nfunction stringify(arr, offset = 0) {\n const uuid = unsafeStringify(arr, offset);\n if (!validate(uuid)) {\n throw TypeError('Stringified UUID is invalid');\n }\n return uuid;\n}\nexport default stringify;\n", "let getRandomValues;\nconst rnds8 = new Uint8Array(16);\nexport default function rng() {\n if (!getRandomValues) {\n if (typeof crypto === 'undefined' || !crypto.getRandomValues) {\n throw new Error('crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported');\n }\n getRandomValues = crypto.getRandomValues.bind(crypto);\n }\n return getRandomValues(rnds8);\n}\n", "const randomUUID = typeof crypto !== 'undefined' && crypto.randomUUID && crypto.randomUUID.bind(crypto);\nexport default { randomUUID };\n", "import native from './native.js';\nimport rng from './rng.js';\nimport { unsafeStringify } from './stringify.js';\nfunction v4(options, buf, offset) {\n if (native.randomUUID && !buf && !options) {\n return native.randomUUID();\n }\n options = options || {};\n const rnds = options.random ?? options.rng?.() ?? rng();\n if (rnds.length < 16) {\n throw new Error('Random bytes length must be >= 16');\n }\n rnds[6] = (rnds[6] & 0x0f) | 0x40;\n rnds[8] = (rnds[8] & 0x3f) | 0x80;\n if (buf) {\n offset = offset || 0;\n if (offset < 0 || offset + 16 > buf.length) {\n throw new RangeError(`UUID byte range ${offset}:${offset + 15} is out of buffer bounds`);\n }\n for (let i = 0; i < 16; ++i) {\n buf[offset + i] = rnds[i];\n }\n return buf;\n }\n return unsafeStringify(rnds);\n}\nexport default v4;\n", "export * from \"./errors.js\";\nexport * from \"./helpers/parseUtil.js\";\nexport * from \"./helpers/typeAliases.js\";\nexport * from \"./helpers/util.js\";\nexport * from \"./types.js\";\nexport * from \"./ZodError.js\";\n", "export var util;\n(function (util) {\n util.assertEqual = (_) => { };\n function assertIs(_arg) { }\n util.assertIs = assertIs;\n function assertNever(_x) {\n throw new Error();\n }\n util.assertNever = assertNever;\n util.arrayToEnum = (items) => {\n const obj = {};\n for (const item of items) {\n obj[item] = item;\n }\n return obj;\n };\n util.getValidEnumValues = (obj) => {\n const validKeys = util.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== \"number\");\n const filtered = {};\n for (const k of validKeys) {\n filtered[k] = obj[k];\n }\n return util.objectValues(filtered);\n };\n util.objectValues = (obj) => {\n return util.objectKeys(obj).map(function (e) {\n return obj[e];\n });\n };\n util.objectKeys = typeof Object.keys === \"function\" // eslint-disable-line ban/ban\n ? (obj) => Object.keys(obj) // eslint-disable-line ban/ban\n : (object) => {\n const keys = [];\n for (const key in object) {\n if (Object.prototype.hasOwnProperty.call(object, key)) {\n keys.push(key);\n }\n }\n return keys;\n };\n util.find = (arr, checker) => {\n for (const item of arr) {\n if (checker(item))\n return item;\n }\n return undefined;\n };\n util.isInteger = typeof Number.isInteger === \"function\"\n ? (val) => Number.isInteger(val) // eslint-disable-line ban/ban\n : (val) => typeof val === \"number\" && Number.isFinite(val) && Math.floor(val) === val;\n function joinValues(array, separator = \" | \") {\n return array.map((val) => (typeof val === \"string\" ? `'${val}'` : val)).join(separator);\n }\n util.joinValues = joinValues;\n util.jsonStringifyReplacer = (_, value) => {\n if (typeof value === \"bigint\") {\n return value.toString();\n }\n return value;\n };\n})(util || (util = {}));\nexport var objectUtil;\n(function (objectUtil) {\n objectUtil.mergeShapes = (first, second) => {\n return {\n ...first,\n ...second, // second overwrites first\n };\n };\n})(objectUtil || (objectUtil = {}));\nexport const ZodParsedType = util.arrayToEnum([\n \"string\",\n \"nan\",\n \"number\",\n \"integer\",\n \"float\",\n \"boolean\",\n \"date\",\n \"bigint\",\n \"symbol\",\n \"function\",\n \"undefined\",\n \"null\",\n \"array\",\n \"object\",\n \"unknown\",\n \"promise\",\n \"void\",\n \"never\",\n \"map\",\n \"set\",\n]);\nexport const getParsedType = (data) => {\n const t = typeof data;\n switch (t) {\n case \"undefined\":\n return ZodParsedType.undefined;\n case \"string\":\n return ZodParsedType.string;\n case \"number\":\n return Number.isNaN(data) ? ZodParsedType.nan : ZodParsedType.number;\n case \"boolean\":\n return ZodParsedType.boolean;\n case \"function\":\n return ZodParsedType.function;\n case \"bigint\":\n return ZodParsedType.bigint;\n case \"symbol\":\n return ZodParsedType.symbol;\n case \"object\":\n if (Array.isArray(data)) {\n return ZodParsedType.array;\n }\n if (data === null) {\n return ZodParsedType.null;\n }\n if (data.then && typeof data.then === \"function\" && data.catch && typeof data.catch === \"function\") {\n return ZodParsedType.promise;\n }\n if (typeof Map !== \"undefined\" && data instanceof Map) {\n return ZodParsedType.map;\n }\n if (typeof Set !== \"undefined\" && data instanceof Set) {\n return ZodParsedType.set;\n }\n if (typeof Date !== \"undefined\" && data instanceof Date) {\n return ZodParsedType.date;\n }\n return ZodParsedType.object;\n default:\n return ZodParsedType.unknown;\n }\n};\n", "import { util } from \"./helpers/util.js\";\nexport const ZodIssueCode = util.arrayToEnum([\n \"invalid_type\",\n \"invalid_literal\",\n \"custom\",\n \"invalid_union\",\n \"invalid_union_discriminator\",\n \"invalid_enum_value\",\n \"unrecognized_keys\",\n \"invalid_arguments\",\n \"invalid_return_type\",\n \"invalid_date\",\n \"invalid_string\",\n \"too_small\",\n \"too_big\",\n \"invalid_intersection_types\",\n \"not_multiple_of\",\n \"not_finite\",\n]);\nexport const quotelessJson = (obj) => {\n const json = JSON.stringify(obj, null, 2);\n return json.replace(/\"([^\"]+)\":/g, \"$1:\");\n};\nexport class ZodError extends Error {\n get errors() {\n return this.issues;\n }\n constructor(issues) {\n super();\n this.issues = [];\n this.addIssue = (sub) => {\n this.issues = [...this.issues, sub];\n };\n this.addIssues = (subs = []) => {\n this.issues = [...this.issues, ...subs];\n };\n const actualProto = new.target.prototype;\n if (Object.setPrototypeOf) {\n // eslint-disable-next-line ban/ban\n Object.setPrototypeOf(this, actualProto);\n }\n else {\n this.__proto__ = actualProto;\n }\n this.name = \"ZodError\";\n this.issues = issues;\n }\n format(_mapper) {\n const mapper = _mapper ||\n function (issue) {\n return issue.message;\n };\n const fieldErrors = { _errors: [] };\n const processError = (error) => {\n for (const issue of error.issues) {\n if (issue.code === \"invalid_union\") {\n issue.unionErrors.map(processError);\n }\n else if (issue.code === \"invalid_return_type\") {\n processError(issue.returnTypeError);\n }\n else if (issue.code === \"invalid_arguments\") {\n processError(issue.argumentsError);\n }\n else if (issue.path.length === 0) {\n fieldErrors._errors.push(mapper(issue));\n }\n else {\n let curr = fieldErrors;\n let i = 0;\n while (i < issue.path.length) {\n const el = issue.path[i];\n const terminal = i === issue.path.length - 1;\n if (!terminal) {\n curr[el] = curr[el] || { _errors: [] };\n // if (typeof el === \"string\") {\n // curr[el] = curr[el] || { _errors: [] };\n // } else if (typeof el === \"number\") {\n // const errorArray: any = [];\n // errorArray._errors = [];\n // curr[el] = curr[el] || errorArray;\n // }\n }\n else {\n curr[el] = curr[el] || { _errors: [] };\n curr[el]._errors.push(mapper(issue));\n }\n curr = curr[el];\n i++;\n }\n }\n }\n };\n processError(this);\n return fieldErrors;\n }\n static assert(value) {\n if (!(value instanceof ZodError)) {\n throw new Error(`Not a ZodError: ${value}`);\n }\n }\n toString() {\n return this.message;\n }\n get message() {\n return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2);\n }\n get isEmpty() {\n return this.issues.length === 0;\n }\n flatten(mapper = (issue) => issue.message) {\n const fieldErrors = {};\n const formErrors = [];\n for (const sub of this.issues) {\n if (sub.path.length > 0) {\n const firstEl = sub.path[0];\n fieldErrors[firstEl] = fieldErrors[firstEl] || [];\n fieldErrors[firstEl].push(mapper(sub));\n }\n else {\n formErrors.push(mapper(sub));\n }\n }\n return { formErrors, fieldErrors };\n }\n get formErrors() {\n return this.flatten();\n }\n}\nZodError.create = (issues) => {\n const error = new ZodError(issues);\n return error;\n};\n", "import { ZodIssueCode } from \"../ZodError.js\";\nimport { util, ZodParsedType } from \"../helpers/util.js\";\nconst errorMap = (issue, _ctx) => {\n let message;\n switch (issue.code) {\n case ZodIssueCode.invalid_type:\n if (issue.received === ZodParsedType.undefined) {\n message = \"Required\";\n }\n else {\n message = `Expected ${issue.expected}, received ${issue.received}`;\n }\n break;\n case ZodIssueCode.invalid_literal:\n message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`;\n break;\n case ZodIssueCode.unrecognized_keys:\n message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, \", \")}`;\n break;\n case ZodIssueCode.invalid_union:\n message = `Invalid input`;\n break;\n case ZodIssueCode.invalid_union_discriminator:\n message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`;\n break;\n case ZodIssueCode.invalid_enum_value:\n message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`;\n break;\n case ZodIssueCode.invalid_arguments:\n message = `Invalid function arguments`;\n break;\n case ZodIssueCode.invalid_return_type:\n message = `Invalid function return type`;\n break;\n case ZodIssueCode.invalid_date:\n message = `Invalid date`;\n break;\n case ZodIssueCode.invalid_string:\n if (typeof issue.validation === \"object\") {\n if (\"includes\" in issue.validation) {\n message = `Invalid input: must include \"${issue.validation.includes}\"`;\n if (typeof issue.validation.position === \"number\") {\n message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`;\n }\n }\n else if (\"startsWith\" in issue.validation) {\n message = `Invalid input: must start with \"${issue.validation.startsWith}\"`;\n }\n else if (\"endsWith\" in issue.validation) {\n message = `Invalid input: must end with \"${issue.validation.endsWith}\"`;\n }\n else {\n util.assertNever(issue.validation);\n }\n }\n else if (issue.validation !== \"regex\") {\n message = `Invalid ${issue.validation}`;\n }\n else {\n message = \"Invalid\";\n }\n break;\n case ZodIssueCode.too_small:\n if (issue.type === \"array\")\n message = `Array must contain ${issue.exact ? \"exactly\" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`;\n else if (issue.type === \"string\")\n message = `String must contain ${issue.exact ? \"exactly\" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`;\n else if (issue.type === \"number\")\n message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;\n else if (issue.type === \"bigint\")\n message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;\n else if (issue.type === \"date\")\n message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`;\n else\n message = \"Invalid input\";\n break;\n case ZodIssueCode.too_big:\n if (issue.type === \"array\")\n message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`;\n else if (issue.type === \"string\")\n message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`;\n else if (issue.type === \"number\")\n message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;\n else if (issue.type === \"bigint\")\n message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;\n else if (issue.type === \"date\")\n message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`;\n else\n message = \"Invalid input\";\n break;\n case ZodIssueCode.custom:\n message = `Invalid input`;\n break;\n case ZodIssueCode.invalid_intersection_types:\n message = `Intersection results could not be merged`;\n break;\n case ZodIssueCode.not_multiple_of:\n message = `Number must be a multiple of ${issue.multipleOf}`;\n break;\n case ZodIssueCode.not_finite:\n message = \"Number must be finite\";\n break;\n default:\n message = _ctx.defaultError;\n util.assertNever(issue);\n }\n return { message };\n};\nexport default errorMap;\n", "import defaultErrorMap from \"./locales/en.js\";\nlet overrideErrorMap = defaultErrorMap;\nexport { defaultErrorMap };\nexport function setErrorMap(map) {\n overrideErrorMap = map;\n}\nexport function getErrorMap() {\n return overrideErrorMap;\n}\n", "import { getErrorMap } from \"../errors.js\";\nimport defaultErrorMap from \"../locales/en.js\";\nexport const makeIssue = (params) => {\n const { data, path, errorMaps, issueData } = params;\n const fullPath = [...path, ...(issueData.path || [])];\n const fullIssue = {\n ...issueData,\n path: fullPath,\n };\n if (issueData.message !== undefined) {\n return {\n ...issueData,\n path: fullPath,\n message: issueData.message,\n };\n }\n let errorMessage = \"\";\n const maps = errorMaps\n .filter((m) => !!m)\n .slice()\n .reverse();\n for (const map of maps) {\n errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message;\n }\n return {\n ...issueData,\n path: fullPath,\n message: errorMessage,\n };\n};\nexport const EMPTY_PATH = [];\nexport function addIssueToContext(ctx, issueData) {\n const overrideMap = getErrorMap();\n const issue = makeIssue({\n issueData: issueData,\n data: ctx.data,\n path: ctx.path,\n errorMaps: [\n ctx.common.contextualErrorMap, // contextual error map is first priority\n ctx.schemaErrorMap, // then schema-bound map if available\n overrideMap, // then global override map\n overrideMap === defaultErrorMap ? undefined : defaultErrorMap, // then global default map\n ].filter((x) => !!x),\n });\n ctx.common.issues.push(issue);\n}\nexport class ParseStatus {\n constructor() {\n this.value = \"valid\";\n }\n dirty() {\n if (this.value === \"valid\")\n this.value = \"dirty\";\n }\n abort() {\n if (this.value !== \"aborted\")\n this.value = \"aborted\";\n }\n static mergeArray(status, results) {\n const arrayValue = [];\n for (const s of results) {\n if (s.status === \"aborted\")\n return INVALID;\n if (s.status === \"dirty\")\n status.dirty();\n arrayValue.push(s.value);\n }\n return { status: status.value, value: arrayValue };\n }\n static async mergeObjectAsync(status, pairs) {\n const syncPairs = [];\n for (const pair of pairs) {\n const key = await pair.key;\n const value = await pair.value;\n syncPairs.push({\n key,\n value,\n });\n }\n return ParseStatus.mergeObjectSync(status, syncPairs);\n }\n static mergeObjectSync(status, pairs) {\n const finalObject = {};\n for (const pair of pairs) {\n const { key, value } = pair;\n if (key.status === \"aborted\")\n return INVALID;\n if (value.status === \"aborted\")\n return INVALID;\n if (key.status === \"dirty\")\n status.dirty();\n if (value.status === \"dirty\")\n status.dirty();\n if (key.value !== \"__proto__\" && (typeof value.value !== \"undefined\" || pair.alwaysSet)) {\n finalObject[key.value] = value.value;\n }\n }\n return { status: status.value, value: finalObject };\n }\n}\nexport const INVALID = Object.freeze({\n status: \"aborted\",\n});\nexport const DIRTY = (value) => ({ status: \"dirty\", value });\nexport const OK = (value) => ({ status: \"valid\", value });\nexport const isAborted = (x) => x.status === \"aborted\";\nexport const isDirty = (x) => x.status === \"dirty\";\nexport const isValid = (x) => x.status === \"valid\";\nexport const isAsync = (x) => typeof Promise !== \"undefined\" && x instanceof Promise;\n", "export var errorUtil;\n(function (errorUtil) {\n errorUtil.errToObj = (message) => typeof message === \"string\" ? { message } : message || {};\n // biome-ignore lint:\n errorUtil.toString = (message) => typeof message === \"string\" ? message : message?.message;\n})(errorUtil || (errorUtil = {}));\n", "import { ZodError, ZodIssueCode, } from \"./ZodError.js\";\nimport { defaultErrorMap, getErrorMap } from \"./errors.js\";\nimport { errorUtil } from \"./helpers/errorUtil.js\";\nimport { DIRTY, INVALID, OK, ParseStatus, addIssueToContext, isAborted, isAsync, isDirty, isValid, makeIssue, } from \"./helpers/parseUtil.js\";\nimport { util, ZodParsedType, getParsedType } from \"./helpers/util.js\";\nclass ParseInputLazyPath {\n constructor(parent, value, path, key) {\n this._cachedPath = [];\n this.parent = parent;\n this.data = value;\n this._path = path;\n this._key = key;\n }\n get path() {\n if (!this._cachedPath.length) {\n if (Array.isArray(this._key)) {\n this._cachedPath.push(...this._path, ...this._key);\n }\n else {\n this._cachedPath.push(...this._path, this._key);\n }\n }\n return this._cachedPath;\n }\n}\nconst handleResult = (ctx, result) => {\n if (isValid(result)) {\n return { success: true, data: result.value };\n }\n else {\n if (!ctx.common.issues.length) {\n throw new Error(\"Validation failed but no issues detected.\");\n }\n return {\n success: false,\n get error() {\n if (this._error)\n return this._error;\n const error = new ZodError(ctx.common.issues);\n this._error = error;\n return this._error;\n },\n };\n }\n};\nfunction processCreateParams(params) {\n if (!params)\n return {};\n const { errorMap, invalid_type_error, required_error, description } = params;\n if (errorMap && (invalid_type_error || required_error)) {\n throw new Error(`Can't use \"invalid_type_error\" or \"required_error\" in conjunction with custom error map.`);\n }\n if (errorMap)\n return { errorMap: errorMap, description };\n const customMap = (iss, ctx) => {\n const { message } = params;\n if (iss.code === \"invalid_enum_value\") {\n return { message: message ?? ctx.defaultError };\n }\n if (typeof ctx.data === \"undefined\") {\n return { message: message ?? required_error ?? ctx.defaultError };\n }\n if (iss.code !== \"invalid_type\")\n return { message: ctx.defaultError };\n return { message: message ?? invalid_type_error ?? ctx.defaultError };\n };\n return { errorMap: customMap, description };\n}\nexport class ZodType {\n get description() {\n return this._def.description;\n }\n _getType(input) {\n return getParsedType(input.data);\n }\n _getOrReturnCtx(input, ctx) {\n return (ctx || {\n common: input.parent.common,\n data: input.data,\n parsedType: getParsedType(input.data),\n schemaErrorMap: this._def.errorMap,\n path: input.path,\n parent: input.parent,\n });\n }\n _processInputParams(input) {\n return {\n status: new ParseStatus(),\n ctx: {\n common: input.parent.common,\n data: input.data,\n parsedType: getParsedType(input.data),\n schemaErrorMap: this._def.errorMap,\n path: input.path,\n parent: input.parent,\n },\n };\n }\n _parseSync(input) {\n const result = this._parse(input);\n if (isAsync(result)) {\n throw new Error(\"Synchronous parse encountered promise.\");\n }\n return result;\n }\n _parseAsync(input) {\n const result = this._parse(input);\n return Promise.resolve(result);\n }\n parse(data, params) {\n const result = this.safeParse(data, params);\n if (result.success)\n return result.data;\n throw result.error;\n }\n safeParse(data, params) {\n const ctx = {\n common: {\n issues: [],\n async: params?.async ?? false,\n contextualErrorMap: params?.errorMap,\n },\n path: params?.path || [],\n schemaErrorMap: this._def.errorMap,\n parent: null,\n data,\n parsedType: getParsedType(data),\n };\n const result = this._parseSync({ data, path: ctx.path, parent: ctx });\n return handleResult(ctx, result);\n }\n \"~validate\"(data) {\n const ctx = {\n common: {\n issues: [],\n async: !!this[\"~standard\"].async,\n },\n path: [],\n schemaErrorMap: this._def.errorMap,\n parent: null,\n data,\n parsedType: getParsedType(data),\n };\n if (!this[\"~standard\"].async) {\n try {\n const result = this._parseSync({ data, path: [], parent: ctx });\n return isValid(result)\n ? {\n value: result.value,\n }\n : {\n issues: ctx.common.issues,\n };\n }\n catch (err) {\n if (err?.message?.toLowerCase()?.includes(\"encountered\")) {\n this[\"~standard\"].async = true;\n }\n ctx.common = {\n issues: [],\n async: true,\n };\n }\n }\n return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid(result)\n ? {\n value: result.value,\n }\n : {\n issues: ctx.common.issues,\n });\n }\n async parseAsync(data, params) {\n const result = await this.safeParseAsync(data, params);\n if (result.success)\n return result.data;\n throw result.error;\n }\n async safeParseAsync(data, params) {\n const ctx = {\n common: {\n issues: [],\n contextualErrorMap: params?.errorMap,\n async: true,\n },\n path: params?.path || [],\n schemaErrorMap: this._def.errorMap,\n parent: null,\n data,\n parsedType: getParsedType(data),\n };\n const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx });\n const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult));\n return handleResult(ctx, result);\n }\n refine(check, message) {\n const getIssueProperties = (val) => {\n if (typeof message === \"string\" || typeof message === \"undefined\") {\n return { message };\n }\n else if (typeof message === \"function\") {\n return message(val);\n }\n else {\n return message;\n }\n };\n return this._refinement((val, ctx) => {\n const result = check(val);\n const setError = () => ctx.addIssue({\n code: ZodIssueCode.custom,\n ...getIssueProperties(val),\n });\n if (typeof Promise !== \"undefined\" && result instanceof Promise) {\n return result.then((data) => {\n if (!data) {\n setError();\n return false;\n }\n else {\n return true;\n }\n });\n }\n if (!result) {\n setError();\n return false;\n }\n else {\n return true;\n }\n });\n }\n refinement(check, refinementData) {\n return this._refinement((val, ctx) => {\n if (!check(val)) {\n ctx.addIssue(typeof refinementData === \"function\" ? refinementData(val, ctx) : refinementData);\n return false;\n }\n else {\n return true;\n }\n });\n }\n _refinement(refinement) {\n return new ZodEffects({\n schema: this,\n typeName: ZodFirstPartyTypeKind.ZodEffects,\n effect: { type: \"refinement\", refinement },\n });\n }\n superRefine(refinement) {\n return this._refinement(refinement);\n }\n constructor(def) {\n /** Alias of safeParseAsync */\n this.spa = this.safeParseAsync;\n this._def = def;\n this.parse = this.parse.bind(this);\n this.safeParse = this.safeParse.bind(this);\n this.parseAsync = this.parseAsync.bind(this);\n this.safeParseAsync = this.safeParseAsync.bind(this);\n this.spa = this.spa.bind(this);\n this.refine = this.refine.bind(this);\n this.refinement = this.refinement.bind(this);\n this.superRefine = this.superRefine.bind(this);\n this.optional = this.optional.bind(this);\n this.nullable = this.nullable.bind(this);\n this.nullish = this.nullish.bind(this);\n this.array = this.array.bind(this);\n this.promise = this.promise.bind(this);\n this.or = this.or.bind(this);\n this.and = this.and.bind(this);\n this.transform = this.transform.bind(this);\n this.brand = this.brand.bind(this);\n this.default = this.default.bind(this);\n this.catch = this.catch.bind(this);\n this.describe = this.describe.bind(this);\n this.pipe = this.pipe.bind(this);\n this.readonly = this.readonly.bind(this);\n this.isNullable = this.isNullable.bind(this);\n this.isOptional = this.isOptional.bind(this);\n this[\"~standard\"] = {\n version: 1,\n vendor: \"zod\",\n validate: (data) => this[\"~validate\"](data),\n };\n }\n optional() {\n return ZodOptional.create(this, this._def);\n }\n nullable() {\n return ZodNullable.create(this, this._def);\n }\n nullish() {\n return this.nullable().optional();\n }\n array() {\n return ZodArray.create(this);\n }\n promise() {\n return ZodPromise.create(this, this._def);\n }\n or(option) {\n return ZodUnion.create([this, option], this._def);\n }\n and(incoming) {\n return ZodIntersection.create(this, incoming, this._def);\n }\n transform(transform) {\n return new ZodEffects({\n ...processCreateParams(this._def),\n schema: this,\n typeName: ZodFirstPartyTypeKind.ZodEffects,\n effect: { type: \"transform\", transform },\n });\n }\n default(def) {\n const defaultValueFunc = typeof def === \"function\" ? def : () => def;\n return new ZodDefault({\n ...processCreateParams(this._def),\n innerType: this,\n defaultValue: defaultValueFunc,\n typeName: ZodFirstPartyTypeKind.ZodDefault,\n });\n }\n brand() {\n return new ZodBranded({\n typeName: ZodFirstPartyTypeKind.ZodBranded,\n type: this,\n ...processCreateParams(this._def),\n });\n }\n catch(def) {\n const catchValueFunc = typeof def === \"function\" ? def : () => def;\n return new ZodCatch({\n ...processCreateParams(this._def),\n innerType: this,\n catchValue: catchValueFunc,\n typeName: ZodFirstPartyTypeKind.ZodCatch,\n });\n }\n describe(description) {\n const This = this.constructor;\n return new This({\n ...this._def,\n description,\n });\n }\n pipe(target) {\n return ZodPipeline.create(this, target);\n }\n readonly() {\n return ZodReadonly.create(this);\n }\n isOptional() {\n return this.safeParse(undefined).success;\n }\n isNullable() {\n return this.safeParse(null).success;\n }\n}\nconst cuidRegex = /^c[^\\s-]{8,}$/i;\nconst cuid2Regex = /^[0-9a-z]+$/;\nconst ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i;\n// const uuidRegex =\n// /^([a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[a-f0-9]{4}-[a-f0-9]{12}|00000000-0000-0000-0000-000000000000)$/i;\nconst uuidRegex = /^[0-9a-fA-F]{8}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{12}$/i;\nconst nanoidRegex = /^[a-z0-9_-]{21}$/i;\nconst jwtRegex = /^[A-Za-z0-9-_]+\\.[A-Za-z0-9-_]+\\.[A-Za-z0-9-_]*$/;\nconst durationRegex = /^[-+]?P(?!$)(?:(?:[-+]?\\d+Y)|(?:[-+]?\\d+[.,]\\d+Y$))?(?:(?:[-+]?\\d+M)|(?:[-+]?\\d+[.,]\\d+M$))?(?:(?:[-+]?\\d+W)|(?:[-+]?\\d+[.,]\\d+W$))?(?:(?:[-+]?\\d+D)|(?:[-+]?\\d+[.,]\\d+D$))?(?:T(?=[\\d+-])(?:(?:[-+]?\\d+H)|(?:[-+]?\\d+[.,]\\d+H$))?(?:(?:[-+]?\\d+M)|(?:[-+]?\\d+[.,]\\d+M$))?(?:[-+]?\\d+(?:[.,]\\d+)?S)?)??$/;\n// from https://stackoverflow.com/a/46181/1550155\n// old version: too slow, didn't support unicode\n// const emailRegex = /^((([a-z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])+(\\.([a-z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])+)*)|((\\x22)((((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(([\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x7f]|\\x21|[\\x23-\\x5b]|[\\x5d-\\x7e]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(\\\\([\\x01-\\x09\\x0b\\x0c\\x0d-\\x7f]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]))))*(((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(\\x22)))@((([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])))\\.)+(([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])))$/i;\n//old email regex\n// const emailRegex = /^(([^<>()[\\].,;:\\s@\"]+(\\.[^<>()[\\].,;:\\s@\"]+)*)|(\".+\"))@((?!-)([^<>()[\\].,;:\\s@\"]+\\.)+[^<>()[\\].,;:\\s@\"]{1,})[^-<>()[\\].,;:\\s@\"]$/i;\n// eslint-disable-next-line\n// const emailRegex =\n// /^(([^<>()[\\]\\\\.,;:\\s@\\\"]+(\\.[^<>()[\\]\\\\.,;:\\s@\\\"]+)*)|(\\\".+\\\"))@((\\[(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\])|(\\[IPv6:(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))\\])|([A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])*(\\.[A-Za-z]{2,})+))$/;\n// const emailRegex =\n// /^[a-zA-Z0-9\\.\\!\\#\\$\\%\\&\\'\\*\\+\\/\\=\\?\\^\\_\\`\\{\\|\\}\\~\\-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;\n// const emailRegex =\n// /^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])$/i;\nconst emailRegex = /^(?!\\.)(?!.*\\.\\.)([A-Z0-9_'+\\-\\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\\-]*\\.)+[A-Z]{2,}$/i;\n// const emailRegex =\n// /^[a-z0-9.!#$%&\u2019*+/=?^_`{|}~-]+@[a-z0-9-]+(?:\\.[a-z0-9\\-]+)*$/i;\n// from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression\nconst _emojiRegex = `^(\\\\p{Extended_Pictographic}|\\\\p{Emoji_Component})+$`;\nlet emojiRegex;\n// faster, simpler, safer\nconst ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;\nconst ipv4CidrRegex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\/(3[0-2]|[12]?[0-9])$/;\n// const ipv6Regex =\n// /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}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,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;\n// https://stackoverflow.com/questions/7860392/determine-if-string-is-in-base64-using-javascript\nconst base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;\n// https://base64.guru/standards/base64url\nconst base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/;\n// simple\n// const dateRegexSource = `\\\\d{4}-\\\\d{2}-\\\\d{2}`;\n// no leap year validation\n// const dateRegexSource = `\\\\d{4}-((0[13578]|10|12)-31|(0[13-9]|1[0-2])-30|(0[1-9]|1[0-2])-(0[1-9]|1\\\\d|2\\\\d))`;\n// with leap year validation\nconst dateRegexSource = `((\\\\d\\\\d[2468][048]|\\\\d\\\\d[13579][26]|\\\\d\\\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\\\d|30)|(02)-(0[1-9]|1\\\\d|2[0-8])))`;\nconst dateRegex = new RegExp(`^${dateRegexSource}$`);\nfunction timeRegexSource(args) {\n let secondsRegexSource = `[0-5]\\\\d`;\n if (args.precision) {\n secondsRegexSource = `${secondsRegexSource}\\\\.\\\\d{${args.precision}}`;\n }\n else if (args.precision == null) {\n secondsRegexSource = `${secondsRegexSource}(\\\\.\\\\d+)?`;\n }\n const secondsQuantifier = args.precision ? \"+\" : \"?\"; // require seconds if precision is nonzero\n return `([01]\\\\d|2[0-3]):[0-5]\\\\d(:${secondsRegexSource})${secondsQuantifier}`;\n}\nfunction timeRegex(args) {\n return new RegExp(`^${timeRegexSource(args)}$`);\n}\n// Adapted from https://stackoverflow.com/a/3143231\nexport function datetimeRegex(args) {\n let regex = `${dateRegexSource}T${timeRegexSource(args)}`;\n const opts = [];\n opts.push(args.local ? `Z?` : `Z`);\n if (args.offset)\n opts.push(`([+-]\\\\d{2}:?\\\\d{2})`);\n regex = `${regex}(${opts.join(\"|\")})`;\n return new RegExp(`^${regex}$`);\n}\nfunction isValidIP(ip, version) {\n if ((version === \"v4\" || !version) && ipv4Regex.test(ip)) {\n return true;\n }\n if ((version === \"v6\" || !version) && ipv6Regex.test(ip)) {\n return true;\n }\n return false;\n}\nfunction isValidJWT(jwt, alg) {\n if (!jwtRegex.test(jwt))\n return false;\n try {\n const [header] = jwt.split(\".\");\n if (!header)\n return false;\n // Convert base64url to base64\n const base64 = header\n .replace(/-/g, \"+\")\n .replace(/_/g, \"/\")\n .padEnd(header.length + ((4 - (header.length % 4)) % 4), \"=\");\n const decoded = JSON.parse(atob(base64));\n if (typeof decoded !== \"object\" || decoded === null)\n return false;\n if (\"typ\" in decoded && decoded?.typ !== \"JWT\")\n return false;\n if (!decoded.alg)\n return false;\n if (alg && decoded.alg !== alg)\n return false;\n return true;\n }\n catch {\n return false;\n }\n}\nfunction isValidCidr(ip, version) {\n if ((version === \"v4\" || !version) && ipv4CidrRegex.test(ip)) {\n return true;\n }\n if ((version === \"v6\" || !version) && ipv6CidrRegex.test(ip)) {\n return true;\n }\n return false;\n}\nexport class ZodString extends ZodType {\n _parse(input) {\n if (this._def.coerce) {\n input.data = String(input.data);\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.string) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.string,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const status = new ParseStatus();\n let ctx = undefined;\n for (const check of this._def.checks) {\n if (check.kind === \"min\") {\n if (input.data.length < check.value) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: check.value,\n type: \"string\",\n inclusive: true,\n exact: false,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"max\") {\n if (input.data.length > check.value) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: check.value,\n type: \"string\",\n inclusive: true,\n exact: false,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"length\") {\n const tooBig = input.data.length > check.value;\n const tooSmall = input.data.length < check.value;\n if (tooBig || tooSmall) {\n ctx = this._getOrReturnCtx(input, ctx);\n if (tooBig) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: check.value,\n type: \"string\",\n inclusive: true,\n exact: true,\n message: check.message,\n });\n }\n else if (tooSmall) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: check.value,\n type: \"string\",\n inclusive: true,\n exact: true,\n message: check.message,\n });\n }\n status.dirty();\n }\n }\n else if (check.kind === \"email\") {\n if (!emailRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"email\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"emoji\") {\n if (!emojiRegex) {\n emojiRegex = new RegExp(_emojiRegex, \"u\");\n }\n if (!emojiRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"emoji\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"uuid\") {\n if (!uuidRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"uuid\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"nanoid\") {\n if (!nanoidRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"nanoid\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"cuid\") {\n if (!cuidRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"cuid\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"cuid2\") {\n if (!cuid2Regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"cuid2\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"ulid\") {\n if (!ulidRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"ulid\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"url\") {\n try {\n new URL(input.data);\n }\n catch {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"url\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"regex\") {\n check.regex.lastIndex = 0;\n const testResult = check.regex.test(input.data);\n if (!testResult) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"regex\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"trim\") {\n input.data = input.data.trim();\n }\n else if (check.kind === \"includes\") {\n if (!input.data.includes(check.value, check.position)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: { includes: check.value, position: check.position },\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"toLowerCase\") {\n input.data = input.data.toLowerCase();\n }\n else if (check.kind === \"toUpperCase\") {\n input.data = input.data.toUpperCase();\n }\n else if (check.kind === \"startsWith\") {\n if (!input.data.startsWith(check.value)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: { startsWith: check.value },\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"endsWith\") {\n if (!input.data.endsWith(check.value)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: { endsWith: check.value },\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"datetime\") {\n const regex = datetimeRegex(check);\n if (!regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: \"datetime\",\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"date\") {\n const regex = dateRegex;\n if (!regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: \"date\",\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"time\") {\n const regex = timeRegex(check);\n if (!regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: \"time\",\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"duration\") {\n if (!durationRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"duration\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"ip\") {\n if (!isValidIP(input.data, check.version)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"ip\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"jwt\") {\n if (!isValidJWT(input.data, check.alg)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"jwt\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"cidr\") {\n if (!isValidCidr(input.data, check.version)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"cidr\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"base64\") {\n if (!base64Regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"base64\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"base64url\") {\n if (!base64urlRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"base64url\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else {\n util.assertNever(check);\n }\n }\n return { status: status.value, value: input.data };\n }\n _regex(regex, validation, message) {\n return this.refinement((data) => regex.test(data), {\n validation,\n code: ZodIssueCode.invalid_string,\n ...errorUtil.errToObj(message),\n });\n }\n _addCheck(check) {\n return new ZodString({\n ...this._def,\n checks: [...this._def.checks, check],\n });\n }\n email(message) {\n return this._addCheck({ kind: \"email\", ...errorUtil.errToObj(message) });\n }\n url(message) {\n return this._addCheck({ kind: \"url\", ...errorUtil.errToObj(message) });\n }\n emoji(message) {\n return this._addCheck({ kind: \"emoji\", ...errorUtil.errToObj(message) });\n }\n uuid(message) {\n return this._addCheck({ kind: \"uuid\", ...errorUtil.errToObj(message) });\n }\n nanoid(message) {\n return this._addCheck({ kind: \"nanoid\", ...errorUtil.errToObj(message) });\n }\n cuid(message) {\n return this._addCheck({ kind: \"cuid\", ...errorUtil.errToObj(message) });\n }\n cuid2(message) {\n return this._addCheck({ kind: \"cuid2\", ...errorUtil.errToObj(message) });\n }\n ulid(message) {\n return this._addCheck({ kind: \"ulid\", ...errorUtil.errToObj(message) });\n }\n base64(message) {\n return this._addCheck({ kind: \"base64\", ...errorUtil.errToObj(message) });\n }\n base64url(message) {\n // base64url encoding is a modification of base64 that can safely be used in URLs and filenames\n return this._addCheck({\n kind: \"base64url\",\n ...errorUtil.errToObj(message),\n });\n }\n jwt(options) {\n return this._addCheck({ kind: \"jwt\", ...errorUtil.errToObj(options) });\n }\n ip(options) {\n return this._addCheck({ kind: \"ip\", ...errorUtil.errToObj(options) });\n }\n cidr(options) {\n return this._addCheck({ kind: \"cidr\", ...errorUtil.errToObj(options) });\n }\n datetime(options) {\n if (typeof options === \"string\") {\n return this._addCheck({\n kind: \"datetime\",\n precision: null,\n offset: false,\n local: false,\n message: options,\n });\n }\n return this._addCheck({\n kind: \"datetime\",\n precision: typeof options?.precision === \"undefined\" ? null : options?.precision,\n offset: options?.offset ?? false,\n local: options?.local ?? false,\n ...errorUtil.errToObj(options?.message),\n });\n }\n date(message) {\n return this._addCheck({ kind: \"date\", message });\n }\n time(options) {\n if (typeof options === \"string\") {\n return this._addCheck({\n kind: \"time\",\n precision: null,\n message: options,\n });\n }\n return this._addCheck({\n kind: \"time\",\n precision: typeof options?.precision === \"undefined\" ? null : options?.precision,\n ...errorUtil.errToObj(options?.message),\n });\n }\n duration(message) {\n return this._addCheck({ kind: \"duration\", ...errorUtil.errToObj(message) });\n }\n regex(regex, message) {\n return this._addCheck({\n kind: \"regex\",\n regex: regex,\n ...errorUtil.errToObj(message),\n });\n }\n includes(value, options) {\n return this._addCheck({\n kind: \"includes\",\n value: value,\n position: options?.position,\n ...errorUtil.errToObj(options?.message),\n });\n }\n startsWith(value, message) {\n return this._addCheck({\n kind: \"startsWith\",\n value: value,\n ...errorUtil.errToObj(message),\n });\n }\n endsWith(value, message) {\n return this._addCheck({\n kind: \"endsWith\",\n value: value,\n ...errorUtil.errToObj(message),\n });\n }\n min(minLength, message) {\n return this._addCheck({\n kind: \"min\",\n value: minLength,\n ...errorUtil.errToObj(message),\n });\n }\n max(maxLength, message) {\n return this._addCheck({\n kind: \"max\",\n value: maxLength,\n ...errorUtil.errToObj(message),\n });\n }\n length(len, message) {\n return this._addCheck({\n kind: \"length\",\n value: len,\n ...errorUtil.errToObj(message),\n });\n }\n /**\n * Equivalent to `.min(1)`\n */\n nonempty(message) {\n return this.min(1, errorUtil.errToObj(message));\n }\n trim() {\n return new ZodString({\n ...this._def,\n checks: [...this._def.checks, { kind: \"trim\" }],\n });\n }\n toLowerCase() {\n return new ZodString({\n ...this._def,\n checks: [...this._def.checks, { kind: \"toLowerCase\" }],\n });\n }\n toUpperCase() {\n return new ZodString({\n ...this._def,\n checks: [...this._def.checks, { kind: \"toUpperCase\" }],\n });\n }\n get isDatetime() {\n return !!this._def.checks.find((ch) => ch.kind === \"datetime\");\n }\n get isDate() {\n return !!this._def.checks.find((ch) => ch.kind === \"date\");\n }\n get isTime() {\n return !!this._def.checks.find((ch) => ch.kind === \"time\");\n }\n get isDuration() {\n return !!this._def.checks.find((ch) => ch.kind === \"duration\");\n }\n get isEmail() {\n return !!this._def.checks.find((ch) => ch.kind === \"email\");\n }\n get isURL() {\n return !!this._def.checks.find((ch) => ch.kind === \"url\");\n }\n get isEmoji() {\n return !!this._def.checks.find((ch) => ch.kind === \"emoji\");\n }\n get isUUID() {\n return !!this._def.checks.find((ch) => ch.kind === \"uuid\");\n }\n get isNANOID() {\n return !!this._def.checks.find((ch) => ch.kind === \"nanoid\");\n }\n get isCUID() {\n return !!this._def.checks.find((ch) => ch.kind === \"cuid\");\n }\n get isCUID2() {\n return !!this._def.checks.find((ch) => ch.kind === \"cuid2\");\n }\n get isULID() {\n return !!this._def.checks.find((ch) => ch.kind === \"ulid\");\n }\n get isIP() {\n return !!this._def.checks.find((ch) => ch.kind === \"ip\");\n }\n get isCIDR() {\n return !!this._def.checks.find((ch) => ch.kind === \"cidr\");\n }\n get isBase64() {\n return !!this._def.checks.find((ch) => ch.kind === \"base64\");\n }\n get isBase64url() {\n // base64url encoding is a modification of base64 that can safely be used in URLs and filenames\n return !!this._def.checks.find((ch) => ch.kind === \"base64url\");\n }\n get minLength() {\n let min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"min\") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n }\n return min;\n }\n get maxLength() {\n let max = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"max\") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return max;\n }\n}\nZodString.create = (params) => {\n return new ZodString({\n checks: [],\n typeName: ZodFirstPartyTypeKind.ZodString,\n coerce: params?.coerce ?? false,\n ...processCreateParams(params),\n });\n};\n// https://stackoverflow.com/questions/3966484/why-does-modulus-operator-return-fractional-number-in-javascript/31711034#31711034\nfunction floatSafeRemainder(val, step) {\n const valDecCount = (val.toString().split(\".\")[1] || \"\").length;\n const stepDecCount = (step.toString().split(\".\")[1] || \"\").length;\n const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;\n const valInt = Number.parseInt(val.toFixed(decCount).replace(\".\", \"\"));\n const stepInt = Number.parseInt(step.toFixed(decCount).replace(\".\", \"\"));\n return (valInt % stepInt) / 10 ** decCount;\n}\nexport class ZodNumber extends ZodType {\n constructor() {\n super(...arguments);\n this.min = this.gte;\n this.max = this.lte;\n this.step = this.multipleOf;\n }\n _parse(input) {\n if (this._def.coerce) {\n input.data = Number(input.data);\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.number) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.number,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n let ctx = undefined;\n const status = new ParseStatus();\n for (const check of this._def.checks) {\n if (check.kind === \"int\") {\n if (!util.isInteger(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: \"integer\",\n received: \"float\",\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"min\") {\n const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;\n if (tooSmall) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: check.value,\n type: \"number\",\n inclusive: check.inclusive,\n exact: false,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"max\") {\n const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;\n if (tooBig) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: check.value,\n type: \"number\",\n inclusive: check.inclusive,\n exact: false,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"multipleOf\") {\n if (floatSafeRemainder(input.data, check.value) !== 0) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.not_multiple_of,\n multipleOf: check.value,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"finite\") {\n if (!Number.isFinite(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.not_finite,\n message: check.message,\n });\n status.dirty();\n }\n }\n else {\n util.assertNever(check);\n }\n }\n return { status: status.value, value: input.data };\n }\n gte(value, message) {\n return this.setLimit(\"min\", value, true, errorUtil.toString(message));\n }\n gt(value, message) {\n return this.setLimit(\"min\", value, false, errorUtil.toString(message));\n }\n lte(value, message) {\n return this.setLimit(\"max\", value, true, errorUtil.toString(message));\n }\n lt(value, message) {\n return this.setLimit(\"max\", value, false, errorUtil.toString(message));\n }\n setLimit(kind, value, inclusive, message) {\n return new ZodNumber({\n ...this._def,\n checks: [\n ...this._def.checks,\n {\n kind,\n value,\n inclusive,\n message: errorUtil.toString(message),\n },\n ],\n });\n }\n _addCheck(check) {\n return new ZodNumber({\n ...this._def,\n checks: [...this._def.checks, check],\n });\n }\n int(message) {\n return this._addCheck({\n kind: \"int\",\n message: errorUtil.toString(message),\n });\n }\n positive(message) {\n return this._addCheck({\n kind: \"min\",\n value: 0,\n inclusive: false,\n message: errorUtil.toString(message),\n });\n }\n negative(message) {\n return this._addCheck({\n kind: \"max\",\n value: 0,\n inclusive: false,\n message: errorUtil.toString(message),\n });\n }\n nonpositive(message) {\n return this._addCheck({\n kind: \"max\",\n value: 0,\n inclusive: true,\n message: errorUtil.toString(message),\n });\n }\n nonnegative(message) {\n return this._addCheck({\n kind: \"min\",\n value: 0,\n inclusive: true,\n message: errorUtil.toString(message),\n });\n }\n multipleOf(value, message) {\n return this._addCheck({\n kind: \"multipleOf\",\n value: value,\n message: errorUtil.toString(message),\n });\n }\n finite(message) {\n return this._addCheck({\n kind: \"finite\",\n message: errorUtil.toString(message),\n });\n }\n safe(message) {\n return this._addCheck({\n kind: \"min\",\n inclusive: true,\n value: Number.MIN_SAFE_INTEGER,\n message: errorUtil.toString(message),\n })._addCheck({\n kind: \"max\",\n inclusive: true,\n value: Number.MAX_SAFE_INTEGER,\n message: errorUtil.toString(message),\n });\n }\n get minValue() {\n let min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"min\") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n }\n return min;\n }\n get maxValue() {\n let max = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"max\") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return max;\n }\n get isInt() {\n return !!this._def.checks.find((ch) => ch.kind === \"int\" || (ch.kind === \"multipleOf\" && util.isInteger(ch.value)));\n }\n get isFinite() {\n let max = null;\n let min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"finite\" || ch.kind === \"int\" || ch.kind === \"multipleOf\") {\n return true;\n }\n else if (ch.kind === \"min\") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n else if (ch.kind === \"max\") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return Number.isFinite(min) && Number.isFinite(max);\n }\n}\nZodNumber.create = (params) => {\n return new ZodNumber({\n checks: [],\n typeName: ZodFirstPartyTypeKind.ZodNumber,\n coerce: params?.coerce || false,\n ...processCreateParams(params),\n });\n};\nexport class ZodBigInt extends ZodType {\n constructor() {\n super(...arguments);\n this.min = this.gte;\n this.max = this.lte;\n }\n _parse(input) {\n if (this._def.coerce) {\n try {\n input.data = BigInt(input.data);\n }\n catch {\n return this._getInvalidInput(input);\n }\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.bigint) {\n return this._getInvalidInput(input);\n }\n let ctx = undefined;\n const status = new ParseStatus();\n for (const check of this._def.checks) {\n if (check.kind === \"min\") {\n const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;\n if (tooSmall) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n type: \"bigint\",\n minimum: check.value,\n inclusive: check.inclusive,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"max\") {\n const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;\n if (tooBig) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n type: \"bigint\",\n maximum: check.value,\n inclusive: check.inclusive,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"multipleOf\") {\n if (input.data % check.value !== BigInt(0)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.not_multiple_of,\n multipleOf: check.value,\n message: check.message,\n });\n status.dirty();\n }\n }\n else {\n util.assertNever(check);\n }\n }\n return { status: status.value, value: input.data };\n }\n _getInvalidInput(input) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.bigint,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n gte(value, message) {\n return this.setLimit(\"min\", value, true, errorUtil.toString(message));\n }\n gt(value, message) {\n return this.setLimit(\"min\", value, false, errorUtil.toString(message));\n }\n lte(value, message) {\n return this.setLimit(\"max\", value, true, errorUtil.toString(message));\n }\n lt(value, message) {\n return this.setLimit(\"max\", value, false, errorUtil.toString(message));\n }\n setLimit(kind, value, inclusive, message) {\n return new ZodBigInt({\n ...this._def,\n checks: [\n ...this._def.checks,\n {\n kind,\n value,\n inclusive,\n message: errorUtil.toString(message),\n },\n ],\n });\n }\n _addCheck(check) {\n return new ZodBigInt({\n ...this._def,\n checks: [...this._def.checks, check],\n });\n }\n positive(message) {\n return this._addCheck({\n kind: \"min\",\n value: BigInt(0),\n inclusive: false,\n message: errorUtil.toString(message),\n });\n }\n negative(message) {\n return this._addCheck({\n kind: \"max\",\n value: BigInt(0),\n inclusive: false,\n message: errorUtil.toString(message),\n });\n }\n nonpositive(message) {\n return this._addCheck({\n kind: \"max\",\n value: BigInt(0),\n inclusive: true,\n message: errorUtil.toString(message),\n });\n }\n nonnegative(message) {\n return this._addCheck({\n kind: \"min\",\n value: BigInt(0),\n inclusive: true,\n message: errorUtil.toString(message),\n });\n }\n multipleOf(value, message) {\n return this._addCheck({\n kind: \"multipleOf\",\n value,\n message: errorUtil.toString(message),\n });\n }\n get minValue() {\n let min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"min\") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n }\n return min;\n }\n get maxValue() {\n let max = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"max\") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return max;\n }\n}\nZodBigInt.create = (params) => {\n return new ZodBigInt({\n checks: [],\n typeName: ZodFirstPartyTypeKind.ZodBigInt,\n coerce: params?.coerce ?? false,\n ...processCreateParams(params),\n });\n};\nexport class ZodBoolean extends ZodType {\n _parse(input) {\n if (this._def.coerce) {\n input.data = Boolean(input.data);\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.boolean) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.boolean,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n}\nZodBoolean.create = (params) => {\n return new ZodBoolean({\n typeName: ZodFirstPartyTypeKind.ZodBoolean,\n coerce: params?.coerce || false,\n ...processCreateParams(params),\n });\n};\nexport class ZodDate extends ZodType {\n _parse(input) {\n if (this._def.coerce) {\n input.data = new Date(input.data);\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.date) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.date,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n if (Number.isNaN(input.data.getTime())) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_date,\n });\n return INVALID;\n }\n const status = new ParseStatus();\n let ctx = undefined;\n for (const check of this._def.checks) {\n if (check.kind === \"min\") {\n if (input.data.getTime() < check.value) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n message: check.message,\n inclusive: true,\n exact: false,\n minimum: check.value,\n type: \"date\",\n });\n status.dirty();\n }\n }\n else if (check.kind === \"max\") {\n if (input.data.getTime() > check.value) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n message: check.message,\n inclusive: true,\n exact: false,\n maximum: check.value,\n type: \"date\",\n });\n status.dirty();\n }\n }\n else {\n util.assertNever(check);\n }\n }\n return {\n status: status.value,\n value: new Date(input.data.getTime()),\n };\n }\n _addCheck(check) {\n return new ZodDate({\n ...this._def,\n checks: [...this._def.checks, check],\n });\n }\n min(minDate, message) {\n return this._addCheck({\n kind: \"min\",\n value: minDate.getTime(),\n message: errorUtil.toString(message),\n });\n }\n max(maxDate, message) {\n return this._addCheck({\n kind: \"max\",\n value: maxDate.getTime(),\n message: errorUtil.toString(message),\n });\n }\n get minDate() {\n let min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"min\") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n }\n return min != null ? new Date(min) : null;\n }\n get maxDate() {\n let max = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"max\") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return max != null ? new Date(max) : null;\n }\n}\nZodDate.create = (params) => {\n return new ZodDate({\n checks: [],\n coerce: params?.coerce || false,\n typeName: ZodFirstPartyTypeKind.ZodDate,\n ...processCreateParams(params),\n });\n};\nexport class ZodSymbol extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.symbol) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.symbol,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n}\nZodSymbol.create = (params) => {\n return new ZodSymbol({\n typeName: ZodFirstPartyTypeKind.ZodSymbol,\n ...processCreateParams(params),\n });\n};\nexport class ZodUndefined extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.undefined) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.undefined,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n}\nZodUndefined.create = (params) => {\n return new ZodUndefined({\n typeName: ZodFirstPartyTypeKind.ZodUndefined,\n ...processCreateParams(params),\n });\n};\nexport class ZodNull extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.null) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.null,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n}\nZodNull.create = (params) => {\n return new ZodNull({\n typeName: ZodFirstPartyTypeKind.ZodNull,\n ...processCreateParams(params),\n });\n};\nexport class ZodAny extends ZodType {\n constructor() {\n super(...arguments);\n // to prevent instances of other classes from extending ZodAny. this causes issues with catchall in ZodObject.\n this._any = true;\n }\n _parse(input) {\n return OK(input.data);\n }\n}\nZodAny.create = (params) => {\n return new ZodAny({\n typeName: ZodFirstPartyTypeKind.ZodAny,\n ...processCreateParams(params),\n });\n};\nexport class ZodUnknown extends ZodType {\n constructor() {\n super(...arguments);\n // required\n this._unknown = true;\n }\n _parse(input) {\n return OK(input.data);\n }\n}\nZodUnknown.create = (params) => {\n return new ZodUnknown({\n typeName: ZodFirstPartyTypeKind.ZodUnknown,\n ...processCreateParams(params),\n });\n};\nexport class ZodNever extends ZodType {\n _parse(input) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.never,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n}\nZodNever.create = (params) => {\n return new ZodNever({\n typeName: ZodFirstPartyTypeKind.ZodNever,\n ...processCreateParams(params),\n });\n};\nexport class ZodVoid extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.undefined) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.void,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n}\nZodVoid.create = (params) => {\n return new ZodVoid({\n typeName: ZodFirstPartyTypeKind.ZodVoid,\n ...processCreateParams(params),\n });\n};\nexport class ZodArray extends ZodType {\n _parse(input) {\n const { ctx, status } = this._processInputParams(input);\n const def = this._def;\n if (ctx.parsedType !== ZodParsedType.array) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.array,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n if (def.exactLength !== null) {\n const tooBig = ctx.data.length > def.exactLength.value;\n const tooSmall = ctx.data.length < def.exactLength.value;\n if (tooBig || tooSmall) {\n addIssueToContext(ctx, {\n code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small,\n minimum: (tooSmall ? def.exactLength.value : undefined),\n maximum: (tooBig ? def.exactLength.value : undefined),\n type: \"array\",\n inclusive: true,\n exact: true,\n message: def.exactLength.message,\n });\n status.dirty();\n }\n }\n if (def.minLength !== null) {\n if (ctx.data.length < def.minLength.value) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: def.minLength.value,\n type: \"array\",\n inclusive: true,\n exact: false,\n message: def.minLength.message,\n });\n status.dirty();\n }\n }\n if (def.maxLength !== null) {\n if (ctx.data.length > def.maxLength.value) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: def.maxLength.value,\n type: \"array\",\n inclusive: true,\n exact: false,\n message: def.maxLength.message,\n });\n status.dirty();\n }\n }\n if (ctx.common.async) {\n return Promise.all([...ctx.data].map((item, i) => {\n return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i));\n })).then((result) => {\n return ParseStatus.mergeArray(status, result);\n });\n }\n const result = [...ctx.data].map((item, i) => {\n return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i));\n });\n return ParseStatus.mergeArray(status, result);\n }\n get element() {\n return this._def.type;\n }\n min(minLength, message) {\n return new ZodArray({\n ...this._def,\n minLength: { value: minLength, message: errorUtil.toString(message) },\n });\n }\n max(maxLength, message) {\n return new ZodArray({\n ...this._def,\n maxLength: { value: maxLength, message: errorUtil.toString(message) },\n });\n }\n length(len, message) {\n return new ZodArray({\n ...this._def,\n exactLength: { value: len, message: errorUtil.toString(message) },\n });\n }\n nonempty(message) {\n return this.min(1, message);\n }\n}\nZodArray.create = (schema, params) => {\n return new ZodArray({\n type: schema,\n minLength: null,\n maxLength: null,\n exactLength: null,\n typeName: ZodFirstPartyTypeKind.ZodArray,\n ...processCreateParams(params),\n });\n};\nfunction deepPartialify(schema) {\n if (schema instanceof ZodObject) {\n const newShape = {};\n for (const key in schema.shape) {\n const fieldSchema = schema.shape[key];\n newShape[key] = ZodOptional.create(deepPartialify(fieldSchema));\n }\n return new ZodObject({\n ...schema._def,\n shape: () => newShape,\n });\n }\n else if (schema instanceof ZodArray) {\n return new ZodArray({\n ...schema._def,\n type: deepPartialify(schema.element),\n });\n }\n else if (schema instanceof ZodOptional) {\n return ZodOptional.create(deepPartialify(schema.unwrap()));\n }\n else if (schema instanceof ZodNullable) {\n return ZodNullable.create(deepPartialify(schema.unwrap()));\n }\n else if (schema instanceof ZodTuple) {\n return ZodTuple.create(schema.items.map((item) => deepPartialify(item)));\n }\n else {\n return schema;\n }\n}\nexport class ZodObject extends ZodType {\n constructor() {\n super(...arguments);\n this._cached = null;\n /**\n * @deprecated In most cases, this is no longer needed - unknown properties are now silently stripped.\n * If you want to pass through unknown properties, use `.passthrough()` instead.\n */\n this.nonstrict = this.passthrough;\n // extend<\n // Augmentation extends ZodRawShape,\n // NewOutput extends util.flatten<{\n // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation\n // ? Augmentation[k][\"_output\"]\n // : k extends keyof Output\n // ? Output[k]\n // : never;\n // }>,\n // NewInput extends util.flatten<{\n // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation\n // ? Augmentation[k][\"_input\"]\n // : k extends keyof Input\n // ? Input[k]\n // : never;\n // }>\n // >(\n // augmentation: Augmentation\n // ): ZodObject<\n // extendShape<T, Augmentation>,\n // UnknownKeys,\n // Catchall,\n // NewOutput,\n // NewInput\n // > {\n // return new ZodObject({\n // ...this._def,\n // shape: () => ({\n // ...this._def.shape(),\n // ...augmentation,\n // }),\n // }) as any;\n // }\n /**\n * @deprecated Use `.extend` instead\n * */\n this.augment = this.extend;\n }\n _getCached() {\n if (this._cached !== null)\n return this._cached;\n const shape = this._def.shape();\n const keys = util.objectKeys(shape);\n this._cached = { shape, keys };\n return this._cached;\n }\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.object) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.object,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const { status, ctx } = this._processInputParams(input);\n const { shape, keys: shapeKeys } = this._getCached();\n const extraKeys = [];\n if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === \"strip\")) {\n for (const key in ctx.data) {\n if (!shapeKeys.includes(key)) {\n extraKeys.push(key);\n }\n }\n }\n const pairs = [];\n for (const key of shapeKeys) {\n const keyValidator = shape[key];\n const value = ctx.data[key];\n pairs.push({\n key: { status: \"valid\", value: key },\n value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),\n alwaysSet: key in ctx.data,\n });\n }\n if (this._def.catchall instanceof ZodNever) {\n const unknownKeys = this._def.unknownKeys;\n if (unknownKeys === \"passthrough\") {\n for (const key of extraKeys) {\n pairs.push({\n key: { status: \"valid\", value: key },\n value: { status: \"valid\", value: ctx.data[key] },\n });\n }\n }\n else if (unknownKeys === \"strict\") {\n if (extraKeys.length > 0) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.unrecognized_keys,\n keys: extraKeys,\n });\n status.dirty();\n }\n }\n else if (unknownKeys === \"strip\") {\n }\n else {\n throw new Error(`Internal ZodObject error: invalid unknownKeys value.`);\n }\n }\n else {\n // run catchall validation\n const catchall = this._def.catchall;\n for (const key of extraKeys) {\n const value = ctx.data[key];\n pairs.push({\n key: { status: \"valid\", value: key },\n value: catchall._parse(new ParseInputLazyPath(ctx, value, ctx.path, key) //, ctx.child(key), value, getParsedType(value)\n ),\n alwaysSet: key in ctx.data,\n });\n }\n }\n if (ctx.common.async) {\n return Promise.resolve()\n .then(async () => {\n const syncPairs = [];\n for (const pair of pairs) {\n const key = await pair.key;\n const value = await pair.value;\n syncPairs.push({\n key,\n value,\n alwaysSet: pair.alwaysSet,\n });\n }\n return syncPairs;\n })\n .then((syncPairs) => {\n return ParseStatus.mergeObjectSync(status, syncPairs);\n });\n }\n else {\n return ParseStatus.mergeObjectSync(status, pairs);\n }\n }\n get shape() {\n return this._def.shape();\n }\n strict(message) {\n errorUtil.errToObj;\n return new ZodObject({\n ...this._def,\n unknownKeys: \"strict\",\n ...(message !== undefined\n ? {\n errorMap: (issue, ctx) => {\n const defaultError = this._def.errorMap?.(issue, ctx).message ?? ctx.defaultError;\n if (issue.code === \"unrecognized_keys\")\n return {\n message: errorUtil.errToObj(message).message ?? defaultError,\n };\n return {\n message: defaultError,\n };\n },\n }\n : {}),\n });\n }\n strip() {\n return new ZodObject({\n ...this._def,\n unknownKeys: \"strip\",\n });\n }\n passthrough() {\n return new ZodObject({\n ...this._def,\n unknownKeys: \"passthrough\",\n });\n }\n // const AugmentFactory =\n // <Def extends ZodObjectDef>(def: Def) =>\n // <Augmentation extends ZodRawShape>(\n // augmentation: Augmentation\n // ): ZodObject<\n // extendShape<ReturnType<Def[\"shape\"]>, Augmentation>,\n // Def[\"unknownKeys\"],\n // Def[\"catchall\"]\n // > => {\n // return new ZodObject({\n // ...def,\n // shape: () => ({\n // ...def.shape(),\n // ...augmentation,\n // }),\n // }) as any;\n // };\n extend(augmentation) {\n return new ZodObject({\n ...this._def,\n shape: () => ({\n ...this._def.shape(),\n ...augmentation,\n }),\n });\n }\n /**\n * Prior to zod@1.0.12 there was a bug in the\n * inferred type of merged objects. Please\n * upgrade if you are experiencing issues.\n */\n merge(merging) {\n const merged = new ZodObject({\n unknownKeys: merging._def.unknownKeys,\n catchall: merging._def.catchall,\n shape: () => ({\n ...this._def.shape(),\n ...merging._def.shape(),\n }),\n typeName: ZodFirstPartyTypeKind.ZodObject,\n });\n return merged;\n }\n // merge<\n // Incoming extends AnyZodObject,\n // Augmentation extends Incoming[\"shape\"],\n // NewOutput extends {\n // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation\n // ? Augmentation[k][\"_output\"]\n // : k extends keyof Output\n // ? Output[k]\n // : never;\n // },\n // NewInput extends {\n // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation\n // ? Augmentation[k][\"_input\"]\n // : k extends keyof Input\n // ? Input[k]\n // : never;\n // }\n // >(\n // merging: Incoming\n // ): ZodObject<\n // extendShape<T, ReturnType<Incoming[\"_def\"][\"shape\"]>>,\n // Incoming[\"_def\"][\"unknownKeys\"],\n // Incoming[\"_def\"][\"catchall\"],\n // NewOutput,\n // NewInput\n // > {\n // const merged: any = new ZodObject({\n // unknownKeys: merging._def.unknownKeys,\n // catchall: merging._def.catchall,\n // shape: () =>\n // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),\n // typeName: ZodFirstPartyTypeKind.ZodObject,\n // }) as any;\n // return merged;\n // }\n setKey(key, schema) {\n return this.augment({ [key]: schema });\n }\n // merge<Incoming extends AnyZodObject>(\n // merging: Incoming\n // ): //ZodObject<T & Incoming[\"_shape\"], UnknownKeys, Catchall> = (merging) => {\n // ZodObject<\n // extendShape<T, ReturnType<Incoming[\"_def\"][\"shape\"]>>,\n // Incoming[\"_def\"][\"unknownKeys\"],\n // Incoming[\"_def\"][\"catchall\"]\n // > {\n // // const mergedShape = objectUtil.mergeShapes(\n // // this._def.shape(),\n // // merging._def.shape()\n // // );\n // const merged: any = new ZodObject({\n // unknownKeys: merging._def.unknownKeys,\n // catchall: merging._def.catchall,\n // shape: () =>\n // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),\n // typeName: ZodFirstPartyTypeKind.ZodObject,\n // }) as any;\n // return merged;\n // }\n catchall(index) {\n return new ZodObject({\n ...this._def,\n catchall: index,\n });\n }\n pick(mask) {\n const shape = {};\n for (const key of util.objectKeys(mask)) {\n if (mask[key] && this.shape[key]) {\n shape[key] = this.shape[key];\n }\n }\n return new ZodObject({\n ...this._def,\n shape: () => shape,\n });\n }\n omit(mask) {\n const shape = {};\n for (const key of util.objectKeys(this.shape)) {\n if (!mask[key]) {\n shape[key] = this.shape[key];\n }\n }\n return new ZodObject({\n ...this._def,\n shape: () => shape,\n });\n }\n /**\n * @deprecated\n */\n deepPartial() {\n return deepPartialify(this);\n }\n partial(mask) {\n const newShape = {};\n for (const key of util.objectKeys(this.shape)) {\n const fieldSchema = this.shape[key];\n if (mask && !mask[key]) {\n newShape[key] = fieldSchema;\n }\n else {\n newShape[key] = fieldSchema.optional();\n }\n }\n return new ZodObject({\n ...this._def,\n shape: () => newShape,\n });\n }\n required(mask) {\n const newShape = {};\n for (const key of util.objectKeys(this.shape)) {\n if (mask && !mask[key]) {\n newShape[key] = this.shape[key];\n }\n else {\n const fieldSchema = this.shape[key];\n let newField = fieldSchema;\n while (newField instanceof ZodOptional) {\n newField = newField._def.innerType;\n }\n newShape[key] = newField;\n }\n }\n return new ZodObject({\n ...this._def,\n shape: () => newShape,\n });\n }\n keyof() {\n return createZodEnum(util.objectKeys(this.shape));\n }\n}\nZodObject.create = (shape, params) => {\n return new ZodObject({\n shape: () => shape,\n unknownKeys: \"strip\",\n catchall: ZodNever.create(),\n typeName: ZodFirstPartyTypeKind.ZodObject,\n ...processCreateParams(params),\n });\n};\nZodObject.strictCreate = (shape, params) => {\n return new ZodObject({\n shape: () => shape,\n unknownKeys: \"strict\",\n catchall: ZodNever.create(),\n typeName: ZodFirstPartyTypeKind.ZodObject,\n ...processCreateParams(params),\n });\n};\nZodObject.lazycreate = (shape, params) => {\n return new ZodObject({\n shape,\n unknownKeys: \"strip\",\n catchall: ZodNever.create(),\n typeName: ZodFirstPartyTypeKind.ZodObject,\n ...processCreateParams(params),\n });\n};\nexport class ZodUnion extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n const options = this._def.options;\n function handleResults(results) {\n // return first issue-free validation if it exists\n for (const result of results) {\n if (result.result.status === \"valid\") {\n return result.result;\n }\n }\n for (const result of results) {\n if (result.result.status === \"dirty\") {\n // add issues from dirty option\n ctx.common.issues.push(...result.ctx.common.issues);\n return result.result;\n }\n }\n // return invalid\n const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues));\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_union,\n unionErrors,\n });\n return INVALID;\n }\n if (ctx.common.async) {\n return Promise.all(options.map(async (option) => {\n const childCtx = {\n ...ctx,\n common: {\n ...ctx.common,\n issues: [],\n },\n parent: null,\n };\n return {\n result: await option._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: childCtx,\n }),\n ctx: childCtx,\n };\n })).then(handleResults);\n }\n else {\n let dirty = undefined;\n const issues = [];\n for (const option of options) {\n const childCtx = {\n ...ctx,\n common: {\n ...ctx.common,\n issues: [],\n },\n parent: null,\n };\n const result = option._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: childCtx,\n });\n if (result.status === \"valid\") {\n return result;\n }\n else if (result.status === \"dirty\" && !dirty) {\n dirty = { result, ctx: childCtx };\n }\n if (childCtx.common.issues.length) {\n issues.push(childCtx.common.issues);\n }\n }\n if (dirty) {\n ctx.common.issues.push(...dirty.ctx.common.issues);\n return dirty.result;\n }\n const unionErrors = issues.map((issues) => new ZodError(issues));\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_union,\n unionErrors,\n });\n return INVALID;\n }\n }\n get options() {\n return this._def.options;\n }\n}\nZodUnion.create = (types, params) => {\n return new ZodUnion({\n options: types,\n typeName: ZodFirstPartyTypeKind.ZodUnion,\n ...processCreateParams(params),\n });\n};\n/////////////////////////////////////////////////////\n/////////////////////////////////////////////////////\n////////// //////////\n////////// ZodDiscriminatedUnion //////////\n////////// //////////\n/////////////////////////////////////////////////////\n/////////////////////////////////////////////////////\nconst getDiscriminator = (type) => {\n if (type instanceof ZodLazy) {\n return getDiscriminator(type.schema);\n }\n else if (type instanceof ZodEffects) {\n return getDiscriminator(type.innerType());\n }\n else if (type instanceof ZodLiteral) {\n return [type.value];\n }\n else if (type instanceof ZodEnum) {\n return type.options;\n }\n else if (type instanceof ZodNativeEnum) {\n // eslint-disable-next-line ban/ban\n return util.objectValues(type.enum);\n }\n else if (type instanceof ZodDefault) {\n return getDiscriminator(type._def.innerType);\n }\n else if (type instanceof ZodUndefined) {\n return [undefined];\n }\n else if (type instanceof ZodNull) {\n return [null];\n }\n else if (type instanceof ZodOptional) {\n return [undefined, ...getDiscriminator(type.unwrap())];\n }\n else if (type instanceof ZodNullable) {\n return [null, ...getDiscriminator(type.unwrap())];\n }\n else if (type instanceof ZodBranded) {\n return getDiscriminator(type.unwrap());\n }\n else if (type instanceof ZodReadonly) {\n return getDiscriminator(type.unwrap());\n }\n else if (type instanceof ZodCatch) {\n return getDiscriminator(type._def.innerType);\n }\n else {\n return [];\n }\n};\nexport class ZodDiscriminatedUnion extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.object) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.object,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const discriminator = this.discriminator;\n const discriminatorValue = ctx.data[discriminator];\n const option = this.optionsMap.get(discriminatorValue);\n if (!option) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_union_discriminator,\n options: Array.from(this.optionsMap.keys()),\n path: [discriminator],\n });\n return INVALID;\n }\n if (ctx.common.async) {\n return option._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n }\n else {\n return option._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n }\n }\n get discriminator() {\n return this._def.discriminator;\n }\n get options() {\n return this._def.options;\n }\n get optionsMap() {\n return this._def.optionsMap;\n }\n /**\n * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor.\n * However, it only allows a union of objects, all of which need to share a discriminator property. This property must\n * have a different value for each object in the union.\n * @param discriminator the name of the discriminator property\n * @param types an array of object schemas\n * @param params\n */\n static create(discriminator, options, params) {\n // Get all the valid discriminator values\n const optionsMap = new Map();\n // try {\n for (const type of options) {\n const discriminatorValues = getDiscriminator(type.shape[discriminator]);\n if (!discriminatorValues.length) {\n throw new Error(`A discriminator value for key \\`${discriminator}\\` could not be extracted from all schema options`);\n }\n for (const value of discriminatorValues) {\n if (optionsMap.has(value)) {\n throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`);\n }\n optionsMap.set(value, type);\n }\n }\n return new ZodDiscriminatedUnion({\n typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion,\n discriminator,\n options,\n optionsMap,\n ...processCreateParams(params),\n });\n }\n}\nfunction mergeValues(a, b) {\n const aType = getParsedType(a);\n const bType = getParsedType(b);\n if (a === b) {\n return { valid: true, data: a };\n }\n else if (aType === ZodParsedType.object && bType === ZodParsedType.object) {\n const bKeys = util.objectKeys(b);\n const sharedKeys = util.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1);\n const newObj = { ...a, ...b };\n for (const key of sharedKeys) {\n const sharedValue = mergeValues(a[key], b[key]);\n if (!sharedValue.valid) {\n return { valid: false };\n }\n newObj[key] = sharedValue.data;\n }\n return { valid: true, data: newObj };\n }\n else if (aType === ZodParsedType.array && bType === ZodParsedType.array) {\n if (a.length !== b.length) {\n return { valid: false };\n }\n const newArray = [];\n for (let index = 0; index < a.length; index++) {\n const itemA = a[index];\n const itemB = b[index];\n const sharedValue = mergeValues(itemA, itemB);\n if (!sharedValue.valid) {\n return { valid: false };\n }\n newArray.push(sharedValue.data);\n }\n return { valid: true, data: newArray };\n }\n else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a === +b) {\n return { valid: true, data: a };\n }\n else {\n return { valid: false };\n }\n}\nexport class ZodIntersection extends ZodType {\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n const handleParsed = (parsedLeft, parsedRight) => {\n if (isAborted(parsedLeft) || isAborted(parsedRight)) {\n return INVALID;\n }\n const merged = mergeValues(parsedLeft.value, parsedRight.value);\n if (!merged.valid) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_intersection_types,\n });\n return INVALID;\n }\n if (isDirty(parsedLeft) || isDirty(parsedRight)) {\n status.dirty();\n }\n return { status: status.value, value: merged.data };\n };\n if (ctx.common.async) {\n return Promise.all([\n this._def.left._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n }),\n this._def.right._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n }),\n ]).then(([left, right]) => handleParsed(left, right));\n }\n else {\n return handleParsed(this._def.left._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n }), this._def.right._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n }));\n }\n }\n}\nZodIntersection.create = (left, right, params) => {\n return new ZodIntersection({\n left: left,\n right: right,\n typeName: ZodFirstPartyTypeKind.ZodIntersection,\n ...processCreateParams(params),\n });\n};\n// type ZodTupleItems = [ZodTypeAny, ...ZodTypeAny[]];\nexport class ZodTuple extends ZodType {\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.array) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.array,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n if (ctx.data.length < this._def.items.length) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: this._def.items.length,\n inclusive: true,\n exact: false,\n type: \"array\",\n });\n return INVALID;\n }\n const rest = this._def.rest;\n if (!rest && ctx.data.length > this._def.items.length) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: this._def.items.length,\n inclusive: true,\n exact: false,\n type: \"array\",\n });\n status.dirty();\n }\n const items = [...ctx.data]\n .map((item, itemIndex) => {\n const schema = this._def.items[itemIndex] || this._def.rest;\n if (!schema)\n return null;\n return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex));\n })\n .filter((x) => !!x); // filter nulls\n if (ctx.common.async) {\n return Promise.all(items).then((results) => {\n return ParseStatus.mergeArray(status, results);\n });\n }\n else {\n return ParseStatus.mergeArray(status, items);\n }\n }\n get items() {\n return this._def.items;\n }\n rest(rest) {\n return new ZodTuple({\n ...this._def,\n rest,\n });\n }\n}\nZodTuple.create = (schemas, params) => {\n if (!Array.isArray(schemas)) {\n throw new Error(\"You must pass an array of schemas to z.tuple([ ... ])\");\n }\n return new ZodTuple({\n items: schemas,\n typeName: ZodFirstPartyTypeKind.ZodTuple,\n rest: null,\n ...processCreateParams(params),\n });\n};\nexport class ZodRecord extends ZodType {\n get keySchema() {\n return this._def.keyType;\n }\n get valueSchema() {\n return this._def.valueType;\n }\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.object) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.object,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const pairs = [];\n const keyType = this._def.keyType;\n const valueType = this._def.valueType;\n for (const key in ctx.data) {\n pairs.push({\n key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)),\n value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)),\n alwaysSet: key in ctx.data,\n });\n }\n if (ctx.common.async) {\n return ParseStatus.mergeObjectAsync(status, pairs);\n }\n else {\n return ParseStatus.mergeObjectSync(status, pairs);\n }\n }\n get element() {\n return this._def.valueType;\n }\n static create(first, second, third) {\n if (second instanceof ZodType) {\n return new ZodRecord({\n keyType: first,\n valueType: second,\n typeName: ZodFirstPartyTypeKind.ZodRecord,\n ...processCreateParams(third),\n });\n }\n return new ZodRecord({\n keyType: ZodString.create(),\n valueType: first,\n typeName: ZodFirstPartyTypeKind.ZodRecord,\n ...processCreateParams(second),\n });\n }\n}\nexport class ZodMap extends ZodType {\n get keySchema() {\n return this._def.keyType;\n }\n get valueSchema() {\n return this._def.valueType;\n }\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.map) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.map,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const keyType = this._def.keyType;\n const valueType = this._def.valueType;\n const pairs = [...ctx.data.entries()].map(([key, value], index) => {\n return {\n key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, \"key\"])),\n value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, \"value\"])),\n };\n });\n if (ctx.common.async) {\n const finalMap = new Map();\n return Promise.resolve().then(async () => {\n for (const pair of pairs) {\n const key = await pair.key;\n const value = await pair.value;\n if (key.status === \"aborted\" || value.status === \"aborted\") {\n return INVALID;\n }\n if (key.status === \"dirty\" || value.status === \"dirty\") {\n status.dirty();\n }\n finalMap.set(key.value, value.value);\n }\n return { status: status.value, value: finalMap };\n });\n }\n else {\n const finalMap = new Map();\n for (const pair of pairs) {\n const key = pair.key;\n const value = pair.value;\n if (key.status === \"aborted\" || value.status === \"aborted\") {\n return INVALID;\n }\n if (key.status === \"dirty\" || value.status === \"dirty\") {\n status.dirty();\n }\n finalMap.set(key.value, value.value);\n }\n return { status: status.value, value: finalMap };\n }\n }\n}\nZodMap.create = (keyType, valueType, params) => {\n return new ZodMap({\n valueType,\n keyType,\n typeName: ZodFirstPartyTypeKind.ZodMap,\n ...processCreateParams(params),\n });\n};\nexport class ZodSet extends ZodType {\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.set) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.set,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const def = this._def;\n if (def.minSize !== null) {\n if (ctx.data.size < def.minSize.value) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: def.minSize.value,\n type: \"set\",\n inclusive: true,\n exact: false,\n message: def.minSize.message,\n });\n status.dirty();\n }\n }\n if (def.maxSize !== null) {\n if (ctx.data.size > def.maxSize.value) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: def.maxSize.value,\n type: \"set\",\n inclusive: true,\n exact: false,\n message: def.maxSize.message,\n });\n status.dirty();\n }\n }\n const valueType = this._def.valueType;\n function finalizeSet(elements) {\n const parsedSet = new Set();\n for (const element of elements) {\n if (element.status === \"aborted\")\n return INVALID;\n if (element.status === \"dirty\")\n status.dirty();\n parsedSet.add(element.value);\n }\n return { status: status.value, value: parsedSet };\n }\n const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i)));\n if (ctx.common.async) {\n return Promise.all(elements).then((elements) => finalizeSet(elements));\n }\n else {\n return finalizeSet(elements);\n }\n }\n min(minSize, message) {\n return new ZodSet({\n ...this._def,\n minSize: { value: minSize, message: errorUtil.toString(message) },\n });\n }\n max(maxSize, message) {\n return new ZodSet({\n ...this._def,\n maxSize: { value: maxSize, message: errorUtil.toString(message) },\n });\n }\n size(size, message) {\n return this.min(size, message).max(size, message);\n }\n nonempty(message) {\n return this.min(1, message);\n }\n}\nZodSet.create = (valueType, params) => {\n return new ZodSet({\n valueType,\n minSize: null,\n maxSize: null,\n typeName: ZodFirstPartyTypeKind.ZodSet,\n ...processCreateParams(params),\n });\n};\nexport class ZodFunction extends ZodType {\n constructor() {\n super(...arguments);\n this.validate = this.implement;\n }\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.function) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.function,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n function makeArgsIssue(args, error) {\n return makeIssue({\n data: args,\n path: ctx.path,\n errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), defaultErrorMap].filter((x) => !!x),\n issueData: {\n code: ZodIssueCode.invalid_arguments,\n argumentsError: error,\n },\n });\n }\n function makeReturnsIssue(returns, error) {\n return makeIssue({\n data: returns,\n path: ctx.path,\n errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), defaultErrorMap].filter((x) => !!x),\n issueData: {\n code: ZodIssueCode.invalid_return_type,\n returnTypeError: error,\n },\n });\n }\n const params = { errorMap: ctx.common.contextualErrorMap };\n const fn = ctx.data;\n if (this._def.returns instanceof ZodPromise) {\n // Would love a way to avoid disabling this rule, but we need\n // an alias (using an arrow function was what caused 2651).\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const me = this;\n return OK(async function (...args) {\n const error = new ZodError([]);\n const parsedArgs = await me._def.args.parseAsync(args, params).catch((e) => {\n error.addIssue(makeArgsIssue(args, e));\n throw error;\n });\n const result = await Reflect.apply(fn, this, parsedArgs);\n const parsedReturns = await me._def.returns._def.type\n .parseAsync(result, params)\n .catch((e) => {\n error.addIssue(makeReturnsIssue(result, e));\n throw error;\n });\n return parsedReturns;\n });\n }\n else {\n // Would love a way to avoid disabling this rule, but we need\n // an alias (using an arrow function was what caused 2651).\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const me = this;\n return OK(function (...args) {\n const parsedArgs = me._def.args.safeParse(args, params);\n if (!parsedArgs.success) {\n throw new ZodError([makeArgsIssue(args, parsedArgs.error)]);\n }\n const result = Reflect.apply(fn, this, parsedArgs.data);\n const parsedReturns = me._def.returns.safeParse(result, params);\n if (!parsedReturns.success) {\n throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]);\n }\n return parsedReturns.data;\n });\n }\n }\n parameters() {\n return this._def.args;\n }\n returnType() {\n return this._def.returns;\n }\n args(...items) {\n return new ZodFunction({\n ...this._def,\n args: ZodTuple.create(items).rest(ZodUnknown.create()),\n });\n }\n returns(returnType) {\n return new ZodFunction({\n ...this._def,\n returns: returnType,\n });\n }\n implement(func) {\n const validatedFunc = this.parse(func);\n return validatedFunc;\n }\n strictImplement(func) {\n const validatedFunc = this.parse(func);\n return validatedFunc;\n }\n static create(args, returns, params) {\n return new ZodFunction({\n args: (args ? args : ZodTuple.create([]).rest(ZodUnknown.create())),\n returns: returns || ZodUnknown.create(),\n typeName: ZodFirstPartyTypeKind.ZodFunction,\n ...processCreateParams(params),\n });\n }\n}\nexport class ZodLazy extends ZodType {\n get schema() {\n return this._def.getter();\n }\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n const lazySchema = this._def.getter();\n return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx });\n }\n}\nZodLazy.create = (getter, params) => {\n return new ZodLazy({\n getter: getter,\n typeName: ZodFirstPartyTypeKind.ZodLazy,\n ...processCreateParams(params),\n });\n};\nexport class ZodLiteral extends ZodType {\n _parse(input) {\n if (input.data !== this._def.value) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n received: ctx.data,\n code: ZodIssueCode.invalid_literal,\n expected: this._def.value,\n });\n return INVALID;\n }\n return { status: \"valid\", value: input.data };\n }\n get value() {\n return this._def.value;\n }\n}\nZodLiteral.create = (value, params) => {\n return new ZodLiteral({\n value: value,\n typeName: ZodFirstPartyTypeKind.ZodLiteral,\n ...processCreateParams(params),\n });\n};\nfunction createZodEnum(values, params) {\n return new ZodEnum({\n values,\n typeName: ZodFirstPartyTypeKind.ZodEnum,\n ...processCreateParams(params),\n });\n}\nexport class ZodEnum extends ZodType {\n _parse(input) {\n if (typeof input.data !== \"string\") {\n const ctx = this._getOrReturnCtx(input);\n const expectedValues = this._def.values;\n addIssueToContext(ctx, {\n expected: util.joinValues(expectedValues),\n received: ctx.parsedType,\n code: ZodIssueCode.invalid_type,\n });\n return INVALID;\n }\n if (!this._cache) {\n this._cache = new Set(this._def.values);\n }\n if (!this._cache.has(input.data)) {\n const ctx = this._getOrReturnCtx(input);\n const expectedValues = this._def.values;\n addIssueToContext(ctx, {\n received: ctx.data,\n code: ZodIssueCode.invalid_enum_value,\n options: expectedValues,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n get options() {\n return this._def.values;\n }\n get enum() {\n const enumValues = {};\n for (const val of this._def.values) {\n enumValues[val] = val;\n }\n return enumValues;\n }\n get Values() {\n const enumValues = {};\n for (const val of this._def.values) {\n enumValues[val] = val;\n }\n return enumValues;\n }\n get Enum() {\n const enumValues = {};\n for (const val of this._def.values) {\n enumValues[val] = val;\n }\n return enumValues;\n }\n extract(values, newDef = this._def) {\n return ZodEnum.create(values, {\n ...this._def,\n ...newDef,\n });\n }\n exclude(values, newDef = this._def) {\n return ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), {\n ...this._def,\n ...newDef,\n });\n }\n}\nZodEnum.create = createZodEnum;\nexport class ZodNativeEnum extends ZodType {\n _parse(input) {\n const nativeEnumValues = util.getValidEnumValues(this._def.values);\n const ctx = this._getOrReturnCtx(input);\n if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) {\n const expectedValues = util.objectValues(nativeEnumValues);\n addIssueToContext(ctx, {\n expected: util.joinValues(expectedValues),\n received: ctx.parsedType,\n code: ZodIssueCode.invalid_type,\n });\n return INVALID;\n }\n if (!this._cache) {\n this._cache = new Set(util.getValidEnumValues(this._def.values));\n }\n if (!this._cache.has(input.data)) {\n const expectedValues = util.objectValues(nativeEnumValues);\n addIssueToContext(ctx, {\n received: ctx.data,\n code: ZodIssueCode.invalid_enum_value,\n options: expectedValues,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n get enum() {\n return this._def.values;\n }\n}\nZodNativeEnum.create = (values, params) => {\n return new ZodNativeEnum({\n values: values,\n typeName: ZodFirstPartyTypeKind.ZodNativeEnum,\n ...processCreateParams(params),\n });\n};\nexport class ZodPromise extends ZodType {\n unwrap() {\n return this._def.type;\n }\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.promise,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data);\n return OK(promisified.then((data) => {\n return this._def.type.parseAsync(data, {\n path: ctx.path,\n errorMap: ctx.common.contextualErrorMap,\n });\n }));\n }\n}\nZodPromise.create = (schema, params) => {\n return new ZodPromise({\n type: schema,\n typeName: ZodFirstPartyTypeKind.ZodPromise,\n ...processCreateParams(params),\n });\n};\nexport class ZodEffects extends ZodType {\n innerType() {\n return this._def.schema;\n }\n sourceType() {\n return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects\n ? this._def.schema.sourceType()\n : this._def.schema;\n }\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n const effect = this._def.effect || null;\n const checkCtx = {\n addIssue: (arg) => {\n addIssueToContext(ctx, arg);\n if (arg.fatal) {\n status.abort();\n }\n else {\n status.dirty();\n }\n },\n get path() {\n return ctx.path;\n },\n };\n checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx);\n if (effect.type === \"preprocess\") {\n const processed = effect.transform(ctx.data, checkCtx);\n if (ctx.common.async) {\n return Promise.resolve(processed).then(async (processed) => {\n if (status.value === \"aborted\")\n return INVALID;\n const result = await this._def.schema._parseAsync({\n data: processed,\n path: ctx.path,\n parent: ctx,\n });\n if (result.status === \"aborted\")\n return INVALID;\n if (result.status === \"dirty\")\n return DIRTY(result.value);\n if (status.value === \"dirty\")\n return DIRTY(result.value);\n return result;\n });\n }\n else {\n if (status.value === \"aborted\")\n return INVALID;\n const result = this._def.schema._parseSync({\n data: processed,\n path: ctx.path,\n parent: ctx,\n });\n if (result.status === \"aborted\")\n return INVALID;\n if (result.status === \"dirty\")\n return DIRTY(result.value);\n if (status.value === \"dirty\")\n return DIRTY(result.value);\n return result;\n }\n }\n if (effect.type === \"refinement\") {\n const executeRefinement = (acc) => {\n const result = effect.refinement(acc, checkCtx);\n if (ctx.common.async) {\n return Promise.resolve(result);\n }\n if (result instanceof Promise) {\n throw new Error(\"Async refinement encountered during synchronous parse operation. Use .parseAsync instead.\");\n }\n return acc;\n };\n if (ctx.common.async === false) {\n const inner = this._def.schema._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n if (inner.status === \"aborted\")\n return INVALID;\n if (inner.status === \"dirty\")\n status.dirty();\n // return value is ignored\n executeRefinement(inner.value);\n return { status: status.value, value: inner.value };\n }\n else {\n return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => {\n if (inner.status === \"aborted\")\n return INVALID;\n if (inner.status === \"dirty\")\n status.dirty();\n return executeRefinement(inner.value).then(() => {\n return { status: status.value, value: inner.value };\n });\n });\n }\n }\n if (effect.type === \"transform\") {\n if (ctx.common.async === false) {\n const base = this._def.schema._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n if (!isValid(base))\n return INVALID;\n const result = effect.transform(base.value, checkCtx);\n if (result instanceof Promise) {\n throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);\n }\n return { status: status.value, value: result };\n }\n else {\n return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => {\n if (!isValid(base))\n return INVALID;\n return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({\n status: status.value,\n value: result,\n }));\n });\n }\n }\n util.assertNever(effect);\n }\n}\nZodEffects.create = (schema, effect, params) => {\n return new ZodEffects({\n schema,\n typeName: ZodFirstPartyTypeKind.ZodEffects,\n effect,\n ...processCreateParams(params),\n });\n};\nZodEffects.createWithPreprocess = (preprocess, schema, params) => {\n return new ZodEffects({\n schema,\n effect: { type: \"preprocess\", transform: preprocess },\n typeName: ZodFirstPartyTypeKind.ZodEffects,\n ...processCreateParams(params),\n });\n};\nexport { ZodEffects as ZodTransformer };\nexport class ZodOptional extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType === ZodParsedType.undefined) {\n return OK(undefined);\n }\n return this._def.innerType._parse(input);\n }\n unwrap() {\n return this._def.innerType;\n }\n}\nZodOptional.create = (type, params) => {\n return new ZodOptional({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodOptional,\n ...processCreateParams(params),\n });\n};\nexport class ZodNullable extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType === ZodParsedType.null) {\n return OK(null);\n }\n return this._def.innerType._parse(input);\n }\n unwrap() {\n return this._def.innerType;\n }\n}\nZodNullable.create = (type, params) => {\n return new ZodNullable({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodNullable,\n ...processCreateParams(params),\n });\n};\nexport class ZodDefault extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n let data = ctx.data;\n if (ctx.parsedType === ZodParsedType.undefined) {\n data = this._def.defaultValue();\n }\n return this._def.innerType._parse({\n data,\n path: ctx.path,\n parent: ctx,\n });\n }\n removeDefault() {\n return this._def.innerType;\n }\n}\nZodDefault.create = (type, params) => {\n return new ZodDefault({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodDefault,\n defaultValue: typeof params.default === \"function\" ? params.default : () => params.default,\n ...processCreateParams(params),\n });\n};\nexport class ZodCatch extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n // newCtx is used to not collect issues from inner types in ctx\n const newCtx = {\n ...ctx,\n common: {\n ...ctx.common,\n issues: [],\n },\n };\n const result = this._def.innerType._parse({\n data: newCtx.data,\n path: newCtx.path,\n parent: {\n ...newCtx,\n },\n });\n if (isAsync(result)) {\n return result.then((result) => {\n return {\n status: \"valid\",\n value: result.status === \"valid\"\n ? result.value\n : this._def.catchValue({\n get error() {\n return new ZodError(newCtx.common.issues);\n },\n input: newCtx.data,\n }),\n };\n });\n }\n else {\n return {\n status: \"valid\",\n value: result.status === \"valid\"\n ? result.value\n : this._def.catchValue({\n get error() {\n return new ZodError(newCtx.common.issues);\n },\n input: newCtx.data,\n }),\n };\n }\n }\n removeCatch() {\n return this._def.innerType;\n }\n}\nZodCatch.create = (type, params) => {\n return new ZodCatch({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodCatch,\n catchValue: typeof params.catch === \"function\" ? params.catch : () => params.catch,\n ...processCreateParams(params),\n });\n};\nexport class ZodNaN extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.nan) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.nan,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return { status: \"valid\", value: input.data };\n }\n}\nZodNaN.create = (params) => {\n return new ZodNaN({\n typeName: ZodFirstPartyTypeKind.ZodNaN,\n ...processCreateParams(params),\n });\n};\nexport const BRAND = Symbol(\"zod_brand\");\nexport class ZodBranded extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n const data = ctx.data;\n return this._def.type._parse({\n data,\n path: ctx.path,\n parent: ctx,\n });\n }\n unwrap() {\n return this._def.type;\n }\n}\nexport class ZodPipeline extends ZodType {\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.common.async) {\n const handleAsync = async () => {\n const inResult = await this._def.in._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n if (inResult.status === \"aborted\")\n return INVALID;\n if (inResult.status === \"dirty\") {\n status.dirty();\n return DIRTY(inResult.value);\n }\n else {\n return this._def.out._parseAsync({\n data: inResult.value,\n path: ctx.path,\n parent: ctx,\n });\n }\n };\n return handleAsync();\n }\n else {\n const inResult = this._def.in._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n if (inResult.status === \"aborted\")\n return INVALID;\n if (inResult.status === \"dirty\") {\n status.dirty();\n return {\n status: \"dirty\",\n value: inResult.value,\n };\n }\n else {\n return this._def.out._parseSync({\n data: inResult.value,\n path: ctx.path,\n parent: ctx,\n });\n }\n }\n }\n static create(a, b) {\n return new ZodPipeline({\n in: a,\n out: b,\n typeName: ZodFirstPartyTypeKind.ZodPipeline,\n });\n }\n}\nexport class ZodReadonly extends ZodType {\n _parse(input) {\n const result = this._def.innerType._parse(input);\n const freeze = (data) => {\n if (isValid(data)) {\n data.value = Object.freeze(data.value);\n }\n return data;\n };\n return isAsync(result) ? result.then((data) => freeze(data)) : freeze(result);\n }\n unwrap() {\n return this._def.innerType;\n }\n}\nZodReadonly.create = (type, params) => {\n return new ZodReadonly({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodReadonly,\n ...processCreateParams(params),\n });\n};\n////////////////////////////////////////\n////////////////////////////////////////\n////////// //////////\n////////// z.custom //////////\n////////// //////////\n////////////////////////////////////////\n////////////////////////////////////////\nfunction cleanParams(params, data) {\n const p = typeof params === \"function\" ? params(data) : typeof params === \"string\" ? { message: params } : params;\n const p2 = typeof p === \"string\" ? { message: p } : p;\n return p2;\n}\nexport function custom(check, _params = {}, \n/**\n * @deprecated\n *\n * Pass `fatal` into the params object instead:\n *\n * ```ts\n * z.string().custom((val) => val.length > 5, { fatal: false })\n * ```\n *\n */\nfatal) {\n if (check)\n return ZodAny.create().superRefine((data, ctx) => {\n const r = check(data);\n if (r instanceof Promise) {\n return r.then((r) => {\n if (!r) {\n const params = cleanParams(_params, data);\n const _fatal = params.fatal ?? fatal ?? true;\n ctx.addIssue({ code: \"custom\", ...params, fatal: _fatal });\n }\n });\n }\n if (!r) {\n const params = cleanParams(_params, data);\n const _fatal = params.fatal ?? fatal ?? true;\n ctx.addIssue({ code: \"custom\", ...params, fatal: _fatal });\n }\n return;\n });\n return ZodAny.create();\n}\nexport { ZodType as Schema, ZodType as ZodSchema };\nexport const late = {\n object: ZodObject.lazycreate,\n};\nexport var ZodFirstPartyTypeKind;\n(function (ZodFirstPartyTypeKind) {\n ZodFirstPartyTypeKind[\"ZodString\"] = \"ZodString\";\n ZodFirstPartyTypeKind[\"ZodNumber\"] = \"ZodNumber\";\n ZodFirstPartyTypeKind[\"ZodNaN\"] = \"ZodNaN\";\n ZodFirstPartyTypeKind[\"ZodBigInt\"] = \"ZodBigInt\";\n ZodFirstPartyTypeKind[\"ZodBoolean\"] = \"ZodBoolean\";\n ZodFirstPartyTypeKind[\"ZodDate\"] = \"ZodDate\";\n ZodFirstPartyTypeKind[\"ZodSymbol\"] = \"ZodSymbol\";\n ZodFirstPartyTypeKind[\"ZodUndefined\"] = \"ZodUndefined\";\n ZodFirstPartyTypeKind[\"ZodNull\"] = \"ZodNull\";\n ZodFirstPartyTypeKind[\"ZodAny\"] = \"ZodAny\";\n ZodFirstPartyTypeKind[\"ZodUnknown\"] = \"ZodUnknown\";\n ZodFirstPartyTypeKind[\"ZodNever\"] = \"ZodNever\";\n ZodFirstPartyTypeKind[\"ZodVoid\"] = \"ZodVoid\";\n ZodFirstPartyTypeKind[\"ZodArray\"] = \"ZodArray\";\n ZodFirstPartyTypeKind[\"ZodObject\"] = \"ZodObject\";\n ZodFirstPartyTypeKind[\"ZodUnion\"] = \"ZodUnion\";\n ZodFirstPartyTypeKind[\"ZodDiscriminatedUnion\"] = \"ZodDiscriminatedUnion\";\n ZodFirstPartyTypeKind[\"ZodIntersection\"] = \"ZodIntersection\";\n ZodFirstPartyTypeKind[\"ZodTuple\"] = \"ZodTuple\";\n ZodFirstPartyTypeKind[\"ZodRecord\"] = \"ZodRecord\";\n ZodFirstPartyTypeKind[\"ZodMap\"] = \"ZodMap\";\n ZodFirstPartyTypeKind[\"ZodSet\"] = \"ZodSet\";\n ZodFirstPartyTypeKind[\"ZodFunction\"] = \"ZodFunction\";\n ZodFirstPartyTypeKind[\"ZodLazy\"] = \"ZodLazy\";\n ZodFirstPartyTypeKind[\"ZodLiteral\"] = \"ZodLiteral\";\n ZodFirstPartyTypeKind[\"ZodEnum\"] = \"ZodEnum\";\n ZodFirstPartyTypeKind[\"ZodEffects\"] = \"ZodEffects\";\n ZodFirstPartyTypeKind[\"ZodNativeEnum\"] = \"ZodNativeEnum\";\n ZodFirstPartyTypeKind[\"ZodOptional\"] = \"ZodOptional\";\n ZodFirstPartyTypeKind[\"ZodNullable\"] = \"ZodNullable\";\n ZodFirstPartyTypeKind[\"ZodDefault\"] = \"ZodDefault\";\n ZodFirstPartyTypeKind[\"ZodCatch\"] = \"ZodCatch\";\n ZodFirstPartyTypeKind[\"ZodPromise\"] = \"ZodPromise\";\n ZodFirstPartyTypeKind[\"ZodBranded\"] = \"ZodBranded\";\n ZodFirstPartyTypeKind[\"ZodPipeline\"] = \"ZodPipeline\";\n ZodFirstPartyTypeKind[\"ZodReadonly\"] = \"ZodReadonly\";\n})(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));\n// requires TS 4.4+\nclass Class {\n constructor(..._) { }\n}\nconst instanceOfType = (\n// const instanceOfType = <T extends new (...args: any[]) => any>(\ncls, params = {\n message: `Input not instance of ${cls.name}`,\n}) => custom((data) => data instanceof cls, params);\nconst stringType = ZodString.create;\nconst numberType = ZodNumber.create;\nconst nanType = ZodNaN.create;\nconst bigIntType = ZodBigInt.create;\nconst booleanType = ZodBoolean.create;\nconst dateType = ZodDate.create;\nconst symbolType = ZodSymbol.create;\nconst undefinedType = ZodUndefined.create;\nconst nullType = ZodNull.create;\nconst anyType = ZodAny.create;\nconst unknownType = ZodUnknown.create;\nconst neverType = ZodNever.create;\nconst voidType = ZodVoid.create;\nconst arrayType = ZodArray.create;\nconst objectType = ZodObject.create;\nconst strictObjectType = ZodObject.strictCreate;\nconst unionType = ZodUnion.create;\nconst discriminatedUnionType = ZodDiscriminatedUnion.create;\nconst intersectionType = ZodIntersection.create;\nconst tupleType = ZodTuple.create;\nconst recordType = ZodRecord.create;\nconst mapType = ZodMap.create;\nconst setType = ZodSet.create;\nconst functionType = ZodFunction.create;\nconst lazyType = ZodLazy.create;\nconst literalType = ZodLiteral.create;\nconst enumType = ZodEnum.create;\nconst nativeEnumType = ZodNativeEnum.create;\nconst promiseType = ZodPromise.create;\nconst effectsType = ZodEffects.create;\nconst optionalType = ZodOptional.create;\nconst nullableType = ZodNullable.create;\nconst preprocessType = ZodEffects.createWithPreprocess;\nconst pipelineType = ZodPipeline.create;\nconst ostring = () => stringType().optional();\nconst onumber = () => numberType().optional();\nconst oboolean = () => booleanType().optional();\nexport const coerce = {\n string: ((arg) => ZodString.create({ ...arg, coerce: true })),\n number: ((arg) => ZodNumber.create({ ...arg, coerce: true })),\n boolean: ((arg) => ZodBoolean.create({\n ...arg,\n coerce: true,\n })),\n bigint: ((arg) => ZodBigInt.create({ ...arg, coerce: true })),\n date: ((arg) => ZodDate.create({ ...arg, coerce: true })),\n};\nexport { anyType as any, arrayType as array, bigIntType as bigint, booleanType as boolean, dateType as date, discriminatedUnionType as discriminatedUnion, effectsType as effect, enumType as enum, functionType as function, instanceOfType as instanceof, intersectionType as intersection, lazyType as lazy, literalType as literal, mapType as map, nanType as nan, nativeEnumType as nativeEnum, neverType as never, nullType as null, nullableType as nullable, numberType as number, objectType as object, oboolean, onumber, optionalType as optional, ostring, pipelineType as pipeline, preprocessType as preprocess, promiseType as promise, recordType as record, setType as set, strictObjectType as strictObject, stringType as string, symbolType as symbol, effectsType as transformer, tupleType as tuple, undefinedType as undefined, unionType as union, unknownType as unknown, voidType as void, };\nexport const NEVER = INVALID;\n", "import { z } from \"zod\";\n\nexport const FunctionCallSchema = z.object({\n name: z.string(),\n arguments: z.string(),\n});\n\nexport const ToolCallSchema = z.object({\n id: z.string(),\n type: z.literal(\"function\"),\n function: FunctionCallSchema,\n encryptedValue: z.string().optional(),\n});\n\nexport const BaseMessageSchema = z.object({\n id: z.string(),\n role: z.string(),\n content: z.string().optional(),\n name: z.string().optional(),\n encryptedValue: z.string().optional(),\n});\n\nexport const TextInputContentSchema = z.object({\n type: z.literal(\"text\"),\n text: z.string(),\n});\n\nexport const InputContentDataSourceSchema = z.object({\n type: z.literal(\"data\"),\n value: z.string(),\n mimeType: z.string(),\n});\n\nexport const InputContentUrlSourceSchema = z.object({\n type: z.literal(\"url\"),\n value: z.string(),\n mimeType: z.string().optional(),\n});\n\nexport const InputContentSourceSchema = z.discriminatedUnion(\"type\", [\n InputContentDataSourceSchema,\n InputContentUrlSourceSchema,\n]);\n\nexport const ImageInputContentSchema = z.object({\n type: z.literal(\"image\"),\n source: InputContentSourceSchema,\n metadata: z.unknown().optional(),\n});\n\nexport const AudioInputContentSchema = z.object({\n type: z.literal(\"audio\"),\n source: InputContentSourceSchema,\n metadata: z.unknown().optional(),\n});\n\nexport const VideoInputContentSchema = z.object({\n type: z.literal(\"video\"),\n source: InputContentSourceSchema,\n metadata: z.unknown().optional(),\n});\n\nexport const DocumentInputContentSchema = z.object({\n type: z.literal(\"document\"),\n source: InputContentSourceSchema,\n metadata: z.unknown().optional(),\n});\n\nexport const ImageInputPartSchema = ImageInputContentSchema;\nexport const AudioInputPartSchema = AudioInputContentSchema;\nexport const VideoInputPartSchema = VideoInputContentSchema;\nexport const DocumentInputPartSchema = DocumentInputContentSchema;\n\nconst LegacyBinaryInputContentObjectSchema = z.object({\n type: z.literal(\"binary\"),\n mimeType: z.string(),\n id: z.string().optional(),\n url: z.string().optional(),\n data: z.string().optional(),\n filename: z.string().optional(),\n});\n\nconst ensureBinaryPayload = (\n value: { id?: string; url?: string; data?: string },\n ctx: z.RefinementCtx,\n) => {\n if (!value.id && !value.url && !value.data) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: \"BinaryInputContent requires at least one of id, url, or data.\",\n path: [\"id\"],\n });\n }\n};\n\nexport const BinaryInputContentSchema = LegacyBinaryInputContentObjectSchema.superRefine(\n (value, ctx) => {\n ensureBinaryPayload(value, ctx);\n },\n);\n\nconst InputContentBaseSchema = z.discriminatedUnion(\"type\", [\n TextInputContentSchema,\n ImageInputContentSchema,\n AudioInputContentSchema,\n VideoInputContentSchema,\n DocumentInputContentSchema,\n LegacyBinaryInputContentObjectSchema,\n]);\n\nexport const InputContentSchema = InputContentBaseSchema.superRefine((value, ctx) => {\n if (value.type === \"binary\") {\n ensureBinaryPayload(value, ctx);\n }\n});\n\nexport const DeveloperMessageSchema = BaseMessageSchema.extend({\n role: z.literal(\"developer\"),\n content: z.string(),\n});\n\nexport const SystemMessageSchema = BaseMessageSchema.extend({\n role: z.literal(\"system\"),\n content: z.string(),\n});\n\nexport const AssistantMessageSchema = BaseMessageSchema.extend({\n role: z.literal(\"assistant\"),\n content: z.string().optional(),\n toolCalls: z.array(ToolCallSchema).optional(),\n});\n\nexport const UserMessageSchema = BaseMessageSchema.extend({\n role: z.literal(\"user\"),\n content: z.union([z.string(), z.array(InputContentSchema)]),\n});\n\nexport const ToolMessageSchema = z.object({\n id: z.string(),\n content: z.string(),\n role: z.literal(\"tool\"),\n toolCallId: z.string(),\n error: z.string().optional(),\n encryptedValue: z.string().optional(),\n});\n\nexport const ActivityMessageSchema = z.object({\n id: z.string(),\n role: z.literal(\"activity\"),\n activityType: z.string(),\n content: z.record(z.any()),\n});\n\nexport const ReasoningMessageSchema = z.object({\n id: z.string(),\n role: z.literal(\"reasoning\"),\n content: z.string(),\n encryptedValue: z.string().optional(),\n});\n\nexport const MessageSchema = z.discriminatedUnion(\"role\", [\n DeveloperMessageSchema,\n SystemMessageSchema,\n AssistantMessageSchema,\n UserMessageSchema,\n ToolMessageSchema,\n ActivityMessageSchema,\n ReasoningMessageSchema,\n]);\n\nexport const RoleSchema = z.union([\n z.literal(\"developer\"),\n z.literal(\"system\"),\n z.literal(\"assistant\"),\n z.literal(\"user\"),\n z.literal(\"tool\"),\n z.literal(\"activity\"),\n z.literal(\"reasoning\"),\n]);\n\nexport const ContextSchema = z.object({\n description: z.string(),\n value: z.string(),\n});\n\nexport const ToolSchema = z.object({\n name: z.string(),\n description: z.string(),\n parameters: z.any(), // JSON Schema for the tool parameters\n metadata: z.record(z.any()).optional(), // Arbitrary tool metadata (e.g. a2ui schema)\n});\n\nexport const InterruptSchema = z.object({\n id: z.string(),\n reason: z.string(),\n message: z.string().optional(),\n toolCallId: z.string().optional(),\n responseSchema: z.record(z.any()).optional(),\n expiresAt: z.string().optional(),\n metadata: z.record(z.any()).optional(),\n});\n\nexport const ResumeEntrySchema = z.object({\n interruptId: z.string(),\n status: z.enum([\"resolved\", \"cancelled\"]),\n payload: z.any().optional(),\n});\n\nexport const RunAgentInputSchema = z.object({\n threadId: z.string(),\n runId: z.string(),\n parentRunId: z.string().optional(),\n state: z.any(),\n messages: z.array(MessageSchema),\n tools: z.array(ToolSchema),\n context: z.array(ContextSchema),\n forwardedProps: z.any(),\n resume: z.array(ResumeEntrySchema).optional(),\n});\n\nexport const StateSchema = z.any();\n\nexport type ToolCall = z.infer<typeof ToolCallSchema>;\nexport type FunctionCall = z.infer<typeof FunctionCallSchema>;\nexport type TextInputContent = z.infer<typeof TextInputContentSchema>;\nexport type InputContentDataSource = z.infer<typeof InputContentDataSourceSchema>;\nexport type InputContentUrlSource = z.infer<typeof InputContentUrlSourceSchema>;\nexport type InputContentSource = z.infer<typeof InputContentSourceSchema>;\nexport type ImageInputContent = z.infer<typeof ImageInputContentSchema>;\nexport type AudioInputContent = z.infer<typeof AudioInputContentSchema>;\nexport type VideoInputContent = z.infer<typeof VideoInputContentSchema>;\nexport type DocumentInputContent = z.infer<typeof DocumentInputContentSchema>;\nexport type ImageInputPart = ImageInputContent;\nexport type AudioInputPart = AudioInputContent;\nexport type VideoInputPart = VideoInputContent;\nexport type DocumentInputPart = DocumentInputContent;\nexport type BinaryInputContent = z.infer<typeof BinaryInputContentSchema>;\nexport type InputContent = z.infer<typeof InputContentSchema>;\nexport type InputContentPart = z.infer<typeof InputContentSchema>;\nexport type DeveloperMessage = z.infer<typeof DeveloperMessageSchema>;\nexport type SystemMessage = z.infer<typeof SystemMessageSchema>;\nexport type AssistantMessage = z.infer<typeof AssistantMessageSchema>;\nexport type UserMessage = z.infer<typeof UserMessageSchema>;\nexport type ToolMessage = z.infer<typeof ToolMessageSchema>;\nexport type ActivityMessage = z.infer<typeof ActivityMessageSchema>;\nexport type ReasoningMessage = z.infer<typeof ReasoningMessageSchema>;\nexport type Message = z.infer<typeof MessageSchema>;\nexport type Context = z.infer<typeof ContextSchema>;\nexport type Tool = z.infer<typeof ToolSchema>;\nexport type RunAgentInput = z.infer<typeof RunAgentInputSchema>;\nexport type State = z.infer<typeof StateSchema>;\nexport type Role = z.infer<typeof RoleSchema>;\nexport type Interrupt = z.infer<typeof InterruptSchema>;\nexport type ResumeEntry = z.infer<typeof ResumeEntrySchema>;\nexport type ResumeStatus = z.infer<typeof ResumeEntrySchema>[\"status\"];\n\nexport class AGUIError extends Error {\n constructor(message: string) {\n super(message);\n }\n}\n\nexport class AGUIConnectNotImplementedError extends AGUIError {\n constructor() {\n super(\"Connect not implemented. This method is not supported by the current agent.\");\n }\n}\n", "import { z } from \"zod\";\nimport { ToolSchema } from \"./types\";\n\n/** Describes a sub-agent that can be invoked by a parent agent. */\nexport const SubAgentInfoSchema = z.object({\n /** Unique name or identifier of the sub-agent. */\n name: z.string(),\n /** What this sub-agent specializes in. Helps clients build agent selection UIs. */\n description: z.string().optional(),\n});\n\n/**\n * Basic metadata about the agent. Useful for discovery UIs, agent marketplaces,\n * and debugging. Set these when you want clients to display agent information\n * or when multiple agents are available and users need to pick one.\n */\nexport const IdentityCapabilitiesSchema = z.object({\n /** Human-readable name shown in UIs and agent selectors. */\n name: z.string().optional(),\n /** The framework or platform powering this agent (e.g., \"langgraph\", \"mastra\", \"crewai\"). */\n type: z.string().optional(),\n /** What this agent does — helps users and routing logic decide when to use it. */\n description: z.string().optional(),\n /** Semantic version of the agent (e.g., \"1.2.0\"). Useful for compatibility checks. */\n version: z.string().optional(),\n /** Organization or team that maintains this agent. */\n provider: z.string().optional(),\n /** URL to the agent's documentation or homepage. */\n documentationUrl: z.string().optional(),\n /** Arbitrary key-value pairs for integration-specific identity info. */\n metadata: z.record(z.unknown()).optional(),\n});\n\n/**\n * Declares which transport mechanisms the agent supports. Clients use this\n * to pick the best connection strategy. Only set flags to `true` for transports\n * your agent actually handles — omit or set `false` for unsupported ones.\n */\nexport const TransportCapabilitiesSchema = z.object({\n /** Set `true` if the agent streams responses via SSE. Most agents enable this. */\n streaming: z.boolean().optional(),\n /** Set `true` if the agent accepts persistent WebSocket connections. */\n websocket: z.boolean().optional(),\n /** Set `true` if the agent supports the AG-UI binary protocol (protobuf over HTTP). */\n httpBinary: z.boolean().optional(),\n /** Set `true` if the agent can send async updates via webhooks after a run finishes. */\n pushNotifications: z.boolean().optional(),\n /** Set `true` if the agent supports resuming interrupted streams via sequence numbers. */\n resumable: z.boolean().optional(),\n});\n\n/**\n * Tool calling capabilities. Distinguishes between tools the agent itself provides\n * (listed in `items`) and tools the client passes at runtime via `RunAgentInput.tools`.\n * Enable this when your agent can call functions, search the web, execute code, etc.\n */\nexport const ToolsCapabilitiesSchema = z.object({\n /** Set `true` if the agent can make tool calls at all. Set `false` to explicitly\n * signal tool calling is disabled even if items are present. */\n supported: z.boolean().optional(),\n /** The tools this agent provides on its own (full JSON Schema definitions).\n * These are distinct from client-provided tools passed in `RunAgentInput.tools`. */\n items: z.array(ToolSchema).optional(),\n /** Set `true` if the agent can invoke multiple tools concurrently within a single step. */\n parallelCalls: z.boolean().optional(),\n /** Set `true` if the agent accepts and uses tools provided by the client at runtime. */\n clientProvided: z.boolean().optional(),\n});\n\n/**\n * Output format support. Enable `structuredOutput` when your agent can return\n * responses conforming to a JSON schema, which is useful for programmatic consumption.\n */\nexport const OutputCapabilitiesSchema = z.object({\n /** Set `true` if the agent can produce structured JSON output matching a provided schema. */\n structuredOutput: z.boolean().optional(),\n /** MIME types the agent can produce (e.g., `[\"text/plain\", \"application/json\"]`).\n * Omit if the agent only produces plain text. */\n supportedMimeTypes: z.array(z.string()).optional(),\n});\n\n/**\n * State and memory management capabilities. These tell the client how the agent\n * handles shared state and whether conversation context persists across runs.\n */\nexport const StateCapabilitiesSchema = z.object({\n /** Set `true` if the agent emits `STATE_SNAPSHOT` events (full state replacement). */\n snapshots: z.boolean().optional(),\n /** Set `true` if the agent emits `STATE_DELTA` events (JSON Patch incremental updates). */\n deltas: z.boolean().optional(),\n /** Set `true` if the agent has long-term memory beyond the current thread\n * (e.g., vector store, knowledge base, or cross-session recall). */\n memory: z.boolean().optional(),\n /** Set `true` if state is preserved across multiple runs within the same thread.\n * When `false`, state resets on each run. */\n persistentState: z.boolean().optional(),\n});\n\n/**\n * Multi-agent coordination capabilities. Enable these when your agent can\n * orchestrate or hand off work to other agents.\n */\nexport const MultiAgentCapabilitiesSchema = z.object({\n /** Set `true` if the agent participates in any form of multi-agent coordination. */\n supported: z.boolean().optional(),\n /** Set `true` if the agent can delegate subtasks to other agents while retaining control. */\n delegation: z.boolean().optional(),\n /** Set `true` if the agent can transfer the conversation entirely to another agent. */\n handoffs: z.boolean().optional(),\n /** List of sub-agents this agent can invoke. Helps clients build agent selection UIs. */\n subAgents: z.array(SubAgentInfoSchema).optional(),\n});\n\n/**\n * Reasoning and thinking capabilities. Enable these when your agent exposes its\n * internal thought process (e.g., chain-of-thought, extended thinking).\n */\nexport const ReasoningCapabilitiesSchema = z.object({\n /** Set `true` if the agent produces reasoning/thinking tokens visible to the client. */\n supported: z.boolean().optional(),\n /** Set `true` if reasoning tokens are streamed incrementally (vs. returned all at once). */\n streaming: z.boolean().optional(),\n /** Set `true` if reasoning content is encrypted (zero-data-retention mode).\n * Clients should expect opaque `encryptedValue` fields instead of readable content. */\n encrypted: z.boolean().optional(),\n});\n\n/**\n * Modalities the agent can accept as input. Clients use this to show/hide\n * file upload buttons, audio recorders, image pickers, etc.\n */\nexport const MultimodalInputCapabilitiesSchema = z.object({\n /** Set `true` if the agent can process image inputs (e.g., screenshots, photos). */\n image: z.boolean().optional(),\n /** Set `true` if the agent can process audio inputs (speech, recordings). */\n audio: z.boolean().optional(),\n /** Set `true` if the agent can process video inputs. */\n video: z.boolean().optional(),\n /** Set `true` if the agent can process PDF documents. */\n pdf: z.boolean().optional(),\n /** Set `true` if the agent can process arbitrary file uploads. */\n file: z.boolean().optional(),\n});\n\n/**\n * Modalities the agent can produce as output. Clients use this to anticipate\n * rich content in the agent's response.\n */\nexport const MultimodalOutputCapabilitiesSchema = z.object({\n /** Set `true` if the agent can generate images as part of its response. */\n image: z.boolean().optional(),\n /** Set `true` if the agent can produce audio output (text-to-speech, audio files). */\n audio: z.boolean().optional(),\n});\n\n/**\n * Multimodal input and output support. Organized into `input` and `output`\n * sub-objects so clients can independently query what the agent accepts\n * versus what it produces.\n */\nexport const MultimodalCapabilitiesSchema = z.object({\n /** Modalities the agent can accept as input (images, audio, video, PDFs, files). */\n input: MultimodalInputCapabilitiesSchema.optional(),\n /** Modalities the agent can produce as output (images, audio). */\n output: MultimodalOutputCapabilitiesSchema.optional(),\n});\n\n/**\n * Execution control and limits. Declare these so clients can set expectations\n * about how long or how many steps an agent run might take.\n */\nexport const ExecutionCapabilitiesSchema = z.object({\n /** Set `true` if the agent can execute code (e.g., Python, JavaScript) during a run. */\n codeExecution: z.boolean().optional(),\n /** Set `true` if code execution happens in a sandboxed/isolated environment.\n * Only meaningful when `codeExecution` is `true`. */\n sandboxed: z.boolean().optional(),\n /** Maximum number of tool-call/reasoning iterations the agent will perform per run.\n * Helps clients display progress or set timeout expectations. */\n maxIterations: z.number().optional(),\n /** Maximum wall-clock time (in milliseconds) the agent will run before timing out. */\n maxExecutionTime: z.number().optional(),\n});\n\n/**\n * Human-in-the-loop interaction support. Enable these when your agent can pause\n * execution to request human input, approval, or feedback before continuing.\n */\nexport const HumanInTheLoopCapabilitiesSchema = z.object({\n /** Set `true` if the agent supports any form of human-in-the-loop interaction. */\n supported: z.boolean().optional(),\n /** Set `true` if the agent can pause and request explicit approval before\n * performing sensitive actions (e.g., sending emails, deleting data). */\n approvals: z.boolean().optional(),\n /** Set `true` if the agent allows humans to intervene and modify its plan mid-execution. */\n interventions: z.boolean().optional(),\n /** Set `true` if the agent can incorporate user feedback (thumbs up/down, corrections)\n * to improve its behavior within the current session. */\n feedback: z.boolean().optional(),\n /** Set `true` if the agent participates in the AG-UI interrupt protocol\n * (emits RUN_FINISHED with outcome={ type: \"interrupt\", interrupts: [...] },\n * accepts resume[]). */\n interrupts: z.boolean().optional(),\n /** Set `true` if tool-call interrupts accept editedArgs in the resume payload.\n * Only meaningful when interrupts is true. */\n approveWithEdits: z.boolean().optional(),\n});\n\n/**\n * A typed, categorized snapshot of an agent's current capabilities.\n * Returned by `getCapabilities()` on `AbstractAgent`.\n *\n * All fields are optional — agents only declare what they support.\n * Omitted fields mean the capability is not declared (unknown), not that\n * it's unsupported.\n *\n * The `custom` field is an escape hatch for integration-specific capabilities\n * that don't fit into the standard categories.\n */\nexport const AgentCapabilitiesSchema = z.object({\n /** Agent identity and metadata. */\n identity: IdentityCapabilitiesSchema.optional(),\n /** Supported transport mechanisms (SSE, WebSocket, binary, etc.). */\n transport: TransportCapabilitiesSchema.optional(),\n /** Tools the agent provides and tool calling configuration. */\n tools: ToolsCapabilitiesSchema.optional(),\n /** Output format support (structured output, MIME types). */\n output: OutputCapabilitiesSchema.optional(),\n /** State and memory management (snapshots, deltas, persistence). */\n state: StateCapabilitiesSchema.optional(),\n /** Multi-agent coordination (delegation, handoffs, sub-agents). */\n multiAgent: MultiAgentCapabilitiesSchema.optional(),\n /** Reasoning and thinking support (chain-of-thought, encrypted thinking). */\n reasoning: ReasoningCapabilitiesSchema.optional(),\n /** Multimodal input/output support (images, audio, video, files). */\n multimodal: MultimodalCapabilitiesSchema.optional(),\n /** Execution control and limits (code execution, timeouts, iteration caps). */\n execution: ExecutionCapabilitiesSchema.optional(),\n /** Human-in-the-loop support (approvals, interventions, feedback). */\n humanInTheLoop: HumanInTheLoopCapabilitiesSchema.optional(),\n /** Integration-specific capabilities not covered by the standard categories. */\n custom: z.record(z.unknown()).optional(),\n});\n\n/** Describes a sub-agent that can be invoked by a parent agent. */\nexport type SubAgentInfo = z.infer<typeof SubAgentInfoSchema>;\n/** Agent identity and metadata for discovery UIs, marketplaces, and debugging. */\nexport type IdentityCapabilities = z.infer<typeof IdentityCapabilitiesSchema>;\n/** Supported transport mechanisms (SSE, WebSocket, binary protocol, push notifications). */\nexport type TransportCapabilities = z.infer<typeof TransportCapabilitiesSchema>;\n/** Tool calling support and agent-provided tool definitions. */\nexport type ToolsCapabilities = z.infer<typeof ToolsCapabilitiesSchema>;\n/** Output format support (structured output, MIME types). */\nexport type OutputCapabilities = z.infer<typeof OutputCapabilitiesSchema>;\n/** State and memory management (snapshots, deltas, persistence, long-term memory). */\nexport type StateCapabilities = z.infer<typeof StateCapabilitiesSchema>;\n/** Multi-agent coordination (delegation, handoffs, sub-agent orchestration). */\nexport type MultiAgentCapabilities = z.infer<typeof MultiAgentCapabilitiesSchema>;\n/** Reasoning and thinking visibility (streaming, encrypted chain-of-thought). */\nexport type ReasoningCapabilities = z.infer<typeof ReasoningCapabilitiesSchema>;\n/** Modalities the agent can accept as input (images, audio, video, PDFs, files). */\nexport type MultimodalInputCapabilities = z.infer<typeof MultimodalInputCapabilitiesSchema>;\n/** Modalities the agent can produce as output (images, audio). */\nexport type MultimodalOutputCapabilities = z.infer<typeof MultimodalOutputCapabilitiesSchema>;\n/** Multimodal input/output support (images, audio, video, PDFs, file uploads). */\nexport type MultimodalCapabilities = z.infer<typeof MultimodalCapabilitiesSchema>;\n/** Execution control and limits (code execution, sandboxing, iteration caps, timeouts). */\nexport type ExecutionCapabilities = z.infer<typeof ExecutionCapabilitiesSchema>;\n/** Human-in-the-loop interaction support (approvals, interventions, feedback). */\nexport type HumanInTheLoopCapabilities = z.infer<typeof HumanInTheLoopCapabilitiesSchema>;\n/** A typed, categorized snapshot of an agent's current capabilities. Returned by `getCapabilities()`. */\nexport type AgentCapabilities = z.infer<typeof AgentCapabilitiesSchema>;\n", "import { z } from \"zod\";\nimport { MessageSchema, StateSchema, RunAgentInputSchema, InterruptSchema } from \"./types\";\n\n// Text messages can have any role except \"tool\"\nconst TextMessageRoleSchema = z.union([\n z.literal(\"developer\"),\n z.literal(\"system\"),\n z.literal(\"assistant\"),\n z.literal(\"user\"),\n]);\n\nexport enum EventType {\n TEXT_MESSAGE_START = \"TEXT_MESSAGE_START\",\n TEXT_MESSAGE_CONTENT = \"TEXT_MESSAGE_CONTENT\",\n TEXT_MESSAGE_END = \"TEXT_MESSAGE_END\",\n TEXT_MESSAGE_CHUNK = \"TEXT_MESSAGE_CHUNK\",\n TOOL_CALL_START = \"TOOL_CALL_START\",\n TOOL_CALL_ARGS = \"TOOL_CALL_ARGS\",\n TOOL_CALL_END = \"TOOL_CALL_END\",\n TOOL_CALL_CHUNK = \"TOOL_CALL_CHUNK\",\n TOOL_CALL_RESULT = \"TOOL_CALL_RESULT\",\n /**\n * @deprecated Use REASONING_START instead. Will be removed in 1.0.0.\n */\n THINKING_START = \"THINKING_START\",\n /**\n * @deprecated Use REASONING_END instead. Will be removed in 1.0.0.\n */\n THINKING_END = \"THINKING_END\",\n /**\n * @deprecated Use REASONING_MESSAGE_START instead. Will be removed in 1.0.0.\n */\n THINKING_TEXT_MESSAGE_START = \"THINKING_TEXT_MESSAGE_START\",\n /**\n * @deprecated Use REASONING_MESSAGE_CONTENT instead. Will be removed in 1.0.0.\n */\n THINKING_TEXT_MESSAGE_CONTENT = \"THINKING_TEXT_MESSAGE_CONTENT\",\n /**\n * @deprecated Use REASONING_MESSAGE_END instead. Will be removed in 1.0.0.\n */\n THINKING_TEXT_MESSAGE_END = \"THINKING_TEXT_MESSAGE_END\",\n STATE_SNAPSHOT = \"STATE_SNAPSHOT\",\n STATE_DELTA = \"STATE_DELTA\",\n MESSAGES_SNAPSHOT = \"MESSAGES_SNAPSHOT\",\n ACTIVITY_SNAPSHOT = \"ACTIVITY_SNAPSHOT\",\n ACTIVITY_DELTA = \"ACTIVITY_DELTA\",\n RAW = \"RAW\",\n CUSTOM = \"CUSTOM\",\n RUN_STARTED = \"RUN_STARTED\",\n RUN_FINISHED = \"RUN_FINISHED\",\n RUN_ERROR = \"RUN_ERROR\",\n STEP_STARTED = \"STEP_STARTED\",\n STEP_FINISHED = \"STEP_FINISHED\",\n REASONING_START = \"REASONING_START\",\n REASONING_MESSAGE_START = \"REASONING_MESSAGE_START\",\n REASONING_MESSAGE_CONTENT = \"REASONING_MESSAGE_CONTENT\",\n REASONING_MESSAGE_END = \"REASONING_MESSAGE_END\",\n REASONING_MESSAGE_CHUNK = \"REASONING_MESSAGE_CHUNK\",\n REASONING_END = \"REASONING_END\",\n REASONING_ENCRYPTED_VALUE = \"REASONING_ENCRYPTED_VALUE\",\n}\n\nexport const BaseEventSchema = z\n .object({\n type: z.nativeEnum(EventType),\n timestamp: z.number().optional(),\n rawEvent: z.any().optional(),\n })\n .passthrough();\n\nexport const TextMessageStartEventSchema = BaseEventSchema.extend({\n type: z.literal(EventType.TEXT_MESSAGE_START),\n messageId: z.string(),\n role: TextMessageRoleSchema.default(\"assistant\"),\n name: z.string().optional(),\n});\n\nexport const TextMessageContentEventSchema = BaseEventSchema.extend({\n type: z.literal(EventType.TEXT_MESSAGE_CONTENT),\n messageId: z.string(),\n delta: z.string(),\n});\n\nexport const TextMessageEndEventSchema = BaseEventSchema.extend({\n type: z.literal(EventType.TEXT_MESSAGE_END),\n messageId: z.string(),\n});\n\nexport const TextMessageChunkEventSchema = BaseEventSchema.extend({\n type: z.literal(EventType.TEXT_MESSAGE_CHUNK),\n messageId: z.string().optional(),\n role: TextMessageRoleSchema.optional(),\n delta: z.string().optional(),\n name: z.string().optional(),\n});\n\n/**\n * @deprecated Use ReasoningMessageStartEventSchema instead. Will be removed in 1.0.0.\n */\nexport const ThinkingTextMessageStartEventSchema = BaseEventSchema.extend({\n type: z.literal(EventType.THINKING_TEXT_MESSAGE_START),\n});\n\n/**\n * @deprecated Use ReasoningMessageContentEventSchema instead. Will be removed in 1.0.0.\n */\nexport const ThinkingTextMessageContentEventSchema = TextMessageContentEventSchema.omit({\n messageId: true,\n type: true,\n}).extend({\n type: z.literal(EventType.THINKING_TEXT_MESSAGE_CONTENT),\n});\n\n/**\n * @deprecated Use ReasoningMessageEndEventSchema instead. Will be removed in 1.0.0.\n */\nexport const ThinkingTextMessageEndEventSchema = BaseEventSchema.extend({\n type: z.literal(EventType.THINKING_TEXT_MESSAGE_END),\n});\n\nexport const ToolCallStartEventSchema = BaseEventSchema.extend({\n type: z.literal(EventType.TOOL_CALL_START),\n toolCallId: z.string(),\n toolCallName: z.string(),\n parentMessageId: z.string().optional(),\n});\n\nexport const ToolCallArgsEventSchema = BaseEventSchema.extend({\n type: z.literal(EventType.TOOL_CALL_ARGS),\n toolCallId: z.string(),\n delta: z.string(),\n});\n\nexport const ToolCallEndEventSchema = BaseEventSchema.extend({\n type: z.literal(EventType.TOOL_CALL_END),\n toolCallId: z.string(),\n});\n\nexport const ToolCallResultEventSchema = BaseEventSchema.extend({\n messageId: z.string(),\n type: z.literal(EventType.TOOL_CALL_RESULT),\n toolCallId: z.string(),\n content: z.string(),\n role: z.literal(\"tool\").optional(),\n});\n\nexport const ToolCallChunkEventSchema = BaseEventSchema.extend({\n type: z.literal(EventType.TOOL_CALL_CHUNK),\n toolCallId: z.string().optional(),\n toolCallName: z.string().optional(),\n parentMessageId: z.string().optional(),\n delta: z.string().optional(),\n});\n\n/**\n * @deprecated Use ReasoningStartEventSchema instead. Will be removed in 1.0.0.\n */\nexport const ThinkingStartEventSchema = BaseEventSchema.extend({\n type: z.literal(EventType.THINKING_START),\n title: z.string().optional(),\n});\n\n/**\n * @deprecated Use ReasoningEndEventSchema instead. Will be removed in 1.0.0.\n */\nexport const ThinkingEndEventSchema = BaseEventSchema.extend({\n type: z.literal(EventType.THINKING_END),\n});\n\nexport const StateSnapshotEventSchema = BaseEventSchema.extend({\n type: z.literal(EventType.STATE_SNAPSHOT),\n snapshot: StateSchema,\n});\n\nexport const StateDeltaEventSchema = BaseEventSchema.extend({\n type: z.literal(EventType.STATE_DELTA),\n delta: z.array(z.any()), // JSON Patch (RFC 6902)\n});\n\nexport const MessagesSnapshotEventSchema = BaseEventSchema.extend({\n type: z.literal(EventType.MESSAGES_SNAPSHOT),\n messages: z.array(MessageSchema),\n});\n\nexport const ActivitySnapshotEventSchema = BaseEventSchema.extend({\n type: z.literal(EventType.ACTIVITY_SNAPSHOT),\n messageId: z.string(),\n activityType: z.string(),\n content: z.record(z.any()),\n replace: z.boolean().optional().default(true),\n});\n\nexport const ActivityDeltaEventSchema = BaseEventSchema.extend({\n type: z.literal(EventType.ACTIVITY_DELTA),\n messageId: z.string(),\n activityType: z.string(),\n patch: z.array(z.any()),\n});\n\nexport const RawEventSchema = BaseEventSchema.extend({\n type: z.literal(EventType.RAW),\n event: z.any(),\n source: z.string().optional(),\n});\n\nexport const CustomEventSchema = BaseEventSchema.extend({\n type: z.literal(EventType.CUSTOM),\n name: z.string(),\n value: z.any(),\n});\n\nexport const RunStartedEventSchema = BaseEventSchema.extend({\n type: z.literal(EventType.RUN_STARTED),\n threadId: z.string(),\n runId: z.string(),\n parentRunId: z.string().optional(),\n input: RunAgentInputSchema.optional(),\n});\n\nexport const RunFinishedSuccessOutcomeSchema = z\n .object({\n type: z.literal(\"success\"),\n })\n .strict();\n\nexport const RunFinishedInterruptOutcomeSchema = z\n .object({\n type: z.literal(\"interrupt\"),\n interrupts: z.array(InterruptSchema).min(1),\n })\n .strict();\n\nexport const RunFinishedOutcomeSchema = z.discriminatedUnion(\"type\", [\n RunFinishedSuccessOutcomeSchema,\n RunFinishedInterruptOutcomeSchema,\n]);\n\nexport const RunFinishedEventSchema = BaseEventSchema.extend({\n type: z.literal(EventType.RUN_FINISHED),\n threadId: z.string(),\n runId: z.string(),\n result: z.any().optional(),\n // Accept `null` and treat it as omitted, so producers like the Pydantic-based\n // Python SDK that serialize via `model_dump()` (without `exclude_none=True`)\n // and emit `\"outcome\": null` for the legacy no-outcome case still validate.\n outcome: RunFinishedOutcomeSchema.nullable().optional().transform((v) => v ?? undefined),\n});\n\nexport const RunErrorEventSchema = BaseEventSchema.extend({\n type: z.literal(EventType.RUN_ERROR),\n message: z.string(),\n code: z.string().optional(),\n});\n\nexport const StepStartedEventSchema = BaseEventSchema.extend({\n type: z.literal(EventType.STEP_STARTED),\n stepName: z.string(),\n});\n\nexport const StepFinishedEventSchema = BaseEventSchema.extend({\n type: z.literal(EventType.STEP_FINISHED),\n stepName: z.string(),\n});\n\n// Schema for the encrypted signature subtype\nexport const ReasoningEncryptedValueSubtypeSchema = z.union([\n z.literal(\"tool-call\"),\n z.literal(\"message\"),\n]);\n\nexport const ReasoningStartEventSchema = BaseEventSchema.extend({\n type: z.literal(EventType.REASONING_START),\n messageId: z.string(),\n});\n\nexport const ReasoningMessageStartEventSchema = BaseEventSchema.extend({\n type: z.literal(EventType.REASONING_MESSAGE_START),\n messageId: z.string(),\n role: z.literal(\"reasoning\"),\n});\n\nexport const ReasoningMessageContentEventSchema = BaseEventSchema.extend({\n type: z.literal(EventType.REASONING_MESSAGE_CONTENT),\n messageId: z.string(),\n delta: z.string(),\n});\n\nexport const ReasoningMessageEndEventSchema = BaseEventSchema.extend({\n type: z.literal(EventType.REASONING_MESSAGE_END),\n messageId: z.string(),\n});\n\nexport const ReasoningMessageChunkEventSchema = BaseEventSchema.extend({\n type: z.literal(EventType.REASONING_MESSAGE_CHUNK),\n messageId: z.string().optional(),\n delta: z.string().optional(),\n});\n\nexport const ReasoningEndEventSchema = BaseEventSchema.extend({\n type: z.literal(EventType.REASONING_END),\n messageId: z.string(),\n});\n\nexport const ReasoningEncryptedValueEventSchema = BaseEventSchema.extend({\n type: z.literal(EventType.REASONING_ENCRYPTED_VALUE),\n subtype: ReasoningEncryptedValueSubtypeSchema,\n entityId: z.string(),\n encryptedValue: z.string(),\n});\n\nexport const EventSchemas = z.discriminatedUnion(\"type\", [\n TextMessageStartEventSchema,\n TextMessageContentEventSchema,\n TextMessageEndEventSchema,\n TextMessageChunkEventSchema,\n ThinkingStartEventSchema,\n ThinkingEndEventSchema,\n ThinkingTextMessageStartEventSchema,\n ThinkingTextMessageContentEventSchema,\n ThinkingTextMessageEndEventSchema,\n ToolCallStartEventSchema,\n ToolCallArgsEventSchema,\n ToolCallEndEventSchema,\n ToolCallChunkEventSchema,\n ToolCallResultEventSchema,\n StateSnapshotEventSchema,\n StateDeltaEventSchema,\n MessagesSnapshotEventSchema,\n ActivitySnapshotEventSchema,\n ActivityDeltaEventSchema,\n RawEventSchema,\n CustomEventSchema,\n RunStartedEventSchema,\n RunFinishedEventSchema,\n RunErrorEventSchema,\n StepStartedEventSchema,\n StepFinishedEventSchema,\n ReasoningStartEventSchema,\n ReasoningMessageStartEventSchema,\n ReasoningMessageContentEventSchema,\n ReasoningMessageEndEventSchema,\n ReasoningMessageChunkEventSchema,\n ReasoningEndEventSchema,\n ReasoningEncryptedValueEventSchema,\n]);\n\nexport type BaseEvent = z.infer<typeof BaseEventSchema>;\nexport type AGUIEvent = z.infer<typeof EventSchemas>;\nexport type BaseEventFields = z.infer<typeof BaseEventSchema>;\nexport type AGUIEventByType = {\n [EventType.TEXT_MESSAGE_START]: TextMessageStartEvent;\n [EventType.TEXT_MESSAGE_CONTENT]: TextMessageContentEvent;\n [EventType.TEXT_MESSAGE_END]: TextMessageEndEvent;\n [EventType.TEXT_MESSAGE_CHUNK]: TextMessageChunkEvent;\n [EventType.THINKING_TEXT_MESSAGE_START]: ThinkingTextMessageStartEvent;\n [EventType.THINKING_TEXT_MESSAGE_CONTENT]: ThinkingTextMessageContentEvent;\n [EventType.THINKING_TEXT_MESSAGE_END]: ThinkingTextMessageEndEvent;\n [EventType.TOOL_CALL_START]: ToolCallStartEvent;\n [EventType.TOOL_CALL_ARGS]: ToolCallArgsEvent;\n [EventType.TOOL_CALL_END]: ToolCallEndEvent;\n [EventType.TOOL_CALL_CHUNK]: ToolCallChunkEvent;\n [EventType.TOOL_CALL_RESULT]: ToolCallResultEvent;\n [EventType.THINKING_START]: ThinkingStartEvent;\n [EventType.THINKING_END]: ThinkingEndEvent;\n [EventType.STATE_SNAPSHOT]: StateSnapshotEvent;\n [EventType.STATE_DELTA]: StateDeltaEvent;\n [EventType.MESSAGES_SNAPSHOT]: MessagesSnapshotEvent;\n [EventType.ACTIVITY_SNAPSHOT]: ActivitySnapshotEvent;\n [EventType.ACTIVITY_DELTA]: ActivityDeltaEvent;\n [EventType.RAW]: RawEvent;\n [EventType.CUSTOM]: CustomEvent;\n [EventType.RUN_STARTED]: RunStartedEvent;\n [EventType.RUN_FINISHED]: RunFinishedEvent;\n [EventType.RUN_ERROR]: RunErrorEvent;\n [EventType.STEP_STARTED]: StepStartedEvent;\n [EventType.STEP_FINISHED]: StepFinishedEvent;\n [EventType.REASONING_START]: ReasoningStartEvent;\n [EventType.REASONING_MESSAGE_START]: ReasoningMessageStartEvent;\n [EventType.REASONING_MESSAGE_CONTENT]: ReasoningMessageContentEvent;\n [EventType.REASONING_MESSAGE_END]: ReasoningMessageEndEvent;\n [EventType.REASONING_MESSAGE_CHUNK]: ReasoningMessageChunkEvent;\n [EventType.REASONING_END]: ReasoningEndEvent;\n [EventType.REASONING_ENCRYPTED_VALUE]: ReasoningEncryptedValueEvent;\n};\nexport type AGUIEventOf<T extends EventType> = AGUIEventByType[T];\nexport type EventPayloadOf<T extends EventType> = Omit<AGUIEventOf<T>, keyof BaseEventFields>;\n\ntype EventProps<Schema extends z.ZodTypeAny> = Omit<z.input<Schema>, \"type\">;\n\nexport type BaseEventProps = EventProps<typeof BaseEventSchema>;\n\nexport type TextMessageStartEventProps = EventProps<typeof TextMessageStartEventSchema>;\nexport type TextMessageContentEventProps = EventProps<typeof TextMessageContentEventSchema>;\nexport type TextMessageEndEventProps = EventProps<typeof TextMessageEndEventSchema>;\nexport type TextMessageChunkEventProps = EventProps<typeof TextMessageChunkEventSchema>;\nexport type ThinkingTextMessageStartEventProps = EventProps<\n typeof ThinkingTextMessageStartEventSchema\n>;\nexport type ThinkingTextMessageContentEventProps = EventProps<\n typeof ThinkingTextMessageContentEventSchema\n>;\nexport type ThinkingTextMessageEndEventProps = EventProps<typeof ThinkingTextMessageEndEventSchema>;\nexport type ToolCallStartEventProps = EventProps<typeof ToolCallStartEventSchema>;\nexport type ToolCallArgsEventProps = EventProps<typeof ToolCallArgsEventSchema>;\nexport type ToolCallEndEventProps = EventProps<typeof ToolCallEndEventSchema>;\nexport type ToolCallChunkEventProps = EventProps<typeof ToolCallChunkEventSchema>;\nexport type ToolCallResultEventProps = EventProps<typeof ToolCallResultEventSchema>;\nexport type ThinkingStartEventProps = EventProps<typeof ThinkingStartEventSchema>;\nexport type ThinkingEndEventProps = EventProps<typeof ThinkingEndEventSchema>;\nexport type StateSnapshotEventProps = EventProps<typeof StateSnapshotEventSchema>;\nexport type StateDeltaEventProps = EventProps<typeof StateDeltaEventSchema>;\nexport type MessagesSnapshotEventProps = EventProps<typeof MessagesSnapshotEventSchema>;\nexport type ActivitySnapshotEventProps = EventProps<typeof ActivitySnapshotEventSchema>;\nexport type ActivityDeltaEventProps = EventProps<typeof ActivityDeltaEventSchema>;\nexport type RawEventProps = EventProps<typeof RawEventSchema>;\nexport type CustomEventProps = EventProps<typeof CustomEventSchema>;\nexport type RunStartedEventProps = EventProps<typeof RunStartedEventSchema>;\nexport type RunFinishedEventProps = EventProps<typeof RunFinishedEventSchema>;\nexport type RunErrorEventProps = EventProps<typeof RunErrorEventSchema>;\nexport type StepStartedEventProps = EventProps<typeof StepStartedEventSchema>;\nexport type StepFinishedEventProps = EventProps<typeof StepFinishedEventSchema>;\nexport type ReasoningStartEventProps = EventProps<typeof ReasoningStartEventSchema>;\nexport type ReasoningMessageStartEventProps = EventProps<typeof ReasoningMessageStartEventSchema>;\nexport type ReasoningMessageContentEventProps = EventProps<\n typeof ReasoningMessageContentEventSchema\n>;\nexport type ReasoningMessageEndEventProps = EventProps<typeof ReasoningMessageEndEventSchema>;\nexport type ReasoningMessageChunkEventProps = EventProps<typeof ReasoningMessageChunkEventSchema>;\nexport type ReasoningEndEventProps = EventProps<typeof ReasoningEndEventSchema>;\nexport type ReasoningEncryptedValueEventProps = EventProps<\n typeof ReasoningEncryptedValueEventSchema\n>;\n\nexport type TextMessageStartEvent = z.infer<typeof TextMessageStartEventSchema>;\nexport type TextMessageContentEvent = z.infer<typeof TextMessageContentEventSchema>;\nexport type TextMessageEndEvent = z.infer<typeof TextMessageEndEventSchema>;\nexport type TextMessageChunkEvent = z.infer<typeof TextMessageChunkEventSchema>;\nexport type ThinkingTextMessageStartEvent = z.infer<typeof ThinkingTextMessageStartEventSchema>;\nexport type ThinkingTextMessageContentEvent = z.infer<typeof ThinkingTextMessageContentEventSchema>;\nexport type ThinkingTextMessageEndEvent = z.infer<typeof ThinkingTextMessageEndEventSchema>;\nexport type ToolCallStartEvent = z.infer<typeof ToolCallStartEventSchema>;\nexport type ToolCallArgsEvent = z.infer<typeof ToolCallArgsEventSchema>;\nexport type ToolCallEndEvent = z.infer<typeof ToolCallEndEventSchema>;\nexport type ToolCallChunkEvent = z.infer<typeof ToolCallChunkEventSchema>;\nexport type ToolCallResultEvent = z.infer<typeof ToolCallResultEventSchema>;\nexport type ThinkingStartEvent = z.infer<typeof ThinkingStartEventSchema>;\nexport type ThinkingEndEvent = z.infer<typeof ThinkingEndEventSchema>;\nexport type StateSnapshotEvent = z.infer<typeof StateSnapshotEventSchema>;\nexport type StateDeltaEvent = z.infer<typeof StateDeltaEventSchema>;\nexport type MessagesSnapshotEvent = z.infer<typeof MessagesSnapshotEventSchema>;\nexport type ActivitySnapshotEvent = z.infer<typeof ActivitySnapshotEventSchema>;\nexport type ActivityDeltaEvent = z.infer<typeof ActivityDeltaEventSchema>;\nexport type RawEvent = z.infer<typeof RawEventSchema>;\nexport type CustomEvent = z.infer<typeof CustomEventSchema>;\nexport type RunStartedEvent = z.infer<typeof RunStartedEventSchema>;\nexport type RunFinishedEvent = z.infer<typeof RunFinishedEventSchema>;\nexport type RunFinishedOutcome = z.infer<typeof RunFinishedOutcomeSchema>;\nexport type RunFinishedSuccessOutcome = z.infer<typeof RunFinishedSuccessOutcomeSchema>;\nexport type RunFinishedInterruptOutcome = z.infer<typeof RunFinishedInterruptOutcomeSchema>;\nexport type RunErrorEvent = z.infer<typeof RunErrorEventSchema>;\nexport type StepStartedEvent = z.infer<typeof StepStartedEventSchema>;\nexport type StepFinishedEvent = z.infer<typeof StepFinishedEventSchema>;\nexport type ReasoningStartEvent = z.infer<typeof ReasoningStartEventSchema>;\nexport type ReasoningMessageStartEvent = z.infer<typeof ReasoningMessageStartEventSchema>;\nexport type ReasoningMessageContentEvent = z.infer<typeof ReasoningMessageContentEventSchema>;\nexport type ReasoningMessageEndEvent = z.infer<typeof ReasoningMessageEndEventSchema>;\nexport type ReasoningMessageChunkEvent = z.infer<typeof ReasoningMessageChunkEventSchema>;\nexport type ReasoningEndEvent = z.infer<typeof ReasoningEndEventSchema>;\nexport type ReasoningEncryptedValueEvent = z.infer<typeof ReasoningEncryptedValueEventSchema>;\nexport type ReasoningEncryptedValueSubtype = z.infer<typeof ReasoningEncryptedValueSubtypeSchema>;\n", "import { PatchError, _deepClone, isInteger, unescapePathComponent, hasUndefined } from './helpers.mjs';\nexport var JsonPatchError = PatchError;\nexport var deepClone = _deepClone;\n/* We use a Javascript hash to store each\n function. Each hash entry (property) uses\n the operation identifiers specified in rfc6902.\n In this way, we can map each patch operation\n to its dedicated function in efficient way.\n */\n/* The operations applicable to an object */\nvar objOps = {\n add: function (obj, key, document) {\n obj[key] = this.value;\n return { newDocument: document };\n },\n remove: function (obj, key, document) {\n var removed = obj[key];\n delete obj[key];\n return { newDocument: document, removed: removed };\n },\n replace: function (obj, key, document) {\n var removed = obj[key];\n obj[key] = this.value;\n return { newDocument: document, removed: removed };\n },\n move: function (obj, key, document) {\n /* in case move target overwrites an existing value,\n return the removed value, this can be taxing performance-wise,\n and is potentially unneeded */\n var removed = getValueByPointer(document, this.path);\n if (removed) {\n removed = _deepClone(removed);\n }\n var originalValue = applyOperation(document, { op: \"remove\", path: this.from }).removed;\n applyOperation(document, { op: \"add\", path: this.path, value: originalValue });\n return { newDocument: document, removed: removed };\n },\n copy: function (obj, key, document) {\n var valueToCopy = getValueByPointer(document, this.from);\n // enforce copy by value so further operations don't affect source (see issue #177)\n applyOperation(document, { op: \"add\", path: this.path, value: _deepClone(valueToCopy) });\n return { newDocument: document };\n },\n test: function (obj, key, document) {\n return { newDocument: document, test: _areEquals(obj[key], this.value) };\n },\n _get: function (obj, key, document) {\n this.value = obj[key];\n return { newDocument: document };\n }\n};\n/* The operations applicable to an array. Many are the same as for the object */\nvar arrOps = {\n add: function (arr, i, document) {\n if (isInteger(i)) {\n arr.splice(i, 0, this.value);\n }\n else { // array props\n arr[i] = this.value;\n }\n // this may be needed when using '-' in an array\n return { newDocument: document, index: i };\n },\n remove: function (arr, i, document) {\n var removedList = arr.splice(i, 1);\n return { newDocument: document, removed: removedList[0] };\n },\n replace: function (arr, i, document) {\n var removed = arr[i];\n arr[i] = this.value;\n return { newDocument: document, removed: removed };\n },\n move: objOps.move,\n copy: objOps.copy,\n test: objOps.test,\n _get: objOps._get\n};\n/**\n * Retrieves a value from a JSON document by a JSON pointer.\n * Returns the value.\n *\n * @param document The document to get the value from\n * @param pointer an escaped JSON pointer\n * @return The retrieved value\n */\nexport function getValueByPointer(document, pointer) {\n if (pointer == '') {\n return document;\n }\n var getOriginalDestination = { op: \"_get\", path: pointer };\n applyOperation(document, getOriginalDestination);\n return getOriginalDestination.value;\n}\n/**\n * Apply a single JSON Patch Operation on a JSON document.\n * Returns the {newDocument, result} of the operation.\n * It modifies the `document` and `operation` objects - it gets the values by reference.\n * If you would like to avoid touching your values, clone them:\n * `jsonpatch.applyOperation(document, jsonpatch._deepClone(operation))`.\n *\n * @param document The document to patch\n * @param operation The operation to apply\n * @param validateOperation `false` is without validation, `true` to use default jsonpatch's validation, or you can pass a `validateOperation` callback to be used for validation.\n * @param mutateDocument Whether to mutate the original document or clone it before applying\n * @param banPrototypeModifications Whether to ban modifications to `__proto__`, defaults to `true`.\n * @return `{newDocument, result}` after the operation\n */\nexport function applyOperation(document, operation, validateOperation, mutateDocument, banPrototypeModifications, index) {\n if (validateOperation === void 0) { validateOperation = false; }\n if (mutateDocument === void 0) { mutateDocument = true; }\n if (banPrototypeModifications === void 0) { banPrototypeModifications = true; }\n if (index === void 0) { index = 0; }\n if (validateOperation) {\n if (typeof validateOperation == 'function') {\n validateOperation(operation, 0, document, operation.path);\n }\n else {\n validator(operation, 0);\n }\n }\n /* ROOT OPERATIONS */\n if (operation.path === \"\") {\n var returnValue = { newDocument: document };\n if (operation.op === 'add') {\n returnValue.newDocument = operation.value;\n return returnValue;\n }\n else if (operation.op === 'replace') {\n returnValue.newDocument = operation.value;\n returnValue.removed = document; //document we removed\n return returnValue;\n }\n else if (operation.op === 'move' || operation.op === 'copy') { // it's a move or copy to root\n returnValue.newDocument = getValueByPointer(document, operation.from); // get the value by json-pointer in `from` field\n if (operation.op === 'move') { // report removed item\n returnValue.removed = document;\n }\n return returnValue;\n }\n else if (operation.op === 'test') {\n returnValue.test = _areEquals(document, operation.value);\n if (returnValue.test === false) {\n throw new JsonPatchError(\"Test operation failed\", 'TEST_OPERATION_FAILED', index, operation, document);\n }\n returnValue.newDocument = document;\n return returnValue;\n }\n else if (operation.op === 'remove') { // a remove on root\n returnValue.removed = document;\n returnValue.newDocument = null;\n return returnValue;\n }\n else if (operation.op === '_get') {\n operation.value = document;\n return returnValue;\n }\n else { /* bad operation */\n if (validateOperation) {\n throw new JsonPatchError('Operation `op` property is not one of operations defined in RFC-6902', 'OPERATION_OP_INVALID', index, operation, document);\n }\n else {\n return returnValue;\n }\n }\n } /* END ROOT OPERATIONS */\n else {\n if (!mutateDocument) {\n document = _deepClone(document);\n }\n var path = operation.path || \"\";\n var keys = path.split('/');\n var obj = document;\n var t = 1; //skip empty element - http://jsperf.com/to-shift-or-not-to-shift\n var len = keys.length;\n var existingPathFragment = undefined;\n var key = void 0;\n var validateFunction = void 0;\n if (typeof validateOperation == 'function') {\n validateFunction = validateOperation;\n }\n else {\n validateFunction = validator;\n }\n while (true) {\n key = keys[t];\n if (key && key.indexOf('~') != -1) {\n key = unescapePathComponent(key);\n }\n if (banPrototypeModifications &&\n (key == '__proto__' ||\n (key == 'prototype' && t > 0 && keys[t - 1] == 'constructor'))) {\n throw new TypeError('JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README');\n }\n if (validateOperation) {\n if (existingPathFragment === undefined) {\n if (obj[key] === undefined) {\n existingPathFragment = keys.slice(0, t).join('/');\n }\n else if (t == len - 1) {\n existingPathFragment = operation.path;\n }\n if (existingPathFragment !== undefined) {\n validateFunction(operation, 0, document, existingPathFragment);\n }\n }\n }\n t++;\n if (Array.isArray(obj)) {\n if (key === '-') {\n key = obj.length;\n }\n else {\n if (validateOperation && !isInteger(key)) {\n throw new JsonPatchError(\"Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index\", \"OPERATION_PATH_ILLEGAL_ARRAY_INDEX\", index, operation, document);\n } // only parse key when it's an integer for `arr.prop` to work\n else if (isInteger(key)) {\n key = ~~key;\n }\n }\n if (t >= len) {\n if (validateOperation && operation.op === \"add\" && key > obj.length) {\n throw new JsonPatchError(\"The specified index MUST NOT be greater than the number of elements in the array\", \"OPERATION_VALUE_OUT_OF_BOUNDS\", index, operation, document);\n }\n var returnValue = arrOps[operation.op].call(operation, obj, key, document); // Apply patch\n if (returnValue.test === false) {\n throw new JsonPatchError(\"Test operation failed\", 'TEST_OPERATION_FAILED', index, operation, document);\n }\n return returnValue;\n }\n }\n else {\n if (t >= len) {\n var returnValue = objOps[operation.op].call(operation, obj, key, document); // Apply patch\n if (returnValue.test === false) {\n throw new JsonPatchError(\"Test operation failed\", 'TEST_OPERATION_FAILED', index, operation, document);\n }\n return returnValue;\n }\n }\n obj = obj[key];\n // If we have more keys in the path, but the next value isn't a non-null object,\n // throw an OPERATION_PATH_UNRESOLVABLE error instead of iterating again.\n if (validateOperation && t < len && (!obj || typeof obj !== \"object\")) {\n throw new JsonPatchError('Cannot perform operation at the desired path', 'OPERATION_PATH_UNRESOLVABLE', index, operation, document);\n }\n }\n }\n}\n/**\n * Apply a full JSON Patch array on a JSON document.\n * Returns the {newDocument, result} of the patch.\n * It modifies the `document` object and `patch` - it gets the values by reference.\n * If you would like to avoid touching your values, clone them:\n * `jsonpatch.applyPatch(document, jsonpatch._deepClone(patch))`.\n *\n * @param document The document to patch\n * @param patch The patch to apply\n * @param validateOperation `false` is without validation, `true` to use default jsonpatch's validation, or you can pass a `validateOperation` callback to be used for validation.\n * @param mutateDocument Whether to mutate the original document or clone it before applying\n * @param banPrototypeModifications Whether to ban modifications to `__proto__`, defaults to `true`.\n * @return An array of `{newDocument, result}` after the patch\n */\nexport function applyPatch(document, patch, validateOperation, mutateDocument, banPrototypeModifications) {\n if (mutateDocument === void 0) { mutateDocument = true; }\n if (banPrototypeModifications === void 0) { banPrototypeModifications = true; }\n if (validateOperation) {\n if (!Array.isArray(patch)) {\n throw new JsonPatchError('Patch sequence must be an array', 'SEQUENCE_NOT_AN_ARRAY');\n }\n }\n if (!mutateDocument) {\n document = _deepClone(document);\n }\n var results = new Array(patch.length);\n for (var i = 0, length_1 = patch.length; i < length_1; i++) {\n // we don't need to pass mutateDocument argument because if it was true, we already deep cloned the object, we'll just pass `true`\n results[i] = applyOperation(document, patch[i], validateOperation, true, banPrototypeModifications, i);\n document = results[i].newDocument; // in case root was replaced\n }\n results.newDocument = document;\n return results;\n}\n/**\n * Apply a single JSON Patch Operation on a JSON document.\n * Returns the updated document.\n * Suitable as a reducer.\n *\n * @param document The document to patch\n * @param operation The operation to apply\n * @return The updated document\n */\nexport function applyReducer(document, operation, index) {\n var operationResult = applyOperation(document, operation);\n if (operationResult.test === false) { // failed test\n throw new JsonPatchError(\"Test operation failed\", 'TEST_OPERATION_FAILED', index, operation, document);\n }\n return operationResult.newDocument;\n}\n/**\n * Validates a single operation. Called from `jsonpatch.validate`. Throws `JsonPatchError` in case of an error.\n * @param {object} operation - operation object (patch)\n * @param {number} index - index of operation in the sequence\n * @param {object} [document] - object where the operation is supposed to be applied\n * @param {string} [existingPathFragment] - comes along with `document`\n */\nexport function validator(operation, index, document, existingPathFragment) {\n if (typeof operation !== 'object' || operation === null || Array.isArray(operation)) {\n throw new JsonPatchError('Operation is not an object', 'OPERATION_NOT_AN_OBJECT', index, operation, document);\n }\n else if (!objOps[operation.op]) {\n throw new JsonPatchError('Operation `op` property is not one of operations defined in RFC-6902', 'OPERATION_OP_INVALID', index, operation, document);\n }\n else if (typeof operation.path !== 'string') {\n throw new JsonPatchError('Operation `path` property is not a string', 'OPERATION_PATH_INVALID', index, operation, document);\n }\n else if (operation.path.indexOf('/') !== 0 && operation.path.length > 0) {\n // paths that aren't empty string should start with \"/\"\n throw new JsonPatchError('Operation `path` property must start with \"/\"', 'OPERATION_PATH_INVALID', index, operation, document);\n }\n else if ((operation.op === 'move' || operation.op === 'copy') && typeof operation.from !== 'string') {\n throw new JsonPatchError('Operation `from` property is not present (applicable in `move` and `copy` operations)', 'OPERATION_FROM_REQUIRED', index, operation, document);\n }\n else if ((operation.op === 'add' || operation.op === 'replace' || operation.op === 'test') && operation.value === undefined) {\n throw new JsonPatchError('Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)', 'OPERATION_VALUE_REQUIRED', index, operation, document);\n }\n else if ((operation.op === 'add' || operation.op === 'replace' || operation.op === 'test') && hasUndefined(operation.value)) {\n throw new JsonPatchError('Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)', 'OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED', index, operation, document);\n }\n else if (document) {\n if (operation.op == \"add\") {\n var pathLen = operation.path.split(\"/\").length;\n var existingPathLen = existingPathFragment.split(\"/\").length;\n if (pathLen !== existingPathLen + 1 && pathLen !== existingPathLen) {\n throw new JsonPatchError('Cannot perform an `add` operation at the desired path', 'OPERATION_PATH_CANNOT_ADD', index, operation, document);\n }\n }\n else if (operation.op === 'replace' || operation.op === 'remove' || operation.op === '_get') {\n if (operation.path !== existingPathFragment) {\n throw new JsonPatchError('Cannot perform the operation at a path that does not exist', 'OPERATION_PATH_UNRESOLVABLE', index, operation, document);\n }\n }\n else if (operation.op === 'move' || operation.op === 'copy') {\n var existingValue = { op: \"_get\", path: operation.from, value: undefined };\n var error = validate([existingValue], document);\n if (error && error.name === 'OPERATION_PATH_UNRESOLVABLE') {\n throw new JsonPatchError('Cannot perform the operation from a path that does not exist', 'OPERATION_FROM_UNRESOLVABLE', index, operation, document);\n }\n }\n }\n}\n/**\n * Validates a sequence of operations. If `document` parameter is provided, the sequence is additionally validated against the object document.\n * If error is encountered, returns a JsonPatchError object\n * @param sequence\n * @param document\n * @returns {JsonPatchError|undefined}\n */\nexport function validate(sequence, document, externalValidator) {\n try {\n if (!Array.isArray(sequence)) {\n throw new JsonPatchError('Patch sequence must be an array', 'SEQUENCE_NOT_AN_ARRAY');\n }\n if (document) {\n //clone document and sequence so that we can safely try applying operations\n applyPatch(_deepClone(document), _deepClone(sequence), externalValidator || true);\n }\n else {\n externalValidator = externalValidator || validator;\n for (var i = 0; i < sequence.length; i++) {\n externalValidator(sequence[i], i, document, undefined);\n }\n }\n }\n catch (e) {\n if (e instanceof JsonPatchError) {\n return e;\n }\n else {\n throw e;\n }\n }\n}\n// based on https://github.com/epoberezkin/fast-deep-equal\n// MIT License\n// Copyright (c) 2017 Evgeny Poberezkin\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\nexport function _areEquals(a, b) {\n if (a === b)\n return true;\n if (a && b && typeof a == 'object' && typeof b == 'object') {\n var arrA = Array.isArray(a), arrB = Array.isArray(b), i, length, key;\n if (arrA && arrB) {\n length = a.length;\n if (length != b.length)\n return false;\n for (i = length; i-- !== 0;)\n if (!_areEquals(a[i], b[i]))\n return false;\n return true;\n }\n if (arrA != arrB)\n return false;\n var keys = Object.keys(a);\n length = keys.length;\n if (length !== Object.keys(b).length)\n return false;\n for (i = length; i-- !== 0;)\n if (!b.hasOwnProperty(keys[i]))\n return false;\n for (i = length; i-- !== 0;) {\n key = keys[i];\n if (!_areEquals(a[key], b[key]))\n return false;\n }\n return true;\n }\n return a !== a && b !== b;\n}\n;\n", "/*!\n * https://github.com/Starcounter-Jack/JSON-Patch\n * (c) 2017-2022 Joachim Wester\n * MIT licensed\n */\nvar __extends = (this && this.__extends) || (function () {\n var extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return extendStatics(d, b);\n };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nvar _hasOwnProperty = Object.prototype.hasOwnProperty;\nexport function hasOwnProperty(obj, key) {\n return _hasOwnProperty.call(obj, key);\n}\nexport function _objectKeys(obj) {\n if (Array.isArray(obj)) {\n var keys_1 = new Array(obj.length);\n for (var k = 0; k < keys_1.length; k++) {\n keys_1[k] = \"\" + k;\n }\n return keys_1;\n }\n if (Object.keys) {\n return Object.keys(obj);\n }\n var keys = [];\n for (var i in obj) {\n if (hasOwnProperty(obj, i)) {\n keys.push(i);\n }\n }\n return keys;\n}\n;\n/**\n* Deeply clone the object.\n* https://jsperf.com/deep-copy-vs-json-stringify-json-parse/25 (recursiveDeepCopy)\n* @param {any} obj value to clone\n* @return {any} cloned obj\n*/\nexport function _deepClone(obj) {\n switch (typeof obj) {\n case \"object\":\n return JSON.parse(JSON.stringify(obj)); //Faster than ES5 clone - http://jsperf.com/deep-cloning-of-objects/5\n case \"undefined\":\n return null; //this is how JSON.stringify behaves for array items\n default:\n return obj; //no need to clone primitives\n }\n}\n//3x faster than cached /^\\d+$/.test(str)\nexport function isInteger(str) {\n var i = 0;\n var len = str.length;\n var charCode;\n while (i < len) {\n charCode = str.charCodeAt(i);\n if (charCode >= 48 && charCode <= 57) {\n i++;\n continue;\n }\n return false;\n }\n return true;\n}\n/**\n* Escapes a json pointer path\n* @param path The raw pointer\n* @return the Escaped path\n*/\nexport function escapePathComponent(path) {\n if (path.indexOf('/') === -1 && path.indexOf('~') === -1)\n return path;\n return path.replace(/~/g, '~0').replace(/\\//g, '~1');\n}\n/**\n * Unescapes a json pointer path\n * @param path The escaped pointer\n * @return The unescaped path\n */\nexport function unescapePathComponent(path) {\n return path.replace(/~1/g, '/').replace(/~0/g, '~');\n}\nexport function _getPathRecursive(root, obj) {\n var found;\n for (var key in root) {\n if (hasOwnProperty(root, key)) {\n if (root[key] === obj) {\n return escapePathComponent(key) + '/';\n }\n else if (typeof root[key] === 'object') {\n found = _getPathRecursive(root[key], obj);\n if (found != '') {\n return escapePathComponent(key) + '/' + found;\n }\n }\n }\n }\n return '';\n}\nexport function getPath(root, obj) {\n if (root === obj) {\n return '/';\n }\n var path = _getPathRecursive(root, obj);\n if (path === '') {\n throw new Error(\"Object not found in root\");\n }\n return \"/\" + path;\n}\n/**\n* Recursively checks whether an object has any undefined values inside.\n*/\nexport function hasUndefined(obj) {\n if (obj === undefined) {\n return true;\n }\n if (obj) {\n if (Array.isArray(obj)) {\n for (var i_1 = 0, len = obj.length; i_1 < len; i_1++) {\n if (hasUndefined(obj[i_1])) {\n return true;\n }\n }\n }\n else if (typeof obj === \"object\") {\n var objKeys = _objectKeys(obj);\n var objKeysLength = objKeys.length;\n for (var i = 0; i < objKeysLength; i++) {\n if (hasUndefined(obj[objKeys[i]])) {\n return true;\n }\n }\n }\n }\n return false;\n}\nfunction patchErrorMessageFormatter(message, args) {\n var messageParts = [message];\n for (var key in args) {\n var value = typeof args[key] === 'object' ? JSON.stringify(args[key], null, 2) : args[key]; // pretty print\n if (typeof value !== 'undefined') {\n messageParts.push(key + \": \" + value);\n }\n }\n return messageParts.join('\\n');\n}\nvar PatchError = /** @class */ (function (_super) {\n __extends(PatchError, _super);\n function PatchError(message, name, index, operation, tree) {\n var _newTarget = this.constructor;\n var _this = _super.call(this, patchErrorMessageFormatter(message, { name: name, index: index, operation: operation, tree: tree })) || this;\n _this.name = name;\n _this.index = index;\n _this.operation = operation;\n _this.tree = tree;\n Object.setPrototypeOf(_this, _newTarget.prototype); // restore prototype chain, see https://stackoverflow.com/a/48342359\n _this.message = patchErrorMessageFormatter(message, { name: name, index: index, operation: operation, tree: tree });\n return _this;\n }\n return PatchError;\n}(Error));\nexport { PatchError };\n", "/*!\n * https://github.com/Starcounter-Jack/JSON-Patch\n * (c) 2017-2021 Joachim Wester\n * MIT license\n */\nimport { _deepClone, _objectKeys, escapePathComponent, hasOwnProperty } from './helpers.mjs';\nimport { applyPatch } from './core.mjs';\nvar beforeDict = new WeakMap();\nvar Mirror = /** @class */ (function () {\n function Mirror(obj) {\n this.observers = new Map();\n this.obj = obj;\n }\n return Mirror;\n}());\nvar ObserverInfo = /** @class */ (function () {\n function ObserverInfo(callback, observer) {\n this.callback = callback;\n this.observer = observer;\n }\n return ObserverInfo;\n}());\nfunction getMirror(obj) {\n return beforeDict.get(obj);\n}\nfunction getObserverFromMirror(mirror, callback) {\n return mirror.observers.get(callback);\n}\nfunction removeObserverFromMirror(mirror, observer) {\n mirror.observers.delete(observer.callback);\n}\n/**\n * Detach an observer from an object\n */\nexport function unobserve(root, observer) {\n observer.unobserve();\n}\n/**\n * Observes changes made to an object, which can then be retrieved using generate\n */\nexport function observe(obj, callback) {\n var patches = [];\n var observer;\n var mirror = getMirror(obj);\n if (!mirror) {\n mirror = new Mirror(obj);\n beforeDict.set(obj, mirror);\n }\n else {\n var observerInfo = getObserverFromMirror(mirror, callback);\n observer = observerInfo && observerInfo.observer;\n }\n if (observer) {\n return observer;\n }\n observer = {};\n mirror.value = _deepClone(obj);\n if (callback) {\n observer.callback = callback;\n observer.next = null;\n var dirtyCheck = function () {\n generate(observer);\n };\n var fastCheck = function () {\n clearTimeout(observer.next);\n observer.next = setTimeout(dirtyCheck);\n };\n if (typeof window !== 'undefined') { //not Node\n window.addEventListener('mouseup', fastCheck);\n window.addEventListener('keyup', fastCheck);\n window.addEventListener('mousedown', fastCheck);\n window.addEventListener('keydown', fastCheck);\n window.addEventListener('change', fastCheck);\n }\n }\n observer.patches = patches;\n observer.object = obj;\n observer.unobserve = function () {\n generate(observer);\n clearTimeout(observer.next);\n removeObserverFromMirror(mirror, observer);\n if (typeof window !== 'undefined') {\n window.removeEventListener('mouseup', fastCheck);\n window.removeEventListener('keyup', fastCheck);\n window.removeEventListener('mousedown', fastCheck);\n window.removeEventListener('keydown', fastCheck);\n window.removeEventListener('change', fastCheck);\n }\n };\n mirror.observers.set(callback, new ObserverInfo(callback, observer));\n return observer;\n}\n/**\n * Generate an array of patches from an observer\n */\nexport function generate(observer, invertible) {\n if (invertible === void 0) { invertible = false; }\n var mirror = beforeDict.get(observer.object);\n _generate(mirror.value, observer.object, observer.patches, \"\", invertible);\n if (observer.patches.length) {\n applyPatch(mirror.value, observer.patches);\n }\n var temp = observer.patches;\n if (temp.length > 0) {\n observer.patches = [];\n if (observer.callback) {\n observer.callback(temp);\n }\n }\n return temp;\n}\n// Dirty check if obj is different from mirror, generate patches and update mirror\nfunction _generate(mirror, obj, patches, path, invertible) {\n if (obj === mirror) {\n return;\n }\n if (typeof obj.toJSON === \"function\") {\n obj = obj.toJSON();\n }\n var newKeys = _objectKeys(obj);\n var oldKeys = _objectKeys(mirror);\n var changed = false;\n var deleted = false;\n //if ever \"move\" operation is implemented here, make sure this test runs OK: \"should not generate the same patch twice (move)\"\n for (var t = oldKeys.length - 1; t >= 0; t--) {\n var key = oldKeys[t];\n var oldVal = mirror[key];\n if (hasOwnProperty(obj, key) && !(obj[key] === undefined && oldVal !== undefined && Array.isArray(obj) === false)) {\n var newVal = obj[key];\n if (typeof oldVal == \"object\" && oldVal != null && typeof newVal == \"object\" && newVal != null && Array.isArray(oldVal) === Array.isArray(newVal)) {\n _generate(oldVal, newVal, patches, path + \"/\" + escapePathComponent(key), invertible);\n }\n else {\n if (oldVal !== newVal) {\n changed = true;\n if (invertible) {\n patches.push({ op: \"test\", path: path + \"/\" + escapePathComponent(key), value: _deepClone(oldVal) });\n }\n patches.push({ op: \"replace\", path: path + \"/\" + escapePathComponent(key), value: _deepClone(newVal) });\n }\n }\n }\n else if (Array.isArray(mirror) === Array.isArray(obj)) {\n if (invertible) {\n patches.push({ op: \"test\", path: path + \"/\" + escapePathComponent(key), value: _deepClone(oldVal) });\n }\n patches.push({ op: \"remove\", path: path + \"/\" + escapePathComponent(key) });\n deleted = true; // property has been deleted\n }\n else {\n if (invertible) {\n patches.push({ op: \"test\", path: path, value: mirror });\n }\n patches.push({ op: \"replace\", path: path, value: obj });\n changed = true;\n }\n }\n if (!deleted && newKeys.length == oldKeys.length) {\n return;\n }\n for (var t = 0; t < newKeys.length; t++) {\n var key = newKeys[t];\n if (!hasOwnProperty(mirror, key) && obj[key] !== undefined) {\n patches.push({ op: \"add\", path: path + \"/\" + escapePathComponent(key), value: _deepClone(obj[key]) });\n }\n }\n}\n/**\n * Create an array of patches from the differences in two objects\n */\nexport function compare(tree1, tree2, invertible) {\n if (invertible === void 0) { invertible = false; }\n var patches = [];\n _generate(tree1, tree2, patches, '', invertible);\n return patches;\n}\n", "export * from './module/core.mjs';\nexport * from './module/duplex.mjs';\nexport {\n PatchError as JsonPatchError,\n _deepClone as deepClone,\n escapePathComponent,\n unescapePathComponent\n} from './module/helpers.mjs';\n\n\n/**\n * Default export for backwards compat\n */\n\nimport * as core from './module/core.mjs';\nimport * as duplex from './module/duplex.mjs';\nimport {\n PatchError as JsonPatchError,\n _deepClone as deepClone,\n escapePathComponent,\n unescapePathComponent\n} from './module/helpers.mjs';\n\nexport default Object.assign({}, core, duplex, {\n JsonPatchError,\n deepClone,\n escapePathComponent,\n unescapePathComponent\n});", "/******************************************************************************\nCopyright (c) Microsoft Corporation.\n\nPermission to use, copy, modify, and/or distribute this software for any\npurpose with or without fee is hereby granted.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\nPERFORMANCE OF THIS SOFTWARE.\n***************************************************************************** */\n/* global Reflect, Promise, SuppressedError, Symbol, Iterator */\n\nvar extendStatics = function(d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\n return extendStatics(d, b);\n};\n\nexport function __extends(d, b) {\n if (typeof b !== \"function\" && b !== null)\n throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n}\n\nexport var __assign = function() {\n __assign = Object.assign || function __assign(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\n }\n return t;\n }\n return __assign.apply(this, arguments);\n}\n\nexport function __rest(s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\n t[p[i]] = s[p[i]];\n }\n return t;\n}\n\nexport function __decorate(decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n}\n\nexport function __param(paramIndex, decorator) {\n return function (target, key) { decorator(target, key, paramIndex); }\n}\n\nexport function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {\n function accept(f) { if (f !== void 0 && typeof f !== \"function\") throw new TypeError(\"Function expected\"); return f; }\n var kind = contextIn.kind, key = kind === \"getter\" ? \"get\" : kind === \"setter\" ? \"set\" : \"value\";\n var target = !descriptorIn && ctor ? contextIn[\"static\"] ? ctor : ctor.prototype : null;\n var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});\n var _, done = false;\n for (var i = decorators.length - 1; i >= 0; i--) {\n var context = {};\n for (var p in contextIn) context[p] = p === \"access\" ? {} : contextIn[p];\n for (var p in contextIn.access) context.access[p] = contextIn.access[p];\n context.addInitializer = function (f) { if (done) throw new TypeError(\"Cannot add initializers after decoration has completed\"); extraInitializers.push(accept(f || null)); };\n var result = (0, decorators[i])(kind === \"accessor\" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);\n if (kind === \"accessor\") {\n if (result === void 0) continue;\n if (result === null || typeof result !== \"object\") throw new TypeError(\"Object expected\");\n if (_ = accept(result.get)) descriptor.get = _;\n if (_ = accept(result.set)) descriptor.set = _;\n if (_ = accept(result.init)) initializers.unshift(_);\n }\n else if (_ = accept(result)) {\n if (kind === \"field\") initializers.unshift(_);\n else descriptor[key] = _;\n }\n }\n if (target) Object.defineProperty(target, contextIn.name, descriptor);\n done = true;\n};\n\nexport function __runInitializers(thisArg, initializers, value) {\n var useValue = arguments.length > 2;\n for (var i = 0; i < initializers.length; i++) {\n value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);\n }\n return useValue ? value : void 0;\n};\n\nexport function __propKey(x) {\n return typeof x === \"symbol\" ? x : \"\".concat(x);\n};\n\nexport function __setFunctionName(f, name, prefix) {\n if (typeof name === \"symbol\") name = name.description ? \"[\".concat(name.description, \"]\") : \"\";\n return Object.defineProperty(f, \"name\", { configurable: true, value: prefix ? \"\".concat(prefix, \" \", name) : name });\n};\n\nexport function __metadata(metadataKey, metadataValue) {\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\n}\n\nexport function __awaiter(thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n}\n\nexport function __generator(thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === \"function\" ? Iterator : Object).prototype);\n return g.next = verb(0), g[\"throw\"] = verb(1), g[\"return\"] = verb(2), typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (g && (g = 0, op[0] && (_ = 0)), _) try {\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [op[0] & 2, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n}\n\nexport var __createBinding = Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n});\n\nexport function __exportStar(m, o) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);\n}\n\nexport function __values(o) {\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\n if (m) return m.call(o);\n if (o && typeof o.length === \"number\") return {\n next: function () {\n if (o && i >= o.length) o = void 0;\n return { value: o && o[i++], done: !o };\n }\n };\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\n}\n\nexport function __read(o, n) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n if (!m) return o;\n var i = m.call(o), r, ar = [], e;\n try {\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n }\n catch (error) { e = { error: error }; }\n finally {\n try {\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\n }\n finally { if (e) throw e.error; }\n }\n return ar;\n}\n\n/** @deprecated */\nexport function __spread() {\n for (var ar = [], i = 0; i < arguments.length; i++)\n ar = ar.concat(__read(arguments[i]));\n return ar;\n}\n\n/** @deprecated */\nexport function __spreadArrays() {\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\n r[k] = a[j];\n return r;\n}\n\nexport function __spreadArray(to, from, pack) {\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\n if (ar || !(i in from)) {\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\n ar[i] = from[i];\n }\n }\n return to.concat(ar || Array.prototype.slice.call(from));\n}\n\nexport function __await(v) {\n return this instanceof __await ? (this.v = v, this) : new __await(v);\n}\n\nexport function __asyncGenerator(thisArg, _arguments, generator) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\n return i = Object.create((typeof AsyncIterator === \"function\" ? AsyncIterator : Object).prototype), verb(\"next\"), verb(\"throw\"), verb(\"return\", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i;\n function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; }\n function verb(n, f) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; if (f) i[n] = f(i[n]); } }\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\n function fulfill(value) { resume(\"next\", value); }\n function reject(value) { resume(\"throw\", value); }\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\n}\n\nexport function __asyncDelegator(o) {\n var i, p;\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; }\n}\n\nexport function __asyncValues(o) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var m = o[Symbol.asyncIterator], i;\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\n}\n\nexport function __makeTemplateObject(cooked, raw) {\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\n return cooked;\n};\n\nvar __setModuleDefault = Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n};\n\nvar ownKeys = function(o) {\n ownKeys = Object.getOwnPropertyNames || function (o) {\n var ar = [];\n for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;\n return ar;\n };\n return ownKeys(o);\n};\n\nexport function __importStar(mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== \"default\") __createBinding(result, mod, k[i]);\n __setModuleDefault(result, mod);\n return result;\n}\n\nexport function __importDefault(mod) {\n return (mod && mod.__esModule) ? mod : { default: mod };\n}\n\nexport function __classPrivateFieldGet(receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n}\n\nexport function __classPrivateFieldSet(receiver, state, value, kind, f) {\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n}\n\nexport function __classPrivateFieldIn(state, receiver) {\n if (receiver === null || (typeof receiver !== \"object\" && typeof receiver !== \"function\")) throw new TypeError(\"Cannot use 'in' operator on non-object\");\n return typeof state === \"function\" ? receiver === state : state.has(receiver);\n}\n\nexport function __addDisposableResource(env, value, async) {\n if (value !== null && value !== void 0) {\n if (typeof value !== \"object\" && typeof value !== \"function\") throw new TypeError(\"Object expected.\");\n var dispose, inner;\n if (async) {\n if (!Symbol.asyncDispose) throw new TypeError(\"Symbol.asyncDispose is not defined.\");\n dispose = value[Symbol.asyncDispose];\n }\n if (dispose === void 0) {\n if (!Symbol.dispose) throw new TypeError(\"Symbol.dispose is not defined.\");\n dispose = value[Symbol.dispose];\n if (async) inner = dispose;\n }\n if (typeof dispose !== \"function\") throw new TypeError(\"Object not disposable.\");\n if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } };\n env.stack.push({ value: value, dispose: dispose, async: async });\n }\n else if (async) {\n env.stack.push({ async: true });\n }\n return value;\n}\n\nvar _SuppressedError = typeof SuppressedError === \"function\" ? SuppressedError : function (error, suppressed, message) {\n var e = new Error(message);\n return e.name = \"SuppressedError\", e.error = error, e.suppressed = suppressed, e;\n};\n\nexport function __disposeResources(env) {\n function fail(e) {\n env.error = env.hasError ? new _SuppressedError(e, env.error, \"An error was suppressed during disposal.\") : e;\n env.hasError = true;\n }\n var r, s = 0;\n function next() {\n while (r = env.stack.pop()) {\n try {\n if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);\n if (r.dispose) {\n var result = r.dispose.call(r.value);\n if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { fail(e); return next(); });\n }\n else s |= 1;\n }\n catch (e) {\n fail(e);\n }\n }\n if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();\n if (env.hasError) throw env.error;\n }\n return next();\n}\n\nexport function __rewriteRelativeImportExtension(path, preserveJsx) {\n if (typeof path === \"string\" && /^\\.\\.?\\//.test(path)) {\n return path.replace(/\\.(tsx)$|((?:\\.d)?)((?:\\.[^./]+?)?)\\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {\n return tsx ? preserveJsx ? \".jsx\" : \".js\" : d && (!ext || !cm) ? m : (d + ext + \".\" + cm.toLowerCase() + \"js\");\n });\n }\n return path;\n}\n\nexport default {\n __extends,\n __assign,\n __rest,\n __decorate,\n __param,\n __esDecorate,\n __runInitializers,\n __propKey,\n __setFunctionName,\n __metadata,\n __awaiter,\n __generator,\n __createBinding,\n __exportStar,\n __values,\n __read,\n __spread,\n __spreadArrays,\n __spreadArray,\n __await,\n __asyncGenerator,\n __asyncDelegator,\n __asyncValues,\n __makeTemplateObject,\n __importStar,\n __importDefault,\n __classPrivateFieldGet,\n __classPrivateFieldSet,\n __classPrivateFieldIn,\n __addDisposableResource,\n __disposeResources,\n __rewriteRelativeImportExtension,\n};\n", "/**\n * Returns true if the object is a function.\n * @param value The value to check\n */\nexport function isFunction(value: any): value is (...args: any[]) => any {\n return typeof value === 'function';\n}\n", "/**\n * Used to create Error subclasses until the community moves away from ES5.\n *\n * This is because compiling from TypeScript down to ES5 has issues with subclassing Errors\n * as well as other built-in types: https://github.com/Microsoft/TypeScript/issues/12123\n *\n * @param createImpl A factory function to create the actual constructor implementation. The returned\n * function should be a named function that calls `_super` internally.\n */\nexport function createErrorClass<T>(createImpl: (_super: any) => any): T {\n const _super = (instance: any) => {\n Error.call(instance);\n instance.stack = new Error().stack;\n };\n\n const ctorFunc = createImpl(_super);\n ctorFunc.prototype = Object.create(Error.prototype);\n ctorFunc.prototype.constructor = ctorFunc;\n return ctorFunc;\n}\n", "import { createErrorClass } from './createErrorClass';\n\nexport interface UnsubscriptionError extends Error {\n readonly errors: any[];\n}\n\nexport interface UnsubscriptionErrorCtor {\n /**\n * @deprecated Internal implementation detail. Do not construct error instances.\n * Cannot be tagged as internal: https://github.com/ReactiveX/rxjs/issues/6269\n */\n new (errors: any[]): UnsubscriptionError;\n}\n\n/**\n * An error thrown when one or more errors have occurred during the\n * `unsubscribe` of a {@link Subscription}.\n */\nexport const UnsubscriptionError: UnsubscriptionErrorCtor = createErrorClass(\n (_super) =>\n function UnsubscriptionErrorImpl(this: any, errors: (Error | string)[]) {\n _super(this);\n this.message = errors\n ? `${errors.length} errors occurred during unsubscription:\n${errors.map((err, i) => `${i + 1}) ${err.toString()}`).join('\\n ')}`\n : '';\n this.name = 'UnsubscriptionError';\n this.errors = errors;\n }\n);\n", "/**\n * Removes an item from an array, mutating it.\n * @param arr The array to remove the item from\n * @param item The item to remove\n */\nexport function arrRemove<T>(arr: T[] | undefined | null, item: T) {\n if (arr) {\n const index = arr.indexOf(item);\n 0 <= index && arr.splice(index, 1);\n }\n}\n", "import { isFunction } from './util/isFunction';\nimport { UnsubscriptionError } from './util/UnsubscriptionError';\nimport { SubscriptionLike, TeardownLogic, Unsubscribable } from './types';\nimport { arrRemove } from './util/arrRemove';\n\n/**\n * Represents a disposable resource, such as the execution of an Observable. A\n * Subscription has one important method, `unsubscribe`, that takes no argument\n * and just disposes the resource held by the subscription.\n *\n * Additionally, subscriptions may be grouped together through the `add()`\n * method, which will attach a child Subscription to the current Subscription.\n * When a Subscription is unsubscribed, all its children (and its grandchildren)\n * will be unsubscribed as well.\n *\n * @class Subscription\n */\nexport class Subscription implements SubscriptionLike {\n /** @nocollapse */\n public static EMPTY = (() => {\n const empty = new Subscription();\n empty.closed = true;\n return empty;\n })();\n\n /**\n * A flag to indicate whether this Subscription has already been unsubscribed.\n */\n public closed = false;\n\n private _parentage: Subscription[] | Subscription | null = null;\n\n /**\n * The list of registered finalizers to execute upon unsubscription. Adding and removing from this\n * list occurs in the {@link #add} and {@link #remove} methods.\n */\n private _finalizers: Exclude<TeardownLogic, void>[] | null = null;\n\n /**\n * @param initialTeardown A function executed first as part of the finalization\n * process that is kicked off when {@link #unsubscribe} is called.\n */\n constructor(private initialTeardown?: () => void) {}\n\n /**\n * Disposes the resources held by the subscription. May, for instance, cancel\n * an ongoing Observable execution or cancel any other type of work that\n * started when the Subscription was created.\n * @return {void}\n */\n unsubscribe(): void {\n let errors: any[] | undefined;\n\n if (!this.closed) {\n this.closed = true;\n\n // Remove this from it's parents.\n const { _parentage } = this;\n if (_parentage) {\n this._parentage = null;\n if (Array.isArray(_parentage)) {\n for (const parent of _parentage) {\n parent.remove(this);\n }\n } else {\n _parentage.remove(this);\n }\n }\n\n const { initialTeardown: initialFinalizer } = this;\n if (isFunction(initialFinalizer)) {\n try {\n initialFinalizer();\n } catch (e) {\n errors = e instanceof UnsubscriptionError ? e.errors : [e];\n }\n }\n\n const { _finalizers } = this;\n if (_finalizers) {\n this._finalizers = null;\n for (const finalizer of _finalizers) {\n try {\n execFinalizer(finalizer);\n } catch (err) {\n errors = errors ?? [];\n if (err instanceof UnsubscriptionError) {\n errors = [...errors, ...err.errors];\n } else {\n errors.push(err);\n }\n }\n }\n }\n\n if (errors) {\n throw new UnsubscriptionError(errors);\n }\n }\n }\n\n /**\n * Adds a finalizer to this subscription, so that finalization will be unsubscribed/called\n * when this subscription is unsubscribed. If this subscription is already {@link #closed},\n * because it has already been unsubscribed, then whatever finalizer is passed to it\n * will automatically be executed (unless the finalizer itself is also a closed subscription).\n *\n * Closed Subscriptions cannot be added as finalizers to any subscription. Adding a closed\n * subscription to a any subscription will result in no operation. (A noop).\n *\n * Adding a subscription to itself, or adding `null` or `undefined` will not perform any\n * operation at all. (A noop).\n *\n * `Subscription` instances that are added to this instance will automatically remove themselves\n * if they are unsubscribed. Functions and {@link Unsubscribable} objects that you wish to remove\n * will need to be removed manually with {@link #remove}\n *\n * @param teardown The finalization logic to add to this subscription.\n */\n add(teardown: TeardownLogic): void {\n // Only add the finalizer if it's not undefined\n // and don't add a subscription to itself.\n if (teardown && teardown !== this) {\n if (this.closed) {\n // If this subscription is already closed,\n // execute whatever finalizer is handed to it automatically.\n execFinalizer(teardown);\n } else {\n if (teardown instanceof Subscription) {\n // We don't add closed subscriptions, and we don't add the same subscription\n // twice. Subscription unsubscribe is idempotent.\n if (teardown.closed || teardown._hasParent(this)) {\n return;\n }\n teardown._addParent(this);\n }\n (this._finalizers = this._finalizers ?? []).push(teardown);\n }\n }\n }\n\n /**\n * Checks to see if a this subscription already has a particular parent.\n * This will signal that this subscription has already been added to the parent in question.\n * @param parent the parent to check for\n */\n private _hasParent(parent: Subscription) {\n const { _parentage } = this;\n return _parentage === parent || (Array.isArray(_parentage) && _parentage.includes(parent));\n }\n\n /**\n * Adds a parent to this subscription so it can be removed from the parent if it\n * unsubscribes on it's own.\n *\n * NOTE: THIS ASSUMES THAT {@link _hasParent} HAS ALREADY BEEN CHECKED.\n * @param parent The parent subscription to add\n */\n private _addParent(parent: Subscription) {\n const { _parentage } = this;\n this._parentage = Array.isArray(_parentage) ? (_parentage.push(parent), _parentage) : _parentage ? [_parentage, parent] : parent;\n }\n\n /**\n * Called on a child when it is removed via {@link #remove}.\n * @param parent The parent to remove\n */\n private _removeParent(parent: Subscription) {\n const { _parentage } = this;\n if (_parentage === parent) {\n this._parentage = null;\n } else if (Array.isArray(_parentage)) {\n arrRemove(_parentage, parent);\n }\n }\n\n /**\n * Removes a finalizer from this subscription that was previously added with the {@link #add} method.\n *\n * Note that `Subscription` instances, when unsubscribed, will automatically remove themselves\n * from every other `Subscription` they have been added to. This means that using the `remove` method\n * is not a common thing and should be used thoughtfully.\n *\n * If you add the same finalizer instance of a function or an unsubscribable object to a `Subscription` instance\n * more than once, you will need to call `remove` the same number of times to remove all instances.\n *\n * All finalizer instances are removed to free up memory upon unsubscription.\n *\n * @param teardown The finalizer to remove from this subscription\n */\n remove(teardown: Exclude<TeardownLogic, void>): void {\n const { _finalizers } = this;\n _finalizers && arrRemove(_finalizers, teardown);\n\n if (teardown instanceof Subscription) {\n teardown._removeParent(this);\n }\n }\n}\n\nexport const EMPTY_SUBSCRIPTION = Subscription.EMPTY;\n\nexport function isSubscription(value: any): value is Subscription {\n return (\n value instanceof Subscription ||\n (value && 'closed' in value && isFunction(value.remove) && isFunction(value.add) && isFunction(value.unsubscribe))\n );\n}\n\nfunction execFinalizer(finalizer: Unsubscribable | (() => void)) {\n if (isFunction(finalizer)) {\n finalizer();\n } else {\n finalizer.unsubscribe();\n }\n}\n", "import { Subscriber } from './Subscriber';\nimport { ObservableNotification } from './types';\n\n/**\n * The {@link GlobalConfig} object for RxJS. It is used to configure things\n * like how to react on unhandled errors.\n */\nexport const config: GlobalConfig = {\n onUnhandledError: null,\n onStoppedNotification: null,\n Promise: undefined,\n useDeprecatedSynchronousErrorHandling: false,\n useDeprecatedNextContext: false,\n};\n\n/**\n * The global configuration object for RxJS, used to configure things\n * like how to react on unhandled errors. Accessible via {@link config}\n * object.\n */\nexport interface GlobalConfig {\n /**\n * A registration point for unhandled errors from RxJS. These are errors that\n * cannot were not handled by consuming code in the usual subscription path. For\n * example, if you have this configured, and you subscribe to an observable without\n * providing an error handler, errors from that subscription will end up here. This\n * will _always_ be called asynchronously on another job in the runtime. This is because\n * we do not want errors thrown in this user-configured handler to interfere with the\n * behavior of the library.\n */\n onUnhandledError: ((err: any) => void) | null;\n\n /**\n * A registration point for notifications that cannot be sent to subscribers because they\n * have completed, errored or have been explicitly unsubscribed. By default, next, complete\n * and error notifications sent to stopped subscribers are noops. However, sometimes callers\n * might want a different behavior. For example, with sources that attempt to report errors\n * to stopped subscribers, a caller can configure RxJS to throw an unhandled error instead.\n * This will _always_ be called asynchronously on another job in the runtime. This is because\n * we do not want errors thrown in this user-configured handler to interfere with the\n * behavior of the library.\n */\n onStoppedNotification: ((notification: ObservableNotification<any>, subscriber: Subscriber<any>) => void) | null;\n\n /**\n * The promise constructor used by default for {@link Observable#toPromise toPromise} and {@link Observable#forEach forEach}\n * methods.\n *\n * @deprecated As of version 8, RxJS will no longer support this sort of injection of a\n * Promise constructor. If you need a Promise implementation other than native promises,\n * please polyfill/patch Promise as you see appropriate. Will be removed in v8.\n */\n Promise?: PromiseConstructorLike;\n\n /**\n * If true, turns on synchronous error rethrowing, which is a deprecated behavior\n * in v6 and higher. This behavior enables bad patterns like wrapping a subscribe\n * call in a try/catch block. It also enables producer interference, a nasty bug\n * where a multicast can be broken for all observers by a downstream consumer with\n * an unhandled error. DO NOT USE THIS FLAG UNLESS IT'S NEEDED TO BUY TIME\n * FOR MIGRATION REASONS.\n *\n * @deprecated As of version 8, RxJS will no longer support synchronous throwing\n * of unhandled errors. All errors will be thrown on a separate call stack to prevent bad\n * behaviors described above. Will be removed in v8.\n */\n useDeprecatedSynchronousErrorHandling: boolean;\n\n /**\n * If true, enables an as-of-yet undocumented feature from v5: The ability to access\n * `unsubscribe()` via `this` context in `next` functions created in observers passed\n * to `subscribe`.\n *\n * This is being removed because the performance was severely problematic, and it could also cause\n * issues when types other than POJOs are passed to subscribe as subscribers, as they will likely have\n * their `this` context overwritten.\n *\n * @deprecated As of version 8, RxJS will no longer support altering the\n * context of next functions provided as part of an observer to Subscribe. Instead,\n * you will have access to a subscription or a signal or token that will allow you to do things like\n * unsubscribe and test closed status. Will be removed in v8.\n */\n useDeprecatedNextContext: boolean;\n}\n", "import type { TimerHandle } from './timerHandle';\ntype SetTimeoutFunction = (handler: () => void, timeout?: number, ...args: any[]) => TimerHandle;\ntype ClearTimeoutFunction = (handle: TimerHandle) => void;\n\ninterface TimeoutProvider {\n setTimeout: SetTimeoutFunction;\n clearTimeout: ClearTimeoutFunction;\n delegate:\n | {\n setTimeout: SetTimeoutFunction;\n clearTimeout: ClearTimeoutFunction;\n }\n | undefined;\n}\n\nexport const timeoutProvider: TimeoutProvider = {\n // When accessing the delegate, use the variable rather than `this` so that\n // the functions can be called without being bound to the provider.\n setTimeout(handler: () => void, timeout?: number, ...args) {\n const { delegate } = timeoutProvider;\n if (delegate?.setTimeout) {\n return delegate.setTimeout(handler, timeout, ...args);\n }\n return setTimeout(handler, timeout, ...args);\n },\n clearTimeout(handle) {\n const { delegate } = timeoutProvider;\n return (delegate?.clearTimeout || clearTimeout)(handle as any);\n },\n delegate: undefined,\n};\n", "import { config } from '../config';\nimport { timeoutProvider } from '../scheduler/timeoutProvider';\n\n/**\n * Handles an error on another job either with the user-configured {@link onUnhandledError},\n * or by throwing it on that new job so it can be picked up by `window.onerror`, `process.on('error')`, etc.\n *\n * This should be called whenever there is an error that is out-of-band with the subscription\n * or when an error hits a terminal boundary of the subscription and no error handler was provided.\n *\n * @param err the error to report\n */\nexport function reportUnhandledError(err: any) {\n timeoutProvider.setTimeout(() => {\n const { onUnhandledError } = config;\n if (onUnhandledError) {\n // Execute the user-configured error handler.\n onUnhandledError(err);\n } else {\n // Throw so it is picked up by the runtime's uncaught error mechanism.\n throw err;\n }\n });\n}\n", "/* tslint:disable:no-empty */\nexport function noop() { }\n", "import { CompleteNotification, NextNotification, ErrorNotification } from './types';\n\n/**\n * A completion object optimized for memory use and created to be the\n * same \"shape\" as other notifications in v8.\n * @internal\n */\nexport const COMPLETE_NOTIFICATION = (() => createNotification('C', undefined, undefined) as CompleteNotification)();\n\n/**\n * Internal use only. Creates an optimized error notification that is the same \"shape\"\n * as other notifications.\n * @internal\n */\nexport function errorNotification(error: any): ErrorNotification {\n return createNotification('E', undefined, error) as any;\n}\n\n/**\n * Internal use only. Creates an optimized next notification that is the same \"shape\"\n * as other notifications.\n * @internal\n */\nexport function nextNotification<T>(value: T) {\n return createNotification('N', value, undefined) as NextNotification<T>;\n}\n\n/**\n * Ensures that all notifications created internally have the same \"shape\" in v8.\n *\n * TODO: This is only exported to support a crazy legacy test in `groupBy`.\n * @internal\n */\nexport function createNotification(kind: 'N' | 'E' | 'C', value: any, error: any) {\n return {\n kind,\n value,\n error,\n };\n}\n", "import { config } from '../config';\n\nlet context: { errorThrown: boolean; error: any } | null = null;\n\n/**\n * Handles dealing with errors for super-gross mode. Creates a context, in which\n * any synchronously thrown errors will be passed to {@link captureError}. Which\n * will record the error such that it will be rethrown after the call back is complete.\n * TODO: Remove in v8\n * @param cb An immediately executed function.\n */\nexport function errorContext(cb: () => void) {\n if (config.useDeprecatedSynchronousErrorHandling) {\n const isRoot = !context;\n if (isRoot) {\n context = { errorThrown: false, error: null };\n }\n cb();\n if (isRoot) {\n const { errorThrown, error } = context!;\n context = null;\n if (errorThrown) {\n throw error;\n }\n }\n } else {\n // This is the general non-deprecated path for everyone that\n // isn't crazy enough to use super-gross mode (useDeprecatedSynchronousErrorHandling)\n cb();\n }\n}\n\n/**\n * Captures errors only in super-gross mode.\n * @param err the error to capture\n */\nexport function captureError(err: any) {\n if (config.useDeprecatedSynchronousErrorHandling && context) {\n context.errorThrown = true;\n context.error = err;\n }\n}\n", "import { isFunction } from './util/isFunction';\nimport { Observer, ObservableNotification } from './types';\nimport { isSubscription, Subscription } from './Subscription';\nimport { config } from './config';\nimport { reportUnhandledError } from './util/reportUnhandledError';\nimport { noop } from './util/noop';\nimport { nextNotification, errorNotification, COMPLETE_NOTIFICATION } from './NotificationFactories';\nimport { timeoutProvider } from './scheduler/timeoutProvider';\nimport { captureError } from './util/errorContext';\n\n/**\n * Implements the {@link Observer} interface and extends the\n * {@link Subscription} class. While the {@link Observer} is the public API for\n * consuming the values of an {@link Observable}, all Observers get converted to\n * a Subscriber, in order to provide Subscription-like capabilities such as\n * `unsubscribe`. Subscriber is a common type in RxJS, and crucial for\n * implementing operators, but it is rarely used as a public API.\n *\n * @class Subscriber<T>\n */\nexport class Subscriber<T> extends Subscription implements Observer<T> {\n /**\n * A static factory for a Subscriber, given a (potentially partial) definition\n * of an Observer.\n * @param next The `next` callback of an Observer.\n * @param error The `error` callback of an\n * Observer.\n * @param complete The `complete` callback of an\n * Observer.\n * @return A Subscriber wrapping the (partially defined)\n * Observer represented by the given arguments.\n * @nocollapse\n * @deprecated Do not use. Will be removed in v8. There is no replacement for this\n * method, and there is no reason to be creating instances of `Subscriber` directly.\n * If you have a specific use case, please file an issue.\n */\n static create<T>(next?: (x?: T) => void, error?: (e?: any) => void, complete?: () => void): Subscriber<T> {\n return new SafeSubscriber(next, error, complete);\n }\n\n /** @deprecated Internal implementation detail, do not use directly. Will be made internal in v8. */\n protected isStopped: boolean = false;\n /** @deprecated Internal implementation detail, do not use directly. Will be made internal in v8. */\n protected destination: Subscriber<any> | Observer<any>; // this `any` is the escape hatch to erase extra type param (e.g. R)\n\n /**\n * @deprecated Internal implementation detail, do not use directly. Will be made internal in v8.\n * There is no reason to directly create an instance of Subscriber. This type is exported for typings reasons.\n */\n constructor(destination?: Subscriber<any> | Observer<any>) {\n super();\n if (destination) {\n this.destination = destination;\n // Automatically chain subscriptions together here.\n // if destination is a Subscription, then it is a Subscriber.\n if (isSubscription(destination)) {\n destination.add(this);\n }\n } else {\n this.destination = EMPTY_OBSERVER;\n }\n }\n\n /**\n * The {@link Observer} callback to receive notifications of type `next` from\n * the Observable, with a value. The Observable may call this method 0 or more\n * times.\n * @param {T} [value] The `next` value.\n * @return {void}\n */\n next(value?: T): void {\n if (this.isStopped) {\n handleStoppedNotification(nextNotification(value), this);\n } else {\n this._next(value!);\n }\n }\n\n /**\n * The {@link Observer} callback to receive notifications of type `error` from\n * the Observable, with an attached `Error`. Notifies the Observer that\n * the Observable has experienced an error condition.\n * @param {any} [err] The `error` exception.\n * @return {void}\n */\n error(err?: any): void {\n if (this.isStopped) {\n handleStoppedNotification(errorNotification(err), this);\n } else {\n this.isStopped = true;\n this._error(err);\n }\n }\n\n /**\n * The {@link Observer} callback to receive a valueless notification of type\n * `complete` from the Observable. Notifies the Observer that the Observable\n * has finished sending push-based notifications.\n * @return {void}\n */\n complete(): void {\n if (this.isStopped) {\n handleStoppedNotification(COMPLETE_NOTIFICATION, this);\n } else {\n this.isStopped = true;\n this._complete();\n }\n }\n\n unsubscribe(): void {\n if (!this.closed) {\n this.isStopped = true;\n super.unsubscribe();\n this.destination = null!;\n }\n }\n\n protected _next(value: T): void {\n this.destination.next(value);\n }\n\n protected _error(err: any): void {\n try {\n this.destination.error(err);\n } finally {\n this.unsubscribe();\n }\n }\n\n protected _complete(): void {\n try {\n this.destination.complete();\n } finally {\n this.unsubscribe();\n }\n }\n}\n\n/**\n * This bind is captured here because we want to be able to have\n * compatibility with monoid libraries that tend to use a method named\n * `bind`. In particular, a library called Monio requires this.\n */\nconst _bind = Function.prototype.bind;\n\nfunction bind<Fn extends (...args: any[]) => any>(fn: Fn, thisArg: any): Fn {\n return _bind.call(fn, thisArg);\n}\n\n/**\n * Internal optimization only, DO NOT EXPOSE.\n * @internal\n */\nclass ConsumerObserver<T> implements Observer<T> {\n constructor(private partialObserver: Partial<Observer<T>>) {}\n\n next(value: T): void {\n const { partialObserver } = this;\n if (partialObserver.next) {\n try {\n partialObserver.next(value);\n } catch (error) {\n handleUnhandledError(error);\n }\n }\n }\n\n error(err: any): void {\n const { partialObserver } = this;\n if (partialObserver.error) {\n try {\n partialObserver.error(err);\n } catch (error) {\n handleUnhandledError(error);\n }\n } else {\n handleUnhandledError(err);\n }\n }\n\n complete(): void {\n const { partialObserver } = this;\n if (partialObserver.complete) {\n try {\n partialObserver.complete();\n } catch (error) {\n handleUnhandledError(error);\n }\n }\n }\n}\n\nexport class SafeSubscriber<T> extends Subscriber<T> {\n constructor(\n observerOrNext?: Partial<Observer<T>> | ((value: T) => void) | null,\n error?: ((e?: any) => void) | null,\n complete?: (() => void) | null\n ) {\n super();\n\n let partialObserver: Partial<Observer<T>>;\n if (isFunction(observerOrNext) || !observerOrNext) {\n // The first argument is a function, not an observer. The next\n // two arguments *could* be observers, or they could be empty.\n partialObserver = {\n next: (observerOrNext ?? undefined) as (((value: T) => void) | undefined),\n error: error ?? undefined,\n complete: complete ?? undefined,\n };\n } else {\n // The first argument is a partial observer.\n let context: any;\n if (this && config.useDeprecatedNextContext) {\n // This is a deprecated path that made `this.unsubscribe()` available in\n // next handler functions passed to subscribe. This only exists behind a flag\n // now, as it is *very* slow.\n context = Object.create(observerOrNext);\n context.unsubscribe = () => this.unsubscribe();\n partialObserver = {\n next: observerOrNext.next && bind(observerOrNext.next, context),\n error: observerOrNext.error && bind(observerOrNext.error, context),\n complete: observerOrNext.complete && bind(observerOrNext.complete, context),\n };\n } else {\n // The \"normal\" path. Just use the partial observer directly.\n partialObserver = observerOrNext;\n }\n }\n\n // Wrap the partial observer to ensure it's a full observer, and\n // make sure proper error handling is accounted for.\n this.destination = new ConsumerObserver(partialObserver);\n }\n}\n\nfunction handleUnhandledError(error: any) {\n if (config.useDeprecatedSynchronousErrorHandling) {\n captureError(error);\n } else {\n // Ideal path, we report this as an unhandled error,\n // which is thrown on a new call stack.\n reportUnhandledError(error);\n }\n}\n\n/**\n * An error handler used when no error handler was supplied\n * to the SafeSubscriber -- meaning no error handler was supplied\n * do the `subscribe` call on our observable.\n * @param err The error to handle\n */\nfunction defaultErrorHandler(err: any) {\n throw err;\n}\n\n/**\n * A handler for notifications that cannot be sent to a stopped subscriber.\n * @param notification The notification being sent\n * @param subscriber The stopped subscriber\n */\nfunction handleStoppedNotification(notification: ObservableNotification<any>, subscriber: Subscriber<any>) {\n const { onStoppedNotification } = config;\n onStoppedNotification && timeoutProvider.setTimeout(() => onStoppedNotification(notification, subscriber));\n}\n\n/**\n * The observer used as a stub for subscriptions where the user did not\n * pass any arguments to `subscribe`. Comes with the default error handling\n * behavior.\n */\nexport const EMPTY_OBSERVER: Readonly<Observer<any>> & { closed: true } = {\n closed: true,\n next: noop,\n error: defaultErrorHandler,\n complete: noop,\n};\n", "/**\n * Symbol.observable or a string \"@@observable\". Used for interop\n *\n * @deprecated We will no longer be exporting this symbol in upcoming versions of RxJS.\n * Instead polyfill and use Symbol.observable directly *or* use https://www.npmjs.com/package/symbol-observable\n */\nexport const observable: string | symbol = (() => (typeof Symbol === 'function' && Symbol.observable) || '@@observable')();\n", "/**\n * This function takes one parameter and just returns it. Simply put,\n * this is like `<T>(x: T): T => x`.\n *\n * ## Examples\n *\n * This is useful in some cases when using things like `mergeMap`\n *\n * ```ts\n * import { interval, take, map, range, mergeMap, identity } from 'rxjs';\n *\n * const source$ = interval(1000).pipe(take(5));\n *\n * const result$ = source$.pipe(\n * map(i => range(i)),\n * mergeMap(identity) // same as mergeMap(x => x)\n * );\n *\n * result$.subscribe({\n * next: console.log\n * });\n * ```\n *\n * Or when you want to selectively apply an operator\n *\n * ```ts\n * import { interval, take, identity } from 'rxjs';\n *\n * const shouldLimit = () => Math.random() < 0.5;\n *\n * const source$ = interval(1000);\n *\n * const result$ = source$.pipe(shouldLimit() ? take(5) : identity);\n *\n * result$.subscribe({\n * next: console.log\n * });\n * ```\n *\n * @param x Any value that is returned by this function\n * @returns The value passed as the first parameter to this function\n */\nexport function identity<T>(x: T): T {\n return x;\n}\n", "import { identity } from './identity';\nimport { UnaryFunction } from '../types';\n\nexport function pipe(): typeof identity;\nexport function pipe<T, A>(fn1: UnaryFunction<T, A>): UnaryFunction<T, A>;\nexport function pipe<T, A, B>(fn1: UnaryFunction<T, A>, fn2: UnaryFunction<A, B>): UnaryFunction<T, B>;\nexport function pipe<T, A, B, C>(fn1: UnaryFunction<T, A>, fn2: UnaryFunction<A, B>, fn3: UnaryFunction<B, C>): UnaryFunction<T, C>;\nexport function pipe<T, A, B, C, D>(\n fn1: UnaryFunction<T, A>,\n fn2: UnaryFunction<A, B>,\n fn3: UnaryFunction<B, C>,\n fn4: UnaryFunction<C, D>\n): UnaryFunction<T, D>;\nexport function pipe<T, A, B, C, D, E>(\n fn1: UnaryFunction<T, A>,\n fn2: UnaryFunction<A, B>,\n fn3: UnaryFunction<B, C>,\n fn4: UnaryFunction<C, D>,\n fn5: UnaryFunction<D, E>\n): UnaryFunction<T, E>;\nexport function pipe<T, A, B, C, D, E, F>(\n fn1: UnaryFunction<T, A>,\n fn2: UnaryFunction<A, B>,\n fn3: UnaryFunction<B, C>,\n fn4: UnaryFunction<C, D>,\n fn5: UnaryFunction<D, E>,\n fn6: UnaryFunction<E, F>\n): UnaryFunction<T, F>;\nexport function pipe<T, A, B, C, D, E, F, G>(\n fn1: UnaryFunction<T, A>,\n fn2: UnaryFunction<A, B>,\n fn3: UnaryFunction<B, C>,\n fn4: UnaryFunction<C, D>,\n fn5: UnaryFunction<D, E>,\n fn6: UnaryFunction<E, F>,\n fn7: UnaryFunction<F, G>\n): UnaryFunction<T, G>;\nexport function pipe<T, A, B, C, D, E, F, G, H>(\n fn1: UnaryFunction<T, A>,\n fn2: UnaryFunction<A, B>,\n fn3: UnaryFunction<B, C>,\n fn4: UnaryFunction<C, D>,\n fn5: UnaryFunction<D, E>,\n fn6: UnaryFunction<E, F>,\n fn7: UnaryFunction<F, G>,\n fn8: UnaryFunction<G, H>\n): UnaryFunction<T, H>;\nexport function pipe<T, A, B, C, D, E, F, G, H, I>(\n fn1: UnaryFunction<T, A>,\n fn2: UnaryFunction<A, B>,\n fn3: UnaryFunction<B, C>,\n fn4: UnaryFunction<C, D>,\n fn5: UnaryFunction<D, E>,\n fn6: UnaryFunction<E, F>,\n fn7: UnaryFunction<F, G>,\n fn8: UnaryFunction<G, H>,\n fn9: UnaryFunction<H, I>\n): UnaryFunction<T, I>;\nexport function pipe<T, A, B, C, D, E, F, G, H, I>(\n fn1: UnaryFunction<T, A>,\n fn2: UnaryFunction<A, B>,\n fn3: UnaryFunction<B, C>,\n fn4: UnaryFunction<C, D>,\n fn5: UnaryFunction<D, E>,\n fn6: UnaryFunction<E, F>,\n fn7: UnaryFunction<F, G>,\n fn8: UnaryFunction<G, H>,\n fn9: UnaryFunction<H, I>,\n ...fns: UnaryFunction<any, any>[]\n): UnaryFunction<T, unknown>;\n\n/**\n * pipe() can be called on one or more functions, each of which can take one argument (\"UnaryFunction\")\n * and uses it to return a value.\n * It returns a function that takes one argument, passes it to the first UnaryFunction, and then\n * passes the result to the next one, passes that result to the next one, and so on. \n */\nexport function pipe(...fns: Array<UnaryFunction<any, any>>): UnaryFunction<any, any> {\n return pipeFromArray(fns);\n}\n\n/** @internal */\nexport function pipeFromArray<T, R>(fns: Array<UnaryFunction<T, R>>): UnaryFunction<T, R> {\n if (fns.length === 0) {\n return identity as UnaryFunction<any, any>;\n }\n\n if (fns.length === 1) {\n return fns[0];\n }\n\n return function piped(input: T): R {\n return fns.reduce((prev: any, fn: UnaryFunction<T, R>) => fn(prev), input as any);\n };\n}\n", "import { Operator } from './Operator';\nimport { SafeSubscriber, Subscriber } from './Subscriber';\nimport { isSubscription, Subscription } from './Subscription';\nimport { TeardownLogic, OperatorFunction, Subscribable, Observer } from './types';\nimport { observable as Symbol_observable } from './symbol/observable';\nimport { pipeFromArray } from './util/pipe';\nimport { config } from './config';\nimport { isFunction } from './util/isFunction';\nimport { errorContext } from './util/errorContext';\n\n/**\n * A representation of any set of values over any amount of time. This is the most basic building block\n * of RxJS.\n *\n * @class Observable<T>\n */\nexport class Observable<T> implements Subscribable<T> {\n /**\n * @deprecated Internal implementation detail, do not use directly. Will be made internal in v8.\n */\n source: Observable<any> | undefined;\n\n /**\n * @deprecated Internal implementation detail, do not use directly. Will be made internal in v8.\n */\n operator: Operator<any, T> | undefined;\n\n /**\n * @constructor\n * @param {Function} subscribe the function that is called when the Observable is\n * initially subscribed to. This function is given a Subscriber, to which new values\n * can be `next`ed, or an `error` method can be called to raise an error, or\n * `complete` can be called to notify of a successful completion.\n */\n constructor(subscribe?: (this: Observable<T>, subscriber: Subscriber<T>) => TeardownLogic) {\n if (subscribe) {\n this._subscribe = subscribe;\n }\n }\n\n // HACK: Since TypeScript inherits static properties too, we have to\n // fight against TypeScript here so Subject can have a different static create signature\n /**\n * Creates a new Observable by calling the Observable constructor\n * @owner Observable\n * @method create\n * @param {Function} subscribe? the subscriber function to be passed to the Observable constructor\n * @return {Observable} a new observable\n * @nocollapse\n * @deprecated Use `new Observable()` instead. Will be removed in v8.\n */\n static create: (...args: any[]) => any = <T>(subscribe?: (subscriber: Subscriber<T>) => TeardownLogic) => {\n return new Observable<T>(subscribe);\n };\n\n /**\n * Creates a new Observable, with this Observable instance as the source, and the passed\n * operator defined as the new observable's operator.\n * @method lift\n * @param operator the operator defining the operation to take on the observable\n * @return a new observable with the Operator applied\n * @deprecated Internal implementation detail, do not use directly. Will be made internal in v8.\n * If you have implemented an operator using `lift`, it is recommended that you create an\n * operator by simply returning `new Observable()` directly. See \"Creating new operators from\n * scratch\" section here: https://rxjs.dev/guide/operators\n */\n lift<R>(operator?: Operator<T, R>): Observable<R> {\n const observable = new Observable<R>();\n observable.source = this;\n observable.operator = operator;\n return observable;\n }\n\n subscribe(observerOrNext?: Partial<Observer<T>> | ((value: T) => void)): Subscription;\n /** @deprecated Instead of passing separate callback arguments, use an observer argument. Signatures taking separate callback arguments will be removed in v8. Details: https://rxjs.dev/deprecations/subscribe-arguments */\n subscribe(next?: ((value: T) => void) | null, error?: ((error: any) => void) | null, complete?: (() => void) | null): Subscription;\n /**\n * Invokes an execution of an Observable and registers Observer handlers for notifications it will emit.\n *\n * <span class=\"informal\">Use it when you have all these Observables, but still nothing is happening.</span>\n *\n * `subscribe` is not a regular operator, but a method that calls Observable's internal `subscribe` function. It\n * might be for example a function that you passed to Observable's constructor, but most of the time it is\n * a library implementation, which defines what will be emitted by an Observable, and when it be will emitted. This means\n * that calling `subscribe` is actually the moment when Observable starts its work, not when it is created, as it is often\n * the thought.\n *\n * Apart from starting the execution of an Observable, this method allows you to listen for values\n * that an Observable emits, as well as for when it completes or errors. You can achieve this in two\n * of the following ways.\n *\n * The first way is creating an object that implements {@link Observer} interface. It should have methods\n * defined by that interface, but note that it should be just a regular JavaScript object, which you can create\n * yourself in any way you want (ES6 class, classic function constructor, object literal etc.). In particular, do\n * not attempt to use any RxJS implementation details to create Observers - you don't need them. Remember also\n * that your object does not have to implement all methods. If you find yourself creating a method that doesn't\n * do anything, you can simply omit it. Note however, if the `error` method is not provided and an error happens,\n * it will be thrown asynchronously. Errors thrown asynchronously cannot be caught using `try`/`catch`. Instead,\n * use the {@link onUnhandledError} configuration option or use a runtime handler (like `window.onerror` or\n * `process.on('error)`) to be notified of unhandled errors. Because of this, it's recommended that you provide\n * an `error` method to avoid missing thrown errors.\n *\n * The second way is to give up on Observer object altogether and simply provide callback functions in place of its methods.\n * This means you can provide three functions as arguments to `subscribe`, where the first function is equivalent\n * of a `next` method, the second of an `error` method and the third of a `complete` method. Just as in case of an Observer,\n * if you do not need to listen for something, you can omit a function by passing `undefined` or `null`,\n * since `subscribe` recognizes these functions by where they were placed in function call. When it comes\n * to the `error` function, as with an Observer, if not provided, errors emitted by an Observable will be thrown asynchronously.\n *\n * You can, however, subscribe with no parameters at all. This may be the case where you're not interested in terminal events\n * and you also handled emissions internally by using operators (e.g. using `tap`).\n *\n * Whichever style of calling `subscribe` you use, in both cases it returns a Subscription object.\n * This object allows you to call `unsubscribe` on it, which in turn will stop the work that an Observable does and will clean\n * up all resources that an Observable used. Note that cancelling a subscription will not call `complete` callback\n * provided to `subscribe` function, which is reserved for a regular completion signal that comes from an Observable.\n *\n * Remember that callbacks provided to `subscribe` are not guaranteed to be called asynchronously.\n * It is an Observable itself that decides when these functions will be called. For example {@link of}\n * by default emits all its values synchronously. Always check documentation for how given Observable\n * will behave when subscribed and if its default behavior can be modified with a `scheduler`.\n *\n * #### Examples\n *\n * Subscribe with an {@link guide/observer Observer}\n *\n * ```ts\n * import { of } from 'rxjs';\n *\n * const sumObserver = {\n * sum: 0,\n * next(value) {\n * console.log('Adding: ' + value);\n * this.sum = this.sum + value;\n * },\n * error() {\n * // We actually could just remove this method,\n * // since we do not really care about errors right now.\n * },\n * complete() {\n * console.log('Sum equals: ' + this.sum);\n * }\n * };\n *\n * of(1, 2, 3) // Synchronously emits 1, 2, 3 and then completes.\n * .subscribe(sumObserver);\n *\n * // Logs:\n * // 'Adding: 1'\n * // 'Adding: 2'\n * // 'Adding: 3'\n * // 'Sum equals: 6'\n * ```\n *\n * Subscribe with functions ({@link deprecations/subscribe-arguments deprecated})\n *\n * ```ts\n * import { of } from 'rxjs'\n *\n * let sum = 0;\n *\n * of(1, 2, 3).subscribe(\n * value => {\n * console.log('Adding: ' + value);\n * sum = sum + value;\n * },\n * undefined,\n * () => console.log('Sum equals: ' + sum)\n * );\n *\n * // Logs:\n * // 'Adding: 1'\n * // 'Adding: 2'\n * // 'Adding: 3'\n * // 'Sum equals: 6'\n * ```\n *\n * Cancel a subscription\n *\n * ```ts\n * import { interval } from 'rxjs';\n *\n * const subscription = interval(1000).subscribe({\n * next(num) {\n * console.log(num)\n * },\n * complete() {\n * // Will not be called, even when cancelling subscription.\n * console.log('completed!');\n * }\n * });\n *\n * setTimeout(() => {\n * subscription.unsubscribe();\n * console.log('unsubscribed!');\n * }, 2500);\n *\n * // Logs:\n * // 0 after 1s\n * // 1 after 2s\n * // 'unsubscribed!' after 2.5s\n * ```\n *\n * @param {Observer|Function} observerOrNext (optional) Either an observer with methods to be called,\n * or the first of three possible handlers, which is the handler for each value emitted from the subscribed\n * Observable.\n * @param {Function} error (optional) A handler for a terminal event resulting from an error. If no error handler is provided,\n * the error will be thrown asynchronously as unhandled.\n * @param {Function} complete (optional) A handler for a terminal event resulting from successful completion.\n * @return {Subscription} a subscription reference to the registered handlers\n * @method subscribe\n */\n subscribe(\n observerOrNext?: Partial<Observer<T>> | ((value: T) => void) | null,\n error?: ((error: any) => void) | null,\n complete?: (() => void) | null\n ): Subscription {\n const subscriber = isSubscriber(observerOrNext) ? observerOrNext : new SafeSubscriber(observerOrNext, error, complete);\n\n errorContext(() => {\n const { operator, source } = this;\n subscriber.add(\n operator\n ? // We're dealing with a subscription in the\n // operator chain to one of our lifted operators.\n operator.call(subscriber, source)\n : source\n ? // If `source` has a value, but `operator` does not, something that\n // had intimate knowledge of our API, like our `Subject`, must have\n // set it. We're going to just call `_subscribe` directly.\n this._subscribe(subscriber)\n : // In all other cases, we're likely wrapping a user-provided initializer\n // function, so we need to catch errors and handle them appropriately.\n this._trySubscribe(subscriber)\n );\n });\n\n return subscriber;\n }\n\n /** @internal */\n protected _trySubscribe(sink: Subscriber<T>): TeardownLogic {\n try {\n return this._subscribe(sink);\n } catch (err) {\n // We don't need to return anything in this case,\n // because it's just going to try to `add()` to a subscription\n // above.\n sink.error(err);\n }\n }\n\n /**\n * Used as a NON-CANCELLABLE means of subscribing to an observable, for use with\n * APIs that expect promises, like `async/await`. You cannot unsubscribe from this.\n *\n * **WARNING**: Only use this with observables you *know* will complete. If the source\n * observable does not complete, you will end up with a promise that is hung up, and\n * potentially all of the state of an async function hanging out in memory. To avoid\n * this situation, look into adding something like {@link timeout}, {@link take},\n * {@link takeWhile}, or {@link takeUntil} amongst others.\n *\n * #### Example\n *\n * ```ts\n * import { interval, take } from 'rxjs';\n *\n * const source$ = interval(1000).pipe(take(4));\n *\n * async function getTotal() {\n * let total = 0;\n *\n * await source$.forEach(value => {\n * total += value;\n * console.log('observable -> ' + value);\n * });\n *\n * return total;\n * }\n *\n * getTotal().then(\n * total => console.log('Total: ' + total)\n * );\n *\n * // Expected:\n * // 'observable -> 0'\n * // 'observable -> 1'\n * // 'observable -> 2'\n * // 'observable -> 3'\n * // 'Total: 6'\n * ```\n *\n * @param next a handler for each value emitted by the observable\n * @return a promise that either resolves on observable completion or\n * rejects with the handled error\n */\n forEach(next: (value: T) => void): Promise<void>;\n\n /**\n * @param next a handler for each value emitted by the observable\n * @param promiseCtor a constructor function used to instantiate the Promise\n * @return a promise that either resolves on observable completion or\n * rejects with the handled error\n * @deprecated Passing a Promise constructor will no longer be available\n * in upcoming versions of RxJS. This is because it adds weight to the library, for very\n * little benefit. If you need this functionality, it is recommended that you either\n * polyfill Promise, or you create an adapter to convert the returned native promise\n * to whatever promise implementation you wanted. Will be removed in v8.\n */\n forEach(next: (value: T) => void, promiseCtor: PromiseConstructorLike): Promise<void>;\n\n forEach(next: (value: T) => void, promiseCtor?: PromiseConstructorLike): Promise<void> {\n promiseCtor = getPromiseCtor(promiseCtor);\n\n return new promiseCtor<void>((resolve, reject) => {\n const subscriber = new SafeSubscriber<T>({\n next: (value) => {\n try {\n next(value);\n } catch (err) {\n reject(err);\n subscriber.unsubscribe();\n }\n },\n error: reject,\n complete: resolve,\n });\n this.subscribe(subscriber);\n }) as Promise<void>;\n }\n\n /** @internal */\n protected _subscribe(subscriber: Subscriber<any>): TeardownLogic {\n return this.source?.subscribe(subscriber);\n }\n\n /**\n * An interop point defined by the es7-observable spec https://github.com/zenparsing/es-observable\n * @method Symbol.observable\n * @return {Observable} this instance of the observable\n */\n [Symbol_observable]() {\n return this;\n }\n\n /* tslint:disable:max-line-length */\n pipe(): Observable<T>;\n pipe<A>(op1: OperatorFunction<T, A>): Observable<A>;\n pipe<A, B>(op1: OperatorFunction<T, A>, op2: OperatorFunction<A, B>): Observable<B>;\n pipe<A, B, C>(op1: OperatorFunction<T, A>, op2: OperatorFunction<A, B>, op3: OperatorFunction<B, C>): Observable<C>;\n pipe<A, B, C, D>(\n op1: OperatorFunction<T, A>,\n op2: OperatorFunction<A, B>,\n op3: OperatorFunction<B, C>,\n op4: OperatorFunction<C, D>\n ): Observable<D>;\n pipe<A, B, C, D, E>(\n op1: OperatorFunction<T, A>,\n op2: OperatorFunction<A, B>,\n op3: OperatorFunction<B, C>,\n op4: OperatorFunction<C, D>,\n op5: OperatorFunction<D, E>\n ): Observable<E>;\n pipe<A, B, C, D, E, F>(\n op1: OperatorFunction<T, A>,\n op2: OperatorFunction<A, B>,\n op3: OperatorFunction<B, C>,\n op4: OperatorFunction<C, D>,\n op5: OperatorFunction<D, E>,\n op6: OperatorFunction<E, F>\n ): Observable<F>;\n pipe<A, B, C, D, E, F, G>(\n op1: OperatorFunction<T, A>,\n op2: OperatorFunction<A, B>,\n op3: OperatorFunction<B, C>,\n op4: OperatorFunction<C, D>,\n op5: OperatorFunction<D, E>,\n op6: OperatorFunction<E, F>,\n op7: OperatorFunction<F, G>\n ): Observable<G>;\n pipe<A, B, C, D, E, F, G, H>(\n op1: OperatorFunction<T, A>,\n op2: OperatorFunction<A, B>,\n op3: OperatorFunction<B, C>,\n op4: OperatorFunction<C, D>,\n op5: OperatorFunction<D, E>,\n op6: OperatorFunction<E, F>,\n op7: OperatorFunction<F, G>,\n op8: OperatorFunction<G, H>\n ): Observable<H>;\n pipe<A, B, C, D, E, F, G, H, I>(\n op1: OperatorFunction<T, A>,\n op2: OperatorFunction<A, B>,\n op3: OperatorFunction<B, C>,\n op4: OperatorFunction<C, D>,\n op5: OperatorFunction<D, E>,\n op6: OperatorFunction<E, F>,\n op7: OperatorFunction<F, G>,\n op8: OperatorFunction<G, H>,\n op9: OperatorFunction<H, I>\n ): Observable<I>;\n pipe<A, B, C, D, E, F, G, H, I>(\n op1: OperatorFunction<T, A>,\n op2: OperatorFunction<A, B>,\n op3: OperatorFunction<B, C>,\n op4: OperatorFunction<C, D>,\n op5: OperatorFunction<D, E>,\n op6: OperatorFunction<E, F>,\n op7: OperatorFunction<F, G>,\n op8: OperatorFunction<G, H>,\n op9: OperatorFunction<H, I>,\n ...operations: OperatorFunction<any, any>[]\n ): Observable<unknown>;\n /* tslint:enable:max-line-length */\n\n /**\n * Used to stitch together functional operators into a chain.\n * @method pipe\n * @return {Observable} the Observable result of all of the operators having\n * been called in the order they were passed in.\n *\n * ## Example\n *\n * ```ts\n * import { interval, filter, map, scan } from 'rxjs';\n *\n * interval(1000)\n * .pipe(\n * filter(x => x % 2 === 0),\n * map(x => x + x),\n * scan((acc, x) => acc + x)\n * )\n * .subscribe(x => console.log(x));\n * ```\n */\n pipe(...operations: OperatorFunction<any, any>[]): Observable<any> {\n return pipeFromArray(operations)(this);\n }\n\n /* tslint:disable:max-line-length */\n /** @deprecated Replaced with {@link firstValueFrom} and {@link lastValueFrom}. Will be removed in v8. Details: https://rxjs.dev/deprecations/to-promise */\n toPromise(): Promise<T | undefined>;\n /** @deprecated Replaced with {@link firstValueFrom} and {@link lastValueFrom}. Will be removed in v8. Details: https://rxjs.dev/deprecations/to-promise */\n toPromise(PromiseCtor: typeof Promise): Promise<T | undefined>;\n /** @deprecated Replaced with {@link firstValueFrom} and {@link lastValueFrom}. Will be removed in v8. Details: https://rxjs.dev/deprecations/to-promise */\n toPromise(PromiseCtor: PromiseConstructorLike): Promise<T | undefined>;\n /* tslint:enable:max-line-length */\n\n /**\n * Subscribe to this Observable and get a Promise resolving on\n * `complete` with the last emission (if any).\n *\n * **WARNING**: Only use this with observables you *know* will complete. If the source\n * observable does not complete, you will end up with a promise that is hung up, and\n * potentially all of the state of an async function hanging out in memory. To avoid\n * this situation, look into adding something like {@link timeout}, {@link take},\n * {@link takeWhile}, or {@link takeUntil} amongst others.\n *\n * @method toPromise\n * @param [promiseCtor] a constructor function used to instantiate\n * the Promise\n * @return A Promise that resolves with the last value emit, or\n * rejects on an error. If there were no emissions, Promise\n * resolves with undefined.\n * @deprecated Replaced with {@link firstValueFrom} and {@link lastValueFrom}. Will be removed in v8. Details: https://rxjs.dev/deprecations/to-promise\n */\n toPromise(promiseCtor?: PromiseConstructorLike): Promise<T | undefined> {\n promiseCtor = getPromiseCtor(promiseCtor);\n\n return new promiseCtor((resolve, reject) => {\n let value: T | undefined;\n this.subscribe(\n (x: T) => (value = x),\n (err: any) => reject(err),\n () => resolve(value)\n );\n }) as Promise<T | undefined>;\n }\n}\n\n/**\n * Decides between a passed promise constructor from consuming code,\n * A default configured promise constructor, and the native promise\n * constructor and returns it. If nothing can be found, it will throw\n * an error.\n * @param promiseCtor The optional promise constructor to passed by consuming code\n */\nfunction getPromiseCtor(promiseCtor: PromiseConstructorLike | undefined) {\n return promiseCtor ?? config.Promise ?? Promise;\n}\n\nfunction isObserver<T>(value: any): value is Observer<T> {\n return value && isFunction(value.next) && isFunction(value.error) && isFunction(value.complete);\n}\n\nfunction isSubscriber<T>(value: any): value is Subscriber<T> {\n return (value && value instanceof Subscriber) || (isObserver(value) && isSubscription(value));\n}\n", "import { Observable } from '../Observable';\nimport { Subscriber } from '../Subscriber';\nimport { OperatorFunction } from '../types';\nimport { isFunction } from './isFunction';\n\n/**\n * Used to determine if an object is an Observable with a lift function.\n */\nexport function hasLift(source: any): source is { lift: InstanceType<typeof Observable>['lift'] } {\n return isFunction(source?.lift);\n}\n\n/**\n * Creates an `OperatorFunction`. Used to define operators throughout the library in a concise way.\n * @param init The logic to connect the liftedSource to the subscriber at the moment of subscription.\n */\nexport function operate<T, R>(\n init: (liftedSource: Observable<T>, subscriber: Subscriber<R>) => (() => void) | void\n): OperatorFunction<T, R> {\n return (source: Observable<T>) => {\n if (hasLift(source)) {\n return source.lift(function (this: Subscriber<R>, liftedSource: Observable<T>) {\n try {\n return init(liftedSource, this);\n } catch (err) {\n this.error(err);\n }\n });\n }\n throw new TypeError('Unable to lift unknown Observable type');\n };\n}\n", "import { Subscriber } from '../Subscriber';\n\n/**\n * Creates an instance of an `OperatorSubscriber`.\n * @param destination The downstream subscriber.\n * @param onNext Handles next values, only called if this subscriber is not stopped or closed. Any\n * error that occurs in this function is caught and sent to the `error` method of this subscriber.\n * @param onError Handles errors from the subscription, any errors that occur in this handler are caught\n * and send to the `destination` error handler.\n * @param onComplete Handles completion notification from the subscription. Any errors that occur in\n * this handler are sent to the `destination` error handler.\n * @param onFinalize Additional teardown logic here. This will only be called on teardown if the\n * subscriber itself is not already closed. This is called after all other teardown logic is executed.\n */\nexport function createOperatorSubscriber<T>(\n destination: Subscriber<any>,\n onNext?: (value: T) => void,\n onComplete?: () => void,\n onError?: (err: any) => void,\n onFinalize?: () => void\n): Subscriber<T> {\n return new OperatorSubscriber(destination, onNext, onComplete, onError, onFinalize);\n}\n\n/**\n * A generic helper for allowing operators to be created with a Subscriber and\n * use closures to capture necessary state from the operator function itself.\n */\nexport class OperatorSubscriber<T> extends Subscriber<T> {\n /**\n * Creates an instance of an `OperatorSubscriber`.\n * @param destination The downstream subscriber.\n * @param onNext Handles next values, only called if this subscriber is not stopped or closed. Any\n * error that occurs in this function is caught and sent to the `error` method of this subscriber.\n * @param onError Handles errors from the subscription, any errors that occur in this handler are caught\n * and send to the `destination` error handler.\n * @param onComplete Handles completion notification from the subscription. Any errors that occur in\n * this handler are sent to the `destination` error handler.\n * @param onFinalize Additional finalization logic here. This will only be called on finalization if the\n * subscriber itself is not already closed. This is called after all other finalization logic is executed.\n * @param shouldUnsubscribe An optional check to see if an unsubscribe call should truly unsubscribe.\n * NOTE: This currently **ONLY** exists to support the strange behavior of {@link groupBy}, where unsubscription\n * to the resulting observable does not actually disconnect from the source if there are active subscriptions\n * to any grouped observable. (DO NOT EXPOSE OR USE EXTERNALLY!!!)\n */\n constructor(\n destination: Subscriber<any>,\n onNext?: (value: T) => void,\n onComplete?: () => void,\n onError?: (err: any) => void,\n private onFinalize?: () => void,\n private shouldUnsubscribe?: () => boolean\n ) {\n // It's important - for performance reasons - that all of this class's\n // members are initialized and that they are always initialized in the same\n // order. This will ensure that all OperatorSubscriber instances have the\n // same hidden class in V8. This, in turn, will help keep the number of\n // hidden classes involved in property accesses within the base class as\n // low as possible. If the number of hidden classes involved exceeds four,\n // the property accesses will become megamorphic and performance penalties\n // will be incurred - i.e. inline caches won't be used.\n //\n // The reasons for ensuring all instances have the same hidden class are\n // further discussed in this blog post from Benedikt Meurer:\n // https://benediktmeurer.de/2018/03/23/impact-of-polymorphism-on-component-based-frameworks-like-react/\n super(destination);\n this._next = onNext\n ? function (this: OperatorSubscriber<T>, value: T) {\n try {\n onNext(value);\n } catch (err) {\n destination.error(err);\n }\n }\n : super._next;\n this._error = onError\n ? function (this: OperatorSubscriber<T>, err: any) {\n try {\n onError(err);\n } catch (err) {\n // Send any errors that occur down stream.\n destination.error(err);\n } finally {\n // Ensure finalization.\n this.unsubscribe();\n }\n }\n : super._error;\n this._complete = onComplete\n ? function (this: OperatorSubscriber<T>) {\n try {\n onComplete();\n } catch (err) {\n // Send any errors that occur down stream.\n destination.error(err);\n } finally {\n // Ensure finalization.\n this.unsubscribe();\n }\n }\n : super._complete;\n }\n\n unsubscribe() {\n if (!this.shouldUnsubscribe || this.shouldUnsubscribe()) {\n const { closed } = this;\n super.unsubscribe();\n // Execute additional teardown if we have any and we didn't already do so.\n !closed && this.onFinalize?.();\n }\n }\n}\n", "import { createErrorClass } from './createErrorClass';\n\nexport interface ObjectUnsubscribedError extends Error {}\n\nexport interface ObjectUnsubscribedErrorCtor {\n /**\n * @deprecated Internal implementation detail. Do not construct error instances.\n * Cannot be tagged as internal: https://github.com/ReactiveX/rxjs/issues/6269\n */\n new (): ObjectUnsubscribedError;\n}\n\n/**\n * An error thrown when an action is invalid because the object has been\n * unsubscribed.\n *\n * @see {@link Subject}\n * @see {@link BehaviorSubject}\n *\n * @class ObjectUnsubscribedError\n */\nexport const ObjectUnsubscribedError: ObjectUnsubscribedErrorCtor = createErrorClass(\n (_super) =>\n function ObjectUnsubscribedErrorImpl(this: any) {\n _super(this);\n this.name = 'ObjectUnsubscribedError';\n this.message = 'object unsubscribed';\n }\n);\n", "import { Operator } from './Operator';\nimport { Observable } from './Observable';\nimport { Subscriber } from './Subscriber';\nimport { Subscription, EMPTY_SUBSCRIPTION } from './Subscription';\nimport { Observer, SubscriptionLike, TeardownLogic } from './types';\nimport { ObjectUnsubscribedError } from './util/ObjectUnsubscribedError';\nimport { arrRemove } from './util/arrRemove';\nimport { errorContext } from './util/errorContext';\n\n/**\n * A Subject is a special type of Observable that allows values to be\n * multicasted to many Observers. Subjects are like EventEmitters.\n *\n * Every Subject is an Observable and an Observer. You can subscribe to a\n * Subject, and you can call next to feed values as well as error and complete.\n */\nexport class Subject<T> extends Observable<T> implements SubscriptionLike {\n closed = false;\n\n private currentObservers: Observer<T>[] | null = null;\n\n /** @deprecated Internal implementation detail, do not use directly. Will be made internal in v8. */\n observers: Observer<T>[] = [];\n /** @deprecated Internal implementation detail, do not use directly. Will be made internal in v8. */\n isStopped = false;\n /** @deprecated Internal implementation detail, do not use directly. Will be made internal in v8. */\n hasError = false;\n /** @deprecated Internal implementation detail, do not use directly. Will be made internal in v8. */\n thrownError: any = null;\n\n /**\n * Creates a \"subject\" by basically gluing an observer to an observable.\n *\n * @nocollapse\n * @deprecated Recommended you do not use. Will be removed at some point in the future. Plans for replacement still under discussion.\n */\n static create: (...args: any[]) => any = <T>(destination: Observer<T>, source: Observable<T>): AnonymousSubject<T> => {\n return new AnonymousSubject<T>(destination, source);\n };\n\n constructor() {\n // NOTE: This must be here to obscure Observable's constructor.\n super();\n }\n\n /** @deprecated Internal implementation detail, do not use directly. Will be made internal in v8. */\n lift<R>(operator: Operator<T, R>): Observable<R> {\n const subject = new AnonymousSubject(this, this);\n subject.operator = operator as any;\n return subject as any;\n }\n\n /** @internal */\n protected _throwIfClosed() {\n if (this.closed) {\n throw new ObjectUnsubscribedError();\n }\n }\n\n next(value: T) {\n errorContext(() => {\n this._throwIfClosed();\n if (!this.isStopped) {\n if (!this.currentObservers) {\n this.currentObservers = Array.from(this.observers);\n }\n for (const observer of this.currentObservers) {\n observer.next(value);\n }\n }\n });\n }\n\n error(err: any) {\n errorContext(() => {\n this._throwIfClosed();\n if (!this.isStopped) {\n this.hasError = this.isStopped = true;\n this.thrownError = err;\n const { observers } = this;\n while (observers.length) {\n observers.shift()!.error(err);\n }\n }\n });\n }\n\n complete() {\n errorContext(() => {\n this._throwIfClosed();\n if (!this.isStopped) {\n this.isStopped = true;\n const { observers } = this;\n while (observers.length) {\n observers.shift()!.complete();\n }\n }\n });\n }\n\n unsubscribe() {\n this.isStopped = this.closed = true;\n this.observers = this.currentObservers = null!;\n }\n\n get observed() {\n return this.observers?.length > 0;\n }\n\n /** @internal */\n protected _trySubscribe(subscriber: Subscriber<T>): TeardownLogic {\n this._throwIfClosed();\n return super._trySubscribe(subscriber);\n }\n\n /** @internal */\n protected _subscribe(subscriber: Subscriber<T>): Subscription {\n this._throwIfClosed();\n this._checkFinalizedStatuses(subscriber);\n return this._innerSubscribe(subscriber);\n }\n\n /** @internal */\n protected _innerSubscribe(subscriber: Subscriber<any>) {\n const { hasError, isStopped, observers } = this;\n if (hasError || isStopped) {\n return EMPTY_SUBSCRIPTION;\n }\n this.currentObservers = null;\n observers.push(subscriber);\n return new Subscription(() => {\n this.currentObservers = null;\n arrRemove(observers, subscriber);\n });\n }\n\n /** @internal */\n protected _checkFinalizedStatuses(subscriber: Subscriber<any>) {\n const { hasError, thrownError, isStopped } = this;\n if (hasError) {\n subscriber.error(thrownError);\n } else if (isStopped) {\n subscriber.complete();\n }\n }\n\n /**\n * Creates a new Observable with this Subject as the source. You can do this\n * to create custom Observer-side logic of the Subject and conceal it from\n * code that uses the Observable.\n * @return {Observable} Observable that the Subject casts to\n */\n asObservable(): Observable<T> {\n const observable: any = new Observable<T>();\n observable.source = this;\n return observable;\n }\n}\n\n/**\n * @class AnonymousSubject<T>\n */\nexport class AnonymousSubject<T> extends Subject<T> {\n constructor(\n /** @deprecated Internal implementation detail, do not use directly. Will be made internal in v8. */\n public destination?: Observer<T>,\n source?: Observable<T>\n ) {\n super();\n this.source = source;\n }\n\n next(value: T) {\n this.destination?.next?.(value);\n }\n\n error(err: any) {\n this.destination?.error?.(err);\n }\n\n complete() {\n this.destination?.complete?.();\n }\n\n /** @internal */\n protected _subscribe(subscriber: Subscriber<T>): Subscription {\n return this.source?.subscribe(subscriber) ?? EMPTY_SUBSCRIPTION;\n }\n}\n", "import { TimestampProvider } from '../types';\n\ninterface DateTimestampProvider extends TimestampProvider {\n delegate: TimestampProvider | undefined;\n}\n\nexport const dateTimestampProvider: DateTimestampProvider = {\n now() {\n // Use the variable rather than `this` so that the function can be called\n // without being bound to the provider.\n return (dateTimestampProvider.delegate || Date).now();\n },\n delegate: undefined,\n};\n", "import { Subject } from './Subject';\nimport { TimestampProvider } from './types';\nimport { Subscriber } from './Subscriber';\nimport { Subscription } from './Subscription';\nimport { dateTimestampProvider } from './scheduler/dateTimestampProvider';\n\n/**\n * A variant of {@link Subject} that \"replays\" old values to new subscribers by emitting them when they first subscribe.\n *\n * `ReplaySubject` has an internal buffer that will store a specified number of values that it has observed. Like `Subject`,\n * `ReplaySubject` \"observes\" values by having them passed to its `next` method. When it observes a value, it will store that\n * value for a time determined by the configuration of the `ReplaySubject`, as passed to its constructor.\n *\n * When a new subscriber subscribes to the `ReplaySubject` instance, it will synchronously emit all values in its buffer in\n * a First-In-First-Out (FIFO) manner. The `ReplaySubject` will also complete, if it has observed completion; and it will\n * error if it has observed an error.\n *\n * There are two main configuration items to be concerned with:\n *\n * 1. `bufferSize` - This will determine how many items are stored in the buffer, defaults to infinite.\n * 2. `windowTime` - The amount of time to hold a value in the buffer before removing it from the buffer.\n *\n * Both configurations may exist simultaneously. So if you would like to buffer a maximum of 3 values, as long as the values\n * are less than 2 seconds old, you could do so with a `new ReplaySubject(3, 2000)`.\n *\n * ### Differences with BehaviorSubject\n *\n * `BehaviorSubject` is similar to `new ReplaySubject(1)`, with a couple of exceptions:\n *\n * 1. `BehaviorSubject` comes \"primed\" with a single value upon construction.\n * 2. `ReplaySubject` will replay values, even after observing an error, where `BehaviorSubject` will not.\n *\n * @see {@link Subject}\n * @see {@link BehaviorSubject}\n * @see {@link shareReplay}\n */\nexport class ReplaySubject<T> extends Subject<T> {\n private _buffer: (T | number)[] = [];\n private _infiniteTimeWindow = true;\n\n /**\n * @param bufferSize The size of the buffer to replay on subscription\n * @param windowTime The amount of time the buffered items will stay buffered\n * @param timestampProvider An object with a `now()` method that provides the current timestamp. This is used to\n * calculate the amount of time something has been buffered.\n */\n constructor(\n private _bufferSize = Infinity,\n private _windowTime = Infinity,\n private _timestampProvider: TimestampProvider = dateTimestampProvider\n ) {\n super();\n this._infiniteTimeWindow = _windowTime === Infinity;\n this._bufferSize = Math.max(1, _bufferSize);\n this._windowTime = Math.max(1, _windowTime);\n }\n\n next(value: T): void {\n const { isStopped, _buffer, _infiniteTimeWindow, _timestampProvider, _windowTime } = this;\n if (!isStopped) {\n _buffer.push(value);\n !_infiniteTimeWindow && _buffer.push(_timestampProvider.now() + _windowTime);\n }\n this._trimBuffer();\n super.next(value);\n }\n\n /** @internal */\n protected _subscribe(subscriber: Subscriber<T>): Subscription {\n this._throwIfClosed();\n this._trimBuffer();\n\n const subscription = this._innerSubscribe(subscriber);\n\n const { _infiniteTimeWindow, _buffer } = this;\n // We use a copy here, so reentrant code does not mutate our array while we're\n // emitting it to a new subscriber.\n const copy = _buffer.slice();\n for (let i = 0; i < copy.length && !subscriber.closed; i += _infiniteTimeWindow ? 1 : 2) {\n subscriber.next(copy[i] as T);\n }\n\n this._checkFinalizedStatuses(subscriber);\n\n return subscription;\n }\n\n private _trimBuffer() {\n const { _bufferSize, _timestampProvider, _buffer, _infiniteTimeWindow } = this;\n // If we don't have an infinite buffer size, and we're over the length,\n // use splice to truncate the old buffer values off. Note that we have to\n // double the size for instances where we're not using an infinite time window\n // because we're storing the values and the timestamps in the same array.\n const adjustedBufferSize = (_infiniteTimeWindow ? 1 : 2) * _bufferSize;\n _bufferSize < Infinity && adjustedBufferSize < _buffer.length && _buffer.splice(0, _buffer.length - adjustedBufferSize);\n\n // Now, if we're not in an infinite time window, remove all values where the time is\n // older than what is allowed.\n if (!_infiniteTimeWindow) {\n const now = _timestampProvider.now();\n let last = 0;\n // Search the array for the first timestamp that isn't expired and\n // truncate the buffer up to that point.\n for (let i = 1; i < _buffer.length && (_buffer[i] as number) <= now; i += 2) {\n last = i;\n }\n last && _buffer.splice(0, last + 1);\n }\n }\n}\n", "import { Observable } from '../Observable';\nimport { SchedulerLike } from '../types';\n\n/**\n * A simple Observable that emits no items to the Observer and immediately\n * emits a complete notification.\n *\n * <span class=\"informal\">Just emits 'complete', and nothing else.</span>\n *\n * \n *\n * A simple Observable that only emits the complete notification. It can be used\n * for composing with other Observables, such as in a {@link mergeMap}.\n *\n * ## Examples\n *\n * Log complete notification\n *\n * ```ts\n * import { EMPTY } from 'rxjs';\n *\n * EMPTY.subscribe({\n * next: () => console.log('Next'),\n * complete: () => console.log('Complete!')\n * });\n *\n * // Outputs\n * // Complete!\n * ```\n *\n * Emit the number 7, then complete\n *\n * ```ts\n * import { EMPTY, startWith } from 'rxjs';\n *\n * const result = EMPTY.pipe(startWith(7));\n * result.subscribe(x => console.log(x));\n *\n * // Outputs\n * // 7\n * ```\n *\n * Map and flatten only odd numbers to the sequence `'a'`, `'b'`, `'c'`\n *\n * ```ts\n * import { interval, mergeMap, of, EMPTY } from 'rxjs';\n *\n * const interval$ = interval(1000);\n * const result = interval$.pipe(\n * mergeMap(x => x % 2 === 1 ? of('a', 'b', 'c') : EMPTY),\n * );\n * result.subscribe(x => console.log(x));\n *\n * // Results in the following to the console:\n * // x is equal to the count on the interval, e.g. (0, 1, 2, 3, ...)\n * // x will occur every 1000ms\n * // if x % 2 is equal to 1, print a, b, c (each on its own)\n * // if x % 2 is not equal to 1, nothing will be output\n * ```\n *\n * @see {@link Observable}\n * @see {@link NEVER}\n * @see {@link of}\n * @see {@link throwError}\n */\nexport const EMPTY = new Observable<never>((subscriber) => subscriber.complete());\n\n/**\n * @param scheduler A {@link SchedulerLike} to use for scheduling\n * the emission of the complete notification.\n * @deprecated Replaced with the {@link EMPTY} constant or {@link scheduled} (e.g. `scheduled([], scheduler)`). Will be removed in v8.\n */\nexport function empty(scheduler?: SchedulerLike) {\n return scheduler ? emptyScheduled(scheduler) : EMPTY;\n}\n\nfunction emptyScheduled(scheduler: SchedulerLike) {\n return new Observable<never>((subscriber) => scheduler.schedule(() => subscriber.complete()));\n}\n", "import { SchedulerLike } from '../types';\nimport { isFunction } from './isFunction';\n\nexport function isScheduler(value: any): value is SchedulerLike {\n return value && isFunction(value.schedule);\n}\n", "import { SchedulerLike } from '../types';\nimport { isFunction } from './isFunction';\nimport { isScheduler } from './isScheduler';\n\nfunction last<T>(arr: T[]): T | undefined {\n return arr[arr.length - 1];\n}\n\nexport function popResultSelector(args: any[]): ((...args: unknown[]) => unknown) | undefined {\n return isFunction(last(args)) ? args.pop() : undefined;\n}\n\nexport function popScheduler(args: any[]): SchedulerLike | undefined {\n return isScheduler(last(args)) ? args.pop() : undefined;\n}\n\nexport function popNumber(args: any[], defaultValue: number): number {\n return typeof last(args) === 'number' ? args.pop()! : defaultValue;\n}\n", "export const isArrayLike = (<T>(x: any): x is ArrayLike<T> => x && typeof x.length === 'number' && typeof x !== 'function');", "import { isFunction } from \"./isFunction\";\n\n/**\n * Tests to see if the object is \"thennable\".\n * @param value the object to test\n */\nexport function isPromise(value: any): value is PromiseLike<any> {\n return isFunction(value?.then);\n}\n", "import { InteropObservable } from '../types';\nimport { observable as Symbol_observable } from '../symbol/observable';\nimport { isFunction } from './isFunction';\n\n/** Identifies an input as being Observable (but not necessary an Rx Observable) */\nexport function isInteropObservable(input: any): input is InteropObservable<any> {\n return isFunction(input[Symbol_observable]);\n}\n", "import { isFunction } from './isFunction';\n\nexport function isAsyncIterable<T>(obj: any): obj is AsyncIterable<T> {\n return Symbol.asyncIterator && isFunction(obj?.[Symbol.asyncIterator]);\n}\n", "/**\n * Creates the TypeError to throw if an invalid object is passed to `from` or `scheduled`.\n * @param input The object that was passed.\n */\nexport function createInvalidObservableTypeError(input: any) {\n // TODO: We should create error codes that can be looked up, so this can be less verbose.\n return new TypeError(\n `You provided ${\n input !== null && typeof input === 'object' ? 'an invalid object' : `'${input}'`\n } where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable.`\n );\n}\n", "export function getSymbolIterator(): symbol {\n if (typeof Symbol !== 'function' || !Symbol.iterator) {\n return '@@iterator' as any;\n }\n\n return Symbol.iterator;\n}\n\nexport const iterator = getSymbolIterator();\n", "import { iterator as Symbol_iterator } from '../symbol/iterator';\nimport { isFunction } from './isFunction';\n\n/** Identifies an input as being an Iterable */\nexport function isIterable(input: any): input is Iterable<any> {\n return isFunction(input?.[Symbol_iterator]);\n}\n", "import { ReadableStreamLike } from '../types';\nimport { isFunction } from './isFunction';\n\nexport async function* readableStreamLikeToAsyncGenerator<T>(readableStream: ReadableStreamLike<T>): AsyncGenerator<T> {\n const reader = readableStream.getReader();\n try {\n while (true) {\n const { value, done } = await reader.read();\n if (done) {\n return;\n }\n yield value!;\n }\n } finally {\n reader.releaseLock();\n }\n}\n\nexport function isReadableStreamLike<T>(obj: any): obj is ReadableStreamLike<T> {\n // We don't want to use instanceof checks because they would return\n // false for instances from another Realm, like an <iframe>.\n return isFunction(obj?.getReader);\n}\n", "import { isArrayLike } from '../util/isArrayLike';\nimport { isPromise } from '../util/isPromise';\nimport { Observable } from '../Observable';\nimport { ObservableInput, ObservedValueOf, ReadableStreamLike } from '../types';\nimport { isInteropObservable } from '../util/isInteropObservable';\nimport { isAsyncIterable } from '../util/isAsyncIterable';\nimport { createInvalidObservableTypeError } from '../util/throwUnobservableError';\nimport { isIterable } from '../util/isIterable';\nimport { isReadableStreamLike, readableStreamLikeToAsyncGenerator } from '../util/isReadableStreamLike';\nimport { Subscriber } from '../Subscriber';\nimport { isFunction } from '../util/isFunction';\nimport { reportUnhandledError } from '../util/reportUnhandledError';\nimport { observable as Symbol_observable } from '../symbol/observable';\n\nexport function innerFrom<O extends ObservableInput<any>>(input: O): Observable<ObservedValueOf<O>>;\nexport function innerFrom<T>(input: ObservableInput<T>): Observable<T> {\n if (input instanceof Observable) {\n return input;\n }\n if (input != null) {\n if (isInteropObservable(input)) {\n return fromInteropObservable(input);\n }\n if (isArrayLike(input)) {\n return fromArrayLike(input);\n }\n if (isPromise(input)) {\n return fromPromise(input);\n }\n if (isAsyncIterable(input)) {\n return fromAsyncIterable(input);\n }\n if (isIterable(input)) {\n return fromIterable(input);\n }\n if (isReadableStreamLike(input)) {\n return fromReadableStreamLike(input);\n }\n }\n\n throw createInvalidObservableTypeError(input);\n}\n\n/**\n * Creates an RxJS Observable from an object that implements `Symbol.observable`.\n * @param obj An object that properly implements `Symbol.observable`.\n */\nexport function fromInteropObservable<T>(obj: any) {\n return new Observable((subscriber: Subscriber<T>) => {\n const obs = obj[Symbol_observable]();\n if (isFunction(obs.subscribe)) {\n return obs.subscribe(subscriber);\n }\n // Should be caught by observable subscribe function error handling.\n throw new TypeError('Provided object does not correctly implement Symbol.observable');\n });\n}\n\n/**\n * Synchronously emits the values of an array like and completes.\n * This is exported because there are creation functions and operators that need to\n * make direct use of the same logic, and there's no reason to make them run through\n * `from` conditionals because we *know* they're dealing with an array.\n * @param array The array to emit values from\n */\nexport function fromArrayLike<T>(array: ArrayLike<T>) {\n return new Observable((subscriber: Subscriber<T>) => {\n // Loop over the array and emit each value. Note two things here:\n // 1. We're making sure that the subscriber is not closed on each loop.\n // This is so we don't continue looping over a very large array after\n // something like a `take`, `takeWhile`, or other synchronous unsubscription\n // has already unsubscribed.\n // 2. In this form, reentrant code can alter that array we're looping over.\n // This is a known issue, but considered an edge case. The alternative would\n // be to copy the array before executing the loop, but this has\n // performance implications.\n for (let i = 0; i < array.length && !subscriber.closed; i++) {\n subscriber.next(array[i]);\n }\n subscriber.complete();\n });\n}\n\nexport function fromPromise<T>(promise: PromiseLike<T>) {\n return new Observable((subscriber: Subscriber<T>) => {\n promise\n .then(\n (value) => {\n if (!subscriber.closed) {\n subscriber.next(value);\n subscriber.complete();\n }\n },\n (err: any) => subscriber.error(err)\n )\n .then(null, reportUnhandledError);\n });\n}\n\nexport function fromIterable<T>(iterable: Iterable<T>) {\n return new Observable((subscriber: Subscriber<T>) => {\n for (const value of iterable) {\n subscriber.next(value);\n if (subscriber.closed) {\n return;\n }\n }\n subscriber.complete();\n });\n}\n\nexport function fromAsyncIterable<T>(asyncIterable: AsyncIterable<T>) {\n return new Observable((subscriber: Subscriber<T>) => {\n process(asyncIterable, subscriber).catch((err) => subscriber.error(err));\n });\n}\n\nexport function fromReadableStreamLike<T>(readableStream: ReadableStreamLike<T>) {\n return fromAsyncIterable(readableStreamLikeToAsyncGenerator(readableStream));\n}\n\nasync function process<T>(asyncIterable: AsyncIterable<T>, subscriber: Subscriber<T>) {\n for await (const value of asyncIterable) {\n subscriber.next(value);\n // A side-effect may have closed our subscriber,\n // check before the next iteration.\n if (subscriber.closed) {\n return;\n }\n }\n subscriber.complete();\n}\n", "import { Subscription } from '../Subscription';\nimport { SchedulerAction, SchedulerLike } from '../types';\n\nexport function executeSchedule(\n parentSubscription: Subscription,\n scheduler: SchedulerLike,\n work: () => void,\n delay: number,\n repeat: true\n): void;\nexport function executeSchedule(\n parentSubscription: Subscription,\n scheduler: SchedulerLike,\n work: () => void,\n delay?: number,\n repeat?: false\n): Subscription;\n\nexport function executeSchedule(\n parentSubscription: Subscription,\n scheduler: SchedulerLike,\n work: () => void,\n delay = 0,\n repeat = false\n): Subscription | void {\n const scheduleSubscription = scheduler.schedule(function (this: SchedulerAction<any>) {\n work();\n if (repeat) {\n parentSubscription.add(this.schedule(null, delay));\n } else {\n this.unsubscribe();\n }\n }, delay);\n\n parentSubscription.add(scheduleSubscription);\n\n if (!repeat) {\n // Because user-land scheduler implementations are unlikely to properly reuse\n // Actions for repeat scheduling, we can't trust that the returned subscription\n // will control repeat subscription scenarios. So we're trying to avoid using them\n // incorrectly within this library.\n return scheduleSubscription;\n }\n}\n", "/** @prettier */\nimport { MonoTypeOperatorFunction, SchedulerLike } from '../types';\nimport { executeSchedule } from '../util/executeSchedule';\nimport { operate } from '../util/lift';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\n\n/**\n * Re-emits all notifications from source Observable with specified scheduler.\n *\n * <span class=\"informal\">Ensure a specific scheduler is used, from outside of an Observable.</span>\n *\n * `observeOn` is an operator that accepts a scheduler as a first parameter, which will be used to reschedule\n * notifications emitted by the source Observable. It might be useful, if you do not have control over\n * internal scheduler of a given Observable, but want to control when its values are emitted nevertheless.\n *\n * Returned Observable emits the same notifications (nexted values, complete and error events) as the source Observable,\n * but rescheduled with provided scheduler. Note that this doesn't mean that source Observables internal\n * scheduler will be replaced in any way. Original scheduler still will be used, but when the source Observable emits\n * notification, it will be immediately scheduled again - this time with scheduler passed to `observeOn`.\n * An anti-pattern would be calling `observeOn` on Observable that emits lots of values synchronously, to split\n * that emissions into asynchronous chunks. For this to happen, scheduler would have to be passed into the source\n * Observable directly (usually into the operator that creates it). `observeOn` simply delays notifications a\n * little bit more, to ensure that they are emitted at expected moments.\n *\n * As a matter of fact, `observeOn` accepts second parameter, which specifies in milliseconds with what delay notifications\n * will be emitted. The main difference between {@link delay} operator and `observeOn` is that `observeOn`\n * will delay all notifications - including error notifications - while `delay` will pass through error\n * from source Observable immediately when it is emitted. In general it is highly recommended to use `delay` operator\n * for any kind of delaying of values in the stream, while using `observeOn` to specify which scheduler should be used\n * for notification emissions in general.\n *\n * ## Example\n *\n * Ensure values in subscribe are called just before browser repaint\n *\n * ```ts\n * import { interval, observeOn, animationFrameScheduler } from 'rxjs';\n *\n * const someDiv = document.createElement('div');\n * someDiv.style.cssText = 'width: 200px;background: #09c';\n * document.body.appendChild(someDiv);\n * const intervals = interval(10); // Intervals are scheduled\n * // with async scheduler by default...\n * intervals.pipe(\n * observeOn(animationFrameScheduler) // ...but we will observe on animationFrame\n * ) // scheduler to ensure smooth animation.\n * .subscribe(val => {\n * someDiv.style.height = val + 'px';\n * });\n * ```\n *\n * @see {@link delay}\n *\n * @param scheduler Scheduler that will be used to reschedule notifications from source Observable.\n * @param delay Number of milliseconds that states with what delay every notification should be rescheduled.\n * @return A function that returns an Observable that emits the same\n * notifications as the source Observable, but with provided scheduler.\n */\nexport function observeOn<T>(scheduler: SchedulerLike, delay = 0): MonoTypeOperatorFunction<T> {\n return operate((source, subscriber) => {\n source.subscribe(\n createOperatorSubscriber(\n subscriber,\n (value) => executeSchedule(subscriber, scheduler, () => subscriber.next(value), delay),\n () => executeSchedule(subscriber, scheduler, () => subscriber.complete(), delay),\n (err) => executeSchedule(subscriber, scheduler, () => subscriber.error(err), delay)\n )\n );\n });\n}\n", "import { MonoTypeOperatorFunction, SchedulerLike } from '../types';\nimport { operate } from '../util/lift';\n\n/**\n * Asynchronously subscribes Observers to this Observable on the specified {@link SchedulerLike}.\n *\n * With `subscribeOn` you can decide what type of scheduler a specific Observable will be using when it is subscribed to.\n *\n * Schedulers control the speed and order of emissions to observers from an Observable stream.\n *\n * \n *\n * ## Example\n *\n * Given the following code:\n *\n * ```ts\n * import { of, merge } from 'rxjs';\n *\n * const a = of(1, 2, 3);\n * const b = of(4, 5, 6);\n *\n * merge(a, b).subscribe(console.log);\n *\n * // Outputs\n * // 1\n * // 2\n * // 3\n * // 4\n * // 5\n * // 6\n * ```\n *\n * Both Observable `a` and `b` will emit their values directly and synchronously once they are subscribed to.\n *\n * If we instead use the `subscribeOn` operator declaring that we want to use the {@link asyncScheduler} for values emitted by Observable `a`:\n *\n * ```ts\n * import { of, subscribeOn, asyncScheduler, merge } from 'rxjs';\n *\n * const a = of(1, 2, 3).pipe(subscribeOn(asyncScheduler));\n * const b = of(4, 5, 6);\n *\n * merge(a, b).subscribe(console.log);\n *\n * // Outputs\n * // 4\n * // 5\n * // 6\n * // 1\n * // 2\n * // 3\n * ```\n *\n * The reason for this is that Observable `b` emits its values directly and synchronously like before\n * but the emissions from `a` are scheduled on the event loop because we are now using the {@link asyncScheduler} for that specific Observable.\n *\n * @param scheduler The {@link SchedulerLike} to perform subscription actions on.\n * @param delay A delay to pass to the scheduler to delay subscriptions\n * @return A function that returns an Observable modified so that its\n * subscriptions happen on the specified {@link SchedulerLike}.\n */\nexport function subscribeOn<T>(scheduler: SchedulerLike, delay: number = 0): MonoTypeOperatorFunction<T> {\n return operate((source, subscriber) => {\n subscriber.add(scheduler.schedule(() => source.subscribe(subscriber), delay));\n });\n}\n", "import { innerFrom } from '../observable/innerFrom';\nimport { observeOn } from '../operators/observeOn';\nimport { subscribeOn } from '../operators/subscribeOn';\nimport { InteropObservable, SchedulerLike } from '../types';\n\nexport function scheduleObservable<T>(input: InteropObservable<T>, scheduler: SchedulerLike) {\n return innerFrom(input).pipe(subscribeOn(scheduler), observeOn(scheduler));\n}\n", "import { innerFrom } from '../observable/innerFrom';\nimport { observeOn } from '../operators/observeOn';\nimport { subscribeOn } from '../operators/subscribeOn';\nimport { SchedulerLike } from '../types';\n\nexport function schedulePromise<T>(input: PromiseLike<T>, scheduler: SchedulerLike) {\n return innerFrom(input).pipe(subscribeOn(scheduler), observeOn(scheduler));\n}\n", "import { Observable } from '../Observable';\nimport { SchedulerLike } from '../types';\n\nexport function scheduleArray<T>(input: ArrayLike<T>, scheduler: SchedulerLike) {\n return new Observable<T>((subscriber) => {\n // The current array index.\n let i = 0;\n // Start iterating over the array like on a schedule.\n return scheduler.schedule(function () {\n if (i === input.length) {\n // If we have hit the end of the array like in the\n // previous job, we can complete.\n subscriber.complete();\n } else {\n // Otherwise let's next the value at the current index,\n // then increment our index.\n subscriber.next(input[i++]);\n // If the last emission didn't cause us to close the subscriber\n // (via take or some side effect), reschedule the job and we'll\n // make another pass.\n if (!subscriber.closed) {\n this.schedule();\n }\n }\n });\n });\n}\n", "import { Observable } from '../Observable';\nimport { SchedulerLike } from '../types';\nimport { iterator as Symbol_iterator } from '../symbol/iterator';\nimport { isFunction } from '../util/isFunction';\nimport { executeSchedule } from '../util/executeSchedule';\n\n/**\n * Used in {@link scheduled} to create an observable from an Iterable.\n * @param input The iterable to create an observable from\n * @param scheduler The scheduler to use\n */\nexport function scheduleIterable<T>(input: Iterable<T>, scheduler: SchedulerLike) {\n return new Observable<T>((subscriber) => {\n let iterator: Iterator<T, T>;\n\n // Schedule the initial creation of the iterator from\n // the iterable. This is so the code in the iterable is\n // not called until the scheduled job fires.\n executeSchedule(subscriber, scheduler, () => {\n // Create the iterator.\n iterator = (input as any)[Symbol_iterator]();\n\n executeSchedule(\n subscriber,\n scheduler,\n () => {\n let value: T;\n let done: boolean | undefined;\n try {\n // Pull the value out of the iterator\n ({ value, done } = iterator.next());\n } catch (err) {\n // We got an error while pulling from the iterator\n subscriber.error(err);\n return;\n }\n\n if (done) {\n // If it is \"done\" we just complete. This mimics the\n // behavior of JavaScript's `for..of` consumption of\n // iterables, which will not emit the value from an iterator\n // result of `{ done: true: value: 'here' }`.\n subscriber.complete();\n } else {\n // The iterable is not done, emit the value.\n subscriber.next(value);\n }\n },\n 0,\n true\n );\n });\n\n // During finalization, if we see this iterator has a `return` method,\n // then we know it is a Generator, and not just an Iterator. So we call\n // the `return()` function. This will ensure that any `finally { }` blocks\n // inside of the generator we can hit will be hit properly.\n return () => isFunction(iterator?.return) && iterator.return();\n });\n}\n", "import { SchedulerLike } from '../types';\nimport { Observable } from '../Observable';\nimport { executeSchedule } from '../util/executeSchedule';\n\nexport function scheduleAsyncIterable<T>(input: AsyncIterable<T>, scheduler: SchedulerLike) {\n if (!input) {\n throw new Error('Iterable cannot be null');\n }\n return new Observable<T>((subscriber) => {\n executeSchedule(subscriber, scheduler, () => {\n const iterator = input[Symbol.asyncIterator]();\n executeSchedule(\n subscriber,\n scheduler,\n () => {\n iterator.next().then((result) => {\n if (result.done) {\n // This will remove the subscriptions from\n // the parent subscription.\n subscriber.complete();\n } else {\n subscriber.next(result.value);\n }\n });\n },\n 0,\n true\n );\n });\n });\n}\n", "import { SchedulerLike, ReadableStreamLike } from '../types';\nimport { Observable } from '../Observable';\nimport { scheduleAsyncIterable } from './scheduleAsyncIterable';\nimport { readableStreamLikeToAsyncGenerator } from '../util/isReadableStreamLike';\n\nexport function scheduleReadableStreamLike<T>(input: ReadableStreamLike<T>, scheduler: SchedulerLike): Observable<T> {\n return scheduleAsyncIterable(readableStreamLikeToAsyncGenerator(input), scheduler);\n}\n", "import { scheduleObservable } from './scheduleObservable';\nimport { schedulePromise } from './schedulePromise';\nimport { scheduleArray } from './scheduleArray';\nimport { scheduleIterable } from './scheduleIterable';\nimport { scheduleAsyncIterable } from './scheduleAsyncIterable';\nimport { isInteropObservable } from '../util/isInteropObservable';\nimport { isPromise } from '../util/isPromise';\nimport { isArrayLike } from '../util/isArrayLike';\nimport { isIterable } from '../util/isIterable';\nimport { ObservableInput, SchedulerLike } from '../types';\nimport { Observable } from '../Observable';\nimport { isAsyncIterable } from '../util/isAsyncIterable';\nimport { createInvalidObservableTypeError } from '../util/throwUnobservableError';\nimport { isReadableStreamLike } from '../util/isReadableStreamLike';\nimport { scheduleReadableStreamLike } from './scheduleReadableStreamLike';\n\n/**\n * Converts from a common {@link ObservableInput} type to an observable where subscription and emissions\n * are scheduled on the provided scheduler.\n *\n * @see {@link from}\n * @see {@link of}\n *\n * @param input The observable, array, promise, iterable, etc you would like to schedule\n * @param scheduler The scheduler to use to schedule the subscription and emissions from\n * the returned observable.\n */\nexport function scheduled<T>(input: ObservableInput<T>, scheduler: SchedulerLike): Observable<T> {\n if (input != null) {\n if (isInteropObservable(input)) {\n return scheduleObservable(input, scheduler);\n }\n if (isArrayLike(input)) {\n return scheduleArray(input, scheduler);\n }\n if (isPromise(input)) {\n return schedulePromise(input, scheduler);\n }\n if (isAsyncIterable(input)) {\n return scheduleAsyncIterable(input, scheduler);\n }\n if (isIterable(input)) {\n return scheduleIterable(input, scheduler);\n }\n if (isReadableStreamLike(input)) {\n return scheduleReadableStreamLike(input, scheduler);\n }\n }\n throw createInvalidObservableTypeError(input);\n}\n", "import { Observable } from '../Observable';\nimport { ObservableInput, SchedulerLike, ObservedValueOf } from '../types';\nimport { scheduled } from '../scheduled/scheduled';\nimport { innerFrom } from './innerFrom';\n\nexport function from<O extends ObservableInput<any>>(input: O): Observable<ObservedValueOf<O>>;\n/** @deprecated The `scheduler` parameter will be removed in v8. Use `scheduled`. Details: https://rxjs.dev/deprecations/scheduler-argument */\nexport function from<O extends ObservableInput<any>>(input: O, scheduler: SchedulerLike | undefined): Observable<ObservedValueOf<O>>;\n\n/**\n * Creates an Observable from an Array, an array-like object, a Promise, an iterable object, or an Observable-like object.\n *\n * <span class=\"informal\">Converts almost anything to an Observable.</span>\n *\n * \n *\n * `from` converts various other objects and data types into Observables. It also converts a Promise, an array-like, or an\n * <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#iterable\" target=\"_blank\">iterable</a>\n * object into an Observable that emits the items in that promise, array, or iterable. A String, in this context, is treated\n * as an array of characters. Observable-like objects (contains a function named with the ES2015 Symbol for Observable) can also be\n * converted through this operator.\n *\n * ## Examples\n *\n * Converts an array to an Observable\n *\n * ```ts\n * import { from } from 'rxjs';\n *\n * const array = [10, 20, 30];\n * const result = from(array);\n *\n * result.subscribe(x => console.log(x));\n *\n * // Logs:\n * // 10\n * // 20\n * // 30\n * ```\n *\n * Convert an infinite iterable (from a generator) to an Observable\n *\n * ```ts\n * import { from, take } from 'rxjs';\n *\n * function* generateDoubles(seed) {\n * let i = seed;\n * while (true) {\n * yield i;\n * i = 2 * i; // double it\n * }\n * }\n *\n * const iterator = generateDoubles(3);\n * const result = from(iterator).pipe(take(10));\n *\n * result.subscribe(x => console.log(x));\n *\n * // Logs:\n * // 3\n * // 6\n * // 12\n * // 24\n * // 48\n * // 96\n * // 192\n * // 384\n * // 768\n * // 1536\n * ```\n *\n * With `asyncScheduler`\n *\n * ```ts\n * import { from, asyncScheduler } from 'rxjs';\n *\n * console.log('start');\n *\n * const array = [10, 20, 30];\n * const result = from(array, asyncScheduler);\n *\n * result.subscribe(x => console.log(x));\n *\n * console.log('end');\n *\n * // Logs:\n * // 'start'\n * // 'end'\n * // 10\n * // 20\n * // 30\n * ```\n *\n * @see {@link fromEvent}\n * @see {@link fromEventPattern}\n *\n * @param {ObservableInput<T>} A subscription object, a Promise, an Observable-like,\n * an Array, an iterable, or an array-like object to be converted.\n * @param {SchedulerLike} An optional {@link SchedulerLike} on which to schedule the emission of values.\n * @return {Observable<T>}\n */\nexport function from<T>(input: ObservableInput<T>, scheduler?: SchedulerLike): Observable<T> {\n return scheduler ? scheduled(input, scheduler) : innerFrom(input);\n}\n", "import { SchedulerLike, ValueFromArray } from '../types';\nimport { Observable } from '../Observable';\nimport { popScheduler } from '../util/args';\nimport { from } from './from';\n\n// Devs are more likely to pass null or undefined than they are a scheduler\n// without accompanying values. To make things easier for (naughty) devs who\n// use the `strictNullChecks: false` TypeScript compiler option, these\n// overloads with explicit null and undefined values are included.\n\nexport function of(value: null): Observable<null>;\nexport function of(value: undefined): Observable<undefined>;\n\n/** @deprecated The `scheduler` parameter will be removed in v8. Use `scheduled`. Details: https://rxjs.dev/deprecations/scheduler-argument */\nexport function of(scheduler: SchedulerLike): Observable<never>;\n/** @deprecated The `scheduler` parameter will be removed in v8. Use `scheduled`. Details: https://rxjs.dev/deprecations/scheduler-argument */\nexport function of<A extends readonly unknown[]>(...valuesAndScheduler: [...A, SchedulerLike]): Observable<ValueFromArray<A>>;\n\nexport function of(): Observable<never>;\n/** @deprecated Do not specify explicit type parameters. Signatures with type parameters that cannot be inferred will be removed in v8. */\nexport function of<T>(): Observable<T>;\nexport function of<T>(value: T): Observable<T>;\nexport function of<A extends readonly unknown[]>(...values: A): Observable<ValueFromArray<A>>;\n\n/**\n * Converts the arguments to an observable sequence.\n *\n * <span class=\"informal\">Each argument becomes a `next` notification.</span>\n *\n * \n *\n * Unlike {@link from}, it does not do any flattening and emits each argument in whole\n * as a separate `next` notification.\n *\n * ## Examples\n *\n * Emit the values `10, 20, 30`\n *\n * ```ts\n * import { of } from 'rxjs';\n *\n * of(10, 20, 30)\n * .subscribe({\n * next: value => console.log('next:', value),\n * error: err => console.log('error:', err),\n * complete: () => console.log('the end'),\n * });\n *\n * // Outputs\n * // next: 10\n * // next: 20\n * // next: 30\n * // the end\n * ```\n *\n * Emit the array `[1, 2, 3]`\n *\n * ```ts\n * import { of } from 'rxjs';\n *\n * of([1, 2, 3])\n * .subscribe({\n * next: value => console.log('next:', value),\n * error: err => console.log('error:', err),\n * complete: () => console.log('the end'),\n * });\n *\n * // Outputs\n * // next: [1, 2, 3]\n * // the end\n * ```\n *\n * @see {@link from}\n * @see {@link range}\n *\n * @param {...T} values A comma separated list of arguments you want to be emitted\n * @return {Observable} An Observable that emits the arguments\n * described above and then completes.\n */\nexport function of<T>(...args: Array<T | SchedulerLike>): Observable<T> {\n const scheduler = popScheduler(args);\n return from(args as T[], scheduler);\n}\n", "import { Observable } from '../Observable';\nimport { Subscriber } from '../Subscriber';\nimport { SchedulerLike } from '../types';\nimport { isFunction } from '../util/isFunction';\n\n/**\n * Creates an observable that will create an error instance and push it to the consumer as an error\n * immediately upon subscription.\n *\n * <span class=\"informal\">Just errors and does nothing else</span>\n *\n * \n *\n * This creation function is useful for creating an observable that will create an error and error every\n * time it is subscribed to. Generally, inside of most operators when you might want to return an errored\n * observable, this is unnecessary. In most cases, such as in the inner return of {@link concatMap},\n * {@link mergeMap}, {@link defer}, and many others, you can simply throw the error, and RxJS will pick\n * that up and notify the consumer of the error.\n *\n * ## Example\n *\n * Create a simple observable that will create a new error with a timestamp and log it\n * and the message every time you subscribe to it\n *\n * ```ts\n * import { throwError } from 'rxjs';\n *\n * let errorCount = 0;\n *\n * const errorWithTimestamp$ = throwError(() => {\n * const error: any = new Error(`This is error number ${ ++errorCount }`);\n * error.timestamp = Date.now();\n * return error;\n * });\n *\n * errorWithTimestamp$.subscribe({\n * error: err => console.log(err.timestamp, err.message)\n * });\n *\n * errorWithTimestamp$.subscribe({\n * error: err => console.log(err.timestamp, err.message)\n * });\n *\n * // Logs the timestamp and a new error message for each subscription\n * ```\n *\n * ### Unnecessary usage\n *\n * Using `throwError` inside of an operator or creation function\n * with a callback, is usually not necessary\n *\n * ```ts\n * import { of, concatMap, timer, throwError } from 'rxjs';\n *\n * const delays$ = of(1000, 2000, Infinity, 3000);\n *\n * delays$.pipe(\n * concatMap(ms => {\n * if (ms < 10000) {\n * return timer(ms);\n * } else {\n * // This is probably overkill.\n * return throwError(() => new Error(`Invalid time ${ ms }`));\n * }\n * })\n * )\n * .subscribe({\n * next: console.log,\n * error: console.error\n * });\n * ```\n *\n * You can just throw the error instead\n *\n * ```ts\n * import { of, concatMap, timer } from 'rxjs';\n *\n * const delays$ = of(1000, 2000, Infinity, 3000);\n *\n * delays$.pipe(\n * concatMap(ms => {\n * if (ms < 10000) {\n * return timer(ms);\n * } else {\n * // Cleaner and easier to read for most folks.\n * throw new Error(`Invalid time ${ ms }`);\n * }\n * })\n * )\n * .subscribe({\n * next: console.log,\n * error: console.error\n * });\n * ```\n *\n * @param errorFactory A factory function that will create the error instance that is pushed.\n */\nexport function throwError(errorFactory: () => any): Observable<never>;\n\n/**\n * Returns an observable that will error with the specified error immediately upon subscription.\n *\n * @param error The error instance to emit\n * @deprecated Support for passing an error value will be removed in v8. Instead, pass a factory function to `throwError(() => new Error('test'))`. This is\n * because it will create the error at the moment it should be created and capture a more appropriate stack trace. If\n * for some reason you need to create the error ahead of time, you can still do that: `const err = new Error('test'); throwError(() => err);`.\n */\nexport function throwError(error: any): Observable<never>;\n\n/**\n * Notifies the consumer of an error using a given scheduler by scheduling it at delay `0` upon subscription.\n *\n * @param errorOrErrorFactory An error instance or error factory\n * @param scheduler A scheduler to use to schedule the error notification\n * @deprecated The `scheduler` parameter will be removed in v8.\n * Use `throwError` in combination with {@link observeOn}: `throwError(() => new Error('test')).pipe(observeOn(scheduler));`.\n * Details: https://rxjs.dev/deprecations/scheduler-argument\n */\nexport function throwError(errorOrErrorFactory: any, scheduler: SchedulerLike): Observable<never>;\n\nexport function throwError(errorOrErrorFactory: any, scheduler?: SchedulerLike): Observable<never> {\n const errorFactory = isFunction(errorOrErrorFactory) ? errorOrErrorFactory : () => errorOrErrorFactory;\n const init = (subscriber: Subscriber<never>) => subscriber.error(errorFactory());\n return new Observable(scheduler ? (subscriber) => scheduler.schedule(init as any, 0, subscriber) : init);\n}\n", "import { createErrorClass } from './createErrorClass';\n\nexport interface EmptyError extends Error {}\n\nexport interface EmptyErrorCtor {\n /**\n * @deprecated Internal implementation detail. Do not construct error instances.\n * Cannot be tagged as internal: https://github.com/ReactiveX/rxjs/issues/6269\n */\n new (): EmptyError;\n}\n\n/**\n * An error thrown when an Observable or a sequence was queried but has no\n * elements.\n *\n * @see {@link first}\n * @see {@link last}\n * @see {@link single}\n * @see {@link firstValueFrom}\n * @see {@link lastValueFrom}\n *\n * @class EmptyError\n */\nexport const EmptyError: EmptyErrorCtor = createErrorClass((_super) => function EmptyErrorImpl(this: any) {\n _super(this);\n this.name = 'EmptyError';\n this.message = 'no elements in sequence';\n});\n", "import { Observable } from './Observable';\nimport { EmptyError } from './util/EmptyError';\n\nexport interface LastValueFromConfig<T> {\n defaultValue: T;\n}\n\nexport function lastValueFrom<T, D>(source: Observable<T>, config: LastValueFromConfig<D>): Promise<T | D>;\nexport function lastValueFrom<T>(source: Observable<T>): Promise<T>;\n\n/**\n * Converts an observable to a promise by subscribing to the observable,\n * waiting for it to complete, and resolving the returned promise with the\n * last value from the observed stream.\n *\n * If the observable stream completes before any values were emitted, the\n * returned promise will reject with {@link EmptyError} or will resolve\n * with the default value if a default was specified.\n *\n * If the observable stream emits an error, the returned promise will reject\n * with that error.\n *\n * **WARNING**: Only use this with observables you *know* will complete. If the source\n * observable does not complete, you will end up with a promise that is hung up, and\n * potentially all of the state of an async function hanging out in memory. To avoid\n * this situation, look into adding something like {@link timeout}, {@link take},\n * {@link takeWhile}, or {@link takeUntil} amongst others.\n *\n * ## Example\n *\n * Wait for the last value from a stream and emit it from a promise in\n * an async function\n *\n * ```ts\n * import { interval, take, lastValueFrom } from 'rxjs';\n *\n * async function execute() {\n * const source$ = interval(2000).pipe(take(10));\n * const finalNumber = await lastValueFrom(source$);\n * console.log(`The final number is ${ finalNumber }`);\n * }\n *\n * execute();\n *\n * // Expected output:\n * // 'The final number is 9'\n * ```\n *\n * @see {@link firstValueFrom}\n *\n * @param source the observable to convert to a promise\n * @param config a configuration object to define the `defaultValue` to use if the source completes without emitting a value\n */\nexport function lastValueFrom<T, D>(source: Observable<T>, config?: LastValueFromConfig<D>): Promise<T | D> {\n const hasConfig = typeof config === 'object';\n return new Promise<T | D>((resolve, reject) => {\n let _hasValue = false;\n let _value: T;\n source.subscribe({\n next: (value) => {\n _value = value;\n _hasValue = true;\n },\n error: reject,\n complete: () => {\n if (_hasValue) {\n resolve(_value);\n } else if (hasConfig) {\n resolve(config!.defaultValue);\n } else {\n reject(new EmptyError());\n }\n },\n });\n });\n}\n", "import { OperatorFunction } from '../types';\nimport { operate } from '../util/lift';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\n\nexport function map<T, R>(project: (value: T, index: number) => R): OperatorFunction<T, R>;\n/** @deprecated Use a closure instead of a `thisArg`. Signatures accepting a `thisArg` will be removed in v8. */\nexport function map<T, R, A>(project: (this: A, value: T, index: number) => R, thisArg: A): OperatorFunction<T, R>;\n\n/**\n * Applies a given `project` function to each value emitted by the source\n * Observable, and emits the resulting values as an Observable.\n *\n * <span class=\"informal\">Like [Array.prototype.map()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map),\n * it passes each source value through a transformation function to get\n * corresponding output values.</span>\n *\n * \n *\n * Similar to the well known `Array.prototype.map` function, this operator\n * applies a projection to each value and emits that projection in the output\n * Observable.\n *\n * ## Example\n *\n * Map every click to the `clientX` position of that click\n *\n * ```ts\n * import { fromEvent, map } from 'rxjs';\n *\n * const clicks = fromEvent<PointerEvent>(document, 'click');\n * const positions = clicks.pipe(map(ev => ev.clientX));\n *\n * positions.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link mapTo}\n * @see {@link pluck}\n *\n * @param {function(value: T, index: number): R} project The function to apply\n * to each `value` emitted by the source Observable. The `index` parameter is\n * the number `i` for the i-th emission that has happened since the\n * subscription, starting from the number `0`.\n * @param {any} [thisArg] An optional argument to define what `this` is in the\n * `project` function.\n * @return A function that returns an Observable that emits the values from the\n * source Observable transformed by the given `project` function.\n */\nexport function map<T, R>(project: (value: T, index: number) => R, thisArg?: any): OperatorFunction<T, R> {\n return operate((source, subscriber) => {\n // The index of the value from the source. Used with projection.\n let index = 0;\n // Subscribe to the source, all errors and completions are sent along\n // to the consumer.\n source.subscribe(\n createOperatorSubscriber(subscriber, (value: T) => {\n // Call the projection function with the appropriate this context,\n // and send the resulting value to the consumer.\n subscriber.next(project.call(thisArg, value, index++));\n })\n );\n });\n}\n", "import { Observable } from '../Observable';\nimport { innerFrom } from '../observable/innerFrom';\nimport { Subscriber } from '../Subscriber';\nimport { ObservableInput, SchedulerLike } from '../types';\nimport { executeSchedule } from '../util/executeSchedule';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\n\n/**\n * A process embodying the general \"merge\" strategy. This is used in\n * `mergeMap` and `mergeScan` because the logic is otherwise nearly identical.\n * @param source The original source observable\n * @param subscriber The consumer subscriber\n * @param project The projection function to get our inner sources\n * @param concurrent The number of concurrent inner subscriptions\n * @param onBeforeNext Additional logic to apply before nexting to our consumer\n * @param expand If `true` this will perform an \"expand\" strategy, which differs only\n * in that it recurses, and the inner subscription must be schedule-able.\n * @param innerSubScheduler A scheduler to use to schedule inner subscriptions,\n * this is to support the expand strategy, mostly, and should be deprecated\n */\nexport function mergeInternals<T, R>(\n source: Observable<T>,\n subscriber: Subscriber<R>,\n project: (value: T, index: number) => ObservableInput<R>,\n concurrent: number,\n onBeforeNext?: (innerValue: R) => void,\n expand?: boolean,\n innerSubScheduler?: SchedulerLike,\n additionalFinalizer?: () => void\n) {\n // Buffered values, in the event of going over our concurrency limit\n const buffer: T[] = [];\n // The number of active inner subscriptions.\n let active = 0;\n // An index to pass to our accumulator function\n let index = 0;\n // Whether or not the outer source has completed.\n let isComplete = false;\n\n /**\n * Checks to see if we can complete our result or not.\n */\n const checkComplete = () => {\n // If the outer has completed, and nothing is left in the buffer,\n // and we don't have any active inner subscriptions, then we can\n // Emit the state and complete.\n if (isComplete && !buffer.length && !active) {\n subscriber.complete();\n }\n };\n\n // If we're under our concurrency limit, just start the inner subscription, otherwise buffer and wait.\n const outerNext = (value: T) => (active < concurrent ? doInnerSub(value) : buffer.push(value));\n\n const doInnerSub = (value: T) => {\n // If we're expanding, we need to emit the outer values and the inner values\n // as the inners will \"become outers\" in a way as they are recursively fed\n // back to the projection mechanism.\n expand && subscriber.next(value as any);\n\n // Increment the number of active subscriptions so we can track it\n // against our concurrency limit later.\n active++;\n\n // A flag used to show that the inner observable completed.\n // This is checked during finalization to see if we should\n // move to the next item in the buffer, if there is on.\n let innerComplete = false;\n\n // Start our inner subscription.\n innerFrom(project(value, index++)).subscribe(\n createOperatorSubscriber(\n subscriber,\n (innerValue) => {\n // `mergeScan` has additional handling here. For example\n // taking the inner value and updating state.\n onBeforeNext?.(innerValue);\n\n if (expand) {\n // If we're expanding, then just recurse back to our outer\n // handler. It will emit the value first thing.\n outerNext(innerValue as any);\n } else {\n // Otherwise, emit the inner value.\n subscriber.next(innerValue);\n }\n },\n () => {\n // Flag that we have completed, so we know to check the buffer\n // during finalization.\n innerComplete = true;\n },\n // Errors are passed to the destination.\n undefined,\n () => {\n // During finalization, if the inner completed (it wasn't errored or\n // cancelled), then we want to try the next item in the buffer if\n // there is one.\n if (innerComplete) {\n // We have to wrap this in a try/catch because it happens during\n // finalization, possibly asynchronously, and we want to pass\n // any errors that happen (like in a projection function) to\n // the outer Subscriber.\n try {\n // INNER SOURCE COMPLETE\n // Decrement the active count to ensure that the next time\n // we try to call `doInnerSub`, the number is accurate.\n active--;\n // If we have more values in the buffer, try to process those\n // Note that this call will increment `active` ahead of the\n // next conditional, if there were any more inner subscriptions\n // to start.\n while (buffer.length && active < concurrent) {\n const bufferedValue = buffer.shift()!;\n // Particularly for `expand`, we need to check to see if a scheduler was provided\n // for when we want to start our inner subscription. Otherwise, we just start\n // are next inner subscription.\n if (innerSubScheduler) {\n executeSchedule(subscriber, innerSubScheduler, () => doInnerSub(bufferedValue));\n } else {\n doInnerSub(bufferedValue);\n }\n }\n // Check to see if we can complete, and complete if so.\n checkComplete();\n } catch (err) {\n subscriber.error(err);\n }\n }\n }\n )\n );\n };\n\n // Subscribe to our source observable.\n source.subscribe(\n createOperatorSubscriber(subscriber, outerNext, () => {\n // Outer completed, make a note of it, and check to see if we can complete everything.\n isComplete = true;\n checkComplete();\n })\n );\n\n // Additional finalization (for when the destination is torn down).\n // Other finalization is added implicitly via subscription above.\n return () => {\n additionalFinalizer?.();\n };\n}\n", "import { ObservableInput, OperatorFunction, ObservedValueOf } from '../types';\nimport { map } from './map';\nimport { innerFrom } from '../observable/innerFrom';\nimport { operate } from '../util/lift';\nimport { mergeInternals } from './mergeInternals';\nimport { isFunction } from '../util/isFunction';\n\n/* tslint:disable:max-line-length */\nexport function mergeMap<T, O extends ObservableInput<any>>(\n project: (value: T, index: number) => O,\n concurrent?: number\n): OperatorFunction<T, ObservedValueOf<O>>;\n/** @deprecated The `resultSelector` parameter will be removed in v8. Use an inner `map` instead. Details: https://rxjs.dev/deprecations/resultSelector */\nexport function mergeMap<T, O extends ObservableInput<any>>(\n project: (value: T, index: number) => O,\n resultSelector: undefined,\n concurrent?: number\n): OperatorFunction<T, ObservedValueOf<O>>;\n/** @deprecated The `resultSelector` parameter will be removed in v8. Use an inner `map` instead. Details: https://rxjs.dev/deprecations/resultSelector */\nexport function mergeMap<T, R, O extends ObservableInput<any>>(\n project: (value: T, index: number) => O,\n resultSelector: (outerValue: T, innerValue: ObservedValueOf<O>, outerIndex: number, innerIndex: number) => R,\n concurrent?: number\n): OperatorFunction<T, R>;\n/* tslint:enable:max-line-length */\n\n/**\n * Projects each source value to an Observable which is merged in the output\n * Observable.\n *\n * <span class=\"informal\">Maps each value to an Observable, then flattens all of\n * these inner Observables using {@link mergeAll}.</span>\n *\n * \n *\n * Returns an Observable that emits items based on applying a function that you\n * supply to each item emitted by the source Observable, where that function\n * returns an Observable, and then merging those resulting Observables and\n * emitting the results of this merger.\n *\n * ## Example\n *\n * Map and flatten each letter to an Observable ticking every 1 second\n *\n * ```ts\n * import { of, mergeMap, interval, map } from 'rxjs';\n *\n * const letters = of('a', 'b', 'c');\n * const result = letters.pipe(\n * mergeMap(x => interval(1000).pipe(map(i => x + i)))\n * );\n *\n * result.subscribe(x => console.log(x));\n *\n * // Results in the following:\n * // a0\n * // b0\n * // c0\n * // a1\n * // b1\n * // c1\n * // continues to list a, b, c every second with respective ascending integers\n * ```\n *\n * @see {@link concatMap}\n * @see {@link exhaustMap}\n * @see {@link merge}\n * @see {@link mergeAll}\n * @see {@link mergeMapTo}\n * @see {@link mergeScan}\n * @see {@link switchMap}\n *\n * @param {function(value: T, ?index: number): ObservableInput} project A function\n * that, when applied to an item emitted by the source Observable, returns an\n * Observable.\n * @param {number} [concurrent=Infinity] Maximum number of input\n * Observables being subscribed to concurrently.\n * @return A function that returns an Observable that emits the result of\n * applying the projection function (and the optional deprecated\n * `resultSelector`) to each item emitted by the source Observable and merging\n * the results of the Observables obtained from this transformation.\n */\nexport function mergeMap<T, R, O extends ObservableInput<any>>(\n project: (value: T, index: number) => O,\n resultSelector?: ((outerValue: T, innerValue: ObservedValueOf<O>, outerIndex: number, innerIndex: number) => R) | number,\n concurrent: number = Infinity\n): OperatorFunction<T, ObservedValueOf<O> | R> {\n if (isFunction(resultSelector)) {\n // DEPRECATED PATH\n return mergeMap((a, i) => map((b: any, ii: number) => resultSelector(a, b, i, ii))(innerFrom(project(a, i))), concurrent);\n } else if (typeof resultSelector === 'number') {\n concurrent = resultSelector;\n }\n\n return operate((source, subscriber) => mergeInternals(source, subscriber, project, concurrent));\n}\n", "import { mergeMap } from './mergeMap';\nimport { identity } from '../util/identity';\nimport { OperatorFunction, ObservableInput, ObservedValueOf } from '../types';\n\n/**\n * Converts a higher-order Observable into a first-order Observable which\n * concurrently delivers all values that are emitted on the inner Observables.\n *\n * <span class=\"informal\">Flattens an Observable-of-Observables.</span>\n *\n * \n *\n * `mergeAll` subscribes to an Observable that emits Observables, also known as\n * a higher-order Observable. Each time it observes one of these emitted inner\n * Observables, it subscribes to that and delivers all the values from the\n * inner Observable on the output Observable. The output Observable only\n * completes once all inner Observables have completed. Any error delivered by\n * a inner Observable will be immediately emitted on the output Observable.\n *\n * ## Examples\n *\n * Spawn a new interval Observable for each click event, and blend their outputs as one Observable\n *\n * ```ts\n * import { fromEvent, map, interval, mergeAll } from 'rxjs';\n *\n * const clicks = fromEvent(document, 'click');\n * const higherOrder = clicks.pipe(map(() => interval(1000)));\n * const firstOrder = higherOrder.pipe(mergeAll());\n *\n * firstOrder.subscribe(x => console.log(x));\n * ```\n *\n * Count from 0 to 9 every second for each click, but only allow 2 concurrent timers\n *\n * ```ts\n * import { fromEvent, map, interval, take, mergeAll } from 'rxjs';\n *\n * const clicks = fromEvent(document, 'click');\n * const higherOrder = clicks.pipe(\n * map(() => interval(1000).pipe(take(10)))\n * );\n * const firstOrder = higherOrder.pipe(mergeAll(2));\n *\n * firstOrder.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link combineLatestAll}\n * @see {@link concatAll}\n * @see {@link exhaustAll}\n * @see {@link merge}\n * @see {@link mergeMap}\n * @see {@link mergeMapTo}\n * @see {@link mergeScan}\n * @see {@link switchAll}\n * @see {@link switchMap}\n * @see {@link zipAll}\n *\n * @param {number} [concurrent=Infinity] Maximum number of inner\n * Observables being subscribed to concurrently.\n * @return A function that returns an Observable that emits values coming from\n * all the inner Observables emitted by the source Observable.\n */\nexport function mergeAll<O extends ObservableInput<any>>(concurrent: number = Infinity): OperatorFunction<O, ObservedValueOf<O>> {\n return mergeMap(identity, concurrent);\n}\n", "import { Observable } from '../Observable';\nimport { ObservedValueOf, ObservableInput } from '../types';\nimport { innerFrom } from './innerFrom';\n\n/**\n * Creates an Observable that, on subscribe, calls an Observable factory to\n * make an Observable for each new Observer.\n *\n * <span class=\"informal\">Creates the Observable lazily, that is, only when it\n * is subscribed.\n * </span>\n *\n * \n *\n * `defer` allows you to create an Observable only when the Observer\n * subscribes. It waits until an Observer subscribes to it, calls the given\n * factory function to get an Observable -- where a factory function typically\n * generates a new Observable -- and subscribes the Observer to this Observable.\n * In case the factory function returns a falsy value, then EMPTY is used as\n * Observable instead. Last but not least, an exception during the factory\n * function call is transferred to the Observer by calling `error`.\n *\n * ## Example\n *\n * Subscribe to either an Observable of clicks or an Observable of interval, at random\n *\n * ```ts\n * import { defer, fromEvent, interval } from 'rxjs';\n *\n * const clicksOrInterval = defer(() => {\n * return Math.random() > 0.5\n * ? fromEvent(document, 'click')\n * : interval(1000);\n * });\n * clicksOrInterval.subscribe(x => console.log(x));\n *\n * // Results in the following behavior:\n * // If the result of Math.random() is greater than 0.5 it will listen\n * // for clicks anywhere on the \"document\"; when document is clicked it\n * // will log a MouseEvent object to the console. If the result is less\n * // than 0.5 it will emit ascending numbers, one every second(1000ms).\n * ```\n *\n * @see {@link Observable}\n *\n * @param {function(): ObservableInput} observableFactory The Observable\n * factory function to invoke for each Observer that subscribes to the output\n * Observable. May also return a Promise, which will be converted on the fly\n * to an Observable.\n * @return {Observable} An Observable whose Observers' subscriptions trigger\n * an invocation of the given Observable factory function.\n */\nexport function defer<R extends ObservableInput<any>>(observableFactory: () => R): Observable<ObservedValueOf<R>> {\n return new Observable<ObservedValueOf<R>>((subscriber) => {\n innerFrom(observableFactory()).subscribe(subscriber);\n });\n}\n", "import { Observable } from '../Observable';\n\nimport { ObservableInput, OperatorFunction, ObservedValueOf } from '../types';\nimport { Subscription } from '../Subscription';\nimport { innerFrom } from '../observable/innerFrom';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\nimport { operate } from '../util/lift';\n\n/* tslint:disable:max-line-length */\nexport function catchError<T, O extends ObservableInput<any>>(\n selector: (err: any, caught: Observable<T>) => O\n): OperatorFunction<T, T | ObservedValueOf<O>>;\n/* tslint:enable:max-line-length */\n\n/**\n * Catches errors on the observable to be handled by returning a new observable or throwing an error.\n *\n * <span class=\"informal\">\n * It only listens to the error channel and ignores notifications.\n * Handles errors from the source observable, and maps them to a new observable.\n * The error may also be rethrown, or a new error can be thrown to emit an error from the result.\n * </span>\n *\n * \n *\n * This operator handles errors, but forwards along all other events to the resulting observable.\n * If the source observable terminates with an error, it will map that error to a new observable,\n * subscribe to it, and forward all of its events to the resulting observable.\n *\n * ## Examples\n *\n * Continue with a different Observable when there's an error\n *\n * ```ts\n * import { of, map, catchError } from 'rxjs';\n *\n * of(1, 2, 3, 4, 5)\n * .pipe(\n * map(n => {\n * if (n === 4) {\n * throw 'four!';\n * }\n * return n;\n * }),\n * catchError(err => of('I', 'II', 'III', 'IV', 'V'))\n * )\n * .subscribe(x => console.log(x));\n * // 1, 2, 3, I, II, III, IV, V\n * ```\n *\n * Retry the caught source Observable again in case of error, similar to `retry()` operator\n *\n * ```ts\n * import { of, map, catchError, take } from 'rxjs';\n *\n * of(1, 2, 3, 4, 5)\n * .pipe(\n * map(n => {\n * if (n === 4) {\n * throw 'four!';\n * }\n * return n;\n * }),\n * catchError((err, caught) => caught),\n * take(30)\n * )\n * .subscribe(x => console.log(x));\n * // 1, 2, 3, 1, 2, 3, ...\n * ```\n *\n * Throw a new error when the source Observable throws an error\n *\n * ```ts\n * import { of, map, catchError } from 'rxjs';\n *\n * of(1, 2, 3, 4, 5)\n * .pipe(\n * map(n => {\n * if (n === 4) {\n * throw 'four!';\n * }\n * return n;\n * }),\n * catchError(err => {\n * throw 'error in source. Details: ' + err;\n * })\n * )\n * .subscribe({\n * next: x => console.log(x),\n * error: err => console.log(err)\n * });\n * // 1, 2, 3, error in source. Details: four!\n * ```\n *\n * @see {@link onErrorResumeNext}\n * @see {@link repeat}\n * @see {@link repeatWhen}\n * @see {@link retry }\n * @see {@link retryWhen}\n *\n * @param {function} selector a function that takes as arguments `err`, which is the error, and `caught`, which\n * is the source observable, in case you'd like to \"retry\" that observable by returning it again. Whatever observable\n * is returned by the `selector` will be used to continue the observable chain.\n * @return A function that returns an Observable that originates from either\n * the source or the Observable returned by the `selector` function.\n */\nexport function catchError<T, O extends ObservableInput<any>>(\n selector: (err: any, caught: Observable<T>) => O\n): OperatorFunction<T, T | ObservedValueOf<O>> {\n return operate((source, subscriber) => {\n let innerSub: Subscription | null = null;\n let syncUnsub = false;\n let handledResult: Observable<ObservedValueOf<O>>;\n\n innerSub = source.subscribe(\n createOperatorSubscriber(subscriber, undefined, undefined, (err) => {\n handledResult = innerFrom(selector(err, catchError(selector)(source)));\n if (innerSub) {\n innerSub.unsubscribe();\n innerSub = null;\n handledResult.subscribe(subscriber);\n } else {\n // We don't have an innerSub yet, that means the error was synchronous\n // because the subscribe call hasn't returned yet.\n syncUnsub = true;\n }\n })\n );\n\n if (syncUnsub) {\n // We have a synchronous error, we need to make sure to\n // finalize right away. This ensures that callbacks in the `finalize` operator are called\n // at the right time, and that finalization occurs at the expected\n // time between the source error and the subscription to the\n // next observable.\n innerSub.unsubscribe();\n innerSub = null;\n handledResult!.subscribe(subscriber);\n }\n });\n}\n", "import { mergeMap } from './mergeMap';\nimport { ObservableInput, OperatorFunction, ObservedValueOf } from '../types';\nimport { isFunction } from '../util/isFunction';\n\n/* tslint:disable:max-line-length */\nexport function concatMap<T, O extends ObservableInput<any>>(\n project: (value: T, index: number) => O\n): OperatorFunction<T, ObservedValueOf<O>>;\n/** @deprecated The `resultSelector` parameter will be removed in v8. Use an inner `map` instead. Details: https://rxjs.dev/deprecations/resultSelector */\nexport function concatMap<T, O extends ObservableInput<any>>(\n project: (value: T, index: number) => O,\n resultSelector: undefined\n): OperatorFunction<T, ObservedValueOf<O>>;\n/** @deprecated The `resultSelector` parameter will be removed in v8. Use an inner `map` instead. Details: https://rxjs.dev/deprecations/resultSelector */\nexport function concatMap<T, R, O extends ObservableInput<any>>(\n project: (value: T, index: number) => O,\n resultSelector: (outerValue: T, innerValue: ObservedValueOf<O>, outerIndex: number, innerIndex: number) => R\n): OperatorFunction<T, R>;\n/* tslint:enable:max-line-length */\n\n/**\n * Projects each source value to an Observable which is merged in the output\n * Observable, in a serialized fashion waiting for each one to complete before\n * merging the next.\n *\n * <span class=\"informal\">Maps each value to an Observable, then flattens all of\n * these inner Observables using {@link concatAll}.</span>\n *\n * \n *\n * Returns an Observable that emits items based on applying a function that you\n * supply to each item emitted by the source Observable, where that function\n * returns an (so-called \"inner\") Observable. Each new inner Observable is\n * concatenated with the previous inner Observable.\n *\n * __Warning:__ if source values arrive endlessly and faster than their\n * corresponding inner Observables can complete, it will result in memory issues\n * as inner Observables amass in an unbounded buffer waiting for their turn to\n * be subscribed to.\n *\n * Note: `concatMap` is equivalent to `mergeMap` with concurrency parameter set\n * to `1`.\n *\n * ## Example\n *\n * For each click event, tick every second from 0 to 3, with no concurrency\n *\n * ```ts\n * import { fromEvent, concatMap, interval, take } from 'rxjs';\n *\n * const clicks = fromEvent(document, 'click');\n * const result = clicks.pipe(\n * concatMap(ev => interval(1000).pipe(take(4)))\n * );\n * result.subscribe(x => console.log(x));\n *\n * // Results in the following:\n * // (results are not concurrent)\n * // For every click on the \"document\" it will emit values 0 to 3 spaced\n * // on a 1000ms interval\n * // one click = 1000ms-> 0 -1000ms-> 1 -1000ms-> 2 -1000ms-> 3\n * ```\n *\n * @see {@link concat}\n * @see {@link concatAll}\n * @see {@link concatMapTo}\n * @see {@link exhaustMap}\n * @see {@link mergeMap}\n * @see {@link switchMap}\n *\n * @param {function(value: T, ?index: number): ObservableInput} project A function\n * that, when applied to an item emitted by the source Observable, returns an\n * Observable.\n * @return A function that returns an Observable that emits the result of\n * applying the projection function (and the optional deprecated\n * `resultSelector`) to each item emitted by the source Observable and taking\n * values from each projected inner Observable sequentially.\n */\nexport function concatMap<T, R, O extends ObservableInput<any>>(\n project: (value: T, index: number) => O,\n resultSelector?: (outerValue: T, innerValue: ObservedValueOf<O>, outerIndex: number, innerIndex: number) => R\n): OperatorFunction<T, ObservedValueOf<O> | R> {\n return isFunction(resultSelector) ? mergeMap(project, resultSelector, 1) : mergeMap(project, 1);\n}\n", "import { OperatorFunction } from '../types';\nimport { operate } from '../util/lift';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\n\n/**\n * Emits a given value if the source Observable completes without emitting any\n * `next` value, otherwise mirrors the source Observable.\n *\n * <span class=\"informal\">If the source Observable turns out to be empty, then\n * this operator will emit a default value.</span>\n *\n * \n *\n * `defaultIfEmpty` emits the values emitted by the source Observable or a\n * specified default value if the source Observable is empty (completes without\n * having emitted any `next` value).\n *\n * ## Example\n *\n * If no clicks happen in 5 seconds, then emit 'no clicks'\n *\n * ```ts\n * import { fromEvent, takeUntil, interval, defaultIfEmpty } from 'rxjs';\n *\n * const clicks = fromEvent(document, 'click');\n * const clicksBeforeFive = clicks.pipe(takeUntil(interval(5000)));\n * const result = clicksBeforeFive.pipe(defaultIfEmpty('no clicks'));\n * result.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link empty}\n * @see {@link last}\n *\n * @param defaultValue The default value used if the source\n * Observable is empty.\n * @return A function that returns an Observable that emits either the\n * specified `defaultValue` if the source Observable emits no items, or the\n * values emitted by the source Observable.\n */\nexport function defaultIfEmpty<T, R>(defaultValue: R): OperatorFunction<T, T | R> {\n return operate((source, subscriber) => {\n let hasValue = false;\n source.subscribe(\n createOperatorSubscriber(\n subscriber,\n (value) => {\n hasValue = true;\n subscriber.next(value);\n },\n () => {\n if (!hasValue) {\n subscriber.next(defaultValue!);\n }\n subscriber.complete();\n }\n )\n );\n });\n}\n", "import { MonoTypeOperatorFunction } from '../types';\nimport { operate } from '../util/lift';\n\n/**\n * Returns an Observable that mirrors the source Observable, but will call a specified function when\n * the source terminates on complete or error.\n * The specified function will also be called when the subscriber explicitly unsubscribes.\n *\n * ## Examples\n *\n * Execute callback function when the observable completes\n *\n * ```ts\n * import { interval, take, finalize } from 'rxjs';\n *\n * // emit value in sequence every 1 second\n * const source = interval(1000);\n * const example = source.pipe(\n * take(5), //take only the first 5 values\n * finalize(() => console.log('Sequence complete')) // Execute when the observable completes\n * );\n * const subscribe = example.subscribe(val => console.log(val));\n *\n * // results:\n * // 0\n * // 1\n * // 2\n * // 3\n * // 4\n * // 'Sequence complete'\n * ```\n *\n * Execute callback function when the subscriber explicitly unsubscribes\n *\n * ```ts\n * import { interval, finalize, tap, noop, timer } from 'rxjs';\n *\n * const source = interval(100).pipe(\n * finalize(() => console.log('[finalize] Called')),\n * tap({\n * next: () => console.log('[next] Called'),\n * error: () => console.log('[error] Not called'),\n * complete: () => console.log('[tap complete] Not called')\n * })\n * );\n *\n * const sub = source.subscribe({\n * next: x => console.log(x),\n * error: noop,\n * complete: () => console.log('[complete] Not called')\n * });\n *\n * timer(150).subscribe(() => sub.unsubscribe());\n *\n * // results:\n * // '[next] Called'\n * // 0\n * // '[finalize] Called'\n * ```\n *\n * @param {function} callback Function to be called when source terminates.\n * @return A function that returns an Observable that mirrors the source, but\n * will call the specified function on termination.\n */\nexport function finalize<T>(callback: () => void): MonoTypeOperatorFunction<T> {\n return operate((source, subscriber) => {\n // TODO: This try/finally was only added for `useDeprecatedSynchronousErrorHandling`.\n // REMOVE THIS WHEN THAT HOT GARBAGE IS REMOVED IN V8.\n try {\n source.subscribe(subscriber);\n } finally {\n subscriber.add(callback);\n }\n });\n}\n", "import { Subscriber } from '../Subscriber';\nimport { ObservableInput, OperatorFunction, ObservedValueOf } from '../types';\nimport { innerFrom } from '../observable/innerFrom';\nimport { operate } from '../util/lift';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\n\n/* tslint:disable:max-line-length */\nexport function switchMap<T, O extends ObservableInput<any>>(\n project: (value: T, index: number) => O\n): OperatorFunction<T, ObservedValueOf<O>>;\n/** @deprecated The `resultSelector` parameter will be removed in v8. Use an inner `map` instead. Details: https://rxjs.dev/deprecations/resultSelector */\nexport function switchMap<T, O extends ObservableInput<any>>(\n project: (value: T, index: number) => O,\n resultSelector: undefined\n): OperatorFunction<T, ObservedValueOf<O>>;\n/** @deprecated The `resultSelector` parameter will be removed in v8. Use an inner `map` instead. Details: https://rxjs.dev/deprecations/resultSelector */\nexport function switchMap<T, R, O extends ObservableInput<any>>(\n project: (value: T, index: number) => O,\n resultSelector: (outerValue: T, innerValue: ObservedValueOf<O>, outerIndex: number, innerIndex: number) => R\n): OperatorFunction<T, R>;\n/* tslint:enable:max-line-length */\n\n/**\n * Projects each source value to an Observable which is merged in the output\n * Observable, emitting values only from the most recently projected Observable.\n *\n * <span class=\"informal\">Maps each value to an Observable, then flattens all of\n * these inner Observables using {@link switchAll}.</span>\n *\n * \n *\n * Returns an Observable that emits items based on applying a function that you\n * supply to each item emitted by the source Observable, where that function\n * returns an (so-called \"inner\") Observable. Each time it observes one of these\n * inner Observables, the output Observable begins emitting the items emitted by\n * that inner Observable. When a new inner Observable is emitted, `switchMap`\n * stops emitting items from the earlier-emitted inner Observable and begins\n * emitting items from the new one. It continues to behave like this for\n * subsequent inner Observables.\n *\n * ## Example\n *\n * Generate new Observable according to source Observable values\n *\n * ```ts\n * import { of, switchMap } from 'rxjs';\n *\n * const switched = of(1, 2, 3).pipe(switchMap(x => of(x, x ** 2, x ** 3)));\n * switched.subscribe(x => console.log(x));\n * // outputs\n * // 1\n * // 1\n * // 1\n * // 2\n * // 4\n * // 8\n * // 3\n * // 9\n * // 27\n * ```\n *\n * Restart an interval Observable on every click event\n *\n * ```ts\n * import { fromEvent, switchMap, interval } from 'rxjs';\n *\n * const clicks = fromEvent(document, 'click');\n * const result = clicks.pipe(switchMap(() => interval(1000)));\n * result.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link concatMap}\n * @see {@link exhaustMap}\n * @see {@link mergeMap}\n * @see {@link switchAll}\n * @see {@link switchMapTo}\n *\n * @param {function(value: T, index: number): ObservableInput} project A function\n * that, when applied to an item emitted by the source Observable, returns an\n * Observable.\n * @return A function that returns an Observable that emits the result of\n * applying the projection function (and the optional deprecated\n * `resultSelector`) to each item emitted by the source Observable and taking\n * only the values from the most recently projected inner Observable.\n */\nexport function switchMap<T, R, O extends ObservableInput<any>>(\n project: (value: T, index: number) => O,\n resultSelector?: (outerValue: T, innerValue: ObservedValueOf<O>, outerIndex: number, innerIndex: number) => R\n): OperatorFunction<T, ObservedValueOf<O> | R> {\n return operate((source, subscriber) => {\n let innerSubscriber: Subscriber<ObservedValueOf<O>> | null = null;\n let index = 0;\n // Whether or not the source subscription has completed\n let isComplete = false;\n\n // We only complete the result if the source is complete AND we don't have an active inner subscription.\n // This is called both when the source completes and when the inners complete.\n const checkComplete = () => isComplete && !innerSubscriber && subscriber.complete();\n\n source.subscribe(\n createOperatorSubscriber(\n subscriber,\n (value) => {\n // Cancel the previous inner subscription if there was one\n innerSubscriber?.unsubscribe();\n let innerIndex = 0;\n const outerIndex = index++;\n // Start the next inner subscription\n innerFrom(project(value, outerIndex)).subscribe(\n (innerSubscriber = createOperatorSubscriber(\n subscriber,\n // When we get a new inner value, next it through. Note that this is\n // handling the deprecate result selector here. This is because with this architecture\n // it ends up being smaller than using the map operator.\n (innerValue) => subscriber.next(resultSelector ? resultSelector(value, innerValue, outerIndex, innerIndex++) : innerValue),\n () => {\n // The inner has completed. Null out the inner subscriber to\n // free up memory and to signal that we have no inner subscription\n // currently.\n innerSubscriber = null!;\n checkComplete();\n }\n ))\n );\n },\n () => {\n isComplete = true;\n checkComplete();\n }\n )\n );\n });\n}\n", "import { MonoTypeOperatorFunction, ObservableInput } from '../types';\nimport { operate } from '../util/lift';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\nimport { innerFrom } from '../observable/innerFrom';\nimport { noop } from '../util/noop';\n\n/**\n * Emits the values emitted by the source Observable until a `notifier`\n * Observable emits a value.\n *\n * <span class=\"informal\">Lets values pass until a second Observable,\n * `notifier`, emits a value. Then, it completes.</span>\n *\n * \n *\n * `takeUntil` subscribes and begins mirroring the source Observable. It also\n * monitors a second Observable, `notifier` that you provide. If the `notifier`\n * emits a value, the output Observable stops mirroring the source Observable\n * and completes. If the `notifier` doesn't emit any value and completes\n * then `takeUntil` will pass all values.\n *\n * ## Example\n *\n * Tick every second until the first click happens\n *\n * ```ts\n * import { interval, fromEvent, takeUntil } from 'rxjs';\n *\n * const source = interval(1000);\n * const clicks = fromEvent(document, 'click');\n * const result = source.pipe(takeUntil(clicks));\n * result.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link take}\n * @see {@link takeLast}\n * @see {@link takeWhile}\n * @see {@link skip}\n *\n * @param {Observable} notifier The Observable whose first emitted value will\n * cause the output Observable of `takeUntil` to stop emitting values from the\n * source Observable.\n * @return A function that returns an Observable that emits the values from the\n * source Observable until `notifier` emits its first value.\n */\nexport function takeUntil<T>(notifier: ObservableInput<any>): MonoTypeOperatorFunction<T> {\n return operate((source, subscriber) => {\n innerFrom(notifier).subscribe(createOperatorSubscriber(subscriber, () => subscriber.complete(), noop));\n !subscriber.closed && source.subscribe(subscriber);\n });\n}\n", "import { MonoTypeOperatorFunction, Observer } from '../types';\nimport { isFunction } from '../util/isFunction';\nimport { operate } from '../util/lift';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\nimport { identity } from '../util/identity';\n\n/**\n * An extension to the {@link Observer} interface used only by the {@link tap} operator.\n *\n * It provides a useful set of callbacks a user can register to do side-effects in\n * cases other than what the usual {@link Observer} callbacks are\n * ({@link guide/glossary-and-semantics#next next},\n * {@link guide/glossary-and-semantics#error error} and/or\n * {@link guide/glossary-and-semantics#complete complete}).\n *\n * ## Example\n *\n * ```ts\n * import { fromEvent, switchMap, tap, interval, take } from 'rxjs';\n *\n * const source$ = fromEvent(document, 'click');\n * const result$ = source$.pipe(\n * switchMap((_, i) => i % 2 === 0\n * ? fromEvent(document, 'mousemove').pipe(\n * tap({\n * subscribe: () => console.log('Subscribed to the mouse move events after click #' + i),\n * unsubscribe: () => console.log('Mouse move events #' + i + ' unsubscribed'),\n * finalize: () => console.log('Mouse move events #' + i + ' finalized')\n * })\n * )\n * : interval(1_000).pipe(\n * take(5),\n * tap({\n * subscribe: () => console.log('Subscribed to the 1-second interval events after click #' + i),\n * unsubscribe: () => console.log('1-second interval events #' + i + ' unsubscribed'),\n * finalize: () => console.log('1-second interval events #' + i + ' finalized')\n * })\n * )\n * )\n * );\n *\n * const subscription = result$.subscribe({\n * next: console.log\n * });\n *\n * setTimeout(() => {\n * console.log('Unsubscribe after 60 seconds');\n * subscription.unsubscribe();\n * }, 60_000);\n * ```\n */\nexport interface TapObserver<T> extends Observer<T> {\n /**\n * The callback that `tap` operator invokes at the moment when the source Observable\n * gets subscribed to.\n */\n subscribe: () => void;\n /**\n * The callback that `tap` operator invokes when an explicit\n * {@link guide/glossary-and-semantics#unsubscription unsubscribe} happens. It won't get invoked on\n * `error` or `complete` events.\n */\n unsubscribe: () => void;\n /**\n * The callback that `tap` operator invokes when any kind of\n * {@link guide/glossary-and-semantics#finalization finalization} happens - either when\n * the source Observable `error`s or `complete`s or when it gets explicitly unsubscribed\n * by the user. There is no difference in using this callback or the {@link finalize}\n * operator, but if you're already using `tap` operator, you can use this callback\n * instead. You'd get the same result in either case.\n */\n finalize: () => void;\n}\nexport function tap<T>(observerOrNext?: Partial<TapObserver<T>> | ((value: T) => void)): MonoTypeOperatorFunction<T>;\n/** @deprecated Instead of passing separate callback arguments, use an observer argument. Signatures taking separate callback arguments will be removed in v8. Details: https://rxjs.dev/deprecations/subscribe-arguments */\nexport function tap<T>(\n next?: ((value: T) => void) | null,\n error?: ((error: any) => void) | null,\n complete?: (() => void) | null\n): MonoTypeOperatorFunction<T>;\n\n/**\n * Used to perform side-effects for notifications from the source observable\n *\n * <span class=\"informal\">Used when you want to affect outside state with a notification without altering the notification</span>\n *\n * \n *\n * Tap is designed to allow the developer a designated place to perform side effects. While you _could_ perform side-effects\n * inside of a `map` or a `mergeMap`, that would make their mapping functions impure, which isn't always a big deal, but will\n * make it so you can't do things like memoize those functions. The `tap` operator is designed solely for such side-effects to\n * help you remove side-effects from other operations.\n *\n * For any notification, next, error, or complete, `tap` will call the appropriate callback you have provided to it, via a function\n * reference, or a partial observer, then pass that notification down the stream.\n *\n * The observable returned by `tap` is an exact mirror of the source, with one exception: Any error that occurs -- synchronously -- in a handler\n * provided to `tap` will be emitted as an error from the returned observable.\n *\n * > Be careful! You can mutate objects as they pass through the `tap` operator's handlers.\n *\n * The most common use of `tap` is actually for debugging. You can place a `tap(console.log)` anywhere\n * in your observable `pipe`, log out the notifications as they are emitted by the source returned by the previous\n * operation.\n *\n * ## Examples\n *\n * Check a random number before it is handled. Below is an observable that will use a random number between 0 and 1,\n * and emit `'big'` or `'small'` depending on the size of that number. But we wanted to log what the original number\n * was, so we have added a `tap(console.log)`.\n *\n * ```ts\n * import { of, tap, map } from 'rxjs';\n *\n * of(Math.random()).pipe(\n * tap(console.log),\n * map(n => n > 0.5 ? 'big' : 'small')\n * ).subscribe(console.log);\n * ```\n *\n * Using `tap` to analyze a value and force an error. Below is an observable where in our system we only\n * want to emit numbers 3 or less we get from another source. We can force our observable to error\n * using `tap`.\n *\n * ```ts\n * import { of, tap } from 'rxjs';\n *\n * const source = of(1, 2, 3, 4, 5);\n *\n * source.pipe(\n * tap(n => {\n * if (n > 3) {\n * throw new TypeError(`Value ${ n } is greater than 3`);\n * }\n * })\n * )\n * .subscribe({ next: console.log, error: err => console.log(err.message) });\n * ```\n *\n * We want to know when an observable completes before moving on to the next observable. The system\n * below will emit a random series of `'X'` characters from 3 different observables in sequence. The\n * only way we know when one observable completes and moves to the next one, in this case, is because\n * we have added a `tap` with the side effect of logging to console.\n *\n * ```ts\n * import { of, concatMap, interval, take, map, tap } from 'rxjs';\n *\n * of(1, 2, 3).pipe(\n * concatMap(n => interval(1000).pipe(\n * take(Math.round(Math.random() * 10)),\n * map(() => 'X'),\n * tap({ complete: () => console.log(`Done with ${ n }`) })\n * ))\n * )\n * .subscribe(console.log);\n * ```\n *\n * @see {@link finalize}\n * @see {@link TapObserver}\n *\n * @param observerOrNext A next handler or partial observer\n * @param error An error handler\n * @param complete A completion handler\n * @return A function that returns an Observable identical to the source, but\n * runs the specified Observer or callback(s) for each item.\n */\nexport function tap<T>(\n observerOrNext?: Partial<TapObserver<T>> | ((value: T) => void) | null,\n error?: ((e: any) => void) | null,\n complete?: (() => void) | null\n): MonoTypeOperatorFunction<T> {\n // We have to check to see not only if next is a function,\n // but if error or complete were passed. This is because someone\n // could technically call tap like `tap(null, fn)` or `tap(null, null, fn)`.\n const tapObserver =\n isFunction(observerOrNext) || error || complete\n ? // tslint:disable-next-line: no-object-literal-type-assertion\n ({ next: observerOrNext as Exclude<typeof observerOrNext, Partial<TapObserver<T>>>, error, complete } as Partial<TapObserver<T>>)\n : observerOrNext;\n\n return tapObserver\n ? operate((source, subscriber) => {\n tapObserver.subscribe?.();\n let isUnsub = true;\n source.subscribe(\n createOperatorSubscriber(\n subscriber,\n (value) => {\n tapObserver.next?.(value);\n subscriber.next(value);\n },\n () => {\n isUnsub = false;\n tapObserver.complete?.();\n subscriber.complete();\n },\n (err) => {\n isUnsub = false;\n tapObserver.error?.(err);\n subscriber.error(err);\n },\n () => {\n if (isUnsub) {\n tapObserver.unsubscribe?.();\n }\n tapObserver.finalize?.();\n }\n )\n );\n })\n : // Tap was called with no valid tap observer or handler\n // (e.g. `tap(null, null, null)` or `tap(null)` or `tap()`)\n // so we're going to just mirror the source.\n identity;\n}\n", "const enum ContextType {\n TOP_LEVEL = \"topLevel\",\n STRING = \"string\",\n STRING_ESCAPED = \"stringEscaped\",\n STRING_UNICODE = \"stringUnicode\",\n NUMBER = \"number\",\n NUMBER_NEEDS_DIGIT = \"numberNeedsDigit\",\n NUMBER_NEEDS_EXPONENT = \"numberNeedsExponent\",\n TRUE = \"true\",\n FALSE = \"false\",\n NULL = \"null\",\n ARRAY_NEEDS_VALUE = \"arrayNeedsValue\",\n ARRAY_NEEDS_COMMA = \"arrayNeedsComma\",\n OBJECT_NEEDS_KEY = \"objectNeedsKey\",\n OBJECT_NEEDS_COLON = \"objectNeedsColon\",\n OBJECT_NEEDS_VALUE = \"objectNeedsValue\",\n OBJECT_NEEDS_COMMA = \"objectNeedsComma\",\n}\n\nconst enum RespawnReason {\n STRING_ESCAPE = \"stringEscape\",\n COLLECTION_ITEM = \"collectionItem\",\n}\n\nfunction isWhitespace(char: string): boolean {\n return \"\\u0020\\u000D\\u000A\\u0009\".indexOf(char) >= 0;\n}\n\nexport default function untruncateJson(json: string): string {\n const contextStack: ContextType[] = [ContextType.TOP_LEVEL];\n let position = 0;\n let respawnPosition: number | undefined;\n let respawnStackLength: number | undefined;\n let respawnReason: RespawnReason | undefined;\n\n const push = (context: ContextType) => contextStack.push(context);\n const replace = (context: ContextType) =>\n (contextStack[contextStack.length - 1] = context);\n const setRespawn = (reason: RespawnReason) => {\n if (respawnPosition == null) {\n respawnPosition = position;\n respawnStackLength = contextStack.length;\n respawnReason = reason;\n }\n };\n const clearRespawn = (reason: RespawnReason) => {\n if (reason === respawnReason) {\n respawnPosition = undefined;\n respawnStackLength = undefined;\n respawnReason = undefined;\n }\n };\n const pop = () => contextStack.pop();\n const dontConsumeCharacter = () => position--;\n\n const startAny = (char: string) => {\n if (\"0\" <= char && char <= \"9\") {\n push(ContextType.NUMBER);\n return;\n }\n switch (char) {\n case '\"':\n push(ContextType.STRING);\n return;\n case \"-\":\n push(ContextType.NUMBER_NEEDS_DIGIT);\n return;\n case \"t\":\n push(ContextType.TRUE);\n return;\n case \"f\":\n push(ContextType.FALSE);\n return;\n case \"n\":\n push(ContextType.NULL);\n return;\n case \"[\":\n push(ContextType.ARRAY_NEEDS_VALUE);\n return;\n case \"{\":\n push(ContextType.OBJECT_NEEDS_KEY);\n return;\n }\n };\n\n for (const { length } = json; position < length; position++) {\n const char = json[position];\n switch (contextStack[contextStack.length - 1]) {\n case ContextType.TOP_LEVEL:\n startAny(char);\n break;\n case ContextType.STRING:\n switch (char) {\n case '\"':\n pop();\n break;\n case \"\\\\\":\n setRespawn(RespawnReason.STRING_ESCAPE);\n push(ContextType.STRING_ESCAPED);\n break;\n }\n break;\n case ContextType.STRING_ESCAPED:\n if (char === \"u\") {\n push(ContextType.STRING_UNICODE);\n } else {\n clearRespawn(RespawnReason.STRING_ESCAPE);\n pop();\n }\n break;\n case ContextType.STRING_UNICODE:\n if (position - json.lastIndexOf(\"u\", position) === 4) {\n clearRespawn(RespawnReason.STRING_ESCAPE);\n pop();\n }\n break;\n case ContextType.NUMBER:\n if (char === \".\") {\n replace(ContextType.NUMBER_NEEDS_DIGIT);\n } else if (char === \"e\" || char === \"E\") {\n replace(ContextType.NUMBER_NEEDS_EXPONENT);\n } else if (char < \"0\" || char > \"9\") {\n dontConsumeCharacter();\n pop();\n }\n break;\n case ContextType.NUMBER_NEEDS_DIGIT:\n replace(ContextType.NUMBER);\n break;\n case ContextType.NUMBER_NEEDS_EXPONENT:\n if (char === \"+\" || char === \"-\") {\n replace(ContextType.NUMBER_NEEDS_DIGIT);\n } else {\n replace(ContextType.NUMBER);\n }\n break;\n case ContextType.TRUE:\n case ContextType.FALSE:\n case ContextType.NULL:\n if (char < \"a\" || char > \"z\") {\n dontConsumeCharacter();\n pop();\n }\n break;\n case ContextType.ARRAY_NEEDS_VALUE:\n if (char === \"]\") {\n pop();\n } else if (!isWhitespace(char)) {\n clearRespawn(RespawnReason.COLLECTION_ITEM);\n replace(ContextType.ARRAY_NEEDS_COMMA);\n startAny(char);\n }\n break;\n case ContextType.ARRAY_NEEDS_COMMA:\n if (char === \"]\") {\n pop();\n } else if (char === \",\") {\n setRespawn(RespawnReason.COLLECTION_ITEM);\n replace(ContextType.ARRAY_NEEDS_VALUE);\n }\n break;\n case ContextType.OBJECT_NEEDS_KEY:\n if (char === \"}\") {\n pop();\n } else if (char === '\"') {\n setRespawn(RespawnReason.COLLECTION_ITEM);\n replace(ContextType.OBJECT_NEEDS_COLON);\n push(ContextType.STRING);\n }\n break;\n case ContextType.OBJECT_NEEDS_COLON:\n if (char === \":\") {\n replace(ContextType.OBJECT_NEEDS_VALUE);\n }\n break;\n case ContextType.OBJECT_NEEDS_VALUE:\n if (!isWhitespace(char)) {\n clearRespawn(RespawnReason.COLLECTION_ITEM);\n replace(ContextType.OBJECT_NEEDS_COMMA);\n startAny(char);\n }\n break;\n case ContextType.OBJECT_NEEDS_COMMA:\n if (char === \"}\") {\n pop();\n } else if (char === \",\") {\n setRespawn(RespawnReason.COLLECTION_ITEM);\n replace(ContextType.OBJECT_NEEDS_KEY);\n }\n break;\n }\n }\n\n if (respawnStackLength != null) {\n contextStack.length = respawnStackLength;\n }\n const result = [\n respawnPosition != null ? json.slice(0, respawnPosition) : json,\n ];\n const finishWord = (word: string) =>\n result.push(word.slice(json.length - json.lastIndexOf(word[0])));\n for (let i = contextStack.length - 1; i >= 0; i--) {\n switch (contextStack[i]) {\n case ContextType.STRING:\n result.push('\"');\n break;\n case ContextType.NUMBER_NEEDS_DIGIT:\n case ContextType.NUMBER_NEEDS_EXPONENT:\n result.push(\"0\");\n break;\n case ContextType.TRUE:\n finishWord(\"true\");\n break;\n case ContextType.FALSE:\n finishWord(\"false\");\n break;\n case ContextType.NULL:\n finishWord(\"null\");\n break;\n case ContextType.ARRAY_NEEDS_VALUE:\n case ContextType.ARRAY_NEEDS_COMMA:\n result.push(\"]\");\n break;\n case ContextType.OBJECT_NEEDS_KEY:\n case ContextType.OBJECT_NEEDS_COLON:\n case ContextType.OBJECT_NEEDS_VALUE:\n case ContextType.OBJECT_NEEDS_COMMA:\n result.push(\"}\");\n break;\n }\n }\n return result.join(\"\");\n}\n", "// Copyright 2008 Google Inc. All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n// * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n// * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n// * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n//\n// Code generated by the Protocol Buffer compiler is owned by the owner\n// of the input file used when generating it. This code is not\n// standalone and requires a support library to be linked with it. This\n// support library is itself covered by the above license.\n/**\n * Read a 64 bit varint as two JS numbers.\n *\n * Returns tuple:\n * [0]: low bits\n * [1]: high bits\n *\n * Copyright 2008 Google Inc. All rights reserved.\n *\n * See https://github.com/protocolbuffers/protobuf/blob/8a71927d74a4ce34efe2d8769fda198f52d20d12/js/experimental/runtime/kernel/buffer_decoder.js#L175\n */\nexport function varint64read() {\n let lowBits = 0;\n let highBits = 0;\n for (let shift = 0; shift < 28; shift += 7) {\n let b = this.buf[this.pos++];\n lowBits |= (b & 0x7f) << shift;\n if ((b & 0x80) == 0) {\n this.assertBounds();\n return [lowBits, highBits];\n }\n }\n let middleByte = this.buf[this.pos++];\n // last four bits of the first 32 bit number\n lowBits |= (middleByte & 0x0f) << 28;\n // 3 upper bits are part of the next 32 bit number\n highBits = (middleByte & 0x70) >> 4;\n if ((middleByte & 0x80) == 0) {\n this.assertBounds();\n return [lowBits, highBits];\n }\n for (let shift = 3; shift <= 31; shift += 7) {\n let b = this.buf[this.pos++];\n highBits |= (b & 0x7f) << shift;\n if ((b & 0x80) == 0) {\n this.assertBounds();\n return [lowBits, highBits];\n }\n }\n throw new Error(\"invalid varint\");\n}\n/**\n * Write a 64 bit varint, given as two JS numbers, to the given bytes array.\n *\n * Copyright 2008 Google Inc. All rights reserved.\n *\n * See https://github.com/protocolbuffers/protobuf/blob/8a71927d74a4ce34efe2d8769fda198f52d20d12/js/experimental/runtime/kernel/writer.js#L344\n */\nexport function varint64write(lo, hi, bytes) {\n for (let i = 0; i < 28; i = i + 7) {\n const shift = lo >>> i;\n const hasNext = !(shift >>> 7 == 0 && hi == 0);\n const byte = (hasNext ? shift | 0x80 : shift) & 0xff;\n bytes.push(byte);\n if (!hasNext) {\n return;\n }\n }\n const splitBits = ((lo >>> 28) & 0x0f) | ((hi & 0x07) << 4);\n const hasMoreBits = !(hi >> 3 == 0);\n bytes.push((hasMoreBits ? splitBits | 0x80 : splitBits) & 0xff);\n if (!hasMoreBits) {\n return;\n }\n for (let i = 3; i < 31; i = i + 7) {\n const shift = hi >>> i;\n const hasNext = !(shift >>> 7 == 0);\n const byte = (hasNext ? shift | 0x80 : shift) & 0xff;\n bytes.push(byte);\n if (!hasNext) {\n return;\n }\n }\n bytes.push((hi >>> 31) & 0x01);\n}\n// constants for binary math\nconst TWO_PWR_32_DBL = 0x100000000;\n/**\n * Parse decimal string of 64 bit integer value as two JS numbers.\n *\n * Copyright 2008 Google Inc. All rights reserved.\n *\n * See https://github.com/protocolbuffers/protobuf-javascript/blob/a428c58273abad07c66071d9753bc4d1289de426/experimental/runtime/int64.js#L10\n */\nexport function int64FromString(dec) {\n // Check for minus sign.\n const minus = dec[0] === \"-\";\n if (minus) {\n dec = dec.slice(1);\n }\n // Work 6 decimal digits at a time, acting like we're converting base 1e6\n // digits to binary. This is safe to do with floating point math because\n // Number.isSafeInteger(ALL_32_BITS * 1e6) == true.\n const base = 1e6;\n let lowBits = 0;\n let highBits = 0;\n function add1e6digit(begin, end) {\n // Note: Number('') is 0.\n const digit1e6 = Number(dec.slice(begin, end));\n highBits *= base;\n lowBits = lowBits * base + digit1e6;\n // Carry bits from lowBits to\n if (lowBits >= TWO_PWR_32_DBL) {\n highBits = highBits + ((lowBits / TWO_PWR_32_DBL) | 0);\n lowBits = lowBits % TWO_PWR_32_DBL;\n }\n }\n add1e6digit(-24, -18);\n add1e6digit(-18, -12);\n add1e6digit(-12, -6);\n add1e6digit(-6);\n return minus ? negate(lowBits, highBits) : newBits(lowBits, highBits);\n}\n/**\n * Losslessly converts a 64-bit signed integer in 32:32 split representation\n * into a decimal string.\n *\n * Copyright 2008 Google Inc. All rights reserved.\n *\n * See https://github.com/protocolbuffers/protobuf-javascript/blob/a428c58273abad07c66071d9753bc4d1289de426/experimental/runtime/int64.js#L10\n */\nexport function int64ToString(lo, hi) {\n let bits = newBits(lo, hi);\n // If we're treating the input as a signed value and the high bit is set, do\n // a manual two's complement conversion before the decimal conversion.\n const negative = bits.hi & 0x80000000;\n if (negative) {\n bits = negate(bits.lo, bits.hi);\n }\n const result = uInt64ToString(bits.lo, bits.hi);\n return negative ? \"-\" + result : result;\n}\n/**\n * Losslessly converts a 64-bit unsigned integer in 32:32 split representation\n * into a decimal string.\n *\n * Copyright 2008 Google Inc. All rights reserved.\n *\n * See https://github.com/protocolbuffers/protobuf-javascript/blob/a428c58273abad07c66071d9753bc4d1289de426/experimental/runtime/int64.js#L10\n */\nexport function uInt64ToString(lo, hi) {\n ({ lo, hi } = toUnsigned(lo, hi));\n // Skip the expensive conversion if the number is small enough to use the\n // built-in conversions.\n // Number.MAX_SAFE_INTEGER = 0x001FFFFF FFFFFFFF, thus any number with\n // highBits <= 0x1FFFFF can be safely expressed with a double and retain\n // integer precision.\n // Proven by: Number.isSafeInteger(0x1FFFFF * 2**32 + 0xFFFFFFFF) == true.\n if (hi <= 0x1fffff) {\n return String(TWO_PWR_32_DBL * hi + lo);\n }\n // What this code is doing is essentially converting the input number from\n // base-2 to base-1e7, which allows us to represent the 64-bit range with\n // only 3 (very large) digits. Those digits are then trivial to convert to\n // a base-10 string.\n // The magic numbers used here are -\n // 2^24 = 16777216 = (1,6777216) in base-1e7.\n // 2^48 = 281474976710656 = (2,8147497,6710656) in base-1e7.\n // Split 32:32 representation into 16:24:24 representation so our\n // intermediate digits don't overflow.\n const low = lo & 0xffffff;\n const mid = ((lo >>> 24) | (hi << 8)) & 0xffffff;\n const high = (hi >> 16) & 0xffff;\n // Assemble our three base-1e7 digits, ignoring carries. The maximum\n // value in a digit at this step is representable as a 48-bit integer, which\n // can be stored in a 64-bit floating point number.\n let digitA = low + mid * 6777216 + high * 6710656;\n let digitB = mid + high * 8147497;\n let digitC = high * 2;\n // Apply carries from A to B and from B to C.\n const base = 10000000;\n if (digitA >= base) {\n digitB += Math.floor(digitA / base);\n digitA %= base;\n }\n if (digitB >= base) {\n digitC += Math.floor(digitB / base);\n digitB %= base;\n }\n // If digitC is 0, then we should have returned in the trivial code path\n // at the top for non-safe integers. Given this, we can assume both digitB\n // and digitA need leading zeros.\n return (digitC.toString() +\n decimalFrom1e7WithLeadingZeros(digitB) +\n decimalFrom1e7WithLeadingZeros(digitA));\n}\nfunction toUnsigned(lo, hi) {\n return { lo: lo >>> 0, hi: hi >>> 0 };\n}\nfunction newBits(lo, hi) {\n return { lo: lo | 0, hi: hi | 0 };\n}\n/**\n * Returns two's compliment negation of input.\n * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators#Signed_32-bit_integers\n */\nfunction negate(lowBits, highBits) {\n highBits = ~highBits;\n if (lowBits) {\n lowBits = ~lowBits + 1;\n }\n else {\n // If lowBits is 0, then bitwise-not is 0xFFFFFFFF,\n // adding 1 to that, results in 0x100000000, which leaves\n // the low bits 0x0 and simply adds one to the high bits.\n highBits += 1;\n }\n return newBits(lowBits, highBits);\n}\n/**\n * Returns decimal representation of digit1e7 with leading zeros.\n */\nconst decimalFrom1e7WithLeadingZeros = (digit1e7) => {\n const partial = String(digit1e7);\n return \"0000000\".slice(partial.length) + partial;\n};\n/**\n * Write a 32 bit varint, signed or unsigned. Same as `varint64write(0, value, bytes)`\n *\n * Copyright 2008 Google Inc. All rights reserved.\n *\n * See https://github.com/protocolbuffers/protobuf/blob/1b18833f4f2a2f681f4e4a25cdf3b0a43115ec26/js/binary/encoder.js#L144\n */\nexport function varint32write(value, bytes) {\n if (value >= 0) {\n // write value as varint 32\n while (value > 0x7f) {\n bytes.push((value & 0x7f) | 0x80);\n value = value >>> 7;\n }\n bytes.push(value);\n }\n else {\n for (let i = 0; i < 9; i++) {\n bytes.push((value & 127) | 128);\n value = value >> 7;\n }\n bytes.push(1);\n }\n}\n/**\n * Read an unsigned 32 bit varint.\n *\n * See https://github.com/protocolbuffers/protobuf/blob/8a71927d74a4ce34efe2d8769fda198f52d20d12/js/experimental/runtime/kernel/buffer_decoder.js#L220\n */\nexport function varint32read() {\n let b = this.buf[this.pos++];\n let result = b & 0x7f;\n if ((b & 0x80) == 0) {\n this.assertBounds();\n return result;\n }\n b = this.buf[this.pos++];\n result |= (b & 0x7f) << 7;\n if ((b & 0x80) == 0) {\n this.assertBounds();\n return result;\n }\n b = this.buf[this.pos++];\n result |= (b & 0x7f) << 14;\n if ((b & 0x80) == 0) {\n this.assertBounds();\n return result;\n }\n b = this.buf[this.pos++];\n result |= (b & 0x7f) << 21;\n if ((b & 0x80) == 0) {\n this.assertBounds();\n return result;\n }\n // Extract only last 4 bits\n b = this.buf[this.pos++];\n result |= (b & 0x0f) << 28;\n for (let readBytes = 5; (b & 0x80) !== 0 && readBytes < 10; readBytes++)\n b = this.buf[this.pos++];\n if ((b & 0x80) != 0)\n throw new Error(\"invalid varint\");\n this.assertBounds();\n // Result can have 32 bits, convert it to unsigned\n return result >>> 0;\n}\n", "// Copyright 2021-2026 Buf Technologies, Inc.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nimport { int64FromString, int64ToString, uInt64ToString, } from \"./wire/varint.js\";\n/**\n * Int64Support for the current environment.\n */\nexport const protoInt64 = /*@__PURE__*/ makeInt64Support();\nfunction makeInt64Support() {\n const dv = new DataView(new ArrayBuffer(8));\n // note that Safari 14 implements BigInt, but not the DataView methods\n const ok = typeof BigInt === \"function\" &&\n typeof dv.getBigInt64 === \"function\" &&\n typeof dv.getBigUint64 === \"function\" &&\n typeof dv.setBigInt64 === \"function\" &&\n typeof dv.setBigUint64 === \"function\" &&\n (!!globalThis.Deno ||\n typeof process != \"object\" ||\n typeof process.env != \"object\" ||\n process.env.BUF_BIGINT_DISABLE !== \"1\");\n if (ok) {\n const MIN = BigInt(\"-9223372036854775808\");\n const MAX = BigInt(\"9223372036854775807\");\n const UMIN = BigInt(\"0\");\n const UMAX = BigInt(\"18446744073709551615\");\n return {\n zero: BigInt(0),\n supported: true,\n parse(value) {\n const bi = typeof value == \"bigint\" ? value : BigInt(value);\n if (bi > MAX || bi < MIN) {\n throw new Error(`invalid int64: ${value}`);\n }\n return bi;\n },\n uParse(value) {\n const bi = typeof value == \"bigint\" ? value : BigInt(value);\n if (bi > UMAX || bi < UMIN) {\n throw new Error(`invalid uint64: ${value}`);\n }\n return bi;\n },\n enc(value) {\n dv.setBigInt64(0, this.parse(value), true);\n return {\n lo: dv.getInt32(0, true),\n hi: dv.getInt32(4, true),\n };\n },\n uEnc(value) {\n dv.setBigInt64(0, this.uParse(value), true);\n return {\n lo: dv.getInt32(0, true),\n hi: dv.getInt32(4, true),\n };\n },\n dec(lo, hi) {\n dv.setInt32(0, lo, true);\n dv.setInt32(4, hi, true);\n return dv.getBigInt64(0, true);\n },\n uDec(lo, hi) {\n dv.setInt32(0, lo, true);\n dv.setInt32(4, hi, true);\n return dv.getBigUint64(0, true);\n },\n };\n }\n return {\n zero: \"0\",\n supported: false,\n parse(value) {\n if (typeof value != \"string\") {\n value = value.toString();\n }\n assertInt64String(value);\n return value;\n },\n uParse(value) {\n if (typeof value != \"string\") {\n value = value.toString();\n }\n assertUInt64String(value);\n return value;\n },\n enc(value) {\n if (typeof value != \"string\") {\n value = value.toString();\n }\n assertInt64String(value);\n return int64FromString(value);\n },\n uEnc(value) {\n if (typeof value != \"string\") {\n value = value.toString();\n }\n assertUInt64String(value);\n return int64FromString(value);\n },\n dec(lo, hi) {\n return int64ToString(lo, hi);\n },\n uDec(lo, hi) {\n return uInt64ToString(lo, hi);\n },\n };\n}\nfunction assertInt64String(value) {\n if (!/^-?[0-9]+$/.test(value)) {\n throw new Error(\"invalid int64: \" + value);\n }\n}\nfunction assertUInt64String(value) {\n if (!/^[0-9]+$/.test(value)) {\n throw new Error(\"invalid uint64: \" + value);\n }\n}\n", "// Copyright 2021-2026 Buf Technologies, Inc.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nconst symbol = Symbol.for(\"@bufbuild/protobuf/text-encoding\");\n/**\n * Protobuf-ES requires the Text Encoding API to convert UTF-8 from and to\n * binary. This WHATWG API is widely available, but it is not part of the\n * ECMAScript standard. On runtimes where it is not available, use this\n * function to provide your own implementation.\n *\n * Note that the Text Encoding API does not provide a way to validate UTF-8.\n * Our implementation falls back to use encodeURIComponent().\n */\nexport function configureTextEncoding(textEncoding) {\n globalThis[symbol] = textEncoding;\n}\nexport function getTextEncoding() {\n if (globalThis[symbol] == undefined) {\n const te = new globalThis.TextEncoder();\n const td = new globalThis.TextDecoder();\n let tdStrict;\n globalThis[symbol] = {\n encodeUtf8(text) {\n return te.encode(text);\n },\n decodeUtf8(bytes, strict) {\n if (strict) {\n if (tdStrict === undefined) {\n tdStrict = new globalThis.TextDecoder(\"utf-8\", { fatal: true });\n }\n return tdStrict.decode(bytes);\n }\n return td.decode(bytes);\n },\n checkUtf8(text) {\n try {\n encodeURIComponent(text);\n return true;\n }\n catch (_) {\n return false;\n }\n },\n };\n }\n return globalThis[symbol];\n}\n", "// Copyright 2021-2026 Buf Technologies, Inc.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\nimport { varint32read, varint32write, varint64read, varint64write, } from \"./varint.js\";\nimport { protoInt64 } from \"../proto-int64.js\";\nimport { getTextEncoding } from \"./text-encoding.js\";\n/**\n * Protobuf binary format wire types.\n *\n * A wire type provides just enough information to find the length of the\n * following value.\n *\n * See https://developers.google.com/protocol-buffers/docs/encoding#structure\n */\nexport var WireType;\n(function (WireType) {\n /**\n * Used for int32, int64, uint32, uint64, sint32, sint64, bool, enum\n */\n WireType[WireType[\"Varint\"] = 0] = \"Varint\";\n /**\n * Used for fixed64, sfixed64, double.\n * Always 8 bytes with little-endian byte order.\n */\n WireType[WireType[\"Bit64\"] = 1] = \"Bit64\";\n /**\n * Used for string, bytes, embedded messages, packed repeated fields\n *\n * Only repeated numeric types (types which use the varint, 32-bit,\n * or 64-bit wire types) can be packed. In proto3, such fields are\n * packed by default.\n */\n WireType[WireType[\"LengthDelimited\"] = 2] = \"LengthDelimited\";\n /**\n * Start of a tag-delimited aggregate, such as a proto2 group, or a message\n * in editions with message_encoding = DELIMITED.\n */\n WireType[WireType[\"StartGroup\"] = 3] = \"StartGroup\";\n /**\n * End of a tag-delimited aggregate.\n */\n WireType[WireType[\"EndGroup\"] = 4] = \"EndGroup\";\n /**\n * Used for fixed32, sfixed32, float.\n * Always 4 bytes with little-endian byte order.\n */\n WireType[WireType[\"Bit32\"] = 5] = \"Bit32\";\n})(WireType || (WireType = {}));\n/**\n * Maximum value for a 32-bit floating point value (Protobuf FLOAT).\n */\nexport const FLOAT32_MAX = 3.4028234663852886e38;\n/**\n * Minimum value for a 32-bit floating point value (Protobuf FLOAT).\n */\nexport const FLOAT32_MIN = -3.4028234663852886e38;\n/**\n * Maximum value for an unsigned 32-bit integer (Protobuf UINT32, FIXED32).\n */\nexport const UINT32_MAX = 0xffffffff;\n/**\n * Maximum value for a signed 32-bit integer (Protobuf INT32, SFIXED32, SINT32).\n */\nexport const INT32_MAX = 0x7fffffff;\n/**\n * Minimum value for a signed 32-bit integer (Protobuf INT32, SFIXED32, SINT32).\n */\nexport const INT32_MIN = -0x80000000;\nexport class BinaryWriter {\n constructor(encodeUtf8 = getTextEncoding().encodeUtf8) {\n this.encodeUtf8 = encodeUtf8;\n /**\n * Previous fork states.\n */\n this.stack = [];\n this.chunks = [];\n this.buf = [];\n }\n /**\n * Return all bytes written and reset this writer.\n */\n finish() {\n if (this.buf.length) {\n this.chunks.push(new Uint8Array(this.buf)); // flush the buffer\n this.buf = [];\n }\n let len = 0;\n for (let i = 0; i < this.chunks.length; i++)\n len += this.chunks[i].length;\n let bytes = new Uint8Array(len);\n let offset = 0;\n for (let i = 0; i < this.chunks.length; i++) {\n bytes.set(this.chunks[i], offset);\n offset += this.chunks[i].length;\n }\n this.chunks = [];\n return bytes;\n }\n /**\n * Start a new fork for length-delimited data like a message\n * or a packed repeated field.\n *\n * Must be joined later with `join()`.\n */\n fork() {\n this.stack.push({ chunks: this.chunks, buf: this.buf });\n this.chunks = [];\n this.buf = [];\n return this;\n }\n /**\n * Join the last fork. Write its length and bytes, then\n * return to the previous state.\n */\n join() {\n // get chunk of fork\n let chunk = this.finish();\n // restore previous state\n let prev = this.stack.pop();\n if (!prev)\n throw new Error(\"invalid state, fork stack empty\");\n this.chunks = prev.chunks;\n this.buf = prev.buf;\n // write length of chunk as varint\n this.uint32(chunk.byteLength);\n return this.raw(chunk);\n }\n /**\n * Writes a tag (field number and wire type).\n *\n * Equivalent to `uint32( (fieldNo << 3 | type) >>> 0 )`.\n *\n * Generated code should compute the tag ahead of time and call `uint32()`.\n */\n tag(fieldNo, type) {\n return this.uint32(((fieldNo << 3) | type) >>> 0);\n }\n /**\n * Write a chunk of raw bytes.\n */\n raw(chunk) {\n if (this.buf.length) {\n this.chunks.push(new Uint8Array(this.buf));\n this.buf = [];\n }\n this.chunks.push(chunk);\n return this;\n }\n /**\n * Write a `uint32` value, an unsigned 32 bit varint.\n */\n uint32(value) {\n assertUInt32(value);\n // write value as varint 32, inlined for speed\n while (value > 0x7f) {\n this.buf.push((value & 0x7f) | 0x80);\n value = value >>> 7;\n }\n this.buf.push(value);\n return this;\n }\n /**\n * Write a `int32` value, a signed 32 bit varint.\n */\n int32(value) {\n assertInt32(value);\n varint32write(value, this.buf);\n return this;\n }\n /**\n * Write a `bool` value, a varint.\n */\n bool(value) {\n this.buf.push(value ? 1 : 0);\n return this;\n }\n /**\n * Write a `bytes` value, length-delimited arbitrary data.\n */\n bytes(value) {\n this.uint32(value.byteLength); // write length of chunk as varint\n return this.raw(value);\n }\n /**\n * Write a `string` value, length-delimited data converted to UTF-8 text.\n */\n string(value) {\n let chunk = this.encodeUtf8(value);\n this.uint32(chunk.byteLength); // write length of chunk as varint\n return this.raw(chunk);\n }\n /**\n * Write a `float` value, 32-bit floating point number.\n */\n float(value) {\n assertFloat32(value);\n let chunk = new Uint8Array(4);\n new DataView(chunk.buffer).setFloat32(0, value, true);\n return this.raw(chunk);\n }\n /**\n * Write a `double` value, a 64-bit floating point number.\n */\n double(value) {\n let chunk = new Uint8Array(8);\n new DataView(chunk.buffer).setFloat64(0, value, true);\n return this.raw(chunk);\n }\n /**\n * Write a `fixed32` value, an unsigned, fixed-length 32-bit integer.\n */\n fixed32(value) {\n assertUInt32(value);\n let chunk = new Uint8Array(4);\n new DataView(chunk.buffer).setUint32(0, value, true);\n return this.raw(chunk);\n }\n /**\n * Write a `sfixed32` value, a signed, fixed-length 32-bit integer.\n */\n sfixed32(value) {\n assertInt32(value);\n let chunk = new Uint8Array(4);\n new DataView(chunk.buffer).setInt32(0, value, true);\n return this.raw(chunk);\n }\n /**\n * Write a `sint32` value, a signed, zigzag-encoded 32-bit varint.\n */\n sint32(value) {\n assertInt32(value);\n // zigzag encode\n value = ((value << 1) ^ (value >> 31)) >>> 0;\n varint32write(value, this.buf);\n return this;\n }\n /**\n * Write a `sfixed64` value, a signed, fixed-length 64-bit integer.\n */\n sfixed64(value) {\n let chunk = new Uint8Array(8), view = new DataView(chunk.buffer), tc = protoInt64.enc(value);\n view.setInt32(0, tc.lo, true);\n view.setInt32(4, tc.hi, true);\n return this.raw(chunk);\n }\n /**\n * Write a `fixed64` value, an unsigned, fixed-length 64 bit integer.\n */\n fixed64(value) {\n let chunk = new Uint8Array(8), view = new DataView(chunk.buffer), tc = protoInt64.uEnc(value);\n view.setInt32(0, tc.lo, true);\n view.setInt32(4, tc.hi, true);\n return this.raw(chunk);\n }\n /**\n * Write a `int64` value, a signed 64-bit varint.\n */\n int64(value) {\n let tc = protoInt64.enc(value);\n varint64write(tc.lo, tc.hi, this.buf);\n return this;\n }\n /**\n * Write a `sint64` value, a signed, zig-zag-encoded 64-bit varint.\n */\n sint64(value) {\n const tc = protoInt64.enc(value), \n // zigzag encode\n sign = tc.hi >> 31, lo = (tc.lo << 1) ^ sign, hi = ((tc.hi << 1) | (tc.lo >>> 31)) ^ sign;\n varint64write(lo, hi, this.buf);\n return this;\n }\n /**\n * Write a `uint64` value, an unsigned 64-bit varint.\n */\n uint64(value) {\n const tc = protoInt64.uEnc(value);\n varint64write(tc.lo, tc.hi, this.buf);\n return this;\n }\n}\nexport class BinaryReader {\n constructor(buf, decodeUtf8 = getTextEncoding().decodeUtf8) {\n this.decodeUtf8 = decodeUtf8;\n this.varint64 = varint64read; // dirty cast for `this`\n /**\n * Read a `uint32` field, an unsigned 32 bit varint.\n */\n this.uint32 = varint32read;\n this.buf = buf;\n this.len = buf.length;\n this.pos = 0;\n this.view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);\n }\n /**\n * Reads a tag - field number and wire type. Tags are uint32 varints; values\n * that do not fit in uint32 are rejected.\n */\n tag() {\n const start = this.pos;\n const tag = this.uint32();\n const bytesRead = this.pos - start;\n if (bytesRead > 5 || (bytesRead == 5 && this.buf[this.pos - 1] > 0x0f)) {\n throw new Error(\"illegal tag: varint overflows uint32\");\n }\n const fieldNo = tag >>> 3;\n const wireType = tag & 7;\n if (fieldNo <= 0 || wireType > 5) {\n throw new Error(\"illegal tag: field no \" + fieldNo + \" wire type \" + wireType);\n }\n return [fieldNo, wireType];\n }\n /**\n * Skip one element and return the skipped data.\n *\n * When skipping StartGroup, provide the tags field number to check for\n * matching field number in the EndGroup tag.\n */\n skip(wireType, fieldNo) {\n let start = this.pos;\n switch (wireType) {\n case WireType.Varint:\n while (this.buf[this.pos++] & 0x80) {\n // ignore\n }\n break;\n // @ts-ignore TS7029: Fallthrough case in switch -- ignore instead of expect-error for compiler settings without noFallthroughCasesInSwitch: true\n case WireType.Bit64:\n this.pos += 4;\n case WireType.Bit32:\n this.pos += 4;\n break;\n case WireType.LengthDelimited:\n let len = this.uint32();\n this.pos += len;\n break;\n case WireType.StartGroup:\n for (;;) {\n const [fn, wt] = this.tag();\n if (wt === WireType.EndGroup) {\n if (fieldNo !== undefined && fn !== fieldNo) {\n throw new Error(\"invalid end group tag\");\n }\n break;\n }\n this.skip(wt, fn);\n }\n break;\n default:\n throw new Error(\"cant skip wire type \" + wireType);\n }\n this.assertBounds();\n return this.buf.subarray(start, this.pos);\n }\n /**\n * Throws error if position in byte array is out of range.\n */\n assertBounds() {\n if (this.pos > this.len)\n throw new RangeError(\"premature EOF\");\n }\n /**\n * Read a `int32` field, a signed 32 bit varint.\n */\n int32() {\n return this.uint32() | 0;\n }\n /**\n * Read a `sint32` field, a signed, zigzag-encoded 32-bit varint.\n */\n sint32() {\n let zze = this.uint32();\n // decode zigzag\n return (zze >>> 1) ^ -(zze & 1);\n }\n /**\n * Read a `int64` field, a signed 64-bit varint.\n */\n int64() {\n return protoInt64.dec(...this.varint64());\n }\n /**\n * Read a `uint64` field, an unsigned 64-bit varint.\n */\n uint64() {\n return protoInt64.uDec(...this.varint64());\n }\n /**\n * Read a `sint64` field, a signed, zig-zag-encoded 64-bit varint.\n */\n sint64() {\n let [lo, hi] = this.varint64();\n // decode zig zag\n let s = -(lo & 1);\n lo = ((lo >>> 1) | ((hi & 1) << 31)) ^ s;\n hi = (hi >>> 1) ^ s;\n return protoInt64.dec(lo, hi);\n }\n /**\n * Read a `bool` field, a variant.\n */\n bool() {\n let [lo, hi] = this.varint64();\n return lo !== 0 || hi !== 0;\n }\n /**\n * Read a `fixed32` field, an unsigned, fixed-length 32-bit integer.\n */\n fixed32() {\n // biome-ignore lint/suspicious/noAssignInExpressions: no\n return this.view.getUint32((this.pos += 4) - 4, true);\n }\n /**\n * Read a `sfixed32` field, a signed, fixed-length 32-bit integer.\n */\n sfixed32() {\n // biome-ignore lint/suspicious/noAssignInExpressions: no\n return this.view.getInt32((this.pos += 4) - 4, true);\n }\n /**\n * Read a `fixed64` field, an unsigned, fixed-length 64 bit integer.\n */\n fixed64() {\n return protoInt64.uDec(this.sfixed32(), this.sfixed32());\n }\n /**\n * Read a `fixed64` field, a signed, fixed-length 64-bit integer.\n */\n sfixed64() {\n return protoInt64.dec(this.sfixed32(), this.sfixed32());\n }\n /**\n * Read a `float` field, 32-bit floating point number.\n */\n float() {\n // biome-ignore lint/suspicious/noAssignInExpressions: no\n return this.view.getFloat32((this.pos += 4) - 4, true);\n }\n /**\n * Read a `double` field, a 64-bit floating point number.\n */\n double() {\n // biome-ignore lint/suspicious/noAssignInExpressions: no\n return this.view.getFloat64((this.pos += 8) - 8, true);\n }\n /**\n * Read a `bytes` field, length-delimited arbitrary data.\n */\n bytes() {\n let len = this.uint32(), start = this.pos;\n this.pos += len;\n this.assertBounds();\n return this.buf.subarray(start, start + len);\n }\n /**\n * Read a `string` field, length-delimited data converted to UTF-8 text. If\n * `strict` is true, throw on invalid UTF-8 instead of substituting U+FFFD.\n */\n string(strict) {\n return this.decodeUtf8(this.bytes(), strict);\n }\n}\n/**\n * Assert a valid signed protobuf 32-bit integer as a number or string.\n */\nfunction assertInt32(arg) {\n if (typeof arg == \"string\") {\n arg = Number(arg);\n }\n else if (typeof arg != \"number\") {\n throw new Error(\"invalid int32: \" + typeof arg);\n }\n if (!Number.isInteger(arg) ||\n arg > INT32_MAX ||\n arg < INT32_MIN)\n throw new Error(\"invalid int32: \" + arg);\n}\n/**\n * Assert a valid unsigned protobuf 32-bit integer as a number or string.\n */\nfunction assertUInt32(arg) {\n if (typeof arg == \"string\") {\n arg = Number(arg);\n }\n else if (typeof arg != \"number\") {\n throw new Error(\"invalid uint32: \" + typeof arg);\n }\n if (!Number.isInteger(arg) ||\n arg > UINT32_MAX ||\n arg < 0)\n throw new Error(\"invalid uint32: \" + arg);\n}\n/**\n * Assert a valid protobuf float value as a number or string.\n */\nfunction assertFloat32(arg) {\n if (typeof arg == \"string\") {\n const o = arg;\n arg = Number(arg);\n if (Number.isNaN(arg) && o !== \"NaN\") {\n throw new Error(\"invalid float32: \" + o);\n }\n }\n else if (typeof arg != \"number\") {\n throw new Error(\"invalid float32: \" + typeof arg);\n }\n if (Number.isFinite(arg) &&\n (arg > FLOAT32_MAX || arg < FLOAT32_MIN))\n throw new Error(\"invalid float32: \" + arg);\n}\n", "// Code generated by protoc-gen-ts_proto. DO NOT EDIT.\n// versions:\n// protoc-gen-ts_proto v2.7.7\n// protoc v4.25.9\n// source: google/protobuf/struct.proto\n\n/* eslint-disable */\nimport { BinaryReader, BinaryWriter } from \"@bufbuild/protobuf/wire\";\n\nexport const protobufPackage = \"google.protobuf\";\n\n/**\n * `NullValue` is a singleton enumeration to represent the null value for the\n * `Value` type union.\n *\n * The JSON representation for `NullValue` is JSON `null`.\n */\nexport enum NullValue {\n /** NULL_VALUE - Null value. */\n NULL_VALUE = 0,\n UNRECOGNIZED = -1,\n}\n\n/**\n * `Struct` represents a structured data value, consisting of fields\n * which map to dynamically typed values. In some languages, `Struct`\n * might be supported by a native representation. For example, in\n * scripting languages like JS a struct is represented as an\n * object. The details of that representation are described together\n * with the proto support for the language.\n *\n * The JSON representation for `Struct` is JSON object.\n */\nexport interface Struct {\n /** Unordered map of dynamically typed values. */\n fields: { [key: string]: any | undefined };\n}\n\nexport interface Struct_FieldsEntry {\n key: string;\n value: any | undefined;\n}\n\n/**\n * `Value` represents a dynamically typed value which can be either\n * null, a number, a string, a boolean, a recursive struct value, or a\n * list of values. A producer of value is expected to set one of these\n * variants. Absence of any variant indicates an error.\n *\n * The JSON representation for `Value` is JSON value.\n */\nexport interface Value {\n /** Represents a null value. */\n nullValue?:\n | NullValue\n | undefined;\n /** Represents a double value. */\n numberValue?:\n | number\n | undefined;\n /** Represents a string value. */\n stringValue?:\n | string\n | undefined;\n /** Represents a boolean value. */\n boolValue?:\n | boolean\n | undefined;\n /** Represents a structured value. */\n structValue?:\n | { [key: string]: any }\n | undefined;\n /** Represents a repeated `Value`. */\n listValue?: Array<any> | undefined;\n}\n\n/**\n * `ListValue` is a wrapper around a repeated field of values.\n *\n * The JSON representation for `ListValue` is JSON array.\n */\nexport interface ListValue {\n /** Repeated field of dynamically typed values. */\n values: any[];\n}\n\nfunction createBaseStruct(): Struct {\n return { fields: {} };\n}\n\nexport const Struct: MessageFns<Struct> & StructWrapperFns = {\n encode(message: Struct, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n Object.entries(message.fields).forEach(([key, value]) => {\n if (value !== undefined) {\n Struct_FieldsEntry.encode({ key: key as any, value }, writer.uint32(10).fork()).join();\n }\n });\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): Struct {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseStruct();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 10) {\n break;\n }\n\n const entry1 = Struct_FieldsEntry.decode(reader, reader.uint32());\n if (entry1.value !== undefined) {\n message.fields[entry1.key] = entry1.value;\n }\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<Struct>, I>>(base?: I): Struct {\n return Struct.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<Struct>, I>>(object: I): Struct {\n const message = createBaseStruct();\n message.fields = Object.entries(object.fields ?? {}).reduce<{ [key: string]: any | undefined }>(\n (acc, [key, value]) => {\n if (value !== undefined) {\n acc[key] = value;\n }\n return acc;\n },\n {},\n );\n return message;\n },\n\n wrap(object: { [key: string]: any } | undefined): Struct {\n const struct = createBaseStruct();\n\n if (object !== undefined) {\n for (const key of Object.keys(object)) {\n struct.fields[key] = object[key];\n }\n }\n return struct;\n },\n\n unwrap(message: Struct): { [key: string]: any } {\n const object: { [key: string]: any } = {};\n if (message.fields) {\n for (const key of Object.keys(message.fields)) {\n object[key] = message.fields[key];\n }\n }\n return object;\n },\n};\n\nfunction createBaseStruct_FieldsEntry(): Struct_FieldsEntry {\n return { key: \"\", value: undefined };\n}\n\nexport const Struct_FieldsEntry: MessageFns<Struct_FieldsEntry> = {\n encode(message: Struct_FieldsEntry, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n if (message.key !== \"\") {\n writer.uint32(10).string(message.key);\n }\n if (message.value !== undefined) {\n Value.encode(Value.wrap(message.value), writer.uint32(18).fork()).join();\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): Struct_FieldsEntry {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseStruct_FieldsEntry();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 10) {\n break;\n }\n\n message.key = reader.string();\n continue;\n }\n case 2: {\n if (tag !== 18) {\n break;\n }\n\n message.value = Value.unwrap(Value.decode(reader, reader.uint32()));\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<Struct_FieldsEntry>, I>>(base?: I): Struct_FieldsEntry {\n return Struct_FieldsEntry.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<Struct_FieldsEntry>, I>>(object: I): Struct_FieldsEntry {\n const message = createBaseStruct_FieldsEntry();\n message.key = object.key ?? \"\";\n message.value = object.value ?? undefined;\n return message;\n },\n};\n\nfunction createBaseValue(): Value {\n return {\n nullValue: undefined,\n numberValue: undefined,\n stringValue: undefined,\n boolValue: undefined,\n structValue: undefined,\n listValue: undefined,\n };\n}\n\nexport const Value: MessageFns<Value> & AnyValueWrapperFns = {\n encode(message: Value, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n if (message.nullValue !== undefined) {\n writer.uint32(8).int32(message.nullValue);\n }\n if (message.numberValue !== undefined) {\n writer.uint32(17).double(message.numberValue);\n }\n if (message.stringValue !== undefined) {\n writer.uint32(26).string(message.stringValue);\n }\n if (message.boolValue !== undefined) {\n writer.uint32(32).bool(message.boolValue);\n }\n if (message.structValue !== undefined) {\n Struct.encode(Struct.wrap(message.structValue), writer.uint32(42).fork()).join();\n }\n if (message.listValue !== undefined) {\n ListValue.encode(ListValue.wrap(message.listValue), writer.uint32(50).fork()).join();\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): Value {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseValue();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 8) {\n break;\n }\n\n message.nullValue = reader.int32() as any;\n continue;\n }\n case 2: {\n if (tag !== 17) {\n break;\n }\n\n message.numberValue = reader.double();\n continue;\n }\n case 3: {\n if (tag !== 26) {\n break;\n }\n\n message.stringValue = reader.string();\n continue;\n }\n case 4: {\n if (tag !== 32) {\n break;\n }\n\n message.boolValue = reader.bool();\n continue;\n }\n case 5: {\n if (tag !== 42) {\n break;\n }\n\n message.structValue = Struct.unwrap(Struct.decode(reader, reader.uint32()));\n continue;\n }\n case 6: {\n if (tag !== 50) {\n break;\n }\n\n message.listValue = ListValue.unwrap(ListValue.decode(reader, reader.uint32()));\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<Value>, I>>(base?: I): Value {\n return Value.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<Value>, I>>(object: I): Value {\n const message = createBaseValue();\n message.nullValue = object.nullValue ?? undefined;\n message.numberValue = object.numberValue ?? undefined;\n message.stringValue = object.stringValue ?? undefined;\n message.boolValue = object.boolValue ?? undefined;\n message.structValue = object.structValue ?? undefined;\n message.listValue = object.listValue ?? undefined;\n return message;\n },\n\n wrap(value: any): Value {\n const result = createBaseValue();\n if (value === null) {\n result.nullValue = NullValue.NULL_VALUE;\n } else if (typeof value === \"boolean\") {\n result.boolValue = value;\n } else if (typeof value === \"number\") {\n result.numberValue = value;\n } else if (typeof value === \"string\") {\n result.stringValue = value;\n } else if (globalThis.Array.isArray(value)) {\n result.listValue = value;\n } else if (typeof value === \"object\") {\n result.structValue = value;\n } else if (typeof value !== \"undefined\") {\n throw new globalThis.Error(\"Unsupported any value type: \" + typeof value);\n }\n return result;\n },\n\n unwrap(message: any): string | number | boolean | Object | null | Array<any> | undefined {\n if (message.stringValue !== undefined) {\n return message.stringValue;\n } else if (message?.numberValue !== undefined) {\n return message.numberValue;\n } else if (message?.boolValue !== undefined) {\n return message.boolValue;\n } else if (message?.structValue !== undefined) {\n return message.structValue as any;\n } else if (message?.listValue !== undefined) {\n return message.listValue;\n } else if (message?.nullValue !== undefined) {\n return null;\n }\n return undefined;\n },\n};\n\nfunction createBaseListValue(): ListValue {\n return { values: [] };\n}\n\nexport const ListValue: MessageFns<ListValue> & ListValueWrapperFns = {\n encode(message: ListValue, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n for (const v of message.values) {\n Value.encode(Value.wrap(v!), writer.uint32(10).fork()).join();\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): ListValue {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseListValue();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 10) {\n break;\n }\n\n message.values.push(Value.unwrap(Value.decode(reader, reader.uint32())));\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<ListValue>, I>>(base?: I): ListValue {\n return ListValue.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<ListValue>, I>>(object: I): ListValue {\n const message = createBaseListValue();\n message.values = object.values?.map((e) => e) || [];\n return message;\n },\n\n wrap(array: Array<any> | undefined): ListValue {\n const result = createBaseListValue();\n result.values = array ?? [];\n return result;\n },\n\n unwrap(message: ListValue): Array<any> {\n if (message?.hasOwnProperty(\"values\") && globalThis.Array.isArray(message.values)) {\n return message.values;\n } else {\n return message as any;\n }\n },\n};\n\ntype Builtin = Date | Function | Uint8Array | string | number | boolean | undefined;\n\nexport type DeepPartial<T> = T extends Builtin ? T\n : T extends globalThis.Array<infer U> ? globalThis.Array<DeepPartial<U>>\n : T extends ReadonlyArray<infer U> ? ReadonlyArray<DeepPartial<U>>\n : T extends {} ? { [K in keyof T]?: DeepPartial<T[K]> }\n : Partial<T>;\n\ntype KeysOfUnion<T> = T extends T ? keyof T : never;\nexport type Exact<P, I extends P> = P extends Builtin ? P\n : P & { [K in keyof P]: Exact<P[K], I[K]> } & { [K in Exclude<keyof I, KeysOfUnion<P>>]: never };\n\nexport interface MessageFns<T> {\n encode(message: T, writer?: BinaryWriter): BinaryWriter;\n decode(input: BinaryReader | Uint8Array, length?: number): T;\n create<I extends Exact<DeepPartial<T>, I>>(base?: I): T;\n fromPartial<I extends Exact<DeepPartial<T>, I>>(object: I): T;\n}\n\nexport interface StructWrapperFns {\n wrap(object: { [key: string]: any } | undefined): Struct;\n unwrap(message: Struct): { [key: string]: any };\n}\n\nexport interface AnyValueWrapperFns {\n wrap(value: any): Value;\n unwrap(message: any): string | number | boolean | Object | null | Array<any> | undefined;\n}\n\nexport interface ListValueWrapperFns {\n wrap(array: Array<any> | undefined): ListValue;\n unwrap(message: ListValue): Array<any>;\n}\n", "// Code generated by protoc-gen-ts_proto. DO NOT EDIT.\n// versions:\n// protoc-gen-ts_proto v2.7.7\n// protoc v4.25.9\n// source: patch.proto\n\n/* eslint-disable */\nimport { BinaryReader, BinaryWriter } from \"@bufbuild/protobuf/wire\";\nimport { Value } from \"./google/protobuf/struct\";\n\nexport const protobufPackage = \"ag_ui\";\n\nexport enum JsonPatchOperationType {\n ADD = 0,\n REMOVE = 1,\n REPLACE = 2,\n MOVE = 3,\n COPY = 4,\n TEST = 5,\n UNRECOGNIZED = -1,\n}\n\nexport interface JsonPatchOperation {\n op: JsonPatchOperationType;\n path: string;\n from?: string | undefined;\n value?: any | undefined;\n}\n\nfunction createBaseJsonPatchOperation(): JsonPatchOperation {\n return { op: 0, path: \"\", from: undefined, value: undefined };\n}\n\nexport const JsonPatchOperation: MessageFns<JsonPatchOperation> = {\n encode(message: JsonPatchOperation, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n if (message.op !== 0) {\n writer.uint32(8).int32(message.op);\n }\n if (message.path !== \"\") {\n writer.uint32(18).string(message.path);\n }\n if (message.from !== undefined) {\n writer.uint32(26).string(message.from);\n }\n if (message.value !== undefined) {\n Value.encode(Value.wrap(message.value), writer.uint32(34).fork()).join();\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): JsonPatchOperation {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseJsonPatchOperation();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 8) {\n break;\n }\n\n message.op = reader.int32() as any;\n continue;\n }\n case 2: {\n if (tag !== 18) {\n break;\n }\n\n message.path = reader.string();\n continue;\n }\n case 3: {\n if (tag !== 26) {\n break;\n }\n\n message.from = reader.string();\n continue;\n }\n case 4: {\n if (tag !== 34) {\n break;\n }\n\n message.value = Value.unwrap(Value.decode(reader, reader.uint32()));\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<JsonPatchOperation>, I>>(base?: I): JsonPatchOperation {\n return JsonPatchOperation.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<JsonPatchOperation>, I>>(object: I): JsonPatchOperation {\n const message = createBaseJsonPatchOperation();\n message.op = object.op ?? 0;\n message.path = object.path ?? \"\";\n message.from = object.from ?? undefined;\n message.value = object.value ?? undefined;\n return message;\n },\n};\n\ntype Builtin = Date | Function | Uint8Array | string | number | boolean | undefined;\n\nexport type DeepPartial<T> = T extends Builtin ? T\n : T extends globalThis.Array<infer U> ? globalThis.Array<DeepPartial<U>>\n : T extends ReadonlyArray<infer U> ? ReadonlyArray<DeepPartial<U>>\n : T extends {} ? { [K in keyof T]?: DeepPartial<T[K]> }\n : Partial<T>;\n\ntype KeysOfUnion<T> = T extends T ? keyof T : never;\nexport type Exact<P, I extends P> = P extends Builtin ? P\n : P & { [K in keyof P]: Exact<P[K], I[K]> } & { [K in Exclude<keyof I, KeysOfUnion<P>>]: never };\n\nexport interface MessageFns<T> {\n encode(message: T, writer?: BinaryWriter): BinaryWriter;\n decode(input: BinaryReader | Uint8Array, length?: number): T;\n create<I extends Exact<DeepPartial<T>, I>>(base?: I): T;\n fromPartial<I extends Exact<DeepPartial<T>, I>>(object: I): T;\n}\n", "// Code generated by protoc-gen-ts_proto. DO NOT EDIT.\n// versions:\n// protoc-gen-ts_proto v2.7.7\n// protoc v4.25.9\n// source: types.proto\n\n/* eslint-disable */\nimport { BinaryReader, BinaryWriter } from \"@bufbuild/protobuf/wire\";\nimport { Value } from \"./google/protobuf/struct\";\n\nexport const protobufPackage = \"ag_ui\";\n\nexport interface ToolCall {\n id: string;\n type: string;\n function: ToolCall_Function | undefined;\n}\n\nexport interface ToolCall_Function {\n name: string;\n arguments: string;\n}\n\nexport interface InputContentDataSource {\n value: string;\n mimeType: string;\n}\n\nexport interface InputContentUrlSource {\n value: string;\n mimeType?: string | undefined;\n}\n\nexport interface InputContentSource {\n data?: InputContentDataSource | undefined;\n url?: InputContentUrlSource | undefined;\n}\n\nexport interface TextInputPart {\n text: string;\n}\n\nexport interface ImageInputPart {\n source: InputContentSource | undefined;\n metadata?: any | undefined;\n}\n\nexport interface AudioInputPart {\n source: InputContentSource | undefined;\n metadata?: any | undefined;\n}\n\nexport interface VideoInputPart {\n source: InputContentSource | undefined;\n metadata?: any | undefined;\n}\n\nexport interface DocumentInputPart {\n source: InputContentSource | undefined;\n metadata?: any | undefined;\n}\n\nexport interface InputContent {\n text?: TextInputPart | undefined;\n image?: ImageInputPart | undefined;\n audio?: AudioInputPart | undefined;\n video?: VideoInputPart | undefined;\n document?: DocumentInputPart | undefined;\n}\n\nexport interface Message {\n id: string;\n role: string;\n content?: string | undefined;\n name?: string | undefined;\n toolCalls: ToolCall[];\n toolCallId?: string | undefined;\n error?: string | undefined;\n contentParts: InputContent[];\n}\n\nexport interface Interrupt {\n id: string;\n reason: string;\n message?: string | undefined;\n toolCallId?: string | undefined;\n responseSchema?: any | undefined;\n expiresAt?: string | undefined;\n metadata?: any | undefined;\n}\n\nfunction createBaseToolCall(): ToolCall {\n return { id: \"\", type: \"\", function: undefined };\n}\n\nexport const ToolCall: MessageFns<ToolCall> = {\n encode(message: ToolCall, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n if (message.id !== \"\") {\n writer.uint32(10).string(message.id);\n }\n if (message.type !== \"\") {\n writer.uint32(18).string(message.type);\n }\n if (message.function !== undefined) {\n ToolCall_Function.encode(message.function, writer.uint32(26).fork()).join();\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): ToolCall {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseToolCall();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 10) {\n break;\n }\n\n message.id = reader.string();\n continue;\n }\n case 2: {\n if (tag !== 18) {\n break;\n }\n\n message.type = reader.string();\n continue;\n }\n case 3: {\n if (tag !== 26) {\n break;\n }\n\n message.function = ToolCall_Function.decode(reader, reader.uint32());\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<ToolCall>, I>>(base?: I): ToolCall {\n return ToolCall.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<ToolCall>, I>>(object: I): ToolCall {\n const message = createBaseToolCall();\n message.id = object.id ?? \"\";\n message.type = object.type ?? \"\";\n message.function = (object.function !== undefined && object.function !== null)\n ? ToolCall_Function.fromPartial(object.function)\n : undefined;\n return message;\n },\n};\n\nfunction createBaseToolCall_Function(): ToolCall_Function {\n return { name: \"\", arguments: \"\" };\n}\n\nexport const ToolCall_Function: MessageFns<ToolCall_Function> = {\n encode(message: ToolCall_Function, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n if (message.name !== \"\") {\n writer.uint32(10).string(message.name);\n }\n if (message.arguments !== \"\") {\n writer.uint32(18).string(message.arguments);\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): ToolCall_Function {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseToolCall_Function();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 10) {\n break;\n }\n\n message.name = reader.string();\n continue;\n }\n case 2: {\n if (tag !== 18) {\n break;\n }\n\n message.arguments = reader.string();\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<ToolCall_Function>, I>>(base?: I): ToolCall_Function {\n return ToolCall_Function.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<ToolCall_Function>, I>>(object: I): ToolCall_Function {\n const message = createBaseToolCall_Function();\n message.name = object.name ?? \"\";\n message.arguments = object.arguments ?? \"\";\n return message;\n },\n};\n\nfunction createBaseInputContentDataSource(): InputContentDataSource {\n return { value: \"\", mimeType: \"\" };\n}\n\nexport const InputContentDataSource: MessageFns<InputContentDataSource> = {\n encode(message: InputContentDataSource, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n if (message.value !== \"\") {\n writer.uint32(10).string(message.value);\n }\n if (message.mimeType !== \"\") {\n writer.uint32(18).string(message.mimeType);\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): InputContentDataSource {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseInputContentDataSource();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 10) {\n break;\n }\n\n message.value = reader.string();\n continue;\n }\n case 2: {\n if (tag !== 18) {\n break;\n }\n\n message.mimeType = reader.string();\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<InputContentDataSource>, I>>(base?: I): InputContentDataSource {\n return InputContentDataSource.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<InputContentDataSource>, I>>(object: I): InputContentDataSource {\n const message = createBaseInputContentDataSource();\n message.value = object.value ?? \"\";\n message.mimeType = object.mimeType ?? \"\";\n return message;\n },\n};\n\nfunction createBaseInputContentUrlSource(): InputContentUrlSource {\n return { value: \"\", mimeType: undefined };\n}\n\nexport const InputContentUrlSource: MessageFns<InputContentUrlSource> = {\n encode(message: InputContentUrlSource, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n if (message.value !== \"\") {\n writer.uint32(10).string(message.value);\n }\n if (message.mimeType !== undefined) {\n writer.uint32(18).string(message.mimeType);\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): InputContentUrlSource {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseInputContentUrlSource();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 10) {\n break;\n }\n\n message.value = reader.string();\n continue;\n }\n case 2: {\n if (tag !== 18) {\n break;\n }\n\n message.mimeType = reader.string();\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<InputContentUrlSource>, I>>(base?: I): InputContentUrlSource {\n return InputContentUrlSource.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<InputContentUrlSource>, I>>(object: I): InputContentUrlSource {\n const message = createBaseInputContentUrlSource();\n message.value = object.value ?? \"\";\n message.mimeType = object.mimeType ?? undefined;\n return message;\n },\n};\n\nfunction createBaseInputContentSource(): InputContentSource {\n return { data: undefined, url: undefined };\n}\n\nexport const InputContentSource: MessageFns<InputContentSource> = {\n encode(message: InputContentSource, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n if (message.data !== undefined) {\n InputContentDataSource.encode(message.data, writer.uint32(10).fork()).join();\n }\n if (message.url !== undefined) {\n InputContentUrlSource.encode(message.url, writer.uint32(18).fork()).join();\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): InputContentSource {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseInputContentSource();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 10) {\n break;\n }\n\n message.data = InputContentDataSource.decode(reader, reader.uint32());\n continue;\n }\n case 2: {\n if (tag !== 18) {\n break;\n }\n\n message.url = InputContentUrlSource.decode(reader, reader.uint32());\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<InputContentSource>, I>>(base?: I): InputContentSource {\n return InputContentSource.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<InputContentSource>, I>>(object: I): InputContentSource {\n const message = createBaseInputContentSource();\n message.data = (object.data !== undefined && object.data !== null)\n ? InputContentDataSource.fromPartial(object.data)\n : undefined;\n message.url = (object.url !== undefined && object.url !== null)\n ? InputContentUrlSource.fromPartial(object.url)\n : undefined;\n return message;\n },\n};\n\nfunction createBaseTextInputPart(): TextInputPart {\n return { text: \"\" };\n}\n\nexport const TextInputPart: MessageFns<TextInputPart> = {\n encode(message: TextInputPart, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n if (message.text !== \"\") {\n writer.uint32(10).string(message.text);\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): TextInputPart {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseTextInputPart();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 10) {\n break;\n }\n\n message.text = reader.string();\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<TextInputPart>, I>>(base?: I): TextInputPart {\n return TextInputPart.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<TextInputPart>, I>>(object: I): TextInputPart {\n const message = createBaseTextInputPart();\n message.text = object.text ?? \"\";\n return message;\n },\n};\n\nfunction createBaseImageInputPart(): ImageInputPart {\n return { source: undefined, metadata: undefined };\n}\n\nexport const ImageInputPart: MessageFns<ImageInputPart> = {\n encode(message: ImageInputPart, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n if (message.source !== undefined) {\n InputContentSource.encode(message.source, writer.uint32(10).fork()).join();\n }\n if (message.metadata !== undefined) {\n Value.encode(Value.wrap(message.metadata), writer.uint32(18).fork()).join();\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): ImageInputPart {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseImageInputPart();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 10) {\n break;\n }\n\n message.source = InputContentSource.decode(reader, reader.uint32());\n continue;\n }\n case 2: {\n if (tag !== 18) {\n break;\n }\n\n message.metadata = Value.unwrap(Value.decode(reader, reader.uint32()));\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<ImageInputPart>, I>>(base?: I): ImageInputPart {\n return ImageInputPart.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<ImageInputPart>, I>>(object: I): ImageInputPart {\n const message = createBaseImageInputPart();\n message.source = (object.source !== undefined && object.source !== null)\n ? InputContentSource.fromPartial(object.source)\n : undefined;\n message.metadata = object.metadata ?? undefined;\n return message;\n },\n};\n\nfunction createBaseAudioInputPart(): AudioInputPart {\n return { source: undefined, metadata: undefined };\n}\n\nexport const AudioInputPart: MessageFns<AudioInputPart> = {\n encode(message: AudioInputPart, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n if (message.source !== undefined) {\n InputContentSource.encode(message.source, writer.uint32(10).fork()).join();\n }\n if (message.metadata !== undefined) {\n Value.encode(Value.wrap(message.metadata), writer.uint32(18).fork()).join();\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): AudioInputPart {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseAudioInputPart();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 10) {\n break;\n }\n\n message.source = InputContentSource.decode(reader, reader.uint32());\n continue;\n }\n case 2: {\n if (tag !== 18) {\n break;\n }\n\n message.metadata = Value.unwrap(Value.decode(reader, reader.uint32()));\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<AudioInputPart>, I>>(base?: I): AudioInputPart {\n return AudioInputPart.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<AudioInputPart>, I>>(object: I): AudioInputPart {\n const message = createBaseAudioInputPart();\n message.source = (object.source !== undefined && object.source !== null)\n ? InputContentSource.fromPartial(object.source)\n : undefined;\n message.metadata = object.metadata ?? undefined;\n return message;\n },\n};\n\nfunction createBaseVideoInputPart(): VideoInputPart {\n return { source: undefined, metadata: undefined };\n}\n\nexport const VideoInputPart: MessageFns<VideoInputPart> = {\n encode(message: VideoInputPart, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n if (message.source !== undefined) {\n InputContentSource.encode(message.source, writer.uint32(10).fork()).join();\n }\n if (message.metadata !== undefined) {\n Value.encode(Value.wrap(message.metadata), writer.uint32(18).fork()).join();\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): VideoInputPart {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseVideoInputPart();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 10) {\n break;\n }\n\n message.source = InputContentSource.decode(reader, reader.uint32());\n continue;\n }\n case 2: {\n if (tag !== 18) {\n break;\n }\n\n message.metadata = Value.unwrap(Value.decode(reader, reader.uint32()));\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<VideoInputPart>, I>>(base?: I): VideoInputPart {\n return VideoInputPart.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<VideoInputPart>, I>>(object: I): VideoInputPart {\n const message = createBaseVideoInputPart();\n message.source = (object.source !== undefined && object.source !== null)\n ? InputContentSource.fromPartial(object.source)\n : undefined;\n message.metadata = object.metadata ?? undefined;\n return message;\n },\n};\n\nfunction createBaseDocumentInputPart(): DocumentInputPart {\n return { source: undefined, metadata: undefined };\n}\n\nexport const DocumentInputPart: MessageFns<DocumentInputPart> = {\n encode(message: DocumentInputPart, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n if (message.source !== undefined) {\n InputContentSource.encode(message.source, writer.uint32(10).fork()).join();\n }\n if (message.metadata !== undefined) {\n Value.encode(Value.wrap(message.metadata), writer.uint32(18).fork()).join();\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): DocumentInputPart {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseDocumentInputPart();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 10) {\n break;\n }\n\n message.source = InputContentSource.decode(reader, reader.uint32());\n continue;\n }\n case 2: {\n if (tag !== 18) {\n break;\n }\n\n message.metadata = Value.unwrap(Value.decode(reader, reader.uint32()));\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<DocumentInputPart>, I>>(base?: I): DocumentInputPart {\n return DocumentInputPart.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<DocumentInputPart>, I>>(object: I): DocumentInputPart {\n const message = createBaseDocumentInputPart();\n message.source = (object.source !== undefined && object.source !== null)\n ? InputContentSource.fromPartial(object.source)\n : undefined;\n message.metadata = object.metadata ?? undefined;\n return message;\n },\n};\n\nfunction createBaseInputContent(): InputContent {\n return { text: undefined, image: undefined, audio: undefined, video: undefined, document: undefined };\n}\n\nexport const InputContent: MessageFns<InputContent> = {\n encode(message: InputContent, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n if (message.text !== undefined) {\n TextInputPart.encode(message.text, writer.uint32(10).fork()).join();\n }\n if (message.image !== undefined) {\n ImageInputPart.encode(message.image, writer.uint32(18).fork()).join();\n }\n if (message.audio !== undefined) {\n AudioInputPart.encode(message.audio, writer.uint32(26).fork()).join();\n }\n if (message.video !== undefined) {\n VideoInputPart.encode(message.video, writer.uint32(34).fork()).join();\n }\n if (message.document !== undefined) {\n DocumentInputPart.encode(message.document, writer.uint32(42).fork()).join();\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): InputContent {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseInputContent();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 10) {\n break;\n }\n\n message.text = TextInputPart.decode(reader, reader.uint32());\n continue;\n }\n case 2: {\n if (tag !== 18) {\n break;\n }\n\n message.image = ImageInputPart.decode(reader, reader.uint32());\n continue;\n }\n case 3: {\n if (tag !== 26) {\n break;\n }\n\n message.audio = AudioInputPart.decode(reader, reader.uint32());\n continue;\n }\n case 4: {\n if (tag !== 34) {\n break;\n }\n\n message.video = VideoInputPart.decode(reader, reader.uint32());\n continue;\n }\n case 5: {\n if (tag !== 42) {\n break;\n }\n\n message.document = DocumentInputPart.decode(reader, reader.uint32());\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<InputContent>, I>>(base?: I): InputContent {\n return InputContent.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<InputContent>, I>>(object: I): InputContent {\n const message = createBaseInputContent();\n message.text = (object.text !== undefined && object.text !== null)\n ? TextInputPart.fromPartial(object.text)\n : undefined;\n message.image = (object.image !== undefined && object.image !== null)\n ? ImageInputPart.fromPartial(object.image)\n : undefined;\n message.audio = (object.audio !== undefined && object.audio !== null)\n ? AudioInputPart.fromPartial(object.audio)\n : undefined;\n message.video = (object.video !== undefined && object.video !== null)\n ? VideoInputPart.fromPartial(object.video)\n : undefined;\n message.document = (object.document !== undefined && object.document !== null)\n ? DocumentInputPart.fromPartial(object.document)\n : undefined;\n return message;\n },\n};\n\nfunction createBaseMessage(): Message {\n return {\n id: \"\",\n role: \"\",\n content: undefined,\n name: undefined,\n toolCalls: [],\n toolCallId: undefined,\n error: undefined,\n contentParts: [],\n };\n}\n\nexport const Message: MessageFns<Message> = {\n encode(message: Message, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n if (message.id !== \"\") {\n writer.uint32(10).string(message.id);\n }\n if (message.role !== \"\") {\n writer.uint32(18).string(message.role);\n }\n if (message.content !== undefined) {\n writer.uint32(26).string(message.content);\n }\n if (message.name !== undefined) {\n writer.uint32(34).string(message.name);\n }\n for (const v of message.toolCalls) {\n ToolCall.encode(v!, writer.uint32(42).fork()).join();\n }\n if (message.toolCallId !== undefined) {\n writer.uint32(50).string(message.toolCallId);\n }\n if (message.error !== undefined) {\n writer.uint32(58).string(message.error);\n }\n for (const v of message.contentParts) {\n InputContent.encode(v!, writer.uint32(66).fork()).join();\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): Message {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseMessage();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 10) {\n break;\n }\n\n message.id = reader.string();\n continue;\n }\n case 2: {\n if (tag !== 18) {\n break;\n }\n\n message.role = reader.string();\n continue;\n }\n case 3: {\n if (tag !== 26) {\n break;\n }\n\n message.content = reader.string();\n continue;\n }\n case 4: {\n if (tag !== 34) {\n break;\n }\n\n message.name = reader.string();\n continue;\n }\n case 5: {\n if (tag !== 42) {\n break;\n }\n\n message.toolCalls.push(ToolCall.decode(reader, reader.uint32()));\n continue;\n }\n case 6: {\n if (tag !== 50) {\n break;\n }\n\n message.toolCallId = reader.string();\n continue;\n }\n case 7: {\n if (tag !== 58) {\n break;\n }\n\n message.error = reader.string();\n continue;\n }\n case 8: {\n if (tag !== 66) {\n break;\n }\n\n message.contentParts.push(InputContent.decode(reader, reader.uint32()));\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<Message>, I>>(base?: I): Message {\n return Message.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<Message>, I>>(object: I): Message {\n const message = createBaseMessage();\n message.id = object.id ?? \"\";\n message.role = object.role ?? \"\";\n message.content = object.content ?? undefined;\n message.name = object.name ?? undefined;\n message.toolCalls = object.toolCalls?.map((e) => ToolCall.fromPartial(e)) || [];\n message.toolCallId = object.toolCallId ?? undefined;\n message.error = object.error ?? undefined;\n message.contentParts = object.contentParts?.map((e) => InputContent.fromPartial(e)) || [];\n return message;\n },\n};\n\nfunction createBaseInterrupt(): Interrupt {\n return {\n id: \"\",\n reason: \"\",\n message: undefined,\n toolCallId: undefined,\n responseSchema: undefined,\n expiresAt: undefined,\n metadata: undefined,\n };\n}\n\nexport const Interrupt: MessageFns<Interrupt> = {\n encode(message: Interrupt, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n if (message.id !== \"\") {\n writer.uint32(10).string(message.id);\n }\n if (message.reason !== \"\") {\n writer.uint32(18).string(message.reason);\n }\n if (message.message !== undefined) {\n writer.uint32(26).string(message.message);\n }\n if (message.toolCallId !== undefined) {\n writer.uint32(34).string(message.toolCallId);\n }\n if (message.responseSchema !== undefined) {\n Value.encode(Value.wrap(message.responseSchema), writer.uint32(42).fork()).join();\n }\n if (message.expiresAt !== undefined) {\n writer.uint32(50).string(message.expiresAt);\n }\n if (message.metadata !== undefined) {\n Value.encode(Value.wrap(message.metadata), writer.uint32(58).fork()).join();\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): Interrupt {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseInterrupt();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 10) {\n break;\n }\n\n message.id = reader.string();\n continue;\n }\n case 2: {\n if (tag !== 18) {\n break;\n }\n\n message.reason = reader.string();\n continue;\n }\n case 3: {\n if (tag !== 26) {\n break;\n }\n\n message.message = reader.string();\n continue;\n }\n case 4: {\n if (tag !== 34) {\n break;\n }\n\n message.toolCallId = reader.string();\n continue;\n }\n case 5: {\n if (tag !== 42) {\n break;\n }\n\n message.responseSchema = Value.unwrap(Value.decode(reader, reader.uint32()));\n continue;\n }\n case 6: {\n if (tag !== 50) {\n break;\n }\n\n message.expiresAt = reader.string();\n continue;\n }\n case 7: {\n if (tag !== 58) {\n break;\n }\n\n message.metadata = Value.unwrap(Value.decode(reader, reader.uint32()));\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<Interrupt>, I>>(base?: I): Interrupt {\n return Interrupt.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<Interrupt>, I>>(object: I): Interrupt {\n const message = createBaseInterrupt();\n message.id = object.id ?? \"\";\n message.reason = object.reason ?? \"\";\n message.message = object.message ?? undefined;\n message.toolCallId = object.toolCallId ?? undefined;\n message.responseSchema = object.responseSchema ?? undefined;\n message.expiresAt = object.expiresAt ?? undefined;\n message.metadata = object.metadata ?? undefined;\n return message;\n },\n};\n\ntype Builtin = Date | Function | Uint8Array | string | number | boolean | undefined;\n\nexport type DeepPartial<T> = T extends Builtin ? T\n : T extends globalThis.Array<infer U> ? globalThis.Array<DeepPartial<U>>\n : T extends ReadonlyArray<infer U> ? ReadonlyArray<DeepPartial<U>>\n : T extends {} ? { [K in keyof T]?: DeepPartial<T[K]> }\n : Partial<T>;\n\ntype KeysOfUnion<T> = T extends T ? keyof T : never;\nexport type Exact<P, I extends P> = P extends Builtin ? P\n : P & { [K in keyof P]: Exact<P[K], I[K]> } & { [K in Exclude<keyof I, KeysOfUnion<P>>]: never };\n\nexport interface MessageFns<T> {\n encode(message: T, writer?: BinaryWriter): BinaryWriter;\n decode(input: BinaryReader | Uint8Array, length?: number): T;\n create<I extends Exact<DeepPartial<T>, I>>(base?: I): T;\n fromPartial<I extends Exact<DeepPartial<T>, I>>(object: I): T;\n}\n", "// Code generated by protoc-gen-ts_proto. DO NOT EDIT.\n// versions:\n// protoc-gen-ts_proto v2.7.7\n// protoc v4.25.9\n// source: events.proto\n\n/* eslint-disable */\nimport { BinaryReader, BinaryWriter } from \"@bufbuild/protobuf/wire\";\nimport { Value } from \"./google/protobuf/struct\";\nimport { JsonPatchOperation } from \"./patch\";\nimport { Interrupt, Message } from \"./types\";\n\nexport const protobufPackage = \"ag_ui\";\n\nexport enum EventType {\n TEXT_MESSAGE_START = 0,\n TEXT_MESSAGE_CONTENT = 1,\n TEXT_MESSAGE_END = 2,\n TOOL_CALL_START = 3,\n TOOL_CALL_ARGS = 4,\n TOOL_CALL_END = 5,\n STATE_SNAPSHOT = 6,\n STATE_DELTA = 7,\n MESSAGES_SNAPSHOT = 8,\n RAW = 9,\n CUSTOM = 10,\n RUN_STARTED = 11,\n RUN_FINISHED = 12,\n RUN_ERROR = 13,\n STEP_STARTED = 14,\n STEP_FINISHED = 15,\n UNRECOGNIZED = -1,\n}\n\nexport interface BaseEvent {\n type: EventType;\n timestamp?: number | undefined;\n rawEvent?: any | undefined;\n}\n\nexport interface TextMessageStartEvent {\n baseEvent: BaseEvent | undefined;\n messageId: string;\n role?: string | undefined;\n name?: string | undefined;\n}\n\nexport interface TextMessageContentEvent {\n baseEvent: BaseEvent | undefined;\n messageId: string;\n delta: string;\n}\n\nexport interface TextMessageEndEvent {\n baseEvent: BaseEvent | undefined;\n messageId: string;\n}\n\nexport interface ToolCallStartEvent {\n baseEvent: BaseEvent | undefined;\n toolCallId: string;\n toolCallName: string;\n parentMessageId?: string | undefined;\n}\n\nexport interface ToolCallArgsEvent {\n baseEvent: BaseEvent | undefined;\n toolCallId: string;\n delta: string;\n}\n\nexport interface ToolCallEndEvent {\n baseEvent: BaseEvent | undefined;\n toolCallId: string;\n}\n\nexport interface StateSnapshotEvent {\n baseEvent: BaseEvent | undefined;\n snapshot: any | undefined;\n}\n\nexport interface StateDeltaEvent {\n baseEvent: BaseEvent | undefined;\n delta: JsonPatchOperation[];\n}\n\nexport interface MessagesSnapshotEvent {\n baseEvent: BaseEvent | undefined;\n messages: Message[];\n}\n\nexport interface RawEvent {\n baseEvent: BaseEvent | undefined;\n event: any | undefined;\n source?: string | undefined;\n}\n\nexport interface CustomEvent {\n baseEvent: BaseEvent | undefined;\n name: string;\n value?: any | undefined;\n}\n\nexport interface RunStartedEvent {\n baseEvent: BaseEvent | undefined;\n threadId: string;\n runId: string;\n}\n\nexport interface RunFinishedEvent {\n baseEvent: BaseEvent | undefined;\n threadId: string;\n runId: string;\n result?: any | undefined;\n outcome: string;\n interrupts: Interrupt[];\n}\n\nexport interface RunErrorEvent {\n baseEvent: BaseEvent | undefined;\n code?: string | undefined;\n message: string;\n}\n\nexport interface StepStartedEvent {\n baseEvent: BaseEvent | undefined;\n stepName: string;\n}\n\nexport interface StepFinishedEvent {\n baseEvent: BaseEvent | undefined;\n stepName: string;\n}\n\nexport interface TextMessageChunkEvent {\n baseEvent: BaseEvent | undefined;\n messageId?: string | undefined;\n role?: string | undefined;\n delta?: string | undefined;\n name?: string | undefined;\n}\n\nexport interface ToolCallChunkEvent {\n baseEvent: BaseEvent | undefined;\n toolCallId?: string | undefined;\n toolCallName?: string | undefined;\n parentMessageId?: string | undefined;\n delta?: string | undefined;\n}\n\nexport interface Event {\n textMessageStart?: TextMessageStartEvent | undefined;\n textMessageContent?: TextMessageContentEvent | undefined;\n textMessageEnd?: TextMessageEndEvent | undefined;\n toolCallStart?: ToolCallStartEvent | undefined;\n toolCallArgs?: ToolCallArgsEvent | undefined;\n toolCallEnd?: ToolCallEndEvent | undefined;\n stateSnapshot?: StateSnapshotEvent | undefined;\n stateDelta?: StateDeltaEvent | undefined;\n messagesSnapshot?: MessagesSnapshotEvent | undefined;\n raw?: RawEvent | undefined;\n custom?: CustomEvent | undefined;\n runStarted?: RunStartedEvent | undefined;\n runFinished?: RunFinishedEvent | undefined;\n runError?: RunErrorEvent | undefined;\n stepStarted?: StepStartedEvent | undefined;\n stepFinished?: StepFinishedEvent | undefined;\n textMessageChunk?: TextMessageChunkEvent | undefined;\n toolCallChunk?: ToolCallChunkEvent | undefined;\n}\n\nfunction createBaseBaseEvent(): BaseEvent {\n return { type: 0, timestamp: undefined, rawEvent: undefined };\n}\n\nexport const BaseEvent: MessageFns<BaseEvent> = {\n encode(message: BaseEvent, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n if (message.type !== 0) {\n writer.uint32(8).int32(message.type);\n }\n if (message.timestamp !== undefined) {\n writer.uint32(16).int64(message.timestamp);\n }\n if (message.rawEvent !== undefined) {\n Value.encode(Value.wrap(message.rawEvent), writer.uint32(26).fork()).join();\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): BaseEvent {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseBaseEvent();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 8) {\n break;\n }\n\n message.type = reader.int32() as any;\n continue;\n }\n case 2: {\n if (tag !== 16) {\n break;\n }\n\n message.timestamp = longToNumber(reader.int64());\n continue;\n }\n case 3: {\n if (tag !== 26) {\n break;\n }\n\n message.rawEvent = Value.unwrap(Value.decode(reader, reader.uint32()));\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<BaseEvent>, I>>(base?: I): BaseEvent {\n return BaseEvent.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<BaseEvent>, I>>(object: I): BaseEvent {\n const message = createBaseBaseEvent();\n message.type = object.type ?? 0;\n message.timestamp = object.timestamp ?? undefined;\n message.rawEvent = object.rawEvent ?? undefined;\n return message;\n },\n};\n\nfunction createBaseTextMessageStartEvent(): TextMessageStartEvent {\n return { baseEvent: undefined, messageId: \"\", role: undefined, name: undefined };\n}\n\nexport const TextMessageStartEvent: MessageFns<TextMessageStartEvent> = {\n encode(message: TextMessageStartEvent, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n if (message.baseEvent !== undefined) {\n BaseEvent.encode(message.baseEvent, writer.uint32(10).fork()).join();\n }\n if (message.messageId !== \"\") {\n writer.uint32(18).string(message.messageId);\n }\n if (message.role !== undefined) {\n writer.uint32(26).string(message.role);\n }\n if (message.name !== undefined) {\n writer.uint32(34).string(message.name);\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): TextMessageStartEvent {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseTextMessageStartEvent();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 10) {\n break;\n }\n\n message.baseEvent = BaseEvent.decode(reader, reader.uint32());\n continue;\n }\n case 2: {\n if (tag !== 18) {\n break;\n }\n\n message.messageId = reader.string();\n continue;\n }\n case 3: {\n if (tag !== 26) {\n break;\n }\n\n message.role = reader.string();\n continue;\n }\n case 4: {\n if (tag !== 34) {\n break;\n }\n\n message.name = reader.string();\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<TextMessageStartEvent>, I>>(base?: I): TextMessageStartEvent {\n return TextMessageStartEvent.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<TextMessageStartEvent>, I>>(object: I): TextMessageStartEvent {\n const message = createBaseTextMessageStartEvent();\n message.baseEvent = (object.baseEvent !== undefined && object.baseEvent !== null)\n ? BaseEvent.fromPartial(object.baseEvent)\n : undefined;\n message.messageId = object.messageId ?? \"\";\n message.role = object.role ?? undefined;\n message.name = object.name ?? undefined;\n return message;\n },\n};\n\nfunction createBaseTextMessageContentEvent(): TextMessageContentEvent {\n return { baseEvent: undefined, messageId: \"\", delta: \"\" };\n}\n\nexport const TextMessageContentEvent: MessageFns<TextMessageContentEvent> = {\n encode(message: TextMessageContentEvent, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n if (message.baseEvent !== undefined) {\n BaseEvent.encode(message.baseEvent, writer.uint32(10).fork()).join();\n }\n if (message.messageId !== \"\") {\n writer.uint32(18).string(message.messageId);\n }\n if (message.delta !== \"\") {\n writer.uint32(26).string(message.delta);\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): TextMessageContentEvent {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseTextMessageContentEvent();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 10) {\n break;\n }\n\n message.baseEvent = BaseEvent.decode(reader, reader.uint32());\n continue;\n }\n case 2: {\n if (tag !== 18) {\n break;\n }\n\n message.messageId = reader.string();\n continue;\n }\n case 3: {\n if (tag !== 26) {\n break;\n }\n\n message.delta = reader.string();\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<TextMessageContentEvent>, I>>(base?: I): TextMessageContentEvent {\n return TextMessageContentEvent.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<TextMessageContentEvent>, I>>(object: I): TextMessageContentEvent {\n const message = createBaseTextMessageContentEvent();\n message.baseEvent = (object.baseEvent !== undefined && object.baseEvent !== null)\n ? BaseEvent.fromPartial(object.baseEvent)\n : undefined;\n message.messageId = object.messageId ?? \"\";\n message.delta = object.delta ?? \"\";\n return message;\n },\n};\n\nfunction createBaseTextMessageEndEvent(): TextMessageEndEvent {\n return { baseEvent: undefined, messageId: \"\" };\n}\n\nexport const TextMessageEndEvent: MessageFns<TextMessageEndEvent> = {\n encode(message: TextMessageEndEvent, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n if (message.baseEvent !== undefined) {\n BaseEvent.encode(message.baseEvent, writer.uint32(10).fork()).join();\n }\n if (message.messageId !== \"\") {\n writer.uint32(18).string(message.messageId);\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): TextMessageEndEvent {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseTextMessageEndEvent();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 10) {\n break;\n }\n\n message.baseEvent = BaseEvent.decode(reader, reader.uint32());\n continue;\n }\n case 2: {\n if (tag !== 18) {\n break;\n }\n\n message.messageId = reader.string();\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<TextMessageEndEvent>, I>>(base?: I): TextMessageEndEvent {\n return TextMessageEndEvent.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<TextMessageEndEvent>, I>>(object: I): TextMessageEndEvent {\n const message = createBaseTextMessageEndEvent();\n message.baseEvent = (object.baseEvent !== undefined && object.baseEvent !== null)\n ? BaseEvent.fromPartial(object.baseEvent)\n : undefined;\n message.messageId = object.messageId ?? \"\";\n return message;\n },\n};\n\nfunction createBaseToolCallStartEvent(): ToolCallStartEvent {\n return { baseEvent: undefined, toolCallId: \"\", toolCallName: \"\", parentMessageId: undefined };\n}\n\nexport const ToolCallStartEvent: MessageFns<ToolCallStartEvent> = {\n encode(message: ToolCallStartEvent, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n if (message.baseEvent !== undefined) {\n BaseEvent.encode(message.baseEvent, writer.uint32(10).fork()).join();\n }\n if (message.toolCallId !== \"\") {\n writer.uint32(18).string(message.toolCallId);\n }\n if (message.toolCallName !== \"\") {\n writer.uint32(26).string(message.toolCallName);\n }\n if (message.parentMessageId !== undefined) {\n writer.uint32(34).string(message.parentMessageId);\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): ToolCallStartEvent {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseToolCallStartEvent();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 10) {\n break;\n }\n\n message.baseEvent = BaseEvent.decode(reader, reader.uint32());\n continue;\n }\n case 2: {\n if (tag !== 18) {\n break;\n }\n\n message.toolCallId = reader.string();\n continue;\n }\n case 3: {\n if (tag !== 26) {\n break;\n }\n\n message.toolCallName = reader.string();\n continue;\n }\n case 4: {\n if (tag !== 34) {\n break;\n }\n\n message.parentMessageId = reader.string();\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<ToolCallStartEvent>, I>>(base?: I): ToolCallStartEvent {\n return ToolCallStartEvent.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<ToolCallStartEvent>, I>>(object: I): ToolCallStartEvent {\n const message = createBaseToolCallStartEvent();\n message.baseEvent = (object.baseEvent !== undefined && object.baseEvent !== null)\n ? BaseEvent.fromPartial(object.baseEvent)\n : undefined;\n message.toolCallId = object.toolCallId ?? \"\";\n message.toolCallName = object.toolCallName ?? \"\";\n message.parentMessageId = object.parentMessageId ?? undefined;\n return message;\n },\n};\n\nfunction createBaseToolCallArgsEvent(): ToolCallArgsEvent {\n return { baseEvent: undefined, toolCallId: \"\", delta: \"\" };\n}\n\nexport const ToolCallArgsEvent: MessageFns<ToolCallArgsEvent> = {\n encode(message: ToolCallArgsEvent, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n if (message.baseEvent !== undefined) {\n BaseEvent.encode(message.baseEvent, writer.uint32(10).fork()).join();\n }\n if (message.toolCallId !== \"\") {\n writer.uint32(18).string(message.toolCallId);\n }\n if (message.delta !== \"\") {\n writer.uint32(26).string(message.delta);\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): ToolCallArgsEvent {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseToolCallArgsEvent();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 10) {\n break;\n }\n\n message.baseEvent = BaseEvent.decode(reader, reader.uint32());\n continue;\n }\n case 2: {\n if (tag !== 18) {\n break;\n }\n\n message.toolCallId = reader.string();\n continue;\n }\n case 3: {\n if (tag !== 26) {\n break;\n }\n\n message.delta = reader.string();\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<ToolCallArgsEvent>, I>>(base?: I): ToolCallArgsEvent {\n return ToolCallArgsEvent.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<ToolCallArgsEvent>, I>>(object: I): ToolCallArgsEvent {\n const message = createBaseToolCallArgsEvent();\n message.baseEvent = (object.baseEvent !== undefined && object.baseEvent !== null)\n ? BaseEvent.fromPartial(object.baseEvent)\n : undefined;\n message.toolCallId = object.toolCallId ?? \"\";\n message.delta = object.delta ?? \"\";\n return message;\n },\n};\n\nfunction createBaseToolCallEndEvent(): ToolCallEndEvent {\n return { baseEvent: undefined, toolCallId: \"\" };\n}\n\nexport const ToolCallEndEvent: MessageFns<ToolCallEndEvent> = {\n encode(message: ToolCallEndEvent, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n if (message.baseEvent !== undefined) {\n BaseEvent.encode(message.baseEvent, writer.uint32(10).fork()).join();\n }\n if (message.toolCallId !== \"\") {\n writer.uint32(18).string(message.toolCallId);\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): ToolCallEndEvent {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseToolCallEndEvent();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 10) {\n break;\n }\n\n message.baseEvent = BaseEvent.decode(reader, reader.uint32());\n continue;\n }\n case 2: {\n if (tag !== 18) {\n break;\n }\n\n message.toolCallId = reader.string();\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<ToolCallEndEvent>, I>>(base?: I): ToolCallEndEvent {\n return ToolCallEndEvent.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<ToolCallEndEvent>, I>>(object: I): ToolCallEndEvent {\n const message = createBaseToolCallEndEvent();\n message.baseEvent = (object.baseEvent !== undefined && object.baseEvent !== null)\n ? BaseEvent.fromPartial(object.baseEvent)\n : undefined;\n message.toolCallId = object.toolCallId ?? \"\";\n return message;\n },\n};\n\nfunction createBaseStateSnapshotEvent(): StateSnapshotEvent {\n return { baseEvent: undefined, snapshot: undefined };\n}\n\nexport const StateSnapshotEvent: MessageFns<StateSnapshotEvent> = {\n encode(message: StateSnapshotEvent, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n if (message.baseEvent !== undefined) {\n BaseEvent.encode(message.baseEvent, writer.uint32(10).fork()).join();\n }\n if (message.snapshot !== undefined) {\n Value.encode(Value.wrap(message.snapshot), writer.uint32(18).fork()).join();\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): StateSnapshotEvent {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseStateSnapshotEvent();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 10) {\n break;\n }\n\n message.baseEvent = BaseEvent.decode(reader, reader.uint32());\n continue;\n }\n case 2: {\n if (tag !== 18) {\n break;\n }\n\n message.snapshot = Value.unwrap(Value.decode(reader, reader.uint32()));\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<StateSnapshotEvent>, I>>(base?: I): StateSnapshotEvent {\n return StateSnapshotEvent.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<StateSnapshotEvent>, I>>(object: I): StateSnapshotEvent {\n const message = createBaseStateSnapshotEvent();\n message.baseEvent = (object.baseEvent !== undefined && object.baseEvent !== null)\n ? BaseEvent.fromPartial(object.baseEvent)\n : undefined;\n message.snapshot = object.snapshot ?? undefined;\n return message;\n },\n};\n\nfunction createBaseStateDeltaEvent(): StateDeltaEvent {\n return { baseEvent: undefined, delta: [] };\n}\n\nexport const StateDeltaEvent: MessageFns<StateDeltaEvent> = {\n encode(message: StateDeltaEvent, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n if (message.baseEvent !== undefined) {\n BaseEvent.encode(message.baseEvent, writer.uint32(10).fork()).join();\n }\n for (const v of message.delta) {\n JsonPatchOperation.encode(v!, writer.uint32(18).fork()).join();\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): StateDeltaEvent {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseStateDeltaEvent();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 10) {\n break;\n }\n\n message.baseEvent = BaseEvent.decode(reader, reader.uint32());\n continue;\n }\n case 2: {\n if (tag !== 18) {\n break;\n }\n\n message.delta.push(JsonPatchOperation.decode(reader, reader.uint32()));\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<StateDeltaEvent>, I>>(base?: I): StateDeltaEvent {\n return StateDeltaEvent.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<StateDeltaEvent>, I>>(object: I): StateDeltaEvent {\n const message = createBaseStateDeltaEvent();\n message.baseEvent = (object.baseEvent !== undefined && object.baseEvent !== null)\n ? BaseEvent.fromPartial(object.baseEvent)\n : undefined;\n message.delta = object.delta?.map((e) => JsonPatchOperation.fromPartial(e)) || [];\n return message;\n },\n};\n\nfunction createBaseMessagesSnapshotEvent(): MessagesSnapshotEvent {\n return { baseEvent: undefined, messages: [] };\n}\n\nexport const MessagesSnapshotEvent: MessageFns<MessagesSnapshotEvent> = {\n encode(message: MessagesSnapshotEvent, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n if (message.baseEvent !== undefined) {\n BaseEvent.encode(message.baseEvent, writer.uint32(10).fork()).join();\n }\n for (const v of message.messages) {\n Message.encode(v!, writer.uint32(18).fork()).join();\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): MessagesSnapshotEvent {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseMessagesSnapshotEvent();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 10) {\n break;\n }\n\n message.baseEvent = BaseEvent.decode(reader, reader.uint32());\n continue;\n }\n case 2: {\n if (tag !== 18) {\n break;\n }\n\n message.messages.push(Message.decode(reader, reader.uint32()));\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<MessagesSnapshotEvent>, I>>(base?: I): MessagesSnapshotEvent {\n return MessagesSnapshotEvent.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<MessagesSnapshotEvent>, I>>(object: I): MessagesSnapshotEvent {\n const message = createBaseMessagesSnapshotEvent();\n message.baseEvent = (object.baseEvent !== undefined && object.baseEvent !== null)\n ? BaseEvent.fromPartial(object.baseEvent)\n : undefined;\n message.messages = object.messages?.map((e) => Message.fromPartial(e)) || [];\n return message;\n },\n};\n\nfunction createBaseRawEvent(): RawEvent {\n return { baseEvent: undefined, event: undefined, source: undefined };\n}\n\nexport const RawEvent: MessageFns<RawEvent> = {\n encode(message: RawEvent, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n if (message.baseEvent !== undefined) {\n BaseEvent.encode(message.baseEvent, writer.uint32(10).fork()).join();\n }\n if (message.event !== undefined) {\n Value.encode(Value.wrap(message.event), writer.uint32(18).fork()).join();\n }\n if (message.source !== undefined) {\n writer.uint32(26).string(message.source);\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): RawEvent {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseRawEvent();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 10) {\n break;\n }\n\n message.baseEvent = BaseEvent.decode(reader, reader.uint32());\n continue;\n }\n case 2: {\n if (tag !== 18) {\n break;\n }\n\n message.event = Value.unwrap(Value.decode(reader, reader.uint32()));\n continue;\n }\n case 3: {\n if (tag !== 26) {\n break;\n }\n\n message.source = reader.string();\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<RawEvent>, I>>(base?: I): RawEvent {\n return RawEvent.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<RawEvent>, I>>(object: I): RawEvent {\n const message = createBaseRawEvent();\n message.baseEvent = (object.baseEvent !== undefined && object.baseEvent !== null)\n ? BaseEvent.fromPartial(object.baseEvent)\n : undefined;\n message.event = object.event ?? undefined;\n message.source = object.source ?? undefined;\n return message;\n },\n};\n\nfunction createBaseCustomEvent(): CustomEvent {\n return { baseEvent: undefined, name: \"\", value: undefined };\n}\n\nexport const CustomEvent: MessageFns<CustomEvent> = {\n encode(message: CustomEvent, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n if (message.baseEvent !== undefined) {\n BaseEvent.encode(message.baseEvent, writer.uint32(10).fork()).join();\n }\n if (message.name !== \"\") {\n writer.uint32(18).string(message.name);\n }\n if (message.value !== undefined) {\n Value.encode(Value.wrap(message.value), writer.uint32(26).fork()).join();\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): CustomEvent {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseCustomEvent();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 10) {\n break;\n }\n\n message.baseEvent = BaseEvent.decode(reader, reader.uint32());\n continue;\n }\n case 2: {\n if (tag !== 18) {\n break;\n }\n\n message.name = reader.string();\n continue;\n }\n case 3: {\n if (tag !== 26) {\n break;\n }\n\n message.value = Value.unwrap(Value.decode(reader, reader.uint32()));\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<CustomEvent>, I>>(base?: I): CustomEvent {\n return CustomEvent.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<CustomEvent>, I>>(object: I): CustomEvent {\n const message = createBaseCustomEvent();\n message.baseEvent = (object.baseEvent !== undefined && object.baseEvent !== null)\n ? BaseEvent.fromPartial(object.baseEvent)\n : undefined;\n message.name = object.name ?? \"\";\n message.value = object.value ?? undefined;\n return message;\n },\n};\n\nfunction createBaseRunStartedEvent(): RunStartedEvent {\n return { baseEvent: undefined, threadId: \"\", runId: \"\" };\n}\n\nexport const RunStartedEvent: MessageFns<RunStartedEvent> = {\n encode(message: RunStartedEvent, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n if (message.baseEvent !== undefined) {\n BaseEvent.encode(message.baseEvent, writer.uint32(10).fork()).join();\n }\n if (message.threadId !== \"\") {\n writer.uint32(18).string(message.threadId);\n }\n if (message.runId !== \"\") {\n writer.uint32(26).string(message.runId);\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): RunStartedEvent {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseRunStartedEvent();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 10) {\n break;\n }\n\n message.baseEvent = BaseEvent.decode(reader, reader.uint32());\n continue;\n }\n case 2: {\n if (tag !== 18) {\n break;\n }\n\n message.threadId = reader.string();\n continue;\n }\n case 3: {\n if (tag !== 26) {\n break;\n }\n\n message.runId = reader.string();\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<RunStartedEvent>, I>>(base?: I): RunStartedEvent {\n return RunStartedEvent.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<RunStartedEvent>, I>>(object: I): RunStartedEvent {\n const message = createBaseRunStartedEvent();\n message.baseEvent = (object.baseEvent !== undefined && object.baseEvent !== null)\n ? BaseEvent.fromPartial(object.baseEvent)\n : undefined;\n message.threadId = object.threadId ?? \"\";\n message.runId = object.runId ?? \"\";\n return message;\n },\n};\n\nfunction createBaseRunFinishedEvent(): RunFinishedEvent {\n return { baseEvent: undefined, threadId: \"\", runId: \"\", result: undefined, outcome: \"\", interrupts: [] };\n}\n\nexport const RunFinishedEvent: MessageFns<RunFinishedEvent> = {\n encode(message: RunFinishedEvent, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n if (message.baseEvent !== undefined) {\n BaseEvent.encode(message.baseEvent, writer.uint32(10).fork()).join();\n }\n if (message.threadId !== \"\") {\n writer.uint32(18).string(message.threadId);\n }\n if (message.runId !== \"\") {\n writer.uint32(26).string(message.runId);\n }\n if (message.result !== undefined) {\n Value.encode(Value.wrap(message.result), writer.uint32(34).fork()).join();\n }\n if (message.outcome !== \"\") {\n writer.uint32(42).string(message.outcome);\n }\n for (const v of message.interrupts) {\n Interrupt.encode(v!, writer.uint32(50).fork()).join();\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): RunFinishedEvent {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseRunFinishedEvent();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 10) {\n break;\n }\n\n message.baseEvent = BaseEvent.decode(reader, reader.uint32());\n continue;\n }\n case 2: {\n if (tag !== 18) {\n break;\n }\n\n message.threadId = reader.string();\n continue;\n }\n case 3: {\n if (tag !== 26) {\n break;\n }\n\n message.runId = reader.string();\n continue;\n }\n case 4: {\n if (tag !== 34) {\n break;\n }\n\n message.result = Value.unwrap(Value.decode(reader, reader.uint32()));\n continue;\n }\n case 5: {\n if (tag !== 42) {\n break;\n }\n\n message.outcome = reader.string();\n continue;\n }\n case 6: {\n if (tag !== 50) {\n break;\n }\n\n message.interrupts.push(Interrupt.decode(reader, reader.uint32()));\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<RunFinishedEvent>, I>>(base?: I): RunFinishedEvent {\n return RunFinishedEvent.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<RunFinishedEvent>, I>>(object: I): RunFinishedEvent {\n const message = createBaseRunFinishedEvent();\n message.baseEvent = (object.baseEvent !== undefined && object.baseEvent !== null)\n ? BaseEvent.fromPartial(object.baseEvent)\n : undefined;\n message.threadId = object.threadId ?? \"\";\n message.runId = object.runId ?? \"\";\n message.result = object.result ?? undefined;\n message.outcome = object.outcome ?? \"\";\n message.interrupts = object.interrupts?.map((e) => Interrupt.fromPartial(e)) || [];\n return message;\n },\n};\n\nfunction createBaseRunErrorEvent(): RunErrorEvent {\n return { baseEvent: undefined, code: undefined, message: \"\" };\n}\n\nexport const RunErrorEvent: MessageFns<RunErrorEvent> = {\n encode(message: RunErrorEvent, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n if (message.baseEvent !== undefined) {\n BaseEvent.encode(message.baseEvent, writer.uint32(10).fork()).join();\n }\n if (message.code !== undefined) {\n writer.uint32(18).string(message.code);\n }\n if (message.message !== \"\") {\n writer.uint32(26).string(message.message);\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): RunErrorEvent {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseRunErrorEvent();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 10) {\n break;\n }\n\n message.baseEvent = BaseEvent.decode(reader, reader.uint32());\n continue;\n }\n case 2: {\n if (tag !== 18) {\n break;\n }\n\n message.code = reader.string();\n continue;\n }\n case 3: {\n if (tag !== 26) {\n break;\n }\n\n message.message = reader.string();\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<RunErrorEvent>, I>>(base?: I): RunErrorEvent {\n return RunErrorEvent.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<RunErrorEvent>, I>>(object: I): RunErrorEvent {\n const message = createBaseRunErrorEvent();\n message.baseEvent = (object.baseEvent !== undefined && object.baseEvent !== null)\n ? BaseEvent.fromPartial(object.baseEvent)\n : undefined;\n message.code = object.code ?? undefined;\n message.message = object.message ?? \"\";\n return message;\n },\n};\n\nfunction createBaseStepStartedEvent(): StepStartedEvent {\n return { baseEvent: undefined, stepName: \"\" };\n}\n\nexport const StepStartedEvent: MessageFns<StepStartedEvent> = {\n encode(message: StepStartedEvent, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n if (message.baseEvent !== undefined) {\n BaseEvent.encode(message.baseEvent, writer.uint32(10).fork()).join();\n }\n if (message.stepName !== \"\") {\n writer.uint32(18).string(message.stepName);\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): StepStartedEvent {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseStepStartedEvent();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 10) {\n break;\n }\n\n message.baseEvent = BaseEvent.decode(reader, reader.uint32());\n continue;\n }\n case 2: {\n if (tag !== 18) {\n break;\n }\n\n message.stepName = reader.string();\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<StepStartedEvent>, I>>(base?: I): StepStartedEvent {\n return StepStartedEvent.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<StepStartedEvent>, I>>(object: I): StepStartedEvent {\n const message = createBaseStepStartedEvent();\n message.baseEvent = (object.baseEvent !== undefined && object.baseEvent !== null)\n ? BaseEvent.fromPartial(object.baseEvent)\n : undefined;\n message.stepName = object.stepName ?? \"\";\n return message;\n },\n};\n\nfunction createBaseStepFinishedEvent(): StepFinishedEvent {\n return { baseEvent: undefined, stepName: \"\" };\n}\n\nexport const StepFinishedEvent: MessageFns<StepFinishedEvent> = {\n encode(message: StepFinishedEvent, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n if (message.baseEvent !== undefined) {\n BaseEvent.encode(message.baseEvent, writer.uint32(10).fork()).join();\n }\n if (message.stepName !== \"\") {\n writer.uint32(18).string(message.stepName);\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): StepFinishedEvent {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseStepFinishedEvent();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 10) {\n break;\n }\n\n message.baseEvent = BaseEvent.decode(reader, reader.uint32());\n continue;\n }\n case 2: {\n if (tag !== 18) {\n break;\n }\n\n message.stepName = reader.string();\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<StepFinishedEvent>, I>>(base?: I): StepFinishedEvent {\n return StepFinishedEvent.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<StepFinishedEvent>, I>>(object: I): StepFinishedEvent {\n const message = createBaseStepFinishedEvent();\n message.baseEvent = (object.baseEvent !== undefined && object.baseEvent !== null)\n ? BaseEvent.fromPartial(object.baseEvent)\n : undefined;\n message.stepName = object.stepName ?? \"\";\n return message;\n },\n};\n\nfunction createBaseTextMessageChunkEvent(): TextMessageChunkEvent {\n return { baseEvent: undefined, messageId: undefined, role: undefined, delta: undefined, name: undefined };\n}\n\nexport const TextMessageChunkEvent: MessageFns<TextMessageChunkEvent> = {\n encode(message: TextMessageChunkEvent, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n if (message.baseEvent !== undefined) {\n BaseEvent.encode(message.baseEvent, writer.uint32(10).fork()).join();\n }\n if (message.messageId !== undefined) {\n writer.uint32(18).string(message.messageId);\n }\n if (message.role !== undefined) {\n writer.uint32(26).string(message.role);\n }\n if (message.delta !== undefined) {\n writer.uint32(34).string(message.delta);\n }\n if (message.name !== undefined) {\n writer.uint32(42).string(message.name);\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): TextMessageChunkEvent {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseTextMessageChunkEvent();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 10) {\n break;\n }\n\n message.baseEvent = BaseEvent.decode(reader, reader.uint32());\n continue;\n }\n case 2: {\n if (tag !== 18) {\n break;\n }\n\n message.messageId = reader.string();\n continue;\n }\n case 3: {\n if (tag !== 26) {\n break;\n }\n\n message.role = reader.string();\n continue;\n }\n case 4: {\n if (tag !== 34) {\n break;\n }\n\n message.delta = reader.string();\n continue;\n }\n case 5: {\n if (tag !== 42) {\n break;\n }\n\n message.name = reader.string();\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<TextMessageChunkEvent>, I>>(base?: I): TextMessageChunkEvent {\n return TextMessageChunkEvent.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<TextMessageChunkEvent>, I>>(object: I): TextMessageChunkEvent {\n const message = createBaseTextMessageChunkEvent();\n message.baseEvent = (object.baseEvent !== undefined && object.baseEvent !== null)\n ? BaseEvent.fromPartial(object.baseEvent)\n : undefined;\n message.messageId = object.messageId ?? undefined;\n message.role = object.role ?? undefined;\n message.delta = object.delta ?? undefined;\n message.name = object.name ?? undefined;\n return message;\n },\n};\n\nfunction createBaseToolCallChunkEvent(): ToolCallChunkEvent {\n return {\n baseEvent: undefined,\n toolCallId: undefined,\n toolCallName: undefined,\n parentMessageId: undefined,\n delta: undefined,\n };\n}\n\nexport const ToolCallChunkEvent: MessageFns<ToolCallChunkEvent> = {\n encode(message: ToolCallChunkEvent, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n if (message.baseEvent !== undefined) {\n BaseEvent.encode(message.baseEvent, writer.uint32(10).fork()).join();\n }\n if (message.toolCallId !== undefined) {\n writer.uint32(18).string(message.toolCallId);\n }\n if (message.toolCallName !== undefined) {\n writer.uint32(26).string(message.toolCallName);\n }\n if (message.parentMessageId !== undefined) {\n writer.uint32(34).string(message.parentMessageId);\n }\n if (message.delta !== undefined) {\n writer.uint32(42).string(message.delta);\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): ToolCallChunkEvent {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseToolCallChunkEvent();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 10) {\n break;\n }\n\n message.baseEvent = BaseEvent.decode(reader, reader.uint32());\n continue;\n }\n case 2: {\n if (tag !== 18) {\n break;\n }\n\n message.toolCallId = reader.string();\n continue;\n }\n case 3: {\n if (tag !== 26) {\n break;\n }\n\n message.toolCallName = reader.string();\n continue;\n }\n case 4: {\n if (tag !== 34) {\n break;\n }\n\n message.parentMessageId = reader.string();\n continue;\n }\n case 5: {\n if (tag !== 42) {\n break;\n }\n\n message.delta = reader.string();\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<ToolCallChunkEvent>, I>>(base?: I): ToolCallChunkEvent {\n return ToolCallChunkEvent.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<ToolCallChunkEvent>, I>>(object: I): ToolCallChunkEvent {\n const message = createBaseToolCallChunkEvent();\n message.baseEvent = (object.baseEvent !== undefined && object.baseEvent !== null)\n ? BaseEvent.fromPartial(object.baseEvent)\n : undefined;\n message.toolCallId = object.toolCallId ?? undefined;\n message.toolCallName = object.toolCallName ?? undefined;\n message.parentMessageId = object.parentMessageId ?? undefined;\n message.delta = object.delta ?? undefined;\n return message;\n },\n};\n\nfunction createBaseEvent(): Event {\n return {\n textMessageStart: undefined,\n textMessageContent: undefined,\n textMessageEnd: undefined,\n toolCallStart: undefined,\n toolCallArgs: undefined,\n toolCallEnd: undefined,\n stateSnapshot: undefined,\n stateDelta: undefined,\n messagesSnapshot: undefined,\n raw: undefined,\n custom: undefined,\n runStarted: undefined,\n runFinished: undefined,\n runError: undefined,\n stepStarted: undefined,\n stepFinished: undefined,\n textMessageChunk: undefined,\n toolCallChunk: undefined,\n };\n}\n\nexport const Event: MessageFns<Event> = {\n encode(message: Event, writer: BinaryWriter = new BinaryWriter()): BinaryWriter {\n if (message.textMessageStart !== undefined) {\n TextMessageStartEvent.encode(message.textMessageStart, writer.uint32(10).fork()).join();\n }\n if (message.textMessageContent !== undefined) {\n TextMessageContentEvent.encode(message.textMessageContent, writer.uint32(18).fork()).join();\n }\n if (message.textMessageEnd !== undefined) {\n TextMessageEndEvent.encode(message.textMessageEnd, writer.uint32(26).fork()).join();\n }\n if (message.toolCallStart !== undefined) {\n ToolCallStartEvent.encode(message.toolCallStart, writer.uint32(34).fork()).join();\n }\n if (message.toolCallArgs !== undefined) {\n ToolCallArgsEvent.encode(message.toolCallArgs, writer.uint32(42).fork()).join();\n }\n if (message.toolCallEnd !== undefined) {\n ToolCallEndEvent.encode(message.toolCallEnd, writer.uint32(50).fork()).join();\n }\n if (message.stateSnapshot !== undefined) {\n StateSnapshotEvent.encode(message.stateSnapshot, writer.uint32(58).fork()).join();\n }\n if (message.stateDelta !== undefined) {\n StateDeltaEvent.encode(message.stateDelta, writer.uint32(66).fork()).join();\n }\n if (message.messagesSnapshot !== undefined) {\n MessagesSnapshotEvent.encode(message.messagesSnapshot, writer.uint32(74).fork()).join();\n }\n if (message.raw !== undefined) {\n RawEvent.encode(message.raw, writer.uint32(82).fork()).join();\n }\n if (message.custom !== undefined) {\n CustomEvent.encode(message.custom, writer.uint32(90).fork()).join();\n }\n if (message.runStarted !== undefined) {\n RunStartedEvent.encode(message.runStarted, writer.uint32(98).fork()).join();\n }\n if (message.runFinished !== undefined) {\n RunFinishedEvent.encode(message.runFinished, writer.uint32(106).fork()).join();\n }\n if (message.runError !== undefined) {\n RunErrorEvent.encode(message.runError, writer.uint32(114).fork()).join();\n }\n if (message.stepStarted !== undefined) {\n StepStartedEvent.encode(message.stepStarted, writer.uint32(122).fork()).join();\n }\n if (message.stepFinished !== undefined) {\n StepFinishedEvent.encode(message.stepFinished, writer.uint32(130).fork()).join();\n }\n if (message.textMessageChunk !== undefined) {\n TextMessageChunkEvent.encode(message.textMessageChunk, writer.uint32(138).fork()).join();\n }\n if (message.toolCallChunk !== undefined) {\n ToolCallChunkEvent.encode(message.toolCallChunk, writer.uint32(146).fork()).join();\n }\n return writer;\n },\n\n decode(input: BinaryReader | Uint8Array, length?: number): Event {\n const reader = input instanceof BinaryReader ? input : new BinaryReader(input);\n const end = length === undefined ? reader.len : reader.pos + length;\n const message = createBaseEvent();\n while (reader.pos < end) {\n const tag = reader.uint32();\n switch (tag >>> 3) {\n case 1: {\n if (tag !== 10) {\n break;\n }\n\n message.textMessageStart = TextMessageStartEvent.decode(reader, reader.uint32());\n continue;\n }\n case 2: {\n if (tag !== 18) {\n break;\n }\n\n message.textMessageContent = TextMessageContentEvent.decode(reader, reader.uint32());\n continue;\n }\n case 3: {\n if (tag !== 26) {\n break;\n }\n\n message.textMessageEnd = TextMessageEndEvent.decode(reader, reader.uint32());\n continue;\n }\n case 4: {\n if (tag !== 34) {\n break;\n }\n\n message.toolCallStart = ToolCallStartEvent.decode(reader, reader.uint32());\n continue;\n }\n case 5: {\n if (tag !== 42) {\n break;\n }\n\n message.toolCallArgs = ToolCallArgsEvent.decode(reader, reader.uint32());\n continue;\n }\n case 6: {\n if (tag !== 50) {\n break;\n }\n\n message.toolCallEnd = ToolCallEndEvent.decode(reader, reader.uint32());\n continue;\n }\n case 7: {\n if (tag !== 58) {\n break;\n }\n\n message.stateSnapshot = StateSnapshotEvent.decode(reader, reader.uint32());\n continue;\n }\n case 8: {\n if (tag !== 66) {\n break;\n }\n\n message.stateDelta = StateDeltaEvent.decode(reader, reader.uint32());\n continue;\n }\n case 9: {\n if (tag !== 74) {\n break;\n }\n\n message.messagesSnapshot = MessagesSnapshotEvent.decode(reader, reader.uint32());\n continue;\n }\n case 10: {\n if (tag !== 82) {\n break;\n }\n\n message.raw = RawEvent.decode(reader, reader.uint32());\n continue;\n }\n case 11: {\n if (tag !== 90) {\n break;\n }\n\n message.custom = CustomEvent.decode(reader, reader.uint32());\n continue;\n }\n case 12: {\n if (tag !== 98) {\n break;\n }\n\n message.runStarted = RunStartedEvent.decode(reader, reader.uint32());\n continue;\n }\n case 13: {\n if (tag !== 106) {\n break;\n }\n\n message.runFinished = RunFinishedEvent.decode(reader, reader.uint32());\n continue;\n }\n case 14: {\n if (tag !== 114) {\n break;\n }\n\n message.runError = RunErrorEvent.decode(reader, reader.uint32());\n continue;\n }\n case 15: {\n if (tag !== 122) {\n break;\n }\n\n message.stepStarted = StepStartedEvent.decode(reader, reader.uint32());\n continue;\n }\n case 16: {\n if (tag !== 130) {\n break;\n }\n\n message.stepFinished = StepFinishedEvent.decode(reader, reader.uint32());\n continue;\n }\n case 17: {\n if (tag !== 138) {\n break;\n }\n\n message.textMessageChunk = TextMessageChunkEvent.decode(reader, reader.uint32());\n continue;\n }\n case 18: {\n if (tag !== 146) {\n break;\n }\n\n message.toolCallChunk = ToolCallChunkEvent.decode(reader, reader.uint32());\n continue;\n }\n }\n if ((tag & 7) === 4 || tag === 0) {\n break;\n }\n reader.skip(tag & 7);\n }\n return message;\n },\n\n create<I extends Exact<DeepPartial<Event>, I>>(base?: I): Event {\n return Event.fromPartial(base ?? ({} as any));\n },\n fromPartial<I extends Exact<DeepPartial<Event>, I>>(object: I): Event {\n const message = createBaseEvent();\n message.textMessageStart = (object.textMessageStart !== undefined && object.textMessageStart !== null)\n ? TextMessageStartEvent.fromPartial(object.textMessageStart)\n : undefined;\n message.textMessageContent = (object.textMessageContent !== undefined && object.textMessageContent !== null)\n ? TextMessageContentEvent.fromPartial(object.textMessageContent)\n : undefined;\n message.textMessageEnd = (object.textMessageEnd !== undefined && object.textMessageEnd !== null)\n ? TextMessageEndEvent.fromPartial(object.textMessageEnd)\n : undefined;\n message.toolCallStart = (object.toolCallStart !== undefined && object.toolCallStart !== null)\n ? ToolCallStartEvent.fromPartial(object.toolCallStart)\n : undefined;\n message.toolCallArgs = (object.toolCallArgs !== undefined && object.toolCallArgs !== null)\n ? ToolCallArgsEvent.fromPartial(object.toolCallArgs)\n : undefined;\n message.toolCallEnd = (object.toolCallEnd !== undefined && object.toolCallEnd !== null)\n ? ToolCallEndEvent.fromPartial(object.toolCallEnd)\n : undefined;\n message.stateSnapshot = (object.stateSnapshot !== undefined && object.stateSnapshot !== null)\n ? StateSnapshotEvent.fromPartial(object.stateSnapshot)\n : undefined;\n message.stateDelta = (object.stateDelta !== undefined && object.stateDelta !== null)\n ? StateDeltaEvent.fromPartial(object.stateDelta)\n : undefined;\n message.messagesSnapshot = (object.messagesSnapshot !== undefined && object.messagesSnapshot !== null)\n ? MessagesSnapshotEvent.fromPartial(object.messagesSnapshot)\n : undefined;\n message.raw = (object.raw !== undefined && object.raw !== null) ? RawEvent.fromPartial(object.raw) : undefined;\n message.custom = (object.custom !== undefined && object.custom !== null)\n ? CustomEvent.fromPartial(object.custom)\n : undefined;\n message.runStarted = (object.runStarted !== undefined && object.runStarted !== null)\n ? RunStartedEvent.fromPartial(object.runStarted)\n : undefined;\n message.runFinished = (object.runFinished !== undefined && object.runFinished !== null)\n ? RunFinishedEvent.fromPartial(object.runFinished)\n : undefined;\n message.runError = (object.runError !== undefined && object.runError !== null)\n ? RunErrorEvent.fromPartial(object.runError)\n : undefined;\n message.stepStarted = (object.stepStarted !== undefined && object.stepStarted !== null)\n ? StepStartedEvent.fromPartial(object.stepStarted)\n : undefined;\n message.stepFinished = (object.stepFinished !== undefined && object.stepFinished !== null)\n ? StepFinishedEvent.fromPartial(object.stepFinished)\n : undefined;\n message.textMessageChunk = (object.textMessageChunk !== undefined && object.textMessageChunk !== null)\n ? TextMessageChunkEvent.fromPartial(object.textMessageChunk)\n : undefined;\n message.toolCallChunk = (object.toolCallChunk !== undefined && object.toolCallChunk !== null)\n ? ToolCallChunkEvent.fromPartial(object.toolCallChunk)\n : undefined;\n return message;\n },\n};\n\ntype Builtin = Date | Function | Uint8Array | string | number | boolean | undefined;\n\nexport type DeepPartial<T> = T extends Builtin ? T\n : T extends globalThis.Array<infer U> ? globalThis.Array<DeepPartial<U>>\n : T extends ReadonlyArray<infer U> ? ReadonlyArray<DeepPartial<U>>\n : T extends {} ? { [K in keyof T]?: DeepPartial<T[K]> }\n : Partial<T>;\n\ntype KeysOfUnion<T> = T extends T ? keyof T : never;\nexport type Exact<P, I extends P> = P extends Builtin ? P\n : P & { [K in keyof P]: Exact<P[K], I[K]> } & { [K in Exclude<keyof I, KeysOfUnion<P>>]: never };\n\nfunction longToNumber(int64: { toString(): string }): number {\n const num = globalThis.Number(int64.toString());\n if (num > globalThis.Number.MAX_SAFE_INTEGER) {\n throw new globalThis.Error(\"Value is larger than Number.MAX_SAFE_INTEGER\");\n }\n if (num < globalThis.Number.MIN_SAFE_INTEGER) {\n throw new globalThis.Error(\"Value is smaller than Number.MIN_SAFE_INTEGER\");\n }\n return num;\n}\n\nexport interface MessageFns<T> {\n encode(message: T, writer?: BinaryWriter): BinaryWriter;\n decode(input: BinaryReader | Uint8Array, length?: number): T;\n create<I extends Exact<DeepPartial<T>, I>>(base?: I): T;\n fromPartial<I extends Exact<DeepPartial<T>, I>>(object: I): T;\n}\n", "import {\n BaseEvent,\n AGUIEvent,\n EventSchemas,\n EventType,\n Message,\n RunFinishedOutcome,\n} from \"@ag-ui/core\";\nimport * as protoEvents from \"./generated/events\";\nimport * as protoPatch from \"./generated/patch\";\n\nconst toProtoSource = (source: any): any => {\n if (!source || typeof source !== \"object\") {\n return undefined;\n }\n\n if (source.type === \"data\") {\n return {\n data: {\n value: source.value,\n mimeType: source.mimeType,\n },\n };\n }\n\n if (source.type === \"url\") {\n return {\n url: {\n value: source.value,\n mimeType: source.mimeType,\n },\n };\n }\n\n return undefined;\n};\n\nconst toProtoContentPart = (part: any): any => {\n if (!part || typeof part !== \"object\") {\n return undefined;\n }\n\n switch (part.type) {\n case \"text\":\n return {\n text: {\n text: part.text,\n },\n };\n case \"image\":\n return {\n image: {\n source: toProtoSource(part.source),\n metadata: part.metadata,\n },\n };\n case \"audio\":\n return {\n audio: {\n source: toProtoSource(part.source),\n metadata: part.metadata,\n },\n };\n case \"video\":\n return {\n video: {\n source: toProtoSource(part.source),\n metadata: part.metadata,\n },\n };\n case \"document\":\n return {\n document: {\n source: toProtoSource(part.source),\n metadata: part.metadata,\n },\n };\n case \"binary\": {\n const source = part.data\n ? { data: { value: part.data, mimeType: part.mimeType } }\n : part.url\n ? { url: { value: part.url, mimeType: part.mimeType } }\n : part.id\n ? { url: { value: part.id, mimeType: part.mimeType } }\n : undefined;\n\n if (!source) {\n return undefined;\n }\n\n return {\n document: {\n source,\n metadata: {\n legacyBinary: true,\n filename: part.filename,\n id: part.id,\n },\n },\n };\n }\n default:\n return undefined;\n }\n};\n\nconst fromProtoSource = (source: any): any => {\n if (!source || typeof source !== \"object\") {\n return undefined;\n }\n\n if (source.data) {\n return {\n type: \"data\",\n value: source.data.value,\n mimeType: source.data.mimeType,\n };\n }\n\n if (source.url) {\n return {\n type: \"url\",\n value: source.url.value,\n mimeType: source.url.mimeType,\n };\n }\n\n return undefined;\n};\n\nconst fromProtoContentPart = (part: any): any => {\n if (!part || typeof part !== \"object\") {\n return undefined;\n }\n\n if (part.text) {\n return {\n type: \"text\",\n text: part.text.text,\n };\n }\n\n if (part.image) {\n return {\n type: \"image\",\n source: fromProtoSource(part.image.source),\n metadata: part.image.metadata,\n };\n }\n\n if (part.audio) {\n return {\n type: \"audio\",\n source: fromProtoSource(part.audio.source),\n metadata: part.audio.metadata,\n };\n }\n\n if (part.video) {\n return {\n type: \"video\",\n source: fromProtoSource(part.video.source),\n metadata: part.video.metadata,\n };\n }\n\n if (part.document) {\n return {\n type: \"document\",\n source: fromProtoSource(part.document.source),\n metadata: part.document.metadata,\n };\n }\n\n return undefined;\n};\n\nfunction toCamelCase(str: string): string {\n return str.toLowerCase().replace(/_([a-z])/g, (_, letter) => letter.toUpperCase());\n}\n\n/**\n * Encodes an event message to a protocol buffer binary format.\n */\nexport function encode(event: BaseEvent): Uint8Array {\n /**\n * In previous versions of AG-UI, we didn't really validate the events\n * against a schema. With stronger types for events and Zod schemas, we\n * can now validate.\n *\n * However, I don't want to break compatibility with existing clients\n * even if they are encoding invalid events. This surfaces a warning\n * to them in those situations.\n *\n * @author mikeryandev\n */\n let validatedEvent: AGUIEvent | BaseEvent;\n try {\n validatedEvent = EventSchemas.parse(event) as AGUIEvent;\n } catch (err) {\n console.warn(\n \"[ag-ui][proto.encode] Malformed devent detected, falling back to unvalidated event\",\n err,\n event,\n );\n validatedEvent = event;\n }\n const oneofField = toCamelCase(validatedEvent.type);\n const { type, timestamp, rawEvent, ...rest } = validatedEvent as AGUIEvent as Record<string, any>;\n\n // since protobuf does not support optional arrays, we need to ensure that the toolCalls array is always present\n if (type === EventType.MESSAGES_SNAPSHOT && Array.isArray(rest.messages)) {\n rest.messages = (rest.messages as Message[]).map((message) => {\n const untypedMessage = message as any;\n const normalizedMessage: any = { ...untypedMessage, contentParts: [] };\n\n if (Array.isArray(untypedMessage.content)) {\n const contentParts = untypedMessage.content\n .map((part: any) => toProtoContentPart(part))\n .filter((part: any) => part !== undefined);\n\n normalizedMessage.contentParts = contentParts;\n normalizedMessage.content = undefined;\n }\n\n if (untypedMessage.toolCalls === undefined) {\n normalizedMessage.toolCalls = [];\n }\n\n return normalizedMessage;\n });\n }\n\n // RunFinishedEvent: flatten the nested `outcome` discriminated union into the\n // proto's `outcome` (string) and `interrupts` (repeated) fields. The wire\n // shape stays stable; the TS layer just exposes a richer object.\n if (type === EventType.RUN_FINISHED) {\n const outcome: RunFinishedOutcome | undefined = rest.outcome;\n if (outcome === undefined) {\n rest.outcome = \"\";\n rest.interrupts = [];\n } else if (outcome.type === \"interrupt\") {\n rest.outcome = \"interrupt\";\n rest.interrupts = outcome.interrupts;\n } else {\n rest.outcome = \"success\";\n rest.interrupts = [];\n }\n }\n\n // custom mapping for json patch operations\n if (type === EventType.STATE_DELTA && Array.isArray(rest.delta)) {\n rest.delta = (rest.delta as any[]).map((operation: any) => ({\n ...operation,\n op: protoPatch.JsonPatchOperationType[operation.op.toUpperCase()],\n }));\n }\n\n const eventMessage = {\n [oneofField]: {\n baseEvent: {\n type: protoEvents.EventType[event.type as keyof typeof protoEvents.EventType],\n timestamp,\n rawEvent,\n },\n ...rest,\n },\n };\n return protoEvents.Event.encode(eventMessage).finish();\n}\n\n/**\n * Decodes a protocol buffer binary format to an event message.\n * The format includes a 4-byte length prefix followed by the message.\n */\nexport function decode(data: Uint8Array): BaseEvent {\n const event = protoEvents.Event.decode(data);\n const decoded = Object.values(event).find((value) => value !== undefined);\n if (!decoded) {\n throw new Error(\"Invalid event\");\n }\n decoded.type = protoEvents.EventType[decoded.baseEvent.type];\n decoded.timestamp = decoded.baseEvent.timestamp;\n decoded.rawEvent = decoded.baseEvent.rawEvent;\n delete decoded.baseEvent;\n\n // we want tool calls to be optional, so we need to remove them if they are empty\n if (decoded.type === EventType.MESSAGES_SNAPSHOT) {\n for (const message of (decoded as any).messages as Message[]) {\n const untypedMessage = message as any;\n\n if (untypedMessage.role === \"user\" && Array.isArray(untypedMessage.contentParts)) {\n const contentParts = untypedMessage.contentParts\n .map((part: any) => fromProtoContentPart(part))\n .filter((part: any) => part !== undefined);\n\n if (contentParts.length > 0) {\n untypedMessage.content = contentParts;\n }\n }\n\n if (Array.isArray(untypedMessage.contentParts) && untypedMessage.contentParts.length === 0) {\n untypedMessage.contentParts = undefined;\n }\n\n if (untypedMessage.toolCalls?.length === 0) {\n untypedMessage.toolCalls = undefined;\n }\n }\n }\n\n // RunFinishedEvent: rebuild the nested `outcome` discriminated union from the\n // flat proto fields. Empty/missing `outcome` decodes to `undefined` (legacy\n // event); \"success\" decodes to `{ type: \"success\" }`; \"interrupt\" decodes to\n // `{ type: \"interrupt\", interrupts }`.\n if (decoded.type === EventType.RUN_FINISHED) {\n const runFinished = decoded as any;\n const wireOutcome: string | undefined =\n typeof runFinished.outcome === \"string\" && runFinished.outcome !== \"\"\n ? runFinished.outcome\n : undefined;\n const wireInterrupts: any[] = Array.isArray(runFinished.interrupts)\n ? runFinished.interrupts\n : [];\n\n delete runFinished.interrupts;\n\n if (wireOutcome === \"interrupt\") {\n runFinished.outcome = { type: \"interrupt\", interrupts: wireInterrupts };\n } else if (wireOutcome === \"success\") {\n runFinished.outcome = { type: \"success\" };\n } else {\n delete runFinished.outcome;\n }\n }\n\n // custom mapping for json patch operations\n if (decoded.type === EventType.STATE_DELTA) {\n for (const operation of (decoded as any).delta) {\n operation.op = protoPatch.JsonPatchOperationType[operation.op].toLowerCase();\n Object.keys(operation).forEach((key) => {\n if (operation[key] === undefined) {\n delete operation[key];\n }\n });\n }\n }\n\n Object.keys(decoded).forEach((key) => {\n if (decoded[key] === undefined) {\n delete decoded[key];\n }\n });\n\n return EventSchemas.parse(decoded);\n}\n", "export { encode, decode } from \"./proto\";\n\nexport const AGUI_MEDIA_TYPE = \"application/vnd.ag-ui.event+proto\";\n", "/**\n * Allowed arithmetic operators\n */\nexport type CompareOperator = '>' | '>=' | '=' | '<' | '<=' | '!=';\n\nexport const semver =\n /^[v^~<>=]*?(\\d+)(?:\\.([x*]|\\d+)(?:\\.([x*]|\\d+)(?:\\.([x*]|\\d+))?(?:-([\\da-z\\-]+(?:\\.[\\da-z\\-]+)*))?(?:\\+[\\da-z\\-]+(?:\\.[\\da-z\\-]+)*)?)?)?$/i;\n\nexport const validateAndParse = (version: string) => {\n if (typeof version !== 'string') {\n throw new TypeError('Invalid argument expected string');\n }\n const match = version.match(semver);\n if (!match) {\n throw new Error(\n `Invalid argument not valid semver ('${version}' received)`\n );\n }\n match.shift();\n return match;\n};\n\nconst isWildcard = (s: string) => s === '*' || s === 'x' || s === 'X';\n\nconst tryParse = (v: string) => {\n const n = parseInt(v, 10);\n return isNaN(n) ? v : n;\n};\n\nconst forceType = (a: string | number, b: string | number) =>\n typeof a !== typeof b ? [String(a), String(b)] : [a, b];\n\nconst compareStrings = (a: string, b: string) => {\n if (isWildcard(a) || isWildcard(b)) return 0;\n const [ap, bp] = forceType(tryParse(a), tryParse(b));\n if (ap > bp) return 1;\n if (ap < bp) return -1;\n return 0;\n};\n\nexport const compareSegments = (\n a: string | string[] | RegExpMatchArray,\n b: string | string[] | RegExpMatchArray\n) => {\n for (let i = 0; i < Math.max(a.length, b.length); i++) {\n const r = compareStrings(a[i] || '0', b[i] || '0');\n if (r !== 0) return r;\n }\n return 0;\n};\n", "import { compareSegments, validateAndParse } from './utils.js';\n\n/**\n * Compare [semver](https://semver.org/) version strings to find greater, equal or lesser.\n * This library supports the full semver specification, including comparing versions with different number of digits like `1.0.0`, `1.0`, `1`, and pre-release versions like `1.0.0-alpha`.\n * @param v1 - First version to compare\n * @param v2 - Second version to compare\n * @returns Numeric value compatible with the [Array.sort(fn) interface](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort#Parameters).\n */\nexport const compareVersions = (v1: string, v2: string) => {\n // validate input and split into segments\n const n1 = validateAndParse(v1);\n const n2 = validateAndParse(v2);\n\n // pop off the patch\n const p1 = n1.pop();\n const p2 = n2.pop();\n\n // validate numbers\n const r = compareSegments(n1, n2);\n if (r !== 0) return r;\n\n // validate pre-release\n if (p1 && p2) {\n return compareSegments(p1.split('.'), p2.split('.'));\n } else if (p1 || p2) {\n return p1 ? -1 : 1;\n }\n\n return 0;\n};\n", "import { v4 as uuidv4 } from \"uuid\";\n\nexport const structuredClone_ = <T>(obj: T): T => {\n if (typeof structuredClone === \"function\") {\n return structuredClone(obj);\n }\n\n try {\n return JSON.parse(JSON.stringify(obj));\n } catch (err) {\n // Preserve array vs object type in shallow fallback\n if (Array.isArray(obj)) {\n return [...obj] as unknown as T;\n }\n return { ...obj } as T;\n }\n};\n\n/**\n * Generate a random UUID v4\n * Cross-platform compatible (Node.js, browsers, React Native)\n */\nexport function randomUUID(): string {\n return uuidv4();\n}\n\n// Note: semver helpers were removed in favor of using\n// the external `compare-versions` library directly at call sites.\n\n/**\n * Parses a semantic version string into its numeric components.\n * Supports incomplete versions (e.g. \"1\", \"1.2\") by defaulting missing segments to zero.\n *\n * @throws If the version string is not a valid semantic version.\n */\n// (Intentionally left minimal.)\n", "import {\n BaseEvent,\n Interrupt,\n Message,\n RunAgentInput,\n RunErrorEvent,\n RunFinishedEvent,\n RunStartedEvent,\n State,\n StateDeltaEvent,\n StateSnapshotEvent,\n StepFinishedEvent,\n StepStartedEvent,\n TextMessageContentEvent,\n TextMessageEndEvent,\n TextMessageStartEvent,\n ToolCallArgsEvent,\n ToolCallEndEvent,\n ToolCallResultEvent,\n ToolCallStartEvent,\n MessagesSnapshotEvent,\n RawEvent,\n CustomEvent,\n ToolCall,\n ActivitySnapshotEvent,\n ActivityDeltaEvent,\n ActivityMessage,\n ReasoningStartEvent,\n ReasoningMessageStartEvent,\n ReasoningMessageContentEvent,\n ReasoningMessageEndEvent,\n ReasoningEndEvent,\n ReasoningEncryptedValueEvent,\n} from \"@ag-ui/core\";\nimport { AbstractAgent } from \"./agent\";\nimport { structuredClone_ } from \"@/utils\";\n\nexport interface AgentStateMutation {\n messages?: Message[];\n state?: State;\n stopPropagation?: boolean;\n}\n\nexport interface AgentSubscriberParams {\n messages: ReadonlyArray<Readonly<Message>>;\n // NOTE: State resolves to `any` at the type level (z.infer<typeof z.any()>), so Readonly<State>\n // provides no compile-time mutation protection. Runtime enforcement via deepFreeze in\n // dev/test mode is the only guard against in-place mutation of state.\n state: Readonly<State>;\n agent: AbstractAgent;\n input: RunAgentInput;\n}\n\n// Utility type to allow callbacks to be implemented either synchronously or asynchronously.\nexport type MaybePromise<T> = T | Promise<T>;\n\nexport interface AgentSubscriber {\n // Request lifecycle\n onRunInitialized?(\n params: AgentSubscriberParams,\n ): MaybePromise<Omit<AgentStateMutation, \"stopPropagation\"> | void>;\n onRunFailed?(\n params: { error: Error } & AgentSubscriberParams,\n ): MaybePromise<Omit<AgentStateMutation, \"stopPropagation\"> | void>;\n onRunFinalized?(\n params: AgentSubscriberParams,\n ): MaybePromise<Omit<AgentStateMutation, \"stopPropagation\"> | void>;\n\n // Events\n onEvent?(\n params: { event: BaseEvent } & AgentSubscriberParams,\n ): MaybePromise<AgentStateMutation | void>;\n\n onRunStartedEvent?(\n params: { event: RunStartedEvent } & AgentSubscriberParams,\n ): MaybePromise<AgentStateMutation | void>;\n onRunFinishedEvent?(\n params: (\n | { event: RunFinishedEvent; outcome: \"success\"; result?: unknown }\n | { event: RunFinishedEvent; outcome: \"interrupt\"; interrupts: Interrupt[] }\n ) &\n AgentSubscriberParams,\n ): MaybePromise<AgentStateMutation | void>;\n onRunErrorEvent?(\n params: { event: RunErrorEvent } & AgentSubscriberParams,\n ): MaybePromise<AgentStateMutation | void>;\n\n onStepStartedEvent?(\n params: { event: StepStartedEvent } & AgentSubscriberParams,\n ): MaybePromise<AgentStateMutation | void>;\n onStepFinishedEvent?(\n params: { event: StepFinishedEvent } & AgentSubscriberParams,\n ): MaybePromise<AgentStateMutation | void>;\n\n onTextMessageStartEvent?(\n params: { event: TextMessageStartEvent } & AgentSubscriberParams,\n ): MaybePromise<AgentStateMutation | void>;\n onTextMessageContentEvent?(\n params: {\n event: TextMessageContentEvent;\n textMessageBuffer: string;\n } & AgentSubscriberParams,\n ): MaybePromise<AgentStateMutation | void>;\n onTextMessageEndEvent?(\n params: { event: TextMessageEndEvent; textMessageBuffer: string } & AgentSubscriberParams,\n ): MaybePromise<AgentStateMutation | void>;\n\n onToolCallStartEvent?(\n params: { event: ToolCallStartEvent } & AgentSubscriberParams,\n ): MaybePromise<AgentStateMutation | void>;\n onToolCallArgsEvent?(\n params: {\n event: ToolCallArgsEvent;\n toolCallBuffer: string;\n toolCallName: string;\n partialToolCallArgs: Record<string, any>;\n } & AgentSubscriberParams,\n ): MaybePromise<AgentStateMutation | void>;\n onToolCallEndEvent?(\n params: {\n event: ToolCallEndEvent;\n toolCallName: string;\n toolCallArgs: Record<string, any>;\n } & AgentSubscriberParams,\n ): MaybePromise<AgentStateMutation | void>;\n\n onToolCallResultEvent?(\n params: { event: ToolCallResultEvent } & AgentSubscriberParams,\n ): MaybePromise<AgentStateMutation | void>;\n\n onStateSnapshotEvent?(\n params: { event: StateSnapshotEvent } & AgentSubscriberParams,\n ): MaybePromise<AgentStateMutation | void>;\n\n onStateDeltaEvent?(\n params: { event: StateDeltaEvent } & AgentSubscriberParams,\n ): MaybePromise<AgentStateMutation | void>;\n\n onMessagesSnapshotEvent?(\n params: { event: MessagesSnapshotEvent } & AgentSubscriberParams,\n ): MaybePromise<AgentStateMutation | void>;\n\n onActivitySnapshotEvent?(\n params: {\n event: ActivitySnapshotEvent;\n activityMessage?: ActivityMessage;\n existingMessage?: Message;\n } & AgentSubscriberParams,\n ): MaybePromise<AgentStateMutation | void>;\n\n onActivityDeltaEvent?(\n params: {\n event: ActivityDeltaEvent;\n activityMessage?: ActivityMessage;\n } & AgentSubscriberParams,\n ): MaybePromise<AgentStateMutation | void>;\n\n onRawEvent?(\n params: { event: RawEvent } & AgentSubscriberParams,\n ): MaybePromise<AgentStateMutation | void>;\n\n onCustomEvent?(\n params: { event: CustomEvent } & AgentSubscriberParams,\n ): MaybePromise<AgentStateMutation | void>;\n\n // Reasoning events\n onReasoningStartEvent?(\n params: { event: ReasoningStartEvent } & AgentSubscriberParams,\n ): MaybePromise<AgentStateMutation | void>;\n\n onReasoningMessageStartEvent?(\n params: { event: ReasoningMessageStartEvent } & AgentSubscriberParams,\n ): MaybePromise<AgentStateMutation | void>;\n\n onReasoningMessageContentEvent?(\n params: {\n event: ReasoningMessageContentEvent;\n reasoningMessageBuffer: string;\n } & AgentSubscriberParams,\n ): MaybePromise<AgentStateMutation | void>;\n\n onReasoningMessageEndEvent?(\n params: {\n event: ReasoningMessageEndEvent;\n reasoningMessageBuffer: string;\n } & AgentSubscriberParams,\n ): MaybePromise<AgentStateMutation | void>;\n\n onReasoningEndEvent?(\n params: { event: ReasoningEndEvent } & AgentSubscriberParams,\n ): MaybePromise<AgentStateMutation | void>;\n\n onReasoningEncryptedValueEvent?(\n params: { event: ReasoningEncryptedValueEvent } & AgentSubscriberParams,\n ): MaybePromise<AgentStateMutation | void>;\n\n // State changes\n onMessagesChanged?(\n params: Omit<AgentSubscriberParams, \"input\"> & { input?: RunAgentInput },\n ): MaybePromise<void>;\n onStateChanged?(\n params: Omit<AgentSubscriberParams, \"input\"> & { input?: RunAgentInput },\n ): MaybePromise<void>;\n onNewMessage?(\n params: { message: Message } & Omit<AgentSubscriberParams, \"input\"> & {\n input?: RunAgentInput;\n },\n ): MaybePromise<void>;\n onNewToolCall?(\n params: { toolCall: ToolCall } & Omit<AgentSubscriberParams, \"input\"> & {\n input?: RunAgentInput;\n },\n ): MaybePromise<void>;\n}\n\nfunction deepFreeze<T>(obj: T): T {\n Object.freeze(obj);\n if (obj !== null && typeof obj === \"object\") {\n for (const value of Object.values(obj)) {\n if (value !== null && typeof value === \"object\" && !Object.isFrozen(value)) {\n deepFreeze(value);\n }\n }\n }\n return obj;\n}\n\nexport async function runSubscribersWithMutation(\n subscribers: AgentSubscriber[],\n initialMessages: Message[],\n initialState: State,\n executor: (\n subscriber: AgentSubscriber,\n messages: ReadonlyArray<Readonly<Message>>,\n state: Readonly<State>,\n ) => MaybePromise<AgentStateMutation | void>,\n): Promise<AgentStateMutation> {\n const hasProcess = typeof process !== \"undefined\" && typeof process.env !== \"undefined\";\n const isTestEnvironment =\n hasProcess && (process.env.NODE_ENV === \"test\" || Boolean(process.env.VITEST_WORKER_ID));\n const isDev =\n hasProcess &&\n (process.env.NODE_ENV === \"development\" ||\n process.env.NODE_ENV === \"test\" ||\n Boolean(process.env.VITEST_WORKER_ID));\n const baselineMessages = structuredClone_(initialMessages);\n const baselineState = structuredClone_(initialState);\n let messages: Message[] = baselineMessages;\n let state: State = baselineState;\n\n let stopPropagation: boolean | undefined = undefined;\n\n for (const subscriber of subscribers) {\n try {\n // Subscribers receive shared references and must not mutate them in-place.\n // Mutations should only be communicated via the return value.\n // In dev/test mode only: deep-freeze inputs so accidental in-place mutations surface\n // as TypeErrors immediately. In production, enforcement is type-level only.\n if (isDev) {\n deepFreeze(messages);\n deepFreeze(state);\n }\n const mutation = await executor(subscriber, messages, state);\n\n if (mutation === undefined) {\n // Nothing returned – keep going\n continue;\n }\n\n // Replace with a defensive copy of the subscriber's mutation,\n // but skip if the subscriber returned the same reference (no-op).\n if (mutation.messages !== undefined && mutation.messages !== messages) {\n messages = structuredClone_(mutation.messages);\n }\n\n if (mutation.state !== undefined && mutation.state !== state) {\n state = structuredClone_(mutation.state);\n }\n\n stopPropagation = mutation.stopPropagation;\n\n if (stopPropagation === true) {\n break;\n }\n } catch (error) {\n if (isDev && error instanceof TypeError) {\n // Likely a freeze violation: subscriber attempted to mutate frozen inputs in-place.\n // In test environments, re-throw so tests fail fast and the violation is visible.\n // In development (non-test), log a specific message to distinguish freeze violations\n // from ordinary subscriber errors.\n if (isTestEnvironment) {\n throw error;\n }\n console.error(\n \"AG-UI: Subscriber attempted to mutate frozen inputs in-place. \" +\n \"Return mutations via AgentStateMutation instead of mutating directly.\",\n error,\n );\n } else if (!isTestEnvironment) {\n console.error(\"Subscriber error:\", error);\n }\n // Skip this subscriber's mutation and continue\n continue;\n }\n }\n\n // In dev/test mode, the canonical messages/state references may have been\n // frozen in-place (for subscriber mutation detection). Clone them before\n // returning so callers receive a mutable copy, not a frozen one.\n return {\n ...(messages !== baselineMessages\n ? { messages: isDev && Object.isFrozen(messages) ? structuredClone_(messages) : messages }\n : {}),\n ...(state !== baselineState\n ? { state: isDev && Object.isFrozen(state) ? structuredClone_(state) : state }\n : {}),\n ...(stopPropagation !== undefined ? { stopPropagation } : {}),\n };\n}\n", "import { Message, ResumeEntry, RunAgentInput, State } from \"@ag-ui/core\";\n\n/** Normalized debug configuration for the AG-UI agent. */\nexport interface ResolvedAgentDebugConfig {\n enabled: boolean;\n events: boolean;\n lifecycle: boolean;\n verbose: boolean;\n}\n\n/** Debug input — boolean shorthand or granular config. */\nexport type AgentDebugConfig =\n | boolean\n | {\n events?: boolean;\n lifecycle?: boolean;\n verbose?: boolean;\n };\n\n/** Resolves an AgentDebugConfig into a normalized ResolvedAgentDebugConfig. */\nexport function resolveAgentDebugConfig(\n debug: AgentDebugConfig | undefined,\n): ResolvedAgentDebugConfig {\n if (!debug) return { enabled: false, events: false, lifecycle: false, verbose: false };\n if (debug === true) return { enabled: true, events: true, lifecycle: true, verbose: true };\n\n const events = debug.events ?? true;\n const lifecycle = debug.lifecycle ?? true;\n const verbose = debug.verbose ?? false;\n return { enabled: events || lifecycle, events, lifecycle, verbose };\n}\n\nexport interface AgentConfig {\n agentId?: string;\n description?: string;\n threadId?: string;\n initialMessages?: Message[];\n initialState?: State;\n debug?: AgentDebugConfig;\n}\n\nexport type HttpAgentFetchFn = (url: string, requestInit: RequestInit) => Promise<Response>;\n\nexport interface HttpAgentConfig extends AgentConfig {\n url: string;\n headers?: Record<string, string>;\n fetch?: HttpAgentFetchFn;\n}\n\nexport interface RunAgentParameters\n extends Partial<Pick<RunAgentInput, \"runId\" | \"tools\" | \"context\" | \"forwardedProps\">> {\n /** Per-interrupt responses addressing every open interrupt from the previous run. */\n resume?: ResumeEntry[];\n}\n", "import { ResolvedAgentDebugConfig, resolveAgentDebugConfig } from \"@/agent/types\";\n\n/** Accepted input wherever a debug logger can be provided. */\nexport type DebugLoggerInput = DebugLogger | boolean | null | undefined;\n\n/**\n * Resolves a DebugLoggerInput into a DebugLogger or undefined.\n * - `true` → creates a new DebugLogger with all logging enabled\n * - `DebugLogger` instance → returned as-is\n * - `false`, `null`, `undefined` → returns undefined\n */\nexport function resolveDebugLogger(input: DebugLoggerInput): DebugLogger | undefined {\n if (input instanceof DebugLogger) return input;\n if (input === true) return new DebugLogger(resolveAgentDebugConfig(true));\n return undefined;\n}\n\n/**\n * Centralized debug logger for the AG-UI event pipeline.\n * Handles verbose vs summary output based on config.\n */\nexport class DebugLogger {\n constructor(private config: ResolvedAgentDebugConfig) {}\n\n /**\n * Log an event-level debug message.\n * Only logs when `config.events` is enabled.\n * In verbose mode, logs the full data; otherwise logs the summary.\n */\n event(prefix: string, label: string, data: unknown, summary?: Record<string, unknown>): void {\n if (!this.config.events) return;\n if (this.config.verbose) {\n console.debug(`[${prefix}] ${label}`, typeof data === \"string\" ? data : JSON.stringify(data));\n } else {\n console.debug(`[${prefix}] ${label}`, summary ?? data);\n }\n }\n\n /**\n * Log a lifecycle-level debug message.\n * Only logs when `config.lifecycle` is enabled.\n */\n lifecycle(prefix: string, label: string, data?: Record<string, unknown>): void {\n if (!this.config.lifecycle) return;\n if (data) {\n console.debug(`[${prefix}] ${label}`, data);\n } else {\n console.debug(`[${prefix}] ${label}`);\n }\n }\n\n /** Whether event-level logging is enabled. */\n get eventsEnabled(): boolean {\n return this.config.events;\n }\n\n /** Whether lifecycle-level logging is enabled. */\n get lifecycleEnabled(): boolean {\n return this.config.lifecycle;\n }\n\n /** Whether any logging is enabled. */\n get enabled(): boolean {\n return this.config.enabled;\n }\n}\n\n/**\n * Creates a DebugLogger if debug is enabled, otherwise returns undefined.\n * This allows consumers to pass it around cheaply when debug is off.\n */\nexport function createDebugLogger(config: ResolvedAgentDebugConfig): DebugLogger | undefined {\n return config.enabled ? new DebugLogger(config) : undefined;\n}\n", "import type { AbstractAgent } from \"@/agent/agent\";\nimport {\n type AgentStateMutation,\n type AgentSubscriber,\n runSubscribersWithMutation,\n} from \"@/agent/subscriber\";\nimport {\n type ActivityDeltaEvent,\n type ActivityMessage,\n type ActivitySnapshotEvent,\n type AssistantMessage,\n type BaseEvent,\n type CustomEvent,\n DeveloperMessage,\n EventType,\n type Message,\n type MessagesSnapshotEvent,\n type RawEvent,\n type ReasoningEncryptedValueEvent,\n type ReasoningEndEvent,\n type ReasoningMessage,\n type ReasoningMessageContentEvent,\n type ReasoningMessageEndEvent,\n type ReasoningMessageStartEvent,\n type ReasoningStartEvent,\n type RunAgentInput,\n type RunErrorEvent,\n type RunFinishedEvent,\n type RunStartedEvent,\n type StateDeltaEvent,\n type StateSnapshotEvent,\n type StepFinishedEvent,\n type StepStartedEvent,\n SystemMessage,\n type TextMessageContentEvent,\n type TextMessageEndEvent,\n type TextMessageStartEvent,\n type ToolCallArgsEvent,\n type ToolCallEndEvent,\n type ToolCallResultEvent,\n type ToolCallStartEvent,\n type ToolMessage,\n UserMessage,\n} from \"@ag-ui/core\";\nimport jsonpatch from \"fast-json-patch\";\nimport { EMPTY, of } from \"rxjs\";\nimport type { Observable } from \"rxjs\";\nimport { concatMap, defaultIfEmpty, mergeAll, mergeMap } from \"rxjs/operators\";\nimport untruncateJson from \"untruncate-json\";\nimport { structuredClone_ } from \"../utils\";\nimport { type DebugLoggerInput, resolveDebugLogger } from \"@/debug-logger\";\n\n/**\n * Resolves (or creates) the assistant message that a tool call should attach to.\n *\n * Resolution order:\n * 1. `parentMessageId` matches an existing assistant message — return it.\n * 2. `parentMessageId` matches a non-assistant message (collision) — create new, keyed by `toolCallId`.\n * 3. `parentMessageId` not found — create new, keyed by `parentMessageId`.\n * 4. No `parentMessageId` — create new, keyed by `toolCallId`.\n */\nfunction resolveOrCreateAssistantMessage(\n messages: Message[],\n parentMessageId: string | undefined,\n toolCallId: string,\n): AssistantMessage {\n if (parentMessageId) {\n const existing = messages.find((m) => m.id === parentMessageId);\n if (existing?.role === \"assistant\") {\n return existing as AssistantMessage;\n }\n\n if (existing) {\n console.warn(\n `TOOL_CALL_START: parentMessageId '${parentMessageId}' matches a '${existing.role}' message, ` +\n `not assistant — falling back to toolCallId`,\n );\n }\n\n const created: AssistantMessage = {\n id: existing ? toolCallId : parentMessageId,\n role: \"assistant\",\n toolCalls: [],\n };\n messages.push(created);\n return created;\n }\n\n const created: AssistantMessage = { id: toolCallId, role: \"assistant\", toolCalls: [] };\n messages.push(created);\n return created;\n}\n\nexport const defaultApplyEvents = (\n input: RunAgentInput,\n events$: Observable<BaseEvent>,\n agent: AbstractAgent,\n subscribers: AgentSubscriber[],\n debugLogger?: DebugLoggerInput,\n): Observable<AgentStateMutation> => {\n const log = resolveDebugLogger(debugLogger);\n let messages = structuredClone_(agent.messages);\n let state = structuredClone_(input.state);\n let currentMutation: AgentStateMutation = {};\n\n const applyMutation = (mutation: AgentStateMutation) => {\n if (mutation.messages !== undefined) {\n messages = mutation.messages;\n currentMutation.messages = mutation.messages;\n }\n if (mutation.state !== undefined) {\n state = mutation.state;\n currentMutation.state = mutation.state;\n }\n };\n\n const emitUpdates = () => {\n const result = structuredClone_(currentMutation) as AgentStateMutation;\n currentMutation = {};\n if (result.messages !== undefined || result.state !== undefined) {\n return of(result);\n }\n return EMPTY;\n };\n\n return events$.pipe(\n concatMap(async (event) => {\n const mutation = await runSubscribersWithMutation(\n subscribers,\n messages,\n state,\n (subscriber, messages, state) =>\n subscriber.onEvent?.({ event, agent, input, messages, state }),\n );\n applyMutation(mutation);\n\n if (mutation.stopPropagation === true) {\n log?.event(\"APPLY\", \"Event dropped:\", event, {\n type: event.type,\n reason: \"stopPropagation by subscriber\",\n });\n } else {\n log?.event(\"APPLY\", \"Event applied:\", event, {\n type: event.type,\n subscribers: subscribers.length,\n });\n }\n\n if (mutation.stopPropagation === true) {\n return emitUpdates();\n }\n\n switch (event.type) {\n case EventType.TEXT_MESSAGE_START: {\n const mutation = await runSubscribersWithMutation(\n subscribers,\n messages,\n state,\n (subscriber, messages, state) =>\n subscriber.onTextMessageStartEvent?.({\n event: event as TextMessageStartEvent,\n messages,\n state,\n agent,\n input,\n }),\n );\n applyMutation(mutation);\n\n if (mutation.stopPropagation !== true) {\n const { messageId, role = \"assistant\", name } = event as TextMessageStartEvent;\n\n // Check if a message with this ID already exists (e.g., created by TOOL_CALL_START\n // with the same parentMessageId)\n const existingMessage = messages.find((m) => m.id === messageId);\n\n if (!existingMessage) {\n // Create a new message using properties from the event\n // Text messages can be developer, system, assistant, or user (not tool)\n const newMessage: Message = {\n id: messageId,\n role: role,\n content: \"\",\n ...(name !== undefined && { name }),\n };\n\n // Add the new message to the messages array\n messages.push(newMessage);\n applyMutation({ messages });\n }\n // If message already exists, we don't need to create a new one\n // The TEXT_MESSAGE_CONTENT events will update the existing message's content\n }\n return emitUpdates();\n }\n\n case EventType.TEXT_MESSAGE_CONTENT: {\n const { messageId, delta } = event as TextMessageContentEvent;\n\n // Find the target message by ID\n const targetMessage = messages.find((m) => m.id === messageId);\n if (!targetMessage) {\n console.warn(`TEXT_MESSAGE_CONTENT: No message found with ID '${messageId}'`);\n return emitUpdates();\n }\n\n const mutation = await runSubscribersWithMutation(\n subscribers,\n messages,\n state,\n (subscriber, messages, state) =>\n subscriber.onTextMessageContentEvent?.({\n event: event as TextMessageContentEvent,\n messages,\n state,\n agent,\n input,\n textMessageBuffer:\n typeof targetMessage.content === \"string\" ? targetMessage.content : \"\",\n }),\n );\n applyMutation(mutation);\n\n if (mutation.stopPropagation !== true) {\n // Append content to the correct message by ID\n const existingContent =\n typeof targetMessage.content === \"string\" ? targetMessage.content : \"\";\n targetMessage.content = `${existingContent}${delta}`;\n applyMutation({ messages });\n }\n\n return emitUpdates();\n }\n\n case EventType.TEXT_MESSAGE_END: {\n const { messageId } = event as TextMessageEndEvent;\n\n // Find the target message by ID\n const targetMessage = messages.find((m) => m.id === messageId);\n if (!targetMessage) {\n console.warn(`TEXT_MESSAGE_END: No message found with ID '${messageId}'`);\n return emitUpdates();\n }\n\n const mutation = await runSubscribersWithMutation(\n subscribers,\n messages,\n state,\n (subscriber, messages, state) =>\n subscriber.onTextMessageEndEvent?.({\n event: event as TextMessageEndEvent,\n messages,\n state,\n agent,\n input,\n textMessageBuffer:\n typeof targetMessage.content === \"string\" ? targetMessage.content : \"\",\n }),\n );\n applyMutation(mutation);\n\n await Promise.all(\n subscribers.map((subscriber) => {\n subscriber.onNewMessage?.({\n message: targetMessage,\n messages,\n state,\n agent,\n input,\n });\n }),\n );\n\n return emitUpdates();\n }\n\n case EventType.TOOL_CALL_START: {\n const mutation = await runSubscribersWithMutation(\n subscribers,\n messages,\n state,\n (subscriber, messages, state) =>\n subscriber.onToolCallStartEvent?.({\n event: event as ToolCallStartEvent,\n messages,\n state,\n agent,\n input,\n }),\n );\n applyMutation(mutation);\n\n if (mutation.stopPropagation !== true) {\n const { toolCallId, toolCallName, parentMessageId } = event as ToolCallStartEvent;\n\n const targetMessage = resolveOrCreateAssistantMessage(\n messages,\n parentMessageId,\n toolCallId,\n );\n\n targetMessage.toolCalls ??= [];\n\n // Add the new tool call\n targetMessage.toolCalls.push({\n id: toolCallId,\n type: \"function\",\n function: {\n name: toolCallName,\n arguments: \"\",\n },\n });\n\n applyMutation({ messages });\n }\n\n return emitUpdates();\n }\n\n case EventType.TOOL_CALL_ARGS: {\n const { toolCallId, delta } = event as ToolCallArgsEvent;\n\n // Find the message containing this tool call\n const targetMessage = messages.find((m) =>\n (m as AssistantMessage).toolCalls?.some((tc) => tc.id === toolCallId),\n ) as AssistantMessage;\n\n if (!targetMessage) {\n console.warn(\n `TOOL_CALL_ARGS: No message found containing tool call with ID '${toolCallId}'`,\n );\n return emitUpdates();\n }\n\n // Find the specific tool call\n const targetToolCall = targetMessage.toolCalls?.find((tc) => tc.id === toolCallId);\n if (!targetToolCall) {\n console.warn(`TOOL_CALL_ARGS: No tool call found with ID '${toolCallId}'`);\n return emitUpdates();\n }\n\n const mutation = await runSubscribersWithMutation(\n subscribers,\n messages,\n state,\n (subscriber, messages, state) => {\n const toolCallBuffer = targetToolCall.function.arguments;\n const toolCallName = targetToolCall.function.name;\n let partialToolCallArgs = {};\n try {\n // Parse from toolCallBuffer only (before current delta is applied)\n partialToolCallArgs = untruncateJson(toolCallBuffer);\n } catch (error) {}\n\n return subscriber.onToolCallArgsEvent?.({\n event: event as ToolCallArgsEvent,\n messages,\n state,\n agent,\n input,\n toolCallBuffer,\n toolCallName,\n partialToolCallArgs,\n });\n },\n );\n applyMutation(mutation);\n\n if (mutation.stopPropagation !== true) {\n // Append the arguments to the correct tool call by ID\n targetToolCall.function.arguments += delta;\n applyMutation({ messages });\n }\n\n return emitUpdates();\n }\n\n case EventType.TOOL_CALL_END: {\n const { toolCallId } = event as ToolCallEndEvent;\n\n // Find the message containing this tool call\n const targetMessage = messages.find((m) =>\n (m as AssistantMessage).toolCalls?.some((tc) => tc.id === toolCallId),\n ) as AssistantMessage;\n\n if (!targetMessage) {\n console.warn(\n `TOOL_CALL_END: No message found containing tool call with ID '${toolCallId}'`,\n );\n return emitUpdates();\n }\n\n // Find the specific tool call\n const targetToolCall = targetMessage.toolCalls?.find((tc) => tc.id === toolCallId);\n if (!targetToolCall) {\n console.warn(`TOOL_CALL_END: No tool call found with ID '${toolCallId}'`);\n return emitUpdates();\n }\n\n const mutation = await runSubscribersWithMutation(\n subscribers,\n messages,\n state,\n (subscriber, messages, state) => {\n const toolCallArgsString = targetToolCall.function.arguments;\n const toolCallName = targetToolCall.function.name;\n let toolCallArgs = {};\n try {\n toolCallArgs = JSON.parse(toolCallArgsString);\n } catch (error) {}\n return subscriber.onToolCallEndEvent?.({\n event: event as ToolCallEndEvent,\n messages,\n state,\n agent,\n input,\n toolCallName,\n toolCallArgs,\n });\n },\n );\n applyMutation(mutation);\n\n await Promise.all(\n subscribers.map((subscriber) => {\n subscriber.onNewToolCall?.({\n toolCall: targetToolCall,\n messages,\n state,\n agent,\n input,\n });\n }),\n );\n\n return emitUpdates();\n }\n\n case EventType.TOOL_CALL_RESULT: {\n const mutation = await runSubscribersWithMutation(\n subscribers,\n messages,\n state,\n (subscriber, messages, state) =>\n subscriber.onToolCallResultEvent?.({\n event: event as ToolCallResultEvent,\n messages,\n state,\n agent,\n input,\n }),\n );\n\n applyMutation(mutation);\n\n if (mutation.stopPropagation !== true) {\n const { messageId, toolCallId, content, role } = event as ToolCallResultEvent;\n\n const toolMessage: ToolMessage = {\n id: messageId,\n toolCallId,\n role: role || \"tool\",\n content: content,\n };\n\n messages.push(toolMessage);\n\n await Promise.all(\n subscribers.map((subscriber) => {\n subscriber.onNewMessage?.({\n message: toolMessage,\n messages,\n state,\n agent,\n input,\n });\n }),\n );\n\n applyMutation({ messages });\n }\n\n return emitUpdates();\n }\n\n case EventType.STATE_SNAPSHOT: {\n const mutation = await runSubscribersWithMutation(\n subscribers,\n messages,\n state,\n (subscriber, messages, state) =>\n subscriber.onStateSnapshotEvent?.({\n event: event as StateSnapshotEvent,\n messages,\n state,\n agent,\n input,\n }),\n );\n applyMutation(mutation);\n\n if (mutation.stopPropagation !== true) {\n const { snapshot } = event as StateSnapshotEvent;\n\n // Replace state with the literal snapshot\n state = snapshot;\n\n applyMutation({ state });\n }\n\n return emitUpdates();\n }\n\n case EventType.STATE_DELTA: {\n const mutation = await runSubscribersWithMutation(\n subscribers,\n messages,\n state,\n (subscriber, messages, state) =>\n subscriber.onStateDeltaEvent?.({\n event: event as StateDeltaEvent,\n messages,\n state,\n agent,\n input,\n }),\n );\n applyMutation(mutation);\n\n if (mutation.stopPropagation !== true) {\n const { delta } = event as StateDeltaEvent;\n\n try {\n // Apply the JSON Patch operations to the current state without mutating the original\n const result = jsonpatch.applyPatch(state, delta, true, false);\n state = result.newDocument;\n applyMutation({ state });\n } catch (error: unknown) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n console.warn(\n `Failed to apply state patch:\\nCurrent state: ${JSON.stringify(state, null, 2)}\\nPatch operations: ${JSON.stringify(delta, null, 2)}\\nError: ${errorMessage}`,\n );\n // If patch failed, only emit updates if there were subscriber mutations\n // This prevents emitting updates when both patch fails AND no subscriber mutations\n }\n }\n\n return emitUpdates();\n }\n\n case EventType.MESSAGES_SNAPSHOT: {\n const mutation = await runSubscribersWithMutation(\n subscribers,\n messages,\n state,\n (subscriber, messages, state) =>\n subscriber.onMessagesSnapshotEvent?.({\n event: event as MessagesSnapshotEvent,\n messages,\n state,\n agent,\n input,\n }),\n );\n applyMutation(mutation);\n\n if (mutation.stopPropagation !== true) {\n const { messages: newMessages } = event as MessagesSnapshotEvent;\n\n // Edit-based merge: update existing messages with snapshot data while\n // preserving activity and reasoning messages (which the backend\n // doesn't include in the snapshot).\n const snapshotMap = new Map(newMessages.map((m) => [m.id, m]));\n\n // Step 1 + 2: Keep activity/reasoning messages as-is, keep messages\n // present in the snapshot (replaced with snapshot version), drop\n // everything else.\n const isClientOnlyRole = (role: string) =>\n role === \"activity\" || role === \"reasoning\";\n messages = messages\n .filter((m) => isClientOnlyRole(m.role) || snapshotMap.has(m.id))\n .map((m) => (isClientOnlyRole(m.role) ? m : snapshotMap.get(m.id)!));\n\n // Step 3: Append messages from the snapshot that we don't have yet.\n const existingIds = new Set(messages.map((m) => m.id));\n for (const snapshotMsg of newMessages) {\n if (!existingIds.has(snapshotMsg.id)) {\n messages.push(snapshotMsg);\n }\n }\n\n applyMutation({ messages });\n }\n\n return emitUpdates();\n }\n\n case EventType.ACTIVITY_SNAPSHOT: {\n const activityEvent = event as ActivitySnapshotEvent;\n const existingIndex = messages.findIndex((m) => m.id === activityEvent.messageId);\n const existingMessage = existingIndex >= 0 ? messages[existingIndex] : undefined;\n const existingActivityMessage =\n existingMessage?.role === \"activity\" ? (existingMessage as ActivityMessage) : undefined;\n const replace = activityEvent.replace ?? true;\n\n const mutation = await runSubscribersWithMutation(\n subscribers,\n messages,\n state,\n (subscriber, messages, state) =>\n subscriber.onActivitySnapshotEvent?.({\n event: activityEvent,\n messages,\n state,\n agent,\n input,\n activityMessage: existingActivityMessage,\n existingMessage,\n }),\n );\n applyMutation(mutation);\n\n if (mutation.stopPropagation !== true) {\n const activityMessage: ActivityMessage = {\n id: activityEvent.messageId,\n role: \"activity\",\n activityType: activityEvent.activityType,\n content: structuredClone_(activityEvent.content),\n };\n\n let createdMessage: ActivityMessage | undefined;\n\n if (existingIndex === -1) {\n messages.push(activityMessage);\n createdMessage = activityMessage;\n } else if (existingActivityMessage) {\n if (replace) {\n messages[existingIndex] = {\n ...existingActivityMessage,\n activityType: activityEvent.activityType,\n content: structuredClone_(activityEvent.content),\n };\n }\n } else if (replace) {\n messages[existingIndex] = activityMessage;\n createdMessage = activityMessage;\n }\n\n applyMutation({ messages });\n\n if (createdMessage) {\n await Promise.all(\n subscribers.map((subscriber) =>\n subscriber.onNewMessage?.({\n message: createdMessage,\n messages,\n state,\n agent,\n input,\n }),\n ),\n );\n }\n }\n\n return emitUpdates();\n }\n\n case EventType.ACTIVITY_DELTA: {\n const activityEvent = event as ActivityDeltaEvent;\n const existingIndex = messages.findIndex((m) => m.id === activityEvent.messageId);\n if (existingIndex === -1) {\n return emitUpdates();\n }\n\n const existingMessage = messages[existingIndex];\n if (existingMessage.role !== \"activity\") {\n console.warn(\n `ACTIVITY_DELTA: Message '${activityEvent.messageId}' is not an activity message`,\n );\n return emitUpdates();\n }\n\n const existingActivityMessage = existingMessage as ActivityMessage;\n\n const mutation = await runSubscribersWithMutation(\n subscribers,\n messages,\n state,\n (subscriber, messages, state) =>\n subscriber.onActivityDeltaEvent?.({\n event: activityEvent,\n messages,\n state,\n agent,\n input,\n activityMessage: existingActivityMessage,\n }),\n );\n applyMutation(mutation);\n\n if (mutation.stopPropagation !== true) {\n try {\n const baseContent = structuredClone_(existingActivityMessage.content ?? {});\n\n const result = jsonpatch.applyPatch(\n baseContent,\n activityEvent.patch ?? [],\n true,\n false,\n );\n const updatedContent = result.newDocument as ActivityMessage[\"content\"];\n\n messages[existingIndex] = {\n ...existingActivityMessage,\n content: structuredClone_(updatedContent),\n activityType: activityEvent.activityType,\n };\n\n applyMutation({ messages });\n } catch (error: unknown) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n console.warn(\n `Failed to apply activity patch for '${activityEvent.messageId}': ${errorMessage}`,\n );\n }\n }\n\n return emitUpdates();\n }\n\n case EventType.RAW: {\n const mutation = await runSubscribersWithMutation(\n subscribers,\n messages,\n state,\n (subscriber, messages, state) =>\n subscriber.onRawEvent?.({\n event: event as RawEvent,\n messages,\n state,\n agent,\n input,\n }),\n );\n applyMutation(mutation);\n\n return emitUpdates();\n }\n\n case EventType.CUSTOM: {\n const mutation = await runSubscribersWithMutation(\n subscribers,\n messages,\n state,\n (subscriber, messages, state) =>\n subscriber.onCustomEvent?.({\n event: event as CustomEvent,\n messages,\n state,\n agent,\n input,\n }),\n );\n applyMutation(mutation);\n\n return emitUpdates();\n }\n\n case EventType.RUN_STARTED: {\n const mutation = await runSubscribersWithMutation(\n subscribers,\n messages,\n state,\n (subscriber, messages, state) =>\n subscriber.onRunStartedEvent?.({\n event: event as RunStartedEvent,\n messages,\n state,\n agent,\n input,\n }),\n );\n applyMutation(mutation);\n\n // Handle input.messages if present and stopPropagation is not set\n if (mutation.stopPropagation !== true) {\n const runStartedEvent = event as RunStartedEvent;\n\n // Check if the event contains input with messages\n if (runStartedEvent.input?.messages) {\n // Add messages that aren't already present (checked by ID)\n for (const message of runStartedEvent.input.messages) {\n const existingMessage = messages.find((m) => m.id === message.id);\n if (!existingMessage) {\n messages.push(message);\n }\n }\n\n // Apply mutation to emit the updated messages\n applyMutation({ messages });\n }\n }\n\n return emitUpdates();\n }\n\n case EventType.RUN_FINISHED: {\n const e = event as RunFinishedEvent;\n const finishedParams =\n e.outcome?.type === \"interrupt\"\n ? ({\n event: e,\n outcome: \"interrupt\" as const,\n interrupts: e.outcome.interrupts,\n } as const)\n : ({ event: e, outcome: \"success\" as const, result: e.result } as const);\n const mutation = await runSubscribersWithMutation(\n subscribers,\n messages,\n state,\n (subscriber, messages, state) =>\n subscriber.onRunFinishedEvent?.({\n ...finishedParams,\n messages,\n state,\n agent,\n input,\n }),\n );\n applyMutation(mutation);\n\n // Update pending interrupts AFTER subscribers run, and only if no\n // subscriber suppressed the event — matches the lifecycle pattern\n // used by every other case in this switch. Defensive-copy the\n // interrupt list so consumers that hold the original event payload\n // can't mutate the agent's tracked state through array aliasing.\n if (mutation.stopPropagation !== true) {\n agent.pendingInterrupts =\n finishedParams.outcome === \"interrupt\"\n ? [...finishedParams.interrupts]\n : [];\n }\n\n return emitUpdates();\n }\n\n case EventType.RUN_ERROR: {\n const mutation = await runSubscribersWithMutation(\n subscribers,\n messages,\n state,\n (subscriber, messages, state) =>\n subscriber.onRunErrorEvent?.({\n event: event as RunErrorEvent,\n messages,\n state,\n agent,\n input,\n }),\n );\n applyMutation(mutation);\n\n return emitUpdates();\n }\n\n case EventType.STEP_STARTED: {\n const mutation = await runSubscribersWithMutation(\n subscribers,\n messages,\n state,\n (subscriber, messages, state) =>\n subscriber.onStepStartedEvent?.({\n event: event as StepStartedEvent,\n messages,\n state,\n agent,\n input,\n }),\n );\n applyMutation(mutation);\n\n return emitUpdates();\n }\n\n case EventType.STEP_FINISHED: {\n const mutation = await runSubscribersWithMutation(\n subscribers,\n messages,\n state,\n (subscriber, messages, state) =>\n subscriber.onStepFinishedEvent?.({\n event: event as StepFinishedEvent,\n messages,\n state,\n agent,\n input,\n }),\n );\n applyMutation(mutation);\n\n return emitUpdates();\n }\n\n case EventType.TEXT_MESSAGE_CHUNK: {\n throw new Error(\"TEXT_MESSAGE_CHUNK must be tranformed before being applied\");\n }\n\n case EventType.TOOL_CALL_CHUNK: {\n throw new Error(\"TOOL_CALL_CHUNK must be tranformed before being applied\");\n }\n\n case EventType.THINKING_START: {\n return emitUpdates();\n }\n\n case EventType.THINKING_END: {\n return emitUpdates();\n }\n\n case EventType.THINKING_TEXT_MESSAGE_START: {\n return emitUpdates();\n }\n\n case EventType.THINKING_TEXT_MESSAGE_CONTENT: {\n return emitUpdates();\n }\n\n case EventType.THINKING_TEXT_MESSAGE_END: {\n return emitUpdates();\n }\n\n case EventType.REASONING_START: {\n const mutation = await runSubscribersWithMutation(\n subscribers,\n messages,\n state,\n (subscriber, messages, state) =>\n subscriber.onReasoningStartEvent?.({\n event: event as ReasoningStartEvent,\n messages,\n state,\n agent,\n input,\n }),\n );\n applyMutation(mutation);\n return emitUpdates();\n }\n\n case EventType.REASONING_MESSAGE_START: {\n const mutation = await runSubscribersWithMutation(\n subscribers,\n messages,\n state,\n (subscriber, messages, state) =>\n subscriber.onReasoningMessageStartEvent?.({\n event: event as ReasoningMessageStartEvent,\n messages,\n state,\n agent,\n input,\n }),\n );\n applyMutation(mutation);\n\n if (mutation.stopPropagation !== true) {\n const { messageId } = event as ReasoningMessageStartEvent;\n const existingMessage = messages.find((m) => m.id === messageId);\n\n if (!existingMessage) {\n const newMessage: ReasoningMessage = {\n id: messageId,\n role: \"reasoning\",\n content: \"\",\n };\n messages.push(newMessage);\n applyMutation({ messages });\n }\n }\n return emitUpdates();\n }\n\n case EventType.REASONING_MESSAGE_CONTENT: {\n const { messageId, delta } = event as ReasoningMessageContentEvent;\n\n const targetMessage = messages.find((m) => m.id === messageId);\n if (!targetMessage) {\n console.warn(`REASONING_MESSAGE_CONTENT: No message found with ID '${messageId}'`);\n return emitUpdates();\n }\n\n const mutation = await runSubscribersWithMutation(\n subscribers,\n messages,\n state,\n (subscriber, messages, state) =>\n subscriber.onReasoningMessageContentEvent?.({\n event: event as ReasoningMessageContentEvent,\n messages,\n state,\n agent,\n input,\n reasoningMessageBuffer:\n typeof targetMessage.content === \"string\" ? targetMessage.content : \"\",\n }),\n );\n applyMutation(mutation);\n\n if (mutation.stopPropagation !== true) {\n const existingContent =\n typeof targetMessage.content === \"string\" ? targetMessage.content : \"\";\n targetMessage.content = `${existingContent}${delta}`;\n applyMutation({ messages });\n }\n return emitUpdates();\n }\n\n case EventType.REASONING_MESSAGE_END: {\n const { messageId } = event as ReasoningMessageEndEvent;\n\n const targetMessage = messages.find((m) => m.id === messageId);\n if (!targetMessage) {\n console.warn(`REASONING_MESSAGE_END: No message found with ID '${messageId}'`);\n return emitUpdates();\n }\n\n const mutation = await runSubscribersWithMutation(\n subscribers,\n messages,\n state,\n (subscriber, messages, state) =>\n subscriber.onReasoningMessageEndEvent?.({\n event: event as ReasoningMessageEndEvent,\n messages,\n state,\n agent,\n input,\n reasoningMessageBuffer:\n typeof targetMessage.content === \"string\" ? targetMessage.content : \"\",\n }),\n );\n applyMutation(mutation);\n\n await Promise.all(\n subscribers.map((subscriber) => {\n subscriber.onNewMessage?.({\n message: targetMessage,\n messages,\n state,\n agent,\n input,\n });\n }),\n );\n\n return emitUpdates();\n }\n\n case EventType.REASONING_MESSAGE_CHUNK: {\n throw new Error(\"REASONING_MESSAGE_CHUNK must be transformed before being applied\");\n }\n\n case EventType.REASONING_END: {\n const mutation = await runSubscribersWithMutation(\n subscribers,\n messages,\n state,\n (subscriber, messages, state) =>\n subscriber.onReasoningEndEvent?.({\n event: event as ReasoningEndEvent,\n messages,\n state,\n agent,\n input,\n }),\n );\n applyMutation(mutation);\n return emitUpdates();\n }\n\n case EventType.REASONING_ENCRYPTED_VALUE: {\n const { subtype, entityId, encryptedValue } = event as ReasoningEncryptedValueEvent;\n const mutation = await runSubscribersWithMutation(\n subscribers,\n messages,\n state,\n (subscriber, messages, state) =>\n subscriber.onReasoningEncryptedValueEvent?.({\n event: event as ReasoningEncryptedValueEvent,\n messages,\n state,\n agent,\n input,\n }),\n );\n applyMutation(mutation);\n if (mutation.stopPropagation !== true) {\n let entityUpdated = false;\n if (subtype === \"tool-call\") {\n // Find tool call by entityId and set encryptedValue\n for (const message of messages) {\n if (message.role === \"assistant\" && message.toolCalls) {\n const toolCall = message.toolCalls.find((tc) => tc.id === entityId);\n if (toolCall) {\n toolCall.encryptedValue = encryptedValue;\n entityUpdated = true;\n break;\n }\n }\n }\n } else {\n // subtype is \"message\"\n // Find message by entityId and set encryptedValue\n const message = messages.find((m) => m.id === entityId);\n // Activity messages do not have encryptedValue\n if (message?.role !== \"activity\" && message) {\n message.encryptedValue = encryptedValue;\n entityUpdated = true;\n }\n }\n if (entityUpdated) {\n currentMutation.messages = messages;\n }\n }\n return emitUpdates();\n }\n }\n\n // This makes TypeScript check that the switch is exhaustive\n // If a new EventType is added, this will cause a compile error\n const _exhaustiveCheck: never = event.type;\n return emitUpdates();\n }),\n mergeAll(),\n // Only use defaultIfEmpty when there are subscribers to avoid emitting empty updates\n // when patches fail and there are no subscribers (like in state patching test)\n subscribers.length > 0 ? defaultIfEmpty({} as AgentStateMutation) : (stream: any) => stream,\n );\n};\n", "import { BaseEvent, EventType, AGUIError } from \"@ag-ui/core\";\nimport { Observable, throwError, of } from \"rxjs\";\nimport { mergeMap } from \"rxjs/operators\";\nimport { type DebugLoggerInput, resolveDebugLogger } from \"@/debug-logger\";\n\nexport const verifyEvents =\n (debugLogger?: DebugLoggerInput) =>\n (source$: Observable<BaseEvent>): Observable<BaseEvent> => {\n const log = resolveDebugLogger(debugLogger);\n // Declare variables in closure to maintain state across events\n let activeMessages = new Map<string, boolean>(); // Map of message ID -> active status\n let activeToolCalls = new Map<string, boolean>(); // Map of tool call ID -> active status\n let runFinished = false;\n let runError = false; // New flag to track if RUN_ERROR has been sent\n // New flags to track first/last event requirements\n let firstEventReceived = false;\n // Track active steps\n let activeSteps = new Map<string, boolean>(); // Map of step name -> active status\n let activeThinkingStep = false;\n let activeThinkingStepMessage = false;\n let runStarted = false; // Track if a run has started\n\n // Function to reset state for a new run\n const resetRunState = () => {\n activeMessages.clear();\n activeToolCalls.clear();\n activeSteps.clear();\n activeThinkingStep = false;\n activeThinkingStepMessage = false;\n runFinished = false;\n runError = false;\n runStarted = true;\n };\n\n return source$.pipe(\n // Process each event through our state machine\n mergeMap((event) => {\n const eventType = event.type;\n\n log?.event(\"VERIFY\", \"Event:\", event, { type: event.type });\n\n // Check if run has errored\n if (runError) {\n return throwError(\n () =>\n new AGUIError(\n `Cannot send event type '${eventType}': The run has already errored with 'RUN_ERROR'. No further events can be sent.`,\n ),\n );\n }\n\n // Check if run has already finished (but allow new RUN_STARTED to start a new run)\n if (\n runFinished &&\n eventType !== EventType.RUN_ERROR &&\n eventType !== EventType.RUN_STARTED\n ) {\n return throwError(\n () =>\n new AGUIError(\n `Cannot send event type '${eventType}': The run has already finished with 'RUN_FINISHED'. Start a new run with 'RUN_STARTED'.`,\n ),\n );\n }\n\n // Handle first event requirement and sequential RUN_STARTED\n if (!firstEventReceived) {\n firstEventReceived = true;\n if (eventType !== EventType.RUN_STARTED && eventType !== EventType.RUN_ERROR) {\n return throwError(() => new AGUIError(`First event must be 'RUN_STARTED'`));\n }\n } else if (eventType === EventType.RUN_STARTED) {\n // Allow RUN_STARTED after RUN_FINISHED (new run), but not during an active run\n if (runStarted && !runFinished) {\n return throwError(\n () =>\n new AGUIError(\n `Cannot send 'RUN_STARTED' while a run is still active. The previous run must be finished with 'RUN_FINISHED' before starting a new run.`,\n ),\n );\n }\n // If we're here, it's either the first RUN_STARTED or a new run after RUN_FINISHED\n if (runFinished) {\n // This is a new run after the previous one finished, reset state\n resetRunState();\n }\n }\n\n // Validate event based on type and current state\n switch (eventType) {\n // Text message flow\n case EventType.TEXT_MESSAGE_START: {\n const messageId = (event as any).messageId;\n\n // Check if this message is already in progress\n if (activeMessages.has(messageId)) {\n return throwError(\n () =>\n new AGUIError(\n `Cannot send 'TEXT_MESSAGE_START' event: A text message with ID '${messageId}' is already in progress. Complete it with 'TEXT_MESSAGE_END' first.`,\n ),\n );\n }\n\n activeMessages.set(messageId, true);\n return of(event);\n }\n\n case EventType.TEXT_MESSAGE_CONTENT: {\n const messageId = (event as any).messageId;\n\n // Must be in a message with this ID\n if (!activeMessages.has(messageId)) {\n return throwError(\n () =>\n new AGUIError(\n `Cannot send 'TEXT_MESSAGE_CONTENT' event: No active text message found with ID '${messageId}'. Start a text message with 'TEXT_MESSAGE_START' first.`,\n ),\n );\n }\n\n return of(event);\n }\n\n case EventType.TEXT_MESSAGE_END: {\n const messageId = (event as any).messageId;\n\n // Must be in a message with this ID\n if (!activeMessages.has(messageId)) {\n return throwError(\n () =>\n new AGUIError(\n `Cannot send 'TEXT_MESSAGE_END' event: No active text message found with ID '${messageId}'. A 'TEXT_MESSAGE_START' event must be sent first.`,\n ),\n );\n }\n\n // Remove message from active set\n activeMessages.delete(messageId);\n return of(event);\n }\n\n // Tool call flow\n case EventType.TOOL_CALL_START: {\n const toolCallId = (event as any).toolCallId;\n\n // Check if this tool call is already in progress\n if (activeToolCalls.has(toolCallId)) {\n return throwError(\n () =>\n new AGUIError(\n `Cannot send 'TOOL_CALL_START' event: A tool call with ID '${toolCallId}' is already in progress. Complete it with 'TOOL_CALL_END' first.`,\n ),\n );\n }\n\n activeToolCalls.set(toolCallId, true);\n return of(event);\n }\n\n case EventType.TOOL_CALL_ARGS: {\n const toolCallId = (event as any).toolCallId;\n\n // Must be in a tool call with this ID\n if (!activeToolCalls.has(toolCallId)) {\n return throwError(\n () =>\n new AGUIError(\n `Cannot send 'TOOL_CALL_ARGS' event: No active tool call found with ID '${toolCallId}'. Start a tool call with 'TOOL_CALL_START' first.`,\n ),\n );\n }\n\n return of(event);\n }\n\n case EventType.TOOL_CALL_END: {\n const toolCallId = (event as any).toolCallId;\n\n // Must be in a tool call with this ID\n if (!activeToolCalls.has(toolCallId)) {\n return throwError(\n () =>\n new AGUIError(\n `Cannot send 'TOOL_CALL_END' event: No active tool call found with ID '${toolCallId}'. A 'TOOL_CALL_START' event must be sent first.`,\n ),\n );\n }\n\n // Remove tool call from active set\n activeToolCalls.delete(toolCallId);\n return of(event);\n }\n\n // Step flow\n case EventType.STEP_STARTED: {\n const stepName = (event as any).stepName;\n if (activeSteps.has(stepName)) {\n return throwError(\n () => new AGUIError(`Step \"${stepName}\" is already active for 'STEP_STARTED'`),\n );\n }\n activeSteps.set(stepName, true);\n return of(event);\n }\n\n case EventType.STEP_FINISHED: {\n const stepName = (event as any).stepName;\n if (!activeSteps.has(stepName)) {\n return throwError(\n () =>\n new AGUIError(\n `Cannot send 'STEP_FINISHED' for step \"${stepName}\" that was not started`,\n ),\n );\n }\n activeSteps.delete(stepName);\n return of(event);\n }\n\n // Run flow\n case EventType.RUN_STARTED: {\n // We've already validated this above\n runStarted = true;\n return of(event);\n }\n\n case EventType.RUN_FINISHED: {\n // Can't be the first event (already checked)\n // and can't happen after already being finished (already checked)\n\n // Check that all steps are finished before run ends\n if (activeSteps.size > 0) {\n const unfinishedSteps = Array.from(activeSteps.keys()).join(\", \");\n return throwError(\n () =>\n new AGUIError(\n `Cannot send 'RUN_FINISHED' while steps are still active: ${unfinishedSteps}`,\n ),\n );\n }\n\n // Check that all messages are finished before run ends\n if (activeMessages.size > 0) {\n const unfinishedMessages = Array.from(activeMessages.keys()).join(\", \");\n return throwError(\n () =>\n new AGUIError(\n `Cannot send 'RUN_FINISHED' while text messages are still active: ${unfinishedMessages}`,\n ),\n );\n }\n\n // Check that all tool calls are finished before run ends\n if (activeToolCalls.size > 0) {\n const unfinishedToolCalls = Array.from(activeToolCalls.keys()).join(\", \");\n return throwError(\n () =>\n new AGUIError(\n `Cannot send 'RUN_FINISHED' while tool calls are still active: ${unfinishedToolCalls}`,\n ),\n );\n }\n\n runFinished = true;\n return of(event);\n }\n\n case EventType.RUN_ERROR: {\n // RUN_ERROR can happen at any time\n runError = true; // Set flag to prevent any further events\n return of(event);\n }\n\n case EventType.CUSTOM: {\n return of(event);\n }\n\n // Text message flow\n case EventType.THINKING_TEXT_MESSAGE_START: {\n if (!activeThinkingStep) {\n return throwError(\n () =>\n new AGUIError(\n `Cannot send 'THINKING_TEXT_MESSAGE_START' event: A thinking step is not in progress. Create one with 'THINKING_START' first.`,\n ),\n );\n }\n // Can't start a message if one is already in progress\n if (activeThinkingStepMessage) {\n return throwError(\n () =>\n new AGUIError(\n `Cannot send 'THINKING_TEXT_MESSAGE_START' event: A thinking message is already in progress. Complete it with 'THINKING_TEXT_MESSAGE_END' first.`,\n ),\n );\n }\n\n activeThinkingStepMessage = true;\n return of(event);\n }\n\n case EventType.THINKING_TEXT_MESSAGE_CONTENT: {\n // Must be in a message and IDs must match\n if (!activeThinkingStepMessage) {\n return throwError(\n () =>\n new AGUIError(\n `Cannot send 'THINKING_TEXT_MESSAGE_CONTENT' event: No active thinking message found. Start a message with 'THINKING_TEXT_MESSAGE_START' first.`,\n ),\n );\n }\n\n return of(event);\n }\n\n case EventType.THINKING_TEXT_MESSAGE_END: {\n // Must be in a message and IDs must match\n if (!activeThinkingStepMessage) {\n return throwError(\n () =>\n new AGUIError(\n `Cannot send 'THINKING_TEXT_MESSAGE_END' event: No active thinking message found. A 'THINKING_TEXT_MESSAGE_START' event must be sent first.`,\n ),\n );\n }\n\n // Reset message state\n activeThinkingStepMessage = false;\n return of(event);\n }\n\n case EventType.THINKING_START: {\n if (activeThinkingStep) {\n return throwError(\n () =>\n new AGUIError(\n `Cannot send 'THINKING_START' event: A thinking step is already in progress. End it with 'THINKING_END' first.`,\n ),\n );\n }\n\n activeThinkingStep = true;\n return of(event);\n }\n\n case EventType.THINKING_END: {\n // Must be in a message and IDs must match\n if (!activeThinkingStep) {\n return throwError(\n () =>\n new AGUIError(\n `Cannot send 'THINKING_END' event: No active thinking step found. A 'THINKING_START' event must be sent first.`,\n ),\n );\n }\n\n // Reset message state\n activeThinkingStep = false;\n return of(event);\n }\n\n default: {\n return of(event);\n }\n }\n }),\n );\n };\n", "import { Observable, from, defer, throwError } from \"rxjs\";\nimport { mergeMap, switchMap } from \"rxjs/operators\";\n\nexport enum HttpEventType {\n HEADERS = \"headers\",\n DATA = \"data\",\n}\n\nexport interface HttpDataEvent {\n type: HttpEventType.DATA;\n data?: Uint8Array;\n}\n\nexport interface HttpHeadersEvent {\n type: HttpEventType.HEADERS;\n status: number;\n headers: Headers;\n}\n\nexport type HttpEvent = HttpDataEvent | HttpHeadersEvent;\n\nexport const runHttpRequest = (\n fetchResponse: () => Promise<Response>,\n): Observable<HttpEvent> => {\n // Defer the fetch so that it's executed when subscribed to\n return defer(() => from(fetchResponse())).pipe(\n switchMap((response) => {\n if (!response.ok) {\n const contentType = response.headers.get(\"content-type\") || \"\";\n // Read the (small) error body once, then error the stream\n return from(response.text()).pipe(\n mergeMap((text) => {\n let payload: unknown = text;\n if (contentType.includes(\"application/json\")) {\n try { payload = JSON.parse(text); } catch {/* keep raw text */}\n }\n const err: any = new Error(\n `HTTP ${response.status}: ${typeof payload === \"string\" ? payload : JSON.stringify(payload)}`\n );\n err.status = response.status;\n err.payload = payload;\n return throwError(() => err);\n })\n );\n }\n // Emit headers event first\n const headersEvent: HttpHeadersEvent = {\n type: HttpEventType.HEADERS,\n status: response.status,\n headers: response.headers,\n };\n\n const reader = response.body?.getReader();\n if (!reader) {\n return throwError(() => new Error(\"Failed to getReader() from response\"));\n }\n\n return new Observable<HttpEvent>((subscriber) => {\n // Emit headers event first\n subscriber.next(headersEvent);\n\n (async () => {\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n // Emit data event instead of raw Uint8Array\n const dataEvent: HttpDataEvent = {\n type: HttpEventType.DATA,\n data: value,\n };\n subscriber.next(dataEvent);\n }\n subscriber.complete();\n } catch (error) {\n subscriber.error(error);\n }\n })();\n\n return () => {\n reader.cancel().catch((error) => {\n if ((error as DOMException)?.name === \"AbortError\") {\n return;\n }\n\n throw error;\n });\n };\n });\n }),\n );\n};\n", "import { Observable, Subject } from \"rxjs\";\nimport { HttpEvent, HttpEventType } from \"../run/http-request\";\nimport { type DebugLoggerInput, resolveDebugLogger } from \"@/debug-logger\";\n\n/**\n * Parses a stream of HTTP events into a stream of JSON objects using Server-Sent Events (SSE) format.\n * Strictly follows the SSE standard where:\n * - Events are separated by double newlines ('\\n\\n')\n * - Only 'data:' prefixed lines are processed\n * - Multi-line data events are supported and joined\n * - Non-data fields (event, id, retry) are ignored\n */\nexport const parseSSEStream = (\n source$: Observable<HttpEvent>,\n debugLogger?: DebugLoggerInput,\n): Observable<any> => {\n const log = resolveDebugLogger(debugLogger);\n const jsonSubject = new Subject<any>();\n // Create TextDecoder with stream option set to true to handle split UTF-8 characters\n const decoder = new TextDecoder(\"utf-8\", { fatal: false });\n let buffer = \"\";\n\n // Subscribe to the source once and multicast to all subscribers\n source$.subscribe({\n next: (event: HttpEvent) => {\n if (event.type === HttpEventType.HEADERS) {\n return;\n }\n\n if (event.type === HttpEventType.DATA && event.data) {\n // Decode chunk carefully to handle UTF-8\n const text = decoder.decode(event.data, { stream: true });\n buffer += text;\n\n // Process complete events (separated by double newlines)\n const events = buffer.split(/\\n\\n/);\n // Keep the last potentially incomplete event in buffer\n buffer = events.pop() || \"\";\n\n for (const event of events) {\n processSSEEvent(event);\n }\n }\n },\n error: (err) => jsonSubject.error(err),\n complete: () => {\n // Use the final call to decoder.decode() to flush any remaining bytes\n if (buffer) {\n buffer += decoder.decode();\n // Process any remaining SSE event data\n processSSEEvent(buffer);\n }\n jsonSubject.complete();\n },\n });\n\n /**\n * Helper function to process an SSE event.\n * Extracts and joins data lines, then parses the result as JSON.\n *\n * Follows the SSE spec by processing lines starting with 'data:',\n * ignoring a single space if it is present after the colon.\n *\n * @param eventText The raw event text to process\n */\n function processSSEEvent(eventText: string) {\n const lines = eventText.split(\"\\n\");\n const dataLines: string[] = [];\n\n for (const line of lines) {\n if (line.startsWith(\"data:\")) {\n // Remove 'data:' prefix, and optionally a single space afterwards\n dataLines.push(line.slice(5).replace(/^ /, \"\"));\n }\n }\n\n // Only process if we have data lines\n if (dataLines.length > 0) {\n try {\n // Join multi-line data and parse JSON\n const jsonStr = dataLines.join(\"\\n\");\n const json = JSON.parse(jsonStr);\n log?.event(\"SSE\", \"Event received:\", json, { type: json.type });\n jsonSubject.next(json);\n } catch (err) {\n jsonSubject.error(err);\n }\n }\n }\n\n return jsonSubject.asObservable();\n};\n", "import { Observable, Subject } from \"rxjs\";\nimport { HttpEvent, HttpEventType } from \"../run/http-request\";\nimport { BaseEvent } from \"@ag-ui/core\";\nimport * as proto from \"@ag-ui/proto\";\n\n/**\n * Parses a stream of HTTP events into a stream of BaseEvent objects using Protocol Buffer format.\n * Each message is prefixed with a 4-byte length header (uint32 in big-endian format)\n * followed by the protocol buffer encoded message.\n */\nexport const parseProtoStream = (source$: Observable<HttpEvent>): Observable<BaseEvent> => {\n const eventSubject = new Subject<BaseEvent>();\n let buffer = new Uint8Array(0);\n\n source$.subscribe({\n next: (event: HttpEvent) => {\n if (event.type === HttpEventType.HEADERS) {\n return;\n }\n\n if (event.type === HttpEventType.DATA && event.data) {\n // Append the new data to our buffer\n const newBuffer = new Uint8Array(buffer.length + event.data.length);\n newBuffer.set(buffer, 0);\n newBuffer.set(event.data, buffer.length);\n buffer = newBuffer;\n\n // Process as many complete messages as possible\n processBuffer();\n }\n },\n error: (err) => eventSubject.error(err),\n complete: () => {\n // Try to process any remaining data in the buffer\n if (buffer.length > 0) {\n try {\n processBuffer();\n } catch (error: unknown) {\n console.warn(\"Incomplete or invalid protocol buffer data at stream end\");\n }\n }\n eventSubject.complete();\n },\n });\n\n /**\n * Process as many complete messages as possible from the buffer\n */\n function processBuffer() {\n // Keep processing while we have enough data for at least a header (4 bytes)\n while (buffer.length >= 4) {\n // Read message length from the first 4 bytes (big-endian uint32)\n const view = new DataView(buffer.buffer, buffer.byteOffset, 4);\n const messageLength = view.getUint32(0, false); // false = big-endian\n\n // Check if we have the complete message (header + message body)\n const totalLength = 4 + messageLength;\n if (buffer.length < totalLength) {\n // Not enough data yet, wait for more\n break;\n }\n\n try {\n // Extract the message (skipping the 4-byte header)\n const message = buffer.slice(4, totalLength);\n\n // Decode the protocol buffer message using the imported decode function\n const event = proto.decode(message);\n\n // Emit the parsed event\n eventSubject.next(event);\n\n // Remove the processed message from the buffer\n buffer = buffer.slice(totalLength);\n } catch (error: unknown) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n eventSubject.error(new Error(`Failed to decode protocol buffer message: ${errorMessage}`));\n return;\n }\n }\n }\n\n return eventSubject.asObservable();\n};\n", "import { BaseEvent, EventSchemas } from \"@ag-ui/core\";\nimport { Subject, ReplaySubject, Observable } from \"rxjs\";\nimport { HttpEvent, HttpEventType } from \"../run/http-request\";\nimport { parseSSEStream } from \"./sse\";\nimport { parseProtoStream } from \"./proto\";\nimport * as proto from \"@ag-ui/proto\";\nimport { EventType } from \"@ag-ui/core\";\nimport { type DebugLoggerInput, resolveDebugLogger } from \"@/debug-logger\";\n\n/**\n * Transforms HTTP events into BaseEvents using the appropriate format parser based on content type.\n */\nexport const transformHttpEventStream = (\n source$: Observable<HttpEvent>,\n debugLogger?: DebugLoggerInput,\n): Observable<BaseEvent> => {\n const log = resolveDebugLogger(debugLogger);\n const eventSubject = new Subject<BaseEvent>();\n\n // Use ReplaySubject to buffer events until we decide on the parser\n const bufferSubject = new ReplaySubject<HttpEvent>();\n\n // Flag to track whether we've set up the parser\n let parserInitialized = false;\n\n // Subscribe to source and buffer events while we determine the content type\n source$.subscribe({\n next: (event: HttpEvent) => {\n // Forward event to buffer\n bufferSubject.next(event);\n\n // If we get headers and haven't initialized a parser yet, check content type\n if (event.type === HttpEventType.HEADERS && !parserInitialized) {\n parserInitialized = true;\n const contentType = event.headers.get(\"content-type\");\n\n log?.lifecycle(\"HTTP\", \"Stream format detected:\", {\n contentType,\n parser: contentType === proto.AGUI_MEDIA_TYPE ? \"protobuf\" : \"sse\",\n });\n\n // Choose parser based on content type\n if (contentType === proto.AGUI_MEDIA_TYPE) {\n // Use protocol buffer parser\n parseProtoStream(bufferSubject).subscribe({\n next: (event) => eventSubject.next(event),\n error: (err) => eventSubject.error(err),\n complete: () => eventSubject.complete(),\n });\n } else {\n // Use SSE JSON parser for all other cases\n parseSSEStream(bufferSubject, log).subscribe({\n next: (json) => {\n try {\n const parsedEvent = EventSchemas.parse(json);\n log?.event(\"HTTP\", \"Event validated:\", parsedEvent, {\n type: parsedEvent.type,\n valid: true,\n });\n eventSubject.next(parsedEvent as BaseEvent);\n } catch (err) {\n log?.event(\"HTTP\", \"Event invalid:\", { json, error: String(err) });\n eventSubject.error(err);\n }\n },\n error: (err) => {\n if ((err as DOMException)?.name === \"AbortError\") {\n eventSubject.next({\n type: EventType.RUN_ERROR,\n message: (err as DOMException).message || \"Request aborted\",\n code: \"abort\",\n rawEvent: err,\n });\n eventSubject.complete();\n return;\n }\n return eventSubject.error(err);\n },\n complete: () => eventSubject.complete(),\n });\n }\n } else if (!parserInitialized) {\n eventSubject.error(new Error(\"No headers event received before data events\"));\n }\n },\n error: (err) => {\n bufferSubject.error(err);\n eventSubject.error(err);\n },\n complete: () => {\n bufferSubject.complete();\n },\n });\n\n return eventSubject.asObservable();\n};\n", "import { z } from \"zod\";\n\n// Protocol Events\nexport const LegacyRuntimeEventTypes = z.enum([\n \"TextMessageStart\",\n \"TextMessageContent\",\n \"TextMessageEnd\",\n \"ActionExecutionStart\",\n \"ActionExecutionArgs\",\n \"ActionExecutionEnd\",\n \"ActionExecutionResult\",\n \"AgentStateMessage\",\n \"MetaEvent\",\n \"RunStarted\",\n \"RunFinished\",\n \"RunError\",\n \"NodeStarted\",\n \"NodeFinished\",\n]);\n\nexport const LegacyRuntimeMetaEventName = z.enum([\n \"LangGraphInterruptEvent\",\n \"PredictState\",\n \"Exit\",\n]);\n\nexport const LegacyTextMessageStart = z.object({\n type: z.literal(LegacyRuntimeEventTypes.enum.TextMessageStart),\n messageId: z.string(),\n parentMessageId: z.string().optional(),\n role: z.string().optional(),\n});\n\nexport const LegacyTextMessageContent = z.object({\n type: z.literal(LegacyRuntimeEventTypes.enum.TextMessageContent),\n messageId: z.string(),\n content: z.string(),\n});\n\nexport const LegacyTextMessageEnd = z.object({\n type: z.literal(LegacyRuntimeEventTypes.enum.TextMessageEnd),\n messageId: z.string(),\n});\n\nexport const LegacyActionExecutionStart = z.object({\n type: z.literal(LegacyRuntimeEventTypes.enum.ActionExecutionStart),\n actionExecutionId: z.string(),\n actionName: z.string(),\n parentMessageId: z.string().optional(),\n});\n\nexport const LegacyActionExecutionArgs = z.object({\n type: z.literal(LegacyRuntimeEventTypes.enum.ActionExecutionArgs),\n actionExecutionId: z.string(),\n args: z.string(),\n});\n\nexport const LegacyActionExecutionEnd = z.object({\n type: z.literal(LegacyRuntimeEventTypes.enum.ActionExecutionEnd),\n actionExecutionId: z.string(),\n});\n\nexport const LegacyActionExecutionResult = z.object({\n type: z.literal(LegacyRuntimeEventTypes.enum.ActionExecutionResult),\n actionName: z.string(),\n actionExecutionId: z.string(),\n result: z.string(),\n});\n\nexport const LegacyAgentStateMessage = z.object({\n type: z.literal(LegacyRuntimeEventTypes.enum.AgentStateMessage),\n threadId: z.string(),\n agentName: z.string(),\n nodeName: z.string(),\n runId: z.string(),\n active: z.boolean(),\n role: z.string(),\n state: z.string(),\n running: z.boolean(),\n});\n\nexport const LegacyMetaEvent = z.object({\n type: z.literal(LegacyRuntimeEventTypes.enum.MetaEvent),\n name: LegacyRuntimeMetaEventName,\n value: z.any(),\n});\n\n\nexport const LegacyRunError = z.object({\n type: z.literal(LegacyRuntimeEventTypes.enum.RunError),\n message: z.string(),\n code: z.string().optional(),\n});\n\nexport const LegacyRuntimeProtocolEvent = z.discriminatedUnion(\"type\", [\n LegacyTextMessageStart,\n LegacyTextMessageContent,\n LegacyTextMessageEnd,\n LegacyActionExecutionStart,\n LegacyActionExecutionArgs,\n LegacyActionExecutionEnd,\n LegacyActionExecutionResult,\n LegacyAgentStateMessage,\n LegacyMetaEvent,\n LegacyRunError,\n]);\n\n// Protocol Event type exports\nexport type RuntimeEventTypes = z.infer<typeof LegacyRuntimeEventTypes>;\nexport type RuntimeMetaEventName = z.infer<typeof LegacyRuntimeMetaEventName>;\nexport type LegacyTextMessageStart = z.infer<typeof LegacyTextMessageStart>;\nexport type LegacyTextMessageContent = z.infer<typeof LegacyTextMessageContent>;\nexport type LegacyTextMessageEnd = z.infer<typeof LegacyTextMessageEnd>;\nexport type LegacyActionExecutionStart = z.infer<typeof LegacyActionExecutionStart>;\nexport type LegacyActionExecutionArgs = z.infer<typeof LegacyActionExecutionArgs>;\nexport type LegacyActionExecutionEnd = z.infer<typeof LegacyActionExecutionEnd>;\nexport type LegacyActionExecutionResult = z.infer<typeof LegacyActionExecutionResult>;\nexport type LegacyAgentStateMessage = z.infer<typeof LegacyAgentStateMessage>;\nexport type LegacyMetaEvent = z.infer<typeof LegacyMetaEvent>;\nexport type LegacyRuntimeProtocolEvent = z.infer<typeof LegacyRuntimeProtocolEvent>;\nexport type LegacyRunError = z.infer<typeof LegacyRunError>;\n\n// Message schemas (with kind discriminator)\nexport const LegacyTextMessageSchema = z.object({\n id: z.string(),\n role: z.string(),\n content: z.string(),\n parentMessageId: z.string().optional(),\n});\n\nexport const LegacyActionExecutionMessageSchema = z.object({\n id: z.string(),\n name: z.string(),\n arguments: z.any(),\n parentMessageId: z.string().optional(),\n});\n\nexport const LegacyResultMessageSchema = z.object({\n id: z.string(),\n result: z.any(),\n actionExecutionId: z.string(),\n actionName: z.string(),\n});\n\n// Message type exports\nexport type LegacyTextMessage = z.infer<typeof LegacyTextMessageSchema>;\nexport type LegacyActionExecutionMessage = z.infer<typeof LegacyActionExecutionMessageSchema>;\nexport type LegacyResultMessage = z.infer<typeof LegacyResultMessageSchema>;\nexport type LegacyMessage = LegacyTextMessage | LegacyActionExecutionMessage | LegacyResultMessage;\n", "import { mergeMap } from \"rxjs/operators\";\nimport jsonpatch from \"fast-json-patch\";\n\nimport {\n BaseEvent,\n EventType,\n TextMessageStartEvent,\n TextMessageContentEvent,\n TextMessageEndEvent,\n ToolCallStartEvent,\n ToolCallArgsEvent,\n ToolCallEndEvent,\n ToolCallResultEvent,\n CustomEvent,\n StateSnapshotEvent,\n StepStartedEvent,\n Message,\n StateDeltaEvent,\n MessagesSnapshotEvent,\n ToolCall,\n RunErrorEvent,\n} from \"@ag-ui/core\";\nimport { Observable } from \"rxjs\";\nimport {\n LegacyTextMessageStart,\n LegacyTextMessageContent,\n LegacyTextMessageEnd,\n LegacyActionExecutionStart,\n LegacyActionExecutionArgs,\n LegacyActionExecutionEnd,\n LegacyRuntimeEventTypes,\n LegacyRuntimeProtocolEvent,\n LegacyMetaEvent,\n LegacyAgentStateMessage,\n LegacyMessage,\n LegacyTextMessage,\n LegacyActionExecutionMessage,\n LegacyResultMessage,\n LegacyActionExecutionResult,\n LegacyRunError\n} from \"./types\";\nimport untruncateJson from \"untruncate-json\";\n\nconst flattenMessageContentToText = (content: Message[\"content\"]) => {\n if (typeof content === \"string\") {\n return content;\n }\n\n if (!Array.isArray(content)) {\n return undefined;\n }\n\n const textParts = content\n .filter((part): part is { type: \"text\"; text: string } => part.type === \"text\")\n .map((part) => part.text)\n .filter((text) => text.length > 0);\n\n if (textParts.length === 0) {\n return undefined;\n }\n\n return textParts.join(\"\\n\");\n};\n\ninterface PredictStateValue {\n state_key: string;\n tool: string;\n tool_argument: string;\n}\n\nexport const convertToLegacyEvents =\n (threadId: string, runId: string, agentName: string) =>\n (events$: Observable<BaseEvent>): Observable<LegacyRuntimeProtocolEvent> => {\n let currentState: any = {};\n let running = true;\n let active = true;\n let nodeName = \"\";\n let syncedMessages: Message[] | null = null;\n let predictState: PredictStateValue[] | null = null;\n let currentToolCalls: ToolCall[] = [];\n let toolCallNames: Record<string, string> = {};\n\n const updateCurrentState = (newState: any) => {\n // the legacy protocol will only support object state\n if (typeof newState === \"object\" && newState !== null) {\n if (\"messages\" in newState) {\n delete newState.messages;\n }\n currentState = newState;\n }\n };\n\n return events$.pipe(\n mergeMap((event) => {\n switch (event.type) {\n case EventType.TEXT_MESSAGE_START: {\n const startEvent = event as TextMessageStartEvent;\n return [\n {\n type: LegacyRuntimeEventTypes.enum.TextMessageStart,\n messageId: startEvent.messageId,\n role: startEvent.role,\n } as LegacyTextMessageStart,\n ];\n }\n case EventType.TEXT_MESSAGE_CONTENT: {\n const contentEvent = event as TextMessageContentEvent;\n return [\n {\n type: LegacyRuntimeEventTypes.enum.TextMessageContent,\n messageId: contentEvent.messageId,\n content: contentEvent.delta,\n } as LegacyTextMessageContent,\n ];\n }\n case EventType.TEXT_MESSAGE_END: {\n const endEvent = event as TextMessageEndEvent;\n return [\n {\n type: LegacyRuntimeEventTypes.enum.TextMessageEnd,\n messageId: endEvent.messageId,\n } as LegacyTextMessageEnd,\n ];\n }\n case EventType.TOOL_CALL_START: {\n const startEvent = event as ToolCallStartEvent;\n\n currentToolCalls.push({\n id: startEvent.toolCallId,\n type: \"function\",\n function: {\n name: startEvent.toolCallName,\n arguments: \"\",\n },\n });\n\n active = true;\n toolCallNames[startEvent.toolCallId] = startEvent.toolCallName;\n\n return [\n {\n type: LegacyRuntimeEventTypes.enum.ActionExecutionStart,\n actionExecutionId: startEvent.toolCallId,\n actionName: startEvent.toolCallName,\n parentMessageId: startEvent.parentMessageId,\n } as LegacyActionExecutionStart,\n ];\n }\n case EventType.TOOL_CALL_ARGS: {\n const argsEvent = event as ToolCallArgsEvent;\n\n // Find the tool call by ID instead of using the last one\n const currentToolCall = currentToolCalls.find((tc) => tc.id === argsEvent.toolCallId);\n if (!currentToolCall) {\n console.warn(`TOOL_CALL_ARGS: No tool call found with ID '${argsEvent.toolCallId}'`);\n return [];\n }\n\n currentToolCall.function.arguments += argsEvent.delta;\n let didUpdateState = false;\n\n if (predictState) {\n let currentPredictState = predictState.find(\n (s) => s.tool == currentToolCall.function.name,\n );\n\n if (currentPredictState) {\n try {\n const currentArgs = JSON.parse(\n untruncateJson(currentToolCall.function.arguments),\n );\n if (\n currentPredictState.tool_argument &&\n currentPredictState.tool_argument in currentArgs\n ) {\n updateCurrentState({\n ...currentState,\n [currentPredictState.state_key]:\n currentArgs[currentPredictState.tool_argument],\n });\n didUpdateState = true;\n } else if (!currentPredictState.tool_argument) {\n updateCurrentState({\n ...currentState,\n [currentPredictState.state_key]: currentArgs,\n });\n didUpdateState = true;\n }\n } catch (e) {}\n }\n }\n\n return [\n {\n type: LegacyRuntimeEventTypes.enum.ActionExecutionArgs,\n actionExecutionId: argsEvent.toolCallId,\n args: argsEvent.delta,\n } as LegacyActionExecutionArgs,\n ...(didUpdateState\n ? [\n {\n type: LegacyRuntimeEventTypes.enum.AgentStateMessage,\n threadId,\n agentName,\n nodeName,\n runId,\n running,\n role: \"assistant\",\n state: JSON.stringify(currentState),\n active,\n },\n ]\n : []),\n ];\n }\n case EventType.TOOL_CALL_END: {\n const endEvent = event as ToolCallEndEvent;\n return [\n {\n type: LegacyRuntimeEventTypes.enum.ActionExecutionEnd,\n actionExecutionId: endEvent.toolCallId,\n } as LegacyActionExecutionEnd,\n ];\n }\n case EventType.TOOL_CALL_RESULT: {\n const resultEvent = event as ToolCallResultEvent;\n return [\n {\n type: LegacyRuntimeEventTypes.enum.ActionExecutionResult,\n actionExecutionId: resultEvent.toolCallId,\n result: resultEvent.content,\n actionName: toolCallNames[resultEvent.toolCallId] || \"unknown\",\n } as LegacyActionExecutionResult,\n ];\n }\n case EventType.RAW: {\n // The legacy protocol doesn't support raw events\n return [];\n }\n case EventType.CUSTOM: {\n const customEvent = event as CustomEvent;\n switch (customEvent.name) {\n case \"Exit\":\n running = false;\n break;\n case \"PredictState\":\n predictState = customEvent.value as PredictStateValue[];\n break;\n }\n\n return [\n {\n type: LegacyRuntimeEventTypes.enum.MetaEvent,\n name: customEvent.name,\n value: customEvent.value,\n } as LegacyMetaEvent,\n ];\n }\n case EventType.STATE_SNAPSHOT: {\n const stateEvent = event as StateSnapshotEvent;\n updateCurrentState(stateEvent.snapshot);\n\n return [\n {\n type: LegacyRuntimeEventTypes.enum.AgentStateMessage,\n threadId,\n agentName,\n nodeName,\n runId,\n running,\n role: \"assistant\",\n state: JSON.stringify(currentState),\n active,\n } as LegacyAgentStateMessage,\n ];\n }\n case EventType.STATE_DELTA: {\n const deltaEvent = event as StateDeltaEvent;\n const result = jsonpatch.applyPatch(currentState, deltaEvent.delta, true, false);\n if (!result) {\n return [];\n }\n updateCurrentState(result.newDocument);\n\n return [\n {\n type: LegacyRuntimeEventTypes.enum.AgentStateMessage,\n threadId,\n agentName,\n nodeName,\n runId,\n running,\n role: \"assistant\",\n state: JSON.stringify(currentState),\n active,\n } as LegacyAgentStateMessage,\n ];\n }\n case EventType.MESSAGES_SNAPSHOT: {\n const messagesSnapshot = event as MessagesSnapshotEvent;\n syncedMessages = messagesSnapshot.messages;\n return [\n {\n type: LegacyRuntimeEventTypes.enum.AgentStateMessage,\n threadId,\n agentName,\n nodeName,\n runId,\n running,\n role: \"assistant\",\n state: JSON.stringify({\n ...currentState,\n ...(syncedMessages ? { messages: syncedMessages } : {}),\n }),\n active: true,\n } as LegacyAgentStateMessage,\n ];\n }\n case EventType.RUN_STARTED: {\n // There is nothing to do in the legacy protocol\n return [];\n }\n case EventType.RUN_FINISHED: {\n if (syncedMessages) {\n currentState.messages = syncedMessages;\n }\n\n // Only do an update if state is not empty\n if (Object.keys(currentState).length === 0) {\n return [];\n }\n\n return [\n {\n type: LegacyRuntimeEventTypes.enum.AgentStateMessage,\n threadId,\n agentName,\n nodeName,\n runId,\n running,\n role: \"assistant\",\n state: JSON.stringify({\n ...currentState,\n ...(syncedMessages\n ? {\n messages: convertMessagesToLegacyFormat(syncedMessages),\n }\n : {}),\n }),\n active: false,\n } as LegacyAgentStateMessage,\n ];\n }\n case EventType.RUN_ERROR: {\n const errorEvent = event as RunErrorEvent;\n return [\n {\n type: LegacyRuntimeEventTypes.enum.RunError,\n message: errorEvent.message,\n code: errorEvent.code,\n } as LegacyRunError,\n ];\n }\n case EventType.STEP_STARTED: {\n const stepStarted = event as StepStartedEvent;\n nodeName = stepStarted.stepName;\n\n currentToolCalls = [];\n predictState = null;\n\n return [\n {\n type: LegacyRuntimeEventTypes.enum.AgentStateMessage,\n threadId,\n agentName,\n nodeName,\n runId,\n running,\n role: \"assistant\",\n state: JSON.stringify(currentState),\n active: true,\n } as LegacyAgentStateMessage,\n ];\n }\n case EventType.STEP_FINISHED: {\n currentToolCalls = [];\n predictState = null;\n\n return [\n {\n type: LegacyRuntimeEventTypes.enum.AgentStateMessage,\n threadId,\n agentName,\n nodeName,\n runId,\n running,\n role: \"assistant\",\n state: JSON.stringify(currentState),\n active: false,\n } as LegacyAgentStateMessage,\n ];\n }\n default: {\n return [];\n }\n }\n }),\n );\n };\n\nexport function convertMessagesToLegacyFormat(messages: Message[]): LegacyMessage[] {\n const result: LegacyMessage[] = [];\n\n for (const message of messages) {\n if (message.role === \"assistant\" || message.role === \"user\" || message.role === \"system\") {\n const textContent = flattenMessageContentToText(message.content);\n if (textContent) {\n const textMessage: LegacyTextMessage = {\n id: message.id,\n role: message.role,\n content: textContent,\n };\n result.push(textMessage);\n }\n if (message.role === \"assistant\" && message.toolCalls && message.toolCalls.length > 0) {\n for (const toolCall of message.toolCalls) {\n const actionExecutionMessage: LegacyActionExecutionMessage = {\n id: toolCall.id,\n name: toolCall.function.name,\n arguments: JSON.parse(toolCall.function.arguments),\n parentMessageId: message.id,\n };\n result.push(actionExecutionMessage);\n }\n }\n } else if (message.role === \"tool\") {\n let actionName = \"unknown\";\n for (const m of messages) {\n if (m.role === \"assistant\" && m.toolCalls?.length) {\n for (const toolCall of m.toolCalls) {\n if (toolCall.id === message.toolCallId) {\n actionName = toolCall.function.name;\n break;\n }\n }\n }\n }\n const toolMessage: LegacyResultMessage = {\n id: message.id,\n result: message.content,\n actionExecutionId: message.toolCallId,\n actionName,\n };\n result.push(toolMessage);\n }\n }\n\n return result;\n}\n", "import { mergeMap, Observable, finalize } from \"rxjs\";\nimport {\n BaseEvent,\n TextMessageChunkEvent,\n TextMessageContentEvent,\n TextMessageEndEvent,\n TextMessageStartEvent,\n ToolCallArgsEvent,\n ToolCallChunkEvent,\n ToolCallEndEvent,\n ToolCallStartEvent,\n ReasoningMessageChunkEvent,\n ReasoningMessageContentEvent,\n ReasoningMessageEndEvent,\n ReasoningMessageStartEvent,\n} from \"@ag-ui/core\";\nimport { EventType } from \"@ag-ui/core\";\nimport { type DebugLoggerInput, resolveDebugLogger } from \"@/debug-logger\";\n\ninterface TextMessageFields {\n messageId: string;\n name?: string;\n}\n\ninterface ToolCallFields {\n toolCallId: string;\n toolCallName: string;\n parentMessageId?: string;\n}\n\ninterface ReasoningMessageFields {\n messageId: string;\n}\n\nexport const transformChunks =\n (debugLogger?: DebugLoggerInput) =>\n (events$: Observable<BaseEvent>): Observable<BaseEvent> => {\n const log = resolveDebugLogger(debugLogger);\n let textMessageFields: TextMessageFields | undefined;\n let toolCallFields: ToolCallFields | undefined;\n let reasoningMessageFields: ReasoningMessageFields | undefined;\n let mode: \"text\" | \"tool\" | \"reasoning\" | undefined;\n\n const closeTextMessage = () => {\n if (!textMessageFields || mode !== \"text\") {\n throw new Error(\"No text message to close\");\n }\n const event = {\n type: EventType.TEXT_MESSAGE_END,\n messageId: textMessageFields.messageId,\n } as TextMessageEndEvent;\n mode = undefined;\n textMessageFields = undefined;\n\n log?.event(\"TRANSFORM\", \"TEXT_MESSAGE_END\", event, {\n messageId: event.messageId,\n });\n\n return event;\n };\n\n const closeToolCall = () => {\n if (!toolCallFields || mode !== \"tool\") {\n throw new Error(\"No tool call to close\");\n }\n const event = {\n type: EventType.TOOL_CALL_END,\n toolCallId: toolCallFields.toolCallId,\n } as ToolCallEndEvent;\n mode = undefined;\n toolCallFields = undefined;\n\n log?.event(\"TRANSFORM\", \"TOOL_CALL_END\", event, {\n toolCallId: event.toolCallId,\n });\n\n return event;\n };\n\n const closeReasoningMessage = () => {\n if (!reasoningMessageFields || mode !== \"reasoning\") {\n throw new Error(\"No reasoning message to close\");\n }\n const event = {\n type: EventType.REASONING_MESSAGE_END,\n messageId: reasoningMessageFields.messageId,\n } as ReasoningMessageEndEvent;\n mode = undefined;\n reasoningMessageFields = undefined;\n\n log?.event(\"TRANSFORM\", \"REASONING_MESSAGE_END\", event, {\n messageId: event.messageId,\n });\n\n return event;\n };\n\n const closePendingEvent = () => {\n if (mode === \"text\") {\n return [closeTextMessage()];\n }\n if (mode === \"tool\") {\n return [closeToolCall()];\n }\n if (mode === \"reasoning\") {\n return [closeReasoningMessage()];\n }\n return [];\n };\n\n return events$.pipe(\n mergeMap((event) => {\n switch (event.type) {\n case EventType.TEXT_MESSAGE_START:\n case EventType.TEXT_MESSAGE_CONTENT:\n case EventType.TEXT_MESSAGE_END:\n case EventType.TOOL_CALL_START:\n case EventType.TOOL_CALL_ARGS:\n case EventType.TOOL_CALL_END:\n case EventType.TOOL_CALL_RESULT:\n case EventType.STATE_SNAPSHOT:\n case EventType.STATE_DELTA:\n case EventType.MESSAGES_SNAPSHOT:\n case EventType.CUSTOM:\n case EventType.RUN_STARTED:\n case EventType.RUN_FINISHED:\n case EventType.RUN_ERROR:\n case EventType.STEP_STARTED:\n case EventType.STEP_FINISHED:\n case EventType.THINKING_START:\n case EventType.THINKING_END:\n case EventType.THINKING_TEXT_MESSAGE_START:\n case EventType.THINKING_TEXT_MESSAGE_CONTENT:\n case EventType.THINKING_TEXT_MESSAGE_END:\n case EventType.REASONING_START:\n case EventType.REASONING_MESSAGE_START:\n case EventType.REASONING_MESSAGE_CONTENT:\n case EventType.REASONING_MESSAGE_END:\n case EventType.REASONING_END:\n return [...closePendingEvent(), event];\n case EventType.RAW:\n case EventType.ACTIVITY_SNAPSHOT:\n case EventType.ACTIVITY_DELTA:\n case EventType.REASONING_ENCRYPTED_VALUE:\n return [event];\n case EventType.TEXT_MESSAGE_CHUNK:\n const messageChunkEvent = event as TextMessageChunkEvent;\n const textMessageResult = [];\n if (\n // we are not in a text message\n mode !== \"text\" ||\n // or the message id is different\n (messageChunkEvent.messageId !== undefined &&\n messageChunkEvent.messageId !== textMessageFields?.messageId)\n ) {\n // close the current message if any\n textMessageResult.push(...closePendingEvent());\n }\n\n // we are not in a text message, start a new one\n if (mode !== \"text\") {\n if (messageChunkEvent.messageId === undefined) {\n throw new Error(\"First TEXT_MESSAGE_CHUNK must have a messageId\");\n }\n\n textMessageFields = {\n messageId: messageChunkEvent.messageId,\n name: messageChunkEvent.name,\n };\n mode = \"text\";\n\n const textMessageStartEvent = {\n type: EventType.TEXT_MESSAGE_START,\n messageId: messageChunkEvent.messageId,\n role: messageChunkEvent.role || \"assistant\",\n ...(messageChunkEvent.name !== undefined && { name: messageChunkEvent.name }),\n } as TextMessageStartEvent;\n\n textMessageResult.push(textMessageStartEvent);\n\n log?.event(\"TRANSFORM\", \"TEXT_MESSAGE_START\", textMessageStartEvent, {\n messageId: messageChunkEvent.messageId,\n });\n }\n\n if (messageChunkEvent.delta !== undefined) {\n const textMessageContentEvent = {\n type: EventType.TEXT_MESSAGE_CONTENT,\n messageId: textMessageFields!.messageId,\n delta: messageChunkEvent.delta,\n } as TextMessageContentEvent;\n\n textMessageResult.push(textMessageContentEvent);\n\n log?.event(\"TRANSFORM\", \"TEXT_MESSAGE_CONTENT\", textMessageContentEvent, {\n messageId: textMessageFields!.messageId,\n });\n }\n\n return textMessageResult;\n case EventType.TOOL_CALL_CHUNK:\n const toolCallChunkEvent = event as ToolCallChunkEvent;\n const toolMessageResult = [];\n if (\n // we are not in a text message\n mode !== \"tool\" ||\n // or the tool call id is different\n (toolCallChunkEvent.toolCallId !== undefined &&\n toolCallChunkEvent.toolCallId !== toolCallFields?.toolCallId)\n ) {\n // close the current message if any\n toolMessageResult.push(...closePendingEvent());\n }\n\n if (mode !== \"tool\") {\n if (toolCallChunkEvent.toolCallId === undefined) {\n throw new Error(\"First TOOL_CALL_CHUNK must have a toolCallId\");\n }\n if (toolCallChunkEvent.toolCallName === undefined) {\n throw new Error(\"First TOOL_CALL_CHUNK must have a toolCallName\");\n }\n toolCallFields = {\n toolCallId: toolCallChunkEvent.toolCallId,\n toolCallName: toolCallChunkEvent.toolCallName,\n parentMessageId: toolCallChunkEvent.parentMessageId,\n };\n mode = \"tool\";\n\n const toolCallStartEvent = {\n type: EventType.TOOL_CALL_START,\n toolCallId: toolCallChunkEvent.toolCallId,\n toolCallName: toolCallChunkEvent.toolCallName,\n parentMessageId: toolCallChunkEvent.parentMessageId,\n } as ToolCallStartEvent;\n\n toolMessageResult.push(toolCallStartEvent);\n\n log?.event(\"TRANSFORM\", \"TOOL_CALL_START\", toolCallStartEvent, {\n toolCallId: toolCallChunkEvent.toolCallId,\n toolCallName: toolCallChunkEvent.toolCallName,\n });\n }\n\n if (toolCallChunkEvent.delta !== undefined) {\n const toolCallArgsEvent = {\n type: EventType.TOOL_CALL_ARGS,\n toolCallId: toolCallFields!.toolCallId,\n delta: toolCallChunkEvent.delta,\n } as ToolCallArgsEvent;\n\n toolMessageResult.push(toolCallArgsEvent);\n\n log?.event(\"TRANSFORM\", \"TOOL_CALL_ARGS\", toolCallArgsEvent, {\n toolCallId: toolCallFields!.toolCallId,\n });\n }\n\n return toolMessageResult;\n case EventType.REASONING_MESSAGE_CHUNK:\n const reasoningChunkEvent = event as ReasoningMessageChunkEvent;\n const reasoningMessageResult = [];\n if (\n // we are not in a reasoning message\n mode !== \"reasoning\" ||\n // or the message id is different\n (reasoningChunkEvent.messageId &&\n reasoningChunkEvent.messageId !== reasoningMessageFields?.messageId)\n ) {\n // close the current message if any\n reasoningMessageResult.push(...closePendingEvent());\n }\n\n // we are not in a reasoning message, start a new one\n if (mode !== \"reasoning\") {\n if (reasoningChunkEvent.messageId === undefined) {\n throw new Error(\"First REASONING_MESSAGE_CHUNK must have a messageId\");\n }\n\n reasoningMessageFields = {\n messageId: reasoningChunkEvent.messageId,\n };\n mode = \"reasoning\";\n\n const reasoningMessageStartEvent = {\n type: EventType.REASONING_MESSAGE_START,\n messageId: reasoningChunkEvent.messageId,\n } as ReasoningMessageStartEvent;\n reasoningMessageResult.push(reasoningMessageStartEvent);\n\n log?.event(\"TRANSFORM\", \"REASONING_MESSAGE_START\", reasoningMessageStartEvent, {\n messageId: reasoningChunkEvent.messageId,\n });\n }\n\n if (reasoningChunkEvent.delta !== undefined) {\n const reasoningMessageContentEvent = {\n type: EventType.REASONING_MESSAGE_CONTENT,\n messageId: reasoningMessageFields!.messageId,\n delta: reasoningChunkEvent.delta,\n } as ReasoningMessageContentEvent;\n\n reasoningMessageResult.push(reasoningMessageContentEvent);\n\n log?.event(\"TRANSFORM\", \"REASONING_MESSAGE_CONTENT\", reasoningMessageContentEvent, {\n messageId: reasoningMessageFields!.messageId,\n });\n }\n\n return reasoningMessageResult;\n }\n const _exhaustiveCheck: never = event.type;\n return [];\n }),\n finalize(() => {\n // This ensures that we close any pending events when the source observable completes\n closePendingEvent();\n }),\n );\n };\n", "import type {\n Interrupt,\n ResumeEntry,\n RunFinishedEvent,\n RunFinishedOutcome,\n} from \"@ag-ui/core\";\n\nexport function getRunOutcome(event: RunFinishedEvent): RunFinishedOutcome | undefined {\n return event.outcome;\n}\n\nexport function isInterruptExpired(interrupt: Interrupt, now: Date = new Date()): boolean {\n if (interrupt.expiresAt === undefined) return false;\n return new Date(interrupt.expiresAt) <= now;\n}\n\ntype ResumeResponse =\n | { status: \"resolved\"; payload?: unknown }\n | { status: \"cancelled\" };\n\nexport function buildResumeArray(\n interrupts: Interrupt[],\n responses: Record<string, ResumeResponse>,\n): ResumeEntry[] {\n const openIds = new Set(interrupts.map((i) => i.id));\n const responseIds = new Set(Object.keys(responses));\n\n const missing = [...openIds].filter((id) => !responseIds.has(id));\n if (missing.length > 0) {\n throw new Error(`buildResumeArray: missing responses for open interrupts: ${missing.join(\", \")}`);\n }\n\n const unknown = [...responseIds].filter((id) => !openIds.has(id));\n if (unknown.length > 0) {\n throw new Error(`buildResumeArray: responses reference unknown interrupt ids: ${unknown.join(\", \")}`);\n }\n\n return interrupts.map((i) => {\n const r = responses[i.id];\n if (r.status === \"resolved\") {\n const entry: ResumeEntry = { interruptId: i.id, status: \"resolved\" };\n if (r.payload !== undefined) entry.payload = r.payload;\n return entry;\n }\n return { interruptId: i.id, status: \"cancelled\" };\n });\n}\n", "import { AbstractAgent } from \"@/agent\";\nimport { RunAgentInput, BaseEvent, Message } from \"@ag-ui/core\";\nimport { Observable, ReplaySubject } from \"rxjs\";\nimport { concatMap } from \"rxjs/operators\";\nimport { transformChunks } from \"@/chunks\";\nimport { defaultApplyEvents } from \"@/apply\";\nimport { structuredClone_ } from \"@/utils\";\n\nexport type MiddlewareFunction = (\n input: RunAgentInput,\n next: AbstractAgent,\n) => Observable<BaseEvent>;\n\nexport interface EventWithState {\n event: BaseEvent;\n messages: Message[];\n state: any;\n}\n\nexport abstract class Middleware {\n abstract run(input: RunAgentInput, next: AbstractAgent): Observable<BaseEvent>;\n\n /**\n * Runs the next agent in the chain with automatic chunk transformation.\n */\n protected runNext(input: RunAgentInput, next: AbstractAgent): Observable<BaseEvent> {\n return next.run(input).pipe(\n transformChunks(false), // Always transform chunks to full events\n );\n }\n\n /**\n * Runs the next agent and tracks state, providing current messages and state with each event.\n * The messages and state represent the state AFTER the event has been applied.\n */\n protected runNextWithState(\n input: RunAgentInput,\n next: AbstractAgent,\n ): Observable<EventWithState> {\n let currentMessages = structuredClone_(input.messages || []);\n let currentState = structuredClone_(input.state || {});\n\n // Use a ReplaySubject to feed events one by one\n const eventSubject = new ReplaySubject<BaseEvent>();\n\n // Set up defaultApplyEvents to process events\n const mutations$ = defaultApplyEvents(input, eventSubject, next, []);\n\n // Subscribe to track state changes\n mutations$.subscribe((mutation) => {\n if (mutation.messages !== undefined) {\n currentMessages = mutation.messages;\n }\n if (mutation.state !== undefined) {\n currentState = mutation.state;\n }\n });\n\n return this.runNext(input, next).pipe(\n concatMap(async (event) => {\n // Feed the event to defaultApplyEvents and wait for it to process\n eventSubject.next(event);\n\n // Give defaultApplyEvents a chance to process\n await new Promise((resolve) => setTimeout(resolve, 0));\n\n // Return event with current state\n return {\n event,\n messages: structuredClone_(currentMessages),\n state: structuredClone_(currentState),\n };\n }),\n );\n }\n}\n\n// Wrapper class to convert a function into a Middleware instance\nexport class FunctionMiddleware extends Middleware {\n constructor(private fn: MiddlewareFunction) {\n super();\n }\n\n run(input: RunAgentInput, next: AbstractAgent): Observable<BaseEvent> {\n return this.fn(input, next);\n }\n}\n", "import { Middleware } from \"./middleware\";\nimport { AbstractAgent } from \"@/agent\";\nimport {\n RunAgentInput,\n BaseEvent,\n EventType,\n ToolCallStartEvent,\n ToolCallArgsEvent,\n ToolCallEndEvent,\n ToolCallResultEvent,\n} from \"@ag-ui/core\";\nimport { Observable } from \"rxjs\";\nimport { filter } from \"rxjs/operators\";\n\ntype FilterToolCallsConfig =\n | { allowedToolCalls: string[]; disallowedToolCalls?: never }\n | { disallowedToolCalls: string[]; allowedToolCalls?: never };\n\nexport class FilterToolCallsMiddleware extends Middleware {\n private blockedToolCallIds = new Set<string>();\n private readonly allowedTools?: Set<string>;\n private readonly disallowedTools?: Set<string>;\n\n constructor(config: FilterToolCallsConfig) {\n super();\n\n // Runtime validation (belt and suspenders approach)\n if (config.allowedToolCalls && config.disallowedToolCalls) {\n throw new Error(\"Cannot specify both allowedToolCalls and disallowedToolCalls\");\n }\n\n if (!config.allowedToolCalls && !config.disallowedToolCalls) {\n throw new Error(\"Must specify either allowedToolCalls or disallowedToolCalls\");\n }\n\n if (config.allowedToolCalls) {\n this.allowedTools = new Set(config.allowedToolCalls);\n } else if (config.disallowedToolCalls) {\n this.disallowedTools = new Set(config.disallowedToolCalls);\n }\n }\n\n run(input: RunAgentInput, next: AbstractAgent): Observable<BaseEvent> {\n // Use runNext which already includes transformChunks\n return this.runNext(input, next).pipe(\n filter((event) => {\n // Handle TOOL_CALL_START events\n if (event.type === EventType.TOOL_CALL_START) {\n const toolCallStartEvent = event as ToolCallStartEvent;\n const shouldFilter = this.shouldFilterTool(toolCallStartEvent.toolCallName);\n\n if (shouldFilter) {\n // Track this tool call ID as blocked\n this.blockedToolCallIds.add(toolCallStartEvent.toolCallId);\n return false; // Filter out this event\n }\n\n return true; // Allow this event\n }\n\n // Handle TOOL_CALL_ARGS events\n if (event.type === EventType.TOOL_CALL_ARGS) {\n const toolCallArgsEvent = event as ToolCallArgsEvent;\n return !this.blockedToolCallIds.has(toolCallArgsEvent.toolCallId);\n }\n\n // Handle TOOL_CALL_END events\n if (event.type === EventType.TOOL_CALL_END) {\n const toolCallEndEvent = event as ToolCallEndEvent;\n return !this.blockedToolCallIds.has(toolCallEndEvent.toolCallId);\n }\n\n // Handle TOOL_CALL_RESULT events\n if (event.type === EventType.TOOL_CALL_RESULT) {\n const toolCallResultEvent = event as ToolCallResultEvent;\n const isBlocked = this.blockedToolCallIds.has(toolCallResultEvent.toolCallId);\n\n if (isBlocked) {\n // Clean up the blocked ID after the last event\n this.blockedToolCallIds.delete(toolCallResultEvent.toolCallId);\n return false;\n }\n\n return true;\n }\n\n // Allow all other events through\n return true;\n }),\n );\n }\n\n private shouldFilterTool(toolName: string): boolean {\n if (this.allowedTools) {\n // If using allowed list, filter out tools NOT in the list\n return !this.allowedTools.has(toolName);\n } else if (this.disallowedTools) {\n // If using disallowed list, filter out tools IN the list\n return this.disallowedTools.has(toolName);\n }\n\n return false;\n }\n}\n", "import { Middleware } from \"./middleware\";\nimport { AbstractAgent } from \"@/agent\";\nimport type { RunAgentInput, BaseEvent } from \"@ag-ui/core\";\nimport type { Observable } from \"rxjs\";\n\ntype InputMessage = RunAgentInput[\"messages\"][number];\n\nfunction sanitizeMessageContent(message: InputMessage): InputMessage {\n const rawContent = (message as { content?: unknown }).content;\n\n if (Array.isArray(rawContent)) {\n const concatenatedContent = rawContent\n .filter(\n (part): part is { type: \"text\"; text: string } =>\n typeof part === \"object\" &&\n part !== null &&\n \"type\" in part &&\n (part as { type: unknown }).type === \"text\" &&\n typeof (part as { text?: unknown }).text === \"string\",\n )\n .map((part) => part.text)\n .join(\"\");\n\n return {\n ...message,\n content: concatenatedContent,\n } as InputMessage;\n }\n\n if (typeof rawContent === \"string\") {\n return message;\n }\n\n return {\n ...message,\n content: \"\",\n } as InputMessage;\n}\n\n/**\n * Middleware placeholder that maintains compatibility with AG-UI 0.0.39 flows.\n * Currently it simply forwards all events to the next middleware/agent.\n */\nexport class BackwardCompatibility_0_0_39 extends Middleware {\n override run(input: RunAgentInput, next: AbstractAgent): Observable<BaseEvent> {\n const { parentRunId: _parentRunId, ...rest } = input;\n const sanitizedInput: RunAgentInput = {\n ...rest,\n messages: rest.messages.map(sanitizeMessageContent),\n } as RunAgentInput;\n\n return this.runNext(sanitizedInput, next);\n }\n}\n", "import { Middleware } from \"./middleware\";\nimport { AbstractAgent } from \"@/agent\";\nimport type { RunAgentInput, BaseEvent } from \"@ag-ui/core\";\nimport { EventType } from \"@ag-ui/core\";\nimport type { Observable } from \"rxjs\";\nimport { map } from \"rxjs/operators\";\nimport { randomUUID } from \"@/utils\";\n\n// Event type strings for THINKING events (deprecated)\nconst THINKING_START = \"THINKING_START\";\nconst THINKING_END = \"THINKING_END\";\nconst THINKING_TEXT_MESSAGE_START = \"THINKING_TEXT_MESSAGE_START\";\nconst THINKING_TEXT_MESSAGE_CONTENT = \"THINKING_TEXT_MESSAGE_CONTENT\";\nconst THINKING_TEXT_MESSAGE_END = \"THINKING_TEXT_MESSAGE_END\";\n\n/**\n * Middleware that maps deprecated THINKING events to the new REASONING events.\n *\n * This ensures backward compatibility for agents that still emit legacy THINKING\n * events (THINKING_START, THINKING_END, THINKING_TEXT_MESSAGE_START, etc.)\n * by transforming them into the corresponding REASONING events.\n *\n * Event mapping:\n * - THINKING_START → REASONING_START\n * - THINKING_TEXT_MESSAGE_START → REASONING_MESSAGE_START\n * - THINKING_TEXT_MESSAGE_CONTENT → REASONING_MESSAGE_CONTENT\n * - THINKING_TEXT_MESSAGE_END → REASONING_MESSAGE_END\n * - THINKING_END → REASONING_END\n *\n */\nexport class BackwardCompatibility_0_0_45 extends Middleware {\n private currentReasoningId: string | null = null;\n private currentMessageId: string | null = null;\n\n private warnAboutTransformation(from: string, to: string) {\n if (\n typeof process !== \"undefined\" &&\n typeof process.env !== \"undefined\" &&\n process.env.SUPPRESS_TRANSFORMATION_WARNINGS\n )\n return;\n console.warn(\n `AG-UI is converting ${from} to ${to}. To remove this warning, upgrade your AG-UI integration package (e.g. @ag-ui/langgraph). To surpress it, set SUPPRESS_TRANSFORMATION_WARNINGS=true in your .env file.`,\n );\n }\n override run(input: RunAgentInput, next: AbstractAgent): Observable<BaseEvent> {\n // Reset state for each run\n this.currentReasoningId = null;\n this.currentMessageId = null;\n\n return this.runNext(input, next).pipe(map((event) => this.transformEvent(event)));\n }\n\n private transformEvent(event: BaseEvent): BaseEvent {\n const eventType = event.type as string;\n\n switch (eventType) {\n case THINKING_START: {\n this.currentReasoningId = randomUUID();\n const { title, ...rest } = event as BaseEvent & { title?: string };\n this.warnAboutTransformation(THINKING_START, EventType.REASONING_START);\n return {\n ...rest,\n type: EventType.REASONING_START,\n messageId: this.currentReasoningId,\n };\n }\n\n case THINKING_TEXT_MESSAGE_START: {\n this.currentMessageId = randomUUID();\n this.warnAboutTransformation(\n THINKING_TEXT_MESSAGE_START,\n EventType.REASONING_MESSAGE_START,\n );\n return {\n ...event,\n type: EventType.REASONING_MESSAGE_START,\n messageId: this.currentMessageId,\n role: \"assistant\" as const,\n };\n }\n\n case THINKING_TEXT_MESSAGE_CONTENT: {\n const { delta, ...rest } = event as BaseEvent & { delta: string };\n this.warnAboutTransformation(\n THINKING_TEXT_MESSAGE_CONTENT,\n EventType.REASONING_MESSAGE_CONTENT,\n );\n return {\n ...rest,\n type: EventType.REASONING_MESSAGE_CONTENT,\n messageId: this.currentMessageId ?? randomUUID(),\n delta,\n };\n }\n\n case THINKING_TEXT_MESSAGE_END: {\n const messageId = this.currentMessageId ?? randomUUID();\n this.warnAboutTransformation(THINKING_TEXT_MESSAGE_END, EventType.REASONING_MESSAGE_END);\n return {\n ...event,\n type: EventType.REASONING_MESSAGE_END,\n messageId,\n };\n }\n\n case THINKING_END: {\n const reasoningId = this.currentReasoningId ?? randomUUID();\n this.warnAboutTransformation(THINKING_END, EventType.REASONING_END);\n return {\n ...event,\n type: EventType.REASONING_END,\n messageId: reasoningId,\n };\n }\n\n default:\n return event;\n }\n }\n}\n", "import { Middleware } from \"./middleware\";\nimport { AbstractAgent } from \"@/agent\";\nimport type { RunAgentInput, BaseEvent } from \"@ag-ui/core\";\nimport type { Observable } from \"rxjs\";\n\ntype InputMessage = RunAgentInput[\"messages\"][number];\n\ninterface LegacyBinaryContent {\n type: \"binary\";\n mimeType: string;\n id?: string;\n url?: string;\n data?: string;\n filename?: string;\n}\n\ninterface NewContentPart {\n type: \"image\" | \"audio\" | \"video\" | \"document\";\n source: { type: \"data\"; value: string; mimeType: string } | { type: \"url\"; value: string; mimeType: string };\n metadata?: unknown;\n}\n\nfunction mimeTypeToContentType(mimeType: string): \"image\" | \"audio\" | \"video\" | \"document\" {\n if (mimeType.startsWith(\"image/\")) return \"image\";\n if (mimeType.startsWith(\"audio/\")) return \"audio\";\n if (mimeType.startsWith(\"video/\")) return \"video\";\n return \"document\";\n}\n\nfunction isLegacyBinaryContent(part: unknown): part is LegacyBinaryContent {\n return (\n typeof part === \"object\" &&\n part !== null &&\n \"type\" in part &&\n (part as { type: unknown }).type === \"binary\" &&\n \"mimeType\" in part &&\n typeof (part as { mimeType: unknown }).mimeType === \"string\"\n );\n}\n\nfunction convertBinaryToNewFormat(binary: LegacyBinaryContent): NewContentPart | LegacyBinaryContent {\n const contentType = mimeTypeToContentType(binary.mimeType);\n\n if (binary.data) {\n return {\n type: contentType,\n source: { type: \"data\", value: binary.data, mimeType: binary.mimeType },\n ...(binary.filename ? { metadata: { filename: binary.filename } } : {}),\n };\n }\n\n if (binary.url) {\n return {\n type: contentType,\n source: { type: \"url\", value: binary.url, mimeType: binary.mimeType },\n ...(binary.filename ? { metadata: { filename: binary.filename } } : {}),\n };\n }\n\n // If only `id` is present, we can't map to the new source format.\n // Return as-is — the schema still accepts BinaryInputContent.\n return binary;\n}\n\nfunction upgradeMessageContent(message: InputMessage): InputMessage {\n const rawContent = (message as { content?: unknown }).content;\n\n if (!Array.isArray(rawContent)) {\n return message;\n }\n\n const upgraded = rawContent.map((part: unknown) => {\n if (isLegacyBinaryContent(part)) {\n return convertBinaryToNewFormat(part);\n }\n return part;\n });\n\n return { ...message, content: upgraded } as InputMessage;\n}\n\n/**\n * Middleware that converts legacy BinaryInputContent entries (type: \"binary\")\n * to the new dedicated content types (image, audio, video, document) with\n * source discriminator.\n *\n * Old format (v0.0.47 and below):\n * { type: \"binary\", mimeType: \"image/png\", data: \"base64...\" }\n *\n * New format (v0.0.48+):\n * { type: \"image\", source: { type: \"data\", value: \"base64...\", mimeType: \"image/png\" } }\n *\n * Plain string content and TextInputContent pass through unchanged.\n * BinaryInputContent entries that only have `id` (no data/url) are left as-is\n * since they can't be mapped to the new source format.\n */\nexport class BackwardCompatibility_0_0_47 extends Middleware {\n override run(input: RunAgentInput, next: AbstractAgent): Observable<BaseEvent> {\n const upgradedInput: RunAgentInput = {\n ...input,\n messages: input.messages.map(upgradeMessageContent),\n };\n\n return this.runNext(upgradedInput, next);\n }\n}\n", "", "import { defaultApplyEvents } from \"@/apply/default\";\nimport {\n Message,\n State,\n RunAgentInput,\n BaseEvent,\n ToolCall,\n AssistantMessage,\n AgentCapabilities,\n Interrupt,\n} from \"@ag-ui/core\";\n\nimport {\n AgentConfig,\n AgentDebugConfig,\n RunAgentParameters,\n ResolvedAgentDebugConfig,\n resolveAgentDebugConfig,\n} from \"./types\";\nimport { DebugLogger, createDebugLogger } from \"@/debug-logger\";\nimport { v4 as uuidv4 } from \"uuid\";\nimport { structuredClone_ } from \"@/utils\";\nimport { compareVersions } from \"compare-versions\";\nimport { catchError, map, tap } from \"rxjs/operators\";\nimport { finalize } from \"rxjs/operators\";\nimport { takeUntil } from \"rxjs/operators\";\nimport { pipe, Observable, from, of, EMPTY, Subject, defer } from \"rxjs\";\nimport { verifyEvents } from \"@/verify\";\nimport { convertToLegacyEvents } from \"@/legacy/convert\";\nimport { LegacyRuntimeProtocolEvent } from \"@/legacy/types\";\nimport { lastValueFrom } from \"rxjs\";\nimport { transformChunks } from \"@/chunks\";\nimport { AgentStateMutation, AgentSubscriber, runSubscribersWithMutation } from \"./subscriber\";\nimport { AGUIConnectNotImplementedError, AGUIError } from \"@ag-ui/core\";\nimport { isInterruptExpired } from \"@/interrupts\";\nimport {\n Middleware,\n MiddlewareFunction,\n FunctionMiddleware,\n BackwardCompatibility_0_0_39,\n BackwardCompatibility_0_0_45,\n BackwardCompatibility_0_0_47,\n} from \"@/middleware\";\nimport packageJson from \"../../package.json\";\n\nexport interface RunAgentResult {\n result: any;\n newMessages: Message[];\n}\n\nexport abstract class AbstractAgent {\n public agentId?: string;\n public description: string;\n public threadId: string;\n public messages: Message[];\n public state: State;\n private _debug: ResolvedAgentDebugConfig;\n private _debugLogger: DebugLogger | undefined;\n public subscribers: AgentSubscriber[] = [];\n public isRunning: boolean = false;\n /** Interrupts emitted by the most recent run that have not yet been resolved.\n * Populated when RUN_FINISHED arrives with outcome.type === \"interrupt\".\n * Cleared when a subsequent run completes successfully. */\n public pendingInterrupts: Interrupt[] = [];\n private middlewares: Middleware[] = [];\n // Emits to immediately detach from the active run (stop processing its stream)\n private activeRunDetach$?: Subject<void>;\n private activeRunCompletionPromise?: Promise<void>;\n\n get maxVersion() {\n return packageJson.version;\n }\n\n get debug(): ResolvedAgentDebugConfig {\n return this._debug;\n }\n\n set debug(value: AgentDebugConfig | ResolvedAgentDebugConfig) {\n this._debug = resolveAgentDebugConfig(value as AgentDebugConfig);\n this._debugLogger = createDebugLogger(this._debug);\n }\n\n get debugLogger(): DebugLogger | undefined {\n return this._debugLogger;\n }\n\n set debugLogger(value: DebugLogger | boolean | undefined) {\n if (typeof value === \"boolean\") {\n this._debugLogger = value\n ? createDebugLogger(resolveAgentDebugConfig(true))\n : undefined;\n } else {\n this._debugLogger = value;\n }\n }\n\n constructor({\n agentId,\n description,\n threadId,\n initialMessages,\n initialState,\n debug,\n }: AgentConfig = {}) {\n this.agentId = agentId;\n this.description = description ?? \"\";\n this.threadId = threadId ?? uuidv4();\n this.messages = structuredClone_(initialMessages ?? []);\n this.state = structuredClone_(initialState ?? {});\n this._debug = resolveAgentDebugConfig(debug);\n this._debugLogger = createDebugLogger(this._debug);\n\n if (compareVersions(this.maxVersion, \"0.0.39\") <= 0) {\n this.middlewares.unshift(new BackwardCompatibility_0_0_39());\n }\n\n // Auto-insert BackwardCompatibility_0_0_45 for backward compatibility\n // with legacy THINKING events (deprecated, will be removed in 1.0.0)\n if (compareVersions(this.maxVersion, \"0.0.45\") <= 0) {\n this.middlewares.unshift(new BackwardCompatibility_0_0_45());\n }\n\n // Auto-insert BackwardCompatibility_0_0_47 for backward compatibility\n // with legacy BinaryInputContent (maps to dedicated image/audio/video/document types)\n if (compareVersions(this.maxVersion, \"0.0.47\") <= 0) {\n this.middlewares.unshift(new BackwardCompatibility_0_0_47());\n }\n\n }\n\n public subscribe(subscriber: AgentSubscriber) {\n this.subscribers.push(subscriber);\n return {\n unsubscribe: () => {\n this.subscribers = this.subscribers.filter((s) => s !== subscriber);\n },\n };\n }\n\n abstract run(input: RunAgentInput): Observable<BaseEvent>;\n\n /**\n * Returns the agent's current capabilities.\n * Optional — subclasses implement this to advertise what they support.\n */\n getCapabilities?(): Promise<AgentCapabilities>;\n\n public use(...middlewares: (Middleware | MiddlewareFunction)[]): this {\n const normalizedMiddlewares = middlewares.map((middleware) =>\n typeof middleware === \"function\" ? new FunctionMiddleware(middleware) : middleware,\n );\n this.middlewares.push(...normalizedMiddlewares);\n return this;\n }\n\n public async runAgent(\n parameters?: RunAgentParameters,\n subscriber?: AgentSubscriber,\n ): Promise<RunAgentResult> {\n try {\n this.isRunning = true;\n this.agentId = this.agentId ?? uuidv4();\n const input = this.prepareRunAgentInput(parameters);\n\n this.debugLogger?.lifecycle(\"LIFECYCLE\", \"Run started:\", {\n agentId: this.agentId,\n threadId: this.threadId,\n });\n\n let result: any = undefined;\n const currentMessageIds = new Set(this.messages.map((message) => message.id));\n\n const subscribers: AgentSubscriber[] = [\n {\n onRunFinishedEvent: (params) => {\n if (params.outcome === \"success\") {\n result = params.result;\n }\n },\n },\n ...this.subscribers,\n subscriber ?? {},\n ];\n\n await this.onInitialize(input, subscribers);\n\n // Per-run detachment signal + completion promise\n this.activeRunDetach$ = new Subject<void>();\n let resolveActiveRunCompletion: (() => void) | undefined;\n this.activeRunCompletionPromise = new Promise<void>((resolve) => {\n resolveActiveRunCompletion = resolve;\n });\n\n const pipeline = pipe(\n () => {\n // Build middleware chain using reduceRight so middlewares can intercept runs.\n if (this.middlewares.length === 0) {\n return this.run(input);\n }\n\n const chainedAgent = this.middlewares.reduceRight(\n (nextAgent: AbstractAgent, middleware) =>\n ({\n run: (i: RunAgentInput) => middleware.run(i, nextAgent),\n get messages() {\n return nextAgent.messages;\n },\n get state() {\n return nextAgent.state;\n },\n }) as AbstractAgent,\n this, // Original agent is the final 'next'\n );\n\n return chainedAgent.run(input);\n },\n transformChunks(this.debugLogger),\n verifyEvents(this.debugLogger),\n // Stop processing immediately when this run is detached\n (source$) => source$.pipe(takeUntil(this.activeRunDetach$!)),\n (source$) => this.apply(input, source$, subscribers),\n (source$) => this.processApplyEvents(input, source$, subscribers),\n catchError((error) => {\n this.debugLogger?.lifecycle(\"LIFECYCLE\", \"Run errored:\", {\n agentId: this.agentId,\n error: error instanceof Error ? error.message : String(error),\n });\n this.isRunning = false;\n return this.onError(input, error, subscribers);\n }),\n finalize(() => {\n this.debugLogger?.lifecycle(\"LIFECYCLE\", \"Run finished:\", {\n agentId: this.agentId,\n threadId: this.threadId,\n });\n this.isRunning = false;\n void this.onFinalize(input, subscribers);\n resolveActiveRunCompletion?.();\n resolveActiveRunCompletion = undefined;\n this.activeRunCompletionPromise = undefined;\n this.activeRunDetach$ = undefined;\n }),\n );\n\n await lastValueFrom(pipeline(of(null)));\n const newMessages = structuredClone_(this.messages).filter(\n (message: Message) => !currentMessageIds.has(message.id),\n );\n return { result, newMessages };\n } finally {\n this.isRunning = false;\n }\n }\n\n protected connect(input: RunAgentInput): Observable<BaseEvent> {\n throw new AGUIConnectNotImplementedError();\n }\n public async connectAgent(\n parameters?: RunAgentParameters,\n subscriber?: AgentSubscriber,\n ): Promise<RunAgentResult> {\n try {\n this.isRunning = true;\n this.agentId = this.agentId ?? uuidv4();\n const input = this.prepareRunAgentInput(parameters);\n let result: any = undefined;\n const currentMessageIds = new Set(this.messages.map((message) => message.id));\n\n const subscribers: AgentSubscriber[] = [\n {\n onRunFinishedEvent: (params) => {\n if (params.outcome === \"success\") {\n result = params.result;\n }\n },\n },\n ...this.subscribers,\n subscriber ?? {},\n ];\n\n await this.onInitialize(input, subscribers);\n\n // Per-run detachment signal + completion promise\n this.activeRunDetach$ = new Subject<void>();\n let resolveActiveRunCompletion: (() => void) | undefined;\n this.activeRunCompletionPromise = new Promise<void>((resolve) => {\n resolveActiveRunCompletion = resolve;\n });\n\n const pipeline = pipe(\n () => defer(() => this.connect(input)),\n transformChunks(this.debugLogger),\n verifyEvents(this.debugLogger),\n // Stop processing immediately when this run is detached\n (source$) => source$.pipe(takeUntil(this.activeRunDetach$!)),\n (source$) => this.apply(input, source$, subscribers),\n (source$) => this.processApplyEvents(input, source$, subscribers),\n catchError((error) => {\n this.isRunning = false;\n if (!(error instanceof AGUIConnectNotImplementedError)) {\n return this.onError(input, error, subscribers);\n }\n return EMPTY;\n }),\n finalize(() => {\n this.isRunning = false;\n void this.onFinalize(input, subscribers);\n resolveActiveRunCompletion?.();\n resolveActiveRunCompletion = undefined;\n this.activeRunCompletionPromise = undefined;\n this.activeRunDetach$ = undefined;\n }),\n );\n\n // defaultValue prevents EmptyError when catchError returns EMPTY\n // (e.g. ConnectNotImplementedError path)\n await lastValueFrom(pipeline(of(null)), { defaultValue: undefined });\n const newMessages = structuredClone_(this.messages).filter(\n (message: Message) => !currentMessageIds.has(message.id),\n );\n return { result, newMessages };\n } finally {\n this.isRunning = false;\n }\n }\n\n public abortRun() {}\n\n public async detachActiveRun(): Promise<void> {\n if (!this.activeRunDetach$) {\n return;\n }\n const completion = this.activeRunCompletionPromise ?? Promise.resolve();\n this.activeRunDetach$.next();\n this.activeRunDetach$?.complete();\n await completion;\n }\n\n protected apply(\n input: RunAgentInput,\n events$: Observable<BaseEvent>,\n subscribers: AgentSubscriber[],\n ): Observable<AgentStateMutation> {\n return defaultApplyEvents(input, events$, this, subscribers, this.debugLogger);\n }\n\n protected processApplyEvents(\n input: RunAgentInput,\n events$: Observable<AgentStateMutation>,\n subscribers: AgentSubscriber[],\n ): Observable<AgentStateMutation> {\n return events$.pipe(\n tap((event) => {\n if (event.messages) {\n this.messages = event.messages;\n subscribers.forEach((subscriber) => {\n subscriber.onMessagesChanged?.({\n messages: this.messages,\n state: this.state,\n agent: this,\n input,\n });\n });\n }\n if (event.state) {\n this.state = event.state;\n subscribers.forEach((subscriber) => {\n subscriber.onStateChanged?.({\n state: this.state,\n messages: this.messages,\n agent: this,\n input,\n });\n });\n }\n }),\n );\n }\n\n protected prepareRunAgentInput(parameters?: RunAgentParameters): RunAgentInput {\n const clonedMessages = structuredClone_(this.messages) as Message[];\n const messagesWithoutActivity = clonedMessages.filter((message) => message.role !== \"activity\");\n\n return {\n threadId: this.threadId,\n runId: parameters?.runId || uuidv4(),\n tools: structuredClone_(parameters?.tools ?? []),\n context: structuredClone_(parameters?.context ?? []),\n forwardedProps: structuredClone_(parameters?.forwardedProps ?? {}),\n state: structuredClone_(this.state),\n messages: messagesWithoutActivity,\n ...(parameters?.resume !== undefined ? { resume: structuredClone_(parameters.resume) } : {}),\n };\n }\n\n protected async onInitialize(input: RunAgentInput, subscribers: AgentSubscriber[]) {\n if (this.pendingInterrupts.length > 0) {\n const resumeIds = new Set((input.resume ?? []).map((r) => r.interruptId));\n const uncovered = this.pendingInterrupts\n .map((i) => i.id)\n .filter((id) => !resumeIds.has(id));\n if (uncovered.length > 0) {\n throw new AGUIError(\n `Thread has ${uncovered.length} pending interrupt(s) not addressed by resume: ${uncovered.join(\", \")}`,\n );\n }\n for (const i of this.pendingInterrupts) {\n if (isInterruptExpired(i)) {\n throw new AGUIError(`Interrupt ${i.id} expired at ${i.expiresAt}`);\n }\n }\n }\n\n const onRunInitializedMutation = await runSubscribersWithMutation(\n subscribers,\n this.messages,\n this.state,\n (subscriber, messages, state) =>\n subscriber.onRunInitialized?.({ messages, state, agent: this, input }),\n );\n if (\n onRunInitializedMutation.messages !== undefined ||\n onRunInitializedMutation.state !== undefined\n ) {\n if (onRunInitializedMutation.messages) {\n this.messages = onRunInitializedMutation.messages;\n input.messages = onRunInitializedMutation.messages;\n subscribers.forEach((subscriber) => {\n subscriber.onMessagesChanged?.({\n messages: this.messages,\n state: this.state,\n agent: this,\n input,\n });\n });\n }\n if (onRunInitializedMutation.state) {\n this.state = onRunInitializedMutation.state;\n input.state = onRunInitializedMutation.state;\n subscribers.forEach((subscriber) => {\n subscriber.onStateChanged?.({\n state: this.state,\n messages: this.messages,\n agent: this,\n input,\n });\n });\n }\n }\n }\n\n protected onError(input: RunAgentInput, error: Error, subscribers: AgentSubscriber[]) {\n return from(\n runSubscribersWithMutation(\n subscribers,\n this.messages,\n this.state,\n (subscriber, messages, state) =>\n subscriber.onRunFailed?.({ error, messages, state, agent: this, input }),\n ),\n ).pipe(\n map((onRunFailedMutation) => {\n const mutation = onRunFailedMutation as AgentStateMutation;\n if (mutation.messages !== undefined || mutation.state !== undefined) {\n if (mutation.messages !== undefined) {\n this.messages = mutation.messages;\n subscribers.forEach((subscriber) => {\n subscriber.onMessagesChanged?.({\n messages: this.messages,\n state: this.state,\n agent: this,\n input,\n });\n });\n }\n if (mutation.state !== undefined) {\n this.state = mutation.state;\n subscribers.forEach((subscriber) => {\n subscriber.onStateChanged?.({\n state: this.state,\n messages: this.messages,\n agent: this,\n input,\n });\n });\n }\n }\n\n if (mutation.stopPropagation !== true) {\n // Silently ignore abort errors (e.g. from navigation during active requests).\n // AbortController.abort(reason) can produce:\n // - A DOMException with name \"AbortError\"\n // - The reason value itself as a plain string (e.g. \"component unmounted\")\n const errStr = String(error);\n const isAbort =\n error.name === \"AbortError\" ||\n error.message === \"Fetch is aborted\" ||\n error.message === \"signal is aborted without reason\" ||\n error.message === \"component unmounted\" ||\n errStr === \"component unmounted\";\n if (!isAbort) {\n console.error(\"Agent execution failed:\", error);\n throw error;\n }\n }\n\n // Return an empty mutation instead of null to prevent EmptyError\n return {} as AgentStateMutation;\n }),\n );\n }\n\n protected async onFinalize(input: RunAgentInput, subscribers: AgentSubscriber[]) {\n const onRunFinalizedMutation = await runSubscribersWithMutation(\n subscribers,\n this.messages,\n this.state,\n (subscriber, messages, state) =>\n subscriber.onRunFinalized?.({ messages, state, agent: this, input }),\n );\n\n if (\n onRunFinalizedMutation.messages !== undefined ||\n onRunFinalizedMutation.state !== undefined\n ) {\n if (onRunFinalizedMutation.messages !== undefined) {\n this.messages = onRunFinalizedMutation.messages;\n subscribers.forEach((subscriber) => {\n subscriber.onMessagesChanged?.({\n messages: this.messages,\n state: this.state,\n agent: this,\n input,\n });\n });\n }\n if (onRunFinalizedMutation.state !== undefined) {\n this.state = onRunFinalizedMutation.state;\n subscribers.forEach((subscriber) => {\n subscriber.onStateChanged?.({\n state: this.state,\n messages: this.messages,\n agent: this,\n input,\n });\n });\n }\n }\n }\n\n public clone() {\n const cloned = Object.create(Object.getPrototypeOf(this));\n\n cloned.agentId = this.agentId;\n cloned.description = this.description;\n cloned.threadId = this.threadId;\n cloned.messages = structuredClone_(this.messages);\n cloned.state = structuredClone_(this.state);\n cloned._debug = this._debug;\n cloned._debugLogger = this._debugLogger;\n cloned.isRunning = this.isRunning;\n cloned.subscribers = [...this.subscribers];\n cloned.middlewares = [...this.middlewares];\n cloned.pendingInterrupts = structuredClone_(this.pendingInterrupts);\n\n return cloned;\n }\n\n public addMessage(message: Message) {\n // Add message to the messages array\n this.messages.push(message);\n\n // Notify subscribers sequentially in the background\n (async () => {\n // Fire onNewMessage sequentially\n for (const subscriber of this.subscribers) {\n await subscriber.onNewMessage?.({\n message,\n messages: this.messages,\n state: this.state,\n agent: this,\n });\n }\n\n // Fire onNewToolCall if the message is from assistant and contains tool calls\n if (message.role === \"assistant\" && message.toolCalls) {\n for (const toolCall of message.toolCalls) {\n for (const subscriber of this.subscribers) {\n await subscriber.onNewToolCall?.({\n toolCall,\n messages: this.messages,\n state: this.state,\n agent: this,\n });\n }\n }\n }\n\n // Fire onMessagesChanged sequentially\n for (const subscriber of this.subscribers) {\n await subscriber.onMessagesChanged?.({\n messages: this.messages,\n state: this.state,\n agent: this,\n });\n }\n })();\n }\n\n public addMessages(messages: Message[]) {\n // Add all messages to the messages array\n this.messages.push(...messages);\n\n // Notify subscribers sequentially in the background\n (async () => {\n // Fire onNewMessage and onNewToolCall for each message sequentially\n for (const message of messages) {\n // Fire onNewMessage sequentially\n for (const subscriber of this.subscribers) {\n await subscriber.onNewMessage?.({\n message,\n messages: this.messages,\n state: this.state,\n agent: this,\n });\n }\n\n // Fire onNewToolCall if the message is from assistant and contains tool calls\n if (message.role === \"assistant\" && message.toolCalls) {\n for (const toolCall of message.toolCalls) {\n for (const subscriber of this.subscribers) {\n await subscriber.onNewToolCall?.({\n toolCall,\n messages: this.messages,\n state: this.state,\n agent: this,\n });\n }\n }\n }\n }\n\n // Fire onMessagesChanged once at the end sequentially\n for (const subscriber of this.subscribers) {\n await subscriber.onMessagesChanged?.({\n messages: this.messages,\n state: this.state,\n agent: this,\n });\n }\n })();\n }\n\n public setMessages(messages: Message[]) {\n // Replace the entire messages array\n this.messages = structuredClone_(messages);\n\n // Notify subscribers sequentially in the background\n (async () => {\n // Fire onMessagesChanged sequentially\n for (const subscriber of this.subscribers) {\n await subscriber.onMessagesChanged?.({\n messages: this.messages,\n state: this.state,\n agent: this,\n });\n }\n })();\n }\n\n public setState(state: State) {\n // Replace the entire state\n this.state = structuredClone_(state);\n\n // Notify subscribers sequentially in the background\n (async () => {\n // Fire onStateChanged sequentially\n for (const subscriber of this.subscribers) {\n await subscriber.onStateChanged?.({\n messages: this.messages,\n state: this.state,\n agent: this,\n });\n }\n })();\n }\n\n public legacy_to_be_removed_runAgentBridged(\n config?: RunAgentParameters,\n ): Observable<LegacyRuntimeProtocolEvent> {\n this.agentId = this.agentId ?? uuidv4();\n const input = this.prepareRunAgentInput(config);\n\n // Build middleware chain for legacy bridge\n const runObservable = (() => {\n if (this.middlewares.length === 0) {\n return this.run(input);\n }\n\n const chainedAgent = this.middlewares.reduceRight(\n (nextAgent: AbstractAgent, middleware) =>\n ({\n run: (i: RunAgentInput) => middleware.run(i, nextAgent),\n get messages() {\n return nextAgent.messages;\n },\n get state() {\n return nextAgent.state;\n },\n }) as AbstractAgent,\n this,\n );\n\n return chainedAgent.run(input);\n })();\n\n return runObservable.pipe(\n transformChunks(this.debugLogger),\n verifyEvents(this.debugLogger),\n convertToLegacyEvents(this.threadId, input.runId, this.agentId),\n (events$: Observable<LegacyRuntimeProtocolEvent>) => {\n return events$.pipe(\n map((event) => {\n this.debugLogger?.event(\"LEGACY\", \"Event:\", event, { type: event.type });\n return event;\n }),\n );\n },\n );\n }\n}\n", "import { AbstractAgent, RunAgentResult } from \"./agent\";\nimport { runHttpRequest } from \"@/run/http-request\";\nimport { HttpAgentConfig, HttpAgentFetchFn, RunAgentParameters } from \"./types\";\nimport { RunAgentInput, BaseEvent } from \"@ag-ui/core\";\nimport { structuredClone_ } from \"@/utils\";\nimport { transformHttpEventStream } from \"@/transform/http\";\nimport { Observable } from \"rxjs\";\nimport { AgentSubscriber } from \"./subscriber\";\n\ninterface RunHttpAgentConfig extends RunAgentParameters {\n abortController?: AbortController;\n}\n\nexport class HttpAgent extends AbstractAgent {\n public url: string;\n public headers: Record<string, string>;\n public fetch: HttpAgentFetchFn;\n public abortController: AbortController = new AbortController();\n\n /**\n * Returns the fetch config for the http request.\n * Override this to customize the request.\n *\n * @returns The fetch config for the http request.\n */\n protected requestInit(input: RunAgentInput): RequestInit {\n return {\n method: \"POST\",\n headers: {\n ...this.headers,\n \"Content-Type\": \"application/json\",\n Accept: \"text/event-stream\",\n },\n body: JSON.stringify(input),\n signal: this.abortController.signal,\n };\n }\n\n public runAgent(\n parameters?: RunHttpAgentConfig,\n subscriber?: AgentSubscriber,\n ): Promise<RunAgentResult> {\n this.abortController = parameters?.abortController ?? new AbortController();\n return super.runAgent(parameters, subscriber);\n }\n\n abortRun() {\n this.abortController.abort();\n super.abortRun();\n }\n\n constructor(config: HttpAgentConfig) {\n super(config);\n this.url = config.url;\n this.headers = structuredClone_(config.headers ?? {});\n this.fetch = config.fetch ?? fetch;\n }\n\n run(input: RunAgentInput): Observable<BaseEvent> {\n const httpEvents = runHttpRequest(() => this.fetch(this.url, this.requestInit(input)));\n return transformHttpEventStream(httpEvents, this.debugLogger);\n }\n\n public clone(): HttpAgent {\n const cloned = super.clone() as HttpAgent;\n cloned.url = this.url;\n cloned.headers = structuredClone_(this.headers ?? {});\n cloned.fetch = this.fetch;\n\n const newController = new AbortController();\n const originalSignal = this.abortController.signal as AbortSignal & { reason?: unknown };\n if (originalSignal.aborted) {\n newController.abort(originalSignal.reason);\n }\n cloned.abortController = newController;\n\n return cloned;\n }\n}\n", "import {\n BaseEvent,\n EventType,\n TextMessageStartEvent,\n TextMessageContentEvent,\n TextMessageEndEvent,\n ToolCallStartEvent,\n ToolCallArgsEvent,\n ToolCallEndEvent,\n StateSnapshotEvent,\n StateDeltaEvent,\n} from \"@ag-ui/core\";\nimport jsonpatch from \"fast-json-patch\";\nimport { structuredClone_ } from \"../utils\";\n\n/**\n * Compacts streaming events by consolidating multiple deltas into single events.\n * For text messages: multiple content deltas become one concatenated delta.\n * For tool calls: multiple args deltas become one concatenated delta.\n * For state: all STATE_SNAPSHOT and STATE_DELTA events within a run are compacted\n * into a single STATE_SNAPSHOT representing the final state.\n * Events between related streaming events are reordered to keep streaming events together.\n *\n * @param events - Array of events to compact\n * @returns Compacted array of events\n */\nexport function compactEvents(events: BaseEvent[]): BaseEvent[] {\n const compacted: BaseEvent[] = [];\n const pendingTextMessages = new Map<\n string,\n {\n start?: TextMessageStartEvent;\n contents: TextMessageContentEvent[];\n end?: TextMessageEndEvent;\n otherEvents: BaseEvent[];\n }\n >();\n const pendingToolCalls = new Map<\n string,\n {\n start?: ToolCallStartEvent;\n args: ToolCallArgsEvent[];\n end?: ToolCallEndEvent;\n otherEvents: BaseEvent[];\n }\n >();\n\n // State compaction: collects state events, flushed at RUN_STARTED (pre-run/inter-run), RUN_FINISHED/RUN_ERROR (in-run), and at end (trailing)\n let stateEvents: (StateSnapshotEvent | StateDeltaEvent)[] = [];\n\n for (const event of events) {\n // Handle text message streaming events\n if (event.type === EventType.TEXT_MESSAGE_START) {\n const startEvent = event as TextMessageStartEvent;\n const messageId = startEvent.messageId;\n\n if (!pendingTextMessages.has(messageId)) {\n pendingTextMessages.set(messageId, {\n contents: [],\n otherEvents: [],\n });\n }\n\n const pending = pendingTextMessages.get(messageId)!;\n pending.start = startEvent;\n } else if (event.type === EventType.TEXT_MESSAGE_CONTENT) {\n const contentEvent = event as TextMessageContentEvent;\n const messageId = contentEvent.messageId;\n\n if (!pendingTextMessages.has(messageId)) {\n pendingTextMessages.set(messageId, {\n contents: [],\n otherEvents: [],\n });\n }\n\n const pending = pendingTextMessages.get(messageId)!;\n pending.contents.push(contentEvent);\n } else if (event.type === EventType.TEXT_MESSAGE_END) {\n const endEvent = event as TextMessageEndEvent;\n const messageId = endEvent.messageId;\n\n if (!pendingTextMessages.has(messageId)) {\n pendingTextMessages.set(messageId, {\n contents: [],\n otherEvents: [],\n });\n }\n\n const pending = pendingTextMessages.get(messageId)!;\n pending.end = endEvent;\n\n // Flush this message's events\n flushTextMessage(messageId, pending, compacted);\n pendingTextMessages.delete(messageId);\n } else if (event.type === EventType.TOOL_CALL_START) {\n const startEvent = event as ToolCallStartEvent;\n const toolCallId = startEvent.toolCallId;\n\n if (!pendingToolCalls.has(toolCallId)) {\n pendingToolCalls.set(toolCallId, {\n args: [],\n otherEvents: [],\n });\n }\n\n const pending = pendingToolCalls.get(toolCallId)!;\n pending.start = startEvent;\n } else if (event.type === EventType.TOOL_CALL_ARGS) {\n const argsEvent = event as ToolCallArgsEvent;\n const toolCallId = argsEvent.toolCallId;\n\n if (!pendingToolCalls.has(toolCallId)) {\n pendingToolCalls.set(toolCallId, {\n args: [],\n otherEvents: [],\n });\n }\n\n const pending = pendingToolCalls.get(toolCallId)!;\n pending.args.push(argsEvent);\n } else if (event.type === EventType.TOOL_CALL_END) {\n const endEvent = event as ToolCallEndEvent;\n const toolCallId = endEvent.toolCallId;\n\n if (!pendingToolCalls.has(toolCallId)) {\n pendingToolCalls.set(toolCallId, {\n args: [],\n otherEvents: [],\n });\n }\n\n const pending = pendingToolCalls.get(toolCallId)!;\n pending.end = endEvent;\n\n // Flush this tool call's events\n flushToolCall(toolCallId, pending, compacted);\n pendingToolCalls.delete(toolCallId);\n } else if (event.type === EventType.RUN_STARTED) {\n // Flush any pre-run state events before starting a new run\n flushState(stateEvents, compacted);\n stateEvents = [];\n compacted.push(event);\n } else if (\n event.type === EventType.RUN_FINISHED ||\n event.type === EventType.RUN_ERROR\n ) {\n // Flush compacted state into output before the run boundary event\n flushState(stateEvents, compacted);\n stateEvents = [];\n compacted.push(event);\n } else if (\n event.type === EventType.STATE_SNAPSHOT ||\n event.type === EventType.STATE_DELTA\n ) {\n // Collect state events for compaction\n stateEvents.push(event as StateSnapshotEvent | StateDeltaEvent);\n } else {\n // For non-streaming events, check if we're in the middle of any streaming sequences\n let addedToBuffer = false;\n\n // Check text messages\n for (const [messageId, pending] of pendingTextMessages) {\n // If we have a start but no end yet, this event is \"in between\"\n if (pending.start && !pending.end) {\n pending.otherEvents.push(event);\n addedToBuffer = true;\n break;\n }\n }\n\n // Check tool calls if not already buffered\n if (!addedToBuffer) {\n for (const [toolCallId, pending] of pendingToolCalls) {\n // If we have a start but no end yet, this event is \"in between\"\n if (pending.start && !pending.end) {\n pending.otherEvents.push(event);\n addedToBuffer = true;\n break;\n }\n }\n }\n\n // If not in the middle of any streaming sequence, add directly to compacted\n if (!addedToBuffer) {\n compacted.push(event);\n }\n }\n }\n\n // Flush any remaining incomplete messages\n for (const [messageId, pending] of pendingTextMessages) {\n flushTextMessage(messageId, pending, compacted);\n }\n\n // Flush any remaining incomplete tool calls\n for (const [toolCallId, pending] of pendingToolCalls) {\n flushToolCall(toolCallId, pending, compacted);\n }\n\n // Flush any remaining state events (incomplete run or events outside runs)\n flushState(stateEvents, compacted);\n\n return compacted;\n}\n\nfunction flushTextMessage(\n messageId: string,\n pending: {\n start?: TextMessageStartEvent;\n contents: TextMessageContentEvent[];\n end?: TextMessageEndEvent;\n otherEvents: BaseEvent[];\n },\n compacted: BaseEvent[],\n): void {\n // Add start event if present\n if (pending.start) {\n compacted.push(pending.start);\n }\n\n // Compact all content events into one\n if (pending.contents.length > 0) {\n const concatenatedDelta = pending.contents.map((c) => c.delta).join(\"\");\n\n const compactedContent: TextMessageContentEvent = {\n type: EventType.TEXT_MESSAGE_CONTENT,\n messageId: messageId,\n delta: concatenatedDelta,\n };\n\n compacted.push(compactedContent);\n }\n\n // Add end event if present\n if (pending.end) {\n compacted.push(pending.end);\n }\n\n // Add any events that were in between\n for (const otherEvent of pending.otherEvents) {\n compacted.push(otherEvent);\n }\n}\n\nfunction flushToolCall(\n toolCallId: string,\n pending: {\n start?: ToolCallStartEvent;\n args: ToolCallArgsEvent[];\n end?: ToolCallEndEvent;\n otherEvents: BaseEvent[];\n },\n compacted: BaseEvent[],\n): void {\n // Add start event if present\n if (pending.start) {\n compacted.push(pending.start);\n }\n\n // Compact all args events into one\n if (pending.args.length > 0) {\n const concatenatedArgs = pending.args.map((a) => a.delta).join(\"\");\n\n const compactedArgs: ToolCallArgsEvent = {\n type: EventType.TOOL_CALL_ARGS,\n toolCallId: toolCallId,\n delta: concatenatedArgs,\n };\n\n compacted.push(compactedArgs);\n }\n\n // Add end event if present\n if (pending.end) {\n compacted.push(pending.end);\n }\n\n // Add any events that were in between\n for (const otherEvent of pending.otherEvents) {\n compacted.push(otherEvent);\n }\n}\n\nfunction flushState(\n stateEvents: (StateSnapshotEvent | StateDeltaEvent)[],\n compacted: BaseEvent[],\n): void {\n if (stateEvents.length === 0) {\n return;\n }\n\n let state: any = {};\n\n for (const event of stateEvents) {\n if (event.type === EventType.STATE_SNAPSHOT) {\n state = structuredClone_(event.snapshot);\n } else {\n const result = jsonpatch.applyPatch(state, structuredClone_(event.delta), true, false);\n state = result.newDocument;\n }\n }\n\n const compactedSnapshot: StateSnapshotEvent = {\n type: EventType.STATE_SNAPSHOT,\n snapshot: state,\n };\n\n compacted.push(compactedSnapshot);\n}\n", "// The package's single home for enums and constant-like values. Per\n// CLAUDE.md this is the only file allowed to export multiple symbols.\n\n/** The Custom Element tag name registered by {@link defineAgUiChat}. */\nexport const ELEMENT_TAG = \"ag-ui-chat\";\n\n/**\n * Event dispatched by `<ag-ui-chat>` when the user submits a message.\n * `detail` carries `{ content: string }`. Later phases wire this to the\n * AG-UI client; for now it is the public seam for host integration.\n */\nexport const SUBMIT_EVENT = \"ag-ui-submit\";\n\n/** Roles a chat message can take. */\nexport const MESSAGE_ROLE = {\n USER: \"user\",\n ASSISTANT: \"assistant\",\n} as const;\n\n/**\n * JSON-Schema extension key marking a tool as destructive. Mirrors the\n * `django-ag-ui` server side. When a tool's `parameters` carries\n * `{ \"x-destructive\": true }`, the element gates its execution behind the\n * confirmation modal (unless `autoConfirm` is set).\n */\nexport const X_DESTRUCTIVE_KEY = \"x-destructive\";\n\n/**\n * JSON-Schema extension key marking a tool as navigating \u2014 its handler triggers\n * a full page reload (an MPA navigation). When a tool's `parameters` carries\n * `{ \"x-navigates\": true }`, the element checkpoints the call before the reload\n * and resumes the run loop once the next page mounts. Mirrors `x-destructive`.\n */\nexport const X_NAVIGATES_KEY = \"x-navigates\";\n\n/** Upper bound on frontend tool-call \u2192 re-run rounds within one send. */\nexport const MAX_TOOL_ROUNDS = 10;\n\n/**\n * Lifecycle status of a rendered tool-call card. A card opens as `PENDING`\n * while the call runs, then settles to `DONE`, `ERROR`, or `DECLINED`.\n */\nexport const TOOL_CALL_STATUS = {\n PENDING: \"pending\",\n DONE: \"done\",\n ERROR: \"error\",\n DECLINED: \"declined\",\n} as const;\n", "import { type AbstractAgent, type AgentSubscriber, randomUUID } from \"@ag-ui/client\";\nimport type { Context, Message, Tool } from \"@ag-ui/core\";\nimport { MAX_TOOL_ROUNDS } from \"./constants.js\";\n\n/** A tool call surfaced to the host by {@link AgUiClient}. */\nexport interface AgUiToolCall {\n readonly id: string;\n readonly name: string;\n readonly args: Record<string, unknown>;\n}\n\n/** The result of executing a frontend tool, destined for a tool-result message. */\nexport interface ToolExecution {\n /** String content for the AG-UI tool-result message. */\n content: string;\n /** Present when the handler failed; surfaced for logging. */\n error?: string;\n /**\n * When `true`, a navigating tool triggered a page reload. The loop stops\n * without appending a result \u2014 the result is supplied after the next mount\n * (see the resume path). Mutually exclusive with a usable `content`.\n */\n halt?: boolean;\n}\n\n/**\n * Executes a frontend tool call.\n *\n * Returns the {@link ToolExecution} to post back to the agent, or ``null`` when\n * the call is not a frontend tool the host owns (a server-side tool the server\n * already executed \u2014 the client must not re-run for it).\n */\nexport type ExecuteTool = (call: AgUiToolCall) => Promise<ToolExecution | null>;\n\n/**\n * Callbacks the {@link AgUiClient} invokes as a run progresses. The host\n * (the `<ag-ui-chat>` element) implements these to render streaming text and\n * tool activity into the chat.\n */\nexport interface AgUiClientHandlers {\n onRunStart(): void;\n /** Fired on every streamed token; ``buffer`` is the full text so far. */\n onTextDelta(buffer: string): void;\n /** Fired when the assistant message completes; ``buffer`` is the final text. */\n onTextEnd(buffer: string): void;\n /** Fired when the agent finishes calling a tool (server- or frontend-side). */\n onToolCall(call: AgUiToolCall): void;\n onRunEnd(): void;\n onError(message: string): void;\n}\n\n/**\n * Provider of the per-run frontend tool catalog and context. Both are read\n * fresh on every {@link AgUiClient.send} so the catalog reflects the current\n * page state.\n */\nexport interface AgUiRunInputs {\n getTools?: () => Tool[];\n getContext?: () => Context[];\n}\n\nexport interface AgUiClientConfig extends AgUiRunInputs {\n /** The AG-UI agent to drive. Injected so it can be faked in tests. */\n agent: AbstractAgent;\n handlers: AgUiClientHandlers;\n /** Executes frontend tool calls. Omit for server-only tool sets. */\n executeTool?: ExecuteTool;\n /**\n * Invoked with the latest history whenever it changes, so the host can\n * persist it for durability across page reloads. Omit to keep the\n * conversation in-memory only.\n */\n onPersist?: (messages: readonly Message[]) => void;\n}\n\n/**\n * Thin orchestration layer over an AG-UI {@link AbstractAgent}.\n *\n * Translates AG-UI's subscriber callbacks into the host's\n * {@link AgUiClientHandlers}, and appends the user message + current frontend\n * tool catalog + context to each run.\n */\nexport class AgUiClient {\n readonly #agent: AbstractAgent;\n readonly #handlers: AgUiClientHandlers;\n readonly #getTools: () => Tool[];\n readonly #getContext: () => Context[];\n readonly #executeTool: ExecuteTool | null;\n readonly #onPersist: (messages: readonly Message[]) => void;\n\n constructor(config: AgUiClientConfig) {\n this.#agent = config.agent;\n this.#handlers = config.handlers;\n this.#getTools = config.getTools ?? (() => []);\n this.#getContext = config.getContext ?? (() => []);\n this.#executeTool = config.executeTool ?? null;\n this.#onPersist = config.onPersist ?? (() => {});\n }\n\n /** Whether a run is currently in flight. */\n get running(): boolean {\n return this.#agent.isRunning;\n }\n\n /** The current conversation history (for persistence / rehydration). */\n get messages(): readonly Message[] {\n return this.#agent.messages;\n }\n\n /**\n * Append a user message and run the agent to completion.\n *\n * When the agent calls frontend tools, this executes them and re-runs the\n * agent with the results, looping until the agent stops calling frontend\n * tools (bounded by {@link MAX_TOOL_ROUNDS}).\n */\n async send(content: string): Promise<void> {\n this.#agent.addMessage({ id: randomUUID(), role: \"user\", content });\n this.#onPersist(this.#agent.messages);\n await this.#run();\n }\n\n /**\n * Resume the run loop after a navigating tool's result was supplied\n * post-reload (via {@link addToolResult}). Unlike {@link send}, adds no user\n * message \u2014 it simply continues the conversation already in history.\n */\n async resume(): Promise<void> {\n await this.#run();\n }\n\n /** Append a frontend tool result to history (used by the resume path). */\n addToolResult(toolCallId: string, content: string): void {\n this.#agent.addMessage({ id: randomUUID(), role: \"tool\", content, toolCallId });\n this.#onPersist(this.#agent.messages);\n }\n\n async #run(): Promise<void> {\n try {\n await this.#runLoop();\n } catch (error) {\n this.#handlers.onError(error instanceof Error ? error.message : String(error));\n }\n }\n\n async #runLoop(): Promise<void> {\n for (let round = 0; round < MAX_TOOL_ROUNDS; round += 1) {\n const pending: AgUiToolCall[] = [];\n await this.#agent.runAgent(\n { tools: this.#getTools(), context: this.#getContext() },\n this.#buildSubscriber(pending),\n );\n this.#onPersist(this.#agent.messages);\n if (this.#executeTool === null || pending.length === 0) {\n return;\n }\n let executed = false;\n for (const call of pending) {\n const result = await this.#executeTool(call);\n if (result === null) {\n continue;\n }\n if (result.halt === true) {\n // A navigating tool reloaded the page; the result arrives on the\n // next mount. Stop here rather than re-running into a dead context.\n return;\n }\n this.#agent.addMessage({\n id: randomUUID(),\n role: \"tool\",\n content: result.content,\n toolCallId: call.id,\n });\n this.#onPersist(this.#agent.messages);\n executed = true;\n }\n if (!executed) {\n return;\n }\n }\n }\n\n #buildSubscriber(pending: AgUiToolCall[]): AgentSubscriber {\n const h = this.#handlers;\n return {\n onRunInitialized() {\n h.onRunStart();\n },\n onTextMessageContentEvent({ textMessageBuffer }) {\n h.onTextDelta(textMessageBuffer);\n },\n onTextMessageEndEvent({ textMessageBuffer }) {\n h.onTextEnd(textMessageBuffer);\n },\n onToolCallEndEvent({ event, toolCallName, toolCallArgs }) {\n const call: AgUiToolCall = {\n id: event.toolCallId,\n name: toolCallName,\n args: toolCallArgs,\n };\n pending.push(call);\n h.onToolCall(call);\n },\n onRunErrorEvent({ event }) {\n h.onError(event.message);\n },\n onRunFinalized() {\n h.onRunEnd();\n },\n };\n }\n}\n", "import type { Tool } from \"@ag-ui/core\";\n\n/**\n * A tool the frontend declares and executes itself.\n *\n * `parameters` is a JSON Schema (and may carry the `x-destructive` extension).\n * `handler` receives the parsed arguments and returns a result that is\n * JSON-serialised into the AG-UI tool-result message sent back to the agent.\n */\nexport interface ClientTool {\n name: string;\n description: string;\n parameters: Record<string, unknown>;\n handler: (args: Record<string, unknown>) => unknown | Promise<unknown>;\n}\n\n/**\n * Holds the frontend tools a host has declared on an `<ag-ui-chat>` element.\n *\n * Produces AG-UI {@link Tool} definitions for `RunAgentInput.tools` and looks\n * up handlers when the agent calls a tool. Pure (no DOM); the element owns one\n * instance.\n */\nexport class ClientToolRegistry {\n readonly #tools = new Map<string, ClientTool>();\n\n /** Register a tool. Throws if the name is already taken. */\n register(tool: ClientTool): void {\n if (this.#tools.has(tool.name)) {\n throw new Error(`tool \"${tool.name}\" already registered`);\n }\n this.#tools.set(tool.name, tool);\n }\n\n has(name: string): boolean {\n return this.#tools.has(name);\n }\n\n /** Return a registered tool or throw. */\n get(name: string): ClientTool {\n const tool = this.#tools.get(name);\n if (tool === undefined) {\n throw new Error(`tool \"${name}\" is not registered`);\n }\n return tool;\n }\n\n /** AG-UI tool definitions for `RunAgentInput.tools`. */\n tools(): Tool[] {\n return [...this.#tools.values()].map((tool) => ({\n name: tool.name,\n description: tool.description,\n parameters: tool.parameters,\n }));\n }\n}\n", "/** What the confirmation modal displays. */\nexport interface ConfirmationRequest {\n toolName: string;\n args: Record<string, unknown>;\n}\n\n/**\n * Render a confirmation modal into ``host`` and resolve when the user decides.\n *\n * Resolves ``true`` if the user confirms, ``false`` if they cancel or dismiss\n * via the backdrop. The modal is appended to ``host`` (the chat container\n * inside the element's shadow root) and removed once resolved.\n */\nexport function requestConfirmation(\n host: Node & ParentNode,\n request: ConfirmationRequest,\n): Promise<boolean> {\n return new Promise<boolean>((resolve) => {\n const overlay = document.createElement(\"div\");\n overlay.className = \"modal-overlay\";\n\n const dialog = document.createElement(\"div\");\n dialog.className = \"modal\";\n\n const title = document.createElement(\"div\");\n title.className = \"modal-title\";\n title.textContent = \"Confirm action\";\n\n const body = document.createElement(\"div\");\n body.className = \"modal-body\";\n body.textContent = `Run \u201C${request.toolName}\u201D?`;\n\n const args = document.createElement(\"pre\");\n args.className = \"modal-args\";\n args.textContent = JSON.stringify(request.args, null, 2);\n\n const actions = document.createElement(\"div\");\n actions.className = \"modal-actions\";\n\n const cancel = document.createElement(\"button\");\n cancel.className = \"modal-btn modal-btn--cancel\";\n cancel.type = \"button\";\n cancel.textContent = \"Cancel\";\n\n const confirm = document.createElement(\"button\");\n confirm.className = \"modal-btn modal-btn--confirm\";\n confirm.type = \"button\";\n confirm.textContent = \"Run\";\n\n const close = (accepted: boolean): void => {\n overlay.remove();\n resolve(accepted);\n };\n\n cancel.addEventListener(\"click\", () => close(false));\n confirm.addEventListener(\"click\", () => close(true));\n overlay.addEventListener(\"click\", (event) => {\n if (event.target === overlay) {\n close(false);\n }\n });\n\n actions.append(cancel, confirm);\n dialog.append(title, body, args, actions);\n overlay.append(dialog);\n host.appendChild(overlay);\n confirm.focus();\n });\n}\n", "import { randomUUID } from \"@ag-ui/client\";\nimport type { Message } from \"@ag-ui/core\";\n\n/**\n * A checkpoint recorded just before a navigating tool reloads the page.\n *\n * The reload destroys the in-memory run loop, so the element persists this\n * marker first; on the next mount it supplies the tool's result and resumes.\n */\nexport interface NavigationCheckpoint {\n /** The tool-call id whose result must be supplied after the reload. */\n readonly toolCallId: string;\n}\n\n/**\n * Client-side persistence seam for the conversation and a pending-navigation\n * checkpoint, keyed by `thread_id`.\n *\n * The default {@link SessionStorageStore} keeps everything per-tab in\n * `sessionStorage`, so the chat survives the full page reloads of a\n * multi-page app. A host may inject a server-backed store instead (e.g. one\n * that rehydrates from a history endpoint); `loadMessages` is therefore\n * async-friendly. The checkpoint methods stay synchronous \u2014 the marker is a\n * tiny local hint a server store can derive from history and no-op.\n */\nexport interface ClientConversationStore {\n /** A stable conversation id, generated and persisted on first read. */\n threadId(): string;\n /** Load the persisted message history, or `null` when none exists. */\n loadMessages(threadId: string): Promise<readonly Message[] | null>;\n /** Persist the message history. */\n saveMessages(threadId: string, messages: readonly Message[]): void;\n /** Load the pending-navigation checkpoint, or `null` when none is set. */\n loadCheckpoint(threadId: string): NavigationCheckpoint | null;\n /** Set the pending-navigation checkpoint, or clear it when given `null`. */\n saveCheckpoint(threadId: string, checkpoint: NavigationCheckpoint | null): void;\n /** Forget the conversation and checkpoint (e.g. a \"new chat\" action). */\n clear(threadId: string): void;\n}\n\nconst THREAD_KEY = \"ag-ui-chat:thread\";\nconst MESSAGES_PREFIX = \"ag-ui-chat:messages:\";\nconst CHECKPOINT_PREFIX = \"ag-ui-chat:checkpoint:\";\n\n/**\n * Default {@link ClientConversationStore}: per-tab `sessionStorage`.\n *\n * Survives full page reloads and same-tab navigation, clears on tab close \u2014\n * the right scope for an embedded agent's conversation in a multi-page app.\n * One thread id per tab; the message history and checkpoint are namespaced by\n * it so two tabs hold independent conversations.\n */\nexport class SessionStorageStore implements ClientConversationStore {\n threadId(): string {\n const existing = sessionStorage.getItem(THREAD_KEY);\n if (existing !== null) {\n return existing;\n }\n const id = randomUUID();\n sessionStorage.setItem(THREAD_KEY, id);\n return id;\n }\n\n loadMessages(threadId: string): Promise<readonly Message[] | null> {\n return Promise.resolve(this.#readJson<Message[]>(MESSAGES_PREFIX + threadId));\n }\n\n saveMessages(threadId: string, messages: readonly Message[]): void {\n sessionStorage.setItem(MESSAGES_PREFIX + threadId, JSON.stringify(messages));\n }\n\n loadCheckpoint(threadId: string): NavigationCheckpoint | null {\n return this.#readJson<NavigationCheckpoint>(CHECKPOINT_PREFIX + threadId);\n }\n\n saveCheckpoint(threadId: string, checkpoint: NavigationCheckpoint | null): void {\n const key = CHECKPOINT_PREFIX + threadId;\n if (checkpoint === null) {\n sessionStorage.removeItem(key);\n return;\n }\n sessionStorage.setItem(key, JSON.stringify(checkpoint));\n }\n\n clear(threadId: string): void {\n sessionStorage.removeItem(MESSAGES_PREFIX + threadId);\n sessionStorage.removeItem(CHECKPOINT_PREFIX + threadId);\n sessionStorage.removeItem(THREAD_KEY);\n }\n\n /** Parse a stored JSON value, returning `null` when absent or corrupt. */\n #readJson<T>(key: string): T | null {\n const raw = sessionStorage.getItem(key);\n if (raw === null) {\n return null;\n }\n try {\n return JSON.parse(raw) as T;\n } catch {\n return null;\n }\n }\n}\n", "import { type AbstractAgent, HttpAgent } from \"@ag-ui/client\";\nimport type { Message } from \"@ag-ui/core\";\n\n/** Config for {@link createHttpAgent}. */\nexport interface HttpAgentOptions {\n endpoint: string;\n headers?: Record<string, string>;\n /** Stable conversation id, so the agent's runs share a thread. */\n threadId?: string;\n /** Rehydrated history to seed the agent with (durable conversation). */\n initialMessages?: readonly Message[];\n}\n\n/**\n * Build an AG-UI {@link HttpAgent} pointed at ``endpoint``.\n *\n * This is the default agent factory used by ``<ag-ui-chat>``. Tests and\n * advanced hosts override the element's ``agentFactory`` to inject a\n * different {@link AbstractAgent} (e.g. a fake, or a middleware-wrapped one).\n */\nexport function createHttpAgent(options: HttpAgentOptions): AbstractAgent {\n return new HttpAgent({\n url: options.endpoint,\n headers: options.headers ?? {},\n // HttpAgent invokes its configured fetch as a method (`this.fetch(...)`),\n // which would rebind the global `fetch` to the agent instance and trigger\n // \"Illegal invocation\" in browsers. Wrap it so `fetch` is always called as\n // a free function with the correct receiver.\n fetch: (url, init) => fetch(url, init),\n // Spread conditionally: under `exactOptionalPropertyTypes` an explicit\n // `undefined` is not assignable to these optional config fields.\n ...(options.threadId !== undefined ? { threadId: options.threadId } : {}),\n ...(options.initialMessages !== undefined\n ? { initialMessages: [...options.initialMessages] }\n : {}),\n });\n}\n\n/** Signature of the agent factory the element calls to build its agent. */\nexport type AgentFactory = (options: HttpAgentOptions) => AbstractAgent;\n", "import { X_DESTRUCTIVE_KEY } from \"./constants.js\";\n\n/**\n * Whether a tool's JSON-Schema `parameters` marks it destructive.\n *\n * Reads the `x-destructive` extension stamped by the server (`django-ag-ui`'s\n * `build_input_schema`) or by a host declaring a tool directly.\n */\nexport function isDestructive(parameters: Record<string, unknown>): boolean {\n return parameters[X_DESTRUCTIVE_KEY] === true;\n}\n", "import { X_NAVIGATES_KEY } from \"./constants.js\";\n\n/**\n * Whether a tool's JSON-Schema `parameters` marks it as navigating.\n *\n * Reads the `x-navigates` extension. A navigating tool's handler reloads the\n * page (MPA navigation), so the element checkpoints the call and resumes the\n * run loop after the next page mounts, rather than awaiting a result inline.\n */\nexport function isNavigates(parameters: Record<string, unknown>): boolean {\n return parameters[X_NAVIGATES_KEY] === true;\n}\n", "import type { Context } from \"@ag-ui/core\";\n\n/**\n * A compact snapshot of the current page's actionable surface (field\n * names/types/labels, button labels+handles \u2014 not values). Host-defined shape;\n * kept small because it rides in every `RunAgentInput.context`.\n */\nexport type PageMap = Record<string, unknown>;\n\n/**\n * Build the per-run context entry for the page map.\n *\n * Returns a single `page_map` context item when auto-injection is on and a\n * provider is set, else nothing. Recomputed each run so it reflects the page\n * the agent is currently looking at.\n */\nexport function createPageMapContext(\n getPageMap: (() => PageMap) | null,\n autoInject: boolean,\n): Context[] {\n if (!autoInject || getPageMap === null) {\n return [];\n }\n return [{ description: \"page_map\", value: JSON.stringify(getPageMap()) }];\n}\n", "import type { ClientTool } from \"./client_tool_registry.js\";\nimport { X_NAVIGATES_KEY } from \"./constants.js\";\n\n/** A single navigable route the host declares for the agent. */\nexport interface Route {\n /** Stable id the agent uses with `navigate_to_route`. */\n readonly id: string;\n /** The URL path to navigate to. */\n readonly path: string;\n /** Human label shown to the agent. */\n readonly title?: string;\n /** Optional grouping (e.g. an app or section). */\n readonly group?: string;\n /** Optional longer description of when to use the route. */\n readonly description?: string;\n}\n\n/** The host-declared catalog of navigable routes. */\nexport type RouteMap = readonly Route[];\n\n/** Append `params` to `path` as a query string (no-op when empty). */\nfunction withQuery(path: string, params: Record<string, unknown> | undefined): string {\n if (params === undefined) {\n return path;\n }\n const usp = new URLSearchParams();\n for (const [key, value] of Object.entries(params)) {\n usp.set(key, String(value));\n }\n const query = usp.toString();\n return query === \"\" ? path : `${path}?${query}`;\n}\n\n/**\n * The built-in `route.*` tools, bound to live getters so a host can set\n * `routeMap` / `navigate` before or after mount.\n *\n * `list_routes` is read-only; `navigate_to_route` is marked `x-navigates` so an\n * MPA reload checkpoints + resumes. When the host supplies a `navigate(path)`\n * callback (an SPA), the element routes client-side instead and the run loop\n * simply continues \u2014 see `AgUiChat`'s execute path.\n */\nexport function createRouteTools(\n getRouteMap: () => RouteMap,\n getNavigate: () => ((path: string) => void) | null,\n): ClientTool[] {\n return [\n {\n name: \"list_routes\",\n description: \"List the routes the app can navigate to.\",\n parameters: { type: \"object\", properties: {}, required: [] },\n handler: () => getRouteMap(),\n },\n {\n name: \"navigate_to_route\",\n description: \"Navigate to one of the app's routes by its id.\",\n parameters: {\n type: \"object\",\n properties: {\n route_id: { type: \"string\" },\n params: { type: \"object\" },\n },\n required: [\"route_id\"],\n [X_NAVIGATES_KEY]: true,\n },\n handler: (args) => {\n const routeId = args[\"route_id\"];\n const route = getRouteMap().find((r) => r.id === routeId);\n if (route === undefined) {\n throw new Error(`unknown route \"${String(routeId)}\"`);\n }\n const path = withQuery(route.path, args[\"params\"] as Record<string, unknown> | undefined);\n const navigate = getNavigate();\n if (navigate !== null) {\n navigate(path);\n } else {\n window.location.assign(path);\n }\n return { navigated: true, path };\n },\n },\n ];\n}\n", "import type { ClientTool } from \"./client_tool_registry.js\";\nimport { X_DESTRUCTIVE_KEY } from \"./constants.js\";\n\n/**\n * A binding from a named piece of host application state to agent tools.\n *\n * Ergonomic sugar over `registerTool` for SPA state (Redux/Zustand/signals):\n * generates a read tool and, when `write` is given, a destructive set tool.\n */\nexport interface StateHook {\n /** Base name; tools become `read_<name>` and `set_<name>`. */\n readonly name: string;\n /** Returns the current state value. */\n readonly read: () => unknown;\n /** Mutates the state from the agent-supplied args. Omit for read-only. */\n readonly write?: (args: Record<string, unknown>) => unknown;\n /** JSON-Schema for the set tool's args. Defaults to an open object. */\n readonly schema?: Record<string, unknown>;\n}\n\n/**\n * Build the tools for a {@link StateHook}: always a `read_<name>` (read-only)\n * tool, plus a `set_<name>` (`x-destructive`) tool when `write` is supplied.\n */\nexport function createStateHookTools(hook: StateHook): ClientTool[] {\n const tools: ClientTool[] = [\n {\n name: `read_${hook.name}`,\n description: `Read the \"${hook.name}\" state.`,\n parameters: { type: \"object\", properties: {}, required: [] },\n handler: () => hook.read(),\n },\n ];\n const write = hook.write;\n if (write !== undefined) {\n tools.push({\n name: `set_${hook.name}`,\n description: `Update the \"${hook.name}\" state.`,\n parameters: { ...(hook.schema ?? { type: \"object\" }), [X_DESTRUCTIVE_KEY]: true },\n handler: (args) => write(args),\n });\n }\n return tools;\n}\n", "// Shadow-DOM-scoped styles for the chat shell. Kept as a string constant so\n// the Custom Element can inject it into its shadow root without a build-time\n// CSS pipeline. Scoped by the shadow boundary, so class names stay terse.\n\nexport const STYLES = `\n:host {\n /* Colors */\n --ag-ui-bg: #ffffff;\n --ag-ui-fg: #1a1a2e;\n --ag-ui-accent: #4f46e5;\n --ag-ui-user-bg: #4f46e5;\n --ag-ui-user-fg: #ffffff;\n --ag-ui-assistant-bg: #f1f1f6;\n --ag-ui-input-bg: var(--ag-ui-bg);\n --ag-ui-tool-bg: var(--ag-ui-assistant-bg);\n --ag-ui-tool-fg: var(--ag-ui-accent);\n --ag-ui-header-bg: var(--ag-ui-accent);\n --ag-ui-header-fg: #ffffff;\n --ag-ui-border: #e2e2ec;\n --ag-ui-radius: 12px;\n\n /* Status accents for tool-call cards. */\n --ag-ui-success: #15803d;\n --ag-ui-danger: #b91c1c;\n --ag-ui-muted: #6b7280;\n\n /* Surface \u2014 set --ag-ui-shadow: none for a flush, embedded panel. */\n --ag-ui-shadow: 0 12px 32px rgba(20, 20, 50, 0.18);\n --ag-ui-font: inherit;\n --ag-ui-font-size: 14px;\n\n /* Layout \u2014 override from outside to dock the widget anywhere.\n Set --ag-ui-position: static (and place this element in your own\n grid/flex layout) to embed it in the page flow instead of floating. */\n --ag-ui-position: fixed;\n --ag-ui-z-index: 2147483000;\n --ag-ui-width: 380px;\n --ag-ui-height: 560px;\n --ag-ui-inset: auto 24px 24px auto;\n --ag-ui-max-width: calc(100vw - 48px);\n --ag-ui-max-height: calc(100vh - 48px);\n\n position: var(--ag-ui-position);\n inset: var(--ag-ui-inset);\n z-index: var(--ag-ui-z-index);\n width: var(--ag-ui-width);\n max-width: var(--ag-ui-max-width);\n height: var(--ag-ui-height);\n max-height: var(--ag-ui-max-height);\n display: flex;\n font-family: var(--ag-ui-font);\n font-size: var(--ag-ui-font-size);\n color: var(--ag-ui-fg);\n}\n\n.chat {\n position: relative;\n display: flex;\n flex-direction: column;\n flex: 1;\n min-height: 0;\n background: var(--ag-ui-bg);\n border: 1px solid var(--ag-ui-border);\n border-radius: var(--ag-ui-radius);\n box-shadow: var(--ag-ui-shadow);\n overflow: hidden;\n}\n\n.header {\n padding: 12px 16px;\n font-weight: 600;\n border-bottom: 1px solid var(--ag-ui-border);\n background: var(--ag-ui-header-bg);\n color: var(--ag-ui-header-fg);\n}\n\n.messages {\n flex: 1;\n overflow-y: auto;\n padding: 16px;\n display: flex;\n flex-direction: column;\n gap: 10px;\n}\n\n.message {\n max-width: 80%;\n padding: 8px 12px;\n border-radius: 14px;\n line-height: 1.4;\n white-space: pre-wrap;\n word-break: break-word;\n}\n\n.message--user {\n align-self: flex-end;\n background: var(--ag-ui-user-bg);\n color: var(--ag-ui-user-fg);\n border-bottom-right-radius: 4px;\n}\n\n.message--assistant {\n align-self: flex-start;\n background: var(--ag-ui-assistant-bg);\n border-bottom-left-radius: 4px;\n}\n\n.tool-call {\n align-self: flex-start;\n max-width: 80%;\n box-sizing: border-box;\n display: flex;\n flex-direction: column;\n gap: 6px;\n font-size: 12px;\n font-family: ui-monospace, \"SF Mono\", Menlo, monospace;\n padding: 8px 10px;\n border-radius: 8px;\n background: var(--ag-ui-tool-bg);\n border: 1px solid var(--ag-ui-border);\n color: var(--ag-ui-tool-fg);\n}\n\n.tool-call-head {\n display: flex;\n align-items: center;\n justify-content: space-between;\n gap: 8px;\n}\n\n.tool-call-name {\n font-weight: 600;\n word-break: break-word;\n}\n\n.tool-call-status {\n flex: none;\n padding: 1px 8px;\n border-radius: 999px;\n font-size: 11px;\n font-weight: 600;\n background: rgba(127, 127, 127, 0.16);\n color: var(--ag-ui-muted);\n}\n\n.tool-call[data-status=\"done\"] .tool-call-status {\n color: var(--ag-ui-success);\n}\n\n.tool-call[data-status=\"error\"] .tool-call-status {\n color: var(--ag-ui-danger);\n}\n\n.tool-call[data-status=\"declined\"] .tool-call-status {\n color: var(--ag-ui-muted);\n}\n\n.tool-call-args,\n.tool-call-result {\n margin: 0;\n padding: 6px 8px;\n max-height: 160px;\n overflow: auto;\n background: var(--ag-ui-bg);\n border: 1px solid var(--ag-ui-border);\n border-radius: 6px;\n white-space: pre-wrap;\n word-break: break-word;\n color: var(--ag-ui-fg);\n}\n\n.tool-call-toggle {\n align-self: flex-start;\n border: none;\n padding: 0;\n background: none;\n font: inherit;\n font-weight: 600;\n color: var(--ag-ui-accent);\n cursor: pointer;\n}\n\n.tool-call-toggle::before {\n content: \"\u25B8 \";\n}\n\n.tool-call-toggle[aria-expanded=\"true\"]::before {\n content: \"\u25BE \";\n}\n\n.input-row {\n display: flex;\n gap: 8px;\n padding: 12px;\n border-top: 1px solid var(--ag-ui-border);\n}\n\n.input {\n flex: 1;\n resize: none;\n background: var(--ag-ui-input-bg);\n border: 1px solid var(--ag-ui-border);\n border-radius: 8px;\n padding: 8px 10px;\n font: inherit;\n color: inherit;\n outline: none;\n}\n\n.input:focus {\n border-color: var(--ag-ui-accent);\n}\n\n.send {\n border: none;\n border-radius: 8px;\n padding: 0 16px;\n background: var(--ag-ui-accent);\n color: #ffffff;\n font: inherit;\n font-weight: 600;\n cursor: pointer;\n}\n\n.send:disabled {\n opacity: 0.5;\n cursor: default;\n}\n\n.modal-overlay {\n position: absolute;\n inset: 0;\n display: flex;\n align-items: center;\n justify-content: center;\n padding: 16px;\n background: rgba(20, 20, 50, 0.4);\n backdrop-filter: blur(2px);\n}\n\n.modal {\n width: 100%;\n max-width: 320px;\n background: var(--ag-ui-bg);\n border-radius: 12px;\n box-shadow: 0 16px 40px rgba(20, 20, 50, 0.3);\n overflow: hidden;\n}\n\n.modal-title {\n padding: 12px 16px;\n font-weight: 600;\n border-bottom: 1px solid var(--ag-ui-border);\n}\n\n.modal-body {\n padding: 12px 16px 4px;\n}\n\n.modal-args {\n margin: 0 16px 12px;\n padding: 8px 10px;\n max-height: 140px;\n overflow: auto;\n font-size: 12px;\n font-family: ui-monospace, \"SF Mono\", Menlo, monospace;\n background: var(--ag-ui-assistant-bg);\n border-radius: 8px;\n white-space: pre-wrap;\n word-break: break-word;\n}\n\n.modal-actions {\n display: flex;\n gap: 8px;\n padding: 0 16px 16px;\n justify-content: flex-end;\n}\n\n.modal-btn {\n border: 1px solid var(--ag-ui-border);\n border-radius: 8px;\n padding: 8px 14px;\n font: inherit;\n font-weight: 600;\n cursor: pointer;\n background: var(--ag-ui-bg);\n color: var(--ag-ui-fg);\n}\n\n.modal-btn--confirm {\n border-color: var(--ag-ui-accent);\n background: var(--ag-ui-accent);\n color: #ffffff;\n}\n`;\n", "import { TOOL_CALL_STATUS } from \"./constants.js\";\n\n/** Any state a tool-call card can be in. */\nexport type ToolCallStatus = (typeof TOOL_CALL_STATUS)[keyof typeof TOOL_CALL_STATUS];\n\n/** The terminal states a card settles into (everything but `pending`). */\nexport type SettledStatus = Exclude<ToolCallStatus, typeof TOOL_CALL_STATUS.PENDING>;\n\n/** Short pill text shown for each status. */\nconst STATUS_LABEL: Record<ToolCallStatus, string> = {\n [TOOL_CALL_STATUS.PENDING]: \"running\u2026\",\n [TOOL_CALL_STATUS.DONE]: \"\u2713 done\",\n [TOOL_CALL_STATUS.ERROR]: \"\u26A0 error\",\n [TOOL_CALL_STATUS.DECLINED]: \"\u2298 declined\",\n};\n\n/** Toggle-button label for each settled outcome's collapsible body. */\nconst RESULT_LABEL: Record<SettledStatus, string> = {\n [TOOL_CALL_STATUS.DONE]: \"Result\",\n [TOOL_CALL_STATUS.ERROR]: \"Error\",\n [TOOL_CALL_STATUS.DECLINED]: \"Declined\",\n};\n\n/**\n * A live tool-call card for the chat transcript.\n *\n * Construction renders the tool name, its pretty-printed arguments, and a\n * `running\u2026` status pill. {@link settle} later flips the pill to the outcome\n * and appends a click-to-expand body holding the result (or error / decline\n * message), collapsed by default.\n *\n * Pure DOM (no framework); the host appends {@link element} into its shadow\n * root and themes it via the `--ag-ui-*` custom properties.\n */\nexport class ToolCallCard {\n /** The card's root element; append this into the message list. */\n readonly element: HTMLDivElement;\n\n readonly #status: HTMLSpanElement;\n\n constructor(name: string, args: Record<string, unknown>) {\n this.element = document.createElement(\"div\");\n this.element.className = \"tool-call\";\n this.element.setAttribute(\"data-tool-name\", name);\n this.element.setAttribute(\"data-status\", TOOL_CALL_STATUS.PENDING);\n\n const head = document.createElement(\"div\");\n head.className = \"tool-call-head\";\n\n const label = document.createElement(\"span\");\n label.className = \"tool-call-name\";\n label.textContent = `\uD83D\uDD27 ${name}`;\n\n this.#status = document.createElement(\"span\");\n this.#status.className = \"tool-call-status\";\n this.#status.textContent = STATUS_LABEL[TOOL_CALL_STATUS.PENDING];\n\n head.append(label, this.#status);\n\n const argsEl = document.createElement(\"pre\");\n argsEl.className = \"tool-call-args\";\n argsEl.textContent = JSON.stringify(args, null, 2);\n\n this.element.append(head, argsEl);\n }\n\n /**\n * Flip the status pill to ``status`` and append a collapsed body holding\n * ``text`` (the JSON result, an error message, a decline notice, or a\n * server-executed note) behind a click-to-expand toggle.\n */\n settle(status: SettledStatus, text: string): void {\n this.element.setAttribute(\"data-status\", status);\n this.#status.textContent = STATUS_LABEL[status];\n\n const toggle = document.createElement(\"button\");\n toggle.type = \"button\";\n toggle.className = \"tool-call-toggle\";\n toggle.setAttribute(\"aria-expanded\", \"false\");\n toggle.textContent = RESULT_LABEL[status];\n\n const output = document.createElement(\"pre\");\n output.className = \"tool-call-result\";\n output.textContent = text;\n output.hidden = true;\n\n toggle.addEventListener(\"click\", () => {\n const expand = output.hidden;\n output.hidden = !expand;\n toggle.setAttribute(\"aria-expanded\", String(expand));\n });\n\n this.element.append(toggle, output);\n }\n}\n", "import type { Context, Message, Tool } from \"@ag-ui/core\";\nimport {\n AgUiClient,\n type AgUiClientHandlers,\n type AgUiToolCall,\n type ToolExecution,\n} from \"./agui_client.js\";\nimport { type ClientTool, ClientToolRegistry } from \"./client_tool_registry.js\";\nimport { requestConfirmation } from \"./confirmation_modal.js\";\nimport { MESSAGE_ROLE, SUBMIT_EVENT, TOOL_CALL_STATUS } from \"./constants.js\";\nimport {\n type ClientConversationStore,\n type NavigationCheckpoint,\n SessionStorageStore,\n} from \"./conversation_store.js\";\nimport { type AgentFactory, createHttpAgent } from \"./create_http_agent.js\";\nimport { isDestructive } from \"./is_destructive.js\";\nimport { isNavigates } from \"./is_navigates.js\";\nimport { createPageMapContext, type PageMap } from \"./page_map.js\";\nimport { createRouteTools, type RouteMap } from \"./route_map.js\";\nimport { createStateHookTools, type StateHook } from \"./state_hook.js\";\nimport { STYLES } from \"./styles.js\";\nimport { ToolCallCard } from \"./tool_call_card.js\";\n\n/** The role a rendered chat message takes. */\nexport type MessageRole = (typeof MESSAGE_ROLE)[keyof typeof MESSAGE_ROLE];\n\n/** `detail` shape of the {@link SUBMIT_EVENT} CustomEvent. */\nexport interface SubmitDetail {\n readonly content: string;\n}\n\n/**\n * `<ag-ui-chat>` \u2014 a framework-free chat sidebar Web Component over AG-UI.\n *\n * Owns the Shadow DOM shell (header, scrolling message list, input row),\n * builds an {@link AgUiClient} on first send (via the overridable\n * {@link agentFactory}), and renders streaming assistant text plus tool-call\n * activity. Emits a {@link SUBMIT_EVENT} for host visibility.\n *\n * The per-run frontend tool catalog and context are supplied by\n * {@link getTools} / {@link getContext}, which later phases (the tool\n * registry, DOM driver) populate.\n */\nexport class AgUiChat extends HTMLElement {\n /** Agent factory; override to inject a custom or fake agent (tests). */\n agentFactory: AgentFactory = createHttpAgent;\n\n /** Extra HTTP headers for the AG-UI endpoint (e.g. CSRF). */\n headers: Record<string, string> = {};\n\n /** When true, destructive tools execute without a confirmation modal. */\n autoConfirm = false;\n\n /**\n * Per-run frontend tool catalog provider. Defaults to the built-in\n * `route.*` tools (when a {@link routeMap} is set) plus the tools registered\n * via {@link registerTool} / {@link registerStateHook}; override to supply a\n * fully custom catalog.\n */\n getTools: () => Tool[] = () => [\n ...this.#routeTools().map((t) => ({\n name: t.name,\n description: t.description,\n parameters: t.parameters,\n })),\n ...this.#toolRegistry.tools(),\n ];\n\n /**\n * Per-run context provider. Defaults to the compact page map (when a\n * {@link getPageMap} provider is set and {@link autoInjectPageMap} is on).\n */\n getContext: () => Context[] = () => createPageMapContext(this.getPageMap, this.autoInjectPageMap);\n\n /**\n * Navigable routes the agent can jump to via the built-in `route.*` tools.\n * A compact summary also rides in each run's context.\n */\n routeMap: RouteMap = [];\n\n /**\n * Optional client-side router. When set (an SPA), `navigate_to_route` routes\n * in-page and the run loop continues; when unset (an MPA like the admin), it\n * falls back to `window.location` and the resumable-loop machinery applies.\n */\n navigate: ((path: string) => void) | null = null;\n\n /** Provider for the per-run page map; see {@link getContext}. */\n getPageMap: (() => PageMap) | null = null;\n\n /** Whether to auto-inject the page map into context each run. */\n autoInjectPageMap = true;\n\n /**\n * Persistence for the conversation + navigation checkpoint. Defaults to\n * per-tab `sessionStorage` so the chat survives full page reloads; inject a\n * server-backed store for cross-tab/device durability.\n */\n conversationStore: ClientConversationStore = new SessionStorageStore();\n\n /**\n * Builds the tool result a navigating tool resumes with after the page\n * reloads. Defaults to the landed URL; a host (e.g. the admin package) can\n * override to include a page snapshot or post-reload validation errors.\n */\n navigationResult: (checkpoint: NavigationCheckpoint) => unknown = () => ({\n navigated: true,\n url: window.location.href,\n });\n\n readonly #toolRegistry = new ClientToolRegistry();\n /** Tool-call cards awaiting execution, keyed by call id. */\n readonly #toolCards = new Map<string, ToolCallCard>();\n readonly #root: ShadowRoot;\n readonly #chat: HTMLDivElement;\n readonly #messages: HTMLDivElement;\n readonly #input: HTMLTextAreaElement;\n readonly #send: HTMLButtonElement;\n\n #client: AgUiClient | null = null;\n #streamingBubble: HTMLDivElement | null = null;\n #threadId = \"\";\n #initialMessages: readonly Message[] = [];\n\n constructor() {\n super();\n this.#root = this.attachShadow({ mode: \"open\" });\n this.#chat = document.createElement(\"div\");\n this.#messages = document.createElement(\"div\");\n this.#input = document.createElement(\"textarea\");\n this.#send = document.createElement(\"button\");\n }\n\n /** Declare a frontend tool the agent may call. */\n registerTool(tool: ClientTool): void {\n this.#toolRegistry.register(tool);\n }\n\n /** Bind a piece of host state to `read_<name>` / `set_<name>` tools. */\n registerStateHook(hook: StateHook): void {\n for (const tool of createStateHookTools(hook)) {\n this.#toolRegistry.register(tool);\n }\n }\n\n /** The built-in `route.*` tools, present only when a route map is set. */\n #routeTools(): ClientTool[] {\n if (this.routeMap.length === 0) {\n return [];\n }\n return createRouteTools(\n () => this.routeMap,\n () => this.navigate,\n );\n }\n\n /** Resolve a tool by name: built-in route tools first, then the registry. */\n #resolveTool(name: string): ClientTool | null {\n const route = this.#routeTools().find((t) => t.name === name);\n if (route !== undefined) {\n return route;\n }\n return this.#toolRegistry.has(name) ? this.#toolRegistry.get(name) : null;\n }\n\n /** The AG-UI endpoint URL, read from the `endpoint` attribute. */\n get endpoint(): string {\n return this.getAttribute(\"endpoint\") ?? \"\";\n }\n\n connectedCallback(): void {\n this.#render();\n this.#threadId = this.conversationStore.threadId();\n void this.#rehydrate();\n }\n\n /**\n * Restore the conversation from the store on mount, then \u2014 if a navigating\n * tool reloaded the page mid-run \u2014 resume the loop by supplying that tool's\n * result from the page we landed on.\n */\n async #rehydrate(): Promise<void> {\n const messages = await this.conversationStore.loadMessages(this.#threadId);\n if (messages !== null) {\n this.#initialMessages = messages;\n for (const message of messages) {\n this.#renderHistoricMessage(message);\n }\n }\n const checkpoint = this.conversationStore.loadCheckpoint(this.#threadId);\n if (checkpoint !== null) {\n await this.#resumeFrom(checkpoint);\n }\n }\n\n /** Render a restored message as a chat bubble (text turns only). */\n #renderHistoricMessage(message: Message): void {\n if (typeof message.content !== \"string\" || message.content === \"\") {\n return;\n }\n if (message.role === MESSAGE_ROLE.USER) {\n this.appendMessage(MESSAGE_ROLE.USER, message.content);\n } else if (message.role === MESSAGE_ROLE.ASSISTANT) {\n this.appendMessage(MESSAGE_ROLE.ASSISTANT, message.content);\n }\n }\n\n /** Complete the checkpointed navigating tool call and continue the run. */\n async #resumeFrom(checkpoint: NavigationCheckpoint): Promise<void> {\n this.conversationStore.saveCheckpoint(this.#threadId, null);\n const client = this.#ensureClient();\n client.addToolResult(checkpoint.toolCallId, JSON.stringify(this.navigationResult(checkpoint)));\n await client.resume();\n }\n\n /** Append a message bubble and return it. */\n appendMessage(role: MessageRole, content: string): HTMLDivElement {\n const bubble = document.createElement(\"div\");\n bubble.className = `message message--${role}`;\n bubble.textContent = content;\n this.#messages.appendChild(bubble);\n this.#messages.scrollTop = this.#messages.scrollHeight;\n return bubble;\n }\n\n #render(): void {\n const style = document.createElement(\"style\");\n style.textContent = STYLES;\n\n this.#chat.className = \"chat\";\n\n const header = document.createElement(\"div\");\n header.className = \"header\";\n header.textContent = this.getAttribute(\"title-text\") ?? \"Assistant\";\n\n this.#messages.className = \"messages\";\n\n const inputRow = document.createElement(\"div\");\n inputRow.className = \"input-row\";\n\n this.#input.className = \"input\";\n this.#input.rows = 2;\n this.#input.placeholder = \"Ask anything\u2026\";\n this.#input.addEventListener(\"keydown\", (event) => this.#onKeydown(event));\n\n this.#send.className = \"send\";\n this.#send.type = \"button\";\n this.#send.textContent = \"Send\";\n this.#send.addEventListener(\"click\", () => {\n void this.#submit();\n });\n\n inputRow.append(this.#input, this.#send);\n this.#chat.append(header, this.#messages, inputRow);\n this.#root.append(style, this.#chat);\n }\n\n #onKeydown(event: KeyboardEvent): void {\n if (event.key === \"Enter\" && !event.shiftKey) {\n event.preventDefault();\n void this.#submit();\n }\n }\n\n async #submit(): Promise<void> {\n const content = this.#input.value.trim();\n if (content === \"\") {\n return;\n }\n this.appendMessage(MESSAGE_ROLE.USER, content);\n this.#input.value = \"\";\n this.dispatchEvent(\n new CustomEvent<SubmitDetail>(SUBMIT_EVENT, {\n detail: { content },\n bubbles: true,\n composed: true,\n }),\n );\n await this.#client_send(content);\n }\n\n async #client_send(content: string): Promise<void> {\n if (this.endpoint === \"\") {\n return;\n }\n await this.#ensureClient().send(content);\n }\n\n #ensureClient(): AgUiClient {\n if (this.#client === null) {\n const agent = this.agentFactory({\n endpoint: this.endpoint,\n headers: this.headers,\n threadId: this.#threadId,\n initialMessages: this.#initialMessages,\n });\n this.#client = new AgUiClient({\n agent,\n handlers: this.#handlers(),\n getTools: () => this.getTools(),\n getContext: () => this.getContext(),\n executeTool: (call) => this.#executeTool(call),\n onPersist: (messages) => this.conversationStore.saveMessages(this.#threadId, messages),\n });\n }\n return this.#client;\n }\n\n async #executeTool(call: AgUiToolCall): Promise<ToolExecution | null> {\n const card = this.#cardFor(call);\n this.#toolCards.delete(call.id);\n const tool = this.#resolveTool(call.name);\n if (tool === null) {\n // A server-side tool the server already executed \u2014 not ours to re-run.\n card.settle(TOOL_CALL_STATUS.DONE, \"Executed on the server.\");\n return null;\n }\n if (isDestructive(tool.parameters) && !this.autoConfirm) {\n const accepted = await requestConfirmation(this.#chat, {\n toolName: call.name,\n args: call.args,\n });\n if (!accepted) {\n const message = \"User declined the action.\";\n card.settle(TOOL_CALL_STATUS.DECLINED, message);\n return { content: message };\n }\n }\n // A navigating tool reloads only without a client-side router; with a\n // host `navigate()` (SPA) it routes in-page and the loop just continues.\n const navigates = isNavigates(tool.parameters) && this.navigate === null;\n if (navigates) {\n // Checkpoint before the handler reloads the page; the history (incl.\n // this tool call) was already persisted when the run that produced it\n // settled. The result is supplied on the next mount via the resume path.\n this.conversationStore.saveCheckpoint(this.#threadId, { toolCallId: call.id });\n }\n try {\n const result = await tool.handler(call.args);\n if (navigates) {\n card.settle(TOOL_CALL_STATUS.DONE, \"Navigating\u2026\");\n return { content: \"\", halt: true };\n }\n const content = JSON.stringify(result ?? null);\n card.settle(TOOL_CALL_STATUS.DONE, content);\n return { content };\n } catch (error) {\n if (navigates) {\n // The navigation never happened; drop the dangling checkpoint.\n this.conversationStore.saveCheckpoint(this.#threadId, null);\n }\n const message = error instanceof Error ? error.message : String(error);\n card.settle(TOOL_CALL_STATUS.ERROR, message);\n return { content: `Error: ${message}`, error: message };\n }\n }\n\n #handlers(): AgUiClientHandlers {\n return {\n onRunStart: () => {\n this.#send.disabled = true;\n },\n onTextDelta: (buffer) => {\n this.#streamInto(buffer);\n },\n onTextEnd: (buffer) => {\n this.#streamInto(buffer);\n this.#streamingBubble = null;\n },\n onToolCall: (call) => {\n this.#cardFor(call);\n },\n onRunEnd: () => {\n this.#send.disabled = false;\n this.#streamingBubble = null;\n },\n onError: (message) => {\n this.appendMessage(MESSAGE_ROLE.ASSISTANT, `\u26A0\uFE0F ${message}`);\n this.#send.disabled = false;\n this.#streamingBubble = null;\n },\n };\n }\n\n #streamInto(buffer: string): void {\n if (this.#streamingBubble === null) {\n this.#streamingBubble = this.appendMessage(MESSAGE_ROLE.ASSISTANT, \"\");\n }\n this.#streamingBubble.textContent = buffer;\n this.#messages.scrollTop = this.#messages.scrollHeight;\n }\n\n /**\n * The card for ``call``, creating and appending it on first sight.\n *\n * {@link AgUiClientHandlers.onToolCall} creates the card (pending) during the\n * run; {@link #executeTool} later retrieves the same card to settle it.\n */\n #cardFor(call: AgUiToolCall): ToolCallCard {\n const existing = this.#toolCards.get(call.id);\n if (existing !== undefined) {\n return existing;\n }\n const card = new ToolCallCard(call.name, call.args);\n this.#toolCards.set(call.id, card);\n this.#messages.appendChild(card.element);\n this.#messages.scrollTop = this.#messages.scrollHeight;\n return card;\n }\n}\n", "/**\n * Visible-action animation primitives.\n *\n * These run against the **host page** DOM (not the element's shadow root) so a\n * user watches the agent type, highlight, and click at human-readable speed.\n * Each is configurable; pass small/zero durations in tests (or use fake timers).\n */\n\nconst ACCENT = \"#4f46e5\";\n\nfunction delay(ms: number): Promise<void> {\n return new Promise<void>((resolve) => {\n setTimeout(resolve, ms);\n });\n}\n\n/** An element whose `value` can be typed into. */\nexport type TextLikeElement = HTMLInputElement | HTMLTextAreaElement;\n\nexport interface TypeOptions {\n /** Milliseconds between characters. Default 35. */\n charDelayMs?: number;\n}\n\n/**\n * Clear ``el`` and type ``value`` one character at a time, firing ``input``\n * events as a real user would, then a final ``change`` event.\n */\nexport async function typeInto(\n el: TextLikeElement,\n value: string,\n options: TypeOptions = {},\n): Promise<void> {\n const charDelayMs = options.charDelayMs ?? 35;\n el.value = \"\";\n el.dispatchEvent(new Event(\"input\", { bubbles: true }));\n for (const char of value) {\n el.value += char;\n el.dispatchEvent(new Event(\"input\", { bubbles: true }));\n if (charDelayMs > 0) {\n await delay(charDelayMs);\n }\n }\n el.dispatchEvent(new Event(\"change\", { bubbles: true }));\n}\n\nexport interface HighlightClickOptions {\n /** Milliseconds to hold the highlight before clicking. Default 280. */\n highlightMs?: number;\n}\n\n/** Outline ``el``, pause so the user sees it, then click and restore. */\nexport async function highlightThenClick(\n el: HTMLElement,\n options: HighlightClickOptions = {},\n): Promise<void> {\n const highlightMs = options.highlightMs ?? 280;\n const previousOutline = el.style.outline;\n const previousOffset = el.style.outlineOffset;\n el.style.outline = `2px solid ${ACCENT}`;\n el.style.outlineOffset = \"2px\";\n await delay(highlightMs);\n el.style.outline = previousOutline;\n el.style.outlineOffset = previousOffset;\n el.click();\n}\n\n/** Scroll ``el`` to the vertical centre of the viewport. */\nexport function scrollIntoCenterView(el: HTMLElement): void {\n el.scrollIntoView({ block: \"center\", inline: \"nearest\", behavior: \"smooth\" });\n}\n\nexport interface FlashOptions {\n /** Milliseconds to hold the focus flash. Default 200. */\n flashMs?: number;\n}\n\n/** Focus ``el`` and briefly flash a ring around it. */\nexport async function focusWithFlash(el: HTMLElement, options: FlashOptions = {}): Promise<void> {\n const flashMs = options.flashMs ?? 200;\n el.focus();\n const previousShadow = el.style.boxShadow;\n el.style.boxShadow = `0 0 0 3px rgba(79, 70, 229, 0.4)`;\n await delay(flashMs);\n el.style.boxShadow = previousShadow;\n}\n", "import { AgUiChat } from \"./ag_ui_chat.js\";\nimport { ELEMENT_TAG } from \"./constants.js\";\n\n/**\n * Register the `<ag-ui-chat>` Custom Element.\n *\n * Idempotent: calling it more than once (or after another module already\n * registered the tag) is a no-op. Registration is an explicit step rather\n * than an import side effect so the package is SSR-safe and tree-shakeable.\n */\nexport function defineAgUiChat(): void {\n if (customElements.get(ELEMENT_TAG) === undefined) {\n customElements.define(ELEMENT_TAG, AgUiChat);\n }\n}\n", "import {\n focusWithFlash,\n type HighlightClickOptions,\n highlightThenClick,\n scrollIntoCenterView,\n type TextLikeElement,\n type TypeOptions,\n typeInto,\n} from \"./animations.js\";\n\n/**\n * Generic, framework-free DOM-driving primitives.\n *\n * Each operates on an element the caller has already located. Host packages\n * (e.g. `django-admin-agent`) wrap these with environment-aware lookups \u2014\n * `fill_field(name, value)` finds `#id_<name>` then calls {@link fillField}.\n */\n\nexport interface FillFieldOptions extends TypeOptions, FlashOptionsLike {}\n\ninterface FlashOptionsLike {\n flashMs?: number;\n}\n\n/** Scroll to, focus (with a flash), and type ``value`` into a text field. */\nexport async function fillField(\n el: TextLikeElement,\n value: string,\n options: FillFieldOptions = {},\n): Promise<void> {\n scrollIntoCenterView(el);\n await focusWithFlash(el, { flashMs: options.flashMs ?? 0 });\n await typeInto(el, value, options);\n}\n\n/** Scroll to, highlight, and click an element. */\nexport async function clickElement(\n el: HTMLElement,\n options: HighlightClickOptions = {},\n): Promise<void> {\n scrollIntoCenterView(el);\n await highlightThenClick(el, options);\n}\n\n/**\n * Set a `<select>` or checkbox value without typing animation, dispatching the\n * ``input`` and ``change`` events frameworks listen for.\n */\nexport function setControlValue(\n el: HTMLInputElement | HTMLSelectElement,\n value: string | boolean,\n): void {\n if (el instanceof HTMLInputElement && el.type === \"checkbox\") {\n el.checked = Boolean(value);\n } else {\n el.value = String(value);\n }\n el.dispatchEvent(new Event(\"input\", { bubbles: true }));\n el.dispatchEvent(new Event(\"change\", { bubbles: true }));\n}\n", "export const VERSION: string = \"0.1.0\";\n"],
|
|
5
|
+
"mappings": "6FACA,IAAMA,EAAY,CAAC,EACnB,QAASC,EAAI,EAAGA,EAAI,IAAK,EAAEA,EACvBD,EAAU,MAAMC,EAAI,KAAO,SAAS,EAAE,EAAE,MAAM,CAAC,CAAC,EAE7C,SAASC,GAAgBC,EAAKC,EAAS,EAAG,CAC7C,OAAQJ,EAAUG,EAAIC,EAAS,CAAC,CAAC,EAC7BJ,EAAUG,EAAIC,EAAS,CAAC,CAAC,EACzBJ,EAAUG,EAAIC,EAAS,CAAC,CAAC,EACzBJ,EAAUG,EAAIC,EAAS,CAAC,CAAC,EACzB,IACAJ,EAAUG,EAAIC,EAAS,CAAC,CAAC,EACzBJ,EAAUG,EAAIC,EAAS,CAAC,CAAC,EACzB,IACAJ,EAAUG,EAAIC,EAAS,CAAC,CAAC,EACzBJ,EAAUG,EAAIC,EAAS,CAAC,CAAC,EACzB,IACAJ,EAAUG,EAAIC,EAAS,CAAC,CAAC,EACzBJ,EAAUG,EAAIC,EAAS,CAAC,CAAC,EACzB,IACAJ,EAAUG,EAAIC,EAAS,EAAE,CAAC,EAC1BJ,EAAUG,EAAIC,EAAS,EAAE,CAAC,EAC1BJ,EAAUG,EAAIC,EAAS,EAAE,CAAC,EAC1BJ,EAAUG,EAAIC,EAAS,EAAE,CAAC,EAC1BJ,EAAUG,EAAIC,EAAS,EAAE,CAAC,EAC1BJ,EAAUG,EAAIC,EAAS,EAAE,CAAC,GAAG,YAAY,CACjD,CC1BA,IAAIC,GACEC,GAAQ,IAAI,WAAW,EAAE,EAChB,SA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MAAM,QAAUO,EACnBP,EAAG,MAAM,cAAgBQ,EACzBR,EAAG,MAAM,CACX,CAGO,SAASS,GAAqBT,EAAuB,CAC1DA,EAAG,eAAe,CAAE,MAAO,SAAU,OAAQ,UAAW,SAAU,QAAS,CAAC,CAC9E,CAQA,eAAsBU,GAAeV,EAAiBE,EAAwB,CAAC,EAAkB,CAC/F,IAAMS,EAAUT,EAAQ,SAAW,IACnCF,EAAG,MAAM,EACT,IAAMY,EAAiBZ,EAAG,MAAM,UAChCA,EAAG,MAAM,UAAY,mCACrB,MAAMJ,GAAMe,CAAO,EACnBX,EAAG,MAAM,UAAYY,CACvB,CC3EO,SAASC,IAAuB,CACjC,eAAe,IAAIC,EAAW,IAAM,QACtC,eAAe,OAAOA,GAAaC,EAAQ,CAE/C,CCWA,eAAsBC,GACpBC,EACAC,EACAC,EAA4B,CAAC,EACd,CACfC,GAAqBH,CAAE,EACvB,MAAMI,GAAeJ,EAAI,CAAE,QAASE,EAAQ,SAAW,CAAE,CAAC,EAC1D,MAAMG,GAASL,EAAIC,EAAOC,CAAO,CACnC,CAGA,eAAsBI,GACpBN,EACAE,EAAiC,CAAC,EACnB,CACfC,GAAqBH,CAAE,EACvB,MAAMO,GAAmBP,EAAIE,CAAO,CACtC,CAMO,SAASM,GACdR,EACAC,EACM,CACFD,aAAc,kBAAoBA,EAAG,OAAS,WAChDA,EAAG,QAAU,EAAQC,EAErBD,EAAG,MAAQ,OAAOC,CAAK,EAEzBD,EAAG,cAAc,IAAI,MAAM,QAAS,CAAE,QAAS,EAAK,CAAC,CAAC,EACtDA,EAAG,cAAc,IAAI,MAAM,SAAU,CAAE,QAAS,EAAK,CAAC,CAAC,CACzD,CC3DO,IAAMS,GAAkB",
|
|
6
|
+
"names": ["byteToHex", "i", "unsafeStringify", "arr", "offset", "getRandomValues", "rnds8", "rng", "randomUUID", "native_default", "v4", "options", "buf", "offset", "native_default", "rnds", "rng", "i", "unsafeStringify", "v4_default", "external_exports", "__export", "BRAND", "DIRTY", "EMPTY_PATH", "INVALID", "NEVER", "OK", "ParseStatus", "ZodType", "ZodAny", "ZodArray", "ZodBigInt", "ZodBoolean", "ZodBranded", "ZodCatch", "ZodDate", "ZodDefault", "ZodDiscriminatedUnion", "ZodEffects", "ZodEnum", "ZodError", "ZodFirstPartyTypeKind", "ZodFunction", "ZodIntersection", "ZodIssueCode", "ZodLazy", "ZodLiteral", "ZodMap", "ZodNaN", "ZodNativeEnum", "ZodNever", "ZodNull", "ZodNullable", "ZodNumber", "ZodObject", "ZodOptional", "ZodParsedType", "ZodPipeline", "ZodPromise", "ZodReadonly", "ZodRecord", "ZodSet", "ZodString", "ZodSymbol", "ZodTuple", "ZodUndefined", "ZodUnion", "ZodUnknown", "ZodVoid", "addIssueToContext", "anyType", "arrayType", "bigIntType", "booleanType", "coerce", "custom", "dateType", "datetimeRegex", "en_default", "discriminatedUnionType", "effectsType", "enumType", "functionType", "getErrorMap", "getParsedType", "instanceOfType", "intersectionType", "isAborted", "isAsync", "isDirty", "isValid", "late", "lazyType", "literalType", "makeIssue", "mapType", "nanType", "nativeEnumType", "neverType", "nullType", "nullableType", "numberType", "objectType", "objectUtil", "oboolean", "onumber", "optionalType", "ostring", "pipelineType", "preprocessType", "promiseType", "quotelessJson", "recordType", "setType", "setErrorMap", "strictObjectType", "stringType", "symbolType", "tupleType", "undefinedType", "unionType", "unknownType", "util", "voidType", "util", "_", "assertIs", "_arg", "assertNever", "_x", "items", "obj", "item", "validKeys", "k", "filtered", "e", "object", "keys", "key", "arr", "checker", "val", "joinValues", "array", "separator", "value", "objectUtil", "first", "second", "ZodParsedType", "getParsedType", "data", "ZodIssueCode", "util", "quotelessJson", "obj", "ZodError", "_ZodError", "issues", "sub", "subs", "actualProto", "_mapper", "mapper", "issue", "fieldErrors", "processError", "error", "curr", "i", "el", "value", "formErrors", "firstEl", "errorMap", "issue", "_ctx", "message", "ZodIssueCode", "ZodParsedType", "util", "en_default", "overrideErrorMap", "en_default", "setErrorMap", "map", "overrideErrorMap", "getErrorMap", "makeIssue", "params", "data", "path", "errorMaps", "issueData", "fullPath", "fullIssue", "errorMessage", "maps", "m", "map", "EMPTY_PATH", "addIssueToContext", "ctx", "overrideMap", "getErrorMap", "issue", "en_default", "x", "ParseStatus", "_ParseStatus", "status", "results", "arrayValue", "INVALID", "pairs", "syncPairs", "pair", "key", "value", "finalObject", "DIRTY", "OK", "isAborted", "isDirty", "isValid", "isAsync", "errorUtil", "message", "ParseInputLazyPath", "parent", "value", "path", "key", "handleResult", "ctx", "result", "isValid", "error", "ZodError", "processCreateParams", "params", "errorMap", "invalid_type_error", "required_error", "description", "iss", "message", "ZodType", "input", "getParsedType", "ParseStatus", "isAsync", "data", "err", "maybeAsyncResult", "check", "getIssueProperties", "val", "setError", "ZodIssueCode", "refinementData", "refinement", "ZodEffects", "ZodFirstPartyTypeKind", "def", "ZodOptional", "ZodNullable", "ZodArray", "ZodPromise", "option", "ZodUnion", "incoming", "ZodIntersection", "transform", "defaultValueFunc", "ZodDefault", "ZodBranded", "catchValueFunc", "ZodCatch", "This", "target", "ZodPipeline", "ZodReadonly", "cuidRegex", "cuid2Regex", "ulidRegex", "uuidRegex", "nanoidRegex", "jwtRegex", "durationRegex", "emailRegex", "_emojiRegex", "emojiRegex", "ipv4Regex", "ipv4CidrRegex", "ipv6Regex", "ipv6CidrRegex", "base64Regex", "base64urlRegex", "dateRegexSource", "dateRegex", "timeRegexSource", "args", "secondsRegexSource", "secondsQuantifier", "timeRegex", "datetimeRegex", "regex", "opts", "isValidIP", "ip", "version", "isValidJWT", "jwt", "alg", "header", "base64", "decoded", "isValidCidr", "ZodString", "_ZodString", "ZodParsedType", "addIssueToContext", "INVALID", "status", "tooBig", "tooSmall", "util", "validation", "errorUtil", "options", "minLength", "maxLength", "len", "ch", "min", "max", "floatSafeRemainder", "step", "valDecCount", "stepDecCount", "decCount", "valInt", "stepInt", "ZodNumber", "_ZodNumber", "kind", "inclusive", "ZodBigInt", "_ZodBigInt", "ZodBoolean", "OK", "ZodDate", "_ZodDate", "minDate", "maxDate", "ZodSymbol", "ZodUndefined", "ZodNull", "ZodAny", "ZodUnknown", "ZodNever", "ZodVoid", "_ZodArray", "item", "i", "schema", "deepPartialify", "ZodObject", "newShape", "fieldSchema", "ZodTuple", "_ZodObject", "shape", "keys", "shapeKeys", "extraKeys", "pairs", "keyValidator", "unknownKeys", "catchall", "syncPairs", "pair", "issue", "defaultError", "augmentation", "merging", "index", "mask", "newField", "createZodEnum", "handleResults", "results", "unionErrors", "childCtx", "dirty", "issues", "types", "getDiscriminator", "type", "ZodLazy", "ZodLiteral", "ZodEnum", "ZodNativeEnum", "ZodDiscriminatedUnion", "_ZodDiscriminatedUnion", "discriminator", "discriminatorValue", "optionsMap", "discriminatorValues", "mergeValues", "a", "b", "aType", "bType", "bKeys", "sharedKeys", "newObj", "sharedValue", "newArray", "itemA", "itemB", "handleParsed", "parsedLeft", "parsedRight", "isAborted", "merged", "isDirty", "left", "right", "_ZodTuple", "items", "itemIndex", "x", "rest", "schemas", "ZodRecord", "_ZodRecord", "keyType", "valueType", "first", "second", "third", "ZodMap", "finalMap", "ZodSet", "_ZodSet", "finalizeSet", "elements", "parsedSet", "element", "minSize", "maxSize", "size", "ZodFunction", "_ZodFunction", "makeArgsIssue", "makeIssue", "getErrorMap", "en_default", "makeReturnsIssue", "returns", "fn", "me", "parsedArgs", "e", "parsedReturns", "returnType", "func", "getter", "values", "_ZodEnum", "expectedValues", "enumValues", "newDef", "opt", "nativeEnumValues", "promisified", "effect", "checkCtx", "arg", "processed", "DIRTY", "executeRefinement", "acc", "inner", "base", "preprocess", "ZodOptional", "ZodType", "input", "ZodParsedType", "OK", "type", "params", "ZodFirstPartyTypeKind", "processCreateParams", "ZodNullable", "ZodDefault", "ctx", "data", "ZodCatch", "newCtx", "result", "isAsync", "ZodError", "ZodNaN", "addIssueToContext", "ZodIssueCode", "INVALID", "BRAND", "ZodBranded", "ZodPipeline", "_ZodPipeline", "status", "inResult", "DIRTY", "a", "b", "ZodReadonly", "freeze", "isValid", "cleanParams", "p", "custom", "check", "_params", "fatal", "ZodAny", "r", "_fatal", "late", "ZodObject", "ZodFirstPartyTypeKind", "instanceOfType", "cls", "params", "custom", "data", "stringType", "ZodString", "numberType", "ZodNumber", "nanType", "ZodNaN", "bigIntType", "ZodBigInt", "booleanType", "ZodBoolean", "dateType", "ZodDate", "symbolType", "ZodSymbol", "undefinedType", "ZodUndefined", "nullType", "ZodNull", "anyType", "ZodAny", "unknownType", "ZodUnknown", "neverType", "ZodNever", "voidType", "ZodVoid", "arrayType", "ZodArray", "objectType", "ZodObject", "strictObjectType", "unionType", "ZodUnion", "discriminatedUnionType", "ZodDiscriminatedUnion", "intersectionType", "ZodIntersection", "tupleType", "ZodTuple", "recordType", "ZodRecord", "mapType", "ZodMap", "setType", "ZodSet", "functionType", "ZodFunction", "lazyType", "ZodLazy", "literalType", "ZodLiteral", "enumType", "ZodEnum", "nativeEnumType", "ZodNativeEnum", "promiseType", "ZodPromise", "effectsType", "ZodEffects", "optionalType", "ZodOptional", "nullableType", "ZodNullable", "preprocessType", "pipelineType", "ZodPipeline", "ostring", "onumber", "oboolean", "coerce", "arg", "NEVER", "INVALID", "FunctionCallSchema", "external_exports", "ToolCallSchema", "BaseMessageSchema", "TextInputContentSchema", "InputContentDataSourceSchema", "InputContentUrlSourceSchema", "InputContentSourceSchema", "ImageInputContentSchema", "AudioInputContentSchema", "VideoInputContentSchema", "DocumentInputContentSchema", "LegacyBinaryInputContentObjectSchema", "external_exports", "ensureBinaryPayload", "value", "ctx", "BinaryInputContentSchema", "InputContentBaseSchema", "TextInputContentSchema", "ImageInputContentSchema", "AudioInputContentSchema", "VideoInputContentSchema", "DocumentInputContentSchema", "InputContentSchema", "DeveloperMessageSchema", "BaseMessageSchema", "SystemMessageSchema", "AssistantMessageSchema", "ToolCallSchema", "UserMessageSchema", "ToolMessageSchema", "ActivityMessageSchema", "ReasoningMessageSchema", "MessageSchema", "RoleSchema", "ContextSchema", "ToolSchema", "InterruptSchema", "ResumeEntrySchema", "RunAgentInputSchema", "StateSchema", "AGUIError", "message", "AGUIConnectNotImplementedError", "SubAgentInfoSchema", "IdentityCapabilitiesSchema", "TransportCapabilitiesSchema", "ToolsCapabilitiesSchema", "OutputCapabilitiesSchema", "StateCapabilitiesSchema", "MultiAgentCapabilitiesSchema", "ReasoningCapabilitiesSchema", "MultimodalInputCapabilitiesSchema", "MultimodalOutputCapabilitiesSchema", "MultimodalCapabilitiesSchema", "ExecutionCapabilitiesSchema", "HumanInTheLoopCapabilitiesSchema", "AgentCapabilitiesSchema", "TextMessageRoleSchema", "EventType", "BaseEventSchema", "TextMessageStartEventSchema", "TextMessageContentEventSchema", "TextMessageEndEventSchema", "TextMessageChunkEventSchema", "ThinkingTextMessageStartEventSchema", "ThinkingTextMessageContentEventSchema", "ThinkingTextMessageEndEventSchema", "ToolCallStartEventSchema", "ToolCallArgsEventSchema", "ToolCallEndEventSchema", "ToolCallResultEventSchema", "ToolCallChunkEventSchema", "ThinkingStartEventSchema", "ThinkingEndEventSchema", "StateSnapshotEventSchema", "StateDeltaEventSchema", "MessagesSnapshotEventSchema", "ActivitySnapshotEventSchema", "ActivityDeltaEventSchema", "RawEventSchema", "CustomEventSchema", "RunStartedEventSchema", "RunFinishedSuccessOutcomeSchema", "RunFinishedInterruptOutcomeSchema", "RunFinishedOutcomeSchema", "RunFinishedEventSchema", "v", "RunErrorEventSchema", "StepStartedEventSchema", "StepFinishedEventSchema", "ReasoningEncryptedValueSubtypeSchema", "ReasoningStartEventSchema", "ReasoningMessageStartEventSchema", "ReasoningMessageContentEventSchema", "ReasoningMessageEndEventSchema", "ReasoningMessageChunkEventSchema", "ReasoningEndEventSchema", "ReasoningEncryptedValueEventSchema", "EventSchemas", "core_exports", "__export", "JsonPatchError", "_areEquals", "applyOperation", "applyPatch", "applyReducer", "deepClone", "getValueByPointer", "validate", "validator", "__extends", "extendStatics", "d", "b", "p", "__", "_hasOwnProperty", "hasOwnProperty", "obj", "key", "_objectKeys", "keys_1", "k", "keys", "i", "_deepClone", "isInteger", "str", "len", "charCode", "escapePathComponent", "path", "unescapePathComponent", "hasUndefined", "obj", "i_1", "len", "objKeys", "_objectKeys", "objKeysLength", "i", "patchErrorMessageFormatter", "message", "args", "messageParts", "key", "value", "PatchError", "_super", "__extends", "name", "index", "operation", "tree", "_newTarget", "_this", "JsonPatchError", "PatchError", "deepClone", "_deepClone", "objOps", "obj", "key", "document", "removed", "getValueByPointer", "originalValue", "applyOperation", "valueToCopy", "_areEquals", "arrOps", "arr", "i", "isInteger", "removedList", "pointer", "getOriginalDestination", "operation", "validateOperation", "mutateDocument", "banPrototypeModifications", "index", "validator", "returnValue", "path", "keys", "t", "len", "existingPathFragment", "validateFunction", "unescapePathComponent", "applyPatch", "patch", "results", "length_1", "applyReducer", "operationResult", "hasUndefined", "pathLen", "existingPathLen", "existingValue", "error", "validate", "sequence", "externalValidator", "e", "a", "b", "arrA", "arrB", "length", "duplex_exports", "__export", "compare", "generate", "observe", "unobserve", "beforeDict", "Mirror", "obj", "ObserverInfo", "callback", "observer", "getMirror", "getObserverFromMirror", "mirror", "removeObserverFromMirror", "unobserve", "root", "observe", "patches", "observerInfo", "_deepClone", "dirtyCheck", "generate", "fastCheck", "invertible", "_generate", "applyPatch", "temp", "path", "newKeys", "_objectKeys", "oldKeys", "changed", "deleted", "t", "key", "oldVal", "hasOwnProperty", "newVal", "escapePathComponent", "compare", "tree1", "tree2", "fast_json_patch_default", "core_exports", "duplex_exports", "PatchError", "_deepClone", "escapePathComponent", "unescapePathComponent", "extendStatics", "d", "b", "p", "__extends", "__", "__awaiter", "thisArg", "_arguments", "P", "generator", "adopt", "value", "resolve", "reject", "fulfilled", "step", "e", "rejected", "result", "__generator", "body", "_", "t", "f", "y", "g", "verb", "n", "v", "op", "__values", "o", "s", "m", "i", "__read", "n", "r", "ar", "e", "error", "__spreadArray", "to", "from", "pack", "i", "l", "ar", "__await", "v", "__asyncGenerator", "thisArg", "_arguments", "generator", "g", "q", "verb", "awaitReturn", "f", "reject", "n", "a", "b", "resume", "step", "e", "settle", "r", "fulfill", "value", "__asyncValues", "o", "m", "i", "__values", "verb", "n", "v", "resolve", "reject", "settle", "d", "isFunction", "value", "createErrorClass", "createImpl", "_super", "instance", "ctorFunc", "UnsubscriptionError", "createErrorClass", "_super", "errors", "err", "i", "arrRemove", "arr", "item", "index", "Subscription", "initialTeardown", "errors", "_parentage", "_parentage_1", "__values", "_parentage_1_1", "parent_1", "initialFinalizer", "isFunction", "e", "UnsubscriptionError", "_finalizers", "_finalizers_1", "_finalizers_1_1", "finalizer", "execFinalizer", "err", "__spreadArray", "__read", "teardown", "_a", "parent", "arrRemove", "empty", "EMPTY_SUBSCRIPTION", "Subscription", "isSubscription", "value", "isFunction", "execFinalizer", "finalizer", "config", "timeoutProvider", "handler", "timeout", "args", "_i", "delegate", "__spreadArray", "__read", "handle", "reportUnhandledError", "err", "timeoutProvider", "onUnhandledError", "config", "noop", "COMPLETE_NOTIFICATION", "createNotification", "errorNotification", "error", "nextNotification", "value", "kind", "context", "errorContext", "cb", "config", "isRoot", "_a", "errorThrown", "error", "captureError", "err", "Subscriber", "_super", "__extends", "destination", "_this", "isSubscription", "EMPTY_OBSERVER", "next", "error", "complete", "SafeSubscriber", "value", "handleStoppedNotification", "nextNotification", "err", "errorNotification", "COMPLETE_NOTIFICATION", "Subscription", "_bind", "bind", "fn", "thisArg", "ConsumerObserver", "partialObserver", "value", "error", "handleUnhandledError", "err", "SafeSubscriber", "_super", "__extends", "observerOrNext", "complete", "_this", "isFunction", "context_1", "config", "Subscriber", "handleUnhandledError", "error", "config", "captureError", "reportUnhandledError", "defaultErrorHandler", "err", "handleStoppedNotification", "notification", "subscriber", "onStoppedNotification", "timeoutProvider", "EMPTY_OBSERVER", "noop", "observable", "identity", "x", "pipe", "fns", "_i", "pipeFromArray", "identity", "input", "prev", "fn", "Observable", "subscribe", "operator", "observable", "observerOrNext", "error", "complete", "_this", "subscriber", "isSubscriber", "SafeSubscriber", "errorContext", "_a", "source", "sink", "err", "next", "promiseCtor", "getPromiseCtor", "resolve", "reject", "value", "operations", "_i", "pipeFromArray", "x", "getPromiseCtor", "promiseCtor", "_a", "config", "isObserver", "value", "isFunction", "isSubscriber", "Subscriber", "isSubscription", "hasLift", "source", "isFunction", "operate", "init", "liftedSource", "err", "createOperatorSubscriber", "destination", "onNext", "onComplete", "onError", "onFinalize", "OperatorSubscriber", "_super", "__extends", "shouldUnsubscribe", "_this", "value", "err", "closed_1", "_a", "Subscriber", "ObjectUnsubscribedError", "createErrorClass", "_super", "Subject", "_super", "__extends", "_this", "operator", "subject", "AnonymousSubject", "ObjectUnsubscribedError", "value", "errorContext", "_b", "__values", "_c", "observer", "err", "observers", "_a", "subscriber", "hasError", "isStopped", "EMPTY_SUBSCRIPTION", "Subscription", "arrRemove", "thrownError", "observable", "Observable", "destination", "source", "AnonymousSubject", "_super", "__extends", "destination", "source", "_this", "value", "_b", "_a", "err", "subscriber", "EMPTY_SUBSCRIPTION", "Subject", "dateTimestampProvider", "ReplaySubject", "_super", "__extends", "_bufferSize", "_windowTime", "_timestampProvider", "dateTimestampProvider", "_this", "value", "_a", "isStopped", "_buffer", "_infiniteTimeWindow", "subscriber", "subscription", "copy", "i", "adjustedBufferSize", "now", "last", "Subject", "EMPTY", "Observable", "subscriber", "isScheduler", "value", "isFunction", "last", "arr", "popScheduler", "args", "isScheduler", "last", "isArrayLike", "x", "isPromise", "value", "isFunction", "isInteropObservable", "input", "isFunction", "observable", "isAsyncIterable", "obj", "isFunction", "createInvalidObservableTypeError", "input", "getSymbolIterator", "iterator", "isIterable", "input", "isFunction", "iterator", "readableStreamLikeToAsyncGenerator", "readableStream", "reader", "__await", "_a", "_b", "value", "done", "isReadableStreamLike", "obj", "isFunction", "innerFrom", "input", "Observable", "isInteropObservable", "fromInteropObservable", "isArrayLike", "fromArrayLike", "isPromise", "fromPromise", "isAsyncIterable", "fromAsyncIterable", "isIterable", "fromIterable", "isReadableStreamLike", "fromReadableStreamLike", "createInvalidObservableTypeError", "obj", "subscriber", "obs", "observable", "isFunction", "array", "i", "promise", "value", "err", "reportUnhandledError", "iterable", "iterable_1", "__values", "iterable_1_1", "asyncIterable", "process", "readableStream", "readableStreamLikeToAsyncGenerator", "asyncIterable_1", "__asyncValues", "asyncIterable_1_1", "executeSchedule", "parentSubscription", "scheduler", "work", "delay", "repeat", "scheduleSubscription", "observeOn", "scheduler", "delay", "operate", "source", "subscriber", "createOperatorSubscriber", "value", "executeSchedule", "err", "subscribeOn", "scheduler", "delay", "operate", "source", "subscriber", "scheduleObservable", "input", "scheduler", "innerFrom", "subscribeOn", "observeOn", "schedulePromise", "input", "scheduler", "innerFrom", "subscribeOn", "observeOn", "scheduleArray", "input", "scheduler", "Observable", "subscriber", "i", "scheduleIterable", "input", "scheduler", "Observable", "subscriber", "iterator", "executeSchedule", "value", "done", "_a", "err", "isFunction", "scheduleAsyncIterable", "input", "scheduler", "Observable", "subscriber", "executeSchedule", "iterator", "result", "scheduleReadableStreamLike", "input", "scheduler", "scheduleAsyncIterable", "readableStreamLikeToAsyncGenerator", "scheduled", "input", "scheduler", "isInteropObservable", "scheduleObservable", "isArrayLike", "scheduleArray", "isPromise", "schedulePromise", "isAsyncIterable", "scheduleAsyncIterable", "isIterable", "scheduleIterable", "isReadableStreamLike", "scheduleReadableStreamLike", "createInvalidObservableTypeError", "from", "input", "scheduler", "scheduled", "innerFrom", "of", "args", "_i", "scheduler", "popScheduler", "from", "throwError", "errorOrErrorFactory", "scheduler", "errorFactory", "isFunction", "init", "subscriber", "Observable", "EmptyError", "createErrorClass", "_super", "lastValueFrom", "source", "config", "hasConfig", "resolve", "reject", "_hasValue", "_value", "value", "EmptyError", "map", "project", "thisArg", "operate", "source", "subscriber", "index", "createOperatorSubscriber", "value", "mergeInternals", "source", "subscriber", "project", "concurrent", "onBeforeNext", "expand", "innerSubScheduler", "additionalFinalizer", "buffer", "active", "index", "isComplete", "checkComplete", "outerNext", "value", "doInnerSub", "innerComplete", "innerFrom", "createOperatorSubscriber", "innerValue", "bufferedValue", "executeSchedule", "err", "mergeMap", "project", "resultSelector", "concurrent", "isFunction", "a", "i", "map", "b", "ii", "innerFrom", "operate", "source", "subscriber", "mergeInternals", "mergeAll", "concurrent", "mergeMap", "identity", "defer", "observableFactory", "Observable", "subscriber", "innerFrom", "catchError", "selector", "operate", "source", "subscriber", "innerSub", "syncUnsub", "handledResult", "createOperatorSubscriber", "err", "innerFrom", "concatMap", "project", "resultSelector", "isFunction", "mergeMap", "defaultIfEmpty", "defaultValue", "operate", "source", "subscriber", "hasValue", "createOperatorSubscriber", "value", "finalize", "callback", "operate", "source", "subscriber", "switchMap", "project", "resultSelector", "operate", "source", "subscriber", "innerSubscriber", "index", "isComplete", "checkComplete", "createOperatorSubscriber", "value", "innerIndex", "outerIndex", "innerFrom", "innerValue", "takeUntil", "notifier", "operate", "source", "subscriber", "innerFrom", "createOperatorSubscriber", "noop", "tap", "observerOrNext", "error", "complete", "tapObserver", "isFunction", "operate", "source", "subscriber", "_a", "isUnsub", "createOperatorSubscriber", "value", "err", "_b", "identity", "isWhitespace", "char", "untruncateJson", "json", "contextStack", "position", "respawnPosition", "respawnStackLength", "respawnReason", "push", "context", "replace", "setRespawn", "reason", "clearRespawn", "pop", "dontConsumeCharacter", "startAny", "length", "result", "finishWord", "word", "i", "varint64read", "lowBits", "highBits", "shift", "b", "middleByte", "varint64write", "lo", "hi", "bytes", "i", "hasNext", "byte", "splitBits", "hasMoreBits", "TWO_PWR_32_DBL", "int64FromString", "dec", "minus", "base", "add1e6digit", "begin", "end", "digit1e6", "negate", "newBits", "int64ToString", "bits", "negative", "result", "uInt64ToString", "toUnsigned", "low", "mid", "high", "digitA", "digitB", "digitC", "decimalFrom1e7WithLeadingZeros", "digit1e7", "partial", "varint32write", "value", "varint32read", "readBytes", "protoInt64", "makeInt64Support", "dv", "MIN", "MAX", "UMIN", "UMAX", "value", "bi", "lo", "hi", "assertInt64String", "assertUInt64String", "int64FromString", "int64ToString", "uInt64ToString", "symbol", "getTextEncoding", "symbol", "te", "td", "tdStrict", "text", "bytes", "strict", "WireType", "FLOAT32_MAX", "FLOAT32_MIN", "UINT32_MAX", "INT32_MAX", "INT32_MIN", "BinaryWriter", "encodeUtf8", "getTextEncoding", "len", "i", "bytes", "offset", "chunk", "prev", "fieldNo", "type", "value", "assertUInt32", "assertInt32", "varint32write", "assertFloat32", "view", "tc", "protoInt64", "varint64write", "sign", "lo", "hi", "BinaryReader", "buf", "decodeUtf8", "varint64read", "varint32read", "start", "tag", "bytesRead", "wireType", "fn", "wt", "zze", "s", "strict", "arg", "o", "NullValue", "createBaseStruct", "Struct", "message", "writer", "BinaryWriter", "key", "value", "Struct_FieldsEntry", "input", "length", "reader", "BinaryReader", "end", "tag", "entry1", "base", "object", "acc", "struct", "createBaseStruct_FieldsEntry", "Value", "createBaseValue", "ListValue", "result", "createBaseListValue", "v", "e", "array", "JsonPatchOperationType", "createBaseJsonPatchOperation", "JsonPatchOperation", "createBaseToolCall", "ToolCall", "ToolCall_Function", "createBaseToolCall_Function", "createBaseInputContentDataSource", "InputContentDataSource", "createBaseInputContentUrlSource", "InputContentUrlSource", "createBaseInputContentSource", "InputContentSource", "createBaseTextInputPart", "TextInputPart", "createBaseImageInputPart", "ImageInputPart", "createBaseAudioInputPart", "AudioInputPart", "createBaseVideoInputPart", "VideoInputPart", "createBaseDocumentInputPart", "DocumentInputPart", "createBaseInputContent", "InputContent", "createBaseMessage", "Message", "createBaseInterrupt", "Interrupt", "EventType", "createBaseBaseEvent", "BaseEvent", "longToNumber", "createBaseTextMessageStartEvent", "TextMessageStartEvent", "BaseEvent$1", "createBaseTextMessageContentEvent", "TextMessageContentEvent", "createBaseTextMessageEndEvent", "TextMessageEndEvent", "createBaseToolCallStartEvent", "ToolCallStartEvent", "createBaseToolCallArgsEvent", "ToolCallArgsEvent", "createBaseToolCallEndEvent", "ToolCallEndEvent", "createBaseStateSnapshotEvent", "StateSnapshotEvent", "createBaseStateDeltaEvent", "StateDeltaEvent", "createBaseMessagesSnapshotEvent", "MessagesSnapshotEvent", "createBaseRawEvent", "RawEvent", "createBaseCustomEvent", "CustomEvent", "createBaseRunStartedEvent", "RunStartedEvent", "createBaseRunFinishedEvent", "RunFinishedEvent", "createBaseRunErrorEvent", "RunErrorEvent", "createBaseStepStartedEvent", "StepStartedEvent", "createBaseStepFinishedEvent", "StepFinishedEvent", "createBaseTextMessageChunkEvent", "TextMessageChunkEvent", "createBaseToolCallChunkEvent", "ToolCallChunkEvent", "createBaseEvent", "Event", "int64", "num", "fromProtoSource", "source", "fromProtoContentPart", "part", "decode", "data", "event", "Event", "decoded", "value", "protoEvents.EventType", "EventType", "message", "untypedMessage", "contentParts", "part", "fromProtoContentPart", "runFinished", "wireOutcome", "wireInterrupts", "operation", "protoPatch.JsonPatchOperationType", "key", "EventSchemas", "AGUI_MEDIA_TYPE", "semver", "validateAndParse", "version", "match", "isWildcard", "s", "tryParse", "v", "n", "forceType", "a", "b", "compareStrings", "ap", "bp", "compareSegments", "i", "r", "compareVersions", "v1", "v2", "n1", "validateAndParse", "n2", "p1", "p2", "r", "compareSegments", "D", "O", "uuidv4", "k", "A", "n", "r", "i", "a", "o", "s", "c", "l", "u", "d", "t", "e", "j", "M", "N", "P", "oe", "F", "f", "of", "EMPTY", "concatMap", "EventType", "untruncateJson", "fast_json_patch_default", "mergeAll", "defaultIfEmpty", "I", "p", "m", "mergeMap", "throwError", "AGUIError", "L", "R", "defer", "from", "switchMap", "Observable", "z", "Subject", "B", "decode", "V", "ReplaySubject", "AGUI_MEDIA_TYPE", "EventSchemas", "H", "external_exports", "se", "ce", "le", "ue", "de", "fe", "pe", "me", "he", "ge", "_e", "ve", "U", "ye", "W", "finalize", "G", "K", "W", "n", "D", "r", "i", "ReplaySubject", "F", "e", "concatMap", "q", "Ce", "n", "e", "J", "K", "r", "i", "Y", "X", "Z", "we", "Te", "Ee", "map", "O", "EventType", "De", "Oe", "ke", "Ae", "je", "Me", "Ne", "packageJson.version", "j", "P", "t", "a", "uuidv4", "D", "compareVersions", "q", "Subject", "s", "lastValueFrom", "pipe", "W", "I", "takeUntil", "catchError", "finalize", "of", "c", "AGUIConnectNotImplementedError", "d", "defer", "EMPTY", "f", "F", "tap", "AGUIError", "G", "A", "from", "U", "Pe", "V", "R", "ELEMENT_TAG", "SUBMIT_EVENT", "MESSAGE_ROLE", "X_DESTRUCTIVE_KEY", "X_NAVIGATES_KEY", "MAX_TOOL_ROUNDS", "TOOL_CALL_STATUS", "AgUiClient", "#agent", "#handlers", "#getTools", "#getContext", "#executeTool", "#onPersist", "config", "content", "O", "#run", "toolCallId", "#runLoop", "error", "round", "MAX_TOOL_ROUNDS", "pending", "#buildSubscriber", "executed", "call", "result", "h", "textMessageBuffer", "event", "toolCallName", "toolCallArgs", "ClientToolRegistry", "#tools", "tool", "name", "requestConfirmation", "host", "request", "resolve", "overlay", "dialog", "title", "body", "args", "actions", "cancel", "confirm", "close", "accepted", "event", "THREAD_KEY", "MESSAGES_PREFIX", "CHECKPOINT_PREFIX", "SessionStorageStore", "existing", "id", "O", "threadId", "#readJson", "messages", "checkpoint", "key", "raw", "createHttpAgent", "options", "Pe", "url", "init", "isDestructive", "parameters", "X_DESTRUCTIVE_KEY", "isNavigates", "parameters", "X_NAVIGATES_KEY", "createPageMapContext", "getPageMap", "autoInject", "withQuery", "path", "params", "usp", "key", "value", "query", "createRouteTools", "getRouteMap", "getNavigate", "X_NAVIGATES_KEY", "args", "routeId", "route", "r", "navigate", "createStateHookTools", "hook", "tools", "write", "X_DESTRUCTIVE_KEY", "args", "STYLES", "STATUS_LABEL", "TOOL_CALL_STATUS", "RESULT_LABEL", "ToolCallCard", "#status", "name", "args", "head", "label", "argsEl", "status", "text", "toggle", "output", "expand", "AgUiChat", "createHttpAgent", "#routeTools", "#toolRegistry", "createPageMapContext", "SessionStorageStore", "ClientToolRegistry", "#toolCards", "#root", "#chat", "#messages", "#input", "#send", "#client", "#streamingBubble", "#threadId", "#initialMessages", "tool", "hook", "createStateHookTools", "createRouteTools", "#resolveTool", "name", "route", "t", "#render", "#rehydrate", "messages", "message", "#renderHistoricMessage", "checkpoint", "#resumeFrom", "MESSAGE_ROLE", "client", "#ensureClient", "role", "content", "bubble", "style", "STYLES", "header", "inputRow", "event", "#onKeydown", "#submit", "SUBMIT_EVENT", "#client_send", "agent", "AgUiClient", "#handlers", "call", "#executeTool", "card", "#cardFor", "TOOL_CALL_STATUS", "isDestructive", "requestConfirmation", "navigates", "isNavigates", "result", "error", "buffer", "#streamInto", "existing", "ToolCallCard", "ACCENT", "delay", "ms", "resolve", "typeInto", "el", "value", "options", "charDelayMs", "char", "highlightThenClick", "highlightMs", "previousOutline", "previousOffset", "scrollIntoCenterView", "focusWithFlash", "flashMs", "previousShadow", "defineAgUiChat", "ELEMENT_TAG", "AgUiChat", "fillField", "el", "value", "options", "scrollIntoCenterView", "focusWithFlash", "typeInto", "clickElement", "highlightThenClick", "setControlValue", "VERSION"]
|
|
7
|
+
}
|