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/runtime.js CHANGED
@@ -3550,6 +3550,7 @@ function removeSection(doc, name) {
3550
3550
  var DEFAULT_PROFILE = "default";
3551
3551
  var DEFAULT_ENDPOINT = "https://www.sim.ai";
3552
3552
  var OUTPUT_FORMATS = ["table", "json", "yaml", "text"];
3553
+ var DEFAULT_OUTPUT_FORMAT = "json";
3553
3554
  var FORBIDDEN_IN_VALUE_GLOBAL = new RegExp(FORBIDDEN_IN_VALUE.source, "g");
3554
3555
  function redact(value) {
3555
3556
  return value.replace(FORBIDDEN_IN_VALUE_GLOBAL, " ");
@@ -3900,7 +3901,7 @@ function resolveProfile(overrides = {}) {
3900
3901
  ["flag", overrides.output],
3901
3902
  ["env", process.env.SIM_OUTPUT],
3902
3903
  ["config", config.output]
3903
- ], "table", "default");
3904
+ ], DEFAULT_OUTPUT_FORMAT, "default");
3904
3905
  if (!OUTPUT_FORMATS.includes(output.value)) {
3905
3906
  throw new ProfileConfigError(`Unknown output format "${redact(String(output.value))}" from ${output.source}. Use one of: ${OUTPUT_FORMATS.join(", ")}`);
3906
3907
  }
@@ -17055,7 +17056,7 @@ Waiting for you to approve in the browser…`));
17055
17056
  }
17056
17057
  }
17057
17058
  function loginCommand() {
17058
- 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) => {
17059
+ 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) => {
17059
17060
  const profile = profileFrom(command, { allowUnknownProfile: true });
17060
17061
  const authProfile = resolveAuthenticationProfileName(profile.name);
17061
17062
  if (authProfile !== profile.name) {
@@ -17389,7 +17390,7 @@ function profileListingContext(command) {
17389
17390
  throw error;
17390
17391
  return {
17391
17392
  activeName: named || DEFAULT_PROFILE,
17392
- output: requested ? requested : "table"
17393
+ output: requested ? requested : DEFAULT_OUTPUT_FORMAT
17393
17394
  };
17394
17395
  }
17395
17396
  }
@@ -17437,7 +17438,7 @@ function quoteProfileArgument(name) {
17437
17438
  return `'${redacted.replaceAll("'", "'\\''")}'`;
17438
17439
  }
17439
17440
  function configureCommand() {
17440
- 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) => {
17441
+ 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) => {
17441
17442
  const globals = globalsOf(command);
17442
17443
  const selectedProfile = globals.profile || process.env.SIM_PROFILE;
17443
17444
  const profileArg = selectedProfile ? ` --profile ${quoteProfileArgument(selectedProfile)}` : "";
@@ -17593,7 +17594,7 @@ var CLI_CONTRACT = {
17593
17594
  getBillingStatus: {
17594
17595
  command: "billing status",
17595
17596
  allWorkspaces: true,
17596
- describe: "Show billing status and current-period credit usage (credits and storage require an OAuth login or personal API key)",
17597
+ describe: "Show billing status, credits spent this period, and storage used (credits and storage require an OAuth login or personal API key)",
17597
17598
  fields: [
17598
17599
  { header: "plan" },
17599
17600
  { header: "status" },
@@ -17716,6 +17717,7 @@ var CLI_CONTRACT = {
17716
17717
  confirm: "This archives the knowledge base and every document in it; restore with `knowledge restore`."
17717
17718
  },
17718
17719
  deleteKnowledgeDocument: {
17720
+ describe: "Delete a document from a knowledge base",
17719
17721
  pathArgumentNames: KNOWLEDGE_BASE_PATH_ARGUMENT,
17720
17722
  confirm: "This deletes the document and its embeddings."
17721
17723
  },
@@ -17754,6 +17756,7 @@ var CLI_CONTRACT = {
17754
17756
  ]
17755
17757
  },
17756
17758
  listLogs: {
17759
+ describe: "List run logs, such as failed or errored runs, by workflow, trigger or time",
17757
17760
  flags: {
17758
17761
  ...LOG_LIST_FILTER_FLAGS,
17759
17762
  details: {
@@ -17866,6 +17869,7 @@ var CLI_CONTRACT = {
17866
17869
  },
17867
17870
  applyWorkflowOperations: {
17868
17871
  command: "workflows operations apply",
17872
+ describe: "Edit a workflow’s blocks, connections and settings with a batch of operations",
17869
17873
  confirm: "This edits the draft graph: the batch adds, edits, or deletes blocks and their edges as written.",
17870
17874
  flags: {
17871
17875
  operations: { json: true, describe: WORKFLOW_OPERATIONS_HELP },
@@ -17968,6 +17972,7 @@ var CLI_CONTRACT = {
17968
17972
  },
17969
17973
  queryRows: {
17970
17974
  command: "tables rows query",
17975
+ describe: "Query rows with a filter and sort",
17971
17976
  flags: {
17972
17977
  predicate: { name: "filter", json: true, describe: TABLE_READ_FILTER_HELP },
17973
17978
  sort: { json: true, describe: TABLE_SORT_HELP }
@@ -21367,7 +21372,7 @@ async function downloadToOutput(command, operation, pathParams, options) {
21367
21372
  });
21368
21373
  }
21369
21374
  function attachFileGet(files) {
21370
- 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));
21375
+ 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));
21371
21376
  }
21372
21377
  function attachFileVersionDownload(versions) {
21373
21378
  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));
@@ -21914,7 +21919,7 @@ function inSeconds(ms) {
21914
21919
  return Math.round(ms / 100) / 10;
21915
21920
  }
21916
21921
  function attachLogsFollow(logs) {
21917
- 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([
21922
+ 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([
21918
21923
  ...V2_OPERATIONS.listLogs.query.level.values
21919
21924
  ])).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", `
21920
21925
  Each run prints once, when it is first seen, so its status is the status it had
@@ -22809,6 +22814,1140 @@ function attachProtocolCommands(program) {
22809
22814
  attachChat(program);
22810
22815
  }
22811
22816
 
