react-instantsearch 7.39.1 → 7.41.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- /*! React InstantSearch 7.39.1 | © Algolia, Inc. and contributors; MIT License | https://github.com/algolia/instantsearch */
1
+ /*! React InstantSearch 7.41.0 | © Algolia, Inc. and contributors; MIT License | https://github.com/algolia/instantsearch */
2
2
  (function (global, factory) {
3
3
  typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('react')) :
4
4
  typeof define === 'function' && define.amd ? define(['exports', 'react'], factory) :
@@ -24,7 +24,7 @@
24
24
 
25
25
  var React__namespace = /*#__PURE__*/_interopNamespaceDefault(React);
26
26
 
27
- var version$2 = '7.39.1';
27
+ var version$2 = '7.41.0';
28
28
 
29
29
  function _define_property(obj, key, value) {
30
30
  if (key in obj) {
@@ -7037,7 +7037,7 @@
7037
7037
  return attribute;
7038
7038
  }
7039
7039
 
7040
- function addAbsolutePosition(hits, page, hitsPerPage) {
7040
+ function addAbsolutePosition$1(hits, page, hitsPerPage) {
7041
7041
  return hits.map(function(hit, idx) {
7042
7042
  return _object_spread_props(_object_spread({}, hit), {
7043
7043
  __position: hitsPerPage * page + idx + 1
@@ -7045,7 +7045,7 @@
7045
7045
  });
7046
7046
  }
7047
7047
 
7048
- function addQueryID(hits, queryID) {
7048
+ function addQueryID$1(hits, queryID) {
7049
7049
  if (!queryID) {
7050
7050
  return hits;
7051
7051
  }
@@ -7254,6 +7254,12 @@
7254
7254
  return widget.$$type === 'ais.dynamicWidgets' || widget.$$type === 'ais.feeds';
7255
7255
  }
7256
7256
 
7257
+ /**
7258
+ * Logs a warning when this function is called, in development environment only.
7259
+ */ var deprecate = function deprecate(fn, // eslint-disable-next-line no-unused-vars
7260
+ message) {
7261
+ return fn;
7262
+ };
7257
7263
  /**
7258
7264
  * Logs a warning
7259
7265
  * This is used to log issues in development environment only.
@@ -7520,6 +7526,9 @@
7520
7526
  current: 0
7521
7527
  },
7522
7528
  waitForResultsRef: null,
7529
+ resolveWaitForResultsRef: {
7530
+ current: null
7531
+ },
7523
7532
  ignoreMultipleHooksWarning: false
7524
7533
  });
7525
7534
 
@@ -7731,7 +7740,10 @@
7731
7740
  useWidget({
7732
7741
  widget: widget,
7733
7742
  parentIndex: parentIndex,
7734
- props: stableProps,
7743
+ props: [
7744
+ stableProps,
7745
+ stableAdditionalWidgetProperties
7746
+ ],
7735
7747
  shouldSsr: Boolean(serverContext),
7736
7748
  skipSuspense: skipSuspense
7737
7749
  });
@@ -8467,13 +8479,47 @@
8467
8479
  ].concat(_to_consumable_array(resolveScopedResultsFromWidgets(current.getWidgets()))));
8468
8480
  }, []);
8469
8481
  }
8482
+ function getWidgetsRequestDependencies(widgets) {
8483
+ return widgets.reduce(function(dependencies, widget) {
8484
+ if (isIndexWidget(widget)) {
8485
+ if (widget._isolated) {
8486
+ return dependencies;
8487
+ }
8488
+ var childDependencies = getWidgetsRequestDependencies(widget.getWidgets());
8489
+ return {
8490
+ hasSearchWidget: dependencies.hasSearchWidget || childDependencies.hasSearchWidget,
8491
+ hasRecommendWidget: dependencies.hasRecommendWidget || childDependencies.hasRecommendWidget
8492
+ };
8493
+ }
8494
+ if (widget.dependsOn === 'recommend') {
8495
+ return _object_spread_props(_object_spread({}, dependencies), {
8496
+ hasRecommendWidget: true
8497
+ });
8498
+ }
8499
+ if (widget.dependsOn === 'none') {
8500
+ return dependencies;
8501
+ }
8502
+ return _object_spread_props(_object_spread({}, dependencies), {
8503
+ hasSearchWidget: true
8504
+ });
8505
+ }, {
8506
+ hasSearchWidget: false,
8507
+ hasRecommendWidget: false
8508
+ });
8509
+ }
8510
+ function recomputeInstantSearchRequestDependencies(instantSearchInstance) {
8511
+ var _getWidgetsRequestDependencies = getWidgetsRequestDependencies(instantSearchInstance.mainIndex.getWidgets()), hasSearchWidget = _getWidgetsRequestDependencies.hasSearchWidget, hasRecommendWidget = _getWidgetsRequestDependencies.hasRecommendWidget;
8512
+ instantSearchInstance._hasSearchWidget = hasSearchWidget;
8513
+ instantSearchInstance._hasRecommendWidget = hasRecommendWidget;
8514
+ }
8470
8515
  var index = function index(widgetParams) {
8471
- if (widgetParams === undefined || widgetParams.indexName === undefined && !widgetParams.EXPERIMENTAL_isolated) {
8516
+ var _widgetParams_EXPERIMENTAL_isolated;
8517
+ if (widgetParams === undefined || widgetParams.indexName === undefined && !widgetParams.isolated && !widgetParams.EXPERIMENTAL_isolated) {
8472
8518
  throw new Error(withUsage$s('The `indexName` option is required.'));
8473
8519
  }
8474
8520
  // When isolated=true, we use an empty string as the default indexName.
8475
8521
  // This is intentional: isolated indices do not require a real index name.
8476
- var _widgetParams_indexName = widgetParams.indexName, indexName = _widgetParams_indexName === void 0 ? '' : _widgetParams_indexName, _widgetParams_indexId = widgetParams.indexId, indexId = _widgetParams_indexId === void 0 ? indexName : _widgetParams_indexId, tmp = widgetParams.EXPERIMENTAL_isolated, isolated = tmp === void 0 ? false : tmp;
8522
+ var _widgetParams_indexName = widgetParams.indexName, indexName = _widgetParams_indexName === void 0 ? '' : _widgetParams_indexName, _widgetParams_indexId = widgetParams.indexId, indexId = _widgetParams_indexId === void 0 ? indexName : _widgetParams_indexId, _widgetParams_isolated = widgetParams.isolated, isolated = _widgetParams_isolated === void 0 ? (_widgetParams_EXPERIMENTAL_isolated = widgetParams.EXPERIMENTAL_isolated) !== null && _widgetParams_EXPERIMENTAL_isolated !== void 0 ? _widgetParams_EXPERIMENTAL_isolated : false : _widgetParams_isolated;
8477
8523
  var localWidgets = [];
8478
8524
  var localUiState = {};
8479
8525
  var localInstantSearchInstance = null;
@@ -8481,8 +8527,11 @@
8481
8527
  var helper = null;
8482
8528
  var derivedHelper = null;
8483
8529
  var lastValidSearchParameters = null;
8484
- var hasRecommendWidget = false;
8485
- var hasSearchWidget = false;
8530
+ var recomputeLocalRequestDependencies = function recomputeLocalRequestDependencies() {
8531
+ if (localInstantSearchInstance) {
8532
+ recomputeInstantSearchRequestDependencies(localInstantSearchInstance);
8533
+ }
8534
+ };
8486
8535
  return {
8487
8536
  $$type: 'ais.index',
8488
8537
  $$widgetType: 'ais.index',
@@ -8573,21 +8622,12 @@
8573
8622
  }
8574
8623
  flatWidgets.forEach(function(widget) {
8575
8624
  widget.parent = _this;
8576
- if (isIndexWidget(widget)) {
8577
- return;
8625
+ if (!isIndexWidget(widget)) {
8626
+ addWidgetId(widget);
8578
8627
  }
8579
- if (localInstantSearchInstance && widget.dependsOn === 'recommend') {
8580
- localInstantSearchInstance._hasRecommendWidget = true;
8581
- } else if (localInstantSearchInstance) {
8582
- localInstantSearchInstance._hasSearchWidget = true;
8583
- } else if (widget.dependsOn === 'recommend') {
8584
- hasRecommendWidget = true;
8585
- } else {
8586
- hasSearchWidget = true;
8587
- }
8588
- addWidgetId(widget);
8589
8628
  });
8590
8629
  localWidgets = localWidgets.concat(flatWidgets);
8630
+ recomputeLocalRequestDependencies();
8591
8631
  if (localInstantSearchInstance && Boolean(flatWidgets.length)) {
8592
8632
  privateHelperSetState(helper, {
8593
8633
  state: getLocalWidgetsSearchParameters(localWidgets, {
@@ -8644,21 +8684,10 @@
8644
8684
  localWidgets = localWidgets.filter(function(widget) {
8645
8685
  return flatWidgets.indexOf(widget) === -1;
8646
8686
  });
8647
- localWidgets.forEach(function(widget) {
8687
+ flatWidgets.forEach(function(widget) {
8648
8688
  widget.parent = undefined;
8649
- if (isIndexWidget(widget)) {
8650
- return;
8651
- }
8652
- if (localInstantSearchInstance && widget.dependsOn === 'recommend') {
8653
- localInstantSearchInstance._hasRecommendWidget = true;
8654
- } else if (localInstantSearchInstance) {
8655
- localInstantSearchInstance._hasSearchWidget = true;
8656
- } else if (widget.dependsOn === 'recommend') {
8657
- hasRecommendWidget = true;
8658
- } else {
8659
- hasSearchWidget = true;
8660
- }
8661
8689
  });
8690
+ recomputeLocalRequestDependencies();
8662
8691
  if (localInstantSearchInstance && Boolean(flatWidgets.length)) {
8663
8692
  var _flatWidgets_reduce = flatWidgets.reduce(function(states, widget) {
8664
8693
  // the `dispose` method exists at this point we already assert it
@@ -8881,12 +8910,7 @@
8881
8910
  // schedule a render that will render the results injected on the helper.
8882
8911
  instantSearchInstance.scheduleRender();
8883
8912
  }
8884
- if (hasRecommendWidget) {
8885
- instantSearchInstance._hasRecommendWidget = true;
8886
- }
8887
- if (hasSearchWidget) {
8888
- instantSearchInstance._hasSearchWidget = true;
8889
- }
8913
+ recomputeLocalRequestDependencies();
8890
8914
  },
8891
8915
  render: function render(param) {
8892
8916
  var _this = this;
@@ -9160,7 +9184,7 @@
9160
9184
  });
9161
9185
  }
9162
9186
 
9163
- var version = '4.106.0';
9187
+ var version = '4.108.0';
9164
9188
 
9165
9189
  var ANONYMOUS_TOKEN_COOKIE_KEY = '_ALGOLIA';
9166
9190
  function getCookie(name) {
@@ -11301,8 +11325,11 @@
11301
11325
  mainHelper.searchForFacetValues = mainHelper.searchForCompositionFacetValues.bind(mainHelper);
11302
11326
  }
11303
11327
  mainHelper.search = function() {
11304
- _this.status = 'loading';
11305
- _this.scheduleRender(false);
11328
+ var hasSearchOrRecommendWidget = _this._hasSearchWidget || _this._hasRecommendWidget;
11329
+ if (hasSearchOrRecommendWidget) {
11330
+ _this.status = 'loading';
11331
+ }
11332
+ _this.scheduleRender(!hasSearchOrRecommendWidget);
11306
11333
  // This solution allows us to keep the exact same API for the users but
11307
11334
  // under the hood, we have a different implementation. It should be
11308
11335
  // completely transparent for the rest of the codebase. Only this module
@@ -11366,7 +11393,7 @@
11366
11393
  error.error = error;
11367
11394
  _this.error = error;
11368
11395
  _this.status = 'error';
11369
- _this.scheduleRender(false);
11396
+ _this.scheduleRender(!_this._hasSearchWidget && !_this._hasRecommendWidget);
11370
11397
  // This needs to execute last because it throws the error.
11371
11398
  _this.emit('error', error);
11372
11399
  });
@@ -12055,10 +12082,14 @@
12055
12082
  return function(widgetParams) {
12056
12083
  var _ref = widgetParams || {}, _ref_escapeHTML = _ref.escapeHTML, escapeHTML = _ref_escapeHTML === void 0 ? true : _ref_escapeHTML, _ref_transformItems = _ref.transformItems, transformItems = _ref_transformItems === void 0 ? function(indices) {
12057
12084
  return indices;
12058
- } : _ref_transformItems, tmp = _ref.future, _ref1 = tmp === void 0 ? {} : tmp, _ref_undefinedEmptyQuery = _ref1.undefinedEmptyQuery, undefinedEmptyQuery = _ref_undefinedEmptyQuery === void 0 ? false : _ref_undefinedEmptyQuery;
12085
+ } : _ref_transformItems, _ref_requiresSearch = _ref.requiresSearch, requiresSearch = _ref_requiresSearch === void 0 ? true : _ref_requiresSearch, tmp = _ref.future, _ref1 = tmp === void 0 ? {} : tmp, _ref_undefinedEmptyQuery = _ref1.undefinedEmptyQuery, undefinedEmptyQuery = _ref_undefinedEmptyQuery === void 0 ? false : _ref_undefinedEmptyQuery;
12059
12086
  var connectorState = {};
12060
12087
  return {
12061
12088
  $$type: 'ais.autocomplete',
12089
+ dependsOn: requiresSearch ? 'search' : 'none',
12090
+ shouldRender: requiresSearch ? undefined : function() {
12091
+ return true;
12092
+ },
12062
12093
  init: function init(initOptions) {
12063
12094
  var instantSearchInstance = initOptions.instantSearchInstance;
12064
12095
  renderFn(_object_spread_props(_object_spread({}, this.getWidgetRenderState(initOptions)), {
@@ -12102,7 +12133,7 @@
12102
12133
  helper: scopedResult.helper,
12103
12134
  widgetType: _this.$$type
12104
12135
  });
12105
- var hits = scopedResult.results ? addQueryID(addAbsolutePosition(scopedResult.results.hits, scopedResult.results.page, scopedResult.results.hitsPerPage), scopedResult.results.queryID) : [];
12136
+ var hits = scopedResult.results ? addQueryID$1(addAbsolutePosition$1(scopedResult.results.hits, scopedResult.results.page, scopedResult.results.hitsPerPage), scopedResult.results.queryID) : [];
12106
12137
  return {
12107
12138
  indexId: scopedResult.indexId,
12108
12139
  indexName: ((_scopedResult_results = scopedResult.results) === null || _scopedResult_results === void 0 ? void 0 : _scopedResult_results.index) || '',
@@ -12599,6 +12630,7 @@
12599
12630
  return undefined;
12600
12631
  }
12601
12632
 
12633
+ var _computedKey$1;
12602
12634
  var tryParseJson = function tryParseJson(value) {
12603
12635
  try {
12604
12636
  return JSON.parse(value);
@@ -12669,6 +12701,8 @@
12669
12701
  return fallbackInput;
12670
12702
  };
12671
12703
  var defaultGuardrailFallbackResponse = 'Sorry, we are not able to generate a response at the moment.';
12704
+ _computedKey$1 = /** @internal */ '~addToolResultForMessage';
12705
+ var _computedKey1$1 = _computedKey$1;
12672
12706
  /**
12673
12707
  * Abstract base class for chat implementations.
12674
12708
  */ var AbstractChat = /*#__PURE__*/ function() {
@@ -12688,6 +12722,12 @@
12688
12722
  _define_property(this, "sendAutomaticallyWhen", void 0);
12689
12723
  _define_property(this, "shouldRepairToolInput", void 0);
12690
12724
  _define_property(this, "activeResponse", null);
12725
+ _define_property(this, "latestResponse", null);
12726
+ _define_property(this, "responsesByToolCallId", new Map());
12727
+ _define_property(this, "responseByMessage", new WeakMap());
12728
+ // Once tool ownership is discarded, an identifier-only result cannot prove
12729
+ // which response generation submitted it. Scoped submissions remain safe.
12730
+ _define_property(this, "acceptsIdentifierOnlyToolResults", true);
12691
12731
  _define_property(this, "jobExecutor", new SerialJobExecutor());
12692
12732
  /**
12693
12733
  * Appends or replaces a user message to the chat list. This triggers the API call to fetch
@@ -12773,13 +12813,13 @@
12773
12813
  // Find the message to regenerate from
12774
12814
  var targetIndex = -1;
12775
12815
  if (messageId) {
12776
- targetIndex = _this1.state.messages.findIndex(function(m) {
12816
+ targetIndex = _this1.messages.findIndex(function(m) {
12777
12817
  return m.id === messageId;
12778
12818
  });
12779
12819
  } else {
12780
12820
  // Find the last assistant message
12781
- for(var i = _this1.state.messages.length - 1; i >= 0; i--){
12782
- if (_this1.state.messages[i].role === 'assistant') {
12821
+ for(var i = _this1.messages.length - 1; i >= 0; i--){
12822
+ if (_this1.messages[i].role === 'assistant') {
12783
12823
  targetIndex = i;
12784
12824
  break;
12785
12825
  }
@@ -12787,7 +12827,7 @@
12787
12827
  }
12788
12828
  if (targetIndex >= 0) {
12789
12829
  // Remove the assistant message and all messages after it
12790
- _this1.state.messages = _this1.state.messages.slice(0, targetIndex);
12830
+ _this1.messages = _this1.messages.slice(0, targetIndex);
12791
12831
  }
12792
12832
  return _this1.makeRequest(_object_spread({
12793
12833
  trigger: 'regenerate-message',
@@ -12802,23 +12842,10 @@
12802
12842
  if (!_this.transport) {
12803
12843
  return Promise.reject(new Error('Transport is required for resuming stream. Please provide a transport when initializing the chat.'));
12804
12844
  }
12805
- _this.setStatus({
12806
- status: 'submitted'
12807
- });
12808
- return _this.transport.reconnectToStream(_object_spread({
12809
- chatId: _this.id
12810
- }, options)).then(function(stream) {
12811
- if (stream) {
12812
- return _this.processStreamWithCallbacks(stream);
12813
- } else {
12814
- _this.setStatus({
12815
- status: 'ready'
12816
- });
12817
- return Promise.resolve();
12818
- }
12819
- }, function(error) {
12820
- _this.handleError(error);
12821
- return Promise.resolve();
12845
+ return _this.consume(function() {
12846
+ return _this.transport.reconnectToStream(_object_spread({
12847
+ chatId: _this.id
12848
+ }, options));
12822
12849
  });
12823
12850
  });
12824
12851
  });
@@ -12834,53 +12861,57 @@
12834
12861
  });
12835
12862
  /**
12836
12863
  * Add a tool result for a tool call.
12837
- */ _define_property(this, "addToolResult", function(param) {
12838
- var tool = param.tool, toolCallId = param.toolCallId, output = param.output;
12839
- return _this.jobExecutor.run(function() {
12840
- // Find the message with this tool call
12841
- var messageIndex = _this.state.messages.findIndex(function(m) {
12842
- var _ref;
12843
- var _m_parts;
12844
- return (_ref = (_m_parts = m.parts) === null || _m_parts === void 0 ? void 0 : _m_parts.some(function(p) {
12845
- return 'toolCallId' in p && p.toolCallId === toolCallId || 'type' in p && p.type === "tool-".concat(String(tool));
12846
- })) !== null && _ref !== void 0 ? _ref : false;
12847
- });
12848
- if (messageIndex === -1) return Promise.resolve();
12849
- var message = _this.state.messages[messageIndex];
12850
- var updatedParts = message.parts.map(function(part) {
12851
- if ('toolCallId' in part && part.toolCallId === toolCallId && 'state' in part) {
12852
- return _object_spread_props(_object_spread({}, part), {
12853
- state: 'output-available',
12854
- output: output
12855
- });
12856
- }
12857
- return part;
12858
- });
12859
- _this.state.replaceMessage(messageIndex, _object_spread_props(_object_spread({}, message), {
12860
- parts: updatedParts
12861
- }));
12862
- // Check if we should auto-send based on sendAutomaticallyWhen
12863
- if (_this.sendAutomaticallyWhen) {
12864
- return Promise.resolve(_this.sendAutomaticallyWhen({
12865
- messages: _this.state.messages
12866
- })).then(function(shouldSend) {
12867
- if (shouldSend) {
12868
- return _this.makeRequest({
12869
- trigger: 'submit-message'
12870
- });
12871
- }
12872
- return Promise.resolve();
12864
+ */ _define_property(this, "addToolResult", function(options) {
12865
+ if (!_this.acceptsIdentifierOnlyToolResults) {
12866
+ return Promise.resolve();
12867
+ }
12868
+ var owners = _this.responsesByToolCallId.get(options.toolCallId);
12869
+ var response = (owners === null || owners === void 0 ? void 0 : owners.size) === 1 ? owners.values().next().value : undefined;
12870
+ if (response) return _this.submitToolResult(response, options);
12871
+ var findMatchingMessage = function findMatchingMessage() {
12872
+ var matchingMessages = _this.messages.filter(function(message) {
12873
+ var _message_parts;
12874
+ return (_message_parts = message.parts) === null || _message_parts === void 0 ? void 0 : _message_parts.some(function(part) {
12875
+ return 'toolCallId' in part && part.toolCallId === options.toolCallId;
12873
12876
  });
12877
+ });
12878
+ return matchingMessages.length === 1 ? matchingMessages[0] : undefined;
12879
+ };
12880
+ if (!findMatchingMessage()) return Promise.resolve();
12881
+ return _this.jobExecutor.run(function() {
12882
+ if (!_this.acceptsIdentifierOnlyToolResults) return Promise.resolve();
12883
+ var message = findMatchingMessage();
12884
+ if (!message || !_this.commit(options.toolCallId, options.output, message.id, undefined, message)) {
12885
+ return Promise.resolve();
12874
12886
  }
12875
- return Promise.resolve();
12887
+ return _this.continueResponse();
12876
12888
  });
12877
12889
  });
12890
+ _define_property(this, _computedKey1$1, function(message, options) {
12891
+ var hasToolCall = function hasToolCall(candidate) {
12892
+ var _candidate_parts;
12893
+ return ((_candidate_parts = candidate.parts) === null || _candidate_parts === void 0 ? void 0 : _candidate_parts.some(function(part) {
12894
+ return 'toolCallId' in part && part.toolCallId === options.toolCallId;
12895
+ })) === true;
12896
+ };
12897
+ if (!hasToolCall(message)) {
12898
+ return Promise.resolve();
12899
+ }
12900
+ var response = _this.responseByMessage.get(message);
12901
+ var currentMessage = _this.messages.includes(message) ? message : response && !response.isRetired ? _this.messages.find(function(candidate) {
12902
+ return candidate.id === message.id && _this.responseByMessage.get(candidate) === response && hasToolCall(candidate);
12903
+ }) : undefined;
12904
+ if (!currentMessage) return Promise.resolve();
12905
+ return _this.submitToolResult(response, options, currentMessage.id, currentMessage);
12906
+ });
12878
12907
  /**
12879
12908
  * Abort the current request immediately, keep the generated tokens if any.
12880
12909
  */ _define_property(this, "stop", function() {
12881
12910
  if (_this.activeResponse) {
12882
- _this.activeResponse.abortController.abort();
12911
+ var response = _this.activeResponse;
12912
+ response.outcome = 'aborted';
12883
12913
  _this.activeResponse = null;
12914
+ response.abortController.abort();
12884
12915
  }
12885
12916
  _this.setStatus({
12886
12917
  status: 'ready'
@@ -12942,6 +12973,14 @@
12942
12973
  * context.
12943
12974
  */ key: "resetConversationId",
12944
12975
  value: function resetConversationId() {
12976
+ if (this.responsesByToolCallId.size > 0 || this.messages.some(function(message) {
12977
+ var _message_parts;
12978
+ return (_message_parts = message.parts) === null || _message_parts === void 0 ? void 0 : _message_parts.some(function(part) {
12979
+ return 'toolCallId' in part;
12980
+ });
12981
+ })) {
12982
+ this.acceptsIdentifierOnlyToolResults = false;
12983
+ }
12945
12984
  this.conversationId = this.generateId();
12946
12985
  }
12947
12986
  },
@@ -12951,7 +12990,93 @@
12951
12990
  return this.state.messages;
12952
12991
  },
12953
12992
  set: function set(messages) {
12993
+ var _this = this;
12994
+ var getToolOccurrences = function getToolOccurrences(message) {
12995
+ return message.parts.filter(function(part) {
12996
+ return 'toolCallId' in part;
12997
+ }).map(function(part) {
12998
+ return {
12999
+ type: part.type,
13000
+ toolCallId: part.toolCallId,
13001
+ state: 'state' in part ? part.state : undefined,
13002
+ input: 'input' in part ? part.input : undefined,
13003
+ output: 'output' in part ? part.output : undefined,
13004
+ errorText: 'errorText' in part ? part.errorText : undefined,
13005
+ providerExecuted: 'providerExecuted' in part ? part.providerExecuted : undefined
13006
+ };
13007
+ });
13008
+ };
13009
+ var isEquivalentRehydration = function isEquivalentRehydration(message) {
13010
+ var replacements = messages.filter(function(candidate) {
13011
+ return candidate.id === message.id;
13012
+ });
13013
+ if (replacements.length !== 1) return false;
13014
+ var toolOccurrences = getToolOccurrences(message);
13015
+ var replacementToolOccurrences = getToolOccurrences(replacements[0]);
13016
+ return toolOccurrences.length > 0 || replacementToolOccurrences.length > 0 ? isEqual(toolOccurrences, replacementToolOccurrences) : isEqual(message.parts, replacements[0].parts);
13017
+ };
13018
+ var detachedResponses = new Set();
13019
+ this.state.messages.forEach(function(message) {
13020
+ if (!messages.includes(message)) {
13021
+ var response = _this.responseByMessage.get(message);
13022
+ if (response && !isEquivalentRehydration(message)) {
13023
+ detachedResponses.add(response);
13024
+ }
13025
+ }
13026
+ });
13027
+ var removedToolOwner = this.state.messages.some(function(message) {
13028
+ var _message_parts;
13029
+ return ((_message_parts = message.parts) === null || _message_parts === void 0 ? void 0 : _message_parts.some(function(part) {
13030
+ return 'toolCallId' in part;
13031
+ })) && !messages.includes(message) && !isEquivalentRehydration(message);
13032
+ });
13033
+ var toolCallIds = new Set();
13034
+ var hasDuplicateToolCallId = messages.some(function(message) {
13035
+ var _message_parts;
13036
+ return ((_message_parts = message.parts) === null || _message_parts === void 0 ? void 0 : _message_parts.some(function(part) {
13037
+ if (!('toolCallId' in part)) {
13038
+ return false;
13039
+ }
13040
+ if (toolCallIds.has(part.toolCallId)) {
13041
+ return true;
13042
+ }
13043
+ toolCallIds.add(part.toolCallId);
13044
+ return false;
13045
+ })) === true;
13046
+ });
13047
+ if (removedToolOwner || hasDuplicateToolCallId) {
13048
+ this.acceptsIdentifierOnlyToolResults = false;
13049
+ }
12954
13050
  this.state.messages = messages;
13051
+ var retainedMessageIds = new Set(messages.map(function(message) {
13052
+ return message.id;
13053
+ }));
13054
+ var responses = new Set();
13055
+ this.responsesByToolCallId.forEach(function(owners) {
13056
+ owners.forEach(function(response) {
13057
+ return responses.add(response);
13058
+ });
13059
+ });
13060
+ if (this.activeResponse) {
13061
+ responses.add(this.activeResponse);
13062
+ }
13063
+ detachedResponses.forEach(function(response) {
13064
+ responses.add(response);
13065
+ _this.retireResponse(response);
13066
+ });
13067
+ responses.forEach(function(response) {
13068
+ var message = response.messageId ? messages.find(function(candidate) {
13069
+ return candidate.id === response.messageId;
13070
+ }) : undefined;
13071
+ if (message && !response.isRetired && !detachedResponses.has(response)) {
13072
+ _this.responseByMessage.set(message, response);
13073
+ }
13074
+ });
13075
+ responses.forEach(function(response) {
13076
+ if (detachedResponses.has(response) || response.messageId && !retainedMessageIds.has(response.messageId)) {
13077
+ _this.pruneDetachedResponse(response);
13078
+ }
13079
+ });
12955
13080
  }
12956
13081
  },
12957
13082
  {
@@ -12960,6 +13085,154 @@
12960
13085
  return this.state.messages[this.state.messages.length - 1];
12961
13086
  }
12962
13087
  },
13088
+ {
13089
+ key: "replaceMessage",
13090
+ value: function replaceMessage(index, message, response) {
13091
+ var _this_messages_index;
13092
+ this.state.replaceMessage(index, message);
13093
+ var canonicalMessage = (_this_messages_index = this.messages[index]) !== null && _this_messages_index !== void 0 ? _this_messages_index : message;
13094
+ if (response && this.messages.includes(canonicalMessage)) {
13095
+ this.responseByMessage.set(canonicalMessage, response);
13096
+ }
13097
+ return canonicalMessage;
13098
+ }
13099
+ },
13100
+ {
13101
+ key: "commit",
13102
+ value: function commit(toolCallId, output, messageId, response, expectedMessage) {
13103
+ var isTargetPart = function isTargetPart(part) {
13104
+ return 'toolCallId' in part && part.toolCallId === toolCallId;
13105
+ };
13106
+ var messageIndex = this.messages.findIndex(function(message) {
13107
+ return (!messageId || message.id === messageId) && (!expectedMessage || message === expectedMessage) && message.parts.some(isTargetPart);
13108
+ });
13109
+ if (messageIndex === -1) return false;
13110
+ var message = this.messages[messageIndex];
13111
+ var partIndex = message.parts.findIndex(isTargetPart);
13112
+ var part = message.parts[partIndex];
13113
+ if (!('state' in part) || part.state === 'output-available' && !part.preliminary || part.state === 'output-error') {
13114
+ return false;
13115
+ }
13116
+ // eslint-disable-next-line no-unused-vars, @typescript-eslint/no-unused-vars
13117
+ part.preliminary; // eslint-disable-next-line no-unused-vars, @typescript-eslint/no-unused-vars
13118
+ part.rawOutput;
13119
+ var committedPart = _object_without_properties(part, [
13120
+ "preliminary",
13121
+ "rawOutput"
13122
+ ]);
13123
+ var updatedParts = _to_consumable_array(message.parts);
13124
+ updatedParts[partIndex] = _object_spread_props(_object_spread({}, committedPart), {
13125
+ state: 'output-available',
13126
+ output: output
13127
+ });
13128
+ var updatedMessage = _object_spread_props(_object_spread({}, message), {
13129
+ parts: updatedParts
13130
+ });
13131
+ this.replaceMessage(messageIndex, updatedMessage, response);
13132
+ return true;
13133
+ }
13134
+ },
13135
+ {
13136
+ key: "continueResponse",
13137
+ value: function continueResponse(response) {
13138
+ var _this = this;
13139
+ if (response) {
13140
+ this.pruneDetachedResponse(response);
13141
+ if (response.isRetired || response.outcome !== 'succeeded' || response.requiredToolCallIds.size === 0 || Array.from(response.requiredToolCallIds).some(function(toolCallId) {
13142
+ return !response.resolvedToolCallIds.has(toolCallId);
13143
+ }) || !response.didNotifyFinish || response.didEvaluateContinuation) {
13144
+ return Promise.resolve();
13145
+ }
13146
+ response.didEvaluateContinuation = true;
13147
+ }
13148
+ if (!this.sendAutomaticallyWhen) return Promise.resolve();
13149
+ return Promise.resolve().then(function() {
13150
+ return _this.sendAutomaticallyWhen({
13151
+ messages: _this.messages
13152
+ });
13153
+ }).then(function(shouldSend) {
13154
+ if (response) {
13155
+ _this.pruneDetachedResponse(response);
13156
+ if (response.isRetired) return undefined;
13157
+ }
13158
+ return shouldSend ? _this.makeRequest({
13159
+ trigger: 'submit-message'
13160
+ }) : undefined;
13161
+ }).catch(function(error) {
13162
+ if (response) {
13163
+ _this.pruneDetachedResponse(response);
13164
+ if (response.isRetired) return;
13165
+ _this.handleError(error, {
13166
+ updateState: _this.latestResponse === response
13167
+ });
13168
+ return;
13169
+ }
13170
+ _this.handleError(error);
13171
+ });
13172
+ }
13173
+ },
13174
+ {
13175
+ key: "retireResponse",
13176
+ value: function retireResponse(response) {
13177
+ if (response.isRetired) return;
13178
+ response.isRetired = true;
13179
+ response.didEvaluateContinuation = true;
13180
+ if (this.activeResponse === response) {
13181
+ response.outcome = 'aborted';
13182
+ this.activeResponse = null;
13183
+ response.abortController.abort();
13184
+ this.setStatus({
13185
+ status: 'ready'
13186
+ });
13187
+ }
13188
+ }
13189
+ },
13190
+ {
13191
+ key: "pruneDetachedResponse",
13192
+ value: function pruneDetachedResponse(response) {
13193
+ var _this = this;
13194
+ if (!response.isRetired) {
13195
+ if (!response.messageId || this.messages.some(function(message) {
13196
+ return message.id === response.messageId;
13197
+ })) {
13198
+ return;
13199
+ }
13200
+ this.retireResponse(response);
13201
+ }
13202
+ // Keep a routing tombstone while a callback is running so public
13203
+ // addToolResult calls settle directly instead of entering the executor.
13204
+ if (response.pendingToolCallbacks > 0) return;
13205
+ this.responsesByToolCallId.forEach(function(owners, toolCallId) {
13206
+ owners.delete(response);
13207
+ if (owners.size === 0) {
13208
+ _this.responsesByToolCallId.delete(toolCallId);
13209
+ }
13210
+ });
13211
+ }
13212
+ },
13213
+ {
13214
+ key: "submitToolResult",
13215
+ value: function submitToolResult(response, param) {
13216
+ var _this = this;
13217
+ var toolCallId = param.toolCallId, output = param.output, messageId = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : response === null || response === void 0 ? void 0 : response.messageId, expectedMessage = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : messageId ? this.messages.find(function(message) {
13218
+ return message.id === messageId;
13219
+ }) : undefined;
13220
+ if (response === null || response === void 0 ? void 0 : response.isRetired) return Promise.resolve();
13221
+ var commitResult = function commitResult() {
13222
+ if (!_this.commit(toolCallId, output, messageId, response, expectedMessage)) {
13223
+ return Promise.resolve();
13224
+ }
13225
+ if (response === null || response === void 0 ? void 0 : response.requiredToolCallIds.has(toolCallId)) {
13226
+ response.resolvedToolCallIds.add(toolCallId);
13227
+ }
13228
+ return _this.continueResponse(response);
13229
+ };
13230
+ if (response && (this.activeResponse === response || response.outcome !== 'succeeded' || response.didEvaluateContinuation)) {
13231
+ return commitResult();
13232
+ }
13233
+ return this.jobExecutor.run(commitResult);
13234
+ }
13235
+ },
12963
13236
  {
12964
13237
  key: "makeRequest",
12965
13238
  value: function makeRequest(options) {
@@ -12967,42 +13240,72 @@
12967
13240
  if (!this.transport) {
12968
13241
  return Promise.reject(new Error('Transport is required for sending messages. Please provide a transport when initializing the chat.'));
12969
13242
  }
12970
- // Abort any existing request
13243
+ return this.consume(function(abortSignal) {
13244
+ return _this.transport.sendMessages({
13245
+ chatId: _this.id,
13246
+ messages: _this.messages,
13247
+ abortSignal: abortSignal,
13248
+ trigger: options.trigger,
13249
+ messageId: options.messageId,
13250
+ headers: options.headers,
13251
+ body: options.body,
13252
+ requestMetadata: options.metadata
13253
+ });
13254
+ });
13255
+ }
13256
+ },
13257
+ {
13258
+ key: "consume",
13259
+ value: function consume(createStream) {
13260
+ var _this = this;
12971
13261
  if (this.activeResponse) {
13262
+ this.activeResponse.outcome = 'aborted';
12972
13263
  this.activeResponse.abortController.abort();
12973
13264
  }
12974
- var abortController = new AbortController();
12975
- this.activeResponse = {
12976
- abortController: abortController
13265
+ var response = {
13266
+ abortController: new AbortController(),
13267
+ outcome: 'active',
13268
+ isRetired: false,
13269
+ requiredToolCallIds: new Set(),
13270
+ resolvedToolCallIds: new Set(),
13271
+ returnedToolCallbacks: [],
13272
+ pendingToolCallbacks: 0,
13273
+ didNotifyFinish: false,
13274
+ didEvaluateContinuation: false
12977
13275
  };
13276
+ this.activeResponse = response;
13277
+ this.latestResponse = response;
12978
13278
  this.setStatus({
12979
13279
  status: 'submitted'
12980
13280
  });
12981
- return this.transport.sendMessages({
12982
- chatId: this.id,
12983
- messages: this.state.messages,
12984
- abortSignal: abortController.signal,
12985
- trigger: options.trigger,
12986
- messageId: options.messageId,
12987
- headers: options.headers,
12988
- body: options.body,
12989
- requestMetadata: options.metadata
12990
- }).then(function(stream) {
12991
- _this.activeResponse.stream = stream;
12992
- return _this.processStreamWithCallbacks(stream);
13281
+ return createStream(response.abortController.signal).then(function(stream) {
13282
+ if (_this.activeResponse === response) {
13283
+ if (stream) return _this.processStream(stream, response);
13284
+ response.outcome = 'succeeded';
13285
+ _this.activeResponse = null;
13286
+ _this.setStatus({
13287
+ status: 'ready'
13288
+ });
13289
+ }
13290
+ return undefined;
12993
13291
  }, function(error) {
13292
+ if (_this.activeResponse !== response) return;
13293
+ _this.activeResponse = null;
12994
13294
  if (error.name === 'AbortError') {
12995
- // Request was aborted, don't treat as error
12996
- return Promise.resolve();
13295
+ response.outcome = 'aborted';
13296
+ _this.setStatus({
13297
+ status: 'ready'
13298
+ });
13299
+ } else {
13300
+ response.outcome = 'failed';
13301
+ _this.handleError(error);
12997
13302
  }
12998
- _this.handleError(error);
12999
- return Promise.resolve();
13000
13303
  });
13001
13304
  }
13002
13305
  },
13003
13306
  {
13004
- key: "processStreamWithCallbacks",
13005
- value: function processStreamWithCallbacks(stream) {
13307
+ key: "processStream",
13308
+ value: function processStream1(stream, response) {
13006
13309
  var _this = this;
13007
13310
  this.setStatus({
13008
13311
  status: 'streaming'
@@ -13011,26 +13314,135 @@
13011
13314
  var currentMessage;
13012
13315
  var currentMessageIndex = -1;
13013
13316
  var isAbort = false;
13014
- var isDisconnect = false;
13015
13317
  var isError = false;
13016
- // Track current text/reasoning part state
13017
- var currentTextPartId;
13018
- var currentReasoningPartId;
13019
13318
  var toolRawInputByCallId = {};
13020
13319
  var toolRawOutputByCallId = {};
13021
- // Promise chain for handling tool calls that return promises
13022
- var pendingToolCall = Promise.resolve();
13320
+ var findToolPart = function findToolPart(toolCallId) {
13321
+ return currentMessage.parts.findIndex(function(part) {
13322
+ return 'toolCallId' in part && part.toolCallId === toolCallId;
13323
+ });
13324
+ };
13325
+ var setPart = function setPart(index, part) {
13326
+ var parts = _to_consumable_array(currentMessage.parts);
13327
+ parts[index < 0 ? parts.length : index] = part;
13328
+ currentMessage = _object_spread_props(_object_spread({}, currentMessage), {
13329
+ parts: parts
13330
+ });
13331
+ currentMessage = _this.replaceMessage(currentMessageIndex, currentMessage, response);
13332
+ };
13333
+ var mergeCallProviderMetadata = function mergeCallProviderMetadata(toolCallId, metadata) {
13334
+ var toolIndex = findToolPart(toolCallId);
13335
+ if (toolIndex < 0) return;
13336
+ var existingPart = currentMessage.parts[toolIndex];
13337
+ setPart(toolIndex, _object_spread_props(_object_spread({}, existingPart), {
13338
+ callProviderMetadata: metadata !== null && metadata !== void 0 ? metadata : existingPart.callProviderMetadata
13339
+ }));
13340
+ };
13341
+ var getCanonicalMessage = function getCanonicalMessage() {
13342
+ var _this_messages_find;
13343
+ return response.messageId ? (_this_messages_find = _this.messages.find(function(message) {
13344
+ return message.id === response.messageId;
13345
+ })) !== null && _this_messages_find !== void 0 ? _this_messages_find : currentMessage : currentMessage;
13346
+ };
13347
+ var notifyFinish = function notifyFinish(param) {
13348
+ var isAbort = param.isAbort, isDisconnect = param.isDisconnect, isError = param.isError, message = param.message, _param_allowRetired = param.allowRetired, allowRetired = _param_allowRetired === void 0 ? false : _param_allowRetired;
13349
+ _this.pruneDetachedResponse(response);
13350
+ if (response.isRetired && !allowRetired || response.didNotifyFinish) {
13351
+ return;
13352
+ }
13353
+ response.didNotifyFinish = true;
13354
+ var canonicalMessage = message !== null && message !== void 0 ? message : getCanonicalMessage();
13355
+ if (_this.onFinish && canonicalMessage) {
13356
+ _this.onFinish({
13357
+ message: canonicalMessage,
13358
+ messages: _this.messages,
13359
+ isAbort: isAbort,
13360
+ isDisconnect: isDisconnect,
13361
+ isError: isError
13362
+ });
13363
+ }
13364
+ };
13365
+ var failToolCall = function failToolCall(reason) {
13366
+ if (response.outcome !== 'active') return;
13367
+ var message = getCanonicalMessage();
13368
+ var wasRetired = response.isRetired;
13369
+ var error = _instanceof(reason, Error) ? reason : new Error(String(reason));
13370
+ response.outcome = 'failed';
13371
+ response.abortController.abort();
13372
+ if (_this.activeResponse === response) {
13373
+ _this.activeResponse = null;
13374
+ _this.handleError(error);
13375
+ }
13376
+ notifyFinish({
13377
+ isAbort: false,
13378
+ isDisconnect: false,
13379
+ isError: true,
13380
+ message: message,
13381
+ allowRetired: !wasRetired
13382
+ });
13383
+ };
13384
+ var acceptServerToolResult = function acceptServerToolResult(toolCallId) {
13385
+ if (response.requiredToolCallIds.has(toolCallId)) {
13386
+ response.resolvedToolCallIds.add(toolCallId);
13387
+ }
13388
+ };
13023
13389
  return new Promise(function(resolve) {
13390
+ var finish = function finish(error) {
13391
+ if (response.outcome === 'failed') {
13392
+ resolve();
13393
+ return;
13394
+ }
13395
+ isAbort || (isAbort = response.outcome === 'aborted' || !!error && error.name === 'AbortError');
13396
+ response.outcome = isAbort ? 'aborted' : error ? 'failed' : 'succeeded';
13397
+ if (_this.activeResponse === response) {
13398
+ _this.activeResponse = null;
13399
+ if (error && !isAbort) {
13400
+ _this.handleError(error);
13401
+ } else {
13402
+ _this.setStatus({
13403
+ status: 'ready'
13404
+ });
13405
+ }
13406
+ }
13407
+ notifyFinish({
13408
+ isAbort: isAbort,
13409
+ isDisconnect: !!error && !isAbort,
13410
+ isError: isError
13411
+ });
13412
+ resolve(isAbort || error ? undefined : _this.continueResponse(response));
13413
+ };
13024
13414
  processStream(stream, function(chunk) {
13415
+ if (_this.activeResponse !== response || response.isRetired) return;
13416
+ if (currentMessageId) {
13417
+ var canonicalMessageIndex = _this.messages.findIndex(function(message) {
13418
+ return message.id === currentMessageId;
13419
+ });
13420
+ if (canonicalMessageIndex === -1) {
13421
+ _this.pruneDetachedResponse(response);
13422
+ return;
13423
+ }
13424
+ currentMessageIndex = canonicalMessageIndex;
13425
+ currentMessage = _this.messages[canonicalMessageIndex];
13426
+ _this.responseByMessage.set(currentMessage, response);
13427
+ }
13025
13428
  switch(chunk.type){
13026
13429
  case 'start':
13027
13430
  {
13028
13431
  currentMessageId = chunk.messageId || _this.generateId();
13432
+ response.messageId = currentMessageId;
13029
13433
  // Check if we're continuing an existing message or creating a new one
13030
13434
  var lastMessage = _this.lastMessage;
13031
13435
  if (lastMessage && lastMessage.role === 'assistant' && lastMessage.id === currentMessageId) {
13032
- currentMessage = lastMessage;
13033
- currentMessageIndex = _this.state.messages.length - 1;
13436
+ if (lastMessage.parts.some(function(part) {
13437
+ return 'toolCallId' in part;
13438
+ })) {
13439
+ _this.acceptsIdentifierOnlyToolResults = false;
13440
+ }
13441
+ currentMessage = _object_spread_props(_object_spread({}, lastMessage), {
13442
+ parts: _to_consumable_array(lastMessage.parts)
13443
+ });
13444
+ currentMessageIndex = _this.messages.length - 1;
13445
+ currentMessage = _this.replaceMessage(currentMessageIndex, currentMessage, response);
13034
13446
  } else {
13035
13447
  currentMessage = {
13036
13448
  id: currentMessageId,
@@ -13039,123 +13451,60 @@
13039
13451
  metadata: chunk.messageMetadata
13040
13452
  };
13041
13453
  _this.state.pushMessage(currentMessage);
13042
- currentMessageIndex = _this.state.messages.length - 1;
13454
+ currentMessageIndex = _this.messages.length - 1;
13455
+ _this.responseByMessage.set(currentMessage, response);
13043
13456
  }
13044
13457
  break;
13045
13458
  }
13046
13459
  case 'text-start':
13460
+ case 'reasoning-start':
13047
13461
  {
13048
13462
  if (!currentMessage) break;
13049
- currentTextPartId = chunk.id;
13050
- var textPart = {
13051
- type: 'text',
13463
+ var type = chunk.type === 'text-start' ? 'text' : 'reasoning';
13464
+ setPart(-1, {
13465
+ type: type,
13052
13466
  text: '',
13053
13467
  state: 'streaming',
13054
13468
  providerMetadata: chunk.providerMetadata
13055
- };
13056
- currentMessage = _object_spread_props(_object_spread({}, currentMessage), {
13057
- parts: _to_consumable_array(currentMessage.parts).concat([
13058
- textPart
13059
- ])
13060
13469
  });
13061
- _this.state.replaceMessage(currentMessageIndex, currentMessage);
13062
13470
  break;
13063
13471
  }
13064
13472
  case 'text-delta':
13473
+ case 'reasoning-delta':
13065
13474
  {
13066
- if (!currentMessage || !currentTextPartId) break;
13067
- var partIndex = currentMessage.parts.findIndex(function(p) {
13068
- return p.type === 'text' && p.state === 'streaming';
13475
+ var type1 = chunk.type === 'text-delta' ? 'text' : 'reasoning';
13476
+ if (!currentMessage) break;
13477
+ var partIndex = currentMessage.parts.findIndex(function(part) {
13478
+ return part.type === type1 && part.state === 'streaming';
13069
13479
  });
13070
13480
  if (partIndex === -1) break;
13071
- var updatedParts = _to_consumable_array(currentMessage.parts);
13072
- var textPart1 = updatedParts[partIndex];
13073
- updatedParts[partIndex] = _object_spread_props(_object_spread({}, textPart1), {
13074
- text: textPart1.text + chunk.delta
13075
- });
13076
- currentMessage = _object_spread_props(_object_spread({}, currentMessage), {
13077
- parts: updatedParts
13078
- });
13079
- _this.state.replaceMessage(currentMessageIndex, currentMessage);
13481
+ var part = currentMessage.parts[partIndex];
13482
+ setPart(partIndex, _object_spread_props(_object_spread({}, part), {
13483
+ text: part.text + chunk.delta
13484
+ }));
13080
13485
  break;
13081
13486
  }
13082
13487
  case 'text-end':
13083
- {
13084
- if (!currentMessage) break;
13085
- var partIndex1 = currentMessage.parts.findIndex(function(p) {
13086
- return p.type === 'text' && p.state === 'streaming';
13087
- });
13088
- if (partIndex1 === -1) break;
13089
- var updatedParts1 = _to_consumable_array(currentMessage.parts);
13090
- var textPart2 = updatedParts1[partIndex1];
13091
- updatedParts1[partIndex1] = _object_spread_props(_object_spread({}, textPart2), {
13092
- state: 'done'
13093
- });
13094
- currentMessage = _object_spread_props(_object_spread({}, currentMessage), {
13095
- parts: updatedParts1
13096
- });
13097
- _this.state.replaceMessage(currentMessageIndex, currentMessage);
13098
- currentTextPartId = undefined;
13099
- break;
13100
- }
13101
- case 'reasoning-start':
13102
- {
13103
- if (!currentMessage) break;
13104
- currentReasoningPartId = chunk.id;
13105
- var reasoningPart = {
13106
- type: 'reasoning',
13107
- text: '',
13108
- state: 'streaming',
13109
- providerMetadata: chunk.providerMetadata
13110
- };
13111
- currentMessage = _object_spread_props(_object_spread({}, currentMessage), {
13112
- parts: _to_consumable_array(currentMessage.parts).concat([
13113
- reasoningPart
13114
- ])
13115
- });
13116
- _this.state.replaceMessage(currentMessageIndex, currentMessage);
13117
- break;
13118
- }
13119
- case 'reasoning-delta':
13120
- {
13121
- if (!currentMessage || !currentReasoningPartId) break;
13122
- var partIndex2 = currentMessage.parts.findIndex(function(p) {
13123
- return p.type === 'reasoning' && p.state === 'streaming';
13124
- });
13125
- if (partIndex2 === -1) break;
13126
- var updatedParts2 = _to_consumable_array(currentMessage.parts);
13127
- var reasoningPart1 = updatedParts2[partIndex2];
13128
- updatedParts2[partIndex2] = _object_spread_props(_object_spread({}, reasoningPart1), {
13129
- text: reasoningPart1.text + chunk.delta
13130
- });
13131
- currentMessage = _object_spread_props(_object_spread({}, currentMessage), {
13132
- parts: updatedParts2
13133
- });
13134
- _this.state.replaceMessage(currentMessageIndex, currentMessage);
13135
- break;
13136
- }
13137
13488
  case 'reasoning-end':
13138
13489
  {
13139
13490
  if (!currentMessage) break;
13140
- var partIndex3 = currentMessage.parts.findIndex(function(p) {
13141
- return p.type === 'reasoning' && p.state === 'streaming';
13491
+ var type2 = chunk.type === 'text-end' ? 'text' : 'reasoning';
13492
+ var partIndex1 = currentMessage.parts.findIndex(function(part) {
13493
+ return part.type === type2 && part.state === 'streaming';
13142
13494
  });
13143
- if (partIndex3 === -1) break;
13144
- var updatedParts3 = _to_consumable_array(currentMessage.parts);
13145
- var reasoningPart2 = updatedParts3[partIndex3];
13146
- updatedParts3[partIndex3] = _object_spread_props(_object_spread({}, reasoningPart2), {
13495
+ if (partIndex1 === -1) break;
13496
+ setPart(partIndex1, _object_spread_props(_object_spread({}, currentMessage.parts[partIndex1]), {
13147
13497
  state: 'done'
13148
- });
13149
- currentMessage = _object_spread_props(_object_spread({}, currentMessage), {
13150
- parts: updatedParts3
13151
- });
13152
- _this.state.replaceMessage(currentMessageIndex, currentMessage);
13153
- currentReasoningPartId = undefined;
13498
+ }));
13154
13499
  break;
13155
13500
  }
13156
13501
  case 'tool-input-start':
13157
13502
  {
13158
13503
  if (!currentMessage) break;
13504
+ var completedPart = currentMessage.parts.find(function(part) {
13505
+ return 'toolCallId' in part && part.toolCallId === chunk.toolCallId && 'state' in part && (part.state === 'output-available' || part.state === 'output-error');
13506
+ });
13507
+ if (completedPart) break;
13159
13508
  var initialRawInput = typeof chunk.input === 'string' ? chunk.input : chunk.input !== undefined ? JSON.stringify(chunk.input) : '';
13160
13509
  toolRawInputByCallId[chunk.toolCallId] = initialRawInput;
13161
13510
  var toolPart = {
@@ -13166,12 +13515,7 @@
13166
13515
  rawInput: initialRawInput || undefined,
13167
13516
  providerExecuted: chunk.providerExecuted
13168
13517
  };
13169
- currentMessage = _object_spread_props(_object_spread({}, currentMessage), {
13170
- parts: _to_consumable_array(currentMessage.parts).concat([
13171
- toolPart
13172
- ])
13173
- });
13174
- _this.state.replaceMessage(currentMessageIndex, currentMessage);
13518
+ setPart(-1, toolPart);
13175
13519
  break;
13176
13520
  }
13177
13521
  case 'tool-input-delta':
@@ -13179,10 +13523,11 @@
13179
13523
  var _ref, _ref1, _chunk_toolName, _ref2;
13180
13524
  var _existingPart_type, _this_shouldRepairToolInput, _this1;
13181
13525
  if (!currentMessage) break;
13182
- var toolIndex = currentMessage.parts.findIndex(function(p) {
13183
- return 'toolCallId' in p && p.toolCallId === chunk.toolCallId;
13184
- });
13526
+ var toolIndex = findToolPart(chunk.toolCallId);
13185
13527
  var existingPart = toolIndex >= 0 ? currentMessage.parts[toolIndex] : null;
13528
+ if ((existingPart === null || existingPart === void 0 ? void 0 : existingPart.state) === 'output-available' || (existingPart === null || existingPart === void 0 ? void 0 : existingPart.state) === 'output-error') {
13529
+ break;
13530
+ }
13186
13531
  var previousRawInput = (_ref = (_ref1 = existingPart === null || existingPart === void 0 ? void 0 : existingPart.rawInput) !== null && _ref1 !== void 0 ? _ref1 : toolRawInputByCallId[chunk.toolCallId]) !== null && _ref !== void 0 ? _ref : '';
13187
13532
  var nextRawInput = "".concat(previousRawInput).concat(chunk.inputTextDelta);
13188
13533
  toolRawInputByCallId[chunk.toolCallId] = nextRawInput;
@@ -13197,30 +13542,20 @@
13197
13542
  input: parsedInput,
13198
13543
  rawInput: nextRawInput
13199
13544
  });
13200
- if (toolIndex >= 0) {
13201
- var updatedParts4 = _to_consumable_array(currentMessage.parts);
13202
- updatedParts4[toolIndex] = nextToolPart;
13203
- currentMessage = _object_spread_props(_object_spread({}, currentMessage), {
13204
- parts: updatedParts4
13205
- });
13206
- } else {
13207
- currentMessage = _object_spread_props(_object_spread({}, currentMessage), {
13208
- parts: _to_consumable_array(currentMessage.parts).concat([
13209
- nextToolPart
13210
- ])
13211
- });
13212
- }
13213
- _this.state.replaceMessage(currentMessageIndex, currentMessage);
13545
+ setPart(toolIndex, nextToolPart);
13214
13546
  break;
13215
13547
  }
13216
13548
  case 'tool-input-available':
13217
13549
  {
13218
13550
  if (!currentMessage) break;
13551
+ if (response.requiredToolCallIds.has(chunk.toolCallId)) break;
13219
13552
  delete toolRawInputByCallId[chunk.toolCallId];
13220
13553
  // Find existing tool part or create new one
13221
- var existingIndex = currentMessage.parts.findIndex(function(p) {
13222
- return 'toolCallId' in p && p.toolCallId === chunk.toolCallId;
13223
- });
13554
+ var existingIndex = findToolPart(chunk.toolCallId);
13555
+ var existingPart1 = existingIndex >= 0 ? currentMessage.parts[existingIndex] : null;
13556
+ if ((existingPart1 === null || existingPart1 === void 0 ? void 0 : existingPart1.state) === 'output-available' || (existingPart1 === null || existingPart1 === void 0 ? void 0 : existingPart1.state) === 'output-error') {
13557
+ break;
13558
+ }
13224
13559
  var toolPart1 = {
13225
13560
  type: "tool-".concat(chunk.toolName),
13226
13561
  toolCallId: chunk.toolCallId,
@@ -13229,35 +13564,63 @@
13229
13564
  callProviderMetadata: chunk.callProviderMetadata,
13230
13565
  providerExecuted: chunk.providerExecuted
13231
13566
  };
13232
- if (existingIndex >= 0) {
13233
- var updatedParts5 = _to_consumable_array(currentMessage.parts);
13234
- updatedParts5[existingIndex] = toolPart1;
13235
- currentMessage = _object_spread_props(_object_spread({}, currentMessage), {
13236
- parts: updatedParts5
13237
- });
13238
- } else {
13239
- currentMessage = _object_spread_props(_object_spread({}, currentMessage), {
13240
- parts: _to_consumable_array(currentMessage.parts).concat([
13241
- toolPart1
13242
- ])
13243
- });
13567
+ setPart(existingIndex, toolPart1);
13568
+ if (_this.messages.some(function(message) {
13569
+ var _message_parts;
13570
+ return message !== currentMessage && ((_message_parts = message.parts) === null || _message_parts === void 0 ? void 0 : _message_parts.some(function(part) {
13571
+ return 'toolCallId' in part && part.toolCallId === chunk.toolCallId;
13572
+ }));
13573
+ })) {
13574
+ _this.acceptsIdentifierOnlyToolResults = false;
13244
13575
  }
13245
- _this.state.replaceMessage(currentMessageIndex, currentMessage);
13246
13576
  // Trigger onToolCall callback only for client-executed tools
13247
13577
  // (server-executed tools have providerExecuted: true and don't need client handling)
13248
13578
  if (_this.onToolCall && !chunk.providerExecuted) {
13249
- var result = _this.onToolCall({
13250
- toolCall: {
13251
- toolName: chunk.toolName,
13252
- toolCallId: chunk.toolCallId,
13253
- input: chunk.input,
13254
- dynamic: 'dynamic' in chunk ? chunk.dynamic : undefined
13255
- }
13579
+ var _this_responsesByToolCallId_get;
13580
+ var owners = (_this_responsesByToolCallId_get = _this.responsesByToolCallId.get(chunk.toolCallId)) !== null && _this_responsesByToolCallId_get !== void 0 ? _this_responsesByToolCallId_get : new Set();
13581
+ var existingOwners = Array.from(owners).filter(function(owner) {
13582
+ return owner !== response;
13256
13583
  });
13257
- if (result && typeof result.then === 'function') {
13258
- pendingToolCall = pendingToolCall.then(function() {
13259
- return result;
13584
+ if (existingOwners.length > 0) {
13585
+ _this.acceptsIdentifierOnlyToolResults = false;
13586
+ var conflictingOwner = existingOwners.find(function(owner) {
13587
+ return !owner.isRetired && (owner.outcome === 'active' || owner.outcome === 'succeeded' && (!owner.resolvedToolCallIds.has(chunk.toolCallId) || owner.pendingToolCallbacks > 0));
13588
+ });
13589
+ if (conflictingOwner) {
13590
+ // Neither response may continue once ownership is ambiguous.
13591
+ conflictingOwner.didEvaluateContinuation = true;
13592
+ failToolCall(new Error('Tool call "'.concat(chunk.toolCallId, '" is already owned by another response.')));
13593
+ break;
13594
+ }
13595
+ }
13596
+ response.requiredToolCallIds.add(chunk.toolCallId);
13597
+ owners.add(response);
13598
+ _this.responsesByToolCallId.set(chunk.toolCallId, owners);
13599
+ response.pendingToolCallbacks++;
13600
+ try {
13601
+ var result = _this.onToolCall({
13602
+ toolCall: {
13603
+ toolName: chunk.toolName,
13604
+ toolCallId: chunk.toolCallId,
13605
+ input: chunk.input,
13606
+ dynamic: 'dynamic' in chunk ? chunk.dynamic : undefined
13607
+ }
13608
+ }, function(options) {
13609
+ return response.isRetired ? Promise.resolve() : _this.submitToolResult(response, options);
13260
13610
  });
13611
+ if (result) {
13612
+ response.returnedToolCallbacks.push(Promise.resolve(result).catch(failToolCall).then(function() {
13613
+ response.pendingToolCallbacks--;
13614
+ _this.pruneDetachedResponse(response);
13615
+ }));
13616
+ } else {
13617
+ response.pendingToolCallbacks--;
13618
+ _this.pruneDetachedResponse(response);
13619
+ }
13620
+ } catch (error) {
13621
+ response.pendingToolCallbacks--;
13622
+ failToolCall(error);
13623
+ _this.pruneDetachedResponse(response);
13261
13624
  }
13262
13625
  }
13263
13626
  break;
@@ -13267,15 +13630,14 @@
13267
13630
  var _ref3, _ref4;
13268
13631
  if (!currentMessage) break;
13269
13632
  var _chunk_data = chunk.data, toolCallId = _chunk_data.toolCallId, toolName1 = _chunk_data.toolName, delta = _chunk_data.delta;
13270
- var toolIndex1 = currentMessage.parts.findIndex(function(p) {
13271
- return 'toolCallId' in p && p.toolCallId === toolCallId;
13272
- });
13273
- var existingPart1 = toolIndex1 >= 0 ? currentMessage.parts[toolIndex1] : null;
13274
- var previousRawOutput = (_ref3 = (_ref4 = existingPart1 === null || existingPart1 === void 0 ? void 0 : existingPart1.rawOutput) !== null && _ref4 !== void 0 ? _ref4 : toolRawOutputByCallId[toolCallId]) !== null && _ref3 !== void 0 ? _ref3 : '';
13633
+ if (response.resolvedToolCallIds.has(toolCallId)) break;
13634
+ var toolIndex1 = findToolPart(toolCallId);
13635
+ var existingPart2 = toolIndex1 >= 0 ? currentMessage.parts[toolIndex1] : null;
13636
+ var previousRawOutput = (_ref3 = (_ref4 = existingPart2 === null || existingPart2 === void 0 ? void 0 : existingPart2.rawOutput) !== null && _ref4 !== void 0 ? _ref4 : toolRawOutputByCallId[toolCallId]) !== null && _ref3 !== void 0 ? _ref3 : '';
13275
13637
  var nextRawOutput = "".concat(previousRawOutput).concat(delta);
13276
13638
  toolRawOutputByCallId[toolCallId] = nextRawOutput;
13277
- var parsedOutput = parseToolInputDelta(nextRawOutput, existingPart1 === null || existingPart1 === void 0 ? void 0 : existingPart1.output);
13278
- var nextToolPart1 = _object_spread_props(_object_spread({}, existingPart1 !== null && existingPart1 !== void 0 ? existingPart1 : {
13639
+ var parsedOutput = parseToolInputDelta(nextRawOutput, existingPart2 === null || existingPart2 === void 0 ? void 0 : existingPart2.output);
13640
+ var nextToolPart1 = _object_spread_props(_object_spread({}, existingPart2 !== null && existingPart2 !== void 0 ? existingPart2 : {
13279
13641
  type: "tool-".concat(toolName1),
13280
13642
  toolCallId: toolCallId,
13281
13643
  input: undefined
@@ -13285,47 +13647,34 @@
13285
13647
  rawOutput: nextRawOutput,
13286
13648
  preliminary: true
13287
13649
  });
13288
- if (toolIndex1 >= 0) {
13289
- var updatedParts6 = _to_consumable_array(currentMessage.parts);
13290
- updatedParts6[toolIndex1] = nextToolPart1;
13291
- currentMessage = _object_spread_props(_object_spread({}, currentMessage), {
13292
- parts: updatedParts6
13293
- });
13294
- } else {
13295
- currentMessage = _object_spread_props(_object_spread({}, currentMessage), {
13296
- parts: _to_consumable_array(currentMessage.parts).concat([
13297
- nextToolPart1
13298
- ])
13299
- });
13300
- }
13301
- _this.state.replaceMessage(currentMessageIndex, currentMessage);
13650
+ setPart(toolIndex1, nextToolPart1);
13302
13651
  break;
13303
13652
  }
13304
13653
  case 'tool-output-available':
13305
13654
  {
13306
13655
  if (!currentMessage) break;
13307
- var toolIndex2 = currentMessage.parts.findIndex(function(p) {
13308
- return 'toolCallId' in p && p.toolCallId === chunk.toolCallId;
13309
- });
13656
+ var toolIndex2 = findToolPart(chunk.toolCallId);
13310
13657
  if (toolIndex2 >= 0) {
13311
13658
  delete toolRawInputByCallId[chunk.toolCallId];
13312
13659
  delete toolRawOutputByCallId[chunk.toolCallId];
13313
- var updatedParts7 = _to_consumable_array(currentMessage.parts);
13314
- var existingPart2 = updatedParts7[toolIndex2];
13660
+ var existingPart3 = currentMessage.parts[toolIndex2];
13661
+ if (response.resolvedToolCallIds.has(chunk.toolCallId)) {
13662
+ mergeCallProviderMetadata(chunk.toolCallId, chunk.callProviderMetadata);
13663
+ break;
13664
+ }
13315
13665
  // eslint-disable-next-line no-unused-vars, @typescript-eslint/no-unused-vars
13316
- var _ignored = existingPart2.rawOutput, rest = _object_without_properties(existingPart2, [
13666
+ var _ignored = existingPart3.rawOutput, rest = _object_without_properties(existingPart3, [
13317
13667
  "rawOutput"
13318
13668
  ]);
13319
- updatedParts7[toolIndex2] = _object_spread_props(_object_spread({}, rest), {
13669
+ setPart(toolIndex2, _object_spread_props(_object_spread({}, rest), {
13320
13670
  state: 'output-available',
13321
13671
  output: chunk.output,
13322
13672
  callProviderMetadata: chunk.callProviderMetadata,
13323
13673
  preliminary: chunk.preliminary
13324
- });
13325
- currentMessage = _object_spread_props(_object_spread({}, currentMessage), {
13326
- parts: updatedParts7
13327
- });
13328
- _this.state.replaceMessage(currentMessageIndex, currentMessage);
13674
+ }));
13675
+ if (!chunk.preliminary) {
13676
+ acceptServerToolResult(chunk.toolCallId);
13677
+ }
13329
13678
  }
13330
13679
  break;
13331
13680
  }
@@ -13333,13 +13682,15 @@
13333
13682
  {
13334
13683
  var _chunk_input, _chunk_providerExecuted, _chunk_providerMetadata;
13335
13684
  if (!currentMessage) break;
13685
+ if (response.resolvedToolCallIds.has(chunk.toolCallId)) {
13686
+ mergeCallProviderMetadata(chunk.toolCallId, chunk.providerMetadata);
13687
+ break;
13688
+ }
13336
13689
  delete toolRawInputByCallId[chunk.toolCallId];
13337
13690
  delete toolRawOutputByCallId[chunk.toolCallId];
13338
- var toolIndex3 = currentMessage.parts.findIndex(function(p) {
13339
- return 'toolCallId' in p && p.toolCallId === chunk.toolCallId;
13340
- });
13341
- var existingPart3 = toolIndex3 >= 0 ? currentMessage.parts[toolIndex3] : null;
13342
- var _ref5 = existingPart3 !== null && existingPart3 !== void 0 ? existingPart3 : {}, _ignoredOutput = _ref5.output, _ignoredRawOutput = _ref5.rawOutput, _ignoredPreliminary = _ref5.preliminary, carryOver = _object_without_properties(_ref5, [
13691
+ var toolIndex3 = findToolPart(chunk.toolCallId);
13692
+ var existingPart4 = toolIndex3 >= 0 ? currentMessage.parts[toolIndex3] : null;
13693
+ var _ref5 = existingPart4 !== null && existingPart4 !== void 0 ? existingPart4 : {}, _ignoredOutput = _ref5.output, _ignoredRawOutput = _ref5.rawOutput, _ignoredPreliminary = _ref5.preliminary, carryOver = _object_without_properties(_ref5, [
13343
13694
  "output",
13344
13695
  "rawOutput",
13345
13696
  "preliminary"
@@ -13354,49 +13705,35 @@
13354
13705
  providerExecuted: (_chunk_providerExecuted = chunk.providerExecuted) !== null && _chunk_providerExecuted !== void 0 ? _chunk_providerExecuted : carryOver.providerExecuted,
13355
13706
  callProviderMetadata: (_chunk_providerMetadata = chunk.providerMetadata) !== null && _chunk_providerMetadata !== void 0 ? _chunk_providerMetadata : carryOver.callProviderMetadata
13356
13707
  });
13357
- if (toolIndex3 >= 0) {
13358
- var updatedParts8 = _to_consumable_array(currentMessage.parts);
13359
- updatedParts8[toolIndex3] = nextToolPart2;
13360
- currentMessage = _object_spread_props(_object_spread({}, currentMessage), {
13361
- parts: updatedParts8
13362
- });
13363
- } else {
13364
- currentMessage = _object_spread_props(_object_spread({}, currentMessage), {
13365
- parts: _to_consumable_array(currentMessage.parts).concat([
13366
- nextToolPart2
13367
- ])
13368
- });
13369
- }
13370
- _this.state.replaceMessage(currentMessageIndex, currentMessage);
13708
+ setPart(toolIndex3, nextToolPart2);
13709
+ acceptServerToolResult(chunk.toolCallId);
13371
13710
  break;
13372
13711
  }
13373
13712
  case 'tool-output-error':
13374
13713
  {
13375
13714
  var _chunk_providerExecuted1, _chunk_providerMetadata1;
13376
13715
  if (!currentMessage) break;
13377
- var toolIndex4 = currentMessage.parts.findIndex(function(p) {
13378
- return 'toolCallId' in p && p.toolCallId === chunk.toolCallId;
13379
- });
13716
+ if (response.resolvedToolCallIds.has(chunk.toolCallId)) {
13717
+ mergeCallProviderMetadata(chunk.toolCallId, chunk.providerMetadata);
13718
+ break;
13719
+ }
13720
+ var toolIndex4 = findToolPart(chunk.toolCallId);
13380
13721
  if (toolIndex4 < 0) break;
13381
13722
  delete toolRawInputByCallId[chunk.toolCallId];
13382
13723
  delete toolRawOutputByCallId[chunk.toolCallId];
13383
- var updatedParts9 = _to_consumable_array(currentMessage.parts);
13384
- var existingPart4 = updatedParts9[toolIndex4];
13385
- var _ignoredRawOutput1 = existingPart4.rawOutput, _ignoredPreliminary1 = existingPart4.preliminary, _ignoredOutput1 = existingPart4.output, rest1 = _object_without_properties(existingPart4, [
13724
+ var existingPart5 = currentMessage.parts[toolIndex4];
13725
+ var _ignoredRawOutput1 = existingPart5.rawOutput, _ignoredPreliminary1 = existingPart5.preliminary, _ignoredOutput1 = existingPart5.output, rest1 = _object_without_properties(existingPart5, [
13386
13726
  "rawOutput",
13387
13727
  "preliminary",
13388
13728
  "output"
13389
13729
  ]);
13390
- updatedParts9[toolIndex4] = _object_spread_props(_object_spread({}, rest1), {
13730
+ setPart(toolIndex4, _object_spread_props(_object_spread({}, rest1), {
13391
13731
  state: 'output-error',
13392
13732
  errorText: chunk.errorText,
13393
13733
  providerExecuted: (_chunk_providerExecuted1 = chunk.providerExecuted) !== null && _chunk_providerExecuted1 !== void 0 ? _chunk_providerExecuted1 : rest1.providerExecuted,
13394
13734
  callProviderMetadata: (_chunk_providerMetadata1 = chunk.providerMetadata) !== null && _chunk_providerMetadata1 !== void 0 ? _chunk_providerMetadata1 : rest1.callProviderMetadata
13395
- });
13396
- currentMessage = _object_spread_props(_object_spread({}, currentMessage), {
13397
- parts: updatedParts9
13398
- });
13399
- _this.state.replaceMessage(currentMessageIndex, currentMessage);
13735
+ }));
13736
+ acceptServerToolResult(chunk.toolCallId);
13400
13737
  break;
13401
13738
  }
13402
13739
  case 'source-url':
@@ -13408,12 +13745,7 @@
13408
13745
  url: chunk.url,
13409
13746
  title: chunk.title
13410
13747
  };
13411
- currentMessage = _object_spread_props(_object_spread({}, currentMessage), {
13412
- parts: _to_consumable_array(currentMessage.parts).concat([
13413
- sourcePart
13414
- ])
13415
- });
13416
- _this.state.replaceMessage(currentMessageIndex, currentMessage);
13748
+ setPart(-1, sourcePart);
13417
13749
  break;
13418
13750
  }
13419
13751
  case 'source-document':
@@ -13427,12 +13759,7 @@
13427
13759
  filename: chunk.filename,
13428
13760
  providerMetadata: chunk.providerMetadata
13429
13761
  };
13430
- currentMessage = _object_spread_props(_object_spread({}, currentMessage), {
13431
- parts: _to_consumable_array(currentMessage.parts).concat([
13432
- docPart
13433
- ])
13434
- });
13435
- _this.state.replaceMessage(currentMessageIndex, currentMessage);
13762
+ setPart(-1, docPart);
13436
13763
  break;
13437
13764
  }
13438
13765
  case 'file':
@@ -13443,26 +13770,15 @@
13443
13770
  url: chunk.url,
13444
13771
  mediaType: chunk.mediaType
13445
13772
  };
13446
- currentMessage = _object_spread_props(_object_spread({}, currentMessage), {
13447
- parts: _to_consumable_array(currentMessage.parts).concat([
13448
- filePart
13449
- ])
13450
- });
13451
- _this.state.replaceMessage(currentMessageIndex, currentMessage);
13773
+ setPart(-1, filePart);
13452
13774
  break;
13453
13775
  }
13454
13776
  case 'start-step':
13455
13777
  {
13456
13778
  if (!currentMessage) break;
13457
- var stepPart = {
13779
+ setPart(-1, {
13458
13780
  type: 'step-start'
13459
- };
13460
- currentMessage = _object_spread_props(_object_spread({}, currentMessage), {
13461
- parts: _to_consumable_array(currentMessage.parts).concat([
13462
- stepPart
13463
- ])
13464
13781
  });
13465
- _this.state.replaceMessage(currentMessageIndex, currentMessage);
13466
13782
  break;
13467
13783
  }
13468
13784
  case 'message-metadata':
@@ -13471,7 +13787,7 @@
13471
13787
  currentMessage = _object_spread_props(_object_spread({}, currentMessage), {
13472
13788
  metadata: chunk.messageMetadata
13473
13789
  });
13474
- _this.state.replaceMessage(currentMessageIndex, currentMessage);
13790
+ currentMessage = _this.replaceMessage(currentMessageIndex, currentMessage, response);
13475
13791
  break;
13476
13792
  }
13477
13793
  case 'error':
@@ -13491,7 +13807,7 @@
13491
13807
  currentMessage = _object_spread_props(_object_spread({}, currentMessage), {
13492
13808
  metadata: chunk.messageMetadata
13493
13809
  });
13494
- _this.state.replaceMessage(currentMessageIndex, currentMessage);
13810
+ currentMessage = _this.replaceMessage(currentMessageIndex, currentMessage, response);
13495
13811
  }
13496
13812
  break;
13497
13813
  }
@@ -13517,14 +13833,13 @@
13517
13833
  ]
13518
13834
  };
13519
13835
  if (currentMessageIndex >= 0) {
13520
- _this.state.replaceMessage(currentMessageIndex, currentMessage);
13836
+ currentMessage = _this.replaceMessage(currentMessageIndex, currentMessage, response);
13521
13837
  } else {
13522
13838
  _this.state.pushMessage(currentMessage);
13523
- currentMessageIndex = _this.state.messages.length - 1;
13839
+ currentMessageIndex = _this.messages.length - 1;
13840
+ _this.responseByMessage.set(currentMessage, response);
13524
13841
  }
13525
13842
  currentMessageId = currentMessage.id;
13526
- currentTextPartId = undefined;
13527
- currentReasoningPartId = undefined;
13528
13843
  break;
13529
13844
  }
13530
13845
  default:
@@ -13537,12 +13852,7 @@
13537
13852
  id: chunk.id,
13538
13853
  data: chunk.data
13539
13854
  };
13540
- currentMessage = _object_spread_props(_object_spread({}, currentMessage), {
13541
- parts: _to_consumable_array(currentMessage.parts).concat([
13542
- dataPart
13543
- ])
13544
- });
13545
- _this.state.replaceMessage(currentMessageIndex, currentMessage);
13855
+ setPart(-1, dataPart);
13546
13856
  // Trigger onData callback
13547
13857
  if (_this.onData) {
13548
13858
  _this.onData(dataPart);
@@ -13551,49 +13861,11 @@
13551
13861
  }
13552
13862
  }
13553
13863
  }, function() {
13554
- // Wait for any pending tool calls to complete
13555
- pendingToolCall.then(function() {
13556
- // Stream finished successfully
13557
- _this.setStatus({
13558
- status: 'ready'
13559
- });
13560
- _this.activeResponse = null;
13561
- // Trigger onFinish callback
13562
- if (_this.onFinish && currentMessage) {
13563
- _this.onFinish({
13564
- message: currentMessage,
13565
- messages: _this.state.messages,
13566
- isAbort: isAbort,
13567
- isDisconnect: isDisconnect,
13568
- isError: isError
13569
- });
13570
- }
13571
- // Note: sendAutomaticallyWhen is only checked in addToolResult,
13572
- // not here. For server-executed tools, the server continues the
13573
- // conversation. For client-executed tools, addToolResult handles it.
13574
- resolve();
13864
+ return Promise.all(response.returnedToolCallbacks).then(function() {
13865
+ return finish();
13575
13866
  });
13576
13867
  }, function(error) {
13577
- if (error.name === 'AbortError') {
13578
- isAbort = true;
13579
- _this.setStatus({
13580
- status: 'ready'
13581
- });
13582
- } else {
13583
- isDisconnect = true;
13584
- _this.handleError(error);
13585
- }
13586
- // Still call onFinish even on error/abort
13587
- if (_this.onFinish && currentMessage) {
13588
- _this.onFinish({
13589
- message: currentMessage,
13590
- messages: _this.state.messages,
13591
- isAbort: isAbort,
13592
- isDisconnect: isDisconnect,
13593
- isError: isError
13594
- });
13595
- }
13596
- resolve();
13868
+ return finish(error);
13597
13869
  });
13598
13870
  });
13599
13871
  }
@@ -13601,10 +13873,13 @@
13601
13873
  {
13602
13874
  key: "handleError",
13603
13875
  value: function handleError(error) {
13604
- this.setStatus({
13605
- status: 'error',
13606
- error: error
13607
- });
13876
+ var _ref = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {}, _ref_updateState = _ref.updateState, updateState = _ref_updateState === void 0 ? true : _ref_updateState;
13877
+ if (updateState) {
13878
+ this.setStatus({
13879
+ status: 'error',
13880
+ error: error
13881
+ });
13882
+ }
13608
13883
  if (this.onError) {
13609
13884
  this.onError(error);
13610
13885
  }
@@ -14097,14 +14372,16 @@
14097
14372
  var unmountFn = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : noop;
14098
14373
  checkRendering(renderFn, withUsage$o());
14099
14374
  return function(widgetParams) {
14100
- var _ref = widgetParams || {}, _ref_resume = _ref.resume, resume = _ref_resume === void 0 ? false : _ref_resume, _ref_tools = _ref.tools, tools = _ref_tools === void 0 ? {} : _ref_tools, _ref_type = _ref.type, type = _ref_type === void 0 ? 'chat' : _ref_type, context = _ref.context, initialUserMessage = _ref.initialUserMessage, initialMessages = _ref.initialMessages, _ref_disableTriggerValidation = _ref.disableTriggerValidation, disableTriggerValidation = _ref_disableTriggerValidation === void 0 ? false : _ref_disableTriggerValidation, options = _object_without_properties(_ref, [
14375
+ var _ref = widgetParams || {}, _ref_resume = _ref.resume, resume = _ref_resume === void 0 ? false : _ref_resume, _ref_tools = _ref.tools, tools = _ref_tools === void 0 ? {} : _ref_tools, _ref_type = _ref.type, type = _ref_type === void 0 ? 'chat' : _ref_type, context = _ref.context, initialUserMessage = _ref.initialUserMessage, initialMessages = _ref.initialMessages, _ref_disableTriggerValidation = _ref.disableTriggerValidation, disableTriggerValidation = _ref_disableTriggerValidation === void 0 ? false : _ref_disableTriggerValidation, _ref_sendAutomaticallyWhen = _ref.sendAutomaticallyWhen, sendAutomaticallyWhen = _ref_sendAutomaticallyWhen === void 0 ? lastAssistantMessageIsCompleteWithToolCalls : _ref_sendAutomaticallyWhen, _ref_requiresSearch = _ref.requiresSearch, requiresSearch = _ref_requiresSearch === void 0 ? true : _ref_requiresSearch, options = _object_without_properties(_ref, [
14101
14376
  "resume",
14102
14377
  "tools",
14103
14378
  "type",
14104
14379
  "context",
14105
14380
  "initialUserMessage",
14106
14381
  "initialMessages",
14107
- "disableTriggerValidation"
14382
+ "disableTriggerValidation",
14383
+ "sendAutomaticallyWhen",
14384
+ "requiresSearch"
14108
14385
  ]);
14109
14386
  var _chatInstance;
14110
14387
  var input = '';
@@ -14265,8 +14542,8 @@
14265
14542
  return options.chat;
14266
14543
  }
14267
14544
  return new Chat$1(_object_spread_props(_object_spread({}, options), {
14545
+ sendAutomaticallyWhen: sendAutomaticallyWhen,
14268
14546
  transport: transport,
14269
- sendAutomaticallyWhen: lastAssistantMessageIsCompleteWithToolCalls,
14270
14547
  shouldRepairToolInput: function shouldRepairToolInput(toolName) {
14271
14548
  var tool = tools[toolName];
14272
14549
  if (!tool && toolName.startsWith("".concat(SearchIndexToolType$2, "_"))) {
@@ -14275,7 +14552,7 @@
14275
14552
  if (!tool) return true;
14276
14553
  return Boolean(tool.streamInput);
14277
14554
  },
14278
- onToolCall: function onToolCall(param) {
14555
+ onToolCall: function onToolCall(param, submitToolResult) {
14279
14556
  var toolCall = param.toolCall;
14280
14557
  var tool = tools[toolCall.toolName];
14281
14558
  // Compatibility shim with Algolia MCP Server search tool
@@ -14283,7 +14560,7 @@
14283
14560
  tool = tools[SearchIndexToolType$2];
14284
14561
  }
14285
14562
  if (!tool) {
14286
- return _chatInstance.addToolResult({
14563
+ return submitToolResult({
14287
14564
  output: 'No tool implemented for "'.concat(toolCall.toolName, '".'),
14288
14565
  tool: toolCall.toolName,
14289
14566
  toolCallId: toolCall.toolCallId
@@ -14292,7 +14569,7 @@
14292
14569
  if (tool.onToolCall) {
14293
14570
  var addToolResult = function addToolResult(param) {
14294
14571
  var output = param.output;
14295
- return _chatInstance.addToolResult({
14572
+ return submitToolResult({
14296
14573
  output: output,
14297
14574
  tool: toolCall.toolName,
14298
14575
  toolCallId: toolCall.toolCallId
@@ -14308,6 +14585,7 @@
14308
14585
  };
14309
14586
  return {
14310
14587
  $$type: 'ais.chat',
14588
+ dependsOn: requiresSearch ? 'search' : 'none',
14311
14589
  init: function init(initOptions) {
14312
14590
  var _this = this;
14313
14591
  var instantSearchInstance = initOptions.instantSearchInstance;
@@ -14413,6 +14691,7 @@
14413
14691
  var _param = _sliced_to_array(param, 2), key = _param[0], tool = _param[1];
14414
14692
  var toolWithAddToolResult = _object_spread_props(_object_spread({}, tool), {
14415
14693
  addToolResult: _chatInstance.addToolResult,
14694
+ '~addToolResultForMessage': _chatInstance['~addToolResultForMessage'],
14416
14695
  applyFilters: applyFilters,
14417
14696
  sendEvent: sendEvent
14418
14697
  });
@@ -14520,6 +14799,7 @@
14520
14799
  return {
14521
14800
  $$type: 'ais.chatTrigger',
14522
14801
  opensChat: true,
14802
+ dependsOn: 'none',
14523
14803
  init: function init(initOptions) {
14524
14804
  lastOptions = initOptions;
14525
14805
  renderFn(_object_spread_props(_object_spread({}, this.getWidgetRenderState(initOptions)), {
@@ -14548,6 +14828,9 @@
14548
14828
  return _object_spread_props(_object_spread({}, renderState), {
14549
14829
  chatTrigger: this.getWidgetRenderState(renderOptions)
14550
14830
  });
14831
+ },
14832
+ shouldRender: function shouldRender() {
14833
+ return true;
14551
14834
  }
14552
14835
  };
14553
14836
  };
@@ -14905,8 +15188,8 @@
14905
15188
  if (escapeHTML && results.hits.length > 0) {
14906
15189
  results.hits = escapeHits(results.hits);
14907
15190
  }
14908
- var itemsWithAbsolutePosition = addAbsolutePosition(results.hits, 0, 1);
14909
- var itemsWithAbsolutePositionAndQueryID = addQueryID(itemsWithAbsolutePosition, results.queryID);
15191
+ var itemsWithAbsolutePosition = addAbsolutePosition$1(results.hits, 0, 1);
15192
+ var itemsWithAbsolutePositionAndQueryID = addQueryID$1(itemsWithAbsolutePosition, results.queryID);
14910
15193
  var transformedItems = transformItems(itemsWithAbsolutePositionAndQueryID, {
14911
15194
  results: results
14912
15195
  });
@@ -15425,8 +15708,8 @@
15425
15708
  if (escapeHTML && results.hits.length > 0) {
15426
15709
  results.hits = escapeHits(results.hits);
15427
15710
  }
15428
- var hitsWithAbsolutePosition = addAbsolutePosition(results.hits, results.page, results.hitsPerPage);
15429
- var hitsWithAbsolutePositionAndQueryID = addQueryID(hitsWithAbsolutePosition, results.queryID);
15711
+ var hitsWithAbsolutePosition = addAbsolutePosition$1(results.hits, results.page, results.hitsPerPage);
15712
+ var hitsWithAbsolutePositionAndQueryID = addQueryID$1(hitsWithAbsolutePosition, results.queryID);
15430
15713
  var items = transformItems(hitsWithAbsolutePositionAndQueryID, {
15431
15714
  results: results
15432
15715
  });
@@ -15757,8 +16040,8 @@
15757
16040
  if (escapeHTML && results.hits.length > 0) {
15758
16041
  results.hits = escapeHits(results.hits);
15759
16042
  }
15760
- var hitsWithAbsolutePosition = addAbsolutePosition(results.hits, results.page, results.hitsPerPage);
15761
- var hitsWithAbsolutePositionAndQueryID = addQueryID(hitsWithAbsolutePosition, results.queryID);
16043
+ var hitsWithAbsolutePosition = addAbsolutePosition$1(results.hits, results.page, results.hitsPerPage);
16044
+ var hitsWithAbsolutePositionAndQueryID = addQueryID$1(hitsWithAbsolutePosition, results.queryID);
15762
16045
  var transformedHits = transformItems(hitsWithAbsolutePositionAndQueryID, {
15763
16046
  results: results
15764
16047
  });
@@ -17190,8 +17473,8 @@
17190
17473
  if (escapeHTML && results.hits.length > 0) {
17191
17474
  results.hits = escapeHits(results.hits);
17192
17475
  }
17193
- var itemsWithAbsolutePosition = addAbsolutePosition(results.hits, 0, 1);
17194
- var itemsWithAbsolutePositionAndQueryID = addQueryID(itemsWithAbsolutePosition, results.queryID);
17476
+ var itemsWithAbsolutePosition = addAbsolutePosition$1(results.hits, 0, 1);
17477
+ var itemsWithAbsolutePositionAndQueryID = addQueryID$1(itemsWithAbsolutePosition, results.queryID);
17195
17478
  var transformedItems = transformItems(itemsWithAbsolutePositionAndQueryID, {
17196
17479
  results: results
17197
17480
  });
@@ -17871,8 +18154,8 @@
17871
18154
  if (escapeHTML && results.hits.length > 0) {
17872
18155
  results.hits = escapeHits(results.hits);
17873
18156
  }
17874
- var itemsWithAbsolutePosition = addAbsolutePosition(results.hits, 0, 1);
17875
- var itemsWithAbsolutePositionAndQueryID = addQueryID(itemsWithAbsolutePosition, results.queryID);
18157
+ var itemsWithAbsolutePosition = addAbsolutePosition$1(results.hits, 0, 1);
18158
+ var itemsWithAbsolutePositionAndQueryID = addQueryID$1(itemsWithAbsolutePosition, results.queryID);
17876
18159
  var transformedItems = transformItems(itemsWithAbsolutePositionAndQueryID, {
17877
18160
  results: results
17878
18161
  });
@@ -18044,8 +18327,8 @@
18044
18327
  if (escapeHTML && results.hits.length > 0) {
18045
18328
  results.hits = escapeHits(results.hits);
18046
18329
  }
18047
- var itemsWithAbsolutePosition = addAbsolutePosition(results.hits, 0, 1);
18048
- var itemsWithAbsolutePositionAndQueryID = addQueryID(itemsWithAbsolutePosition, results.queryID);
18330
+ var itemsWithAbsolutePosition = addAbsolutePosition$1(results.hits, 0, 1);
18331
+ var itemsWithAbsolutePositionAndQueryID = addQueryID$1(itemsWithAbsolutePosition, results.queryID);
18049
18332
  var transformedItems = transformItems(itemsWithAbsolutePositionAndQueryID, {
18050
18333
  results: results
18051
18334
  });
@@ -18488,6 +18771,8 @@
18488
18771
  // later during hydration.
18489
18772
  var requestParamsList;
18490
18773
  var client = helper.getClient();
18774
+ var waitsForSearch = search._hasSearchWidget;
18775
+ var waitsForRecommend = !skipRecommend && search._hasRecommendWidget;
18491
18776
  if (search.compositionID) {
18492
18777
  helper.setClient(_object_spread_props(_object_spread({}, client), {
18493
18778
  search: function search(query) {
@@ -18508,17 +18793,22 @@
18508
18793
  }
18509
18794
  }));
18510
18795
  }
18511
- if (search._hasSearchWidget) {
18796
+ if (waitsForSearch) {
18512
18797
  if (search.compositionID) {
18513
18798
  helper.searchWithComposition();
18514
18799
  } else {
18515
18800
  helper.searchOnlyWithDerivedHelpers();
18516
18801
  }
18517
18802
  }
18518
- !skipRecommend && search._hasRecommendWidget && helper.recommend();
18803
+ if (waitsForRecommend) {
18804
+ helper.recommend();
18805
+ }
18806
+ if (!waitsForSearch && !waitsForRecommend) {
18807
+ return Promise.resolve([]);
18808
+ }
18519
18809
  return new Promise(function(resolve, reject) {
18520
- var searchResultsReceived = !search._hasSearchWidget;
18521
- var recommendResultsReceived = !search._hasRecommendWidget || skipRecommend;
18810
+ var searchResultsReceived = !waitsForSearch;
18811
+ var recommendResultsReceived = !waitsForRecommend;
18522
18812
  // All derived helpers resolve in the same tick so we're safe only relying
18523
18813
  // on the first one.
18524
18814
  helper.derivedHelpers[0].on('result', function() {
@@ -18558,6 +18848,13 @@
18558
18848
  var requestParamsIndex = 0;
18559
18849
  walkIndex(rootIndex, function(widget) {
18560
18850
  var _widget_getHelper;
18851
+ var currentIndex = widget;
18852
+ while(currentIndex){
18853
+ if (currentIndex._isolated) {
18854
+ return;
18855
+ }
18856
+ currentIndex = currentIndex.getParent();
18857
+ }
18561
18858
  var searchResults = widget.getResults();
18562
18859
  var recommendResults = (_widget_getHelper = widget.getHelper()) === null || _widget_getHelper === void 0 ? void 0 : _widget_getHelper.lastRecommendResults;
18563
18860
  if (searchResults || recommendResults) {
@@ -18588,7 +18885,7 @@
18588
18885
  });
18589
18886
  }
18590
18887
  });
18591
- if (Object.keys(initialResults).length === 0) {
18888
+ if (Object.keys(initialResults).length === 0 && (requestParamsList === null || requestParamsList === void 0 ? void 0 : requestParamsList.length) !== 0) {
18592
18889
  throw new Error('The root index does not have any results. Make sure you have at least one widget that provides results.');
18593
18890
  }
18594
18891
  return initialResults;
@@ -18623,6 +18920,13 @@
18623
18920
  var shouldRefetch = false;
18624
18921
  // Two-pass widgets require another query to discover and mount child widgets.
18625
18922
  walkIndex(searchRef.current.mainIndex, function(index) {
18923
+ var current = index;
18924
+ while(current){
18925
+ if (current._isolated) {
18926
+ return;
18927
+ }
18928
+ current = current.getParent();
18929
+ }
18626
18930
  shouldRefetch = shouldRefetch || index.getWidgets().some(isTwoPassWidget);
18627
18931
  });
18628
18932
  if (shouldRefetch) {
@@ -20371,8 +20675,11 @@
20371
20675
  var ToolLayoutComponent = tool.layoutComponent;
20372
20676
  var toolMessage = part;
20373
20677
  var boundAddToolResult = function boundAddToolResult(params) {
20374
- var _tool_addToolResult;
20375
- return (_tool_addToolResult = tool.addToolResult) === null || _tool_addToolResult === void 0 ? void 0 : _tool_addToolResult.call(tool, {
20678
+ return tool['~addToolResultForMessage'] ? tool['~addToolResultForMessage'](message, {
20679
+ output: params.output,
20680
+ tool: part.type,
20681
+ toolCallId: toolMessage.toolCallId
20682
+ }) : tool.addToolResult({
20376
20683
  output: params.output,
20377
20684
  tool: part.type,
20378
20685
  toolCallId: toolMessage.toolCallId
@@ -20546,20 +20853,6 @@
20546
20853
  var copyToClipboard = function copyToClipboard(message) {
20547
20854
  navigator.clipboard.writeText(getTextContent(message));
20548
20855
  };
20549
- /**
20550
- * Memoization comparator for a message row. `replaceMessage` only clones the
20551
- * message being updated, so completed messages keep a stable reference across
20552
- * streaming deltas. We compare just what affects a row's render — `message`,
20553
- * `status`, `suggestionsElement`, and this message's feedback — and ignore the
20554
- * props that get a fresh reference every render but don't change the output
20555
- * (`tools`, `messages`, callbacks, `indexUiState`). `indexUiState` in
20556
- * particular can't be compared: `getUiState()` returns a new object each render
20557
- * and would defeat the memo. Trade-off: a completed row keeps the callbacks/
20558
- * `indexUiState` it last rendered with until its next genuine render.
20559
- */ function areMessagePropsEqual(prev, next) {
20560
- var _prev_feedbackState, _next_feedbackState;
20561
- return prev.message === next.message && prev.status === next.status && prev.suggestionsElement === next.suggestionsElement && ((_prev_feedbackState = prev.feedbackState) === null || _prev_feedbackState === void 0 ? void 0 : _prev_feedbackState[prev.message.id]) === ((_next_feedbackState = next.feedbackState) === null || _next_feedbackState === void 0 ? void 0 : _next_feedbackState[next.message.id]);
20562
- }
20563
20856
  function createDefaultMessageComponent(param) {
20564
20857
  var createElement = param.createElement, Fragment = param.Fragment;
20565
20858
  var ChatMessage = createChatMessageComponent({
@@ -20667,7 +20960,7 @@
20667
20960
  };
20668
20961
  }
20669
20962
  function createChatMessagesComponent(param) {
20670
- var createElement = param.createElement, Fragment = param.Fragment, memo = param.memo;
20963
+ var createElement = param.createElement, Fragment = param.Fragment, useMemo = param.useMemo;
20671
20964
  var Button = createButtonComponent({
20672
20965
  createElement: createElement
20673
20966
  });
@@ -20676,8 +20969,23 @@
20676
20969
  Fragment: Fragment
20677
20970
  });
20678
20971
  // Skip re-rendering (and re-compiling the markdown of) completed messages on
20679
- // every streaming delta.
20680
- var MemoizedDefaultMessage = memo(DefaultMessageComponent, areMessagePropsEqual);
20972
+ // every streaming delta. The deps tuple matches the row's render inputs;
20973
+ // callbacks/`indexUiState` are intentionally excluded because `getUiState()`
20974
+ // returns a fresh object every render and would defeat the memo — completed
20975
+ // rows keep the callbacks/`indexUiState` they last rendered with until their
20976
+ // next genuine update.
20977
+ function MemoizedDefaultMessage(props) {
20978
+ var _props_feedbackState;
20979
+ var messageFeedback = (_props_feedbackState = props.feedbackState) === null || _props_feedbackState === void 0 ? void 0 : _props_feedbackState[props.message.id];
20980
+ return useMemo(function() {
20981
+ return /*#__PURE__*/ createElement(DefaultMessageComponent, props);
20982
+ }, [
20983
+ props.message,
20984
+ props.status,
20985
+ props.suggestionsElement,
20986
+ messageFeedback
20987
+ ]);
20988
+ }
20681
20989
  var DefaultLoaderComponent = createChatMessageLoaderComponent({
20682
20990
  createElement: createElement
20683
20991
  });
@@ -21058,7 +21366,7 @@
21058
21366
  return typeof window !== 'undefined' && typeof window.matchMedia === 'function' && window.matchMedia('(prefers-reduced-motion: reduce)').matches;
21059
21367
  }
21060
21368
  function createChatComponent(param) {
21061
- var createElement = param.createElement, Fragment = param.Fragment, memo = param.memo, useState = param.useState;
21369
+ var createElement = param.createElement, Fragment = param.Fragment, useMemo = param.useMemo, useState = param.useState;
21062
21370
  var ChatHeader = createChatHeaderComponent({
21063
21371
  createElement: createElement,
21064
21372
  Fragment: Fragment
@@ -21066,7 +21374,7 @@
21066
21374
  var ChatMessages = createChatMessagesComponent({
21067
21375
  createElement: createElement,
21068
21376
  Fragment: Fragment,
21069
- memo: memo
21377
+ useMemo: useMemo
21070
21378
  });
21071
21379
  var ChatPrompt = createChatPromptComponent({
21072
21380
  createElement: createElement,
@@ -21340,6 +21648,162 @@
21340
21648
  };
21341
21649
  }
21342
21650
 
21651
+ function addAbsolutePosition(hits, page, hitsPerPage) {
21652
+ return hits.map(function(hit, idx) {
21653
+ return _object_spread_props(_object_spread({}, hit), {
21654
+ __position: hitsPerPage * page + idx + 1
21655
+ });
21656
+ });
21657
+ }
21658
+ function addQueryID(hits, queryID) {
21659
+ if (!queryID) {
21660
+ return hits;
21661
+ }
21662
+ return hits.map(function(hit) {
21663
+ return _object_spread_props(_object_spread({}, hit), {
21664
+ __queryID: queryID
21665
+ });
21666
+ });
21667
+ }
21668
+
21669
+ function createHeaderComponent(param) {
21670
+ var createElement = param.createElement;
21671
+ var Button = createButtonComponent({
21672
+ createElement: createElement
21673
+ });
21674
+ return function HeaderComponent(param) {
21675
+ var showViewAll = param.showViewAll, canScrollLeft = param.canScrollLeft, canScrollRight = param.canScrollRight, scrollLeft = param.scrollLeft, scrollRight = param.scrollRight, nbHits = param.nbHits, input = param.input, nbItems = param.nbItems, applyFilters = param.applyFilters, getSearchPageURL = param.getSearchPageURL, onClose = param.onClose;
21676
+ if (nbItems < 1) {
21677
+ return null;
21678
+ }
21679
+ return /*#__PURE__*/ createElement("div", {
21680
+ className: "ais-ChatToolSearchIndexCarouselHeader"
21681
+ }, /*#__PURE__*/ createElement("div", {
21682
+ className: "ais-ChatToolSearchIndexCarouselHeaderResults"
21683
+ }, nbHits && /*#__PURE__*/ createElement("div", {
21684
+ className: "ais-ChatToolSearchIndexCarouselHeaderCount"
21685
+ }, nbItems, " of ", nbHits.toLocaleString(), " result", nbHits > 1 ? 's' : ''), showViewAll && /*#__PURE__*/ createElement(Button, {
21686
+ variant: "ghost",
21687
+ size: "sm",
21688
+ onClick: function onClick() {
21689
+ if (!input || !applyFilters) return;
21690
+ var params = applyFilters({
21691
+ query: input.query,
21692
+ facetFilters: getFacetFiltersFromToolInput(input)
21693
+ });
21694
+ if (getSearchPageURL) {
21695
+ var searchPageURL = getSearchPageURL(params);
21696
+ var resolvedURL = new URL(searchPageURL, window.location.href);
21697
+ if (resolvedURL.pathname !== window.location.pathname) {
21698
+ window.location.href = searchPageURL;
21699
+ }
21700
+ }
21701
+ onClose();
21702
+ },
21703
+ className: "ais-ChatToolSearchIndexCarouselHeaderViewAll"
21704
+ }, "View all", /*#__PURE__*/ createElement(ArrowRightIcon, {
21705
+ createElement: createElement
21706
+ }))), nbItems > 2 && /*#__PURE__*/ createElement("div", {
21707
+ className: "ais-ChatToolSearchIndexCarouselHeaderScrollButtons"
21708
+ }, /*#__PURE__*/ createElement(Button, {
21709
+ variant: "outline",
21710
+ size: "sm",
21711
+ iconOnly: true,
21712
+ onClick: scrollLeft,
21713
+ disabled: !canScrollLeft,
21714
+ className: "ais-ChatToolSearchIndexCarouselHeaderScrollButton"
21715
+ }, /*#__PURE__*/ createElement(ChevronLeftIcon, {
21716
+ createElement: createElement
21717
+ })), /*#__PURE__*/ createElement(Button, {
21718
+ variant: "outline",
21719
+ size: "sm",
21720
+ iconOnly: true,
21721
+ onClick: scrollRight,
21722
+ disabled: !canScrollRight,
21723
+ className: "ais-ChatToolSearchIndexCarouselHeaderScrollButton"
21724
+ }, /*#__PURE__*/ createElement(ChevronRightIcon, {
21725
+ createElement: createElement
21726
+ }))));
21727
+ };
21728
+ }
21729
+ function createCarouselToolComponent(param) {
21730
+ var createElement = param.createElement, Fragment = param.Fragment, useMemo = param.useMemo, useRef = param.useRef, useState = param.useState;
21731
+ var DefaultHeader = createHeaderComponent({
21732
+ createElement: createElement,
21733
+ Fragment: Fragment
21734
+ });
21735
+ var Carousel = createCarouselComponent({
21736
+ createElement: createElement,
21737
+ Fragment: Fragment
21738
+ });
21739
+ return function CarouselTool(userProps) {
21740
+ var ItemComponent = userProps.itemComponent, HeaderComponent = userProps.headerComponent, getSearchPageURL = userProps.getSearchPageURL, _userProps_toolProps = userProps.toolProps, message = _userProps_toolProps.message, applyFilters = _userProps_toolProps.applyFilters, onClose = _userProps_toolProps.onClose, sendEvent = _userProps_toolProps.sendEvent, showViewAll = userProps.headerProps.showViewAll;
21741
+ var input = message === null || message === void 0 ? void 0 : message.input;
21742
+ var output = message === null || message === void 0 ? void 0 : message.output;
21743
+ var hits = (output === null || output === void 0 ? void 0 : output.hits) || [];
21744
+ var items = addQueryID(addAbsolutePosition(hits, 0, hits.length), output === null || output === void 0 ? void 0 : output.queryID);
21745
+ var nbItems = items.length;
21746
+ var _useState = _sliced_to_array(useState(false), 2), canScrollLeft = _useState[0], setCanScrollLeft = _useState[1];
21747
+ var _useState1 = _sliced_to_array(useState(true), 2), canScrollRight = _useState1[0], setCanScrollRight = _useState1[1];
21748
+ var carouselIdRef = useRef('');
21749
+ if (!carouselIdRef.current) {
21750
+ carouselIdRef.current = generateCarouselId();
21751
+ }
21752
+ var carouselRefs = {
21753
+ listRef: useRef(null),
21754
+ nextButtonRef: useRef(null),
21755
+ previousButtonRef: useRef(null),
21756
+ carouselIdRef: carouselIdRef,
21757
+ canScrollLeft: canScrollLeft,
21758
+ canScrollRight: canScrollRight,
21759
+ setCanScrollLeft: setCanScrollLeft,
21760
+ setCanScrollRight: setCanScrollRight
21761
+ };
21762
+ var MemoedHeaderComponent = useMemo(function() {
21763
+ if (HeaderComponent) {
21764
+ return function(props) {
21765
+ return /*#__PURE__*/ createElement(HeaderComponent, _object_spread({
21766
+ showViewAll: showViewAll,
21767
+ nbHits: output === null || output === void 0 ? void 0 : output.nbHits,
21768
+ input: input,
21769
+ nbItems: nbItems,
21770
+ applyFilters: applyFilters,
21771
+ getSearchPageURL: getSearchPageURL,
21772
+ onClose: onClose
21773
+ }, props));
21774
+ };
21775
+ }
21776
+ return function(props) {
21777
+ return /*#__PURE__*/ createElement(DefaultHeader, _object_spread({
21778
+ showViewAll: showViewAll,
21779
+ nbHits: output === null || output === void 0 ? void 0 : output.nbHits,
21780
+ input: input,
21781
+ nbItems: nbItems,
21782
+ applyFilters: applyFilters,
21783
+ getSearchPageURL: getSearchPageURL,
21784
+ onClose: onClose
21785
+ }, props));
21786
+ };
21787
+ }, [
21788
+ showViewAll,
21789
+ HeaderComponent,
21790
+ output === null || output === void 0 ? void 0 : output.nbHits,
21791
+ input,
21792
+ nbItems,
21793
+ applyFilters,
21794
+ getSearchPageURL,
21795
+ onClose
21796
+ ]);
21797
+ return /*#__PURE__*/ createElement(Carousel, _object_spread_props(_object_spread({}, carouselRefs), {
21798
+ items: items,
21799
+ itemComponent: ItemComponent,
21800
+ headerComponent: MemoedHeaderComponent,
21801
+ showNavigation: false,
21802
+ sendEvent: sendEvent
21803
+ }));
21804
+ };
21805
+ }
21806
+
21343
21807
  var DEFAULT_TRANSLATIONS$1 = {
21344
21808
  streamingLabel: 'Curating results…'
21345
21809
  };
@@ -22528,7 +22992,7 @@
22528
22992
  }));
22529
22993
  }
22530
22994
 
22531
- var Autocomplete = createAutocompleteComponent({
22995
+ var AutocompleteUiComponent = createAutocompleteComponent({
22532
22996
  createElement: React.createElement,
22533
22997
  Fragment: React.Fragment
22534
22998
  });
@@ -22714,19 +23178,20 @@
22714
23178
  setIsModalOpen: setIsModalOpen
22715
23179
  };
22716
23180
  }
22717
- function EXPERIMENTAL_Autocomplete(props) {
23181
+ function Autocomplete(props) {
22718
23182
  var _showRecent_classNames, _showRecent_classNames1, _showRecent_classNames2, _showRecent_classNames3;
22719
23183
  var indices = 'indices' in props ? props.indices : undefined;
22720
23184
  var feeds = 'feeds' in props ? props.feeds : undefined;
22721
23185
  var isFeedsMode = feeds !== undefined;
22722
- var showQuerySuggestions = props.showQuerySuggestions, showPromptSuggestions = props.showPromptSuggestions, showRecent = props.showRecent, userSearchParameters = props.searchParameters, detachedMediaQuery = props.detachedMediaQuery, tmp = props.translations, userTranslations = tmp === void 0 ? {} : tmp, transformItems = props.transformItems, restProps = _object_without_properties(props, [
23186
+ var showQuerySuggestions = props.showQuerySuggestions, showPromptSuggestions = props.showPromptSuggestions, showRecent = props.showRecent, userSearchParameters = props.searchParameters, detachedMediaQuery = props.detachedMediaQuery, tmp = props.translations, userTranslations = tmp === void 0 ? {} : tmp, transformItems = props.transformItems, _props_requiresSearch = props.requiresSearch, requiresSearch = _props_requiresSearch === void 0 ? true : _props_requiresSearch, restProps = _object_without_properties(props, [
22723
23187
  "showQuerySuggestions",
22724
23188
  "showPromptSuggestions",
22725
23189
  "showRecent",
22726
23190
  "searchParameters",
22727
23191
  "detachedMediaQuery",
22728
23192
  "translations",
22729
- "transformItems"
23193
+ "transformItems",
23194
+ "requiresSearch"
22730
23195
  ]);
22731
23196
  var autoFocus = restProps.autoFocus, placeholder = restProps.placeholder, classNames = restProps.classNames;
22732
23197
  // Eager-mount only when `autoFocus` is set — otherwise wait for first focus
@@ -22735,19 +23200,21 @@
22735
23200
  var translations = _object_spread({}, DEFAULT_TRANSLATIONS, userTranslations);
22736
23201
  var _useInstantSearch = useInstantSearch(), indexUiState = _useInstantSearch.indexUiState, indexRenderState = _useInstantSearch.indexRenderState, status = _useInstantSearch.status;
22737
23202
  var compositionID = useInstantSearchContext().compositionID;
23203
+ var dependsOn = requiresSearch ? 'search' : 'none';
22738
23204
  var refine = useSearchBox({}, _object_spread({
22739
23205
  $$type: 'ais.autocomplete',
22740
- $$widgetType: 'ais.autocomplete'
23206
+ $$widgetType: 'ais.autocomplete',
23207
+ dependsOn: dependsOn
22741
23208
  }, props.aiMode ? {
22742
23209
  opensChat: true
22743
23210
  } : {})).refine;
22744
23211
  var domId = useAutocompleteId();
22745
23212
  var instanceKey = domId.replace(/:/g, '');
22746
23213
  if (isFeedsMode && indices !== undefined) {
22747
- throw new Error('EXPERIMENTAL_Autocomplete: `feeds` and `indices` are mutually exclusive.');
23214
+ throw new Error('Autocomplete: `feeds` and `indices` are mutually exclusive.');
22748
23215
  }
22749
23216
  if (isFeedsMode && !compositionID) {
22750
- throw new Error('EXPERIMENTAL_Autocomplete in feeds-mode requires a composition-based <InstantSearch> (compositionID must be set).');
23217
+ throw new Error('Autocomplete in feeds-mode requires a composition-based <InstantSearch> (compositionID must be set).');
22751
23218
  }
22752
23219
  var isSearchStalled = status === 'stalled';
22753
23220
  var searchParameters = _object_spread({
@@ -22962,7 +23429,7 @@
22962
23429
  }
22963
23430
  setActivated(true);
22964
23431
  };
22965
- return /*#__PURE__*/ React.createElement(Autocomplete, _object_spread_props(_object_spread({}, shellRootProps), {
23432
+ return /*#__PURE__*/ React.createElement(AutocompleteUiComponent, _object_spread_props(_object_spread({}, shellRootProps), {
22966
23433
  classNames: classNames
22967
23434
  }), isDetached ? /*#__PURE__*/ React.createElement(AutocompleteDetachedSearchButton, {
22968
23435
  query: (_indexUiState_query = indexUiState.query) !== null && _indexUiState_query !== void 0 ? _indexUiState_query : '',
@@ -23005,7 +23472,7 @@
23005
23472
  }));
23006
23473
  if (isFeedsMode) {
23007
23474
  return /*#__PURE__*/ React.createElement(Index, {
23008
- EXPERIMENTAL_isolated: true,
23475
+ isolated: true,
23009
23476
  indexName: compositionID,
23010
23477
  indexId: "ais-autocomplete-".concat(instanceKey)
23011
23478
  }, /*#__PURE__*/ React.createElement(Configure, searchParameters), /*#__PURE__*/ React.createElement(Feeds, {
@@ -23016,7 +23483,7 @@
23016
23483
  }), innerAutocomplete);
23017
23484
  }
23018
23485
  return /*#__PURE__*/ React.createElement(Index, {
23019
- EXPERIMENTAL_isolated: true,
23486
+ isolated: true,
23020
23487
  indexId: "ais-autocomplete-".concat(instanceKey)
23021
23488
  }, /*#__PURE__*/ React.createElement(Configure, searchParameters), indicesConfig.map(function(index) {
23022
23489
  return /*#__PURE__*/ React.createElement(Index, {
@@ -23026,6 +23493,7 @@
23026
23493
  }, /*#__PURE__*/ React.createElement(Configure, index.searchParameters));
23027
23494
  }), innerAutocomplete);
23028
23495
  }
23496
+ /** @deprecated use Autocomplete instead */ var EXPERIMENTAL_Autocomplete = deprecate(Autocomplete);
23029
23497
  function InnerAutocomplete(_0) {
23030
23498
  var indicesConfig = _0.indicesConfig, refineSearchBox = _0.refineSearchBox, isSearchStalled = _0.isSearchStalled, getSearchPageURL = _0.getSearchPageURL, userOnSelect = _0.onSelect, indexUiState = _0.indexUiState, isSearchPage = _0.isSearchPage, PanelComponent = _0.panelComponent, showRecent = _0.showRecent, recentSearchConfig = _0.recentSearchConfig, showQuerySuggestions = _0.showQuerySuggestions, showPromptSuggestions = _0.showPromptSuggestions, chatRenderState = _0.chatRenderState, transformItems = _0.transformItems, placeholder = _0.placeholder, autoFocus = _0.autoFocus, translations = _0.translations, classNames = _0.classNames, aiMode = _0.aiMode, domId = _0.domId, detached = _0.detached, props = _object_without_properties(_0, [
23031
23499
  "indicesConfig",
@@ -23315,7 +23783,7 @@
23315
23783
  "ref"
23316
23784
  ]);
23317
23785
  if (isDetached) {
23318
- return /*#__PURE__*/ React.createElement(Autocomplete, _object_spread_props(_object_spread({}, props, rootProps), {
23786
+ return /*#__PURE__*/ React.createElement(AutocompleteUiComponent, _object_spread_props(_object_spread({}, props, rootProps), {
23319
23787
  rootRef: rootRef,
23320
23788
  classNames: classNames
23321
23789
  }), /*#__PURE__*/ React.createElement(AutocompleteDetachedSearchButton, {
@@ -23341,7 +23809,7 @@
23341
23809
  }, searchBoxContent), panelContent)));
23342
23810
  }
23343
23811
  // Normal (non-detached) rendering
23344
- return /*#__PURE__*/ React.createElement(Autocomplete, _object_spread_props(_object_spread({}, props, rootProps), {
23812
+ return /*#__PURE__*/ React.createElement(AutocompleteUiComponent, _object_spread_props(_object_spread({}, props, rootProps), {
23345
23813
  rootRef: rootRef,
23346
23814
  classNames: classNames
23347
23815
  }), searchBoxContent, panelContent);
@@ -23558,92 +24026,23 @@
23558
24026
  }
23559
24027
 
23560
24028
  function createCarouselTool(showViewAll, itemComponent, getSearchPageURL) {
23561
- var Button = createButtonComponent({
23562
- createElement: React.createElement
24029
+ var SearchLayoutUIComponent = createCarouselToolComponent({
24030
+ createElement: React.createElement,
24031
+ Fragment: React.Fragment,
24032
+ useMemo: React.useMemo,
24033
+ useRef: React.useRef,
24034
+ useState: React.useState
23563
24035
  });
23564
- function SearchLayoutComponent(param) {
23565
- var message = param.message, applyFilters = param.applyFilters, onClose = param.onClose, sendEvent = param.sendEvent;
23566
- var _ref;
23567
- var _output_hits;
23568
- var input = message === null || message === void 0 ? void 0 : message.input;
23569
- var output = message === null || message === void 0 ? void 0 : message.output;
23570
- var hitsWithAbsolutePosition = addAbsolutePosition((output === null || output === void 0 ? void 0 : output.hits) || [], 0, ((_ref = input === null || input === void 0 ? void 0 : input.number_of_results) !== null && _ref !== void 0 ? _ref : output === null || output === void 0 ? void 0 : (_output_hits = output.hits) === null || _output_hits === void 0 ? void 0 : _output_hits.length) || 5);
23571
- var items = addQueryID(hitsWithAbsolutePosition, output === null || output === void 0 ? void 0 : output.queryID);
23572
- var MemoedHeaderComponent = React.useMemo(function() {
23573
- return function(props) {
23574
- return /*#__PURE__*/ React.createElement(HeaderComponent, _object_spread({
23575
- nbHits: output === null || output === void 0 ? void 0 : output.nbHits,
23576
- input: input,
23577
- hitsPerPage: items.length,
23578
- onClose: onClose,
23579
- applyFilters: applyFilters
23580
- }, props));
23581
- };
23582
- }, [
23583
- items.length,
23584
- input,
23585
- output === null || output === void 0 ? void 0 : output.nbHits,
23586
- applyFilters,
23587
- onClose
23588
- ]);
23589
- return /*#__PURE__*/ React.createElement(Carousel, {
23590
- items: items,
24036
+ var SearchLayoutComponent = function SearchLayoutComponent(toolProps) {
24037
+ return /*#__PURE__*/ React.createElement(SearchLayoutUIComponent, {
24038
+ getSearchPageURL: getSearchPageURL,
24039
+ headerProps: {
24040
+ showViewAll: showViewAll
24041
+ },
23591
24042
  itemComponent: itemComponent,
23592
- sendEvent: sendEvent,
23593
- showNavigation: false,
23594
- headerComponent: MemoedHeaderComponent
24043
+ toolProps: toolProps
23595
24044
  });
23596
- }
23597
- function HeaderComponent(param) {
23598
- var canScrollLeft = param.canScrollLeft, canScrollRight = param.canScrollRight, scrollLeft = param.scrollLeft, scrollRight = param.scrollRight, nbHits = param.nbHits, input = param.input, hitsPerPage = param.hitsPerPage, applyFilters = param.applyFilters, onClose = param.onClose;
23599
- if ((hitsPerPage !== null && hitsPerPage !== void 0 ? hitsPerPage : 0) < 1) {
23600
- return null;
23601
- }
23602
- return /*#__PURE__*/ React.createElement("div", {
23603
- className: "ais-ChatToolSearchIndexCarouselHeader"
23604
- }, /*#__PURE__*/ React.createElement("div", {
23605
- className: "ais-ChatToolSearchIndexCarouselHeaderResults"
23606
- }, nbHits && /*#__PURE__*/ React.createElement("div", {
23607
- className: "ais-ChatToolSearchIndexCarouselHeaderCount"
23608
- }, hitsPerPage !== null && hitsPerPage !== void 0 ? hitsPerPage : 0, " of ", nbHits.toLocaleString(), " result", nbHits > 1 ? 's' : ''), showViewAll && /*#__PURE__*/ React.createElement(Button, {
23609
- variant: "ghost",
23610
- size: "sm",
23611
- onClick: function onClick() {
23612
- if (!input || !applyFilters) return;
23613
- var params = applyFilters({
23614
- query: input.query,
23615
- facetFilters: getFacetFiltersFromToolInput(input)
23616
- });
23617
- if (getSearchPageURL && new URL(getSearchPageURL(params)).pathname !== window.location.pathname) {
23618
- window.location.href = getSearchPageURL(params);
23619
- }
23620
- onClose();
23621
- },
23622
- className: "ais-ChatToolSearchIndexCarouselHeaderViewAll"
23623
- }, "View all", /*#__PURE__*/ React.createElement(ArrowRightIcon, {
23624
- createElement: React.createElement
23625
- }))), (hitsPerPage !== null && hitsPerPage !== void 0 ? hitsPerPage : 0) > 2 && /*#__PURE__*/ React.createElement("div", {
23626
- className: "ais-ChatToolSearchIndexCarouselHeaderScrollButtons"
23627
- }, /*#__PURE__*/ React.createElement(Button, {
23628
- variant: "outline",
23629
- size: "sm",
23630
- iconOnly: true,
23631
- onClick: scrollLeft,
23632
- disabled: !canScrollLeft,
23633
- className: "ais-ChatToolSearchIndexCarouselHeaderScrollButton"
23634
- }, /*#__PURE__*/ React.createElement(ChevronLeftIcon, {
23635
- createElement: React.createElement
23636
- })), /*#__PURE__*/ React.createElement(Button, {
23637
- variant: "outline",
23638
- size: "sm",
23639
- iconOnly: true,
23640
- onClick: scrollRight,
23641
- disabled: !canScrollRight,
23642
- className: "ais-ChatToolSearchIndexCarouselHeaderScrollButton"
23643
- }, /*#__PURE__*/ React.createElement(ChevronRightIcon, {
23644
- createElement: React.createElement
23645
- }))));
23646
- }
24045
+ };
23647
24046
  return {
23648
24047
  layoutComponent: SearchLayoutComponent
23649
24048
  };
@@ -23652,7 +24051,7 @@
23652
24051
  var ChatUiComponent = createChatComponent({
23653
24052
  createElement: React.createElement,
23654
24053
  Fragment: React.Fragment,
23655
- memo: React.memo,
24054
+ useMemo: React.useMemo,
23656
24055
  useState: React.useState
23657
24056
  });
23658
24057
  function createDefaultTools(itemComponent, getSearchPageURL) {
@@ -25715,6 +26114,7 @@
25715
26114
  return /*#__PURE__*/ React.createElement(FilterSuggestionsUiComponent, _object_spread({}, props, uiProps));
25716
26115
  }
25717
26116
 
26117
+ exports.Autocomplete = Autocomplete;
25718
26118
  exports.Breadcrumb = Breadcrumb;
25719
26119
  exports.Carousel = Carousel;
25720
26120
  exports.Chat = Chat;