@mastra/react 0.2.3 → 0.2.4-alpha.1

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.
Files changed (22) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/dist/{chunk-REDZDNFN-B1ouuY83.js → chunk-REDZDNFN-D4oanb5P.js} +2 -2
  3. package/dist/{chunk-REDZDNFN-B1ouuY83.js.map → chunk-REDZDNFN-D4oanb5P.js.map} +1 -1
  4. package/dist/{chunk-REDZDNFN-CbkG5d3w.cjs → chunk-REDZDNFN-fhjnNsSU.cjs} +2 -2
  5. package/dist/{chunk-REDZDNFN-CbkG5d3w.cjs.map → chunk-REDZDNFN-fhjnNsSU.cjs.map} +1 -1
  6. package/dist/{index-BQSALCsO.js → index-DAN4vgIA.js} +829 -2355
  7. package/dist/index-DAN4vgIA.js.map +1 -0
  8. package/dist/{index-DT_KGByV.cjs → index-VHXhgr5V.cjs} +160 -1686
  9. package/dist/index-VHXhgr5V.cjs.map +1 -0
  10. package/dist/index.cjs +1 -1
  11. package/dist/index.js +1 -1
  12. package/dist/{token-6GSAFR2W-XRCSVUPZ-nW1dYF0l.js → token-6GSAFR2W-XRCSVUPZ-D1m4Pmyv.js} +3 -3
  13. package/dist/{token-6GSAFR2W-XRCSVUPZ-nW1dYF0l.js.map → token-6GSAFR2W-XRCSVUPZ-D1m4Pmyv.js.map} +1 -1
  14. package/dist/{token-6GSAFR2W-XRCSVUPZ-D4lFShVi.cjs → token-6GSAFR2W-XRCSVUPZ-DtWMGnar.cjs} +3 -3
  15. package/dist/{token-6GSAFR2W-XRCSVUPZ-D4lFShVi.cjs.map → token-6GSAFR2W-XRCSVUPZ-DtWMGnar.cjs.map} +1 -1
  16. package/dist/{token-util-NEHG7TUY-U7CX7GS4-IihD8c3p.js → token-util-NEHG7TUY-U7CX7GS4-C_TOJaxg.js} +2 -2
  17. package/dist/{token-util-NEHG7TUY-U7CX7GS4-IihD8c3p.js.map → token-util-NEHG7TUY-U7CX7GS4-C_TOJaxg.js.map} +1 -1
  18. package/dist/{token-util-NEHG7TUY-U7CX7GS4-BZFIAvf9.cjs → token-util-NEHG7TUY-U7CX7GS4-MfOGpyjN.cjs} +2 -2
  19. package/dist/{token-util-NEHG7TUY-U7CX7GS4-BZFIAvf9.cjs.map → token-util-NEHG7TUY-U7CX7GS4-MfOGpyjN.cjs.map} +1 -1
  20. package/package.json +5 -5
  21. package/dist/index-BQSALCsO.js.map +0 -1
  22. package/dist/index-DT_KGByV.cjs.map +0 -1
@@ -2,9 +2,9 @@ import { jsx, jsxs } from 'react/jsx-runtime';
2
2
  import { createContext, useContext, useRef, useState, useEffect, Fragment, useLayoutEffect, useCallback } from 'react';
3
3
  import { MastraClient } from '@mastra/client-js';
4
4
  import * as z4 from 'zod/v4';
5
- import { z } from 'zod/v4';
5
+ import { z as z$1 } from 'zod/v4';
6
6
  import { ZodFirstPartyTypeKind } from 'zod/v3';
7
- import z10, { z as z$1 } from 'zod';
7
+ import z10, { z as z$2 } from 'zod';
8
8
  import { v4 } from '@lukeed/uuid';
9
9
  import { ChevronDownIcon, CheckIcon, CopyIcon } from 'lucide-react';
10
10
  import { twMerge } from 'tailwind-merge';
@@ -347,7 +347,7 @@ const toUIMessage = ({ chunk, conversation, metadata }) => {
347
347
  toolCallId,
348
348
  state: "output-error",
349
349
  input: toolPart.input,
350
- errorText: String(error),
350
+ errorText: typeof error === "string" ? error : error instanceof Error ? error.message : error?.message ?? String(error),
351
351
  callProviderMetadata: chunk.payload.providerMetadata
352
352
  };
