@kanorio/sdk 0.0.0-stage → 1.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +66 -2
- package/dist/customer-oauth.d.ts +86 -0
- package/dist/customer-oauth.js +112 -0
- package/dist/customer.d.ts +176 -0
- package/dist/customer.js +125 -0
- package/dist/delivery.d.ts +35 -0
- package/dist/delivery.js +49 -0
- package/dist/edge.d.ts +108 -0
- package/dist/edge.js +287 -0
- package/dist/forms.d.ts +123 -0
- package/dist/forms.js +130 -0
- package/dist/generated/customer.d.ts +3157 -0
- package/dist/generated/delivery.d.ts +2408 -0
- package/dist/generated/management.d.ts +38333 -0
- package/dist/http.d.ts +73 -0
- package/dist/http.js +162 -0
- package/dist/index.d.ts +16 -0
- package/dist/index.js +17 -0
- package/dist/locales.d.ts +80 -0
- package/dist/locales.js +81 -0
- package/dist/management.d.ts +19 -0
- package/dist/management.js +22 -0
- package/dist/paginate.d.ts +18 -0
- package/dist/paginate.js +27 -0
- package/dist/preview.d.ts +40 -0
- package/dist/preview.js +131 -0
- package/dist/protection.d.ts +74 -0
- package/dist/protection.js +68 -0
- package/dist/revalidate.d.ts +84 -0
- package/dist/revalidate.js +143 -0
- package/dist/seo.d.ts +120 -0
- package/dist/seo.js +125 -0
- package/dist/server-key.d.ts +71 -0
- package/dist/server-key.js +103 -0
- package/dist/shared/api/delivery/cache-tags.d.ts +142 -0
- package/dist/shared/api/delivery/cache-tags.js +212 -0
- package/dist/shared/api/server-key.d.ts +90 -0
- package/dist/shared/api/server-key.js +260 -0
- package/dist/shared/business-registry/attribution.d.ts +14 -0
- package/dist/shared/business-registry/attribution.js +28 -0
- package/dist/shared/business-registry/define.d.ts +3 -0
- package/dist/shared/business-registry/define.js +4 -0
- package/dist/shared/business-registry/formats/eu-vat.d.ts +2 -0
- package/dist/shared/business-registry/formats/eu-vat.js +54 -0
- package/dist/shared/business-registry/formats/hk-br.d.ts +5 -0
- package/dist/shared/business-registry/formats/hk-br.js +23 -0
- package/dist/shared/business-registry/formats/jp-trn.d.ts +6 -0
- package/dist/shared/business-registry/formats/jp-trn.js +23 -0
- package/dist/shared/business-registry/formats/kr-brn.d.ts +6 -0
- package/dist/shared/business-registry/formats/kr-brn.js +30 -0
- package/dist/shared/business-registry/formats/my.d.ts +7 -0
- package/dist/shared/business-registry/formats/my.js +32 -0
- package/dist/shared/business-registry/formats/sg-uen.d.ts +1 -0
- package/dist/shared/business-registry/formats/sg-uen.js +21 -0
- package/dist/shared/business-registry/formats/tw-vat.d.ts +10 -0
- package/dist/shared/business-registry/formats/tw-vat.js +32 -0
- package/dist/shared/business-registry/index.d.ts +9 -0
- package/dist/shared/business-registry/index.js +10 -0
- package/dist/shared/business-registry/lookup-wire.d.ts +33 -0
- package/dist/shared/business-registry/lookup-wire.js +8 -0
- package/dist/shared/business-registry/normalize.d.ts +7 -0
- package/dist/shared/business-registry/normalize.js +12 -0
- package/dist/shared/business-registry/registry.d.ts +26 -0
- package/dist/shared/business-registry/registry.js +67 -0
- package/dist/shared/business-registry/types.d.ts +60 -0
- package/dist/shared/business-registry/types.js +10 -0
- package/dist/shared/localization/locale-path.d.ts +38 -0
- package/dist/shared/localization/locale-path.js +76 -0
- package/dist/shared/localization/request-locale.d.ts +42 -0
- package/dist/shared/localization/request-locale.js +61 -0
- package/dist/shared/seo/alternates.d.ts +61 -0
- package/dist/shared/seo/alternates.js +71 -0
- package/dist/shared/types/forms-logic.d.ts +96 -0
- package/dist/shared/types/forms-logic.js +209 -0
- package/dist/shared/types/number-input.d.ts +5 -0
- package/dist/shared/types/number-input.js +16 -0
- package/dist/shared/utils/redirect-matching.d.ts +76 -0
- package/dist/shared/utils/redirect-matching.js +181 -0
- package/dist/tax-id.d.ts +7 -0
- package/dist/tax-id.js +6 -0
- package/dist/typed.d.ts +85 -0
- package/dist/typed.js +28 -0
- package/package.json +86 -3
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
// Copied from Kanorio's shared code by `pnpm --filter @kanorio/sdk gen`. Do not edit by hand; a contract test keeps the two copies identical.
|
|
2
|
+
/**
|
|
3
|
+
* Canonical and hreflang for a customer site. `<head>` and the sitemap both call this one function, so they always agree.
|
|
4
|
+
*
|
|
5
|
+
* Rules:
|
|
6
|
+
* - The primary locale has no prefix (`/about`) and secondary locales use a subdirectory (`/en/about`); the prefix is the locale's saved `pathPrefix` (`locale-path.ts`).
|
|
7
|
+
* - Each locale version is self-canonical; only locales that are live and have a translation of this page are listed, plus the primary locale; x-default points to the primary locale.
|
|
8
|
+
* - A fallback page (a secondary locale was requested but this page has no translation, so primary-locale content is served): canonical points to the primary locale URL and no hreflang is emitted.
|
|
9
|
+
* - hreflang codes: `zh-Hant` becomes `zh-TW`, everything else is the locale code; Google accepts BCP 47 such as `en-US` and `pt-BR`.
|
|
10
|
+
* - Language catch-all (as Nuxt i18n does): when a language has a single regional version in this set (`en-US`),
|
|
11
|
+
* a bare-language hreflang (`en`) is added for the same URL so users of that language elsewhere match it too; it is not added when the language has two or more versions
|
|
12
|
+
* (there is no basis for choosing one, so it is left to Google) and never for Chinese (Traditional, Simplified and Hong Kong are different writing systems).
|
|
13
|
+
* - Never redirects by Accept-Language or IP (this only produces markup).
|
|
14
|
+
*/
|
|
15
|
+
import { languageOfLocale } from "../localization/locale-path.js";
|
|
16
|
+
/** Site locale code to hreflang */
|
|
17
|
+
export function hreflangOf(locale) {
|
|
18
|
+
if (locale === "zh-Hant")
|
|
19
|
+
return "zh-TW";
|
|
20
|
+
return locale;
|
|
21
|
+
}
|
|
22
|
+
function pathIn(locale, path, localizedPaths) {
|
|
23
|
+
return localizedPaths?.[locale] ?? path;
|
|
24
|
+
}
|
|
25
|
+
/** This page's URL in a locale */
|
|
26
|
+
export function localizedSiteUrl(siteUrl, primaryLocale, locale, path, localePrefixes) {
|
|
27
|
+
const base = siteUrl.replace(/\/+$/, "");
|
|
28
|
+
const cleanPath = path === "/" || path === "" ? "" : path.startsWith("/") ? path : `/${path}`;
|
|
29
|
+
// The home page follows the site's convention: the primary home page is `https://host` (no trailing slash), a secondary one is `https://host/en`
|
|
30
|
+
if (locale === primaryLocale)
|
|
31
|
+
return `${base}${cleanPath}`;
|
|
32
|
+
return `${base}/${localePrefixes[locale] ?? locale.toLowerCase()}${cleanPath}`;
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* hreflang to URL for a set of locale versions (primary first, secondary locales sorted by code, language catch-alls, and x-default last pointing to the primary).
|
|
36
|
+
* Both the alternates in `<head>` and the sitemap's `<xhtml:link>` are produced here.
|
|
37
|
+
*/
|
|
38
|
+
export function hreflangEntries(siteUrl, path, primaryLocale, secondaryLocales, localePrefixes, localizedPaths) {
|
|
39
|
+
const versions = [primaryLocale, ...[...new Set(secondaryLocales.filter((l) => l !== primaryLocale))].sort()];
|
|
40
|
+
const entries = versions.map((locale) => ({
|
|
41
|
+
hreflang: hreflangOf(locale),
|
|
42
|
+
href: localizedSiteUrl(siteUrl, primaryLocale, locale, pathIn(locale, path, localizedPaths), localePrefixes),
|
|
43
|
+
locale,
|
|
44
|
+
}));
|
|
45
|
+
const byLanguage = new Map();
|
|
46
|
+
for (const locale of versions)
|
|
47
|
+
byLanguage.set(languageOfLocale(locale), [...(byLanguage.get(languageOfLocale(locale)) ?? []), locale]);
|
|
48
|
+
for (const [language, group] of byLanguage) {
|
|
49
|
+
const only = group.length === 1 ? group[0] : null;
|
|
50
|
+
if (!only || language === "zh" || !only.includes("-") || hreflangOf(only) === language)
|
|
51
|
+
continue;
|
|
52
|
+
entries.push({ hreflang: language, href: localizedSiteUrl(siteUrl, primaryLocale, only, pathIn(only, path, localizedPaths), localePrefixes), locale: null });
|
|
53
|
+
}
|
|
54
|
+
entries.push({ hreflang: "x-default", href: entries[0].href, locale: null });
|
|
55
|
+
return entries;
|
|
56
|
+
}
|
|
57
|
+
export function buildSiteAlternates(input) {
|
|
58
|
+
const { siteUrl, path, primaryLocale, requestLocale, resolvedLocale, localePrefixes, localizedPaths } = input;
|
|
59
|
+
const canonical = localizedSiteUrl(siteUrl, primaryLocale, resolvedLocale, pathIn(resolvedLocale, path, localizedPaths), localePrefixes);
|
|
60
|
+
// Fallback: a secondary locale was requested but primary-locale content is served, so canonical points to the primary and no hreflang is emitted
|
|
61
|
+
if (resolvedLocale !== requestLocale)
|
|
62
|
+
return { canonical, languages: {} };
|
|
63
|
+
const languages = {};
|
|
64
|
+
for (const entry of hreflangEntries(siteUrl, path, primaryLocale, input.availableLocales, localePrefixes, localizedPaths))
|
|
65
|
+
languages[entry.hreflang] = entry.href;
|
|
66
|
+
return { canonical, languages };
|
|
67
|
+
}
|
|
68
|
+
/** For the sitemap's `<xhtml:link rel="alternate">`: every version of the same page (primary, language catch-alls and x-default) */
|
|
69
|
+
export function sitemapAlternates(siteUrl, path, primaryLocale, availableLocales, localePrefixes, localizedPaths) {
|
|
70
|
+
return hreflangEntries(siteUrl, path, primaryLocale, availableLocales, localePrefixes, localizedPaths).map(({ hreflang, href }) => ({ hreflang, href }));
|
|
71
|
+
}
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Conditional display for online forms: "this question appears only when A is chosen".
|
|
3
|
+
*
|
|
4
|
+
* A question can carry `visibleWhen`: a set of conditions (at most 5) that shows it when all (`all`) or any (`any`) of them match.
|
|
5
|
+
* The storefront (deciding which questions to draw) and the server (deciding which to validate and which answers to store) both call `resolveVisibleFieldIds`, so the two always agree:
|
|
6
|
+
* a hidden question is not shown, not validated (required does not block) and its answer is stored as null.
|
|
7
|
+
*
|
|
8
|
+
* Rules:
|
|
9
|
+
* - A condition can only refer to an earlier question (`kind: "field"`) or one of the form's hidden fields (`kind: "hidden"`)
|
|
10
|
+
* - When the source question is itself hidden, it counts as unanswered
|
|
11
|
+
* - Email and phone questions cannot be hidden (they identify the contact, and the form's other rules rely on them)
|
|
12
|
+
* - When a rule cannot be evaluated (missing source, a later question, an operator that does not apply), the question is shown: better to ask one question too many than to hide a required one forever
|
|
13
|
+
*
|
|
14
|
+
* Pure functions with no dependencies: `@kanorio/sdk` carries a copy, so a self-hosted front end evaluates the same way. Only relative imports inside this folder.
|
|
15
|
+
* Scoring, if added later, only needs one more source in `kind` (a variable), with no data migration.
|
|
16
|
+
*/
|
|
17
|
+
export declare const FORM_CONDITION_OPS: readonly ["answered", "not_answered", "includes", "not_includes", "equals", "not_equals", "contains", "gt", "gte", "lt", "lte"];
|
|
18
|
+
export type FormConditionOp = (typeof FORM_CONDITION_OPS)[number];
|
|
19
|
+
export declare const FORM_LOGIC_LIMITS: {
|
|
20
|
+
/** Maximum conditions per question */
|
|
21
|
+
readonly MAX_CONDITIONS: 5;
|
|
22
|
+
/** Maximum length of a condition's comparison text */
|
|
23
|
+
readonly VALUE_MAX: 200;
|
|
24
|
+
};
|
|
25
|
+
export interface FormCondition {
|
|
26
|
+
/** Whether the source is a question (`ref` is the question id) or a hidden field (`ref` is the hidden field id) */
|
|
27
|
+
kind: "field" | "hidden";
|
|
28
|
+
ref: string;
|
|
29
|
+
op: FormConditionOp;
|
|
30
|
+
/** An option id (includes), comparison text (equals, contains) or a number (numeric comparison); answered and unanswered take no value */
|
|
31
|
+
value?: string | number;
|
|
32
|
+
}
|
|
33
|
+
export interface FormVisibleWhen {
|
|
34
|
+
match: "all" | "any";
|
|
35
|
+
conditions: FormCondition[];
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Which operators each source supports. Phone, date, time and email can only be tested for answered or not; file, description text, address and tax ID cannot be sources (empty arrays).
|
|
39
|
+
* A new question type needs an entry here (forms.ts has a compile-time check).
|
|
40
|
+
*/
|
|
41
|
+
export declare const CONDITION_OPS_BY_TYPE: {
|
|
42
|
+
readonly short_text: readonly ["answered", "not_answered", "equals", "not_equals", "contains"];
|
|
43
|
+
readonly long_text: readonly ["answered", "not_answered", "equals", "not_equals", "contains"];
|
|
44
|
+
readonly url: readonly ["answered", "not_answered", "equals", "not_equals", "contains"];
|
|
45
|
+
readonly email: readonly ["answered", "not_answered"];
|
|
46
|
+
readonly phone: readonly ["answered", "not_answered"];
|
|
47
|
+
readonly date: readonly ["answered", "not_answered"];
|
|
48
|
+
readonly time: readonly ["answered", "not_answered"];
|
|
49
|
+
readonly choice: readonly ["answered", "not_answered", "includes", "not_includes"];
|
|
50
|
+
readonly number: readonly ["answered", "not_answered", "equals", "not_equals", "gt", "gte", "lt", "lte"];
|
|
51
|
+
readonly rating: readonly ["answered", "not_answered", "equals", "not_equals", "gt", "gte", "lt", "lte"];
|
|
52
|
+
readonly file: readonly [];
|
|
53
|
+
readonly statement: readonly [];
|
|
54
|
+
readonly address: readonly [];
|
|
55
|
+
readonly tax_id: readonly [];
|
|
56
|
+
/** A hidden field (a string taken from a URL parameter) */
|
|
57
|
+
readonly hidden: readonly ["answered", "not_answered", "equals", "not_equals", "contains"];
|
|
58
|
+
};
|
|
59
|
+
export type FormConditionSourceType = keyof typeof CONDITION_OPS_BY_TYPE;
|
|
60
|
+
export declare function conditionOpsFor(sourceType: string): readonly FormConditionOp[];
|
|
61
|
+
/** Which kind of value this operator takes */
|
|
62
|
+
export type FormConditionValueKind = "none" | "option" | "text" | "number";
|
|
63
|
+
export declare function conditionValueKind(sourceType: string, op: FormConditionOp): FormConditionValueKind;
|
|
64
|
+
/** The question details conditional logic needs (a subset of the form definition) */
|
|
65
|
+
export interface LogicField {
|
|
66
|
+
id: string;
|
|
67
|
+
type: string;
|
|
68
|
+
visibleWhen?: FormVisibleWhen | null;
|
|
69
|
+
options?: ReadonlyArray<{
|
|
70
|
+
id: string;
|
|
71
|
+
}>;
|
|
72
|
+
}
|
|
73
|
+
export type FormConditionIssue =
|
|
74
|
+
/** The source does not exist, or is not an earlier question */
|
|
75
|
+
"missing_source" | "op_not_allowed" | "value_required" | "value_unexpected"
|
|
76
|
+
/** The value has the wrong type (text where a number is needed, or the reverse) */
|
|
77
|
+
| "value_type" | "unknown_option";
|
|
78
|
+
/**
|
|
79
|
+
* Checks whether a condition is valid for its source. `source` is undefined when the source cannot be found.
|
|
80
|
+
* Shared by the schema (blocking on save) and the editor (marking as you type).
|
|
81
|
+
*/
|
|
82
|
+
export declare function findConditionIssue(condition: FormCondition, source: {
|
|
83
|
+
type: string;
|
|
84
|
+
options?: ReadonlyArray<{
|
|
85
|
+
id: string;
|
|
86
|
+
}>;
|
|
87
|
+
} | undefined): FormConditionIssue | null;
|
|
88
|
+
/** Whether a single condition holds for an answer; null when the operator does not apply to this source (cannot be evaluated) */
|
|
89
|
+
export declare function evaluateCondition(condition: FormCondition, sourceType: string, raw: unknown): boolean | null;
|
|
90
|
+
/**
|
|
91
|
+
* Works out which questions to show from the current answers. `answers` maps a question id or hidden field id to its value (the raw value the visitor typed is fine).
|
|
92
|
+
* Evaluated in question order: when an earlier question is hidden, a condition referring to it treats it as unanswered.
|
|
93
|
+
*/
|
|
94
|
+
export declare function resolveVisibleFieldIds(fields: readonly LogicField[], answers: Readonly<Record<string, unknown>>): Set<string>;
|
|
95
|
+
/** Whether this form has any conditional display (without it, the storefront need not recompute on every input) */
|
|
96
|
+
export declare function hasVisibilityRules(fields: readonly LogicField[]): boolean;
|
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
// Copied from Kanorio's shared code by `pnpm --filter @kanorio/sdk gen`. Do not edit by hand; a contract test keeps the two copies identical.
|
|
2
|
+
/**
|
|
3
|
+
* Conditional display for online forms: "this question appears only when A is chosen".
|
|
4
|
+
*
|
|
5
|
+
* A question can carry `visibleWhen`: a set of conditions (at most 5) that shows it when all (`all`) or any (`any`) of them match.
|
|
6
|
+
* The storefront (deciding which questions to draw) and the server (deciding which to validate and which answers to store) both call `resolveVisibleFieldIds`, so the two always agree:
|
|
7
|
+
* a hidden question is not shown, not validated (required does not block) and its answer is stored as null.
|
|
8
|
+
*
|
|
9
|
+
* Rules:
|
|
10
|
+
* - A condition can only refer to an earlier question (`kind: "field"`) or one of the form's hidden fields (`kind: "hidden"`)
|
|
11
|
+
* - When the source question is itself hidden, it counts as unanswered
|
|
12
|
+
* - Email and phone questions cannot be hidden (they identify the contact, and the form's other rules rely on them)
|
|
13
|
+
* - When a rule cannot be evaluated (missing source, a later question, an operator that does not apply), the question is shown: better to ask one question too many than to hide a required one forever
|
|
14
|
+
*
|
|
15
|
+
* Pure functions with no dependencies: `@kanorio/sdk` carries a copy, so a self-hosted front end evaluates the same way. Only relative imports inside this folder.
|
|
16
|
+
* Scoring, if added later, only needs one more source in `kind` (a variable), with no data migration.
|
|
17
|
+
*/
|
|
18
|
+
import { parseNumberInput } from "./number-input.js";
|
|
19
|
+
export const FORM_CONDITION_OPS = [
|
|
20
|
+
"answered",
|
|
21
|
+
"not_answered",
|
|
22
|
+
"includes",
|
|
23
|
+
"not_includes",
|
|
24
|
+
"equals",
|
|
25
|
+
"not_equals",
|
|
26
|
+
"contains",
|
|
27
|
+
"gt",
|
|
28
|
+
"gte",
|
|
29
|
+
"lt",
|
|
30
|
+
"lte",
|
|
31
|
+
];
|
|
32
|
+
export const FORM_LOGIC_LIMITS = {
|
|
33
|
+
/** Maximum conditions per question */
|
|
34
|
+
MAX_CONDITIONS: 5,
|
|
35
|
+
/** Maximum length of a condition's comparison text */
|
|
36
|
+
VALUE_MAX: 200,
|
|
37
|
+
};
|
|
38
|
+
const PRESENCE_OPS = ["answered", "not_answered"];
|
|
39
|
+
const TEXT_OPS = ["answered", "not_answered", "equals", "not_equals", "contains"];
|
|
40
|
+
const CHOICE_OPS = ["answered", "not_answered", "includes", "not_includes"];
|
|
41
|
+
const NUMBER_OPS = ["answered", "not_answered", "equals", "not_equals", "gt", "gte", "lt", "lte"];
|
|
42
|
+
/**
|
|
43
|
+
* Which operators each source supports. Phone, date, time and email can only be tested for answered or not; file, description text, address and tax ID cannot be sources (empty arrays).
|
|
44
|
+
* A new question type needs an entry here (forms.ts has a compile-time check).
|
|
45
|
+
*/
|
|
46
|
+
export const CONDITION_OPS_BY_TYPE = {
|
|
47
|
+
short_text: TEXT_OPS,
|
|
48
|
+
long_text: TEXT_OPS,
|
|
49
|
+
url: TEXT_OPS,
|
|
50
|
+
email: PRESENCE_OPS,
|
|
51
|
+
phone: PRESENCE_OPS,
|
|
52
|
+
date: PRESENCE_OPS,
|
|
53
|
+
time: PRESENCE_OPS,
|
|
54
|
+
choice: CHOICE_OPS,
|
|
55
|
+
number: NUMBER_OPS,
|
|
56
|
+
rating: NUMBER_OPS,
|
|
57
|
+
file: [],
|
|
58
|
+
statement: [],
|
|
59
|
+
address: [],
|
|
60
|
+
tax_id: [],
|
|
61
|
+
/** A hidden field (a string taken from a URL parameter) */
|
|
62
|
+
hidden: TEXT_OPS,
|
|
63
|
+
};
|
|
64
|
+
export function conditionOpsFor(sourceType) {
|
|
65
|
+
return CONDITION_OPS_BY_TYPE[sourceType] ?? [];
|
|
66
|
+
}
|
|
67
|
+
export function conditionValueKind(sourceType, op) {
|
|
68
|
+
switch (op) {
|
|
69
|
+
case "answered":
|
|
70
|
+
case "not_answered":
|
|
71
|
+
return "none";
|
|
72
|
+
case "includes":
|
|
73
|
+
case "not_includes":
|
|
74
|
+
return "option";
|
|
75
|
+
case "contains":
|
|
76
|
+
return "text";
|
|
77
|
+
case "equals":
|
|
78
|
+
case "not_equals":
|
|
79
|
+
return sourceType === "number" || sourceType === "rating" ? "number" : "text";
|
|
80
|
+
case "gt":
|
|
81
|
+
case "gte":
|
|
82
|
+
case "lt":
|
|
83
|
+
case "lte":
|
|
84
|
+
return "number";
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* Checks whether a condition is valid for its source. `source` is undefined when the source cannot be found.
|
|
89
|
+
* Shared by the schema (blocking on save) and the editor (marking as you type).
|
|
90
|
+
*/
|
|
91
|
+
export function findConditionIssue(condition, source) {
|
|
92
|
+
if (!source)
|
|
93
|
+
return "missing_source";
|
|
94
|
+
if (!conditionOpsFor(source.type).includes(condition.op))
|
|
95
|
+
return "op_not_allowed";
|
|
96
|
+
const kind = conditionValueKind(source.type, condition.op);
|
|
97
|
+
const { value } = condition;
|
|
98
|
+
if (kind === "none")
|
|
99
|
+
return value === undefined ? null : "value_unexpected";
|
|
100
|
+
if (value === undefined || value === "")
|
|
101
|
+
return "value_required";
|
|
102
|
+
if (kind === "number")
|
|
103
|
+
return typeof value === "number" && Number.isFinite(value) ? null : "value_type";
|
|
104
|
+
if (typeof value !== "string")
|
|
105
|
+
return "value_type";
|
|
106
|
+
if (kind === "option" && !source.options?.some((option) => option.id === value))
|
|
107
|
+
return "unknown_option";
|
|
108
|
+
return null;
|
|
109
|
+
}
|
|
110
|
+
function isAnswered(raw) {
|
|
111
|
+
if (raw === null || raw === undefined)
|
|
112
|
+
return false;
|
|
113
|
+
if (typeof raw === "string")
|
|
114
|
+
return raw.trim() !== "";
|
|
115
|
+
if (Array.isArray(raw))
|
|
116
|
+
return raw.length > 0;
|
|
117
|
+
return true;
|
|
118
|
+
}
|
|
119
|
+
/** Text comparison ignores case and surrounding whitespace, and treats full-width and half-width as the same */
|
|
120
|
+
function foldText(value) {
|
|
121
|
+
return typeof value === "string" ? value.normalize("NFKC").trim().toLowerCase() : typeof value === "number" ? String(value) : "";
|
|
122
|
+
}
|
|
123
|
+
/** Whether a single condition holds for an answer; null when the operator does not apply to this source (cannot be evaluated) */
|
|
124
|
+
export function evaluateCondition(condition, sourceType, raw) {
|
|
125
|
+
if (!conditionOpsFor(sourceType).includes(condition.op))
|
|
126
|
+
return null;
|
|
127
|
+
const answered = isAnswered(raw);
|
|
128
|
+
switch (condition.op) {
|
|
129
|
+
case "answered":
|
|
130
|
+
return answered;
|
|
131
|
+
case "not_answered":
|
|
132
|
+
return !answered;
|
|
133
|
+
case "includes":
|
|
134
|
+
case "not_includes": {
|
|
135
|
+
const picked = Array.isArray(raw) ? raw : typeof raw === "string" && raw ? [raw] : [];
|
|
136
|
+
const has = picked.includes(condition.value);
|
|
137
|
+
return condition.op === "includes" ? has : !has;
|
|
138
|
+
}
|
|
139
|
+
case "contains":
|
|
140
|
+
return answered && foldText(raw).includes(foldText(condition.value));
|
|
141
|
+
case "equals":
|
|
142
|
+
case "not_equals": {
|
|
143
|
+
if (conditionValueKind(sourceType, condition.op) === "number") {
|
|
144
|
+
const number = parseNumberInput(raw);
|
|
145
|
+
const same = number !== null && number === condition.value;
|
|
146
|
+
return condition.op === "equals" ? same : !same;
|
|
147
|
+
}
|
|
148
|
+
const same = answered && foldText(raw) === foldText(condition.value);
|
|
149
|
+
return condition.op === "equals" ? same : !same;
|
|
150
|
+
}
|
|
151
|
+
case "gt":
|
|
152
|
+
case "gte":
|
|
153
|
+
case "lt":
|
|
154
|
+
case "lte": {
|
|
155
|
+
const number = parseNumberInput(raw);
|
|
156
|
+
const target = typeof condition.value === "number" ? condition.value : null;
|
|
157
|
+
// Empty or not a number: the comparison does not hold
|
|
158
|
+
if (number === null || target === null)
|
|
159
|
+
return false;
|
|
160
|
+
if (condition.op === "gt")
|
|
161
|
+
return number > target;
|
|
162
|
+
if (condition.op === "gte")
|
|
163
|
+
return number >= target;
|
|
164
|
+
if (condition.op === "lt")
|
|
165
|
+
return number < target;
|
|
166
|
+
return number <= target;
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
/**
|
|
171
|
+
* Works out which questions to show from the current answers. `answers` maps a question id or hidden field id to its value (the raw value the visitor typed is fine).
|
|
172
|
+
* Evaluated in question order: when an earlier question is hidden, a condition referring to it treats it as unanswered.
|
|
173
|
+
*/
|
|
174
|
+
export function resolveVisibleFieldIds(fields, answers) {
|
|
175
|
+
const visible = new Set();
|
|
176
|
+
const seen = new Map();
|
|
177
|
+
for (const field of fields) {
|
|
178
|
+
const rule = field.visibleWhen;
|
|
179
|
+
const conditions = rule && Array.isArray(rule.conditions) ? rule.conditions : [];
|
|
180
|
+
// Email and phone identify the contact and are not affected by conditions
|
|
181
|
+
if (conditions.length === 0 || field.type === "email" || field.type === "phone") {
|
|
182
|
+
visible.add(field.id);
|
|
183
|
+
seen.set(field.id, field.type);
|
|
184
|
+
continue;
|
|
185
|
+
}
|
|
186
|
+
let undecidable = false;
|
|
187
|
+
const results = conditions.map((condition) => {
|
|
188
|
+
const sourceType = condition.kind === "hidden" ? "hidden" : seen.get(condition.ref);
|
|
189
|
+
if (!sourceType) {
|
|
190
|
+
undecidable = true;
|
|
191
|
+
return false;
|
|
192
|
+
}
|
|
193
|
+
// The source question is itself hidden: treated as unanswered
|
|
194
|
+
const raw = condition.kind === "hidden" || visible.has(condition.ref) ? answers[condition.ref] : null;
|
|
195
|
+
const result = evaluateCondition(condition, sourceType, raw);
|
|
196
|
+
if (result === null)
|
|
197
|
+
undecidable = true;
|
|
198
|
+
return result === true;
|
|
199
|
+
});
|
|
200
|
+
if (undecidable || (rule?.match === "any" ? results.some(Boolean) : results.every(Boolean)))
|
|
201
|
+
visible.add(field.id);
|
|
202
|
+
seen.set(field.id, field.type);
|
|
203
|
+
}
|
|
204
|
+
return visible;
|
|
205
|
+
}
|
|
206
|
+
/** Whether this form has any conditional display (without it, the storefront need not recompute on every input) */
|
|
207
|
+
export function hasVisibilityRules(fields) {
|
|
208
|
+
return fields.some((field) => (field.visibleWhen?.conditions?.length ?? 0) > 0);
|
|
209
|
+
}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A visitor's typed number to a number. Accepts full-width digits (common with Chinese, Japanese and Korean input methods) and thousands separators; null when it is not a finite number.
|
|
3
|
+
* No dependencies: form validation, conditional logic and `@kanorio/sdk` use the same code.
|
|
4
|
+
*/
|
|
5
|
+
export declare function parseNumberInput(raw: unknown): number | null;
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
// Copied from Kanorio's shared code by `pnpm --filter @kanorio/sdk gen`. Do not edit by hand; a contract test keeps the two copies identical.
|
|
2
|
+
/**
|
|
3
|
+
* A visitor's typed number to a number. Accepts full-width digits (common with Chinese, Japanese and Korean input methods) and thousands separators; null when it is not a finite number.
|
|
4
|
+
* No dependencies: form validation, conditional logic and `@kanorio/sdk` use the same code.
|
|
5
|
+
*/
|
|
6
|
+
export function parseNumberInput(raw) {
|
|
7
|
+
if (typeof raw === "number")
|
|
8
|
+
return Number.isFinite(raw) ? raw : null;
|
|
9
|
+
if (typeof raw !== "string")
|
|
10
|
+
return null;
|
|
11
|
+
const cleaned = raw.normalize("NFKC").replace(/[\s,]/g, "");
|
|
12
|
+
if (!/^[+-]?(\d+\.?\d*|\.\d+)$/.test(cleaned))
|
|
13
|
+
return null;
|
|
14
|
+
const value = Number(cleaned);
|
|
15
|
+
return Number.isFinite(value) ? value : null;
|
|
16
|
+
}
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The single source of truth for URL redirect matching and loop detection (a contract across apps).
|
|
3
|
+
*
|
|
4
|
+
* - The hosted-site middleware uses `matchRedirect` at runtime to perform redirects.
|
|
5
|
+
* - Before saving, the server uses `isSelfLoop`, `findRedirectLoopKeys` and `hasRedirectChainLoop`
|
|
6
|
+
* to simulate the same matching and detect loops.
|
|
7
|
+
*
|
|
8
|
+
* Both use this module, so the matching rules (exact first, then the longest wildcard prefix, then resolving relative and wildcard targets)
|
|
9
|
+
* never drift apart. Pure string functions with no React or Node dependency, safe to bundle for an edge runtime.
|
|
10
|
+
*/
|
|
11
|
+
export type RedirectRuleLite = {
|
|
12
|
+
sourcePath: string;
|
|
13
|
+
targetUrl: string;
|
|
14
|
+
statusCode?: number;
|
|
15
|
+
/**
|
|
16
|
+
* The locale a rule belongs to. null or unset: shared by every locale, matched on the path without the locale prefix, with in-site targets given the prefix back.
|
|
17
|
+
* A value: belongs to that locale only (a renamed translated slug, a disabled locale, a changed prefix); source and target already include the prefix, matched on the full path with the target used as is.
|
|
18
|
+
*/
|
|
19
|
+
locale?: string | null;
|
|
20
|
+
};
|
|
21
|
+
/**
|
|
22
|
+
* Paths are matched in canonical form: the percent-encoding browsers actually send, with escape codes in uppercase; query and fragment are not part of the path.
|
|
23
|
+
*
|
|
24
|
+
* A visitor's pathname arrives encoded (`/%E7%94%A2%E5%93%81.pdf`), while the source an owner typed may be raw characters
|
|
25
|
+
* or an encoded string pasted from the address bar (in either case). Compared as plain strings, a rule written in raw characters would never match.
|
|
26
|
+
* Both sides go through this function before comparing; it parses with the WHATWG URL, so the result agrees with browsers and `NextRequest.nextUrl.pathname`.
|
|
27
|
+
*/
|
|
28
|
+
export declare function canonicalRedirectPath(path: string): string;
|
|
29
|
+
/**
|
|
30
|
+
* Resolves one path by the matching rules: exact match first, otherwise the longest wildcard prefix (a `sourcePath` ending in `/*`).
|
|
31
|
+
* A target ending in `/*` keeps the remaining sub-path; otherwise everything goes to the same target.
|
|
32
|
+
* Returns the matched rule, the resolved target (an in-site relative path or a full external URL) and the status code; null without a match.
|
|
33
|
+
* Path and source are both compared in the canonical form of `canonicalRedirectPath` (raw and percent-encoded are the same path).
|
|
34
|
+
*/
|
|
35
|
+
export declare function matchRedirect<R extends RedirectRuleLite>(pathname: string, rules: R[]): {
|
|
36
|
+
rule: R;
|
|
37
|
+
target: string;
|
|
38
|
+
statusCode: number;
|
|
39
|
+
} | null;
|
|
40
|
+
/**
|
|
41
|
+
* Redirect matching on multilingual sites: locale-specific rules first (full path, target as is), then shared rules (unprefixed path).
|
|
42
|
+
* When `scoped` is true the target already includes the locale prefix; when false the caller adds the request locale's prefix to in-site targets (the existing behavior).
|
|
43
|
+
*/
|
|
44
|
+
export declare function matchLocalizedRedirect<R extends RedirectRuleLite>(fullPathname: string, localePathname: string, rules: R[]): {
|
|
45
|
+
rule: R;
|
|
46
|
+
target: string;
|
|
47
|
+
statusCode: number;
|
|
48
|
+
scoped: boolean;
|
|
49
|
+
} | null;
|
|
50
|
+
/** Strips the trailing slash (keeping the root "/"), for self-redirect comparison. */
|
|
51
|
+
export declare function stripTrailingSlash(value: string): string;
|
|
52
|
+
/** Exact self-redirect (/foo and /foo/ are the same). */
|
|
53
|
+
export declare function isExactSelf(source: string, target: string): boolean;
|
|
54
|
+
/**
|
|
55
|
+
* A wildcard source whose in-site relative target falls inside what the source covers ("/*" to "/", "/blog/*" to "/blog/x").
|
|
56
|
+
* Targets outside it ("/blog/*" to "/about") and external URLs do not count.
|
|
57
|
+
*/
|
|
58
|
+
export declare function isScopeLoop(source: string, target: string): boolean;
|
|
59
|
+
/** Whether a single rule loops on itself (an exact self-redirect or a wildcard covering its own target). */
|
|
60
|
+
export declare function isSelfLoop(source: string, target: string): boolean;
|
|
61
|
+
/**
|
|
62
|
+
* Finds the keys of rules that take part in a redirect loop across rules (for example /a to /b and /b to /a).
|
|
63
|
+
*
|
|
64
|
+
* Starting from each rule's representative path, it applies `matchRedirect` hop by hop and detects a cycle with a visited set.
|
|
65
|
+
* Single-rule self-loops should be handled first by the caller with `isSelfLoop`; this focuses on rules pointing at each other.
|
|
66
|
+
*
|
|
67
|
+
* Precision: `maxHops = number of rules + 1`. In this functional structure an acyclic walk ends after visiting at most as many
|
|
68
|
+
* distinct states as there are rules, so `number of rules + 1` is an exact bound with no false positives; a growing chain (never ending) is judged a loop once it exceeds the bound.
|
|
69
|
+
*/
|
|
70
|
+
export declare function findRedirectLoopKeys<R extends {
|
|
71
|
+
key: string;
|
|
72
|
+
sourcePath: string;
|
|
73
|
+
targetUrl: string;
|
|
74
|
+
}>(rules: R[]): Set<string>;
|
|
75
|
+
/** Whether a redirect loop across rules exists. Check single-rule self-loops separately with `isSelfLoop`. */
|
|
76
|
+
export declare function hasRedirectChainLoop(rules: RedirectRuleLite[]): boolean;
|
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
// Copied from Kanorio's shared code by `pnpm --filter @kanorio/sdk gen`. Do not edit by hand; a contract test keeps the two copies identical.
|
|
2
|
+
/**
|
|
3
|
+
* The single source of truth for URL redirect matching and loop detection (a contract across apps).
|
|
4
|
+
*
|
|
5
|
+
* - The hosted-site middleware uses `matchRedirect` at runtime to perform redirects.
|
|
6
|
+
* - Before saving, the server uses `isSelfLoop`, `findRedirectLoopKeys` and `hasRedirectChainLoop`
|
|
7
|
+
* to simulate the same matching and detect loops.
|
|
8
|
+
*
|
|
9
|
+
* Both use this module, so the matching rules (exact first, then the longest wildcard prefix, then resolving relative and wildcard targets)
|
|
10
|
+
* never drift apart. Pure string functions with no React or Node dependency, safe to bundle for an edge runtime.
|
|
11
|
+
*/
|
|
12
|
+
/** Representative sub-path of a wildcard source during loop simulation (internal only, chosen not to collide with real paths). */
|
|
13
|
+
const LOOP_PROBE = "__kanorio_loop_probe__";
|
|
14
|
+
/**
|
|
15
|
+
* Global step budget for loop detection: normal input stays far below it.
|
|
16
|
+
* It only triggers on pathological input (very many wildcard rules), to keep a save from taking too long;
|
|
17
|
+
* past it detection stops, and the rest is covered by the middleware's runtime guard and the browser's ERR_TOO_MANY_REDIRECTS.
|
|
18
|
+
*/
|
|
19
|
+
const MAX_TOTAL_STEPS = 200_000;
|
|
20
|
+
/** Paths that need no encoding: unreserved characters and the separators allowed in a path (most rules take this route and skip parsing) */
|
|
21
|
+
const PLAIN_PATH_PATTERN = /^[A-Za-z0-9\-._~/*!$&'()+,;=:@]*$/;
|
|
22
|
+
/** Cache of canonical forms: within one isolate the rule strings are the same on every request; cleared entirely past the limit */
|
|
23
|
+
const _canonicalPathCache = new Map();
|
|
24
|
+
const CANONICAL_PATH_CACHE_MAX = 5000;
|
|
25
|
+
/**
|
|
26
|
+
* Paths are matched in canonical form: the percent-encoding browsers actually send, with escape codes in uppercase; query and fragment are not part of the path.
|
|
27
|
+
*
|
|
28
|
+
* A visitor's pathname arrives encoded (`/%E7%94%A2%E5%93%81.pdf`), while the source an owner typed may be raw characters
|
|
29
|
+
* or an encoded string pasted from the address bar (in either case). Compared as plain strings, a rule written in raw characters would never match.
|
|
30
|
+
* Both sides go through this function before comparing; it parses with the WHATWG URL, so the result agrees with browsers and `NextRequest.nextUrl.pathname`.
|
|
31
|
+
*/
|
|
32
|
+
export function canonicalRedirectPath(path) {
|
|
33
|
+
if (!path.startsWith("/") || PLAIN_PATH_PATTERN.test(path))
|
|
34
|
+
return path;
|
|
35
|
+
const cached = _canonicalPathCache.get(path);
|
|
36
|
+
if (cached !== undefined)
|
|
37
|
+
return cached;
|
|
38
|
+
let encoded = path;
|
|
39
|
+
try {
|
|
40
|
+
encoded = new URL(`http://x${path}`).pathname;
|
|
41
|
+
}
|
|
42
|
+
catch {
|
|
43
|
+
// Cannot be parsed (an unpaired surrogate, for example): left as is, which means it never matches
|
|
44
|
+
}
|
|
45
|
+
const canonical = encoded.replace(/%[0-9a-f]{2}/gi, (escape) => escape.toUpperCase());
|
|
46
|
+
if (_canonicalPathCache.size >= CANONICAL_PATH_CACHE_MAX)
|
|
47
|
+
_canonicalPathCache.clear();
|
|
48
|
+
_canonicalPathCache.set(path, canonical);
|
|
49
|
+
return canonical;
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Resolves one path by the matching rules: exact match first, otherwise the longest wildcard prefix (a `sourcePath` ending in `/*`).
|
|
53
|
+
* A target ending in `/*` keeps the remaining sub-path; otherwise everything goes to the same target.
|
|
54
|
+
* Returns the matched rule, the resolved target (an in-site relative path or a full external URL) and the status code; null without a match.
|
|
55
|
+
* Path and source are both compared in the canonical form of `canonicalRedirectPath` (raw and percent-encoded are the same path).
|
|
56
|
+
*/
|
|
57
|
+
export function matchRedirect(pathname, rules) {
|
|
58
|
+
const requested = canonicalRedirectPath(pathname);
|
|
59
|
+
// 1. Exact pathname match (case-sensitive, per the URL standard)
|
|
60
|
+
const exact = rules.find((rule) => canonicalRedirectPath(rule.sourcePath) === requested);
|
|
61
|
+
if (exact) {
|
|
62
|
+
return { rule: exact, target: exact.targetUrl, statusCode: exact.statusCode ?? 301 };
|
|
63
|
+
}
|
|
64
|
+
// 2. Wildcard prefix match (the longest prefix wins)
|
|
65
|
+
let best = null;
|
|
66
|
+
for (const rule of rules) {
|
|
67
|
+
if (!rule.sourcePath.endsWith("/*"))
|
|
68
|
+
continue;
|
|
69
|
+
const prefix = canonicalRedirectPath(rule.sourcePath).slice(0, -1); // "/blog/*" → "/blog/"
|
|
70
|
+
if (requested.startsWith(prefix)) {
|
|
71
|
+
if (!best || prefix.length > best.prefix.length) {
|
|
72
|
+
best = { prefix, rule };
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
if (!best)
|
|
77
|
+
return null;
|
|
78
|
+
const suffix = requested.slice(best.prefix.length); // the remaining sub-path (already encoded, still a valid URL once appended to the target)
|
|
79
|
+
const target = best.rule.targetUrl.endsWith("/*")
|
|
80
|
+
? best.rule.targetUrl.slice(0, -1) + suffix
|
|
81
|
+
: best.rule.targetUrl;
|
|
82
|
+
return { rule: best.rule, target, statusCode: best.rule.statusCode ?? 301 };
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* Redirect matching on multilingual sites: locale-specific rules first (full path, target as is), then shared rules (unprefixed path).
|
|
86
|
+
* When `scoped` is true the target already includes the locale prefix; when false the caller adds the request locale's prefix to in-site targets (the existing behavior).
|
|
87
|
+
*/
|
|
88
|
+
export function matchLocalizedRedirect(fullPathname, localePathname, rules) {
|
|
89
|
+
const scopedRules = rules.filter((rule) => rule.locale);
|
|
90
|
+
if (scopedRules.length > 0) {
|
|
91
|
+
const hit = matchRedirect(fullPathname, scopedRules);
|
|
92
|
+
if (hit)
|
|
93
|
+
return { ...hit, scoped: true };
|
|
94
|
+
}
|
|
95
|
+
const shared = scopedRules.length > 0 ? rules.filter((rule) => !rule.locale) : rules;
|
|
96
|
+
const hit = matchRedirect(localePathname, shared);
|
|
97
|
+
return hit ? { ...hit, scoped: false } : null;
|
|
98
|
+
}
|
|
99
|
+
/** Strips the trailing slash (keeping the root "/"), for self-redirect comparison. */
|
|
100
|
+
export function stripTrailingSlash(value) {
|
|
101
|
+
return value.length > 1 && value.endsWith("/") ? value.slice(0, -1) : value;
|
|
102
|
+
}
|
|
103
|
+
/** Exact self-redirect (/foo and /foo/ are the same). */
|
|
104
|
+
export function isExactSelf(source, target) {
|
|
105
|
+
return stripTrailingSlash(source) === stripTrailingSlash(target);
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* A wildcard source whose in-site relative target falls inside what the source covers ("/*" to "/", "/blog/*" to "/blog/x").
|
|
109
|
+
* Targets outside it ("/blog/*" to "/about") and external URLs do not count.
|
|
110
|
+
*/
|
|
111
|
+
export function isScopeLoop(source, target) {
|
|
112
|
+
if (!source.endsWith("/*") || !target.startsWith("/"))
|
|
113
|
+
return false;
|
|
114
|
+
const srcPrefix = source.slice(0, -1); // "/blog/*" → "/blog/"
|
|
115
|
+
const targetBase = target.endsWith("/*") ? target.slice(0, -1) : target;
|
|
116
|
+
return targetBase.startsWith(srcPrefix);
|
|
117
|
+
}
|
|
118
|
+
/** Whether a single rule loops on itself (an exact self-redirect or a wildcard covering its own target). */
|
|
119
|
+
export function isSelfLoop(source, target) {
|
|
120
|
+
return isExactSelf(source, target) || isScopeLoop(source, target);
|
|
121
|
+
}
|
|
122
|
+
/**
|
|
123
|
+
* Finds the keys of rules that take part in a redirect loop across rules (for example /a to /b and /b to /a).
|
|
124
|
+
*
|
|
125
|
+
* Starting from each rule's representative path, it applies `matchRedirect` hop by hop and detects a cycle with a visited set.
|
|
126
|
+
* Single-rule self-loops should be handled first by the caller with `isSelfLoop`; this focuses on rules pointing at each other.
|
|
127
|
+
*
|
|
128
|
+
* Precision: `maxHops = number of rules + 1`. In this functional structure an acyclic walk ends after visiting at most as many
|
|
129
|
+
* distinct states as there are rules, so `number of rules + 1` is an exact bound with no false positives; a growing chain (never ending) is judged a loop once it exceeds the bound.
|
|
130
|
+
*/
|
|
131
|
+
export function findRedirectLoopKeys(rules) {
|
|
132
|
+
const loopKeys = new Set();
|
|
133
|
+
const maxHops = rules.length + 1;
|
|
134
|
+
let budget = MAX_TOTAL_STEPS;
|
|
135
|
+
for (const start of rules) {
|
|
136
|
+
if (budget <= 0)
|
|
137
|
+
break; // pathological input: the budget is spent, stop detecting (the runtime guard covers the rest)
|
|
138
|
+
const sample = start.sourcePath.endsWith("/*")
|
|
139
|
+
? start.sourcePath.slice(0, -1) + LOOP_PROBE
|
|
140
|
+
: start.sourcePath;
|
|
141
|
+
const seen = new Set([sample]);
|
|
142
|
+
const usedKeys = [];
|
|
143
|
+
let cur = sample;
|
|
144
|
+
for (let i = 0; i < maxHops; i++) {
|
|
145
|
+
if (budget-- <= 0 || cur === null) {
|
|
146
|
+
cur = null; // budget spent: conservatively treated as ended (not misjudged as a loop)
|
|
147
|
+
break;
|
|
148
|
+
}
|
|
149
|
+
// The type is annotated explicitly: cur is assigned matched.target at the end of the loop, and letting matched be inferred
|
|
150
|
+
// would form a circular inference with cur (TS7022). The annotation breaks the cycle.
|
|
151
|
+
const matched = matchRedirect(cur, rules);
|
|
152
|
+
// No match or an external URL: the redirect chain ends here, no loop
|
|
153
|
+
if (!matched || !matched.target.startsWith("/")) {
|
|
154
|
+
cur = null;
|
|
155
|
+
break;
|
|
156
|
+
}
|
|
157
|
+
usedKeys.push(matched.rule.key);
|
|
158
|
+
if (seen.has(matched.target)) {
|
|
159
|
+
// Back on a path already visited: a loop; mark every rule on the way
|
|
160
|
+
usedKeys.forEach((k) => loopKeys.add(k));
|
|
161
|
+
cur = null;
|
|
162
|
+
break;
|
|
163
|
+
}
|
|
164
|
+
seen.add(matched.target);
|
|
165
|
+
cur = matched.target;
|
|
166
|
+
}
|
|
167
|
+
// Still not ended after maxHops: a growing endless chain, conservatively treated as a loop
|
|
168
|
+
if (cur !== null)
|
|
169
|
+
usedKeys.forEach((k) => loopKeys.add(k));
|
|
170
|
+
}
|
|
171
|
+
return loopKeys;
|
|
172
|
+
}
|
|
173
|
+
/** Whether a redirect loop across rules exists. Check single-rule self-loops separately with `isSelfLoop`. */
|
|
174
|
+
export function hasRedirectChainLoop(rules) {
|
|
175
|
+
const keyed = rules.map((r, i) => ({
|
|
176
|
+
key: String(i),
|
|
177
|
+
sourcePath: r.sourcePath,
|
|
178
|
+
targetUrl: r.targetUrl,
|
|
179
|
+
}));
|
|
180
|
+
return findRedirectLoopKeys(keyed).size > 0;
|
|
181
|
+
}
|