resuxjs 0.2.6 → 0.2.8

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
@@ -8,19 +8,7 @@ This is an MVP, not a production-ready framework.
8
8
 
9
9
  ## Create App
10
10
 
11
- Resux is published as one npm package. After publishing, users can scaffold an app with the same package they install in the app:
12
-
13
- ```sh
14
- npm create resuxjs@latest
15
- ```
16
-
17
- With a project directory:
18
-
19
- ```sh
20
- npm create resuxjs@latest my-app
21
- ```
22
-
23
- Equivalent direct package command:
11
+ Create a new app with the latest published Resux package:
24
12
 
25
13
  ```sh
26
14
  npx resuxjs@latest init
@@ -43,7 +31,7 @@ Generated apps use a single Resux dependency, similar to Nuxt apps installing `n
43
31
  ```json
44
32
  {
45
33
  "dependencies": {
46
- "resuxjs": "^0.1.0"
34
+ "resuxjs": "^0.2.8"
47
35
  }
48
36
  }
49
37
  ```
@@ -93,24 +81,6 @@ npm run pack:check
93
81
 
94
82
  This builds, tests, and dry-runs npm packing for the single `resuxjs` package.
95
83
 
96
- ## Publishing
97
-
98
- Publish the single package:
99
-
100
- ```sh
101
- npm publish --access public
102
- ```
103
-
104
- After `resuxjs` is published, users can run `npx resuxjs@latest init`.
105
-
106
- ## Compatibility Policy
107
-
108
- Resux follows npm semver starting with the `0.1.x` release line.
109
-
110
- - Patch releases, such as `0.1.1`, preserve compatibility for documented APIs, generated starter structure, CLI commands, config keys, file-based routing conventions, and runtime payload formats.
111
- - Minor releases before `1.0.0`, such as `0.2.0`, may include breaking changes, but they must be documented in release notes and migration guidance before publishing.
112
- - Experimental or undocumented internals, including generated files under `.resux`, may change between releases unless they are explicitly documented as public API.
113
-
114
84
  ## CLI
115
85
 
116
86
  The `resux` CLI supports:
