@intlayer/core 9.3.1 → 9.3.3
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/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/compiler.cjs +2 -1
- package/dist/cjs/markdown/compiler.cjs.map +1 -1
- 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/compiler.mjs +2 -1
- package/dist/esm/markdown/compiler.mjs.map +1 -1
- 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/@intlayer/core/dist/types/formatters/compact.d.ts +1 -0
- package/dist/types/@intlayer/core/dist/types/formatters/currency.d.ts +1 -0
- package/dist/types/@intlayer/core/dist/types/formatters/date.d.ts +1 -0
- package/dist/types/@intlayer/core/dist/types/formatters/index.d.ts +9 -0
- package/dist/types/@intlayer/core/dist/types/formatters/list.d.ts +1 -0
- package/dist/types/@intlayer/core/dist/types/formatters/number.d.ts +1 -0
- package/dist/types/@intlayer/core/dist/types/formatters/percentage.d.ts +1 -0
- package/dist/types/@intlayer/core/dist/types/formatters/relativeTime.d.ts +1 -0
- package/dist/types/@intlayer/core/dist/types/formatters/units.d.ts +1 -0
- package/dist/types/@intlayer/core/dist/types/interpreter/getCondition.d.ts +2 -0
- package/dist/types/@intlayer/core/dist/types/interpreter/getContent/deepTransform.d.ts +1 -0
- package/dist/types/@intlayer/core/dist/types/interpreter/getContent/getContent.d.ts +3 -0
- package/dist/types/@intlayer/core/dist/types/interpreter/getContent/index.d.ts +3 -0
- package/dist/types/@intlayer/core/dist/types/interpreter/getContent/plugins.d.ts +7 -0
- package/dist/types/@intlayer/core/dist/types/interpreter/getDictionary.d.ts +4 -0
- package/dist/types/@intlayer/core/dist/types/interpreter/getEnumeration.d.ts +2 -0
- package/dist/types/@intlayer/core/dist/types/interpreter/getGender.d.ts +2 -0
- package/dist/types/@intlayer/core/dist/types/interpreter/getInsertion.d.ts +2 -0
- package/dist/types/@intlayer/core/dist/types/interpreter/getIntlayer.d.ts +4 -0
- package/dist/types/@intlayer/core/dist/types/interpreter/getNesting.d.ts +6 -0
- package/dist/types/@intlayer/core/dist/types/interpreter/getPlural.d.ts +3 -0
- package/dist/types/@intlayer/core/dist/types/interpreter/getSelect.d.ts +2 -0
- package/dist/types/@intlayer/core/dist/types/interpreter/getTranslation.d.ts +1 -0
- package/dist/types/@intlayer/core/dist/types/interpreter/index.d.ts +15 -0
- package/dist/types/@intlayer/core/dist/types/interpreter/interpolableNode.d.ts +2 -0
- package/dist/types/@intlayer/core/dist/types/localization/comparePaths.d.ts +1 -0
- package/dist/types/@intlayer/core/dist/types/localization/domainUtils.d.ts +2 -0
- package/dist/types/@intlayer/core/dist/types/localization/generateSitemap.d.ts +2 -0
- package/dist/types/@intlayer/core/dist/types/localization/getBrowserLocale.d.ts +1 -0
- package/dist/types/@intlayer/core/dist/types/localization/getHTMLTextDir.d.ts +1 -0
- package/dist/types/@intlayer/core/dist/types/localization/getLocale.d.ts +1 -0
- package/dist/types/@intlayer/core/dist/types/localization/getLocaleFromPath.d.ts +2 -0
- package/dist/types/@intlayer/core/dist/types/localization/getLocaleLang.d.ts +1 -0
- package/dist/types/@intlayer/core/dist/types/localization/getLocaleName.d.ts +1 -0
- package/dist/types/@intlayer/core/dist/types/localization/getLocalizedPath.d.ts +2 -0
- package/dist/types/@intlayer/core/dist/types/localization/getLocalizedUrl.d.ts +2 -0
- package/dist/types/@intlayer/core/dist/types/localization/getMultilingualUrls.d.ts +2 -0
- package/dist/types/@intlayer/core/dist/types/localization/getPathWithoutLocale.d.ts +1 -0
- package/dist/types/@intlayer/core/dist/types/localization/getPrefix.d.ts +2 -0
- package/dist/types/@intlayer/core/dist/types/localization/index.d.ts +20 -0
- package/dist/types/@intlayer/core/dist/types/localization/localeDetector.d.ts +2 -0
- package/dist/types/@intlayer/core/dist/types/localization/localeMapper.d.ts +1 -0
- package/dist/types/@intlayer/core/dist/types/localization/localeResolver.d.ts +1 -0
- package/dist/types/@intlayer/core/dist/types/localization/resolveBrowserLocale.d.ts +2 -0
- package/dist/types/@intlayer/core/dist/types/localization/rewriteUtils.d.ts +2 -0
- package/dist/types/@intlayer/core/dist/types/localization/validatePrefix.d.ts +2 -0
- package/dist/types/@intlayer/core/dist/types/markdown/index.d.ts +2 -0
- package/dist/types/@intlayer/core/dist/types/transpiler/condition/condition.d.ts +1 -0
- package/dist/types/@intlayer/core/dist/types/transpiler/condition/index.d.ts +1 -0
- package/dist/types/@intlayer/core/dist/types/transpiler/enumeration/enumeration.d.ts +1 -0
- package/dist/types/@intlayer/core/dist/types/transpiler/enumeration/index.d.ts +1 -0
- package/dist/types/@intlayer/core/dist/types/transpiler/file/file.d.ts +1 -0
- package/dist/types/@intlayer/core/dist/types/transpiler/file/index.d.ts +1 -0
- package/dist/types/@intlayer/core/dist/types/transpiler/gender/gender.d.ts +1 -0
- package/dist/types/@intlayer/core/dist/types/transpiler/gender/index.d.ts +1 -0
- package/dist/types/@intlayer/core/dist/types/transpiler/html/html.d.ts +1 -0
- package/dist/types/@intlayer/core/dist/types/transpiler/html/index.d.ts +1 -0
- package/dist/types/@intlayer/core/dist/types/transpiler/index.d.ts +22 -0
- package/dist/types/@intlayer/core/dist/types/transpiler/insertion/index.d.ts +1 -0
- package/dist/types/@intlayer/core/dist/types/transpiler/insertion/insertion.d.ts +1 -0
- package/dist/types/@intlayer/core/dist/types/transpiler/markdown/index.d.ts +1 -0
- package/dist/types/@intlayer/core/dist/types/transpiler/markdown/markdown.d.ts +1 -0
- package/dist/types/@intlayer/core/dist/types/transpiler/nesting/index.d.ts +1 -0
- package/dist/types/@intlayer/core/dist/types/transpiler/nesting/nesting.d.ts +4 -0
- package/dist/types/@intlayer/core/dist/types/transpiler/plural/index.d.ts +1 -0
- package/dist/types/@intlayer/core/dist/types/transpiler/plural/plural.d.ts +1 -0
- package/dist/types/@intlayer/core/dist/types/transpiler/select/index.d.ts +1 -0
- package/dist/types/@intlayer/core/dist/types/transpiler/select/select.d.ts +1 -0
- package/dist/types/@intlayer/core/dist/types/transpiler/translation/index.d.ts +1 -0
- package/dist/types/@intlayer/core/dist/types/transpiler/translation/translation.d.ts +2 -0
- package/dist/types/@intlayer/core/dist/types/utils/index.d.ts +3 -0
- package/dist/types/@intlayer/core/dist/types/utils/intl.d.ts +1 -0
- package/dist/types/@intlayer/core/dist/types/utils/isSameKeyPath.d.ts +1 -0
- package/dist/types/@intlayer/core/dist/types/utils/localeStorage.d.ts +2 -0
- 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 +8 -5
- package/dist/types/interpreter/getPlural.d.ts +1 -1
- package/dist/types/intlayer/dist/types/index.d.ts +14 -0
- 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/compiler.d.ts +12 -1
- package/dist/types/markdown/compiler.d.ts.map +1 -1
- 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 +3 -3
- package/dist/types/markdown/utils.d.ts +6 -0
- package/dist/types/markdown/utils.d.ts.map +1 -1
- package/package.json +7 -7
|
@@ -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;CAC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,cAAc,WACzC;;AAGA,MAAa,gBAAgB,IAAI,OAC/B,QAAQ,UAAU,CAAC,IAAI,cAAc,IACvC;;AAGA,MAAa,yBAAyB,IAAI,OACxC,QAAQ,UAAU,CAAC,IAAI,cAAc,IACvC;AAMA,MAAa,0BAA0B,SAA2B;CAChE,OACE,WACC,aAAmB,sBAAsB,yBAC1C;AAEJ;AAEA,MAAa,2BAA2B,wBAA8B;AACtE,MAAa,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"}
|
|
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?/;\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,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,y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,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":";;;;;;;AAwBA,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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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;;;;A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ACpC,MAAM,SAAS;CACf,MAAM,SAAS;CAEf,MAAM,WAAW,YAAY,IAAI,IAAI;CACrC,IAAI,eACF,QAAQ,IACN,sBAAsB,SAAS,QAAQ,CAAC,EAAE,uBAAuB,SAAS,OAAO,kBAAkB,OAAO,QAC5G;CAGF,OAAO;AACT;;;;AAKA,MAAa,cACX,OACA,UACA,QAAoB,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"}
|
|
@@ -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 };
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import { PRELOADED_DYNAMIC_KEY } from "./preloadedDynamicLoader.mjs";
|
|
2
|
+
import { QUALIFIER_DYNAMIC_TYPES_KEY } from "./qualifiedDynamicLoader.mjs";
|
|
3
|
+
import { internationalization } from "@intlayer/config/built";
|
|
4
|
+
|
|
5
|
+
//#region src/dictionaryManipulator/plainDynamicLoader.ts
|
|
6
|
+
/** Marker properties a loader map carries alongside its per-locale loaders. */
|
|
7
|
+
const MARKER_KEYS = [PRELOADED_DYNAMIC_KEY, QUALIFIER_DYNAMIC_TYPES_KEY];
|
|
8
|
+
/**
|
|
9
|
+
* Ordered locale candidates for a chunk lookup, mirroring the static fallback
|
|
10
|
+
* chain `getTranslation` applies: the requested locale, its base language, then
|
|
11
|
+
* the default locale and its base language.
|
|
12
|
+
*/
|
|
13
|
+
const getLocaleCandidates = (locale) => {
|
|
14
|
+
const candidates = [];
|
|
15
|
+
const addCandidate = (candidate) => {
|
|
16
|
+
if (candidate && !candidates.includes(candidate)) candidates.push(candidate);
|
|
17
|
+
};
|
|
18
|
+
addCandidate(locale);
|
|
19
|
+
addCandidate(locale.split("-")[0]);
|
|
20
|
+
addCandidate(internationalization.defaultLocale);
|
|
21
|
+
addCandidate(internationalization.defaultLocale?.split("-")[0]);
|
|
22
|
+
return candidates;
|
|
23
|
+
};
|
|
24
|
+
/**
|
|
25
|
+
* Picks the chunk loader serving a locale out of a plain dynamic loader map.
|
|
26
|
+
*
|
|
27
|
+
* A dictionary is only emitted for the locales it declares, so a read for any
|
|
28
|
+
* other locale — an undeclared one, or a partially translated dictionary under
|
|
29
|
+
* `requiredLocales` — has no chunk of its own. Static mode answers such a read
|
|
30
|
+
* with the default locale's content rather than nothing, and this walks the
|
|
31
|
+
* same chain so dynamic mode stays interchangeable with it.
|
|
32
|
+
*
|
|
33
|
+
* @param loaderMap - Default export of a generated dynamic entry point.
|
|
34
|
+
* @param locale - Locale the caller is about to render.
|
|
35
|
+
* @returns The loader to invoke and the locale its chunk holds, or `undefined`
|
|
36
|
+
* when the map holds no chunk for the locale nor for any fallback.
|
|
37
|
+
*/
|
|
38
|
+
const findPlainDynamicLoader = (loaderMap, locale) => {
|
|
39
|
+
for (const candidate of getLocaleCandidates(locale)) {
|
|
40
|
+
const loader = loaderMap[candidate];
|
|
41
|
+
if (typeof loader === "function") return {
|
|
42
|
+
locale: candidate,
|
|
43
|
+
loader
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
};
|
|
47
|
+
/** Lists the locales a loader map actually emitted a chunk for. */
|
|
48
|
+
const getEmittedLocales = (loaderMap) => Object.keys(loaderMap).filter((loaderKey) => !MARKER_KEYS.includes(loaderKey) && typeof loaderMap[loaderKey] === "function");
|
|
49
|
+
/**
|
|
50
|
+
* {@link findPlainDynamicLoader}, for callers that cannot render without a
|
|
51
|
+
* chunk and would otherwise fail on an `undefined` loader with an error naming
|
|
52
|
+
* neither the dictionary nor the locale.
|
|
53
|
+
*
|
|
54
|
+
* @param loaderMap - Default export of a generated dynamic entry point.
|
|
55
|
+
* @param key - Dictionary key, used to describe an unresolvable lookup.
|
|
56
|
+
* @param locale - Locale the caller is about to render.
|
|
57
|
+
* @returns The loader to invoke, and the locale its chunk holds.
|
|
58
|
+
* @throws When neither the locale nor any of its fallbacks has a chunk, which
|
|
59
|
+
* only happens on a malformed or empty entry point.
|
|
60
|
+
*/
|
|
61
|
+
const resolvePlainDynamicLoader = (loaderMap, key, locale) => {
|
|
62
|
+
const resolved = findPlainDynamicLoader(loaderMap, locale);
|
|
63
|
+
if (resolved) return resolved;
|
|
64
|
+
const emittedLocales = getEmittedLocales(loaderMap);
|
|
65
|
+
throw new Error(`[intlayer] No dynamic chunk found for dictionary "${key}" and locale "${locale}". Emitted locales: ${emittedLocales.length > 0 ? emittedLocales.join(", ") : "(none)"}.`);
|
|
66
|
+
};
|
|
67
|
+
|
|
68
|
+
//#endregion
|
|
69
|
+
export { findPlainDynamicLoader, resolvePlainDynamicLoader };
|
|
70
|
+
//# sourceMappingURL=plainDynamicLoader.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"plainDynamicLoader.mjs","names":[],"sources":["../../../src/dictionaryManipulator/plainDynamicLoader.ts"],"sourcesContent":["import { internationalization } from '@intlayer/config/built';\nimport type { Dictionary } from '@intlayer/types/dictionary';\nimport type { LocalesValues } from '@intlayer/types/module_augmentation';\nimport { PRELOADED_DYNAMIC_KEY } from './preloadedDynamicLoader';\nimport { QUALIFIER_DYNAMIC_TYPES_KEY } from './qualifiedDynamicLoader';\n\n/**\n * Default export shape of a generated dynamic entry point for a plain (non\n * qualified) key: one lazy chunk loader per emitted locale.\n */\nexport type PlainDynamicLoaderMap<T extends Dictionary = Dictionary> = {\n [locale: string]: (() => Promise<T>) | undefined;\n};\n\n/** A chunk loader together with the locale it was emitted for. */\nexport type ResolvedDynamicLoader<T extends Dictionary = Dictionary> = {\n /**\n * Locale the returned loader actually serves, which differs from the\n * requested one whenever the fallback chain was walked.\n */\n locale: LocalesValues;\n loader: () => Promise<T>;\n};\n\n/** Marker properties a loader map carries alongside its per-locale loaders. */\nconst MARKER_KEYS: string[] = [\n PRELOADED_DYNAMIC_KEY,\n QUALIFIER_DYNAMIC_TYPES_KEY,\n];\n\n/**\n * Ordered locale candidates for a chunk lookup, mirroring the static fallback\n * chain `getTranslation` applies: the requested locale, its base language, then\n * the default locale and its base language.\n */\nconst getLocaleCandidates = (locale: LocalesValues): string[] => {\n const candidates: string[] = [];\n\n const addCandidate = (candidate?: string) => {\n if (candidate && !candidates.includes(candidate))\n candidates.push(candidate);\n };\n\n addCandidate(locale);\n addCandidate(locale.split('-')[0]);\n addCandidate(internationalization.defaultLocale);\n addCandidate(internationalization.defaultLocale?.split('-')[0]);\n\n return candidates;\n};\n\n/**\n * Picks the chunk loader serving a locale out of a plain dynamic loader map.\n *\n * A dictionary is only emitted for the locales it declares, so a read for any\n * other locale — an undeclared one, or a partially translated dictionary under\n * `requiredLocales` — has no chunk of its own. Static mode answers such a read\n * with the default locale's content rather than nothing, and this walks the\n * same chain so dynamic mode stays interchangeable with it.\n *\n * @param loaderMap - Default export of a generated dynamic entry point.\n * @param locale - Locale the caller is about to render.\n * @returns The loader to invoke and the locale its chunk holds, or `undefined`\n * when the map holds no chunk for the locale nor for any fallback.\n */\nexport const findPlainDynamicLoader = <T extends Dictionary>(\n loaderMap: PlainDynamicLoaderMap<T>,\n locale: LocalesValues\n): ResolvedDynamicLoader<T> | undefined => {\n for (const candidate of getLocaleCandidates(locale)) {\n const loader = loaderMap[candidate];\n\n if (typeof loader === 'function') {\n return { locale: candidate as LocalesValues, loader };\n }\n }\n\n return undefined;\n};\n\n/** Lists the locales a loader map actually emitted a chunk for. */\nconst getEmittedLocales = (loaderMap: PlainDynamicLoaderMap): string[] =>\n Object.keys(loaderMap).filter(\n (loaderKey) =>\n !MARKER_KEYS.includes(loaderKey) &&\n typeof loaderMap[loaderKey] === 'function'\n );\n\n/**\n * {@link findPlainDynamicLoader}, for callers that cannot render without a\n * chunk and would otherwise fail on an `undefined` loader with an error naming\n * neither the dictionary nor the locale.\n *\n * @param loaderMap - Default export of a generated dynamic entry point.\n * @param key - Dictionary key, used to describe an unresolvable lookup.\n * @param locale - Locale the caller is about to render.\n * @returns The loader to invoke, and the locale its chunk holds.\n * @throws When neither the locale nor any of its fallbacks has a chunk, which\n * only happens on a malformed or empty entry point.\n */\nexport const resolvePlainDynamicLoader = <T extends Dictionary>(\n loaderMap: PlainDynamicLoaderMap<T>,\n key: string,\n locale: LocalesValues\n): ResolvedDynamicLoader<T> => {\n const resolved = findPlainDynamicLoader<T>(loaderMap, locale);\n\n if (resolved) return resolved;\n\n const emittedLocales = getEmittedLocales(loaderMap);\n\n throw new Error(\n `[intlayer] No dynamic chunk found for dictionary \"${key}\" and locale \"${locale}\". Emitted locales: ${\n emittedLocales.length > 0 ? emittedLocales.join(', ') : '(none)'\n }.`\n );\n};\n"],"mappings":";;;;;;AAyBA,MAAM,cAAwB,CAC5B,uBACA,2BACF;;;;;;AAOA,MAAM,uBAAuB,WAAoC;CAC/D,MAAM,aAAuB,CAAC;CAE9B,MAAM,gBAAgB,cAAuB;EAC3C,IAAI,aAAa,CAAC,WAAW,SAAS,SAAS,GAC7C,WAAW,KAAK,SAAS;CAC7B;CAEA,aAAa,MAAM;CACnB,aAAa,OAAO,MAAM,GAAG,CAAC,CAAC,EAAE;CACjC,aAAa,qBAAqB,aAAa;CAC/C,aAAa,qBAAqB,eAAe,MAAM,GAAG,CAAC,CAAC,EAAE;CAE9D,OAAO;AACT;;;;;;;;;;;;;;;AAgBA,MAAa,0BACX,WACA,WACyC;CACzC,KAAK,MAAM,aAAa,oBAAoB,MAAM,GAAG;EACnD,MAAM,SAAS,UAAU;EAEzB,IAAI,OAAO,WAAW,YACpB,OAAO;GAAE,QAAQ;GAA4B;EAAO;CAExD;AAGF;;AAGA,MAAM,qBAAqB,cACzB,OAAO,KAAK,SAAS,CAAC,CAAC,QACpB,cACC,CAAC,YAAY,SAAS,SAAS,KAC/B,OAAO,UAAU,eAAe,UACpC;;;;;;;;;;;;;AAcF,MAAa,6BACX,WACA,KACA,WAC6B;CAC7B,MAAM,WAAW,uBAA0B,WAAW,MAAM;CAE5D,IAAI,UAAU,OAAO;CAErB,MAAM,iBAAiB,kBAAkB,SAAS;CAElD,MAAM,IAAI,MACR,qDAAqD,IAAI,gBAAgB,OAAO,sBAC9E,eAAe,SAAS,IAAI,eAAe,KAAK,IAAI,IAAI,SACzD,EACH;AACF"}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { PRELOADED_DYNAMIC_KEY } from "@intlayer/config/defaultValues";
|
|
2
|
+
|
|
3
|
+
//#region src/dictionaryManipulator/preloadedDynamicLoader.ts
|
|
4
|
+
/**
|
|
5
|
+
* Reads the preloaded dictionary of a dynamic loader map, when one was resolved
|
|
6
|
+
* for the requested locale.
|
|
7
|
+
*
|
|
8
|
+
* Deliberately synchronous, and deliberately not routed through the suspender
|
|
9
|
+
* cache: a suspender only leaves `pending` inside a `.then` callback, so feeding
|
|
10
|
+
* it an already-resolved promise would still suspend for one microtask — long
|
|
11
|
+
* enough for a pending fallback to paint, which is the flash this whole
|
|
12
|
+
* mechanism exists to remove.
|
|
13
|
+
*
|
|
14
|
+
* @param loaderMap - Default export of a generated dynamic entry point.
|
|
15
|
+
* @param locale - Locale the caller is about to render.
|
|
16
|
+
* @returns The dictionary when it was preloaded for `locale`, else `undefined`.
|
|
17
|
+
*/
|
|
18
|
+
const getPreloadedDictionary = (loaderMap, locale) => {
|
|
19
|
+
if (typeof loaderMap !== "object" || loaderMap === null) return void 0;
|
|
20
|
+
const preloaded = loaderMap[PRELOADED_DYNAMIC_KEY];
|
|
21
|
+
if (!preloaded || preloaded.locale !== locale) return void 0;
|
|
22
|
+
return preloaded.dictionary;
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
//#endregion
|
|
26
|
+
export { PRELOADED_DYNAMIC_KEY, getPreloadedDictionary };
|
|
27
|
+
//# sourceMappingURL=preloadedDynamicLoader.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"preloadedDynamicLoader.mjs","names":[],"sources":["../../../src/dictionaryManipulator/preloadedDynamicLoader.ts"],"sourcesContent":["import { PRELOADED_DYNAMIC_KEY } from '@intlayer/config/defaultValues';\nimport type { Dictionary } from '@intlayer/types/dictionary';\nimport type { LocalesValues } from '@intlayer/types/module_augmentation';\n\n/**\n * Marker under which a generated dynamic entry point carries the dictionary it\n * preloaded while evaluating. Defined in `@intlayer/config` so the code\n * generator and the build plugins can read it without pulling the runtime in,\n * and re-exported here where the consumers of the loaded content live.\n */\nexport { PRELOADED_DYNAMIC_KEY };\n\n/**\n * The value attached under {@link PRELOADED_DYNAMIC_KEY}.\n *\n * `locale` is the locale the preamble resolved at module-evaluation time. It is\n * compared against the locale the read actually asks for, so a disagreement\n * (a client-side locale switch, or a resolution the provider overrode) falls\n * back to loading rather than serving content in the wrong language.\n */\nexport type PreloadedDynamicEntry = {\n locale: LocalesValues;\n dictionary: Dictionary;\n};\n\n/** A plain dynamic loader map that may carry a preloaded entry. */\nexport type PreloadableDynamicLoaderMap = {\n [PRELOADED_DYNAMIC_KEY]?: PreloadedDynamicEntry;\n};\n\n/**\n * Reads the preloaded dictionary of a dynamic loader map, when one was resolved\n * for the requested locale.\n *\n * Deliberately synchronous, and deliberately not routed through the suspender\n * cache: a suspender only leaves `pending` inside a `.then` callback, so feeding\n * it an already-resolved promise would still suspend for one microtask — long\n * enough for a pending fallback to paint, which is the flash this whole\n * mechanism exists to remove.\n *\n * @param loaderMap - Default export of a generated dynamic entry point.\n * @param locale - Locale the caller is about to render.\n * @returns The dictionary when it was preloaded for `locale`, else `undefined`.\n */\nexport const getPreloadedDictionary = (\n loaderMap: unknown,\n locale: LocalesValues\n): Dictionary | undefined => {\n if (typeof loaderMap !== 'object' || loaderMap === null) return undefined;\n\n const preloaded = (loaderMap as PreloadableDynamicLoaderMap)[\n PRELOADED_DYNAMIC_KEY\n ];\n\n if (!preloaded || preloaded.locale !== locale) return undefined;\n\n return preloaded.dictionary;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;AA4CA,MAAa,0BACX,WACA,WAC2B;CAC3B,IAAI,OAAO,cAAc,YAAY,cAAc,MAAM,OAAO;CAEhE,MAAM,YAAa,UACjB;CAGF,IAAI,CAAC,aAAa,UAAU,WAAW,QAAQ,OAAO;CAEtD,OAAO,UAAU;AACnB"}
|
|
@@ -1,18 +1,12 @@
|
|
|
1
1
|
import { COMPOSITE_ID_SEPARATOR, resolveEffectiveVariantId, serializeVariantChain } from "./qualifiedDictionary.mjs";
|
|
2
|
+
import { QUALIFIER_DYNAMIC_TYPES_KEY } from "@intlayer/config/defaultValues";
|
|
2
3
|
|
|
3
4
|
//#region src/dictionaryManipulator/qualifiedDynamicLoader.ts
|
|
4
5
|
/**
|
|
5
|
-
* Marker property carrying the ordered qualifier dimensions on a dynamic loader
|
|
6
|
-
* map. Its presence distinguishes a qualified group loader map (a nested tree
|
|
7
|
-
* of chunks) from a plain dynamic loader map (one chunk per `locale`). Prefixed
|
|
8
|
-
* and unlikely to collide with a real locale code.
|
|
9
|
-
*/
|
|
10
|
-
const QUALIFIER_DYNAMIC_TYPES_KEY = "__intlayerQualifierTypes";
|
|
11
|
-
/**
|
|
12
6
|
* Type guard discriminating a qualified dynamic loader map (collections /
|
|
13
7
|
* variants, possibly combined) from a plain dynamic loader map.
|
|
14
8
|
*/
|
|
15
|
-
const isQualifiedDynamicLoaderMap = (value) => typeof value === "object" && value !== null &&
|
|
9
|
+
const isQualifiedDynamicLoaderMap = (value) => typeof value === "object" && value !== null && QUALIFIER_DYNAMIC_TYPES_KEY in value;
|
|
16
10
|
/**
|
|
17
11
|
* Walks the loader tree following the selector and collects the chunk loaders
|
|
18
12
|
* it targets — shared by the sync ({@link resolveQualifiedDynamicContent}) and
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"qualifiedDynamicLoader.mjs","names":[],"sources":["../../../src/dictionaryManipulator/qualifiedDynamicLoader.ts"],"sourcesContent":["import type {\n Dictionary,\n DictionaryQualifierType,\n DictionarySelector,\n} from '@intlayer/types/dictionary';\nimport {\n COMPOSITE_ID_SEPARATOR,\n resolveEffectiveVariantId,\n serializeVariantChain,\n} from './qualifiedDictionary';\n\n/**\n * Marker property carrying the ordered qualifier dimensions on a dynamic loader\n * map. Its presence distinguishes a qualified group loader map (a nested tree\n * of chunks) from a plain dynamic loader map (one chunk per `locale`). Prefixed\n * and unlikely to collide with a real locale code.\n */\nexport const QUALIFIER_DYNAMIC_TYPES_KEY = '__intlayerQualifierTypes';\n\n/**\n * A lazily-imported per-locale dictionary chunk loader.\n */\nexport type DynamicDictionaryLoader = () => Promise<Dictionary>;\n\n/**\n * Nested tree of chunk loaders: one nesting level per declared dimension (in\n * canonical order), leaves are loaders.\n */\nexport type QualifiedDynamicLoaderTree = {\n [segment: string]: QualifiedDynamicLoaderTree | DynamicDictionaryLoader;\n};\n\n/**\n * Default export shape of a generated dynamic entry point for a qualified key.\n * One nesting level per dimension under each locale, plus the dimension marker.\n *\n * ```ts\n * {\n * __intlayerQualifierTypes: ['variant', 'item'],\n * en: { promo: { '1': () => import('./json/x/promo/1/en.json'), … }, … },\n * fr: { … },\n * }\n * ```\n */\nexport type QualifiedDynamicLoaderMap = {\n [QUALIFIER_DYNAMIC_TYPES_KEY]: DictionaryQualifierType[];\n [locale: string]: QualifiedDynamicLoaderTree | DictionaryQualifierType[];\n};\n\n/**\n * Type guard discriminating a qualified dynamic loader map (collections /\n * variants, possibly combined) from a plain dynamic loader map.\n */\nexport const isQualifiedDynamicLoaderMap = (\n value: unknown\n): value is QualifiedDynamicLoaderMap =>\n typeof value === 'object' &&\n value !== null &&\n QUALIFIER_DYNAMIC_TYPES_KEY in value;\n\n/** One targeted chunk: its stable cache key and lazy loader. */\ntype CollectedChunk = {\n cacheKey: string;\n loader: DynamicDictionaryLoader;\n};\n\ntype CollectedChunks = {\n /** True when the `item` axis is open (collection result → array). */\n itemAxisOpen: boolean;\n /** True when a required coordinate is absent (result → [] or null). */\n missed: boolean;\n /** The chunks the selector targets (in collection order for the item axis). */\n chunks: CollectedChunk[];\n};\n\n/**\n * Walks the loader tree following the selector and collects the chunk loaders\n * it targets — shared by the sync ({@link resolveQualifiedDynamicContent}) and\n * async ({@link resolveQualifiedDynamicContentAsync}) resolvers.\n */\nconst collectQualifiedChunks = (\n loaderMap: QualifiedDynamicLoaderMap,\n key: string,\n locale: string,\n selector: DictionarySelector | undefined\n): CollectedChunks => {\n const qualifierTypes = loaderMap[QUALIFIER_DYNAMIC_TYPES_KEY];\n const localeTree = loaderMap[locale] as\n | QualifiedDynamicLoaderTree\n | undefined;\n\n const itemAxisOpen =\n qualifierTypes.includes('item') && selector?.item === undefined;\n\n if (!localeTree) return { itemAxisOpen, missed: true, chunks: [] };\n\n const chunks: CollectedChunk[] = [];\n\n const walk = (\n node: QualifiedDynamicLoaderTree | DynamicDictionaryLoader,\n dimensions: DictionaryQualifierType[],\n segments: string[]\n ): boolean => {\n if (dimensions.length === 0) {\n chunks.push({\n cacheKey: `${key}.${locale}.${segments.join(COMPOSITE_ID_SEPARATOR)}`,\n loader: node as DynamicDictionaryLoader,\n });\n return true;\n }\n\n const [dimension, ...rest] = dimensions;\n const tree = node as QualifiedDynamicLoaderTree;\n\n if (dimension === 'item' && selector?.item === undefined) {\n // Open collection axis: fan out into every sibling chunk, ordered.\n for (const segment of Object.keys(tree).sort(\n (left, right) => Number(left) - Number(right)\n )) {\n walk(tree[segment]!, rest, [...segments, segment]);\n }\n return true;\n }\n\n // A variant with no chunk of its own falls back to the `default` chunk, so\n // only the entries that actually differ need to be emitted.\n const segment =\n dimension === 'variant'\n ? resolveEffectiveVariantId(\n serializeVariantChain(selector?.variant),\n (variantId) => tree[variantId] !== undefined\n )\n : String(selector?.item);\n\n const child = tree[segment];\n if (!child) return false;\n\n return walk(child, rest, [...segments, segment]);\n };\n\n const found = walk(localeTree, qualifierTypes, []);\n\n return { itemAxisOpen, missed: !found, chunks };\n};\n\n/**\n * Resolves the content of a qualified dynamic loader map against a selector,\n * loading only the chunk(s) the selector actually targets.\n *\n * Walks the nested loader tree one dimension at a time (canonical order\n * `variant → item`): `variant` descends by the serialized id, falling back to\n * `default` when the selected variant has no chunk of its own, and `item`\n * either narrows to the selected index or — when no item is given — expands\n * into every sibling chunk (the collection axis). Semantics mirror\n * `resolveQualifiedDictionary` so dynamic and static modes behave alike.\n *\n * The Suspense mechanism is injected through `loadChunk` so the same logic\n * serves both the client (suspender cache) and the server (`react.use`). Every\n * targeted loader is started before the first chunk is read, so sibling chunks\n * load in parallel rather than waterfalling.\n *\n * @param loaderMap - The qualified dynamic loader map (entry point default export).\n * @param key - The dictionary key (used to build stable chunk cache keys).\n * @param locale - The resolved locale to load chunks for.\n * @param selector - The selector splitting the qualifier dimensions.\n * @param loadChunk - Reads a started chunk promise, suspending until it resolves.\n * @param transform - Turns a resolved chunk dictionary into final content.\n */\nexport const resolveQualifiedDynamicContent = <Content>(params: {\n loaderMap: QualifiedDynamicLoaderMap;\n key: string;\n locale: string;\n selector: DictionarySelector | undefined;\n loadChunk: (cacheKey: string, promise: Promise<Dictionary>) => Dictionary;\n transform: (dictionary: Dictionary) => Content;\n}): Content | Content[] | null => {\n const { loaderMap, key, locale, selector, loadChunk, transform } = params;\n\n const { itemAxisOpen, missed, chunks } = collectQualifiedChunks(\n loaderMap,\n key,\n locale,\n selector\n );\n\n if (missed) return itemAxisOpen ? [] : null;\n\n // Start every loader before reading, so siblings load in parallel.\n const dictionaries = chunks.map(({ cacheKey, loader }) =>\n loadChunk(cacheKey, loader())\n );\n\n if (itemAxisOpen) return dictionaries.map(transform);\n\n const [dictionary] = dictionaries;\n return dictionary ? transform(dictionary) : null;\n};\n\n/**\n * Async counterpart of {@link resolveQualifiedDynamicContent} for frameworks\n * that load dictionaries with `await` instead of Suspense (Vue, Svelte, Lit,\n * vanilla). Awaits every targeted chunk in parallel, then resolves identically.\n *\n * @param loaderMap - The qualified dynamic loader map.\n * @param key - The dictionary key (used to build stable chunk cache keys).\n * @param locale - The resolved locale to load chunks for.\n * @param selector - The selector splitting the qualifier dimensions.\n * @param transform - Turns a resolved chunk dictionary into final content.\n */\nexport const resolveQualifiedDynamicContentAsync = async <Content>(params: {\n loaderMap: QualifiedDynamicLoaderMap;\n key: string;\n locale: string;\n selector: DictionarySelector | undefined;\n transform: (dictionary: Dictionary) => Content;\n}): Promise<Content | Content[] | null> => {\n const { loaderMap, key, locale, selector, transform } = params;\n\n const { itemAxisOpen, missed, chunks } = collectQualifiedChunks(\n loaderMap,\n key,\n locale,\n selector\n );\n\n if (missed) return itemAxisOpen ? [] : null;\n\n const dictionaries = await Promise.all(chunks.map(({ loader }) => loader()));\n\n if (itemAxisOpen) return dictionaries.map(transform);\n\n const [dictionary] = dictionaries;\n return dictionary ? transform(dictionary) : null;\n};\n"],"mappings":";;;;;;;;;AAiBA,MAAa,8BAA8B;;;;;AAoC3C,MAAa,+BACX,UAEA,OAAO,UAAU,YACjB,UAAU,sCACqB;;;;;;AAsBjC,MAAM,0BACJ,WACA,KACA,QACA,aACoB;CACpB,MAAM,iBAAiB,UAAU;CACjC,MAAM,aAAa,UAAU;CAI7B,MAAM,eACJ,eAAe,SAAS,MAAM,KAAK,UAAU,SAAS;CAExD,IAAI,CAAC,YAAY,OAAO;EAAE;EAAc,QAAQ;EAAM,QAAQ,CAAC;CAAE;CAEjE,MAAM,SAA2B,CAAC;CAElC,MAAM,QACJ,MACA,YACA,aACY;EACZ,IAAI,WAAW,WAAW,GAAG;GAC3B,OAAO,KAAK;IACV,UAAU,GAAG,IAAI,GAAG,OAAO,GAAG,SAAS,QAA2B;IAClE,QAAQ;GACV,CAAC;GACD,OAAO;EACT;EAEA,MAAM,CAAC,WAAW,GAAG,QAAQ;EAC7B,MAAM,OAAO;EAEb,IAAI,cAAc,UAAU,UAAU,SAAS,QAAW;GAExD,KAAK,MAAM,WAAW,OAAO,KAAK,IAAI,CAAC,CAAC,MACrC,MAAM,UAAU,OAAO,IAAI,IAAI,OAAO,KAAK,CAC9C,GACE,KAAK,KAAK,UAAW,MAAM,CAAC,GAAG,UAAU,OAAO,CAAC;GAEnD,OAAO;EACT;EAIA,MAAM,UACJ,cAAc,YACV,0BACE,sBAAsB,UAAU,OAAO,IACtC,cAAc,KAAK,eAAe,MACrC,IACA,OAAO,UAAU,IAAI;EAE3B,MAAM,QAAQ,KAAK;EACnB,IAAI,CAAC,OAAO,OAAO;EAEnB,OAAO,KAAK,OAAO,MAAM,CAAC,GAAG,UAAU,OAAO,CAAC;CACjD;CAIA,OAAO;EAAE;EAAc,QAAQ,CAFjB,KAAK,YAAY,gBAAgB,CAAC,CAEZ;EAAG;CAAO;AAChD;;;;;;;;;;;;;;;;;;;;;;;;AAyBA,MAAa,kCAA2C,WAOtB;CAChC,MAAM,EAAE,WAAW,KAAK,QAAQ,UAAU,WAAW,cAAc;CAEnE,MAAM,EAAE,cAAc,QAAQ,WAAW,uBACvC,WACA,KACA,QACA,QACF;CAEA,IAAI,QAAQ,OAAO,eAAe,CAAC,IAAI;CAGvC,MAAM,eAAe,OAAO,KAAK,EAAE,UAAU,aAC3C,UAAU,UAAU,OAAO,CAAC,CAC9B;CAEA,IAAI,cAAc,OAAO,aAAa,IAAI,SAAS;CAEnD,MAAM,CAAC,cAAc;CACrB,OAAO,aAAa,UAAU,UAAU,IAAI;AAC9C;;;;;;;;;;;;AAaA,MAAa,sCAAsC,OAAgB,WAMxB;CACzC,MAAM,EAAE,WAAW,KAAK,QAAQ,UAAU,cAAc;CAExD,MAAM,EAAE,cAAc,QAAQ,WAAW,uBACvC,WACA,KACA,QACA,QACF;CAEA,IAAI,QAAQ,OAAO,eAAe,CAAC,IAAI;CAEvC,MAAM,eAAe,MAAM,QAAQ,IAAI,OAAO,KAAK,EAAE,aAAa,OAAO,CAAC,CAAC;CAE3E,IAAI,cAAc,OAAO,aAAa,IAAI,SAAS;CAEnD,MAAM,CAAC,cAAc;CACrB,OAAO,aAAa,UAAU,UAAU,IAAI;AAC9C"}
|
|
1
|
+
{"version":3,"file":"qualifiedDynamicLoader.mjs","names":[],"sources":["../../../src/dictionaryManipulator/qualifiedDynamicLoader.ts"],"sourcesContent":["import { QUALIFIER_DYNAMIC_TYPES_KEY } from '@intlayer/config/defaultValues';\nimport type {\n Dictionary,\n DictionaryQualifierType,\n DictionarySelector,\n} from '@intlayer/types/dictionary';\nimport {\n COMPOSITE_ID_SEPARATOR,\n resolveEffectiveVariantId,\n serializeVariantChain,\n} from './qualifiedDictionary';\n\n/**\n * Marker property carrying the ordered qualifier dimensions on a dynamic loader\n * map. Defined in `@intlayer/config` so the code generator and the build\n * plugins can read it without pulling the runtime in, and re-exported here\n * where its consumers live.\n */\nexport { QUALIFIER_DYNAMIC_TYPES_KEY };\n\n/**\n * A lazily-imported per-locale dictionary chunk loader.\n */\nexport type DynamicDictionaryLoader = () => Promise<Dictionary>;\n\n/**\n * Nested tree of chunk loaders: one nesting level per declared dimension (in\n * canonical order), leaves are loaders.\n */\nexport type QualifiedDynamicLoaderTree = {\n [segment: string]: QualifiedDynamicLoaderTree | DynamicDictionaryLoader;\n};\n\n/**\n * Default export shape of a generated dynamic entry point for a qualified key.\n * One nesting level per dimension under each locale, plus the dimension marker.\n *\n * ```ts\n * {\n * __intlayerQualifierTypes: ['variant', 'item'],\n * en: { promo: { '1': () => import('./json/x/promo/1/en.json'), … }, … },\n * fr: { … },\n * }\n * ```\n */\nexport type QualifiedDynamicLoaderMap = {\n [QUALIFIER_DYNAMIC_TYPES_KEY]: DictionaryQualifierType[];\n [locale: string]: QualifiedDynamicLoaderTree | DictionaryQualifierType[];\n};\n\n/**\n * Type guard discriminating a qualified dynamic loader map (collections /\n * variants, possibly combined) from a plain dynamic loader map.\n */\nexport const isQualifiedDynamicLoaderMap = (\n value: unknown\n): value is QualifiedDynamicLoaderMap =>\n typeof value === 'object' &&\n value !== null &&\n QUALIFIER_DYNAMIC_TYPES_KEY in value;\n\n/** One targeted chunk: its stable cache key and lazy loader. */\ntype CollectedChunk = {\n cacheKey: string;\n loader: DynamicDictionaryLoader;\n};\n\ntype CollectedChunks = {\n /** True when the `item` axis is open (collection result → array). */\n itemAxisOpen: boolean;\n /** True when a required coordinate is absent (result → [] or null). */\n missed: boolean;\n /** The chunks the selector targets (in collection order for the item axis). */\n chunks: CollectedChunk[];\n};\n\n/**\n * Walks the loader tree following the selector and collects the chunk loaders\n * it targets — shared by the sync ({@link resolveQualifiedDynamicContent}) and\n * async ({@link resolveQualifiedDynamicContentAsync}) resolvers.\n */\nconst collectQualifiedChunks = (\n loaderMap: QualifiedDynamicLoaderMap,\n key: string,\n locale: string,\n selector: DictionarySelector | undefined\n): CollectedChunks => {\n const qualifierTypes = loaderMap[QUALIFIER_DYNAMIC_TYPES_KEY];\n const localeTree = loaderMap[locale] as\n | QualifiedDynamicLoaderTree\n | undefined;\n\n const itemAxisOpen =\n qualifierTypes.includes('item') && selector?.item === undefined;\n\n if (!localeTree) return { itemAxisOpen, missed: true, chunks: [] };\n\n const chunks: CollectedChunk[] = [];\n\n const walk = (\n node: QualifiedDynamicLoaderTree | DynamicDictionaryLoader,\n dimensions: DictionaryQualifierType[],\n segments: string[]\n ): boolean => {\n if (dimensions.length === 0) {\n chunks.push({\n cacheKey: `${key}.${locale}.${segments.join(COMPOSITE_ID_SEPARATOR)}`,\n loader: node as DynamicDictionaryLoader,\n });\n return true;\n }\n\n const [dimension, ...rest] = dimensions;\n const tree = node as QualifiedDynamicLoaderTree;\n\n if (dimension === 'item' && selector?.item === undefined) {\n // Open collection axis: fan out into every sibling chunk, ordered.\n for (const segment of Object.keys(tree).sort(\n (left, right) => Number(left) - Number(right)\n )) {\n walk(tree[segment]!, rest, [...segments, segment]);\n }\n return true;\n }\n\n // A variant with no chunk of its own falls back to the `default` chunk, so\n // only the entries that actually differ need to be emitted.\n const segment =\n dimension === 'variant'\n ? resolveEffectiveVariantId(\n serializeVariantChain(selector?.variant),\n (variantId) => tree[variantId] !== undefined\n )\n : String(selector?.item);\n\n const child = tree[segment];\n if (!child) return false;\n\n return walk(child, rest, [...segments, segment]);\n };\n\n const found = walk(localeTree, qualifierTypes, []);\n\n return { itemAxisOpen, missed: !found, chunks };\n};\n\n/**\n * Resolves the content of a qualified dynamic loader map against a selector,\n * loading only the chunk(s) the selector actually targets.\n *\n * Walks the nested loader tree one dimension at a time (canonical order\n * `variant → item`): `variant` descends by the serialized id, falling back to\n * `default` when the selected variant has no chunk of its own, and `item`\n * either narrows to the selected index or — when no item is given — expands\n * into every sibling chunk (the collection axis). Semantics mirror\n * `resolveQualifiedDictionary` so dynamic and static modes behave alike.\n *\n * The Suspense mechanism is injected through `loadChunk` so the same logic\n * serves both the client (suspender cache) and the server (`react.use`). Every\n * targeted loader is started before the first chunk is read, so sibling chunks\n * load in parallel rather than waterfalling.\n *\n * @param loaderMap - The qualified dynamic loader map (entry point default export).\n * @param key - The dictionary key (used to build stable chunk cache keys).\n * @param locale - The resolved locale to load chunks for.\n * @param selector - The selector splitting the qualifier dimensions.\n * @param loadChunk - Reads a started chunk promise, suspending until it resolves.\n * @param transform - Turns a resolved chunk dictionary into final content.\n */\nexport const resolveQualifiedDynamicContent = <Content>(params: {\n loaderMap: QualifiedDynamicLoaderMap;\n key: string;\n locale: string;\n selector: DictionarySelector | undefined;\n loadChunk: (cacheKey: string, promise: Promise<Dictionary>) => Dictionary;\n transform: (dictionary: Dictionary) => Content;\n}): Content | Content[] | null => {\n const { loaderMap, key, locale, selector, loadChunk, transform } = params;\n\n const { itemAxisOpen, missed, chunks } = collectQualifiedChunks(\n loaderMap,\n key,\n locale,\n selector\n );\n\n if (missed) return itemAxisOpen ? [] : null;\n\n // Start every loader before reading, so siblings load in parallel.\n const dictionaries = chunks.map(({ cacheKey, loader }) =>\n loadChunk(cacheKey, loader())\n );\n\n if (itemAxisOpen) return dictionaries.map(transform);\n\n const [dictionary] = dictionaries;\n return dictionary ? transform(dictionary) : null;\n};\n\n/**\n * Async counterpart of {@link resolveQualifiedDynamicContent} for frameworks\n * that load dictionaries with `await` instead of Suspense (Vue, Svelte, Lit,\n * vanilla). Awaits every targeted chunk in parallel, then resolves identically.\n *\n * @param loaderMap - The qualified dynamic loader map.\n * @param key - The dictionary key (used to build stable chunk cache keys).\n * @param locale - The resolved locale to load chunks for.\n * @param selector - The selector splitting the qualifier dimensions.\n * @param transform - Turns a resolved chunk dictionary into final content.\n */\nexport const resolveQualifiedDynamicContentAsync = async <Content>(params: {\n loaderMap: QualifiedDynamicLoaderMap;\n key: string;\n locale: string;\n selector: DictionarySelector | undefined;\n transform: (dictionary: Dictionary) => Content;\n}): Promise<Content | Content[] | null> => {\n const { loaderMap, key, locale, selector, transform } = params;\n\n const { itemAxisOpen, missed, chunks } = collectQualifiedChunks(\n loaderMap,\n key,\n locale,\n selector\n );\n\n if (missed) return itemAxisOpen ? [] : null;\n\n const dictionaries = await Promise.all(chunks.map(({ loader }) => loader()));\n\n if (itemAxisOpen) return dictionaries.map(transform);\n\n const [dictionary] = dictionaries;\n return dictionary ? transform(dictionary) : null;\n};\n"],"mappings":";;;;;;;;AAsDA,MAAa,+BACX,UAEA,OAAO,UAAU,YACjB,UAAU,QACV,+BAA+B;;;;;;AAsBjC,MAAM,0BACJ,WACA,KACA,QACA,aACoB;CACpB,MAAM,iBAAiB,UAAU;CACjC,MAAM,aAAa,UAAU;CAI7B,MAAM,eACJ,eAAe,SAAS,MAAM,KAAK,UAAU,SAAS;CAExD,IAAI,CAAC,YAAY,OAAO;EAAE;EAAc,QAAQ;EAAM,QAAQ,CAAC;CAAE;CAEjE,MAAM,SAA2B,CAAC;CAElC,MAAM,QACJ,MACA,YACA,aACY;EACZ,IAAI,WAAW,WAAW,GAAG;GAC3B,OAAO,KAAK;IACV,UAAU,GAAG,IAAI,GAAG,OAAO,GAAG,SAAS,QAA2B;IAClE,QAAQ;GACV,CAAC;GACD,OAAO;EACT;EAEA,MAAM,CAAC,WAAW,GAAG,QAAQ;EAC7B,MAAM,OAAO;EAEb,IAAI,cAAc,UAAU,UAAU,SAAS,QAAW;GAExD,KAAK,MAAM,WAAW,OAAO,KAAK,IAAI,CAAC,CAAC,MACrC,MAAM,UAAU,OAAO,IAAI,IAAI,OAAO,KAAK,CAC9C,GACE,KAAK,KAAK,UAAW,MAAM,CAAC,GAAG,UAAU,OAAO,CAAC;GAEnD,OAAO;EACT;EAIA,MAAM,UACJ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{ mergeQualifiedDictionaries } from "./dictionaryManipulator/mergeQualifiedDictionaries.mjs";
|
|
65
65
|
import { orderDictionaries } from "./dictionaryManipulator/orderDictionaries.mjs";
|
|
66
66
|
import { normalizeDictionaries, normalizeDictionary } from "./dictionaryManipulator/normalizeDictionary.mjs";
|
|
67
|
+
import { PRELOADED_DYNAMIC_KEY, getPreloadedDictionary } from "./dictionaryManipulator/preloadedDynamicLoader.mjs";
|
|
67
68
|
import { QUALIFIER_DYNAMIC_TYPES_KEY, isQualifiedDynamicLoaderMap, resolveQualifiedDynamicContent, resolveQualifiedDynamicContentAsync } from "./dictionaryManipulator/qualifiedDynamicLoader.mjs";
|
|
68
69
|
import { removeContentNodeByKeyPath } from "./dictionaryManipulator/removeContentNodeByKeyPath.mjs";
|
|
69
70
|
import { renameContentNodeByKeyPath } from "./dictionaryManipulator/renameContentNodeByKeyPath.mjs";
|
|
@@ -72,8 +73,9 @@ import { checkIsURLAbsolute } from "./utils/checkIsURLAbsolute.mjs";
|
|
|
72
73
|
import { getPathWithoutLocale } from "./localization/getPathWithoutLocale.mjs";
|
|
73
74
|
import { comparePaths, normalizePath } from "./localization/comparePaths.mjs";
|
|
74
75
|
import { getDomainHostname, getDomainOrigin, getLocaleFromDomain, isLocaleExclusiveOnDomain } from "./localization/domainUtils.mjs";
|
|
75
|
-
import { getPrefix } from "./localization/getPrefix.mjs";
|
|
76
|
-
import { getCanonicalPath, getInternalPath,
|
|
76
|
+
import { getPrefix, isDeclaredLocale } from "./localization/getPrefix.mjs";
|
|
77
|
+
import { getCanonicalPath, getInternalPath, getRewritePath, getRewriteRules, resolveLocalizedPath } from "./localization/rewriteUtils.mjs";
|
|
78
|
+
import { getLocalizedPath } from "./localization/getLocalizedPath.mjs";
|
|
77
79
|
import { getLocalizedUrl } from "./localization/getLocalizedUrl.mjs";
|
|
78
80
|
import { getMultilingualUrls } from "./localization/getMultilingualUrls.mjs";
|
|
79
81
|
import { generateSitemap, generateSitemapUrl } from "./localization/generateSitemap.mjs";
|
|
@@ -89,8 +91,9 @@ import { getLocaleLang } from "./localization/getLocaleLang.mjs";
|
|
|
89
91
|
import { getLocaleName } from "./localization/getLocaleName.mjs";
|
|
90
92
|
import { localeFlatMap, localeMap, localeRecord } from "./localization/localeMapper.mjs";
|
|
91
93
|
import { formatProxyEnabledMessage, isProxyStorageLocaleEnabled, resolveProxyMode } from "./localization/proxyMode.mjs";
|
|
94
|
+
import { getPreloadLocale, resolveBrowserLocale } from "./localization/resolveBrowserLocale.mjs";
|
|
92
95
|
import { validatePrefix } from "./localization/validatePrefix.mjs";
|
|
93
|
-
import { ATTRIBUTES_TO_SANITIZE, ATTRIBUTE_TO_NODE_PROP_MAP, ATTR_EXTRACTOR_R, BLOCKQUOTE_ALERT_R, BLOCKQUOTE_R, BLOCKQUOTE_TRIM_LEFT_MULTILINE_R, BLOCK_END_R, BREAK_LINE_R, BREAK_THEMATIC_R, CAPTURE_LETTER_AFTER_HYPHEN, CODE_BLOCK_FENCED_R, CODE_BLOCK_R, CODE_INLINE_R, CONSECUTIVE_NEWLINE_R, CR_NEWLINE_R, CUSTOM_COMPONENT_R, DO_NOT_PROCESS_HTML_ELEMENTS, DURATION_DELAY_TRIGGER, FOOTNOTE_R, FOOTNOTE_REFERENCE_R, FORMFEED_R, FRONT_MATTER_R, GFM_TASK_R, HEADING_ATX_COMPLIANT_R, HEADING_R, HEADING_SETEXT_R, HTML_BLOCK_ELEMENT_R, HTML_CHAR_CODE_R, HTML_COMMENT_R, HTML_CUSTOM_ATTR_R, HTML_LEFT_TRIM_AMOUNT_R, HTML_SELF_CLOSING_ELEMENT_R, INLINE_SKIP_R, INTERPOLATION_R, LINK_AUTOLINK_BARE_URL_R, LINK_AUTOLINK_R, LIST_LOOKBEHIND_R, LOOKAHEAD, NAMED_CODES_TO_UNICODE, NP_TABLE_R, ORDERED, ORDERED_LIST_BULLET, ORDERED_LIST_ITEM_PREFIX, ORDERED_LIST_ITEM_PREFIX_R, ORDERED_LIST_ITEM_R, ORDERED_LIST_R, PARAGRAPH_R, Priority, REFERENCE_IMAGE_OR_LINK, REFERENCE_IMAGE_R, REFERENCE_LINK_R, RuleType, SHORTCODE_R, SHOULD_RENDER_AS_BLOCK_R, TABLE_CENTER_ALIGN, TABLE_LEFT_ALIGN, TABLE_RIGHT_ALIGN, TABLE_TRIM_PIPES, TAB_R, TEXT_BOLD_R, TEXT_EMPHASIZED_R, TEXT_ESCAPED_R, TEXT_MARKED_R, TEXT_PLAIN_R, TEXT_STRIKETHROUGHED_R, TRIM_STARTING_NEWLINES, UNESCAPE_R, UNORDERED, UNORDERED_LIST_BULLET, UNORDERED_LIST_ITEM_PREFIX, UNORDERED_LIST_ITEM_PREFIX_R, UNORDERED_LIST_ITEM_R, UNORDERED_LIST_R, generateListItemPrefix, generateListItemPrefixRegex, generateListItemRegex, generateListRegex } from "./markdown/constants.mjs";
|
|
96
|
+
import { ATTRIBUTES_TO_SANITIZE, ATTRIBUTE_TO_NODE_PROP_MAP, ATTR_EXTRACTOR_R, BLOCKQUOTE_ALERT_R, BLOCKQUOTE_R, BLOCKQUOTE_TRIM_LEFT_MULTILINE_R, BLOCK_END_R, BREAK_LINE_R, BREAK_THEMATIC_R, CAPTURE_LETTER_AFTER_HYPHEN, CODE_BLOCK_FENCED_R, CODE_BLOCK_R, CODE_INLINE_R, CONSECUTIVE_NEWLINE_R, CR_NEWLINE_R, CUSTOM_COMPONENT_R, DO_NOT_PROCESS_HTML_ELEMENTS, DURATION_DELAY_TRIGGER, FENCE_DELIMITER_R, FOOTNOTE_R, FOOTNOTE_REFERENCE_R, FORMFEED_R, FRONT_MATTER_R, GFM_TASK_R, HEADING_ATX_COMPLIANT_R, HEADING_R, HEADING_SETEXT_R, HTML_BLOCK_ELEMENT_R, HTML_CHAR_CODE_R, HTML_COMMENT_R, HTML_CUSTOM_ATTR_R, HTML_LEFT_TRIM_AMOUNT_R, HTML_SELF_CLOSING_ELEMENT_R, INLINE_SKIP_R, INTERPOLATION_R, LINK_AUTOLINK_BARE_URL_R, LINK_AUTOLINK_R, LIST_LOOKBEHIND_R, LOOKAHEAD, NAMED_CODES_TO_UNICODE, NP_TABLE_R, ORDERED, ORDERED_LIST_BULLET, ORDERED_LIST_ITEM_PREFIX, ORDERED_LIST_ITEM_PREFIX_R, ORDERED_LIST_ITEM_R, ORDERED_LIST_R, PARAGRAPH_R, Priority, REFERENCE_IMAGE_OR_LINK, REFERENCE_IMAGE_R, REFERENCE_LINK_R, RuleType, SHORTCODE_R, SHOULD_RENDER_AS_BLOCK_R, TABLE_CENTER_ALIGN, TABLE_LEFT_ALIGN, TABLE_RIGHT_ALIGN, TABLE_TRIM_PIPES, TAB_R, TEXT_BOLD_R, TEXT_EMPHASIZED_R, TEXT_ESCAPED_R, TEXT_MARKED_R, TEXT_PLAIN_R, TEXT_STRIKETHROUGHED_R, TRIM_STARTING_NEWLINES, UNESCAPE_R, UNORDERED, UNORDERED_LIST_BULLET, UNORDERED_LIST_ITEM_PREFIX, UNORDERED_LIST_ITEM_PREFIX_R, UNORDERED_LIST_ITEM_R, UNORDERED_LIST_R, generateListItemPrefix, generateListItemPrefixRegex, generateListItemRegex, generateListRegex } from "./markdown/constants.mjs";
|
|
94
97
|
import { allowInline, anyScopeRegex, attributeValueToNodePropValue, blockRegex, captureNothing, cx, get, inlineRegex, normalizeAttributeKey, normalizeWhitespace, parseBlock, parseCaptureInline, parseInline, parseSimpleInline, parseStyleAttribute, parseTableAlign, parseTableAlignCapture, parseTableCells, parseTableRow, qualifies, renderNothing, sanitizer, simpleInlineRegex, slugify, some, startsWith, trimEnd, trimLeadingWhitespaceOutsideFences, unescapeString, unquote } from "./markdown/utils.mjs";
|
|
95
98
|
import { parserFor } from "./markdown/parser.mjs";
|
|
96
99
|
import { createRenderer, renderFor } from "./markdown/renderer.mjs";
|
|
@@ -104,4 +107,4 @@ import { interpolateMessage, parseTaggedMessage, resolveMessage, resolveMessageN
|
|
|
104
107
|
import { isSameKeyPath } from "./utils/isSameKeyPath.mjs";
|
|
105
108
|
import { stringifyYaml } from "./utils/stringifyYaml.mjs";
|
|
106
109
|
|
|
107
|
-
export { ATTRIBUTES_TO_SANITIZE, ATTRIBUTE_TO_NODE_PROP_MAP, ATTR_EXTRACTOR_R, BLOCKQUOTE_ALERT_R, BLOCKQUOTE_R, BLOCKQUOTE_TRIM_LEFT_MULTILINE_R, BLOCK_END_R, BREAK_LINE_R, BREAK_THEMATIC_R, CAPTURE_LETTER_AFTER_HYPHEN, CODE_BLOCK_FENCED_R, CODE_BLOCK_R, CODE_INLINE_R, COMPOSITE_ID_SEPARATOR, CONSECUTIVE_NEWLINE_R, CR_NEWLINE_R, CUSTOM_COMPONENT_R, CachedIntl, CachedIntl as Intl, DEFAULT_VARIANT_ID, DO_NOT_PROCESS_HTML_ELEMENTS, DURATION_DELAY_TRIGGER, FOOTNOTE_R, FOOTNOTE_REFERENCE_R, FORMFEED_R, FRONT_MATTER_R, GFM_TASK_R, HEADING_ATX_COMPLIANT_R, HEADING_R, HEADING_SETEXT_R, HTML_BLOCK_ELEMENT_R, HTML_CHAR_CODE_R, HTML_COMMENT_R, HTML_CUSTOM_ATTR_R, HTML_LEFT_TRIM_AMOUNT_R, HTML_SELF_CLOSING_ELEMENT_R, HTML_TAGS, INLINE_SKIP_R, INTERPOLATION_R, LINK_AUTOLINK_BARE_URL_R, LINK_AUTOLINK_R, LIST_LOOKBEHIND_R, LOOKAHEAD, LocaleStorage, LocaleStorageClient, LocaleStorageServer, NAMED_CODES_TO_UNICODE, NP_TABLE_R, ORDERED, ORDERED_LIST_BULLET, ORDERED_LIST_ITEM_PREFIX, ORDERED_LIST_ITEM_PREFIX_R, ORDERED_LIST_ITEM_R, ORDERED_LIST_R, PARAGRAPH_R, Priority, QUALIFIER_DYNAMIC_TYPES_KEY, QUALIFIER_ORDER, REFERENCE_IMAGE_OR_LINK, REFERENCE_IMAGE_R, REFERENCE_LINK_R, RuleType, SHORTCODE_R, SHOULD_RENDER_AS_BLOCK_R, TABLE_CENTER_ALIGN, TABLE_LEFT_ALIGN, TABLE_RIGHT_ALIGN, TABLE_TRIM_PIPES, TAB_R, TEXT_BOLD_R, TEXT_EMPHASIZED_R, TEXT_ESCAPED_R, TEXT_MARKED_R, TEXT_PLAIN_R, TEXT_STRIKETHROUGHED_R, TRIM_STARTING_NEWLINES, UNESCAPE_R, UNORDERED, UNORDERED_LIST_BULLET, UNORDERED_LIST_ITEM_PREFIX, UNORDERED_LIST_ITEM_PREFIX_R, UNORDERED_LIST_ITEM_R, UNORDERED_LIST_R, VOID_HTML_ELEMENTS, allowInline, anyScopeRegex, attributeValueToNodePropValue, bindIntl, blockRegex, buildMaskPlugin, captureNothing, checkIsURLAbsolute, checkMissingLocalesPlugin, compact, comparePaths, compile, compileWithOptions, condition as cond, conditionPlugin, createCompiler, createRenderer, currency, cx, date, deepTransformNode, editDictionaryByKeyPath, enumeration as enu, enumerationPlugin, fallbackPlugin, filePlugin, filterMissingTranslationsOnlyPlugin, filterTranslationsOnlyPlugin, findMatchingCondition, formatProxyEnabledMessage, gender, genderPlugin, generateListItemPrefix, generateListItemPrefixRegex, generateListItemRegex, generateListRegex, generateSitemap, generateSitemapUrl, get, getBasePlugins, getBrowserLocale, getCachedIntl, getCanonicalPath, getCondition, getContent, getContentNodeByKeyPath, getCookie, getDefaultNode, getDictionary, getDictionaryCompositeIds, getDictionaryQualifierIds, getDictionaryQualifierTypes, getDictionarySelectorCacheKey, getDomainHostname, getDomainOrigin, getEditedContent, getEditedDictionary, getEmptyNode, getEnumeration, getFilterMissingTranslationsContent, getFilterMissingTranslationsDictionary, getFilterTranslationsOnlyContent, getFilterTranslationsOnlyDictionary, getFilteredLocalesContent, getFilteredLocalesDictionary, getGender, getHTML, getHTMLTextDir, getInsertion, getInsertionValues, getInternalPath, getInterpolableContent, getIntlayer, getLocale, getLocaleFromDomain, getLocaleFromPath, getLocaleFromStorage, getLocaleFromStorageClient, getLocaleFromStorageServer, getLocaleLang, getLocaleName, getLocalizedContent, getLocalizedPath, getLocalizedUrl, getMarkdownMetadata, getMaskContent, getMissingLocalesContent, getMissingLocalesContentFromDictionary, getMultilingualDictionary, getMultilingualUrls, getNestedDictionaryGraph, getNestedDictionaryKeys, getNestedDictionaryReferences, getNesting, getNodeChildren, getNodeType, getPathWithoutLocale, getPerLocaleDictionary, getPlural, getPrefix, getReplacedValuesContent, getRewritePath, getRewriteRules, getSelect, getSplittedContent, getSplittedDictionaryContent, getTranslation, getVariantIds, html, i18nextToIntlayerFormatter, icuToIntlayerFormatter, inlineRegex, insertion as insert, insertContentInDictionary, insertionPlugin, interpolateMessage, intlayerToI18nextFormatter, intlayerToICUFormatter, intlayerToPortableObjectFormatter, intlayerToVueI18nFormatter, isInterpolableWrapperNode, isLocaleExclusiveOnDomain, isProxyStorageLocaleEnabled, isQualifiedDictionaryGroup, isQualifiedDynamicLoaderMap, isSameKeyPath, isValidElement, list, localeDetector, localeFlatMap, localeMap, localeRecord, localeResolver, localeStorageOptions, markdown as md, mergeDictionaries, mergeQualifiedDictionaries, navigatePath, nesting as nest, nestedPlugin, normalizeAttributeKey, normalizeDictionaries, normalizeDictionary, normalizePath, normalizeWhitespace, number, orderDictionaries, parseBlock, parseCaptureInline, parseDictionarySelector, parseInline, parseMarkdown, parseSimpleInline, parseStyleAttribute, parseTableAlign, parseTableAlignCapture, parseTableCells, parseTableRow, parseTaggedMessage, parseYaml, parserFor, percentage, plural, pluralPlugin, portableObjectToIntlayerFormatter, presets, qualifies, rebuildInterpolableContent, reconstructQualifiedEntry, relativeTime, removeContentNodeByKeyPath, renameContentNodeByKeyPath, renderFor, renderMarkdownAst, renderNothing, resolveDictionaryArgument, resolveEffectiveVariantId, resolveMessage, resolveMessageNode, resolveProviderVariant, resolveProxyMode, resolveQualifiedDictionary, resolveQualifiedDynamicContent, resolveQualifiedDynamicContentAsync, sanitizer, select, selectPlugin, serializeVariant, serializeVariantChain, setLocaleInStorage, setLocaleInStorageClient, setLocaleInStorageServer, simpleInlineRegex, slugify, some, splitInsertionTemplate, startsWith, stringifyYaml, translation as t, transformInterpolableNode, translationPlugin, trimEnd, trimLeadingWhitespaceOutsideFences, unescapeString, units, unquote, updateNodeChildren, validateHTML, validateMarkdown, validatePrefix, vueI18nToIntlayerFormatter };
|
|
110
|
+
export { ATTRIBUTES_TO_SANITIZE, ATTRIBUTE_TO_NODE_PROP_MAP, ATTR_EXTRACTOR_R, BLOCKQUOTE_ALERT_R, BLOCKQUOTE_R, BLOCKQUOTE_TRIM_LEFT_MULTILINE_R, BLOCK_END_R, BREAK_LINE_R, BREAK_THEMATIC_R, CAPTURE_LETTER_AFTER_HYPHEN, CODE_BLOCK_FENCED_R, CODE_BLOCK_R, CODE_INLINE_R, COMPOSITE_ID_SEPARATOR, CONSECUTIVE_NEWLINE_R, CR_NEWLINE_R, CUSTOM_COMPONENT_R, CachedIntl, CachedIntl as Intl, DEFAULT_VARIANT_ID, DO_NOT_PROCESS_HTML_ELEMENTS, DURATION_DELAY_TRIGGER, FENCE_DELIMITER_R, FOOTNOTE_R, FOOTNOTE_REFERENCE_R, FORMFEED_R, FRONT_MATTER_R, GFM_TASK_R, HEADING_ATX_COMPLIANT_R, HEADING_R, HEADING_SETEXT_R, HTML_BLOCK_ELEMENT_R, HTML_CHAR_CODE_R, HTML_COMMENT_R, HTML_CUSTOM_ATTR_R, HTML_LEFT_TRIM_AMOUNT_R, HTML_SELF_CLOSING_ELEMENT_R, HTML_TAGS, INLINE_SKIP_R, INTERPOLATION_R, LINK_AUTOLINK_BARE_URL_R, LINK_AUTOLINK_R, LIST_LOOKBEHIND_R, LOOKAHEAD, LocaleStorage, LocaleStorageClient, LocaleStorageServer, NAMED_CODES_TO_UNICODE, NP_TABLE_R, ORDERED, ORDERED_LIST_BULLET, ORDERED_LIST_ITEM_PREFIX, ORDERED_LIST_ITEM_PREFIX_R, ORDERED_LIST_ITEM_R, ORDERED_LIST_R, PARAGRAPH_R, PRELOADED_DYNAMIC_KEY, Priority, QUALIFIER_DYNAMIC_TYPES_KEY, QUALIFIER_ORDER, REFERENCE_IMAGE_OR_LINK, REFERENCE_IMAGE_R, REFERENCE_LINK_R, RuleType, SHORTCODE_R, SHOULD_RENDER_AS_BLOCK_R, TABLE_CENTER_ALIGN, TABLE_LEFT_ALIGN, TABLE_RIGHT_ALIGN, TABLE_TRIM_PIPES, TAB_R, TEXT_BOLD_R, TEXT_EMPHASIZED_R, TEXT_ESCAPED_R, TEXT_MARKED_R, TEXT_PLAIN_R, TEXT_STRIKETHROUGHED_R, TRIM_STARTING_NEWLINES, UNESCAPE_R, UNORDERED, UNORDERED_LIST_BULLET, UNORDERED_LIST_ITEM_PREFIX, UNORDERED_LIST_ITEM_PREFIX_R, UNORDERED_LIST_ITEM_R, UNORDERED_LIST_R, VOID_HTML_ELEMENTS, allowInline, anyScopeRegex, attributeValueToNodePropValue, bindIntl, blockRegex, buildMaskPlugin, captureNothing, checkIsURLAbsolute, checkMissingLocalesPlugin, compact, comparePaths, compile, compileWithOptions, condition as cond, conditionPlugin, createCompiler, createRenderer, currency, cx, date, deepTransformNode, editDictionaryByKeyPath, enumeration as enu, enumerationPlugin, fallbackPlugin, filePlugin, filterMissingTranslationsOnlyPlugin, filterTranslationsOnlyPlugin, findMatchingCondition, formatProxyEnabledMessage, gender, genderPlugin, generateListItemPrefix, generateListItemPrefixRegex, generateListItemRegex, generateListRegex, generateSitemap, generateSitemapUrl, get, getBasePlugins, getBrowserLocale, getCachedIntl, getCanonicalPath, getCondition, getContent, getContentNodeByKeyPath, getCookie, getDefaultNode, getDictionary, getDictionaryCompositeIds, getDictionaryQualifierIds, getDictionaryQualifierTypes, getDictionarySelectorCacheKey, getDomainHostname, getDomainOrigin, getEditedContent, getEditedDictionary, getEmptyNode, getEnumeration, getFilterMissingTranslationsContent, getFilterMissingTranslationsDictionary, getFilterTranslationsOnlyContent, getFilterTranslationsOnlyDictionary, getFilteredLocalesContent, getFilteredLocalesDictionary, getGender, getHTML, getHTMLTextDir, getInsertion, getInsertionValues, getInternalPath, getInterpolableContent, getIntlayer, getLocale, getLocaleFromDomain, getLocaleFromPath, getLocaleFromStorage, getLocaleFromStorageClient, getLocaleFromStorageServer, getLocaleLang, getLocaleName, getLocalizedContent, getLocalizedPath, getLocalizedUrl, getMarkdownMetadata, getMaskContent, getMissingLocalesContent, getMissingLocalesContentFromDictionary, getMultilingualDictionary, getMultilingualUrls, getNestedDictionaryGraph, getNestedDictionaryKeys, getNestedDictionaryReferences, getNesting, getNodeChildren, getNodeType, getPathWithoutLocale, getPerLocaleDictionary, getPlural, getPrefix, getPreloadLocale, getPreloadedDictionary, getReplacedValuesContent, getRewritePath, getRewriteRules, getSelect, getSplittedContent, getSplittedDictionaryContent, getTranslation, getVariantIds, html, i18nextToIntlayerFormatter, icuToIntlayerFormatter, inlineRegex, insertion as insert, insertContentInDictionary, insertionPlugin, interpolateMessage, intlayerToI18nextFormatter, intlayerToICUFormatter, intlayerToPortableObjectFormatter, intlayerToVueI18nFormatter, isDeclaredLocale, isInterpolableWrapperNode, isLocaleExclusiveOnDomain, isProxyStorageLocaleEnabled, isQualifiedDictionaryGroup, isQualifiedDynamicLoaderMap, isSameKeyPath, isValidElement, list, localeDetector, localeFlatMap, localeMap, localeRecord, localeResolver, localeStorageOptions, markdown as md, mergeDictionaries, mergeQualifiedDictionaries, navigatePath, nesting as nest, nestedPlugin, normalizeAttributeKey, normalizeDictionaries, normalizeDictionary, normalizePath, normalizeWhitespace, number, orderDictionaries, parseBlock, parseCaptureInline, parseDictionarySelector, parseInline, parseMarkdown, parseSimpleInline, parseStyleAttribute, parseTableAlign, parseTableAlignCapture, parseTableCells, parseTableRow, parseTaggedMessage, parseYaml, parserFor, percentage, plural, pluralPlugin, portableObjectToIntlayerFormatter, presets, qualifies, rebuildInterpolableContent, reconstructQualifiedEntry, relativeTime, removeContentNodeByKeyPath, renameContentNodeByKeyPath, renderFor, renderMarkdownAst, renderNothing, resolveBrowserLocale, resolveDictionaryArgument, resolveEffectiveVariantId, resolveLocalizedPath, resolveMessage, resolveMessageNode, resolveProviderVariant, resolveProxyMode, resolveQualifiedDictionary, resolveQualifiedDynamicContent, resolveQualifiedDynamicContentAsync, sanitizer, select, selectPlugin, serializeVariant, serializeVariantChain, setLocaleInStorage, setLocaleInStorageClient, setLocaleInStorageServer, simpleInlineRegex, slugify, some, splitInsertionTemplate, startsWith, stringifyYaml, translation as t, transformInterpolableNode, translationPlugin, trimEnd, trimLeadingWhitespaceOutsideFences, unescapeString, units, unquote, updateNodeChildren, validateHTML, validateMarkdown, validatePrefix, vueI18nToIntlayerFormatter };
|
|
@@ -34,7 +34,7 @@ import { getPathWithoutLocale } from "./getPathWithoutLocale.mjs";
|
|
|
34
34
|
*/
|
|
35
35
|
const normalizePath = (inputUrl, locales) => {
|
|
36
36
|
const withoutLocale = getPathWithoutLocale(inputUrl || "/", locales);
|
|
37
|
-
const { pathname } = checkIsURLAbsolute(withoutLocale) ? new URL(withoutLocale) : new URL(withoutLocale, "http://
|
|
37
|
+
const { pathname } = checkIsURLAbsolute(withoutLocale) ? new URL(withoutLocale) : new URL(withoutLocale, "http://e.com");
|
|
38
38
|
if (pathname.length > 1 && pathname.endsWith("/")) return pathname.slice(0, -1);
|
|
39
39
|
return pathname || "/";
|
|
40
40
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"comparePaths.mjs","names":[],"sources":["../../../src/localization/comparePaths.ts"],"sourcesContent":["import type {\n DeclaredLocales,\n LocalesValues,\n} from '@intlayer/types/module_augmentation';\nimport { checkIsURLAbsolute } from '../utils/checkIsURLAbsolute';\nimport { getPathWithoutLocale } from './getPathWithoutLocale';\n\n/**\n * Normalizes a URL or pathname into a canonical, locale-agnostic pathname so\n * that two paths pointing to the same page compare equal — useful for\n * highlighting the active navigation link.\n *\n * The normalization:\n * - strips the locale segment (reusing {@link getPathWithoutLocale})\n * - strips the protocol/host so absolute and relative inputs compare equally\n * - drops the query string and hash\n * - ensures a single leading slash\n * - removes any trailing slash (except for the root path)\n * - falls back to `'/'` for empty values\n *\n * Example:\n *\n * ```ts\n * normalizePath('/ru/path') // '/path'\n * normalizePath('/ru/path/') // '/path'\n * normalizePath('ru/path') // '/path'\n * normalizePath('/ru/') // '/'\n * normalizePath('/ru') // '/'\n * normalizePath('') // '/'\n * normalizePath('https://example.com/ru/path') // '/path'\n * ```\n *\n * @param inputUrl - The URL string or pathname to normalize.\n * @param locales - Optional array of supported locales. Defaults to the\n * configured locales.\n * @returns The normalized, locale-agnostic pathname.\n */\nexport const normalizePath = <const L extends LocalesValues = DeclaredLocales>(\n inputUrl: string,\n locales?: L[]\n): string => {\n const withoutLocale = getPathWithoutLocale(inputUrl || '/', locales);\n\n // Reuse the URL API to isolate the pathname from any host/query/hash.\n const url = checkIsURLAbsolute(withoutLocale)\n ? new URL(withoutLocale)\n : new URL(withoutLocale, 'http://
|
|
1
|
+
{"version":3,"file":"comparePaths.mjs","names":[],"sources":["../../../src/localization/comparePaths.ts"],"sourcesContent":["import type {\n DeclaredLocales,\n LocalesValues,\n} from '@intlayer/types/module_augmentation';\nimport { checkIsURLAbsolute } from '../utils/checkIsURLAbsolute';\nimport { getPathWithoutLocale } from './getPathWithoutLocale';\n\n/**\n * Normalizes a URL or pathname into a canonical, locale-agnostic pathname so\n * that two paths pointing to the same page compare equal — useful for\n * highlighting the active navigation link.\n *\n * The normalization:\n * - strips the locale segment (reusing {@link getPathWithoutLocale})\n * - strips the protocol/host so absolute and relative inputs compare equally\n * - drops the query string and hash\n * - ensures a single leading slash\n * - removes any trailing slash (except for the root path)\n * - falls back to `'/'` for empty values\n *\n * Example:\n *\n * ```ts\n * normalizePath('/ru/path') // '/path'\n * normalizePath('/ru/path/') // '/path'\n * normalizePath('ru/path') // '/path'\n * normalizePath('/ru/') // '/'\n * normalizePath('/ru') // '/'\n * normalizePath('') // '/'\n * normalizePath('https://example.com/ru/path') // '/path'\n * ```\n *\n * @param inputUrl - The URL string or pathname to normalize.\n * @param locales - Optional array of supported locales. Defaults to the\n * configured locales.\n * @returns The normalized, locale-agnostic pathname.\n */\nexport const normalizePath = <const L extends LocalesValues = DeclaredLocales>(\n inputUrl: string,\n locales?: L[]\n): string => {\n const withoutLocale = getPathWithoutLocale(inputUrl || '/', locales);\n\n // Reuse the URL API to isolate the pathname from any host/query/hash.\n const url = checkIsURLAbsolute(withoutLocale)\n ? new URL(withoutLocale)\n : new URL(withoutLocale, 'http://e.com');\n\n const { pathname } = url;\n\n // Remove a trailing slash, keeping the root path intact.\n if (pathname.length > 1 && pathname.endsWith('/')) {\n return pathname.slice(0, -1);\n }\n\n return pathname || '/';\n};\n\n/**\n * Compares two URLs or pathnames for equality, ignoring locale segment,\n * protocol/host, query string, hash and trailing slashes.\n *\n * Both inputs are normalized through {@link normalizePath} before comparison,\n * making this ideal for matching the current pathname against a navigation\n * link's `href`.\n *\n * Example:\n *\n * ```ts\n * comparePaths('/ru/path', '/path') // true\n * comparePaths('/ru/path/', '/path') // true\n * comparePaths('/ru/path', '/path/') // true\n * comparePaths('/ru/', '/') // true\n * comparePaths('/ru', '/') // true\n * comparePaths('ru/path', '/path') // true\n * comparePaths('', '/') // true\n * comparePaths('/ru', '') // true\n * comparePaths('/ru/path', '/other') // false\n * ```\n *\n * @param pathname - The first URL string or pathname to compare.\n * @param href - The second URL string or pathname to compare.\n * @param locales - Optional array of supported locales. Defaults to the\n * configured locales.\n * @returns `true` when both inputs resolve to the same locale-agnostic path.\n */\nexport const comparePaths = <const L extends LocalesValues = DeclaredLocales>(\n pathname: string,\n href: string,\n locales?: L[]\n): boolean => normalizePath(pathname, locales) === normalizePath(href, locales);\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqCA,MAAa,iBACX,UACA,YACW;CACX,MAAM,gBAAgB,qBAAqB,YAAY,KAAK,OAAO;CAOnE,MAAM,EAAE,aAJI,mBAAmB,aAAa,IACxC,IAAI,IAAI,aAAa,IACrB,IAAI,IAAI,eAAe,cAAc;CAKzC,IAAI,SAAS,SAAS,KAAK,SAAS,SAAS,GAAG,GAC9C,OAAO,SAAS,MAAM,GAAG,EAAE;CAG7B,OAAO,YAAY;AACrB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8BA,MAAa,gBACX,UACA,MACA,YACY,cAAc,UAAU,OAAO,MAAM,cAAc,MAAM,OAAO"}
|