@t0.labs/daxta 0.4.7 → 0.4.8
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 +34 -4
- package/assets/viewer.html +821 -57
- package/dist/build/build-spec.js +5 -0
- package/dist/catalog/index.d.ts +1 -0
- package/dist/catalog/index.js +1 -0
- package/dist/cli/install.js +41 -3
- package/dist/cli/uninstall.js +1 -1
- package/dist/config.d.ts +18 -1
- package/dist/config.js +30 -0
- package/dist/index.d.ts +1 -1
- package/dist/serve/index.js +36 -4
- package/dist/serve/middleware.d.ts +1 -1
- package/dist/serve/middleware.js +70 -2
- package/dist/serve/paths.d.ts +2 -0
- package/dist/serve/paths.js +5 -0
- package/dist/serve/viewer-store.d.ts +22 -0
- package/dist/serve/viewer-store.js +135 -0
- package/package.json +1 -1
package/dist/build/build-spec.js
CHANGED
|
@@ -43,6 +43,7 @@ const config_1 = require("../config");
|
|
|
43
43
|
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
|
+
const viewer_store_1 = require("../serve/viewer-store");
|
|
46
47
|
const METHOD_RANK = { get: 0, post: 1, put: 2, patch: 3, delete: 4 };
|
|
47
48
|
/** Re-map old/mis-templated hits onto Nest routes (or stronger heuristics). */
|
|
48
49
|
function canonicalizeHit(hit) {
|
|
@@ -706,6 +707,10 @@ function buildDaxtaSpec(options = {}) {
|
|
|
706
707
|
const existingHits = readJson((0, paths_1.getHitsJsonPath)());
|
|
707
708
|
const existingSpec = readJson((0, paths_1.getSpecJsonPath)());
|
|
708
709
|
const writeHtml = options.html !== false;
|
|
710
|
+
const seededStore = (0, viewer_store_1.ensureViewerStoreSeeded)();
|
|
711
|
+
if (seededStore && !options.silent) {
|
|
712
|
+
console.log(`Seeded ${seededStore} from envPresets`);
|
|
713
|
+
}
|
|
709
714
|
if (!hits.length) {
|
|
710
715
|
if (existingSpec && writeHtml && viewerTemplateNewerThanHtml()) {
|
|
711
716
|
const refreshed = applyViewerMeta(existingSpec);
|
package/dist/catalog/index.d.ts
CHANGED
|
@@ -26,6 +26,7 @@ export declare function viewerTreeConfig(): {
|
|
|
26
26
|
treeSkipParams: boolean;
|
|
27
27
|
treePathOverrides: Record<string, string[]>;
|
|
28
28
|
exampleLabelStyle: "status-case" | "status-title-case" | "full";
|
|
29
|
+
envPresets: Record<string, import("../config").EnvPreset> | undefined;
|
|
29
30
|
};
|
|
30
31
|
export declare function operationTag(pathTemplate: string, method: string): string;
|
|
31
32
|
export declare function defaultTitle(method: string, pathTemplate: string): string;
|
package/dist/catalog/index.js
CHANGED
|
@@ -83,6 +83,7 @@ function viewerTreeConfig() {
|
|
|
83
83
|
treeSkipParams: config.treeSkipParams !== false,
|
|
84
84
|
treePathOverrides: config.treePathOverrides,
|
|
85
85
|
exampleLabelStyle: config.exampleLabelStyle ?? 'status-title-case',
|
|
86
|
+
envPresets: config.envPresets,
|
|
86
87
|
};
|
|
87
88
|
}
|
|
88
89
|
function titleCase(value) {
|
package/dist/cli/install.js
CHANGED
|
@@ -118,6 +118,13 @@ export default defineConfig({
|
|
|
118
118
|
treeSkipParams: true,
|
|
119
119
|
exampleLabelStyle: 'status-title-case',
|
|
120
120
|
fieldsFile: 'daxta/out/daxta.fields.json',
|
|
121
|
+
viewerStoreFile: 'daxta/viewer-store.json',
|
|
122
|
+
// Multi-base Try-it presets (docs env picker). Secrets stay in viewer-store / UI.
|
|
123
|
+
envPresets: {
|
|
124
|
+
local: { baseUrl: 'http://localhost:3000' },
|
|
125
|
+
staging: { baseUrl: 'https://api.staging.example.com' },
|
|
126
|
+
production: { baseUrl: 'https://api.example.com' },
|
|
127
|
+
},
|
|
121
128
|
});
|
|
122
129
|
`;
|
|
123
130
|
if (!dryRun)
|
|
@@ -126,7 +133,7 @@ export default defineConfig({
|
|
|
126
133
|
}
|
|
127
134
|
function ensureGitignore(cwd, dryRun) {
|
|
128
135
|
const gitignorePath = path.join(cwd, '.gitignore');
|
|
129
|
-
const entries = ['daxta/out/', '**/.jest.daxta.runtime.json'];
|
|
136
|
+
const entries = ['daxta/out/', 'daxta/viewer-store.json', '**/.jest.daxta.runtime.json'];
|
|
130
137
|
if (!(0, fs_1.existsSync)(gitignorePath)) {
|
|
131
138
|
if (!dryRun)
|
|
132
139
|
(0, fs_1.writeFileSync)(gitignorePath, `${entries.join('\n')}\n`);
|
|
@@ -146,6 +153,33 @@ function ensureGitignore(cwd, dryRun) {
|
|
|
146
153
|
(0, fs_1.writeFileSync)(gitignorePath, next);
|
|
147
154
|
return added.map((e) => `.gitignore += ${e}`);
|
|
148
155
|
}
|
|
156
|
+
const ENV_CANDIDATES = ['.env', '.env.local', '.env.development', '.env.development.local'];
|
|
157
|
+
/** Ensure DAXTA_DOCS is present (default true). Mirrors uninstall strip. */
|
|
158
|
+
function ensureEnvDaxtaDocs(cwd, dryRun) {
|
|
159
|
+
for (const name of ENV_CANDIDATES) {
|
|
160
|
+
const filePath = path.join(cwd, name);
|
|
161
|
+
if (!(0, fs_1.existsSync)(filePath))
|
|
162
|
+
continue;
|
|
163
|
+
const text = (0, fs_1.readFileSync)(filePath, 'utf8');
|
|
164
|
+
if (/^\s*DAXTA_DOCS\s*=/m.test(text))
|
|
165
|
+
return `${name} · DAXTA_DOCS already set`;
|
|
166
|
+
}
|
|
167
|
+
const targetName = ENV_CANDIDATES.find((name) => (0, fs_1.existsSync)(path.join(cwd, name))) ?? '.env';
|
|
168
|
+
const targetPath = path.join(cwd, targetName);
|
|
169
|
+
const created = !(0, fs_1.existsSync)(targetPath);
|
|
170
|
+
const line = 'DAXTA_DOCS=true';
|
|
171
|
+
if (!dryRun) {
|
|
172
|
+
if (created) {
|
|
173
|
+
(0, fs_1.writeFileSync)(targetPath, `${line}\n`);
|
|
174
|
+
}
|
|
175
|
+
else {
|
|
176
|
+
const text = (0, fs_1.readFileSync)(targetPath, 'utf8');
|
|
177
|
+
const next = text.endsWith('\n') || text.length === 0 ? `${text}${line}\n` : `${text}\n${line}\n`;
|
|
178
|
+
(0, fs_1.writeFileSync)(targetPath, next);
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
return created ? `created ${targetName} (+ DAXTA_DOCS=true)` : `${targetName} += DAXTA_DOCS=true`;
|
|
182
|
+
}
|
|
149
183
|
function runPackageInstall(cwd, pm, version, dryRun) {
|
|
150
184
|
if (dryRun)
|
|
151
185
|
return 'dry-run';
|
|
@@ -217,6 +251,7 @@ async function installDaxta(options = {}) {
|
|
|
217
251
|
return 'already ignored';
|
|
218
252
|
return { summary: `${notes.length} entr${notes.length === 1 ? 'y' : 'ies'}`, details: notes };
|
|
219
253
|
}, { paceMs });
|
|
254
|
+
await (0, ui_1.step)('Set DAXTA_DOCS in env', () => ensureEnvDaxtaDocs(cwd, dryRun), { paceMs });
|
|
220
255
|
if (!options.skipMain) {
|
|
221
256
|
console.log('');
|
|
222
257
|
console.log(` ${ui_1.c.yellow(ui_1.c.bold('?'))} ${ui_1.c.bold('Nest entry')} ${ui_1.c.dim('— wire apiDocs(app)')}`);
|
|
@@ -299,16 +334,19 @@ async function installDaxta(options = {}) {
|
|
|
299
334
|
}
|
|
300
335
|
(0, ui_1.box)('Done', [
|
|
301
336
|
`${ui_1.c.green('✔')} DAxTA wired for ${ui_1.c.bold(project)}`,
|
|
302
|
-
`${ui_1.c.dim('env')} ${ui_1.c.cyan('DAXTA_DOCS=true')}
|
|
337
|
+
`${ui_1.c.dim('env')} ${ui_1.c.cyan('DAXTA_DOCS=true')} written (set ${ui_1.c.cyan('false')} to disable /docs)`,
|
|
303
338
|
`${ui_1.c.dim('tests')} run your usual script — Docs ready prints when Jest finishes`,
|
|
304
339
|
`${ui_1.c.dim('sidebar')} ${ui_1.c.cyan('daxta tree')} anytime to re-arrange folders`,
|
|
305
340
|
]);
|
|
306
341
|
const wired = testScript && pkg.scripts?.[testScript] ? testScript : null;
|
|
307
342
|
(0, ui_1.nextSteps)([
|
|
308
|
-
{ cmd: 'echo "DAXTA_DOCS=true" >> .env', why: 'enable /docs on the app port' },
|
|
309
343
|
{
|
|
310
344
|
cmd: wired ? `${pm} run ${wired}` : 'pnpm test',
|
|
311
345
|
why: 'unchanged entrypoint — DAxTA is a Jest plugin',
|
|
312
346
|
},
|
|
347
|
+
{
|
|
348
|
+
cmd: `${pm} start:dev`,
|
|
349
|
+
why: 'open /docs (DAXTA_DOCS already in .env)',
|
|
350
|
+
},
|
|
313
351
|
]);
|
|
314
352
|
}
|
package/dist/cli/uninstall.js
CHANGED
|
@@ -72,7 +72,7 @@ function stripGitignore(cwd, dryRun) {
|
|
|
72
72
|
const gitignorePath = path.join(cwd, '.gitignore');
|
|
73
73
|
if (!(0, fs_1.existsSync)(gitignorePath))
|
|
74
74
|
return [];
|
|
75
|
-
const remove = new Set(['daxta/out/', 'daxta/', '**/.jest.daxta.runtime.json']);
|
|
75
|
+
const remove = new Set(['daxta/out/', 'daxta/', 'daxta/viewer-store.json', '**/.jest.daxta.runtime.json']);
|
|
76
76
|
const before = (0, fs_1.readFileSync)(gitignorePath, 'utf8');
|
|
77
77
|
const lines = before.split(/\r?\n/);
|
|
78
78
|
const kept = lines.filter((line) => !remove.has(line.trim()));
|
package/dist/config.d.ts
CHANGED
|
@@ -8,9 +8,21 @@ export type SpecInfo = {
|
|
|
8
8
|
version?: string;
|
|
9
9
|
description?: string;
|
|
10
10
|
};
|
|
11
|
+
/** Named Try-it preset: own baseUrl + optional extra variables (tokens, etc.). */
|
|
12
|
+
export type EnvPreset = {
|
|
13
|
+
baseUrl: string;
|
|
14
|
+
/** Extra variables merged into the preset (baseUrl wins from EnvPreset.baseUrl). */
|
|
15
|
+
variables?: Record<string, string>;
|
|
16
|
+
};
|
|
11
17
|
export type DaxtaConfig = {
|
|
12
18
|
workspace?: string;
|
|
13
19
|
baseUrl?: string;
|
|
20
|
+
/**
|
|
21
|
+
* Multi-base Try-it presets (local / staging / production, …).
|
|
22
|
+
* Seeded into the docs env picker and `daxta/viewer-store.json` on first write.
|
|
23
|
+
* Default: `{ local: { baseUrl } }` from `baseUrl`.
|
|
24
|
+
*/
|
|
25
|
+
envPresets?: Record<string, EnvPreset>;
|
|
14
26
|
controllersRoot?: string;
|
|
15
27
|
outDir?: string;
|
|
16
28
|
/**
|
|
@@ -35,6 +47,11 @@ export type DaxtaConfig = {
|
|
|
35
47
|
port?: number;
|
|
36
48
|
fieldsFile?: string;
|
|
37
49
|
docsPath?: string;
|
|
50
|
+
/**
|
|
51
|
+
* Persisted Try-it env/header store (survives rebuild). Default `daxta/viewer-store.json`.
|
|
52
|
+
* Served at `{docsPath}/env.json`. Keep out of git if it holds secrets.
|
|
53
|
+
*/
|
|
54
|
+
viewerStoreFile?: string;
|
|
38
55
|
testScript?: string;
|
|
39
56
|
testCommand?: string;
|
|
40
57
|
daxtaVersion?: string;
|
|
@@ -48,7 +65,7 @@ export type DaxtaConfig = {
|
|
|
48
65
|
includeHit?: (method: string, pathTemplate: string, test?: string) => boolean;
|
|
49
66
|
treePathSegments?: (pathTemplate: string) => string[] | undefined;
|
|
50
67
|
};
|
|
51
|
-
export type ResolvedDaxtaConfig = Required<Pick<DaxtaConfig, 'workspace' | 'baseUrl' | 'controllersRoot' | 'outDir' | 'treeLayout' | 'treePathOverrides' | 'treeSkipParams' | 'exampleLabelStyle' | 'port' | 'fieldsFile' | 'docsPath'>> & DaxtaConfig;
|
|
68
|
+
export type ResolvedDaxtaConfig = Required<Pick<DaxtaConfig, 'workspace' | 'baseUrl' | 'controllersRoot' | 'outDir' | 'treeLayout' | 'treePathOverrides' | 'treeSkipParams' | 'exampleLabelStyle' | 'port' | 'fieldsFile' | 'docsPath' | 'viewerStoreFile'>> & DaxtaConfig;
|
|
52
69
|
export declare function defineConfig(config: DaxtaConfig): DaxtaConfig;
|
|
53
70
|
export declare function normalizeTreeLayout(layout: TreeLayout | LegacyTreeLayout | undefined): TreeLayout;
|
|
54
71
|
export declare function resolveConfig(cwd?: string, overrides?: DaxtaConfig): ResolvedDaxtaConfig;
|
package/dist/config.js
CHANGED
|
@@ -53,6 +53,10 @@ const DEFAULTS = {
|
|
|
53
53
|
port: 5199,
|
|
54
54
|
fieldsFile: 'daxta.fields.json',
|
|
55
55
|
docsPath: '/docs',
|
|
56
|
+
viewerStoreFile: 'daxta/viewer-store.json',
|
|
57
|
+
envPresets: {
|
|
58
|
+
local: { baseUrl: 'http://localhost:3000' },
|
|
59
|
+
},
|
|
56
60
|
};
|
|
57
61
|
let cached = null;
|
|
58
62
|
function defineConfig(config) {
|
|
@@ -101,13 +105,39 @@ function resolveConfig(cwd = process.cwd(), overrides) {
|
|
|
101
105
|
merged.treeSkipParams = DEFAULTS.treeSkipParams;
|
|
102
106
|
if (merged.exampleLabelStyle == null)
|
|
103
107
|
merged.exampleLabelStyle = DEFAULTS.exampleLabelStyle;
|
|
108
|
+
merged.envPresets = normalizeEnvPresets(merged.envPresets, merged.baseUrl);
|
|
104
109
|
merged.controllersRoot = path.isAbsolute(merged.controllersRoot)
|
|
105
110
|
? merged.controllersRoot
|
|
106
111
|
: path.join(cwd, merged.controllersRoot);
|
|
107
112
|
merged.outDir = path.isAbsolute(merged.outDir) ? merged.outDir : path.join(cwd, merged.outDir);
|
|
108
113
|
merged.fieldsFile = path.isAbsolute(merged.fieldsFile) ? merged.fieldsFile : path.join(cwd, merged.fieldsFile);
|
|
114
|
+
merged.viewerStoreFile = path.isAbsolute(merged.viewerStoreFile)
|
|
115
|
+
? merged.viewerStoreFile
|
|
116
|
+
: path.join(cwd, merged.viewerStoreFile);
|
|
109
117
|
return merged;
|
|
110
118
|
}
|
|
119
|
+
function normalizeEnvPresets(presets, fallbackBaseUrl) {
|
|
120
|
+
const input = presets && typeof presets === 'object' ? presets : {};
|
|
121
|
+
const out = {};
|
|
122
|
+
for (const [name, preset] of Object.entries(input)) {
|
|
123
|
+
if (!name.trim() || !preset || typeof preset !== 'object')
|
|
124
|
+
continue;
|
|
125
|
+
const baseUrl = String(preset.baseUrl || fallbackBaseUrl).replace(/\/$/, '') || fallbackBaseUrl;
|
|
126
|
+
const variables = {};
|
|
127
|
+
if (preset.variables && typeof preset.variables === 'object') {
|
|
128
|
+
for (const [key, value] of Object.entries(preset.variables)) {
|
|
129
|
+
if (!key || key === 'baseUrl')
|
|
130
|
+
continue;
|
|
131
|
+
variables[key] = String(value ?? '');
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
out[name] = Object.keys(variables).length ? { baseUrl, variables } : { baseUrl };
|
|
135
|
+
}
|
|
136
|
+
if (!Object.keys(out).length) {
|
|
137
|
+
out.local = { baseUrl: String(fallbackBaseUrl).replace(/\/$/, '') || 'http://localhost:3000' };
|
|
138
|
+
}
|
|
139
|
+
return out;
|
|
140
|
+
}
|
|
111
141
|
function getConfig(forceReload = false) {
|
|
112
142
|
if (!cached || forceReload)
|
|
113
143
|
cached = resolveConfig();
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { defineConfig, getConfig, resolveConfig, normalizeTreeLayout, type DaxtaConfig, type TreeLayout, type ExampleLabelStyle, type SpecInfo } from './config';
|
|
1
|
+
export { defineConfig, getConfig, resolveConfig, normalizeTreeLayout, type DaxtaConfig, type EnvPreset, type TreeLayout, type ExampleLabelStyle, type SpecInfo } from './config';
|
|
2
2
|
export { buildDaxtaSpec, buildOpenApi, loadHits, type BuildResult, type Scenario } from './build/build-spec';
|
|
3
3
|
export { rebuildFromDisk, flushAndRebuild, clearPartialMarker, touchPartialMarker } from './build/incremental';
|
|
4
4
|
export { install, flush, clearWorkerHits, getHits, type RecordedHit } from './recorder';
|
package/dist/serve/index.js
CHANGED
|
@@ -42,6 +42,7 @@ const config_1 = require("../config");
|
|
|
42
42
|
const paths_1 = require("./paths");
|
|
43
43
|
const proxy_1 = require("./proxy");
|
|
44
44
|
const spec_utils_1 = require("./spec-utils");
|
|
45
|
+
const viewer_store_1 = require("./viewer-store");
|
|
45
46
|
var middleware_1 = require("./middleware");
|
|
46
47
|
Object.defineProperty(exports, "apiDocs", { enumerable: true, get: function () { return middleware_1.apiDocs; } });
|
|
47
48
|
Object.defineProperty(exports, "apiDocsHandler", { enumerable: true, get: function () { return middleware_1.apiDocsHandler; } });
|
|
@@ -54,6 +55,12 @@ function send(res, status, body, headers = {}) {
|
|
|
54
55
|
res.writeHead(status, headers);
|
|
55
56
|
res.end(body);
|
|
56
57
|
}
|
|
58
|
+
async function readBody(req) {
|
|
59
|
+
const chunks = [];
|
|
60
|
+
for await (const chunk of req)
|
|
61
|
+
chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
|
|
62
|
+
return Buffer.concat(chunks);
|
|
63
|
+
}
|
|
57
64
|
/** Standalone docs HTTP server (CLI: `daxta serve`). Prefer `apiDocs(app)` on the app port. */
|
|
58
65
|
function serveApiDocs(options = {}) {
|
|
59
66
|
const config = (0, config_1.getConfig)();
|
|
@@ -68,9 +75,7 @@ function serveApiDocs(options = {}) {
|
|
|
68
75
|
return;
|
|
69
76
|
}
|
|
70
77
|
if (url.pathname === '/__proxy') {
|
|
71
|
-
const
|
|
72
|
-
for await (const chunk of req)
|
|
73
|
-
chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
|
|
78
|
+
const body = await readBody(req);
|
|
74
79
|
const headers = {};
|
|
75
80
|
for (const [key, value] of Object.entries(req.headers)) {
|
|
76
81
|
if (value == null)
|
|
@@ -84,11 +89,37 @@ function serveApiDocs(options = {}) {
|
|
|
84
89
|
target: url.searchParams.get('target') || '',
|
|
85
90
|
method,
|
|
86
91
|
headers,
|
|
87
|
-
body
|
|
92
|
+
body,
|
|
88
93
|
});
|
|
89
94
|
send(res, proxied.status, proxied.body, proxied.headers);
|
|
90
95
|
return;
|
|
91
96
|
}
|
|
97
|
+
if (url.pathname === `${docsBase}/env.json` || url.pathname === '/env.json') {
|
|
98
|
+
if (method === 'GET' || method === 'HEAD') {
|
|
99
|
+
const store = (0, viewer_store_1.readViewerEnvStore)();
|
|
100
|
+
send(res, 200, `${JSON.stringify(store ?? null)}\n`, {
|
|
101
|
+
'content-type': 'application/json; charset=utf-8',
|
|
102
|
+
'cache-control': 'no-store',
|
|
103
|
+
});
|
|
104
|
+
return;
|
|
105
|
+
}
|
|
106
|
+
if (method === 'PUT' || method === 'POST') {
|
|
107
|
+
try {
|
|
108
|
+
const raw = (await readBody(req)).toString('utf8');
|
|
109
|
+
const saved = (0, viewer_store_1.writeViewerEnvStore)(raw ? JSON.parse(raw) : null);
|
|
110
|
+
send(res, 200, `${JSON.stringify(saved)}\n`, {
|
|
111
|
+
'content-type': 'application/json; charset=utf-8',
|
|
112
|
+
'cache-control': 'no-store',
|
|
113
|
+
});
|
|
114
|
+
}
|
|
115
|
+
catch (error) {
|
|
116
|
+
send(res, 400, `${JSON.stringify({ error: error instanceof Error ? error.message : String(error) })}\n`, {
|
|
117
|
+
'content-type': 'application/json; charset=utf-8',
|
|
118
|
+
});
|
|
119
|
+
}
|
|
120
|
+
return;
|
|
121
|
+
}
|
|
122
|
+
}
|
|
92
123
|
if (url.pathname === '/' || url.pathname === docsBase || url.pathname === `${docsBase}/`) {
|
|
93
124
|
if (!(0, fs_1.existsSync)(htmlPath)) {
|
|
94
125
|
send(res, 404, 'openapi.html not found. Run `daxta build` first.');
|
|
@@ -119,6 +150,7 @@ function serveApiDocs(options = {}) {
|
|
|
119
150
|
server.listen(port, '127.0.0.1', () => {
|
|
120
151
|
console.log(`DAxTA docs: http://127.0.0.1:${port}${docsBase}`);
|
|
121
152
|
console.log(`DAxTA OpenAPI: http://127.0.0.1:${port}${docsBase}/openapi.json`);
|
|
153
|
+
console.log(`DAxTA env: http://127.0.0.1:${port}${docsBase}/env.json`);
|
|
122
154
|
});
|
|
123
155
|
return server;
|
|
124
156
|
}
|
|
@@ -23,7 +23,7 @@ type LooseResponse = {
|
|
|
23
23
|
export type ApiDocsHandler = (req: LooseRequest, res: LooseResponse, next: (error?: unknown) => void) => void | Promise<void>;
|
|
24
24
|
/**
|
|
25
25
|
* Express / Nest handler that serves the DAxTA viewer under `/docs`
|
|
26
|
-
* (or `basePath`)
|
|
26
|
+
* (or `basePath`), Try-it proxy at `/__proxy`, and env store at `{base}/env.json`.
|
|
27
27
|
*/
|
|
28
28
|
export declare function apiDocsHandler(options?: ApiDocsOptions): ApiDocsHandler;
|
|
29
29
|
/**
|
package/dist/serve/middleware.js
CHANGED
|
@@ -6,6 +6,7 @@ const fs_1 = require("fs");
|
|
|
6
6
|
const paths_1 = require("./paths");
|
|
7
7
|
const proxy_1 = require("./proxy");
|
|
8
8
|
const spec_utils_1 = require("./spec-utils");
|
|
9
|
+
const viewer_store_1 = require("./viewer-store");
|
|
9
10
|
function requestPathname(req) {
|
|
10
11
|
const raw = req.originalUrl || req.url || req.path || '/';
|
|
11
12
|
try {
|
|
@@ -56,9 +57,47 @@ function bodyToBuffer(body) {
|
|
|
56
57
|
return Buffer.from(body);
|
|
57
58
|
return Buffer.from(JSON.stringify(body));
|
|
58
59
|
}
|
|
60
|
+
async function readRequestJson(req) {
|
|
61
|
+
if (req.body != null && req.body !== '') {
|
|
62
|
+
if (typeof req.body === 'string') {
|
|
63
|
+
try {
|
|
64
|
+
return JSON.parse(req.body);
|
|
65
|
+
}
|
|
66
|
+
catch {
|
|
67
|
+
return null;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
if (Buffer.isBuffer(req.body)) {
|
|
71
|
+
try {
|
|
72
|
+
return JSON.parse(req.body.toString('utf8'));
|
|
73
|
+
}
|
|
74
|
+
catch {
|
|
75
|
+
return null;
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
return req.body;
|
|
79
|
+
}
|
|
80
|
+
const stream = req;
|
|
81
|
+
if (typeof stream.on !== 'function' || stream.readableEnded)
|
|
82
|
+
return null;
|
|
83
|
+
const chunks = [];
|
|
84
|
+
await new Promise((resolve, reject) => {
|
|
85
|
+
stream.on('data', (chunk) => chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)));
|
|
86
|
+
stream.on('end', () => resolve());
|
|
87
|
+
stream.on('error', reject);
|
|
88
|
+
});
|
|
89
|
+
if (!chunks.length)
|
|
90
|
+
return null;
|
|
91
|
+
try {
|
|
92
|
+
return JSON.parse(Buffer.concat(chunks).toString('utf8'));
|
|
93
|
+
}
|
|
94
|
+
catch {
|
|
95
|
+
return null;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
59
98
|
/**
|
|
60
99
|
* Express / Nest handler that serves the DAxTA viewer under `/docs`
|
|
61
|
-
* (or `basePath`)
|
|
100
|
+
* (or `basePath`), Try-it proxy at `/__proxy`, and env store at `{base}/env.json`.
|
|
62
101
|
*/
|
|
63
102
|
function apiDocsHandler(options = {}) {
|
|
64
103
|
const basePath = (options.basePath ?? (0, paths_1.getDocsBasePath)()).replace(/\/$/, '') || '/docs';
|
|
@@ -84,7 +123,36 @@ function apiDocsHandler(options = {}) {
|
|
|
84
123
|
}
|
|
85
124
|
const isDocsRoot = pathname === basePath || pathname === `${basePath}/`;
|
|
86
125
|
const isDocsSpec = pathname === `${basePath}/openapi.json`;
|
|
87
|
-
|
|
126
|
+
const isDocsEnv = pathname === `${basePath}/env.json`;
|
|
127
|
+
if (!isDocsRoot && !isDocsSpec && !isDocsEnv) {
|
|
128
|
+
next();
|
|
129
|
+
return;
|
|
130
|
+
}
|
|
131
|
+
if (isDocsEnv) {
|
|
132
|
+
if (method === 'GET' || method === 'HEAD') {
|
|
133
|
+
const store = (0, viewer_store_1.readViewerEnvStore)();
|
|
134
|
+
write(res, 200, `${JSON.stringify(store ?? null)}\n`, {
|
|
135
|
+
'content-type': 'application/json; charset=utf-8',
|
|
136
|
+
'cache-control': 'no-store',
|
|
137
|
+
});
|
|
138
|
+
return;
|
|
139
|
+
}
|
|
140
|
+
if (method === 'PUT' || method === 'POST') {
|
|
141
|
+
try {
|
|
142
|
+
const payload = await readRequestJson(req);
|
|
143
|
+
const saved = (0, viewer_store_1.writeViewerEnvStore)(payload);
|
|
144
|
+
write(res, 200, `${JSON.stringify(saved)}\n`, {
|
|
145
|
+
'content-type': 'application/json; charset=utf-8',
|
|
146
|
+
'cache-control': 'no-store',
|
|
147
|
+
});
|
|
148
|
+
}
|
|
149
|
+
catch (error) {
|
|
150
|
+
write(res, 400, `${JSON.stringify({ error: error instanceof Error ? error.message : String(error) })}\n`, {
|
|
151
|
+
'content-type': 'application/json; charset=utf-8',
|
|
152
|
+
});
|
|
153
|
+
}
|
|
154
|
+
return;
|
|
155
|
+
}
|
|
88
156
|
next();
|
|
89
157
|
return;
|
|
90
158
|
}
|
package/dist/serve/paths.d.ts
CHANGED
|
@@ -2,6 +2,8 @@ export declare function getOutDir(): string;
|
|
|
2
2
|
export declare function getHtmlPath(): string;
|
|
3
3
|
export declare function getSpecJsonPath(): string;
|
|
4
4
|
export declare function getHitsJsonPath(): string;
|
|
5
|
+
/** Try-it env/headers — outside outDir so rebuild does not wipe it. */
|
|
6
|
+
export declare function getViewerStorePath(): string;
|
|
5
7
|
export declare function getViewerAssetPath(): string;
|
|
6
8
|
export declare function getFaviconAssetPath(): string;
|
|
7
9
|
export declare function getDocsBasePath(): string;
|
package/dist/serve/paths.js
CHANGED
|
@@ -37,6 +37,7 @@ exports.getOutDir = getOutDir;
|
|
|
37
37
|
exports.getHtmlPath = getHtmlPath;
|
|
38
38
|
exports.getSpecJsonPath = getSpecJsonPath;
|
|
39
39
|
exports.getHitsJsonPath = getHitsJsonPath;
|
|
40
|
+
exports.getViewerStorePath = getViewerStorePath;
|
|
40
41
|
exports.getViewerAssetPath = getViewerAssetPath;
|
|
41
42
|
exports.getFaviconAssetPath = getFaviconAssetPath;
|
|
42
43
|
exports.getDocsBasePath = getDocsBasePath;
|
|
@@ -54,6 +55,10 @@ function getSpecJsonPath() {
|
|
|
54
55
|
function getHitsJsonPath() {
|
|
55
56
|
return path.join(getOutDir(), 'hits.json');
|
|
56
57
|
}
|
|
58
|
+
/** Try-it env/headers — outside outDir so rebuild does not wipe it. */
|
|
59
|
+
function getViewerStorePath() {
|
|
60
|
+
return (0, config_1.getConfig)().viewerStoreFile;
|
|
61
|
+
}
|
|
57
62
|
function getViewerAssetPath() {
|
|
58
63
|
return path.join(__dirname, '..', '..', 'assets', 'viewer.html');
|
|
59
64
|
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
export type ViewerStoreRow = {
|
|
2
|
+
key: string;
|
|
3
|
+
value: string;
|
|
4
|
+
};
|
|
5
|
+
export type ViewerEnvConfig = {
|
|
6
|
+
variables: ViewerStoreRow[];
|
|
7
|
+
headerGroups: Record<string, ViewerStoreRow[]>;
|
|
8
|
+
};
|
|
9
|
+
export type ViewerEnvStore = {
|
|
10
|
+
activeEnv: string;
|
|
11
|
+
activeGroup: string;
|
|
12
|
+
envs: Record<string, ViewerEnvConfig>;
|
|
13
|
+
};
|
|
14
|
+
/** Validate / coerce UI store JSON. Returns null if unusable. */
|
|
15
|
+
export declare function normalizeViewerEnvStore(raw: unknown): ViewerEnvStore | null;
|
|
16
|
+
export declare function readViewerEnvStore(): ViewerEnvStore | null;
|
|
17
|
+
export declare function writeViewerEnvStore(raw: unknown): ViewerEnvStore;
|
|
18
|
+
/**
|
|
19
|
+
* If viewer-store.json is missing, seed it from `envPresets` in daxta.config
|
|
20
|
+
* (local / staging / production baseUrls). Does not overwrite an existing file.
|
|
21
|
+
*/
|
|
22
|
+
export declare function ensureViewerStoreSeeded(): string | null;
|
|
@@ -0,0 +1,135 @@
|
|
|
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.normalizeViewerEnvStore = normalizeViewerEnvStore;
|
|
37
|
+
exports.readViewerEnvStore = readViewerEnvStore;
|
|
38
|
+
exports.writeViewerEnvStore = writeViewerEnvStore;
|
|
39
|
+
exports.ensureViewerStoreSeeded = ensureViewerStoreSeeded;
|
|
40
|
+
const fs_1 = require("fs");
|
|
41
|
+
const path = __importStar(require("path"));
|
|
42
|
+
const config_1 = require("../config");
|
|
43
|
+
const paths_1 = require("./paths");
|
|
44
|
+
function isRow(value) {
|
|
45
|
+
return Boolean(value && typeof value === 'object' && typeof value.key === 'string');
|
|
46
|
+
}
|
|
47
|
+
function normalizeRows(value) {
|
|
48
|
+
if (!Array.isArray(value))
|
|
49
|
+
return [];
|
|
50
|
+
return value.filter(isRow).map((row) => ({ key: String(row.key || ''), value: String(row.value ?? '') }));
|
|
51
|
+
}
|
|
52
|
+
/** Validate / coerce UI store JSON. Returns null if unusable. */
|
|
53
|
+
function normalizeViewerEnvStore(raw) {
|
|
54
|
+
if (!raw || typeof raw !== 'object')
|
|
55
|
+
return null;
|
|
56
|
+
const input = raw;
|
|
57
|
+
const envsIn = input.envs;
|
|
58
|
+
if (!envsIn || typeof envsIn !== 'object')
|
|
59
|
+
return null;
|
|
60
|
+
const envs = {};
|
|
61
|
+
for (const [name, env] of Object.entries(envsIn)) {
|
|
62
|
+
if (!env || typeof env !== 'object')
|
|
63
|
+
continue;
|
|
64
|
+
const envObj = env;
|
|
65
|
+
const headerGroupsIn = envObj.headerGroups;
|
|
66
|
+
const headerGroups = {};
|
|
67
|
+
if (headerGroupsIn && typeof headerGroupsIn === 'object') {
|
|
68
|
+
for (const [group, rows] of Object.entries(headerGroupsIn)) {
|
|
69
|
+
headerGroups[group] = normalizeRows(rows);
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
if (!Object.keys(headerGroups).length) {
|
|
73
|
+
headerGroups.default = [{ key: 'content-type', value: 'application/json' }];
|
|
74
|
+
}
|
|
75
|
+
envs[name] = {
|
|
76
|
+
variables: normalizeRows(envObj.variables),
|
|
77
|
+
headerGroups,
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
if (!Object.keys(envs).length)
|
|
81
|
+
return null;
|
|
82
|
+
const activeEnv = typeof input.activeEnv === 'string' && envs[input.activeEnv] ? input.activeEnv : Object.keys(envs)[0];
|
|
83
|
+
const groups = Object.keys(envs[activeEnv].headerGroups);
|
|
84
|
+
const activeGroup = typeof input.activeGroup === 'string' && groups.includes(input.activeGroup) ? input.activeGroup : groups[0] || 'default';
|
|
85
|
+
return { activeEnv, activeGroup, envs };
|
|
86
|
+
}
|
|
87
|
+
function readViewerEnvStore() {
|
|
88
|
+
const filePath = (0, paths_1.getViewerStorePath)();
|
|
89
|
+
if (!(0, fs_1.existsSync)(filePath))
|
|
90
|
+
return null;
|
|
91
|
+
try {
|
|
92
|
+
return normalizeViewerEnvStore(JSON.parse((0, fs_1.readFileSync)(filePath, 'utf8')));
|
|
93
|
+
}
|
|
94
|
+
catch {
|
|
95
|
+
return null;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
function writeViewerEnvStore(raw) {
|
|
99
|
+
const store = normalizeViewerEnvStore(raw);
|
|
100
|
+
if (!store)
|
|
101
|
+
throw new Error('Invalid viewer env store');
|
|
102
|
+
const filePath = (0, paths_1.getViewerStorePath)();
|
|
103
|
+
(0, fs_1.mkdirSync)(path.dirname(filePath), { recursive: true });
|
|
104
|
+
(0, fs_1.writeFileSync)(filePath, `${JSON.stringify(store, null, 2)}\n`);
|
|
105
|
+
return store;
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* If viewer-store.json is missing, seed it from `envPresets` in daxta.config
|
|
109
|
+
* (local / staging / production baseUrls). Does not overwrite an existing file.
|
|
110
|
+
*/
|
|
111
|
+
function ensureViewerStoreSeeded() {
|
|
112
|
+
const filePath = (0, paths_1.getViewerStorePath)();
|
|
113
|
+
if ((0, fs_1.existsSync)(filePath))
|
|
114
|
+
return null;
|
|
115
|
+
const config = (0, config_1.getConfig)();
|
|
116
|
+
const presets = config.envPresets ?? { local: { baseUrl: config.baseUrl } };
|
|
117
|
+
const envs = {};
|
|
118
|
+
for (const [name, preset] of Object.entries(presets)) {
|
|
119
|
+
const variables = [{ key: 'baseUrl', value: String(preset.baseUrl || config.baseUrl) }];
|
|
120
|
+
for (const [key, value] of Object.entries(preset.variables ?? {})) {
|
|
121
|
+
if (!key || key === 'baseUrl')
|
|
122
|
+
continue;
|
|
123
|
+
variables.push({ key, value: String(value ?? '') });
|
|
124
|
+
}
|
|
125
|
+
envs[name] = {
|
|
126
|
+
variables,
|
|
127
|
+
headerGroups: { default: [{ key: 'content-type', value: 'application/json' }] },
|
|
128
|
+
};
|
|
129
|
+
}
|
|
130
|
+
const names = Object.keys(envs);
|
|
131
|
+
if (!names.length)
|
|
132
|
+
return null;
|
|
133
|
+
writeViewerEnvStore({ activeEnv: names.includes('local') ? 'local' : names[0], activeGroup: 'default', envs });
|
|
134
|
+
return filePath;
|
|
135
|
+
}
|