@kanorio/sdk 1.0.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.
Files changed (81) hide show
  1. package/README.md +41 -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 +36 -20
  10. package/dist/forms.d.ts +33 -14
  11. package/dist/forms.js +20 -14
  12. package/dist/generated/delivery.d.ts +564 -13
  13. package/dist/generated/management.d.ts +790 -81
  14. package/dist/http.d.ts +13 -13
  15. package/dist/http.js +8 -8
  16. package/dist/image.d.ts +77 -0
  17. package/dist/image.js +78 -0
  18. package/dist/index.d.ts +2 -1
  19. package/dist/index.js +4 -3
  20. package/dist/locales.d.ts +22 -22
  21. package/dist/locales.js +12 -12
  22. package/dist/management.d.ts +5 -5
  23. package/dist/management.js +3 -3
  24. package/dist/next.d.ts +66 -0
  25. package/dist/next.js +58 -0
  26. package/dist/paginate.d.ts +3 -3
  27. package/dist/paginate.js +3 -3
  28. package/dist/preview.d.ts +13 -13
  29. package/dist/preview.js +11 -11
  30. package/dist/protection.d.ts +18 -18
  31. package/dist/protection.js +11 -11
  32. package/dist/revalidate.d.ts +22 -22
  33. package/dist/revalidate.js +14 -14
  34. package/dist/seo.d.ts +137 -21
  35. package/dist/seo.js +113 -21
  36. package/dist/server-key.d.ts +2 -2
  37. package/dist/server-key.js +2 -2
  38. package/dist/shared/api/delivery/cache-tags.d.ts +41 -39
  39. package/dist/shared/api/delivery/cache-tags.js +36 -34
  40. package/dist/shared/api/server-key.d.ts +32 -28
  41. package/dist/shared/api/server-key.js +41 -33
  42. package/dist/shared/business-registry/attribution.d.ts +5 -5
  43. package/dist/shared/business-registry/attribution.js +4 -4
  44. package/dist/shared/business-registry/define.d.ts +1 -1
  45. package/dist/shared/business-registry/define.js +1 -1
  46. package/dist/shared/business-registry/formats/eu-vat.js +4 -4
  47. package/dist/shared/business-registry/formats/hk-br.d.ts +2 -2
  48. package/dist/shared/business-registry/formats/hk-br.js +4 -4
  49. package/dist/shared/business-registry/formats/jp-trn.d.ts +3 -3
  50. package/dist/shared/business-registry/formats/jp-trn.js +4 -4
  51. package/dist/shared/business-registry/formats/kr-brn.d.ts +2 -2
  52. package/dist/shared/business-registry/formats/kr-brn.js +3 -3
  53. package/dist/shared/business-registry/formats/my.d.ts +3 -3
  54. package/dist/shared/business-registry/formats/my.js +4 -4
  55. package/dist/shared/business-registry/formats/sg-uen.js +4 -4
  56. package/dist/shared/business-registry/formats/tw-vat.d.ts +5 -5
  57. package/dist/shared/business-registry/formats/tw-vat.js +6 -6
  58. package/dist/shared/business-registry/index.js +1 -1
  59. package/dist/shared/business-registry/lookup-wire.d.ts +9 -9
  60. package/dist/shared/business-registry/lookup-wire.js +4 -4
  61. package/dist/shared/business-registry/normalize.d.ts +3 -3
  62. package/dist/shared/business-registry/normalize.js +4 -4
  63. package/dist/shared/business-registry/registry.d.ts +9 -9
  64. package/dist/shared/business-registry/registry.js +13 -13
  65. package/dist/shared/business-registry/types.d.ts +20 -20
  66. package/dist/shared/business-registry/types.js +6 -6
  67. package/dist/shared/localization/locale-path.d.ts +18 -18
  68. package/dist/shared/localization/locale-path.js +18 -18
  69. package/dist/shared/localization/request-locale.d.ts +16 -16
  70. package/dist/shared/localization/request-locale.js +13 -13
  71. package/dist/shared/seo/alternates.d.ts +26 -26
  72. package/dist/shared/seo/alternates.js +18 -18
  73. package/dist/shared/types/forms-logic.d.ts +28 -28
  74. package/dist/shared/types/forms-logic.js +27 -27
  75. package/dist/shared/types/number-input.d.ts +2 -2
  76. package/dist/shared/types/number-input.js +3 -3
  77. package/dist/shared/utils/redirect-matching.d.ts +33 -24
  78. package/dist/shared/utils/redirect-matching.js +73 -40
  79. package/dist/typed.d.ts +5 -5
  80. package/dist/typed.js +3 -3
  81. package/package.json +15 -10