22817
+ // ../../node_modules/minisearch/dist/es/index.js
22818
+ var ENTRIES = "ENTRIES";
22819
+ var KEYS = "KEYS";
22820
+ var VALUES = "VALUES";
22821
+ var LEAF = "";
22822
+
22823
+ class TreeIterator {
22824
+ constructor(set, type) {
22825
+ const node = set._tree;
22826
+ const keys = Array.from(node.keys());
22827
+ this.set = set;
22828
+ this._type = type;
22829
+ this._path = keys.length > 0 ? [{ node, keys }] : [];
22830
+ }
22831
+ next() {
22832
+ const value = this.dive();
22833
+ this.backtrack();
22834
+ return value;
22835
+ }
22836
+ dive() {
22837
+ if (this._path.length === 0) {
22838
+ return { done: true, value: undefined };
22839
+ }
22840
+ const { node, keys } = last$1(this._path);
22841
+ if (last$1(keys) === LEAF) {
22842
+ return { done: false, value: this.result() };
22843
+ }
22844
+ const child = node.get(last$1(keys));
22845
+ this._path.push({ node: child, keys: Array.from(child.keys()) });
22846
+ return this.dive();
22847
+ }
22848
+ backtrack() {
22849
+ if (this._path.length === 0) {
22850
+ return;
22851
+ }
22852
+ const keys = last$1(this._path).keys;
22853
+ keys.pop();
22854
+ if (keys.length > 0) {
22855
+ return;
22856
+ }
22857
+ this._path.pop();
22858
+ this.backtrack();
22859
+ }
22860
+ key() {
22861
+ return this.set._prefix + this._path.map(({ keys }) => last$1(keys)).filter((key) => key !== LEAF).join("");
22862
+ }
22863
+ value() {
22864
+ return last$1(this._path).node.get(LEAF);
22865
+ }
22866
+ result() {
22867
+ switch (this._type) {
22868
+ case VALUES:
22869
+ return this.value();
22870
+ case KEYS:
22871
+ return this.key();
22872
+ default:
22873
+ return [this.key(), this.value()];
22874
+ }
22875
+ }
22876
+ [Symbol.iterator]() {
22877
+ return this;
22878
+ }
22879
+ }
22880
+ var last$1 = (array) => {
22881
+ return array[array.length - 1];
22882
+ };
22883
+ var fuzzySearch = (node, query, maxDistance) => {
22884
+ const results = new Map;
22885
+ if (query === undefined)
22886
+ return results;
22887
+ const n = query.length + 1;
22888
+ const m = n + maxDistance;
22889
+ const matrix = new Uint8Array(m * n).fill(maxDistance + 1);
22890
+ for (let j = 0;j < n; ++j)
22891
+ matrix[j] = j;
22892
+ for (let i = 1;i < m; ++i)
22893
+ matrix[i * n] = i;
22894
+ recurse(node, query, maxDistance, results, matrix, 1, n, "");
22895
+ return results;
22896
+ };
22897
+ var recurse = (node, query, maxDistance, results, matrix, m, n, prefix) => {
22898
+ const offset = m * n;
22899
+ key:
22900
+ for (const key of node.keys()) {
22901
+ if (key === LEAF) {
22902
+ const distance = matrix[offset - 1];
22903
+ if (distance <= maxDistance) {
22904
+ results.set(prefix, [node.get(key), distance]);
22905
+ }
22906
+ } else {
22907
+ let i = m;
22908
+ for (let pos = 0;pos < key.length; ++pos, ++i) {
22909
+ const char = key[pos];
22910
+ const thisRowOffset = n * i;
22911
+ const prevRowOffset = thisRowOffset - n;
22912
+ let minDistance = matrix[thisRowOffset];
22913
+ const jmin = Math.max(0, i - maxDistance - 1);
22914
+ const jmax = Math.min(n - 1, i + maxDistance);
22915
+ for (let j = jmin;j < jmax; ++j) {
22916
+ const different = char !== query[j];
22917
+ const rpl = matrix[prevRowOffset + j] + +different;
22918
+ const del = matrix[prevRowOffset + j + 1] + 1;
22919
+ const ins = matrix[thisRowOffset + j] + 1;
22920
+ const dist = matrix[thisRowOffset + j + 1] = Math.min(rpl, del, ins);
22921
+ if (dist < minDistance)
22922
+ minDistance = dist;
22923
+ }
22924
+ if (minDistance > maxDistance) {
22925
+ continue key;
22926
+ }
22927
+ }
22928
+ recurse(node.get(key), query, maxDistance, results, matrix, i, n, prefix + key);
22929
+ }
22930
+ }
22931
+ };
22932
+
22933
+ class SearchableMap {
22934
+ constructor(tree = new Map, prefix = "") {
22935
+ this._size = undefined;
22936
+ this._tree = tree;
22937
+ this._prefix = prefix;
22938
+ }
22939
+ atPrefix(prefix) {
22940
+ if (!prefix.startsWith(this._prefix)) {
22941
+ throw new Error("Mismatched prefix");
22942
+ }
22943
+ const [node, path] = trackDown(this._tree, prefix.slice(this._prefix.length));
22944
+ if (node === undefined) {
22945
+ const [parentNode, key] = last(path);
22946
+ for (const k of parentNode.keys()) {
22947
+ if (k !== LEAF && k.startsWith(key)) {
22948
+ const node = new Map;
22949
+ node.set(k.slice(key.length), parentNode.get(k));
22950
+ return new SearchableMap(node, prefix);
22951
+ }
22952
+ }
22953
+ }
22954
+ return new SearchableMap(node, prefix);
22955
+ }
22956
+ clear() {
22957
+ this._size = undefined;
22958
+ this._tree.clear();
22959
+ }
22960
+ delete(key) {
22961
+ this._size = undefined;
22962
+ return remove(this._tree, key);
22963
+ }
22964
+ entries() {
22965
+ return new TreeIterator(this, ENTRIES);
22966
+ }
22967
+ forEach(fn) {
22968
+ for (const [key, value] of this) {
22969
+ fn(key, value, this);
22970
+ }
22971
+ }
22972
+ fuzzyGet(key, maxEditDistance) {
22973
+ return fuzzySearch(this._tree, key, maxEditDistance);
22974
+ }
22975
+ get(key) {
22976
+ const node = lookup(this._tree, key);
22977
+ return node !== undefined ? node.get(LEAF) : undefined;
22978
+ }
22979
+ has(key) {
22980
+ const node = lookup(this._tree, key);
22981
+ return node !== undefined && node.has(LEAF);
22982
+ }
22983
+ keys() {
22984
+ return new TreeIterator(this, KEYS);
22985
+ }
22986
+ set(key, value) {
22987
+ if (typeof key !== "string") {
22988
+ throw new Error("key must be a string");
22989
+ }
22990
+ this._size = undefined;
22991
+ const node = createPath(this._tree, key);
22992
+ node.set(LEAF, value);
22993
+ return this;
22994
+ }
22995
+ get size() {
22996
+ if (this._size) {
22997
+ return this._size;
22998
+ }
22999
+ this._size = 0;
23000
+ const iter = this.entries();
23001
+ while (!iter.next().done)
23002
+ this._size += 1;
23003
+ return this._size;
23004
+ }
23005
+ update(key, fn) {
23006
+ if (typeof key !== "string") {
23007
+ throw new Error("key must be a string");
23008
+ }
23009
+ this._size = undefined;
23010
+ const node = createPath(this._tree, key);
23011
+ node.set(LEAF, fn(node.get(LEAF)));
23012
+ return this;
23013
+ }
23014
+ fetch(key, initial) {
23015
+ if (typeof key !== "string") {
23016
+ throw new Error("key must be a string");
23017
+ }
23018
+ this._size = undefined;
23019
+ const node = createPath(this._tree, key);
23020
+ let value = node.get(LEAF);
23021
+ if (value === undefined) {
23022
+ node.set(LEAF, value = initial());
23023
+ }
23024
+ return value;
23025
+ }
23026
+ values() {
23027
+ return new TreeIterator(this, VALUES);
23028
+ }
23029
+ [Symbol.iterator]() {
23030
+ return this.entries();
23031
+ }
23032
+ static from(entries) {
23033
+ const tree = new SearchableMap;
23034
+ for (const [key, value] of entries) {
23035
+ tree.set(key, value);
23036
+ }
23037
+ return tree;
23038
+ }
23039
+ static fromObject(object) {
23040
+ return SearchableMap.from(Object.entries(object));
23041
+ }
23042
+ }
23043
+ var trackDown = (tree, key, path = []) => {
23044
+ if (key.length === 0 || tree == null) {
23045
+ return [tree, path];
23046
+ }
23047
+ for (const k of tree.keys()) {
23048
+ if (k !== LEAF && key.startsWith(k)) {
23049
+ path.push([tree, k]);
23050
+ return trackDown(tree.get(k), key.slice(k.length), path);
23051
+ }
23052
+ }
23053
+ path.push([tree, key]);
23054
+ return trackDown(undefined, "", path);
23055
+ };
23056
+ var lookup = (tree, key) => {
23057
+ if (key.length === 0 || tree == null) {
23058
+ return tree;
23059
+ }
23060
+ for (const k of tree.keys()) {
23061
+ if (k !== LEAF && key.startsWith(k)) {
23062
+ return lookup(tree.get(k), key.slice(k.length));
23063
+ }
23064
+ }
23065
+ };
23066
+ var createPath = (node, key) => {
23067
+ const keyLength = key.length;
23068
+ outer:
23069
+ for (let pos = 0;node && pos < keyLength; ) {
23070
+ for (const k of node.keys()) {
23071
+ if (k !== LEAF && key[pos] === k[0]) {
23072
+ const len = Math.min(keyLength - pos, k.length);
23073
+ let offset = 1;
23074
+ while (offset < len && key[pos + offset] === k[offset])
23075
+ ++offset;
23076
+ const child = node.get(k);
23077
+ if (offset === k.length) {
23078
+ node = child;
23079
+ } else {
23080
+ const intermediate = new Map;
23081
+ intermediate.set(k.slice(offset), child);
23082
+ node.set(key.slice(pos, pos + offset), intermediate);
23083
+ node.delete(k);
23084
+ node = intermediate;
23085
+ }
23086
+ pos += offset;
23087
+ continue outer;
23088
+ }
23089
+ }
23090
+ const child = new Map;
23091
+ node.set(key.slice(pos), child);
23092
+ return child;
23093
+ }
23094
+ return node;
23095
+ };
23096
+ var remove = (tree, key) => {
23097
+ const [node, path] = trackDown(tree, key);
23098
+ if (node === undefined) {
23099
+ return;
23100
+ }
23101
+ node.delete(LEAF);
23102
+ if (node.size === 0) {
23103
+ cleanup(path);
23104
+ } else if (node.size === 1) {
23105
+ const [key, value] = node.entries().next().value;
23106
+ merge2(path, key, value);
23107
+ }
23108
+ };
23109
+ var cleanup = (path) => {
23110
+ if (path.length === 0) {
23111
+ return;
23112
+ }
23113
+ const [node, key] = last(path);
23114
+ node.delete(key);
23115
+ if (node.size === 0) {
23116
+ cleanup(path.slice(0, -1));
23117
+ } else if (node.size === 1) {
23118
+ const [key, value] = node.entries().next().value;
23119
+ if (key !== LEAF) {
23120
+ merge2(path.slice(0, -1), key, value);
23121
+ }
23122
+ }
23123
+ };
23124
+ var merge2 = (path, key, value) => {
23125
+ if (path.length === 0) {
23126
+ return;
23127
+ }
23128
+ const [node, nodeKey] = last(path);
23129
+ node.set(nodeKey + key, value);
23130
+ node.delete(nodeKey);
23131
+ };
23132
+ var last = (array) => {
23133
+ return array[array.length - 1];
23134
+ };
23135
+ var OR = "or";
23136
+ var AND = "and";
23137
+ var AND_NOT = "and_not";
23138
+
23139
+ class MiniSearch {
23140
+ constructor(options) {
23141
+ if ((options === null || options === undefined ? undefined : options.fields) == null) {
23142
+ throw new Error('MiniSearch: option "fields" must be provided');
23143
+ }
23144
+ const autoVacuum = options.autoVacuum == null || options.autoVacuum === true ? defaultAutoVacuumOptions : options.autoVacuum;
23145
+ this._options = {
23146
+ ...defaultOptions,
23147
+ ...options,
23148
+ autoVacuum,
23149
+ searchOptions: { ...defaultSearchOptions, ...options.searchOptions || {} },
23150
+ autoSuggestOptions: { ...defaultAutoSuggestOptions, ...options.autoSuggestOptions || {} }
23151
+ };
23152
+ this._index = new SearchableMap;
23153
+ this._documentCount = 0;
23154
+ this._documentIds = new Map;
23155
+ this._idToShortId = new Map;
23156
+ this._fieldIds = {};
23157
+ this._fieldLength = new Map;
23158
+ this._avgFieldLength = [];
23159
+ this._nextId = 0;
23160
+ this._storedFields = new Map;
23161
+ this._dirtCount = 0;
23162
+ this._currentVacuum = null;
23163
+ this._enqueuedVacuum = null;
23164
+ this._enqueuedVacuumConditions = defaultVacuumConditions;
23165
+ this.addFields(this._options.fields);
23166
+ }
23167
+ add(document) {
23168
+ const { extractField, stringifyField, tokenize, processTerm, 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
+ if (this._idToShortId.has(id)) {
23174
+ throw new Error(`MiniSearch: duplicate ID ${id}`);
23175
+ }
23176
+ const shortDocumentId = this.addDocumentId(id);
23177
+ this.saveStoredFields(shortDocumentId, document);
23178
+ for (const field of fields) {
23179
+ const fieldValue = extractField(document, field);
23180
+ if (fieldValue == null)
23181
+ continue;
23182
+ const tokens = tokenize(stringifyField(fieldValue, field), field);
23183
+ const fieldId = this._fieldIds[field];
23184
+ const uniqueTerms = new Set(tokens).size;
23185
+ this.addFieldLength(shortDocumentId, fieldId, this._documentCount - 1, uniqueTerms);
23186
+ for (const term of tokens) {
23187
+ const processedTerm = processTerm(term, field);
23188
+ if (Array.isArray(processedTerm)) {
23189
+ for (const t of processedTerm) {
23190
+ this.addTerm(fieldId, shortDocumentId, t);
23191
+ }
23192
+ } else if (processedTerm) {
23193
+ this.addTerm(fieldId, shortDocumentId, processedTerm);
23194
+ }
23195
+ }
23196
+ }
23197
+ }
23198
+ addAll(documents) {
23199
+ for (const document of documents)
23200
+ this.add(document);
23201
+ }
23202
+ addAllAsync(documents, options = {}) {
23203
+ const { chunkSize = 10 } = options;
23204
+ const acc = { chunk: [], promise: Promise.resolve() };
23205
+ const { chunk, promise } = documents.reduce(({ chunk, promise }, document, i) => {
23206
+ chunk.push(document);
23207
+ if ((i + 1) % chunkSize === 0) {
23208
+ return {
23209
+ chunk: [],
23210
+ promise: promise.then(() => new Promise((resolve) => setTimeout(resolve, 0))).then(() => this.addAll(chunk))
23211
+ };
23212
+ } else {
23213
+ return { chunk, promise };
23214
+ }
23215
+ }, acc);
23216
+ return promise.then(() => this.addAll(chunk));
23217
+ }
23218
+ remove(document) {
23219
+ const { tokenize, processTerm, extractField, stringifyField, fields, idField } = this._options;
23220
+ const id = extractField(document, idField);
23221
+ if (id == null) {
23222
+ throw new Error(`MiniSearch: document does not have ID field "${idField}"`);
23223
+ }
23224
+ const shortId = this._idToShortId.get(id);
23225
+ if (shortId == null) {
23226
+ throw new Error(`MiniSearch: cannot remove document with ID ${id}: it is not in the index`);
23227
+ }
23228
+ for (const field of fields) {
23229
+ const fieldValue = extractField(document, field);
23230
+ if (fieldValue == null)
23231
+ continue;
23232
+ const tokens = tokenize(stringifyField(fieldValue, field), field);
23233
+ const fieldId = this._fieldIds[field];
23234
+ const uniqueTerms = new Set(tokens).size;
23235
+ this.removeFieldLength(shortId, fieldId, this._documentCount, uniqueTerms);
23236
+ for (const term of tokens) {
23237
+ const processedTerm = processTerm(term, field);
23238
+ if (Array.isArray(processedTerm)) {
23239
+ for (const t of processedTerm) {
23240
+ this.removeTerm(fieldId, shortId, t);
23241
+ }
23242
+ } else if (processedTerm) {
23243
+ this.removeTerm(fieldId, shortId, processedTerm);
23244
+ }
23245
+ }
23246
+ }
23247
+ this._storedFields.delete(shortId);
23248
+ this._documentIds.delete(shortId);
23249
+ this._idToShortId.delete(id);
23250
+ this._fieldLength.delete(shortId);
23251
+ this._documentCount -= 1;
23252
+ }
23253
+ removeAll(documents) {
23254
+ if (documents) {
23255
+ for (const document of documents)
23256
+ this.remove(document);
23257
+ } else if (arguments.length > 0) {
23258
+ throw new Error("Expected documents to be present. Omit the argument to remove all documents.");
23259
+ } else {
23260
+ this._index = new SearchableMap;
23261
+ this._documentCount = 0;
23262
+ this._documentIds = new Map;
23263
+ this._idToShortId = new Map;
23264
+ this._fieldLength = new Map;
23265
+ this._avgFieldLength = [];
23266
+ this._storedFields = new Map;
23267
+ this._nextId = 0;
23268
+ }
23269
+ }
23270
+ discard(id) {
23271
+ const shortId = this._idToShortId.get(id);
23272
+ if (shortId == null) {
23273
+ throw new Error(`MiniSearch: cannot discard document with ID ${id}: it is not in the index`);
23274
+ }
23275
+ this._idToShortId.delete(id);
23276
+ this._documentIds.delete(shortId);
23277
+ this._storedFields.delete(shortId);
23278
+ (this._fieldLength.get(shortId) || []).forEach((fieldLength, fieldId) => {
23279
+ this.removeFieldLength(shortId, fieldId, this._documentCount, fieldLength);
23280
+ });
23281
+ this._fieldLength.delete(shortId);
23282
+ this._documentCount -= 1;
23283
+ this._dirtCount += 1;
23284
+ this.maybeAutoVacuum();
23285
+ }
23286
+ maybeAutoVacuum() {
23287
+ if (this._options.autoVacuum === false) {
23288
+ return;
23289
+ }
23290
+ const { minDirtFactor, minDirtCount, batchSize, batchWait } = this._options.autoVacuum;
23291
+ this.conditionalVacuum({ batchSize, batchWait }, { minDirtCount, minDirtFactor });
23292
+ }
23293
+ discardAll(ids) {
23294
+ const autoVacuum = this._options.autoVacuum;
23295
+ try {
23296
+ this._options.autoVacuum = false;
23297
+ for (const id of ids) {
23298
+ this.discard(id);
23299
+ }
23300
+ } finally {
23301
+ this._options.autoVacuum = autoVacuum;
23302
+ }
23303
+ this.maybeAutoVacuum();
23304
+ }
23305
+ replace(updatedDocument) {
23306
+ const { idField, extractField } = this._options;
23307
+ const id = extractField(updatedDocument, idField);
23308
+ this.discard(id);
23309
+ this.add(updatedDocument);
23310
+ }
23311
+ vacuum(options = {}) {
23312
+ return this.conditionalVacuum(options);
23313
+ }
23314
+ conditionalVacuum(options, conditions) {
23315
+ if (this._currentVacuum) {
23316
+ this._enqueuedVacuumConditions = this._enqueuedVacuumConditions && conditions;
23317
+ if (this._enqueuedVacuum != null) {
23318
+ return this._enqueuedVacuum;
23319
+ }
23320
+ this._enqueuedVacuum = this._currentVacuum.then(() => {
23321
+ const conditions = this._enqueuedVacuumConditions;
23322
+ this._enqueuedVacuumConditions = defaultVacuumConditions;
23323
+ return this.performVacuuming(options, conditions);
23324
+ });
23325
+ return this._enqueuedVacuum;
23326
+ }
23327
+ if (this.vacuumConditionsMet(conditions) === false) {
23328
+ return Promise.resolve();
23329
+ }
23330
+ this._currentVacuum = this.performVacuuming(options);
23331
+ return this._currentVacuum;
23332
+ }
23333
+ async performVacuuming(options, conditions) {
23334
+ const initialDirtCount = this._dirtCount;
23335
+ if (this.vacuumConditionsMet(conditions)) {
23336
+ const batchSize = options.batchSize || defaultVacuumOptions.batchSize;
23337
+ const batchWait = options.batchWait || defaultVacuumOptions.batchWait;
23338
+ let i = 1;
23339
+ for (const [term, fieldsData] of this._index) {
23340
+ for (const [fieldId, fieldIndex] of fieldsData) {
23341
+ for (const [shortId] of fieldIndex) {
23342
+ if (this._documentIds.has(shortId)) {
23343
+ continue;
23344
+ }
23345
+ if (fieldIndex.size <= 1) {
23346
+ fieldsData.delete(fieldId);
23347
+ } else {
23348
+ fieldIndex.delete(shortId);
23349
+ }
23350
+ }
23351
+ }
23352
+ if (this._index.get(term).size === 0) {
23353
+ this._index.delete(term);
23354
+ }
23355
+ if (i % batchSize === 0) {
23356
+ await new Promise((resolve) => setTimeout(resolve, batchWait));
23357
+ }
23358
+ i += 1;
23359
+ }
23360
+ this._dirtCount -= initialDirtCount;
23361
+ }
23362
+ await null;
23363
+ this._currentVacuum = this._enqueuedVacuum;
23364
+ this._enqueuedVacuum = null;
23365
+ }
23366
+ vacuumConditionsMet(conditions) {
23367
+ if (conditions == null) {
23368
+ return true;
23369
+ }
23370
+ let { minDirtCount, minDirtFactor } = conditions;
23371
+ minDirtCount = minDirtCount || defaultAutoVacuumOptions.minDirtCount;
23372
+ minDirtFactor = minDirtFactor || defaultAutoVacuumOptions.minDirtFactor;
23373
+ return this.dirtCount >= minDirtCount && this.dirtFactor >= minDirtFactor;
23374
+ }
23375
+ get isVacuuming() {
23376
+ return this._currentVacuum != null;
23377
+ }
23378
+ get dirtCount() {
23379
+ return this._dirtCount;
23380
+ }
23381
+ get dirtFactor() {
23382
+ return this._dirtCount / (1 + this._documentCount + this._dirtCount);
23383
+ }
23384
+ has(id) {
23385
+ return this._idToShortId.has(id);
23386
+ }
23387
+ getStoredFields(id) {
23388
+ const shortId = this._idToShortId.get(id);
23389
+ if (shortId == null) {
23390
+ return;
23391
+ }
23392
+ return this._storedFields.get(shortId);
23393
+ }
23394
+ search(query, searchOptions = {}) {
23395
+ const { searchOptions: globalSearchOptions } = this._options;
23396
+ const searchOptionsWithDefaults = { ...globalSearchOptions, ...searchOptions };
23397
+ const rawResults = this.executeQuery(query, searchOptions);
23398
+ const results = [];
23399
+ for (const [docId, { score, terms, match }] of rawResults) {
23400
+ const quality = terms.length || 1;
23401
+ const result = {
23402
+ id: this._documentIds.get(docId),
23403
+ score: score * quality,
23404
+ terms: Object.keys(match),
23405
+ queryTerms: terms,
23406
+ match
23407
+ };
23408
+ Object.assign(result, this._storedFields.get(docId));
23409
+ if (searchOptionsWithDefaults.filter == null || searchOptionsWithDefaults.filter(result)) {
23410
+ results.push(result);
23411
+ }
23412
+ }
23413
+ if (query === MiniSearch.wildcard && searchOptionsWithDefaults.boostDocument == null) {
23414
+ return results;
23415
+ }
23416
+ results.sort(byScore);
23417
+ return results;
23418
+ }
23419
+ autoSuggest(queryString, options = {}) {
23420
+ options = { ...this._options.autoSuggestOptions, ...options };
23421
+ const suggestions = new Map;
23422
+ for (const { score, terms } of this.search(queryString, options)) {
23423
+ const phrase = terms.join(" ");
23424
+ const suggestion = suggestions.get(phrase);
23425
+ if (suggestion != null) {
23426
+ suggestion.score += score;
23427
+ suggestion.count += 1;
23428
+ } else {
23429
+ suggestions.set(phrase, { score, terms, count: 1 });
23430
+ }
23431
+ }
23432
+ const results = [];
23433
+ for (const [suggestion, { score, terms, count }] of suggestions) {
23434
+ results.push({ suggestion, terms, score: score / count });
23435
+ }
23436
+ results.sort(byScore);
23437
+ return results;
23438
+ }
23439
+ get documentCount() {
23440
+ return this._documentCount;
23441
+ }
23442
+ get termCount() {
23443
+ return this._index.size;
23444
+ }
23445
+ static loadJSON(json, options) {
23446
+ if (options == null) {
23447
+ throw new Error("MiniSearch: loadJSON should be given the same options used when serializing the index");
23448
+ }
23449
+ return this.loadJS(JSON.parse(json), options);
23450
+ }
23451
+ static async loadJSONAsync(json, options) {
23452
+ if (options == null) {
23453
+ throw new Error("MiniSearch: loadJSON should be given the same options used when serializing the index");
23454
+ }
23455
+ return this.loadJSAsync(JSON.parse(json), options);
23456
+ }
23457
+ static getDefault(optionName) {
23458
+ if (defaultOptions.hasOwnProperty(optionName)) {
23459
+ return getOwnProperty(defaultOptions, optionName);
23460
+ } else {
23461
+ throw new Error(`MiniSearch: unknown option "${optionName}"`);
23462
+ }
23463
+ }
23464
+ static loadJS(js, options) {
23465
+ const { index, documentIds, fieldLength, storedFields, serializationVersion } = js;
23466
+ const miniSearch = this.instantiateMiniSearch(js, options);
23467
+ miniSearch._documentIds = objectToNumericMap(documentIds);
23468
+ miniSearch._fieldLength = objectToNumericMap(fieldLength);
23469
+ miniSearch._storedFields = objectToNumericMap(storedFields);
23470
+ for (const [shortId, id] of miniSearch._documentIds) {
23471
+ miniSearch._idToShortId.set(id, shortId);
23472
+ }
23473
+ for (const [term, data] of index) {
23474
+ const dataMap = new Map;
23475
+ for (const fieldId of Object.keys(data)) {
23476
+ let indexEntry = data[fieldId];
23477
+ if (serializationVersion === 1) {
23478
+ indexEntry = indexEntry.ds;
23479
+ }
23480
+ dataMap.set(parseInt(fieldId, 10), objectToNumericMap(indexEntry));
23481
+ }
23482
+ miniSearch._index.set(term, dataMap);
23483
+ }
23484
+ return miniSearch;
23485
+ }
23486
+ static async loadJSAsync(js, options) {
23487
+ const { index, documentIds, fieldLength, storedFields, serializationVersion } = js;
23488
+ const miniSearch = this.instantiateMiniSearch(js, options);
23489
+ miniSearch._documentIds = await objectToNumericMapAsync(documentIds);
23490
+ miniSearch._fieldLength = await objectToNumericMapAsync(fieldLength);
23491
+ miniSearch._storedFields = await objectToNumericMapAsync(storedFields);
23492
+ for (const [shortId, id] of miniSearch._documentIds) {
23493
+ miniSearch._idToShortId.set(id, shortId);
23494
+ }
23495
+ let count = 0;
23496
+ for (const [term, data] of index) {
23497
+ const dataMap = new Map;
23498
+ for (const fieldId of Object.keys(data)) {
23499
+ let indexEntry = data[fieldId];
23500
+ if (serializationVersion === 1) {
23501
+ indexEntry = indexEntry.ds;
23502
+ }
23503
+ dataMap.set(parseInt(fieldId, 10), await objectToNumericMapAsync(indexEntry));
23504
+ }
23505
+ if (++count % 1000 === 0)
23506
+ await wait(0);
23507
+ miniSearch._index.set(term, dataMap);
23508
+ }
23509
+ return miniSearch;
23510
+ }
23511
+ static instantiateMiniSearch(js, options) {
23512
+ const { documentCount, nextId, fieldIds, averageFieldLength, dirtCount, serializationVersion } = js;
23513
+ if (serializationVersion !== 1 && serializationVersion !== 2) {
23514
+ throw new Error("MiniSearch: cannot deserialize an index created with an incompatible version");
23515
+ }
23516
+ const miniSearch = new MiniSearch(options);
23517
+ miniSearch._documentCount = documentCount;
23518
+ miniSearch._nextId = nextId;
23519
+ miniSearch._idToShortId = new Map;
23520
+ miniSearch._fieldIds = fieldIds;
23521
+ miniSearch._avgFieldLength = averageFieldLength;
23522
+ miniSearch._dirtCount = dirtCount || 0;
23523
+ miniSearch._index = new SearchableMap;
23524
+ return miniSearch;
23525
+ }
23526
+ executeQuery(query, searchOptions = {}) {
23527
+ if (query === MiniSearch.wildcard) {
23528
+ return this.executeWildcardQuery(searchOptions);
23529
+ }
23530
+ if (typeof query !== "string") {
23531
+ const options = { ...searchOptions, ...query, queries: undefined };
23532
+ const results = query.queries.map((subquery) => this.executeQuery(subquery, options));
23533
+ return this.combineResults(results, options.combineWith);
23534
+ }
23535
+ const { tokenize, processTerm, searchOptions: globalSearchOptions } = this._options;
23536
+ const options = { tokenize, processTerm, ...globalSearchOptions, ...searchOptions };
23537
+ const { tokenize: searchTokenize, processTerm: searchProcessTerm } = options;
23538
+ const terms = searchTokenize(query).flatMap((term) => searchProcessTerm(term)).filter((term) => !!term);
23539
+ const queries = terms.map(termToQuerySpec(options));
23540
+ const results = queries.map((query) => this.executeQuerySpec(query, options));
23541
+ return this.combineResults(results, options.combineWith);
23542
+ }
23543
+ executeQuerySpec(query, searchOptions) {
23544
+ const options = { ...this._options.searchOptions, ...searchOptions };
23545
+ const boosts = (options.fields || this._options.fields).reduce((boosts, field) => ({ ...boosts, [field]: getOwnProperty(options.boost, field) || 1 }), {});
23546
+ const { boostDocument, weights, maxFuzzy, bm25: bm25params } = options;
23547
+ const { fuzzy: fuzzyWeight, prefix: prefixWeight } = { ...defaultSearchOptions.weights, ...weights };
23548
+ const data = this._index.get(query.term);
23549
+ const results = this.termResults(query.term, query.term, 1, query.termBoost, data, boosts, boostDocument, bm25params);
23550
+ let prefixMatches;
23551
+ let fuzzyMatches;
23552
+ if (query.prefix) {
23553
+ prefixMatches = this._index.atPrefix(query.term);
23554
+ }
23555
+ if (query.fuzzy) {
23556
+ const fuzzy = query.fuzzy === true ? 0.2 : query.fuzzy;
23557
+ const maxDistance = fuzzy < 1 ? Math.min(maxFuzzy, Math.round(query.term.length * fuzzy)) : fuzzy;
23558
+ if (maxDistance)
23559
+ fuzzyMatches = this._index.fuzzyGet(query.term, maxDistance);
23560
+ }
23561
+ if (prefixMatches) {
23562
+ for (const [term, data] of prefixMatches) {
23563
+ const distance = term.length - query.term.length;
23564
+ if (!distance) {
23565
+ continue;
23566
+ }
23567
+ fuzzyMatches === null || fuzzyMatches === undefined || fuzzyMatches.delete(term);
23568
+ const weight = prefixWeight * term.length / (term.length + 0.3 * distance);
23569
+ this.termResults(query.term, term, weight, query.termBoost, data, boosts, boostDocument, bm25params, results);
23570
+ }
23571
+ }
23572
+ if (fuzzyMatches) {
23573
+ for (const term of fuzzyMatches.keys()) {
23574
+ const [data, distance] = fuzzyMatches.get(term);
23575
+ if (!distance) {
23576
+ continue;
23577
+ }
23578
+ const weight = fuzzyWeight * term.length / (term.length + distance);
23579
+ this.termResults(query.term, term, weight, query.termBoost, data, boosts, boostDocument, bm25params, results);
23580
+ }
23581
+ }
23582
+ return results;
23583
+ }
23584
+ executeWildcardQuery(searchOptions) {
23585
+ const results = new Map;
23586
+ const options = { ...this._options.searchOptions, ...searchOptions };
23587
+ for (const [shortId, id] of this._documentIds) {
23588
+ const score = options.boostDocument ? options.boostDocument(id, "", this._storedFields.get(shortId)) : 1;
23589
+ results.set(shortId, {
23590
+ score,
23591
+ terms: [],
23592
+ match: {}
23593
+ });
23594
+ }
23595
+ return results;
23596
+ }
23597
+ combineResults(results, combineWith = OR) {
23598
+ if (results.length === 0) {
23599
+ return new Map;
23600
+ }
23601
+ const operator = combineWith.toLowerCase();
23602
+ const combinator = combinators[operator];
23603
+ if (!combinator) {
23604
+ throw new Error(`Invalid combination operator: ${combineWith}`);
23605
+ }
23606
+ return results.reduce(combinator) || new Map;
23607
+ }
23608
+ toJSON() {
23609
+ const index = [];
23610
+ for (const [term, fieldIndex] of this._index) {
23611
+ const data = {};
23612
+ for (const [fieldId, freqs] of fieldIndex) {
23613
+ data[fieldId] = Object.fromEntries(freqs);
23614
+ }
23615
+ index.push([term, data]);
23616
+ }
23617
+ return {
23618
+ documentCount: this._documentCount,
23619
+ nextId: this._nextId,
23620
+ documentIds: Object.fromEntries(this._documentIds),
23621
+ fieldIds: this._fieldIds,
23622
+ fieldLength: Object.fromEntries(this._fieldLength),
23623
+ averageFieldLength: this._avgFieldLength,
23624
+ storedFields: Object.fromEntries(this._storedFields),
23625
+ dirtCount: this._dirtCount,
23626
+ index,
23627
+ serializationVersion: 2
23628
+ };
23629
+ }
23630
+ termResults(sourceTerm, derivedTerm, termWeight, termBoost, fieldTermData, fieldBoosts, boostDocumentFn, bm25params, results = new Map) {
23631
+ if (fieldTermData == null)
23632
+ return results;
23633
+ for (const field of Object.keys(fieldBoosts)) {
23634
+ const fieldBoost = fieldBoosts[field];
23635
+ const fieldId = this._fieldIds[field];
23636
+ const fieldTermFreqs = fieldTermData.get(fieldId);
23637
+ if (fieldTermFreqs == null)
23638
+ continue;
23639
+ let matchingFields = fieldTermFreqs.size;
23640
+ const avgFieldLength = this._avgFieldLength[fieldId];
23641
+ for (const docId of fieldTermFreqs.keys()) {
23642
+ if (!this._documentIds.has(docId)) {
23643
+ this.removeTerm(fieldId, docId, derivedTerm);
23644
+ matchingFields -= 1;
23645
+ continue;
23646
+ }
23647
+ const docBoost = boostDocumentFn ? boostDocumentFn(this._documentIds.get(docId), derivedTerm, this._storedFields.get(docId)) : 1;
23648
+ if (!docBoost)
23649
+ continue;
23650
+ const termFreq = fieldTermFreqs.get(docId);
23651
+ const fieldLength = this._fieldLength.get(docId)[fieldId];
23652
+ const rawScore = calcBM25Score(termFreq, matchingFields, this._documentCount, fieldLength, avgFieldLength, bm25params);
23653
+ const weightedScore = termWeight * termBoost * fieldBoost * docBoost * rawScore;
23654
+ const result = results.get(docId);
23655
+ if (result) {
23656
+ result.score += weightedScore;
23657
+ assignUniqueTerm(result.terms, sourceTerm);
23658
+ const match = getOwnProperty(result.match, derivedTerm);
23659
+ if (match) {
23660
+ match.push(field);
23661
+ } else {
23662
+ result.match[derivedTerm] = [field];
23663
+ }
23664
+ } else {
23665
+ results.set(docId, {
23666
+ score: weightedScore,
23667
+ terms: [sourceTerm],
23668
+ match: { [derivedTerm]: [field] }
23669
+ });
23670
+ }
23671
+ }
23672
+ }
23673
+ return results;
23674
+ }
23675
+ addTerm(fieldId, documentId, term) {
23676
+ const indexData = this._index.fetch(term, createMap);
23677
+ let fieldIndex = indexData.get(fieldId);
23678
+ if (fieldIndex == null) {
23679
+ fieldIndex = new Map;
23680
+ fieldIndex.set(documentId, 1);
23681
+ indexData.set(fieldId, fieldIndex);
23682
+ } else {
23683
+ const docs = fieldIndex.get(documentId);
23684
+ fieldIndex.set(documentId, (docs || 0) + 1);
23685
+ }
23686
+ }
23687
+ removeTerm(fieldId, documentId, term) {
23688
+ if (!this._index.has(term)) {
23689
+ this.warnDocumentChanged(documentId, fieldId, term);
23690
+ return;
23691
+ }
23692
+ const indexData = this._index.fetch(term, createMap);
23693
+ const fieldIndex = indexData.get(fieldId);
23694
+ if (fieldIndex == null || fieldIndex.get(documentId) == null) {
23695
+ this.warnDocumentChanged(documentId, fieldId, term);
23696
+ } else if (fieldIndex.get(documentId) <= 1) {
23697
+ if (fieldIndex.size <= 1) {
23698
+ indexData.delete(fieldId);
23699
+ } else {
23700
+ fieldIndex.delete(documentId);
23701
+ }
23702
+ } else {
23703
+ fieldIndex.set(documentId, fieldIndex.get(documentId) - 1);
23704
+ }
23705
+ if (this._index.get(term).size === 0) {
23706
+ this._index.delete(term);
23707
+ }
23708
+ }
23709
+ warnDocumentChanged(shortDocumentId, fieldId, term) {
23710
+ for (const fieldName of Object.keys(this._fieldIds)) {
23711
+ if (this._fieldIds[fieldName] === fieldId) {
23712
+ 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");
23713
+ return;
23714
+ }
23715
+ }
23716
+ }
23717
+ addDocumentId(documentId) {
23718
+ const shortDocumentId = this._nextId;
23719
+ this._idToShortId.set(documentId, shortDocumentId);
23720
+ this._documentIds.set(shortDocumentId, documentId);
23721
+ this._documentCount += 1;
23722
+ this._nextId += 1;
23723
+ return shortDocumentId;
23724
+ }
23725
+ addFields(fields) {
23726
+ for (let i = 0;i < fields.length; i++) {
23727
+ this._fieldIds[fields[i]] = i;
23728
+ }
23729
+ }
23730
+ addFieldLength(documentId, fieldId, count, length) {
23731
+ let fieldLengths = this._fieldLength.get(documentId);
23732
+ if (fieldLengths == null)
23733
+ this._fieldLength.set(documentId, fieldLengths = []);
23734
+ fieldLengths[fieldId] = length;
23735
+ const averageFieldLength = this._avgFieldLength[fieldId] || 0;
23736
+ const totalFieldLength = averageFieldLength * count + length;
23737
+ this._avgFieldLength[fieldId] = totalFieldLength / (count + 1);
23738
+ }
23739
+ removeFieldLength(documentId, fieldId, count, length) {
23740
+ if (count === 1) {
23741
+ this._avgFieldLength[fieldId] = 0;
23742
+ return;
23743
+ }
23744
+ const totalFieldLength = this._avgFieldLength[fieldId] * count - length;
23745
+ this._avgFieldLength[fieldId] = totalFieldLength / (count - 1);
23746
+ }
23747
+ saveStoredFields(documentId, doc) {
23748
+ const { storeFields, extractField } = this._options;
23749
+ if (storeFields == null || storeFields.length === 0) {
23750
+ return;
23751
+ }
23752
+ let documentFields = this._storedFields.get(documentId);
23753
+ if (documentFields == null)
23754
+ this._storedFields.set(documentId, documentFields = {});
23755
+ for (const fieldName of storeFields) {
23756
+ const fieldValue = extractField(doc, fieldName);
23757
+ if (fieldValue !== undefined)
23758
+ documentFields[fieldName] = fieldValue;
23759
+ }
23760
+ }
23761
+ }
23762
+ MiniSearch.wildcard = Symbol("*");
23763
+ var getOwnProperty = (object, property) => Object.prototype.hasOwnProperty.call(object, property) ? object[property] : undefined;
23764
+ var combinators = {
23765
+ [OR]: (a, b) => {
23766
+ for (const docId of b.keys()) {
23767
+ const existing = a.get(docId);
23768
+ if (existing == null) {
23769
+ a.set(docId, b.get(docId));
23770
+ } else {
23771
+ const { score, terms, match } = b.get(docId);
23772
+ existing.score = existing.score + score;
23773
+ existing.match = Object.assign(existing.match, match);
23774
+ assignUniqueTerms(existing.terms, terms);
23775
+ }
23776
+ }
23777
+ return a;
23778
+ },
23779
+ [AND]: (a, b) => {
23780
+ const combined = new Map;
23781
+ for (const docId of b.keys()) {
23782
+ const existing = a.get(docId);
23783
+ if (existing == null)
23784
+ continue;
23785
+ const { score, terms, match } = b.get(docId);
23786
+ assignUniqueTerms(existing.terms, terms);
23787
+ combined.set(docId, {
23788
+ score: existing.score + score,
23789
+ terms: existing.terms,
23790
+ match: Object.assign(existing.match, match)
23791
+ });
23792
+ }
23793
+ return combined;
23794
+ },
23795
+ [AND_NOT]: (a, b) => {
23796
+ for (const docId of b.keys())
23797
+ a.delete(docId);
23798
+ return a;
23799
+ }
23800
+ };
23801
+ var defaultBM25params = { k: 1.2, b: 0.7, d: 0.5 };
23802
+ var calcBM25Score = (termFreq, matchingCount, totalCount, fieldLength, avgFieldLength, bm25params) => {
23803
+ const { k, b, d } = bm25params;
23804
+ const invDocFreq = Math.log(1 + (totalCount - matchingCount + 0.5) / (matchingCount + 0.5));
23805
+ return invDocFreq * (d + termFreq * (k + 1) / (termFreq + k * (1 - b + b * fieldLength / avgFieldLength)));
23806
+ };
23807
+ var termToQuerySpec = (options) => (term, i, terms) => {
23808
+ const fuzzy = typeof options.fuzzy === "function" ? options.fuzzy(term, i, terms) : options.fuzzy || false;
23809
+ const prefix = typeof options.prefix === "function" ? options.prefix(term, i, terms) : options.prefix === true;
23810
+ const termBoost = typeof options.boostTerm === "function" ? options.boostTerm(term, i, terms) : 1;
23811
+ return { term, fuzzy, prefix, termBoost };
23812
+ };
23813
+ var defaultOptions = {
23814
+ idField: "id",
23815
+ extractField: (document, fieldName) => document[fieldName],
23816
+ stringifyField: (fieldValue, fieldName) => fieldValue.toString(),
23817
+ tokenize: (text) => text.split(SPACE_OR_PUNCTUATION),
23818
+ processTerm: (term) => term.toLowerCase(),
23819
+ fields: undefined,
23820
+ searchOptions: undefined,
23821
+ storeFields: [],
23822
+ logger: (level, message) => {
23823
+ if (typeof (console === null || console === undefined ? undefined : console[level]) === "function")
23824
+ console[level](message);
23825
+ },
23826
+ autoVacuum: true
23827
+ };
23828
+ var defaultSearchOptions = {
23829
+ combineWith: OR,
23830
+ prefix: false,
23831
+ fuzzy: false,
23832
+ maxFuzzy: 6,
23833
+ boost: {},
23834
+ weights: { fuzzy: 0.45, prefix: 0.375 },
23835
+ bm25: defaultBM25params
23836
+ };
23837
+ var defaultAutoSuggestOptions = {
23838
+ combineWith: AND,
23839
+ prefix: (term, i, terms) => i === terms.length - 1
23840
+ };
23841
+ var defaultVacuumOptions = { batchSize: 1000, batchWait: 10 };
23842
+ var defaultVacuumConditions = { minDirtFactor: 0.1, minDirtCount: 20 };
23843
+ var defaultAutoVacuumOptions = { ...defaultVacuumOptions, ...defaultVacuumConditions };
23844
+ var assignUniqueTerm = (target, term) => {
23845
+ if (!target.includes(term))
23846
+ target.push(term);
23847
+ };
23848
+ var assignUniqueTerms = (target, source) => {
23849
+ for (const term of source) {
23850
+ if (!target.includes(term))
23851
+ target.push(term);
23852
+ }
23853
+ };
23854
+ var byScore = ({ score: a }, { score: b }) => b - a;
23855
+ var createMap = () => new Map;
23856
+ var objectToNumericMap = (object) => {
23857
+ const map = new Map;
23858
+ for (const key of Object.keys(object)) {
23859
+ map.set(parseInt(key, 10), object[key]);
23860
+ }
23861
+ return map;
23862
+ };
23863
+ var objectToNumericMapAsync = async (object) => {
23864
+ const map = new Map;
23865
+ let count = 0;
23866
+ for (const key of Object.keys(object)) {
23867
+ map.set(parseInt(key, 10), object[key]);
23868
+ if (++count % 1000 === 0) {
23869
+ await wait(0);
23870
+ }
23871
+ }
23872
+ return map;
23873
+ };
23874
+ var wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
23875
+ var SPACE_OR_PUNCTUATION = /[\n\r\p{Z}\p{P}]+/u;
23876
+
23877
+ // src/commands/search.ts
23878
+ var MAX_RESULTS = 5;
23879
+ var FIELD_BOOST = { command: 8, summary: 5, context: 0.5 };
23880
+ 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(" "));
23881
+ var MIN_EXPANDED_TERM_LENGTH = 3;
23882
+ var MIN_FUZZY_TERM_LENGTH = 5;
23883
+ var SEARCH_OPTIONS = {
23884
+ boost: FIELD_BOOST,
23885
+ processTerm: (term) => {
23886
+ const lower = term.toLowerCase();
23887
+ return STOP_WORDS.has(lower) ? null : lower;
23888
+ },
23889
+ prefix: (term) => term.length >= MIN_EXPANDED_TERM_LENGTH,
23890
+ fuzzy: (term) => term.length >= MIN_FUZZY_TERM_LENGTH ? 0.2 : false
23891
+ };
23892
+ var TRAILING_PARENTHETICAL = /\s*\([^)]*\)\s*$/;
23893
+ var COLUMNS3 = [
23894
+ { header: "command", value: (result) => result.command },
23895
+ { header: "summary", value: (result) => result.summary }
23896
+ ];
23897
+ function isHidden(command) {
23898
+ return command._hidden === true;
23899
+ }
23900
+ function visibleSubcommands(command) {
23901
+ return command.commands.filter((child) => child.name() !== "help" && !isHidden(child));
23902
+ }
23903
+ function collectDocuments(command, path, ancestors, exclude) {
23904
+ const children = visibleSubcommands(command);
23905
+ if (children.length === 0) {
23906
+ const display = command.description();
23907
+ return [
23908
+ {
23909
+ command: ["sim", ...path].join(" "),
23910
+ display,
23911
+ summary: display.replace(TRAILING_PARENTHETICAL, ""),
23912
+ context: [
23913
+ ...ancestors,
23914
+ ...command.registeredArguments.map((argument) => `${argument.name()} ${argument.description}`.trim()),
23915
+ ...command.options.filter((option) => !option.hidden).map((option) => `${option.long ?? option.short ?? ""} ${option.description}`.trim())
23916
+ ].join(" ")
23917
+ }
23918
+ ];
23919
+ }
23920
+ const nextAncestors = path.length > 0 ? [...ancestors, command.description()] : ancestors;
23921
+ return children.filter((child) => child !== exclude).flatMap((child) => collectDocuments(child, [...path, child.name()], nextAncestors, exclude));
23922
+ }
23923
+ function searchCommands(program, query, exclude) {
23924
+ const index = new MiniSearch({
23925
+ fields: ["command", "summary", "context"],
23926
+ storeFields: ["command", "display"],
23927
+ idField: "command"
23928
+ });
23929
+ index.addAll(collectDocuments(program, [], [], exclude));
23930
+ return index.search(query, SEARCH_OPTIONS).slice(0, MAX_RESULTS).map((hit) => ({ command: hit.command, summary: hit.display }));
23931
+ }
23932
+ function searchCommand() {
23933
+ 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", `
23934
+ Ranks the commands this CLI ships, locally; your query is never sent anywhere.
23935
+ Returns the ${MAX_RESULTS} best matches. Run \`<command> --help\` on one for its flags.
23936
+
23937
+ Examples:
23938
+ $ sim cli search "cancel a running workflow"
23939
+ $ sim cli search list table rows`).action((words, _options, command) => {
23940
+ let program = command;
23941
+ while (program.parent)
23942
+ program = program.parent;
23943
+ const results = searchCommands(program, words.join(" "), command);
23944
+ printList(profileFrom(command).output, results, COLUMNS3);
23945
+ });
23946
+ }
23947
+ function cliCommand() {
23948
+ return new Command("cli").description("Discover commands in this CLI").addCommand(searchCommand());
23949
+ }
23950
+
22812
23951
  // src/terminal/secret-input.ts
