@eventcatalog/sdk 2.10.0 → 2.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (108) hide show
  1. package/README.md +86 -1
  2. package/dist/cli/index.d.mts +1 -0
  3. package/dist/cli/index.d.ts +1 -0
  4. package/dist/{eventcatalog.js → cli/index.js} +691 -347
  5. package/dist/cli/index.js.map +1 -0
  6. package/dist/{eventcatalog.mjs → cli/index.mjs} +765 -401
  7. package/dist/cli/index.mjs.map +1 -0
  8. package/dist/cli-docs.d.mts +43 -0
  9. package/dist/cli-docs.d.ts +43 -0
  10. package/dist/cli-docs.js +1513 -0
  11. package/dist/cli-docs.js.map +1 -0
  12. package/dist/cli-docs.mjs +1485 -0
  13. package/dist/cli-docs.mjs.map +1 -0
  14. package/dist/index.d.mts +504 -4
  15. package/dist/index.d.ts +504 -4
  16. package/dist/index.js +325 -108
  17. package/dist/index.js.map +1 -1
  18. package/dist/index.mjs +325 -108
  19. package/dist/index.mjs.map +1 -1
  20. package/package.json +13 -4
  21. package/dist/channels.d.mts +0 -214
  22. package/dist/channels.d.ts +0 -214
  23. package/dist/channels.js +0 -432
  24. package/dist/channels.js.map +0 -1
  25. package/dist/channels.mjs +0 -384
  26. package/dist/channels.mjs.map +0 -1
  27. package/dist/commands.d.mts +0 -274
  28. package/dist/commands.d.ts +0 -274
  29. package/dist/commands.js +0 -394
  30. package/dist/commands.js.map +0 -1
  31. package/dist/commands.mjs +0 -350
  32. package/dist/commands.mjs.map +0 -1
  33. package/dist/containers.d.mts +0 -179
  34. package/dist/containers.d.ts +0 -179
  35. package/dist/containers.js +0 -388
  36. package/dist/containers.js.map +0 -1
  37. package/dist/containers.mjs +0 -345
  38. package/dist/containers.mjs.map +0 -1
  39. package/dist/custom-docs.d.mts +0 -89
  40. package/dist/custom-docs.d.ts +0 -89
  41. package/dist/custom-docs.js +0 -164
  42. package/dist/custom-docs.js.map +0 -1
  43. package/dist/custom-docs.mjs +0 -122
  44. package/dist/custom-docs.mjs.map +0 -1
  45. package/dist/data-stores.d.mts +0 -179
  46. package/dist/data-stores.d.ts +0 -179
  47. package/dist/data-stores.js +0 -401
  48. package/dist/data-stores.js.map +0 -1
  49. package/dist/data-stores.mjs +0 -356
  50. package/dist/data-stores.mjs.map +0 -1
  51. package/dist/domains.d.mts +0 -297
  52. package/dist/domains.d.ts +0 -297
  53. package/dist/domains.js +0 -480
  54. package/dist/domains.js.map +0 -1
  55. package/dist/domains.mjs +0 -433
  56. package/dist/domains.mjs.map +0 -1
  57. package/dist/entities.d.mts +0 -174
  58. package/dist/entities.d.ts +0 -174
  59. package/dist/entities.js +0 -348
  60. package/dist/entities.js.map +0 -1
  61. package/dist/entities.mjs +0 -307
  62. package/dist/entities.mjs.map +0 -1
  63. package/dist/eventcatalog.d.mts +0 -21
  64. package/dist/eventcatalog.d.ts +0 -21
  65. package/dist/eventcatalog.js.map +0 -1
  66. package/dist/eventcatalog.mjs.map +0 -1
  67. package/dist/events.d.mts +0 -276
  68. package/dist/events.d.ts +0 -276
  69. package/dist/events.js +0 -393
  70. package/dist/events.js.map +0 -1
  71. package/dist/events.mjs +0 -349
  72. package/dist/events.mjs.map +0 -1
  73. package/dist/messages.d.mts +0 -65
  74. package/dist/messages.d.ts +0 -65
  75. package/dist/messages.js +0 -312
  76. package/dist/messages.js.map +0 -1
  77. package/dist/messages.mjs +0 -269
  78. package/dist/messages.mjs.map +0 -1
  79. package/dist/queries.d.mts +0 -276
  80. package/dist/queries.d.ts +0 -276
  81. package/dist/queries.js +0 -394
  82. package/dist/queries.js.map +0 -1
  83. package/dist/queries.mjs +0 -350
  84. package/dist/queries.mjs.map +0 -1
  85. package/dist/services.d.mts +0 -384
  86. package/dist/services.d.ts +0 -384
  87. package/dist/services.js +0 -577
  88. package/dist/services.js.map +0 -1
  89. package/dist/services.mjs +0 -526
  90. package/dist/services.mjs.map +0 -1
  91. package/dist/teams.d.mts +0 -90
  92. package/dist/teams.d.ts +0 -90
  93. package/dist/teams.js +0 -246
  94. package/dist/teams.js.map +0 -1
  95. package/dist/teams.mjs +0 -202
  96. package/dist/teams.mjs.map +0 -1
  97. package/dist/types.d.d.mts +0 -304
  98. package/dist/types.d.d.ts +0 -304
  99. package/dist/types.d.js +0 -19
  100. package/dist/types.d.js.map +0 -1
  101. package/dist/types.d.mjs +0 -1
  102. package/dist/types.d.mjs.map +0 -1
  103. package/dist/users.d.mts +0 -83
  104. package/dist/users.d.ts +0 -83
  105. package/dist/users.js +0 -127
  106. package/dist/users.js.map +0 -1
  107. package/dist/users.mjs +0 -88
  108. package/dist/users.mjs.map +0 -1
