react-instantsearch-core 7.38.0 → 7.39.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -9,4 +9,4 @@ Object.defineProperty(exports, "default", {
9
9
  return _default;
10
10
  }
11
11
  });
12
- var _default = '7.38.0';
12
+ var _default = '7.39.1';
@@ -1,2 +1,2 @@
1
- declare const _default: "7.38.0";
1
+ declare const _default: "7.39.1";
2
2
  export default _default;
@@ -1,3 +1,3 @@
1
- var version = '7.38.0';
1
+ var version = '7.39.1';
2
2
 
3
3
  export { version as default };
@@ -1,4 +1,4 @@
1
- /*! React InstantSearch Core 7.38.0 | © Algolia, Inc. and contributors; MIT License | https://github.com/algolia/instantsearch */
1
+ /*! React InstantSearch Core 7.39.1 | © 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.38.0';
27
+ var version$2 = '7.39.1';
28
28
 
29
29
  function _define_property(obj, key, value) {
30
30
  if (key in obj) {
@@ -571,10 +571,10 @@
571
571
  return objectHasKeys_1;
572
572
  }
573
573
 
574
- var omit;
574
+ var omit$1;
575
575
  var hasRequiredOmit;
576
576
  function requireOmit() {
577
- if (hasRequiredOmit) return omit;
577
+ if (hasRequiredOmit) return omit$1;
578
578
  hasRequiredOmit = 1;
579
579
  // https://github.com/babel/babel/blob/3aaafae053fa75febb3aa45d45b6f00646e30ba4/packages/babel-helpers/src/helpers.js#L604-L620
580
580
  function _objectWithoutPropertiesLoose(source, excluded) {
@@ -591,8 +591,8 @@
591
591
  }
592
592
  return target;
593
593
  }
594
- omit = _objectWithoutPropertiesLoose;
595
- return omit;
594
+ omit$1 = _objectWithoutPropertiesLoose;
595
+ return omit$1;
596
596
  }
597
597
 
598
598
  var RecommendParameters_1;
@@ -3919,7 +3919,7 @@
3919
3919
  function requireVersion() {
3920
3920
  if (hasRequiredVersion) return version$1;
3921
3921
  hasRequiredVersion = 1;
3922
- version$1 = '3.29.1';
3922
+ version$1 = '3.29.2';
3923
3923
  return version$1;
3924
3924
  }
3925
3925
 
@@ -7267,19 +7267,23 @@
7267
7267
  return widget.$$type === 'ais.dynamicWidgets' || widget.$$type === 'ais.feeds';
7268
7268
  }
7269
7269
 
7270
- function range(param) {
7271
- var _param_start = param.start, start = _param_start === void 0 ? 0 : _param_start, end = param.end, _param_step = param.step, step = _param_step === void 0 ? 1 : _param_step;
7272
- // We can't divide by 0 so we re-assign the step to 1 if it happens.
7273
- var limitStep = step === 0 ? 1 : step;
7274
- // In some cases the array to create has a decimal length.
7275
- // We therefore need to round the value.
7276
- // Example:
7277
- // { start: 1, end: 5000, step: 500 }
7278
- // => Array length = (5000 - 1) / 500 = 9.998
7279
- var arrayLength = Math.round((end - start) / limitStep);
7280
- return _to_consumable_array(Array(arrayLength)).map(function(_, current) {
7281
- return start + current * limitStep;
7282
- });
7270
+ /**
7271
+ * Creates a new object with the same keys as the original object, but without the excluded keys.
7272
+ * @param source original object
7273
+ * @param excluded keys to remove from the original object
7274
+ * @returns the new object
7275
+ */ function omit(source, excluded) {
7276
+ if (source === null || source === undefined) {
7277
+ return source;
7278
+ }
7279
+ return Object.keys(source).reduce(function(target, key) {
7280
+ if (excluded.indexOf(key) >= 0) {
7281
+ return target;
7282
+ }
7283
+ var validKey = key;
7284
+ target[validKey] = source[validKey];
7285
+ return target;
7286
+ }, {});
7283
7287
  }
7284
7288
 
