@emdashjetpack/astro 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 emdashJetpack
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,42 @@
1
- # Temporary Holding Version
1
+ # Jetpack for Astro
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
+ Use these site components with the Jetpack plugins installed on your EmDash site.
4
+
5
+ ## Setup
6
+
7
+ ```sh
8
+ npm install @emdashjetpack/astro
9
+ ```
10
+
11
+ Add `JetpackAnalytics` to your layout and `RelatedPosts` to a post template. Pass the saved EmDash entry ID to `RelatedPosts`.
12
+
13
+ ```astro
14
+ ---
15
+ import JetpackAnalytics from "@emdashjetpack/astro/components/JetpackAnalytics.astro";
16
+ import RelatedPosts from "@emdashjetpack/astro/components/RelatedPosts.astro";
17
+
18
+ const { entry } = Astro.props;
19
+ ---
20
+
21
+ <JetpackAnalytics />
22
+ <RelatedPosts contentId={entry.id} />
23
+ ```
24
+
25
+ For plugins registered in Astro config, the components use the plugin slug by default. For plugins installed through EmDash Registry, use the installed runtime ID from the plugin’s Admin URL under `/_emdash/admin/plugins/<id>`. Set only the IDs for the registry-installed plugins your site uses:
26
+
27
+ | Plugin | Astro environment variable |
28
+ | ----------- | -------------------------------------- |
29
+ | Core | `PUBLIC_JETPACK_CORE_PLUGIN_ID` |
30
+ | CRM | `PUBLIC_JETPACK_CRM_PLUGIN_ID` |
31
+ | Newsletter | `PUBLIC_JETPACK_NEWSLETTER_PLUGIN_ID` |
32
+ | Memberships | `PUBLIC_JETPACK_MEMBERSHIPS_PLUGIN_ID` |
33
+
34
+ For example, add `PUBLIC_JETPACK_CORE_PLUGIN_ID=r_pevqnqnmktkujhfu` to the site’s `.env` for the official Jetpack Core registry install. These IDs are public route segments. Restart the dev server or rebuild after changing them.
35
+
36
+ | Optional feature | Site setup |
37
+ | ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
38
+ | CRM | Add `LeadCaptureForm.astro` to a page that should accept leads. |
39
+ | Newsletter | Configure EmDash email, add `NewsletterForm.astro`, and register the default Astro integration from `@emdashjetpack/astro/integration` to add the confirmation page. |
40
+ | Memberships | Configure the subscription provider, register the default Astro integration from `@emdashjetpack/astro/integration-membership`, and wrap member content in `PaywallGate.astro`. |
41
+
42
+ Import components from `@emdashjetpack/astro/components/<Name>.astro` and add Astro integrations to the site’s existing `integrations` array.
package/package.json CHANGED
@@ -1,6 +1,30 @@
1
1
  {
2
2
  "name": "@emdashjetpack/astro",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.2.0",
4
+ "license": "MIT",
5
+ "repository": {
6
+ "type": "git",
7
+ "url": "git+https://github.com/emdashJetpack/emdashjetpack.git",
8
+ "directory": "packages/astro"
9
+ },
10
+ "files": [
11
+ "src"
12
+ ],
13
+ "type": "module",
14
+ "exports": {
15
+ ".": "./src/index.ts",
16
+ "./integration": "./src/integration.ts",
17
+ "./integration-membership": "./src/integration-membership.ts",
18
+ "./components/*": "./src/components/*"
19
+ },
20
+ "publishConfig": {
21
+ "access": "public"
22
+ },
23
+ "peerDependencies": {
24
+ "astro": "^6.0.0 || ^7.0.0",
25
+ "emdash": "^1.6.0"
26
+ },
27
+ "scripts": {
28
+ "typecheck": "tsc -p tsconfig.json --noEmit"
29
+ }
6
30
  }
