@matterandmotion/emdash-engagement 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,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,105 @@
1
- # Temporary Holding Version
1
+ # @matterandmotion/emdash-engagement
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Likes, view counts and "most popular" lists for [EmDash CMS](https://github.com/emdash-cms/emdash) entries. Counting happens in the browser after the page loads, so pages stay fully cacheable. No cookies, and no IP addresses stored.
4
+
5
+ > **Status: pre-release (0.x).** Settings and routes may change between minor versions.
6
+
7
+ ```
8
+ pnpm add @matterandmotion/emdash-engagement
9
+ ```
10
+
11
+ ```js
12
+ // astro.config.mjs
13
+ import engagement from "@matterandmotion/emdash-engagement";
14
+
15
+ emdash({ database, storage, plugins: [engagement] });
16
+ ```
17
+
18
+ It's a standard-format plugin, so it also runs sandboxed (`sandboxed: [engagement]`). Use one install path per site.
19
+
20
+ ## The component
21
+
22
+ ```astro
23
+ ---
24
+ import Engagement from "@matterandmotion/emdash-engagement/astro/Engagement.astro";
25
+ ---
26
+ <Engagement collection="posts" id={entry.data.id} />
27
+ ```
28
+
29
+ It shows a like button and the view count. After the page loads it:
30
+ - fetches the counts (cached for 30 seconds);
31
+ - sends one view per entry per day from each browser;
32
+ - sends a like on click, and remembers it in the browser's local storage so the button stays pressed;
33
+ - remembers the highest counts it has shown, so a reload within the 30-second cache never shows fewer views than the visitor just saw.
34
+
35
+ Props: `collection`, `id` (the entry's ID, not its slug), `countView` (default `true`), `showViews` (default `true`), `likeLabel`, `viewLabel` and `viewsLabel` (the words after a count of one and any other count, chosen by the page language's plural rules), and `pluginId` for registry installs. Style it through the `mm-engagement` classes, `--mm-engagement-font-size` and `--mm-engagement-liked`. Without JavaScript it stays hidden.
36
+
37
+ ## Popular lists
38
+
39
+ Server code reads top lists and counts in-process:
40
+
41
+ ```astro
42
+ ---
43
+ import { getTopEntries } from "@matterandmotion/emdash-engagement/astro";
44
+ import { getEmDashEntry } from "emdash";
45
+
46
+ const top = await getTopEntries(Astro, { collection: "posts", by: "views", period: "week", limit: 5 });
47
+ const entries = (await Promise.all(top.map(({ id }) => getEmDashEntry("posts", id)))).flatMap(
48
+ ({ entry }) => (entry ? [entry] : []),
49
+ );
50
+ ---
51
+ ```
52
+
53
+ Look each ID up before showing it: an entry may have been unpublished since it was counted, and `getEmDashEntry` returns only published entries.
54
+
55
+ | Helper | Returns |
56
+ |---|---|
57
+ | `getTopEntries(Astro, { collection, by?, period?, limit? })` | `[{ id, likes, views }]`, by `"views"` (default) or `"likes"`, for `"all"` time (default) or this `"week"` (ISO week, UTC) |
58
+ | `getCounts(Astro, { collection, ids })` | `{ [id]: { likes, views } }` for up to 50 entries |
59
+ | `engagementEndpoint({ pluginId? })` | The routes' base path, for your own browser code |
60
+
61
+ ## How counting works
62
+
63
+ - **Visitors** are a hash of IP address and user agent under a salt that changes every day (UTC) and is then discarded. A hash can't be reversed into an address or linked across days.
64
+ - **Bots** (crawlers, link previews, scripts, requests without a user agent) aren't counted.
65
+ - **Only published entries** are counted, in the collections you choose.
66
+ - **Likes:** one per visitor, entry and day on the server; the browser remembers a like for good. Think of them as applause rather than a vote: a visitor on a new device or a new day can like again.
67
+ - **Views:** the component sends at most one a day per browser. The server also caps each visitor at 300 views and 60 likes an hour.
68
+ - **Periods:** each like and view updates an all-time counter and one for the current ISO week. Weekly counters older than eight weeks are deleted.
69
+
70
+ ## Settings
71
+
72
+ | Key | Default | Meaning |
73
+ |---|---|---|
74
+ | `collections` | *(empty)* | Comma-separated collections to count. Empty counts every collection. |
75
+
76
+ ## Routes
77
+
78
+ Under `/_emdash/api/plugins/mm-engagement/` (`r_…` for registry installs):
79
+
80
+ | Route | Access | Purpose |
81
+ |---|---|---|
82
+ | `POST view` | Public | `{ collection, id }` → `{ ok, counted, views? }` |
83
+ | `POST like` | Public | `{ collection, id }` → `{ ok, liked, likes }` |
84
+ | `GET counts?collection=&ids=` | Public, cached 30 s | `{ counts: { [id]: { likes, views } } }` |
85
+ | `GET top?collection=&by=&period=&limit=` | Public, cached 5 min | `{ entries: [{ id, likes, views }] }` |
86
+ | `POST export` | Administrators | `{ cursor? }` → all-time counts, 100 per page |
87
+
88
+ ## Hooks
89
+
90
+ | Hook | Does |
91
+ |---|---|
92
+ | `cron` (`cleanup`, hourly) | Deletes expired like marks, rate-limit windows and old weekly counters. |
93
+ | `plugin:activate` | Schedules the task. |
94
+
95
+ Capability: `content:read`.
96
+
97
+ ## Data and limits
98
+
99
+ - **Storage:** `counters` (per entry: all-time and weekly likes and views), `marks` (one per like, kept two days), `limits` (hourly per-visitor windows).
100
+ - **KV:** `state:salt`, today's salt.
101
+ - **Personal data:** none kept. Visitor hashes use a salt discarded daily.
102
+
103
+ ## License
104
+
105
+ MIT © Matter & Motion
@@ -0,0 +1,208 @@
1
+ ---
2
+ /**
3
+ * A like button and view count for one entry. Counting happens in the browser
4
+ * after the page loads, so the page itself stays cacheable.
5
+ *
6
+ * - Sends one view per entry per day from each browser (unless `countView` is false).
7
+ * - Remembers a like in localStorage, so the button stays pressed, and the
8
+ * highest counts it has shown, so a cached response never shows fewer.
9
+ * - Without JavaScript the counts and button stay hidden.
10
+ *
11
+ * Style it through the `mm-engagement` classes or the CSS custom properties below.
12
+ */
13
+ import { engagementEndpoint } from "./index";
14
+
15
+ interface Props {
16
+ collection: string;
17
+ /** The entry's ID (`entry.data.id`), not its slug. */
18
+ id: string;
19
+ /** Set for registry installs (`r_…`). */
20
+ pluginId?: string;
21
+ /** Count this page as a view. Default true. */
22
+ countView?: boolean;
23
+ /** Show the view count. Default true. */
24
+ showViews?: boolean;
25
+ likeLabel?: string;
26
+ /** Shown after a count of one ("1 view"), as the page language's plural rules decide. */
27
+ viewLabel?: string;
28
+ /** Shown after any other count ("0 views", "2 views"). */
29
+ viewsLabel?: string;
30
+ }
31
+
32
+ const {
33
+ collection,
34
+ id,
35
+ pluginId,
36
+ countView = true,
37
+ showViews = true,
38
+ likeLabel = "Like",
39
+ viewLabel = "view",
40
+ viewsLabel = "views",
41
+ } = Astro.props;
42
+ const endpoint = engagementEndpoint(pluginId ? { pluginId } : {});
43
+ ---
44
+
45
+ <div
46
+ class="mm-engagement"
47
+ data-mm-engagement
48
+ data-endpoint={endpoint}
49
+ data-collection={collection}
50
+ data-id={id}
51
+ data-count-view={countView ? "1" : "0"}
52
+ hidden
53
+ >
54
+ <button type="button" class="mm-engagement__like" aria-pressed="false" data-like>
55
+ <span aria-hidden="true" class="mm-engagement__icon">♥</span>
56
+ <span>{likeLabel}</span>
57
+ <span class="mm-engagement__count" data-likes></span>
58
+ </button>
59
+ {
60
+ showViews && (
61
+ <span class="mm-engagement__views">
62
+ <span data-views>0</span> <span data-views-label data-one={viewLabel} data-other={viewsLabel}>{viewsLabel}</span>
63
+ </span>
64
+ )
65
+ }
66
+ </div>
67
+
68
+ <style>
69
+ .mm-engagement {
70
+ display: flex;
71
+ align-items: center;
72
+ gap: 0.75em;
73
+ font-size: var(--mm-engagement-font-size, 0.9rem);
74
+ }
75
+ .mm-engagement[hidden] {
76
+ display: none;
77
+ }
78
+ .mm-engagement__like {
79
+ display: inline-flex;
80
+ align-items: center;
81
+ gap: 0.35em;
82
+ padding: 0.3em 0.8em;
83
+ border: 1px solid currentColor;
84
+ border-radius: 999px;
85
+ background: transparent;
86
+ color: inherit;
87
+ font: inherit;
88
+ cursor: pointer;
89
+ }
90
+ .mm-engagement__like[aria-pressed="true"] .mm-engagement__icon {
91
+ color: var(--mm-engagement-liked, #d6336c);
92
+ }
93
+ .mm-engagement__like:disabled {
94
+ cursor: default;
95
+ }
96
+ </style>
97
+
98
+ <script>
99
+ type Counts = { likes: number; views: number };
100
+
101
+ function memory() {
102
+ try {
103
+ return window.localStorage;
104
+ } catch {
105
+ return null;
106
+ }
107
+ }
108
+
109
+ async function call(url: string, init?: RequestInit) {
110
+ const response = await fetch(url, init);
111
+ if (!response.ok) return null;
112
+ const json = (await response.json()) as { data?: unknown };
113
+ return (json.data ?? json) as Record<string, unknown>;
114
+ }
115
+
116
+ /** "one" or another plural category for `count`, in the page's language. */
117
+ function pluralCategory(count: number) {
118
+ try {
119
+ return new Intl.PluralRules(document.documentElement.lang || undefined).select(count);
120
+ } catch {
121
+ return count === 1 ? "one" : "other";
122
+ }
123
+ }
124
+
125
+ function post(url: string, body: unknown) {
126
+ return call(url, {
127
+ method: "POST",
128
+ headers: { "content-type": "application/json" },
129
+ body: JSON.stringify(body),
130
+ keepalive: true,
131
+ });
132
+ }
133
+
134
+ function setup(root: HTMLElement) {
135
+ const { endpoint, collection, id, countView } = root.dataset;
136
+ if (!endpoint || !collection || !id || root.dataset.ready) return;
137
+ root.dataset.ready = "1";
138
+ const store = memory();
139
+ const key = `mm-engagement:${collection}:${id}`;
140
+ const today = new Date().toISOString().slice(0, 10);
141
+ const button = root.querySelector<HTMLButtonElement>("[data-like]");
142
+ const likes = root.querySelector<HTMLElement>("[data-likes]");
143
+ const views = root.querySelector<HTMLElement>("[data-views]");
144
+ const viewsLabel = root.querySelector<HTMLElement>("[data-views-label]");
145
+ const target = { collection, id };
146
+
147
+ // The highest counts this browser has seen for the entry. All-time counts
148
+ // only grow, so a cached counts response (30 s), or one that arrives after
149
+ // this browser's own view or like, never takes them back down.
150
+ const seenKey = `${key}:seen`;
151
+ const seen: Partial<Counts> = {};
152
+ const show = (counts: Partial<Counts>) => {
153
+ if (typeof counts.likes === "number") {
154
+ seen.likes = Math.max(seen.likes ?? 0, counts.likes);
155
+ if (likes) likes.textContent = String(seen.likes);
156
+ }
157
+ if (typeof counts.views === "number") {
158
+ seen.views = Math.max(seen.views ?? 0, counts.views);
159
+ if (views) views.textContent = String(seen.views);
160
+ if (viewsLabel) {
161
+ const { one, other } = viewsLabel.dataset;
162
+ viewsLabel.textContent = (pluralCategory(seen.views) === "one" ? one : other) ?? "";
163
+ }
164
+ }
165
+ try {
166
+ store?.setItem(seenKey, JSON.stringify(seen));
167
+ } catch {
168
+ // Storage full or blocked: the counts still show.
169
+ }
170
+ };
171
+ try {
172
+ const saved = JSON.parse(store?.getItem(seenKey) ?? "null") as Partial<Counts> | null;
173
+ if (saved && typeof saved === "object") show(saved);
174
+ } catch {
175
+ // Unreadable: wait for the server's counts.
176
+ }
177
+ const pressed = () => {
178
+ button?.setAttribute("aria-pressed", "true");
179
+ if (button) button.disabled = true;
180
+ };
181
+
182
+ if (store?.getItem(`${key}:liked`) === "1") pressed();
183
+ root.hidden = false;
184
+
185
+ const query = new URLSearchParams({ collection, ids: id });
186
+ call(`${endpoint}/counts?${query}`).then((data) => {
187
+ const counts = (data?.counts as Record<string, Counts> | undefined)?.[id];
188
+ if (counts) show(counts);
189
+ });
190
+
191
+ if (countView === "1" && store?.getItem(`${key}:viewed`) !== today) {
192
+ post(`${endpoint}/view`, target).then((data) => {
193
+ store?.setItem(`${key}:viewed`, today);
194
+ if (data && typeof data.views === "number") show({ views: data.views });
195
+ });
196
+ }
197
+
198
+ button?.addEventListener("click", () => {
199
+ pressed();
200
+ store?.setItem(`${key}:liked`, "1");
201
+ post(`${endpoint}/like`, target).then((data) => {
202
+ if (data && typeof data.likes === "number") show({ likes: data.likes });
203
+ });
204
+ });
205
+ }
206
+
207
+ for (const root of document.querySelectorAll<HTMLElement>("[data-mm-engagement]")) setup(root);
208
+ </script>
package/astro/index.ts ADDED
@@ -0,0 +1,90 @@
1
+ /**
2
+ * Site-side helpers. Server code (pages, endpoints) reads counts and top lists
3
+ * in-process through EmDash's public plugin route handler; the browser part
4
+ * lives in `Engagement.astro`.
5
+ *
6
+ * Shipped as TypeScript source; the site's Vite compiles it.
7
+ */
8
+
9
+ export interface AstroLike {
10
+ locals: unknown;
11
+ request: Request;
12
+ }
13
+
14
+ export interface EngagementOptions {
15
+ /** The plugin's ID: `mm-engagement` for config installs, `r_…` for registry installs. */
16
+ pluginId?: string;
17
+ }
18
+
19
+ export interface EntryCounts {
20
+ likes: number;
21
+ views: number;
22
+ }
23
+
24
+ type PublicRouteHandler = (
25
+ pluginId: string,
26
+ method: string,
27
+ path: string,
28
+ request: Request,
29
+ ) => Promise<{ success: boolean; data?: unknown }>;
30
+
31
+ /** The base URL of the plugin's routes, for browser code. */
32
+ export function engagementEndpoint(options: EngagementOptions = {}): string {
33
+ return `/_emdash/api/plugins/${options.pluginId ?? "mm-engagement"}`;
34
+ }
35
+
36
+ async function get<T>(
37
+ astro: AstroLike,
38
+ route: string,
39
+ query: Record<string, string>,
40
+ options: EngagementOptions,
41
+ ): Promise<T | null> {
42
+ const emdash = (astro.locals as { emdash?: { handlePublicPluginApiRoute?: PublicRouteHandler } })
43
+ .emdash;
44
+ const handler = emdash?.handlePublicPluginApiRoute;
45
+ if (!handler) return null;
46
+ const pluginId = options.pluginId ?? "mm-engagement";
47
+ const url = new URL(`${engagementEndpoint(options)}/${route}`, astro.request.url);
48
+ for (const [key, value] of Object.entries(query)) url.searchParams.set(key, value);
49
+ const result = await handler(pluginId, "GET", `/${route}`, new Request(url, { method: "GET" }));
50
+ return result.success ? (result.data as T) : null;
51
+ }
52
+
53
+ /**
54
+ * Most-viewed or most-liked entries, as `{ id, likes, views }`. Look the IDs up
55
+ * with `getEmDashEntry` (which returns only published entries) before showing them.
56
+ */
57
+ export async function getTopEntries(
58
+ astro: AstroLike,
59
+ input: { collection: string; by?: "views" | "likes"; period?: "all" | "week"; limit?: number },
60
+ options: EngagementOptions = {},
61
+ ): Promise<Array<{ id: string } & EntryCounts>> {
62
+ const data = await get<{ entries: Array<{ id: string } & EntryCounts> }>(
63
+ astro,
64
+ "top",
65
+ {
66
+ collection: input.collection,
67
+ by: input.by ?? "views",
68
+ period: input.period ?? "all",
69
+ limit: String(input.limit ?? 10),
70
+ },
71
+ options,
72
+ );
73
+ return data?.entries ?? [];
74
+ }
75
+
76
+ /** All-time likes and views for up to 50 entries of one collection. */
77
+ export async function getCounts(
78
+ astro: AstroLike,
79
+ input: { collection: string; ids: readonly string[] },
80
+ options: EngagementOptions = {},
81
+ ): Promise<Record<string, EntryCounts>> {
82
+ if (input.ids.length === 0) return {};
83
+ const data = await get<{ counts: Record<string, EntryCounts> }>(
84
+ astro,
85
+ "counts",
86
+ { collection: input.collection, ids: input.ids.slice(0, 50).join(",") },
87
+ options,
88
+ );
89
+ return data?.counts ?? {};
90
+ }
@@ -0,0 +1,5 @@
1
+ // Auto-generated by emdash-plugin build. Do not edit.
2
+ import type { PluginDescriptor } from "emdash";
3
+
4
+ declare const descriptor: PluginDescriptor;
5
+ export default descriptor;
package/dist/index.mjs ADDED
@@ -0,0 +1,121 @@
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-engagement",
10
+ "displayName": "Engagement",
11
+ "description": "Likes, view counts and top lists, counted from the browser so pages stay cacheable, with no cookies.",
12
+ "version": "0.1.1",
13
+ "format": "standard",
14
+ "entrypoint": "@matterandmotion/emdash-engagement/sandbox",
15
+ "capabilities": [
16
+ "content:read"
17
+ ],
18
+ "allowedHosts": [],
19
+ "storage": {
20
+ "counters": {
21
+ "indexes": [
22
+ "period",
23
+ [
24
+ "period",
25
+ "collection",
26
+ "likes"
27
+ ],
28
+ [
29
+ "period",
30
+ "collection",
31
+ "views"
32
+ ]
33
+ ]
34
+ },
35
+ "marks": {
36
+ "indexes": [
37
+ "expiresAt"
38
+ ]
39
+ },
40
+ "limits": {
41
+ "indexes": [
42
+ "expiresAt"
43
+ ]
44
+ }
45
+ },
46
+ "hooks": [
47
+ {
48
+ "name": "plugin:activate",
49
+ "errorPolicy": "continue"
50
+ },
51
+ {
52
+ "name": "cron",
53
+ "timeout": 10000,
54
+ "errorPolicy": "continue"
55
+ }
56
+ ],
57
+ "routes": [
58
+ {
59
+ "name": "view",
60
+ "methods": [
61
+ "POST"
62
+ ],
63
+ "request": {
64
+ "body": "json",
65
+ "headers": [
66
+ "user-agent"
67
+ ]
68
+ },
69
+ "public": true
70
+ },
71
+ {
72
+ "name": "like",
73
+ "methods": [
74
+ "POST"
75
+ ],
76
+ "request": {
77
+ "body": "json",
78
+ "headers": [
79
+ "user-agent"
80
+ ]
81
+ },
82
+ "public": true
83
+ },
84
+ {
85
+ "name": "counts",
86
+ "methods": [
87
+ "GET"
88
+ ],
89
+ "request": {
90
+ "body": "none"
91
+ },
92
+ "public": true,
93
+ "cacheControl": "public, max-age=30"
94
+ },
95
+ {
96
+ "name": "top",
97
+ "methods": [
98
+ "GET"
99
+ ],
100
+ "request": {
101
+ "body": "none"
102
+ },
103
+ "public": true,
104
+ "cacheControl": "public, max-age=300"
105
+ },
106
+ {
107
+ "name": "export",
108
+ "permission": "plugins:manage"
109
+ }
110
+ ],
111
+ "settingsSchema": {
112
+ "collections": {
113
+ "label": "Collections to count",
114
+ "description": "Comma-separated collection slugs. Leave empty to count every collection.",
115
+ "type": "string",
116
+ "default": ""
117
+ }
118
+ }
119
+ });
120
+
121
+ export default descriptor;
@@ -0,0 +1,117 @@
1
+ {
2
+ "id": "mm-engagement",
3
+ "version": "0.1.1",
4
+ "declaredAccess": {
5
+ "content": {
6
+ "read": {}
7
+ }
8
+ },
9
+ "capabilities": [
10
+ "content:read"
11
+ ],
12
+ "allowedHosts": [],
13
+ "storage": {
14
+ "counters": {
15
+ "indexes": [
16
+ "period",
17
+ [
18
+ "period",
19
+ "collection",
20
+ "likes"
21
+ ],
22
+ [
23
+ "period",
24
+ "collection",
25
+ "views"
26
+ ]
27
+ ]
28
+ },
29
+ "marks": {
30
+ "indexes": [
31
+ "expiresAt"
32
+ ]
33
+ },
34
+ "limits": {
35
+ "indexes": [
36
+ "expiresAt"
37
+ ]
38
+ }
39
+ },
40
+ "hooks": [
41
+ {
42
+ "name": "plugin:activate",
43
+ "errorPolicy": "continue"
44
+ },
45
+ {
46
+ "name": "cron",
47
+ "timeout": 10000,
48
+ "errorPolicy": "continue"
49
+ }
50
+ ],
51
+ "routes": [
52
+ {
53
+ "name": "view",
54
+ "methods": [
55
+ "POST"
56
+ ],
57
+ "request": {
58
+ "body": "json",
59
+ "headers": [
60
+ "user-agent"
61
+ ]
62
+ },
63
+ "public": true
64
+ },
65
+ {
66
+ "name": "like",
67
+ "methods": [
68
+ "POST"
69
+ ],
70
+ "request": {
71
+ "body": "json",
72
+ "headers": [
73
+ "user-agent"
74
+ ]
75
+ },
76
+ "public": true
77
+ },
78
+ {
79
+ "name": "counts",
80
+ "methods": [
81
+ "GET"
82
+ ],
83
+ "request": {
84
+ "body": "none"
85
+ },
86
+ "public": true,
87
+ "cacheControl": "public, max-age=30"
88
+ },
89
+ {
90
+ "name": "top",
91
+ "methods": [
92
+ "GET"
93
+ ],
94
+ "request": {
95
+ "body": "none"
96
+ },
97
+ "public": true,
98
+ "cacheControl": "public, max-age=300"
99
+ },
100
+ {
101
+ "name": "export",
102
+ "permission": "plugins:manage"
103
+ }
104
+ ],
105
+ "admin": {
106
+ "settingsSchema": {
107
+ "collections": {
108
+ "label": "Collections to count",
109
+ "description": "Comma-separated collection slugs. Leave empty to count every collection.",
110
+ "type": "string",
111
+ "default": ""
112
+ }
113
+ },
114
+ "pages": [],
115
+ "widgets": []
116
+ }
117
+ }
@@ -0,0 +1,7 @@
1
+ import { SandboxedPlugin } from "emdash/plugin";
2
+
3
+ //#region src/plugin.d.ts
4
+ declare const plugin: SandboxedPlugin;
5
+ //#endregion
6
+ export { plugin as default };
7
+ //# sourceMappingURL=plugin.d.mts.map
@@ -0,0 +1 @@
1
+ const e=new TextEncoder;function t(t){return e.encode(t)}function n(e){return typeof e==`string`?t(e):e}function r(e){let t=``;for(let n of e)t+=n.toString(16).padStart(2,`0`);return t}function i(e){return new Uint8Array(e)}async function a(e,t){let r=await crypto.subtle.importKey(`raw`,i(n(e)),{name:`HMAC`,hash:`SHA-256`},!1,[`sign`]);return new Uint8Array(await crypto.subtle.sign(`HMAC`,r,i(n(t))))}function o(e){return e instanceof Error?e.message:String(e)}function s(e,t){return async(n,r)=>{try{await t(n,r)}catch(t){r.log.error(`${e} failed`,{error:o(t)})}}}async function c(e,t,n,{now:r=Date.now(),windowMs:i=3600*1e3}={}){let a=Math.floor(r/i),o=`${t}:${a}`;for(let t=0;t<3;t++){let t=await e.updateIf(o,{where:{},delta:{count:{inc:1}}});if(t.applied)return t.data.count<=n;if((await e.compareAndSet(o,null,{count:1,expiresAt:(a+2)*i})).applied)return n>=1}return!1}async function l(e,t=Date.now()){let{items:n}=await e.query({where:{expiresAt:{lt:t}},limit:100});return n.length===0?0:e.deleteMany(n.map(e=>e.id))}function u(e){if(!e)throw Error(`A storage collection this plugin needs isn't declared`);return e}function d(e){let t=new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate()));t.setUTCDate(t.getUTCDate()+4-(t.getUTCDay()||7));let n=Date.UTC(t.getUTCFullYear(),0,1),r=Math.ceil(((t.getTime()-n)/864e5+1)/7);return`${t.getUTCFullYear()}-W${String(r).padStart(2,`0`)}`}function f(e,t){return e===`all`?`all`:d(t)}function p(e,t,n){return`${e}|${t}|${n}`}async function m(e,t,n,r){let i=p(t.period,t.collection,t.entryId),a=r.toISOString();for(let r=0;r<3;r++){let r=await e.updateIf(i,{where:{},set:{updatedAt:a},delta:{[n]:{inc:1}}});if(r.applied)return r.data[n];if((await e.compareAndSet(i,null,{...t,likes:n===`likes`?1:0,views:n===`views`?1:0,updatedAt:a})).applied)return 1}throw Error(`Couldn't update counter ${i}`)}async function h(e,t,n,r,i){let[a]=await Promise.all([m(e,{collection:t,entryId:n,period:`all`},r,i),m(e,{collection:t,entryId:n,period:d(i)},r,i)]);return a}async function g(e,t,n){let r=await e.getMany(n.map(e=>p(`all`,t,e))),i={};for(let e of n){let n=r.get(p(`all`,t,e));i[e]={likes:n?.likes??0,views:n?.views??0}}return i}async function _(e,t){let{items:n}=await e.query({where:{period:f(t.period,t.now),collection:t.collection},orderBy:{[t.by]:`desc`},limit:t.limit});return n.filter(e=>e.data[t.by]>0).map(({data:e})=>({id:e.entryId,likes:e.likes,views:e.views}))}async function v(e,t,n=8){let r=d(new Date(t.getTime()-n*7*864e5)),{items:i}=await e.query({where:{period:{lt:r}},limit:100});return i.length===0?0:e.deleteMany(i.map(e=>e.id))}const y=`state:salt`;function b(e){return e.toISOString().slice(0,10)}function x(){let e=new Uint8Array(32);return crypto.getRandomValues(e),r(e)}async function S(e,t){let n=b(t);for(let t=0;t<3;t++){let t=await e.getVersioned(y);if(t?.value?.day===n)return t.value.salt;let r={day:n,salt:x()};if((await e.compareAndSet(y,t?.revision??null,r)).applied)return r.salt}throw Error(`Couldn't rotate the visitor salt`)}async function C(e,t,n){return r(await a(e,`${t??``}\n${n??``}`)).slice(0,32)}const w=/bot|crawl|spider|slurp|preview|facebookexternalhit|embedly|headless|lighthouse|python-requests|curl|wget|httpclient|go-http-client|java\/|okhttp|scrapy/i;function T(e){return!e||w.test(e)}const E=`cleanup`,D=/^[a-z][a-z0-9_]*$/,O=/^[A-Za-z0-9_-]{1,64}$/;function k(e){return{counters:u(e.storage.counters),marks:u(e.storage.marks),limits:u(e.storage.limits)}}function A(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:{}}function j(e){let t=Array.isArray(e)?e[0]:e;return typeof t==`string`?t:void 0}async function M(e){let t=await e.settings.get(`collections`)??``;return String(t).split(/[,\n]/).map(e=>e.trim()).filter(e=>D.test(e))}async function N(e,t){let n=A(e),r=j(n.collection),i=j(n.id);if(!r||!D.test(r)||!i||!O.test(i))return{error:`invalid-input`};let a=await M(t);return a.length>0&&!a.includes(r)?{error:`not-counted`}:{collection:r,id:i}}async function P(e,t,n,r,i){let a=t.request.headers[`user-agent`]??null;if(T(a))return{skip:`bot`};if((await n.content?.get(e.collection,e.id))?.status!==`published`)return{error:`not-found`};let o=A(t.requestMeta),s=typeof o.ip==`string`?o.ip:null,l=await C(await S(n.kv,i),s,a),u=r===`views`?300:60;return await c(k(n).limits,`${r}:${l}`,u,{now:i.getTime()})?{visitor:l}:{skip:`limited`}}async function F(e,t){if(e.name!==E)return;let n=new Date,{counters:r,marks:i,limits:a}=k(t),[o,s,c]=await Promise.all([l(i,n.getTime()),l(a,n.getTime()),v(r,n)]);o+s+c>0&&t.log.info(`Engagement cleanup`,{deletedMarks:o,deletedLimits:s,deletedWeeks:c})}const I={hooks:{"plugin:activate":{errorPolicy:`continue`,handler:s(`engagement activation`,async(e,t)=>{await t.cron?.schedule(E,{schedule:`17 * * * *`})})},cron:{timeout:1e4,errorPolicy:`continue`,handler:s(`engagement cleanup`,F)}},routes:{view:{public:!0,methods:[`POST`],request:{body:`json`,headers:[`user-agent`]},handler:async(e,t)=>{let n=await N(e.input,t);if(`error`in n)return{ok:!1,error:n.error};let r=new Date,i=await P(n,e,t,`views`,r);return`error`in i?{ok:!1,error:i.error}:`skip`in i?{ok:!0,counted:!1}:{ok:!0,counted:!0,views:await h(k(t).counters,n.collection,n.id,`views`,r)}}},like:{public:!0,methods:[`POST`],request:{body:`json`,headers:[`user-agent`]},handler:async(e,t)=>{let n=await N(e.input,t);if(`error`in n)return{ok:!1,error:n.error};let r=new Date,i=await P(n,e,t,`likes`,r);if(`error`in i)return{ok:!1,error:i.error};let{counters:a,marks:o}=k(t);return`skip`in i||!(await o.compareAndSet(`${b(r)}|${i.visitor}|${n.collection}|${n.id}`,null,{expiresAt:r.getTime()+2*864e5})).applied?{ok:!0,liked:!1,likes:await(async()=>(await g(a,n.collection,[n.id]))[n.id]?.likes??0)()}:{ok:!0,liked:!0,likes:await h(a,n.collection,n.id,`likes`,r)}}},counts:{public:!0,methods:[`GET`],request:{body:`none`},cacheControl:`public, max-age=30`,handler:async(e,t)=>{let n=A(e.input),r=j(n.collection),i=[...new Set((j(n.ids)??``).split(`,`).map(e=>e.trim()).filter(e=>O.test(e)))].slice(0,50);return!r||!D.test(r)||i.length===0?{counts:{}}:{counts:await g(k(t).counters,r,i)}}},top:{public:!0,methods:[`GET`],request:{body:`none`},cacheControl:`public, max-age=300`,handler:async(e,t)=>{let n=A(e.input),r=j(n.collection);if(!r||!D.test(r))return{entries:[]};let i=j(n.by)===`likes`?`likes`:`views`,a=j(n.period)===`week`?`week`:`all`,o=Math.min(Math.max(Number(j(n.limit))||10,1),50);return{entries:await _(k(t).counters,{collection:r,by:i,period:a,limit:o,now:new Date})}}},export:{permission:`plugins:manage`,handler:async(e,t)=>{let n=j(A(e.input).cursor),r=await k(t).counters.query({where:{period:`all`},limit:100,...n?{cursor:n}:{}});return{items:r.items.map(({data:e})=>({collection:e.collection,id:e.entryId,likes:e.likes,views:e.views})),cursor:r.hasMore?r.cursor??null:null}}}}};export{I as default};
@@ -0,0 +1,46 @@
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-engagement/...).
5
+ "slug": "mm-engagement",
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": "Engagement",
11
+ "description": "Likes, view counts and top lists, counted from the browser so pages stay cacheable, with no cookies.",
12
+ "keywords": ["likes", "views", "popular", "analytics"],
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
+ // content:read: only published entries are counted.
19
+ "capabilities": ["content:read"],
20
+ "allowedHosts": [],
21
+ "storage": {
22
+ // One document per entry and period ("all", or an ISO week such as 2026-W49).
23
+ "counters": {
24
+ "indexes": ["period", ["period", "collection", "likes"], ["period", "collection", "views"]]
25
+ },
26
+ // One like per visitor, entry and day; deleted after two days.
27
+ "marks": { "indexes": ["expiresAt"] },
28
+ // Hourly per-visitor counters that stop scripted inflation.
29
+ "limits": { "indexes": ["expiresAt"] }
30
+ },
31
+
32
+ "admin": {
33
+ "settingsSchema": {
34
+ "collections": {
35
+ "type": "string",
36
+ "label": "Collections to count",
37
+ "description": "Comma-separated collection slugs. Leave empty to count every collection.",
38
+ "default": ""
39
+ }
40
+ }
41
+ },
42
+
43
+ "release": {
44
+ "requires": { "env:emdash": ">=1.6.0" }
45
+ }
46
+ }
package/package.json CHANGED
@@ -1,6 +1,67 @@
1
1
  {
2
2
  "name": "@matterandmotion/emdash-engagement",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.1",
4
+ "description": "Likes, view counts and top lists for EmDash CMS entries, counted from the browser so pages stay cacheable, with no cookies.",
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
+ "./astro/Engagement.astro": "./astro/Engagement.astro"
15
+ },
16
+ "files": [
17
+ "dist/*.mjs",
18
+ "dist/*.d.mts",
19
+ "dist/manifest.json",
20
+ "astro",
21
+ "emdash-plugin.jsonc",
22
+ "README.md"
23
+ ],
24
+ "keywords": [
25
+ "emdash",
26
+ "emdash-plugin",
27
+ "likes",
28
+ "views",
29
+ "analytics",
30
+ "popular"
31
+ ],
32
+ "repository": {
33
+ "type": "git",
34
+ "url": "git+https://github.com/matterandmotion/emdash-plugins.git",
35
+ "directory": "packages/engagement"
36
+ },
37
+ "homepage": "https://github.com/matterandmotion/emdash-plugins/tree/main/packages/engagement#readme",
38
+ "bugs": "https://github.com/matterandmotion/emdash-plugins/issues",
39
+ "engines": {
40
+ "node": ">=22.16"
41
+ },
42
+ "publishConfig": {
43
+ "access": "public"
44
+ },
45
+ "peerDependencies": {
46
+ "astro": ">=6.0.0",
47
+ "emdash": "^1.6.0"
48
+ },
49
+ "peerDependenciesMeta": {
50
+ "astro": {
51
+ "optional": true
52
+ }
53
+ },
54
+ "devDependencies": {
55
+ "@emdash-cms/plugin-cli": "0.13.7",
56
+ "@emdash-cms/plugin-test": "0.2.13",
57
+ "emdash": "1.6.0",
58
+ "@matterandmotion/emdash-plugin-toolkit": "0.1.0"
59
+ },
60
+ "scripts": {
61
+ "validate": "emdash-plugin validate",
62
+ "build": "emdash-plugin build",
63
+ "bundle": "emdash-plugin bundle",
64
+ "typecheck": "tsc --noEmit",
65
+ "test": "emdash-plugin validate && vitest run"
66
+ }
6
67
  }