353
353
  } else {
@@ -966,125 +966,6 @@ const resolveToChildMessages = (messages) => {
966
966
  return childMessages;
967
967
  };
968
968
 
969
- // src/request-context/index.ts
970
- var RequestContext = class {
971
- registry = /* @__PURE__ */ new Map();
972
- constructor(iterable) {
973
- this.registry = new Map(iterable);
974
- }
975
- /**
976
- * set a value with strict typing if `Values` is a Record and the key exists in it.
977
- */
978
- set(key, value) {
979
- this.registry.set(key, value);
980
- }
981
- /**
982
- * Get a value with its type
983
- */
984
- get(key) {
985
- return this.registry.get(key);
986
- }
987
- /**
988
- * Check if a key exists in the container
989
- */
990
- has(key) {
991
- return this.registry.has(key);
992
- }
993
- /**
994
- * Delete a value by key
995
- */
996
- delete(key) {
997
- return this.registry.delete(key);
998
- }
999
- /**
1000
- * Clear all values from the container
1001
- */
1002
- clear() {
1003
- this.registry.clear();
1004
- }
1005
- /**
1006
- * Get all keys in the container
1007
- */
1008
- keys() {
1009
- return this.registry.keys();
1010
- }
1011
- /**
1012
- * Get all values in the container
1013
- */
1014
- values() {
1015
- return this.registry.values();
1016
- }
1017
- /**
1018
- * Get all entries in the container.
1019
- * Returns a discriminated union of tuples for proper type narrowing when iterating.
1020
- */
1021
- entries() {
1022
- return this.registry.entries();
1023
- }
1024
- /**
1025
- * Get the size of the container
1026
- */
1027
- size() {
1028
- return this.registry.size;
1029
- }
1030
- /**
1031
- * Execute a function for each entry in the container.
1032
- * The callback receives properly typed key-value pairs.
1033
- */
1034
- forEach(callbackfn) {
1035
- this.registry.forEach(callbackfn);
1036
- }
1037
- /**
1038
- * Custom JSON serialization method.
1039
- * Converts the internal Map to a plain object for proper JSON serialization.
1040
- * Non-serializable values (e.g., RPC proxies, functions, circular references)
1041
- * are skipped to prevent serialization errors when storing to database.
1042
- */
1043
- toJSON() {
1044
- const result = {};
1045
- for (const [key, value] of this.registry.entries()) {
1046
- if (this.isSerializable(value)) {
1047
- result[key] = value;
1048
- }
1049
- }
1050
- return result;
1051
- }
1052
- /**
1053
- * Check if a value can be safely serialized to JSON.
1054
- */
1055
- isSerializable(value) {
1056
- if (value === null || value === void 0) return true;
1057
- if (typeof value === "function") return false;
1058
- if (typeof value === "symbol") return false;
1059
- if (typeof value !== "object") return true;
1060
- try {
1061
- JSON.stringify(value);
1062
- return true;
1063
- } catch {
1064
- return false;
1065
- }
1066
- }
1067
- /**
1068
- * Get all values as a typed object for destructuring.
1069
- * Returns Record<string, any> when untyped, or the Values type when typed.
1070
- *
1071
- * @example
1072
- * ```typescript
1073
- * const ctx = new RequestContext<{ userId: string; apiKey: string }>();
1074
- * ctx.set('userId', 'user-123');
1075
- * ctx.set('apiKey', 'key-456');
1076
- * const { userId, apiKey } = ctx.all;
1077
- * ```
1078
- */
1079
- get all() {
1080
- return Object.fromEntries(this.registry);
1081
- }
1082
- };
1083
-
1084
- function getDefaultExportFromCjs (x) {
1085
- return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
1086
- }
1087
-
1088
969
  var __create$4 = Object.create;
1089
970
  var __defProp$6 = Object.defineProperty;
1090
971
  var __getOwnPropDesc$4 = Object.getOwnPropertyDescriptor;
@@ -3268,8 +3149,8 @@ var require_get_vercel_oidc_token = __commonJS$3({
3268
3149
  }
3269
3150
  try {
3270
3151
  const [{ getTokenPayload, isExpired }, { refreshToken }] = await Promise.all([
3271
- await import('./token-util-NEHG7TUY-U7CX7GS4-IihD8c3p.js'),
3272
- await import('./token-6GSAFR2W-XRCSVUPZ-nW1dYF0l.js')
3152
+ await import('./token-util-NEHG7TUY-U7CX7GS4-C_TOJaxg.js'),
3153
+ await import('./token-6GSAFR2W-XRCSVUPZ-D1m4Pmyv.js')
3273
3154
  ]);
3274
3155
  if (!token || isExpired(getTokenPayload(token))) {
3275
3156
  await refreshToken();
@@ -3458,8 +3339,8 @@ var marker5 = `vercel.ai.gateway.error.${name4}`;
3458
3339
  var symbol5 = Symbol.for(marker5);
3459
3340
  var modelNotFoundParamSchema = lazyValidator(
3460
3341
  () => zodSchema$2(
3461
- z.object({
3462
- modelId: z.string()
3342
+ z$1.object({
3343
+ modelId: z$1.string()
3463
3344
  })
3464
3345
  )
3465
3346
  );
@@ -3581,12 +3462,12 @@ async function createGatewayErrorFromResponse({
3581
3462
  }
3582
3463
  var gatewayErrorResponseSchema = lazyValidator(
3583
3464
  () => zodSchema$2(
3584
- z.object({
3585
- error: z.object({
3586
- message: z.string(),
3587
- type: z.string().nullish(),
3588
- param: z.unknown().nullish(),
3589
- code: z.union([z.string(), z.number()]).nullish()
3465
+ z$1.object({
3466
+ error: z$1.object({
3467
+ message: z$1.string(),
3468
+ type: z$1.string().nullish(),
3469
+ param: z$1.unknown().nullish(),
3470
+ code: z$1.union([z$1.string(), z$1.number()]).nullish()
3590
3471
  })
3591
3472
  })
3592
3473
  )
@@ -3635,7 +3516,7 @@ async function parseAuthMethod(headers) {
3635
3516
  return result.success ? result.value : void 0;
3636
3517
  }
3637
3518
  var gatewayAuthMethodSchema = lazyValidator(
3638
- () => zodSchema$2(z.union([z.literal("api-key"), z.literal("oidc")]))
3519
+ () => zodSchema$2(z$1.union([z$1.literal("api-key"), z$1.literal("oidc")]))
3639
3520
  );
3640
3521
  var GatewayFetchMetadata = class {
3641
3522
  constructor(config) {
@@ -3650,7 +3531,7 @@ var GatewayFetchMetadata = class {
3650
3531
  gatewayAvailableModelsResponseSchema
3651
3532
  ),
3652
3533
  failedResponseHandler: createJsonErrorResponseHandler({
3653
- errorSchema: z.any(),
3534
+ errorSchema: z$1.any(),
3654
3535
  errorToMessage: (data) => data
3655
3536
  }),
3656
3537
  fetch: this.config.fetch
@@ -3670,7 +3551,7 @@ var GatewayFetchMetadata = class {
3670
3551
  gatewayCreditsResponseSchema
3671
3552
  ),
3672
3553
  failedResponseHandler: createJsonErrorResponseHandler({
3673
- errorSchema: z.any(),
3554
+ errorSchema: z$1.any(),
3674
3555
  errorToMessage: (data) => data
3675
3556
  }),
3676
3557
  fetch: this.config.fetch
@@ -3683,17 +3564,17 @@ var GatewayFetchMetadata = class {
3683
3564
  };
3684
3565
  var gatewayAvailableModelsResponseSchema = lazyValidator(
3685
3566
  () => zodSchema$2(
3686
- z.object({
3687
- models: z.array(
3688
- z.object({
3689
- id: z.string(),
3690
- name: z.string(),
3691
- description: z.string().nullish(),
3692
- pricing: z.object({
3693
- input: z.string(),
3694
- output: z.string(),
3695
- input_cache_read: z.string().nullish(),
3696
- input_cache_write: z.string().nullish()
3567
+ z$1.object({
3568
+ models: z$1.array(
3569
+ z$1.object({
3570
+ id: z$1.string(),
3571
+ name: z$1.string(),
3572
+ description: z$1.string().nullish(),
3573
+ pricing: z$1.object({
3574
+ input: z$1.string(),
3575
+ output: z$1.string(),
3576
+ input_cache_read: z$1.string().nullish(),
3577
+ input_cache_write: z$1.string().nullish()
3697
3578
  }).transform(
3698
3579
  ({ input, output, input_cache_read, input_cache_write }) => ({
3699
3580
  input,
@@ -3702,12 +3583,12 @@ var gatewayAvailableModelsResponseSchema = lazyValidator(
3702
3583
  ...input_cache_write ? { cacheCreationInputTokens: input_cache_write } : {}
3703
3584
  })
3704
3585
  ).nullish(),
3705
- specification: z.object({
3706
- specificationVersion: z.literal("v2"),
3707
- provider: z.string(),
3708
- modelId: z.string()
3586
+ specification: z$1.object({
3587
+ specificationVersion: z$1.literal("v2"),
3588
+ provider: z$1.string(),
3589
+ modelId: z$1.string()
3709
3590
  }),
3710
- modelType: z.enum(["language", "embedding", "image"]).nullish()
3591
+ modelType: z$1.enum(["language", "embedding", "image"]).nullish()
3711
3592
  })
3712
3593
  )
3713
3594
  })
@@ -3715,9 +3596,9 @@ var gatewayAvailableModelsResponseSchema = lazyValidator(
3715
3596
  );
3716
3597
  var gatewayCreditsResponseSchema = lazyValidator(
3717
3598
  () => zodSchema$2(
3718
- z.object({
3719
- balance: z.string(),
3720
- total_used: z.string()
3599
+ z$1.object({
3600
+ balance: z$1.string(),
3601
+ total_used: z$1.string()
3721
3602
  }).transform(({ balance, total_used }) => ({
3722
3603
  balance,
3723
3604
  totalUsed: total_used
@@ -3759,9 +3640,9 @@ var GatewayLanguageModel = class {
3759
3640
  await resolve(this.config.o11yHeaders)
3760
3641
  ),
3761
3642
  body: args,
3762
- successfulResponseHandler: createJsonResponseHandler(z.any()),
3643
+ successfulResponseHandler: createJsonResponseHandler(z$1.any()),
3763
3644
  failedResponseHandler: createJsonErrorResponseHandler({
3764
- errorSchema: z.any(),
3645
+ errorSchema: z$1.any(),
3765
3646
  errorToMessage: (data) => data
3766
3647
  }),
3767
3648
  ...abortSignal && { abortSignal },
@@ -3791,9 +3672,9 @@ var GatewayLanguageModel = class {
3791
3672
  await resolve(this.config.o11yHeaders)
3792
3673
  ),
3793
3674
  body: args,
3794
- successfulResponseHandler: createEventSourceResponseHandler(z.any()),
3675
+ successfulResponseHandler: createEventSourceResponseHandler(z$1.any()),
3795
3676
  failedResponseHandler: createJsonErrorResponseHandler({
3796
- errorSchema: z.any(),
3677
+ errorSchema: z$1.any(),
3797
3678
  errorToMessage: (data) => data
3798
3679
  }),
3799
3680
  ...abortSignal && { abortSignal },
@@ -3909,7 +3790,7 @@ var GatewayEmbeddingModel = class {
3909
3790
  gatewayEmbeddingResponseSchema
3910
3791
  ),
3911
3792
  failedResponseHandler: createJsonErrorResponseHandler({
3912
- errorSchema: z.any(),
3793
+ errorSchema: z$1.any(),
3913
3794
  errorToMessage: (data) => data
3914
3795
  }),
3915
3796
  ...abortSignal && { abortSignal },
@@ -3937,10 +3818,10 @@ var GatewayEmbeddingModel = class {
3937
3818
  };
3938
3819
  var gatewayEmbeddingResponseSchema = lazyValidator(
3939
3820
  () => zodSchema$2(
3940
- z.object({
3941
- embeddings: z.array(z.array(z.number())),
3942
- usage: z.object({ tokens: z.number() }).nullish(),
3943
- providerMetadata: z.record(z.string(), z.record(z.string(), z.unknown())).optional()
3821
+ z$1.object({
3822
+ embeddings: z$1.array(z$1.array(z$1.number())),
3823
+ usage: z$1.object({ tokens: z$1.number() }).nullish(),
3824
+ providerMetadata: z$1.record(z$1.string(), z$1.record(z$1.string(), z$1.unknown())).optional()
3944
3825
  })
3945
3826
  )
3946
3827
  );
@@ -3990,7 +3871,7 @@ var GatewayImageModel = class {
3990
3871
  gatewayImageResponseSchema
3991
3872
  ),
3992
3873
  failedResponseHandler: createJsonErrorResponseHandler({
3993
- errorSchema: z.any(),
3874
+ errorSchema: z$1.any(),
3994
3875
  errorToMessage: (data) => data
3995
3876
  }),
3996
3877
  ...abortSignal && { abortSignal },
@@ -4021,19 +3902,19 @@ var GatewayImageModel = class {
4021
3902
  };
4022
3903
  }
4023
3904
  };
4024
- var providerMetadataEntrySchema = z.object({
4025
- images: z.array(z.unknown()).optional()
4026
- }).catchall(z.unknown());
4027
- var gatewayImageResponseSchema = z.object({
4028
- images: z.array(z.string()),
3905
+ var providerMetadataEntrySchema = z$1.object({
3906
+ images: z$1.array(z$1.unknown()).optional()
3907
+ }).catchall(z$1.unknown());
3908
+ var gatewayImageResponseSchema = z$1.object({
3909
+ images: z$1.array(z$1.string()),
4029
3910
  // Always base64 strings over the wire
4030
- warnings: z.array(
4031
- z.object({
4032
- type: z.literal("other"),
4033
- message: z.string()
3911
+ warnings: z$1.array(
3912
+ z$1.object({
3913
+ type: z$1.literal("other"),
3914
+ message: z$1.string()
4034
3915
  })
4035
3916
  ).optional(),
4036
- providerMetadata: z.record(z.string(), providerMetadataEntrySchema).optional()
3917
+ providerMetadata: z$1.record(z$1.string(), providerMetadataEntrySchema).optional()
4037
3918
  });
4038
3919
  async function getVercelRequestId() {
4039
3920
  var _a83;
@@ -4938,11 +4819,11 @@ var MessageConversionError$1 = class MessageConversionError extends AISDKError$3
4938
4819
  }
4939
4820
  };
4940
4821
  _a12 = symbol12;
4941
- var dataContentSchema$2 = z.union([
4942
- z.string(),
4943
- z.instanceof(Uint8Array),
4944
- z.instanceof(ArrayBuffer),
4945
- z.custom(
4822
+ var dataContentSchema$2 = z$1.union([
4823
+ z$1.string(),
4824
+ z$1.instanceof(Uint8Array),
4825
+ z$1.instanceof(ArrayBuffer),
4826
+ z$1.custom(
4946
4827
  // Buffer might not be available in some environments such as CloudFlare:
4947
4828
  (value) => {
4948
4829
  var _a16, _b8;
@@ -4951,113 +4832,113 @@ var dataContentSchema$2 = z.union([
4951
4832
  { message: "Must be a Buffer" }
4952
4833
  )
4953
4834
  ]);
4954
- var jsonValueSchema$2 = z.lazy(
4955
- () => z.union([
4956
- z.null(),
4957
- z.string(),
4958
- z.number(),
4959
- z.boolean(),
4960
- z.record(z.string(), jsonValueSchema$2),
4961
- z.array(jsonValueSchema$2)
4835
+ var jsonValueSchema$2 = z$1.lazy(
4836
+ () => z$1.union([
4837
+ z$1.null(),
4838
+ z$1.string(),
4839
+ z$1.number(),
4840
+ z$1.boolean(),
4841
+ z$1.record(z$1.string(), jsonValueSchema$2),
4842
+ z$1.array(jsonValueSchema$2)
4962
4843
  ])
4963
4844
  );
4964
- var providerMetadataSchema$2 = z.record(
4965
- z.string(),
4966
- z.record(z.string(), jsonValueSchema$2)
4845
+ var providerMetadataSchema$2 = z$1.record(
4846
+ z$1.string(),
4847
+ z$1.record(z$1.string(), jsonValueSchema$2)
4967
4848
  );
4968
- var textPartSchema$2 = z.object({
4969
- type: z.literal("text"),
4970
- text: z.string(),
4849
+ var textPartSchema$2 = z$1.object({
4850
+ type: z$1.literal("text"),
4851
+ text: z$1.string(),
4971
4852
  providerOptions: providerMetadataSchema$2.optional()
4972
4853
  });
4973
- var imagePartSchema$2 = z.object({
4974
- type: z.literal("image"),
4975
- image: z.union([dataContentSchema$2, z.instanceof(URL)]),
4976
- mediaType: z.string().optional(),
4854
+ var imagePartSchema$2 = z$1.object({
4855
+ type: z$1.literal("image"),
4856
+ image: z$1.union([dataContentSchema$2, z$1.instanceof(URL)]),
4857
+ mediaType: z$1.string().optional(),
4977
4858
  providerOptions: providerMetadataSchema$2.optional()
4978
4859
  });
4979
- var filePartSchema$2 = z.object({
4980
- type: z.literal("file"),
4981
- data: z.union([dataContentSchema$2, z.instanceof(URL)]),
4982
- filename: z.string().optional(),
4983
- mediaType: z.string(),
4860
+ var filePartSchema$2 = z$1.object({
4861
+ type: z$1.literal("file"),
4862
+ data: z$1.union([dataContentSchema$2, z$1.instanceof(URL)]),
4863
+ filename: z$1.string().optional(),
4864
+ mediaType: z$1.string(),
4984
4865
  providerOptions: providerMetadataSchema$2.optional()
4985
4866
  });
4986
- var reasoningPartSchema$2 = z.object({
4987
- type: z.literal("reasoning"),
4988
- text: z.string(),
4867
+ var reasoningPartSchema$2 = z$1.object({
4868
+ type: z$1.literal("reasoning"),
4869
+ text: z$1.string(),
4989
4870
  providerOptions: providerMetadataSchema$2.optional()
4990
4871
  });
4991
- var toolCallPartSchema$2 = z.object({
4992
- type: z.literal("tool-call"),
4993
- toolCallId: z.string(),
4994
- toolName: z.string(),
4995
- input: z.unknown(),
4872
+ var toolCallPartSchema$2 = z$1.object({
4873
+ type: z$1.literal("tool-call"),
4874
+ toolCallId: z$1.string(),
4875
+ toolName: z$1.string(),
4876
+ input: z$1.unknown(),
4996
4877
  providerOptions: providerMetadataSchema$2.optional(),
4997
- providerExecuted: z.boolean().optional()
4878
+ providerExecuted: z$1.boolean().optional()
4998
4879
  });
4999
- var outputSchema = z.discriminatedUnion("type", [
5000
- z.object({
5001
- type: z.literal("text"),
5002
- value: z.string()
4880
+ var outputSchema = z$1.discriminatedUnion("type", [
4881
+ z$1.object({
4882
+ type: z$1.literal("text"),
4883
+ value: z$1.string()
5003
4884
  }),
5004
- z.object({
5005
- type: z.literal("json"),
4885
+ z$1.object({
4886
+ type: z$1.literal("json"),
5006
4887
  value: jsonValueSchema$2
5007
4888
  }),
5008
- z.object({
5009
- type: z.literal("error-text"),
5010
- value: z.string()
4889
+ z$1.object({
4890
+ type: z$1.literal("error-text"),
4891
+ value: z$1.string()
5011
4892
  }),
5012
- z.object({
5013
- type: z.literal("error-json"),
4893
+ z$1.object({
4894
+ type: z$1.literal("error-json"),
5014
4895
  value: jsonValueSchema$2
5015
4896
  }),
5016
- z.object({
5017
- type: z.literal("content"),
5018
- value: z.array(
5019
- z.union([
5020
- z.object({
5021
- type: z.literal("text"),
5022
- text: z.string()
4897
+ z$1.object({
4898
+ type: z$1.literal("content"),
4899
+ value: z$1.array(
4900
+ z$1.union([
4901
+ z$1.object({
4902
+ type: z$1.literal("text"),
4903
+ text: z$1.string()
5023
4904
  }),
5024
- z.object({
5025
- type: z.literal("media"),
5026
- data: z.string(),
5027
- mediaType: z.string()
4905
+ z$1.object({
4906
+ type: z$1.literal("media"),
4907
+ data: z$1.string(),
4908
+ mediaType: z$1.string()
5028
4909
  })
5029
4910
  ])
5030
4911
  )
5031
4912
  })
5032
4913
  ]);
5033
- var toolResultPartSchema$2 = z.object({
5034
- type: z.literal("tool-result"),
5035
- toolCallId: z.string(),
5036
- toolName: z.string(),
4914
+ var toolResultPartSchema$2 = z$1.object({
4915
+ type: z$1.literal("tool-result"),
4916
+ toolCallId: z$1.string(),
4917
+ toolName: z$1.string(),
5037
4918
  output: outputSchema,
5038
4919
  providerOptions: providerMetadataSchema$2.optional()
5039
4920
  });
5040
- var systemModelMessageSchema = z.object(
4921
+ var systemModelMessageSchema = z$1.object(
5041
4922
  {
5042
- role: z.literal("system"),
5043
- content: z.string(),
4923
+ role: z$1.literal("system"),
4924
+ content: z$1.string(),
5044
4925
  providerOptions: providerMetadataSchema$2.optional()
5045
4926
  }
5046
4927
  );
5047
- var userModelMessageSchema = z.object({
5048
- role: z.literal("user"),
5049
- content: z.union([
5050
- z.string(),
5051
- z.array(z.union([textPartSchema$2, imagePartSchema$2, filePartSchema$2]))
4928
+ var userModelMessageSchema = z$1.object({
4929
+ role: z$1.literal("user"),
4930
+ content: z$1.union([
4931
+ z$1.string(),
4932
+ z$1.array(z$1.union([textPartSchema$2, imagePartSchema$2, filePartSchema$2]))
5052
4933
  ]),
5053
4934
  providerOptions: providerMetadataSchema$2.optional()
5054
4935
  });
5055
- var assistantModelMessageSchema = z.object({
5056
- role: z.literal("assistant"),
5057
- content: z.union([
5058
- z.string(),
5059
- z.array(
5060
- z.union([
4936
+ var assistantModelMessageSchema = z$1.object({
4937
+ role: z$1.literal("assistant"),
4938
+ content: z$1.union([
4939
+ z$1.string(),
4940
+ z$1.array(
4941
+ z$1.union([
5061
4942
  textPartSchema$2,
5062
4943
  filePartSchema$2,
5063
4944
  reasoningPartSchema$2,
@@ -5068,12 +4949,12 @@ var assistantModelMessageSchema = z.object({
5068
4949
  ]),
5069
4950
  providerOptions: providerMetadataSchema$2.optional()
5070
4951
  });
5071
- var toolModelMessageSchema = z.object({
5072
- role: z.literal("tool"),
5073
- content: z.array(toolResultPartSchema$2),
4952
+ var toolModelMessageSchema = z$1.object({
4953
+ role: z$1.literal("tool"),
4954
+ content: z$1.array(toolResultPartSchema$2),
5074
4955
  providerOptions: providerMetadataSchema$2.optional()
5075
4956
  });
5076
- z.union([
4957
+ z$1.union([
5077
4958
  systemModelMessageSchema,
5078
4959
  userModelMessageSchema,
5079
4960
  assistantModelMessageSchema,
@@ -5865,94 +5746,213 @@ var MastraBaseError = class extends Error {
5865
5746
  var MastraError = class extends MastraBaseError {
5866
5747
  };
5867
5748
 
5868
- // ../_vendored/ai_v4/dist/chunk-OPIPXJLE.js
5869
- var __create$2 = Object.create;
5870
- var __defProp$3 = Object.defineProperty;
5871
- var __getOwnPropDesc$2 = Object.getOwnPropertyDescriptor;
5872
- var __getOwnPropNames$2 = Object.getOwnPropertyNames;
5873
- var __getProtoOf$2 = Object.getPrototypeOf;
5874
- var __hasOwnProp$2 = Object.prototype.hasOwnProperty;
5875
- var __commonJS$2 = (cb, mod) => function __require22() {
5876
- return mod || (0, cb[__getOwnPropNames$2(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
5877
- };
5878
- var __copyProps$2 = (to, from, except, desc) => {
5879
- if (from && typeof from === "object" || typeof from === "function") {
5880
- for (let key of __getOwnPropNames$2(from))
5881
- if (!__hasOwnProp$2.call(to, key) && key !== except)
5882
- __defProp$3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc$2(from, key)) || desc.enumerable });
5749
+ // src/request-context/index.ts
5750
+ var RequestContext = class {
5751
+ registry = /* @__PURE__ */ new Map();
5752
+ constructor(iterable) {
5753
+ this.registry = new Map(iterable);
5883
5754
  }
5884
- return to;
5885
- };
5886
- var __toESM$1 = (mod, isNodeMode, target) => (target = mod != null ? __create$2(__getProtoOf$2(mod)) : {}, __copyProps$2(
5887
- // If the importer is in node compatibility mode or this is not an ESM
5888
- // file that has been converted to a CommonJS file using a Babel-
5889
- // compatible transform (i.e. "__esModule" has not been set), then set
5890
- // "default" to the CommonJS "module.exports" for node compatibility.
5891
- __defProp$3(target, "default", { value: mod, enumerable: true }),
5892
- mod
5893
- ));
5894
- var require_secure_json_parse$1 = __commonJS$2({
5895
- "../../../node_modules/.pnpm/secure-json-parse@2.7.0/node_modules/secure-json-parse/index.js"(exports$1, module) {
5896
- var hasBuffer = typeof Buffer !== "undefined";
5897
- var suspectProtoRx = /"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/;
5898
- var suspectConstructorRx = /"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/;
5899
- function _parse(text2, reviver, options) {
5900
- if (options == null) {
5901
- if (reviver !== null && typeof reviver === "object") {
5902
- options = reviver;
5903
- reviver = void 0;
5904
- }
5905
- }
5906
- if (hasBuffer && Buffer.isBuffer(text2)) {
5907
- text2 = text2.toString();
5908
- }
5909
- if (text2 && text2.charCodeAt(0) === 65279) {
5910
- text2 = text2.slice(1);
5911
- }
5912
- const obj = JSON.parse(text2, reviver);
5913
- if (obj === null || typeof obj !== "object") {
5914
- return obj;
5915
- }
5916
- const protoAction = options && options.protoAction || "error";
5917
- const constructorAction = options && options.constructorAction || "error";
5918
- if (protoAction === "ignore" && constructorAction === "ignore") {
5919
- return obj;
5920
- }
5921
- if (protoAction !== "ignore" && constructorAction !== "ignore") {
5922
- if (suspectProtoRx.test(text2) === false && suspectConstructorRx.test(text2) === false) {
5923
- return obj;
5924
- }
5925
- } else if (protoAction !== "ignore" && constructorAction === "ignore") {
5926
- if (suspectProtoRx.test(text2) === false) {
5927
- return obj;
5928
- }
5929
- } else {
5930
- if (suspectConstructorRx.test(text2) === false) {
5931
- return obj;
5932
- }
5933
- }
5934
- return filter(obj, { protoAction, constructorAction, safe: options && options.safe });
5935
- }
5936
- function filter(obj, { protoAction = "error", constructorAction = "error", safe } = {}) {
5937
- let next = [obj];
5938
- while (next.length) {
5939
- const nodes = next;
5940
- next = [];
5941
- for (const node of nodes) {
5942
- if (protoAction !== "ignore" && Object.prototype.hasOwnProperty.call(node, "__proto__")) {
5943
- if (safe === true) {
5944
- return null;
5945
- } else if (protoAction === "error") {
5946
- throw new SyntaxError("Object contains forbidden prototype property");
5947
- }
5948
- delete node.__proto__;
5949
- }
5950
- if (constructorAction !== "ignore" && Object.prototype.hasOwnProperty.call(node, "constructor") && Object.prototype.hasOwnProperty.call(node.constructor, "prototype")) {
5951
- if (safe === true) {
5952
- return null;
5953
- } else if (constructorAction === "error") {
5954
- throw new SyntaxError("Object contains forbidden prototype property");
5955
- }
5755
+ /**
5756
+ * set a value with strict typing if `Values` is a Record and the key exists in it.
5757
+ */
5758
+ set(key, value) {
5759
+ this.registry.set(key, value);
5760
+ }
5761
+ /**
5762
+ * Get a value with its type
5763
+ */
5764
+ get(key) {
5765
+ return this.registry.get(key);
5766
+ }
5767
+ /**
5768
+ * Check if a key exists in the container
5769
+ */
5770
+ has(key) {
5771
+ return this.registry.has(key);
5772
+ }
5773
+ /**
5774
+ * Delete a value by key
5775
+ */
5776
+ delete(key) {
5777
+ return this.registry.delete(key);
5778
+ }
5779
+ /**
5780
+ * Clear all values from the container
5781
+ */
5782
+ clear() {
5783
+ this.registry.clear();
5784
+ }
5785
+ /**
5786
+ * Get all keys in the container
5787
+ */
5788
+ keys() {
5789
+ return this.registry.keys();
5790
+ }
5791
+ /**
5792
+ * Get all values in the container
5793
+ */
5794
+ values() {
5795
+ return this.registry.values();
5796
+ }
5797
+ /**
5798
+ * Get all entries in the container.
5799
+ * Returns a discriminated union of tuples for proper type narrowing when iterating.
5800
+ */
5801
+ entries() {
5802
+ return this.registry.entries();
5803
+ }
5804
+ /**
5805
+ * Get the size of the container
5806
+ */
5807
+ size() {
5808
+ return this.registry.size;
5809
+ }
5810
+ /**
5811
+ * Execute a function for each entry in the container.
5812
+ * The callback receives properly typed key-value pairs.
5813
+ */
5814
+ forEach(callbackfn) {
5815
+ this.registry.forEach(callbackfn);
5816
+ }
5817
+ /**
5818
+ * Custom JSON serialization method.
5819
+ * Converts the internal Map to a plain object for proper JSON serialization.
5820
+ * Non-serializable values (e.g., RPC proxies, functions, circular references)
5821
+ * are skipped to prevent serialization errors when storing to database.
5822
+ */
5823
+ toJSON() {
5824
+ const result = {};
5825
+ for (const [key, value] of this.registry.entries()) {
5826
+ if (this.isSerializable(value)) {
5827
+ result[key] = value;
5828
+ }
5829
+ }
5830
+ return result;
5831
+ }
5832
+ /**
5833
+ * Check if a value can be safely serialized to JSON.
5834
+ */
5835
+ isSerializable(value) {
5836
+ if (value === null || value === void 0) return true;
5837
+ if (typeof value === "function") return false;
5838
+ if (typeof value === "symbol") return false;
5839
+ if (typeof value !== "object") return true;
5840
+ try {
5841
+ JSON.stringify(value);
5842
+ return true;
5843
+ } catch {
5844
+ return false;
5845
+ }
5846
+ }
5847
+ /**
5848
+ * Get all values as a typed object for destructuring.
5849
+ * Returns Record<string, any> when untyped, or the Values type when typed.
5850
+ *
5851
+ * @example
5852
+ * ```typescript
5853
+ * const ctx = new RequestContext<{ userId: string; apiKey: string }>();
5854
+ * ctx.set('userId', 'user-123');
5855
+ * ctx.set('apiKey', 'key-456');
5856
+ * const { userId, apiKey } = ctx.all;
5857
+ * ```
5858
+ */
5859
+ get all() {
5860
+ return Object.fromEntries(this.registry);
5861
+ }
5862
+ };
5863
+
5864
+ function getDefaultExportFromCjs (x) {
5865
+ return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
5866
+ }
5867
+
5868
+ // ../_vendored/ai_v4/dist/chunk-OPIPXJLE.js
5869
+ var __create$2 = Object.create;
5870
+ var __defProp$3 = Object.defineProperty;
5871
+ var __getOwnPropDesc$2 = Object.getOwnPropertyDescriptor;
5872
+ var __getOwnPropNames$2 = Object.getOwnPropertyNames;
5873
+ var __getProtoOf$2 = Object.getPrototypeOf;
5874
+ var __hasOwnProp$2 = Object.prototype.hasOwnProperty;
5875
+ var __commonJS$2 = (cb, mod) => function __require22() {
5876
+ return mod || (0, cb[__getOwnPropNames$2(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
5877
+ };
5878
+ var __copyProps$2 = (to, from, except, desc) => {
5879
+ if (from && typeof from === "object" || typeof from === "function") {
5880
+ for (let key of __getOwnPropNames$2(from))
5881
+ if (!__hasOwnProp$2.call(to, key) && key !== except)
5882
+ __defProp$3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc$2(from, key)) || desc.enumerable });
5883
+ }
5884
+ return to;
5885
+ };
5886
+ var __toESM$1 = (mod, isNodeMode, target) => (target = mod != null ? __create$2(__getProtoOf$2(mod)) : {}, __copyProps$2(
5887
+ // If the importer is in node compatibility mode or this is not an ESM
5888
+ // file that has been converted to a CommonJS file using a Babel-
5889
+ // compatible transform (i.e. "__esModule" has not been set), then set
5890
+ // "default" to the CommonJS "module.exports" for node compatibility.
5891
+ __defProp$3(target, "default", { value: mod, enumerable: true }),
5892
+ mod
5893
+ ));
5894
+ var require_secure_json_parse$1 = __commonJS$2({
5895
+ "../../../node_modules/.pnpm/secure-json-parse@2.7.0/node_modules/secure-json-parse/index.js"(exports$1, module) {
5896
+ var hasBuffer = typeof Buffer !== "undefined";
5897
+ var suspectProtoRx = /"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/;
5898
+ var suspectConstructorRx = /"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/;
5899
+ function _parse(text2, reviver, options) {
5900
+ if (options == null) {
5901
+ if (reviver !== null && typeof reviver === "object") {
5902
+ options = reviver;
5903
+ reviver = void 0;
5904
+ }
5905
+ }
5906
+ if (hasBuffer && Buffer.isBuffer(text2)) {
5907
+ text2 = text2.toString();
5908
+ }
5909
+ if (text2 && text2.charCodeAt(0) === 65279) {
5910
+ text2 = text2.slice(1);
5911
+ }
5912
+ const obj = JSON.parse(text2, reviver);
5913
+ if (obj === null || typeof obj !== "object") {
5914
+ return obj;
5915
+ }
5916
+ const protoAction = options && options.protoAction || "error";
5917
+ const constructorAction = options && options.constructorAction || "error";
5918
+ if (protoAction === "ignore" && constructorAction === "ignore") {
5919
+ return obj;
5920
+ }
5921
+ if (protoAction !== "ignore" && constructorAction !== "ignore") {
5922
+ if (suspectProtoRx.test(text2) === false && suspectConstructorRx.test(text2) === false) {
5923
+ return obj;
5924
+ }
5925
+ } else if (protoAction !== "ignore" && constructorAction === "ignore") {
5926
+ if (suspectProtoRx.test(text2) === false) {
5927
+ return obj;
5928
+ }
5929
+ } else {
5930
+ if (suspectConstructorRx.test(text2) === false) {
5931
+ return obj;
5932
+ }
5933
+ }
5934
+ return filter(obj, { protoAction, constructorAction, safe: options && options.safe });
5935
+ }
5936
+ function filter(obj, { protoAction = "error", constructorAction = "error", safe } = {}) {
5937
+ let next = [obj];
5938
+ while (next.length) {
5939
+ const nodes = next;
5940
+ next = [];
5941
+ for (const node of nodes) {
5942
+ if (protoAction !== "ignore" && Object.prototype.hasOwnProperty.call(node, "__proto__")) {
5943
+ if (safe === true) {
5944
+ return null;
5945
+ } else if (protoAction === "error") {
5946
+ throw new SyntaxError("Object contains forbidden prototype property");
5947
+ }
5948
+ delete node.__proto__;
5949
+ }
5950
+ if (constructorAction !== "ignore" && Object.prototype.hasOwnProperty.call(node, "constructor") && Object.prototype.hasOwnProperty.call(node.constructor, "prototype")) {
5951
+ if (safe === true) {
5952
+ return null;
5953
+ } else if (constructorAction === "error") {
5954
+ throw new SyntaxError("Object contains forbidden prototype property");
5955
+ }
5956
5956
  delete node.constructor;
5957
5957
  }
5958
5958
  for (const key in node) {
@@ -8832,11 +8832,11 @@ var InvalidDataContentError = class extends AISDKError$2 {
8832
8832
  }
8833
8833
  };
8834
8834
  _a62 = symbol62;
8835
- var dataContentSchema$1 = z$1.union([
8836
- z$1.string(),
8837
- z$1.instanceof(Uint8Array),
8838
- z$1.instanceof(ArrayBuffer),
8839
- z$1.custom(
8835
+ var dataContentSchema$1 = z$2.union([
8836
+ z$2.string(),
8837
+ z$2.instanceof(Uint8Array),
8838
+ z$2.instanceof(ArrayBuffer),
8839
+ z$2.custom(
8840
8840
  // Buffer might not be available in some environments such as CloudFlare:
8841
8841
  (value) => {
8842
8842
  var _a17, _b;
@@ -9195,102 +9195,102 @@ function convertToCoreMessages(messages, options) {
9195
9195
  }
9196
9196
  return coreMessages;
9197
9197
  }
9198
- var jsonValueSchema$1 = z$1.lazy(
9199
- () => z$1.union([
9200
- z$1.null(),
9201
- z$1.string(),
9202
- z$1.number(),
9203
- z$1.boolean(),
9204
- z$1.record(z$1.string(), jsonValueSchema$1),
9205
- z$1.array(jsonValueSchema$1)
9198
+ var jsonValueSchema$1 = z$2.lazy(
9199
+ () => z$2.union([
9200
+ z$2.null(),
9201
+ z$2.string(),
9202
+ z$2.number(),
9203
+ z$2.boolean(),
9204
+ z$2.record(z$2.string(), jsonValueSchema$1),
9205
+ z$2.array(jsonValueSchema$1)
9206
9206
  ])
9207
9207
  );
9208
- var providerMetadataSchema$1 = z$1.record(
9209
- z$1.string(),
9210
- z$1.record(z$1.string(), jsonValueSchema$1)
9208
+ var providerMetadataSchema$1 = z$2.record(
9209
+ z$2.string(),
9210
+ z$2.record(z$2.string(), jsonValueSchema$1)
9211
9211
  );
9212
- var toolResultContentSchema$1 = z$1.array(
9213
- z$1.union([
9214
- z$1.object({ type: z$1.literal("text"), text: z$1.string() }),
9215
- z$1.object({
9216
- type: z$1.literal("image"),
9217
- data: z$1.string(),
9218
- mimeType: z$1.string().optional()
9212
+ var toolResultContentSchema$1 = z$2.array(
9213
+ z$2.union([
9214
+ z$2.object({ type: z$2.literal("text"), text: z$2.string() }),
9215
+ z$2.object({
9216
+ type: z$2.literal("image"),
9217
+ data: z$2.string(),
9218
+ mimeType: z$2.string().optional()
9219
9219
  })
9220
9220
  ])
9221
9221
  );
9222
- var textPartSchema$1 = z$1.object({
9223
- type: z$1.literal("text"),
9224
- text: z$1.string(),
9222
+ var textPartSchema$1 = z$2.object({
9223
+ type: z$2.literal("text"),
9224
+ text: z$2.string(),
9225
9225
  providerOptions: providerMetadataSchema$1.optional(),
9226
9226
  experimental_providerMetadata: providerMetadataSchema$1.optional()
9227
9227
  });
9228
- var imagePartSchema$1 = z$1.object({
9229
- type: z$1.literal("image"),
9230
- image: z$1.union([dataContentSchema$1, z$1.instanceof(URL)]),
9231
- mimeType: z$1.string().optional(),
9228
+ var imagePartSchema$1 = z$2.object({
9229
+ type: z$2.literal("image"),
9230
+ image: z$2.union([dataContentSchema$1, z$2.instanceof(URL)]),
9231
+ mimeType: z$2.string().optional(),
9232
9232
  providerOptions: providerMetadataSchema$1.optional(),
9233
9233
  experimental_providerMetadata: providerMetadataSchema$1.optional()
9234
9234
  });
9235
- var filePartSchema$1 = z$1.object({
9236
- type: z$1.literal("file"),
9237
- data: z$1.union([dataContentSchema$1, z$1.instanceof(URL)]),
9238
- filename: z$1.string().optional(),
9239
- mimeType: z$1.string(),
9235
+ var filePartSchema$1 = z$2.object({
9236
+ type: z$2.literal("file"),
9237
+ data: z$2.union([dataContentSchema$1, z$2.instanceof(URL)]),
9238
+ filename: z$2.string().optional(),
9239
+ mimeType: z$2.string(),
9240
9240
  providerOptions: providerMetadataSchema$1.optional(),
9241
9241
  experimental_providerMetadata: providerMetadataSchema$1.optional()
9242
9242
  });
9243
- var reasoningPartSchema$1 = z$1.object({
9244
- type: z$1.literal("reasoning"),
9245
- text: z$1.string(),
9243
+ var reasoningPartSchema$1 = z$2.object({
9244
+ type: z$2.literal("reasoning"),
9245
+ text: z$2.string(),
9246
9246
  providerOptions: providerMetadataSchema$1.optional(),
9247
9247
  experimental_providerMetadata: providerMetadataSchema$1.optional()
9248
9248
  });
9249
- var redactedReasoningPartSchema$1 = z$1.object({
9250
- type: z$1.literal("redacted-reasoning"),
9251
- data: z$1.string(),
9249
+ var redactedReasoningPartSchema$1 = z$2.object({
9250
+ type: z$2.literal("redacted-reasoning"),
9251
+ data: z$2.string(),
9252
9252
  providerOptions: providerMetadataSchema$1.optional(),
9253
9253
  experimental_providerMetadata: providerMetadataSchema$1.optional()
9254
9254
  });
9255
- var toolCallPartSchema$1 = z$1.object({
9256
- type: z$1.literal("tool-call"),
9257
- toolCallId: z$1.string(),
9258
- toolName: z$1.string(),
9259
- args: z$1.unknown(),
9255
+ var toolCallPartSchema$1 = z$2.object({
9256
+ type: z$2.literal("tool-call"),
9257
+ toolCallId: z$2.string(),
9258
+ toolName: z$2.string(),
9259
+ args: z$2.unknown(),
9260
9260
  providerOptions: providerMetadataSchema$1.optional(),
9261
9261
  experimental_providerMetadata: providerMetadataSchema$1.optional()
9262
9262
  });
9263
- var toolResultPartSchema$1 = z$1.object({
9264
- type: z$1.literal("tool-result"),
9265
- toolCallId: z$1.string(),
9266
- toolName: z$1.string(),
9267
- result: z$1.unknown(),
9263
+ var toolResultPartSchema$1 = z$2.object({
9264
+ type: z$2.literal("tool-result"),
9265
+ toolCallId: z$2.string(),
9266
+ toolName: z$2.string(),
9267
+ result: z$2.unknown(),
9268
9268
  content: toolResultContentSchema$1.optional(),
9269
- isError: z$1.boolean().optional(),
9269
+ isError: z$2.boolean().optional(),
9270
9270
  providerOptions: providerMetadataSchema$1.optional(),
9271
9271
  experimental_providerMetadata: providerMetadataSchema$1.optional()
9272
9272
  });
9273
- var coreSystemMessageSchema$1 = z$1.object({
9274
- role: z$1.literal("system"),
9275
- content: z$1.string(),
9273
+ var coreSystemMessageSchema$1 = z$2.object({
9274
+ role: z$2.literal("system"),
9275
+ content: z$2.string(),
9276
9276
  providerOptions: providerMetadataSchema$1.optional(),
9277
9277
  experimental_providerMetadata: providerMetadataSchema$1.optional()
9278
9278
  });
9279
- var coreUserMessageSchema$1 = z$1.object({
9280
- role: z$1.literal("user"),
9281
- content: z$1.union([
9282
- z$1.string(),
9283
- z$1.array(z$1.union([textPartSchema$1, imagePartSchema$1, filePartSchema$1]))
9279
+ var coreUserMessageSchema$1 = z$2.object({
9280
+ role: z$2.literal("user"),
9281
+ content: z$2.union([
9282
+ z$2.string(),
9283
+ z$2.array(z$2.union([textPartSchema$1, imagePartSchema$1, filePartSchema$1]))
9284
9284
  ]),
9285
9285
  providerOptions: providerMetadataSchema$1.optional(),
9286
9286
  experimental_providerMetadata: providerMetadataSchema$1.optional()
9287
9287
  });
9288
- var coreAssistantMessageSchema$1 = z$1.object({
9289
- role: z$1.literal("assistant"),
9290
- content: z$1.union([
9291
- z$1.string(),
9292
- z$1.array(
9293
- z$1.union([
9288
+ var coreAssistantMessageSchema$1 = z$2.object({
9289
+ role: z$2.literal("assistant"),
9290
+ content: z$2.union([
9291
+ z$2.string(),
9292
+ z$2.array(
9293
+ z$2.union([
9294
9294
  textPartSchema$1,
9295
9295
  filePartSchema$1,
9296
9296
  reasoningPartSchema$1,
@@ -9302,13 +9302,13 @@ var coreAssistantMessageSchema$1 = z$1.object({
9302
9302
  providerOptions: providerMetadataSchema$1.optional(),
9303
9303
  experimental_providerMetadata: providerMetadataSchema$1.optional()
9304
9304
  });
9305
- var coreToolMessageSchema$1 = z$1.object({
9306
- role: z$1.literal("tool"),
9307
- content: z$1.array(toolResultPartSchema$1),
9305
+ var coreToolMessageSchema$1 = z$2.object({
9306
+ role: z$2.literal("tool"),
9307
+ content: z$2.array(toolResultPartSchema$1),
9308
9308
  providerOptions: providerMetadataSchema$1.optional(),
9309
9309
  experimental_providerMetadata: providerMetadataSchema$1.optional()
9310
9310
  });
9311
- z$1.union([
9311
+ z$2.union([
9312
9312
  coreSystemMessageSchema$1,
9313
9313
  coreUserMessageSchema$1,
9314
9314
  coreAssistantMessageSchema$1,
@@ -9518,125 +9518,125 @@ createIdGenerator$2({
9518
9518
  prefix: "msg",
9519
9519
  size: 24
9520
9520
  });
9521
- var ClientOrServerImplementationSchema$1 = z$1.object({
9522
- name: z$1.string(),
9523
- version: z$1.string()
9521
+ var ClientOrServerImplementationSchema$1 = z$2.object({
9522
+ name: z$2.string(),
9523
+ version: z$2.string()
9524
9524
  }).passthrough();
9525
- var BaseParamsSchema$1 = z$1.object({
9526
- _meta: z$1.optional(z$1.object({}).passthrough())
9525
+ var BaseParamsSchema$1 = z$2.object({
9526
+ _meta: z$2.optional(z$2.object({}).passthrough())
9527
9527
  }).passthrough();
9528
9528
  var ResultSchema$1 = BaseParamsSchema$1;
9529
- var RequestSchema$1 = z$1.object({
9530
- method: z$1.string(),
9531
- params: z$1.optional(BaseParamsSchema$1)
9529
+ var RequestSchema$1 = z$2.object({
9530
+ method: z$2.string(),
9531
+ params: z$2.optional(BaseParamsSchema$1)
9532
9532
  });
9533
- var ServerCapabilitiesSchema$1 = z$1.object({
9534
- experimental: z$1.optional(z$1.object({}).passthrough()),
9535
- logging: z$1.optional(z$1.object({}).passthrough()),
9536
- prompts: z$1.optional(
9537
- z$1.object({
9538
- listChanged: z$1.optional(z$1.boolean())
9533
+ var ServerCapabilitiesSchema$1 = z$2.object({
9534
+ experimental: z$2.optional(z$2.object({}).passthrough()),
9535
+ logging: z$2.optional(z$2.object({}).passthrough()),
9536
+ prompts: z$2.optional(
9537
+ z$2.object({
9538
+ listChanged: z$2.optional(z$2.boolean())
9539
9539
  }).passthrough()
9540
9540
  ),
9541
- resources: z$1.optional(
9542
- z$1.object({
9543
- subscribe: z$1.optional(z$1.boolean()),
9544
- listChanged: z$1.optional(z$1.boolean())
9541
+ resources: z$2.optional(
9542
+ z$2.object({
9543
+ subscribe: z$2.optional(z$2.boolean()),
9544
+ listChanged: z$2.optional(z$2.boolean())
9545
9545
  }).passthrough()
9546
9546
  ),
9547
- tools: z$1.optional(
9548
- z$1.object({
9549
- listChanged: z$1.optional(z$1.boolean())
9547
+ tools: z$2.optional(
9548
+ z$2.object({
9549
+ listChanged: z$2.optional(z$2.boolean())
9550
9550
  }).passthrough()
9551
9551
  )
9552
9552
  }).passthrough();
9553
9553
  ResultSchema$1.extend({
9554
- protocolVersion: z$1.string(),
9554
+ protocolVersion: z$2.string(),
9555
9555
  capabilities: ServerCapabilitiesSchema$1,
9556
9556
  serverInfo: ClientOrServerImplementationSchema$1,
9557
- instructions: z$1.optional(z$1.string())
9557
+ instructions: z$2.optional(z$2.string())
9558
9558
  });
9559
9559
  var PaginatedResultSchema$1 = ResultSchema$1.extend({
9560
- nextCursor: z$1.optional(z$1.string())
9560
+ nextCursor: z$2.optional(z$2.string())
9561
9561
  });
9562
- var ToolSchema$1 = z$1.object({
9563
- name: z$1.string(),
9564
- description: z$1.optional(z$1.string()),
9565
- inputSchema: z$1.object({
9566
- type: z$1.literal("object"),
9567
- properties: z$1.optional(z$1.object({}).passthrough())
9562
+ var ToolSchema$1 = z$2.object({
9563
+ name: z$2.string(),
9564
+ description: z$2.optional(z$2.string()),
9565
+ inputSchema: z$2.object({
9566
+ type: z$2.literal("object"),
9567
+ properties: z$2.optional(z$2.object({}).passthrough())
9568
9568
  }).passthrough()
9569
9569
  }).passthrough();
9570
9570
  PaginatedResultSchema$1.extend({
9571
- tools: z$1.array(ToolSchema$1)
9571
+ tools: z$2.array(ToolSchema$1)
9572
9572
  });
9573
- var TextContentSchema$1 = z$1.object({
9574
- type: z$1.literal("text"),
9575
- text: z$1.string()
9573
+ var TextContentSchema$1 = z$2.object({
9574
+ type: z$2.literal("text"),
9575
+ text: z$2.string()
9576
9576
  }).passthrough();
9577
- var ImageContentSchema$1 = z$1.object({
9578
- type: z$1.literal("image"),
9579
- data: z$1.string().base64(),
9580
- mimeType: z$1.string()
9577
+ var ImageContentSchema$1 = z$2.object({
9578
+ type: z$2.literal("image"),
9579
+ data: z$2.string().base64(),
9580
+ mimeType: z$2.string()
9581
9581
  }).passthrough();
9582
- var ResourceContentsSchema$1 = z$1.object({
9582
+ var ResourceContentsSchema$1 = z$2.object({
9583
9583
  /**
9584
9584
  * The URI of this resource.
9585
9585
  */
9586
- uri: z$1.string(),
9586
+ uri: z$2.string(),
9587
9587
  /**
9588
9588
  * The MIME type of this resource, if known.
9589
9589
  */
9590
- mimeType: z$1.optional(z$1.string())
9590
+ mimeType: z$2.optional(z$2.string())
9591
9591
  }).passthrough();
9592
9592
  var TextResourceContentsSchema$1 = ResourceContentsSchema$1.extend({
9593
- text: z$1.string()
9593
+ text: z$2.string()
9594
9594
  });
9595
9595
  var BlobResourceContentsSchema$1 = ResourceContentsSchema$1.extend({
9596
- blob: z$1.string().base64()
9596
+ blob: z$2.string().base64()
9597
9597
  });
9598
- var EmbeddedResourceSchema$1 = z$1.object({
9599
- type: z$1.literal("resource"),
9600
- resource: z$1.union([TextResourceContentsSchema$1, BlobResourceContentsSchema$1])
9598
+ var EmbeddedResourceSchema$1 = z$2.object({
9599
+ type: z$2.literal("resource"),
9600
+ resource: z$2.union([TextResourceContentsSchema$1, BlobResourceContentsSchema$1])
9601
9601
  }).passthrough();
9602
9602
  ResultSchema$1.extend({
9603
- content: z$1.array(
9604
- z$1.union([TextContentSchema$1, ImageContentSchema$1, EmbeddedResourceSchema$1])
9603
+ content: z$2.array(
9604
+ z$2.union([TextContentSchema$1, ImageContentSchema$1, EmbeddedResourceSchema$1])
9605
9605
  ),
9606
- isError: z$1.boolean().default(false).optional()
9606
+ isError: z$2.boolean().default(false).optional()
9607
9607
  }).or(
9608
9608
  ResultSchema$1.extend({
9609
- toolResult: z$1.unknown()
9609
+ toolResult: z$2.unknown()
9610
9610
  })
9611
9611
  );
9612
9612
  var JSONRPC_VERSION$1 = "2.0";
9613
- var JSONRPCRequestSchema$1 = z$1.object({
9614
- jsonrpc: z$1.literal(JSONRPC_VERSION$1),
9615
- id: z$1.union([z$1.string(), z$1.number().int()])
9613
+ var JSONRPCRequestSchema$1 = z$2.object({
9614
+ jsonrpc: z$2.literal(JSONRPC_VERSION$1),
9615
+ id: z$2.union([z$2.string(), z$2.number().int()])
9616
9616
  }).merge(RequestSchema$1).strict();
9617
- var JSONRPCResponseSchema$1 = z$1.object({
9618
- jsonrpc: z$1.literal(JSONRPC_VERSION$1),
9619
- id: z$1.union([z$1.string(), z$1.number().int()]),
9617
+ var JSONRPCResponseSchema$1 = z$2.object({
9618
+ jsonrpc: z$2.literal(JSONRPC_VERSION$1),
9619
+ id: z$2.union([z$2.string(), z$2.number().int()]),
9620
9620
  result: ResultSchema$1
9621
9621
  }).strict();
9622
- var JSONRPCErrorSchema$1 = z$1.object({
9623
- jsonrpc: z$1.literal(JSONRPC_VERSION$1),
9624
- id: z$1.union([z$1.string(), z$1.number().int()]),
9625
- error: z$1.object({
9626
- code: z$1.number().int(),
9627
- message: z$1.string(),
9628
- data: z$1.optional(z$1.unknown())
9622
+ var JSONRPCErrorSchema$1 = z$2.object({
9623
+ jsonrpc: z$2.literal(JSONRPC_VERSION$1),
9624
+ id: z$2.union([z$2.string(), z$2.number().int()]),
9625
+ error: z$2.object({
9626
+ code: z$2.number().int(),
9627
+ message: z$2.string(),
9628
+ data: z$2.optional(z$2.unknown())
9629
9629
  })
9630
9630
  }).strict();
9631
- var JSONRPCNotificationSchema$1 = z$1.object({
9632
- jsonrpc: z$1.literal(JSONRPC_VERSION$1)
9631
+ var JSONRPCNotificationSchema$1 = z$2.object({
9632
+ jsonrpc: z$2.literal(JSONRPC_VERSION$1)
9633
9633
  }).merge(
9634
- z$1.object({
9635
- method: z$1.string(),
9636
- params: z$1.optional(BaseParamsSchema$1)
9634
+ z$2.object({
9635
+ method: z$2.string(),
9636
+ params: z$2.optional(BaseParamsSchema$1)
9637
9637
  })
9638
9638
  ).strict();
9639
- z$1.union([
9639
+ z$2.union([
9640
9640
  JSONRPCRequestSchema$1,
9641
9641
  JSONRPCNotificationSchema$1,
9642
9642
  JSONRPCResponseSchema$1,
@@ -10020,11 +10020,11 @@ var TypeDetector = class _TypeDetector {
10020
10020
  );
10021
10021
  }
10022
10022
  };
10023
- z$1.union([
10024
- z$1.string(),
10025
- z$1.instanceof(Uint8Array),
10026
- z$1.instanceof(ArrayBuffer),
10027
- z$1.custom(
10023
+ z$2.union([
10024
+ z$2.string(),
10025
+ z$2.instanceof(Uint8Array),
10026
+ z$2.instanceof(ArrayBuffer),
10027
+ z$2.custom(
10028
10028
  // Buffer might not be available in some environments such as CloudFlare:
10029
10029
  (value) => globalThis.Buffer?.isBuffer(value) ?? false,
10030
10030
  { message: "Must be a Buffer" }
@@ -11724,15 +11724,43 @@ function aiV5UIMessagesToAIV5ModelMessages(messages, dbMessages, filterIncomplet
11724
11724
  const sanitized = sanitizeV5UIMessages(messages, filterIncompleteToolCalls);
11725
11725
  const preprocessed = addStartStepPartsForAIV5(sanitized);
11726
11726
  const result = convertToModelMessages(preprocessed);
11727
- const withProviderOptions = result.map((modelMsg, index) => {
11728
- const uiMsg = preprocessed[index];
11729
- if (uiMsg?.metadata && typeof uiMsg.metadata === "object" && "providerMetadata" in uiMsg.metadata && uiMsg.metadata.providerMetadata) {
11730
- return {
11731
- ...modelMsg,
11732
- providerOptions: uiMsg.metadata.providerMetadata
11733
- };
11734
- }
11735
- return modelMsg;
11727
+ const storedModelOutputs = /* @__PURE__ */ new Map();
11728
+ for (const dbMsg of dbMessages) {
11729
+ if (dbMsg.content?.format === 2 && dbMsg.content.parts) {
11730
+ for (const part of dbMsg.content.parts) {
11731
+ if (part.type === "tool-invocation" && part.toolInvocation?.state === "result" && part.providerMetadata?.mastra && typeof part.providerMetadata.mastra === "object" && "modelOutput" in part.providerMetadata.mastra) {
11732
+ storedModelOutputs.set(
11733
+ part.toolInvocation.toolCallId,
11734
+ part.providerMetadata.mastra.modelOutput
11735
+ );
11736
+ }
11737
+ }
11738
+ }
11739
+ }
11740
+ if (storedModelOutputs.size > 0) {
11741
+ for (const modelMsg of result) {
11742
+ if (modelMsg.role === "tool" && Array.isArray(modelMsg.content)) {
11743
+ for (let i = 0; i < modelMsg.content.length; i++) {
11744
+ const part = modelMsg.content[i];
11745
+ if (part.type === "tool-result" && storedModelOutputs.has(part.toolCallId)) {
11746
+ modelMsg.content[i] = {
11747
+ ...part,
11748
+ output: storedModelOutputs.get(part.toolCallId)
11749
+ };
11750
+ }
11751
+ }
11752
+ }
11753
+ }
11754
+ }
11755
+ const withProviderOptions = result.map((modelMsg, index) => {
11756
+ const uiMsg = preprocessed[index];
11757
+ if (uiMsg?.metadata && typeof uiMsg.metadata === "object" && "providerMetadata" in uiMsg.metadata && uiMsg.metadata.providerMetadata) {
11758
+ return {
11759
+ ...modelMsg,
11760
+ providerOptions: uiMsg.metadata.providerMetadata
11761
+ };
11762
+ }
11763
+ return modelMsg;
11736
11764
  });
11737
11765
  return ensureAnthropicCompatibleMessages(withProviderOptions, dbMessages);
11738
11766
  }
@@ -11994,6 +12022,12 @@ var MessageMerger = class _MessageMerger {
11994
12022
  ...part.toolInvocation.args
11995
12023
  }
11996
12024
  };
12025
+ if (part.providerMetadata) {
12026
+ existingCallPart.providerMetadata = {
12027
+ ...existingCallPart.providerMetadata,
12028
+ ...part.providerMetadata
12029
+ };
12030
+ }
11997
12031
  if (!latestMessage.content.toolInvocations) {
11998
12032
  latestMessage.content.toolInvocations = [];
11999
12033
  }
@@ -23106,11 +23140,11 @@ var NoObjectGeneratedError = class extends AISDKError {
23106
23140
  }
23107
23141
  };
23108
23142
  _a42 = symbol42;
23109
- var dataContentSchema = z$1.union([
23110
- z$1.string(),
23111
- z$1.instanceof(Uint8Array),
23112
- z$1.instanceof(ArrayBuffer),
23113
- z$1.custom(
23143
+ var dataContentSchema = z$2.union([
23144
+ z$2.string(),
23145
+ z$2.instanceof(Uint8Array),
23146
+ z$2.instanceof(ArrayBuffer),
23147
+ z$2.custom(
23114
23148
  // Buffer might not be available in some environments such as CloudFlare:
23115
23149
  (value) => {
23116
23150
  var _a17, _b;
@@ -23119,102 +23153,102 @@ var dataContentSchema = z$1.union([
23119
23153
  { message: "Must be a Buffer" }
23120
23154
  )
23121
23155
  ]);
23122
- var jsonValueSchema = z$1.lazy(
23123
- () => z$1.union([
23124
- z$1.null(),
23125
- z$1.string(),
23126
- z$1.number(),
23127
- z$1.boolean(),
23128
- z$1.record(z$1.string(), jsonValueSchema),
23129
- z$1.array(jsonValueSchema)
23156
+ var jsonValueSchema = z$2.lazy(
23157
+ () => z$2.union([
23158
+ z$2.null(),
23159
+ z$2.string(),
23160
+ z$2.number(),
23161
+ z$2.boolean(),
23162
+ z$2.record(z$2.string(), jsonValueSchema),
23163
+ z$2.array(jsonValueSchema)
23130
23164
  ])
23131
23165
  );
23132
- var providerMetadataSchema = z$1.record(
23133
- z$1.string(),
23134
- z$1.record(z$1.string(), jsonValueSchema)
23166
+ var providerMetadataSchema = z$2.record(
23167
+ z$2.string(),
23168
+ z$2.record(z$2.string(), jsonValueSchema)
23135
23169
  );
23136
- var toolResultContentSchema = z$1.array(
23137
- z$1.union([
23138
- z$1.object({ type: z$1.literal("text"), text: z$1.string() }),
23139
- z$1.object({
23140
- type: z$1.literal("image"),
23141
- data: z$1.string(),
23142
- mimeType: z$1.string().optional()
23170
+ var toolResultContentSchema = z$2.array(
23171
+ z$2.union([
23172
+ z$2.object({ type: z$2.literal("text"), text: z$2.string() }),
23173
+ z$2.object({
23174
+ type: z$2.literal("image"),
23175
+ data: z$2.string(),
23176
+ mimeType: z$2.string().optional()
23143
23177
  })
23144
23178
  ])
23145
23179
  );
23146
- var textPartSchema = z$1.object({
23147
- type: z$1.literal("text"),
23148
- text: z$1.string(),
23180
+ var textPartSchema = z$2.object({
23181
+ type: z$2.literal("text"),
23182
+ text: z$2.string(),
23149
23183
  providerOptions: providerMetadataSchema.optional(),
23150
23184
  experimental_providerMetadata: providerMetadataSchema.optional()
23151
23185
  });
23152
- var imagePartSchema = z$1.object({
23153
- type: z$1.literal("image"),
23154
- image: z$1.union([dataContentSchema, z$1.instanceof(URL)]),
23155
- mimeType: z$1.string().optional(),
23186
+ var imagePartSchema = z$2.object({
23187
+ type: z$2.literal("image"),
23188
+ image: z$2.union([dataContentSchema, z$2.instanceof(URL)]),
23189
+ mimeType: z$2.string().optional(),
23156
23190
  providerOptions: providerMetadataSchema.optional(),
23157
23191
  experimental_providerMetadata: providerMetadataSchema.optional()
23158
23192
  });
23159
- var filePartSchema = z$1.object({
23160
- type: z$1.literal("file"),
23161
- data: z$1.union([dataContentSchema, z$1.instanceof(URL)]),
23162
- filename: z$1.string().optional(),
23163
- mimeType: z$1.string(),
23193
+ var filePartSchema = z$2.object({
23194
+ type: z$2.literal("file"),
23195
+ data: z$2.union([dataContentSchema, z$2.instanceof(URL)]),
23196
+ filename: z$2.string().optional(),
23197
+ mimeType: z$2.string(),
23164
23198
  providerOptions: providerMetadataSchema.optional(),
23165
23199
  experimental_providerMetadata: providerMetadataSchema.optional()
23166
23200
  });
23167
- var reasoningPartSchema = z$1.object({
23168
- type: z$1.literal("reasoning"),
23169
- text: z$1.string(),
23201
+ var reasoningPartSchema = z$2.object({
23202
+ type: z$2.literal("reasoning"),
23203
+ text: z$2.string(),
23170
23204
  providerOptions: providerMetadataSchema.optional(),
23171
23205
  experimental_providerMetadata: providerMetadataSchema.optional()
23172
23206
  });
23173
- var redactedReasoningPartSchema = z$1.object({
23174
- type: z$1.literal("redacted-reasoning"),
23175
- data: z$1.string(),
23207
+ var redactedReasoningPartSchema = z$2.object({
23208
+ type: z$2.literal("redacted-reasoning"),
23209
+ data: z$2.string(),
23176
23210
  providerOptions: providerMetadataSchema.optional(),
23177
23211
  experimental_providerMetadata: providerMetadataSchema.optional()
23178
23212
  });
23179
- var toolCallPartSchema = z$1.object({
23180
- type: z$1.literal("tool-call"),
23181
- toolCallId: z$1.string(),
23182
- toolName: z$1.string(),
23183
- args: z$1.unknown(),
23213
+ var toolCallPartSchema = z$2.object({
23214
+ type: z$2.literal("tool-call"),
23215
+ toolCallId: z$2.string(),
23216
+ toolName: z$2.string(),
23217
+ args: z$2.unknown(),
23184
23218
  providerOptions: providerMetadataSchema.optional(),
23185
23219
  experimental_providerMetadata: providerMetadataSchema.optional()
23186
23220
  });
23187
- var toolResultPartSchema = z$1.object({
23188
- type: z$1.literal("tool-result"),
23189
- toolCallId: z$1.string(),
23190
- toolName: z$1.string(),
23191
- result: z$1.unknown(),
23221
+ var toolResultPartSchema = z$2.object({
23222
+ type: z$2.literal("tool-result"),
23223
+ toolCallId: z$2.string(),
23224
+ toolName: z$2.string(),
23225
+ result: z$2.unknown(),
23192
23226
  content: toolResultContentSchema.optional(),
23193
- isError: z$1.boolean().optional(),
23227
+ isError: z$2.boolean().optional(),
23194
23228
  providerOptions: providerMetadataSchema.optional(),
23195
23229
  experimental_providerMetadata: providerMetadataSchema.optional()
23196
23230
  });
23197
- var coreSystemMessageSchema = z$1.object({
23198
- role: z$1.literal("system"),
23199
- content: z$1.string(),
23231
+ var coreSystemMessageSchema = z$2.object({
23232
+ role: z$2.literal("system"),
23233
+ content: z$2.string(),
23200
23234
  providerOptions: providerMetadataSchema.optional(),
23201
23235
  experimental_providerMetadata: providerMetadataSchema.optional()
23202
23236
  });
23203
- var coreUserMessageSchema = z$1.object({
23204
- role: z$1.literal("user"),
23205
- content: z$1.union([
23206
- z$1.string(),
23207
- z$1.array(z$1.union([textPartSchema, imagePartSchema, filePartSchema]))
23237
+ var coreUserMessageSchema = z$2.object({
23238
+ role: z$2.literal("user"),
23239
+ content: z$2.union([
23240
+ z$2.string(),
23241
+ z$2.array(z$2.union([textPartSchema, imagePartSchema, filePartSchema]))
23208
23242
  ]),
23209
23243
  providerOptions: providerMetadataSchema.optional(),
23210
23244
  experimental_providerMetadata: providerMetadataSchema.optional()
23211
23245
  });
23212
- var coreAssistantMessageSchema = z$1.object({
23213
- role: z$1.literal("assistant"),
23214
- content: z$1.union([
23215
- z$1.string(),
23216
- z$1.array(
23217
- z$1.union([
23246
+ var coreAssistantMessageSchema = z$2.object({
23247
+ role: z$2.literal("assistant"),
23248
+ content: z$2.union([
23249
+ z$2.string(),
23250
+ z$2.array(
23251
+ z$2.union([
23218
23252
  textPartSchema,
23219
23253
  filePartSchema,
23220
23254
  reasoningPartSchema,
@@ -23226,13 +23260,13 @@ var coreAssistantMessageSchema = z$1.object({
23226
23260
  providerOptions: providerMetadataSchema.optional(),
23227
23261
  experimental_providerMetadata: providerMetadataSchema.optional()
23228
23262
  });
23229
- var coreToolMessageSchema = z$1.object({
23230
- role: z$1.literal("tool"),
23231
- content: z$1.array(toolResultPartSchema),
23263
+ var coreToolMessageSchema = z$2.object({
23264
+ role: z$2.literal("tool"),
23265
+ content: z$2.array(toolResultPartSchema),
23232
23266
  providerOptions: providerMetadataSchema.optional(),
23233
23267
  experimental_providerMetadata: providerMetadataSchema.optional()
23234
23268
  });
23235
- z$1.union([
23269
+ z$2.union([
23236
23270
  coreSystemMessageSchema,
23237
23271
  coreUserMessageSchema,
23238
23272
  coreAssistantMessageSchema,
@@ -23442,125 +23476,125 @@ createIdGenerator({
23442
23476
  prefix: "msg",
23443
23477
  size: 24
23444
23478
  });
23445
- var ClientOrServerImplementationSchema = z$1.object({
23446
- name: z$1.string(),
23447
- version: z$1.string()
23479
+ var ClientOrServerImplementationSchema = z$2.object({
23480
+ name: z$2.string(),
23481
+ version: z$2.string()
23448
23482
  }).passthrough();
23449
- var BaseParamsSchema = z$1.object({
23450
- _meta: z$1.optional(z$1.object({}).passthrough())
23483
+ var BaseParamsSchema = z$2.object({
23484
+ _meta: z$2.optional(z$2.object({}).passthrough())
23451
23485
  }).passthrough();
23452
23486
  var ResultSchema = BaseParamsSchema;
23453
- var RequestSchema = z$1.object({
23454
- method: z$1.string(),
23455
- params: z$1.optional(BaseParamsSchema)
23487
+ var RequestSchema = z$2.object({
23488
+ method: z$2.string(),
23489
+ params: z$2.optional(BaseParamsSchema)
23456
23490
  });
23457
- var ServerCapabilitiesSchema = z$1.object({
23458
- experimental: z$1.optional(z$1.object({}).passthrough()),
23459
- logging: z$1.optional(z$1.object({}).passthrough()),
23460
- prompts: z$1.optional(
23461
- z$1.object({
23462
- listChanged: z$1.optional(z$1.boolean())
23491
+ var ServerCapabilitiesSchema = z$2.object({
23492
+ experimental: z$2.optional(z$2.object({}).passthrough()),
23493
+ logging: z$2.optional(z$2.object({}).passthrough()),
23494
+ prompts: z$2.optional(
23495
+ z$2.object({
23496
+ listChanged: z$2.optional(z$2.boolean())
23463
23497
  }).passthrough()
23464
23498
  ),
23465
- resources: z$1.optional(
23466
- z$1.object({
23467
- subscribe: z$1.optional(z$1.boolean()),
23468
- listChanged: z$1.optional(z$1.boolean())
23499
+ resources: z$2.optional(
23500
+ z$2.object({
23501
+ subscribe: z$2.optional(z$2.boolean()),
23502
+ listChanged: z$2.optional(z$2.boolean())
23469
23503
  }).passthrough()
23470
23504
  ),
23471
- tools: z$1.optional(
23472
- z$1.object({
23473
- listChanged: z$1.optional(z$1.boolean())
23505
+ tools: z$2.optional(
23506
+ z$2.object({
23507
+ listChanged: z$2.optional(z$2.boolean())
23474
23508
  }).passthrough()
23475
23509
  )
23476
23510
  }).passthrough();
23477
23511
  ResultSchema.extend({
23478
- protocolVersion: z$1.string(),
23512
+ protocolVersion: z$2.string(),
23479
23513
  capabilities: ServerCapabilitiesSchema,
23480
23514
  serverInfo: ClientOrServerImplementationSchema,
23481
- instructions: z$1.optional(z$1.string())
23515
+ instructions: z$2.optional(z$2.string())
23482
23516
  });
23483
23517
  var PaginatedResultSchema = ResultSchema.extend({
23484
- nextCursor: z$1.optional(z$1.string())
23518
+ nextCursor: z$2.optional(z$2.string())
23485
23519
  });
23486
- var ToolSchema = z$1.object({
23487
- name: z$1.string(),
23488
- description: z$1.optional(z$1.string()),
23489
- inputSchema: z$1.object({
23490
- type: z$1.literal("object"),
23491
- properties: z$1.optional(z$1.object({}).passthrough())
23520
+ var ToolSchema = z$2.object({
23521
+ name: z$2.string(),
23522
+ description: z$2.optional(z$2.string()),
23523
+ inputSchema: z$2.object({
23524
+ type: z$2.literal("object"),
23525
+ properties: z$2.optional(z$2.object({}).passthrough())
23492
23526
  }).passthrough()
23493
23527
  }).passthrough();
23494
23528
  PaginatedResultSchema.extend({
23495
- tools: z$1.array(ToolSchema)
23529
+ tools: z$2.array(ToolSchema)
23496
23530
  });
23497
- var TextContentSchema = z$1.object({
23498
- type: z$1.literal("text"),
23499
- text: z$1.string()
23531
+ var TextContentSchema = z$2.object({
23532
+ type: z$2.literal("text"),
23533
+ text: z$2.string()
23500
23534
  }).passthrough();
23501
- var ImageContentSchema = z$1.object({
23502
- type: z$1.literal("image"),
23503
- data: z$1.string().base64(),
23504
- mimeType: z$1.string()
23535
+ var ImageContentSchema = z$2.object({
23536
+ type: z$2.literal("image"),
23537
+ data: z$2.string().base64(),
23538
+ mimeType: z$2.string()
23505
23539
  }).passthrough();
23506
- var ResourceContentsSchema = z$1.object({
23540
+ var ResourceContentsSchema = z$2.object({
23507
23541
  /**
23508
23542
  * The URI of this resource.
23509
23543
  */
23510
- uri: z$1.string(),
23544
+ uri: z$2.string(),
23511
23545
  /**
23512
23546
  * The MIME type of this resource, if known.
23513
23547
  */
23514
- mimeType: z$1.optional(z$1.string())
23548
+ mimeType: z$2.optional(z$2.string())
23515
23549
  }).passthrough();
23516
23550
  var TextResourceContentsSchema = ResourceContentsSchema.extend({
23517
- text: z$1.string()
23551
+ text: z$2.string()
23518
23552
  });
23519
23553
  var BlobResourceContentsSchema = ResourceContentsSchema.extend({
23520
- blob: z$1.string().base64()
23554
+ blob: z$2.string().base64()
23521
23555
  });
23522
- var EmbeddedResourceSchema = z$1.object({
23523
- type: z$1.literal("resource"),
23524
- resource: z$1.union([TextResourceContentsSchema, BlobResourceContentsSchema])
23556
+ var EmbeddedResourceSchema = z$2.object({
23557
+ type: z$2.literal("resource"),
23558
+ resource: z$2.union([TextResourceContentsSchema, BlobResourceContentsSchema])
23525
23559
  }).passthrough();
23526
23560
  ResultSchema.extend({
23527
- content: z$1.array(
23528
- z$1.union([TextContentSchema, ImageContentSchema, EmbeddedResourceSchema])
23561
+ content: z$2.array(
23562
+ z$2.union([TextContentSchema, ImageContentSchema, EmbeddedResourceSchema])
23529
23563
  ),
23530
- isError: z$1.boolean().default(false).optional()
23564
+ isError: z$2.boolean().default(false).optional()
23531
23565
  }).or(
23532
23566
  ResultSchema.extend({
23533
- toolResult: z$1.unknown()
23567
+ toolResult: z$2.unknown()
23534
23568
  })
23535
23569
  );
23536
23570
  var JSONRPC_VERSION = "2.0";
23537
- var JSONRPCRequestSchema = z$1.object({
23538
- jsonrpc: z$1.literal(JSONRPC_VERSION),
23539
- id: z$1.union([z$1.string(), z$1.number().int()])
23571
+ var JSONRPCRequestSchema = z$2.object({
23572
+ jsonrpc: z$2.literal(JSONRPC_VERSION),
23573
+ id: z$2.union([z$2.string(), z$2.number().int()])
23540
23574
  }).merge(RequestSchema).strict();
23541
- var JSONRPCResponseSchema = z$1.object({
23542
- jsonrpc: z$1.literal(JSONRPC_VERSION),
23543
- id: z$1.union([z$1.string(), z$1.number().int()]),
23575
+ var JSONRPCResponseSchema = z$2.object({
23576
+ jsonrpc: z$2.literal(JSONRPC_VERSION),
23577
+ id: z$2.union([z$2.string(), z$2.number().int()]),
23544
23578
  result: ResultSchema
23545
23579
  }).strict();
23546
- var JSONRPCErrorSchema = z$1.object({
23547
- jsonrpc: z$1.literal(JSONRPC_VERSION),
23548
- id: z$1.union([z$1.string(), z$1.number().int()]),
23549
- error: z$1.object({
23550
- code: z$1.number().int(),
23551
- message: z$1.string(),
23552
- data: z$1.optional(z$1.unknown())
23580
+ var JSONRPCErrorSchema = z$2.object({
23581
+ jsonrpc: z$2.literal(JSONRPC_VERSION),
23582
+ id: z$2.union([z$2.string(), z$2.number().int()]),
23583
+ error: z$2.object({
23584
+ code: z$2.number().int(),
23585
+ message: z$2.string(),
23586
+ data: z$2.optional(z$2.unknown())
23553
23587
  })
23554
23588
  }).strict();
23555
- var JSONRPCNotificationSchema = z$1.object({
23556
- jsonrpc: z$1.literal(JSONRPC_VERSION)
23589
+ var JSONRPCNotificationSchema = z$2.object({
23590
+ jsonrpc: z$2.literal(JSONRPC_VERSION)
23557
23591
  }).merge(
23558
- z$1.object({
23559
- method: z$1.string(),
23560
- params: z$1.optional(BaseParamsSchema)
23592
+ z$2.object({
23593
+ method: z$2.string(),
23594
+ params: z$2.optional(BaseParamsSchema)
23561
23595
  })
23562
23596
  ).strict();
23563
- z$1.union([
23597
+ z$2.union([
23564
23598
  JSONRPCRequestSchema,
23565
23599
  JSONRPCNotificationSchema,
23566
23600
  JSONRPCResponseSchema,
@@ -24055,1568 +24089,7 @@ __publicField(Tiktoken, "specialTokenRegex", (tokens) => {
24055
24089
  return new RegExp(tokens.map((i) => escapeRegex(i)).join("|"), "g");
24056
24090
  });
24057
24091
 
24058
- /**
24059
- * @module LRUCache
24060
- */
24061
- const defaultPerf = (typeof performance === 'object' &&
24062
- performance &&
24063
- typeof performance.now === 'function') ?
24064
- performance
24065
- : Date;
24066
- const warned = new Set();
24067
- /* c8 ignore start */
24068
- const PROCESS = (typeof process === 'object' && !!process ?
24069
- process
24070
- : {});
24071
- /* c8 ignore start */
24072
- const emitWarning = (msg, type, code, fn) => {
24073
- typeof PROCESS.emitWarning === 'function' ?
24074
- PROCESS.emitWarning(msg, type, code, fn)
24075
- : console.error(`[${code}] ${type}: ${msg}`);
24076
- };
24077
- let AC = globalThis.AbortController;
24078
- let AS = globalThis.AbortSignal;
24079
- /* c8 ignore start */
24080
- if (typeof AC === 'undefined') {
24081
- //@ts-ignore
24082
- AS = class AbortSignal {
24083
- onabort;
24084
- _onabort = [];
24085
- reason;
24086
- aborted = false;
24087
- addEventListener(_, fn) {
24088
- this._onabort.push(fn);
24089
- }
24090
- };
24091
- //@ts-ignore
24092
- AC = class AbortController {
24093
- constructor() {
24094
- warnACPolyfill();
24095
- }
24096
- signal = new AS();
24097
- abort(reason) {
24098
- if (this.signal.aborted)
24099
- return;
24100
- //@ts-ignore
24101
- this.signal.reason = reason;
24102
- //@ts-ignore
24103
- this.signal.aborted = true;
24104
- //@ts-ignore
24105
- for (const fn of this.signal._onabort) {
24106
- fn(reason);
24107
- }
24108
- this.signal.onabort?.(reason);
24109
- }
24110
- };
24111
- let printACPolyfillWarning = PROCESS.env?.LRU_CACHE_IGNORE_AC_WARNING !== '1';
24112
- const warnACPolyfill = () => {
24113
- if (!printACPolyfillWarning)
24114
- return;
24115
- printACPolyfillWarning = false;
24116
- emitWarning('AbortController is not defined. If using lru-cache in ' +
24117
- 'node 14, load an AbortController polyfill from the ' +
24118
- '`node-abort-controller` package. A minimal polyfill is ' +
24119
- 'provided for use by LRUCache.fetch(), but it should not be ' +
24120
- 'relied upon in other contexts (eg, passing it to other APIs that ' +
24121
- 'use AbortController/AbortSignal might have undesirable effects). ' +
24122
- 'You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.', 'NO_ABORT_CONTROLLER', 'ENOTSUP', warnACPolyfill);
24123
- };
24124
- }
24125
- /* c8 ignore stop */
24126
- const shouldWarn = (code) => !warned.has(code);
24127
- const isPosInt = (n) => n && n === Math.floor(n) && n > 0 && isFinite(n);
24128
- /* c8 ignore start */
24129
- // This is a little bit ridiculous, tbh.
24130
- // The maximum array length is 2^32-1 or thereabouts on most JS impls.
24131
- // And well before that point, you're caching the entire world, I mean,
24132
- // that's ~32GB of just integers for the next/prev links, plus whatever
24133
- // else to hold that many keys and values. Just filling the memory with
24134
- // zeroes at init time is brutal when you get that big.
24135
- // But why not be complete?
24136
- // Maybe in the future, these limits will have expanded.
24137
- const getUintArray = (max) => !isPosInt(max) ? null
24138
- : max <= Math.pow(2, 8) ? Uint8Array
24139
- : max <= Math.pow(2, 16) ? Uint16Array
24140
- : max <= Math.pow(2, 32) ? Uint32Array
24141
- : max <= Number.MAX_SAFE_INTEGER ? ZeroArray
24142
- : null;
24143
- /* c8 ignore stop */
24144
- class ZeroArray extends Array {
24145
- constructor(size) {
24146
- super(size);
24147
- this.fill(0);
24148
- }
24149
- }
24150
- class Stack {
24151
- heap;
24152
- length;
24153
- // private constructor
24154
- static #constructing = false;
24155
- static create(max) {
24156
- const HeapCls = getUintArray(max);
24157
- if (!HeapCls)
24158
- return [];
24159
- Stack.#constructing = true;
24160
- const s = new Stack(max, HeapCls);
24161
- Stack.#constructing = false;
24162
- return s;
24163
- }
24164
- constructor(max, HeapCls) {
24165
- /* c8 ignore start */
24166
- if (!Stack.#constructing) {
24167
- throw new TypeError('instantiate Stack using Stack.create(n)');
24168
- }
24169
- /* c8 ignore stop */
24170
- this.heap = new HeapCls(max);
24171
- this.length = 0;
24172
- }
24173
- push(n) {
24174
- this.heap[this.length++] = n;
24175
- }
24176
- pop() {
24177
- return this.heap[--this.length];
24178
- }
24179
- }
24180
- /**
24181
- * Default export, the thing you're using this module to get.
24182
- *
24183
- * The `K` and `V` types define the key and value types, respectively. The
24184
- * optional `FC` type defines the type of the `context` object passed to
24185
- * `cache.fetch()` and `cache.memo()`.
24186
- *
24187
- * Keys and values **must not** be `null` or `undefined`.
24188
- *
24189
- * All properties from the options object (with the exception of `max`,
24190
- * `maxSize`, `fetchMethod`, `memoMethod`, `dispose` and `disposeAfter`) are
24191
- * added as normal public members. (The listed options are read-only getters.)
24192
- *
24193
- * Changing any of these will alter the defaults for subsequent method calls.
24194
- */
24195
- class LRUCache {
24196
- // options that cannot be changed without disaster
24197
- #max;
24198
- #maxSize;
24199
- #dispose;
24200
- #onInsert;
24201
- #disposeAfter;
24202
- #fetchMethod;
24203
- #memoMethod;
24204
- #perf;
24205
- /**
24206
- * {@link LRUCache.OptionsBase.perf}
24207
- */
24208
- get perf() {
24209
- return this.#perf;
24210
- }
24211
- /**
24212
- * {@link LRUCache.OptionsBase.ttl}
24213
- */
24214
- ttl;
24215
- /**
24216
- * {@link LRUCache.OptionsBase.ttlResolution}
24217
- */
24218
- ttlResolution;
24219
- /**
24220
- * {@link LRUCache.OptionsBase.ttlAutopurge}
24221
- */
24222
- ttlAutopurge;
24223
- /**
24224
- * {@link LRUCache.OptionsBase.updateAgeOnGet}
24225
- */
24226
- updateAgeOnGet;
24227
- /**
24228
- * {@link LRUCache.OptionsBase.updateAgeOnHas}
24229
- */
24230
- updateAgeOnHas;
24231
- /**
24232
- * {@link LRUCache.OptionsBase.allowStale}
24233
- */
24234
- allowStale;
24235
- /**
24236
- * {@link LRUCache.OptionsBase.noDisposeOnSet}
24237
- */
24238
- noDisposeOnSet;
24239
- /**
24240
- * {@link LRUCache.OptionsBase.noUpdateTTL}
24241
- */
24242
- noUpdateTTL;
24243
- /**
24244
- * {@link LRUCache.OptionsBase.maxEntrySize}
24245
- */
24246
- maxEntrySize;
24247
- /**
24248
- * {@link LRUCache.OptionsBase.sizeCalculation}
24249
- */
24250
- sizeCalculation;
24251
- /**
24252
- * {@link LRUCache.OptionsBase.noDeleteOnFetchRejection}
24253
- */
24254
- noDeleteOnFetchRejection;
24255
- /**
24256
- * {@link LRUCache.OptionsBase.noDeleteOnStaleGet}
24257
- */
24258
- noDeleteOnStaleGet;
24259
- /**
24260
- * {@link LRUCache.OptionsBase.allowStaleOnFetchAbort}
24261
- */
24262
- allowStaleOnFetchAbort;
24263
- /**
24264
- * {@link LRUCache.OptionsBase.allowStaleOnFetchRejection}
24265
- */
24266
- allowStaleOnFetchRejection;
24267
- /**
24268
- * {@link LRUCache.OptionsBase.ignoreFetchAbort}
24269
- */
24270
- ignoreFetchAbort;
24271
- // computed properties
24272
- #size;
24273
- #calculatedSize;
24274
- #keyMap;
24275
- #keyList;
24276
- #valList;
24277
- #next;
24278
- #prev;
24279
- #head;
24280
- #tail;
24281
- #free;
24282
- #disposed;
24283
- #sizes;
24284
- #starts;
24285
- #ttls;
24286
- #hasDispose;
24287
- #hasFetchMethod;
24288
- #hasDisposeAfter;
24289
- #hasOnInsert;
24290
- /**
24291
- * Do not call this method unless you need to inspect the
24292
- * inner workings of the cache. If anything returned by this
24293
- * object is modified in any way, strange breakage may occur.
24294
- *
24295
- * These fields are private for a reason!
24296
- *
24297
- * @internal
24298
- */
24299
- static unsafeExposeInternals(c) {
24300
- return {
24301
- // properties
24302
- starts: c.#starts,
24303
- ttls: c.#ttls,
24304
- sizes: c.#sizes,
24305
- keyMap: c.#keyMap,
24306
- keyList: c.#keyList,
24307
- valList: c.#valList,
24308
- next: c.#next,
24309
- prev: c.#prev,
24310
- get head() {
24311
- return c.#head;
24312
- },
24313
- get tail() {
24314
- return c.#tail;
24315
- },
24316
- free: c.#free,
24317
- // methods
24318
- isBackgroundFetch: (p) => c.#isBackgroundFetch(p),
24319
- backgroundFetch: (k, index, options, context) => c.#backgroundFetch(k, index, options, context),
24320
- moveToTail: (index) => c.#moveToTail(index),
24321
- indexes: (options) => c.#indexes(options),
24322
- rindexes: (options) => c.#rindexes(options),
24323
- isStale: (index) => c.#isStale(index),
24324
- };
24325
- }
24326
- // Protected read-only members
24327
- /**
24328
- * {@link LRUCache.OptionsBase.max} (read-only)
24329
- */
24330
- get max() {
24331
- return this.#max;
24332
- }
24333
- /**
24334
- * {@link LRUCache.OptionsBase.maxSize} (read-only)
24335
- */
24336
- get maxSize() {
24337
- return this.#maxSize;
24338
- }
24339
- /**
24340
- * The total computed size of items in the cache (read-only)
24341
- */
24342
- get calculatedSize() {
24343
- return this.#calculatedSize;
24344
- }
24345
- /**
24346
- * The number of items stored in the cache (read-only)
24347
- */
24348
- get size() {
24349
- return this.#size;
24350
- }
24351
- /**
24352
- * {@link LRUCache.OptionsBase.fetchMethod} (read-only)
24353
- */
24354
- get fetchMethod() {
24355
- return this.#fetchMethod;
24356
- }
24357
- get memoMethod() {
24358
- return this.#memoMethod;
24359
- }
24360
- /**
24361
- * {@link LRUCache.OptionsBase.dispose} (read-only)
24362
- */
24363
- get dispose() {
24364
- return this.#dispose;
24365
- }
24366
- /**
24367
- * {@link LRUCache.OptionsBase.onInsert} (read-only)
24368
- */
24369
- get onInsert() {
24370
- return this.#onInsert;
24371
- }
24372
- /**
24373
- * {@link LRUCache.OptionsBase.disposeAfter} (read-only)
24374
- */
24375
- get disposeAfter() {
24376
- return this.#disposeAfter;
24377
- }
24378
- constructor(options) {
24379
- const { max = 0, ttl, ttlResolution = 1, ttlAutopurge, updateAgeOnGet, updateAgeOnHas, allowStale, dispose, onInsert, disposeAfter, noDisposeOnSet, noUpdateTTL, maxSize = 0, maxEntrySize = 0, sizeCalculation, fetchMethod, memoMethod, noDeleteOnFetchRejection, noDeleteOnStaleGet, allowStaleOnFetchRejection, allowStaleOnFetchAbort, ignoreFetchAbort, perf, } = options;
24380
- if (perf !== undefined) {
24381
- if (typeof perf?.now !== 'function') {
24382
- throw new TypeError('perf option must have a now() method if specified');
24383
- }
24384
- }
24385
- this.#perf = perf ?? defaultPerf;
24386
- if (max !== 0 && !isPosInt(max)) {
24387
- throw new TypeError('max option must be a nonnegative integer');
24388
- }
24389
- const UintArray = max ? getUintArray(max) : Array;
24390
- if (!UintArray) {
24391
- throw new Error('invalid max value: ' + max);
24392
- }
24393
- this.#max = max;
24394
- this.#maxSize = maxSize;
24395
- this.maxEntrySize = maxEntrySize || this.#maxSize;
24396
- this.sizeCalculation = sizeCalculation;
24397
- if (this.sizeCalculation) {
24398
- if (!this.#maxSize && !this.maxEntrySize) {
24399
- throw new TypeError('cannot set sizeCalculation without setting maxSize or maxEntrySize');
24400
- }
24401
- if (typeof this.sizeCalculation !== 'function') {
24402
- throw new TypeError('sizeCalculation set to non-function');
24403
- }
24404
- }
24405
- if (memoMethod !== undefined &&
24406
- typeof memoMethod !== 'function') {
24407
- throw new TypeError('memoMethod must be a function if defined');
24408
- }
24409
- this.#memoMethod = memoMethod;
24410
- if (fetchMethod !== undefined &&
24411
- typeof fetchMethod !== 'function') {
24412
- throw new TypeError('fetchMethod must be a function if specified');
24413
- }
24414
- this.#fetchMethod = fetchMethod;
24415
- this.#hasFetchMethod = !!fetchMethod;
24416
- this.#keyMap = new Map();
24417
- this.#keyList = new Array(max).fill(undefined);
24418
- this.#valList = new Array(max).fill(undefined);
24419
- this.#next = new UintArray(max);
24420
- this.#prev = new UintArray(max);
24421
- this.#head = 0;
24422
- this.#tail = 0;
24423
- this.#free = Stack.create(max);
24424
- this.#size = 0;
24425
- this.#calculatedSize = 0;
24426
- if (typeof dispose === 'function') {
24427
- this.#dispose = dispose;
24428
- }
24429
- if (typeof onInsert === 'function') {
24430
- this.#onInsert = onInsert;
24431
- }
24432
- if (typeof disposeAfter === 'function') {
24433
- this.#disposeAfter = disposeAfter;
24434
- this.#disposed = [];
24435
- }
24436
- else {
24437
- this.#disposeAfter = undefined;
24438
- this.#disposed = undefined;
24439
- }
24440
- this.#hasDispose = !!this.#dispose;
24441
- this.#hasOnInsert = !!this.#onInsert;
24442
- this.#hasDisposeAfter = !!this.#disposeAfter;
24443
- this.noDisposeOnSet = !!noDisposeOnSet;
24444
- this.noUpdateTTL = !!noUpdateTTL;
24445
- this.noDeleteOnFetchRejection = !!noDeleteOnFetchRejection;
24446
- this.allowStaleOnFetchRejection = !!allowStaleOnFetchRejection;
24447
- this.allowStaleOnFetchAbort = !!allowStaleOnFetchAbort;
24448
- this.ignoreFetchAbort = !!ignoreFetchAbort;
24449
- // NB: maxEntrySize is set to maxSize if it's set
24450
- if (this.maxEntrySize !== 0) {
24451
- if (this.#maxSize !== 0) {
24452
- if (!isPosInt(this.#maxSize)) {
24453
- throw new TypeError('maxSize must be a positive integer if specified');
24454
- }
24455
- }
24456
- if (!isPosInt(this.maxEntrySize)) {
24457
- throw new TypeError('maxEntrySize must be a positive integer if specified');
24458
- }
24459
- this.#initializeSizeTracking();
24460
- }
24461
- this.allowStale = !!allowStale;
24462
- this.noDeleteOnStaleGet = !!noDeleteOnStaleGet;
24463
- this.updateAgeOnGet = !!updateAgeOnGet;
24464
- this.updateAgeOnHas = !!updateAgeOnHas;
24465
- this.ttlResolution =
24466
- isPosInt(ttlResolution) || ttlResolution === 0 ?
24467
- ttlResolution
24468
- : 1;
24469
- this.ttlAutopurge = !!ttlAutopurge;
24470
- this.ttl = ttl || 0;
24471
- if (this.ttl) {
24472
- if (!isPosInt(this.ttl)) {
24473
- throw new TypeError('ttl must be a positive integer if specified');
24474
- }
24475
- this.#initializeTTLTracking();
24476
- }
24477
- // do not allow completely unbounded caches
24478
- if (this.#max === 0 && this.ttl === 0 && this.#maxSize === 0) {
24479
- throw new TypeError('At least one of max, maxSize, or ttl is required');
24480
- }
24481
- if (!this.ttlAutopurge && !this.#max && !this.#maxSize) {
24482
- const code = 'LRU_CACHE_UNBOUNDED';
24483
- if (shouldWarn(code)) {
24484
- warned.add(code);
24485
- const msg = 'TTL caching without ttlAutopurge, max, or maxSize can ' +
24486
- 'result in unbounded memory consumption.';
24487
- emitWarning(msg, 'UnboundedCacheWarning', code, LRUCache);
24488
- }
24489
- }
24490
- }
24491
- /**
24492
- * Return the number of ms left in the item's TTL. If item is not in cache,
24493
- * returns `0`. Returns `Infinity` if item is in cache without a defined TTL.
24494
- */
24495
- getRemainingTTL(key) {
24496
- return this.#keyMap.has(key) ? Infinity : 0;
24497
- }
24498
- #initializeTTLTracking() {
24499
- const ttls = new ZeroArray(this.#max);
24500
- const starts = new ZeroArray(this.#max);
24501
- this.#ttls = ttls;
24502
- this.#starts = starts;
24503
- this.#setItemTTL = (index, ttl, start = this.#perf.now()) => {
24504
- starts[index] = ttl !== 0 ? start : 0;
24505
- ttls[index] = ttl;
24506
- if (ttl !== 0 && this.ttlAutopurge) {
24507
- const t = setTimeout(() => {
24508
- if (this.#isStale(index)) {
24509
- this.#delete(this.#keyList[index], 'expire');
24510
- }
24511
- }, ttl + 1);
24512
- // unref() not supported on all platforms
24513
- /* c8 ignore start */
24514
- if (t.unref) {
24515
- t.unref();
24516
- }
24517
- /* c8 ignore stop */
24518
- }
24519
- };
24520
- this.#updateItemAge = index => {
24521
- starts[index] = ttls[index] !== 0 ? this.#perf.now() : 0;
24522
- };
24523
- this.#statusTTL = (status, index) => {
24524
- if (ttls[index]) {
24525
- const ttl = ttls[index];
24526
- const start = starts[index];
24527
- /* c8 ignore next */
24528
- if (!ttl || !start)
24529
- return;
24530
- status.ttl = ttl;
24531
- status.start = start;
24532
- status.now = cachedNow || getNow();
24533
- const age = status.now - start;
24534
- status.remainingTTL = ttl - age;
24535
- }
24536
- };
24537
- // debounce calls to perf.now() to 1s so we're not hitting
24538
- // that costly call repeatedly.
24539
- let cachedNow = 0;
24540
- const getNow = () => {
24541
- const n = this.#perf.now();
24542
- if (this.ttlResolution > 0) {
24543
- cachedNow = n;
24544
- const t = setTimeout(() => (cachedNow = 0), this.ttlResolution);
24545
- // not available on all platforms
24546
- /* c8 ignore start */
24547
- if (t.unref) {
24548
- t.unref();
24549
- }
24550
- /* c8 ignore stop */
24551
- }
24552
- return n;
24553
- };
24554
- this.getRemainingTTL = key => {
24555
- const index = this.#keyMap.get(key);
24556
- if (index === undefined) {
24557
- return 0;
24558
- }
24559
- const ttl = ttls[index];
24560
- const start = starts[index];
24561
- if (!ttl || !start) {
24562
- return Infinity;
24563
- }
24564
- const age = (cachedNow || getNow()) - start;
24565
- return ttl - age;
24566
- };
24567
- this.#isStale = index => {
24568
- const s = starts[index];
24569
- const t = ttls[index];
24570
- return !!t && !!s && (cachedNow || getNow()) - s > t;
24571
- };
24572
- }
24573
- // conditionally set private methods related to TTL
24574
- #updateItemAge = () => { };
24575
- #statusTTL = () => { };
24576
- #setItemTTL = () => { };
24577
- /* c8 ignore stop */
24578
- #isStale = () => false;
24579
- #initializeSizeTracking() {
24580
- const sizes = new ZeroArray(this.#max);
24581
- this.#calculatedSize = 0;
24582
- this.#sizes = sizes;
24583
- this.#removeItemSize = index => {
24584
- this.#calculatedSize -= sizes[index];
24585
- sizes[index] = 0;
24586
- };
24587
- this.#requireSize = (k, v, size, sizeCalculation) => {
24588
- // provisionally accept background fetches.
24589
- // actual value size will be checked when they return.
24590
- if (this.#isBackgroundFetch(v)) {
24591
- return 0;
24592
- }
24593
- if (!isPosInt(size)) {
24594
- if (sizeCalculation) {
24595
- if (typeof sizeCalculation !== 'function') {
24596
- throw new TypeError('sizeCalculation must be a function');
24597
- }
24598
- size = sizeCalculation(v, k);
24599
- if (!isPosInt(size)) {
24600
- throw new TypeError('sizeCalculation return invalid (expect positive integer)');
24601
- }
24602
- }
24603
- else {
24604
- throw new TypeError('invalid size value (must be positive integer). ' +
24605
- 'When maxSize or maxEntrySize is used, sizeCalculation ' +
24606
- 'or size must be set.');
24607
- }
24608
- }
24609
- return size;
24610
- };
24611
- this.#addItemSize = (index, size, status) => {
24612
- sizes[index] = size;
24613
- if (this.#maxSize) {
24614
- const maxSize = this.#maxSize - sizes[index];
24615
- while (this.#calculatedSize > maxSize) {
24616
- this.#evict(true);
24617
- }
24618
- }
24619
- this.#calculatedSize += sizes[index];
24620
- if (status) {
24621
- status.entrySize = size;
24622
- status.totalCalculatedSize = this.#calculatedSize;
24623
- }
24624
- };
24625
- }
24626
- #removeItemSize = _i => { };
24627
- #addItemSize = (_i, _s, _st) => { };
24628
- #requireSize = (_k, _v, size, sizeCalculation) => {
24629
- if (size || sizeCalculation) {
24630
- throw new TypeError('cannot set size without setting maxSize or maxEntrySize on cache');
24631
- }
24632
- return 0;
24633
- };
24634
- *#indexes({ allowStale = this.allowStale } = {}) {
24635
- if (this.#size) {
24636
- for (let i = this.#tail; true;) {
24637
- if (!this.#isValidIndex(i)) {
24638
- break;
24639
- }
24640
- if (allowStale || !this.#isStale(i)) {
24641
- yield i;
24642
- }
24643
- if (i === this.#head) {
24644
- break;
24645
- }
24646
- else {
24647
- i = this.#prev[i];
24648
- }
24649
- }
24650
- }
24651
- }
24652
- *#rindexes({ allowStale = this.allowStale } = {}) {
24653
- if (this.#size) {
24654
- for (let i = this.#head; true;) {
24655
- if (!this.#isValidIndex(i)) {
24656
- break;
24657
- }
24658
- if (allowStale || !this.#isStale(i)) {
24659
- yield i;
24660
- }
24661
- if (i === this.#tail) {
24662
- break;
24663
- }
24664
- else {
24665
- i = this.#next[i];
24666
- }
24667
- }
24668
- }
24669
- }
24670
- #isValidIndex(index) {
24671
- return (index !== undefined &&
24672
- this.#keyMap.get(this.#keyList[index]) === index);
24673
- }
24674
- /**
24675
- * Return a generator yielding `[key, value]` pairs,
24676
- * in order from most recently used to least recently used.
24677
- */
24678
- *entries() {
24679
- for (const i of this.#indexes()) {
24680
- if (this.#valList[i] !== undefined &&
24681
- this.#keyList[i] !== undefined &&
24682
- !this.#isBackgroundFetch(this.#valList[i])) {
24683
- yield [this.#keyList[i], this.#valList[i]];
24684
- }
24685
- }
24686
- }
24687
- /**
24688
- * Inverse order version of {@link LRUCache.entries}
24689
- *
24690
- * Return a generator yielding `[key, value]` pairs,
24691
- * in order from least recently used to most recently used.
24692
- */
24693
- *rentries() {
24694
- for (const i of this.#rindexes()) {
24695
- if (this.#valList[i] !== undefined &&
24696
- this.#keyList[i] !== undefined &&
24697
- !this.#isBackgroundFetch(this.#valList[i])) {
24698
- yield [this.#keyList[i], this.#valList[i]];
24699
- }
24700
- }
24701
- }
24702
- /**
24703
- * Return a generator yielding the keys in the cache,
24704
- * in order from most recently used to least recently used.
24705
- */
24706
- *keys() {
24707
- for (const i of this.#indexes()) {
24708
- const k = this.#keyList[i];
24709
- if (k !== undefined &&
24710
- !this.#isBackgroundFetch(this.#valList[i])) {
24711
- yield k;
24712
- }
24713
- }
24714
- }
24715
- /**
24716
- * Inverse order version of {@link LRUCache.keys}
24717
- *
24718
- * Return a generator yielding the keys in the cache,
24719
- * in order from least recently used to most recently used.
24720
- */
24721
- *rkeys() {
24722
- for (const i of this.#rindexes()) {
24723
- const k = this.#keyList[i];
24724
- if (k !== undefined &&
24725
- !this.#isBackgroundFetch(this.#valList[i])) {
24726
- yield k;
24727
- }
24728
- }
24729
- }
24730
- /**
24731
- * Return a generator yielding the values in the cache,
24732
- * in order from most recently used to least recently used.
24733
- */
24734
- *values() {
24735
- for (const i of this.#indexes()) {
24736
- const v = this.#valList[i];
24737
- if (v !== undefined &&
24738
- !this.#isBackgroundFetch(this.#valList[i])) {
24739
- yield this.#valList[i];
24740
- }
24741
- }
24742
- }
24743
- /**
24744
- * Inverse order version of {@link LRUCache.values}
24745
- *
24746
- * Return a generator yielding the values in the cache,
24747
- * in order from least recently used to most recently used.
24748
- */
24749
- *rvalues() {
24750
- for (const i of this.#rindexes()) {
24751
- const v = this.#valList[i];
24752
- if (v !== undefined &&
24753
- !this.#isBackgroundFetch(this.#valList[i])) {
24754
- yield this.#valList[i];
24755
- }
24756
- }
24757
- }
24758
- /**
24759
- * Iterating over the cache itself yields the same results as
24760
- * {@link LRUCache.entries}
24761
- */
24762
- [Symbol.iterator]() {
24763
- return this.entries();
24764
- }
24765
- /**
24766
- * A String value that is used in the creation of the default string
24767
- * description of an object. Called by the built-in method
24768
- * `Object.prototype.toString`.
24769
- */
24770
- [Symbol.toStringTag] = 'LRUCache';
24771
- /**
24772
- * Find a value for which the supplied fn method returns a truthy value,
24773
- * similar to `Array.find()`. fn is called as `fn(value, key, cache)`.
24774
- */
24775
- find(fn, getOptions = {}) {
24776
- for (const i of this.#indexes()) {
24777
- const v = this.#valList[i];
24778
- const value = this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v;
24779
- if (value === undefined)
24780
- continue;
24781
- if (fn(value, this.#keyList[i], this)) {
24782
- return this.get(this.#keyList[i], getOptions);
24783
- }
24784
- }
24785
- }
24786
- /**
24787
- * Call the supplied function on each item in the cache, in order from most
24788
- * recently used to least recently used.
24789
- *
24790
- * `fn` is called as `fn(value, key, cache)`.
24791
- *
24792
- * If `thisp` is provided, function will be called in the `this`-context of
24793
- * the provided object, or the cache if no `thisp` object is provided.
24794
- *
24795
- * Does not update age or recenty of use, or iterate over stale values.
24796
- */
24797
- forEach(fn, thisp = this) {
24798
- for (const i of this.#indexes()) {
24799
- const v = this.#valList[i];
24800
- const value = this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v;
24801
- if (value === undefined)
24802
- continue;
24803
- fn.call(thisp, value, this.#keyList[i], this);
24804
- }
24805
- }
24806
- /**
24807
- * The same as {@link LRUCache.forEach} but items are iterated over in
24808
- * reverse order. (ie, less recently used items are iterated over first.)
24809
- */
24810
- rforEach(fn, thisp = this) {
24811
- for (const i of this.#rindexes()) {
24812
- const v = this.#valList[i];
24813
- const value = this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v;
24814
- if (value === undefined)
24815
- continue;
24816
- fn.call(thisp, value, this.#keyList[i], this);
24817
- }
24818
- }
24819
- /**
24820
- * Delete any stale entries. Returns true if anything was removed,
24821
- * false otherwise.
24822
- */
24823
- purgeStale() {
24824
- let deleted = false;
24825
- for (const i of this.#rindexes({ allowStale: true })) {
24826
- if (this.#isStale(i)) {
24827
- this.#delete(this.#keyList[i], 'expire');
24828
- deleted = true;
24829
- }
24830
- }
24831
- return deleted;
24832
- }
24833
- /**
24834
- * Get the extended info about a given entry, to get its value, size, and
24835
- * TTL info simultaneously. Returns `undefined` if the key is not present.
24836
- *
24837
- * Unlike {@link LRUCache#dump}, which is designed to be portable and survive
24838
- * serialization, the `start` value is always the current timestamp, and the
24839
- * `ttl` is a calculated remaining time to live (negative if expired).
24840
- *
24841
- * Always returns stale values, if their info is found in the cache, so be
24842
- * sure to check for expirations (ie, a negative {@link LRUCache.Entry#ttl})
24843
- * if relevant.
24844
- */
24845
- info(key) {
24846
- const i = this.#keyMap.get(key);
24847
- if (i === undefined)
24848
- return undefined;
24849
- const v = this.#valList[i];
24850
- /* c8 ignore start - this isn't tested for the info function,
24851
- * but it's the same logic as found in other places. */
24852
- const value = this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v;
24853
- if (value === undefined)
24854
- return undefined;
24855
- /* c8 ignore end */
24856
- const entry = { value };
24857
- if (this.#ttls && this.#starts) {
24858
- const ttl = this.#ttls[i];
24859
- const start = this.#starts[i];
24860
- if (ttl && start) {
24861
- const remain = ttl - (this.#perf.now() - start);
24862
- entry.ttl = remain;
24863
- entry.start = Date.now();
24864
- }
24865
- }
24866
- if (this.#sizes) {
24867
- entry.size = this.#sizes[i];
24868
- }
24869
- return entry;
24870
- }
24871
- /**
24872
- * Return an array of [key, {@link LRUCache.Entry}] tuples which can be
24873
- * passed to {@link LRUCache#load}.
24874
- *
24875
- * The `start` fields are calculated relative to a portable `Date.now()`
24876
- * timestamp, even if `performance.now()` is available.
24877
- *
24878
- * Stale entries are always included in the `dump`, even if
24879
- * {@link LRUCache.OptionsBase.allowStale} is false.
24880
- *
24881
- * Note: this returns an actual array, not a generator, so it can be more
24882
- * easily passed around.
24883
- */
24884
- dump() {
24885
- const arr = [];
24886
- for (const i of this.#indexes({ allowStale: true })) {
24887
- const key = this.#keyList[i];
24888
- const v = this.#valList[i];
24889
- const value = this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v;
24890
- if (value === undefined || key === undefined)
24891
- continue;
24892
- const entry = { value };
24893
- if (this.#ttls && this.#starts) {
24894
- entry.ttl = this.#ttls[i];
24895
- // always dump the start relative to a portable timestamp
24896
- // it's ok for this to be a bit slow, it's a rare operation.
24897
- const age = this.#perf.now() - this.#starts[i];
24898
- entry.start = Math.floor(Date.now() - age);
24899
- }
24900
- if (this.#sizes) {
24901
- entry.size = this.#sizes[i];
24902
- }
24903
- arr.unshift([key, entry]);
24904
- }
24905
- return arr;
24906
- }
24907
- /**
24908
- * Reset the cache and load in the items in entries in the order listed.
24909
- *
24910
- * The shape of the resulting cache may be different if the same options are
24911
- * not used in both caches.
24912
- *
24913
- * The `start` fields are assumed to be calculated relative to a portable
24914
- * `Date.now()` timestamp, even if `performance.now()` is available.
24915
- */
24916
- load(arr) {
24917
- this.clear();
24918
- for (const [key, entry] of arr) {
24919
- if (entry.start) {
24920
- // entry.start is a portable timestamp, but we may be using
24921
- // node's performance.now(), so calculate the offset, so that
24922
- // we get the intended remaining TTL, no matter how long it's
24923
- // been on ice.
24924
- //
24925
- // it's ok for this to be a bit slow, it's a rare operation.
24926
- const age = Date.now() - entry.start;
24927
- entry.start = this.#perf.now() - age;
24928
- }
24929
- this.set(key, entry.value, entry);
24930
- }
24931
- }
24932
- /**
24933
- * Add a value to the cache.
24934
- *
24935
- * Note: if `undefined` is specified as a value, this is an alias for
24936
- * {@link LRUCache#delete}
24937
- *
24938
- * Fields on the {@link LRUCache.SetOptions} options param will override
24939
- * their corresponding values in the constructor options for the scope
24940
- * of this single `set()` operation.
24941
- *
24942
- * If `start` is provided, then that will set the effective start
24943
- * time for the TTL calculation. Note that this must be a previous
24944
- * value of `performance.now()` if supported, or a previous value of
24945
- * `Date.now()` if not.
24946
- *
24947
- * Options object may also include `size`, which will prevent
24948
- * calling the `sizeCalculation` function and just use the specified
24949
- * number if it is a positive integer, and `noDisposeOnSet` which
24950
- * will prevent calling a `dispose` function in the case of
24951
- * overwrites.
24952
- *
24953
- * If the `size` (or return value of `sizeCalculation`) for a given
24954
- * entry is greater than `maxEntrySize`, then the item will not be
24955
- * added to the cache.
24956
- *
24957
- * Will update the recency of the entry.
24958
- *
24959
- * If the value is `undefined`, then this is an alias for
24960
- * `cache.delete(key)`. `undefined` is never stored in the cache.
24961
- */
24962
- set(k, v, setOptions = {}) {
24963
- if (v === undefined) {
24964
- this.delete(k);
24965
- return this;
24966
- }
24967
- const { ttl = this.ttl, start, noDisposeOnSet = this.noDisposeOnSet, sizeCalculation = this.sizeCalculation, status, } = setOptions;
24968
- let { noUpdateTTL = this.noUpdateTTL } = setOptions;
24969
- const size = this.#requireSize(k, v, setOptions.size || 0, sizeCalculation);
24970
- // if the item doesn't fit, don't do anything
24971
- // NB: maxEntrySize set to maxSize by default
24972
- if (this.maxEntrySize && size > this.maxEntrySize) {
24973
- if (status) {
24974
- status.set = 'miss';
24975
- status.maxEntrySizeExceeded = true;
24976
- }
24977
- // have to delete, in case something is there already.
24978
- this.#delete(k, 'set');
24979
- return this;
24980
- }
24981
- let index = this.#size === 0 ? undefined : this.#keyMap.get(k);
24982
- if (index === undefined) {
24983
- // addition
24984
- index = (this.#size === 0 ? this.#tail
24985
- : this.#free.length !== 0 ? this.#free.pop()
24986
- : this.#size === this.#max ? this.#evict(false)
24987
- : this.#size);
24988
- this.#keyList[index] = k;
24989
- this.#valList[index] = v;
24990
- this.#keyMap.set(k, index);
24991
- this.#next[this.#tail] = index;
24992
- this.#prev[index] = this.#tail;
24993
- this.#tail = index;
24994
- this.#size++;
24995
- this.#addItemSize(index, size, status);
24996
- if (status)
24997
- status.set = 'add';
24998
- noUpdateTTL = false;
24999
- if (this.#hasOnInsert) {
25000
- this.#onInsert?.(v, k, 'add');
25001
- }
25002
- }
25003
- else {
25004
- // update
25005
- this.#moveToTail(index);
25006
- const oldVal = this.#valList[index];
25007
- if (v !== oldVal) {
25008
- if (this.#hasFetchMethod && this.#isBackgroundFetch(oldVal)) {
25009
- oldVal.__abortController.abort(new Error('replaced'));
25010
- const { __staleWhileFetching: s } = oldVal;
25011
- if (s !== undefined && !noDisposeOnSet) {
25012
- if (this.#hasDispose) {
25013
- this.#dispose?.(s, k, 'set');
25014
- }
25015
- if (this.#hasDisposeAfter) {
25016
- this.#disposed?.push([s, k, 'set']);
25017
- }
25018
- }
25019
- }
25020
- else if (!noDisposeOnSet) {
25021
- if (this.#hasDispose) {
25022
- this.#dispose?.(oldVal, k, 'set');
25023
- }
25024
- if (this.#hasDisposeAfter) {
25025
- this.#disposed?.push([oldVal, k, 'set']);
25026
- }
25027
- }
25028
- this.#removeItemSize(index);
25029
- this.#addItemSize(index, size, status);
25030
- this.#valList[index] = v;
25031
- if (status) {
25032
- status.set = 'replace';
25033
- const oldValue = oldVal && this.#isBackgroundFetch(oldVal) ?
25034
- oldVal.__staleWhileFetching
25035
- : oldVal;
25036
- if (oldValue !== undefined)
25037
- status.oldValue = oldValue;
25038
- }
25039
- }
25040
- else if (status) {
25041
- status.set = 'update';
25042
- }
25043
- if (this.#hasOnInsert) {
25044
- this.onInsert?.(v, k, v === oldVal ? 'update' : 'replace');
25045
- }
25046
- }
25047
- if (ttl !== 0 && !this.#ttls) {
25048
- this.#initializeTTLTracking();
25049
- }
25050
- if (this.#ttls) {
25051
- if (!noUpdateTTL) {
25052
- this.#setItemTTL(index, ttl, start);
25053
- }
25054
- if (status)
25055
- this.#statusTTL(status, index);
25056
- }
25057
- if (!noDisposeOnSet && this.#hasDisposeAfter && this.#disposed) {
25058
- const dt = this.#disposed;
25059
- let task;
25060
- while ((task = dt?.shift())) {
25061
- this.#disposeAfter?.(...task);
25062
- }
25063
- }
25064
- return this;
25065
- }
25066
- /**
25067
- * Evict the least recently used item, returning its value or
25068
- * `undefined` if cache is empty.
25069
- */
25070
- pop() {
25071
- try {
25072
- while (this.#size) {
25073
- const val = this.#valList[this.#head];
25074
- this.#evict(true);
25075
- if (this.#isBackgroundFetch(val)) {
25076
- if (val.__staleWhileFetching) {
25077
- return val.__staleWhileFetching;
25078
- }
25079
- }
25080
- else if (val !== undefined) {
25081
- return val;
25082
- }
25083
- }
25084
- }
25085
- finally {
25086
- if (this.#hasDisposeAfter && this.#disposed) {
25087
- const dt = this.#disposed;
25088
- let task;
25089
- while ((task = dt?.shift())) {
25090
- this.#disposeAfter?.(...task);
25091
- }
25092
- }
25093
- }
25094
- }
25095
- #evict(free) {
25096
- const head = this.#head;
25097
- const k = this.#keyList[head];
25098
- const v = this.#valList[head];
25099
- if (this.#hasFetchMethod && this.#isBackgroundFetch(v)) {
25100
- v.__abortController.abort(new Error('evicted'));
25101
- }
25102
- else if (this.#hasDispose || this.#hasDisposeAfter) {
25103
- if (this.#hasDispose) {
25104
- this.#dispose?.(v, k, 'evict');
25105
- }
25106
- if (this.#hasDisposeAfter) {
25107
- this.#disposed?.push([v, k, 'evict']);
25108
- }
25109
- }
25110
- this.#removeItemSize(head);
25111
- // if we aren't about to use the index, then null these out
25112
- if (free) {
25113
- this.#keyList[head] = undefined;
25114
- this.#valList[head] = undefined;
25115
- this.#free.push(head);
25116
- }
25117
- if (this.#size === 1) {
25118
- this.#head = this.#tail = 0;
25119
- this.#free.length = 0;
25120
- }
25121
- else {
25122
- this.#head = this.#next[head];
25123
- }
25124
- this.#keyMap.delete(k);
25125
- this.#size--;
25126
- return head;
25127
- }
25128
- /**
25129
- * Check if a key is in the cache, without updating the recency of use.
25130
- * Will return false if the item is stale, even though it is technically
25131
- * in the cache.
25132
- *
25133
- * Check if a key is in the cache, without updating the recency of
25134
- * use. Age is updated if {@link LRUCache.OptionsBase.updateAgeOnHas} is set
25135
- * to `true` in either the options or the constructor.
25136
- *
25137
- * Will return `false` if the item is stale, even though it is technically in
25138
- * the cache. The difference can be determined (if it matters) by using a
25139
- * `status` argument, and inspecting the `has` field.
25140
- *
25141
- * Will not update item age unless
25142
- * {@link LRUCache.OptionsBase.updateAgeOnHas} is set.
25143
- */
25144
- has(k, hasOptions = {}) {
25145
- const { updateAgeOnHas = this.updateAgeOnHas, status } = hasOptions;
25146
- const index = this.#keyMap.get(k);
25147
- if (index !== undefined) {
25148
- const v = this.#valList[index];
25149
- if (this.#isBackgroundFetch(v) &&
25150
- v.__staleWhileFetching === undefined) {
25151
- return false;
25152
- }
25153
- if (!this.#isStale(index)) {
25154
- if (updateAgeOnHas) {
25155
- this.#updateItemAge(index);
25156
- }
25157
- if (status) {
25158
- status.has = 'hit';
25159
- this.#statusTTL(status, index);
25160
- }
25161
- return true;
25162
- }
25163
- else if (status) {
25164
- status.has = 'stale';
25165
- this.#statusTTL(status, index);
25166
- }
25167
- }
25168
- else if (status) {
25169
- status.has = 'miss';
25170
- }
25171
- return false;
25172
- }
25173
- /**
25174
- * Like {@link LRUCache#get} but doesn't update recency or delete stale
25175
- * items.
25176
- *
25177
- * Returns `undefined` if the item is stale, unless
25178
- * {@link LRUCache.OptionsBase.allowStale} is set.
25179
- */
25180
- peek(k, peekOptions = {}) {
25181
- const { allowStale = this.allowStale } = peekOptions;
25182
- const index = this.#keyMap.get(k);
25183
- if (index === undefined ||
25184
- (!allowStale && this.#isStale(index))) {
25185
- return;
25186
- }
25187
- const v = this.#valList[index];
25188
- // either stale and allowed, or forcing a refresh of non-stale value
25189
- return this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v;
25190
- }
25191
- #backgroundFetch(k, index, options, context) {
25192
- const v = index === undefined ? undefined : this.#valList[index];
25193
- if (this.#isBackgroundFetch(v)) {
25194
- return v;
25195
- }
25196
- const ac = new AC();
25197
- const { signal } = options;
25198
- // when/if our AC signals, then stop listening to theirs.
25199
- signal?.addEventListener('abort', () => ac.abort(signal.reason), {
25200
- signal: ac.signal,
25201
- });
25202
- const fetchOpts = {
25203
- signal: ac.signal,
25204
- options,
25205
- context,
25206
- };
25207
- const cb = (v, updateCache = false) => {
25208
- const { aborted } = ac.signal;
25209
- const ignoreAbort = options.ignoreFetchAbort && v !== undefined;
25210
- if (options.status) {
25211
- if (aborted && !updateCache) {
25212
- options.status.fetchAborted = true;
25213
- options.status.fetchError = ac.signal.reason;
25214
- if (ignoreAbort)
25215
- options.status.fetchAbortIgnored = true;
25216
- }
25217
- else {
25218
- options.status.fetchResolved = true;
25219
- }
25220
- }
25221
- if (aborted && !ignoreAbort && !updateCache) {
25222
- return fetchFail(ac.signal.reason);
25223
- }
25224
- // either we didn't abort, and are still here, or we did, and ignored
25225
- const bf = p;
25226
- // if nothing else has been written there but we're set to update the
25227
- // cache and ignore the abort, or if it's still pending on this specific
25228
- // background request, then write it to the cache.
25229
- const vl = this.#valList[index];
25230
- if (vl === p || ignoreAbort && updateCache && vl === undefined) {
25231
- if (v === undefined) {
25232
- if (bf.__staleWhileFetching !== undefined) {
25233
- this.#valList[index] = bf.__staleWhileFetching;
25234
- }
25235
- else {
25236
- this.#delete(k, 'fetch');
25237
- }
25238
- }
25239
- else {
25240
- if (options.status)
25241
- options.status.fetchUpdated = true;
25242
- this.set(k, v, fetchOpts.options);
25243
- }
25244
- }
25245
- return v;
25246
- };
25247
- const eb = (er) => {
25248
- if (options.status) {
25249
- options.status.fetchRejected = true;
25250
- options.status.fetchError = er;
25251
- }
25252
- return fetchFail(er);
25253
- };
25254
- const fetchFail = (er) => {
25255
- const { aborted } = ac.signal;
25256
- const allowStaleAborted = aborted && options.allowStaleOnFetchAbort;
25257
- const allowStale = allowStaleAborted || options.allowStaleOnFetchRejection;
25258
- const noDelete = allowStale || options.noDeleteOnFetchRejection;
25259
- const bf = p;
25260
- if (this.#valList[index] === p) {
25261
- // if we allow stale on fetch rejections, then we need to ensure that
25262
- // the stale value is not removed from the cache when the fetch fails.
25263
- const del = !noDelete || bf.__staleWhileFetching === undefined;
25264
- if (del) {
25265
- this.#delete(k, 'fetch');
25266
- }
25267
- else if (!allowStaleAborted) {
25268
- // still replace the *promise* with the stale value,
25269
- // since we are done with the promise at this point.
25270
- // leave it untouched if we're still waiting for an
25271
- // aborted background fetch that hasn't yet returned.
25272
- this.#valList[index] = bf.__staleWhileFetching;
25273
- }
25274
- }
25275
- if (allowStale) {
25276
- if (options.status && bf.__staleWhileFetching !== undefined) {
25277
- options.status.returnedStale = true;
25278
- }
25279
- return bf.__staleWhileFetching;
25280
- }
25281
- else if (bf.__returned === bf) {
25282
- throw er;
25283
- }
25284
- };
25285
- const pcall = (res, rej) => {
25286
- const fmp = this.#fetchMethod?.(k, v, fetchOpts);
25287
- if (fmp && fmp instanceof Promise) {
25288
- fmp.then(v => res(v === undefined ? undefined : v), rej);
25289
- }
25290
- // ignored, we go until we finish, regardless.
25291
- // defer check until we are actually aborting,
25292
- // so fetchMethod can override.
25293
- ac.signal.addEventListener('abort', () => {
25294
- if (!options.ignoreFetchAbort ||
25295
- options.allowStaleOnFetchAbort) {
25296
- res(undefined);
25297
- // when it eventually resolves, update the cache.
25298
- if (options.allowStaleOnFetchAbort) {
25299
- res = v => cb(v, true);
25300
- }
25301
- }
25302
- });
25303
- };
25304
- if (options.status)
25305
- options.status.fetchDispatched = true;
25306
- const p = new Promise(pcall).then(cb, eb);
25307
- const bf = Object.assign(p, {
25308
- __abortController: ac,
25309
- __staleWhileFetching: v,
25310
- __returned: undefined,
25311
- });
25312
- if (index === undefined) {
25313
- // internal, don't expose status.
25314
- this.set(k, bf, { ...fetchOpts.options, status: undefined });
25315
- index = this.#keyMap.get(k);
25316
- }
25317
- else {
25318
- this.#valList[index] = bf;
25319
- }
25320
- return bf;
25321
- }
25322
- #isBackgroundFetch(p) {
25323
- if (!this.#hasFetchMethod)
25324
- return false;
25325
- const b = p;
25326
- return (!!b &&
25327
- b instanceof Promise &&
25328
- b.hasOwnProperty('__staleWhileFetching') &&
25329
- b.__abortController instanceof AC);
25330
- }
25331
- async fetch(k, fetchOptions = {}) {
25332
- const {
25333
- // get options
25334
- allowStale = this.allowStale, updateAgeOnGet = this.updateAgeOnGet, noDeleteOnStaleGet = this.noDeleteOnStaleGet,
25335
- // set options
25336
- ttl = this.ttl, noDisposeOnSet = this.noDisposeOnSet, size = 0, sizeCalculation = this.sizeCalculation, noUpdateTTL = this.noUpdateTTL,
25337
- // fetch exclusive options
25338
- noDeleteOnFetchRejection = this.noDeleteOnFetchRejection, allowStaleOnFetchRejection = this.allowStaleOnFetchRejection, ignoreFetchAbort = this.ignoreFetchAbort, allowStaleOnFetchAbort = this.allowStaleOnFetchAbort, context, forceRefresh = false, status, signal, } = fetchOptions;
25339
- if (!this.#hasFetchMethod) {
25340
- if (status)
25341
- status.fetch = 'get';
25342
- return this.get(k, {
25343
- allowStale,
25344
- updateAgeOnGet,
25345
- noDeleteOnStaleGet,
25346
- status,
25347
- });
25348
- }
25349
- const options = {
25350
- allowStale,
25351
- updateAgeOnGet,
25352
- noDeleteOnStaleGet,
25353
- ttl,
25354
- noDisposeOnSet,
25355
- size,
25356
- sizeCalculation,
25357
- noUpdateTTL,
25358
- noDeleteOnFetchRejection,
25359
- allowStaleOnFetchRejection,
25360
- allowStaleOnFetchAbort,
25361
- ignoreFetchAbort,
25362
- status,
25363
- signal,
25364
- };
25365
- let index = this.#keyMap.get(k);
25366
- if (index === undefined) {
25367
- if (status)
25368
- status.fetch = 'miss';
25369
- const p = this.#backgroundFetch(k, index, options, context);
25370
- return (p.__returned = p);
25371
- }
25372
- else {
25373
- // in cache, maybe already fetching
25374
- const v = this.#valList[index];
25375
- if (this.#isBackgroundFetch(v)) {
25376
- const stale = allowStale && v.__staleWhileFetching !== undefined;
25377
- if (status) {
25378
- status.fetch = 'inflight';
25379
- if (stale)
25380
- status.returnedStale = true;
25381
- }
25382
- return stale ? v.__staleWhileFetching : (v.__returned = v);
25383
- }
25384
- // if we force a refresh, that means do NOT serve the cached value,
25385
- // unless we are already in the process of refreshing the cache.
25386
- const isStale = this.#isStale(index);
25387
- if (!forceRefresh && !isStale) {
25388
- if (status)
25389
- status.fetch = 'hit';
25390
- this.#moveToTail(index);
25391
- if (updateAgeOnGet) {
25392
- this.#updateItemAge(index);
25393
- }
25394
- if (status)
25395
- this.#statusTTL(status, index);
25396
- return v;
25397
- }
25398
- // ok, it is stale or a forced refresh, and not already fetching.
25399
- // refresh the cache.
25400
- const p = this.#backgroundFetch(k, index, options, context);
25401
- const hasStale = p.__staleWhileFetching !== undefined;
25402
- const staleVal = hasStale && allowStale;
25403
- if (status) {
25404
- status.fetch = isStale ? 'stale' : 'refresh';
25405
- if (staleVal && isStale)
25406
- status.returnedStale = true;
25407
- }
25408
- return staleVal ? p.__staleWhileFetching : (p.__returned = p);
25409
- }
25410
- }
25411
- async forceFetch(k, fetchOptions = {}) {
25412
- const v = await this.fetch(k, fetchOptions);
25413
- if (v === undefined)
25414
- throw new Error('fetch() returned undefined');
25415
- return v;
25416
- }
25417
- memo(k, memoOptions = {}) {
25418
- const memoMethod = this.#memoMethod;
25419
- if (!memoMethod) {
25420
- throw new Error('no memoMethod provided to constructor');
25421
- }
25422
- const { context, forceRefresh, ...options } = memoOptions;
25423
- const v = this.get(k, options);
25424
- if (!forceRefresh && v !== undefined)
25425
- return v;
25426
- const vv = memoMethod(k, v, {
25427
- options,
25428
- context,
25429
- });
25430
- this.set(k, vv, options);
25431
- return vv;
25432
- }
25433
- /**
25434
- * Return a value from the cache. Will update the recency of the cache
25435
- * entry found.
25436
- *
25437
- * If the key is not found, get() will return `undefined`.
25438
- */
25439
- get(k, getOptions = {}) {
25440
- const { allowStale = this.allowStale, updateAgeOnGet = this.updateAgeOnGet, noDeleteOnStaleGet = this.noDeleteOnStaleGet, status, } = getOptions;
25441
- const index = this.#keyMap.get(k);
25442
- if (index !== undefined) {
25443
- const value = this.#valList[index];
25444
- const fetching = this.#isBackgroundFetch(value);
25445
- if (status)
25446
- this.#statusTTL(status, index);
25447
- if (this.#isStale(index)) {
25448
- if (status)
25449
- status.get = 'stale';
25450
- // delete only if not an in-flight background fetch
25451
- if (!fetching) {
25452
- if (!noDeleteOnStaleGet) {
25453
- this.#delete(k, 'expire');
25454
- }
25455
- if (status && allowStale)
25456
- status.returnedStale = true;
25457
- return allowStale ? value : undefined;
25458
- }
25459
- else {
25460
- if (status &&
25461
- allowStale &&
25462
- value.__staleWhileFetching !== undefined) {
25463
- status.returnedStale = true;
25464
- }
25465
- return allowStale ? value.__staleWhileFetching : undefined;
25466
- }
25467
- }
25468
- else {
25469
- if (status)
25470
- status.get = 'hit';
25471
- // if we're currently fetching it, we don't actually have it yet
25472
- // it's not stale, which means this isn't a staleWhileRefetching.
25473
- // If it's not stale, and fetching, AND has a __staleWhileFetching
25474
- // value, then that means the user fetched with {forceRefresh:true},
25475
- // so it's safe to return that value.
25476
- if (fetching) {
25477
- return value.__staleWhileFetching;
25478
- }
25479
- this.#moveToTail(index);
25480
- if (updateAgeOnGet) {
25481
- this.#updateItemAge(index);
25482
- }
25483
- return value;
25484
- }
25485
- }
25486
- else if (status) {
25487
- status.get = 'miss';
25488
- }
25489
- }
25490
- #connect(p, n) {
25491
- this.#prev[n] = p;
25492
- this.#next[p] = n;
25493
- }
25494
- #moveToTail(index) {
25495
- // if tail already, nothing to do
25496
- // if head, move head to next[index]
25497
- // else
25498
- // move next[prev[index]] to next[index] (head has no prev)
25499
- // move prev[next[index]] to prev[index]
25500
- // prev[index] = tail
25501
- // next[tail] = index
25502
- // tail = index
25503
- if (index !== this.#tail) {
25504
- if (index === this.#head) {
25505
- this.#head = this.#next[index];
25506
- }
25507
- else {
25508
- this.#connect(this.#prev[index], this.#next[index]);
25509
- }
25510
- this.#connect(this.#tail, index);
25511
- this.#tail = index;
25512
- }
25513
- }
25514
- /**
25515
- * Deletes a key out of the cache.
25516
- *
25517
- * Returns true if the key was deleted, false otherwise.
25518
- */
25519
- delete(k) {
25520
- return this.#delete(k, 'delete');
25521
- }
25522
- #delete(k, reason) {
25523
- let deleted = false;
25524
- if (this.#size !== 0) {
25525
- const index = this.#keyMap.get(k);
25526
- if (index !== undefined) {
25527
- deleted = true;
25528
- if (this.#size === 1) {
25529
- this.#clear(reason);
25530
- }
25531
- else {
25532
- this.#removeItemSize(index);
25533
- const v = this.#valList[index];
25534
- if (this.#isBackgroundFetch(v)) {
25535
- v.__abortController.abort(new Error('deleted'));
25536
- }
25537
- else if (this.#hasDispose || this.#hasDisposeAfter) {
25538
- if (this.#hasDispose) {
25539
- this.#dispose?.(v, k, reason);
25540
- }
25541
- if (this.#hasDisposeAfter) {
25542
- this.#disposed?.push([v, k, reason]);
25543
- }
25544
- }
25545
- this.#keyMap.delete(k);
25546
- this.#keyList[index] = undefined;
25547
- this.#valList[index] = undefined;
25548
- if (index === this.#tail) {
25549
- this.#tail = this.#prev[index];
25550
- }
25551
- else if (index === this.#head) {
25552
- this.#head = this.#next[index];
25553
- }
25554
- else {
25555
- const pi = this.#prev[index];
25556
- this.#next[pi] = this.#next[index];
25557
- const ni = this.#next[index];
25558
- this.#prev[ni] = this.#prev[index];
25559
- }
25560
- this.#size--;
25561
- this.#free.push(index);
25562
- }
25563
- }
25564
- }
25565
- if (this.#hasDisposeAfter && this.#disposed?.length) {
25566
- const dt = this.#disposed;
25567
- let task;
25568
- while ((task = dt?.shift())) {
25569
- this.#disposeAfter?.(...task);
25570
- }
25571
- }
25572
- return deleted;
25573
- }
25574
- /**
25575
- * Clear the cache entirely, throwing away all values.
25576
- */
25577
- clear() {
25578
- return this.#clear('delete');
25579
- }
25580
- #clear(reason) {
25581
- for (const index of this.#rindexes({ allowStale: true })) {
25582
- const v = this.#valList[index];
25583
- if (this.#isBackgroundFetch(v)) {
25584
- v.__abortController.abort(new Error('deleted'));
25585
- }
25586
- else {
25587
- const k = this.#keyList[index];
25588
- if (this.#hasDispose) {
25589
- this.#dispose?.(v, k, reason);
25590
- }
25591
- if (this.#hasDisposeAfter) {
25592
- this.#disposed?.push([v, k, reason]);
25593
- }
25594
- }
25595
- }
25596
- this.#keyMap.clear();
25597
- this.#valList.fill(undefined);
25598
- this.#keyList.fill(undefined);
25599
- if (this.#ttls && this.#starts) {
25600
- this.#ttls.fill(0);
25601
- this.#starts.fill(0);
25602
- }
25603
- if (this.#sizes) {
25604
- this.#sizes.fill(0);
25605
- }
25606
- this.#head = 0;
25607
- this.#tail = 0;
25608
- this.#free.length = 0;
25609
- this.#calculatedSize = 0;
25610
- this.#size = 0;
25611
- if (this.#hasDisposeAfter && this.#disposed) {
25612
- const dt = this.#disposed;
25613
- let task;
25614
- while ((task = dt?.shift())) {
25615
- this.#disposeAfter?.(...task);
25616
- }
25617
- }
25618
- }
25619
- }
24092
+ var M=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,I=new Set,R=typeof process=="object"&&process?process:{},x=(a,t,e,i)=>{typeof R.emitWarning=="function"?R.emitWarning(a,t,e,i):console.error(`[${e}] ${t}: ${a}`);},C=globalThis.AbortController,D=globalThis.AbortSignal;if(typeof C>"u"){D=class{onabort;_onabort=[];reason;aborted=false;addEventListener(i,s){this._onabort.push(s);}},C=class{constructor(){t();}signal=new D;abort(i){if(!this.signal.aborted){this.signal.reason=i,this.signal.aborted=true;for(let s of this.signal._onabort)s(i);this.signal.onabort?.(i);}}};let a=R.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",t=()=>{a&&(a=false,x("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.","NO_ABORT_CONTROLLER","ENOTSUP",t));};}var G=a=>!I.has(a),y=a=>a&&a===Math.floor(a)&&a>0&&isFinite(a),U=a=>y(a)?a<=Math.pow(2,8)?Uint8Array:a<=Math.pow(2,16)?Uint16Array:a<=Math.pow(2,32)?Uint32Array:a<=Number.MAX_SAFE_INTEGER?z:null:null,z=class extends Array{constructor(t){super(t),this.fill(0);}},W=class a{heap;length;static#o=false;static create(t){let e=U(t);if(!e)return [];a.#o=true;let i=new a(t,e);return a.#o=false,i}constructor(t,e){if(!a.#o)throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new e(t),this.length=0;}push(t){this.heap[this.length++]=t;}pop(){return this.heap[--this.length]}},L=class a{#o;#c;#w;#C;#S;#L;#I;#m;get perf(){return this.#m}ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#n;#_;#s;#i;#t;#a;#u;#l;#h;#b;#r;#y;#A;#d;#g;#T;#v;#f;#x;static unsafeExposeInternals(t){return {starts:t.#A,ttls:t.#d,autopurgeTimers:t.#g,sizes:t.#y,keyMap:t.#s,keyList:t.#i,valList:t.#t,next:t.#a,prev:t.#u,get head(){return t.#l},get tail(){return t.#h},free:t.#b,isBackgroundFetch:e=>t.#e(e),backgroundFetch:(e,i,s,h)=>t.#G(e,i,s,h),moveToTail:e=>t.#D(e),indexes:e=>t.#F(e),rindexes:e=>t.#O(e),isStale:e=>t.#p(e)}}get max(){return this.#o}get maxSize(){return this.#c}get calculatedSize(){return this.#_}get size(){return this.#n}get fetchMethod(){return this.#L}get memoMethod(){return this.#I}get dispose(){return this.#w}get onInsert(){return this.#C}get disposeAfter(){return this.#S}constructor(t){let{max:e=0,ttl:i,ttlResolution:s=1,ttlAutopurge:h,updateAgeOnGet:n,updateAgeOnHas:o,allowStale:r,dispose:f,onInsert:m,disposeAfter:c,noDisposeOnSet:d,noUpdateTTL:g,maxSize:A=0,maxEntrySize:p=0,sizeCalculation:_,fetchMethod:l,memoMethod:w,noDeleteOnFetchRejection:b,noDeleteOnStaleGet:S,allowStaleOnFetchRejection:u,allowStaleOnFetchAbort:T,ignoreFetchAbort:F,perf:v}=t;if(v!==void 0&&typeof v?.now!="function")throw new TypeError("perf option must have a now() method if specified");if(this.#m=v??M,e!==0&&!y(e))throw new TypeError("max option must be a nonnegative integer");let O=e?U(e):Array;if(!O)throw new Error("invalid max value: "+e);if(this.#o=e,this.#c=A,this.maxEntrySize=p||this.#c,this.sizeCalculation=_,this.sizeCalculation){if(!this.#c&&!this.maxEntrySize)throw new TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");if(typeof this.sizeCalculation!="function")throw new TypeError("sizeCalculation set to non-function")}if(w!==void 0&&typeof w!="function")throw new TypeError("memoMethod must be a function if defined");if(this.#I=w,l!==void 0&&typeof l!="function")throw new TypeError("fetchMethod must be a function if specified");if(this.#L=l,this.#v=!!l,this.#s=new Map,this.#i=new Array(e).fill(void 0),this.#t=new Array(e).fill(void 0),this.#a=new O(e),this.#u=new O(e),this.#l=0,this.#h=0,this.#b=W.create(e),this.#n=0,this.#_=0,typeof f=="function"&&(this.#w=f),typeof m=="function"&&(this.#C=m),typeof c=="function"?(this.#S=c,this.#r=[]):(this.#S=void 0,this.#r=void 0),this.#T=!!this.#w,this.#x=!!this.#C,this.#f=!!this.#S,this.noDisposeOnSet=!!d,this.noUpdateTTL=!!g,this.noDeleteOnFetchRejection=!!b,this.allowStaleOnFetchRejection=!!u,this.allowStaleOnFetchAbort=!!T,this.ignoreFetchAbort=!!F,this.maxEntrySize!==0){if(this.#c!==0&&!y(this.#c))throw new TypeError("maxSize must be a positive integer if specified");if(!y(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#B();}if(this.allowStale=!!r,this.noDeleteOnStaleGet=!!S,this.updateAgeOnGet=!!n,this.updateAgeOnHas=!!o,this.ttlResolution=y(s)||s===0?s:1,this.ttlAutopurge=!!h,this.ttl=i||0,this.ttl){if(!y(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.#j();}if(this.#o===0&&this.ttl===0&&this.#c===0)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#o&&!this.#c){let E="LRU_CACHE_UNBOUNDED";G(E)&&(I.add(E),x("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",E,a));}}getRemainingTTL(t){return this.#s.has(t)?1/0:0}#j(){let t=new z(this.#o),e=new z(this.#o);this.#d=t,this.#A=e;let i=this.ttlAutopurge?new Array(this.#o):void 0;this.#g=i,this.#N=(n,o,r=this.#m.now())=>{if(e[n]=o!==0?r:0,t[n]=o,i?.[n]&&(clearTimeout(i[n]),i[n]=void 0),o!==0&&i){let f=setTimeout(()=>{this.#p(n)&&this.#E(this.#i[n],"expire");},o+1);f.unref&&f.unref(),i[n]=f;}},this.#R=n=>{e[n]=t[n]!==0?this.#m.now():0;},this.#z=(n,o)=>{if(t[o]){let r=t[o],f=e[o];if(!r||!f)return;n.ttl=r,n.start=f,n.now=s||h();let m=n.now-f;n.remainingTTL=r-m;}};let s=0,h=()=>{let n=this.#m.now();if(this.ttlResolution>0){s=n;let o=setTimeout(()=>s=0,this.ttlResolution);o.unref&&o.unref();}return n};this.getRemainingTTL=n=>{let o=this.#s.get(n);if(o===void 0)return 0;let r=t[o],f=e[o];if(!r||!f)return 1/0;let m=(s||h())-f;return r-m},this.#p=n=>{let o=e[n],r=t[n];return !!r&&!!o&&(s||h())-o>r};}#R=()=>{};#z=()=>{};#N=()=>{};#p=()=>false;#B(){let t=new z(this.#o);this.#_=0,this.#y=t,this.#W=e=>{this.#_-=t[e],t[e]=0;},this.#P=(e,i,s,h)=>{if(this.#e(i))return 0;if(!y(s))if(h){if(typeof h!="function")throw new TypeError("sizeCalculation must be a function");if(s=h(i,e),!y(s))throw new TypeError("sizeCalculation return invalid (expect positive integer)")}else throw new TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");return s},this.#U=(e,i,s)=>{if(t[e]=i,this.#c){let h=this.#c-t[e];for(;this.#_>h;)this.#M(true);}this.#_+=t[e],s&&(s.entrySize=i,s.totalCalculatedSize=this.#_);};}#W=t=>{};#U=(t,e,i)=>{};#P=(t,e,i,s)=>{if(i||s)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#F({allowStale:t=this.allowStale}={}){if(this.#n)for(let e=this.#h;!(!this.#H(e)||((t||!this.#p(e))&&(yield e),e===this.#l));)e=this.#u[e];}*#O({allowStale:t=this.allowStale}={}){if(this.#n)for(let e=this.#l;!(!this.#H(e)||((t||!this.#p(e))&&(yield e),e===this.#h));)e=this.#a[e];}#H(t){return t!==void 0&&this.#s.get(this.#i[t])===t}*entries(){for(let t of this.#F())this.#t[t]!==void 0&&this.#i[t]!==void 0&&!this.#e(this.#t[t])&&(yield [this.#i[t],this.#t[t]]);}*rentries(){for(let t of this.#O())this.#t[t]!==void 0&&this.#i[t]!==void 0&&!this.#e(this.#t[t])&&(yield [this.#i[t],this.#t[t]]);}*keys(){for(let t of this.#F()){let e=this.#i[t];e!==void 0&&!this.#e(this.#t[t])&&(yield e);}}*rkeys(){for(let t of this.#O()){let e=this.#i[t];e!==void 0&&!this.#e(this.#t[t])&&(yield e);}}*values(){for(let t of this.#F())this.#t[t]!==void 0&&!this.#e(this.#t[t])&&(yield this.#t[t]);}*rvalues(){for(let t of this.#O())this.#t[t]!==void 0&&!this.#e(this.#t[t])&&(yield this.#t[t]);}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(t,e={}){for(let i of this.#F()){let s=this.#t[i],h=this.#e(s)?s.__staleWhileFetching:s;if(h!==void 0&&t(h,this.#i[i],this))return this.get(this.#i[i],e)}}forEach(t,e=this){for(let i of this.#F()){let s=this.#t[i],h=this.#e(s)?s.__staleWhileFetching:s;h!==void 0&&t.call(e,h,this.#i[i],this);}}rforEach(t,e=this){for(let i of this.#O()){let s=this.#t[i],h=this.#e(s)?s.__staleWhileFetching:s;h!==void 0&&t.call(e,h,this.#i[i],this);}}purgeStale(){let t=false;for(let e of this.#O({allowStale:true}))this.#p(e)&&(this.#E(this.#i[e],"expire"),t=true);return t}info(t){let e=this.#s.get(t);if(e===void 0)return;let i=this.#t[e],s=this.#e(i)?i.__staleWhileFetching:i;if(s===void 0)return;let h={value:s};if(this.#d&&this.#A){let n=this.#d[e],o=this.#A[e];if(n&&o){let r=n-(this.#m.now()-o);h.ttl=r,h.start=Date.now();}}return this.#y&&(h.size=this.#y[e]),h}dump(){let t=[];for(let e of this.#F({allowStale:true})){let i=this.#i[e],s=this.#t[e],h=this.#e(s)?s.__staleWhileFetching:s;if(h===void 0||i===void 0)continue;let n={value:h};if(this.#d&&this.#A){n.ttl=this.#d[e];let o=this.#m.now()-this.#A[e];n.start=Math.floor(Date.now()-o);}this.#y&&(n.size=this.#y[e]),t.unshift([i,n]);}return t}load(t){this.clear();for(let[e,i]of t){if(i.start){let s=Date.now()-i.start;i.start=this.#m.now()-s;}this.set(e,i.value,i);}}set(t,e,i={}){if(e===void 0)return this.delete(t),this;let{ttl:s=this.ttl,start:h,noDisposeOnSet:n=this.noDisposeOnSet,sizeCalculation:o=this.sizeCalculation,status:r}=i,{noUpdateTTL:f=this.noUpdateTTL}=i,m=this.#P(t,e,i.size||0,o);if(this.maxEntrySize&&m>this.maxEntrySize)return r&&(r.set="miss",r.maxEntrySizeExceeded=true),this.#E(t,"set"),this;let c=this.#n===0?void 0:this.#s.get(t);if(c===void 0)c=this.#n===0?this.#h:this.#b.length!==0?this.#b.pop():this.#n===this.#o?this.#M(false):this.#n,this.#i[c]=t,this.#t[c]=e,this.#s.set(t,c),this.#a[this.#h]=c,this.#u[c]=this.#h,this.#h=c,this.#n++,this.#U(c,m,r),r&&(r.set="add"),f=false,this.#x&&this.#C?.(e,t,"add");else {this.#D(c);let d=this.#t[c];if(e!==d){if(this.#v&&this.#e(d)){d.__abortController.abort(new Error("replaced"));let{__staleWhileFetching:g}=d;g!==void 0&&!n&&(this.#T&&this.#w?.(g,t,"set"),this.#f&&this.#r?.push([g,t,"set"]));}else n||(this.#T&&this.#w?.(d,t,"set"),this.#f&&this.#r?.push([d,t,"set"]));if(this.#W(c),this.#U(c,m,r),this.#t[c]=e,r){r.set="replace";let g=d&&this.#e(d)?d.__staleWhileFetching:d;g!==void 0&&(r.oldValue=g);}}else r&&(r.set="update");this.#x&&this.onInsert?.(e,t,e===d?"update":"replace");}if(s!==0&&!this.#d&&this.#j(),this.#d&&(f||this.#N(c,s,h),r&&this.#z(r,c)),!n&&this.#f&&this.#r){let d=this.#r,g;for(;g=d?.shift();)this.#S?.(...g);}return this}pop(){try{for(;this.#n;){let t=this.#t[this.#l];if(this.#M(!0),this.#e(t)){if(t.__staleWhileFetching)return t.__staleWhileFetching}else if(t!==void 0)return t}}finally{if(this.#f&&this.#r){let t=this.#r,e;for(;e=t?.shift();)this.#S?.(...e);}}}#M(t){let e=this.#l,i=this.#i[e],s=this.#t[e];return this.#v&&this.#e(s)?s.__abortController.abort(new Error("evicted")):(this.#T||this.#f)&&(this.#T&&this.#w?.(s,i,"evict"),this.#f&&this.#r?.push([s,i,"evict"])),this.#W(e),this.#g?.[e]&&(clearTimeout(this.#g[e]),this.#g[e]=void 0),t&&(this.#i[e]=void 0,this.#t[e]=void 0,this.#b.push(e)),this.#n===1?(this.#l=this.#h=0,this.#b.length=0):this.#l=this.#a[e],this.#s.delete(i),this.#n--,e}has(t,e={}){let{updateAgeOnHas:i=this.updateAgeOnHas,status:s}=e,h=this.#s.get(t);if(h!==void 0){let n=this.#t[h];if(this.#e(n)&&n.__staleWhileFetching===void 0)return false;if(this.#p(h))s&&(s.has="stale",this.#z(s,h));else return i&&this.#R(h),s&&(s.has="hit",this.#z(s,h)),true}else s&&(s.has="miss");return false}peek(t,e={}){let{allowStale:i=this.allowStale}=e,s=this.#s.get(t);if(s===void 0||!i&&this.#p(s))return;let h=this.#t[s];return this.#e(h)?h.__staleWhileFetching:h}#G(t,e,i,s){let h=e===void 0?void 0:this.#t[e];if(this.#e(h))return h;let n=new C,{signal:o}=i;o?.addEventListener("abort",()=>n.abort(o.reason),{signal:n.signal});let r={signal:n.signal,options:i,context:s},f=(p,_=false)=>{let{aborted:l}=n.signal,w=i.ignoreFetchAbort&&p!==void 0,b=i.ignoreFetchAbort||!!(i.allowStaleOnFetchAbort&&p!==void 0);if(i.status&&(l&&!_?(i.status.fetchAborted=true,i.status.fetchError=n.signal.reason,w&&(i.status.fetchAbortIgnored=true)):i.status.fetchResolved=true),l&&!w&&!_)return c(n.signal.reason,b);let S=g,u=this.#t[e];return (u===g||w&&_&&u===void 0)&&(p===void 0?S.__staleWhileFetching!==void 0?this.#t[e]=S.__staleWhileFetching:this.#E(t,"fetch"):(i.status&&(i.status.fetchUpdated=true),this.set(t,p,r.options))),p},m=p=>(i.status&&(i.status.fetchRejected=true,i.status.fetchError=p),c(p,false)),c=(p,_)=>{let{aborted:l}=n.signal,w=l&&i.allowStaleOnFetchAbort,b=w||i.allowStaleOnFetchRejection,S=b||i.noDeleteOnFetchRejection,u=g;if(this.#t[e]===g&&(!S||!_&&u.__staleWhileFetching===void 0?this.#E(t,"fetch"):w||(this.#t[e]=u.__staleWhileFetching)),b)return i.status&&u.__staleWhileFetching!==void 0&&(i.status.returnedStale=true),u.__staleWhileFetching;if(u.__returned===u)throw p},d=(p,_)=>{let l=this.#L?.(t,h,r);l&&l instanceof Promise&&l.then(w=>p(w===void 0?void 0:w),_),n.signal.addEventListener("abort",()=>{(!i.ignoreFetchAbort||i.allowStaleOnFetchAbort)&&(p(void 0),i.allowStaleOnFetchAbort&&(p=w=>f(w,true)));});};i.status&&(i.status.fetchDispatched=true);let g=new Promise(d).then(f,m),A=Object.assign(g,{__abortController:n,__staleWhileFetching:h,__returned:void 0});return e===void 0?(this.set(t,A,{...r.options,status:void 0}),e=this.#s.get(t)):this.#t[e]=A,A}#e(t){if(!this.#v)return false;let e=t;return !!e&&e instanceof Promise&&e.hasOwnProperty("__staleWhileFetching")&&e.__abortController instanceof C}async fetch(t,e={}){let{allowStale:i=this.allowStale,updateAgeOnGet:s=this.updateAgeOnGet,noDeleteOnStaleGet:h=this.noDeleteOnStaleGet,ttl:n=this.ttl,noDisposeOnSet:o=this.noDisposeOnSet,size:r=0,sizeCalculation:f=this.sizeCalculation,noUpdateTTL:m=this.noUpdateTTL,noDeleteOnFetchRejection:c=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:d=this.allowStaleOnFetchRejection,ignoreFetchAbort:g=this.ignoreFetchAbort,allowStaleOnFetchAbort:A=this.allowStaleOnFetchAbort,context:p,forceRefresh:_=false,status:l,signal:w}=e;if(!this.#v)return l&&(l.fetch="get"),this.get(t,{allowStale:i,updateAgeOnGet:s,noDeleteOnStaleGet:h,status:l});let b={allowStale:i,updateAgeOnGet:s,noDeleteOnStaleGet:h,ttl:n,noDisposeOnSet:o,size:r,sizeCalculation:f,noUpdateTTL:m,noDeleteOnFetchRejection:c,allowStaleOnFetchRejection:d,allowStaleOnFetchAbort:A,ignoreFetchAbort:g,status:l,signal:w},S=this.#s.get(t);if(S===void 0){l&&(l.fetch="miss");let u=this.#G(t,S,b,p);return u.__returned=u}else {let u=this.#t[S];if(this.#e(u)){let E=i&&u.__staleWhileFetching!==void 0;return l&&(l.fetch="inflight",E&&(l.returnedStale=true)),E?u.__staleWhileFetching:u.__returned=u}let T=this.#p(S);if(!_&&!T)return l&&(l.fetch="hit"),this.#D(S),s&&this.#R(S),l&&this.#z(l,S),u;let F=this.#G(t,S,b,p),O=F.__staleWhileFetching!==void 0&&i;return l&&(l.fetch=T?"stale":"refresh",O&&T&&(l.returnedStale=true)),O?F.__staleWhileFetching:F.__returned=F}}async forceFetch(t,e={}){let i=await this.fetch(t,e);if(i===void 0)throw new Error("fetch() returned undefined");return i}memo(t,e={}){let i=this.#I;if(!i)throw new Error("no memoMethod provided to constructor");let{context:s,forceRefresh:h,...n}=e,o=this.get(t,n);if(!h&&o!==void 0)return o;let r=i(t,o,{options:n,context:s});return this.set(t,r,n),r}get(t,e={}){let{allowStale:i=this.allowStale,updateAgeOnGet:s=this.updateAgeOnGet,noDeleteOnStaleGet:h=this.noDeleteOnStaleGet,status:n}=e,o=this.#s.get(t);if(o!==void 0){let r=this.#t[o],f=this.#e(r);return n&&this.#z(n,o),this.#p(o)?(n&&(n.get="stale"),f?(n&&i&&r.__staleWhileFetching!==void 0&&(n.returnedStale=true),i?r.__staleWhileFetching:void 0):(h||this.#E(t,"expire"),n&&i&&(n.returnedStale=true),i?r:void 0)):(n&&(n.get="hit"),f?r.__staleWhileFetching:(this.#D(o),s&&this.#R(o),r))}else n&&(n.get="miss");}#k(t,e){this.#u[e]=t,this.#a[t]=e;}#D(t){t!==this.#h&&(t===this.#l?this.#l=this.#a[t]:this.#k(this.#u[t],this.#a[t]),this.#k(this.#h,t),this.#h=t);}delete(t){return this.#E(t,"delete")}#E(t,e){let i=false;if(this.#n!==0){let s=this.#s.get(t);if(s!==void 0)if(this.#g?.[s]&&(clearTimeout(this.#g?.[s]),this.#g[s]=void 0),i=true,this.#n===1)this.#V(e);else {this.#W(s);let h=this.#t[s];if(this.#e(h)?h.__abortController.abort(new Error("deleted")):(this.#T||this.#f)&&(this.#T&&this.#w?.(h,t,e),this.#f&&this.#r?.push([h,t,e])),this.#s.delete(t),this.#i[s]=void 0,this.#t[s]=void 0,s===this.#h)this.#h=this.#u[s];else if(s===this.#l)this.#l=this.#a[s];else {let n=this.#u[s];this.#a[n]=this.#a[s];let o=this.#a[s];this.#u[o]=this.#u[s];}this.#n--,this.#b.push(s);}}if(this.#f&&this.#r?.length){let s=this.#r,h;for(;h=s?.shift();)this.#S?.(...h);}return i}clear(){return this.#V("delete")}#V(t){for(let e of this.#O({allowStale:true})){let i=this.#t[e];if(this.#e(i))i.__abortController.abort(new Error("deleted"));else {let s=this.#i[e];this.#T&&this.#w?.(i,s,t),this.#f&&this.#r?.push([i,s,t]);}}if(this.#s.clear(),this.#t.fill(void 0),this.#i.fill(void 0),this.#d&&this.#A){this.#d.fill(0),this.#A.fill(0);for(let e of this.#g??[])e!==void 0&&clearTimeout(e);this.#g?.fill(void 0);}if(this.#y&&this.#y.fill(0),this.#l=0,this.#h=0,this.#b.length=0,this.#_=0,this.#n=0,this.#f&&this.#r){let e=this.#r,i;for(;i=e?.shift();)this.#S?.(...i);}}};
25620
24093
 
25621
24094
  // ../../node_modules/.pnpm/fast-deep-equal@3.1.3/node_modules/fast-deep-equal/index.js
25622
24095
  var require_fast_deep_equal = __commonJS$4({
@@ -25651,59 +24124,59 @@ var require_fast_deep_equal = __commonJS$4({
25651
24124
  };
25652
24125
  }
25653
24126
  });
25654
- var TextPartSchema = z$1.object({
25655
- type: z$1.literal("text"),
25656
- text: z$1.string()
24127
+ var TextPartSchema = z$2.object({
24128
+ type: z$2.literal("text"),
24129
+ text: z$2.string()
25657
24130
  }).passthrough();
25658
- var ImagePartSchema = z$1.object({
25659
- type: z$1.literal("image"),
25660
- image: z$1.union([z$1.string(), z$1.instanceof(URL), z$1.instanceof(Uint8Array)]),
25661
- mimeType: z$1.string().optional()
24131
+ var ImagePartSchema = z$2.object({
24132
+ type: z$2.literal("image"),
24133
+ image: z$2.union([z$2.string(), z$2.instanceof(URL), z$2.instanceof(Uint8Array)]),
24134
+ mimeType: z$2.string().optional()
25662
24135
  }).passthrough();
25663
- var FilePartSchema = z$1.object({
25664
- type: z$1.literal("file"),
25665
- data: z$1.union([z$1.string(), z$1.instanceof(URL), z$1.instanceof(Uint8Array)]),
25666
- mimeType: z$1.string()
24136
+ var FilePartSchema = z$2.object({
24137
+ type: z$2.literal("file"),
24138
+ data: z$2.union([z$2.string(), z$2.instanceof(URL), z$2.instanceof(Uint8Array)]),
24139
+ mimeType: z$2.string()
25667
24140
  }).passthrough();
25668
- var ToolInvocationPartSchema = z$1.object({
25669
- type: z$1.literal("tool-invocation"),
25670
- toolInvocation: z$1.object({
25671
- toolCallId: z$1.string(),
25672
- toolName: z$1.string(),
25673
- args: z$1.unknown(),
25674
- state: z$1.enum(["partial-call", "call", "result"]),
25675
- result: z$1.unknown().optional()
24141
+ var ToolInvocationPartSchema = z$2.object({
24142
+ type: z$2.literal("tool-invocation"),
24143
+ toolInvocation: z$2.object({
24144
+ toolCallId: z$2.string(),
24145
+ toolName: z$2.string(),
24146
+ args: z$2.unknown(),
24147
+ state: z$2.enum(["partial-call", "call", "result"]),
24148
+ result: z$2.unknown().optional()
25676
24149
  })
25677
24150
  }).passthrough();
25678
- var ReasoningPartSchema = z$1.object({
25679
- type: z$1.literal("reasoning"),
25680
- reasoning: z$1.string(),
25681
- details: z$1.array(
25682
- z$1.object({
25683
- type: z$1.enum(["text", "redacted"]),
25684
- text: z$1.string().optional(),
25685
- data: z$1.string().optional()
24151
+ var ReasoningPartSchema = z$2.object({
24152
+ type: z$2.literal("reasoning"),
24153
+ reasoning: z$2.string(),
24154
+ details: z$2.array(
24155
+ z$2.object({
24156
+ type: z$2.enum(["text", "redacted"]),
24157
+ text: z$2.string().optional(),
24158
+ data: z$2.string().optional()
25686
24159
  })
25687
24160
  )
25688
24161
  }).passthrough();
25689
- var SourcePartSchema = z$1.object({
25690
- type: z$1.literal("source"),
25691
- source: z$1.object({
25692
- sourceType: z$1.string(),
25693
- id: z$1.string(),
25694
- url: z$1.string().optional(),
25695
- title: z$1.string().optional()
24162
+ var SourcePartSchema = z$2.object({
24163
+ type: z$2.literal("source"),
24164
+ source: z$2.object({
24165
+ sourceType: z$2.string(),
24166
+ id: z$2.string(),
24167
+ url: z$2.string().optional(),
24168
+ title: z$2.string().optional()
25696
24169
  })
25697
24170
  }).passthrough();
25698
- var StepStartPartSchema = z$1.object({
25699
- type: z$1.literal("step-start")
24171
+ var StepStartPartSchema = z$2.object({
24172
+ type: z$2.literal("step-start")
25700
24173
  }).passthrough();
25701
- var DataPartSchema = z$1.object({
25702
- type: z$1.string().refine((t) => t.startsWith("data-"), { message: 'Type must start with "data-"' }),
25703
- id: z$1.string().optional(),
25704
- data: z$1.unknown()
24174
+ var DataPartSchema = z$2.object({
24175
+ type: z$2.string().refine((t) => t.startsWith("data-"), { message: 'Type must start with "data-"' }),
24176
+ id: z$2.string().optional(),
24177
+ data: z$2.unknown()
25705
24178
  }).passthrough();
25706
- var MessagePartSchema = z$1.union([
24179
+ var MessagePartSchema = z$2.union([
25707
24180
  TextPartSchema,
25708
24181
  ImagePartSchema,
25709
24182
  FilePartSchema,
@@ -25713,153 +24186,153 @@ var MessagePartSchema = z$1.union([
25713
24186
  StepStartPartSchema,
25714
24187
  DataPartSchema
25715
24188
  ]);
25716
- z$1.object({
24189
+ z$2.object({
25717
24190
  /** Format version - 2 corresponds to AI SDK v4 UIMessage format */
25718
- format: z$1.literal(2),
24191
+ format: z$2.literal(2),
25719
24192
  /** Array of message parts (text, images, tool calls, etc.) */
25720
- parts: z$1.array(MessagePartSchema),
24193
+ parts: z$2.array(MessagePartSchema),
25721
24194
  /** Legacy content field for backwards compatibility */
25722
- content: z$1.string().optional(),
24195
+ content: z$2.string().optional(),
25723
24196
  /** Additional metadata */
25724
- metadata: z$1.record(z$1.unknown()).optional(),
24197
+ metadata: z$2.record(z$2.unknown()).optional(),
25725
24198
  /** Provider-specific metadata */
25726
- providerMetadata: z$1.record(z$1.unknown()).optional()
24199
+ providerMetadata: z$2.record(z$2.unknown()).optional()
25727
24200
  });
25728
- var ProcessorMessageContentSchema = z$1.object({
24201
+ var ProcessorMessageContentSchema = z$2.object({
25729
24202
  /** Format version - 2 corresponds to AI SDK v4 UIMessage format */
25730
- format: z$1.literal(2),
24203
+ format: z$2.literal(2),
25731
24204
  /** Array of message parts (text, images, tool calls, etc.) */
25732
- parts: z$1.array(MessagePartSchema),
24205
+ parts: z$2.array(MessagePartSchema),
25733
24206
  /** Legacy content field for backwards compatibility */
25734
- content: z$1.string().optional(),
24207
+ content: z$2.string().optional(),
25735
24208
  /** Additional metadata */
25736
- metadata: z$1.record(z$1.unknown()).optional(),
24209
+ metadata: z$2.record(z$2.unknown()).optional(),
25737
24210
  /** Provider-specific metadata */
25738
- providerMetadata: z$1.record(z$1.unknown()).optional()
24211
+ providerMetadata: z$2.record(z$2.unknown()).optional()
25739
24212
  }).passthrough();
25740
- var ProcessorMessageSchema = z$1.object({
24213
+ var ProcessorMessageSchema = z$2.object({
25741
24214
  /** Unique message identifier */
25742
- id: z$1.string(),
24215
+ id: z$2.string(),
25743
24216
  /** Message role */
25744
- role: z$1.enum(["user", "assistant", "system", "tool"]),
24217
+ role: z$2.enum(["user", "assistant", "system", "tool"]),
25745
24218
  /** When the message was created */
25746
- createdAt: z$1.coerce.date(),
24219
+ createdAt: z$2.coerce.date(),
25747
24220
  /** Thread identifier for conversation grouping */
25748
- threadId: z$1.string().optional(),
24221
+ threadId: z$2.string().optional(),
25749
24222
  /** Resource identifier */
25750
- resourceId: z$1.string().optional(),
24223
+ resourceId: z$2.string().optional(),
25751
24224
  /** Message type */
25752
- type: z$1.string().optional(),
24225
+ type: z$2.string().optional(),
25753
24226
  /** Message content with parts */
25754
24227
  content: ProcessorMessageContentSchema
25755
24228
  }).passthrough();
25756
- var messageListSchema = z$1.custom();
25757
- var messagesSchema = z$1.array(ProcessorMessageSchema);
25758
- var SystemMessageTextPartSchema = z$1.object({
25759
- type: z$1.literal("text"),
25760
- text: z$1.string()
24229
+ var messageListSchema = z$2.custom();
24230
+ var messagesSchema = z$2.array(ProcessorMessageSchema);
24231
+ var SystemMessageTextPartSchema = z$2.object({
24232
+ type: z$2.literal("text"),
24233
+ text: z$2.string()
25761
24234
  }).passthrough();
25762
- z$1.object({
25763
- role: z$1.literal("system"),
25764
- content: z$1.union([z$1.string(), z$1.array(SystemMessageTextPartSchema)]),
24235
+ z$2.object({
24236
+ role: z$2.literal("system"),
24237
+ content: z$2.union([z$2.string(), z$2.array(SystemMessageTextPartSchema)]),
25765
24238
  /** Optional experimental provider-specific extensions */
25766
- experimental_providerMetadata: z$1.record(z$1.unknown()).optional()
24239
+ experimental_providerMetadata: z$2.record(z$2.unknown()).optional()
25767
24240
  }).passthrough();
25768
- var CoreMessageSchema = z$1.object({
25769
- role: z$1.enum(["system", "user", "assistant", "tool"]),
25770
- content: z$1.unknown()
24241
+ var CoreMessageSchema = z$2.object({
24242
+ role: z$2.enum(["system", "user", "assistant", "tool"]),
24243
+ content: z$2.unknown()
25771
24244
  }).passthrough();
25772
- var systemMessagesSchema = z$1.array(CoreMessageSchema);
25773
- var toolCallSchema = z$1.object({
25774
- toolName: z$1.string(),
25775
- toolCallId: z$1.string(),
25776
- args: z$1.unknown()
24245
+ var systemMessagesSchema = z$2.array(CoreMessageSchema);
24246
+ var toolCallSchema = z$2.object({
24247
+ toolName: z$2.string(),
24248
+ toolCallId: z$2.string(),
24249
+ args: z$2.unknown()
25777
24250
  });
25778
- var retryCountSchema = z$1.number().optional();
25779
- var ProcessorInputPhaseSchema = z$1.object({
25780
- phase: z$1.literal("input"),
24251
+ var retryCountSchema = z$2.number().optional();
24252
+ var ProcessorInputPhaseSchema = z$2.object({
24253
+ phase: z$2.literal("input"),
25781
24254
  messages: messagesSchema,
25782
24255
  messageList: messageListSchema,
25783
24256
  systemMessages: systemMessagesSchema.optional(),
25784
24257
  retryCount: retryCountSchema
25785
24258
  });
25786
- var ProcessorInputStepPhaseSchema = z$1.object({
25787
- phase: z$1.literal("inputStep"),
24259
+ var ProcessorInputStepPhaseSchema = z$2.object({
24260
+ phase: z$2.literal("inputStep"),
25788
24261
  messages: messagesSchema,
25789
24262
  messageList: messageListSchema,
25790
- stepNumber: z$1.number().describe("The current step number (0-indexed)"),
24263
+ stepNumber: z$2.number().describe("The current step number (0-indexed)"),
25791
24264
  systemMessages: systemMessagesSchema.optional(),
25792
24265
  retryCount: retryCountSchema,
25793
24266
  // Model and tools configuration (can be modified by processors)
25794
- model: z$1.custom().optional().describe("Current model for this step"),
25795
- tools: z$1.custom().optional().describe("Current tools available for this step"),
25796
- toolChoice: z$1.custom().optional().describe("Current tool choice setting"),
25797
- activeTools: z$1.array(z$1.string()).optional().describe("Currently active tools"),
25798
- providerOptions: z$1.custom().optional().describe("Provider-specific options"),
25799
- modelSettings: z$1.custom().optional().describe("Model settings (temperature, etc.)"),
25800
- structuredOutput: z$1.custom().optional().describe("Structured output configuration"),
25801
- steps: z$1.custom().optional().describe("Results from previous steps")
24267
+ model: z$2.custom().optional().describe("Current model for this step"),
24268
+ tools: z$2.custom().optional().describe("Current tools available for this step"),
24269
+ toolChoice: z$2.custom().optional().describe("Current tool choice setting"),
24270
+ activeTools: z$2.array(z$2.string()).optional().describe("Currently active tools"),
24271
+ providerOptions: z$2.custom().optional().describe("Provider-specific options"),
24272
+ modelSettings: z$2.custom().optional().describe("Model settings (temperature, etc.)"),
24273
+ structuredOutput: z$2.custom().optional().describe("Structured output configuration"),
24274
+ steps: z$2.custom().optional().describe("Results from previous steps")
25802
24275
  });
25803
- var ProcessorOutputStreamPhaseSchema = z$1.object({
25804
- phase: z$1.literal("outputStream"),
25805
- part: z$1.unknown().nullable().describe("The current chunk being processed. Can be null to skip."),
25806
- streamParts: z$1.array(z$1.unknown()).describe("All chunks seen so far"),
25807
- state: z$1.record(z$1.unknown()).describe("Mutable state object that persists across chunks"),
24276
+ var ProcessorOutputStreamPhaseSchema = z$2.object({
24277
+ phase: z$2.literal("outputStream"),
24278
+ part: z$2.unknown().nullable().describe("The current chunk being processed. Can be null to skip."),
24279
+ streamParts: z$2.array(z$2.unknown()).describe("All chunks seen so far"),
24280
+ state: z$2.record(z$2.unknown()).describe("Mutable state object that persists across chunks"),
25808
24281
  messageList: messageListSchema.optional(),
25809
24282
  retryCount: retryCountSchema
25810
24283
  });
25811
- var ProcessorOutputResultPhaseSchema = z$1.object({
25812
- phase: z$1.literal("outputResult"),
24284
+ var ProcessorOutputResultPhaseSchema = z$2.object({
24285
+ phase: z$2.literal("outputResult"),
25813
24286
  messages: messagesSchema,
25814
24287
  messageList: messageListSchema,
25815
24288
  retryCount: retryCountSchema
25816
24289
  });
25817
- var ProcessorOutputStepPhaseSchema = z$1.object({
25818
- phase: z$1.literal("outputStep"),
24290
+ var ProcessorOutputStepPhaseSchema = z$2.object({
24291
+ phase: z$2.literal("outputStep"),
25819
24292
  messages: messagesSchema,
25820
24293
  messageList: messageListSchema,
25821
- stepNumber: z$1.number().describe("The current step number (0-indexed)"),
25822
- finishReason: z$1.string().optional().describe("The finish reason from the LLM (stop, tool-use, length, etc.)"),
25823
- toolCalls: z$1.array(toolCallSchema).optional().describe("Tool calls made in this step (if any)"),
25824
- text: z$1.string().optional().describe("Generated text from this step"),
24294
+ stepNumber: z$2.number().describe("The current step number (0-indexed)"),
24295
+ finishReason: z$2.string().optional().describe("The finish reason from the LLM (stop, tool-use, length, etc.)"),
24296
+ toolCalls: z$2.array(toolCallSchema).optional().describe("Tool calls made in this step (if any)"),
24297
+ text: z$2.string().optional().describe("Generated text from this step"),
25825
24298
  systemMessages: systemMessagesSchema.optional(),
25826
24299
  retryCount: retryCountSchema
25827
24300
  });
25828
- z$1.discriminatedUnion("phase", [
24301
+ z$2.discriminatedUnion("phase", [
25829
24302
  ProcessorInputPhaseSchema,
25830
24303
  ProcessorInputStepPhaseSchema,
25831
24304
  ProcessorOutputStreamPhaseSchema,
25832
24305
  ProcessorOutputResultPhaseSchema,
25833
24306
  ProcessorOutputStepPhaseSchema
25834
24307
  ]);
25835
- z$1.object({
24308
+ z$2.object({
25836
24309
  // Phase field
25837
- phase: z$1.enum(["input", "inputStep", "outputStream", "outputResult", "outputStep"]),
24310
+ phase: z$2.enum(["input", "inputStep", "outputStream", "outputResult", "outputStep"]),
25838
24311
  // Message-based fields (used by most phases)
25839
24312
  messages: messagesSchema.optional(),
25840
24313
  messageList: messageListSchema.optional(),
25841
24314
  systemMessages: systemMessagesSchema.optional(),
25842
24315
  // Step-based fields
25843
- stepNumber: z$1.number().optional(),
24316
+ stepNumber: z$2.number().optional(),
25844
24317
  // Stream-based fields
25845
- part: z$1.unknown().nullable().optional(),
25846
- streamParts: z$1.array(z$1.unknown()).optional(),
25847
- state: z$1.record(z$1.unknown()).optional(),
24318
+ part: z$2.unknown().nullable().optional(),
24319
+ streamParts: z$2.array(z$2.unknown()).optional(),
24320
+ state: z$2.record(z$2.unknown()).optional(),
25848
24321
  // Output step fields
25849
- finishReason: z$1.string().optional(),
25850
- toolCalls: z$1.array(toolCallSchema).optional(),
25851
- text: z$1.string().optional(),
24322
+ finishReason: z$2.string().optional(),
24323
+ toolCalls: z$2.array(toolCallSchema).optional(),
24324
+ text: z$2.string().optional(),
25852
24325
  // Retry count
25853
- retryCount: z$1.number().optional(),
24326
+ retryCount: z$2.number().optional(),
25854
24327
  // Model and tools configuration (for inputStep phase)
25855
- model: z$1.custom().optional(),
25856
- tools: z$1.custom().optional(),
25857
- toolChoice: z$1.custom().optional(),
25858
- activeTools: z$1.array(z$1.string()).optional(),
25859
- providerOptions: z$1.custom().optional(),
25860
- modelSettings: z$1.custom().optional(),
25861
- structuredOutput: z$1.custom().optional(),
25862
- steps: z$1.custom().optional()
24328
+ model: z$2.custom().optional(),
24329
+ tools: z$2.custom().optional(),
24330
+ toolChoice: z$2.custom().optional(),
24331
+ activeTools: z$2.array(z$2.string()).optional(),
24332
+ providerOptions: z$2.custom().optional(),
24333
+ modelSettings: z$2.custom().optional(),
24334
+ structuredOutput: z$2.custom().optional(),
24335
+ steps: z$2.custom().optional()
25863
24336
  });
25864
24337
  var languageModelUsageSchema = z10.object({
25865
24338
  inputTokens: z10.number().optional(),
@@ -25963,13 +24436,13 @@ function formatCompletionFeedback(result, maxIterationReached) {
25963
24436
  }
25964
24437
  return lines.join("\n");
25965
24438
  }
25966
- z$1.object({
25967
- isComplete: z$1.boolean().describe("Whether the task is complete"),
25968
- completionReason: z$1.string().describe("Explanation of why the task is or is not complete"),
25969
- finalResult: z$1.string().optional().describe("The final result text to return to the user. omit if primitive result is sufficient")
24439
+ z$2.object({
24440
+ isComplete: z$2.boolean().describe("Whether the task is complete"),
24441
+ completionReason: z$2.string().describe("Explanation of why the task is or is not complete"),
24442
+ finalResult: z$2.string().optional().describe("The final result text to return to the user. omit if primitive result is sufficient")
25970
24443
  });
25971
- z$1.object({
25972
- finalResult: z$1.string().optional().describe("The final result text to return to the user, omit if primitive result is sufficient")
24444
+ z$2.object({
24445
+ finalResult: z$2.string().optional().describe("The final result text to return to the user, omit if primitive result is sufficient")
25973
24446
  });
25974
24447
  z10.enum(["agent", "workflow", "none", "tool"]);
25975
24448
 
@@ -25978,47 +24451,48 @@ __toESM$3(require_fast_deep_equal());
25978
24451
 
25979
24452
  // src/agent/workflows/prepare-stream/prepare-memory-step.ts
25980
24453
  __toESM$3(require_fast_deep_equal());
25981
- var coreToolSchema = z$1.object({
25982
- id: z$1.string().optional(),
25983
- description: z$1.string().optional(),
25984
- parameters: z$1.union([
25985
- z$1.record(z$1.string(), z$1.any()),
24454
+ var coreToolSchema = z$2.object({
24455
+ id: z$2.string().optional(),
24456
+ description: z$2.string().optional(),
24457
+ parameters: z$2.union([
24458
+ z$2.record(z$2.string(), z$2.any()),
25986
24459
  // JSON Schema as object
25987
- z$1.any()
24460
+ z$2.any()
25988
24461
  // Zod schema or other schema types - validated at tool execution
25989
24462
  ]),
25990
- outputSchema: z$1.union([z$1.record(z$1.string(), z$1.any()), z$1.any()]).optional(),
25991
- execute: z$1.optional(z$1.function(z$1.tuple([z$1.any(), z$1.any()]), z$1.promise(z$1.any()))),
25992
- type: z$1.union([z$1.literal("function"), z$1.literal("provider-defined"), z$1.undefined()]).optional(),
25993
- args: z$1.record(z$1.string(), z$1.any()).optional()
24463
+ outputSchema: z$2.union([z$2.record(z$2.string(), z$2.any()), z$2.any()]).optional(),
24464
+ execute: z$2.optional(z$2.function(z$2.tuple([z$2.any(), z$2.any()]), z$2.promise(z$2.any()))),
24465
+ toModelOutput: z$2.optional(z$2.function(z$2.tuple([z$2.any()]), z$2.any())),
24466
+ type: z$2.union([z$2.literal("function"), z$2.literal("provider-defined"), z$2.undefined()]).optional(),
24467
+ args: z$2.record(z$2.string(), z$2.any()).optional()
25994
24468
  });
25995
- var storageThreadSchema = z$1.object({
25996
- id: z$1.string(),
25997
- title: z$1.string().optional(),
25998
- resourceId: z$1.string(),
25999
- createdAt: z$1.date(),
26000
- updatedAt: z$1.date(),
26001
- metadata: z$1.record(z$1.string(), z$1.any()).optional()
24469
+ var storageThreadSchema = z$2.object({
24470
+ id: z$2.string(),
24471
+ title: z$2.string().optional(),
24472
+ resourceId: z$2.string(),
24473
+ createdAt: z$2.date(),
24474
+ updatedAt: z$2.date(),
24475
+ metadata: z$2.record(z$2.string(), z$2.any()).optional()
26002
24476
  });
26003
- z$1.object({
26004
- convertedTools: z$1.record(z$1.string(), coreToolSchema)
24477
+ z$2.object({
24478
+ convertedTools: z$2.record(z$2.string(), coreToolSchema)
26005
24479
  });
26006
- z$1.object({
26007
- threadExists: z$1.boolean(),
24480
+ z$2.object({
24481
+ threadExists: z$2.boolean(),
26008
24482
  thread: storageThreadSchema.optional(),
26009
- messageList: z$1.instanceof(MessageList$1),
24483
+ messageList: z$2.instanceof(MessageList$1),
26010
24484
  /** Shared processor states map that persists across loop iterations for both input and output processors */
26011
- processorStates: z$1.instanceof(Map),
24485
+ processorStates: z$2.instanceof(Map),
26012
24486
  /** Tripwire data when input processor triggered abort */
26013
- tripwire: z$1.object({
26014
- reason: z$1.string(),
26015
- retry: z$1.boolean().optional(),
26016
- metadata: z$1.unknown().optional(),
26017
- processorId: z$1.string().optional()
24487
+ tripwire: z$2.object({
24488
+ reason: z$2.string(),
24489
+ retry: z$2.boolean().optional(),
24490
+ metadata: z$2.unknown().optional(),
24491
+ processorId: z$2.string().optional()
26018
24492
  }).optional()
26019
24493
  });
26020
24494
  var DEFAULT_CACHE_MAX_SIZE = 1e3;
26021
- new LRUCache({
24495
+ new L({
26022
24496
  max: DEFAULT_CACHE_MAX_SIZE
26023
24497
  });
26024
24498
 
@@ -27700,4 +26174,4 @@ function useCancelWorkflowRun() {
27700
26174
  }
27701
26175
 
27702
26176
  export { MessageUsages as $, EntryTitleClass as A, EntryTitle as B, CodeBlockClass as C, CodeBlock as D, Entity as E, CodeCopyButton as F, Icon as G, IconButtonClass as H, IconSizes as I, IconButton as J, AgentIcon as K, ToolsIcon as L, MastraReactProvider as M, Tooltip as N, TooltipContentClass as O, TooltipContent as P, TooltipTrigger as Q, MessageClass as R, Message as S, ToolApprovalClass as T, MessageContentClass as U, MessageContent as V, WorkflowIcon as W, MessageActionsClass as X, MessageActions as Y, MessageUsagesClass as Z, __commonJS$3 as _, __require2 as a, MessageUsageClass as a0, MessageUsage as a1, MessageUsageEntryClass as a2, MessageUsageEntry as a3, MessageUsageValueClass as a4, MessageUsageValue as a5, MessageListClass as a6, MessageList as a7, MessageStreamingClass as a8, MessageStreaming as a9, useCreateWorkflowRun as aa, useCancelWorkflowRun as ab, useStreamWorkflow as ac, useChat as b, resolveToChildMessages as c, toAssistantUIMessage as d, useEntity as e, EntityTriggerClass as f, EntityTriggerVariantClasses as g, EntityTrigger as h, EntityContentClass as i, EntityContent as j, EntityCaret as k, ToolApproval as l, mapWorkflowStreamChunkToWatchResult as m, ToolApprovalTitleClass as n, ToolApprovalTitle as o, ToolApprovalHeaderClass as p, ToolApprovalHeader as q, require_token_error as r, ToolApprovalContentClass as s, toUIMessage as t, useMastraClient as u, ToolApprovalContent as v, ToolApprovalActionsClass as w, ToolApprovalActions as x, EntryClass as y, Entry as z };
27703
- //# sourceMappingURL=index-BQSALCsO.js.map
26177
+ //# sourceMappingURL=index-DAN4vgIA.js.map