@redocly/replay 0.28.0-next.9 → 0.28.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 (61) hide show
  1. package/dist/{replay-AiChatProvider-B_f9Wn8a.js → replay-AiChatProvider-BRqjyy2W.js} +2 -2
  2. package/dist/{replay-AiChatProvider-DuTK5g1N.js → replay-AiChatProvider-DUVoLgY2.js} +138 -140
  3. package/dist/{replay-AiChatSqliteDBStorage-cXsRIQfJ.js → replay-AiChatSqliteDBStorage-0evx56pl.js} +1 -1
  4. package/dist/{replay-AiChatSqliteDBStorage-CHfMo6M6.js → replay-AiChatSqliteDBStorage-C5AnRloD.js} +1 -1
  5. package/dist/{replay-AiPanel-CGbGwIMX.js → replay-AiPanel-CMjVD12K.js} +50 -50
  6. package/dist/{replay-AiPanel-C_C52r20.js → replay-AiPanel-PVgJioX3.js} +2 -2
  7. package/dist/replay-FileWatcher-CFYprlWN.js +364 -0
  8. package/dist/replay-FileWatcher-DGLwO5Kd.js +1 -0
  9. package/dist/{replay-SemanticSearchService-BLF1oOOu.js → replay-SemanticSearchService-Bh5xYa91.js} +15 -15
  10. package/dist/{replay-SemanticSearchService-DTc0oxN4.js → replay-SemanticSearchService-CulKCCNl.js} +1 -1
  11. package/dist/{replay-SqliteDBStorage-DF9kKplR.js → replay-SqliteDBStorage-Bz0muHEk.js} +1 -1
  12. package/dist/{replay-SqliteDBStorage-B_kyJ0a3.js → replay-SqliteDBStorage-CVHRAsPD.js} +1 -1
  13. package/dist/replay-TauriFileSystemAdapter-B163-f2D.js +108 -0
  14. package/dist/replay-TauriFileSystemAdapter-D4bOmvzP.js +1 -0
  15. package/dist/{replay-TauriRootStorage-Den8gI4S.js → replay-TauriRootStorage-2MPQE-3f.js} +192 -188
  16. package/dist/replay-TauriRootStorage-CjWUrnWz.js +1 -0
  17. package/dist/{replay-agent-loop-B8Mjb8DU.js → replay-agent-loop-BgYyBo9e.js} +3 -3
  18. package/dist/{replay-agent-loop-Z_nrrmg_.js → replay-agent-loop-DYDFXAZj.js} +1 -1
  19. package/dist/{replay-ai-chat-mappers-D7e8buTk.js → replay-ai-chat-mappers-BEwNRQPV.js} +1 -1
  20. package/dist/{replay-ai-chat-mappers-aJ_VMb6Z.js → replay-ai-chat-mappers-CMtNqQHX.js} +1 -1
  21. package/dist/{replay-create-model-Bw20x80b.js → replay-create-model-B2ZsGTjs.js} +3 -3
  22. package/dist/{replay-create-model-Be3vPVDb.js → replay-create-model-DPxfOEfv.js} +4 -4
  23. package/dist/{replay-db-BQXljNM0.js → replay-db-C9iqyMet.js} +1 -1
  24. package/dist/{replay-db-BmZNrdZM.js → replay-db-D4-LmLRk.js} +1 -1
  25. package/dist/{replay-external-resolver-BQvSDNfH.js → replay-external-resolver-BXgVrfzk.js} +2 -2
  26. package/dist/{replay-external-resolver-BLzbbtnT.js → replay-external-resolver-CTUbNZGW.js} +1 -1
  27. package/dist/{replay-index-BCz452N6.js → replay-index-4TEahAPK.js} +21604 -21055
  28. package/dist/{replay-index-C0kvTxxm.js → replay-index-B4U7iZuq.js} +41 -41
  29. package/dist/{replay-index-DAIwC3ls.js → replay-index-B8O3wYqo.js} +1 -1
  30. package/dist/{replay-index-C7y4K4Cr.js → replay-index-Bdg7noSD.js} +1 -1
  31. package/dist/replay-index-CG9VN2JQ.js +4 -0
  32. package/dist/{replay-index-B-uZhXHj.js → replay-index-DcC173cC.js} +1 -1
  33. package/dist/{replay-index-DYtXcqDk.js → replay-index-Nz5obVS5.js} +1131 -1131
  34. package/dist/{replay-index-wBHsAQEV.js → replay-index-q63USe25.js} +1 -1
  35. package/dist/{replay-lint-BzkTeXqI.js → replay-lint-4XFKTmSY.js} +97 -97
  36. package/dist/{replay-lint-graphql-BZF2eLiZ.js → replay-lint-graphql-BsBWkZ6L.js} +1 -1
  37. package/dist/{replay-lint-graphql-BDBGJSir.js → replay-lint-graphql-De2eDZnT.js} +1 -1
  38. package/dist/{replay-lint-CqDMOMQt.js → replay-lint-s7ylMBWz.js} +6100 -6063
  39. package/dist/{replay-periodic-revalidation-C7SkB1vs.js → replay-periodic-revalidation-BMFP7f-u.js} +1 -1
  40. package/dist/{replay-periodic-revalidation-orCv_JoF.js → replay-periodic-revalidation-DJbblUef.js} +1 -1
  41. package/dist/{replay-resolve-DZMWoig2.js → replay-resolve-BtNxNrKo.js} +1 -1
  42. package/dist/{replay-resolve-0e5f8I7b.js → replay-resolve-BueEsOnR.js} +1 -1
  43. package/dist/{replay-respect-run-ChP63WzG.js → replay-respect-run-B_dJjlti.js} +1 -1
  44. package/dist/{replay-respect-run-CLW3wGhx.js → replay-respect-run-Dfpbcsns.js} +3 -3
  45. package/dist/{replay-tauri-path-DBt1dqkG.js → replay-tauri-path-Bht3XIt7.js} +1 -1
  46. package/dist/{replay-tauri-path-DvLF4Z8f.js → replay-tauri-path-CiuYXh_j.js} +2 -2
  47. package/dist/replay-useAiChatQueries-02CRdEPJ.js +215 -0
  48. package/dist/{replay-useAiChatQueries-S6v5duiJ.js → replay-useAiChatQueries-D2hh5omV.js} +994 -945
  49. package/dist/{replay-validate-key-CNl7BV_v.js → replay-validate-key-ALwOF1Ux.js} +1 -1
  50. package/dist/{replay-validate-key-CMJODIH6.js → replay-validate-key-B7fbWbfv.js} +2 -2
  51. package/dist/replay.cjs +1 -1
  52. package/dist/replay.d.ts +5 -0
  53. package/dist/replay.js +8 -8
  54. package/package.json +5 -5
  55. package/dist/replay-FileWatcher-DEOB0_DG.js +0 -1
  56. package/dist/replay-FileWatcher-Z6eygcBI.js +0 -359
  57. package/dist/replay-TauriFileSystemAdapter-CwSMakdJ.js +0 -1
  58. package/dist/replay-TauriFileSystemAdapter-DcFBYSUW.js +0 -99
  59. package/dist/replay-TauriRootStorage-DEGEIJrz.js +0 -1
  60. package/dist/replay-index-gM6vL6iT.js +0 -4
  61. package/dist/replay-useAiChatQueries-Bypgnkwa.js +0 -215
