@meritt/yamb-render-xml 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,20 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2026 Alexey Simonenko, alexey@simonenko.dev, https://simonenko.xyz
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of
6
+ this software and associated documentation files (the "Software"), to deal in
7
+ the Software without restriction, including without limitation the rights to
8
+ use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
9
+ the Software, and to permit persons to whom the Software is furnished to do so,
10
+ subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
17
+ FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
18
+ COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
19
+ IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
20
+ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/package.json CHANGED
@@ -1,6 +1,74 @@
1
1
  {
2
2
  "name": "@meritt/yamb-render-xml",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0",
4
+ "description": "RSS 2.0 and Atom 1.0 renderers for Yamb post collections",
5
+ "keywords": [
6
+ "atom",
7
+ "blog",
8
+ "feed",
9
+ "renderer",
10
+ "rss",
11
+ "xml",
12
+ "yamb"
13
+ ],
14
+ "license": "MIT",
15
+ "author": {
16
+ "name": "Alexey Simonenko",
17
+ "email": "alexey@simonenko.dev",
18
+ "url": "https://simonenko.xyz"
19
+ },
20
+ "repository": {
21
+ "type": "git",
22
+ "url": "git+https://github.com/yamb/render-xml.git"
23
+ },
24
+ "files": [
25
+ "src"
26
+ ],
27
+ "type": "module",
28
+ "sideEffects": false,
29
+ "imports": {
30
+ "#core": "yamb",
31
+ "#core/*": "yamb/*"
32
+ },
33
+ "exports": {
34
+ ".": "./src/index.js",
35
+ "./errors": "./src/errors/index.js",
36
+ "./package.json": "./package.json"
37
+ },
38
+ "publishConfig": {
39
+ "access": "public"
40
+ },
41
+ "dependencies": {
42
+ "zod": "^4.6.7"
43
+ },
44
+ "devDependencies": {
45
+ "@meritt/yamb-markdown": "0.1.0",
46
+ "@meritt/yamb-microtypo": "0.1.0",
47
+ "@meritt/yamb-render-html": "0.1.0",
48
+ "@meritt/yamb-render-json": "0.1.0",
49
+ "@xmldom/xmldom": "^0.9.12",
50
+ "oxfmt": "0.80.0",
51
+ "oxlint": "1.95.0",
52
+ "yamb": "1.0.0"
53
+ },
54
+ "peerDependencies": {
55
+ "yamb": "^1.0.0"
56
+ },
57
+ "devEngines": {
58
+ "runtime": {
59
+ "name": "node",
60
+ "version": "26.13.1",
61
+ "onFail": "download"
62
+ }
63
+ },
64
+ "engines": {
65
+ "node": ">=26.13.0"
66
+ },
67
+ "scripts": {
68
+ "lint": "oxlint",
69
+ "format": "oxfmt",
70
+ "format:check": "oxfmt --check",
71
+ "test": "node scripts/run-tests.mjs",
72
+ "test:watch": "node --test --watch 'test/**/*.test.js'"
73
+ }
6
74
  }
