@octarq/plugin-links 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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 jungley
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/api.ts ADDED
@@ -0,0 +1,223 @@
1
+ // Links feature API surface — the slice of the JSON API owned by the links
2
+ // plugin. Fully self-contained without relative host leaks.
3
+ import type { StatKV } from "@octarq/plugin-sdk";
4
+
5
+ export class ApiError extends Error {
6
+ status: number;
7
+ body?: any;
8
+ requestId?: string;
9
+ constructor(status: number, message: string, body?: any, requestId?: string) {
10
+ super(message);
11
+ this.status = status;
12
+ this.body = body;
13
+ this.requestId = requestId;
14
+ }
15
+ }
16
+
17
+ export function getAppLang(): string {
18
+ try {
19
+ const saved = localStorage.getItem("lang");
20
+ if (saved) return saved;
21
+ } catch {
22
+ /* ignore */
23
+ }
24
+ return typeof navigator !== "undefined" ? navigator.language || "en" : "en";
25
+ }
26
+
27
+ interface ErrorEnvelope {
28
+ message?: string;
29
+ error?: string;
30
+ detail?: string;
31
+ details?: Array<string | { location?: string; message?: string }>;
32
+ }
33
+
34
+ export async function req<T>(method: string, path: string, body?: unknown, lang?: string): Promise<T> {
35
+ const currentLang = lang || getAppLang();
36
+ const headers: Record<string, string> = {
37
+ "Accept-Language": currentLang,
38
+ };
39
+ if (body) {
40
+ headers["Content-Type"] = "application/json";
41
+ }
42
+ const res = await fetch(path, {
43
+ method,
44
+ headers,
45
+ body: body ? JSON.stringify(body) : undefined,
46
+ });
47
+ if (!res.ok) {
48
+ let msg = res.statusText;
49
+ let parsed: ErrorEnvelope | null = null;
50
+ try {
51
+ parsed = (await res.json()) as ErrorEnvelope;
52
+ if (parsed?.message) {
53
+ msg = parsed.message;
54
+ if (parsed.details && Array.isArray(parsed.details) && parsed.details.length > 0) {
55
+ const detailMsgs = parsed.details
56
+ .map((d) => {
57
+ if (typeof d === "string") return d;
58
+ if (d?.message) {
59
+ const loc = d.location ? `${d.location.replace(/^body\./, "")}: ` : "";
60
+ return `${loc}${d.message}`;
61
+ }
62
+ return "";
63
+ })
64
+ .filter(Boolean)
65
+ .join("; ");
66
+ if (detailMsgs) msg = `${msg} (${detailMsgs})`;
67
+ }
68
+ } else if (parsed?.error) {
69
+ msg = parsed.error;
70
+ } else if (parsed?.detail) {
71
+ msg = parsed.detail;
72
+ }
73
+ } catch {
74
+ // Non-JSON error body: fall through to statusText.
75
+ }
76
+ const requestId = res.headers.get("x-request-id") || undefined;
77
+ throw new ApiError(res.status, msg || `HTTP ${res.status}`, parsed, requestId);
78
+ }
79
+ if (res.status === 204) return undefined as unknown as T;
80
+ const contentType = res.headers.get("content-type");
81
+ if (contentType && contentType.includes("application/json")) {
82
+ return (await res.json()) as T;
83
+ }
84
+ return (await res.text()) as unknown as T;
85
+ }
86
+
87
+ export type { StatKV };
88
+
89
+ export interface HostEntry {
90
+ host: string;
91
+ enabled: boolean;
92
+ }
93
+
94
+ export interface Domain {
95
+ id: number;
96
+ name: string;
97
+ providerAccountId?: number;
98
+ zoneId?: string;
99
+ note?: string;
100
+ forMail?: boolean;
101
+ forLink?: boolean;
102
+ linkHosts?: HostEntry[] | null;
103
+ mailHosts?: HostEntry[] | null;
104
+ createdAt?: string;
105
+ [key: string]: any;
106
+ }
107
+
108
+ export function effectiveLinkHosts(d: Domain | { hosts?: string[]; linkHosts?: HostEntry[]; name?: string }): string[] {
109
+ if ("linkHosts" in d && Array.isArray(d.linkHosts)) {
110
+ return d.linkHosts.filter((h) => h.enabled).map((h) => h.host);
111
+ }
112
+ if ("hosts" in d && Array.isArray(d.hosts)) {
113
+ return d.hosts;
114
+ }
115
+ return [];
116
+ }
117
+
118
+ export interface Overview extends Record<string, unknown> {
119
+ tokens?: number;
120
+ includeBot?: boolean;
121
+ links?: number;
122
+ activeLinks?: number;
123
+ domains?: number;
124
+ linkDomains?: number;
125
+ mailDomains?: number;
126
+ mailboxes?: number;
127
+ emails?: number;
128
+ unread?: number;
129
+ totalClicks?: number;
130
+ clicks7d?: number;
131
+ clicks30d?: number;
132
+ botClicks7d?: number;
133
+ botClicks30d?: number;
134
+ series?: StatKV[] | null;
135
+ topLinks?: { id: number; slug: string; host: string; title: string; tags: string; clicks: number }[] | null;
136
+ devices?: StatKV[] | null;
137
+ countries?: StatKV[] | null;
138
+ cities?: StatKV[] | null;
139
+ recentEmails?: { id: number; from: string; subject: string; read: boolean; receivedAt: string }[] | null;
140
+ }
141
+
142
+ export interface Link {
143
+ id: number;
144
+ host: string;
145
+ slug: string;
146
+ target: string;
147
+ note: string;
148
+ title: string;
149
+ tags: string;
150
+ expiresAt: string | null;
151
+ expiredUrl: string;
152
+ clickLimit: number;
153
+ archived: boolean;
154
+ enabled: boolean;
155
+ clicks: number;
156
+ password?: string;
157
+ hasPassword: boolean;
158
+ routingRules?: any[];
159
+ createdAt: string;
160
+ }
161
+
162
+ export interface LinkStats {
163
+ total: number;
164
+ windowed: number;
165
+ days: number;
166
+ metric?: "pv" | "uv";
167
+ series: StatKV[];
168
+ referers: StatKV[] | null;
169
+ channels: StatKV[] | null;
170
+ countries: StatKV[] | null;
171
+ regions: StatKV[] | null;
172
+ devices: StatKV[] | null;
173
+ browsers: StatKV[] | null;
174
+ utmSources: StatKV[] | null;
175
+ utmMediums: StatKV[] | null;
176
+ utmCampaigns: StatKV[] | null;
177
+ variants: StatKV[] | null;
178
+ }
179
+
180
+ export interface LinksCapabilities {
181
+ geoReady: boolean;
182
+ mode: "configured" | "unavailable";
183
+ }
184
+
185
+ export const linksApi = {
186
+ links: (params: { q?: string; tag?: string; host?: string; archived?: boolean; limit?: number; offset?: number } = {}) => {
187
+ const sp = new URLSearchParams();
188
+ if (params.q) sp.set("q", params.q);
189
+ if (params.tag) sp.set("tag", params.tag);
190
+ if (params.host) sp.set("host", params.host);
191
+ if (params.archived) sp.set("archived", "1");
192
+ if (params.limit) sp.set("limit", params.limit.toString());
193
+ if (params.offset) sp.set("offset", params.offset.toString());
194
+ const qs = sp.toString();
195
+ return req<Link[]>("GET", `/api/links${qs ? `?${qs}` : ""}`);
196
+ },
197
+ createLink: (l: Partial<Link> & { password?: string }) => req<Link>("POST", "/api/links", l),
198
+ updateLink: (id: number, l: Partial<Link> & { password?: string }) =>
199
+ req<Link>("PUT", `/api/links/${id}`, l),
200
+ deleteLink: (id: number) => req("DELETE", `/api/links/${id}`),
201
+ linkStats: (id: number, days = 30, metric: "pv" | "uv" = "uv") =>
202
+ req<LinkStats>("GET", `/api/links/${id}/stats?days=${days}&metric=${metric}`),
203
+ linkMetadata: (url: string) =>
204
+ req<{ title: string; description: string; favicon: string }>(
205
+ "GET",
206
+ `/api/links/metadata?url=${encodeURIComponent(url)}`,
207
+ ),
208
+ capabilities: () => req<LinksCapabilities>("GET", "/api/links/capabilities"),
209
+ domains: (q?: { q?: string; limit?: number; offset?: number }) => {
210
+ const sp = new URLSearchParams();
211
+ if (q?.q) sp.set("q", q.q);
212
+ if (q?.limit) sp.set("limit", String(q.limit));
213
+ if (q?.offset) sp.set("offset", String(q.offset));
214
+ const qs = sp.toString();
215
+ return req<Domain[]>("GET", `/api/domains${qs ? `?${qs}` : ""}`);
216
+ },
217
+ overview: (includeBot = false) => req<Overview>("GET", `/api/overview?include_bot=${includeBot}`),
218
+ aiAssistStatus: () => req<{ configured: boolean; provider: string }>("GET", "/api/ai/assist/status"),
219
+ aiSuggestSlug: (target: string, title?: string) =>
220
+ req<{ slugs: string[] }>("POST", "/api/ai/assist/suggest-slug", { target, title }),
221
+ };
222
+
223
+ export { linksApi as api };
@@ -0,0 +1,18 @@
1
+ import { useTranslation } from "@octarq/plugin-sdk";
2
+
3
+ export function BotToggle({ value, onChange }: { value: boolean; onChange: (v: boolean) => void }) {
4
+ const { t } = useTranslation();
5
+ return (
6
+ <button
7
+ onClick={() => onChange(!value)}
8
+ title={value ? t("links.hideBotTraffic") : t("links.showBotTraffic")}
9
+ className={`flex items-center gap-1.5 rounded-full px-2.5 py-1 text-xs font-medium transition ${
10
+ value
11
+ ? "bg-warning-bg text-warning-fg border border-warning-border hover:brightness-95"
12
+ : "bg-surface-hover text-muted-foreground hover:bg-surface-hover"
13
+ }`}
14
+ >
15
+ <span>{value ? t("links.botsOn") : t("links.botsOff")}</span>
16
+ </button>
17
+ );
18
+ }
@@ -0,0 +1,68 @@
1
+ import { describe, it, expect } from "vitest";
2
+ import { parseLinksFilter, buildLinksFilterQuery } from "./filters";
3
+
4
+ describe("Links url-backed filters pure functions", () => {
5
+ it("1. parses query params correctly and defaults empty query to defaults", () => {
6
+ // Non-empty query
7
+ const parsed = parseLinksFilter("?q=promo&archived=1");
8
+ expect(parsed).toEqual({ q: "promo", archived: true });
9
+
10
+ // Empty query
11
+ const defaultParsed = parseLinksFilter("");
12
+ expect(defaultParsed).toEqual({ q: "", archived: false });
13
+
14
+ // Query with only search term
15
+ const searchOnly = parseLinksFilter("?q=hello");
16
+ expect(searchOnly).toEqual({ q: "hello", archived: false });
17
+
18
+ // Query with archived=0
19
+ const archivedZero = parseLinksFilter("?archived=0");
20
+ expect(archivedZero).toEqual({ q: "", archived: false });
21
+ });
22
+
23
+ it("2. serializes filter values to query without including default values", () => {
24
+ // Default values: q is empty, archived is false -> query should be empty
25
+ const queryDefault = buildLinksFilterQuery({ q: "", archived: false });
26
+ expect(queryDefault.toString()).toBe("");
27
+
28
+ // Only search term
29
+ const querySearch = buildLinksFilterQuery({ q: "promo", archived: false });
30
+ expect(querySearch.toString()).toBe("q=promo");
31
+
32
+ // Only archived
33
+ const queryArchived = buildLinksFilterQuery({ q: "", archived: true });
34
+ expect(queryArchived.toString()).toBe("archived=1");
35
+
36
+ // Both
37
+ const queryBoth = buildLinksFilterQuery({ q: "promo", archived: true });
38
+ expect(queryBoth.toString()).toBe("q=promo&archived=1");
39
+ });
40
+
41
+ it("3. satisfies roundtrip consistency (parse -> serialize -> parse)", () => {
42
+ const originalFilters = { q: "promo", archived: true };
43
+ const serialized = buildLinksFilterQuery(originalFilters);
44
+ const reParsed = parseLinksFilter(serialized);
45
+ expect(reParsed).toEqual(originalFilters);
46
+
47
+ const defaultFilters = { q: "", archived: false };
48
+ const serializedDefault = buildLinksFilterQuery(defaultFilters);
49
+ const reParsedDefault = parseLinksFilter(serializedDefault);
50
+ expect(reParsedDefault).toEqual(defaultFilters);
51
+ });
52
+
53
+ it("4. preserves existing query parameters such as create=1", () => {
54
+ const existing = new URLSearchParams("create=1&foo=bar");
55
+ const updated = buildLinksFilterQuery({ q: "promo", archived: true }, existing);
56
+ expect(updated.get("create")).toBe("1");
57
+ expect(updated.get("foo")).toBe("bar");
58
+ expect(updated.get("q")).toBe("promo");
59
+ expect(updated.get("archived")).toBe("1");
60
+
61
+ // Deleting filters should keep create=1
62
+ const cleaned = buildLinksFilterQuery({ q: "", archived: false }, updated);
63
+ expect(cleaned.get("create")).toBe("1");
64
+ expect(cleaned.get("foo")).toBe("bar");
65
+ expect(cleaned.get("q")).toBeNull();
66
+ expect(cleaned.get("archived")).toBeNull();
67
+ });
68
+ });
package/filters.ts ADDED
@@ -0,0 +1,29 @@
1
+ export interface LinksFilterState {
2
+ q: string;
3
+ archived: boolean;
4
+ }
5
+
6
+ export function parseLinksFilter(searchParams: URLSearchParams | string): LinksFilterState {
7
+ const params = typeof searchParams === "string" ? new URLSearchParams(searchParams) : searchParams;
8
+ const q = params.get("q") || "";
9
+ const archived = params.get("archived") === "1";
10
+ return { q, archived };
11
+ }
12
+
13
+ export function buildLinksFilterQuery(
14
+ filters: LinksFilterState,
15
+ prevParams?: URLSearchParams
16
+ ): URLSearchParams {
17
+ const next = new URLSearchParams(prevParams);
18
+ if (filters.q) {
19
+ next.set("q", filters.q);
20
+ } else {
21
+ next.delete("q");
22
+ }
23
+ if (filters.archived) {
24
+ next.set("archived", "1");
25
+ } else {
26
+ next.delete("archived");
27
+ }
28
+ return next;
29
+ }