@@ -0,0 +1,364 @@
1
+ import { i as f, t as w, P as m, q as v, u as C, D as F } from "./replay-index-4TEahAPK.js";
2
+ import { g } from "./replay-SemanticSearchService-Bh5xYa91.js";
3
+ var E;
4
+ (function(l) {
5
+ l.WINDOW_RESIZED = "tauri://resize", l.WINDOW_MOVED = "tauri://move", l.WINDOW_CLOSE_REQUESTED = "tauri://close-requested", l.WINDOW_DESTROYED = "tauri://destroyed", l.WINDOW_FOCUS = "tauri://focus", l.WINDOW_BLUR = "tauri://blur", l.WINDOW_SCALE_FACTOR_CHANGED = "tauri://scale-change", l.WINDOW_THEME_CHANGED = "tauri://theme-changed", l.WINDOW_CREATED = "tauri://window-created", l.WEBVIEW_CREATED = "tauri://webview-created", l.DRAG_ENTER = "tauri://drag-enter", l.DRAG_OVER = "tauri://drag-over", l.DRAG_DROP = "tauri://drag-drop", l.DRAG_LEAVE = "tauri://drag-leave";
6
+ })(E || (E = {}));
7
+ async function _(l, e) {
8
+ await f("plugin:event|unlisten", {
9
+ event: l,
10
+ eventId: e
11
+ });
12
+ }
13
+ async function A(l, e, i) {
14
+ var s;
15
+ const n = (s = void 0) !== null && s !== void 0 ? s : { kind: "Any" };
16
+ return f("plugin:event|listen", {
17
+ event: l,
18
+ target: n,
19
+ handler: w(e)
20
+ }).then((t) => async () => _(l, t));
21
+ }
22
+ class P {
23
+ constructor(e, i, s, n, t, o) {
24
+ this.storage = e, this.projectDir = i, this.aiEnabled = s, this.environments = n, this.apis = t, this.collections = o;
25
+ }
26
+ storage;
27
+ projectDir;
28
+ aiEnabled;
29
+ environments;
30
+ apis;
31
+ collections;
32
+ watchPath = null;
33
+ unlistenEvent = null;
34
+ pendingEnvironmentsReload = Promise.resolve();
35
+ get tauriStorage() {
36
+ return this.storage;
37
+ }
38
+ indexApis(e) {
39
+ !this.aiEnabled || e.length === 0 || g().indexApis(e).catch((i) => console.error("Semantic index (apis):", i));
40
+ }
41
+ indexCollections(e) {
42
+ !this.aiEnabled || e.length === 0 || g().indexCollections(e).catch((i) => console.error("Semantic index (collections):", i));
43
+ }
44
+ removeApis(e) {
45
+ if (!this.aiEnabled || e.length === 0) return;
46
+ const i = g();
47
+ Promise.all(e.map((s) => i.removeApi(s))).catch(
48
+ (s) => console.error("Semantic remove (apis):", s)
49
+ );
50
+ }
51
+ removeCollections(e) {
52
+ if (!this.aiEnabled || e.length === 0) return;
53
+ const i = g();
54
+ Promise.all(e.map((s) => i.removeCollection(s))).catch(
55
+ (s) => console.error("Semantic remove (collections):", s)
56
+ );
57
+ }
58
+ /**
59
+ * Starts watching the directory for changes.
60
+ */
61
+ async start() {
62
+ if (this.watchPath) {
63
+ console.warn("Watcher already started for:", this.watchPath);
64
+ return;
65
+ }
66
+ try {
67
+ this.unlistenEvent = await A("fs-watch-event", async (e) => {
68
+ const i = e.payload;
69
+ try {
70
+ await this.handleEvent(i);
71
+ } catch (s) {
72
+ console.error("Error handling file change:", s);
73
+ }
74
+ }), await f("fs_watch", {
75
+ path: this.projectDir,
76
+ options: {
77
+ recursive: !0,
78
+ delayMs: 500
79
+ }
80
+ }), this.watchPath = this.projectDir;
81
+ } catch (e) {
82
+ throw console.error("Failed to start file watcher:", e), this.unlistenEvent && (this.unlistenEvent(), this.unlistenEvent = null), e;
83
+ }
84
+ }
85
+ /**
86
+ * Stops watching and cleans up resources.
87
+ */
88
+ async stop() {
89
+ if (this.watchPath)
90
+ try {
91
+ await f("fs_unwatch", { path: this.watchPath });
92
+ } catch (e) {
93
+ console.error("Error stopping file watcher:", e);
94
+ } finally {
95
+ this.unlistenEvent && (this.unlistenEvent(), this.unlistenEvent = null), this.watchPath = null;
96
+ }
97
+ }
98
+ /**
99
+ * Main event handler - dispatches to specific handlers based on event type.
100
+ */
101
+ async handleEvent(e) {
102
+ const { changeType: i, paths: s, pathTypes: n, type: t } = e;
103
+ if (await this.isProjectFolderRemoved(s, i)) {
104
+ await this.handleProjectFolderRemoval();
105
+ return;
106
+ }
107
+ const o = this.filterSpecFiles(s, n);
108
+ if (o.paths.length === 0)
109
+ return;
110
+ const a = await this.toFileEntries(o.paths, o.pathTypes);
111
+ switch (i) {
112
+ case "changed":
113
+ (t.includes("Data") || t.includes("Name")) && await this.handleModify(a);
114
+ break;
115
+ case "added":
116
+ await this.handleCreate(a);
117
+ break;
118
+ case "deleted":
119
+ await this.handleDelete(a);
120
+ break;
121
+ case "renamed":
122
+ await this.handleRename(a);
123
+ break;
124
+ default:
125
+ console.log("Unhandled change type:", i);
126
+ }
127
+ }
128
+ /**
129
+ * Filter paths to only include yaml/json files.
130
+ * Returns filtered paths and their corresponding pathTypes.
131
+ */
132
+ filterSpecFiles(e, i) {
133
+ const s = [], n = [];
134
+ for (let t = 0; t < e.length; t++) {
135
+ const o = e[t], a = o.split(".").pop()?.toLowerCase();
136
+ a && ["yaml", "yml", "json"].includes(a) && (s.push(o), n.push(i[t] || "unknown"));
137
+ }
138
+ return { paths: s, pathTypes: n };
139
+ }
140
+ /**
141
+ * Convert absolute paths to file entry format with relative paths and types.
142
+ */
143
+ async toFileEntries(e, i) {
144
+ return Promise.all(
145
+ e.map(async (s, n) => ({
146
+ relative_path: await m.relative(this.projectDir, s),
147
+ absolute_path: s,
148
+ type: i[n] || "unknown"
149
+ }))
150
+ );
151
+ }
152
+ hasExternalConfigChange(e) {
153
+ return e.some(
154
+ (i) => v(i.relative_path) && !this.storage.isWatchExcluded(i.relative_path)
155
+ );
156
+ }
157
+ withoutConfigFile(e) {
158
+ return e.filter((i) => !v(i.relative_path));
159
+ }
160
+ consolidateFileEntries(e) {
161
+ const i = [], s = /* @__PURE__ */ new Set();
162
+ for (const n of e)
163
+ s.has(n.relative_path) || (s.add(n.relative_path), this.storage.isWatchExcluded(n.relative_path) || i.push(n));
164
+ return i;
165
+ }
166
+ /**
167
+ * Handles file content modification events.
168
+ * If file doesn't exist in state yet, treat as creation.
169
+ */
170
+ async handleModify(e) {
171
+ const i = this.hasExternalConfigChange(e), s = this.withoutConfigFile(e), { newApiFiles: n, existingApiFiles: t } = this.categorizeApisFromFiles(s), { newCollectionFiles: o, existingCollectionFiles: a } = this.categorizeCollectionsFromFiles(s), c = await this.findApisToReload(e), r = await this.findCollectionsToReload(e), d = [...n, ...o];
172
+ d.length > 0 && await this.handleCreate(d), i && await this.reloadEnvironments();
173
+ const p = this.consolidateFileEntries([...t, ...c]), u = this.consolidateFileEntries([
174
+ ...a,
175
+ ...r
176
+ ]);
177
+ await this.reloadApis(p), await this.reloadCollections(u);
178
+ }
179
+ /**
180
+ * Handles file creation events.
181
+ * If file already exists in state, update it instead of creating duplicate.
182
+ */
183
+ async handleCreate(e) {
184
+ this.hasExternalConfigChange(e) && await this.reloadEnvironments();
185
+ const i = this.withoutConfigFile(e), s = i.filter((r) => r.type === "api"), n = i.filter((r) => r.type === "collection"), { newApiFiles: t, existingApiFiles: o } = this.categorizeApisFromFiles(s), { newCollectionFiles: a, existingCollectionFiles: c } = this.categorizeCollectionsFromFiles(n);
186
+ if (t.length > 0 || a.length > 0) {
187
+ t.forEach((h) => this.storage.addPersistExcludedId(h.relative_path)), a.forEach((h) => this.storage.addPersistExcludedId(h.relative_path));
188
+ const r = t.length > 0 ? await this.tauriStorage.loadAndParseApis(t, void 0, !0) : [], d = a.length > 0 ? await this.tauriStorage.loadAndParseCollections(a, void 0) : [], p = r.filter((h) => h !== null), u = d.filter((h) => h !== null);
189
+ this.apis.set([...this.apis.get(), ...p]), this.collections.set([...this.collections.get(), ...u]), this.indexApis(p), this.indexCollections(u), setTimeout(() => {
190
+ t.forEach((h) => this.storage.removePersistExcludedId(h.relative_path)), a.forEach(
191
+ (h) => this.storage.removePersistExcludedId(h.relative_path)
192
+ );
193
+ }, 500);
194
+ }
195
+ o.length > 0 && await this.reloadApis(o), c.length > 0 && await this.reloadCollections(c);
196
+ }
197
+ /**
198
+ * Categorize API paths into new vs existing
199
+ */
200
+ /**
201
+ * Categorize API files into new vs existing
202
+ */
203
+ categorizeApisFromFiles(e) {
204
+ const i = /* @__PURE__ */ new Set(), s = [], n = [];
205
+ for (const t of e) {
206
+ if (i.has(t.relative_path))
207
+ continue;
208
+ i.add(t.relative_path), this.apis.get().some((a) => a.id === t.relative_path) ? n.push(t) : t.type === "api" && s.push(t);
209
+ }
210
+ return { newApiFiles: s, existingApiFiles: n };
211
+ }
212
+ /**
213
+ * Categorize collection files into new vs existing
214
+ */
215
+ categorizeCollectionsFromFiles(e) {
216
+ const i = /* @__PURE__ */ new Set(), s = [], n = [];
217
+ for (const t of e) {
218
+ if (i.has(t.relative_path))
219
+ continue;
220
+ i.add(t.relative_path), this.collections.get().some((a) => a.id === t.relative_path) ? n.push(t) : t.type === "collection" && s.push(t);
221
+ }
222
+ return { newCollectionFiles: s, existingCollectionFiles: n };
223
+ }
224
+ /**
225
+ * Handles file deletion events.
226
+ */
227
+ async handleDelete(e) {
228
+ this.hasExternalConfigChange(e) && await this.reloadEnvironments();
229
+ const i = this.withoutConfigFile(e), s = [], n = [];
230
+ for (const t of i) {
231
+ this.storage.addPersistExcludedId(t.relative_path);
232
+ const o = this.apis.get();
233
+ o.some((r) => r.id === t.relative_path) && (this.apis.set(o.filter((r) => r.id !== t.relative_path)), this.tauriStorage.deleteApiFromCache(t.relative_path), s.push(t.relative_path));
234
+ const a = this.collections.get(), c = a.findIndex(
235
+ (r) => r.id === t.relative_path
236
+ );
237
+ c >= 0 && (this.collections.set(a.filter((r, d) => d !== c)), n.push(t.relative_path)), setTimeout(() => {
238
+ this.storage.removePersistExcludedId(t.relative_path);
239
+ }, 500);
240
+ }
241
+ this.removeApis(s), this.removeCollections(n);
242
+ }
243
+ /**
244
+ * Handles file rename/move events.
245
+ * For rename events, files typically contains [oldFile, newFile]
246
+ */
247
+ async handleRename(e) {
248
+ if (e.length >= 2) {
249
+ const [i, s] = e;
250
+ await this.handleDelete([i]), await this.handleCreate([s]);
251
+ } else
252
+ await this.handleCreate(e);
253
+ }
254
+ /**
255
+ * Checks if the project folder itself was renamed/moved/deleted.
256
+ * This happens when:
257
+ * - We get a rename/delete event for the project directory itself
258
+ * - Or when paths no longer match the watched directory structure
259
+ */
260
+ async isProjectFolderRemoved(e, i) {
261
+ if (e.length === 0)
262
+ return !1;
263
+ if (i === "deleted" || i === "renamed") {
264
+ for (const n of e)
265
+ if (n === this.projectDir)
266
+ return !0;
267
+ }
268
+ return e.filter(
269
+ (n) => !n.startsWith(this.projectDir + "/") && n !== this.projectDir
270
+ ).length > 0 && i === "renamed";
271
+ }
272
+ /**
273
+ * Handles the case when the entire project folder is renamed or deleted.
274
+ * Clears all APIs and collections from state.
275
+ */
276
+ async handleProjectFolderRemoval() {
277
+ const e = this.apis.get(), i = e.map((t) => t.id);
278
+ e.forEach((t) => {
279
+ this.storage.addPersistExcludedId(t.id), this.tauriStorage.deleteApiFromCache(t.id);
280
+ }), this.apis.set([]);
281
+ const s = this.collections.get(), n = s.map((t) => t.id);
282
+ s.forEach((t) => {
283
+ this.storage.addPersistExcludedId(t.id);
284
+ }), this.collections.set([]), setTimeout(() => {
285
+ e.forEach((t) => this.storage.removePersistExcludedId(t.id)), s.forEach((t) => this.storage.removePersistExcludedId(t.id));
286
+ }, 500), this.removeApis(i), this.removeCollections(n), await this.stop();
287
+ }
288
+ async findApisToReload(e) {
289
+ const i = [];
290
+ return await Promise.all(
291
+ this.apis.get().map(async (s) => {
292
+ const n = s.fileDependencies ?? /* @__PURE__ */ new Set(), t = s.id, o = e.find((a) => n.has(a.absolute_path));
293
+ if (!this.storage.isWatchExcluded(t) && o) {
294
+ const a = await m.join(this.projectDir, t);
295
+ i.push({
296
+ relative_path: t,
297
+ absolute_path: a,
298
+ type: "api"
299
+ });
300
+ }
301
+ })
302
+ ), i;
303
+ }
304
+ async findCollectionsToReload(e) {
305
+ const i = [];
306
+ return await Promise.all(
307
+ this.collections.get().map(async (s) => {
308
+ const n = s.fileDependencies ?? /* @__PURE__ */ new Set(), t = s.id, o = e.find((a) => n.has(a.absolute_path));
309
+ if (!this.storage.isWatchExcluded(t) && o) {
310
+ const a = await m.join(this.projectDir, t);
311
+ i.push({
312
+ relative_path: t,
313
+ absolute_path: a,
314
+ type: "collection"
315
+ });
316
+ }
317
+ })
318
+ ), i;
319
+ }
320
+ reloadEnvironments() {
321
+ const e = this.pendingEnvironmentsReload.then(() => this.readAndPublishEnvironments());
322
+ return this.pendingEnvironmentsReload = e.catch(() => {
323
+ }), e;
324
+ }
325
+ async readAndPublishEnvironments() {
326
+ const e = this.environments.get(), i = await this.tauriStorage.readEnvironments();
327
+ !(this.environments.get() !== e) && (i.length > 0 || !this.storage.getEnvironmentsConfigError()) && this.environments.set(i.length > 0 ? i : C(F)), this.storage.publishEnvironmentsConfigError();
328
+ }
329
+ async reloadApis(e) {
330
+ if (e.length === 0) return;
331
+ const i = await this.tauriStorage.loadAndParseApis(e, void 0, !0), s = [];
332
+ await Promise.all(
333
+ i.map(async (n, t) => {
334
+ if (!n) {
335
+ await this.handleDelete([e[t]]);
336
+ return;
337
+ }
338
+ const o = this.apis.get();
339
+ o.some((a) => a.id === n.id) ? (this.storage.addPersistExcludedId(n.id), this.apis.set(o.map((a) => a.id === n.id ? n : a)), s.push(n), setTimeout(() => this.storage.removePersistExcludedId(n.id), 500)) : console.warn("API not found in state after reload:", n.id);
340
+ })
341
+ ), s.length > 0 && this.indexApis(s);
342
+ }
343
+ async reloadCollections(e) {
344
+ if (e.length === 0) return;
345
+ const i = await this.tauriStorage.loadAndParseCollections(e, void 0), s = [];
346
+ await Promise.all(
347
+ i.map(async (n, t) => {
348
+ if (!n) {
349
+ await this.handleDelete([e[t]]);
350
+ return;
351
+ }
352
+ const o = this.collections.get(), a = o.findIndex((c) => c.id === n.id);
353
+ a >= 0 ? (this.storage.addPersistExcludedId(n.id), this.collections.set(
354
+ o.map(
355
+ (c, r) => r === a ? n : c
356
+ )
357
+ ), s.push(n), setTimeout(() => this.storage.removePersistExcludedId(n.id), 500)) : console.warn("Collection not found in state after reload:", n.id);
358
+ })
359
+ ), s.length > 0 && this.indexCollections(s);
360
+ }
361
+ }
362
+ export {
363
+ P as FileWatcher
364
+ };
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const h=require("./replay-index-Nz5obVS5.js"),f=require("./replay-SemanticSearchService-CulKCCNl.js");var v;(function(l){l.WINDOW_RESIZED="tauri://resize",l.WINDOW_MOVED="tauri://move",l.WINDOW_CLOSE_REQUESTED="tauri://close-requested",l.WINDOW_DESTROYED="tauri://destroyed",l.WINDOW_FOCUS="tauri://focus",l.WINDOW_BLUR="tauri://blur",l.WINDOW_SCALE_FACTOR_CHANGED="tauri://scale-change",l.WINDOW_THEME_CHANGED="tauri://theme-changed",l.WINDOW_CREATED="tauri://window-created",l.WEBVIEW_CREATED="tauri://webview-created",l.DRAG_ENTER="tauri://drag-enter",l.DRAG_OVER="tauri://drag-over",l.DRAG_DROP="tauri://drag-drop",l.DRAG_LEAVE="tauri://drag-leave"})(v||(v={}));async function m(l,e){await h.invoke("plugin:event|unlisten",{event:l,eventId:e})}async function E(l,e,i){var s;const n=(s=void 0)!==null&&s!==void 0?s:{kind:"Any"};return h.invoke("plugin:event|listen",{event:l,target:n,handler:h.transformCallback(e)}).then(t=>async()=>m(l,t))}class w{constructor(e,i,s,n,t,o){this.storage=e,this.projectDir=i,this.aiEnabled=s,this.environments=n,this.apis=t,this.collections=o}storage;projectDir;aiEnabled;environments;apis;collections;watchPath=null;unlistenEvent=null;pendingEnvironmentsReload=Promise.resolve();get tauriStorage(){return this.storage}indexApis(e){!this.aiEnabled||e.length===0||f.getSemanticSearchService().indexApis(e).catch(i=>console.error("Semantic index (apis):",i))}indexCollections(e){!this.aiEnabled||e.length===0||f.getSemanticSearchService().indexCollections(e).catch(i=>console.error("Semantic index (collections):",i))}removeApis(e){if(!this.aiEnabled||e.length===0)return;const i=f.getSemanticSearchService();Promise.all(e.map(s=>i.removeApi(s))).catch(s=>console.error("Semantic remove (apis):",s))}removeCollections(e){if(!this.aiEnabled||e.length===0)return;const i=f.getSemanticSearchService();Promise.all(e.map(s=>i.removeCollection(s))).catch(s=>console.error("Semantic remove (collections):",s))}async start(){if(this.watchPath){console.warn("Watcher already started for:",this.watchPath);return}try{this.unlistenEvent=await E("fs-watch-event",async e=>{const i=e.payload;try{await this.handleEvent(i)}catch(s){console.error("Error handling file change:",s)}}),await h.invoke("fs_watch",{path:this.projectDir,options:{recursive:!0,delayMs:500}}),this.watchPath=this.projectDir}catch(e){throw console.error("Failed to start file watcher:",e),this.unlistenEvent&&(this.unlistenEvent(),this.unlistenEvent=null),e}}async stop(){if(this.watchPath)try{await h.invoke("fs_unwatch",{path:this.watchPath})}catch(e){console.error("Error stopping file watcher:",e)}finally{this.unlistenEvent&&(this.unlistenEvent(),this.unlistenEvent=null),this.watchPath=null}}async handleEvent(e){const{changeType:i,paths:s,pathTypes:n,type:t}=e;if(await this.isProjectFolderRemoved(s,i)){await this.handleProjectFolderRemoval();return}const o=this.filterSpecFiles(s,n);if(o.paths.length===0)return;const a=await this.toFileEntries(o.paths,o.pathTypes);switch(i){case"changed":(t.includes("Data")||t.includes("Name"))&&await this.handleModify(a);break;case"added":await this.handleCreate(a);break;case"deleted":await this.handleDelete(a);break;case"renamed":await this.handleRename(a);break;default:console.log("Unhandled change type:",i)}}filterSpecFiles(e,i){const s=[],n=[];for(let t=0;t<e.length;t++){const o=e[t],a=o.split(".").pop()?.toLowerCase();a&&["yaml","yml","json"].includes(a)&&(s.push(o),n.push(i[t]||"unknown"))}return{paths:s,pathTypes:n}}async toFileEntries(e,i){return Promise.all(e.map(async(s,n)=>({relative_path:await h.PathUtils.relative(this.projectDir,s),absolute_path:s,type:i[n]||"unknown"})))}hasExternalConfigChange(e){return e.some(i=>h.isRedoclyConfigFile(i.relative_path)&&!this.storage.isWatchExcluded(i.relative_path))}withoutConfigFile(e){return e.filter(i=>!h.isRedoclyConfigFile(i.relative_path))}consolidateFileEntries(e){const i=[],s=new Set;for(const n of e)s.has(n.relative_path)||(s.add(n.relative_path),this.storage.isWatchExcluded(n.relative_path)||i.push(n));return i}async handleModify(e){const i=this.hasExternalConfigChange(e),s=this.withoutConfigFile(e),{newApiFiles:n,existingApiFiles:t}=this.categorizeApisFromFiles(s),{newCollectionFiles:o,existingCollectionFiles:a}=this.categorizeCollectionsFromFiles(s),c=await this.findApisToReload(e),r=await this.findCollectionsToReload(e),p=[...n,...o];p.length>0&&await this.handleCreate(p),i&&await this.reloadEnvironments();const u=this.consolidateFileEntries([...t,...c]),g=this.consolidateFileEntries([...a,...r]);await this.reloadApis(u),await this.reloadCollections(g)}async handleCreate(e){this.hasExternalConfigChange(e)&&await this.reloadEnvironments();const i=this.withoutConfigFile(e),s=i.filter(r=>r.type==="api"),n=i.filter(r=>r.type==="collection"),{newApiFiles:t,existingApiFiles:o}=this.categorizeApisFromFiles(s),{newCollectionFiles:a,existingCollectionFiles:c}=this.categorizeCollectionsFromFiles(n);if(t.length>0||a.length>0){t.forEach(d=>this.storage.addPersistExcludedId(d.relative_path)),a.forEach(d=>this.storage.addPersistExcludedId(d.relative_path));const r=t.length>0?await this.tauriStorage.loadAndParseApis(t,void 0,!0):[],p=a.length>0?await this.tauriStorage.loadAndParseCollections(a,void 0):[],u=r.filter(d=>d!==null),g=p.filter(d=>d!==null);this.apis.set([...this.apis.get(),...u]),this.collections.set([...this.collections.get(),...g]),this.indexApis(u),this.indexCollections(g),setTimeout(()=>{t.forEach(d=>this.storage.removePersistExcludedId(d.relative_path)),a.forEach(d=>this.storage.removePersistExcludedId(d.relative_path))},500)}o.length>0&&await this.reloadApis(o),c.length>0&&await this.reloadCollections(c)}categorizeApisFromFiles(e){const i=new Set,s=[],n=[];for(const t of e){if(i.has(t.relative_path))continue;i.add(t.relative_path),this.apis.get().some(a=>a.id===t.relative_path)?n.push(t):t.type==="api"&&s.push(t)}return{newApiFiles:s,existingApiFiles:n}}categorizeCollectionsFromFiles(e){const i=new Set,s=[],n=[];for(const t of e){if(i.has(t.relative_path))continue;i.add(t.relative_path),this.collections.get().some(a=>a.id===t.relative_path)?n.push(t):t.type==="collection"&&s.push(t)}return{newCollectionFiles:s,existingCollectionFiles:n}}async handleDelete(e){this.hasExternalConfigChange(e)&&await this.reloadEnvironments();const i=this.withoutConfigFile(e),s=[],n=[];for(const t of i){this.storage.addPersistExcludedId(t.relative_path);const o=this.apis.get();o.some(r=>r.id===t.relative_path)&&(this.apis.set(o.filter(r=>r.id!==t.relative_path)),this.tauriStorage.deleteApiFromCache(t.relative_path),s.push(t.relative_path));const a=this.collections.get(),c=a.findIndex(r=>r.id===t.relative_path);c>=0&&(this.collections.set(a.filter((r,p)=>p!==c)),n.push(t.relative_path)),setTimeout(()=>{this.storage.removePersistExcludedId(t.relative_path)},500)}this.removeApis(s),this.removeCollections(n)}async handleRename(e){if(e.length>=2){const[i,s]=e;await this.handleDelete([i]),await this.handleCreate([s])}else await this.handleCreate(e)}async isProjectFolderRemoved(e,i){if(e.length===0)return!1;if(i==="deleted"||i==="renamed"){for(const n of e)if(n===this.projectDir)return!0}return e.filter(n=>!n.startsWith(this.projectDir+"/")&&n!==this.projectDir).length>0&&i==="renamed"}async handleProjectFolderRemoval(){const e=this.apis.get(),i=e.map(t=>t.id);e.forEach(t=>{this.storage.addPersistExcludedId(t.id),this.tauriStorage.deleteApiFromCache(t.id)}),this.apis.set([]);const s=this.collections.get(),n=s.map(t=>t.id);s.forEach(t=>{this.storage.addPersistExcludedId(t.id)}),this.collections.set([]),setTimeout(()=>{e.forEach(t=>this.storage.removePersistExcludedId(t.id)),s.forEach(t=>this.storage.removePersistExcludedId(t.id))},500),this.removeApis(i),this.removeCollections(n),await this.stop()}async findApisToReload(e){const i=[];return await Promise.all(this.apis.get().map(async s=>{const n=s.fileDependencies??new Set,t=s.id,o=e.find(a=>n.has(a.absolute_path));if(!this.storage.isWatchExcluded(t)&&o){const a=await h.PathUtils.join(this.projectDir,t);i.push({relative_path:t,absolute_path:a,type:"api"})}})),i}async findCollectionsToReload(e){const i=[];return await Promise.all(this.collections.get().map(async s=>{const n=s.fileDependencies??new Set,t=s.id,o=e.find(a=>n.has(a.absolute_path));if(!this.storage.isWatchExcluded(t)&&o){const a=await h.PathUtils.join(this.projectDir,t);i.push({relative_path:t,absolute_path:a,type:"collection"})}})),i}reloadEnvironments(){const e=this.pendingEnvironmentsReload.then(()=>this.readAndPublishEnvironments());return this.pendingEnvironmentsReload=e.catch(()=>{}),e}async readAndPublishEnvironments(){const e=this.environments.get(),i=await this.tauriStorage.readEnvironments();!(this.environments.get()!==e)&&(i.length>0||!this.storage.getEnvironmentsConfigError())&&this.environments.set(i.length>0?i:h.cloneObject(h.DEFAULT_ENVIRONMENTS)),this.storage.publishEnvironmentsConfigError()}async reloadApis(e){if(e.length===0)return;const i=await this.tauriStorage.loadAndParseApis(e,void 0,!0),s=[];await Promise.all(i.map(async(n,t)=>{if(!n){await this.handleDelete([e[t]]);return}const o=this.apis.get();o.some(a=>a.id===n.id)?(this.storage.addPersistExcludedId(n.id),this.apis.set(o.map(a=>a.id===n.id?n:a)),s.push(n),setTimeout(()=>this.storage.removePersistExcludedId(n.id),500)):console.warn("API not found in state after reload:",n.id)})),s.length>0&&this.indexApis(s)}async reloadCollections(e){if(e.length===0)return;const i=await this.tauriStorage.loadAndParseCollections(e,void 0),s=[];await Promise.all(i.map(async(n,t)=>{if(!n){await this.handleDelete([e[t]]);return}const o=this.collections.get(),a=o.findIndex(c=>c.id===n.id);a>=0?(this.storage.addPersistExcludedId(n.id),this.collections.set(o.map((c,r)=>r===a?n:c)),s.push(n),setTimeout(()=>this.storage.removePersistExcludedId(n.id),500)):console.warn("Collection not found in state after reload:",n.id)})),s.length>0&&this.indexCollections(s)}}exports.FileWatcher=w;
@@ -1,4 +1,4 @@
1
- import { i as f, H as W, I as X, x as y } from "./replay-index-BCz452N6.js";
1
+ import { i as f, I as W, J as X, y } from "./replay-index-4TEahAPK.js";
2
2
  import { O as z } from "./replay-Observable-D6wKbFwB.js";
