netjes 0.0.4 → 0.0.6

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.
Files changed (123) hide show
  1. package/README.md +12 -8
  2. package/cli/commands.mjs +94 -15
  3. package/cli/process-io.mjs +2 -2
  4. package/cli/scaffold.mjs +89 -8
  5. package/dist/actions.d.ts +3 -2
  6. package/dist/actions.d.ts.map +1 -1
  7. package/dist/actions.js +5 -4
  8. package/dist/actions.js.map +1 -1
  9. package/dist/client-entry.js +4 -1
  10. package/dist/client-entry.js.map +1 -1
  11. package/dist/document.d.ts +3 -1
  12. package/dist/document.d.ts.map +1 -1
  13. package/dist/document.js +4 -3
  14. package/dist/document.js.map +1 -1
  15. package/dist/index.d.ts +4 -3
  16. package/dist/index.d.ts.map +1 -1
  17. package/dist/index.js +3 -2
  18. package/dist/index.js.map +1 -1
  19. package/dist/lang.d.ts +10 -0
  20. package/dist/lang.d.ts.map +1 -0
  21. package/dist/lang.js +26 -0
  22. package/dist/lang.js.map +1 -0
  23. package/dist/link.d.ts +15 -3
  24. package/dist/link.d.ts.map +1 -1
  25. package/dist/link.js +15 -9
  26. package/dist/link.js.map +1 -1
  27. package/dist/locale.d.ts +5 -0
  28. package/dist/locale.d.ts.map +1 -1
  29. package/dist/locale.js +4 -0
  30. package/dist/locale.js.map +1 -1
  31. package/dist/metadata.d.ts +81 -4
  32. package/dist/metadata.d.ts.map +1 -1
  33. package/dist/metadata.js +129 -7
  34. package/dist/metadata.js.map +1 -1
  35. package/dist/modules.d.ts +6 -1
  36. package/dist/modules.d.ts.map +1 -1
  37. package/dist/modules.js +15 -1
  38. package/dist/modules.js.map +1 -1
  39. package/dist/mounted.d.ts +3 -7
  40. package/dist/mounted.d.ts.map +1 -1
  41. package/dist/mounted.js.map +1 -1
  42. package/dist/navigation-guard.d.ts +59 -0
  43. package/dist/navigation-guard.d.ts.map +1 -0
  44. package/dist/navigation-guard.js +116 -0
  45. package/dist/navigation-guard.js.map +1 -0
  46. package/dist/offline.d.ts +11 -0
  47. package/dist/offline.d.ts.map +1 -0
  48. package/dist/offline.js +98 -0
  49. package/dist/offline.js.map +1 -0
  50. package/dist/payload.d.ts +38 -2
  51. package/dist/payload.d.ts.map +1 -1
  52. package/dist/payload.js +54 -7
  53. package/dist/payload.js.map +1 -1
  54. package/dist/render-document.d.ts +8 -1
  55. package/dist/render-document.d.ts.map +1 -1
  56. package/dist/render-document.js +2 -0
  57. package/dist/render-document.js.map +1 -1
  58. package/dist/root.d.ts.map +1 -1
  59. package/dist/root.js +10 -1
  60. package/dist/root.js.map +1 -1
  61. package/dist/route-tree.d.ts +2 -1
  62. package/dist/route-tree.d.ts.map +1 -1
  63. package/dist/route-tree.js +14 -7
  64. package/dist/route-tree.js.map +1 -1
  65. package/dist/router.d.ts +101 -20
  66. package/dist/router.d.ts.map +1 -1
  67. package/dist/router.js +590 -68
  68. package/dist/router.js.map +1 -1
  69. package/dist/schema.d.ts +2 -0
  70. package/dist/schema.d.ts.map +1 -1
  71. package/dist/schema.js +5 -0
  72. package/dist/schema.js.map +1 -1
  73. package/dist/service-worker.d.ts +81 -0
  74. package/dist/service-worker.d.ts.map +1 -0
  75. package/dist/service-worker.js +584 -0
  76. package/dist/service-worker.js.map +1 -0
  77. package/dist/testing.d.ts +18 -0
  78. package/dist/testing.d.ts.map +1 -1
  79. package/dist/testing.js +63 -22
  80. package/dist/testing.js.map +1 -1
  81. package/package.json +16 -5
  82. package/sidecar/server.mjs +105 -16
  83. package/skills/netjes/SKILL.md +5 -3
  84. package/skills/netjes/references/caching-and-streaming.md +22 -1
  85. package/skills/netjes/references/data-and-actions.md +5 -4
  86. package/skills/netjes/references/deployment.md +3 -3
  87. package/skills/netjes/references/routing.md +14 -6
  88. package/skills/netjes/references/testing.md +6 -3
  89. package/src/actions.tsx +5 -4
  90. package/src/client-entry.tsx +4 -1
  91. package/src/document.tsx +17 -5
  92. package/src/index.ts +12 -2
  93. package/src/lang.ts +28 -0
  94. package/src/link.tsx +37 -9
  95. package/src/locale.ts +5 -0
  96. package/src/metadata.tsx +207 -11
  97. package/src/modules.ts +19 -3
  98. package/src/mounted.tsx +3 -3
  99. package/src/navigation-guard.ts +136 -0
  100. package/src/offline.ts +97 -0
  101. package/src/payload.ts +78 -8
  102. package/src/render-document.tsx +10 -1
  103. package/src/root.tsx +22 -10
  104. package/src/route-tree.tsx +18 -7
  105. package/src/router.tsx +765 -104
  106. package/src/schema.ts +11 -0
  107. package/src/service-worker.ts +632 -0
  108. package/src/testing-vitest.ts +1 -1
  109. package/src/testing.tsx +68 -15
  110. package/template/Dockerfile +1 -1
  111. package/template/Dockerfile.pnpm +68 -0
  112. package/template/Dockerfile.workspace +52 -0
  113. package/template/Dockerfile.workspace.dockerignore +15 -0
  114. package/template/README.md +6 -2
  115. package/template/_AGENTS.md +9 -3
  116. package/template/app/layout.tsx +0 -1
  117. package/template/docker-compose.override.yml +15 -3
  118. package/template/generated/netjes.ts +1 -1
  119. package/tsconfig.strict-app.json +27 -0
  120. package/vite/packages.mjs +97 -0
  121. package/vite/plugin.d.ts +8 -1
  122. package/vite/plugin.mjs +156 -9
  123. /package/template/{public/favicon.svg → app/icon.svg} +0 -0