package/dist/edge.js CHANGED
@@ -1,19 +1,19 @@
1
1
  /**
2
- * `@kanorio/sdk/edge`:AI 爬蟲管理與追蹤+301/302 轉址規則邊緣中介層(Stage F2)。
2
+ * `@kanorio/sdk/edge`: edge middleware for AI crawler management and tracking, plus 301/302 redirect rules.
3
3
  *
4
- * 設計原則(智慧放伺服器,SDK 越薄越好):
5
- * - 封鎖清單(`crawlerRules.blockedTokens`)與轉址規則(`/api/v1/redirects`)皆由 Kanorio Content Delivery API
6
- * 動態拉取並以記憶體短快取(預設 60 秒)保存,站主在後台更新規則後無須重部署前端即生效。
7
- * - 命中已知 AI 爬蟲時,自動非阻塞回報至 `POST {siteUrl}/api/v1/analytics/bot-hit`,
8
- * 讓後台 `/analytics/bots` 與 `/console`「AI 與安全防護」卡在自架前端(Headless)模式下同樣有完整數據。
9
- * - 多語網站(ADR-0010 決策 13;`features.locales`):與代管站同一套規則——主語系碼當前綴(`/zh-hant/about`)301 回無前綴;
10
- * `/{前綴}/llms.txt`、`llms-full.txt`、`rss.xml`、`feed.xml`、`feed.atom` 由邊緣回該語系的檔案;轉址規則以無前綴的路徑比對、
11
- * 站內目標接回同一個前綴;放行的決策帶 `locale`(語系、無前綴路徑)供前端路由
4
+ * Design (the logic lives on the server; the SDK stays thin):
5
+ * - The block list (`crawlerRules.blockedTokens`) and the redirect rules (`/api/v1/redirects`) are fetched from the Kanorio Content Delivery API
6
+ * and kept in a short in-memory cache (60 seconds by default), so rule changes in the dashboard apply without redeploying the front end.
7
+ * - A hit from a known AI crawler is reported, without blocking, to `POST {siteUrl}/api/v1/analytics/bot-hit`,
8
+ * so the dashboard's crawler analytics have full data for a self-hosted front end too.
9
+ * - Multilingual sites (`features.locales`) follow the same rules as hosted sites: the primary locale code used as a prefix (`/zh-hant/about`) redirects 301 to the unprefixed path;
10
+ * `/{prefix}/llms.txt`, `llms-full.txt`, `rss.xml`, `feed.xml` and `feed.atom` are answered at the edge with that locale's file; redirect rules match the unprefixed path
11
+ * and in-site targets get the same prefix back; an allowed decision carries `locale` (locale and unprefixed path) for the front end's routing
12
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
- import { matchLocalizedRedirect } from "./shared/utils/redirect-matching.js";
16
+ import { canonicalRedirectPath, matchLocalizedRedirect } from "./shared/utils/redirect-matching.js";
17
17
  export const CRAWLER_LIST_VERSION = "2026-10-22";
18
18
  export const EDGE_BOT_LIST = [
19
19
  { uaToken: "OAI-SearchBot", operator: "openai", intent: "retrieval", blockable: true },
@@ -75,7 +75,7 @@ export function isEdgeBotBlocked(bot, blockedTokens) {
75
75
  return blockedTokens.some((token) => token.toLowerCase() === botToken);
76
76
  }
77
77
  const INDEXNOW_KEY_PATH_RE = /^\/([a-f0-9]{32})\.txt$/i;
78
- /** `/{前綴}/llms.txt` 這類每語系的 SEO 衍生檔 → Delivery 端點(與代管站 `localized-seo-files.ts` 同一組檔名) */
78
+ /** Per-locale SEO files such as `/{prefix}/llms.txt` mapped to their Delivery endpoints (the same file names hosted sites use) */
79
79
  const LOCALIZED_SEO_FILES = {
80
80
  "llms.txt": "/seo/llms.txt",
81
81
  "llms-full.txt": "/seo/llms-full.txt",
@@ -108,7 +108,7 @@ export function createKanorioMiddleware(options) {
108
108
  try {
109
109
  const tasks = [];
110
110
  if (enableCrawlers || enableIndexNow || enableLocales) {
111
- // 爬蟲封鎖規則、IndexNow 金鑰與語系集合同一支 /site 回應,合併一次請求避免重複打 Delivery API
111
+ // Crawler block rules, the IndexNow key and the locale set come from the same /site response; one request avoids calling the Delivery API again
112
112
  tasks.push(f(`${apiBase}/site`, { headers: { Accept: "application/json" } })
113
113
  .then((r) => (r.ok ? r.json() : null))
114
114
  .then((data) => {
@@ -154,10 +154,25 @@ 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`;
160
- // 帶主機金鑰與來源 IP(只讀平台保證的標頭);沒設金鑰時照舊送,邊緣會擋下,回報遺失但不影響請求
175
+ // Sends the server key and the visitor IP (read only from headers the platform guarantees); without a key it is still sent, the edge blocks it and the report is lost without affecting the request
161
176
  const promise = serverKeyRequest({ serverKey: options.serverKey, visitorIp: visitorIpFromRequest(request) }, url)
162
177
  .then((viaServerKey) => f(url, {
163
178
  method: "POST",
@@ -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);
@@ -191,7 +207,7 @@ export function createKanorioMiddleware(options) {
191
207
  };
192
208
  }
193
209
  }
194
- // 語系(多語網站):主語系碼當前綴 301 回無前綴;每語系的 SEO 衍生檔由邊緣回應
210
+ // Locales (multilingual sites): the primary locale code as a prefix redirects 301 to the unprefixed path; per-locale SEO files are answered at the edge
195
211
  let locale;
196
212
  if (enableLocales && state.primaryLocale && state.locales.length > 1) {
197
213
  const resolved = resolveRequestLocale({ pathname, primaryLocale: state.primaryLocale, locales: state.locales });
@@ -215,13 +231,13 @@ export function createKanorioMiddleware(options) {
215
231
  }
216
232
  }
217
233
  catch {
218
- // 回源失敗:放行讓前端自己處理(通常是 404)
234
+ // Origin fetch failed: allow and let the front end handle it (usually a 404)
219
235
  }
220
236
  }
221
237
  }
222
238
  }
223
- // 轉址規則:精確優先、再最長 wildcard 前綴(與代管站同一份比對);多語網站的共用規則以無前綴的路徑比對、站內目標接回同一個前綴,
224
- // 帶語系的規則(翻譯代稱改名、語系停用、改前綴)以完整路徑比對、目標原樣(ADR-0010 決策 18)
239
+ // Redirect rules: exact match first, then the longest wildcard prefix (the same matching hosted sites use); on multilingual sites shared rules match the unprefixed path and in-site targets get the same prefix back,
240
+ // while locale-specific rules (a renamed translated slug, a disabled locale, a changed prefix) match the full path and use the target as is
225
241
  if (enableRedirects && state.redirects.length > 0) {
226
242
  const matchPath = locale ? locale.pathname : pathname;
227
243
  const hit = matchLocalizedRedirect(pathname, matchPath, state.redirects);
@@ -230,8 +246,8 @@ export function createKanorioMiddleware(options) {
230
246
  if (hit.target.startsWith("/")) {
231
247
  const root = !hit.scoped && locale?.prefixed ? localeRootPath(locale.locale, locale.primaryLocale, state.locales) : "";
232
248
  const localized = root ? `${root}${hit.target === "/" ? "" : hit.target}` : hit.target;
233
- // 迴圈保險:目標就是目前這一頁(例如 wildcard "/*" → "/")就不轉
234
- if (localized !== pathname) {
249
+ // Loop guard: do not redirect when the target is the current page (wildcard "/*" to "/", for example); compared in canonical form (raw and percent-encoded are the same path)
250
+ if (canonicalRedirectPath(localized) !== canonicalRedirectPath(pathname)) {
235
251
  return { action: "redirect", status: statusCode, location: new URL(`${localized}${url.search}`, url.origin).toString() };
236
252
  }
237
253
  }
package/dist/forms.d.ts CHANGED
@@ -1,17 +1,26 @@
1
1
  /**
2
- * Headless 表單 SDK 輔助:讀取表單定義 → 取得人機驗證題目 → 申請檔案上傳票 → 送出表單回覆。
3
- * 給自刻表單 UI 的開發者搭配 `useKanorioBotProtection` 或伺服器端流程使用。
2
+ * Helpers for headless forms: read the form definition, get the bot-protection challenge, request a file upload ticket, submit the response.
3
+ * For developers who build their own form UI, with `useKanorioBotProtection` or a server-side flow.
4
4
  *
5
- * 回應依三套 API 共用的契約(ADR-0006 決定 2-1):成功是原物件、失敗是 `{ error: { code, message, details? } }`。
6
- * 這裡把兩者收斂成 `{ ok: true, … }`/`{ ok: false, error }`,表單 UI 不必自己分辨 HTTP 狀態。
5
+ * Responses follow the contract shared by the three APIs: success is the object itself, failure is `{ error: { code, message, details? } }`.
6
+ * Here both become `{ ok: true, ... }` or `{ ok: false, error }`, so a form UI does not have to read HTTP statuses.
7
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";
12
- /** `GET /forms/{id}/challenge`:內建 ALTCHA 題目,或網站選的第三方 widget 參數(form-protection.md「人機驗證提供者」) */
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"];
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
- /** 送出與上傳都要帶的防護欄位(`_hp`、`_wp`、`_co` 為蜜罐,一律空字串) */
23
+ /** Protection fields sent with submissions and uploads (`_hp`, `_wp` and `_co` are honeypots, always empty strings) */
15
24
  export type FormProtectionFields = ProtectionFields;
16
25
  export interface FormUploadTicketRequest {
17
26
  fieldId: string;
@@ -23,7 +32,7 @@ export interface FormUploadTicketRequest {
23
32
  export interface FormApiError {
24
33
  code: string;
25
34
  message: string;
26
- /** INVALID_ANSWERS 時為各題的錯誤(`details.issues`) */
35
+ /** Per-question errors on INVALID_ANSWERS (`details.issues`) */
27
36
  issues?: unknown;
28
37
  details?: unknown;
29
38
  }
@@ -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
  /**
@@ -82,18 +101,18 @@ export interface FormTaxIdLookupRequest {
82
101
  protection?: FormProtectionFields | Record<string, unknown>;
83
102
  }
84
103
  /**
85
- * 由 challenge 組出防護欄位:表單顯示時呼叫 `challenge()`,送出時把結果交給這裡。
86
- * 內建題目在這裡解(工作量證明,約 0.5~1 秒);網站改用 Turnstile、reCAPTCHA、hCaptcha 時,先用 challenge 的
87
- * `siteKey`、`action`(Turnstile 另有 `cData`)畫該家 widget,再把 token 以 `captchaToken` 傳進來。
88
- * `renderedAt` 是表單顯示的時間(毫秒)。題目與 token 都是一次性的:每次送出前重新取。
104
+ * Builds the protection fields from a challenge: call `challenge()` when the form is shown, and pass the result here on submit.
105
+ * The built-in challenge is solved here (proof of work, about 0.5 to 1 second); when the site uses Turnstile, reCAPTCHA or hCaptcha, render that widget with the challenge's
106
+ * `siteKey` and `action` (Turnstile also has `cData`), then pass its token in as `captchaToken`.
107
+ * `renderedAt` is when the form was shown (milliseconds). Challenges and tokens are single-use: get a new one before every submit.
89
108
  */
90
109
  export declare function protectionFromChallenge(formId: string, challenge: FormChallengeResponse, renderedAt: number, options?: {
91
110
  captchaToken?: string;
92
111
  signal?: AbortSignal;
93
112
  }): Promise<FormProtectionFields>;
94
113
  /**
95
- * 附件上傳票的防護欄位:內建時傳入送出用的那份(`solved`,同一個解可重複用於上傳);
96
- * 網站改用第三方時用 challenge 的 `uploadToken`(widget token 是一次性的,留給送出)。
114
+ * Protection fields for an attachment upload ticket: with the built-in challenge, pass the ones used for submitting (`solved`; the same solution can be reused for uploads);
115
+ * with a third-party provider, use the challenge's `uploadToken` (the widget token is single-use and is kept for the submit).
97
116
  */
98
117
  export declare function uploadProtectionFromChallenge(formId: string, challenge: FormChallengeResponse, renderedAt: number, solved?: FormProtectionFields): FormProtectionFields | null;
99
118
  export interface FormsHelpersOptions extends ServerKeyOptions {
package/dist/forms.js CHANGED
@@ -1,32 +1,32 @@
1
1
  /**
2
- * Headless 表單 SDK 輔助:讀取表單定義 → 取得人機驗證題目 → 申請檔案上傳票 → 送出表單回覆。
3
- * 給自刻表單 UI 的開發者搭配 `useKanorioBotProtection` 或伺服器端流程使用。
2
+ * Helpers for headless forms: read the form definition, get the bot-protection challenge, request a file upload ticket, submit the response.
3
+ * For developers who build their own form UI, with `useKanorioBotProtection` or a server-side flow.
4
4
  *
5
- * 回應依三套 API 共用的契約(ADR-0006 決定 2-1):成功是原物件、失敗是 `{ error: { code, message, details? } }`。
6
- * 這裡把兩者收斂成 `{ ok: true, … }`/`{ ok: false, error }`,表單 UI 不必自己分辨 HTTP 狀態。
5
+ * Responses follow the contract shared by the three APIs: success is the object itself, failure is `{ error: { code, message, details? } }`.
6
+ * Here both become `{ ok: true, ... }` or `{ ok: false, error }`, so a form UI does not have to read HTTP statuses.
7
7
  */
8
8
  import { EDGE_CHALLENGE_CODE, edgeChallengeMessage, isEdgeChallenge, serverKeyRequest } from "./server-key.js";
9
9
  import { deliveryBaseUrl } from "./delivery.js";
10
10
  import { resolveVisibleFieldIds } from "./shared/types/forms-logic.js";
11
11
  import { protectionFromChallenge as protectionFieldsFromChallenge, uploadProtectionFromChallenge as uploadFieldsFromChallenge } from "./protection.js";
12
12
  /**
13
- * 由 challenge 組出防護欄位:表單顯示時呼叫 `challenge()`,送出時把結果交給這裡。
14
- * 內建題目在這裡解(工作量證明,約 0.5~1 秒);網站改用 Turnstile、reCAPTCHA、hCaptcha 時,先用 challenge 的
15
- * `siteKey`、`action`(Turnstile 另有 `cData`)畫該家 widget,再把 token 以 `captchaToken` 傳進來。
16
- * `renderedAt` 是表單顯示的時間(毫秒)。題目與 token 都是一次性的:每次送出前重新取。
13
+ * Builds the protection fields from a challenge: call `challenge()` when the form is shown, and pass the result here on submit.
14
+ * The built-in challenge is solved here (proof of work, about 0.5 to 1 second); when the site uses Turnstile, reCAPTCHA or hCaptcha, render that widget with the challenge's
15
+ * `siteKey` and `action` (Turnstile also has `cData`), then pass its token in as `captchaToken`.
16
+ * `renderedAt` is when the form was shown (milliseconds). Challenges and tokens are single-use: get a new one before every submit.
17
17
  */
18
18
  export function protectionFromChallenge(formId, challenge, renderedAt, options = {}) {
19
19
  return protectionFieldsFromChallenge(challenge, { context: formId, renderedAt, captchaToken: options.captchaToken, signal: options.signal });
20
20
  }
21
21
  /**
22
- * 附件上傳票的防護欄位:內建時傳入送出用的那份(`solved`,同一個解可重複用於上傳);
23
- * 網站改用第三方時用 challenge 的 `uploadToken`(widget token 是一次性的,留給送出)。
22
+ * Protection fields for an attachment upload ticket: with the built-in challenge, pass the ones used for submitting (`solved`; the same solution can be reused for uploads);
23
+ * with a third-party provider, use the challenge's `uploadToken` (the widget token is single-use and is kept for the submit).
24
24
  */
25
25
  export function uploadProtectionFromChallenge(formId, challenge, renderedAt, solved) {
26
26
  return uploadFieldsFromChallenge(challenge, { context: formId, renderedAt, solved });
27
27
  }
28
28
  async function readFormError(res, hasServerKey) {
29
- // 邊緣的 challenge 頁(伺服器端沒帶主機金鑰):回一個說得出下一步的錯誤
29
+ // The edge's challenge page (a server call without a server key): return an error that says what to do next
30
30
  if (isEdgeChallenge(res))
31
31
  return { code: EDGE_CHALLENGE_CODE, message: edgeChallengeMessage(hasServerKey) };
32
32
  const body = (await res.json().catch(() => null));
@@ -90,10 +90,10 @@ export function createFormsHelpers(options) {
90
90
  async lookupTaxId(formId, input) {
91
91
  const { protection, ...rest } = input;
92
92
  const res = await post(`/forms/${encodeURIComponent(formId)}/tax-id-lookup`, { ...rest, ...(protection ?? {}) }).catch(() => null);
93
- // 查不了不是錯誤:一律當成「沒有可帶入的資料」
93
+ // Being unable to look up is not an error: always treated as nothing to prefill
94
94
  if (!res || !res.ok)
95
95
  return { ok: false, reason: res?.status === 429 ? "rate_limited" : "unavailable" };
96
- // Delivery 的回應不帶 ok:`{ status, ... }`,沒查時是 `{ status: "UNAVAILABLE", reason }`
96
+ // Delivery responses carry no `ok`: `{ status, ... }`, or `{ status: "UNAVAILABLE", reason }` when no lookup ran
97
97
  const data = (await res.json().catch(() => null));
98
98
  if (!data || typeof data.status !== "string")
99
99
  return { ok: false, reason: "unavailable" };
@@ -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
  }