7285
7289
  function createInitArgs(instantSearchInstance, parent, uiState) {
@@ -7327,6 +7331,132 @@
7327
7331
  instantSearchInstance.renderState = _object_spread_props(_object_spread({}, instantSearchInstance.renderState), _define_property({}, parentIndexName, _object_spread({}, instantSearchInstance.renderState[parentIndexName], renderState)));
7328
7332
  }
7329
7333
 
7334
+ function serializeParamValue(value) {
7335
+ if (value === undefined || value === null) {
7336
+ return null;
7337
+ }
7338
+ var t = typeof value === "undefined" ? "undefined" : _type_of(value);
7339
+ if (t === 'string' || t === 'number' || t === 'boolean') {
7340
+ return {
7341
+ value: String(value),
7342
+ type: t
7343
+ };
7344
+ }
7345
+ if (Array.isArray(value) || t === 'object') {
7346
+ var type = Array.isArray(value) ? 'array' : 'object';
7347
+ try {
7348
+ return {
7349
+ value: JSON.stringify(value),
7350
+ type: type
7351
+ };
7352
+ } catch (unused) {
7353
+ return {
7354
+ type: type
7355
+ };
7356
+ }
7357
+ }
7358
+ if (t === 'function') {
7359
+ return {
7360
+ value: value.name,
7361
+ type: 'function'
7362
+ };
7363
+ }
7364
+ // symbols, DOM elements: name only
7365
+ return null;
7366
+ }
7367
+ /**
7368
+ * Turns a `widgetParams`-style record into the serialized `WidgetTreeParam[]`
7369
+ * shape used throughout the usage events. Shared between the widget tree and
7370
+ * the root `ais.instantSearch` node so every node reports params identically.
7371
+ */ function serializeWidgetParams(widgetParams) {
7372
+ var params = [];
7373
+ Object.keys(widgetParams).forEach(function(key) {
7374
+ var raw = widgetParams[key];
7375
+ if (raw === undefined) {
7376
+ return;
7377
+ }
7378
+ var serialized = serializeParamValue(raw);
7379
+ if (serialized) {
7380
+ params.push(_object_spread({
7381
+ name: key
7382
+ }, serialized));
7383
+ } else {
7384
+ params.push({
7385
+ name: key
7386
+ });
7387
+ }
7388
+ });
7389
+ return params;
7390
+ }
7391
+ function buildWidgetTree(widgets, instantSearchInstance) {
7392
+ var parent = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : instantSearchInstance.mainIndex;
7393
+ var initOptions = createInitArgs(instantSearchInstance, parent, instantSearchInstance._initialUiState);
7394
+ return widgets.map(function(widget) {
7395
+ var widgetParams = {};
7396
+ if (widget.getWidgetRenderState) {
7397
+ var renderState = widget.getWidgetRenderState(initOptions);
7398
+ if (renderState && renderState.widgetParams) {
7399
+ widgetParams = renderState.widgetParams;
7400
+ }
7401
+ }
7402
+ var params = serializeWidgetParams(widgetParams);
7403
+ var children = isIndexWidget(widget) ? buildWidgetTree(widget.getWidgets(), instantSearchInstance, widget) : [];
7404
+ return {
7405
+ type: widget.$$widgetType || widget.$$type || 'unknown',
7406
+ params: params,
7407
+ children: children
7408
+ };
7409
+ });
7410
+ }
7411
+
7412
+ function extractWidgetPayload(widgets, instantSearchInstance, payload) {
7413
+ var parent = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : instantSearchInstance.mainIndex;
7414
+ var initOptions = createInitArgs(instantSearchInstance, parent, instantSearchInstance._initialUiState);
7415
+ widgets.forEach(function(widget) {
7416
+ var widgetParams = {};
7417
+ if (widget.getWidgetRenderState) {
7418
+ var renderState = widget.getWidgetRenderState(initOptions);
7419
+ if (renderState && renderState.widgetParams) {
7420
+ // casting, as we just earlier checked widgetParams exists, and thus an object
7421
+ widgetParams = renderState.widgetParams;
7422
+ }
7423
+ }
7424
+ // since we destructure in all widgets, the parameters with defaults are set to "undefined"
7425
+ var params = Object.keys(widgetParams).filter(function(key) {
7426
+ return widgetParams[key] !== undefined;
7427
+ });
7428
+ payload.widgets.push({
7429
+ type: widget.$$type,
7430
+ widgetType: widget.$$widgetType,
7431
+ params: params
7432
+ });
7433
+ if (isIndexWidget(widget)) {
7434
+ extractWidgetPayload(widget.getWidgets(), instantSearchInstance, payload, widget);
7435
+ }
7436
+ });
7437
+ }
7438
+
7439
+ var now = typeof performance !== 'undefined' ? function() {
7440
+ return performance.now();
7441
+ } : function() {
7442
+ return Date.now();
7443
+ };
7444
+
7445
+ function range(param) {
7446
+ var _param_start = param.start, start = _param_start === void 0 ? 0 : _param_start, end = param.end, _param_step = param.step, step = _param_step === void 0 ? 1 : _param_step;
7447
+ // We can't divide by 0 so we re-assign the step to 1 if it happens.
7448
+ var limitStep = step === 0 ? 1 : step;
7449
+ // In some cases the array to create has a decimal length.
7450
+ // We therefore need to round the value.
7451
+ // Example:
7452
+ // { start: 1, end: 5000, step: 500 }
7453
+ // => Array length = (5000 - 1) / 500 = 9.998
7454
+ var arrayLength = Math.round((end - start) / limitStep);
7455
+ return _to_consumable_array(Array(arrayLength)).map(function(_, current) {
7456
+ return start + current * limitStep;
7457
+ });
7458
+ }
7459
+
7330
7460
  function resolveSearchParameters(current) {
7331
7461
  var parent = current.getParent();
7332
7462
  var states = [
@@ -9062,6 +9192,8 @@
9062
9192
  });
