macaly-tagger 1.0.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 macaly-tagger
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,220 @@
1
+ # Macaly Tagger
2
+
3
+ A webpack loader that adds location metadata to JSX elements for development debugging. This loader automatically injects `data-macaly-loc` and `data-macaly-name` attributes into your JSX elements, making it easy to trace elements back to their source code location.
4
+
5
+ ## Features
6
+
7
+ - 🎯 **Precise location tracking**: Shows exact file, line, and column for each JSX element
8
+ - 🚀 **Zero runtime overhead**: Only runs in development mode
9
+ - 🔧 **Easy integration**: Simple webpack configuration
10
+ - 📦 **TypeScript support**: Works with both `.jsx` and `.tsx` files
11
+ - 🚫 **Smart filtering**: Automatically excludes `node_modules`
12
+
13
+ ## Installation
14
+
15
+ ```bash
16
+ npm install --save-dev macaly-tagger
17
+ ```
18
+
19
+ The loader has the following dependencies that will be installed automatically:
20
+
21
+ - `@babel/parser`
22
+ - `magic-string`
23
+ - `estree-walker`
24
+
25
+ ## Usage
26
+
27
+ ### Next.js Setup
28
+
29
+ Configure your `next.config.js`:
30
+
31
+ ```js
32
+ const path = require("path");
33
+
34
+ /** @type {import('next').NextConfig} */
35
+ const nextConfig = {
36
+ webpack: (config, { dev, isServer }) => {
37
+ // Only apply in development
38
+ if (dev) {
39
+ config.module.rules.unshift({
40
+ test: /\.(jsx|tsx)$/,
41
+ exclude: /node_modules/,
42
+ use: [
43
+ {
44
+ loader: "macaly-tagger",
45
+ },
46
+ ],
47
+ enforce: "pre", // Run before other loaders
48
+ });
49
+ }
50
+
51
+ return config;
52
+ },
53
+ };
54
+
55
+ module.exports = nextConfig;
56
+ ```
57
+
58
+ ### Webpack Setup
59
+
60
+ For custom webpack configurations:
61
+
62
+ ```js
63
+ module.exports = {
64
+ module: {
65
+ rules: [
66
+ {
67
+ test: /\.(jsx|tsx)$/,
68
+ exclude: /node_modules/,
69
+ use: [
70
+ {
71
+ loader: "macaly-tagger",
72
+ },
73
+ ],
74
+ enforce: "pre",
75
+ },
76
+ // ... other rules
77
+ ],
78
+ },
79
+ };
80
+ ```
81
+
82
+ ### Vite Setup
83
+
84
+ For Vite projects, you'll need a Vite plugin wrapper (not included in this package).
85
+
86
+ ## Example
87
+
88
+ ### Input JSX:
89
+
90
+ ```jsx
91
+ export default function TestComponent() {
92
+ return (
93
+ <div className="container">
94
+ <h1>Hello Macaly!</h1>
95
+ <button onClick={() => console.log("clicked")}>Click me</button>
96
+ <MyLib.SpecialButton />
97
+ </div>
98
+ );
99
+ }
100
+ ```
101
+
102
+ ### Output HTML (in browser):
103
+
104
+ ```html
105
+ <div
106
+ data-macaly-loc="components/TestComponent.jsx:3:4"
107
+ data-macaly-name="div"
108
+ class="container"
109
+ >
110
+ <h1 data-macaly-loc="components/TestComponent.jsx:4:6" data-macaly-name="h1">
111
+ Hello Macaly!
112
+ </h1>
113
+ <button
114
+ data-macaly-loc="components/TestComponent.jsx:5:6"
115
+ data-macaly-name="button"
116
+ >
117
+ Click me
118
+ </button>
119
+ <button
120
+ data-macaly-loc="components/TestComponent.jsx:8:6"
121
+ data-macaly-name="MyLib.SpecialButton"
122
+ >
123
+ Special
124
+ </button>
125
+ </div>
126
+ ```
127
+
128
+ ## How It Works
129
+
130
+ The loader:
131
+
132
+ 1. **Parses JSX/TSX files** using Babel parser
133
+ 2. **Walks the AST** to find JSX opening elements
134
+ 3. **Adds location attributes** with file path, line, and column information
135
+ 4. **Preserves source maps** for debugging
136
+ 5. **Skips already tagged elements** to avoid duplicates
137
+
138
+ ## Configuration
139
+
140
+ The loader works out of the box with no configuration needed. It automatically:
141
+
142
+ - Processes only `.jsx` and `.tsx` files
143
+ - Excludes `node_modules` directory
144
+ - Runs only in development mode (when configured properly)
145
+ - Handles both regular JSX elements (`<div>`) and member expressions (`<MyLib.Button>`)
146
+
147
+ ## Attributes Added
148
+
149
+ For each JSX element, the loader adds:
150
+
151
+ - `data-macaly-loc`: File path, line, and column (e.g., `"components/Button.jsx:15:8"`)
152
+ - `data-macaly-name`: Component/element name (e.g., `"button"` or `"MyLib.Button"`)
153
+
154
+ ## Browser DevTools Integration
155
+
156
+ Once installed, you can:
157
+
158
+ 1. Open browser DevTools
159
+ 2. Inspect any element
160
+ 3. See the `data-macaly-loc` attribute to find the exact source location
161
+ 4. Use browser extensions or custom scripts to jump to source code
162
+
163
+ ## Troubleshooting
164
+
165
+ ### Not seeing attributes?
166
+
167
+ 1. **Check console for errors**: Look for `[macaly-tagger]` warnings in the browser console
168
+ 2. **Verify development mode**: Ensure the loader only runs in development (`dev && !isServer` for Next.js)
169
+ 3. **Check file extensions**: Only `.jsx` and `.tsx` files are processed
170
+
171
+ ### Build errors?
172
+
173
+ 1. **Install dependencies**: Ensure all peer dependencies are installed
174
+ 2. **Check webpack version**: Requires webpack >= 4.0.0
175
+ 3. **Verify loader path**: Make sure the loader is correctly referenced
176
+
177
+ ### Performance issues?
178
+
179
+ The loader is optimized for development:
180
+
181
+ - Only processes JSX/TSX files
182
+ - Excludes node_modules automatically
183
+ - Uses efficient AST walking
184
+ - Includes source map support
185
+
186
+ ### Enable debug logging
187
+
188
+ Add a console log to see which files are being processed:
189
+
190
+ ```js
191
+ // In your webpack config
192
+ {
193
+ loader: 'macaly-tagger',
194
+ options: {
195
+ debug: true // If you implement options support
196
+ }
197
+ }
198
+ ```
199
+
200
+ ## Contributing
201
+
202
+ 1. Fork the repository
203
+ 2. Create a feature branch
204
+ 3. Make your changes
205
+ 4. Add tests if applicable
206
+ 5. Submit a pull request
207
+
208
+ ## License
209
+
210
+ MIT License - see LICENSE file for details.
211
+
212
+ ## Changelog
213
+
214
+ ### 1.0.0
215
+
216
+ - Initial release
217
+ - Support for JSX and TSX files
218
+ - Location tracking with file, line, and column
219
+ - Member expression support (e.g., `MyLib.Button`)
220
+ - Source map preservation
@@ -0,0 +1,3 @@
1
+ export { default } from './macaly-tagger-loader';
2
+ export type { MacalyTaggerLoaderOptions } from './types';
3
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,wBAAwB,CAAC;AACjD,YAAY,EAAE,yBAAyB,EAAE,MAAM,SAAS,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,8 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.default = void 0;
7
+ var macaly_tagger_loader_1 = require("./macaly-tagger-loader");
8
+ Object.defineProperty(exports, "default", { enumerable: true, get: function () { return __importDefault(macaly_tagger_loader_1).default; } });
@@ -0,0 +1,4 @@
1
+ import type { MacalyTaggerLoader } from './types';
2
+ declare const macalyTaggerLoader: MacalyTaggerLoader;
3
+ export default macalyTaggerLoader;
4
+ //# sourceMappingURL=macaly-tagger-loader.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"macaly-tagger-loader.d.ts","sourceRoot":"","sources":["../src/macaly-tagger-loader.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EACV,kBAAkB,EAInB,MAAM,SAAS,CAAC;AAuFjB,QAAA,MAAM,kBAAkB,EAAE,kBAmIzB,CAAC;AAEF,eAAe,kBAAkB,CAAC"}
@@ -0,0 +1,191 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ var __importDefault = (this && this.__importDefault) || function (mod) {
36
+ return (mod && mod.__esModule) ? mod : { "default": mod };
37
+ };
38
+ Object.defineProperty(exports, "__esModule", { value: true });
39
+ const parser_1 = require("@babel/parser");
40
+ const magic_string_1 = __importDefault(require("magic-string"));
41
+ const path = __importStar(require("path"));
42
+ const estree_walker_1 = require("estree-walker");
43
+ const VALID_EXTENSIONS = new Set(['.jsx', '.tsx']);
44
+ function getMemberExpressionName(memberExpression) {
45
+ if (memberExpression.type === 'JSXIdentifier') {
46
+ return memberExpression.name;
47
+ }
48
+ if (memberExpression.type === 'JSXMemberExpression') {
49
+ const object = getMemberExpressionName(memberExpression.object);
50
+ const property = memberExpression.property.name;
51
+ return object ? `${object}.${property}` : null;
52
+ }
53
+ return null;
54
+ }
55
+ function isElementAlreadyTagged(attributes) {
56
+ return (attributes?.some((attr) => attr.type === 'JSXAttribute' &&
57
+ attr.name?.type === 'JSXIdentifier' &&
58
+ attr.name.name === 'data-macaly-loc') ?? false);
59
+ }
60
+ function getJSXElementInfo(node) {
61
+ let tagName;
62
+ let insertPosition;
63
+ if (node.name?.type === 'JSXIdentifier') {
64
+ tagName = node.name.name;
65
+ insertPosition = node.name.end ?? 0;
66
+ }
67
+ else if (node.name?.type === 'JSXMemberExpression') {
68
+ const name = getMemberExpressionName(node.name);
69
+ if (!name)
70
+ return null;
71
+ tagName = name;
72
+ insertPosition = node.name.end ?? 0;
73
+ }
74
+ else {
75
+ console.log('[macaly-tagger] Unsupported JSX element type:', node.name?.type);
76
+ return null;
77
+ }
78
+ if (!tagName || insertPosition === 0) {
79
+ console.log('[macaly-tagger] Missing tagName or insertPosition:', { tagName, insertPosition });
80
+ return null;
81
+ }
82
+ const loc = node.loc?.start;
83
+ if (!loc) {
84
+ console.log('[macaly-tagger] No location info for element:', tagName);
85
+ return null;
86
+ }
87
+ return {
88
+ tagName,
89
+ insertPosition,
90
+ location: loc,
91
+ };
92
+ }
93
+ const macalyTaggerLoader = function (code) {
94
+ console.log('[macaly-tagger] Loader called with:', this.resourcePath);
95
+ const callback = this.async();
96
+ const options = this.getOptions() || {};
97
+ if (!callback) {
98
+ throw new Error('[macaly-tagger] Async callback not available');
99
+ }
100
+ const transform = async () => {
101
+ try {
102
+ if (!VALID_EXTENSIONS.has(path.extname(this.resourcePath)) ||
103
+ this.resourcePath.includes('node_modules')) {
104
+ if (options.debug) {
105
+ console.log('[macaly-tagger] Skipping file:', this.resourcePath);
106
+ }
107
+ return null;
108
+ }
109
+ if (options.debug) {
110
+ console.log('[macaly-tagger] Processing file:', this.resourcePath);
111
+ }
112
+ const ast = (0, parser_1.parse)(code, {
113
+ sourceType: 'module',
114
+ plugins: ['jsx', 'typescript'],
115
+ sourceFilename: this.resourcePath,
116
+ });
117
+ const ms = new magic_string_1.default(code);
118
+ const fileRelative = path.relative(this.rootContext || process.cwd(), this.resourcePath);
119
+ let transformCount = 0;
120
+ if (options.debug) {
121
+ console.log('[macaly-tagger] File relative path:', fileRelative);
122
+ }
123
+ (0, estree_walker_1.walk)(ast, {
124
+ enter: (node) => {
125
+ try {
126
+ if (node.type !== 'JSXOpeningElement')
127
+ return;
128
+ const jsxNode = node;
129
+ if (options.debug) {
130
+ console.log('[macaly-tagger] Found JSX element:', jsxNode.name?.type);
131
+ }
132
+ if (isElementAlreadyTagged(jsxNode.attributes)) {
133
+ if (options.debug) {
134
+ console.log('[macaly-tagger] Element already tagged');
135
+ }
136
+ return;
137
+ }
138
+ const elementInfo = getJSXElementInfo(jsxNode);
139
+ if (!elementInfo)
140
+ return;
141
+ const { tagName, insertPosition, location } = elementInfo;
142
+ const macalyLoc = `${fileRelative}:${location.line}:${location.column}`;
143
+ if (options.debug) {
144
+ console.log('[macaly-tagger] Adding attributes to:', tagName, 'at', macalyLoc);
145
+ }
146
+ ms.appendLeft(insertPosition, ` data-macaly-loc="${macalyLoc}" data-macaly-name="${tagName}"`);
147
+ transformCount++;
148
+ }
149
+ catch (error) {
150
+ console.warn(`[macaly-tagger] Warning: Failed to process JSX node in ${this.resourcePath}:`, error);
151
+ }
152
+ },
153
+ });
154
+ if (options.debug) {
155
+ console.log('[macaly-tagger] Transform count:', transformCount);
156
+ }
157
+ if (transformCount === 0) {
158
+ if (options.debug) {
159
+ console.log('[macaly-tagger] No transformations made for:', fileRelative);
160
+ }
161
+ return null;
162
+ }
163
+ const transformedCode = ms.toString();
164
+ if (options.debug) {
165
+ console.log('[macaly-tagger] Successfully transformed:', fileRelative, 'with', transformCount, 'changes');
166
+ }
167
+ return {
168
+ code: transformedCode,
169
+ map: ms.generateMap({ hires: true }),
170
+ };
171
+ }
172
+ catch (error) {
173
+ console.warn(`[macaly-tagger] Warning: Failed to transform ${this.resourcePath}:`, error);
174
+ return null;
175
+ }
176
+ };
177
+ transform()
178
+ .then((result) => {
179
+ if (result) {
180
+ callback(null, result.code, result.map);
181
+ }
182
+ else {
183
+ callback(null, code);
184
+ }
185
+ })
186
+ .catch((err) => {
187
+ console.error(`[macaly-tagger] ERROR in ${this.resourcePath}:`, err);
188
+ callback(null, code);
189
+ });
190
+ };
191
+ exports.default = macalyTaggerLoader;
@@ -0,0 +1,19 @@
1
+ import { LoaderDefinitionFunction } from 'webpack';
2
+ export interface MacalyTaggerLoaderOptions {
3
+ debug?: boolean;
4
+ }
5
+ export interface SourceLocation {
6
+ line: number;
7
+ column: number;
8
+ }
9
+ export interface JSXElementInfo {
10
+ tagName: string;
11
+ insertPosition: number;
12
+ location: SourceLocation;
13
+ }
14
+ export interface TransformResult {
15
+ code: string;
16
+ map: any;
17
+ }
18
+ export type MacalyTaggerLoader = LoaderDefinitionFunction<MacalyTaggerLoaderOptions>;
19
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,wBAAwB,EAAE,MAAM,SAAS,CAAC;AAEnD,MAAM,WAAW,yBAAyB;IACxC,KAAK,CAAC,EAAE,OAAO,CAAC;CACjB;AAED,MAAM,WAAW,cAAc;IAC7B,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,EAAE,MAAM,CAAC;CAChB;AAED,MAAM,WAAW,cAAc;IAC7B,OAAO,EAAE,MAAM,CAAC;IAChB,cAAc,EAAE,MAAM,CAAC;IACvB,QAAQ,EAAE,cAAc,CAAC;CAC1B;AAED,MAAM,WAAW,eAAe;IAC9B,IAAI,EAAE,MAAM,CAAC;IACb,GAAG,EAAE,GAAG,CAAC;CACV;AAED,MAAM,MAAM,kBAAkB,GAAG,wBAAwB,CAAC,yBAAyB,CAAC,CAAC"}
package/dist/types.js ADDED
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
package/package.json ADDED
@@ -0,0 +1,88 @@
1
+ {
2
+ "name": "macaly-tagger",
3
+ "version": "1.0.0",
4
+ "description": "A webpack loader that adds location metadata to JSX elements for development debugging",
5
+ "main": "dist/index.js",
6
+ "types": "dist/index.d.ts",
7
+ "module": "dist/index.js",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "require": "./dist/index.js",
12
+ "import": "./dist/index.js"
13
+ },
14
+ "./package.json": "./package.json"
15
+ },
16
+ "scripts": {
17
+ "build": "tsc -p tsconfig.build.json",
18
+ "build:watch": "tsc -p tsconfig.build.json --watch",
19
+ "clean": "rimraf dist",
20
+ "dev": "tsc -p tsconfig.build.json --watch",
21
+ "lint": "eslint src --ext .ts,.tsx",
22
+ "lint:fix": "eslint src --ext .ts,.tsx --fix",
23
+ "format": "prettier --write \"src/**/*.{ts,tsx}\"",
24
+ "format:check": "prettier --check \"src/**/*.{ts,tsx}\"",
25
+ "test": "vitest run",
26
+ "test:watch": "vitest",
27
+ "test:coverage": "vitest run --coverage",
28
+ "type-check": "tsc --noEmit",
29
+ "prepublishOnly": "npm run clean && npm run build && npm run test && npm run lint",
30
+ "prepack": "npm run build"
31
+ },
32
+ "keywords": [
33
+ "webpack",
34
+ "loader",
35
+ "jsx",
36
+ "tsx",
37
+ "react",
38
+ "nextjs",
39
+ "debugging",
40
+ "development",
41
+ "typescript",
42
+ "babel"
43
+ ],
44
+ "author": {
45
+ "name": "Macaly",
46
+ "email": "hi@macaly.com",
47
+ "url": "https://macaly.com"
48
+ },
49
+ "license": "MIT",
50
+ "dependencies": {
51
+ "@babel/parser": "^7.24.0",
52
+ "magic-string": "^0.30.0",
53
+ "estree-walker": "^2.0.2"
54
+ },
55
+ "devDependencies": {
56
+ "@babel/types": "^7.24.0",
57
+ "@types/estree": "^1.0.5",
58
+ "@types/node": "^20.11.30",
59
+ "@typescript-eslint/eslint-plugin": "^7.3.1",
60
+ "@typescript-eslint/parser": "^7.3.1",
61
+ "eslint": "^8.57.0",
62
+ "eslint-config-prettier": "^9.1.0",
63
+ "eslint-plugin-prettier": "^5.1.3",
64
+ "vitest": "^1.4.0",
65
+ "prettier": "^3.2.5",
66
+ "rimraf": "^5.0.5",
67
+ "typescript": "^5.4.2"
68
+ },
69
+ "peerDependencies": {
70
+ "webpack": ">=4.0.0"
71
+ },
72
+ "files": [
73
+ "dist/**/*",
74
+ "README.md",
75
+ "LICENSE"
76
+ ],
77
+ "engines": {
78
+ "node": ">=16.0.0"
79
+ },
80
+ "repository": {
81
+ "type": "git",
82
+ "url": "https://github.com/langtail/macaly-tagger.git"
83
+ },
84
+ "bugs": {
85
+ "url": "https://github.com/langtail/macaly-tagger/issues"
86
+ },
87
+ "homepage": "https://github.com/langtail/macaly-tagger#readme"
88
+ }