@fuzdev/fuz_util 0.48.3 → 0.49.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/sort.js ADDED
@@ -0,0 +1,123 @@
1
+ /**
2
+ * Generic topological sort using Kahn's algorithm.
3
+ *
4
+ * Orders items so that dependencies come before dependents.
5
+ * Works with any item type that has `id` and optional `depends_on`.
6
+ *
7
+ * @module
8
+ */
9
+ /**
10
+ * Sort items by their dependencies using Kahn's algorithm.
11
+ *
12
+ * Returns items ordered so that dependencies come before dependents.
13
+ * If a cycle is detected, returns an error with the cycle path.
14
+ *
15
+ * @param items - Array of items to sort.
16
+ * @param label - Label for error messages (e.g. "resource", "step").
17
+ * @returns Sorted items or error if cycle detected.
18
+ */
19
+ export const topological_sort = (items, label = 'item') => {
20
+ // Build id -> item map
21
+ const item_map = new Map();
22
+ for (const item of items) {
23
+ if (item_map.has(item.id)) {
24
+ return { ok: false, error: `duplicate ${label} id: ${item.id}` };
25
+ }
26
+ item_map.set(item.id, item);
27
+ }
28
+ // Validate all dependencies exist and count dependents per item
29
+ // dependents_count[X] = how many items list X in their depends_on
30
+ const dependents_count = new Map();
31
+ for (const item of items) {
32
+ dependents_count.set(item.id, 0);
33
+ }
34
+ for (const item of items) {
35
+ const deps = item.depends_on ?? [];
36
+ for (const dep of deps) {
37
+ if (!item_map.has(dep)) {
38
+ return { ok: false, error: `${label} "${item.id}" depends on unknown ${label} "${dep}"` };
39
+ }
40
+ dependents_count.set(dep, dependents_count.get(dep) + 1);
41
+ }
42
+ }
43
+ // Start from leaf items (nothing depends on them), work toward roots
44
+ const queue = [];
45
+ for (const [id, count] of dependents_count) {
46
+ if (count === 0) {
47
+ queue.push(id);
48
+ }
49
+ }
50
+ // Process leaves first, then items whose dependents are all processed
51
+ const sorted = [];
52
+ const visited = new Set();
53
+ while (queue.length > 0) {
54
+ const id = queue.shift();
55
+ if (visited.has(id))
56
+ continue;
57
+ visited.add(id);
58
+ sorted.push(item_map.get(id));
59
+ // This item is processed — decrement its dependencies' dependent counts
60
+ const deps = item_map.get(id).depends_on ?? [];
61
+ for (const dep of deps) {
62
+ const new_count = dependents_count.get(dep) - 1;
63
+ dependents_count.set(dep, new_count);
64
+ if (new_count === 0) {
65
+ queue.push(dep);
66
+ }
67
+ }
68
+ }
69
+ // Check for cycle
70
+ if (sorted.length !== items.length) {
71
+ const unvisited = items.filter((item) => !visited.has(item.id)).map((item) => item.id);
72
+ const cycle = find_cycle(item_map, unvisited);
73
+ return {
74
+ ok: false,
75
+ error: `dependency cycle detected: ${cycle.join(' -> ')}`,
76
+ cycle,
77
+ };
78
+ }
79
+ // Reverse: leaves were processed first, but dependencies must come first in output
80
+ sorted.reverse();
81
+ return { ok: true, sorted };
82
+ };
83
+ /**
84
+ * Find a cycle in the dependency graph starting from unvisited nodes.
85
+ * Used for error reporting when a cycle is detected.
86
+ */
87
+ const find_cycle = (item_map, unvisited) => {
88
+ const unvisited_set = new Set(unvisited);
89
+ // DFS to find cycle
90
+ const path = [];
91
+ const in_path = new Set();
92
+ const dfs = (id) => {
93
+ if (in_path.has(id)) {
94
+ path.push(id);
95
+ return true;
96
+ }
97
+ if (!unvisited_set.has(id))
98
+ return false;
99
+ in_path.add(id);
100
+ path.push(id);
101
+ const item = item_map.get(id);
102
+ const deps = item?.depends_on ?? [];
103
+ for (const dep of deps) {
104
+ if (dfs(dep))
105
+ return true;
106
+ }
107
+ in_path.delete(id);
108
+ path.pop();
109
+ return false;
110
+ };
111
+ if (unvisited.length > 0) {
112
+ dfs(unvisited[0]);
113
+ }
114
+ // Extract just the cycle portion
115
+ if (path.length > 0) {
116
+ const last = path[path.length - 1];
117
+ const cycle_start = path.indexOf(last);
118
+ if (cycle_start < path.length - 1) {
119
+ return path.slice(cycle_start);
120
+ }
121
+ }
122
+ return unvisited;
123
+ };
@@ -16,10 +16,10 @@ import { z } from 'zod';
16
16
  export declare const DeclarationKind: z.ZodEnum<{
17
17
  function: "function";
18
18
  type: "type";
19
- constructor: "constructor";
20
19
  json: "json";
21
20
  variable: "variable";
22
21
  class: "class";
22
+ constructor: "constructor";
23
23
  component: "component";
24
24
  css: "css";
25
25
  }>;
