@mccaskie-labs/workbench-library 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +5 -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
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
# @mccaskie-labs/workbench-library
|
|
2
|
+
|
|
3
|
+
## 0.1.0
|
|
4
|
+
|
|
5
|
+
- First version (`docs/capabilities/28-library.md`, block B9): `createLibrary` over the app's own database with `libraryMigration`, and files in the app's own R2 bucket. Courses, shows and shelves of items with words and a YouTube or Vimeo player, audio, a PDF, a picture or a download. Each collection is open to everyone, anyone signed in, a plan feature, or buyers (`purchase`, `grant` on the payments tool's `paid` outcome, once per payment; `revoke` after a refund; access for good or a number of months). Free preview items, lessons that open a set number of days after the person started (midnight in the project's time zone), scheduled items, short-lived signed file links and `serveFile` with Range support, sponsor slots with dates, a podcast feed for public shows, `finished` answering the progress tool's mark, `mine` for the member area, and `tick`, `cleanup` and `forget`. Service role only. The collection page, item page, locked notice and member's list in `./ui` (`wb-library-*`, `LIBRARY_STYLES`, words in English, Tagalog and Taglish, money to 2 decimal places), and `npx workbench-library init|generate|migration`.
|
package/README.md
CHANGED
|
@@ -1,3 +1,63 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @mccaskie-labs/workbench-library
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Courses, shows and member content for apps built on Workbench, a private platform. Spec: `docs/capabilities/28-library.md`. Published publicly so Workbench projects can install it with no token; it is not supported for other uses.
|
|
4
|
+
|
|
5
|
+
```sh
|
|
6
|
+
npm install @mccaskie-labs/workbench-library
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
## Set up
|
|
10
|
+
|
|
11
|
+
1. `npx workbench-library init` writes the starter `workbench/library.json` (or the client questions in `capabilities/library.json` fill it). Take `country`, `time_zone` and `currency` from `workbench/country.json`.
|
|
12
|
+
2. `npx workbench-library generate` checks it and writes `src/library.generated.ts` (`LIBRARY`). Checks can run `npx workbench-library generate --check`.
|
|
13
|
+
3. `npx workbench-library migration` writes `libraryMigration` and its down file into `supabase/migrations` and `supabase/rollback`. It creates functions, so Control asks for approval even on staging.
|
|
14
|
+
4. Add an R2 bucket binding `LIBRARY_BUCKET` for each environment, and set `LIBRARY_SECRET` (at least 32 random characters) as a Worker secret. Members-only file links are signed with it.
|
|
15
|
+
|
|
16
|
+
## Use
|
|
17
|
+
|
|
18
|
+
```ts
|
|
19
|
+
import { createLibrary } from '@mccaskie-labs/workbench-library'
|
|
20
|
+
import { renderCollection, renderItem, renderLocked } from '@mccaskie-labs/workbench-library/ui'
|
|
21
|
+
import { LIBRARY } from './library.generated'
|
|
22
|
+
|
|
23
|
+
const library = createLibrary({ db: serviceClient, config: LIBRARY, secret: env.LIBRARY_SECRET })
|
|
24
|
+
|
|
25
|
+
// Who is looking: the app's sign-in, and the features workbench-plans gives them.
|
|
26
|
+
const viewer = { member: user?.id ?? null, features: memberFeatures }
|
|
27
|
+
|
|
28
|
+
// /learn/<course>: the list, with what the progress tool says is done.
|
|
29
|
+
const view = await library.view(viewer, course, { done })
|
|
30
|
+
html = renderCollection(view, LIBRARY, { startAction: `/learn/${course}/start`, actions: { sign_in: '/sign-in', buy: `/buy/${course}` } })
|
|
31
|
+
|
|
32
|
+
// /learn/<course>/<lesson>
|
|
33
|
+
const it = await library.open(viewer, course, lesson, { done })
|
|
34
|
+
html = it.ok ? renderItem(it, LIBRARY, { doneAction: `/learn/${course}/${lesson}/done` }) : renderLocked(it, LIBRARY)
|
|
35
|
+
|
|
36
|
+
// The Start and Done routes:
|
|
37
|
+
await library.enrol(viewer, course) // dripped lessons count from today
|
|
38
|
+
const f = await library.finished(viewer, course, lesson) // f.mark goes to the progress tool's mark()
|
|
39
|
+
|
|
40
|
+
// Files: <paths.files>/<id>, checked and streamed from R2 with Range support.
|
|
41
|
+
return library.serveFile(request, env.LIBRARY_BUCKET)
|
|
42
|
+
|
|
43
|
+
// A public show's podcast feed:
|
|
44
|
+
const xml = await library.feed('the-yarn', { origin: url.origin })
|
|
45
|
+
|
|
46
|
+
// Selling a course through the payments tool:
|
|
47
|
+
const p = await library.purchase(course) // p.line, p.source for the invoice
|
|
48
|
+
await library.grant({ collection: course, member, ref: payment.id }) // on "paid" only
|
|
49
|
+
await library.revoke(payment.id) // after a refund
|
|
50
|
+
|
|
51
|
+
// The cron, hourly:
|
|
52
|
+
const { opened, published } = await library.tick() // email "Lesson 3 is open"
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
- Who may see a collection: `everyone`, `signed_in`, `feature` (a plans feature) or `bought`. An item marked `preview` is open to everyone. Drafts and scheduled items show only to `{ owner: true }`.
|
|
56
|
+
- Videos are YouTube or Vimeo addresses (`embed`), shown in the privacy-friendly player; anything else is refused. Audio, PDFs, pictures and downloads go in the bucket through `addFile`.
|
|
57
|
+
- A sponsor slot (`saveSponsor`) covers the episodes that came out between its dates, on the page and in the feed. Slots on one show don't overlap.
|
|
58
|
+
- `mine(member)` lists what a member started or bought, for the "My account" page. `forget(member)` deletes their rows; `tick()` runs `cleanup()`, which deletes ended access after `retention.ended_access_days`.
|
|
59
|
+
- `LibraryError` is for the app's own mistakes and database failures. A visitor who can't open something gets `{ ok: false, reason }`: `sign_in`, `plan`, `buy`, `not_started` or `opens_later`.
|
|
60
|
+
|
|
61
|
+
## Look
|
|
62
|
+
|
|
63
|
+
Every element `./ui` draws has a `wb-library-*` class with a default rule in `LIBRARY_STYLES` (`./styles`); `npx workbench-ui styles` puts them in the project's `public/styles/workbench.css`, and the project restyles them in `project.css`. The words are in `LIBRARY_WORDS` (English, Tagalog, Taglish) under `ui.wblibrary.*`.
|
package/dist/access.d.ts
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { Collection, Item, ItemEntry, LibraryConfig, Locked, Viewer } from "./types.ts";
|
|
2
|
+
/** Is the item there at all for this viewer? Drafts and scheduled items are the owner's only. */
|
|
3
|
+
export declare function visible(item: Item, viewer: Viewer, now: Date): boolean;
|
|
4
|
+
/** May the viewer see the collection's items (previews aside)? null: yes. */
|
|
5
|
+
export declare function collectionLock(c: Collection, viewer: Viewer, startedAt: string | null, currency: string): Locked | null;
|
|
6
|
+
/** Each visible item with whether it's open to the viewer, in order. */
|
|
7
|
+
export declare function entries(c: Collection, items: readonly Item[], viewer: Viewer, startedAt: string | null, config: Pick<LibraryConfig, "time_zone" | "currency">, now: Date, done?: ReadonlySet<string>): ItemEntry[];
|
package/dist/access.js
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
// Who may see what, worked out from the collection's rule, the viewer, when
|
|
2
|
+
// they started, and the clock. Plain code over what the store answered, so
|
|
3
|
+
// the same rules decide the list, the item page, the Done button and the
|
|
4
|
+
// member area.
|
|
5
|
+
import { opensAt } from "./time.js";
|
|
6
|
+
/** Is the item there at all for this viewer? Drafts and scheduled items are the owner's only. */
|
|
7
|
+
export function visible(item, viewer, now) {
|
|
8
|
+
if (viewer.owner)
|
|
9
|
+
return true;
|
|
10
|
+
return item.status === "published" && (item.publish_at === null || new Date(item.publish_at).getTime() <= now.getTime());
|
|
11
|
+
}
|
|
12
|
+
/** May the viewer see the collection's items (previews aside)? null: yes. */
|
|
13
|
+
export function collectionLock(c, viewer, startedAt, currency) {
|
|
14
|
+
if (viewer.owner || c.access === "everyone")
|
|
15
|
+
return null;
|
|
16
|
+
if (viewer.member === null)
|
|
17
|
+
return { ok: false, reason: "sign_in" };
|
|
18
|
+
if (c.access === "signed_in")
|
|
19
|
+
return null;
|
|
20
|
+
if (c.access === "feature")
|
|
21
|
+
return viewer.features?.includes(c.feature ?? "") ? null : { ok: false, reason: "plan", feature: c.feature ?? undefined };
|
|
22
|
+
return startedAt !== null ? null : { ok: false, reason: "buy", ...(c.price_cents !== null ? { price_cents: c.price_cents, currency } : {}) };
|
|
23
|
+
}
|
|
24
|
+
/** Each visible item with whether it's open to the viewer, in order. */
|
|
25
|
+
export function entries(c, items, viewer, startedAt, config, now, done = new Set()) {
|
|
26
|
+
const lock = collectionLock(c, viewer, startedAt, config.currency);
|
|
27
|
+
return items
|
|
28
|
+
.filter((i) => visible(i, viewer, now))
|
|
29
|
+
.sort((a, b) => a.position - b.position || a.created_at.localeCompare(b.created_at))
|
|
30
|
+
.map((item) => {
|
|
31
|
+
const locked = itemLock(item, lock, viewer, startedAt, config.time_zone, now);
|
|
32
|
+
return { item, state: locked ? "locked" : "open", locked, done: done.has(item.id) || done.has(item.slug) };
|
|
33
|
+
});
|
|
34
|
+
}
|
|
35
|
+
function itemLock(item, lock, viewer, startedAt, timeZone, now) {
|
|
36
|
+
if (viewer.owner || item.preview)
|
|
37
|
+
return null;
|
|
38
|
+
if (lock)
|
|
39
|
+
return lock;
|
|
40
|
+
if (item.drip_days === null || item.drip_days === 0)
|
|
41
|
+
return null;
|
|
42
|
+
if (startedAt === null)
|
|
43
|
+
return viewer.member === null ? { ok: false, reason: "sign_in" } : { ok: false, reason: "not_started" };
|
|
44
|
+
const at = opensAt(startedAt, item.drip_days, timeZone);
|
|
45
|
+
return at.getTime() > now.getTime() ? { ok: false, reason: "opens_later", opens_at: at.toISOString() } : null;
|
|
46
|
+
}
|
package/dist/cli.d.ts
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import type { LibraryConfig } from "./types.ts";
|
|
3
|
+
export declare const LIBRARY_FILE = "workbench/library.json";
|
|
4
|
+
export declare const LIBRARY_MODULE = "src/library.generated.ts";
|
|
5
|
+
/** What the settings mean, in lines for the owner. */
|
|
6
|
+
export declare function summaryLines(c: LibraryConfig): string[];
|
|
7
|
+
/** The generated module for a checked config. */
|
|
8
|
+
export declare function moduleText(c: LibraryConfig): string;
|
|
9
|
+
/** Reads and checks the project's library.json. Throws naming every problem. */
|
|
10
|
+
export declare function readLibrary(dir: string): LibraryConfig;
|
|
11
|
+
/** Runs one command; returns the exit code. */
|
|
12
|
+
export declare function run(argv: string[], log?: (s: string) => void, err?: (s: string) => void): number;
|
package/dist/cli.js
ADDED
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// `npx workbench-library init [dir]` writes the starter workbench/library.json
|
|
3
|
+
// (courses, shows and shelves in Sydney; audio, PDFs and pictures up to
|
|
4
|
+
// 100 MB; YouTube and Vimeo players) unless there is one.
|
|
5
|
+
//
|
|
6
|
+
// `npx workbench-library generate [--check] [dir]`, run in a project's
|
|
7
|
+
// folder: reads workbench/library.json, checks it, prints what it means, and
|
|
8
|
+
// writes src/library.generated.ts: LIBRARY for createLibrary. --check writes
|
|
9
|
+
// nothing and fails when the file is out of date or wrong.
|
|
10
|
+
//
|
|
11
|
+
// `npx workbench-library migration [dir]` writes libraryMigration into
|
|
12
|
+
// supabase/migrations/<timestamp>_workbench_library.sql with its down file in
|
|
13
|
+
// supabase/rollback/, unless a library migration is already there.
|
|
14
|
+
import { existsSync, mkdirSync, readdirSync, readFileSync, realpathSync, writeFileSync } from "node:fs";
|
|
15
|
+
import { dirname, join, resolve } from "node:path";
|
|
16
|
+
import { fileURLToPath } from "node:url";
|
|
17
|
+
import { libraryProblems } from "./config.js";
|
|
18
|
+
import { libraryMigration } from "./migration.js";
|
|
19
|
+
import { STARTER_LIBRARY } from "./starters.js";
|
|
20
|
+
const USAGE = "usage: workbench-library init [dir]\n workbench-library generate [--check] [dir]\n workbench-library migration [dir]";
|
|
21
|
+
export const LIBRARY_FILE = "workbench/library.json";
|
|
22
|
+
export const LIBRARY_MODULE = "src/library.generated.ts";
|
|
23
|
+
const read = (path) => readFileSync(path, "utf8").replace(/\r\n/g, "\n");
|
|
24
|
+
const KIND_WORDS = { course: "courses", show: "shows with a podcast feed", shelf: "shelves of downloads" };
|
|
25
|
+
/** What the settings mean, in lines for the owner. */
|
|
26
|
+
export function summaryLines(c) {
|
|
27
|
+
const hosts = c.embeds.map((e) => (e === "youtube" ? "YouTube" : "Vimeo"));
|
|
28
|
+
return [
|
|
29
|
+
`You can make ${c.kinds.map((k) => KIND_WORDS[k]).join(", ")}.`,
|
|
30
|
+
`Files up to ${c.files.max_mb} MB: ${c.files.types.join(", ")}. Videos are ${hosts.length ? `${hosts.join(" or ")} links` : "not offered"}.`,
|
|
31
|
+
`Members-only files open through links that last ${c.link_minutes} minutes.`,
|
|
32
|
+
`Pages at ${c.paths.base}/<collection>, files at ${c.paths.files}/<id>.`,
|
|
33
|
+
`Who started or bought what is kept ${c.retention.ended_access_days} days after their access ends.`,
|
|
34
|
+
];
|
|
35
|
+
}
|
|
36
|
+
/** The generated module for a checked config. */
|
|
37
|
+
export function moduleText(c) {
|
|
38
|
+
return [
|
|
39
|
+
`// Generated by \`npx workbench-library generate\` from ${LIBRARY_FILE}. Don't edit: change the`,
|
|
40
|
+
"// JSON and generate again (Checks runs `npx workbench-library generate --check`).",
|
|
41
|
+
"",
|
|
42
|
+
'import type { LibraryConfig } from "@mccaskie-labs/workbench-library";',
|
|
43
|
+
"",
|
|
44
|
+
`export const LIBRARY = ${JSON.stringify(c, null, 2)} as const satisfies LibraryConfig;`,
|
|
45
|
+
"",
|
|
46
|
+
].join("\n");
|
|
47
|
+
}
|
|
48
|
+
/** Reads and checks the project's library.json. Throws naming every problem. */
|
|
49
|
+
export function readLibrary(dir) {
|
|
50
|
+
const path = join(dir, LIBRARY_FILE);
|
|
51
|
+
if (!existsSync(path))
|
|
52
|
+
throw new Error(`${LIBRARY_FILE} is missing: run \`npx workbench-library init\` or answer the library questions first (capabilities/library.json, offer)`);
|
|
53
|
+
let parsed;
|
|
54
|
+
try {
|
|
55
|
+
parsed = JSON.parse(read(path));
|
|
56
|
+
}
|
|
57
|
+
catch (e) {
|
|
58
|
+
throw new Error(`${LIBRARY_FILE}: not valid JSON (${e.message})`);
|
|
59
|
+
}
|
|
60
|
+
const problems = libraryProblems(parsed, LIBRARY_FILE);
|
|
61
|
+
if (problems.length)
|
|
62
|
+
throw new Error(problems.join("\n"));
|
|
63
|
+
const { $schema: _, ...rest } = parsed;
|
|
64
|
+
return rest;
|
|
65
|
+
}
|
|
66
|
+
function migrationStamp(at) {
|
|
67
|
+
return at.toISOString().replace(/[-:T]/g, "").slice(0, 14);
|
|
68
|
+
}
|
|
69
|
+
/** Runs one command; returns the exit code. */
|
|
70
|
+
export function run(argv, log = console.log, err = console.error) {
|
|
71
|
+
const [command, ...rest] = argv;
|
|
72
|
+
const check = rest.includes("--check");
|
|
73
|
+
const bad = rest.find((a) => a.startsWith("--") && a !== "--check");
|
|
74
|
+
if (bad || (command !== "init" && command !== "generate" && command !== "migration") || (command !== "generate" && check)) {
|
|
75
|
+
err(bad ? `${bad} isn't an option\n${USAGE}` : USAGE);
|
|
76
|
+
return 2;
|
|
77
|
+
}
|
|
78
|
+
const dir = resolve(rest.find((a) => !a.startsWith("--")) ?? ".");
|
|
79
|
+
try {
|
|
80
|
+
if (command === "init") {
|
|
81
|
+
const path = join(dir, LIBRARY_FILE);
|
|
82
|
+
if (existsSync(path)) {
|
|
83
|
+
log(`${LIBRARY_FILE} is already there; nothing written`);
|
|
84
|
+
return 0;
|
|
85
|
+
}
|
|
86
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
87
|
+
writeFileSync(path, `${JSON.stringify(STARTER_LIBRARY, null, 2)}\n`);
|
|
88
|
+
log(`wrote ${LIBRARY_FILE}; change country, time_zone and currency to match workbench/country.json, then run \`npx workbench-library generate\``);
|
|
89
|
+
return 0;
|
|
90
|
+
}
|
|
91
|
+
if (command === "migration") {
|
|
92
|
+
const folder = join(dir, "supabase/migrations");
|
|
93
|
+
if (existsSync(folder) && readdirSync(folder).some((f) => f.endsWith("_workbench_library.sql"))) {
|
|
94
|
+
log("supabase/migrations already has the library migration; nothing written");
|
|
95
|
+
return 0;
|
|
96
|
+
}
|
|
97
|
+
const name = `${migrationStamp(new Date())}_workbench_library.sql`;
|
|
98
|
+
mkdirSync(folder, { recursive: true });
|
|
99
|
+
mkdirSync(join(dir, "supabase/rollback"), { recursive: true });
|
|
100
|
+
writeFileSync(join(folder, name), `-- workbench-library: courses, shows and member content (docs/capabilities/28-library.md)\n${libraryMigration.up}`);
|
|
101
|
+
writeFileSync(join(dir, "supabase/rollback", name.replace(/\.sql$/, "_down.sql")), `-- Reverses ${name}\n${libraryMigration.down}`);
|
|
102
|
+
log(`wrote supabase/migrations/${name} and its down file`);
|
|
103
|
+
return 0;
|
|
104
|
+
}
|
|
105
|
+
const c = readLibrary(dir);
|
|
106
|
+
for (const line of summaryLines(c))
|
|
107
|
+
log(line);
|
|
108
|
+
const out = join(dir, LIBRARY_MODULE);
|
|
109
|
+
const text = moduleText(c);
|
|
110
|
+
const current = existsSync(out) ? read(out) : null;
|
|
111
|
+
if (check) {
|
|
112
|
+
if (current !== text) {
|
|
113
|
+
err(`${LIBRARY_MODULE} is out of date: run \`npx workbench-library generate\` and commit it`);
|
|
114
|
+
return 1;
|
|
115
|
+
}
|
|
116
|
+
log(`${LIBRARY_MODULE} is current`);
|
|
117
|
+
return 0;
|
|
118
|
+
}
|
|
119
|
+
if (current !== text) {
|
|
120
|
+
mkdirSync(dirname(out), { recursive: true });
|
|
121
|
+
writeFileSync(out, text);
|
|
122
|
+
log(`wrote ${LIBRARY_MODULE}`);
|
|
123
|
+
}
|
|
124
|
+
else
|
|
125
|
+
log(`${LIBRARY_MODULE} is current`);
|
|
126
|
+
return 0;
|
|
127
|
+
}
|
|
128
|
+
catch (e) {
|
|
129
|
+
err(e.message);
|
|
130
|
+
return 1;
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
const isMain = (() => {
|
|
134
|
+
try {
|
|
135
|
+
return process.argv[1] !== undefined && realpathSync(process.argv[1]) === realpathSync(fileURLToPath(import.meta.url));
|
|
136
|
+
}
|
|
137
|
+
catch {
|
|
138
|
+
return false;
|
|
139
|
+
}
|
|
140
|
+
})();
|
|
141
|
+
if (isMain)
|
|
142
|
+
process.exitCode = run(process.argv.slice(2));
|
package/dist/config.d.ts
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { LibraryConfig } from "./types.ts";
|
|
2
|
+
export declare const KINDS: readonly ["course", "show", "shelf"];
|
|
3
|
+
export declare const EMBED_HOSTS: readonly ["youtube", "vimeo"];
|
|
4
|
+
/** Every problem with the file, or none. */
|
|
5
|
+
export declare function libraryProblems(input: unknown, where?: string): string[];
|
|
6
|
+
/** The config, checked; throws naming every problem. */
|
|
7
|
+
export declare function checkLibrary<C extends LibraryConfig>(c: C): C;
|
package/dist/config.js
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
// Checks workbench/library.json. The generator runs these before it writes
|
|
2
|
+
// src/library.generated.ts, and createLibrary runs them again at startup.
|
|
3
|
+
import { LibraryError } from "./errors.js";
|
|
4
|
+
export const KINDS = ["course", "show", "shelf"];
|
|
5
|
+
export const EMBED_HOSTS = ["youtube", "vimeo"];
|
|
6
|
+
const isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
7
|
+
const isWhole = (v, min, max) => typeof v === "number" && Number.isInteger(v) && v >= min && v <= max;
|
|
8
|
+
const isPath = (v) => typeof v === "string" && /^\/[a-z0-9][a-z0-9/_-]*[a-z0-9]$/.test(v) && !v.includes("//");
|
|
9
|
+
function validTimeZone(tz) {
|
|
10
|
+
try {
|
|
11
|
+
new Intl.DateTimeFormat("en", { timeZone: tz });
|
|
12
|
+
return true;
|
|
13
|
+
}
|
|
14
|
+
catch {
|
|
15
|
+
return false;
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
/** Every problem with the file, or none. */
|
|
19
|
+
export function libraryProblems(input, where = "workbench/library.json") {
|
|
20
|
+
const p = [];
|
|
21
|
+
if (!isObject(input))
|
|
22
|
+
return [`${where}: not a JSON object`];
|
|
23
|
+
const c = input;
|
|
24
|
+
for (const k of Object.keys(c)) {
|
|
25
|
+
if (!["$schema", "format", "country", "time_zone", "currency", "kinds", "files", "embeds", "link_minutes", "paths", "retention"].includes(k))
|
|
26
|
+
p.push(`${where}: unknown setting "${k}"`);
|
|
27
|
+
}
|
|
28
|
+
if (c.format !== 1)
|
|
29
|
+
p.push(`${where}: "format" must be 1`);
|
|
30
|
+
if (typeof c.country !== "string" || !/^[A-Z]{2}$/.test(c.country))
|
|
31
|
+
p.push(`${where}: "country" must be a two-letter code in capitals, such as "AU"`);
|
|
32
|
+
if (typeof c.time_zone !== "string" || !validTimeZone(c.time_zone))
|
|
33
|
+
p.push(`${where}: "time_zone" must be a time zone name, such as "Australia/Sydney"`);
|
|
34
|
+
if (typeof c.currency !== "string" || !/^[A-Z]{3}$/.test(c.currency))
|
|
35
|
+
p.push(`${where}: "currency" must be a three-letter code in capitals, such as "AUD"`);
|
|
36
|
+
if (!Array.isArray(c.kinds) || c.kinds.length === 0)
|
|
37
|
+
p.push(`${where}: "kinds" must list at least one of "course", "show" and "shelf"`);
|
|
38
|
+
else {
|
|
39
|
+
for (const k of c.kinds)
|
|
40
|
+
if (!KINDS.includes(k))
|
|
41
|
+
p.push(`${where}: kind ${JSON.stringify(k)} must be "course", "show" or "shelf"`);
|
|
42
|
+
if (new Set(c.kinds).size !== c.kinds.length)
|
|
43
|
+
p.push(`${where}: "kinds" lists a kind twice`);
|
|
44
|
+
}
|
|
45
|
+
if (!isObject(c.files))
|
|
46
|
+
p.push(`${where}: "files" must be { "max_mb", "types" }`);
|
|
47
|
+
else {
|
|
48
|
+
if (!isWhole(c.files.max_mb, 1, 500))
|
|
49
|
+
p.push(`${where}: files "max_mb" must be a whole number from 1 to 500`);
|
|
50
|
+
if (!Array.isArray(c.files.types))
|
|
51
|
+
p.push(`${where}: files "types" must be a list of content types, such as ["audio/mpeg", "application/pdf"]`);
|
|
52
|
+
else
|
|
53
|
+
for (const t of c.files.types) {
|
|
54
|
+
if (typeof t !== "string" || !/^[a-z]+\/[a-z0-9.+-]+$/.test(t))
|
|
55
|
+
p.push(`${where}: file type ${JSON.stringify(t)} must be a content type, such as "audio/mpeg"`);
|
|
56
|
+
else if (t.startsWith("video/"))
|
|
57
|
+
p.push(`${where}: file type "${t}": videos are links to YouTube or Vimeo, not files (docs/capabilities/28-library.md, L1)`);
|
|
58
|
+
else if (t === "text/html" || t === "image/svg+xml" || t.includes("javascript"))
|
|
59
|
+
p.push(`${where}: file type "${t}" can run script in a browser, so it isn't allowed`);
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
if (!Array.isArray(c.embeds))
|
|
63
|
+
p.push(`${where}: "embeds" must be a list: [] or any of "youtube" and "vimeo"`);
|
|
64
|
+
else
|
|
65
|
+
for (const e of c.embeds)
|
|
66
|
+
if (!EMBED_HOSTS.includes(e))
|
|
67
|
+
p.push(`${where}: embed ${JSON.stringify(e)} must be "youtube" or "vimeo"`);
|
|
68
|
+
if (!isWhole(c.link_minutes, 5, 1440))
|
|
69
|
+
p.push(`${where}: "link_minutes" must be a whole number from 5 to 1440`);
|
|
70
|
+
if (!isObject(c.paths) || !isPath(c.paths.base) || !isPath(c.paths.files))
|
|
71
|
+
p.push(`${where}: "paths" must be { "base": "/learn", "files": "/library/files" }: lower-case paths starting with /`);
|
|
72
|
+
else if (c.paths.base === c.paths.files)
|
|
73
|
+
p.push(`${where}: paths "base" and "files" must differ`);
|
|
74
|
+
if (!isObject(c.retention) || !isWhole(c.retention.ended_access_days, 1, 3650))
|
|
75
|
+
p.push(`${where}: "retention" must be { "ended_access_days": 1 to 3650 }`);
|
|
76
|
+
return p;
|
|
77
|
+
}
|
|
78
|
+
/** The config, checked; throws naming every problem. */
|
|
79
|
+
export function checkLibrary(c) {
|
|
80
|
+
const problems = libraryProblems(c, "library config");
|
|
81
|
+
if (problems.length)
|
|
82
|
+
throw new LibraryError("bad_config", problems.join("\n"));
|
|
83
|
+
return c;
|
|
84
|
+
}
|
package/dist/embed.d.ts
ADDED
package/dist/embed.js
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
// Turns a YouTube or Vimeo address the owner pastes into the address of the
|
|
2
|
+
// privacy-friendly player, or refuses it. Only these hosts are ever put in an
|
|
3
|
+
// iframe, so an item can't embed a page that runs anything else.
|
|
4
|
+
const YT_ID = /^[A-Za-z0-9_-]{11}$/;
|
|
5
|
+
/** The player for a pasted address, or null when it isn't a video on an allowed host. */
|
|
6
|
+
export function embedFor(pasted, allowed) {
|
|
7
|
+
let u;
|
|
8
|
+
try {
|
|
9
|
+
u = new URL(pasted.trim());
|
|
10
|
+
}
|
|
11
|
+
catch {
|
|
12
|
+
return null;
|
|
13
|
+
}
|
|
14
|
+
if (u.protocol !== "https:" && u.protocol !== "http:")
|
|
15
|
+
return null;
|
|
16
|
+
const host = u.hostname.toLowerCase().replace(/^www\.|^m\./, "");
|
|
17
|
+
const parts = u.pathname.split("/").filter(Boolean);
|
|
18
|
+
if (allowed.includes("youtube")) {
|
|
19
|
+
let id;
|
|
20
|
+
if (host === "youtu.be")
|
|
21
|
+
id = parts[0];
|
|
22
|
+
else if (host === "youtube.com" || host === "youtube-nocookie.com") {
|
|
23
|
+
if (parts[0] === "watch")
|
|
24
|
+
id = u.searchParams.get("v") ?? undefined;
|
|
25
|
+
else if (parts[0] === "embed" || parts[0] === "shorts" || parts[0] === "live")
|
|
26
|
+
id = parts[1];
|
|
27
|
+
}
|
|
28
|
+
if (id !== undefined) {
|
|
29
|
+
if (!YT_ID.test(id))
|
|
30
|
+
return null;
|
|
31
|
+
const start = Number.parseInt((u.searchParams.get("t") ?? u.searchParams.get("start") ?? "").replace(/s$/, ""), 10);
|
|
32
|
+
return { host: "youtube", src: `https://www.youtube-nocookie.com/embed/${id}${Number.isFinite(start) && start > 0 ? `?start=${start}` : ""}` };
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
if (allowed.includes("vimeo")) {
|
|
36
|
+
let id;
|
|
37
|
+
let hash = null;
|
|
38
|
+
if (host === "vimeo.com" && parts[0] && /^\d+$/.test(parts[0])) {
|
|
39
|
+
id = parts[0];
|
|
40
|
+
hash = parts[1] ?? null;
|
|
41
|
+
}
|
|
42
|
+
else if (host === "player.vimeo.com" && parts[0] === "video") {
|
|
43
|
+
id = parts[1];
|
|
44
|
+
hash = u.searchParams.get("h");
|
|
45
|
+
}
|
|
46
|
+
if (id !== undefined) {
|
|
47
|
+
if (!/^\d{1,12}$/.test(id) || (hash !== null && !/^[0-9a-f]{6,20}$/.test(hash)))
|
|
48
|
+
return null;
|
|
49
|
+
return { host: "vimeo", src: `https://player.vimeo.com/video/${id}${hash ? `?h=${hash}` : ""}` };
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
return null;
|
|
53
|
+
}
|
package/dist/errors.d.ts
ADDED
package/dist/errors.js
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
// The one error the package throws. A visitor who can't see an item gets an
|
|
2
|
+
// answer, never a throw (Locked); this is for a mistake in the app's own call,
|
|
3
|
+
// a setting that's wrong, or a database failure.
|
|
4
|
+
export class LibraryError extends Error {
|
|
5
|
+
code;
|
|
6
|
+
constructor(code, message) {
|
|
7
|
+
super(message);
|
|
8
|
+
this.name = "LibraryError";
|
|
9
|
+
this.code = code;
|
|
10
|
+
}
|
|
11
|
+
}
|
package/dist/feed.d.ts
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { Collection, Item, LibraryConfig, LibraryFile, Sponsor } from "./types.ts";
|
|
2
|
+
export interface FeedInput {
|
|
3
|
+
collection: Collection;
|
|
4
|
+
items: readonly Item[];
|
|
5
|
+
files: readonly LibraryFile[];
|
|
6
|
+
sponsors: readonly Sponsor[];
|
|
7
|
+
/** "https://example.com", no trailing slash. */
|
|
8
|
+
origin: string;
|
|
9
|
+
config: Pick<LibraryConfig, "paths" | "time_zone" | "country">;
|
|
10
|
+
now: Date;
|
|
11
|
+
}
|
|
12
|
+
/** HH:MM:SS for itunes:duration. */
|
|
13
|
+
export declare function duration(seconds: number): string;
|
|
14
|
+
export declare function podcastFeed(f: FeedInput): string;
|
package/dist/feed.js
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
// The podcast feed of a show: RSS 2.0 with the Apple Podcasts tags, which
|
|
2
|
+
// Spotify and the other apps read too. Only a published show open to
|
|
3
|
+
// everyone has one (createLibrary's feed() checks), and only its live
|
|
4
|
+
// episodes with an audio file are in it. Enclosures are the public file
|
|
5
|
+
// addresses, which serveFile answers while the episode stays public.
|
|
6
|
+
import { sponsorsFor } from "./sponsors.js";
|
|
7
|
+
import { esc, paragraphs } from "./text.js";
|
|
8
|
+
const cdata = (s) => `<![CDATA[${s.replace(/]]>/g, "]]]]><![CDATA[>")}]]>`;
|
|
9
|
+
/** HH:MM:SS for itunes:duration. */
|
|
10
|
+
export function duration(seconds) {
|
|
11
|
+
const h = Math.floor(seconds / 3600);
|
|
12
|
+
const m = Math.floor((seconds % 3600) / 60);
|
|
13
|
+
const s = seconds % 60;
|
|
14
|
+
return [h, m, s].map((n) => String(n).padStart(2, "0")).join(":");
|
|
15
|
+
}
|
|
16
|
+
export function podcastFeed(f) {
|
|
17
|
+
const c = f.collection;
|
|
18
|
+
const show = c.show;
|
|
19
|
+
const base = `${f.origin}${f.config.paths.base}/${c.slug}`;
|
|
20
|
+
const fileUrl = (id) => `${f.origin}${f.config.paths.files}/${id}`;
|
|
21
|
+
const files = new Map(f.files.map((x) => [x.id, x]));
|
|
22
|
+
const cover = c.cover_file ? files.get(c.cover_file) : undefined;
|
|
23
|
+
const language = show?.language ?? (f.config.country === "PH" ? "en-ph" : "en-au");
|
|
24
|
+
const episodes = [...f.items]
|
|
25
|
+
.filter((i) => i.media?.kind === "file" && files.get(i.media.file)?.type.startsWith("audio/"))
|
|
26
|
+
.sort((a, b) => (b.publish_at ?? b.created_at).localeCompare(a.publish_at ?? a.created_at))
|
|
27
|
+
.map((i) => {
|
|
28
|
+
const file = files.get(i.media.file);
|
|
29
|
+
const lines = sponsorsFor(i, f.sponsors, f.config.time_zone).map((s) => `<p>${esc(s.message)}${s.url ? ` <a href="${esc(s.url)}">${esc(s.url)}</a>` : ""}</p>`);
|
|
30
|
+
const notes = paragraphs(i.body) + lines.join("");
|
|
31
|
+
return [
|
|
32
|
+
" <item>",
|
|
33
|
+
` <title>${esc(i.title)}</title>`,
|
|
34
|
+
` <link>${esc(`${base}/${i.slug}`)}</link>`,
|
|
35
|
+
` <guid isPermaLink="false">${esc(i.id)}</guid>`,
|
|
36
|
+
` <pubDate>${new Date(i.publish_at ?? i.created_at).toUTCString()}</pubDate>`,
|
|
37
|
+
` <description>${cdata(notes)}</description>`,
|
|
38
|
+
` <enclosure url="${esc(fileUrl(file.id))}" length="${file.bytes}" type="${esc(file.type)}"/>`,
|
|
39
|
+
i.seconds ? ` <itunes:duration>${duration(i.seconds)}</itunes:duration>` : "",
|
|
40
|
+
i.episode !== null ? ` <itunes:episode>${i.episode}</itunes:episode>` : "",
|
|
41
|
+
i.season !== null ? ` <itunes:season>${i.season}</itunes:season>` : "",
|
|
42
|
+
` <itunes:explicit>${show?.explicit ? "true" : "false"}</itunes:explicit>`,
|
|
43
|
+
" </item>",
|
|
44
|
+
]
|
|
45
|
+
.filter(Boolean)
|
|
46
|
+
.join("\n");
|
|
47
|
+
});
|
|
48
|
+
return [
|
|
49
|
+
'<?xml version="1.0" encoding="UTF-8"?>',
|
|
50
|
+
'<rss version="2.0" xmlns:itunes="http://www.itunes.com/dtds/podcast-1.0.dtd" xmlns:atom="http://www.w3.org/2005/Atom">',
|
|
51
|
+
" <channel>",
|
|
52
|
+
` <title>${esc(c.title)}</title>`,
|
|
53
|
+
` <link>${esc(base)}</link>`,
|
|
54
|
+
` <atom:link href="${esc(`${base}/feed.xml`)}" rel="self" type="application/rss+xml"/>`,
|
|
55
|
+
` <description>${cdata(c.summary ?? c.title)}</description>`,
|
|
56
|
+
` <language>${esc(language)}</language>`,
|
|
57
|
+
` <lastBuildDate>${f.now.toUTCString()}</lastBuildDate>`,
|
|
58
|
+
show?.author ? ` <itunes:author>${esc(show.author)}</itunes:author>` : "",
|
|
59
|
+
show?.owner_name || show?.owner_email
|
|
60
|
+
? ` <itunes:owner>${show.owner_name ? `<itunes:name>${esc(show.owner_name)}</itunes:name>` : ""}${show.owner_email ? `<itunes:email>${esc(show.owner_email)}</itunes:email>` : ""}</itunes:owner>`
|
|
61
|
+
: "",
|
|
62
|
+
cover ? ` <itunes:image href="${esc(fileUrl(cover.id))}"/>` : "",
|
|
63
|
+
show?.category ? ` <itunes:category text="${esc(show.category)}"/>` : "",
|
|
64
|
+
` <itunes:explicit>${show?.explicit ? "true" : "false"}</itunes:explicit>`,
|
|
65
|
+
" <itunes:type>episodic</itunes:type>",
|
|
66
|
+
...episodes,
|
|
67
|
+
" </channel>",
|
|
68
|
+
"</rss>",
|
|
69
|
+
"",
|
|
70
|
+
]
|
|
71
|
+
.filter((l) => l !== "")
|
|
72
|
+
.join("\n")
|
|
73
|
+
.concat("\n");
|
|
74
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
export { createLibrary, type Library, type LibraryClient, type LibraryOptions, type NewCollection, type NewItem, type NewSponsor } from "./library.ts";
|
|
2
|
+
export { libraryMigration } from "./migration.ts";
|
|
3
|
+
export { checkLibrary, libraryProblems, EMBED_HOSTS, KINDS } from "./config.ts";
|
|
4
|
+
export { embedFor } from "./embed.ts";
|
|
5
|
+
export { podcastFeed, duration, type FeedInput } from "./feed.ts";
|
|
6
|
+
export { parseRange, readLink, signedPath, type LibraryBucket, type LinkCheck } from "./links.ts";
|
|
7
|
+
export { sponsorsFor } from "./sponsors.ts";
|
|
8
|
+
export { opensAt, dayIn } from "./time.ts";
|
|
9
|
+
export { collectionLock, entries, visible } from "./access.ts";
|
|
10
|
+
export { STARTER_LIBRARY } from "./starters.ts";
|
|
11
|
+
export { LibraryError, type LibraryErrorCode } from "./errors.ts";
|
|
12
|
+
export type * from "./types.ts";
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
// @mccaskie-labs/workbench-library: courses, shows and shelves of resources
|
|
2
|
+
// in the app's own database and R2 bucket, shown to everyone, signed-in
|
|
3
|
+
// members, a plan feature or buyers, with dripped lessons, scheduled items,
|
|
4
|
+
// signed file links, sponsor slots and a podcast feed. Spec:
|
|
5
|
+
// docs/capabilities/28-library.md.
|
|
6
|
+
export { createLibrary } from "./library.js";
|
|
7
|
+
export { libraryMigration } from "./migration.js";
|
|
8
|
+
export { checkLibrary, libraryProblems, EMBED_HOSTS, KINDS } from "./config.js";
|
|
9
|
+
export { embedFor } from "./embed.js";
|
|
10
|
+
export { podcastFeed, duration } from "./feed.js";
|
|
11
|
+
export { parseRange, readLink, signedPath } from "./links.js";
|
|
12
|
+
export { sponsorsFor } from "./sponsors.js";
|
|
13
|
+
export { opensAt, dayIn } from "./time.js";
|
|
14
|
+
export { collectionLock, entries, visible } from "./access.js";
|
|
15
|
+
export { STARTER_LIBRARY } from "./starters.js";
|
|
16
|
+
export { LibraryError } from "./errors.js";
|