@eventcatalog/sdk 0.0.1 → 0.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -21,4 +21,3 @@ await getEvent('InventoryEvent');
21
21
  // Gets event by id and version
22
22
  await getEvent('InventoryEvent', '1.0.0');
23
23
  ```
24
-
@@ -0,0 +1,2 @@
1
+ export { addFileToEvent, addSchemaToEvent, getEvent, rmEvent, rmEventById, versionEvent, writeEvent } from './events.mjs';
2
+ import './types.d.mjs';
package/dist/docs.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ export { addFileToEvent, addSchemaToEvent, getEvent, rmEvent, rmEventById, versionEvent, writeEvent } from './events.js';
2
+ import './types.d.js';
package/dist/docs.js ADDED
@@ -0,0 +1,181 @@
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/docs.ts
31
+ var docs_exports = {};
32
+ __export(docs_exports, {
33
+ addFileToEvent: () => addFileToEvent,
34
+ addSchemaToEvent: () => addSchemaToEvent,
35
+ getEvent: () => getEvent,
36
+ rmEvent: () => rmEvent,
37
+ rmEventById: () => rmEventById,
38
+ versionEvent: () => versionEvent,
39
+ writeEvent: () => writeEvent
40
+ });
41
+ module.exports = __toCommonJS(docs_exports);
42
+
43
+ // src/events.ts
44
+ var import_gray_matter = __toESM(require("gray-matter"));
45
+ var import_promises2 = __toESM(require("fs/promises"));
46
+ var import_node_path2 = require("path");
47
+ var import_node_path3 = require("path");
48
+
49
+ // src/internal/utils.ts
50
+ var import_glob = require("glob");
51
+ var import_promises = __toESM(require("fs/promises"));
52
+ var import_fs_extra = require("fs-extra");
53
+ var import_node_path = require("path");
54
+ var versionExists = async (catalogDir, id, version) => {
55
+ const files = await getFiles(`${catalogDir}/**/index.md`);
56
+ const matchedFiles = await searchFilesForId(files, id, version) || [];
57
+ return matchedFiles.length > 0;
58
+ };
59
+ var findFileById = async (catalogDir, id, version) => {
60
+ const files = await getFiles(`${catalogDir}/**/index.md`);
61
+ const matchedFiles = await searchFilesForId(files, id) || [];
62
+ if (!version) {
63
+ return matchedFiles.find((path) => !path.includes("versioned"));
64
+ }
65
+ return matchedFiles.find((path) => path.includes(`versioned/${version}`));
66
+ };
67
+ var getFiles = async (pattern) => {
68
+ try {
69
+ const files = await (0, import_glob.glob)(pattern, { ignore: "node_modules/**" });
70
+ return files;
71
+ } catch (error) {
72
+ throw new Error(`Error finding files: ${error}`);
73
+ }
74
+ };
75
+ var searchFilesForId = async (files, id, version) => {
76
+ const idRegex = new RegExp(`^id:\\s*['"]?${id}['"]?\\s*$`, "m");
77
+ const versionRegex = new RegExp(`^version:\\s*['"]?${version}['"]?\\s*$`, "m");
78
+ const matches = await Promise.all(
79
+ files.map(async (file) => {
80
+ const content = await import_promises.default.readFile(file, "utf-8");
81
+ const hasIdMatch = content.match(idRegex);
82
+ if (version && !content.match(versionRegex)) {
83
+ return void 0;
84
+ }
85
+ if (hasIdMatch) {
86
+ return file;
87
+ }
88
+ })
89
+ );
90
+ return matches.filter(Boolean).filter((file) => file !== void 0);
91
+ };
92
+ var copyDir = async (catalogDir, source, target, filter) => {
93
+ const tmpDirectory = (0, import_node_path.join)(catalogDir, "tmp");
94
+ await import_promises.default.mkdir(tmpDirectory, { recursive: true });
95
+ await (0, import_fs_extra.copy)(source, tmpDirectory, {
96
+ overwrite: true,
97
+ filter
98
+ });
99
+ await (0, import_fs_extra.copy)(tmpDirectory, target, {
100
+ overwrite: true,
101
+ filter
102
+ });
103
+ await import_promises.default.rm(tmpDirectory, { recursive: true });
104
+ };
105
+
106
+ // src/events.ts
107
+ var getEvent = (directory) => async (id, version) => {
108
+ const file = await findFileById(directory, id, version);
109
+ if (!file) throw new Error(`No event found for the given id: ${id}` + (version ? ` and version ${version}` : ""));
110
+ const { data, content } = import_gray_matter.default.read(file);
111
+ return {
112
+ ...data,
113
+ markdown: content.trim()
114
+ };
115
+ };
116
+ var writeEvent = (directory) => async (event, options = { path: "" }) => {
117
+ const path = options.path || `/${event.id}`;
118
+ const exists = await versionExists(directory, event.id, event.version);
119
+ if (exists) {
120
+ throw new Error(`Failed to write event as the version ${event.version} already exists`);
121
+ }
122
+ const { markdown, ...frontmatter } = event;
123
+ const document = import_gray_matter.default.stringify(markdown.trim(), frontmatter);
124
+ await import_promises2.default.mkdir((0, import_node_path2.join)(directory, path), { recursive: true });
125
+ await import_promises2.default.writeFile((0, import_node_path2.join)(directory, path, "index.md"), document);
126
+ };
127
+ var rmEvent = (directory) => async (path) => {
128
+ await import_promises2.default.rm((0, import_node_path2.join)(directory, path), { recursive: true });
129
+ };
130
+ var rmEventById = (directory) => async (id, version) => {
131
+ const files = await getFiles(`${directory}/**/index.md`);
132
+ const matchedFiles = await searchFilesForId(files, id, version);
133
+ if (matchedFiles.length === 0) {
134
+ throw new Error(`No event found with id: ${id}`);
135
+ }
136
+ await Promise.all(matchedFiles.map((file) => import_promises2.default.rm(file)));
137
+ };
138
+ var versionEvent = (directory) => async (id) => {
139
+ const files = await getFiles(`${directory}/**/index.md`);
140
+ const matchedFiles = await searchFilesForId(files, id);
141
+ if (matchedFiles.length === 0) {
142
+ throw new Error(`No event found with id: ${id}`);
143
+ }
144
+ const file = matchedFiles[0];
145
+ const eventDirectory = (0, import_node_path3.dirname)(file);
146
+ const { data: { version = "0.0.1" } = {} } = import_gray_matter.default.read(file);
147
+ const targetDirectory = (0, import_node_path2.join)(eventDirectory, "versioned", version);
148
+ await import_promises2.default.mkdir(targetDirectory, { recursive: true });
149
+ await copyDir(directory, eventDirectory, targetDirectory, (src) => {
150
+ return !src.includes("versioned");
151
+ });
152
+ await import_promises2.default.readdir(eventDirectory).then(async (resourceFiles) => {
153
+ await Promise.all(
154
+ resourceFiles.map(async (file2) => {
155
+ if (file2 !== "versioned") {
156
+ await import_promises2.default.rm((0, import_node_path2.join)(eventDirectory, file2), { recursive: true });
157
+ }
158
+ })
159
+ );
160
+ });
161
+ };
162
+ var addFileToEvent = (directory) => async (id, file, version) => {
163
+ const pathToEvent = await findFileById(directory, id, version);
164
+ if (!pathToEvent) throw new Error("Cannot find directory to write file to");
165
+ const contentDirectory = (0, import_node_path3.dirname)(pathToEvent);
166
+ await import_promises2.default.writeFile((0, import_node_path2.join)(contentDirectory, file.fileName), file.content);
167
+ };
168
+ var addSchemaToEvent = (directory) => async (id, schema, version) => {
169
+ await addFileToEvent(directory)(id, { content: schema.schema, fileName: schema.fileName }, version);
170
+ };
171
+ // Annotate the CommonJS export names for ESM import in node:
172
+ 0 && (module.exports = {
173
+ addFileToEvent,
174
+ addSchemaToEvent,
175
+ getEvent,
176
+ rmEvent,
177
+ rmEventById,
178
+ versionEvent,
179
+ writeEvent
180
+ });
181
+ //# sourceMappingURL=docs.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/docs.ts","../src/events.ts","../src/internal/utils.ts"],"sourcesContent":["/**\n * Used for docs not bundled\n */\nexport * from './events';\n","import matter from 'gray-matter';\nimport fs from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { dirname } from 'node:path';\nimport { copyDir, findFileById, getFiles, searchFilesForId, versionExists } from './internal/utils';\nimport type { Event } from './types';\n\n/**\n * Returns an event from EventCatalog.\n *\n * You can optionally specify a version to get a specific version of the event.\n *\n * @example\n * ```ts\n * import utils from '@eventcatalog/utils`;\n *\n * const { getEvent } = utils('/path/to/eventcatalog');\n *\n * // Gets the latest version of the event\n * cont event = await getEvent('InventoryAdjusted');\n *\n * // Gets a version of the event\n * cont event = await getEvent('InventoryAdjusted', '0.0.1');\n * ```\n */\nexport const getEvent =\n (directory: string) =>\n async (id: string, version?: string): Promise<Event> => {\n const file = await findFileById(directory, id, version);\n\n if (!file) throw new Error(`No event found for the given id: ${id}` + (version ? ` and version ${version}` : ''));\n\n const { data, content } = matter.read(file);\n\n return {\n ...data,\n markdown: content.trim(),\n } as Event;\n };\n\nexport const writeEvent =\n (directory: string) =>\n async (event: Event, options: { path: string } = { path: '' }) => {\n // Get the path\n const path = options.path || `/${event.id}`;\n const exists = await versionExists(directory, event.id, event.version);\n\n if (exists) {\n throw new Error(`Failed to write event as the version ${event.version} already exists`);\n }\n\n const { markdown, ...frontmatter } = event;\n const document = matter.stringify(markdown.trim(), frontmatter);\n await fs.mkdir(join(directory, path), { recursive: true });\n await fs.writeFile(join(directory, path, 'index.md'), document);\n };\n\nexport const rmEvent = (directory: string) => async (path: string) => {\n await fs.rm(join(directory, path), { recursive: true });\n};\n\nexport const rmEventById = (directory: string) => async (id: string, version?: string) => {\n // Find all the events in the directory\n const files = await getFiles(`${directory}/**/index.md`);\n\n const matchedFiles = await searchFilesForId(files, id, version);\n\n if (matchedFiles.length === 0) {\n throw new Error(`No event found with id: ${id}`);\n }\n\n await Promise.all(matchedFiles.map((file) => fs.rm(file)));\n};\n\nexport const versionEvent = (directory: string) => async (id: string) => {\n // Find all the events in the directory\n const files = await getFiles(`${directory}/**/index.md`);\n const matchedFiles = await searchFilesForId(files, id);\n\n if (matchedFiles.length === 0) {\n throw new Error(`No event found with id: ${id}`);\n }\n\n // Event that is in the route of the project\n const file = matchedFiles[0];\n const eventDirectory = dirname(file);\n const { data: { version = '0.0.1' } = {} } = matter.read(file);\n const targetDirectory = join(eventDirectory, 'versioned', version);\n\n await fs.mkdir(targetDirectory, { recursive: true });\n\n // Copy the event to the versioned directory\n await copyDir(directory, eventDirectory, targetDirectory, (src) => {\n return !src.includes('versioned');\n });\n\n // Remove all the files in the root of the resource as they have now been versioned\n await fs.readdir(eventDirectory).then(async (resourceFiles) => {\n await Promise.all(\n resourceFiles.map(async (file) => {\n if (file !== 'versioned') {\n await fs.rm(join(eventDirectory, file), { recursive: true });\n }\n })\n );\n });\n};\n\nexport const addFileToEvent =\n (directory: string) => async (id: string, file: { content: string; fileName: string }, version?: string) => {\n const pathToEvent = await findFileById(directory, id, version);\n if (!pathToEvent) throw new Error('Cannot find directory to write file to');\n const contentDirectory = dirname(pathToEvent);\n await fs.writeFile(join(contentDirectory, file.fileName), file.content);\n };\n\nexport const addSchemaToEvent =\n (directory: string) => async (id: string, schema: { schema: string; fileName: string }, version?: string) => {\n await addFileToEvent(directory)(id, { content: schema.schema, fileName: schema.fileName }, version);\n };\n","import { glob } from 'glob';\nimport fs from 'node:fs/promises';\nimport { copy, CopyFilterAsync, CopyFilterSync } from 'fs-extra';\nimport { join } from 'node:path';\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`);\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`);\n const matchedFiles = (await searchFilesForId(files, id)) || [];\n\n // Return the latest one\n if (!version) {\n return matchedFiles.find((path) => !path.includes('versioned'));\n }\n\n // Find the versioned event\n return matchedFiles.find((path) => path.includes(`versioned/${version}`));\n};\n\nexport const getFiles = async (pattern: string) => {\n try {\n const files = await glob(pattern, { ignore: 'node_modules/**' });\n return files;\n } catch (error) {\n throw new Error(`Error finding files: ${error}`);\n }\n};\n\nexport const searchFilesForId = async (files: string[], id: string, version?: string) => {\n const idRegex = new RegExp(`^id:\\\\s*['\"]?${id}['\"]?\\\\s*$`, 'm');\n const versionRegex = new RegExp(`^version:\\\\s*['\"]?${version}['\"]?\\\\s*$`, 'm');\n\n const matches = await Promise.all(\n files.map(async (file) => {\n const content = await fs.readFile(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\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 await fs.mkdir(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 await fs.rm(tmpDirectory, { recursive: true });\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,yBAAmB;AACnB,IAAAA,mBAAe;AACf,IAAAC,oBAAqB;AACrB,IAAAA,oBAAwB;;;ACHxB,kBAAqB;AACrB,sBAAe;AACf,sBAAsD;AACtD,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;AAAA,MACZ,cAAc,IAAI,OAAOC,UAAS;AAChC,YAAIA,UAAS,aAAa;AACxB,gBAAM,iBAAAD,QAAG,OAAG,wBAAK,gBAAgBC,KAAI,GAAG,EAAE,WAAW,KAAK,CAAC;AAAA,QAC7D;AAAA,MACF,CAAC;AAAA,IACH;AAAA,EACF,CAAC;AACH;AAEO,IAAM,iBACX,CAAC,cAAsB,OAAO,IAAY,MAA6C,YAAqB;AAC1G,QAAM,cAAc,MAAM,aAAa,WAAW,IAAI,OAAO;AAC7D,MAAI,CAAC,YAAa,OAAM,IAAI,MAAM,wCAAwC;AAC1E,QAAM,uBAAmB,2BAAQ,WAAW;AAC5C,QAAM,iBAAAD,QAAG,cAAU,wBAAK,kBAAkB,KAAK,QAAQ,GAAG,KAAK,OAAO;AACxE;AAEK,IAAM,mBACX,CAAC,cAAsB,OAAO,IAAY,QAA8C,YAAqB;AAC3G,QAAM,eAAe,SAAS,EAAE,IAAI,EAAE,SAAS,OAAO,QAAQ,UAAU,OAAO,SAAS,GAAG,OAAO;AACpG;","names":["import_promises","import_node_path","fs","matter","fs","file"]}
package/dist/docs.mjs ADDED
@@ -0,0 +1,138 @@
1
+ // src/events.ts
2
+ import matter from "gray-matter";
3
+ import fs2 from "fs/promises";
4
+ import { join as join2 } from "path";
5
+ import { dirname } from "path";
6
+
7
+ // src/internal/utils.ts
8
+ import { glob } from "glob";
9
+ import fs from "fs/promises";
10
+ import { copy } from "fs-extra";
11
+ import { join } from "path";
12
+ var versionExists = async (catalogDir, id, version) => {
13
+ const files = await getFiles(`${catalogDir}/**/index.md`);
14
+ const matchedFiles = await searchFilesForId(files, id, version) || [];
15
+ return matchedFiles.length > 0;
16
+ };
17
+ var findFileById = async (catalogDir, id, version) => {
18
+ const files = await getFiles(`${catalogDir}/**/index.md`);
19
+ const matchedFiles = await searchFilesForId(files, id) || [];
20
+ if (!version) {
21
+ return matchedFiles.find((path) => !path.includes("versioned"));
22
+ }
23
+ return matchedFiles.find((path) => path.includes(`versioned/${version}`));
24
+ };
25
+ var getFiles = async (pattern) => {
26
+ try {
27
+ const files = await glob(pattern, { ignore: "node_modules/**" });
28
+ return files;
29
+ } catch (error) {
30
+ throw new Error(`Error finding files: ${error}`);
31
+ }
32
+ };
33
+ var searchFilesForId = async (files, id, version) => {
34
+ const idRegex = new RegExp(`^id:\\s*['"]?${id}['"]?\\s*$`, "m");
35
+ const versionRegex = new RegExp(`^version:\\s*['"]?${version}['"]?\\s*$`, "m");
36
+ const matches = await Promise.all(
37
+ files.map(async (file) => {
38
+ const content = await fs.readFile(file, "utf-8");
39
+ const hasIdMatch = content.match(idRegex);
40
+ if (version && !content.match(versionRegex)) {
41
+ return void 0;
42
+ }
43
+ if (hasIdMatch) {
44
+ return file;
45
+ }
46
+ })
47
+ );
48
+ return matches.filter(Boolean).filter((file) => file !== void 0);
49
+ };
50
+ var copyDir = async (catalogDir, source, target, filter) => {
51
+ const tmpDirectory = join(catalogDir, "tmp");
52
+ await fs.mkdir(tmpDirectory, { recursive: true });
53
+ await copy(source, tmpDirectory, {
54
+ overwrite: true,
55
+ filter
56
+ });
57
+ await copy(tmpDirectory, target, {
58
+ overwrite: true,
59
+ filter
60
+ });
61
+ await fs.rm(tmpDirectory, { recursive: true });
62
+ };
63
+
64
+ // src/events.ts
65
+ var getEvent = (directory) => async (id, version) => {
66
+ const file = await findFileById(directory, id, version);
67
+ if (!file) throw new Error(`No event found for the given id: ${id}` + (version ? ` and version ${version}` : ""));
68
+ const { data, content } = matter.read(file);
69
+ return {
70
+ ...data,
71
+ markdown: content.trim()
72
+ };
73
+ };
74
+ var writeEvent = (directory) => async (event, options = { path: "" }) => {
75
+ const path = options.path || `/${event.id}`;
76
+ const exists = await versionExists(directory, event.id, event.version);
77
+ if (exists) {
78
+ throw new Error(`Failed to write event as the version ${event.version} already exists`);
79
+ }
80
+ const { markdown, ...frontmatter } = event;
81
+ const document = matter.stringify(markdown.trim(), frontmatter);
82
+ await fs2.mkdir(join2(directory, path), { recursive: true });
83
+ await fs2.writeFile(join2(directory, path, "index.md"), document);
84
+ };
85
+ var rmEvent = (directory) => async (path) => {
86
+ await fs2.rm(join2(directory, path), { recursive: true });
87
+ };
88
+ var rmEventById = (directory) => async (id, version) => {
89
+ const files = await getFiles(`${directory}/**/index.md`);
90
+ const matchedFiles = await searchFilesForId(files, id, version);
91
+ if (matchedFiles.length === 0) {
92
+ throw new Error(`No event found with id: ${id}`);
93
+ }
94
+ await Promise.all(matchedFiles.map((file) => fs2.rm(file)));
95
+ };
96
+ var versionEvent = (directory) => async (id) => {
97
+ const files = await getFiles(`${directory}/**/index.md`);
98
+ const matchedFiles = await searchFilesForId(files, id);
99
+ if (matchedFiles.length === 0) {
100
+ throw new Error(`No event found with id: ${id}`);
101
+ }
102
+ const file = matchedFiles[0];
103
+ const eventDirectory = dirname(file);
104
+ const { data: { version = "0.0.1" } = {} } = matter.read(file);
105
+ const targetDirectory = join2(eventDirectory, "versioned", version);
106
+ await fs2.mkdir(targetDirectory, { recursive: true });
107
+ await copyDir(directory, eventDirectory, targetDirectory, (src) => {
108
+ return !src.includes("versioned");
109
+ });
110
+ await fs2.readdir(eventDirectory).then(async (resourceFiles) => {
111
+ await Promise.all(
112
+ resourceFiles.map(async (file2) => {
113
+ if (file2 !== "versioned") {
114
+ await fs2.rm(join2(eventDirectory, file2), { recursive: true });
115
+ }
116
+ })
117
+ );
118
+ });
119
+ };
120
+ var addFileToEvent = (directory) => async (id, file, version) => {
121
+ const pathToEvent = await findFileById(directory, id, version);
122
+ if (!pathToEvent) throw new Error("Cannot find directory to write file to");
123
+ const contentDirectory = dirname(pathToEvent);
124
+ await fs2.writeFile(join2(contentDirectory, file.fileName), file.content);
125
+ };
126
+ var addSchemaToEvent = (directory) => async (id, schema, version) => {
127
+ await addFileToEvent(directory)(id, { content: schema.schema, fileName: schema.fileName }, version);
128
+ };
129
+ export {
130
+ addFileToEvent,
131
+ addSchemaToEvent,
132
+ getEvent,
133
+ rmEvent,
134
+ rmEventById,
135
+ versionEvent,
136
+ writeEvent
137
+ };
138
+ //# sourceMappingURL=docs.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/events.ts","../src/internal/utils.ts"],"sourcesContent":["import matter from 'gray-matter';\nimport fs from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { dirname } from 'node:path';\nimport { copyDir, findFileById, getFiles, searchFilesForId, versionExists } from './internal/utils';\nimport type { Event } from './types';\n\n/**\n * Returns an event from EventCatalog.\n *\n * You can optionally specify a version to get a specific version of the event.\n *\n * @example\n * ```ts\n * import utils from '@eventcatalog/utils`;\n *\n * const { getEvent } = utils('/path/to/eventcatalog');\n *\n * // Gets the latest version of the event\n * cont event = await getEvent('InventoryAdjusted');\n *\n * // Gets a version of the event\n * cont event = await getEvent('InventoryAdjusted', '0.0.1');\n * ```\n */\nexport const getEvent =\n (directory: string) =>\n async (id: string, version?: string): Promise<Event> => {\n const file = await findFileById(directory, id, version);\n\n if (!file) throw new Error(`No event found for the given id: ${id}` + (version ? ` and version ${version}` : ''));\n\n const { data, content } = matter.read(file);\n\n return {\n ...data,\n markdown: content.trim(),\n } as Event;\n };\n\nexport const writeEvent =\n (directory: string) =>\n async (event: Event, options: { path: string } = { path: '' }) => {\n // Get the path\n const path = options.path || `/${event.id}`;\n const exists = await versionExists(directory, event.id, event.version);\n\n if (exists) {\n throw new Error(`Failed to write event as the version ${event.version} already exists`);\n }\n\n const { markdown, ...frontmatter } = event;\n const document = matter.stringify(markdown.trim(), frontmatter);\n await fs.mkdir(join(directory, path), { recursive: true });\n await fs.writeFile(join(directory, path, 'index.md'), document);\n };\n\nexport const rmEvent = (directory: string) => async (path: string) => {\n await fs.rm(join(directory, path), { recursive: true });\n};\n\nexport const rmEventById = (directory: string) => async (id: string, version?: string) => {\n // Find all the events in the directory\n const files = await getFiles(`${directory}/**/index.md`);\n\n const matchedFiles = await searchFilesForId(files, id, version);\n\n if (matchedFiles.length === 0) {\n throw new Error(`No event found with id: ${id}`);\n }\n\n await Promise.all(matchedFiles.map((file) => fs.rm(file)));\n};\n\nexport const versionEvent = (directory: string) => async (id: string) => {\n // Find all the events in the directory\n const files = await getFiles(`${directory}/**/index.md`);\n const matchedFiles = await searchFilesForId(files, id);\n\n if (matchedFiles.length === 0) {\n throw new Error(`No event found with id: ${id}`);\n }\n\n // Event that is in the route of the project\n const file = matchedFiles[0];\n const eventDirectory = dirname(file);\n const { data: { version = '0.0.1' } = {} } = matter.read(file);\n const targetDirectory = join(eventDirectory, 'versioned', version);\n\n await fs.mkdir(targetDirectory, { recursive: true });\n\n // Copy the event to the versioned directory\n await copyDir(directory, eventDirectory, targetDirectory, (src) => {\n return !src.includes('versioned');\n });\n\n // Remove all the files in the root of the resource as they have now been versioned\n await fs.readdir(eventDirectory).then(async (resourceFiles) => {\n await Promise.all(\n resourceFiles.map(async (file) => {\n if (file !== 'versioned') {\n await fs.rm(join(eventDirectory, file), { recursive: true });\n }\n })\n );\n });\n};\n\nexport const addFileToEvent =\n (directory: string) => async (id: string, file: { content: string; fileName: string }, version?: string) => {\n const pathToEvent = await findFileById(directory, id, version);\n if (!pathToEvent) throw new Error('Cannot find directory to write file to');\n const contentDirectory = dirname(pathToEvent);\n await fs.writeFile(join(contentDirectory, file.fileName), file.content);\n };\n\nexport const addSchemaToEvent =\n (directory: string) => async (id: string, schema: { schema: string; fileName: string }, version?: string) => {\n await addFileToEvent(directory)(id, { content: schema.schema, fileName: schema.fileName }, version);\n };\n","import { glob } from 'glob';\nimport fs from 'node:fs/promises';\nimport { copy, CopyFilterAsync, CopyFilterSync } from 'fs-extra';\nimport { join } from 'node:path';\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`);\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`);\n const matchedFiles = (await searchFilesForId(files, id)) || [];\n\n // Return the latest one\n if (!version) {\n return matchedFiles.find((path) => !path.includes('versioned'));\n }\n\n // Find the versioned event\n return matchedFiles.find((path) => path.includes(`versioned/${version}`));\n};\n\nexport const getFiles = async (pattern: string) => {\n try {\n const files = await glob(pattern, { ignore: 'node_modules/**' });\n return files;\n } catch (error) {\n throw new Error(`Error finding files: ${error}`);\n }\n};\n\nexport const searchFilesForId = async (files: string[], id: string, version?: string) => {\n const idRegex = new RegExp(`^id:\\\\s*['\"]?${id}['\"]?\\\\s*$`, 'm');\n const versionRegex = new RegExp(`^version:\\\\s*['\"]?${version}['\"]?\\\\s*$`, 'm');\n\n const matches = await Promise.all(\n files.map(async (file) => {\n const content = await fs.readFile(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\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 await fs.mkdir(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 await fs.rm(tmpDirectory, { recursive: true });\n};\n"],"mappings":";AAAA,OAAO,YAAY;AACnB,OAAOA,SAAQ;AACf,SAAS,QAAAC,aAAY;AACrB,SAAS,eAAe;;;ACHxB,SAAS,YAAY;AACrB,OAAO,QAAQ;AACf,SAAS,YAA6C;AACtD,SAAS,YAAY;AAKd,IAAM,gBAAgB,OAAO,YAAoB,IAAY,YAAoB;AACtF,QAAM,QAAQ,MAAM,SAAS,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A,EACF,CAAC;AACH;AAEO,IAAM,iBACX,CAAC,cAAsB,OAAO,IAAY,MAA6C,YAAqB;AAC1G,QAAM,cAAc,MAAM,aAAa,WAAW,IAAI,OAAO;AAC7D,MAAI,CAAC,YAAa,OAAM,IAAI,MAAM,wCAAwC;AAC1E,QAAM,mBAAmB,QAAQ,WAAW;AAC5C,QAAMF,IAAG,UAAUC,MAAK,kBAAkB,KAAK,QAAQ,GAAG,KAAK,OAAO;AACxE;AAEK,IAAM,mBACX,CAAC,cAAsB,OAAO,IAAY,QAA8C,YAAqB;AAC3G,QAAM,eAAe,SAAS,EAAE,IAAI,EAAE,SAAS,OAAO,QAAQ,UAAU,OAAO,SAAS,GAAG,OAAO;AACpG;","names":["fs","join","fs","join","file"]}
@@ -0,0 +1,37 @@
1
+ import { Event } from './types.d.mjs';
2
+
3
+ /**
4
+ * Returns an event from EventCatalog.
5
+ *
6
+ * You can optionally specify a version to get a specific version of the event.
7
+ *
8
+ * @example
9
+ * ```ts
10
+ * import utils from '@eventcatalog/utils`;
11
+ *
12
+ * const { getEvent } = utils('/path/to/eventcatalog');
13
+ *
14
+ * // Gets the latest version of the event
15
+ * cont event = await getEvent('InventoryAdjusted');
16
+ *
17
+ * // Gets a version of the event
18
+ * cont event = await getEvent('InventoryAdjusted', '0.0.1');
19
+ * ```
20
+ */
21
+ declare const getEvent: (directory: string) => (id: string, version?: string) => Promise<Event>;
22
+ declare const writeEvent: (directory: string) => (event: Event, options?: {
23
+ path: string;
24
+ }) => Promise<void>;
25
+ declare const rmEvent: (directory: string) => (path: string) => Promise<void>;
26
+ declare const rmEventById: (directory: string) => (id: string, version?: string) => Promise<void>;
27
+ declare const versionEvent: (directory: string) => (id: string) => Promise<void>;
28
+ declare const addFileToEvent: (directory: string) => (id: string, file: {
29
+ content: string;
30
+ fileName: string;
31
+ }, version?: string) => Promise<void>;
32
+ declare const addSchemaToEvent: (directory: string) => (id: string, schema: {
33
+ schema: string;
34
+ fileName: string;
35
+ }, version?: string) => Promise<void>;
36
+
37
+ export { addFileToEvent, addSchemaToEvent, getEvent, rmEvent, rmEventById, versionEvent, writeEvent };
@@ -0,0 +1,37 @@
1
+ import { Event } from './types.d.js';
2
+
3
+ /**
4
+ * Returns an event from EventCatalog.
5
+ *
6
+ * You can optionally specify a version to get a specific version of the event.
7
+ *
8
+ * @example
9
+ * ```ts
10
+ * import utils from '@eventcatalog/utils`;
11
+ *
12
+ * const { getEvent } = utils('/path/to/eventcatalog');
13
+ *
14
+ * // Gets the latest version of the event
15
+ * cont event = await getEvent('InventoryAdjusted');
16
+ *
17
+ * // Gets a version of the event
18
+ * cont event = await getEvent('InventoryAdjusted', '0.0.1');
19
+ * ```
20
+ */
21
+ declare const getEvent: (directory: string) => (id: string, version?: string) => Promise<Event>;
22
+ declare const writeEvent: (directory: string) => (event: Event, options?: {
23
+ path: string;
24
+ }) => Promise<void>;
25
+ declare const rmEvent: (directory: string) => (path: string) => Promise<void>;
26
+ declare const rmEventById: (directory: string) => (id: string, version?: string) => Promise<void>;
27
+ declare const versionEvent: (directory: string) => (id: string) => Promise<void>;
28
+ declare const addFileToEvent: (directory: string) => (id: string, file: {
29
+ content: string;
30
+ fileName: string;
31
+ }, version?: string) => Promise<void>;
32
+ declare const addSchemaToEvent: (directory: string) => (id: string, schema: {
33
+ schema: string;
34
+ fileName: string;
35
+ }, version?: string) => Promise<void>;
36
+
37
+ export { addFileToEvent, addSchemaToEvent, getEvent, rmEvent, rmEventById, versionEvent, writeEvent };
package/dist/events.js ADDED
@@ -0,0 +1,179 @@
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/events.ts
31
+ var events_exports = {};
32
+ __export(events_exports, {
33
+ addFileToEvent: () => addFileToEvent,
34
+ addSchemaToEvent: () => addSchemaToEvent,
35
+ getEvent: () => getEvent,
36
+ rmEvent: () => rmEvent,
37
+ rmEventById: () => rmEventById,
38
+ versionEvent: () => versionEvent,
39
+ writeEvent: () => writeEvent
40
+ });
41
+ module.exports = __toCommonJS(events_exports);
42
+ var import_gray_matter = __toESM(require("gray-matter"));
43
+ var import_promises2 = __toESM(require("fs/promises"));
44
+ var import_node_path2 = require("path");
45
+ var import_node_path3 = require("path");
46
+
47
+ // src/internal/utils.ts
48
+ var import_glob = require("glob");
49
+ var import_promises = __toESM(require("fs/promises"));
50
+ var import_fs_extra = require("fs-extra");
51
+ var import_node_path = require("path");
52
+ var versionExists = async (catalogDir, id, version) => {
53
+ const files = await getFiles(`${catalogDir}/**/index.md`);
54
+ const matchedFiles = await searchFilesForId(files, id, version) || [];
55
+ return matchedFiles.length > 0;
56
+ };
57
+ var findFileById = async (catalogDir, id, version) => {
58
+ const files = await getFiles(`${catalogDir}/**/index.md`);
59
+ const matchedFiles = await searchFilesForId(files, id) || [];
60
+ if (!version) {
61
+ return matchedFiles.find((path) => !path.includes("versioned"));
62
+ }
63
+ return matchedFiles.find((path) => path.includes(`versioned/${version}`));
64
+ };
65
+ var getFiles = async (pattern) => {
66
+ try {
67
+ const files = await (0, import_glob.glob)(pattern, { ignore: "node_modules/**" });
68
+ return files;
69
+ } catch (error) {
70
+ throw new Error(`Error finding files: ${error}`);
71
+ }
72
+ };
73
+ var searchFilesForId = async (files, id, version) => {
74
+ const idRegex = new RegExp(`^id:\\s*['"]?${id}['"]?\\s*$`, "m");
75
+ const versionRegex = new RegExp(`^version:\\s*['"]?${version}['"]?\\s*$`, "m");
76
+ const matches = await Promise.all(
77
+ files.map(async (file) => {
78
+ const content = await import_promises.default.readFile(file, "utf-8");
79
+ const hasIdMatch = content.match(idRegex);
80
+ if (version && !content.match(versionRegex)) {
81
+ return void 0;
82
+ }
83
+ if (hasIdMatch) {
84
+ return file;
85
+ }
86
+ })
87
+ );
88
+ return matches.filter(Boolean).filter((file) => file !== void 0);
89
+ };
90
+ var copyDir = async (catalogDir, source, target, filter) => {
91
+ const tmpDirectory = (0, import_node_path.join)(catalogDir, "tmp");
92
+ await import_promises.default.mkdir(tmpDirectory, { recursive: true });
93
+ await (0, import_fs_extra.copy)(source, tmpDirectory, {
94
+ overwrite: true,
95
+ filter
96
+ });
97
+ await (0, import_fs_extra.copy)(tmpDirectory, target, {
98
+ overwrite: true,
99
+ filter
100
+ });
101
+ await import_promises.default.rm(tmpDirectory, { recursive: true });
102
+ };
103
+
104
+ // src/events.ts
105
+ var getEvent = (directory) => async (id, version) => {
106
+ const file = await findFileById(directory, id, version);
107
+ if (!file) throw new Error(`No event found for the given id: ${id}` + (version ? ` and version ${version}` : ""));
108
+ const { data, content } = import_gray_matter.default.read(file);
109
+ return {
110
+ ...data,
111
+ markdown: content.trim()
112
+ };
113
+ };
114
+ var writeEvent = (directory) => async (event, options = { path: "" }) => {
115
+ const path = options.path || `/${event.id}`;
116
+ const exists = await versionExists(directory, event.id, event.version);
117
+ if (exists) {
118
+ throw new Error(`Failed to write event as the version ${event.version} already exists`);
119
+ }
120
+ const { markdown, ...frontmatter } = event;
121
+ const document = import_gray_matter.default.stringify(markdown.trim(), frontmatter);
122
+ await import_promises2.default.mkdir((0, import_node_path2.join)(directory, path), { recursive: true });
123
+ await import_promises2.default.writeFile((0, import_node_path2.join)(directory, path, "index.md"), document);
124
+ };
125
+ var rmEvent = (directory) => async (path) => {
126
+ await import_promises2.default.rm((0, import_node_path2.join)(directory, path), { recursive: true });
127
+ };
128
+ var rmEventById = (directory) => async (id, version) => {
129
+ const files = await getFiles(`${directory}/**/index.md`);
130
+ const matchedFiles = await searchFilesForId(files, id, version);
131
+ if (matchedFiles.length === 0) {
132
+ throw new Error(`No event found with id: ${id}`);
133
+ }
134
+ await Promise.all(matchedFiles.map((file) => import_promises2.default.rm(file)));
135
+ };
136
+ var versionEvent = (directory) => async (id) => {
137
+ const files = await getFiles(`${directory}/**/index.md`);
138
+ const matchedFiles = await searchFilesForId(files, id);
139
+ if (matchedFiles.length === 0) {
140
+ throw new Error(`No event found with id: ${id}`);
141
+ }
142
+ const file = matchedFiles[0];
143
+ const eventDirectory = (0, import_node_path3.dirname)(file);
144
+ const { data: { version = "0.0.1" } = {} } = import_gray_matter.default.read(file);
145
+ const targetDirectory = (0, import_node_path2.join)(eventDirectory, "versioned", version);
146
+ await import_promises2.default.mkdir(targetDirectory, { recursive: true });
147
+ await copyDir(directory, eventDirectory, targetDirectory, (src) => {
148
+ return !src.includes("versioned");
149
+ });
150
+ await import_promises2.default.readdir(eventDirectory).then(async (resourceFiles) => {
151
+ await Promise.all(
152
+ resourceFiles.map(async (file2) => {
153
+ if (file2 !== "versioned") {
154
+ await import_promises2.default.rm((0, import_node_path2.join)(eventDirectory, file2), { recursive: true });
155
+ }
156
+ })
157
+ );
158
+ });
159
+ };
160
+ var addFileToEvent = (directory) => async (id, file, version) => {
161
+ const pathToEvent = await findFileById(directory, id, version);
162
+ if (!pathToEvent) throw new Error("Cannot find directory to write file to");
163
+ const contentDirectory = (0, import_node_path3.dirname)(pathToEvent);
164
+ await import_promises2.default.writeFile((0, import_node_path2.join)(contentDirectory, file.fileName), file.content);
165
+ };
166
+ var addSchemaToEvent = (directory) => async (id, schema, version) => {
167
+ await addFileToEvent(directory)(id, { content: schema.schema, fileName: schema.fileName }, version);
168
+ };
169
+ // Annotate the CommonJS export names for ESM import in node:
170
+ 0 && (module.exports = {
171
+ addFileToEvent,
172
+ addSchemaToEvent,
173
+ getEvent,
174
+ rmEvent,
175
+ rmEventById,
176
+ versionEvent,
177
+ writeEvent
178
+ });
179
+ //# sourceMappingURL=events.js.map