@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/src/lib/string.ts CHANGED
@@ -208,3 +208,39 @@ export const levenshtein_distance = (a: string, b: string): number => {
208
208
 
209
209
  return prev[short_len]!;
210
210
  };
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
+
238
+ /**
239
+ * Check if content appears to be binary.
240
+ *
241
+ * Checks for null bytes in the first 8KB of content.
242
+ *
243
+ * @param content - Content to check.
244
+ * @returns True if content appears to be binary.
245
+ */
246
+ export const string_is_binary = (content: string): boolean => content.slice(0, 8192).includes('\0');
@@ -0,0 +1,270 @@
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` without interpolation, and
57
+ * `BinaryExpression` with the `+` operator (string concatenation).
58
+ * Returns `null` for dynamic expressions, non-string literals, or unsupported node types.
59
+ *
60
+ * @param expr An ESTree expression AST node.
61
+ * @returns The resolved static string, or `null` if the expression is dynamic.
62
+ */
63
+ export const evaluate_static_expr = (expr: Expression): string | null => {
64
+ if (expr.type === 'Literal' && typeof expr.value === 'string') return expr.value;
65
+ if (expr.type === 'TemplateLiteral' && expr.expressions.length === 0) {
66
+ return expr.quasis.map((q) => q.value.cooked ?? q.value.raw).join('');
67
+ }
68
+ if (expr.type === 'BinaryExpression' && expr.operator === '+') {
69
+ if (expr.left.type === 'PrivateIdentifier') return null;
70
+ const left = evaluate_static_expr(expr.left);
71
+ if (left === null) return null;
72
+ const right = evaluate_static_expr(expr.right);
73
+ if (right === null) return null;
74
+ return left + right;
75
+ }
76
+ return null;
77
+ };
78
+
79
+ /**
80
+ * Extracts a static string value from a Svelte attribute value AST node.
81
+ *
82
+ * Handles three forms:
83
+ * - Boolean `true` (bare attribute like `inline`) -- returns `null`.
84
+ * - Array with a single `Text` node (quoted attribute like `content="text"`) --
85
+ * returns the text data.
86
+ * - `ExpressionTag` (expression like `content={'text'}`) -- delegates to `evaluate_static_expr`.
87
+ *
88
+ * Returns `null` for null literals, mixed arrays, dynamic expressions, and non-string values.
89
+ *
90
+ * @param value The attribute value from `AST.Attribute['value']`.
91
+ * @returns The resolved static string, or `null` if the value is dynamic.
92
+ */
93
+ export const extract_static_string = (value: AST.Attribute['value']): string | null => {
94
+ // Boolean attribute (e.g., <Mdz inline />)
95
+ if (value === true) return null;
96
+
97
+ // Plain attribute: content="text"
98
+ if (Array.isArray(value)) {
99
+ const first = value[0];
100
+ if (value.length === 1 && first?.type === 'Text') {
101
+ return first.data;
102
+ }
103
+ return null;
104
+ }
105
+
106
+ // ExpressionTag: content={expr}
107
+ const expr = value.expression;
108
+ // Null literal
109
+ if (expr.type === 'Literal' && expr.value === null) return null;
110
+ return evaluate_static_expr(expr);
111
+ };
112
+
113
+ /**
114
+ * Resolves local names that import from specified source paths.
115
+ *
116
+ * Scans `ImportDeclaration` nodes in both the instance and module scripts.
117
+ * Handles default, named, and aliased imports. Skips namespace imports.
118
+ * Returns import node references alongside names to support import removal.
119
+ *
120
+ * @param ast The parsed Svelte AST root node.
121
+ * @param component_imports Array of import source paths to match against.
122
+ * @returns Map of local names to their resolved import info.
123
+ */
124
+ export const resolve_component_names = (
125
+ ast: AST.Root,
126
+ component_imports: Array<string>,
127
+ ): Map<string, ResolvedComponentImport> => {
128
+ const names: Map<string, ResolvedComponentImport> = new Map();
129
+ for (const script of [ast.instance, ast.module]) {
130
+ if (!script) continue;
131
+ for (const node of script.content.body) {
132
+ if (node.type !== 'ImportDeclaration') continue;
133
+ if (!component_imports.includes(node.source.value as string)) continue;
134
+ for (const specifier of node.specifiers) {
135
+ if (specifier.type === 'ImportNamespaceSpecifier') continue;
136
+ names.set(specifier.local.name, {import_node: node, specifier});
137
+ }
138
+ }
139
+ }
140
+ return names;
141
+ };
142
+
143
+ /**
144
+ * Finds the position to insert new import statements within a script block.
145
+ *
146
+ * Returns the end position of the last `ImportDeclaration`, or the start
147
+ * of the script body content if no imports exist.
148
+ *
149
+ * @param script The parsed `AST.Script` node.
150
+ * @returns The character position where new imports should be inserted.
151
+ */
152
+ export const find_import_insert_position = (script: AST.Script): number => {
153
+ let last_import_end = -1;
154
+ for (const node of script.content.body) {
155
+ if (node.type === 'ImportDeclaration') {
156
+ // Svelte's parser always provides position data on AST nodes
157
+ last_import_end = (node as unknown as AST.BaseNode).end;
158
+ }
159
+ }
160
+ if (last_import_end !== -1) {
161
+ return last_import_end;
162
+ }
163
+ return (script.content as unknown as AST.BaseNode).start;
164
+ };
165
+
166
+ /**
167
+ * Generates indented import statement lines from an import map.
168
+ *
169
+ * Default imports produce `import Name from 'path';` lines.
170
+ * Named imports are grouped by path into `import {a, b} from 'path';` lines.
171
+ *
172
+ * @param imports Map of local names to their import info.
173
+ * @param indent Indentation prefix for each line. @default '\t'
174
+ * @returns A string of newline-separated import statements.
175
+ */
176
+ export const generate_import_lines = (
177
+ imports: Map<string, PreprocessImportInfo>,
178
+ indent: string = '\t',
179
+ ): string => {
180
+ const default_imports: Array<[string, string]> = [];
181
+ const named_by_path: Map<string, Array<string>> = new Map();
182
+
183
+ for (const [name, {path, kind}] of imports) {
184
+ if (kind === 'default') {
185
+ default_imports.push([name, path]);
186
+ } else {
187
+ let names = named_by_path.get(path);
188
+ if (!names) {
189
+ names = [];
190
+ named_by_path.set(path, names);
191
+ }
192
+ names.push(name);
193
+ }
194
+ }
195
+
196
+ const lines: Array<string> = [];
197
+ for (const [name, path] of default_imports) {
198
+ lines.push(`${indent}import ${name} from '${path}';`);
199
+ }
200
+ for (const [path, names] of named_by_path) {
201
+ lines.push(`${indent}import {${names.join(', ')}} from '${path}';`);
202
+ }
203
+ return lines.join('\n');
204
+ };
205
+
206
+ /**
207
+ * Checks if an identifier with the given name appears anywhere in an AST subtree.
208
+ *
209
+ * Recursively walks all object and array properties of the tree, matching
210
+ * ESTree `Identifier` nodes (`{type: 'Identifier', name}`). Nodes in the
211
+ * `skip` set are excluded from traversal — used to skip `ImportDeclaration`
212
+ * nodes so the import's own specifier identifier doesn't false-positive.
213
+ *
214
+ * Safe for Svelte template ASTs: `Component.name` is a plain string property
215
+ * (not an `Identifier` node), so `<Mdz>` tags do not produce false matches.
216
+ *
217
+ * @param node The AST subtree to search.
218
+ * @param name The identifier name to look for.
219
+ * @param skip Set of AST nodes to skip during traversal.
220
+ * @returns `true` if a matching `Identifier` node is found.
221
+ */
222
+ export const has_identifier_in_tree = (
223
+ node: unknown,
224
+ name: string,
225
+ skip?: Set<unknown>,
226
+ ): boolean => {
227
+ if (node === null || node === undefined || typeof node !== 'object') return false;
228
+ if (skip?.has(node)) return false;
229
+ if (Array.isArray(node)) {
230
+ return node.some((child) => has_identifier_in_tree(child, name, skip));
231
+ }
232
+ const record = node as Record<string, unknown>;
233
+ if (record.type === 'Identifier' && record.name === name) return true;
234
+ for (const key of Object.keys(record)) {
235
+ if (has_identifier_in_tree(record[key], name, skip)) return true;
236
+ }
237
+ return false;
238
+ };
239
+
240
+ /**
241
+ * Escapes text for safe embedding in Svelte template markup.
242
+ *
243
+ * Uses a single-pass regex replacement to avoid corruption that occurs with sequential
244
+ * `.replace()` calls (where the second replace matches characters introduced by the first).
245
+ *
246
+ * Escapes four characters:
247
+ * - `{` → `{'{'}` and `}` → `{'}'}` — prevents Svelte expression interpretation
248
+ * - `<` → `&lt;` — prevents HTML/Svelte tag interpretation
249
+ * - `&` → `&amp;` — prevents HTML entity interpretation
250
+ *
251
+ * The `&` escaping is necessary because runtime `MdzNodeView.svelte` renders text
252
+ * with `{node.content}` (a Svelte expression), which auto-escapes `&` to `&amp;`.
253
+ * The preprocessor emits raw template text where `&` is NOT auto-escaped, so
254
+ * manual escaping is required to match the runtime behavior.
255
+ */
256
+ export const escape_svelte_text = (text: string): string =>
257
+ text.replace(/[{}<&]/g, (ch) => {
258
+ switch (ch) {
259
+ case '{':
260
+ return "{'{'}";
261
+ case '}':
262
+ return "{'}'}";
263
+ case '<':
264
+ return '&lt;';
265
+ case '&':
266
+ return '&amp;';
267
+ default:
268
+ return ch;
269
+ }
270
+ });