package/readme.md ADDED
@@ -0,0 +1,78 @@
1
+ # @meritt/yamb-render-xml
2
+
3
+ [![npm version][npm-image]][npm-url] [![Build status][github-actions-image]][github-actions-url] [![Coverage status][coveralls-image]][coveralls-url] [![Dependency status][libraries-image]][libraries-url]
4
+
5
+ Render [Yamb](https://github.com/yamb/yamb) post collections as RSS 2.0 and Atom 1.0 XML.
6
+
7
+ For GitHub Packages, route the `@yamb` scope to `https://npm.pkg.github.com` and install `@yamb/render-xml`.
8
+
9
+ ## Quick start
10
+
11
+ Requires Node.js 26.13 or later and `yamb`. Direct rendering needs no storage.
12
+
13
+ ```bash
14
+ pnpm add yamb @meritt/yamb-render-xml
15
+ ```
16
+
17
+ ```js
18
+ import { atom, rss } from '@meritt/yamb-render-xml';
19
+
20
+ const source = {
21
+ id: 'hello',
22
+ uri: '2026/11/hello',
23
+ title: 'Hello',
24
+ text: 'Hello, world.',
25
+ status: 'published',
26
+ publishedAt: '2026-11-12T09:00:00Z',
27
+ updatedAt: '2026-11-12T09:00:00Z'
28
+ };
29
+
30
+ const ctx = {
31
+ base: new URL('https://example.com/blog'),
32
+ timeZone: 'UTC'
33
+ };
34
+
35
+ const news = rss({
36
+ title: 'My blog',
37
+ description: 'Latest articles',
38
+ language: 'en',
39
+ feed: 'https://example.com/blog/rss.xml'
40
+ });
41
+
42
+ const updates = atom({
43
+ title: 'My blog',
44
+ feed: 'https://example.com/blog/atom.xml',
45
+ author: {
46
+ name: 'Editor'
47
+ }
48
+ });
49
+
50
+ const input = {
51
+ posts: [source]
52
+ };
53
+
54
+ console.log(await news.collection(input, ctx));
55
+ console.log(await updates.collection(input, ctx));
56
+ ```
57
+
58
+ ## Reference
59
+
60
+ - [RSS and Atom configuration](api/readme.md#configuration), [output mapping](api/readme.md#output-mapping) and [Markdown preparation](api/readme.md#content-and-preparation)
61
+ - [Yamb core reference](https://github.com/yamb/yamb#reference) for renderer registration and context
62
+
63
+ ## Author
64
+
65
+ [Alexey Simonenko](https://simonenko.xyz)
66
+
67
+ ## License
68
+
69
+ MIT. See `LICENSE`.
70
+
71
+ [npm-image]: https://img.shields.io/npm/v/@meritt/yamb-render-xml?style=flat
72
+ [npm-url]: https://www.npmjs.com/package/@meritt/yamb-render-xml
73
+ [github-actions-image]: https://github.com/yamb/render-xml/actions/workflows/ci.yml/badge.svg
74
+ [github-actions-url]: https://github.com/yamb/render-xml/actions/workflows/ci.yml
75
+ [coveralls-image]: https://coveralls.io/repos/github/yamb/render-xml/badge.svg
76
+ [coveralls-url]: https://coveralls.io/github/yamb/render-xml
77
+ [libraries-image]: https://img.shields.io/librariesio/release/npm/%40meritt%2Fyamb-render-xml?style=flat
78
+ [libraries-url]: https://libraries.io/npm/%40meritt%2Fyamb-render-xml
@@ -0,0 +1,148 @@
1
+ import { z } from 'zod';
2
+
3
+ import { AsyncIteratorHelper } from '#core/async-iterator';
4
+ import { RendererFailedError, RendererInputError } from '#core/errors';
5
+ import { url } from '#core/url';
6
+
7
+ import pkg from '../../package.json' with { type: 'json' };
8
+ import { content, full } from '../content.js';
9
+ import { XmlRendererConfigError } from '../errors/index.js';
10
+ import { AtomConfigSchema } from '../schemas/zod.js';
11
+ import { author, element, link, writer } from '../xml.js';
12
+
13
+ const precision = { fractionalSecondDigits: 9 };
14
+
15
+ export class AtomRenderer {
16
+ #config;
17
+
18
+ constructor(config) {
19
+ const result = AtomConfigSchema.safeParse(config);
20
+
21
+ if (!result.success) {
22
+ throw new XmlRendererConfigError(`invalid config: ${z.prettifyError(result.error)}`, {
23
+ details: { issues: result.error.issues }
24
+ });
25
+ }
26
+
27
+ this.name = 'atom';
28
+ this.version = pkg.version;
29
+ this.#config = result.data;
30
+ }
31
+
32
+ async collection(input, ctx) {
33
+ try {
34
+ ctx.signal?.throwIfAborted();
35
+ const posts = input?.posts;
36
+
37
+ if (
38
+ !posts ||
39
+ (typeof posts[Symbol.asyncIterator] !== 'function' &&
40
+ typeof posts[Symbol.iterator] !== 'function')
41
+ ) {
42
+ throw new RendererInputError('input.posts must be iterable or async iterable');
43
+ }
44
+
45
+ const config = this.#config;
46
+ const base = url('./', ctx.base);
47
+ const out = writer(config.bytes, this.name);
48
+ let { updated } = config;
49
+
50
+ out.raw('<?xml version="1.0" encoding="UTF-8"?>\n<feed xmlns="http://www.w3.org/2005/Atom"');
51
+
52
+ if (config.language !== undefined) {
53
+ out.raw(' xml:lang="');
54
+ out.text(config.language, true);
55
+ out.raw('"');
56
+ }
57
+
58
+ out.raw('>\n');
59
+
60
+ element(out, 'title', config.title, ' type="text"');
61
+ element(out, 'id', new URL(config.id ?? config.feed).href);
62
+ link(out, 'self', 'application/atom+xml', new URL(config.feed).href);
63
+ link(out, 'alternate', 'text/html', config.link ?? ctx.base.href);
64
+
65
+ if (config.description !== undefined) {
66
+ element(out, 'subtitle', config.description, ' type="text"');
67
+ }
68
+
69
+ if (config.author) {
70
+ author(out, config.author, base);
71
+ }
72
+
73
+ const { position } = out;
74
+ const ids = new Set();
75
+
76
+ if (config.limit > 0) {
77
+ const iterator = AsyncIteratorHelper.from(posts, { signal: ctx.signal });
78
+
79
+ for await (const value of iterator.take(config.limit)) {
80
+ ctx.signal?.throwIfAborted();
81
+ const { post, prepared, documentURL } = await content(value, config, ctx);
82
+
83
+ if (ids.has(post.id)) {
84
+ throw new RendererInputError('duplicate atom post id');
85
+ }
86
+
87
+ ids.add(post.id);
88
+
89
+ if (!config.author && !post.author) {
90
+ throw new RendererInputError('atom requires a feed author or an author on every entry');
91
+ }
92
+
93
+ if (Temporal.Instant.compare(post.updatedAt, updated) > 0) {
94
+ updated = post.updatedAt;
95
+ }
96
+
97
+ out.raw('<entry>\n');
98
+ element(
99
+ out,
100
+ 'id',
101
+ `${new URL(config.id ?? config.feed).href}#post/${encodeURIComponent(post.id)}`
102
+ );
103
+ element(out, 'title', prepared.title, ' type="text"');
104
+ link(out, 'alternate', 'text/html', documentURL);
105
+ element(out, 'published', post.publishedAt.toString(precision));
106
+ element(out, 'updated', post.updatedAt.toString(precision));
107
+
108
+ if (post.author) {
109
+ author(out, post.author, base);
110
+ }
111
+
112
+ for (const tag of post.tags ?? []) {
113
+ out.raw('<category term="');
114
+ out.text(tag, true);
115
+ out.raw('"/>\n');
116
+ }
117
+
118
+ if (prepared.preview !== undefined) {
119
+ element(out, 'summary', prepared.preview.feedHtml, ' type="html"');
120
+ }
121
+
122
+ element(out, 'content', full(prepared), ' type="html"');
123
+ out.raw('</entry>\n');
124
+ }
125
+ }
126
+
127
+ if (ids.size === 0 && !config.author) {
128
+ throw new RendererInputError('empty atom feed requires an author');
129
+ }
130
+
131
+ out.raw(`<updated>${updated.toString(precision)}</updated>\n`, position);
132
+ out.raw('</feed>');
133
+ ctx.signal?.throwIfAborted();
134
+
135
+ return out.end();
136
+ } catch (error) {
137
+ if (ctx.signal?.aborted && Object.is(error, ctx.signal.reason)) {
138
+ throw error;
139
+ }
140
+
141
+ if (error?.name === 'AbortError' || error?.code?.startsWith?.('YAMB_')) {
142
+ throw error;
143
+ }
144
+
145
+ throw new RendererFailedError('atom generation failed', { cause: error });
146
+ }
147
+ }
148
+ }
@@ -0,0 +1,24 @@
1
+ import { element } from '../xml.js';
2
+
3
+ export function buildChannelHeader(out, config, ctx, lastBuildDate) {
4
+ out.raw('<?xml version="1.0" encoding="UTF-8"?>\n');
5
+ out.raw(
6
+ '<rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">\n <channel>\n'
7
+ );
8
+ element(out, 'title', config.title);
9
+ element(out, 'link', config.link ?? ctx.base.href);
10
+ element(out, 'description', config.description);
11
+ element(out, 'language', config.language);
12
+
13
+ if (config.copyright !== undefined) {
14
+ element(out, 'copyright', config.copyright);
15
+ }
16
+
17
+ if (lastBuildDate !== undefined) {
18
+ element(out, 'lastBuildDate', lastBuildDate);
19
+ }
20
+ }
21
+
22
+ export function closingTags() {
23
+ return ' </channel>\n</rss>';
24
+ }
@@ -0,0 +1,26 @@
1
+ import { full } from '../content.js';
2
+ import { toRfc2822Utc } from '../lib/rfc2822.js';
3
+ import { element } from '../xml.js';
4
+
5
+ export function buildItem(out, post, prepared, documentURL, config) {
6
+ out.raw(' <item>\n');
7
+ element(out, 'title', prepared.title);
8
+ element(out, 'link', documentURL);
9
+ element(
10
+ out,
11
+ 'guid',
12
+ `${config.id ?? config.feed}#post/${encodeURIComponent(post.id)}`,
13
+ ' isPermaLink="false"'
14
+ );
15
+ element(out, 'pubDate', toRfc2822Utc(post.publishedAt));
16
+
17
+ const body = full(prepared);
18
+ element(out, 'content:encoded', body);
19
+ element(out, 'description', prepared.preview === undefined ? body : prepared.preview.feedHtml);
20
+
21
+ for (const tag of post.tags ?? []) {
22
+ element(out, 'category', tag);
23
+ }
24
+
25
+ out.raw(' </item>\n');
26
+ }
package/src/content.js ADDED
@@ -0,0 +1,81 @@
1
+ import { RendererInputError } from '#core/errors';
2
+ import { url } from '#core/url';
3
+
4
+ import { FeedPostSchema, PreparedSchema } from './schemas/zod.js';
5
+
6
+ function parse(schema, value, message) {
7
+ const result = schema.safeParse(value);
8
+
9
+ if (!result.success) {
10
+ throw new RendererInputError(message, { details: { issues: result.error.issues } });
11
+ }
12
+
13
+ return result.data;
14
+ }
15
+
16
+ function escape(value) {
17
+ return value
18
+ .replaceAll('&', '&amp;')
19
+ .replaceAll('<', '&lt;')
20
+ .replaceAll('>', '&gt;')
21
+ .replaceAll('"', '&quot;')
22
+ .replaceAll("'", '&#39;');
23
+ }
24
+
25
+ function literal(title, { text, preview, cover }) {
26
+ const prepared = { title, text: { feedHtml: escape(text) }, cover };
27
+
28
+ if (preview !== undefined) {
29
+ prepared.preview = { feedHtml: escape(preview), plain: preview };
30
+ }
31
+
32
+ return prepared;
33
+ }
34
+
35
+ export async function content(value, config, ctx) {
36
+ const source = structuredClone(value);
37
+ const post = parse(FeedPostSchema, source, 'feed requires saved published posts');
38
+
39
+ const prepared = config.prepare
40
+ ? await config.prepare(structuredClone(source), ctx)
41
+ : literal(source.title, post);
42
+ ctx.signal?.throwIfAborted();
43
+
44
+ const result = parse(PreparedSchema, prepared, 'invalid prepared post');
45
+ const documentURL = url(post.uri, ctx.base).href;
46
+ const cover = result.cover.url
47
+ ? { ...result.cover, url: new URL(result.cover.url, documentURL).href }
48
+ : result.cover;
49
+
50
+ if ((cover.url?.length ?? 0) > 5000000) {
51
+ throw new RendererInputError('derived cover URL exceeds 5000000 UTF-16 units');
52
+ }
53
+
54
+ return { post, prepared: { ...result, cover }, documentURL };
55
+ }
56
+
57
+ export function full(prepared) {
58
+ const { cover } = prepared;
59
+
60
+ if (!cover.url) {
61
+ return prepared.text.feedHtml;
62
+ }
63
+
64
+ let image = `<figure><img src="${escape(cover.url)}" alt="${escape(cover.alt ?? '')}"`;
65
+
66
+ if (cover.width !== undefined) {
67
+ image += ` width="${cover.width}"`;
68
+ }
69
+
70
+ if (cover.height !== undefined) {
71
+ image += ` height="${cover.height}"`;
72
+ }
73
+
74
+ image += '>';
75
+
76
+ if (cover.caption !== undefined) {
77
+ image += `<figcaption>${escape(cover.caption)}</figcaption>`;
78
+ }
79
+
80
+ return `${image}</figure>${prepared.text.feedHtml}`;
81
+ }
@@ -0,0 +1 @@
1
+ export { XmlRendererConfigError } from './xml-renderer-config.js';
@@ -0,0 +1,5 @@
1
+ import { YambError } from '#core/errors';
2
+
3
+ export class XmlRendererConfigError extends YambError {
4
+ static code = 'YAMB_XML_RENDERER_CONFIG';
5
+ }
package/src/escape.js ADDED
@@ -0,0 +1,19 @@
1
+ // oxlint-disable-next-line eslint/no-control-regex
2
+ const ILLEGAL_XML_CHARS = /[^\u0009\u000a\u000d\u0020-\ud7ff\ue000-\ufffd\u{10000}-\u{10ffff}]/gu;
3
+
4
+ export function cleanXml(value) {
5
+ return String(value).replace(ILLEGAL_XML_CHARS, '');
6
+ }
7
+
8
+ export function escapeXml(value) {
9
+ if (value === null || value === undefined) {
10
+ return '';
11
+ }
12
+
13
+ return cleanXml(value)
14
+ .replaceAll('&', '&amp;')
15
+ .replaceAll('<', '&lt;')
16
+ .replaceAll('>', '&gt;')
17
+ .replaceAll('"', '&quot;')
18
+ .replaceAll("'", '&apos;');
19
+ }
package/src/index.js ADDED
@@ -0,0 +1,12 @@
1
+ import { AtomRenderer } from './atom/index.js';
2
+ import { RssRenderer } from './rss/index.js';
3
+
4
+ export function rss(config) {
5
+ return new RssRenderer(config);
6
+ }
7
+
8
+ export function atom(config) {
9
+ return new AtomRenderer(config);
10
+ }
11
+
12
+ export { AtomRenderer, RssRenderer };
@@ -0,0 +1,3 @@
1
+ export function toRfc2822Utc(instant) {
2
+ return new Date(Temporal.Instant.from(instant).epochMilliseconds).toUTCString();
3
+ }
@@ -0,0 +1,36 @@
1
+ import { z } from 'zod';
2
+
3
+ import pkg from '../../package.json' with { type: 'json' };
4
+ import { XmlRendererConfigError } from '../errors/index.js';
5
+ import { ConfigSchema } from '../schemas/zod.js';
6
+ import { setState } from './internal.js';
7
+ import methods from './methods.js';
8
+
9
+ export class RssRenderer {
10
+ constructor(config) {
11
+ const result = ConfigSchema.safeParse(config);
12
+
13
+ if (!result.success) {
14
+ throw new XmlRendererConfigError(`invalid config: ${z.prettifyError(result.error)}`, {
15
+ details: { issues: result.error.issues }
16
+ });
17
+ }
18
+
19
+ this.name = 'rss';
20
+ this.version = pkg.version;
21
+ setState(this, { config: result.data });
22
+ }
23
+
24
+ static {
25
+ for (const method of methods) {
26
+ Object.defineProperty(this.prototype, method.name, {
27
+ value(...args) {
28
+ return method.fn(this, ...args);
29
+ },
30
+ writable: false,
31
+ configurable: false,
32
+ enumerable: false
33
+ });
34
+ }
35
+ }
36
+ }
@@ -0,0 +1,3 @@
1
+ import { store } from '#core/internal';
2
+
3
+ export const { get: getState, set: setState } = store('RssRenderer');
@@ -0,0 +1,78 @@
1
+ import { AsyncIteratorHelper } from '#core/async-iterator';
2
+ import { RendererFailedError, RendererInputError } from '#core/errors';
3
+
4
+ import { buildChannelHeader, closingTags } from '../../builders/channel.js';
5
+ import { buildItem } from '../../builders/item.js';
6
+ import { content } from '../../content.js';
7
+ import { toRfc2822Utc } from '../../lib/rfc2822.js';
8
+ import { writer } from '../../xml.js';
9
+ import { getState } from '../internal.js';
10
+
11
+ export default {
12
+ name: 'collection',
13
+
14
+ async fn(renderer, input, ctx) {
15
+ try {
16
+ ctx.signal?.throwIfAborted();
17
+ const posts = input?.posts;
18
+
19
+ if (
20
+ !posts ||
21
+ (typeof posts[Symbol.asyncIterator] !== 'function' &&
22
+ typeof posts[Symbol.iterator] !== 'function')
23
+ ) {
24
+ throw new RendererInputError('input.posts must be iterable or async iterable');
25
+ }
26
+
27
+ const { config } = getState(renderer);
28
+ const out = writer(config.bytes, renderer.name);
29
+ buildChannelHeader(out, config, ctx);
30
+
31
+ const { position } = out;
32
+ let updated;
33
+ const ids = new Set();
34
+
35
+ if (config.limit > 0) {
36
+ const iterator = AsyncIteratorHelper.from(posts, { signal: ctx.signal });
37
+
38
+ for await (const value of iterator.take(config.limit)) {
39
+ ctx.signal?.throwIfAborted();
40
+ const { post, prepared, documentURL } = await content(value, config, ctx);
41
+
42
+ if (ids.has(post.id)) {
43
+ throw new RendererInputError('duplicate rss post id');
44
+ }
45
+
46
+ ids.add(post.id);
47
+
48
+ buildItem(out, post, prepared, documentURL, config);
49
+
50
+ for (const candidate of [post.updatedAt, post.publishedAt]) {
51
+ if (!updated || Temporal.Instant.compare(candidate, updated) > 0) {
52
+ updated = candidate;
53
+ }
54
+ }
55
+ }
56
+ }
57
+
58
+ if (updated) {
59
+ out.raw(` <lastBuildDate>${toRfc2822Utc(updated)}</lastBuildDate>\n`, position);
60
+ }
61
+
62
+ out.raw(closingTags());
63
+ ctx.signal?.throwIfAborted();
64
+
65
+ return out.end();
66
+ } catch (error) {
67
+ if (ctx.signal?.aborted && Object.is(error, ctx.signal.reason)) {
68
+ throw error;
69
+ }
70
+
71
+ if (error?.name === 'AbortError' || error?.code?.startsWith?.('YAMB_')) {
72
+ throw error;
73
+ }
74
+
75
+ throw new RendererFailedError('rss generation failed', { cause: error });
76
+ }
77
+ }
78
+ };
@@ -0,0 +1,3 @@
1
+ import collection from './methods/collection.js';
2
+
3
+ export default [collection];
@@ -0,0 +1,120 @@
1
+ import { z } from 'zod';
2
+
3
+ import {
4
+ AuthorSchema,
5
+ CoverSchema,
6
+ IdSchema,
7
+ InstantSchema,
8
+ PreviewSchema,
9
+ TagsSchema,
10
+ TextSchema,
11
+ TitleSchema,
12
+ UriSchema
13
+ } from '#core/schemas';
14
+
15
+ export const ConfigSchema = z.strictObject({
16
+ title: z.string().min(1),
17
+ description: z.string().min(1),
18
+ language: z
19
+ .string()
20
+ .regex(/^[a-zA-Z]{2,3}(-[a-zA-Z0-9]{1,8})*$/, 'must be a BCP 47 language tag')
21
+ .default('ru'),
22
+ copyright: z.string().optional(),
23
+ link: z.httpUrl().optional(),
24
+ feed: z.httpUrl().refine((value) => !value.includes('#'), 'must not contain a fragment'),
25
+ id: z
26
+ .httpUrl()
27
+ .refine((value) => !value.includes('#'), 'must not contain a fragment')
28
+ .optional(),
29
+ prepare: z.function().optional(),
30
+ limit: z.number().int().nonnegative().default(20),
31
+ bytes: z.number().int().positive().default(8388608)
32
+ });
33
+
34
+ const AtomLanguageSchema = z.string().refine((value) => {
35
+ try {
36
+ return Intl.getCanonicalLocales(value).length === 1;
37
+ } catch {
38
+ return false;
39
+ }
40
+ }, 'must be a locale identifier supported by Intl');
41
+
42
+ const AtomUrlSchema = z
43
+ .httpUrl()
44
+ .refine((value) => !value.includes('#'), 'must not contain a fragment');
45
+
46
+ export const AtomConfigSchema = z.strictObject({
47
+ title: z.string().refine((value) => value.trim().length > 0, 'must not be empty'),
48
+ feed: AtomUrlSchema,
49
+ id: AtomUrlSchema.optional(),
50
+ link: z.httpUrl().optional(),
51
+ description: z.string().optional(),
52
+ language: AtomLanguageSchema.optional(),
53
+ author: AuthorSchema.optional(),
54
+ prepare: z.function().optional(),
55
+ limit: z.number().int().nonnegative().default(20),
56
+ bytes: z.number().int().positive().default(8388608),
57
+ updated: InstantSchema.prefault('1970-01-01T00:00:00Z')
58
+ });
59
+
60
+ const derived = z.string().refine((value) => value.length <= 5000000, {
61
+ error: 'derived field exceeds 5000000 UTF-16 units',
62
+ abort: true
63
+ });
64
+
65
+ const PreparedCoverSchema = z.strictObject({
66
+ ...CoverSchema.in.shape,
67
+ alt: derived.optional(),
68
+ caption: derived.optional(),
69
+ url: derived
70
+ .refine((value) => {
71
+ // oxlint-disable-next-line no-control-regex
72
+ if (/[\\\x00-\x20\x7f]/u.test(value) || value.startsWith('//')) {
73
+ return false;
74
+ }
75
+
76
+ if (value === '') {
77
+ return true;
78
+ }
79
+
80
+ if (value.startsWith('/') || value.startsWith('./')) {
81
+ return URL.canParse(value, 'https://example.invalid/');
82
+ }
83
+
84
+ if (!/^https?:\/\//i.test(value)) {
85
+ return false;
86
+ }
87
+
88
+ const parsed = URL.parse(value);
89
+
90
+ return Boolean(parsed) && !parsed.username && !parsed.password;
91
+ }, 'invalid prepared cover URL')
92
+ .optional()
93
+ });
94
+
95
+ export const PreparedSchema = z.object({
96
+ title: derived,
97
+ text: z.object({ feedHtml: derived }),
98
+ preview: z.object({ feedHtml: derived, plain: derived.optional() }).optional(),
99
+ cover: PreparedCoverSchema
100
+ });
101
+
102
+ export const FeedPostSchema = z.object({
103
+ id: IdSchema.refine((value) => value.isWellFormed(), 'id must be valid Unicode'),
104
+ uri: UriSchema,
105
+ title: z
106
+ .string()
107
+ .refine((value) => value.length <= 500, {
108
+ error: 'title exceeds 500 UTF-16 units',
109
+ abort: true
110
+ })
111
+ .pipe(TitleSchema),
112
+ text: TextSchema,
113
+ preview: PreviewSchema.optional(),
114
+ cover: CoverSchema.default({}),
115
+ status: z.literal('published'),
116
+ updatedAt: InstantSchema,
117
+ publishedAt: InstantSchema,
118
+ author: AuthorSchema.optional(),
119
+ tags: TagsSchema.optional()
120
+ });
package/src/xml.js ADDED
@@ -0,0 +1,96 @@
1
+ import { Buffer } from 'node:buffer';
2
+
3
+ import { RendererInputError } from '#core/errors';
4
+ import { url } from '#core/url';
5
+
6
+ import { cleanXml, escapeXml } from './escape.js';
7
+
8
+ export function writer(bytes, format) {
9
+ const parts = [];
10
+ let size = 0;
11
+
12
+ function check(length) {
13
+ if (length > bytes - size) {
14
+ throw new RendererInputError(`${format} output exceeds bytes`);
15
+ }
16
+ }
17
+
18
+ return {
19
+ get position() {
20
+ return parts.length;
21
+ },
22
+
23
+ raw(value, position) {
24
+ const length = Buffer.byteLength(value);
25
+ check(length);
26
+ size += length;
27
+
28
+ if (position === undefined) {
29
+ parts.push(value);
30
+ } else {
31
+ parts.splice(position, 0, value);
32
+ }
33
+ },
34
+
35
+ text(value, attribute = false) {
36
+ const clean = cleanXml(value);
37
+ let length = Buffer.byteLength(clean);
38
+ check(length);
39
+
40
+ const pattern = attribute ? /[&<>"'\r\t\n]/g : /[&<>"'\r]/g;
41
+
42
+ for (const [char] of clean.matchAll(pattern)) {
43
+ if (char === '"' || char === "'") {
44
+ length += 5;
45
+ } else if (char === '<' || char === '>' || char === '\t') {
46
+ length += 3;
47
+ } else {
48
+ length += 4;
49
+ }
50
+
51
+ check(length);
52
+ }
53
+
54
+ size += length;
55
+
56
+ let escaped = escapeXml(clean).replaceAll('\r', '&#13;');
57
+
58
+ if (attribute) {
59
+ escaped = escaped.replaceAll('\t', '&#9;').replaceAll('\n', '&#10;');
60
+ }
61
+
62
+ parts.push(escaped);
63
+ },
64
+
65
+ end() {
66
+ return parts.join('');
67
+ }
68
+ };
69
+ }
70
+
71
+ export function element(out, name, value, attributes = '') {
72
+ out.raw(`<${name}${attributes}>`);
73
+ out.text(value);
74
+ out.raw(`</${name}>\n`);
75
+ }
76
+
77
+ export function link(out, rel, type, href) {
78
+ out.raw(`<link rel="${rel}" type="${type}" href="`);
79
+ out.text(href, true);
80
+ out.raw('"/>\n');
81
+ }
82
+
83
+ export function author(out, value, base) {
84
+ out.raw('<author>\n');
85
+ element(out, 'name', value.name);
86
+
87
+ if (value.email !== undefined) {
88
+ element(out, 'email', value.email);
89
+ }
90
+
91
+ if (value.url) {
92
+ element(out, 'uri', url(value.url, base).href);
93
+ }
94
+
95
+ out.raw('</author>\n');
96
+ }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.