@x12i/static-memorix-explorer-api 1.3.2 → 1.5.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.
package/README.md CHANGED
@@ -21,6 +21,26 @@ Then open **http://localhost:5030/demo**. The command prints the Demo, API,
21
21
  Health, and JSON paths when it starts. No database or additional configuration
22
22
  is required.
23
23
 
24
+ To create an editable demo in your own directory instead of using the bundled
25
+ read-only seeds:
26
+
27
+ ```bash
28
+ memorix-explorer create-demo
29
+ memorix-explorer --mocks-dir ./memorix-demo
30
+ ```
31
+
32
+ The first command creates `./memorix-demo` with `demo.html`, seed data,
33
+ metadata, write descriptors, and its own README. It refuses to overwrite an
34
+ existing path. The second command serves that folder, and all UI create/edit/
35
+ delete operations persist their routed JSON files inside it.
36
+
37
+ Choose a different destination or port if needed:
38
+
39
+ ```bash
40
+ memorix-explorer create-demo --dir ./my-project-fixtures
41
+ memorix-explorer --mocks-dir ./my-project-fixtures --port 8080
42
+ ```
43
+
24
44
  Useful options:
25
45
 
26
46
  ```bash
@@ -29,6 +49,16 @@ memorix-explorer --help
29
49
  memorix-explorer --version
30
50
  ```
31
51
 
52
+ Stop a server started by the CLI:
53
+
54
+ ```bash
55
+ memorix-explorer stop # port 5030
56
+ memorix-explorer stop --port 8080
57
+ ```
58
+
59
+ If a requested port is occupied, the CLI explains these stop and alternate-port
60
+ options instead of returning only `EADDRINUSE`.
61
+
32
62
  ### Run from this repository
33
63
 