9063
9193
  }
9064
9194
 
9195
+ var version = '4.106.0';
9196
+
9065
9197
  var ANONYMOUS_TOKEN_COOKIE_KEY = '_ALGOLIA';
9066
9198
  function getCookie(name) {
9067
9199
  if ((typeof document === "undefined" ? "undefined" : _type_of(document)) !== 'object' || typeof document.cookie !== 'string') {
@@ -9084,8 +9216,61 @@
9084
9216
  return getCookie(ANONYMOUS_TOKEN_COOKIE_KEY);
9085
9217
  }
9086
9218
 
9219
+ var USAGE_SESSION_KEY = 'ais.usage.sessionId';
9220
+ // Cache the id for the lifetime of the runtime so repeated calls don't hit
9221
+ // `sessionStorage` again, and so we always return the same id even when
9222
+ // storage is unavailable (SSR, privacy mode) and we fall back to a fresh UUID.
9223
+ var usageSessionId = null;
9224
+ function getUsageSessionId() {
9225
+ if (usageSessionId) {
9226
+ return usageSessionId;
9227
+ }
9228
+ try {
9229
+ var existing = sessionStorage.getItem(USAGE_SESSION_KEY);
9230
+ if (existing) {
9231
+ usageSessionId = existing;
9232
+ return usageSessionId;
9233
+ }
9234
+ usageSessionId = createUUID();
9235
+ sessionStorage.setItem(USAGE_SESSION_KEY, usageSessionId);
9236
+ return usageSessionId;
9237
+ } catch (unused) {
9238
+ // sessionStorage unavailable (SSR, privacy mode, etc.)
9239
+ usageSessionId = createUUID();
9240
+ return usageSessionId;
9241
+ }
9242
+ }
9243
+ /** @deprecated use bindEvent instead */ function writeDataAttributes(param) {
9244
+ var method = param.method, payload = param.payload;
9245
+ if ((typeof payload === "undefined" ? "undefined" : _type_of(payload)) !== 'object') {
9246
+ throw new Error("The insights helper expects the payload to be an object.");
9247
+ }
9248
+ var serializedPayload;
9249
+ try {
9250
+ serializedPayload = serializePayload(payload);
9251
+ } catch (error) {
9252
+ throw new Error("Could not JSON serialize the payload object.");
9253
+ }
9254
+ return 'data-insights-method="'.concat(method, '" data-insights-payload="').concat(serializedPayload, '"');
9255
+ }
9256
+ /**
9257
+ * @deprecated This function will be still supported in 4.x releases, but not further. It is replaced by the `insights` middleware. For more information, visit https://www.algolia.com/doc/guides/getting-insights-and-analytics/search-analytics/click-through-and-conversions/how-to/send-click-and-conversion-events-with-instantsearch/js/
9258
+ */ function insights(method, payload) {
9259
+ return writeDataAttributes({
9260
+ method: method,
9261
+ payload: payload
9262
+ });
9263
+ }
9264
+
9087
9265
  var ALGOLIA_INSIGHTS_VERSION = '2.17.2';
9088
9266
  var ALGOLIA_INSIGHTS_SRC = "https://cdn.jsdelivr.net/npm/search-insights@".concat(ALGOLIA_INSIGHTS_VERSION, "/dist/search-insights.min.js");
9267
+ // InstantSearch options that must never be sent in usage events because
9268
+ // they carry credentials or end-user data. Everything else is reported as-is.
9269
+ var SENSITIVE_OPTIONS = [
9270
+ 'searchClient',
9271
+ 'insightsClient',
9272
+ 'initialUiState'
9273
+ ];
9089
9274
  function createInsightsMiddleware() {
9090
9275
  var props = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
9091
9276
  var _insightsClient = props.insightsClient, insightsInitParams = props.insightsInitParams, onEvent = props.onEvent, _props_$$internal = props.$$internal, $$internal = _props_$$internal === void 0 ? false : _props_$$internal, _props_$$automatic = props.$$automatic, $$automatic = _props_$$automatic === void 0 ? false : _props_$$automatic;
@@ -9175,6 +9360,7 @@
9175
9360
  }
9176
9361
  var initialParameters;
9177
9362
  var helper;
9363
+ var removeStartEventListener = null;
9178
9364
  return {
9179
9365
  $$type: 'ais.insights',
9180
9366
  $$internal: $$internal,
@@ -9349,8 +9535,65 @@
9349
9535
  insightsClientWithLocalCredentials(event.insightsMethod, event.payload);
9350
9536
  } else ;
9351
9537
  };
