@fuzdev/fuz_util 0.48.4 → 0.49.1

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/diff.js CHANGED
@@ -3,7 +3,7 @@
3
3
  *
4
4
  * @module
5
5
  */
6
- import { is_binary } from './string.js';
6
+ import { string_is_binary } from './string.js';
7
7
  /**
8
8
  * Generate a line-based diff between two strings using LCS algorithm.
9
9
  *
@@ -176,7 +176,7 @@ export const format_diff = (diff, current_path, desired_path, options = {}) => {
176
176
  */
177
177
  export const generate_diff = (current, desired, path, options = {}) => {
178
178
  // Skip binary files
179
- if (is_binary(current) || is_binary(desired)) {
179
+ if (string_is_binary(current) || string_is_binary(desired)) {
180
180
  return null;
181
181
  }
182
182
  const diff = diff_lines(current, desired);
package/dist/path.d.ts CHANGED
@@ -53,6 +53,17 @@ export type PathPiece = {
53
53
  * @todo maybe rethink this API, it's a bit weird, but fits the usage in `ui/Breadcrumbs.svelte`
54
54
  */
55
55
  export declare const parse_path_pieces: (raw_path: string) => Array<PathPiece>;
56
+ /**
57
+ * Checks if a filename matches any exclusion pattern.
58
+ *
59
+ * Returns `false` when `filename` is `undefined`, empty string, or `exclude` is empty.
60
+ * String patterns use substring matching. RegExp patterns use `.test()`.
61
+ *
62
+ * @param filename The file path to check, or `undefined` for virtual files.
63
+ * @param exclude Array of string or RegExp exclusion patterns.
64
+ * @returns `true` if the file should be excluded from processing.
65
+ */
66
+ export declare const should_exclude_path: (filename: string | undefined, exclude: Array<string | RegExp>) => boolean;
56
67
  /**
57
68
  * Converts a string into a URL-compatible slug.
58
69
  * @param str the string to convert
@@ -1 +1 @@
1
- {"version":3,"file":"path.d.ts","sourceRoot":"../src/lib/","sources":["../src/lib/path.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAC,QAAQ,EAAC,MAAM,YAAY,CAAC;AAEzC;;GAEG;AACH,MAAM,MAAM,MAAM,GAAG,QAAQ,CAAC,MAAM,EAAE,QAAQ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AA6B,KAAG,MAYpE,CAAC"}
package/dist/path.js CHANGED
@@ -42,6 +42,21 @@ export const parse_path_pieces = (raw_path) => {
42
42
  }
43
43
  return pieces;
44
44
  };
45
+ /**
46
+ * Checks if a filename matches any exclusion pattern.
47
+ *
48
+ * Returns `false` when `filename` is `undefined`, empty string, or `exclude` is empty.
49
+ * String patterns use substring matching. RegExp patterns use `.test()`.
50
+ *
51
+ * @param filename The file path to check, or `undefined` for virtual files.
52
+ * @param exclude Array of string or RegExp exclusion patterns.
53
+ * @returns `true` if the file should be excluded from processing.
54
+ */
55
+ export const should_exclude_path = (filename, exclude) => {
56
+ if (!filename || exclude.length === 0)
57
+ return false;
58
+ return exclude.some((pattern) => typeof pattern === 'string' ? filename.includes(pattern) : pattern.test(filename));
59
+ };
45
60
  /**
46
61
  * Converts a string into a URL-compatible slug.
47
62
  * @param str the string to convert
package/dist/string.d.ts CHANGED
@@ -70,6 +70,13 @@ export declare const pad_width: (str: string, target_width: number, align?: "lef
70
70
  * @returns The edit distance between the strings
71
71
  */
72
72
  export declare const levenshtein_distance: (a: string, b: string) => number;
73
+ /**
74
+ * Escapes a string for use inside a single-quoted JS string literal.
75
+ *
76
+ * Uses a single-pass regex replacement to escape backslashes, single quotes,
77
+ * newlines, carriage returns, and Unicode line/paragraph separators.
78
+ */
79
+ export declare const escape_js_string: (value: string) => string;
73
80
  /**
74
81
  * Check if content appears to be binary.
75
82
  *
@@ -78,5 +85,5 @@ export declare const levenshtein_distance: (a: string, b: string) => number;
78
85
  * @param content - Content to check.
79
86
  * @returns True if content appears to be binary.
80
87
  */
81
- export declare const is_binary: (content: string) => boolean;
88
+ export declare const string_is_binary: (content: string) => boolean;
82
89
  //# sourceMappingURL=string.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"string.d.ts","sourceRoot":"../src/lib/","sources":["../src/lib/string.ts"],"names":[],"mappings":"AAEA;;GAEG;AACH,eAAO,MAAM,QAAQ,GAAI,KAAK,MAAM,EAAE,WAAW,MA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AIG;AACH,eAAO,MAAM,SAAS,GAAI,OAAO,OAAO,KAAG,MACwC,CAAC;AAEpF;;;;;;;GAOG;AACH,eAAO,MAAM,oBAAoB,GAAI,KAAK,MAAM,KAAG,MAuClD,CAAC;AAEF;;GAEG;AACH,eAAO,MAAM,SAAS,GACrB,KAAK,MAAM,EACX,cAAc,MAAM,EACpB,QAAO,MAAM,GAAG,OAAgB,KAC9B,MAQF,CAAC;AAEF;;;;;;;GAOG;AACH,eAAO,MAAM,oBAAoB,GAAI,GAAG,MAAM,EAAE,GAAG,MAAM,KAAG,MAmC3D,CAAC;AAEF;;;;;GAKG;AACH,eAAO,MAAM,gBAAgB,GAAI,OAAO,MAAM,KAAG,MAkB9C,CAAC;AAEJ;;;;;;;GAOG;AACH,eAAO,MAAM,gBAAgB,GAAI,SAAS,MAAM,KAAG,OAAgD,CAAC"}
package/dist/string.js CHANGED
@@ -191,6 +191,30 @@ export const levenshtein_distance = (a, b) => {
191
191
  }
192
192
  return prev[short_len];
193
193
  };
194
+ /**
195
+ * Escapes a string for use inside a single-quoted JS string literal.
196
+ *
197
+ * Uses a single-pass regex replacement to escape backslashes, single quotes,
198
+ * newlines, carriage returns, and Unicode line/paragraph separators.
199
+ */
200
+ export const escape_js_string = (value) => value.replace(/[\\'\n\r\u2028\u2029]/g, (ch) => {
201
+ switch (ch) {
202
+ case '\\':
203
+ return '\\\\';
204
+ case "'":
205
+ return "\\'";
206
+ case '\n':
207
+ return '\\n';
208
+ case '\r':
209
+ return '\\r';
210
+ case '\u2028':
211
+ return '\\u2028';
212
+ case '\u2029':
213
+ return '\\u2029';
214
+ default:
215
+ return ch;
216
+ }
217
+ });
194
218
  /**
195
219
  * Check if content appears to be binary.
196
220
  *
@@ -199,7 +223,4 @@ export const levenshtein_distance = (a, b) => {
199
223
  * @param content - Content to check.
200
224
  * @returns True if content appears to be binary.
201
225
  */
202
- export const is_binary = (content) => {
203
- const sample = content.slice(0, 8192);
204
- return sample.includes('\0');
205
- };
226
+ export const string_is_binary = (content) => content.slice(0, 8192).includes('\0');
@@ -0,0 +1,152 @@
1
+ /**
2
+ * Shared helper functions for Svelte preprocessors.
3
+ *
4
+ * Provides AST utilities for detecting static content, resolving imports,
5
+ * managing import statements, and escaping strings for Svelte templates.
6
+ * Used by `svelte_preprocess_mdz` in fuz_ui, `svelte_preprocess_fuz_code`
7
+ * in fuz_code, and potentially other Svelte preprocessors.
8
+ *
9
+ * Uses `import type` from `svelte/compiler` for AST types only — no runtime
10
+ * Svelte dependency. Consumers must have `svelte` installed for type resolution.
11
+ *
12
+ * @module
13
+ */
14
+ import type { Expression, ImportDeclaration, ImportDefaultSpecifier, ImportSpecifier } from 'estree';
15
+ import type { AST } from 'svelte/compiler';
16
+ /** Import metadata for a single import specifier. */
17
+ export interface PreprocessImportInfo {
18
+ /** The module path to import from. */
19
+ path: string;
20
+ /** Whether this is a default or named import. */
21
+ kind: 'default' | 'named';
22
+ }
23
+ /** Information about a resolved component import. */
24
+ export interface ResolvedComponentImport {
25
+ /** The `ImportDeclaration` AST node that provides this name. */
26
+ import_node: ImportDeclaration;
27
+ /** The specific import specifier for this name. */
28
+ specifier: ImportSpecifier | ImportDefaultSpecifier;
29
+ }
30
+ /**
31
+ * Finds an attribute by name on a component AST node.
32
+ *
33
+ * Iterates the node's `attributes` array and returns the first `Attribute`
34
+ * node whose `name` matches. Skips `SpreadAttribute`, directive, and other node types.
35
+ *
36
+ * @param node The component AST node to search.
37
+ * @param name The attribute name to find.
38
+ * @returns The matching `Attribute` node, or `undefined` if not found.
39
+ */
40
+ export declare const find_attribute: (node: AST.Component, name: string) => AST.Attribute | undefined;
41
+ /**
42
+ * Recursively evaluates an expression AST node to a static string value.
43
+ *
44
+ * Handles string `Literal`, `TemplateLiteral` (including interpolations when all
45
+ * expressions resolve), `BinaryExpression` with `+`, and `Identifier` lookup
46
+ * via an optional bindings map built by `build_static_bindings`.
47
+ * Returns `null` for dynamic expressions, non-string literals, or unsupported node types.
48
+ *
49
+ * @param expr An ESTree expression AST node.
50
+ * @param bindings Optional map of variable names to their resolved static string values.
51
+ * @returns The resolved static string, or `null` if the expression is dynamic.
52
+ */
53
+ export declare const evaluate_static_expr: (expr: Expression, bindings?: ReadonlyMap<string, string>) => string | null;
54
+ /**
55
+ * Extracts a static string value from a Svelte attribute value AST node.
56
+ *
57
+ * Handles three forms:
58
+ * - Boolean `true` (bare attribute like `inline`) -- returns `null`.
59
+ * - Array with a single `Text` node (quoted attribute like `content="text"`) --
60
+ * returns the text data.
61
+ * - `ExpressionTag` (expression like `content={'text'}`) -- delegates to `evaluate_static_expr`.
62
+ *
63
+ * Returns `null` for null literals, mixed arrays, dynamic expressions, and non-string values.
64
+ *
65
+ * @param value The attribute value from `AST.Attribute['value']`.
66
+ * @param bindings Optional map of variable names to their resolved static string values.
67
+ * @returns The resolved static string, or `null` if the value is dynamic.
68
+ */
69
+ export declare const extract_static_string: (value: AST.Attribute["value"], bindings?: ReadonlyMap<string, string>) => string | null;
70
+ /**
71
+ * Builds a map of statically resolvable `const` bindings from a Svelte AST.
72
+ *
73
+ * Scans top-level `const` variable declarations in both instance and module scripts.
74
+ * For each declarator with a plain `Identifier` pattern and a statically evaluable
75
+ * initializer, adds the binding to the map. Processes declarations in source order
76
+ * so that chained references resolve: `const a = 'x'; const b = a;` maps `b` to `'x'`.
77
+ *
78
+ * Skips destructuring patterns, `let`/`var` declarations, and declarations
79
+ * whose initializers reference dynamic values.
80
+ *
81
+ * @param ast The parsed Svelte AST root node.
82
+ * @returns Map of variable names to their resolved static string values.
83
+ */
84
+ export declare const build_static_bindings: (ast: AST.Root) => Map<string, string>;
85
+ /**
86
+ * Resolves local names that import from specified source paths.
87
+ *
88
+ * Scans `ImportDeclaration` nodes in both the instance and module scripts.
89
+ * Handles default, named, and aliased imports. Skips namespace imports.
90
+ * Returns import node references alongside names to support import removal.
91
+ *
92
+ * @param ast The parsed Svelte AST root node.
93
+ * @param component_imports Array of import source paths to match against.
94
+ * @returns Map of local names to their resolved import info.
95
+ */
96
+ export declare const resolve_component_names: (ast: AST.Root, component_imports: Array<string>) => Map<string, ResolvedComponentImport>;
97
+ /**
98
+ * Finds the position to insert new import statements within a script block.
99
+ *
100
+ * Returns the end position of the last `ImportDeclaration`, or the start
101
+ * of the script body content if no imports exist.
102
+ *
103
+ * @param script The parsed `AST.Script` node.
104
+ * @returns The character position where new imports should be inserted.
105
+ */
106
+ export declare const find_import_insert_position: (script: AST.Script) => number;
107
+ /**
108
+ * Generates indented import statement lines from an import map.
109
+ *
110
+ * Default imports produce `import Name from 'path';` lines.
111
+ * Named imports are grouped by path into `import {a, b} from 'path';` lines.
112
+ *
113
+ * @param imports Map of local names to their import info.
114
+ * @param indent Indentation prefix for each line. @default '\t'
115
+ * @returns A string of newline-separated import statements.
116
+ */
117
+ export declare const generate_import_lines: (imports: Map<string, PreprocessImportInfo>, indent?: string) => string;
118
+ /**
119
+ * Checks if an identifier with the given name appears anywhere in an AST subtree.
120
+ *
121
+ * Recursively walks all object and array properties of the tree, matching
122
+ * ESTree `Identifier` nodes (`{type: 'Identifier', name}`). Nodes in the
123
+ * `skip` set are excluded from traversal — used to skip `ImportDeclaration`
124
+ * nodes so the import's own specifier identifier doesn't false-positive.
125
+ *
126
+ * Safe for Svelte template ASTs: `Component.name` is a plain string property
127
+ * (not an `Identifier` node), so `<Mdz>` tags do not produce false matches.
128
+ *
129
+ * @param node The AST subtree to search.
130
+ * @param name The identifier name to look for.
131
+ * @param skip Set of AST nodes to skip during traversal.
132
+ * @returns `true` if a matching `Identifier` node is found.
133
+ */
134
+ export declare const has_identifier_in_tree: (node: unknown, name: string, skip?: Set<unknown>) => boolean;
135
+ /**
136
+ * Escapes text for safe embedding in Svelte template markup.
137
+ *
138
+ * Uses a single-pass regex replacement to avoid corruption that occurs with sequential
139
+ * `.replace()` calls (where the second replace matches characters introduced by the first).
140
+ *
141
+ * Escapes four characters:
142
+ * - `{` → `{'{'}` and `}` → `{'}'}` — prevents Svelte expression interpretation
143
+ * - `<` → `&lt;` — prevents HTML/Svelte tag interpretation
144
+ * - `&` → `&amp;` — prevents HTML entity interpretation
145
+ *
146
+ * The `&` escaping is necessary because runtime `MdzNodeView.svelte` renders text
147
+ * with `{node.content}` (a Svelte expression), which auto-escapes `&` to `&amp;`.
148
+ * The preprocessor emits raw template text where `&` is NOT auto-escaped, so
149
+ * manual escaping is required to match the runtime behavior.
150
+ */
151
+ export declare const escape_svelte_text: (text: string) => string;
152
+ //# sourceMappingURL=svelte_preprocess_helpers.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"svelte_preprocess_helpers.d.ts","sourceRoot":"../src/lib/","sources":["../src/lib/svelte_preprocess_helpers.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,OAAO,KAAK,EAAC,UAAU,EAAE,iBAAiB,EAAE,sBAAsB,EAAE,eAAe,EAAC,MAAM,QAAQ,CAAC;AACnG,OAAO,KAAK,EAAC,GAAG,EAAC,MAAM,iBAAiB,CAAC;AAEzC,qDAAqD;AACrD,MAAM,WAAW,oBAAoB;IACpC,sCAAsC;IACtC,IAAI,EAAE,MAAM,CAAC;IACb,iDAAiD;IACjD,IAAI,EAAE,SAAS,GAAG,OAAO,CAAC;CAC1B;AAED,qDAAqD;AACrD,MAAM,WAAW,uBAAuB;IACvC,gEAAgE;IAChE,WAAW,EAAE,iBAAiB,CAAC;IAC/B,mDAAmD;IACnD,SAAS,EAAE,eAAe,GAAG,sBAAsB,CAAC;CACpD;AAED;;;;;;;;;GASG;AACH,eAAO,MAAM,cAAc,GAAI,MAAM,GAAG,CAAC,SAAS,EAAE,MAAM,MAAM,KAAG,GAAG,CAAC,SAAS,GAAG,SAOlF,CAAC;AAEF;;;;;;;;;;;GAWG;AACH,eAAO,MAAM,oBAAoB,GAChC,MAAM,UAAU,EAChB,WAAW,WAAW,CAAC,MAAM,EAAE,MAAM,CAAC,KACpC,MAAM,GAAG,IA+BX,CAAC;AAEF;;;;;;;;;;;;;;GAcG;AACH,eAAO,MAAM,qBAAqB,GACjC,OAAO,GAAG,CAAC,SAAS,CAAC,OAAO,CAAC,EAC7B,WAAW,WAAW,CAAC,MAAM,EAAE,MAAM,CAAC,KACpC,MAAM,GAAG,IAkBX,CAAC;AAEF;;;;;;;;;;;;;GAaG;AACH,eAAO,MAAM,qBAAqB,GAAI,KAAK,GAAG,CAAC,IAAI,KAAG,GAAG,CAAC,MAAM,EAAE,MAAM,CAiBvE,CAAC;AAEF;;;;;;;;;;GAUG;AACH,eAAO,MAAM,uBAAuB,GACnC,KAAK,GAAG,CAAC,IAAI,EACb,mBAAmB,KAAK,CAAC,MAAM,CAAC,KAC9B,GAAG,CAAC,MAAM,EAAE,uBAAuB,CAcrC,CAAC;AAEF;;;;;;;;GAQG;AACH,eAAO,MAAM,2BAA2B,GAAI,QAAQ,GAAG,CAAC,MAAM,KAAG,MAYhE,CAAC;AAEF;;;;;;;;;GASG;AACH,eAAO,MAAM,qBAAqB,GACjC,SAAS,GAAG,CAAC,MAAM,EAAE,oBAAoB,CAAC,EAC1C,SAAQ,MAAa,KACnB,MAyBF,CAAC;AAEF;;;;;;;;;;;;;;;GAeG;AACH,eAAO,MAAM,sBAAsB,GAClC,MAAM,OAAO,EACb,MAAM,MAAM,EACZ,OAAO,GAAG,CAAC,OAAO,CAAC,KACjB,OAYF,CAAC;AAEF;;;;;;;;;;;;;;;GAeG;AACH,eAAO,MAAM,kBAAkB,GAAI,MAAM,MAAM,KAAG,MAc/C,CAAC"}
@@ -0,0 +1,300 @@
1
+ /**
2
+ * Shared helper functions for Svelte preprocessors.
3
+ *
4
+ * Provides AST utilities for detecting static content, resolving imports,
5
+ * managing import statements, and escaping strings for Svelte templates.
6
+ * Used by `svelte_preprocess_mdz` in fuz_ui, `svelte_preprocess_fuz_code`
7
+ * in fuz_code, and potentially other Svelte preprocessors.
8
+ *
9
+ * Uses `import type` from `svelte/compiler` for AST types only — no runtime
10
+ * Svelte dependency. Consumers must have `svelte` installed for type resolution.
11
+ *
12
+ * @module
13
+ */
14
+ /**
15
+ * Finds an attribute by name on a component AST node.
16
+ *
17
+ * Iterates the node's `attributes` array and returns the first `Attribute`
18
+ * node whose `name` matches. Skips `SpreadAttribute`, directive, and other node types.
19
+ *
20
+ * @param node The component AST node to search.
21
+ * @param name The attribute name to find.
22
+ * @returns The matching `Attribute` node, or `undefined` if not found.
23
+ */
24
+ export const find_attribute = (node, name) => {
25
+ for (const attr of node.attributes) {
26
+ if (attr.type === 'Attribute' && attr.name === name) {
27
+ return attr;
28
+ }
29
+ }
30
+ return undefined;
31
+ };
32
+ /**
33
+ * Recursively evaluates an expression AST node to a static string value.
34
+ *
35
+ * Handles string `Literal`, `TemplateLiteral` (including interpolations when all
36
+ * expressions resolve), `BinaryExpression` with `+`, and `Identifier` lookup
37
+ * via an optional bindings map built by `build_static_bindings`.
38
+ * Returns `null` for dynamic expressions, non-string literals, or unsupported node types.
39
+ *
40
+ * @param expr An ESTree expression AST node.
41
+ * @param bindings Optional map of variable names to their resolved static string values.
42
+ * @returns The resolved static string, or `null` if the expression is dynamic.
43
+ */
44
+ export const evaluate_static_expr = (expr, bindings) => {
45
+ if (expr.type === 'Literal' && typeof expr.value === 'string')
46
+ return expr.value;
47
+ if (expr.type === 'TemplateLiteral') {
48
+ if (expr.expressions.length === 0) {
49
+ return expr.quasis.map((q) => q.value.cooked ?? q.value.raw).join('');
50
+ }
51
+ // Try resolving interpolations through bindings
52
+ const parts = [];
53
+ for (let i = 0; i < expr.quasis.length; i++) {
54
+ const quasi = expr.quasis[i];
55
+ parts.push(quasi.value.cooked ?? quasi.value.raw);
56
+ if (i < expr.expressions.length) {
57
+ const val = evaluate_static_expr(expr.expressions[i], bindings);
58
+ if (val === null)
59
+ return null;
60
+ parts.push(val);
61
+ }
62
+ }
63
+ return parts.join('');
64
+ }
65
+ if (expr.type === 'BinaryExpression' && expr.operator === '+') {
66
+ if (expr.left.type === 'PrivateIdentifier')
67
+ return null;
68
+ const left = evaluate_static_expr(expr.left, bindings);
69
+ if (left === null)
70
+ return null;
71
+ const right = evaluate_static_expr(expr.right, bindings);
72
+ if (right === null)
73
+ return null;
74
+ return left + right;
75
+ }
76
+ if (expr.type === 'Identifier' && bindings?.has(expr.name)) {
77
+ return bindings.get(expr.name);
78
+ }
79
+ return null;
80
+ };
81
+ /**
82
+ * Extracts a static string value from a Svelte attribute value AST node.
83
+ *
84
+ * Handles three forms:
85
+ * - Boolean `true` (bare attribute like `inline`) -- returns `null`.
86
+ * - Array with a single `Text` node (quoted attribute like `content="text"`) --
87
+ * returns the text data.
88
+ * - `ExpressionTag` (expression like `content={'text'}`) -- delegates to `evaluate_static_expr`.
89
+ *
90
+ * Returns `null` for null literals, mixed arrays, dynamic expressions, and non-string values.
91
+ *
92
+ * @param value The attribute value from `AST.Attribute['value']`.
93
+ * @param bindings Optional map of variable names to their resolved static string values.
94
+ * @returns The resolved static string, or `null` if the value is dynamic.
95
+ */
96
+ export const extract_static_string = (value, bindings) => {
97
+ // Boolean attribute (e.g., <Mdz inline />)
98
+ if (value === true)
99
+ return null;
100
+ // Plain attribute: content="text"
101
+ if (Array.isArray(value)) {
102
+ const first = value[0];
103
+ if (value.length === 1 && first?.type === 'Text') {
104
+ return first.data;
105
+ }
106
+ return null;
107
+ }
108
+ // ExpressionTag: content={expr}
109
+ const expr = value.expression;
110
+ // Null literal
111
+ if (expr.type === 'Literal' && expr.value === null)
112
+ return null;
113
+ return evaluate_static_expr(expr, bindings);
114
+ };
115
+ /**
116
+ * Builds a map of statically resolvable `const` bindings from a Svelte AST.
117
+ *
118
+ * Scans top-level `const` variable declarations in both instance and module scripts.
119
+ * For each declarator with a plain `Identifier` pattern and a statically evaluable
120
+ * initializer, adds the binding to the map. Processes declarations in source order
121
+ * so that chained references resolve: `const a = 'x'; const b = a;` maps `b` to `'x'`.
122
+ *
123
+ * Skips destructuring patterns, `let`/`var` declarations, and declarations
124
+ * whose initializers reference dynamic values.
125
+ *
126
+ * @param ast The parsed Svelte AST root node.
127
+ * @returns Map of variable names to their resolved static string values.
128
+ */
129
+ export const build_static_bindings = (ast) => {
130
+ const bindings = new Map();
131
+ for (const script of [ast.instance, ast.module]) {
132
+ if (!script)
133
+ continue;
134
+ for (const node of script.content.body) {
135
+ if (node.type !== 'VariableDeclaration' || node.kind !== 'const')
136
+ continue;
137
+ for (const declarator of node.declarations) {
138
+ if (declarator.id.type !== 'Identifier')
139
+ continue;
140
+ if (!declarator.init)
141
+ continue;
142
+ const value = evaluate_static_expr(declarator.init, bindings);
143
+ if (value !== null) {
144
+ bindings.set(declarator.id.name, value);
145
+ }
146
+ }
147
+ }
148
+ }
149
+ return bindings;
150
+ };
151
+ /**
152
+ * Resolves local names that import from specified source paths.
153
+ *
154
+ * Scans `ImportDeclaration` nodes in both the instance and module scripts.
155
+ * Handles default, named, and aliased imports. Skips namespace imports.
156
+ * Returns import node references alongside names to support import removal.
157
+ *
158
+ * @param ast The parsed Svelte AST root node.
159
+ * @param component_imports Array of import source paths to match against.
160
+ * @returns Map of local names to their resolved import info.
161
+ */
162
+ export const resolve_component_names = (ast, component_imports) => {
163
+ const names = new Map();
164
+ for (const script of [ast.instance, ast.module]) {
165
+ if (!script)
166
+ continue;
167
+ for (const node of script.content.body) {
168
+ if (node.type !== 'ImportDeclaration')
169
+ continue;
170
+ if (!component_imports.includes(node.source.value))
171
+ continue;
172
+ for (const specifier of node.specifiers) {
173
+ if (specifier.type === 'ImportNamespaceSpecifier')
174
+ continue;
175
+ names.set(specifier.local.name, { import_node: node, specifier });
176
+ }
177
+ }
178
+ }
179
+ return names;
180
+ };
181
+ /**
182
+ * Finds the position to insert new import statements within a script block.
183
+ *
184
+ * Returns the end position of the last `ImportDeclaration`, or the start
185
+ * of the script body content if no imports exist.
186
+ *
187
+ * @param script The parsed `AST.Script` node.
188
+ * @returns The character position where new imports should be inserted.
189
+ */
190
+ export const find_import_insert_position = (script) => {
191
+ let last_import_end = -1;
192
+ for (const node of script.content.body) {
193
+ if (node.type === 'ImportDeclaration') {
194
+ // Svelte's parser always provides position data on AST nodes
195
+ last_import_end = node.end;
196
+ }
197
+ }
198
+ if (last_import_end !== -1) {
199
+ return last_import_end;
200
+ }
201
+ return script.content.start;
202
+ };
203
+ /**
204
+ * Generates indented import statement lines from an import map.
205
+ *
206
+ * Default imports produce `import Name from 'path';` lines.
207
+ * Named imports are grouped by path into `import {a, b} from 'path';` lines.
208
+ *
209
+ * @param imports Map of local names to their import info.
210
+ * @param indent Indentation prefix for each line. @default '\t'
211
+ * @returns A string of newline-separated import statements.
212
+ */
213
+ export const generate_import_lines = (imports, indent = '\t') => {
214
+ const default_imports = [];
215
+ const named_by_path = new Map();
216
+ for (const [name, { path, kind }] of imports) {
217
+ if (kind === 'default') {
218
+ default_imports.push([name, path]);
219
+ }
220
+ else {
221
+ let names = named_by_path.get(path);
222
+ if (!names) {
223
+ names = [];
224
+ named_by_path.set(path, names);
225
+ }
226
+ names.push(name);
227
+ }
228
+ }
229
+ const lines = [];
230
+ for (const [name, path] of default_imports) {
231
+ lines.push(`${indent}import ${name} from '${path}';`);
232
+ }
233
+ for (const [path, names] of named_by_path) {
234
+ lines.push(`${indent}import {${names.join(', ')}} from '${path}';`);
235
+ }
236
+ return lines.join('\n');
237
+ };
238
+ /**
239
+ * Checks if an identifier with the given name appears anywhere in an AST subtree.
240
+ *
241
+ * Recursively walks all object and array properties of the tree, matching
242
+ * ESTree `Identifier` nodes (`{type: 'Identifier', name}`). Nodes in the
243
+ * `skip` set are excluded from traversal — used to skip `ImportDeclaration`
244
+ * nodes so the import's own specifier identifier doesn't false-positive.
245
+ *
246
+ * Safe for Svelte template ASTs: `Component.name` is a plain string property
247
+ * (not an `Identifier` node), so `<Mdz>` tags do not produce false matches.
248
+ *
249
+ * @param node The AST subtree to search.
250
+ * @param name The identifier name to look for.
251
+ * @param skip Set of AST nodes to skip during traversal.
252
+ * @returns `true` if a matching `Identifier` node is found.
253
+ */
254
+ export const has_identifier_in_tree = (node, name, skip) => {
255
+ if (node === null || node === undefined || typeof node !== 'object')
256
+ return false;
257
+ if (skip?.has(node))
258
+ return false;
259
+ if (Array.isArray(node)) {
260
+ return node.some((child) => has_identifier_in_tree(child, name, skip));
261
+ }
262
+ const record = node;
263
+ if (record.type === 'Identifier' && record.name === name)
264
+ return true;
265
+ for (const key of Object.keys(record)) {
266
+ if (has_identifier_in_tree(record[key], name, skip))
267
+ return true;
268
+ }
269
+ return false;
270
+ };
271
+ /**
272
+ * Escapes text for safe embedding in Svelte template markup.
273
+ *
274
+ * Uses a single-pass regex replacement to avoid corruption that occurs with sequential
275
+ * `.replace()` calls (where the second replace matches characters introduced by the first).
276
+ *
277
+ * Escapes four characters:
278
+ * - `{` → `{'{'}` and `}` → `{'}'}` — prevents Svelte expression interpretation
279
+ * - `<` → `&lt;` — prevents HTML/Svelte tag interpretation
280
+ * - `&` → `&amp;` — prevents HTML entity interpretation
281
+ *
282
+ * The `&` escaping is necessary because runtime `MdzNodeView.svelte` renders text
283
+ * with `{node.content}` (a Svelte expression), which auto-escapes `&` to `&amp;`.
284
+ * The preprocessor emits raw template text where `&` is NOT auto-escaped, so
285
+ * manual escaping is required to match the runtime behavior.
286
+ */
287
+ export const escape_svelte_text = (text) => text.replace(/[{}<&]/g, (ch) => {
288
+ switch (ch) {
289
+ case '{':
290
+ return "{'{'}";
291
+ case '}':
292
+ return "{'}'}";
293
+ case '<':
294
+ return '&lt;';
295
+ case '&':
296
+ return '&amp;';
297
+ default:
298
+ return ch;
299
+ }
300
+ });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fuzdev/fuz_util",
3
- "version": "0.48.4",
3
+ "version": "0.49.1",
4
4
  "description": "utility belt for JS",
5
5
  "glyph": "🦕",
6
6
  "logo": "logo.svg",
@@ -44,8 +44,10 @@
44
44
  "web"
45
45
  ],
46
46
  "peerDependencies": {
47
+ "@types/estree": "^1",
47
48
  "@types/node": "^24",
48
49
  "esm-env": "^1.2.2",
50
+ "svelte": "^5",
49
51
  "zod": "^4.0.14"
50
52
  },
51
53
  "peerDependenciesMeta": {
@@ -55,6 +57,12 @@
55
57
  "esm-env": {
56
58
  "optional": true
57
59
  },
60
+ "@types/estree": {
61
+ "optional": true
62
+ },
63
+ "svelte": {
64
+ "optional": true
65
+ },
58
66
  "zod": {
59
67
  "optional": true
60
68
  }
@@ -70,6 +78,7 @@
70
78
  "@sveltejs/kit": "^2.50.1",
71
79
  "@sveltejs/package": "^2.5.7",
72
80
  "@sveltejs/vite-plugin-svelte": "^6.2.4",
81
+ "@types/estree": "^1.0.8",
73
82
  "@types/node": "^24.10.1",
74
83
  "@webref/css": "^8.2.0",
75
84
  "dequal": "^2.0.3",
package/src/lib/diff.ts CHANGED
@@ -4,7 +4,7 @@
4
4
  * @module
5
5
  */
6
6
 
7
- import {is_binary} from './string.js';
7
+ import {string_is_binary} from './string.js';
8
8
 
9
9
  /** Line diff result */
10
10
  export interface DiffLine {
@@ -224,7 +224,7 @@ export const generate_diff = (
224
224
  options: FormatDiffOptions = {},
225
225
  ): string | null => {
226
226
  // Skip binary files
227
- if (is_binary(current) || is_binary(desired)) {
227
+ if (string_is_binary(current) || string_is_binary(desired)) {
228
228
  return null;
229
229
  }
230
230
 
package/src/lib/path.ts CHANGED
@@ -94,6 +94,26 @@ export const parse_path_pieces = (raw_path: string): Array<PathPiece> => {
94
94
  return pieces;
95
95
  };
96
96
 
97
+ /**
98
+ * Checks if a filename matches any exclusion pattern.
99
+ *
100
+ * Returns `false` when `filename` is `undefined`, empty string, or `exclude` is empty.
101
+ * String patterns use substring matching. RegExp patterns use `.test()`.
102
+ *
103
+ * @param filename The file path to check, or `undefined` for virtual files.
104
+ * @param exclude Array of string or RegExp exclusion patterns.
105
+ * @returns `true` if the file should be excluded from processing.
106
+ */
107
+ export const should_exclude_path = (
108
+ filename: string | undefined,
109
+ exclude: Array<string | RegExp>,
110
+ ): boolean => {
111
+ if (!filename || exclude.length === 0) return false;
112
+ return exclude.some((pattern) =>
113
+ typeof pattern === 'string' ? filename.includes(pattern) : pattern.test(filename),
114
+ );
115
+ };
116
+
97
117
  /**
98
118
  * Converts a string into a URL-compatible slug.
99
119
  * @param str the string to convert
package/src/lib/string.ts CHANGED
@@ -209,6 +209,32 @@ export const levenshtein_distance = (a: string, b: string): number => {
209
209
  return prev[short_len]!;
210
210
  };
211
211
 
212
+ /**
213
+ * Escapes a string for use inside a single-quoted JS string literal.
214
+ *
215
+ * Uses a single-pass regex replacement to escape backslashes, single quotes,
216
+ * newlines, carriage returns, and Unicode line/paragraph separators.
217
+ */
218
+ export const escape_js_string = (value: string): string =>
219
+ value.replace(/[\\'\n\r\u2028\u2029]/g, (ch) => {
220
+ switch (ch) {
221
+ case '\\':
222
+ return '\\\\';
223
+ case "'":
224
+ return "\\'";
225
+ case '\n':
226
+ return '\\n';
227
+ case '\r':
228
+ return '\\r';
229
+ case '\u2028':
230
+ return '\\u2028';
231
+ case '\u2029':
232
+ return '\\u2029';
233
+ default:
234
+ return ch;
235
+ }
236
+ });
237
+
212
238
  /**
213
239
  * Check if content appears to be binary.
214
240
  *
@@ -217,7 +243,4 @@ export const levenshtein_distance = (a: string, b: string): number => {
217
243
  * @param content - Content to check.
218
244
  * @returns True if content appears to be binary.
219
245
  */
220
- export const is_binary = (content: string): boolean => {
221
- const sample = content.slice(0, 8192);
222
- return sample.includes('\0');
223
- };
246
+ export const string_is_binary = (content: string): boolean => content.slice(0, 8192).includes('\0');
@@ -0,0 +1,329 @@
1
+ /**
2
+ * Shared helper functions for Svelte preprocessors.
3
+ *
4
+ * Provides AST utilities for detecting static content, resolving imports,
5
+ * managing import statements, and escaping strings for Svelte templates.
6
+ * Used by `svelte_preprocess_mdz` in fuz_ui, `svelte_preprocess_fuz_code`
7
+ * in fuz_code, and potentially other Svelte preprocessors.
8
+ *
9
+ * Uses `import type` from `svelte/compiler` for AST types only — no runtime
10
+ * Svelte dependency. Consumers must have `svelte` installed for type resolution.
11
+ *
12
+ * @module
13
+ */
14
+
15
+ import type {Expression, ImportDeclaration, ImportDefaultSpecifier, ImportSpecifier} from 'estree';
16
+ import type {AST} from 'svelte/compiler';
17
+
18
+ /** Import metadata for a single import specifier. */
19
+ export interface PreprocessImportInfo {
20
+ /** The module path to import from. */
21
+ path: string;
22
+ /** Whether this is a default or named import. */
23
+ kind: 'default' | 'named';
24
+ }
25
+
26
+ /** Information about a resolved component import. */
27
+ export interface ResolvedComponentImport {
28
+ /** The `ImportDeclaration` AST node that provides this name. */
29
+ import_node: ImportDeclaration;
30
+ /** The specific import specifier for this name. */
31
+ specifier: ImportSpecifier | ImportDefaultSpecifier;
32
+ }
33
+
34
+ /**
35
+ * Finds an attribute by name on a component AST node.
36
+ *
37
+ * Iterates the node's `attributes` array and returns the first `Attribute`
38
+ * node whose `name` matches. Skips `SpreadAttribute`, directive, and other node types.
39
+ *
40
+ * @param node The component AST node to search.
41
+ * @param name The attribute name to find.
42
+ * @returns The matching `Attribute` node, or `undefined` if not found.
43
+ */
44
+ export const find_attribute = (node: AST.Component, name: string): AST.Attribute | undefined => {
45
+ for (const attr of node.attributes) {
46
+ if (attr.type === 'Attribute' && attr.name === name) {
47
+ return attr;
48
+ }
49
+ }
50
+ return undefined;
51
+ };
52
+
53
+ /**
54
+ * Recursively evaluates an expression AST node to a static string value.
55
+ *
56
+ * Handles string `Literal`, `TemplateLiteral` (including interpolations when all
57
+ * expressions resolve), `BinaryExpression` with `+`, and `Identifier` lookup
58
+ * via an optional bindings map built by `build_static_bindings`.
59
+ * Returns `null` for dynamic expressions, non-string literals, or unsupported node types.
60
+ *
61
+ * @param expr An ESTree expression AST node.
62
+ * @param bindings Optional map of variable names to their resolved static string values.
63
+ * @returns The resolved static string, or `null` if the expression is dynamic.
64
+ */
65
+ export const evaluate_static_expr = (
66
+ expr: Expression,
67
+ bindings?: ReadonlyMap<string, string>,
68
+ ): string | null => {
69
+ if (expr.type === 'Literal' && typeof expr.value === 'string') return expr.value;
70
+ if (expr.type === 'TemplateLiteral') {
71
+ if (expr.expressions.length === 0) {
72
+ return expr.quasis.map((q) => q.value.cooked ?? q.value.raw).join('');
73
+ }
74
+ // Try resolving interpolations through bindings
75
+ const parts: Array<string> = [];
76
+ for (let i = 0; i < expr.quasis.length; i++) {
77
+ const quasi = expr.quasis[i]!;
78
+ parts.push(quasi.value.cooked ?? quasi.value.raw);
79
+ if (i < expr.expressions.length) {
80
+ const val = evaluate_static_expr(expr.expressions[i]!, bindings);
81
+ if (val === null) return null;
82
+ parts.push(val);
83
+ }
84
+ }
85
+ return parts.join('');
86
+ }
87
+ if (expr.type === 'BinaryExpression' && expr.operator === '+') {
88
+ if (expr.left.type === 'PrivateIdentifier') return null;
89
+ const left = evaluate_static_expr(expr.left, bindings);
90
+ if (left === null) return null;
91
+ const right = evaluate_static_expr(expr.right, bindings);
92
+ if (right === null) return null;
93
+ return left + right;
94
+ }
95
+ if (expr.type === 'Identifier' && bindings?.has(expr.name)) {
96
+ return bindings.get(expr.name)!;
97
+ }
98
+ return null;
99
+ };
100
+
101
+ /**
102
+ * Extracts a static string value from a Svelte attribute value AST node.
103
+ *
104
+ * Handles three forms:
105
+ * - Boolean `true` (bare attribute like `inline`) -- returns `null`.
106
+ * - Array with a single `Text` node (quoted attribute like `content="text"`) --
107
+ * returns the text data.
108
+ * - `ExpressionTag` (expression like `content={'text'}`) -- delegates to `evaluate_static_expr`.
109
+ *
110
+ * Returns `null` for null literals, mixed arrays, dynamic expressions, and non-string values.
111
+ *
112
+ * @param value The attribute value from `AST.Attribute['value']`.
113
+ * @param bindings Optional map of variable names to their resolved static string values.
114
+ * @returns The resolved static string, or `null` if the value is dynamic.
115
+ */
116
+ export const extract_static_string = (
117
+ value: AST.Attribute['value'],
118
+ bindings?: ReadonlyMap<string, string>,
119
+ ): string | null => {
120
+ // Boolean attribute (e.g., <Mdz inline />)
121
+ if (value === true) return null;
122
+
123
+ // Plain attribute: content="text"
124
+ if (Array.isArray(value)) {
125
+ const first = value[0];
126
+ if (value.length === 1 && first?.type === 'Text') {
127
+ return first.data;
128
+ }
129
+ return null;
130
+ }
131
+
132
+ // ExpressionTag: content={expr}
133
+ const expr = value.expression;
134
+ // Null literal
135
+ if (expr.type === 'Literal' && expr.value === null) return null;
136
+ return evaluate_static_expr(expr, bindings);
137
+ };
138
+
139
+ /**
140
+ * Builds a map of statically resolvable `const` bindings from a Svelte AST.
141
+ *
142
+ * Scans top-level `const` variable declarations in both instance and module scripts.
143
+ * For each declarator with a plain `Identifier` pattern and a statically evaluable
144
+ * initializer, adds the binding to the map. Processes declarations in source order
145
+ * so that chained references resolve: `const a = 'x'; const b = a;` maps `b` to `'x'`.
146
+ *
147
+ * Skips destructuring patterns, `let`/`var` declarations, and declarations
148
+ * whose initializers reference dynamic values.
149
+ *
150
+ * @param ast The parsed Svelte AST root node.
151
+ * @returns Map of variable names to their resolved static string values.
152
+ */
153
+ export const build_static_bindings = (ast: AST.Root): Map<string, string> => {
154
+ const bindings: Map<string, string> = new Map();
155
+ for (const script of [ast.instance, ast.module]) {
156
+ if (!script) continue;
157
+ for (const node of script.content.body) {
158
+ if (node.type !== 'VariableDeclaration' || node.kind !== 'const') continue;
159
+ for (const declarator of node.declarations) {
160
+ if (declarator.id.type !== 'Identifier') continue;
161
+ if (!declarator.init) continue;
162
+ const value = evaluate_static_expr(declarator.init, bindings);
163
+ if (value !== null) {
164
+ bindings.set(declarator.id.name, value);
165
+ }
166
+ }
167
+ }
168
+ }
169
+ return bindings;
170
+ };
171
+
172
+ /**
173
+ * Resolves local names that import from specified source paths.
174
+ *
175
+ * Scans `ImportDeclaration` nodes in both the instance and module scripts.
176
+ * Handles default, named, and aliased imports. Skips namespace imports.
177
+ * Returns import node references alongside names to support import removal.
178
+ *
179
+ * @param ast The parsed Svelte AST root node.
180
+ * @param component_imports Array of import source paths to match against.
181
+ * @returns Map of local names to their resolved import info.
182
+ */
183
+ export const resolve_component_names = (
184
+ ast: AST.Root,
185
+ component_imports: Array<string>,
186
+ ): Map<string, ResolvedComponentImport> => {
187
+ const names: Map<string, ResolvedComponentImport> = new Map();
188
+ for (const script of [ast.instance, ast.module]) {
189
+ if (!script) continue;
190
+ for (const node of script.content.body) {
191
+ if (node.type !== 'ImportDeclaration') continue;
192
+ if (!component_imports.includes(node.source.value as string)) continue;
193
+ for (const specifier of node.specifiers) {
194
+ if (specifier.type === 'ImportNamespaceSpecifier') continue;
195
+ names.set(specifier.local.name, {import_node: node, specifier});
196
+ }
197
+ }
198
+ }
199
+ return names;
200
+ };
201
+
202
+ /**
203
+ * Finds the position to insert new import statements within a script block.
204
+ *
205
+ * Returns the end position of the last `ImportDeclaration`, or the start
206
+ * of the script body content if no imports exist.
207
+ *
208
+ * @param script The parsed `AST.Script` node.
209
+ * @returns The character position where new imports should be inserted.
210
+ */
211
+ export const find_import_insert_position = (script: AST.Script): number => {
212
+ let last_import_end = -1;
213
+ for (const node of script.content.body) {
214
+ if (node.type === 'ImportDeclaration') {
215
+ // Svelte's parser always provides position data on AST nodes
216
+ last_import_end = (node as unknown as AST.BaseNode).end;
217
+ }
218
+ }
219
+ if (last_import_end !== -1) {
220
+ return last_import_end;
221
+ }
222
+ return (script.content as unknown as AST.BaseNode).start;
223
+ };
224
+
225
+ /**
226
+ * Generates indented import statement lines from an import map.
227
+ *
228
+ * Default imports produce `import Name from 'path';` lines.
229
+ * Named imports are grouped by path into `import {a, b} from 'path';` lines.
230
+ *
231
+ * @param imports Map of local names to their import info.
232
+ * @param indent Indentation prefix for each line. @default '\t'
233
+ * @returns A string of newline-separated import statements.
234
+ */
235
+ export const generate_import_lines = (
236
+ imports: Map<string, PreprocessImportInfo>,
237
+ indent: string = '\t',
238
+ ): string => {
239
+ const default_imports: Array<[string, string]> = [];
240
+ const named_by_path: Map<string, Array<string>> = new Map();
241
+
242
+ for (const [name, {path, kind}] of imports) {
243
+ if (kind === 'default') {
244
+ default_imports.push([name, path]);
245
+ } else {
246
+ let names = named_by_path.get(path);
247
+ if (!names) {
248
+ names = [];
249
+ named_by_path.set(path, names);
250
+ }
251
+ names.push(name);
252
+ }
253
+ }
254
+
255
+ const lines: Array<string> = [];
256
+ for (const [name, path] of default_imports) {
257
+ lines.push(`${indent}import ${name} from '${path}';`);
258
+ }
259
+ for (const [path, names] of named_by_path) {
260
+ lines.push(`${indent}import {${names.join(', ')}} from '${path}';`);
261
+ }
262
+ return lines.join('\n');
263
+ };
264
+
265
+ /**
266
+ * Checks if an identifier with the given name appears anywhere in an AST subtree.
267
+ *
268
+ * Recursively walks all object and array properties of the tree, matching
269
+ * ESTree `Identifier` nodes (`{type: 'Identifier', name}`). Nodes in the
270
+ * `skip` set are excluded from traversal — used to skip `ImportDeclaration`
271
+ * nodes so the import's own specifier identifier doesn't false-positive.
272
+ *
273
+ * Safe for Svelte template ASTs: `Component.name` is a plain string property
274
+ * (not an `Identifier` node), so `<Mdz>` tags do not produce false matches.
275
+ *
276
+ * @param node The AST subtree to search.
277
+ * @param name The identifier name to look for.
278
+ * @param skip Set of AST nodes to skip during traversal.
279
+ * @returns `true` if a matching `Identifier` node is found.
280
+ */
281
+ export const has_identifier_in_tree = (
282
+ node: unknown,
283
+ name: string,
284
+ skip?: Set<unknown>,
285
+ ): boolean => {
286
+ if (node === null || node === undefined || typeof node !== 'object') return false;
287
+ if (skip?.has(node)) return false;
288
+ if (Array.isArray(node)) {
289
+ return node.some((child) => has_identifier_in_tree(child, name, skip));
290
+ }
291
+ const record = node as Record<string, unknown>;
292
+ if (record.type === 'Identifier' && record.name === name) return true;
293
+ for (const key of Object.keys(record)) {
294
+ if (has_identifier_in_tree(record[key], name, skip)) return true;
295
+ }
296
+ return false;
297
+ };
298
+
299
+ /**
300
+ * Escapes text for safe embedding in Svelte template markup.
301
+ *
302
+ * Uses a single-pass regex replacement to avoid corruption that occurs with sequential
303
+ * `.replace()` calls (where the second replace matches characters introduced by the first).
304
+ *
305
+ * Escapes four characters:
306
+ * - `{` → `{'{'}` and `}` → `{'}'}` — prevents Svelte expression interpretation
307
+ * - `<` → `&lt;` — prevents HTML/Svelte tag interpretation
308
+ * - `&` → `&amp;` — prevents HTML entity interpretation
309
+ *
310
+ * The `&` escaping is necessary because runtime `MdzNodeView.svelte` renders text
311
+ * with `{node.content}` (a Svelte expression), which auto-escapes `&` to `&amp;`.
312
+ * The preprocessor emits raw template text where `&` is NOT auto-escaped, so
313
+ * manual escaping is required to match the runtime behavior.
314
+ */
315
+ export const escape_svelte_text = (text: string): string =>
316
+ text.replace(/[{}<&]/g, (ch) => {
317
+ switch (ch) {
318
+ case '{':
319
+ return "{'{'}";
320
+ case '}':
321
+ return "{'}'}";
322
+ case '<':
323
+ return '&lt;';
324
+ case '&':
325
+ return '&amp;';
326
+ default:
327
+ return ch;
328
+ }
329
+ });