@kanorio/sdk 0.0.0-stage → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +66 -2
  3. package/dist/customer-oauth.d.ts +86 -0
  4. package/dist/customer-oauth.js +112 -0
  5. package/dist/customer.d.ts +176 -0
  6. package/dist/customer.js +125 -0
  7. package/dist/delivery.d.ts +35 -0
  8. package/dist/delivery.js +49 -0
  9. package/dist/edge.d.ts +108 -0
  10. package/dist/edge.js +287 -0
  11. package/dist/forms.d.ts +123 -0
  12. package/dist/forms.js +130 -0
  13. package/dist/generated/customer.d.ts +3157 -0
  14. package/dist/generated/delivery.d.ts +2408 -0
  15. package/dist/generated/management.d.ts +38333 -0
  16. package/dist/http.d.ts +73 -0
  17. package/dist/http.js +162 -0
  18. package/dist/index.d.ts +16 -0
  19. package/dist/index.js +17 -0
  20. package/dist/locales.d.ts +80 -0
  21. package/dist/locales.js +81 -0
  22. package/dist/management.d.ts +19 -0
  23. package/dist/management.js +22 -0
  24. package/dist/paginate.d.ts +18 -0
  25. package/dist/paginate.js +27 -0
  26. package/dist/preview.d.ts +40 -0
  27. package/dist/preview.js +131 -0
  28. package/dist/protection.d.ts +74 -0
  29. package/dist/protection.js +68 -0
  30. package/dist/revalidate.d.ts +84 -0
  31. package/dist/revalidate.js +143 -0
  32. package/dist/seo.d.ts +120 -0
  33. package/dist/seo.js +125 -0
  34. package/dist/server-key.d.ts +71 -0
  35. package/dist/server-key.js +103 -0
  36. package/dist/shared/api/delivery/cache-tags.d.ts +142 -0
  37. package/dist/shared/api/delivery/cache-tags.js +212 -0
  38. package/dist/shared/api/server-key.d.ts +90 -0
  39. package/dist/shared/api/server-key.js +260 -0
  40. package/dist/shared/business-registry/attribution.d.ts +14 -0
  41. package/dist/shared/business-registry/attribution.js +28 -0
  42. package/dist/shared/business-registry/define.d.ts +3 -0
  43. package/dist/shared/business-registry/define.js +4 -0
  44. package/dist/shared/business-registry/formats/eu-vat.d.ts +2 -0
  45. package/dist/shared/business-registry/formats/eu-vat.js +54 -0
  46. package/dist/shared/business-registry/formats/hk-br.d.ts +5 -0
  47. package/dist/shared/business-registry/formats/hk-br.js +23 -0
  48. package/dist/shared/business-registry/formats/jp-trn.d.ts +6 -0
  49. package/dist/shared/business-registry/formats/jp-trn.js +23 -0
  50. package/dist/shared/business-registry/formats/kr-brn.d.ts +6 -0
  51. package/dist/shared/business-registry/formats/kr-brn.js +30 -0
  52. package/dist/shared/business-registry/formats/my.d.ts +7 -0
  53. package/dist/shared/business-registry/formats/my.js +32 -0
  54. package/dist/shared/business-registry/formats/sg-uen.d.ts +1 -0
  55. package/dist/shared/business-registry/formats/sg-uen.js +21 -0
  56. package/dist/shared/business-registry/formats/tw-vat.d.ts +10 -0
  57. package/dist/shared/business-registry/formats/tw-vat.js +32 -0
  58. package/dist/shared/business-registry/index.d.ts +9 -0
  59. package/dist/shared/business-registry/index.js +10 -0
  60. package/dist/shared/business-registry/lookup-wire.d.ts +33 -0
  61. package/dist/shared/business-registry/lookup-wire.js +8 -0
  62. package/dist/shared/business-registry/normalize.d.ts +7 -0
  63. package/dist/shared/business-registry/normalize.js +12 -0
  64. package/dist/shared/business-registry/registry.d.ts +26 -0
  65. package/dist/shared/business-registry/registry.js +67 -0
  66. package/dist/shared/business-registry/types.d.ts +60 -0
  67. package/dist/shared/business-registry/types.js +10 -0
  68. package/dist/shared/localization/locale-path.d.ts +38 -0
  69. package/dist/shared/localization/locale-path.js +76 -0
  70. package/dist/shared/localization/request-locale.d.ts +42 -0
  71. package/dist/shared/localization/request-locale.js +61 -0
  72. package/dist/shared/seo/alternates.d.ts +61 -0
  73. package/dist/shared/seo/alternates.js +71 -0
  74. package/dist/shared/types/forms-logic.d.ts +96 -0
  75. package/dist/shared/types/forms-logic.js +209 -0
  76. package/dist/shared/types/number-input.d.ts +5 -0
  77. package/dist/shared/types/number-input.js +16 -0
  78. package/dist/shared/utils/redirect-matching.d.ts +76 -0
  79. package/dist/shared/utils/redirect-matching.js +181 -0
  80. package/dist/tax-id.d.ts +7 -0
  81. package/dist/tax-id.js +6 -0
  82. package/dist/typed.d.ts +85 -0
  83. package/dist/typed.js +28 -0
  84. package/package.json +86 -3
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Kanorio, Inc.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,67 @@
1
- # Temporary Holding Version
1
+ # @kanorio/sdk
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Typed `fetch` clients for the three Kanorio HTTP APIs, plus helpers for headless frontends (SEO rewrites, JSON-LD, webhook-driven cache revalidation). Types are generated from the OpenAPI documents with openapi-typescript, so each path, its parameters, request body and success response are checked at compile time.
4
+
5
+ | Client | API | Base URL | Credential |
6
+ |---|---|---|---|
7
+ | `createManagementClient` | Management API | `https://app.kanorio.com/api/v1` | Personal access token, OAuth access token or service account token. Server-side only. |
8
+ | `createDeliveryClient` | Content Delivery API | `https://{site}/api/v1` | None for reads (anonymous and edge-cached). A server key for writes sent from your own server. |
9
+ | `createCustomerClient` | Customer API | `https://{site}/api/v1/customer` | Customer access token from passwordless sign-in, plus a server key when your own server makes the call. |
10
+
11
+ ```ts
12
+ import { createCustomerClient, createDeliveryClient, createManagementClient } from "@kanorio/sdk";
13
+
14
+ const management = createManagementClient({ token: process.env.KANORIO_TOKEN! });
15
+ const sites = await management.get("/sites");
16
+
17
+ const delivery = createDeliveryClient({ siteUrl: "https://example.com" });
18
+ const { product } = await delivery.get("/products/{slug}", { params: { slug: "react-course" } });
19
+
20
+ const customer = createCustomerClient({
21
+ siteUrl: "https://example.com",
22
+ token: () => localStorage.getItem("kanorio.customer.token"),
23
+ });
24
+ ```
25
+
26
+ When your own server writes on a visitor's behalf (submitting a form, exchanging a customer sign-in code, reporting crawler hits from middleware), pass a server key and the visitor's IP. Without the key, server-to-server writes are stopped by an edge challenge and the SDK throws `KanorioEdgeChallengeError`.
27
+
28
+ ```ts
29
+ import { createFormsHelpers, visitorIpFromRequest } from "@kanorio/sdk";
30
+
31
+ const forms = createFormsHelpers({
32
+ siteUrl: "https://example.com",
33
+ serverKey: process.env.KANORIO_SERVER_KEY, // knr_sk_…, a service account of type "Website server"
34
+ visitorIp: visitorIpFromRequest(request),
35
+ });
36
+ ```
37
+
38
+ A server key is refused in browser code, requires HTTPS, and cannot call the Management API. `visitorIpFromRequest` reads the IP on Cloudflare, Vercel, Netlify and Fly.io; on other hosts pass the IP your platform gives you, or name a header your own reverse proxy overwrites with `{ trustedHeader }`.
39
+
40
+ Errors throw `KanorioApiError` with `code`, `status` and `details`. Deprecated operations surface through the `onDeprecation` callback (the `Deprecation`, `Sunset` and `Link` response headers).
41
+
42
+ ## Tax id validation
43
+
44
+ `@kanorio/sdk/tax-id` validates tax ids the way the hosted checkout and forms do, without a network call:
45
+
46
+ ```ts
47
+ import { isBlockingTaxIdIssue, listTaxIdTypes, validateTaxIdFormat } from "@kanorio/sdk/tax-id";
48
+
49
+ listTaxIdTypes("TW"); // ["tw_vat"]
50
+ const result = validateTaxIdFormat({ country: "TW", value: "0459-5252" });
51
+ if (result.ok) save(result.normalized); // "04595252"
52
+ else if (isBlockingTaxIdIssue(result)) showError(result.issue); // "FORMAT" | "CHECKSUM" | "EMPTY"
53
+ ```
54
+
55
+ Type names follow Stripe (`tw_vat`, `hk_br`, `jp_trn`, `kr_brn`, `eu_vat`, `sg_uen`, `my_itn`, `my_sst`). A country with no registered type returns `UNSUPPORTED`; accept the value as free text. Types whose rules are not yet verified against the authority's own documents report `enforcement: "warn"`: show a hint, do not block.
56
+
57
+ ## Compatibility
58
+
59
+ - ES modules only. Use `import`. CommonJS code can `require("@kanorio/sdk")` on Node.js 20.19 / 22.12 or later (this is how `next.config.ts` loads it); on older versions use `await import("@kanorio/sdk")`.
60
+ - Node.js 20 or later for server-side use.
61
+ - Within `1.x`, methods, options and response fields are only added. Removing or changing one is a new major version.
62
+
63
+ ## Documentation and support
64
+
65
+ - Documentation: <https://kanorio.com/en/developers/sdk>
66
+ - Changes: [CHANGELOG.md](./CHANGELOG.md). Released together with `@kanorio/elements` and `@kanorio/cli` under one version number.
67
+ - Questions and bug reports: <support@kanorio.com>. To report a security issue, write to <security@kanorio.com> instead of opening a public report.
@@ -0,0 +1,86 @@
1
+ /**
2
+ * OAuth 2.1 authorization code + PKCE for the hosted sign-in page: your own front end does not draw a sign-in screen.
3
+ * It sends the customer to Kanorio's hosted `/account/login`, and on return exchanges the authorization code for a `knr_cat_` bearer token (the same token `<kanorio-account>` uses).
4
+ *
5
+ * In the browser: `startHostedCustomerLogin()` creates the PKCE pair and state, stores them in sessionStorage and navigates to the sign-in page;
6
+ * back on `redirectUri`, `completeHostedCustomerLogin()` reads `?code&state`, checks the state, exchanges the token and clears the query.
7
+ * On a server (or when you manage tokens yourself): `exchangeHostedLoginCode()`, `refreshCustomerToken()` and `revokeCustomerToken()`.
8
+ */
9
+ import type { ServerKeyOptions } from "./server-key.js";
10
+ export interface HostedLoginGrant {
11
+ accessToken: string;
12
+ tokenType: "Bearer";
13
+ expiresIn: number;
14
+ expiresAt: string;
15
+ refreshToken: string;
16
+ refreshTokenExpiresIn: number;
17
+ contactId: string;
18
+ }
19
+ /** PKCE: a random verifier of 43 to 128 characters; challenge = BASE64URL(SHA-256(verifier)) (RFC 7636; OAuth 2.1 allows S256 only) */
20
+ export declare function createPkcePair(): Promise<{
21
+ verifier: string;
22
+ challenge: string;
23
+ method: "S256";
24
+ }>;
25
+ export interface HostedLoginUrlParams {
26
+ /** For example `https://demo.kanorio.com`: the site URL that serves the hosted sign-in page */
27
+ siteUrl: string;
28
+ /** Site id (`id` from `GET /site`); the OAuth client_id */
29
+ clientId: string;
30
+ /** Where to return after sign-in: https, and its origin must be in the site's allowed origins */
31
+ redirectUri: string;
32
+ codeChallenge: string;
33
+ state: string;
34
+ /** Locale path root of the sign-in page (multilingual sites, for example `/en`); omit for the primary locale */
35
+ localeRoot?: string;
36
+ }
37
+ export declare function buildHostedLoginUrl(params: HostedLoginUrlParams): string;
38
+ export interface StartHostedLoginOptions {
39
+ siteUrl: string;
40
+ clientId: string;
41
+ /** Defaults to the current page (without code and state) */
42
+ redirectUri?: string;
43
+ localeRoot?: string;
44
+ /** Where the PKCE verifier and state are kept; sessionStorage by default (readable only when returning in the same tab) */
45
+ storage?: Storage;
46
+ /** Navigate yourself (with a router, for example); `window.location.assign` by default */
47
+ navigate?: (url: string) => void;
48
+ }
49
+ /** Step one: create the PKCE pair and state, remember them, and send the customer to the hosted sign-in page */
50
+ export declare function startHostedCustomerLogin(options: StartHostedLoginOptions): Promise<void>;
51
+ export interface CompleteHostedLoginOptions {
52
+ siteUrl: string;
53
+ clientId: string;
54
+ storage?: Storage;
55
+ /** Store the token in `localStorage["kanorio.customer.token"]` after the exchange (other Elements read it); true by default */
56
+ storeToken?: boolean;
57
+ /** Remove code and state from the URL (so they stay out of history and Referer); true by default */
58
+ cleanUrl?: boolean;
59
+ }
60
+ /**
61
+ * Step two: call this back on redirectUri. Returns null when the URL has no `code`; throws when the state does not match or the token exchange fails.
62
+ */
63
+ export declare function completeHostedCustomerLogin(options: CompleteHostedLoginOptions): Promise<HostedLoginGrant | null>;
64
+ /**
65
+ * Exchanges an authorization code for tokens (any environment). When called on a **server**, pass `serverKey` (and `visitorIp`):
66
+ * a server-to-server write without a server key is blocked at the edge. Do not pass it in the browser.
67
+ */
68
+ export declare function exchangeHostedLoginCode(params: {
69
+ siteUrl: string;
70
+ clientId: string;
71
+ code: string;
72
+ codeVerifier: string;
73
+ redirectUri: string;
74
+ } & ServerKeyOptions): Promise<HostedLoginGrant>;
75
+ /** Rotation: get a new access and refresh token; the old refresh token is revoked immediately, so store both returned tokens */
76
+ export declare function refreshCustomerToken(params: {
77
+ siteUrl: string;
78
+ clientId: string;
79
+ refreshToken: string;
80
+ } & ServerKeyOptions): Promise<HostedLoginGrant>;
81
+ /** Revokes an access or refresh token (ends the whole session) */
82
+ export declare function revokeCustomerToken(params: {
83
+ siteUrl: string;
84
+ token: string;
85
+ tokenTypeHint?: "access_token" | "refresh_token";
86
+ } & ServerKeyOptions): Promise<void>;
@@ -0,0 +1,112 @@
1
+ /**
2
+ * OAuth 2.1 authorization code + PKCE for the hosted sign-in page: your own front end does not draw a sign-in screen.
3
+ * It sends the customer to Kanorio's hosted `/account/login`, and on return exchanges the authorization code for a `knr_cat_` bearer token (the same token `<kanorio-account>` uses).
4
+ *
5
+ * In the browser: `startHostedCustomerLogin()` creates the PKCE pair and state, stores them in sessionStorage and navigates to the sign-in page;
6
+ * back on `redirectUri`, `completeHostedCustomerLogin()` reads `?code&state`, checks the state, exchanges the token and clears the query.
7
+ * On a server (or when you manage tokens yourself): `exchangeHostedLoginCode()`, `refreshCustomerToken()` and `revokeCustomerToken()`.
8
+ */
9
+ import { createCustomerClient, writeStoredCustomerToken } from "./customer.js";
10
+ const PKCE_STORAGE_KEY = "kanorio.customer.pkce";
11
+ function toGrant(wire) {
12
+ return {
13
+ accessToken: wire.access_token,
14
+ tokenType: wire.token_type,
15
+ expiresIn: wire.expires_in,
16
+ expiresAt: wire.expires_at,
17
+ refreshToken: wire.refresh_token,
18
+ refreshTokenExpiresIn: wire.refresh_token_expires_in,
19
+ contactId: wire.contactId,
20
+ };
21
+ }
22
+ function base64url(bytes) {
23
+ let binary = "";
24
+ for (const byte of bytes)
25
+ binary += String.fromCharCode(byte);
26
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
27
+ }
28
+ function randomString(bytes = 32) {
29
+ const buffer = new Uint8Array(bytes);
30
+ crypto.getRandomValues(buffer);
31
+ return base64url(buffer);
32
+ }
33
+ /** PKCE: a random verifier of 43 to 128 characters; challenge = BASE64URL(SHA-256(verifier)) (RFC 7636; OAuth 2.1 allows S256 only) */
34
+ export async function createPkcePair() {
35
+ const verifier = randomString(32);
36
+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier));
37
+ return { verifier, challenge: base64url(new Uint8Array(digest)), method: "S256" };
38
+ }
39
+ export function buildHostedLoginUrl(params) {
40
+ const base = params.siteUrl.replace(/\/+$/, "");
41
+ const url = new URL(`${base}${params.localeRoot ?? ""}/account/login`);
42
+ url.searchParams.set("client_id", params.clientId);
43
+ url.searchParams.set("redirect_uri", params.redirectUri);
44
+ url.searchParams.set("code_challenge", params.codeChallenge);
45
+ url.searchParams.set("code_challenge_method", "S256");
46
+ url.searchParams.set("state", params.state);
47
+ return url.toString();
48
+ }
49
+ function currentRedirectUri() {
50
+ const url = new URL(window.location.href);
51
+ url.searchParams.delete("code");
52
+ url.searchParams.delete("state");
53
+ url.hash = "";
54
+ return url.toString();
55
+ }
56
+ /** Step one: create the PKCE pair and state, remember them, and send the customer to the hosted sign-in page */
57
+ export async function startHostedCustomerLogin(options) {
58
+ const storage = options.storage ?? sessionStorage;
59
+ const redirectUri = options.redirectUri ?? currentRedirectUri();
60
+ const pkce = await createPkcePair();
61
+ const state = randomString(16);
62
+ storage.setItem(PKCE_STORAGE_KEY, JSON.stringify({ verifier: pkce.verifier, state, redirectUri }));
63
+ const url = buildHostedLoginUrl({ siteUrl: options.siteUrl, clientId: options.clientId, redirectUri, codeChallenge: pkce.challenge, state, localeRoot: options.localeRoot });
64
+ (options.navigate ?? ((target) => window.location.assign(target)))(url);
65
+ }
66
+ /**
67
+ * Step two: call this back on redirectUri. Returns null when the URL has no `code`; throws when the state does not match or the token exchange fails.
68
+ */
69
+ export async function completeHostedCustomerLogin(options) {
70
+ const url = new URL(window.location.href);
71
+ const code = url.searchParams.get("code");
72
+ const state = url.searchParams.get("state");
73
+ if (!code)
74
+ return null;
75
+ const storage = options.storage ?? sessionStorage;
76
+ const raw = storage.getItem(PKCE_STORAGE_KEY);
77
+ storage.removeItem(PKCE_STORAGE_KEY);
78
+ const saved = raw ? JSON.parse(raw) : null;
79
+ if (!saved || saved.state !== state)
80
+ throw new Error("Hosted sign-in state mismatch; start the sign-in again.");
81
+ if (options.cleanUrl !== false) {
82
+ url.searchParams.delete("code");
83
+ url.searchParams.delete("state");
84
+ window.history.replaceState(window.history.state, "", url.toString());
85
+ }
86
+ const grant = await exchangeHostedLoginCode({ siteUrl: options.siteUrl, clientId: options.clientId, code, codeVerifier: saved.verifier, redirectUri: saved.redirectUri });
87
+ if (options.storeToken !== false)
88
+ writeStoredCustomerToken(grant.accessToken);
89
+ return grant;
90
+ }
91
+ /**
92
+ * Exchanges an authorization code for tokens (any environment). When called on a **server**, pass `serverKey` (and `visitorIp`):
93
+ * a server-to-server write without a server key is blocked at the edge. Do not pass it in the browser.
94
+ */
95
+ export async function exchangeHostedLoginCode(params) {
96
+ const client = createCustomerClient({ siteUrl: params.siteUrl, serverKey: params.serverKey, visitorIp: params.visitorIp });
97
+ const wire = (await client.post("/auth/oauth2/token", {
98
+ body: { grant_type: "authorization_code", code: params.code, code_verifier: params.codeVerifier, redirect_uri: params.redirectUri, client_id: params.clientId },
99
+ }));
100
+ return toGrant(wire);
101
+ }
102
+ /** Rotation: get a new access and refresh token; the old refresh token is revoked immediately, so store both returned tokens */
103
+ export async function refreshCustomerToken(params) {
104
+ const client = createCustomerClient({ siteUrl: params.siteUrl, serverKey: params.serverKey, visitorIp: params.visitorIp });
105
+ const wire = (await client.post("/auth/oauth2/token", { body: { grant_type: "refresh_token", refresh_token: params.refreshToken, client_id: params.clientId } }));
106
+ return toGrant(wire);
107
+ }
108
+ /** Revokes an access or refresh token (ends the whole session) */
109
+ export async function revokeCustomerToken(params) {
110
+ const client = createCustomerClient({ siteUrl: params.siteUrl, serverKey: params.serverKey, visitorIp: params.visitorIp });
111
+ await client.post("/auth/oauth2/revoke", { body: { token: params.token, ...(params.tokenTypeHint ? { token_type_hint: params.tokenTypeHint } : {}) } });
112
+ }
@@ -0,0 +1,176 @@
1
+ /**
2
+ * Customer API (`https://{site}/api/v1/customer`, Bearer = the customer's session token).
3
+ * Browsers can call it directly (CORS follows the site's allowed origins). Types are generated from the Customer API's OpenAPI document; successful responses carry no `ok`, and errors use the shared envelope.
4
+ *
5
+ * Besides `createCustomerClient` there is `createCustomerContentClient`, which implements the
6
+ * content client interface (`openUnit`, `reportProgress`, `submitQuiz`, `getCertificate`) that `@kanorio/elements` injects into `<kanorio-unit>`.
7
+ */
8
+ import type { paths as CustomerPaths } from "./generated/customer.js";
9
+ import { type HttpClientOptions } from "./http.js";
10
+ import { type TypedClient } from "./typed.js";
11
+ export type { CustomerPaths };
12
+ export type CustomerClient = TypedClient<CustomerPaths>;
13
+ export type CustomerTokenSource = string | null | undefined | (() => string | null | undefined | Promise<string | null | undefined>);
14
+ export interface CustomerClientOptions extends Omit<HttpClientOptions, "baseUrl" | "headers"> {
15
+ /** For example `https://demo.kanorio.com` */
16
+ siteUrl: string;
17
+ /** The customer's bearer token; may be null for anonymous endpoints (challenge, verify) */
18
+ token?: CustomerTokenSource;
19
+ headers?: HeadersInit;
20
+ /**
21
+ * Content locale (multilingual sites): sent as `locale` when opening a unit, and titles follow it. Omit to use the customer's own locale or the primary locale.
22
+ * Only affects `createCustomerContentClient`; typically the Elements provider passes the page locale in.
23
+ */
24
+ locale?: string | null;
25
+ }
26
+ export declare function customerBaseUrl(siteUrl: string): string;
27
+ export declare function createCustomerClient(options: CustomerClientOptions): CustomerClient;
28
+ /** Default place the browser keeps the bearer token (`<kanorio-login>` writes it, other components read it) */
29
+ export declare const CUSTOMER_TOKEN_STORAGE_KEY = "kanorio.customer.token";
30
+ export declare function readStoredCustomerToken(storage?: Storage | undefined): string | null;
31
+ export declare function writeStoredCustomerToken(token: string | null, storage?: Storage | undefined): void;
32
+ /** One `captions` entry: a caption track, one per locale; `source` says AI-generated or uploaded by the owner, and `edited` means the owner changed the text. Hidden by default until the learner turns captions on */
33
+ type OpenUnitRendition = {
34
+ kind: "original" | "mp4" | "hls" | "poster" | "thumbnails" | "captions" | "chapters";
35
+ url: string;
36
+ mimeType: string;
37
+ width?: number;
38
+ height?: number;
39
+ bytes?: number;
40
+ locale?: string;
41
+ source?: "ai" | "upload" | "translation";
42
+ edited?: boolean;
43
+ };
44
+ /** `renditions`, `poster`, `thumbnails`, `streaming`: the video's streaming sources (play `hls` when present; `url` is the original file); `expiresIn` depends on the video's length */
45
+ type OpenUnitOk = {
46
+ ok: true;
47
+ mode: "read" | "download";
48
+ url: string;
49
+ expiresIn: number;
50
+ title: string | null;
51
+ fileName: string;
52
+ mimeType: string | null;
53
+ allowDownload: boolean;
54
+ renditions?: OpenUnitRendition[];
55
+ poster?: string | null;
56
+ thumbnails?: string | null;
57
+ streaming?: "none" | "partial" | "ready";
58
+ };
59
+ type OpenUnitFail = {
60
+ ok: false;
61
+ code: string;
62
+ availableAt?: string;
63
+ };
64
+ /** One report: besides position and duration, the server only records watch history (plays, hours, retention) when sessionId and segments are sent; see the Customer API docs */
65
+ type ProgressReportItem = {
66
+ positionSeconds?: number;
67
+ durationSeconds?: number;
68
+ completed?: boolean;
69
+ opened?: boolean;
70
+ sessionId?: string;
71
+ segments?: Array<[number, number] | [number, number, number]>;
72
+ startupMs?: number;
73
+ stallCount?: number;
74
+ stallMs?: number;
75
+ rendition?: number;
76
+ seekTargets?: number[];
77
+ device?: "desktop" | "mobile" | "tablet";
78
+ };
79
+ type ProgressOk = {
80
+ ok: true;
81
+ unit: "not_started" | "in-progress" | "completed";
82
+ /** Share of an audio or video unit that was watched, 0 to 100; null without a duration or segment data; absent on older servers */
83
+ unitCoveredPercent?: number | null;
84
+ /** null for a `lite` heartbeat when the unit was not just completed */
85
+ deliverable: {
86
+ id: string;
87
+ percent: number;
88
+ completed: boolean;
89
+ completedAt?: string | null;
90
+ } | null;
91
+ deliverableJustCompleted: boolean;
92
+ };
93
+ type ProgressFail = {
94
+ ok: false;
95
+ code: string;
96
+ };
97
+ type QuizSubmitOk = {
98
+ ok: true;
99
+ /** graded: passing completes the unit; practice: submitting completes it and no pass mark applies. Absent on older servers */
100
+ mode?: "graded" | "practice";
101
+ score: number;
102
+ correct: number;
103
+ total: number;
104
+ passed: boolean;
105
+ perQuestion: Record<string, boolean>;
106
+ attemptsUsed: number;
107
+ maxAttempts: number | null;
108
+ canRetry: boolean;
109
+ reveal: {
110
+ questions: Array<{
111
+ id: string;
112
+ correctOptionIds: string[]; /** Accepted answers for short-answer and number questions; absent on older servers */
113
+ acceptedAnswers?: string[];
114
+ explanation: string | null;
115
+ }>;
116
+ } | null;
117
+ unit: "not_started" | "in-progress" | "completed";
118
+ deliverable: {
119
+ id: string;
120
+ percent: number;
121
+ completed: boolean;
122
+ completedAt?: string | null;
123
+ };
124
+ deliverableJustCompleted: boolean;
125
+ };
126
+ type CertificateOk = {
127
+ ok: true;
128
+ certificate: {
129
+ serial: string;
130
+ issuedAt: string;
131
+ url: string;
132
+ expiresIn: number;
133
+ };
134
+ };
135
+ type TranscriptOk = {
136
+ ok: true;
137
+ unitId: string;
138
+ locale: string;
139
+ source: "ai" | "upload" | "translation";
140
+ edited: boolean;
141
+ segments: Array<{
142
+ s: number;
143
+ e: number;
144
+ t: string;
145
+ }>;
146
+ tracks: Array<{
147
+ locale: string;
148
+ source: "ai" | "upload" | "translation";
149
+ edited: boolean;
150
+ }>;
151
+ };
152
+ export interface CustomerContentClientLike {
153
+ /** `options.attachmentId`: download URL for one of the unit's attachments (`mode` is ignored) */
154
+ openUnit(unitId: string, mode: "read" | "download", options?: {
155
+ attachmentId?: string;
156
+ }): Promise<OpenUnitOk | OpenUnitFail>;
157
+ reportProgress(input: {
158
+ unitId: string;
159
+ reports: ProgressReportItem[]; /** Heartbeat: skips the deliverable-level result unless this report completed the unit */
160
+ lite?: boolean;
161
+ }): Promise<ProgressOk | ProgressFail>;
162
+ /** Submits a quiz, graded by the server; passing a graded quiz, or submitting a practice quiz, marks the unit complete. Multiple-choice values are option ids; short-answer and number questions take one string */
163
+ submitQuiz(input: {
164
+ unitId: string;
165
+ answers: Record<string, string[]>;
166
+ }): Promise<QuizSubmitOk | ProgressFail>;
167
+ /** Short-lived download URL of the completion certificate (course completed and certificates enabled) */
168
+ getCertificate(deliverableId: string): Promise<CertificateOk | ProgressFail>;
169
+ /** The unit's transcript (same set as the caption tracks; omit `locale` for the customer's own locale, and the original is returned when no track matches) */
170
+ getTranscript(unitId: string, locale?: string | null): Promise<TranscriptOk | ProgressFail>;
171
+ }
172
+ /**
173
+ * Content client for Elements: errors are returned as `{ ok: false, code }` instead of thrown (a result type, unrelated to the HTTP shape), and components show locked, not released or expired by code.
174
+ * When anonymous (no token), `openUnit` goes through the Delivery API's `POST /api/v1/units/:id/open` (free preview units only).
175
+ */
176
+ export declare function createCustomerContentClient(options: CustomerClientOptions): CustomerContentClientLike;
@@ -0,0 +1,125 @@
1
+ /**
2
+ * Customer API (`https://{site}/api/v1/customer`, Bearer = the customer's session token).
3
+ * Browsers can call it directly (CORS follows the site's allowed origins). Types are generated from the Customer API's OpenAPI document; successful responses carry no `ok`, and errors use the shared envelope.
4
+ *
5
+ * Besides `createCustomerClient` there is `createCustomerContentClient`, which implements the
6
+ * content client interface (`openUnit`, `reportProgress`, `submitQuiz`, `getCertificate`) that `@kanorio/elements` injects into `<kanorio-unit>`.
7
+ */
8
+ import { createHttpClient, KanorioApiError } from "./http.js";
9
+ import { createTypedClient } from "./typed.js";
10
+ export function customerBaseUrl(siteUrl) {
11
+ return `${siteUrl.replace(/\/+$/, "")}/api/v1/customer`;
12
+ }
13
+ async function resolveToken(source) {
14
+ const value = typeof source === "function" ? await source() : source;
15
+ return value ? value : null;
16
+ }
17
+ export function createCustomerClient(options) {
18
+ const { siteUrl, token, headers, ...rest } = options;
19
+ const http = createHttpClient({
20
+ ...rest,
21
+ baseUrl: customerBaseUrl(siteUrl),
22
+ headers: async () => {
23
+ const h = new Headers(headers);
24
+ const value = await resolveToken(token);
25
+ if (value)
26
+ h.set("authorization", `Bearer ${value}`);
27
+ return h;
28
+ },
29
+ });
30
+ return createTypedClient(http);
31
+ }
32
+ /** Default place the browser keeps the bearer token (`<kanorio-login>` writes it, other components read it) */
33
+ export const CUSTOMER_TOKEN_STORAGE_KEY = "kanorio.customer.token";
34
+ /** `localStorage`, or undefined where there is none or reading it throws (a sandboxed frame without `allow-same-origin`, storage blocked) */
35
+ function defaultStorage() {
36
+ try {
37
+ return typeof localStorage === "undefined" ? undefined : localStorage;
38
+ }
39
+ catch {
40
+ return undefined;
41
+ }
42
+ }
43
+ export function readStoredCustomerToken(storage = defaultStorage()) {
44
+ try {
45
+ return storage?.getItem(CUSTOMER_TOKEN_STORAGE_KEY) ?? null;
46
+ }
47
+ catch {
48
+ return null;
49
+ }
50
+ }
51
+ export function writeStoredCustomerToken(token, storage = defaultStorage()) {
52
+ try {
53
+ if (token)
54
+ storage?.setItem(CUSTOMER_TOKEN_STORAGE_KEY, token);
55
+ else
56
+ storage?.removeItem(CUSTOMER_TOKEN_STORAGE_KEY);
57
+ }
58
+ catch {
59
+ // Private mode or storage disabled: ignore
60
+ }
61
+ }
62
+ /** Successful HTTP responses carry no `ok`; the result types shared by components use `ok` to tell success from failure */
63
+ function succeed(body) {
64
+ return { ...body, ok: true };
65
+ }
66
+ /**
67
+ * Content client for Elements: errors are returned as `{ ok: false, code }` instead of thrown (a result type, unrelated to the HTTP shape), and components show locked, not released or expired by code.
68
+ * When anonymous (no token), `openUnit` goes through the Delivery API's `POST /api/v1/units/:id/open` (free preview units only).
69
+ */
70
+ export function createCustomerContentClient(options) {
71
+ const client = createCustomerClient(options);
72
+ const anonymous = createHttpClient({ ...options, baseUrl: `${options.siteUrl.replace(/\/+$/, "")}/api/v1` });
73
+ const toFail = (error) => {
74
+ if (error instanceof KanorioApiError)
75
+ return { ok: false, code: error.code, ...(error.availableAt ? { availableAt: error.availableAt } : {}) };
76
+ return { ok: false, code: "NETWORK_ERROR" };
77
+ };
78
+ return {
79
+ async openUnit(unitId, mode, openOptions) {
80
+ try {
81
+ const token = await resolveToken(options.token);
82
+ if (!token)
83
+ return succeed(await anonymous.request("POST", `units/${encodeURIComponent(unitId)}/open`, { body: { mode } }));
84
+ const body = openOptions?.attachmentId ? { mode, attachmentId: openOptions.attachmentId } : { mode };
85
+ return succeed((await client.post("/units/{id}/open", { params: { id: unitId }, query: options.locale ? { locale: options.locale } : {}, body })));
86
+ }
87
+ catch (error) {
88
+ return toFail(error);
89
+ }
90
+ },
91
+ async reportProgress(input) {
92
+ try {
93
+ return succeed((await client.post("/progress", { body: input })));
94
+ }
95
+ catch (error) {
96
+ return toFail(error);
97
+ }
98
+ },
99
+ async submitQuiz(input) {
100
+ try {
101
+ return succeed((await client.post("/units/{id}/quiz", { params: { id: input.unitId }, body: { answers: input.answers } })));
102
+ }
103
+ catch (error) {
104
+ return toFail(error);
105
+ }
106
+ },
107
+ async getCertificate(deliverableId) {
108
+ try {
109
+ return succeed((await client.get("/deliverables/{deliverableId}/certificate", { params: { deliverableId } })));
110
+ }
111
+ catch (error) {
112
+ return toFail(error);
113
+ }
114
+ },
115
+ async getTranscript(unitId, locale) {
116
+ try {
117
+ const wanted = locale ?? options.locale;
118
+ return succeed((await client.get("/units/{id}/transcript", { params: { id: unitId }, query: wanted ? { locale: wanted } : {} })));
119
+ }
120
+ catch (error) {
121
+ return toFail(error);
122
+ }
123
+ },
124
+ };
125
+ }
@@ -0,0 +1,35 @@
1
+ /**
2
+ * Content Delivery API (`https://{site}/api/v1`, anonymous and cacheable).
3
+ * Types are generated from the Delivery API's OpenAPI document. `siteUrl` is the site's URL (hosted subdomain or custom domain).
4
+ */
5
+ import type { paths as DeliveryPaths } from "./generated/delivery.js";
6
+ import { type HttpClientOptions } from "./http.js";
7
+ import { type SeoHelpers } from "./seo.js";
8
+ import { type TypedClient } from "./typed.js";
9
+ export type { DeliveryPaths };
10
+ export type DeliveryClient = TypedClient<DeliveryPaths> & {
11
+ readonly seo: SeoHelpers;
12
+ };
13
+ export interface DeliveryClientOptions extends Omit<HttpClientOptions, "baseUrl"> {
14
+ /** For example `https://demo.kanorio.com` */
15
+ siteUrl: string;
16
+ /**
17
+ * Read-only preview token (`knr_pv_...`, issued under Site settings > Developer or by the `site.create_preview_token` operation).
18
+ * When set, every request sends `X-Kanorio-Preview` and gets unpublished drafts without caching; pass a function to decide per request in Draft Mode.
19
+ */
20
+ previewToken?: string | (() => string | null | undefined | Promise<string | null | undefined>);
21
+ }
22
+ export declare const DELIVERY_PREVIEW_HEADER = "x-kanorio-preview";
23
+ export declare function deliveryBaseUrl(siteUrl: string): string;
24
+ export declare function createDeliveryClient(options: DeliveryClientOptions): DeliveryClient;
25
+ export declare const DELIVERY_CACHE_TAGS_HEADER = "x-kanorio-cache-tags";
26
+ /**
27
+ * Parses the cache tags from a Delivery API response's `X-Kanorio-Cache-Tags` header (raw strings, the same vocabulary as a webhook's `data.cacheTags`).
28
+ * To tag a framework cache, use `frameworkCacheTags` (which adds the namespace).
29
+ */
30
+ export declare function parseDeliveryCacheTags(headers: Headers | Record<string, string | undefined> | null | undefined): string[];
31
+ /**
32
+ * Response cache tags with the namespace added (`kanorio:` by default), ready for Next.js `fetch(..., { next: { tags } })` or `cacheTag()`.
33
+ * `createRevalidateHandler` calls `revalidateTag` with the same prefix when an event arrives, so the two sides match. Accepts headers or an already parsed array.
34
+ */
35
+ export declare function frameworkCacheTags(source: Headers | Record<string, string | undefined> | readonly string[] | null | undefined, prefix?: string): string[];