@delali/narsil 0.3.1-next.185 → 0.3.1-next.193

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.
Files changed (170) hide show
  1. package/README.md +1 -0
  2. package/dist/adapters/filesystem.mjs +2 -2
  3. package/dist/adapters/gcs.mjs +2 -2
  4. package/dist/adapters/indexeddb.mjs +1 -1
  5. package/dist/adapters/s3.mjs +2 -2
  6. package/dist/browser/chunk-4E5APHTM.mjs +1459 -0
  7. package/dist/browser/{chunk-4ZICWS4V.mjs → chunk-QAOVAYAG.mjs} +1 -1
  8. package/dist/browser/{chunk-CPSHS46N.mjs → chunk-UQG4HUGQ.mjs} +82 -50
  9. package/dist/browser/{chunk-2Q45HI5H.mjs → chunk-YINZFPLT.mjs} +7 -0
  10. package/dist/browser/{module-XVLHJ7T7.mjs → module-ZZTNG5JZ.mjs} +26 -3
  11. package/dist/browser/{optional-writes-ZTBHYQMN.mjs → optional-writes-J5BHKEQL.mjs} +21 -8
  12. package/dist/browser/{storage-leaf-4XMCITJ6.mjs → storage-leaf-N3JMQ6CF.mjs} +14569 -13747
  13. package/dist/{capabilities-DAHXphRn.d.ts → capabilities-CLnQHIqV.d.ts} +51 -9
  14. package/dist/{chunk-KLVMK3R5.mjs → chunk-2CKDCC65.mjs} +1 -1
  15. package/dist/{chunk-CODGHJVW.mjs → chunk-2HVQYOOD.mjs} +40 -12
  16. package/dist/{chunk-M5I64AQW.mjs → chunk-3N5GUXBI.mjs} +33 -33
  17. package/dist/{chunk-DU23J5JG.mjs → chunk-5CIHQIA4.mjs} +6 -6
  18. package/dist/{react-native/chunks/chunk-ZUFOYZ5P.mjs → chunk-62X472AC.mjs} +1 -1
  19. package/dist/{chunk-QJGDB3WR.mjs → chunk-6GHX35ZM.mjs} +2 -2
  20. package/dist/{chunk-G3XRHAJA.mjs → chunk-6MC6BCXK.mjs} +3 -3
  21. package/dist/{chunk-X5NHWOXT.mjs → chunk-7P5YWDRQ.mjs} +2 -2
  22. package/dist/{chunk-MHBG33R5.mjs → chunk-7X4IIREW.mjs} +76 -46
  23. package/dist/{chunk-F4OOBPKA.mjs → chunk-AOYQTX6W.mjs} +1 -1
  24. package/dist/{chunk-D6FYUTFN.mjs → chunk-ASZLNVWW.mjs} +1 -1
  25. package/dist/{chunk-LR6JJVML.mjs → chunk-D2EJUM4A.mjs} +764 -699
  26. package/dist/{chunk-FETZYCH7.mjs → chunk-F6F4G322.mjs} +26 -1
  27. package/dist/{chunk-2YWWHMVC.mjs → chunk-FGOGT273.mjs} +2 -2
  28. package/dist/{chunk-5BUEBIXR.mjs → chunk-GLXLSPLO.mjs} +18 -5
  29. package/dist/{chunk-IE3Q62QD.mjs → chunk-GR5GMFJJ.mjs} +1 -1
  30. package/dist/{chunk-Y7QUFIGV.mjs → chunk-GXED6R3Q.mjs} +2 -2
  31. package/dist/{chunk-BVZWWMOU.mjs → chunk-HHYQMGPW.mjs} +2 -2
  32. package/dist/{chunk-SL53DHVE.mjs → chunk-HSA3H3VW.mjs} +121 -68
  33. package/dist/{chunk-YM2HI5N5.mjs → chunk-IL5DRCNU.mjs} +2 -2
  34. package/dist/{chunk-JDG6CCXM.mjs → chunk-JENWA4WX.mjs} +2 -2
  35. package/dist/{chunk-2GONI5HL.mjs → chunk-JXINPXRS.mjs} +5 -4
  36. package/dist/chunk-K5GNK5GE.mjs +602 -0
  37. package/dist/{chunk-WLFOLAQI.mjs → chunk-KBU3ZFJN.mjs} +2 -2
  38. package/dist/{chunk-EDEE7ETQ.mjs → chunk-KOA6T2IC.mjs} +3 -3
  39. package/dist/{chunk-N3M4NPML.mjs → chunk-M2Z5WVWW.mjs} +1 -1
  40. package/dist/{chunk-EWGIF6FQ.mjs → chunk-NJJN4FMM.mjs} +1 -1
  41. package/dist/{chunk-C7YQHCSO.mjs → chunk-P4F4UWLC.mjs} +1 -1
  42. package/dist/{chunk-VYSWVQCE.mjs → chunk-PAPQGC6I.mjs} +2 -2
  43. package/dist/{chunk-I2WJCRIH.mjs → chunk-R2PJKSNL.mjs} +1 -1
  44. package/dist/{chunk-6SZQETSC.mjs → chunk-RORNUNXW.mjs} +5 -2
  45. package/dist/{chunk-FBQYC5OX.mjs → chunk-SB5HCIIO.mjs} +16 -13
  46. package/dist/{chunk-CYCVPTTR.mjs → chunk-SCZI7COG.mjs} +2 -2
  47. package/dist/{chunk-O337MDRJ.mjs → chunk-SHES4VP5.mjs} +38 -13
  48. package/dist/{chunk-H4QYQ5DE.mjs → chunk-SIIDIGKI.mjs} +2 -2
  49. package/dist/{chunk-A3OAFUZI.mjs → chunk-SM2SYVIX.mjs} +2 -2
  50. package/dist/{chunk-II6XF6M4.mjs → chunk-SMLUZGSI.mjs} +9 -8
  51. package/dist/{chunk-2KCCQK4R.mjs → chunk-TSE2VWPX.mjs} +2 -2
  52. package/dist/{chunk-WSIU6YXQ.mjs → chunk-YPEJ6ODL.mjs} +1732 -743
  53. package/dist/{chunk-7WXGUTWK.mjs → chunk-Z6SIJH5O.mjs} +17 -6
  54. package/dist/{chunk-Q3ZZH5Z7.mjs → chunk-ZKOQR7EA.mjs} +7 -0
  55. package/dist/{chunk-CKEOTSF5.mjs → chunk-ZS2YUB2L.mjs} +6 -3
  56. package/dist/{chunk-FCQMZDRI.mjs → chunk-ZVZYJIIP.mjs} +3 -3
  57. package/dist/{client-DpqtT2XG.d.ts → client-uB0kp2yT.d.ts} +88 -5
  58. package/dist/client.d.ts +7 -7
  59. package/dist/client.mjs +3 -1265
  60. package/dist/{config-D9WR3MhO.d.ts → config-BvHQ-C7U.d.ts} +3 -3
  61. package/dist/{config-C687-reW.d.ts → config-PqgNY1H7.d.ts} +1 -1
  62. package/dist/{core-leaf-NEUM7PU3.mjs → core-leaf-TAR3GJVE.mjs} +3 -3
  63. package/dist/{direct-executor-37IH3ISS.mjs → direct-executor-WSZALYCV.mjs} +8 -8
  64. package/dist/distribution/coordinator/etcd.d.ts +1 -1
  65. package/dist/distribution/coordinator/etcd.mjs +35 -15
  66. package/dist/distribution/coordinator/in-memory.d.ts +1 -1
  67. package/dist/distribution/coordinator/in-memory.mjs +16 -6
  68. package/dist/distribution/transport/grpc.mjs +2 -2
  69. package/dist/distribution/transport/tcp.mjs +2 -2
  70. package/dist/distribution.d.ts +70 -9
  71. package/dist/distribution.mjs +1695 -680
  72. package/dist/{durability-config-NWU2G2SJ.mjs → durability-config-VWS2K24E.mjs} +1 -1
  73. package/dist/{react-native/chunks/embed-4LBSQD7U.mjs → embed-4PHHKGBK.mjs} +1 -1
  74. package/dist/embeddings/openai.mjs +2 -2
  75. package/dist/{engine-De6JzTW8.d.ts → engine-qjAxJSKk.d.ts} +206 -7
  76. package/dist/{index-CBUl4z3E.d.ts → index-BaQIAnk0.d.ts} +137 -111
  77. package/dist/index.browser.mjs +3 -3
  78. package/dist/index.d.ts +4 -4
  79. package/dist/index.mjs +8 -8
  80. package/dist/index.react-native.mjs +9 -9
  81. package/dist/{long-query-thread-DIPJBMV7.mjs → long-query-thread-N2DNPEA3.mjs} +21 -21
  82. package/dist/{module-Z3CL4GJ4.mjs → module-UQFIJQMG.mjs} +33 -13
  83. package/dist/{msgpack-leaf-7KBYOVTF.mjs → msgpack-leaf-H5ZYW7S7.mjs} +4 -4
  84. package/dist/{optional-reads-ENKMVQ4Q.mjs → optional-reads-5HFMF2QZ.mjs} +2 -2
  85. package/dist/{optional-writes-YIVJMQ4D.mjs → optional-writes-CGDBJBHQ.mjs} +31 -18
  86. package/dist/{paged-partition-archive-IZ6U7DVN.mjs → paged-partition-archive-UK44CVXG.mjs} +20 -20
  87. package/dist/partial-words.browser.mjs +3 -3
  88. package/dist/partial-words.mjs +8 -8
  89. package/dist/pattern.browser.mjs +2 -2
  90. package/dist/pattern.mjs +3 -3
  91. package/dist/persistence/durability/checkpoint-worker.d.ts +7 -0
  92. package/dist/persistence/durability/checkpoint-worker.mjs +18 -18
  93. package/dist/{phrase-module-ZY3TLTQA.mjs → phrase-module-EFESWOCR.mjs} +2 -2
  94. package/dist/{query-actions-7EOKT3WD.mjs → query-actions-7BL3YZDW.mjs} +8 -8
  95. package/dist/query-suggestions/merge-worker.mjs +11 -11
  96. package/dist/query-suggestions.browser.mjs +3 -3
  97. package/dist/query-suggestions.d.ts +1 -1
  98. package/dist/query-suggestions.mjs +9 -9
  99. package/dist/react-native/chunks/{chunk-TQ26BKBH.mjs → chunk-43R4GCM7.mjs} +7 -0
  100. package/dist/react-native/chunks/{chunk-CBU4M3EU.mjs → chunk-63DZ26X5.mjs} +277 -75
  101. package/dist/react-native/chunks/{chunk-BN6FUB7N.mjs → chunk-AN4HKLB4.mjs} +1 -1
  102. package/dist/react-native/chunks/{chunk-T5HF3FW3.mjs → chunk-BNFGA7TY.mjs} +3 -3
  103. package/dist/react-native/chunks/{chunk-PVMEHBQO.mjs → chunk-CW2ZFXSE.mjs} +1 -1
  104. package/dist/react-native/chunks/{chunk-NLEFMPY3.mjs → chunk-G434H5WG.mjs} +15 -4
  105. package/dist/react-native/chunks/{chunk-SK3DPAI4.mjs → chunk-HTBY4GON.mjs} +2 -2
  106. package/dist/react-native/chunks/{chunk-ZQPSXN6C.mjs → chunk-IP3QLETQ.mjs} +5 -5
  107. package/dist/react-native/chunks/{chunk-7TPO4FLE.mjs → chunk-LOKGE4OQ.mjs} +3 -3
  108. package/dist/react-native/chunks/{chunk-ZDDJVR7X.mjs → chunk-MRH36RN3.mjs} +2 -2
  109. package/dist/react-native/chunks/{chunk-YOTP2FPE.mjs → chunk-UO44MA5M.mjs} +1 -1
  110. package/dist/{chunk-4JBTALUC.mjs → react-native/chunks/chunk-UYAZLGEM.mjs} +1 -1
  111. package/dist/react-native/chunks/{chunk-WFQ6YQZA.mjs → chunk-UYKIV2KT.mjs} +1 -1
  112. package/dist/react-native/chunks/{chunk-IEY4DARA.mjs → chunk-XHYOQ4K4.mjs} +2 -2
  113. package/dist/react-native/chunks/{chunk-OZ3XEM6D.mjs → chunk-ZUJCUPVS.mjs} +1 -1
  114. package/dist/react-native/chunks/{core-leaf-TPBRRWVN.mjs → core-leaf-5PVST5PR.mjs} +4 -4
  115. package/dist/react-native/chunks/{durability-config-RVTWSXPH.mjs → durability-config-FCSD4MXY.mjs} +1 -1
  116. package/dist/{embed-2QMYCD2Q.mjs → react-native/chunks/embed-HA2I7RCF.mjs} +1 -1
  117. package/dist/react-native/chunks/{gzip.react-native-DLO4WW27.mjs → gzip.react-native-CVM4NQG2.mjs} +2 -2
  118. package/dist/react-native/chunks/{module-COLNJNML.mjs → module-QRCYB7QV.mjs} +32 -9
  119. package/dist/react-native/chunks/msgpack-leaf-JMNGSTRW.mjs +7 -0
  120. package/dist/react-native/chunks/{optional-reads-74HYI4DO.mjs → optional-reads-AFPO2FEB.mjs} +3 -3
  121. package/dist/react-native/chunks/{optional-writes-QETIM6BI.mjs → optional-writes-GC6JWMAF.mjs} +31 -18
  122. package/dist/react-native/chunks/{phrase-module-UC4YGEBB.mjs → phrase-module-IGYBK7XH.mjs} +3 -3
  123. package/dist/react-native/chunks/{resolve-vector-text-FU7D4QP5.mjs → resolve-vector-text-GE2CRJKI.mjs} +1 -1
  124. package/dist/react-native/chunks/{restore-queue-3E2MJIJS.mjs → restore-queue-2ACONS4W.mjs} +12 -12
  125. package/dist/react-native/chunks/{segment-codec-leaf-IE4DXUZV.mjs → segment-codec-leaf-SSIWXVUG.mjs} +10 -10
  126. package/dist/react-native/chunks/{segment-merge-leaf-62LQ5WZB.mjs → segment-merge-leaf-I2WDFE6O.mjs} +11 -11
  127. package/dist/react-native/chunks/{storage-leaf-LNOLKWZB.mjs → storage-leaf-YXXMG4VR.mjs} +14727 -13915
  128. package/dist/react-native/chunks/{store-leaf-Y7CBOPFZ.mjs → store-leaf-FS7A4PZA.mjs} +11 -11
  129. package/dist/react-native/chunks/{suggestions-leaf-PSUGL6MI.mjs → suggestions-leaf-PSFCT5EX.mjs} +11 -11
  130. package/dist/react-native/chunks/{worker-copies-MW5O5U3D.mjs → worker-copies-QRMISMEL.mjs} +10 -10
  131. package/dist/react-native/partial-words.mjs +9 -9
  132. package/dist/react-native/pattern.mjs +5 -5
  133. package/dist/react-native/query-suggestions.mjs +9 -9
  134. package/dist/react-native/sync.mjs +433 -51
  135. package/dist/react-native/synonyms.mjs +9 -9
  136. package/dist/react.d.ts +8 -8
  137. package/dist/react.mjs +7 -0
  138. package/dist/{rerank-KTV5L7MZ.mjs → rerank-4GFC26FD.mjs} +8 -8
  139. package/dist/rerankers/http.mjs +2 -2
  140. package/dist/{resolve-vector-text-SD6BEMKZ.mjs → resolve-vector-text-OD4J3WHF.mjs} +2 -2
  141. package/dist/{restore-queue-ES7TDJ5V.mjs → restore-queue-E4EIUYVV.mjs} +11 -11
  142. package/dist/{segment-codec-leaf-DO75VKEV.mjs → segment-codec-leaf-MP6DILVE.mjs} +9 -9
  143. package/dist/{segment-merge-leaf-JGND6LG5.mjs → segment-merge-leaf-ED2NMUC5.mjs} +9 -9
  144. package/dist/server.d.ts +13 -9
  145. package/dist/server.mjs +875 -348
  146. package/dist/{storage-leaf-ZI3H2WJY.mjs → storage-leaf-HQFO37W7.mjs} +5234 -5835
  147. package/dist/{store-leaf-YIH36Y5J.mjs → store-leaf-PL2G7RM5.mjs} +10 -10
  148. package/dist/{suggestions-leaf-FP5HSTFP.mjs → suggestions-leaf-I3MEHACP.mjs} +12 -12
  149. package/dist/sync/filesystem.d.ts +2 -2
  150. package/dist/sync/filesystem.mjs +16 -16
  151. package/dist/sync/indexeddb.browser.mjs +1 -1
  152. package/dist/sync/indexeddb.d.ts +2 -2
  153. package/dist/sync/indexeddb.mjs +3 -3
  154. package/dist/sync.browser.mjs +35 -1108
  155. package/dist/sync.d.ts +3 -3
  156. package/dist/sync.mjs +430 -51
  157. package/dist/synonyms.browser.mjs +3 -3
  158. package/dist/synonyms.mjs +8 -8
  159. package/dist/{tasks-X2IJQc8J.d.ts → tasks-C65V7lIr.d.ts} +3 -3
  160. package/dist/thread-LTFI3RK5.mjs +31 -0
  161. package/dist/{types-D0YasjoX.d.ts → types-CpCg-Gq-.d.ts} +1 -1
  162. package/dist/vector/search-worker.mjs +5 -5
  163. package/dist/{worker-copies-WYPRCNB7.mjs → worker-copies-P7YWXEP5.mjs} +11 -11
  164. package/dist/workers/entry.mjs +14 -14
  165. package/openapi.json +144 -0
  166. package/package.json +5 -7
  167. package/dist/chunk-URVH6BLO.mjs +0 -217
  168. package/dist/react-native/chunks/msgpack-leaf-GTKLF6GJ.mjs +0 -7
  169. package/dist/thread-NQRNW3IH.mjs +0 -31
  170. /package/dist/{chunk-CV3Q2EKO.mjs → chunk-S5QMWECL.mjs} +0 -0
