sanity-plugin-seofields 1.9.0 → 1.10.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/README.md +71 -0
- package/dist/chunk-CRCXC45D.js +56 -0
- package/dist/chunk-CRCXC45D.js.map +1 -0
- package/dist/{chunk-3OK3S2F7.cjs → chunk-EUG4MNRC.cjs} +60 -20
- package/dist/chunk-EUG4MNRC.cjs.map +1 -0
- package/dist/{chunk-Z5AOUU4H.js → chunk-NLEB47UV.js} +60 -20
- package/dist/chunk-NLEB47UV.js.map +1 -0
- package/dist/{chunk-FUUWBQE2.cjs → chunk-OULUDJPI.cjs} +66 -7
- package/dist/chunk-OULUDJPI.cjs.map +1 -0
- package/dist/{chunk-KIEO6QG3.js → chunk-XD4HKLEA.js} +66 -7
- package/dist/chunk-XD4HKLEA.js.map +1 -0
- package/dist/chunk-XYAZJ3WX.cjs +56 -0
- package/dist/chunk-XYAZJ3WX.cjs.map +1 -0
- package/dist/cli.js +1 -1
- package/dist/head.cjs +10 -2
- package/dist/head.cjs.map +1 -1
- package/dist/head.d.cts +61 -1
- package/dist/head.d.ts +61 -1
- package/dist/head.js +9 -1
- package/dist/hreflang-_VbSuWYD.d.cts +29 -0
- package/dist/hreflang-_VbSuWYD.d.ts +29 -0
- package/dist/index.cjs +101 -8
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +3 -2
- package/dist/index.d.ts +3 -2
- package/dist/index.js +273 -180
- package/dist/index.js.map +1 -1
- package/dist/next.cjs +11 -3
- package/dist/next.cjs.map +1 -1
- package/dist/next.d.cts +2 -1
- package/dist/next.d.ts +2 -1
- package/dist/next.js +9 -1
- package/dist/next.js.map +1 -1
- package/dist/{plugin-DoGeZP79.d.cts → plugin-HFuWZsJu.d.cts} +68 -1
- package/dist/{plugin-DQdThyxG.d.ts → plugin-oQUCim56.d.ts} +68 -1
- package/dist/server.cjs +2 -2
- package/dist/server.cjs.map +1 -1
- package/dist/server.d.cts +6 -8
- package/dist/server.d.ts +6 -8
- package/dist/server.js +1 -1
- package/dist/server.js.map +1 -1
- package/package.json +2 -2
- package/dist/chunk-3OK3S2F7.cjs.map +0 -1
- package/dist/chunk-FUUWBQE2.cjs.map +0 -1
- package/dist/chunk-KIEO6QG3.js.map +0 -1
- package/dist/chunk-Z5AOUU4H.js.map +0 -1
package/README.md
CHANGED
|
@@ -334,6 +334,7 @@ seofields({
|
|
|
334
334
|
| `fieldVisibility` | Hide specific SEO fields for specific document types |
|
|
335
335
|
| `fieldGroups` | Customize how fields are grouped in the `seoFields` object |
|
|
336
336
|
| `apiVersion` | Sanity API version used by plugin clients |
|
|
337
|
+
| `hreflang` | Auto-populate hreflangs from translations — see [Hreflang auto-populate](#hreflang-auto-populate) |
|
|
337
338
|
| `dashboard` | Enable and configure the SEO Health Dashboard tool |
|
|
338
339
|
| `licenseKey` | License key for pro features (dashboard, publish gate, pro industries) |
|
|
339
340
|
| `ai` | Enable "Generate with AI" fields — see [AI Content Generation](#ai-content-generation) |
|
|
@@ -381,6 +382,18 @@ export const {POST, OPTIONS} = createNextRouteHandler({
|
|
|
381
382
|
|
|
382
383
|
Without `industry` set, generation uses generic prompts, which are always free.
|
|
383
384
|
|
|
385
|
+
**Custom prompts** — write your own prompt wording with `customPrompt` (free: one function) or `customPrompts` (paid: up to 5 generic + 5 per industry, behind a license). Your function receives all extracted document values (`content`, `focusKeyword`, `keywords`, `meta`, `field`, `industry`) and returns the prompt string. Custom prompts replace the built-in pool by default; set `merge: true` to mix them in. In proxy mode set them on the server handler config. See [AI.md → Custom Prompts](./AI.md#custom-prompts).
|
|
386
|
+
|
|
387
|
+
```ts
|
|
388
|
+
seofields({
|
|
389
|
+
ai: {
|
|
390
|
+
provider: 'openai',
|
|
391
|
+
apiKey: process.env.SANITY_STUDIO_OPENAI_API_KEY,
|
|
392
|
+
customPrompt: (v) => `Write a 55-char SEO ${v.field} about: ${v.content.slice(0, 200)}`,
|
|
393
|
+
},
|
|
394
|
+
})
|
|
395
|
+
```
|
|
396
|
+
|
|
384
397
|
**Content source** (`ai.content`) — defaults to the document's `body` field. Accepts a single field, an array of fields in priority order, or a per-document-type mapping with a `default` fallback. Nested Portable Text is found automatically.
|
|
385
398
|
|
|
386
399
|
**Refinement pipeline** — each generation attempt is checked for target character length, required keyword presence (injected if missing), readability (simplified if too complex), and focus-keyword verbatim match against existing title/description. Controlled by `maxRetries` and `keepFirstOnValidationFail`.
|
|
@@ -840,6 +853,64 @@ Docs: [Frontend integration](https://sanity-plugin-seofields.thehardik.in/docs/f
|
|
|
840
853
|
|
|
841
854
|
---
|
|
842
855
|
|
|
856
|
+
## Hreflang auto-populate
|
|
857
|
+
|
|
858
|
+
For projects using [`@sanity/document-internationalization`](https://github.com/sanity-io/document-internationalization), derive hreflang alternates from your translation references instead of typing them by hand.
|
|
859
|
+
|
|
860
|
+
**Frontend** — `buildHreflangs()` turns the resolved `_translations` array into entries and feeds `buildSeoMeta`:
|
|
861
|
+
|
|
862
|
+
```ts
|
|
863
|
+
import {buildSeoMeta, buildHreflangs} from 'sanity-plugin-seofields/next' // or /head
|
|
864
|
+
|
|
865
|
+
// GROQ: "_translations": *[_type=="translation.metadata" && references(^._id)].translations[].value->{ language, "slug": slug.current }
|
|
866
|
+
export async function generateMetadata() {
|
|
867
|
+
return buildSeoMeta({
|
|
868
|
+
seo: data.seo,
|
|
869
|
+
baseUrl: 'https://example.com',
|
|
870
|
+
path: `/${data.slug.current}`,
|
|
871
|
+
hreflangs: buildHreflangs(data._translations, {
|
|
872
|
+
baseUrl: 'https://example.com',
|
|
873
|
+
xDefault: 'en',
|
|
874
|
+
// resolvePath: (t) => `/${t.language}/${t.slug}`,
|
|
875
|
+
}),
|
|
876
|
+
})
|
|
877
|
+
}
|
|
878
|
+
```
|
|
879
|
+
|
|
880
|
+
**Studio** — enable `hreflang.autoFill` to add a **Sync from translations** button to the `hreflangs` field (entries stay editable):
|
|
881
|
+
|
|
882
|
+
```ts
|
|
883
|
+
seofields({
|
|
884
|
+
baseUrl: 'https://example.com',
|
|
885
|
+
hreflang: {autoFill: true /*, localeField: 'language', resolvePath */},
|
|
886
|
+
})
|
|
887
|
+
```
|
|
888
|
+
|
|
889
|
+
The Studio sync reads `translation.metadata` via the standard client — no extra dependency required.
|
|
890
|
+
|
|
891
|
+
---
|
|
892
|
+
|
|
893
|
+
## llms.txt generator
|
|
894
|
+
|
|
895
|
+
Generate an [llms.txt](https://llmstxt.org) file from your Sanity content with `buildLlmsTxt()` + `docsToLlmsSection()` (framework-neutral, exported from `/head` and `/next`):
|
|
896
|
+
|
|
897
|
+
```ts
|
|
898
|
+
import {buildLlmsTxt, docsToLlmsSection} from 'sanity-plugin-seofields/head'
|
|
899
|
+
|
|
900
|
+
const body = buildLlmsTxt({
|
|
901
|
+
title: 'Acme',
|
|
902
|
+
summary: 'Everything Acme, for humans and LLMs.',
|
|
903
|
+
baseUrl: 'https://acme.com',
|
|
904
|
+
sections: [
|
|
905
|
+
docsToLlmsSection(posts, {title: 'Blog', baseUrl: 'https://acme.com'}),
|
|
906
|
+
docsToLlmsSection(docsPages, {title: 'Docs', baseUrl: 'https://acme.com'}),
|
|
907
|
+
],
|
|
908
|
+
})
|
|
909
|
+
// serve `body` from /llms.txt (route handler or build step)
|
|
910
|
+
```
|
|
911
|
+
|
|
912
|
+
---
|
|
913
|
+
|
|
843
914
|
## CLI
|
|
844
915
|
|
|
845
916
|
Run the CLI:
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
// src/helpers/url.ts
|
|
2
|
+
function joinUrl(base, path) {
|
|
3
|
+
const normalizedBase = base.replace(/\/+$/, "");
|
|
4
|
+
const normalizedPath = path.replace(/^\/+/, "");
|
|
5
|
+
return [normalizedBase, normalizedPath].filter(Boolean).join("/");
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
// src/helpers/hreflang.ts
|
|
9
|
+
function normalizeSlug(slug) {
|
|
10
|
+
var _a;
|
|
11
|
+
if (typeof slug === "string") return slug || void 0;
|
|
12
|
+
if (slug && typeof slug === "object") return (_a = slug.current) != null ? _a : void 0;
|
|
13
|
+
return void 0;
|
|
14
|
+
}
|
|
15
|
+
function resolveUrl(t, baseUrl, resolvePath) {
|
|
16
|
+
if (t.url) return t.url;
|
|
17
|
+
let path;
|
|
18
|
+
if (resolvePath) {
|
|
19
|
+
path = resolvePath(t);
|
|
20
|
+
} else if (t.path) {
|
|
21
|
+
path = t.path;
|
|
22
|
+
} else {
|
|
23
|
+
const slug = normalizeSlug(t.slug);
|
|
24
|
+
path = slug ? `/${slug.replace(/^\/+/, "")}` : void 0;
|
|
25
|
+
}
|
|
26
|
+
if (path === null || path === void 0 || path === "") return void 0;
|
|
27
|
+
return baseUrl ? joinUrl(baseUrl, path) : path;
|
|
28
|
+
}
|
|
29
|
+
function buildHreflangs(translations, options = {}) {
|
|
30
|
+
var _a;
|
|
31
|
+
const { baseUrl, resolvePath, xDefault, current } = options;
|
|
32
|
+
const all = current ? [current, ...translations != null ? translations : []] : [...translations != null ? translations : []];
|
|
33
|
+
const entries = [];
|
|
34
|
+
const seen = /* @__PURE__ */ new Set();
|
|
35
|
+
for (const t of all) {
|
|
36
|
+
const locale = (_a = t == null ? void 0 : t.language) == null ? void 0 : _a.trim();
|
|
37
|
+
if (!locale || seen.has(locale)) continue;
|
|
38
|
+
const url = resolveUrl(t, baseUrl, resolvePath);
|
|
39
|
+
if (!url) continue;
|
|
40
|
+
seen.add(locale);
|
|
41
|
+
entries.push({ locale, url });
|
|
42
|
+
}
|
|
43
|
+
if (xDefault) {
|
|
44
|
+
const match = entries.find((e) => e.locale === xDefault);
|
|
45
|
+
if (match && !seen.has("x-default")) {
|
|
46
|
+
entries.push({ locale: "x-default", url: match.url });
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
return entries;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export {
|
|
53
|
+
joinUrl,
|
|
54
|
+
buildHreflangs
|
|
55
|
+
};
|
|
56
|
+
//# sourceMappingURL=chunk-CRCXC45D.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/helpers/url.ts","../src/helpers/hreflang.ts"],"sourcesContent":["/**\n * Join a base URL and a path into a single URL, tolerating leading/trailing slashes on either side.\n *\n * @example\n * joinUrl('https://example.com/', '/about') // 'https://example.com/about'\n * joinUrl('https://example.com', '') // 'https://example.com'\n * joinUrl('', 'about') // 'about'\n */\nexport function joinUrl(base: string, path: string): string {\n const normalizedBase = base.replace(/\\/+$/, '') // remove trailing /\n const normalizedPath = path.replace(/^\\/+/, '') // remove leading /\n return [normalizedBase, normalizedPath].filter(Boolean).join('/')\n}\n","/**\n * Build hreflang alternate-link entries from resolved document translations.\n *\n * Designed for `@sanity/document-internationalization`: a standard GROQ query resolves translations as\n *\n * ```groq\n * \"_translations\": *[_type == \"translation.metadata\" && references(^._id)].translations[].value->{\n * language, \"slug\": slug.current\n * }\n * ```\n *\n * Pass that array here to get entries matching the plugin's `hreflangEntry` shape (`{locale, url}`),\n * which are assignable to `seo.hreflangs` or to `buildSeoMeta({ hreflangs })`.\n */\nimport {joinUrl} from './url'\n\nexport interface HreflangTranslation {\n /** BCP 47 language/region tag, e.g. \"en\", \"fr-FR\". */\n language?: string | null\n /** Sanity slug — either the raw string or the `{ current }` object. */\n slug?: {current?: string | null} | string | null\n /** Pre-built path (e.g. \"/fr/about\"). Wins over `slug`. */\n path?: string | null\n /** Absolute URL. Wins over `baseUrl` + path. */\n url?: string | null\n}\n\nexport interface BuildHreflangsOptions {\n /** Site origin, e.g. \"https://example.com\". Prepended to each translation's path. */\n baseUrl?: string\n /** Build the path for a translation. Defaults to `/${slug}`. Return null/undefined to skip. */\n resolvePath?: (t: HreflangTranslation) => string | null | undefined\n /** Language tag to also emit as an `x-default` entry (pointing at that language's URL). */\n xDefault?: string\n /** Include the current document itself in the set. */\n current?: HreflangTranslation\n}\n\nexport interface HreflangLinkEntry {\n locale: string\n url: string\n}\n\nfunction normalizeSlug(slug: HreflangTranslation['slug']): string | undefined {\n if (typeof slug === 'string') return slug || undefined\n if (slug && typeof slug === 'object') return slug.current ?? undefined\n return undefined\n}\n\nfunction resolveUrl(\n t: HreflangTranslation,\n baseUrl: string | undefined,\n resolvePath: BuildHreflangsOptions['resolvePath'],\n): string | undefined {\n if (t.url) return t.url\n\n let path: string | null | undefined\n if (resolvePath) {\n path = resolvePath(t)\n } else if (t.path) {\n path = t.path\n } else {\n const slug = normalizeSlug(t.slug)\n path = slug ? `/${slug.replace(/^\\/+/, '')}` : undefined\n }\n\n if (path === null || path === undefined || path === '') return undefined\n return baseUrl ? joinUrl(baseUrl, path) : path\n}\n\nexport function buildHreflangs(\n translations: HreflangTranslation[] | null | undefined,\n options: BuildHreflangsOptions = {},\n): HreflangLinkEntry[] {\n const {baseUrl, resolvePath, xDefault, current} = options\n const all = current ? [current, ...(translations ?? [])] : [...(translations ?? [])]\n\n const entries: HreflangLinkEntry[] = []\n const seen = new Set<string>()\n\n for (const t of all) {\n const locale = t?.language?.trim()\n if (!locale || seen.has(locale)) continue\n const url = resolveUrl(t, baseUrl, resolvePath)\n if (!url) continue\n seen.add(locale)\n entries.push({locale, url})\n }\n\n if (xDefault) {\n const match = entries.find((e) => e.locale === xDefault)\n if (match && !seen.has('x-default')) {\n entries.push({locale: 'x-default', url: match.url})\n }\n }\n\n return entries\n}\n"],"mappings":";AAQO,SAAS,QAAQ,MAAc,MAAsB;AAC1D,QAAM,iBAAiB,KAAK,QAAQ,QAAQ,EAAE;AAC9C,QAAM,iBAAiB,KAAK,QAAQ,QAAQ,EAAE;AAC9C,SAAO,CAAC,gBAAgB,cAAc,EAAE,OAAO,OAAO,EAAE,KAAK,GAAG;AAClE;;;AC+BA,SAAS,cAAc,MAAuD;AA3C9E;AA4CE,MAAI,OAAO,SAAS,SAAU,QAAO,QAAQ;AAC7C,MAAI,QAAQ,OAAO,SAAS,SAAU,SAAO,UAAK,YAAL,YAAgB;AAC7D,SAAO;AACT;AAEA,SAAS,WACP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|
|
289
289
|
var DEFAULT_PROMPTS = buildFieldPrompts(GENERIC_CTX, PUBLIC_ANGLE_COUNT);
|
|
290
|
-
|
|
290
|
+
function normalizeCustomPrompts(customPrompt, customPrompts) {
|
|
291
|
+
if (customPrompts) return customPrompts;
|
|
292
|
+
if (customPrompt) return { generic: [customPrompt] };
|
|
293
|
+
return void 0;
|
|
294
|
+
}
|
|
295
|
+
function toPromptFn(fn, field, industry) {
|
|
296
|
+
return (p) => fn({
|
|
297
|
+
field,
|
|
298
|
+
content: p.content,
|
|
299
|
+
focusKeyword: p.keyword,
|
|
300
|
+
keywords: p.keywords,
|
|
301
|
+
meta: p.meta,
|
|
302
|
+
industry
|
|
303
|
+
});
|
|
304
|
+
}
|
|
305
|
+
function wrapCustom(custom, field, industry) {
|
|
306
|
+
var _a, _b, _c;
|
|
307
|
+
const genericFns = (_a = custom.generic) != null ? _a : [];
|
|
308
|
+
const industryFns = industry ? (_c = (_b = custom.byIndustry) == null ? void 0 : _b[industry]) != null ? _c : [] : [];
|
|
309
|
+
return {
|
|
310
|
+
genericPrompts: genericFns.map((fn) => toPromptFn(fn, field, industry)),
|
|
311
|
+
industryPrompts: industryFns.map((fn) => toPromptFn(fn, field, industry)),
|
|
312
|
+
merge: custom.merge === true
|
|
313
|
+
};
|
|
314
|
+
}
|
|
315
|
+
async function resolvePromptPool(field, industry, licenseKey, projectId, custom) {
|
|
316
|
+
var _a;
|
|
291
317
|
const isFreeIndustry = Boolean(
|
|
292
318
|
industry && FREE_INDUSTRIES.includes(industry)
|
|
293
319
|
);
|
|
294
320
|
const publicPrompts = isFreeIndustry ? INDUSTRY_PROMPTS[industry][field] : DEFAULT_PROMPTS[field];
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
321
|
+
const wrapped = custom ? wrapCustom(custom, field, industry) : void 0;
|
|
322
|
+
if (licenseKey) {
|
|
323
|
+
try {
|
|
324
|
+
const mod = await Promise.resolve().then(() => _interopRequireWildcard(require("seofields-pro")));
|
|
325
|
+
if (typeof mod.resolveLicensedPromptPool === "function") {
|
|
326
|
+
return mod.resolveLicensedPromptPool({
|
|
327
|
+
licenseKey,
|
|
328
|
+
projectId,
|
|
329
|
+
field,
|
|
330
|
+
industry,
|
|
331
|
+
publicPrompts,
|
|
332
|
+
custom: wrapped
|
|
333
|
+
});
|
|
334
|
+
}
|
|
335
|
+
} catch (e) {
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
if (wrapped) {
|
|
339
|
+
const single = (_a = wrapped.industryPrompts[0]) != null ? _a : wrapped.genericPrompts[0];
|
|
340
|
+
if (single) {
|
|
341
|
+
return wrapped.merge ? [...publicPrompts, single] : [single];
|
|
342
|
+
}
|
|
308
343
|
}
|
|
344
|
+
return publicPrompts;
|
|
309
345
|
}
|
|
310
|
-
async function pickPrompt(field, params, industry, licenseKey, projectId) {
|
|
311
|
-
const pool = await resolvePromptPool(field, industry, licenseKey, projectId);
|
|
346
|
+
async function pickPrompt(field, params, { industry, licenseKey, projectId, custom } = {}) {
|
|
347
|
+
const pool = await resolvePromptPool(field, industry, licenseKey, projectId, custom);
|
|
312
348
|
const fn = pool[Math.floor(Math.random() * pool.length)];
|
|
313
349
|
return fn(params);
|
|
314
350
|
}
|
|
@@ -644,6 +680,7 @@ async function generateSeoText(field, content, focusKeyword, keywords, { config,
|
|
|
644
680
|
const callApi = buildCallApi(config, (_a = config.temperature) != null ? _a : 0.7, abortSignal);
|
|
645
681
|
const maxRetries = (_b = config.maxRetries) != null ? _b : DEFAULT_MAX_RETRIES;
|
|
646
682
|
const isLicensed = Boolean(config._licenseKey);
|
|
683
|
+
const custom = normalizeCustomPrompts(config.customPrompt, config.customPrompts);
|
|
647
684
|
const constraint = FIELD_CONSTRAINTS[field];
|
|
648
685
|
let firstRaw = "";
|
|
649
686
|
let lastRaw = "";
|
|
@@ -652,9 +689,12 @@ async function generateSeoText(field, content, focusKeyword, keywords, { config,
|
|
|
652
689
|
const prompt = await pickPrompt(
|
|
653
690
|
field,
|
|
654
691
|
{ content, keyword: focusKeyword, keywords, meta },
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
692
|
+
{
|
|
693
|
+
industry: config.industry,
|
|
694
|
+
licenseKey: isLicensed ? config._licenseKey : void 0,
|
|
695
|
+
projectId: config._projectId,
|
|
696
|
+
custom
|
|
697
|
+
}
|
|
658
698
|
);
|
|
659
699
|
const raw = stripQuotes(await callApi(prompt));
|
|
660
700
|
if (attempt === 0) firstRaw = raw;
|
|
@@ -670,4 +710,4 @@ async function generateSeoText(field, content, focusKeyword, keywords, { config,
|
|
|
670
710
|
|
|
671
711
|
|
|
672
712
|
exports.analyzeReadability = analyzeReadability; exports.pickTestOutput = pickTestOutput; exports.generateSeoText = generateSeoText;
|
|
673
|
-
//# sourceMappingURL=chunk-
|
|
713
|
+
//# sourceMappingURL=chunk-EUG4MNRC.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["/Users/hardik/GITHUB/sanity-plugin-seofields/npm/dist/chunk-EUG4MNRC.cjs","../src/utils/readability.ts","../src/utils/seoPrompts.ts","../src/utils/seoContentGen.ts"],"names":[],"mappings":"AAAA;AACE;AACA;AACF,wDAA6B;AAC7B;AACA;ACYA,SAAS,cAAA,CAAe,IAAA,EAAsB;AAjB9C,EAAA,IAAA,EAAA;AAkBE,EAAA,MAAM,EAAA,EAAI,IAAA,CAAK,WAAA,CAAY,CAAA,CAAE,OAAA,CAAQ,SAAA,EAAW,EAAE,CAAA;AAClD,EAAA,GAAA,CAAI,CAAA,CAAE,OAAA,GAAU,CAAA,EAAG,OAAO,CAAA;AAG1B,EAAA,MAAM,OAAA,EAAA,CAAS,GAAA,EAAA,CAAA,CAAE,KAAA,CAAM,YAAY,CAAA,EAAA,GAApB,KAAA,EAAA,GAA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AA;AAEO,EAAA;AACT;AAamB;AAjZnB,EAAA;AAmZyD,EAAA;AAElC,EAAA;AACF,IAAA;AACf,MAAA;AACA,MAAA;AACA,MAAA;AACA,MAAA;AACA,MAAA;AACiB,MAAA;AACA,MAAA;AACE,MAAA;AACX,MAAA;AACT,IAAA;AACH,EAAA;AAEuB,EAAA;AACyC,EAAA;AAExB,EAAA;AACK,EAAA;AACkC,EAAA;AACrC,EAAA;AAC3B,EAAA;AACD,EAAA;AAE0C,EAAA;AAC3B,IAAA;AAEN,IAAA;AACnB,MAAA;AAC+C,MAAA;AAC/C,MAAA;AACmB,QAAA;AAC6B,QAAA;AAC5B,QAAA;AAClB,QAAA;AACF,MAAA;AACF,IAAA;AAC6C,IAAA;AACf,IAAA;AAEkD,IAAA;AAErB,IAAA;AAChC,IAAA;AAC7B,EAAA;AAG8D,EAAA;AAChE;AH6PyF;AACA;AACA;AACA;AACA;AACA","file":"/Users/hardik/GITHUB/sanity-plugin-seofields/npm/dist/chunk-EUG4MNRC.cjs","sourcesContent":[null,"export interface ReadabilityResult {\n score: number\n gradeLevel: number\n avgWordsPerSentence: number\n words: number\n sentences: number\n label: string\n color: 'green' | 'orange' | 'red'\n}\n\n/**\n * Count vowel groups in a single word (improved — no regex stripping hacks).\n * - Lowercase, strip non-alpha\n * - If <= 3 chars -> 1 syllable\n * - Count consecutive vowel groups ([aeiouy]+ matches)\n * - Special case: silent trailing 'e' after consonant -> subtract 1 syllable, min 1\n */\nfunction countSyllables(word: string): number {\n const w = word.toLowerCase().replace(/[^a-z]/g, '')\n if (w.length <= 3) return 1\n\n // Count consecutive vowel groups\n const groups = w.match(/[aeiouy]+/g) ?? []\n let count = groups.length\n\n // Special case: silent trailing 'e' after consonant -> subtract 1 syllable, min 1\n if (w.endsWith('e') && w.length > 1 && !/[aeiouy]/.test(w[w.length - 2])) {\n count = Math.max(1, count - 1)\n }\n\n return Math.max(1, count)\n}\n\n/**\n * Split text on sentence boundaries (., !, ?)\n */\nfunction countSentences(text: string): number {\n const matches = text.match(/[.!?]+/g)\n return matches ? matches.length : 1\n}\n\n/**\n * Compute Flesch Reading Ease and Flesch-Kincaid Grade Level.\n * Returns null if text has fewer than 10 words.\n *\n * Flesch Reading Ease: 206.835 - 1.015*(words/sentences) - 84.6*(syllables/words)\n * FK Grade Level: 0.39*(words/sentences) + 11.8*(syllables/words) - 15.59\n */\nexport function analyzeReadability(text: string): ReadabilityResult | null {\n const wordList = text.trim().split(/\\s+/).filter(Boolean)\n const words = wordList.length\n if (words < 10) return null\n\n const sentences = countSentences(text)\n const syllables = wordList.reduce((acc, word) => acc + countSyllables(word), 0)\n\n const rawScore = 206.835 - 1.015 * (words / sentences) - 84.6 * (syllables / words)\n const score = Math.round(rawScore * 10) / 10\n\n const rawGrade = 0.39 * (words / sentences) + 11.8 * (syllables / words) - 15.59\n const gradeLevel = Math.round(rawGrade * 10) / 10\n\n const avgWordsPerSentence = Math.round((words / sentences) * 10) / 10\n\n let label: string\n let color: 'green' | 'orange' | 'red'\n\n if (score >= 70) {\n label = 'Easy to read'\n color = 'green'\n } else if (score >= 50) {\n label = 'Fairly easy'\n color = 'green'\n } else if (score >= 30) {\n label = 'Moderately difficult'\n color = 'orange'\n } else {\n label = 'Difficult to read'\n color = 'red'\n }\n\n return {\n score,\n gradeLevel,\n avgWordsPerSentence,\n words,\n sentences,\n label,\n color,\n }\n}\n","import type {AiIndustry, CustomPromptFn} from '../plugin'\n\nexport const FREE_INDUSTRIES = [\n 'blog',\n 'restaurant',\n 'travel',\n 'ecommerce',\n 'education',\n 'fitness',\n 'hospitality',\n 'nonprofit',\n] as const\nexport const PRO_INDUSTRIES = [\n 'healthcare',\n 'pharmacy',\n 'finance',\n 'realestate',\n 'saas',\n 'legal',\n 'insurance',\n 'automotive',\n 'homeServices',\n] as const\nconst PUBLIC_ANGLE_COUNT = 4\n\nexport type SeoGenField =\n | 'title'\n | 'description'\n | 'focusKeyword'\n | 'keywords'\n | 'ogTitle'\n | 'ogDescription'\n | 'twitterTitle'\n | 'twitterDescription'\n\nexport type MetaContext = {title?: string; description?: string; slug?: string}\n\ntype PromptParams = {content: string; keyword: string; keywords: string[]; meta?: MetaContext}\ntype PromptFn = (p: PromptParams) => string\ntype AngleFn = (params: PromptParams & {ctx: string}) => string\ntype FieldAngles = Record<SeoGenField, AngleFn[]>\ntype PublicIndustry = (typeof FREE_INDUSTRIES)[number]\n\n/**\n * Normalized custom-prompt config. `customPrompt` (free) collapses into `generic: [fn]`;\n * `customPrompts` (paid) is used as-is. See `normalizeCustomPrompts`.\n */\nexport type CustomPromptConfig = {\n generic?: CustomPromptFn[]\n byIndustry?: Partial<Record<AiIndustry, CustomPromptFn[]>>\n merge?: boolean\n}\n\n/** Custom prompts already wrapped as `PromptFn`s and bound to the current field + industry. */\ntype WrappedCustom = {genericPrompts: PromptFn[]; industryPrompts: PromptFn[]; merge: boolean}\n\ntype LicensedPromptPoolResolver = (options: {\n licenseKey?: string\n projectId?: string\n field: SeoGenField\n industry?: AiIndustry\n /** Free-tier pool — returned as-is when the license fails validation or the pro package is unavailable. */\n publicPrompts: PromptFn[]\n /** Pre-wrapped custom prompts. Count caps (≤5 each) + merge are applied behind license validation. */\n custom?: WrappedCustom\n}) => Promise<PromptFn[]>\n\nconst GENERIC_CTX = 'Write for a general web audience.'\n\nfunction buildKeywordLine(\n keyword: string,\n keywords: string[],\n keywordRequirement: string,\n fallback: string,\n): string {\n if (keywords.length > 0) {\n return `- At least one of these keywords MUST appear verbatim: ${keywords.join(', ')}`\n }\n\n if (keyword) {\n return `- The keyword \"${keyword}\" MUST appear ${keywordRequirement}`\n }\n\n return fallback\n}\n\nconst PUBLIC_INDUSTRY_CONTEXTS = {\n blog: 'Write for a blog or editorial publication. Use engaging, informative language. Appeal to curious readers seeking knowledge.',\n ecommerce:\n 'Write for an e-commerce store. Use action-oriented language that drives purchases. Highlight value, deals, and product benefits.',\n education:\n 'Write for an educational platform or course provider. Use encouraging, growth-focused language. Emphasize skills, outcomes, and career impact.',\n restaurant:\n 'Write for a restaurant, cafe, or food business. Use sensory, appetizing language. Evoke taste, ambiance, and memorable dining experience.',\n travel:\n 'Write for a travel agency or tourism brand. Use evocative, inspiring language. Paint vivid pictures of destinations and unforgettable experiences.',\n fitness:\n 'Write for a gym, studio, or personal training brand. Use motivating, energetic language. Emphasize results, transformation, and community.',\n hospitality:\n 'Write for a hotel, resort, or short-term rental brand. Use welcoming, sensory language. Evoke comfort, amenities, and a memorable stay.',\n nonprofit:\n 'Write for a nonprofit or charitable organization. Use sincere, mission-driven language. Emphasize impact, community, and the cause over sales language.',\n} satisfies Record<PublicIndustry, string>\n\n// ─── Title angles ────────────────────────────────────────────────────────────\n\n// Only the 4 free-tier angles live here — the remaining 6 per field live in `seofields-pro`\n// and are never shipped in this package's bundle. See resolvePromptPool below.\nconst TITLE_ANGLES = [\n 'Lead with a strong action verb',\n 'Lead with the key benefit to the reader',\n 'Use a how-to format (How to …)',\n 'Use a question format that the reader wants answered',\n]\n\nconst titleFns: AngleFn[] = TITLE_ANGLES.map((angle) => ({content, keyword, keywords, ctx}) => {\n const kwLine = buildKeywordLine(\n keyword,\n keywords,\n 'verbatim in the title',\n '- Make it compelling and clear without a specific keyword',\n )\n return `You are an SEO expert. ${ctx}\nGenerate one SEO-optimized meta title using this angle: ${angle}.\nRequirements:\n- Strictly 50–60 characters including spaces and punctuation\n${kwLine}\n- Apply the angle — do not deviate\n- Return ONLY the title text. No quotes, no explanation.\n\nPage content:\n${content}`\n})\n\n// ─── Description angles ───────────────────────────────────────────────────────\n\nconst DESC_ANGLES = [\n \"Open with a direct answer to the reader's likely question, then add a clear call to action\",\n 'Open with the pain point the reader has, then offer the solution this page provides',\n 'Open with a bold claim, then briefly back it up',\n 'Open with who this is for, then state what they will get',\n]\n\nconst descFns: AngleFn[] = DESC_ANGLES.map((angle) => ({content, keyword, keywords, ctx}) => {\n const kwLine = buildKeywordLine(\n keyword,\n keywords,\n 'naturally in the description',\n '- Include a clear call to action',\n )\n return `You are an SEO expert. ${ctx}\nGenerate one SEO-optimized meta description using this angle: ${angle}.\nRequirements:\n- Strictly 120–160 characters including spaces and punctuation\n${kwLine}\n- Short sentences (under 15 words each), plain everyday words, no jargon — aim for high readability\n- Apply the angle — do not deviate\n- Return ONLY the description text. No quotes, no explanation.\n\nPage content:\n${content}`\n})\n\n// ─── OG Title angles ──────────────────────────────────────────────────────────\n\nconst OG_TITLE_ANGLES = [\n 'Curiosity hook — make the reader need to click to find out',\n 'FOMO angle — what they will miss if they do not read this',\n 'Social proof angle — imply consensus, popularity, or trust',\n 'Question angle — pose the exact question the audience is thinking',\n]\n\nconst ogTitleFns: AngleFn[] = OG_TITLE_ANGLES.map(\n (angle) =>\n ({content, keyword, ctx}) =>\n `You are a social media and SEO expert. ${ctx}\nGenerate one Open Graph title for social sharing using this angle: ${angle}.\nRequirements:\n- Strictly 40–60 characters\n- Optimized for social sharing engagement, not just search\n- Include the core topic clearly${keyword ? ` (topic: \"${keyword}\")` : ''}\n- Apply the angle above — do not deviate from it\n- Return ONLY the OG title text. No quotes, no explanation.\n\nPage content:\n${content}`,\n)\n\n// ─── OG Description angles ────────────────────────────────────────────────────\n\nconst OG_DESC_ANGLES = [\n 'Focus on what the reader gets — concrete takeaways or outcomes',\n 'Transformation promise — describe the before/after state',\n 'Bold claim backed by a brief piece of evidence or context',\n 'Pain relief framing — identify the problem and promise relief',\n]\n\nconst ogDescFns: AngleFn[] = OG_DESC_ANGLES.map(\n (angle) =>\n ({content, keyword, ctx}) =>\n `You are a social media and SEO expert. ${ctx}\nGenerate one Open Graph description for social sharing using this angle: ${angle}.\nRequirements:\n- Strictly 90–120 characters\n- Compelling enough to drive clicks from social feeds\n- Include the core topic naturally${keyword ? ` (topic: \"${keyword}\")` : ''}\n- Apply the angle above — do not deviate from it\n- Return ONLY the OG description text. No quotes, no explanation.\n\nPage content:\n${content}`,\n)\n\n// ─── Twitter Title angles ─────────────────────────────────────────────────────\n\nconst TW_TITLE_ANGLES = [\n 'Punchy curiosity hook — make the reader need to click',\n 'Direct FOMO — what they miss by scrolling past',\n 'Conversational question the audience is silently asking',\n 'Bold, scroll-stopping claim in plain language',\n]\n\nconst twTitleFns: AngleFn[] = TW_TITLE_ANGLES.map(\n (angle) =>\n ({content, keyword, ctx}) =>\n `You are a social media copywriter. ${ctx}\nGenerate one X (Twitter) card title using this angle: ${angle}.\nRequirements:\n- Strictly 30–70 characters\n- Punchy and direct — Twitter audiences scroll fast\n- Include the core topic naturally${keyword ? ` (topic: \"${keyword}\")` : ''}\n- Apply the angle above — do not deviate from it\n- Return ONLY the title text. No quotes, no explanation.\n\nPage content:\n${content}`,\n)\n\n// ─── Twitter Description angles ───────────────────────────────────────────────\n\nconst TW_DESC_ANGLES = [\n 'Conversational direct answer — what the page gives you',\n 'Pain-point opener followed by relief in one sentence',\n 'Bold hook followed by the core benefit',\n 'Short-form transformation promise',\n]\n\nconst twDescFns: AngleFn[] = TW_DESC_ANGLES.map(\n (angle) =>\n ({content, keyword, ctx}) =>\n `You are a social media copywriter. ${ctx}\nGenerate one X (Twitter) card description using this angle: ${angle}.\nRequirements:\n- Strictly 50–200 characters\n- Conversational and punchy — casual Twitter tone\n- Include the core topic naturally${keyword ? ` (topic: \"${keyword}\")` : ''}\n- Apply the angle above — do not deviate from it\n- Return ONLY the description text. No quotes, no explanation.\n\nPage content:\n${content}`,\n)\n\n// ─── Focus Keyword angles ─────────────────────────────────────────────────────\n\nconst FK_ANGLES = [\n 'Identify the single keyword phrase a user would most likely search to find this page',\n 'Identify the primary search intent keyword — what the reader types when looking for this content',\n 'Extract the most commercially or informationally valuable keyword from this content',\n 'Identify the exact phrase that best captures the core topic of this page',\n]\n\nconst fkFns: AngleFn[] = FK_ANGLES.map((angle) => ({content, meta, ctx}) => {\n const hasTitle = Boolean(meta?.title)\n const hasDescription = Boolean(meta?.description)\n const hasSlug = Boolean(meta?.slug)\n\n const metaBlock =\n hasTitle || hasDescription || hasSlug\n ? `\\nExisting page fields:\n${hasTitle ? `Meta title: \"${meta!.title}\"` : ''}\n${hasDescription ? `Meta description: \"${meta!.description}\"` : ''}\n${hasSlug ? `URL slug: \"${meta!.slug}\"` : ''}\n\nCRITICAL: The keyword you return MUST appear verbatim (exact match, case-insensitive) inside the meta title${hasDescription ? ' and meta description' : ''} above.\nDo NOT invent a new keyword — extract one that already exists in those fields.\n${hasSlug ? 'Prefer a phrase that also appears in the URL slug.' : ''}\n`\n : ''\n\n return `You are an SEO expert. ${ctx}\nTask: ${angle}.\n${metaBlock}\nRequirements:\n- Return ONLY the keyword or keyword phrase (1–4 words typically)\n- It MUST appear verbatim in the meta title${hasDescription ? ' and description' : ''} provided above\n- No explanation, no quotes, no punctuation, no extra words\n- Single line response\n\nPage content:\n${content}`\n})\n\n// ─── Keywords angles ──────────────────────────────────────────────────────────\n\nconst KW_ANGLES = [\n 'Generate 8 keywords mixing high-volume short-tail and specific long-tail phrases',\n 'Generate 8 keywords that cover both the main topic and closely related subtopics',\n 'Generate 8 keywords targeting both informational and commercial search intent',\n 'Generate 8 keywords including question-based phrases people would search',\n]\n\nconst kwFns: AngleFn[] = KW_ANGLES.map(\n (angle) =>\n ({content, keyword, ctx}) =>\n `You are an SEO expert. ${ctx}\n${angle}${keyword ? ` Include \"${keyword}\" as one of the keywords.` : ''}\nRequirements:\n- Return exactly 8 keywords as a comma-separated list\n- No numbering, no explanation, no quotes around individual keywords\n- Mix short-tail (1–2 words) and long-tail (3–5 words) phrases\n- All keywords must be directly relevant to the page content\n\nPage content:\n${content}`,\n)\n\n// ─── Angle map ────────────────────────────────────────────────────────────────\n\nconst BASE_ANGLES: FieldAngles = {\n title: titleFns,\n description: descFns,\n focusKeyword: fkFns,\n keywords: kwFns,\n ogTitle: ogTitleFns,\n ogDescription: ogDescFns,\n twitterTitle: twTitleFns,\n twitterDescription: twDescFns,\n}\n\nfunction buildFieldPrompts(ctx: string, count: number): Record<SeoGenField, PromptFn[]> {\n const out = {} as Record<SeoGenField, PromptFn[]>\n for (const field of Object.keys(BASE_ANGLES) as SeoGenField[]) {\n out[field] = BASE_ANGLES[field]\n .slice(0, count)\n .map((fn) => (p: PromptParams) => fn({...p, ctx}))\n }\n return out\n}\n\nexport const INDUSTRY_PROMPTS = Object.fromEntries(\n (Object.keys(PUBLIC_INDUSTRY_CONTEXTS) as PublicIndustry[]).map((industry) => [\n industry,\n buildFieldPrompts(PUBLIC_INDUSTRY_CONTEXTS[industry], PUBLIC_ANGLE_COUNT),\n ]),\n) as Record<PublicIndustry, Record<SeoGenField, PromptFn[]>>\n\nexport const DEFAULT_PROMPTS = buildFieldPrompts(GENERIC_CTX, PUBLIC_ANGLE_COUNT)\n\n/** Collapse the two public config fields into one normalized shape. `customPrompts` wins if both are set. */\nexport function normalizeCustomPrompts(\n customPrompt?: CustomPromptFn,\n customPrompts?: CustomPromptConfig,\n): CustomPromptConfig | undefined {\n if (customPrompts) return customPrompts\n if (customPrompt) return {generic: [customPrompt]}\n return undefined\n}\n\n// Bind a user CustomPromptFn to the current field + industry, exposing it through the existing PromptFn\n// contract. `p.keyword` maps to `focusKeyword` in the values object handed to the user.\nfunction toPromptFn(fn: CustomPromptFn, field: SeoGenField, industry?: AiIndustry): PromptFn {\n return (p: PromptParams) =>\n fn({\n field,\n content: p.content,\n focusKeyword: p.keyword,\n keywords: p.keywords,\n meta: p.meta,\n industry,\n })\n}\n\n// Wrap the custom fns relevant to this (field, industry) into PromptFns. Counts are NOT capped here —\n// the free cap (1) is applied in resolvePromptPool, the paid cap (5 each) inside seofields-pro.\nfunction wrapCustom(\n custom: CustomPromptConfig,\n field: SeoGenField,\n industry?: AiIndustry,\n): WrappedCustom {\n const genericFns = custom.generic ?? []\n const industryFns = industry ? (custom.byIndustry?.[industry] ?? []) : []\n return {\n genericPrompts: genericFns.map((fn) => toPromptFn(fn, field, industry)),\n industryPrompts: industryFns.map((fn) => toPromptFn(fn, field, industry)),\n merge: custom.merge === true,\n }\n}\n\nasync function resolvePromptPool(\n field: SeoGenField,\n industry?: AiIndustry,\n licenseKey?: string,\n projectId?: string,\n custom?: CustomPromptConfig,\n): Promise<PromptFn[]> {\n const isFreeIndustry = Boolean(\n industry && (FREE_INDUSTRIES as readonly string[]).includes(industry),\n )\n const publicPrompts = isFreeIndustry\n ? INDUSTRY_PROMPTS[industry as PublicIndustry][field]\n : DEFAULT_PROMPTS[field]\n\n const wrapped = custom ? wrapCustom(custom, field, industry) : undefined\n\n // The remaining angles (up to 10 total) plus the paid custom-prompt cap (5 each) live entirely in\n // `seofields-pro` — never shipped in this package's bundle — and are only unlocked once the license\n // actually validates.\n if (licenseKey) {\n try {\n const mod = (await import('seofields-pro')) as {\n resolveLicensedPromptPool?: LicensedPromptPoolResolver\n }\n // Pro package unavailable — an unverified licenseKey alone must never unlock the pool.\n if (typeof mod.resolveLicensedPromptPool === 'function') {\n return mod.resolveLicensedPromptPool({\n licenseKey,\n projectId,\n field,\n industry,\n publicPrompts,\n custom: wrapped,\n })\n }\n } catch {\n // fall through to the free path below\n }\n }\n\n // Free / pro-unavailable path. Custom prompts are capped to a single prompt (industry-specific for\n // the active industry preferred, else generic). Cannot be enforced cryptographically here.\n if (wrapped) {\n const single = wrapped.industryPrompts[0] ?? wrapped.genericPrompts[0]\n if (single) {\n return wrapped.merge ? [...publicPrompts, single] : [single]\n }\n }\n return publicPrompts\n}\n\nexport type PickPromptOptions = {\n industry?: AiIndustry\n licenseKey?: string\n projectId?: string\n custom?: CustomPromptConfig\n}\n\nexport async function pickPrompt(\n field: SeoGenField,\n params: PromptParams,\n {industry, licenseKey, projectId, custom}: PickPromptOptions = {},\n): Promise<string> {\n const pool = await resolvePromptPool(field, industry, licenseKey, projectId, custom)\n const fn = pool[Math.floor(Math.random() * pool.length)]\n return fn(params)\n}\n\n// ─── Test mode static outputs ─────────────────────────────────────────────────\n\nexport const TEST_MODE_OUTPUTS: Record<SeoGenField, string[]> = {\n title: [\n 'Boost Your SEO Rankings With These Proven Tips',\n 'How to Write Meta Titles That Drive More Clicks',\n '10 Strategies to Improve Your Search Visibility',\n 'Why Your Meta Title Is Killing Your Click-Through Rate',\n ],\n description: [\n 'Learn how to write SEO-optimized meta titles that rank higher and earn more clicks. Discover the exact techniques used by top SEO professionals.',\n 'Struggling with low organic traffic? Our complete guide covers everything you need to fix your meta tags and climb the search rankings fast.',\n 'Meta titles under 60 characters get the best click-through rates. Find out how to craft compelling titles that rank and convert visitors.',\n 'This guide is for content creators and marketers who want to improve search rankings without technical expertise. Start seeing results today.',\n ],\n focusKeyword: [\n 'seo meta title',\n 'on-page seo',\n 'meta tag optimization',\n 'organic traffic growth',\n ],\n keywords: [\n 'seo tips, meta title optimization, on-page seo, search rankings, click-through rate, seo guide, organic traffic, meta description, keyword placement, seo best practices',\n 'meta tags, title tag optimization, serp optimization, seo ranking factors, page title seo, seo for beginners, improve search rankings, seo checklist, meta title length, seo tools',\n 'on-page optimization, meta tag guide, seo title tips, increase organic traffic, search visibility, seo writing, title tag examples, meta description length, content seo, seo strategy',\n 'seo optimization guide, meta title examples, serp click-through rate, google ranking tips, seo content writing, page title best practices, keyword in title, seo traffic, rank higher google, search engine results',\n ],\n ogTitle: [\n 'The SEO Secret That Tripled Our Organic Traffic',\n 'Are You Making These 5 Common Meta Title Mistakes?',\n 'This One Change Can Double Your Search Click-Through Rate',\n 'Why 90% of Meta Titles Fail to Drive Clicks',\n ],\n ogDescription: [\n 'Get the exact framework top SEO teams use to write meta titles that rank higher and earn more clicks from search results.',\n 'Before: low CTR and invisible search rankings. After: consistent page-one results. Here is how to make that shift with your meta tags.',\n 'Research shows properly optimized meta titles get 30% more clicks. We show you exactly how to achieve that in under 10 minutes.',\n 'If your page is not getting clicks from search results, your meta title is likely the problem. Here is how to diagnose and fix it.',\n ],\n twitterTitle: [\n 'The Meta Title Trick That Tripled Our Traffic',\n \"You're Probably Writing Meta Titles Wrong\",\n 'One Change That Doubles Your Click-Through Rate',\n 'Why Most Meta Titles Fail (And How to Fix Yours)',\n ],\n twitterDescription: [\n \"Most pages leave clicks on the table because of weak meta titles. Here's the fix — in under 10 minutes.\",\n \"Low search CTR? Your meta title is probably the culprit. Here's how to diagnose and fix it today.\",\n 'Optimized meta titles get 30% more clicks. This guide shows you exactly how to write one that works.',\n 'Stop writing generic meta titles. This thread-worthy guide gives you templates that rank and convert.',\n ],\n}\n\nexport function pickTestOutput(field: SeoGenField): string {\n const arr = TEST_MODE_OUTPUTS[field]\n return arr[Math.floor(Math.random() * arr.length)]\n}\n","import type {AiConfig, AiIndustry} from '../plugin'\nimport {analyzeReadability} from './readability'\nimport {type MetaContext, normalizeCustomPrompts, pickPrompt, type SeoGenField} from './seoPrompts'\n\nconst DEFAULT_MAX_RETRIES = 2\n\nconst PROVIDER_DEFAULTS: Record<string, {baseUrl: string; model: string; requiresKey: boolean}> = {\n openai: {baseUrl: 'https://api.openai.com/v1', model: 'gpt-4o-mini', requiresKey: true},\n anthropic: {\n baseUrl: 'https://api.anthropic.com',\n model: 'claude-haiku-4-5-20251001',\n requiresKey: true,\n },\n groq: {\n baseUrl: 'https://api.groq.com/openai/v1',\n model: 'llama-3.3-70b-versatile',\n requiresKey: true,\n },\n gemini: {\n baseUrl: 'https://generativelanguage.googleapis.com/v1beta/openai',\n model: 'gemini-2.0-flash',\n requiresKey: true,\n },\n ollama: {baseUrl: 'http://localhost:11434/v1', model: 'llama3.2', requiresKey: false},\n}\n\n// Must exactly match validation thresholds in seoUtils.ts\nconst FIELD_CONSTRAINTS: Partial<Record<SeoGenField, {min: number; max: number}>> = {\n title: {min: 50, max: 60},\n description: {min: 120, max: 160},\n ogTitle: {min: 40, max: 60},\n ogDescription: {min: 90, max: 120},\n twitterTitle: {min: 30, max: 70},\n twitterDescription: {min: 50, max: 200},\n}\n\nfunction parseApiError(status: number, body: unknown): string {\n const msg =\n (body as {error?: {message?: string}})?.error?.message ||\n (body as {message?: string})?.message ||\n ''\n if (status === 401)\n return `Authentication failed (401). Check your API key.${msg ? ` ${msg}` : ''}`\n if (status === 429)\n return `Rate limit reached (429). Wait a moment and try again.${msg ? ` ${msg}` : ''}`\n if (status >= 500)\n return `Provider server error (${status}). Try again shortly.${msg ? ` ${msg}` : ''}`\n return msg || `Request failed with status ${status}.`\n}\n\ninterface CallOpts {\n apiKey?: string\n model: string\n temperature: number\n}\n\nasync function callOpenAICompat(\n baseUrl: string,\n opts: CallOpts,\n prompt: string,\n signal: AbortSignal,\n): Promise<string> {\n const headers: Record<string, string> = {'Content-Type': 'application/json'}\n if (opts.apiKey) headers.Authorization = `Bearer ${opts.apiKey}`\n\n const res = await fetch(`${baseUrl}/chat/completions`, {\n method: 'POST',\n headers,\n signal,\n body: JSON.stringify({\n model: opts.model,\n messages: [{role: 'user', content: prompt}],\n /* eslint-disable camelcase */\n max_tokens: 300,\n /* eslint-enable camelcase */\n temperature: opts.temperature,\n }),\n })\n const data = await res.json()\n if (!res.ok) throw new Error(parseApiError(res.status, data))\n return ((data.choices?.[0]?.message?.content as string) || '').trim()\n}\n\nasync function callAnthropic(\n opts: CallOpts,\n apiKey: string,\n prompt: string,\n signal: AbortSignal,\n): Promise<string> {\n const res = await fetch('https://api.anthropic.com/v1/messages', {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'x-api-key': apiKey,\n 'anthropic-version': '2023-06-01',\n 'anthropic-dangerous-direct-browser-access': 'true',\n },\n signal,\n body: JSON.stringify({\n model: opts.model,\n /* eslint-disable camelcase */\n max_tokens: 300,\n /* eslint-enable camelcase */\n temperature: opts.temperature,\n messages: [{role: 'user', content: prompt}],\n }),\n })\n const data = await res.json()\n if (!res.ok) throw new Error(parseApiError(res.status, data))\n return ((data.content?.[0]?.text as string) || '').trim()\n}\n\ninterface ProxyRequest {\n field: SeoGenField\n content: string\n focusKeyword: string\n keywords: string[]\n meta: MetaContext | undefined\n endpoint: string\n industry: AiIndustry | undefined\n licenseKey: string | undefined\n signal: AbortSignal\n}\n\nasync function callProxy({\n field,\n content,\n focusKeyword,\n keywords,\n meta,\n endpoint,\n industry,\n licenseKey,\n signal,\n}: ProxyRequest): Promise<string> {\n const res = await fetch(endpoint, {\n method: 'POST',\n headers: {'Content-Type': 'application/json'},\n signal,\n body: JSON.stringify({field, content, focusKeyword, keywords, meta, industry, licenseKey}),\n })\n const data = await res.json()\n if (!res.ok) throw new Error(parseApiError(res.status, data))\n const result = (data as {result?: string}).result\n if (!result) throw new Error('Proxy response missing \"result\" field.')\n return result.trim()\n}\n\n// Strip surrounding quotes that models sometimes add despite instructions\nfunction stripQuotes(text: string): string {\n return text.replace(/^[\"'\"\"]|[\"'\"\"]$/g, '').trim()\n}\n\n// Targeted fix: model sees the exact text + what's wrong — far more reliable than blind regeneration\nasync function refineLength(\n field: SeoGenField,\n raw: string,\n constraint: {min: number; max: number},\n callApi: (prompt: string) => Promise<string>,\n): Promise<string> {\n const len = raw.length\n const isTooShort = len < constraint.min\n const action = isTooShort ? 'Expand' : 'Shorten'\n const issue = isTooShort\n ? `too short at ${len} characters (minimum is ${constraint.min})`\n : `too long at ${len} characters (maximum is ${constraint.max})`\n\n const prompt = `This SEO ${field} is ${issue}. Target range: ${constraint.min}–${constraint.max} characters.\n${action} it to fit within that range. Preserve the meaning and any keywords present.\nCount every character carefully before outputting. The final text MUST be ${constraint.min}–${constraint.max} chars.\nCurrent text (${len} chars): \"${raw}\"\nReturn ONLY the rewritten text. No quotes, no labels, no character count.`\n\n return callApi(prompt)\n}\n\n// Targeted fix: insert the missing keyword while keeping length in range\nasync function refineKeyword(\n field: SeoGenField,\n raw: string,\n keywords: string[],\n constraint: {min: number; max: number} | undefined,\n callApi: (prompt: string) => Promise<string>,\n): Promise<string> {\n const kwList = keywords.join(', ')\n const rangeNote = constraint\n ? ` The final text MUST be ${constraint.min}–${constraint.max} characters.`\n : ''\n\n const prompt = `This SEO ${field} is missing a required keyword.\nRewrite it to include at least one of these keywords naturally: ${kwList}.${rangeNote}\nDo not force the keyword awkwardly — weave it in as if it was always there.\nCurrent text: \"${raw}\"\nReturn ONLY the rewritten text. No quotes, no labels, no explanation.`\n\n return callApi(prompt)\n}\n\n// Targeted fix: pick a keyword that actually exists verbatim in the existing title/description\nasync function refineFocusKeyword(\n raw: string,\n meta: MetaContext,\n callApi: (prompt: string) => Promise<string>,\n): Promise<string> {\n const missing: string[] = []\n const kw = raw.toLowerCase().trim()\n if (meta.title && !meta.title.toLowerCase().includes(kw))\n missing.push(`meta title: \"${meta.title}\"`)\n if (meta.description && !meta.description.toLowerCase().includes(kw))\n missing.push(`meta description: \"${meta.description}\"`)\n\n const prompt = `The focus keyword \"${raw}\" does not appear verbatim in the following existing page fields:\n${missing.join('\\n')}\n\nExtract a keyword or phrase (1–4 words) that appears VERBATIM in those fields.\nDo not invent a new keyword — only return a phrase already present in the text above.\n${meta.slug ? `URL slug: \"${meta.slug}\" — prefer a phrase that also matches part of this.` : ''}\n\nReturn ONLY the keyword. No quotes, no explanation, no punctuation. Single line.`\n\n return callApi(prompt)\n}\n\n// Targeted fix: simplify language to improve readability score\nasync function refineReadability(\n raw: string,\n constraint: {min: number; max: number},\n callApi: (prompt: string) => Promise<string>,\n): Promise<string> {\n const prompt = `This SEO meta description uses language that is too complex.\nRewrite it so it reads simply and clearly:\n- Use short sentences (under 15 words each)\n- Use common everyday words — no jargon or passive voice\n- Keep the same core meaning and any keywords present\n- The final text MUST be ${constraint.min}–${constraint.max} characters\nCurrent text: \"${raw}\"\nReturn ONLY the rewritten text. No quotes, no labels, no explanation.`\n\n return callApi(prompt)\n}\n\nfunction checkLength(field: SeoGenField, text: string): boolean {\n const constraint = FIELD_CONSTRAINTS[field]\n if (!constraint) return true\n return text.length >= constraint.min && text.length <= constraint.max\n}\n\nfunction checkKeywords(field: SeoGenField, text: string, keywords: string[]): boolean {\n if ((field === 'title' || field === 'description') && keywords.length > 0) {\n const lower = text.toLowerCase()\n return keywords.some((kw) => lower.includes(kw.toLowerCase().trim()))\n }\n return true\n}\n\nfunction checkReadability(field: SeoGenField, text: string): boolean {\n if (field === 'description') {\n const readability = analyzeReadability(text)\n return !readability || readability.score >= 50\n }\n return true\n}\n\nfunction checkFocusKeywordInMeta(kw: string, meta: MetaContext): boolean {\n const lower = kw.toLowerCase().trim()\n if (meta.title && !meta.title.toLowerCase().includes(lower)) return false\n if (meta.description && !meta.description.toLowerCase().includes(lower)) return false\n return true\n}\n\nfunction validateOutput(\n field: SeoGenField,\n text: string,\n keywords: string[],\n meta?: MetaContext,\n): string | null {\n if (!checkLength(field, text)) return null\n if (!checkKeywords(field, text, keywords)) return null\n if (!checkReadability(field, text)) return null\n if (field === 'focusKeyword' && meta && (meta.title || meta.description)) {\n if (!checkFocusKeywordInMeta(text, meta)) return null\n }\n return text\n}\n\nfunction warnIfKeyExposed(config: AiConfig): void {\n if (config.apiKey && typeof window !== 'undefined') {\n console.warn(\n '[sanity-plugin-seofields] \"apiKey\" is bundled into the Studio\\'s client-side JS and is readable by ' +\n 'anyone with Studio access. Use \"endpoint\" with a server-side proxy instead — see ' +\n '\"sanity-plugin-seofields/server\" for ready-made handlers.',\n )\n }\n}\n\nfunction buildCallApi(\n config: AiConfig,\n temperature: number,\n abortSignal: AbortSignal,\n): (prompt: string) => Promise<string> {\n const provider = config.provider ?? 'openai'\n const providerDef = PROVIDER_DEFAULTS[provider]\n if (!providerDef) throw new Error(`Unknown provider \"${provider}\".`)\n if (providerDef.requiresKey && !config.apiKey) {\n throw new Error(`No API key configured for \"${provider}\". Add apiKey to your ai plugin config.`)\n }\n\n const baseUrl = config.baseUrl ?? providerDef.baseUrl\n const model = config.model ?? providerDef.model\n const opts: CallOpts = {apiKey: config.apiKey, model, temperature}\n\n const useAnthropic = provider === 'anthropic' && !config.baseUrl\n return (prompt: string) =>\n useAnthropic\n ? callAnthropic(opts, config.apiKey!, prompt, abortSignal)\n : callOpenAICompat(baseUrl, opts, prompt, abortSignal)\n}\n\ninterface RefinementCtx {\n field: SeoGenField\n keywords: string[]\n meta: MetaContext | undefined\n constraint: {min: number; max: number} | undefined\n callApi: (prompt: string) => Promise<string>\n abortSignal: AbortSignal\n}\n\n// Runs passes 1-4 against a single raw response, tolerating errors/aborts by keeping the prior text.\nasync function refineRawText(raw: string, ctx: RefinementCtx): Promise<string> {\n const {field, keywords, meta, constraint, callApi, abortSignal} = ctx\n let text = raw\n\n // Pass 1 — fix length if wrong\n if (constraint && !checkLength(field, text)) {\n try {\n abortSignal.throwIfAborted()\n text = stripQuotes(await refineLength(field, text, constraint, callApi))\n } catch {\n // aborted or errored — continue with what we have\n }\n }\n\n // Pass 2 — inject missing keyword if required (title/description fields)\n if (!checkKeywords(field, text, keywords)) {\n try {\n abortSignal.throwIfAborted()\n text = stripQuotes(await refineKeyword(field, text, keywords, constraint, callApi))\n // re-fix length after keyword injection since it may have shifted\n if (constraint && !checkLength(field, text)) {\n abortSignal.throwIfAborted()\n text = stripQuotes(await refineLength(field, text, constraint, callApi))\n }\n } catch {\n // aborted or errored — continue with what we have\n }\n }\n\n // Pass 3 — simplify for readability (description only)\n if (!checkReadability(field, text) && constraint) {\n try {\n abortSignal.throwIfAborted()\n text = stripQuotes(await refineReadability(text, constraint, callApi))\n // re-fix length after rewrite\n if (!checkLength(field, text)) {\n abortSignal.throwIfAborted()\n text = stripQuotes(await refineLength(field, text, constraint, callApi))\n }\n } catch {\n // aborted or errored — continue with what we have\n }\n }\n\n // Pass 4 — ensure focus keyword exists verbatim in existing title + description\n if (\n field === 'focusKeyword' &&\n meta &&\n (meta.title || meta.description) &&\n !checkFocusKeywordInMeta(text, meta)\n ) {\n try {\n abortSignal.throwIfAborted()\n text = stripQuotes(await refineFocusKeyword(text, meta, callApi))\n } catch {\n // aborted or errored — continue with what we have\n }\n }\n\n return text\n}\n\nexport interface GenerateOpts {\n config: AiConfig\n signal?: AbortSignal\n meta?: MetaContext\n}\n\nexport async function generateSeoText(\n field: SeoGenField,\n content: string,\n focusKeyword: string,\n keywords: string[],\n {config, signal, meta}: GenerateOpts,\n): Promise<string> {\n const abortSignal = signal ?? AbortSignal.timeout(15000)\n\n if (config.endpoint) {\n return callProxy({\n field,\n content,\n focusKeyword,\n keywords,\n meta,\n endpoint: config.endpoint,\n industry: config.industry,\n licenseKey: config._licenseKey,\n signal: abortSignal,\n })\n }\n\n warnIfKeyExposed(config)\n const callApi = buildCallApi(config, config.temperature ?? 0.7, abortSignal)\n\n const maxRetries = config.maxRetries ?? DEFAULT_MAX_RETRIES\n const isLicensed = Boolean(config._licenseKey)\n const custom = normalizeCustomPrompts(config.customPrompt, config.customPrompts)\n const constraint = FIELD_CONSTRAINTS[field]\n let firstRaw = ''\n let lastRaw = ''\n\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\n abortSignal.throwIfAborted()\n\n const prompt = await pickPrompt(\n field,\n {content, keyword: focusKeyword, keywords, meta},\n {\n industry: config.industry,\n licenseKey: isLicensed ? config._licenseKey : undefined,\n projectId: config._projectId,\n custom,\n },\n )\n const raw = stripQuotes(await callApi(prompt))\n if (attempt === 0) firstRaw = raw\n\n lastRaw = await refineRawText(raw, {field, keywords, meta, constraint, callApi, abortSignal})\n\n const valid = validateOutput(field, lastRaw, keywords, meta)\n if (valid !== null) return valid\n }\n\n // All attempts exhausted — true = keep first response, false/undefined = keep last\n return config.keepFirstOnValidationFail === true ? firstRaw : lastRaw\n}\n"]}
|
|
@@ -287,28 +287,64 @@ var INDUSTRY_PROMPTS = Object.fromEntries(
|
|
|
287
287
|
])
|
|
288
288
|
);
|
|
289
289
|
var DEFAULT_PROMPTS = buildFieldPrompts(GENERIC_CTX, PUBLIC_ANGLE_COUNT);
|
|
290
|
-
|
|
290
|
+
function normalizeCustomPrompts(customPrompt, customPrompts) {
|
|
291
|
+
if (customPrompts) return customPrompts;
|
|
292
|
+
if (customPrompt) return { generic: [customPrompt] };
|
|
293
|
+
return void 0;
|
|
294
|
+
}
|
|
295
|
+
function toPromptFn(fn, field, industry) {
|
|
296
|
+
return (p) => fn({
|
|
297
|
+
field,
|
|
298
|
+
content: p.content,
|
|
299
|
+
focusKeyword: p.keyword,
|
|
300
|
+
keywords: p.keywords,
|
|
301
|
+
meta: p.meta,
|
|
302
|
+
industry
|
|
303
|
+
});
|
|
304
|
+
}
|
|
305
|
+
function wrapCustom(custom, field, industry) {
|
|
306
|
+
var _a, _b, _c;
|
|
307
|
+
const genericFns = (_a = custom.generic) != null ? _a : [];
|
|
308
|
+
const industryFns = industry ? (_c = (_b = custom.byIndustry) == null ? void 0 : _b[industry]) != null ? _c : [] : [];
|
|
309
|
+
return {
|
|
310
|
+
genericPrompts: genericFns.map((fn) => toPromptFn(fn, field, industry)),
|
|
311
|
+
industryPrompts: industryFns.map((fn) => toPromptFn(fn, field, industry)),
|
|
312
|
+
merge: custom.merge === true
|
|
313
|
+
};
|
|
314
|
+
}
|
|
315
|
+
async function resolvePromptPool(field, industry, licenseKey, projectId, custom) {
|
|
316
|
+
var _a;
|
|
291
317
|
const isFreeIndustry = Boolean(
|
|
292
318
|
industry && FREE_INDUSTRIES.includes(industry)
|
|
293
319
|
);
|
|
294
320
|
const publicPrompts = isFreeIndustry ? INDUSTRY_PROMPTS[industry][field] : DEFAULT_PROMPTS[field];
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
321
|
+
const wrapped = custom ? wrapCustom(custom, field, industry) : void 0;
|
|
322
|
+
if (licenseKey) {
|
|
323
|
+
try {
|
|
324
|
+
const mod = await import("seofields-pro");
|
|
325
|
+
if (typeof mod.resolveLicensedPromptPool === "function") {
|
|
326
|
+
return mod.resolveLicensedPromptPool({
|
|
327
|
+
licenseKey,
|
|
328
|
+
projectId,
|
|
329
|
+
field,
|
|
330
|
+
industry,
|
|
331
|
+
publicPrompts,
|
|
332
|
+
custom: wrapped
|
|
333
|
+
});
|
|
334
|
+
}
|
|
335
|
+
} catch (e) {
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
if (wrapped) {
|
|
339
|
+
const single = (_a = wrapped.industryPrompts[0]) != null ? _a : wrapped.genericPrompts[0];
|
|
340
|
+
if (single) {
|
|
341
|
+
return wrapped.merge ? [...publicPrompts, single] : [single];
|
|
342
|
+
}
|
|
308
343
|
}
|
|
344
|
+
return publicPrompts;
|
|
309
345
|
}
|
|
310
|
-
async function pickPrompt(field, params, industry, licenseKey, projectId) {
|
|
311
|
-
const pool = await resolvePromptPool(field, industry, licenseKey, projectId);
|
|
346
|
+
async function pickPrompt(field, params, { industry, licenseKey, projectId, custom } = {}) {
|
|
347
|
+
const pool = await resolvePromptPool(field, industry, licenseKey, projectId, custom);
|
|
312
348
|
const fn = pool[Math.floor(Math.random() * pool.length)];
|
|
313
349
|
return fn(params);
|
|
314
350
|
}
|
|
@@ -644,6 +680,7 @@ async function generateSeoText(field, content, focusKeyword, keywords, { config,
|
|
|
644
680
|
const callApi = buildCallApi(config, (_a = config.temperature) != null ? _a : 0.7, abortSignal);
|
|
645
681
|
const maxRetries = (_b = config.maxRetries) != null ? _b : DEFAULT_MAX_RETRIES;
|
|
646
682
|
const isLicensed = Boolean(config._licenseKey);
|
|
683
|
+
const custom = normalizeCustomPrompts(config.customPrompt, config.customPrompts);
|
|
647
684
|
const constraint = FIELD_CONSTRAINTS[field];
|
|
648
685
|
let firstRaw = "";
|
|
649
686
|
let lastRaw = "";
|
|
@@ -652,9 +689,12 @@ async function generateSeoText(field, content, focusKeyword, keywords, { config,
|
|
|
652
689
|
const prompt = await pickPrompt(
|
|
653
690
|
field,
|
|
654
691
|
{ content, keyword: focusKeyword, keywords, meta },
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
692
|
+
{
|
|
693
|
+
industry: config.industry,
|
|
694
|
+
licenseKey: isLicensed ? config._licenseKey : void 0,
|
|
695
|
+
projectId: config._projectId,
|
|
696
|
+
custom
|
|
697
|
+
}
|
|
658
698
|
);
|
|
659
699
|
const raw = stripQuotes(await callApi(prompt));
|
|
660
700
|
if (attempt === 0) firstRaw = raw;
|
|
@@ -670,4 +710,4 @@ export {
|
|
|
670
710
|
pickTestOutput,
|
|
671
711
|
generateSeoText
|
|
672
712
|
};
|
|
673
|
-
//# sourceMappingURL=chunk-
|
|
713
|
+
//# sourceMappingURL=chunk-NLEB47UV.js.map
|