9538
+ // usage tracking (browser-only)
9539
+ safelyRunOnBrowser(function() {
9540
+ var usageSessionId = getUsageSessionId();
9541
+ function sendUsageEvent(event) {
9542
+ var _helper_state;
9543
+ var userToken = (_helper_state = helper.state) === null || _helper_state === void 0 ? void 0 : _helper_state.userToken;
9544
+ insightsClientWithLocalCredentials('sendEvents', [
9545
+ _object_spread({
9546
+ eventType: 'instantsearch',
9547
+ timestamp: Date.now(),
9548
+ sessionID: usageSessionId,
9549
+ userToken: userToken ? String(userToken) : undefined
9550
+ }, event)
9551
+ ]);
9552
+ }
9553
+ // Send the start event on the first `render`, by which point every
9554
+ // flavor has registered its widgets. `bootstrapMs` then measures the
9555
+ // time between the constructor running and that point, so for flavors
9556
+ // that register widgets right at start (e.g. React) it captures the
9557
+ // cost of adding them.
9558
+ var sendStartEvent = function sendStartEvent() {
9559
+ try {
9560
+ var bootstrapMs = Math.round(now() - instantSearchInstance._createdAt);
9561
+ sendUsageEvent({
9562
+ eventName: '__start__',
9563
+ algoliaAgent: getAlgoliaAgent(instantSearchInstance.client),
9564
+ version: version,
9565
+ applicationId: appId,
9566
+ performance: {
9567
+ bootstrapMs: bootstrapMs
9568
+ },
9569
+ widgets: [
9570
+ {
9571
+ type: 'ais.instantSearch',
9572
+ // The options the instance was created with, serialized the
9573
+ // same way every widget's params are. Derived dynamically from
9574
+ // `_initialOptions` so new options are reported automatically,
9575
+ // minus the keys that carry credentials or user data. Functions
9576
+ // (`onStateChange`, `searchFunction`) report their `fn.name`
9577
+ // when present, tagged `type: 'function'`.
9578
+ params: instantSearchInstance._initialOptions ? serializeWidgetParams(omit(instantSearchInstance._initialOptions, _to_consumable_array(SENSITIVE_OPTIONS))) : [],
9579
+ children: buildWidgetTree(instantSearchInstance.mainIndex.getWidgets(), instantSearchInstance)
9580
+ }
9581
+ ]
9582
+ });
9583
+ } catch (unused) {
9584
+ // usage tracking must never crash the host app
9585
+ }
9586
+ };
9587
+ instantSearchInstance.once('render', sendStartEvent);
9588
+ removeStartEventListener = function removeStartEventListener() {
9589
+ return instantSearchInstance.removeListener('render', sendStartEvent);
9590
+ };
9591
+ });
9352
9592
  },
