@knighted/jsx 1.0.0 → 1.2.0-rc.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/README.md CHANGED
@@ -15,13 +15,17 @@ npm install @knighted/jsx
15
15
  > [!IMPORTANT]
16
16
  > This package is ESM-only and targets browsers or ESM-aware bundlers. `require()` is not supported; use native `import`/`<script type="module">` and a DOM-like environment.
17
17
 
18
+ > [!NOTE]
19
+ > Planning to use the React runtime (`@knighted/jsx/react`)? Install `react@>=18` and `react-dom@>=18` alongside this package so the helper can create elements and render them through ReactDOM.
20
+
18
21
  The parser automatically uses native bindings when it runs in Node.js. To enable the WASM binding for browser builds you also need the `@oxc-parser/binding-wasm32-wasi` package. Because npm enforces the `cpu: ["wasm32"]` flag you must opt into the install explicitly:
19
22
 
20
23
  ```sh
21
24
  npm_config_ignore_platform=true npm install @oxc-parser/binding-wasm32-wasi
22
25
  ```
23
26
 
24
- > Tip: public CDNs such as `esm.sh` or `jsdelivr` already publish bundles that include the WASM binding, so you can import this package directly from those endpoints in `<script type="module">` blocks without any extra setup.
27
+ > [!TIP]
28
+ > Public CDNs such as `esm.sh` or `jsdelivr` already publish bundles that include the WASM binding, so you can import this package directly from those endpoints in `<script type="module">` blocks without any extra setup.
25
29
 
26
30
  ## Usage
27
31
 
@@ -40,6 +44,71 @@ const button = jsx`
40
44
  document.body.append(button)
41
45
  ```
42
46
 
47
+ ### React runtime (`reactJsx`)
48
+
49
+ Need to compose React elements instead of DOM nodes? Import the dedicated helper from the `@knighted/jsx/react` subpath (React 18+ and `react-dom` are still required to mount the tree):
50
+
51
+ ```ts
52
+ import { reactJsx } from '@knighted/jsx/react'
53
+ import { createRoot } from 'react-dom/client'
54
+
55
+ const view = reactJsx`
56
+ <section className="react-demo">
57
+ <h2>Hello from React</h2>
58
+ <button onClick={${() => console.log('clicked!')}}>Tap me</button>
59
+ </section>
60
+ `
61
+
62
+ createRoot(document.getElementById('root')!).render(view)
63
+ ```
64
+
65
+ The React runtime shares the same template semantics as `jsx`, except it returns React elements (via `React.createElement`) so you can embed other React components with `<${MyComponent} />` and use hooks/state as usual. The helper lives in a separate subpath so DOM-only consumers never pay the React dependency cost.
66
+
67
+ ## Loader integration
68
+
69
+ Use the published loader entry (`@knighted/jsx/loader`) when you want your bundler to rewrite tagged template literals at build time. The loader finds every ` jsx`` ` (and, by default, ` reactJsx`` ` ) invocation, rebuilds the template with real JSX semantics, and hands back transformed source that can run in any environment.
70
+
71
+ ```js
72
+ // rspack.config.js / webpack.config.js
73
+ export default {
74
+ module: {
75
+ rules: [
76
+ {
77
+ test: /\.[jt]sx?$/,
78
+ include: path.resolve(__dirname, 'src'),
79
+ use: [
80
+ {
81
+ loader: '@knighted/jsx/loader',
82
+ options: {
83
+ // Both optional: restrict or rename the tagged templates.
84
+ // tag: 'jsx', // single-tag option
85
+ // tags: ['jsx', 'reactJsx'],
86
+ },
87
+ },
88
+ ],
89
+ },
90
+ ],
91
+ },
92
+ }
93
+ ```
94
+
95
+ Pair the loader with your existing TypeScript/JSX transpiler (SWC, Babel, Rspack’s builtin loader, etc.) so regular React components and the tagged templates can live side by side. The demo fixture under `test/fixtures/rspack-app` shows a full setup that mixes Lit and React:
96
+
97
+ ```sh
98
+ npm run build
99
+ npm run setup:wasm
100
+ npm run build:fixture
101
+ ```
102
+
103
+ Then point a static server at the fixture root (which serves `index.html` and the bundled `dist/bundle.js`) to see it in a browser:
104
+
105
+ ```sh
106
+ # Serve the rspack fixture from the repo root
107
+ npx http-server test/fixtures/rspack-app -p 4173
108
+ ```
109
+
110
+ Visit `http://localhost:4173` (or whichever port you pick) to interact with the Lit + React demo.
111
+
43
112
  ### Interpolations