@@ -154,12 +124,17 @@ Generated apps include `env.d.ts` and `tsconfig.json` wired to `resuxjs/globals`
154
124
  ```ts
155
125
  const count = useState("count", () => 0)
156
126
  const route = useRoute()
127
+ const router = useRouter()
157
128
  useSeoMeta({
158
129
  title: "My App",
159
130
  description: "My app description",
160
131
  ogTitle: "My App"
161
132
  })
162
133
 
134
+ function openAbout() {
135
+ router.push("/about")
136
+ }
137
+
163
138
  export default defineResuxConfig({
164
139
  app: {
165
140
  head: {
@@ -238,11 +213,6 @@ Resux supports first-party and third-party build-time modules in `resux.config.t
238
213
  ```ts
239
214
  export default defineResuxConfig({
240
215
  modules: [
241
- ["resux:seo", {
242
- title: "My App",
243
- description: "A Resux application.",
244
- themeColor: "#2563eb"
245
- }],
246
216
  "resux:security",
247
217
  ["resux:performance", { assetMaxAge: 31536000 }],
248
218
  ["./modules/security.ts", { header: "enabled" }]
@@ -256,7 +226,6 @@ export default defineResuxConfig({
256
226
 
257
227
  Built-in modules:
258
228
 
259
- - `resux:seo`: adds title, description, Open Graph, Twitter card, theme color, and optional link tags.
260
229
  - `resux:security`: adds default production hardening headers and optional custom headers or CSP through route rules.
261
230
  - `resux:performance`: adds immutable cache rules for built Resux runtime/handler assets and `no-store` for route payloads.
262
231
 
@@ -329,7 +298,7 @@ Server middleware can continue by returning nothing, end the Node response direc
329
298
  - Resumable event handlers such as `@click="increment"`.
330
299
  - Lazy client handler chunks loaded on first interaction.
331
300
  - Client-side navigation, persistent same-layout DOM, built-in route transition progress, and hover/focus route payload prefetch for same-origin links.
332
- - MVP composables: `useState`, `useAsyncData`, `useRoute`, `useHead`, `useSeoMeta`, `useRuntimeConfig`, `useResuxApp`, `useFetch`, `$fetch`, and `onMounted`.
301
+ - MVP composables: `useState`, `useAsyncData`, `useRoute`, `useRouter`, `useHead`, `useSeoMeta`, `useRuntimeConfig`, `useResuxApp`, `useFetch`, `$fetch`, and `onMounted`.
333
302
  - `useAsyncData` returns a resource with reactive `data`, `pending`, and `error` refs, plus `value` as a data alias for compatibility. It still works with `await` when you want to block setup.
334
303
 
335
304
  ## Component Syntax
@@ -399,6 +368,8 @@ The MVP compiler supports:
399
368
  - `<ResuxLink to="/path">`.
400
369
  - `defineProps()` in components.
401
370
  - `definePageMeta({ layout, middleware, title, meta })`.
371
+ - `useRoute()` for the current path, params, and query.
372
+ - `useRouter().push("/path")`, `replace`, `back`, `forward`, and `go`.
402
373
  - `useHead({ title, meta, link })`.
403
374
  - `useSeoMeta({ title, description, ogTitle, ogImage, twitterCard })`.
404
375
  - `onMounted()`, run when the component scope is first resumed in the browser.
@@ -248,7 +248,8 @@ export function compileVueSource(source, options) {
248
248
  throw new ResuxCompileError("Resux components need a <template> block.", locationFromOffset(options.file, source, 0));
249
249
  }
250
250
  const script = descriptor.scriptSetup?.content ?? "";
251
- const template = compileTemplate(descriptor.template.content, options.file);
251
+ const templateRefBindings = inferTemplateRefBindings(script, options.file);
252
+ const template = compileTemplate(descriptor.template.content, options.file, templateRefBindings);
252
253
  const analysis = analyzeScript(script, options.file, template.inlineHandlers);
253
254
  validateTemplateHandlers(template.handlers, analysis, options.file, source);
254
255
  const serverSource = createComponentModuleSource({
@@ -315,10 +316,11 @@ export function createRouteManifest(root, files, idByFile, compiledByFile) {
315
316
  })
316
317
  .sort((a, b) => routeScore(b.path) - routeScore(a.path) || a.path.localeCompare(b.path));
317
318
  }
318
- function compileTemplate(template, file) {
319
+ function compileTemplate(template, file, templateRefBindings = new Set()) {
319
320
  const ast = parseTemplate(template, { comments: false });
320
321
  const state = {
321
322
  file,
323
+ templateRefBindings,
322
324
  bindingIndex: 0,
323
325
  inlineHandlerIndex: 0,
324
326
  handlers: [],
@@ -340,7 +342,7 @@ function compileTemplateNode(node, state) {
340
342
  if (node.type === NodeTypes.INTERPOLATION) {
341
343
  return {
342
344
  type: "interpolation",
343
- expression: node.content.content,
345
+ expression: transformTemplateExpression(node.content.content, state.templateRefBindings, state.file, node),
344
346
  bindingId: nextBindingId(state)
345
347
  };
346
348
  }
@@ -377,7 +379,7 @@ function compileTemplateNode(node, state) {
377
379
  attrs.push({
378
380
  kind: "dynamic",
379
381
  name: arg,
380
- value: expression,
382
+ value: transformTemplateExpression(expression, state.templateRefBindings, state.file, prop),
381
383
  bindingId: nextBindingId(state)
382
384
  });
383
385
  continue;
@@ -407,7 +409,7 @@ function compileTemplateNode(node, state) {
407
409
  throw new ResuxCompileError("v-if needs an expression.", locationFromVueNode(state.file, prop));
408
410
  }
409
411
  element.if = {
410
- expression,
412
+ expression: transformTemplateExpression(expression, state.templateRefBindings, state.file, prop),
411
413
  blockId: nextBindingId(state)
412
414
  };
413
415
  continue;
@@ -418,6 +420,7 @@ function compileTemplateNode(node, state) {
418
420
  throw new ResuxCompileError("v-for needs an expression.", locationFromVueNode(state.file, prop));
419
421
  }
420
422
  element.for = parseForExpression(expression, state.file, prop, state);
423
+ element.for.source = transformTemplateExpression(element.for.source, state.templateRefBindings, state.file, prop);
421
424
  continue;
422
425
  }
423
426
  if (prop.name === "show") {
@@ -428,7 +431,7 @@ function compileTemplateNode(node, state) {
428
431
  attrs.push({
429
432
  kind: "dynamic",
430
433
  name: "hidden",
431
- value: `!(${expression})`,
434
+ value: `!(${transformTemplateExpression(expression, state.templateRefBindings, state.file, prop)})`,
432
435
  bindingId: nextBindingId(state)
433
436
  });
434
437
  continue;
@@ -440,7 +443,7 @@ function compileTemplateNode(node, state) {
440
443
  }
441
444
  element.children = [{
442
445
  type: "interpolation",
443
- expression,
446
+ expression: transformTemplateExpression(expression, state.templateRefBindings, state.file, prop),
444
447
  bindingId: nextBindingId(state)
445
448
  }];
446
449
  continue;
@@ -451,7 +454,7 @@ function compileTemplateNode(node, state) {
451
454
  throw new ResuxCompileError("v-html needs an expression.", locationFromVueNode(state.file, prop));
452
455
  }
453
456
  element.html = {
454
- expression,
457
+ expression: transformTemplateExpression(expression, state.templateRefBindings, state.file, prop),
455
458
  bindingId: nextBindingId(state)
456
459
  };
457
460
  element.children = [];
@@ -469,7 +472,7 @@ function compileTemplateNode(node, state) {
469
472
  attrs.push({
470
473
  kind: "dynamic",
471
474
  name: model.attribute,
472
- value: model.value,
475
+ value: transformTemplateExpression(model.value, state.templateRefBindings, state.file, prop),
473
476
  bindingId: nextBindingId(state)
474
477
  });
475
478
  const event = {
@@ -499,9 +502,10 @@ function createModelBinding(tag, props, expression, state) {
499
502
  const isCheckbox = inputType === "checkbox";
500
503
  const handler = nextInlineHandlerName(state);
501
504
  const target = "$event.target";
505
+ const assignmentExpression = state.templateRefBindings.has(expression.trim()) ? `${expression.trim()}.value` : expression;
502
506
  const assignment = isCheckbox
503
- ? `${expression} = Boolean(${target} && ${target}.checked)`
504
- : `${expression} = ${target} ? ${target}.value : ""`;
507
+ ? `${assignmentExpression} = Boolean(${target} && ${target}.checked)`
508
+ : `${assignmentExpression} = ${target} ? ${target}.value : ""`;
505
509
  state.inlineHandlers.push({
506
510
  name: handler,
507
511
  source: `function ${handler}($event) {\n${assignment}\n}`
@@ -517,6 +521,55 @@ function staticAttributeValue(props, name) {
517
521
  const attr = props.find((prop) => prop.type === NodeTypes.ATTRIBUTE && prop.name === name);
518
522
  return attr?.value?.content;
519
523
  }
524
+ function transformTemplateExpression(expression, templateRefBindings, file, node) {
525
+ if (templateRefBindings.size === 0) {
526
+ return expression;
527
+ }
528
+ const wrapped = `(${expression})`;
529
+ const sourceFile = ts.createSourceFile(`${file}?template-expression`, wrapped, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
530
+ if ((sourceFile.parseDiagnostics ?? []).length > 0) {
531
+ throw new ResuxCompileError("Template expression is not valid JavaScript.", locationFromVueNode(file, node));
532
+ }
533
+ const insertions = [];
534
+ const visit = (current) => {
535
+ if (ts.isIdentifier(current) && templateRefBindings.has(current.text) && shouldAutoUnwrapTemplateIdentifier(current)) {
536
+ const position = current.end - 1;
537
+ if (position >= 0 && position <= expression.length) {
538
+ insertions.push(position);
539
+ }
540
+ }
541
+ ts.forEachChild(current, visit);
542
+ };
543
+ visit(sourceFile);
544
+ if (insertions.length === 0) {
545
+ return expression;
546
+ }
547
+ const uniqueInsertions = [...new Set(insertions)].sort((a, b) => b - a);
548
+ let transformed = expression;
549
+ for (const position of uniqueInsertions) {
550
+ transformed = `${transformed.slice(0, position)}.value${transformed.slice(position)}`;
551
+ }
552
+ return transformed;
553
+ }
554
+ function shouldAutoUnwrapTemplateIdentifier(node) {
555
+ const parent = node.parent;
556
+ if (!parent) {
557
+ return true;
558
+ }
559
+ if (ts.isPropertyAccessExpression(parent)) {
560
+ if (parent.expression === node && parent.name.text === "value") {
561
+ return false;
562
+ }
563
+ return parent.name !== node;
564
+ }
565
+ if (ts.isPropertyAssignment(parent) && parent.name === node) {
566
+ return false;
567
+ }
568
+ if (ts.isShorthandPropertyAssignment(parent) || ts.isBindingElement(parent)) {
569
+ return false;
570
+ }
571
+ return true;
572
+ }
520
573
  function isAssignableExpression(expression) {
521
574
  return /^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*|\[[^\]]+\])*$/.test(expression.trim());
522
575
  }
@@ -579,6 +632,7 @@ function analyzeScript(script, file, inlineHandlers = []) {
579
632
  const bindings = new Set();
580
633
  const handlerNames = new Set();
581
634
  const resumableBindings = new Set();
635
+ const templateRefBindings = inferTemplateRefBindings(script, file);
582
636
  const handlers = new Map();
583
637
  let pageMeta;
584
638
  for (const statement of sourceFile.statements) {
@@ -633,11 +687,60 @@ function analyzeScript(script, file, inlineHandlers = []) {
633
687
  bindings: [...bindings],
634
688
  handlerNames,
635
689
  resumableBindings,
690
+ templateRefBindings,
636
691
  handlers,
637
692
  sourceFile,
638
693
  pageMeta
639
694
  };
640
695
  }
696
+ function inferTemplateRefBindings(script, file) {
697
+ const sourceFile = ts.createSourceFile(file, script, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
698
+ const bindings = new Set();
699
+ for (const statement of sourceFile.statements) {
700
+ if (!ts.isVariableStatement(statement)) {
701
+ continue;
702
+ }
703
+ for (const declaration of statement.declarationList.declarations) {
704
+ const initializer = unwrapAwaitExpression(declaration.initializer);
705
+ if (!initializer || !ts.isCallExpression(initializer)) {
706
+ continue;
707
+ }
708
+ const callee = initializer.expression;
709
+ const calleeName = ts.isIdentifier(callee)
710
+ ? callee.text
711
+ : ts.isPropertyAccessExpression(callee) && ts.isIdentifier(callee.name)
712
+ ? callee.name.text
713
+ : "";
714
+ if (ts.isIdentifier(declaration.name) && isTemplateRefFactory(calleeName)) {
715
+ bindings.add(declaration.name.text);
716
+ continue;
717
+ }
718
+ if (ts.isObjectBindingPattern(declaration.name) && isAsyncDataFactory(calleeName)) {
719
+ for (const element of declaration.name.elements) {
720
+ if (!ts.isBindingElement(element) || !ts.isIdentifier(element.name)) {
721
+ continue;
722
+ }
723
+ const propertyName = element.propertyName && ts.isIdentifier(element.propertyName)
724
+ ? element.propertyName.text
725
+ : element.name.text;
726
+ if (["data", "pending", "error", "value"].includes(propertyName)) {
727
+ bindings.add(element.name.text);
728
+ }
729
+ }
730
+ }
731
+ }
732
+ }
733
+ return bindings;
734
+ }
735
+ function unwrapAwaitExpression(node) {
736
+ return node && ts.isAwaitExpression(node) ? node.expression : node;
737
+ }
738
+ function isTemplateRefFactory(name) {
739
+ return ["ref", "computed", "shallowRef", "useState", "useAsyncData", "useFetch"].includes(name);
740
+ }
741
+ function isAsyncDataFactory(name) {
742
+ return ["useAsyncData", "useFetch"].includes(name);
743
+ }
641
744
  function isDefinePageMetaStatement(statement) {
642
745
  return ts.isExpressionStatement(statement)
643
746
  && ts.isCallExpression(statement.expression)
@@ -774,7 +877,7 @@ function isResumableInitializer(node) {
774
877
  return false;
775
878
  }
776
879
  if (ts.isCallExpression(node) && ts.isIdentifier(node.expression)) {
777
- return ["useState", "useAsyncData", "useRoute", "useRuntimeConfig", "useResuxApp", "defineProps"].includes(node.expression.text);
880
+ return ["useState", "useAsyncData", "useRoute", "useRouter", "useRuntimeConfig", "useResuxApp", "defineProps"].includes(node.expression.text);
778
881
  }
779
882
  if (ts.isAwaitExpression(node) && ts.isCallExpression(node.expression) && ts.isIdentifier(node.expression.expression)) {
780
883
  return ["useAsyncData", "useFetch"].includes(node.expression.expression.text);
@@ -801,7 +904,7 @@ function createComponentModuleSource(options) {
801
904
  options.analysis.imports,
802
905
  `const __template = ${JSON.stringify(options.template, null, 2)};`,
803
906
  `async function __rx_setup(__ctx) {`,
804
- `const { useState, useAsyncData, useRoute, useHead, useSeoMeta, useRuntimeConfig, useResuxApp, useFetch, $fetch, onMounted, definePageMeta, defineProps } = __ctx;`,
907
+ `const { useState, useAsyncData, useRoute, useRouter, useHead, useSeoMeta, useRuntimeConfig, useResuxApp, useFetch, $fetch, onMounted, definePageMeta, defineProps } = __ctx;`,
805
908
  options.analysis.setupBody,
806
909
  `return { ${options.analysis.bindings.join(", ")} };`,
807
910
  `}`,
@@ -1279,42 +1382,6 @@ function resolveBuiltinModule(specifier) {
1279
1382
  return builtinModules[normalized] ?? null;
1280
1383
  }
1281
1384
  const builtinModules = {
1282
- seo: {
1283
- defaults: {},
1284
- setup(options, resux) {
1285
- const input = isPlainObject(options) ? options : {};
1286
- const meta = [];
1287
- const title = firstString(input.title);
1288
- const description = firstString(input.description);
1289
- const image = firstString(input.image);
1290
- const themeColor = firstString(input.themeColor);
1291
- const twitterCard = firstString(input.twitterCard) ?? "summary_large_image";
1292
- if (description) {
1293
- meta.push({ name: "description", content: description });
1294
- meta.push({ property: "og:description", content: description });
1295
- meta.push({ name: "twitter:description", content: description });
1296
- }
1297
- if (title) {
1298
- meta.push({ property: "og:title", content: title });
1299
- meta.push({ name: "twitter:title", content: title });
1300
- }
1301
- if (image) {
1302
- meta.push({ property: "og:image", content: image });
1303
- meta.push({ name: "twitter:image", content: image });
1304
- }
1305
- if (themeColor) {
1306
- meta.push({ name: "theme-color", content: themeColor });
1307
- }
1308
- if (twitterCard) {
1309
- meta.push({ name: "twitter:card", content: twitterCard });
1310
- }
1311
- resux.addHead({
1312
- ...(title ? { title } : {}),
1313
- ...(meta.length ? { meta } : {}),
1314
- ...(Array.isArray(input.link) ? { link: input.link.filter(isPlainObject) } : {})
1315
- });
1316
- }
1317
- },
1318
1385
  security: {
1319
1386
  defaults: {
1320
1387
  route: "/**",