package/vite/plugin.mjs CHANGED
@@ -1,15 +1,17 @@
1
1
  // @ts-check
2
- import { readFileSync } from 'node:fs';
3
- import { copyFile, mkdir, readdir, writeFile } from 'node:fs/promises';
4
- import { createRequire } from 'node:module';
2
+ import { createHash } from 'node:crypto';
3
+ import { existsSync, readFileSync, statSync } from 'node:fs';
4
+ import { copyFile, mkdir, readFile, readdir, stat, writeFile } from 'node:fs/promises';
5
+ import { createRequire, registerHooks } from 'node:module';
5
6
  import path from 'node:path';
6
- import { fileURLToPath } from 'node:url';
7
+ import { fileURLToPath, pathToFileURL } from 'node:url';
7
8
  import react from '@vitejs/plugin-react';
8
- import { normalizePath, searchForWorkspaceRoot } from 'vite';
9
+ import { build, normalizePath, searchForWorkspaceRoot } from 'vite';
9
10
  import { findPackage } from '../cli/packages.mjs';
10
11
  import {
11
12
  CONVENTION_EXTENSIONS,
12
13
  CONVENTION_FILES,
14
+ checkPackageTsconfig,
13
15
  commonJsDependencies,
14
16
  fileId,
15
17
  filePath,
@@ -46,6 +48,40 @@ const RESOLVED_QUERY_ID = `\0${QUERY_ID}`;
46
48
  */
47
49
  const isTailwindStylesheet = (id) =>
48
50
  !/[?&](?:worker|sharedworker|raw|url)\b|\?commonjs-proxy/.test(id) && !id.includes('/.vite/') && (id.split('?')[0] ?? id).endsWith('.css');
51
+ /**
52
+ * A metadata file's name at the root of the app directory (MetadataFiles.cs has the same rule): favicon.ico, icon and
53
+ * icon1, icon2, ... in .ico, .png, .svg, .jpg or .jpeg, apple-icon and on in .png, .jpg or .jpeg, and the web app
54
+ * manifest. Lower case only.
55
+ */
56
+ const METADATA_FILE = /^(?:favicon\.ico|icon[0-9]*\.(?:ico|png|svg|jpg|jpeg)|apple-icon[0-9]*\.(?:png|jpg|jpeg)|manifest\.(?:webmanifest|json))$/;
57
+
58
+ /**
59
+ * The metadata files at the root of a folder, in ordinal order: files, and links to files, as the .NET app reads them
60
+ * in development.
61
+ * @param {string} dir
62
+ * @returns {Promise<string[]>}
63
+ */
64
+ async function metadataFiles(dir) {
65
+ /** @type {import('node:fs').Dirent[]} */
66
+ let entries;
67
+ try {
68
+ entries = await readdir(dir, { withFileTypes: true });
69
+ } catch {
70
+ return [];
71
+ }
72
+ const found = await Promise.all(
73
+ entries
74
+ .filter((entry) => METADATA_FILE.test(entry.name))
75
+ .map(async (entry) => {
76
+ if (entry.isFile()) return entry.name;
77
+ if (!entry.isSymbolicLink()) return null;
78
+ const target = await stat(path.join(dir, entry.name)).catch(() => null);
79
+ return target?.isFile() ? entry.name : null;
80
+ }),
81
+ );
82
+ return found.filter((name) => name !== null).sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));
83
+ }
84
+
49
85
  /** The URL the .NET dev asset resolver points browsers at. */
