@delali/narsil 0.3.1-next.70 → 0.3.1-next.71

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/react.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { createContext, useState, useEffect, createElement, useRef, useEffectEvent, useCallback, useMemo, useContext, useSyncExternalStore } from 'react';
1
+ import { createContext, useState, createElement, useRef, useEffectEvent, useEffect, useCallback, useMemo, useContext, useSyncExternalStore } from 'react';
2
2
 
3
3
  // src/errors.ts
4
4
  var NARSIL_ERROR_MARKER = /* @__PURE__ */ Symbol.for("@delali/narsil.NarsilError");
@@ -147,8 +147,53 @@ function isNarsilError(value) {
147
147
  return typeof value === "object" && value !== null && NARSIL_ERROR_MARKER in value;
148
148
  }
149
149
 
150
+ // src/react/reader.ts
151
+ function plainNumbersIn(value) {
152
+ if (value === null || typeof value !== "object") return value;
153
+ if (ArrayBuffer.isView(value)) {
154
+ return value instanceof DataView ? value : Array.from(value);
155
+ }
156
+ if (Array.isArray(value)) {
157
+ let copy2 = null;
158
+ for (let at = 0; at < value.length; at++) {
159
+ const converted = plainNumbersIn(value[at]);
160
+ if (converted === value[at]) continue;
161
+ copy2 ??= value.slice();
162
+ copy2[at] = converted;
163
+ }
164
+ return copy2 ?? value;
165
+ }
166
+ let copy = null;
167
+ for (const [key, held] of Object.entries(value)) {
168
+ const converted = plainNumbersIn(held);
169
+ if (converted === held) continue;
170
+ copy ??= { ...value };
171
+ copy[key] = converted;
172
+ }
173
+ return copy ?? value;
174
+ }
175
+ function withPlainNumbers(answer) {
176
+ return answer.then((value) => plainNumbersIn(value));
177
+ }
178
+ function engineReader(engine) {
179
+ return {
180
+ query(indexName, params) {
181
+ return withPlainNumbers(engine.query(indexName, params));
182
+ },
183
+ preflight: (indexName, params) => engine.preflight(indexName, params),
184
+ suggest: (indexName, params) => engine.suggest(indexName, params),
185
+ get: (indexName, docId) => withPlainNumbers(engine.get(indexName, docId)),
186
+ listDocuments(indexName, params) {
187
+ return withPlainNumbers(engine.listDocuments(indexName, params));
188
+ },
189
+ listIndexes: async () => engine.listIndexes(),
190
+ getStats: async (indexName) => engine.getStats(indexName)
191
+ };
192
+ }
193
+
150
194
  // src/react/constants.ts
151
195
  var DEFAULT_KEEP_ALIVE_MS = 2e3;
196
+ var DEFAULT_REFRESH_AFTER_WRITE_MS = 200;
152
197
  var DEFAULT_TASK_POLL_INTERVAL_MS = 250;
153
198
  var ERROR_RETRY_INTERVAL_MS = 5e3;
154
199
  var MAX_QUERY_KEY_DEPTH = 32;
@@ -173,10 +218,13 @@ var IDLE_SNAPSHOT = Object.freeze({
173
218
  isLoading: false,
174
219
  isFetching: false
175
220
  });
