@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.
- package/LICENSE +21 -0
- package/README.md +66 -2
- package/dist/customer-oauth.d.ts +86 -0
- package/dist/customer-oauth.js +112 -0
- package/dist/customer.d.ts +176 -0
- package/dist/customer.js +125 -0
- package/dist/delivery.d.ts +35 -0
- package/dist/delivery.js +49 -0
- package/dist/edge.d.ts +108 -0
- package/dist/edge.js +287 -0
- package/dist/forms.d.ts +123 -0
- package/dist/forms.js +130 -0
- package/dist/generated/customer.d.ts +3157 -0
- package/dist/generated/delivery.d.ts +2408 -0
- package/dist/generated/management.d.ts +38333 -0
- package/dist/http.d.ts +73 -0
- package/dist/http.js +162 -0
- package/dist/index.d.ts +16 -0
- package/dist/index.js +17 -0
- package/dist/locales.d.ts +80 -0
- package/dist/locales.js +81 -0
- package/dist/management.d.ts +19 -0
- package/dist/management.js +22 -0
- package/dist/paginate.d.ts +18 -0
- package/dist/paginate.js +27 -0
- package/dist/preview.d.ts +40 -0
- package/dist/preview.js +131 -0
- package/dist/protection.d.ts +74 -0
- package/dist/protection.js +68 -0
- package/dist/revalidate.d.ts +84 -0
- package/dist/revalidate.js +143 -0
- package/dist/seo.d.ts +120 -0
- package/dist/seo.js +125 -0
- package/dist/server-key.d.ts +71 -0
- package/dist/server-key.js +103 -0
- package/dist/shared/api/delivery/cache-tags.d.ts +142 -0
- package/dist/shared/api/delivery/cache-tags.js +212 -0
- package/dist/shared/api/server-key.d.ts +90 -0
- package/dist/shared/api/server-key.js +260 -0
- package/dist/shared/business-registry/attribution.d.ts +14 -0
- package/dist/shared/business-registry/attribution.js +28 -0
- package/dist/shared/business-registry/define.d.ts +3 -0
- package/dist/shared/business-registry/define.js +4 -0
- package/dist/shared/business-registry/formats/eu-vat.d.ts +2 -0
- package/dist/shared/business-registry/formats/eu-vat.js +54 -0
- package/dist/shared/business-registry/formats/hk-br.d.ts +5 -0
- package/dist/shared/business-registry/formats/hk-br.js +23 -0
- package/dist/shared/business-registry/formats/jp-trn.d.ts +6 -0
- package/dist/shared/business-registry/formats/jp-trn.js +23 -0
- package/dist/shared/business-registry/formats/kr-brn.d.ts +6 -0
- package/dist/shared/business-registry/formats/kr-brn.js +30 -0
- package/dist/shared/business-registry/formats/my.d.ts +7 -0
- package/dist/shared/business-registry/formats/my.js +32 -0
- package/dist/shared/business-registry/formats/sg-uen.d.ts +1 -0
- package/dist/shared/business-registry/formats/sg-uen.js +21 -0
- package/dist/shared/business-registry/formats/tw-vat.d.ts +10 -0
- package/dist/shared/business-registry/formats/tw-vat.js +32 -0
- package/dist/shared/business-registry/index.d.ts +9 -0
- package/dist/shared/business-registry/index.js +10 -0
- package/dist/shared/business-registry/lookup-wire.d.ts +33 -0
- package/dist/shared/business-registry/lookup-wire.js +8 -0
- package/dist/shared/business-registry/normalize.d.ts +7 -0
- package/dist/shared/business-registry/normalize.js +12 -0
- package/dist/shared/business-registry/registry.d.ts +26 -0
- package/dist/shared/business-registry/registry.js +67 -0
- package/dist/shared/business-registry/types.d.ts +60 -0
- package/dist/shared/business-registry/types.js +10 -0
- package/dist/shared/localization/locale-path.d.ts +38 -0
- package/dist/shared/localization/locale-path.js +76 -0
- package/dist/shared/localization/request-locale.d.ts +42 -0
- package/dist/shared/localization/request-locale.js +61 -0
- package/dist/shared/seo/alternates.d.ts +61 -0
- package/dist/shared/seo/alternates.js +71 -0
- package/dist/shared/types/forms-logic.d.ts +96 -0
- package/dist/shared/types/forms-logic.js +209 -0
- package/dist/shared/types/number-input.d.ts +5 -0
- package/dist/shared/types/number-input.js +16 -0
- package/dist/shared/utils/redirect-matching.d.ts +76 -0
- package/dist/shared/utils/redirect-matching.js +181 -0
- package/dist/tax-id.d.ts +7 -0
- package/dist/tax-id.js +6 -0
- package/dist/typed.d.ts +85 -0
- package/dist/typed.js +28 -0
- package/package.json +86 -3
package/dist/http.d.ts
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The fetch core shared by the three clients: builds the URL, sends headers, parses JSON, turns the error envelope into `KanorioApiError`
|
|
3
|
+
* and reads the Deprecation and Sunset headers (RFC 9745, RFC 8594). No business logic.
|
|
4
|
+
*/
|
|
5
|
+
import { type ServerKeyOptions } from "./server-key.js";
|
|
6
|
+
export declare const KANORIO_SDK_VERSION = "1.1.0";
|
|
7
|
+
export declare const SDK_VERSION_HEADER = "x-kanorio-sdk-version";
|
|
8
|
+
export interface ErrorEnvelope {
|
|
9
|
+
error: {
|
|
10
|
+
code: string;
|
|
11
|
+
message: string;
|
|
12
|
+
details?: unknown;
|
|
13
|
+
};
|
|
14
|
+
}
|
|
15
|
+
export declare function isErrorEnvelope(value: unknown): value is ErrorEnvelope;
|
|
16
|
+
export declare class KanorioApiError extends Error {
|
|
17
|
+
readonly code: string;
|
|
18
|
+
readonly status: number;
|
|
19
|
+
readonly details?: unknown | undefined;
|
|
20
|
+
/** Suggested wait in seconds on 429 and 503 (the `Retry-After` header or `details.retryAfter`) */
|
|
21
|
+
readonly retryAfter?: number | undefined;
|
|
22
|
+
/** Release time attached to an access decision (`details.availableAt` of `NOT_RELEASED`) */
|
|
23
|
+
readonly availableAt?: string | undefined;
|
|
24
|
+
constructor(code: string, status: number, message: string, details?: unknown | undefined,
|
|
25
|
+
/** Suggested wait in seconds on 429 and 503 (the `Retry-After` header or `details.retryAfter`) */
|
|
26
|
+
retryAfter?: number | undefined,
|
|
27
|
+
/** Release time attached to an access decision (`details.availableAt` of `NOT_RELEASED`) */
|
|
28
|
+
availableAt?: string | undefined);
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* The request never reached the API: Kanorio's edge answered with a challenge page (HTTP 403, HTML).
|
|
32
|
+
* On a server this means the write needs a server key; `message` says exactly what to do.
|
|
33
|
+
*/
|
|
34
|
+
export declare class KanorioEdgeChallengeError extends KanorioApiError {
|
|
35
|
+
constructor(message: string);
|
|
36
|
+
}
|
|
37
|
+
export declare function toApiError(status: number, body: unknown, headers: Headers): KanorioApiError;
|
|
38
|
+
export interface DeprecationNotice {
|
|
39
|
+
method: string;
|
|
40
|
+
path: string;
|
|
41
|
+
sunset: string | null;
|
|
42
|
+
successor: string | null;
|
|
43
|
+
policy: string | null;
|
|
44
|
+
}
|
|
45
|
+
export declare function parseDeprecation(headers: Headers, method: string, path: string): DeprecationNotice | null;
|
|
46
|
+
export type QueryValue = string | number | boolean | null | undefined;
|
|
47
|
+
export type Query = Record<string, QueryValue | QueryValue[]>;
|
|
48
|
+
export declare function buildUrl(baseUrl: string, path: string, query?: Query): string;
|
|
49
|
+
export interface HttpClientOptions extends ServerKeyOptions {
|
|
50
|
+
baseUrl: string;
|
|
51
|
+
/** Uses the global `fetch` when omitted */
|
|
52
|
+
fetch?: typeof fetch;
|
|
53
|
+
/** Headers added to every request (may be a function, for dynamic tokens) */
|
|
54
|
+
headers?: HeadersInit | (() => HeadersInit | Promise<HeadersInit>);
|
|
55
|
+
/** Timeout in milliseconds; none when omitted */
|
|
56
|
+
timeoutMs?: number;
|
|
57
|
+
/** Called when the server announces a deprecation (`console.warn` once by default) */
|
|
58
|
+
onDeprecation?: (notice: DeprecationNotice) => void;
|
|
59
|
+
/** User agent string (Node); ignored in browsers */
|
|
60
|
+
userAgent?: string;
|
|
61
|
+
}
|
|
62
|
+
export interface RequestOptions {
|
|
63
|
+
query?: Query;
|
|
64
|
+
body?: unknown;
|
|
65
|
+
headers?: HeadersInit;
|
|
66
|
+
signal?: AbortSignal;
|
|
67
|
+
}
|
|
68
|
+
export interface HttpClient {
|
|
69
|
+
request<T>(method: string, path: string, options?: RequestOptions): Promise<T>;
|
|
70
|
+
/** The full response (headers and status), without throwing */
|
|
71
|
+
raw(method: string, path: string, options?: RequestOptions): Promise<Response>;
|
|
72
|
+
}
|
|
73
|
+
export declare function createHttpClient(options: HttpClientOptions): HttpClient;
|
package/dist/http.js
ADDED
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The fetch core shared by the three clients: builds the URL, sends headers, parses JSON, turns the error envelope into `KanorioApiError`
|
|
3
|
+
* and reads the Deprecation and Sunset headers (RFC 9745, RFC 8594). No business logic.
|
|
4
|
+
*/
|
|
5
|
+
import { EDGE_CHALLENGE_CODE, edgeChallengeMessage, isEdgeChallenge, serverKeyRequest } from "./server-key.js";
|
|
6
|
+
export const KANORIO_SDK_VERSION = "1.1.0";
|
|
7
|
+
export const SDK_VERSION_HEADER = "x-kanorio-sdk-version";
|
|
8
|
+
export function isErrorEnvelope(value) {
|
|
9
|
+
if (typeof value !== "object" || value === null)
|
|
10
|
+
return false;
|
|
11
|
+
const error = value.error;
|
|
12
|
+
if (typeof error !== "object" || error === null)
|
|
13
|
+
return false;
|
|
14
|
+
const { code, message } = error;
|
|
15
|
+
return typeof code === "string" && typeof message === "string";
|
|
16
|
+
}
|
|
17
|
+
export class KanorioApiError extends Error {
|
|
18
|
+
code;
|
|
19
|
+
status;
|
|
20
|
+
details;
|
|
21
|
+
retryAfter;
|
|
22
|
+
availableAt;
|
|
23
|
+
constructor(code, status, message, details,
|
|
24
|
+
/** Suggested wait in seconds on 429 and 503 (the `Retry-After` header or `details.retryAfter`) */
|
|
25
|
+
retryAfter,
|
|
26
|
+
/** Release time attached to an access decision (`details.availableAt` of `NOT_RELEASED`) */
|
|
27
|
+
availableAt) {
|
|
28
|
+
super(message);
|
|
29
|
+
this.code = code;
|
|
30
|
+
this.status = status;
|
|
31
|
+
this.details = details;
|
|
32
|
+
this.retryAfter = retryAfter;
|
|
33
|
+
this.availableAt = availableAt;
|
|
34
|
+
this.name = "KanorioApiError";
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* The request never reached the API: Kanorio's edge answered with a challenge page (HTTP 403, HTML).
|
|
39
|
+
* On a server this means the write needs a server key; `message` says exactly what to do.
|
|
40
|
+
*/
|
|
41
|
+
export class KanorioEdgeChallengeError extends KanorioApiError {
|
|
42
|
+
constructor(message) {
|
|
43
|
+
super(EDGE_CHALLENGE_CODE, 403, message);
|
|
44
|
+
this.name = "KanorioEdgeChallengeError";
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
export function toApiError(status, body, headers) {
|
|
48
|
+
const retryHeader = headers.get("retry-after");
|
|
49
|
+
const retryAfter = retryHeader ? Number.parseInt(retryHeader, 10) : undefined;
|
|
50
|
+
if (isErrorEnvelope(body)) {
|
|
51
|
+
// The three APIs share one error envelope: extra fields are in details
|
|
52
|
+
const details = body.error.details;
|
|
53
|
+
const detailRetry = typeof details?.retryAfter === "number" ? details.retryAfter : undefined;
|
|
54
|
+
const availableAt = typeof details?.availableAt === "string" ? details.availableAt : undefined;
|
|
55
|
+
return new KanorioApiError(body.error.code, status, body.error.message, body.error.details, retryAfter ?? detailRetry, availableAt);
|
|
56
|
+
}
|
|
57
|
+
const code = status === 401 ? "UNAUTHENTICATED" : status === 404 ? "NOT_FOUND" : status === 429 ? "RATE_LIMITED" : status >= 500 ? "UPSTREAM_ERROR" : "HTTP_ERROR";
|
|
58
|
+
const text = typeof body === "string" ? body.slice(0, 200) : "";
|
|
59
|
+
return new KanorioApiError(code, status, text || `Request failed with HTTP ${status}.`, undefined, retryAfter);
|
|
60
|
+
}
|
|
61
|
+
export function parseDeprecation(headers, method, path) {
|
|
62
|
+
if (!headers.has("deprecation"))
|
|
63
|
+
return null;
|
|
64
|
+
const link = headers.get("link") ?? "";
|
|
65
|
+
const rel = (name) => {
|
|
66
|
+
const match = link.match(new RegExp(`<([^>]+)>;\\s*rel="${name}"`));
|
|
67
|
+
return match?.[1] ?? null;
|
|
68
|
+
};
|
|
69
|
+
return { method, path, sunset: headers.get("sunset"), successor: rel("successor-version"), policy: rel("deprecation") };
|
|
70
|
+
}
|
|
71
|
+
export function buildUrl(baseUrl, path, query) {
|
|
72
|
+
const url = new URL(path.replace(/^\//, ""), baseUrl.endsWith("/") ? baseUrl : `${baseUrl}/`);
|
|
73
|
+
if (query) {
|
|
74
|
+
for (const [key, raw] of Object.entries(query)) {
|
|
75
|
+
const values = Array.isArray(raw) ? raw : [raw];
|
|
76
|
+
for (const v of values) {
|
|
77
|
+
if (v === undefined || v === null)
|
|
78
|
+
continue;
|
|
79
|
+
url.searchParams.append(key, String(v));
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
return url.toString();
|
|
84
|
+
}
|
|
85
|
+
export function createHttpClient(options) {
|
|
86
|
+
const fetchImpl = options.fetch ?? globalThis.fetch;
|
|
87
|
+
if (!fetchImpl)
|
|
88
|
+
throw new Error("@kanorio/sdk: global fetch is not available; pass `fetch` in options.");
|
|
89
|
+
const warned = new Set();
|
|
90
|
+
const onDeprecation = options.onDeprecation ??
|
|
91
|
+
((notice) => {
|
|
92
|
+
const key = `${notice.method} ${notice.path}`;
|
|
93
|
+
if (warned.has(key))
|
|
94
|
+
return;
|
|
95
|
+
warned.add(key);
|
|
96
|
+
console.warn(`[kanorio] ${key} is deprecated${notice.sunset ? ` (sunset ${notice.sunset})` : ""}${notice.successor ? `; use ${notice.successor}` : ""}.`);
|
|
97
|
+
});
|
|
98
|
+
async function raw(method, path, req = {}) {
|
|
99
|
+
const headers = new Headers(typeof options.headers === "function" ? await options.headers() : options.headers);
|
|
100
|
+
new Headers(req.headers).forEach((v, k) => headers.set(k, v));
|
|
101
|
+
headers.set("accept", "application/json");
|
|
102
|
+
if (typeof document === "undefined") {
|
|
103
|
+
headers.set(SDK_VERSION_HEADER, KANORIO_SDK_VERSION);
|
|
104
|
+
if (options.userAgent)
|
|
105
|
+
headers.set("user-agent", options.userAgent);
|
|
106
|
+
}
|
|
107
|
+
let body;
|
|
108
|
+
if (req.body !== undefined) {
|
|
109
|
+
headers.set("content-type", "application/json");
|
|
110
|
+
body = JSON.stringify(req.body);
|
|
111
|
+
}
|
|
112
|
+
const url = buildUrl(options.baseUrl, path, req.query);
|
|
113
|
+
// Server key: server side only, https only, redirects not followed (custom headers are not stripped on cross-origin redirects)
|
|
114
|
+
const viaServerKey = await serverKeyRequest(options, url);
|
|
115
|
+
if (viaServerKey)
|
|
116
|
+
for (const [name, value] of Object.entries(viaServerKey.headers))
|
|
117
|
+
headers.set(name, value);
|
|
118
|
+
const controller = options.timeoutMs ? new AbortController() : null;
|
|
119
|
+
const timer = controller ? setTimeout(() => controller.abort(), options.timeoutMs) : null;
|
|
120
|
+
if (controller && req.signal)
|
|
121
|
+
req.signal.addEventListener("abort", () => controller.abort(), { once: true });
|
|
122
|
+
try {
|
|
123
|
+
return await fetchImpl(url, {
|
|
124
|
+
method,
|
|
125
|
+
headers,
|
|
126
|
+
body,
|
|
127
|
+
signal: controller?.signal ?? req.signal,
|
|
128
|
+
...(viaServerKey ? { redirect: viaServerKey.redirect } : {}),
|
|
129
|
+
});
|
|
130
|
+
}
|
|
131
|
+
finally {
|
|
132
|
+
if (timer)
|
|
133
|
+
clearTimeout(timer);
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
async function request(method, path, req = {}) {
|
|
137
|
+
const res = await raw(method, path, req);
|
|
138
|
+
// The edge's challenge page is not an API response: return an error that says what to do next instead of "HTTP 403" and a block of HTML
|
|
139
|
+
if (isEdgeChallenge(res))
|
|
140
|
+
throw new KanorioEdgeChallengeError(edgeChallengeMessage(Boolean(options.serverKey)));
|
|
141
|
+
const notice = parseDeprecation(res.headers, method, path);
|
|
142
|
+
if (notice)
|
|
143
|
+
onDeprecation(notice);
|
|
144
|
+
const text = await res.text();
|
|
145
|
+
let parsed = text;
|
|
146
|
+
if (text) {
|
|
147
|
+
try {
|
|
148
|
+
parsed = JSON.parse(text);
|
|
149
|
+
}
|
|
150
|
+
catch {
|
|
151
|
+
parsed = text;
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
else {
|
|
155
|
+
parsed = undefined;
|
|
156
|
+
}
|
|
157
|
+
if (!res.ok)
|
|
158
|
+
throw toApiError(res.status, parsed, res.headers);
|
|
159
|
+
return parsed;
|
|
160
|
+
}
|
|
161
|
+
return { request, raw };
|
|
162
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
export { KanorioApiError, KanorioEdgeChallengeError, KANORIO_SDK_VERSION, SDK_VERSION_HEADER, type DeprecationNotice, type HttpClientOptions, type HttpClient, } from "./http.js";
|
|
2
|
+
export { visitorIpFromRequest, SERVER_KEY_HEADER, SERVER_KEY_VISITOR_IP_HEADER, EDGE_CHALLENGE_CODE, type ServerKeyOptions, type VisitorIpSource, type VisitorIpOptions, } from "./server-key.js";
|
|
3
|
+
export type { TypedClient, TypedRequest, SuccessResponseOf } from "./typed.js";
|
|
4
|
+
export { paginate, listAll, type ListPage } from "./paginate.js";
|
|
5
|
+
export { createManagementClient, DEFAULT_MANAGEMENT_BASE_URL, type ManagementClient, type ManagementClientOptions, type ManagementPaths, } from "./management.js";
|
|
6
|
+
export { createDeliveryClient, deliveryBaseUrl, parseDeliveryCacheTags, frameworkCacheTags, DELIVERY_CACHE_TAGS_HEADER, DELIVERY_PREVIEW_HEADER, type DeliveryClient, type DeliveryClientOptions, type DeliveryPaths, } from "./delivery.js";
|
|
7
|
+
export { createCustomerClient, createCustomerContentClient, customerBaseUrl, readStoredCustomerToken, writeStoredCustomerToken, CUSTOMER_TOKEN_STORAGE_KEY, type CustomerClient, type CustomerClientOptions, type CustomerContentClientLike, type CustomerPaths, type CustomerTokenSource, } from "./customer.js";
|
|
8
|
+
export { buildHostedLoginUrl, completeHostedCustomerLogin, createPkcePair, exchangeHostedLoginCode, refreshCustomerToken, revokeCustomerToken, startHostedCustomerLogin, type CompleteHostedLoginOptions, type HostedLoginGrant, type HostedLoginUrlParams, type StartHostedLoginOptions, } from "./customer-oauth.js";
|
|
9
|
+
export { seo, seoRewrites, fetchDeliveryJsonLd, fetchSitemapEntries, createSeoHelpers, listingRobots, type ListingKey, type ListingState, type SeoRewriteFramework, type NextSeoRewriteRule, type SeoRewritesOptions, type DeliveryJsonLdResult, type SitemapEntry, type SitemapEntriesResult, type SeoHelpers, } from "./seo.js";
|
|
10
|
+
export { cacheTag, localizeCacheTag, localizeCacheTags, prefixCacheTags, responseCacheTags, eventCacheTags, DEFAULT_CACHE_TAG_PREFIX, CACHE_TAG_LOCALE_SEPARATOR, DELIVERY_CACHE_TAG_LIMIT, type TranslationCacheScope, } from "./shared/api/delivery/cache-tags.js";
|
|
11
|
+
export { locales, buildAlternates, requestLocaleOf, localizedPath, languageSwitcher, resolveRequestLocale, withLocalePrefix, localeRootPath, localePrefixMap, localePrefixOf, localeOfPrefix, hreflangOf, buildSiteAlternates, sitemapAlternates, type BuildAlternatesOptions, type PageAlternates, type HreflangLink, type SiteLocaleMeta, type LocaleRoute, type RequestLocaleResult, type SiteAlternates, } from "./locales.js";
|
|
12
|
+
export { revalidate, createRevalidateHandler, verifyWebhookSignature, computeWebhookSignature, buildWebhookSignatureHeader, parseWebhookSignatureHeader, extractWebhookCacheTags, WEBHOOK_SIGNATURE_HEADER, WEBHOOK_DELIVERY_HEADER, WEBHOOK_EVENT_HEADER, DEFAULT_WEBHOOK_TOLERANCE_SECONDS, type VerifyWebhookSignatureOptions, type ParsedWebhookSignature, type WebhookEnvelope, type RevalidateHandlerOptions, } from "./revalidate.js";
|
|
13
|
+
export { forms, createFormsHelpers, protectionFromChallenge, uploadProtectionFromChallenge, type FormApiError, type FormProtectionFields, type FormChallengeResponse, type FormUploadTicketRequest, type FormUploadTicketResponse, type FormSubmitInput, type FormSubmitResult, type FormsHelpers, } from "./forms.js";
|
|
14
|
+
export { edge, createKanorioMiddleware, classifyEdgeUserAgent, isEdgeBotBlocked, EDGE_BOT_LIST, CRAWLER_LIST_VERSION, type EdgeBotInfo, type RedirectRule, type KanorioMiddlewareOptions, type MiddlewareDecision, type KanorioMiddleware, } from "./edge.js";
|
|
15
|
+
export { preview, previewHeaders, tokenFromCookieHeader, isValidPreviewTokenFormat, sanitizePreviewRedirectPath, createPreviewRouteHandler, PREVIEW_TOKEN_PREFIX, PREVIEW_COOKIE_NAME, type PreviewRouteHandlerOptions, } from "./preview.js";
|
|
16
|
+
export { protectionFromChallenge as solveProtectionChallenge, solveAltchaChallenge, type AltchaChallenge, type ProtectionChallenge, type ProtectionFields, type ProtectionProvider, } from "./protection.js";
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
export { KanorioApiError, KanorioEdgeChallengeError, KANORIO_SDK_VERSION, SDK_VERSION_HEADER, } from "./http.js";
|
|
2
|
+
export { visitorIpFromRequest, SERVER_KEY_HEADER, SERVER_KEY_VISITOR_IP_HEADER, EDGE_CHALLENGE_CODE, } from "./server-key.js";
|
|
3
|
+
export { paginate, listAll } from "./paginate.js";
|
|
4
|
+
export { createManagementClient, DEFAULT_MANAGEMENT_BASE_URL, } from "./management.js";
|
|
5
|
+
export { createDeliveryClient, deliveryBaseUrl, parseDeliveryCacheTags, frameworkCacheTags, DELIVERY_CACHE_TAGS_HEADER, DELIVERY_PREVIEW_HEADER, } from "./delivery.js";
|
|
6
|
+
export { createCustomerClient, createCustomerContentClient, customerBaseUrl, readStoredCustomerToken, writeStoredCustomerToken, CUSTOMER_TOKEN_STORAGE_KEY, } from "./customer.js";
|
|
7
|
+
export { buildHostedLoginUrl, completeHostedCustomerLogin, createPkcePair, exchangeHostedLoginCode, refreshCustomerToken, revokeCustomerToken, startHostedCustomerLogin, } from "./customer-oauth.js";
|
|
8
|
+
export { seo, seoRewrites, fetchDeliveryJsonLd, fetchSitemapEntries, createSeoHelpers, listingRobots, } from "./seo.js";
|
|
9
|
+
export { cacheTag, localizeCacheTag, localizeCacheTags, prefixCacheTags, responseCacheTags, eventCacheTags, DEFAULT_CACHE_TAG_PREFIX, CACHE_TAG_LOCALE_SEPARATOR, DELIVERY_CACHE_TAG_LIMIT, } from "./shared/api/delivery/cache-tags.js";
|
|
10
|
+
export { locales, buildAlternates, requestLocaleOf, localizedPath, languageSwitcher, resolveRequestLocale, withLocalePrefix, localeRootPath, localePrefixMap, localePrefixOf, localeOfPrefix, hreflangOf, buildSiteAlternates, sitemapAlternates, } from "./locales.js";
|
|
11
|
+
export { revalidate, createRevalidateHandler, verifyWebhookSignature, computeWebhookSignature, buildWebhookSignatureHeader, parseWebhookSignatureHeader, extractWebhookCacheTags, WEBHOOK_SIGNATURE_HEADER, WEBHOOK_DELIVERY_HEADER, WEBHOOK_EVENT_HEADER, DEFAULT_WEBHOOK_TOLERANCE_SECONDS, } from "./revalidate.js";
|
|
12
|
+
export { forms, createFormsHelpers, protectionFromChallenge, uploadProtectionFromChallenge, } from "./forms.js";
|
|
13
|
+
export { edge, createKanorioMiddleware, classifyEdgeUserAgent, isEdgeBotBlocked, EDGE_BOT_LIST, CRAWLER_LIST_VERSION, } from "./edge.js";
|
|
14
|
+
export { preview, previewHeaders, tokenFromCookieHeader, isValidPreviewTokenFormat, sanitizePreviewRedirectPath, createPreviewRouteHandler, PREVIEW_TOKEN_PREFIX, PREVIEW_COOKIE_NAME, } from "./preview.js";
|
|
15
|
+
// Bot protection (shared by forms and customer sign-in): for forms, `protectionFromChallenge(formId, challenge, renderedAt)` is above;
|
|
16
|
+
// for sign-in (`GET /customer/auth/protection`), use `solveProtectionChallenge(challenge, { context, renderedAt })`
|
|
17
|
+
export { protectionFromChallenge as solveProtectionChallenge, solveAltchaChallenge, } from "./protection.js";
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Locale routing and hreflang for multilingual sites (the same behavior as hosted sites).
|
|
3
|
+
*
|
|
4
|
+
* The same pure functions Kanorio's hosted sites use (`src/shared/**` is copied from Kanorio's shared code by `pnpm --filter @kanorio/sdk gen`):
|
|
5
|
+
* - The primary locale has no prefix (`/about`) and secondary locales use a subdirectory (`/en/about`); the prefix is the `pathPrefix` the owner saved (`locales[]` in `GET /api/v1/site`)
|
|
6
|
+
* - `resolveRequestLocale` reads the first path segment; the primary locale code used as a prefix (`/zh-hant/about`) must redirect 301 to the unprefixed path
|
|
7
|
+
* - `buildAlternates` works out canonical and hreflang: each locale version is self-canonical, only locales with a translation of this page are listed, and x-default points to the primary locale;
|
|
8
|
+
* an untranslated fallback page's canonical points to the primary locale URL and it emits no hreflang
|
|
9
|
+
*/
|
|
10
|
+
import { type LocaleRoute } from "./shared/localization/locale-path.js";
|
|
11
|
+
import { type RequestLocaleResult } from "./shared/localization/request-locale.js";
|
|
12
|
+
import { hreflangEntries, type SiteAlternates } from "./shared/seo/alternates.js";
|
|
13
|
+
export { localeOfPrefix, localePrefixMap, localePrefixOf, languageOfLocale, type LocaleRoute } from "./shared/localization/locale-path.js";
|
|
14
|
+
export { resolveRequestLocale, withLocalePrefix, localeRootPath, type RequestLocaleInput, type RequestLocaleResult } from "./shared/localization/request-locale.js";
|
|
15
|
+
export { buildSiteAlternates, hreflangEntries, hreflangOf, localizedSiteUrl, sitemapAlternates, type SiteAlternates, type SiteAlternatesInput, type LocalePrefixes } from "./shared/seo/alternates.js";
|
|
16
|
+
/** The locale-related fields of the `GET /api/v1/site` response */
|
|
17
|
+
export interface SiteLocaleMeta {
|
|
18
|
+
primaryLocale?: string | null;
|
|
19
|
+
locales?: readonly LocaleRoute[] | null;
|
|
20
|
+
}
|
|
21
|
+
export interface BuildAlternatesOptions {
|
|
22
|
+
/** The external front end's public URL, without a trailing slash (`https://www.example.com`) */
|
|
23
|
+
siteUrl: string;
|
|
24
|
+
/** The `GET /api/v1/site` response (`primaryLocale`, `locales[]`) */
|
|
25
|
+
site: SiteLocaleMeta;
|
|
26
|
+
/** Path in the primary locale's space (no prefix): `/about`, `/blog/hello`, the home page `/` */
|
|
27
|
+
path: string;
|
|
28
|
+
/** The locale in the URL (`locale` from `resolveRequestLocale`); omit for the primary locale */
|
|
29
|
+
requestLocale?: string | null;
|
|
30
|
+
/** The locale the content was actually served in (`resolvedLocale` of the Delivery response); omit to use `requestLocale` */
|
|
31
|
+
resolvedLocale?: string | null;
|
|
32
|
+
/** Secondary locales with a published translation of this page (`availableLocales` of the Delivery response); `"all"` means every live locale has one (list pages) */
|
|
33
|
+
availableLocales?: readonly string[] | "all" | null;
|
|
34
|
+
/**
|
|
35
|
+
* This page's path in every live locale (no prefix; `localePaths` of the Delivery response). Each locale can have its own translated slug:
|
|
36
|
+
* when given, it is used to build each locale's URL; otherwise every locale uses `path`
|
|
37
|
+
*/
|
|
38
|
+
localePaths?: Readonly<Record<string, string>> | null;
|
|
39
|
+
}
|
|
40
|
+
export interface HreflangLink {
|
|
41
|
+
rel: "alternate";
|
|
42
|
+
hreflang: string;
|
|
43
|
+
href: string;
|
|
44
|
+
}
|
|
45
|
+
export interface PageAlternates extends SiteAlternates {
|
|
46
|
+
/** `<link rel="alternate" hreflang="..." href="...">`; empty for fallback pages and single-language sites */
|
|
47
|
+
links: HreflangLink[];
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* A page's canonical and hreflang (`canonical` and `languages` fit Next.js `metadata.alternates` directly).
|
|
51
|
+
* Single-language sites get only canonical; a fallback page (a secondary locale was requested but the page has no translation) points canonical to the primary locale URL and emits no hreflang.
|
|
52
|
+
*/
|
|
53
|
+
export declare function buildAlternates(options: BuildAlternatesOptions): PageAlternates;
|
|
54
|
+
/** The request locale for an external front end: the prefix is read from the first path segment; always the primary locale when `site` has no locale data (single-language sites) */
|
|
55
|
+
export declare function requestLocaleOf(pathname: string, site: SiteLocaleMeta): RequestLocaleResult;
|
|
56
|
+
/** This page's path in a locale (the primary locale has no prefix); for a language switcher */
|
|
57
|
+
export declare function localizedPath(pathname: string, locale: string, site: SiteLocaleMeta): string;
|
|
58
|
+
/**
|
|
59
|
+
* Language switcher: this page's URL in every live locale (primary first, then in `locales[]` order).
|
|
60
|
+
* With `localePaths` (from the Delivery response), each locale uses its own path (translated slugs); otherwise `path` is placed under each locale's prefix.
|
|
61
|
+
*/
|
|
62
|
+
export declare function languageSwitcher(options: {
|
|
63
|
+
siteUrl: string;
|
|
64
|
+
site: SiteLocaleMeta;
|
|
65
|
+
path: string;
|
|
66
|
+
localePaths?: Readonly<Record<string, string>> | null;
|
|
67
|
+
}): Array<{
|
|
68
|
+
locale: string;
|
|
69
|
+
hreflang: string;
|
|
70
|
+
href: string;
|
|
71
|
+
isPrimary: boolean;
|
|
72
|
+
pathPrefix: string | null;
|
|
73
|
+
}>;
|
|
74
|
+
export { hreflangEntries as hreflangEntriesOf };
|
|
75
|
+
export declare const locales: {
|
|
76
|
+
readonly resolve: typeof requestLocaleOf;
|
|
77
|
+
readonly path: typeof localizedPath;
|
|
78
|
+
readonly alternates: typeof buildAlternates;
|
|
79
|
+
readonly switcher: typeof languageSwitcher;
|
|
80
|
+
};
|
package/dist/locales.js
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Locale routing and hreflang for multilingual sites (the same behavior as hosted sites).
|
|
3
|
+
*
|
|
4
|
+
* The same pure functions Kanorio's hosted sites use (`src/shared/**` is copied from Kanorio's shared code by `pnpm --filter @kanorio/sdk gen`):
|
|
5
|
+
* - The primary locale has no prefix (`/about`) and secondary locales use a subdirectory (`/en/about`); the prefix is the `pathPrefix` the owner saved (`locales[]` in `GET /api/v1/site`)
|
|
6
|
+
* - `resolveRequestLocale` reads the first path segment; the primary locale code used as a prefix (`/zh-hant/about`) must redirect 301 to the unprefixed path
|
|
7
|
+
* - `buildAlternates` works out canonical and hreflang: each locale version is self-canonical, only locales with a translation of this page are listed, and x-default points to the primary locale;
|
|
8
|
+
* an untranslated fallback page's canonical points to the primary locale URL and it emits no hreflang
|
|
9
|
+
*/
|
|
10
|
+
import { localePrefixMap, localePrefixOf } from "./shared/localization/locale-path.js";
|
|
11
|
+
import { resolveRequestLocale, withLocalePrefix } from "./shared/localization/request-locale.js";
|
|
12
|
+
import { buildSiteAlternates, hreflangEntries, hreflangOf } from "./shared/seo/alternates.js";
|
|
13
|
+
export { localeOfPrefix, localePrefixMap, localePrefixOf, languageOfLocale } from "./shared/localization/locale-path.js";
|
|
14
|
+
export { resolveRequestLocale, withLocalePrefix, localeRootPath } from "./shared/localization/request-locale.js";
|
|
15
|
+
export { buildSiteAlternates, hreflangEntries, hreflangOf, localizedSiteUrl, sitemapAlternates } from "./shared/seo/alternates.js";
|
|
16
|
+
/**
|
|
17
|
+
* A page's canonical and hreflang (`canonical` and `languages` fit Next.js `metadata.alternates` directly).
|
|
18
|
+
* Single-language sites get only canonical; a fallback page (a secondary locale was requested but the page has no translation) points canonical to the primary locale URL and emits no hreflang.
|
|
19
|
+
*/
|
|
20
|
+
export function buildAlternates(options) {
|
|
21
|
+
const primaryLocale = options.site.primaryLocale ?? null;
|
|
22
|
+
const routes = options.site.locales ?? [];
|
|
23
|
+
const siteUrl = options.siteUrl.replace(/\/+$/, "");
|
|
24
|
+
const path = options.path.startsWith("/") ? options.path : `/${options.path}`;
|
|
25
|
+
if (!primaryLocale || routes.length < 2) {
|
|
26
|
+
return { canonical: `${siteUrl}${path === "/" ? "" : path}`, languages: {}, links: [] };
|
|
27
|
+
}
|
|
28
|
+
const requestLocale = options.requestLocale ?? primaryLocale;
|
|
29
|
+
const resolvedLocale = options.resolvedLocale ?? requestLocale;
|
|
30
|
+
const secondary = routes.filter((r) => !r.isPrimary && r.locale !== primaryLocale).map((r) => r.locale);
|
|
31
|
+
const availableLocales = options.availableLocales === "all" ? secondary : (options.availableLocales ?? []);
|
|
32
|
+
const alternates = buildSiteAlternates({
|
|
33
|
+
siteUrl,
|
|
34
|
+
path,
|
|
35
|
+
primaryLocale,
|
|
36
|
+
requestLocale,
|
|
37
|
+
resolvedLocale,
|
|
38
|
+
availableLocales,
|
|
39
|
+
localePrefixes: localePrefixMap(routes, primaryLocale),
|
|
40
|
+
localizedPaths: options.localePaths ?? null,
|
|
41
|
+
});
|
|
42
|
+
const links = Object.entries(alternates.languages).map(([hreflang, href]) => ({ rel: "alternate", hreflang, href }));
|
|
43
|
+
return { ...alternates, links };
|
|
44
|
+
}
|
|
45
|
+
/** The request locale for an external front end: the prefix is read from the first path segment; always the primary locale when `site` has no locale data (single-language sites) */
|
|
46
|
+
export function requestLocaleOf(pathname, site) {
|
|
47
|
+
const primaryLocale = site.primaryLocale ?? "";
|
|
48
|
+
const routes = site.locales ?? [];
|
|
49
|
+
if (!primaryLocale || routes.length === 0)
|
|
50
|
+
return { locale: primaryLocale, pathname: pathname || "/", prefixed: false, redirectTo: null };
|
|
51
|
+
return resolveRequestLocale({ pathname, primaryLocale, locales: routes });
|
|
52
|
+
}
|
|
53
|
+
/** This page's path in a locale (the primary locale has no prefix); for a language switcher */
|
|
54
|
+
export function localizedPath(pathname, locale, site) {
|
|
55
|
+
const primaryLocale = site.primaryLocale ?? locale;
|
|
56
|
+
return withLocalePrefix(pathname, locale, primaryLocale, site.locales ?? []);
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Language switcher: this page's URL in every live locale (primary first, then in `locales[]` order).
|
|
60
|
+
* With `localePaths` (from the Delivery response), each locale uses its own path (translated slugs); otherwise `path` is placed under each locale's prefix.
|
|
61
|
+
*/
|
|
62
|
+
export function languageSwitcher(options) {
|
|
63
|
+
const primaryLocale = options.site.primaryLocale ?? null;
|
|
64
|
+
const routes = options.site.locales ?? [];
|
|
65
|
+
if (!primaryLocale)
|
|
66
|
+
return [];
|
|
67
|
+
const siteUrl = options.siteUrl.replace(/\/+$/, "");
|
|
68
|
+
const ordered = [...routes].sort((a, b) => Number(Boolean(b.isPrimary)) - Number(Boolean(a.isPrimary)));
|
|
69
|
+
return ordered.map((route) => {
|
|
70
|
+
const prefix = localePrefixOf(route.locale, routes, primaryLocale);
|
|
71
|
+
const path = withLocalePrefix(options.localePaths?.[route.locale] ?? options.path, route.locale, primaryLocale, routes);
|
|
72
|
+
return { locale: route.locale, hreflang: hreflangOf(route.locale), href: `${siteUrl}${path === "/" ? "" : path}`, isPrimary: route.locale === primaryLocale, pathPrefix: prefix };
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
export { hreflangEntries as hreflangEntriesOf };
|
|
76
|
+
export const locales = {
|
|
77
|
+
resolve: requestLocaleOf,
|
|
78
|
+
path: localizedPath,
|
|
79
|
+
alternates: buildAlternates,
|
|
80
|
+
switcher: languageSwitcher,
|
|
81
|
+
};
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Management API (`https://app.kanorio.com/api/v1`, Bearer = a personal access token `knr_pat_` or a service account token `knr_sa_`; an OAuth access token `knr_at_` works when it was issued for the Management API, as `kanorio login` does).
|
|
3
|
+
* MCP (`https://app.kanorio.com/api/mcp`) is another way to reach the same API and shares the same operation registry.
|
|
4
|
+
* Types are generated by openapi-typescript from the Management API's OpenAPI document (a snapshot of `GET /api/v1/openapi.json`).
|
|
5
|
+
*/
|
|
6
|
+
import type { paths as ManagementPaths } from "./generated/management.js";
|
|
7
|
+
import { type HttpClientOptions } from "./http.js";
|
|
8
|
+
import { type TypedClient } from "./typed.js";
|
|
9
|
+
export type { ManagementPaths };
|
|
10
|
+
export type ManagementClient = TypedClient<ManagementPaths>;
|
|
11
|
+
export interface ManagementClientOptions extends Omit<HttpClientOptions, "baseUrl" | "headers"> {
|
|
12
|
+
/** `knr_pat_...` or `knr_sa_...` (or an OAuth `knr_at_...` issued for the Management API); may be a function, for rotation */
|
|
13
|
+
token: string | (() => string | Promise<string>);
|
|
14
|
+
/** Defaults to {@link DEFAULT_MANAGEMENT_BASE_URL} */
|
|
15
|
+
baseUrl?: string;
|
|
16
|
+
headers?: HeadersInit;
|
|
17
|
+
}
|
|
18
|
+
export declare const DEFAULT_MANAGEMENT_BASE_URL = "https://app.kanorio.com/api/v1";
|
|
19
|
+
export declare function createManagementClient(options: ManagementClientOptions): ManagementClient;
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Management API (`https://app.kanorio.com/api/v1`, Bearer = a personal access token `knr_pat_` or a service account token `knr_sa_`; an OAuth access token `knr_at_` works when it was issued for the Management API, as `kanorio login` does).
|
|
3
|
+
* MCP (`https://app.kanorio.com/api/mcp`) is another way to reach the same API and shares the same operation registry.
|
|
4
|
+
* Types are generated by openapi-typescript from the Management API's OpenAPI document (a snapshot of `GET /api/v1/openapi.json`).
|
|
5
|
+
*/
|
|
6
|
+
import { createHttpClient } from "./http.js";
|
|
7
|
+
import { createTypedClient } from "./typed.js";
|
|
8
|
+
export const DEFAULT_MANAGEMENT_BASE_URL = "https://app.kanorio.com/api/v1";
|
|
9
|
+
export function createManagementClient(options) {
|
|
10
|
+
const { token, baseUrl, headers, ...rest } = options;
|
|
11
|
+
const http = createHttpClient({
|
|
12
|
+
...rest,
|
|
13
|
+
baseUrl: baseUrl ?? DEFAULT_MANAGEMENT_BASE_URL,
|
|
14
|
+
headers: async () => {
|
|
15
|
+
const h = new Headers(headers);
|
|
16
|
+
const value = typeof token === "function" ? await token() : token;
|
|
17
|
+
h.set("authorization", `Bearer ${value}`);
|
|
18
|
+
return h;
|
|
19
|
+
},
|
|
20
|
+
});
|
|
21
|
+
return createTypedClient(http);
|
|
22
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Lists in all three APIs return the same envelope `{ data, hasMore, nextCursor }`.
|
|
3
|
+
* `paginate` follows `nextCursor` page by page and yields item by item; the caller only puts the cursor into its own query.
|
|
4
|
+
*
|
|
5
|
+
* ```ts
|
|
6
|
+
* for await (const post of paginate((cursor) => client.get("/collections/{key}/items", { params: { key: "blog" }, query: { cursor } }))) {
|
|
7
|
+
* console.log(post.slug);
|
|
8
|
+
* }
|
|
9
|
+
* ```
|
|
10
|
+
*/
|
|
11
|
+
export interface ListPage<T> {
|
|
12
|
+
data: T[];
|
|
13
|
+
hasMore: boolean;
|
|
14
|
+
nextCursor: string | null;
|
|
15
|
+
}
|
|
16
|
+
export declare function paginate<T>(fetchPage: (cursor: string | undefined) => Promise<ListPage<T>>): AsyncGenerator<T, void, undefined>;
|
|
17
|
+
/** Fetches every page and returns an array (for small lists; use {@link paginate} to process large ones item by item) */
|
|
18
|
+
export declare function listAll<T>(fetchPage: (cursor: string | undefined) => Promise<ListPage<T>>): Promise<T[]>;
|
package/dist/paginate.js
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Lists in all three APIs return the same envelope `{ data, hasMore, nextCursor }`.
|
|
3
|
+
* `paginate` follows `nextCursor` page by page and yields item by item; the caller only puts the cursor into its own query.
|
|
4
|
+
*
|
|
5
|
+
* ```ts
|
|
6
|
+
* for await (const post of paginate((cursor) => client.get("/collections/{key}/items", { params: { key: "blog" }, query: { cursor } }))) {
|
|
7
|
+
* console.log(post.slug);
|
|
8
|
+
* }
|
|
9
|
+
* ```
|
|
10
|
+
*/
|
|
11
|
+
export async function* paginate(fetchPage) {
|
|
12
|
+
let cursor;
|
|
13
|
+
for (;;) {
|
|
14
|
+
const page = await fetchPage(cursor);
|
|
15
|
+
yield* page.data;
|
|
16
|
+
if (!page.hasMore || !page.nextCursor)
|
|
17
|
+
return;
|
|
18
|
+
cursor = page.nextCursor;
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
/** Fetches every page and returns an array (for small lists; use {@link paginate} to process large ones item by item) */
|
|
22
|
+
export async function listAll(fetchPage) {
|
|
23
|
+
const out = [];
|
|
24
|
+
for await (const item of paginate(fetchPage))
|
|
25
|
+
out.push(item);
|
|
26
|
+
return out;
|
|
27
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@kanorio/sdk/preview`: helpers for Next.js Draft Mode and Astro with preview tokens (`knr_pv_`).
|
|
3
|
+
*
|
|
4
|
+
* - `previewHeaders(token)`: builds the `X-Kanorio-Preview: knr_pv_...` header, used with `?preview=1` to read unpublished drafts.
|
|
5
|
+
* - `tokenFromCookieHeader(cookieHeader)`: safely reads the `kanorio_preview` token from a `Request`'s `Cookie` header.
|
|
6
|
+
* - `createPreviewRouteHandler({ siteUrl, enableDraftMode })`: one line in Next.js `app/api/preview/route.ts` or an Astro endpoint;
|
|
7
|
+
* it validates the `knr_pv_` format, verifies signature and expiry with the Kanorio Delivery API (when `siteUrl` is given), blocks open redirects,
|
|
8
|
+
* sets the `kanorio_preview` HttpOnly cookie and redirects 307 to the target page.
|
|
9
|
+
*/
|
|
10
|
+
export declare const PREVIEW_TOKEN_PREFIX = "knr_pv_";
|
|
11
|
+
export declare const PREVIEW_COOKIE_NAME = "kanorio_preview";
|
|
12
|
+
export declare function isValidPreviewTokenFormat(token: string | null | undefined): token is string;
|
|
13
|
+
/** Only in-site paths starting with a single `/` are allowed, which blocks `//evil.com` and `https://evil.com` open redirects */
|
|
14
|
+
export declare function sanitizePreviewRedirectPath(raw: string | null | undefined): string;
|
|
15
|
+
export declare function previewHeaders(token: string): Record<string, string>;
|
|
16
|
+
/** Extracts and validates the `kanorio_preview` token from an HTTP `Cookie` header; `null` when absent or malformed */
|
|
17
|
+
export declare function tokenFromCookieHeader(cookieHeader: string | null | undefined): string | null;
|
|
18
|
+
export interface PreviewRouteHandlerOptions {
|
|
19
|
+
/**
|
|
20
|
+
* Optional: with a Kanorio system or service URL (for example `https://s-xxx.kanorio.com`),
|
|
21
|
+
* the token's signature and expiry are verified against `GET {siteUrl}/api/v1/site?preview=1` before Draft Mode is enabled,
|
|
22
|
+
* so a forged or expired token cannot leave the browser in a broken preview state.
|
|
23
|
+
*/
|
|
24
|
+
siteUrl?: string;
|
|
25
|
+
/** In the Next.js App Router, pass `async () => (await draftMode()).enable()` */
|
|
26
|
+
enableDraftMode?: (token: string) => void | Promise<void>;
|
|
27
|
+
/** Cookie lifetime in seconds (3600 by default) */
|
|
28
|
+
cookieMaxAgeSeconds?: number;
|
|
29
|
+
fetch?: typeof globalThis.fetch;
|
|
30
|
+
}
|
|
31
|
+
export declare function createPreviewRouteHandler(options?: PreviewRouteHandlerOptions): (request: Request) => Promise<Response>;
|
|
32
|
+
export declare const preview: {
|
|
33
|
+
headers: typeof previewHeaders;
|
|
34
|
+
tokenFromCookieHeader: typeof tokenFromCookieHeader;
|
|
35
|
+
isValidTokenFormat: typeof isValidPreviewTokenFormat;
|
|
36
|
+
sanitizeRedirectPath: typeof sanitizePreviewRedirectPath;
|
|
37
|
+
createRouteHandler: typeof createPreviewRouteHandler;
|
|
38
|
+
COOKIE_NAME: string;
|
|
39
|
+
TOKEN_PREFIX: string;
|
|
40
|
+
};
|