22813
23952
  import { emitKeypressEvents } from "node:readline";
22814
23953
  var MAX_SECRET_LENGTH = 65536;
@@ -22970,7 +24109,7 @@ function attachSecretCommands(program) {
22970
24109
  if (!secrets)
22971
24110
  throw new Error("The generated secrets command group is missing");
22972
24111
  const redactionSpellings = new Set;
22973
- 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));
24112
+ 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));
22974
24113
  }
22975
24114
 
22976
24115
  // src/telemetry/transport.ts
@@ -23216,19 +24355,28 @@ or custom-tool ID can open with a dash, which reads as a flag; put -- in front
23216
24355
  of it, as in sim audit-logs get -- -HlDcD1z76nK6R4crsUp0.
23217
24356
 
23218
24357
  Examples:
24358
+ $ sim cli search "cancel a workflow run" Find the command for a task
23219
24359
  $ sim login Authorize the default profile
23220
24360
  $ sim login --profile dev --endpoint http://localhost:3000
23221
24361
  $ sim profile add acme --workspace 7e2d9c14-6b83-4a55-8f01-c4d3e9a76b28
23222
24362
  $ sim workflows list
23223
24363
  $ sim logs list --level error --limit 20
23224
- $ sim configure --set-output json Save a profile output default
23225
- $ sim --output json tables get tbl_9f3c1a05d4b7426e8c2f0917ab35de64
24364
+ $ sim configure --set-output table Prefer tables over the JSON default
24365
+ $ sim --output table tables get tbl_9f3c1a05d4b7426e8c2f0917ab35de64
23226
24366
  $ sim knowledge search --query "refund policy" --kb 4c1b7f60-2d55-4a3e-9c18-70b6ea2f9d31
