@matterandmotion/emdash-series 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +139 -2
- package/astro/index.ts +158 -0
- package/dist/index.d.mts +5 -0
- package/dist/index.mjs +119 -0
- package/dist/manifest.json +120 -0
- package/dist/plugin.d.mts +7 -0
- package/dist/plugin.mjs +1 -0
- package/emdash-plugin.jsonc +67 -0
- package/package.json +67 -3
- package/profile/index.d.mts +38 -0
- package/profile/index.mjs +119 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Matter & Motion
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,140 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @matterandmotion/emdash-series
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Numbered series for any [EmDash CMS](https://github.com/emdash-cms/emdash) collection: automatic numbering, previous/next navigation, structured data, and a health report. Works with stories told in parts, podcast seasons, course lessons, newsletters, and any other content published in order.
|
|
4
|
+
|
|
5
|
+
> **Status: pre-release (0.x).** Settings and routes may change between minor versions.
|
|
6
|
+
|
|
7
|
+
```
|
|
8
|
+
pnpm add @matterandmotion/emdash-series
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
```js
|
|
12
|
+
// astro.config.mjs
|
|
13
|
+
import series from "@matterandmotion/emdash-series";
|
|
14
|
+
|
|
15
|
+
emdash({ database, storage, plugins: [series] });
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
It's a standard-format plugin, so it also runs sandboxed (`sandboxed: [series]`). Use one install path per site.
|
|
19
|
+
|
|
20
|
+
## Content model
|
|
21
|
+
|
|
22
|
+
Plugins can't create fields, so your site's schema (seed or admin) provides them. The plugin needs:
|
|
23
|
+
|
|
24
|
+
| Where | Field | Type | Notes |
|
|
25
|
+
|---|---|---|---|
|
|
26
|
+
| Each installment collection | `series` | string (or select or slug), **indexed** | The slug of the series the entry belongs to. |
|
|
27
|
+
| Each installment collection | `number` | integer (or number), **indexed** | Leave empty: the plugin fills it in. |
|
|
28
|
+
| Series collection (default `series`) | `title` | string | Named in structured data. |
|
|
29
|
+
|
|
30
|
+
Field and collection names are settings. A chapters collection is just another installment collection (each chapter has a series and a number).
|
|
31
|
+
|
|
32
|
+
`@matterandmotion/emdash-series/profile` exports these definitions for setup tools:
|
|
33
|
+
|
|
34
|
+
```js
|
|
35
|
+
import { navigationIndexSql, serialProfile } from "@matterandmotion/emdash-series/profile";
|
|
36
|
+
|
|
37
|
+
serialProfile({ installmentCollections: ["episodes"], chaptersCollection: "chapters" });
|
|
38
|
+
// → collection definitions for EmDash's schema API
|
|
39
|
+
navigationIndexSql("episodes");
|
|
40
|
+
// → CREATE INDEX IF NOT EXISTS mm_series_nav_episodes ON ec_episodes (series, number, id) WHERE deleted_at IS NULL
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
**Add the navigation index on large sites.** EmDash indexes each field on its own, which can't serve "the next entry in this series" without reading the whole series. The composite index answers it in one row. Apply the SQL once per installment collection with your database tool (`wrangler d1 execute`, `sqlite3`); it's safe to run twice.
|
|
44
|
+
|
|
45
|
+
## What it does
|
|
46
|
+
|
|
47
|
+
### Automatic numbering
|
|
48
|
+
|
|
49
|
+
When an entry is saved in an installment collection:
|
|
50
|
+
|
|
51
|
+
- **No number:** it gets the next number in its series. Each series has its own counter, updated atomically, so concurrent saves never share a number.
|
|
52
|
+
- **An explicit number** (an import or a manual edit): it's kept, and the counter moves up to at least that number so later entries continue after it.
|
|
53
|
+
- **An update that leaves the number out** is left alone. Clearing the field asks for a new number.
|
|
54
|
+
- **Translations** keep their source entry's number.
|
|
55
|
+
|
|
56
|
+
Counters never go down, so a deleted entry's number isn't reused. Numbering never blocks a save: if it fails, the entry is saved as submitted and the error is logged.
|
|
57
|
+
|
|
58
|
+
### Navigation
|
|
59
|
+
|
|
60
|
+
Templates use the `/astro` helpers, which run in the site and read only published entries:
|
|
61
|
+
|
|
62
|
+
```astro
|
|
63
|
+
---
|
|
64
|
+
import { getSeriesNav } from "@matterandmotion/emdash-series/astro";
|
|
65
|
+
|
|
66
|
+
const nav = await getSeriesNav({ collection: "episodes", series, number });
|
|
67
|
+
Astro.cache?.set(nav.cacheHint);
|
|
68
|
+
---
|
|
69
|
+
{nav.previous && <a rel="prev" href={`/episodes/${nav.previous.data.slug}`}>Previous</a>}
|
|
70
|
+
{nav.next && <a rel="next" href={`/episodes/${nav.next.data.slug}`}>Next</a>}
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
| Helper | Returns |
|
|
74
|
+
|---|---|
|
|
75
|
+
| `getSeriesNav({ collection, series, number })` | `first`, `previous`, `next`, `latest` and a merged `cacheHint` |
|
|
76
|
+
| `getSeriesEntries({ collection, series, limit?, cursor?, direction? })` | One page of a series in number order |
|
|
77
|
+
| `getLatestEntry({ collection, series? })` | The highest number in a series, or the newest published entry |
|
|
78
|
+
| `getRandomEntry({ collection, series })` | A random published entry (don't cache the page) |
|
|
79
|
+
|
|
80
|
+
Every helper takes `seriesField` and `numberField` when your fields use other names.
|
|
81
|
+
|
|
82
|
+
### Structured data
|
|
83
|
+
|
|
84
|
+
On published installment pages, the plugin adds JSON-LD naming the entry's number and series. Pages must pass their content reference to EmDash's page context (`content: { collection, id, slug }`). The type depends on the `schemaProfile` setting:
|
|
85
|
+
|
|
86
|
+
| Setting | Series type | Entry type | Number property |
|
|
87
|
+
|---|---|---|---|
|
|
88
|
+
| `creative-work` (default) | `CreativeWorkSeries` | `CreativeWork` | `position` |
|
|
89
|
+
| `book` | `Book` | `Chapter` | `position` |
|
|
90
|
+
| `podcast` | `PodcastSeries` | `PodcastEpisode` | `episodeNumber` |
|
|
91
|
+
| `periodical-art` | `ComicSeries` | `ComicIssue` | `issueNumber` |
|
|
92
|
+
|
|
93
|
+
Series titles and URLs come from a small cache that publishing and unpublishing a series keep current. Series added another way (a seed or an import) are picked up the first time one of their pages renders.
|
|
94
|
+
|
|
95
|
+
### Reserved series slugs
|
|
96
|
+
|
|
97
|
+
Series often live at `/<slug>`, so a series named after one of the site's own routes would hide that route. List those paths in **Reserved series slugs**; publishing or scheduling a series with one of them is refused with a message to the editor.
|
|
98
|
+
|
|
99
|
+
## Settings
|
|
100
|
+
|
|
101
|
+
| Key | Default | Meaning |
|
|
102
|
+
|---|---|---|
|
|
103
|
+
| `collections` | *(empty)* | Comma-separated installment collections. Empty means every collection with an indexed series field and an indexed number field. |
|
|
104
|
+
| `seriesField` | `series` | Field holding the series slug. |
|
|
105
|
+
| `numberField` | `number` | Field holding the number. |
|
|
106
|
+
| `seriesCollection` | `series` | Collection with one entry per series; its slugs match the series field. |
|
|
107
|
+
| `schemaProfile` | `creative-work` | Structured data types (see above). |
|
|
108
|
+
| `reservedSlugs` | *(empty)* | Comma-separated slugs a series may not use. |
|
|
109
|
+
|
|
110
|
+
## Routes
|
|
111
|
+
|
|
112
|
+
Under `/_emdash/api/plugins/mm-series/` (`r_…` for registry installs):
|
|
113
|
+
|
|
114
|
+
| Route | Access | Purpose |
|
|
115
|
+
|---|---|---|
|
|
116
|
+
| `GET nav?collection=&series=&number=` | Public, cached 60 s | `{ first, previous, next, latest }` for headless or client-side use. Each item is `{ id, slug, title, number }`. Without `number`, only `first` and `latest`. Returns 400 for bad input and 404 for collections it doesn't manage. |
|
|
117
|
+
| `POST health` | Administrators | Setup problems, and per series: count, entries without a number, duplicate and missing numbers, and whether the counter is behind the highest number. Also rebuilds the series cache. Reads up to 1,500 entries per call. |
|
|
118
|
+
|
|
119
|
+
## Hooks
|
|
120
|
+
|
|
121
|
+
| Hook | Does |
|
|
122
|
+
|---|---|
|
|
123
|
+
| `content:beforeSave` | Numbers installments (timeout 4 s). |
|
|
124
|
+
| `content:beforePublish`, `content:beforeSchedule` | Refuse reserved series slugs. |
|
|
125
|
+
| `content:afterPublish`, `content:afterUnpublish` | Keep the series cache current. |
|
|
126
|
+
| `page:metadata` | Adds JSON-LD to published installment pages. |
|
|
127
|
+
| `plugin:activate` | Logs setup problems and rebuilds the series cache. |
|
|
128
|
+
|
|
129
|
+
Capabilities: `content:read`, `content:write`, `schema:read`, `hooks.content-policy:register`.
|
|
130
|
+
|
|
131
|
+
## Data and limits
|
|
132
|
+
|
|
133
|
+
- **Storage:** `counters`, one document per series (`<collection>::<series>` → `{ value }`).
|
|
134
|
+
- **KV:** `state:series-index`, a map of series slug → `{ title, path }`.
|
|
135
|
+
- No personal data. Uninstalling leaves counters behind; they only matter if the plugin is reinstalled.
|
|
136
|
+
- The series cache reads up to 300 series at a time. Bigger sites still work, with structured data naming a series by slug until it's republished.
|
|
137
|
+
|
|
138
|
+
## License
|
|
139
|
+
|
|
140
|
+
MIT © Matter & Motion
|
package/astro/index.ts
ADDED
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Site-side helpers for templates: series queries on top of EmDash's
|
|
3
|
+
* `getEmDashCollection`. They run in the site (not the plugin sandbox), read
|
|
4
|
+
* only published entries, and use the same indexed `series` and `number`
|
|
5
|
+
* fields as the plugin. Chapters are just another series collection, so
|
|
6
|
+
* `getSeriesEntries({ collection: "chapters", series })` lists them.
|
|
7
|
+
*
|
|
8
|
+
* Shipped as TypeScript source; the site's Vite compiles it.
|
|
9
|
+
*/
|
|
10
|
+
import { type CacheHint, type ContentEntry, getEmDashCollection, type WhereValue } from "emdash";
|
|
11
|
+
|
|
12
|
+
export interface SeriesFields {
|
|
13
|
+
/** The installment collection, for example "episodes". */
|
|
14
|
+
collection: string;
|
|
15
|
+
/** Field holding the series slug. Default "series". */
|
|
16
|
+
seriesField?: string;
|
|
17
|
+
/** Field holding the installment number. Default "number". */
|
|
18
|
+
numberField?: string;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export interface SeriesNavigation<T> {
|
|
22
|
+
first: ContentEntry<T> | null;
|
|
23
|
+
previous: ContentEntry<T> | null;
|
|
24
|
+
next: ContentEntry<T> | null;
|
|
25
|
+
latest: ContentEntry<T> | null;
|
|
26
|
+
/** Pass to `Astro.cache.set()` so the page is invalidated when any of these change. */
|
|
27
|
+
cacheHint: CacheHint;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function names(options: SeriesFields) {
|
|
31
|
+
return {
|
|
32
|
+
seriesField: options.seriesField ?? "series",
|
|
33
|
+
numberField: options.numberField ?? "number",
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** Combines cache hints from several queries: all tags, latest modification. */
|
|
38
|
+
export function mergeCacheHints(hints: readonly CacheHint[]): CacheHint {
|
|
39
|
+
const tags = [...new Set(hints.flatMap((hint) => hint.tags ?? []))];
|
|
40
|
+
const times = hints
|
|
41
|
+
.map((hint) => hint.lastModified?.getTime())
|
|
42
|
+
.filter((time): time is number => time !== undefined);
|
|
43
|
+
const merged: CacheHint = {};
|
|
44
|
+
if (tags.length > 0) merged.tags = tags;
|
|
45
|
+
if (times.length > 0) merged.lastModified = new Date(Math.max(...times));
|
|
46
|
+
return merged;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
async function one<T>(
|
|
50
|
+
options: SeriesFields,
|
|
51
|
+
where: Record<string, WhereValue>,
|
|
52
|
+
direction: "asc" | "desc",
|
|
53
|
+
): Promise<{ entry: ContentEntry<T> | null; cacheHint: CacheHint }> {
|
|
54
|
+
const { numberField } = names(options);
|
|
55
|
+
const { entries, cacheHint } = await getEmDashCollection<string, T>(options.collection, {
|
|
56
|
+
where,
|
|
57
|
+
orderBy: { [numberField]: direction },
|
|
58
|
+
limit: 1,
|
|
59
|
+
});
|
|
60
|
+
return { entry: entries[0] ?? null, cacheHint };
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* First, previous, next and latest installments around `number` in a series.
|
|
65
|
+
* Four one-row queries on the indexed fields. (The loader takes range bounds as
|
|
66
|
+
* strings; the database compares them numerically against the integer column.)
|
|
67
|
+
*/
|
|
68
|
+
export async function getSeriesNav<T = Record<string, unknown>>(
|
|
69
|
+
options: SeriesFields & { series: string; number: number },
|
|
70
|
+
): Promise<SeriesNavigation<T>> {
|
|
71
|
+
const { seriesField, numberField } = names(options);
|
|
72
|
+
const inSeries = { [seriesField]: options.series };
|
|
73
|
+
const [first, previous, next, latest] = await Promise.all([
|
|
74
|
+
one<T>(options, inSeries, "asc"),
|
|
75
|
+
one<T>(options, { ...inSeries, [numberField]: { lt: String(options.number) } }, "desc"),
|
|
76
|
+
one<T>(options, { ...inSeries, [numberField]: { gt: String(options.number) } }, "asc"),
|
|
77
|
+
one<T>(options, inSeries, "desc"),
|
|
78
|
+
]);
|
|
79
|
+
return {
|
|
80
|
+
first: first.entry,
|
|
81
|
+
previous: previous.entry,
|
|
82
|
+
next: next.entry,
|
|
83
|
+
latest: latest.entry,
|
|
84
|
+
cacheHint: mergeCacheHints([first, previous, next, latest].map((r) => r.cacheHint)),
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** One page of a series in number order. Pass `nextCursor` back as `cursor` for the next page. */
|
|
89
|
+
export async function getSeriesEntries<T = Record<string, unknown>>(
|
|
90
|
+
options: SeriesFields & {
|
|
91
|
+
series: string;
|
|
92
|
+
limit?: number;
|
|
93
|
+
cursor?: string;
|
|
94
|
+
direction?: "asc" | "desc";
|
|
95
|
+
},
|
|
96
|
+
) {
|
|
97
|
+
const { seriesField, numberField } = names(options);
|
|
98
|
+
const { entries, cacheHint, nextCursor } = await getEmDashCollection<string, T>(
|
|
99
|
+
options.collection,
|
|
100
|
+
{
|
|
101
|
+
where: { [seriesField]: options.series },
|
|
102
|
+
orderBy: { [numberField]: options.direction ?? "asc" },
|
|
103
|
+
limit: options.limit ?? 100,
|
|
104
|
+
...(options.cursor === undefined ? {} : { cursor: options.cursor }),
|
|
105
|
+
},
|
|
106
|
+
);
|
|
107
|
+
return { entries, cacheHint, nextCursor };
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* The latest installment: the highest number in `series`, or, without a
|
|
112
|
+
* series, the most recently published installment in the collection.
|
|
113
|
+
*/
|
|
114
|
+
export async function getLatestEntry<T = Record<string, unknown>>(
|
|
115
|
+
options: SeriesFields & { series?: string },
|
|
116
|
+
): Promise<{ entry: ContentEntry<T> | null; cacheHint: CacheHint }> {
|
|
117
|
+
if (options.series !== undefined) {
|
|
118
|
+
const { seriesField } = names(options);
|
|
119
|
+
return one<T>(options, { [seriesField]: options.series }, "desc");
|
|
120
|
+
}
|
|
121
|
+
const { entries, cacheHint } = await getEmDashCollection<string, T>(options.collection, {
|
|
122
|
+
orderBy: { published_at: "desc" },
|
|
123
|
+
limit: 1,
|
|
124
|
+
});
|
|
125
|
+
return { entry: entries[0] ?? null, cacheHint };
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* A random installment of a series: picks a number between the first and the
|
|
130
|
+
* latest, then takes the first installment at or after it. Gaps make the
|
|
131
|
+
* installment after a gap a little more likely. Don't cache the result.
|
|
132
|
+
*/
|
|
133
|
+
export async function getRandomEntry<T = Record<string, unknown>>(
|
|
134
|
+
options: SeriesFields & { series: string; random?: () => number },
|
|
135
|
+
): Promise<ContentEntry<T> | null> {
|
|
136
|
+
const { seriesField, numberField } = names(options);
|
|
137
|
+
const inSeries = { [seriesField]: options.series };
|
|
138
|
+
const [first, latest] = await Promise.all([
|
|
139
|
+
one<T>(options, inSeries, "asc"),
|
|
140
|
+
one<T>(options, inSeries, "desc"),
|
|
141
|
+
]);
|
|
142
|
+
const low = readNumber(first.entry, numberField);
|
|
143
|
+
const high = readNumber(latest.entry, numberField);
|
|
144
|
+
if (low === undefined || high === undefined) return first.entry;
|
|
145
|
+
const pick = low + Math.floor((options.random ?? Math.random)() * (high - low + 1));
|
|
146
|
+
const { entry } = await one<T>(
|
|
147
|
+
options,
|
|
148
|
+
{ ...inSeries, [numberField]: { gte: String(pick) } },
|
|
149
|
+
"asc",
|
|
150
|
+
);
|
|
151
|
+
return entry ?? latest.entry;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
function readNumber(entry: ContentEntry<unknown> | null, field: string): number | undefined {
|
|
155
|
+
const data = entry?.data as Record<string, unknown> | undefined;
|
|
156
|
+
const value = data?.[field];
|
|
157
|
+
return typeof value === "number" && Number.isSafeInteger(value) ? value : undefined;
|
|
158
|
+
}
|
package/dist/index.d.mts
ADDED
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
// Auto-generated by emdash-plugin build. Do not edit.
|
|
2
|
+
// Source: emdash-plugin.jsonc + package.json
|
|
3
|
+
//
|
|
4
|
+
// Default-exports a sandboxed plugin descriptor. Pass it directly into
|
|
5
|
+
// emdash's `plugins:` or `sandboxed:` array — no factory call needed.
|
|
6
|
+
|
|
7
|
+
/** @type {import("emdash").PluginDescriptor} */
|
|
8
|
+
const descriptor = Object.freeze({
|
|
9
|
+
"id": "mm-series",
|
|
10
|
+
"displayName": "Series",
|
|
11
|
+
"description": "Series and chapters for any collection: automatic numbering, previous/next navigation and structured data.",
|
|
12
|
+
"version": "0.1.0",
|
|
13
|
+
"format": "standard",
|
|
14
|
+
"entrypoint": "@matterandmotion/emdash-series/sandbox",
|
|
15
|
+
"capabilities": [
|
|
16
|
+
"content:read",
|
|
17
|
+
"content:write",
|
|
18
|
+
"schema:read",
|
|
19
|
+
"hooks.content-policy:register"
|
|
20
|
+
],
|
|
21
|
+
"allowedHosts": [],
|
|
22
|
+
"storage": {
|
|
23
|
+
"counters": {
|
|
24
|
+
"indexes": []
|
|
25
|
+
}
|
|
26
|
+
},
|
|
27
|
+
"hooks": [
|
|
28
|
+
{
|
|
29
|
+
"name": "plugin:activate",
|
|
30
|
+
"errorPolicy": "continue"
|
|
31
|
+
},
|
|
32
|
+
{
|
|
33
|
+
"name": "content:beforeSave",
|
|
34
|
+
"priority": 50,
|
|
35
|
+
"timeout": 4000
|
|
36
|
+
},
|
|
37
|
+
"content:beforePublish",
|
|
38
|
+
"content:beforeSchedule",
|
|
39
|
+
{
|
|
40
|
+
"name": "content:afterPublish",
|
|
41
|
+
"errorPolicy": "continue"
|
|
42
|
+
},
|
|
43
|
+
{
|
|
44
|
+
"name": "content:afterUnpublish",
|
|
45
|
+
"errorPolicy": "continue"
|
|
46
|
+
},
|
|
47
|
+
"page:metadata"
|
|
48
|
+
],
|
|
49
|
+
"routes": [
|
|
50
|
+
{
|
|
51
|
+
"name": "nav",
|
|
52
|
+
"methods": [
|
|
53
|
+
"GET"
|
|
54
|
+
],
|
|
55
|
+
"response": "raw",
|
|
56
|
+
"public": true,
|
|
57
|
+
"cacheControl": "public, max-age=60"
|
|
58
|
+
},
|
|
59
|
+
{
|
|
60
|
+
"name": "health",
|
|
61
|
+
"permission": "plugins:manage"
|
|
62
|
+
}
|
|
63
|
+
],
|
|
64
|
+
"settingsSchema": {
|
|
65
|
+
"collections": {
|
|
66
|
+
"label": "Installment collections",
|
|
67
|
+
"description": "Comma-separated collection slugs. Leave empty to use every collection with an indexed string series field and an indexed integer number field.",
|
|
68
|
+
"type": "string",
|
|
69
|
+
"default": ""
|
|
70
|
+
},
|
|
71
|
+
"seriesField": {
|
|
72
|
+
"label": "Series field",
|
|
73
|
+
"type": "string",
|
|
74
|
+
"default": "series"
|
|
75
|
+
},
|
|
76
|
+
"numberField": {
|
|
77
|
+
"label": "Number field",
|
|
78
|
+
"type": "string",
|
|
79
|
+
"default": "number"
|
|
80
|
+
},
|
|
81
|
+
"seriesCollection": {
|
|
82
|
+
"label": "Series collection",
|
|
83
|
+
"description": "Collection holding one entry per series (its slug matches the series field).",
|
|
84
|
+
"type": "string",
|
|
85
|
+
"default": "series"
|
|
86
|
+
},
|
|
87
|
+
"schemaProfile": {
|
|
88
|
+
"label": "Structured data type",
|
|
89
|
+
"type": "select",
|
|
90
|
+
"options": [
|
|
91
|
+
{
|
|
92
|
+
"value": "creative-work",
|
|
93
|
+
"label": "Generic series (CreativeWorkSeries)"
|
|
94
|
+
},
|
|
95
|
+
{
|
|
96
|
+
"value": "book",
|
|
97
|
+
"label": "Serialised book (Book and Chapter)"
|
|
98
|
+
},
|
|
99
|
+
{
|
|
100
|
+
"value": "podcast",
|
|
101
|
+
"label": "Podcast series and episodes"
|
|
102
|
+
},
|
|
103
|
+
{
|
|
104
|
+
"value": "periodical-art",
|
|
105
|
+
"label": "Illustrated serial (ComicSeries and ComicIssue)"
|
|
106
|
+
}
|
|
107
|
+
],
|
|
108
|
+
"default": "creative-work"
|
|
109
|
+
},
|
|
110
|
+
"reservedSlugs": {
|
|
111
|
+
"label": "Reserved series slugs",
|
|
112
|
+
"description": "Comma-separated top-level paths a series slug may not use (the site's own routes).",
|
|
113
|
+
"type": "string",
|
|
114
|
+
"default": ""
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
});
|
|
118
|
+
|
|
119
|
+
export default descriptor;
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
{
|
|
2
|
+
"id": "mm-series",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"declaredAccess": {
|
|
5
|
+
"content": {
|
|
6
|
+
"read": {},
|
|
7
|
+
"write": {},
|
|
8
|
+
"policy": {}
|
|
9
|
+
},
|
|
10
|
+
"schema": {
|
|
11
|
+
"read": {}
|
|
12
|
+
}
|
|
13
|
+
},
|
|
14
|
+
"capabilities": [
|
|
15
|
+
"content:read",
|
|
16
|
+
"content:write",
|
|
17
|
+
"schema:read",
|
|
18
|
+
"hooks.content-policy:register"
|
|
19
|
+
],
|
|
20
|
+
"allowedHosts": [],
|
|
21
|
+
"storage": {
|
|
22
|
+
"counters": {
|
|
23
|
+
"indexes": []
|
|
24
|
+
}
|
|
25
|
+
},
|
|
26
|
+
"hooks": [
|
|
27
|
+
{
|
|
28
|
+
"name": "plugin:activate",
|
|
29
|
+
"errorPolicy": "continue"
|
|
30
|
+
},
|
|
31
|
+
{
|
|
32
|
+
"name": "content:beforeSave",
|
|
33
|
+
"priority": 50,
|
|
34
|
+
"timeout": 4000
|
|
35
|
+
},
|
|
36
|
+
"content:beforePublish",
|
|
37
|
+
"content:beforeSchedule",
|
|
38
|
+
{
|
|
39
|
+
"name": "content:afterPublish",
|
|
40
|
+
"errorPolicy": "continue"
|
|
41
|
+
},
|
|
42
|
+
{
|
|
43
|
+
"name": "content:afterUnpublish",
|
|
44
|
+
"errorPolicy": "continue"
|
|
45
|
+
},
|
|
46
|
+
"page:metadata"
|
|
47
|
+
],
|
|
48
|
+
"routes": [
|
|
49
|
+
{
|
|
50
|
+
"name": "nav",
|
|
51
|
+
"methods": [
|
|
52
|
+
"GET"
|
|
53
|
+
],
|
|
54
|
+
"response": "raw",
|
|
55
|
+
"public": true,
|
|
56
|
+
"cacheControl": "public, max-age=60"
|
|
57
|
+
},
|
|
58
|
+
{
|
|
59
|
+
"name": "health",
|
|
60
|
+
"permission": "plugins:manage"
|
|
61
|
+
}
|
|
62
|
+
],
|
|
63
|
+
"admin": {
|
|
64
|
+
"settingsSchema": {
|
|
65
|
+
"collections": {
|
|
66
|
+
"label": "Installment collections",
|
|
67
|
+
"description": "Comma-separated collection slugs. Leave empty to use every collection with an indexed string series field and an indexed integer number field.",
|
|
68
|
+
"type": "string",
|
|
69
|
+
"default": ""
|
|
70
|
+
},
|
|
71
|
+
"seriesField": {
|
|
72
|
+
"label": "Series field",
|
|
73
|
+
"type": "string",
|
|
74
|
+
"default": "series"
|
|
75
|
+
},
|
|
76
|
+
"numberField": {
|
|
77
|
+
"label": "Number field",
|
|
78
|
+
"type": "string",
|
|
79
|
+
"default": "number"
|
|
80
|
+
},
|
|
81
|
+
"seriesCollection": {
|
|
82
|
+
"label": "Series collection",
|
|
83
|
+
"description": "Collection holding one entry per series (its slug matches the series field).",
|
|
84
|
+
"type": "string",
|
|
85
|
+
"default": "series"
|
|
86
|
+
},
|
|
87
|
+
"schemaProfile": {
|
|
88
|
+
"label": "Structured data type",
|
|
89
|
+
"type": "select",
|
|
90
|
+
"options": [
|
|
91
|
+
{
|
|
92
|
+
"value": "creative-work",
|
|
93
|
+
"label": "Generic series (CreativeWorkSeries)"
|
|
94
|
+
},
|
|
95
|
+
{
|
|
96
|
+
"value": "book",
|
|
97
|
+
"label": "Serialised book (Book and Chapter)"
|
|
98
|
+
},
|
|
99
|
+
{
|
|
100
|
+
"value": "podcast",
|
|
101
|
+
"label": "Podcast series and episodes"
|
|
102
|
+
},
|
|
103
|
+
{
|
|
104
|
+
"value": "periodical-art",
|
|
105
|
+
"label": "Illustrated serial (ComicSeries and ComicIssue)"
|
|
106
|
+
}
|
|
107
|
+
],
|
|
108
|
+
"default": "creative-work"
|
|
109
|
+
},
|
|
110
|
+
"reservedSlugs": {
|
|
111
|
+
"label": "Reserved series slugs",
|
|
112
|
+
"description": "Comma-separated top-level paths a series slug may not use (the site's own routes).",
|
|
113
|
+
"type": "string",
|
|
114
|
+
"default": ""
|
|
115
|
+
}
|
|
116
|
+
},
|
|
117
|
+
"pages": [],
|
|
118
|
+
"widgets": []
|
|
119
|
+
}
|
|
120
|
+
}
|
package/dist/plugin.mjs
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
function e(e){return typeof e==`string`?[e]:e}function t(e,t){return t===void 0?e:{...e,purpose:t}}function n(n,r){if(!n)return[t({kind:`missing-collection`,collection:r.collection},r.purpose)];let i=[];for(let a of r.fields){let r=e(a.type),o=n.fields.find(e=>e.slug===a.field);if(!o){i.push(t({kind:`missing-field`,collection:n.slug,field:a.field,expected:r},a.purpose));continue}if(!r.includes(o.type)){i.push({kind:`wrong-type`,collection:n.slug,field:a.field,expected:r,actual:o.type});continue}a.indexed&&!o.indexed&&i.push({kind:`not-indexed`,collection:n.slug,field:a.field}),a.searchable&&!o.searchable&&i.push({kind:`not-searchable`,collection:n.slug,field:a.field})}return i}function r(e){let t=`field`in e?`${e.collection}.${e.field}`:e.collection;switch(e.kind){case`missing-collection`:return`Collection "${t}" doesn't exist.`;case`missing-field`:return`Field "${t}" doesn't exist (expected ${e.expected.join(` or `)}).`;case`wrong-type`:return`Field "${t}" is ${e.actual}, expected ${e.expected.join(` or `)}.`;case`not-indexed`:return`Field "${t}" must be indexed.`;case`not-searchable`:return`Field "${t}" must be searchable.`}}function i(e){return e instanceof Error?e.message:String(e)}function a(e,t){return async(n,r)=>{try{await t(n,r)}catch(t){r.log.error(`${e} failed`,{error:i(t)})}}}var o=class{#e;#t;constructor(e,t=Date.now){this.#t=t,this.#e=t()+e}remaining(){return Math.max(0,this.#e-this.#t())}exhausted(e=0){return this.remaining()<=e}};function s(e,t){if(e&&typeof e==`object`&&t in e){let n=e[t];if(typeof n==`number`)return n}}async function c(e,t,{field:n=`value`,by:r=1,attempts:i=5}={}){if(!Number.isSafeInteger(r))throw RangeError("incrementCounter: `by` must be a safe integer");for(let a=0;a<i;a++){let i=r>=0?{inc:r}:{dec:-r},a=await e.updateIf(t,{where:{},delta:{[n]:i}});if(a.applied){let e=s(a.data,n);if(e===void 0)throw Error(`incrementCounter: "${n}" missing after update`);return e}if((await e.compareAndSet(t,null,{[n]:r})).applied)return r}throw Error(`incrementCounter: gave up after ${i} attempts on "${t}"`)}async function l(e,t,n,{field:r=`value`,attempts:i=5}={}){if(!Number.isSafeInteger(n))throw RangeError("bumpCounterTo: `value` must be a safe integer");for(let a=0;a<i;a++){if((await e.updateIf(t,{where:{[r]:{lt:n}},set:{[r]:n}})).applied||(await e.compareAndSet(t,null,{[r]:n})).applied)return n;let i=s(await e.get(t),r);if(i!==void 0&&i>=n)return i}throw Error(`bumpCounterTo: gave up after ${i} attempts on "${t}"`)}function u(e={}){let t=[];return new Headers(e.headers).forEach((e,n)=>t.push([n,e])),{__emdashPluginResponse:!0,status:e.status??200,headers:t,body:e.body??null}}const d=[`string`,`select`,`slug`],f=[`integer`,`number`];function p(e,t){let n=e.fields.find(e=>e.slug===t.seriesField),r=e.fields.find(e=>e.slug===t.numberField);return!!(n?.indexed&&r?.indexed&&d.includes(n.type)&&f.includes(r.type))}function m(e,t){return t.collections.length>0?[...t.collections]:e.filter(e=>e.slug!==t.seriesCollection&&p(e,t)).map(e=>e.slug)}function h(e,t){return e.map(e=>({collection:e,purpose:`Holds numbered installments of a series.`,fields:[{field:t.seriesField,type:d,indexed:!0,purpose:`The series slug each installment belongs to.`},{field:t.numberField,type:f,indexed:!0,purpose:`The installment's position in its series.`}]}))}async function g(e,t,n){if(t.collections.length>0)return t.collections.includes(e);if(!n||e===t.seriesCollection)return!1;let r=await n.getCollection(e);return r?p(r,t):!1}function _(e){return e==null||e===``}function v(e){let t=typeof e==`number`?e:typeof e==`string`&&/^\d+$/.test(e.trim())?Number(e.trim()):NaN;return Number.isSafeInteger(t)&&t>=0?t:void 0}function y(e){if(typeof e!=`string`)return;let t=e.trim();return t&&t.length<=200?t:void 0}function b(e,t){let n=y(e.content[t.seriesField]);if(n===void 0)return{kind:`skip`,reason:`no-series`};let r=e.content[t.numberField];if(_(r))return e.translationOf?{kind:`skip`,reason:`translation`}:!e.isNew&&!(t.numberField in e.content)?{kind:`skip`,reason:`not-in-update`}:{kind:`assign`,series:n};let i=v(r);return i===void 0?{kind:`skip`,reason:`not-a-whole-number`}:{kind:`raise`,series:n,number:i}}function x(e,t){return`${e}::${t}`}function S(e,t=new Map){let n=new Map;for(let t of e){if(t.series===void 0)continue;let e=n.get(t.series)??[];e.push(t),n.set(t.series,e)}let r=[];for(let[e,i]of[...n].sort(([e],[t])=>e.localeCompare(t))){let n=new Map,a=0;for(let{number:e}of i)e===void 0?a++:n.set(e,(n.get(e)??0)+1);let o=[...n.keys()].sort((e,t)=>e-t),s=o[0]??null,c=o.at(-1)??null,l=[],u=0;if(s!==null&&c!==null){u=c-s+1-o.length;for(let e=s;e<=c&&e-s<1e5&&l.length<50;e++)n.has(e)||l.push(e)}let d=t.get(e)??null;r.push({series:e,count:i.length,unnumbered:a,min:s,max:c,duplicates:o.filter(e=>(n.get(e)??0)>1),missing:l,missingCount:u,counter:d,counterBehind:c!==null&&(d??0)<c})}return r}async function C(e,t,n,r,i){let a=[],o,s=0;for(;s<i&&!r.exhausted(500);){let r=await e.list(t,o===void 0?{limit:100}:{limit:100,cursor:o});s++;for(let e of r.items)a.push({series:y(e.data[n.seriesField]),number:v(e.data[n.numberField])});if(!r.hasMore||!r.cursor)return{entries:a,complete:!0,calls:s};o=r.cursor}return{entries:a,complete:!1,calls:s}}function w(e){return Array.isArray(e)?e[0]:e}function T(e){let t=typeof e==`object`&&e?e:{},n=w(t.collection),r=y(w(t.series)),i=w(t.number);if(typeof n!=`string`||!/^[a-z][a-z0-9_]*$/.test(n))return{error:`collection is required`};if(r===void 0)return{error:`series is required`};if(i===void 0||i===``)return{collection:n,series:r};let a=v(i);return a===void 0?{error:`number must be a whole number`}:{collection:n,series:r,number:a}}function E(e,t){if(!e)return null;let n=e.data.title;return{id:e.id,slug:e.slug,title:typeof n==`string`?n:null,number:v(e.data[t])??null}}async function D(e,t,n){let{seriesField:r,numberField:i}=n,a=async(n,a)=>{let o={[r]:t.series};n&&(o[i]=n);let{items:s}=await e.list(t.collection,{limit:1,orderBy:{[i]:a},where:{status:`published`,fieldFilters:o}});return E(s[0],i)},o=t.number,[s,c,l,u]=await Promise.all([a(null,`asc`),o===void 0?null:a({lt:o},`desc`),o===void 0?null:a({gt:o},`asc`),a(null,`desc`)]);return{first:s,previous:c,next:l,latest:u}}const O=`state:series-index`;function k(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function A(e){return typeof e==`string`&&e.trim()?e.trim():null}function j(e,t){if(!e)return null;let n=e.replaceAll(`{slug}`,encodeURIComponent(t.slug)).replaceAll(`{id}`,encodeURIComponent(t.id));return n.includes(`{`)?null:n}function M(e){let t=k(e.data)?e.data:e;return{id:A(e.id)??A(t.id),slug:A(e.slug)??A(t.slug),title:A(t.title)??A(t.name)}}async function N(e,t,n=5){for(let r=0;r<n;r++){let n=await e.getVersioned(O),r=k(n?.value)?{...n.value}:{};if((await e.compareAndSet(O,n?.revision??null,t(r))).applied)return}throw Error(`Couldn't update the series index after ${n} attempts`)}async function P(e){let t=await e.get(O);return k(t)?t:{}}const F=[`creative-work`,`book`,`podcast`,`periodical-art`],I=Object.freeze({collections:[],seriesField:`series`,numberField:`number`,seriesCollection:`series`,schemaProfile:`creative-work`,reservedSlugs:[]}),L=/^[a-z][a-z0-9_]*$/;function R(e){if(typeof e!=`string`)return[];let t=e.split(/[,\n]/).map(e=>e.trim()).filter(Boolean);return[...new Set(t)]}function z(e,t){if(typeof e!=`string`)return t;let n=e.trim();return L.test(n)?n:t}function B(e){return typeof e==`string`&&F.includes(e)}function V(e){let t=new Map;for(let{key:n,value:r}of e)t.set(n.startsWith(`settings:`)?n.slice(9):n,r);let n=t.get(`schemaProfile`);return{collections:R(t.get(`collections`)).filter(e=>L.test(e)),seriesField:z(t.get(`seriesField`),I.seriesField),numberField:z(t.get(`numberField`),I.numberField),seriesCollection:z(t.get(`seriesCollection`),I.seriesCollection),schemaProfile:B(n)?n:I.schemaProfile,reservedSlugs:R(t.get(`reservedSlugs`)).map(e=>e.toLowerCase())}}async function H(e){return V(await e.list())}const U={"creative-work":{series:`CreativeWorkSeries`,installment:`CreativeWork`,numberProperty:`position`,partOfProperty:`isPartOf`},book:{series:`Book`,installment:`Chapter`,numberProperty:`position`,partOfProperty:`isPartOf`},podcast:{series:`PodcastSeries`,installment:`PodcastEpisode`,numberProperty:`episodeNumber`,partOfProperty:`partOfSeries`},"periodical-art":{series:`ComicSeries`,installment:`ComicIssue`,numberProperty:`issueNumber`,partOfProperty:`isPartOf`}};function W(e){let t=U[e.profile],n={"@type":t.series,identifier:e.series.slug};e.series.title&&(n.name=e.series.title),e.series.url&&(n.url=e.series.url);let r={"@context":`https://schema.org`,"@type":t.installment,url:e.url,[t.numberProperty]:e.number,[t.partOfProperty]:n};return e.title&&(r.name=e.title),e.datePublished&&(r.datePublished=e.datePublished),r}function G(e){return e instanceof Error?e.message:String(e)}function K(e,t,r){let i=new Map(e.map(e=>[e.slug,e]));return h(t,r).flatMap(e=>n(i.get(e.collection)??null,e))}function q(e,t){return u({status:e,headers:{"content-type":`application/json; charset=utf-8`},body:{kind:`text`,value:JSON.stringify(t)}})}async function J(e,t){try{let n=await H(t.settings);if(!await g(e.collection,n,t.schema))return;let r=b({content:e.content,isNew:e.isNew,translationOf:e.translationOf},n);if(r.kind===`skip`)return;let i=t.storage.counters;if(!i)throw Error("storage collection `counters` is not declared");let a=x(e.collection,r.series);if(r.kind===`raise`){await l(i,a,r.number);return}let o=await c(i,a);return{...e.content,[n.numberField]:o}}catch(n){t.log.error(`Couldn't number the installment; it was saved without a new number`,{collection:e.collection,error:G(n)});return}}async function Y(e,t){let n=await H(t.settings);if(e.collection!==n.seriesCollection||n.reservedSlugs.length===0)return;let{slug:r}=M(e.content);if(r&&n.reservedSlugs.includes(r.toLowerCase()))return{cancel:!0,reason:`The slug "${r}" is reserved by the site. Choose another slug for this series.`}}async function X(e,t,n){return j((await e.schema?.getCollection(t.seriesCollection))?.urlPattern,n)}async function Z(e,t){let n=await H(t.settings);if(e.collection!==n.seriesCollection)return;let{id:r,slug:i,title:a}=M(e.content);if(!r||!i)return;let o=await X(t,n,{id:r,slug:i});await N(t.kv,e=>({...e,[i]:{title:a,path:o}}))}async function Q(e,t){let n=await H(t.settings);if(e.collection!==n.seriesCollection)return;let{slug:r}=M(e.content);r&&await N(t.kv,e=>{let{[r]:t,...n}=e;return n})}async function $(e,t,n,r){if(!e.content||!e.schema)return{index:{},complete:!1};let i=await e.schema.getCollection(t.seriesCollection),a={},o=!i,s;for(let r=0;i&&r<3&&!n.exhausted(1e3);r++){let n=await e.content.list(t.seriesCollection,{limit:100,where:{status:`published`},...s===void 0?{}:{cursor:s}});for(let e of n.items)e.slug&&(a[e.slug]={title:M(e).title,path:j(i.urlPattern,{id:e.id,slug:e.slug})});if(!n.hasMore||!n.cursor){o=!0;break}s=n.cursor}return r!==void 0&&!(r in a)&&(a[r]={title:null,path:null}),await N(e.kv,e=>o?a:{...e,...a}),{index:a,complete:o}}async function ee(e,t){let n=e.page;if(!n.content||!t.content)return null;let r=await H(t.settings),{collection:i,id:a}=n.content;if(i===r.seriesCollection||r.collections.length>0&&!r.collections.includes(i))return null;let s=await t.content.get(i,a);if(s?.status!==`published`)return null;let c=y(s.data[r.seriesField]),l=v(s.data[r.numberField]);if(c===void 0||l===void 0||r.collections.length===0&&!await g(i,r,t.schema))return null;let u=await P(t.kv);c in u||(u=(await $(t,r,new o(3e3),c)).index);let d=u[c],f=s.data.title;return{kind:`jsonld`,id:`mm-series`,graph:W({profile:r.schemaProfile,url:n.canonical??n.url,number:l,title:typeof f==`string`?f:n.pageTitle,datePublished:s.publishedAt,series:{slug:c,title:d?.title,url:d?.path?t.url(d.path):null}})}}const te={hooks:{"plugin:activate":{errorPolicy:`continue`,handler:a(`series activation`,async(e,t)=>{let n=await H(t.settings);if(!t.schema)return;let i=await t.schema.listCollections(),a=m(i,n);a.length===0&&t.log.warn(`No collection has an indexed "${n.seriesField}" field and an indexed "${n.numberField}" field, so nothing will be numbered.`);for(let e of K(i,a,n))t.log.warn(r(e));await $(t,n,new o(3e3))})},"content:beforeSave":{priority:50,timeout:4e3,errorPolicy:`abort`,handler:J},"content:beforePublish":{handler:Y},"content:beforeSchedule":{handler:Y},"content:afterPublish":{errorPolicy:`continue`,handler:a(`series index update`,Z)},"content:afterUnpublish":{errorPolicy:`continue`,handler:a(`series index update`,Q)},"page:metadata":ee},routes:{nav:{public:!0,methods:[`GET`],response:`raw`,cacheControl:`public, max-age=60`,handler:async(e,t)=>{let n=T(e.input);if(`error`in n)return q(400,{error:n.error});if(!t.content)return q(500,{error:`content access is unavailable`});let r=await H(t.settings);return n.collection===r.seriesCollection||!await g(n.collection,r,t.schema)?q(404,{error:`not a series collection`}):q(200,await D(t.content,n,r))}},health:{permission:`plugins:manage`,handler:async(e,t)=>{let n=new o(4e3),i=await H(t.settings);if(!t.schema||!t.content)return{ok:!1,settings:i,problems:[`Schema or content access is unavailable.`]};let a=await t.schema.listCollections(),s=m(a,i),c=K(a,s,i),l=new Map,u=await t.storage.counters?.query({limit:100});for(let{id:e,data:t}of u?.items??[]){let n=t?.value;typeof n==`number`&&l.set(e,n)}let d=[],f=!0,p=0;for(let e of s){let r=await C(t.content,e,i,n,15-p);p+=r.calls,f&&=r.complete;let a=`${e}::`,o=new Map([...l].filter(([e])=>e.startsWith(a)).map(([e,t])=>[e.slice(a.length),t]));d.push({collection:e,series:S(r.entries,o)})}let h=await $(t,i,n);return{ok:c.length===0&&f,settings:i,collections:s,problems:c.map(r),reports:d,complete:f,seriesIndexed:Object.keys(h.index).length}}}}};export{te as default};
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
{
|
|
2
|
+
"$schema": "./node_modules/@emdash-cms/plugin-cli/schemas/emdash-plugin.schema.json",
|
|
3
|
+
|
|
4
|
+
// Config installs use this slug as the plugin ID (routes: /_emdash/api/plugins/mm-series/...).
|
|
5
|
+
"slug": "mm-series",
|
|
6
|
+
// Placeholder until the Matter & Motion registry publisher account exists.
|
|
7
|
+
// Replace before the first registry release.
|
|
8
|
+
"publisher": "did:plc:aaaaaaaaaaaaaaaaaaaaaaaa",
|
|
9
|
+
|
|
10
|
+
"name": "Series",
|
|
11
|
+
"description": "Series and chapters for any collection: automatic numbering, previous/next navigation and structured data.",
|
|
12
|
+
"keywords": ["series", "chapters", "navigation", "numbering", "serial"],
|
|
13
|
+
"license": "MIT",
|
|
14
|
+
"author": { "name": "Matter & Motion", "url": "https://github.com/matterandmotion" },
|
|
15
|
+
"security": { "url": "https://github.com/matterandmotion/emdash-plugins/security" },
|
|
16
|
+
"repo": "https://github.com/matterandmotion/emdash-plugins",
|
|
17
|
+
|
|
18
|
+
// beforeSave sets the number (content:write); navigation, structured data and
|
|
19
|
+
// the series index read entries (content:read); auto-detection and setup checks
|
|
20
|
+
// read the schema (schema:read); publish and schedule hooks refuse reserved
|
|
21
|
+
// series slugs (hooks.content-policy:register).
|
|
22
|
+
"capabilities": ["content:read", "content:write", "schema:read", "hooks.content-policy:register"],
|
|
23
|
+
"allowedHosts": [],
|
|
24
|
+
"storage": {
|
|
25
|
+
"counters": { "indexes": [] }
|
|
26
|
+
},
|
|
27
|
+
|
|
28
|
+
"admin": {
|
|
29
|
+
"settingsSchema": {
|
|
30
|
+
"collections": {
|
|
31
|
+
"type": "string",
|
|
32
|
+
"label": "Installment collections",
|
|
33
|
+
"description": "Comma-separated collection slugs. Leave empty to use every collection with an indexed string series field and an indexed integer number field.",
|
|
34
|
+
"default": ""
|
|
35
|
+
},
|
|
36
|
+
"seriesField": { "type": "string", "label": "Series field", "default": "series" },
|
|
37
|
+
"numberField": { "type": "string", "label": "Number field", "default": "number" },
|
|
38
|
+
"seriesCollection": {
|
|
39
|
+
"type": "string",
|
|
40
|
+
"label": "Series collection",
|
|
41
|
+
"description": "Collection holding one entry per series (its slug matches the series field).",
|
|
42
|
+
"default": "series"
|
|
43
|
+
},
|
|
44
|
+
"schemaProfile": {
|
|
45
|
+
"type": "select",
|
|
46
|
+
"label": "Structured data type",
|
|
47
|
+
"default": "creative-work",
|
|
48
|
+
"options": [
|
|
49
|
+
{ "value": "creative-work", "label": "Generic series (CreativeWorkSeries)" },
|
|
50
|
+
{ "value": "book", "label": "Serialised book (Book and Chapter)" },
|
|
51
|
+
{ "value": "podcast", "label": "Podcast series and episodes" },
|
|
52
|
+
{ "value": "periodical-art", "label": "Illustrated serial (ComicSeries and ComicIssue)" }
|
|
53
|
+
]
|
|
54
|
+
},
|
|
55
|
+
"reservedSlugs": {
|
|
56
|
+
"type": "string",
|
|
57
|
+
"label": "Reserved series slugs",
|
|
58
|
+
"description": "Comma-separated top-level paths a series slug may not use (the site's own routes).",
|
|
59
|
+
"default": ""
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
},
|
|
63
|
+
|
|
64
|
+
"release": {
|
|
65
|
+
"requires": { "env:emdash": ">=1.6.0" }
|
|
66
|
+
}
|
|
67
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,70 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@matterandmotion/emdash-series",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Series and chapters for any EmDash collection: automatic numbering, previous/next navigation and structured data.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"exports": {
|
|
8
|
+
".": {
|
|
9
|
+
"types": "./dist/index.d.mts",
|
|
10
|
+
"default": "./dist/index.mjs"
|
|
11
|
+
},
|
|
12
|
+
"./sandbox": "./dist/plugin.mjs",
|
|
13
|
+
"./astro": "./astro/index.ts",
|
|
14
|
+
"./profile": {
|
|
15
|
+
"types": "./profile/index.d.mts",
|
|
16
|
+
"default": "./profile/index.mjs"
|
|
17
|
+
}
|
|
18
|
+
},
|
|
19
|
+
"files": [
|
|
20
|
+
"dist/*.mjs",
|
|
21
|
+
"dist/*.d.mts",
|
|
22
|
+
"dist/manifest.json",
|
|
23
|
+
"astro",
|
|
24
|
+
"profile",
|
|
25
|
+
"emdash-plugin.jsonc",
|
|
26
|
+
"README.md"
|
|
27
|
+
],
|
|
28
|
+
"keywords": [
|
|
29
|
+
"emdash",
|
|
30
|
+
"emdash-plugin",
|
|
31
|
+
"series",
|
|
32
|
+
"chapters",
|
|
33
|
+
"navigation"
|
|
34
|
+
],
|
|
35
|
+
"repository": {
|
|
36
|
+
"type": "git",
|
|
37
|
+
"url": "git+https://github.com/matterandmotion/emdash-plugins.git",
|
|
38
|
+
"directory": "packages/series"
|
|
39
|
+
},
|
|
40
|
+
"homepage": "https://github.com/matterandmotion/emdash-plugins/tree/main/packages/series#readme",
|
|
41
|
+
"bugs": "https://github.com/matterandmotion/emdash-plugins/issues",
|
|
42
|
+
"engines": {
|
|
43
|
+
"node": ">=22.16"
|
|
44
|
+
},
|
|
45
|
+
"publishConfig": {
|
|
46
|
+
"access": "public"
|
|
47
|
+
},
|
|
48
|
+
"peerDependencies": {
|
|
49
|
+
"astro": ">=6.0.0",
|
|
50
|
+
"emdash": "^1.6.0"
|
|
51
|
+
},
|
|
52
|
+
"peerDependenciesMeta": {
|
|
53
|
+
"astro": {
|
|
54
|
+
"optional": true
|
|
55
|
+
}
|
|
56
|
+
},
|
|
57
|
+
"devDependencies": {
|
|
58
|
+
"@emdash-cms/plugin-cli": "0.13.7",
|
|
59
|
+
"@emdash-cms/plugin-test": "0.2.13",
|
|
60
|
+
"emdash": "1.6.0",
|
|
61
|
+
"@matterandmotion/emdash-plugin-toolkit": "0.1.0"
|
|
62
|
+
},
|
|
63
|
+
"scripts": {
|
|
64
|
+
"validate": "emdash-plugin validate",
|
|
65
|
+
"build": "emdash-plugin build",
|
|
66
|
+
"bundle": "emdash-plugin bundle",
|
|
67
|
+
"typecheck": "tsc --noEmit",
|
|
68
|
+
"test": "emdash-plugin validate && vitest run"
|
|
69
|
+
}
|
|
6
70
|
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
/** Matches the body of `POST /_emdash/api/schema/collections/:slug/fields`. */
|
|
2
|
+
export interface FieldDefinition {
|
|
3
|
+
slug: string;
|
|
4
|
+
label: string;
|
|
5
|
+
type: string;
|
|
6
|
+
required?: boolean;
|
|
7
|
+
indexed?: boolean;
|
|
8
|
+
searchable?: boolean;
|
|
9
|
+
validation?: Record<string, unknown> | null;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
/** Matches the body of `POST /_emdash/api/schema/collections`, plus the fields to create. */
|
|
13
|
+
export interface CollectionDefinition {
|
|
14
|
+
slug: string;
|
|
15
|
+
label: string;
|
|
16
|
+
labelSingular?: string;
|
|
17
|
+
fields: FieldDefinition[];
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export interface SerialProfileOptions {
|
|
21
|
+
/** Collections holding installments, as slugs or `{ slug, label }`. */
|
|
22
|
+
installmentCollections: ReadonlyArray<string | { slug: string; label?: string }>;
|
|
23
|
+
/** Default "series". */
|
|
24
|
+
seriesCollection?: string;
|
|
25
|
+
/** Adds a chapters collection with this slug. */
|
|
26
|
+
chaptersCollection?: string;
|
|
27
|
+
/** Default "series". */
|
|
28
|
+
seriesField?: string;
|
|
29
|
+
/** Default "number". */
|
|
30
|
+
numberField?: string;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export declare function serialProfile(options: SerialProfileOptions): CollectionDefinition[];
|
|
34
|
+
|
|
35
|
+
export declare function navigationIndexSql(
|
|
36
|
+
collection: string,
|
|
37
|
+
fields?: { seriesField?: string; numberField?: string },
|
|
38
|
+
): string;
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The schema the series plugin expects, for setup tools (doctor and migrate
|
|
3
|
+
* commands) and templates. Plain JavaScript so Node scripts can import it
|
|
4
|
+
* without a build step. The definitions match the body of EmDash's schema REST
|
|
5
|
+
* API and `CollectionDefinition` in `@matterandmotion/emdash-plugin-toolkit`.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
const SLUG = /^[a-z][a-z0-9_]*$/;
|
|
9
|
+
|
|
10
|
+
function assertSlug(value, what) {
|
|
11
|
+
if (typeof value !== "string" || !SLUG.test(value)) {
|
|
12
|
+
throw new TypeError(
|
|
13
|
+
`${what} must be a lowercase slug (a-z, 0-9, _), got ${JSON.stringify(value)}`,
|
|
14
|
+
);
|
|
15
|
+
}
|
|
16
|
+
return value;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function labelFor(slug) {
|
|
20
|
+
const words = slug.replaceAll("_", " ");
|
|
21
|
+
return words.charAt(0).toUpperCase() + words.slice(1);
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function seriesFields(seriesField, numberField) {
|
|
25
|
+
return [
|
|
26
|
+
{
|
|
27
|
+
slug: seriesField,
|
|
28
|
+
label: "Series",
|
|
29
|
+
type: "string",
|
|
30
|
+
required: true,
|
|
31
|
+
indexed: true,
|
|
32
|
+
},
|
|
33
|
+
{
|
|
34
|
+
slug: numberField,
|
|
35
|
+
label: "Number",
|
|
36
|
+
type: "integer",
|
|
37
|
+
indexed: true,
|
|
38
|
+
validation: { min: 0 },
|
|
39
|
+
},
|
|
40
|
+
];
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Collections and fields for numbered series.
|
|
45
|
+
*
|
|
46
|
+
* - Each installment collection gets an indexed `series` string and an indexed
|
|
47
|
+
* `number` integer (left empty, the plugin numbers new installments).
|
|
48
|
+
* - The series collection gets a `title` (used in structured data).
|
|
49
|
+
* - The optional chapters collection is itself a series collection: each chapter
|
|
50
|
+
* has a series and a number.
|
|
51
|
+
*
|
|
52
|
+
* Other packages' profiles can add fields to the same collections; merge them
|
|
53
|
+
* with `mergeDefinitions` from the toolkit.
|
|
54
|
+
*
|
|
55
|
+
* @param {import("./index.d.mts").SerialProfileOptions} options
|
|
56
|
+
* @returns {import("./index.d.mts").CollectionDefinition[]}
|
|
57
|
+
*/
|
|
58
|
+
export function serialProfile(options) {
|
|
59
|
+
const seriesField = assertSlug(options.seriesField ?? "series", "seriesField");
|
|
60
|
+
const numberField = assertSlug(options.numberField ?? "number", "numberField");
|
|
61
|
+
const seriesCollection = assertSlug(options.seriesCollection ?? "series", "seriesCollection");
|
|
62
|
+
if (
|
|
63
|
+
!Array.isArray(options.installmentCollections) ||
|
|
64
|
+
options.installmentCollections.length === 0
|
|
65
|
+
) {
|
|
66
|
+
throw new TypeError("installmentCollections must list at least one collection");
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
const definitions = [
|
|
70
|
+
{
|
|
71
|
+
slug: seriesCollection,
|
|
72
|
+
label: "Series",
|
|
73
|
+
labelSingular: "Series",
|
|
74
|
+
fields: [{ slug: "title", label: "Title", type: "string", required: true }],
|
|
75
|
+
},
|
|
76
|
+
];
|
|
77
|
+
|
|
78
|
+
for (const entry of options.installmentCollections) {
|
|
79
|
+
const { slug, label } = typeof entry === "string" ? { slug: entry } : entry;
|
|
80
|
+
assertSlug(slug, "installment collection");
|
|
81
|
+
definitions.push({
|
|
82
|
+
slug,
|
|
83
|
+
label: label ?? labelFor(slug),
|
|
84
|
+
fields: seriesFields(seriesField, numberField),
|
|
85
|
+
});
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
if (options.chaptersCollection) {
|
|
89
|
+
const slug = assertSlug(options.chaptersCollection, "chaptersCollection");
|
|
90
|
+
definitions.push({
|
|
91
|
+
slug,
|
|
92
|
+
label: "Chapters",
|
|
93
|
+
labelSingular: "Chapter",
|
|
94
|
+
fields: [
|
|
95
|
+
{ slug: "title", label: "Title", type: "string", required: true },
|
|
96
|
+
...seriesFields(seriesField, numberField),
|
|
97
|
+
],
|
|
98
|
+
});
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
return definitions;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* SQL for the composite index that makes navigation fast on large series.
|
|
106
|
+
* EmDash indexes each field separately, which can't serve "next installment in
|
|
107
|
+
* this series" without scanning; this index answers it in one row. Apply it
|
|
108
|
+
* once per installment collection (SQLite, D1 and PostgreSQL all accept it).
|
|
109
|
+
*
|
|
110
|
+
* @param {string} collection
|
|
111
|
+
* @param {{ seriesField?: string, numberField?: string }} [fields]
|
|
112
|
+
* @returns {string}
|
|
113
|
+
*/
|
|
114
|
+
export function navigationIndexSql(collection, fields = {}) {
|
|
115
|
+
const table = assertSlug(collection, "collection");
|
|
116
|
+
const seriesField = assertSlug(fields.seriesField ?? "series", "seriesField");
|
|
117
|
+
const numberField = assertSlug(fields.numberField ?? "number", "numberField");
|
|
118
|
+
return `CREATE INDEX IF NOT EXISTS mm_series_nav_${table} ON ec_${table} (${seriesField}, ${numberField}, id) WHERE deleted_at IS NULL`;
|
|
119
|
+
}
|