astro-avdeb 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,10 @@
1
+ # Changelog
2
+
3
+ ## 0.1.0 — 2026-11-21
4
+
5
+ - First release: `astro-avdeb` integration with `<AvdebProducts>`, `<AvdebProduct>` and `<AvdebButton>`
6
+ components; grid, carousel, list and spotlight layouts; horizontal, hero and compact single-product
7
+ styles; inherit / light / dark / auto themes; `--avdeb-*` design tokens with zero-specificity defaults,
8
+ `styles: false` and an importable `astro-avdeb/styles.css`; headless `getAvdebProducts()`
9
+ (`astro-avdeb/data`); in-memory cache with one-week stale fallback, request merging and a per-minute
10
+ request budget; secret key / referral code from options or `AVDEB_SECRET_KEY` / `AVDEB_REF_CODE`.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 AVDEB
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,243 @@
1
- # Temporary Holding Version
1
+ # astro-avdeb
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
+ Show [AVDEB](https://avdeb.com/developers/#astro) products on your Astro site (a creator's shop, a category, a search or a single product) with **your referral code on every link**.
4
+
5
+ ![AVDEB products in the spotlight layout, rendered by astro-avdeb](https://raw.githubusercontent.com/Avdebcom/astro-avdeb/main/.github/screenshot.jpg)
6
+
7
+ - **Three components:** `<AvdebProducts>`, `<AvdebProduct>` and `<AvdebButton>`. They work in `.astro` pages, layouts and MDX.
8
+ - **Four layouts:** grid, carousel (scroll-snap with keyboard and arrow buttons), list ("shop the post") and spotlight (first product featured). Single products render as a horizontal card, a hero or a compact card, with your own badge and note.
9
+ - **Fits any theme:** container queries let embeds adapt to the column they sit in. Choose inherit, light, dark or system theme, one of three card styles, plus accent colour, corner radius and image shape.
10
+ - **Easy to restyle:** every rule is `:where()`-wrapped, so your CSS always wins. 25+ `--avdeb-*` design tokens, `class` and `style` on every component, `styles: false` to bring your own CSS, and a headless `getAvdebProducts()` for fully custom markup.
11
+ - **Fast and resilient:** products are fetched at build or render time on the server and cached in memory per query. Identical embeds share one request. If AVDEB can't be reached, the last good copy is served for a week.
12
+ - **Honest links:** referral links get `rel="sponsored"`, and an optional disclosure line appears under embeds that carry a code.
13
+ - **Private by default:** no third-party scripts, cookies, iframes or tracking. The only client JS is ~40 lines for carousel arrows. Your secret key never reaches the browser.
14
+
15
+ Works with Astro 5, 6 and 7, with static output (SSG) and with server output on any adapter.
16
+
17
+ ## Install
18
+
19
+ ```sh
20
+ npx astro add astro-avdeb
21
+ ```
22
+
23
+ Or manually:
24
+
25
+ ```sh
26
+ npm install astro-avdeb
27
+ ```
28
+
29
+ ```js
30
+ // astro.config.mjs
31
+ import { defineConfig } from "astro/config";
32
+ import avdeb from "astro-avdeb";
33
+
34
+ export default defineConfig({
35
+ integrations: [avdeb()],
36
+ });
37
+ ```
38
+
39
+ Then add your key or referral code to `.env` (see [Become an AVDEB affiliate](#become-an-avdeb-affiliate-or-creator)):
40
+
41
+ ```sh
42
+ # Either: secret key from Partner dashboard → Embeds & API (adds your code automatically, up to 48 products per embed)
43
+ AVDEB_SECRET_KEY=avdeb_sk_...
44
+ # Or: just your referral code (up to 12 products per embed)
45
+ AVDEB_REF_CODE=YOURCODE
46
+ ```
47
+
48
+ Without either one, embeds still work, but the links don't earn commission.
49
+
50
+ ## Use
51
+
52
+ ```astro
53
+ ---
54
+ import { AvdebProducts, AvdebProduct, AvdebButton } from "astro-avdeb/components";
55
+ ---
56
+
57
+ <!-- Paste any AVDEB creator, category or product link; the source is detected automatically -->
58
+ <AvdebProducts url="https://avdeb.com/creators/cleo/" heading="From my shop" />
59
+
60
+ <AvdebProducts tag="stickers" layout="carousel" columns={4} limit={10} />
61
+ <AvdebProducts q="keychain" layout="list" limit={3} />
62
+ <AvdebProducts tag="3d-prints" layout="spotlight" theme="dark" accentColor="#e0a84f" />
63
+
64
+ <AvdebProduct handle="cat-sticker" variant="hero" badge="Editor's pick" note="I use it every day." />
65
+
66
+ <AvdebButton href="/creators/cleo/" label="Visit my shop" variant="outline" align="center" />
67
+ ```
68
+
69
+ In MDX, import the components at the top of the file and use them the same way.
70
+
71
+ ### `<AvdebProducts>`
72
+
73
+ | Prop | Type | Default | |
74
+ |---|---|---|---|
75
+ | `url` | string | | Any `avdeb.com/creators/…`, `/category/…` or `/store/…` link |
76
+ | `creator` / `tag` / `type` / `q` | string | | Creator slug, category slug, product type, search phrase. Leave all empty for the newest products |
77
+ | `limit` | number | 6 | Up to 12 without a secret key, 48 with one |
78
+ | `layout` | `grid` \| `carousel` \| `list` \| `spotlight` | `grid` | |
79
+ | `columns` | 1–6 | 3 | Fewer on narrow containers automatically |
80
+ | `heading`, `intro` | string | | Optional header above the products |
81
+ | `headingLevel` | 2–5 | 2 | Card titles use the next level |
82
+ | `viewAll`, `viewAllLabel` | boolean, string | `true`, "View all" | "View all" link for creator and category embeds |
83
+ | `cardStyle` | `elevated` \| `outline` \| `minimal` | `elevated` | |
84
+ | `theme` | `inherit` \| `light` \| `dark` \| `auto` | `inherit` | `inherit` uses your text colour on a transparent background |
85
+ | `accentColor` | hex | AVDEB green | Prices, badges, buttons |
86
+ | `radius` | 0–32 | 16 | Corner radius in px |
87
+ | `imageRatio` | `square` \| `portrait` \| `landscape` | `square` | |
88
+ | `ctaLabel` | string | "View product" | |
89
+ | `hidePrice`, `hideCreator`, `hideBadges` | boolean | | |
90
+ | `newTab` | boolean | `false` | |
91
+ | `class`, `style` | string | | Added to the root `<section>` |
92
+
93
+ ### `<AvdebProduct>`
94
+
95
+ `handle` (a product handle or an `avdeb.com/store/…` link), `variant` (`horizontal` by default, `hero` or `card`), `badge`, `note`, and the same styling props as `<AvdebProducts>`.
96
+
97
+ ### `<AvdebButton>`
98
+
99
+ `href` (an avdeb.com URL or a path such as `/store/cat-sticker/`; other hosts render as plain text), `label`, `variant` (`solid`, `outline` or `link`), `align` (`start`, `center` or `end`), `accentColor`, `newTab`, `class`, `style`.
100
+
101
+ ## Options
102
+
103
+ Every display option sets the site-wide default; component props override it per embed.
104
+
105
+ ```js
106
+ avdeb({
107
+ apiKey: undefined, // default: AVDEB_SECRET_KEY
108
+ refCode: undefined, // default: AVDEB_REF_CODE
109
+ layout: "grid",
110
+ columns: 3,
111
+ cardStyle: "elevated",
112
+ theme: "inherit",
113
+ accentColor: "", // hex, e.g. "#7c3aed"
114
+ radius: 16,
115
+ imageRatio: "square",
116
+ ctaLabel: "View product",
117
+ showPrice: true,
118
+ showCreator: true,
119
+ showBadges: true, // "−25%" sale and "New" badges
120
+ newTab: false,
121
+ showDisclosure: true, // shown only when links carry a referral code
122
+ disclosureText: "As an AVDEB affiliate, I earn a commission from qualifying purchases.",
123
+ locale: undefined, // price format; default: Astro.currentLocale, else "en-US"
124
+ cacheMinutes: 360, // in-memory product cache (SSR); a build fetches each query once
125
+ requestsPerMinute: 120,
126
+ styles: true, // false = ship no CSS
127
+ });
128
+ ```
129
+
130
+ ## Styling
131
+
132
+ The defaults are designed to look native on most themes. When you want your own look, you have five levels of control:
133
+
134
+ **1. Props and options:** `theme`, `cardStyle`, `accentColor`, `radius`, `imageRatio`.
135
+
136
+ **2. Design tokens:** set `--avdeb-*` custom properties on `.avdeb` to restyle every embed, or on a class you pass to one embed. Values in your CSS win over options and props.
137
+
138
+ ```css
139
+ .avdeb {
140
+ --avdeb-accent: #ff4d00;
141
+ --avdeb-radius: 0px;
142
+ --avdeb-gap: 1.5rem;
143
+ --avdeb-font-title: "Fraunces", serif;
144
+ }
145
+ ```
146
+
147
+ | Token | |
148
+ |---|---|
149
+ | `--avdeb-accent`, `--avdeb-accent-contrast`, `--avdeb-accent-text` | Accent, text on accent, accent used as text |
150
+ | `--avdeb-surface` | Section background (light/dark/auto themes) |
151
+ | `--avdeb-card-bg`, `--avdeb-border`, `--avdeb-border-soft` | Cards |
152
+ | `--avdeb-media-bg` | Image placeholder background |
153
+ | `--avdeb-muted` | Secondary text |
154
+ | `--avdeb-badge-bg`, `--avdeb-badge-text` | Badges |
155
+ | `--avdeb-shadow`, `--avdeb-shadow-hover` | Elevated cards |
156
+ | `--avdeb-radius`, `--avdeb-ratio`, `--avdeb-cols`, `--avdeb-gap`, `--avdeb-pad` | Shape and layout |
157
+ | `--avdeb-font-title`, `--avdeb-heading-size`, `--avdeb-title-size`, `--avdeb-title-leading` | Type |
158
+ | `--avdeb-ease` | Motion curve |
159
+ | `--avdeb-btn-bg`, `--avdeb-btn-color` | `<AvdebButton>` |
160
+
161
+ **3. Your own selectors:** all default rules have zero specificity, so plain class selectors override them:
162
+
163
+ ```css
164
+ .brutal .avdeb-card { border-width: 2px; box-shadow: 6px 6px 0 #111; }
165
+ ```
166
+
167
+ ```astro
168
+ <AvdebProducts tag="stickers" class="brutal" cardStyle="outline" />
169
+ ```
170
+
171
+ The markup uses stable BEM classes: `.avdeb`, `.avdeb--{layout}`, `.avdeb--{cardStyle}`, `.avdeb__header`, `.avdeb__heading`, `.avdeb__intro`, `.avdeb__items`, `.avdeb-card`, `.avdeb-card--featured`, `.avdeb-card__media`, `.avdeb-card__title`, `.avdeb-card__by`, `.avdeb-card__price`, `.avdeb-card__cta`, `.avdeb-badge`, `.avdeb__disclosure`, `.avdeb-btn`, `.avdeb-btn--{variant}`. The root has `data-theme` and the Tailwind `not-prose` class.
172
+
173
+ **4. Bring your own CSS:** `avdeb({ styles: false })` ships no stylesheet. To start from the defaults, import them yourself, for example into a cascade layer:
174
+
175
+ ```css
176
+ @import "astro-avdeb/styles.css" layer(avdeb);
177
+ ```
178
+
179
+ **5. Headless:** render products with your own markup:
180
+
181
+ ```astro
182
+ ---
183
+ import { getAvdebProducts } from "astro-avdeb/data";
184
+ const { cards, viewAll, disclosure } = await getAvdebProducts({ tag: "stickers", limit: 4 });
185
+ ---
186
+ <ul>
187
+ {cards.map((c) => (
188
+ <li><a href={c.href} rel={c.rel} target={c.target}><img src={c.image} alt="" /> {c.title} — {c.price}</a></li>
189
+ ))}
190
+ </ul>
191
+ {disclosure && <small>{disclosure}</small>}
192
+ ```
193
+
194
+ Each card has `href` (with your referral code), `rel`, `target`, `title`, `image`, `width`, `height`, `price`, `compareAt`, `discount`, `isNew` and `creator`. Raw API products are in `products`.
195
+
196
+ ## Become an AVDEB affiliate (or creator)
197
+
198
+ You only need an account to earn commission. Program details:
199
+ [avdeb.com/affiliate](https://avdeb.com/affiliate/): 5% commission, 30-day cookie, monthly PayPal payouts in USD
200
+ ($50 minimum), open worldwide, approval usually within 24 hours.
201
+
202
+ 1. Open [avdeb.com/affiliate/apply](https://avdeb.com/affiliate/apply/).
203
+ 2. **Account:** email + password (or *Sign in* if you already have an AVDEB account).
204
+ 3. **Program:** *Affiliate* (share products, earn commission), *Creator* (submit sticker or 3D designs that
205
+ AVDEB prints and ships; you earn on every sale), or both.
206
+ 4. **Personal information & details:** first and last name, country, tax residency, legal name (business name optional).
207
+ 5. **Address:** street, city, state/province, postal code.
208
+ 6. **Payout & promotion:** PayPal email for commissions; optionally your website and social links.
209
+ 7. Accept the Terms & Conditions and Privacy Policy, then click **Create Account & Apply**.
210
+ 8. After approval you get your referral link by email and in the dashboard.
211
+ 9. In the partner dashboard, open **Embeds & API** ([direct link](https://avdeb.com/affiliate/dashboard/developers/)) and
212
+ create a **secret key** (`avdeb_sk_…`), or copy your referral code from **Links**.
213
+ 10. Put it in `.env` as `AVDEB_SECRET_KEY` (or `AVDEB_REF_CODE`) and rebuild. Every product link now carries your code.
214
+
215
+ Creators: once your designs are listed, show them with `<AvdebProducts creator="your-slug" />`.
216
+
217
+ Please disclose affiliate links to your readers. The disclosure line is on by default.
218
+
219
+ ## How it works
220
+
221
+ - Components fetch `https://api.avdeb.com/v1/catalog/products` on the server, at build time for static pages and at request time for on-demand pages. Pages are plain HTML links and images.
222
+ - With a secret key, requests send `Authorization: Bearer avdeb_sk_…` and the API returns links that already carry your code. Without one, `?ref=` is added to every link.
223
+ - Each query is cached in memory, so every page of a build shares one request per query. If a request fails, the last good result (up to a week old) is served, retried after 15 minutes, and logged. At most `requestsPerMinute` calls are made.
224
+ - The secret key is read on the server only. It is never rendered into HTML or sent to client scripts.
225
+ - All product data is validated before rendering: only `https://avdeb.com` links and `https://` images get through.
226
+
227
+ ## Development
228
+
229
+ Requires Node 22.12+.
230
+
231
+ ```sh
232
+ npm install
233
+ npm test # unit tests (node --test)
234
+ npm run typecheck
235
+
236
+ # demo site with every layout
237
+ npm pack --pack-destination demo
238
+ cd demo && npm install astro ./astro-avdeb-*.tgz && npx astro dev
239
+ ```
240
+
241
+ ## License
242
+
243
+ MIT © AVDEB
package/package.json CHANGED
@@ -1,6 +1,67 @@
1
1
  {
2
- "name": "astro-avdeb",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
2
+ "name": "astro-avdeb",
3
+ "version": "0.1.0",
4
+ "description": "Astro components for AVDEB products — grid, carousel, list and spotlight embeds with your affiliate referral link on every product",
5
+ "type": "module",
6
+ "main": "./src/index.ts",
7
+ "types": "./src/index.ts",
8
+ "exports": {
9
+ ".": "./src/index.ts",
10
+ "./components": "./src/components/index.ts",
11
+ "./data": "./src/data.ts",
12
+ "./styles.css": "./src/styles.css",
13
+ "./package.json": "./package.json"
14
+ },
15
+ "files": [
16
+ "src",
17
+ "types/virtual.d.ts",
18
+ "README.md",
19
+ "CHANGELOG.md",
20
+ "LICENSE"
21
+ ],
22
+ "keywords": [
23
+ "withastro",
24
+ "astro-component",
25
+ "astro-integration",
26
+ "astro",
27
+ "ui",
28
+ "css",
29
+ "affiliate",
30
+ "products",
31
+ "product-embed",
32
+ "ecommerce",
33
+ "avdeb"
34
+ ],
35
+ "homepage": "https://avdeb.com/developers/#astro",
36
+ "repository": {
37
+ "type": "git",
38
+ "url": "git+https://github.com/Avdebcom/astro-avdeb.git"
39
+ },
40
+ "bugs": {
41
+ "url": "https://github.com/Avdebcom/astro-avdeb/issues"
42
+ },
43
+ "author": {
44
+ "name": "AVDEB",
45
+ "url": "https://avdeb.com/developers/"
46
+ },
47
+ "license": "MIT",
48
+ "sideEffects": [
49
+ "*.css",
50
+ "*.astro"
51
+ ],
52
+ "engines": {
53
+ "node": ">=22.12.0"
54
+ },
55
+ "peerDependencies": {
56
+ "astro": ">=5.0.0"
57
+ },
58
+ "devDependencies": {
59
+ "@types/node": "^22.18.0",
60
+ "astro": "^7.4.0",
61
+ "typescript": "^5.9.0"
62
+ },
63
+ "scripts": {
64
+ "test": "node --test \"tests/**/*.test.ts\"",
65
+ "typecheck": "tsc --noEmit"
66
+ }
67
+ }
package/src/catalog.ts ADDED
@@ -0,0 +1,292 @@
1
+ /**
2
+ * AVDEB catalog API contract: query sanitising, response validation, link helpers.
3
+ * Pure module — safe to import from routes, Astro components and tests.
4
+ */
5
+
6
+ import {
7
+ API_BASE,
8
+ DEFAULT_LIMIT,
9
+ MAX_LIMIT_ANONYMOUS,
10
+ MAX_LIMIT_SECRET,
11
+ PUBLISHABLE_KEY_PREFIX,
12
+ SECRET_KEY_RE,
13
+ SITE_ORIGIN,
14
+ } from "./constants.ts";
15
+
16
+ export interface CatalogQuery {
17
+ creator?: string;
18
+ tag?: string;
19
+ type?: string;
20
+ handle?: string;
21
+ q?: string;
22
+ limit: number;
23
+ }
24
+
25
+ export interface ProductCreator {
26
+ slug: string;
27
+ name: string;
28
+ url: string | null;
29
+ }
30
+
31
+ export interface Product {
32
+ handle: string;
33
+ title: string;
34
+ url: string;
35
+ image: string | null;
36
+ price: number | null;
37
+ compareAtPrice: number | null;
38
+ currency: string;
39
+ type: string | null;
40
+ tags: string[];
41
+ creator: ProductCreator | null;
42
+ createdAt: string | null;
43
+ }
44
+
45
+ export type Tier = "anonymous" | "publishable" | "secret";
46
+
47
+ export interface ProductsResult {
48
+ products: Product[];
49
+ ref: string;
50
+ tier: Tier;
51
+ }
52
+
53
+ export interface KeyOwner {
54
+ type: string;
55
+ name: string;
56
+ ref: string;
57
+ creatorSlug: string;
58
+ }
59
+
60
+ export type KeyProblem = "publishable" | "malformed";
61
+
62
+ const SLUG_RE = /[^a-z0-9-]+/g;
63
+ const TYPE_RE = /[^\p{L}\p{N} &'-]+/gu;
64
+ // eslint-disable-next-line no-control-regex -- strip control characters from search input
65
+ const CONTROL_RE = /[\u0000-\u001f\u007f]+/g;
66
+ const CURRENCY_RE = /^[A-Z]{3}$/;
67
+
68
+ function isRecord(value: unknown): value is Record<string, unknown> {
69
+ return typeof value === "object" && value !== null && !Array.isArray(value);
70
+ }
71
+
72
+ function str(value: unknown): string {
73
+ return typeof value === "string" ? value : typeof value === "number" ? String(value) : "";
74
+ }
75
+
76
+ /** Referral codes are letters, digits, "-" and "_" (as issued in the AVDEB affiliate dashboard). */
77
+ export function cleanRef(code: unknown): string {
78
+ return str(code).replace(/[^A-Za-z0-9_-]/g, "").slice(0, 40);
79
+ }
80
+
81
+ /** Lower-case URL slug (creator, category, product handle). */
82
+ export function cleanSlug(value: unknown): string {
83
+ return str(value).trim().toLowerCase().replace(SLUG_RE, "-").replace(/^-+|-+$/g, "").slice(0, 100);
84
+ }
85
+
86
+ /** Product type such as "Sticker" or "Phone Case". */
87
+ export function cleanType(value: unknown): string {
88
+ return str(value).replace(TYPE_RE, "").replace(/\s+/g, " ").trim().slice(0, 40);
89
+ }
90
+
91
+ /** Free-text search phrase. */
92
+ export function cleanSearch(value: unknown): string {
93
+ return str(value).replace(CONTROL_RE, " ").replace(/\s+/g, " ").trim().slice(0, 100);
94
+ }
95
+
96
+ /** `null` for a usable secret key, otherwise why it can't be used. Empty input is not a problem. */
97
+ export function keyProblem(key: unknown): KeyProblem | null {
98
+ const k = str(key).trim();
99
+ if (k === "" || SECRET_KEY_RE.test(k)) return null;
100
+ return k.startsWith(PUBLISHABLE_KEY_PREFIX) ? "publishable" : "malformed";
101
+ }
102
+
103
+ /** The key when it is a well-formed secret key, otherwise "". */
104
+ export function usableKey(key: unknown): string {
105
+ const k = str(key).trim();
106
+ return SECRET_KEY_RE.test(k) ? k : "";
107
+ }
108
+
109
+ export function maxLimit(hasKey: boolean): number {
110
+ return hasKey ? MAX_LIMIT_SECRET : MAX_LIMIT_ANONYMOUS;
111
+ }
112
+
113
+ export function isAvdebUrl(url: unknown): url is string {
114
+ if (typeof url !== "string") return false;
115
+ try {
116
+ const u = new URL(url);
117
+ const host = u.hostname.toLowerCase();
118
+ return u.protocol === "https:" && (host === "avdeb.com" || host === "www.avdeb.com");
119
+ } catch {
120
+ return false;
121
+ }
122
+ }
123
+
124
+ /**
125
+ * Absolute avdeb.com URL for an avdeb.com URL or a site path ("/store/cat/"), with `ref` set when
126
+ * given. Anything pointing elsewhere returns "" so callers never link off-site by accident.
127
+ */
128
+ export function avdebLink(input: unknown, ref = ""): string {
129
+ let raw = str(input).trim();
130
+ if (raw === "") return "";
131
+ if (raw.startsWith("/") && !raw.startsWith("//")) raw = SITE_ORIGIN + raw;
132
+ else if (/^(www\.)?avdeb\.com(\/|$)/i.test(raw)) raw = "https://" + raw;
133
+ if (!isAvdebUrl(raw)) return "";
134
+ const u = new URL(raw);
135
+ const code = cleanRef(ref);
136
+ if (code !== "") u.searchParams.set("ref", code);
137
+ return u.toString();
138
+ }
139
+
140
+ export function hasRef(url: string): boolean {
141
+ try {
142
+ return new URL(url).searchParams.has("ref");
143
+ } catch {
144
+ return false;
145
+ }
146
+ }
147
+
148
+ export type LinkTarget = { kind: "creator" | "tag" | "handle"; value: string };
149
+
150
+ /**
151
+ * Recognise an AVDEB page a user pasted: /creators/{slug}/, /category/{slug}/, /store/{handle}/.
152
+ * Accepts full URLs, scheme-less "avdeb.com/…" and bare paths.
153
+ */
154
+ export function parseAvdebLink(input: unknown): LinkTarget | null {
155
+ const raw = str(input).trim();
156
+ if (raw === "") return null;
157
+ let path: string;
158
+ if (raw.startsWith("/") && !raw.startsWith("//")) {
159
+ path = raw;
160
+ } else {
161
+ const withScheme = /^https?:\/\//i.test(raw) ? raw : `https://${raw}`;
162
+ try {
163
+ const u = new URL(withScheme);
164
+ const host = u.hostname.toLowerCase();
165
+ if (host !== "avdeb.com" && host !== "www.avdeb.com") return null;
166
+ path = u.pathname;
167
+ } catch {
168
+ return null;
169
+ }
170
+ }
171
+ const [section, slug] = path.split(/[?#]/)[0]!.split("/").filter(Boolean);
172
+ const value = cleanSlug(slug);
173
+ if (!section || value === "") return null;
174
+ const kind = ({ creators: "creator", category: "tag", store: "handle" } as const)[
175
+ section.toLowerCase() as "creators" | "category" | "store"
176
+ ];
177
+ return kind ? { kind, value } : null;
178
+ }
179
+
180
+ /**
181
+ * Validate an untrusted query (route input). Unknown keys are ignored; an empty filter set means
182
+ * "newest products". `limit` is clamped to the tier max; a handle always means one product.
183
+ */
184
+ export function sanitizeQuery(input: unknown, max: number): CatalogQuery {
185
+ const src = isRecord(input) ? input : {};
186
+ const query: CatalogQuery = { limit: DEFAULT_LIMIT };
187
+ const creator = cleanSlug(src.creator);
188
+ const tag = cleanSlug(src.tag);
189
+ const type = cleanType(src.type);
190
+ const handle = cleanSlug(src.handle);
191
+ const q = cleanSearch(src.q);
192
+ if (creator) query.creator = creator;
193
+ if (tag) query.tag = tag;
194
+ if (type) query.type = type;
195
+ if (handle) query.handle = handle;
196
+ if (q) query.q = q;
197
+ const limit = Math.trunc(Number(src.limit));
198
+ query.limit = handle ? 1 : Number.isFinite(limit) && limit > 0 ? Math.min(max, limit) : Math.min(max, DEFAULT_LIMIT);
199
+ return query;
200
+ }
201
+
202
+ /** Stable string for a query (cache key, request de-duplication). */
203
+ export function queryKey(q: CatalogQuery): string {
204
+ return [q.creator ?? "", q.tag ?? "", q.type ?? "", q.handle ?? "", q.q ?? "", q.limit].join("|");
205
+ }
206
+
207
+ /** GET /v1/catalog/products URL. `ref` is only sent without a key (key holders get their own code). */
208
+ export function productsUrl(q: CatalogQuery, ref = ""): string {
209
+ const params = new URLSearchParams();
210
+ for (const k of ["creator", "tag", "type", "handle", "q"] as const) {
211
+ const v = q[k];
212
+ if (v) params.set(k, v);
213
+ }
214
+ params.set("limit", String(q.limit));
215
+ const code = cleanRef(ref);
216
+ if (code) params.set("ref", code);
217
+ return `${API_BASE}/products?${params.toString()}`;
218
+ }
219
+
220
+ function money(value: unknown): number | null {
221
+ return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : null;
222
+ }
223
+
224
+ /** Keep only fields the plugin renders, validated. `null` for anything unusable. */
225
+ export function normalizeProduct(raw: unknown): Product | null {
226
+ if (!isRecord(raw)) return null;
227
+ const handle = cleanSlug(raw.handle);
228
+ const title = str(raw.title).replace(CONTROL_RE, " ").trim().slice(0, 200);
229
+ const url = str(raw.url);
230
+ if (!handle || !title || !isAvdebUrl(url)) return null;
231
+
232
+ const image = str(raw.image);
233
+ const currency = str(raw.currency).toUpperCase();
234
+ let creator: ProductCreator | null = null;
235
+ if (isRecord(raw.creator)) {
236
+ const slug = cleanSlug(raw.creator.slug);
237
+ if (slug) {
238
+ const creatorUrl = str(raw.creator.url);
239
+ creator = {
240
+ slug,
241
+ name: str(raw.creator.name).trim().slice(0, 120) || slug,
242
+ url: isAvdebUrl(creatorUrl) ? creatorUrl : null,
243
+ };
244
+ }
245
+ }
246
+ const createdAt = str(raw.created_at);
247
+ return {
248
+ handle,
249
+ title,
250
+ url,
251
+ image: image.startsWith("https://") ? image : null,
252
+ price: money(raw.price),
253
+ compareAtPrice: money(raw.compare_at_price),
254
+ currency: CURRENCY_RE.test(currency) ? currency : "USD",
255
+ type: cleanType(raw.type) || null,
256
+ tags: Array.isArray(raw.tags) ? raw.tags.map(cleanSlug).filter(Boolean).slice(0, 20) : [],
257
+ creator,
258
+ createdAt: createdAt && !Number.isNaN(Date.parse(createdAt)) ? createdAt : null,
259
+ };
260
+ }
261
+
262
+ export function parseProductsResponse(json: unknown): ProductsResult | null {
263
+ if (!isRecord(json) || !Array.isArray(json.products)) return null;
264
+ const products: Product[] = [];
265
+ const seen = new Set<string>();
266
+ for (const raw of json.products) {
267
+ const p = normalizeProduct(raw);
268
+ if (p && !seen.has(p.handle)) {
269
+ seen.add(p.handle);
270
+ products.push(p);
271
+ }
272
+ }
273
+ const tier = json.tier === "secret" || json.tier === "publishable" ? json.tier : "anonymous";
274
+ return { products, ref: cleanRef(json.ref), tier };
275
+ }
276
+
277
+ export function parseKeyResponse(json: unknown): KeyOwner | null {
278
+ if (!isRecord(json) || !isRecord(json.owner)) return null;
279
+ const o = json.owner;
280
+ return {
281
+ type: str(o.type).replace(/[^a-z_-]/gi, "").toLowerCase().slice(0, 20),
282
+ name: str(o.name).trim().slice(0, 120),
283
+ ref: cleanRef(o.ref),
284
+ creatorSlug: cleanSlug(o.creator_slug),
285
+ };
286
+ }
287
+
288
+ /** Error message from an API error body (`{ "error": "…" }`) or the HTTP status. */
289
+ export function apiErrorMessage(status: number, json: unknown): string {
290
+ const msg = isRecord(json) ? str(json.error).trim().slice(0, 200) : "";
291
+ return msg || `HTTP ${status}`;
292
+ }