@kanorio/sdk 1.0.0 → 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 (76) hide show
  1. package/README.md +2 -2
  2. package/dist/customer-oauth.d.ts +21 -21
  3. package/dist/customer-oauth.js +12 -12
  4. package/dist/customer.d.ts +22 -22
  5. package/dist/customer.js +20 -11
  6. package/dist/delivery.d.ts +9 -9
  7. package/dist/delivery.js +6 -6
  8. package/dist/edge.d.ts +25 -21
  9. package/dist/edge.js +19 -19
  10. package/dist/forms.d.ts +13 -13
  11. package/dist/forms.js +13 -13
  12. package/dist/generated/delivery.d.ts +35 -7
  13. package/dist/generated/management.d.ts +111 -26
  14. package/dist/http.d.ts +13 -13
  15. package/dist/http.js +8 -8
  16. package/dist/index.js +2 -2
  17. package/dist/locales.d.ts +22 -22
  18. package/dist/locales.js +12 -12
  19. package/dist/management.d.ts +5 -5
  20. package/dist/management.js +3 -3
  21. package/dist/paginate.d.ts +3 -3
  22. package/dist/paginate.js +3 -3
  23. package/dist/preview.d.ts +13 -13
  24. package/dist/preview.js +11 -11
  25. package/dist/protection.d.ts +18 -18
  26. package/dist/protection.js +11 -11
  27. package/dist/revalidate.d.ts +22 -22
  28. package/dist/revalidate.js +14 -14
  29. package/dist/seo.d.ts +20 -20
  30. package/dist/seo.js +20 -20
  31. package/dist/server-key.d.ts +2 -2
  32. package/dist/server-key.js +2 -2
  33. package/dist/shared/api/delivery/cache-tags.d.ts +39 -39
  34. package/dist/shared/api/delivery/cache-tags.js +34 -34
  35. package/dist/shared/api/server-key.d.ts +32 -28
  36. package/dist/shared/api/server-key.js +41 -33
  37. package/dist/shared/business-registry/attribution.d.ts +5 -5
  38. package/dist/shared/business-registry/attribution.js +4 -4
  39. package/dist/shared/business-registry/define.d.ts +1 -1
  40. package/dist/shared/business-registry/define.js +1 -1
  41. package/dist/shared/business-registry/formats/eu-vat.js +4 -4
  42. package/dist/shared/business-registry/formats/hk-br.d.ts +2 -2
  43. package/dist/shared/business-registry/formats/hk-br.js +4 -4
  44. package/dist/shared/business-registry/formats/jp-trn.d.ts +3 -3
  45. package/dist/shared/business-registry/formats/jp-trn.js +4 -4
  46. package/dist/shared/business-registry/formats/kr-brn.d.ts +2 -2
  47. package/dist/shared/business-registry/formats/kr-brn.js +3 -3
  48. package/dist/shared/business-registry/formats/my.d.ts +3 -3
  49. package/dist/shared/business-registry/formats/my.js +4 -4
  50. package/dist/shared/business-registry/formats/sg-uen.js +4 -4
  51. package/dist/shared/business-registry/formats/tw-vat.d.ts +5 -5
  52. package/dist/shared/business-registry/formats/tw-vat.js +6 -6
  53. package/dist/shared/business-registry/index.js +1 -1
  54. package/dist/shared/business-registry/lookup-wire.d.ts +9 -9
  55. package/dist/shared/business-registry/lookup-wire.js +4 -4
  56. package/dist/shared/business-registry/normalize.d.ts +3 -3
  57. package/dist/shared/business-registry/normalize.js +4 -4
  58. package/dist/shared/business-registry/registry.d.ts +9 -9
  59. package/dist/shared/business-registry/registry.js +13 -13
  60. package/dist/shared/business-registry/types.d.ts +20 -20
  61. package/dist/shared/business-registry/types.js +6 -6
  62. package/dist/shared/localization/locale-path.d.ts +18 -18
  63. package/dist/shared/localization/locale-path.js +18 -18
  64. package/dist/shared/localization/request-locale.d.ts +16 -16
  65. package/dist/shared/localization/request-locale.js +13 -13
  66. package/dist/shared/seo/alternates.d.ts +26 -26
  67. package/dist/shared/seo/alternates.js +18 -18
  68. package/dist/shared/types/forms-logic.d.ts +28 -28
  69. package/dist/shared/types/forms-logic.js +27 -27
  70. package/dist/shared/types/number-input.d.ts +2 -2
  71. package/dist/shared/types/number-input.js +3 -3
  72. package/dist/shared/utils/redirect-matching.d.ts +33 -24
  73. package/dist/shared/utils/redirect-matching.js +73 -40
  74. package/dist/typed.d.ts +5 -5
  75. package/dist/typed.js +3 -3
  76. package/package.json +10 -10
package/dist/locales.d.ts CHANGED
@@ -1,11 +1,11 @@
1
1
  /**
2
- * 多語網站的語系路由與 hreflang(ADR-0010 決策 4、10、13;Headless 同權)。
2
+ * Locale routing and hreflang for multilingual sites (the same behavior as hosted sites).
3
3
  *
4
- * 與 Kanorio 代管站同一套純函式(`src/shared/**` 由 `pnpm --filter @kanorio/sdk gen` 從 packages/shared 複製):
5
- * - 主語系無前綴(`/about`),次語系子目錄(`/en/about`);前綴是站主存下來的 `pathPrefix`(`GET /api/v1/site` 的 `locales[]`)
6
- * - `resolveRequestLocale` 認路徑第一段;主語系碼當前綴(`/zh-hant/about`)要 301 回無前綴
7
- * - `buildAlternates` 算 canonical 與 hreflang:每個語系版本 self-canonical、只列這一頁有翻譯的語系、x-default 指主語系;
8
- * 未翻譯的 fallback 頁 canonical 指主語系網址、不出 hreflang
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
9
  */
