@writedocs/generator 0.11.1 → 0.13.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.
@@ -1,168 +1,235 @@
1
- // The picture a link to a page shows when it's shared - generated for every
2
- // page that has none of its own: 1200x630, with the site's logo, the page's
3
- // title and description, and a band of the site's primary color.
4
- //
5
- // Two steps, both without a browser or a system font:
6
- // 1. satori lays the card out (flexbox, text wrapping) and draws every
7
- // letter as a path, from the Inter files in src/assets/fonts/. Because
8
- // the letters are paths, the result looks the same on any machine - a
9
- // build server has no fonts installed to rely on.
10
- // 2. resvg (WebAssembly, so no binary per platform) turns that SVG into a
11
- // PNG. Social networks and chat apps don't show SVG previews.
12
- //
13
- // src/pages/og/[...slug].png.ts serves the result at /og/<page>.png;
14
- // [...slug].astro points a page's og:image there when it has no
15
- // `seo.ogImage`.
16
- //
17
- // Plain JavaScript, for scripts/og-image.test.js.
18
- import fs from 'node:fs';
19
- import path from 'node:path';
20
- import { createRequire } from 'node:module';
21
- import { fileURLToPath } from 'node:url';
22
- import { imageSize } from './image-size.js';
23
- import { plainLine } from './meta-description.js';
24
-
25
- export const OG_WIDTH = 1200;
26
- export const OG_HEIGHT = 630;
27
-
28
- /** Whether a page gets a generated picture: it has none of its own (`seo`
29
- * is the site's with the page's merged over it), search engines index it,
30
- * and it's a page - not a link to somewhere else (`url`) - on a site that
31
- * hasn't turned generated pictures off. */
32
- export function wantsGeneratedCard(seo, data = {}, siteSeo = {}) {
33
- // writedocs.json `"seo": { "generatedOgImage": false }` turns them off
34
- // for the whole site - `siteSeo` is the site's own `seo`, since the merged
35
- // one (mergeSeo()) only carries the fields a page can set.
36
- if (siteSeo?.generatedOgImage === false) return false;
37
- return !seo?.ogImage && !seo?.noindex && !data.url;
38
- }
39
-
40
- /** The address of a page's generated picture: /og/<page id>.png. */
41
- export function ogImagePath(pageId) {
42
- return `/og/${pageId}.png`;
43
- }
44
-
45
- // The font files, by the package's own folder when the CLI says where it is
46
- // (WRITEDOCS_PACKAGE_ROOT, src/cli/run-astro.js): inside a build this module
47
- // is part of a bundle somewhere else, and a path from its own location
48
- // would miss them.
49
- const fontsDir = process.env.WRITEDOCS_PACKAGE_ROOT
50
- ? path.join(process.env.WRITEDOCS_PACKAGE_ROOT, 'src', 'assets', 'fonts')
51
- : path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'assets', 'fonts');
52
- const fontFile = (name) => fs.readFileSync(path.join(fontsDir, name));
53
-
54
- let fonts = null;
55
- /** Inter, regular and semibold. The extended-Latin files go under a name of
56
- * their own, second in the card's font-family: satori takes a letter from
57
- * the first family that has it, and only one file per family and weight. */
58
- function loadFonts() {
59
- fonts ??= [
60
- { name: 'Inter', weight: 400, style: 'normal', data: fontFile('inter-latin-400-normal.woff') },
61
- { name: 'Inter', weight: 600, style: 'normal', data: fontFile('inter-latin-600-normal.woff') },
62
- { name: 'Inter Ext', weight: 400, style: 'normal', data: fontFile('inter-latin-ext-400-normal.woff') },
63
- { name: 'Inter Ext', weight: 600, style: 'normal', data: fontFile('inter-latin-ext-600-normal.woff') },
64
- ];
65
- return fonts;
66
- }
67
-
68
- // The two renderers are loaded when the first card is drawn, not with this
69
- // module: every page imports it for wantsGeneratedCard(), and most builds of
70
- // a page never draw anything.
71
- let renderer = null;
72
- function loadRenderer() {
73
- renderer ??= (async () => {
74
- const [{ default: satori }, resvg] = await Promise.all([import('satori'), import('@resvg/resvg-wasm')]);
75
- // Once per process: a second initWasm() throws.
76
- await resvg.initWasm(fs.readFileSync(createRequire(import.meta.url).resolve('@resvg/resvg-wasm/index_bg.wasm')));
77
- return { satori, Resvg: resvg.Resvg };
78
- })();
79
- return renderer;
80
- }
81
-
82
- const MIME = { '.svg': 'image/svg+xml', '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.gif': 'image/gif', '.webp': 'image/webp' };
83
-
84
- /** The logo file as something the card can draw: a data URI and the size to
85
- * draw it at - `height` tall, as wide as its proportions say, and no wider
86
- * than `maxWidth`. Null for a file that can't be read or measured. */
87
- export function logoForCard(file, height = 64, maxWidth = 520) {
88
- if (!file) return null;
89
- const type = MIME[path.extname(file).toLowerCase()];
90
- const size = type && imageSize(file);
91
- if (!size) return null;
92
- let width = (size.width / size.height) * height;
93
- let drawn = height;
94
- if (width > maxWidth) {
95
- drawn = (maxWidth / width) * height;
96
- width = maxWidth;
97
- }
98
- try {
99
- return { src: `data:${type};base64,${fs.readFileSync(file).toString('base64')}`, width: Math.round(width), height: Math.round(drawn) };
100
- } catch {
101
- return null;
102
- }
103
- }
104
-
105
- const cut = (value, max) => (value.length > max ? `${value.slice(0, max - 1).replace(/\s+\S*$/, '')}…` : value);
106
- const el = (type, style, children, props = {}) => ({ type, props: { style, children, ...props } });
107
-
108
- /** The card as satori's element tree. A long title gets smaller letters
109
- * rather than being cut short; the description is clamped to three lines. */
110
- export function ogCard({ title, description, siteName, primary = '#0029F5', logo = null }) {
111
- const heading = cut(plainLine(title), 110);
112
- const text = description ? cut(plainLine(description), 200) : '';
113
- const titleSize = heading.length > 70 ? 52 : heading.length > 40 ? 62 : 72;
114
- return el(
115
- 'div',
116
- { width: OG_WIDTH, height: OG_HEIGHT, display: 'flex', flexDirection: 'column', backgroundColor: '#ffffff', fontFamily: 'Inter, Inter Ext', color: '#18191d' },
117
- [
118
- el(
119
- 'div',
120
- { display: 'flex', flexDirection: 'column', flexGrow: 1, padding: '72px 80px 0 80px' },
121
- [
122
- // The logo - or, for a site without one (or with one on another
123
- // server, which a build shouldn't wait for), its name.
124
- logo
125
- ? el('img', { width: logo.width, height: logo.height }, undefined, { src: logo.src, width: logo.width, height: logo.height })
126
- : el('div', { display: 'flex', fontSize: 34, fontWeight: 600, color: primary }, siteName),
127
- el(
128
- 'div',
129
- { display: 'flex', flexDirection: 'column', flexGrow: 1, justifyContent: 'center' },
130
- [
131
- el('div', { display: 'flex', fontSize: titleSize, fontWeight: 600, lineHeight: 1.12, letterSpacing: '-0.02em' }, heading),
132
- text ? el('div', { display: 'flex', marginTop: 28, fontSize: 30, lineHeight: 1.4, color: '#404045', lineClamp: 3 }, text) : null,
133
- ].filter(Boolean)
134
- ),
135
- ]
136
- ),
137
- el(
138
- 'div',
139
- { display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '0 80px 44px 80px', fontSize: 24, color: '#6b6b76' },
140
- // With a logo, the name says whose docs these are; without one the
141
- // name is already at the top.
142
- [el('div', { display: 'flex' }, logo ? siteName : '')]
143
- ),
144
- el('div', { display: 'flex', width: OG_WIDTH, height: 14, backgroundColor: primary }, undefined),
145
- ]
146
- );
147
- }
148
-
149
- /** The card as SVG. */
150
- export async function ogImageSvg(options) {
151
- const { satori } = await loadRenderer();
152
- return satori(ogCard(options), { width: OG_WIDTH, height: OG_HEIGHT, fonts: loadFonts() });
153
- }
154
-
155
- /** The card as a PNG: a Buffer, 1200x630. */
156
- export async function ogImagePng(options) {
157
- const svg = await ogImageSvg(options);
158
- const { Resvg } = await loadRenderer();
159
- const resvg = new Resvg(svg, { fitTo: { mode: 'width', value: OG_WIDTH } });
160
- const rendered = resvg.render();
161
- const png = Buffer.from(rendered.asPng());
162
- // Both live in the WebAssembly memory, which nothing collects: freeing
163
- // only the image left the parsed SVG of every card there until the build
164
- // ended, and past ~800 cards each one took three times as long.
165
- rendered.free?.();
166
- resvg.free?.();
167
- return png;
168
- }
1
+ // The picture a link to a page shows when it's shared - generated for every
2
+ // page that has none of its own: 1200x630, with the site's logo, the page's
3
+ // title and description, and a band of the site's primary color.
4
+ //
5
+ // Two steps, both without a browser or a system font:
6
+ // 1. satori lays the card out (flexbox, text wrapping) and draws every
7
+ // letter as a path, from the Inter files in src/assets/fonts/. Because
8
+ // the letters are paths, the result looks the same on any machine - a
9
+ // build server has no fonts installed to rely on.
10
+ // 2. resvg (WebAssembly, so no binary per platform) turns that SVG into
11
+ // pixels, and encodePng() below writes them as a PNG with Node's own
12
+ // zlib. Social networks and chat apps don't show SVG previews.
13
+ //
14
+ // src/pages/og/[...slug].png.ts serves the result at /og/<page>.png;
15
+ // [...slug].astro points a page's og:image there when it has no
16
+ // `seo.ogImage`.
17
+ //
18
+ // Plain JavaScript, for scripts/og-image.test.js.
19
+ import fs from 'node:fs';
20
+ import path from 'node:path';
21
+ import zlib from 'node:zlib';
22
+ import { createRequire } from 'node:module';
23
+ import { fileURLToPath } from 'node:url';
24
+ import { imageSize } from './image-size.js';
25
+ import { plainLine } from './meta-description.js';
26
+
27
+ export const OG_WIDTH = 1200;
28
+ export const OG_HEIGHT = 630;
29
+
30
+ /** Whether a page gets a generated picture: it has none of its own (`seo`
31
+ * is the site's with the page's merged over it), search engines index it,
32
+ * and it's a page - not a link to somewhere else (`url`) - on a site that
33
+ * hasn't turned generated pictures off. */
34
+ export function wantsGeneratedCard(seo, data = {}, siteSeo = {}) {
35
+ // writedocs.json `"seo": { "generatedOgImage": false }` turns them off
36
+ // for the whole site - `siteSeo` is the site's own `seo`, since the merged
37
+ // one (mergeSeo()) only carries the fields a page can set.
38
+ if (siteSeo?.generatedOgImage === false) return false;
39
+ return !seo?.ogImage && !seo?.noindex && !data.url;
40
+ }
41
+
42
+ /** The address of a page's generated picture: /og/<page id>.png. */
43
+ export function ogImagePath(pageId) {
44
+ return `/og/${pageId}.png`;
45
+ }
46
+
47
+ // The font files, by the package's own folder when the CLI says where it is
48
+ // (WRITEDOCS_PACKAGE_ROOT, src/cli/run-astro.js): inside a build this module
49
+ // is part of a bundle somewhere else, and a path from its own location
50
+ // would miss them.
51
+ const fontsDir = process.env.WRITEDOCS_PACKAGE_ROOT
52
+ ? path.join(process.env.WRITEDOCS_PACKAGE_ROOT, 'src', 'assets', 'fonts')
53
+ : path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'assets', 'fonts');
54
+ const fontFile = (name) => fs.readFileSync(path.join(fontsDir, name));
55
+
56
+ let fonts = null;
57
+ /** Inter, regular and semibold. The extended-Latin files go under a name of
58
+ * their own, second in the card's font-family: satori takes a letter from
59
+ * the first family that has it, and only one file per family and weight. */
60
+ function loadFonts() {
61
+ fonts ??= [
62
+ { name: 'Inter', weight: 400, style: 'normal', data: fontFile('inter-latin-400-normal.woff') },
63
+ { name: 'Inter', weight: 600, style: 'normal', data: fontFile('inter-latin-600-normal.woff') },
64
+ { name: 'Inter Ext', weight: 400, style: 'normal', data: fontFile('inter-latin-ext-400-normal.woff') },
65
+ { name: 'Inter Ext', weight: 600, style: 'normal', data: fontFile('inter-latin-ext-600-normal.woff') },
66
+ ];
67
+ return fonts;
68
+ }
69
+
70
+ // The two renderers are loaded when the first card is drawn, not with this
71
+ // module: every page imports it for wantsGeneratedCard(), and most builds of
72
+ // a page never draw anything.
73
+ let renderer = null;
74
+ function loadRenderer() {
75
+ renderer ??= (async () => {
76
+ const [{ default: satori }, resvg] = await Promise.all([import('satori'), import('@resvg/resvg-wasm')]);
77
+ // Once per process: a second initWasm() throws.
78
+ await resvg.initWasm(fs.readFileSync(createRequire(import.meta.url).resolve('@resvg/resvg-wasm/index_bg.wasm')));
79
+ return { satori, Resvg: resvg.Resvg };
80
+ })();
81
+ return renderer;
82
+ }
83
+
84
+ const MIME = { '.svg': 'image/svg+xml', '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.gif': 'image/gif', '.webp': 'image/webp' };
85
+
86
+ /** The logo file as something the card can draw: a data URI and the size to
87
+ * draw it at - `height` tall, as wide as its proportions say, and no wider
88
+ * than `maxWidth`. Null for a file that can't be read or measured. */
89
+ export function logoForCard(file, height = 64, maxWidth = 520) {
90
+ if (!file) return null;
91
+ const type = MIME[path.extname(file).toLowerCase()];
92
+ const size = type && imageSize(file);
93
+ if (!size) return null;
94
+ let width = (size.width / size.height) * height;
95
+ let drawn = height;
96
+ if (width > maxWidth) {
97
+ drawn = (maxWidth / width) * height;
98
+ width = maxWidth;
99
+ }
100
+ try {
101
+ return { src: `data:${type};base64,${fs.readFileSync(file).toString('base64')}`, width: Math.round(width), height: Math.round(drawn) };
102
+ } catch {
103
+ return null;
104
+ }
105
+ }
106
+
107
+ const cut = (value, max) => (value.length > max ? `${value.slice(0, max - 1).replace(/\s+\S*$/, '')}…` : value);
108
+ const el = (type, style, children, props = {}) => ({ type, props: { style, children, ...props } });
109
+
110
+ /** The card as satori's element tree. A long title gets smaller letters
111
+ * rather than being cut short; the description is clamped to three lines. */
112
+ export function ogCard({ title, description, siteName, primary = '#0029F5', logo = null }) {
113
+ const heading = cut(plainLine(title), 110);
114
+ const text = description ? cut(plainLine(description), 200) : '';
115
+ const titleSize = heading.length > 70 ? 52 : heading.length > 40 ? 62 : 72;
116
+ return el(
117
+ 'div',
118
+ { width: OG_WIDTH, height: OG_HEIGHT, display: 'flex', flexDirection: 'column', backgroundColor: '#ffffff', fontFamily: 'Inter, Inter Ext', color: '#18191d' },
119
+ [
120
+ el(
121
+ 'div',
122
+ { display: 'flex', flexDirection: 'column', flexGrow: 1, padding: '72px 80px 0 80px' },
123
+ [
124
+ // The logo - or, for a site without one (or with one on another
125
+ // server, which a build shouldn't wait for), its name.
126
+ logo
127
+ ? el('img', { width: logo.width, height: logo.height }, undefined, { src: logo.src, width: logo.width, height: logo.height })
128
+ : el('div', { display: 'flex', fontSize: 34, fontWeight: 600, color: primary }, siteName),
129
+ el(
130
+ 'div',
131
+ { display: 'flex', flexDirection: 'column', flexGrow: 1, justifyContent: 'center' },
132
+ [
133
+ el('div', { display: 'flex', fontSize: titleSize, fontWeight: 600, lineHeight: 1.12, letterSpacing: '-0.02em' }, heading),
134
+ text ? el('div', { display: 'flex', marginTop: 28, fontSize: 30, lineHeight: 1.4, color: '#404045', lineClamp: 3 }, text) : null,
135
+ ].filter(Boolean)
136
+ ),
137
+ ]
138
+ ),
139
+ el(
140
+ 'div',
141
+ { display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '0 80px 44px 80px', fontSize: 24, color: '#6b6b76' },
142
+ // With a logo, the name says whose docs these are; without one the
143
+ // name is already at the top.
144
+ [el('div', { display: 'flex' }, logo ? siteName : '')]
145
+ ),
146
+ el('div', { display: 'flex', width: OG_WIDTH, height: 14, backgroundColor: primary }, undefined),
147
+ ]
148
+ );
149
+ }
150
+
151
+ /** The card as SVG. */
152
+ export async function ogImageSvg(options) {
153
+ const { satori } = await loadRenderer();
154
+ return satori(ogCard(options), { width: OG_WIDTH, height: OG_HEIGHT, fonts: loadFonts() });
155
+ }
156
+
157
+ // The PNG is written here, not by resvg's own asPng(): that one compresses
158
+ // in WebAssembly, and it was three quarters of the time a card took (12-25
159
+ // ms of it, against ~1.6 ms for Node's zlib, which is native). The pixels
160
+ // are the same - only the compressed bytes differ.
161
+ //
162
+ // The CRC of each chunk comes from this table rather than zlib.crc32(),
163
+ // which only exists from Node 22.2 / 20.15 - nothing here raises the Node
164
+ // version `engines` asks for.
165
+ const CRC_TABLE = new Int32Array(256);
166
+ for (let n = 0; n < 256; n++) {
167
+ let c = n;
168
+ for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
169
+ CRC_TABLE[n] = c;
170
+ }
171
+ function crc32(bytes) {
172
+ let c = -1;
173
+ for (let i = 0; i < bytes.length; i++) c = CRC_TABLE[(c ^ bytes[i]) & 0xff] ^ (c >>> 8);
174
+ return (c ^ -1) >>> 0;
175
+ }
176
+ function pngChunk(type, data) {
177
+ const chunk = Buffer.alloc(data.length + 12);
178
+ chunk.writeUInt32BE(data.length, 0);
179
+ chunk.write(type, 4, 'latin1');
180
+ data.copy(chunk, 8);
181
+ chunk.writeUInt32BE(crc32(chunk.subarray(4, 8 + data.length)), 8 + data.length);
182
+ return chunk;
183
+ }
184
+
185
+ /** RGBA pixels (8 bits each, `width * height * 4` bytes) as a PNG: RGBA,
186
+ * no interlacing, filter 0 on every row, deflated at level 3 - level 6
187
+ * makes a file a third smaller but takes four times as long, and a card is
188
+ * ~30 KB either way. */
189
+ export function encodePng(width, height, rgba) {
190
+ const header = Buffer.alloc(13);
191
+ header.writeUInt32BE(width, 0);
192
+ header.writeUInt32BE(height, 4);
193
+ header[8] = 8; // bits per channel
194
+ header[9] = 6; // RGBA
195
+ const stride = width * 4;
196
+ const rows = Buffer.alloc((stride + 1) * height);
197
+ for (let y = 0; y < height; y++) {
198
+ // Each row starts with its filter type: 0, none.
199
+ rows.set(rgba.subarray(y * stride, (y + 1) * stride), y * (stride + 1) + 1);
200
+ }
201
+ return Buffer.concat([
202
+ Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),
203
+ pngChunk('IHDR', header),
204
+ pngChunk('IDAT', zlib.deflateSync(rows, { level: 3 })),
205
+ pngChunk('IEND', Buffer.alloc(0)),
206
+ ]);
207
+ }
208
+
209
+ /** Whether every pixel is opaque. resvg's pixels are premultiplied by their
210
+ * alpha, and a PNG's aren't: only for opaque pixels are they the same
211
+ * numbers. A card always is - its background is white from edge to edge. */
212
+ function opaque(rgba) {
213
+ for (let i = 3; i < rgba.length; i += 4) if (rgba[i] !== 255) return false;
214
+ return true;
215
+ }
216
+
217
+ /** The card as a PNG: a Buffer, 1200x630. `resvgEncoder` writes it with
218
+ * resvg's own encoder instead, as before encodePng() - for the tests, which
219
+ * check that both give the same picture. */
220
+ export async function ogImagePng(options, { resvgEncoder = false } = {}) {
221
+ const svg = await ogImageSvg(options);
222
+ const { Resvg } = await loadRenderer();
223
+ const resvg = new Resvg(svg, { fitTo: { mode: 'width', value: OG_WIDTH } });
224
+ const rendered = resvg.render();
225
+ const pixels = resvgEncoder ? null : rendered.pixels;
226
+ // A picture with any see-through pixel (which a card never has) goes
227
+ // through resvg's encoder, which converts them.
228
+ const png = pixels && opaque(pixels) ? encodePng(rendered.width, rendered.height, pixels) : Buffer.from(rendered.asPng());
229
+ // Both live in the WebAssembly memory, which nothing collects: freeing
230
+ // only the image left the parsed SVG of every card there until the build
231
+ // ended, and past ~800 cards each one took three times as long.
232
+ rendered.free?.();
233
+ resvg.free?.();
234
+ return png;
235
+ }
@@ -0,0 +1,80 @@
1
+ // `writedocs dev`: what the preview knows about the OpenAPI specs between one
2
+ // regeneration and the next - the files to watch, and a spec that stopped
3
+ // parsing. Kept in a file in the project's temp folder, because three places
4
+ // need it: cli/dev.js writes it after the first generateApiPages(),
5
+ // lib/openapi-reload-integration.js after each regeneration (and reads it when
6
+ // the preview restarts), and every page reads it when it renders.
7
+ //
8
+ // A spec that doesn't parse: generateApiPages() writes nothing, so the API
9
+ // pages stay those of the last version that parsed, and every page throws
10
+ // the error instead of rendering (throwIfOpenApiProblem(), called from
11
+ // src/pages/[...slug].astro) - Astro shows it as it shows a broken page or a
12
+ // broken writedocs.json, until the spec parses again.
13
+ //
14
+ // Only `writedocs dev` reads or writes it: a build never looks.
15
+ //
16
+ // Plain JavaScript: the integration and cli/dev.js run under plain Node.
17
+ import fs from 'node:fs';
18
+ import path from 'node:path';
19
+ import { writedocsTempDir } from './writedocs-temp-dir.js';
20
+
21
+ const stateFile = (contentDir) => path.join(writedocsTempDir(contentDir), 'dev-openapi.json');
22
+
23
+ /** `{ sources: [absolute paths], problem: null | specProblem() }` - empty
24
+ * when nothing was written yet. */
25
+ export function readDevOpenApiState(contentDir) {
26
+ try {
27
+ const state = JSON.parse(fs.readFileSync(stateFile(contentDir), 'utf-8'));
28
+ return { sources: Array.isArray(state.sources) ? state.sources : [], problem: state.problem ?? null };
29
+ } catch {
30
+ return { sources: [], problem: null };
31
+ }
32
+ }
33
+
34
+ export function writeDevOpenApiState(contentDir, { sources, problem }) {
35
+ const file = stateFile(contentDir);
36
+ fs.mkdirSync(path.dirname(file), { recursive: true });
37
+ fs.writeFileSync(file, JSON.stringify({ sources, problem: problem ?? null }, null, 2));
38
+ }
39
+
40
+ /** A generateApiPages() failure, for the terminal and the page: the file it
41
+ * is about (absolute, or null), where in it ("openapi.yaml:12:5", relative
42
+ * to the project), and the message without the parser's "Error parsing
43
+ * <file>:" prefix and code frame. */
44
+ export function specProblem(err, contentDir) {
45
+ const firstLine = String(err?.message ?? err).split('\n')[0];
46
+ let message = firstLine.replace(/^\[writedocs\]\s*/, '');
47
+ let file = typeof err?.source === 'string' && err.source ? path.resolve(err.source) : null;
48
+ let line = null;
49
+ let column = null;
50
+ // swagger-parser: "Error parsing <file>: <reason> (12:5)" and "Error
51
+ // opening file <file>: ENOENT: ..." - the file is err.source.
52
+ const parsing = message.match(/^Error (?:parsing|opening file) .+?: (.*)$/);
53
+ if (parsing) message = parsing[1];
54
+ if (err?.ioErrorCode === 'ENOENT' || /^ENOENT\b/.test(message)) message = "This file doesn't exist - a $ref points to it.";
55
+ const pos = message.match(/\s*\((\d+):(\d+)\)\s*$/);
56
+ if (pos) {
57
+ line = Number(pos[1]);
58
+ column = Number(pos[2]);
59
+ message = message.slice(0, pos.index);
60
+ }
61
+ // Errors about writedocs.json's openapi groups (a missing spec, two
62
+ // groups on one path) name no spec file - they're about writedocs.json.
63
+ if (!file && /writedocs\.json/.test(message)) file = path.join(contentDir, 'writedocs.json');
64
+ const rel = file ? path.relative(contentDir, file).split(path.sep).join('/') : null;
65
+ const where = rel ? `${rel}${line ? `:${line}${column ? `:${column}` : ''}` : ''}` : null;
66
+ return { file, line, column, where, message: message.trim() || 'The OpenAPI spec could not be read.' };
67
+ }
68
+
69
+ /** The error a page throws while a spec doesn't parse - nothing otherwise,
70
+ * and nothing outside `writedocs dev`. */
71
+ export function throwIfOpenApiProblem(contentDir) {
72
+ if (process.env.WRITEDOCS_COMMAND !== 'dev') return;
73
+ const { problem } = readDevOpenApiState(contentDir);
74
+ if (!problem) return;
75
+ const err = new Error(problem.where ? `${problem.where} ${problem.message}` : problem.message);
76
+ err.name = 'OpenAPIError';
77
+ err.hint = "The OpenAPI spec can't be read, so the API pages show the last version that could. Fix the spec and the preview reloads by itself.";
78
+ if (problem.file) err.loc = { file: problem.file, line: problem.line ?? undefined, column: problem.column ?? undefined };
79
+ throw err;
80
+ }