sim 2.1.28 → 2.2.0-preview.172.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.
package/dist/index.js CHANGED
@@ -7736,6 +7736,7 @@ function removeSection(doc, name) {
7736
7736
  var DEFAULT_PROFILE = "default";
7737
7737
  var DEFAULT_ENDPOINT = "https://www.sim.ai";
7738
7738
  var OUTPUT_FORMATS = ["table", "json", "yaml", "text"];
7739
+ var DEFAULT_OUTPUT_FORMAT = "json";
7739
7740
  var FORBIDDEN_IN_VALUE_GLOBAL = new RegExp(FORBIDDEN_IN_VALUE.source, "g");
7740
7741
  function redact(value) {
7741
7742
  return value.replace(FORBIDDEN_IN_VALUE_GLOBAL, " ");
@@ -8086,7 +8087,7 @@ function resolveProfile(overrides = {}) {
8086
8087
  ["flag", overrides.output],
8087
8088
  ["env", process.env.SIM_OUTPUT],
8088
8089
  ["config", config.output]
8089
- ], "table", "default");
8090
+ ], DEFAULT_OUTPUT_FORMAT, "default");
8090
8091
  if (!OUTPUT_FORMATS.includes(output.value)) {
8091
8092
  throw new ProfileConfigError(`Unknown output format "${redact(String(output.value))}" from ${output.source}. Use one of: ${OUTPUT_FORMATS.join(", ")}`);
8092
8093
  }
@@ -17004,7 +17005,7 @@ Waiting for you to approve in the browser…`));
17004
17005
  }
17005
17006
  }
17006
17007
  function loginCommand() {
17007
- return new Command("login").description("Sign in through the browser and store the login for the profile").addOption(new Option("--method <method>", "Credential to obtain: oauth requires OAuth support; api-key creates a permanent key through pairing (auto-selects when omitted)").choices(["oauth", "api-key"])).option("--no-browser", "Print the approval URL without opening it (either login method)").option("--read-only", "Ask only for permission to read, never to change anything").option("--callback-port <port>", "Pin the local port the browser returns to").option("-y, --yes", "Overwrite an existing API-key profile without prompting").action(async (options, command) => {
17008
+ return new Command("login").description("Log in through the browser and store the login for the profile").addOption(new Option("--method <method>", "Credential to obtain: oauth requires OAuth support; api-key creates a permanent key through pairing (auto-selects when omitted)").choices(["oauth", "api-key"])).option("--no-browser", "Print the approval URL without opening it (either login method)").option("--read-only", "Ask only for permission to read, never to change anything").option("--callback-port <port>", "Pin the local port the browser returns to").option("-y, --yes", "Overwrite an existing API-key profile without prompting").action(async (options, command) => {
17008
17009
  const profile = profileFrom(command, { allowUnknownProfile: true });
17009
17010
  const authProfile = resolveAuthenticationProfileName(profile.name);
17010
17011
  if (authProfile !== profile.name) {
@@ -17338,7 +17339,7 @@ function profileListingContext(command) {
17338
17339
  throw error;
17339
17340
  return {
17340
17341
  activeName: named || DEFAULT_PROFILE,
17341
- output: requested ? requested : "table"
17342
+ output: requested ? requested : DEFAULT_OUTPUT_FORMAT
17342
17343
  };
17343
17344
  }
17344
17345
  }
@@ -17386,7 +17387,7 @@ function quoteProfileArgument(name) {
17386
17387
  return `'${redacted.replaceAll("'", "'\\''")}'`;
17387
17388
  }
17388
17389
  function configureCommand() {
17389
- return new Command("configure").description("Set a profile's endpoint, default workspace, or output format").option("--set-endpoint <url>", "Sim deployment to talk to").option("--set-workspace <id>", "Default workspace for workspace-scoped commands").option("--set-output <format>", `Default output format (${OUTPUT_FORMATS.join(" | ")})`).option("--unset <key...>", "Remove settings (endpoint, workspace, output)").action(async (options, command) => {
17390
+ return new Command("configure").description("Switch a profile's default workspace, or set its endpoint or output format").option("--set-endpoint <url>", "Sim deployment to talk to").option("--set-workspace <id>", "Default workspace for workspace-scoped commands").option("--set-output <format>", `Default output format (${OUTPUT_FORMATS.join(" | ")})`).option("--unset <key...>", "Remove settings (endpoint, workspace, output)").action(async (options, command) => {
17390
17391
  const globals = globalsOf(command);
17391
17392
  const selectedProfile = globals.profile || process.env.SIM_PROFILE;
17392
17393
  const profileArg = selectedProfile ? ` --profile ${quoteProfileArgument(selectedProfile)}` : "";
@@ -17542,7 +17543,7 @@ var CLI_CONTRACT = {
17542
17543
  getBillingStatus: {
17543
17544
  command: "billing status",
17544
17545
  allWorkspaces: true,
17545
- describe: "Show billing status and current-period credit usage (credits and storage require an OAuth login or personal API key)",
17546
+ describe: "Show billing status, credits spent this period, and storage used (credits and storage require an OAuth login or personal API key)",
17546
17547
  fields: [
17547
17548
  { header: "plan" },
17548
17549
  { header: "status" },
@@ -17665,6 +17666,7 @@ var CLI_CONTRACT = {
17665
17666
  confirm: "This archives the knowledge base and every document in it; restore with `knowledge restore`."
17666
17667
  },
17667
17668
  deleteKnowledgeDocument: {
17669
+ describe: "Delete a document from a knowledge base",
17668
17670
  pathArgumentNames: KNOWLEDGE_BASE_PATH_ARGUMENT,
17669
17671
  confirm: "This deletes the document and its embeddings."
17670
17672
  },
@@ -17703,6 +17705,7 @@ var CLI_CONTRACT = {
17703
17705
  ]
17704
17706
  },
17705
17707
  listLogs: {
17708
+ describe: "List run logs, such as failed or errored runs, by workflow, trigger or time",
17706
17709
  flags: {
17707
17710
  ...LOG_LIST_FILTER_FLAGS,
17708
17711
  details: {
@@ -17815,6 +17818,7 @@ var CLI_CONTRACT = {
17815
17818
  },
17816
17819
  applyWorkflowOperations: {
17817
17820
  command: "workflows operations apply",
17821
+ describe: "Edit a workflow’s blocks, connections and settings with a batch of operations",
17818
17822
  confirm: "This edits the draft graph: the batch adds, edits, or deletes blocks and their edges as written.",
17819
17823
  flags: {
17820
17824
  operations: { json: true, describe: WORKFLOW_OPERATIONS_HELP },
@@ -17917,6 +17921,7 @@ var CLI_CONTRACT = {
17917
17921
  },
17918
17922
  queryRows: {
17919
17923
  command: "tables rows query",
17924
+ describe: "Query rows with a filter and sort",
17920
17925
  flags: {
17921
17926
  predicate: { name: "filter", json: true, describe: TABLE_READ_FILTER_HELP },
17922
17927
  sort: { json: true, describe: TABLE_SORT_HELP }
@@ -21316,7 +21321,7 @@ async function downloadToOutput(command, operation, pathParams, options) {
21316
21321
  });
21317
21322
  }
21318
21323
  function attachFileGet(files) {
21319
- files.command("get").argument("<fileId>", "File whose content to read").allowExcessArguments(false).description("Get a file’s content").option("-o, --output-file <path>", "Write content to a file instead of stdout").option("--force", "Overwrite --output-file if it already exists").action((fileId, options, command) => downloadToOutput(command, V2_OPERATIONS.downloadFile, { fileId }, options));
21324
+ files.command("get").argument("<fileId>", "File whose content to read").allowExcessArguments(false).description("Download a file’s content to stdout or a local file").option("-o, --output-file <path>", "Write content to a file instead of stdout").option("--force", "Overwrite --output-file if it already exists").action((fileId, options, command) => downloadToOutput(command, V2_OPERATIONS.downloadFile, { fileId }, options));
21320
21325
  }
21321
21326
  function attachFileVersionDownload(versions) {
21322
21327
  versions.command("download").argument("<fileId>", "File identifier.").argument("<version>", "Version number.").allowExcessArguments(false).description("Download the content of one version of a file").option("-o, --output-file <path>", "Write content to a file instead of stdout").option("--force", "Overwrite --output-file if it already exists").action((fileId, version, options, command) => downloadToOutput(command, V2_OPERATIONS.downloadFileVersion, { fileId, version }, options));
@@ -21863,7 +21868,7 @@ function inSeconds(ms) {
21863
21868
  return Math.round(ms / 100) / 10;
21864
21869
  }
21865
21870
  function attachLogsFollow(logs) {
21866
- logs.command("follow").description("Watch runs as they arrive, printing each new run once").option("--workflow <id>", "Only follow runs of this workflow (repeatable)", collect, []).option("--folder <path>", "Only follow runs of workflows in this folder (repeatable)", collect, []).option("--trigger <type>", "Only follow runs with this trigger type (repeatable)", collect, []).addOption(new Option("--level <level>", "Only follow runs at this severity").choices([
21871
+ logs.command("follow").description("Watch runs live as they arrive, printing each new run once").option("--workflow <id>", "Only follow runs of this workflow (repeatable)", collect, []).option("--folder <path>", "Only follow runs of workflows in this folder (repeatable)", collect, []).option("--trigger <type>", "Only follow runs with this trigger type (repeatable)", collect, []).addOption(new Option("--level <level>", "Only follow runs at this severity").choices([
21867
21872
  ...V2_OPERATIONS.listLogs.query.level.values
21868
21873
  ])).addOption(new Option("--details <level>", "Response detail level; full names each run’s workflow").choices([...V2_OPERATIONS.listLogs.query.details.values]).default("full")).option("-n, --lines <count>", "Recent runs to print before watching", String(DEFAULT_BACKLOG)).option("--interval <seconds>", "Seconds between polls", String(DEFAULT_INTERVAL_SECONDS)).addHelpText("after", `
