pups-client 0.0.0-stage → 0.2.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 +21 -0
- package/README.md +163 -2
- package/dist/cli/bin.d.ts +3 -0
- package/dist/cli/bin.d.ts.map +1 -0
- package/dist/cli/bin.js +4 -0
- package/dist/cli/bin.js.map +1 -0
- package/dist/cli/file-store.d.ts +21 -0
- package/dist/cli/file-store.d.ts.map +1 -0
- package/dist/cli/file-store.js +59 -0
- package/dist/cli/file-store.js.map +1 -0
- package/dist/cli/loopback.d.ts +28 -0
- package/dist/cli/loopback.d.ts.map +1 -0
- package/dist/cli/loopback.js +82 -0
- package/dist/cli/loopback.js.map +1 -0
- package/dist/cli/main.d.ts +16 -0
- package/dist/cli/main.d.ts.map +1 -0
- package/dist/cli/main.js +337 -0
- package/dist/cli/main.js.map +1 -0
- package/dist/client.d.ts +151 -0
- package/dist/client.d.ts.map +1 -0
- package/dist/client.js +427 -0
- package/dist/client.js.map +1 -0
- package/dist/discovery.d.ts +58 -0
- package/dist/discovery.d.ts.map +1 -0
- package/dist/discovery.js +138 -0
- package/dist/discovery.js.map +1 -0
- package/dist/errors.d.ts +77 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +59 -0
- package/dist/errors.js.map +1 -0
- package/dist/feed.d.ts +314 -0
- package/dist/feed.d.ts.map +1 -0
- package/dist/feed.js +805 -0
- package/dist/feed.js.map +1 -0
- package/dist/file-types.d.ts +30 -0
- package/dist/file-types.d.ts.map +1 -0
- package/dist/file-types.js +67 -0
- package/dist/file-types.js.map +1 -0
- package/dist/host-meta.d.ts +71 -0
- package/dist/host-meta.d.ts.map +1 -0
- package/dist/host-meta.js +122 -0
- package/dist/host-meta.js.map +1 -0
- package/dist/index.d.ts +25 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +16 -0
- package/dist/index.js.map +1 -0
- package/dist/oauth.d.ts +54 -0
- package/dist/oauth.d.ts.map +1 -0
- package/dist/oauth.js +124 -0
- package/dist/oauth.js.map +1 -0
- package/dist/paths.d.ts +32 -0
- package/dist/paths.d.ts.map +1 -0
- package/dist/paths.js +91 -0
- package/dist/paths.js.map +1 -0
- package/dist/scopes.d.ts +28 -0
- package/dist/scopes.d.ts.map +1 -0
- package/dist/scopes.js +56 -0
- package/dist/scopes.js.map +1 -0
- package/dist/session.d.ts +194 -0
- package/dist/session.d.ts.map +1 -0
- package/dist/session.js +317 -0
- package/dist/session.js.map +1 -0
- package/dist/store/indexeddb-store.d.ts +23 -0
- package/dist/store/indexeddb-store.d.ts.map +1 -0
- package/dist/store/indexeddb-store.js +116 -0
- package/dist/store/indexeddb-store.js.map +1 -0
- package/dist/store/memory-store.d.ts +13 -0
- package/dist/store/memory-store.d.ts.map +1 -0
- package/dist/store/memory-store.js +22 -0
- package/dist/store/memory-store.js.map +1 -0
- package/dist/store/token-store.d.ts +35 -0
- package/dist/store/token-store.d.ts.map +1 -0
- package/dist/store/token-store.js +2 -0
- package/dist/store/token-store.js.map +1 -0
- package/dist/tabs.d.ts +29 -0
- package/dist/tabs.d.ts.map +1 -0
- package/dist/tabs.js +51 -0
- package/dist/tabs.js.map +1 -0
- package/dist/tokens.d.ts +59 -0
- package/dist/tokens.d.ts.map +1 -0
- package/dist/tokens.js +200 -0
- package/dist/tokens.js.map +1 -0
- package/dist/util.d.ts +23 -0
- package/dist/util.d.ts.map +1 -0
- package/dist/util.js +109 -0
- package/dist/util.js.map +1 -0
- package/dist/version.d.ts +2 -0
- package/dist/version.d.ts.map +1 -0
- package/dist/version.js +2 -0
- package/dist/version.js.map +1 -0
- package/package.json +55 -4
- package/src/cli/bin.ts +4 -0
- package/src/cli/file-store.ts +66 -0
- package/src/cli/loopback.ts +103 -0
- package/src/cli/main.ts +329 -0
- package/src/client.ts +496 -0
- package/src/discovery.ts +178 -0
- package/src/errors.ts +136 -0
- package/src/feed.ts +1007 -0
- package/src/file-types.ts +80 -0
- package/src/host-meta.ts +148 -0
- package/src/index.ts +49 -0
- package/src/oauth.ts +163 -0
- package/src/paths.ts +92 -0
- package/src/scopes.ts +68 -0
- package/src/session.ts +396 -0
- package/src/store/indexeddb-store.ts +140 -0
- package/src/store/memory-store.ts +28 -0
- package/src/store/token-store.ts +36 -0
- package/src/tabs.ts +61 -0
- package/src/tokens.ts +208 -0
- package/src/util.ts +118 -0
- package/src/version.ts +1 -0
package/src/feed.ts
ADDED
|
@@ -0,0 +1,1007 @@
|
|
|
1
|
+
import { isPupsError, PupsError } from './errors.js'
|
|
2
|
+
import { fileTypes } from './file-types.js'
|
|
3
|
+
import { pathFromPublicUrl } from './paths.js'
|
|
4
|
+
import type { Scope } from './scopes.js'
|
|
5
|
+
import type { Body, PupsSession } from './session.js'
|
|
6
|
+
import { randomString } from './util.js'
|
|
7
|
+
|
|
8
|
+
/** The link relation that registers a feed in `host-meta.json` (RFC-7). A placeholder in RFC-7. */
|
|
9
|
+
export const FEED_REL = 'https://bigwide.net/ns/feed'
|
|
10
|
+
|
|
11
|
+
/** The `about` of the `_pups` object: RFC-7. Not its final location; readers must not rely on it. */
|
|
12
|
+
export const PUPS_FEED_SPEC = 'https://github.com/bigwide-net/RFCs/blob/main/RFC-7-Feed-Publishing-with-PUPS.md'
|
|
13
|
+
|
|
14
|
+
const RFC1_URL = 'https://github.com/bigwide-net/RFCs/blob/main/RFC-1-Source-for-JSON-Feeds.md'
|
|
15
|
+
const JSON_FEED_VERSION = 'https://jsonfeed.org/version/1.1'
|
|
16
|
+
const FEED_CONTENT_TYPE = 'application/feed+json'
|
|
17
|
+
const maxArchiveNumber = 999_999
|
|
18
|
+
/** The feed file keeps at least this many items, also when `maxBytes` is exceeded (RFC-7 "Size in bytes"). */
|
|
19
|
+
const minFeedItems = 10
|
|
20
|
+
|
|
21
|
+
const mainComment = `This feed is maintained by apps through a Personal Upload Server (PUPS), following ${PUPS_FEED_SPEC}. It contains the newest items. If it has _pups.archive_url, all items are in the archives, starting with the one there.`
|
|
22
|
+
const archiveComment = (feedUrl: string) =>
|
|
23
|
+
`This is an archive of ${feedUrl}, maintained by apps through a Personal Upload Server (PUPS), following ${PUPS_FEED_SPEC}. New items appear in the feed at _pups.updates_url, older ones are in the archive at next_url.`
|
|
24
|
+
|
|
25
|
+
/** Feed names (RFC-7 "Named feeds"): 1 to 40 lowercase letters, digits and `-`, not starting or ending with `-`. */
|
|
26
|
+
const feedNamePattern = /^[a-z0-9](?:[a-z0-9-]{0,38}[a-z0-9])?$/
|
|
27
|
+
|
|
28
|
+
/** The main feed's media directories in `/feed/`, which therefore can't be feed names. */
|
|
29
|
+
const mainMediaFolders = ['images', 'media']
|
|
30
|
+
|
|
31
|
+
/** Top-level fields that are fixed or managed by RFC-7, and can't be set through `create()` or `updateSettings()`. */
|
|
32
|
+
const reservedFields = new Set(['version', 'home_page_url', 'feed_url', 'user_comment', 'next_url', 'items', 'hubs', '_pups', 'icon', 'favicon'])
|
|
33
|
+
|
|
34
|
+
export interface FeedAuthor {
|
|
35
|
+
name?: string
|
|
36
|
+
url?: string
|
|
37
|
+
avatar?: string
|
|
38
|
+
[field: string]: unknown
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export interface FeedAttachment {
|
|
42
|
+
url: string
|
|
43
|
+
mime_type: string
|
|
44
|
+
title?: string
|
|
45
|
+
size_in_bytes?: number
|
|
46
|
+
duration_in_seconds?: number
|
|
47
|
+
[field: string]: unknown
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** A JSON Feed 1.1 item. */
|
|
51
|
+
export interface FeedItem {
|
|
52
|
+
id: string
|
|
53
|
+
url?: string
|
|
54
|
+
external_url?: string
|
|
55
|
+
title?: string
|
|
56
|
+
content_html?: string
|
|
57
|
+
content_text?: string
|
|
58
|
+
summary?: string
|
|
59
|
+
image?: string
|
|
60
|
+
banner_image?: string
|
|
61
|
+
date_published?: string
|
|
62
|
+
date_modified?: string
|
|
63
|
+
authors?: FeedAuthor[]
|
|
64
|
+
tags?: string[]
|
|
65
|
+
language?: string
|
|
66
|
+
attachments?: FeedAttachment[]
|
|
67
|
+
[field: string]: unknown
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** The `_pups` object of a feed file or archive. */
|
|
71
|
+
export interface PupsMarker {
|
|
72
|
+
about?: string
|
|
73
|
+
pupsControlled?: boolean
|
|
74
|
+
/** In the feed file: the public URL of the newest archive. */
|
|
75
|
+
archive_url?: string
|
|
76
|
+
/** In an archive: the public URL of the feed file, which readers poll. */
|
|
77
|
+
updates_url?: string
|
|
78
|
+
[field: string]: unknown
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** A JSON Feed 1.1 document, as stored in a feed file or archive. */
|
|
82
|
+
export interface FeedDocument {
|
|
83
|
+
version: string
|
|
84
|
+
title: string
|
|
85
|
+
home_page_url?: string
|
|
86
|
+
feed_url?: string
|
|
87
|
+
description?: string
|
|
88
|
+
user_comment?: string
|
|
89
|
+
next_url?: string
|
|
90
|
+
icon?: string
|
|
91
|
+
favicon?: string
|
|
92
|
+
authors?: FeedAuthor[]
|
|
93
|
+
language?: string
|
|
94
|
+
expired?: boolean
|
|
95
|
+
hubs?: unknown[]
|
|
96
|
+
items: FeedItem[]
|
|
97
|
+
_pups?: PupsMarker
|
|
98
|
+
[field: string]: unknown
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* The fields of a feed that belong to the owner (RFC-7 "Fields"). Extensions such as `_podcast` (RFC-3) or
|
|
103
|
+
* `_source` (RFC-1) are allowed too. Icons are set with `setIcon()` and `setFavicon()`.
|
|
104
|
+
*/
|
|
105
|
+
export interface FeedSettings {
|
|
106
|
+
title?: string
|
|
107
|
+
description?: string
|
|
108
|
+
authors?: FeedAuthor[]
|
|
109
|
+
language?: string
|
|
110
|
+
expired?: boolean
|
|
111
|
+
[extension: `_${string}`]: unknown
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** Changes to the settings: a value sets the field, `null` removes it, `undefined` leaves it unchanged. */
|
|
115
|
+
export type FeedSettingsChanges = { [K in keyof FeedSettings]?: FeedSettings[K] | null }
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* An image, audio or video file to upload: a `Blob` (or `File`) with a type or name, or a body with its type or
|
|
119
|
+
* extension. The extension must be on the RFC-6 allowlist.
|
|
120
|
+
*/
|
|
121
|
+
export type MediaInput = Blob | { body: Body; type?: string; extension?: string }
|
|
122
|
+
|
|
123
|
+
/** The settings of a new feed. */
|
|
124
|
+
export interface FeedSetup extends FeedSettings {
|
|
125
|
+
title: string
|
|
126
|
+
/** 512 × 512 pixels, stored in `images/icons/` in the feed directory. */
|
|
127
|
+
icon?: MediaInput
|
|
128
|
+
/** 64 × 64 pixels, stored in `images/icons/` in the feed directory. */
|
|
129
|
+
favicon?: MediaInput
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** A new post: a JSON Feed item without `id` (generated unless given) and with a few conveniences. */
|
|
133
|
+
export interface PostInput {
|
|
134
|
+
/** Generated if missing: 16 random URL-safe characters. Must be unique across the feed and its archives. */
|
|
135
|
+
id?: string
|
|
136
|
+
title?: string
|
|
137
|
+
content_html?: string
|
|
138
|
+
content_text?: string
|
|
139
|
+
/**
|
|
140
|
+
* The text as Markdown, stored in `_source.markdown` (RFC-1). If neither `content_html` nor `content_text` is
|
|
141
|
+
* given, the Markdown is also used as `content_text`, since JSON Feed requires one of them.
|
|
142
|
+
*/
|
|
143
|
+
markdown?: string
|
|
144
|
+
summary?: string
|
|
145
|
+
url?: string
|
|
146
|
+
external_url?: string
|
|
147
|
+
image?: string
|
|
148
|
+
banner_image?: string
|
|
149
|
+
/** Default: now. */
|
|
150
|
+
date_published?: string | Date
|
|
151
|
+
authors?: FeedAuthor[]
|
|
152
|
+
tags?: string[]
|
|
153
|
+
language?: string
|
|
154
|
+
attachments?: FeedAttachment[]
|
|
155
|
+
[extension: `_${string}`]: unknown
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/** Changes to a post: a value sets the field, `null` removes it, `undefined` leaves it unchanged. */
|
|
159
|
+
export type PostChanges = { [K in Exclude<keyof PostInput, 'id'>]?: PostInput[K] | null }
|
|
160
|
+
|
|
161
|
+
export interface PostResult {
|
|
162
|
+
id: string
|
|
163
|
+
/** The item as stored. */
|
|
164
|
+
item: FeedItem
|
|
165
|
+
/**
|
|
166
|
+
* The URL of the item's archive plus `#<id>`. Items never leave their archive, so it never changes; use it e.g.
|
|
167
|
+
* as the `source` of an RFC-4 webmention. In a feed without archives, the feed file's URL plus `#<id>`.
|
|
168
|
+
*/
|
|
169
|
+
url: string
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
export interface MediaResult {
|
|
173
|
+
path: string
|
|
174
|
+
/** The public URL, to reference from items. */
|
|
175
|
+
url: string
|
|
176
|
+
/** The served type, e.g. for `attachments[].mime_type`. */
|
|
177
|
+
type: string
|
|
178
|
+
size: number
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
export type FeedState =
|
|
182
|
+
/** There is no feed file yet. `create()` sets it up. */
|
|
183
|
+
| { status: 'missing' }
|
|
184
|
+
/** A feed maintained by PUPS clients, ready to write. */
|
|
185
|
+
| { status: 'pups'; feed: FeedDocument; etag: string }
|
|
186
|
+
/** A JSON Feed without `_pups.pupsControlled`: maintained by other means, and never written (RFC-7). */
|
|
187
|
+
| { status: 'foreign'; feed: FeedDocument }
|
|
188
|
+
/** The file exists but is not a JSON Feed. */
|
|
189
|
+
| { status: 'invalid' }
|
|
190
|
+
|
|
191
|
+
export interface FeedOptions {
|
|
192
|
+
/** How many of the newest items the feed file holds. Default 30 (RFC-7 "Feed size"). */
|
|
193
|
+
maxItems?: number
|
|
194
|
+
/** How many items an archive holds. Default 20 (RFC-7 "Archives"); other clients expect 20. */
|
|
195
|
+
archiveSize?: number
|
|
196
|
+
/**
|
|
197
|
+
* Whether to start archives for a feed that has none, on its next post (RFC-7 "Starting the archives").
|
|
198
|
+
* Default true. With false, posts to such a feed only go into the feed file, and items beyond `maxItems` are
|
|
199
|
+
* dropped. Feeds that have archives always keep them.
|
|
200
|
+
*/
|
|
201
|
+
startArchives?: boolean
|
|
202
|
+
/**
|
|
203
|
+
* Optional: keep fewer items in the feed file when it would be larger than this many bytes, but at least 10
|
|
204
|
+
* (RFC-7 "Size in bytes").
|
|
205
|
+
*/
|
|
206
|
+
maxBytes?: number
|
|
207
|
+
/** How often an operation is repeated when another client changed the feed in between. Default 8. */
|
|
208
|
+
maxAttempts?: number
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/** A feed registered in `host-meta.json`. */
|
|
212
|
+
export interface FeedLink {
|
|
213
|
+
/** The public URL of the feed file. */
|
|
214
|
+
url: string
|
|
215
|
+
type?: string
|
|
216
|
+
/** Set if the feed is a main or named feed on this PUPS server, in the layout of RFC-7. */
|
|
217
|
+
feed?: PupsFeed
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
type Signal = { signal?: AbortSignal }
|
|
221
|
+
|
|
222
|
+
interface Loaded {
|
|
223
|
+
path: string
|
|
224
|
+
doc: FeedDocument
|
|
225
|
+
etag: string
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
interface Found {
|
|
229
|
+
main: Loaded
|
|
230
|
+
file: Loaded
|
|
231
|
+
index: number
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/** The scopes an app needs to write a feed: the feed file and the feed directory (RFC-7 "Server requirements"). */
|
|
235
|
+
export function feedScopes(name?: string): Scope[] {
|
|
236
|
+
const { path, directory } = feedPaths(name)
|
|
237
|
+
return [`write:${path}`, `write:${directory}`]
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
function feedPaths(name?: string): { path: `/${string}`; directory: `/${string}` } {
|
|
241
|
+
if (name === undefined) return { path: '/feed.json', directory: '/feed/' }
|
|
242
|
+
if (!feedNamePattern.test(name))
|
|
243
|
+
throw new PupsError('invalid_request', `"${name}" is not a valid feed name: use 1 to 40 lowercase letters, digits and "-", not starting or ending with "-" (RFC-7, Named feeds).`)
|
|
244
|
+
if (mainMediaFolders.includes(name))
|
|
245
|
+
throw new PupsError('invalid_request', `"${name}" can't be a feed name: /feed/${name}/ and its files belong to the main feed (RFC-7, Named feeds).`)
|
|
246
|
+
return { path: `/feed/${name}.json`, directory: `/feed/${name}/` }
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
const isObject = (value: unknown): value is Record<string, unknown> =>
|
|
250
|
+
!!value && typeof value == 'object' && !Array.isArray(value)
|
|
251
|
+
|
|
252
|
+
const isFeedDocument = (value: unknown): value is FeedDocument =>
|
|
253
|
+
isObject(value) && typeof value.version == 'string' && value.version.startsWith('https://jsonfeed.org/version/1')
|
|
254
|
+
&& Array.isArray(value.items) && value.items.every(i => isObject(i) && typeof i.id == 'string')
|
|
255
|
+
|
|
256
|
+
const isControlled = (doc: FeedDocument) => doc._pups?.pupsControlled === true
|
|
257
|
+
|
|
258
|
+
const notControlled = (path: string) =>
|
|
259
|
+
new PupsError('not_pups_controlled', `${path} is not maintained by PUPS clients: it has no "_pups": { "pupsControlled": true }. It is never written; the owner can hand it over by adding that marker (RFC-7, The _pups object).`)
|
|
260
|
+
|
|
261
|
+
const conflict = (what: string) => new PupsError('precondition_failed', `${what} changed in the meantime.`)
|
|
262
|
+
|
|
263
|
+
const now = () => new Date().toISOString().replace(/\.\d{3}Z$/, 'Z')
|
|
264
|
+
|
|
265
|
+
const clone = <T>(value: T): T => structuredClone(value)
|
|
266
|
+
|
|
267
|
+
const serialize = (doc: FeedDocument) => JSON.stringify(doc, null, 2)
|
|
268
|
+
|
|
269
|
+
const byteLength = (text: string) => new TextEncoder().encode(text).length
|
|
270
|
+
|
|
271
|
+
const replaceAt = <T>(array: T[], index: number, value: T) => array.map((v, i) => i == index ? value : v)
|
|
272
|
+
|
|
273
|
+
/** Adds `incoming` items at the top of `existing`; an item whose id is already there replaces the old copy instead. */
|
|
274
|
+
function mergeItems(existing: FeedItem[], incoming: FeedItem[]): FeedItem[] {
|
|
275
|
+
const byId = new Map(incoming.map(item => [item.id, item]))
|
|
276
|
+
const present = new Set(existing.map(item => item.id))
|
|
277
|
+
return [...incoming.filter(item => !present.has(item.id)), ...existing.map(item => byId.get(item.id) ?? item)]
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
/** Every string inside `value`, deeply. */
|
|
281
|
+
function* strings(value: unknown): Generator<string> {
|
|
282
|
+
if (typeof value == 'string') yield value
|
|
283
|
+
else if (Array.isArray(value)) for (const v of value) yield* strings(v)
|
|
284
|
+
else if (isObject(value)) for (const v of Object.values(value)) yield* strings(v)
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
/** The file extension for a media type, preferring extensions that are served as exactly that type. */
|
|
288
|
+
function extensionForType(type: string): string | undefined {
|
|
289
|
+
const essence = type.split(';')[0]!.trim().toLowerCase()
|
|
290
|
+
const entries = Object.entries(fileTypes)
|
|
291
|
+
return entries.find(([, t]) => t.served == essence)?.[0] ?? entries.find(([, t]) => t.accepted.includes(essence))?.[0]
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
/**
|
|
295
|
+
* A feed on the owner's domain, maintained according to RFC-7: the main feed `/feed.json`, or a named feed
|
|
296
|
+
* `/feed/<name>.json`, each with its feed directory for archives, icons and media: `/feed/`, or `/feed/<name>/`.
|
|
297
|
+
* The main feed keeps its media in `/feed/images/` and `/feed/media/`, since the rest of `/feed/` belongs to the
|
|
298
|
+
* named feeds.
|
|
299
|
+
*
|
|
300
|
+
* Get one from `session.feed()` or `session.feed('photos')`. The session needs the feed's scopes, see
|
|
301
|
+
* {@link feedScopes}. All writes are safe against concurrent changes by other apps and the owner: they are
|
|
302
|
+
* read-modify-write cycles with ETags, repeated when another client wrote in between.
|
|
303
|
+
*/
|
|
304
|
+
export class PupsFeed {
|
|
305
|
+
/** The name of a named feed; undefined for the main feed. */
|
|
306
|
+
readonly name?: string
|
|
307
|
+
/** The feed file, e.g. `/feed.json` or `/feed/photos.json`. */
|
|
308
|
+
readonly path: string
|
|
309
|
+
/** The feed directory, e.g. `/feed/` or `/feed/photos/`. */
|
|
310
|
+
readonly directory: string
|
|
311
|
+
readonly #session: PupsSession
|
|
312
|
+
readonly #maxItems: number
|
|
313
|
+
readonly #archiveSize: number
|
|
314
|
+
readonly #archivesWanted: boolean
|
|
315
|
+
readonly #maxBytes?: number
|
|
316
|
+
readonly #maxAttempts: number
|
|
317
|
+
|
|
318
|
+
/** @internal Use `session.feed()`. */
|
|
319
|
+
constructor(session: PupsSession, name?: string, options: FeedOptions = {}) {
|
|
320
|
+
const { path, directory } = feedPaths(name)
|
|
321
|
+
this.name = name
|
|
322
|
+
this.path = path
|
|
323
|
+
this.directory = directory
|
|
324
|
+
this.#session = session
|
|
325
|
+
this.#maxItems = options.maxItems ?? 30
|
|
326
|
+
this.#archiveSize = options.archiveSize ?? 20
|
|
327
|
+
this.#archivesWanted = options.startArchives ?? true
|
|
328
|
+
this.#maxBytes = options.maxBytes
|
|
329
|
+
this.#maxAttempts = options.maxAttempts ?? 8
|
|
330
|
+
if (!(this.#archiveSize >= 1 && this.#maxItems >= 1))
|
|
331
|
+
throw new PupsError('invalid_request', 'Feed options: maxItems and archiveSize must be at least 1.')
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
/** The public URL of the feed file, its `feed_url`. */
|
|
335
|
+
get url(): string {
|
|
336
|
+
return this.#session.publicUrl(this.path)
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
/** The scopes needed to write this feed. */
|
|
340
|
+
get scopes(): Scope[] {
|
|
341
|
+
return feedScopes(this.name)
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
/** Whether the session may write the feed file and the feed directory. */
|
|
345
|
+
get writable(): boolean {
|
|
346
|
+
return this.#session.canWrite(this.path) && this.#session.canWrite(this.#archivePath(0))
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
/** Reads the feed file and tells whether it exists, and whether PUPS clients may write it. */
|
|
350
|
+
async load(options: Signal = {}): Promise<FeedState> {
|
|
351
|
+
try {
|
|
352
|
+
const loaded = await this.#read(this.path, options.signal)
|
|
353
|
+
if (!loaded) return { status: 'missing' }
|
|
354
|
+
return isControlled(loaded.doc) ? { status: 'pups', feed: loaded.doc, etag: loaded.etag } : { status: 'foreign', feed: loaded.doc }
|
|
355
|
+
} catch (e) {
|
|
356
|
+
if (isPupsError(e, 'invalid_feed')) return { status: 'invalid' }
|
|
357
|
+
throw e
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
/**
|
|
362
|
+
* Sets up a new feed (RFC-7 "Setting up a feed"): uploads the icons, writes the feed file with the fixed fields
|
|
363
|
+
* and the `_pups` marker, and registers the feed in `host-meta.json` (unless `register` is false).
|
|
364
|
+
* @returns `registered`: false if the feed couldn't be registered; call `register()` again later, or tell the owner
|
|
365
|
+
* to add the link to `host-meta.json` by hand.
|
|
366
|
+
* @throws {PupsError} `precondition_failed` if the feed file exists already; `insufficient_scope`.
|
|
367
|
+
*/
|
|
368
|
+
async create(setup: FeedSetup, options: Signal & { register?: boolean } = {}): Promise<{ url: string; registered: boolean }> {
|
|
369
|
+
const { icon, favicon, title, ...settings } = setup
|
|
370
|
+
if (typeof title != 'string' || !title.trim()) throw new PupsError('invalid_request', 'A feed needs a title.')
|
|
371
|
+
this.#checkSettings(settings)
|
|
372
|
+
this.#checkWritable()
|
|
373
|
+
const uploaded: MediaResult[] = []
|
|
374
|
+
try {
|
|
375
|
+
const iconFile = icon && await this.#upload(icon, 'images/icons/icon-', options.signal)
|
|
376
|
+
if (iconFile) uploaded.push(iconFile)
|
|
377
|
+
const faviconFile = favicon && await this.#upload(favicon, 'images/icons/favicon-', options.signal)
|
|
378
|
+
if (faviconFile) uploaded.push(faviconFile)
|
|
379
|
+
const { description, ...rest } = settings
|
|
380
|
+
const doc: FeedDocument = {
|
|
381
|
+
version: JSON_FEED_VERSION,
|
|
382
|
+
title,
|
|
383
|
+
home_page_url: this.#session.me,
|
|
384
|
+
feed_url: this.url,
|
|
385
|
+
...description === undefined ? {} : { description },
|
|
386
|
+
user_comment: mainComment,
|
|
387
|
+
...iconFile ? { icon: iconFile.url } : {},
|
|
388
|
+
...faviconFile ? { favicon: faviconFile.url } : {},
|
|
389
|
+
...rest,
|
|
390
|
+
items: [],
|
|
391
|
+
_pups: { about: PUPS_FEED_SPEC, pupsControlled: true },
|
|
392
|
+
}
|
|
393
|
+
await this.#session.create(this.path, serialize(doc), { contentType: FEED_CONTENT_TYPE, signal: options.signal })
|
|
394
|
+
} catch (e) {
|
|
395
|
+
await Promise.all(uploaded.map(file => this.#deleteQuietly(file.path)))
|
|
396
|
+
if (isPupsError(e, 'precondition_failed'))
|
|
397
|
+
throw new PupsError('precondition_failed', `${this.path} exists already. Use load() to see whether it can be used.`, { cause: e })
|
|
398
|
+
throw e
|
|
399
|
+
}
|
|
400
|
+
if (options.register === false) return { url: this.url, registered: false }
|
|
401
|
+
try {
|
|
402
|
+
return { url: this.url, registered: await this.register(options) }
|
|
403
|
+
} catch (e) {
|
|
404
|
+
// The feed exists now; a failed registration must not look like a failed setup.
|
|
405
|
+
if (isPupsError(e, 'aborted')) throw e
|
|
406
|
+
return { url: this.url, registered: false }
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
/**
|
|
411
|
+
* Registers the feed in `host-meta.json` (RFC-7 "Registering feeds"), unless a link with the feed relation and
|
|
412
|
+
* this feed's URL exists already.
|
|
413
|
+
* @returns false if the server has no host-meta endpoint, or doesn't allow the feed relation for this path.
|
|
414
|
+
*/
|
|
415
|
+
async register(options: Signal = {}): Promise<boolean> {
|
|
416
|
+
const hostMeta = this.#session.hostMeta
|
|
417
|
+
if (!hostMeta.available || !hostMeta.allowsRel(FEED_REL, this.path)) return false
|
|
418
|
+
const document = await hostMeta.get(options)
|
|
419
|
+
if (document.links?.some(link => link.rel == FEED_REL && link.href == this.url)) return true
|
|
420
|
+
await hostMeta.addLink({ rel: FEED_REL, href: this.path, type: FEED_CONTENT_TYPE }, options)
|
|
421
|
+
return true
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
/**
|
|
425
|
+
* Changes the owner's fields of the feed (RFC-7 "Editing a feed"): a value sets a field, `null` removes it.
|
|
426
|
+
* @returns the feed as written.
|
|
427
|
+
*/
|
|
428
|
+
async updateSettings(changes: FeedSettingsChanges, options: Signal = {}): Promise<FeedDocument> {
|
|
429
|
+
this.#checkSettings(changes)
|
|
430
|
+
if (changes.title === null || (changes.title !== undefined && !changes.title.trim()))
|
|
431
|
+
throw new PupsError('invalid_request', 'A feed needs a title.')
|
|
432
|
+
return this.#transaction(async () => {
|
|
433
|
+
const main = await this.#readControlled(this.path, options.signal)
|
|
434
|
+
const doc = { ...main.doc }
|
|
435
|
+
for (const [key, value] of Object.entries(changes))
|
|
436
|
+
if (value === null) delete doc[key]
|
|
437
|
+
else if (value !== undefined) doc[key] = value
|
|
438
|
+
return this.#writeMain(doc, main.etag, options.signal)
|
|
439
|
+
})
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
/**
|
|
443
|
+
* Uploads a new icon (512 × 512) to `/feed/images/icons/` (`/feed/<name>/images/icons/` for a named feed) and
|
|
444
|
+
* deletes the old one, or removes it with `null`.
|
|
445
|
+
*/
|
|
446
|
+
setIcon(media: MediaInput | null, options: Signal = {}): Promise<FeedDocument> {
|
|
447
|
+
return this.#setImage('icon', media, options.signal)
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
/** Uploads a new favicon (64 × 64) to the icons directory, like `setIcon()`, or removes it with `null`. */
|
|
451
|
+
setFavicon(media: MediaInput | null, options: Signal = {}): Promise<FeedDocument> {
|
|
452
|
+
return this.#setImage('favicon', media, options.signal)
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
/**
|
|
456
|
+
* Uploads an image, audio or video file into the feed directory under a new, unique name, by default
|
|
457
|
+
* `images/<year>/…` for images and `media/<year>/…` for everything else. Reference it from a post by its `url`.
|
|
458
|
+
* For the main feed, `folder` must be inside `images/` or `media/`: the rest of `/feed/` belongs to named feeds.
|
|
459
|
+
*/
|
|
460
|
+
async uploadMedia(media: MediaInput, options: Signal & { folder?: string } = {}): Promise<MediaResult> {
|
|
461
|
+
const { type } = this.#mediaType(media)
|
|
462
|
+
const folder = (options.folder ?? (type.startsWith('image/') ? 'images' : 'media')).replace(/^\/+|\/+$/g, '')
|
|
463
|
+
if (folder == 'images/icons' || folder.startsWith('images/icons/'))
|
|
464
|
+
throw new PupsError('invalid_request', `${this.directory}images/icons/ is reserved for the feed's icons (RFC-7, Icons).`)
|
|
465
|
+
if (this.name === undefined && !mainMediaFolders.includes(folder.split('/')[0]!))
|
|
466
|
+
throw new PupsError('invalid_request', `The main feed's media go into /feed/images/ or /feed/media/; the rest of /feed/ belongs to named feeds (RFC-7, Items).`)
|
|
467
|
+
return this.#upload(media, `${folder}/${new Date().getUTCFullYear()}/`, options.signal)
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
/**
|
|
471
|
+
* Adds a post (RFC-7 "Posting with archives"): first to the newest archive, or to a new archive once the newest
|
|
472
|
+
* holds `archiveSize` items, then to the top of the feed file, which keeps the newest `maxItems`. A feed without
|
|
473
|
+
* archives gets them now, unless `startArchives` is false; then the post only goes into the feed file. Upload
|
|
474
|
+
* media with `uploadMedia()` before posting.
|
|
475
|
+
* @returns the post, with `url`: its archive's URL plus `#<id>`, which never changes; for a feed without
|
|
476
|
+
* archives, the feed file's URL plus `#<id>`, valid while the post is among the newest.
|
|
477
|
+
*/
|
|
478
|
+
async addPost(input: PostInput, options: Signal = {}): Promise<PostResult> {
|
|
479
|
+
const item = this.#newItem(input)
|
|
480
|
+
const signal = options.signal
|
|
481
|
+
let archiveUrl = ''
|
|
482
|
+
let firstAttempt = true
|
|
483
|
+
await this.#transaction(async () => {
|
|
484
|
+
const main = await this.#readControlled(this.path, signal)
|
|
485
|
+
// On a retry, the item may be in the feed file already: another client repaired it from the archive.
|
|
486
|
+
if (firstAttempt && main.doc.items.some(i => i.id == item.id))
|
|
487
|
+
throw new PupsError('invalid_request', `The feed already has an item with the id "${item.id}".`)
|
|
488
|
+
firstAttempt = false
|
|
489
|
+
const doc: FeedDocument = { ...main.doc, _pups: { ...main.doc._pups } }
|
|
490
|
+
const hasArchives = this.#archiveNumber(doc._pups!.archive_url) !== undefined
|
|
491
|
+
if (!hasArchives && !this.#archivesWanted) {
|
|
492
|
+
// A feed without archives: the feed file is all there is (RFC-7 "Posting").
|
|
493
|
+
archiveUrl = this.url
|
|
494
|
+
await this.#writeMain({ ...doc, items: this.#newestItems([item], doc.items, doc) }, main.etag, signal)
|
|
495
|
+
return
|
|
496
|
+
}
|
|
497
|
+
if (!hasArchives) {
|
|
498
|
+
const started = await this.#startArchives(main, signal)
|
|
499
|
+
if (started) doc._pups!.archive_url = started
|
|
500
|
+
}
|
|
501
|
+
const added = await this.#addToArchive(main, doc, item, signal)
|
|
502
|
+
archiveUrl = added.url
|
|
503
|
+
doc._pups!.archive_url = added.url
|
|
504
|
+
// The old chain of a handed-over feed now continues behind the oldest archive.
|
|
505
|
+
if (!hasArchives) delete doc.next_url
|
|
506
|
+
doc.items = this.#newestItems(added.recent, doc.items, doc)
|
|
507
|
+
await this.#writeMain(doc, main.etag, signal)
|
|
508
|
+
})
|
|
509
|
+
return this.#result(item, archiveUrl)
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
/**
|
|
513
|
+
* Finds a post by id in the archives (or, for a handed-over feed without archives yet, in the feed file).
|
|
514
|
+
* @returns undefined if there is no such post.
|
|
515
|
+
*/
|
|
516
|
+
async getPost(id: string, options: Signal = {}): Promise<PostResult | undefined> {
|
|
517
|
+
const main = await this.#read(this.path, options.signal)
|
|
518
|
+
const found = main && await this.#find(main, id, options.signal)
|
|
519
|
+
return found && this.#result(found.file.doc.items[found.index]!, this.#session.publicUrl(found.file.path))
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
/**
|
|
523
|
+
* All posts, newest first: the archives from `_pups.archive_url` along `next_url` (for a feed without archives,
|
|
524
|
+
* the feed file and its `next_url` chain). Each post is returned once.
|
|
525
|
+
*/
|
|
526
|
+
async *posts(options: Signal = {}): AsyncGenerator<FeedItem> {
|
|
527
|
+
const main = await this.#read(this.path, options.signal)
|
|
528
|
+
if (!main) return
|
|
529
|
+
const seen = new Set<string>()
|
|
530
|
+
for await (const file of this.#chain(main, options.signal))
|
|
531
|
+
for (const item of file.doc.items)
|
|
532
|
+
if (!seen.has(item.id)) {
|
|
533
|
+
seen.add(item.id)
|
|
534
|
+
yield item
|
|
535
|
+
}
|
|
536
|
+
}
|
|
537
|
+
|
|
538
|
+
/**
|
|
539
|
+
* Edits a post in its archive, and in the feed file if it is among the newest items (RFC-7 "Editing and deleting
|
|
540
|
+
* items"), and sets `date_modified`. `changes` is either an object (a value sets a field, `null` removes it), or
|
|
541
|
+
* a function that gets a copy of the item and returns the new item, or `undefined` to leave it unchanged. The
|
|
542
|
+
* function may run more than once.
|
|
543
|
+
*
|
|
544
|
+
* Apps should edit posts only when the owner asks them to, whichever app created them.
|
|
545
|
+
* @throws {PupsError} `not_found`
|
|
546
|
+
*/
|
|
547
|
+
async editPost(id: string, changes: PostChanges | ((item: FeedItem) => FeedItem | undefined | Promise<FeedItem | undefined>), options: Signal = {}): Promise<PostResult> {
|
|
548
|
+
const signal = options.signal
|
|
549
|
+
return this.#transaction(async () => {
|
|
550
|
+
const { main, file, index } = await this.#findWritable(id, signal)
|
|
551
|
+
const old = file.doc.items[index]!
|
|
552
|
+
const fileUrl = this.#session.publicUrl(file.path)
|
|
553
|
+
const changed = typeof changes == 'function' ? await changes(clone(old)) : this.#applyChanges(clone(old), changes)
|
|
554
|
+
if (!changed) return this.#result(old, fileUrl)
|
|
555
|
+
const item: FeedItem = { ...changed, id, date_modified: now() }
|
|
556
|
+
if (file != main) await this.#writeArchive(file, replaceAt(file.doc.items, index, item), signal)
|
|
557
|
+
const mainIndex = main.doc.items.findIndex(i => i.id == id)
|
|
558
|
+
if (mainIndex >= 0) await this.#writeMain({ ...main.doc, items: replaceAt(main.doc.items, mainIndex, item) }, main.etag, signal)
|
|
559
|
+
return this.#result(item, fileUrl)
|
|
560
|
+
})
|
|
561
|
+
}
|
|
562
|
+
|
|
563
|
+
/**
|
|
564
|
+
* Deletes a post from its archive and from the feed file, which is then filled up again with the newest items
|
|
565
|
+
* from the archives. With `deleteMedia`, it also deletes the files in the feed directory that the post references
|
|
566
|
+
* and no other post does; this reads all archives.
|
|
567
|
+
* @returns the deleted item, and the public URLs of the deleted media files.
|
|
568
|
+
* @throws {PupsError} `not_found`
|
|
569
|
+
*/
|
|
570
|
+
async deletePost(id: string, options: Signal & { deleteMedia?: boolean } = {}): Promise<{ item: FeedItem; deletedMedia: string[] }> {
|
|
571
|
+
const signal = options.signal
|
|
572
|
+
const item = await this.#transaction(async () => {
|
|
573
|
+
const { main, file, index } = await this.#findWritable(id, signal)
|
|
574
|
+
const item = file.doc.items[index]!
|
|
575
|
+
if (file != main) {
|
|
576
|
+
await this.#writeArchive(file, file.doc.items.filter(i => i.id != id), signal)
|
|
577
|
+
// Fill the feed file up again from the archives, which no longer contain the item.
|
|
578
|
+
const newest: FeedItem[] = []
|
|
579
|
+
for await (const archive of this.#chain(main, signal)) {
|
|
580
|
+
newest.push(...archive.doc.items.filter(i => i.id != id))
|
|
581
|
+
if (newest.length >= this.#maxItems) break
|
|
582
|
+
}
|
|
583
|
+
await this.#writeMain({ ...main.doc, items: this.#newestItems(newest, [], main.doc) }, main.etag, signal)
|
|
584
|
+
} else
|
|
585
|
+
await this.#writeMain({ ...main.doc, items: main.doc.items.filter(i => i.id != id) }, main.etag, signal)
|
|
586
|
+
return item
|
|
587
|
+
})
|
|
588
|
+
const deletedMedia: string[] = []
|
|
589
|
+
if (options.deleteMedia) {
|
|
590
|
+
const candidates = new Set(this.#mediaUrls(item))
|
|
591
|
+
if (candidates.size)
|
|
592
|
+
for await (const other of this.posts(options))
|
|
593
|
+
for (const url of this.#mediaUrls(other)) candidates.delete(url)
|
|
594
|
+
for (const url of candidates) {
|
|
595
|
+
const path = pathFromPublicUrl(this.#session.server, url)
|
|
596
|
+
if (path && await this.#deleteQuietly(path, signal)) deletedMedia.push(url)
|
|
597
|
+
}
|
|
598
|
+
}
|
|
599
|
+
return { item, deletedMedia }
|
|
600
|
+
}
|
|
601
|
+
|
|
602
|
+
// Reading
|
|
603
|
+
|
|
604
|
+
/**
|
|
605
|
+
* Reads a feed file or archive from `storage_base`.
|
|
606
|
+
* @returns undefined if it doesn't exist.
|
|
607
|
+
* @throws {PupsError} `invalid_feed` if it is not a JSON Feed.
|
|
608
|
+
*/
|
|
609
|
+
async #read(path: string, signal?: AbortSignal): Promise<Loaded | undefined> {
|
|
610
|
+
const file = await this.#session.get(path, { signal })
|
|
611
|
+
if (!file) return
|
|
612
|
+
if (!file.etag)
|
|
613
|
+
throw new PupsError('server_error', `The server sends no ETag for ${path}, so it can't be changed safely. It must expose the ETag header to browsers (RFC-6, CORS).`)
|
|
614
|
+
let doc: unknown
|
|
615
|
+
try {
|
|
616
|
+
doc = await file.json()
|
|
617
|
+
} catch {
|
|
618
|
+
// Not JSON: handled below.
|
|
619
|
+
}
|
|
620
|
+
if (!isFeedDocument(doc)) throw new PupsError('invalid_feed', `${path} is not a JSON Feed.`)
|
|
621
|
+
return { path, doc, etag: file.etag }
|
|
622
|
+
}
|
|
623
|
+
|
|
624
|
+
/** Reads a file that must exist and carry the `_pups` marker. */
|
|
625
|
+
async #readControlled(path: string, signal?: AbortSignal): Promise<Loaded> {
|
|
626
|
+
const loaded = await this.#read(path, signal)
|
|
627
|
+
if (!loaded)
|
|
628
|
+
throw new PupsError('not_found', path == this.path ? `There is no feed at ${path} yet. Set it up with create().` : `${path} doesn't exist.`)
|
|
629
|
+
if (!isControlled(loaded.doc)) throw notControlled(path)
|
|
630
|
+
return loaded
|
|
631
|
+
}
|
|
632
|
+
|
|
633
|
+
/**
|
|
634
|
+
* The files that hold all items: the archives from `_pups.archive_url` along `next_url`, as far as they are files
|
|
635
|
+
* on this server. A feed without archives yet (handed over, not posted to) holds its items in the feed file and
|
|
636
|
+
* the pages its `next_url` names.
|
|
637
|
+
*/
|
|
638
|
+
async *#chain(main: Loaded, signal?: AbortSignal): AsyncGenerator<Loaded> {
|
|
639
|
+
const visited = new Set<string>([main.path])
|
|
640
|
+
const archive = main.doc._pups?.archive_url
|
|
641
|
+
let file: Loaded | undefined = main
|
|
642
|
+
let next = archive && this.#archiveNumber(archive) !== undefined ? archive : undefined
|
|
643
|
+
if (next) file = undefined
|
|
644
|
+
else yield main
|
|
645
|
+
for (;;) {
|
|
646
|
+
if (file) next = file.doc.next_url
|
|
647
|
+
const path = next && pathFromPublicUrl(this.#session.server, next)
|
|
648
|
+
if (!path || visited.has(path)) return
|
|
649
|
+
visited.add(path)
|
|
650
|
+
try {
|
|
651
|
+
file = await this.#read(path, signal)
|
|
652
|
+
} catch (e) {
|
|
653
|
+
if (!isPupsError(e, 'invalid_feed', 'invalid_path')) throw e
|
|
654
|
+
return
|
|
655
|
+
}
|
|
656
|
+
if (!file) return
|
|
657
|
+
yield file
|
|
658
|
+
}
|
|
659
|
+
}
|
|
660
|
+
|
|
661
|
+
async #find(main: Loaded, id: string, signal?: AbortSignal): Promise<Found | undefined> {
|
|
662
|
+
for await (const file of this.#chain(main, signal)) {
|
|
663
|
+
const index = file.doc.items.findIndex(item => item.id == id)
|
|
664
|
+
if (index >= 0) return { main, file, index }
|
|
665
|
+
}
|
|
666
|
+
return
|
|
667
|
+
}
|
|
668
|
+
|
|
669
|
+
async #findWritable(id: string, signal?: AbortSignal): Promise<Found> {
|
|
670
|
+
const main = await this.#readControlled(this.path, signal)
|
|
671
|
+
const found = await this.#find(main, id, signal)
|
|
672
|
+
if (!found) throw new PupsError('not_found', `There is no post with the id "${id}" in ${this.path} or its archives.`)
|
|
673
|
+
if (!isControlled(found.file.doc)) throw notControlled(found.file.path)
|
|
674
|
+
return found
|
|
675
|
+
}
|
|
676
|
+
|
|
677
|
+
// Writing
|
|
678
|
+
|
|
679
|
+
/** Runs `operation` again when another client changed a file in between, up to `maxAttempts` times. */
|
|
680
|
+
async #transaction<T>(operation: () => Promise<T>): Promise<T> {
|
|
681
|
+
for (let attempt = 1; ; attempt++)
|
|
682
|
+
try {
|
|
683
|
+
return await operation()
|
|
684
|
+
} catch (e) {
|
|
685
|
+
if (!isPupsError(e, 'precondition_failed') || attempt >= this.#maxAttempts) throw e
|
|
686
|
+
}
|
|
687
|
+
}
|
|
688
|
+
|
|
689
|
+
/**
|
|
690
|
+
* Writes the feed file. Sets the fixed fields, so that a feed the owner handed over gets them on its first write,
|
|
691
|
+
* and upgrades JSON Feed 1.0 (RFC-7 "Handing over an existing feed"). The optional `next_url` of a feed with
|
|
692
|
+
* archives is kept equal to `archive_url` (RFC-7 "Reading").
|
|
693
|
+
*/
|
|
694
|
+
async #writeMain(doc: FeedDocument, etag: string, signal?: AbortSignal): Promise<FeedDocument> {
|
|
695
|
+
const { author, ...rest } = doc
|
|
696
|
+
const fixed: FeedDocument = {
|
|
697
|
+
...rest,
|
|
698
|
+
version: JSON_FEED_VERSION,
|
|
699
|
+
home_page_url: this.#session.me,
|
|
700
|
+
feed_url: this.url,
|
|
701
|
+
user_comment: mainComment,
|
|
702
|
+
}
|
|
703
|
+
if (author !== undefined && fixed.authors === undefined) fixed.authors = [author as FeedAuthor]
|
|
704
|
+
if (fixed.next_url !== undefined && this.#archiveNumber(fixed._pups?.archive_url) !== undefined) fixed.next_url = fixed._pups!.archive_url
|
|
705
|
+
await this.#session.replace(this.path, serialize(fixed), etag, { contentType: FEED_CONTENT_TYPE, signal })
|
|
706
|
+
return fixed
|
|
707
|
+
}
|
|
708
|
+
|
|
709
|
+
async #writeArchive(archive: Loaded, items: FeedItem[], signal?: AbortSignal) {
|
|
710
|
+
await this.#session.replace(archive.path, serialize({ ...archive.doc, items }), archive.etag, { contentType: FEED_CONTENT_TYPE, signal })
|
|
711
|
+
}
|
|
712
|
+
|
|
713
|
+
/**
|
|
714
|
+
* The items of the feed file: the newest archive items first (which also repairs items an interrupted post wrote
|
|
715
|
+
* only into the archive), then the other items of the feed file, at most `maxItems`, fewer if `maxBytes` is set
|
|
716
|
+
* and exceeded, but at least 10.
|
|
717
|
+
*/
|
|
718
|
+
#newestItems(recent: FeedItem[], current: FeedItem[], doc: FeedDocument): FeedItem[] {
|
|
719
|
+
const ids = new Set(recent.map(item => item.id))
|
|
720
|
+
const items = [...recent, ...current.filter(item => !ids.has(item.id))].slice(0, this.#maxItems)
|
|
721
|
+
if (this.#maxBytes)
|
|
722
|
+
while (items.length > minFeedItems && byteLength(serialize({ ...doc, items })) > this.#maxBytes) items.pop()
|
|
723
|
+
return items
|
|
724
|
+
}
|
|
725
|
+
|
|
726
|
+
// Archives
|
|
727
|
+
|
|
728
|
+
#archivePath(n: number) {
|
|
729
|
+
return `${this.directory}feed.${String(n).padStart(6, '0')}.json`
|
|
730
|
+
}
|
|
731
|
+
|
|
732
|
+
#archiveUrl(n: number) {
|
|
733
|
+
return this.#session.publicUrl(this.#archivePath(n))
|
|
734
|
+
}
|
|
735
|
+
|
|
736
|
+
/** The number of the archive at `url`, or undefined if `url` is not an archive file of this feed. */
|
|
737
|
+
#archiveNumber(url: string | undefined): number | undefined {
|
|
738
|
+
const path = url && pathFromPublicUrl(this.#session.server, url)
|
|
739
|
+
if (!path?.startsWith(this.directory)) return
|
|
740
|
+
const match = /^feed\.(\d{6})\.json$/.exec(path.slice(this.directory.length))
|
|
741
|
+
return match ? Number(match[1]) : undefined
|
|
742
|
+
}
|
|
743
|
+
|
|
744
|
+
/** A new archive with the feed fields of the feed file (RFC-7 "Archives"). */
|
|
745
|
+
#newArchive(n: number, main: FeedDocument, items: FeedItem[], nextUrl: string | undefined): FeedDocument {
|
|
746
|
+
const { items: _items, next_url: _next, user_comment: _comment, hubs: _hubs, author: _author, _pups, ...fields } = main
|
|
747
|
+
const { archive_url: _archive, ...marker } = _pups ?? {}
|
|
748
|
+
const podcast = fields._podcast
|
|
749
|
+
if (isObject(podcast) && 'liveItems' in podcast) {
|
|
750
|
+
const { liveItems: _live, ...rest } = podcast
|
|
751
|
+
fields._podcast = rest
|
|
752
|
+
}
|
|
753
|
+
return {
|
|
754
|
+
...fields,
|
|
755
|
+
version: JSON_FEED_VERSION,
|
|
756
|
+
home_page_url: this.#session.me,
|
|
757
|
+
feed_url: this.#archiveUrl(n),
|
|
758
|
+
user_comment: archiveComment(this.url),
|
|
759
|
+
...nextUrl ? { next_url: nextUrl } : {},
|
|
760
|
+
items,
|
|
761
|
+
_pups: { about: PUPS_FEED_SPEC, ...marker, pupsControlled: true, updates_url: this.url },
|
|
762
|
+
}
|
|
763
|
+
}
|
|
764
|
+
|
|
765
|
+
async #createArchive(n: number, main: FeedDocument, items: FeedItem[], nextUrl: string | undefined, signal?: AbortSignal) {
|
|
766
|
+
await this.#session.create(this.#archivePath(n), serialize(this.#newArchive(n, main, items, nextUrl)), { contentType: FEED_CONTENT_TYPE, signal })
|
|
767
|
+
}
|
|
768
|
+
|
|
769
|
+
/**
|
|
770
|
+
* Reads an archive for writing.
|
|
771
|
+
* @returns undefined if it doesn't exist, 'foreign' if it exists but is no PUPS archive.
|
|
772
|
+
*/
|
|
773
|
+
async #readArchive(path: string, signal?: AbortSignal): Promise<Loaded | 'foreign' | undefined> {
|
|
774
|
+
try {
|
|
775
|
+
const loaded = await this.#read(path, signal)
|
|
776
|
+
return loaded && !isControlled(loaded.doc) ? 'foreign' : loaded
|
|
777
|
+
} catch (e) {
|
|
778
|
+
if (isPupsError(e, 'invalid_feed')) return 'foreign'
|
|
779
|
+
throw e
|
|
780
|
+
}
|
|
781
|
+
}
|
|
782
|
+
|
|
783
|
+
/**
|
|
784
|
+
* Puts the items of a feed without archives into new archives of `archiveSize`, oldest first (RFC-7 "Starting the
|
|
785
|
+
* archives"). The oldest archive continues the feed's `next_url` chain.
|
|
786
|
+
* @returns the URL of the newest archive, or undefined if the feed has no items.
|
|
787
|
+
*/
|
|
788
|
+
async #startArchives(main: Loaded, signal?: AbortSignal): Promise<string | undefined> {
|
|
789
|
+
const oldestFirst = [...main.doc.items].reverse()
|
|
790
|
+
let url: string | undefined
|
|
791
|
+
for (let n = 0; n * this.#archiveSize < oldestFirst.length; n++) {
|
|
792
|
+
const items = oldestFirst.slice(n * this.#archiveSize, (n + 1) * this.#archiveSize).reverse()
|
|
793
|
+
const nextUrl = n ? this.#archiveUrl(n - 1) : main.doc.next_url
|
|
794
|
+
try {
|
|
795
|
+
await this.#createArchive(n, main.doc, items, nextUrl, signal)
|
|
796
|
+
} catch (e) {
|
|
797
|
+
if (!isPupsError(e, 'precondition_failed')) throw e
|
|
798
|
+
// Left behind by an interrupted start: complete it, as long as it holds only these items.
|
|
799
|
+
const existing = await this.#readArchive(this.#archivePath(n), signal)
|
|
800
|
+
const ids = new Set(items.map(item => item.id))
|
|
801
|
+
if (!existing || existing == 'foreign' || !existing.doc.items.every(item => ids.has(item.id)))
|
|
802
|
+
throw new PupsError('conflict', `${this.#archivePath(n)} exists already, but ${this.path} has no archive_url. Remove the file, or set _pups.archive_url (RFC-7, Starting the archives).`)
|
|
803
|
+
await this.#writeArchive(existing, items, signal)
|
|
804
|
+
}
|
|
805
|
+
url = this.#archiveUrl(n)
|
|
806
|
+
}
|
|
807
|
+
return url
|
|
808
|
+
}
|
|
809
|
+
|
|
810
|
+
/**
|
|
811
|
+
* Adds an item to the newest archive, or to a new archive if the newest holds `archiveSize` items (RFC-7
|
|
812
|
+
* "Posting"). Writes only archives; the caller writes the feed file afterwards.
|
|
813
|
+
* @returns the archive's URL, and the newest items known from the archives, newest first.
|
|
814
|
+
*/
|
|
815
|
+
async #addToArchive(main: Loaded, doc: FeedDocument, item: FeedItem, signal?: AbortSignal): Promise<{ url: string; recent: FeedItem[] }> {
|
|
816
|
+
const newest = this.#archiveNumber(doc._pups?.archive_url)
|
|
817
|
+
let previous: FeedItem[] = []
|
|
818
|
+
if (newest !== undefined) {
|
|
819
|
+
const existing = await this.#readArchive(this.#archivePath(newest), signal)
|
|
820
|
+
if (!existing) {
|
|
821
|
+
// The owner deleted it: create it again, linked to the next older archive.
|
|
822
|
+
await this.#createArchive(newest, doc, [item], newest ? this.#archiveUrl(newest - 1) : undefined, signal)
|
|
823
|
+
return { url: this.#archiveUrl(newest), recent: [item] }
|
|
824
|
+
}
|
|
825
|
+
if (existing != 'foreign') {
|
|
826
|
+
const merged = mergeItems(existing.doc.items, [item])
|
|
827
|
+
if (merged.length <= this.#archiveSize) {
|
|
828
|
+
await this.#writeArchive(existing, merged, signal)
|
|
829
|
+
return { url: this.#archiveUrl(newest), recent: merged }
|
|
830
|
+
}
|
|
831
|
+
previous = existing.doc.items
|
|
832
|
+
}
|
|
833
|
+
}
|
|
834
|
+
// The archive before the new one: the newest, or for a feed without archives the end of its old chain.
|
|
835
|
+
const nextUrl = newest === undefined ? doc.next_url : this.#archiveUrl(newest)
|
|
836
|
+
for (let n = newest === undefined ? 0 : newest + 1; n <= maxArchiveNumber; n++) {
|
|
837
|
+
try {
|
|
838
|
+
await this.#createArchive(n, doc, [item], nextUrl, signal)
|
|
839
|
+
return { url: this.#archiveUrl(n), recent: [item, ...previous] }
|
|
840
|
+
} catch (e) {
|
|
841
|
+
if (!isPupsError(e, 'precondition_failed')) throw e
|
|
842
|
+
}
|
|
843
|
+
// The archive exists: left behind by an interrupted client, or created by another client just now.
|
|
844
|
+
const existing = await this.#readArchive(this.#archivePath(n), signal)
|
|
845
|
+
if (existing && existing != 'foreign' && existing.doc.next_url == nextUrl) {
|
|
846
|
+
const merged = mergeItems(existing.doc.items, [item])
|
|
847
|
+
if (merged.length <= this.#archiveSize) {
|
|
848
|
+
await this.#writeArchive(existing, merged, signal)
|
|
849
|
+
return { url: this.#archiveUrl(n), recent: [...merged, ...previous] }
|
|
850
|
+
}
|
|
851
|
+
}
|
|
852
|
+
const current = await this.#session.get(this.path, { signal })
|
|
853
|
+
if (current?.etag != main.etag) throw conflict(this.path)
|
|
854
|
+
}
|
|
855
|
+
throw new PupsError('conflict', `No free archive number in ${this.directory}.`)
|
|
856
|
+
}
|
|
857
|
+
|
|
858
|
+
// Items and media
|
|
859
|
+
|
|
860
|
+
#newItem(input: PostInput): FeedItem {
|
|
861
|
+
const { id, markdown, date_published, ...fields } = input
|
|
862
|
+
if (id !== undefined && (typeof id != 'string' || !id))
|
|
863
|
+
throw new PupsError('invalid_request', 'A post id must be a non-empty string.')
|
|
864
|
+
const item: FeedItem = {
|
|
865
|
+
id: id ?? randomString(12),
|
|
866
|
+
...fields,
|
|
867
|
+
date_published: date_published instanceof Date ? date_published.toISOString() : date_published ?? now(),
|
|
868
|
+
}
|
|
869
|
+
if (markdown !== undefined) this.#setMarkdown(item, markdown)
|
|
870
|
+
if (item.content_html === undefined && item.content_text === undefined)
|
|
871
|
+
throw new PupsError('invalid_request', 'A post needs content_html, content_text or markdown (JSON Feed requires content).')
|
|
872
|
+
return item
|
|
873
|
+
}
|
|
874
|
+
|
|
875
|
+
#applyChanges(item: FeedItem, changes: PostChanges): FeedItem {
|
|
876
|
+
for (const [key, value] of Object.entries(changes)) {
|
|
877
|
+
if (key == 'id') throw new PupsError('invalid_request', 'The id of a post can\'t be changed.')
|
|
878
|
+
if (value === undefined) continue
|
|
879
|
+
if (key == 'markdown') {
|
|
880
|
+
if (value === null) {
|
|
881
|
+
const source = isObject(item._source) ? { ...item._source } : undefined
|
|
882
|
+
if (source) {
|
|
883
|
+
delete source.markdown
|
|
884
|
+
item._source = source
|
|
885
|
+
}
|
|
886
|
+
} else this.#setMarkdown(item, value as string)
|
|
887
|
+
} else if (value === null) delete item[key]
|
|
888
|
+
else item[key] = value instanceof Date ? value.toISOString() : value
|
|
889
|
+
}
|
|
890
|
+
if (item.content_html === undefined && item.content_text === undefined)
|
|
891
|
+
throw new PupsError('invalid_request', 'A post needs content_html or content_text (JSON Feed requires content).')
|
|
892
|
+
return item
|
|
893
|
+
}
|
|
894
|
+
|
|
895
|
+
/** Stores Markdown in `_source.markdown` (RFC-1), with `content_text` as the fallback JSON Feed requires. */
|
|
896
|
+
#setMarkdown(item: FeedItem, markdown: string) {
|
|
897
|
+
const source = isObject(item._source) ? item._source : {}
|
|
898
|
+
item._source = { about: RFC1_URL, ...source, markdown }
|
|
899
|
+
if (item.content_html === undefined) item.content_text = markdown
|
|
900
|
+
}
|
|
901
|
+
|
|
902
|
+
#result(item: FeedItem, fileUrl: string): PostResult {
|
|
903
|
+
return { id: item.id, item, url: `${fileUrl}#${encodeURIComponent(item.id)}` }
|
|
904
|
+
}
|
|
905
|
+
|
|
906
|
+
/**
|
|
907
|
+
* The URLs of this feed's media files (not icons, not archives) that an item references. For the main feed, only
|
|
908
|
+
* `/feed/images/` and `/feed/media/`, so that files of named feeds are never taken for its own.
|
|
909
|
+
*/
|
|
910
|
+
#mediaUrls(item: FeedItem): string[] {
|
|
911
|
+
const base = this.#session.publicUrl(this.directory)
|
|
912
|
+
const bases = this.name === undefined ? mainMediaFolders.map(folder => `${base}${folder}/`) : [base]
|
|
913
|
+
const icons = `${base}images/icons/`
|
|
914
|
+
const urls = new Set<string>()
|
|
915
|
+
for (const text of strings(item))
|
|
916
|
+
for (const [url] of text.matchAll(/https?:\/\/[^\s"'<>()]+/g))
|
|
917
|
+
if (bases.some(b => url.startsWith(b)) && !url.startsWith(icons) && this.#archiveNumber(url) === undefined) urls.add(url)
|
|
918
|
+
return [...urls]
|
|
919
|
+
}
|
|
920
|
+
|
|
921
|
+
#mediaType(media: MediaInput): { type: string; extension: string; body: Body } {
|
|
922
|
+
const blob = typeof Blob != 'undefined' && media instanceof Blob ? media : undefined
|
|
923
|
+
const given = blob ? undefined : media as { body: Body; type?: string; extension?: string }
|
|
924
|
+
const nameExtension = (blob as File | undefined)?.name?.match(/\.([a-z0-9]+)$/i)?.[1]
|
|
925
|
+
const type = blob?.type || given?.type
|
|
926
|
+
const extension = (given?.extension ?? nameExtension ?? (type ? extensionForType(type) : undefined))?.toLowerCase().replace(/^\./, '')
|
|
927
|
+
const fileType = extension ? fileTypes[extension] : undefined
|
|
928
|
+
if (!extension || !fileType)
|
|
929
|
+
throw new PupsError('unsupported_type', `Can't tell the file type of the upload${extension ? ` (".${extension}" is not allowed)` : ''}. Pass a Blob with a type, or { body, type } or { body, extension } (RFC-6, File types).`)
|
|
930
|
+
return { type: fileType.served, extension, body: blob ?? given!.body }
|
|
931
|
+
}
|
|
932
|
+
|
|
933
|
+
async #upload(media: MediaInput, prefix: string, signal?: AbortSignal): Promise<MediaResult> {
|
|
934
|
+
const { type, extension, body } = this.#mediaType(media)
|
|
935
|
+
const path = `${this.directory}${prefix}${randomString(9)}.${extension}`
|
|
936
|
+
const result = await this.#session.create(path, body, { signal })
|
|
937
|
+
const size = typeof body == 'string' ? byteLength(body) : body instanceof Blob ? body.size : (body as ArrayBuffer | ArrayBufferView).byteLength
|
|
938
|
+
return { path, url: result.url, type, size }
|
|
939
|
+
}
|
|
940
|
+
|
|
941
|
+
async #setImage(field: 'icon' | 'favicon', media: MediaInput | null, signal?: AbortSignal): Promise<FeedDocument> {
|
|
942
|
+
const uploaded = media ? await this.#upload(media, `images/icons/${field}-`, signal) : undefined
|
|
943
|
+
let old: unknown
|
|
944
|
+
let doc: FeedDocument
|
|
945
|
+
try {
|
|
946
|
+
doc = await this.#transaction(async () => {
|
|
947
|
+
const main = await this.#readControlled(this.path, signal)
|
|
948
|
+
old = main.doc[field]
|
|
949
|
+
const changed = { ...main.doc }
|
|
950
|
+
if (uploaded) changed[field] = uploaded.url
|
|
951
|
+
else delete changed[field]
|
|
952
|
+
return this.#writeMain(changed, main.etag, signal)
|
|
953
|
+
})
|
|
954
|
+
} catch (e) {
|
|
955
|
+
if (uploaded) await this.#deleteQuietly(uploaded.path)
|
|
956
|
+
throw e
|
|
957
|
+
}
|
|
958
|
+
const oldPath = typeof old == 'string' && old != uploaded?.url ? pathFromPublicUrl(this.#session.server, old) : undefined
|
|
959
|
+
if (oldPath?.startsWith(`${this.directory}images/icons/`)) await this.#deleteQuietly(oldPath, signal)
|
|
960
|
+
return doc
|
|
961
|
+
}
|
|
962
|
+
|
|
963
|
+
/** Deletes a file, ignoring a missing one. @returns whether it was deleted. */
|
|
964
|
+
async #deleteQuietly(path: string, signal?: AbortSignal): Promise<boolean> {
|
|
965
|
+
try {
|
|
966
|
+
await this.#session.delete(path, { signal })
|
|
967
|
+
return true
|
|
968
|
+
} catch (e) {
|
|
969
|
+
if (isPupsError(e, 'not_found')) return false
|
|
970
|
+
throw e
|
|
971
|
+
}
|
|
972
|
+
}
|
|
973
|
+
|
|
974
|
+
#checkSettings(settings: Record<string, unknown>) {
|
|
975
|
+
for (const key of Object.keys(settings))
|
|
976
|
+
if (reservedFields.has(key))
|
|
977
|
+
throw new PupsError('invalid_request', key == 'icon' || key == 'favicon'
|
|
978
|
+
? `Set ${key} with ${key == 'icon' ? 'setIcon' : 'setFavicon'}(), which stores it in images/icons/ (RFC-7, Icons).`
|
|
979
|
+
: `"${key}" is fixed or managed by RFC-7 and can't be set.`)
|
|
980
|
+
else if (!['title', 'description', 'authors', 'language', 'expired'].includes(key) && !key.startsWith('_'))
|
|
981
|
+
throw new PupsError('invalid_request', `"${key}" is not a feed field the owner can set. Use title, description, authors, language, expired or an extension starting with "_".`)
|
|
982
|
+
}
|
|
983
|
+
|
|
984
|
+
#checkWritable() {
|
|
985
|
+
if (!this.writable)
|
|
986
|
+
throw new PupsError('insufficient_scope', `Writing ${this.path} needs the scopes ${this.scopes.join(' ')} (RFC-7, Server requirements).`)
|
|
987
|
+
}
|
|
988
|
+
}
|
|
989
|
+
|
|
990
|
+
/** The feeds registered in the owner's `host-meta.json` (RFC-7 "Registering feeds"). */
|
|
991
|
+
export async function listFeeds(session: PupsSession, options: Signal & FeedOptions = {}): Promise<FeedLink[]> {
|
|
992
|
+
const document = await session.hostMeta.get(options)
|
|
993
|
+
const links = (document.links ?? []).filter(link => link.rel == FEED_REL && typeof link.href == 'string')
|
|
994
|
+
return links.map(link => {
|
|
995
|
+
const url = link.href!
|
|
996
|
+
const path = pathFromPublicUrl(session.server, url)
|
|
997
|
+
const name = path == '/feed.json' ? null : /^\/feed\/([^/]+)\.json$/.exec(path ?? '')?.[1]
|
|
998
|
+
let feed: PupsFeed | undefined
|
|
999
|
+
if (name !== undefined)
|
|
1000
|
+
try {
|
|
1001
|
+
feed = new PupsFeed(session, name ?? undefined, options)
|
|
1002
|
+
} catch {
|
|
1003
|
+
// Not a valid feed name, e.g. an archive or a link the owner added.
|
|
1004
|
+
}
|
|
1005
|
+
return { url, ...typeof link.type == 'string' ? { type: link.type } : {}, ...feed ? { feed } : {} }
|
|
1006
|
+
})
|
|
1007
|
+
}
|