3
3
  import { p as K } from "./replay-promise-map-limit-Db_42GvV.js";
4
4
  function w(t) {
@@ -152,8 +152,8 @@ function ce(t) {
152
152
  return { textParts: e, summaries: n };
153
153
  }
154
154
  function R(t) {
155
- const { apiId: e, apiTitle: n, path: o, method: s, op: i, pathItem: r, globalSchemes: c, apiSecurity: a } = t, u = i.summary ?? "", l = w(i.description ?? ""), d = i.operationId ?? "", p = i.tags ?? [], m = s.toUpperCase(), g = V(i, r), h = ne(i.security, a, c), x = h.length > 0 ? h.map((_) => `api_sec:${e}:${_.schemeName}`) : void 0, I = [n, `${m} ${o}`, u, l];
156
- d && I.push(`operationId: ${d}`), p.length > 0 && I.push(`Tags: ${p.join(", ")}`), i.deprecated && I.push("DEPRECATED"), g.length > 0 && I.push(`Parameters: ${g.map(J).join(". ")}.`);
155
+ const { apiId: e, apiTitle: n, path: o, method: s, op: i, pathItem: r, globalSchemes: c, apiSecurity: a } = t, u = i.summary ?? "", l = w(i.description ?? ""), d = i.operationId ?? "", p = i.tags ?? [], m = s.toUpperCase(), g = V(i, r), h = ne(i.security, a, c), I = h.length > 0 ? h.map((_) => `api_sec:${e}:${_.schemeName}`) : void 0, x = [n, `${m} ${o}`, u, l];
156
+ d && x.push(`operationId: ${d}`), p.length > 0 && x.push(`Tags: ${p.join(", ")}`), i.deprecated && x.push("DEPRECATED"), g.length > 0 && x.push(`Parameters: ${g.map(J).join(". ")}.`);
157
157
  let k;
158
158
  const v = [], T = i.requestBody;
159
159
  if (T) {
@@ -162,15 +162,15 @@ function R(t) {
162
162
  const N = re(_, {
163
163
  hideReadOnly: m === "POST" || m === "PUT" || m === "PATCH"
164
164
  });
165
- N.textPart && I.push(N.textPart), k = N.schemaJson, v.push(...N.examples);
165
+ N.textPart && x.push(N.textPart), k = N.schemaJson, v.push(...N.examples);
166
166
  }
167
167
  }
168
168
  const { textParts: B, summaries: A } = ce(
169
169
  i.responses ?? {}
170
170
  );
171
- B.length > 0 && I.push(`Responses: ${B.join(", ")}.`);
171
+ B.length > 0 && x.push(`Responses: ${B.join(", ")}.`);
172
172
  const C = ie(h);
173
- C && I.push(C);
173
+ C && x.push(C);
174
174
  const E = `api_op:${e}:${o}:${s}:${d || `${o}-${s}`}`, Q = {
175
175
  type: "api_operation",
176
176
  id: E,
@@ -186,12 +186,12 @@ function R(t) {
186
186
  parameterDetails: g.length > 0 ? g : void 0,
187
187
  requestBodySchema: k,
188
188
  responseSchemas: A.length > 0 ? A : void 0,
189
- securitySchemeRefs: x,
189
+ securitySchemeRefs: I,
190
190
  examples: v.length > 0 ? v : void 0
191
191
  };
192
192
  return {
193
193
  id: E,
194
- text: S(I.filter(Boolean).join(" ")),
194
+ text: S(x.filter(Boolean).join(" ")),
195
195
  payload: Q
196
196
  };
197
197
  }
@@ -338,11 +338,11 @@ function pe(t) {
338
338
  const d = i.parameters ? le(i.parameters) : [];
339
339
  d.length > 0 && l.push(`Parameters: ${d.map(J).join(". ")}.`), i.requestBody?.type && l.push(`Request body type: ${i.requestBody.type}`);
340
340
  const m = (i.successCriteria ?? []).map((h) => {
341
- let x = h.condition;
342
- return h.context && (x += ` context: ${h.context}`), h.type && (x += ` (${h.type})`), x;
341
+ let I = h.condition;
342
+ return h.context && (I += ` context: ${h.context}`), h.type && (I += ` (${h.type})`), I;
343
343
  });
344
344
  if (m.length > 0 && l.push(`Success criteria: ${m.join("; ")}`), i.outputs?.length) {
345
- const h = i.outputs.map((x) => `${x.key}=${x.value}`).filter(Boolean);
345
+ const h = i.outputs.map((I) => `${I.key}=${I.value}`).filter(Boolean);
346
346
  h.length && l.push(`Outputs: ${h.join(", ")}`);
347
347
  }
348
348
  const g = `step:${e}:${o}:${r}`;
@@ -398,7 +398,7 @@ function me(t) {
398
398
  return W(X(t));
399
399
  }
400
400
  const ye = {};
401
- class xe extends z {
401
+ class Ie extends z {
402
402
  constructor(e) {
403
403
  super(), this.collectionName = e;
404
404
  }
@@ -535,7 +535,7 @@ class xe extends z {
535
535
  });
536
536
  }
537
537
  }
538
- const M = "replay_search", Ie = 384, $ = {
538
+ const M = "replay_search", xe = 384, $ = {
539
539
  added: 0,
540
540
  updated: 0,
541
541
  removed: 0,
@@ -553,7 +553,7 @@ class ge extends z {
553
553
  return this.projectId ? `${M}_${this.projectId}` : M;
554
554
  }
555
555
  createIndexer() {
556
- const e = new xe(this.collectionName);
556
+ const e = new Ie(this.collectionName);
557
557
  return e.subscribe("indexing-activity", (n) => {
558
558
  this.emit("indexing-activity", n);
559
559
  }), e;
@@ -595,7 +595,7 @@ class ge extends z {
595
595
  await f("plugin:velesdb|create_collection", {
596
596
  request: {
597
597
  name: this.collectionName,
598
- dimension: Ie,
598
+ dimension: xe,
599
599
  metric: "cosine",
600
600
  storage_mode: "full"
601
601
  }
@@ -1 +1 @@
1
- "use strict";const d=require("./replay-index-DYtXcqDk.js"),H=require("./replay-Observable-bjJ6wkRB.js"),Z=require("./replay-promise-map-limit-DRDkHc-b.js");function g(t){return t==null?"":typeof t=="string"?t:typeof t=="object"&&"raw"in t&&typeof t.raw=="string"?t.raw:String(t)}function $(t){return t.replace(/\s+/g," ").trim()}function S(t){return typeof t=="object"&&t!==null&&"$ref"in t}function P(t){return S(t)?null:t}function q(t){try{return JSON.stringify(t)}catch{return String(t)}}function z(t){let e=`${t.name} (${t.in}`;return t.required&&(e+=", required"),t.type&&(e+=`, ${t.type}`),t.format&&(e+=`, format: ${t.format}`),t.enum&&(e+=`, enum: [${t.enum.join(",")}]`),t.pattern&&(e+=`, pattern: ${t.pattern}`),e+=")",e}function J(t){return t.type?Array.isArray(t.type)?t.type.join("|"):t.type:t.oneOf?"oneOf":t.anyOf?"anyOf":t.allOf?"allOf":"object"}function V(t){return t==="querystring"?"query":t==="query"||t==="header"||t==="path"||t==="cookie"?t:"query"}function ee(t){const e=t.schema&&!S(t.schema)?t.schema:null,n={name:t.name,in:V(t.in),required:t.required??!1};return e&&(n.type=J(e),e.format&&(n.format=e.format),e.enum&&(n.enum=e.enum.map(String)),e.pattern&&(n.pattern=e.pattern),e.example!==void 0&&(n.example=String(e.example))),t.description&&(n.description=g(t.description)),t.example!==void 0&&!n.example&&(n.example=String(t.example)),n}function te(t,e){const n=new Set,o=[],s=i=>{for(const r of i){const c=P(r);if(!c||!c.name)continue;const a=`${c.in}:${c.name}`;n.has(a)||(n.add(a),o.push(ee(c)))}};return t.parameters&&s(t.parameters),e.parameters&&s(e.parameters),o}function U(t,e=2,n=0){if(n>=e||!t.properties)return[];const o=new Set(t.required??[]);return Object.entries(t.properties).map(([s,i])=>({name:s,type:J(i),required:o.has(s),readOnly:i.readOnly}))}function F(t){const e=t.components?.securitySchemes;if(!e)return[];const n=[];for(const[o,s]of Object.entries(e)){const i=P(s);i&&n.push(ne(o,i))}return n}function ne(t,e){const n={schemeName:t,type:e.type};if(e.in&&(n.in=e.in),e.name&&(n.name=e.name),e.scheme&&(n.scheme=e.scheme),e.bearerFormat&&(n.bearerFormat=e.bearerFormat),e.flows){const o=Object.keys(e.flows).filter(i=>e.flows[i]);o.length>0&&(n.flows=o.join(", "));const s=new Set;for(const i of o){const r=e.flows[i];r?.scopes&&Object.keys(r.scopes).forEach(c=>s.add(c))}s.size>0&&(n.scopes=[...s].join(", "))}return n}function ie(t,e,n){const o=t??e;if(!o||n.length===0)return[];const s=new Set;for(const i of o)for(const r of Object.keys(i))s.add(r);return n.filter(i=>s.has(i.schemeName))}function oe(t){return t.length===0?"":`Security: ${t.map(n=>{let o=`${n.schemeName} (${n.type}`;return n.scheme&&(o+=`, ${n.scheme}`),n.in&&n.name&&(o+=`, ${n.name} in ${n.in}`),o+=")",o}).join("; ")}.`}const se=["get","put","post","delete","options","head","patch","trace"],re=["query","x-query"];function ce(t,e){const n=[],o=Object.keys(t.content??{});if(o.length===0)return{textPart:"",schemaJson:"{}",examples:n};const s=o.find(u=>u.includes("json"))??o[0],i=t.content?.[s],r=i?.schema&&!S(i.schema)?i.schema:null,a=(r?U(r):[]).filter(u=>!e.hideReadOnly||!u.readOnly),p=t.required?"required":"optional";let l=`Request body (${s}, ${p})`;if(a.length>0){const u=a.map(f=>`${f.name}: ${f.type}${f.required?" required":""}${f.readOnly?" readOnly":""}`);l+=`: {${u.join(", ")}}`}return i?.example!==void 0&&n.push(q(i.example)),{textPart:l,schemaJson:JSON.stringify(a),examples:n}}function ae(t){const e=[],n=[];for(const[o,s]of Object.entries(t)){if(S(s))continue;const i=g(s.description??"");e.push(`${o} ${i}`.trim());const r={statusCode:o};i&&(r.description=i);const c=s.content;if(c){const a=Object.keys(c).find(l=>l.includes("json"))??Object.keys(c)[0],p=c[a]?.schema;if(p&&!S(p)){const l=U(p);l.length>0&&(r.schemaProperties=JSON.stringify(l))}}n.push(r)}return{textParts:e,summaries:n}}function D(t){const{apiId:e,apiTitle:n,path:o,method:s,op:i,pathItem:r,globalSchemes:c,apiSecurity:a}=t,p=i.summary??"",l=g(i.description??""),u=i.operationId??"",f=i.tags??[],m=s.toUpperCase(),I=te(i,r),h=ie(i.security,a,c),y=h.length>0?h.map(v=>`api_sec:${e}:${v.schemeName}`):void 0,x=[n,`${m} ${o}`,p,l];u&&x.push(`operationId: ${u}`),f.length>0&&x.push(`Tags: ${f.join(", ")}`),i.deprecated&&x.push("DEPRECATED"),I.length>0&&x.push(`Parameters: ${I.map(z).join(". ")}.`);let T;const _=[],j=i.requestBody;if(j){const v=P(j);if(v){const b=ce(v,{hideReadOnly:m==="POST"||m==="PUT"||m==="PATCH"});b.textPart&&x.push(b.textPart),T=b.schemaJson,_.push(...b.examples)}}const{textParts:A,summaries:B}=ae(i.responses??{});A.length>0&&x.push(`Responses: ${A.join(", ")}.`);const C=oe(h);C&&x.push(C);const E=`api_op:${e}:${o}:${s}:${u||`${o}-${s}`}`,Y={type:"api_operation",id:E,contentHash:"",title:p||`${m} ${o}`,description:l||void 0,apiId:e,path:o,method:m,operationId:u||void 0,tags:f.length>0?f:void 0,deprecated:i.deprecated||void 0,parameterDetails:I.length>0?I:void 0,requestBodySchema:T,responseSchemas:B.length>0?B:void 0,securitySchemeRefs:y,examples:_.length>0?_:void 0};return{id:E,text:$(x.filter(Boolean).join(" ")),payload:Y}}function L(t){const e=t.info?.title??"Untitled API",n=g(t.info?.description??t.info?.summary??""),o=t.id;return{id:`api:${o}`,text:$([e,n].filter(Boolean).join(" ")),payload:{type:"api",id:`api:${o}`,contentHash:"",title:e,description:n||void 0,apiId:o}}}function G(t){const e=[];for(const n of t){e.push(L(n));const o=n.info?.title??"Untitled API",s=n.id,i=F(n);for(const c of i){const a=`api_sec:${s}:${c.schemeName}`,p=[`${c.schemeName}: type=${c.type}`,c.scheme?`scheme=${c.scheme}`:"",c.in&&c.name?`${c.name} in ${c.in}`:"",c.bearerFormat?`format=${c.bearerFormat}`:"",c.flows?`flows=[${c.flows}]`:"",c.scopes?`scopes=[${c.scopes}]`:""].filter(Boolean).join(" ");e.push({id:a,text:$(`${o} Authentication. ${c.schemeName}. ${p}.`),payload:{type:"api_security",id:a,contentHash:"",title:`${o} — ${c.schemeName}`,apiId:s,securityScheme:c}})}const r=n.paths??{};for(const[c,a]of Object.entries(r)){if(!a||typeof a!="object")continue;const p=[...se.filter(u=>u in a),...re.filter(u=>u in a)];for(const u of p){const f=a[u];!f||typeof f!="object"||e.push(D({apiId:s,apiTitle:o,path:c,method:u,op:f,pathItem:a,globalSchemes:i,apiSecurity:n.security}))}const l=a.additionalOperations;if(l&&typeof l=="object")for(const[u,f]of Object.entries(l))!f||typeof f!="object"||e.push(D({apiId:s,apiTitle:o,path:c,method:u,op:f,pathItem:a,globalSchemes:i,apiSecurity:n.security}))}}return e}function le(t){const e=[],n=[{list:t.queryParameters,loc:"query"},{list:t.headers,loc:"header"},{list:t.cookies,loc:"cookie"},{list:t.pathParameters,loc:"path"}];for(const{list:o,loc:s}of n)for(const i of o)if("key"in i){const r=i;e.push({name:r.key,in:s,required:!1})}return e}function W(t){const e=t.id,n=t.info?.title??"Untitled Collection",o=g(t.info?.description??t.info?.summary??"");return{id:`collection:${e}`,text:$([n,o].filter(Boolean).join(" ")),payload:{type:"collection",id:`collection:${e}`,contentHash:"",title:n,description:o||void 0,collectionId:e}}}function Q(t){const{collectionId:e,collectionTitle:n,workflow:o}=t,s=o.workflowId??"",i=o.summary??s,r=g(o.description??""),c=[n,i,r];if(o.inputs&&c.push(`Inputs schema: ${q(o.inputs)}`),o.outputs?.length){const a=o.outputs.map(p=>p.key).filter(Boolean);a.length&&c.push(`Outputs: ${a.join(", ")}`)}return o.dependsOn?.length&&c.push(`Depends on: ${o.dependsOn.join(", ")}`),{id:`workflow:${e}:${s}`,text:$(c.filter(Boolean).join(" ")),payload:{type:"workflow",id:`workflow:${e}:${s}`,contentHash:"",title:i,description:r||void 0,collectionId:e,workflowId:s}}}function X(t){const{collectionId:e,collectionTitle:n,workflowId:o,workflowTitle:s,step:i}=t,r=i.stepId??"",c=g(i.description??""),a=i.operation,p=i.xOperation,l=[n,s,`step: ${r}`];c&&l.push(c),a?(l.push(`${a.method?.toUpperCase()} ${a.path}`),a.apiId&&l.push(`API: ${a.apiId}`),a.operationId&&l.push(`operationId: ${a.operationId}`)):p&&l.push(`${p.method?.toUpperCase()} ${p.url}`);const u=i.parameters?le(i.parameters):[];u.length>0&&l.push(`Parameters: ${u.map(z).join(". ")}.`),i.requestBody?.type&&l.push(`Request body type: ${i.requestBody.type}`);const m=(i.successCriteria??[]).map(h=>{let y=h.condition;return h.context&&(y+=` context: ${h.context}`),h.type&&(y+=` (${h.type})`),y});if(m.length>0&&l.push(`Success criteria: ${m.join("; ")}`),i.outputs?.length){const h=i.outputs.map(y=>`${y.key}=${y.value}`).filter(Boolean);h.length&&l.push(`Outputs: ${h.join(", ")}`)}const I=`step:${e}:${o}:${r}`;return{id:I,text:$(l.filter(Boolean).join(" ")),payload:{type:"step",id:I,contentHash:"",title:r,description:c||void 0,collectionId:e,workflowId:o,stepId:r,path:a?.path??p?.url,method:(a?.method??p?.method)?.toUpperCase(),apiId:a?.apiId,operationId:a?.operationId,parameterDetails:u.length>0?u:void 0,successCriteria:m.length>0?m:void 0,requestBodySchema:i.requestBody?.type?q(i.requestBody):void 0}}}function K(t){const e=[];for(const n of t){const o=n.id,s=n.info?.title??"Untitled Collection";e.push(W(n));for(const i of n.workflows??[]){e.push(Q({collectionId:o,collectionTitle:s,workflow:i}));const r=i.workflowId??"",c=i.summary??r;for(const a of i.steps??[])e.push(X({collectionId:o,collectionTitle:s,workflowId:r,workflowTitle:c,step:a}))}}return e}function de(t,e){return[...G(t),...K(e)]}const N=10,ue=4;function R(t){let e=0;for(let n=0;n<t.length;n++)e=(e<<5)-e+t.charCodeAt(n)|0;return e>>>0}function pe(t){return d.bytesToHex(d.md5(t))}const fe={};class he extends H.Observable{constructor(e){super(),this.collectionName=e}collectionName;activeIndexJobs=0;getIndexingActivityState(){return{inProgress:this.activeIndexJobs>0}}beginIndexJob(){this.activeIndexJobs++,this.activeIndexJobs===1&&this.emit("indexing-activity",{inProgress:!0})}endIndexJob(){this.activeIndexJobs=Math.max(0,this.activeIndexJobs-1),this.activeIndexJobs===0&&this.emit("indexing-activity",{inProgress:!1})}async getIdsByPayload(e,n){return d.invoke("semantic_search_get_ids_by_payload",{collectionName:this.collectionName,field:e,value:n})}async getAllIds(){return d.invoke("semantic_search_get_all_ids",{collectionName:this.collectionName})}async getScopeHashes(e){const n=e.apiIds??[],o=e.collectionIds??[];let s;if(n.length===0&&o.length===0)s=await this.getAllIds();else{const r=[];for(const a of n)r.push(this.getIdsByPayload("apiId",a));for(const a of o)r.push(this.getIdsByPayload("collectionId",a));s=(await Promise.all(r)).flat()}const i=new Map;for(const r of s)i.set(r.id,r.contentHash);return i}async indexDocuments(e,n){if(e.length===0&&!n)return{added:0,updated:0,removed:0,unchanged:0};const o=await this.getScopeHashes(n??{}),s=[],i=new Set;let r=0,c=0;for(const l of e){const u=pe(l.text);l.payload.contentHash=u,i.add(l.id);const f=o.get(l.id);f===u?c++:(f||r++,s.push(l))}const a=s.length-r,p=[];for(const l of o.keys())i.has(l)||p.push(l);if(p.length>0||s.length>0){this.beginIndexJob();try{p.length>0&&await this.deletePoints(p.map(R)),s.length>0&&await this.embedAndUpsert(s),await this.flush()}finally{this.endIndexJob()}}return{added:r,updated:a,removed:p.length,unchanged:c}}async removeByPayloadFilter(e,n){return d.invoke("semantic_search_delete_by_payload",{collectionName:this.collectionName,field:e,value:n})}async getStoredDocumentCount(){try{return(await d.invoke("plugin:velesdb|list_collections"))?.find(o=>o.name===this.collectionName)?.count??0}catch{return 0}}async getDocumentsByIds(e){if(e.length===0)return new Map;const n=e.map(R),o=await d.invoke("plugin:velesdb|get_points",{request:{collection:this.collectionName,ids:n}}),s=new Map;for(const i of o??[])if(i?.payload){const r=i.payload;r.id&&s.set(r.id,r)}return s}async embedAndUpsert(e){const n=[],o=e.length;for(let s=0;s<o;s+=N)n.push({docs:e.slice(s,s+N),index:Math.floor(s/N)});await Z.promiseMapLimit(n,ue,async s=>{const i=s.docs.map(r=>({id:r.id,text:r.text||r.payload.title,payload:r.payload}));await d.invoke("semantic_search_embed_and_upsert",{collectionName:this.collectionName,documents:i})})}async deletePoints(e){e.length!==0&&await d.invoke("plugin:velesdb|delete_points",{request:{collection:this.collectionName,ids:e}})}async flush(){await d.invoke("plugin:velesdb|flush",{name:this.collectionName}),await d.invoke("semantic_search_write_hnsw_marker",{collectionName:this.collectionName}).catch(()=>{})}}const M="replay_search",me=384,w={added:0,updated:0,removed:0,unchanged:0};function k(t){return t.added+t.updated>0}class ye extends H.Observable{initialized=!1;projectId=null;indexer=null;indexQueue=Promise.resolve();get collectionName(){return this.projectId?`${M}_${this.projectId}`:M}createIndexer(){const e=new he(this.collectionName);return e.subscribe("indexing-activity",n=>{this.emit("indexing-activity",n)}),e}getIndexer(){return this.indexer||(this.indexer=this.createIndexer()),this.indexer}getIndexingActivityState(){return this.getIndexer().getIndexingActivityState()}async ensureInitialized(){this.initialized||await this.init()}enqueueIndex(e,n){const s=this.indexQueue.then(()=>e()).then(async i=>(n(i)&&await this.unloadModel(),i)).catch(async i=>{throw console.error("Semantic index:",i),await this.unloadModel(),i});return this.indexQueue=s.catch(()=>{}),s}async unloadModel(){try{await d.invoke("semantic_search_unload_model")}catch{}}setProject(e){this.projectId!==e&&(this.projectId=e,this.initialized=!1,this.indexer=this.createIndexer())}async init(){if(d.isTauriApp()&&!this.initialized){try{if((await d.invoke("plugin:velesdb|list_collections"))?.some(n=>n.name===this.collectionName)){this.initialized=!0;return}}catch{}await d.invoke("plugin:velesdb|create_collection",{request:{name:this.collectionName,dimension:me,metric:"cosine",storage_mode:"full"}}),this.initialized=!0}}async indexApis(e){if(!d.isTauriApp())return w;const n=this.collectionName,o=this.getIndexer(),s=G(e),i={apiIds:e.map(r=>r.id)};return await this.ensureInitialized(),this.enqueueIndex(async()=>this.collectionName!==n?w:o.indexDocuments(s,i),k)}async indexCollections(e){if(!d.isTauriApp())return w;const n=this.collectionName,o=this.getIndexer(),s=K(e),i={collectionIds:e.map(r=>r.id)};return await this.ensureInitialized(),this.enqueueIndex(async()=>this.collectionName!==n?w:o.indexDocuments(s,i),k)}async removeApi(e){if(!d.isTauriApp())return;const n=this.getIndexer();await this.ensureInitialized(),await this.enqueueIndex(()=>n.removeByPayloadFilter("apiId",e),()=>!1)}async removeCollection(e){if(!d.isTauriApp())return;const n=this.getIndexer();await this.ensureInitialized(),await this.enqueueIndex(()=>n.removeByPayloadFilter("collectionId",e),()=>!1)}async reindex(e){if(!d.isTauriApp())return w;const n=this.collectionName,o=this.getIndexer();return await this.ensureInitialized(),this.enqueueIndex(async()=>{if(this.collectionName!==n)return w;const{apis:s,collections:i}=e(),r=de(s,i);return o.indexDocuments(r,fe)},k)}async search(e,n=10,o){if(!d.isTauriApp())return[];try{await this.ensureInitialized();const s=o&&Object.keys(o).length>0?{type:o.type,apiId:o.apiId,collectionId:o.collectionId,path:o.path,method:o.method,operationId:o.operationId,workflowId:o.workflowId,stepId:o.stepId}:void 0,r=((await d.invoke("semantic_search_text",{collection:this.collectionName,query:e,topK:n,filters:s})).results??[]).map(c=>({...c.payload,score:c.score??0}));return await this.enrichWithRelatedSecurity(r),r}catch{return[]}}async enrichWithRelatedSecurity(e){const n=e.filter(i=>i.type==="api_operation"&&i.securitySchemeRefs?.length);if(n.length===0)return;const o=[...new Set(n.flatMap(i=>i.securitySchemeRefs??[]))],s=await this.getIndexer().getDocumentsByIds(o);for(const i of n){const r=[];for(const c of i.securitySchemeRefs??[]){const a=s.get(c);a?.securityScheme&&r.push(a.securityScheme)}r.length>0&&(i.relatedSecuritySchemes=r)}}async status(){if(!d.isTauriApp())return{indexed:0,modelLoaded:!1};const e=await this.getIndexer().getStoredDocumentCount();let n=!1;try{n=(await d.invoke("semantic_search_model_status")).loaded}catch{}return{indexed:e,modelLoaded:n}}async clear(){if(!(!d.isTauriApp()||!this.initialized))try{await d.invoke("plugin:velesdb|delete_collection",{name:this.collectionName}),this.initialized=!1}catch{}}async preloadModel(){if(d.isTauriApp())try{await d.invoke("semantic_search_preload_model")}catch{}}}let O=null;function xe(){return O||(O=new ye),O}exports.extractApiDocument=L;exports.extractCollectionDocument=W;exports.extractGlobalSecuritySchemes=F;exports.extractOperationDocument=D;exports.extractStepDocument=X;exports.extractWorkflowDocument=Q;exports.getSemanticSearchService=xe;
1
+ "use strict";const d=require("./replay-index-Nz5obVS5.js"),H=require("./replay-Observable-bjJ6wkRB.js"),Z=require("./replay-promise-map-limit-DRDkHc-b.js");function g(t){return t==null?"":typeof t=="string"?t:typeof t=="object"&&"raw"in t&&typeof t.raw=="string"?t.raw:String(t)}function $(t){return t.replace(/\s+/g," ").trim()}function S(t){return typeof t=="object"&&t!==null&&"$ref"in t}function P(t){return S(t)?null:t}function q(t){try{return JSON.stringify(t)}catch{return String(t)}}function z(t){let e=`${t.name} (${t.in}`;return t.required&&(e+=", required"),t.type&&(e+=`, ${t.type}`),t.format&&(e+=`, format: ${t.format}`),t.enum&&(e+=`, enum: [${t.enum.join(",")}]`),t.pattern&&(e+=`, pattern: ${t.pattern}`),e+=")",e}function J(t){return t.type?Array.isArray(t.type)?t.type.join("|"):t.type:t.oneOf?"oneOf":t.anyOf?"anyOf":t.allOf?"allOf":"object"}function V(t){return t==="querystring"?"query":t==="query"||t==="header"||t==="path"||t==="cookie"?t:"query"}function ee(t){const e=t.schema&&!S(t.schema)?t.schema:null,n={name:t.name,in:V(t.in),required:t.required??!1};return e&&(n.type=J(e),e.format&&(n.format=e.format),e.enum&&(n.enum=e.enum.map(String)),e.pattern&&(n.pattern=e.pattern),e.example!==void 0&&(n.example=String(e.example))),t.description&&(n.description=g(t.description)),t.example!==void 0&&!n.example&&(n.example=String(t.example)),n}function te(t,e){const n=new Set,o=[],s=i=>{for(const r of i){const c=P(r);if(!c||!c.name)continue;const a=`${c.in}:${c.name}`;n.has(a)||(n.add(a),o.push(ee(c)))}};return t.parameters&&s(t.parameters),e.parameters&&s(e.parameters),o}function U(t,e=2,n=0){if(n>=e||!t.properties)return[];const o=new Set(t.required??[]);return Object.entries(t.properties).map(([s,i])=>({name:s,type:J(i),required:o.has(s),readOnly:i.readOnly}))}function F(t){const e=t.components?.securitySchemes;if(!e)return[];const n=[];for(const[o,s]of Object.entries(e)){const i=P(s);i&&n.push(ne(o,i))}return n}function ne(t,e){const n={schemeName:t,type:e.type};if(e.in&&(n.in=e.in),e.name&&(n.name=e.name),e.scheme&&(n.scheme=e.scheme),e.bearerFormat&&(n.bearerFormat=e.bearerFormat),e.flows){const o=Object.keys(e.flows).filter(i=>e.flows[i]);o.length>0&&(n.flows=o.join(", "));const s=new Set;for(const i of o){const r=e.flows[i];r?.scopes&&Object.keys(r.scopes).forEach(c=>s.add(c))}s.size>0&&(n.scopes=[...s].join(", "))}return n}function ie(t,e,n){const o=t??e;if(!o||n.length===0)return[];const s=new Set;for(const i of o)for(const r of Object.keys(i))s.add(r);return n.filter(i=>s.has(i.schemeName))}function oe(t){return t.length===0?"":`Security: ${t.map(n=>{let o=`${n.schemeName} (${n.type}`;return n.scheme&&(o+=`, ${n.scheme}`),n.in&&n.name&&(o+=`, ${n.name} in ${n.in}`),o+=")",o}).join("; ")}.`}const se=["get","put","post","delete","options","head","patch","trace"],re=["query","x-query"];function ce(t,e){const n=[],o=Object.keys(t.content??{});if(o.length===0)return{textPart:"",schemaJson:"{}",examples:n};const s=o.find(u=>u.includes("json"))??o[0],i=t.content?.[s],r=i?.schema&&!S(i.schema)?i.schema:null,a=(r?U(r):[]).filter(u=>!e.hideReadOnly||!u.readOnly),p=t.required?"required":"optional";let l=`Request body (${s}, ${p})`;if(a.length>0){const u=a.map(f=>`${f.name}: ${f.type}${f.required?" required":""}${f.readOnly?" readOnly":""}`);l+=`: {${u.join(", ")}}`}return i?.example!==void 0&&n.push(q(i.example)),{textPart:l,schemaJson:JSON.stringify(a),examples:n}}function ae(t){const e=[],n=[];for(const[o,s]of Object.entries(t)){if(S(s))continue;const i=g(s.description??"");e.push(`${o} ${i}`.trim());const r={statusCode:o};i&&(r.description=i);const c=s.content;if(c){const a=Object.keys(c).find(l=>l.includes("json"))??Object.keys(c)[0],p=c[a]?.schema;if(p&&!S(p)){const l=U(p);l.length>0&&(r.schemaProperties=JSON.stringify(l))}}n.push(r)}return{textParts:e,summaries:n}}function D(t){const{apiId:e,apiTitle:n,path:o,method:s,op:i,pathItem:r,globalSchemes:c,apiSecurity:a}=t,p=i.summary??"",l=g(i.description??""),u=i.operationId??"",f=i.tags??[],m=s.toUpperCase(),I=te(i,r),h=ie(i.security,a,c),y=h.length>0?h.map(v=>`api_sec:${e}:${v.schemeName}`):void 0,x=[n,`${m} ${o}`,p,l];u&&x.push(`operationId: ${u}`),f.length>0&&x.push(`Tags: ${f.join(", ")}`),i.deprecated&&x.push("DEPRECATED"),I.length>0&&x.push(`Parameters: ${I.map(z).join(". ")}.`);let T;const _=[],j=i.requestBody;if(j){const v=P(j);if(v){const b=ce(v,{hideReadOnly:m==="POST"||m==="PUT"||m==="PATCH"});b.textPart&&x.push(b.textPart),T=b.schemaJson,_.push(...b.examples)}}const{textParts:A,summaries:B}=ae(i.responses??{});A.length>0&&x.push(`Responses: ${A.join(", ")}.`);const C=oe(h);C&&x.push(C);const E=`api_op:${e}:${o}:${s}:${u||`${o}-${s}`}`,Y={type:"api_operation",id:E,contentHash:"",title:p||`${m} ${o}`,description:l||void 0,apiId:e,path:o,method:m,operationId:u||void 0,tags:f.length>0?f:void 0,deprecated:i.deprecated||void 0,parameterDetails:I.length>0?I:void 0,requestBodySchema:T,responseSchemas:B.length>0?B:void 0,securitySchemeRefs:y,examples:_.length>0?_:void 0};return{id:E,text:$(x.filter(Boolean).join(" ")),payload:Y}}function L(t){const e=t.info?.title??"Untitled API",n=g(t.info?.description??t.info?.summary??""),o=t.id;return{id:`api:${o}`,text:$([e,n].filter(Boolean).join(" ")),payload:{type:"api",id:`api:${o}`,contentHash:"",title:e,description:n||void 0,apiId:o}}}function G(t){const e=[];for(const n of t){e.push(L(n));const o=n.info?.title??"Untitled API",s=n.id,i=F(n);for(const c of i){const a=`api_sec:${s}:${c.schemeName}`,p=[`${c.schemeName}: type=${c.type}`,c.scheme?`scheme=${c.scheme}`:"",c.in&&c.name?`${c.name} in ${c.in}`:"",c.bearerFormat?`format=${c.bearerFormat}`:"",c.flows?`flows=[${c.flows}]`:"",c.scopes?`scopes=[${c.scopes}]`:""].filter(Boolean).join(" ");e.push({id:a,text:$(`${o} Authentication. ${c.schemeName}. ${p}.`),payload:{type:"api_security",id:a,contentHash:"",title:`${o} — ${c.schemeName}`,apiId:s,securityScheme:c}})}const r=n.paths??{};for(const[c,a]of Object.entries(r)){if(!a||typeof a!="object")continue;const p=[...se.filter(u=>u in a),...re.filter(u=>u in a)];for(const u of p){const f=a[u];!f||typeof f!="object"||e.push(D({apiId:s,apiTitle:o,path:c,method:u,op:f,pathItem:a,globalSchemes:i,apiSecurity:n.security}))}const l=a.additionalOperations;if(l&&typeof l=="object")for(const[u,f]of Object.entries(l))!f||typeof f!="object"||e.push(D({apiId:s,apiTitle:o,path:c,method:u,op:f,pathItem:a,globalSchemes:i,apiSecurity:n.security}))}}return e}function le(t){const e=[],n=[{list:t.queryParameters,loc:"query"},{list:t.headers,loc:"header"},{list:t.cookies,loc:"cookie"},{list:t.pathParameters,loc:"path"}];for(const{list:o,loc:s}of n)for(const i of o)if("key"in i){const r=i;e.push({name:r.key,in:s,required:!1})}return e}function W(t){const e=t.id,n=t.info?.title??"Untitled Collection",o=g(t.info?.description??t.info?.summary??"");return{id:`collection:${e}`,text:$([n,o].filter(Boolean).join(" ")),payload:{type:"collection",id:`collection:${e}`,contentHash:"",title:n,description:o||void 0,collectionId:e}}}function Q(t){const{collectionId:e,collectionTitle:n,workflow:o}=t,s=o.workflowId??"",i=o.summary??s,r=g(o.description??""),c=[n,i,r];if(o.inputs&&c.push(`Inputs schema: ${q(o.inputs)}`),o.outputs?.length){const a=o.outputs.map(p=>p.key).filter(Boolean);a.length&&c.push(`Outputs: ${a.join(", ")}`)}return o.dependsOn?.length&&c.push(`Depends on: ${o.dependsOn.join(", ")}`),{id:`workflow:${e}:${s}`,text:$(c.filter(Boolean).join(" ")),payload:{type:"workflow",id:`workflow:${e}:${s}`,contentHash:"",title:i,description:r||void 0,collectionId:e,workflowId:s}}}function X(t){const{collectionId:e,collectionTitle:n,workflowId:o,workflowTitle:s,step:i}=t,r=i.stepId??"",c=g(i.description??""),a=i.operation,p=i.xOperation,l=[n,s,`step: ${r}`];c&&l.push(c),a?(l.push(`${a.method?.toUpperCase()} ${a.path}`),a.apiId&&l.push(`API: ${a.apiId}`),a.operationId&&l.push(`operationId: ${a.operationId}`)):p&&l.push(`${p.method?.toUpperCase()} ${p.url}`);const u=i.parameters?le(i.parameters):[];u.length>0&&l.push(`Parameters: ${u.map(z).join(". ")}.`),i.requestBody?.type&&l.push(`Request body type: ${i.requestBody.type}`);const m=(i.successCriteria??[]).map(h=>{let y=h.condition;return h.context&&(y+=` context: ${h.context}`),h.type&&(y+=` (${h.type})`),y});if(m.length>0&&l.push(`Success criteria: ${m.join("; ")}`),i.outputs?.length){const h=i.outputs.map(y=>`${y.key}=${y.value}`).filter(Boolean);h.length&&l.push(`Outputs: ${h.join(", ")}`)}const I=`step:${e}:${o}:${r}`;return{id:I,text:$(l.filter(Boolean).join(" ")),payload:{type:"step",id:I,contentHash:"",title:r,description:c||void 0,collectionId:e,workflowId:o,stepId:r,path:a?.path??p?.url,method:(a?.method??p?.method)?.toUpperCase(),apiId:a?.apiId,operationId:a?.operationId,parameterDetails:u.length>0?u:void 0,successCriteria:m.length>0?m:void 0,requestBodySchema:i.requestBody?.type?q(i.requestBody):void 0}}}function K(t){const e=[];for(const n of t){const o=n.id,s=n.info?.title??"Untitled Collection";e.push(W(n));for(const i of n.workflows??[]){e.push(Q({collectionId:o,collectionTitle:s,workflow:i}));const r=i.workflowId??"",c=i.summary??r;for(const a of i.steps??[])e.push(X({collectionId:o,collectionTitle:s,workflowId:r,workflowTitle:c,step:a}))}}return e}function de(t,e){return[...G(t),...K(e)]}const N=10,ue=4;function R(t){let e=0;for(let n=0;n<t.length;n++)e=(e<<5)-e+t.charCodeAt(n)|0;return e>>>0}function pe(t){return d.bytesToHex(d.md5(t))}const fe={};class he extends H.Observable{constructor(e){super(),this.collectionName=e}collectionName;activeIndexJobs=0;getIndexingActivityState(){return{inProgress:this.activeIndexJobs>0}}beginIndexJob(){this.activeIndexJobs++,this.activeIndexJobs===1&&this.emit("indexing-activity",{inProgress:!0})}endIndexJob(){this.activeIndexJobs=Math.max(0,this.activeIndexJobs-1),this.activeIndexJobs===0&&this.emit("indexing-activity",{inProgress:!1})}async getIdsByPayload(e,n){return d.invoke("semantic_search_get_ids_by_payload",{collectionName:this.collectionName,field:e,value:n})}async getAllIds(){return d.invoke("semantic_search_get_all_ids",{collectionName:this.collectionName})}async getScopeHashes(e){const n=e.apiIds??[],o=e.collectionIds??[];let s;if(n.length===0&&o.length===0)s=await this.getAllIds();else{const r=[];for(const a of n)r.push(this.getIdsByPayload("apiId",a));for(const a of o)r.push(this.getIdsByPayload("collectionId",a));s=(await Promise.all(r)).flat()}const i=new Map;for(const r of s)i.set(r.id,r.contentHash);return i}async indexDocuments(e,n){if(e.length===0&&!n)return{added:0,updated:0,removed:0,unchanged:0};const o=await this.getScopeHashes(n??{}),s=[],i=new Set;let r=0,c=0;for(const l of e){const u=pe(l.text);l.payload.contentHash=u,i.add(l.id);const f=o.get(l.id);f===u?c++:(f||r++,s.push(l))}const a=s.length-r,p=[];for(const l of o.keys())i.has(l)||p.push(l);if(p.length>0||s.length>0){this.beginIndexJob();try{p.length>0&&await this.deletePoints(p.map(R)),s.length>0&&await this.embedAndUpsert(s),await this.flush()}finally{this.endIndexJob()}}return{added:r,updated:a,removed:p.length,unchanged:c}}async removeByPayloadFilter(e,n){return d.invoke("semantic_search_delete_by_payload",{collectionName:this.collectionName,field:e,value:n})}async getStoredDocumentCount(){try{return(await d.invoke("plugin:velesdb|list_collections"))?.find(o=>o.name===this.collectionName)?.count??0}catch{return 0}}async getDocumentsByIds(e){if(e.length===0)return new Map;const n=e.map(R),o=await d.invoke("plugin:velesdb|get_points",{request:{collection:this.collectionName,ids:n}}),s=new Map;for(const i of o??[])if(i?.payload){const r=i.payload;r.id&&s.set(r.id,r)}return s}async embedAndUpsert(e){const n=[],o=e.length;for(let s=0;s<o;s+=N)n.push({docs:e.slice(s,s+N),index:Math.floor(s/N)});await Z.promiseMapLimit(n,ue,async s=>{const i=s.docs.map(r=>({id:r.id,text:r.text||r.payload.title,payload:r.payload}));await d.invoke("semantic_search_embed_and_upsert",{collectionName:this.collectionName,documents:i})})}async deletePoints(e){e.length!==0&&await d.invoke("plugin:velesdb|delete_points",{request:{collection:this.collectionName,ids:e}})}async flush(){await d.invoke("plugin:velesdb|flush",{name:this.collectionName}),await d.invoke("semantic_search_write_hnsw_marker",{collectionName:this.collectionName}).catch(()=>{})}}const M="replay_search",me=384,w={added:0,updated:0,removed:0,unchanged:0};function k(t){return t.added+t.updated>0}class ye extends H.Observable{initialized=!1;projectId=null;indexer=null;indexQueue=Promise.resolve();get collectionName(){return this.projectId?`${M}_${this.projectId}`:M}createIndexer(){const e=new he(this.collectionName);return e.subscribe("indexing-activity",n=>{this.emit("indexing-activity",n)}),e}getIndexer(){return this.indexer||(this.indexer=this.createIndexer()),this.indexer}getIndexingActivityState(){return this.getIndexer().getIndexingActivityState()}async ensureInitialized(){this.initialized||await this.init()}enqueueIndex(e,n){const s=this.indexQueue.then(()=>e()).then(async i=>(n(i)&&await this.unloadModel(),i)).catch(async i=>{throw console.error("Semantic index:",i),await this.unloadModel(),i});return this.indexQueue=s.catch(()=>{}),s}async unloadModel(){try{await d.invoke("semantic_search_unload_model")}catch{}}setProject(e){this.projectId!==e&&(this.projectId=e,this.initialized=!1,this.indexer=this.createIndexer())}async init(){if(d.isTauriApp()&&!this.initialized){try{if((await d.invoke("plugin:velesdb|list_collections"))?.some(n=>n.name===this.collectionName)){this.initialized=!0;return}}catch{}await d.invoke("plugin:velesdb|create_collection",{request:{name:this.collectionName,dimension:me,metric:"cosine",storage_mode:"full"}}),this.initialized=!0}}async indexApis(e){if(!d.isTauriApp())return w;const n=this.collectionName,o=this.getIndexer(),s=G(e),i={apiIds:e.map(r=>r.id)};return await this.ensureInitialized(),this.enqueueIndex(async()=>this.collectionName!==n?w:o.indexDocuments(s,i),k)}async indexCollections(e){if(!d.isTauriApp())return w;const n=this.collectionName,o=this.getIndexer(),s=K(e),i={collectionIds:e.map(r=>r.id)};return await this.ensureInitialized(),this.enqueueIndex(async()=>this.collectionName!==n?w:o.indexDocuments(s,i),k)}async removeApi(e){if(!d.isTauriApp())return;const n=this.getIndexer();await this.ensureInitialized(),await this.enqueueIndex(()=>n.removeByPayloadFilter("apiId",e),()=>!1)}async removeCollection(e){if(!d.isTauriApp())return;const n=this.getIndexer();await this.ensureInitialized(),await this.enqueueIndex(()=>n.removeByPayloadFilter("collectionId",e),()=>!1)}async reindex(e){if(!d.isTauriApp())return w;const n=this.collectionName,o=this.getIndexer();return await this.ensureInitialized(),this.enqueueIndex(async()=>{if(this.collectionName!==n)return w;const{apis:s,collections:i}=e(),r=de(s,i);return o.indexDocuments(r,fe)},k)}async search(e,n=10,o){if(!d.isTauriApp())return[];try{await this.ensureInitialized();const s=o&&Object.keys(o).length>0?{type:o.type,apiId:o.apiId,collectionId:o.collectionId,path:o.path,method:o.method,operationId:o.operationId,workflowId:o.workflowId,stepId:o.stepId}:void 0,r=((await d.invoke("semantic_search_text",{collection:this.collectionName,query:e,topK:n,filters:s})).results??[]).map(c=>({...c.payload,score:c.score??0}));return await this.enrichWithRelatedSecurity(r),r}catch{return[]}}async enrichWithRelatedSecurity(e){const n=e.filter(i=>i.type==="api_operation"&&i.securitySchemeRefs?.length);if(n.length===0)return;const o=[...new Set(n.flatMap(i=>i.securitySchemeRefs??[]))],s=await this.getIndexer().getDocumentsByIds(o);for(const i of n){const r=[];for(const c of i.securitySchemeRefs??[]){const a=s.get(c);a?.securityScheme&&r.push(a.securityScheme)}r.length>0&&(i.relatedSecuritySchemes=r)}}async status(){if(!d.isTauriApp())return{indexed:0,modelLoaded:!1};const e=await this.getIndexer().getStoredDocumentCount();let n=!1;try{n=(await d.invoke("semantic_search_model_status")).loaded}catch{}return{indexed:e,modelLoaded:n}}async clear(){if(!(!d.isTauriApp()||!this.initialized))try{await d.invoke("plugin:velesdb|delete_collection",{name:this.collectionName}),this.initialized=!1}catch{}}async preloadModel(){if(d.isTauriApp())try{await d.invoke("semantic_search_preload_model")}catch{}}}let O=null;function xe(){return O||(O=new ye),O}exports.extractApiDocument=L;exports.extractCollectionDocument=W;exports.extractGlobalSecuritySchemes=F;exports.extractOperationDocument=D;exports.extractStepDocument=X;exports.extractWorkflowDocument=Q;exports.getSemanticSearchService=xe;
@@ -1,4 +1,4 @@
1
- import { i as Qe } from "./replay-index-BCz452N6.js";
1
+ import { i as Qe } from "./replay-index-4TEahAPK.js";
2
2
  import { h as Ve } from "./replay-history.schema-B0lLwmdG.js";
3
3
  import { s as Ue } from "./replay-step-context.schema-BOprzd6Z.js";
4
4
  import { b as J, c as X, a as ee } from "./replay-ai-message-parts.schema-DKLf0SiG.js";