21869
21874
  Each run prints once, when it is first seen, so its status is the status it had
@@ -22758,6 +22763,1140 @@ function attachProtocolCommands(program) {
22758
22763
  attachChat(program);
22759
22764
  }
22760
22765
 
22766
+ // ../../node_modules/minisearch/dist/es/index.js
22767
+ var ENTRIES = "ENTRIES";
22768
+ var KEYS = "KEYS";
22769
+ var VALUES = "VALUES";
22770
+ var LEAF = "";
22771
+
22772
+ class TreeIterator {
22773
+ constructor(set, type) {
22774
+ const node = set._tree;
22775
+ const keys = Array.from(node.keys());
22776
+ this.set = set;
22777
+ this._type = type;
22778
+ this._path = keys.length > 0 ? [{ node, keys }] : [];
22779
+ }
22780
+ next() {
22781
+ const value = this.dive();
22782
+ this.backtrack();
22783
+ return value;
22784
+ }
22785
+ dive() {
22786
+ if (this._path.length === 0) {
22787
+ return { done: true, value: undefined };
22788
+ }
22789
+ const { node, keys } = last$1(this._path);
22790
+ if (last$1(keys) === LEAF) {
22791
+ return { done: false, value: this.result() };
22792
+ }
22793
+ const child = node.get(last$1(keys));
22794
+ this._path.push({ node: child, keys: Array.from(child.keys()) });
22795
+ return this.dive();
22796
+ }
22797
+ backtrack() {
22798
+ if (this._path.length === 0) {
22799
+ return;
22800
+ }
22801
+ const keys = last$1(this._path).keys;
22802
+ keys.pop();
22803
+ if (keys.length > 0) {
22804
+ return;
22805
+ }
22806
+ this._path.pop();
22807
+ this.backtrack();
22808
+ }
22809
+ key() {
22810
+ return this.set._prefix + this._path.map(({ keys }) => last$1(keys)).filter((key) => key !== LEAF).join("");
22811
+ }
22812
+ value() {
22813
+ return last$1(this._path).node.get(LEAF);
22814
+ }
22815
+ result() {
22816
+ switch (this._type) {
22817
+ case VALUES:
22818
+ return this.value();
22819
+ case KEYS:
22820
+ return this.key();
22821
+ default:
22822
+ return [this.key(), this.value()];
22823
+ }
22824
+ }
22825
+ [Symbol.iterator]() {
22826
+ return this;
22827
+ }
22828
+ }
22829
+ var last$1 = (array) => {
22830
+ return array[array.length - 1];
22831
+ };
22832
+ var fuzzySearch = (node, query, maxDistance) => {
22833
+ const results = new Map;
22834
+ if (query === undefined)
22835
+ return results;
22836
+ const n = query.length + 1;
22837
+ const m = n + maxDistance;
22838
+ const matrix = new Uint8Array(m * n).fill(maxDistance + 1);
22839
+ for (let j = 0;j < n; ++j)
22840
+ matrix[j] = j;
22841
+ for (let i = 1;i < m; ++i)
22842
+ matrix[i * n] = i;
22843
+ recurse(node, query, maxDistance, results, matrix, 1, n, "");
22844
+ return results;
22845
+ };
22846
+ var recurse = (node, query, maxDistance, results, matrix, m, n, prefix) => {
22847
+ const offset = m * n;
22848
+ key:
22849
+ for (const key of node.keys()) {
22850
+ if (key === LEAF) {
22851
+ const distance = matrix[offset - 1];
22852
+ if (distance <= maxDistance) {
22853
+ results.set(prefix, [node.get(key), distance]);
22854
+ }
22855
+ } else {
22856
+ let i = m;
22857
+ for (let pos = 0;pos < key.length; ++pos, ++i) {
22858
+ const char = key[pos];
22859
+ const thisRowOffset = n * i;
22860
+ const prevRowOffset = thisRowOffset - n;
22861
+ let minDistance = matrix[thisRowOffset];
22862
+ const jmin = Math.max(0, i - maxDistance - 1);
22863
+ const jmax = Math.min(n - 1, i + maxDistance);
22864
+ for (let j = jmin;j < jmax; ++j) {
22865
+ const different = char !== query[j];
22866
+ const rpl = matrix[prevRowOffset + j] + +different;
22867
+ const del = matrix[prevRowOffset + j + 1] + 1;
22868
+ const ins = matrix[thisRowOffset + j] + 1;
22869
+ const dist = matrix[thisRowOffset + j + 1] = Math.min(rpl, del, ins);
22870
+ if (dist < minDistance)
22871
+ minDistance = dist;
22872
+ }
22873
+ if (minDistance > maxDistance) {
22874
+ continue key;
22875
+ }
22876
+ }
22877
+ recurse(node.get(key), query, maxDistance, results, matrix, i, n, prefix + key);
22878
+ }
22879
+ }
22880
+ };
22881
+
22882
+ class SearchableMap {
22883
+ constructor(tree = new Map, prefix = "") {
22884
+ this._size = undefined;
22885
+ this._tree = tree;
22886
+ this._prefix = prefix;
22887
+ }
22888
+ atPrefix(prefix) {
22889
+ if (!prefix.startsWith(this._prefix)) {
22890
+ throw new Error("Mismatched prefix");
22891
+ }
22892
+ const [node, path] = trackDown(this._tree, prefix.slice(this._prefix.length));
22893
+ if (node === undefined) {
22894
+ const [parentNode, key] = last(path);
22895
+ for (const k of parentNode.keys()) {
22896
+ if (k !== LEAF && k.startsWith(key)) {
22897
+ const node = new Map;
22898
+ node.set(k.slice(key.length), parentNode.get(k));
22899
+ return new SearchableMap(node, prefix);
22900
+ }
22901
+ }
22902
+ }
22903
+ return new SearchableMap(node, prefix);
22904
+ }
22905
+ clear() {
22906
+ this._size = undefined;
22907
+ this._tree.clear();
22908
+ }
22909
+ delete(key) {
22910
+ this._size = undefined;
22911
+ return remove(this._tree, key);
22912
+ }
22913
+ entries() {
22914
+ return new TreeIterator(this, ENTRIES);
22915
+ }
22916
+ forEach(fn) {
22917
+ for (const [key, value] of this) {
22918
+ fn(key, value, this);
22919
+ }
22920
+ }
22921
+ fuzzyGet(key, maxEditDistance) {
22922
+ return fuzzySearch(this._tree, key, maxEditDistance);
22923
+ }
22924
+ get(key) {
22925
+ const node = lookup(this._tree, key);
22926
+ return node !== undefined ? node.get(LEAF) : undefined;
22927
+ }
22928
+ has(key) {
22929
+ const node = lookup(this._tree, key);
22930
+ return node !== undefined && node.has(LEAF);
22931
+ }
22932
+ keys() {
22933
+ return new TreeIterator(this, KEYS);
22934
+ }
22935
+ set(key, value) {
22936
+ if (typeof key !== "string") {
22937
+ throw new Error("key must be a string");
22938
+ }
22939
+ this._size = undefined;
22940
+ const node = createPath(this._tree, key);
22941
+ node.set(LEAF, value);
22942
+ return this;
22943
+ }
22944
+ get size() {
22945
+ if (this._size) {
22946
+ return this._size;
22947
+ }
22948
+ this._size = 0;
22949
+ const iter = this.entries();
22950
+ while (!iter.next().done)
22951
+ this._size += 1;
22952
+ return this._size;
22953
+ }
22954
+ update(key, fn) {
22955
+ if (typeof key !== "string") {
22956
+ throw new Error("key must be a string");
22957
+ }
22958
+ this._size = undefined;
22959
+ const node = createPath(this._tree, key);
22960
+ node.set(LEAF, fn(node.get(LEAF)));
22961
+ return this;
22962
+ }
22963
+ fetch(key, initial) {
22964
+ if (typeof key !== "string") {
22965
+ throw new Error("key must be a string");
22966
+ }
22967
+ this._size = undefined;
22968
+ const node = createPath(this._tree, key);
22969
+ let value = node.get(LEAF);
22970
+ if (value === undefined) {
22971
+ node.set(LEAF, value = initial());
22972
+ }
22973
+ return value;
22974
+ }
22975
+ values() {
22976
+ return new TreeIterator(this, VALUES);
22977
+ }
22978
+ [Symbol.iterator]() {
22979
+ return this.entries();
22980
+ }
22981
+ static from(entries) {
22982
+ const tree = new SearchableMap;
22983
+ for (const [key, value] of entries) {
22984
+ tree.set(key, value);
22985
+ }
22986
+ return tree;
22987
+ }
22988
+ static fromObject(object) {
22989
+ return SearchableMap.from(Object.entries(object));
22990
+ }
22991
+ }
22992
+ var trackDown = (tree, key, path = []) => {
22993
+ if (key.length === 0 || tree == null) {
22994
+ return [tree, path];
22995
+ }
22996
+ for (const k of tree.keys()) {
22997
+ if (k !== LEAF && key.startsWith(k)) {
22998
+ path.push([tree, k]);
22999
+ return trackDown(tree.get(k), key.slice(k.length), path);
23000
+ }
23001
+ }
23002
+ path.push([tree, key]);
23003
+ return trackDown(undefined, "", path);
23004
+ };
23005
+ var lookup = (tree, key) => {
23006
+ if (key.length === 0 || tree == null) {
23007
+ return tree;
23008
+ }
23009
+ for (const k of tree.keys()) {
23010
+ if (k !== LEAF && key.startsWith(k)) {
23011
+ return lookup(tree.get(k), key.slice(k.length));
23012
+ }
23013
+ }
23014
+ };
23015
+ var createPath = (node, key) => {
23016
+ const keyLength = key.length;
23017
+ outer:
23018
+ for (let pos = 0;node && pos < keyLength; ) {
23019
+ for (const k of node.keys()) {
23020
+ if (k !== LEAF && key[pos] === k[0]) {
23021
+ const len = Math.min(keyLength - pos, k.length);
23022
+ let offset = 1;
23023
+ while (offset < len && key[pos + offset] === k[offset])
23024
+ ++offset;
23025
+ const child = node.get(k);
23026
+ if (offset === k.length) {
23027
+ node = child;
23028
+ } else {
23029
+ const intermediate = new Map;
23030
+ intermediate.set(k.slice(offset), child);
23031
+ node.set(key.slice(pos, pos + offset), intermediate);
23032
+ node.delete(k);
23033
+ node = intermediate;
23034
+ }
23035
+ pos += offset;
23036
+ continue outer;
23037
+ }
23038
+ }
23039
+ const child = new Map;
23040
+ node.set(key.slice(pos), child);
23041
+ return child;
23042
+ }
23043
+ return node;
23044
+ };
23045
+ var remove = (tree, key) => {
23046
+ const [node, path] = trackDown(tree, key);
23047
+ if (node === undefined) {
23048
+ return;
23049
+ }
23050
+ node.delete(LEAF);
23051
+ if (node.size === 0) {
23052
+ cleanup(path);
23053
+ } else if (node.size === 1) {
23054
+ const [key, value] = node.entries().next().value;
23055
+ merge2(path, key, value);
23056
+ }
23057
+ };
23058
+ var cleanup = (path) => {
23059
+ if (path.length === 0) {
23060
+ return;
23061
+ }
23062
+ const [node, key] = last(path);
23063
+ node.delete(key);
23064
+ if (node.size === 0) {
23065
+ cleanup(path.slice(0, -1));
23066
+ } else if (node.size === 1) {
23067
+ const [key, value] = node.entries().next().value;
23068
+ if (key !== LEAF) {
23069
+ merge2(path.slice(0, -1), key, value);
23070
+ }
23071
+ }
23072
+ };
23073
+ var merge2 = (path, key, value) => {
23074
+ if (path.length === 0) {
23075
+ return;
23076
+ }
23077
+ const [node, nodeKey] = last(path);
23078
+ node.set(nodeKey + key, value);
23079
+ node.delete(nodeKey);
23080
+ };
23081
+ var last = (array) => {
23082
+ return array[array.length - 1];
23083
+ };
23084
+ var OR = "or";
23085
+ var AND = "and";
23086
+ var AND_NOT = "and_not";
23087
+
23088
+ class MiniSearch {
23089
+ constructor(options) {
23090
+ if ((options === null || options === undefined ? undefined : options.fields) == null) {
23091
+ throw new Error('MiniSearch: option "fields" must be provided');
23092
+ }
23093
+ const autoVacuum = options.autoVacuum == null || options.autoVacuum === true ? defaultAutoVacuumOptions : options.autoVacuum;
23094
+ this._options = {
23095
+ ...defaultOptions,
23096
+ ...options,
23097
+ autoVacuum,
23098
+ searchOptions: { ...defaultSearchOptions, ...options.searchOptions || {} },
23099
+ autoSuggestOptions: { ...defaultAutoSuggestOptions, ...options.autoSuggestOptions || {} }
23100
+ };
23101
+ this._index = new SearchableMap;
23102
+ this._documentCount = 0;
23103
+ this._documentIds = new Map;
23104
+ this._idToShortId = new Map;
23105
+ this._fieldIds = {};
23106
+ this._fieldLength = new Map;
23107
+ this._avgFieldLength = [];
23108
+ this._nextId = 0;
23109
+ this._storedFields = new Map;
23110
+ this._dirtCount = 0;
23111
+ this._currentVacuum = null;
23112
+ this._enqueuedVacuum = null;
23113
+ this._enqueuedVacuumConditions = defaultVacuumConditions;
23114
+ this.addFields(this._options.fields);
23115
+ }
23116
+ add(document) {
23117
+ const { extractField, stringifyField, tokenize, processTerm, fields, idField } = this._options;
23118
+ const id = extractField(document, idField);
23119
+ if (id == null) {
23120
+ throw new Error(`MiniSearch: document does not have ID field "${idField}"`);
23121
+ }
23122
+ if (this._idToShortId.has(id)) {
23123
+ throw new Error(`MiniSearch: duplicate ID ${id}`);
23124
+ }
23125
+ const shortDocumentId = this.addDocumentId(id);
23126
+ this.saveStoredFields(shortDocumentId, document);
23127
+ for (const field of fields) {
23128
+ const fieldValue = extractField(document, field);
23129
+ if (fieldValue == null)
23130
+ continue;
23131
+ const tokens = tokenize(stringifyField(fieldValue, field), field);
23132
+ const fieldId = this._fieldIds[field];
23133
+ const uniqueTerms = new Set(tokens).size;
23134
+ this.addFieldLength(shortDocumentId, fieldId, this._documentCount - 1, uniqueTerms);
23135
+ for (const term of tokens) {
23136
+ const processedTerm = processTerm(term, field);
23137
+ if (Array.isArray(processedTerm)) {
23138
+ for (const t of processedTerm) {
23139
+ this.addTerm(fieldId, shortDocumentId, t);
23140
+ }
23141
+ } else if (processedTerm) {
23142
+ this.addTerm(fieldId, shortDocumentId, processedTerm);
23143
+ }
23144
+ }
23145
+ }
23146
+ }
23147
+ addAll(documents) {
23148
+ for (const document of documents)
23149
+ this.add(document);
23150
+ }
23151
+ addAllAsync(documents, options = {}) {
23152
+ const { chunkSize = 10 } = options;
23153
+ const acc = { chunk: [], promise: Promise.resolve() };
23154
+ const { chunk, promise } = documents.reduce(({ chunk, promise }, document, i) => {
23155
+ chunk.push(document);
23156
+ if ((i + 1) % chunkSize === 0) {
23157
+ return {
23158
+ chunk: [],
23159
+ promise: promise.then(() => new Promise((resolve) => setTimeout(resolve, 0))).then(() => this.addAll(chunk))
23160
+ };
23161
+ } else {
23162
+ return { chunk, promise };
23163
+ }
23164
+ }, acc);
23165
+ return promise.then(() => this.addAll(chunk));
23166
+ }
23167
+ remove(document) {
23168
+ const { tokenize, processTerm, extractField, stringifyField, fields, idField } = this._options;
23169
+ const id = extractField(document, idField);
23170
+ if (id == null) {
23171
+ throw new Error(`MiniSearch: document does not have ID field "${idField}"`);
23172
+ }
23173
+ const shortId = this._idToShortId.get(id);
23174
+ if (shortId == null) {
23175
+ throw new Error(`MiniSearch: cannot remove document with ID ${id}: it is not in the index`);
23176
+ }
23177
+ for (const field of fields) {
23178
+ const fieldValue = extractField(document, field);
23179
+ if (fieldValue == null)
23180
+ continue;
23181
+ const tokens = tokenize(stringifyField(fieldValue, field), field);
23182
+ const fieldId = this._fieldIds[field];
23183
+ const uniqueTerms = new Set(tokens).size;
23184
+ this.removeFieldLength(shortId, fieldId, this._documentCount, uniqueTerms);
23185
+ for (const term of tokens) {
23186
+ const processedTerm = processTerm(term, field);
23187
+ if (Array.isArray(processedTerm)) {
23188
+ for (const t of processedTerm) {
23189
+ this.removeTerm(fieldId, shortId, t);
23190
+ }
23191
+ } else if (processedTerm) {
23192
+ this.removeTerm(fieldId, shortId, processedTerm);
23193
+ }
23194
+ }
23195
+ }
23196
+ this._storedFields.delete(shortId);
23197
+ this._documentIds.delete(shortId);
23198
+ this._idToShortId.delete(id);
23199
+ this._fieldLength.delete(shortId);
23200
+ this._documentCount -= 1;
23201
+ }
23202
+ removeAll(documents) {
23203
+ if (documents) {
23204
+ for (const document of documents)
23205
+ this.remove(document);
23206
+ } else if (arguments.length > 0) {
23207
+ throw new Error("Expected documents to be present. Omit the argument to remove all documents.");
23208
+ } else {
23209
+ this._index = new SearchableMap;
23210
+ this._documentCount = 0;
23211
+ this._documentIds = new Map;
23212
+ this._idToShortId = new Map;
23213
+ this._fieldLength = new Map;
23214
+ this._avgFieldLength = [];
23215
+ this._storedFields = new Map;
23216
+ this._nextId = 0;
23217
+ }
23218
+ }
23219
+ discard(id) {
23220
+ const shortId = this._idToShortId.get(id);
23221
+ if (shortId == null) {
23222
+ throw new Error(`MiniSearch: cannot discard document with ID ${id}: it is not in the index`);
23223
+ }
23224
+ this._idToShortId.delete(id);
23225
+ this._documentIds.delete(shortId);
23226
+ this._storedFields.delete(shortId);
23227
+ (this._fieldLength.get(shortId) || []).forEach((fieldLength, fieldId) => {
23228
+ this.removeFieldLength(shortId, fieldId, this._documentCount, fieldLength);
23229
+ });
23230
+ this._fieldLength.delete(shortId);
23231
+ this._documentCount -= 1;
23232
+ this._dirtCount += 1;
23233
+ this.maybeAutoVacuum();
23234
+ }
23235
+ maybeAutoVacuum() {
23236
+ if (this._options.autoVacuum === false) {
23237
+ return;
23238
+ }
23239
+ const { minDirtFactor, minDirtCount, batchSize, batchWait } = this._options.autoVacuum;
23240
+ this.conditionalVacuum({ batchSize, batchWait }, { minDirtCount, minDirtFactor });
23241
+ }
23242
+ discardAll(ids) {
23243
+ const autoVacuum = this._options.autoVacuum;
23244
+ try {
23245
+ this._options.autoVacuum = false;
23246
+ for (const id of ids) {
23247
+ this.discard(id);
23248
+ }
23249
+ } finally {
23250
+ this._options.autoVacuum = autoVacuum;
23251
+ }
23252
+ this.maybeAutoVacuum();
23253
+ }
23254
+ replace(updatedDocument) {
23255
+ const { idField, extractField } = this._options;
23256
+ const id = extractField(updatedDocument, idField);
23257
+ this.discard(id);
23258
+ this.add(updatedDocument);
23259
+ }
23260
+ vacuum(options = {}) {
23261
+ return this.conditionalVacuum(options);
23262
+ }
23263
+ conditionalVacuum(options, conditions) {
23264
+ if (this._currentVacuum) {
23265
+ this._enqueuedVacuumConditions = this._enqueuedVacuumConditions && conditions;
23266
+ if (this._enqueuedVacuum != null) {
23267
+ return this._enqueuedVacuum;
23268
+ }
23269
+ this._enqueuedVacuum = this._currentVacuum.then(() => {
23270
+ const conditions = this._enqueuedVacuumConditions;
23271
+ this._enqueuedVacuumConditions = defaultVacuumConditions;
23272
+ return this.performVacuuming(options, conditions);
23273
+ });
23274
+ return this._enqueuedVacuum;
23275
+ }
23276
+ if (this.vacuumConditionsMet(conditions) === false) {
23277
+ return Promise.resolve();
23278
+ }
23279
+ this._currentVacuum = this.performVacuuming(options);
23280
+ return this._currentVacuum;
23281
+ }
23282
+ async performVacuuming(options, conditions) {
23283
+ const initialDirtCount = this._dirtCount;
23284
+ if (this.vacuumConditionsMet(conditions)) {
23285
+ const batchSize = options.batchSize || defaultVacuumOptions.batchSize;
23286
+ const batchWait = options.batchWait || defaultVacuumOptions.batchWait;
23287
+ let i = 1;
23288
+ for (const [term, fieldsData] of this._index) {
23289
+ for (const [fieldId, fieldIndex] of fieldsData) {
23290
+ for (const [shortId] of fieldIndex) {
23291
+ if (this._documentIds.has(shortId)) {
23292
+ continue;
23293
+ }
23294
+ if (fieldIndex.size <= 1) {
23295
+ fieldsData.delete(fieldId);
23296
+ } else {
23297
+ fieldIndex.delete(shortId);
23298
+ }
23299
+ }
23300
+ }
23301
+ if (this._index.get(term).size === 0) {
23302
+ this._index.delete(term);
23303
+ }
23304
+ if (i % batchSize === 0) {
23305
+ await new Promise((resolve) => setTimeout(resolve, batchWait));
23306
+ }
23307
+ i += 1;
23308
+ }
23309
+ this._dirtCount -= initialDirtCount;
23310
+ }
23311
+ await null;
23312
+ this._currentVacuum = this._enqueuedVacuum;
23313
+ this._enqueuedVacuum = null;
23314
+ }
23315
+ vacuumConditionsMet(conditions) {
23316
+ if (conditions == null) {
23317
+ return true;
23318
+ }
23319
+ let { minDirtCount, minDirtFactor } = conditions;
23320
+ minDirtCount = minDirtCount || defaultAutoVacuumOptions.minDirtCount;
23321
+ minDirtFactor = minDirtFactor || defaultAutoVacuumOptions.minDirtFactor;
23322
+ return this.dirtCount >= minDirtCount && this.dirtFactor >= minDirtFactor;
23323
+ }
23324
+ get isVacuuming() {
23325
+ return this._currentVacuum != null;
23326
+ }
23327
+ get dirtCount() {
23328
+ return this._dirtCount;
23329
+ }
23330
+ get dirtFactor() {
23331
+ return this._dirtCount / (1 + this._documentCount + this._dirtCount);
23332
+ }
23333
+ has(id) {
23334
+ return this._idToShortId.has(id);
23335
+ }
23336
+ getStoredFields(id) {
23337
+ const shortId = this._idToShortId.get(id);
23338
+ if (shortId == null) {
23339
+ return;
23340
+ }
23341
+ return this._storedFields.get(shortId);
23342
+ }
23343
+ search(query, searchOptions = {}) {
23344
+ const { searchOptions: globalSearchOptions } = this._options;
23345
+ const searchOptionsWithDefaults = { ...globalSearchOptions, ...searchOptions };
23346
+ const rawResults = this.executeQuery(query, searchOptions);
23347
+ const results = [];
23348
+ for (const [docId, { score, terms, match }] of rawResults) {
23349
+ const quality = terms.length || 1;
23350
+ const result = {
23351
+ id: this._documentIds.get(docId),
23352
+ score: score * quality,
23353
+ terms: Object.keys(match),
23354
+ queryTerms: terms,
23355
+ match
23356
+ };
23357
+ Object.assign(result, this._storedFields.get(docId));
23358
+ if (searchOptionsWithDefaults.filter == null || searchOptionsWithDefaults.filter(result)) {
23359
+ results.push(result);
23360
+ }
23361
+ }
23362
+ if (query === MiniSearch.wildcard && searchOptionsWithDefaults.boostDocument == null) {
23363
+ return results;
23364
+ }
23365
+ results.sort(byScore);
23366
+ return results;
23367
+ }
23368
+ autoSuggest(queryString, options = {}) {
23369
+ options = { ...this._options.autoSuggestOptions, ...options };
23370
+ const suggestions = new Map;
23371
+ for (const { score, terms } of this.search(queryString, options)) {
23372
+ const phrase = terms.join(" ");
23373
+ const suggestion = suggestions.get(phrase);
23374
+ if (suggestion != null) {
23375
+ suggestion.score += score;
23376
+ suggestion.count += 1;
23377
+ } else {
23378
+ suggestions.set(phrase, { score, terms, count: 1 });
23379
+ }
23380
+ }
23381
+ const results = [];
23382
+ for (const [suggestion, { score, terms, count }] of suggestions) {
23383
+ results.push({ suggestion, terms, score: score / count });
23384
+ }
23385
+ results.sort(byScore);
23386
+ return results;
23387
+ }
23388
+ get documentCount() {
23389
+ return this._documentCount;
23390
+ }
23391
+ get termCount() {
23392
+ return this._index.size;
23393
+ }
23394
+ static loadJSON(json, options) {
23395
+ if (options == null) {
23396
+ throw new Error("MiniSearch: loadJSON should be given the same options used when serializing the index");
23397
+ }
23398
+ return this.loadJS(JSON.parse(json), options);
23399
+ }
23400
+ static async loadJSONAsync(json, options) {
23401
+ if (options == null) {
23402
+ throw new Error("MiniSearch: loadJSON should be given the same options used when serializing the index");
23403
+ }
23404
+ return this.loadJSAsync(JSON.parse(json), options);
23405
+ }
23406
+ static getDefault(optionName) {
23407
+ if (defaultOptions.hasOwnProperty(optionName)) {
23408
+ return getOwnProperty(defaultOptions, optionName);
23409
+ } else {
23410
+ throw new Error(`MiniSearch: unknown option "${optionName}"`);
23411
+ }
23412
+ }
23413
+ static loadJS(js, options) {
23414
+ const { index, documentIds, fieldLength, storedFields, serializationVersion } = js;
23415
+ const miniSearch = this.instantiateMiniSearch(js, options);
23416
+ miniSearch._documentIds = objectToNumericMap(documentIds);
23417
+ miniSearch._fieldLength = objectToNumericMap(fieldLength);
23418
+ miniSearch._storedFields = objectToNumericMap(storedFields);
23419
+ for (const [shortId, id] of miniSearch._documentIds) {
23420
+ miniSearch._idToShortId.set(id, shortId);
23421
+ }
23422
+ for (const [term, data] of index) {
23423
+ const dataMap = new Map;
23424
+ for (const fieldId of Object.keys(data)) {
23425
+ let indexEntry = data[fieldId];
23426
+ if (serializationVersion === 1) {
23427
+ indexEntry = indexEntry.ds;
23428
+ }
23429
+ dataMap.set(parseInt(fieldId, 10), objectToNumericMap(indexEntry));
23430
+ }
23431
+ miniSearch._index.set(term, dataMap);
23432
+ }
23433
+ return miniSearch;
23434
+ }
23435
+ static async loadJSAsync(js, options) {
23436
+ const { index, documentIds, fieldLength, storedFields, serializationVersion } = js;
23437
+ const miniSearch = this.instantiateMiniSearch(js, options);
23438
+ miniSearch._documentIds = await objectToNumericMapAsync(documentIds);
23439
+ miniSearch._fieldLength = await objectToNumericMapAsync(fieldLength);
23440
+ miniSearch._storedFields = await objectToNumericMapAsync(storedFields);
23441
+ for (const [shortId, id] of miniSearch._documentIds) {
23442
+ miniSearch._idToShortId.set(id, shortId);
23443
+ }
23444
+ let count = 0;
23445
+ for (const [term, data] of index) {
23446
+ const dataMap = new Map;
23447
+ for (const fieldId of Object.keys(data)) {
23448
+ let indexEntry = data[fieldId];
23449
+ if (serializationVersion === 1) {
23450
+ indexEntry = indexEntry.ds;
23451
+ }
23452
+ dataMap.set(parseInt(fieldId, 10), await objectToNumericMapAsync(indexEntry));
23453
+ }
23454
+ if (++count % 1000 === 0)
23455
+ await wait(0);
23456
+ miniSearch._index.set(term, dataMap);
23457
+ }
23458
+ return miniSearch;
23459
+ }
23460
+ static instantiateMiniSearch(js, options) {
23461
+ const { documentCount, nextId, fieldIds, averageFieldLength, dirtCount, serializationVersion } = js;
23462
+ if (serializationVersion !== 1 && serializationVersion !== 2) {
23463
+ throw new Error("MiniSearch: cannot deserialize an index created with an incompatible version");
23464
+ }
23465
+ const miniSearch = new MiniSearch(options);
23466
+ miniSearch._documentCount = documentCount;
23467
+ miniSearch._nextId = nextId;
23468
+ miniSearch._idToShortId = new Map;
23469
+ miniSearch._fieldIds = fieldIds;
23470
+ miniSearch._avgFieldLength = averageFieldLength;
23471
+ miniSearch._dirtCount = dirtCount || 0;
23472
+ miniSearch._index = new SearchableMap;
23473
+ return miniSearch;
23474
+ }
23475
+ executeQuery(query, searchOptions = {}) {
23476
+ if (query === MiniSearch.wildcard) {
23477
+ return this.executeWildcardQuery(searchOptions);
23478
+ }
23479
+ if (typeof query !== "string") {
23480
+ const options = { ...searchOptions, ...query, queries: undefined };
23481
+ const results = query.queries.map((subquery) => this.executeQuery(subquery, options));
23482
+ return this.combineResults(results, options.combineWith);
23483
+ }
23484
+ const { tokenize, processTerm, searchOptions: globalSearchOptions } = this._options;
23485
+ const options = { tokenize, processTerm, ...globalSearchOptions, ...searchOptions };
23486
+ const { tokenize: searchTokenize, processTerm: searchProcessTerm } = options;
23487
+ const terms = searchTokenize(query).flatMap((term) => searchProcessTerm(term)).filter((term) => !!term);
23488
+ const queries = terms.map(termToQuerySpec(options));
23489
+ const results = queries.map((query) => this.executeQuerySpec(query, options));
23490
+ return this.combineResults(results, options.combineWith);
23491
+ }
23492
+ executeQuerySpec(query, searchOptions) {
23493
+ const options = { ...this._options.searchOptions, ...searchOptions };
23494
+ const boosts = (options.fields || this._options.fields).reduce((boosts, field) => ({ ...boosts, [field]: getOwnProperty(options.boost, field) || 1 }), {});
23495
+ const { boostDocument, weights, maxFuzzy, bm25: bm25params } = options;
23496
+ const { fuzzy: fuzzyWeight, prefix: prefixWeight } = { ...defaultSearchOptions.weights, ...weights };
23497
+ const data = this._index.get(query.term);
23498
+ const results = this.termResults(query.term, query.term, 1, query.termBoost, data, boosts, boostDocument, bm25params);
23499
+ let prefixMatches;
23500
+ let fuzzyMatches;
23501
+ if (query.prefix) {
23502
+ prefixMatches = this._index.atPrefix(query.term);
23503
+ }
23504
+ if (query.fuzzy) {
23505
+ const fuzzy = query.fuzzy === true ? 0.2 : query.fuzzy;
23506
+ const maxDistance = fuzzy < 1 ? Math.min(maxFuzzy, Math.round(query.term.length * fuzzy)) : fuzzy;
23507
+ if (maxDistance)
23508
+ fuzzyMatches = this._index.fuzzyGet(query.term, maxDistance);
23509
+ }
23510
+ if (prefixMatches) {
23511
+ for (const [term, data] of prefixMatches) {
23512
+ const distance = term.length - query.term.length;
23513
+ if (!distance) {
23514
+ continue;
23515
+ }
23516
+ fuzzyMatches === null || fuzzyMatches === undefined || fuzzyMatches.delete(term);
23517
+ const weight = prefixWeight * term.length / (term.length + 0.3 * distance);
23518
+ this.termResults(query.term, term, weight, query.termBoost, data, boosts, boostDocument, bm25params, results);
23519
+ }
23520
+ }
23521
+ if (fuzzyMatches) {
23522
+ for (const term of fuzzyMatches.keys()) {
23523
+ const [data, distance] = fuzzyMatches.get(term);
23524
+ if (!distance) {
23525
+ continue;
23526
+ }
23527
+ const weight = fuzzyWeight * term.length / (term.length + distance);
23528
+ this.termResults(query.term, term, weight, query.termBoost, data, boosts, boostDocument, bm25params, results);
23529
+ }
23530
+ }
23531
+ return results;
23532
+ }
23533
+ executeWildcardQuery(searchOptions) {
23534
+ const results = new Map;
23535
+ const options = { ...this._options.searchOptions, ...searchOptions };
23536
+ for (const [shortId, id] of this._documentIds) {
23537
+ const score = options.boostDocument ? options.boostDocument(id, "", this._storedFields.get(shortId)) : 1;
23538
+ results.set(shortId, {
23539
+ score,
23540
+ terms: [],
23541
+ match: {}
23542
+ });
23543
+ }
23544
+ return results;
23545
+ }
23546
+ combineResults(results, combineWith = OR) {
23547
+ if (results.length === 0) {
23548
+ return new Map;
23549
+ }
23550
+ const operator = combineWith.toLowerCase();
23551
+ const combinator = combinators[operator];
23552
+ if (!combinator) {
23553
+ throw new Error(`Invalid combination operator: ${combineWith}`);
23554
+ }
23555
+ return results.reduce(combinator) || new Map;
23556
+ }
23557
+ toJSON() {
23558
+ const index = [];
23559
+ for (const [term, fieldIndex] of this._index) {
23560
+ const data = {};
23561
+ for (const [fieldId, freqs] of fieldIndex) {
23562
+ data[fieldId] = Object.fromEntries(freqs);
23563
+ }
23564
+ index.push([term, data]);
23565
+ }
23566
+ return {
23567
+ documentCount: this._documentCount,
23568
+ nextId: this._nextId,
23569
+ documentIds: Object.fromEntries(this._documentIds),
23570
+ fieldIds: this._fieldIds,
23571
+ fieldLength: Object.fromEntries(this._fieldLength),
23572
+ averageFieldLength: this._avgFieldLength,
23573
+ storedFields: Object.fromEntries(this._storedFields),
23574
+ dirtCount: this._dirtCount,
23575
+ index,
23576
+ serializationVersion: 2
23577
+ };
23578
+ }
23579
+ termResults(sourceTerm, derivedTerm, termWeight, termBoost, fieldTermData, fieldBoosts, boostDocumentFn, bm25params, results = new Map) {
23580
+ if (fieldTermData == null)
23581
+ return results;
23582
+ for (const field of Object.keys(fieldBoosts)) {
23583
+ const fieldBoost = fieldBoosts[field];
23584
+ const fieldId = this._fieldIds[field];
23585
+ const fieldTermFreqs = fieldTermData.get(fieldId);
23586
+ if (fieldTermFreqs == null)
23587
+ continue;
23588
+ let matchingFields = fieldTermFreqs.size;
23589
+ const avgFieldLength = this._avgFieldLength[fieldId];
23590
+ for (const docId of fieldTermFreqs.keys()) {
23591
+ if (!this._documentIds.has(docId)) {
23592
+ this.removeTerm(fieldId, docId, derivedTerm);
23593
+ matchingFields -= 1;
23594
+ continue;
23595
+ }
23596
+ const docBoost = boostDocumentFn ? boostDocumentFn(this._documentIds.get(docId), derivedTerm, this._storedFields.get(docId)) : 1;
23597
+ if (!docBoost)
23598
+ continue;
23599
+ const termFreq = fieldTermFreqs.get(docId);
23600
+ const fieldLength = this._fieldLength.get(docId)[fieldId];
23601
+ const rawScore = calcBM25Score(termFreq, matchingFields, this._documentCount, fieldLength, avgFieldLength, bm25params);
23602
+ const weightedScore = termWeight * termBoost * fieldBoost * docBoost * rawScore;
23603
+ const result = results.get(docId);
23604
+ if (result) {
23605
+ result.score += weightedScore;
23606
+ assignUniqueTerm(result.terms, sourceTerm);
23607
+ const match = getOwnProperty(result.match, derivedTerm);
23608
+ if (match) {
23609
+ match.push(field);
23610
+ } else {
23611
+ result.match[derivedTerm] = [field];
23612
+ }
23613
+ } else {
23614
+ results.set(docId, {
23615
+ score: weightedScore,
23616
+ terms: [sourceTerm],
23617
+ match: { [derivedTerm]: [field] }
23618
+ });
23619
+ }
23620
+ }
23621
+ }
23622
+ return results;
23623
+ }
23624
+ addTerm(fieldId, documentId, term) {
23625
+ const indexData = this._index.fetch(term, createMap);
23626
+ let fieldIndex = indexData.get(fieldId);
23627
+ if (fieldIndex == null) {
23628
+ fieldIndex = new Map;
23629
+ fieldIndex.set(documentId, 1);
23630
+ indexData.set(fieldId, fieldIndex);
23631
+ } else {
23632
+ const docs = fieldIndex.get(documentId);
23633
+ fieldIndex.set(documentId, (docs || 0) + 1);
23634
+ }
23635
+ }
23636
+ removeTerm(fieldId, documentId, term) {
23637
+ if (!this._index.has(term)) {
23638
+ this.warnDocumentChanged(documentId, fieldId, term);
23639
+ return;
23640
+ }
23641
+ const indexData = this._index.fetch(term, createMap);
23642
+ const fieldIndex = indexData.get(fieldId);
23643
+ if (fieldIndex == null || fieldIndex.get(documentId) == null) {
23644
+ this.warnDocumentChanged(documentId, fieldId, term);
23645
+ } else if (fieldIndex.get(documentId) <= 1) {
23646
+ if (fieldIndex.size <= 1) {
23647
+ indexData.delete(fieldId);
23648
+ } else {
23649
+ fieldIndex.delete(documentId);
23650
+ }
23651
+ } else {
23652
+ fieldIndex.set(documentId, fieldIndex.get(documentId) - 1);
23653
+ }
23654
+ if (this._index.get(term).size === 0) {
23655
+ this._index.delete(term);
23656
+ }
23657
+ }
23658
+ warnDocumentChanged(shortDocumentId, fieldId, term) {
23659
+ for (const fieldName of Object.keys(this._fieldIds)) {
23660
+ if (this._fieldIds[fieldName] === fieldId) {
23661
+ this._options.logger("warn", `MiniSearch: document with ID ${this._documentIds.get(shortDocumentId)} has changed before removal: term "${term}" was not present in field "${fieldName}". Removing a document after it has changed can corrupt the index!`, "version_conflict");
23662
+ return;
23663
+ }
23664
+ }
23665
+ }
23666
+ addDocumentId(documentId) {
23667
+ const shortDocumentId = this._nextId;
23668
+ this._idToShortId.set(documentId, shortDocumentId);
23669
+ this._documentIds.set(shortDocumentId, documentId);
23670
+ this._documentCount += 1;
23671
+ this._nextId += 1;
23672
+ return shortDocumentId;
23673
+ }
23674
+ addFields(fields) {
23675
+ for (let i = 0;i < fields.length; i++) {
23676
+ this._fieldIds[fields[i]] = i;
23677
+ }
23678
+ }
23679
+ addFieldLength(documentId, fieldId, count, length) {
23680
+ let fieldLengths = this._fieldLength.get(documentId);
23681
+ if (fieldLengths == null)
23682
+ this._fieldLength.set(documentId, fieldLengths = []);
23683
+ fieldLengths[fieldId] = length;
23684
+ const averageFieldLength = this._avgFieldLength[fieldId] || 0;
23685
+ const totalFieldLength = averageFieldLength * count + length;
23686
+ this._avgFieldLength[fieldId] = totalFieldLength / (count + 1);
23687
+ }
23688
+ removeFieldLength(documentId, fieldId, count, length) {
23689
+ if (count === 1) {
23690
+ this._avgFieldLength[fieldId] = 0;
23691
+ return;
23692
+ }
23693
+ const totalFieldLength = this._avgFieldLength[fieldId] * count - length;
23694
+ this._avgFieldLength[fieldId] = totalFieldLength / (count - 1);
23695
+ }
23696
+ saveStoredFields(documentId, doc) {
23697
+ const { storeFields, extractField } = this._options;
23698
+ if (storeFields == null || storeFields.length === 0) {
23699
+ return;
23700
+ }
23701
+ let documentFields = this._storedFields.get(documentId);
23702
+ if (documentFields == null)
23703
+ this._storedFields.set(documentId, documentFields = {});
23704
+ for (const fieldName of storeFields) {
23705
+ const fieldValue = extractField(doc, fieldName);
23706
+ if (fieldValue !== undefined)
23707
+ documentFields[fieldName] = fieldValue;
23708
+ }
23709
+ }
23710
+ }
23711
+ MiniSearch.wildcard = Symbol("*");
23712
+ var getOwnProperty = (object, property) => Object.prototype.hasOwnProperty.call(object, property) ? object[property] : undefined;
23713
+ var combinators = {
23714
+ [OR]: (a, b) => {
23715
+ for (const docId of b.keys()) {
23716
+ const existing = a.get(docId);
23717
+ if (existing == null) {
23718
+ a.set(docId, b.get(docId));
23719
+ } else {
23720
+ const { score, terms, match } = b.get(docId);
23721
+ existing.score = existing.score + score;
23722
+ existing.match = Object.assign(existing.match, match);
23723
+ assignUniqueTerms(existing.terms, terms);
23724
+ }
23725
+ }
23726
+ return a;
23727
+ },
23728
+ [AND]: (a, b) => {
23729
+ const combined = new Map;
23730
+ for (const docId of b.keys()) {
23731
+ const existing = a.get(docId);
23732
+ if (existing == null)
23733
+ continue;
23734
+ const { score, terms, match } = b.get(docId);
23735
+ assignUniqueTerms(existing.terms, terms);
23736
+ combined.set(docId, {
23737
+ score: existing.score + score,
23738
+ terms: existing.terms,
23739
+ match: Object.assign(existing.match, match)
23740
+ });
23741
+ }
23742
+ return combined;
23743
+ },
23744
+ [AND_NOT]: (a, b) => {
23745
+ for (const docId of b.keys())
23746
+ a.delete(docId);
23747
+ return a;
23748
+ }
23749
+ };
23750
+ var defaultBM25params = { k: 1.2, b: 0.7, d: 0.5 };
23751
+ var calcBM25Score = (termFreq, matchingCount, totalCount, fieldLength, avgFieldLength, bm25params) => {
23752
+ const { k, b, d } = bm25params;
23753
+ const invDocFreq = Math.log(1 + (totalCount - matchingCount + 0.5) / (matchingCount + 0.5));
23754
+ return invDocFreq * (d + termFreq * (k + 1) / (termFreq + k * (1 - b + b * fieldLength / avgFieldLength)));
23755
+ };
23756
+ var termToQuerySpec = (options) => (term, i, terms) => {
23757
+ const fuzzy = typeof options.fuzzy === "function" ? options.fuzzy(term, i, terms) : options.fuzzy || false;
23758
+ const prefix = typeof options.prefix === "function" ? options.prefix(term, i, terms) : options.prefix === true;
23759
+ const termBoost = typeof options.boostTerm === "function" ? options.boostTerm(term, i, terms) : 1;
23760
+ return { term, fuzzy, prefix, termBoost };
23761
+ };
23762
+ var defaultOptions = {
23763
+ idField: "id",
23764
+ extractField: (document, fieldName) => document[fieldName],
23765
+ stringifyField: (fieldValue, fieldName) => fieldValue.toString(),
23766
+ tokenize: (text) => text.split(SPACE_OR_PUNCTUATION),
23767
+ processTerm: (term) => term.toLowerCase(),
23768
+ fields: undefined,
23769
+ searchOptions: undefined,
23770
+ storeFields: [],
23771
+ logger: (level, message) => {
23772
+ if (typeof (console === null || console === undefined ? undefined : console[level]) === "function")
23773
+ console[level](message);
23774
+ },
23775
+ autoVacuum: true
23776
+ };
23777
+ var defaultSearchOptions = {
23778
+ combineWith: OR,
23779
+ prefix: false,
23780
+ fuzzy: false,
23781
+ maxFuzzy: 6,
23782
+ boost: {},
23783
+ weights: { fuzzy: 0.45, prefix: 0.375 },
23784
+ bm25: defaultBM25params
23785
+ };
23786
+ var defaultAutoSuggestOptions = {
23787
+ combineWith: AND,
23788
+ prefix: (term, i, terms) => i === terms.length - 1
23789
+ };
23790
+ var defaultVacuumOptions = { batchSize: 1000, batchWait: 10 };
23791
+ var defaultVacuumConditions = { minDirtFactor: 0.1, minDirtCount: 20 };
23792
+ var defaultAutoVacuumOptions = { ...defaultVacuumOptions, ...defaultVacuumConditions };
23793
+ var assignUniqueTerm = (target, term) => {
23794
+ if (!target.includes(term))
23795
+ target.push(term);
23796
+ };
23797
+ var assignUniqueTerms = (target, source) => {
23798
+ for (const term of source) {
23799
+ if (!target.includes(term))
23800
+ target.push(term);
23801
+ }
23802
+ };
23803
+ var byScore = ({ score: a }, { score: b }) => b - a;
23804
+ var createMap = () => new Map;
23805
+ var objectToNumericMap = (object) => {
23806
+ const map = new Map;
23807
+ for (const key of Object.keys(object)) {
23808
+ map.set(parseInt(key, 10), object[key]);
23809
+ }
23810
+ return map;
23811
+ };
23812
+ var objectToNumericMapAsync = async (object) => {
23813
+ const map = new Map;
23814
+ let count = 0;
23815
+ for (const key of Object.keys(object)) {
23816
+ map.set(parseInt(key, 10), object[key]);
23817
+ if (++count % 1000 === 0) {
23818
+ await wait(0);
23819
+ }
23820
+ }
23821
+ return map;
23822
+ };
23823
+ var wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
23824
+ var SPACE_OR_PUNCTUATION = /[\n\r\p{Z}\p{P}]+/u;
23825
+
23826
+ // src/commands/search.ts
23827
+ var MAX_RESULTS = 5;
23828
+ var FIELD_BOOST = { command: 8, summary: 5, context: 0.5 };
23829
+ var STOP_WORDS = new Set("a am an and are as at be by can do does for from how i in into is it me my of on or so that the this to what when where which why with you your".split(" "));
23830
+ var MIN_EXPANDED_TERM_LENGTH = 3;
23831
+ var MIN_FUZZY_TERM_LENGTH = 5;
23832
+ var SEARCH_OPTIONS = {
23833
+ boost: FIELD_BOOST,
23834
+ processTerm: (term) => {
23835
+ const lower = term.toLowerCase();
23836
+ return STOP_WORDS.has(lower) ? null : lower;
23837
+ },
23838
+ prefix: (term) => term.length >= MIN_EXPANDED_TERM_LENGTH,
23839
+ fuzzy: (term) => term.length >= MIN_FUZZY_TERM_LENGTH ? 0.2 : false
23840
+ };
23841
+ var TRAILING_PARENTHETICAL = /\s*\([^)]*\)\s*$/;
23842
+ var COLUMNS3 = [
23843
+ { header: "command", value: (result) => result.command },
23844
+ { header: "summary", value: (result) => result.summary }
23845
+ ];
23846
+ function isHidden(command) {
23847
+ return command._hidden === true;
23848
+ }
23849
+ function visibleSubcommands(command) {
23850
+ return command.commands.filter((child) => child.name() !== "help" && !isHidden(child));
23851
+ }
23852
+ function collectDocuments(command, path, ancestors, exclude) {
23853
+ const children = visibleSubcommands(command);
23854
+ if (children.length === 0) {
23855
+ const display = command.description();
23856
+ return [
23857
+ {
23858
+ command: ["sim", ...path].join(" "),
23859
+ display,
23860
+ summary: display.replace(TRAILING_PARENTHETICAL, ""),
23861
+ context: [
23862
+ ...ancestors,
23863
+ ...command.registeredArguments.map((argument) => `${argument.name()} ${argument.description}`.trim()),
23864
+ ...command.options.filter((option) => !option.hidden).map((option) => `${option.long ?? option.short ?? ""} ${option.description}`.trim())
23865
+ ].join(" ")
23866
+ }
23867
+ ];
23868
+ }
23869
+ const nextAncestors = path.length > 0 ? [...ancestors, command.description()] : ancestors;
23870
+ return children.filter((child) => child !== exclude).flatMap((child) => collectDocuments(child, [...path, child.name()], nextAncestors, exclude));
23871
+ }
23872
+ function searchCommands(program, query, exclude) {
23873
+ const index = new MiniSearch({
23874
+ fields: ["command", "summary", "context"],
23875
+ storeFields: ["command", "display"],
23876
+ idField: "command"
23877
+ });
23878
+ index.addAll(collectDocuments(program, [], [], exclude));
23879
+ return index.search(query, SEARCH_OPTIONS).slice(0, MAX_RESULTS).map((hit) => ({ command: hit.command, summary: hit.display }));
23880
+ }
23881
+ function searchCommand() {
23882
+ return new Command("search").description("Find the command for a task, described in plain words").argument("<query...>", 'What you want to do, e.g. "cancel a workflow run"').addHelpText("after", `
23883
+ Ranks the commands this CLI ships, locally; your query is never sent anywhere.
23884
+ Returns the ${MAX_RESULTS} best matches. Run \`<command> --help\` on one for its flags.
23885
+
23886
+ Examples:
23887
+ $ sim cli search "cancel a running workflow"
23888
+ $ sim cli search list table rows`).action((words, _options, command) => {
23889
+ let program = command;
23890
+ while (program.parent)
23891
+ program = program.parent;
23892
+ const results = searchCommands(program, words.join(" "), command);
23893
+ printList(profileFrom(command).output, results, COLUMNS3);
23894
+ });
23895
+ }
23896
+ function cliCommand() {
23897
+ return new Command("cli").description("Discover commands in this CLI").addCommand(searchCommand());
23898
+ }
23899
+
22761
23900
  // src/terminal/secret-input.ts
