@kivacore/dom-selector-client 0.0.0 → 0.7.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/index.js ADDED
@@ -0,0 +1,1467 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/index.ts
4
+ import { Command } from "commander";
5
+ import chalk2 from "chalk";
6
+
7
+ // package.json
8
+ var name = "@kivacore/dom-selector-client";
9
+ var version = "0.6.3";
10
+
11
+ // src/installer.ts
12
+ import fs from "fs/promises";
13
+ import { spawn } from "child_process";
14
+ import path from "path";
15
+ import { fileURLToPath } from "url";
16
+ import chalk from "chalk";
17
+ var __filename = fileURLToPath(import.meta.url);
18
+ var __dirname = path.dirname(__filename);
19
+ async function fileExists(p) {
20
+ try {
21
+ await fs.stat(p);
22
+ return true;
23
+ } catch {
24
+ return false;
25
+ }
26
+ }
27
+ async function readJson(p) {
28
+ return JSON.parse(await fs.readFile(p, "utf8"));
29
+ }
30
+ async function detectProject(cwd) {
31
+ const pkgPath = path.join(cwd, "package.json");
32
+ if (!await fileExists(pkgPath)) {
33
+ console.warn(chalk.red("package.json not found. Run this in your project root."));
34
+ process.exit(1);
35
+ }
36
+ const pkg = await readJson(pkgPath);
37
+ const deps = { ...pkg.dependencies || {}, ...pkg.devDependencies || {} };
38
+ const isNext = !!deps.next || await fileExists(path.join(cwd, "next.config.js")) || await fileExists(path.join(cwd, "next.config.mjs")) || await fileExists(path.join(cwd, "next.config.ts")) || await fileExists(path.join(cwd, "next.config.cjs"));
39
+ const astroConfigCandidates = [
40
+ "astro.config.mjs",
41
+ "astro.config.ts",
42
+ "astro.config.js"
43
+ ];
44
+ let astroConfigPath = null;
45
+ for (const candidate of astroConfigCandidates) {
46
+ const resolvedPath = path.join(cwd, candidate);
47
+ if (await fileExists(resolvedPath)) {
48
+ astroConfigPath = resolvedPath;
49
+ break;
50
+ }
51
+ }
52
+ const isAstro = !!deps.astro || !!astroConfigPath;
53
+ const hasReact = !!deps.react || !!deps["@astrojs/react"] || !!deps.preact;
54
+ const hasVue = !!deps.vue || !!deps["@astrojs/vue"];
55
+ const framework = hasReact ? "react" : hasVue ? "vue" : "vanilla";
56
+ return {
57
+ astroConfigPath,
58
+ deps,
59
+ framework,
60
+ isAstro,
61
+ isNext,
62
+ pkg
63
+ };
64
+ }
65
+ async function detectPackageManager(cwd) {
66
+ const packageManagerFiles = [
67
+ ["pnpm", "pnpm-lock.yaml"],
68
+ ["bun", "bun.lockb"],
69
+ ["bun", "bun.lock"],
70
+ ["yarn", "yarn.lock"],
71
+ ["npm", "package-lock.json"]
72
+ ];
73
+ for (const [packageManager, filename] of packageManagerFiles) {
74
+ if (await fileExists(path.join(cwd, filename))) {
75
+ return packageManager;
76
+ }
77
+ }
78
+ const userAgent = process.env.npm_config_user_agent ?? "";
79
+ if (userAgent.startsWith("pnpm/")) {
80
+ return "pnpm";
81
+ }
82
+ if (userAgent.startsWith("yarn/")) {
83
+ return "yarn";
84
+ }
85
+ if (userAgent.startsWith("bun/")) {
86
+ return "bun";
87
+ }
88
+ return "npm";
89
+ }
90
+ function createInstallArgs(packageManager, packages) {
91
+ switch (packageManager) {
92
+ case "pnpm":
93
+ return [
94
+ "add",
95
+ "-D",
96
+ ...packages
97
+ ];
98
+ case "yarn":
99
+ return [
100
+ "add",
101
+ "-D",
102
+ ...packages
103
+ ];
104
+ case "bun":
105
+ return [
106
+ "add",
107
+ "-d",
108
+ ...packages
109
+ ];
110
+ case "npm":
111
+ default:
112
+ return [
113
+ "install",
114
+ "-D",
115
+ ...packages
116
+ ];
117
+ }
118
+ }
119
+ async function runPackageManagerInstall(packageManager, cwd, packages) {
120
+ if (packages.length === 0) {
121
+ return;
122
+ }
123
+ const args = createInstallArgs(packageManager, packages);
124
+ await new Promise((resolve, reject) => {
125
+ const child = spawn(packageManager, args, {
126
+ cwd,
127
+ stdio: "inherit"
128
+ });
129
+ child.on("error", reject);
130
+ child.on("exit", (code) => {
131
+ if (code === 0) {
132
+ resolve();
133
+ return;
134
+ }
135
+ reject(new Error(`${packageManager} ${args.join(" ")} exited with code ${code ?? "unknown"}`));
136
+ });
137
+ });
138
+ }
139
+ async function readShippedFile(src, fallback, missingSourceMessage) {
140
+ if (src && await fileExists(src)) {
141
+ return fs.readFile(src, "utf8");
142
+ }
143
+ if (src) {
144
+ console.warn(chalk.yellow(missingSourceMessage));
145
+ }
146
+ return fallback;
147
+ }
148
+ async function syncShippedFile(dest, content) {
149
+ if (await fileExists(dest)) {
150
+ const existing = await fs.readFile(dest, "utf8");
151
+ if (existing === content) {
152
+ console.info(chalk.gray(`${path.basename(dest)} already up to date`));
153
+ return false;
154
+ }
155
+ await fs.writeFile(dest, content, "utf8");
156
+ console.info(chalk.green(`Updated ${path.basename(dest)} in project root`));
157
+ return true;
158
+ }
159
+ await fs.writeFile(dest, content, "utf8");
160
+ console.info(chalk.green(`Created ${path.basename(dest)} in project root`));
161
+ return true;
162
+ }
163
+ function findMatching(code, startIndex, openChar, closeChar) {
164
+ let i = startIndex;
165
+ let depth = 0;
166
+ let inStr = false;
167
+ let strQuote = "";
168
+ let inLineComment = false;
169
+ let inBlockComment = false;
170
+ for (; i < code.length; i++) {
171
+ const ch = code[i];
172
+ const prev = code[i - 1];
173
+ const next = code[i + 1];
174
+ if (inLineComment) {
175
+ if (ch === "\n") inLineComment = false;
176
+ continue;
177
+ }
178
+ if (inBlockComment) {
179
+ if (ch === "*" && next === "/") {
180
+ inBlockComment = false;
181
+ i++;
182
+ }
183
+ continue;
184
+ }
185
+ if (!inStr && ch === "/" && next === "/") {
186
+ inLineComment = true;
187
+ i++;
188
+ continue;
189
+ }
190
+ if (!inStr && ch === "/" && next === "*") {
191
+ inBlockComment = true;
192
+ i++;
193
+ continue;
194
+ }
195
+ if (inStr) {
196
+ if (ch === strQuote && prev !== "\\") {
197
+ inStr = false;
198
+ strQuote = "";
199
+ }
200
+ continue;
201
+ } else {
202
+ if (ch === '"' || ch === "'" || ch === "`") {
203
+ inStr = true;
204
+ strQuote = ch;
205
+ continue;
206
+ }
207
+ }
208
+ if (ch === openChar) {
209
+ depth++;
210
+ continue;
211
+ }
212
+ if (ch === closeChar) {
213
+ depth--;
214
+ if (depth === 0) return i;
215
+ continue;
216
+ }
217
+ }
218
+ return -1;
219
+ }
220
+ function findViteObjectRange(code) {
221
+ const viteKey = /\bvite\s*:\s*\{/g;
222
+ const match = viteKey.exec(code);
223
+ if (!match) return null;
224
+ const braceStart = code.indexOf("{", match.index);
225
+ if (braceStart === -1) return null;
226
+ const braceEnd = findMatching(code, braceStart, "{", "}");
227
+ if (braceEnd === -1) return null;
228
+ return { start: braceStart, end: braceEnd };
229
+ }
230
+ function findPluginsArrayRange(code, viteRange) {
231
+ const slice = code.slice(viteRange.start, viteRange.end + 1);
232
+ const pluginsKeyRe = /plugins\s*:\s*\[/g;
233
+ const m = pluginsKeyRe.exec(slice);
234
+ if (!m) return null;
235
+ const absBracketStart = viteRange.start + slice.indexOf("[", m.index);
236
+ const absBracketEnd = findMatching(code, absBracketStart, "[", "]");
237
+ if (absBracketEnd === -1) return null;
238
+ return { start: absBracketStart, end: absBracketEnd };
239
+ }
240
+ function hasBabelAnnotatePlugin(code) {
241
+ return code.includes("name: 'babel-component-annotate'") || code.includes('name: "babel-component-annotate"');
242
+ }
243
+ function hasHtmlAnnotatePlugin(code) {
244
+ return code.includes("name: 'html-element-annotate'") || code.includes('name: "html-element-annotate"');
245
+ }
246
+ function hasDomSelectorHelperPlugin(code) {
247
+ return code.includes("name: 'dom-selector-helper-inject'") || code.includes('name: "dom-selector-helper-inject"');
248
+ }
249
+ function parseImportStatement(line) {
250
+ const match = line.match(/^\s*import\s+(.+?)\s+from\s+['"]([^'"]+)['"];?\s*$/);
251
+ if (!match) return null;
252
+ return {
253
+ binding: match[1].replace(/\s+/g, " ").trim(),
254
+ source: match[2].trim()
255
+ };
256
+ }
257
+ function isSameImport(a, b) {
258
+ return a.binding === b.binding && a.source === b.source;
259
+ }
260
+ function ensureImport(code, importLine) {
261
+ const lines = code.split("\n");
262
+ const desiredImport = parseImportStatement(importLine);
263
+ let insertIdx = 0;
264
+ const existingMatches = [];
265
+ for (let i = 0; i < lines.length; i++) {
266
+ const trimmed = lines[i].trim();
267
+ const parsedImport = parseImportStatement(lines[i]);
268
+ if (desiredImport && parsedImport && isSameImport(parsedImport, desiredImport)) {
269
+ existingMatches.push(i);
270
+ }
271
+ if (trimmed.startsWith("import ")) {
272
+ insertIdx = i + 1;
273
+ } else if (trimmed.length && !trimmed.startsWith("//")) {
274
+ break;
275
+ }
276
+ }
277
+ if (existingMatches.length > 0) {
278
+ for (let i = existingMatches.length - 1; i >= 1; i--) {
279
+ lines.splice(existingMatches[i], 1);
280
+ }
281
+ return lines.join("\n");
282
+ }
283
+ if (!desiredImport && code.includes(importLine)) return code;
284
+ lines.splice(insertIdx, 0, importLine);
285
+ return lines.join("\n");
286
+ }
287
+ var BABEL_VITE_PLUGIN_OBJ = `{
288
+ name: 'babel-component-annotate',
289
+ enforce: 'pre',
290
+ transform(code, id) {
291
+ if (id.endsWith('.jsx') || id.endsWith('.tsx')) {
292
+ const result = babel.transformSync(code, {
293
+ filename: id,
294
+ plugins: [componentAnnotatePlugin],
295
+ parserOpts: { plugins: ['jsx', 'typescript'] }
296
+ });
297
+ return { code: result?.code || code, map: result?.map || null };
298
+ }
299
+ }
300
+ }`;
301
+ var DOM_SELECTOR_HELPER_PLUGIN = `{
302
+ name: 'dom-selector-helper-inject',
303
+ enforce: 'pre',
304
+ transformIndexHtml(html) {
305
+ if (process.env.NODE_ENV === 'production') return html;
306
+ const scriptTag = '<script type="module" src="/dom-selector-helper.js"></script>';
307
+ if (html.includes('</head>')) {
308
+ return html.replace('</head>', scriptTag + '\\n</head>');
309
+ } else if (html.includes('</body>')) {
310
+ return html.replace('</body>', scriptTag + '\\n</body>');
311
+ }
312
+ return html + scriptTag;
313
+ },
314
+ configureServer(server) {
315
+ server.middlewares.use((req, res, next) => {
316
+ if (req.url === '/dom-selector-helper.js') {
317
+ const fs = require('fs');
318
+ const path = require('path');
319
+ const helperPath = path.join(process.cwd(), 'dom-selector-helper.js');
320
+ if (fs.existsSync(helperPath)) {
321
+ res.setHeader('Content-Type', 'application/javascript');
322
+ res.end(fs.readFileSync(helperPath, 'utf-8'));
323
+ return;
324
+ }
325
+ }
326
+ next();
327
+ });
328
+ }
329
+ }`;
330
+ var HTML_VITE_PLUGIN_OBJ = `{
331
+ name: 'html-element-annotate',
332
+ enforce: 'post',
333
+ transform(code, id) {
334
+ if (process.env.NODE_ENV === 'production') return null;
335
+ if (!id.endsWith('.astro')) return null;
336
+ const cwd = process.cwd();
337
+ const relativeFilePath = path.relative(cwd, id);
338
+ const getLineAndColumn = (code, index) => {
339
+ let line = 1; let column = 0;
340
+ for (let i = 0; i < index; i++) {
341
+ if (code[i] === '\\n') { line++; column = 0; } else { column++; }
342
+ }
343
+ return { line, column: column + 1 };
344
+ };
345
+ const frontmatterMatch = code.match(/^---\\n[\\s\\S]*?\\n---\\n/);
346
+ const frontmatterEnd = frontmatterMatch ? frontmatterMatch[0].length : 0;
347
+ const scriptStyleRegex = /<(script|style)(\\s[^>]*)?>([\\s\\S]*?)<\\/\\1>/gi;
348
+ const protectedRanges = [];
349
+ let m;
350
+ while ((m = scriptStyleRegex.exec(code)) !== null) {
351
+ protectedRanges.push({ start: m.index, end: m.index + m[0].length });
352
+ }
353
+ if (frontmatterEnd > 0) protectedRanges.push({ start: 0, end: frontmatterEnd });
354
+ protectedRanges.sort((a, b) => a.start - b.start);
355
+ let modifiedCode = '';
356
+ let lastEnd = 0;
357
+ const processSection = (section, baseOffset) => section.replace(
358
+ /<(?!\\/|script|style|meta|link|title|head|html|!DOCTYPE)(\\w+)(?![^>]*data-component-)([^>]*)>/g,
359
+ (match, tagName, attributes, offset) => {
360
+ const absoluteOffset = baseOffset + offset;
361
+ const { line, column } = getLineAndColumn(code, absoluteOffset);
362
+ const componentPath = relativeFilePath + ':' + line + ':' + column;
363
+ return '<' + tagName + attributes + ' data-component-name="' + tagName + '" data-component-path="' + componentPath + '">';
364
+ }
365
+ );
366
+ for (const range of protectedRanges) {
367
+ if (lastEnd < range.start) {
368
+ const section = code.substring(lastEnd, range.start);
369
+ modifiedCode += processSection(section, lastEnd);
370
+ }
371
+ modifiedCode += code.substring(range.start, range.end);
372
+ lastEnd = range.end;
373
+ }
374
+ if (lastEnd < code.length) {
375
+ const section = code.substring(lastEnd);
376
+ modifiedCode += processSection(section, lastEnd);
377
+ }
378
+ return { code: modifiedCode, map: null };
379
+ }
380
+ }`;
381
+ async function ensureBabelPluginFile(cwd) {
382
+ const src = path.join(__dirname, "../src/babel-plugin-component-annotate.ts");
383
+ const dest = path.join(cwd, "babel-plugin-component-annotate.ts");
384
+ const content = await readShippedFile(
385
+ src,
386
+ BABEL_PLUGIN_TS,
387
+ `Source plugin not found at ${src}. Using bundled fallback.`
388
+ );
389
+ return syncShippedFile(dest, content);
390
+ }
391
+ async function ensureBabelPluginJsFile(cwd) {
392
+ const dest = path.join(cwd, "babel-plugin-component-annotate.js");
393
+ return syncShippedFile(dest, BABEL_PLUGIN_JS);
394
+ }
395
+ async function ensureDomSelectorHelperFile(cwd) {
396
+ const src = path.join(__dirname, "../src/dom-selector-helper.js");
397
+ const dest = path.join(cwd, "dom-selector-helper.js");
398
+ const content = await readShippedFile(
399
+ src,
400
+ DOM_SELECTOR_HELPER_JS,
401
+ `Source helper not found at ${src}. Using bundled fallback.`
402
+ );
403
+ return syncShippedFile(dest, content);
404
+ }
405
+ function insertIntoPluginsArray(code, viteRange, pluginObjStr) {
406
+ const pluginsRange = findPluginsArrayRange(code, viteRange);
407
+ if (!pluginsRange) {
408
+ const insertionPoint = viteRange.end;
409
+ const before = code.slice(0, insertionPoint);
410
+ const after = code.slice(insertionPoint);
411
+ const lineStart = before.lastIndexOf("\n", viteRange.start) + 1;
412
+ const indent = `${before.slice(lineStart, viteRange.start).match(/^\s*/)?.[0]} ` || " ";
413
+ const needsComma = /[^,{]\s*$/.test(
414
+ before.slice(before.lastIndexOf("{", viteRange.start), insertionPoint)
415
+ );
416
+ const comma = needsComma ? "," : "";
417
+ const addition = `
418
+ ${indent}plugins: [
419
+ ${indent} ${pluginObjStr}
420
+ ${indent}]${comma}
421
+ `;
422
+ return before + addition + after;
423
+ } else {
424
+ const before = code.slice(0, pluginsRange.end);
425
+ const after = code.slice(pluginsRange.end);
426
+ const between = code.slice(pluginsRange.start + 1, pluginsRange.end).trim();
427
+ const prefix = between.length ? ",\n" : "\n";
428
+ const viteSlice = code.slice(viteRange.start, pluginsRange.start);
429
+ const lineStart = viteSlice.lastIndexOf("\n") + 1;
430
+ const baseIndent = `${viteSlice.slice(lineStart).match(/^\s*/)?.[0]} ` || " ";
431
+ const insertion = `${prefix}${baseIndent}${pluginObjStr}
432
+ `;
433
+ return before + insertion + after;
434
+ }
435
+ }
436
+ async function modifyAstroConfig(astroConfigPath, framework, cwd) {
437
+ let code = await fs.readFile(astroConfigPath, "utf8");
438
+ const original = code;
439
+ let changed = false;
440
+ const viteRange = findViteObjectRange(code);
441
+ if (!viteRange) {
442
+ console.warn(chalk.yellow("Could not find vite: {} block in astro.config. Skipping modifications."));
443
+ return false;
444
+ }
445
+ if (!hasDomSelectorHelperPlugin(code)) {
446
+ code = insertIntoPluginsArray(code, viteRange, DOM_SELECTOR_HELPER_PLUGIN);
447
+ console.info(chalk.green("Added dom-selector-helper-inject plugin to astro.config"));
448
+ }
449
+ if (framework === "react") {
450
+ code = ensureImport(code, 'import componentAnnotatePlugin from "./babel-plugin-component-annotate";');
451
+ code = ensureImport(code, "import * as babel from '@babel/core';");
452
+ if (!hasBabelAnnotatePlugin(code)) {
453
+ code = insertIntoPluginsArray(code, viteRange, BABEL_VITE_PLUGIN_OBJ);
454
+ console.info(chalk.green("Added babel-component-annotate Vite plugin to astro.config"));
455
+ }
456
+ changed = await ensureBabelPluginFile(cwd) || changed;
457
+ } else if (framework === "vanilla") {
458
+ if (!code.includes("import * as path from 'path'") && !code.includes("import * as path from 'node:path'")) {
459
+ code = ensureImport(code, "import * as path from 'path';");
460
+ }
461
+ if (!hasHtmlAnnotatePlugin(code)) {
462
+ code = insertIntoPluginsArray(code, viteRange, HTML_VITE_PLUGIN_OBJ);
463
+ console.info(chalk.green("Added html-element-annotate Vite plugin to astro.config"));
464
+ }
465
+ }
466
+ if (code !== original) {
467
+ await fs.writeFile(astroConfigPath, code, "utf8");
468
+ changed = true;
469
+ }
470
+ return changed;
471
+ }
472
+ async function findRootViteConfig(cwd) {
473
+ const candidates = [
474
+ "vite.config.ts",
475
+ "vite.config.mjs",
476
+ "vite.config.js",
477
+ "vite.config.cjs"
478
+ ];
479
+ for (const f of candidates) {
480
+ const p = path.join(cwd, f);
481
+ if (await fileExists(p)) return p;
482
+ }
483
+ return null;
484
+ }
485
+ async function modifyViteConfig(viteConfigPath, framework, cwd) {
486
+ let code = await fs.readFile(viteConfigPath, "utf8");
487
+ const original = code;
488
+ let changed = false;
489
+ const defineIdx = code.indexOf("defineConfig(");
490
+ const objStart = code.indexOf("{", defineIdx);
491
+ if (defineIdx === -1 || objStart === -1) {
492
+ console.warn(chalk.yellow("Unsupported vite.config shape; skipping automatic modification"));
493
+ return false;
494
+ }
495
+ const objEnd = findMatching(code, objStart, "{", "}");
496
+ const viteRange = { start: objStart, end: objEnd };
497
+ if (!hasDomSelectorHelperPlugin(code)) {
498
+ code = insertIntoPluginsArray(code, viteRange, DOM_SELECTOR_HELPER_PLUGIN);
499
+ console.info(chalk.green("Added dom-selector-helper-inject plugin to vite.config"));
500
+ }
501
+ if (framework === "react") {
502
+ code = ensureImport(code, 'import componentAnnotatePlugin from "./babel-plugin-component-annotate";');
503
+ code = ensureImport(code, "import * as babel from '@babel/core';");
504
+ if (!hasBabelAnnotatePlugin(code)) {
505
+ code = insertIntoPluginsArray(code, viteRange, BABEL_VITE_PLUGIN_OBJ);
506
+ console.info(chalk.green("Added babel-component-annotate Vite plugin to vite.config"));
507
+ }
508
+ changed = await ensureBabelPluginFile(cwd) || changed;
509
+ } else if (framework === "vanilla") {
510
+ if (!code.includes("import * as path from 'path'") && !code.includes("import * as path from 'node:path'")) {
511
+ code = ensureImport(code, "import * as path from 'path';");
512
+ }
513
+ if (!hasHtmlAnnotatePlugin(code)) {
514
+ code = insertIntoPluginsArray(code, viteRange, HTML_VITE_PLUGIN_OBJ);
515
+ console.info(chalk.green("Added html-element-annotate Vite plugin to vite.config"));
516
+ }
517
+ }
518
+ if (code !== original) {
519
+ await fs.writeFile(viteConfigPath, code, "utf8");
520
+ changed = true;
521
+ }
522
+ return changed;
523
+ }
524
+ async function runInstaller(targetDir) {
525
+ const cwd = targetDir || process.cwd();
526
+ const {
527
+ astroConfigPath,
528
+ deps,
529
+ framework,
530
+ isAstro,
531
+ isNext
532
+ } = await detectProject(cwd);
533
+ if (isNext) {
534
+ console.info(chalk.blue(`Detected project: Next.js; framework: ${framework}`));
535
+ } else {
536
+ console.info(chalk.blue(`Detected project: ${isAstro ? "Astro" : "Vite/Other"}; framework: ${framework}`));
537
+ }
538
+ let changed = false;
539
+ changed = await ensureDomSelectorHelperFile(cwd) || changed;
540
+ if (isNext) {
541
+ changed = await installForNext(cwd) || changed;
542
+ } else if (isAstro) {
543
+ const resolvedAstroConfigPath = astroConfigPath ?? path.join(cwd, "astro.config.mjs");
544
+ changed = await modifyAstroConfig(resolvedAstroConfigPath, framework, cwd) || changed;
545
+ } else {
546
+ const viteConfigPath = await findRootViteConfig(cwd);
547
+ if (!viteConfigPath) {
548
+ console.warn(chalk.yellow("vite.config not found in project root. Nothing to modify."));
549
+ } else {
550
+ changed = await modifyViteConfig(viteConfigPath, framework, cwd) || changed;
551
+ }
552
+ }
553
+ if (framework === "react") {
554
+ if (!deps["@babel/core"]) {
555
+ console.warn(
556
+ chalk.yellow("Warning: '@babel/core' not found in devDependencies. Please install it: npm i -D @babel/core")
557
+ );
558
+ }
559
+ }
560
+ if (changed) {
561
+ console.info(chalk.green("\u2713 Component annotation installation completed with changes."));
562
+ } else {
563
+ console.info(chalk.gray("Component annotation: nothing to change."));
564
+ }
565
+ }
566
+ async function runSetup(targetDir) {
567
+ const cwd = targetDir || process.cwd();
568
+ const {
569
+ deps,
570
+ framework
571
+ } = await detectProject(cwd);
572
+ const packageManager = await detectPackageManager(cwd);
573
+ const packagesToInstall = [];
574
+ if (!deps[name]) {
575
+ packagesToInstall.push(`${name}@${version}`);
576
+ }
577
+ if (framework === "react" && !deps["@babel/core"]) {
578
+ packagesToInstall.push("@babel/core");
579
+ }
580
+ if (packagesToInstall.length > 0) {
581
+ console.info(
582
+ chalk.blue(
583
+ `Installing dev dependencies with ${packageManager}: ${packagesToInstall.join(", ")}`
584
+ )
585
+ );
586
+ await runPackageManagerInstall(packageManager, cwd, packagesToInstall);
587
+ } else {
588
+ console.info(chalk.gray("Required dev dependencies already installed."));
589
+ }
590
+ await runInstaller(cwd);
591
+ }
592
+ var BABEL_PLUGIN_TS = `import * as nodePath from 'node:path'
593
+
594
+ interface ComponentInfo {
595
+ name: string
596
+ path: string
597
+ line: number
598
+ column: number
599
+ }
600
+
601
+ interface BabelTypes {
602
+ isJSXAttribute: (node: any) => boolean
603
+ jsxAttribute: (name: any, value: any) => any
604
+ jsxIdentifier: (name: string) => any
605
+ stringLiteral: (value: string) => any
606
+ isIdentifier: (node: any) => boolean
607
+ isArrowFunctionExpression: (node: any) => boolean
608
+ isFunctionExpression: (node: any) => boolean
609
+ }
610
+
611
+ interface PluginObj {
612
+ visitor: {
613
+ [key: string]: any
614
+ }
615
+ }
616
+
617
+ interface BabelPath {
618
+ node: any
619
+ }
620
+
621
+ interface BabelState {
622
+ file: {
623
+ opts: {
624
+ filename?: string
625
+ cwd?: string
626
+ }
627
+ }
628
+ relativeFilePath?: string
629
+ }
630
+
631
+ export default function componentAnnotatePlugin({
632
+ types: t,
633
+ }: {
634
+ types: BabelTypes
635
+ }): PluginObj {
636
+ const componentStack: Array<ComponentInfo> = []
637
+
638
+ function createDataAttributes(
639
+ componentName: string,
640
+ filePath: string,
641
+ line: number,
642
+ column: number,
643
+ ) {
644
+ const attributes = []
645
+ attributes.push(
646
+ t.jsxAttribute(
647
+ t.jsxIdentifier('data-component-name'),
648
+ t.stringLiteral(componentName),
649
+ ),
650
+ )
651
+ const componentPath = \`\${filePath}:\${line}:\${column}\`
652
+ attributes.push(
653
+ t.jsxAttribute(
654
+ t.jsxIdentifier('data-component-path'),
655
+ t.stringLiteral(componentPath),
656
+ ),
657
+ )
658
+ return attributes
659
+ }
660
+
661
+ function hasComponentAttributes(openingElement: any): boolean {
662
+ return openingElement.attributes.some(
663
+ (attr: any) =>
664
+ t.isJSXAttribute(attr) &&
665
+ (attr.name.name === 'data-component-name' ||
666
+ attr.name.name === 'data-component-path'),
667
+ )
668
+ }
669
+
670
+ return {
671
+ visitor: {
672
+ Program(_path: BabelPath, state: BabelState) {
673
+ componentStack.length = 0
674
+ const filename = state.file.opts.filename || ''
675
+ const cwd = state.file.opts.cwd || process.cwd()
676
+ state.relativeFilePath = nodePath.relative(cwd, filename)
677
+ },
678
+ FunctionDeclaration: {
679
+ enter(path: BabelPath, state: BabelState) {
680
+ if (path.node.id && /^[A-Z]/.test(path.node.id.name)) {
681
+ const loc = path.node.loc
682
+ componentStack.push({
683
+ name: path.node.id.name,
684
+ path: state.relativeFilePath || '',
685
+ line: loc?.start.line || 0,
686
+ column: loc?.start.column || 0,
687
+ })
688
+ }
689
+ },
690
+ exit(path: BabelPath) {
691
+ if (path.node.id && /^[A-Z]/.test(path.node.id.name)) {
692
+ componentStack.pop()
693
+ }
694
+ },
695
+ },
696
+ VariableDeclarator: {
697
+ enter(path: BabelPath, state: BabelState) {
698
+ if (
699
+ t.isIdentifier(path.node.id) &&
700
+ /^[A-Z]/.test(path.node.id.name) &&
701
+ (t.isArrowFunctionExpression(path.node.init) ||
702
+ t.isFunctionExpression(path.node.init))
703
+ ) {
704
+ const loc = path.node.loc
705
+ componentStack.push({
706
+ name: path.node.id.name,
707
+ path: state.relativeFilePath || '',
708
+ line: loc?.start.line || 0,
709
+ column: loc?.start.column || 0,
710
+ })
711
+ }
712
+ },
713
+ exit(path: BabelPath) {
714
+ if (
715
+ t.isIdentifier(path.node.id) &&
716
+ /^[A-Z]/.test(path.node.id.name) &&
717
+ (t.isArrowFunctionExpression(path.node.init) ||
718
+ t.isFunctionExpression(path.node.init))
719
+ ) {
720
+ componentStack.pop()
721
+ }
722
+ },
723
+ },
724
+ JSXOpeningElement(path: BabelPath, state: BabelState) {
725
+ const openingElement = path.node
726
+ const nameNode = openingElement.name
727
+ const elementName =
728
+ nameNode?.name ||
729
+ (nameNode?.property && nameNode.property.name)
730
+ if (hasComponentAttributes(openingElement) || !elementName) {
731
+ return
732
+ }
733
+ if (
734
+ elementName === 'Fragment' ||
735
+ (nameNode?.type === 'JSXMemberExpression' &&
736
+ nameNode.property?.name === 'Fragment')
737
+ ) {
738
+ return
739
+ }
740
+ const loc = openingElement.loc
741
+ const attributes = createDataAttributes(
742
+ elementName,
743
+ state.relativeFilePath || '',
744
+ loc?.start.line || 0,
745
+ loc?.start.column || 0,
746
+ )
747
+ openingElement.attributes.push(...attributes)
748
+ },
749
+ },
750
+ }
751
+ }
752
+ `;
753
+ var DOM_SELECTOR_HELPER_JS = String.raw`(() => {
754
+ const MESSAGE_TYPE = 'DOCY_SELECTOR';
755
+ const acceptedAttrNames = new Set(['role', 'name', 'aria-label', 'rel', 'href']);
756
+ let state = {
757
+ enabled: false,
758
+ parentOrigin: '*',
759
+ overlay: null,
760
+ originalCursor: '',
761
+ onMove: null,
762
+ onClick: null,
763
+ onLeave: null,
764
+ };
765
+
766
+ // Forward console logs to parent window (once)
767
+ try {
768
+ if (!window.__docy_console_patched__) {
769
+ Object.defineProperty(window, '__docy_console_patched__', {
770
+ value: true,
771
+ writable: false,
772
+ configurable: false,
773
+ enumerable: false,
774
+ });
775
+ ['log', 'info', 'warn', 'error', 'debug'].forEach((level) => {
776
+ const orig = console[level];
777
+ if (typeof orig !== 'function') return;
778
+ console[level] = (...args) => {
779
+ try {
780
+ window.parent.postMessage(
781
+ { kind: 'console', level, args, ts: Date.now() },
782
+ '*'
783
+ );
784
+ } catch (_) {
785
+ // ignore postMessage errors
786
+ }
787
+ return orig.apply(console, args);
788
+ };
789
+ });
790
+ }
791
+ } catch (_) {
792
+ // ignore
793
+ }
794
+
795
+ function ensureOverlay() {
796
+ if (state.overlay) return state.overlay;
797
+ const ov = document.createElement('div');
798
+ ov.className = 'docy-element-selector-overlay';
799
+ Object.assign(ov.style, {
800
+ position: 'absolute',
801
+ pointerEvents: 'none',
802
+ border: '2px solid #3b82f6',
803
+ backgroundColor: 'rgba(59,130,246,0.25)',
804
+ zIndex: '2147483647',
805
+ transition: 'all 0.1s ease',
806
+ display: 'none',
807
+ left: '0px',
808
+ top: '0px',
809
+ width: '0px',
810
+ height: '0px',
811
+ });
812
+ document.body.appendChild(ov);
813
+ return (state.overlay = ov);
814
+ }
815
+
816
+ function wordLike(name) {
817
+ if (!/^[a-z-]{3,}$/i.test(name)) {
818
+ return false;
819
+ }
820
+
821
+ const words = name.split(/-|[A-Z]/);
822
+ for (const word of words) {
823
+ if (word.length <= 2) {
824
+ return false;
825
+ }
826
+ if (/[^aeiou]{4,}/i.test(word)) {
827
+ return false;
828
+ }
829
+ }
830
+
831
+ return true;
832
+ }
833
+
834
+ function isAcceptedAttr(name, value) {
835
+ let nameIsOk = acceptedAttrNames.has(name);
836
+ nameIsOk ||= name.startsWith('data-') && wordLike(name);
837
+
838
+ let valueIsOk = wordLike(value) && value.length < 100;
839
+ valueIsOk ||= value.startsWith('#') && wordLike(value.slice(1));
840
+
841
+ return nameIsOk && valueIsOk;
842
+ }
843
+
844
+ function isAcceptedIdName(name) {
845
+ return wordLike(name);
846
+ }
847
+
848
+ function isAcceptedClassName(name) {
849
+ return wordLike(name);
850
+ }
851
+
852
+ function isAcceptedTagName() {
853
+ return true;
854
+ }
855
+
856
+ function getCssEscape() {
857
+ if (typeof CSS !== 'undefined' && typeof CSS.escape === 'function') {
858
+ return CSS.escape.bind(CSS);
859
+ }
860
+
861
+ return (value) => String(value).replace(/[^a-zA-Z0-9_-]/g, '\\$&');
862
+ }
863
+
864
+ function createFinderConfig(options) {
865
+ return {
866
+ root: document.body,
867
+ idName: isAcceptedIdName,
868
+ className: isAcceptedClassName,
869
+ tagName: isAcceptedTagName,
870
+ attr: isAcceptedAttr,
871
+ timeoutMs: 1000,
872
+ seedMinLength: 3,
873
+ optimizedMinLength: 2,
874
+ maxNumberOfPathChecks: Number.POSITIVE_INFINITY,
875
+ ...options,
876
+ };
877
+ }
878
+
879
+ function createKnotSelector(path) {
880
+ let node = path[0];
881
+ let query = node.name;
882
+
883
+ for (let i = 1; i < path.length; i++) {
884
+ const level = path[i].level || 0;
885
+ if (node.level === level - 1) {
886
+ query = path[i].name + ' > ' + query;
887
+ } else {
888
+ query = path[i].name + ' ' + query;
889
+ }
890
+ node = path[i];
891
+ }
892
+
893
+ return query;
894
+ }
895
+
896
+ function getPathPenalty(path) {
897
+ return path
898
+ .map((node) => node.penalty)
899
+ .reduce((acc, value) => acc + value, 0);
900
+ }
901
+
902
+ function compareByPenalty(a, b) {
903
+ return getPathPenalty(a) - getPathPenalty(b);
904
+ }
905
+
906
+ function indexOfElement(input, tagName) {
907
+ const parent = input.parentNode;
908
+ if (!parent) {
909
+ return undefined;
910
+ }
911
+
912
+ let child = parent.firstChild;
913
+ if (!child) {
914
+ return undefined;
915
+ }
916
+
917
+ let index = 0;
918
+ while (child) {
919
+ if (
920
+ child.nodeType === Node.ELEMENT_NODE
921
+ && (
922
+ tagName === undefined
923
+ || child.tagName.toLowerCase() === tagName
924
+ )
925
+ ) {
926
+ index++;
927
+ }
928
+ if (child === input) {
929
+ break;
930
+ }
931
+ child = child.nextSibling;
932
+ }
933
+
934
+ return index;
935
+ }
936
+
937
+ function nthChild(tagName, index) {
938
+ if (tagName === 'html') {
939
+ return 'html';
940
+ }
941
+
942
+ return tagName + ':nth-child(' + index + ')';
943
+ }
944
+
945
+ function nthOfType(tagName, index) {
946
+ if (tagName === 'html') {
947
+ return 'html';
948
+ }
949
+
950
+ return tagName + ':nth-of-type(' + index + ')';
951
+ }
952
+
953
+ function tie(element, config) {
954
+ const level = [];
955
+ const escapeCss = getCssEscape();
956
+ const elementId = element.getAttribute('id');
957
+
958
+ if (elementId && config.idName(elementId)) {
959
+ level.push({
960
+ name: '#' + escapeCss(elementId),
961
+ penalty: 0,
962
+ });
963
+ }
964
+
965
+ for (let i = 0; i < element.classList.length; i++) {
966
+ const name = element.classList[i];
967
+ if (config.className(name)) {
968
+ level.push({
969
+ name: '.' + escapeCss(name),
970
+ penalty: 1,
971
+ });
972
+ }
973
+ }
974
+
975
+ for (let i = 0; i < element.attributes.length; i++) {
976
+ const attribute = element.attributes[i];
977
+ if (config.attr(attribute.name, attribute.value)) {
978
+ level.push({
979
+ name: '[' + escapeCss(attribute.name) + '="' + escapeCss(attribute.value) + '"]',
980
+ penalty: 2,
981
+ });
982
+ }
983
+ }
984
+
985
+ const tagName = element.tagName.toLowerCase();
986
+ if (config.tagName(tagName)) {
987
+ level.push({
988
+ name: tagName,
989
+ penalty: 5,
990
+ });
991
+
992
+ const index = indexOfElement(element, tagName);
993
+ if (index !== undefined) {
994
+ level.push({
995
+ name: nthOfType(tagName, index),
996
+ penalty: 10,
997
+ });
998
+ }
999
+ }
1000
+
1001
+ const nth = indexOfElement(element);
1002
+ if (nth !== undefined) {
1003
+ level.push({
1004
+ name: nthChild(tagName, nth),
1005
+ penalty: 50,
1006
+ });
1007
+ }
1008
+
1009
+ return level;
1010
+ }
1011
+
1012
+ function* combinations(stack, path = []) {
1013
+ if (stack.length === 0) {
1014
+ yield path;
1015
+ return;
1016
+ }
1017
+
1018
+ for (const node of stack[0]) {
1019
+ yield* combinations(stack.slice(1), path.concat(node));
1020
+ }
1021
+ }
1022
+
1023
+ function* search(input, config, rootDocument) {
1024
+ const stack = [];
1025
+ let paths = [];
1026
+ let current = input;
1027
+ let levelIndex = 0;
1028
+
1029
+ while (current && current !== rootDocument) {
1030
+ const level = tie(current, config);
1031
+ for (const node of level) {
1032
+ node.level = levelIndex;
1033
+ }
1034
+ stack.push(level);
1035
+ current = current.parentElement;
1036
+ levelIndex++;
1037
+
1038
+ paths.push(...combinations(stack));
1039
+
1040
+ if (levelIndex >= config.seedMinLength) {
1041
+ paths.sort(compareByPenalty);
1042
+ for (const candidate of paths) {
1043
+ yield candidate;
1044
+ }
1045
+ paths = [];
1046
+ }
1047
+ }
1048
+
1049
+ paths.sort(compareByPenalty);
1050
+ for (const candidate of paths) {
1051
+ yield candidate;
1052
+ }
1053
+ }
1054
+
1055
+ function findRootDocument(rootNode, defaults, input) {
1056
+ const root = input.getRootNode ? input.getRootNode() : null;
1057
+ if (root && root.constructor && root.constructor.name === 'ShadowRoot') {
1058
+ return root;
1059
+ }
1060
+ if (rootNode.nodeType === Node.DOCUMENT_NODE) {
1061
+ return rootNode;
1062
+ }
1063
+ if (rootNode === defaults.root) {
1064
+ return rootNode.ownerDocument;
1065
+ }
1066
+
1067
+ return rootNode;
1068
+ }
1069
+
1070
+ function isUniquePath(path, rootDocument) {
1071
+ const css = createKnotSelector(path);
1072
+ const count = rootDocument.querySelectorAll(css).length;
1073
+
1074
+ if (count === 0) {
1075
+ throw new Error("Can't select any node with this selector: " + css);
1076
+ }
1077
+
1078
+ return count === 1;
1079
+ }
1080
+
1081
+ function fallbackPath(input, rootDocument) {
1082
+ let current = input;
1083
+ let levelIndex = 0;
1084
+ const path = [];
1085
+
1086
+ while (current && current !== rootDocument) {
1087
+ const tagName = current.tagName.toLowerCase();
1088
+ const index = indexOfElement(current, tagName);
1089
+ if (index === undefined) {
1090
+ return undefined;
1091
+ }
1092
+
1093
+ path.push({
1094
+ name: nthOfType(tagName, index),
1095
+ penalty: Number.NaN,
1096
+ level: levelIndex,
1097
+ });
1098
+ current = current.parentElement;
1099
+ levelIndex++;
1100
+ }
1101
+
1102
+ if (isUniquePath(path, rootDocument)) {
1103
+ return path;
1104
+ }
1105
+
1106
+ return undefined;
1107
+ }
1108
+
1109
+ function* optimize(path, input, config, rootDocument, startTime) {
1110
+ if (path.length <= 2 || path.length <= config.optimizedMinLength) {
1111
+ return;
1112
+ }
1113
+
1114
+ for (let i = 1; i < path.length - 1; i++) {
1115
+ if (Date.now() - startTime > config.timeoutMs) {
1116
+ return;
1117
+ }
1118
+
1119
+ const nextPath = [...path];
1120
+ nextPath.splice(i, 1);
1121
+
1122
+ if (
1123
+ isUniquePath(nextPath, rootDocument)
1124
+ && rootDocument.querySelector(createKnotSelector(nextPath)) === input
1125
+ ) {
1126
+ yield nextPath;
1127
+ yield* optimize(nextPath, input, config, rootDocument, startTime);
1128
+ }
1129
+ }
1130
+ }
1131
+
1132
+ function finder(input, options = {}) {
1133
+ if (input.nodeType !== Node.ELEMENT_NODE) {
1134
+ throw new Error("Can't generate CSS selector for non-element node type.");
1135
+ }
1136
+ if (input.tagName.toLowerCase() === 'html') {
1137
+ return 'html';
1138
+ }
1139
+
1140
+ const defaults = createFinderConfig();
1141
+ const config = { ...defaults, ...options };
1142
+ const startTime = Date.now();
1143
+ const rootDocument = findRootDocument(config.root, defaults, input);
1144
+ let foundPath;
1145
+ let count = 0;
1146
+
1147
+ for (const candidate of search(input, config, rootDocument)) {
1148
+ if (
1149
+ Date.now() - startTime > config.timeoutMs
1150
+ || count >= config.maxNumberOfPathChecks
1151
+ ) {
1152
+ const fallback = fallbackPath(input, rootDocument);
1153
+ if (!fallback) {
1154
+ throw new Error(
1155
+ "Timeout: Can't find a unique selector after " + config.timeoutMs + 'ms'
1156
+ );
1157
+ }
1158
+
1159
+ return createKnotSelector(fallback);
1160
+ }
1161
+
1162
+ count++;
1163
+ if (isUniquePath(candidate, rootDocument)) {
1164
+ foundPath = candidate;
1165
+ break;
1166
+ }
1167
+ }
1168
+
1169
+ if (!foundPath) {
1170
+ throw new Error('Selector was not found.');
1171
+ }
1172
+
1173
+ const optimized = [...optimize(foundPath, input, config, rootDocument, startTime)];
1174
+ optimized.sort(compareByPenalty);
1175
+
1176
+ if (optimized.length > 0) {
1177
+ return createKnotSelector(optimized[0]);
1178
+ }
1179
+
1180
+ return createKnotSelector(foundPath);
1181
+ }
1182
+
1183
+ function getElementFilePath(el) {
1184
+ return (
1185
+ el.getAttribute('data-current-file-path')
1186
+ || el.getAttribute('data-component-path')
1187
+ );
1188
+ }
1189
+
1190
+ function getElementSelector(el) {
1191
+ try {
1192
+ return finder(el);
1193
+ } catch {
1194
+ return null;
1195
+ }
1196
+ }
1197
+
1198
+ function enableSelector(parentOrigin) {
1199
+ if (state.enabled) return;
1200
+ state.enabled = true;
1201
+ state.parentOrigin = parentOrigin || '*';
1202
+
1203
+ const overlay = ensureOverlay();
1204
+ state.originalCursor = document.body.style.cursor || '';
1205
+ document.body.style.cursor = 'crosshair';
1206
+
1207
+ state.onMove = (e) => {
1208
+ const target = e.target;
1209
+ if (!(target instanceof Element)) return;
1210
+ if (target === overlay) return;
1211
+
1212
+ const rect = target.getBoundingClientRect();
1213
+ overlay.style.display = 'block';
1214
+ // Position overlay in page coordinates
1215
+ overlay.style.left = (rect.left + window.scrollX) + 'px';
1216
+ overlay.style.top = (rect.top + window.scrollY) + 'px';
1217
+ overlay.style.width = rect.width + 'px';
1218
+ overlay.style.height = rect.height + 'px';
1219
+ };
1220
+
1221
+ state.onClick = (e) => {
1222
+ e.preventDefault();
1223
+ e.stopPropagation();
1224
+
1225
+ const target = e.target;
1226
+ if (!(target instanceof Element)) return;
1227
+ const rect = target.getBoundingClientRect();
1228
+
1229
+ const hasTextContent =
1230
+ target.childNodes.length === 1 &&
1231
+ target.childNodes[0].nodeType === Node.TEXT_NODE;
1232
+
1233
+ const payload = {
1234
+ // Viewport-relative rect (parent will translate using iframe position)
1235
+ rect: {
1236
+ left: rect.left,
1237
+ top: rect.top,
1238
+ right: rect.right,
1239
+ bottom: rect.bottom,
1240
+ width: rect.width,
1241
+ height: rect.height,
1242
+ },
1243
+ componentName: target.getAttribute('data-component-name'),
1244
+ filePath: getElementFilePath(target),
1245
+ componentPath: target.getAttribute('data-component-path'),
1246
+ selector: getElementSelector(target),
1247
+ tagName: target.tagName.toLowerCase(),
1248
+ className: target.className || '',
1249
+ hasTextContent: !!hasTextContent,
1250
+ textContent: hasTextContent ? (target.textContent ?? '') : null,
1251
+ src: target.tagName.toLowerCase() === 'img' ? (target.getAttribute('src') ?? '') : null,
1252
+ };
1253
+
1254
+ try {
1255
+ window.parent.postMessage(
1256
+ { type: MESSAGE_TYPE, action: 'elementSelected', payload },
1257
+ state.parentOrigin
1258
+ );
1259
+ } catch (err) {
1260
+ // No-op
1261
+ }
1262
+
1263
+ overlay.style.display = 'none';
1264
+ };
1265
+
1266
+ state.onLeave = () => {
1267
+ if (state.overlay) state.overlay.style.display = 'none';
1268
+ };
1269
+
1270
+ document.addEventListener('pointermove', state.onMove, { passive: true });
1271
+ document.addEventListener('click', state.onClick, true);
1272
+ document.addEventListener('mouseleave', state.onLeave);
1273
+ }
1274
+
1275
+ function disableSelector() {
1276
+ if (!state.enabled) return;
1277
+ state.enabled = false;
1278
+
1279
+ document.removeEventListener('pointermove', state.onMove, { passive: true });
1280
+ document.removeEventListener('click', state.onClick, true);
1281
+ document.removeEventListener('mouseleave', state.onLeave);
1282
+
1283
+ state.onMove = state.onClick = state.onLeave = null;
1284
+
1285
+ if (state.overlay) {
1286
+ state.overlay.remove();
1287
+ state.overlay = null;
1288
+ }
1289
+ document.body.style.cursor = state.originalCursor || '';
1290
+ }
1291
+
1292
+ function onMessage(event) {
1293
+ const data = event.data;
1294
+ if (!data || data.type !== MESSAGE_TYPE) return;
1295
+
1296
+ if (data.action === 'enable') {
1297
+ // Store initiator origin for secure replies
1298
+ enableSelector(event.origin);
1299
+ } else if (data.action === 'disable') {
1300
+ disableSelector();
1301
+ }
1302
+ }
1303
+
1304
+ window.addEventListener('message', onMessage);
1305
+ })();`;
1306
+ var BABEL_PLUGIN_JS = `const nodePath = require('node:path');
1307
+
1308
+ module.exports = function componentAnnotatePlugin({ types: t }) {
1309
+ let relativeFilePath = '';
1310
+
1311
+ function createDataAttributes(componentName, filePath, line, column) {
1312
+ return [
1313
+ t.jsxAttribute(t.jsxIdentifier('data-component-name'), t.stringLiteral(String(componentName || ''))),
1314
+ t.jsxAttribute(
1315
+ t.jsxIdentifier('data-component-path'),
1316
+ t.stringLiteral(String(filePath || '') + ':' + String(line || 0) + ':' + String((column || 0)))
1317
+ ),
1318
+ ];
1319
+ }
1320
+
1321
+ function hasComponentAttributes(openingElement) {
1322
+ return (openingElement.attributes || []).some(
1323
+ (attr) =>
1324
+ t.isJSXAttribute && t.isJSXAttribute(attr) &&
1325
+ attr.name && (attr.name.name === 'data-component-name' || attr.name.name === 'data-component-path')
1326
+ );
1327
+ }
1328
+
1329
+ return {
1330
+ visitor: {
1331
+ Program(_path, state) {
1332
+ const filename = (state && state.file && state.file.opts && state.file.opts.filename) || '';
1333
+ const cwd = (state && state.file && state.file.opts && state.file.opts.cwd) || process.cwd();
1334
+ relativeFilePath = nodePath.relative(cwd, filename);
1335
+ },
1336
+ JSXOpeningElement(path) {
1337
+ const openingElement = path.node;
1338
+ const nameNode = openingElement && openingElement.name;
1339
+ const elementName = nameNode && (nameNode.name || (nameNode.property && nameNode.property.name));
1340
+ if (!elementName || hasComponentAttributes(openingElement)) return;
1341
+ if (
1342
+ elementName === 'Fragment' ||
1343
+ (nameNode && nameNode.type === 'JSXMemberExpression' && nameNode.property && nameNode.property.name === 'Fragment')
1344
+ ) {
1345
+ return;
1346
+ }
1347
+ const start = openingElement.loc && openingElement.loc.start || { line: 0, column: 0 };
1348
+ const attributes = createDataAttributes(elementName, relativeFilePath, start.line || 0, start.column || 0);
1349
+ openingElement.attributes = (openingElement.attributes || []).concat(attributes);
1350
+ },
1351
+ },
1352
+ };
1353
+ };
1354
+ `;
1355
+ async function installForNext(cwd) {
1356
+ let changed = false;
1357
+ changed = await ensureBabelPluginJsFile(cwd) || changed;
1358
+ try {
1359
+ const pkg = await readJson(path.join(cwd, "package.json"));
1360
+ const deps = { ...pkg.dependencies || {}, ...pkg.devDependencies || {} };
1361
+ if (!deps["@babel/core"]) {
1362
+ console.warn(chalk.yellow("Warning: '@babel/core' not found. Install it with: npm i -D @babel/core"));
1363
+ }
1364
+ } catch {
1365
+ }
1366
+ const babelrcJson = path.join(cwd, ".babelrc");
1367
+ const babelrcJsonAlt = path.join(cwd, ".babelrc.json");
1368
+ const babelConfigJs = path.join(cwd, "babel.config.js");
1369
+ const babelrcJs = path.join(cwd, ".babelrc.js");
1370
+ if (await fileExists(babelrcJson) || await fileExists(babelrcJsonAlt)) {
1371
+ const file = await fileExists(babelrcJson) ? babelrcJson : babelrcJsonAlt;
1372
+ try {
1373
+ const json = await readJson(file);
1374
+ const presets = Array.isArray(json.presets) ? json.presets : [];
1375
+ if (!presets.includes("next/babel")) presets.push("next/babel");
1376
+ let plugins = Array.isArray(json.plugins) ? json.plugins : [];
1377
+ const pluginPath = "./babel-plugin-component-annotate";
1378
+ if (!plugins.some((p) => (Array.isArray(p) ? p[0] : p) === pluginPath)) {
1379
+ plugins = plugins.concat([pluginPath]);
1380
+ changed = true;
1381
+ }
1382
+ json.presets = presets;
1383
+ json.plugins = plugins;
1384
+ await fs.writeFile(file, `${JSON.stringify(json, null, 2)}
1385
+ `, "utf8");
1386
+ console.info(chalk.green(`Updated ${path.basename(file)} with annotate plugin`));
1387
+ } catch {
1388
+ console.warn(chalk.yellow(`Could not modify ${path.basename(file)} automatically. Please add './babel-plugin-component-annotate' to plugins.`));
1389
+ }
1390
+ return changed;
1391
+ }
1392
+ if (await fileExists(babelConfigJs) || await fileExists(babelrcJs)) {
1393
+ const file = await fileExists(babelConfigJs) ? babelConfigJs : babelrcJs;
1394
+ try {
1395
+ let code = await fs.readFile(file, "utf8");
1396
+ let modified = false;
1397
+ if (!code.includes("next/babel")) {
1398
+ const presetsIdx = code.search(/presets\s*:\s*\[/);
1399
+ if (presetsIdx !== -1) {
1400
+ const bracketStart = code.indexOf("[", presetsIdx);
1401
+ const bracketEnd = findMatching(code, bracketStart, "[", "]");
1402
+ if (bracketStart !== -1 && bracketEnd !== -1) {
1403
+ const inside = code.slice(bracketStart + 1, bracketEnd).trim();
1404
+ const prefix = inside.length ? `${inside}, ` : "";
1405
+ code = `${code.slice(0, bracketStart + 1) + prefix}'next/babel'${code.slice(bracketEnd)}`;
1406
+ modified = true;
1407
+ }
1408
+ }
1409
+ }
1410
+ if (!code.includes("babel-plugin-component-annotate")) {
1411
+ const pluginsIdx = code.search(/plugins\s*:\s*\[/);
1412
+ if (pluginsIdx !== -1) {
1413
+ const bracketStart = code.indexOf("[", pluginsIdx);
1414
+ const bracketEnd = findMatching(code, bracketStart, "[", "]");
1415
+ if (bracketStart !== -1 && bracketEnd !== -1) {
1416
+ const inside = code.slice(bracketStart + 1, bracketEnd).trim();
1417
+ const prefix = inside.length ? `${inside}, ` : "";
1418
+ code = `${code.slice(0, bracketStart + 1) + prefix}'./babel-plugin-component-annotate'${code.slice(bracketEnd)}`;
1419
+ modified = true;
1420
+ }
1421
+ }
1422
+ }
1423
+ if (modified) {
1424
+ await fs.writeFile(file, code, "utf8");
1425
+ console.info(chalk.green(`Updated ${path.basename(file)} with annotate plugin`));
1426
+ changed = true;
1427
+ } else {
1428
+ console.info(chalk.gray(`${path.basename(file)} already contains required entries or could not be modified safely.`));
1429
+ }
1430
+ } catch {
1431
+ console.warn(chalk.yellow(`Could not modify ${path.basename(file)} automatically. Please add './babel-plugin-component-annotate' to plugins and 'next/babel' to presets.`));
1432
+ }
1433
+ return changed;
1434
+ }
1435
+ const config = `module.exports = {
1436
+ presets: ['next/babel'],
1437
+ plugins: ['./babel-plugin-component-annotate'],
1438
+ };
1439
+ `;
1440
+ await fs.writeFile(babelConfigJs, config, "utf8");
1441
+ console.info(chalk.green("Created babel.config.js with annotate plugin for Next.js"));
1442
+ changed = true;
1443
+ return changed;
1444
+ }
1445
+
1446
+ // src/index.ts
1447
+ var program = new Command();
1448
+ program.name("dom-selector").description("CLI tool for DOM selector operations").version(version);
1449
+ program.command("setup").alias("init").description("Install dom-selector dev dependencies and configure the project in one step").option("-d, --directory <dir>", "Target directory (defaults to current directory)").action(async (options) => {
1450
+ try {
1451
+ console.info(chalk2.blue("\u{1F680} Setting up dom-selector..."));
1452
+ await runSetup(options.directory);
1453
+ } catch (error) {
1454
+ console.warn(chalk2.red("Error during setup:"), error);
1455
+ process.exit(1);
1456
+ }
1457
+ });
1458
+ program.command("install").description("Configure component annotation plugins for projects where the package is already installed").option("-d, --directory <dir>", "Target directory (defaults to current directory)").action(async (options) => {
1459
+ try {
1460
+ console.info(chalk2.blue("\u{1F527} Installing component annotation plugins..."));
1461
+ await runInstaller(options.directory);
1462
+ } catch (error) {
1463
+ console.warn(chalk2.red("Error during installation:"), error);
1464
+ process.exit(1);
1465
+ }
1466
+ });
1467
+ program.parse();