@@ -80,10 +80,10 @@ export declare const DeclarationJson: z.ZodObject<{
80
80
  kind: z.ZodEnum<{
81
81
  function: "function";
82
82
  type: "type";
83
- constructor: "constructor";
84
83
  json: "json";
85
84
  variable: "variable";
86
85
  class: "class";
86
+ constructor: "constructor";
87
87
  component: "component";
88
88
  css: "css";
89
89
  }>;
@@ -172,10 +172,10 @@ export declare const ModuleJson: z.ZodObject<{
172
172
  kind: z.ZodEnum<{
173
173
  function: "function";
174
174
  type: "type";
175
- constructor: "constructor";
176
175
  json: "json";
177
176
  variable: "variable";
178
177
  class: "class";
178
+ constructor: "constructor";
179
179
  component: "component";
180
180
  css: "css";
181
181
  }>;
@@ -279,10 +279,10 @@ export declare const SourceJson: z.ZodObject<{
279
279
  kind: z.ZodEnum<{
280
280
  function: "function";
281
281
  type: "type";
282
- constructor: "constructor";
283
282
  json: "json";
284
283
  variable: "variable";
285
284
  class: "class";
285
+ constructor: "constructor";
286
286
  component: "component";
287
287
  css: "css";
288
288
  }>;
package/dist/string.d.ts CHANGED
@@ -70,4 +70,20 @@ 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;
80
+ /**
81
+ * Check if content appears to be binary.
82
+ *
83
+ * Checks for null bytes in the first 8KB of content.
84
+ *
85
+ * @param content - Content to check.
86
+ * @returns True if content appears to be binary.
87
+ */
88
+ export declare const string_is_binary: (content: string) => boolean;
73
89
  //# sourceMappingURL=string.d.ts.map
@@ -1 +1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H,eAAO,MAAM,UAAU,GAAI,KAAK,MAAM,KAAG,MAAsD,CAAC;AAEhG;;;;GAIG;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,3 +191,36 @@ 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
+ });
218
+ /**
219
+ * Check if content appears to be binary.
220
+ *
221
+ * Checks for null bytes in the first 8KB of content.
222
+ *
223
+ * @param content - Content to check.
224
+ * @returns True if content appears to be binary.
225
+ */
226
+ export const string_is_binary = (content) => content.slice(0, 8192).includes('\0');
@@ -0,0 +1,134 @@
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` without interpolation, and
45
+ * `BinaryExpression` with the `+` operator (string concatenation).
46
+ * Returns `null` for dynamic expressions, non-string literals, or unsupported node types.
47
+ *
48
+ * @param expr An ESTree expression AST node.
49
+ * @returns The resolved static string, or `null` if the expression is dynamic.
50
+ */
51
+ export declare const evaluate_static_expr: (expr: Expression) => string | null;
52
+ /**
53
+ * Extracts a static string value from a Svelte attribute value AST node.
54
+ *
55
+ * Handles three forms:
56
+ * - Boolean `true` (bare attribute like `inline`) -- returns `null`.
57
+ * - Array with a single `Text` node (quoted attribute like `content="text"`) --
58
+ * returns the text data.
59
+ * - `ExpressionTag` (expression like `content={'text'}`) -- delegates to `evaluate_static_expr`.
60
+ *
61
+ * Returns `null` for null literals, mixed arrays, dynamic expressions, and non-string values.
62
+ *
63
+ * @param value The attribute value from `AST.Attribute['value']`.
64
+ * @returns The resolved static string, or `null` if the value is dynamic.
65
+ */
66
+ export declare const extract_static_string: (value: AST.Attribute["value"]) => string | null;
67
+ /**
68
+ * Resolves local names that import from specified source paths.
69
+ *
70
+ * Scans `ImportDeclaration` nodes in both the instance and module scripts.
71
+ * Handles default, named, and aliased imports. Skips namespace imports.
72
+ * Returns import node references alongside names to support import removal.
73
+ *
74
+ * @param ast The parsed Svelte AST root node.
75
+ * @param component_imports Array of import source paths to match against.
76
+ * @returns Map of local names to their resolved import info.
77
+ */
78
+ export declare const resolve_component_names: (ast: AST.Root, component_imports: Array<string>) => Map<string, ResolvedComponentImport>;
79
+ /**
80
+ * Finds the position to insert new import statements within a script block.
81
+ *
82
+ * Returns the end position of the last `ImportDeclaration`, or the start
83
+ * of the script body content if no imports exist.
84
+ *
85
+ * @param script The parsed `AST.Script` node.
86
+ * @returns The character position where new imports should be inserted.
87
+ */
88
+ export declare const find_import_insert_position: (script: AST.Script) => number;
89
+ /**
90
+ * Generates indented import statement lines from an import map.
91
+ *
92
+ * Default imports produce `import Name from 'path';` lines.
93
+ * Named imports are grouped by path into `import {a, b} from 'path';` lines.
94
+ *
95
+ * @param imports Map of local names to their import info.
96
+ * @param indent Indentation prefix for each line. @default '\t'
97
+ * @returns A string of newline-separated import statements.
98
+ */
99
+ export declare const generate_import_lines: (imports: Map<string, PreprocessImportInfo>, indent?: string) => string;
100
+ /**
101
+ * Checks if an identifier with the given name appears anywhere in an AST subtree.
102
+ *
103
+ * Recursively walks all object and array properties of the tree, matching
104
+ * ESTree `Identifier` nodes (`{type: 'Identifier', name}`). Nodes in the
105
+ * `skip` set are excluded from traversal — used to skip `ImportDeclaration`
106
+ * nodes so the import's own specifier identifier doesn't false-positive.
107
+ *
108
+ * Safe for Svelte template ASTs: `Component.name` is a plain string property
109
+ * (not an `Identifier` node), so `<Mdz>` tags do not produce false matches.
110
+ *
111
+ * @param node The AST subtree to search.
112
+ * @param name The identifier name to look for.
113
+ * @param skip Set of AST nodes to skip during traversal.
114
+ * @returns `true` if a matching `Identifier` node is found.
115
+ */
116
+ export declare const has_identifier_in_tree: (node: unknown, name: string, skip?: Set<unknown>) => boolean;
117
+ /**
118
+ * Escapes text for safe embedding in Svelte template markup.
119
+ *
120
+ * Uses a single-pass regex replacement to avoid corruption that occurs with sequential
121
+ * `.replace()` calls (where the second replace matches characters introduced by the first).
122
+ *
123
+ * Escapes four characters:
124
+ * - `{` → `{'{'}` and `}` → `{'}'}` — prevents Svelte expression interpretation
125
+ * - `<` → `&lt;` — prevents HTML/Svelte tag interpretation
126
+ * - `&` → `&amp;` — prevents HTML entity interpretation
127
+ *
128
+ * The `&` escaping is necessary because runtime `MdzNodeView.svelte` renders text
129
+ * with `{node.content}` (a Svelte expression), which auto-escapes `&` to `&amp;`.
130
+ * The preprocessor emits raw template text where `&` is NOT auto-escaped, so
131
+ * manual escaping is required to match the runtime behavior.
132
+ */
133
+ export declare const escape_svelte_text: (text: string) => string;
134
+ //# 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;A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AAO,CAAC,KACjB,OAYF,CAAC;AAEF;;;;;;;;;;;;;;;GAeG;AACH,eAAO,MAAM,kBAAkB,GAAI,MAAM,MAAM,KAAG,MAc/C,CAAC"}
@@ -0,0 +1,243 @@
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` without interpolation, and
36
+ * `BinaryExpression` with the `+` operator (string concatenation).
37
+ * Returns `null` for dynamic expressions, non-string literals, or unsupported node types.
38
+ *
39
+ * @param expr An ESTree expression AST node.
40
+ * @returns The resolved static string, or `null` if the expression is dynamic.
41
+ */
42
+ export const evaluate_static_expr = (expr) => {
43
+ if (expr.type === 'Literal' && typeof expr.value === 'string')
44
+ return expr.value;
45
+ if (expr.type === 'TemplateLiteral' && expr.expressions.length === 0) {
46
+ return expr.quasis.map((q) => q.value.cooked ?? q.value.raw).join('');
47
+ }
48
+ if (expr.type === 'BinaryExpression' && expr.operator === '+') {
49
+ if (expr.left.type === 'PrivateIdentifier')
50
+ return null;
51
+ const left = evaluate_static_expr(expr.left);
52
+ if (left === null)
53
+ return null;
54
+ const right = evaluate_static_expr(expr.right);
55
+ if (right === null)
56
+ return null;
57
+ return left + right;
58
+ }
59
+ return null;
60
+ };
61
+ /**
62
+ * Extracts a static string value from a Svelte attribute value AST node.
63
+ *
64
+ * Handles three forms:
65
+ * - Boolean `true` (bare attribute like `inline`) -- returns `null`.
66
+ * - Array with a single `Text` node (quoted attribute like `content="text"`) --
67
+ * returns the text data.
68
+ * - `ExpressionTag` (expression like `content={'text'}`) -- delegates to `evaluate_static_expr`.
69
+ *
70
+ * Returns `null` for null literals, mixed arrays, dynamic expressions, and non-string values.
71
+ *
72
+ * @param value The attribute value from `AST.Attribute['value']`.
73
+ * @returns The resolved static string, or `null` if the value is dynamic.
74
+ */
75
+ export const extract_static_string = (value) => {
76
+ // Boolean attribute (e.g., <Mdz inline />)
77
+ if (value === true)
78
+ return null;
79
+ // Plain attribute: content="text"
80
+ if (Array.isArray(value)) {
81
+ const first = value[0];
82
+ if (value.length === 1 && first?.type === 'Text') {
83
+ return first.data;
84
+ }
85
+ return null;
86
+ }
87
+ // ExpressionTag: content={expr}
88
+ const expr = value.expression;
89
+ // Null literal
90
+ if (expr.type === 'Literal' && expr.value === null)
91
+ return null;
92
+ return evaluate_static_expr(expr);
93
+ };
94
+ /**
95
+ * Resolves local names that import from specified source paths.
96
+ *
97
+ * Scans `ImportDeclaration` nodes in both the instance and module scripts.
98
+ * Handles default, named, and aliased imports. Skips namespace imports.
99
+ * Returns import node references alongside names to support import removal.
100
+ *
101
+ * @param ast The parsed Svelte AST root node.
102
+ * @param component_imports Array of import source paths to match against.
103
+ * @returns Map of local names to their resolved import info.
104
+ */
105
+ export const resolve_component_names = (ast, component_imports) => {
106
+ const names = new Map();
107
+ for (const script of [ast.instance, ast.module]) {
108
+ if (!script)
109
+ continue;
110
+ for (const node of script.content.body) {
111
+ if (node.type !== 'ImportDeclaration')
112
+ continue;
113
+ if (!component_imports.includes(node.source.value))
114
+ continue;
115
+ for (const specifier of node.specifiers) {
116
+ if (specifier.type === 'ImportNamespaceSpecifier')
117
+ continue;
118
+ names.set(specifier.local.name, { import_node: node, specifier });
119
+ }
120
+ }
121
+ }
122
+ return names;
123
+ };
124
+ /**
125
+ * Finds the position to insert new import statements within a script block.
126
+ *
127
+ * Returns the end position of the last `ImportDeclaration`, or the start
128
+ * of the script body content if no imports exist.
129
+ *
130
+ * @param script The parsed `AST.Script` node.
131
+ * @returns The character position where new imports should be inserted.
132
+ */
133
+ export const find_import_insert_position = (script) => {
134
+ let last_import_end = -1;
135
+ for (const node of script.content.body) {
136
+ if (node.type === 'ImportDeclaration') {
137
+ // Svelte's parser always provides position data on AST nodes
138
+ last_import_end = node.end;
139
+ }
140
+ }
141
+ if (last_import_end !== -1) {
142
+ return last_import_end;
143
+ }
144
+ return script.content.start;
145
+ };
146
+ /**
147
+ * Generates indented import statement lines from an import map.
148
+ *
149
+ * Default imports produce `import Name from 'path';` lines.
150
+ * Named imports are grouped by path into `import {a, b} from 'path';` lines.
151
+ *
152
+ * @param imports Map of local names to their import info.
153
+ * @param indent Indentation prefix for each line. @default '\t'
154
+ * @returns A string of newline-separated import statements.
155
+ */
156
+ export const generate_import_lines = (imports, indent = '\t') => {
157
+ const default_imports = [];
158
+ const named_by_path = new Map();
159
+ for (const [name, { path, kind }] of imports) {
160
+ if (kind === 'default') {
161
+ default_imports.push([name, path]);
162
+ }
163
+ else {
164
+ let names = named_by_path.get(path);
165
+ if (!names) {
166
+ names = [];
167
+ named_by_path.set(path, names);
168
+ }
169
+ names.push(name);
170
+ }
171
+ }
172
+ const lines = [];
173
+ for (const [name, path] of default_imports) {
174
+ lines.push(`${indent}import ${name} from '${path}';`);
175
+ }
176
+ for (const [path, names] of named_by_path) {
177
+ lines.push(`${indent}import {${names.join(', ')}} from '${path}';`);
178
+ }
179
+ return lines.join('\n');
180
+ };
181
+ /**
182
+ * Checks if an identifier with the given name appears anywhere in an AST subtree.
183
+ *
184
+ * Recursively walks all object and array properties of the tree, matching
185
+ * ESTree `Identifier` nodes (`{type: 'Identifier', name}`). Nodes in the
186
+ * `skip` set are excluded from traversal — used to skip `ImportDeclaration`
187
+ * nodes so the import's own specifier identifier doesn't false-positive.
188
+ *
189
+ * Safe for Svelte template ASTs: `Component.name` is a plain string property
190
+ * (not an `Identifier` node), so `<Mdz>` tags do not produce false matches.
191
+ *
192
+ * @param node The AST subtree to search.
193
+ * @param name The identifier name to look for.
194
+ * @param skip Set of AST nodes to skip during traversal.
195
+ * @returns `true` if a matching `Identifier` node is found.
196
+ */
197
+ export const has_identifier_in_tree = (node, name, skip) => {
198
+ if (node === null || node === undefined || typeof node !== 'object')
199
+ return false;
200
+ if (skip?.has(node))
201
+ return false;
202
+ if (Array.isArray(node)) {
203
+ return node.some((child) => has_identifier_in_tree(child, name, skip));
204
+ }
205
+ const record = node;
206
+ if (record.type === 'Identifier' && record.name === name)
207
+ return true;
208
+ for (const key of Object.keys(record)) {
209
+ if (has_identifier_in_tree(record[key], name, skip))
210
+ return true;
211
+ }
212
+ return false;
213
+ };
214
+ /**
215
+ * Escapes text for safe embedding in Svelte template markup.
216
+ *
217
+ * Uses a single-pass regex replacement to avoid corruption that occurs with sequential
218
+ * `.replace()` calls (where the second replace matches characters introduced by the first).
219
+ *
220
+ * Escapes four characters:
221
+ * - `{` → `{'{'}` and `}` → `{'}'}` — prevents Svelte expression interpretation
222
+ * - `<` → `&lt;` — prevents HTML/Svelte tag interpretation
223
+ * - `&` → `&amp;` — prevents HTML entity interpretation
224
+ *
225
+ * The `&` escaping is necessary because runtime `MdzNodeView.svelte` renders text
226
+ * with `{node.content}` (a Svelte expression), which auto-escapes `&` to `&amp;`.
227
+ * The preprocessor emits raw template text where `&` is NOT auto-escaped, so
228
+ * manual escaping is required to match the runtime behavior.
229
+ */
230
+ export const escape_svelte_text = (text) => text.replace(/[{}<&]/g, (ch) => {
231
+ switch (ch) {
232
+ case '{':
233
+ return "{'{'}";
234
+ case '}':
235
+ return "{'}'}";
236
+ case '<':
237
+ return '&lt;';
238
+ case '&':
239
+ return '&amp;';
240
+ default:
241
+ return ch;
242
+ }
243
+ });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fuzdev/fuz_util",
3
- "version": "0.48.3",
3
+ "version": "0.49.0",
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
  }
