@simpcn/transforms 0.0.0-stage → 0.1.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 +21 -0
- package/dist/index.d.ts +15 -0
- package/dist/index.js +210 -0
- package/package.json +40 -3
- package/README.md +0 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Garvit jain
|
|
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
|
|
13
|
+
all 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
|
|
21
|
+
THE SOFTWARE.
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { AssetUrlResolver } from '@simpcn/core';
|
|
2
|
+
export declare function rewriteCssValue(value: string, resolver: AssetUrlResolver): string;
|
|
3
|
+
export declare function transformCss(code: string, id: string, resolver: AssetUrlResolver): {
|
|
4
|
+
code: string;
|
|
5
|
+
map: string;
|
|
6
|
+
} | null;
|
|
7
|
+
export declare function transformJs(code: string, id: string, resolver: AssetUrlResolver, warn: (message: string) => void, options?: {
|
|
8
|
+
helperModule?: string;
|
|
9
|
+
nextImages?: boolean;
|
|
10
|
+
preserveImageOptimization?: boolean;
|
|
11
|
+
}): {
|
|
12
|
+
code: string;
|
|
13
|
+
map: import("magic-string").SourceMap;
|
|
14
|
+
} | null;
|
|
15
|
+
export declare function transformHtml(code: string, resolver: AssetUrlResolver): string;
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,210 @@
|
|
|
1
|
+
import { parse } from '@babel/parser';
|
|
2
|
+
import traverse from '@babel/traverse';
|
|
3
|
+
import { VISITOR_KEYS } from '@babel/types';
|
|
4
|
+
import MagicString from 'magic-string';
|
|
5
|
+
import { parse as parseHtml } from 'parse5';
|
|
6
|
+
import postcss from 'postcss';
|
|
7
|
+
import valueParser from 'postcss-value-parser';
|
|
8
|
+
const media = new Set(['img', 'source', 'video', 'audio', 'track', 'input', 'embed']);
|
|
9
|
+
function attributeKind(tag, name, rel = '') {
|
|
10
|
+
if (media.has(tag) && name === 'src')
|
|
11
|
+
return 'url';
|
|
12
|
+
if (['img', 'source'].includes(tag) && name.toLowerCase() === 'srcset')
|
|
13
|
+
return 'srcset';
|
|
14
|
+
if (tag === 'video' && name === 'poster' || tag === 'object' && name === 'data' || tag === 'image' && ['href', 'xlinkHref', 'xlink:href'].includes(name))
|
|
15
|
+
return 'url';
|
|
16
|
+
if (tag === 'link' && name === 'href' && rel.split(/\s+/).some(token => ['icon', 'apple-touch-icon', 'preload'].includes(token)))
|
|
17
|
+
return 'url';
|
|
18
|
+
return undefined;
|
|
19
|
+
}
|
|
20
|
+
function decodeCss(value) {
|
|
21
|
+
return value.replace(/\\([\da-fA-F]{1,6})(?:\r\n|[ \t\r\n\f])?|\\([^\r\n\f])/g, (_match, hex, character) => {
|
|
22
|
+
if (!hex)
|
|
23
|
+
return character;
|
|
24
|
+
const code = parseInt(hex, 16);
|
|
25
|
+
return String.fromCodePoint(code === 0 || code > 0x10ffff || code >= 0xd800 && code <= 0xdfff ? 0xfffd : code);
|
|
26
|
+
});
|
|
27
|
+
}
|
|
28
|
+
export function rewriteCssValue(value, resolver) {
|
|
29
|
+
const parsed = valueParser(value);
|
|
30
|
+
parsed.walk(node => {
|
|
31
|
+
if (node.type !== 'function' || node.value.toLowerCase() !== 'url')
|
|
32
|
+
return;
|
|
33
|
+
const parts = node.nodes.filter(part => part.type !== 'space' && part.type !== 'comment');
|
|
34
|
+
if (parts.length !== 1 || !['word', 'string'].includes(parts[0].type))
|
|
35
|
+
return false;
|
|
36
|
+
const url = decodeCss(parts[0].value);
|
|
37
|
+
const resolved = resolver.resolve(url);
|
|
38
|
+
if (resolved !== url) {
|
|
39
|
+
const escaped = resolved.replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/\n/g, '\\a ').replace(/\r/g, '\\d ');
|
|
40
|
+
node.nodes = valueParser(`"${escaped}"`).nodes;
|
|
41
|
+
}
|
|
42
|
+
return false;
|
|
43
|
+
});
|
|
44
|
+
return parsed.toString();
|
|
45
|
+
}
|
|
46
|
+
export function transformCss(code, id, resolver) {
|
|
47
|
+
const root = postcss.parse(code, { from: id });
|
|
48
|
+
let changed = false;
|
|
49
|
+
root.walkDecls(declaration => {
|
|
50
|
+
const value = rewriteCssValue(declaration.value, resolver);
|
|
51
|
+
if (value !== declaration.value) {
|
|
52
|
+
declaration.value = value;
|
|
53
|
+
changed = true;
|
|
54
|
+
}
|
|
55
|
+
});
|
|
56
|
+
if (!changed)
|
|
57
|
+
return null;
|
|
58
|
+
const result = root.toResult({ from: id, to: id, map: { inline: false, annotation: false, sourcesContent: true } });
|
|
59
|
+
return { code: result.css, map: result.map.toString() };
|
|
60
|
+
}
|
|
61
|
+
function staticValue(attribute) {
|
|
62
|
+
const raw = attribute.value;
|
|
63
|
+
if (raw?.type === 'StringLiteral')
|
|
64
|
+
return { value: raw.value, node: raw, rawAttribute: true };
|
|
65
|
+
const expression = raw?.type === 'JSXExpressionContainer' ? raw.expression : undefined;
|
|
66
|
+
if (expression?.type === 'StringLiteral')
|
|
67
|
+
return { value: expression.value, node: expression, rawAttribute: false };
|
|
68
|
+
if (expression?.type === 'TemplateLiteral' && expression.expressions.length === 0) {
|
|
69
|
+
return { value: expression.quasis[0].value.cooked ?? expression.quasis[0].value.raw, node: expression, rawAttribute: false };
|
|
70
|
+
}
|
|
71
|
+
return undefined;
|
|
72
|
+
}
|
|
73
|
+
export function transformJs(code, id, resolver, warn, options = {}) {
|
|
74
|
+
const ast = parse(code, { sourceType: 'unambiguous', sourceFilename: id,
|
|
75
|
+
plugins: /\.tsx?$/.test(id) ? /\.tsx$/.test(id) ? ['typescript', 'jsx'] : ['typescript'] : ['jsx'] });
|
|
76
|
+
const output = new MagicString(code);
|
|
77
|
+
const helperNames = new Set();
|
|
78
|
+
for (const statement of ast.program.body) {
|
|
79
|
+
if (statement.type !== 'ImportDeclaration' || statement.source.value !== (options.helperModule ?? 'virtual:simpcn'))
|
|
80
|
+
continue;
|
|
81
|
+
for (const specifier of statement.specifiers) {
|
|
82
|
+
if (specifier.type === 'ImportSpecifier' && specifier.imported.type === 'Identifier' && specifier.imported.name === 'assetUrl')
|
|
83
|
+
helperNames.add(specifier.local.name);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
function walk(node) {
|
|
87
|
+
if (node.type === 'JSXOpeningElement')
|
|
88
|
+
rewriteElement(node);
|
|
89
|
+
for (const key of VISITOR_KEYS[node.type] ?? []) {
|
|
90
|
+
const value = node[key];
|
|
91
|
+
for (const child of Array.isArray(value) ? value : [value]) {
|
|
92
|
+
if (child && typeof child === 'object' && 'type' in child)
|
|
93
|
+
walk(child);
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
function rewriteElement(element) {
|
|
98
|
+
if (element.name.type !== 'JSXIdentifier')
|
|
99
|
+
return;
|
|
100
|
+
const tag = element.name.name;
|
|
101
|
+
const relAttribute = element.attributes.find(attr => attr.type === 'JSXAttribute' && attr.name.type === 'JSXIdentifier' && attr.name.name === 'rel');
|
|
102
|
+
const rel = relAttribute ? staticValue(relAttribute)?.value ?? '' : '';
|
|
103
|
+
for (const attr of element.attributes) {
|
|
104
|
+
if (attr.type !== 'JSXAttribute' || attr.name.type !== 'JSXIdentifier')
|
|
105
|
+
continue;
|
|
106
|
+
const kind = attributeKind(tag, attr.name.name, rel);
|
|
107
|
+
if (!kind)
|
|
108
|
+
continue;
|
|
109
|
+
const literal = staticValue(attr);
|
|
110
|
+
if (!literal) {
|
|
111
|
+
const expression = attr.value?.type === 'JSXExpressionContainer' ? attr.value.expression : undefined;
|
|
112
|
+
if (!(expression?.type === 'CallExpression' && expression.callee.type === 'Identifier' && helperNames.has(expression.callee.name))) {
|
|
113
|
+
warn(`Dynamic ${tag}.${attr.name.name} in ${id} was left unchanged; use assetUrl() from ${options.helperModule ?? 'virtual:simpcn'} when it references managed assets.`);
|
|
114
|
+
}
|
|
115
|
+
continue;
|
|
116
|
+
}
|
|
117
|
+
const value = kind === 'srcset' ? resolver.resolveSrcSet(literal.value) : resolver.resolve(literal.value);
|
|
118
|
+
if (value !== literal.value) {
|
|
119
|
+
const replacement = JSON.stringify(value);
|
|
120
|
+
output.overwrite(literal.node.start, literal.node.end, literal.rawAttribute ? `{${replacement}}` : replacement);
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
walk(ast);
|
|
125
|
+
if (options.nextImages)
|
|
126
|
+
traverse(ast, {
|
|
127
|
+
JSXOpeningElement(elementPath) {
|
|
128
|
+
const element = elementPath.node;
|
|
129
|
+
if (element.name.type !== 'JSXIdentifier')
|
|
130
|
+
return;
|
|
131
|
+
const binding = elementPath.scope.getBinding(element.name.name);
|
|
132
|
+
if (!binding?.constant)
|
|
133
|
+
return;
|
|
134
|
+
const specifier = binding.path.node;
|
|
135
|
+
const declaration = binding.path.parentPath;
|
|
136
|
+
const importedImage = specifier.type === 'ImportDefaultSpecifier' ||
|
|
137
|
+
specifier.type === 'ImportSpecifier' && specifier.imported.type === 'Identifier' && specifier.imported.name === 'default';
|
|
138
|
+
if (!importedImage || !declaration?.isImportDeclaration() || declaration.node.source.value !== 'next/image' || declaration.node.importKind === 'type')
|
|
139
|
+
return;
|
|
140
|
+
const attributes = element.attributes.filter((attribute) => attribute.type === 'JSXAttribute');
|
|
141
|
+
const named = (name) => attributes.filter(attribute => attribute.name.type === 'JSXIdentifier' && attribute.name.name === name);
|
|
142
|
+
const sources = named('src');
|
|
143
|
+
if (!sources.length)
|
|
144
|
+
return;
|
|
145
|
+
const literal = staticValue(sources[0]);
|
|
146
|
+
if (!literal)
|
|
147
|
+
return; // Ownership of arbitrary dynamic/API URLs cannot be inferred.
|
|
148
|
+
const resolved = resolver.resolve(literal.value);
|
|
149
|
+
if (resolved === literal.value)
|
|
150
|
+
return; // Only the already-verified public inventory is managed.
|
|
151
|
+
const unoptimized = named('unoptimized');
|
|
152
|
+
const explicitlyDirect = unoptimized.length === 1 && (unoptimized[0].value === null ||
|
|
153
|
+
unoptimized[0].value?.type === 'JSXExpressionContainer' && unoptimized[0].value.expression.type === 'BooleanLiteral' && unoptimized[0].value.expression.value);
|
|
154
|
+
let reason;
|
|
155
|
+
if (sources.length !== 1 || element.attributes.some(attribute => attribute.type === 'JSXSpreadAttribute'))
|
|
156
|
+
reason = 'duplicate src or spread props';
|
|
157
|
+
else if (named('loader').length || named('overrideSrc').length)
|
|
158
|
+
reason = 'an explicit loader or overrideSrc';
|
|
159
|
+
else if (unoptimized.length && !explicitlyDirect)
|
|
160
|
+
reason = 'an explicit unoptimized setting';
|
|
161
|
+
else if (options.preserveImageOptimization && !explicitlyDirect)
|
|
162
|
+
reason = 'explicit image optimization settings in next.config';
|
|
163
|
+
if (reason) {
|
|
164
|
+
warn(`Managed next/image ${literal.value} in ${id} was left unchanged because of ${reason}. For direct delivery, resolve conflicting props and use unoptimized or assetUrl() explicitly.`);
|
|
165
|
+
return;
|
|
166
|
+
}
|
|
167
|
+
const replacement = JSON.stringify(resolved);
|
|
168
|
+
output.overwrite(literal.node.start, literal.node.end, literal.rawAttribute ? `{${replacement}}` : replacement);
|
|
169
|
+
// Insert before the tag terminator, preserving whitespace, attributes and children.
|
|
170
|
+
if (!unoptimized.length)
|
|
171
|
+
output.appendLeft(element.end - (element.selfClosing ? 2 : 1), ' unoptimized ');
|
|
172
|
+
},
|
|
173
|
+
});
|
|
174
|
+
return output.hasChanged() ? { code: output.toString(), map: output.generateMap({ hires: true, source: id, includeContent: true }) } : null;
|
|
175
|
+
}
|
|
176
|
+
const escapeHtml = (value) => value.replace(/&/g, '&').replace(/"/g, '"').replace(/</g, '<').replace(/>/g, '>');
|
|
177
|
+
export function transformHtml(code, resolver) {
|
|
178
|
+
const root = parseHtml(code, { sourceCodeLocationInfo: true });
|
|
179
|
+
const output = new MagicString(code);
|
|
180
|
+
function walk(node) {
|
|
181
|
+
if ('tagName' in node) {
|
|
182
|
+
const rel = node.attrs.find(attr => attr.name === 'rel')?.value ?? '';
|
|
183
|
+
for (const attr of node.attrs) {
|
|
184
|
+
const name = attr.prefix ? `${attr.prefix}:${attr.name}` : attr.name;
|
|
185
|
+
const location = node.sourceCodeLocation?.attrs?.[name];
|
|
186
|
+
const kind = attributeKind(node.tagName, name, rel);
|
|
187
|
+
const value = name === 'style' ? rewriteCssValue(attr.value, resolver) :
|
|
188
|
+
kind === 'srcset' ? resolver.resolveSrcSet(attr.value) : kind ? resolver.resolve(attr.value) : attr.value;
|
|
189
|
+
if (location && value !== attr.value)
|
|
190
|
+
output.overwrite(location.startOffset, location.endOffset, `${name}="${escapeHtml(value)}"`);
|
|
191
|
+
}
|
|
192
|
+
if (node.tagName === 'style') {
|
|
193
|
+
for (const child of node.childNodes) {
|
|
194
|
+
if ('value' in child && child.nodeName === '#text' && child.sourceCodeLocation) {
|
|
195
|
+
const transformed = transformCss(child.value, 'inline.css', resolver);
|
|
196
|
+
if (transformed)
|
|
197
|
+
output.overwrite(child.sourceCodeLocation.startOffset, child.sourceCodeLocation.endOffset, transformed.code);
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
if ('content' in node)
|
|
202
|
+
walk(node.content);
|
|
203
|
+
}
|
|
204
|
+
if ('childNodes' in node)
|
|
205
|
+
for (const child of node.childNodes)
|
|
206
|
+
walk(child);
|
|
207
|
+
}
|
|
208
|
+
walk(root);
|
|
209
|
+
return output.toString();
|
|
210
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,43 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@simpcn/transforms",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"files": [
|
|
6
|
+
"dist"
|
|
7
|
+
],
|
|
8
|
+
"exports": {
|
|
9
|
+
".": {
|
|
10
|
+
"types": "./dist/index.d.ts",
|
|
11
|
+
"import": "./dist/index.js"
|
|
12
|
+
}
|
|
13
|
+
},
|
|
14
|
+
"engines": {
|
|
15
|
+
"node": ">=24.11.0"
|
|
16
|
+
},
|
|
17
|
+
"dependencies": {
|
|
18
|
+
"@babel/parser": "^8.0.7",
|
|
19
|
+
"@babel/traverse": "^8.0.7",
|
|
20
|
+
"@babel/types": "^8.0.6",
|
|
21
|
+
"@simpcn/core": "0.1.0",
|
|
22
|
+
"magic-string": "^1.4.3",
|
|
23
|
+
"parse5": "^8.0.1",
|
|
24
|
+
"postcss": "^8.5.29",
|
|
25
|
+
"postcss-value-parser": "^4.2.0"
|
|
26
|
+
},
|
|
27
|
+
"description": "Shared parser-based asset URL transformations for simpcn framework adapters.",
|
|
28
|
+
"license": "MIT",
|
|
29
|
+
"repository": {
|
|
30
|
+
"type": "git",
|
|
31
|
+
"url": "git+https://github.com/garvitj2003/simpcn.git",
|
|
32
|
+
"directory": "packages/transforms"
|
|
33
|
+
},
|
|
34
|
+
"homepage": "https://github.com/garvitj2003/simpcn#readme",
|
|
35
|
+
"bugs": {
|
|
36
|
+
"url": "https://github.com/garvitj2003/simpcn/issues"
|
|
37
|
+
},
|
|
38
|
+
"author": "Garvit jain",
|
|
39
|
+
"scripts": {
|
|
40
|
+
"build": "tsc -p tsconfig.build.json",
|
|
41
|
+
"typecheck": "tsc --noEmit"
|
|
42
|
+
}
|
|
6
43
|
}
|
package/README.md
DELETED