@kanorio/sdk 1.1.0 → 1.2.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 CHANGED
@@ -39,6 +39,45 @@ A server key is refused in browser code, requires HTTPS, and cannot call the Man
39
39
 
40
40
  Errors throw `KanorioApiError` with `code`, `status` and `details`. Deprecated operations surface through the `onDeprecation` callback (the `Deprecation`, `Sunset` and `Link` response headers).
41
41
 
42
+ ## Images and page metadata
43
+
44
+ `image` turns an image field into something you can render, and an image URL into the size you need. `seo.metadata` builds a page's `<head>` values by the rules the hosted site uses, so your front end and a Kanorio-hosted site share the same SEO behavior:
45
+
46
+ ```ts
47
+ import { image, seo } from "@kanorio/sdk";
48
+
49
+ const { item, assets } = await delivery.get("/collections/{key}/items/{slug}", { params: { key: "blog", slug } });
50
+
51
+ // The cover is optional: an asset id, looked up in `assets`
52
+ const cover = image.resolve(item.fieldData.cover_image, assets);
53
+ if (cover) {
54
+ cover.url; // the original
55
+ image.url(cover.url, { width: 800 }); // resized by Kanorio's edge, never enlarged
56
+ image.srcSet(cover.url); // 400w, 800w, 1200w, 1600w
57
+ }
58
+
59
+ const meta = seo.metadata(item, { siteUrl: "https://www.example.com", site });
60
+ meta.canonical; // the author's canonical on the primary locale, else the page's own URL
61
+ meta.robots; // { index, follow }
62
+ meta.openGraph.image; // { url, alt }: the share image, already cropped the way the author framed it
63
+ ```
64
+
65
+ The share image comes from `fieldData.share_image`, which Kanorio resolves on the server: the image the author chose for sharing, else a post's cover, the generated title card, or the first image in the body. Pass `site` (the `GET /site` response) on multilingual sites to get hreflang and the right canonical for translated pages.
66
+
67
+ For Next.js, `@kanorio/sdk/next` adapts these without depending on `next`:
68
+
69
+ ```ts
70
+ import { seoMetadata } from "@kanorio/sdk";
71
+ import { kanorioImageLoader, toNextMetadata } from "@kanorio/sdk/next";
72
+
73
+ export async function generateMetadata({ params }) {
74
+ const data = await loadPost((await params).slug);
75
+ return data ? toNextMetadata(seoMetadata(data.item, { siteUrl: SITE_URL, site })) : {};
76
+ }
77
+
78
+ // <Image loader={kanorioImageLoader} src={cover.url} width={cover.width} height={cover.height} alt={cover.alt ?? ""} />
79
+ ```
80
+
42
81
  ## Tax id validation
43
82
 
44
83
  `@kanorio/sdk/tax-id` validates tax ids the way the hosted checkout and forms do, without a network call:
package/dist/edge.js CHANGED
@@ -11,7 +11,7 @@
11
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
12
  */
13
13
  import { deliveryBaseUrl } from "./delivery.js";
14
- import { serverKeyRequest, visitorIpFromRequest } from "./server-key.js";
14
+ import { edgeChallengeMessage, isEdgeChallenge, serverKeyRequest, visitorIpFromRequest } from "./server-key.js";
15
15
  import { localeRootPath, resolveRequestLocale } from "./shared/localization/request-locale.js";
16
16
  import { canonicalRedirectPath, matchLocalizedRedirect } from "./shared/utils/redirect-matching.js";
17
17
  export const CRAWLER_LIST_VERSION = "2026-10-22";
@@ -154,6 +154,21 @@ export function createKanorioMiddleware(options) {
154
154
  })();
155
155
  return inflight;
156
156
  }