22762
23901
  import { emitKeypressEvents } from "node:readline";
22763
23902
  var MAX_SECRET_LENGTH = 65536;
@@ -22919,7 +24058,7 @@ function attachSecretCommands(program) {
22919
24058
  if (!secrets)
22920
24059
  throw new Error("The generated secrets command group is missing");
22921
24060
  const redactionSpellings = new Set;
22922
- secrets.command("set").argument("<name>", "Secret name, as referenced in workflows").description(describeOperation(V2_OPERATIONS.setSecret, "Create or replace a named secret")).addOption(new Option("--scope <scope>", "Secret ownership scope (required)").choices([...SECRET_SCOPES]).makeOptionMandatory()).option("--value <value|@file>", "Secret value. Passing it inline exposes it to shell history and process listings; @path reads it from a file and @- from stdin, verbatim — a trailing newline is part of the value, so write the file with printf rather than echo. Prefix a literal leading @ with a second one").option("--description <description>", "What the secret is for, shown to teammates; workspace scope only. Omit to leave an existing description unchanged").option("--unredacted", `${V2_OPERATIONS.setSecret.body.unredacted.describe} Pass --no-unredacted to restore redaction`).option("--no-unredacted", "Send --unredacted as false").on("option:unredacted", () => redactionSpellings.add("--unredacted")).on("option:no-unredacted", () => redactionSpellings.add("--no-unredacted")).action((name, options, command) => setSecret(name, options, command, redactionSpellings));
24061
+ secrets.command("set").argument("<name>", "Secret name, as referenced in workflows").description(describeOperation(V2_OPERATIONS.setSecret, "Create or replace a named secret, such as an API key or environment variable")).addOption(new Option("--scope <scope>", "Secret ownership scope (required)").choices([...SECRET_SCOPES]).makeOptionMandatory()).option("--value <value|@file>", "Secret value. Passing it inline exposes it to shell history and process listings; @path reads it from a file and @- from stdin, verbatim — a trailing newline is part of the value, so write the file with printf rather than echo. Prefix a literal leading @ with a second one").option("--description <description>", "What the secret is for, shown to teammates; workspace scope only. Omit to leave an existing description unchanged").option("--unredacted", `${V2_OPERATIONS.setSecret.body.unredacted.describe} Pass --no-unredacted to restore redaction`).option("--no-unredacted", "Send --unredacted as false").on("option:unredacted", () => redactionSpellings.add("--unredacted")).on("option:no-unredacted", () => redactionSpellings.add("--no-unredacted")).action((name, options, command) => setSecret(name, options, command, redactionSpellings));
22923
24062
  }
