@kanorio/sdk 0.0.0-stage → 1.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.
Files changed (84) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +66 -2
  3. package/dist/customer-oauth.d.ts +86 -0
  4. package/dist/customer-oauth.js +112 -0
  5. package/dist/customer.d.ts +176 -0
  6. package/dist/customer.js +125 -0
  7. package/dist/delivery.d.ts +35 -0
  8. package/dist/delivery.js +49 -0
  9. package/dist/edge.d.ts +108 -0
  10. package/dist/edge.js +287 -0
  11. package/dist/forms.d.ts +123 -0
  12. package/dist/forms.js +130 -0
  13. package/dist/generated/customer.d.ts +3157 -0
  14. package/dist/generated/delivery.d.ts +2408 -0
  15. package/dist/generated/management.d.ts +38333 -0
  16. package/dist/http.d.ts +73 -0
  17. package/dist/http.js +162 -0
  18. package/dist/index.d.ts +16 -0
  19. package/dist/index.js +17 -0
  20. package/dist/locales.d.ts +80 -0
  21. package/dist/locales.js +81 -0
  22. package/dist/management.d.ts +19 -0
  23. package/dist/management.js +22 -0
  24. package/dist/paginate.d.ts +18 -0
  25. package/dist/paginate.js +27 -0
  26. package/dist/preview.d.ts +40 -0
  27. package/dist/preview.js +131 -0
  28. package/dist/protection.d.ts +74 -0
  29. package/dist/protection.js +68 -0
  30. package/dist/revalidate.d.ts +84 -0
  31. package/dist/revalidate.js +143 -0
  32. package/dist/seo.d.ts +120 -0
  33. package/dist/seo.js +125 -0
  34. package/dist/server-key.d.ts +71 -0
  35. package/dist/server-key.js +103 -0
  36. package/dist/shared/api/delivery/cache-tags.d.ts +142 -0
  37. package/dist/shared/api/delivery/cache-tags.js +212 -0
  38. package/dist/shared/api/server-key.d.ts +90 -0
  39. package/dist/shared/api/server-key.js +260 -0
  40. package/dist/shared/business-registry/attribution.d.ts +14 -0
  41. package/dist/shared/business-registry/attribution.js +28 -0
  42. package/dist/shared/business-registry/define.d.ts +3 -0
  43. package/dist/shared/business-registry/define.js +4 -0
  44. package/dist/shared/business-registry/formats/eu-vat.d.ts +2 -0
  45. package/dist/shared/business-registry/formats/eu-vat.js +54 -0
  46. package/dist/shared/business-registry/formats/hk-br.d.ts +5 -0
  47. package/dist/shared/business-registry/formats/hk-br.js +23 -0
  48. package/dist/shared/business-registry/formats/jp-trn.d.ts +6 -0
  49. package/dist/shared/business-registry/formats/jp-trn.js +23 -0
  50. package/dist/shared/business-registry/formats/kr-brn.d.ts +6 -0
  51. package/dist/shared/business-registry/formats/kr-brn.js +30 -0
  52. package/dist/shared/business-registry/formats/my.d.ts +7 -0
  53. package/dist/shared/business-registry/formats/my.js +32 -0
  54. package/dist/shared/business-registry/formats/sg-uen.d.ts +1 -0
  55. package/dist/shared/business-registry/formats/sg-uen.js +21 -0
  56. package/dist/shared/business-registry/formats/tw-vat.d.ts +10 -0
  57. package/dist/shared/business-registry/formats/tw-vat.js +32 -0
  58. package/dist/shared/business-registry/index.d.ts +9 -0
  59. package/dist/shared/business-registry/index.js +10 -0
  60. package/dist/shared/business-registry/lookup-wire.d.ts +33 -0
  61. package/dist/shared/business-registry/lookup-wire.js +8 -0
  62. package/dist/shared/business-registry/normalize.d.ts +7 -0
  63. package/dist/shared/business-registry/normalize.js +12 -0
  64. package/dist/shared/business-registry/registry.d.ts +26 -0
  65. package/dist/shared/business-registry/registry.js +67 -0
  66. package/dist/shared/business-registry/types.d.ts +60 -0
  67. package/dist/shared/business-registry/types.js +10 -0
  68. package/dist/shared/localization/locale-path.d.ts +38 -0
  69. package/dist/shared/localization/locale-path.js +76 -0
  70. package/dist/shared/localization/request-locale.d.ts +42 -0
  71. package/dist/shared/localization/request-locale.js +61 -0
  72. package/dist/shared/seo/alternates.d.ts +61 -0
  73. package/dist/shared/seo/alternates.js +71 -0
  74. package/dist/shared/types/forms-logic.d.ts +96 -0
  75. package/dist/shared/types/forms-logic.js +209 -0
  76. package/dist/shared/types/number-input.d.ts +5 -0
  77. package/dist/shared/types/number-input.js +16 -0
  78. package/dist/shared/utils/redirect-matching.d.ts +76 -0
  79. package/dist/shared/utils/redirect-matching.js +181 -0
  80. package/dist/tax-id.d.ts +7 -0
  81. package/dist/tax-id.js +6 -0
  82. package/dist/typed.d.ts +85 -0
  83. package/dist/typed.js +28 -0
  84. package/package.json +86 -3
