@intlayer/core 9.3.2 → 9.4.0-canary.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/cjs/dictionaryManipulator/index.cjs +5 -1
- package/dist/cjs/dictionaryManipulator/plainDynamicLoader.cjs +71 -0
- package/dist/cjs/dictionaryManipulator/plainDynamicLoader.cjs.map +1 -0
- package/dist/cjs/dictionaryManipulator/preloadedDynamicLoader.cjs +29 -0
- package/dist/cjs/dictionaryManipulator/preloadedDynamicLoader.cjs.map +1 -0
- package/dist/cjs/dictionaryManipulator/qualifiedDynamicLoader.cjs +4 -10
- package/dist/cjs/dictionaryManipulator/qualifiedDynamicLoader.cjs.map +1 -1
- package/dist/cjs/index.cjs +13 -2
- package/dist/cjs/localization/comparePaths.cjs +1 -1
- package/dist/cjs/localization/comparePaths.cjs.map +1 -1
- package/dist/cjs/localization/domainUtils.cjs.map +1 -1
- package/dist/cjs/localization/getHTMLTextDir.cjs +11 -10
- package/dist/cjs/localization/getHTMLTextDir.cjs.map +1 -1
- package/dist/cjs/localization/getLocale.cjs.map +1 -1
- package/dist/cjs/localization/getLocaleFromPath.cjs +3 -3
- package/dist/cjs/localization/getLocaleFromPath.cjs.map +1 -1
- package/dist/cjs/localization/getLocalizedPath.cjs +74 -0
- package/dist/cjs/localization/getLocalizedPath.cjs.map +1 -0
- package/dist/cjs/localization/getLocalizedPath.test-d.cjs +83 -0
- package/dist/cjs/localization/getLocalizedPath.test-d.cjs.map +1 -0
- package/dist/cjs/localization/getLocalizedUrl.cjs +9 -25
- package/dist/cjs/localization/getLocalizedUrl.cjs.map +1 -1
- package/dist/cjs/localization/getLocalizedUrl.test-d.cjs +42 -0
- package/dist/cjs/localization/getLocalizedUrl.test-d.cjs.map +1 -0
- package/dist/cjs/localization/getPathWithoutLocale.cjs +2 -2
- package/dist/cjs/localization/getPathWithoutLocale.cjs.map +1 -1
- package/dist/cjs/localization/getPrefix.cjs +15 -1
- package/dist/cjs/localization/getPrefix.cjs.map +1 -1
- package/dist/cjs/localization/index.cjs +7 -1
- package/dist/cjs/localization/localeDetector.cjs +5 -3
- package/dist/cjs/localization/localeDetector.cjs.map +1 -1
- package/dist/cjs/localization/localeMapper.cjs.map +1 -1
- package/dist/cjs/localization/localeResolver.cjs.map +1 -1
- package/dist/cjs/localization/resolveBrowserLocale.cjs +63 -0
- package/dist/cjs/localization/resolveBrowserLocale.cjs.map +1 -0
- package/dist/cjs/localization/rewriteUtils.cjs +26 -14
- package/dist/cjs/localization/rewriteUtils.cjs.map +1 -1
- package/dist/cjs/localization/rewriteUtils.test-d.cjs +48 -0
- package/dist/cjs/localization/rewriteUtils.test-d.cjs.map +1 -0
- package/dist/cjs/markdown/constants.cjs +3 -0
- package/dist/cjs/markdown/constants.cjs.map +1 -1
- package/dist/cjs/markdown/index.cjs +1 -0
- package/dist/cjs/markdown/utils.cjs +23 -1
- package/dist/cjs/markdown/utils.cjs.map +1 -1
- package/dist/esm/dictionaryManipulator/index.mjs +2 -1
- package/dist/esm/dictionaryManipulator/plainDynamicLoader.mjs +70 -0
- package/dist/esm/dictionaryManipulator/plainDynamicLoader.mjs.map +1 -0
- package/dist/esm/dictionaryManipulator/preloadedDynamicLoader.mjs +27 -0
- package/dist/esm/dictionaryManipulator/preloadedDynamicLoader.mjs.map +1 -0
- package/dist/esm/dictionaryManipulator/qualifiedDynamicLoader.mjs +2 -8
- package/dist/esm/dictionaryManipulator/qualifiedDynamicLoader.mjs.map +1 -1
- package/dist/esm/index.mjs +7 -4
- package/dist/esm/localization/comparePaths.mjs +1 -1
- package/dist/esm/localization/comparePaths.mjs.map +1 -1
- package/dist/esm/localization/domainUtils.mjs.map +1 -1
- package/dist/esm/localization/getHTMLTextDir.mjs +11 -10
- package/dist/esm/localization/getHTMLTextDir.mjs.map +1 -1
- package/dist/esm/localization/getLocale.mjs.map +1 -1
- package/dist/esm/localization/getLocaleFromPath.mjs +4 -4
- package/dist/esm/localization/getLocaleFromPath.mjs.map +1 -1
- package/dist/esm/localization/getLocalizedPath.mjs +73 -0
- package/dist/esm/localization/getLocalizedPath.mjs.map +1 -0
- package/dist/esm/localization/getLocalizedPath.test-d.mjs +83 -0
- package/dist/esm/localization/getLocalizedPath.test-d.mjs.map +1 -0
- package/dist/esm/localization/getLocalizedUrl.mjs +10 -26
- package/dist/esm/localization/getLocalizedUrl.mjs.map +1 -1
- package/dist/esm/localization/getLocalizedUrl.test-d.mjs +42 -0
- package/dist/esm/localization/getLocalizedUrl.test-d.mjs.map +1 -0
- package/dist/esm/localization/getPathWithoutLocale.mjs +2 -2
- package/dist/esm/localization/getPathWithoutLocale.mjs.map +1 -1
- package/dist/esm/localization/getPrefix.mjs +15 -2
- package/dist/esm/localization/getPrefix.mjs.map +1 -1
- package/dist/esm/localization/index.mjs +5 -3
- package/dist/esm/localization/localeDetector.mjs +5 -3
- package/dist/esm/localization/localeDetector.mjs.map +1 -1
- package/dist/esm/localization/localeMapper.mjs.map +1 -1
- package/dist/esm/localization/localeResolver.mjs.map +1 -1
- package/dist/esm/localization/resolveBrowserLocale.mjs +61 -0
- package/dist/esm/localization/resolveBrowserLocale.mjs.map +1 -0
- package/dist/esm/localization/rewriteUtils.mjs +26 -14
- package/dist/esm/localization/rewriteUtils.mjs.map +1 -1
- package/dist/esm/localization/rewriteUtils.test-d.mjs +48 -0
- package/dist/esm/localization/rewriteUtils.test-d.mjs.map +1 -0
- package/dist/esm/markdown/constants.mjs +3 -1
- package/dist/esm/markdown/constants.mjs.map +1 -1
- package/dist/esm/markdown/index.mjs +2 -2
- package/dist/esm/markdown/utils.mjs +24 -2
- package/dist/esm/markdown/utils.mjs.map +1 -1
- package/dist/types/dictionaryManipulator/index.d.ts +2 -1
- package/dist/types/dictionaryManipulator/plainDynamicLoader.d.ts +50 -0
- package/dist/types/dictionaryManipulator/plainDynamicLoader.d.ts.map +1 -0
- package/dist/types/dictionaryManipulator/preloadedDynamicLoader.d.ts +38 -0
- package/dist/types/dictionaryManipulator/preloadedDynamicLoader.d.ts.map +1 -0
- package/dist/types/dictionaryManipulator/qualifiedDynamicLoader.d.ts +1 -7
- package/dist/types/dictionaryManipulator/qualifiedDynamicLoader.d.ts.map +1 -1
- package/dist/types/index.d.ts +7 -4
- package/dist/types/localization/domainUtils.d.ts +2 -3
- package/dist/types/localization/domainUtils.d.ts.map +1 -1
- package/dist/types/localization/getHTMLTextDir.d.ts.map +1 -1
- package/dist/types/localization/getLocale.d.ts +2 -2
- package/dist/types/localization/getLocale.d.ts.map +1 -1
- package/dist/types/localization/getLocaleFromPath.d.ts +2 -2
- package/dist/types/localization/getLocaleFromPath.d.ts.map +1 -1
- package/dist/types/localization/getLocalizedPath.d.ts +47 -0
- package/dist/types/localization/getLocalizedPath.d.ts.map +1 -0
- package/dist/types/localization/getLocalizedPath.test-d.d.ts +1 -0
- package/dist/types/localization/getLocalizedUrl.d.ts +5 -1
- package/dist/types/localization/getLocalizedUrl.d.ts.map +1 -1
- package/dist/types/localization/getLocalizedUrl.test-d.d.ts +1 -0
- package/dist/types/localization/getPrefix.d.ts +20 -8
- package/dist/types/localization/getPrefix.d.ts.map +1 -1
- package/dist/types/localization/index.d.ts +5 -3
- package/dist/types/localization/localeDetector.d.ts +2 -1
- package/dist/types/localization/localeDetector.d.ts.map +1 -1
- package/dist/types/localization/localeMapper.d.ts +4 -5
- package/dist/types/localization/localeMapper.d.ts.map +1 -1
- package/dist/types/localization/localeResolver.d.ts +2 -3
- package/dist/types/localization/localeResolver.d.ts.map +1 -1
- package/dist/types/localization/resolveBrowserLocale.d.ts +35 -0
- package/dist/types/localization/resolveBrowserLocale.d.ts.map +1 -0
- package/dist/types/localization/rewriteUtils.d.ts +51 -11
- package/dist/types/localization/rewriteUtils.d.ts.map +1 -1
- package/dist/types/localization/rewriteUtils.test-d.d.ts +1 -0
- package/dist/types/markdown/constants.d.ts +3 -1
- package/dist/types/markdown/constants.d.ts.map +1 -1
- package/dist/types/markdown/index.d.ts +2 -2
- package/dist/types/markdown/utils.d.ts +6 -0
- package/dist/types/markdown/utils.d.ts.map +1 -1
- package/package.json +7 -7
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
2
|
+
const require_localization_domainUtils = require('./domainUtils.cjs');
|
|
3
|
+
const require_localization_getPrefix = require('./getPrefix.cjs');
|
|
4
|
+
const require_utils_localeStorage = require('../utils/localeStorage.cjs');
|
|
5
|
+
const require_localization_getLocaleFromPath = require('./getLocaleFromPath.cjs');
|
|
6
|
+
|
|
7
|
+
//#region src/localization/resolveBrowserLocale.ts
|
|
8
|
+
/**
|
|
9
|
+
* Resolves the locale of the current document outside of React.
|
|
10
|
+
*
|
|
11
|
+
* Generated dynamic entry points need the locale while they are still
|
|
12
|
+
* evaluating, long before a provider exists, so this reproduces the precedence
|
|
13
|
+
* a provider applies — URL first (which is what a router hands the provider as
|
|
14
|
+
* `locale`), then browser storage, then the configured default. Agreeing with
|
|
15
|
+
* the provider is what makes the preloaded read hit; disagreeing is safe but
|
|
16
|
+
* costs a load, since the consumer compares locales before using a preloaded
|
|
17
|
+
* dictionary.
|
|
18
|
+
*
|
|
19
|
+
* @param options - Routing overrides, defaulting to the built configuration.
|
|
20
|
+
* @returns The resolved locale, falling back to the default locale off-browser.
|
|
21
|
+
*/
|
|
22
|
+
const resolveBrowserLocale = (options) => {
|
|
23
|
+
const { defaultLocale, mode, domains } = require_localization_getPrefix.resolveRoutingConfig(options);
|
|
24
|
+
if (typeof window === "undefined") return defaultLocale;
|
|
25
|
+
if (domains) {
|
|
26
|
+
const localeFromDomain = require_localization_domainUtils.getLocaleFromDomain(window.location.hostname, domains);
|
|
27
|
+
if (localeFromDomain) return localeFromDomain;
|
|
28
|
+
}
|
|
29
|
+
if (mode === "prefix-all" || mode === "prefix-no-default" || mode === "search-params" && new URLSearchParams(window.location.search).has("locale")) {
|
|
30
|
+
const localeFromPath = require_localization_getLocaleFromPath.getLocaleFromPath(window.location.pathname + window.location.search, options);
|
|
31
|
+
if (localeFromPath) return localeFromPath;
|
|
32
|
+
}
|
|
33
|
+
return require_utils_localeStorage.getLocaleFromStorageClient() ?? defaultLocale;
|
|
34
|
+
};
|
|
35
|
+
/** URL (path + search) the memoized locale below was resolved against. */
|
|
36
|
+
let memoizedUrl;
|
|
37
|
+
let memoizedLocale;
|
|
38
|
+
/**
|
|
39
|
+
* {@link resolveBrowserLocale}, memoized for the current URL.
|
|
40
|
+
*
|
|
41
|
+
* Every generated dynamic entry point calls this as it evaluates, and an
|
|
42
|
+
* application has hundreds of them — repeating the cookie and storage reads
|
|
43
|
+
* that many times on startup is pure cost, since they cannot change while a
|
|
44
|
+
* page is being assembled.
|
|
45
|
+
*
|
|
46
|
+
* Keying the cache on the URL rather than caching forever keeps a client-side
|
|
47
|
+
* locale change honest: navigating to another locale's URL loads further
|
|
48
|
+
* chunks with that locale, instead of preloading the old one and silently
|
|
49
|
+
* falling back to an asynchronous read.
|
|
50
|
+
*/
|
|
51
|
+
const getPreloadLocale = () => {
|
|
52
|
+
const currentUrl = typeof window === "undefined" ? "" : window.location.pathname + window.location.search;
|
|
53
|
+
if (memoizedLocale === void 0 || memoizedUrl !== currentUrl) {
|
|
54
|
+
memoizedUrl = currentUrl;
|
|
55
|
+
memoizedLocale = resolveBrowserLocale();
|
|
56
|
+
}
|
|
57
|
+
return memoizedLocale;
|
|
58
|
+
};
|
|
59
|
+
|
|
60
|
+
//#endregion
|
|
61
|
+
exports.getPreloadLocale = getPreloadLocale;
|
|
62
|
+
exports.resolveBrowserLocale = resolveBrowserLocale;
|
|
63
|
+
//# sourceMappingURL=resolveBrowserLocale.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"resolveBrowserLocale.cjs","names":["resolveRoutingConfig","getLocaleFromDomain","getLocaleFromPath","getLocaleFromStorageClient"],"sources":["../../../src/localization/resolveBrowserLocale.ts"],"sourcesContent":["import type { LocalesValues } from '@intlayer/types/module_augmentation';\nimport { getLocaleFromStorageClient } from '../utils/localeStorage';\nimport { getLocaleFromDomain } from './domainUtils';\nimport { getLocaleFromPath } from './getLocaleFromPath';\nimport { type RoutingOptions, resolveRoutingConfig } from './getPrefix';\n\n/**\n * Resolves the locale of the current document outside of React.\n *\n * Generated dynamic entry points need the locale while they are still\n * evaluating, long before a provider exists, so this reproduces the precedence\n * a provider applies — URL first (which is what a router hands the provider as\n * `locale`), then browser storage, then the configured default. Agreeing with\n * the provider is what makes the preloaded read hit; disagreeing is safe but\n * costs a load, since the consumer compares locales before using a preloaded\n * dictionary.\n *\n * @param options - Routing overrides, defaulting to the built configuration.\n * @returns The resolved locale, falling back to the default locale off-browser.\n */\nexport const resolveBrowserLocale = (\n options?: RoutingOptions\n): LocalesValues => {\n const { defaultLocale, mode, domains } = resolveRoutingConfig(options);\n\n if (typeof window === 'undefined') return defaultLocale;\n\n // A domain mapped to exactly one locale identifies it on its own, and no URL\n // prefix is emitted for it — so it has to be consulted before the path.\n if (domains) {\n const localeFromDomain = getLocaleFromDomain(\n window.location.hostname,\n domains\n );\n if (localeFromDomain) return localeFromDomain;\n }\n\n // Only a URL that actually carries a locale may take precedence over a\n // stored preference: in `no-prefix`, and in `search-params` without the\n // parameter, `getLocaleFromPath` answers the default locale — which is not\n // what a provider would receive from its router, and would shadow storage.\n const urlCarriesLocale =\n mode === 'prefix-all' ||\n mode === 'prefix-no-default' ||\n (mode === 'search-params' &&\n new URLSearchParams(window.location.search).has('locale'));\n\n if (urlCarriesLocale) {\n const localeFromPath = getLocaleFromPath(\n window.location.pathname + window.location.search,\n options\n );\n if (localeFromPath) return localeFromPath;\n }\n\n return getLocaleFromStorageClient() ?? defaultLocale;\n};\n\n/** URL (path + search) the memoized locale below was resolved against. */\nlet memoizedUrl: string | undefined;\nlet memoizedLocale: LocalesValues | undefined;\n\n/**\n * {@link resolveBrowserLocale}, memoized for the current URL.\n *\n * Every generated dynamic entry point calls this as it evaluates, and an\n * application has hundreds of them — repeating the cookie and storage reads\n * that many times on startup is pure cost, since they cannot change while a\n * page is being assembled.\n *\n * Keying the cache on the URL rather than caching forever keeps a client-side\n * locale change honest: navigating to another locale's URL loads further\n * chunks with that locale, instead of preloading the old one and silently\n * falling back to an asynchronous read.\n */\nexport const getPreloadLocale = (): LocalesValues => {\n const currentUrl =\n typeof window === 'undefined'\n ? ''\n : window.location.pathname + window.location.search;\n\n if (memoizedLocale === undefined || memoizedUrl !== currentUrl) {\n memoizedUrl = currentUrl;\n memoizedLocale = resolveBrowserLocale();\n }\n\n return memoizedLocale;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAoBA,MAAa,wBACX,YACkB;CAClB,MAAM,EAAE,eAAe,MAAM,YAAYA,oDAAqB,OAAO;CAErE,IAAI,OAAO,WAAW,aAAa,OAAO;CAI1C,IAAI,SAAS;EACX,MAAM,mBAAmBC,qDACvB,OAAO,SAAS,UAChB,OACF;EACA,IAAI,kBAAkB,OAAO;CAC/B;CAYA,IALE,SAAS,gBACT,SAAS,uBACR,SAAS,mBACR,IAAI,gBAAgB,OAAO,SAAS,MAAM,CAAC,CAAC,IAAI,QAAQ,GAEtC;EACpB,MAAM,iBAAiBC,yDACrB,OAAO,SAAS,WAAW,OAAO,SAAS,QAC3C,OACF;EACA,IAAI,gBAAgB,OAAO;CAC7B;CAEA,OAAOC,uDAA2B,KAAK;AACzC;;AAGA,IAAI;AACJ,IAAI;;;;;;;;;;;;;;AAeJ,MAAa,yBAAwC;CACnD,MAAM,aACJ,OAAO,WAAW,cACd,KACA,OAAO,SAAS,WAAW,OAAO,SAAS;CAEjD,IAAI,mBAAmB,UAAa,gBAAgB,YAAY;EAC9D,cAAc;EACd,iBAAiB,qBAAqB;CACxC;CAEA,OAAO;AACT"}
|
|
@@ -1,15 +1,16 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
2
|
+
let _intlayer_config_built = require("@intlayer/config/built");
|
|
3
|
+
|
|
2
4
|
//#region src/localization/rewriteUtils.ts
|
|
3
5
|
/**
|
|
4
|
-
* True when rewrite rules are explicitly disabled at build time
|
|
5
|
-
* (INTLAYER_ROUTING_REWRITE_RULES === 'false').
|
|
6
|
-
*/
|
|
7
|
-
const TREE_SHAKE_REWRITE = process.env.INTLAYER_ROUTING_REWRITE_RULES === "false";
|
|
8
|
-
/**
|
|
9
6
|
* Normalizes legacy Record format or extracts specialized rules from RewriteObject.
|
|
7
|
+
*
|
|
8
|
+
* Idempotent: already-normalized rules are handed back untouched, so a caller
|
|
9
|
+
* holding resolved rules can pass them on without re-normalizing.
|
|
10
10
|
*/
|
|
11
11
|
const getRewriteRules = (rewrite, context = "url") => {
|
|
12
|
-
if (!rewrite ||
|
|
12
|
+
if (!rewrite || process.env.INTLAYER_ROUTING_REWRITE_RULES && process.env.INTLAYER_ROUTING_REWRITE_RULES === "false") return void 0;
|
|
13
|
+
if (Array.isArray(rewrite.rules)) return rewrite;
|
|
13
14
|
if ("url" in rewrite) return rewrite[context];
|
|
14
15
|
return { rules: Object.entries(rewrite).map(([canonical, localized]) => ({
|
|
15
16
|
canonical: canonical.startsWith("/") ? canonical.replace(/\[([^\]]+)\]/g, ":$1") : `/${canonical.replace(/\[([^\]]+)\]/g, ":$1")}`,
|
|
@@ -50,7 +51,7 @@ const extractParams = (url, pattern) => {
|
|
|
50
51
|
* If locale is provided, only check for that locale. Otherwise, check for all locales.
|
|
51
52
|
*/
|
|
52
53
|
const getCanonicalPath = (localizedPath, locale, rewriteRules) => {
|
|
53
|
-
if (!rewriteRules ||
|
|
54
|
+
if (!rewriteRules || process.env.INTLAYER_ROUTING_REWRITE_RULES && process.env.INTLAYER_ROUTING_REWRITE_RULES === "false") return localizedPath;
|
|
54
55
|
for (const rule of rewriteRules.rules) {
|
|
55
56
|
const { canonical, localized } = rule;
|
|
56
57
|
const localesToCheck = locale ? [locale] : Object.keys(localized);
|
|
@@ -64,10 +65,21 @@ const getCanonicalPath = (localizedPath, locale, rewriteRules) => {
|
|
|
64
65
|
return localizedPath;
|
|
65
66
|
};
|
|
66
67
|
/**
|
|
67
|
-
* Given a canonical path (e.g., "/products/123"), finds the localized URL pattern
|
|
68
|
+
* Given a canonical path (e.g., "/products/123"), finds the localized URL pattern
|
|
69
|
+
* (e.g., "/produits/123") and reports whether a rule actually matched.
|
|
70
|
+
*
|
|
71
|
+
* Takes already-normalized rules, so callers that resolve the rules once (proxies,
|
|
72
|
+
* static emitters) can reuse them. {@link getLocalizedPath} is the user-facing
|
|
73
|
+
* counterpart: it accepts the raw `routing.rewrite` configuration, defaults to the
|
|
74
|
+
* project configuration, and returns the path alone.
|
|
75
|
+
*
|
|
76
|
+
* @param canonicalPath - The internal application path (e.g. `/product/:id`, `/about`).
|
|
77
|
+
* @param locale - The target locale. Defaults to the configured default locale.
|
|
78
|
+
* @param rewriteRules - Normalized rules, as returned by {@link getRewriteRules}.
|
|
79
|
+
* @returns The localized path, discriminated on whether a rewrite rule matched.
|
|
68
80
|
*/
|
|
69
|
-
const
|
|
70
|
-
if (!rewriteRules ||
|
|
81
|
+
const resolveLocalizedPath = (canonicalPath, locale, rewriteRules) => {
|
|
82
|
+
if (!rewriteRules || process.env.INTLAYER_ROUTING_REWRITE_RULES && process.env.INTLAYER_ROUTING_REWRITE_RULES === "false") return {
|
|
71
83
|
path: canonicalPath,
|
|
72
84
|
isRewritten: false
|
|
73
85
|
};
|
|
@@ -75,7 +87,7 @@ const getLocalizedPath = (canonicalPath, locale, rewriteRules) => {
|
|
|
75
87
|
const { canonical, localized } = rule;
|
|
76
88
|
const params = extractParams(canonicalPath, canonical);
|
|
77
89
|
if (params) {
|
|
78
|
-
const targetPattern = localized[locale];
|
|
90
|
+
const targetPattern = localized[locale ?? _intlayer_config_built.internationalization.defaultLocale];
|
|
79
91
|
if (targetPattern) return {
|
|
80
92
|
path: fillPath(targetPattern, params),
|
|
81
93
|
isRewritten: true
|
|
@@ -100,18 +112,18 @@ const getInternalPath = (canonicalPath, locale) => {
|
|
|
100
112
|
* Given a current pathname and locale, returns the pretty localized path if a rewrite rule exists and the path is not already localized.
|
|
101
113
|
*/
|
|
102
114
|
const getRewritePath = (pathname, locale, rewrite) => {
|
|
103
|
-
if (
|
|
115
|
+
if (process.env.INTLAYER_ROUTING_REWRITE_RULES && process.env.INTLAYER_ROUTING_REWRITE_RULES === "false") return void 0;
|
|
104
116
|
const rules = getRewriteRules(rewrite, "url");
|
|
105
117
|
if (!rules) return void 0;
|
|
106
118
|
const canonicalPath = getCanonicalPath(pathname, void 0, rules);
|
|
107
|
-
const { path: localizedPath, isRewritten } =
|
|
119
|
+
const { path: localizedPath, isRewritten } = resolveLocalizedPath(canonicalPath, locale, rules);
|
|
108
120
|
if (isRewritten && localizedPath !== pathname) return localizedPath;
|
|
109
121
|
};
|
|
110
122
|
|
|
111
123
|
//#endregion
|
|
112
124
|
exports.getCanonicalPath = getCanonicalPath;
|
|
113
125
|
exports.getInternalPath = getInternalPath;
|
|
114
|
-
exports.getLocalizedPath = getLocalizedPath;
|
|
115
126
|
exports.getRewritePath = getRewritePath;
|
|
116
127
|
exports.getRewriteRules = getRewriteRules;
|
|
128
|
+
exports.resolveLocalizedPath = resolveLocalizedPath;
|
|
117
129
|
//# sourceMappingURL=rewriteUtils.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"rewriteUtils.cjs","names":[],"sources":["../../../src/localization/rewriteUtils.ts"],"sourcesContent":["// ── Tree-shake constants ──────────────────────────────────────────────────────\n// When these env vars are injected at build time, bundlers eliminate the\n// branches guarded by these constants.\n\n/**\n * True when rewrite rules are explicitly disabled at build time\n * (INTLAYER_ROUTING_REWRITE_RULES === 'false').\n */\nconst TREE_SHAKE_REWRITE =\n process.env.INTLAYER_ROUTING_REWRITE_RULES === 'false';\n\nimport type { Locale } from '@intlayer/types/allLocales';\nimport type {\n RewriteObject,\n RewriteRules,\n RoutingConfig,\n} from '@intlayer/types/config';\nimport type { LocalesValues } from '@intlayer/types/module_augmentation';\n\nexport type LocalizedPathResult = {\n path: string;\n isRewritten: boolean;\n};\n\n/**\n * Normalizes legacy Record format or extracts specialized rules from RewriteObject.\n */\nexport const getRewriteRules = (\n rewrite: RoutingConfig['rewrite'],\n context: keyof RewriteObject = 'url'\n): RewriteRules | undefined => {\n if (!rewrite || TREE_SHAKE_REWRITE) return undefined;\n\n if ('url' in rewrite) {\n return (rewrite as RewriteObject)[context];\n }\n\n // Normalize legacy format\n return {\n rules: Object.entries(rewrite).map(([canonical, localized]) => ({\n // Normalize canonical path\n canonical: canonical.startsWith('/')\n ? canonical.replace(/\\[([^\\]]+)\\]/g, ':$1')\n : `/${canonical.replace(/\\[([^\\]]+)\\]/g, ':$1')}`,\n\n // Normalize localized path\n localized: Object.fromEntries(\n Object.entries(localized).map(([locale, pattern]) => {\n const normalizedPattern = pattern?.startsWith('/')\n ? pattern.replace(/\\[([^\\]]+)\\]/g, ':$1')\n : `/${(pattern || '').replace(/\\[([^\\]]+)\\]/g, ':$1')}`;\n return [locale, normalizedPattern];\n })\n ),\n })),\n };\n};\n\n/**\n * Converts normalized pattern to Regex.\n * Internal syntax supports:\n * - :param -> ([^/]+) (one segment)\n * - :param* -> (.*) (zero or more segments)\n * - :param+ -> (.+) (one or more segments)\n * - :param? -> ([^/]*) (zero or one segment)\n */\nconst patternToRegex = (pattern: string) => {\n const regexString = pattern\n .replace(/\\//g, '\\\\/') // Escape slashes\n .replace(/\\\\\\/:(?:[^/\\\\*+?]+)\\*/g, '(?:\\\\/(.*))?') // /:param*\n .replace(/\\\\\\/:(?:[^/\\\\*+?]+)\\?/g, '(?:\\\\/([^\\\\/]+))?') // /:param?\n .replace(/:([^/\\\\*+?]+)\\*/g, '(.*)') // :param* (if no leading slash)\n .replace(/:([^/\\\\*+?]+)\\?/g, '([^\\\\/]*)') // :param? (if no leading slash)\n .replace(/:([^/\\\\*+?]+)\\+/g, '(.+)') // :param+\n .replace(/:([^/\\\\*+?]+)/g, '([^\\\\/]+)'); // :param\n\n return new RegExp(`^${regexString}$`);\n};\n\n/**\n * Replaces route parameters in a path with provided values.\n */\nconst fillPath = (pattern: string, params: string[]) => {\n let index = 0;\n return (\n pattern\n .replace(/:([^/\\\\*+?]+)[*+?]?/g, () => params[index++] ?? '')\n .replace(/\\/+/g, '/')\n .replace(/\\/$/, '') || '/'\n );\n};\n\n/**\n * Extract values from a URL based on a pattern.\n */\nconst extractParams = (url: string, pattern: string): string[] | null => {\n const regex = patternToRegex(pattern);\n const match = url.match(regex);\n return match ? match.slice(1) : null;\n};\n\n/**\n * Given a localized URL (e.g., \"/produits/123\"), finds the canonical internal path (e.g., \"/products/123\").\n * If locale is provided, only check for that locale. Otherwise, check for all locales.\n */\nexport const getCanonicalPath = (\n localizedPath: string,\n locale?: Locale,\n rewriteRules?: RewriteRules\n): string => {\n if (!rewriteRules || TREE_SHAKE_REWRITE) return localizedPath;\n\n for (const rule of rewriteRules.rules) {\n const { canonical, localized } = rule;\n const localesToCheck = locale ? [locale] : Object.keys(localized);\n\n for (const loc of localesToCheck) {\n const localizedPattern = localized[loc as keyof typeof localized];\n\n if (!localizedPattern) continue;\n\n const params = extractParams(localizedPath, localizedPattern);\n\n if (params) {\n return fillPath(canonical, params);\n }\n }\n }\n\n return localizedPath;\n};\n\n/**\n * Given a canonical path (e.g., \"/products/123\"), finds the localized URL pattern (e.g., \"/produits/123\").\n */\nexport const getLocalizedPath = (\n canonicalPath: string,\n locale: LocalesValues,\n rewriteRules?: RewriteRules\n): LocalizedPathResult => {\n if (!rewriteRules || TREE_SHAKE_REWRITE)\n return { path: canonicalPath, isRewritten: false };\n\n for (const rule of rewriteRules.rules) {\n const { canonical, localized } = rule;\n\n // Check if the input path matches a configured canonical pattern\n const params = extractParams(canonicalPath, canonical);\n\n if (params) {\n const targetPattern = localized[locale as keyof typeof localized];\n\n if (targetPattern) {\n return {\n path: fillPath(targetPattern, params),\n isRewritten: true,\n };\n }\n }\n }\n\n return { path: canonicalPath, isRewritten: false };\n};\n\n/**\n * Returns the internal path for a given canonical path and locale.\n * Ensures the locale prefix is present exactly once.\n */\nexport const getInternalPath = (\n canonicalPath: string,\n locale: Locale\n): string => {\n const pathWithLeadingSlash = canonicalPath.startsWith('/')\n ? canonicalPath\n : `/${canonicalPath}`;\n\n if (\n pathWithLeadingSlash.startsWith(`/${locale}/`) ||\n pathWithLeadingSlash === `/${locale}`\n ) {\n return pathWithLeadingSlash;\n }\n\n return `/${locale}${pathWithLeadingSlash === '/' ? '' : pathWithLeadingSlash}`;\n};\n\n/**\n * Given a current pathname and locale, returns the pretty localized path if a rewrite rule exists and the path is not already localized.\n */\nexport const getRewritePath = (\n pathname: string,\n locale: Locale,\n rewrite?: RoutingConfig['rewrite']\n): string | undefined => {\n if (TREE_SHAKE_REWRITE) return undefined;\n const rules = getRewriteRules(rewrite, 'url');\n if (!rules) return undefined;\n\n // Identify canonical path (relative to root, no locale prefix expected in 'url' context)\n const canonicalPath = getCanonicalPath(pathname, undefined, rules);\n\n // Get the localized path for the current locale\n const { path: localizedPath, isRewritten } = getLocalizedPath(\n canonicalPath,\n locale,\n rules\n );\n\n if (isRewritten && localizedPath !== pathname) {\n return localizedPath;\n }\n\n return undefined;\n};\n"],"mappings":";;;;;;AAQA,MAAM,qBACJ,QAAQ,IAAI,mCAAmC;;;;AAkBjD,MAAa,mBACX,SACA,UAA+B,UACF;CAC7B,IAAI,CAAC,WAAW,oBAAoB,OAAO;CAE3C,IAAI,SAAS,SACX,OAAQ,QAA0B;CAIpC,OAAO,EACL,OAAO,OAAO,QAAQ,OAAO,CAAC,CAAC,KAAK,CAAC,WAAW,gBAAgB;EAE9D,WAAW,UAAU,WAAW,GAAG,IAC/B,UAAU,QAAQ,iBAAiB,KAAK,IACxC,IAAI,UAAU,QAAQ,iBAAiB,KAAK;EAGhD,WAAW,OAAO,YAChB,OAAO,QAAQ,SAAS,CAAC,CAAC,KAAK,CAAC,QAAQ,aAAa;GAInD,OAAO,CAAC,QAHkB,SAAS,WAAW,GAAG,IAC7C,QAA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,iBACwB;CACxB,IAAI,CAAC,gBAAgB,oBACnB,OAAO;EAAE,MAAM;EAAe,aAAa;CAAM;CAEnD,KAAK,MAAM,QAAQ,aAAa,OAAO;EACrC,MAAM,EAAE,WAAW,cAAc;EAGjC,MAAM,SAAS,cAAc,eAAe,SAAS;EAErD,IAAI,QAAQ;GACV,MAAM,gBAAgB,UAAU;GAEhC,IAAI,eACF,OAAO;IACL,MAAM,SAAS,eAAe,MAAM;IACpC,aAAa;GACf;EAEJ;CACF;CAEA,OAAO;EAAE,MAAM;EAAe,aAAa;CAAM;AACnD;;;;;AAMA,MAAa,mBACX,eACA,WACW;CACX,MAAM,uBAAuB,cAAc,WAAW,GAAG,IACrD,gBACA,IAAI;CAER,IACE,qBAAqB,WAAW,IAAI,OAAO,EAAE,KAC7C,yBAAyB,IAAI,UAE7B,OAAO;CAGT,OAAO,IAAI,SAAS,yBAAyB,MAAM,KAAK;AAC1D;;;;AAKA,MAAa,kBACX,UACA,QACA,YACuB;CACvB,IAAI,oBAAoB,OAAO;CAC/B,MAAM,QAAQ,gBAAgB,SAAS,KAAK;CAC5C,IAAI,CAAC,OAAO,OAAO;CAGnB,MAAM,gBAAgB,iBAAiB,UAAU,QAAW,KAAK;CAGjE,MAAM,EAAE,MAAM,eAAe,gBAAgB,iBAC3C,eACA,QACA,KACF;CAEA,IAAI,eAAe,kBAAkB,UACnC,OAAO;AAIX"}
|
|
1
|
+
{"version":3,"file":"rewriteUtils.cjs","names":["legacyRules","internationalization"],"sources":["../../../src/localization/rewriteUtils.ts"],"sourcesContent":["import { internationalization } from '@intlayer/config/built';\nimport type {\n RewriteObject,\n RewriteRules,\n RoutingConfig,\n} from '@intlayer/types/config';\nimport type {\n LocalesValues,\n ResolvedDefaultLocale,\n} from '@intlayer/types/module_augmentation';\n\n/**\n * Outcome of resolving a canonical path against the rewrite rules.\n *\n * Discriminated on `isRewritten`: when no rule matched, `path` is the very\n * input that was passed in, so a literal input keeps its literal type. Only a\n * rewritten path is computed at runtime and therefore widens to `string`.\n */\nexport type LocalizedPathResult<CanonicalPath extends string = string> =\n | { path: CanonicalPath; isRewritten: false }\n | { path: string; isRewritten: true };\n\n/** Adds the leading slash a path may be missing. */\ntype WithLeadingSlash<Path extends string> = Path extends `/${string}`\n ? Path\n : `/${Path}`;\n\n/**\n * Computes the locale-prefixed internal path for a path and a locale, mirroring\n * `getInternalPath`'s runtime behaviour: an already-prefixed path is returned\n * untouched, the root collapses to `/${Locale}` (never a trailing slash), and\n * anything else gets the prefix prepended.\n *\n * Falls back to `string` for a non-literal path, where the prefixed and\n * already-prefixed cases cannot be told apart.\n *\n * @example\n * type A = InternalPath<'/about', 'fr'>; // '/fr/about'\n * type B = InternalPath<'/', 'fr'>; // '/fr'\n * type C = InternalPath<'/fr/about', 'fr'>; // '/fr/about' (already prefixed)\n */\nexport type InternalPath<\n Path extends string,\n Locale extends string,\n> = string extends Path\n ? string\n : WithLeadingSlash<Path> extends infer Prefixed extends string\n ? Prefixed extends `/${Locale}` | `/${Locale}/${string}`\n ? Prefixed\n : Prefixed extends '/'\n ? `/${Locale}`\n : `/${Locale}${Prefixed}`\n : never;\n\n/**\n * Normalizes legacy Record format or extracts specialized rules from RewriteObject.\n *\n * Idempotent: already-normalized rules are handed back untouched, so a caller\n * holding resolved rules can pass them on without re-normalizing.\n */\nexport const getRewriteRules = <\n const Context extends keyof RewriteObject = 'url',\n>(\n rewrite: RoutingConfig['rewrite'] | RewriteRules,\n context: Context = 'url' as Context\n): RewriteRules | undefined => {\n if (\n !rewrite ||\n (process.env.INTLAYER_ROUTING_REWRITE_RULES &&\n process.env.INTLAYER_ROUTING_REWRITE_RULES === 'false')\n )\n return undefined;\n\n if (Array.isArray((rewrite as RewriteRules).rules)) {\n return rewrite as RewriteRules;\n }\n\n if ('url' in rewrite) {\n return (rewrite as RewriteObject)[context];\n }\n\n // Normalize legacy format\n const legacyRules = rewrite as Record<string, Record<string, string>>;\n\n return {\n rules: Object.entries(legacyRules).map(([canonical, localized]) => ({\n // Normalize canonical path\n canonical: canonical.startsWith('/')\n ? canonical.replace(/\\[([^\\]]+)\\]/g, ':$1')\n : `/${canonical.replace(/\\[([^\\]]+)\\]/g, ':$1')}`,\n\n // Normalize localized path\n localized: Object.fromEntries(\n Object.entries(localized).map(([locale, pattern]) => {\n const normalizedPattern = pattern?.startsWith('/')\n ? pattern.replace(/\\[([^\\]]+)\\]/g, ':$1')\n : `/${(pattern || '').replace(/\\[([^\\]]+)\\]/g, ':$1')}`;\n return [locale, normalizedPattern];\n })\n ),\n })),\n };\n};\n\n/**\n * Converts normalized pattern to Regex.\n * Internal syntax supports:\n * - :param -> ([^/]+) (one segment)\n * - :param* -> (.*) (zero or more segments)\n * - :param+ -> (.+) (one or more segments)\n * - :param? -> ([^/]*) (zero or one segment)\n */\nconst patternToRegex = (pattern: string) => {\n const regexString = pattern\n .replace(/\\//g, '\\\\/') // Escape slashes\n .replace(/\\\\\\/:(?:[^/\\\\*+?]+)\\*/g, '(?:\\\\/(.*))?') // /:param*\n .replace(/\\\\\\/:(?:[^/\\\\*+?]+)\\?/g, '(?:\\\\/([^\\\\/]+))?') // /:param?\n .replace(/:([^/\\\\*+?]+)\\*/g, '(.*)') // :param* (if no leading slash)\n .replace(/:([^/\\\\*+?]+)\\?/g, '([^\\\\/]*)') // :param? (if no leading slash)\n .replace(/:([^/\\\\*+?]+)\\+/g, '(.+)') // :param+\n .replace(/:([^/\\\\*+?]+)/g, '([^\\\\/]+)'); // :param\n\n return new RegExp(`^${regexString}$`);\n};\n\n/**\n * Replaces route parameters in a path with provided values.\n */\nconst fillPath = (pattern: string, params: string[]) => {\n let index = 0;\n return (\n pattern\n .replace(/:([^/\\\\*+?]+)[*+?]?/g, () => params[index++] ?? '')\n .replace(/\\/+/g, '/')\n .replace(/\\/$/, '') || '/'\n );\n};\n\n/**\n * Extract values from a URL based on a pattern.\n */\nconst extractParams = (url: string, pattern: string): string[] | null => {\n const regex = patternToRegex(pattern);\n const match = url.match(regex);\n return match ? match.slice(1) : null;\n};\n\n/**\n * Given a localized URL (e.g., \"/produits/123\"), finds the canonical internal path (e.g., \"/products/123\").\n * If locale is provided, only check for that locale. Otherwise, check for all locales.\n */\nexport const getCanonicalPath = <\n const Path extends string,\n const Locale extends LocalesValues = LocalesValues,\n>(\n localizedPath: Path,\n locale?: Locale,\n rewriteRules?: RewriteRules\n): string => {\n if (\n !rewriteRules ||\n (process.env.INTLAYER_ROUTING_REWRITE_RULES &&\n process.env.INTLAYER_ROUTING_REWRITE_RULES === 'false')\n )\n return localizedPath;\n\n for (const rule of rewriteRules.rules) {\n const { canonical, localized } = rule;\n const localesToCheck = locale ? [locale] : Object.keys(localized);\n\n for (const loc of localesToCheck) {\n const localizedPattern = localized[loc as keyof typeof localized];\n\n if (!localizedPattern) continue;\n\n const params = extractParams(localizedPath, localizedPattern);\n\n if (params) {\n return fillPath(canonical, params);\n }\n }\n }\n\n return localizedPath;\n};\n\n/**\n * Given a canonical path (e.g., \"/products/123\"), finds the localized URL pattern\n * (e.g., \"/produits/123\") and reports whether a rule actually matched.\n *\n * Takes already-normalized rules, so callers that resolve the rules once (proxies,\n * static emitters) can reuse them. {@link getLocalizedPath} is the user-facing\n * counterpart: it accepts the raw `routing.rewrite` configuration, defaults to the\n * project configuration, and returns the path alone.\n *\n * @param canonicalPath - The internal application path (e.g. `/product/:id`, `/about`).\n * @param locale - The target locale. Defaults to the configured default locale.\n * @param rewriteRules - Normalized rules, as returned by {@link getRewriteRules}.\n * @returns The localized path, discriminated on whether a rewrite rule matched.\n */\nexport const resolveLocalizedPath = <\n const CanonicalPath extends string,\n const Locale extends LocalesValues = ResolvedDefaultLocale,\n>(\n canonicalPath: CanonicalPath,\n locale?: Locale,\n rewriteRules?: RewriteRules\n): LocalizedPathResult<CanonicalPath> => {\n if (\n !rewriteRules ||\n (process.env.INTLAYER_ROUTING_REWRITE_RULES &&\n process.env.INTLAYER_ROUTING_REWRITE_RULES === 'false')\n )\n return { path: canonicalPath, isRewritten: false };\n\n for (const rule of rewriteRules.rules) {\n const { canonical, localized } = rule;\n\n // Check if the input path matches a configured canonical pattern\n const params = extractParams(canonicalPath, canonical);\n\n if (params) {\n const targetLocale = locale ?? internationalization.defaultLocale;\n const targetPattern = localized[targetLocale as keyof typeof localized];\n\n if (targetPattern) {\n return {\n path: fillPath(targetPattern, params),\n isRewritten: true,\n };\n }\n }\n }\n\n return { path: canonicalPath, isRewritten: false };\n};\n\n/**\n * Returns the internal path for a given canonical path and locale.\n * Ensures the locale prefix is present exactly once.\n */\nexport const getInternalPath = <\n const Path extends string,\n const Locale extends LocalesValues,\n>(\n canonicalPath: Path,\n locale: Locale\n): InternalPath<Path, Locale> => {\n const pathWithLeadingSlash = canonicalPath.startsWith('/')\n ? canonicalPath\n : `/${canonicalPath}`;\n\n if (\n pathWithLeadingSlash.startsWith(`/${locale}/`) ||\n pathWithLeadingSlash === `/${locale}`\n ) {\n return pathWithLeadingSlash as InternalPath<Path, Locale>;\n }\n\n return `/${locale}${\n pathWithLeadingSlash === '/' ? '' : pathWithLeadingSlash\n }` as InternalPath<Path, Locale>;\n};\n\n/**\n * Given a current pathname and locale, returns the pretty localized path if a rewrite rule exists and the path is not already localized.\n */\nexport const getRewritePath = <\n const Path extends string,\n const Locale extends LocalesValues = ResolvedDefaultLocale,\n>(\n pathname: Path,\n locale: Locale,\n rewrite?: RoutingConfig['rewrite']\n): string | undefined => {\n if (\n process.env.INTLAYER_ROUTING_REWRITE_RULES &&\n process.env.INTLAYER_ROUTING_REWRITE_RULES === 'false'\n )\n return undefined;\n const rules = getRewriteRules(rewrite, 'url');\n if (!rules) return undefined;\n\n // Identify canonical path (relative to root, no locale prefix expected in 'url' context)\n const canonicalPath = getCanonicalPath(pathname, undefined, rules);\n\n // Get the localized path for the current locale\n const { path: localizedPath, isRewritten } = resolveLocalizedPath(\n canonicalPath,\n locale,\n rules\n );\n\n if (isRewritten && localizedPath !== pathname) {\n return localizedPath;\n }\n\n return undefined;\n};\n"],"mappings":";;;;;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X,UACA,QACA,YACuB;CACvB,IACE,QAAQ,IAAI,kCACZ,QAAQ,IAAI,mCAAmC,SAE/C,OAAO;CACT,MAAM,QAAQ,gBAAgB,SAAS,KAAK;CAC5C,IAAI,CAAC,OAAO,OAAO;CAGnB,MAAM,gBAAgB,iBAAiB,UAAU,QAAW,KAAK;CAGjE,MAAM,EAAE,MAAM,eAAe,gBAAgB,qBAC3C,eACA,QACA,KACF;CAEA,IAAI,eAAe,kBAAkB,UACnC,OAAO;AAIX"}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
const require_localization_rewriteUtils = require('./rewriteUtils.cjs');
|
|
2
|
+
let vitest = require("vitest");
|
|
3
|
+
|
|
4
|
+
//#region src/localization/rewriteUtils.test-d.ts
|
|
5
|
+
/**
|
|
6
|
+
* `getInternalPath` is pure string surgery — no rewrite rules involved — so its
|
|
7
|
+
* result is fully derivable from the arguments whenever both are literals.
|
|
8
|
+
*/
|
|
9
|
+
(0, vitest.describe)("getInternalPath", () => {
|
|
10
|
+
(0, vitest.it)("should prefix a literal path with the locale", () => {
|
|
11
|
+
(0, vitest.expectTypeOf)(require_localization_rewriteUtils.getInternalPath("/about", "fr")).toEqualTypeOf();
|
|
12
|
+
});
|
|
13
|
+
(0, vitest.it)("should collapse the root to a bare prefix, never a trailing slash", () => {
|
|
14
|
+
(0, vitest.expectTypeOf)(require_localization_rewriteUtils.getInternalPath("/", "fr")).toEqualTypeOf();
|
|
15
|
+
});
|
|
16
|
+
(0, vitest.it)("should leave an already-prefixed path untouched", () => {
|
|
17
|
+
(0, vitest.expectTypeOf)(require_localization_rewriteUtils.getInternalPath("/fr/about", "fr")).toEqualTypeOf();
|
|
18
|
+
(0, vitest.expectTypeOf)(require_localization_rewriteUtils.getInternalPath("/fr", "fr")).toEqualTypeOf();
|
|
19
|
+
});
|
|
20
|
+
(0, vitest.it)("should add the leading slash a path is missing", () => {
|
|
21
|
+
(0, vitest.expectTypeOf)(require_localization_rewriteUtils.getInternalPath("about", "fr")).toEqualTypeOf();
|
|
22
|
+
});
|
|
23
|
+
(0, vitest.it)("should widen to string when the path is not a literal", () => {
|
|
24
|
+
(0, vitest.expectTypeOf)(require_localization_rewriteUtils.getInternalPath("/about", "fr")).toEqualTypeOf();
|
|
25
|
+
});
|
|
26
|
+
});
|
|
27
|
+
/**
|
|
28
|
+
* `resolveLocalizedPath` only computes a new path when a rule matched, so the
|
|
29
|
+
* `isRewritten: false` branch still carries the exact input it was given.
|
|
30
|
+
*/
|
|
31
|
+
(0, vitest.describe)("resolveLocalizedPath", () => {
|
|
32
|
+
(0, vitest.it)("should keep the input literal on the non-rewritten branch", () => {
|
|
33
|
+
const result = require_localization_rewriteUtils.resolveLocalizedPath("/about", "fr");
|
|
34
|
+
if (!result.isRewritten) (0, vitest.expectTypeOf)(result.path).toEqualTypeOf();
|
|
35
|
+
else (0, vitest.expectTypeOf)(result.path).toEqualTypeOf();
|
|
36
|
+
});
|
|
37
|
+
(0, vitest.it)("should discriminate on isRewritten", () => {
|
|
38
|
+
(0, vitest.expectTypeOf)(require_localization_rewriteUtils.resolveLocalizedPath("/about")).toEqualTypeOf();
|
|
39
|
+
});
|
|
40
|
+
});
|
|
41
|
+
(0, vitest.describe)("getCanonicalPath", () => {
|
|
42
|
+
(0, vitest.it)("should accept an omitted locale (checks every locale)", () => {
|
|
43
|
+
(0, vitest.expectTypeOf)(require_localization_rewriteUtils.getCanonicalPath("/a-propos")).toEqualTypeOf();
|
|
44
|
+
});
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
//#endregion
|
|
48
|
+
//# sourceMappingURL=rewriteUtils.test-d.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"rewriteUtils.test-d.cjs","names":["describe","getInternalPath","resolveLocalizedPath","getCanonicalPath"],"sources":["../../../src/localization/rewriteUtils.test-d.ts"],"sourcesContent":["import { describe, expectTypeOf, it } from 'vitest';\nimport {\n getCanonicalPath,\n getInternalPath,\n resolveLocalizedPath,\n} from './rewriteUtils';\n\n/**\n * `getInternalPath` is pure string surgery — no rewrite rules involved — so its\n * result is fully derivable from the arguments whenever both are literals.\n */\ndescribe('getInternalPath', () => {\n it('should prefix a literal path with the locale', () => {\n expectTypeOf(getInternalPath('/about', 'fr')).toEqualTypeOf<'/fr/about'>();\n });\n\n it('should collapse the root to a bare prefix, never a trailing slash', () => {\n expectTypeOf(getInternalPath('/', 'fr')).toEqualTypeOf<'/fr'>();\n });\n\n it('should leave an already-prefixed path untouched', () => {\n expectTypeOf(\n getInternalPath('/fr/about', 'fr')\n ).toEqualTypeOf<'/fr/about'>();\n expectTypeOf(getInternalPath('/fr', 'fr')).toEqualTypeOf<'/fr'>();\n });\n\n it('should add the leading slash a path is missing', () => {\n expectTypeOf(getInternalPath('about', 'fr')).toEqualTypeOf<'/fr/about'>();\n });\n\n it('should widen to string when the path is not a literal', () => {\n const dynamicPath = '/about' as string;\n\n expectTypeOf(getInternalPath(dynamicPath, 'fr')).toEqualTypeOf<string>();\n });\n});\n\n/**\n * `resolveLocalizedPath` only computes a new path when a rule matched, so the\n * `isRewritten: false` branch still carries the exact input it was given.\n */\ndescribe('resolveLocalizedPath', () => {\n it('should keep the input literal on the non-rewritten branch', () => {\n const result = resolveLocalizedPath('/about', 'fr');\n\n if (!result.isRewritten) {\n expectTypeOf(result.path).toEqualTypeOf<'/about'>();\n } else {\n expectTypeOf(result.path).toEqualTypeOf<string>();\n }\n });\n\n it('should discriminate on isRewritten', () => {\n expectTypeOf(resolveLocalizedPath('/about')).toEqualTypeOf<\n | { path: '/about'; isRewritten: false }\n | { path: string; isRewritten: true }\n >();\n });\n});\n\ndescribe('getCanonicalPath', () => {\n it('should accept an omitted locale (checks every locale)', () => {\n expectTypeOf(getCanonicalPath('/a-propos')).toEqualTypeOf<string>();\n });\n});\n"],"mappings":";;;;;;;;IAWAA,iBAAS,yBAAyB;CAChC,eAAG,sDAAsD;EACvD,yBAAaC,kDAAgB,UAAU,IAAI,CAAC,CAAC,CAAC,cAA2B;CAC3E,CAAC;CAED,eAAG,2EAA2E;EAC5E,yBAAaA,kDAAgB,KAAK,IAAI,CAAC,CAAC,CAAC,cAAqB;CAChE,CAAC;CAED,eAAG,yDAAyD;EAC1D,yBACEA,kDAAgB,aAAa,IAAI,CACnC,CAAC,CAAC,cAA2B;EAC7B,yBAAaA,kDAAgB,OAAO,IAAI,CAAC,CAAC,CAAC,cAAqB;CAClE,CAAC;CAED,eAAG,wDAAwD;EACzD,yBAAaA,kDAAgB,SAAS,IAAI,CAAC,CAAC,CAAC,cAA2B;CAC1E,CAAC;CAED,eAAG,+DAA+D;EAGhE,yBAAaA,kDAAgB,UAAa,IAAI,CAAC,CAAC,CAAC,cAAsB;CACzE,CAAC;AACH,CAAC;;;;;IAMDD,iBAAS,8BAA8B;CACrC,eAAG,mEAAmE;EACpE,MAAM,SAASE,uDAAqB,UAAU,IAAI;EAElD,IAAI,CAAC,OAAO,aACV,yBAAa,OAAO,IAAI,CAAC,CAAC,cAAwB;OAElD,yBAAa,OAAO,IAAI,CAAC,CAAC,cAAsB;CAEpD,CAAC;CAED,eAAG,4CAA4C;EAC7C,yBAAaA,uDAAqB,QAAQ,CAAC,CAAC,CAAC,cAG3C;CACJ,CAAC;AACH,CAAC;IAEDF,iBAAS,0BAA0B;CACjC,eAAG,+DAA+D;EAChE,yBAAaG,mDAAiB,WAAW,CAAC,CAAC,CAAC,cAAsB;CACpE,CAAC;AACH,CAAC"}
|
|
@@ -156,6 +156,8 @@ const BREAK_THEMATIC_R = /^(?:([-*_])( *\1){2,}) *(?:\n *)+\n/;
|
|
|
156
156
|
/** Code block patterns */
|
|
157
157
|
const CODE_BLOCK_FENCED_R = /^(?: {1,3})?(`{3,}|~{3,}) *(\S+)? *([^\n]*?)?\n([\s\S]*?)(?:\1\n?|$)/;
|
|
158
158
|
const CODE_BLOCK_R = /^(?: {4}[^\n]+\n*)+(?:\n *)+\n?/;
|
|
159
|
+
/** A single line opening or closing a fenced code block, with its indentation. */
|
|
160
|
+
const FENCE_DELIMITER_R = /^([ \t]*)(`{3,}|~{3,})/;
|
|
159
161
|
const CODE_INLINE_R = /^(`+)((?:\\`|(?!\1)`|[^`])+)\1/;
|
|
160
162
|
/** Newline patterns */
|
|
161
163
|
const CONSECUTIVE_NEWLINE_R = /^(?:\n *)*\n/;
|
|
@@ -276,6 +278,7 @@ exports.CR_NEWLINE_R = CR_NEWLINE_R;
|
|
|
276
278
|
exports.CUSTOM_COMPONENT_R = CUSTOM_COMPONENT_R;
|
|
277
279
|
exports.DO_NOT_PROCESS_HTML_ELEMENTS = DO_NOT_PROCESS_HTML_ELEMENTS;
|
|
278
280
|
exports.DURATION_DELAY_TRIGGER = DURATION_DELAY_TRIGGER;
|
|
281
|
+
exports.FENCE_DELIMITER_R = FENCE_DELIMITER_R;
|
|
279
282
|
exports.FOOTNOTE_R = FOOTNOTE_R;
|
|
280
283
|
exports.FOOTNOTE_REFERENCE_R = FOOTNOTE_REFERENCE_R;
|
|
281
284
|
exports.FORMFEED_R = FORMFEED_R;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"constants.cjs","names":[],"sources":["../../../src/markdown/constants.ts"],"sourcesContent":["// ============================================================================\n// RULE TYPES\n// ============================================================================\n\n/**\n * Analogous to `node.type`. Please note that the values here may change at any time,\n * so do not hard code against the value directly.\n */\nexport const RuleType = {\n blockQuote: '0',\n breakLine: '1',\n breakThematic: '2',\n codeBlock: '3',\n codeFenced: '4',\n codeInline: '5',\n footnote: '6',\n footnoteReference: '7',\n gfmTask: '8',\n heading: '9',\n headingSetext: '10',\n /** only available if not `disableHTMLParsing` */\n htmlBlock: '11',\n htmlComment: '12',\n /** only available if not `disableHTMLParsing` */\n htmlSelfClosing: '13',\n /** Custom components like <Tabs>, <TabItem> */\n customComponent: '34',\n image: '14',\n link: '15',\n /** emits a `link` 'node', does not render directly */\n linkAngleBraceStyleDetector: '16',\n /** emits a `link` 'node', does not render directly */\n linkBareUrlDetector: '17',\n newlineCoalescer: '19',\n orderedList: '20',\n paragraph: '21',\n ref: '22',\n refImage: '23',\n refLink: '24',\n table: '25',\n tableSeparator: '26',\n text: '27',\n textBolded: '28',\n textEmphasized: '29',\n textEscaped: '30',\n textMarked: '31',\n textStrikethroughed: '32',\n unorderedList: '33',\n} as const;\n\n// In test environment, use human-readable keys for easier debugging\nif (process.env.NODE_ENV === 'test') {\n Object.keys(RuleType).forEach((key) => {\n (RuleType as any)[key] = key;\n });\n}\n\nexport type RuleTypeValue = (typeof RuleType)[keyof typeof RuleType];\n\n// ============================================================================\n// PRIORITY LEVELS\n// ============================================================================\n\n/**\n * Priority levels for rule ordering.\n */\nexport const Priority = {\n /** anything that must scan the tree before everything else */\n MAX: 0,\n /** scans for block-level constructs */\n HIGH: 1,\n /** inline w/ more priority than other inline */\n MED: 2,\n /** inline elements */\n LOW: 3,\n /** bare text and stuff that is considered leftovers */\n MIN: 4,\n} as const;\n\nexport type PriorityValue = (typeof Priority)[keyof typeof Priority];\n\n// ============================================================================\n// PERFORMANCE CONSTANTS\n// ============================================================================\n\n/** Threshold for performance logging (in milliseconds) */\nexport const DURATION_DELAY_TRIGGER = 20;\n\n// ============================================================================\n// ATTRIBUTE MAPPING\n// ============================================================================\n\n/**\n * Map of HTML attributes to their JSX prop equivalents.\n * Some renderers use camelCase for certain attributes.\n */\nexport const ATTRIBUTE_TO_NODE_PROP_MAP: Record<string, string> = [\n 'allowFullScreen',\n 'allowTransparency',\n 'autoComplete',\n 'autoFocus',\n 'autoPlay',\n 'cellPadding',\n 'cellSpacing',\n 'charSet',\n 'classId',\n 'colSpan',\n 'contentEditable',\n 'contextMenu',\n 'crossOrigin',\n 'encType',\n 'formAction',\n 'formEncType',\n 'formMethod',\n 'formNoValidate',\n 'formTarget',\n 'frameBorder',\n 'hrefLang',\n 'inputMode',\n 'keyParams',\n 'keyType',\n 'marginHeight',\n 'marginWidth',\n 'maxLength',\n 'mediaGroup',\n 'minLength',\n 'noValidate',\n 'radioGroup',\n 'readOnly',\n 'rowSpan',\n 'spellCheck',\n 'srcDoc',\n 'srcLang',\n 'srcSet',\n 'tabIndex',\n 'useMap',\n].reduce(\n (obj: Record<string, string>, x) => {\n obj[x.toLowerCase()] = x;\n return obj;\n },\n { class: 'className', for: 'htmlFor' }\n);\n\n// ============================================================================\n// NAMED CODES TO UNICODE\n// ============================================================================\n\n/**\n * Default HTML entity to unicode mappings.\n */\nexport const NAMED_CODES_TO_UNICODE: Record<string, string> = {\n amp: '\\u0026',\n apos: '\\u0027',\n gt: '\\u003e',\n lt: '\\u003c',\n nbsp: '\\u00a0',\n quot: '\\u201c',\n};\n\n// ============================================================================\n// SPECIAL ELEMENTS\n// ============================================================================\n\n/** HTML elements that should not have their content processed */\nexport const DO_NOT_PROCESS_HTML_ELEMENTS = ['style', 'script', 'pre'];\n\n/** Attributes that require URL sanitization */\nexport const ATTRIBUTES_TO_SANITIZE = [\n 'src',\n 'href',\n 'data',\n 'formAction',\n 'srcDoc',\n 'action',\n];\n\n// ============================================================================\n// REGEX PATTERNS\n// ============================================================================\n\n/** Attribute extractor regex */\nexport const ATTR_EXTRACTOR_R =\n /([-A-Z0-9_:]+)(?:\\s*=\\s*(?:(?:\"((?:\\\\.|[^\"])*)\")|(?:'((?:\\\\.|[^'])*)')|(?:\\{((?:\\\\.|{[^}]*?}|[^}])*)\\})))?/gi;\n\n/** Block end detection */\nexport const BLOCK_END_R = /\\n{2,}$/;\n\n/** Blockquote patterns */\nexport const BLOCKQUOTE_R = /^(\\s*>[\\s\\S]*?)(?=\\n\\n|$)/;\nexport const BLOCKQUOTE_TRIM_LEFT_MULTILINE_R = /^ *> ?/gm;\nexport const BLOCKQUOTE_ALERT_R = /^(?:\\[!([^\\]]*)\\]\\n)?([\\s\\S]*)/;\n\n/** Line break patterns */\nexport const BREAK_LINE_R = /^ {2,}\\n/;\nexport const BREAK_THEMATIC_R = /^(?:([-*_])( *\\1){2,}) *(?:\\n *)+\\n/;\n\n/** Code block patterns */\nexport const CODE_BLOCK_FENCED_R =\n /^(?: {1,3})?(`{3,}|~{3,}) *(\\S+)? *([^\\n]*?)?\\n([\\s\\S]*?)(?:\\1\\n?|$)/;\nexport const CODE_BLOCK_R = /^(?: {4}[^\\n]+\\n*)+(?:\\n *)+\\n?/;\nexport const CODE_INLINE_R = /^(`+)((?:\\\\`|(?!\\1)`|[^`])+)\\1/;\n\n/** Newline patterns */\nexport const CONSECUTIVE_NEWLINE_R = /^(?:\\n *)*\\n/;\nexport const CR_NEWLINE_R = /\\r\\n?/g;\n\n/** Footnote patterns */\nexport const FOOTNOTE_R = /^\\[\\^([^\\]]+)](:(.*)((\\n+ {4,}.*)|(\\n(?!\\[\\^).+))*)/;\nexport const FOOTNOTE_REFERENCE_R = /^\\[\\^([^\\]]+)]/;\n\n/** Form feed */\nexport const FORMFEED_R = /\\f/g;\n\n/** Front matter */\nexport const FRONT_MATTER_R = /^---[ \\t]*\\n(.|\\n)*?\\n---[ \\t]*\\n/;\n\n/** GFM task */\nexport const GFM_TASK_R = /^\\s*?\\[(x|\\s)\\]/;\n\n/** Heading patterns */\nexport const HEADING_R = /^ *(#{1,6}) *([^\\n]+?)(?: +#*)?(?:\\n *)*(?:\\n|$)/;\nexport const HEADING_ATX_COMPLIANT_R =\n /^ *(#{1,6}) +([^\\n]+?)(?: +#*)?(?:\\n *)*(?:\\n|$)/;\nexport const HEADING_SETEXT_R = /^([^\\n]+)\\n *(=|-)\\2{2,} *\\n/;\n\n/** HTML patterns */\nexport const HTML_BLOCK_ELEMENT_R =\n /^ *(?!<[a-zA-Z][^ >/]* ?\\/>)<([a-zA-Z][^ >/]*) ?((?:[^>]*[^/])?)>\\n?(\\s*(?:<\\1[^>]*?>[\\s\\S]*?<\\/\\1>|(?!<\\1\\b)[\\s\\S])*?)<\\/\\1>(?!<\\/\\1>)\\n*/i;\nexport const HTML_CHAR_CODE_R =\n /&([a-z0-9]+|#[0-9]{1,6}|#x[0-9a-fA-F]{1,6});/gi;\nexport const HTML_COMMENT_R = /^<!--[\\s\\S]*?(?:-->)/;\nexport const HTML_CUSTOM_ATTR_R = /^(data|aria|x)-[a-z_][a-z\\d_.-]*$/;\nexport const HTML_SELF_CLOSING_ELEMENT_R =\n /^ *<([a-zA-Z][a-zA-Z0-9:]*)(?:\\s+((?:<.*?>|[^>])*))?\\/?>(?!<\\/\\1>)(\\s*\\n)?/i;\n\n/** Custom component pattern */\nexport const CUSTOM_COMPONENT_R =\n /^ *<([A-Z][a-zA-Z0-9]*)(?:\\s+((?:<.*?>|[^>])*))?>\\n?(\\s*(?:<\\1[^>]*?>[\\s\\S]*?<\\/\\1>|(?!<\\1\\b)[\\s\\S])*?)<\\/\\1>(?!<\\/\\1>)\\n*/;\n\n/** Interpolation */\nexport const INTERPOLATION_R = /^\\{.*\\}$/;\n\n/** Link patterns */\nexport const LINK_AUTOLINK_BARE_URL_R = /^(https?:\\/\\/[^\\s<]+[^<.,:;\"')\\]\\s])/;\nexport const LINK_AUTOLINK_R = /^<([^ >]+[:@/][^ >]+)>/;\nexport const CAPTURE_LETTER_AFTER_HYPHEN = /-([a-z])?/gi;\n\n/** Table patterns */\nexport const NP_TABLE_R =\n /^(\\|.*)\\n(?: *(\\|? *[-:]+ *\\|[-| :]*)\\n((?:.*\\|.*\\n)*))?\\n?/;\nexport const TABLE_TRIM_PIPES = /(^ *\\||\\| *$)/g;\nexport const TABLE_CENTER_ALIGN = /^ *:-+: *$/;\nexport const TABLE_LEFT_ALIGN = /^ *:-+ *$/;\nexport const TABLE_RIGHT_ALIGN = /^ *-+: *$/;\n\n/** Paragraph */\nexport const PARAGRAPH_R = /^[^\\n]+(?: {2}\\n|\\n{2,})/;\n\n/** Reference patterns */\nexport const REFERENCE_IMAGE_OR_LINK =\n /^\\[([^\\]]*)\\]:\\s+<?([^\\s>]+)>?\\s*(\"([^\"]*)\")?/;\nexport const REFERENCE_IMAGE_R = /^!\\[([^\\]]*)\\] ?\\[([^\\]]*)\\]/;\nexport const REFERENCE_LINK_R = /^\\[([^\\]]*)\\] ?\\[([^\\]]*)\\]/;\n\n/** Block detection */\nexport const SHOULD_RENDER_AS_BLOCK_R = /(\\n|^[-*]\\s|^#|^ {2,}|^-{2,}|^>\\s)/;\n\n/** Tab and whitespace */\nexport const TAB_R = /\\t/g;\nexport const TRIM_STARTING_NEWLINES = /^\\n+/;\nexport const HTML_LEFT_TRIM_AMOUNT_R = /^\\n*([ \\t]*)/;\n\n/** List patterns */\nexport const LIST_LOOKBEHIND_R = /(?:^|\\n)( *)$/;\nexport const ORDERED_LIST_BULLET = '(?:\\\\d+\\\\.)';\nexport const UNORDERED_LIST_BULLET = '(?:[*+-])';\n\n/** Text formatting patterns */\nexport const TEXT_ESCAPED_R = /^\\\\([^0-9A-Za-z\\s])/;\nexport const UNESCAPE_R = /\\\\([^0-9A-Za-z\\s])/g;\nexport const TEXT_PLAIN_R =\n /^[\\s\\S](?:(?! {2}\\n|[0-9]\\.|http)[^=*_~\\-\\n:<`\\\\[!])*/;\n\n/** Shortcode pattern */\nexport const SHORTCODE_R = /^(:[a-zA-Z0-9-_]+:)/;\n\n// ============================================================================\n// LIST TYPE CONSTANTS\n// ============================================================================\n\nexport type ListType = 1 | 2;\nexport const ORDERED: ListType = 1;\nexport const UNORDERED: ListType = 2;\n\n// ============================================================================\n// INLINE PATTERN HELPERS\n// ============================================================================\n\n/**\n * Ensure there's at least one more instance of the delimiter later\n * in the current sequence.\n */\nexport const LOOKAHEAD = (double: number): string =>\n `(?=[\\\\s\\\\S]+?\\\\1${double ? '\\\\1' : ''})`;\n\n/**\n * For inline formatting, this partial attempts to ignore characters that\n * may appear in nested formatting.\n */\nexport const INLINE_SKIP_R =\n '((?:\\\\[.*?\\\\][([].*?[)\\\\]]|<.*?>(?:.*?<.*?>)?|`.*?`|\\\\\\\\[^\\\\s]|[\\\\s\\\\S])+?)';\n\n/** Bold text pattern */\nexport const TEXT_BOLD_R = new RegExp(\n `^([*_])\\\\1${LOOKAHEAD(1)}${INLINE_SKIP_R}\\\\1\\\\1(?!\\\\1)`\n);\n\n/** Emphasized text pattern */\nexport const TEXT_EMPHASIZED_R = new RegExp(\n `^([*_])${LOOKAHEAD(0)}${INLINE_SKIP_R}\\\\1(?!\\\\1)`\n);\n\n/** Marked text pattern */\nexport const TEXT_MARKED_R = new RegExp(\n `^(==)${LOOKAHEAD(0)}${INLINE_SKIP_R}\\\\1`\n);\n\n/** Strikethrough text pattern */\nexport const TEXT_STRIKETHROUGHED_R = new RegExp(\n `^(~~)${LOOKAHEAD(0)}${INLINE_SKIP_R}\\\\1`\n);\n\n// ============================================================================\n// LIST REGEX GENERATORS\n// ============================================================================\n\nexport const generateListItemPrefix = (type: ListType): string => {\n return (\n '( *)(' +\n (type === ORDERED ? ORDERED_LIST_BULLET : UNORDERED_LIST_BULLET) +\n ') +'\n );\n};\n\nexport const ORDERED_LIST_ITEM_PREFIX = generateListItemPrefix(ORDERED);\nexport const UNORDERED_LIST_ITEM_PREFIX = generateListItemPrefix(UNORDERED);\n\nexport const generateListItemPrefixRegex = (type: ListType): RegExp => {\n return new RegExp(\n '^' +\n (type === ORDERED ? ORDERED_LIST_ITEM_PREFIX : UNORDERED_LIST_ITEM_PREFIX)\n );\n};\n\nexport const ORDERED_LIST_ITEM_PREFIX_R = generateListItemPrefixRegex(ORDERED);\nexport const UNORDERED_LIST_ITEM_PREFIX_R =\n generateListItemPrefixRegex(UNORDERED);\n\nexport const generateListItemRegex = (type: ListType): RegExp => {\n return new RegExp(\n '^' +\n (type === ORDERED\n ? ORDERED_LIST_ITEM_PREFIX\n : UNORDERED_LIST_ITEM_PREFIX) +\n '[^\\\\n]*(?:\\\\n' +\n '(?!\\\\1' +\n (type === ORDERED ? ORDERED_LIST_BULLET : UNORDERED_LIST_BULLET) +\n ' )[^\\\\n]*)*(\\\\n|$)',\n 'gm'\n );\n};\n\nexport const ORDERED_LIST_ITEM_R = generateListItemRegex(ORDERED);\nexport const UNORDERED_LIST_ITEM_R = generateListItemRegex(UNORDERED);\n\nexport const generateListRegex = (type: ListType): RegExp => {\n const bullet = type === ORDERED ? ORDERED_LIST_BULLET : UNORDERED_LIST_BULLET;\n\n return new RegExp(\n '^( *)(' +\n bullet +\n ') ' +\n '[\\\\s\\\\S]+?(?:\\\\n{2,}(?! )' +\n '(?!\\\\1' +\n bullet +\n ' (?!' +\n bullet +\n ' ))\\\\n*' +\n '|\\\\s*\\\\n*$)'\n );\n};\n\nexport const ORDERED_LIST_R = generateListRegex(ORDERED);\nexport const UNORDERED_LIST_R = generateListRegex(UNORDERED);\n"],"mappings":";;;;;;AAQA,MAAa,WAAW;CACtB,YAAY;CACZ,WAAW;CACX,eAAe;CACf,WAAW;CACX,YAAY;CACZ,YAAY;CACZ,UAAU;CACV,mBAAmB;CACnB,SAAS;CACT,SAAS;CACT,eAAe;;CAEf,WAAW;CACX,aAAa;;CAEb,iBAAiB;;CAEjB,iBAAiB;CACjB,OAAO;CACP,MAAM;;CAEN,6BAA6B;;CAE7B,qBAAqB;CACrB,kBAAkB;CAClB,aAAa;CACb,WAAW;CACX,KAAK;CACL,UAAU;CACV,SAAS;CACT,OAAO;CACP,gBAAgB;CAChB,MAAM;CACN,YAAY;CACZ,gBAAgB;CAChB,aAAa;CACb,YAAY;CACZ,qBAAqB;CACrB,eAAe;AACjB;AAGA,IAAI,QAAQ,IAAI,aAAa,QAC3B,OAAO,KAAK,QAAQ,CAAC,CAAC,SAAS,QAAQ;CACrC,AAAC,SAAiB,OAAO;AAC3B,CAAC;;;;AAYH,MAAa,WAAW;;CAEtB,KAAK;;CAEL,MAAM;;CAEN,KAAK;;CAEL,KAAK;;CAEL,KAAK;AACP;;AASA,MAAa,yBAAyB;;;;;AAUtC,MAAa,6BAAqD;CAChE;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CAC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":["// ============================================================================\n// RULE TYPES\n// ============================================================================\n\n/**\n * Analogous to `node.type`. Please note that the values here may change at any time,\n * so do not hard code against the value directly.\n */\nexport const RuleType = {\n blockQuote: '0',\n breakLine: '1',\n breakThematic: '2',\n codeBlock: '3',\n codeFenced: '4',\n codeInline: '5',\n footnote: '6',\n footnoteReference: '7',\n gfmTask: '8',\n heading: '9',\n headingSetext: '10',\n /** only available if not `disableHTMLParsing` */\n htmlBlock: '11',\n htmlComment: '12',\n /** only available if not `disableHTMLParsing` */\n htmlSelfClosing: '13',\n /** Custom components like <Tabs>, <TabItem> */\n customComponent: '34',\n image: '14',\n link: '15',\n /** emits a `link` 'node', does not render directly */\n linkAngleBraceStyleDetector: '16',\n /** emits a `link` 'node', does not render directly */\n linkBareUrlDetector: '17',\n newlineCoalescer: '19',\n orderedList: '20',\n paragraph: '21',\n ref: '22',\n refImage: '23',\n refLink: '24',\n table: '25',\n tableSeparator: '26',\n text: '27',\n textBolded: '28',\n textEmphasized: '29',\n textEscaped: '30',\n textMarked: '31',\n textStrikethroughed: '32',\n unorderedList: '33',\n} as const;\n\n// In test environment, use human-readable keys for easier debugging\nif (process.env.NODE_ENV === 'test') {\n Object.keys(RuleType).forEach((key) => {\n (RuleType as any)[key] = key;\n });\n}\n\nexport type RuleTypeValue = (typeof RuleType)[keyof typeof RuleType];\n\n// ============================================================================\n// PRIORITY LEVELS\n// ============================================================================\n\n/**\n * Priority levels for rule ordering.\n */\nexport const Priority = {\n /** anything that must scan the tree before everything else */\n MAX: 0,\n /** scans for block-level constructs */\n HIGH: 1,\n /** inline w/ more priority than other inline */\n MED: 2,\n /** inline elements */\n LOW: 3,\n /** bare text and stuff that is considered leftovers */\n MIN: 4,\n} as const;\n\nexport type PriorityValue = (typeof Priority)[keyof typeof Priority];\n\n// ============================================================================\n// PERFORMANCE CONSTANTS\n// ============================================================================\n\n/** Threshold for performance logging (in milliseconds) */\nexport const DURATION_DELAY_TRIGGER = 20;\n\n// ============================================================================\n// ATTRIBUTE MAPPING\n// ============================================================================\n\n/**\n * Map of HTML attributes to their JSX prop equivalents.\n * Some renderers use camelCase for certain attributes.\n */\nexport const ATTRIBUTE_TO_NODE_PROP_MAP: Record<string, string> = [\n 'allowFullScreen',\n 'allowTransparency',\n 'autoComplete',\n 'autoFocus',\n 'autoPlay',\n 'cellPadding',\n 'cellSpacing',\n 'charSet',\n 'classId',\n 'colSpan',\n 'contentEditable',\n 'contextMenu',\n 'crossOrigin',\n 'encType',\n 'formAction',\n 'formEncType',\n 'formMethod',\n 'formNoValidate',\n 'formTarget',\n 'frameBorder',\n 'hrefLang',\n 'inputMode',\n 'keyParams',\n 'keyType',\n 'marginHeight',\n 'marginWidth',\n 'maxLength',\n 'mediaGroup',\n 'minLength',\n 'noValidate',\n 'radioGroup',\n 'readOnly',\n 'rowSpan',\n 'spellCheck',\n 'srcDoc',\n 'srcLang',\n 'srcSet',\n 'tabIndex',\n 'useMap',\n].reduce(\n (obj: Record<string, string>, x) => {\n obj[x.toLowerCase()] = x;\n return obj;\n },\n { class: 'className', for: 'htmlFor' }\n);\n\n// ============================================================================\n// NAMED CODES TO UNICODE\n// ============================================================================\n\n/**\n * Default HTML entity to unicode mappings.\n */\nexport const NAMED_CODES_TO_UNICODE: Record<string, string> = {\n amp: '\\u0026',\n apos: '\\u0027',\n gt: '\\u003e',\n lt: '\\u003c',\n nbsp: '\\u00a0',\n quot: '\\u201c',\n};\n\n// ============================================================================\n// SPECIAL ELEMENTS\n// ============================================================================\n\n/** HTML elements that should not have their content processed */\nexport const DO_NOT_PROCESS_HTML_ELEMENTS = ['style', 'script', 'pre'];\n\n/** Attributes that require URL sanitization */\nexport const ATTRIBUTES_TO_SANITIZE = [\n 'src',\n 'href',\n 'data',\n 'formAction',\n 'srcDoc',\n 'action',\n];\n\n// ============================================================================\n// REGEX PATTERNS\n// ============================================================================\n\n/** Attribute extractor regex */\nexport const ATTR_EXTRACTOR_R =\n /([-A-Z0-9_:]+)(?:\\s*=\\s*(?:(?:\"((?:\\\\.|[^\"])*)\")|(?:'((?:\\\\.|[^'])*)')|(?:\\{((?:\\\\.|{[^}]*?}|[^}])*)\\})))?/gi;\n\n/** Block end detection */\nexport const BLOCK_END_R = /\\n{2,}$/;\n\n/** Blockquote patterns */\nexport const BLOCKQUOTE_R = /^(\\s*>[\\s\\S]*?)(?=\\n\\n|$)/;\nexport const BLOCKQUOTE_TRIM_LEFT_MULTILINE_R = /^ *> ?/gm;\nexport const BLOCKQUOTE_ALERT_R = /^(?:\\[!([^\\]]*)\\]\\n)?([\\s\\S]*)/;\n\n/** Line break patterns */\nexport const BREAK_LINE_R = /^ {2,}\\n/;\nexport const BREAK_THEMATIC_R = /^(?:([-*_])( *\\1){2,}) *(?:\\n *)+\\n/;\n\n/** Code block patterns */\nexport const CODE_BLOCK_FENCED_R =\n /^(?: {1,3})?(`{3,}|~{3,}) *(\\S+)? *([^\\n]*?)?\\n([\\s\\S]*?)(?:\\1\\n?|$)/;\nexport const CODE_BLOCK_R = /^(?: {4}[^\\n]+\\n*)+(?:\\n *)+\\n?/;\n/** A single line opening or closing a fenced code block, with its indentation. */\nexport const FENCE_DELIMITER_R = /^([ \\t]*)(`{3,}|~{3,})/;\nexport const CODE_INLINE_R = /^(`+)((?:\\\\`|(?!\\1)`|[^`])+)\\1/;\n\n/** Newline patterns */\nexport const CONSECUTIVE_NEWLINE_R = /^(?:\\n *)*\\n/;\nexport const CR_NEWLINE_R = /\\r\\n?/g;\n\n/** Footnote patterns */\nexport const FOOTNOTE_R = /^\\[\\^([^\\]]+)](:(.*)((\\n+ {4,}.*)|(\\n(?!\\[\\^).+))*)/;\nexport const FOOTNOTE_REFERENCE_R = /^\\[\\^([^\\]]+)]/;\n\n/** Form feed */\nexport const FORMFEED_R = /\\f/g;\n\n/** Front matter */\nexport const FRONT_MATTER_R = /^---[ \\t]*\\n(.|\\n)*?\\n---[ \\t]*\\n/;\n\n/** GFM task */\nexport const GFM_TASK_R = /^\\s*?\\[(x|\\s)\\]/;\n\n/** Heading patterns */\nexport const HEADING_R = /^ *(#{1,6}) *([^\\n]+?)(?: +#*)?(?:\\n *)*(?:\\n|$)/;\nexport const HEADING_ATX_COMPLIANT_R =\n /^ *(#{1,6}) +([^\\n]+?)(?: +#*)?(?:\\n *)*(?:\\n|$)/;\nexport const HEADING_SETEXT_R = /^([^\\n]+)\\n *(=|-)\\2{2,} *\\n/;\n\n/** HTML patterns */\nexport const HTML_BLOCK_ELEMENT_R =\n /^ *(?!<[a-zA-Z][^ >/]* ?\\/>)<([a-zA-Z][^ >/]*) ?((?:[^>]*[^/])?)>\\n?(\\s*(?:<\\1[^>]*?>[\\s\\S]*?<\\/\\1>|(?!<\\1\\b)[\\s\\S])*?)<\\/\\1>(?!<\\/\\1>)\\n*/i;\nexport const HTML_CHAR_CODE_R =\n /&([a-z0-9]+|#[0-9]{1,6}|#x[0-9a-fA-F]{1,6});/gi;\nexport const HTML_COMMENT_R = /^<!--[\\s\\S]*?(?:-->)/;\nexport const HTML_CUSTOM_ATTR_R = /^(data|aria|x)-[a-z_][a-z\\d_.-]*$/;\nexport const HTML_SELF_CLOSING_ELEMENT_R =\n /^ *<([a-zA-Z][a-zA-Z0-9:]*)(?:\\s+((?:<.*?>|[^>])*))?\\/?>(?!<\\/\\1>)(\\s*\\n)?/i;\n\n/** Custom component pattern */\nexport const CUSTOM_COMPONENT_R =\n /^ *<([A-Z][a-zA-Z0-9]*)(?:\\s+((?:<.*?>|[^>])*))?>\\n?(\\s*(?:<\\1[^>]*?>[\\s\\S]*?<\\/\\1>|(?!<\\1\\b)[\\s\\S])*?)<\\/\\1>(?!<\\/\\1>)\\n*/;\n\n/** Interpolation */\nexport const INTERPOLATION_R = /^\\{.*\\}$/;\n\n/** Link patterns */\nexport const LINK_AUTOLINK_BARE_URL_R = /^(https?:\\/\\/[^\\s<]+[^<.,:;\"')\\]\\s])/;\nexport const LINK_AUTOLINK_R = /^<([^ >]+[:@/][^ >]+)>/;\nexport const CAPTURE_LETTER_AFTER_HYPHEN = /-([a-z])?/gi;\n\n/** Table patterns */\nexport const NP_TABLE_R =\n /^(\\|.*)\\n(?: *(\\|? *[-:]+ *\\|[-| :]*)\\n((?:.*\\|.*\\n)*))?\\n?/;\nexport const TABLE_TRIM_PIPES = /(^ *\\||\\| *$)/g;\nexport const TABLE_CENTER_ALIGN = /^ *:-+: *$/;\nexport const TABLE_LEFT_ALIGN = /^ *:-+ *$/;\nexport const TABLE_RIGHT_ALIGN = /^ *-+: *$/;\n\n/** Paragraph */\nexport const PARAGRAPH_R = /^[^\\n]+(?: {2}\\n|\\n{2,})/;\n\n/** Reference patterns */\nexport const REFERENCE_IMAGE_OR_LINK =\n /^\\[([^\\]]*)\\]:\\s+<?([^\\s>]+)>?\\s*(\"([^\"]*)\")?/;\nexport const REFERENCE_IMAGE_R = /^!\\[([^\\]]*)\\] ?\\[([^\\]]*)\\]/;\nexport const REFERENCE_LINK_R = /^\\[([^\\]]*)\\] ?\\[([^\\]]*)\\]/;\n\n/** Block detection */\nexport const SHOULD_RENDER_AS_BLOCK_R = /(\\n|^[-*]\\s|^#|^ {2,}|^-{2,}|^>\\s)/;\n\n/** Tab and whitespace */\nexport const TAB_R = /\\t/g;\nexport const TRIM_STARTING_NEWLINES = /^\\n+/;\nexport const HTML_LEFT_TRIM_AMOUNT_R = /^\\n*([ \\t]*)/;\n\n/** List patterns */\nexport const LIST_LOOKBEHIND_R = /(?:^|\\n)( *)$/;\nexport const ORDERED_LIST_BULLET = '(?:\\\\d+\\\\.)';\nexport const UNORDERED_LIST_BULLET = '(?:[*+-])';\n\n/** Text formatting patterns */\nexport const TEXT_ESCAPED_R = /^\\\\([^0-9A-Za-z\\s])/;\nexport const UNESCAPE_R = /\\\\([^0-9A-Za-z\\s])/g;\nexport const TEXT_PLAIN_R =\n /^[\\s\\S](?:(?! {2}\\n|[0-9]\\.|http)[^=*_~\\-\\n:<`\\\\[!])*/;\n\n/** Shortcode pattern */\nexport const SHORTCODE_R = /^(:[a-zA-Z0-9-_]+:)/;\n\n// ============================================================================\n// LIST TYPE CONSTANTS\n// ============================================================================\n\nexport type ListType = 1 | 2;\nexport const ORDERED: ListType = 1;\nexport const UNORDERED: ListType = 2;\n\n// ============================================================================\n// INLINE PATTERN HELPERS\n// ============================================================================\n\n/**\n * Ensure there's at least one more instance of the delimiter later\n * in the current sequence.\n */\nexport const LOOKAHEAD = (double: number): string =>\n `(?=[\\\\s\\\\S]+?\\\\1${double ? '\\\\1' : ''})`;\n\n/**\n * For inline formatting, this partial attempts to ignore characters that\n * may appear in nested formatting.\n */\nexport const INLINE_SKIP_R =\n '((?:\\\\[.*?\\\\][([].*?[)\\\\]]|<.*?>(?:.*?<.*?>)?|`.*?`|\\\\\\\\[^\\\\s]|[\\\\s\\\\S])+?)';\n\n/** Bold text pattern */\nexport const TEXT_BOLD_R = new RegExp(\n `^([*_])\\\\1${LOOKAHEAD(1)}${INLINE_SKIP_R}\\\\1\\\\1(?!\\\\1)`\n);\n\n/** Emphasized text pattern */\nexport const TEXT_EMPHASIZED_R = new RegExp(\n `^([*_])${LOOKAHEAD(0)}${INLINE_SKIP_R}\\\\1(?!\\\\1)`\n);\n\n/** Marked text pattern */\nexport const TEXT_MARKED_R = new RegExp(\n `^(==)${LOOKAHEAD(0)}${INLINE_SKIP_R}\\\\1`\n);\n\n/** Strikethrough text pattern */\nexport const TEXT_STRIKETHROUGHED_R = new RegExp(\n `^(~~)${LOOKAHEAD(0)}${INLINE_SKIP_R}\\\\1`\n);\n\n// ============================================================================\n// LIST REGEX GENERATORS\n// ============================================================================\n\nexport const generateListItemPrefix = (type: ListType): string => {\n return (\n '( *)(' +\n (type === ORDERED ? ORDERED_LIST_BULLET : UNORDERED_LIST_BULLET) +\n ') +'\n );\n};\n\nexport const ORDERED_LIST_ITEM_PREFIX = generateListItemPrefix(ORDERED);\nexport const UNORDERED_LIST_ITEM_PREFIX = generateListItemPrefix(UNORDERED);\n\nexport const generateListItemPrefixRegex = (type: ListType): RegExp => {\n return new RegExp(\n '^' +\n (type === ORDERED ? ORDERED_LIST_ITEM_PREFIX : UNORDERED_LIST_ITEM_PREFIX)\n );\n};\n\nexport const ORDERED_LIST_ITEM_PREFIX_R = generateListItemPrefixRegex(ORDERED);\nexport const UNORDERED_LIST_ITEM_PREFIX_R =\n generateListItemPrefixRegex(UNORDERED);\n\nexport const generateListItemRegex = (type: ListType): RegExp => {\n return new RegExp(\n '^' +\n (type === ORDERED\n ? ORDERED_LIST_ITEM_PREFIX\n : UNORDERED_LIST_ITEM_PREFIX) +\n '[^\\\\n]*(?:\\\\n' +\n '(?!\\\\1' +\n (type === ORDERED ? ORDERED_LIST_BULLET : UNORDERED_LIST_BULLET) +\n ' )[^\\\\n]*)*(\\\\n|$)',\n 'gm'\n );\n};\n\nexport const ORDERED_LIST_ITEM_R = generateListItemRegex(ORDERED);\nexport const UNORDERED_LIST_ITEM_R = generateListItemRegex(UNORDERED);\n\nexport const generateListRegex = (type: ListType): RegExp => {\n const bullet = type === ORDERED ? ORDERED_LIST_BULLET : UNORDERED_LIST_BULLET;\n\n return new RegExp(\n '^( *)(' +\n bullet +\n ') ' +\n '[\\\\s\\\\S]+?(?:\\\\n{2,}(?! )' +\n '(?!\\\\1' +\n bullet +\n ' (?!' +\n bullet +\n ' ))\\\\n*' +\n '|\\\\s*\\\\n*$)'\n );\n};\n\nexport const ORDERED_LIST_R = generateListRegex(ORDERED);\nexport const UNORDERED_LIST_R = generateListRegex(UNORDERED);\n"],"mappings":";;;;;;AAQA,MAAa,WAAW;CACtB,YAAY;CACZ,WAAW;CACX,eAAe;CACf,WAAW;CACX,YAAY;CACZ,YAAY;CACZ,UAAU;CACV,mBAAmB;CACnB,SAAS;CACT,SAAS;CACT,eAAe;;CAEf,WAAW;CACX,aAAa;;CAEb,iBAAiB;;CAEjB,iBAAiB;CACjB,OAAO;CACP,MAAM;;CAEN,6BAA6B;;CAE7B,qBAAqB;CACrB,kBAAkB;CAClB,aAAa;CACb,WAAW;CACX,KAAK;CACL,UA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,6BAA6B,wBAAgC;AAE1E,MAAa,+BAA+B,SAA2B;CACrE,OAAO,IAAI,OACT,OACG,aAAmB,2BAA2B,2BACnD;AACF;AAEA,MAAa,6BAA6B,6BAAmC;AAC7E,MAAa,+BACX,6BAAqC;AAEvC,MAAa,yBAAyB,SAA2B;CAC/D,OAAO,IAAI,OACT,OACG,aACG,2BACA,8BACJ,yBAEC,aAAmB,sBAAsB,yBAC1C,sBACF,IACF;AACF;AAEA,MAAa,sBAAsB,uBAA6B;AAChE,MAAa,wBAAwB,uBAA+B;AAEpE,MAAa,qBAAqB,SAA2B;CAC3D,MAAM,SAAS,aAAmB,sBAAsB;CAExD,OAAO,IAAI,OACT,WACE,SACA,sCAGA,SACA,SACA,SACA,oBAEJ;AACF;AAEA,MAAa,iBAAiB,mBAAyB;AACvD,MAAa,mBAAmB,mBAA2B"}
|
|
@@ -26,6 +26,7 @@ exports.CR_NEWLINE_R = require_markdown_constants.CR_NEWLINE_R;
|
|
|
26
26
|
exports.CUSTOM_COMPONENT_R = require_markdown_constants.CUSTOM_COMPONENT_R;
|
|
27
27
|
exports.DO_NOT_PROCESS_HTML_ELEMENTS = require_markdown_constants.DO_NOT_PROCESS_HTML_ELEMENTS;
|
|
28
28
|
exports.DURATION_DELAY_TRIGGER = require_markdown_constants.DURATION_DELAY_TRIGGER;
|
|
29
|
+
exports.FENCE_DELIMITER_R = require_markdown_constants.FENCE_DELIMITER_R;
|
|
29
30
|
exports.FOOTNOTE_R = require_markdown_constants.FOOTNOTE_R;
|
|
30
31
|
exports.FOOTNOTE_REFERENCE_R = require_markdown_constants.FOOTNOTE_REFERENCE_R;
|
|
31
32
|
exports.FORMFEED_R = require_markdown_constants.FORMFEED_R;
|
|
@@ -81,12 +81,34 @@ const normalizeWhitespace = (source) => {
|
|
|
81
81
|
/**
|
|
82
82
|
* Safely remove a uniform leading indentation from lines, but do NOT touch
|
|
83
83
|
* the content inside fenced code blocks (``` or ~~~).
|
|
84
|
+
*
|
|
85
|
+
* Inside a fenced block the structural indentation is irrelevant: what matters
|
|
86
|
+
* is the indentation of the opening fence itself, which is the only amount
|
|
87
|
+
* CommonMark strips from the code lines. A block nested in an indented HTML
|
|
88
|
+
* element but written with its fence at column 0 therefore keeps its code
|
|
89
|
+
* verbatim, instead of losing the first level of indentation.
|
|
84
90
|
*/
|
|
85
91
|
const trimLeadingWhitespaceOutsideFences = (text, whitespace) => {
|
|
86
92
|
const start = performance.now();
|
|
87
93
|
if (!whitespace) return text;
|
|
88
94
|
const lines = text.split("\n");
|
|
89
|
-
|
|
95
|
+
/** Indentation and marker of the fence currently open, if any. */
|
|
96
|
+
let openFence = null;
|
|
97
|
+
const removePrefix = (line, prefix) => prefix && line.startsWith(prefix) ? line.slice(prefix.length) : line;
|
|
98
|
+
const result = lines.map((line) => {
|
|
99
|
+
const fenceMatch = line.match(require_markdown_constants.FENCE_DELIMITER_R);
|
|
100
|
+
if (!openFence) {
|
|
101
|
+
if (fenceMatch) openFence = {
|
|
102
|
+
indentation: fenceMatch[1],
|
|
103
|
+
marker: fenceMatch[2]
|
|
104
|
+
};
|
|
105
|
+
return removePrefix(line, whitespace);
|
|
106
|
+
}
|
|
107
|
+
const isClosingFence = fenceMatch?.[2].startsWith(openFence.marker);
|
|
108
|
+
const { indentation } = openFence;
|
|
109
|
+
if (isClosingFence) openFence = null;
|
|
110
|
+
return removePrefix(line, indentation);
|
|
111
|
+
}).join("\n");
|
|
90
112
|
const duration = performance.now() - start;
|
|
91
113
|
if (duration > 20) console.log(`trimLeadingWhitespaceOutsideFences: ${duration.toFixed(3)}ms, text length: ${text.length}, lines count: ${lines.length}`);
|
|
92
114
|
return result;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.cjs","names":["UNESCAPE_R","CR_NEWLINE_R","FORMFEED_R","TAB_R","HTML_CUSTOM_ATTR_R","CAPTURE_LETTER_AFTER_HYPHEN","ATTRIBUTES_TO_SANITIZE","INTERPOLATION_R","TABLE_RIGHT_ALIGN","TABLE_CENTER_ALIGN","TABLE_LEFT_ALIGN","TABLE_TRIM_PIPES"],"sources":["../../../src/markdown/utils.ts"],"sourcesContent":["import {\n ATTRIBUTES_TO_SANITIZE,\n CAPTURE_LETTER_AFTER_HYPHEN,\n CR_NEWLINE_R,\n DURATION_DELAY_TRIGGER,\n FORMFEED_R,\n HTML_CUSTOM_ATTR_R,\n INTERPOLATION_R,\n TAB_R,\n TABLE_CENTER_ALIGN,\n TABLE_LEFT_ALIGN,\n TABLE_RIGHT_ALIGN,\n TABLE_TRIM_PIPES,\n UNESCAPE_R,\n} from './constants';\nimport type { NestedParser, ParserResult, ParseState, Rule } from './types';\n\n// ============================================================================\n// STRING UTILITIES\n// ============================================================================\n\n/**\n * Trim trailing whitespace from a string.\n */\nexport const trimEnd = (str: string): string => {\n let end = str.length;\n\n while (end > 0 && str[end - 1] <= ' ') end--;\n\n return str.slice(0, end);\n};\n\n/**\n * Check if string starts with prefix.\n */\nexport const startsWith = (str: string, prefix: string): boolean => {\n return str.startsWith(prefix);\n};\n\n/**\n * Remove symmetrical leading and trailing quotes.\n */\nexport const unquote = (str: string): string => {\n const first = str[0];\n\n if (\n (first === '\"' || first === \"'\") &&\n str.length >= 2 &&\n str[str.length - 1] === first\n ) {\n return str.slice(1, -1);\n }\n\n return str;\n};\n\n/**\n * Unescape backslash-escaped characters.\n */\nexport const unescapeString = (rawString: string): string =>\n rawString ? rawString.replace(UNESCAPE_R, '$1') : rawString;\n\n/**\n * Join class names, filtering out falsy values.\n */\nexport const cx = (...args: any[]): string => args.filter(Boolean).join(' ');\n\n/**\n * Get a nested property from an object using dot notation.\n */\nexport const get = (src: any, path: string, fb?: any): any => {\n let ptr = src;\n const frags = path.split('.');\n\n while (frags.length) {\n ptr = ptr[frags[0]];\n\n if (ptr === undefined) break;\n else frags.shift();\n }\n\n return ptr ?? fb;\n};\n\n// ============================================================================\n// SLUGIFY\n// ============================================================================\n\n/**\n * Convert a string to a URL-safe slug.\n * Based on https://stackoverflow.com/a/18123682/1141611\n */\nexport const slugify = (str: string): string =>\n str\n .replace(/[ÀÁÂÃÄÅàáâãä忯]/g, 'a')\n .replace(/[çÇ]/g, 'c')\n .replace(/[ðÐ]/g, 'd')\n .replace(/[ÈÉÊËéèêë]/g, 'e')\n .replace(/[ÏïÎîÍíÌì]/g, 'i')\n .replace(/[Ññ]/g, 'n')\n .replace(/[øØœŒÕõÔôÓóÒò]/g, 'o')\n .replace(/[ÜüÛûÚúÙù]/g, 'u')\n .replace(/[ŸÿÝý]/g, 'y')\n .replace(/[^a-z0-9- ]/gi, '')\n .replace(/ /gi, '-')\n .toLowerCase();\n\n// ============================================================================\n// SANITIZER\n// ============================================================================\n\nconst SANITIZE_R = /(javascript|vbscript|data(?!:image)):/i;\n\n/**\n * Sanitize URLs to prevent XSS attacks.\n * Returns null if the URL is unsafe.\n */\nexport const sanitizer = (input: string): string | null => {\n try {\n const decoded = decodeURIComponent(input).replace(/[^A-Za-z0-9/:]/g, '');\n\n if (SANITIZE_R.test(decoded)) {\n console.warn(\n 'Input contains an unsafe JavaScript/VBScript/data expression, it will not be rendered.',\n decoded\n );\n\n return null;\n }\n } catch (_e) {\n console.warn(\n 'Input could not be decoded due to malformed syntax or characters, it will not be rendered.',\n input\n );\n\n // decodeURIComponent sometimes throws a URIError\n return null;\n }\n\n return input;\n};\n\n// ============================================================================\n// WHITESPACE NORMALIZATION\n// ============================================================================\n\n/**\n * Normalize whitespace in source string.\n */\nexport const normalizeWhitespace = (source: string): string => {\n const start = performance.now();\n const result = source\n .replace(CR_NEWLINE_R, '\\n')\n .replace(FORMFEED_R, '')\n .replace(TAB_R, ' ');\n\n const duration = performance.now() - start;\n\n if (duration > DURATION_DELAY_TRIGGER) {\n console.log(\n `normalizeWhitespace: ${duration.toFixed(3)}ms, source length: ${source.length}`\n );\n }\n\n return result;\n};\n\n/**\n * Safely remove a uniform leading indentation from lines, but do NOT touch\n * the content inside fenced code blocks (``` or ~~~).\n */\nexport const trimLeadingWhitespaceOutsideFences = (\n text: string,\n whitespace: string\n): string => {\n const start = performance.now();\n if (!whitespace) return text;\n\n const lines = text.split('\\n');\n\n // Strip the base structural indentation from every line uniformly.\n // Lines that don't start with the whitespace prefix are left as-is,\n // which correctly preserves relative indentation inside code fences.\n const result = lines\n .map((line) =>\n line.startsWith(whitespace) ? line.slice(whitespace.length) : line\n )\n .join('\\n');\n\n const duration = performance.now() - start;\n if (duration > DURATION_DELAY_TRIGGER) {\n console.log(\n `trimLeadingWhitespaceOutsideFences: ${duration.toFixed(3)}ms, text length: ${text.length}, lines count: ${lines.length}`\n );\n }\n\n return result;\n};\n\n/**\n * Normalize HTML attribute key to JSX prop name.\n */\nexport const normalizeAttributeKey = (key: string): string => {\n const hyphenIndex = key.indexOf('-');\n\n if (hyphenIndex !== -1 && key.match(HTML_CUSTOM_ATTR_R) === null) {\n key = key.replace(CAPTURE_LETTER_AFTER_HYPHEN, (_, letter) => {\n return letter.toUpperCase();\n });\n }\n\n return key;\n};\n\ntype StyleTuple = [key: string, value: string];\n\n/**\n * Parse a CSS style string into an array of [key, value] tuples.\n */\nexport const parseStyleAttribute = (styleString: string): StyleTuple[] => {\n const start = performance.now();\n const styles: StyleTuple[] = [];\n let buffer = '';\n let inUrl = false;\n let inQuotes = false;\n let quoteChar: '\"' | \"'\" | '' = '';\n\n if (!styleString) return styles;\n\n for (let i = 0; i < styleString.length; i++) {\n const char = styleString[i];\n\n if ((char === '\"' || char === \"'\") && !inUrl) {\n if (!inQuotes) {\n inQuotes = true;\n quoteChar = char;\n } else if (char === quoteChar) {\n inQuotes = false;\n quoteChar = '';\n }\n }\n\n if (char === '(' && buffer.endsWith('url')) {\n inUrl = true;\n } else if (char === ')' && inUrl) {\n inUrl = false;\n }\n\n if (char === ';' && !inQuotes && !inUrl) {\n const declaration = buffer.trim();\n\n if (declaration) {\n const colonIndex = declaration.indexOf(':');\n\n if (colonIndex > 0) {\n const key = declaration.slice(0, colonIndex).trim();\n const value = declaration.slice(colonIndex + 1).trim();\n styles.push([key, value]);\n }\n }\n buffer = '';\n } else {\n buffer += char;\n }\n }\n\n const declaration = buffer.trim();\n\n if (declaration) {\n const colonIndex = declaration.indexOf(':');\n if (colonIndex > 0) {\n const key = declaration.slice(0, colonIndex).trim();\n const value = declaration.slice(colonIndex + 1).trim();\n styles.push([key, value]);\n }\n }\n\n const duration = performance.now() - start;\n\n if (duration > DURATION_DELAY_TRIGGER) {\n console.log(\n `parseStyleAttribute: ${duration.toFixed(3)}ms, styleString length: ${styleString.length}, styles count: ${styles.length}`\n );\n }\n\n return styles;\n};\n\n/**\n * Convert an attribute value to a Node prop value.\n */\nexport const attributeValueToNodePropValue = (\n tag: string,\n key: string,\n value: string,\n sanitizeUrlFn: (\n value: string,\n tag: string,\n attribute: string\n ) => string | null\n): any => {\n if (key === 'style') {\n return parseStyleAttribute(value).reduce(\n (styles, [styleKey, styleValue]) => {\n const camelCasedKey = styleKey.replace(/(-[a-z])/g, (substr) =>\n substr[1].toUpperCase()\n );\n\n (styles as Record<string, any>)[camelCasedKey] = sanitizeUrlFn(\n styleValue,\n tag,\n styleKey\n );\n\n return styles;\n },\n {} as Record<string, any>\n );\n } else if (ATTRIBUTES_TO_SANITIZE.indexOf(key) !== -1) {\n return sanitizeUrlFn(unescapeString(value), tag, key);\n } else if (value.match(INTERPOLATION_R)) {\n value = unescapeString(value.slice(1, value.length - 1));\n }\n\n if (value === 'true') {\n return true;\n } else if (value === 'false') {\n return false;\n }\n\n return value;\n};\n\n// ============================================================================\n// TABLE PARSING\n// ============================================================================\n\n/**\n * Parse table alignment from a separator row.\n */\nexport const parseTableAlignCapture = (\n alignCapture: string\n): 'left' | 'right' | 'center' => {\n if (TABLE_RIGHT_ALIGN.test(alignCapture)) {\n return 'right';\n } else if (TABLE_CENTER_ALIGN.test(alignCapture)) {\n return 'center';\n } else if (TABLE_LEFT_ALIGN.test(alignCapture)) {\n return 'left';\n }\n\n return 'left';\n};\n\n/**\n * Parse table alignment row.\n */\nexport const parseTableAlign = (\n source: string\n): ('left' | 'right' | 'center')[] => {\n const alignText = source.replace(TABLE_TRIM_PIPES, '').split('|');\n return alignText.map(parseTableAlignCapture);\n};\n\n/**\n * Parse a single table row.\n */\nexport const parseTableRow = (\n source: string,\n parse: NestedParser,\n state: ParseState,\n tableOutput: boolean\n): ParserResult[][] => {\n const start = performance.now();\n const prevInTable = state.inTable;\n\n state.inTable = true;\n\n const cells: ParserResult[][] = [[]];\n let acc = '';\n\n const flush = (): void => {\n if (!acc) return;\n\n const cell = cells[cells.length - 1];\n cell.push.apply(cell, parse(acc, state));\n acc = '';\n };\n\n source\n .trim()\n .split(/(`[^`]*`|\\\\\\||\\|)/)\n .filter(Boolean)\n .forEach((fragment, i, arr) => {\n if (fragment.trim() === '|') {\n flush();\n\n if (tableOutput) {\n if (i !== 0 && i !== arr.length - 1) {\n cells.push([]);\n }\n\n return;\n }\n }\n\n acc += fragment;\n });\n\n flush();\n\n state.inTable = prevInTable;\n\n const duration = performance.now() - start;\n if (duration > DURATION_DELAY_TRIGGER) {\n console.log(\n `parseTableRow: ${duration.toFixed(3)}ms, source length: ${source.length}, cells count: ${cells.length}`\n );\n }\n\n return cells;\n};\n\n/**\n * Parse table cells (multiple rows).\n */\nexport const parseTableCells = (\n source: string,\n parse: NestedParser,\n state: ParseState\n): ParserResult[][][] => {\n const start = performance.now();\n const rowsText = source.trim().split('\\n');\n\n const result = rowsText.map((rowText) =>\n parseTableRow(rowText, parse, state, true)\n );\n\n const duration = performance.now() - start;\n if (duration > DURATION_DELAY_TRIGGER) {\n console.log(\n `parseTableCells: ${duration.toFixed(3)}ms, source length: ${source.length}, rows count: ${rowsText.length}`\n );\n }\n\n return result;\n};\n\n// ============================================================================\n// PARSING HELPERS\n// ============================================================================\n\n/**\n * Check if a rule qualifies for the current source and state.\n */\nexport const qualifies = (\n source: string,\n state: ParseState,\n qualify: NonNullable<Rule<any>['_qualify']>\n): boolean => {\n if (Array.isArray(qualify)) {\n for (let i = 0; i < qualify.length; i++) {\n if (startsWith(source, qualify[i])) return true;\n }\n\n return false;\n }\n\n return (qualify as (source: string, state: ParseState) => boolean)(\n source,\n state\n );\n};\n\n/**\n * Marks a matcher function as eligible for being run inside an inline context.\n */\nexport const allowInline = <T extends (...args: any[]) => any>(\n fn: T\n): T & { inline: 1 } => {\n (fn as any).inline = 1;\n return fn as T & { inline: 1 };\n};\n\n/**\n * Creates a match function for an inline scoped element from a regex.\n */\nexport const inlineRegex = (regex: RegExp) =>\n allowInline((source: string, state: ParseState): RegExpMatchArray | null => {\n if (state.inline) {\n return regex.exec(source);\n } else {\n return null;\n }\n });\n\n/**\n * Creates a match function for inline elements except links.\n */\nexport const simpleInlineRegex = (regex: RegExp) =>\n allowInline((source: string, state: ParseState): RegExpMatchArray | null => {\n if (state.inline || state.simple) {\n return regex.exec(source);\n } else {\n return null;\n }\n });\n\n/**\n * Creates a match function for a block scoped element from a regex.\n */\nexport const blockRegex =\n (regex: RegExp) =>\n (source: string, state: ParseState): RegExpMatchArray | null => {\n if (state.inline || state.simple) {\n return null;\n } else {\n return regex.exec(source);\n }\n };\n\n/**\n * Creates a match function from a regex, ignoring block/inline scope.\n */\nexport const anyScopeRegex = (\n fn: RegExp | ((source: string, state: ParseState) => RegExpMatchArray | null)\n) =>\n allowInline((source: string, state: ParseState): RegExpMatchArray | null => {\n if (typeof fn === 'function') {\n return fn(source, state);\n }\n return fn.exec(source);\n });\n\n/**\n * Parse inline content (including links).\n */\nexport const parseInline = (\n parse: NestedParser,\n children: string,\n state: ParseState\n): ParserResult[] => {\n const start = performance.now();\n const isCurrentlyInline = state.inline ?? false;\n const isCurrentlySimple = state.simple ?? false;\n state.inline = true;\n state.simple = true;\n const result = parse(children, state);\n state.inline = isCurrentlyInline;\n state.simple = isCurrentlySimple;\n\n const duration = performance.now() - start;\n if (duration > DURATION_DELAY_TRIGGER) {\n console.log(\n `parseInline: ${duration.toFixed(3)}ms, children length: ${children.length}, result count: ${result.length}`\n );\n }\n\n return result;\n};\n\n/**\n * Parse simple inline content (no links).\n */\nexport const parseSimpleInline = (\n parse: NestedParser,\n children: string,\n state: ParseState\n): ParserResult[] => {\n const start = performance.now();\n const isCurrentlyInline = state.inline ?? false;\n const isCurrentlySimple = state.simple ?? false;\n\n state.inline = false;\n state.simple = true;\n const result = parse(children, state);\n state.inline = isCurrentlyInline;\n state.simple = isCurrentlySimple;\n\n const duration = performance.now() - start;\n if (duration > DURATION_DELAY_TRIGGER) {\n console.log(\n `parseSimpleInline: ${duration.toFixed(3)}ms, children length: ${children.length}, result count: ${result.length}`\n );\n }\n\n return result;\n};\n\n/**\n * Parse block content.\n */\nexport const parseBlock = (\n parse: NestedParser,\n children: string,\n state: ParseState = {}\n): ParserResult[] => {\n const start = performance.now();\n const isCurrentlyInline = state.inline || false;\n state.inline = false;\n const normalizedChildren = trimEnd(children);\n const needsTerminator = /\\n\\n$/.test(normalizedChildren) === false;\n const blockInput = needsTerminator\n ? normalizedChildren.endsWith('\\n')\n ? `${normalizedChildren}\\n`\n : `${normalizedChildren}\\n\\n`\n : normalizedChildren;\n\n const result = parse(blockInput, state);\n state.inline = isCurrentlyInline;\n\n const duration = performance.now() - start;\n if (duration > DURATION_DELAY_TRIGGER) {\n console.log(\n `parseBlock: ${duration.toFixed(3)}ms, children length: ${children.length}, result count: ${result.length}`\n );\n }\n\n return result;\n};\n\n/**\n * Helper to parse capture group 2 as inline content.\n */\nexport const parseCaptureInline = (\n capture: RegExpMatchArray,\n parse: NestedParser,\n state: ParseState\n): { children: ParserResult[] } => {\n return {\n children: parseInline(parse, capture[2], state),\n };\n};\n\n/**\n * Helper that captures nothing (empty object).\n */\nexport const captureNothing = (): Record<string, never> => ({});\n\n/**\n * Helper that renders nothing (null).\n */\nexport const renderNothing = (): null => null;\n\n/**\n * Check if any regex in a list matches the input.\n */\nexport const some = (regexes: RegExp[], input: string): boolean => {\n for (let i = 0; i < regexes.length; i++) {\n if (regexes[i].test(input)) {\n return true;\n }\n }\n return false;\n};\n"],"mappings":";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oB,CAAC,MACF;CACnB,MAAM,QAAQ,YAAY,IAAI;CAC9B,MAAM,oBAAoB,MAAM,UAAU;CAC1C,MAAM,SAAS;CACf,MAAM,qBAAqB,QAAQ,QAAQ;CAQ3C,MAAM,SAAS,MAPS,QAAQ,KAAK,kBAAkB,MAAM,QAEzD,mBAAmB,SAAS,IAAI,IAC9B,GAAG,mBAAmB,MACtB,GAAG,mBAAmB,QACxB,oBAE6B,KAAK;CACtC,MAAM,SAAS;CAEf,MAAM,WAAW,YAAY,IAAI,IAAI;CACrC,IAAI,eACF,QAAQ,IACN,eAAe,SAAS,QAAQ,CAAC,EAAE,uBAAuB,SAAS,OAAO,kBAAkB,OAAO,QACrG;CAGF,OAAO;AACT;;;;AAKA,MAAa,sBACX,SACA,OACA,UACiC;CACjC,OAAO,EACL,UAAU,YAAY,OAAO,QAAQ,IAAI,KAAK,EAChD;AACF;;;;AAKA,MAAa,wBAA+C,CAAC;;;;AAK7D,MAAa,sBAA4B;;;;AAKzC,MAAa,QAAQ,SAAmB,UAA2B;CACjE,KAAK,IAAI,IAAI,GAAG,IAAI,QAAQ,QAAQ,KAClC,IAAI,QAAQ,EAAE,CAAC,KAAK,KAAK,GACvB,OAAO;CAGX,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"utils.cjs","names":["UNESCAPE_R","CR_NEWLINE_R","FORMFEED_R","TAB_R","FENCE_DELIMITER_R","HTML_CUSTOM_ATTR_R","CAPTURE_LETTER_AFTER_HYPHEN","ATTRIBUTES_TO_SANITIZE","INTERPOLATION_R","TABLE_RIGHT_ALIGN","TABLE_CENTER_ALIGN","TABLE_LEFT_ALIGN","TABLE_TRIM_PIPES"],"sources":["../../../src/markdown/utils.ts"],"sourcesContent":["import {\n ATTRIBUTES_TO_SANITIZE,\n CAPTURE_LETTER_AFTER_HYPHEN,\n CR_NEWLINE_R,\n DURATION_DELAY_TRIGGER,\n FENCE_DELIMITER_R,\n FORMFEED_R,\n HTML_CUSTOM_ATTR_R,\n INTERPOLATION_R,\n TAB_R,\n TABLE_CENTER_ALIGN,\n TABLE_LEFT_ALIGN,\n TABLE_RIGHT_ALIGN,\n TABLE_TRIM_PIPES,\n UNESCAPE_R,\n} from './constants';\nimport type { NestedParser, ParserResult, ParseState, Rule } from './types';\n\n// ============================================================================\n// STRING UTILITIES\n// ============================================================================\n\n/**\n * Trim trailing whitespace from a string.\n */\nexport const trimEnd = (str: string): string => {\n let end = str.length;\n\n while (end > 0 && str[end - 1] <= ' ') end--;\n\n return str.slice(0, end);\n};\n\n/**\n * Check if string starts with prefix.\n */\nexport const startsWith = (str: string, prefix: string): boolean => {\n return str.startsWith(prefix);\n};\n\n/**\n * Remove symmetrical leading and trailing quotes.\n */\nexport const unquote = (str: string): string => {\n const first = str[0];\n\n if (\n (first === '\"' || first === \"'\") &&\n str.length >= 2 &&\n str[str.length - 1] === first\n ) {\n return str.slice(1, -1);\n }\n\n return str;\n};\n\n/**\n * Unescape backslash-escaped characters.\n */\nexport const unescapeString = (rawString: string): string =>\n rawString ? rawString.replace(UNESCAPE_R, '$1') : rawString;\n\n/**\n * Join class names, filtering out falsy values.\n */\nexport const cx = (...args: any[]): string => args.filter(Boolean).join(' ');\n\n/**\n * Get a nested property from an object using dot notation.\n */\nexport const get = (src: any, path: string, fb?: any): any => {\n let ptr = src;\n const frags = path.split('.');\n\n while (frags.length) {\n ptr = ptr[frags[0]];\n\n if (ptr === undefined) break;\n else frags.shift();\n }\n\n return ptr ?? fb;\n};\n\n// ============================================================================\n// SLUGIFY\n// ============================================================================\n\n/**\n * Convert a string to a URL-safe slug.\n * Based on https://stackoverflow.com/a/18123682/1141611\n */\nexport const slugify = (str: string): string =>\n str\n .replace(/[ÀÁÂÃÄÅàáâãä忯]/g, 'a')\n .replace(/[çÇ]/g, 'c')\n .replace(/[ðÐ]/g, 'd')\n .replace(/[ÈÉÊËéèêë]/g, 'e')\n .replace(/[ÏïÎîÍíÌì]/g, 'i')\n .replace(/[Ññ]/g, 'n')\n .replace(/[øØœŒÕõÔôÓóÒò]/g, 'o')\n .replace(/[ÜüÛûÚúÙù]/g, 'u')\n .replace(/[ŸÿÝý]/g, 'y')\n .replace(/[^a-z0-9- ]/gi, '')\n .replace(/ /gi, '-')\n .toLowerCase();\n\n// ============================================================================\n// SANITIZER\n// ============================================================================\n\nconst SANITIZE_R = /(javascript|vbscript|data(?!:image)):/i;\n\n/**\n * Sanitize URLs to prevent XSS attacks.\n * Returns null if the URL is unsafe.\n */\nexport const sanitizer = (input: string): string | null => {\n try {\n const decoded = decodeURIComponent(input).replace(/[^A-Za-z0-9/:]/g, '');\n\n if (SANITIZE_R.test(decoded)) {\n console.warn(\n 'Input contains an unsafe JavaScript/VBScript/data expression, it will not be rendered.',\n decoded\n );\n\n return null;\n }\n } catch (_e) {\n console.warn(\n 'Input could not be decoded due to malformed syntax or characters, it will not be rendered.',\n input\n );\n\n // decodeURIComponent sometimes throws a URIError\n return null;\n }\n\n return input;\n};\n\n// ============================================================================\n// WHITESPACE NORMALIZATION\n// ============================================================================\n\n/**\n * Normalize whitespace in source string.\n */\nexport const normalizeWhitespace = (source: string): string => {\n const start = performance.now();\n const result = source\n .replace(CR_NEWLINE_R, '\\n')\n .replace(FORMFEED_R, '')\n .replace(TAB_R, ' ');\n\n const duration = performance.now() - start;\n\n if (duration > DURATION_DELAY_TRIGGER) {\n console.log(\n `normalizeWhitespace: ${duration.toFixed(3)}ms, source length: ${source.length}`\n );\n }\n\n return result;\n};\n\n/**\n * Safely remove a uniform leading indentation from lines, but do NOT touch\n * the content inside fenced code blocks (``` or ~~~).\n *\n * Inside a fenced block the structural indentation is irrelevant: what matters\n * is the indentation of the opening fence itself, which is the only amount\n * CommonMark strips from the code lines. A block nested in an indented HTML\n * element but written with its fence at column 0 therefore keeps its code\n * verbatim, instead of losing the first level of indentation.\n */\nexport const trimLeadingWhitespaceOutsideFences = (\n text: string,\n whitespace: string\n): string => {\n const start = performance.now();\n if (!whitespace) return text;\n\n const lines = text.split('\\n');\n\n /** Indentation and marker of the fence currently open, if any. */\n let openFence: { indentation: string; marker: string } | null = null;\n\n const removePrefix = (line: string, prefix: string): string =>\n prefix && line.startsWith(prefix) ? line.slice(prefix.length) : line;\n\n // Outside fences, strip the base structural indentation from every line.\n // Lines that don't start with the whitespace prefix are left as-is.\n const result = lines\n .map((line) => {\n const fenceMatch = line.match(FENCE_DELIMITER_R);\n\n if (!openFence) {\n if (fenceMatch)\n openFence = { indentation: fenceMatch[1], marker: fenceMatch[2] };\n return removePrefix(line, whitespace);\n }\n\n const isClosingFence = fenceMatch?.[2].startsWith(openFence.marker);\n const { indentation } = openFence;\n\n if (isClosingFence) openFence = null;\n\n return removePrefix(line, indentation);\n })\n .join('\\n');\n\n const duration = performance.now() - start;\n if (duration > DURATION_DELAY_TRIGGER) {\n console.log(\n `trimLeadingWhitespaceOutsideFences: ${duration.toFixed(3)}ms, text length: ${text.length}, lines count: ${lines.length}`\n );\n }\n\n return result;\n};\n\n/**\n * Normalize HTML attribute key to JSX prop name.\n */\nexport const normalizeAttributeKey = (key: string): string => {\n const hyphenIndex = key.indexOf('-');\n\n if (hyphenIndex !== -1 && key.match(HTML_CUSTOM_ATTR_R) === null) {\n key = key.replace(CAPTURE_LETTER_AFTER_HYPHEN, (_, letter) => {\n return letter.toUpperCase();\n });\n }\n\n return key;\n};\n\ntype StyleTuple = [key: string, value: string];\n\n/**\n * Parse a CSS style string into an array of [key, value] tuples.\n */\nexport const parseStyleAttribute = (styleString: string): StyleTuple[] => {\n const start = performance.now();\n const styles: StyleTuple[] = [];\n let buffer = '';\n let inUrl = false;\n let inQuotes = false;\n let quoteChar: '\"' | \"'\" | '' = '';\n\n if (!styleString) return styles;\n\n for (let i = 0; i < styleString.length; i++) {\n const char = styleString[i];\n\n if ((char === '\"' || char === \"'\") && !inUrl) {\n if (!inQuotes) {\n inQuotes = true;\n quoteChar = char;\n } else if (char === quoteChar) {\n inQuotes = false;\n quoteChar = '';\n }\n }\n\n if (char === '(' && buffer.endsWith('url')) {\n inUrl = true;\n } else if (char === ')' && inUrl) {\n inUrl = false;\n }\n\n if (char === ';' && !inQuotes && !inUrl) {\n const declaration = buffer.trim();\n\n if (declaration) {\n const colonIndex = declaration.indexOf(':');\n\n if (colonIndex > 0) {\n const key = declaration.slice(0, colonIndex).trim();\n const value = declaration.slice(colonIndex + 1).trim();\n styles.push([key, value]);\n }\n }\n buffer = '';\n } else {\n buffer += char;\n }\n }\n\n const declaration = buffer.trim();\n\n if (declaration) {\n const colonIndex = declaration.indexOf(':');\n if (colonIndex > 0) {\n const key = declaration.slice(0, colonIndex).trim();\n const value = declaration.slice(colonIndex + 1).trim();\n styles.push([key, value]);\n }\n }\n\n const duration = performance.now() - start;\n\n if (duration > DURATION_DELAY_TRIGGER) {\n console.log(\n `parseStyleAttribute: ${duration.toFixed(3)}ms, styleString length: ${styleString.length}, styles count: ${styles.length}`\n );\n }\n\n return styles;\n};\n\n/**\n * Convert an attribute value to a Node prop value.\n */\nexport const attributeValueToNodePropValue = (\n tag: string,\n key: string,\n value: string,\n sanitizeUrlFn: (\n value: string,\n tag: string,\n attribute: string\n ) => string | null\n): any => {\n if (key === 'style') {\n return parseStyleAttribute(value).reduce(\n (styles, [styleKey, styleValue]) => {\n const camelCasedKey = styleKey.replace(/(-[a-z])/g, (substr) =>\n substr[1].toUpperCase()\n );\n\n (styles as Record<string, any>)[camelCasedKey] = sanitizeUrlFn(\n styleValue,\n tag,\n styleKey\n );\n\n return styles;\n },\n {} as Record<string, any>\n );\n } else if (ATTRIBUTES_TO_SANITIZE.indexOf(key) !== -1) {\n return sanitizeUrlFn(unescapeString(value), tag, key);\n } else if (value.match(INTERPOLATION_R)) {\n value = unescapeString(value.slice(1, value.length - 1));\n }\n\n if (value === 'true') {\n return true;\n } else if (value === 'false') {\n return false;\n }\n\n return value;\n};\n\n// ============================================================================\n// TABLE PARSING\n// ============================================================================\n\n/**\n * Parse table alignment from a separator row.\n */\nexport const parseTableAlignCapture = (\n alignCapture: string\n): 'left' | 'right' | 'center' => {\n if (TABLE_RIGHT_ALIGN.test(alignCapture)) {\n return 'right';\n } else if (TABLE_CENTER_ALIGN.test(alignCapture)) {\n return 'center';\n } else if (TABLE_LEFT_ALIGN.test(alignCapture)) {\n return 'left';\n }\n\n return 'left';\n};\n\n/**\n * Parse table alignment row.\n */\nexport const parseTableAlign = (\n source: string\n): ('left' | 'right' | 'center')[] => {\n const alignText = source.replace(TABLE_TRIM_PIPES, '').split('|');\n return alignText.map(parseTableAlignCapture);\n};\n\n/**\n * Parse a single table row.\n */\nexport const parseTableRow = (\n source: string,\n parse: NestedParser,\n state: ParseState,\n tableOutput: boolean\n): ParserResult[][] => {\n const start = performance.now();\n const prevInTable = state.inTable;\n\n state.inTable = true;\n\n const cells: ParserResult[][] = [[]];\n let acc = '';\n\n const flush = (): void => {\n if (!acc) return;\n\n const cell = cells[cells.length - 1];\n cell.push.apply(cell, parse(acc, state));\n acc = '';\n };\n\n source\n .trim()\n .split(/(`[^`]*`|\\\\\\||\\|)/)\n .filter(Boolean)\n .forEach((fragment, i, arr) => {\n if (fragment.trim() === '|') {\n flush();\n\n if (tableOutput) {\n if (i !== 0 && i !== arr.length - 1) {\n cells.push([]);\n }\n\n return;\n }\n }\n\n acc += fragment;\n });\n\n flush();\n\n state.inTable = prevInTable;\n\n const duration = performance.now() - start;\n if (duration > DURATION_DELAY_TRIGGER) {\n console.log(\n `parseTableRow: ${duration.toFixed(3)}ms, source length: ${source.length}, cells count: ${cells.length}`\n );\n }\n\n return cells;\n};\n\n/**\n * Parse table cells (multiple rows).\n */\nexport const parseTableCells = (\n source: string,\n parse: NestedParser,\n state: ParseState\n): ParserResult[][][] => {\n const start = performance.now();\n const rowsText = source.trim().split('\\n');\n\n const result = rowsText.map((rowText) =>\n parseTableRow(rowText, parse, state, true)\n );\n\n const duration = performance.now() - start;\n if (duration > DURATION_DELAY_TRIGGER) {\n console.log(\n `parseTableCells: ${duration.toFixed(3)}ms, source length: ${source.length}, rows count: ${rowsText.length}`\n );\n }\n\n return result;\n};\n\n// ============================================================================\n// PARSING HELPERS\n// ============================================================================\n\n/**\n * Check if a rule qualifies for the current source and state.\n */\nexport const qualifies = (\n source: string,\n state: ParseState,\n qualify: NonNullable<Rule<any>['_qualify']>\n): boolean => {\n if (Array.isArray(qualify)) {\n for (let i = 0; i < qualify.length; i++) {\n if (startsWith(source, qualify[i])) return true;\n }\n\n return false;\n }\n\n return (qualify as (source: string, state: ParseState) => boolean)(\n source,\n state\n );\n};\n\n/**\n * Marks a matcher function as eligible for being run inside an inline context.\n */\nexport const allowInline = <T extends (...args: any[]) => any>(\n fn: T\n): T & { inline: 1 } => {\n (fn as any).inline = 1;\n return fn as T & { inline: 1 };\n};\n\n/**\n * Creates a match function for an inline scoped element from a regex.\n */\nexport const inlineRegex = (regex: RegExp) =>\n allowInline((source: string, state: ParseState): RegExpMatchArray | null => {\n if (state.inline) {\n return regex.exec(source);\n } else {\n return null;\n }\n });\n\n/**\n * Creates a match function for inline elements except links.\n */\nexport const simpleInlineRegex = (regex: RegExp) =>\n allowInline((source: string, state: ParseState): RegExpMatchArray | null => {\n if (state.inline || state.simple) {\n return regex.exec(source);\n } else {\n return null;\n }\n });\n\n/**\n * Creates a match function for a block scoped element from a regex.\n */\nexport const blockRegex =\n (regex: RegExp) =>\n (source: string, state: ParseState): RegExpMatchArray | null => {\n if (state.inline || state.simple) {\n return null;\n } else {\n return regex.exec(source);\n }\n };\n\n/**\n * Creates a match function from a regex, ignoring block/inline scope.\n */\nexport const anyScopeRegex = (\n fn: RegExp | ((source: string, state: ParseState) => RegExpMatchArray | null)\n) =>\n allowInline((source: string, state: ParseState): RegExpMatchArray | null => {\n if (typeof fn === 'function') {\n return fn(source, state);\n }\n return fn.exec(source);\n });\n\n/**\n * Parse inline content (including links).\n */\nexport const parseInline = (\n parse: NestedParser,\n children: string,\n state: ParseState\n): ParserResult[] => {\n const start = performance.now();\n const isCurrentlyInline = state.inline ?? false;\n const isCurrentlySimple = state.simple ?? false;\n state.inline = true;\n state.simple = true;\n const result = parse(children, state);\n state.inline = isCurrentlyInline;\n state.simple = isCurrentlySimple;\n\n const duration = performance.now() - start;\n if (duration > DURATION_DELAY_TRIGGER) {\n console.log(\n `parseInline: ${duration.toFixed(3)}ms, children length: ${children.length}, result count: ${result.length}`\n );\n }\n\n return result;\n};\n\n/**\n * Parse simple inline content (no links).\n */\nexport const parseSimpleInline = (\n parse: NestedParser,\n children: string,\n state: ParseState\n): ParserResult[] => {\n const start = performance.now();\n const isCurrentlyInline = state.inline ?? false;\n const isCurrentlySimple = state.simple ?? false;\n\n state.inline = false;\n state.simple = true;\n const result = parse(children, state);\n state.inline = isCurrentlyInline;\n state.simple = isCurrentlySimple;\n\n const duration = performance.now() - start;\n if (duration > DURATION_DELAY_TRIGGER) {\n console.log(\n `parseSimpleInline: ${duration.toFixed(3)}ms, children length: ${children.length}, result count: ${result.length}`\n );\n }\n\n return result;\n};\n\n/**\n * Parse block content.\n */\nexport const parseBlock = (\n parse: NestedParser,\n children: string,\n state: ParseState = {}\n): ParserResult[] => {\n const start = performance.now();\n const isCurrentlyInline = state.inline || false;\n state.inline = false;\n const normalizedChildren = trimEnd(children);\n const needsTerminator = /\\n\\n$/.test(normalizedChildren) === false;\n const blockInput = needsTerminator\n ? normalizedChildren.endsWith('\\n')\n ? `${normalizedChildren}\\n`\n : `${normalizedChildren}\\n\\n`\n : normalizedChildren;\n\n const result = parse(blockInput, state);\n state.inline = isCurrentlyInline;\n\n const duration = performance.now() - start;\n if (duration > DURATION_DELAY_TRIGGER) {\n console.log(\n `parseBlock: ${duration.toFixed(3)}ms, children length: ${children.length}, result count: ${result.length}`\n );\n }\n\n return result;\n};\n\n/**\n * Helper to parse capture group 2 as inline content.\n */\nexport const parseCaptureInline = (\n capture: RegExpMatchArray,\n parse: NestedParser,\n state: ParseState\n): { children: ParserResult[] } => {\n return {\n children: parseInline(parse, capture[2], state),\n };\n};\n\n/**\n * Helper that captures nothing (empty object).\n */\nexport const captureNothing = (): Record<string, never> => ({});\n\n/**\n * Helper that renders nothing (null).\n */\nexport const renderNothing = (): null => null;\n\n/**\n * Check if any regex in a list matches the input.\n */\nexport const some = (regexes: RegExp[], input: string): boolean => {\n for (let i = 0; i < regexes.length; i++) {\n if (regexes[i].test(input)) {\n return true;\n }\n }\n return false;\n};\n"],"mappings":";;;;;;;AAyBA,MAAa,WAAW,QAAwB;CAC9C,IAAI,MAAM,IAAI;CAEd,OAAO,MAAM,KAAK,IAAI,MAAM,MAAM,KAAK;CAEvC,OAAO,IAAI,MAAM,GAAG,GAAG;AACzB;;;;AAKA,MAAa,cAAc,KAAa,WAA4B;CAClE,OAAO,IAAI,WAAW,MAAM;AAC9B;;;;AAKA,MAAa,WAAW,QAAwB;CAC9C,MAAM,QAAQ,IAAI;CAElB,KACG,UAAU,QAAO,UAAU,QAC5B,IAAI,UAAU,KACd,IAAI,IAAI,SAAS,OAAO,OAExB,OAAO,IAAI,MAAM,GAAG,EAAE;CAGxB,OAAO;AACT;;;;AAKA,MAAa,kBAAkB,cAC7B,YAAY,UAAU,QAAQA,uCAAY,IAAI,IAAI;;;;AAKpD,MAAa,MAAM,GAAG,SAAwB,KAAK,OAAO,OAAO,CAAC,CAAC,KAAK,GAAG;;;;AAK3E,MAAa,OAAO,KAAU,MAAc,OAAkB;CAC5D,IAAI,MAAM;CACV,MAAM,QAAQ,KAAK,MAAM,GAAG;CAE5B,OAAO,MAAM,QAAQ;EACnB,MAAM,IAAI,MAAM;EAEhB,IAAI,QAAQ,QAAW;OAClB,MAAM,MAAM;CACnB;CAEA,OAAO,OAAO;AAChB;;;;;AAUA,MAAa,WAAW,QACtB,IACG,QAAQ,qBAAqB,GAAG,CAAC,CACjC,QAAQ,SAAS,GAAG,CAAC,CACrB,QAAQ,SAAS,GAAG,CAAC,CACrB,QAAQ,eAAe,GAAG,CAAC,CAC3B,QAAQ,eAAe,GAAG,CAAC,CAC3B,QAAQ,SAAS,GAAG,CAAC,CACrB,QAAQ,mBAAmB,GAAG,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jE,KAAK,IAAI,IAAI,GAAG,IAAI,QAAQ,QAAQ,KAClC,IAAI,QAAQ,EAAE,CAAC,KAAK,KAAK,GACvB,OAAO;CAGX,OAAO;AACT"}
|
|
@@ -11,9 +11,10 @@ import { QUALIFIER_ORDER, getDictionaryCompositeIds, getDictionaryQualifierIds,
|
|
|
11
11
|
import { mergeQualifiedDictionaries } from "./mergeQualifiedDictionaries.mjs";
|
|
12
12
|
import { orderDictionaries } from "./orderDictionaries.mjs";
|
|
13
13
|
import { normalizeDictionaries, normalizeDictionary } from "./normalizeDictionary.mjs";
|
|
14
|
+
import { PRELOADED_DYNAMIC_KEY, getPreloadedDictionary } from "./preloadedDynamicLoader.mjs";
|
|
14
15
|
import { QUALIFIER_DYNAMIC_TYPES_KEY, isQualifiedDynamicLoaderMap, resolveQualifiedDynamicContent, resolveQualifiedDynamicContentAsync } from "./qualifiedDynamicLoader.mjs";
|
|
15
16
|
import { removeContentNodeByKeyPath } from "./removeContentNodeByKeyPath.mjs";
|
|
16
17
|
import { renameContentNodeByKeyPath } from "./renameContentNodeByKeyPath.mjs";
|
|
17
18
|
import { updateNodeChildren } from "./updateNodeChildren.mjs";
|
|
18
19
|
|
|
19
|
-
export { COMPOSITE_ID_SEPARATOR, DEFAULT_VARIANT_ID, QUALIFIER_DYNAMIC_TYPES_KEY, QUALIFIER_ORDER, editDictionaryByKeyPath, getContentNodeByKeyPath, getDefaultNode, getDictionaryCompositeIds, getDictionaryQualifierIds, getDictionaryQualifierTypes, getDictionarySelectorCacheKey, getEmptyNode, getNestedDictionaryGraph, getNestedDictionaryKeys, getNestedDictionaryReferences, getNodeChildren, getNodeType, getVariantIds, isQualifiedDictionaryGroup, isQualifiedDynamicLoaderMap, mergeDictionaries, mergeQualifiedDictionaries, normalizeDictionaries, normalizeDictionary, orderDictionaries, parseDictionarySelector, reconstructQualifiedEntry, removeContentNodeByKeyPath, renameContentNodeByKeyPath, resolveDictionaryArgument, resolveEffectiveVariantId, resolveProviderVariant, resolveQualifiedDictionary, resolveQualifiedDynamicContent, resolveQualifiedDynamicContentAsync, serializeVariant, serializeVariantChain, updateNodeChildren };
|
|
20
|
+
export { COMPOSITE_ID_SEPARATOR, DEFAULT_VARIANT_ID, PRELOADED_DYNAMIC_KEY, QUALIFIER_DYNAMIC_TYPES_KEY, QUALIFIER_ORDER, editDictionaryByKeyPath, getContentNodeByKeyPath, getDefaultNode, getDictionaryCompositeIds, getDictionaryQualifierIds, getDictionaryQualifierTypes, getDictionarySelectorCacheKey, getEmptyNode, getNestedDictionaryGraph, getNestedDictionaryKeys, getNestedDictionaryReferences, getNodeChildren, getNodeType, getPreloadedDictionary, getVariantIds, isQualifiedDictionaryGroup, isQualifiedDynamicLoaderMap, mergeDictionaries, mergeQualifiedDictionaries, normalizeDictionaries, normalizeDictionary, orderDictionaries, parseDictionarySelector, reconstructQualifiedEntry, removeContentNodeByKeyPath, renameContentNodeByKeyPath, resolveDictionaryArgument, resolveEffectiveVariantId, resolveProviderVariant, resolveQualifiedDictionary, resolveQualifiedDynamicContent, resolveQualifiedDynamicContentAsync, serializeVariant, serializeVariantChain, updateNodeChildren };
|