@@ -62,14 +70,15 @@
62
70
  "devDependencies": {
63
71
  "@changesets/changelog-git": "^0.2.1",
64
72
  "@fuzdev/fuz_code": "^0.41.0",
65
- "@fuzdev/fuz_css": "^0.45.0",
66
- "@fuzdev/fuz_ui": "^0.180.0",
73
+ "@fuzdev/fuz_css": "^0.47.0",
74
+ "@fuzdev/fuz_ui": "^0.181.1",
67
75
  "@ryanatkn/eslint-config": "^0.9.0",
68
- "@ryanatkn/gro": "^0.189.3",
76
+ "@ryanatkn/gro": "^0.190.0",
69
77
  "@sveltejs/adapter-static": "^3.0.10",
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",
@@ -79,8 +88,8 @@
79
88
  "fast-deep-equal": "^3.1.3",
80
89
  "prettier": "^3.7.4",
81
90
  "prettier-plugin-svelte": "^3.4.1",
82
- "svelte": "^5.48.5",
83
- "svelte-check": "^4.3.5",
91
+ "svelte": "^5.49.1",
92
+ "svelte-check": "^4.3.6",
84
93
  "tslib": "^2.8.1",
85
94
  "typescript": "^5.9.3",
86
95
  "typescript-eslint": "^8.48.1",