@eventcatalog/sdk 2.2.1 → 2.2.2

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.
@@ -0,0 +1,1445 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/eventcatalog.ts
31
+ var eventcatalog_exports = {};
32
+ __export(eventcatalog_exports, {
33
+ dumpCatalog: () => dumpCatalog
34
+ });
35
+ module.exports = __toCommonJS(eventcatalog_exports);
36
+ var import_fs = __toESM(require("fs"));
37
+ var import_node_path12 = __toESM(require("path"));
38
+
39
+ // src/index.ts
40
+ var import_node_path11 = require("path");
41
+
42
+ // src/events.ts
43
+ var import_promises2 = __toESM(require("fs/promises"));
44
+ var import_node_path2 = require("path");
45
+
46
+ // src/internal/utils.ts
47
+ var import_glob = require("glob");
48
+ var import_node_fs = __toESM(require("fs"));
49
+ var import_fs_extra = require("fs-extra");
50
+ var import_node_path = require("path");
51
+ var import_gray_matter = __toESM(require("gray-matter"));
52
+ var import_semver = require("semver");
53
+ var versionExists = async (catalogDir, id, version) => {
54
+ const files = await getFiles(`${catalogDir}/**/index.{md,mdx}`);
55
+ const matchedFiles = await searchFilesForId(files, id, version) || [];
56
+ return matchedFiles.length > 0;
57
+ };
58
+ var findFileById = async (catalogDir, id, version) => {
59
+ const files = await getFiles(`${catalogDir}/**/index.{md,mdx}`);
60
+ const matchedFiles = await searchFilesForId(files, id) || [];
61
+ const latestVersion = matchedFiles.find((path4) => !path4.includes("versioned"));
62
+ if (!version) {
63
+ return latestVersion;
64
+ }
65
+ const parsedFiles = matchedFiles.map((path4) => {
66
+ const { data } = import_gray_matter.default.read(path4);
67
+ return { ...data, path: path4 };
68
+ });
69
+ const semverRange = (0, import_semver.validRange)(version);
70
+ if (semverRange && (0, import_semver.valid)(version)) {
71
+ const match2 = parsedFiles.filter((c) => (0, import_semver.satisfies)(c.version, semverRange));
72
+ return match2.length > 0 ? match2[0].path : void 0;
73
+ }
74
+ const sorted = parsedFiles.sort((a, b) => {
75
+ return a.version.localeCompare(b.version);
76
+ });
77
+ const match = sorted.length > 0 ? [sorted[sorted.length - 1]] : [];
78
+ if (match.length > 0) {
79
+ return match[0].path;
80
+ }
81
+ };
82
+ var getFiles = async (pattern, ignore = "") => {
83
+ try {
84
+ const ignoreList = Array.isArray(ignore) ? ignore : [ignore];
85
+ const files = (0, import_glob.globSync)(pattern, { ignore: ["node_modules/**", ...ignoreList] });
86
+ return files;
87
+ } catch (error) {
88
+ throw new Error(`Error finding files: ${error}`);
89
+ }
90
+ };
91
+ var readMdxFile = async (path4) => {
92
+ const { data } = import_gray_matter.default.read(path4);
93
+ const { markdown, ...frontmatter } = data;
94
+ return { ...frontmatter, markdown };
95
+ };
96
+ var searchFilesForId = async (files, id, version) => {
97
+ const idRegex = new RegExp(`^id:\\s*(['"]|>-)?\\s*${id}['"]?\\s*$`, "m");
98
+ const versionRegex = new RegExp(`^version:\\s*['"]?${version}['"]?\\s*$`, "m");
99
+ const matches = files.map((file) => {
100
+ const content = import_node_fs.default.readFileSync(file, "utf-8");
101
+ const hasIdMatch = content.match(idRegex);
102
+ if (version && !content.match(versionRegex)) {
103
+ return void 0;
104
+ }
105
+ if (hasIdMatch) {
106
+ return file;
107
+ }
108
+ });
109
+ return matches.filter(Boolean).filter((file) => file !== void 0);
110
+ };
111
+ var copyDir = async (catalogDir, source, target, filter) => {
112
+ const tmpDirectory = (0, import_node_path.join)(catalogDir, "tmp");
113
+ import_node_fs.default.mkdirSync(tmpDirectory, { recursive: true });
114
+ await (0, import_fs_extra.copy)(source, tmpDirectory, {
115
+ overwrite: true,
116
+ filter
117
+ });
118
+ await (0, import_fs_extra.copy)(tmpDirectory, target, {
119
+ overwrite: true,
120
+ filter
121
+ });
122
+ import_node_fs.default.rmSync(tmpDirectory, { recursive: true });
123
+ };
124
+ var uniqueVersions = (messages) => {
125
+ const uniqueSet = /* @__PURE__ */ new Set();
126
+ return messages.filter((message) => {
127
+ const key = `${message.id}-${message.version}`;
128
+ if (!uniqueSet.has(key)) {
129
+ uniqueSet.add(key);
130
+ return true;
131
+ }
132
+ return false;
133
+ });
134
+ };
135
+
136
+ // src/internal/resources.ts
137
+ var import_path = require("path");
138
+ var import_gray_matter2 = __toESM(require("gray-matter"));
139
+ var import_promises = __toESM(require("fs/promises"));
140
+ var import_node_fs2 = __toESM(require("fs"));
141
+ var import_semver2 = require("semver");
142
+ var import_proper_lockfile = require("proper-lockfile");
143
+ var versionResource = async (catalogDir, id) => {
144
+ const files = await getFiles(`${catalogDir}/**/index.{md,mdx}`);
145
+ const matchedFiles = await searchFilesForId(files, id);
146
+ if (matchedFiles.length === 0) {
147
+ throw new Error(`No resource found with id: ${id}`);
148
+ }
149
+ const file = matchedFiles[0];
150
+ const sourceDirectory = (0, import_path.dirname)(file);
151
+ const { data: { version = "0.0.1" } = {} } = import_gray_matter2.default.read(file);
152
+ const targetDirectory = getVersionedDirectory(sourceDirectory, version);
153
+ import_node_fs2.default.mkdirSync(targetDirectory, { recursive: true });
154
+ await copyDir(catalogDir, sourceDirectory, targetDirectory, (src) => {
155
+ return !src.includes("versioned");
156
+ });
157
+ await import_promises.default.readdir(sourceDirectory).then(async (resourceFiles) => {
158
+ await Promise.all(
159
+ resourceFiles.map(async (file2) => {
160
+ if (file2 !== "versioned") {
161
+ import_node_fs2.default.rmSync((0, import_path.join)(sourceDirectory, file2), { recursive: true });
162
+ }
163
+ })
164
+ );
165
+ });
166
+ };
167
+ var writeResource = async (catalogDir, resource, options = {
168
+ path: "",
169
+ type: "",
170
+ override: false,
171
+ versionExistingContent: false
172
+ }) => {
173
+ const path4 = options.path || `/${resource.id}`;
174
+ const fullPath = (0, import_path.join)(catalogDir, path4);
175
+ import_node_fs2.default.mkdirSync(fullPath, { recursive: true });
176
+ const lockPath = (0, import_path.join)(fullPath, "index.mdx");
177
+ if (!import_node_fs2.default.existsSync(lockPath)) {
178
+ import_node_fs2.default.writeFileSync(lockPath, "");
179
+ }
180
+ try {
181
+ await (0, import_proper_lockfile.lock)(lockPath, {
182
+ retries: 5,
183
+ stale: 1e4
184
+ // 10 seconds
185
+ });
186
+ const exists = await versionExists(catalogDir, resource.id, resource.version);
187
+ if (exists && !options.override) {
188
+ throw new Error(`Failed to write ${resource.id} (${options.type}) as the version ${resource.version} already exists`);
189
+ }
190
+ const { markdown, ...frontmatter } = resource;
191
+ if (options.versionExistingContent && !exists) {
192
+ const currentResource = await getResource(catalogDir, resource.id);
193
+ if (currentResource) {
194
+ if ((0, import_semver2.satisfies)(resource.version, `>${currentResource.version}`)) {
195
+ await versionResource(catalogDir, resource.id);
196
+ } else {
197
+ throw new Error(`New version ${resource.version} is not greater than current version ${currentResource.version}`);
198
+ }
199
+ }
200
+ }
201
+ const document = import_gray_matter2.default.stringify(markdown.trim(), frontmatter);
202
+ import_node_fs2.default.writeFileSync(lockPath, document);
203
+ } finally {
204
+ await (0, import_proper_lockfile.unlock)(lockPath).catch(() => {
205
+ });
206
+ }
207
+ };
208
+ var getResource = async (catalogDir, id, version, options) => {
209
+ const file = await findFileById(catalogDir, id, version);
210
+ if (!file) return;
211
+ const { data, content } = import_gray_matter2.default.read(file);
212
+ return {
213
+ ...data,
214
+ markdown: content.trim()
215
+ };
216
+ };
217
+ var getResourcePath = async (catalogDir, id, version) => {
218
+ const file = await findFileById(catalogDir, id, version);
219
+ if (!file) return;
220
+ return {
221
+ fullPath: file,
222
+ relativePath: file.replace(catalogDir, ""),
223
+ directory: (0, import_path.dirname)(file.replace(catalogDir, ""))
224
+ };
225
+ };
226
+ var getResources = async (catalogDir, {
227
+ type,
228
+ latestOnly = false,
229
+ ignore = [],
230
+ pattern = ""
231
+ }) => {
232
+ const ignoreList = latestOnly ? `**/versioned/**` : "";
233
+ const filePattern = pattern || `${catalogDir}/**/${type}/**/index.{md,mdx}`;
234
+ const files = await getFiles(filePattern, [ignoreList, ...ignore]);
235
+ if (files.length === 0) return;
236
+ return files.map((file) => {
237
+ const { data, content } = import_gray_matter2.default.read(file);
238
+ return {
239
+ ...data,
240
+ markdown: content.trim()
241
+ };
242
+ });
243
+ };
244
+ var rmResourceById = async (catalogDir, id, version, options) => {
245
+ const files = await getFiles(`${catalogDir}/**/index.{md,mdx}`);
246
+ const matchedFiles = await searchFilesForId(files, id, version);
247
+ if (matchedFiles.length === 0) {
248
+ throw new Error(`No ${options?.type || "resource"} found with id: ${id}`);
249
+ }
250
+ if (options?.persistFiles) {
251
+ await Promise.all(
252
+ matchedFiles.map(async (file) => {
253
+ await import_promises.default.rm(file, { recursive: true });
254
+ })
255
+ );
256
+ } else {
257
+ await Promise.all(
258
+ matchedFiles.map(async (file) => {
259
+ const directory = (0, import_path.dirname)(file);
260
+ await import_promises.default.rm(directory, { recursive: true, force: true });
261
+ })
262
+ );
263
+ }
264
+ };
265
+ var addFileToResource = async (catalogDir, id, file, version) => {
266
+ const pathToResource = await findFileById(catalogDir, id, version);
267
+ if (!pathToResource) throw new Error("Cannot find directory to write file to");
268
+ import_node_fs2.default.writeFileSync((0, import_path.join)((0, import_path.dirname)(pathToResource), file.fileName), file.content);
269
+ };
270
+ var getFileFromResource = async (catalogDir, id, file, version) => {
271
+ const pathToResource = await findFileById(catalogDir, id, version);
272
+ if (!pathToResource) throw new Error("Cannot find directory of resource");
273
+ const exists = await import_promises.default.access((0, import_path.join)((0, import_path.dirname)(pathToResource), file.fileName)).then(() => true).catch(() => false);
274
+ if (!exists) throw new Error(`File ${file.fileName} does not exist in resource ${id} v(${version})`);
275
+ return import_node_fs2.default.readFileSync((0, import_path.join)((0, import_path.dirname)(pathToResource), file.fileName), "utf-8");
276
+ };
277
+ var getVersionedDirectory = (sourceDirectory, version) => {
278
+ return (0, import_path.join)(sourceDirectory, "versioned", version);
279
+ };
280
+
281
+ // src/events.ts
282
+ var getEvent = (directory) => async (id, version) => getResource(directory, id, version, { type: "event" });
283
+ var getEvents = (directory) => async (options) => getResources(directory, { type: "events", ...options });
284
+ var writeEvent = (directory) => async (event, options = { path: "", override: false }) => writeResource(directory, { ...event }, { ...options, type: "event" });
285
+ var writeEventToService = (directory) => async (event, service, options = { path: "" }) => {
286
+ const resourcePath = await getResourcePath(directory, service.id, service.version);
287
+ if (!resourcePath) {
288
+ throw new Error("Service not found");
289
+ }
290
+ let pathForEvent = service.version && service.version !== "latest" ? `${resourcePath.directory}/versioned/${service.version}/events` : `${resourcePath.directory}/events`;
291
+ pathForEvent = (0, import_node_path2.join)(pathForEvent, event.id);
292
+ await writeResource(directory, { ...event }, { ...options, path: pathForEvent, type: "event" });
293
+ };
294
+ var rmEvent = (directory) => async (path4) => {
295
+ await import_promises2.default.rm((0, import_node_path2.join)(directory, path4), { recursive: true });
296
+ };
297
+ var rmEventById = (directory) => async (id, version, persistFiles) => {
298
+ await rmResourceById(directory, id, version, { type: "event", persistFiles });
299
+ };
300
+ var versionEvent = (directory) => async (id) => versionResource(directory, id);
301
+ var addFileToEvent = (directory) => async (id, file, version) => addFileToResource(directory, id, file, version);
302
+ var addSchemaToEvent = (directory) => async (id, schema, version) => {
303
+ await addFileToEvent(directory)(id, { content: schema.schema, fileName: schema.fileName }, version);
304
+ };
305
+ var eventHasVersion = (directory) => async (id, version) => {
306
+ const file = await findFileById(directory, id, version);
307
+ return !!file;
308
+ };
309
+
310
+ // src/commands.ts
311
+ var import_promises3 = __toESM(require("fs/promises"));
312
+ var import_node_path3 = require("path");
313
+ var getCommand = (directory) => async (id, version) => getResource(directory, id, version, { type: "command" });
314
+ var getCommands = (directory) => async (options) => getResources(directory, { type: "commands", ...options });
315
+ var writeCommand = (directory) => async (command, options = { path: "" }) => writeResource(directory, { ...command }, { ...options, type: "command" });
316
+ var writeCommandToService = (directory) => async (command, service, options = { path: "" }) => {
317
+ const resourcePath = await getResourcePath(directory, service.id, service.version);
318
+ if (!resourcePath) {
319
+ throw new Error("Service not found");
320
+ }
321
+ let pathForCommand = service.version && service.version !== "latest" ? `${resourcePath.directory}/versioned/${service.version}/commands` : `${resourcePath.directory}/commands`;
322
+ pathForCommand = (0, import_node_path3.join)(pathForCommand, command.id);
323
+ await writeResource(directory, { ...command }, { ...options, path: pathForCommand, type: "command" });
324
+ };
325
+ var rmCommand = (directory) => async (path4) => {
326
+ await import_promises3.default.rm((0, import_node_path3.join)(directory, path4), { recursive: true });
327
+ };
328
+ var rmCommandById = (directory) => async (id, version, persistFiles) => rmResourceById(directory, id, version, { type: "command", persistFiles });
329
+ var versionCommand = (directory) => async (id) => versionResource(directory, id);
330
+ var addFileToCommand = (directory) => async (id, file, version) => addFileToResource(directory, id, file, version);
331
+ var addSchemaToCommand = (directory) => async (id, schema, version) => {
332
+ await addFileToCommand(directory)(id, { content: schema.schema, fileName: schema.fileName }, version);
333
+ };
334
+ var commandHasVersion = (directory) => async (id, version) => {
335
+ const file = await findFileById(directory, id, version);
336
+ return !!file;
337
+ };
338
+
339
+ // src/queries.ts
340
+ var import_promises4 = __toESM(require("fs/promises"));
341
+ var import_node_path4 = require("path");
342
+ var getQuery = (directory) => async (id, version) => getResource(directory, id, version, { type: "query" });
343
+ var writeQuery = (directory) => async (query, options = { path: "" }) => writeResource(directory, { ...query }, { ...options, type: "query" });
344
+ var getQueries = (directory) => async (options) => getResources(directory, { type: "queries", ...options });
345
+ var writeQueryToService = (directory) => async (query, service, options = { path: "" }) => {
346
+ const resourcePath = await getResourcePath(directory, service.id, service.version);
347
+ if (!resourcePath) {
348
+ throw new Error("Service not found");
349
+ }
350
+ let pathForQuery = service.version && service.version !== "latest" ? `${resourcePath.directory}/versioned/${service.version}/queries` : `${resourcePath.directory}/queries`;
351
+ pathForQuery = (0, import_node_path4.join)(pathForQuery, query.id);
352
+ await writeResource(directory, { ...query }, { ...options, path: pathForQuery, type: "query" });
353
+ };
354
+ var rmQuery = (directory) => async (path4) => {
355
+ await import_promises4.default.rm((0, import_node_path4.join)(directory, path4), { recursive: true });
356
+ };
357
+ var rmQueryById = (directory) => async (id, version, persistFiles) => {
358
+ await rmResourceById(directory, id, version, { type: "query", persistFiles });
359
+ };
360
+ var versionQuery = (directory) => async (id) => versionResource(directory, id);
361
+ var addFileToQuery = (directory) => async (id, file, version) => addFileToResource(directory, id, file, version);
362
+ var addSchemaToQuery = (directory) => async (id, schema, version) => {
363
+ await addFileToQuery(directory)(id, { content: schema.schema, fileName: schema.fileName }, version);
364
+ };
365
+ var queryHasVersion = (directory) => async (id, version) => {
366
+ const file = await findFileById(directory, id, version);
367
+ return !!file;
368
+ };
369
+
370
+ // src/services.ts
371
+ var import_promises5 = __toESM(require("fs/promises"));
372
+ var import_node_path5 = require("path");
373
+ var getService = (directory) => async (id, version) => getResource(directory, id, version, { type: "service" });
374
+ var getServices = (directory) => async (options) => getResources(directory, {
375
+ type: "services",
376
+ ignore: ["**/events/**", "**/commands/**", "**/queries/**"],
377
+ ...options
378
+ });
379
+ var writeService = (directory) => async (service, options = { path: "" }) => {
380
+ const resource = { ...service };
381
+ if (Array.isArray(service.sends)) {
382
+ resource.sends = uniqueVersions(service.sends);
383
+ }
384
+ if (Array.isArray(service.receives)) {
385
+ resource.receives = uniqueVersions(service.receives);
386
+ }
387
+ return await writeResource(directory, resource, { ...options, type: "service" });
388
+ };
389
+ var writeVersionedService = (directory) => async (service) => {
390
+ const resource = { ...service };
391
+ const path4 = getVersionedDirectory(service.id, service.version);
392
+ return await writeService(directory)(resource, { path: path4 });
393
+ };
394
+ var writeServiceToDomain = (directory) => async (service, domain, options = { path: "" }) => {
395
+ let pathForService = domain.version && domain.version !== "latest" ? `/${domain.id}/versioned/${domain.version}/services` : `/${domain.id}/services`;
396
+ pathForService = (0, import_node_path5.join)(pathForService, service.id);
397
+ await writeResource(directory, { ...service }, { ...options, path: pathForService, type: "service" });
398
+ };
399
+ var versionService = (directory) => async (id) => versionResource(directory, id);
400
+ var rmService = (directory) => async (path4) => {
401
+ await import_promises5.default.rm((0, import_node_path5.join)(directory, path4), { recursive: true });
402
+ };
403
+ var rmServiceById = (directory) => async (id, version, persistFiles) => rmResourceById(directory, id, version, { type: "service", persistFiles });
404
+ var addFileToService = (directory) => async (id, file, version) => addFileToResource(directory, id, file, version);
405
+ var getSpecificationFilesForService = (directory) => async (id, version) => {
406
+ let service = await getService(directory)(id, version);
407
+ const filePathToService = await findFileById(directory, id, version);
408
+ if (!filePathToService) throw new Error("Cannot find directory of service");
409
+ let specs = [];
410
+ if (service.specifications) {
411
+ const serviceSpecifications = service.specifications;
412
+ const specificationFiles = Object.keys(serviceSpecifications);
413
+ const getSpecs = specificationFiles.map(async (specFile) => {
414
+ const fileName = serviceSpecifications[specFile];
415
+ if (!fileName) {
416
+ throw new Error(`Specification file name for ${specFile} is undefined`);
417
+ }
418
+ const rawFile = await getFileFromResource(directory, id, { fileName }, version);
419
+ return { key: specFile, content: rawFile, fileName, path: (0, import_node_path5.join)((0, import_node_path5.dirname)(filePathToService), fileName) };
420
+ });
421
+ specs = await Promise.all(getSpecs);
422
+ }
423
+ return specs;
424
+ };
425
+ var addMessageToService = (directory) => async (id, direction, event, version) => {
426
+ let service = await getService(directory)(id, version);
427
+ if (direction === "sends") {
428
+ if (service.sends === void 0) {
429
+ service.sends = [];
430
+ }
431
+ for (let i = 0; i < service.sends.length; i++) {
432
+ if (service.sends[i].id === event.id && service.sends[i].version === event.version) {
433
+ return;
434
+ }
435
+ }
436
+ service.sends.push({ id: event.id, version: event.version });
437
+ } else if (direction === "receives") {
438
+ if (service.receives === void 0) {
439
+ service.receives = [];
440
+ }
441
+ for (let i = 0; i < service.receives.length; i++) {
442
+ if (service.receives[i].id === event.id && service.receives[i].version === event.version) {
443
+ return;
444
+ }
445
+ }
446
+ service.receives.push({ id: event.id, version: event.version });
447
+ } else {
448
+ throw new Error(`Direction ${direction} is invalid, only 'receives' and 'sends' are supported`);
449
+ }
450
+ const existingResource = await findFileById(directory, id, version);
451
+ if (!existingResource) {
452
+ throw new Error(`Cannot find service ${id} in the catalog`);
453
+ }
454
+ const path4 = existingResource.split("/services")[0];
455
+ const pathToResource = (0, import_node_path5.join)(path4, "services");
456
+ await rmServiceById(directory)(id, version);
457
+ await writeService(pathToResource)(service);
458
+ };
459
+ var serviceHasVersion = (directory) => async (id, version) => {
460
+ const file = await findFileById(directory, id, version);
461
+ return !!file;
462
+ };
463
+
464
+ // src/domains.ts
465
+ var import_promises6 = __toESM(require("fs/promises"));
466
+ var import_node_path6 = __toESM(require("path"));
467
+ var import_node_fs3 = __toESM(require("fs"));
468
+ var import_gray_matter3 = __toESM(require("gray-matter"));
469
+ var getDomain = (directory) => async (id, version) => getResource(directory, id, version, { type: "domain" });
470
+ var getDomains = (directory) => async (options) => getResources(directory, {
471
+ type: "domains",
472
+ ignore: ["**/services/**", "**/events/**", "**/commands/**", "**/queries/**", "**/flows/**"],
473
+ ...options
474
+ });
475
+ var writeDomain = (directory) => async (domain, options = { path: "" }) => {
476
+ const resource = { ...domain };
477
+ if (Array.isArray(domain.services)) {
478
+ resource.services = uniqueVersions(domain.services);
479
+ }
480
+ return await writeResource(directory, resource, { ...options, type: "domain" });
481
+ };
482
+ var versionDomain = (directory) => async (id) => versionResource(directory, id);
483
+ var rmDomain = (directory) => async (path4) => {
484
+ await import_promises6.default.rm((0, import_node_path6.join)(directory, path4), { recursive: true });
485
+ };
486
+ var rmDomainById = (directory) => async (id, version, persistFiles) => rmResourceById(directory, id, version, { type: "domain", persistFiles });
487
+ var addFileToDomain = (directory) => async (id, file, version) => addFileToResource(directory, id, file, version);
488
+ var addUbiquitousLanguageToDomain = (directory) => async (id, ubiquitousLanguageDictionary, version) => {
489
+ const content = import_gray_matter3.default.stringify("", {
490
+ ...ubiquitousLanguageDictionary
491
+ });
492
+ await addFileToResource(directory, id, { content, fileName: "ubiquitous-language.mdx" }, version);
493
+ };
494
+ var getUbiquitousLanguageFromDomain = (directory) => async (id, version) => {
495
+ const pathToDomain = await findFileById(directory, id, version) || "";
496
+ const pathToUbiquitousLanguage = import_node_path6.default.join(import_node_path6.default.dirname(pathToDomain), "ubiquitous-language.mdx");
497
+ const fileExists = import_node_fs3.default.existsSync(pathToUbiquitousLanguage);
498
+ if (!fileExists) {
499
+ return void 0;
500
+ }
501
+ const content = await readMdxFile(pathToUbiquitousLanguage);
502
+ return content;
503
+ };
504
+ var domainHasVersion = (directory) => async (id, version) => {
505
+ const file = await findFileById(directory, id, version);
506
+ return !!file;
507
+ };
508
+ var addServiceToDomain = (directory) => async (id, service, version) => {
509
+ let domain = await getDomain(directory)(id, version);
510
+ if (domain.services === void 0) {
511
+ domain.services = [];
512
+ }
513
+ const serviceExistsInList = domain.services.some((s) => s.id === service.id && s.version === service.version);
514
+ if (serviceExistsInList) {
515
+ return;
516
+ }
517
+ domain.services.push(service);
518
+ await rmDomainById(directory)(id, version, true);
519
+ await writeDomain(directory)(domain);
520
+ };
521
+
522
+ // src/channels.ts
523
+ var import_promises7 = __toESM(require("fs/promises"));
524
+ var import_node_path7 = require("path");
525
+ var getChannel = (directory) => async (id, version) => getResource(directory, id, version, { type: "channel" });
526
+ var getChannels = (directory) => async (options) => getResources(directory, { type: "channels", ...options });
527
+ var writeChannel = (directory) => async (channel, options = { path: "" }) => writeResource(directory, { ...channel }, { ...options, type: "channel" });
528
+ var rmChannel = (directory) => async (path4) => {
529
+ await import_promises7.default.rm((0, import_node_path7.join)(directory, path4), { recursive: true });
530
+ };
531
+ var rmChannelById = (directory) => async (id, version, persistFiles) => rmResourceById(directory, id, version, { type: "channel", persistFiles });
532
+ var versionChannel = (directory) => async (id) => versionResource(directory, id);
533
+ var channelHasVersion = (directory) => async (id, version) => {
534
+ const file = await findFileById(directory, id, version);
535
+ return !!file;
536
+ };
537
+ var addMessageToChannel = (directory, collection) => async (id, _message, version) => {
538
+ let channel = await getChannel(directory)(id, version);
539
+ const functions = {
540
+ events: {
541
+ getMessage: getEvent,
542
+ rmMessageById: rmEventById,
543
+ writeMessage: writeEvent
544
+ },
545
+ commands: {
546
+ getMessage: getCommand,
547
+ rmMessageById: rmCommandById,
548
+ writeMessage: writeCommand
549
+ },
550
+ queries: {
551
+ getMessage: getQuery,
552
+ rmMessageById: rmQueryById,
553
+ writeMessage: writeQuery
554
+ }
555
+ };
556
+ const { getMessage, rmMessageById, writeMessage } = functions[collection];
557
+ const message = await getMessage(directory)(_message.id, _message.version);
558
+ if (!message) throw new Error(`Message ${_message.id} with version ${_message.version} not found`);
559
+ if (message.channels === void 0) {
560
+ message.channels = [];
561
+ }
562
+ const channelInfo = { id, version: channel.version, ..._message.parameters && { parameters: _message.parameters } };
563
+ message.channels.push(channelInfo);
564
+ const existingResource = await findFileById(directory, _message.id, _message.version);
565
+ if (!existingResource) {
566
+ throw new Error(`Cannot find message ${id} in the catalog`);
567
+ }
568
+ const path4 = existingResource.split(`/${collection}`)[0];
569
+ const pathToResource = (0, import_node_path7.join)(path4, collection);
570
+ await rmMessageById(directory)(_message.id, _message.version, true);
571
+ await writeMessage(pathToResource)(message);
572
+ };
573
+
574
+ // src/custom-docs.ts
575
+ var import_node_path8 = __toESM(require("path"));
576
+ var import_node_fs4 = __toESM(require("fs"));
577
+ var import_promises8 = __toESM(require("fs/promises"));
578
+ var import_gray_matter4 = __toESM(require("gray-matter"));
579
+ var import_slugify = __toESM(require("slugify"));
580
+ var getCustomDoc = (directory) => async (filePath) => {
581
+ const fullPath = import_node_path8.default.join(directory, filePath);
582
+ const fullPathWithExtension = fullPath.endsWith(".mdx") ? fullPath : `${fullPath}.mdx`;
583
+ const fileExists = import_node_fs4.default.existsSync(fullPathWithExtension);
584
+ if (!fileExists) {
585
+ return void 0;
586
+ }
587
+ return readMdxFile(fullPathWithExtension);
588
+ };
589
+ var getCustomDocs = (directory) => async (options) => {
590
+ if (options?.path) {
591
+ const pattern = `${directory}/${options.path}/**/*.{md,mdx}`;
592
+ return getResources(directory, { type: "docs", pattern });
593
+ }
594
+ return getResources(directory, { type: "docs", pattern: `${directory}/**/*.{md,mdx}` });
595
+ };
596
+ var writeCustomDoc = (directory) => async (customDoc, options = { path: "" }) => {
597
+ const { fileName, ...rest } = customDoc;
598
+ const name = fileName || (0, import_slugify.default)(customDoc.title, { lower: true });
599
+ const withExtension = name.endsWith(".mdx") ? name : `${name}.mdx`;
600
+ const fullPath = import_node_path8.default.join(directory, options.path || "", withExtension);
601
+ import_node_fs4.default.mkdirSync(import_node_path8.default.dirname(fullPath), { recursive: true });
602
+ const document = import_gray_matter4.default.stringify(customDoc.markdown.trim(), rest);
603
+ import_node_fs4.default.writeFileSync(fullPath, document);
604
+ };
605
+ var rmCustomDoc = (directory) => async (filePath) => {
606
+ const withExtension = filePath.endsWith(".mdx") ? filePath : `${filePath}.mdx`;
607
+ await import_promises8.default.rm((0, import_node_path8.join)(directory, withExtension), { recursive: true });
608
+ };
609
+
610
+ // src/teams.ts
611
+ var import_promises9 = __toESM(require("fs/promises"));
612
+ var import_node_fs5 = __toESM(require("fs"));
613
+ var import_node_path9 = require("path");
614
+ var import_gray_matter5 = __toESM(require("gray-matter"));
615
+ var getTeam = (catalogDir) => async (id) => {
616
+ const files = await getFiles(`${catalogDir}/${id}.{md,mdx}`);
617
+ if (files.length == 0) return void 0;
618
+ const file = files[0];
619
+ const { data, content } = import_gray_matter5.default.read(file);
620
+ return {
621
+ ...data,
622
+ id: data.id,
623
+ name: data.name,
624
+ markdown: content.trim()
625
+ };
626
+ };
627
+ var getTeams = (catalogDir) => async (options) => {
628
+ const files = await getFiles(`${catalogDir}/teams/*.{md,mdx}`);
629
+ if (files.length === 0) return [];
630
+ return files.map((file) => {
631
+ const { data, content } = import_gray_matter5.default.read(file);
632
+ return {
633
+ ...data,
634
+ id: data.id,
635
+ name: data.name,
636
+ markdown: content.trim()
637
+ };
638
+ });
639
+ };
640
+ var writeTeam = (catalogDir) => async (team, options = {}) => {
641
+ const resource = { ...team };
642
+ const currentTeam = await getTeam(catalogDir)(resource.id);
643
+ const exists = currentTeam !== void 0;
644
+ if (exists && !options.override) {
645
+ throw new Error(`Failed to write ${resource.id} (team) as it already exists`);
646
+ }
647
+ const { markdown, ...frontmatter } = resource;
648
+ const document = import_gray_matter5.default.stringify(markdown, frontmatter);
649
+ import_node_fs5.default.mkdirSync((0, import_node_path9.join)(catalogDir, ""), { recursive: true });
650
+ import_node_fs5.default.writeFileSync((0, import_node_path9.join)(catalogDir, "", `${resource.id}.mdx`), document);
651
+ };
652
+ var rmTeamById = (catalogDir) => async (id) => {
653
+ await import_promises9.default.rm((0, import_node_path9.join)(catalogDir, `${id}.mdx`), { recursive: true });
654
+ };
655
+
656
+ // src/users.ts
657
+ var import_node_fs6 = __toESM(require("fs"));
658
+ var import_node_path10 = require("path");
659
+ var import_gray_matter6 = __toESM(require("gray-matter"));
660
+ var getUser = (catalogDir) => async (id) => {
661
+ const files = await getFiles(`${catalogDir}/${id}.{md,mdx}`);
662
+ if (files.length == 0) return void 0;
663
+ const file = files[0];
664
+ const { data, content } = import_gray_matter6.default.read(file);
665
+ return {
666
+ ...data,
667
+ id: data.id,
668
+ name: data.name,
669
+ avatarUrl: data.avatarUrl,
670
+ markdown: content.trim()
671
+ };
672
+ };
673
+ var getUsers = (catalogDir) => async (options) => {
674
+ const files = await getFiles(`${catalogDir}/users/*.{md,mdx}`);
675
+ if (files.length === 0) return [];
676
+ return files.map((file) => {
677
+ const { data, content } = import_gray_matter6.default.read(file);
678
+ return {
679
+ ...data,
680
+ id: data.id,
681
+ name: data.name,
682
+ avatarUrl: data.avatarUrl,
683
+ markdown: content.trim()
684
+ };
685
+ });
686
+ };
687
+ var writeUser = (catalogDir) => async (user, options = {}) => {
688
+ const resource = { ...user };
689
+ const currentUser = await getUser(catalogDir)(resource.id);
690
+ const exists = currentUser !== void 0;
691
+ if (exists && !options.override) {
692
+ throw new Error(`Failed to write ${resource.id} (user) as it already exists`);
693
+ }
694
+ const { markdown, ...frontmatter } = resource;
695
+ const document = import_gray_matter6.default.stringify(markdown, frontmatter);
696
+ import_node_fs6.default.mkdirSync((0, import_node_path10.join)(catalogDir, ""), { recursive: true });
697
+ import_node_fs6.default.writeFileSync((0, import_node_path10.join)(catalogDir, "", `${resource.id}.mdx`), document);
698
+ };
699
+ var rmUserById = (catalogDir) => async (id) => {
700
+ import_node_fs6.default.rmSync((0, import_node_path10.join)(catalogDir, `${id}.mdx`), { recursive: true });
701
+ };
702
+
703
+ // src/index.ts
704
+ var index_default = (path4) => {
705
+ return {
706
+ /**
707
+ * Returns an events from EventCatalog
708
+ * @param id - The id of the event to retrieve
709
+ * @param version - Optional id of the version to get (supports semver)
710
+ * @returns Event|Undefined
711
+ */
712
+ getEvent: getEvent((0, import_node_path11.join)(path4)),
713
+ /**
714
+ * Returns all events from EventCatalog
715
+ * @param latestOnly - optional boolean, set to true to get only latest versions
716
+ * @returns Event[]|Undefined
717
+ */
718
+ getEvents: getEvents((0, import_node_path11.join)(path4)),
719
+ /**
720
+ * Adds an event to EventCatalog
721
+ *
722
+ * @param event - The event to write
723
+ * @param options - Optional options to write the event
724
+ *
725
+ */
726
+ writeEvent: writeEvent((0, import_node_path11.join)(path4, "events")),
727
+ /**
728
+ * Adds an event to a service in EventCatalog
729
+ *
730
+ * @param event - The event to write to the service
731
+ * @param service - The service and it's id to write to the event to
732
+ * @param options - Optional options to write the event
733
+ *
734
+ */
735
+ writeEventToService: writeEventToService((0, import_node_path11.join)(path4)),
736
+ /**
737
+ * Remove an event to EventCatalog (modeled on the standard POSIX rm utility)
738
+ *
739
+ * @param path - The path to your event, e.g. `/Inventory/InventoryAdjusted`
740
+ *
741
+ */
742
+ rmEvent: rmEvent((0, import_node_path11.join)(path4, "events")),
743
+ /**
744
+ * Remove an event by an Event id
745
+ *
746
+ * @param id - The id of the event you want to remove
747
+ *
748
+ */
749
+ rmEventById: rmEventById((0, import_node_path11.join)(path4)),
750
+ /**
751
+ * Moves a given event id to the version directory
752
+ * @param directory
753
+ */
754
+ versionEvent: versionEvent((0, import_node_path11.join)(path4)),
755
+ /**
756
+ * Adds a file to the given event
757
+ * @param id - The id of the event to add the file to
758
+ * @param file - File contents to add including the content and the file name
759
+ * @param version - Optional version of the event to add the file to
760
+ * @returns
761
+ */
762
+ addFileToEvent: addFileToEvent((0, import_node_path11.join)(path4)),
763
+ /**
764
+ * Adds a schema to the given event
765
+ * @param id - The id of the event to add the schema to
766
+ * @param schema - Schema contents to add including the content and the file name
767
+ * @param version - Optional version of the event to add the schema to
768
+ * @returns
769
+ */
770
+ addSchemaToEvent: addSchemaToEvent((0, import_node_path11.join)(path4)),
771
+ /**
772
+ * Check to see if an event version exists
773
+ * @param id - The id of the event
774
+ * @param version - The version of the event (supports semver)
775
+ * @returns
776
+ */
777
+ eventHasVersion: eventHasVersion((0, import_node_path11.join)(path4)),
778
+ /**
779
+ * ================================
780
+ * Commands
781
+ * ================================
782
+ */
783
+ /**
784
+ * Returns a command from EventCatalog
785
+ * @param id - The id of the command to retrieve
786
+ * @param version - Optional id of the version to get (supports semver)
787
+ * @returns Command|Undefined
788
+ */
789
+ getCommand: getCommand((0, import_node_path11.join)(path4)),
790
+ /**
791
+ * Returns all commands from EventCatalog
792
+ * @param latestOnly - optional boolean, set to true to get only latest versions
793
+ * @returns Command[]|Undefined
794
+ */
795
+ getCommands: getCommands((0, import_node_path11.join)(path4)),
796
+ /**
797
+ * Adds an command to EventCatalog
798
+ *
799
+ * @param command - The command to write
800
+ * @param options - Optional options to write the command
801
+ *
802
+ */
803
+ writeCommand: writeCommand((0, import_node_path11.join)(path4, "commands")),
804
+ /**
805
+ * Adds a command to a service in EventCatalog
806
+ *
807
+ * @param command - The command to write to the service
808
+ * @param service - The service and it's id to write to the command to
809
+ * @param options - Optional options to write the command
810
+ *
811
+ */
812
+ writeCommandToService: writeCommandToService((0, import_node_path11.join)(path4)),
813
+ /**
814
+ * Remove an command to EventCatalog (modeled on the standard POSIX rm utility)
815
+ *
816
+ * @param path - The path to your command, e.g. `/Inventory/InventoryAdjusted`
817
+ *
818
+ */
819
+ rmCommand: rmCommand((0, import_node_path11.join)(path4, "commands")),
820
+ /**
821
+ * Remove an command by an Event id
822
+ *
823
+ * @param id - The id of the command you want to remove
824
+ *
825
+ */
826
+ rmCommandById: rmCommandById((0, import_node_path11.join)(path4)),
827
+ /**
828
+ * Moves a given command id to the version directory
829
+ * @param directory
830
+ */
831
+ versionCommand: versionCommand((0, import_node_path11.join)(path4)),
832
+ /**
833
+ * Adds a file to the given command
834
+ * @param id - The id of the command to add the file to
835
+ * @param file - File contents to add including the content and the file name
836
+ * @param version - Optional version of the command to add the file to
837
+ * @returns
838
+ */
839
+ addFileToCommand: addFileToCommand((0, import_node_path11.join)(path4)),
840
+ /**
841
+ * Adds a schema to the given command
842
+ * @param id - The id of the command to add the schema to
843
+ * @param schema - Schema contents to add including the content and the file name
844
+ * @param version - Optional version of the command to add the schema to
845
+ * @returns
846
+ */
847
+ addSchemaToCommand: addSchemaToCommand((0, import_node_path11.join)(path4)),
848
+ /**
849
+ * Check to see if a command version exists
850
+ * @param id - The id of the command
851
+ * @param version - The version of the command (supports semver)
852
+ * @returns
853
+ */
854
+ commandHasVersion: commandHasVersion((0, import_node_path11.join)(path4)),
855
+ /**
856
+ * ================================
857
+ * Queries
858
+ * ================================
859
+ */
860
+ /**
861
+ * Returns a query from EventCatalog
862
+ * @param id - The id of the query to retrieve
863
+ * @param version - Optional id of the version to get (supports semver)
864
+ * @returns Query|Undefined
865
+ */
866
+ getQuery: getQuery((0, import_node_path11.join)(path4)),
867
+ /**
868
+ * Returns all queries from EventCatalog
869
+ * @param latestOnly - optional boolean, set to true to get only latest versions
870
+ * @returns Query[]|Undefined
871
+ */
872
+ getQueries: getQueries((0, import_node_path11.join)(path4)),
873
+ /**
874
+ * Adds a query to EventCatalog
875
+ *
876
+ * @param query - The query to write
877
+ * @param options - Optional options to write the event
878
+ *
879
+ */
880
+ writeQuery: writeQuery((0, import_node_path11.join)(path4, "queries")),
881
+ /**
882
+ * Adds a query to a service in EventCatalog
883
+ *
884
+ * @param query - The query to write to the service
885
+ * @param service - The service and it's id to write to the query to
886
+ * @param options - Optional options to write the query
887
+ *
888
+ */
889
+ writeQueryToService: writeQueryToService((0, import_node_path11.join)(path4)),
890
+ /**
891
+ * Remove an query to EventCatalog (modeled on the standard POSIX rm utility)
892
+ *
893
+ * @param path - The path to your query, e.g. `/Orders/GetOrder`
894
+ *
895
+ */
896
+ rmQuery: rmQuery((0, import_node_path11.join)(path4, "queries")),
897
+ /**
898
+ * Remove a query by a Query id
899
+ *
900
+ * @param id - The id of the query you want to remove
901
+ *
902
+ */
903
+ rmQueryById: rmQueryById((0, import_node_path11.join)(path4)),
904
+ /**
905
+ * Moves a given query id to the version directory
906
+ * @param directory
907
+ */
908
+ versionQuery: versionQuery((0, import_node_path11.join)(path4)),
909
+ /**
910
+ * Adds a file to the given query
911
+ * @param id - The id of the query to add the file to
912
+ * @param file - File contents to add including the content and the file name
913
+ * @param version - Optional version of the query to add the file to
914
+ * @returns
915
+ */
916
+ addFileToQuery: addFileToQuery((0, import_node_path11.join)(path4)),
917
+ /**
918
+ * Adds a schema to the given query
919
+ * @param id - The id of the query to add the schema to
920
+ * @param schema - Schema contents to add including the content and the file name
921
+ * @param version - Optional version of the query to add the schema to
922
+ * @returns
923
+ */
924
+ addSchemaToQuery: addSchemaToQuery((0, import_node_path11.join)(path4)),
925
+ /**
926
+ * Check to see if an query version exists
927
+ * @param id - The id of the query
928
+ * @param version - The version of the query (supports semver)
929
+ * @returns
930
+ */
931
+ queryHasVersion: queryHasVersion((0, import_node_path11.join)(path4)),
932
+ /**
933
+ * ================================
934
+ * Channels
935
+ * ================================
936
+ */
937
+ /**
938
+ * Returns a channel from EventCatalog
939
+ * @param id - The id of the channel to retrieve
940
+ * @param version - Optional id of the version to get (supports semver)
941
+ * @returns Channel|Undefined
942
+ */
943
+ getChannel: getChannel((0, import_node_path11.join)(path4)),
944
+ /**
945
+ * Returns all channels from EventCatalog
946
+ * @param latestOnly - optional boolean, set to true to get only latest versions
947
+ * @returns Channel[]|Undefined
948
+ */
949
+ getChannels: getChannels((0, import_node_path11.join)(path4)),
950
+ /**
951
+ * Adds an channel to EventCatalog
952
+ *
953
+ * @param command - The channel to write
954
+ * @param options - Optional options to write the channel
955
+ *
956
+ */
957
+ writeChannel: writeChannel((0, import_node_path11.join)(path4, "channels")),
958
+ /**
959
+ * Remove an channel to EventCatalog (modeled on the standard POSIX rm utility)
960
+ *
961
+ * @param path - The path to your channel, e.g. `/Inventory/InventoryAdjusted`
962
+ *
963
+ */
964
+ rmChannel: rmChannel((0, import_node_path11.join)(path4, "channels")),
965
+ /**
966
+ * Remove an channel by an Event id
967
+ *
968
+ * @param id - The id of the channel you want to remove
969
+ *
970
+ */
971
+ rmChannelById: rmChannelById((0, import_node_path11.join)(path4)),
972
+ /**
973
+ * Moves a given channel id to the version directory
974
+ * @param directory
975
+ */
976
+ versionChannel: versionChannel((0, import_node_path11.join)(path4)),
977
+ /**
978
+ * Check to see if a channel version exists
979
+ * @param id - The id of the channel
980
+ * @param version - The version of the channel (supports semver)
981
+ * @returns
982
+ */
983
+ channelHasVersion: channelHasVersion((0, import_node_path11.join)(path4)),
984
+ /**
985
+ * Add a channel to an event
986
+ *
987
+ * Optionally specify a version to add the channel to a specific version of the event.
988
+ *
989
+ * @example
990
+ * ```ts
991
+ * import utils from '@eventcatalog/utils';
992
+ *
993
+ * const { addEventToChannel } = utils('/path/to/eventcatalog');
994
+ *
995
+ * // adds a new event (InventoryUpdatedEvent) to the inventory.{env}.events channel
996
+ * await addEventToChannel('inventory.{env}.events channel', { id: 'InventoryUpdatedEvent', version: '2.0.0', parameters: { env: 'dev' } });
997
+ *
998
+ * ```
999
+ */
1000
+ addEventToChannel: addMessageToChannel((0, import_node_path11.join)(path4), "events"),
1001
+ /**
1002
+ * Add a channel to an command
1003
+ *
1004
+ * Optionally specify a version to add the channel to a specific version of the command.
1005
+ *
1006
+ * @example
1007
+ * ```ts
1008
+ * import utils from '@eventcatalog/utils';
1009
+ *
1010
+ * const { addCommandToChannel } = utils('/path/to/eventcatalog');
1011
+ *
1012
+ * // adds a new command (UpdateInventory) to the inventory.{env}.events channel
1013
+ * await addCommandToChannel('inventory.{env}.events channel', { id: 'UpdateInventory', version: '2.0.0', parameters: { env: 'dev' } });
1014
+ *
1015
+ * ```
1016
+ */
1017
+ addCommandToChannel: addMessageToChannel((0, import_node_path11.join)(path4), "commands"),
1018
+ /**
1019
+ * Add a channel to an query
1020
+ *
1021
+ * Optionally specify a version to add the channel to a specific version of the query.
1022
+ *
1023
+ * @example
1024
+ * ```ts
1025
+ * import utils from '@eventcatalog/utils';
1026
+ *
1027
+ * const { addQueryToChannel } = utils('/path/to/eventcatalog');
1028
+ *
1029
+ * // adds a new query (GetInventory) to the inventory.{env}.events channel
1030
+ * await addQueryToChannel('inventory.{env}.events channel', { id: 'GetInventory', version: '2.0.0', parameters: { env: 'dev' } });
1031
+ *
1032
+ * ```
1033
+ */
1034
+ addQueryToChannel: addMessageToChannel((0, import_node_path11.join)(path4), "queries"),
1035
+ /**
1036
+ * ================================
1037
+ * SERVICES
1038
+ * ================================
1039
+ */
1040
+ /**
1041
+ * Adds a service to EventCatalog
1042
+ *
1043
+ * @param service - The service to write
1044
+ * @param options - Optional options to write the event
1045
+ *
1046
+ */
1047
+ writeService: writeService((0, import_node_path11.join)(path4, "services")),
1048
+ /**
1049
+ * Adds a versioned service to EventCatalog
1050
+ *
1051
+ * @param service - The service to write
1052
+ *
1053
+ */
1054
+ writeVersionedService: writeVersionedService((0, import_node_path11.join)(path4, "services")),
1055
+ /**
1056
+ * Adds a service to a domain in EventCatalog
1057
+ *
1058
+ * @param service - The service to write
1059
+ * @param domain - The domain to add the service to
1060
+ * @param options - Optional options to write the event
1061
+ *
1062
+ */
1063
+ writeServiceToDomain: writeServiceToDomain((0, import_node_path11.join)(path4, "domains")),
1064
+ /**
1065
+ * Returns a service from EventCatalog
1066
+ * @param id - The id of the service to retrieve
1067
+ * @param version - Optional id of the version to get (supports semver)
1068
+ * @returns Service|Undefined
1069
+ */
1070
+ getService: getService((0, import_node_path11.join)(path4)),
1071
+ /**
1072
+ * Returns all services from EventCatalog
1073
+ * @param latestOnly - optional boolean, set to true to get only latest versions
1074
+ * @returns Service[]|Undefined
1075
+ */
1076
+ getServices: getServices((0, import_node_path11.join)(path4)),
1077
+ /**
1078
+ * Moves a given service id to the version directory
1079
+ * @param directory
1080
+ */
1081
+ versionService: versionService((0, import_node_path11.join)(path4)),
1082
+ /**
1083
+ * Remove a service from EventCatalog (modeled on the standard POSIX rm utility)
1084
+ *
1085
+ * @param path - The path to your service, e.g. `/InventoryService`
1086
+ *
1087
+ */
1088
+ rmService: rmService((0, import_node_path11.join)(path4, "services")),
1089
+ /**
1090
+ * Remove an service by an service id
1091
+ *
1092
+ * @param id - The id of the service you want to remove
1093
+ *
1094
+ */
1095
+ rmServiceById: rmServiceById((0, import_node_path11.join)(path4)),
1096
+ /**
1097
+ * Adds a file to the given service
1098
+ * @param id - The id of the service to add the file to
1099
+ * @param file - File contents to add including the content and the file name
1100
+ * @param version - Optional version of the service to add the file to
1101
+ * @returns
1102
+ */
1103
+ addFileToService: addFileToService((0, import_node_path11.join)(path4)),
1104
+ /**
1105
+ * Returns the specifications for a given service
1106
+ * @param id - The id of the service to retrieve the specifications for
1107
+ * @param version - Optional version of the service
1108
+ * @returns
1109
+ */
1110
+ getSpecificationFilesForService: getSpecificationFilesForService((0, import_node_path11.join)(path4)),
1111
+ /**
1112
+ * Check to see if a service version exists
1113
+ * @param id - The id of the service
1114
+ * @param version - The version of the service (supports semver)
1115
+ * @returns
1116
+ */
1117
+ serviceHasVersion: serviceHasVersion((0, import_node_path11.join)(path4)),
1118
+ /**
1119
+ * Add an event to a service by it's id.
1120
+ *
1121
+ * Optionally specify a version to add the event to a specific version of the service.
1122
+ *
1123
+ * @example
1124
+ * ```ts
1125
+ * import utils from '@eventcatalog/utils';
1126
+ *
1127
+ * const { addEventToService } = utils('/path/to/eventcatalog');
1128
+ *
1129
+ * // adds a new event (InventoryUpdatedEvent) that the InventoryService will send
1130
+ * await addEventToService('InventoryService', 'sends', { event: 'InventoryUpdatedEvent', version: '2.0.0' });
1131
+ *
1132
+ * // adds a new event (OrderComplete) that the InventoryService will receive
1133
+ * await addEventToService('InventoryService', 'receives', { event: 'OrderComplete', version: '2.0.0' });
1134
+ *
1135
+ * ```
1136
+ */
1137
+ addEventToService: addMessageToService((0, import_node_path11.join)(path4)),
1138
+ /**
1139
+ * Add a command to a service by it's id.
1140
+ *
1141
+ * Optionally specify a version to add the event to a specific version of the service.
1142
+ *
1143
+ * @example
1144
+ * ```ts
1145
+ * import utils from '@eventcatalog/utils';
1146
+ *
1147
+ * const { addCommandToService } = utils('/path/to/eventcatalog');
1148
+ *
1149
+ * // adds a new command (UpdateInventoryCommand) that the InventoryService will send
1150
+ * await addCommandToService('InventoryService', 'sends', { command: 'UpdateInventoryCommand', version: '2.0.0' });
1151
+ *
1152
+ * // adds a new command (VerifyInventory) that the InventoryService will receive
1153
+ * await addCommandToService('InventoryService', 'receives', { command: 'VerifyInventory', version: '2.0.0' });
1154
+ *
1155
+ * ```
1156
+ */
1157
+ addCommandToService: addMessageToService((0, import_node_path11.join)(path4)),
1158
+ /**
1159
+ * Add a query to a service by it's id.
1160
+ *
1161
+ * Optionally specify a version to add the event to a specific version of the service.
1162
+ *
1163
+ * @example
1164
+ * ```ts
1165
+ * import utils from '@eventcatalog/utils';
1166
+ *
1167
+ * const { addQueryToService } = utils('/path/to/eventcatalog');
1168
+ *
1169
+ * // adds a new query (UpdateInventory) that the InventoryService will send
1170
+ * await addQueryToService('InventoryService', 'sends', { command: 'UpdateInventory', version: '2.0.0' });
1171
+ *
1172
+ * // adds a new command (VerifyInventory) that the InventoryService will receive
1173
+ * await addQueryToService('InventoryService', 'receives', { command: 'VerifyInventory', version: '2.0.0' });
1174
+ *
1175
+ * ```
1176
+ */
1177
+ addQueryToService: addMessageToService((0, import_node_path11.join)(path4)),
1178
+ /**
1179
+ * ================================
1180
+ * Domains
1181
+ * ================================
1182
+ */
1183
+ /**
1184
+ * Adds a domain to EventCatalog
1185
+ *
1186
+ * @param domain - The domain to write
1187
+ * @param options - Optional options to write the event
1188
+ *
1189
+ */
1190
+ writeDomain: writeDomain((0, import_node_path11.join)(path4, "domains")),
1191
+ /**
1192
+ * Returns a domain from EventCatalog
1193
+ * @param id - The id of the domain to retrieve
1194
+ * @param version - Optional id of the version to get (supports semver)
1195
+ * @returns Domain|Undefined
1196
+ */
1197
+ getDomain: getDomain((0, import_node_path11.join)(path4, "domains")),
1198
+ /**
1199
+ * Returns all domains from EventCatalog
1200
+ * @param latestOnly - optional boolean, set to true to get only latest versions
1201
+ * @returns Domain[]|Undefined
1202
+ */
1203
+ getDomains: getDomains((0, import_node_path11.join)(path4)),
1204
+ /**
1205
+ * Moves a given domain id to the version directory
1206
+ * @param directory
1207
+ */
1208
+ versionDomain: versionDomain((0, import_node_path11.join)(path4, "domains")),
1209
+ /**
1210
+ * Remove a domain from EventCatalog (modeled on the standard POSIX rm utility)
1211
+ *
1212
+ * @param path - The path to your domain, e.g. `/Payment`
1213
+ *
1214
+ */
1215
+ rmDomain: rmDomain((0, import_node_path11.join)(path4, "domains")),
1216
+ /**
1217
+ * Remove an service by an domain id
1218
+ *
1219
+ * @param id - The id of the domain you want to remove
1220
+ *
1221
+ */
1222
+ rmDomainById: rmDomainById((0, import_node_path11.join)(path4, "domains")),
1223
+ /**
1224
+ * Adds a file to the given domain
1225
+ * @param id - The id of the domain to add the file to
1226
+ * @param file - File contents to add including the content and the file name
1227
+ * @param version - Optional version of the domain to add the file to
1228
+ * @returns
1229
+ */
1230
+ addFileToDomain: addFileToDomain((0, import_node_path11.join)(path4, "domains")),
1231
+ /**
1232
+ * Adds an ubiquitous language dictionary to a domain
1233
+ * @param id - The id of the domain to add the ubiquitous language to
1234
+ * @param ubiquitousLanguageDictionary - The ubiquitous language dictionary to add
1235
+ * @param version - Optional version of the domain to add the ubiquitous language to
1236
+ */
1237
+ addUbiquitousLanguageToDomain: addUbiquitousLanguageToDomain((0, import_node_path11.join)(path4, "domains")),
1238
+ /**
1239
+ * Get the ubiquitous language dictionary from a domain
1240
+ * @param id - The id of the domain to get the ubiquitous language from
1241
+ * @param version - Optional version of the domain to get the ubiquitous language from
1242
+ * @returns
1243
+ */
1244
+ getUbiquitousLanguageFromDomain: getUbiquitousLanguageFromDomain((0, import_node_path11.join)(path4, "domains")),
1245
+ /**
1246
+ * Check to see if a domain version exists
1247
+ * @param id - The id of the domain
1248
+ * @param version - The version of the domain (supports semver)
1249
+ * @returns
1250
+ */
1251
+ domainHasVersion: domainHasVersion((0, import_node_path11.join)(path4)),
1252
+ /**
1253
+ * Adds a given service to a domain
1254
+ * @param id - The id of the domain
1255
+ * @param service - The id and version of the service to add
1256
+ * @param version - (Optional) The version of the domain to add the service to
1257
+ * @returns
1258
+ */
1259
+ addServiceToDomain: addServiceToDomain((0, import_node_path11.join)(path4, "domains")),
1260
+ /**
1261
+ * ================================
1262
+ * Teams
1263
+ * ================================
1264
+ */
1265
+ /**
1266
+ * Adds a team to EventCatalog
1267
+ *
1268
+ * @param team - The team to write
1269
+ * @param options - Optional options to write the team
1270
+ *
1271
+ */
1272
+ writeTeam: writeTeam((0, import_node_path11.join)(path4, "teams")),
1273
+ /**
1274
+ * Returns a team from EventCatalog
1275
+ * @param id - The id of the team to retrieve
1276
+ * @returns Team|Undefined
1277
+ */
1278
+ getTeam: getTeam((0, import_node_path11.join)(path4, "teams")),
1279
+ /**
1280
+ * Returns all teams from EventCatalog
1281
+ * @returns Team[]|Undefined
1282
+ */
1283
+ getTeams: getTeams((0, import_node_path11.join)(path4)),
1284
+ /**
1285
+ * Remove a team by the team id
1286
+ *
1287
+ * @param id - The id of the team you want to remove
1288
+ *
1289
+ */
1290
+ rmTeamById: rmTeamById((0, import_node_path11.join)(path4, "teams")),
1291
+ /**
1292
+ * ================================
1293
+ * Users
1294
+ * ================================
1295
+ */
1296
+ /**
1297
+ * Adds a user to EventCatalog
1298
+ *
1299
+ * @param user - The user to write
1300
+ * @param options - Optional options to write the user
1301
+ *
1302
+ */
1303
+ writeUser: writeUser((0, import_node_path11.join)(path4, "users")),
1304
+ /**
1305
+ * Returns a user from EventCatalog
1306
+ * @param id - The id of the user to retrieve
1307
+ * @returns User|Undefined
1308
+ */
1309
+ getUser: getUser((0, import_node_path11.join)(path4, "users")),
1310
+ /**
1311
+ * Returns all user from EventCatalog
1312
+ * @returns User[]|Undefined
1313
+ */
1314
+ getUsers: getUsers((0, import_node_path11.join)(path4)),
1315
+ /**
1316
+ * Remove a user by the user id
1317
+ *
1318
+ * @param id - The id of the user you want to remove
1319
+ *
1320
+ */
1321
+ rmUserById: rmUserById((0, import_node_path11.join)(path4, "users")),
1322
+ /**
1323
+ * ================================
1324
+ * Custom Docs
1325
+ * ================================
1326
+ */
1327
+ /**
1328
+ * Returns a custom doc from EventCatalog
1329
+ * @param path - The path to the custom doc to retrieve
1330
+ * @returns CustomDoc|Undefined
1331
+ */
1332
+ getCustomDoc: getCustomDoc((0, import_node_path11.join)(path4, "docs")),
1333
+ /**
1334
+ * Returns all custom docs from EventCatalog
1335
+ * @param options - Optional options to get custom docs from a specific path
1336
+ * @returns CustomDoc[]|Undefined
1337
+ */
1338
+ getCustomDocs: getCustomDocs((0, import_node_path11.join)(path4, "docs")),
1339
+ /**
1340
+ * Writes a custom doc to EventCatalog
1341
+ * @param customDoc - The custom doc to write
1342
+ * @param options - Optional options to write the custom doc
1343
+ *
1344
+ */
1345
+ writeCustomDoc: writeCustomDoc((0, import_node_path11.join)(path4, "docs")),
1346
+ /**
1347
+ * Removes a custom doc from EventCatalog
1348
+ * @param path - The path to the custom doc to remove
1349
+ *
1350
+ */
1351
+ rmCustomDoc: rmCustomDoc((0, import_node_path11.join)(path4, "docs")),
1352
+ /**
1353
+ * Dumps the catalog to a JSON file.
1354
+ * @param directory - The directory to dump the catalog to
1355
+ * @returns A JSON file with the catalog
1356
+ */
1357
+ dumpCatalog: dumpCatalog((0, import_node_path11.join)(path4))
1358
+ };
1359
+ };
1360
+
1361
+ // src/eventcatalog.ts
1362
+ var DUMP_VERSION = "0.0.1";
1363
+ var getEventCatalogVersion = async (catalogDir) => {
1364
+ const packageJson = import_fs.default.readFileSync((0, import_node_path12.join)(catalogDir, "package.json"), "utf8");
1365
+ const packageJsonObject = JSON.parse(packageJson);
1366
+ return packageJsonObject["dependencies"]["@eventcatalog/core"];
1367
+ };
1368
+ var hydrateResource = async (catalogDir, resources, { attachSchema = false } = {}) => {
1369
+ return await Promise.all(
1370
+ resources.map(async (resource) => {
1371
+ const resourcePath = await getResourcePath(catalogDir, resource.id, resource.version);
1372
+ let schema = "";
1373
+ if (resource.schemaPath && resourcePath?.fullPath) {
1374
+ const pathToSchema = import_node_path12.default.join(import_node_path12.default.dirname(resourcePath?.fullPath), resource.schemaPath);
1375
+ if (import_fs.default.existsSync(pathToSchema)) {
1376
+ schema = import_fs.default.readFileSync(pathToSchema, "utf8");
1377
+ }
1378
+ }
1379
+ const eventcatalog = schema ? { directory: resourcePath?.directory, schema } : { directory: resourcePath?.directory };
1380
+ return {
1381
+ ...resource,
1382
+ _eventcatalog: eventcatalog
1383
+ };
1384
+ })
1385
+ );
1386
+ };
1387
+ var filterCollection = (collection, options) => {
1388
+ return collection.map((item) => ({
1389
+ ...item,
1390
+ markdown: options?.includeMarkdown ? item.markdown : void 0
1391
+ }));
1392
+ };
1393
+ var dumpCatalog = (directory) => async (options) => {
1394
+ const { getDomains: getDomains2, getServices: getServices2, getEvents: getEvents2, getQueries: getQueries2, getCommands: getCommands2, getChannels: getChannels2, getTeams: getTeams2, getUsers: getUsers2 } = index_default(directory);
1395
+ const { includeMarkdown = true } = options || {};
1396
+ const domains = await getDomains2();
1397
+ const services = await getServices2();
1398
+ const events = await getEvents2();
1399
+ const commands = await getCommands2();
1400
+ const queries = await getQueries2();
1401
+ const teams = await getTeams2();
1402
+ const users = await getUsers2();
1403
+ const channels = await getChannels2();
1404
+ const [
1405
+ hydratedDomains,
1406
+ hydratedServices,
1407
+ hydratedEvents,
1408
+ hydratedQueries,
1409
+ hydratedCommands,
1410
+ hydratedTeams,
1411
+ hydratedUsers,
1412
+ hydratedChannels
1413
+ ] = await Promise.all([
1414
+ hydrateResource(directory, domains),
1415
+ hydrateResource(directory, services),
1416
+ hydrateResource(directory, events),
1417
+ hydrateResource(directory, queries),
1418
+ hydrateResource(directory, commands),
1419
+ hydrateResource(directory, teams),
1420
+ hydrateResource(directory, users),
1421
+ hydrateResource(directory, channels)
1422
+ ]);
1423
+ return {
1424
+ version: DUMP_VERSION,
1425
+ catalogVersion: await getEventCatalogVersion(directory),
1426
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
1427
+ resources: {
1428
+ domains: filterCollection(hydratedDomains, { includeMarkdown }),
1429
+ services: filterCollection(hydratedServices, { includeMarkdown }),
1430
+ messages: {
1431
+ events: filterCollection(hydratedEvents, { includeMarkdown }),
1432
+ queries: filterCollection(hydratedQueries, { includeMarkdown }),
1433
+ commands: filterCollection(hydratedCommands, { includeMarkdown })
1434
+ },
1435
+ teams: filterCollection(hydratedTeams, { includeMarkdown }),
1436
+ users: filterCollection(hydratedUsers, { includeMarkdown }),
1437
+ channels: filterCollection(hydratedChannels, { includeMarkdown })
1438
+ }
1439
+ };
1440
+ };
1441
+ // Annotate the CommonJS export names for ESM import in node:
1442
+ 0 && (module.exports = {
1443
+ dumpCatalog
1444
+ });
1445
+ //# sourceMappingURL=eventcatalog.js.map