@t0.labs/daxta 0.4.2 → 0.4.4
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 +14 -0
- package/dist/build/build-spec.js +21 -3
- package/dist/cli/config-edit.d.ts +8 -0
- package/dist/cli/config-edit.js +168 -0
- package/dist/cli/install.js +5 -0
- package/dist/cli/main.js +11 -1
- package/dist/cli/tree.d.ts +12 -0
- package/dist/cli/tree.js +234 -0
- package/dist/fields/dto-fields.d.ts +8 -0
- package/dist/fields/dto-fields.js +64 -1
- package/dist/path.util.d.ts +9 -1
- package/dist/path.util.js +105 -5
- package/dist/recorder/index.js +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -91,10 +91,24 @@ daxta install # one-shot setup
|
|
|
91
91
|
daxta migrate # after a package bump
|
|
92
92
|
daxta build # rebuild OpenAPI/HTML from recorded hits
|
|
93
93
|
daxta serve # optional standalone viewer (prefer apiDocs on the app)
|
|
94
|
+
daxta tree # choose sidebar folder order for a path
|
|
94
95
|
daxta fields … # export field map for an operation
|
|
95
96
|
daxta call … # CLI Try-it
|
|
96
97
|
```
|
|
97
98
|
|
|
99
|
+
### Sidebar order (`daxta tree`)
|
|
100
|
+
|
|
101
|
+
Pick a path and how it should nest under `/docs`:
|
|
102
|
+
|
|
103
|
+
```text
|
|
104
|
+
/v1/admin/baskets
|
|
105
|
+
1) URL order v1 › admin › baskets
|
|
106
|
+
2) Resource-first v1 › baskets › admin
|
|
107
|
+
3) Custom …
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
Saves `treeLayout` / `treePathOverrides` in `daxta.config.ts`. Then `daxta build`.
|
|
111
|
+
|
|
98
112
|
|
|
99
113
|
|
|
100
114
|
## API
|
package/dist/build/build-spec.js
CHANGED
|
@@ -44,6 +44,24 @@ const dto_fields_1 = require("../fields/dto-fields");
|
|
|
44
44
|
const path_util_1 = require("../path.util");
|
|
45
45
|
const paths_1 = require("../serve/paths");
|
|
46
46
|
const METHOD_RANK = { get: 0, post: 1, put: 2, patch: 3, delete: 4 };
|
|
47
|
+
/** Re-map old/mis-templated hits onto Nest routes (or stronger heuristics). */
|
|
48
|
+
function canonicalizeHit(hit) {
|
|
49
|
+
const concrete = hit.path.includes('{') ? (0, path_util_1.materializePath)(hit.path, hit.pathParams) : hit.path;
|
|
50
|
+
const nextPath = (0, path_util_1.templatize)(concrete, hit.test, hit.method);
|
|
51
|
+
if (!nextPath)
|
|
52
|
+
return null;
|
|
53
|
+
const pathParams = concrete !== nextPath || !hit.pathParams || !Object.keys(hit.pathParams).length
|
|
54
|
+
? (0, path_util_1.extractPathParams)(nextPath, concrete)
|
|
55
|
+
: hit.pathParams;
|
|
56
|
+
return {
|
|
57
|
+
...hit,
|
|
58
|
+
path: nextPath,
|
|
59
|
+
pathParams: Object.keys(pathParams).length ? pathParams : hit.pathParams,
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
function canonicalizeHits(hits) {
|
|
63
|
+
return hits.map(canonicalizeHit).filter((hit) => hit != null);
|
|
64
|
+
}
|
|
47
65
|
function readPackageMeta() {
|
|
48
66
|
try {
|
|
49
67
|
const pkg = JSON.parse((0, fs_1.readFileSync)(path.join(process.cwd(), 'package.json'), 'utf8'));
|
|
@@ -379,7 +397,7 @@ function loadHits() {
|
|
|
379
397
|
return [];
|
|
380
398
|
const workerFiles = (0, fs_1.readdirSync)((0, paths_1.getOutDir)()).filter((fileName) => fileName.startsWith('hits-w') && fileName.endsWith('.json'));
|
|
381
399
|
if (workerFiles.length) {
|
|
382
|
-
return workerFiles.flatMap((fileName) => {
|
|
400
|
+
return canonicalizeHits(workerFiles.flatMap((fileName) => {
|
|
383
401
|
try {
|
|
384
402
|
const parsed = JSON.parse((0, fs_1.readFileSync)(path.join((0, paths_1.getOutDir)(), fileName), 'utf8'));
|
|
385
403
|
return Array.isArray(parsed) ? parsed : [];
|
|
@@ -388,14 +406,14 @@ function loadHits() {
|
|
|
388
406
|
console.error(`DAxTA: skipped corrupt hits file ${fileName}:`, error);
|
|
389
407
|
return [];
|
|
390
408
|
}
|
|
391
|
-
});
|
|
409
|
+
}));
|
|
392
410
|
}
|
|
393
411
|
// Fallback after workers were cleaned — rebuild from last merged hits.json
|
|
394
412
|
try {
|
|
395
413
|
if (!(0, fs_1.existsSync)((0, paths_1.getHitsJsonPath)()))
|
|
396
414
|
return [];
|
|
397
415
|
const parsed = JSON.parse((0, fs_1.readFileSync)((0, paths_1.getHitsJsonPath)(), 'utf8'));
|
|
398
|
-
return Array.isArray(parsed) ? parsed : [];
|
|
416
|
+
return canonicalizeHits(Array.isArray(parsed) ? parsed : []);
|
|
399
417
|
}
|
|
400
418
|
catch (error) {
|
|
401
419
|
console.error('DAxTA: skipped corrupt hits.json:', error);
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export declare function findDaxtaConfigPath(cwd?: string): string | null;
|
|
2
|
+
/** Replace or insert a top-level `key: <value>` inside `defineConfig({ ... })`. */
|
|
3
|
+
export declare function upsertConfigValue(configPath: string, key: string, valueLiteral: string): void;
|
|
4
|
+
export declare function formatTsString(value: string): string;
|
|
5
|
+
export declare function formatTsStringArray(values: string[]): string;
|
|
6
|
+
export declare function formatTsStringRecord(record: Record<string, string[]>): string;
|
|
7
|
+
export declare function readTreePathOverrides(cwd?: string): Record<string, string[]>;
|
|
8
|
+
export declare function previewTree(segments: string[]): string;
|
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
14
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
15
|
+
}) : function(o, v) {
|
|
16
|
+
o["default"] = v;
|
|
17
|
+
});
|
|
18
|
+
var __importStar = (this && this.__importStar) || (function () {
|
|
19
|
+
var ownKeys = function(o) {
|
|
20
|
+
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
21
|
+
var ar = [];
|
|
22
|
+
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
23
|
+
return ar;
|
|
24
|
+
};
|
|
25
|
+
return ownKeys(o);
|
|
26
|
+
};
|
|
27
|
+
return function (mod) {
|
|
28
|
+
if (mod && mod.__esModule) return mod;
|
|
29
|
+
var result = {};
|
|
30
|
+
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
31
|
+
__setModuleDefault(result, mod);
|
|
32
|
+
return result;
|
|
33
|
+
};
|
|
34
|
+
})();
|
|
35
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
36
|
+
exports.findDaxtaConfigPath = findDaxtaConfigPath;
|
|
37
|
+
exports.upsertConfigValue = upsertConfigValue;
|
|
38
|
+
exports.formatTsString = formatTsString;
|
|
39
|
+
exports.formatTsStringArray = formatTsStringArray;
|
|
40
|
+
exports.formatTsStringRecord = formatTsStringRecord;
|
|
41
|
+
exports.readTreePathOverrides = readTreePathOverrides;
|
|
42
|
+
exports.previewTree = previewTree;
|
|
43
|
+
const fs_1 = require("fs");
|
|
44
|
+
const path = __importStar(require("path"));
|
|
45
|
+
const ui_1 = require("./ui");
|
|
46
|
+
const CONFIG_NAMES = ['daxta.config.ts', 'daxta.config.js', 'daxta.config.mjs', 'daxta.config.cjs'];
|
|
47
|
+
function findDaxtaConfigPath(cwd = process.cwd()) {
|
|
48
|
+
for (const name of CONFIG_NAMES) {
|
|
49
|
+
const full = path.join(cwd, name);
|
|
50
|
+
if ((0, fs_1.existsSync)(full))
|
|
51
|
+
return full;
|
|
52
|
+
}
|
|
53
|
+
return null;
|
|
54
|
+
}
|
|
55
|
+
/** Replace or insert a top-level `key: <value>` inside `defineConfig({ ... })`. */
|
|
56
|
+
function upsertConfigValue(configPath, key, valueLiteral) {
|
|
57
|
+
let text = (0, fs_1.readFileSync)(configPath, 'utf8');
|
|
58
|
+
const keyRe = new RegExp(`${key}\\s*:`);
|
|
59
|
+
const match = keyRe.exec(text);
|
|
60
|
+
if (!match) {
|
|
61
|
+
const next = text.replace(/defineConfig\(\s*\{/, `defineConfig({\n ${key}: ${valueLiteral},`);
|
|
62
|
+
if (next === text)
|
|
63
|
+
throw new Error(`Could not insert ${key} into ${path.basename(configPath)}`);
|
|
64
|
+
(0, fs_1.writeFileSync)(configPath, next);
|
|
65
|
+
return;
|
|
66
|
+
}
|
|
67
|
+
const afterColon = match.index + match[0].length;
|
|
68
|
+
let i = afterColon;
|
|
69
|
+
while (i < text.length && /\s/.test(text[i]))
|
|
70
|
+
i += 1;
|
|
71
|
+
const start = i;
|
|
72
|
+
let end = i;
|
|
73
|
+
const ch = text[i];
|
|
74
|
+
if (ch === '{' || ch === '[') {
|
|
75
|
+
const open = ch;
|
|
76
|
+
const close = ch === '{' ? '}' : ']';
|
|
77
|
+
let depth = 0;
|
|
78
|
+
let quote = null;
|
|
79
|
+
let escaped = false;
|
|
80
|
+
for (; end < text.length; end += 1) {
|
|
81
|
+
const cur = text[end];
|
|
82
|
+
if (quote) {
|
|
83
|
+
if (escaped) {
|
|
84
|
+
escaped = false;
|
|
85
|
+
continue;
|
|
86
|
+
}
|
|
87
|
+
if (cur === '\\' && quote !== '`') {
|
|
88
|
+
escaped = true;
|
|
89
|
+
continue;
|
|
90
|
+
}
|
|
91
|
+
if (cur === quote)
|
|
92
|
+
quote = null;
|
|
93
|
+
continue;
|
|
94
|
+
}
|
|
95
|
+
if (cur === '"' || cur === "'" || cur === '`') {
|
|
96
|
+
quote = cur;
|
|
97
|
+
continue;
|
|
98
|
+
}
|
|
99
|
+
if (cur === open)
|
|
100
|
+
depth += 1;
|
|
101
|
+
else if (cur === close) {
|
|
102
|
+
depth -= 1;
|
|
103
|
+
if (depth === 0) {
|
|
104
|
+
end += 1;
|
|
105
|
+
break;
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
else if (ch === '"' || ch === "'" || ch === '`') {
|
|
111
|
+
const quote = ch;
|
|
112
|
+
end = i + 1;
|
|
113
|
+
let escaped = false;
|
|
114
|
+
for (; end < text.length; end += 1) {
|
|
115
|
+
const cur = text[end];
|
|
116
|
+
if (escaped) {
|
|
117
|
+
escaped = false;
|
|
118
|
+
continue;
|
|
119
|
+
}
|
|
120
|
+
if (cur === '\\') {
|
|
121
|
+
escaped = true;
|
|
122
|
+
continue;
|
|
123
|
+
}
|
|
124
|
+
if (cur === quote) {
|
|
125
|
+
end += 1;
|
|
126
|
+
break;
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
else {
|
|
131
|
+
while (end < text.length && !/[,}\n]/.test(text[end]))
|
|
132
|
+
end += 1;
|
|
133
|
+
}
|
|
134
|
+
text = `${text.slice(0, start)}${valueLiteral}${text.slice(end)}`;
|
|
135
|
+
(0, fs_1.writeFileSync)(configPath, text);
|
|
136
|
+
}
|
|
137
|
+
function formatTsString(value) {
|
|
138
|
+
return JSON.stringify(value);
|
|
139
|
+
}
|
|
140
|
+
function formatTsStringArray(values) {
|
|
141
|
+
return `[${values.map((value) => JSON.stringify(value)).join(', ')}]`;
|
|
142
|
+
}
|
|
143
|
+
function formatTsStringRecord(record) {
|
|
144
|
+
const keys = Object.keys(record).sort((a, b) => a.localeCompare(b));
|
|
145
|
+
if (!keys.length)
|
|
146
|
+
return '{}';
|
|
147
|
+
const lines = keys.map((key) => ` ${JSON.stringify(key)}: ${formatTsStringArray(record[key])},`);
|
|
148
|
+
return `{\n${lines.join('\n')}\n }`;
|
|
149
|
+
}
|
|
150
|
+
function readTreePathOverrides(cwd = process.cwd()) {
|
|
151
|
+
try {
|
|
152
|
+
// eslint-disable-next-line @typescript-eslint/no-var-requires
|
|
153
|
+
const { createJiti } = require('jiti');
|
|
154
|
+
const configPath = findDaxtaConfigPath(cwd);
|
|
155
|
+
if (!configPath)
|
|
156
|
+
return {};
|
|
157
|
+
const jiti = createJiti(__filename);
|
|
158
|
+
const mod = jiti(configPath);
|
|
159
|
+
const cfg = (mod.default ?? mod);
|
|
160
|
+
return { ...(cfg.treePathOverrides ?? {}) };
|
|
161
|
+
}
|
|
162
|
+
catch {
|
|
163
|
+
return {};
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
function previewTree(segments) {
|
|
167
|
+
return segments.map((part) => ui_1.c.cyan(part)).join(ui_1.c.dim(' › '));
|
|
168
|
+
}
|
package/dist/cli/install.js
CHANGED
|
@@ -40,6 +40,7 @@ const child_process_1 = require("child_process");
|
|
|
40
40
|
const inject_main_1 = require("./inject-main");
|
|
41
41
|
const discover_test_1 = require("./discover-test");
|
|
42
42
|
const jest_hooks_1 = require("./jest-hooks");
|
|
43
|
+
const tree_1 = require("./tree");
|
|
43
44
|
const ui_1 = require("./ui");
|
|
44
45
|
function readJson(filePath) {
|
|
45
46
|
return JSON.parse((0, fs_1.readFileSync)(filePath, 'utf8'));
|
|
@@ -291,10 +292,14 @@ async function installDaxta(options = {}) {
|
|
|
291
292
|
else {
|
|
292
293
|
await (0, ui_1.step)('Attach test hooks', () => 'skipped', { paceMs });
|
|
293
294
|
}
|
|
295
|
+
if (!dryRun) {
|
|
296
|
+
await (0, tree_1.runTreeWizard)({ embedded: true, yes: Boolean(options.yes) });
|
|
297
|
+
}
|
|
294
298
|
(0, ui_1.box)('Done', [
|
|
295
299
|
`${ui_1.c.green('✔')} DAxTA wired for ${ui_1.c.bold(project)}`,
|
|
296
300
|
`${ui_1.c.dim('env')} ${ui_1.c.cyan('DAXTA_DOCS=true')} or ${ui_1.c.cyan('false')}`,
|
|
297
301
|
`${ui_1.c.dim('tests')} run your usual script — Docs ready prints when Jest finishes`,
|
|
302
|
+
`${ui_1.c.dim('sidebar')} ${ui_1.c.cyan('daxta tree')} anytime to re-arrange folders`,
|
|
298
303
|
]);
|
|
299
304
|
const wired = testScript && pkg.scripts?.[testScript] ? testScript : null;
|
|
300
305
|
(0, ui_1.nextSteps)([
|
package/dist/cli/main.js
CHANGED
|
@@ -8,6 +8,7 @@ const serve_1 = require("../serve");
|
|
|
8
8
|
const install_1 = require("./install");
|
|
9
9
|
const migrate_1 = require("./migrate");
|
|
10
10
|
const test_1 = require("./test");
|
|
11
|
+
const tree_1 = require("./tree");
|
|
11
12
|
function usage() {
|
|
12
13
|
console.log(`DAxTA CLI (@t0.labs/daxta)
|
|
13
14
|
|
|
@@ -18,6 +19,7 @@ Usage:
|
|
|
18
19
|
daxta test [--script <name>] [--config <jest.json>] [--serve] [--port <n>] [--yes]
|
|
19
20
|
daxta build
|
|
20
21
|
daxta serve [--port <n>]
|
|
22
|
+
daxta tree [PATH] [--layout resource-first|url-order]
|
|
21
23
|
daxta fields [METHOD] [PATH] [--out <file>]
|
|
22
24
|
daxta call [METHOD] [PATH] [--fields <file>] [--header k:v ...]
|
|
23
25
|
daxta call --file <values.json> [--header k:v ...]
|
|
@@ -27,6 +29,7 @@ One-shot setup:
|
|
|
27
29
|
npx @t0.labs/daxta install
|
|
28
30
|
|
|
29
31
|
daxta test = forwards to your package script (Jest stays parent; DAxTA is a plugin)
|
|
32
|
+
daxta tree = choose how paths appear in the /docs sidebar
|
|
30
33
|
`);
|
|
31
34
|
}
|
|
32
35
|
function parseArgs(argv) {
|
|
@@ -40,7 +43,7 @@ function parseArgs(argv) {
|
|
|
40
43
|
const token = rest[i];
|
|
41
44
|
if (token === '--')
|
|
42
45
|
break;
|
|
43
|
-
if (token === '--port' || token === '--out' || token === '--fields' || token === '--file' || token === '--main') {
|
|
46
|
+
if (token === '--port' || token === '--out' || token === '--fields' || token === '--file' || token === '--main' || token === '--layout') {
|
|
44
47
|
flags[token.slice(2)] = rest[++i];
|
|
45
48
|
}
|
|
46
49
|
else if (token === '--header') {
|
|
@@ -105,6 +108,13 @@ async function main() {
|
|
|
105
108
|
(0, serve_1.serveApiDocs)({ port });
|
|
106
109
|
return;
|
|
107
110
|
}
|
|
111
|
+
if (command === 'tree') {
|
|
112
|
+
await (0, tree_1.runTreeWizard)({
|
|
113
|
+
path: positional[0],
|
|
114
|
+
layout: typeof flags.layout === 'string' ? flags.layout : undefined,
|
|
115
|
+
});
|
|
116
|
+
return;
|
|
117
|
+
}
|
|
108
118
|
if (command === 'fields') {
|
|
109
119
|
const method = positional[0]?.toLowerCase();
|
|
110
120
|
const pathTemplate = positional[1];
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
export type TreeWizardOptions = {
|
|
2
|
+
path?: string;
|
|
3
|
+
layout?: string;
|
|
4
|
+
/** Called from install — no extra banner, always ask layout when TTY */
|
|
5
|
+
embedded?: boolean;
|
|
6
|
+
yes?: boolean;
|
|
7
|
+
};
|
|
8
|
+
/**
|
|
9
|
+
* Interactive sidebar layout wizard.
|
|
10
|
+
* Also used at the end of `daxta install` so the question is not a hidden separate command.
|
|
11
|
+
*/
|
|
12
|
+
export declare function runTreeWizard(options?: TreeWizardOptions): Promise<void>;
|
package/dist/cli/tree.js
ADDED
|
@@ -0,0 +1,234 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.runTreeWizard = runTreeWizard;
|
|
4
|
+
const readline_1 = require("readline");
|
|
5
|
+
const fs_1 = require("fs");
|
|
6
|
+
const config_1 = require("../config");
|
|
7
|
+
const dto_fields_1 = require("../fields/dto-fields");
|
|
8
|
+
const paths_1 = require("../serve/paths");
|
|
9
|
+
const config_edit_1 = require("./config-edit");
|
|
10
|
+
const ui_1 = require("./ui");
|
|
11
|
+
function prompt(question) {
|
|
12
|
+
const rl = (0, readline_1.createInterface)({ input: process.stdin, output: process.stdout });
|
|
13
|
+
return new Promise((resolve) => {
|
|
14
|
+
rl.question(question, (answer) => {
|
|
15
|
+
rl.close();
|
|
16
|
+
resolve(answer.trim());
|
|
17
|
+
});
|
|
18
|
+
});
|
|
19
|
+
}
|
|
20
|
+
function normalizePathInput(raw) {
|
|
21
|
+
const trimmed = raw.trim();
|
|
22
|
+
if (!trimmed)
|
|
23
|
+
return trimmed;
|
|
24
|
+
return trimmed.startsWith('/') ? trimmed.replace(/\/+$/, '') || '/' : `/${trimmed.replace(/\/+$/, '')}`;
|
|
25
|
+
}
|
|
26
|
+
function urlOrderSegments(pathTemplate) {
|
|
27
|
+
return pathTemplate.split('/').filter(Boolean);
|
|
28
|
+
}
|
|
29
|
+
function resourceFirstSegments(pathTemplate) {
|
|
30
|
+
const parts = urlOrderSegments(pathTemplate);
|
|
31
|
+
if (parts.length >= 3 && /^v\d+$/i.test(parts[0])) {
|
|
32
|
+
return [parts[0], parts[2], parts[1], ...parts.slice(3)];
|
|
33
|
+
}
|
|
34
|
+
return parts;
|
|
35
|
+
}
|
|
36
|
+
/** Put known "area" segments (admin/device/…) right after version. */
|
|
37
|
+
function areaFirstSegments(pathTemplate) {
|
|
38
|
+
const parts = urlOrderSegments(pathTemplate);
|
|
39
|
+
if (parts.length < 3 || !/^v\d+$/i.test(parts[0]))
|
|
40
|
+
return parts;
|
|
41
|
+
const areas = new Set(['admin', 'device', 'devices', 'user', 'users', 'me', 'internal', 'public']);
|
|
42
|
+
const version = parts[0];
|
|
43
|
+
const rest = parts.slice(1);
|
|
44
|
+
const areaIdx = rest.findIndex((part) => areas.has(part.toLowerCase()) && !part.startsWith('{'));
|
|
45
|
+
if (areaIdx <= 0)
|
|
46
|
+
return parts;
|
|
47
|
+
const area = rest[areaIdx];
|
|
48
|
+
const without = [...rest.slice(0, areaIdx), ...rest.slice(areaIdx + 1)];
|
|
49
|
+
return [version, area, ...without];
|
|
50
|
+
}
|
|
51
|
+
function listKnownPaths() {
|
|
52
|
+
const fromSpec = new Set();
|
|
53
|
+
try {
|
|
54
|
+
const specPath = (0, paths_1.getSpecJsonPath)();
|
|
55
|
+
if ((0, fs_1.existsSync)(specPath)) {
|
|
56
|
+
const spec = JSON.parse((0, fs_1.readFileSync)(specPath, 'utf8'));
|
|
57
|
+
for (const key of Object.keys(spec.paths ?? {}))
|
|
58
|
+
fromSpec.add(key);
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
catch {
|
|
62
|
+
// ignore
|
|
63
|
+
}
|
|
64
|
+
try {
|
|
65
|
+
for (const pathTemplate of (0, dto_fields_1.listControllerPathTemplates)())
|
|
66
|
+
fromSpec.add(pathTemplate);
|
|
67
|
+
}
|
|
68
|
+
catch {
|
|
69
|
+
// controllers may not parse yet
|
|
70
|
+
}
|
|
71
|
+
return [...fromSpec].sort((a, b) => a.localeCompare(b));
|
|
72
|
+
}
|
|
73
|
+
function printPathChoices(paths, limit = 12) {
|
|
74
|
+
if (!paths.length) {
|
|
75
|
+
console.log(` ${ui_1.c.dim('tip')} type a path like ${ui_1.c.cyan('/v1/admin/baskets')}`);
|
|
76
|
+
return;
|
|
77
|
+
}
|
|
78
|
+
console.log(` ${ui_1.c.dim('known paths')}`);
|
|
79
|
+
paths.slice(0, limit).forEach((item, index) => {
|
|
80
|
+
console.log(` ${ui_1.c.dim(String(index + 1).padStart(2, ' '))} ${ui_1.c.cyan(item)}`);
|
|
81
|
+
});
|
|
82
|
+
if (paths.length > limit)
|
|
83
|
+
console.log(` ${ui_1.c.dim(`… +${paths.length - limit} more`)}`);
|
|
84
|
+
}
|
|
85
|
+
async function pickPath(flagPath) {
|
|
86
|
+
if (flagPath)
|
|
87
|
+
return normalizePathInput(flagPath);
|
|
88
|
+
const known = listKnownPaths();
|
|
89
|
+
printPathChoices(known);
|
|
90
|
+
const answer = await prompt(` ${ui_1.c.yellow('?')} ${ui_1.c.bold('Path')} to arrange in the sidebar\n` +
|
|
91
|
+
` ${ui_1.c.dim('number · /v1/admin/baskets · or n to skip')}\n ${ui_1.c.cyan('›')} `);
|
|
92
|
+
if (!answer || /^n(o)?$/i.test(answer))
|
|
93
|
+
return null;
|
|
94
|
+
if (/^\d+$/.test(answer)) {
|
|
95
|
+
const picked = known[Number(answer) - 1];
|
|
96
|
+
if (!picked)
|
|
97
|
+
throw new Error(`No path #${answer}`);
|
|
98
|
+
return picked;
|
|
99
|
+
}
|
|
100
|
+
return normalizePathInput(answer);
|
|
101
|
+
}
|
|
102
|
+
async function pickGlobalLayout(current) {
|
|
103
|
+
const sample = '/v1/admin/baskets';
|
|
104
|
+
console.log('');
|
|
105
|
+
console.log(` ${ui_1.c.bold('Docs sidebar layout')}`);
|
|
106
|
+
console.log(` ${ui_1.c.dim('Example')} ${ui_1.c.cyan(sample)}`);
|
|
107
|
+
console.log('');
|
|
108
|
+
console.log(` ${ui_1.c.cyan('1')} resource-first`);
|
|
109
|
+
console.log(` ${(0, config_edit_1.previewTree)(resourceFirstSegments(sample))}`);
|
|
110
|
+
console.log(` ${ui_1.c.dim('v1 → baskets → admin')}`);
|
|
111
|
+
console.log('');
|
|
112
|
+
console.log(` ${ui_1.c.cyan('2')} url-order`);
|
|
113
|
+
console.log(` ${(0, config_edit_1.previewTree)(urlOrderSegments(sample))}`);
|
|
114
|
+
console.log(` ${ui_1.c.dim('v1 → admin → baskets')}`);
|
|
115
|
+
console.log('');
|
|
116
|
+
console.log(` ${ui_1.c.cyan('3')} keep ${ui_1.c.dim(`(${current})`)}`);
|
|
117
|
+
const answer = await prompt(` ${ui_1.c.yellow('?')} How should folders nest under /docs?\n ${ui_1.c.cyan('›')} `);
|
|
118
|
+
if (!answer || answer === '3' || /^k(eep)?$/i.test(answer))
|
|
119
|
+
return null;
|
|
120
|
+
if (answer === '1' || /^resource/i.test(answer))
|
|
121
|
+
return 'resource-first';
|
|
122
|
+
if (answer === '2' || /^url/i.test(answer))
|
|
123
|
+
return 'url-order';
|
|
124
|
+
throw new Error(`Unknown layout choice: ${answer}`);
|
|
125
|
+
}
|
|
126
|
+
function layoutChoicesFor(pathTemplate) {
|
|
127
|
+
const url = urlOrderSegments(pathTemplate);
|
|
128
|
+
const resource = resourceFirstSegments(pathTemplate);
|
|
129
|
+
const area = areaFirstSegments(pathTemplate);
|
|
130
|
+
const choices = [
|
|
131
|
+
{ id: 'url', label: 'URL order', segments: url },
|
|
132
|
+
{ id: 'resource', label: 'Resource-first', segments: resource },
|
|
133
|
+
];
|
|
134
|
+
if (area.join('/') !== url.join('/') && area.join('/') !== resource.join('/')) {
|
|
135
|
+
choices.push({ id: 'area', label: 'Area-first (admin/device/…)', segments: area });
|
|
136
|
+
}
|
|
137
|
+
choices.push({ id: 'custom', label: 'Custom segments', segments: url });
|
|
138
|
+
return choices;
|
|
139
|
+
}
|
|
140
|
+
async function pickSegments(pathTemplate) {
|
|
141
|
+
const choices = layoutChoicesFor(pathTemplate);
|
|
142
|
+
console.log('');
|
|
143
|
+
console.log(` ${ui_1.c.bold('Sidebar for')} ${ui_1.c.cyan(pathTemplate)}`);
|
|
144
|
+
console.log(` ${ui_1.c.dim('Which nesting do you want?')}`);
|
|
145
|
+
choices.forEach((choice, index) => {
|
|
146
|
+
const mark = ui_1.c.cyan(String(index + 1));
|
|
147
|
+
console.log(` ${mark} ${ui_1.c.bold(choice.label)}`);
|
|
148
|
+
console.log(` ${(0, config_edit_1.previewTree)(choice.segments)}`);
|
|
149
|
+
});
|
|
150
|
+
const answer = await prompt(` ${ui_1.c.yellow('?')} Choose\n ${ui_1.c.cyan('›')} `);
|
|
151
|
+
if (!answer || /^n(o)?$/i.test(answer))
|
|
152
|
+
return null;
|
|
153
|
+
const index = /^\d+$/.test(answer)
|
|
154
|
+
? Number(answer) - 1
|
|
155
|
+
: choices.findIndex((choice) => choice.id === answer || choice.label.toLowerCase().startsWith(answer.toLowerCase()));
|
|
156
|
+
const selected = choices[index];
|
|
157
|
+
if (!selected)
|
|
158
|
+
throw new Error(`Unknown choice: ${answer}`);
|
|
159
|
+
if (selected.id !== 'custom')
|
|
160
|
+
return selected.segments;
|
|
161
|
+
const typed = await prompt(` ${ui_1.c.yellow('?')} Segments in order ${ui_1.c.dim('(space or › separated)')}\n` +
|
|
162
|
+
` ${ui_1.c.dim('e.g. v1 baskets admin')}\n ${ui_1.c.cyan('›')} `);
|
|
163
|
+
if (!typed)
|
|
164
|
+
return null;
|
|
165
|
+
return typed
|
|
166
|
+
.split(/›|>|,|\s+/)
|
|
167
|
+
.map((part) => part.trim())
|
|
168
|
+
.filter(Boolean);
|
|
169
|
+
}
|
|
170
|
+
function saveLayout(configPath, layout) {
|
|
171
|
+
(0, config_edit_1.upsertConfigValue)(configPath, 'treeLayout', (0, config_edit_1.formatTsString)(layout));
|
|
172
|
+
}
|
|
173
|
+
function saveOverride(configPath, pathTemplate, segments) {
|
|
174
|
+
const overrides = (0, config_edit_1.readTreePathOverrides)();
|
|
175
|
+
overrides[pathTemplate] = segments;
|
|
176
|
+
(0, config_edit_1.upsertConfigValue)(configPath, 'treePathOverrides', (0, config_edit_1.formatTsStringRecord)(overrides));
|
|
177
|
+
}
|
|
178
|
+
/**
|
|
179
|
+
* Interactive sidebar layout wizard.
|
|
180
|
+
* Also used at the end of `daxta install` so the question is not a hidden separate command.
|
|
181
|
+
*/
|
|
182
|
+
async function runTreeWizard(options = {}) {
|
|
183
|
+
if (options.yes || !process.stdin.isTTY) {
|
|
184
|
+
if (!options.embedded) {
|
|
185
|
+
console.log(` ${ui_1.c.dim('tree wizard skipped (non-interactive)')}`);
|
|
186
|
+
}
|
|
187
|
+
return;
|
|
188
|
+
}
|
|
189
|
+
if (!options.embedded)
|
|
190
|
+
(0, ui_1.banner)('DAxTA tree', 'sidebar folder order');
|
|
191
|
+
const configPath = (0, config_edit_1.findDaxtaConfigPath)();
|
|
192
|
+
if (!configPath) {
|
|
193
|
+
throw new Error('No daxta.config.ts found. Run `daxta install` first.');
|
|
194
|
+
}
|
|
195
|
+
(0, config_1.resetConfig)();
|
|
196
|
+
const config = (0, config_1.getConfig)(true);
|
|
197
|
+
console.log('');
|
|
198
|
+
console.log(` ${ui_1.c.yellow(ui_1.c.bold('?'))} ${ui_1.c.bold('Sidebar')} ${ui_1.c.dim('— how /docs folders nest')}`);
|
|
199
|
+
if (options.layout === 'resource-first' || options.layout === 'url-order') {
|
|
200
|
+
saveLayout(configPath, options.layout);
|
|
201
|
+
console.log(` ${ui_1.c.green('✔')} treeLayout → ${ui_1.c.cyan(options.layout)}`);
|
|
202
|
+
}
|
|
203
|
+
else {
|
|
204
|
+
const layout = await pickGlobalLayout(config.treeLayout);
|
|
205
|
+
if (layout) {
|
|
206
|
+
saveLayout(configPath, layout);
|
|
207
|
+
console.log(` ${ui_1.c.green('✔')} treeLayout → ${ui_1.c.cyan(layout)}`);
|
|
208
|
+
}
|
|
209
|
+
else {
|
|
210
|
+
console.log(` ${ui_1.c.dim('kept')} treeLayout ${ui_1.c.cyan(config.treeLayout)}`);
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
const customize = options.path
|
|
214
|
+
? 'y'
|
|
215
|
+
: await prompt(` ${ui_1.c.yellow('?')} Customize a specific path now?\n` +
|
|
216
|
+
` ${ui_1.c.dim('Y')} yes · ${ui_1.c.dim('n')} later ${ui_1.c.dim('(daxta tree)')}\n ${ui_1.c.cyan('›')} `);
|
|
217
|
+
if (customize && !/^n(o)?$/i.test(customize)) {
|
|
218
|
+
const pathTemplate = await pickPath(options.path);
|
|
219
|
+
if (pathTemplate) {
|
|
220
|
+
const segments = await pickSegments(pathTemplate);
|
|
221
|
+
if (segments?.length) {
|
|
222
|
+
saveOverride(configPath, pathTemplate, segments);
|
|
223
|
+
console.log('');
|
|
224
|
+
console.log(` ${ui_1.c.green('✔')} ${ui_1.c.cyan(pathTemplate)}`);
|
|
225
|
+
console.log(` ${(0, config_edit_1.previewTree)(segments)}`);
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
if (!options.embedded) {
|
|
230
|
+
console.log(` ${ui_1.c.dim('saved to')} ${configPath}`);
|
|
231
|
+
console.log(` ${ui_1.c.dim('refresh docs:')} ${ui_1.c.cyan('daxta build')}`);
|
|
232
|
+
console.log('');
|
|
233
|
+
}
|
|
234
|
+
}
|
|
@@ -1,4 +1,12 @@
|
|
|
1
1
|
import 'reflect-metadata';
|
|
2
2
|
export type FieldLocation = 'path' | 'query' | 'header' | 'body';
|
|
3
|
+
export declare function controllerRouteCount(): number;
|
|
4
|
+
/** Unique Nest controller path templates (may omit URI version prefix). */
|
|
5
|
+
export declare function listControllerPathTemplates(): string[];
|
|
6
|
+
/**
|
|
7
|
+
* Map a concrete request path onto a Nest controller OpenAPI template.
|
|
8
|
+
* Prefers the most specific declared route (longest path, fewest params).
|
|
9
|
+
*/
|
|
10
|
+
export declare function matchControllerTemplate(pathname: string, method?: string): string | null;
|
|
3
11
|
/** Returns required flag from DTO metadata, or undefined when unknown (no DTO / no validators). */
|
|
4
12
|
export declare function dtoRequired(method: string, pathTemplate: string, location: FieldLocation, fieldName: string): boolean | undefined;
|
|
@@ -33,6 +33,9 @@ var __importStar = (this && this.__importStar) || (function () {
|
|
|
33
33
|
};
|
|
34
34
|
})();
|
|
35
35
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
36
|
+
exports.controllerRouteCount = controllerRouteCount;
|
|
37
|
+
exports.listControllerPathTemplates = listControllerPathTemplates;
|
|
38
|
+
exports.matchControllerTemplate = matchControllerTemplate;
|
|
36
39
|
exports.dtoRequired = dtoRequired;
|
|
37
40
|
/**
|
|
38
41
|
* Resolve Required / Optional from Nest controllers + class-validator DTO metadata.
|
|
@@ -46,6 +49,7 @@ const storage_1 = require("class-transformer/cjs/storage");
|
|
|
46
49
|
const class_validator_1 = require("class-validator");
|
|
47
50
|
const ts = __importStar(require("typescript"));
|
|
48
51
|
const config_1 = require("../config");
|
|
52
|
+
const path_util_1 = require("../path.util");
|
|
49
53
|
function controllerRoot() {
|
|
50
54
|
return (0, config_1.getConfig)().controllersRoot;
|
|
51
55
|
}
|
|
@@ -274,9 +278,68 @@ function getRoutes() {
|
|
|
274
278
|
});
|
|
275
279
|
return routeCache;
|
|
276
280
|
}
|
|
281
|
+
function controllerRouteCount() {
|
|
282
|
+
return getRoutes().length;
|
|
283
|
+
}
|
|
284
|
+
/** Unique Nest controller path templates (may omit URI version prefix). */
|
|
285
|
+
function listControllerPathTemplates() {
|
|
286
|
+
const seen = new Set();
|
|
287
|
+
for (const route of getRoutes()) {
|
|
288
|
+
seen.add(route.pathTemplate);
|
|
289
|
+
if (!/^\/v\d+/i.test(route.pathTemplate)) {
|
|
290
|
+
seen.add(`/v1${route.pathTemplate.startsWith('/') ? route.pathTemplate : `/${route.pathTemplate}`}`);
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
return [...seen].sort((a, b) => a.localeCompare(b));
|
|
294
|
+
}
|
|
295
|
+
function scoreTemplate(template) {
|
|
296
|
+
const parts = template.split('/').filter(Boolean);
|
|
297
|
+
const params = parts.filter((part) => /^\{.+\}$/.test(part)).length;
|
|
298
|
+
return parts.length * 10 - params;
|
|
299
|
+
}
|
|
300
|
+
function ensureVersionPrefix(template, actual) {
|
|
301
|
+
if (/^\/v\d+/i.test(template) || !/^\/v\d+/i.test(actual))
|
|
302
|
+
return template;
|
|
303
|
+
const version = actual.match(/^\/(v\d+)/i)?.[1] ?? 'v1';
|
|
304
|
+
return `/${version}${template.startsWith('/') ? template : `/${template}`}`;
|
|
305
|
+
}
|
|
306
|
+
/**
|
|
307
|
+
* Map a concrete request path onto a Nest controller OpenAPI template.
|
|
308
|
+
* Prefers the most specific declared route (longest path, fewest params).
|
|
309
|
+
*/
|
|
310
|
+
function matchControllerTemplate(pathname, method) {
|
|
311
|
+
const routes = getRoutes();
|
|
312
|
+
if (!routes.length)
|
|
313
|
+
return null;
|
|
314
|
+
const actual = (pathname.split('?')[0] || '/').replace(/\/+$/, '') || '/';
|
|
315
|
+
const stripped = actual.replace(/^\/v\d+(?=\/|$)/i, '') || '/';
|
|
316
|
+
const methodKey = method?.toLowerCase();
|
|
317
|
+
let best = null;
|
|
318
|
+
for (const route of routes) {
|
|
319
|
+
if (methodKey && route.method !== 'all' && route.method !== methodKey)
|
|
320
|
+
continue;
|
|
321
|
+
const base = route.pathTemplate;
|
|
322
|
+
const versioned = ensureVersionPrefix(base, actual);
|
|
323
|
+
const candidates = [...new Set([base, versioned])];
|
|
324
|
+
for (const template of candidates) {
|
|
325
|
+
const ok = (0, path_util_1.pathMatchesTemplate)(template, actual) ||
|
|
326
|
+
(0, path_util_1.pathMatchesTemplate)(base, stripped) ||
|
|
327
|
+
(0, path_util_1.pathMatchesTemplate)(template, stripped);
|
|
328
|
+
if (!ok)
|
|
329
|
+
continue;
|
|
330
|
+
const resolved = (0, path_util_1.pathMatchesTemplate)(template, actual) ? template : ensureVersionPrefix(base, actual);
|
|
331
|
+
const score = scoreTemplate(resolved);
|
|
332
|
+
if (!best || score > best.score)
|
|
333
|
+
best = { template: resolved, score };
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
return best?.template ?? null;
|
|
337
|
+
}
|
|
277
338
|
function findRoute(method, pathTemplate) {
|
|
278
339
|
const keyMethod = method.toLowerCase();
|
|
279
|
-
|
|
340
|
+
const routes = getRoutes();
|
|
341
|
+
return (routes.find((route) => route.method === keyMethod && route.pathTemplate === pathTemplate) ||
|
|
342
|
+
routes.find((route) => route.method === keyMethod && ensureVersionPrefix(route.pathTemplate, pathTemplate) === pathTemplate));
|
|
280
343
|
}
|
|
281
344
|
function isOptionalMetas(metas) {
|
|
282
345
|
return metas.some((meta) => meta.type === 'conditionalValidation' || meta.name === 'isOptional');
|
package/dist/path.util.d.ts
CHANGED
|
@@ -1,6 +1,14 @@
|
|
|
1
1
|
export declare function toOpenApiTemplate(path: string): string;
|
|
2
2
|
export declare function templateFromTestName(test?: string): string | null;
|
|
3
3
|
export declare function pathMatchesTemplate(template: string, actual: string): boolean;
|
|
4
|
-
export declare function
|
|
4
|
+
export declare function isDynamicSegment(segment: string, previous?: string): boolean;
|
|
5
|
+
export declare function heuristicTemplatize(pathname: string): string;
|
|
6
|
+
/**
|
|
7
|
+
* Map a concrete (or already-templated) path onto an OpenAPI template.
|
|
8
|
+
* Returns null when the hit should not be recorded (unknown vs Nest controllers).
|
|
9
|
+
*/
|
|
10
|
+
export declare function templatize(pathname: string, test?: string, method?: string): string | null;
|
|
5
11
|
export declare function pathParamNames(pathTemplate: string): string[];
|
|
6
12
|
export declare function extractPathParams(pathTemplate: string, actualPath: string): Record<string, string>;
|
|
13
|
+
/** Fill `{param}` slots so a stored template can be re-matched / re-heuristic'd. */
|
|
14
|
+
export declare function materializePath(pathTemplate: string, pathParams?: Record<string, string>): string;
|
package/dist/path.util.js
CHANGED
|
@@ -3,13 +3,48 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
|
3
3
|
exports.toOpenApiTemplate = toOpenApiTemplate;
|
|
4
4
|
exports.templateFromTestName = templateFromTestName;
|
|
5
5
|
exports.pathMatchesTemplate = pathMatchesTemplate;
|
|
6
|
+
exports.isDynamicSegment = isDynamicSegment;
|
|
7
|
+
exports.heuristicTemplatize = heuristicTemplatize;
|
|
6
8
|
exports.templatize = templatize;
|
|
7
9
|
exports.pathParamNames = pathParamNames;
|
|
8
10
|
exports.extractPathParams = extractPathParams;
|
|
11
|
+
exports.materializePath = materializePath;
|
|
9
12
|
const config_1 = require("./config");
|
|
10
13
|
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
11
|
-
const NUMERIC_ID_RE =
|
|
14
|
+
const NUMERIC_ID_RE = /^-?\d+(\.\d+)?$/;
|
|
12
15
|
const TOKENISH_RE = /^[A-Za-z0-9_-]{16,}$/;
|
|
16
|
+
const BOOLISH_RE = /^(true|false|null|undefined)$/i;
|
|
17
|
+
const ENCODED_RE = /%[0-9A-Fa-f]{2}/;
|
|
18
|
+
const LITERAL_PARAM_RE = /^\{[^}]+\}$/;
|
|
19
|
+
/** Path segments that are real route actions/resources, not id-like test values. */
|
|
20
|
+
const STATIC_SEGMENTS = new Set([
|
|
21
|
+
'lock',
|
|
22
|
+
'unlock',
|
|
23
|
+
'pay',
|
|
24
|
+
'complete',
|
|
25
|
+
'cancel',
|
|
26
|
+
'confirm',
|
|
27
|
+
'status',
|
|
28
|
+
'start',
|
|
29
|
+
'stop',
|
|
30
|
+
'retry',
|
|
31
|
+
'approve',
|
|
32
|
+
'reject',
|
|
33
|
+
'search',
|
|
34
|
+
'export',
|
|
35
|
+
'import',
|
|
36
|
+
'me',
|
|
37
|
+
'admin',
|
|
38
|
+
'device',
|
|
39
|
+
'devices',
|
|
40
|
+
'basket',
|
|
41
|
+
'baskets',
|
|
42
|
+
'user',
|
|
43
|
+
'users',
|
|
44
|
+
'health',
|
|
45
|
+
'ready',
|
|
46
|
+
'live',
|
|
47
|
+
]);
|
|
13
48
|
function toOpenApiTemplate(path) {
|
|
14
49
|
return path.replace(/:([A-Za-z_][A-Za-z0-9_]*)/g, '{$1}');
|
|
15
50
|
}
|
|
@@ -29,12 +64,43 @@ function pathMatchesTemplate(template, actual) {
|
|
|
29
64
|
return false;
|
|
30
65
|
return templateParts.every((part, index) => /^\{.+\}$/.test(part) || part === actualParts[index]);
|
|
31
66
|
}
|
|
67
|
+
function safeDecode(segment) {
|
|
68
|
+
try {
|
|
69
|
+
return decodeURIComponent(segment);
|
|
70
|
+
}
|
|
71
|
+
catch {
|
|
72
|
+
return segment;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
function looksLikeCollection(segment) {
|
|
76
|
+
if (!segment || /^v\d+$/i.test(segment) || /^\{.+\}$/.test(segment))
|
|
77
|
+
return false;
|
|
78
|
+
const lower = segment.toLowerCase();
|
|
79
|
+
if (STATIC_SEGMENTS.has(lower) && !lower.endsWith('s'))
|
|
80
|
+
return false;
|
|
81
|
+
return /s$/i.test(segment) || /list|items|records/i.test(segment);
|
|
82
|
+
}
|
|
83
|
+
function looksLikeStaticSegment(segment) {
|
|
84
|
+
return STATIC_SEGMENTS.has(safeDecode(segment).toLowerCase());
|
|
85
|
+
}
|
|
32
86
|
function isDynamicSegment(segment, previous) {
|
|
33
|
-
|
|
87
|
+
const decoded = safeDecode(segment);
|
|
88
|
+
if (UUID_RE.test(decoded))
|
|
89
|
+
return true;
|
|
90
|
+
if (NUMERIC_ID_RE.test(decoded))
|
|
91
|
+
return true;
|
|
92
|
+
if (BOOLISH_RE.test(decoded))
|
|
93
|
+
return true;
|
|
94
|
+
if (LITERAL_PARAM_RE.test(decoded))
|
|
34
95
|
return true;
|
|
35
|
-
if (
|
|
96
|
+
if (ENCODED_RE.test(segment))
|
|
36
97
|
return true;
|
|
37
|
-
if (
|
|
98
|
+
if (/^(\[\]|\{\}|\[.*\]|\{.*\})$/.test(decoded.replace(/\s/g, '')))
|
|
99
|
+
return true;
|
|
100
|
+
if (TOKENISH_RE.test(decoded) && previous && !/^v\d+$/i.test(previous))
|
|
101
|
+
return true;
|
|
102
|
+
// After a collection, only known actions/resources stay literal — test junk becomes {id}
|
|
103
|
+
if (previous && looksLikeCollection(previous) && !looksLikeStaticSegment(decoded))
|
|
38
104
|
return true;
|
|
39
105
|
return false;
|
|
40
106
|
}
|
|
@@ -79,16 +145,43 @@ function heuristicTemplatize(pathname) {
|
|
|
79
145
|
});
|
|
80
146
|
return `/${templated.join('/')}`;
|
|
81
147
|
}
|
|
82
|
-
function
|
|
148
|
+
function matchAgainstControllers(pathname, method) {
|
|
149
|
+
try {
|
|
150
|
+
// Lazy require avoids circular init with dto-fields → path.util
|
|
151
|
+
// eslint-disable-next-line @typescript-eslint/no-var-requires
|
|
152
|
+
const dto = require('./fields/dto-fields');
|
|
153
|
+
const matched = dto.matchControllerTemplate(pathname, method);
|
|
154
|
+
if (matched)
|
|
155
|
+
return { matched };
|
|
156
|
+
if (dto.controllerRouteCount() > 0)
|
|
157
|
+
return { skip: true };
|
|
158
|
+
}
|
|
159
|
+
catch {
|
|
160
|
+
// controllers unavailable
|
|
161
|
+
}
|
|
162
|
+
return { none: true };
|
|
163
|
+
}
|
|
164
|
+
/**
|
|
165
|
+
* Map a concrete (or already-templated) path onto an OpenAPI template.
|
|
166
|
+
* Returns null when the hit should not be recorded (unknown vs Nest controllers).
|
|
167
|
+
*/
|
|
168
|
+
function templatize(pathname, test, method) {
|
|
83
169
|
const trimmed = (pathname.split('?')[0] || '/').replace(/\/+$/, '') || '/';
|
|
84
170
|
if (trimmed === '/')
|
|
85
171
|
return null;
|
|
86
172
|
const custom = (0, config_1.getConfig)().templatize?.(trimmed, test);
|
|
87
173
|
if (custom)
|
|
88
174
|
return custom;
|
|
175
|
+
if (custom === null)
|
|
176
|
+
return null;
|
|
89
177
|
const declared = templateFromTestName(test);
|
|
90
178
|
if (declared && pathMatchesTemplate(declared, trimmed))
|
|
91
179
|
return declared;
|
|
180
|
+
const controller = matchAgainstControllers(trimmed, method);
|
|
181
|
+
if ('matched' in controller)
|
|
182
|
+
return controller.matched;
|
|
183
|
+
if ('skip' in controller)
|
|
184
|
+
return null;
|
|
92
185
|
return heuristicTemplatize(trimmed);
|
|
93
186
|
}
|
|
94
187
|
function pathParamNames(pathTemplate) {
|
|
@@ -106,3 +199,10 @@ function extractPathParams(pathTemplate, actualPath) {
|
|
|
106
199
|
}
|
|
107
200
|
return params;
|
|
108
201
|
}
|
|
202
|
+
/** Fill `{param}` slots so a stored template can be re-matched / re-heuristic'd. */
|
|
203
|
+
function materializePath(pathTemplate, pathParams) {
|
|
204
|
+
return pathTemplate.replace(/\{([^}]+)\}/g, (_, name) => {
|
|
205
|
+
const value = pathParams?.[name];
|
|
206
|
+
return value != null && value !== '' ? encodeURIComponent(value) : name;
|
|
207
|
+
});
|
|
208
|
+
}
|
package/dist/recorder/index.js
CHANGED
|
@@ -77,7 +77,7 @@ function recordFromSuperagent(request, res) {
|
|
|
77
77
|
const rawUrl = request.url || '';
|
|
78
78
|
const url = new URL(rawUrl, 'http://localhost');
|
|
79
79
|
const test = currentTestName();
|
|
80
|
-
const pathTemplate = (0, path_util_1.templatize)(url.pathname, test);
|
|
80
|
+
const pathTemplate = (0, path_util_1.templatize)(url.pathname, test, (request.method || 'GET').toLowerCase());
|
|
81
81
|
if (!pathTemplate)
|
|
82
82
|
return;
|
|
83
83
|
const query = Object.fromEntries(url.searchParams.entries());
|