44
113
 
45
114
  - All dynamic values are provided through standard template literal expressions (`${...}`). Wrap them in JSX braces to keep the syntax valid: `className={${value}}`, `{${items}}`, etc.
@@ -94,7 +163,19 @@ When you are not using a bundler, load the module directly from a CDN that under
94
163
  </script>
95
164
  ```
96
165
 
97
- If you are building locally with Vite/Rollup/Webpack make sure the WASM binding is installable (see the `npm_config_ignore_platform` tip above) so the bundler can resolve `@oxc-parser/binding-wasm32-wasi`.
166
+ If you are building locally with Vite/Rollup/Webpack make sure the WASM binding is installable so the bundler can resolve `@oxc-parser/binding-wasm32-wasi` (details below).
167
+
168
+ ### Installing the WASM binding locally
169
+
170
+ `@oxc-parser/binding-wasm32-wasi` publishes with `"cpu": ["wasm32"]`, so npm/yarn/pnpm skip it on macOS and Linux unless you override the platform guard. Run the helper script after cloning (or whenever you clean `node_modules`) to pull the binding into place for the Vite demo and any other local bundler builds:
171
+
172
+ ```sh
173
+ npm run setup:wasm
174
+ ```
175
+
176
+ The script downloads the published tarball via `npm pack`, extracts it into `node_modules/@oxc-parser/binding-wasm32-wasi`, and removes the temporary archive so your lockfile stays untouched. If you need to test a different binding build, set `WASM_BINDING_PACKAGE` before running the script (for example, `WASM_BINDING_PACKAGE=@oxc-parser/binding-wasm32-wasi@0.100.0 npm run setup:wasm`).
177
+
178
+ Prefer the manual route? You can still run `npm_config_ignore_platform=true npm install --no-save @oxc-parser/binding-wasm32-wasi@^0.99.0`, but the script above replicates the vendored behavior with less ceremony.
98
179
 
99
180
  ### Lite bundle entry
100
181
 
@@ -118,7 +199,7 @@ Tests live in `test/jsx.test.ts` and cover DOM props/events, custom components,
118
199
 
119
200
  ## Browser demo / Vite build
120
201
 
121
- This repo ships with a ready-to-run Vite demo under `examples/browser` that bundles the library (and the WASM binding vendored in `vendor/binding-wasm32-wasi`). Use it for a full end-to-end verification in a real browser (the demo now imports `@knighted/jsx/lite` so you can confirm the lighter entry behaves identically):
202
+ This repo ships with a ready-to-run Vite demo under `examples/browser` that bundles the library (make sure you have installed the WASM binding via the command above first). Use it for a full end-to-end verification in a real browser (the demo imports `@knighted/jsx/lite` so you can confirm the lighter entry behaves identically):
122
203
 
123
204
  ```sh
124
205
  # Start a dev server at http://localhost:5173
@@ -129,7 +210,7 @@ npm run build:demo
129
210
  npm run preview