@@ -0,0 +1,46 @@
1
+ ---
2
+ import { JETPACK_PLUGIN_ID, jetpackPluginBasePath } from "../plugin-paths.ts";
3
+
4
+ interface Props {
5
+ pluginBasePath?: string;
6
+ path?: string;
7
+ contentId?: string;
8
+ }
9
+
10
+ const {
11
+ pluginBasePath = jetpackPluginBasePath(JETPACK_PLUGIN_ID),
12
+ path = Astro.url.pathname,
13
+ contentId,
14
+ } = Astro.props;
15
+ ---
16
+
17
+ <script
18
+ is:inline
19
+ define:vars={{
20
+ beaconUrl: `${pluginBasePath}/beacon`,
21
+ path,
22
+ contentId: contentId ?? null,
23
+ }}
24
+ >
25
+ async function jetpackBeacon() {
26
+ try {
27
+ await fetch(beaconUrl, {
28
+ method: "POST",
29
+ headers: { "Content-Type": "application/json" },
30
+ body: JSON.stringify({
31
+ path,
32
+ ...(contentId ? { contentId } : {}),
33
+ }),
34
+ keepalive: true,
35
+ credentials: "same-origin",
36
+ });
37
+ } catch {
38
+ /* ignore */
39
+ }
40
+ }
41
+ if (document.prerendering) {
42
+ document.addEventListener("astro:page-load", jetpackBeacon, { once: true });
43
+ } else {
44
+ jetpackBeacon();
45
+ }
46
+ </script>
@@ -0,0 +1,104 @@
1
+ ---
2
+ import { JETPACK_CRM_PLUGIN_ID, jetpackPluginBasePath } from "../plugin-paths.ts";
3
+
4
+ interface Props {
5
+ pluginBasePath?: string;
6
+ source?: string;
7
+ tags?: string[];
8
+ submitLabel?: string;
9
+ class?: string;
10
+ }
11
+
12
+ const {
13
+ pluginBasePath = jetpackPluginBasePath(JETPACK_CRM_PLUGIN_ID),
14
+ source = "website",
15
+ tags = [],
16
+ submitLabel = "Subscribe",
17
+ class: className = "",
18
+ } = Astro.props;
19
+
20
+ const tagList = JSON.stringify(tags);
21
+ ---
22
+
23
+ <form class:list={["jetpack-lead-form", className]} action={`${pluginBasePath}/leads`} method="post" aria-label="Lead capture" data-jetpack-lead>
24
+ <label>
25
+ <span>Email</span>
26
+ <input type="email" name="email" required autocomplete="email" />
27
+ </label>
28
+ <label>
29
+ <span>Name</span>
30
+ <input type="text" name="name" autocomplete="name" />
31
+ </label>
32
+ <div class="jetpack-lead-hp" aria-hidden="true">
33
+ <label>
34
+ <span>Website</span>
35
+ <input type="text" name="website_url" tabindex="-1" autocomplete="off" />
36
+ </label>
37
+ </div>
38
+ <button type="submit">{submitLabel}</button>
39
+ <p class="jetpack-lead-status" data-status role="status"></p>
40
+ </form>
41
+
42
+ <script
43
+ define:vars={{
44
+ source,
45
+ tags: tagList,
46
+ }}
47
+ >
48
+ const form = document.currentScript?.previousElementSibling?.closest("[data-jetpack-lead]");
49
+ const statusEl = form?.querySelector("[data-status]");
50
+ if (!(form instanceof HTMLFormElement) || !(statusEl instanceof HTMLElement)) {
51
+ /* not on this page */
52
+ } else {
53
+ form.addEventListener("submit", async (event) => {
54
+ event.preventDefault();
55
+ statusEl.textContent = "";
56
+ const button = form.querySelector('button[type="submit"]');
57
+ if (button) button.disabled = true;
58
+ const data = new FormData(form);
59
+ const payload = {
60
+ email: String(data.get("email") ?? ""),
61
+ name: String(data.get("name") ?? "") || undefined,
62
+ source,
63
+ tags: JSON.parse(tags),
64
+ website_url: String(data.get("website_url") ?? ""),
65
+ };
66
+ try {
67
+ const response = await fetch(form.action, {
68
+ method: "POST",
69
+ headers: { "Content-Type": "application/json" },
70
+ body: JSON.stringify(payload),
71
+ credentials: "same-origin",
72
+ });
73
+ const envelope = await response.json();
74
+ const body = envelope?.data;
75
+ if (!response.ok || !envelope?.success || !body?.ok) {
76
+ throw new Error(body?.error ?? "request_failed");
77
+ }
78
+ statusEl.textContent = "Thanks — you're on the list.";
79
+ statusEl.dataset.state = "ok";
80
+ form.reset();
81
+ } catch {
82
+ statusEl.textContent = "Something went wrong. Please try again.";
83
+ statusEl.dataset.state = "error";
84
+ } finally {
85
+ if (button) button.disabled = false;
86
+ }
87
+ });
88
+ }
89
+ </script>
90
+ <style>
91
+ .jetpack-lead-hp {
92
+ position: absolute;
93
+ left: -10000px;
94
+ width: 1px;
95
+ height: 1px;
96
+ overflow: hidden;
97
+ }
98
+ .jetpack-lead-status[data-state="error"] {
99
+ color: #b42318;
100
+ }
101
+ .jetpack-lead-status[data-state="ok"] {
102
+ color: #027a48;
103
+ }
104
+ </style>
@@ -0,0 +1,96 @@
1
+ ---
2
+ import { JETPACK_NEWSLETTER_PLUGIN_ID, jetpackPluginBasePath } from "../plugin-paths.ts";
3
+
4
+ interface Props {
5
+ pluginBasePath?: string;
6
+ listId?: string;
7
+ submitLabel?: string;
8
+ class?: string;
9
+ }
10
+
11
+ const {
12
+ pluginBasePath = jetpackPluginBasePath(JETPACK_NEWSLETTER_PLUGIN_ID),
13
+ listId = "default",
14
+ submitLabel = "Subscribe",
15
+ class: className = "",
16
+ } = Astro.props;
17
+ ---
18
+
19
+ <form class:list={["jetpack-newsletter-form", className]} action={`${pluginBasePath}/subscribe`} method="post" aria-label="Newsletter signup" data-jetpack-newsletter>
20
+ <label>
21
+ <span>Email</span>
22
+ <input type="email" name="email" required autocomplete="email" />
23
+ </label>
24
+ <div class="jetpack-newsletter-hp" aria-hidden="true">
25
+ <label>
26
+ <span>Website</span>
27
+ <input type="text" name="website_url" tabindex="-1" autocomplete="off" />
28
+ </label>
29
+ </div>
30
+ <button type="submit">{submitLabel}</button>
31
+ <p class="jetpack-newsletter-status" data-status role="status"></p>
32
+ </form>
33
+
34
+ <script
35
+ define:vars={{
36
+ listId,
37
+ }}
38
+ >
39
+ const form = document.currentScript?.previousElementSibling?.closest("[data-jetpack-newsletter]");
40
+ const statusEl = form?.querySelector("[data-status]");
41
+ if (!(form instanceof HTMLFormElement) || !(statusEl instanceof HTMLElement)) {
42
+ /* not on this page */
43
+ } else {
44
+ form.addEventListener("submit", async (event) => {
45
+ event.preventDefault();
46
+ statusEl.textContent = "";
47
+ const button = form.querySelector('button[type="submit"]');
48
+ if (button) button.disabled = true;
49
+ const data = new FormData(form);
50
+ const payload = {
51
+ email: String(data.get("email") ?? ""),
52
+ listId,
53
+ website_url: String(data.get("website_url") ?? ""),
54
+ };
55
+ try {
56
+ const response = await fetch(form.action, {
57
+ method: "POST",
58
+ headers: { "Content-Type": "application/json" },
59
+ body: JSON.stringify(payload),
60
+ credentials: "same-origin",
61
+ });
62
+ const envelope = await response.json();
63
+ const body = envelope?.data;
64
+ if (!response.ok || !envelope?.success || !body?.ok) {
65
+ throw new Error(body?.error ?? "request_failed");
66
+ }
67
+ statusEl.textContent =
68
+ body.status === "confirmed"
69
+ ? "You're already subscribed."
70
+ : "Check your email to confirm your subscription.";
71
+ statusEl.dataset.state = "ok";
72
+ form.reset();
73
+ } catch {
74
+ statusEl.textContent = "Something went wrong. Please try again.";
75
+ statusEl.dataset.state = "error";
76
+ } finally {
77
+ if (button) button.disabled = false;
78
+ }
79
+ });
80
+ }
81
+ </script>
82
+ <style>
83
+ .jetpack-newsletter-hp {
84
+ position: absolute;
85
+ left: -10000px;
86
+ width: 1px;
87
+ height: 1px;
88
+ overflow: hidden;
89
+ }
90
+ .jetpack-newsletter-status[data-state="error"] {
91
+ color: #b42318;
92
+ }
93
+ .jetpack-newsletter-status[data-state="ok"] {
94
+ color: #027a48;
95
+ }
96
+ </style>
@@ -0,0 +1,63 @@
1
+ ---
2
+ import { checkMemberAccess, SESSION_COOKIE } from "../membership-session.js";
3
+
4
+ interface Props {
5
+ /** Shown when the visitor has no active membership session. */
6
+ fallbackTitle?: string;
7
+ fallbackMessage?: string;
8
+ /** Link to DashCommerce checkout or account (site-specific). */
9
+ subscribeHref?: string;
10
+ class?: string;
11
+ }
12
+
13
+ const {
14
+ fallbackTitle = "Members only",
15
+ fallbackMessage = "Subscribe through DashCommerce, then open the link in your subscription email to unlock this content.",
16
+ subscribeHref = "/",
17
+ class: className = "",
18
+ } = Astro.props;
19
+
20
+ const sessionToken = Astro.cookies.get(SESSION_COOKIE)?.value ?? null;
21
+ const hasAccess = await checkMemberAccess(Astro.url.origin, sessionToken);
22
+ ---
23
+
24
+ {
25
+ hasAccess ? (
26
+ <div class:list={["jetpack-paywall-gate", className]}>
27
+ <slot />
28
+ </div>
29
+ ) : (
30
+ <section class:list={["jetpack-paywall-fallback", "band", className]} aria-labelledby="jetpack-paywall-title">
31
+ <div class="frame">
32
+ <h2 id="jetpack-paywall-title">{fallbackTitle}</h2>
33
+ <p>{fallbackMessage}</p>
34
+ <p class="jetpack-paywall-fallback__hint">
35
+ After subscribing, use the portal link in your receipt email; it redirects through
36
+ <code>/jetpack/membership</code> to set your member cookie.
37
+ </p>
38
+ {subscribeHref ? (
39
+ <p>
40
+ <a class="arrow-link" href={subscribeHref}>View subscription options</a>
41
+ </p>
42
+ ) : null}
43
+ </div>
44
+ </section>
45
+ )
46
+ }
47
+
48
+ <style>
49
+ .jetpack-paywall-fallback {
50
+ padding-block: var(--space-xl);
51
+ }
52
+ .jetpack-paywall-fallback h2 {
53
+ margin-block-end: var(--space-sm);
54
+ }
55
+ .jetpack-paywall-fallback__hint {
56
+ margin-block: var(--space-md);
57
+ font-size: var(--text-sm);
58
+ color: var(--color-muted);
59
+ }
60
+ .jetpack-paywall-fallback code {
61
+ font-size: 0.9em;
62
+ }
63
+ </style>
@@ -0,0 +1,89 @@
1
+ ---
2
+ import {
3
+ fetchJetpackRelatedPosts,
4
+ type JetpackRelatedItem,
5
+ } from "../related-posts.js";
6
+
7
+ interface Props {
8
+ contentId: string;
9
+ items?: JetpackRelatedItem[];
10
+ collection?: string;
11
+ heading?: string;
12
+ headingId?: string;
13
+ allPostsHref?: string;
14
+ class?: string;
15
+ }
16
+
17
+ const {
18
+ contentId,
19
+ items: itemsProp,
20
+ collection = "posts",
21
+ heading = "Continue reading",
22
+ headingId = "continue-reading",
23
+ allPostsHref = "/posts",
24
+ class: className = "",
25
+ } = Astro.props;
26
+
27
+ const items =
28
+ itemsProp ??
29
+ (await fetchJetpackRelatedPosts(Astro.url.origin, contentId, collection));
30
+ ---
31
+
32
+ {
33
+ items.length > 0 && (
34
+ <section class:list={["band", "section", "jetpack-related", className]} aria-labelledby={headingId}>
35
+ <div class="frame related">
36
+ <div class="section-head">
37
+ <h2 id={headingId} class="section-head__title">
38
+ {heading}
39
+ </h2>
40
+ <a href={allPostsHref} class="arrow-link">
41
+ All posts
42
+ <svg
43
+ viewBox="0 0 24 24"
44
+ fill="none"
45
+ stroke="currentColor"
46
+ stroke-width="1.75"
47
+ stroke-linecap="round"
48
+ stroke-linejoin="round"
49
+ aria-hidden="true"
50
+ >
51
+ <path d="M5 12h14" />
52
+ <path d="m12 5 7 7-7 7" />
53
+ </svg>
54
+ </a>
55
+ </div>
56
+ <div class="post-grid">
57
+ {items.map((item) => (
58
+ <article class="jetpack-related__card">
59
+ <h3 class="jetpack-related__title">
60
+ <a href={item.url}>{item.title}</a>
61
+ </h3>
62
+ </article>
63
+ ))}
64
+ </div>
65
+ </div>
66
+ </section>
67
+ )
68
+ }
69
+
70
+ <style>
71
+ .jetpack-related__card {
72
+ padding: var(--space-md);
73
+ border: 1px solid var(--color-border);
74
+ border-radius: var(--radius-md);
75
+ background: var(--color-surface);
76
+ }
77
+ .jetpack-related__title {
78
+ margin: 0;
79
+ font-size: var(--text-md);
80
+ line-height: var(--leading-snug);
81
+ }
82
+ .jetpack-related__title a {
83
+ color: inherit;
84
+ text-decoration: none;
85
+ }
86
+ .jetpack-related__title a:hover {
87
+ text-decoration: underline;
88
+ }
89
+ </style>
package/src/index.ts ADDED
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Site companion for EmDash Jetpack plugins.
3
+ * Add Astro components under `src/components/` and import them from your theme.
4
+ */
5
+ export * from "./plugin-paths.js";
6
+
7
+ /** Default DashCommerce plugin id when verifying subscription tokens. */
8
+ export const DASHCOMMERCE_PLUGIN_ID = "dashcommerce";
9
+
10
+ export { fetchJetpackRelatedPosts, type JetpackRelatedItem } from "./related-posts.js";
11
+ export { checkMemberAccess, SESSION_COOKIE } from "./membership-session.js";
@@ -0,0 +1,17 @@
1
+ import type { AstroIntegration } from "astro";
2
+
3
+ /** Injects DashCommerce subscription token exchange (sets the member session cookie). */
4
+ export default function jetpackMembershipPages(): AstroIntegration {
5
+ return {
6
+ name: "emdashjetpack-membership",
7
+ hooks: {
8
+ "astro:config:setup": ({ injectRoute }) => {
9
+ injectRoute({
10
+ pattern: "/jetpack/membership",
11
+ entrypoint: new URL("./pages/MembershipExchange.astro", import.meta.url),
12
+ prerender: false,
13
+ });
14
+ },
15
+ },
16
+ };
17
+ }
@@ -0,0 +1,16 @@
1
+ import type { AstroIntegration } from "astro";
2
+
3
+ export default function jetpackNewsletterPages(): AstroIntegration {
4
+ return {
5
+ name: "emdashjetpack-newsletter",
6
+ hooks: {
7
+ "astro:config:setup": ({ injectRoute }) => {
8
+ injectRoute({
9
+ pattern: "/jetpack/newsletter",
10
+ entrypoint: new URL("./pages/NewsletterAction.astro", import.meta.url),
11
+ prerender: false,
12
+ });
13
+ },
14
+ },
15
+ };
16
+ }
@@ -0,0 +1,29 @@
1
+ import { JETPACK_MEMBERSHIPS_PLUGIN_ID, jetpackPluginBasePath } from "./plugin-paths.js";
2
+
3
+ const SESSION_COOKIE = "jetpack_member";
4
+
5
+ export { SESSION_COOKIE };
6
+
7
+ export async function checkMemberAccess(
8
+ siteOrigin: string,
9
+ sessionToken?: string | null,
10
+ ): Promise<boolean> {
11
+ if (!sessionToken) return false;
12
+ const url = new URL(
13
+ `${jetpackPluginBasePath(JETPACK_MEMBERSHIPS_PLUGIN_ID)}/session-check`,
14
+ siteOrigin,
15
+ );
16
+ url.searchParams.set("sessionToken", sessionToken);
17
+ try {
18
+ const response = await fetch(url, {
19
+ redirect: "manual",
20
+ signal: AbortSignal.timeout(10_000),
21
+ headers: { Accept: "application/json" },
22
+ });
23
+ if (!response.ok) return false;
24
+ const body = (await response.json()) as { success?: boolean; data?: { active?: boolean } };
25
+ return Boolean(body.success && body.data?.active);
26
+ } catch {
27
+ return false;
28
+ }
29
+ }
@@ -0,0 +1,62 @@
1
+ ---
2
+ import { JETPACK_MEMBERSHIPS_PLUGIN_ID, jetpackPluginBasePath } from "../plugin-paths.js";
3
+ import { SESSION_COOKIE } from "../membership-session.js";
4
+
5
+ export const prerender = false;
6
+
7
+ const token = Astro.url.searchParams.get("token")?.trim();
8
+ const redirectTarget = Astro.url.searchParams.get("redirect") ?? "/";
9
+
10
+ const target = new URL("/", Astro.url);
11
+ let redirect = target.pathname;
12
+ try {
13
+ const requested = new URL(redirectTarget, target);
14
+ if (requested.origin === target.origin && !requested.pathname.startsWith("//")) {
15
+ redirect = requested.pathname + requested.search + requested.hash;
16
+ }
17
+ } catch {
18
+ // Use the home page for invalid URLs.
19
+ }
20
+ const responseHeaders = { Location: redirect, "Cache-Control": "private, no-store" };
21
+
22
+ if (!token) return new Response(null, { status: 303, headers: responseHeaders });
23
+
24
+ const sessionUrl = new URL(
25
+ `${jetpackPluginBasePath(JETPACK_MEMBERSHIPS_PLUGIN_ID)}/session`,
26
+ Astro.url,
27
+ );
28
+ try {
29
+ const response = await fetch(sessionUrl, {
30
+ method: "POST",
31
+ redirect: "manual",
32
+ signal: AbortSignal.timeout(10_000),
33
+ headers: {
34
+ Accept: "application/json",
35
+ "Content-Type": "application/json",
36
+ Origin: Astro.url.origin,
37
+ },
38
+ body: JSON.stringify({ token }),
39
+ });
40
+ if (response.ok) {
41
+ const body = (await response.json()) as {
42
+ success?: boolean;
43
+ data?: { ok?: boolean; sessionToken?: string; expiresAt?: string };
44
+ };
45
+ const expiry = Date.parse(body.data?.expiresAt ?? "");
46
+ const maxAge = Math.floor((expiry - Date.now()) / 1000);
47
+ if (body.success && body.data?.ok && body.data.sessionToken && maxAge > 0) {
48
+ Astro.cookies.set(SESSION_COOKIE, body.data.sessionToken, {
49
+ path: "/",
50
+ httpOnly: true,
51
+ secure: Astro.url.protocol === "https:",
52
+ sameSite: "lax",
53
+ maxAge,
54
+ });
55
+ }
56
+ }
57
+ } catch {
58
+ // A failed exchange leaves access unchanged. The destination renders the access prompt.
59
+ }
60
+
61
+ return new Response(null, { status: 303, headers: responseHeaders });
62
+ ---
@@ -0,0 +1,38 @@
1
+ ---
2
+ import { JETPACK_NEWSLETTER_PLUGIN_ID, jetpackPluginBasePath } from "../plugin-paths.ts";
3
+
4
+ Astro.response.headers.set("Cache-Control", "private, no-store");
5
+ // Chromium omits Origin on native form navigations with no-referrer.
6
+ Astro.response.headers.set("Referrer-Policy", "strict-origin");
7
+
8
+ const token = Astro.url.searchParams.get("token");
9
+ const action = Astro.url.searchParams.get("action");
10
+ const result = Astro.url.searchParams.get("result");
11
+ const actionLabel = action === "unsubscribe" ? "Unsubscribe" : "Confirm subscription";
12
+ const valid = token && /^[a-f0-9]{48}$/.test(token) && (action === "confirm" || action === "unsubscribe");
13
+ const message = result === "confirmed" ? "Your subscription is confirmed."
14
+ : result === "unsubscribed" ? "You have been unsubscribed."
15
+ : "This link is invalid or has expired.";
16
+ ---
17
+
18
+ <!doctype html>
19
+ <html lang="en">
20
+ <head>
21
+ <meta charset="utf-8" />
22
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
23
+ <meta name="robots" content="noindex" />
24
+ <title>Newsletter subscription</title>
25
+ </head>
26
+ <body>
27
+ <main>
28
+ <h1>Newsletter subscription</h1>
29
+ {valid ? (
30
+ <form method="post" action={`${jetpackPluginBasePath(JETPACK_NEWSLETTER_PLUGIN_ID)}/subscription-action`}>
31
+ <input type="hidden" name="action" value={action} />
32
+ <input type="hidden" name="token" value={token} />
33
+ <button type="submit">{actionLabel}</button>
34
+ </form>
35
+ ) : <p>{message}</p>}
36
+ </main>
37
+ </body>
38
+ </html>
@@ -0,0 +1,42 @@
1
+ export const JETPACK_PLUGIN_ID = "emdashjetpack";
2
+ export const JETPACK_CRM_PLUGIN_ID = "emdashjetpack-crm";
3
+ export const JETPACK_LINK_MONITOR_PLUGIN_ID = "emdashjetpack-link-monitor";
4
+ export const JETPACK_LINK_MONITOR_SCOPED_PLUGIN_ID = "emdashjetpack-link-monitor-scoped";
5
+ export const JETPACK_NEWSLETTER_PLUGIN_ID = "emdashjetpack-newsletter";
6
+ export const JETPACK_MEMBERSHIPS_PLUGIN_ID = "emdashjetpack-memberships";
7
+ export const JETPACK_AI_PLUGIN_ID = "emdashjetpack-ai";
8
+ export const JETPACK_SOCIAL_PLUGIN_ID = "emdashjetpack-social";
9
+
10
+ declare global {
11
+ interface ImportMetaEnv {
12
+ readonly PUBLIC_JETPACK_CORE_PLUGIN_ID?: string;
13
+ readonly PUBLIC_JETPACK_CRM_PLUGIN_ID?: string;
14
+ readonly PUBLIC_JETPACK_NEWSLETTER_PLUGIN_ID?: string;
15
+ readonly PUBLIC_JETPACK_MEMBERSHIPS_PLUGIN_ID?: string;
16
+ }
17
+
18
+ interface ImportMeta {
19
+ readonly env: ImportMetaEnv;
20
+ }
21
+ }
22
+
23
+ const runtimeIds: Readonly<Record<string, string | undefined>> = {
24
+ [JETPACK_PLUGIN_ID]: import.meta.env?.PUBLIC_JETPACK_CORE_PLUGIN_ID,
25
+ [JETPACK_CRM_PLUGIN_ID]: import.meta.env?.PUBLIC_JETPACK_CRM_PLUGIN_ID,
26
+ [JETPACK_NEWSLETTER_PLUGIN_ID]: import.meta.env?.PUBLIC_JETPACK_NEWSLETTER_PLUGIN_ID,
27
+ [JETPACK_MEMBERSHIPS_PLUGIN_ID]: import.meta.env?.PUBLIC_JETPACK_MEMBERSHIPS_PLUGIN_ID,
28
+ };
29
+
30
+ /** Public HTTP prefix for an exact EmDash runtime plugin ID. */
31
+ export function pluginPublicBasePath(pluginId: string): string {
32
+ return `/_emdash/api/plugins/${pluginId}`;
33
+ }
34
+
35
+ /** Use the configured runtime ID for a registry install, or the slug for a config install. */
36
+ export function jetpackPluginBasePath(slug: string): string {
37
+ const id = runtimeIds[slug] || slug;
38
+ if (!/^[a-z][a-z0-9_-]*$/.test(id)) {
39
+ throw new Error(`Invalid EmDash runtime plugin ID configured for ${slug}`);
40
+ }
41
+ return pluginPublicBasePath(id);
42
+ }
@@ -0,0 +1,38 @@
1
+ import { JETPACK_PLUGIN_ID, jetpackPluginBasePath } from "./plugin-paths.js";
2
+
3
+ export interface JetpackRelatedItem {
4
+ id: string;
5
+ slug: string;
6
+ title: string;
7
+ score: number;
8
+ url: string;
9
+ }
10
+
11
+ /** Server-side fetch of Core related-posts route (taxonomy-ranked). */
12
+ export async function fetchJetpackRelatedPosts(
13
+ siteOrigin: string,
14
+ contentId: string,
15
+ collection = "posts",
16
+ ): Promise<JetpackRelatedItem[]> {
17
+ try {
18
+ const endpoint = new URL(`${jetpackPluginBasePath(JETPACK_PLUGIN_ID)}/related`, siteOrigin);
19
+ endpoint.searchParams.set("collection", collection);
20
+ endpoint.searchParams.set("id", contentId);
21
+ const response = await fetch(endpoint, {
22
+ headers: { Accept: "application/json" },
23
+ });
24
+ if (!response.ok) return [];
25
+ const payload = (await response.json()) as { success?: boolean; data?: { items?: unknown } };
26
+ const items = payload?.data?.items;
27
+ if (payload?.success !== true || !Array.isArray(items)) return [];
28
+ return items.filter(
29
+ (item): item is JetpackRelatedItem =>
30
+ typeof item === "object" &&
31
+ item !== null &&
32
+ typeof (item as JetpackRelatedItem).url === "string" &&
33
+ typeof (item as JetpackRelatedItem).title === "string",
34
+ );
35
+ } catch {
36
+ return [];
37
+ }
38
+ }