@nebula-ai/sdk 1.2.0 → 1.3.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.
Files changed (423) hide show
  1. package/CHANGELOG.md +35 -0
  2. package/LICENSE +4 -23
  3. package/README.md +305 -128
  4. package/api-promise.d.mts +2 -0
  5. package/api-promise.d.mts.map +1 -0
  6. package/api-promise.d.ts +2 -0
  7. package/api-promise.d.ts.map +1 -0
  8. package/api-promise.js +6 -0
  9. package/api-promise.js.map +1 -0
  10. package/api-promise.mjs +2 -0
  11. package/api-promise.mjs.map +1 -0
  12. package/client.d.mts +205 -0
  13. package/client.d.mts.map +1 -0
  14. package/client.d.ts +205 -0
  15. package/client.d.ts.map +1 -0
  16. package/client.js +505 -0
  17. package/client.js.map +1 -0
  18. package/client.mjs +501 -0
  19. package/client.mjs.map +1 -0
  20. package/core/api-promise.d.mts +46 -0
  21. package/core/api-promise.d.mts.map +1 -0
  22. package/core/api-promise.d.ts +46 -0
  23. package/core/api-promise.d.ts.map +1 -0
  24. package/core/api-promise.js +74 -0
  25. package/core/api-promise.js.map +1 -0
  26. package/core/api-promise.mjs +70 -0
  27. package/core/api-promise.mjs.map +1 -0
  28. package/core/error.d.mts +46 -0
  29. package/core/error.d.mts.map +1 -0
  30. package/core/error.d.ts +46 -0
  31. package/core/error.d.ts.map +1 -0
  32. package/core/error.js +113 -0
  33. package/core/error.js.map +1 -0
  34. package/core/error.mjs +97 -0
  35. package/core/error.mjs.map +1 -0
  36. package/core/resource.d.mts +6 -0
  37. package/core/resource.d.mts.map +1 -0
  38. package/core/resource.d.ts +6 -0
  39. package/core/resource.d.ts.map +1 -0
  40. package/core/resource.js +11 -0
  41. package/core/resource.js.map +1 -0
  42. package/core/resource.mjs +7 -0
  43. package/core/resource.mjs.map +1 -0
  44. package/core/uploads.d.mts +3 -0
  45. package/core/uploads.d.mts.map +1 -0
  46. package/core/uploads.d.ts +3 -0
  47. package/core/uploads.d.ts.map +1 -0
  48. package/core/uploads.js +6 -0
  49. package/core/uploads.js.map +1 -0
  50. package/core/uploads.mjs +2 -0
  51. package/core/uploads.mjs.map +1 -0
  52. package/error.d.mts +2 -0
  53. package/error.d.mts.map +1 -0
  54. package/error.d.ts +2 -0
  55. package/error.d.ts.map +1 -0
  56. package/error.js +6 -0
  57. package/error.js.map +1 -0
  58. package/error.mjs +2 -0
  59. package/error.mjs.map +1 -0
  60. package/index.d.mts +13 -0
  61. package/index.d.mts.map +1 -0
  62. package/index.d.ts +13 -0
  63. package/index.d.ts.map +1 -0
  64. package/index.js +43 -0
  65. package/index.js.map +1 -0
  66. package/index.mjs +13 -0
  67. package/index.mjs.map +1 -0
  68. package/internal/builtin-types.d.mts +73 -0
  69. package/internal/builtin-types.d.mts.map +1 -0
  70. package/internal/builtin-types.d.ts +73 -0
  71. package/internal/builtin-types.d.ts.map +1 -0
  72. package/internal/builtin-types.js +4 -0
  73. package/internal/builtin-types.js.map +1 -0
  74. package/internal/builtin-types.mjs +3 -0
  75. package/internal/builtin-types.mjs.map +1 -0
  76. package/internal/detect-platform.d.mts +15 -0
  77. package/internal/detect-platform.d.mts.map +1 -0
  78. package/internal/detect-platform.d.ts +15 -0
  79. package/internal/detect-platform.d.ts.map +1 -0
  80. package/internal/detect-platform.js +162 -0
  81. package/internal/detect-platform.js.map +1 -0
  82. package/internal/detect-platform.mjs +157 -0
  83. package/internal/detect-platform.mjs.map +1 -0
  84. package/internal/errors.d.mts +3 -0
  85. package/internal/errors.d.mts.map +1 -0
  86. package/internal/errors.d.ts +3 -0
  87. package/internal/errors.d.ts.map +1 -0
  88. package/internal/errors.js +41 -0
  89. package/internal/errors.js.map +1 -0
  90. package/internal/errors.mjs +36 -0
  91. package/internal/errors.mjs.map +1 -0
  92. package/internal/headers.d.mts +20 -0
  93. package/internal/headers.d.mts.map +1 -0
  94. package/internal/headers.d.ts +20 -0
  95. package/internal/headers.d.ts.map +1 -0
  96. package/internal/headers.js +79 -0
  97. package/internal/headers.js.map +1 -0
  98. package/internal/headers.mjs +74 -0
  99. package/internal/headers.mjs.map +1 -0
  100. package/internal/parse.d.mts +12 -0
  101. package/internal/parse.d.mts.map +1 -0
  102. package/internal/parse.d.ts +12 -0
  103. package/internal/parse.d.ts.map +1 -0
  104. package/internal/parse.js +40 -0
  105. package/internal/parse.js.map +1 -0
  106. package/internal/parse.mjs +37 -0
  107. package/internal/parse.mjs.map +1 -0
  108. package/internal/qs/formats.d.mts +7 -0
  109. package/internal/qs/formats.d.mts.map +1 -0
  110. package/internal/qs/formats.d.ts +7 -0
  111. package/internal/qs/formats.d.ts.map +1 -0
  112. package/internal/qs/formats.js +13 -0
  113. package/internal/qs/formats.js.map +1 -0
  114. package/internal/qs/formats.mjs +9 -0
  115. package/internal/qs/formats.mjs.map +1 -0
  116. package/internal/qs/index.d.mts +10 -0
  117. package/internal/qs/index.d.mts.map +1 -0
  118. package/internal/qs/index.d.ts +10 -0
  119. package/internal/qs/index.d.ts.map +1 -0
  120. package/internal/qs/index.js +14 -0
  121. package/internal/qs/index.js.map +1 -0
  122. package/internal/qs/index.mjs +10 -0
  123. package/internal/qs/index.mjs.map +1 -0
  124. package/internal/qs/stringify.d.mts +3 -0
  125. package/internal/qs/stringify.d.mts.map +1 -0
  126. package/internal/qs/stringify.d.ts +3 -0
  127. package/internal/qs/stringify.d.ts.map +1 -0
  128. package/internal/qs/stringify.js +277 -0
  129. package/internal/qs/stringify.js.map +1 -0
  130. package/internal/qs/stringify.mjs +274 -0
  131. package/internal/qs/stringify.mjs.map +1 -0
  132. package/internal/qs/types.d.mts +57 -0
  133. package/internal/qs/types.d.mts.map +1 -0
  134. package/internal/qs/types.d.ts +57 -0
  135. package/internal/qs/types.d.ts.map +1 -0
  136. package/internal/qs/types.js +3 -0
  137. package/internal/qs/types.js.map +1 -0
  138. package/internal/qs/types.mjs +2 -0
  139. package/internal/qs/types.mjs.map +1 -0
  140. package/internal/qs/utils.d.mts +15 -0
  141. package/internal/qs/utils.d.mts.map +1 -0
  142. package/internal/qs/utils.d.ts +15 -0
  143. package/internal/qs/utils.d.ts.map +1 -0
  144. package/internal/qs/utils.js +230 -0
  145. package/internal/qs/utils.js.map +1 -0
  146. package/internal/qs/utils.mjs +217 -0
  147. package/internal/qs/utils.mjs.map +1 -0
  148. package/internal/request-options.d.mts +79 -0
  149. package/internal/request-options.d.mts.map +1 -0
  150. package/internal/request-options.d.ts +79 -0
  151. package/internal/request-options.d.ts.map +1 -0
  152. package/internal/request-options.js +14 -0
  153. package/internal/request-options.js.map +1 -0
  154. package/internal/request-options.mjs +10 -0
  155. package/internal/request-options.mjs.map +1 -0
  156. package/internal/shim-types.d.mts +17 -0
  157. package/internal/shim-types.d.mts.map +1 -0
  158. package/internal/shim-types.d.ts +17 -0
  159. package/internal/shim-types.d.ts.map +1 -0
  160. package/internal/shim-types.js +4 -0
  161. package/internal/shim-types.js.map +1 -0
  162. package/internal/shim-types.mjs +3 -0
  163. package/internal/shim-types.mjs.map +1 -0
  164. package/internal/shims.d.mts +20 -0
  165. package/internal/shims.d.mts.map +1 -0
  166. package/internal/shims.d.ts +20 -0
  167. package/internal/shims.d.ts.map +1 -0
  168. package/internal/shims.js +92 -0
  169. package/internal/shims.js.map +1 -0
  170. package/internal/shims.mjs +85 -0
  171. package/internal/shims.mjs.map +1 -0
  172. package/internal/to-file.d.mts +45 -0
  173. package/internal/to-file.d.mts.map +1 -0
  174. package/internal/to-file.d.ts +45 -0
  175. package/internal/to-file.d.ts.map +1 -0
  176. package/internal/to-file.js +91 -0
  177. package/internal/to-file.js.map +1 -0
  178. package/internal/to-file.mjs +88 -0
  179. package/internal/to-file.mjs.map +1 -0
  180. package/internal/tslib.js +81 -0
  181. package/internal/tslib.mjs +17 -0
  182. package/internal/types.d.mts +69 -0
  183. package/internal/types.d.mts.map +1 -0
  184. package/internal/types.d.ts +69 -0
  185. package/internal/types.d.ts.map +1 -0
  186. package/internal/types.js +4 -0
  187. package/internal/types.js.map +1 -0
  188. package/internal/types.mjs +3 -0
  189. package/internal/types.mjs.map +1 -0
  190. package/internal/uploads.d.mts +42 -0
  191. package/internal/uploads.d.mts.map +1 -0
  192. package/internal/uploads.d.ts +42 -0
  193. package/internal/uploads.d.ts.map +1 -0
  194. package/internal/uploads.js +141 -0
  195. package/internal/uploads.js.map +1 -0
  196. package/internal/uploads.mjs +131 -0
  197. package/internal/uploads.mjs.map +1 -0
  198. package/internal/utils/base64.d.mts +3 -0
  199. package/internal/utils/base64.d.mts.map +1 -0
  200. package/internal/utils/base64.d.ts +3 -0
  201. package/internal/utils/base64.d.ts.map +1 -0
  202. package/internal/utils/base64.js +38 -0
  203. package/internal/utils/base64.js.map +1 -0
  204. package/internal/utils/base64.mjs +33 -0
  205. package/internal/utils/base64.mjs.map +1 -0
  206. package/internal/utils/bytes.d.mts +4 -0
  207. package/internal/utils/bytes.d.mts.map +1 -0
  208. package/internal/utils/bytes.d.ts +4 -0
  209. package/internal/utils/bytes.d.ts.map +1 -0
  210. package/internal/utils/bytes.js +31 -0
  211. package/internal/utils/bytes.js.map +1 -0
  212. package/internal/utils/bytes.mjs +26 -0
  213. package/internal/utils/bytes.mjs.map +1 -0
  214. package/internal/utils/env.d.mts +9 -0
  215. package/internal/utils/env.d.mts.map +1 -0
  216. package/internal/utils/env.d.ts +9 -0
  217. package/internal/utils/env.d.ts.map +1 -0
  218. package/internal/utils/env.js +22 -0
  219. package/internal/utils/env.js.map +1 -0
  220. package/internal/utils/env.mjs +18 -0
  221. package/internal/utils/env.mjs.map +1 -0
  222. package/internal/utils/log.d.mts +37 -0
  223. package/internal/utils/log.d.mts.map +1 -0
  224. package/internal/utils/log.d.ts +37 -0
  225. package/internal/utils/log.d.ts.map +1 -0
  226. package/internal/utils/log.js +86 -0
  227. package/internal/utils/log.js.map +1 -0
  228. package/internal/utils/log.mjs +80 -0
  229. package/internal/utils/log.mjs.map +1 -0
  230. package/internal/utils/path.d.mts +15 -0
  231. package/internal/utils/path.d.mts.map +1 -0
  232. package/internal/utils/path.d.ts +15 -0
  233. package/internal/utils/path.d.ts.map +1 -0
  234. package/internal/utils/path.js +79 -0
  235. package/internal/utils/path.js.map +1 -0
  236. package/internal/utils/path.mjs +74 -0
  237. package/internal/utils/path.mjs.map +1 -0
  238. package/internal/utils/query.d.mts +2 -0
  239. package/internal/utils/query.d.mts.map +1 -0
  240. package/internal/utils/query.d.ts +2 -0
  241. package/internal/utils/query.d.ts.map +1 -0
  242. package/internal/utils/query.js +10 -0
  243. package/internal/utils/query.js.map +1 -0
  244. package/internal/utils/query.mjs +6 -0
  245. package/internal/utils/query.mjs.map +1 -0
  246. package/internal/utils/sleep.d.mts +2 -0
  247. package/internal/utils/sleep.d.mts.map +1 -0
  248. package/internal/utils/sleep.d.ts +2 -0
  249. package/internal/utils/sleep.d.ts.map +1 -0
  250. package/internal/utils/sleep.js +7 -0
  251. package/internal/utils/sleep.js.map +1 -0
  252. package/internal/utils/sleep.mjs +3 -0
  253. package/internal/utils/sleep.mjs.map +1 -0
  254. package/internal/utils/uuid.d.mts +5 -0
  255. package/internal/utils/uuid.d.mts.map +1 -0
  256. package/internal/utils/uuid.d.ts +5 -0
  257. package/internal/utils/uuid.d.ts.map +1 -0
  258. package/internal/utils/uuid.js +19 -0
  259. package/internal/utils/uuid.js.map +1 -0
  260. package/internal/utils/uuid.mjs +15 -0
  261. package/internal/utils/uuid.mjs.map +1 -0
  262. package/internal/utils/values.d.mts +18 -0
  263. package/internal/utils/values.d.mts.map +1 -0
  264. package/internal/utils/values.d.ts +18 -0
  265. package/internal/utils/values.d.ts.map +1 -0
  266. package/internal/utils/values.js +112 -0
  267. package/internal/utils/values.js.map +1 -0
  268. package/internal/utils/values.mjs +94 -0
  269. package/internal/utils/values.mjs.map +1 -0
  270. package/internal/utils.d.mts +8 -0
  271. package/internal/utils.d.mts.map +1 -0
  272. package/internal/utils.d.ts +8 -0
  273. package/internal/utils.d.ts.map +1 -0
  274. package/internal/utils.js +12 -0
  275. package/internal/utils.js.map +1 -0
  276. package/internal/utils.mjs +9 -0
  277. package/internal/utils.mjs.map +1 -0
  278. package/lib/dx.d.mts +96 -0
  279. package/lib/dx.d.mts.map +1 -0
  280. package/lib/dx.d.ts +96 -0
  281. package/lib/dx.d.ts.map +1 -0
  282. package/lib/dx.js +239 -0
  283. package/lib/dx.js.map +1 -0
  284. package/lib/dx.mjs +235 -0
  285. package/lib/dx.mjs.map +1 -0
  286. package/package.json +144 -58
  287. package/resource.d.mts +2 -0
  288. package/resource.d.mts.map +1 -0
  289. package/resource.d.ts +2 -0
  290. package/resource.d.ts.map +1 -0
  291. package/resource.js +6 -0
  292. package/resource.js.map +1 -0
  293. package/resource.mjs +2 -0
  294. package/resource.mjs.map +1 -0
  295. package/resources/collections.d.mts +289 -0
  296. package/resources/collections.d.mts.map +1 -0
  297. package/resources/collections.d.ts +289 -0
  298. package/resources/collections.d.ts.map +1 -0
  299. package/resources/collections.js +72 -0
  300. package/resources/collections.js.map +1 -0
  301. package/resources/collections.mjs +68 -0
  302. package/resources/collections.mjs.map +1 -0
  303. package/resources/connectors.d.mts +148 -0
  304. package/resources/connectors.d.mts.map +1 -0
  305. package/resources/connectors.d.ts +148 -0
  306. package/resources/connectors.d.ts.map +1 -0
  307. package/resources/connectors.js +50 -0
  308. package/resources/connectors.js.map +1 -0
  309. package/resources/connectors.mjs +46 -0
  310. package/resources/connectors.mjs.map +1 -0
  311. package/resources/index.d.mts +6 -0
  312. package/resources/index.d.mts.map +1 -0
  313. package/resources/index.d.ts +6 -0
  314. package/resources/index.d.ts.map +1 -0
  315. package/resources/index.js +13 -0
  316. package/resources/index.js.map +1 -0
  317. package/resources/index.mjs +6 -0
  318. package/resources/index.mjs.map +1 -0
  319. package/resources/memories.d.mts +1737 -0
  320. package/resources/memories.d.mts.map +1 -0
  321. package/resources/memories.d.ts +1737 -0
  322. package/resources/memories.d.ts.map +1 -0
  323. package/resources/memories.js +157 -0
  324. package/resources/memories.js.map +1 -0
  325. package/resources/memories.mjs +153 -0
  326. package/resources/memories.mjs.map +1 -0
  327. package/resources/snapshots.d.mts +281 -0
  328. package/resources/snapshots.d.mts.map +1 -0
  329. package/resources/snapshots.d.ts +281 -0
  330. package/resources/snapshots.d.ts.map +1 -0
  331. package/resources/snapshots.js +22 -0
  332. package/resources/snapshots.js.map +1 -0
  333. package/resources/snapshots.mjs +18 -0
  334. package/resources/snapshots.mjs.map +1 -0
  335. package/resources/top-level.d.mts +14 -0
  336. package/resources/top-level.d.mts.map +1 -0
  337. package/resources/top-level.d.ts +14 -0
  338. package/resources/top-level.d.ts.map +1 -0
  339. package/resources/top-level.js +4 -0
  340. package/resources/top-level.js.map +1 -0
  341. package/resources/top-level.mjs +3 -0
  342. package/resources/top-level.mjs.map +1 -0
  343. package/resources.d.mts +2 -0
  344. package/resources.d.mts.map +1 -0
  345. package/resources.d.ts +2 -0
  346. package/resources.d.ts.map +1 -0
  347. package/resources.js +5 -0
  348. package/resources.js.map +1 -0
  349. package/resources.mjs +2 -0
  350. package/resources.mjs.map +1 -0
  351. package/src/api-promise.ts +2 -0
  352. package/src/client.ts +892 -0
  353. package/src/core/README.md +3 -0
  354. package/src/core/api-promise.ts +92 -0
  355. package/src/core/error.ts +130 -0
  356. package/src/core/resource.ts +11 -0
  357. package/src/core/uploads.ts +2 -0
  358. package/src/error.ts +2 -0
  359. package/src/index.ts +36 -0
  360. package/src/internal/README.md +3 -0
  361. package/src/internal/builtin-types.ts +93 -0
  362. package/src/internal/detect-platform.ts +196 -0
  363. package/src/internal/errors.ts +33 -0
  364. package/src/internal/headers.ts +97 -0
  365. package/src/internal/parse.ts +56 -0
  366. package/src/internal/qs/LICENSE.md +13 -0
  367. package/src/internal/qs/README.md +3 -0
  368. package/src/internal/qs/formats.ts +10 -0
  369. package/src/internal/qs/index.ts +13 -0
  370. package/src/internal/qs/stringify.ts +385 -0
  371. package/src/internal/qs/types.ts +71 -0
  372. package/src/internal/qs/utils.ts +265 -0
  373. package/src/internal/request-options.ts +93 -0
  374. package/src/internal/shim-types.ts +26 -0
  375. package/src/internal/shims.ts +107 -0
  376. package/src/internal/to-file.ts +154 -0
  377. package/src/internal/types.ts +95 -0
  378. package/src/internal/uploads.ts +187 -0
  379. package/src/internal/utils/base64.ts +40 -0
  380. package/src/internal/utils/bytes.ts +32 -0
  381. package/src/internal/utils/env.ts +18 -0
  382. package/src/internal/utils/log.ts +127 -0
  383. package/src/internal/utils/path.ts +88 -0
  384. package/src/internal/utils/query.ts +7 -0
  385. package/src/internal/utils/sleep.ts +3 -0
  386. package/src/internal/utils/uuid.ts +17 -0
  387. package/src/internal/utils/values.ts +105 -0
  388. package/src/internal/utils.ts +9 -0
  389. package/src/lib/.keep +4 -0
  390. package/src/lib/dx.ts +459 -0
  391. package/src/resource.ts +2 -0
  392. package/src/resources/collections.ts +474 -0
  393. package/src/resources/connectors.ts +236 -0
  394. package/src/resources/index.ts +56 -0
  395. package/src/resources/memories.ts +2409 -0
  396. package/src/resources/snapshots.ts +387 -0
  397. package/src/resources/top-level.ts +19 -0
  398. package/src/resources.ts +1 -0
  399. package/src/tsconfig.json +11 -0
  400. package/src/uploads.ts +2 -0
  401. package/src/version.ts +1 -0
  402. package/uploads.d.mts +2 -0
  403. package/uploads.d.mts.map +1 -0
  404. package/uploads.d.ts +2 -0
  405. package/uploads.d.ts.map +1 -0
  406. package/uploads.js +6 -0
  407. package/uploads.js.map +1 -0
  408. package/uploads.mjs +2 -0
  409. package/uploads.mjs.map +1 -0
  410. package/version.d.mts +2 -0
  411. package/version.d.mts.map +1 -0
  412. package/version.d.ts +2 -0
  413. package/version.d.ts.map +1 -0
  414. package/version.js +5 -0
  415. package/version.js.map +1 -0
  416. package/version.mjs +2 -0
  417. package/version.mjs.map +1 -0
  418. package/dist/index.d.mts +0 -557
  419. package/dist/index.d.ts +0 -557
  420. package/dist/index.js +0 -1282
  421. package/dist/index.js.map +0 -1
  422. package/dist/index.mjs +0 -1267
  423. package/dist/index.mjs.map +0 -1