@@ -0,0 +1,49 @@
1
+ /**
2
+ * Content Delivery API (`https://{site}/api/v1`, anonymous and cacheable).
3
+ * Types are generated from the Delivery API's OpenAPI document. `siteUrl` is the site's URL (hosted subdomain or custom domain).
4
+ */
5
+ import { createHttpClient } from "./http.js";
6
+ import { createSeoHelpers } from "./seo.js";
7
+ import { createTypedClient } from "./typed.js";
8
+ import { DEFAULT_CACHE_TAG_PREFIX, DELIVERY_CACHE_TAGS_HEADER as SHARED_CACHE_TAGS_HEADER, parseCacheTagsHeader, prefixCacheTags } from "./shared/api/delivery/cache-tags.js";
9
+ export const DELIVERY_PREVIEW_HEADER = "x-kanorio-preview";
10
+ export function deliveryBaseUrl(siteUrl) {
11
+ return `${siteUrl.replace(/\/+$/, "")}/api/v1`;
12
+ }
13
+ export function createDeliveryClient(options) {
14
+ const { siteUrl, previewToken, headers: baseHeaders, ...rest } = options;
15
+ const headers = previewToken === undefined
16
+ ? baseHeaders
17
+ : async () => {
18
+ const merged = new Headers(typeof baseHeaders === "function" ? await baseHeaders() : baseHeaders);
19
+ const token = typeof previewToken === "function" ? await previewToken() : previewToken;
20
+ if (token)
21
+ merged.set(DELIVERY_PREVIEW_HEADER, token);
22
+ return merged;
23
+ };
24
+ const baseClient = createTypedClient(createHttpClient({ ...rest, headers, baseUrl: deliveryBaseUrl(siteUrl) }));
25
+ const seoHelpers = createSeoHelpers({ siteUrl, fetch: rest.fetch });
26
+ return Object.assign(baseClient, { seo: seoHelpers });
27
+ }
28
+ export const DELIVERY_CACHE_TAGS_HEADER = SHARED_CACHE_TAGS_HEADER;
29
+ /**
30
+ * Parses the cache tags from a Delivery API response's `X-Kanorio-Cache-Tags` header (raw strings, the same vocabulary as a webhook's `data.cacheTags`).
31
+ * To tag a framework cache, use `frameworkCacheTags` (which adds the namespace).
32
+ */
33
+ export function parseDeliveryCacheTags(headers) {
34
+ if (!headers)
35
+ return [];
36
+ const raw = typeof headers.get === "function"
37
+ ? headers.get(DELIVERY_CACHE_TAGS_HEADER)
38
+ : headers[DELIVERY_CACHE_TAGS_HEADER] ??
39
+ headers["X-Kanorio-Cache-Tags"];
40
+ return parseCacheTagsHeader(raw);
41
+ }
42
+ /**
43
+ * Response cache tags with the namespace added (`kanorio:` by default), ready for Next.js `fetch(..., { next: { tags } })` or `cacheTag()`.
44
+ * `createRevalidateHandler` calls `revalidateTag` with the same prefix when an event arrives, so the two sides match. Accepts headers or an already parsed array.
45
+ */
46
+ export function frameworkCacheTags(source, prefix = DEFAULT_CACHE_TAG_PREFIX) {
47
+ const raw = Array.isArray(source) ? source : parseDeliveryCacheTags(source);
48
+ return prefixCacheTags(raw, prefix);
49
+ }
package/dist/edge.d.ts ADDED
@@ -0,0 +1,108 @@
1
+ /**
2
+ * `@kanorio/sdk/edge`: edge middleware for AI crawler management and tracking, plus 301/302 redirect rules.
3
+ *
4
+ * Design (the logic lives on the server; the SDK stays thin):
5
+ * - The block list (`crawlerRules.blockedTokens`) and the redirect rules (`/api/v1/redirects`) are fetched from the Kanorio Content Delivery API
6
+ * and kept in a short in-memory cache (60 seconds by default), so rule changes in the dashboard apply without redeploying the front end.
7
+ * - A hit from a known AI crawler is reported, without blocking, to `POST {siteUrl}/api/v1/analytics/bot-hit`,
8
+ * so the dashboard's crawler analytics have full data for a self-hosted front end too.
9
+ * - Multilingual sites (`features.locales`) follow the same rules as hosted sites: the primary locale code used as a prefix (`/zh-hant/about`) redirects 301 to the unprefixed path;
10
+ * `/{prefix}/llms.txt`, `llms-full.txt`, `rss.xml`, `feed.xml` and `feed.atom` are answered at the edge with that locale's file; redirect rules match the unprefixed path
11
+ * and in-site targets get the same prefix back; an allowed decision carries `locale` (locale and unprefixed path) for the front end's routing
12
+ */
13
+ import { type RequestLocaleResult } from "./shared/localization/request-locale.js";
14
+ export declare const CRAWLER_LIST_VERSION = "2026-10-22";
15
+ export interface EdgeBotInfo {
16
+ uaToken: string;
17
+ operator: string;
18
+ intent: "training" | "retrieval" | "search";
19
+ blockable: boolean;
20
+ }
21
+ export declare const EDGE_BOT_LIST: readonly EdgeBotInfo[];
22
+ export declare function classifyEdgeUserAgent(ua: string): EdgeBotInfo | null;
23
+ export declare function isEdgeBotBlocked(bot: EdgeBotInfo, blockedTokens: readonly string[] | null | undefined): boolean;
24
+ export interface RedirectRule {
25
+ sourcePath: string;
26
+ targetUrl: string;
27
+ statusCode: number;
28
+ /** null: shared by every locale (matched on the unprefixed path); a locale code: belongs to that locale only (matched on the full prefixed path, target used as is) */
29
+ locale?: string | null;
30
+ }
31
+ export interface KanorioMiddlewareOptions {
32
+ /** Kanorio system or service URL (for example `https://s-xxx.kanorio.com`) */
33
+ siteUrl: string;
34
+ /** Rule cache lifetime in seconds (60 by default) */
35
+ cacheTtlSeconds?: number;
36
+ /** Feature switches (crawlers, redirects, indexNow and locales are all on by default) */
37
+ features?: {
38
+ crawlers?: boolean;
39
+ redirects?: boolean;
40
+ /**
41
+ * Answers the IndexNow key verification file (`/<32hex>.txt`) automatically, so IndexNow (Bing, Naver, Seznam, Yandex)
42
+ * can verify key ownership on this external domain without the owner wiring a key endpoint.
43
+ */
44
+ indexNow?: boolean;
45
+ /**
46
+ * Locale routing for multilingual sites: the primary locale code as a prefix redirects 301 to the unprefixed path, per-locale llms and RSS files are answered at the edge,
47
+ * and redirect rules match the unprefixed path; an allowed decision carries `locale`. No effect on single-language sites.
48
+ */
49
+ locales?: boolean;
50
+ };
51
+ fetch?: typeof globalThis.fetch;
52
+ /**
53
+ * Server key (`knr_sk_…`, from an environment variable). Required for crawler hit reporting: the report is a
54
+ * server-to-server write, and without a key Kanorio's edge challenges it and the hit is lost. The visitor's
55
+ * (crawler's) IP is read from the incoming request with `visitorIpFromRequest`.
56
+ */
57
+ serverKey?: string;
58
+ }
59
+ /** The request's locale on an allowed decision (multilingual sites only; `pathname` is the primary-locale path without the prefix, used for front-end routing and Delivery reads) */
60
+ export type MiddlewareLocale = RequestLocaleResult & {
61
+ primaryLocale: string;
62
+ };
63
+ export type MiddlewareDecision = {
64
+ action: "pass";
65
+ botHit?: {
66
+ bot: EdgeBotInfo;
67
+ blocked: false;
68
+ };
69
+ locale?: MiddlewareLocale;
70
+ } | {
71
+ action: "block";
72
+ status: 403;
73
+ botHit: {
74
+ bot: EdgeBotInfo;
75
+ blocked: true;
76
+ };
77
+ } | {
78
+ action: "redirect";
79
+ status: 301 | 302;
80
+ location: string;
81
+ } | {
82
+ action: "respond";
83
+ status: 200;
84
+ body: string;
85
+ contentType: string;
86
+ };
87
+ export interface KanorioMiddleware {
88
+ /** Evaluates one Request and returns a decision (no framework-specific Response) */
89
+ evaluate(request: Request, event?: {
90
+ waitUntil?: (promise: Promise<unknown>) => void;
91
+ }): Promise<MiddlewareDecision>;
92
+ /**
93
+ * Next.js handler (the file is `proxy.ts` from Next.js 16, `middleware.ts` in 15 and earlier): returns a `Response` (403, 301/302 or the IndexNow key file) or `null` (allow).
94
+ * On `null`, continue with your own logic; it can go at the top of an existing middleware. Rules are cached in memory (`cacheTtlSeconds`, 60 seconds by default);
95
+ * when Kanorio is unreachable the last rules are kept, and before the first load everything is allowed, so visitors are never blocked.
96
+ */
97
+ handleRequest(request: Request, event?: {
98
+ waitUntil?: (promise: Promise<unknown>) => void;
99
+ }): Promise<Response | null>;
100
+ }
101
+ export declare function createKanorioMiddleware(options: KanorioMiddlewareOptions): KanorioMiddleware;
102
+ export declare const edge: {
103
+ middleware: typeof createKanorioMiddleware;
104
+ classifyUserAgent: typeof classifyEdgeUserAgent;
105
+ isBotBlocked: typeof isEdgeBotBlocked;
106
+ };
107
+ export { resolveRequestLocale } from "./shared/localization/request-locale.js";
108
+ export { matchRedirect, matchLocalizedRedirect } from "./shared/utils/redirect-matching.js";
package/dist/edge.js ADDED
@@ -0,0 +1,287 @@
1
+ /**
2
+ * `@kanorio/sdk/edge`: edge middleware for AI crawler management and tracking, plus 301/302 redirect rules.
3
+ *
4
+ * Design (the logic lives on the server; the SDK stays thin):
5
+ * - The block list (`crawlerRules.blockedTokens`) and the redirect rules (`/api/v1/redirects`) are fetched from the Kanorio Content Delivery API
6
+ * and kept in a short in-memory cache (60 seconds by default), so rule changes in the dashboard apply without redeploying the front end.
7
+ * - A hit from a known AI crawler is reported, without blocking, to `POST {siteUrl}/api/v1/analytics/bot-hit`,
8
+ * so the dashboard's crawler analytics have full data for a self-hosted front end too.
9
+ * - Multilingual sites (`features.locales`) follow the same rules as hosted sites: the primary locale code used as a prefix (`/zh-hant/about`) redirects 301 to the unprefixed path;
10
+ * `/{prefix}/llms.txt`, `llms-full.txt`, `rss.xml`, `feed.xml` and `feed.atom` are answered at the edge with that locale's file; redirect rules match the unprefixed path
11
+ * and in-site targets get the same prefix back; an allowed decision carries `locale` (locale and unprefixed path) for the front end's routing
12
+ */
13
+ import { deliveryBaseUrl } from "./delivery.js";
14
+ import { serverKeyRequest, visitorIpFromRequest } from "./server-key.js";
15
+ import { localeRootPath, resolveRequestLocale } from "./shared/localization/request-locale.js";
16
+ import { canonicalRedirectPath, matchLocalizedRedirect } from "./shared/utils/redirect-matching.js";
17
+ export const CRAWLER_LIST_VERSION = "2026-10-22";
18
+ export const EDGE_BOT_LIST = [
19
+ { uaToken: "OAI-SearchBot", operator: "openai", intent: "retrieval", blockable: true },
20
+ { uaToken: "ChatGPT-User", operator: "openai", intent: "retrieval", blockable: true },
21
+ { uaToken: "GPTBot", operator: "openai", intent: "training", blockable: true },
22
+ { uaToken: "Claude-SearchBot", operator: "anthropic", intent: "retrieval", blockable: true },
23
+ { uaToken: "Claude-User", operator: "anthropic", intent: "retrieval", blockable: true },
24
+ { uaToken: "Claude-Web", operator: "anthropic", intent: "retrieval", blockable: true },
25
+ { uaToken: "ClaudeBot", operator: "anthropic", intent: "training", blockable: true },
26
+ { uaToken: "anthropic-ai", operator: "anthropic", intent: "training", blockable: true },
27
+ { uaToken: "Google-Extended", operator: "google", intent: "training", blockable: true },
28
+ { uaToken: "Google-Agent", operator: "google", intent: "retrieval", blockable: true },
29
+ { uaToken: "Googlebot", operator: "google", intent: "search", blockable: false },
30
+ { uaToken: "PerplexityBot", operator: "perplexity", intent: "retrieval", blockable: true },
31
+ { uaToken: "Perplexity-User", operator: "perplexity", intent: "retrieval", blockable: true },
32
+ { uaToken: "CCBot", operator: "commoncrawl", intent: "training", blockable: true },
33
+ { uaToken: "Bytespider", operator: "bytedance", intent: "training", blockable: true },
34
+ { uaToken: "Applebot-Extended", operator: "apple", intent: "training", blockable: true },
35
+ { uaToken: "Applebot", operator: "apple", intent: "search", blockable: false },
36
+ { uaToken: "Meta-ExternalAgent", operator: "meta", intent: "training", blockable: true },
37
+ { uaToken: "meta-webindexer", operator: "meta", intent: "retrieval", blockable: true },
38
+ { uaToken: "meta-externalfetcher", operator: "meta", intent: "retrieval", blockable: true },
39
+ { uaToken: "FacebookBot", operator: "meta", intent: "training", blockable: true },
40
+ { uaToken: "Amazonbot", operator: "amazon", intent: "training", blockable: true },
41
+ { uaToken: "Amzn-SearchBot", operator: "amazon", intent: "retrieval", blockable: true },
42
+ { uaToken: "Amzn-User", operator: "amazon", intent: "retrieval", blockable: true },
43
+ { uaToken: "MistralAI-User", operator: "mistral", intent: "retrieval", blockable: true },
44
+ { uaToken: "DuckAssistBot", operator: "duckduckgo", intent: "retrieval", blockable: true },
45
+ { uaToken: "YouBot", operator: "you", intent: "retrieval", blockable: true },
46
+ { uaToken: "cohere-ai", operator: "cohere", intent: "training", blockable: true },
47
+ { uaToken: "Grok-DeepSearch", operator: "xai", intent: "retrieval", blockable: true },
48
+ { uaToken: "xAI-Grok", operator: "xai", intent: "retrieval", blockable: true },
49
+ { uaToken: "GrokBot", operator: "xai", intent: "training", blockable: true },
50
+ { uaToken: "Diffbot", operator: "diffbot", intent: "training", blockable: true },
51
+ { uaToken: "AI2Bot", operator: "ai2", intent: "training", blockable: true },
52
+ { uaToken: "iaskspider", operator: "iask", intent: "retrieval", blockable: true },
53
+ { uaToken: "bingbot", operator: "microsoft", intent: "search", blockable: false },
54
+ ];
55
+ const _lowerList = EDGE_BOT_LIST.map((b) => ({
56
+ bot: b,
57
+ lower: b.uaToken.toLowerCase(),
58
+ }));
59
+ export function classifyEdgeUserAgent(ua) {
60
+ if (!ua)
61
+ return null;
62
+ const lowerUa = ua.toLowerCase();
63
+ for (const { bot, lower } of _lowerList) {
64
+ if (lowerUa.includes(lower))
65
+ return bot;
66
+ }
67
+ return null;
68
+ }
69
+ export function isEdgeBotBlocked(bot, blockedTokens) {
70
+ if (!bot.blockable)
71
+ return false;
72
+ if (!blockedTokens?.length)
73
+ return false;
74
+ const botToken = bot.uaToken.toLowerCase();
75
+ return blockedTokens.some((token) => token.toLowerCase() === botToken);
76
+ }
77
+ const INDEXNOW_KEY_PATH_RE = /^\/([a-f0-9]{32})\.txt$/i;
78
+ /** Per-locale SEO files such as `/{prefix}/llms.txt` mapped to their Delivery endpoints (the same file names hosted sites use) */
79
+ const LOCALIZED_SEO_FILES = {
80
+ "llms.txt": "/seo/llms.txt",
81
+ "llms-full.txt": "/seo/llms-full.txt",
82
+ "rss.xml": "/feed",
83
+ "feed.xml": "/feed",
84
+ "feed.atom": "/feed.atom",
85
+ };
86
+ export function createKanorioMiddleware(options) {
87
+ const apiBase = deliveryBaseUrl(options.siteUrl);
88
+ const ttlMs = Math.max(5, options.cacheTtlSeconds ?? 60) * 1000;
89
+ const enableCrawlers = options.features?.crawlers !== false;
90
+ const enableRedirects = options.features?.redirects !== false;
91
+ const enableIndexNow = options.features?.indexNow !== false;
92
+ const enableLocales = options.features?.locales !== false;
93
+ const f = options.fetch ?? globalThis.fetch;
94
+ let cached = null;
95
+ let inflight = null;
96
+ async function loadState() {
97
+ const now = Date.now();
98
+ if (cached && cached.expiresAt > now)
99
+ return cached;
100
+ if (inflight)
101
+ return inflight;
102
+ inflight = (async () => {
103
+ let blockedTokens = cached?.blockedTokens ?? [];
104
+ let indexNowKey = cached?.indexNowKey ?? null;
105
+ let redirects = cached?.redirects ?? [];
106
+ let primaryLocale = cached?.primaryLocale ?? null;
107
+ let locales = cached?.locales ?? [];
108
+ try {
109
+ const tasks = [];
110
+ if (enableCrawlers || enableIndexNow || enableLocales) {
111
+ // Crawler block rules, the IndexNow key and the locale set come from the same /site response; one request avoids calling the Delivery API again
112
+ tasks.push(f(`${apiBase}/site`, { headers: { Accept: "application/json" } })
113
+ .then((r) => (r.ok ? r.json() : null))
114
+ .then((data) => {
115
+ if (enableCrawlers && Array.isArray(data?.crawlerRules?.blockedTokens)) {
116
+ blockedTokens = data.crawlerRules.blockedTokens;
117
+ }
118
+ if (enableIndexNow && typeof data?.indexNowKey === "string") {
119
+ indexNowKey = data.indexNowKey;
120
+ }
121
+ if (enableLocales && typeof data?.primaryLocale === "string" && Array.isArray(data.locales)) {
122
+ primaryLocale = data.primaryLocale;
123
+ locales = data.locales.filter((l) => typeof l?.locale === "string").map((l) => ({ locale: l.locale, isPrimary: Boolean(l.isPrimary), pathPrefix: l.pathPrefix ?? null }));
124
+ }
125
+ })
126
+ .catch(() => undefined));
127
+ }
128
+ if (enableRedirects) {
129
+ tasks.push(f(`${apiBase}/redirects`, { headers: { Accept: "application/json" } })
130
+ .then((r) => (r.ok ? r.json() : null))
131
+ .then((page) => {
132
+ if (Array.isArray(page?.data)) {
133
+ redirects = page.data
134
+ .filter((rule) => rule?.sourcePath && rule?.targetUrl)
135
+ .map((rule) => ({ sourcePath: rule.sourcePath, targetUrl: rule.targetUrl, statusCode: rule.statusCode === 302 ? 302 : 301 }));
136
+ }
137
+ })
138
+ .catch(() => undefined));
139
+ }
140
+ await Promise.all(tasks);
141
+ }
142
+ finally {
143
+ inflight = null;
144
+ }
145
+ cached = {
146
+ expiresAt: Date.now() + ttlMs,
147
+ blockedTokens,
148
+ redirects,
149
+ indexNowKey,
150
+ primaryLocale,
151
+ locales,
152
+ };
153
+ return cached;
154
+ })();
155
+ return inflight;
156
+ }
157
+ function reportBotHit(request, pathname, bot, blocked, event) {
158
+ const userAgent = request.headers.get("user-agent") ?? bot.uaToken;
159
+ const url = `${apiBase}/analytics/bot-hit`;
160
+ // Sends the server key and the visitor IP (read only from headers the platform guarantees); without a key it is still sent, the edge blocks it and the report is lost without affecting the request
161
+ const promise = serverKeyRequest({ serverKey: options.serverKey, visitorIp: visitorIpFromRequest(request) }, url)
162
+ .then((viaServerKey) => f(url, {
163
+ method: "POST",
164
+ headers: { "Content-Type": "application/json", ...(viaServerKey?.headers ?? {}) },
165
+ body: JSON.stringify({
166
+ botToken: bot.uaToken,
167
+ path: pathname,
168
+ blocked,
169
+ userAgent,
170
+ }),
171
+ ...(viaServerKey ? { redirect: viaServerKey.redirect } : {}),
172
+ }))
173
+ .catch(() => undefined);
174
+ if (event?.waitUntil) {
175
+ event.waitUntil(promise);
176
+ }
177
+ }
178
+ return {
179
+ async evaluate(request, event) {
180
+ const url = new URL(request.url);
181
+ const pathname = url.pathname || "/";
182
+ const state = await loadState();
183
+ if (enableIndexNow && state.indexNowKey) {
184
+ const match = INDEXNOW_KEY_PATH_RE.exec(pathname);
185
+ if (match && match[1].toLowerCase() === state.indexNowKey.toLowerCase()) {
186
+ return {
187
+ action: "respond",
188
+ status: 200,
189
+ body: state.indexNowKey,
190
+ contentType: "text/plain; charset=utf-8",
191
+ };
192
+ }
193
+ }
194
+ // Locales (multilingual sites): the primary locale code as a prefix redirects 301 to the unprefixed path; per-locale SEO files are answered at the edge
195
+ let locale;
196
+ if (enableLocales && state.primaryLocale && state.locales.length > 1) {
197
+ const resolved = resolveRequestLocale({ pathname, primaryLocale: state.primaryLocale, locales: state.locales });
198
+ if (resolved.redirectTo !== null) {
199
+ return { action: "redirect", status: 301, location: new URL(`${resolved.redirectTo}${url.search}`, url.origin).toString() };
200
+ }
201
+ locale = { ...resolved, primaryLocale: state.primaryLocale };
202
+ if (resolved.prefixed) {
203
+ const file = /^\/([^/]+)$/.exec(resolved.pathname)?.[1];
204
+ const apiPath = file ? LOCALIZED_SEO_FILES[file] : undefined;
205
+ if (apiPath) {
206
+ const target = new URL(`${apiBase}${apiPath}`);
207
+ target.searchParams.set("locale", resolved.locale);
208
+ for (const [key, value] of url.searchParams)
209
+ if (key !== "locale")
210
+ target.searchParams.append(key, value);
211
+ try {
212
+ const res = await f(target.toString(), { headers: { Accept: "*/*" } });
213
+ if (res.ok) {
214
+ return { action: "respond", status: 200, body: await res.text(), contentType: res.headers.get("content-type") ?? "text/plain; charset=utf-8" };
215
+ }
216
+ }
217
+ catch {
218
+ // Origin fetch failed: allow and let the front end handle it (usually a 404)
219
+ }
220
+ }
221
+ }
222
+ }
223
+ // Redirect rules: exact match first, then the longest wildcard prefix (the same matching hosted sites use); on multilingual sites shared rules match the unprefixed path and in-site targets get the same prefix back,
224
+ // while locale-specific rules (a renamed translated slug, a disabled locale, a changed prefix) match the full path and use the target as is
225
+ if (enableRedirects && state.redirects.length > 0) {
226
+ const matchPath = locale ? locale.pathname : pathname;
227
+ const hit = matchLocalizedRedirect(pathname, matchPath, state.redirects);
228
+ if (hit) {
229
+ const statusCode = hit.statusCode === 302 ? 302 : 301;
230
+ if (hit.target.startsWith("/")) {
231
+ const root = !hit.scoped && locale?.prefixed ? localeRootPath(locale.locale, locale.primaryLocale, state.locales) : "";
232
+ const localized = root ? `${root}${hit.target === "/" ? "" : hit.target}` : hit.target;
233
+ // Loop guard: do not redirect when the target is the current page (wildcard "/*" to "/", for example); compared in canonical form (raw and percent-encoded are the same path)
234
+ if (canonicalRedirectPath(localized) !== canonicalRedirectPath(pathname)) {
235
+ return { action: "redirect", status: statusCode, location: new URL(`${localized}${url.search}`, url.origin).toString() };
236
+ }
237
+ }
238
+ else {
239
+ return { action: "redirect", status: statusCode, location: hit.target };
240
+ }
241
+ }
242
+ }
243
+ if (enableCrawlers) {
244
+ const ua = request.headers.get("user-agent") ?? "";
245
+ const bot = classifyEdgeUserAgent(ua);
246
+ if (bot) {
247
+ const blocked = isEdgeBotBlocked(bot, state.blockedTokens);
248
+ reportBotHit(request, pathname, bot, blocked, event);
249
+ if (blocked) {
250
+ return { action: "block", status: 403, botHit: { bot, blocked: true } };
251
+ }
252
+ return { action: "pass", botHit: { bot, blocked: false }, ...(locale ? { locale } : {}) };
253
+ }
254
+ }
255
+ return { action: "pass", ...(locale ? { locale } : {}) };
256
+ },
257
+ async handleRequest(request, event) {
258
+ const decision = await this.evaluate(request, event);
259
+ if (decision.action === "block") {
260
+ return new Response("Forbidden", {
261
+ status: 403,
262
+ headers: { "Content-Type": "text/plain; charset=utf-8" },
263
+ });
264
+ }
265
+ if (decision.action === "redirect") {
266
+ return new Response(null, {
267
+ status: decision.status,
268
+ headers: { Location: decision.location },
269
+ });
270
+ }
271
+ if (decision.action === "respond") {
272
+ return new Response(decision.body, {
273
+ status: decision.status,
274
+ headers: { "Content-Type": decision.contentType },
275
+ });
276
+ }
277
+ return null;
278
+ },
279
+ };
280
+ }
281
+ export const edge = {
282
+ middleware: createKanorioMiddleware,
283
+ classifyUserAgent: classifyEdgeUserAgent,
284
+ isBotBlocked: isEdgeBotBlocked,
285
+ };
286
+ export { resolveRequestLocale } from "./shared/localization/request-locale.js";
287
+ export { matchRedirect, matchLocalizedRedirect } from "./shared/utils/redirect-matching.js";
@@ -0,0 +1,123 @@
1
+ /**
2
+ * Helpers for headless forms: read the form definition, get the bot-protection challenge, request a file upload ticket, submit the response.
3
+ * For developers who build their own form UI, with `useKanorioBotProtection` or a server-side flow.
4
+ *
5
+ * Responses follow the contract shared by the three APIs: success is the object itself, failure is `{ error: { code, message, details? } }`.
6
+ * Here both become `{ ok: true, ... }` or `{ ok: false, error }`, so a form UI does not have to read HTTP statuses.
7
+ */
8
+ import { type ServerKeyOptions } from "./server-key.js";
9
+ import type { TaxIdLookupResponse } from "./shared/business-registry/lookup-wire.js";
10
+ import { resolveVisibleFieldIds } from "./shared/types/forms-logic.js";
11
+ import { type ProtectionChallenge, type ProtectionFields } from "./protection.js";
12
+ /** `GET /forms/{id}/challenge`: the built-in ALTCHA challenge, or the parameters of the third-party widget the site chose */
13
+ export type FormChallengeResponse = ProtectionChallenge;
14
+ /** Protection fields sent with submissions and uploads (`_hp`, `_wp` and `_co` are honeypots, always empty strings) */
15
+ export type FormProtectionFields = ProtectionFields;
16
+ export interface FormUploadTicketRequest {
17
+ fieldId: string;
18
+ fileName: string;
19
+ mimeType: string;
20
+ fileSize: number;
21
+ protection?: FormProtectionFields | Record<string, unknown>;
22
+ }
23
+ export interface FormApiError {
24
+ code: string;
25
+ message: string;
26
+ /** Per-question errors on INVALID_ANSWERS (`details.issues`) */
27
+ issues?: unknown;
28
+ details?: unknown;
29
+ }
30
+ export type FormUploadTicketResponse = {
31
+ ok: true;
32
+ uploadId: string;
33
+ uploadUrl: string;
34
+ headers?: Record<string, string>;
35
+ expiresIn: number;
36
+ } | {
37
+ ok: false;
38
+ error: FormApiError;
39
+ };
40
+ export interface FormSubmitInput {
41
+ answers: Record<string, unknown>;
42
+ protection?: FormProtectionFields | Record<string, unknown>;
43
+ consent?: "checked" | "submit_statement";
44
+ consentTextId?: string;
45
+ locale?: string;
46
+ pagePath?: string;
47
+ /** Where this visit came from (kept on the submission record): UTM and ad-click parameters, external referrer host, landing path. */
48
+ attribution?: {
49
+ utm?: Record<string, string>;
50
+ referrerHost?: string;
51
+ landingPath?: string;
52
+ };
53
+ }
54
+ export type FormSubmitResult = {
55
+ ok: true;
56
+ state?: "closed" | "not_open" | "full";
57
+ } | {
58
+ ok: false;
59
+ error: FormApiError;
60
+ };
61
+ export interface FormsHelpers {
62
+ get(formId: string): Promise<unknown>;
63
+ challenge(formId: string): Promise<FormChallengeResponse>;
64
+ requestUpload(formId: string, input: FormUploadTicketRequest): Promise<FormUploadTicketResponse>;
65
+ /**
66
+ * Look up the public business registry for a `tax_id` question, to prefill the business name.
67
+ * Only works for a tax ID question on a form that is currently open. The result is advisory:
68
+ * `{ ok: false }` and `NOT_FOUND` are normal outcomes and must not block the submission.
69
+ */
70
+ lookupTaxId(formId: string, input: FormTaxIdLookupRequest): Promise<TaxIdLookupResponse>;
71
+ submit(formId: string, input: FormSubmitInput): Promise<FormSubmitResult>;
72
+ }
73
+ export interface FormTaxIdLookupRequest {
74
+ /** Id of the tax_id question. */
75
+ fieldId: string;
76
+ /** ISO 3166-1 alpha-2 country of the tax ID. */
77
+ country: string;
78
+ /** Tax ID type; defaults to the country's first type. */
79
+ type?: string;
80
+ value: string;
81
+ /** Same protection fields as an upload request (from `uploadProtectionFromChallenge`). */
82
+ protection?: FormProtectionFields | Record<string, unknown>;
83
+ }
84
+ /**
85
+ * Builds the protection fields from a challenge: call `challenge()` when the form is shown, and pass the result here on submit.
86
+ * The built-in challenge is solved here (proof of work, about 0.5 to 1 second); when the site uses Turnstile, reCAPTCHA or hCaptcha, render that widget with the challenge's
87
+ * `siteKey` and `action` (Turnstile also has `cData`), then pass its token in as `captchaToken`.
88
+ * `renderedAt` is when the form was shown (milliseconds). Challenges and tokens are single-use: get a new one before every submit.
89
+ */
90
+ export declare function protectionFromChallenge(formId: string, challenge: FormChallengeResponse, renderedAt: number, options?: {
91
+ captchaToken?: string;
92
+ signal?: AbortSignal;
93
+ }): Promise<FormProtectionFields>;
94
+ /**
95
+ * Protection fields for an attachment upload ticket: with the built-in challenge, pass the ones used for submitting (`solved`; the same solution can be reused for uploads);
96
+ * with a third-party provider, use the challenge's `uploadToken` (the widget token is single-use and is kept for the submit).
97
+ */
98
+ export declare function uploadProtectionFromChallenge(formId: string, challenge: FormChallengeResponse, renderedAt: number, solved?: FormProtectionFields): FormProtectionFields | null;
99
+ export interface FormsHelpersOptions extends ServerKeyOptions {
100
+ siteUrl: string;
101
+ fetch?: typeof globalThis.fetch;
102
+ }
103
+ /**
104
+ * Pass `serverKey` (and `visitorIp`) when your **server** submits on behalf of a visitor. The key proves the
105
+ * request comes from your server; it does not replace form protection, so the submission still needs the
106
+ * `protection` fields the visitor's browser obtained.
107
+ */
108
+ export declare function createFormsHelpers(options: FormsHelpersOptions): FormsHelpers;
109
+ /**
110
+ * Which questions to show for the current answers. A question can carry `visibleWhen` (conditions on earlier questions
111
+ * or hidden fields); the server applies the same function on submit, so a question hidden here is never required and
112
+ * its answer is not saved. Pass the raw values the visitor has entered so far, keyed by question id, together with
113
+ * any hidden field values.
114
+ */
115
+ export { resolveVisibleFieldIds as visibleFieldIds, hasVisibilityRules } from "./shared/types/forms-logic.js";
116
+ export type { FormCondition, FormConditionOp, FormVisibleWhen, LogicField as FormLogicField } from "./shared/types/forms-logic.js";
117
+ export declare const forms: {
118
+ client: typeof createFormsHelpers;
119
+ protectionFromChallenge: typeof protectionFromChallenge;
120
+ uploadProtectionFromChallenge: typeof uploadProtectionFromChallenge;
121
+ visibleFieldIds: typeof resolveVisibleFieldIds;
122
+ };
123
+ export type { TaxIdLookupResponse, TaxIdLookupWire, TaxIdLookupUnavailableWire } from "./shared/business-registry/lookup-wire.js";