@mccaskie-labs/workbench-library 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/CHANGELOG.md +11 -0
- package/README.md +62 -2
- package/dist/access.d.ts +7 -0
- package/dist/access.js +46 -0
- package/dist/cli.d.ts +12 -0
- package/dist/cli.js +142 -0
- package/dist/config.d.ts +7 -0
- package/dist/config.js +84 -0
- package/dist/embed.d.ts +6 -0
- package/dist/embed.js +53 -0
- package/dist/errors.d.ts +5 -0
- package/dist/errors.js +11 -0
- package/dist/feed.d.ts +14 -0
- package/dist/feed.js +74 -0
- package/dist/index.d.ts +12 -0
- package/dist/index.js +16 -0
- package/dist/library.d.ts +156 -0
- package/dist/library.js +422 -0
- package/dist/links.d.ts +37 -0
- package/dist/links.js +68 -0
- package/dist/migration.d.ts +4 -0
- package/dist/migration.js +619 -0
- package/dist/sponsors.d.ts +3 -0
- package/dist/sponsors.js +8 -0
- package/dist/starters.d.ts +20 -0
- package/dist/starters.js +16 -0
- package/dist/styles.d.ts +33 -0
- package/dist/styles.js +86 -0
- package/dist/text.d.ts +3 -0
- package/dist/text.js +26 -0
- package/dist/time.d.ts +6 -0
- package/dist/time.js +36 -0
- package/dist/types.d.ts +245 -0
- package/dist/types.js +3 -0
- package/dist/ui.d.ts +42 -0
- package/dist/ui.js +148 -0
- package/dist/words.d.ts +4 -0
- package/dist/words.js +128 -0
- package/package.json +52 -4
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
import { type LibraryBucket } from "./links.ts";
|
|
2
|
+
import type { AccessRule, Collection, CollectionKind, CollectionView, Item, LibraryConfig, LibraryFile, Locked, MineEntry, Opened, ProgressMark, Purchase, ShowDetails, Sponsor, TickResult, Viewer } from "./types.ts";
|
|
3
|
+
type DbError = {
|
|
4
|
+
message?: string;
|
|
5
|
+
code?: string;
|
|
6
|
+
details?: string;
|
|
7
|
+
} | null;
|
|
8
|
+
/** The part of a Supabase client the package needs. Any supabase-js client fits; use the service client. */
|
|
9
|
+
export interface LibraryClient {
|
|
10
|
+
rpc(fn: string, args: Record<string, unknown>): PromiseLike<{
|
|
11
|
+
data: unknown;
|
|
12
|
+
error: DbError;
|
|
13
|
+
}>;
|
|
14
|
+
}
|
|
15
|
+
export interface LibraryOptions<C extends LibraryConfig> {
|
|
16
|
+
db: LibraryClient;
|
|
17
|
+
/** LIBRARY from src/library.generated.ts (`npx workbench-library generate`). */
|
|
18
|
+
config: C;
|
|
19
|
+
/** LIBRARY_SECRET, a Worker secret of at least 32 random characters. Gated file links are signed with it. */
|
|
20
|
+
secret: string;
|
|
21
|
+
/** The clock, for tests. */
|
|
22
|
+
now?: () => Date;
|
|
23
|
+
}
|
|
24
|
+
export interface NewCollection {
|
|
25
|
+
/** Leave out to make a new one. */
|
|
26
|
+
id?: string;
|
|
27
|
+
/** Lower-case letters, digits and hyphens: the address, /learn/<slug>. */
|
|
28
|
+
slug: string;
|
|
29
|
+
kind: CollectionKind;
|
|
30
|
+
title: string;
|
|
31
|
+
summary?: string | null;
|
|
32
|
+
/** A picture file's id (addFile): the show's cover art or the course's picture. */
|
|
33
|
+
coverFile?: string | null;
|
|
34
|
+
access: AccessRule;
|
|
35
|
+
/** For access "feature": the workbench-plans feature, such as "courses". */
|
|
36
|
+
feature?: string | null;
|
|
37
|
+
/** For access "bought": the price in cents, and how long it lasts (null: for good). */
|
|
38
|
+
priceCents?: number | null;
|
|
39
|
+
accessMonths?: number | null;
|
|
40
|
+
status?: "draft" | "published";
|
|
41
|
+
/** For a show: the feed's details. */
|
|
42
|
+
show?: Partial<ShowDetails> | null;
|
|
43
|
+
}
|
|
44
|
+
export interface NewItem {
|
|
45
|
+
id?: string;
|
|
46
|
+
/** The collection's slug. */
|
|
47
|
+
collection: string;
|
|
48
|
+
slug: string;
|
|
49
|
+
title: string;
|
|
50
|
+
body?: string;
|
|
51
|
+
/** A YouTube or Vimeo address to embed, or a file's id (addFile), or neither. */
|
|
52
|
+
embed?: string | null;
|
|
53
|
+
file?: string | null;
|
|
54
|
+
seconds?: number | null;
|
|
55
|
+
/** Leave out to put it last. */
|
|
56
|
+
position?: number;
|
|
57
|
+
preview?: boolean;
|
|
58
|
+
/** A course lesson that opens this many days after the person started. */
|
|
59
|
+
dripDays?: number | null;
|
|
60
|
+
/** When it appears; null: as soon as it's published. */
|
|
61
|
+
publishAt?: Date | string | null;
|
|
62
|
+
status?: "draft" | "published";
|
|
63
|
+
episode?: number | null;
|
|
64
|
+
season?: number | null;
|
|
65
|
+
}
|
|
66
|
+
export interface NewSponsor {
|
|
67
|
+
id?: string;
|
|
68
|
+
/** The show's slug. */
|
|
69
|
+
collection: string;
|
|
70
|
+
name: string;
|
|
71
|
+
url?: string | null;
|
|
72
|
+
message: string;
|
|
73
|
+
/** YYYY-MM-DD, both days included, in the project's time zone. */
|
|
74
|
+
startsOn: string;
|
|
75
|
+
endsOn: string;
|
|
76
|
+
}
|
|
77
|
+
export interface Library {
|
|
78
|
+
saveCollection(c: NewCollection): Promise<Collection>;
|
|
79
|
+
/** Deletes a collection with its items, sponsors and access rows, and the files only it used (from the bucket too). */
|
|
80
|
+
deleteCollection(slug: string, bucket: LibraryBucket): Promise<{
|
|
81
|
+
files: number;
|
|
82
|
+
}>;
|
|
83
|
+
/** Every collection, drafts too: for the owner. Visitors' lists come from view(). */
|
|
84
|
+
collections(): Promise<Collection[]>;
|
|
85
|
+
saveItem(i: NewItem): Promise<Item>;
|
|
86
|
+
deleteItem(id: string, bucket: LibraryBucket): Promise<{
|
|
87
|
+
deleted: boolean;
|
|
88
|
+
}>;
|
|
89
|
+
/** Streams an upload into the bucket and records it. Refuses a type or size workbench/library.json doesn't allow. */
|
|
90
|
+
addFile(bucket: LibraryBucket, f: {
|
|
91
|
+
body: ReadableStream | ArrayBuffer | Uint8Array;
|
|
92
|
+
name: string;
|
|
93
|
+
type: string;
|
|
94
|
+
bytes: number;
|
|
95
|
+
}): Promise<LibraryFile>;
|
|
96
|
+
/** Deletes a file nothing uses, from the bucket too. */
|
|
97
|
+
deleteFile(id: string, bucket: LibraryBucket): Promise<void>;
|
|
98
|
+
saveSponsor(s: NewSponsor): Promise<Sponsor>;
|
|
99
|
+
deleteSponsor(id: string): Promise<boolean>;
|
|
100
|
+
/** A collection as this viewer sees it, or null when there's no such published collection. */
|
|
101
|
+
view(viewer: Viewer, slug: string, o?: {
|
|
102
|
+
done?: ReadonlySet<string>;
|
|
103
|
+
}): Promise<CollectionView | null>;
|
|
104
|
+
/** One item, its media ready to draw (gated files get a signed link), or why it's locked. Null: no such item for this viewer. */
|
|
105
|
+
open(viewer: Viewer, slug: string, item: string, o?: {
|
|
106
|
+
done?: ReadonlySet<string>;
|
|
107
|
+
}): Promise<Opened | null>;
|
|
108
|
+
/** Starts the member on a collection they may see; dripped lessons count from this day. Twice is a no-op. */
|
|
109
|
+
enrol(viewer: Viewer, slug: string): Promise<{
|
|
110
|
+
ok: true;
|
|
111
|
+
started_at: string;
|
|
112
|
+
} | Locked>;
|
|
113
|
+
/** The member finished an item they may open: answers the mark to pass to progress' mark(). */
|
|
114
|
+
finished(viewer: Viewer, slug: string, item: string): Promise<{
|
|
115
|
+
ok: true;
|
|
116
|
+
mark: ProgressMark;
|
|
117
|
+
} | Locked>;
|
|
118
|
+
/** A signed link to a file, valid for link_minutes. */
|
|
119
|
+
fileUrl(file: string): Promise<string>;
|
|
120
|
+
/** Answers a request to <paths.files>/<id>: checks the link, then streams from R2 with Range support. */
|
|
121
|
+
serveFile(request: Request, bucket: LibraryBucket): Promise<Response>;
|
|
122
|
+
/** The RSS podcast feed of a published show open to everyone, or null. origin: "https://example.com". */
|
|
123
|
+
feed(slug: string, o: {
|
|
124
|
+
origin: string;
|
|
125
|
+
}): Promise<string | null>;
|
|
126
|
+
/** The invoice line and source for buying a collection. */
|
|
127
|
+
purchase(slug: string): Promise<Purchase>;
|
|
128
|
+
/** From the payments tool's "paid" outcome only: lets the member in, once per payment. */
|
|
129
|
+
grant(o: {
|
|
130
|
+
collection: string;
|
|
131
|
+
member: string;
|
|
132
|
+
ref: string;
|
|
133
|
+
}): Promise<{
|
|
134
|
+
repeat: boolean;
|
|
135
|
+
started_at: string;
|
|
136
|
+
ends_at: string | null;
|
|
137
|
+
}>;
|
|
138
|
+
/** After a refund: takes the access the payment gave away. */
|
|
139
|
+
revoke(ref: string): Promise<{
|
|
140
|
+
revoked: boolean;
|
|
141
|
+
}>;
|
|
142
|
+
/** What the member has started or bought, for the "My account" page. */
|
|
143
|
+
mine(member: string): Promise<MineEntry[]>;
|
|
144
|
+
/** Deletes everything kept about a member (their account is deleted). */
|
|
145
|
+
forget(member: string): Promise<{
|
|
146
|
+
deleted: number;
|
|
147
|
+
}>;
|
|
148
|
+
/** From the app's cron (hourly is plenty): the dripped lessons and scheduled items that opened since the last tick, once each; then cleanup(). */
|
|
149
|
+
tick(): Promise<TickResult>;
|
|
150
|
+
/** Deletes access rows retention.ended_access_days after they ended or were revoked. */
|
|
151
|
+
cleanup(): Promise<{
|
|
152
|
+
deleted: number;
|
|
153
|
+
}>;
|
|
154
|
+
}
|
|
155
|
+
export declare function createLibrary<const C extends LibraryConfig>(opts: LibraryOptions<C>): Library;
|
|
156
|
+
export {};
|
package/dist/library.js
ADDED
|
@@ -0,0 +1,422 @@
|
|
|
1
|
+
// createLibrary: courses, shows and shelves in the app's own database
|
|
2
|
+
// (libraryMigration), with files in the app's own R2 bucket, checked against
|
|
3
|
+
// the repo's workbench/library.json. Use it with the service client, server
|
|
4
|
+
// side: the functions are the service role's only (see migration.ts). The
|
|
5
|
+
// app says who is looking (Viewer) and the package decides what they see.
|
|
6
|
+
import { collectionLock, entries } from "./access.js";
|
|
7
|
+
import { checkLibrary } from "./config.js";
|
|
8
|
+
import { embedFor } from "./embed.js";
|
|
9
|
+
import { LibraryError } from "./errors.js";
|
|
10
|
+
import { podcastFeed } from "./feed.js";
|
|
11
|
+
import { parseRange, readLink, signedPath } from "./links.js";
|
|
12
|
+
import { sponsorsFor } from "./sponsors.js";
|
|
13
|
+
import { validDate } from "./time.js";
|
|
14
|
+
function failed(what, error) {
|
|
15
|
+
const m = error?.message ?? "";
|
|
16
|
+
if (m.includes("library_not_found"))
|
|
17
|
+
throw new LibraryError("not_found", `${what}: not found`);
|
|
18
|
+
if (m.includes("library_slug_taken"))
|
|
19
|
+
throw new LibraryError("bad_input", `${what}: that address (slug) is already used`);
|
|
20
|
+
if (m.includes("library_ref_reused"))
|
|
21
|
+
throw new LibraryError("ref_reused", `${what}: this payment ref already let another member or collection in`);
|
|
22
|
+
if (m.includes("library_sponsor_overlap"))
|
|
23
|
+
throw new LibraryError("overlap", `${what}: another sponsor slot on this show covers some of those dates`);
|
|
24
|
+
if (m.includes("library_file_in_use"))
|
|
25
|
+
throw new LibraryError("bad_input", `${what}: an item or a cover still uses this file`);
|
|
26
|
+
throw new LibraryError("store_failed", `${what}: ${m || "no answer"}${error?.code ? ` (${error.code})` : ""}`);
|
|
27
|
+
}
|
|
28
|
+
async function call(db, what, fn, args) {
|
|
29
|
+
const { data, error } = await db.rpc(fn, args);
|
|
30
|
+
if (error)
|
|
31
|
+
failed(what, error);
|
|
32
|
+
return data;
|
|
33
|
+
}
|
|
34
|
+
const SLUG = /^[a-z0-9]([a-z0-9-]{0,78}[a-z0-9])?$/;
|
|
35
|
+
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
|
|
36
|
+
function text(v, what, max = 200, min = 1) {
|
|
37
|
+
if (typeof v !== "string" || v.trim().length < min || v.length > max)
|
|
38
|
+
throw new LibraryError("bad_input", `${what} must be text, ${min} to ${max} characters`);
|
|
39
|
+
return v;
|
|
40
|
+
}
|
|
41
|
+
const maybe = (v, what, max) => (v === null || v === undefined || v === "" ? null : text(v, what, max));
|
|
42
|
+
function slug(v, what = "slug") {
|
|
43
|
+
if (typeof v !== "string" || !SLUG.test(v))
|
|
44
|
+
throw new LibraryError("bad_input", `${what} must be lower-case letters, digits and hyphens, such as "start-here"`);
|
|
45
|
+
return v;
|
|
46
|
+
}
|
|
47
|
+
function id(v, what) {
|
|
48
|
+
if (typeof v !== "string" || !UUID.test(v))
|
|
49
|
+
throw new LibraryError("bad_input", `${what} must be an id`);
|
|
50
|
+
return v;
|
|
51
|
+
}
|
|
52
|
+
function whole(v, what, min, max) {
|
|
53
|
+
if (v === null || v === undefined)
|
|
54
|
+
return null;
|
|
55
|
+
if (typeof v !== "number" || !Number.isInteger(v) || v < min || v > max)
|
|
56
|
+
throw new LibraryError("bad_input", `${what} must be a whole number from ${min} to ${max}`);
|
|
57
|
+
return v;
|
|
58
|
+
}
|
|
59
|
+
function member(v, what = "member") {
|
|
60
|
+
return text(v, what);
|
|
61
|
+
}
|
|
62
|
+
function addMonths(at, months) {
|
|
63
|
+
const d = new Date(at);
|
|
64
|
+
d.setUTCMonth(d.getUTCMonth() + months);
|
|
65
|
+
return d;
|
|
66
|
+
}
|
|
67
|
+
const iso = (v) => (v === null ? null : new Date(v).toISOString());
|
|
68
|
+
function toCollection(r) {
|
|
69
|
+
return { ...r, price_cents: r.price_cents === null ? null : Number(r.price_cents), created_at: iso(r.created_at), updated_at: iso(r.updated_at) };
|
|
70
|
+
}
|
|
71
|
+
function toItem(r) {
|
|
72
|
+
return { ...r, publish_at: iso(r.publish_at), created_at: iso(r.created_at), updated_at: iso(r.updated_at) };
|
|
73
|
+
}
|
|
74
|
+
function toFile(r) {
|
|
75
|
+
return { ...r, bytes: Number(r.bytes), created_at: iso(r.created_at) };
|
|
76
|
+
}
|
|
77
|
+
export function createLibrary(opts) {
|
|
78
|
+
const config = checkLibrary(opts.config);
|
|
79
|
+
const db = opts.db;
|
|
80
|
+
const now = opts.now ?? (() => new Date());
|
|
81
|
+
if (typeof opts.secret !== "string" || opts.secret.length < 32)
|
|
82
|
+
throw new LibraryError("bad_config", "secret (LIBRARY_SECRET) must be at least 32 characters");
|
|
83
|
+
const secret = opts.secret;
|
|
84
|
+
async function load(slugText, who) {
|
|
85
|
+
const r = await call(db, "load collection", "library_view", { p_slug: slug(slugText), p_member: who, p_now: now().toISOString() });
|
|
86
|
+
if (!r)
|
|
87
|
+
return null;
|
|
88
|
+
return {
|
|
89
|
+
collection: toCollection(r.collection),
|
|
90
|
+
items: r.items.map(toItem),
|
|
91
|
+
files: r.files.map(toFile),
|
|
92
|
+
sponsors: r.sponsors,
|
|
93
|
+
started_at: iso(r.started_at),
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
const seen = (viewer, c) => viewer.owner === true || c.status === "published";
|
|
97
|
+
async function viewOf(viewer, slugText, done) {
|
|
98
|
+
const r = await load(slugText, viewer.member === null ? null : member(viewer.member));
|
|
99
|
+
if (!r || !seen(viewer, r.collection))
|
|
100
|
+
return null;
|
|
101
|
+
const lock = collectionLock(r.collection, viewer, r.started_at, config.currency);
|
|
102
|
+
const view = {
|
|
103
|
+
collection: r.collection,
|
|
104
|
+
items: entries(r.collection, r.items, viewer, r.started_at, config, now(), done),
|
|
105
|
+
started_at: r.started_at,
|
|
106
|
+
allowed: lock === null,
|
|
107
|
+
locked: lock,
|
|
108
|
+
};
|
|
109
|
+
return { view, row: r };
|
|
110
|
+
}
|
|
111
|
+
const api = {
|
|
112
|
+
async saveCollection(c) {
|
|
113
|
+
const kind = c.kind;
|
|
114
|
+
if (!config.kinds.includes(kind))
|
|
115
|
+
throw new LibraryError("bad_input", `kind must be one of ${config.kinds.join(", ")} (workbench/library.json "kinds")`);
|
|
116
|
+
if (!["everyone", "signed_in", "feature", "bought"].includes(c.access))
|
|
117
|
+
throw new LibraryError("bad_input", 'access must be "everyone", "signed_in", "feature" or "bought"');
|
|
118
|
+
const feature = c.access === "feature" ? text(c.feature, "feature", 100) : null;
|
|
119
|
+
const price = c.access === "bought" ? whole(c.priceCents, "priceCents", 1, 100_000_000) : null;
|
|
120
|
+
if (c.access === "bought" && price === null)
|
|
121
|
+
throw new LibraryError("bad_input", 'a collection people buy needs priceCents');
|
|
122
|
+
let show = null;
|
|
123
|
+
if (kind === "show") {
|
|
124
|
+
const s = c.show ?? {};
|
|
125
|
+
const email = maybe(s.owner_email, "show owner_email", 200);
|
|
126
|
+
if (email !== null && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email))
|
|
127
|
+
throw new LibraryError("bad_input", "show owner_email must be an email address");
|
|
128
|
+
show = {
|
|
129
|
+
author: maybe(s.author, "show author", 200),
|
|
130
|
+
category: maybe(s.category, "show category", 100),
|
|
131
|
+
explicit: s.explicit === true,
|
|
132
|
+
owner_name: maybe(s.owner_name, "show owner_name", 200),
|
|
133
|
+
owner_email: email,
|
|
134
|
+
language: maybe(s.language, "show language", 20),
|
|
135
|
+
};
|
|
136
|
+
}
|
|
137
|
+
const row = await call(db, "save collection", "library_collection_save", {
|
|
138
|
+
p: {
|
|
139
|
+
id: c.id === undefined ? null : id(c.id, "id"),
|
|
140
|
+
slug: slug(c.slug),
|
|
141
|
+
kind,
|
|
142
|
+
title: text(c.title, "title"),
|
|
143
|
+
summary: maybe(c.summary, "summary", 2000),
|
|
144
|
+
cover_file: c.coverFile ? id(c.coverFile, "coverFile") : null,
|
|
145
|
+
access: c.access,
|
|
146
|
+
feature,
|
|
147
|
+
price_cents: price,
|
|
148
|
+
access_months: c.access === "bought" ? whole(c.accessMonths, "accessMonths", 1, 600) : null,
|
|
149
|
+
status: c.status ?? "draft",
|
|
150
|
+
show,
|
|
151
|
+
},
|
|
152
|
+
p_now: now().toISOString(),
|
|
153
|
+
});
|
|
154
|
+
return toCollection(row);
|
|
155
|
+
},
|
|
156
|
+
async deleteCollection(slugText, bucket) {
|
|
157
|
+
const r = await call(db, "delete collection", "library_collection_delete", { p_slug: slug(slugText) });
|
|
158
|
+
for (const k of r.keys)
|
|
159
|
+
await bucket.delete(k);
|
|
160
|
+
return { files: r.keys.length };
|
|
161
|
+
},
|
|
162
|
+
async collections() {
|
|
163
|
+
return (await call(db, "list collections", "library_collections", {})).map(toCollection);
|
|
164
|
+
},
|
|
165
|
+
async saveItem(i) {
|
|
166
|
+
if (i.embed && i.file)
|
|
167
|
+
throw new LibraryError("bad_input", "an item has an embed or a file, not both");
|
|
168
|
+
let media = { media_kind: "none", embed_url: null, file_id: null };
|
|
169
|
+
if (i.embed) {
|
|
170
|
+
const e = embedFor(text(i.embed, "embed", 500), config.embeds);
|
|
171
|
+
if (!e)
|
|
172
|
+
throw new LibraryError("bad_input", `embed must be a ${config.embeds.join(" or ") || "video"} address (workbench/library.json "embeds")`);
|
|
173
|
+
media = { media_kind: "embed", embed_url: i.embed.trim(), file_id: null };
|
|
174
|
+
}
|
|
175
|
+
else if (i.file)
|
|
176
|
+
media = { media_kind: "file", embed_url: null, file_id: id(i.file, "file") };
|
|
177
|
+
const publish = i.publishAt === null || i.publishAt === undefined ? null : new Date(i.publishAt);
|
|
178
|
+
if (publish && Number.isNaN(publish.getTime()))
|
|
179
|
+
throw new LibraryError("bad_input", "publishAt must be a date and time");
|
|
180
|
+
const row = await call(db, "save item", "library_item_save", {
|
|
181
|
+
p: {
|
|
182
|
+
id: i.id === undefined ? null : id(i.id, "id"),
|
|
183
|
+
collection: slug(i.collection, "collection"),
|
|
184
|
+
slug: slug(i.slug),
|
|
185
|
+
position: whole(i.position, "position", 0, 100_000),
|
|
186
|
+
title: text(i.title, "title"),
|
|
187
|
+
body: i.body === undefined ? "" : text(i.body, "body", 100_000, 0),
|
|
188
|
+
...media,
|
|
189
|
+
seconds: whole(i.seconds, "seconds", 1, 86_400),
|
|
190
|
+
preview: i.preview === true,
|
|
191
|
+
drip_days: whole(i.dripDays, "dripDays", 0, 3650),
|
|
192
|
+
publish_at: publish?.toISOString() ?? null,
|
|
193
|
+
status: i.status ?? "draft",
|
|
194
|
+
episode: whole(i.episode, "episode", 0, 100_000),
|
|
195
|
+
season: whole(i.season, "season", 1, 1000),
|
|
196
|
+
},
|
|
197
|
+
p_now: now().toISOString(),
|
|
198
|
+
});
|
|
199
|
+
return toItem(row);
|
|
200
|
+
},
|
|
201
|
+
async deleteItem(itemId, bucket) {
|
|
202
|
+
const r = await call(db, "delete item", "library_item_delete", { p_id: id(itemId, "id") });
|
|
203
|
+
if (r.key)
|
|
204
|
+
await bucket.delete(r.key);
|
|
205
|
+
return { deleted: r.deleted };
|
|
206
|
+
},
|
|
207
|
+
async addFile(bucket, f) {
|
|
208
|
+
const name = text(f.name, "name").replace(/[\\/\u0000-\u001f"]/g, "_");
|
|
209
|
+
const type = text(f.type, "type", 100).toLowerCase().split(";")[0].trim();
|
|
210
|
+
if (!config.files.types.includes(type))
|
|
211
|
+
throw new LibraryError("bad_input", `files of type ${type} aren't allowed (workbench/library.json files.types: ${config.files.types.join(", ")})`);
|
|
212
|
+
const bytes = whole(f.bytes, "bytes", 1, config.files.max_mb * 1024 * 1024);
|
|
213
|
+
if (bytes === null)
|
|
214
|
+
throw new LibraryError("bad_input", "bytes is needed (the upload's Content-Length)");
|
|
215
|
+
const key = `library/${crypto.randomUUID()}/${encodeURIComponent(name)}`;
|
|
216
|
+
await bucket.put(key, f.body, { httpMetadata: { contentType: type } });
|
|
217
|
+
try {
|
|
218
|
+
return toFile(await call(db, "add file", "library_file_add", { p_key: key, p_name: name, p_type: type, p_bytes: bytes, p_now: now().toISOString() }));
|
|
219
|
+
}
|
|
220
|
+
catch (e) {
|
|
221
|
+
await bucket.delete(key);
|
|
222
|
+
throw e;
|
|
223
|
+
}
|
|
224
|
+
},
|
|
225
|
+
async deleteFile(fileId, bucket) {
|
|
226
|
+
const r = await call(db, "delete file", "library_file_delete", { p_id: id(fileId, "id") });
|
|
227
|
+
if (r.key)
|
|
228
|
+
await bucket.delete(r.key);
|
|
229
|
+
},
|
|
230
|
+
async saveSponsor(s) {
|
|
231
|
+
if (!validDate(s.startsOn) || !validDate(s.endsOn) || s.endsOn < s.startsOn)
|
|
232
|
+
throw new LibraryError("bad_input", "startsOn and endsOn must be days (YYYY-MM-DD), endsOn on or after startsOn");
|
|
233
|
+
const url = maybe(s.url, "url", 500);
|
|
234
|
+
if (url !== null && !/^https:\/\/[^\s]+$/.test(url))
|
|
235
|
+
throw new LibraryError("bad_input", "url must start with https://");
|
|
236
|
+
return call(db, "save sponsor", "library_sponsor_save", {
|
|
237
|
+
p: { id: s.id === undefined ? null : id(s.id, "id"), collection: slug(s.collection, "collection"), name: text(s.name, "name"), url, message: text(s.message, "message", 500), starts_on: s.startsOn, ends_on: s.endsOn },
|
|
238
|
+
});
|
|
239
|
+
},
|
|
240
|
+
async deleteSponsor(sponsorId) {
|
|
241
|
+
return call(db, "delete sponsor", "library_sponsor_delete", { p_id: id(sponsorId, "id") });
|
|
242
|
+
},
|
|
243
|
+
async view(viewer, slugText, o = {}) {
|
|
244
|
+
return (await viewOf(viewer, slugText, o.done))?.view ?? null;
|
|
245
|
+
},
|
|
246
|
+
async open(viewer, slugText, itemSlug, o = {}) {
|
|
247
|
+
const got = await viewOf(viewer, slugText, o.done);
|
|
248
|
+
if (!got)
|
|
249
|
+
return null;
|
|
250
|
+
const { view, row } = got;
|
|
251
|
+
const at = view.items.findIndex((e) => e.item.slug === itemSlug);
|
|
252
|
+
if (at < 0)
|
|
253
|
+
return null;
|
|
254
|
+
const entry = view.items[at];
|
|
255
|
+
if (entry.locked)
|
|
256
|
+
return { ...entry.locked, collection: view.collection, item: entry.item };
|
|
257
|
+
const item = entry.item;
|
|
258
|
+
let media = null;
|
|
259
|
+
if (item.media?.kind === "embed") {
|
|
260
|
+
const e = embedFor(item.media.url, config.embeds);
|
|
261
|
+
media = e ? { kind: "embed", src: e.src, host: e.host } : null;
|
|
262
|
+
}
|
|
263
|
+
else if (item.media?.kind === "file") {
|
|
264
|
+
const f = row.files.find((x) => x.id === item.media.file);
|
|
265
|
+
if (f) {
|
|
266
|
+
const open = view.collection.status === "published" && (item.preview || view.collection.access === "everyone") && item.status === "published";
|
|
267
|
+
media = { kind: "file", url: open ? `${config.paths.files}/${f.id}` : await api.fileUrl(f.id), name: f.name, type: f.type, bytes: f.bytes };
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
return {
|
|
271
|
+
ok: true,
|
|
272
|
+
collection: view.collection,
|
|
273
|
+
item,
|
|
274
|
+
media,
|
|
275
|
+
sponsors: view.collection.kind === "show" ? sponsorsFor(item, row.sponsors, config.time_zone) : [],
|
|
276
|
+
previous: view.items[at - 1]?.item ?? null,
|
|
277
|
+
next: view.items[at + 1]?.item ?? null,
|
|
278
|
+
done: entry.done,
|
|
279
|
+
};
|
|
280
|
+
},
|
|
281
|
+
async enrol(viewer, slugText) {
|
|
282
|
+
const got = await viewOf(viewer, slugText);
|
|
283
|
+
if (!got)
|
|
284
|
+
throw new LibraryError("not_found", `enrol: no collection ${JSON.stringify(slugText)}`);
|
|
285
|
+
if (viewer.member === null)
|
|
286
|
+
return { ok: false, reason: "sign_in" };
|
|
287
|
+
if (got.view.locked)
|
|
288
|
+
return got.view.locked;
|
|
289
|
+
if (got.view.started_at)
|
|
290
|
+
return { ok: true, started_at: got.view.started_at };
|
|
291
|
+
const r = await call(db, "enrol", "library_enrol", { p_slug: slug(slugText), p_member: member(viewer.member), p_now: now().toISOString() });
|
|
292
|
+
return { ok: true, started_at: iso(r.started_at) };
|
|
293
|
+
},
|
|
294
|
+
async finished(viewer, slugText, itemSlug) {
|
|
295
|
+
if (viewer.member === null)
|
|
296
|
+
return { ok: false, reason: "sign_in" };
|
|
297
|
+
const got = await viewOf(viewer, slugText);
|
|
298
|
+
if (!got)
|
|
299
|
+
throw new LibraryError("not_found", `finished: no collection ${JSON.stringify(slugText)}`);
|
|
300
|
+
const entry = got.view.items.find((e) => e.item.slug === itemSlug);
|
|
301
|
+
if (!entry)
|
|
302
|
+
throw new LibraryError("not_found", `finished: no item ${JSON.stringify(itemSlug)}`);
|
|
303
|
+
if (entry.locked)
|
|
304
|
+
return entry.locked;
|
|
305
|
+
return {
|
|
306
|
+
ok: true,
|
|
307
|
+
mark: {
|
|
308
|
+
track: `library:${got.view.collection.slug}`,
|
|
309
|
+
skill: entry.item.slug,
|
|
310
|
+
person: { type: "member", id: member(viewer.member) },
|
|
311
|
+
source: { type: "library_item", id: entry.item.id },
|
|
312
|
+
at: now().toISOString(),
|
|
313
|
+
},
|
|
314
|
+
};
|
|
315
|
+
},
|
|
316
|
+
async fileUrl(fileId) {
|
|
317
|
+
return signedPath(secret, config.paths.files, id(fileId, "file"), new Date(now().getTime() + config.link_minutes * 60_000));
|
|
318
|
+
},
|
|
319
|
+
async serveFile(request, bucket) {
|
|
320
|
+
const deny = (status, why) => new Response(why, { status, headers: { "content-type": "text/plain; charset=utf-8", "cache-control": "no-store" } });
|
|
321
|
+
if (request.method !== "GET" && request.method !== "HEAD")
|
|
322
|
+
return deny(405, "Method not allowed");
|
|
323
|
+
const link = await readLink(secret, config.paths.files, new URL(request.url), now());
|
|
324
|
+
if ("refused" in link)
|
|
325
|
+
return deny(link.refused === "expired" ? 410 : 404, link.refused === "expired" ? "This link has expired. Open the page again for a new one." : "Not found");
|
|
326
|
+
const r = await call(db, "serve file", "library_file_get", { p_id: link.file, p_now: now().toISOString() });
|
|
327
|
+
if (!r || (!link.signed && !r.public))
|
|
328
|
+
return deny(404, "Not found");
|
|
329
|
+
const file = toFile(r.file);
|
|
330
|
+
const range = parseRange(request.headers.get("range"), file.bytes);
|
|
331
|
+
if (range === "bad")
|
|
332
|
+
return new Response(null, { status: 416, headers: { "content-range": `bytes */${file.bytes}` } });
|
|
333
|
+
const headers = new Headers({
|
|
334
|
+
"content-type": file.type,
|
|
335
|
+
"accept-ranges": "bytes",
|
|
336
|
+
"x-content-type-options": "nosniff",
|
|
337
|
+
"cache-control": link.signed ? "private, no-store" : "public, max-age=300",
|
|
338
|
+
"content-disposition": `${/^(audio|image)\/|^application\/pdf$/.test(file.type) ? "inline" : "attachment"}; filename*=UTF-8''${encodeURIComponent(file.name)}`,
|
|
339
|
+
});
|
|
340
|
+
const length = range ? range.length : file.bytes;
|
|
341
|
+
headers.set("content-length", String(length));
|
|
342
|
+
if (range)
|
|
343
|
+
headers.set("content-range", `bytes ${range.offset}-${range.offset + range.length - 1}/${file.bytes}`);
|
|
344
|
+
const status = range ? 206 : 200;
|
|
345
|
+
if (request.method === "HEAD")
|
|
346
|
+
return new Response(null, { status, headers });
|
|
347
|
+
const obj = await bucket.get(file.key, range ? { range } : undefined);
|
|
348
|
+
if (!obj)
|
|
349
|
+
return deny(404, "Not found");
|
|
350
|
+
return new Response(obj.body, { status, headers });
|
|
351
|
+
},
|
|
352
|
+
async feed(slugText, o) {
|
|
353
|
+
const origin = text(o.origin, "origin", 200).replace(/\/+$/, "");
|
|
354
|
+
if (!/^https?:\/\/[^/\s]+$/.test(origin))
|
|
355
|
+
throw new LibraryError("bad_input", 'origin must be like "https://example.com"');
|
|
356
|
+
const r = await load(slugText, null);
|
|
357
|
+
if (!r || r.collection.kind !== "show" || r.collection.status !== "published" || r.collection.access !== "everyone")
|
|
358
|
+
return null;
|
|
359
|
+
const at = now();
|
|
360
|
+
const live = entries(r.collection, r.items, { member: null }, null, config, at).filter((e) => e.state === "open");
|
|
361
|
+
return podcastFeed({
|
|
362
|
+
collection: r.collection,
|
|
363
|
+
items: live.map((e) => e.item),
|
|
364
|
+
files: r.files,
|
|
365
|
+
sponsors: r.sponsors,
|
|
366
|
+
origin,
|
|
367
|
+
config,
|
|
368
|
+
now: at,
|
|
369
|
+
});
|
|
370
|
+
},
|
|
371
|
+
async purchase(slugText) {
|
|
372
|
+
const r = await load(slugText, null);
|
|
373
|
+
if (!r || r.collection.status !== "published")
|
|
374
|
+
throw new LibraryError("not_found", `purchase: no published collection ${JSON.stringify(slugText)}`);
|
|
375
|
+
const c = r.collection;
|
|
376
|
+
if (c.access !== "bought" || c.price_cents === null)
|
|
377
|
+
throw new LibraryError("bad_input", `purchase: ${c.slug} isn't sold one by one`);
|
|
378
|
+
return { source: { type: "library", id: c.id }, currency: config.currency, line: { label: c.title, quantity: 1, unit_cents: c.price_cents, total_cents: c.price_cents }, access_months: c.access_months };
|
|
379
|
+
},
|
|
380
|
+
async grant(o) {
|
|
381
|
+
const r = await load(o.collection, null);
|
|
382
|
+
if (!r)
|
|
383
|
+
throw new LibraryError("not_found", `grant: no collection ${JSON.stringify(o.collection)}`);
|
|
384
|
+
const at = now();
|
|
385
|
+
const ends = r.collection.access_months ? addMonths(at, r.collection.access_months).toISOString() : null;
|
|
386
|
+
const g = await call(db, "grant", "library_grant", {
|
|
387
|
+
p_slug: slug(o.collection, "collection"),
|
|
388
|
+
p_member: member(o.member),
|
|
389
|
+
p_ref: text(o.ref, "ref"),
|
|
390
|
+
p_ends: ends,
|
|
391
|
+
p_now: at.toISOString(),
|
|
392
|
+
});
|
|
393
|
+
return { repeat: g.repeat, started_at: iso(g.started_at), ends_at: iso(g.ends_at) };
|
|
394
|
+
},
|
|
395
|
+
async revoke(ref) {
|
|
396
|
+
return call(db, "revoke", "library_revoke", { p_ref: text(ref, "ref"), p_now: now().toISOString() });
|
|
397
|
+
},
|
|
398
|
+
async mine(who) {
|
|
399
|
+
const rows = await call(db, "member area", "library_mine", { p_member: member(who), p_now: now().toISOString() });
|
|
400
|
+
return rows.map((r) => {
|
|
401
|
+
const c = toCollection(r.collection);
|
|
402
|
+
return { tool: "library", kind: c.kind, id: c.id, title: c.title, href: `${config.paths.base}/${c.slug}`, started_at: iso(r.started_at), ends_at: iso(r.ends_at), bought: r.bought };
|
|
403
|
+
});
|
|
404
|
+
},
|
|
405
|
+
async forget(who) {
|
|
406
|
+
return call(db, "forget member", "library_forget", { p_member: member(who) });
|
|
407
|
+
},
|
|
408
|
+
async tick() {
|
|
409
|
+
const r = await call(db, "tick", "library_tick", { p_tz: config.time_zone, p_now: now().toISOString() });
|
|
410
|
+
const { deleted } = await api.cleanup();
|
|
411
|
+
return {
|
|
412
|
+
opened: r.opened.map((x) => ({ ...x, at: iso(x.at) })),
|
|
413
|
+
published: r.published.map((x) => ({ ...x, at: iso(x.at) })),
|
|
414
|
+
deleted,
|
|
415
|
+
};
|
|
416
|
+
},
|
|
417
|
+
async cleanup() {
|
|
418
|
+
return call(db, "cleanup", "library_cleanup", { p_now: now().toISOString(), p_days: config.retention.ended_access_days });
|
|
419
|
+
},
|
|
420
|
+
};
|
|
421
|
+
return api;
|
|
422
|
+
}
|
package/dist/links.d.ts
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
/** The signed path for a file, valid until `until`. */
|
|
2
|
+
export declare function signedPath(secret: string, filesPath: string, file: string, until: Date): Promise<string>;
|
|
3
|
+
export type LinkCheck = {
|
|
4
|
+
file: string;
|
|
5
|
+
signed: true;
|
|
6
|
+
} | {
|
|
7
|
+
file: string;
|
|
8
|
+
signed: false;
|
|
9
|
+
} | {
|
|
10
|
+
refused: "bad_link" | "expired";
|
|
11
|
+
};
|
|
12
|
+
/** Reads a request's path: which file, and whether its signature holds. */
|
|
13
|
+
export declare function readLink(secret: string, filesPath: string, url: URL, now: Date): Promise<LinkCheck>;
|
|
14
|
+
/** One range of bytes asked for, or null for the whole file; "bad" when it can't be met. */
|
|
15
|
+
export declare function parseRange(header: string | null, size: number): {
|
|
16
|
+
offset: number;
|
|
17
|
+
length: number;
|
|
18
|
+
} | null | "bad";
|
|
19
|
+
/** The part of an R2 bucket binding the package uses. */
|
|
20
|
+
export interface LibraryBucket {
|
|
21
|
+
put(key: string, value: ReadableStream | ArrayBuffer | Uint8Array | string, options?: {
|
|
22
|
+
httpMetadata?: {
|
|
23
|
+
contentType?: string;
|
|
24
|
+
contentDisposition?: string;
|
|
25
|
+
};
|
|
26
|
+
}): Promise<unknown>;
|
|
27
|
+
get(key: string, options?: {
|
|
28
|
+
range?: {
|
|
29
|
+
offset: number;
|
|
30
|
+
length: number;
|
|
31
|
+
};
|
|
32
|
+
}): Promise<{
|
|
33
|
+
body: ReadableStream;
|
|
34
|
+
size: number;
|
|
35
|
+
} | null>;
|
|
36
|
+
delete(key: string): Promise<void>;
|
|
37
|
+
}
|