package/dist/client.mjs CHANGED
@@ -1,193 +1,5 @@
1
- // src/errors.ts
2
- var NARSIL_ERROR_MARKER = /* @__PURE__ */ Symbol.for("@delali/narsil.NarsilError");
3
- var ErrorCodes = {
4
- SCHEMA_INVALID_TYPE: "SCHEMA_INVALID_TYPE",
5
- SCHEMA_DEPTH_EXCEEDED: "SCHEMA_DEPTH_EXCEEDED",
6
- SCHEMA_INVALID_VECTOR_DIMENSION: "SCHEMA_INVALID_VECTOR_DIMENSION",
7
- SCHEMA_INVALID_GEOPOINT: "SCHEMA_INVALID_GEOPOINT",
8
- DOC_NOT_FOUND: "DOC_NOT_FOUND",
9
- DOC_ALREADY_EXISTS: "DOC_ALREADY_EXISTS",
10
- DOC_VALIDATION_FAILED: "DOC_VALIDATION_FAILED",
11
- INDEX_NOT_FOUND: "INDEX_NOT_FOUND",
12
- INDEX_ALREADY_EXISTS: "INDEX_ALREADY_EXISTS",
13
- INDEX_ORPHANED: "INDEX_ORPHANED",
14
- INDEX_REOPEN_CAPACITY_EXHAUSTED: "INDEX_REOPEN_CAPACITY_EXHAUSTED",
15
- INSTANCE_SHUT_DOWN: "INSTANCE_SHUT_DOWN",
16
- PARTITION_CORRUPTED: "PARTITION_CORRUPTED",
17
- PARTITION_REBALANCING_BACKPRESSURE: "PARTITION_REBALANCING_BACKPRESSURE",
18
- WORKER_CRASHED: "WORKER_CRASHED",
19
- WORKER_BUSY: "WORKER_BUSY",
20
- WORKER_TIMEOUT: "WORKER_TIMEOUT",
21
- WORKER_ACTION_FAILED: "WORKER_ACTION_FAILED",
22
- PERSISTENCE_SAVE_FAILED: "PERSISTENCE_SAVE_FAILED",
23
- PERSISTENCE_LOAD_FAILED: "PERSISTENCE_LOAD_FAILED",
24
- PERSISTENCE_DELETE_FAILED: "PERSISTENCE_DELETE_FAILED",
25
- PERSISTENCE_CRC_MISMATCH: "PERSISTENCE_CRC_MISMATCH",
26
- PERSISTENCE_WAL_CORRUPT: "PERSISTENCE_WAL_CORRUPT",
27
- PERSISTENCE_FSYNC_FAILED: "PERSISTENCE_FSYNC_FAILED",
28
- PERSISTENCE_DEPENDENCY_MISSING: "PERSISTENCE_DEPENDENCY_MISSING",
29
- BACKUP_NOT_FOUND: "BACKUP_NOT_FOUND",
30
- BACKUP_ALREADY_EXISTS: "BACKUP_ALREADY_EXISTS",
31
- BACKUP_DAMAGED: "BACKUP_DAMAGED",
32
- BACKUP_DURABILITY_REQUIRED: "BACKUP_DURABILITY_REQUIRED",
33
- BACKUP_IN_PROGRESS: "BACKUP_IN_PROGRESS",
34
- BACKUP_STORE_CLAIMED: "BACKUP_STORE_CLAIMED",
35
- BACKUP_STORE_NOT_CONFIGURED: "BACKUP_STORE_NOT_CONFIGURED",
36
- BACKUP_NOT_READY: "BACKUP_NOT_READY",
37
- SYNC_DURABILITY_REQUIRED: "SYNC_DURABILITY_REQUIRED",
38
- SYNC_BACKUP_STORE_REQUIRED: "SYNC_BACKUP_STORE_REQUIRED",
39
- SYNC_NOT_READY: "SYNC_NOT_READY",
40
- SYNC_NOT_ENABLED: "SYNC_NOT_ENABLED",
41
- SYNC_SNAPSHOT_PREPARING: "SYNC_SNAPSHOT_PREPARING",
42
- QUERY_SUGGESTIONS_NOT_ENABLED: "QUERY_SUGGESTIONS_NOT_ENABLED",
43
- SEARCH_INVALID_FIELD: "SEARCH_INVALID_FIELD",
44
- VECTOR_DIMENSION_MISMATCH: "VECTOR_DIMENSION_MISMATCH",
45
- SEARCH_INVALID_FILTER: "SEARCH_INVALID_FILTER",
46
- SEARCH_INVALID_MODE: "SEARCH_INVALID_MODE",
47
- SEARCH_INVALID_CURSOR: "SEARCH_INVALID_CURSOR",
48
- SEARCH_RESULT_WINDOW_EXCEEDED: "SEARCH_RESULT_WINDOW_EXCEEDED",
49
- SEARCH_WORK_CAP_EXCEEDED: "SEARCH_WORK_CAP_EXCEEDED",
50
- /**
51
- * An engine fault: a write changed the index during a search that held every
52
- * write, so the search could not answer from one state. A correct engine
53
- * never raises it, and retrying the request does not help.
54
- */
55
- SEARCH_STATE_MOVED: "SEARCH_STATE_MOVED",
56
- SEARCH_INVALID_PHRASE: "SEARCH_INVALID_PHRASE",
57
- SEARCH_PHRASE_NOT_READY: "SEARCH_PHRASE_NOT_READY",
58
- BM25_NOT_READY: "BM25_NOT_READY",
59
- LANGUAGE_NOT_SUPPORTED: "LANGUAGE_NOT_SUPPORTED",
60
- ENVELOPE_VERSION_MISMATCH: "ENVELOPE_VERSION_MISMATCH",
61
- ENVELOPE_INVALID_MAGIC: "ENVELOPE_INVALID_MAGIC",
62
- PARTITION_CAPACITY_EXCEEDED: "PARTITION_CAPACITY_EXCEEDED",
63
- RESTORE_MEMORY_EXCEEDED: "RESTORE_MEMORY_EXCEEDED",
64
- MEMORY_WRITE_BLOCKED: "MEMORY_WRITE_BLOCKED",
65
- ANALYSIS_CHANGE_REPLACED: "ANALYSIS_CHANGE_REPLACED",
66
- ANALYSIS_CHANGE_NOT_READY: "ANALYSIS_CHANGE_NOT_READY",
67
- ANALYSIS_GENERATION_MISSING: "ANALYSIS_GENERATION_MISSING",
68
- ANALYSIS_REBUILD_MEMORY_EXCEEDED: "ANALYSIS_REBUILD_MEMORY_EXCEEDED",
69
- EMBEDDING_FAILED: "EMBEDDING_FAILED",
70
- EMBEDDING_DIMENSION_MISMATCH: "EMBEDDING_DIMENSION_MISMATCH",
71
- EMBEDDING_NO_SOURCE: "EMBEDDING_NO_SOURCE",
72
- EMBEDDING_CONFIG_INVALID: "EMBEDDING_CONFIG_INVALID",
73
- RERANK_FAILED: "RERANK_FAILED",
74
- RERANK_CONFIG_INVALID: "RERANK_CONFIG_INVALID",
75
- DOC_MISSING_REQUIRED_FIELD: "DOC_MISSING_REQUIRED_FIELD",
76
- CONFIG_INVALID: "CONFIG_INVALID",
77
- QUERY_ROUTING_FAILED: "QUERY_ROUTING_FAILED",
78
- QUERY_PARTIAL_FAILURE: "QUERY_PARTIAL_FAILURE",
79
- QUERY_NODE_TIMEOUT: "QUERY_NODE_TIMEOUT",
80
- QUERY_NO_ACTIVE_REPLICA: "QUERY_NO_ACTIVE_REPLICA",
81
- SEARCH_CONTEXT_MISSING: "SEARCH_CONTEXT_MISSING",
82
- CLUSTER_OPERATION_UNSUPPORTED: "CLUSTER_OPERATION_UNSUPPORTED",
83
- CLUSTER_WRITE_BLOCKED: "CLUSTER_WRITE_BLOCKED",
84
- ALLOCATION_NO_DATA_NODES: "ALLOCATION_NO_DATA_NODES",
85
- ALLOCATION_INVALID_CONFIG: "ALLOCATION_INVALID_CONFIG",
86
- ALLOCATION_FAILED: "ALLOCATION_FAILED",
87
- CONTROLLER_METADATA_INVALID: "CONTROLLER_METADATA_INVALID",
88
- NODE_BOOTSTRAP_FAILED: "NODE_BOOTSTRAP_FAILED",
89
- NODE_ALREADY_JOINED: "NODE_ALREADY_JOINED",
90
- NODE_NOT_JOINED: "NODE_NOT_JOINED",
91
- NODE_NOT_READY: "NODE_NOT_READY",
92
- NODE_NOT_CONTROLLER: "NODE_NOT_CONTROLLER",
93
- NODE_VERSION_INCOMPATIBLE: "NODE_VERSION_INCOMPATIBLE",
94
- COORDINATOR_DEPENDENCY_MISSING: "COORDINATOR_DEPENDENCY_MISSING",
95
- COORDINATOR_AUTH_FAILED: "COORDINATOR_AUTH_FAILED",
96
- COORDINATOR_UNAVAILABLE: "COORDINATOR_UNAVAILABLE",
97
- TRANSPORT_DEPENDENCY_MISSING: "TRANSPORT_DEPENDENCY_MISSING",
98
- NATIVE_DEPENDENCY_MISSING: "NATIVE_DEPENDENCY_MISSING",
99
- REPLICATION_ENTRY_INVALID: "REPLICATION_ENTRY_INVALID",
100
- REPLICATION_INSYNC_REMOVAL_FAILED: "REPLICATION_INSYNC_REMOVAL_FAILED",
101
- REPLICATION_ROLLBACK_FAILED: "REPLICATION_ROLLBACK_FAILED",
102
- REPLICATION_OUTCOME_UNKNOWN: "REPLICATION_OUTCOME_UNKNOWN",
103
- REPLICATION_WRITE_CONFLICT: "REPLICATION_WRITE_CONFLICT",
104
- REPLICATION_LOG_FULL: "REPLICATION_LOG_FULL",
105
- REPLICATION_ENTRY_CORRUPT: "REPLICATION_ENTRY_CORRUPT",
106
- REPLICATION_SNAPSHOT_CORRUPT: "REPLICATION_SNAPSHOT_CORRUPT",
107
- REPLICATION_TERM_MISMATCH: "REPLICATION_TERM_MISMATCH",
108
- REPLICATION_SYNC_FAILED: "REPLICATION_SYNC_FAILED",
109
- PARTITION_NOT_PRIMARY: "PARTITION_NOT_PRIMARY",
110
- PARTITION_UNASSIGNED: "PARTITION_UNASSIGNED",
111
- INSUFFICIENT_REPLICAS: "INSUFFICIENT_REPLICAS",
112
- SNAPSHOT_SYNC_UNAUTHORIZED: "SNAPSHOT_SYNC_UNAUTHORIZED",
113
- SNAPSHOT_SYNC_REQUEST_INVALID: "SNAPSHOT_SYNC_REQUEST_INVALID",
114
- SNAPSHOT_SYNC_INDEX_NOT_FOUND: "SNAPSHOT_SYNC_INDEX_NOT_FOUND",
115
- SNAPSHOT_SYNC_CAPACITY_EXHAUSTED: "SNAPSHOT_SYNC_CAPACITY_EXHAUSTED",
116
- SNAPSHOT_SYNC_SNAPSHOT_FAILED: "SNAPSHOT_SYNC_SNAPSHOT_FAILED",
117
- SNAPSHOT_SYNC_DECODE_FAILED: "SNAPSHOT_SYNC_DECODE_FAILED",
118
- SNAPSHOT_SYNC_FRAME_INVALID: "SNAPSHOT_SYNC_FRAME_INVALID",
119
- SNAPSHOT_SYNC_HEADER_INVALID: "SNAPSHOT_SYNC_HEADER_INVALID",
120
- SNAPSHOT_SYNC_HEADER_MISMATCH: "SNAPSHOT_SYNC_HEADER_MISMATCH",
121
- SNAPSHOT_SYNC_CHUNK_OUT_OF_ORDER: "SNAPSHOT_SYNC_CHUNK_OUT_OF_ORDER",
122
- SNAPSHOT_SYNC_CHUNK_OVERFLOW: "SNAPSHOT_SYNC_CHUNK_OVERFLOW",
123
- SNAPSHOT_SYNC_CHUNK_SIZE_EXCEEDED: "SNAPSHOT_SYNC_CHUNK_SIZE_EXCEEDED",
124
- SNAPSHOT_SYNC_CHUNK_MISSING: "SNAPSHOT_SYNC_CHUNK_MISSING",
125
- SNAPSHOT_SYNC_END_MISSING: "SNAPSHOT_SYNC_END_MISSING",
126
- SNAPSHOT_SYNC_CHECKSUM_MISMATCH: "SNAPSHOT_SYNC_CHECKSUM_MISMATCH",
127
- SNAPSHOT_SYNC_PRIMARY_ERROR: "SNAPSHOT_SYNC_PRIMARY_ERROR",
128
- SNAPSHOT_SYNC_NO_TARGETS: "SNAPSHOT_SYNC_NO_TARGETS",
129
- SNAPSHOT_SYNC_TRANSPORT_FAILED: "SNAPSHOT_SYNC_TRANSPORT_FAILED",
130
- SNAPSHOT_SYNC_SCHEMA_UNAVAILABLE: "SNAPSHOT_SYNC_SCHEMA_UNAVAILABLE",
131
- SNAPSHOT_SYNC_RESTORE_FAILED: "SNAPSHOT_SYNC_RESTORE_FAILED",
132
- SNAPSHOT_SYNC_RESTORE_CLEANUP_FAILED: "SNAPSHOT_SYNC_RESTORE_CLEANUP_FAILED",
133
- SNAPSHOT_SYNC_TIMEOUT: "SNAPSHOT_SYNC_TIMEOUT",
134
- SNAPSHOT_SYNC_ALLOCATION_UNAVAILABLE: "SNAPSHOT_SYNC_ALLOCATION_UNAVAILABLE",
135
- SNAPSHOT_SYNC_NOT_ASSIGNED: "SNAPSHOT_SYNC_NOT_ASSIGNED",
136
- SNAPSHOT_SYNC_ABORTED: "SNAPSHOT_SYNC_ABORTED"
137
- };
138
- var ServerErrorCodes = {
139
- INVALID_REQUEST: "INVALID_REQUEST",
140
- INVALID_JSON: "INVALID_JSON",
141
- EMPTY_BODY: "EMPTY_BODY",
142
- PAYLOAD_TOO_LARGE: "PAYLOAD_TOO_LARGE",
143
- NOT_FOUND: "NOT_FOUND",
144
- TASK_NOT_FOUND: "TASK_NOT_FOUND",
145
- TASK_NOT_CANCELLABLE: "TASK_NOT_CANCELLABLE",
146
- TASK_OWNED_BY_ANOTHER_INSTANCE: "TASK_OWNED_BY_ANOTHER_INSTANCE",
147
- TASK_INTERRUPTED: "TASK_INTERRUPTED",
148
- TOO_MANY_REQUESTS: "TOO_MANY_REQUESTS",
149
- HOOK_ERROR: "HOOK_ERROR",
150
- INTERNAL_ERROR: "INTERNAL_ERROR"
151
- };
152
- var ClientErrorCodes = {
153
- CLIENT_CONNECTION_FAILED: "CLIENT_CONNECTION_FAILED",
154
- CLIENT_REQUEST_TIMEOUT: "CLIENT_REQUEST_TIMEOUT",
155
- CLIENT_REQUEST_ABORTED: "CLIENT_REQUEST_ABORTED",
156
- CLIENT_INVALID_RESPONSE: "CLIENT_INVALID_RESPONSE",
157
- CLIENT_TASK_TIMEOUT: "CLIENT_TASK_TIMEOUT",
158
- CLIENT_UNEXPECTED_ERROR: "CLIENT_UNEXPECTED_ERROR",
159
- SYNC_ANALYSIS_UNAVAILABLE: "SYNC_ANALYSIS_UNAVAILABLE"
160
- };
161
- var NarsilError = class extends Error {
162
- /** This says which failure it is. */
163
- code;
164
- /** This carries the values behind the failure, such as the field, index, or limit involved. It is empty when the code says everything. */
165
- details;
166
- /**
167
- * Builds an error carrying a code the caller can branch on.
168
- *
169
- * @param code - The failure this error reports, from {@link ErrorCodes} for
170
- * an engine failure, {@link ServerErrorCodes} for one the HTTP layer raised,
171
- * or {@link ClientErrorCodes} for one that stopped a request from reaching a
172
- * server.
173
- * @param message - Plain description, for a log or a person.
174
- * @param details - Values behind the failure, which reach
175
- * {@link NarsilError.details}.
176
- */
177
- constructor(code, message, details) {
178
- super(message);
179
- this.name = "NarsilError";
180
- this.code = code;
181
- this.details = details ?? {};
182
- Object.defineProperty(this, NARSIL_ERROR_MARKER, { value: true });
183
- }
184
- };
185
- function isNarsilError(value) {
186
- return typeof value === "object" && value !== null && NARSIL_ERROR_MARKER in value;
187
- }
188
- function describeError(error) {
189
- return error instanceof Error ? error.message : String(error);
190
- }
1
+ export { createNarsilClient } from './browser/chunk-4E5APHTM.mjs';
2
+ export { ClientErrorCodes, ErrorCodes, NarsilError, ServerErrorCodes, isNarsilError } from './browser/chunk-YINZFPLT.mjs';
191
3
 