22924
24063
 
22925
24064
  // src/telemetry/transport.ts
@@ -23165,19 +24304,28 @@ or custom-tool ID can open with a dash, which reads as a flag; put -- in front
23165
24304
  of it, as in sim audit-logs get -- -HlDcD1z76nK6R4crsUp0.
23166
24305
 
23167
24306
  Examples:
24307
+ $ sim cli search "cancel a workflow run" Find the command for a task
23168
24308
  $ sim login Authorize the default profile
23169
24309
  $ sim login --profile dev --endpoint http://localhost:3000
23170
24310
  $ sim profile add acme --workspace 7e2d9c14-6b83-4a55-8f01-c4d3e9a76b28
23171
24311
  $ sim workflows list
23172
24312
  $ sim logs list --level error --limit 20
23173
- $ sim configure --set-output json Save a profile output default
23174
- $ sim --output json tables get tbl_9f3c1a05d4b7426e8c2f0917ab35de64
24313
+ $ sim configure --set-output table Prefer tables over the JSON default
24314
+ $ sim --output table tables get tbl_9f3c1a05d4b7426e8c2f0917ab35de64
23175
24315
  $ sim knowledge search --query "refund policy" --kb 4c1b7f60-2d55-4a3e-9c18-70b6ea2f9d31
23176
24316
  $ sim workflows export 3a9e21d8-5f47-4c0b-b2ea-91d7c6034ef8 > wf.json