9353
9593
  unsubscribe: function unsubscribe() {
9594
+ if (removeStartEventListener) {
9595
+ removeStartEventListener();
9596
+ }
9354
9597
  insightsClient('onUserTokenChange', undefined);
9355
9598
  instantSearchInstance.sendEventToInsights = noop;
9356
9599
  if (helper && initialParameters) {
@@ -9398,31 +9641,6 @@
9398
9641
  return typeof userToken === 'number' ? userToken.toString() : userToken;
9399
9642
  }
9400
9643
 
9401
- function extractWidgetPayload(widgets, instantSearchInstance, payload) {
9402
- var initOptions = createInitArgs(instantSearchInstance, instantSearchInstance.mainIndex, instantSearchInstance._initialUiState);
9403
- widgets.forEach(function(widget) {
9404
- var widgetParams = {};
9405
- if (widget.getWidgetRenderState) {
9406
- var renderState = widget.getWidgetRenderState(initOptions);
9407
- if (renderState && renderState.widgetParams) {
9408
- // casting, as we just earlier checked widgetParams exists, and thus an object
9409
- widgetParams = renderState.widgetParams;
9410
- }
9411
- }
9412
- // since we destructure in all widgets, the parameters with defaults are set to "undefined"
9413
- var params = Object.keys(widgetParams).filter(function(key) {
9414
- return widgetParams[key] !== undefined;
9415
- });
9416
- payload.widgets.push({
9417
- type: widget.$$type,
9418
- widgetType: widget.$$widgetType,
9419
- params: params
9420
- });
9421
- if (isIndexWidget(widget)) {
9422
- extractWidgetPayload(widget.getWidgets(), instantSearchInstance, payload);
9423
- }
9424
- });
9425
- }
9426
9644
  function isMetadataEnabled() {
9427
9645
  return safelyRunOnBrowser(function(param) {
9428
9646
  var window = param.window;
@@ -10771,28 +10989,6 @@
10771
10989
  return reverseHighlightedValue.replace(new RegExp(TAG_REPLACEMENT.highlightPreTag, 'g'), "<".concat(highlightedTagName, ' class="').concat(className, '">')).replace(new RegExp(TAG_REPLACEMENT.highlightPostTag, 'g'), "</".concat(highlightedTagName, ">"));
10772
10990
  }
10773
10991
 
10774
- /** @deprecated use bindEvent instead */ function writeDataAttributes(param) {
10775
- var method = param.method, payload = param.payload;
10776
- if ((typeof payload === "undefined" ? "undefined" : _type_of(payload)) !== 'object') {
10777
- throw new Error("The insights helper expects the payload to be an object.");
10778
- }
10779
- var serializedPayload;
10780
- try {
10781
- serializedPayload = serializePayload(payload);
10782
- } catch (error) {
10783
- throw new Error("Could not JSON serialize the payload object.");
10784
- }
10785
- return 'data-insights-method="'.concat(method, '" data-insights-payload="').concat(serializedPayload, '"');
10786
- }
10787
- /**
10788
- * @deprecated This function will be still supported in 4.x releases, but not further. It is replaced by the `insights` middleware. For more information, visit https://www.algolia.com/doc/guides/getting-insights-and-analytics/search-analytics/click-through-and-conversions/how-to/send-click-and-conversion-events-with-instantsearch/js/
10789
- */ function insights(method, payload) {
10790
- return writeDataAttributes({
10791
- method: method,
10792
- payload: payload
10793
- });
10794
- }
10795
-
10796
10992
  function hoganHelpers(param) {
10797
10993
  var numberLocale = param.numberLocale;
10798
10994
  return {
@@ -10854,8 +11050,6 @@
10854
11050
  };
10855
11051
  }
10856
11052
 
10857
- var version = '4.104.0';
10858
-
10859
11053
  var withUsage$r = createDocumentationMessageGenerator({
10860
11054
  name: 'instantsearch'
10861
11055
  });
@@ -10875,7 +11069,14 @@
10875
11069
  function InstantSearch(options) {
10876
11070
  _class_call_check(this, InstantSearch);
10877
11071
  var _this;
10878
- _this = _call_super(this, InstantSearch), _define_property(_this, "client", void 0), _define_property(_this, "indexName", void 0), _define_property(_this, "compositionID", void 0), _define_property(_this, "insightsClient", void 0), _define_property(_this, "onStateChange", null), _define_property(_this, "future", void 0), _define_property(_this, "helper", void 0), _define_property(_this, "mainHelper", void 0), _define_property(_this, "mainIndex", void 0), _define_property(_this, "started", void 0), _define_property(_this, "templatesConfig", void 0), _define_property(_this, "renderState", {}), _define_property(_this, "_stalledSearchDelay", void 0), _define_property(_this, "_searchStalledTimer", void 0), _define_property(_this, "_initialUiState", void 0), _define_property(_this, "_initialResults", void 0), _define_property(_this, "_manuallyResetScheduleSearch", false), _define_property(_this, "_resetScheduleSearch", void 0), _define_property(_this, "_createURL", void 0), _define_property(_this, "_searchFunction", void 0), _define_property(_this, "_mainHelperSearch", void 0), _define_property(_this, "_hasSearchWidget", false), _define_property(_this, "_hasRecommendWidget", false), _define_property(_this, "_insights", void 0), _define_property(_this, "middleware", []), _define_property(_this, "sendEventToInsights", void 0), /**
11072
+ _this = _call_super(this, InstantSearch), _define_property(_this, "client", void 0), _define_property(_this, "indexName", void 0), _define_property(_this, "compositionID", void 0), _define_property(_this, "insightsClient", void 0), _define_property(_this, "onStateChange", null), _define_property(_this, "future", void 0), _define_property(_this, "helper", void 0), _define_property(_this, "mainHelper", void 0), _define_property(_this, "mainIndex", void 0), _define_property(_this, "started", void 0), _define_property(_this, "templatesConfig", void 0), _define_property(_this, "renderState", {}), _define_property(_this, "_stalledSearchDelay", void 0), _define_property(_this, "_searchStalledTimer", void 0), _define_property(_this, "_initialUiState", void 0), _define_property(_this, "_initialResults", void 0), _define_property(_this, "_manuallyResetScheduleSearch", false), _define_property(_this, "_resetScheduleSearch", void 0), _define_property(_this, "_createURL", void 0), _define_property(_this, "_searchFunction", void 0), _define_property(_this, "_mainHelperSearch", void 0), _define_property(_this, "_hasSearchWidget", false), _define_property(_this, "_hasRecommendWidget", false), _define_property(_this, "_insights", void 0), /**
11073
+ * The options the instance was created with, kept verbatim so consumers
11074
+ * (e.g. usage events) can introspect the configuration without the class
11075
+ * having to enumerate every option by hand. Typed without the class generics
11076
+ * on purpose: referencing `TUiState`/`TRouteState` here (they sit in
11077
+ * contravariant positions inside `InstantSearchOptions`) would break the
11078
+ * assignability of `InstantSearch<SpecificUiState>` to `InstantSearch`.
11079
+ */ _define_property(_this, "_initialOptions", void 0), _define_property(_this, "middleware", []), _define_property(_this, "sendEventToInsights", void 0), _define_property(_this, "_createdAt", now()), /**
10879
11080
  * The status of the search. Can be "idle", "loading", "stalled", or "error".
10880
11081
  */ _define_property(_this, "status", 'idle'), /**
10881
11082
  * The last returned error from the Search API.
@@ -10923,6 +11124,7 @@
10923
11124
  if (insightsClient && typeof insightsClient !== 'function') {
10924
11125
  throw new Error(withUsage$r('The `insightsClient` option should be a function.'));
10925
11126
  }
11127
+ _this._initialOptions = options;
10926
11128
  _this.client = searchClient;
10927
11129
  _this.future = future;
10928
11130
  _this.insightsClient = insightsClient;
@@ -11295,6 +11497,9 @@
11295
11497
  var instance = param.instance;
11296
11498
  instance.unsubscribe();
11297
11499
  });
11500
+ // Cleared after unsubscribe so in-flight readers (e.g. the insights
11501
+ // start-event listener) have detached before the reference goes away.
11502
+ this._initialOptions = null;
11298
11503
  }
11299
11504
  },
11300
11505
  {
@@ -12403,15 +12608,14 @@
12403
12608
  return Promise.resolve(value);
12404
12609
  }
12405
12610
  /**
12406
- * Error raised when the upstream stream emits a `data-guardrail-violation`
12407
- * chunk. The `message` carries the service-provided `fallbackResponse`, which
12408
- * is intentionally surfaced verbatim through the chat error UI (unlike
12409
- * generic cost-control / 4xx errors, where the raw API message is hidden
12410
- * behind a friendly default).
12611
+ * Error shape for custom chat implementations that still surface a
12612
+ * `data-guardrail-violation` chunk through the error UI. The `message` carries
12613
+ * the service-provided `fallbackResponse`, which is authored for end-user
12614
+ * display.
12411
12615
  *
12412
12616
  * Detection across package boundaries should rely on `error.name` rather than
12413
12617
  * `instanceof` to avoid issues with mixed module copies in bundled apps.
12414
- */ var GuardrailViolationError = /*#__PURE__*/ function(Error1) {
12618
+ */ /*#__PURE__*/ (function(Error1) {
12415
12619
  _inherits(GuardrailViolationError, Error1);
12416
12620
  function GuardrailViolationError(message) {
12417
12621
  _class_call_check(this, GuardrailViolationError);
@@ -12423,7 +12627,7 @@
12423
12627
  return _this;
12424
12628
  }
12425
12629
  return GuardrailViolationError;
12426
- }(_wrap_native_super(Error));
12630
+ })(_wrap_native_super(Error));
12427
12631
  /**
12428
12632
  * Reads a non-empty `message` field off a JSON-serialized error envelope.
12429
12633
  *
@@ -12515,6 +12719,7 @@
12515
12719
  }
12516
12720
  return fallbackInput;
12517
12721
  };
12722
+ var defaultGuardrailFallbackResponse = 'Sorry, we are not able to generate a response at the moment.';
12518
12723
  /**
12519
12724
  * Abstract base class for chat implementations.
12520
12725
  */ var AbstractChat = /*#__PURE__*/ function() {
@@ -13341,28 +13546,37 @@
13341
13546
  }
13342
13547
  break;
13343
13548
  }
13344
- // Surface guardrail violations through the error state, but
13345
- // distinct from generic cost-control / 4xx errors: throw a
13346
- // `GuardrailViolationError` so the UI can render the
13347
- // service-provided `fallbackResponse` verbatim (it's authored for
13348
- // end-user display) instead of the friendly default used for
13349
- // opaque transport errors. Also discard any in-progress assistant
13350
- // message so no partial text lingers above the fallback, and
13351
- // clear the local cursor so the `onFinish` callback doesn't
13352
- // receive a `currentMessage` that no longer exists in state.
13353
13549
  case 'data-guardrail-violation':
13354
13550
  {
13355
- isError = true;
13356
- if (currentMessageIndex >= 0) {
13357
- _this.state.messages = _this.state.messages.slice(0, currentMessageIndex);
13358
- currentMessage = undefined;
13359
- currentMessageIndex = -1;
13360
- }
13361
13551
  // `chunk.data` widens to `unknown` here: the chunk union also
13362
13552
  // carries a generic `data-${string}` member, and the literal
13363
13553
  // matches both, so narrowing can't pick the specific shape.
13364
13554
  var fallbackResponse = chunk.data.fallbackResponse;
13365
- throw new GuardrailViolationError(fallbackResponse || 'Sorry, we are not able to generate a response at the moment.');
13555
+ var fallbackText = fallbackResponse || defaultGuardrailFallbackResponse;
13556
+ // The stream closes after a guardrail violation; keep the
13557
+ // fallback as the current message so the normal finish path runs.
13558
+ currentMessage = {
13559
+ id: (currentMessage === null || currentMessage === void 0 ? void 0 : currentMessage.id) || currentMessageId || _this.generateId(),
13560
+ role: 'assistant',
13561
+ metadata: currentMessage === null || currentMessage === void 0 ? void 0 : currentMessage.metadata,
13562
+ parts: [
13563
+ {
13564
+ type: 'text',
13565
+ text: fallbackText,
13566
+ state: 'done'
13567
+ }
13568
+ ]
13569
+ };
13570
+ if (currentMessageIndex >= 0) {
13571
+ _this.state.replaceMessage(currentMessageIndex, currentMessage);
13572
+ } else {
13573
+ _this.state.pushMessage(currentMessage);
13574
+ currentMessageIndex = _this.state.messages.length - 1;
13575
+ }
13576
+ currentMessageId = currentMessage.id;
13577
+ currentTextPartId = undefined;
13578
+ currentReasoningPartId = undefined;
13579
+ break;
13366
13580
  }
13367
13581
  default:
13368
13582
  {
@@ -13497,7 +13711,7 @@
13497
13711
  var ChatState = /*#__PURE__*/ function() {
13498
13712
  function ChatState() {
13499
13713
  var _this = this;
13500
- var id = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : undefined, initialMessages = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : getDefaultInitialMessages(id);
13714
+ var id = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : undefined, initialMessages = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : undefined, persistence = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : true;
13501
13715
  _class_call_check(this, ChatState);
13502
13716
  _define_property(this, "_messages", void 0);
13503
13717
  _define_property(this, "_status", 'ready');
@@ -13557,7 +13771,16 @@
13557
13771
  return callback();
13558
13772
  });
13559
13773
  });
13560
- this._messages = initialMessages;
13774
+ if (initialMessages !== undefined) {
13775
+ this._messages = initialMessages;
13776
+ } else if (persistence) {
13777
+ this._messages = getDefaultInitialMessages(id);
13778
+ } else {
13779
+ this._messages = [];
13780
+ }
13781
+ if (!persistence) {
13782
+ return;
13783
+ }
13561
13784
  var saveMessagesInLocalStorage = function saveMessagesInLocalStorage() {
13562
13785
  if (_this.status === 'ready') {
13563
13786
  try {
@@ -13611,11 +13834,12 @@
13611
13834
  function Chat(_0) {
13612
13835
  _class_call_check(this, Chat);
13613
13836
  var _this;
13614
- var messages = _0.messages, agentId = _0.agentId, init = _object_without_properties(_0, [
13837
+ var messages = _0.messages, agentId = _0.agentId, _0_persistence = _0.persistence, persistence = _0_persistence === void 0 ? true : _0_persistence, init = _object_without_properties(_0, [
13615
13838
  "messages",
13616
- "agentId"
13839
+ "agentId",
13840
+ "persistence"
13617
13841
  ]);
13618
- var state = new ChatState(agentId, messages);
13842
+ var state = new ChatState(agentId, messages, persistence);
13619
13843
  _this = _call_super(this, Chat, [
13620
13844
  _object_spread_props(_object_spread({}, init), {
13621
13845
  state: state