@mx-space/cli 0.6.8 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- import { $ as drain, $a as identity, $i as reduce$1, $n as try_, $r as get$11, $t as either, A as compose, Aa as pipeArguments, Ai as empty$11, An as orElse$3, Ar as Scope, At as encodeSync, B as ensuring$1, Ba as cached, Bi as head$2, Bn as scope, Br as set$3, Bt as async, C as Number$, Ca as some, Ci as isConfigError, Cn as match$2, Ct as currentContext, D as String$, Da as left, Di as appendAll, Dn as onError, Dr as taggedEnum, Dt as unsafeMake, Ea as string$1, Ei as append$2, En as negate, Er as tagged, Et as get$15, Fa as redact$1, Fi as findFirstIndex, Fn as retry, Fr as isFailure, Ft as addFinalizer, G as mapError$1, Gi as join$1, Gn as suspend, Gr as updateAs, Gt as catchIf, H as fromChannel, Ha as hash, Hi as isArray$1, Hn as serviceFunctions, Hr as updateAndGet, Ht as catchAll, I as make$21, Ia as symbolRedactable, Ii as findLast, In as runFork$1, Ir as void_$1, It as all$5, J as splitLines, Ja as globalValue, Ji as match$1, Jn as tapError, Jr as cons$1, Jt as catchTags, K as run$5, Ka as isObject, Ki as make$22, Kn as sync, Kr as CommitPrototype, Kt as catchSome, L as isConfig, La as toStringUnknown, Li as flatMap$4, Ln as runPromise, Lr as ParentSpan, Lt as annotateLogs, M as decodeUnknown, Ma as Class, Mi as filter$2, Mn as provide$1, Mr as isInterrupted, Mt as _void, N as int, Na as NodeInspectSymbol, Ni as filterMap, Nn as provideService, Nr as isInterruptedOnly, Nt as acquireRelease, O as TaggedError, Oa as merge$1, Oi as contains, On as onInterrupt, Or as error$1, Ot as nominal, P as optional$7, Pa as format$3, Pi as findFirst, Pn as repeatN, Pr as fail$5, Pt as acquireUseRelease$1, Q as unwrapScoped, Qa as dual, Qi as prepend$1, Qn as tryPromise, Qr as fromIterable$2, Qt as dieMessage, R as asyncScoped, Ra as equals, Ri as fromIterable$1, Rn as runSync, Rr as get$10, Rt as as, S as Literal, Sa as orElse$2, Si as omit, Sn as mapInputContext, Sr as unsafeDone, St as succeed$3, Ta as mapInput, Ti as allocate, Tn as matchEffect, Tr as TaggedError$1, Tt as currentTracerEnabled, Ua as string, Ui as isEmptyReadonlyArray, Un as serviceOption, Ur as allLevels, Ut as catchAllCause, Va as combine$2, Vi as headNonEmpty, Vn as scoped, Vr as update$6, Vt as cached$1, W as mapChunks, Wa as symbol, Wi as isNonEmptyReadonlyArray, Wn as succeed$1, Wr as getOrDefault, Wt as catchAllDefect, X as transduce, Xa as constUndefined, Xi as matchRight, Xn as timeout, Xr as of$3, Xt as contextWithEffect, Y as suspend$1, Ya as constFalse, Yi as matchLeft, Yn as tapErrorCause, Yr as isNil, Yt as context, Z as unwrap$5, Za as constVoid, Zi as of$2, Zn as tryMap, Zr as empty$12, Zt as die, _ as fromString, _a as isOption, _i as Reference, _n as logError, _r as failCause$1, _t as effect, a as make$27, aa as tailNonEmpty, ai as add$1, an as filterOrDieMessage, ar as useSpan, at as embedInput, b as Defect, ba as match, bi as getOption, bn as mapBoth, br as make$26, bt as provideMerge, c as make$25, ci as remove$3, cn as fnUntraced, cr as withParentSpan, ct as fromEffect, d as defaultLogger, da as flatMap$3, di as map$10, dn as forkScoped, dr as zipRight, dt as write, ea as reduceRight, ei as has, en as ensuring, eo as pipe, er as uninterruptible, et as foldLeftChunks, f as prettyLoggerDefault, fa as fromNullable, fi as of$1, fn as gen, fr as zipWith, ft as spaced, g as when, ga as isNone, gi as GenericTag, gn as locally, gr as fail$4, gt as make$30, h as value$1, ha as getOrUndefined, hi as unsafeFromArray, hn as isEffect, hr as complete, ht as get$14, i as isMailbox, ia as splitAt, ii as make$29, in as filter$1, io as __toESM, ir as unsafeMakeSemaphore, it as acquireUseRelease, ja as BaseProto, ji as every, jn as orElseFail, jr as addFinalizer$1, jt as is$2, k as Union, ka as right, ki as drop, kn as orDie, kr as log, kt as decodeSync, l as updateEffect, la as map$9, li as seconds, ln as forEach$1, lr as zip, lt as suspend$2, m as orElse$1, ma as getOrThrow, mi as toArray, mn as interruptible, mr as _await, mt as updateContext, n as make$28, na as sort$2, ni as make$24, nn as failCause, no as __exportAll, nr as unlessEffect, nt as fromChannel$1, o as toChannel, oa as take, oi as fromIterable$3, on as flatMap$1, or as when$1, ot as ensuring$2, p as withMinimumLogLevel, pa as getOrElse, pi as reduce$2, pn as ignore, pr as DeferredTypeId, pt as runFork, q as runCollect, qa as isTagged, qi as map$7, qn as tap, qr as round, qt as catchTag, r as unsafeAdd, ra as span, ri as set$2, rn as failSync, ro as __require, rr as unsafeMakeLatch, rt as unwrapScoped$1, s as get$12, sa as unsafeGet, si as has$1, sn as flatten$3, sr as withFiberRuntime, st as flatMap$2, t as join$2, ta as some$1, ti as isEmpty$5, tn as fail$2, to as __commonJSMin, tr as uninterruptibleMask, tt as forEach, u as unify, ua as filter$3, ui as appendAll$1, un as forkDaemon, ur as zipLeft, ut as void_, v as Cause, va as isSome, vi as Tag$2, vn as logWarning, vr as interrupt, vt as mergeAll, w as NumberFromString, wa as boolean$3, wi as isMissingDataOnly, wn as matchCauseEffect, wr as Error$1, wt as currentLoggers, x as Int, xa as none$3, xi as merge$2, xn as mapError, xr as succeed$2, xt as scoped$1, y as Date$, ya as map$8, yi as get$13, yn as map$6, yr as isDone, yt as provide, z as bufferChunks, za as symbol$1, zi as getSomes, zn as runtime, zr as make$23, zt as asVoid } from "./esm-CK9m5JKX.mjs";
1
+ import { $ as drain, $a as identity, $i as reduce$1, $n as try_, $r as get$11, $t as either, A as compose, Aa as pipeArguments, Ai as empty$11, An as orElse$3, Ar as Scope, At as encodeSync, B as ensuring$1, Ba as cached, Bi as head$2, Bn as scope, Br as set$3, Bt as async, C as Number$, Ca as some, Ci as isConfigError, Cn as match$2, Ct as currentContext, D as String$, Da as left, Di as appendAll, Dn as onError, Dr as taggedEnum, Dt as unsafeMake, Ea as string$1, Ei as append$2, En as negate, Er as tagged, Et as get$15, Fa as redact$1, Fi as findFirstIndex, Fn as retry, Fr as isFailure, Ft as addFinalizer, G as mapError$1, Gi as join$1, Gn as suspend, Gr as updateAs, Gt as catchIf, H as fromChannel, Ha as hash, Hi as isArray$1, Hn as serviceFunctions, Hr as updateAndGet, Ht as catchAll, I as make$21, Ia as symbolRedactable, Ii as findLast, In as runFork$1, Ir as void_$1, It as all$5, J as splitLines, Ja as globalValue, Ji as match$1, Jn as tapError, Jr as cons$1, Jt as catchTags, K as run$5, Ka as isObject, Ki as make$22, Kn as sync, Kr as CommitPrototype, Kt as catchSome, L as isConfig, La as toStringUnknown, Li as flatMap$4, Ln as runPromise, Lr as ParentSpan, Lt as annotateLogs, M as decodeUnknown, Ma as Class, Mi as filter$2, Mn as provide$1, Mr as isInterrupted, Mt as _void, N as int, Na as NodeInspectSymbol, Ni as filterMap, Nn as provideService, Nr as isInterruptedOnly, Nt as acquireRelease, O as TaggedError, Oa as merge$2, Oi as contains, On as onInterrupt, Or as error$1, Ot as nominal, P as optional$7, Pa as format$3, Pi as findFirst, Pn as repeatN, Pr as fail$5, Pt as acquireUseRelease$1, Q as unwrapScoped, Qa as dual, Qi as prepend$1, Qn as tryPromise, Qr as fromIterable$2, Qt as dieMessage, R as asyncScoped, Ra as equals, Ri as fromIterable$1, Rn as runSync, Rr as get$10, Rt as as, S as Literal, Sa as orElse$2, Si as omit, Sn as mapInputContext, Sr as unsafeDone, St as succeed$3, Ta as mapInput, Ti as allocate, Tn as matchEffect, Tr as TaggedError$1, Tt as currentTracerEnabled, Ua as string, Ui as isEmptyReadonlyArray, Un as serviceOption, Ur as allLevels, Ut as catchAllCause, Va as combine$2, Vi as headNonEmpty, Vn as scoped, Vr as update$6, Vt as cached$1, W as mapChunks, Wa as symbol, Wi as isNonEmptyReadonlyArray, Wn as succeed$1, Wr as getOrDefault, Wt as catchAllDefect, X as transduce, Xa as constUndefined, Xi as matchRight, Xn as timeout, Xr as of$3, Xt as contextWithEffect, Y as suspend$1, Ya as constFalse, Yi as matchLeft, Yn as tapErrorCause, Yr as isNil, Yt as context, Z as unwrap$5, Za as constVoid, Zi as of$2, Zn as tryMap, Zr as empty$12, Zt as die, _ as fromString, _a as isOption, _i as Reference, _n as logError, _r as failCause$1, _t as effect, a as make$27, aa as tailNonEmpty, ai as add$1, an as filterOrDieMessage, ar as useSpan, at as embedInput, b as Defect, ba as match, bi as getOption, bn as mapBoth, br as make$26, bt as provideMerge, c as make$25, ci as remove$4, cn as fnUntraced, cr as withParentSpan, ct as fromEffect, d as defaultLogger, da as flatMap$3, di as map$10, dn as forkScoped, dr as zipRight, dt as write, ea as reduceRight, ei as has, en as ensuring, eo as pipe, er as uninterruptible, et as foldLeftChunks, f as prettyLoggerDefault, fa as fromNullable, fi as of$1, fn as gen, fr as zipWith, ft as spaced, g as when, ga as isNone, gi as GenericTag, gn as locally, gr as fail$4, gt as make$30, h as value$1, ha as getOrUndefined, hi as unsafeFromArray, hn as isEffect, hr as complete, ht as get$14, i as isMailbox, ia as splitAt, ii as make$29, in as filter$1, io as __toESM, ir as unsafeMakeSemaphore, it as acquireUseRelease, ja as BaseProto, ji as every, jn as orElseFail, jr as addFinalizer$1, jt as is$2, k as Union, ka as right, ki as drop, kn as orDie, kr as log, kt as decodeSync, l as updateEffect, la as map$9, li as seconds, ln as forEach$1, lr as zip, lt as suspend$2, m as orElse$1, ma as getOrThrow, mi as toArray, mn as interruptible, mr as _await, mt as updateContext, n as make$28, na as sort$2, ni as make$24, nn as failCause, no as __exportAll, nr as unlessEffect, nt as fromChannel$1, o as toChannel, oa as take, oi as fromIterable$3, on as flatMap$1, or as when$1, ot as ensuring$2, p as withMinimumLogLevel, pa as getOrElse, pi as reduce$2, pn as ignore, pr as DeferredTypeId, pt as runFork, q as runCollect, qa as isTagged, qi as map$7, qn as tap, qr as round, qt as catchTag, r as unsafeAdd, ra as span, ri as set$2, rn as failSync, ro as __require, rr as unsafeMakeLatch, rt as unwrapScoped$1, s as get$12, sa as unsafeGet, si as has$1, sn as flatten$3, sr as withFiberRuntime, st as flatMap$2, t as join$2, ta as some$1, ti as isEmpty$5, tn as fail$2, to as __commonJSMin, tr as uninterruptibleMask, tt as forEach, u as unify, ua as filter$3, ui as appendAll$1, un as forkDaemon, ur as zipLeft, ut as void_, v as Cause, va as isSome, vi as Tag$2, vn as logWarning, vr as interrupt, vt as mergeAll, w as NumberFromString, wa as boolean$3, wi as isMissingDataOnly, wn as matchCauseEffect, wr as Error$1, wt as currentLoggers, x as Int, xa as none$3, xi as merge$3, xn as mapError, xr as succeed$2, xt as scoped$1, y as Date$, ya as map$8, yi as get$13, yn as map$6, yr as isDone, yt as provide, z as bufferChunks, za as symbol$1, zi as getSomes, zn as runtime, zr as make$23, zt as asVoid } from "./esm-CK9m5JKX.mjs";
2
2
  import { _ as LinkNode, a as HeadingNode, b as CodeHighlightNode, d as ListItemNode, f as ListNode, g as AutoLinkNode, o as QuoteNode, x as CodeNode } from "./LexicalRichText.node-DDpwfE-P.mjs";
3
3
  import { t as HorizontalRuleNode } from "./LexicalExtension.node-CF3EAPN7.mjs";
4
4
  import { Ht as ElementNode, Vt as DecoratorNode } from "./Lexical.node-BUsI9gWr.mjs";
@@ -24,7 +24,7 @@ import * as ChildProcess from "node:child_process";
24
24
  import childProcess, { execFile, spawn } from "node:child_process";
25
25
  import * as readline from "node:readline";
26
26
  import E from "node:readline";
27
- import V, { stdin, stdout } from "node:process";
27
+ import process$1, { stdin, stdout } from "node:process";
28
28
  import "node:tty";
29
29
  //#region ../../node_modules/.pnpm/@effect+platform@0.96.1_effect@3.21.2/node_modules/@effect/platform/dist/esm/Error.js