package/dist/index.mjs DELETED
@@ -1,1267 +0,0 @@
1
- // src/types.ts
2
- var GraphSearchResultType = /* @__PURE__ */ ((GraphSearchResultType2) => {
3
- GraphSearchResultType2["ENTITY"] = "entity";
4
- GraphSearchResultType2["RELATIONSHIP"] = "relationship";
5
- GraphSearchResultType2["COMMUNITY"] = "community";
6
- return GraphSearchResultType2;
7
- })(GraphSearchResultType || {});
8
- var NebulaException = class extends Error {
9
- constructor(message, statusCode, details) {
10
- super(message);
11
- this.statusCode = statusCode;
12
- this.details = details;
13
- this.name = "NebulaException";
14
- }
15
- };
16
- var NebulaClientException = class extends NebulaException {
17
- constructor(message, cause) {
18
- super(message);
19
- this.cause = cause;
20
- this.name = "NebulaClientException";
21
- }
22
- };
23
- var NebulaAuthenticationException = class extends NebulaException {
24
- constructor(message = "Invalid API key") {
25
- super(message, 401);
26
- this.name = "NebulaAuthenticationException";
27
- }
28
- };
29
- var NebulaRateLimitException = class extends NebulaException {
30
- constructor(message = "Rate limit exceeded") {
31
- super(message, 429);
32
- this.name = "NebulaRateLimitException";
33
- }
34
- };
35
- var NebulaValidationException = class extends NebulaException {
36
- constructor(message = "Validation error", details) {
37
- super(message, 400);
38
- this.details = details;
39
- this.name = "NebulaValidationException";
40
- }
41
- };
42
- var NebulaCollectionNotFoundException = class extends NebulaException {
43
- constructor(message = "Collection not found") {
44
- super(message, 404);
45
- this.name = "NebulaCollectionNotFoundException";
46
- }
47
- };
48
- var NebulaNotFoundException = class extends NebulaException {
49
- constructor(resourceId, resourceType = "Resource") {
50
- super(`${resourceType} not found: ${resourceId}`, 404);
51
- this.name = "NebulaNotFoundException";
52
- }
53
- };
54
-
55
- // src/client.ts
56
- var _Nebula = class _Nebula {
57
- // 5MB
58
- constructor(config = {}) {
59
- this.apiKey = config.apiKey;
60
- if (!this.apiKey) {
61
- throw new NebulaClientException(
62
- "API key is required. Pass it to the constructor or set NEBULA_API_KEY environment variable."
63
- );
64
- }
65
- this.baseUrl = (config.baseUrl || "https://api.trynebula.ai").replace(/\/$/, "");
66
- this.timeout = config.timeout || 3e4;
67
- }
68
- // Public mutators used by tests
69
- setApiKey(next) {
70
- this.apiKey = next;
71
- }
72
- setBaseUrl(next) {
73
- this.baseUrl = (next || this.baseUrl).replace(/\/$/, "");
74
- }
75
- // Kept for backwards-compat tests; no-op in current implementation
76
- setCorsProxy(_next) {
77
- }
78
- /** Check if API key is set */
79
- isApiKeySet() {
80
- return !!(this.apiKey && this.apiKey.trim() !== "");
81
- }
82
- /** Detect if a token looks like a Nebula API key (public.raw) */
83
- _isNebulaApiKey(token) {
84
- const candidate = token || this.apiKey;
85
- if (!candidate) return false;
86
- const parts = candidate.split(".");
87
- if (parts.length !== 2) return false;
88
- const [publicPart, rawPart] = parts;
89
- return (publicPart.startsWith("key_") || publicPart.startsWith("neb_")) && !!rawPart && rawPart.length > 0;
90
- }
91
- /** Build authentication headers */
92
- _buildAuthHeaders(includeContentType = true) {
93
- const headers = {};
94
- if (this._isNebulaApiKey()) {
95
- headers["X-API-Key"] = this.apiKey;
96
- } else {
97
- headers["Authorization"] = `Bearer ${this.apiKey}`;
98
- }
99
- if (includeContentType) {
100
- headers["Content-Type"] = "application/json";
101
- }
102
- return headers;
103
- }
104
- _isRecord(value) {
105
- return typeof value === "object" && value !== null && !Array.isArray(value);
106
- }
107
- _unwrapResults(value) {
108
- if (this._isRecord(value) && "results" in value) {
109
- return value.results;
110
- }
111
- return value;
112
- }
113
- _unwrapResultsArray(value) {
114
- const unwrapped = this._unwrapResults(value);
115
- if (Array.isArray(unwrapped)) {
116
- return unwrapped;
117
- }
118
- if (unwrapped === void 0 || unwrapped === null) {
119
- return [];
120
- }
121
- return [unwrapped];
122
- }
123
- _looksLikeMultimodalContent(content) {
124
- if (!Array.isArray(content)) return false;
125
- return content.some((part) => {
126
- if (!this._isRecord(part)) return false;
127
- if (typeof part.type === "string") return true;
128
- if ("data" in part || "s3_key" in part || "url" in part) return true;
129
- return false;
130
- });
131
- }
132
- _normalizeContentParts(contentParts) {
133
- return contentParts.map((part) => {
134
- if (typeof part === "string") {
135
- return { type: "text", text: part };
136
- }
137
- if (!this._isRecord(part)) {
138
- return { type: "text", text: String(part) };
139
- }
140
- if (typeof part.type === "string") {
141
- return part;
142
- }
143
- if ("s3_key" in part && typeof part.s3_key === "string") {
144
- return {
145
- type: "s3_ref",
146
- s3_key: part.s3_key,
147
- bucket: typeof part.bucket === "string" ? part.bucket : void 0,
148
- media_type: typeof part.media_type === "string" ? part.media_type : "application/octet-stream",
149
- filename: typeof part.filename === "string" ? part.filename : void 0,
150
- size_bytes: typeof part.size_bytes === "number" ? part.size_bytes : void 0
151
- };
152
- }
153
- if ("data" in part && typeof part.data === "string") {
154
- return {
155
- type: "file",
156
- data: part.data,
157
- media_type: typeof part.media_type === "string" ? part.media_type : "application/octet-stream",
158
- filename: typeof part.filename === "string" ? part.filename : void 0,
159
- duration_seconds: typeof part.duration_seconds === "number" ? part.duration_seconds : void 0
160
- };
161
- }
162
- return { type: "text", text: String(part) };
163
- });
164
- }
165
- async _serializeContentAsText(content) {
166
- if (this._looksLikeMultimodalContent(content)) {
167
- const normalized = this._normalizeContentParts(content);
168
- const processed = await this._processContentParts(normalized);
169
- return JSON.stringify(processed);
170
- }
171
- if (typeof content === "object" && content !== null) {
172
- return JSON.stringify(content);
173
- }
174
- return String(content ?? "");
175
- }
176
- async _serializeContentAsParts(content) {
177
- if (!this._looksLikeMultimodalContent(content)) return null;
178
- const normalized = this._normalizeContentParts(content);
179
- return await this._processContentParts(normalized);
180
- }
181
- /** Make an HTTP request to the Nebula API */
182
- async _makeRequest(method, endpoint, jsonData, params, extraHeaders) {
183
- const url = new URL(endpoint, this.baseUrl);
184
- if (params) {
185
- Object.entries(params).forEach(([key, value]) => {
186
- if (value !== void 0 && value !== null) {
187
- if (Array.isArray(value)) {
188
- value.forEach((item) => {
189
- url.searchParams.append(key, String(item));
190
- });
191
- } else {
192
- url.searchParams.append(key, String(value));
193
- }
194
- }
195
- });
196
- }
197
- const headers = { ...this._buildAuthHeaders(true), ...extraHeaders };
198
- const controller = new AbortController();
199
- const timeoutId = setTimeout(() => controller.abort(), this.timeout);
200
- try {
201
- const response = await fetch(url.toString(), {
202
- method,
203
- headers,
204
- body: jsonData ? JSON.stringify(jsonData) : void 0,
205
- signal: controller.signal
206
- });
207
- clearTimeout(timeoutId);
208
- if (response.status === 200 || response.status === 202) {
209
- return await response.json();
210
- } else if (response.status === 401) {
211
- throw new NebulaAuthenticationException("Invalid API key");
212
- } else if (response.status === 429) {
213
- throw new NebulaRateLimitException("Rate limit exceeded");
214
- } else if (response.status === 400) {
215
- const errorData = await response.json().catch(() => ({}));
216
- throw new NebulaValidationException(errorData.message || "Validation error", errorData.details);
217
- } else if (response.status === 422) {
218
- const errorData = await response.json().catch(() => ({}));
219
- console.error("[SDK] 422 Validation error - Full details:");
220
- console.error(" Status:", response.status);
221
- console.error(" Error data:", JSON.stringify(errorData, null, 2));
222
- console.error(" Message:", errorData.message);
223
- console.error(" Detail:", errorData.detail);
224
- throw new NebulaValidationException(
225
- errorData.message || (typeof errorData.detail === "string" ? errorData.detail : JSON.stringify(errorData.detail)) || "Validation error",
226
- errorData
227
- );
228
- } else {
229
- const errorData = await response.json().catch(() => ({}));
230
- throw new NebulaException(errorData.message || `API error: ${response.status}`, response.status, errorData);
231
- }
232
- } catch (error) {
233
- clearTimeout(timeoutId);
234
- if (error instanceof NebulaException) {
235
- throw error;
236
- }
237
- if (error instanceof Error && error.name === "AbortError") {
238
- throw new NebulaClientException(`Request timed out after ${this.timeout} milliseconds`);
239
- }
240
- if (error instanceof Error) {
241
- throw new NebulaClientException(`Request failed: ${error.message}`, error);
242
- }
243
- throw new NebulaClientException(`Request failed: ${String(error)}`);
244
- }
245
- }
246
- // Collection Management Methods
247
- /** Create a new collection */
248
- async createCollection(options) {
249
- const data = { name: options.name };
250
- if (options.description) data.description = options.description;
251
- if (options.metadata) data.metadata = options.metadata;
252
- const response = await this._makeRequest("POST", "/v1/collections", data);
253
- const result = response.results || response;
254
- return this._collectionFromDict(result);
255
- }
256
- /** Get a specific collection by ID */
257
- async getCollection(collectionId) {
258
- const response = await this._makeRequest("GET", `/v1/collections/${collectionId}`);
259
- const result = response.results || response;
260
- return this._collectionFromDict(result);
261
- }
262
- /** Get a specific collection by name */
263
- async getCollectionByName(name) {
264
- const response = await this._makeRequest("GET", `/v1/collections/name/${name}`);
265
- const result = response.results || response;
266
- return this._collectionFromDict(result);
267
- }
268
- /** Get all collections */
269
- async listCollections(options) {
270
- const params = {
271
- limit: options?.limit ?? 100,
272
- offset: options?.offset ?? 0
273
- };
274
- if (options?.name !== void 0) {
275
- params.name = options.name;
276
- }
277
- const response = await this._makeRequest("GET", "/v1/collections", void 0, params);
278
- let collections;
279
- if (typeof response === "object" && response !== null && "results" in response) {
280
- collections = response.results;
281
- } else if (Array.isArray(response)) {
282
- collections = response;
283
- } else {
284
- collections = [response];
285
- }
286
- return collections.map((collection) => this._collectionFromDict(collection));
287
- }
288
- /** Update a collection */
289
- async updateCollection(options) {
290
- const data = {};
291
- if (options.name !== void 0) data.name = options.name;
292
- if (options.description !== void 0) data.description = options.description;
293
- if (options.metadata !== void 0) data.metadata = options.metadata;
294
- const response = await this._makeRequest("POST", `/v1/collections/${options.collectionId}`, data);
295
- const result = response.results || response;
296
- return this._collectionFromDict(result);
297
- }
298
- /** Delete a collection */
299
- async deleteCollection(collectionId) {
300
- await this._makeRequest("DELETE", `/v1/collections/${collectionId}`);
301
- return true;
302
- }
303
- // Memory Management Methods
304
- /**
305
- * Legacy convenience: store raw text content into a collection as a document
306
- */
307
- async store(content, collectionId, metadata = {}) {
308
- const docMetadata = {
309
- ...metadata,
310
- memory_type: "memory",
311
- timestamp: (/* @__PURE__ */ new Date()).toISOString()
312
- };
313
- const payload = {
314
- collection_id: collectionId,
315
- raw_text: String(content || ""),
316
- metadata: docMetadata,
317
- ingestion_mode: "fast"
318
- };
319
- const response = await this._makeRequest("POST", "/v1/memories", payload);
320
- const id = response?.results?.engram_id || response?.results?.id || response?.id || "";
321
- const timestamp = docMetadata.timestamp;
322
- const result = {
323
- id: String(id),
324
- memory_id: String(id),
325
- content: String(content || ""),
326
- metadata: docMetadata,
327
- collection_ids: [collectionId],
328
- created_at: timestamp,
329
- updated_at: timestamp
330
- };
331
- return result;
332
- }
333
- /**
334
- * Store a single memory using the unified engrams API.
335
- *
336
- * Automatically infers memory type:
337
- * - If role is present, creates a conversation
338
- * - Otherwise, creates a document
339
- */
340
- async storeMemory(memory, name) {
341
- let mem;
342
- if ("collection_id" in memory) {
343
- mem = memory;
344
- } else {
345
- const memRecord2 = memory;
346
- mem = {
347
- collection_id: memRecord2.collection_id || memRecord2.collectionId || "",
348
- content: memRecord2.content || "",
349
- role: memRecord2.role,
350
- memory_id: memRecord2.memory_id || memRecord2.memoryId || void 0,
351
- metadata: memRecord2.metadata || {}
352
- };
353
- }
354
- if (mem.memory_id) {
355
- return await this._appendToMemory(mem.memory_id, mem);
356
- }
357
- const memoryType = mem.role ? "conversation" : "document";
358
- if (memoryType === "conversation") {
359
- const messages = [];
360
- if (mem.content && mem.role) {
361
- const multimodalParts2 = await this._serializeContentAsParts(mem.content);
362
- const msgContent = multimodalParts2 ?? await this._serializeContentAsText(mem.content);
363
- const memRecord2 = mem;
364
- messages.push({
365
- content: msgContent,
366
- role: mem.role,
367
- metadata: mem.metadata || {},
368
- ...typeof memRecord2.authority === "number" ? { authority: Number(memRecord2.authority) } : {}
369
- });
370
- }
371
- if (messages.length === 0) {
372
- throw new NebulaClientException("Cannot create conversation without messages. Provide content and role.");
373
- }
374
- const data = {
375
- collection_id: mem.collection_id,
376
- name: name || "Conversation",
377
- messages,
378
- metadata: mem.metadata || {}
379
- };
380
- const response2 = await this._makeRequest("POST", "/v1/memories", data);
381
- if (response2.results) {
382
- const convId = response2.results.memory_id || response2.results.id;
383
- if (!convId) {
384
- throw new NebulaClientException("Failed to create conversation: no id returned");
385
- }
386
- return String(convId);
387
- }
388
- throw new NebulaClientException("Failed to create conversation: invalid response format");
389
- }
390
- const docMetadata = { ...mem.metadata };
391
- docMetadata.memory_type = "memory";
392
- const memRecord = mem;
393
- if (typeof memRecord.authority === "number") {
394
- const v = Number(memRecord.authority);
395
- if (!Number.isNaN(v) && v >= 0 && v <= 1) {
396
- docMetadata.authority = v;
397
- }
398
- }
399
- let payload;
400
- const multimodalParts = await this._serializeContentAsParts(mem.content);
401
- if (multimodalParts) {
402
- payload = {
403
- collection_id: mem.collection_id,
404
- content_parts: multimodalParts,
405
- metadata: docMetadata,
406
- ingestion_mode: "fast"
407
- };
408
- } else if (Array.isArray(mem.content) && mem.content.every((x) => typeof x === "string")) {
409
- payload = {
410
- collection_id: mem.collection_id,
411
- chunks: mem.content,
412
- metadata: docMetadata,
413
- ingestion_mode: "fast"
414
- };
415
- } else {
416
- const contentText = await this._serializeContentAsText(mem.content);
417
- if (!contentText || contentText === '""' || contentText === "[]" || contentText === "{}") {
418
- throw new NebulaClientException("Content is required for document memories");
419
- }
420
- payload = {
421
- collection_id: mem.collection_id,
422
- raw_text: contentText,
423
- metadata: docMetadata,
424
- ingestion_mode: "fast"
425
- };
426
- }
427
- const response = await this._makeRequest("POST", "/v1/memories", payload);
428
- const id = response?.results?.engram_id || response?.results?.id || response?.id || "";
429
- return String(id || "");
430
- }
431
- /**
432
- * Internal method to append content to an existing memory
433
- *
434
- * @throws NebulaNotFoundException if memory_id doesn't exist
435
- */
436
- async _appendToMemory(memoryId, memory) {
437
- const collectionId = memory.collection_id;
438
- const content = memory.content;
439
- const metadata = memory.metadata;
440
- if (!collectionId) {
441
- throw new NebulaClientException("collection_id is required");
442
- }
443
- const payload = {
444
- collection_id: collectionId
445
- };
446
- if (Array.isArray(content)) {
447
- if (content.length > 0 && typeof content[0] === "object" && "content" in content[0]) {
448
- payload.messages = content;
449
- } else {
450
- payload.chunks = content;
451
- }
452
- } else if (typeof content === "string") {
453
- payload.raw_text = content;
454
- } else {
455
- throw new NebulaClientException(
456
- "content must be a string, array of strings, or array of message objects"
457
- );
458
- }
459
- if (metadata) {
460
- payload.metadata = metadata;
461
- }
462
- try {
463
- await this._makeRequest("POST", `/v1/memories/${memoryId}/append`, payload);
464
- return memoryId;
465
- } catch (error) {
466
- if (error instanceof NebulaException && error.statusCode === 404) {
467
- throw new NebulaNotFoundException(memoryId, "Memory");
468
- }
469
- throw error;
470
- }
471
- }
472
- /** Store multiple memories using the unified engrams API.
473
- * @param memories - List of Memory objects to store.
474
- * @param metadata - Optional memory-level metadata for conversation groups.
475
- * Each Memory's own metadata is used as per-message metadata.
476
- */
477
- async storeMemories(memories, metadata) {
478
- const results = [];
479
- const convGroups = {};
480
- const others = [];
481
- for (const m of memories) {
482
- if (m.role) {
483
- const key = m.memory_id || `__new__::${m.collection_id}`;
484
- if (!convGroups[key]) convGroups[key] = [];
485
- convGroups[key].push(m);
486
- } else {
487
- others.push(m);
488
- }
489
- }
490
- for (const [key, group] of Object.entries(convGroups)) {
491
- const collectionId = group[0].collection_id;
492
- let convId;
493
- const messages = [];
494
- for (const m of group) {
495
- const multimodalParts = await this._serializeContentAsParts(m.content);
496
- const msgContent = multimodalParts ?? await this._serializeContentAsText(m.content);
497
- if (typeof msgContent === "string") {
498
- if (!msgContent.trim()) continue;
499
- } else if (msgContent.length === 0) {
500
- continue;
501
- }
502
- const mRecord = m;
503
- messages.push({
504
- content: msgContent,
505
- role: m.role,
506
- metadata: m.metadata || {},
507
- ...typeof mRecord.authority === "number" ? { authority: Number(mRecord.authority) } : {}
508
- });
509
- }
510
- if (!messages.length) {
511
- throw new NebulaClientException(
512
- "Cannot create/append conversation without messages. Provide non-empty content."
513
- );
514
- }
515
- if (key.startsWith("__new__::")) {
516
- const data = {
517
- collection_id: collectionId,
518
- name: "Conversation",
519
- messages,
520
- metadata: metadata ?? {}
521
- };
522
- const response = await this._makeRequest("POST", "/v1/memories", data);
523
- if (response.results) {
524
- convId = response.results.memory_id || response.results.id || "";
525
- if (!convId) {
526
- throw new NebulaClientException("Failed to create conversation: no id returned");
527
- }
528
- } else {
529
- throw new NebulaClientException("Failed to create conversation: invalid response format");
530
- }
531
- } else {
532
- convId = key;
533
- const appendMem = {
534
- collection_id: collectionId,
535
- content: messages,
536
- memory_id: convId,
537
- metadata: metadata ?? {}
538
- };
539
- await this._appendToMemory(convId, appendMem);
540
- }
541
- results.push(...Array(group.length).fill(String(convId)));
542
- }
543
- for (const m of others) {
544
- results.push(await this.storeMemory(m));
545
- }
546
- return results;
547
- }
548
- /** Delete one or more memories */
549
- async delete(memoryIds) {
550
- try {
551
- console.log("[SDK] delete() called with:", { memoryIds, type: typeof memoryIds, isArray: Array.isArray(memoryIds) });
552
- if (typeof memoryIds === "string") {
553
- console.log("[SDK] Single deletion path for ID:", memoryIds);
554
- try {
555
- await this._makeRequest("DELETE", `/v1/memories/${memoryIds}`);
556
- return true;
557
- } catch {
558
- console.log("[SDK] Falling back to POST /v1/memories/delete with single ID");
559
- const response = await this._makeRequest("POST", "/v1/memories/delete", memoryIds);
560
- return typeof response === "object" && response.success !== void 0 ? response.success : true;
561
- }
562
- } else {
563
- console.log("[SDK] Batch deletion path for IDs:", memoryIds);
564
- console.log("[SDK] Sending POST request with body:", memoryIds);
565
- const response = await this._makeRequest("POST", "/v1/memories/delete", memoryIds);
566
- console.log("[SDK] Batch deletion response:", response);
567
- return response;
568
- }
569
- } catch (error) {
570
- console.error("[SDK] Delete error:", error);
571
- if (error instanceof Error) {
572
- throw error;
573
- }
574
- throw new NebulaClientException(`Unknown error: ${String(error)}`);
575
- }
576
- }
577
- /** Delete a specific source within a memory */
578
- async deleteSource(sourceId) {
579
- try {
580
- await this._makeRequest("DELETE", `/v1/sources/${sourceId}`);
581
- return true;
582
- } catch (error) {
583
- if (error instanceof NebulaException && error.statusCode === 404) {
584
- throw new NebulaNotFoundException(sourceId, "Source");
585
- }
586
- throw error;
587
- }
588
- }
589
- /** Update a specific source within a memory */
590
- async updateSource(sourceId, content, metadata) {
591
- const payload = { content };
592
- if (metadata !== void 0) {
593
- payload.metadata = metadata;
594
- }
595
- try {
596
- await this._makeRequest("PATCH", `/v1/sources/${sourceId}`, payload);
597
- return true;
598
- } catch (error) {
599
- if (error instanceof NebulaException && error.statusCode === 404) {
600
- throw new NebulaNotFoundException(sourceId, "Source");
601
- }
602
- throw error;
603
- }
604
- }
605
- /**
606
- * Update memory-level properties including name, metadata, and collection associations.
607
- *
608
- * This method allows updating properties of an entire memory (document or conversation)
609
- * without modifying its content. For updating individual sources within a memory,
610
- * use updateSource(). For updating content, use storeMemory() to append.
611
- *
612
- * @param options - Update configuration
613
- * @param options.memoryId - The ID of the memory to update
614
- * @param options.name - New name for the memory (useful for conversations and documents)
615
- * @param options.metadata - Metadata to set. By default, replaces existing metadata.
616
- * Set mergeMetadata=true to merge with existing metadata instead.
617
- * @param options.collectionIds - New collection associations. Must specify at least one valid collection.
618
- * @param options.mergeMetadata - If true, merges provided metadata with existing metadata.
619
- * If false (default), replaces existing metadata entirely.
620
- *
621
- * @returns Promise resolving to true if successful
622
- *
623
- * @throws NebulaNotFoundException if memory_id doesn't exist
624
- * @throws NebulaValidationException if validation fails (e.g., no fields provided)
625
- * @throws NebulaAuthenticationException if user doesn't have permission to update this memory
626
- */
627
- async updateMemory(options) {
628
- const payload = {};
629
- if (options.name !== void 0) {
630
- payload.name = options.name;
631
- }
632
- if (options.metadata !== void 0) {
633
- payload.metadata = options.metadata;
634
- payload.merge_metadata = options.mergeMetadata ?? false;
635
- }
636
- if (options.collectionIds !== void 0) {
637
- payload.collection_ids = options.collectionIds;
638
- }
639
- if (Object.keys(payload).length === 0) {
640
- throw new NebulaValidationException(
641
- "At least one field (name, metadata, or collectionIds) must be provided to update"
642
- );
643
- }
644
- try {
645
- await this._makeRequest("PATCH", `/v1/memories/${options.memoryId}`, payload);
646
- return true;
647
- } catch (error) {
648
- if (error instanceof NebulaException && error.statusCode === 404) {
649
- throw new NebulaNotFoundException(options.memoryId, "Memory");
650
- }
651
- throw error;
652
- }
653
- }
654
- /**
655
- * Get all memories from specific collections with optional metadata filtering
656
- *
657
- * @param options - Configuration for listing memories
658
- * @param options.collection_ids - One or more collection IDs to retrieve memories from
659
- * @param options.limit - Maximum number of memories to return (default: 100)
660
- * @param options.offset - Number of memories to skip for pagination (default: 0)
661
- * @param options.metadata_filters - Optional metadata filters using MongoDB-like operators.
662
- * Supported operators: $eq, $ne, $in, $nin, $exists, $and, $or
663
- *
664
- * @returns Promise resolving to array of MemoryResponse objects
665
- *
666
- * @example
667
- * // Get all playground memories excluding conversations
668
- * const memories = await client.listMemories({
669
- * collection_ids: ['collection-id'],
670
- * metadata_filters: {
671
- * 'metadata.content_type': { $ne: 'conversation' }
672
- * }
673
- * });
674
- *
675
- * @example
676
- * // Complex filter with multiple conditions
677
- * const memories = await client.listMemories({
678
- * collection_ids: ['collection-id'],
679
- * metadata_filters: {
680
- * $and: [
681
- * { 'metadata.playground': { $eq: true } },
682
- * { 'metadata.session_id': { $exists: true } }
683
- * ]
684
- * }
685
- * });
686
- */
687
- async listMemories(options) {
688
- const ids = Array.isArray(options.collection_ids) ? options.collection_ids : [options.collection_ids];
689
- if (!ids.length) {
690
- throw new NebulaClientException("collection_ids must be provided to list_memories().");
691
- }
692
- const params = {
693
- limit: options.limit ?? 100,
694
- offset: options.offset ?? 0,
695
- collection_ids: ids
696
- };
697
- if (options.metadata_filters) {
698
- params.metadata_filters = JSON.stringify(options.metadata_filters);
699
- }
700
- const response = await this._makeRequest("GET", "/v1/memories", void 0, params);
701
- let documents;
702
- if (typeof response === "object" && response !== null && "results" in response) {
703
- documents = response.results;
704
- } else if (Array.isArray(response)) {
705
- documents = response;
706
- } else {
707
- documents = [response];
708
- }
709
- return documents.map((doc) => this._memoryResponseFromDict(doc, ids));
710
- }
711
- /** Get a specific memory by engram ID */
712
- async getMemory(memoryId) {
713
- const response = await this._makeRequest("GET", `/v1/memories/${memoryId}`);
714
- const content = response.text || response.content;
715
- const chunks = Array.isArray(response.chunks) ? response.chunks : void 0;
716
- const memoryData = {
717
- id: response.id,
718
- content,
719
- chunks,
720
- metadata: response.metadata || {},
721
- collection_ids: response.collection_ids || []
722
- };
723
- return this._memoryResponseFromDict(memoryData, []);
724
- }
725
- // Search Methods
726
- /**
727
- * Search within specific collections with optional metadata filtering.
728
- *
729
- * @param options - Search configuration
730
- * @param options.query - Search query string
731
- * @param options.collection_ids - One or more collection IDs to search within
732
- * @param options.effort - Compute effort budget (auto/low/medium/high). Controls traversal compute, not MemoryResponse size.
733
- * @param options.filters - Optional filters to apply to the search. Supports comprehensive metadata filtering
734
- * with MongoDB-like operators for both vector/chunk search and graph search.
735
- * @param options.searchSettings - Optional search configuration
736
- *
737
- * @returns Promise resolving to array of SearchResult objects containing both vector/chunk and graph search results
738
- *
739
- * @example
740
- * // Basic equality filter
741
- * await client.search({
742
- * query: "machine learning",
743
- * collection_ids: ["research-collection"],
744
- * filters: {
745
- * "metadata.category": { $eq: "research" },
746
- * "metadata.verified": true // Shorthand for $eq
747
- * }
748
- * });
749
- *
750
- * @example
751
- * // Numeric comparisons
752
- * await client.search({
753
- * query: "high priority",
754
- * collection_ids: ["tasks"],
755
- * filters: {
756
- * "metadata.priority": { $gte: 8 },
757
- * "metadata.score": { $lt: 100 }
758
- * }
759
- * });
760
- *
761
- * @example
762
- * // String matching
763
- * await client.search({
764
- * query: "employees",
765
- * collection_ids: ["team"],
766
- * filters: {
767
- * "metadata.email": { $ilike: "%@company.com" } // Case-insensitive
768
- * }
769
- * });
770
- *
771
- * @example
772
- * // Array operations
773
- * await client.search({
774
- * query: "developers",
775
- * collection_ids: ["team"],
776
- * filters: {
777
- * "metadata.skills": { $overlap: ["python", "typescript"] } // Has any
778
- * }
779
- * });
780
- *
781
- * @example
782
- * // Nested paths
783
- * await client.search({
784
- * query: "users",
785
- * collection_ids: ["profiles"],
786
- * filters: {
787
- * "metadata.user.preferences.theme": { $eq: "dark" }
788
- * }
789
- * });
790
- *
791
- * @example
792
- * // Complex logical combinations
793
- * await client.search({
794
- * query: "candidates",
795
- * collection_ids: ["hiring"],
796
- * filters: {
797
- * $and: [
798
- * { "metadata.verified": true },
799
- * { "metadata.level": { $gte: 5 } },
800
- * {
801
- * $or: [
802
- * { "metadata.skills": { $overlap: ["python", "go"] } },
803
- * { "metadata.years_experience": { $gte: 8 } }
804
- * ]
805
- * }
806
- * ]
807
- * }
808
- * });
809
- *
810
- * @remarks
811
- * Supported Operators:
812
- * - Comparison: $eq, $ne, $lt, $lte, $gt, $gte
813
- * - String: $like (case-sensitive), $ilike (case-insensitive)
814
- * - Array: $in, $nin, $overlap, $contains
815
- * - JSONB: $json_contains
816
- * - Logical: $and, $or
817
- *
818
- * For comprehensive filtering documentation, see the Metadata Filtering Guide:
819
- * https://docs.trynebula.ai/guides/metadata-filtering
820
- */
821
- async search(options) {
822
- const data = {
823
- query: options.query
824
- };
825
- if (options.effort) {
826
- data.effort = options.effort;
827
- }
828
- if (options.collection_ids) {
829
- const collectionIds2 = Array.isArray(options.collection_ids) ? options.collection_ids : [options.collection_ids];
830
- const validCollectionIds = collectionIds2.filter((id) => id && id.trim() !== "");
831
- if (validCollectionIds.length) {
832
- data.collection_ids = validCollectionIds;
833
- }
834
- }
835
- if (options.filters) {
836
- data.filters = options.filters;
837
- }
838
- if (options.searchSettings) {
839
- data.search_settings = options.searchSettings;
840
- }
841
- const collectionIds = data.collection_ids;
842
- const extraHeaders = collectionIds && collectionIds.length === 1 ? { "X-Nebula-Collection-Id": collectionIds[0] } : void 0;
843
- const response = await this._makeRequest("POST", "/v1/memories/search", data, void 0, extraHeaders);
844
- const memoryResponseData = response.results;
845
- const memoryResponse = {
846
- query: memoryResponseData.query || options.query,
847
- semantics: memoryResponseData.semantics || memoryResponseData.knowledge || [],
848
- procedures: memoryResponseData.procedures || [],
849
- episodes: memoryResponseData.episodes || [],
850
- sources: memoryResponseData.sources || [],
851
- total_traversal_time_ms: memoryResponseData.total_traversal_time_ms,
852
- token_count: memoryResponseData.token_count,
853
- entities: memoryResponseData.entities || []
854
- };
855
- return memoryResponse;
856
- }
857
- // Connector Methods
858
- /** List available connector providers */
859
- async listProviders() {
860
- const response = await this._makeRequest("GET", "/v1/connectors/providers");
861
- return this._unwrapResultsArray(response);
862
- }
863
- /** Start an OAuth connection flow */
864
- async connectProvider(provider, collectionId, config) {
865
- const body = { collection_id: collectionId };
866
- if (config !== void 0) body.config = config;
867
- const response = await this._makeRequest("POST", `/v1/connectors/${provider}/connect`, body);
868
- return this._unwrapResults(response);
869
- }
870
- /** List active connections for a collection */
871
- async listConnections(collectionId) {
872
- const response = await this._makeRequest("GET", "/v1/connectors", void 0, { collection_id: collectionId });
873
- return this._unwrapResultsArray(response);
874
- }
875
- /** Browse Google Drive folders for a connection */
876
- async listFolders(connectionId, parentId) {
877
- const params = {};
878
- if (parentId !== void 0) params.parent_id = parentId;
879
- const response = await this._makeRequest("GET", `/v1/connectors/${connectionId}/folders`, void 0, Object.keys(params).length ? params : void 0);
880
- return this._unwrapResultsArray(response);
881
- }
882
- /** List Slack channels for a connection */
883
- async listChannels(connectionId) {
884
- const response = await this._makeRequest("GET", `/v1/connectors/${connectionId}/channels`);
885
- return this._unwrapResultsArray(response);
886
- }
887
- /** Get a single connection by ID */
888
- async getConnection(connectionId) {
889
- const response = await this._makeRequest("GET", `/v1/connectors/${connectionId}`);
890
- return this._unwrapResults(response);
891
- }
892
- /** Manually trigger a sync for a connection */
893
- async triggerSync(connectionId) {
894
- const response = await this._makeRequest("POST", `/v1/connectors/${connectionId}/sync`);
895
- return this._unwrapResults(response);
896
- }
897
- /** Update connection config (e.g., folder/channel selection) */
898
- async updateConnectionConfig(connectionId, config, apply = "full_resync") {
899
- const response = await this._makeRequest("PATCH", `/v1/connectors/${connectionId}/config`, { config, apply });
900
- return this._unwrapResults(response);
901
- }
902
- /** Disconnect an external data source */
903
- async disconnect(connectionId, deleteMemories = false) {
904
- const params = {};
905
- if (deleteMemories) params.delete_memories = "true";
906
- const response = await this._makeRequest("DELETE", `/v1/connectors/${connectionId}`, void 0, Object.keys(params).length ? params : void 0);
907
- return this._unwrapResults(response);
908
- }
909
- // Health Check
910
- async healthCheck() {
911
- return this._makeRequest("GET", "/v1/health");
912
- }
913
- // Helpers
914
- _collectionFromDict(data) {
915
- let createdAt;
916
- if (data.created_at) {
917
- if (typeof data.created_at === "string") {
918
- createdAt = data.created_at;
919
- } else if (data.created_at instanceof Date) {
920
- createdAt = data.created_at.toISOString();
921
- }
922
- }
923
- let updatedAt;
924
- if (data.updated_at) {
925
- if (typeof data.updated_at === "string") {
926
- updatedAt = data.updated_at;
927
- } else if (data.updated_at instanceof Date) {
928
- updatedAt = data.updated_at.toISOString();
929
- }
930
- }
931
- const collectionId = String(data.id || "");
932
- const collectionName = String(data.name || "");
933
- const collectionDescription = typeof data.description === "string" ? data.description : void 0;
934
- const collectionOwnerId = data.owner_id ? String(data.owner_id) : void 0;
935
- const memoryCount = typeof data.memory_count === "number" ? data.memory_count : 0;
936
- const metadata = {
937
- graph_collection_status: String(data.graph_collection_status || ""),
938
- graph_sync_status: String(data.graph_sync_status || ""),
939
- user_count: typeof data.user_count === "number" ? data.user_count : 0
940
- };
941
- return {
942
- id: collectionId,
943
- name: collectionName,
944
- description: collectionDescription,
945
- metadata,
946
- created_at: createdAt,
947
- updated_at: updatedAt,
948
- memory_count: memoryCount,
949
- owner_id: collectionOwnerId
950
- };
951
- }
952
- _memoryResponseFromDict(data, collectionIds) {
953
- let createdAt;
954
- if (data.created_at) {
955
- if (typeof data.created_at === "string") {
956
- createdAt = data.created_at;
957
- } else if (data.created_at instanceof Date) {
958
- createdAt = data.created_at.toISOString();
959
- }
960
- }
961
- let updatedAt;
962
- if (data.updated_at) {
963
- if (typeof data.updated_at === "string") {
964
- updatedAt = data.updated_at;
965
- } else if (data.updated_at instanceof Date) {
966
- updatedAt = data.updated_at.toISOString();
967
- }
968
- }
969
- const engramId = String(data.id || "");
970
- const content = typeof data.content === "string" ? data.content : typeof data.text === "string" ? data.text : void 0;
971
- let chunks;
972
- if (data.chunks && Array.isArray(data.chunks)) {
973
- if (data.chunks.every((x) => typeof x === "string")) {
974
- chunks = data.chunks.map((text) => ({
975
- id: "",
976
- content: text,
977
- metadata: {}
978
- }));
979
- } else {
980
- chunks = data.chunks.filter((item) => item && typeof item === "object" && ("text" in item || "content" in item)).map((item) => ({
981
- id: String(item.id || ""),
982
- content: String(item.text || item.content || ""),
983
- metadata: typeof item.metadata === "object" && item.metadata !== null ? item.metadata : {},
984
- role: typeof item.role === "string" ? item.role : void 0
985
- }));
986
- }
987
- }
988
- const metadata = { ...typeof data.metadata === "object" && data.metadata !== null ? data.metadata : {} };
989
- if (data.engram_id) {
990
- metadata.engram_id = data.engram_id;
991
- }
992
- let finalId = engramId;
993
- if (data.engram_id && !engramId) {
994
- finalId = String(data.engram_id);
995
- }
996
- if (data.document_metadata && typeof data.document_metadata === "object") {
997
- Object.assign(metadata, data.document_metadata);
998
- }
999
- return {
1000
- id: finalId,
1001
- memory_id: finalId,
1002
- content,
1003
- chunks,
1004
- metadata,
1005
- collection_ids: Array.isArray(data.collection_ids) ? data.collection_ids : collectionIds,
1006
- created_at: createdAt,
1007
- updated_at: updatedAt
1008
- };
1009
- }
1010
- _searchResultFromDict(data) {
1011
- const content = typeof data.content === "string" ? data.content : typeof data.text === "string" ? data.text : "";
1012
- const resultId = String(data.id || data.chunk_id || "");
1013
- return {
1014
- id: String(resultId),
1015
- content: String(content),
1016
- score: typeof data.score === "number" ? data.score : Number(data.score || 0),
1017
- metadata: typeof data.metadata === "object" && data.metadata !== null ? data.metadata : {},
1018
- source: typeof data.source === "string" ? data.source : void 0
1019
- };
1020
- }
1021
- _searchResultFromGraphDict(data) {
1022
- const rid = data.id ? String(data.id) : "";
1023
- const resultTypeStr = typeof data.result_type === "string" ? data.result_type : "entity";
1024
- const rtype = GraphSearchResultType[resultTypeStr.toUpperCase()] || "entity" /* ENTITY */;
1025
- const content = typeof data.content === "object" && data.content !== null ? data.content : {};
1026
- const score = data.score !== void 0 ? Number(data.score) : 0;
1027
- const metadata = typeof data.metadata === "object" && data.metadata !== null ? data.metadata : {};
1028
- const chunkIds = Array.isArray(data.chunk_ids) ? data.chunk_ids : void 0;
1029
- let timestamp;
1030
- if (data.timestamp) {
1031
- if (typeof data.timestamp === "string") {
1032
- timestamp = data.timestamp;
1033
- } else if (data.timestamp instanceof Date) {
1034
- timestamp = data.timestamp.toISOString();
1035
- } else {
1036
- const parsed = new Date(String(data.timestamp));
1037
- if (!Number.isNaN(parsed.valueOf())) {
1038
- timestamp = parsed.toISOString();
1039
- }
1040
- }
1041
- }
1042
- const displayName = typeof data.display_name === "string" ? data.display_name : void 0;
1043
- const sourceRole = typeof data.source_role === "string" ? data.source_role : void 0;
1044
- const engramId = data.engram_id ? String(data.engram_id) : void 0;
1045
- const ownerId = data.owner_id ? String(data.owner_id) : void 0;
1046
- let entity;
1047
- let rel;
1048
- let comm;
1049
- if (rtype === "entity" /* ENTITY */) {
1050
- entity = {
1051
- id: content.id ? String(content.id) : void 0,
1052
- name: String(content.name || ""),
1053
- description: String(content.description || ""),
1054
- metadata: typeof content.metadata === "object" && content.metadata !== null ? content.metadata : {}
1055
- };
1056
- } else if (rtype === "relationship" /* RELATIONSHIP */) {
1057
- rel = {
1058
- id: content.id ? String(content.id) : void 0,
1059
- subject: String(content.subject || ""),
1060
- predicate: String(content.predicate || ""),
1061
- object: String(content.object || ""),
1062
- subject_id: content.subject_id ? String(content.subject_id) : void 0,
1063
- object_id: content.object_id ? String(content.object_id) : void 0,
1064
- description: typeof content.description === "string" ? content.description : void 0,
1065
- metadata: typeof content.metadata === "object" && content.metadata !== null ? content.metadata : {}
1066
- };
1067
- } else {
1068
- comm = {
1069
- id: content.id ? String(content.id) : void 0,
1070
- name: String(content.name || ""),
1071
- summary: String(content.summary || ""),
1072
- metadata: typeof content.metadata === "object" && content.metadata !== null ? content.metadata : {}
1073
- };
1074
- }
1075
- return {
1076
- id: rid,
1077
- score,
1078
- metadata,
1079
- source: "graph",
1080
- content: void 0,
1081
- graph_result_type: rtype,
1082
- graph_entity: entity,
1083
- graph_relationship: rel,
1084
- graph_community: comm,
1085
- chunk_ids: chunkIds,
1086
- timestamp,
1087
- display_name: displayName,
1088
- source_role: sourceRole,
1089
- engram_id: engramId,
1090
- owner_id: ownerId
1091
- };
1092
- }
1093
- async _sha256(message) {
1094
- const msgBuffer = new TextEncoder().encode(message);
1095
- let crypto;
1096
- if (typeof globalThis.crypto !== "undefined" && globalThis.crypto.subtle) {
1097
- crypto = globalThis.crypto;
1098
- } else {
1099
- const nodeCrypto = await import('crypto');
1100
- crypto = nodeCrypto.webcrypto;
1101
- }
1102
- const hashBuffer = await crypto.subtle.digest("SHA-256", msgBuffer);
1103
- const hashArray = Array.from(new Uint8Array(hashBuffer));
1104
- const hashHex = hashArray.map((b) => b.toString(16).padStart(2, "0")).join("");
1105
- return hashHex;
1106
- }
1107
- _formDataFromObject(obj) {
1108
- const formData = new FormData();
1109
- Object.entries(obj).forEach(([key, value]) => {
1110
- formData.append(key, value);
1111
- });
1112
- return formData;
1113
- }
1114
- /**
1115
- * Convert and process multimodal content parts, auto-uploading large base64 files to S3.
1116
- *
1117
- * - Binary parts (`image`/`audio`/`document` with `data`) larger than 5MB are uploaded to S3 and converted to `s3_ref`.
1118
- */
1119
- async _processContentParts(contentParts) {
1120
- const processed = [];
1121
- for (const part of contentParts) {
1122
- if (part.type !== "text" && part.type !== "s3_ref" && "data" in part && part.data) {
1123
- const filePart = part;
1124
- const dataSize = Math.floor(String(filePart.data).length * 3 / 4);
1125
- if (dataSize > _Nebula.MAX_INLINE_SIZE) {
1126
- const filename = filePart.filename || `file.bin`;
1127
- const mediaType = filePart.media_type || "application/octet-stream";
1128
- const uploadInfo = await this.getUploadUrl({
1129
- filename,
1130
- content_type: mediaType,
1131
- file_size: dataSize
1132
- });
1133
- let bytes;
1134
- const atobFn = globalThis.atob;
1135
- if (typeof atobFn === "function") {
1136
- const binaryString = atobFn(String(filePart.data));
1137
- bytes = new Uint8Array(binaryString.length);
1138
- for (let i = 0; i < binaryString.length; i++) {
1139
- bytes[i] = binaryString.charCodeAt(i);
1140
- }
1141
- } else {
1142
- const { Buffer } = await import('buffer');
1143
- bytes = Uint8Array.from(Buffer.from(String(filePart.data), "base64"));
1144
- }
1145
- await fetch(uploadInfo.upload_url, {
1146
- method: "PUT",
1147
- body: bytes,
1148
- headers: { "Content-Type": mediaType }
1149
- });
1150
- processed.push({
1151
- type: "s3_ref",
1152
- s3_key: uploadInfo.s3_key,
1153
- media_type: mediaType,
1154
- filename
1155
- });
1156
- continue;
1157
- }
1158
- }
1159
- processed.push(part);
1160
- }
1161
- return processed;
1162
- }
1163
- /**
1164
- * Get a presigned URL for uploading large files to S3.
1165
- */
1166
- async getUploadUrl(options) {
1167
- const response = await this._makeRequest("POST", "/v1/memories/upload", void 0, {
1168
- filename: options.filename,
1169
- content_type: options.content_type,
1170
- file_size: options.file_size
1171
- });
1172
- if (response.results) {
1173
- return response.results;
1174
- }
1175
- return response;
1176
- }
1177
- };
1178
- // Files larger than 5MB are automatically uploaded to S3
1179
- _Nebula.MAX_INLINE_SIZE = 5 * 1024 * 1024;
1180
- var Nebula = _Nebula;
1181
-
1182
- // src/content.ts
1183
- var MIME_TYPES = {
1184
- // Images
1185
- ".jpg": "image/jpeg",
1186
- ".jpeg": "image/jpeg",
1187
- ".png": "image/png",
1188
- ".gif": "image/gif",
1189
- ".webp": "image/webp",
1190
- ".heic": "image/heic",
1191
- ".bmp": "image/bmp",
1192
- ".tiff": "image/tiff",
1193
- // Audio
1194
- ".mp3": "audio/mpeg",
1195
- ".wav": "audio/wav",
1196
- ".m4a": "audio/m4a",
1197
- ".ogg": "audio/ogg",
1198
- ".flac": "audio/flac",
1199
- ".aac": "audio/aac",
1200
- ".webm": "audio/webm",
1201
- // Documents
1202
- ".pdf": "application/pdf",
1203
- ".doc": "application/msword",
1204
- ".docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
1205
- ".xls": "application/vnd.ms-excel",
1206
- ".xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
1207
- ".ppt": "application/vnd.ms-powerpoint",
1208
- ".pptx": "application/vnd.openxmlformats-officedocument.presentationml.presentation",
1209
- ".txt": "text/plain",
1210
- ".csv": "text/csv",
1211
- ".rtf": "application/rtf",
1212
- ".epub": "application/epub+zip"
1213
- };
1214
- var NebulaContent = class {
1215
- /**
1216
- * Create a FileContentPart from a file path.
1217
- * Automatically deduces media_type and the backend 'type' (image, audio, document).
1218
- */
1219
- static async fromFile(filePath, mediaType) {
1220
- let fs;
1221
- let path;
1222
- try {
1223
- fs = await import('fs/promises');
1224
- path = await import('path');
1225
- } catch (e) {
1226
- throw new Error("File system operations are only supported in Node.js environments.");
1227
- }
1228
- const absolutePath = path.resolve(filePath);
1229
- const fileName = path.basename(absolutePath);
1230
- const ext = path.extname(absolutePath).toLowerCase();
1231
- const detectedMime = mediaType || MIME_TYPES[ext] || "application/octet-stream";
1232
- const buffer = await fs.readFile(absolutePath);
1233
- const data = buffer.toString("base64");
1234
- return {
1235
- data,
1236
- media_type: detectedMime,
1237
- filename: fileName
1238
- };
1239
- }
1240
- };
1241
-
1242
- // src/index.ts
1243
- var MemoryBase = (data) => data;
1244
- var Memory2 = Object.assign(MemoryBase, {
1245
- /**
1246
- * Helper to create a file content part from a file path.
1247
- * Alias for NebulaContent.fromFile().
1248
- */
1249
- File: NebulaContent.fromFile,
1250
- /**
1251
- * Helper to create a complete Memory object from a single file.
1252
- */
1253
- async fromFile(filePath, collection_id, metadata, role) {
1254
- const path = await import('path');
1255
- const filename = path.basename(filePath);
1256
- return {
1257
- collection_id,
1258
- content: [await NebulaContent.fromFile(filePath)],
1259
- metadata: { filename, ...metadata },
1260
- role
1261
- };
1262
- }
1263
- });
1264
-
1265
- export { GraphSearchResultType, Memory2 as Memory, Nebula, NebulaAuthenticationException, NebulaClientException, NebulaCollectionNotFoundException, NebulaContent, NebulaException, NebulaNotFoundException, NebulaRateLimitException, NebulaValidationException, Nebula as default };
1266
- //# sourceMappingURL=index.mjs.map
1267
- //# sourceMappingURL=index.mjs.map