10
10
  import { type LocaleRoute } from "./shared/localization/locale-path.js";
11
11
  import { type RequestLocaleResult } from "./shared/localization/request-locale.js";
@@ -13,27 +13,27 @@ import { hreflangEntries, type SiteAlternates } from "./shared/seo/alternates.js
13
13
  export { localeOfPrefix, localePrefixMap, localePrefixOf, languageOfLocale, type LocaleRoute } from "./shared/localization/locale-path.js";
14
14
  export { resolveRequestLocale, withLocalePrefix, localeRootPath, type RequestLocaleInput, type RequestLocaleResult } from "./shared/localization/request-locale.js";
15
15
  export { buildSiteAlternates, hreflangEntries, hreflangOf, localizedSiteUrl, sitemapAlternates, type SiteAlternates, type SiteAlternatesInput, type LocalePrefixes } from "./shared/seo/alternates.js";
16
- /** `GET /api/v1/site` 回應裡與語系有關的欄位 */
16
+ /** The locale-related fields of the `GET /api/v1/site` response */
17
17
  export interface SiteLocaleMeta {
18
18
  primaryLocale?: string | null;
19
19
  locales?: readonly LocaleRoute[] | null;
20
20
  }
21
21
  export interface BuildAlternatesOptions {
22
- /** 外部前端的對外網址,不含尾斜線(`https://www.example.com`) */
22
+ /** The external front end's public URL, without a trailing slash (`https://www.example.com`) */
23
23
  siteUrl: string;
24
- /** `GET /api/v1/site` 的回應(`primaryLocale`、`locales[]`) */
24
+ /** The `GET /api/v1/site` response (`primaryLocale`, `locales[]`) */
25
25
  site: SiteLocaleMeta;
26
- /** 主語系空間的路徑(無前綴):`/about`、`/blog/hello`、首頁 `/` */
26
+ /** Path in the primary locale's space (no prefix): `/about`, `/blog/hello`, the home page `/` */
27
27
  path: string;
28
- /** 網址上的語系(`resolveRequestLocale` 的 `locale`);省略=主語系 */
28
+ /** The locale in the URL (`locale` from `resolveRequestLocale`); omit for the primary locale */
29
29
  requestLocale?: string | null;
30
- /** 內容實際交付的語系(Delivery 回應的 `resolvedLocale`);省略=`requestLocale` */
30
+ /** The locale the content was actually served in (`resolvedLocale` of the Delivery response); omit to use `requestLocale` */
31
31
  resolvedLocale?: string | null;
32
- /** 這一頁有已發布翻譯的次語系(Delivery 回應的 `availableLocales`);`"all"`=每個已上線語系都有(列表頁) */
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
33
  availableLocales?: readonly string[] | "all" | null;
34
34
  /**
35
- * 這一頁在每個已上線語系的路徑(無前綴;Delivery 回應的 `localePaths`)。各語系可有自己的翻譯網址代稱,
36
- * 有給就用它組每個語系的網址;沒給時每個語系用 `path`
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
37
  */
38
38
  localePaths?: Readonly<Record<string, string>> | null;
39
39
  }
@@ -43,21 +43,21 @@ export interface HreflangLink {
43
43
  href: string;
44
44
  }
45
45
  export interface PageAlternates extends SiteAlternates {
46
- /** `<link rel="alternate" hreflang="…" href="…">`,fallback 頁與單語網站為空 */
46
+ /** `<link rel="alternate" hreflang="..." href="...">`; empty for fallback pages and single-language sites */
47
47
  links: HreflangLink[];
48
48
  }
49
49
  /**
50
- * 一頁的 canonical 與 hreflang(Next.js `metadata.alternates` 可直接用 `canonical`/`languages`)。
51
- * 單語網站只回 canonical;fallback 頁(請求次語系但這一頁沒翻譯)canonical 指主語系網址、不出 hreflang。
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
52
  */
53
53
  export declare function buildAlternates(options: BuildAlternatesOptions): PageAlternates;
54
- /** 外部前端的請求語系:從路徑第一段認前綴;`site` 缺語系資料(單語網站)時一律主語系 */
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
55
  export declare function requestLocaleOf(pathname: string, site: SiteLocaleMeta): RequestLocaleResult;
56
- /** 某語系的這一頁路徑(主語系無前綴);語言切換用 */
56
+ /** This page's path in a locale (the primary locale has no prefix); for a language switcher */
57
57
  export declare function localizedPath(pathname: string, locale: string, site: SiteLocaleMeta): string;
58
58
  /**
59
- * 語言切換選單:每個已上線語系的這一頁網址(主語系在前,其餘依 `locales[]` 順序)。
60
- * 給了 `localePaths`(Delivery 回應)就用每個語系自己的路徑(翻譯網址代稱);沒給時把 `path` 換到各語系前綴底下。
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
61
  */