30
30
  /**
@@ -4719,7 +4719,7 @@ const map$1 = /* @__PURE__ */ dual(2, (self, f) => makeMap(self, (a) => right(f(
4719
4719
  /** @internal */
4720
4720
  const optional$3 = (self) => withDefault(map$1(self, some), none$3());
4721
4721
  /** @internal */
4722
- const orElse = /* @__PURE__ */ dual(2, (self, that) => orElseEither(self, that).pipe(map$1(merge$1)));
4722
+ const orElse = /* @__PURE__ */ dual(2, (self, that) => orElseEither(self, that).pipe(map$1(merge$2)));
4723
4723
  /** @internal */
4724
4724
  const orElseEither = /* @__PURE__ */ dual(2, (self, that) => makeOrElse(self, that));
4725
4725
  /** @internal */
@@ -5144,7 +5144,7 @@ const matchOptions = (input, options, config) => {
5144
5144
  return matchOptions(otherArgs, otherOptions, config).pipe(map$6(([error, otherArgs, map2]) => [
5145
5145
  error,
5146
5146
  otherArgs,
5147
- merge(map1, fromIterable$1(map2))
5147
+ merge$1(map1, fromIterable$1(map2))
5148
5148
  ]));
5149
5149
  }), catchAll((e) => succeed$1([
5150
5150
  some(e),
@@ -5483,7 +5483,7 @@ const matchUnclustered = (input, tail, options, config) => {
5483
5483
  return matchUnclustered(otherFlags, tail, opts1, config).pipe(map$6(([_, opts2, map2]) => [
5484
5484
  tail,
5485
5485
  opts2,
5486
- merge(map1, fromIterable$1(map2))
5486
+ merge$1(map1, fromIterable$1(map2))
5487
5487
  ]));
5488
5488
  }));
5489
5489
  }
@@ -5496,11 +5496,11 @@ const matchUnclustered = (input, tail, options, config) => {
5496
5496
  /**
5497
5497
  * Sums the list associated with the same key.
5498
5498
  */
5499
- const merge = (map1, map2) => {
5499
+ const merge$1 = (map1, map2) => {
5500
5500
  if (isNonEmptyReadonlyArray(map2)) {
5501
5501
  const head = headNonEmpty(map2);
5502
5502
  const tail = tailNonEmpty(map2);
5503
- return merge(match(get$11(map1, head[0]), {
5503
+ return merge$1(match(get$11(map1, head[0]), {
5504
5504
  onNone: () => set$2(map1, head[0], head[1]),
5505
5505
  onSome: (elems) => set$2(map1, head[0], appendAll(elems, head[1]))
5506
5506
  }), tail);
@@ -6866,7 +6866,7 @@ const setAll$1 = /* @__PURE__ */ dual(2, (self, headers) => make$12({
6866
6866
  * @since 1.0.0
6867
6867
  * @category combinators
6868
6868
  */
6869
- const remove$2 = /* @__PURE__ */ dual(2, (self, key) => {
6869
+ const remove$3 = /* @__PURE__ */ dual(2, (self, key) => {
6870
6870
  const out = make$12(self);
6871
6871
  const modify = (key) => {
6872
6872
  if (typeof key === "string") {
@@ -7232,7 +7232,7 @@ const setHash = /* @__PURE__ */ dual(2, (self, hash) => makeInternal(self.method
7232
7232
  /** @internal */
7233
7233
  const setBody = /* @__PURE__ */ dual(2, (self, body) => {
7234
7234
  let headers = self.headers;
7235
- if (body._tag === "Empty" || body._tag === "FormData") headers = remove$2(headers, ["Content-type", "Content-length"]);
7235
+ if (body._tag === "Empty" || body._tag === "FormData") headers = remove$3(headers, ["Content-type", "Content-length"]);
7236
7236
  else {
7237
7237
  const contentType = body.contentType;
7238
7238
  if (contentType) headers = set$1(headers, "content-type", contentType);
@@ -7466,7 +7466,7 @@ const transformResponse = /* @__PURE__ */ dual(2, (self, f) => {
7466
7466
  return makeWith((request) => f(client.postprocess(request)), client.preprocess);
7467
7467
  });
7468
7468
  /** @internal */
7469
- const layerMergedContext$1 = (effect$1) => effect(tag, flatMap$1(context(), (context) => map$6(effect$1, (client) => transformResponse(client, mapInputContext((input) => merge$2(context, input))))));
7469
+ const layerMergedContext$1 = (effect$1) => effect(tag, flatMap$1(context(), (context) => map$6(effect$1, (client) => transformResponse(client, mapInputContext((input) => merge$3(context, input))))));
7470
7470
  //#endregion
7471
7471
  //#region ../../node_modules/.pnpm/@effect+platform@0.96.1_effect@3.21.2/node_modules/@effect/platform/dist/esm/HttpClient.js
7472
7472
  /**
@@ -7867,7 +7867,7 @@ const removeFactory = (method) => {
7867
7867
  force: options?.force ?? false
7868
7868
  });
7869
7869
  };
7870
- const remove$1 = /* @__PURE__ */ removeFactory("remove");
7870
+ const remove$2 = /* @__PURE__ */ removeFactory("remove");
7871
7871
  const makeTempDirectoryScoped = /* @__PURE__ */ (() => {
7872
7872
  const makeDirectory = /* @__PURE__ */ makeTempDirectoryFactory("makeTempDirectoryScoped");
7873
7873
  const removeDirectory = /* @__PURE__ */ removeFactory("makeTempDirectoryScoped");
@@ -8112,7 +8112,7 @@ const layer$9 = /* @__PURE__ */ effect(FileSystem, /* @__PURE__ */ map$6(/* @__P
8112
8112
  readFile,
8113
8113
  readLink,
8114
8114
  realPath,
8115
- remove: remove$1,
8115
+ remove: remove$2,
8116
8116
  rename,
8117
8117
  stat,
8118
8118
  symlink,
@@ -8942,7 +8942,7 @@ const addPrettyLogger = (refs, fiberId) => {
8942
8942
  return updateAs(refs, {
8943
8943
  fiberId,
8944
8944
  fiberRef: currentLoggers,
8945
- value: loggers.pipe(remove$3(defaultLogger), add$1(prettyLoggerDefault))
8945
+ value: loggers.pipe(remove$4(defaultLogger), add$1(prettyLoggerDefault))
8946
8946
  });
8947
8947
  };
8948
8948
  /**
@@ -9042,7 +9042,7 @@ function isInsideContainer() {
9042
9042
  //#endregion
9043
9043
  //#region ../../node_modules/.pnpm/is-wsl@3.1.1/node_modules/is-wsl/index.js
9044
9044
  const isWsl = () => {
9045
- if (V.platform !== "linux") return false;
9045
+ if (process$1.platform !== "linux") return false;
9046
9046
  if (os.release().toLowerCase().includes("microsoft")) {
9047
9047
  if (isInsideContainer()) return false;
9048
9048
  return true;
@@ -9053,11 +9053,11 @@ const isWsl = () => {
9053
9053
  if (fs.existsSync("/proc/sys/fs/binfmt_misc/WSLInterop") || fs.existsSync("/run/WSL")) return !isInsideContainer();
9054
9054
  return false;
9055
9055
  };
9056
- var is_wsl_default = V.env.__IS_WSL_TEST__ ? isWsl : isWsl();
9056
+ var is_wsl_default = process$1.env.__IS_WSL_TEST__ ? isWsl : isWsl();
9057
9057
  //#endregion
9058
9058
  //#region ../../node_modules/.pnpm/powershell-utils@0.1.0/node_modules/powershell-utils/index.js
9059
9059
  const execFile$2 = promisify(childProcess.execFile);
9060
- const powerShellPath$1 = () => `${V.env.SYSTEMROOT || V.env.windir || String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`;
9060
+ const powerShellPath$1 = () => `${process$1.env.SYSTEMROOT || process$1.env.windir || String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`;
9061
9061
  const executePowerShell = async (command, options = {}) => {
9062
9062
  const { powerShellPath: psPath, ...execFileOptions } = options;
9063
9063
  const encodedCommand = executePowerShell.encodeCommand(command);
@@ -9164,7 +9164,7 @@ function defineLazyProperty(object, propertyName, valueGetter) {
9164
9164
  //#region ../../node_modules/.pnpm/default-browser-id@5.0.1/node_modules/default-browser-id/index.js
9165
9165
  const execFileAsync$3 = promisify(execFile);
9166
9166
  async function defaultBrowserId() {
9167
- if (V.platform !== "darwin") throw new Error("macOS only");
9167
+ if (process$1.platform !== "darwin") throw new Error("macOS only");
9168
9168
  const { stdout } = await execFileAsync$3("defaults", [
9169
9169
  "read",
9170
9170
  "com.apple.LaunchServices/com.apple.launchservices.secure",
@@ -9178,7 +9178,7 @@ async function defaultBrowserId() {
9178
9178
  //#region ../../node_modules/.pnpm/run-applescript@7.1.0/node_modules/run-applescript/index.js
9179
9179
  const execFileAsync$2 = promisify(execFile);
9180
9180
  async function runAppleScript(script, { humanReadableOutput = true, signal } = {}) {
9181
- if (V.platform !== "darwin") throw new Error("macOS only");
9181
+ if (process$1.platform !== "darwin") throw new Error("macOS only");
9182
9182
  const outputArguments = humanReadableOutput ? [] : ["-ss"];
9183
9183
  const execOptions = {};
9184
9184
  if (signal) execOptions.signal = signal;
@@ -9289,14 +9289,14 @@ async function defaultBrowser$1(_execFileAsync = execFileAsync$1) {
9289
9289
  const execFileAsync = promisify(execFile);
9290
9290
  const titleize = (string) => string.toLowerCase().replaceAll(/(?:^|\s|-)\S/g, (x) => x.toUpperCase());
9291
9291
  async function defaultBrowser() {
9292
- if (V.platform === "darwin") {
9292
+ if (process$1.platform === "darwin") {
9293
9293
  const id = await defaultBrowserId();
9294
9294
  return {
9295
9295
  name: await bundleName(id),
9296
9296
  id
9297
9297
  };
9298
9298
  }
9299
- if (V.platform === "linux") {
9299
+ if (process$1.platform === "linux") {
9300
9300
  const { stdout } = await execFileAsync("xdg-mime", [
9301
9301
  "query",
9302
9302
  "default",
@@ -9308,18 +9308,18 @@ async function defaultBrowser() {
9308
9308
  id
9309
9309
  };
9310
9310
  }
9311
- if (V.platform === "win32") return defaultBrowser$1();
9311
+ if (process$1.platform === "win32") return defaultBrowser$1();
9312
9312
  throw new Error("Only macOS, Linux, and Windows are supported");
9313
9313
  }
9314
9314
  //#endregion
9315
9315
  //#region ../../node_modules/.pnpm/is-in-ssh@1.0.0/node_modules/is-in-ssh/index.js
9316
- const isInSsh = Boolean(V.env.SSH_CONNECTION || V.env.SSH_CLIENT || V.env.SSH_TTY);
9316
+ const isInSsh = Boolean(process$1.env.SSH_CONNECTION || process$1.env.SSH_CLIENT || process$1.env.SSH_TTY);
9317
9317
  //#endregion
9318
9318
  //#region ../../node_modules/.pnpm/open@11.0.0/node_modules/open/index.js
9319
9319
  const fallbackAttemptSymbol = Symbol("fallbackAttempt");
9320
9320
  const __dirname = import.meta.url ? path.dirname(fileURLToPath(import.meta.url)) : "";
9321
9321
  const localXdgOpenPath = path.join(__dirname, "xdg-open");
9322
- const { platform: platform$1, arch: arch$1 } = V;
9322
+ const { platform: platform$1, arch: arch$1 } = process$1;
9323
9323
  const tryEachApp = async (apps, opener) => {
9324
9324
  if (apps.length === 0) return;
9325
9325
  const errors = [];
@@ -9432,7 +9432,7 @@ const baseOpen = async (options) => {
9432
9432
  await fs$1.access(localXdgOpenPath, constants.X_OK);
9433
9433
  exeLocalXdgOpen = true;
9434
9434
  } catch {}
9435
- command = V.versions.electron ?? (platform$1 === "android" || isBundled || !exeLocalXdgOpen) ? "xdg-open" : localXdgOpenPath;
9435
+ command = process$1.versions.electron ?? (platform$1 === "android" || isBundled || !exeLocalXdgOpen) ? "xdg-open" : localXdgOpenPath;
9436
9436
  }
9437
9437
  if (appArguments.length > 0) cliArguments.push(...appArguments);
9438
9438
  if (!options.wait) {
@@ -11024,7 +11024,7 @@ var ht$1 = class extends m {
11024
11024
  //#endregion
11025
11025
  //#region ../../node_modules/.pnpm/@clack+prompts@1.4.0/node_modules/@clack/prompts/dist/index.mjs
11026
11026
  function ee() {
11027
- return V.platform !== "win32" ? V.env.TERM !== "linux" : !!V.env.CI || !!V.env.WT_SESSION || !!V.env.TERMINUS_SUBLIME || V.env.ConEmuTask === "{cmd::Cmder}" || V.env.TERM_PROGRAM === "Terminus-Sublime" || V.env.TERM_PROGRAM === "vscode" || V.env.TERM === "xterm-256color" || V.env.TERM === "alacritty" || V.env.TERMINAL_EMULATOR === "JetBrains-JediTerm";
11027
+ return process$1.platform !== "win32" ? process$1.env.TERM !== "linux" : !!process$1.env.CI || !!process$1.env.WT_SESSION || !!process$1.env.TERMINUS_SUBLIME || process$1.env.ConEmuTask === "{cmd::Cmder}" || process$1.env.TERM_PROGRAM === "Terminus-Sublime" || process$1.env.TERM_PROGRAM === "vscode" || process$1.env.TERM === "xterm-256color" || process$1.env.TERM === "alacritty" || process$1.env.TERMINAL_EMULATOR === "JetBrains-JediTerm";
11028
11028
  }
11029
11029
  const tt = ee(), w = (t, i) => tt ? t : i, Tt = w("◆", "*"), at = w("■", "x"), ut = w("▲", "x"), H = w("◇", "o");
11030
11030
  const $ = w("│", "|"), x = w("└", "—");
@@ -18214,7 +18214,7 @@ const replaceWith = (node, nodes) => {
18214
18214
  node.remove();
18215
18215
  }
18216
18216
  };
18217
- const remove = (prev, current, next) => {
18217
+ const remove$1 = (prev, current, next) => {
18218
18218
  const { parentNode, nodeType } = current;
18219
18219
  if (prev || next) {
18220
18220
  setAdjacent(prev, next);
@@ -18265,7 +18265,7 @@ var CharacterData$1 = class extends Node$1 {
18265
18265
  replaceWith(this, nodes);
18266
18266
  }
18267
18267
  remove() {
18268
- remove(this[PREV], this, this[NEXT]);
18268
+ remove$1(this[PREV], this, this[NEXT]);
18269
18269
  }
18270
18270
  /* c8 ignore start */
18271
18271
  get data() {
@@ -19656,13 +19656,13 @@ function reduceRules(a, b) {
19656
19656
  //#endregion
19657
19657
  //#region ../../node_modules/.pnpm/css-select@5.2.2/node_modules/css-select/lib/esm/index.js
19658
19658
  const defaultEquals = (a, b) => a === b;
19659
- const defaultOptions = {
19659
+ const defaultOptions$1 = {
19660
19660
  adapter: esm_exports$1,
19661
19661
  equals: defaultEquals
19662
19662
  };
19663
19663
  function convertOptionFormats(options) {
19664
19664
  var _a, _b, _c, _d;
19665
- const opts = options !== null && options !== void 0 ? options : defaultOptions;
19665
+ const opts = options !== null && options !== void 0 ? options : defaultOptions$1;
19666
19666
  (_a = opts.adapter) !== null && _a !== void 0 || (opts.adapter = esm_exports$1);
19667
19667
  (_b = opts.equals) !== null && _b !== void 0 || (opts.equals = (_d = (_c = opts.adapter) === null || _c === void 0 ? void 0 : _c.equals) !== null && _d !== void 0 ? _d : defaultEquals);
19668
19668
  return opts;
@@ -20515,7 +20515,7 @@ var Element$1 = class extends ParentNode {
20515
20515
  replaceWith(this, nodes);
20516
20516
  }
20517
20517
  remove() {
20518
- remove(this[PREV], this, this[END][NEXT]);
20518
+ remove$1(this[PREV], this, this[END][NEXT]);
20519
20519
  }
20520
20520
  get id() {
20521
20521
  return stringAttribute.get(this, "id");
@@ -28251,7 +28251,8 @@ const make$3 = (api, deps = {}) => {
28251
28251
  const resolveCategoryRefs = (refs) => forEach$1(refs, (ref) => resolveCategory(ref), { concurrency: 1 });
28252
28252
  const resolvePostReadPath = (slugOrId) => gen(function* () {
28253
28253
  if (isSnowflakeId(slugOrId)) return `/posts/${slugOrId}`;
28254
- const path = (yield* api.raw(`/posts/get-url/${encodeURIComponent(slugOrId)}`).pipe(mapError(mapApiError)))?.path;
28254
+ const env = yield* api.raw(`/posts/get-url/${encodeURIComponent(slugOrId)}`).pipe(mapError(mapApiError));
28255
+ const path = env?.data?.path ?? env?.path;
28255
28256
  if (!path) return yield* fail$2(new ResourceNotFound({
28256
28257
  message: `post not found: ${slugOrId}`,
28257
28258
  kind: "post",
@@ -28262,7 +28263,8 @@ const make$3 = (api, deps = {}) => {
28262
28263
  const resolvePostId = (slugOrId) => gen(function* () {
28263
28264
  if (isSnowflakeId(slugOrId)) return slugOrId;
28264
28265
  const apiPath = yield* resolvePostReadPath(slugOrId);
28265
- const id = (yield* api.raw(apiPath).pipe(mapError(mapApiError)))?.id;
28266
+ const env = yield* api.raw(apiPath).pipe(mapError(mapApiError));
28267
+ const id = env?.data?.id ?? env?.id;
28266
28268
  if (!id) return yield* fail$2(new ResourceNotFound({
28267
28269
  message: `post not found: ${slugOrId}`,
28268
28270
  kind: "post",
@@ -32224,6 +32226,1777 @@ const profileCmd = make$13("profile").pipe(withDescription(help$2.description),
32224
32226
  rm
32225
32227
  ]));
32226
32228
  //#endregion
32229
+ //#region ../../node_modules/.pnpm/minisearch@7.2.0/node_modules/minisearch/dist/es/index.js
32230
+ /** @ignore */
32231
+ const ENTRIES = "ENTRIES";
32232
+ /** @ignore */
32233
+ const KEYS = "KEYS";
32234
+ /** @ignore */
32235
+ const VALUES = "VALUES";
32236
+ /** @ignore */
32237
+ const LEAF = "";
32238
+ /**
32239
+ * @private
32240
+ */
32241
+ var TreeIterator = class {
32242
+ constructor(set, type) {
32243
+ const node = set._tree;
32244
+ const keys = Array.from(node.keys());
32245
+ this.set = set;
32246
+ this._type = type;
32247
+ this._path = keys.length > 0 ? [{
32248
+ node,
32249
+ keys
32250
+ }] : [];
32251
+ }
32252
+ next() {
32253
+ const value = this.dive();
32254
+ this.backtrack();
32255
+ return value;
32256
+ }
32257
+ dive() {
32258
+ if (this._path.length === 0) return {
32259
+ done: true,
32260
+ value: void 0
32261
+ };
32262
+ const { node, keys } = last$1(this._path);
32263
+ if (last$1(keys) === LEAF) return {
32264
+ done: false,
32265
+ value: this.result()
32266
+ };
32267
+ const child = node.get(last$1(keys));
32268
+ this._path.push({
32269
+ node: child,
32270
+ keys: Array.from(child.keys())
32271
+ });
32272
+ return this.dive();
32273
+ }
32274
+ backtrack() {
32275
+ if (this._path.length === 0) return;
32276
+ const keys = last$1(this._path).keys;
32277
+ keys.pop();
32278
+ if (keys.length > 0) return;
32279
+ this._path.pop();
32280
+ this.backtrack();
32281
+ }
32282
+ key() {
32283
+ return this.set._prefix + this._path.map(({ keys }) => last$1(keys)).filter((key) => key !== LEAF).join("");
32284
+ }
32285
+ value() {
32286
+ return last$1(this._path).node.get(LEAF);
32287
+ }
32288
+ result() {
32289
+ switch (this._type) {
32290
+ case VALUES: return this.value();
32291
+ case KEYS: return this.key();
32292
+ default: return [this.key(), this.value()];
32293
+ }
32294
+ }
32295
+ [Symbol.iterator]() {
32296
+ return this;
32297
+ }
32298
+ };
32299
+ const last$1 = (array) => {
32300
+ return array[array.length - 1];
32301
+ };
32302
+ /**
32303
+ * @ignore
32304
+ */
32305
+ const fuzzySearch = (node, query, maxDistance) => {
32306
+ const results = /* @__PURE__ */ new Map();
32307
+ if (query === void 0) return results;
32308
+ const n = query.length + 1;
32309
+ const m = n + maxDistance;
32310
+ const matrix = new Uint8Array(m * n).fill(maxDistance + 1);
32311
+ for (let j = 0; j < n; ++j) matrix[j] = j;
32312
+ for (let i = 1; i < m; ++i) matrix[i * n] = i;
32313
+ recurse(node, query, maxDistance, results, matrix, 1, n, "");
32314
+ return results;
32315
+ };
32316
+ const recurse = (node, query, maxDistance, results, matrix, m, n, prefix) => {
32317
+ const offset = m * n;
32318
+ key: for (const key of node.keys()) if (key === LEAF) {
32319
+ const distance = matrix[offset - 1];
32320
+ if (distance <= maxDistance) results.set(prefix, [node.get(key), distance]);
32321
+ } else {
32322
+ let i = m;
32323
+ for (let pos = 0; pos < key.length; ++pos, ++i) {
32324
+ const char = key[pos];
32325
+ const thisRowOffset = n * i;
32326
+ const prevRowOffset = thisRowOffset - n;
32327
+ let minDistance = matrix[thisRowOffset];
32328
+ const jmin = Math.max(0, i - maxDistance - 1);
32329
+ const jmax = Math.min(n - 1, i + maxDistance);
32330
+ for (let j = jmin; j < jmax; ++j) {
32331
+ const different = char !== query[j];
32332
+ const rpl = matrix[prevRowOffset + j] + +different;
32333
+ const del = matrix[prevRowOffset + j + 1] + 1;
32334
+ const ins = matrix[thisRowOffset + j] + 1;
32335
+ const dist = matrix[thisRowOffset + j + 1] = Math.min(rpl, del, ins);
32336
+ if (dist < minDistance) minDistance = dist;
32337
+ }
32338
+ if (minDistance > maxDistance) continue key;
32339
+ }
32340
+ recurse(node.get(key), query, maxDistance, results, matrix, i, n, prefix + key);
32341
+ }
32342
+ };
32343
+ /**
32344
+ * A class implementing the same interface as a standard JavaScript
32345
+ * [`Map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map)
32346
+ * with string keys, but adding support for efficiently searching entries with
32347
+ * prefix or fuzzy search. This class is used internally by {@link MiniSearch}
32348
+ * as the inverted index data structure. The implementation is a radix tree
32349
+ * (compressed prefix tree).
32350
+ *
32351
+ * Since this class can be of general utility beyond _MiniSearch_, it is
32352
+ * exported by the `minisearch` package and can be imported (or required) as
32353
+ * `minisearch/SearchableMap`.
32354
+ *
32355
+ * @typeParam T The type of the values stored in the map.
32356
+ */
32357
+ var SearchableMap = class SearchableMap {
32358
+ /**
32359
+ * The constructor is normally called without arguments, creating an empty
32360
+ * map. In order to create a {@link SearchableMap} from an iterable or from an
32361
+ * object, check {@link SearchableMap.from} and {@link
32362
+ * SearchableMap.fromObject}.
32363
+ *
32364
+ * The constructor arguments are for internal use, when creating derived
32365
+ * mutable views of a map at a prefix.
32366
+ */
32367
+ constructor(tree = /* @__PURE__ */ new Map(), prefix = "") {
32368
+ this._size = void 0;
32369
+ this._tree = tree;
32370
+ this._prefix = prefix;
32371
+ }
32372
+ /**
32373
+ * Creates and returns a mutable view of this {@link SearchableMap},
32374
+ * containing only entries that share the given prefix.
32375
+ *
32376
+ * ### Usage:
32377
+ *
32378
+ * ```javascript
32379
+ * let map = new SearchableMap()
32380
+ * map.set("unicorn", 1)
32381
+ * map.set("universe", 2)
32382
+ * map.set("university", 3)
32383
+ * map.set("unique", 4)
32384
+ * map.set("hello", 5)
32385
+ *
32386
+ * let uni = map.atPrefix("uni")
32387
+ * uni.get("unique") // => 4
32388
+ * uni.get("unicorn") // => 1
32389
+ * uni.get("hello") // => undefined
32390
+ *
32391
+ * let univer = map.atPrefix("univer")
32392
+ * univer.get("unique") // => undefined
32393
+ * univer.get("universe") // => 2
32394
+ * univer.get("university") // => 3
32395
+ * ```
32396
+ *
32397
+ * @param prefix The prefix
32398
+ * @return A {@link SearchableMap} representing a mutable view of the original
32399
+ * Map at the given prefix
32400
+ */
32401
+ atPrefix(prefix) {
32402
+ if (!prefix.startsWith(this._prefix)) throw new Error("Mismatched prefix");
32403
+ const [node, path] = trackDown(this._tree, prefix.slice(this._prefix.length));
32404
+ if (node === void 0) {
32405
+ const [parentNode, key] = last(path);
32406
+ for (const k of parentNode.keys()) if (k !== LEAF && k.startsWith(key)) {
32407
+ const node = /* @__PURE__ */ new Map();
32408
+ node.set(k.slice(key.length), parentNode.get(k));
32409
+ return new SearchableMap(node, prefix);
32410
+ }
32411
+ }
32412
+ return new SearchableMap(node, prefix);
32413
+ }
32414
+ /**
32415
+ * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/clear
32416
+ */
32417
+ clear() {
32418
+ this._size = void 0;
32419
+ this._tree.clear();
32420
+ }
32421
+ /**
32422
+ * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/delete
32423
+ * @param key Key to delete
32424
+ */
32425
+ delete(key) {
32426
+ this._size = void 0;
32427
+ return remove(this._tree, key);
32428
+ }
32429
+ /**
32430
+ * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/entries
32431
+ * @return An iterator iterating through `[key, value]` entries.
32432
+ */
32433
+ entries() {
32434
+ return new TreeIterator(this, ENTRIES);
32435
+ }
32436
+ /**
32437
+ * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/forEach
32438
+ * @param fn Iteration function
32439
+ */
32440
+ forEach(fn) {
32441
+ for (const [key, value] of this) fn(key, value, this);
32442
+ }
32443
+ /**
32444
+ * Returns a Map of all the entries that have a key within the given edit
32445
+ * distance from the search key. The keys of the returned Map are the matching
32446
+ * keys, while the values are two-element arrays where the first element is
32447
+ * the value associated to the key, and the second is the edit distance of the
32448
+ * key to the search key.
32449
+ *
32450
+ * ### Usage:
32451
+ *
32452
+ * ```javascript
32453
+ * let map = new SearchableMap()
32454
+ * map.set('hello', 'world')
32455
+ * map.set('hell', 'yeah')
32456
+ * map.set('ciao', 'mondo')
32457
+ *
32458
+ * // Get all entries that match the key 'hallo' with a maximum edit distance of 2
32459
+ * map.fuzzyGet('hallo', 2)
32460
+ * // => Map(2) { 'hello' => ['world', 1], 'hell' => ['yeah', 2] }
32461
+ *
32462
+ * // In the example, the "hello" key has value "world" and edit distance of 1
32463
+ * // (change "e" to "a"), the key "hell" has value "yeah" and edit distance of 2
32464
+ * // (change "e" to "a", delete "o")
32465
+ * ```
32466
+ *
32467
+ * @param key The search key
32468
+ * @param maxEditDistance The maximum edit distance (Levenshtein)
32469
+ * @return A Map of the matching keys to their value and edit distance
32470
+ */
32471
+ fuzzyGet(key, maxEditDistance) {
32472
+ return fuzzySearch(this._tree, key, maxEditDistance);
32473
+ }
32474
+ /**
32475
+ * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/get
32476
+ * @param key Key to get
32477
+ * @return Value associated to the key, or `undefined` if the key is not
32478
+ * found.
32479
+ */
32480
+ get(key) {
32481
+ const node = lookup(this._tree, key);
32482
+ return node !== void 0 ? node.get(LEAF) : void 0;
32483
+ }
32484
+ /**
32485
+ * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/has
32486
+ * @param key Key
32487
+ * @return True if the key is in the map, false otherwise
32488
+ */
32489
+ has(key) {
32490
+ const node = lookup(this._tree, key);
32491
+ return node !== void 0 && node.has(LEAF);
32492
+ }
32493
+ /**
32494
+ * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/keys
32495
+ * @return An `Iterable` iterating through keys
32496
+ */
32497
+ keys() {
32498
+ return new TreeIterator(this, KEYS);
32499
+ }
32500
+ /**
32501
+ * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/set
32502
+ * @param key Key to set
32503
+ * @param value Value to associate to the key
32504
+ * @return The {@link SearchableMap} itself, to allow chaining
32505
+ */
32506
+ set(key, value) {
32507
+ if (typeof key !== "string") throw new Error("key must be a string");
32508
+ this._size = void 0;
32509
+ createPath(this._tree, key).set(LEAF, value);
32510
+ return this;
32511
+ }
32512
+ /**
32513
+ * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/size
32514
+ */
32515
+ get size() {
32516
+ if (this._size) return this._size;
32517
+ /** @ignore */
32518
+ this._size = 0;
32519
+ const iter = this.entries();
32520
+ while (!iter.next().done) this._size += 1;
32521
+ return this._size;
32522
+ }
32523
+ /**
32524
+ * Updates the value at the given key using the provided function. The function
32525
+ * is called with the current value at the key, and its return value is used as
32526
+ * the new value to be set.
32527
+ *
32528
+ * ### Example:
32529
+ *
32530
+ * ```javascript
32531
+ * // Increment the current value by one
32532
+ * searchableMap.update('somekey', (currentValue) => currentValue == null ? 0 : currentValue + 1)
32533
+ * ```
32534
+ *
32535
+ * If the value at the given key is or will be an object, it might not require
32536
+ * re-assignment. In that case it is better to use `fetch()`, because it is
32537
+ * faster.
32538
+ *
32539
+ * @param key The key to update
32540
+ * @param fn The function used to compute the new value from the current one
32541
+ * @return The {@link SearchableMap} itself, to allow chaining
32542
+ */
32543
+ update(key, fn) {
32544
+ if (typeof key !== "string") throw new Error("key must be a string");
32545
+ this._size = void 0;
32546
+ const node = createPath(this._tree, key);
32547
+ node.set(LEAF, fn(node.get(LEAF)));
32548
+ return this;
32549
+ }
32550
+ /**
32551
+ * Fetches the value of the given key. If the value does not exist, calls the
32552
+ * given function to create a new value, which is inserted at the given key
32553
+ * and subsequently returned.
32554
+ *
32555
+ * ### Example:
32556
+ *
32557
+ * ```javascript
32558
+ * const map = searchableMap.fetch('somekey', () => new Map())
32559
+ * map.set('foo', 'bar')
32560
+ * ```
32561
+ *
32562
+ * @param key The key to update
32563
+ * @param initial A function that creates a new value if the key does not exist
32564
+ * @return The existing or new value at the given key
32565
+ */
32566
+ fetch(key, initial) {
32567
+ if (typeof key !== "string") throw new Error("key must be a string");
32568
+ this._size = void 0;
32569
+ const node = createPath(this._tree, key);
32570
+ let value = node.get(LEAF);
32571
+ if (value === void 0) node.set(LEAF, value = initial());
32572
+ return value;
32573
+ }
32574
+ /**
32575
+ * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/values
32576
+ * @return An `Iterable` iterating through values.
32577
+ */
32578
+ values() {
32579
+ return new TreeIterator(this, VALUES);
32580
+ }
32581
+ /**
32582
+ * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/@@iterator
32583
+ */
32584
+ [Symbol.iterator]() {
32585
+ return this.entries();
32586
+ }
32587
+ /**
32588
+ * Creates a {@link SearchableMap} from an `Iterable` of entries
32589
+ *
32590
+ * @param entries Entries to be inserted in the {@link SearchableMap}
32591
+ * @return A new {@link SearchableMap} with the given entries
32592
+ */
32593
+ static from(entries) {
32594
+ const tree = new SearchableMap();
32595
+ for (const [key, value] of entries) tree.set(key, value);
32596
+ return tree;
32597
+ }
32598
+ /**
32599
+ * Creates a {@link SearchableMap} from the iterable properties of a JavaScript object
32600
+ *
32601
+ * @param object Object of entries for the {@link SearchableMap}
32602
+ * @return A new {@link SearchableMap} with the given entries
32603
+ */
32604
+ static fromObject(object) {
32605
+ return SearchableMap.from(Object.entries(object));
32606
+ }
32607
+ };
32608
+ const trackDown = (tree, key, path = []) => {
32609
+ if (key.length === 0 || tree == null) return [tree, path];
32610
+ for (const k of tree.keys()) if (k !== LEAF && key.startsWith(k)) {
32611
+ path.push([tree, k]);
32612
+ return trackDown(tree.get(k), key.slice(k.length), path);
32613
+ }
32614
+ path.push([tree, key]);
32615
+ return trackDown(void 0, "", path);
32616
+ };
32617
+ const lookup = (tree, key) => {
32618
+ if (key.length === 0 || tree == null) return tree;
32619
+ for (const k of tree.keys()) if (k !== LEAF && key.startsWith(k)) return lookup(tree.get(k), key.slice(k.length));
32620
+ };
32621
+ const createPath = (node, key) => {
32622
+ const keyLength = key.length;
32623
+ outer: for (let pos = 0; node && pos < keyLength;) {
32624
+ for (const k of node.keys()) if (k !== LEAF && key[pos] === k[0]) {
32625
+ const len = Math.min(keyLength - pos, k.length);
32626
+ let offset = 1;
32627
+ while (offset < len && key[pos + offset] === k[offset]) ++offset;
32628
+ const child = node.get(k);
32629
+ if (offset === k.length) node = child;
32630
+ else {
32631
+ const intermediate = /* @__PURE__ */ new Map();
32632
+ intermediate.set(k.slice(offset), child);
32633
+ node.set(key.slice(pos, pos + offset), intermediate);
32634
+ node.delete(k);
32635
+ node = intermediate;
32636
+ }
32637
+ pos += offset;
32638
+ continue outer;
32639
+ }
32640
+ const child = /* @__PURE__ */ new Map();
32641
+ node.set(key.slice(pos), child);
32642
+ return child;
32643
+ }
32644
+ return node;
32645
+ };
32646
+ const remove = (tree, key) => {
32647
+ const [node, path] = trackDown(tree, key);
32648
+ if (node === void 0) return;
32649
+ node.delete(LEAF);
32650
+ if (node.size === 0) cleanup(path);
32651
+ else if (node.size === 1) {
32652
+ const [key, value] = node.entries().next().value;
32653
+ merge(path, key, value);
32654
+ }
32655
+ };
32656
+ const cleanup = (path) => {
32657
+ if (path.length === 0) return;
32658
+ const [node, key] = last(path);
32659
+ node.delete(key);
32660
+ if (node.size === 0) cleanup(path.slice(0, -1));
32661
+ else if (node.size === 1) {
32662
+ const [key, value] = node.entries().next().value;
32663
+ if (key !== LEAF) merge(path.slice(0, -1), key, value);
32664
+ }
32665
+ };
32666
+ const merge = (path, key, value) => {
32667
+ if (path.length === 0) return;
32668
+ const [node, nodeKey] = last(path);
32669
+ node.set(nodeKey + key, value);
32670
+ node.delete(nodeKey);
32671
+ };
32672
+ const last = (array) => {
32673
+ return array[array.length - 1];
32674
+ };
32675
+ const OR = "or";
32676
+ const AND = "and";
32677
+ const AND_NOT = "and_not";
32678
+ /**
32679
+ * {@link MiniSearch} is the main entrypoint class, implementing a full-text
32680
+ * search engine in memory.
32681
+ *
32682
+ * @typeParam T The type of the documents being indexed.
32683
+ *
32684
+ * ### Basic example:
32685
+ *
32686
+ * ```javascript
32687
+ * const documents = [
32688
+ * {
32689
+ * id: 1,
32690
+ * title: 'Moby Dick',
32691
+ * text: 'Call me Ishmael. Some years ago...',
32692
+ * category: 'fiction'
32693
+ * },
32694
+ * {
32695
+ * id: 2,
32696
+ * title: 'Zen and the Art of Motorcycle Maintenance',
32697
+ * text: 'I can see by my watch...',
32698
+ * category: 'fiction'
32699
+ * },
32700
+ * {
32701
+ * id: 3,
32702
+ * title: 'Neuromancer',
32703
+ * text: 'The sky above the port was...',
32704
+ * category: 'fiction'
32705
+ * },
32706
+ * {
32707
+ * id: 4,
32708
+ * title: 'Zen and the Art of Archery',
32709
+ * text: 'At first sight it must seem...',
32710
+ * category: 'non-fiction'
32711
+ * },
32712
+ * // ...and more
32713
+ * ]
32714
+ *
32715
+ * // Create a search engine that indexes the 'title' and 'text' fields for
32716
+ * // full-text search. Search results will include 'title' and 'category' (plus the
32717
+ * // id field, that is always stored and returned)
32718
+ * const miniSearch = new MiniSearch({
32719
+ * fields: ['title', 'text'],
32720
+ * storeFields: ['title', 'category']
32721
+ * })
32722
+ *
32723
+ * // Add documents to the index
32724
+ * miniSearch.addAll(documents)
32725
+ *
32726
+ * // Search for documents:
32727
+ * let results = miniSearch.search('zen art motorcycle')
32728
+ * // => [
32729
+ * // { id: 2, title: 'Zen and the Art of Motorcycle Maintenance', category: 'fiction', score: 2.77258 },
32730
+ * // { id: 4, title: 'Zen and the Art of Archery', category: 'non-fiction', score: 1.38629 }
32731
+ * // ]
32732
+ * ```
32733
+ */
32734
+ var MiniSearch = class MiniSearch {
32735
+ /**
32736
+ * @param options Configuration options
32737
+ *
32738
+ * ### Examples:
32739
+ *
32740
+ * ```javascript
32741
+ * // Create a search engine that indexes the 'title' and 'text' fields of your
32742
+ * // documents:
32743
+ * const miniSearch = new MiniSearch({ fields: ['title', 'text'] })
32744
+ * ```
32745
+ *
32746
+ * ### ID Field:
32747
+ *
32748
+ * ```javascript
32749
+ * // Your documents are assumed to include a unique 'id' field, but if you want
32750
+ * // to use a different field for document identification, you can set the
32751
+ * // 'idField' option:
32752
+ * const miniSearch = new MiniSearch({ idField: 'key', fields: ['title', 'text'] })
32753
+ * ```
32754
+ *
32755
+ * ### Options and defaults:
32756
+ *
32757
+ * ```javascript
32758
+ * // The full set of options (here with their default value) is:
32759
+ * const miniSearch = new MiniSearch({
32760
+ * // idField: field that uniquely identifies a document
32761
+ * idField: 'id',
32762
+ *
32763
+ * // extractField: function used to get the value of a field in a document.
32764
+ * // By default, it assumes the document is a flat object with field names as
32765
+ * // property keys and field values as string property values, but custom logic
32766
+ * // can be implemented by setting this option to a custom extractor function.
32767
+ * extractField: (document, fieldName) => document[fieldName],
32768
+ *
32769
+ * // tokenize: function used to split fields into individual terms. By
32770
+ * // default, it is also used to tokenize search queries, unless a specific
32771
+ * // `tokenize` search option is supplied. When tokenizing an indexed field,
32772
+ * // the field name is passed as the second argument.
32773
+ * tokenize: (string, _fieldName) => string.split(SPACE_OR_PUNCTUATION),
32774
+ *
32775
+ * // processTerm: function used to process each tokenized term before
32776
+ * // indexing. It can be used for stemming and normalization. Return a falsy
32777
+ * // value in order to discard a term. By default, it is also used to process
32778
+ * // search queries, unless a specific `processTerm` option is supplied as a
32779
+ * // search option. When processing a term from a indexed field, the field
32780
+ * // name is passed as the second argument.
32781
+ * processTerm: (term, _fieldName) => term.toLowerCase(),
32782
+ *
32783
+ * // searchOptions: default search options, see the `search` method for
32784
+ * // details
32785
+ * searchOptions: undefined,
32786
+ *
32787
+ * // fields: document fields to be indexed. Mandatory, but not set by default
32788
+ * fields: undefined
32789
+ *
32790
+ * // storeFields: document fields to be stored and returned as part of the
32791
+ * // search results.
32792
+ * storeFields: []
32793
+ * })
32794
+ * ```
32795
+ */
32796
+ constructor(options) {
32797
+ if ((options === null || options === void 0 ? void 0 : options.fields) == null) throw new Error("MiniSearch: option \"fields\" must be provided");
32798
+ const autoVacuum = options.autoVacuum == null || options.autoVacuum === true ? defaultAutoVacuumOptions : options.autoVacuum;
32799
+ this._options = {
32800
+ ...defaultOptions,
32801
+ ...options,
32802
+ autoVacuum,
32803
+ searchOptions: {
32804
+ ...defaultSearchOptions,
32805
+ ...options.searchOptions || {}
32806
+ },
32807
+ autoSuggestOptions: {
32808
+ ...defaultAutoSuggestOptions,
32809
+ ...options.autoSuggestOptions || {}
32810
+ }
32811
+ };
32812
+ this._index = new SearchableMap();
32813
+ this._documentCount = 0;
32814
+ this._documentIds = /* @__PURE__ */ new Map();
32815
+ this._idToShortId = /* @__PURE__ */ new Map();
32816
+ this._fieldIds = {};
32817
+ this._fieldLength = /* @__PURE__ */ new Map();
32818
+ this._avgFieldLength = [];
32819
+ this._nextId = 0;
32820
+ this._storedFields = /* @__PURE__ */ new Map();
32821
+ this._dirtCount = 0;
32822
+ this._currentVacuum = null;
32823
+ this._enqueuedVacuum = null;
32824
+ this._enqueuedVacuumConditions = defaultVacuumConditions;
32825
+ this.addFields(this._options.fields);
32826
+ }
32827
+ /**
32828
+ * Adds a document to the index
32829
+ *
32830
+ * @param document The document to be indexed
32831
+ */
32832
+ add(document) {
32833
+ const { extractField, stringifyField, tokenize, processTerm, fields, idField } = this._options;
32834
+ const id = extractField(document, idField);
32835
+ if (id == null) throw new Error(`MiniSearch: document does not have ID field "${idField}"`);
32836
+ if (this._idToShortId.has(id)) throw new Error(`MiniSearch: duplicate ID ${id}`);
32837
+ const shortDocumentId = this.addDocumentId(id);
32838
+ this.saveStoredFields(shortDocumentId, document);
32839
+ for (const field of fields) {
32840
+ const fieldValue = extractField(document, field);
32841
+ if (fieldValue == null) continue;
32842
+ const tokens = tokenize(stringifyField(fieldValue, field), field);
32843
+ const fieldId = this._fieldIds[field];
32844
+ const uniqueTerms = new Set(tokens).size;
32845
+ this.addFieldLength(shortDocumentId, fieldId, this._documentCount - 1, uniqueTerms);
32846
+ for (const term of tokens) {
32847
+ const processedTerm = processTerm(term, field);
32848
+ if (Array.isArray(processedTerm)) for (const t of processedTerm) this.addTerm(fieldId, shortDocumentId, t);
32849
+ else if (processedTerm) this.addTerm(fieldId, shortDocumentId, processedTerm);
32850
+ }
32851
+ }
32852
+ }
32853
+ /**
32854
+ * Adds all the given documents to the index
32855
+ *
32856
+ * @param documents An array of documents to be indexed
32857
+ */
32858
+ addAll(documents) {
32859
+ for (const document of documents) this.add(document);
32860
+ }
32861
+ /**
32862
+ * Adds all the given documents to the index asynchronously.
32863
+ *
32864
+ * Returns a promise that resolves (to `undefined`) when the indexing is done.
32865
+ * This method is useful when index many documents, to avoid blocking the main
32866
+ * thread. The indexing is performed asynchronously and in chunks.
32867
+ *
32868
+ * @param documents An array of documents to be indexed
32869
+ * @param options Configuration options
32870
+ * @return A promise resolving to `undefined` when the indexing is done
32871
+ */
32872
+ addAllAsync(documents, options = {}) {
32873
+ const { chunkSize = 10 } = options;
32874
+ const acc = {
32875
+ chunk: [],
32876
+ promise: Promise.resolve()
32877
+ };
32878
+ const { chunk, promise } = documents.reduce(({ chunk, promise }, document, i) => {
32879
+ chunk.push(document);
32880
+ if ((i + 1) % chunkSize === 0) return {
32881
+ chunk: [],
32882
+ promise: promise.then(() => new Promise((resolve) => setTimeout(resolve, 0))).then(() => this.addAll(chunk))
32883
+ };
32884
+ else return {
32885
+ chunk,
32886
+ promise
32887
+ };
32888
+ }, acc);
32889
+ return promise.then(() => this.addAll(chunk));
32890
+ }
32891
+ /**
32892
+ * Removes the given document from the index.
32893
+ *
32894
+ * The document to remove must NOT have changed between indexing and removal,
32895
+ * otherwise the index will be corrupted.
32896
+ *
32897
+ * This method requires passing the full document to be removed (not just the
32898
+ * ID), and immediately removes the document from the inverted index, allowing
32899
+ * memory to be released. A convenient alternative is {@link
32900
+ * MiniSearch#discard}, which needs only the document ID, and has the same
32901
+ * visible effect, but delays cleaning up the index until the next vacuuming.
32902
+ *
32903
+ * @param document The document to be removed
32904
+ */
32905
+ remove(document) {
32906
+ const { tokenize, processTerm, extractField, stringifyField, fields, idField } = this._options;
32907
+ const id = extractField(document, idField);
32908
+ if (id == null) throw new Error(`MiniSearch: document does not have ID field "${idField}"`);
32909
+ const shortId = this._idToShortId.get(id);
32910
+ if (shortId == null) throw new Error(`MiniSearch: cannot remove document with ID ${id}: it is not in the index`);
32911
+ for (const field of fields) {
32912
+ const fieldValue = extractField(document, field);
32913
+ if (fieldValue == null) continue;
32914
+ const tokens = tokenize(stringifyField(fieldValue, field), field);
32915
+ const fieldId = this._fieldIds[field];
32916
+ const uniqueTerms = new Set(tokens).size;
32917
+ this.removeFieldLength(shortId, fieldId, this._documentCount, uniqueTerms);
32918
+ for (const term of tokens) {
32919
+ const processedTerm = processTerm(term, field);
32920
+ if (Array.isArray(processedTerm)) for (const t of processedTerm) this.removeTerm(fieldId, shortId, t);
32921
+ else if (processedTerm) this.removeTerm(fieldId, shortId, processedTerm);
32922
+ }
32923
+ }
32924
+ this._storedFields.delete(shortId);
32925
+ this._documentIds.delete(shortId);
32926
+ this._idToShortId.delete(id);
32927
+ this._fieldLength.delete(shortId);
32928
+ this._documentCount -= 1;
32929
+ }
32930
+ /**
32931
+ * Removes all the given documents from the index. If called with no arguments,
32932
+ * it removes _all_ documents from the index.
32933
+ *
32934
+ * @param documents The documents to be removed. If this argument is omitted,
32935
+ * all documents are removed. Note that, for removing all documents, it is
32936
+ * more efficient to call this method with no arguments than to pass all
32937
+ * documents.
32938
+ */
32939
+ removeAll(documents) {
32940
+ if (documents) for (const document of documents) this.remove(document);
32941
+ else if (arguments.length > 0) throw new Error("Expected documents to be present. Omit the argument to remove all documents.");
32942
+ else {
32943
+ this._index = new SearchableMap();
32944
+ this._documentCount = 0;
32945
+ this._documentIds = /* @__PURE__ */ new Map();
32946
+ this._idToShortId = /* @__PURE__ */ new Map();
32947
+ this._fieldLength = /* @__PURE__ */ new Map();
32948
+ this._avgFieldLength = [];
32949
+ this._storedFields = /* @__PURE__ */ new Map();
32950
+ this._nextId = 0;
32951
+ }
32952
+ }
32953
+ /**
32954
+ * Discards the document with the given ID, so it won't appear in search results
32955
+ *
32956
+ * It has the same visible effect of {@link MiniSearch.remove} (both cause the
32957
+ * document to stop appearing in searches), but a different effect on the
32958
+ * internal data structures:
32959
+ *
32960
+ * - {@link MiniSearch#remove} requires passing the full document to be
32961
+ * removed as argument, and removes it from the inverted index immediately.
32962
+ *
32963
+ * - {@link MiniSearch#discard} instead only needs the document ID, and
32964
+ * works by marking the current version of the document as discarded, so it
32965
+ * is immediately ignored by searches. This is faster and more convenient
32966
+ * than {@link MiniSearch#remove}, but the index is not immediately
32967
+ * modified. To take care of that, vacuuming is performed after a certain
32968
+ * number of documents are discarded, cleaning up the index and allowing
32969
+ * memory to be released.
32970
+ *
32971
+ * After discarding a document, it is possible to re-add a new version, and
32972
+ * only the new version will appear in searches. In other words, discarding
32973
+ * and re-adding a document works exactly like removing and re-adding it. The
32974
+ * {@link MiniSearch.replace} method can also be used to replace a document
32975
+ * with a new version.
32976
+ *
32977
+ * #### Details about vacuuming
32978
+ *
32979
+ * Repetite calls to this method would leave obsolete document references in
32980
+ * the index, invisible to searches. Two mechanisms take care of cleaning up:
32981
+ * clean up during search, and vacuuming.
32982
+ *
32983
+ * - Upon search, whenever a discarded ID is found (and ignored for the
32984
+ * results), references to the discarded document are removed from the
32985
+ * inverted index entries for the search terms. This ensures that subsequent
32986
+ * searches for the same terms do not need to skip these obsolete references
32987
+ * again.
32988
+ *
32989
+ * - In addition, vacuuming is performed automatically by default (see the
32990
+ * `autoVacuum` field in {@link Options}) after a certain number of
32991
+ * documents are discarded. Vacuuming traverses all terms in the index,
32992
+ * cleaning up all references to discarded documents. Vacuuming can also be
32993
+ * triggered manually by calling {@link MiniSearch#vacuum}.
32994
+ *
32995
+ * @param id The ID of the document to be discarded
32996
+ */
32997
+ discard(id) {
32998
+ const shortId = this._idToShortId.get(id);
32999
+ if (shortId == null) throw new Error(`MiniSearch: cannot discard document with ID ${id}: it is not in the index`);
33000
+ this._idToShortId.delete(id);
33001
+ this._documentIds.delete(shortId);
33002
+ this._storedFields.delete(shortId);
33003
+ (this._fieldLength.get(shortId) || []).forEach((fieldLength, fieldId) => {
33004
+ this.removeFieldLength(shortId, fieldId, this._documentCount, fieldLength);
33005
+ });
33006
+ this._fieldLength.delete(shortId);
33007
+ this._documentCount -= 1;
33008
+ this._dirtCount += 1;
33009
+ this.maybeAutoVacuum();
33010
+ }
33011
+ maybeAutoVacuum() {
33012
+ if (this._options.autoVacuum === false) return;
33013
+ const { minDirtFactor, minDirtCount, batchSize, batchWait } = this._options.autoVacuum;
33014
+ this.conditionalVacuum({
33015
+ batchSize,
33016
+ batchWait
33017
+ }, {
33018
+ minDirtCount,
33019
+ minDirtFactor
33020
+ });
33021
+ }
33022
+ /**
33023
+ * Discards the documents with the given IDs, so they won't appear in search
33024
+ * results
33025
+ *
33026
+ * It is equivalent to calling {@link MiniSearch#discard} for all the given
33027
+ * IDs, but with the optimization of triggering at most one automatic
33028
+ * vacuuming at the end.
33029
+ *
33030
+ * Note: to remove all documents from the index, it is faster and more
33031
+ * convenient to call {@link MiniSearch.removeAll} with no argument, instead
33032
+ * of passing all IDs to this method.
33033
+ */
33034
+ discardAll(ids) {
33035
+ const autoVacuum = this._options.autoVacuum;
33036
+ try {
33037
+ this._options.autoVacuum = false;
33038
+ for (const id of ids) this.discard(id);
33039
+ } finally {
33040
+ this._options.autoVacuum = autoVacuum;
33041
+ }
33042
+ this.maybeAutoVacuum();
33043
+ }
33044
+ /**
33045
+ * It replaces an existing document with the given updated version
33046
+ *
33047
+ * It works by discarding the current version and adding the updated one, so
33048
+ * it is functionally equivalent to calling {@link MiniSearch#discard}
33049
+ * followed by {@link MiniSearch#add}. The ID of the updated document should
33050
+ * be the same as the original one.
33051
+ *
33052
+ * Since it uses {@link MiniSearch#discard} internally, this method relies on
33053
+ * vacuuming to clean up obsolete document references from the index, allowing
33054
+ * memory to be released (see {@link MiniSearch#discard}).
33055
+ *
33056
+ * @param updatedDocument The updated document to replace the old version
33057
+ * with
33058
+ */
33059
+ replace(updatedDocument) {
33060
+ const { idField, extractField } = this._options;
33061
+ const id = extractField(updatedDocument, idField);
33062
+ this.discard(id);
33063
+ this.add(updatedDocument);
33064
+ }
33065
+ /**
33066
+ * Triggers a manual vacuuming, cleaning up references to discarded documents
33067
+ * from the inverted index
33068
+ *
33069
+ * Vacuuming is only useful for applications that use the {@link
33070
+ * MiniSearch#discard} or {@link MiniSearch#replace} methods.
33071
+ *
33072
+ * By default, vacuuming is performed automatically when needed (controlled by
33073
+ * the `autoVacuum` field in {@link Options}), so there is usually no need to
33074
+ * call this method, unless one wants to make sure to perform vacuuming at a
33075
+ * specific moment.
33076
+ *
33077
+ * Vacuuming traverses all terms in the inverted index in batches, and cleans
33078
+ * up references to discarded documents from the posting list, allowing memory
33079
+ * to be released.
33080
+ *
33081
+ * The method takes an optional object as argument with the following keys:
33082
+ *
33083
+ * - `batchSize`: the size of each batch (1000 by default)
33084
+ *
33085
+ * - `batchWait`: the number of milliseconds to wait between batches (10 by
33086
+ * default)
33087
+ *
33088
+ * On large indexes, vacuuming could have a non-negligible cost: batching
33089
+ * avoids blocking the thread for long, diluting this cost so that it is not
33090
+ * negatively affecting the application. Nonetheless, this method should only
33091
+ * be called when necessary, and relying on automatic vacuuming is usually
33092
+ * better.
33093
+ *
33094
+ * It returns a promise that resolves (to undefined) when the clean up is
33095
+ * completed. If vacuuming is already ongoing at the time this method is
33096
+ * called, a new one is enqueued immediately after the ongoing one, and a
33097
+ * corresponding promise is returned. However, no more than one vacuuming is
33098
+ * enqueued on top of the ongoing one, even if this method is called more
33099
+ * times (enqueuing multiple ones would be useless).
33100
+ *
33101
+ * @param options Configuration options for the batch size and delay. See
33102
+ * {@link VacuumOptions}.
33103
+ */
33104
+ vacuum(options = {}) {
33105
+ return this.conditionalVacuum(options);
33106
+ }
33107
+ conditionalVacuum(options, conditions) {
33108
+ if (this._currentVacuum) {
33109
+ this._enqueuedVacuumConditions = this._enqueuedVacuumConditions && conditions;
33110
+ if (this._enqueuedVacuum != null) return this._enqueuedVacuum;
33111
+ this._enqueuedVacuum = this._currentVacuum.then(() => {
33112
+ const conditions = this._enqueuedVacuumConditions;
33113
+ this._enqueuedVacuumConditions = defaultVacuumConditions;
33114
+ return this.performVacuuming(options, conditions);
33115
+ });
33116
+ return this._enqueuedVacuum;
33117
+ }
33118
+ if (this.vacuumConditionsMet(conditions) === false) return Promise.resolve();
33119
+ this._currentVacuum = this.performVacuuming(options);
33120
+ return this._currentVacuum;
33121
+ }
33122
+ async performVacuuming(options, conditions) {
33123
+ const initialDirtCount = this._dirtCount;
33124
+ if (this.vacuumConditionsMet(conditions)) {
33125
+ const batchSize = options.batchSize || defaultVacuumOptions.batchSize;
33126
+ const batchWait = options.batchWait || defaultVacuumOptions.batchWait;
33127
+ let i = 1;
33128
+ for (const [term, fieldsData] of this._index) {
33129
+ for (const [fieldId, fieldIndex] of fieldsData) for (const [shortId] of fieldIndex) {
33130
+ if (this._documentIds.has(shortId)) continue;
33131
+ if (fieldIndex.size <= 1) fieldsData.delete(fieldId);
33132
+ else fieldIndex.delete(shortId);
33133
+ }
33134
+ if (this._index.get(term).size === 0) this._index.delete(term);
33135
+ if (i % batchSize === 0) await new Promise((resolve) => setTimeout(resolve, batchWait));
33136
+ i += 1;
33137
+ }
33138
+ this._dirtCount -= initialDirtCount;
33139
+ }
33140
+ await null;
33141
+ this._currentVacuum = this._enqueuedVacuum;
33142
+ this._enqueuedVacuum = null;
33143
+ }
33144
+ vacuumConditionsMet(conditions) {
33145
+ if (conditions == null) return true;
33146
+ let { minDirtCount, minDirtFactor } = conditions;
33147
+ minDirtCount = minDirtCount || defaultAutoVacuumOptions.minDirtCount;
33148
+ minDirtFactor = minDirtFactor || defaultAutoVacuumOptions.minDirtFactor;
33149
+ return this.dirtCount >= minDirtCount && this.dirtFactor >= minDirtFactor;
33150
+ }
33151
+ /**
33152
+ * Is `true` if a vacuuming operation is ongoing, `false` otherwise
33153
+ */
33154
+ get isVacuuming() {
33155
+ return this._currentVacuum != null;
33156
+ }
33157
+ /**
33158
+ * The number of documents discarded since the most recent vacuuming
33159
+ */
33160
+ get dirtCount() {
33161
+ return this._dirtCount;
33162
+ }
33163
+ /**
33164
+ * A number between 0 and 1 giving an indication about the proportion of
33165
+ * documents that are discarded, and can therefore be cleaned up by vacuuming.
33166
+ * A value close to 0 means that the index is relatively clean, while a higher
33167
+ * value means that the index is relatively dirty, and vacuuming could release
33168
+ * memory.
33169
+ */
33170
+ get dirtFactor() {
33171
+ return this._dirtCount / (1 + this._documentCount + this._dirtCount);
33172
+ }
33173
+ /**
33174
+ * Returns `true` if a document with the given ID is present in the index and
33175
+ * available for search, `false` otherwise
33176
+ *
33177
+ * @param id The document ID
33178
+ */
33179
+ has(id) {
33180
+ return this._idToShortId.has(id);
33181
+ }
33182
+ /**
33183
+ * Returns the stored fields (as configured in the `storeFields` constructor
33184
+ * option) for the given document ID. Returns `undefined` if the document is
33185
+ * not present in the index.
33186
+ *
33187
+ * @param id The document ID
33188
+ */
33189
+ getStoredFields(id) {
33190
+ const shortId = this._idToShortId.get(id);
33191
+ if (shortId == null) return;
33192
+ return this._storedFields.get(shortId);
33193
+ }
33194
+ /**
33195
+ * Search for documents matching the given search query.
33196
+ *
33197
+ * The result is a list of scored document IDs matching the query, sorted by
33198
+ * descending score, and each including data about which terms were matched and
33199
+ * in which fields.
33200
+ *
33201
+ * ### Basic usage:
33202
+ *
33203
+ * ```javascript
33204
+ * // Search for "zen art motorcycle" with default options: terms have to match
33205
+ * // exactly, and individual terms are joined with OR
33206
+ * miniSearch.search('zen art motorcycle')
33207
+ * // => [ { id: 2, score: 2.77258, match: { ... } }, { id: 4, score: 1.38629, match: { ... } } ]
33208
+ * ```
33209
+ *
33210
+ * ### Restrict search to specific fields:
33211
+ *
33212
+ * ```javascript
33213
+ * // Search only in the 'title' field
33214
+ * miniSearch.search('zen', { fields: ['title'] })
33215
+ * ```
33216
+ *
33217
+ * ### Field boosting:
33218
+ *
33219
+ * ```javascript
33220
+ * // Boost a field
33221
+ * miniSearch.search('zen', { boost: { title: 2 } })
33222
+ * ```
33223
+ *
33224
+ * ### Prefix search:
33225
+ *
33226
+ * ```javascript
33227
+ * // Search for "moto" with prefix search (it will match documents
33228
+ * // containing terms that start with "moto" or "neuro")
33229
+ * miniSearch.search('moto neuro', { prefix: true })
33230
+ * ```
33231
+ *
33232
+ * ### Fuzzy search:
33233
+ *
33234
+ * ```javascript
33235
+ * // Search for "ismael" with fuzzy search (it will match documents containing
33236
+ * // terms similar to "ismael", with a maximum edit distance of 0.2 term.length
33237
+ * // (rounded to nearest integer)
33238
+ * miniSearch.search('ismael', { fuzzy: 0.2 })
33239
+ * ```
33240
+ *
33241
+ * ### Combining strategies:
33242
+ *
33243
+ * ```javascript
33244
+ * // Mix of exact match, prefix search, and fuzzy search
33245
+ * miniSearch.search('ismael mob', {
33246
+ * prefix: true,
33247
+ * fuzzy: 0.2
33248
+ * })
33249
+ * ```
33250
+ *
33251
+ * ### Advanced prefix and fuzzy search:
33252
+ *
33253
+ * ```javascript
33254
+ * // Perform fuzzy and prefix search depending on the search term. Here
33255
+ * // performing prefix and fuzzy search only on terms longer than 3 characters
33256
+ * miniSearch.search('ismael mob', {
33257
+ * prefix: term => term.length > 3
33258
+ * fuzzy: term => term.length > 3 ? 0.2 : null
33259
+ * })
33260
+ * ```
33261
+ *
33262
+ * ### Combine with AND:
33263
+ *
33264
+ * ```javascript
33265
+ * // Combine search terms with AND (to match only documents that contain both
33266
+ * // "motorcycle" and "art")
33267
+ * miniSearch.search('motorcycle art', { combineWith: 'AND' })
33268
+ * ```
33269
+ *
33270
+ * ### Combine with AND_NOT:
33271
+ *
33272
+ * There is also an AND_NOT combinator, that finds documents that match the
33273
+ * first term, but do not match any of the other terms. This combinator is
33274
+ * rarely useful with simple queries, and is meant to be used with advanced
33275
+ * query combinations (see later for more details).
33276
+ *
33277
+ * ### Filtering results:
33278
+ *
33279
+ * ```javascript
33280
+ * // Filter only results in the 'fiction' category (assuming that 'category'
33281
+ * // is a stored field)
33282
+ * miniSearch.search('motorcycle art', {
33283
+ * filter: (result) => result.category === 'fiction'
33284
+ * })
33285
+ * ```
33286
+ *
33287
+ * ### Wildcard query
33288
+ *
33289
+ * Searching for an empty string (assuming the default tokenizer) returns no
33290
+ * results. Sometimes though, one needs to match all documents, like in a
33291
+ * "wildcard" search. This is possible by passing the special value
33292
+ * {@link MiniSearch.wildcard} as the query:
33293
+ *
33294
+ * ```javascript
33295
+ * // Return search results for all documents
33296
+ * miniSearch.search(MiniSearch.wildcard)
33297
+ * ```
33298
+ *
33299
+ * Note that search options such as `filter` and `boostDocument` are still
33300
+ * applied, influencing which results are returned, and their order:
33301
+ *
33302
+ * ```javascript
33303
+ * // Return search results for all documents in the 'fiction' category
33304
+ * miniSearch.search(MiniSearch.wildcard, {
33305
+ * filter: (result) => result.category === 'fiction'
33306
+ * })
33307
+ * ```
33308
+ *
33309
+ * ### Advanced combination of queries:
33310
+ *
33311
+ * It is possible to combine different subqueries with OR, AND, and AND_NOT,
33312
+ * and even with different search options, by passing a query expression
33313
+ * tree object as the first argument, instead of a string.
33314
+ *
33315
+ * ```javascript
33316
+ * // Search for documents that contain "zen" and ("motorcycle" or "archery")
33317
+ * miniSearch.search({
33318
+ * combineWith: 'AND',
33319
+ * queries: [
33320
+ * 'zen',
33321
+ * {
33322
+ * combineWith: 'OR',
33323
+ * queries: ['motorcycle', 'archery']
33324
+ * }
33325
+ * ]
33326
+ * })
33327
+ *
33328
+ * // Search for documents that contain ("apple" or "pear") but not "juice" and
33329
+ * // not "tree"
33330
+ * miniSearch.search({
33331
+ * combineWith: 'AND_NOT',
33332
+ * queries: [
33333
+ * {
33334
+ * combineWith: 'OR',
33335
+ * queries: ['apple', 'pear']
33336
+ * },
33337
+ * 'juice',
33338
+ * 'tree'
33339
+ * ]
33340
+ * })
33341
+ * ```
33342
+ *
33343
+ * Each node in the expression tree can be either a string, or an object that
33344
+ * supports all {@link SearchOptions} fields, plus a `queries` array field for
33345
+ * subqueries.
33346
+ *
33347
+ * Note that, while this can become complicated to do by hand for complex or
33348
+ * deeply nested queries, it provides a formalized expression tree API for
33349
+ * external libraries that implement a parser for custom query languages.
33350
+ *
33351
+ * @param query Search query
33352
+ * @param searchOptions Search options. Each option, if not given, defaults to the corresponding value of `searchOptions` given to the constructor, or to the library default.
33353
+ */
33354
+ search(query, searchOptions = {}) {
33355
+ const { searchOptions: globalSearchOptions } = this._options;
33356
+ const searchOptionsWithDefaults = {
33357
+ ...globalSearchOptions,
33358
+ ...searchOptions
33359
+ };
33360
+ const rawResults = this.executeQuery(query, searchOptions);
33361
+ const results = [];
33362
+ for (const [docId, { score, terms, match }] of rawResults) {
33363
+ const quality = terms.length || 1;
33364
+ const result = {
33365
+ id: this._documentIds.get(docId),
33366
+ score: score * quality,
33367
+ terms: Object.keys(match),
33368
+ queryTerms: terms,
33369
+ match
33370
+ };
33371
+ Object.assign(result, this._storedFields.get(docId));
33372
+ if (searchOptionsWithDefaults.filter == null || searchOptionsWithDefaults.filter(result)) results.push(result);
33373
+ }
33374
+ if (query === MiniSearch.wildcard && searchOptionsWithDefaults.boostDocument == null) return results;
33375
+ results.sort(byScore);
33376
+ return results;
33377
+ }
33378
+ /**
33379
+ * Provide suggestions for the given search query
33380
+ *
33381
+ * The result is a list of suggested modified search queries, derived from the
33382
+ * given search query, each with a relevance score, sorted by descending score.
33383
+ *
33384
+ * By default, it uses the same options used for search, except that by
33385
+ * default it performs prefix search on the last term of the query, and
33386
+ * combine terms with `'AND'` (requiring all query terms to match). Custom
33387
+ * options can be passed as a second argument. Defaults can be changed upon
33388
+ * calling the {@link MiniSearch} constructor, by passing a
33389
+ * `autoSuggestOptions` option.
33390
+ *
33391
+ * ### Basic usage:
33392
+ *
33393
+ * ```javascript
33394
+ * // Get suggestions for 'neuro':
33395
+ * miniSearch.autoSuggest('neuro')
33396
+ * // => [ { suggestion: 'neuromancer', terms: [ 'neuromancer' ], score: 0.46240 } ]
33397
+ * ```
33398
+ *
33399
+ * ### Multiple words:
33400
+ *
33401
+ * ```javascript
33402
+ * // Get suggestions for 'zen ar':
33403
+ * miniSearch.autoSuggest('zen ar')
33404
+ * // => [
33405
+ * // { suggestion: 'zen archery art', terms: [ 'zen', 'archery', 'art' ], score: 1.73332 },
33406
+ * // { suggestion: 'zen art', terms: [ 'zen', 'art' ], score: 1.21313 }
33407
+ * // ]
33408
+ * ```
33409
+ *
33410
+ * ### Fuzzy suggestions:
33411
+ *
33412
+ * ```javascript
33413
+ * // Correct spelling mistakes using fuzzy search:
33414
+ * miniSearch.autoSuggest('neromancer', { fuzzy: 0.2 })
33415
+ * // => [ { suggestion: 'neuromancer', terms: [ 'neuromancer' ], score: 1.03998 } ]
33416
+ * ```
33417
+ *
33418
+ * ### Filtering:
33419
+ *
33420
+ * ```javascript
33421
+ * // Get suggestions for 'zen ar', but only within the 'fiction' category
33422
+ * // (assuming that 'category' is a stored field):
33423
+ * miniSearch.autoSuggest('zen ar', {
33424
+ * filter: (result) => result.category === 'fiction'
33425
+ * })
33426
+ * // => [
33427
+ * // { suggestion: 'zen archery art', terms: [ 'zen', 'archery', 'art' ], score: 1.73332 },
33428
+ * // { suggestion: 'zen art', terms: [ 'zen', 'art' ], score: 1.21313 }
33429
+ * // ]
33430
+ * ```
33431
+ *
33432
+ * @param queryString Query string to be expanded into suggestions
33433
+ * @param options Search options. The supported options and default values
33434
+ * are the same as for the {@link MiniSearch#search} method, except that by
33435
+ * default prefix search is performed on the last term in the query, and terms
33436
+ * are combined with `'AND'`.
33437
+ * @return A sorted array of suggestions sorted by relevance score.
33438
+ */
33439
+ autoSuggest(queryString, options = {}) {
33440
+ options = {
33441
+ ...this._options.autoSuggestOptions,
33442
+ ...options
33443
+ };
33444
+ const suggestions = /* @__PURE__ */ new Map();
33445
+ for (const { score, terms } of this.search(queryString, options)) {
33446
+ const phrase = terms.join(" ");
33447
+ const suggestion = suggestions.get(phrase);
33448
+ if (suggestion != null) {
33449
+ suggestion.score += score;
33450
+ suggestion.count += 1;
33451
+ } else suggestions.set(phrase, {
33452
+ score,
33453
+ terms,
33454
+ count: 1
33455
+ });
33456
+ }
33457
+ const results = [];
33458
+ for (const [suggestion, { score, terms, count }] of suggestions) results.push({
33459
+ suggestion,
33460
+ terms,
33461
+ score: score / count
33462
+ });
33463
+ results.sort(byScore);
33464
+ return results;
33465
+ }
33466
+ /**
33467
+ * Total number of documents available to search
33468
+ */
33469
+ get documentCount() {
33470
+ return this._documentCount;
33471
+ }
33472
+ /**
33473
+ * Number of terms in the index
33474
+ */
33475
+ get termCount() {
33476
+ return this._index.size;
33477
+ }
33478
+ /**
33479
+ * Deserializes a JSON index (serialized with `JSON.stringify(miniSearch)`)
33480
+ * and instantiates a MiniSearch instance. It should be given the same options
33481
+ * originally used when serializing the index.
33482
+ *
33483
+ * ### Usage:
33484
+ *
33485
+ * ```javascript
33486
+ * // If the index was serialized with:
33487
+ * let miniSearch = new MiniSearch({ fields: ['title', 'text'] })
33488
+ * miniSearch.addAll(documents)
33489
+ *
33490
+ * const json = JSON.stringify(miniSearch)
33491
+ * // It can later be deserialized like this:
33492
+ * miniSearch = MiniSearch.loadJSON(json, { fields: ['title', 'text'] })
33493
+ * ```
33494
+ *
33495
+ * @param json JSON-serialized index
33496
+ * @param options configuration options, same as the constructor
33497
+ * @return An instance of MiniSearch deserialized from the given JSON.
33498
+ */
33499
+ static loadJSON(json, options) {
33500
+ if (options == null) throw new Error("MiniSearch: loadJSON should be given the same options used when serializing the index");
33501
+ return this.loadJS(JSON.parse(json), options);
33502
+ }
33503
+ /**
33504
+ * Async equivalent of {@link MiniSearch.loadJSON}
33505
+ *
33506
+ * This function is an alternative to {@link MiniSearch.loadJSON} that returns
33507
+ * a promise, and loads the index in batches, leaving pauses between them to avoid
33508
+ * blocking the main thread. It tends to be slower than the synchronous
33509
+ * version, but does not block the main thread, so it can be a better choice
33510
+ * when deserializing very large indexes.
33511
+ *
33512
+ * @param json JSON-serialized index
33513
+ * @param options configuration options, same as the constructor
33514
+ * @return A Promise that will resolve to an instance of MiniSearch deserialized from the given JSON.
33515
+ */
33516
+ static async loadJSONAsync(json, options) {
33517
+ if (options == null) throw new Error("MiniSearch: loadJSON should be given the same options used when serializing the index");
33518
+ return this.loadJSAsync(JSON.parse(json), options);
33519
+ }
33520
+ /**
33521
+ * Returns the default value of an option. It will throw an error if no option
33522
+ * with the given name exists.
33523
+ *
33524
+ * @param optionName Name of the option
33525
+ * @return The default value of the given option
33526
+ *
33527
+ * ### Usage:
33528
+ *
33529
+ * ```javascript
33530
+ * // Get default tokenizer
33531
+ * MiniSearch.getDefault('tokenize')
33532
+ *
33533
+ * // Get default term processor
33534
+ * MiniSearch.getDefault('processTerm')
33535
+ *
33536
+ * // Unknown options will throw an error
33537
+ * MiniSearch.getDefault('notExisting')
33538
+ * // => throws 'MiniSearch: unknown option "notExisting"'
33539
+ * ```
33540
+ */
33541
+ static getDefault(optionName) {
33542
+ if (defaultOptions.hasOwnProperty(optionName)) return getOwnProperty(defaultOptions, optionName);
33543
+ else throw new Error(`MiniSearch: unknown option "${optionName}"`);
33544
+ }
33545
+ /**
33546
+ * @ignore
33547
+ */
33548
+ static loadJS(js, options) {
33549
+ const { index, documentIds, fieldLength, storedFields, serializationVersion } = js;
33550
+ const miniSearch = this.instantiateMiniSearch(js, options);
33551
+ miniSearch._documentIds = objectToNumericMap(documentIds);
33552
+ miniSearch._fieldLength = objectToNumericMap(fieldLength);
33553
+ miniSearch._storedFields = objectToNumericMap(storedFields);
33554
+ for (const [shortId, id] of miniSearch._documentIds) miniSearch._idToShortId.set(id, shortId);
33555
+ for (const [term, data] of index) {
33556
+ const dataMap = /* @__PURE__ */ new Map();
33557
+ for (const fieldId of Object.keys(data)) {
33558
+ let indexEntry = data[fieldId];
33559
+ if (serializationVersion === 1) indexEntry = indexEntry.ds;
33560
+ dataMap.set(parseInt(fieldId, 10), objectToNumericMap(indexEntry));
33561
+ }
33562
+ miniSearch._index.set(term, dataMap);
33563
+ }
33564
+ return miniSearch;
33565
+ }
33566
+ /**
33567
+ * @ignore
33568
+ */
33569
+ static async loadJSAsync(js, options) {
33570
+ const { index, documentIds, fieldLength, storedFields, serializationVersion } = js;
33571
+ const miniSearch = this.instantiateMiniSearch(js, options);
33572
+ miniSearch._documentIds = await objectToNumericMapAsync(documentIds);
33573
+ miniSearch._fieldLength = await objectToNumericMapAsync(fieldLength);
33574
+ miniSearch._storedFields = await objectToNumericMapAsync(storedFields);
33575
+ for (const [shortId, id] of miniSearch._documentIds) miniSearch._idToShortId.set(id, shortId);
33576
+ let count = 0;
33577
+ for (const [term, data] of index) {
33578
+ const dataMap = /* @__PURE__ */ new Map();
33579
+ for (const fieldId of Object.keys(data)) {
33580
+ let indexEntry = data[fieldId];
33581
+ if (serializationVersion === 1) indexEntry = indexEntry.ds;
33582
+ dataMap.set(parseInt(fieldId, 10), await objectToNumericMapAsync(indexEntry));
33583
+ }
33584
+ if (++count % 1e3 === 0) await wait(0);
33585
+ miniSearch._index.set(term, dataMap);
33586
+ }
33587
+ return miniSearch;
33588
+ }
33589
+ /**
33590
+ * @ignore
33591
+ */
33592
+ static instantiateMiniSearch(js, options) {
33593
+ const { documentCount, nextId, fieldIds, averageFieldLength, dirtCount, serializationVersion } = js;
33594
+ if (serializationVersion !== 1 && serializationVersion !== 2) throw new Error("MiniSearch: cannot deserialize an index created with an incompatible version");
33595
+ const miniSearch = new MiniSearch(options);
33596
+ miniSearch._documentCount = documentCount;
33597
+ miniSearch._nextId = nextId;
33598
+ miniSearch._idToShortId = /* @__PURE__ */ new Map();
33599
+ miniSearch._fieldIds = fieldIds;
33600
+ miniSearch._avgFieldLength = averageFieldLength;
33601
+ miniSearch._dirtCount = dirtCount || 0;
33602
+ miniSearch._index = new SearchableMap();
33603
+ return miniSearch;
33604
+ }
33605
+ /**
33606
+ * @ignore
33607
+ */
33608
+ executeQuery(query, searchOptions = {}) {
33609
+ if (query === MiniSearch.wildcard) return this.executeWildcardQuery(searchOptions);
33610
+ if (typeof query !== "string") {
33611
+ const options = {
33612
+ ...searchOptions,
33613
+ ...query,
33614
+ queries: void 0
33615
+ };
33616
+ const results = query.queries.map((subquery) => this.executeQuery(subquery, options));
33617
+ return this.combineResults(results, options.combineWith);
33618
+ }
33619
+ const { tokenize, processTerm, searchOptions: globalSearchOptions } = this._options;
33620
+ const options = {
33621
+ tokenize,
33622
+ processTerm,
33623
+ ...globalSearchOptions,
33624
+ ...searchOptions
33625
+ };
33626
+ const { tokenize: searchTokenize, processTerm: searchProcessTerm } = options;
33627
+ const results = searchTokenize(query).flatMap((term) => searchProcessTerm(term)).filter((term) => !!term).map(termToQuerySpec(options)).map((query) => this.executeQuerySpec(query, options));
33628
+ return this.combineResults(results, options.combineWith);
33629
+ }
33630
+ /**
33631
+ * @ignore
33632
+ */
33633
+ executeQuerySpec(query, searchOptions) {
33634
+ const options = {
33635
+ ...this._options.searchOptions,
33636
+ ...searchOptions
33637
+ };
33638
+ const boosts = (options.fields || this._options.fields).reduce((boosts, field) => ({
33639
+ ...boosts,
33640
+ [field]: getOwnProperty(options.boost, field) || 1
33641
+ }), {});
33642
+ const { boostDocument, weights, maxFuzzy, bm25: bm25params } = options;
33643
+ const { fuzzy: fuzzyWeight, prefix: prefixWeight } = {
33644
+ ...defaultSearchOptions.weights,
33645
+ ...weights
33646
+ };
33647
+ const data = this._index.get(query.term);
33648
+ const results = this.termResults(query.term, query.term, 1, query.termBoost, data, boosts, boostDocument, bm25params);
33649
+ let prefixMatches;
33650
+ let fuzzyMatches;
33651
+ if (query.prefix) prefixMatches = this._index.atPrefix(query.term);
33652
+ if (query.fuzzy) {
33653
+ const fuzzy = query.fuzzy === true ? .2 : query.fuzzy;
33654
+ const maxDistance = fuzzy < 1 ? Math.min(maxFuzzy, Math.round(query.term.length * fuzzy)) : fuzzy;
33655
+ if (maxDistance) fuzzyMatches = this._index.fuzzyGet(query.term, maxDistance);
33656
+ }
33657
+ if (prefixMatches) for (const [term, data] of prefixMatches) {
33658
+ const distance = term.length - query.term.length;
33659
+ if (!distance) continue;
33660
+ fuzzyMatches === null || fuzzyMatches === void 0 || fuzzyMatches.delete(term);
33661
+ const weight = prefixWeight * term.length / (term.length + .3 * distance);
33662
+ this.termResults(query.term, term, weight, query.termBoost, data, boosts, boostDocument, bm25params, results);
33663
+ }
33664
+ if (fuzzyMatches) for (const term of fuzzyMatches.keys()) {
33665
+ const [data, distance] = fuzzyMatches.get(term);
33666
+ if (!distance) continue;
33667
+ const weight = fuzzyWeight * term.length / (term.length + distance);
33668
+ this.termResults(query.term, term, weight, query.termBoost, data, boosts, boostDocument, bm25params, results);
33669
+ }
33670
+ return results;
33671
+ }
33672
+ /**
33673
+ * @ignore
33674
+ */
33675
+ executeWildcardQuery(searchOptions) {
33676
+ const results = /* @__PURE__ */ new Map();
33677
+ const options = {
33678
+ ...this._options.searchOptions,
33679
+ ...searchOptions
33680
+ };
33681
+ for (const [shortId, id] of this._documentIds) {
33682
+ const score = options.boostDocument ? options.boostDocument(id, "", this._storedFields.get(shortId)) : 1;
33683
+ results.set(shortId, {
33684
+ score,
33685
+ terms: [],
33686
+ match: {}
33687
+ });
33688
+ }
33689
+ return results;
33690
+ }
33691
+ /**
33692
+ * @ignore
33693
+ */
33694
+ combineResults(results, combineWith = OR) {
33695
+ if (results.length === 0) return /* @__PURE__ */ new Map();
33696
+ const combinator = combinators[combineWith.toLowerCase()];
33697
+ if (!combinator) throw new Error(`Invalid combination operator: ${combineWith}`);
33698
+ return results.reduce(combinator) || /* @__PURE__ */ new Map();
33699
+ }
33700
+ /**
33701
+ * Allows serialization of the index to JSON, to possibly store it and later
33702
+ * deserialize it with {@link MiniSearch.loadJSON}.
33703
+ *
33704
+ * Normally one does not directly call this method, but rather call the
33705
+ * standard JavaScript `JSON.stringify()` passing the {@link MiniSearch}
33706
+ * instance, and JavaScript will internally call this method. Upon
33707
+ * deserialization, one must pass to {@link MiniSearch.loadJSON} the same
33708
+ * options used to create the original instance that was serialized.
33709
+ *
33710
+ * ### Usage:
33711
+ *
33712
+ * ```javascript
33713
+ * // Serialize the index:
33714
+ * let miniSearch = new MiniSearch({ fields: ['title', 'text'] })
33715
+ * miniSearch.addAll(documents)
33716
+ * const json = JSON.stringify(miniSearch)
33717
+ *
33718
+ * // Later, to deserialize it:
33719
+ * miniSearch = MiniSearch.loadJSON(json, { fields: ['title', 'text'] })
33720
+ * ```
33721
+ *
33722
+ * @return A plain-object serializable representation of the search index.
33723
+ */
33724
+ toJSON() {
33725
+ const index = [];
33726
+ for (const [term, fieldIndex] of this._index) {
33727
+ const data = {};
33728
+ for (const [fieldId, freqs] of fieldIndex) data[fieldId] = Object.fromEntries(freqs);
33729
+ index.push([term, data]);
33730
+ }
33731
+ return {
33732
+ documentCount: this._documentCount,
33733
+ nextId: this._nextId,
33734
+ documentIds: Object.fromEntries(this._documentIds),
33735
+ fieldIds: this._fieldIds,
33736
+ fieldLength: Object.fromEntries(this._fieldLength),
33737
+ averageFieldLength: this._avgFieldLength,
33738
+ storedFields: Object.fromEntries(this._storedFields),
33739
+ dirtCount: this._dirtCount,
33740
+ index,
33741
+ serializationVersion: 2
33742
+ };
33743
+ }
33744
+ /**
33745
+ * @ignore
33746
+ */
33747
+ termResults(sourceTerm, derivedTerm, termWeight, termBoost, fieldTermData, fieldBoosts, boostDocumentFn, bm25params, results = /* @__PURE__ */ new Map()) {
33748
+ if (fieldTermData == null) return results;
33749
+ for (const field of Object.keys(fieldBoosts)) {
33750
+ const fieldBoost = fieldBoosts[field];
33751
+ const fieldId = this._fieldIds[field];
33752
+ const fieldTermFreqs = fieldTermData.get(fieldId);
33753
+ if (fieldTermFreqs == null) continue;
33754
+ let matchingFields = fieldTermFreqs.size;
33755
+ const avgFieldLength = this._avgFieldLength[fieldId];
33756
+ for (const docId of fieldTermFreqs.keys()) {
33757
+ if (!this._documentIds.has(docId)) {
33758
+ this.removeTerm(fieldId, docId, derivedTerm);
33759
+ matchingFields -= 1;
33760
+ continue;
33761
+ }
33762
+ const docBoost = boostDocumentFn ? boostDocumentFn(this._documentIds.get(docId), derivedTerm, this._storedFields.get(docId)) : 1;
33763
+ if (!docBoost) continue;
33764
+ const termFreq = fieldTermFreqs.get(docId);
33765
+ const fieldLength = this._fieldLength.get(docId)[fieldId];
33766
+ const rawScore = calcBM25Score(termFreq, matchingFields, this._documentCount, fieldLength, avgFieldLength, bm25params);
33767
+ const weightedScore = termWeight * termBoost * fieldBoost * docBoost * rawScore;
33768
+ const result = results.get(docId);
33769
+ if (result) {
33770
+ result.score += weightedScore;
33771
+ assignUniqueTerm(result.terms, sourceTerm);
33772
+ const match = getOwnProperty(result.match, derivedTerm);
33773
+ if (match) match.push(field);
33774
+ else result.match[derivedTerm] = [field];
33775
+ } else results.set(docId, {
33776
+ score: weightedScore,
33777
+ terms: [sourceTerm],
33778
+ match: { [derivedTerm]: [field] }
33779
+ });
33780
+ }
33781
+ }
33782
+ return results;
33783
+ }
33784
+ /**
33785
+ * @ignore
33786
+ */
33787
+ addTerm(fieldId, documentId, term) {
33788
+ const indexData = this._index.fetch(term, createMap);
33789
+ let fieldIndex = indexData.get(fieldId);
33790
+ if (fieldIndex == null) {
33791
+ fieldIndex = /* @__PURE__ */ new Map();
33792
+ fieldIndex.set(documentId, 1);
33793
+ indexData.set(fieldId, fieldIndex);
33794
+ } else {
33795
+ const docs = fieldIndex.get(documentId);
33796
+ fieldIndex.set(documentId, (docs || 0) + 1);
33797
+ }
33798
+ }
33799
+ /**
33800
+ * @ignore
33801
+ */
33802
+ removeTerm(fieldId, documentId, term) {
33803
+ if (!this._index.has(term)) {
33804
+ this.warnDocumentChanged(documentId, fieldId, term);
33805
+ return;
33806
+ }
33807
+ const indexData = this._index.fetch(term, createMap);
33808
+ const fieldIndex = indexData.get(fieldId);
33809
+ if (fieldIndex == null || fieldIndex.get(documentId) == null) this.warnDocumentChanged(documentId, fieldId, term);
33810
+ else if (fieldIndex.get(documentId) <= 1) if (fieldIndex.size <= 1) indexData.delete(fieldId);
33811
+ else fieldIndex.delete(documentId);
33812
+ else fieldIndex.set(documentId, fieldIndex.get(documentId) - 1);
33813
+ if (this._index.get(term).size === 0) this._index.delete(term);
33814
+ }
33815
+ /**
33816
+ * @ignore
33817
+ */
33818
+ warnDocumentChanged(shortDocumentId, fieldId, term) {
33819
+ for (const fieldName of Object.keys(this._fieldIds)) if (this._fieldIds[fieldName] === fieldId) {
33820
+ 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");
33821
+ return;
33822
+ }
33823
+ }
33824
+ /**
33825
+ * @ignore
33826
+ */
33827
+ addDocumentId(documentId) {
33828
+ const shortDocumentId = this._nextId;
33829
+ this._idToShortId.set(documentId, shortDocumentId);
33830
+ this._documentIds.set(shortDocumentId, documentId);
33831
+ this._documentCount += 1;
33832
+ this._nextId += 1;
33833
+ return shortDocumentId;
33834
+ }
33835
+ /**
33836
+ * @ignore
33837
+ */
33838
+ addFields(fields) {
33839
+ for (let i = 0; i < fields.length; i++) this._fieldIds[fields[i]] = i;
33840
+ }
33841
+ /**
33842
+ * @ignore
33843
+ */
33844
+ addFieldLength(documentId, fieldId, count, length) {
33845
+ let fieldLengths = this._fieldLength.get(documentId);
33846
+ if (fieldLengths == null) this._fieldLength.set(documentId, fieldLengths = []);
33847
+ fieldLengths[fieldId] = length;
33848
+ const totalFieldLength = (this._avgFieldLength[fieldId] || 0) * count + length;
33849
+ this._avgFieldLength[fieldId] = totalFieldLength / (count + 1);
33850
+ }
33851
+ /**
33852
+ * @ignore
33853
+ */
33854
+ removeFieldLength(documentId, fieldId, count, length) {
33855
+ if (count === 1) {
33856
+ this._avgFieldLength[fieldId] = 0;
33857
+ return;
33858
+ }
33859
+ const totalFieldLength = this._avgFieldLength[fieldId] * count - length;
33860
+ this._avgFieldLength[fieldId] = totalFieldLength / (count - 1);
33861
+ }
33862
+ /**
33863
+ * @ignore
33864
+ */
33865
+ saveStoredFields(documentId, doc) {
33866
+ const { storeFields, extractField } = this._options;
33867
+ if (storeFields == null || storeFields.length === 0) return;
33868
+ let documentFields = this._storedFields.get(documentId);
33869
+ if (documentFields == null) this._storedFields.set(documentId, documentFields = {});
33870
+ for (const fieldName of storeFields) {
33871
+ const fieldValue = extractField(doc, fieldName);
33872
+ if (fieldValue !== void 0) documentFields[fieldName] = fieldValue;
33873
+ }
33874
+ }
33875
+ };
33876
+ /**
33877
+ * The special wildcard symbol that can be passed to {@link MiniSearch#search}
33878
+ * to match all documents
33879
+ */
33880
+ MiniSearch.wildcard = Symbol("*");
33881
+ const getOwnProperty = (object, property) => Object.prototype.hasOwnProperty.call(object, property) ? object[property] : void 0;
33882
+ const combinators = {
33883
+ [OR]: (a, b) => {
33884
+ for (const docId of b.keys()) {
33885
+ const existing = a.get(docId);
33886
+ if (existing == null) a.set(docId, b.get(docId));
33887
+ else {
33888
+ const { score, terms, match } = b.get(docId);
33889
+ existing.score = existing.score + score;
33890
+ existing.match = Object.assign(existing.match, match);
33891
+ assignUniqueTerms(existing.terms, terms);
33892
+ }
33893
+ }
33894
+ return a;
33895
+ },
33896
+ [AND]: (a, b) => {
33897
+ const combined = /* @__PURE__ */ new Map();
33898
+ for (const docId of b.keys()) {
33899
+ const existing = a.get(docId);
33900
+ if (existing == null) continue;
33901
+ const { score, terms, match } = b.get(docId);
33902
+ assignUniqueTerms(existing.terms, terms);
33903
+ combined.set(docId, {
33904
+ score: existing.score + score,
33905
+ terms: existing.terms,
33906
+ match: Object.assign(existing.match, match)
33907
+ });
33908
+ }
33909
+ return combined;
33910
+ },
33911
+ [AND_NOT]: (a, b) => {
33912
+ for (const docId of b.keys()) a.delete(docId);
33913
+ return a;
33914
+ }
33915
+ };
33916
+ const defaultBM25params = {
33917
+ k: 1.2,
33918
+ b: .7,
33919
+ d: .5
33920
+ };
33921
+ const calcBM25Score = (termFreq, matchingCount, totalCount, fieldLength, avgFieldLength, bm25params) => {
33922
+ const { k, b, d } = bm25params;
33923
+ return Math.log(1 + (totalCount - matchingCount + .5) / (matchingCount + .5)) * (d + termFreq * (k + 1) / (termFreq + k * (1 - b + b * fieldLength / avgFieldLength)));
33924
+ };
33925
+ const termToQuerySpec = (options) => (term, i, terms) => {
33926
+ return {
33927
+ term,
33928
+ fuzzy: typeof options.fuzzy === "function" ? options.fuzzy(term, i, terms) : options.fuzzy || false,
33929
+ prefix: typeof options.prefix === "function" ? options.prefix(term, i, terms) : options.prefix === true,
33930
+ termBoost: typeof options.boostTerm === "function" ? options.boostTerm(term, i, terms) : 1
33931
+ };
33932
+ };
33933
+ const defaultOptions = {
33934
+ idField: "id",
33935
+ extractField: (document, fieldName) => document[fieldName],
33936
+ stringifyField: (fieldValue, fieldName) => fieldValue.toString(),
33937
+ tokenize: (text) => text.split(SPACE_OR_PUNCTUATION),
33938
+ processTerm: (term) => term.toLowerCase(),
33939
+ fields: void 0,
33940
+ searchOptions: void 0,
33941
+ storeFields: [],
33942
+ logger: (level, message) => {
33943
+ if (typeof (console === null || console === void 0 ? void 0 : console[level]) === "function") console[level](message);
33944
+ },
33945
+ autoVacuum: true
33946
+ };
33947
+ const defaultSearchOptions = {
33948
+ combineWith: OR,
33949
+ prefix: false,
33950
+ fuzzy: false,
33951
+ maxFuzzy: 6,
33952
+ boost: {},
33953
+ weights: {
33954
+ fuzzy: .45,
33955
+ prefix: .375
33956
+ },
33957
+ bm25: defaultBM25params
33958
+ };
33959
+ const defaultAutoSuggestOptions = {
33960
+ combineWith: AND,
33961
+ prefix: (term, i, terms) => i === terms.length - 1
33962
+ };
33963
+ const defaultVacuumOptions = {
33964
+ batchSize: 1e3,
33965
+ batchWait: 10
33966
+ };
33967
+ const defaultVacuumConditions = {
33968
+ minDirtFactor: .1,
33969
+ minDirtCount: 20
33970
+ };
33971
+ const defaultAutoVacuumOptions = {
33972
+ ...defaultVacuumOptions,
33973
+ ...defaultVacuumConditions
33974
+ };
33975
+ const assignUniqueTerm = (target, term) => {
33976
+ if (!target.includes(term)) target.push(term);
33977
+ };
33978
+ const assignUniqueTerms = (target, source) => {
33979
+ for (const term of source) if (!target.includes(term)) target.push(term);
33980
+ };
33981
+ const byScore = ({ score: a }, { score: b }) => b - a;
33982
+ const createMap = () => /* @__PURE__ */ new Map();
33983
+ const objectToNumericMap = (object) => {
33984
+ const map = /* @__PURE__ */ new Map();
33985
+ for (const key of Object.keys(object)) map.set(parseInt(key, 10), object[key]);
33986
+ return map;
33987
+ };
33988
+ const objectToNumericMapAsync = async (object) => {
33989
+ const map = /* @__PURE__ */ new Map();
33990
+ let count = 0;
33991
+ for (const key of Object.keys(object)) {
33992
+ map.set(parseInt(key, 10), object[key]);
33993
+ if (++count % 1e3 === 0) await wait(0);
33994
+ }
33995
+ return map;
33996
+ };
33997
+ const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
33998
+ const SPACE_OR_PUNCTUATION = /[\n\r\p{Z}\p{P}]+/u;
33999
+ //#endregion
32227
34000
  //#region src/services/Skill.ts
32228
34001
  const requireFrom$2 = createRequire(import.meta.url);
32229
34002
  const findCliPackageRoot = () => {
@@ -32417,50 +34190,85 @@ const buildRegistry = (fs, path, cliDir, haklexDir) => gen(function* () {
32417
34190
  }
32418
34191
  return [...all].sort((a, b) => a.order - b.order);
32419
34192
  });
32420
- const indexOfCaseInsensitive = (haystack, needle) => haystack.toLowerCase().indexOf(needle.toLowerCase());
32421
- const buildSnippets = (body, keyword) => {
32422
- const out = [];
34193
+ const buildIndex = (chapters) => {
34194
+ const mini = new MiniSearch({
34195
+ fields: [
34196
+ "title",
34197
+ "description",
34198
+ "body"
34199
+ ],
34200
+ storeFields: ["slug"],
34201
+ idField: "slug",
34202
+ searchOptions: {
34203
+ boost: {
34204
+ title: 3,
34205
+ description: 2
34206
+ },
34207
+ combineWith: "AND",
34208
+ prefix: true,
34209
+ fuzzy: .2
34210
+ }
34211
+ });
34212
+ mini.addAll(chapters.map((c) => ({
34213
+ slug: c.slug,
34214
+ title: c.title,
34215
+ description: c.description,
34216
+ body: c.body
34217
+ })));
34218
+ return mini;
34219
+ };
34220
+ /**
34221
+ * Tokenize the user's query string the same way MiniSearch does for indexing,
34222
+ * so snippets can be located in the body. We use this lightweight tokenizer
34223
+ * rather than `r.terms` because fuzzy / prefix matches expose the indexed
34224
+ * term, not the substring that appears in the body verbatim.
34225
+ */
34226
+ const tokenizeQuery = (s) => s.toLowerCase().split(/[\s\p{P}]+/u).filter((t) => t.length > 0);
34227
+ const buildSnippets = (body, terms) => {
34228
+ if (terms.length === 0) return [];
32423
34229
  const lower = body.toLowerCase();
32424
- const k = keyword.toLowerCase();
32425
- if (!k) return out;
32426
- let from = 0;
32427
- while (out.length < 3) {
32428
- const idx = lower.indexOf(k, from);
32429
- if (idx < 0) break;
32430
- const start = Math.max(0, idx - 60);
32431
- const end = Math.min(body.length, idx + keyword.length + 60);
32432
- let snippet = body.slice(start, end).replaceAll(/\s+/g, " ").trim();
32433
- if (start > 0) snippet = `…${snippet}`;
32434
- if (end < body.length) snippet = `${snippet}…`;
32435
- out.push(snippet);
32436
- from = idx + keyword.length;
34230
+ const occs = terms.map((term) => {
34231
+ const t = term.toLowerCase();
34232
+ if (!t) return [];
34233
+ const positions = [];
34234
+ let from = 0;
34235
+ while (positions.length < 5) {
34236
+ const idx = lower.indexOf(t, from);
34237
+ if (idx < 0) break;
34238
+ positions.push(idx);
34239
+ from = idx + t.length;
34240
+ }
34241
+ return positions;
34242
+ });
34243
+ const cursors = Array.from({ length: terms.length }).fill(0);
34244
+ const out = [];
34245
+ let progressed = true;
34246
+ while (out.length < 3 && progressed) {
34247
+ progressed = false;
34248
+ for (let i = 0; i < terms.length && out.length < 3; i++) {
34249
+ const c = cursors[i];
34250
+ if (c >= occs[i].length) continue;
34251
+ const idx = occs[i][c];
34252
+ const tLen = terms[i].length;
34253
+ cursors[i] = c + 1;
34254
+ progressed = true;
34255
+ const start = Math.max(0, idx - 60);
34256
+ const end = Math.min(body.length, idx + tLen + 60);
34257
+ let snippet = body.slice(start, end).replaceAll(/\s+/g, " ").trim();
34258
+ if (start > 0) snippet = `…${snippet}`;
34259
+ if (end < body.length) snippet = `${snippet}…`;
34260
+ out.push(snippet);
34261
+ }
32437
34262
  }
32438
34263
  return out;
32439
34264
  };
32440
- const rank = (chapter, keyword) => {
32441
- if (!keyword) return 0;
32442
- let score = 0;
32443
- if (indexOfCaseInsensitive(chapter.title, keyword) >= 0) score += 3;
32444
- if (indexOfCaseInsensitive(chapter.description, keyword) >= 0) score += 2;
32445
- const bodyLower = chapter.body.toLowerCase();
32446
- const k = keyword.toLowerCase();
32447
- let from = 0;
32448
- let count = 0;
32449
- while (count < 10) {
32450
- const idx = bodyLower.indexOf(k, from);
32451
- if (idx < 0) break;
32452
- count += 1;
32453
- from = idx + k.length;
32454
- }
32455
- score += count;
32456
- return score;
32457
- };
32458
34265
  const make$2 = gen(function* () {
32459
34266
  const fs = yield* FileSystem;
32460
34267
  const path = yield* Path$1;
32461
34268
  const cliDir = resolveCliSkillsDir();
32462
34269
  const haklexDir = resolveHaklexSkillsDir();
32463
34270
  const cache = yield* make$23(null);
34271
+ const indexCache = yield* make$23(null);
32464
34272
  const load = gen(function* () {
32465
34273
  const cached = yield* get$10(cache);
32466
34274
  if (cached) return cached;
@@ -32468,6 +34276,13 @@ const make$2 = gen(function* () {
32468
34276
  yield* set$3(cache, chapters);
32469
34277
  return chapters;
32470
34278
  });
34279
+ const loadIndex = gen(function* () {
34280
+ const cached = yield* get$10(indexCache);
34281
+ if (cached) return cached;
34282
+ const mini = buildIndex(yield* load);
34283
+ yield* set$3(indexCache, mini);
34284
+ return mini;
34285
+ });
32471
34286
  return {
32472
34287
  list: load,
32473
34288
  all: load,
@@ -32484,24 +34299,23 @@ const make$2 = gen(function* () {
32484
34299
  return found;
32485
34300
  }),
32486
34301
  search: (keyword) => gen(function* () {
32487
- const chapters = yield* load;
32488
34302
  const kw = keyword.trim();
32489
34303
  if (!kw) return [];
32490
- const scored = [];
32491
- for (const c of chapters) {
32492
- const s = rank(c, kw);
32493
- if (s > 0) scored.push({
32494
- chapter: c,
32495
- score: s
32496
- });
32497
- }
32498
- scored.sort((a, b) => b.score - a.score || a.chapter.order - b.chapter.order);
32499
- return scored.map(({ chapter }) => ({
32500
- slug: chapter.slug,
32501
- title: chapter.title,
32502
- description: chapter.description,
32503
- snippets: buildSnippets(chapter.body, kw)
32504
- }));
34304
+ const chapters = yield* load;
34305
+ const mini = yield* loadIndex;
34306
+ const tokens = tokenizeQuery(kw);
34307
+ const results = mini.search(kw);
34308
+ const bySlug = new Map(chapters.map((c) => [c.slug, c]));
34309
+ return results.flatMap((r) => {
34310
+ const chapter = bySlug.get(r.id);
34311
+ if (!chapter) return [];
34312
+ return [{
34313
+ slug: chapter.slug,
34314
+ title: chapter.title,
34315
+ description: chapter.description,
34316
+ snippets: buildSnippets(chapter.body, tokens)
34317
+ }];
34318
+ });
32505
34319
  })
32506
34320
  };
32507
34321
  });