157
+ // A rejected report must not fail the visitor's request, but it must not be silent either: the site would keep redirecting and
158
+ // blocking while its crawler numbers quietly stop. One warning per middleware instance, never per request.
159
+ let reportWarned = false;
160
+ function warnReportRejected(response) {
161
+ if (reportWarned || response.ok)
162
+ return;
163
+ reportWarned = true;
164
+ const hasKey = Boolean(options.serverKey?.trim());
165
+ const reason = isEdgeChallenge(response)
166
+ ? edgeChallengeMessage(hasKey)
167
+ : response.status === 401
168
+ ? "Kanorio rejected the server key. Keys that start with knr_sa_ are no longer server keys, and a revoked key is rejected too: create a new one under Site settings > Developer (purpose \"Website server\") and store it as KANORIO_SERVER_KEY."
169
+ : `Kanorio answered ${response.status}.`;
170
+ console.warn(`@kanorio/sdk: AI crawler hits are not being recorded. ${reason} Redirects and crawler blocking are not affected.`);
171
+ }
157
172
  function reportBotHit(request, pathname, bot, blocked, event) {
158
173
  const userAgent = request.headers.get("user-agent") ?? bot.uaToken;
159
174
  const url = `${apiBase}/analytics/bot-hit`;
@@ -170,6 +185,7 @@ export function createKanorioMiddleware(options) {
170
185
  }),
171
186
  ...(viaServerKey ? { redirect: viaServerKey.redirect } : {}),
172
187
  }))
188
+ .then(warnReportRejected)
173
189
  .catch(() => undefined);
174
190
  if (event?.waitUntil) {
175
191
  event.waitUntil(promise);
package/dist/forms.d.ts CHANGED
@@ -7,8 +7,17 @@
7
7
  */
8
8
  import { type ServerKeyOptions } from "./server-key.js";
9
9
  import type { TaxIdLookupResponse } from "./shared/business-registry/lookup-wire.js";
10
+ import type { components as DeliveryComponents } from "./generated/delivery.js";
10
11
  import { resolveVisibleFieldIds } from "./shared/types/forms-logic.js";
11
12
  import { type ProtectionChallenge, type ProtectionFields } from "./protection.js";
13
+ /**
14
+ * The form definition from `GET /forms/{id}`: status, questions, settings and the consent text to show.
15
+ * It grows over time: skip question types you do not know and ignore keys you do not recognise.
16
+ */
17
+ export type FormDefinition = DeliveryComponents["schemas"]["Form"];
18
+ /** One question; narrow on `type` to read the keys of that question type */
19
+ export type FormField = DeliveryComponents["schemas"]["FormField"];
20
+ export type FormSettings = DeliveryComponents["schemas"]["FormSettings"];
12
21
  /** `GET /forms/{id}/challenge`: the built-in ALTCHA challenge, or the parameters of the third-party widget the site chose */
13
22
  export type FormChallengeResponse = ProtectionChallenge;
14
23
  /** Protection fields sent with submissions and uploads (`_hp`, `_wp` and `_co` are honeypots, always empty strings) */
@@ -53,13 +62,23 @@ export interface FormSubmitInput {
53
62
  }
54
63
  export type FormSubmitResult = {
55
64
  ok: true;
65
+ /** Present when the form did not take the submission because of its own state; nothing was saved */
56
66
  state?: "closed" | "not_open" | "full";
67
+ /** Id of this submission; absent when `state` is present */
68
+ submissionId?: string;
69
+ /**
70
+ * Where to send the visitor now, when the form has a redirect after submit: a path on the site or an https URL (it can be another site).
71
+ * Answers and the submission id are already filled in. Navigate to it as is, for example `window.location.assign(result.redirectUrl)`.
72
+ */
73
+ redirectUrl?: string;
57
74
  } | {
58
75
  ok: false;
59
76
  error: FormApiError;
60
77
  };
61
78
  export interface FormsHelpers {
62
- get(formId: string): Promise<unknown>;
79
+ get(formId: string): Promise<{
80
+ form: FormDefinition;
81
+ }>;
63
82
  challenge(formId: string): Promise<FormChallengeResponse>;
64
83
  requestUpload(formId: string, input: FormUploadTicketRequest): Promise<FormUploadTicketResponse>;
65
84
  /**
package/dist/forms.js CHANGED
@@ -111,7 +111,13 @@ export function createFormsHelpers(options) {
111
111
  if (!res.ok)
112
112
  return { ok: false, error: await readError(res) };
113
113
  const data = (await res.json().catch(() => ({})));
114
- return data.state ? { ok: true, state: data.state } : { ok: true };
114
+ if (data.state)
115
+ return { ok: true, state: data.state };
116
+ return {
117
+ ok: true,
118
+ ...(typeof data.submissionId === "string" ? { submissionId: data.submissionId } : {}),
119
+ ...(typeof data.redirectUrl === "string" ? { redirectUrl: data.redirectUrl } : {}),
120
+ };
115
121
  },
116
122
  };
117
123
  }