@@ -1,164 +0,0 @@
1
- "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __export = (target, all) => {
9
- for (var name in all)
10
- __defProp(target, name, { get: all[name], enumerable: true });
11
- };
12
- var __copyProps = (to, from, except, desc) => {
13
- if (from && typeof from === "object" || typeof from === "function") {
14
- for (let key of __getOwnPropNames(from))
15
- if (!__hasOwnProp.call(to, key) && key !== except)
16
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
- }
18
- return to;
19
- };
20
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
- // If the importer is in node compatibility mode or this is not an ESM
22
- // file that has been converted to a CommonJS file using a Babel-
23
- // compatible transform (i.e. "__esModule" has not been set), then set
24
- // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
- mod
27
- ));
28
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
-
30
- // src/custom-docs.ts
31
- var custom_docs_exports = {};
32
- __export(custom_docs_exports, {
33
- getCustomDoc: () => getCustomDoc,
34
- getCustomDocs: () => getCustomDocs,
35
- rmCustomDoc: () => rmCustomDoc,
36
- writeCustomDoc: () => writeCustomDoc
37
- });
38
- module.exports = __toCommonJS(custom_docs_exports);
39
- var import_node_path4 = __toESM(require("path"));
40
-
41
- // src/internal/utils.ts
42
- var import_glob = require("glob");
43
- var import_node_fs = __toESM(require("fs"));
44
- var import_fs_extra = require("fs-extra");
45
- var import_node_path = require("path");
46
- var import_gray_matter = __toESM(require("gray-matter"));
47
- var import_semver = require("semver");
48
- var getFiles = async (pattern, ignore = "") => {
49
- try {
50
- const normalizedInputPattern = (0, import_node_path.normalize)(pattern);
51
- const absoluteBaseDir = (0, import_node_path.resolve)(
52
- normalizedInputPattern.includes("**") ? normalizedInputPattern.split("**")[0] : (0, import_node_path.dirname)(normalizedInputPattern)
53
- );
54
- let relativePattern = (0, import_node_path.relative)(absoluteBaseDir, normalizedInputPattern);
55
- relativePattern = relativePattern.replace(/\\/g, "/");
56
- const ignoreList = Array.isArray(ignore) ? ignore : [ignore];
57
- const files = (0, import_glob.globSync)(relativePattern, {
58
- cwd: absoluteBaseDir,
59
- ignore: ["node_modules/**", ...ignoreList],
60
- absolute: true,
61
- nodir: true
62
- });
63
- return files.map(import_node_path.normalize);
64
- } catch (error) {
65
- const absoluteBaseDirForError = (0, import_node_path.resolve)(
66
- (0, import_node_path.normalize)(pattern).includes("**") ? (0, import_node_path.normalize)(pattern).split("**")[0] : (0, import_node_path.dirname)((0, import_node_path.normalize)(pattern))
67
- );
68
- const relativePatternForError = (0, import_node_path.relative)(absoluteBaseDirForError, (0, import_node_path.normalize)(pattern)).replace(/\\/g, "/");
69
- throw new Error(
70
- `Error finding files for pattern "${pattern}" (using cwd: "${absoluteBaseDirForError}", globPattern: "${relativePatternForError}"): ${error.message}`
71
- );
72
- }
73
- };
74
- var readMdxFile = async (path3) => {
75
- const { data } = import_gray_matter.default.read(path3);
76
- const { markdown, ...frontmatter } = data;
77
- return { ...frontmatter, markdown };
78
- };
79
-
80
- // src/custom-docs.ts
81
- var import_node_fs3 = __toESM(require("fs"));
82
- var import_promises2 = __toESM(require("fs/promises"));
83
- var import_gray_matter3 = __toESM(require("gray-matter"));
84
-
85
- // src/internal/resources.ts
86
- var import_path = require("path");
87
- var import_gray_matter2 = __toESM(require("gray-matter"));
88
- var import_promises = __toESM(require("fs/promises"));
89
- var import_node_fs2 = __toESM(require("fs"));
90
- var import_semver2 = require("semver");
91
- var import_proper_lockfile = require("proper-lockfile");
92
- var import_node_path2 = require("path");
93
- var import_node_path3 = __toESM(require("path"));
94
- var getResources = async (catalogDir, {
95
- type,
96
- latestOnly = false,
97
- ignore = [],
98
- pattern = "",
99
- attachSchema = false
100
- }) => {
101
- const ignoreList = latestOnly ? `**/versioned/**` : "";
102
- const filePattern = pattern || `${catalogDir}/**/${type}/**/index.{md,mdx}`;
103
- const files = await getFiles(filePattern, [ignoreList, ...ignore]);
104
- if (files.length === 0) return;
105
- return files.map((file) => {
106
- const { data, content } = import_gray_matter2.default.read(file);
107
- if (attachSchema && data?.schemaPath) {
108
- const resourceDirectory = (0, import_path.dirname)(file);
109
- const pathToSchema = (0, import_path.join)(resourceDirectory, data.schemaPath);
110
- if (import_node_fs2.default.existsSync(pathToSchema)) {
111
- const schema = import_node_fs2.default.readFileSync(pathToSchema, "utf8");
112
- try {
113
- data.schema = JSON.parse(schema);
114
- } catch (error) {
115
- data.schema = schema;
116
- }
117
- }
118
- }
119
- return {
120
- ...data,
121
- markdown: content.trim()
122
- };
123
- });
124
- };
125
-
126
- // src/custom-docs.ts
127
- var import_slugify = __toESM(require("slugify"));
128
- var getCustomDoc = (directory) => async (filePath) => {
129
- const fullPath = import_node_path4.default.join(directory, filePath);
130
- const fullPathWithExtension = fullPath.endsWith(".mdx") ? fullPath : `${fullPath}.mdx`;
131
- const fileExists = import_node_fs3.default.existsSync(fullPathWithExtension);
132
- if (!fileExists) {
133
- return void 0;
134
- }
135
- return readMdxFile(fullPathWithExtension);
136
- };
137
- var getCustomDocs = (directory) => async (options) => {
138
- if (options?.path) {
139
- const pattern = `${directory}/${options.path}/**/*.{md,mdx}`;
140
- return getResources(directory, { type: "docs", pattern });
141
- }
142
- return getResources(directory, { type: "docs", pattern: `${directory}/**/*.{md,mdx}` });
143
- };
144
- var writeCustomDoc = (directory) => async (customDoc, options = { path: "" }) => {
145
- const { fileName, ...rest } = customDoc;
146
- const name = fileName || (0, import_slugify.default)(customDoc.title, { lower: true });
147
- const withExtension = name.endsWith(".mdx") ? name : `${name}.mdx`;
148
- const fullPath = import_node_path4.default.join(directory, options.path || "", withExtension);
149
- import_node_fs3.default.mkdirSync(import_node_path4.default.dirname(fullPath), { recursive: true });
150
- const document = import_gray_matter3.default.stringify(customDoc.markdown.trim(), rest);
151
- import_node_fs3.default.writeFileSync(fullPath, document);
152
- };
153
- var rmCustomDoc = (directory) => async (filePath) => {
154
- const withExtension = filePath.endsWith(".mdx") ? filePath : `${filePath}.mdx`;
155
- await import_promises2.default.rm((0, import_node_path4.join)(directory, withExtension), { recursive: true });
156
- };
157
- // Annotate the CommonJS export names for ESM import in node:
158
- 0 && (module.exports = {
159
- getCustomDoc,
160
- getCustomDocs,
161
- rmCustomDoc,
162
- writeCustomDoc
163
- });
164
- //# sourceMappingURL=custom-docs.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/custom-docs.ts","../src/internal/utils.ts","../src/internal/resources.ts"],"sourcesContent":["import path, { join } from 'node:path';\nimport { readMdxFile } from './internal/utils';\nimport type { CustomDoc } from './types';\nimport fsSync from 'node:fs';\nimport fs from 'node:fs/promises';\nimport matter from 'gray-matter';\nimport { getResources } from './internal/resources';\nimport slugify from 'slugify';\n\n/**\n * Returns a custom doc from EventCatalog by the given file path.\n *\n * @example\n * ```ts\n * import utils from '@eventcatalog/utils';\n *\n * const { getCustomDoc } = utils('/path/to/eventcatalog');\n *\n * // Gets the custom doc by the given file path\n * const customDoc = await getCustomDoc('/guides/inventory-management.mdx');\n * ```\n */\nexport const getCustomDoc =\n (directory: string) =>\n async (filePath: string): Promise<CustomDoc | undefined> => {\n const fullPath = path.join(directory, filePath);\n const fullPathWithExtension = fullPath.endsWith('.mdx') ? fullPath : `${fullPath}.mdx`;\n const fileExists = fsSync.existsSync(fullPathWithExtension);\n if (!fileExists) {\n return undefined;\n }\n return readMdxFile(fullPathWithExtension) as Promise<CustomDoc>;\n };\n\n/**\n * Returns all custom docs for the project.\n *\n * @example\n * ```ts\n * import utils from '@eventcatalog/utils';\n *\n * const { getCustomDocs } = utils('/path/to/eventcatalog');\n *\n * // Gets all custom docs from the catalog\n * const customDocs = await getCustomDocs();\n *\n * // Gets all custom docs from the given path\n * const customDocs = await getCustomDocs({ path: '/guides' });\n * ```\n */\nexport const getCustomDocs =\n (directory: string) =>\n async (options?: { path?: string }): Promise<CustomDoc[]> => {\n if (options?.path) {\n const pattern = `${directory}/${options.path}/**/*.{md,mdx}`;\n return getResources(directory, { type: 'docs', pattern }) as Promise<CustomDoc[]>;\n }\n return getResources(directory, { type: 'docs', pattern: `${directory}/**/*.{md,mdx}` }) as Promise<CustomDoc[]>;\n };\n\n/**\n * Write a custom doc to EventCatalog.\n *\n * You can optionally override the path of the custom doc.\n *\n * @example\n * ```ts\n * import utils from '@eventcatalog/utils';\n *\n * const { writeCustomDoc } = utils('/path/to/eventcatalog');\n *\n * // Write a custom doc to the catalog\n * // Custom doc would be written to docs/inventory-management.mdx\n * await writeCustomDoc({\n * title: 'Inventory Management',\n * summary: 'This is a summary',\n * owners: ['John Doe'],\n * badges: [{ content: 'Badge', backgroundColor: 'red', textColor: 'white' }],\n * markdown: '# Hello world',\n * fileName: 'inventory-management',\n * });\n *\n * // Write a custom doc to the catalog but override the path\n * // Custom doc would be written to docs/guides/inventory-management/introduction.mdx\n * await writeCustomDoc({\n * title: 'Inventory Management',\n * summary: 'This is a summary',\n * owners: ['John Doe'],\n * badges: [{ content: 'Badge', backgroundColor: 'red', textColor: 'white' }],\n * markdown: '# Hello world',\n * fileName: 'introduction',\n * }, { path: \"/guides/inventory-management\"});\n * ```\n */\nexport const writeCustomDoc =\n (directory: string) =>\n async (customDoc: CustomDoc, options: { path?: string } = { path: '' }): Promise<void> => {\n const { fileName, ...rest } = customDoc;\n const name = fileName || slugify(customDoc.title, { lower: true });\n const withExtension = name.endsWith('.mdx') ? name : `${name}.mdx`;\n const fullPath = path.join(directory, options.path || '', withExtension);\n\n fsSync.mkdirSync(path.dirname(fullPath), { recursive: true });\n const document = matter.stringify(customDoc.markdown.trim(), rest);\n fsSync.writeFileSync(fullPath, document);\n };\n\n/**\n * Delete a custom doc by its' path\n *\n * @example\n * ```ts\n * import utils from '@eventcatalog/utils';\n *\n * const { rmCustomDoc } = utils('/path/to/eventcatalog');\n *\n * // removes a custom doc at the given path\n * // Removes the custom doc at docs/guides/inventory-management/introduction.mdx\n * await rmCustomDoc('/guides/inventory-management/introduction');\n * ```\n */\nexport const rmCustomDoc = (directory: string) => async (filePath: string) => {\n const withExtension = filePath.endsWith('.mdx') ? filePath : `${filePath}.mdx`;\n await fs.rm(join(directory, withExtension), { recursive: true });\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 { 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 // Handle both forward and back slashes for cross-platform compatibility (Windows uses \\, Unix uses /)\n const sourceDirectory = dirname(file).replace(/[/\\\\]versioned[/\\\\][^/\\\\]+[/\\\\]/, path.sep);\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 options?: { path?: string }\n) => {\n let pathToResource: string | undefined;\n\n if (options?.path) {\n pathToResource = join(catalogDir, options.path, 'index.mdx');\n } else {\n // Fall back to global lookup (existing behavior)\n pathToResource = await findFileById(catalogDir, id, version);\n }\n\n if (!pathToResource) throw new Error('Cannot find directory to write file to');\n\n // Create the directory if it doesn't exist\n fsSync.mkdirSync(path.dirname(pathToResource), { recursive: true });\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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAAAA,oBAA2B;;;ACA3B,kBAAyB;AACzB,qBAAmB;AACnB,sBAAsD;AACtD,uBAA4F;AAC5F,yBAAmB;AACnB,oBAA6C;AA0DtC,IAAM,WAAW,OAAO,SAAiB,SAA4B,OAAO;AACjF,MAAI;AAEF,UAAM,6BAAyB,4BAAU,OAAO;AAIhD,UAAM,sBAAkB;AAAA,MACtB,uBAAuB,SAAS,IAAI,IAAI,uBAAuB,MAAM,IAAI,EAAE,CAAC,QAAI,0BAAQ,sBAAsB;AAAA,IAChH;AAIA,QAAI,sBAAkB,2BAAS,iBAAiB,sBAAsB;AAStE,sBAAkB,gBAAgB,QAAQ,OAAO,GAAG;AAEpD,UAAM,aAAa,MAAM,QAAQ,MAAM,IAAI,SAAS,CAAC,MAAM;AAE3D,UAAM,YAAQ,sBAAS,iBAAiB;AAAA,MACtC,KAAK;AAAA,MACL,QAAQ,CAAC,mBAAmB,GAAG,UAAU;AAAA,MACzC,UAAU;AAAA,MACV,OAAO;AAAA,IACT,CAAC;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AAO,GAAG,IAAI;AAC5D,QAAM,WAAW,kBAAAF,QAAK,KAAK,WAAW,QAAQ,QAAQ,IAAI,aAAa;AAEvE,kBAAAC,QAAO,UAAU,kBAAAD,QAAK,QAAQ,QAAQ,GAAG,EAAE,WAAW,KAAK,CAAC;AAC5D,QAAM,WAAW,oBAAAG,QAAO,UAAU,UAAU,SAAS,KAAK,GAAG,IAAI;AACjE,kBAAAF,QAAO,cAAc,UAAU,QAAQ;AACzC;AAgBK,IAAM,cAAc,CAAC,cAAsB,OAAO,aAAqB;AAC5E,QAAM,gBAAgB,SAAS,SAAS,MAAM,IAAI,WAAW,GAAG,QAAQ;AACxE,QAAM,iBAAAG,QAAG,OAAG,wBAAK,WAAW,aAAa,GAAG,EAAE,WAAW,KAAK,CAAC;AACjE;","names":["import_node_path","path","matter","import_node_fs","import_promises","import_gray_matter","import_gray_matter","import_node_fs","import_semver","import_node_path","matter","fsSync","path","fsSync","slugify","matter","fs"]}
@@ -1,122 +0,0 @@
1
- // src/custom-docs.ts
2
- import path, { join as join3 } from "node:path";
3
-
4
- // src/internal/utils.ts
5
- import { globSync } from "glob";
6
- import { copy } from "fs-extra";
7
- import { join, dirname, normalize, resolve, relative } from "node:path";
8
- import matter from "gray-matter";
9
- import { satisfies, validRange } from "semver";
10
- var getFiles = async (pattern, ignore = "") => {
11
- try {
12
- const normalizedInputPattern = normalize(pattern);
13
- const absoluteBaseDir = resolve(
14
- normalizedInputPattern.includes("**") ? normalizedInputPattern.split("**")[0] : dirname(normalizedInputPattern)
15
- );
16
- let relativePattern = relative(absoluteBaseDir, normalizedInputPattern);
17
- relativePattern = relativePattern.replace(/\\/g, "/");
18
- const ignoreList = Array.isArray(ignore) ? ignore : [ignore];
19
- const files = globSync(relativePattern, {
20
- cwd: absoluteBaseDir,
21
- ignore: ["node_modules/**", ...ignoreList],
22
- absolute: true,
23
- nodir: true
24
- });
25
- return files.map(normalize);
26
- } catch (error) {
27
- const absoluteBaseDirForError = resolve(
28
- normalize(pattern).includes("**") ? normalize(pattern).split("**")[0] : dirname(normalize(pattern))
29
- );
30
- const relativePatternForError = relative(absoluteBaseDirForError, normalize(pattern)).replace(/\\/g, "/");
31
- throw new Error(
32
- `Error finding files for pattern "${pattern}" (using cwd: "${absoluteBaseDirForError}", globPattern: "${relativePatternForError}"): ${error.message}`
33
- );
34
- }
35
- };
36
- var readMdxFile = async (path2) => {
37
- const { data } = matter.read(path2);
38
- const { markdown, ...frontmatter } = data;
39
- return { ...frontmatter, markdown };
40
- };
41
-
42
- // src/custom-docs.ts
43
- import fsSync2 from "node:fs";
44
- import fs from "node:fs/promises";
45
- import matter3 from "gray-matter";
46
-
47
- // src/internal/resources.ts
48
- import { dirname as dirname2, join as join2 } from "path";
49
- import matter2 from "gray-matter";
50
- import fsSync from "node:fs";
51
- import { satisfies as satisfies2 } from "semver";
52
- import { lock, unlock } from "proper-lockfile";
53
- var getResources = async (catalogDir, {
54
- type,
55
- latestOnly = false,
56
- ignore = [],
57
- pattern = "",
58
- attachSchema = false
59
- }) => {
60
- const ignoreList = latestOnly ? `**/versioned/**` : "";
61
- const filePattern = pattern || `${catalogDir}/**/${type}/**/index.{md,mdx}`;
62
- const files = await getFiles(filePattern, [ignoreList, ...ignore]);
63
- if (files.length === 0) return;
64
- return files.map((file) => {
65
- const { data, content } = matter2.read(file);
66
- if (attachSchema && data?.schemaPath) {
67
- const resourceDirectory = dirname2(file);
68
- const pathToSchema = join2(resourceDirectory, data.schemaPath);
69
- if (fsSync.existsSync(pathToSchema)) {
70
- const schema = fsSync.readFileSync(pathToSchema, "utf8");
71
- try {
72
- data.schema = JSON.parse(schema);
73
- } catch (error) {
74
- data.schema = schema;
75
- }
76
- }
77
- }
78
- return {
79
- ...data,
80
- markdown: content.trim()
81
- };
82
- });
83
- };
84
-
85
- // src/custom-docs.ts
86
- import slugify from "slugify";
87
- var getCustomDoc = (directory) => async (filePath) => {
88
- const fullPath = path.join(directory, filePath);
89
- const fullPathWithExtension = fullPath.endsWith(".mdx") ? fullPath : `${fullPath}.mdx`;
90
- const fileExists = fsSync2.existsSync(fullPathWithExtension);
91
- if (!fileExists) {
92
- return void 0;
93
- }
94
- return readMdxFile(fullPathWithExtension);
95
- };
96
- var getCustomDocs = (directory) => async (options) => {
97
- if (options?.path) {
98
- const pattern = `${directory}/${options.path}/**/*.{md,mdx}`;
99
- return getResources(directory, { type: "docs", pattern });
100
- }
101
- return getResources(directory, { type: "docs", pattern: `${directory}/**/*.{md,mdx}` });
102
- };
103
- var writeCustomDoc = (directory) => async (customDoc, options = { path: "" }) => {
104
- const { fileName, ...rest } = customDoc;
105
- const name = fileName || slugify(customDoc.title, { lower: true });
106
- const withExtension = name.endsWith(".mdx") ? name : `${name}.mdx`;
107
- const fullPath = path.join(directory, options.path || "", withExtension);
108
- fsSync2.mkdirSync(path.dirname(fullPath), { recursive: true });
109
- const document = matter3.stringify(customDoc.markdown.trim(), rest);
110
- fsSync2.writeFileSync(fullPath, document);
111
- };
112
- var rmCustomDoc = (directory) => async (filePath) => {
113
- const withExtension = filePath.endsWith(".mdx") ? filePath : `${filePath}.mdx`;
114
- await fs.rm(join3(directory, withExtension), { recursive: true });
115
- };
116
- export {
117
- getCustomDoc,
118
- getCustomDocs,
119
- rmCustomDoc,
120
- writeCustomDoc
121
- };
122
- //# sourceMappingURL=custom-docs.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/custom-docs.ts","../src/internal/utils.ts","../src/internal/resources.ts"],"sourcesContent":["import path, { join } from 'node:path';\nimport { readMdxFile } from './internal/utils';\nimport type { CustomDoc } from './types';\nimport fsSync from 'node:fs';\nimport fs from 'node:fs/promises';\nimport matter from 'gray-matter';\nimport { getResources } from './internal/resources';\nimport slugify from 'slugify';\n\n/**\n * Returns a custom doc from EventCatalog by the given file path.\n *\n * @example\n * ```ts\n * import utils from '@eventcatalog/utils';\n *\n * const { getCustomDoc } = utils('/path/to/eventcatalog');\n *\n * // Gets the custom doc by the given file path\n * const customDoc = await getCustomDoc('/guides/inventory-management.mdx');\n * ```\n */\nexport const getCustomDoc =\n (directory: string) =>\n async (filePath: string): Promise<CustomDoc | undefined> => {\n const fullPath = path.join(directory, filePath);\n const fullPathWithExtension = fullPath.endsWith('.mdx') ? fullPath : `${fullPath}.mdx`;\n const fileExists = fsSync.existsSync(fullPathWithExtension);\n if (!fileExists) {\n return undefined;\n }\n return readMdxFile(fullPathWithExtension) as Promise<CustomDoc>;\n };\n\n/**\n * Returns all custom docs for the project.\n *\n * @example\n * ```ts\n * import utils from '@eventcatalog/utils';\n *\n * const { getCustomDocs } = utils('/path/to/eventcatalog');\n *\n * // Gets all custom docs from the catalog\n * const customDocs = await getCustomDocs();\n *\n * // Gets all custom docs from the given path\n * const customDocs = await getCustomDocs({ path: '/guides' });\n * ```\n */\nexport const getCustomDocs =\n (directory: string) =>\n async (options?: { path?: string }): Promise<CustomDoc[]> => {\n if (options?.path) {\n const pattern = `${directory}/${options.path}/**/*.{md,mdx}`;\n return getResources(directory, { type: 'docs', pattern }) as Promise<CustomDoc[]>;\n }\n return getResources(directory, { type: 'docs', pattern: `${directory}/**/*.{md,mdx}` }) as Promise<CustomDoc[]>;\n };\n\n/**\n * Write a custom doc to EventCatalog.\n *\n * You can optionally override the path of the custom doc.\n *\n * @example\n * ```ts\n * import utils from '@eventcatalog/utils';\n *\n * const { writeCustomDoc } = utils('/path/to/eventcatalog');\n *\n * // Write a custom doc to the catalog\n * // Custom doc would be written to docs/inventory-management.mdx\n * await writeCustomDoc({\n * title: 'Inventory Management',\n * summary: 'This is a summary',\n * owners: ['John Doe'],\n * badges: [{ content: 'Badge', backgroundColor: 'red', textColor: 'white' }],\n * markdown: '# Hello world',\n * fileName: 'inventory-management',\n * });\n *\n * // Write a custom doc to the catalog but override the path\n * // Custom doc would be written to docs/guides/inventory-management/introduction.mdx\n * await writeCustomDoc({\n * title: 'Inventory Management',\n * summary: 'This is a summary',\n * owners: ['John Doe'],\n * badges: [{ content: 'Badge', backgroundColor: 'red', textColor: 'white' }],\n * markdown: '# Hello world',\n * fileName: 'introduction',\n * }, { path: \"/guides/inventory-management\"});\n * ```\n */\nexport const writeCustomDoc =\n (directory: string) =>\n async (customDoc: CustomDoc, options: { path?: string } = { path: '' }): Promise<void> => {\n const { fileName, ...rest } = customDoc;\n const name = fileName || slugify(customDoc.title, { lower: true });\n const withExtension = name.endsWith('.mdx') ? name : `${name}.mdx`;\n const fullPath = path.join(directory, options.path || '', withExtension);\n\n fsSync.mkdirSync(path.dirname(fullPath), { recursive: true });\n const document = matter.stringify(customDoc.markdown.trim(), rest);\n fsSync.writeFileSync(fullPath, document);\n };\n\n/**\n * Delete a custom doc by its' path\n *\n * @example\n * ```ts\n * import utils from '@eventcatalog/utils';\n *\n * const { rmCustomDoc } = utils('/path/to/eventcatalog');\n *\n * // removes a custom doc at the given path\n * // Removes the custom doc at docs/guides/inventory-management/introduction.mdx\n * await rmCustomDoc('/guides/inventory-management/introduction');\n * ```\n */\nexport const rmCustomDoc = (directory: string) => async (filePath: string) => {\n const withExtension = filePath.endsWith('.mdx') ? filePath : `${filePath}.mdx`;\n await fs.rm(join(directory, withExtension), { recursive: true });\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 { 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 // Handle both forward and back slashes for cross-platform compatibility (Windows uses \\, Unix uses /)\n const sourceDirectory = dirname(file).replace(/[/\\\\]versioned[/\\\\][^/\\\\]+[/\\\\]/, path.sep);\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 options?: { path?: string }\n) => {\n let pathToResource: string | undefined;\n\n if (options?.path) {\n pathToResource = join(catalogDir, options.path, 'index.mdx');\n } else {\n // Fall back to global lookup (existing behavior)\n pathToResource = await findFileById(catalogDir, id, version);\n }\n\n if (!pathToResource) throw new Error('Cannot find directory to write file to');\n\n // Create the directory if it doesn't exist\n fsSync.mkdirSync(path.dirname(pathToResource), { recursive: true });\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"],"mappings":";AAAA,OAAO,QAAQ,QAAAA,aAAY;;;ACA3B,SAAS,gBAAgB;AAEzB,SAAS,YAA6C;AACtD,SAAS,MAAM,SAAS,WAAiC,SAAmB,gBAAgB;AAC5F,OAAO,YAAY;AACnB,SAAS,WAAW,kBAAyB;AA0DtC,IAAM,WAAW,OAAO,SAAiB,SAA4B,OAAO;AACjF,MAAI;AAEF,UAAM,yBAAyB,UAAU,OAAO;AAIhD,UAAM,kBAAkB;AAAA,MACtB,uBAAuB,SAAS,IAAI,IAAI,uBAAuB,MAAM,IAAI,EAAE,CAAC,IAAI,QAAQ,sBAAsB;AAAA,IAChH;AAIA,QAAI,kBAAkB,SAAS,iBAAiB,sBAAsB;AAStE,sBAAkB,gBAAgB,QAAQ,OAAO,GAAG;AAEpD,UAAM,aAAa,MAAM,QAAQ,MAAM,IAAI,SAAS,CAAC,MAAM;AAE3D,UAAM,QAAQ,SAAS,iBAAiB;AAAA,MACtC,KAAK;AAAA,MACL,QAAQ,CAAC,mBAAmB,GAAG,UAAU;AAAA,MACzC,UAAU;AAAA,MACV,OAAO;AAAA,IACT,CAAC;AAGD,WAAO,MAAM,IAAI,SAAS;AAAA,EAC5B,SAAS,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,WAAW,KAAK,CAAC;AAC5D,QAAM,WAAWC,QAAO,UAAU,UAAU,SAAS,KAAK,GAAG,IAAI;AACjE,EAAAD,QAAO,cAAc,UAAU,QAAQ;AACzC;AAgBK,IAAM,cAAc,CAAC,cAAsB,OAAO,aAAqB;AAC5E,QAAM,gBAAgB,SAAS,SAAS,MAAM,IAAI,WAAW,GAAG,QAAQ;AACxE,QAAM,GAAG,GAAGE,MAAK,WAAW,aAAa,GAAG,EAAE,WAAW,KAAK,CAAC;AACjE;","names":["join","path","fsSync","matter","dirname","join","matter","satisfies","matter","dirname","join","fsSync","matter","join"]}
@@ -1,179 +0,0 @@
1
- import { Container } from './types.d.mjs';
2
-
3
- /**
4
- * Returns a data store (e.g. database, cache, etc.) from EventCatalog.
5
- *
6
- * You can optionally specify a version to get a specific version of the data store
7
- *
8
- * @example
9
- * ```ts
10
- * import utils from '@eventcatalog/utils';
11
- *
12
- * const { getContainer } = utils('/path/to/eventcatalog');
13
- *
14
- * // Gets the latest version of the data store
15
- * const container = await getDataStore('orders-db');
16
- *
17
- * // Gets a version of the entity
18
- * const container = await getDataStore('orders-db', '0.0.1');
19
- *
20
- * ```
21
- */
22
- declare const getDataStore: (directory: string) => (id: string, version?: string) => Promise<Container>;
23
- /**
24
- * Returns all data stores (e.g. databases, caches, etc.) from EventCatalog.
25
- *
26
- * You can optionally specify if you want to get the latest version of the data stores.
27
- *
28
- * @example
29
- * ```ts
30
- * import utils from '@eventcatalog/utils';
31
- *
32
- * const { getDataStores } = utils('/path/to/eventcatalog');
33
- *
34
- * // Gets all data stores (and versions) from the catalog
35
- * const containers = await getDataStores();
36
- *
37
- * // Gets all data stores (only latest version) from the catalog
38
- * const containers = await getDataStores({ latestOnly: true });
39
- *
40
- * ```
41
- */
42
- declare const getDataStores: (directory: string) => (options?: {
43
- latestOnly?: boolean;
44
- }) => Promise<Container[]>;
45
- /**
46
- * Write a data store (e.g. database, cache, etc.) to EventCatalog.
47
- */
48
- declare const writeDataStore: (directory: string) => (data: Container, options?: {
49
- path?: string;
50
- override?: boolean;
51
- versionExistingContent?: boolean;
52
- format?: "md" | "mdx";
53
- }) => Promise<void>;
54
- /**
55
- * Version an data store (e.g. database, cache, etc.) by its id.
56
- *
57
- * Takes the latest data store and moves it to a versioned directory.
58
- * All files with this data store are also versioned (e.g /containers/orders-db/schema.json)
59
- *
60
- * @example
61
- * ```ts
62
- * import utils from '@eventcatalog/utils';
63
- *
64
- * const { versionDataStore } = utils('/path/to/eventcatalog');
65
- *
66
- * // moves the latest orders-db data store to a versioned directory
67
- * // the version within that data store is used as the version number.
68
- * await versionDataStore('orders-db');
69
- *
70
- * ```
71
- */
72
- declare const versionDataStore: (directory: string) => (id: string) => Promise<void>;
73
- /**
74
- * Delete an data store (e.g. database, cache, etc.) at its given path.
75
- *
76
- * @example
77
- * ```ts
78
- * import utils from '@eventcatalog/utils';
79
- *
80
- * const { rmDataStore } = utils('/path/to/eventcatalog');
81
- *
82
- * // removes an data store at the given path (containers dir is appended to the given path)
83
- * // Removes the data store at containers/orders-db
84
- * await rmDataStore('/orders-db');
85
- * ```
86
- */
87
- declare const rmDataStore: (directory: string) => (path: string) => Promise<void>;
88
- /**
89
- * Delete an data store (e.g. database, cache, etc.) by its id.
90
- *
91
- * Optionally specify a version to delete a specific version of the data store.
92
- *
93
- * @example
94
- * ```ts
95
- * import utils from '@eventcatalog/utils';
96
- *
97
- * const { rmDataStoreById } = utils('/path/to/eventcatalog');
98
- *
99
- * // deletes the latest orders-db data store
100
- * await rmDataStoreById('orders-db');
101
- *
102
- * // deletes a specific version of the orders-db data store
103
- * await rmDataStoreById('orders-db', '0.0.1');
104
- * ```
105
- */
106
- declare const rmDataStoreById: (directory: string) => (id: string, version?: string, persistFiles?: boolean) => Promise<void>;
107
- /**
108
- * Check to see if the catalog has a version for the given data store (e.g. database, cache, etc.).
109
- *
110
- * @example
111
- * ```ts
112
- * import utils from '@eventcatalog/utils';
113
- *
114
- * const { dataStoreHasVersion } = utils('/path/to/eventcatalog');
115
- *
116
- * // returns true if version is found for the given data store and version (supports semver)
117
- * await dataStoreHasVersion('orders-db', '0.0.1');
118
- * await dataStoreHasVersion('orders-db', 'latest');
119
- * await dataStoreHasVersion('orders-db', '0.0.x');
120
- *
121
- * ```
122
- */
123
- declare const dataStoreHasVersion: (directory: string) => (id: string, version?: string) => Promise<boolean>;
124
- /**
125
- * Add a file to a data store (e.g. database, cache, etc.) by it's id.
126
- *
127
- * Optionally specify a version to add a file to a specific version of the data store.
128
- *
129
- * @example
130
- * ```ts
131
- * import utils from '@eventcatalog/utils';
132
- *
133
- * const { addFileToDataStore } = utils('/path/to/eventcatalog');
134
- *
135
- * // adds a file to the latest InventoryAdjusted data store
136
- * await addFileToDataStore('InventoryAdjusted', { content: 'Hello world', fileName: 'hello.txt' });
137
- *
138
- * // adds a file to a specific version of the InventoryAdjusted data store
139
- * await addFileToDataStore('InventoryAdjusted', { content: 'Hello world', fileName: 'hello.txt' }, '0.0.1');
140
- *
141
- * ```
142
- */
143
- declare const addFileToDataStore: (directory: string) => (id: string, file: {
144
- content: string;
145
- fileName: string;
146
- }, version?: string) => Promise<void>;
147
- /**
148
- * Write an data store (e.g. database, cache, etc.) to a service in EventCatalog.
149
- *
150
- * You can optionally override the path of the data store.
151
- *
152
- * @example
153
- * ```ts
154
- * import utils from '@eventcatalog/utils';
155
- *
156
- * const { writeDataStoreToService } = utils('/path/to/eventcatalog');
157
- *
158
- * // Write a data store to a given service in the catalog
159
- * // Data store would be written to services/Inventory/containers/orders-db
160
- * await writeDataStoreToService({
161
- * id: 'orders-db',
162
- * name: 'Orders DB',
163
- * version: '0.0.1',
164
- * summary: 'This is a summary',
165
- * markdown: '# Hello world',
166
- * container_type: 'database',
167
- * }, { id: 'Inventory' });
168
- * ```
169
- */
170
- declare const writeDataStoreToService: (directory: string) => (container: Container, service: {
171
- id: string;
172
- version?: string;
173
- }, options?: {
174
- path?: string;
175
- format?: "md" | "mdx";
176
- override?: boolean;
177
- }) => Promise<void>;
178
-
179
- export { addFileToDataStore, dataStoreHasVersion, getDataStore, getDataStores, rmDataStore, rmDataStoreById, versionDataStore, writeDataStore, writeDataStoreToService };