130
211
  ```
131
212
 
132
- The Vite config aliases `@oxc-parser/binding-wasm32-wasi` to the vendored copy so you don't have to perform any extra install tricks locally, while production consumers can still rely on the published package. For a zero-build verification of the lite bundle, open `examples/esm-demo-lite.html` locally (double-click or run `open examples/esm-demo-lite.html`) or visit the deployed GitHub Pages build produced by `.github/workflows/deploy-demo.yml` (it serves that same lite HTML demo).
213
+ For a zero-build verification of the lite bundle, open `examples/esm-demo-lite.html` locally (double-click or run `open examples/esm-demo-lite.html`) or visit the deployed GitHub Pages build produced by `.github/workflows/deploy-demo.yml` (it serves that same lite HTML demo).
133
214
 
134
215
  ## Limitations
135
216
 
package/dist/cjs/jsx.cjs CHANGED
@@ -2,57 +2,12 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.jsx = void 0;
4
4
  const oxc_parser_1 = require("oxc-parser");
5
- const OPEN_TAG_RE = /<\s*$/;
6
- const CLOSE_TAG_RE = /<\/\s*$/;
7
- const PLACEHOLDER_PREFIX = '__KX_EXPR__';
8
- let invocationCounter = 0;
9
- const parserOptions = {
10
- lang: 'jsx',
11
- sourceType: 'module',
12
- range: true,
13
- preserveParens: true,
14
- };
5
+ const shared_js_1 = require("./runtime/shared.cjs");
15
6
  const ensureDomAvailable = () => {
16
7
  if (typeof document === 'undefined' || typeof document.createElement !== 'function') {
17
8
  throw new Error('The jsx template tag requires a DOM-like environment (document missing).');
18
9
  }
19
10
  };
20
- const formatParserError = (error) => {
21
- let message = `[oxc-parser] ${error.message}`;
22
- if (error.labels?.length) {
23
- const label = error.labels[0];
24
- if (label.message) {
25
- message += `\n${label.message}`;
26
- }
27
- }
28
- if (error.codeframe) {
29
- message += `\n${error.codeframe}`;
30
- }
31
- return message;
32
- };
33
- const extractRootNode = (program) => {
34
- for (const statement of program.body) {
35
- if (statement.type === 'ExpressionStatement') {
36
- const expression = statement.expression;
37
- if (expression.type === 'JSXElement' || expression.type === 'JSXFragment') {
38
- return expression;
39
- }
40
- }
41
- }
42
- throw new Error('The jsx template must contain a single JSX element or fragment.');
43
- };
44
- const getIdentifierName = (identifier) => {
45
- switch (identifier.type) {
46
- case 'JSXIdentifier':
47
- return identifier.name;
48
- case 'JSXNamespacedName':
49
- return `${identifier.namespace.name}:${identifier.name.name}`;
50
- case 'JSXMemberExpression':
51
- return `${getIdentifierName(identifier.object)}.${identifier.property.name}`;
52
- default:
53
- return '';
54
- }
55
- };
56
11
  const isNodeLike = (value) => {
57
12
  if (typeof Node === 'undefined') {
58
13
  return false;
@@ -71,11 +26,6 @@ const isPromiseLike = (value) => {
71
26
  }
72
27
  return typeof value.then === 'function';
73
28
  };
74
- const normalizeJsxText = (value) => {
75
- const collapsed = value.replace(/\r/g, '').replace(/\n\s+/g, ' ');
76
- const trimmed = collapsed.trim();
77
- return trimmed.length > 0 ? trimmed : '';
78
- };
79
29
  const setDomProp = (element, name, value) => {
80
30
  if (value === false || value === null || value === undefined) {
81
31
  return;
@@ -165,17 +115,18 @@ const appendChildValue = (parent, value) => {
165
115
  }
166
116
  parent.appendChild(document.createTextNode(String(value)));
167
117
  };
168
- const resolveAttributes = (attributes, ctx) => {
118
+ const evaluateExpressionWithNamespace = (expression, ctx, namespace) => (0, shared_js_1.evaluateExpression)(expression, ctx, node => evaluateJsxNode(node, ctx, namespace));
119
+ const resolveAttributes = (attributes, ctx, namespace) => {
169
120
  const props = {};
170
121
  attributes.forEach(attribute => {
171
122
  if (attribute.type === 'JSXSpreadAttribute') {
172
- const spreadValue = evaluateExpression(attribute.argument, ctx);
123
+ const spreadValue = evaluateExpressionWithNamespace(attribute.argument, ctx, namespace);
173
124
  if (spreadValue && typeof spreadValue === 'object' && !Array.isArray(spreadValue)) {
174
125
  Object.assign(props, spreadValue);
175
126
  }
176
127
  return;
177
128
  }
178
- const name = getIdentifierName(attribute.name);
129
+ const name = (0, shared_js_1.getIdentifierName)(attribute.name);
179
130
  if (!attribute.value) {
180
131
  props[name] = true;
181
132
  return;
@@ -188,13 +139,13 @@ const resolveAttributes = (attributes, ctx) => {
188
139
  if (attribute.value.expression.type === 'JSXEmptyExpression') {
189
140
  return;
190
141
  }
191
- props[name] = evaluateExpression(attribute.value.expression, ctx);
142
+ props[name] = evaluateExpressionWithNamespace(attribute.value.expression, ctx, namespace);
192
143
  }
193
144
  });
194
145
  return props;
195
146
  };
196
- const applyDomAttributes = (element, attributes, ctx) => {
197
- const props = resolveAttributes(attributes, ctx);
147
+ const applyDomAttributes = (element, attributes, ctx, namespace) => {
148
+ const props = resolveAttributes(attributes, ctx, namespace);
198
149
  Object.entries(props).forEach(([name, value]) => {
199
150
  if (name === 'key') {
200
151
  return;
@@ -211,7 +162,7 @@ const evaluateJsxChildren = (children, ctx, namespace) => {
211
162
  children.forEach(child => {
212
163
  switch (child.type) {
213
164
  case 'JSXText': {
214
- const text = normalizeJsxText(child.value);
165
+ const text = (0, shared_js_1.normalizeJsxText)(child.value);
215
166
  if (text) {
216
167
  resolved.push(text);
217
168
  }
@@ -221,11 +172,11 @@ const evaluateJsxChildren = (children, ctx, namespace) => {
221
172
  if (child.expression.type === 'JSXEmptyExpression') {
222
173
  break;
223
174
  }
224
- resolved.push(evaluateExpression(child.expression, ctx));
175
+ resolved.push(evaluateExpressionWithNamespace(child.expression, ctx, namespace));
225
176
  break;
226
177
  }
227
178
  case 'JSXSpreadChild': {
228
- const spreadValue = evaluateExpression(child.expression, ctx);
179
+ const spreadValue = evaluateExpressionWithNamespace(child.expression, ctx, namespace);
229
180
  if (spreadValue !== undefined && spreadValue !== null) {
230
181
  resolved.push(spreadValue);
231
182
  }
@@ -241,7 +192,7 @@ const evaluateJsxChildren = (children, ctx, namespace) => {
241
192
  return resolved;
242
193
  };
243
194
  const evaluateComponent = (element, ctx, component, namespace) => {
244
- const props = resolveAttributes(element.openingElement.attributes, ctx);
195
+ const props = resolveAttributes(element.openingElement.attributes, ctx, namespace);
245
196
  const childValues = evaluateJsxChildren(element.children, ctx, namespace);
246
197
  if (childValues.length === 1) {
247
198
  props.children = childValues[0];
@@ -257,7 +208,7 @@ const evaluateComponent = (element, ctx, component, namespace) => {
257
208
  };
258
209
  const evaluateJsxElement = (element, ctx, namespace) => {
259
210
  const opening = element.openingElement;
260
- const tagName = getIdentifierName(opening.name);
211
+ const tagName = (0, shared_js_1.getIdentifierName)(opening.name);
261
212
  const component = ctx.components.get(tagName);
262
213
  if (component) {
263
214
  return evaluateComponent(element, ctx, component, namespace);
@@ -270,7 +221,7 @@ const evaluateJsxElement = (element, ctx, namespace) => {
270
221
  const domElement = nextNamespace === 'svg'
271
222
  ? document.createElementNS('http://www.w3.org/2000/svg', tagName)
272
223
  : document.createElement(tagName);
273
- applyDomAttributes(domElement, opening.attributes, ctx);
224
+ applyDomAttributes(domElement, opening.attributes, ctx, nextNamespace);
274
225
  const childValues = evaluateJsxChildren(element.children, ctx, childNamespace);
275
226
  childValues.forEach(value => appendChildValue(domElement, value));
276
227
  return domElement;
@@ -284,119 +235,14 @@ const evaluateJsxNode = (node, ctx, namespace) => {
284
235
  }
285
236
  return evaluateJsxElement(node, ctx, namespace);
286
237
  };
287
- const walkAst = (node, visitor) => {
288
- if (!node || typeof node !== 'object') {
289
- return;
290
- }
291
- const candidate = node;
292
- if (typeof candidate.type !== 'string') {
293
- return;
294
- }
295
- visitor(candidate);
296
- Object.values(candidate).forEach(value => {
297
- if (!value) {
298
- return;
299
- }
300
- if (Array.isArray(value)) {
301
- value.forEach(child => walkAst(child, visitor));
302
- return;
303
- }
304
- if (typeof value === 'object') {
305
- walkAst(value, visitor);
306
- }
307
- });
308
- };
309
- const collectPlaceholderNames = (expression, ctx) => {
310
- const placeholders = new Set();
311
- walkAst(expression, node => {
312
- if (node.type === 'Identifier' && ctx.placeholders.has(node.name)) {
313
- placeholders.add(node.name);
314
- }
315
- });
316
- return Array.from(placeholders);
317
- };
318
- const evaluateExpression = (expression, ctx) => {
319
- if (expression.type === 'JSXElement' || expression.type === 'JSXFragment') {
320
- return evaluateJsxNode(expression, ctx, null);
321
- }
322
- if (!('range' in expression) || !expression.range) {
323
- throw new Error('Unable to evaluate expression: missing source range information.');
324
- }
325
- const [start, end] = expression.range;
326
- const source = ctx.source.slice(start, end);
327
- const placeholders = collectPlaceholderNames(expression, ctx);
328
- try {
329
- const evaluator = new Function(...placeholders, `"use strict"; return (${source});`);
330
- const args = placeholders.map(name => ctx.placeholders.get(name));
331
- return evaluator(...args);
332
- }
333
- catch (error) {
334
- throw new Error(`Failed to evaluate expression ${source}: ${error.message}`);
335
- }
336
- };
337
- const sanitizeIdentifier = (value) => {
338
- const cleaned = value.replace(/[^a-zA-Z0-9_$]/g, '');
339
- if (!cleaned) {
340
- return 'Component';
341
- }
342
- if (!/[A-Za-z_$]/.test(cleaned[0])) {
343
- return `Component${cleaned}`;
344
- }
345
- return cleaned;
346
- };
347
- const ensureBinding = (value, bindings, bindingLookup) => {
348
- const existing = bindingLookup.get(value);
349
- if (existing) {
350
- return existing;
351
- }
352
- const descriptor = value.displayName || value.name || `Component${bindings.length}`;
353
- const baseName = sanitizeIdentifier(descriptor);
354
- let candidate = baseName;
355
- let suffix = 1;
356
- while (bindings.some(binding => binding.name === candidate)) {
357
- candidate = `${baseName}${suffix++}`;
358
- }
359
- const binding = { name: candidate, value };
360
- bindings.push(binding);
361
- bindingLookup.set(value, binding);
362
- return binding;
363
- };
364
- const buildTemplate = (strings, values) => {
365
- const raw = strings.raw ?? strings;
366
- const placeholders = new Map();
367
- const bindings = [];
368
- const bindingLookup = new Map();
369
- let source = raw[0] ?? '';
370
- const templateId = invocationCounter++;
371
- let placeholderIndex = 0;
372
- for (let idx = 0; idx < values.length; idx++) {
373
- const chunk = raw[idx] ?? '';
374
- const nextChunk = raw[idx + 1] ?? '';
375
- const value = values[idx];
376
- const isTagNamePosition = OPEN_TAG_RE.test(chunk) || CLOSE_TAG_RE.test(chunk);
377
- if (isTagNamePosition && typeof value === 'function') {
378
- const binding = ensureBinding(value, bindings, bindingLookup);
379
- source += binding.name + nextChunk;
380
- continue;
381
- }
382
- if (isTagNamePosition && typeof value === 'string') {
383
- source += value + nextChunk;
384
- continue;
385
- }
386
- const placeholder = `${PLACEHOLDER_PREFIX}${templateId}_${placeholderIndex++}__`;
387
- placeholders.set(placeholder, value);
388
- source += placeholder + nextChunk;
389
- }
390
- return { source, placeholders, bindings };
391
- };
392
238
  const jsx = (templates, ...values) => {
393
239
  ensureDomAvailable();
394
- const build = buildTemplate(templates, values);
395
- const result = (0, oxc_parser_1.parseSync)('inline.jsx', build.source, parserOptions);
240
+ const build = (0, shared_js_1.buildTemplate)(templates, values);
241
+ const result = (0, oxc_parser_1.parseSync)('inline.jsx', build.source, shared_js_1.parserOptions);
396
242
  if (result.errors.length > 0) {
397
- throw new Error(formatParserError(result.errors[0]));
243
+ throw new Error((0, shared_js_1.formatParserError)(result.errors[0]));
398
244
  }
399
- const root = extractRootNode(result.program);
245
+ const root = (0, shared_js_1.extractRootNode)(result.program);
400
246
  const ctx = {
401
247
  source: build.source,
402
248
  placeholders: build.placeholders,