23177
24317
  $ sim workflows import --workflow @wf.json
23178
24318
  $ sim knowledge export 4c1b7f60-2d55-4a3e-9c18-70b6ea2f9d31 -o ./kb.simkb.zip
23179
24319
  $ sim whoami --profile dev
23180
24320
  `;
24321
+ var AGENT_DISCOVERY_NOTE = `=== AGENT COMMAND DISCOVERY ===
24322
+ Do not explore commands by chaining nested --help calls. Instead run:
24323
+ sim cli search "<describe the task you want to accomplish>"
24324
+ It returns the 5 best-matching commands, each with a one-line summary. Pick the
24325
+ best match rather than repeating similar searches, then run
24326
+ \`<command> --help\` for its flags.
24327
+ === END AGENT COMMAND DISCOVERY ===
24328
+ `;
23181
24329
  var ROOT_VALUE_FLAGS = new Set([
23182
24330
  "-P",
23183
24331
  "--profile",
@@ -23215,6 +24363,7 @@ function addVersionOption(program) {
23215
24363
  program.version(cliVersion(), "-V, --version [none]", "output the version number (takes no value)");
23216
24364
  }
23217
24365
  function buildProgram(options = {}) {
24366
+ const env = options.env ?? process.env;
23218
24367
  const program = options.program ?? new Command;
23219
24368
  program.name("sim").description(PROGRAM_DESCRIPTION);
23220
24369
  if (options.version !== false)
@@ -23231,6 +24380,7 @@ function buildProgram(options = {}) {
23231
24380
  const update = updateCommand();
23232
24381
  program.addCommand(update);
23233
24382
  program.addCommand(telemetryCommand());
24383
+ program.addCommand(cliCommand());
23234
24384
  for (const command of buildGeneratedCommands()) {
23235
24385
  program.addCommand(command);
23236
24386
  }
@@ -23238,6 +24388,7 @@ function buildProgram(options = {}) {
23238
24388
  attachProtocolCommands(program);
23239
24389
  attachSecretCommands(program);
23240
24390
  program.addHelpText("after", options.helpText ?? HELP_EPILOGUE);
24391
+ program.addHelpText("beforeAll", ({ command }) => detectCodingAgent(env) !== undefined && command.commands.length > 0 ? AGENT_DISCOVERY_NOTE : "");
23241
24392
  program.hook("preAction", async (_program, command) => {
23242
24393
  if (command === update)
23243
24394
  return;