192
4
  // src/server/capabilities.ts
193
5
  var ASYNC_IMPORT_CAPABILITY = "documents.import.async";
@@ -211,1078 +23,4 @@ var SERVER_CAPABILITIES = [
211
23
  BM25_TUNING_CAPABILITY
212
24
  ];
213
25
 
214
- // src/json-encoding.ts
215
- function toPlainNumbers(key, value) {
216
- if (ArrayBuffer.isView(value) && !(value instanceof DataView)) {
217
- return Array.from(value);
218
- }
219
- return value;
220
- }
221
- function encodeJson(value) {
222
- return JSON.stringify(value, toPlainNumbers);
223
- }
224
-
225
- // src/client/constants.ts
226
- var DEFAULT_REQUEST_TIMEOUT_MS = 3e4;
227
- var NO_TIMEOUT = 0;
228
- var DEFAULT_TASK_POLL_INTERVAL_MS = 250;
229
- var DEFAULT_URL_SKIP_MS = 1e3;
230
- var DEFAULT_MAX_URL_SKIP_MS = 3e4;
231
-
232
- // src/client/paths.ts
233
- function indexPath(indexName) {
234
- return `/indexes/${encodeURIComponent(indexName)}`;
235
- }
236
- function documentPath(indexName, docId) {
237
- return `${indexPath(indexName)}/documents/${encodeURIComponent(docId)}`;
238
- }
239
- function backupPath(backupName) {
240
- return `/backups/${encodeURIComponent(backupName)}`;
241
- }
242
- function taskPath(taskId) {
243
- return `/tasks/${encodeURIComponent(taskId)}`;
244
- }
245
-
246
- // src/client/response-shape.ts
247
- function isRecord(value) {
248
- return typeof value === "object" && value !== null && !Array.isArray(value);
249
- }
250
- function malformed(path, expected) {
251
- return new NarsilError(ClientErrorCodes.CLIENT_INVALID_RESPONSE, `The answer from ${path} holds no ${expected}`, {
252
- route: path
253
- });
254
- }
255
- function readArray(payload, key, path) {
256
- if (!isRecord(payload) || !Array.isArray(payload[key])) throw malformed(path, `"${key}" array`);
257
- return payload[key];
258
- }
259
- function readNumber(payload, key, path) {
260
- if (!isRecord(payload) || typeof payload[key] !== "number") throw malformed(path, `"${key}" number`);
261
- return payload[key];
262
- }
263
- function readBoolean(payload, key, path) {
264
- if (!isRecord(payload) || typeof payload[key] !== "boolean") throw malformed(path, `"${key}" flag`);
265
- return payload[key];
266
- }
267
- function readString(payload, key, path) {
268
- if (!isRecord(payload) || typeof payload[key] !== "string") throw malformed(path, `"${key}" string`);
269
- return payload[key];
270
- }
271
- function readObject(payload, key, path) {
272
- if (!isRecord(payload) || !isRecord(payload[key])) throw malformed(path, `"${key}" object`);
273
- return payload[key];
274
- }
275
- function readBody(payload, path) {
276
- if (!isRecord(payload)) throw malformed(path, "JSON object");
277
- return payload;
278
- }
279
-
280
- // src/client/admin.ts
281
- function createAdminOperations(transport) {
282
- async function postJson(path, body, options) {
283
- const payload = await transport.json({
284
- method: "POST",
285
- path,
286
- body: encodeJson(body),
287
- contentType: "application/json",
288
- options
289
- });
290
- return readBody(payload, path);
291
- }
292
- return {
293
- async checkpoint(indexName, options) {
294
- await transport.json({ method: "POST", path: `${indexPath(indexName)}/_checkpoint`, options });
295
- },
296
- snapshot(indexName, options) {
297
- const { queryHistory, ...request } = options ?? {};
298
- return transport.stream({
299
- method: "GET",
300
- path: `${indexPath(indexName)}/snapshot`,
301
- ...queryHistory === true ? { query: { queryHistory: "true" } } : {},
302
- defaultTimeoutMs: NO_TIMEOUT,
303
- options: request
304
- });
305
- },
306
- async restore(indexName, data, options) {
307
- const path = `${indexPath(indexName)}/restore`;
308
- const payload = await transport.json({
309
- method: "POST",
310
- path,
311
- body: data,
312
- contentType: "application/octet-stream",
313
- defaultTimeoutMs: NO_TIMEOUT,
314
- options
315
- });
316
- return readBody(payload, path);
317
- },
318
- exportDocuments(indexName, options) {
319
- return transport.stream({
320
- method: "GET",
321
- path: `${indexPath(indexName)}/export`,
322
- defaultTimeoutMs: NO_TIMEOUT,
323
- options
324
- });
325
- },
326
- async importDocumentExport(indexName, data, options) {
327
- const path = `${indexPath(indexName)}/import`;
328
- const payload = await transport.json({
329
- method: "POST",
330
- path,
331
- body: data,
332
- contentType: "application/x-ndjson",
333
- defaultTimeoutMs: NO_TIMEOUT,
334
- options
335
- });
336
- return readBody(payload, path);
337
- },
338
- async vectorMaintenanceStatus(indexName, options) {
339
- const path = `${indexPath(indexName)}/vector-maintenance`;
340
- const payload = await transport.json({ method: "GET", path, options });
341
- return readArray(payload, "fields", path);
342
- },
343
- async compactVectors(indexName, fieldName, options) {
344
- await postJson(
345
- `${indexPath(indexName)}/vectors/_compact`,
346
- fieldName === void 0 ? {} : { field: fieldName },
347
- options
348
- );
349
- },
350
- optimizeVectors(indexName, fieldName, options) {
351
- return postJson(
352
- `${indexPath(indexName)}/vectors/_optimize`,
353
- fieldName === void 0 ? {} : { field: fieldName },
354
- options
355
- );
356
- },
357
- rebalance(indexName, targetPartitionCount, options) {
358
- return postJson(`${indexPath(indexName)}/_rebalance`, { targetPartitionCount }, options);
359
- },
360
- async updatePartitionConfig(indexName, partitionConfig, options) {
361
- await postJson(`${indexPath(indexName)}/partition-config`, partitionConfig, options);
362
- },
363
- async updateSynonyms(indexName, synonyms, options) {
364
- await postJson(`${indexPath(indexName)}/synonyms`, { synonyms }, options);
365
- },
366
- async updateBM25(indexName, bm25, options) {
367
- await postJson(`${indexPath(indexName)}/bm25`, bm25, options);
368
- },
369
- async getSynonyms(indexName, options) {
370
- const path = `${indexPath(indexName)}/synonyms`;
371
- const body = await readBody(
372
- await transport.json({ method: "GET", path, options }),
373
- path
374
- );
375
- return body.synonyms;
376
- },
377
- async rebuildAnalysis(indexName, options) {
378
- const path = `${indexPath(indexName)}/_rebuild-analysis`;
379
- return readBody(await transport.json({ method: "POST", path, options }), path);
380
- },
381
- async changeAnalysis(indexName, change, options) {
382
- const path = `${indexPath(indexName)}/_change-analysis`;
383
- return postJson(path, change, options);
384
- },
385
- async getMemoryStats(options) {
386
- const path = "/stats/memory";
387
- return readBody(await transport.json({ method: "GET", path, options }), path);
388
- }
389
- };
390
- }
391
-
392
- // src/client/backups.ts
393
- function createBackupOperations(transport) {
394
- async function postTask(path, body, options) {
395
- const payload = await transport.json({
396
- method: "POST",
397
- path,
398
- body: encodeJson(body),
399
- contentType: "application/json",
400
- options
401
- });
402
- return readBody(payload, path);
403
- }
404
- return {
405
- createBackup(indexName, backupName, options) {
406
- const { queryHistory, ...request } = options ?? {};
407
- const body = { backup: backupName, ...queryHistory === true ? { queryHistory } : {} };
408
- return postTask(`${indexPath(indexName)}/backups`, body, request);
409
- },
410
- async listBackups(options) {
411
- const path = "/backups";
412
- const payload = await transport.json({ method: "GET", path, defaultTimeoutMs: NO_TIMEOUT, options });
413
- return readArray(payload, "backups", path);
414
- },
415
- restoreBackup(backupName, restore, options) {
416
- return postTask(`${backupPath(backupName)}/_restore`, restore, options);
417
- },
418
- async deleteBackup(backupName, options) {
419
- const path = backupPath(backupName);
420
- return readBody(await transport.json({ method: "DELETE", path, options }), path);
421
- }
422
- };
423
- }
424
-
425
- // src/client/bulk.ts
426
- function toNdjson(source) {
427
- if (typeof source === "string") return source;
428
- if (Array.isArray(source)) return source.map((document) => encodeJson(document)).join("\n");
429
- return source;
430
- }
431
- function toBatchResult(payload, path) {
432
- const failed = readArray(payload, "failed", path);
433
- return {
434
- succeeded: readArray(payload, "succeeded", path),
435
- failed: failed.map((entry) => {
436
- const record2 = readBody(entry, path);
437
- const docId = typeof record2.docId === "string" ? record2.docId : "";
438
- const error = readBody(record2.error, path);
439
- const code = typeof error.code === "string" ? error.code : ServerErrorCodes.INTERNAL_ERROR;
440
- const message = typeof error.message === "string" ? error.message : "The server refused the document";
441
- const details = typeof error.details === "object" && error.details !== null ? error.details : void 0;
442
- return { docId, error: new NarsilError(code, message, details) };
443
- })
444
- };
445
- }
446
- function createBulkOperations(transport) {
447
- function batch(indexName, body, options) {
448
- const path = `${indexPath(indexName)}/documents/_batch`;
449
- return transport.json({ method: "POST", path, body: encodeJson(body), contentType: "application/json", options }).then((payload) => toBatchResult(payload, path));
450
- }
451
- function importBody(indexName, source, asynchronous, options) {
452
- return {
453
- method: "POST",
454
- path: `${indexPath(indexName)}/documents/_import`,
455
- ...asynchronous ? { query: { async: "true" } } : {},
456
- body: toNdjson(source),
457
- contentType: "application/x-ndjson",
458
- defaultTimeoutMs: NO_TIMEOUT,
459
- options
460
- };
461
- }
462
- return {
463
- insertBatch(indexName, documents, insertOptions, options) {
464
- return batch(
465
- indexName,
466
- { action: "insert", documents, ...insertOptions === void 0 ? {} : { options: insertOptions } },
467
- options
468
- );
469
- },
470
- updateBatch(indexName, updates, writeOptions, options) {
471
- return batch(
472
- indexName,
473
- { action: "update", updates, ...writeOptions === void 0 ? {} : { options: writeOptions } },
474
- options
475
- );
476
- },
477
- removeBatch(indexName, docIds, writeOptions, options) {
478
- return batch(
479
- indexName,
480
- { action: "delete", docIds, ...writeOptions === void 0 ? {} : { options: writeOptions } },
481
- options
482
- );
483
- },
484
- async getMultiple(indexName, docIds, options) {
485
- const path = `${indexPath(indexName)}/documents/_multi-get`;
486
- const payload = await transport.json({
487
- method: "POST",
488
- path,
489
- body: encodeJson({ docIds }),
490
- contentType: "application/json",
491
- repeatable: true,
492
- options
493
- });
494
- const documents = readObject(payload, "documents", path);
495
- return new Map(Object.entries(documents));
496
- },
497
- async listDocuments(indexName, params, options) {
498
- const path = `${indexPath(indexName)}/documents/_list`;
499
- const payload = await transport.json({
500
- method: "POST",
501
- path,
502
- body: encodeJson(params ?? {}),
503
- contentType: "application/json",
504
- repeatable: true,
505
- options
506
- });
507
- return readBody(payload, path);
508
- },
509
- async importDocuments(indexName, source, options) {
510
- const spec = importBody(indexName, source, false, options);
511
- return readBody(await transport.json(spec), spec.path);
512
- },
513
- async startImport(indexName, source, options) {
514
- const spec = importBody(indexName, source, true, options);
515
- return readBody(await transport.json(spec), spec.path);
516
- }
517
- };
518
- }
519
-
520
- // src/client/documents.ts
521
- function createDocumentOperations(transport) {
522
- return {
523
- async insert(indexName, document, docId, insertOptions, options) {
524
- const path = `${indexPath(indexName)}/documents`;
525
- const payload = await transport.json({
526
- method: "POST",
527
- path,
528
- body: encodeJson({
529
- document,
530
- ...docId === void 0 ? {} : { id: docId },
531
- ...insertOptions === void 0 ? {} : { options: insertOptions }
532
- }),
533
- contentType: "application/json",
534
- options
535
- });
536
- return readString(payload, "id", path);
537
- },
538
- async get(indexName, docId, options) {
539
- const path = documentPath(indexName, docId);
540
- const payload = await transport.jsonOrNull({ method: "GET", path, options }, ErrorCodes.DOC_NOT_FOUND);
541
- if (payload === null) return void 0;
542
- return readObject(payload, "document", path);
543
- },
544
- async has(indexName, docId, options) {
545
- const path = `${documentPath(indexName, docId)}/_exists`;
546
- return readBoolean(await transport.json({ method: "GET", path, options }), "exists", path);
547
- },
548
- async put(indexName, docId, document, writeOptions, options) {
549
- const path = documentPath(indexName, docId);
550
- const payload = await transport.json({
551
- method: "PUT",
552
- path,
553
- body: encodeJson({ document, ...writeOptions === void 0 ? {} : { options: writeOptions } }),
554
- contentType: "application/json",
555
- options
556
- });
557
- return { id: readString(payload, "id", path), created: readBoolean(payload, "created", path) };
558
- },
559
- async update(indexName, docId, document, writeOptions, options) {
560
- await transport.json({
561
- method: "PATCH",
562
- path: documentPath(indexName, docId),
563
- body: encodeJson({ document, ...writeOptions === void 0 ? {} : { options: writeOptions } }),
564
- contentType: "application/json",
565
- options
566
- });
567
- },
568
- async remove(indexName, docId, writeOptions, options) {
569
- await transport.json({
570
- method: "DELETE",
571
- path: documentPath(indexName, docId),
572
- ...writeOptions?.wait === true ? { query: { wait: "true" } } : {},
573
- options
574
- });
575
- },
576
- async waitForWrites(indexName, options) {
577
- await transport.json({ method: "POST", path: `${indexPath(indexName)}/_wait-for-writes`, options });
578
- },
579
- async countDocuments(indexName, options) {
580
- const path = `${indexPath(indexName)}/count`;
581
- return readNumber(await transport.json({ method: "GET", path, options }), "count", path);
582
- }
583
- };
584
- }
585
-
586
- // src/client/failover.ts
587
- var UNSENT_CONNECTION_CODES = /* @__PURE__ */ new Set(["ECONNREFUSED", "ENOTFOUND", "EAI_AGAIN", "ConnectionRefused"]);
588
- var MAX_CAUSE_DEPTH = 4;
589
- var SKIP_DOUBLING_CEILING = 30;
590
- var RETRIED_STATUSES = /* @__PURE__ */ new Set([502, 503, 504]);
591
- function readSkip(value, fallback, field) {
592
- if (value === void 0) return fallback;
593
- if (!Number.isSafeInteger(value) || value < 0) {
594
- throw new NarsilError(ErrorCodes.CONFIG_INVALID, `"${field}" must be a whole number of milliseconds, 0 or more`, {
595
- [field]: value
596
- });
597
- }
598
- return value;
599
- }
600
- function createUrlPool(bases, options) {
601
- const skipMs = readSkip(options.urlSkipMs, DEFAULT_URL_SKIP_MS, "urlSkipMs");
602
- const maxSkipMs = readSkip(options.maxUrlSkipMs, Math.max(DEFAULT_MAX_URL_SKIP_MS, skipMs), "maxUrlSkipMs");
603
- if (maxSkipMs < skipMs) {
604
- throw new NarsilError(ErrorCodes.CONFIG_INVALID, '"maxUrlSkipMs" must be at least "urlSkipMs"', {
605
- urlSkipMs: skipMs,
606
- maxUrlSkipMs: maxSkipMs
607
- });
608
- }
609
- const entries = bases.map((base, position) => ({ base, position, refusals: 0, skipUntil: 0 }));
610
- let nextStart = 0;
611
- return {
612
- order(now) {
613
- const rotation = [...entries.slice(nextStart), ...entries.slice(0, nextStart)];
614
- const open = rotation.filter((entry) => entry.skipUntil <= now);
615
- const skipped = rotation.filter((entry) => entry.skipUntil > now).sort((a, b) => a.skipUntil - b.skipUntil);
616
- return [...open, ...skipped];
617
- },
618
- took(entry) {
619
- nextStart = (entry.position + 1) % entries.length;
620
- },
621
- answered(entry) {
622
- entry.refusals = 0;
623
- entry.skipUntil = 0;
624
- },
625
- refused(entry, now) {
626
- entry.refusals += 1;
627
- const doublings = Math.min(entry.refusals - 1, SKIP_DOUBLING_CEILING);
628
- entry.skipUntil = now + Math.min(skipMs * 2 ** doublings, maxSkipMs);
629
- }
630
- };
631
- }
632
- function failedBeforeSending(error, depth = 0) {
633
- if (depth > MAX_CAUSE_DEPTH || typeof error !== "object" || error === null) return false;
634
- const { code, cause, errors } = error;
635
- if (typeof code === "string" && UNSENT_CONNECTION_CODES.has(code)) return true;
636
- if (failedBeforeSending(cause, depth + 1)) return true;
637
- return Array.isArray(errors) && errors.length > 0 && errors.every((entry) => failedBeforeSending(entry, depth + 1));
638
- }
639
- function answersUnavailable(status) {
640
- return RETRIED_STATUSES.has(status);
641
- }
642
- function movesOnAfterAnswer(status, code, repeatable) {
643
- if (!answersUnavailable(status)) return false;
644
- return repeatable || code === ErrorCodes.NODE_NOT_READY;
645
- }
646
- function earnsExtraTry(failure) {
647
- return failure.code === ClientErrorCodes.CLIENT_CONNECTION_FAILED;
648
- }
649
- function movesOnAfterFailure(failure, sentNothing, repeatable) {
650
- if (failure.code === ClientErrorCodes.CLIENT_REQUEST_TIMEOUT) return repeatable;
651
- if (failure.code === ClientErrorCodes.CLIENT_CONNECTION_FAILED) return repeatable || sentNothing;
652
- return false;
653
- }
654
-
655
- // src/client/http.ts
656
- function isRecord2(value) {
657
- return typeof value === "object" && value !== null && !Array.isArray(value);
658
- }
659
- function unrefTimer(timer) {
660
- const unrefable = timer;
661
- unrefable.unref?.();
662
- }
663
- function startDeadline(timeoutMs, caller) {
664
- const controller = new AbortController();
665
- let expired = false;
666
- const abortWithCaller = () => controller.abort();
667
- if (caller?.aborted) controller.abort();
668
- else caller?.addEventListener("abort", abortWithCaller);
669
- let timer;
670
- if (timeoutMs > 0 && !controller.signal.aborted) {
671
- timer = setTimeout(() => {
672
- expired = true;
673
- controller.abort();
674
- }, timeoutMs);
675
- unrefTimer(timer);
676
- }
677
- return {
678
- signal: controller.signal,
679
- expired: () => expired,
680
- release: () => {
681
- if (timer !== void 0) clearTimeout(timer);
682
- caller?.removeEventListener("abort", abortWithCaller);
683
- }
684
- };
685
- }
686
- var ResponseTooLargeError = class extends Error {
687
- constructor(limitBytes) {
688
- super(`The answer passed the ${limitBytes} byte ceiling this client reads`);
689
- this.limitBytes = limitBytes;
690
- }
691
- };
692
- async function readStreamCapped(stream, limitBytes) {
693
- const reader = stream.getReader();
694
- const chunks = [];
695
- let total = 0;
696
- try {
697
- for (; ; ) {
698
- const { done, value } = await reader.read();
699
- if (done) break;
700
- total += value.byteLength;
701
- if (total > limitBytes) throw new ResponseTooLargeError(limitBytes);
702
- chunks.push(value);
703
- }
704
- } finally {
705
- reader.releaseLock();
706
- if (total > limitBytes) await stream.cancel().catch(() => void 0);
707
- }
708
- const body = new Uint8Array(total);
709
- let offset = 0;
710
- for (const chunk of chunks) {
711
- body.set(chunk, offset);
712
- offset += chunk.byteLength;
713
- }
714
- return body;
715
- }
716
- async function readAnswer(response, limitBytes) {
717
- const stream = response.body;
718
- if (limitBytes > 0 && stream !== null && stream !== void 0) {
719
- return new TextDecoder().decode(await readStreamCapped(stream, limitBytes));
720
- }
721
- const text = await response.text();
722
- if (limitBytes > 0 && text.length > limitBytes) throw new ResponseTooLargeError(limitBytes);
723
- return text;
724
- }
725
- function invalidResponse(message, details) {
726
- return new NarsilError(ClientErrorCodes.CLIENT_INVALID_RESPONSE, message, details);
727
- }
728
- function errorFromBody(status, payload, url) {
729
- const envelope = isRecord2(payload) && isRecord2(payload.error) ? payload.error : void 0;
730
- if (envelope === void 0 || typeof envelope.code !== "string" || typeof envelope.message !== "string") {
731
- return invalidResponse(`The server answered HTTP ${status} without a Narsil error envelope`, { url, status });
732
- }
733
- const details = isRecord2(envelope.details) ? envelope.details : {};
734
- return new NarsilError(envelope.code, envelope.message, { ...details, status });
735
- }
736
- function isHttpUrl(value) {
737
- try {
738
- const parsed = new URL(value);
739
- return parsed.protocol === "http:" || parsed.protocol === "https:";
740
- } catch {
741
- return false;
742
- }
743
- }
744
- function normaliseBase(url) {
745
- const trimmed = url.trim();
746
- if (trimmed.length === 0) {
747
- throw new NarsilError(ErrorCodes.CONFIG_INVALID, 'The client needs a server address, and "url" is empty');
748
- }
749
- if (!trimmed.startsWith("/") && !isHttpUrl(trimmed)) {
750
- throw new NarsilError(
751
- ErrorCodes.CONFIG_INVALID,
752
- `The client cannot read "${trimmed}" as a server address; pass an http or https URL, or a path starting with "/" that a browser resolves against the page`,
753
- { url: trimmed }
754
- );
755
- }
756
- return trimmed.replace(/\/+$/, "");
757
- }
758
- function normaliseBases(url) {
759
- if (typeof url === "string") return [normaliseBase(url)];
760
- if (!Array.isArray(url) || url.length === 0) {
761
- throw new NarsilError(ErrorCodes.CONFIG_INVALID, 'The client needs a server address, and "url" lists none');
762
- }
763
- return url.map((entry) => {
764
- if (typeof entry !== "string") {
765
- throw new NarsilError(ErrorCodes.CONFIG_INVALID, 'Every server address in "url" must be a string');
766
- }
767
- return normaliseBase(entry);
768
- });
769
- }
770
- function translateFailure(err, url, timeoutMs, expired, caller) {
771
- if (err instanceof ResponseTooLargeError) {
772
- return invalidResponse(`The server at ${url} answered more than this client reads: ${err.message}`, {
773
- url,
774
- maxResponseBytes: err.limitBytes
775
- });
776
- }
777
- if (expired) {
778
- return new NarsilError(
779
- ClientErrorCodes.CLIENT_REQUEST_TIMEOUT,
780
- `The server at ${url} did not answer within ${timeoutMs} ms`,
781
- { url, timeoutMs }
782
- );
783
- }
784
- if (caller?.aborted === true) {
785
- return new NarsilError(ClientErrorCodes.CLIENT_REQUEST_ABORTED, `The caller cancelled the request to ${url}`, {
786
- url
787
- });
788
- }
789
- return new NarsilError(
790
- ClientErrorCodes.CLIENT_CONNECTION_FAILED,
791
- `The client could not reach ${url}: ${describeError(err)}`,
792
- { url }
793
- );
794
- }
795
- function envelopeCodeOf(text) {
796
- try {
797
- const payload = JSON.parse(text);
798
- return isRecord2(payload) && isRecord2(payload.error) && typeof payload.error.code === "string" ? payload.error.code : void 0;
799
- } catch {
800
- return void 0;
801
- }
802
- }
803
- function withQuery(path, query) {
804
- if (query === void 0) return path;
805
- const params = new URLSearchParams();
806
- for (const [key, value] of Object.entries(query)) {
807
- if (value !== void 0) params.set(key, value);
808
- }
809
- const encoded = params.toString();
810
- return encoded.length === 0 ? path : `${path}?${encoded}`;
811
- }
812
- function createTransport(options) {
813
- const pool = createUrlPool(normaliseBases(options.url), options);
814
- const send = options.fetch ?? ((input, init) => fetch(input, init));
815
- const baseHeaders = { ...options.headers };
816
- if (options.apiKey !== void 0 && options.apiKey.length > 0) {
817
- baseHeaders.authorization = `Bearer ${options.apiKey}`;
818
- }
819
- function resolveTimeout(spec) {
820
- const perCall = spec.options?.timeoutMs;
821
- if (perCall !== void 0) return perCall;
822
- if (options.timeoutMs !== void 0) return options.timeoutMs;
823
- return spec.defaultTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
824
- }
825
- function resolveResponseCeiling(spec) {
826
- const perCall = spec.options?.maxResponseBytes;
827
- if (perCall !== void 0) return perCall;
828
- return options.maxResponseBytes ?? 0;
829
- }
830
- function recordAttempt(entry, attempt, repeatable) {
831
- if (attempt.kind === "answer") {
832
- if (!answersUnavailable(attempt.status)) {
833
- pool.answered(entry);
834
- return false;
835
- }
836
- return movesOnAfterAnswer(attempt.status, envelopeCodeOf(attempt.text), repeatable);
837
- }
838
- if (attempt.error.code === ClientErrorCodes.CLIENT_CONNECTION_FAILED) pool.refused(entry, Date.now());
839
- return movesOnAfterFailure(attempt.error, attempt.sentNothing, repeatable);
840
- }
841
- function outcomeOf(attempt) {
842
- if (attempt === null) throw new NarsilError(ErrorCodes.CONFIG_INVALID, "The client holds no server address");
843
- if (attempt.kind === "failure") throw attempt.error;
844
- return attempt;
845
- }
846
- async function exchange(spec, keepsStream = false) {
847
- const repeatable = spec.repeatable === true || spec.method === "GET";
848
- const replayable = !(spec.body instanceof ReadableStream);
849
- const tryOn = async (entry2) => {
850
- pool.took(entry2);
851
- return exchangeOnce(entry2.base, spec, keepsStream);
852
- };
853
- let triesOnceMore = repeatable && replayable;
854
- let last = null;
855
- for (const entry2 of pool.order(Date.now())) {
856
- last = await tryOn(entry2);
857
- const moves = recordAttempt(entry2, last, repeatable);
858
- if (!replayable || !moves) return outcomeOf(last);
859
- if (last.kind === "failure" && !earnsExtraTry(last.error)) triesOnceMore = false;
860
- }
861
- const [entry] = pool.order(Date.now());
862
- if (triesOnceMore && entry !== void 0) {
863
- last = await tryOn(entry);
864
- recordAttempt(entry, last, repeatable);
865
- }
866
- return outcomeOf(last);
867
- }
868
- async function exchangeOnce(base, spec, keepsStream) {
869
- const url = `${base}${withQuery(spec.path, spec.query)}`;
870
- const headers = { ...baseHeaders, ...spec.headers, ...spec.options?.headers };
871
- if (spec.contentType !== void 0) headers["content-type"] = spec.contentType;
872
- const timeoutMs = resolveTimeout(spec);
873
- const deadline = startDeadline(timeoutMs, spec.options?.signal);
874
- let handedOver = false;
875
- try {
876
- const init = { method: spec.method, headers, signal: deadline.signal };
877
- if (spec.body !== void 0) init.body = spec.body;
878
- if (spec.body instanceof ReadableStream) init.duplex = "half";
879
- const response = await send(url, init);
880
- if (keepsStream && response.ok && response.body !== null) {
881
- handedOver = true;
882
- const stream = response.body.pipeThrough(
883
- new TransformStream({ flush: () => deadline.release() })
884
- );
885
- return { kind: "answer", status: response.status, url, text: "", stream, headers: response.headers };
886
- }
887
- const text = await readAnswer(response, resolveResponseCeiling(spec));
888
- return { kind: "answer", status: response.status, url, stream: null, text, headers: response.headers };
889
- } catch (err) {
890
- const error = translateFailure(err, url, timeoutMs, deadline.expired(), spec.options?.signal);
891
- const sentNothing = error.code === ClientErrorCodes.CLIENT_CONNECTION_FAILED && failedBeforeSending(err);
892
- return { kind: "failure", error, sentNothing };
893
- } finally {
894
- if (!handedOver) deadline.release();
895
- }
896
- }
897
- function parse(status, text, path) {
898
- if (text.length === 0) return void 0;
899
- try {
900
- return JSON.parse(text);
901
- } catch {
902
- throw invalidResponse(`The server answered HTTP ${status} with a body that is not JSON`, { url: path, status });
903
- }
904
- }
905
- async function json(spec) {
906
- const { status, text, url } = await exchange(spec);
907
- const payload = parse(status, text, url);
908
- if (status >= 200 && status < 300) return payload;
909
- throw errorFromBody(status, payload, url);
910
- }
911
- return {
912
- json,
913
- async jsonOrNull(spec, absentCode) {
914
- try {
915
- return await json(spec);
916
- } catch (err) {
917
- if (err instanceof NarsilError && err.code === absentCode) return null;
918
- throw err;
919
- }
920
- },
921
- async stream(spec) {
922
- const { status, text, stream, url } = await exchange(spec, true);
923
- if (stream !== null) return stream;
924
- throw errorFromBody(status, parse(status, text, url), url);
925
- },
926
- async download(spec) {
927
- const { status, text, stream, headers, url } = await exchange(spec, true);
928
- if (stream !== null && headers !== null) return { status, headers, stream };
929
- throw errorFromBody(status, parse(status, text, url), url);
930
- },
931
- async probe(spec) {
932
- const { status } = await exchange(spec);
933
- return status;
934
- }
935
- };
936
- }
937
-
938
- // src/client/indexes.ts
939
- function createIndexOperations(transport) {
940
- return {
941
- async createIndex(name, config, options) {
942
- await transport.json({
943
- method: "POST",
944
- path: "/indexes",
945
- body: encodeJson({ name, config }),
946
- contentType: "application/json",
947
- options
948
- });
949
- },
950
- async listIndexes(options) {
951
- const path = "/indexes";
952
- return readArray(await transport.json({ method: "GET", path, options }), "indexes", path);
953
- },
954
- async dropIndex(name, options) {
955
- await transport.json({ method: "DELETE", path: indexPath(name), options });
956
- },
957
- async getStats(indexName, options) {
958
- const path = `${indexPath(indexName)}/stats`;
959
- return readBody(await transport.json({ method: "GET", path, options }), path);
960
- },
961
- async getPartitionStats(indexName, options) {
962
- const path = `${indexPath(indexName)}/partitions`;
963
- const payload = await transport.json({ method: "GET", path, options });
964
- return readArray(payload, "partitions", path);
965
- },
966
- async clear(indexName, options) {
967
- await transport.json({ method: "POST", path: `${indexPath(indexName)}/_clear`, options });
968
- },
969
- async open(indexName, options) {
970
- await transport.json({ method: "POST", path: `${indexPath(indexName)}/_open`, options });
971
- },
972
- async close(indexName, options) {
973
- await transport.json({ method: "POST", path: `${indexPath(indexName)}/_close`, options });
974
- }
975
- };
976
- }
977
-
978
- // src/client/query-suggestions.ts
979
- function createQuerySuggestionOperations(transport) {
980
- const pathOf = (indexName, route = "") => `${indexPath(indexName)}/query-suggestions${route}`;
981
- function send(method, path, body, options) {
982
- return transport.json({
983
- method,
984
- path,
985
- ...body === void 0 ? {} : { body: encodeJson(body), contentType: "application/json" },
986
- options
987
- });
988
- }
989
- return {
990
- async updateQuerySuggestions(indexName, setting, options) {
991
- await send("PUT", pathOf(indexName), setting, options);
992
- },
993
- async querySuggestionsStatus(indexName, options) {
994
- const path = pathOf(indexName);
995
- return readBody(await send("GET", path, void 0, options), path);
996
- },
997
- async recordQuery(indexName, query, options) {
998
- const path = pathOf(indexName, "/record");
999
- return readBody(await send("POST", path, { query }, options), path);
1000
- },
1001
- async buildQuerySuggestions(indexName, options) {
1002
- const path = pathOf(indexName, "/build");
1003
- return readBody(await send("POST", path, void 0, options), path);
1004
- },
1005
- async previewQuerySuggestions(indexName, limit, options) {
1006
- const path = pathOf(indexName, "/preview");
1007
- const payload = await transport.json({
1008
- method: "GET",
1009
- path,
1010
- ...limit === void 0 ? {} : { query: { limit: String(limit) } },
1011
- options
1012
- });
1013
- return readBody(payload, path);
1014
- },
1015
- async readQueryBans(indexName, options) {
1016
- const path = pathOf(indexName, "/bans");
1017
- return readArray(await send("GET", path, void 0, options), "bans", path);
1018
- },
1019
- async replaceQueryBans(indexName, bans, options) {
1020
- const path = pathOf(indexName, "/bans");
1021
- return readArray(await send("PUT", path, { bans }, options), "bans", path);
1022
- },
1023
- async removeQuery(indexName, query, options) {
1024
- const path = pathOf(indexName, "/remove");
1025
- return readNumber(await send("POST", path, { query }, options), "suggestionIndexes", path);
1026
- },
1027
- async addManualSuggestion(indexName, suggestion, options) {
1028
- const path = pathOf(indexName, "/manual");
1029
- return readString(await send("POST", path, suggestion, options), "indexName", path);
1030
- }
1031
- };
1032
- }
1033
-
1034
- // src/score-encoding.ts
1035
- function decodeScore(score) {
1036
- if (typeof score === "number") return Number.isFinite(score) ? score : void 0;
1037
- if (score === "NaN") return Number.NaN;
1038
- if (score === "Infinity") return Number.POSITIVE_INFINITY;
1039
- if (score === "-Infinity") return Number.NEGATIVE_INFINITY;
1040
- return void 0;
1041
- }
1042
-
1043
- // src/client/query-response.ts
1044
- function record(value) {
1045
- return typeof value === "object" && value !== null && !Array.isArray(value);
1046
- }
1047
- function invalid(path) {
1048
- throw new NarsilError(ClientErrorCodes.CLIENT_INVALID_RESPONSE, "The search response holds an invalid hit score", {
1049
- route: path
1050
- });
1051
- }
1052
- function decodeHits(hits, path) {
1053
- if (!Array.isArray(hits)) invalid(path);
1054
- for (const hit of hits) {
1055
- if (!record(hit)) invalid(path);
1056
- if (!Object.hasOwn(hit, "score")) continue;
1057
- const score = decodeScore(hit.score);
1058
- if (score === void 0) invalid(path);
1059
- hit.score = score;
1060
- }
1061
- }
1062
- function decodeQueryResult(payload, path) {
1063
- if (!record(payload)) invalid(path);
1064
- decodeHits(payload.hits, path);
1065
- if (payload.groups !== void 0) {
1066
- if (!Array.isArray(payload.groups)) invalid(path);
1067
- for (const group of payload.groups) {
1068
- if (!record(group)) invalid(path);
1069
- decodeHits(group.hits, path);
1070
- }
1071
- }
1072
- return payload;
1073
- }
1074
-
1075
- // src/client/search.ts
1076
- function createSearchOperations(transport) {
1077
- async function post(path, params, options) {
1078
- const payload = await transport.json({
1079
- method: "POST",
1080
- path,
1081
- body: encodeJson(params),
1082
- contentType: "application/json",
1083
- repeatable: true,
1084
- options
1085
- });
1086
- return readBody(payload, path);
1087
- }
1088
- return {
1089
- async query(indexName, params, options) {
1090
- const path = `${indexPath(indexName)}/search`;
1091
- return decodeQueryResult(await post(path, params, options), path);
1092
- },
1093
- preflight(indexName, params, options) {
1094
- return post(`${indexPath(indexName)}/search/preflight`, params, options);
1095
- },
1096
- suggest(indexName, params, options) {
1097
- return post(`${indexPath(indexName)}/suggest`, params, options);
1098
- }
1099
- };
1100
- }
1101
-
1102
- // src/client/server-info.ts
1103
- function createServerOperations(transport) {
1104
- let announced = null;
1105
- async function readCapabilities(options) {
1106
- const path = "/capabilities";
1107
- const payload = await transport.jsonOrNull({ method: "GET", path, options }, ServerErrorCodes.NOT_FOUND);
1108
- if (payload === null) return /* @__PURE__ */ new Set();
1109
- return new Set(readArray(payload, "capabilities", path));
1110
- }
1111
- function load(options) {
1112
- if (announced === null) {
1113
- announced = readCapabilities(options).catch((err) => {
1114
- announced = null;
1115
- throw err;
1116
- });
1117
- }
1118
- return announced;
1119
- }
1120
- return {
1121
- async version(options) {
1122
- const path = "/version";
1123
- return readBody(await transport.json({ method: "GET", path, options }), path);
1124
- },
1125
- async capabilities(options) {
1126
- return [...await load(options)];
1127
- },
1128
- async supports(capability, options) {
1129
- return (await load(options)).has(capability);
1130
- },
1131
- async isAlive(options) {
1132
- return await transport.probe({ method: "GET", path: "/livez", options }) === 200;
1133
- },
1134
- async isReady(options) {
1135
- return await transport.probe({ method: "GET", path: "/readyz", options }) === 200;
1136
- }
1137
- };
1138
- }
1139
-
1140
- // src/client/sync.ts
1141
- var ENTITY_TAG = /^"([0-9a-f]{64})"$/;
1142
- var CONTENT_RANGE = /^bytes (\d+)-(\d+)\/(\d+)$/;
1143
- function invalidDownload(message, path) {
1144
- return new NarsilError(ClientErrorCodes.CLIENT_INVALID_RESPONSE, message, { url: path });
1145
- }
1146
- function createSyncSettingOperations(transport) {
1147
- return {
1148
- async getSync(indexName, options) {
1149
- const path = `${indexPath(indexName)}/sync`;
1150
- return readBody(await transport.json({ method: "GET", path, options }), path);
1151
- },
1152
- async updateSync(indexName, setting, options) {
1153
- const path = `${indexPath(indexName)}/sync`;
1154
- await transport.json({ method: "PUT", path, body: encodeJson(setting), contentType: "application/json", options });
1155
- },
1156
- async syncSnapshot(indexName, resume, options) {
1157
- const path = `${indexPath(indexName)}/sync/snapshot`;
1158
- const headers = resume === void 0 || resume.offset <= 0 ? {} : { range: `bytes=${resume.offset}-`, "if-range": `"${resume.entityTag}"` };
1159
- const answer = await transport.download({ method: "GET", path, headers, defaultTimeoutMs: NO_TIMEOUT, options });
1160
- const entityTag = ENTITY_TAG.exec(answer.headers.get("etag") ?? "")?.[1];
1161
- if (entityTag === void 0) {
1162
- await answer.stream.cancel();
1163
- throw invalidDownload("The server sent the snapshot without an entity tag", path);
1164
- }
1165
- if (answer.status === 206) {
1166
- const range = CONTENT_RANGE.exec(answer.headers.get("content-range") ?? "");
1167
- if (range === null || Number(range[1]) !== resume?.offset) {
1168
- await answer.stream.cancel();
1169
- throw invalidDownload("The server sent a byte range other than the one that the client asked for", path);
1170
- }
1171
- return { entityTag, offset: Number(range[1]), totalBytes: Number(range[3]), stream: answer.stream };
1172
- }
1173
- const length = Number(answer.headers.get("content-length") ?? Number.NaN);
1174
- if (!Number.isSafeInteger(length)) {
1175
- await answer.stream.cancel();
1176
- throw invalidDownload("The server sent the snapshot without its length", path);
1177
- }
1178
- return { entityTag, offset: 0, totalBytes: length, stream: answer.stream };
1179
- }
1180
- };
1181
- }
1182
-
1183
- // src/client/tasks.ts
1184
- function isTerminal(record2) {
1185
- return record2.status === "succeeded" || record2.status === "failed" || record2.status === "cancelled";
1186
- }
1187
- function progressKey(record2) {
1188
- const progress = record2.progress;
1189
- if (progress === void 0) return record2.status;
1190
- return `${record2.status}:${progress.bytesProcessed}:${progress.indexed}:${progress.failed}`;
1191
- }
1192
- function sleep(milliseconds, signal) {
1193
- return new Promise((resolve) => {
1194
- const timer = setTimeout(() => {
1195
- signal?.removeEventListener("abort", stop);
1196
- resolve();
1197
- }, milliseconds);
1198
- function stop() {
1199
- clearTimeout(timer);
1200
- resolve();
1201
- }
1202
- signal?.addEventListener("abort", stop, { once: true });
1203
- });
1204
- }
1205
- function listQuery(query) {
1206
- return {
1207
- indexName: query?.indexName,
1208
- type: query?.type === void 0 || query.type.length === 0 ? void 0 : query.type.join(","),
1209
- status: query?.status === void 0 || query.status.length === 0 ? void 0 : query.status.join(","),
1210
- from: query?.from === void 0 ? void 0 : String(query.from),
1211
- limit: query?.limit === void 0 ? void 0 : String(query.limit)
1212
- };
1213
- }
1214
- function createTaskOperations(transport) {
1215
- const operations = {
1216
- async getTask(taskId, options) {
1217
- const path = taskPath(taskId);
1218
- const payload = await transport.jsonOrNull({ method: "GET", path, options }, ServerErrorCodes.TASK_NOT_FOUND);
1219
- return payload === null ? null : readBody(payload, path);
1220
- },
1221
- async listTasks(query, options) {
1222
- const path = "/tasks";
1223
- const payload = await transport.json({ method: "GET", path, query: listQuery(query), options });
1224
- return readBody(payload, path);
1225
- },
1226
- async cancelTask(taskId, options) {
1227
- const path = `${taskPath(taskId)}/_cancel`;
1228
- return readBody(await transport.json({ method: "POST", path, options }), path);
1229
- },
1230
- async waitForTask(taskId, options) {
1231
- const interval = options?.pollIntervalMs ?? DEFAULT_TASK_POLL_INTERVAL_MS;
1232
- const waitTimeoutMs = options?.waitTimeoutMs ?? 0;
1233
- const startedAt = Date.now();
1234
- let reported = null;
1235
- for (; ; ) {
1236
- if (options?.signal?.aborted === true) {
1237
- throw new NarsilError(
1238
- ClientErrorCodes.CLIENT_REQUEST_ABORTED,
1239
- `The caller stopped waiting for task "${taskId}"`,
1240
- { taskId }
1241
- );
1242
- }
1243
- const record2 = await operations.getTask(taskId, options);
1244
- if (record2 === null) {
1245
- throw new NarsilError(
1246
- ServerErrorCodes.TASK_NOT_FOUND,
1247
- `The server no longer holds task "${taskId}", so its outcome is unknown`,
1248
- { taskId }
1249
- );
1250
- }
1251
- const key = progressKey(record2);
1252
- if (key !== reported) {
1253
- reported = key;
1254
- options?.onProgress?.(record2);
1255
- }
1256
- if (isTerminal(record2)) return record2;
1257
- if (waitTimeoutMs > 0 && Date.now() - startedAt >= waitTimeoutMs) {
1258
- throw new NarsilError(
1259
- ClientErrorCodes.CLIENT_TASK_TIMEOUT,
1260
- `Task "${taskId}" was still ${record2.status} after ${waitTimeoutMs} ms, and it keeps running`,
1261
- { taskId, waitTimeoutMs, status: record2.status }
1262
- );
1263
- }
1264
- await sleep(interval, options?.signal);
1265
- }
1266
- }
1267
- };
1268
- return operations;
1269
- }
1270
-
1271
- // src/client/client.ts
1272
- function createNarsilClient(options) {
1273
- const transport = createTransport(options);
1274
- return {
1275
- ...createIndexOperations(transport),
1276
- ...createDocumentOperations(transport),
1277
- ...createBulkOperations(transport),
1278
- ...createSearchOperations(transport),
1279
- ...createTaskOperations(transport),
1280
- ...createAdminOperations(transport),
1281
- ...createBackupOperations(transport),
1282
- ...createServerOperations(transport),
1283
- ...createSyncSettingOperations(transport),
1284
- ...createQuerySuggestionOperations(transport)
1285
- };
1286
- }
1287
-
1288
- export { ASYNC_IMPORT_CAPABILITY, BM25_TUNING_CAPABILITY, CHANGE_ANALYSIS_CAPABILITY, ClientErrorCodes, DOCUMENT_EXPORT_CAPABILITY, ErrorCodes, INDEX_LIFECYCLE_CAPABILITY, NarsilError, REBUILD_ANALYSIS_CAPABILITY, SERVER_CAPABILITIES, SYNONYMS_CAPABILITY, ServerErrorCodes, TASK_CANCEL_CAPABILITY, TASK_FILTER_CAPABILITY, createNarsilClient, isNarsilError };
26
+ export { ASYNC_IMPORT_CAPABILITY, BM25_TUNING_CAPABILITY, CHANGE_ANALYSIS_CAPABILITY, DOCUMENT_EXPORT_CAPABILITY, INDEX_LIFECYCLE_CAPABILITY, REBUILD_ANALYSIS_CAPABILITY, SERVER_CAPABILITIES, SYNONYMS_CAPABILITY, TASK_CANCEL_CAPABILITY, TASK_FILTER_CAPABILITY };