34
64
  ```bash
@@ -299,6 +329,25 @@ and `knowledgeId`.
299
329
 
300
330
  ## Release history
301
331
 
332
+ ### v1.5.0
333
+ - Added `memorix-explorer stop [--port <number>]` with safe managed-process
334
+ tracking and stale-PID cleanup.
335
+ - Added actionable port-conflict output with stop and alternate-port commands.
336
+ - Changed `create-demo` instructions to relative, user-owned paths such as
337
+ `./memorix-demo`; package or maintainer filesystem paths are never exposed.
338
+ - Added lifecycle and occupied-port integration coverage.
339
+
340
+ ### v1.4.0
341
+ - Added `memorix-explorer create-demo` to create a user-owned, writable demo.
342
+ - Added `--dir` for the generated demo destination and `--mocks-dir` for
343
+ serving any fixture directory directly from the CLI.
344
+ - Generated demos include UI, metadata, seed data, write descriptors, and a
345
+ local usage README.
346
+ - Demo creation is atomic, refuses overwrites, and excludes routed state that
347
+ may have been generated inside a previously used global installation.
348
+ - Installed CLI aliases now use a configuration-first launcher so fixture paths
349
+ are resolved before the server loads.
350
+
302
351
  ### v1.3.2
303
352
  - Added the short `memorix-explorer` CLI command.
304
353
  - Added `--help`/`-h` and `--version`/`-v` commands.
package/dist/cli.d.ts ADDED
@@ -0,0 +1,17 @@
1
+ #!/usr/bin/env node
2
+ export interface CliServerOptions {
3
+ port?: number;
4
+ host?: string;
5
+ mocksDir?: string;
6
+ }
7
+ export declare const CLI_HELP = "Memorix Explorer static server\n\nUsage:\n memorix-explorer create-demo [--dir <path>]\n memorix-explorer stop [--port <number>]\n memorix-explorer [options]\n\nCommands:\n create-demo Create a writable demo folder (default: ./memorix-demo)\n stop Stop a managed server (default port: 5030)\n\nServer options:\n --port <number> Port to listen on (default: 5030)\n --host <address> Host to bind (default: 0.0.0.0)\n --mocks-dir <path> JSON fixture directory\n -h, --help Show this help\n -v, --version Show the installed version\n\nQuick start:\n memorix-explorer create-demo\n memorix-explorer --mocks-dir ./memorix-demo\n";
8
+ export declare function getPackageVersion(): string;
9
+ export declare function parseServerArgs(args: string[]): CliServerOptions;
10
+ export declare function parseCreateDemoArgs(args: string[]): {
11
+ targetDir: string;
12
+ };
13
+ export declare function createDemo(targetDir: string): string;
14
+ export declare function pidFileForPort(port: number): string;
15
+ export declare function registerManagedServer(port: number): void;
16
+ export declare function stopManagedServer(port: number): Promise<boolean>;
17
+ export declare function runCli(args: string[]): Promise<void>;
package/dist/cli.js ADDED
@@ -0,0 +1,276 @@
1
+ #!/usr/bin/env node
2
+ import fs from "node:fs";
3
+ import { randomUUID } from "node:crypto";
4
+ import { execFileSync } from "node:child_process";
5
+ import os from "node:os";
6
+ import path from "node:path";
7
+ import { fileURLToPath } from "node:url";
8
+ export const CLI_HELP = `Memorix Explorer static server
9
+
10
+ Usage:
11
+ memorix-explorer create-demo [--dir <path>]
12
+ memorix-explorer stop [--port <number>]
13
+ memorix-explorer [options]
14
+
15
+ Commands:
16
+ create-demo Create a writable demo folder (default: ./memorix-demo)
17
+ stop Stop a managed server (default port: 5030)
18
+
19
+ Server options:
20
+ --port <number> Port to listen on (default: 5030)
21
+ --host <address> Host to bind (default: 0.0.0.0)
22
+ --mocks-dir <path> JSON fixture directory
23
+ -h, --help Show this help
24
+ -v, --version Show the installed version
25
+
26
+ Quick start:
27
+ memorix-explorer create-demo
28
+ memorix-explorer --mocks-dir ./memorix-demo
29
+ `;
30
+ function packageRoot() {
31
+ return path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
32
+ }
33
+ export function getPackageVersion() {
34
+ return JSON.parse(fs.readFileSync(path.join(packageRoot(), "package.json"), "utf8")).version;
35
+ }
36
+ export function parseServerArgs(args) {
37
+ const options = {};
38
+ for (let index = 0; index < args.length; index++) {
39
+ const arg = args[index];
40
+ if (arg === "--port") {
41
+ const raw = args[++index];
42
+ const port = Number(raw);
43
+ if (!raw || !Number.isInteger(port) || port < 0 || port > 65535) {
44
+ throw new Error("--port must be an integer from 0 to 65535");
45
+ }
46
+ options.port = port;
47
+ }
48
+ else if (arg === "--host") {
49
+ const host = args[++index];
50
+ if (!host)
51
+ throw new Error("--host requires a value");
52
+ options.host = host;
53
+ }
54
+ else if (arg === "--mocks-dir") {
55
+ const mocksDir = args[++index];
56
+ if (!mocksDir)
57
+ throw new Error("--mocks-dir requires a path");
58
+ options.mocksDir = path.resolve(mocksDir);
59
+ }
60
+ else {
61
+ throw new Error(`Unknown CLI argument: ${arg}`);
62
+ }
63
+ }
64
+ return options;
65
+ }
66
+ export function parseCreateDemoArgs(args) {
67
+ let targetDir = path.resolve("memorix-demo");
68
+ for (let index = 0; index < args.length; index++) {
69
+ const arg = args[index];
70
+ if (arg === "--dir") {
71
+ const value = args[++index];
72
+ if (!value)
73
+ throw new Error("--dir requires a path");
74
+ targetDir = path.resolve(value);
75
+ }
76
+ else {
77
+ throw new Error(`Unknown create-demo argument: ${arg}`);
78
+ }
79
+ }
80
+ return { targetDir };
81
+ }
82
+ export function createDemo(targetDir) {
83
+ const resolved = path.resolve(targetDir);
84
+ if (fs.existsSync(resolved)) {
85
+ throw new Error(`Refusing to overwrite existing path: ${resolved}`);
86
+ }
87
+ const bundledMocks = path.join(packageRoot(), "mocks");
88
+ if (!fs.existsSync(bundledMocks)) {
89
+ throw new Error(`Bundled demo fixtures not found: ${bundledMocks}`);
90
+ }
91
+ const temporary = `${resolved}.creating-${randomUUID()}`;
92
+ try {
93
+ fs.cpSync(bundledMocks, temporary, {
94
+ recursive: true,
95
+ errorOnExist: true,
96
+ force: false,
97
+ // A globally installed package may already have routed runtime files.
98
+ // Copy only pristine bundled seeds, never another user's generated state.
99
+ filter: (source) => !path.basename(source).includes("--"),
100
+ });
101
+ fs.writeFileSync(path.join(temporary, "README.md"), `# Memorix Explorer demo\n\n` +
102
+ `Start this demo from this directory:\n\n` +
103
+ "```bash\nmemorix-explorer --mocks-dir . --port 5030\n```\n\n" +
104
+ `Then open http://localhost:5030/demo.\n\n` +
105
+ `Create, edit, and delete operations update the routed JSON files here.\n`, "utf8");
106
+ fs.renameSync(temporary, resolved);
107
+ }
108
+ catch (error) {
109
+ fs.rmSync(temporary, { recursive: true, force: true });
110
+ throw error;
111
+ }
112
+ return resolved;
113
+ }
114
+ function quote(value) {
115
+ return `"${value.replaceAll('"', '\\"')}"`;
116
+ }
117
+ function displayPath(value) {
118
+ const relative = path.relative(process.cwd(), value);
119
+ if (relative && !relative.startsWith("..") && !path.isAbsolute(relative)) {
120
+ return `./${relative}`;
121
+ }
122
+ return value;
123
+ }
124
+ function parsePortOption(args) {
125
+ if (args.length === 0)
126
+ return 5030;
127
+ if (args.length !== 2 || args[0] !== "--port") {
128
+ throw new Error("Usage: memorix-explorer stop [--port <number>]");
129
+ }
130
+ const port = Number(args[1]);
131
+ if (!Number.isInteger(port) || port < 1 || port > 65535) {
132
+ throw new Error("--port must be an integer from 1 to 65535");
133
+ }
134
+ return port;
135
+ }
136
+ function runtimeDirectory() {
137
+ const user = typeof process.getuid === "function" ? String(process.getuid()) : os.userInfo().username;
138
+ return path.join(os.tmpdir(), `memorix-explorer-${user}`);
139
+ }
140
+ export function pidFileForPort(port) {
141
+ return path.join(runtimeDirectory(), `${port}.pid.json`);
142
+ }
143
+ function processCommand(pid) {
144
+ if (process.platform === "win32")
145
+ return "memorix-explorer";
146
+ try {
147
+ return execFileSync("ps", ["-p", String(pid), "-o", "command="], {
148
+ encoding: "utf8",
149
+ stdio: ["ignore", "pipe", "ignore"],
150
+ }).trim();
151
+ }
152
+ catch {
153
+ return "";
154
+ }
155
+ }
156
+ function isRunning(pid) {
157
+ try {
158
+ process.kill(pid, 0);
159
+ return true;
160
+ }
161
+ catch {
162
+ return false;
163
+ }
164
+ }
165
+ export function registerManagedServer(port) {
166
+ const file = pidFileForPort(port);
167
+ fs.mkdirSync(path.dirname(file), { recursive: true });
168
+ fs.writeFileSync(file, JSON.stringify({ pid: process.pid, port, startedAt: new Date().toISOString() }) + "\n");
169
+ process.once("exit", () => {
170
+ try {
171
+ const current = JSON.parse(fs.readFileSync(file, "utf8"));
172
+ if (current.pid === process.pid)
173
+ fs.unlinkSync(file);
174
+ }
175
+ catch {
176
+ // Missing or replaced PID files need no cleanup.
177
+ }
178
+ });
179
+ }
180
+ export async function stopManagedServer(port) {
181
+ const file = pidFileForPort(port);
182
+ if (!fs.existsSync(file))
183
+ return false;
184
+ let pid;
185
+ try {
186
+ pid = Number(JSON.parse(fs.readFileSync(file, "utf8")).pid);
187
+ }
188
+ catch {
189
+ fs.unlinkSync(file);
190
+ return false;
191
+ }
192
+ if (!Number.isInteger(pid) || pid <= 0 || !isRunning(pid)) {
193
+ fs.unlinkSync(file);
194
+ return false;
195
+ }
196
+ const command = processCommand(pid);
197
+ if (process.platform !== "win32" && !command) {
198
+ throw new Error(`Cannot verify Memorix Explorer PID ${pid}; refusing to stop it`);
199
+ }
200
+ if (command && !/memorix-explorer|static-memorix-explorer-api|mock-memorix-explorer-api|dist\/cli\.js/.test(command)) {
201
+ throw new Error(`Refusing to stop PID ${pid}; it is not a Memorix Explorer process`);
202
+ }
203
+ process.kill(pid, "SIGTERM");
204
+ for (let attempt = 0; attempt < 50 && isRunning(pid); attempt++) {
205
+ await new Promise((resolve) => setTimeout(resolve, 100));
206
+ }
207
+ if (isRunning(pid))
208
+ throw new Error(`Timed out while stopping Memorix Explorer PID ${pid}`);
209
+ if (fs.existsSync(file))
210
+ fs.unlinkSync(file);
211
+ return true;
212
+ }
213
+ export async function runCli(args) {
214
+ if (args.includes("--help") || args.includes("-h")) {
215
+ console.log(CLI_HELP);
216
+ return;
217
+ }
218
+ if (args.includes("--version") || args.includes("-v")) {
219
+ console.log(getPackageVersion());
220
+ return;
221
+ }
222
+ if (args[0] === "create-demo") {
223
+ const { targetDir } = parseCreateDemoArgs(args.slice(1));
224
+ const created = createDemo(targetDir);
225
+ const shown = displayPath(created);
226
+ console.log(`\nDemo created:\n ${shown}\n`);
227
+ console.log("Start the server with:");
228
+ console.log(` memorix-explorer --mocks-dir ${quote(shown)}\n`);
229
+ console.log("Then open:");
230
+ console.log(" http://localhost:5030/demo\n");
231
+ console.log("Create, edit, and delete operations will update JSON files in that folder.");
232
+ return;
233
+ }
234
+ if (args[0] === "stop") {
235
+ const port = parsePortOption(args.slice(1));
236
+ const stopped = await stopManagedServer(port);
237
+ console.log(stopped
238
+ ? `Memorix Explorer on port ${port} stopped.`
239
+ : `No managed Memorix Explorer server found on port ${port}.`);
240
+ return;
241
+ }
242
+ const options = parseServerArgs(args);
243
+ if (options.mocksDir)
244
+ process.env.MOCKS_DIR = options.mocksDir;
245
+ const { startServer } = await import("./server.js");
246
+ const port = options.port ?? 5030;
247
+ try {
248
+ const app = await startServer({ port, host: options.host });
249
+ const address = app.server.address();
250
+ const boundPort = typeof address === "object" && address ? address.port : port;
251
+ registerManagedServer(boundPort);
252
+ }
253
+ catch (error) {
254
+ if (error.code === "EADDRINUSE") {
255
+ throw new Error(`Port ${port} is already in use. Run "memorix-explorer stop --port ${port}" ` +
256
+ `or choose another port with "--port ${port + 1}".`);
257
+ }
258
+ throw error;
259
+ }
260
+ }
261
+ function isCliEntrypoint() {
262
+ if (!process.argv[1])
263
+ return false;
264
+ try {
265
+ return fs.realpathSync(path.resolve(process.argv[1])) === fileURLToPath(import.meta.url);
266
+ }
267
+ catch {
268
+ return false;
269
+ }
270
+ }
271
+ if (isCliEntrypoint()) {
272
+ runCli(process.argv.slice(2)).catch((error) => {
273
+ console.error(error instanceof Error ? error.message : error);
274
+ process.exit(1);
275
+ });
276
+ }
@@ -11,7 +11,7 @@ export declare function executeListDescriptor(desc: ListDescriptor, params?: Exp
11
11
  export declare function suggestListExtensions(entityName: string): {
12
12
  entityName: string;
13
13
  suggestions: {
14
- contentType: "events" | "memory" | "analysis" | "decisions";
14
+ contentType: "analysis" | "decisions" | "events" | "memory";
15
15
  collection: string;
16
16
  suggestion: string;
17
17
  }[];
@@ -59,6 +59,54 @@ Memorix Explorer is ready
59
59
  Health: http://localhost:5030/health
60
60
  ```
61
61
 
62
+ ### Create a writable demo
63
+
64
+ The bundled fixtures may live inside a global npm installation. Create a
65
+ user-owned copy before experimenting with create/edit/delete:
66
+
67
+ ```bash
68
+ memorix-explorer create-demo
69
+ ```
70
+
71
+ The command creates `./memorix-demo` and prints the exact next step:
72
+
73
+ ```text
74
+ Demo created:
75
+ ./memorix-demo
76
+
77
+ Start the server with:
78
+ memorix-explorer --mocks-dir "./memorix-demo"
79
+
80
+ Then open:
81
+ http://localhost:5030/demo
82
+ ```
83
+
84
+ The generated directory contains `demo.html`, `data/`, `metadata/`, and a
85
+ README. It is safe to edit and suitable for source control. The command refuses
86
+ to overwrite an existing file or directory.
87
+
88
+ Use a custom folder or port:
89
+
90
+ ```bash
91
+ memorix-explorer create-demo --dir ./fixtures
92
+ memorix-explorer --mocks-dir ./fixtures --port 8080
93
+ ```
94
+
95
+ ### Stop the server
96
+
97
+ Press Ctrl+C in the terminal where the server is running, or stop a managed
98
+ instance from another terminal:
99
+
100
+ ```bash
101
+ memorix-explorer stop
102
+ memorix-explorer stop --port 8080
103
+ ```
104
+
105
+ The CLI tracks only server processes it started and refuses to terminate a PID
106
+ that does not identify as Memorix Explorer. Stale tracking files are removed
107
+ automatically. If startup finds an occupied port, the error prints the matching
108
+ stop command and suggests the next port.
109
+
62
110
  ### With `npx` (no global install)
63
111
 
64
112
  ```bash
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@x12i/static-memorix-explorer-api",
3
- "version": "1.3.2",
3
+ "version": "1.5.0",
4
4
  "description": "Static mock server providing full API parity for the Memorix Explorer API.",
5
5
  "type": "module",
6
6
  "main": "dist/server.js",
@@ -15,14 +15,14 @@
15
15
  }
16
16
  },
17
17
  "bin": {
18
- "memorix-explorer": "dist/server.js",
19
- "static-memorix-explorer-api": "dist/server.js",
20
- "mock-memorix-explorer-api": "dist/server.js"
18
+ "memorix-explorer": "dist/cli.js",
19
+ "static-memorix-explorer-api": "dist/cli.js",
20
+ "mock-memorix-explorer-api": "dist/cli.js"
21
21
  },
22
22
  "scripts": {
23
23
  "build": "tsc -p tsconfig.json",
24
- "start": "node dist/server.js",
25
- "dev": "node --experimental-strip-types server.ts",
24
+ "start": "node dist/cli.js",
25
+ "dev": "node --experimental-strip-types cli.ts",
26
26
  "test": "npm run build && node --test tests/*.test.mjs",
27
27
  "typecheck": "tsc -p tsconfig.json --noEmit",
28
28
  "prepack": "npm run build",