176
- function createResourceStore(keepAliveMs = DEFAULT_KEEP_ALIVE_MS) {
221
+ var ANY_INDEX = /* @__PURE__ */ Symbol("any index");
222
+ var NO_INDEX = /* @__PURE__ */ Symbol("no index");
223
+ function createResourceStore(keepAliveMs = DEFAULT_KEEP_ALIVE_MS, refreshAfterWriteMs = DEFAULT_REFRESH_AFTER_WRITE_MS) {
177
224
  const entries = /* @__PURE__ */ new Map();
178
225
  let holders = 0;
179
226
  let closing = null;
227
+ const staleRefreshes = /* @__PURE__ */ new Map();
180
228
  function publish(entry, next) {
181
229
  entry.snapshot = next;
182
230
  for (const listener of entry.listeners) listener();
@@ -185,6 +233,7 @@ function createResourceStore(keepAliveMs = DEFAULT_KEEP_ALIVE_MS) {
185
233
  if (entry.controller !== null) return;
186
234
  const controller = new AbortController();
187
235
  entry.controller = controller;
236
+ entry.stale = false;
188
237
  entry.version++;
189
238
  const version = entry.version;
190
239
  if (!entry.snapshot.isFetching) publish(entry, { ...entry.snapshot, isFetching: true });
@@ -209,9 +258,32 @@ function createResourceStore(keepAliveMs = DEFAULT_KEEP_ALIVE_MS) {
209
258
  );
210
259
  }
211
260
  function disposeAll() {
261
+ for (const timer of staleRefreshes.values()) clearTimeout(timer);
262
+ staleRefreshes.clear();
212
263
  for (const [key, entry] of [...entries]) drop(key, entry);
213
264
  entries.clear();
214
265
  }
266
+ function refreshStale(scope) {
267
+ staleRefreshes.delete(scope);
268
+ for (const [key, entry] of entries) {
269
+ if (entry.writeScope === scope && entry.stale && entry.listeners.size > 0) load(key, entry);
270
+ }
271
+ }
272
+ function scheduleRefresh(scope) {
273
+ const pending = staleRefreshes.get(scope);
274
+ if (pending !== void 0) clearTimeout(pending);
275
+ staleRefreshes.set(
276
+ scope,
277
+ setTimeout(() => refreshStale(scope), refreshAfterWriteMs)
278
+ );
279
+ }
280
+ function markStale(entry) {
281
+ entry.stale = true;
282
+ if (entry.controller === null) return;
283
+ entry.controller.abort();
284
+ entry.controller = null;
285
+ entry.version++;
286
+ }
215
287
  function drop(key, entry) {
216
288
  if (entries.get(key) === entry) entries.delete(key);
217
289
  if (entry.disposal !== null) clearTimeout(entry.disposal);
@@ -220,7 +292,7 @@ function createResourceStore(keepAliveMs = DEFAULT_KEEP_ALIVE_MS) {
220
292
  entry.controller = null;
221
293
  }
222
294
  return {
223
- subscribe(key, loader, onChange) {
295
+ subscribe(key, loader, onChange, writeScope) {
224
296
  let entry = entries.get(key);
225
297
  if (entry === void 0) {
226
298
  entry = {
@@ -229,7 +301,9 @@ function createResourceStore(keepAliveMs = DEFAULT_KEEP_ALIVE_MS) {
229
301
  loader,
230
302
  controller: null,
231
303
  version: 0,
232
- disposal: null
304
+ disposal: null,
305
+ writeScope,
306
+ stale: false
233
307
  };
234
308
  entries.set(key, entry);
235
309
  } else {
@@ -241,7 +315,7 @@ function createResourceStore(keepAliveMs = DEFAULT_KEEP_ALIVE_MS) {
241
315
  }
242
316
  const held = entry;
243
317
  held.listeners.add(onChange);
244
- const retryable = held.snapshot.isLoading || held.snapshot.error !== void 0;
318
+ const retryable = held.stale || held.snapshot.isLoading || held.snapshot.error !== void 0;
245
319
  if (retryable && held.controller === null) load(key, held);
246
320
  return () => {
247
321
  held.listeners.delete(onChange);
@@ -259,6 +333,15 @@ function createResourceStore(keepAliveMs = DEFAULT_KEEP_ALIVE_MS) {
259
333
  const entry = entries.get(key);
260
334
  if (entry !== void 0) load(key, entry);
261
335
  },
336
+ invalidate(indexName) {
337
+ const marked = /* @__PURE__ */ new Set();
338
+ for (const entry of entries.values()) {
339
+ if (entry.writeScope !== ANY_INDEX && entry.writeScope !== indexName) continue;
340
+ markStale(entry);
341
+ marked.add(entry.writeScope);
342
+ }
343
+ for (const scope of marked) scheduleRefresh(scope);
344
+ },
262
345
  retain() {
263
346
  holders++;
264
347
  if (closing !== null) {
@@ -283,30 +366,72 @@ function createResourceStore(keepAliveMs = DEFAULT_KEEP_ALIVE_MS) {
283
366
 
284
367
  // src/react/context.ts
285
368
  var NarsilContext = createContext(null);
286
- function build(client, keepAliveMs) {
287
- return { client, store: createResourceStore(keepAliveMs), keepAliveMs };
369
+ function buildContextValue(props) {
370
+ const { client, engine, keepAliveMs, refreshAfterWriteMs } = props;
371
+ const shared = { store: createResourceStore(keepAliveMs, refreshAfterWriteMs), keepAliveMs, refreshAfterWriteMs };
372
+ if (client !== void 0 && engine === void 0) return { ...shared, reader: client, client, engine: null };
373
+ if (engine !== void 0 && client === void 0) {
374
+ return { ...shared, reader: engineReader(engine), client: null, engine };
375
+ }
376
+ throw new NarsilError(
377
+ ErrorCodes.CONFIG_INVALID,
378
+ "A NarsilProvider requires exactly one of client and engine, but its props set both or neither"
379
+ );
380
+ }
381
+ function providerPropsChanged(value, props) {
382
+ return value.client !== (props.client ?? null) || value.engine !== (props.engine ?? null) || value.keepAliveMs !== props.keepAliveMs || value.refreshAfterWriteMs !== props.refreshAfterWriteMs;
383
+ }
384
+ function useStoreRetention(store) {
385
+ useEffect(() => store.retain(), [store]);
386
+ }
387
+ function useRefreshAfterWrites(engine, store) {
388
+ useEffect(() => {
389
+ if (engine === null) return;
390
+ const onWrite = (payload) => {
391
+ store.invalidate(payload.indexName);
392
+ };
393
+ engine.on("write", onWrite);
394
+ return () => {
395
+ engine.off("write", onWrite);
396
+ };
397
+ }, [engine, store]);
288
398
  }
289
399
  function NarsilProvider(props) {
290
- const { client, keepAliveMs, children } = props;
291
- const [value, setValue] = useState(() => build(client, keepAliveMs));
292
- if (value.client !== client || value.keepAliveMs !== keepAliveMs) {
293
- setValue(build(client, keepAliveMs));
400
+ const [value, setValue] = useState(() => buildContextValue(props));
401
+ if (providerPropsChanged(value, props)) {
402
+ setValue(buildContextValue(props));
294
403
  }
295
- useEffect(() => value.store.retain(), [value]);
296
- return createElement(NarsilContext.Provider, { value }, children);
404
+ useStoreRetention(value.store);
405
+ useRefreshAfterWrites(value.engine, value.store);
406
+ return createElement(NarsilContext.Provider, { value }, props.children);
297
407
  }
298
408
  function useNarsilContext() {
299
409
  const value = useContext(NarsilContext);
300
410
  if (value === null) {
301
411
  throw new NarsilError(
302
412
  ErrorCodes.CONFIG_INVALID,
303
- "A Narsil hook ran outside a NarsilProvider, so it found no client to send through"
413
+ "A Narsil hook was called outside a NarsilProvider, so no client or engine is available to it"
304
414
  );
305
415
  }
306
416
  return value;
307
417
  }
418
+ function useServerClient(hookName) {
419
+ const { client } = useNarsilContext();
420
+ if (client !== null) return client;
421
+ throw new NarsilError(
422
+ ErrorCodes.CONFIG_INVALID,
423
+ `${hookName} works only under a client of a server, because only a server handles tasks and imports, while the NarsilProvider above it holds an engine`,
424
+ { hook: hookName }
425
+ );
426
+ }
308
427
  function useNarsilClient() {
309
- return useNarsilContext().client;
428
+ const { client } = useNarsilContext();
429
+ if (client !== null) return client;
430
+ throw new NarsilError(
431
+ ErrorCodes.CONFIG_INVALID,
432
+ "useNarsilClient returns a client, while the NarsilProvider above it holds an engine, so import that engine directly",
433
+ { hook: "useNarsilClient" }
434
+ );
310
435
  }
311
436
 
312
437
  // src/react/key.ts
@@ -457,8 +582,8 @@ function useKey(parts) {
457
582
  cached.current = { parts, key };
458
583
  return key;
459
584
  }
460
- function useRead(parts, run, options) {
461
- const { client, store } = useNarsilContext();
585
+ function useRead(source, parts, run, options, writeScope) {
586
+ const { store } = useNarsilContext();
462
587
  const enabled = options?.enabled ?? true;
463
588
  const headers = options?.headers;
464
589
  const timeoutMs = options?.timeoutMs;
@@ -472,11 +597,11 @@ function useRead(parts, run, options) {
472
597
  if (!enabled) return NO_SUBSCRIPTION;
473
598
  const loader = (signal) => {
474
599
  const held = call.current;
475
- return held.run(client, { ...held.request, signal });
600
+ return held.run(source, { ...held.request, signal });
476
601
  };
477
- return store.subscribe(key, loader, onChange);
602
+ return store.subscribe(key, loader, onChange, writeScope);
478
603
  },
479
- [enabled, store, client, key]
604
+ [enabled, store, source, key, writeScope]
480
605
  );
481
606
  const readSnapshot = useCallback(
482
607
  () => enabled ? store.snapshot(key) : IDLE_SNAPSHOT,
@@ -508,21 +633,28 @@ function useRead(parts, run, options) {
508
633
  [data, snapshot, refresh]
509
634
  );
510
635
  }
636
+ function useProviderRead(parts, run, options, writeScope) {
637
+ const { reader } = useNarsilContext();
638
+ return useRead(reader, parts, run, options, writeScope);
639
+ }
511
640
 
512
641
  // src/react/documents.ts
513
642
  function useDocument(indexName, docId, options) {
514
643
  const id = docId ?? "";
515
644
  const enabled = (options?.enabled ?? true) && id.length > 0;
516
- return useRead(["get", indexName, id], (client, request) => client.get(indexName, id, request), {
517
- ...options,
518
- enabled
519
- });
645
+ return useProviderRead(
646
+ ["get", indexName, id],
647
+ (reader, request) => reader.get(indexName, id, request),
648
+ { ...options, enabled },
649
+ indexName
650
+ );
520
651
  }
521
652
  function useDocuments(indexName, params, options) {
522
- return useRead(
653
+ return useProviderRead(
523
654
  ["listDocuments", indexName, params],
524
- (client, request) => client.listDocuments(indexName, params, request),
525
- options
655
+ (reader, request) => reader.listDocuments(indexName, params, request),
656
+ options,
657
+ indexName
526
658
  );
527
659
  }
528
660
 
@@ -544,7 +676,7 @@ function isTerminalTask(record) {
544
676
  // src/react/import.ts
545
677
  var NOTHING = { task: void 0, error: void 0, starting: false };
546
678
  function useImport(indexName, options) {
547
- const client = useNarsilClient();
679
+ const client = useServerClient("useImport");
548
680
  const [progress, setProgress] = useState(NOTHING);
549
681
  const polling = useRef(null);
550
682
  const sending = useRef(null);
@@ -652,51 +784,63 @@ function useImport(indexName, options) {
652
784
 
653
785
  // src/react/indexes.ts
654
786
  function useIndexes(options) {
655
- return useRead(["listIndexes"], (client, request) => client.listIndexes(request), options);
787
+ return useProviderRead(["listIndexes"], (reader, request) => reader.listIndexes(request), options, ANY_INDEX);
656
788
  }
657
789
  function useStats(indexName, options) {
658
- return useRead(["getStats", indexName], (client, request) => client.getStats(indexName, request), options);
790
+ return useProviderRead(
791
+ ["getStats", indexName],
792
+ (reader, request) => reader.getStats(indexName, request),
793
+ options,
794
+ indexName
795
+ );
659
796
  }
660
797
 
661
798
  // src/react/search.ts
662
799
  function useQuery(indexName, params, options) {
663
- return useRead(
800
+ return useProviderRead(
664
801
  ["query", indexName, params],
665
- (client, request) => client.query(indexName, params, request),
666
- options
802
+ (reader, request) => reader.query(indexName, params, request),
803
+ options,
804
+ indexName
667
805
  );
668
806
  }
669
807
  function usePreflight(indexName, params, options) {
670
- return useRead(
808
+ return useProviderRead(
671
809
  ["preflight", indexName, params],
672
- (client, request) => client.preflight(indexName, params, request),
673
- options
810
+ (reader, request) => reader.preflight(indexName, params, request),
811
+ options,
812
+ indexName
674
813
  );
675
814
  }
676
815
  function useSuggest(indexName, params, options) {
677
- return useRead(
816
+ return useProviderRead(
678
817
  ["suggest", indexName, params],
679
- (client, request) => client.suggest(indexName, params, request),
680
- options
818
+ (reader, request) => reader.suggest(indexName, params, request),
819
+ options,
820
+ indexName
681
821
  );
682
822
  }
683
823
 
684
824
  // src/react/tasks.ts
685
825
  function useTask(taskId, options) {
826
+ const client = useServerClient("useTask");
686
827
  const id = taskId ?? "";
687
828
  const enabled = (options?.enabled ?? true) && id.length > 0;
688
- const state = useRead(["getTask", id], (client, request) => client.getTask(id, request), {
689
- ...options,
690
- enabled,
691
- refreshIntervalMs: 0
692
- });
829
+ const state = useRead(
830
+ client,
831
+ ["getTask", id],
832
+ (server, request) => server.getTask(id, request),
833
+ { ...options, enabled, refreshIntervalMs: 0 },
834
+ NO_INDEX
835
+ );
693
836
  const running = state.data !== null && !isTerminalTask(state.data);
694
837
  const interval = pollInterval(options?.pollIntervalMs ?? DEFAULT_TASK_POLL_INTERVAL_MS, state.error !== void 0);
695
838
  usePolling(state.refresh, interval, enabled && running);
696
839
  return state;
697
840
  }
698
841
  function useTasks(query, options) {
699
- return useRead(["listTasks", query], (client, request) => client.listTasks(query, request), options);
842
+ const client = useServerClient("useTasks");
843
+ return useRead(client, ["listTasks", query], (server, request) => server.listTasks(query, request), options, NO_INDEX);
700
844
  }
701
845
 
702
846
  export { ClientErrorCodes, ErrorCodes, NarsilError, NarsilProvider, ServerErrorCodes, isNarsilError, useDocument, useDocuments, useImport, useIndexes, useNarsilClient, usePreflight, useQuery, useStats, useSuggest, useTask, useTasks };
package/dist/server.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  export { C as ClientErrorCode, a as ClientErrorCodes, E as ErrorCode, b as ErrorCodes, N as NarsilError, c as NarsilErrorCode, S as ServerErrorCode, d as ServerErrorCodes, i as isNarsilError } from './memory-C7UMCMH3.js';
2
2
  import { b as ServerOptions, N as NarsilServer } from './capabilities-Dt-7B4Wz.js';
3
3
  export { A as ASYNC_IMPORT_CAPABILITY, C as CorsOptions, E as ErrorEnvelope, I as INDEX_LIFECYCLE_CAPABILITY, O as OnRequestHook, R as REBUILD_ANALYSIS_CAPABILITY, c as RequestContext, d as RequestDenial, S as SERVER_CAPABILITIES, e as ServerLimits, T as TASK_CANCEL_CAPABILITY, a as TASK_FILTER_CAPABILITY } from './capabilities-Dt-7B4Wz.js';
4
- import { a as Narsil } from './engine-CXKfmK7I.js';
4
+ import { a as Narsil } from './engine-igk0aMpQ.js';
5
5
  import { d as TaskProgress, b as ImportResult, h as TaskStore, e as TaskRecord } from './tasks-BZt_zes6.js';
6
6
  export { C as CapabilitiesResponse, a as CreateIndexEmbedding, i as CreateIndexRequest, H as HttpIndexConfig, I as ImportError, M as MemoryStatsResponse, T as TaskListPage, c as TaskListQuery, f as TaskStatus, g as TaskType } from './tasks-BZt_zes6.js';
7
7
  import './schema-Bgzr4g7b.js';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@delali/narsil",
3
- "version": "0.3.1-next.70",
3
+ "version": "0.3.1-next.71",
4
4
  "type": "module",
5
5
  "description": "Distributed search engine with full-text, vector, hybrid, and geosearch. One engine, embedded or on a server, with a cross-language .nrsl format.",
6
6
  "author": "Delali (https://sondelali.com)",
@@ -223,11 +223,11 @@
223
223
  }
224
224
  },
225
225
  "optionalDependencies": {
226
- "@delali/narsil-native-darwin-arm64": "0.3.1-next.70",
227
- "@delali/narsil-native-darwin-x64": "0.3.1-next.70",
228
- "@delali/narsil-native-linux-arm64": "0.3.1-next.70",
229
- "@delali/narsil-native-linux-x64": "0.3.1-next.70",
230
- "@delali/narsil-native-win32-arm64": "0.3.1-next.70",
231
- "@delali/narsil-native-win32-x64": "0.3.1-next.70"
226
+ "@delali/narsil-native-darwin-arm64": "0.3.1-next.71",
227
+ "@delali/narsil-native-darwin-x64": "0.3.1-next.71",
228
+ "@delali/narsil-native-linux-arm64": "0.3.1-next.71",
229
+ "@delali/narsil-native-linux-x64": "0.3.1-next.71",
230
+ "@delali/narsil-native-win32-arm64": "0.3.1-next.71",
231
+ "@delali/narsil-native-win32-x64": "0.3.1-next.71"
232
232
  }
233
233
  }