23227
24367
  $ sim workflows export 3a9e21d8-5f47-4c0b-b2ea-91d7c6034ef8 > wf.json
23228
24368
  $ sim workflows import --workflow @wf.json
23229
24369
  $ sim knowledge export 4c1b7f60-2d55-4a3e-9c18-70b6ea2f9d31 -o ./kb.simkb.zip
23230
24370
  $ sim whoami --profile dev
23231
24371
  `;
24372
+ var AGENT_DISCOVERY_NOTE = `=== AGENT COMMAND DISCOVERY ===
24373
+ Do not explore commands by chaining nested --help calls. Instead run:
24374
+ sim cli search "<describe the task you want to accomplish>"
24375
+ It returns the 5 best-matching commands, each with a one-line summary. Pick the
24376
+ best match rather than repeating similar searches, then run
24377
+ \`<command> --help\` for its flags.
24378
+ === END AGENT COMMAND DISCOVERY ===
24379
+ `;
23232
24380
  var ROOT_VALUE_FLAGS = new Set([
23233
24381
  "-P",
23234
24382
  "--profile",
@@ -23266,6 +24414,7 @@ function addVersionOption(program) {
23266
24414
  program.version(cliVersion(), "-V, --version [none]", "output the version number (takes no value)");
23267
24415
  }
23268
24416
  function buildProgram(options = {}) {
24417
+ const env = options.env ?? process.env;
23269
24418
  const program = options.program ?? new Command;
23270
24419
  program.name("sim").description(PROGRAM_DESCRIPTION);
23271
24420
  if (options.version !== false)
@@ -23282,6 +24431,7 @@ function buildProgram(options = {}) {
23282
24431
  const update = updateCommand();
23283
24432
  program.addCommand(update);
23284
24433
  program.addCommand(telemetryCommand());
24434
+ program.addCommand(cliCommand());
23285
24435
  for (const command of buildGeneratedCommands()) {
23286
24436
  program.addCommand(command);
23287
24437
  }
@@ -23289,6 +24439,7 @@ function buildProgram(options = {}) {
23289
24439
  attachProtocolCommands(program);
23290
24440
  attachSecretCommands(program);
23291
24441
  program.addHelpText("after", options.helpText ?? HELP_EPILOGUE);
24442
+ program.addHelpText("beforeAll", ({ command }) => detectCodingAgent(env) !== undefined && command.commands.length > 0 ? AGENT_DISCOVERY_NOTE : "");
23292
24443
  program.hook("preAction", async (_program, command) => {
23293
24444
  if (command === update)
23294
24445
  return;