50
86
  const DEV_CLIENT_ENTRY_URL = '/@netjes/client-entry';
51
87
 
@@ -82,10 +118,27 @@ function backendDirs(dir) {
82
118
  */
83
119
  const literalGlob = (file) => file.replace(/[()[\]{}*?|]|[!+@](?=\()/g, '\\$&');
84
120
 
85
- /** Loads @tailwindcss/vite only when Tailwind is on, so apps that turn it off need not install it. */
86
- async function tailwind() {
121
+ /** @param {string} root */
122
+ async function loadTailwind(root) {
87
123
  try {
88
- const { default: plugin } = await import('@tailwindcss/vite');
124
+ let entry;
125
+ const parentURL = pathToFileURL(path.join(root, 'package.json')).href;
126
+ // Use Node's import conditions with the app as the parent, without a startup flag for import.meta.resolve.
127
+ const hooks = registerHooks({
128
+ resolve: (specifier, context, nextResolve) => nextResolve(specifier, { ...context, parentURL }),
129
+ });
130
+ try {
131
+ entry = import.meta.resolve('@tailwindcss/vite');
132
+ } catch (error) {
133
+ if (!(error instanceof Error && 'code' in error && error.code === 'ERR_MODULE_NOT_FOUND')) throw error;
134
+ } finally {
135
+ hooks.deregister();
136
+ }
137
+ // import.meta.resolve can return a URL even when the export's target file is missing.
138
+ /** @type {typeof import('@tailwindcss/vite')} */
139
+ const { default: plugin } = entry && statSync(new URL(entry), { throwIfNoEntry: false })?.isFile()
140
+ ? await import(entry)
141
+ : await import('@tailwindcss/vite');
89
142
  return plugin();
90
143
  } catch (error) {
91
144
  throw new Error(
@@ -96,6 +149,42 @@ async function tailwind() {
96
149
  }
97
150
  }
98
151
 
152
+ /** Loads Tailwind once Vite has the app's root and shares its state across the app's environments. @returns {import('vite').Plugin} */
153
+ function tailwindForApp() {
154
+ /** @type {WeakMap<import('vite').ResolvedConfig, { plugins: import('vite').Plugin[], serverHooks: import('vite').ServerHook[] }>} */
155
+ const tailwind = new WeakMap();
156
+ return {
157
+ name: 'netjes:tailwind',
158
+ enforce: 'pre',
159
+ async configResolved(config) {
160
+ /** @type {import('vite').Plugin[]} */
161
+ const plugins = [];
162
+ /** @type {import('vite').ServerHook[]} */
163
+ const serverHooks = [];
164
+ // Tailwind's Vite-wide hooks run here and in configureServer. Vite runs the remaining hooks per environment.
165
+ for (const { apply, configResolved, configureServer, ...plugin } of await loadTailwind(config.root)) {
166
+ if (typeof apply === 'string' && apply !== config.command) continue;
167
+ const resolved = typeof configResolved === 'function' ? configResolved : configResolved?.handler;
168
+ await resolved?.call(this, config);
169
+ const server = typeof configureServer === 'function' ? configureServer : configureServer?.handler;
170
+ if (server) serverHooks.push(server);
171
+ plugins.push(plugin);
172
+ }
173
+ tailwind.set(config, { plugins, serverHooks });
174
+ },
175
+ async configureServer(server) {
176
+ /** @type {Array<() => void>} */
177
+ const postHooks = [];
178
+ for (const hook of tailwind.get(server.config)?.serverHooks ?? []) {
179
+ const post = await hook.call(this, server);
180
+ if (post) postHooks.push(post);
181
+ }
182
+ return () => postHooks.forEach((hook) => hook());
183
+ },
184
+ applyToEnvironment: (environment) => tailwind.get(environment.getTopLevelConfig())?.plugins ?? [],
185
+ };
186
+ }
187
+
99
188
  /**
100
189
  * Whether the app (or a parent workspace) can import a package.
101
190
  * @param {string} root
@@ -214,6 +303,10 @@ export default function netjes(options = {}) {
214
303
  let rootDir = '';
215
304
  /** @type {string} */
216
305
  let outDir = '';
306
+ /** Vite's public directory, or '' when it has none. @type {string} */
307
+ let publicDir = '';
308
+ /** @type {import('vite').ResolvedConfig} */
309
+ let resolvedConfig;
217
310
  /** @type {import('vite').ViteDevServer | undefined} */
218
311
  let devServer;
219
312
  /** The page packages the app lists, read when the config is. @type {import('./packages.mjs').PagePackage[]} */
@@ -282,6 +375,7 @@ export default function netjes(options = {}) {
282
375
  ...test,
283
376
  ...base,
284
377
  appType: 'custom',
378
+ define: { __NETJES_DEV__: JSON.stringify(env.command === 'serve') },
285
379
  // One copy of each, even when netjes is linked (a `file:` dependency, npm link) and has its own node_modules.
286
380
  resolve: {
287
381
  dedupe: [
@@ -351,12 +445,17 @@ export default function netjes(options = {}) {
351
445
  };
352
446
  },
353
447
  configResolved(config) {
448
+ resolvedConfig = config;
354
449
  rootDir = config.root;
355
450
  outDir = path.resolve(config.root, config.build.outDir);
451
+ publicDir = config.publicDir || '';
356
452
  },
357
453
  // The app's route table stops it on a route handler in development, and in every command that starts it. A build
358
454
  // takes only the convention files, so it would leave one out without a word: it stops on it too, saying the same.
359
455
  async buildStart() {
456
+ for (const pkg of packages) {
457
+ if (pkg.linked) checkPackageTsconfig(pkg);
458
+ }
360
459
  if (!isBuild) return;
361
460
  let handler = await findRouteHandler(rootDir, appDir);
362
461
  // A package's, by its file id, as the route table names it.
@@ -368,6 +467,16 @@ export default function netjes(options = {}) {
368
467
  if (handler) {
369
468
  this.error(`'${handler}': route handlers are C# in Netjes. Map a minimal API endpoint instead (app.MapGet, app.MapPost, ...).`);
370
469
  }
470
+ // The client build copies public/ and the metadata files into one folder: the same name in both would be one file.
471
+ if (isSsrBuild || !publicDir) return;
472
+ for (const name of await metadataFiles(path.join(rootDir, appDir))) {
473
+ if (!existsSync(path.join(publicDir, name))) continue;
474
+ const where = (/** @type {string} */ dir) => normalizePath(path.relative(rootDir, path.join(dir, name)));
475
+ this.error(
476
+ `netjes: ${where(publicDir)} and ${where(path.join(rootDir, appDir))} are both served at /${name}. ` +
477
+ `Keep one: the file in ${appDir}/ is linked from every page, the one in public/ only served.`,
478
+ );
479
+ }
371
480
  },
372
481
  configureServer(server) {
373
482
  devServer = server;
@@ -440,6 +549,44 @@ export default function netjes(options = {}) {
440
549
  await copyFile(SIDECAR, path.join(outDir, 'netjes-sidecar.mjs'));
441
550
  return;
442
551
  }
552
+ // The metadata files at the root of the app directory, served at the site root from the client build, and the
553
+ // list of them the .NET app links: not every file in dist/client, which also holds what Vite copied from public/.
554
+ const metadata = await metadataFiles(path.join(rootDir, appDir));
555
+ if (metadata.length > 0) {
556
+ await Promise.all(metadata.map((name) => copyFile(path.join(rootDir, appDir, name), path.join(outDir, name))));
557
+ await mkdir(path.join(outDir, '.vite'), { recursive: true });
558
+ await writeFile(path.join(outDir, '.vite', 'metadata-files.json'), `${JSON.stringify({ files: metadata }, null, 2)}\n`);
559
+ }
560
+ // netjes export requests each page under it, so app.UsePathBase sees the base path the assets were built for.
561
+ if (basePath) {
562
+ await mkdir(path.join(outDir, '.vite'), { recursive: true });
563
+ await writeFile(path.join(outDir, '.vite', 'base-path.json'), `${JSON.stringify({ basePath }, null, 2)}\n`);
564
+ }
565
+ if (options.serviceWorker) {
566
+ const manifest = await readFile(path.join(outDir, '.vite', 'manifest.json'));
567
+ // Match the version the .NET app derives from the same manifest.
568
+ const version = createHash('sha256').update(manifest).digest('hex').slice(0, 12);
569
+ await build({
570
+ root: rootDir,
571
+ configFile: false,
572
+ mode: resolvedConfig.mode,
573
+ base: resolvedConfig.base,
574
+ logLevel: resolvedConfig.logLevel,
575
+ resolve: { alias: resolvedConfig.resolve.alias },
576
+ define: { __NETJES_BUILD__: JSON.stringify(version) },
577
+ build: {
578
+ outDir,
579
+ emptyOutDir: false,
580
+ copyPublicDir: false,
581
+ lib: {
582
+ entry: path.resolve(rootDir, options.serviceWorker),
583
+ formats: ['iife'],
584
+ name: 'NetjesServiceWorker',
585
+ fileName: () => 'sw.js',
586
+ },
587
+ },
588
+ });
589
+ }
443
590
  if (packages.length === 0) return;
444
591
  // Where the .NET app finds the packages in production, next to the manifest: no node_modules there to read them
445
592
  // from, and a manifest key alone does not say which package a file is of.
@@ -477,5 +624,5 @@ export default function netjes(options = {}) {
477
624
  },
478
625
  };
479
626
 
480
- return [react(options.react), plugin, packageNames.length > 0 ? packageStyles : null, options.tailwind === false ? null : tailwind()];
627
+ return [react(options.react), plugin, packageNames.length > 0 ? packageStyles : null, options.tailwind === false ? null : tailwindForApp()];
481
628
  }
File without changes