@eventcatalog/sdk 2.5.5 → 2.6.1

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,37 @@
1
+ import { Message, Service } from './types.d.mjs';
2
+
3
+ /**
4
+ * Returns a message from EventCatalog by a given schema path.
5
+ *
6
+ * @example
7
+ * ```ts
8
+ * import utils from '@eventcatalog/utils';
9
+ *
10
+ * const { getMessageBySchemaPath } = utils('/path/to/eventcatalog');
11
+ *
12
+ * // Get the message by the schema path
13
+ * const message = await getMessageBySchemaPath('/path/to/eventcatalog/messages/InventoryAdjusted/schema.json');
14
+ * const message = await getMessageBySchemaPath('/path/to/eventcatalog/messages/InventoryAdjusted/schema.avro');
15
+ * ```
16
+ */
17
+ declare const getMessageBySchemaPath: (directory: string) => (path: string, options?: {
18
+ attachSchema?: boolean;
19
+ }) => Promise<Message>;
20
+ /**
21
+ * Returns the producers and consumers (services) for a given message.
22
+ *
23
+ * @example
24
+ * ```ts
25
+ * import utils from '@eventcatalog/utils';
26
+ *
27
+ * const { getProducersAndConsumersForMessage } = utils('/path/to/eventcatalog');
28
+ *
29
+ * // Returns the producers and consumers (services) for a given message
30
+ * const { producers, consumers } = await getProducersAndConsumersForMessage('InventoryAdjusted', '0.0.1');
31
+ */
32
+ declare const getProducersAndConsumersForMessage: (directory: string) => (id: string, version?: string) => Promise<{
33
+ producers: Service[];
34
+ consumers: Service[];
35
+ }>;
36
+
37
+ export { getMessageBySchemaPath, getProducersAndConsumersForMessage };
@@ -0,0 +1,37 @@
1
+ import { Message, Service } from './types.d.js';
2
+
3
+ /**
4
+ * Returns a message from EventCatalog by a given schema path.
5
+ *
6
+ * @example
7
+ * ```ts
8
+ * import utils from '@eventcatalog/utils';
9
+ *
10
+ * const { getMessageBySchemaPath } = utils('/path/to/eventcatalog');
11
+ *
12
+ * // Get the message by the schema path
13
+ * const message = await getMessageBySchemaPath('/path/to/eventcatalog/messages/InventoryAdjusted/schema.json');
14
+ * const message = await getMessageBySchemaPath('/path/to/eventcatalog/messages/InventoryAdjusted/schema.avro');
15
+ * ```
16
+ */
17
+ declare const getMessageBySchemaPath: (directory: string) => (path: string, options?: {
18
+ attachSchema?: boolean;
19
+ }) => Promise<Message>;
20
+ /**
21
+ * Returns the producers and consumers (services) for a given message.
22
+ *
23
+ * @example
24
+ * ```ts
25
+ * import utils from '@eventcatalog/utils';
26
+ *
27
+ * const { getProducersAndConsumersForMessage } = utils('/path/to/eventcatalog');
28
+ *
29
+ * // Returns the producers and consumers (services) for a given message
30
+ * const { producers, consumers } = await getProducersAndConsumersForMessage('InventoryAdjusted', '0.0.1');
31
+ */
32
+ declare const getProducersAndConsumersForMessage: (directory: string) => (id: string, version?: string) => Promise<{
33
+ producers: Service[];
34
+ consumers: Service[];
35
+ }>;
36
+
37
+ export { getMessageBySchemaPath, getProducersAndConsumersForMessage };
@@ -0,0 +1,271 @@
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/messages.ts
31
+ var messages_exports = {};
32
+ __export(messages_exports, {
33
+ getMessageBySchemaPath: () => getMessageBySchemaPath,
34
+ getProducersAndConsumersForMessage: () => getProducersAndConsumersForMessage
35
+ });
36
+ module.exports = __toCommonJS(messages_exports);
37
+ var import_node_path3 = require("path");
38
+ var import_gray_matter3 = __toESM(require("gray-matter"));
39
+
40
+ // src/internal/resources.ts
41
+ var import_path = require("path");
42
+
43
+ // src/internal/utils.ts
44
+ var import_glob = require("glob");
45
+ var import_node_fs = __toESM(require("fs"));
46
+ var import_fs_extra = require("fs-extra");
47
+ var import_node_path = require("path");
48
+ var import_gray_matter = __toESM(require("gray-matter"));
49
+ var import_semver = require("semver");
50
+ var findFileById = async (catalogDir, id, version) => {
51
+ const files = await getFiles(`${catalogDir}/**/index.{md,mdx}`);
52
+ const matchedFiles = await searchFilesForId(files, id) || [];
53
+ const latestVersion = matchedFiles.find((path) => !path.includes("versioned"));
54
+ if (!version) {
55
+ return latestVersion;
56
+ }
57
+ const parsedFiles = matchedFiles.map((path) => {
58
+ const { data } = import_gray_matter.default.read(path);
59
+ return { ...data, path };
60
+ });
61
+ const semverRange = (0, import_semver.validRange)(version);
62
+ if (semverRange && (0, import_semver.valid)(version)) {
63
+ const match2 = parsedFiles.filter((c) => (0, import_semver.satisfies)(c.version, semverRange));
64
+ return match2.length > 0 ? match2[0].path : void 0;
65
+ }
66
+ const sorted = parsedFiles.sort((a, b) => {
67
+ return a.version.localeCompare(b.version);
68
+ });
69
+ const match = sorted.length > 0 ? [sorted[sorted.length - 1]] : [];
70
+ if (match.length > 0) {
71
+ return match[0].path;
72
+ }
73
+ };
74
+ var getFiles = async (pattern, ignore = "") => {
75
+ try {
76
+ const normalizedInputPattern = (0, import_node_path.normalize)(pattern);
77
+ const absoluteBaseDir = (0, import_node_path.resolve)(
78
+ normalizedInputPattern.includes("**") ? normalizedInputPattern.split("**")[0] : (0, import_node_path.dirname)(normalizedInputPattern)
79
+ );
80
+ let relativePattern = (0, import_node_path.relative)(absoluteBaseDir, normalizedInputPattern);
81
+ relativePattern = relativePattern.replace(/\\/g, "/");
82
+ const ignoreList = Array.isArray(ignore) ? ignore : [ignore];
83
+ const files = (0, import_glob.globSync)(relativePattern, {
84
+ cwd: absoluteBaseDir,
85
+ ignore: ["node_modules/**", ...ignoreList],
86
+ absolute: true,
87
+ nodir: true
88
+ });
89
+ return files.map(import_node_path.normalize);
90
+ } catch (error) {
91
+ const absoluteBaseDirForError = (0, import_node_path.resolve)(
92
+ (0, import_node_path.normalize)(pattern).includes("**") ? (0, import_node_path.normalize)(pattern).split("**")[0] : (0, import_node_path.dirname)((0, import_node_path.normalize)(pattern))
93
+ );
94
+ const relativePatternForError = (0, import_node_path.relative)(absoluteBaseDirForError, (0, import_node_path.normalize)(pattern)).replace(/\\/g, "/");
95
+ throw new Error(
96
+ `Error finding files for pattern "${pattern}" (using cwd: "${absoluteBaseDirForError}", globPattern: "${relativePatternForError}"): ${error.message}`
97
+ );
98
+ }
99
+ };
100
+ var searchFilesForId = async (files, id, version) => {
101
+ const escapedId = id.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
102
+ const idRegex = new RegExp(`^id:\\s*(['"]|>-)?\\s*${escapedId}['"]?\\s*$`, "m");
103
+ const versionRegex = new RegExp(`^version:\\s*['"]?${version}['"]?\\s*$`, "m");
104
+ const matches = files.map((file) => {
105
+ const content = import_node_fs.default.readFileSync(file, "utf-8");
106
+ const hasIdMatch = content.match(idRegex);
107
+ if (version && !content.match(versionRegex)) {
108
+ return void 0;
109
+ }
110
+ if (hasIdMatch) {
111
+ return file;
112
+ }
113
+ });
114
+ return matches.filter(Boolean).filter((file) => file !== void 0);
115
+ };
116
+
117
+ // src/internal/resources.ts
118
+ var import_gray_matter2 = __toESM(require("gray-matter"));
119
+ var import_promises = __toESM(require("fs/promises"));
120
+ var import_node_fs2 = __toESM(require("fs"));
121
+ var import_semver2 = require("semver");
122
+ var import_proper_lockfile = require("proper-lockfile");
123
+ var getResource = async (catalogDir, id, version, options) => {
124
+ const attachSchema = options?.attachSchema || false;
125
+ const file = await findFileById(catalogDir, id, version);
126
+ if (!file) return;
127
+ const { data, content } = import_gray_matter2.default.read(file);
128
+ if (attachSchema && data?.schemaPath) {
129
+ const resourceDirectory = (0, import_path.dirname)(file);
130
+ const pathToSchema = (0, import_path.join)(resourceDirectory, data.schemaPath);
131
+ if (import_node_fs2.default.existsSync(pathToSchema)) {
132
+ const schema = import_node_fs2.default.readFileSync(pathToSchema, "utf8");
133
+ try {
134
+ data.schema = JSON.parse(schema);
135
+ } catch (error) {
136
+ data.schema = schema;
137
+ }
138
+ }
139
+ }
140
+ return {
141
+ ...data,
142
+ markdown: content.trim()
143
+ };
144
+ };
145
+ var getResourcePath = async (catalogDir, id, version) => {
146
+ const file = await findFileById(catalogDir, id, version);
147
+ if (!file) return;
148
+ return {
149
+ fullPath: file,
150
+ relativePath: file.replace(catalogDir, ""),
151
+ directory: (0, import_path.dirname)(file.replace(catalogDir, ""))
152
+ };
153
+ };
154
+ var getResources = async (catalogDir, {
155
+ type,
156
+ latestOnly = false,
157
+ ignore = [],
158
+ pattern = "",
159
+ attachSchema = false
160
+ }) => {
161
+ const ignoreList = latestOnly ? `**/versioned/**` : "";
162
+ const filePattern = pattern || `${catalogDir}/**/${type}/**/index.{md,mdx}`;
163
+ const files = await getFiles(filePattern, [ignoreList, ...ignore]);
164
+ if (files.length === 0) return;
165
+ return files.map((file) => {
166
+ const { data, content } = import_gray_matter2.default.read(file);
167
+ if (attachSchema && data?.schemaPath) {
168
+ const resourceDirectory = (0, import_path.dirname)(file);
169
+ const pathToSchema = (0, import_path.join)(resourceDirectory, data.schemaPath);
170
+ if (import_node_fs2.default.existsSync(pathToSchema)) {
171
+ const schema = import_node_fs2.default.readFileSync(pathToSchema, "utf8");
172
+ try {
173
+ data.schema = JSON.parse(schema);
174
+ } catch (error) {
175
+ data.schema = schema;
176
+ }
177
+ }
178
+ }
179
+ return {
180
+ ...data,
181
+ markdown: content.trim()
182
+ };
183
+ });
184
+ };
185
+ var isLatestVersion = async (catalogDir, id, version) => {
186
+ const resource = await getResource(catalogDir, id, version);
187
+ if (!resource) return false;
188
+ const pathToResource = await getResourcePath(catalogDir, id, version);
189
+ return !pathToResource?.relativePath.replace(/\\/g, "/").includes("/versioned/");
190
+ };
191
+
192
+ // src/services.ts
193
+ var import_promises2 = __toESM(require("fs/promises"));
194
+ var import_node_path2 = require("path");
195
+ var getServices = (directory) => async (options) => getResources(directory, {
196
+ type: "services",
197
+ ignore: ["**/events/**", "**/commands/**", "**/queries/**", "**/entities/**", "**/subdomains/**/entities/**"],
198
+ ...options
199
+ });
200
+
201
+ // src/messages.ts
202
+ var getMessageBySchemaPath = (directory) => async (path, options) => {
203
+ const pathToMessage = (0, import_node_path3.dirname)(path);
204
+ try {
205
+ const files = await getFiles(`${directory}/${pathToMessage}/index.{md,mdx}`);
206
+ if (!files || files.length === 0) {
207
+ throw new Error(`No message definition file (index.md or index.mdx) found in directory: ${pathToMessage}`);
208
+ }
209
+ const messageFile = files[0];
210
+ const { data } = import_gray_matter3.default.read(messageFile);
211
+ const { id, version } = data;
212
+ if (!id || !version) {
213
+ throw new Error(`Message definition file at ${messageFile} is missing 'id' or 'version' in its frontmatter.`);
214
+ }
215
+ const message = await getResource(directory, id, version, { type: "message", ...options });
216
+ if (!message) {
217
+ throw new Error(`Message resource with id '${id}' and version '${version}' not found, as referenced in ${messageFile}.`);
218
+ }
219
+ return message;
220
+ } catch (error) {
221
+ console.error(`Failed to get message for schema path ${path}. Error processing directory ${pathToMessage}:`, error);
222
+ if (error instanceof Error) {
223
+ error.message = `Failed to retrieve message from ${pathToMessage}: ${error.message}`;
224
+ throw error;
225
+ }
226
+ throw new Error(`Failed to retrieve message from ${pathToMessage} due to an unknown error.`);
227
+ }
228
+ };
229
+ var getProducersAndConsumersForMessage = (directory) => async (id, version) => {
230
+ const services = await getServices(directory)({ latestOnly: true });
231
+ const message = await getResource(directory, id, version, { type: "message" });
232
+ const isMessageLatestVersion = await isLatestVersion(directory, id, version);
233
+ if (!message) {
234
+ throw new Error(`Message resource with id '${id}' and version '${version}' not found.`);
235
+ }
236
+ const producers = [];
237
+ const consumers = [];
238
+ for (const service of services) {
239
+ const servicePublishesMessage = service.sends?.some((_message) => {
240
+ if (_message.version) {
241
+ return _message.id === message.id && _message.version === message.version;
242
+ }
243
+ if (isMessageLatestVersion && _message.id === message.id) {
244
+ return true;
245
+ }
246
+ return false;
247
+ });
248
+ const serviceSubscribesToMessage = service.receives?.some((_message) => {
249
+ if (_message.version) {
250
+ return _message.id === message.id && _message.version === message.version;
251
+ }
252
+ if (isMessageLatestVersion && _message.id === message.id) {
253
+ return true;
254
+ }
255
+ return false;
256
+ });
257
+ if (servicePublishesMessage) {
258
+ producers.push(service);
259
+ }
260
+ if (serviceSubscribesToMessage) {
261
+ consumers.push(service);
262
+ }
263
+ }
264
+ return { producers, consumers };
265
+ };
266
+ // Annotate the CommonJS export names for ESM import in node:
267
+ 0 && (module.exports = {
268
+ getMessageBySchemaPath,
269
+ getProducersAndConsumersForMessage
270
+ });
271
+ //# sourceMappingURL=messages.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/messages.ts","../src/internal/resources.ts","../src/internal/utils.ts","../src/services.ts"],"sourcesContent":["import { dirname, join } from 'node:path';\nimport type { Message, Service } from './types';\nimport matter from 'gray-matter';\nimport { getResource, getResourcePath, isLatestVersion } from './internal/resources';\nimport { getFiles } from './internal/utils';\nimport { getServices } from './services';\n\n/**\n * Returns a message from EventCatalog by a given schema path.\n *\n * @example\n * ```ts\n * import utils from '@eventcatalog/utils';\n *\n * const { getMessageBySchemaPath } = utils('/path/to/eventcatalog');\n *\n * // Get the message by the schema path\n * const message = await getMessageBySchemaPath('/path/to/eventcatalog/messages/InventoryAdjusted/schema.json');\n * const message = await getMessageBySchemaPath('/path/to/eventcatalog/messages/InventoryAdjusted/schema.avro');\n * ```\n */\nexport const getMessageBySchemaPath =\n (directory: string) =>\n async (path: string, options?: { attachSchema?: boolean }): Promise<Message> => {\n const pathToMessage = dirname(path);\n try {\n const files = await getFiles(`${directory}/${pathToMessage}/index.{md,mdx}`);\n\n if (!files || files.length === 0) {\n throw new Error(`No message definition file (index.md or index.mdx) found in directory: ${pathToMessage}`);\n }\n const messageFile = files[0];\n\n const { data } = matter.read(messageFile);\n const { id, version } = data;\n\n if (!id || !version) {\n throw new Error(`Message definition file at ${messageFile} is missing 'id' or 'version' in its frontmatter.`);\n }\n\n const message = await getResource(directory, id, version, { type: 'message', ...options });\n\n if (!message) {\n throw new Error(`Message resource with id '${id}' and version '${version}' not found, as referenced in ${messageFile}.`);\n }\n return message as Message;\n } catch (error) {\n console.error(`Failed to get message for schema path ${path}. Error processing directory ${pathToMessage}:`, error);\n if (error instanceof Error) {\n // Prepend more context to the existing error message\n error.message = `Failed to retrieve message from ${pathToMessage}: ${error.message}`;\n throw error;\n }\n throw new Error(`Failed to retrieve message from ${pathToMessage} due to an unknown error.`);\n }\n };\n\n/**\n * Returns the producers and consumers (services) for a given message.\n *\n * @example\n * ```ts\n * import utils from '@eventcatalog/utils';\n *\n * const { getProducersAndConsumersForMessage } = utils('/path/to/eventcatalog');\n *\n * // Returns the producers and consumers (services) for a given message\n * const { producers, consumers } = await getProducersAndConsumersForMessage('InventoryAdjusted', '0.0.1');\n */\nexport const getProducersAndConsumersForMessage =\n (directory: string) =>\n async (id: string, version?: string): Promise<{ producers: Service[]; consumers: Service[] }> => {\n const services = await getServices(directory)({ latestOnly: true });\n const message = (await getResource(directory, id, version, { type: 'message' })) as Message;\n const isMessageLatestVersion = await isLatestVersion(directory, id, version);\n\n if (!message) {\n throw new Error(`Message resource with id '${id}' and version '${version}' not found.`);\n }\n\n const producers: Service[] = [];\n const consumers: Service[] = [];\n\n for (const service of services) {\n const servicePublishesMessage = service.sends?.some((_message) => {\n if (_message.version) {\n return _message.id === message.id && _message.version === message.version;\n }\n if (isMessageLatestVersion && _message.id === message.id) {\n return true;\n }\n return false;\n });\n const serviceSubscribesToMessage = service.receives?.some((_message) => {\n if (_message.version) {\n return _message.id === message.id && _message.version === message.version;\n }\n if (isMessageLatestVersion && _message.id === message.id) {\n return true;\n }\n return false;\n });\n\n if (servicePublishesMessage) {\n producers.push(service);\n }\n if (serviceSubscribesToMessage) {\n consumers.push(service);\n }\n }\n\n return { producers, consumers };\n };\n","import { dirname, join } from 'path';\nimport { copyDir, findFileById, getFiles, searchFilesForId, versionExists } from './utils';\nimport matter from 'gray-matter';\nimport fs from 'node:fs/promises';\nimport fsSync from 'node:fs';\nimport { Message, Service, CustomDoc } from '../types';\nimport { satisfies } from 'semver';\nimport { lock, unlock } from 'proper-lockfile';\n\ntype Resource = Service | Message | CustomDoc;\n\nexport const versionResource = async (catalogDir: string, id: string) => {\n // Find all the events in the directory\n const files = await getFiles(`${catalogDir}/**/index.{md,mdx}`);\n const matchedFiles = await searchFilesForId(files, id);\n\n if (matchedFiles.length === 0) {\n throw new Error(`No resource found with id: ${id}`);\n }\n\n // Event that is in the route of the project\n const file = matchedFiles[0];\n const sourceDirectory = dirname(file);\n const { data: { version = '0.0.1' } = {} } = matter.read(file);\n const targetDirectory = getVersionedDirectory(sourceDirectory, version);\n\n fsSync.mkdirSync(targetDirectory, { recursive: true });\n\n // Copy the event to the versioned directory\n await copyDir(catalogDir, sourceDirectory, targetDirectory, (src) => {\n return !src.includes('versioned');\n });\n\n // Remove all the files in the root of the resource as they have now been versioned\n await fs.readdir(sourceDirectory).then(async (resourceFiles) => {\n await Promise.all(\n resourceFiles.map(async (file) => {\n if (file !== 'versioned') {\n fsSync.rmSync(join(sourceDirectory, file), { recursive: true });\n }\n })\n );\n });\n};\n\nexport const writeResource = async (\n catalogDir: string,\n resource: Resource,\n options: { path?: string; type: string; override?: boolean; versionExistingContent?: boolean; format?: 'md' | 'mdx' } = {\n path: '',\n type: '',\n override: false,\n versionExistingContent: false,\n format: 'mdx',\n }\n) => {\n const path = options.path || `/${resource.id}`;\n const fullPath = join(catalogDir, path);\n const format = options.format || 'mdx';\n\n // Create directory if it doesn't exist\n fsSync.mkdirSync(fullPath, { recursive: true });\n\n // Create or get lock file path\n const lockPath = join(fullPath, `index.${format}`);\n\n // Ensure the file exists before attempting to lock it\n if (!fsSync.existsSync(lockPath)) {\n fsSync.writeFileSync(lockPath, '');\n }\n\n try {\n // Acquire lock with retry\n await lock(lockPath, {\n retries: 5,\n stale: 10000, // 10 seconds\n });\n\n const exists = await versionExists(catalogDir, resource.id, resource.version);\n\n if (exists && !options.override) {\n throw new Error(`Failed to write ${resource.id} (${options.type}) as the version ${resource.version} already exists`);\n }\n\n const { markdown, ...frontmatter } = resource;\n\n if (options.versionExistingContent && !exists) {\n const currentResource = await getResource(catalogDir, resource.id);\n\n if (currentResource) {\n if (satisfies(resource.version, `>${currentResource.version}`)) {\n await versionResource(catalogDir, resource.id);\n } else {\n throw new Error(`New version ${resource.version} is not greater than current version ${currentResource.version}`);\n }\n }\n }\n\n const document = matter.stringify(markdown.trim(), frontmatter);\n fsSync.writeFileSync(lockPath, document);\n } finally {\n // Always release the lock\n await unlock(lockPath).catch(() => {});\n }\n};\n\nexport const getResource = async (\n catalogDir: string,\n id: string,\n version?: string,\n options?: { type: string; attachSchema?: boolean }\n): Promise<Resource | undefined> => {\n const attachSchema = options?.attachSchema || false;\n const file = await findFileById(catalogDir, id, version);\n if (!file) return;\n\n const { data, content } = matter.read(file);\n\n if (attachSchema && data?.schemaPath) {\n const resourceDirectory = dirname(file);\n const pathToSchema = join(resourceDirectory, data.schemaPath);\n if (fsSync.existsSync(pathToSchema)) {\n const schema = fsSync.readFileSync(pathToSchema, 'utf8');\n // Try to parse the schema\n try {\n data.schema = JSON.parse(schema);\n } catch (error) {\n data.schema = schema;\n }\n }\n }\n\n return {\n ...data,\n markdown: content.trim(),\n } as Resource;\n};\n\nexport const getResourcePath = async (catalogDir: string, id: string, version?: string) => {\n const file = await findFileById(catalogDir, id, version);\n if (!file) return;\n\n return {\n fullPath: file,\n relativePath: file.replace(catalogDir, ''),\n directory: dirname(file.replace(catalogDir, '')),\n };\n};\n\nexport const getResources = async (\n catalogDir: string,\n {\n type,\n latestOnly = false,\n ignore = [],\n pattern = '',\n attachSchema = false,\n }: { type: string; pattern?: string; latestOnly?: boolean; ignore?: string[]; attachSchema?: boolean }\n): Promise<Resource[] | undefined> => {\n const ignoreList = latestOnly ? `**/versioned/**` : '';\n const filePattern = pattern || `${catalogDir}/**/${type}/**/index.{md,mdx}`;\n const files = await getFiles(filePattern, [ignoreList, ...ignore]);\n\n if (files.length === 0) return;\n\n return files.map((file) => {\n const { data, content } = matter.read(file);\n\n // Attach the schema if the attachSchema option is set to true\n if (attachSchema && data?.schemaPath) {\n const resourceDirectory = dirname(file);\n const pathToSchema = join(resourceDirectory, data.schemaPath);\n if (fsSync.existsSync(pathToSchema)) {\n const schema = fsSync.readFileSync(pathToSchema, 'utf8');\n // Try to parse the schema\n try {\n data.schema = JSON.parse(schema);\n } catch (error) {\n data.schema = schema;\n }\n }\n }\n return {\n ...data,\n markdown: content.trim(),\n } as Resource;\n });\n};\n\nexport const rmResourceById = async (\n catalogDir: string,\n id: string,\n version?: string,\n options?: { type: string; persistFiles?: boolean }\n) => {\n const files = await getFiles(`${catalogDir}/**/index.{md,mdx}`);\n\n const matchedFiles = await searchFilesForId(files, id, version);\n\n if (matchedFiles.length === 0) {\n throw new Error(`No ${options?.type || 'resource'} found with id: ${id}`);\n }\n\n if (options?.persistFiles) {\n await Promise.all(\n matchedFiles.map(async (file) => {\n await fs.rm(file, { recursive: true });\n })\n );\n } else {\n await Promise.all(\n matchedFiles.map(async (file) => {\n const directory = dirname(file);\n await fs.rm(directory, { recursive: true, force: true });\n })\n );\n }\n};\n\nexport const addFileToResource = async (\n catalogDir: string,\n id: string,\n file: { content: string; fileName: string },\n version?: string\n) => {\n const pathToResource = await findFileById(catalogDir, id, version);\n\n if (!pathToResource) throw new Error('Cannot find directory to write file to');\n\n let fileContent = file.content.trim();\n\n try {\n const json = JSON.parse(fileContent);\n fileContent = JSON.stringify(json, null, 2);\n } catch (error) {\n // Just silently fail if the file is not valid JSON\n // Write it as it is\n }\n\n fsSync.writeFileSync(join(dirname(pathToResource), file.fileName), fileContent);\n};\n\nexport const getFileFromResource = async (catalogDir: string, id: string, file: { fileName: string }, version?: string) => {\n const pathToResource = await findFileById(catalogDir, id, version);\n\n if (!pathToResource) throw new Error('Cannot find directory of resource');\n\n const exists = await fs\n .access(join(dirname(pathToResource), file.fileName))\n .then(() => true)\n .catch(() => false);\n if (!exists) throw new Error(`File ${file.fileName} does not exist in resource ${id} v(${version})`);\n\n return fsSync.readFileSync(join(dirname(pathToResource), file.fileName), 'utf-8');\n};\nexport const getVersionedDirectory = (sourceDirectory: string, version: any): string => {\n return join(sourceDirectory, 'versioned', version);\n};\n\nexport const isLatestVersion = async (catalogDir: string, id: string, version?: string) => {\n const resource = await getResource(catalogDir, id, version);\n if (!resource) return false;\n\n const pathToResource = await getResourcePath(catalogDir, id, version);\n\n return !pathToResource?.relativePath.replace(/\\\\/g, '/').includes('/versioned/');\n};\n","import { globSync } from 'glob';\nimport fsSync from 'node:fs';\nimport { copy, CopyFilterAsync, CopyFilterSync } from 'fs-extra';\nimport { join, dirname, normalize, sep as pathSeparator, resolve, basename, relative } from 'node:path';\nimport matter from 'gray-matter';\nimport { satisfies, validRange, valid } from 'semver';\n\n/**\n * Returns true if a given version of a resource id exists in the catalog\n */\nexport const versionExists = async (catalogDir: string, id: string, version: string) => {\n const files = await getFiles(`${catalogDir}/**/index.{md,mdx}`);\n const matchedFiles = (await searchFilesForId(files, id, version)) || [];\n return matchedFiles.length > 0;\n};\n\nexport const findFileById = async (catalogDir: string, id: string, version?: string): Promise<string | undefined> => {\n const files = await getFiles(`${catalogDir}/**/index.{md,mdx}`);\n\n const matchedFiles = (await searchFilesForId(files, id)) || [];\n const latestVersion = matchedFiles.find((path) => !path.includes('versioned'));\n\n // If no version is provided, return the latest version\n if (!version) {\n return latestVersion;\n }\n\n // map files into gray matter to get versions\n const parsedFiles = matchedFiles.map((path) => {\n const { data } = matter.read(path);\n return { ...data, path };\n }) as any[];\n\n const semverRange = validRange(version);\n\n if (semverRange && valid(version)) {\n const match = parsedFiles.filter((c) => satisfies(c.version, semverRange));\n return match.length > 0 ? match[0].path : undefined;\n }\n\n // Order by version\n const sorted = parsedFiles.sort((a, b) => {\n return a.version.localeCompare(b.version);\n });\n\n // latest version\n const match = sorted.length > 0 ? [sorted[sorted.length - 1]] : [];\n\n if (match.length > 0) {\n return match[0].path;\n }\n};\n\nexport const getFiles = async (pattern: string, ignore: string | string[] = '') => {\n try {\n // 1. Normalize the input pattern to handle mixed separators potentially\n const normalizedInputPattern = normalize(pattern);\n\n // 2. Determine the absolute base directory (cwd for glob)\n // Resolve ensures it's absolute. Handles cases with/without globstar.\n const absoluteBaseDir = resolve(\n normalizedInputPattern.includes('**') ? normalizedInputPattern.split('**')[0] : dirname(normalizedInputPattern)\n );\n\n // 3. Determine the pattern part relative to the absolute base directory\n // We extract the part of the normalized pattern that comes *after* the absoluteBaseDir\n let relativePattern = relative(absoluteBaseDir, normalizedInputPattern);\n\n // On Windows, relative() might return empty string if paths are identical,\n // or might need normalization if the original pattern didn't have `**`\n // Example: pattern = 'dir/file.md', absoluteBaseDir='.../dir', normalized='...\\dir\\file.md'\n // relative() -> 'file.md'\n // Example: pattern = 'dir/**/file.md', absoluteBaseDir='.../dir', normalized='...\\dir\\**\\file.md'\n // relative() -> '**\\file.md'\n // Convert separators in the relative pattern to forward slashes for glob\n relativePattern = relativePattern.replace(/\\\\/g, '/');\n\n const ignoreList = Array.isArray(ignore) ? ignore : [ignore];\n\n const files = globSync(relativePattern, {\n cwd: absoluteBaseDir,\n ignore: ['node_modules/**', ...ignoreList],\n absolute: true,\n nodir: true,\n });\n\n // 5. Normalize results for consistency before returning\n return files.map(normalize);\n } catch (error: any) {\n // Add more diagnostic info to the error\n const absoluteBaseDirForError = resolve(\n normalize(pattern).includes('**') ? normalize(pattern).split('**')[0] : dirname(normalize(pattern))\n );\n const relativePatternForError = relative(absoluteBaseDirForError, normalize(pattern)).replace(/\\\\/g, '/');\n throw new Error(\n `Error finding files for pattern \"${pattern}\" (using cwd: \"${absoluteBaseDirForError}\", globPattern: \"${relativePatternForError}\"): ${error.message}`\n );\n }\n};\n\nexport const readMdxFile = async (path: string) => {\n const { data } = matter.read(path);\n const { markdown, ...frontmatter } = data;\n return { ...frontmatter, markdown };\n};\n\nexport const searchFilesForId = async (files: string[], id: string, version?: string) => {\n // Escape the id to avoid regex issues\n const escapedId = id.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n const idRegex = new RegExp(`^id:\\\\s*(['\"]|>-)?\\\\s*${escapedId}['\"]?\\\\s*$`, 'm');\n\n const versionRegex = new RegExp(`^version:\\\\s*['\"]?${version}['\"]?\\\\s*$`, 'm');\n\n const matches = files.map((file) => {\n const content = fsSync.readFileSync(file, 'utf-8');\n const hasIdMatch = content.match(idRegex);\n\n // Check version if provided\n if (version && !content.match(versionRegex)) {\n return undefined;\n }\n\n if (hasIdMatch) {\n return file;\n }\n });\n\n return matches.filter(Boolean).filter((file) => file !== undefined);\n};\n\n/**\n * Function to copy a directory from source to target, uses a tmp directory\n * @param catalogDir\n * @param source\n * @param target\n * @param filter\n */\nexport const copyDir = async (catalogDir: string, source: string, target: string, filter?: CopyFilterAsync | CopyFilterSync) => {\n const tmpDirectory = join(catalogDir, 'tmp');\n fsSync.mkdirSync(tmpDirectory, { recursive: true });\n\n // Copy everything over\n await copy(source, tmpDirectory, {\n overwrite: true,\n filter,\n });\n\n await copy(tmpDirectory, target, {\n overwrite: true,\n filter,\n });\n\n // Remove the tmp directory\n fsSync.rmSync(tmpDirectory, { recursive: true });\n};\n\n// Makes sure values in sends/recieves are unique\nexport const uniqueVersions = (messages: { id: string; version: string }[]): { id: string; version: string }[] => {\n const uniqueSet = new Set();\n\n return messages.filter((message) => {\n const key = `${message.id}-${message.version}`;\n if (!uniqueSet.has(key)) {\n uniqueSet.add(key);\n return true;\n }\n return false;\n });\n};\n","import type { Service, Specifications } from './types';\nimport fs from 'node:fs/promises';\nimport { join, dirname, extname } from 'node:path';\nimport {\n addFileToResource,\n getFileFromResource,\n getResource,\n rmResourceById,\n versionResource,\n writeResource,\n getVersionedDirectory,\n getResources,\n getResourcePath,\n} from './internal/resources';\nimport { findFileById, uniqueVersions } from './internal/utils';\n\n/**\n * Returns a service from EventCatalog.\n *\n * You can optionally specify a version to get a specific version of the service\n *\n * @example\n * ```ts\n * import utils from '@eventcatalog/utils';\n *\n * const { getService } = utils('/path/to/eventcatalog');\n *\n * // Gets the latest version of the event\n * const service = await getService('InventoryService');\n *\n * // Gets a version of the event\n * const service = await getService('InventoryService', '0.0.1');\n * ```\n */\nexport const getService =\n (directory: string) =>\n async (id: string, version?: string): Promise<Service> =>\n getResource(directory, id, version, { type: 'service' }) as Promise<Service>;\n\n/**\n * Returns all services from EventCatalog.\n *\n * You can optionally specify if you want to get the latest version of the services.\n *\n * @example\n * ```ts\n * import utils from '@eventcatalog/utils';\n *\n * const { getServices } = utils('/path/to/eventcatalog');\n *\n * // Gets all services (and versions) from the catalog\n * const services = await getServices();\n *\n * // Gets all services (only latest version) from the catalog\n * const services = await getServices({ latestOnly: true });\n * ```\n */\nexport const getServices =\n (directory: string) =>\n async (options?: { latestOnly?: boolean }): Promise<Service[]> =>\n getResources(directory, {\n type: 'services',\n ignore: ['**/events/**', '**/commands/**', '**/queries/**', '**/entities/**', '**/subdomains/**/entities/**'],\n ...options,\n }) as Promise<Service[]>;\n\n/**\n * Write a Service to EventCatalog.\n *\n * You can optionally overide the path of the Service.\n *\n * @example\n * ```ts\n * import utils from '@eventcatalog/utils';\n *\n * const { writeService } = utils('/path/to/eventcatalog');\n *\n * // Write a Service\n * // Service would be written to services/InventoryService\n * await writeService({\n * id: 'InventoryService',\n * name: 'Inventory Service',\n * version: '0.0.1',\n * summary: 'Service that handles the inventory',\n * markdown: '# Hello world',\n * });\n *\n * // Write a service to the catalog but override the path\n * // Service would be written to services/Inventory/InventoryService\n * await writeService({\n * id: 'InventoryService',\n * name: 'Inventory Adjusted',\n * version: '0.0.1',\n * summary: 'This is a summary',\n * markdown: '# Hello world',\n * }, { path: \"/Inventory/InventoryService\"});\n *\n * // Write a service to the catalog and override the existing content (if there is any)\n * await writeService({\n * id: 'InventoryService',\n * name: 'Inventory Adjusted',\n * version: '0.0.1',\n * summary: 'This is a summary',\n * markdown: '# Hello world',\n * }, { override: true });\n *\n * // Write a service to the catalog and version the previous version\n * // only works if the new version is greater than the previous version\n * await writeService({\n * id: 'InventoryService',\n * name: 'Inventory Adjusted',\n * version: '0.0.1',\n * summary: 'This is a summary',\n * markdown: '# Hello world',\n * }, { versionExistingContent: true });\n *\n * ```\n */\nexport const writeService =\n (directory: string) =>\n async (\n service: Service,\n options: { path?: string; override?: boolean; versionExistingContent?: boolean; format?: 'md' | 'mdx' } = {\n path: '',\n override: false,\n format: 'mdx',\n }\n ) => {\n const resource: Service = { ...service };\n\n if (Array.isArray(service.sends)) {\n resource.sends = uniqueVersions(service.sends as { id: string; version: string }[]);\n }\n\n if (Array.isArray(service.receives)) {\n resource.receives = uniqueVersions(service.receives as { id: string; version: string }[]);\n }\n\n return await writeResource(directory, resource, { ...options, type: 'service' });\n };\n\n/**\n * Write a versioned service to EventCatalog.\n *\n * You can optionally overide the path of the Service.\n *\n * @example\n * ```ts\n * import utils from '@eventcatalog/utils';\n *\n * const { writeVersionedService } = utils('/path/to/eventcatalog');\n *\n * // Write a service\n * // Service would be written to services/InventoryService/versioned/0.0.1\n * await writeVersionedService({\n * id: 'InventoryService',\n * name: 'Inventory Service',\n * version: '0.0.1',\n * summary: 'Service that handles the inventory',\n * markdown: '# Hello world',\n * });\n *\n * ```\n */\nexport const writeVersionedService = (directory: string) => async (service: Service) => {\n const resource: Service = { ...service };\n const path = getVersionedDirectory(service.id, service.version);\n\n return await writeService(directory)(resource, { path: path });\n};\n\n/**\n * Write a service to a domain in EventCatalog.\n *\n * @example\n * ```ts\n * import utils from '@eventcatalog/utils';\n *\n * const { writeServiceToDomain } = utils('/path/to/eventcatalog');\n *\n * // Write a service to a domain\n * // Service would be written to domains/Shopping/services/InventoryService\n * await writeServiceToDomain({\n * id: 'InventoryService',\n * name: 'Inventory Service',\n * version: '0.0.1',\n * summary: 'Service that handles the inventory',\n * markdown: '# Hello world',\n * }, { id: 'Shopping' });\n * ```\n */\nexport const writeServiceToDomain =\n (directory: string) =>\n async (\n service: Service,\n domain: { id: string; version?: string; direction?: string },\n options: { path?: string; format?: 'md' | 'mdx'; override?: boolean } = { path: '', format: 'mdx', override: false }\n ) => {\n let pathForService =\n domain.version && domain.version !== 'latest'\n ? `/${domain.id}/versioned/${domain.version}/services`\n : `/${domain.id}/services`;\n pathForService = join(pathForService, service.id);\n\n //\n await writeResource(directory, { ...service }, { ...options, path: pathForService, type: 'service' });\n };\n\n/**\n * Version a service by it's id.\n *\n * Takes the latest service and moves it to a versioned directory.\n * All files with this service are also versioned. (e.g /services/InventoryService/openapi.yml)\n *\n * @example\n * ```ts\n * import utils from '@eventcatalog/utils';\n *\n * const { versionService } = utils('/path/to/eventcatalog');\n *\n * // moves the latest InventoryService service to a versioned directory\n * // the version within that service is used as the version number.\n * await versionService('InventoryService');\n *\n * ```\n */\nexport const versionService = (directory: string) => async (id: string) => versionResource(directory, id);\n\n/**\n * Delete a service at it's given path.\n *\n * @example\n * ```ts\n * import utils from '@eventcatalog/utils';\n *\n * const { rmService } = utils('/path/to/eventcatalog');\n *\n * // Removes the service at services/InventoryService\n * await rmService('/InventoryService');\n * ```\n */\nexport const rmService = (directory: string) => async (path: string) => {\n await fs.rm(join(directory, path), { recursive: true });\n};\n\n/**\n * Delete a service by it's id.\n *\n * Optionally specify a version to delete a specific version of the service.\n *\n * @example\n * ```ts\n * import utils from '@eventcatalog/utils';\n *\n * const { rmServiceById } = utils('/path/to/eventcatalog');\n *\n * // deletes the latest InventoryService event\n * await rmServiceById('InventoryService');\n *\n * // deletes a specific version of the InventoryService event\n * await rmServiceById('InventoryService', '0.0.1');\n * ```\n */\nexport const rmServiceById = (directory: string) => async (id: string, version?: string, persistFiles?: boolean) =>\n rmResourceById(directory, id, version, { type: 'service', persistFiles });\n\n/**\n * Add a file to a service by it's id.\n *\n * Optionally specify a version to add a file to a specific version of the service.\n *\n * @example\n * ```ts\n * import utils from '@eventcatalog/utils';\n *\n * const { addFileToService } = utils('/path/to/eventcatalog');\n *\n * // adds a file to the latest InventoryService event\n * await addFileToService('InventoryService', { content: 'Hello world', fileName: 'hello.txt' });\n *\n * // adds a file to a specific version of the InventoryService event\n * await addFileToService('InventoryService', { content: 'Hello world', fileName: 'hello.txt' }, '0.0.1');\n *\n * ```\n */\n\nexport const addFileToService =\n (directory: string) => async (id: string, file: { content: string; fileName: string }, version?: string) =>\n addFileToResource(directory, id, file, version);\n\n/**\n * Returns specification files for a service\n *\n * Optionally specify a version to of the service\n *\n * @example\n * ```ts\n * import utils from '@eventcatalog/utils';\n *\n * const { getSpecificationFilesForService } = utils('/path/to/eventcatalog');\n *\n * // returns a list of specification files for a service\n * await getSpecificationFilesForService('InventoryService', '0.0.1');\n *\n * ```\n */\n\nexport const getSpecificationFilesForService = (directory: string) => async (id: string, version?: string) => {\n let service: Service = await getService(directory)(id, version);\n const filePathToService = await findFileById(directory, id, version);\n\n if (!filePathToService) throw new Error('Cannot find directory of service');\n\n let specs = [] as any;\n if (service.specifications) {\n const serviceSpecifications = service.specifications;\n const specificationFiles = Object.keys(serviceSpecifications);\n\n const getSpecs = specificationFiles.map(async (specFile) => {\n const fileName = serviceSpecifications[specFile as keyof Specifications];\n\n if (!fileName) {\n throw new Error(`Specification file name for ${specFile} is undefined`);\n }\n const rawFile = await getFileFromResource(directory, id, { fileName }, version);\n\n return { key: specFile, content: rawFile, fileName: fileName, path: join(dirname(filePathToService), fileName) };\n });\n\n specs = await Promise.all(getSpecs);\n }\n return specs;\n};\n\n/**\n * Add an event/command to a service by it's id.\n *\n * Optionally specify a version to add the event to a specific version of the service.\n *\n * @example\n * ```ts\n * import utils from '@eventcatalog/utils';\n *\n * // Adds an event to the service or command to the service\n * const { addEventToService, addCommandToService } = utils('/path/to/eventcatalog');\n *\n * // Adds a new event (InventoryUpdatedEvent) that the InventoryService will send\n * await addEventToService('InventoryService', 'sends', { event: 'InventoryUpdatedEvent', version: '2.0.0' });\n * * // Adds a new event (OrderComplete) that the InventoryService will receive\n * await addEventToService('InventoryService', 'receives', { event: 'OrderComplete', version: '1.0.0' });\n *\n * // Adds a new command (UpdateInventoryCommand) that the InventoryService will send\n * await addCommandToService('InventoryService', 'sends', { command: 'UpdateInventoryCommand', version: '2.0.0' });\n * // Adds a new command (VerifyInventory) that the InventoryService will receive\n * await addCommandToService('InventoryService', 'receives', { command: 'VerifyInventory', version: '1.0.0' });\n *\n * ```\n */\n\nexport const addMessageToService =\n (directory: string) => async (id: string, direction: string, event: { id: string; version: string }, version?: string) => {\n let service: Service = await getService(directory)(id, version);\n const servicePath = await getResourcePath(directory, id, version);\n const extension = extname(servicePath?.fullPath || '');\n\n if (direction === 'sends') {\n if (service.sends === undefined) {\n service.sends = [];\n }\n // We first check if the event is already in the list\n for (let i = 0; i < service.sends.length; i++) {\n if (service.sends[i].id === event.id && service.sends[i].version === event.version) {\n return;\n }\n }\n service.sends.push({ id: event.id, version: event.version });\n } else if (direction === 'receives') {\n if (service.receives === undefined) {\n service.receives = [];\n }\n // We first check if the event is already in the list\n for (let i = 0; i < service.receives.length; i++) {\n if (service.receives[i].id === event.id && service.receives[i].version === event.version) {\n return;\n }\n }\n service.receives.push({ id: event.id, version: event.version });\n } else {\n throw new Error(`Direction ${direction} is invalid, only 'receives' and 'sends' are supported`);\n }\n\n const existingResource = await findFileById(directory, id, version);\n\n if (!existingResource) {\n throw new Error(`Cannot find service ${id} in the catalog`);\n }\n\n // Get where the service was located, make sure it goes back there.\n const path = existingResource.split('/services')[0];\n const pathToResource = join(path, 'services');\n\n await rmServiceById(directory)(id, version);\n await writeService(pathToResource)(service, { format: extension === '.md' ? 'md' : 'mdx' });\n };\n\n/**\n * Check to see if the catalog has a version for the given service.\n *\n * @example\n * ```ts\n * import utils from '@eventcatalog/utils';\n *\n * const { serviceHasVersion } = utils('/path/to/eventcatalog');\n *\n * // returns true if version is found for the given event and version (supports semver)\n * await serviceHasVersion('InventoryService', '0.0.1');\n * await serviceHasVersion('InventoryService', 'latest');\n * await serviceHasVersion('InventoryService', '0.0.x');*\n *\n * ```\n */\nexport const serviceHasVersion = (directory: string) => async (id: string, version?: string) => {\n const file = await findFileById(directory, id, version);\n return !!file;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAAAA,oBAA8B;AAE9B,IAAAC,sBAAmB;;;ACFnB,kBAA8B;;;ACA9B,kBAAyB;AACzB,qBAAmB;AACnB,sBAAsD;AACtD,uBAA4F;AAC5F,yBAAmB;AACnB,oBAA6C;AAWtC,IAAM,eAAe,OAAO,YAAoB,IAAY,YAAkD;AACnH,QAAM,QAAQ,MAAM,SAAS,GAAG,UAAU,oBAAoB;AAE9D,QAAM,eAAgB,MAAM,iBAAiB,OAAO,EAAE,KAAM,CAAC;AAC7D,QAAM,gBAAgB,aAAa,KAAK,CAAC,SAAS,CAAC,KAAK,SAAS,WAAW,CAAC;AAG7E,MAAI,CAAC,SAAS;AACZ,WAAO;AAAA,EACT;AAGA,QAAM,cAAc,aAAa,IAAI,CAAC,SAAS;AAC7C,UAAM,EAAE,KAAK,IAAI,mBAAAC,QAAO,KAAK,IAAI;AACjC,WAAO,EAAE,GAAG,MAAM,KAAK;AAAA,EACzB,CAAC;AAED,QAAM,kBAAc,0B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AAU,KAAK,OAAO;AAAA,IACxB;AAAA,EACF;AAEA,SAAO,EAAE,WAAW,UAAU;AAChC;","names":["import_node_path","import_gray_matter","matter","match","fsSync","import_gray_matter","import_node_fs","import_semver","matter","fsSync","import_promises","import_node_path","matter"]}