@eventcatalog/sdk 2.9.1 → 2.9.5
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.
- package/README.md +1 -1
- package/dist/channels.mjs +20 -27
- package/dist/channels.mjs.map +1 -1
- package/dist/commands.mjs +18 -19
- package/dist/commands.mjs.map +1 -1
- package/dist/containers.mjs +18 -19
- package/dist/containers.mjs.map +1 -1
- package/dist/custom-docs.mjs +15 -19
- package/dist/custom-docs.mjs.map +1 -1
- package/dist/data-stores.mjs +18 -19
- package/dist/data-stores.mjs.map +1 -1
- package/dist/domains.mjs +25 -26
- package/dist/domains.mjs.map +1 -1
- package/dist/entities.mjs +18 -19
- package/dist/entities.mjs.map +1 -1
- package/dist/eventcatalog.js +2 -2
- package/dist/eventcatalog.js.map +1 -1
- package/dist/eventcatalog.mjs +37 -37
- package/dist/eventcatalog.mjs.map +1 -1
- package/dist/events.mjs +18 -19
- package/dist/events.mjs.map +1 -1
- package/dist/index.js +6 -6
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +38 -38
- package/dist/index.mjs.map +1 -1
- package/dist/messages.mjs +14 -19
- package/dist/messages.mjs.map +1 -1
- package/dist/queries.mjs +18 -19
- package/dist/queries.mjs.map +1 -1
- package/dist/services.mjs +31 -32
- package/dist/services.mjs.map +1 -1
- package/dist/teams.mjs +16 -21
- package/dist/teams.mjs.map +1 -1
- package/dist/types.d.d.mts +1 -0
- package/dist/types.d.d.ts +1 -0
- package/dist/types.d.js.map +1 -1
- package/dist/users.mjs +6 -7
- package/dist/users.mjs.map +1 -1
- package/package.json +5 -1
package/dist/messages.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// src/messages.ts
|
|
2
|
-
import { dirname as
|
|
2
|
+
import { dirname as dirname3 } from "node:path";
|
|
3
3
|
import matter3 from "gray-matter";
|
|
4
4
|
|
|
5
5
|
// src/internal/resources.ts
|
|
@@ -7,21 +7,21 @@ import { dirname as dirname2, join as join2 } from "path";
|
|
|
7
7
|
|
|
8
8
|
// src/internal/utils.ts
|
|
9
9
|
import { globSync } from "glob";
|
|
10
|
-
import fsSync from "fs";
|
|
10
|
+
import fsSync from "node:fs";
|
|
11
11
|
import { copy } from "fs-extra";
|
|
12
|
-
import { join, dirname, normalize, resolve, relative } from "path";
|
|
12
|
+
import { join, dirname, normalize, resolve, relative } from "node:path";
|
|
13
13
|
import matter from "gray-matter";
|
|
14
14
|
import { satisfies, validRange } from "semver";
|
|
15
15
|
var findFileById = async (catalogDir, id, version) => {
|
|
16
16
|
const files = await getFiles(`${catalogDir}/**/index.{md,mdx}`);
|
|
17
17
|
const matchedFiles = await searchFilesForId(files, id) || [];
|
|
18
|
-
const latestVersion = matchedFiles.find((
|
|
18
|
+
const latestVersion = matchedFiles.find((path) => !path.includes("versioned"));
|
|
19
19
|
if (!version) {
|
|
20
20
|
return latestVersion;
|
|
21
21
|
}
|
|
22
|
-
const parsedFiles = matchedFiles.map((
|
|
23
|
-
const { data } = matter.read(
|
|
24
|
-
return { ...data, path
|
|
22
|
+
const parsedFiles = matchedFiles.map((path) => {
|
|
23
|
+
const { data } = matter.read(path);
|
|
24
|
+
return { ...data, path };
|
|
25
25
|
});
|
|
26
26
|
if (version === "latest") {
|
|
27
27
|
return latestVersion;
|
|
@@ -88,12 +88,9 @@ var searchFilesForId = async (files, id, version) => {
|
|
|
88
88
|
|
|
89
89
|
// src/internal/resources.ts
|
|
90
90
|
import matter2 from "gray-matter";
|
|
91
|
-
import
|
|
92
|
-
import fsSync2 from "fs";
|
|
91
|
+
import fsSync2 from "node:fs";
|
|
93
92
|
import { satisfies as satisfies2 } from "semver";
|
|
94
93
|
import { lock, unlock } from "proper-lockfile";
|
|
95
|
-
import { basename as basename2 } from "path";
|
|
96
|
-
import path from "path";
|
|
97
94
|
var getResource = async (catalogDir, id, version, options, filePath) => {
|
|
98
95
|
const attachSchema = options?.attachSchema || false;
|
|
99
96
|
const file = filePath || (id ? await findFileById(catalogDir, id, version) : void 0);
|
|
@@ -164,8 +161,6 @@ var isLatestVersion = async (catalogDir, id, version) => {
|
|
|
164
161
|
};
|
|
165
162
|
|
|
166
163
|
// src/services.ts
|
|
167
|
-
import fs2 from "fs/promises";
|
|
168
|
-
import { join as join3, dirname as dirname3, extname, relative as relative2 } from "path";
|
|
169
164
|
var getServices = (directory) => async (options) => getResources(directory, {
|
|
170
165
|
type: "services",
|
|
171
166
|
ignore: ["**/events/**", "**/commands/**", "**/queries/**", "**/entities/**", "**/subdomains/**/entities/**"],
|
|
@@ -174,8 +169,8 @@ var getServices = (directory) => async (options) => getResources(directory, {
|
|
|
174
169
|
|
|
175
170
|
// src/messages.ts
|
|
176
171
|
import { satisfies as satisfies3, validRange as validRange2 } from "semver";
|
|
177
|
-
var getMessageBySchemaPath = (directory) => async (
|
|
178
|
-
const pathToMessage =
|
|
172
|
+
var getMessageBySchemaPath = (directory) => async (path, options) => {
|
|
173
|
+
const pathToMessage = dirname3(path);
|
|
179
174
|
try {
|
|
180
175
|
const files = await getFiles(`${directory}/${pathToMessage}/index.{md,mdx}`);
|
|
181
176
|
if (!files || files.length === 0) {
|
|
@@ -247,18 +242,18 @@ var getProducersAndConsumersForMessage = (directory) => async (id, version, opti
|
|
|
247
242
|
}
|
|
248
243
|
return { producers, consumers };
|
|
249
244
|
};
|
|
250
|
-
var getConsumersOfSchema = (directory) => async (
|
|
245
|
+
var getConsumersOfSchema = (directory) => async (path) => {
|
|
251
246
|
try {
|
|
252
|
-
const message = await getMessageBySchemaPath(directory)(
|
|
247
|
+
const message = await getMessageBySchemaPath(directory)(path);
|
|
253
248
|
const { consumers } = await getProducersAndConsumersForMessage(directory)(message.id, message.version);
|
|
254
249
|
return consumers;
|
|
255
250
|
} catch (error) {
|
|
256
251
|
return [];
|
|
257
252
|
}
|
|
258
253
|
};
|
|
259
|
-
var getProducersOfSchema = (directory) => async (
|
|
254
|
+
var getProducersOfSchema = (directory) => async (path) => {
|
|
260
255
|
try {
|
|
261
|
-
const message = await getMessageBySchemaPath(directory)(
|
|
256
|
+
const message = await getMessageBySchemaPath(directory)(path);
|
|
262
257
|
const { producers } = await getProducersAndConsumersForMessage(directory)(message.id, message.version);
|
|
263
258
|
return producers;
|
|
264
259
|
} catch (error) {
|
package/dist/messages.mjs.map
CHANGED
|
@@ -1 +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';\nimport { satisfies, validRange } from 'semver';\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 (\n id: string,\n version?: string,\n options?: { latestOnly?: boolean }\n ): Promise<{ producers: Service[]; consumers: Service[] }> => {\n const services = await getServices(directory)({ latestOnly: options?.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 const isServiceUsingSemverRange = validRange(_message.version);\n if (isServiceUsingSemverRange) {\n return _message.id === message.id && satisfies(message.version, _message.version);\n } else {\n return _message.id === message.id && message.version === _message.version;\n }\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 const isServiceUsingSemverRange = validRange(_message.version);\n if (isServiceUsingSemverRange) {\n return _message.id === message.id && satisfies(message.version, _message.version);\n } else {\n return _message.id === message.id && message.version === _message.version;\n }\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\n/**\n * Returns the consumers of a given schema path.\n *\n * @example\n * ```ts\n * import utils from '@eventcatalog/utils';\n *\n * const { getConsumersOfSchema } = utils('/path/to/eventcatalog');\n *\n * // Returns the consumers of a given schema path\n * const consumers = await getConsumersOfSchema('events/InventoryAdjusted/schema.json');\n */\nexport const getConsumersOfSchema = (directory: string) => async (path: string) => {\n try {\n const message = await getMessageBySchemaPath(directory)(path);\n const { consumers } = await getProducersAndConsumersForMessage(directory)(message.id, message.version);\n return consumers;\n } catch (error) {\n return [];\n }\n};\n\n/**\n * Returns the producers of a given schema path.\n *\n * @example\n * ```ts\n * import utils from '@eventcatalog/utils';\n *\n * const { getProducersOfSchema } = utils('/path/to/eventcatalog');\n *\n * // Returns the producers of a given schema path\n * const producers = await getProducersOfSchema('events/InventoryAdjusted/schema.json');\n */\nexport const getProducersOfSchema = (directory: string) => async (path: string) => {\n try {\n const message = await getMessageBySchemaPath(directory)(path);\n const { producers } = await getProducersAndConsumersForMessage(directory)(message.id, message.version);\n return producers;\n } catch (error) {\n return [];\n }\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';\nimport { basename } from 'node:path';\nimport path from 'node:path';\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).replace(/\\/versioned?\\/[^/]+\\//, '/');\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 const ignoreListToCopy = ['events', 'commands', 'queries', 'versioned'];\n\n // Copy the event to the versioned directory\n await copyDir(catalogDir, sourceDirectory, targetDirectory, (src) => {\n // get the folder name\n const folderName = basename(src);\n\n if (ignoreListToCopy.includes(folderName)) {\n return false;\n }\n return true;\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 // Dont remove anything in the ignore list\n if (ignoreListToCopy.includes(file)) {\n return;\n }\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 filePath?: string\n): Promise<Resource | undefined> => {\n const attachSchema = options?.attachSchema || false;\n const file = filePath || (id ? await findFileById(catalogDir, id, version) : undefined);\n if (!file || !fsSync.existsSync(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 getResourceFolderName = async (catalogDir: string, id: string, version?: string) => {\n const paths = await getResourcePath(catalogDir, id, version);\n if (!paths) return;\n return paths?.directory.split(path.sep).filter(Boolean).pop();\n};\n\nexport const toResource = async (catalogDir: string, rawContents: string) => {\n const { data, content } = matter(rawContents);\n return {\n ...data,\n markdown: content.trim(),\n } as Resource;\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 // Verify file is actually removed\n await waitForFileRemoval(file);\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 // Verify directory is actually removed\n await waitForFileRemoval(directory);\n })\n );\n }\n};\n\n// Helper function to ensure file/directory is completely removed\nconst waitForFileRemoval = async (path: string, maxRetries: number = 50, delay: number = 10): Promise<void> => {\n for (let i = 0; i < maxRetries; i++) {\n try {\n await fs.access(path);\n // If access succeeds, file still exists, wait and retry\n await new Promise((resolve) => setTimeout(resolve, delay));\n } catch (error) {\n // If access fails, file is removed\n return;\n }\n }\n // If we reach here, file still exists after all retries\n throw new Error(`File/directory ${path} was not removed after ${maxRetries} attempts`);\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 // Handle 'latest' version - return the latest (non-versioned) file\n if (version === 'latest') {\n return latestVersion;\n }\n\n // First, check for exact version match (handles non-semver versions like '1', '2', etc.)\n const exactMatch = parsedFiles.find((c) => c.version === version);\n if (exactMatch) {\n return exactMatch.path;\n }\n\n // Try semver range matching\n const semverRange = validRange(version);\n\n if (semverRange) {\n const match = parsedFiles.filter((c) => {\n try {\n return satisfies(c.version, semverRange);\n } catch (error) {\n // If satisfies fails (e.g., comparing semver range with non-semver version), skip this file\n return false;\n }\n });\n return match.length > 0 ? match[0].path : undefined;\n }\n\n // If no exact match and no valid semver range, return undefined\n return undefined;\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, relative } from 'node:path';\nimport {\n addFileToResource,\n getFileFromResource,\n getResource,\n rmResourceById,\n versionResource,\n writeResource,\n getVersionedDirectory,\n getResources,\n getResourcePath,\n toResource,\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 a service from EventCatalog by it's path.\n *\n * @example\n * ```ts\n * import utils from '@eventcatalog/utils';\n *\n * const { getServiceByPath } = utils('/path/to/eventcatalog');\n *\n * // Returns a service from the catalog by it's path\n * const service = await getServiceByPath('/services/InventoryService/index.mdx');\n * ```\n */\nexport const getServiceByPath = (directory: string) => async (path: string) => {\n const service = await getResource(directory, undefined, undefined, { type: 'service' }, path);\n return service as Service;\n};\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 await rmResourceById(directory, id, version, { type: 'service', persistFiles });\n};\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 let specificationFiles;\n\n if (Array.isArray(serviceSpecifications)) {\n specificationFiles = serviceSpecifications.map((spec) => ({ key: spec.type, path: spec.path }));\n } else {\n specificationFiles = Object.keys(serviceSpecifications).map((spec) => ({\n key: spec,\n path: serviceSpecifications[spec as keyof Specifications] as string,\n }));\n }\n\n const getSpecs = specificationFiles.map(async ({ key, path: fileName }) => {\n if (!fileName) {\n throw new Error(`Specification file name for ${fileName} is undefined`);\n }\n const rawFile = await getFileFromResource(directory, id, { fileName }, version);\n\n return { key, 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\n/**\n * Check to see if the path is a service.\n *\n * @example\n * ```ts\n * import utils from '@eventcatalog/utils';\n *\n * const { isService } = utils('/path/to/eventcatalog');\n *\n * // returns true if the path is a service\n * await isService('/services/InventoryService/index.mdx');\n * ```\n */\nexport const isService = (directory: string) => async (path: string) => {\n const service = await getServiceByPath(directory)(path);\n // Get relative path from root directory\n const relativePath = relative(directory, path);\n\n // Split into path segments using regex to handle both / and \\\n const segments = relativePath.split(/[/\\\\]+/);\n\n // needs to workf or windows too\n return !!service && segments.includes('services');\n};\n\n/**\n * Takes a given raw file and converts it to a service.\n *\n * @param directory - The directory to convert the file to a service.\n * @returns The service.\n * @example\n * ```ts\n * import utils from '@eventcatalog/utils';\n *\n * const { toService } = utils('/path/to/eventcatalog');\n *\n * // Read the file from somewhere\n * const file = fs.readFileSync('/path/to/services/InventoryService/index.mdx', 'utf8');\n *\n * // Converts the raw file to a service\n * await toService(file);\n * ```\n */\nexport const toService = (directory: string) => async (file: string) => toResource(directory, file) as Promise<Service>;\n\n/**\n * Add an entity to a service by its id.\n *\n * @example\n * ```ts\n * import utils from '@eventcatalog/utils';\n *\n * const { addEntityToService } = utils('/path/to/eventcatalog');\n *\n * // adds a new entity (User) to the InventoryService\n * await addEntityToService('InventoryService', { id: 'User', version: '1.0.0' });\n *\n * // adds a new entity (Product) to a specific version of the InventoryService\n * await addEntityToService('InventoryService', { id: 'Product', version: '1.0.0' }, '2.0.0');\n *\n * ```\n */\nexport const addEntityToService =\n (directory: string) => async (id: string, entity: { 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 (service.entities === undefined) {\n service.entities = [];\n }\n\n // Check if the entity is already in the list\n for (let i = 0; i < service.entities.length; i++) {\n if (service.entities[i].id === entity.id && service.entities[i].version === entity.version) {\n return;\n }\n }\n\n service.entities.push({ id: entity.id, version: entity.version });\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 * Add a data store to a service by it's id.\n *\n * Optionally specify a version to add the data store to a specific version of the service.\n *\n * @example\n * ```ts\n * import utils from '@eventcatalog/utils';\n *\n * // Adds an data store to the service\n * const { addDataStoreToService } = utils('/path/to/eventcatalog');\n *\n * // Adds a new data store (orders-db) that the InventoryService will write to\n * await addDataStoreToService('InventoryService', 'writesTo', { id: 'orders-db', version: '2.0.0' });\n *\n * * // Adds a new data store (OrderComplete) that the InventoryService will read from\n * await addDataStoreToService('InventoryService', 'readsFrom', { id: 'orders-db', version: '1.0.0' });\n *\n * ```\n */\n\nexport const addDataStoreToService =\n (directory: string) =>\n async (id: string, operation: 'writesTo' | 'readsFrom', dataStore: { 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 (operation === 'writesTo') {\n if (service.writesTo === undefined) {\n service.writesTo = [];\n }\n\n // We first check if the data store is already in the list\n for (let i = 0; i < service.writesTo.length; i++) {\n if (service.writesTo[i].id === dataStore.id && service.writesTo[i].version === dataStore.version) {\n return;\n }\n }\n\n service.writesTo.push({ id: dataStore.id, version: dataStore.version });\n } else if (operation === 'readsFrom') {\n if (service.readsFrom === undefined) {\n service.readsFrom = [];\n }\n\n // We first check if the data store is already in the list\n for (let i = 0; i < service.readsFrom.length; i++) {\n if (service.readsFrom[i].id === dataStore.id && service.readsFrom[i].version === dataStore.version) {\n return;\n }\n }\n service.readsFrom.push({ id: dataStore.id, version: dataStore.version });\n } else {\n throw new Error(`Operation ${operation} is invalid, only 'writesTo' and 'readsFrom' 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"],"mappings":";AAAA,SAAS,WAAAA,gBAAqB;AAE9B,OAAOC,aAAY;;;ACFnB,SAAS,WAAAC,UAAS,QAAAC,aAAY;;;ACA9B,SAAS,gBA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A,EACT,SAAS,OAAO;AACd,WAAO,CAAC;AAAA,EACV;AACF;AAcO,IAAM,uBAAuB,CAAC,cAAsB,OAAOA,UAAiB;AACjF,MAAI;AACF,UAAM,UAAU,MAAM,uBAAuB,SAAS,EAAEA,KAAI;AAC5D,UAAM,EAAE,UAAU,IAAI,MAAM,mCAAmC,SAAS,EAAE,QAAQ,IAAI,QAAQ,OAAO;AACrG,WAAO;AAAA,EACT,SAAS,OAAO;AACd,WAAO,CAAC;AAAA,EACV;AACF;","names":["dirname","matter","dirname","join","path","matter","fsSync","satisfies","basename","fsSync","matter","dirname","join","matter","dirname","join","fsSync","fs","join","dirname","relative","satisfies","validRange","path","dirname","matter"]}
|
|
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';\nimport { satisfies, validRange } from 'semver';\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 (\n id: string,\n version?: string,\n options?: { latestOnly?: boolean }\n ): Promise<{ producers: Service[]; consumers: Service[] }> => {\n const services = await getServices(directory)({ latestOnly: options?.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 const isServiceUsingSemverRange = validRange(_message.version);\n if (isServiceUsingSemverRange) {\n return _message.id === message.id && satisfies(message.version, _message.version);\n } else {\n return _message.id === message.id && message.version === _message.version;\n }\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 const isServiceUsingSemverRange = validRange(_message.version);\n if (isServiceUsingSemverRange) {\n return _message.id === message.id && satisfies(message.version, _message.version);\n } else {\n return _message.id === message.id && message.version === _message.version;\n }\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\n/**\n * Returns the consumers of a given schema path.\n *\n * @example\n * ```ts\n * import utils from '@eventcatalog/utils';\n *\n * const { getConsumersOfSchema } = utils('/path/to/eventcatalog');\n *\n * // Returns the consumers of a given schema path\n * const consumers = await getConsumersOfSchema('events/InventoryAdjusted/schema.json');\n */\nexport const getConsumersOfSchema = (directory: string) => async (path: string) => {\n try {\n const message = await getMessageBySchemaPath(directory)(path);\n const { consumers } = await getProducersAndConsumersForMessage(directory)(message.id, message.version);\n return consumers;\n } catch (error) {\n return [];\n }\n};\n\n/**\n * Returns the producers of a given schema path.\n *\n * @example\n * ```ts\n * import utils from '@eventcatalog/utils';\n *\n * const { getProducersOfSchema } = utils('/path/to/eventcatalog');\n *\n * // Returns the producers of a given schema path\n * const producers = await getProducersOfSchema('events/InventoryAdjusted/schema.json');\n */\nexport const getProducersOfSchema = (directory: string) => async (path: string) => {\n try {\n const message = await getMessageBySchemaPath(directory)(path);\n const { producers } = await getProducersAndConsumersForMessage(directory)(message.id, message.version);\n return producers;\n } catch (error) {\n return [];\n }\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';\nimport { basename } from 'node:path';\nimport path from 'node:path';\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).replace(/\\/versioned?\\/[^/]+\\//, '/');\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 const ignoreListToCopy = ['events', 'commands', 'queries', 'versioned'];\n\n // Copy the event to the versioned directory\n await copyDir(catalogDir, sourceDirectory, targetDirectory, (src) => {\n // get the folder name\n const folderName = basename(src);\n\n if (ignoreListToCopy.includes(folderName)) {\n return false;\n }\n return true;\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 // Dont remove anything in the ignore list\n if (ignoreListToCopy.includes(file)) {\n return;\n }\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 filePath?: string\n): Promise<Resource | undefined> => {\n const attachSchema = options?.attachSchema || false;\n const file = filePath || (id ? await findFileById(catalogDir, id, version) : undefined);\n if (!file || !fsSync.existsSync(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 getResourceFolderName = async (catalogDir: string, id: string, version?: string) => {\n const paths = await getResourcePath(catalogDir, id, version);\n if (!paths) return;\n return paths?.directory.split(path.sep).filter(Boolean).pop();\n};\n\nexport const toResource = async (catalogDir: string, rawContents: string) => {\n const { data, content } = matter(rawContents);\n return {\n ...data,\n markdown: content.trim(),\n } as Resource;\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 // Verify file is actually removed\n await waitForFileRemoval(file);\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 // Verify directory is actually removed\n await waitForFileRemoval(directory);\n })\n );\n }\n};\n\n// Helper function to ensure file/directory is completely removed\nconst waitForFileRemoval = async (path: string, maxRetries: number = 50, delay: number = 10): Promise<void> => {\n for (let i = 0; i < maxRetries; i++) {\n try {\n await fs.access(path);\n // If access succeeds, file still exists, wait and retry\n await new Promise((resolve) => setTimeout(resolve, delay));\n } catch (error) {\n // If access fails, file is removed\n return;\n }\n }\n // If we reach here, file still exists after all retries\n throw new Error(`File/directory ${path} was not removed after ${maxRetries} attempts`);\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 // Handle 'latest' version - return the latest (non-versioned) file\n if (version === 'latest') {\n return latestVersion;\n }\n\n // First, check for exact version match (handles non-semver versions like '1', '2', etc.)\n const exactMatch = parsedFiles.find((c) => c.version === version);\n if (exactMatch) {\n return exactMatch.path;\n }\n\n // Try semver range matching\n const semverRange = validRange(version);\n\n if (semverRange) {\n const match = parsedFiles.filter((c) => {\n try {\n return satisfies(c.version, semverRange);\n } catch (error) {\n // If satisfies fails (e.g., comparing semver range with non-semver version), skip this file\n return false;\n }\n });\n return match.length > 0 ? match[0].path : undefined;\n }\n\n // If no exact match and no valid semver range, return undefined\n return undefined;\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, relative } from 'node:path';\nimport {\n addFileToResource,\n getFileFromResource,\n getResource,\n rmResourceById,\n versionResource,\n writeResource,\n getVersionedDirectory,\n getResources,\n getResourcePath,\n toResource,\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 a service from EventCatalog by it's path.\n *\n * @example\n * ```ts\n * import utils from '@eventcatalog/utils';\n *\n * const { getServiceByPath } = utils('/path/to/eventcatalog');\n *\n * // Returns a service from the catalog by it's path\n * const service = await getServiceByPath('/services/InventoryService/index.mdx');\n * ```\n */\nexport const getServiceByPath = (directory: string) => async (path: string) => {\n const service = await getResource(directory, undefined, undefined, { type: 'service' }, path);\n return service as Service;\n};\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 await rmResourceById(directory, id, version, { type: 'service', persistFiles });\n};\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 let specificationFiles;\n\n if (Array.isArray(serviceSpecifications)) {\n specificationFiles = serviceSpecifications.map((spec) => ({ key: spec.type, path: spec.path }));\n } else {\n specificationFiles = Object.keys(serviceSpecifications).map((spec) => ({\n key: spec,\n path: serviceSpecifications[spec as keyof Specifications] as string,\n }));\n }\n\n const getSpecs = specificationFiles.map(async ({ key, path: fileName }) => {\n if (!fileName) {\n throw new Error(`Specification file name for ${fileName} is undefined`);\n }\n const rawFile = await getFileFromResource(directory, id, { fileName }, version);\n\n return { key, 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\n/**\n * Check to see if the path is a service.\n *\n * @example\n * ```ts\n * import utils from '@eventcatalog/utils';\n *\n * const { isService } = utils('/path/to/eventcatalog');\n *\n * // returns true if the path is a service\n * await isService('/services/InventoryService/index.mdx');\n * ```\n */\nexport const isService = (directory: string) => async (path: string) => {\n const service = await getServiceByPath(directory)(path);\n // Get relative path from root directory\n const relativePath = relative(directory, path);\n\n // Split into path segments using regex to handle both / and \\\n const segments = relativePath.split(/[/\\\\]+/);\n\n // needs to workf or windows too\n return !!service && segments.includes('services');\n};\n\n/**\n * Takes a given raw file and converts it to a service.\n *\n * @param directory - The directory to convert the file to a service.\n * @returns The service.\n * @example\n * ```ts\n * import utils from '@eventcatalog/utils';\n *\n * const { toService } = utils('/path/to/eventcatalog');\n *\n * // Read the file from somewhere\n * const file = fs.readFileSync('/path/to/services/InventoryService/index.mdx', 'utf8');\n *\n * // Converts the raw file to a service\n * await toService(file);\n * ```\n */\nexport const toService = (directory: string) => async (file: string) => toResource(directory, file) as Promise<Service>;\n\n/**\n * Add an entity to a service by its id.\n *\n * @example\n * ```ts\n * import utils from '@eventcatalog/utils';\n *\n * const { addEntityToService } = utils('/path/to/eventcatalog');\n *\n * // adds a new entity (User) to the InventoryService\n * await addEntityToService('InventoryService', { id: 'User', version: '1.0.0' });\n *\n * // adds a new entity (Product) to a specific version of the InventoryService\n * await addEntityToService('InventoryService', { id: 'Product', version: '1.0.0' }, '2.0.0');\n *\n * ```\n */\nexport const addEntityToService =\n (directory: string) => async (id: string, entity: { 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 (service.entities === undefined) {\n service.entities = [];\n }\n\n // Check if the entity is already in the list\n for (let i = 0; i < service.entities.length; i++) {\n if (service.entities[i].id === entity.id && service.entities[i].version === entity.version) {\n return;\n }\n }\n\n service.entities.push({ id: entity.id, version: entity.version });\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 * Add a data store to a service by it's id.\n *\n * Optionally specify a version to add the data store to a specific version of the service.\n *\n * @example\n * ```ts\n * import utils from '@eventcatalog/utils';\n *\n * // Adds an data store to the service\n * const { addDataStoreToService } = utils('/path/to/eventcatalog');\n *\n * // Adds a new data store (orders-db) that the InventoryService will write to\n * await addDataStoreToService('InventoryService', 'writesTo', { id: 'orders-db', version: '2.0.0' });\n *\n * * // Adds a new data store (OrderComplete) that the InventoryService will read from\n * await addDataStoreToService('InventoryService', 'readsFrom', { id: 'orders-db', version: '1.0.0' });\n *\n * ```\n */\n\nexport const addDataStoreToService =\n (directory: string) =>\n async (id: string, operation: 'writesTo' | 'readsFrom', dataStore: { 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 (operation === 'writesTo') {\n if (service.writesTo === undefined) {\n service.writesTo = [];\n }\n\n // We first check if the data store is already in the list\n for (let i = 0; i < service.writesTo.length; i++) {\n if (service.writesTo[i].id === dataStore.id && service.writesTo[i].version === dataStore.version) {\n return;\n }\n }\n\n service.writesTo.push({ id: dataStore.id, version: dataStore.version });\n } else if (operation === 'readsFrom') {\n if (service.readsFrom === undefined) {\n service.readsFrom = [];\n }\n\n // We first check if the data store is already in the list\n for (let i = 0; i < service.readsFrom.length; i++) {\n if (service.readsFrom[i].id === dataStore.id && service.readsFrom[i].version === dataStore.version) {\n return;\n }\n }\n service.readsFrom.push({ id: dataStore.id, version: dataStore.version });\n } else {\n throw new Error(`Operation ${operation} is invalid, only 'writesTo' and 'readsFrom' 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"],"mappings":";AAAA,SAAS,WAAAA,gBAAqB;AAE9B,OAAOC,aAAY;;;ACFnB,SAAS,WAAAC,UAAS,QAAAC,aAAY;;;ACA9B,SAAS,gBAAgB;AACzB,OAAO,YAAY;AACnB,SAAS,YAA6C;AACtD,SAAS,MAAM,SAAS,WAAiC,SAAmB,gBAAgB;AAC5F,OAAO,YAAY;AACnB,SAAS,WAAW,kBAAyB;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,OAAO,KAAK,IAAI;AACjC,WAAO,EAAE,GAAG,MAAM,KAAK;AAAA,EACzB,CAAC;AAGD,MAAI,YAAY,UAAU;AACxB,WAAO;AAAA,EACT;AAGA,QAAM,aAAa,YAAY,KAAK,CAAC,MAAM,EAAE,YAAY,OAAO;AAChE,MAAI,YAAY;AACd,WAAO,WAAW;AAAA,EACpB;AAGA,QAAM,cAAc,WAAW,OAAO;AAEtC,MAAI,aAAa;AACf,UAAM,QAAQ,YAAY,OAAO,CAAC,MAAM;AACtC,UAAI;AACF,eAAO,UAAU,EAAE,SAAS,WAAW;AAAA,MACzC,SAAS,OAAO;AAEd,eAAO;AAAA,MACT;AAAA,IACF,CAAC;AACD,WAAO,MAAM,SAAS,IAAI,MAAM,CAAC,EAAE,OAAO;AAAA,EAC5C;AAGA,SAAO;AACT;AAEO,IA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AAM,mCAAmC,SAAS,EAAE,QAAQ,IAAI,QAAQ,OAAO;AACrG,WAAO;AAAA,EACT,SAAS,OAAO;AACd,WAAO,CAAC;AAAA,EACV;AACF;AAcO,IAAM,uBAAuB,CAAC,cAAsB,OAAO,SAAiB;AACjF,MAAI;AACF,UAAM,UAAU,MAAM,uBAAuB,SAAS,EAAE,IAAI;AAC5D,UAAM,EAAE,UAAU,IAAI,MAAM,mCAAmC,SAAS,EAAE,QAAQ,IAAI,QAAQ,OAAO;AACrG,WAAO;AAAA,EACT,SAAS,OAAO;AACd,WAAO,CAAC;AAAA,EACV;AACF;","names":["dirname","matter","dirname","join","matter","fsSync","satisfies","fsSync","matter","dirname","join","matter","dirname","join","fsSync","satisfies","validRange","dirname","matter"]}
|
package/dist/queries.mjs
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
// src/queries.ts
|
|
2
|
-
import fs2 from "fs/promises";
|
|
3
|
-
import { join as join3 } from "path";
|
|
2
|
+
import fs2 from "node:fs/promises";
|
|
3
|
+
import { join as join3 } from "node:path";
|
|
4
4
|
|
|
5
5
|
// src/internal/utils.ts
|
|
6
6
|
import { globSync } from "glob";
|
|
7
|
-
import fsSync from "fs";
|
|
7
|
+
import fsSync from "node:fs";
|
|
8
8
|
import { copy } from "fs-extra";
|
|
9
|
-
import { join, dirname, normalize, resolve, relative } from "path";
|
|
9
|
+
import { join, dirname, normalize, resolve, relative } from "node:path";
|
|
10
10
|
import matter from "gray-matter";
|
|
11
11
|
import { satisfies, validRange } from "semver";
|
|
12
12
|
var versionExists = async (catalogDir, id, version) => {
|
|
@@ -17,13 +17,13 @@ var versionExists = async (catalogDir, id, version) => {
|
|
|
17
17
|
var findFileById = async (catalogDir, id, version) => {
|
|
18
18
|
const files = await getFiles(`${catalogDir}/**/index.{md,mdx}`);
|
|
19
19
|
const matchedFiles = await searchFilesForId(files, id) || [];
|
|
20
|
-
const latestVersion = matchedFiles.find((
|
|
20
|
+
const latestVersion = matchedFiles.find((path) => !path.includes("versioned"));
|
|
21
21
|
if (!version) {
|
|
22
22
|
return latestVersion;
|
|
23
23
|
}
|
|
24
|
-
const parsedFiles = matchedFiles.map((
|
|
25
|
-
const { data } = matter.read(
|
|
26
|
-
return { ...data, path
|
|
24
|
+
const parsedFiles = matchedFiles.map((path) => {
|
|
25
|
+
const { data } = matter.read(path);
|
|
26
|
+
return { ...data, path };
|
|
27
27
|
});
|
|
28
28
|
if (version === "latest") {
|
|
29
29
|
return latestVersion;
|
|
@@ -104,12 +104,11 @@ var copyDir = async (catalogDir, source, target, filter) => {
|
|
|
104
104
|
// src/internal/resources.ts
|
|
105
105
|
import { dirname as dirname2, join as join2 } from "path";
|
|
106
106
|
import matter2 from "gray-matter";
|
|
107
|
-
import fs from "fs/promises";
|
|
108
|
-
import fsSync2 from "fs";
|
|
107
|
+
import fs from "node:fs/promises";
|
|
108
|
+
import fsSync2 from "node:fs";
|
|
109
109
|
import { satisfies as satisfies2 } from "semver";
|
|
110
110
|
import { lock, unlock } from "proper-lockfile";
|
|
111
|
-
import { basename as basename2 } from "path";
|
|
112
|
-
import path from "path";
|
|
111
|
+
import { basename as basename2 } from "node:path";
|
|
113
112
|
var versionResource = async (catalogDir, id) => {
|
|
114
113
|
const files = await getFiles(`${catalogDir}/**/index.{md,mdx}`);
|
|
115
114
|
const matchedFiles = await searchFilesForId(files, id);
|
|
@@ -149,8 +148,8 @@ var writeResource = async (catalogDir, resource, options = {
|
|
|
149
148
|
versionExistingContent: false,
|
|
150
149
|
format: "mdx"
|
|
151
150
|
}) => {
|
|
152
|
-
const
|
|
153
|
-
const fullPath = join2(catalogDir,
|
|
151
|
+
const path = options.path || `/${resource.id}`;
|
|
152
|
+
const fullPath = join2(catalogDir, path);
|
|
154
153
|
const format = options.format || "mdx";
|
|
155
154
|
fsSync2.mkdirSync(fullPath, { recursive: true });
|
|
156
155
|
const lockPath = join2(fullPath, `index.${format}`);
|
|
@@ -270,16 +269,16 @@ var rmResourceById = async (catalogDir, id, version, options) => {
|
|
|
270
269
|
);
|
|
271
270
|
}
|
|
272
271
|
};
|
|
273
|
-
var waitForFileRemoval = async (
|
|
272
|
+
var waitForFileRemoval = async (path, maxRetries = 50, delay = 10) => {
|
|
274
273
|
for (let i = 0; i < maxRetries; i++) {
|
|
275
274
|
try {
|
|
276
|
-
await fs.access(
|
|
275
|
+
await fs.access(path);
|
|
277
276
|
await new Promise((resolve2) => setTimeout(resolve2, delay));
|
|
278
277
|
} catch (error) {
|
|
279
278
|
return;
|
|
280
279
|
}
|
|
281
280
|
}
|
|
282
|
-
throw new Error(`File/directory ${
|
|
281
|
+
throw new Error(`File/directory ${path} was not removed after ${maxRetries} attempts`);
|
|
283
282
|
};
|
|
284
283
|
var addFileToResource = async (catalogDir, id, file, version) => {
|
|
285
284
|
const pathToResource = await findFileById(catalogDir, id, version);
|
|
@@ -314,8 +313,8 @@ var writeQueryToService = (directory) => async (query, service, options = { path
|
|
|
314
313
|
pathForQuery = join3(pathForQuery, query.id);
|
|
315
314
|
await writeResource(directory, { ...query }, { ...options, path: pathForQuery, type: "query" });
|
|
316
315
|
};
|
|
317
|
-
var rmQuery = (directory) => async (
|
|
318
|
-
await fs2.rm(join3(directory,
|
|
316
|
+
var rmQuery = (directory) => async (path) => {
|
|
317
|
+
await fs2.rm(join3(directory, path), { recursive: true });
|
|
319
318
|
};
|
|
320
319
|
var rmQueryById = (directory) => async (id, version, persistFiles) => {
|
|
321
320
|
await rmResourceById(directory, id, version, { type: "query", persistFiles });
|