62
62
  export declare function languageSwitcher(options: {
63
63
  siteUrl: string;
package/dist/locales.js CHANGED
@@ -1,11 +1,11 @@
1
1
  /**
2
- * 多語網站的語系路由與 hreflang(ADR-0010 決策 4、10、13;Headless 同權)。
2
+ * Locale routing and hreflang for multilingual sites (the same behavior as hosted sites).
3
3
  *
4
- * 與 Kanorio 代管站同一套純函式(`src/shared/**` 由 `pnpm --filter @kanorio/sdk gen` 從 packages/shared 複製):
5
- * - 主語系無前綴(`/about`),次語系子目錄(`/en/about`);前綴是站主存下來的 `pathPrefix`(`GET /api/v1/site` 的 `locales[]`)
6
- * - `resolveRequestLocale` 認路徑第一段;主語系碼當前綴(`/zh-hant/about`)要 301 回無前綴
7
- * - `buildAlternates` 算 canonical 與 hreflang:每個語系版本 self-canonical、只列這一頁有翻譯的語系、x-default 指主語系;
8
- * 未翻譯的 fallback 頁 canonical 指主語系網址、不出 hreflang
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
9
  */
10
10
  import { localePrefixMap, localePrefixOf } from "./shared/localization/locale-path.js";
11
11
  import { resolveRequestLocale, withLocalePrefix } from "./shared/localization/request-locale.js";
@@ -14,8 +14,8 @@ export { localeOfPrefix, localePrefixMap, localePrefixOf, languageOfLocale } fro
14
14
  export { resolveRequestLocale, withLocalePrefix, localeRootPath } from "./shared/localization/request-locale.js";
15
15
  export { buildSiteAlternates, hreflangEntries, hreflangOf, localizedSiteUrl, sitemapAlternates } from "./shared/seo/alternates.js";
16
16
  /**
17
- * 一頁的 canonical 與 hreflang(Next.js `metadata.alternates` 可直接用 `canonical`/`languages`)。
18
- * 單語網站只回 canonical;fallback 頁(請求次語系但這一頁沒翻譯)canonical 指主語系網址、不出 hreflang。
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
19
  */
20
20
  export function buildAlternates(options) {
21
21
  const primaryLocale = options.site.primaryLocale ?? null;
@@ -42,7 +42,7 @@ export function buildAlternates(options) {
42
42
  const links = Object.entries(alternates.languages).map(([hreflang, href]) => ({ rel: "alternate", hreflang, href }));
43
43
  return { ...alternates, links };
44
44
  }
45
- /** 外部前端的請求語系:從路徑第一段認前綴;`site` 缺語系資料(單語網站)時一律主語系 */
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
46
  export function requestLocaleOf(pathname, site) {
47
47
  const primaryLocale = site.primaryLocale ?? "";
48
48
  const routes = site.locales ?? [];
@@ -50,14 +50,14 @@ export function requestLocaleOf(pathname, site) {
50
50
  return { locale: primaryLocale, pathname: pathname || "/", prefixed: false, redirectTo: null };
51
51
  return resolveRequestLocale({ pathname, primaryLocale, locales: routes });
52
52
  }
53
- /** 某語系的這一頁路徑(主語系無前綴);語言切換用 */
53
+ /** This page's path in a locale (the primary locale has no prefix); for a language switcher */
54
54
  export function localizedPath(pathname, locale, site) {
55
55
  const primaryLocale = site.primaryLocale ?? locale;
56
56
  return withLocalePrefix(pathname, locale, primaryLocale, site.locales ?? []);
57
57
  }
58
58
  /**
59
- * 語言切換選單:每個已上線語系的這一頁網址(主語系在前,其餘依 `locales[]` 順序)。
60
- * 給了 `localePaths`(Delivery 回應)就用每個語系自己的路徑(翻譯網址代稱);沒給時把 `path` 換到各語系前綴底下。
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
61
  */
62
62
  export function languageSwitcher(options) {
63
63
  const primaryLocale = options.site.primaryLocale ?? null;
@@ -1,7 +1,7 @@
1
1
  /**
2
- * Management API(`https://app.kanorio.com/api/v1`,Bearer = personal access token `knr_pat_` 或 service account token `knr_sa_`;OAuth access token `knr_at_` 只對 MCP 有效)。
3
- * MCP(`https://app.kanorio.com/api/mcp`)是同一套 API 的另一種接法,共用同一份 capability registry。
4
- * 型別由 `packages/shared/openapi/management.json`(`GET /api/v1/openapi.json` 的快照)經 openapi-typescript 產生。
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
5
  */
6
6
  import type { paths as ManagementPaths } from "./generated/management.js";
7
7
  import { type HttpClientOptions } from "./http.js";
@@ -9,9 +9,9 @@ import { type TypedClient } from "./typed.js";
9
9
  export type { ManagementPaths };
10
10
  export type ManagementClient = TypedClient<ManagementPaths>;
11
11
  export interface ManagementClientOptions extends Omit<HttpClientOptions, "baseUrl" | "headers"> {
12
- /** `knr_pat_…` 或 `knr_sa_…`(OAuth 的 `knr_at_…` 只能用在 MCP);可為函式供輪替 */
12
+ /** `knr_pat_...` or `knr_sa_...` (or an OAuth `knr_at_...` issued for the Management API); may be a function, for rotation */
13
13
  token: string | (() => string | Promise<string>);
14
- /** 預設 {@link DEFAULT_MANAGEMENT_BASE_URL} */
14
+ /** Defaults to {@link DEFAULT_MANAGEMENT_BASE_URL} */
15
15
  baseUrl?: string;
16
16
  headers?: HeadersInit;
17
17
  }
@@ -1,7 +1,7 @@
1
1
  /**
2
- * Management API(`https://app.kanorio.com/api/v1`,Bearer = personal access token `knr_pat_` 或 service account token `knr_sa_`;OAuth access token `knr_at_` 只對 MCP 有效)。
3
- * MCP(`https://app.kanorio.com/api/mcp`)是同一套 API 的另一種接法,共用同一份 capability registry。
4
- * 型別由 `packages/shared/openapi/management.json`(`GET /api/v1/openapi.json` 的快照)經 openapi-typescript 產生。
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
5
  */
6
6
  import { createHttpClient } from "./http.js";
7
7
  import { createTypedClient } from "./typed.js";
@@ -1,6 +1,6 @@
1
1
  /**
2
- * 三套 API 的列表都回同一個信封 `{ data, hasMore, nextCursor }`(ADR-0006 決定 2-2)。
3
- * `paginate` 依 `nextCursor` 一頁一頁取,逐筆 yield;呼叫端只要把 cursor 放進自己的查詢。
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
4
  *
5
5
  * ```ts
6
6
  * for await (const post of paginate((cursor) => client.get("/collections/{key}/items", { params: { key: "blog" }, query: { cursor } }))) {
@@ -14,5 +14,5 @@ export interface ListPage<T> {
14
14
  nextCursor: string | null;
15
15
  }
16
16
  export declare function paginate<T>(fetchPage: (cursor: string | undefined) => Promise<ListPage<T>>): AsyncGenerator<T, void, undefined>;
17
- /** 取完所有頁並回傳陣列(小清單用;大清單請用 {@link paginate} 逐筆處理) */
17
+ /** Fetches every page and returns an array (for small lists; use {@link paginate} to process large ones item by item) */
18
18
  export declare function listAll<T>(fetchPage: (cursor: string | undefined) => Promise<ListPage<T>>): Promise<T[]>;
package/dist/paginate.js CHANGED
@@ -1,6 +1,6 @@
1
1
  /**
2
- * 三套 API 的列表都回同一個信封 `{ data, hasMore, nextCursor }`(ADR-0006 決定 2-2)。
3
- * `paginate` 依 `nextCursor` 一頁一頁取,逐筆 yield;呼叫端只要把 cursor 放進自己的查詢。
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
4
  *
5
5
  * ```ts
6
6
  * for await (const post of paginate((cursor) => client.get("/collections/{key}/items", { params: { key: "blog" }, query: { cursor } }))) {
@@ -18,7 +18,7 @@ export async function* paginate(fetchPage) {
18
18
  cursor = page.nextCursor;
19
19
  }
20
20
  }
21
- /** 取完所有頁並回傳陣列(小清單用;大清單請用 {@link paginate} 逐筆處理) */
21
+ /** Fetches every page and returns an array (for small lists; use {@link paginate} to process large ones item by item) */
22
22
  export async function listAll(fetchPage) {
23
23
  const out = [];
24
24
  for await (const item of paginate(fetchPage))
package/dist/preview.d.ts CHANGED
@@ -1,30 +1,30 @@
1
1
  /**
2
- * `@kanorio/sdk/preview`:Next.js Draft Mode 與 Astro 預覽權杖(`knr_pv_`)輔助(Stage F3)。
2
+ * `@kanorio/sdk/preview`: helpers for Next.js Draft Mode and Astro with preview tokens (`knr_pv_`).
3
3
  *
4
- * - `previewHeaders(token)`:組裝 `X-Kanorio-Preview: knr_pv_...` 標頭,配合 `?preview=1` 讀取未發布草稿。
5
- * - `tokenFromCookieHeader(cookieHeader)`:從 `Request` 的 `Cookie` 標頭安全取出 `kanorio_preview` 權杖。
6
- * - `createPreviewRouteHandler({ siteUrl, enableDraftMode })`:一行掛在 Next.js `app/api/preview/route.ts` 或 Astro endpoint,
7
- * 驗證 `knr_pv_` 格式、(當提供 `siteUrl` 時)向 Kanorio Delivery API 驗證簽章與時效、阻擋 open redirect,
8
- * 寫入 `kanorio_preview` HttpOnly cookie 並 307 導向目標頁。
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
9
  */
10
10
  export declare const PREVIEW_TOKEN_PREFIX = "knr_pv_";
11
11
  export declare const PREVIEW_COOKIE_NAME = "kanorio_preview";
12
12
  export declare function isValidPreviewTokenFormat(token: string | null | undefined): token is string;
13
- /** 僅允許以單一 `/` 開頭的站內路徑,阻擋 `//evil.com` 或 `https://evil.com` open redirect */
13
+ /** Only in-site paths starting with a single `/` are allowed, which blocks `//evil.com` and `https://evil.com` open redirects */
14
14
  export declare function sanitizePreviewRedirectPath(raw: string | null | undefined): string;
15
15
  export declare function previewHeaders(token: string): Record<string, string>;
16
- /** 從 HTTP `Cookie` 標頭提取並驗證 `kanorio_preview` 權杖;不存在或格式不符時回傳 `null` */
16
+ /** Extracts and validates the `kanorio_preview` token from an HTTP `Cookie` header; `null` when absent or malformed */
17
17
  export declare function tokenFromCookieHeader(cookieHeader: string | null | undefined): string | null;
18
18
  export interface PreviewRouteHandlerOptions {
19
19
  /**
20
- * 選填:傳入 Kanorio 系統或服務網址(如 `https://s-xxx.kanorio.com`)時,
21
- * 會在啟用 Draft Mode 前先向 `GET {siteUrl}/api/v1/site?preview=1` 驗證權杖簽章與有效期限,
22
- * 防止偽造或過期的權杖讓瀏覽器進入失敗的預覽狀態。
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
23
  */
24
24
  siteUrl?: string;
25
- /** Next.js App Router 傳入 `async () => (await draftMode()).enable()` */
25
+ /** In the Next.js App Router, pass `async () => (await draftMode()).enable()` */
26
26
  enableDraftMode?: (token: string) => void | Promise<void>;
27
- /** Cookie 存活秒數(預設 3600 秒) */
27
+ /** Cookie lifetime in seconds (3600 by default) */
28
28
  cookieMaxAgeSeconds?: number;
29
29
  fetch?: typeof globalThis.fetch;
30
30
  }
package/dist/preview.js CHANGED
@@ -1,17 +1,17 @@
1
1
  /**
2
- * `@kanorio/sdk/preview`:Next.js Draft Mode 與 Astro 預覽權杖(`knr_pv_`)輔助(Stage F3)。
2
+ * `@kanorio/sdk/preview`: helpers for Next.js Draft Mode and Astro with preview tokens (`knr_pv_`).
3
3
  *
4
- * - `previewHeaders(token)`:組裝 `X-Kanorio-Preview: knr_pv_...` 標頭,配合 `?preview=1` 讀取未發布草稿。
5
- * - `tokenFromCookieHeader(cookieHeader)`:從 `Request` 的 `Cookie` 標頭安全取出 `kanorio_preview` 權杖。
6
- * - `createPreviewRouteHandler({ siteUrl, enableDraftMode })`:一行掛在 Next.js `app/api/preview/route.ts` 或 Astro endpoint,
7
- * 驗證 `knr_pv_` 格式、(當提供 `siteUrl` 時)向 Kanorio Delivery API 驗證簽章與時效、阻擋 open redirect,
8
- * 寫入 `kanorio_preview` HttpOnly cookie 並 307 導向目標頁。
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
9
  */
10
10
  import { DELIVERY_PREVIEW_HEADER, deliveryBaseUrl } from "./delivery.js";
11
11
  export const PREVIEW_TOKEN_PREFIX = "knr_pv_";
12
12
  export const PREVIEW_COOKIE_NAME = "kanorio_preview";
13
- // 形狀是 `knr_pv_{siteId}.{expiresAtSec}.{jti}.{sig}`;jti 與 sig 都是 base64url,可能含 `-` 與 `_`。
14
- // jti 一段必須接受 `-`:不接受時約六分之一的合法權杖會被判成格式錯誤(預覽路由回 401、cookie 讀不出來)。
13
+ // The shape is `knr_pv_{siteId}.{expiresAtSec}.{jti}.{sig}`; jti and sig are base64url and may contain `-` and `_`.
14
+ // The jti segment must accept `-`: otherwise about one in six valid tokens is treated as malformed (the preview route answers 401 and the cookie cannot be read).
15
15
  const PREVIEW_TOKEN_RE = /^knr_pv_[a-z0-9]+\.\d+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/i;
16
16
  export function isValidPreviewTokenFormat(token) {
17
17
  if (!token || typeof token !== "string")
@@ -19,7 +19,7 @@ export function isValidPreviewTokenFormat(token) {
19
19
  const trimmed = token.trim();
20
20
  return trimmed.length <= 256 && PREVIEW_TOKEN_RE.test(trimmed);
21
21
  }
22
- /** 僅允許以單一 `/` 開頭的站內路徑,阻擋 `//evil.com` 或 `https://evil.com` open redirect */
22
+ /** Only in-site paths starting with a single `/` are allowed, which blocks `//evil.com` and `https://evil.com` open redirects */
23
23
  export function sanitizePreviewRedirectPath(raw) {
24
24
  if (!raw || typeof raw !== "string")
25
25
  return "/";
@@ -34,7 +34,7 @@ export function previewHeaders(token) {
34
34
  [DELIVERY_PREVIEW_HEADER]: token.trim(),
35
35
  };
36
36
  }
37
- /** 從 HTTP `Cookie` 標頭提取並驗證 `kanorio_preview` 權杖;不存在或格式不符時回傳 `null` */
37
+ /** Extracts and validates the `kanorio_preview` token from an HTTP `Cookie` header; `null` when absent or malformed */
38
38
  export function tokenFromCookieHeader(cookieHeader) {
39
39
  if (!cookieHeader)
40
40
  return null;
@@ -95,7 +95,7 @@ export function createPreviewRouteHandler(options = {}) {
95
95
  }
96
96
  }
97
97
  catch {
98
- // 上游網路暫時異常時不誤擋格式合法的權杖
98
+ // Do not reject a well-formed token when the upstream network is temporarily failing
99
99
  }
100
100
  }
101
101
  await options.enableDraftMode?.(token);
@@ -1,10 +1,10 @@
1
1
  /**
2
- * 人機驗證(表單、顧客登入共用):把 `GET /api/v1/forms/{id}/challenge` 或 `GET /api/v1/customer/auth/protection`
3
- * 回的題目變成送出時要帶的防護欄位。
2
+ * Bot protection (shared by forms and customer sign-in): turns the challenge from `GET /api/v1/forms/{id}/challenge` or `GET /api/v1/customer/auth/protection`
3
+ * into the protection fields to send on submit.
4
4
  *
5
- * - `provider: "kanorio"`:內建的 ALTCHA 工作量證明,這裡直接解(Web Crypto,瀏覽器與 Node 20 都能跑),payload 放 `_tk`。
6
- * - 第三方(Turnstile、reCAPTCHA、hCaptcha):用回傳的 `siteKey`、`action`(Turnstile 另有 `cData`)畫該家 widget,
7
- * 把 widget 給的 token 交給這裡,放 `captchaToken`。提供者由網站設定決定,伺服器依設定驗。
5
+ * - `provider: "kanorio"`: the built-in ALTCHA proof of work, solved here (Web Crypto; runs in browsers and Node 20), with the payload in `_tk`.
6
+ * - Third parties (Turnstile, reCAPTCHA, hCaptcha): render that widget with the returned `siteKey` and `action` (Turnstile also has `cData`),
7
+ * then pass the widget's token here to be sent as `captchaToken`. The provider is a site setting, and the server verifies accordingly.
8
8
  */
9
9
  export type ProtectionProvider = "kanorio" | "turnstile" | "recaptcha" | "hcaptcha";
10
10
  export interface AltchaChallenge {
@@ -26,36 +26,36 @@ export type ProtectionChallenge = {
26
26
  action: string;
27
27
  cData: string | null;
28
28
  recaptchaVersion: "v2" | "v3" | null;
29
- /** true:把驗證畫出來(網站登入量異常時) */
29
+ /** true: show the verification (when sign-in volume on the site is unusual) */
30
30
  visible?: boolean;
31
- /** 只有表單:附件上傳票用(第三方 token 是一次性的,留給送出) */
31
+ /** Forms only: for attachment upload tickets (a third-party token is single-use and is kept for the submit) */
32
32
  uploadToken?: string;
33
33
  };
34
- /** 送出時帶的防護欄位(`_hp`、`_wp`、`_co` 是蜜罐,一律空字串) */
34
+ /** Protection fields sent on submit (`_hp`, `_wp` and `_co` are honeypots, always empty strings) */
35
35
  export interface ProtectionFields {
36
36
  _hp: "";
37
37
  _wp: "";
38
38
  _co: "";
39
- /** 畫面顯示的時間(Unix 毫秒) */
39
+ /** When the screen was shown (Unix milliseconds) */
40
40
  _ts: number;
41
- /** 內建:解完的 ALTCHA payload */
41
+ /** Built-in: the solved ALTCHA payload */
42
42
  _tk?: string;
43
- /** 題目綁的對象:表單 id,或 `customer-login:{siteId}` */
43
+ /** What the challenge is bound to: the form id, or `customer-login:{siteId}` */
44
44
  _ctx?: string;
45
- /** 第三方:widget 給的 token */
45
+ /** Third party: the token from the widget */
46
46
  captchaToken?: string;
47
47
  }
48
48
  /**
49
- * 解內建題目:找出 `SHA-256(salt + n) === challenge` 的 n,回 ALTCHA payload(base64 JSON)。
50
- * 中階手機約 0.5~1 秒;`signal` 可在使用者離開頁面時中止。
49
+ * Solves the built-in challenge: finds n where `SHA-256(salt + n) === challenge` and returns the ALTCHA payload (base64 JSON).
50
+ * About 0.5 to 1 second on a mid-range phone; `signal` can abort it when the user leaves the page.
51
51
  */
52
52
  export declare function solveAltchaChallenge(challenge: AltchaChallenge, options?: {
53
53
  signal?: AbortSignal;
54
54
  }): Promise<string>;
55
55
  /**
56
- * 題目 → 防護欄位。內建題目在這裡解;第三方要先畫 widget 拿到 token,再以 `captchaToken` 傳進來。
56
+ * Challenge to protection fields. The built-in challenge is solved here; for a third party, render the widget first and pass its token in as `captchaToken`.
57
57
  *
58
- * @param context 題目綁的對象:表單 id,或 `customer-login:{siteId}`(內建題目才用)
58
+ * @param context What the challenge is bound to: the form id, or `customer-login:{siteId}` (built-in challenge only)
59
59
  */
60
60
  export declare function protectionFromChallenge(challenge: ProtectionChallenge, options: {
61
61
  context: string;
@@ -64,8 +64,8 @@ export declare function protectionFromChallenge(challenge: ProtectionChallenge,
64
64
  signal?: AbortSignal;
65
65
  }): Promise<ProtectionFields>;
66
66
  /**
67
- * 附件上傳票的防護欄位:內建時就是送出用的那份(同一個解、上傳不消費);第三方時用 challenge 的 `uploadToken`,
68
- * widget token 留給送出。
67
+ * Protection fields for an attachment upload ticket: with the built-in challenge they are the ones used for submitting (same solution; uploads do not consume it); with a third party, use the challenge's `uploadToken`
68
+ * and keep the widget token for the submit.
69
69
  */
70
70
  export declare function uploadProtectionFromChallenge(challenge: ProtectionChallenge, options: {
71
71
  context: string;
@@ -1,10 +1,10 @@
1
1
  /**
2
- * 人機驗證(表單、顧客登入共用):把 `GET /api/v1/forms/{id}/challenge` 或 `GET /api/v1/customer/auth/protection`
3
- * 回的題目變成送出時要帶的防護欄位。
2
+ * Bot protection (shared by forms and customer sign-in): turns the challenge from `GET /api/v1/forms/{id}/challenge` or `GET /api/v1/customer/auth/protection`
3
+ * into the protection fields to send on submit.
4
4
  *
5
- * - `provider: "kanorio"`:內建的 ALTCHA 工作量證明,這裡直接解(Web Crypto,瀏覽器與 Node 20 都能跑),payload 放 `_tk`。
6
- * - 第三方(Turnstile、reCAPTCHA、hCaptcha):用回傳的 `siteKey`、`action`(Turnstile 另有 `cData`)畫該家 widget,
7
- * 把 widget 給的 token 交給這裡,放 `captchaToken`。提供者由網站設定決定,伺服器依設定驗。
5
+ * - `provider: "kanorio"`: the built-in ALTCHA proof of work, solved here (Web Crypto; runs in browsers and Node 20), with the payload in `_tk`.
6
+ * - Third parties (Turnstile, reCAPTCHA, hCaptcha): render that widget with the returned `siteKey` and `action` (Turnstile also has `cData`),
7
+ * then pass the widget's token here to be sent as `captchaToken`. The provider is a site setting, and the server verifies accordingly.
8
8
  */
9
9
  const DEFAULT_MAX_NUMBER = 1_000_000;
10
10
  function toHex(buffer) {
@@ -16,8 +16,8 @@ function toBase64(text) {
16
16
  return Buffer.from(text, "utf8").toString("base64");
17
17
  }
18
18
  /**
19
- * 解內建題目:找出 `SHA-256(salt + n) === challenge` 的 n,回 ALTCHA payload(base64 JSON)。
20
- * 中階手機約 0.5~1 秒;`signal` 可在使用者離開頁面時中止。
19
+ * Solves the built-in challenge: finds n where `SHA-256(salt + n) === challenge` and returns the ALTCHA payload (base64 JSON).
20
+ * About 0.5 to 1 second on a mid-range phone; `signal` can abort it when the user leaves the page.
21
21
  */
22
22
  export async function solveAltchaChallenge(challenge, options = {}) {
23
23
  if (challenge.algorithm !== "SHA-256")
@@ -39,9 +39,9 @@ export async function solveAltchaChallenge(challenge, options = {}) {
39
39
  throw new Error("ALTCHA challenge has no solution within maxnumber.");
40
40
  }
41
41
  /**
42
- * 題目 → 防護欄位。內建題目在這裡解;第三方要先畫 widget 拿到 token,再以 `captchaToken` 傳進來。
42
+ * Challenge to protection fields. The built-in challenge is solved here; for a third party, render the widget first and pass its token in as `captchaToken`.
43
43
  *
44
- * @param context 題目綁的對象:表單 id,或 `customer-login:{siteId}`(內建題目才用)
44
+ * @param context What the challenge is bound to: the form id, or `customer-login:{siteId}` (built-in challenge only)
45
45
  */
46
46
  export async function protectionFromChallenge(challenge, options) {
47
47
  const base = { _hp: "", _wp: "", _co: "", _ts: options.renderedAt };
@@ -55,8 +55,8 @@ export async function protectionFromChallenge(challenge, options) {
55
55
  return { ...base, captchaToken: options.captchaToken, _ctx: options.context };
56
56
  }
57
57
  /**
58
- * 附件上傳票的防護欄位:內建時就是送出用的那份(同一個解、上傳不消費);第三方時用 challenge 的 `uploadToken`,
59
- * widget token 留給送出。
58
+ * Protection fields for an attachment upload ticket: with the built-in challenge they are the ones used for submitting (same solution; uploads do not consume it); with a third party, use the challenge's `uploadToken`
59
+ * and keep the widget token for the submit.
60
60
  */
61
61
  export function uploadProtectionFromChallenge(challenge, options) {
62
62
  const base = { _hp: "", _wp: "", _co: "", _ts: options.renderedAt };
@@ -1,13 +1,13 @@
1
1
  /**
2
- * Kanorio Webhook 驗章與 Next.js / Astro On-Demand ISR `revalidateTag` 處理器(階段 6)。
2
+ * Kanorio webhook signature verification and an on-demand `revalidateTag` handler for Next.js and Astro.
3
3
  *
4
- * 契約與伺服器端 `lib/notifications/team/adapters/webhook.ts` 及 docs/infrastructure/webhooks/README.md 一致:
5
- * - `X-Kanorio-Signature: t=<unix 秒>,v1=<hex>[,v1=<hex>]`,`v1` 是以端點簽章金鑰對 `${t}.${rawBody}` 計算的 HMAC-SHA256
6
- * - 金鑰輪替並行期內會同時附新舊兩個 `v1=`,任一相符即通過
7
- * - `X-Kanorio-Event` 為事件鍵、`X-Kanorio-Delivery` 為投遞 id(重試與重送間不變,可去重)
8
- * - 使用 Web Crypto API(`crypto.subtle`),於 Node 20+、Cloudflare Workers、Vercel Edge 皆零依賴可用
9
- * - 從 payload 的 `data.cacheTags` 取出標籤、加上命名空間(預設 `kanorio:`,與 `frameworkCacheTags` 同一套)後呼叫 `revalidateTag`;
10
- * 事件只列出真的變了的標籤(單筆內容的事件不帶 `site:<id>`,別的頁不動),不再自動補整站標籤
4
+ * The contract matches the server and the webhook documentation:
5
+ * - `X-Kanorio-Signature: t=<unix seconds>,v1=<hex>[,v1=<hex>]`, where `v1` is the HMAC-SHA256 of `${t}.${rawBody}` with the endpoint's signing secret
6
+ * - While a secret is being rotated, both the new and the old `v1=` are sent; a match on either passes
7
+ * - `X-Kanorio-Event` is the event key and `X-Kanorio-Delivery` is the delivery id (unchanged across retries and resends, so it can deduplicate)
8
+ * - Uses the Web Crypto API (`crypto.subtle`), with no dependencies on Node 20+, Cloudflare Workers and Vercel Edge
9
+ * - Takes the tags from the payload's `data.cacheTags`, adds the namespace (`kanorio:` by default, the same as `frameworkCacheTags`) and calls `revalidateTag`;
10
+ * an event lists only the tags that really changed (a single record's event does not carry `site:<id>`, so other pages stay cached), and no site-wide tag is added
11
11
  */
12
12
  export declare const WEBHOOK_SIGNATURE_HEADER = "x-kanorio-signature";
13
13
  export declare const WEBHOOK_DELIVERY_HEADER = "x-kanorio-delivery";
@@ -15,10 +15,10 @@ export declare const WEBHOOK_EVENT_HEADER = "x-kanorio-event";
15
15
  export declare const DEFAULT_WEBHOOK_TOLERANCE_SECONDS = 300;
16
16
  export interface VerifyWebhookSignatureOptions {
17
17
  rawBody: string;
18
- /** `X-Kanorio-Signature` 標頭原值(`t=<unix>,v1=<hex>[,v1=<hex>]`) */
18
+ /** The raw `X-Kanorio-Signature` header (`t=<unix>,v1=<hex>[,v1=<hex>]`) */
19
19
  signatureHeader: string | null | undefined;
20
20
  signingSecret: string;
21
- /** 允許的時間偏移秒數(預設 300 秒) */
21
+ /** Allowed clock difference in seconds (300 by default) */
22
22
  toleranceSeconds?: number;
23
23
  nowMs?: number;
24
24
  }
@@ -26,19 +26,19 @@ export interface ParsedWebhookSignature {
26
26
  timestamp: number;
27
27
  signatures: string[];
28
28
  }
29
- /** 解析 `t=<unix>,v1=<hex>[,v1=<hex>]`;格式不符回 null */
29
+ /** Parses `t=<unix>,v1=<hex>[,v1=<hex>]`; null when malformed */
30
30
  export declare function parseWebhookSignatureHeader(header: string | null | undefined): ParsedWebhookSignature | null;
31
- /** 計算單一 `v1` 值(hex);多把金鑰請各呼叫一次再以 `t=…,v1=…,v1=…` 組合 */
31
+ /** Computes one `v1` value (hex); for several secrets, call once each and join as `t=...,v1=...,v1=...` */
32
32
  export declare function computeWebhookSignature(signingSecret: string, timestamp: number | string, rawBody: string): Promise<string>;
33
- /** 產生與伺服器相同格式的 `X-Kanorio-Signature` 值(測試或本機模擬投遞用) */
33
+ /** Builds an `X-Kanorio-Signature` value in the server's format (for tests or simulating a delivery locally) */
34
34
  export declare function buildWebhookSignatureHeader(signingSecrets: string | readonly string[], rawBody: string, timestamp: number): Promise<string>;
35
35
  export declare function verifyWebhookSignature(options: VerifyWebhookSignatureOptions): Promise<boolean>;
36
- /** 通用 JSON webhook payload(`formatGenericWebhook`,version 1) */
36
+ /** The generic JSON webhook payload (version 1) */
37
37
  export interface WebhookEnvelope {
38
38
  version?: string;
39
- /** 與 `X-Kanorio-Delivery` 相同,重試與重送時不變 */
39
+ /** Same as `X-Kanorio-Delivery`; unchanged on retries and resends */
40
40
  id?: string;
41
- /** 事件鍵,例如 `collections.item.published`、`content.site.published` */
41
+ /** Event key, for example `collections.item.published` or `content.site.published` */
42
42
  event?: string;
43
43
  occurredAt?: string;
44
44
  websiteId?: string;
@@ -55,23 +55,23 @@ export interface WebhookEnvelope {
55
55
  };
56
56
  actionUrl?: string | null;
57
57
  }
58
- /** 事件要清的標籤(原始字串,不含命名空間);事件本身已列出該清的全部標籤 */
58
+ /** The tags an event asks to clear (raw strings, no namespace); the event already lists every tag to clear */
59
59
  export declare function extractWebhookCacheTags(payload: WebhookEnvelope): string[];
60
60
  export interface RevalidateHandlerOptions {
61
- /** Webhook 端點的簽章金鑰(`whsec_...`) */
61
+ /** The webhook endpoint's signing secret (`whsec_...`) */
62
62
  signingSecret: string;
63
- /** Next.js `revalidateTag` 或自訂快取失效函式 */
63
+ /** Next.js `revalidateTag` or your own cache invalidation function */
64
64
  revalidateTag: (tag: string) => void | Promise<void>;
65
65
  /**
66
- * 交給 `revalidateTag` 前加的命名空間(預設 `kanorio:`),要與讀取時 `frameworkCacheTags()`/`cacheTags.*` 打在快取上的標籤一致;
67
- * 傳 `""` 用原始標籤
66
+ * Namespace added before calling `revalidateTag` (`kanorio:` by default); it must match the tags that `frameworkCacheTags()` and `cacheTags.*` put on the cache when reading.
67
+ * Pass `""` to use the raw tags
68
68
  */
69
69
  tagPrefix?: string;
70
70
  toleranceSeconds?: number;
71
71
  onEvent?: (payload: WebhookEnvelope, revalidatedTags: string[]) => void | Promise<void>;
72
72
  }
73
73
  /**
74
- * 建立標準 `POST` Route Handler(直接 export 於 Next.js `app/api/revalidate/route.ts` 或 Astro endpoint)。
74
+ * Creates a standard `POST` route handler (export it from Next.js `app/api/revalidate/route.ts` or an Astro endpoint).
75
75
  */
76
76
  export declare function createRevalidateHandler(options: RevalidateHandlerOptions): (request: Request) => Promise<Response>;
77
77
  export declare const revalidate: {