@foldkit/vite-plugin 0.28.0 → 0.29.0-canary.54f8bcd443b4

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
@@ -61,7 +61,7 @@ Pass `ssr` with the path to your server entry to render page requests through it
61
61
  plugins: [foldkit({ ssr: { serverEntry: '/src/entry.server.ts' } })]
62
62
  ```
63
63
 
64
- With this set, the dev server converts HTML page requests to Web `Request` values, passes them to the entry's `renderPage`, and serves the returned `Response`. The request URL retains Vite's configured `base` prefix and the browser's query string. Vite continues to serve the client entry, HMR, and assets, and the server entry runs through Vite's module graph, so edits to it apply without a restart. The client side of the handoff needs no plugin configuration: a server-rendered application's client entry calls `Runtime.hydrate` instead of `Runtime.run`. Hydration adopts matching DOM, rebuilds mismatched subtrees, and refuses an invalid or cross-deployment handoff. The option shapes only the dev server; production hosts import the built server entry themselves. See the [Server Rendering documentation](https://foldkit.dev/core/server-rendering) for the full contract.
64
+ With this set, the dev server converts HTML page requests to Web `Request` values, passes them to the entry's `renderPage`, and serves the returned `Response`. The request URL retains Vite's configured `base` prefix and the browser's query string. Vite continues to serve the client entry, HMR, and assets, and the server entry runs through the module runner of Vite's `ssr` environment, so edits to it apply without a restart. Release what the server entry starts, such as a `ManagedRuntime`, in an `import.meta.hot.dispose` callback in the entry; see [Releasing resources when the server entry reloads](https://foldkit.dev/core/server-rendering#releasing-resources-when-the-server-entry-reloads). The client side of the handoff needs no plugin configuration: a server-rendered application's client entry calls `Runtime.hydrate` instead of `Runtime.run`. Hydration adopts matching DOM, rebuilds mismatched subtrees, and refuses an invalid or cross-deployment handoff. The option shapes only the dev server; production hosts import the built server entry themselves. See the [Server Rendering documentation](https://foldkit.dev/core/server-rendering) for the full contract.
65
65
 
66
66
  Vite retains ownership of configured proxy routes before Foldkit handles application requests. Vite's `server.cors` option applies to Vite-owned source modules, assets, and HMR. It does not add headers to application responses or answer their preflights. Preflight ownership follows `Access-Control-Request-Method`, so a preflight for an application `POST` reaches `renderPage` even when its path looks like an asset. An `OPTIONS` request without both `Origin` and `Access-Control-Request-Method` is not a preflight and also reaches `renderPage`. Define application CORS in `renderPage`, where development and the deployed host share one policy. Vite's `allowedHosts` check runs before proxy and application handling, including `OPTIONS` and methods the Web `Request` API cannot represent.
67
67
 
@@ -171,10 +171,10 @@ When one Vite app build produces the client and server artifacts, the plugin gen
171
171
 
172
172
  ```typescript
173
173
  // src/entry.server.ts
174
- Server.renderToString(config, { flags })
174
+ Server.renderToString(ApplicationBlock, { Flags }, { flags })
175
175
 
176
176
  // src/entry.ts
177
- Runtime.hydrate(application)
177
+ Runtime.hydrate(program)
178
178
  ```
179
179
 
180
180
  Use the `buildId` option or `FOLDKIT_BUILD_ID` as an explicit override when client and server build in separate jobs, or when the id should name a deployment in another system:
@@ -1 +1 @@
1
- {"version":3,"file":"brandDist.d.ts","sourceRoot":"","sources":["../src/brandDist.ts"],"names":[],"mappings":"AAQA,sEAAsE;AACtE,MAAM,MAAM,eAAe,GAAG,QAAQ,CAAC;IACrC,YAAY,EAAE,MAAM,CAAA;IACpB,YAAY,EAAE,MAAM,CAAA;CACrB,CAAC,CAAA;AAEF;;;;;;;;;;;GAWG;AACH,eAAO,MAAM,kBAAkB,gBAChB,MAAM,eACN,MAAM,KAClB,eAyBF,CAAA"}
1
+ {"version":3,"file":"brandDist.d.ts","sources":["../src/brandDist.ts"],"names":[],"mappings":"AAQA,sEAAsE;AACtE,MAAM,MAAM,eAAe,GAAG,QAAQ,CAAC;IACrC,YAAY,EAAE,MAAM,CAAA;IACpB,YAAY,EAAE,MAAM,CAAA;CACrB,CAAC,CAAA;AAEF;;;;;;;;;;;GAWG;AACH,eAAO,MAAM,kBAAkB,gBAChB,MAAM,eACN,MAAM,KAClB,eAyBF,CAAA"}
package/dist/build.d.ts CHANGED
@@ -127,6 +127,10 @@ export declare const renderTargetFor: (clientDirectory: string, path: string, or
127
127
  * use the server entry's `renderDocument` export with the emitted browser assets.
128
128
  * The browser build has a script input and emits no HTML until prerendering.
129
129
  * The server bundle's default export is `{ fetch }`.
130
+ *
131
+ * With prerendering enabled, `vite preview` resolves generated directory-index
132
+ * pages at their declared paths. Vite serves the existing files without running
133
+ * the server entry. Custom application hosts retain their own routing.
130
134
  */
131
135
  export declare const foldkitBuild: (serverEntry: string, options: FoldkitBuildOptions) => Plugin<FoldkitBuildApi>;
132
136
  //# sourceMappingURL=build.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"build.d.ts","sourceRoot":"","sources":["../src/build.ts"],"names":[],"mappings":"AAAA,OAAO,EAAa,MAAM,EAAE,MAAM,QAAQ,CAAA;AAS1C,OAAO,QAA8B,MAAM,WAAW,CAAA;AAEtD,OAAO,KAAK,EAGV,MAAM,EAGP,MAAM,MAAM,CAAA;AAEb,mEAAmE;AACnE,MAAM,MAAM,uBAAuB,GAAG,QAAQ,CAAC;IAC7C;;;OAGG;IACH,KAAK,CAAC,EAAE,aAAa,CAAC,MAAM,CAAC,CAAA;IAC7B;;;;;OAKG;IACH,MAAM,CAAC,EAAE,MAAM,CAAA;CAChB,CAAC,CAAA;AAEF,4EAA4E;AAC5E,MAAM,MAAM,mBAAmB,GAAG,QAAQ,CAAC;IACzC,2HAA2H;IAC3H,WAAW,EAAE,MAAM,CAAA;IACnB,0CAA0C;IAC1C,YAAY,CAAC,EAAE,MAAM,CAAA;IACrB,yCAAyC;IACzC,YAAY,CAAC,EAAE,MAAM,CAAA;IACrB;;;OAGG;IACH,SAAS,CAAC,EAAE,OAAO,GAAG,uBAAuB,CAAA;CAC9C,CAAC,CAAA;AAEF,6EAA6E;AAC7E,eAAO,MAAM,uBAAuB,0BAA0B,CAAA;AAE9D;;;;;;GAMG;AACH,eAAO,MAAM,oBAAoB;IAC/B;;;;OAIG;;IAEH;;;;OAIG;;IAEH,+EAA+E;;IAE/E,2DAA2D;;IAE3D,6EAA6E;;EAE7E,CAAA;AAEF;;;;;GAKG;AACH,MAAM,MAAM,oBAAoB,GAAG,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AM,YAAY,SACjB,MAAM,aACD,MAAM,YACR,OAAO,QAAQ,KACvB,MAQF,CAAA;AA6FD,eAAO,MAAM,eAAe,oBACT,MAAM,QACjB,MAAM,UACJ,MAAM,YACL,OAAO,QAAQ,KACvB,QAAQ,CAAC;IAAE,GAAG,EAAE,GAAG,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE,CA0CrC,CAAA;AAqLD;;;;;;;;;;;;;GAaG;AACH,eAAO,MAAM,YAAY,gBACV,MAAM,WACV,mBAAmB,KAC3B,MAAM,CAAC,eAAe,CAsUxB,CAAA"}
package/dist/build.js CHANGED
@@ -4,6 +4,8 @@ import { existsSync } from 'node:fs';
4
4
  import { mkdir, readFile, writeFile } from 'node:fs/promises';
5
5
  import nodePath, { dirname, resolve } from 'node:path';
6
6
  import { pathToFileURL } from 'node:url';
7
+ import { DEV_TOOLS_OVERLAY_MODULE_ID, DEV_TOOLS_OVERLAY_MODULE_SOURCE, RESOLVED_DEV_TOOLS_OVERLAY_MODULE_ID, shouldInjectDevToolsOverlay, } from './devToolsOverlay.js';
8
+ import { installPrerenderPreview } from './preview.js';
7
9
  /** Vite module id of the fetch handler Foldkit emits as the server entry. */
8
10
  export const FOLDKIT_FETCH_MODULE_ID = 'virtual:foldkit/fetch';
9
11
  /**
@@ -280,6 +282,10 @@ const assetsForFetchModule = (assets) => {
280
282
  * use the server entry's `renderDocument` export with the emitted browser assets.
281
283
  * The browser build has a script input and emits no HTML until prerendering.
282
284
  * The server bundle's default export is `{ fetch }`.
285
+ *
286
+ * With prerendering enabled, `vite preview` resolves generated directory-index
287
+ * pages at their declared paths. Vite serves the existing files without running
288
+ * the server entry. Custom application hosts retain their own routing.
283
289
  */
284
290
  export const foldkitBuild = (serverEntry, options) => {
285
291
  const state = {};
@@ -369,7 +375,10 @@ export const foldkitBuild = (serverEntry, options) => {
369
375
  };
370
376
  return {
371
377
  name: 'foldkit:build',
372
- apply: 'build',
378
+ apply: (_config, { command, isPreview }) => command === 'build' || (isPreview === true && prerender !== undefined),
379
+ ...(prerender === undefined
380
+ ? {}
381
+ : { configurePreviewServer: installPrerenderPreview }),
373
382
  sharedDuringBuild: true,
374
383
  api: {
375
384
  serverEntry,
@@ -404,6 +413,9 @@ export const foldkitBuild = (serverEntry, options) => {
404
413
  },
405
414
  },
406
415
  resolveId(id) {
416
+ if (id === DEV_TOOLS_OVERLAY_MODULE_ID) {
417
+ return RESOLVED_DEV_TOOLS_OVERLAY_MODULE_ID;
418
+ }
407
419
  if (id === CLIENT_MODULE_ID) {
408
420
  return RESOLVED_CLIENT_MODULE_ID;
409
421
  }
@@ -413,12 +425,18 @@ export const foldkitBuild = (serverEntry, options) => {
413
425
  return undefined;
414
426
  },
415
427
  load(id) {
428
+ if (id === RESOLVED_DEV_TOOLS_OVERLAY_MODULE_ID) {
429
+ return DEV_TOOLS_OVERLAY_MODULE_SOURCE;
430
+ }
416
431
  if (id === RESOLVED_CLIENT_MODULE_ID) {
417
432
  const { modulePreload } = this.environment.config.build;
418
433
  const polyfill = modulePreload !== false && modulePreload.polyfill
419
434
  ? "import 'vite/modulepreload-polyfill'\n"
420
435
  : '';
421
- return `${polyfill}import ${JSON.stringify(options.clientEntry)}\n`;
436
+ const overlay = shouldInjectDevToolsOverlay('build', this.environment.config.root)
437
+ ? `import ${JSON.stringify(DEV_TOOLS_OVERLAY_MODULE_ID)}\n`
438
+ : '';
439
+ return `${polyfill}${overlay}import ${JSON.stringify(options.clientEntry)}\n`;
422
440
  }
423
441
  if (id !== RESOLVED_FETCH_MODULE_ID) {
424
442
  return;
@@ -438,10 +456,14 @@ export const foldkitBuild = (serverEntry, options) => {
438
456
  state.assets = collectDocumentAssets(Object.values(bundle), this.environment.config);
439
457
  },
440
458
  },
441
- config: userConfig => {
459
+ config: (userConfig, { isPreview }) => {
442
460
  const client = {
443
461
  build: {
444
- outDir: clientOutDir,
462
+ outDir: isPreview
463
+ ? (userConfig.environments?.['client']?.build?.outDir ??
464
+ userConfig.build?.outDir ??
465
+ clientOutDir)
466
+ : clientOutDir,
445
467
  rolldownOptions: { input: { [CLIENT_CHUNK_NAME]: CLIENT_MODULE_ID } },
446
468
  },
447
469
  };
@@ -475,6 +497,11 @@ export const foldkitBuild = (serverEntry, options) => {
475
497
  : { environments: { client, ssr } };
476
498
  },
477
499
  configResolved(config) {
500
+ if (config.command === 'build' &&
501
+ (config.environments['client']?.build.watch ||
502
+ config.environments['ssr']?.build.watch)) {
503
+ throw new Error('[foldkit] ssr.build does not support build.watch or vite build --watch. Use the Vite dev server for SSR development, or rerun a full vite build when sources change.');
504
+ }
478
505
  if (config.base === '' || config.base === './') {
479
506
  throw new Error('[foldkit] ssr.build requires an absolute URL or root-relative base, such as "/" or "/app/". A relative base cannot locate browser assets consistently across server-rendered routes.');
480
507
  }
@@ -1,4 +1,10 @@
1
1
  import type { Plugin } from 'vite';
2
+ /** The development-only module supplying the running server's build identity.
3
+ * @internal */
4
+ export declare const DEVELOPMENT_BUILD_ID_MODULE_ID = "virtual:foldkit/development-build-id";
5
+ /** Vite's resolved id for the development build-identity module.
6
+ * @internal */
7
+ export declare const RESOLVED_DEVELOPMENT_BUILD_ID_MODULE_ID = "\0virtual:foldkit/development-build-id";
2
8
  /** The build id explicitly supplied through plugin configuration or the
3
9
  * environment, or `undefined` when neither supplied a nonempty value.
4
10
  *
@@ -10,7 +16,8 @@ export declare const resolveBuildId: (configured?: string) => string | undefined
10
16
  * @internal Exported for tests.
11
17
  */
12
18
  export declare const buildIdForCommand: (command: 'build' | 'serve', configured?: string) => string | undefined;
13
- /** Compiles one build identity into application entries and Foldkit itself.
19
+ /** Supplies one build identity through a revalidated development module or
20
+ * inlined production literals.
14
21
  *
15
22
  * @internal
16
23
  */
@@ -1 +1 @@
1
- {"version":3,"file":"buildToken.d.ts","sourceRoot":"","sources":["../src/buildToken.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,MAAM,EAA+B,MAAM,MAAM,CAAA;AAoC/D;;;;GAIG;AACH,eAAO,MAAM,cAAc,gBAAiB,MAAM,KAAG,MAAM,GAAG,SAQ7D,CAAA;AAED;;;GAGG;AACH,eAAO,MAAM,iBAAiB,YACnB,OAAO,GAAG,OAAO,eACb,MAAM,KAClB,MAAM,GAAG,SAMX,CAAA;AA0ID;;;GAGG;AACH,eAAO,MAAM,iBAAiB,aAClB,MAAM,wCAEf,KAAK,CAAC,MAAM,CA+Dd,CAAA"}
1
+ {"version":3,"file":"buildToken.d.ts","sources":["../src/buildToken.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,MAAM,EAA+B,MAAM,MAAM,CAAA;AAyB/D;eACe;AACf,eAAO,MAAM,8BAA8B,yCACH,CAAA;AAExC;eACe;AACf,eAAO,MAAM,uCAAuC,2CAAwC,CAAA;AAc5F;;;;GAIG;AACH,eAAO,MAAM,cAAc,gBAAiB,MAAM,KAAG,MAAM,GAAG,SAQ7D,CAAA;AAED;;;GAGG;AACH,eAAO,MAAM,iBAAiB,YACnB,OAAO,GAAG,OAAO,eACb,MAAM,KAClB,MAAM,GAAG,SAMX,CAAA;AAuJD;;;;GAIG;AACH,eAAO,MAAM,iBAAiB,aAClB,MAAM,wCAEf,KAAK,CAAC,MAAM,CAgFd,CAAA"}
@@ -19,6 +19,13 @@ import { isFoldkitSingletonPackageSpecifier } from './foldkitPackages.js';
19
19
  // still imports Foldkit externally.
20
20
  const BUILD_ID_ENVIRONMENT_VARIABLE = 'FOLDKIT_BUILD_ID';
21
21
  const FRAMEWORK_BUILD_ID_PLACEHOLDER = 'foldkitBuildIdPlaceholder()';
22
+ const DEVELOPMENT_BUILD_ID_BINDING = '__foldkitDevelopmentBuildId';
23
+ /** The development-only module supplying the running server's build identity.
24
+ * @internal */
25
+ export const DEVELOPMENT_BUILD_ID_MODULE_ID = 'virtual:foldkit/development-build-id';
26
+ /** Vite's resolved id for the development build-identity module.
27
+ * @internal */
28
+ export const RESOLVED_DEVELOPMENT_BUILD_ID_MODULE_ID = `\0${DEVELOPMENT_BUILD_ID_MODULE_ID}`;
22
29
  const buildIdentitySessions = new WeakMap();
23
30
  const developmentBuildIds = new WeakMap();
24
31
  /** The build id explicitly supplied through plugin configuration or the
@@ -74,6 +81,7 @@ const buildIdForConfig = (config, configuredBuildId) => {
74
81
  developmentBuildIds.set(config, fresh);
75
82
  return fresh;
76
83
  };
84
+ const buildIdLiteral = (buildId) => buildId === undefined ? 'undefined' : JSON.stringify(buildId);
77
85
  const replaceAll = (source, code, search, replacement) => {
78
86
  let didReplace = false;
79
87
  let fromIndex = 0;
@@ -99,13 +107,20 @@ const transformBuildIdentity = (code, id, config, configuredBuildId) => {
99
107
  !code.includes(FRAMEWORK_BUILD_ID_PLACEHOLDER)) {
100
108
  return undefined;
101
109
  }
102
- const buildId = buildIdForConfig(config, configuredBuildId);
103
- const replacement = buildId === undefined ? 'undefined' : JSON.stringify(buildId);
110
+ const replacement = config.command === 'serve'
111
+ ? DEVELOPMENT_BUILD_ID_BINDING
112
+ : buildIdLiteral(buildIdForConfig(config, configuredBuildId));
104
113
  const transformed = new MagicString(code);
105
114
  const transformedFramework = replaceAll(transformed, code, FRAMEWORK_BUILD_ID_PLACEHOLDER, replacement);
106
115
  if (!transformedFramework) {
107
116
  return undefined;
108
117
  }
118
+ if (config.command === 'serve') {
119
+ // NOTE: Vite serves installed dependency modules with immutable caching.
120
+ // Keep their code stable and revalidate the current server's identity
121
+ // through a virtual module, which Vite serves with no-cache and an ETag.
122
+ transformed.prepend(`import { buildId as ${DEVELOPMENT_BUILD_ID_BINDING} } from ${JSON.stringify(DEVELOPMENT_BUILD_ID_MODULE_ID)};\n`);
123
+ }
109
124
  return {
110
125
  code: transformed.toString(),
111
126
  map: transformed.generateMap({ hires: 'boundary', source: id }),
@@ -127,7 +142,8 @@ const verifyBuildIdentity = (builder) => {
127
142
  'Remove Foldkit packages from explicit SSR or Rolldown externalization ' +
128
143
  'settings and let @foldkit/vite-plugin bundle them.');
129
144
  };
130
- /** Compiles one build identity into application entries and Foldkit itself.
145
+ /** Supplies one build identity through a revalidated development module or
146
+ * inlined production literals.
131
147
  *
132
148
  * @internal
133
149
  */
@@ -154,6 +170,18 @@ export const foldkitBuildToken = (buildId, verifyFrameworkIdentity = true) => {
154
170
  beginBuildIdentity(builder, configuredBuildId, verifyFrameworkIdentity);
155
171
  },
156
172
  },
173
+ resolveId(id) {
174
+ return id === DEVELOPMENT_BUILD_ID_MODULE_ID
175
+ ? RESOLVED_DEVELOPMENT_BUILD_ID_MODULE_ID
176
+ : undefined;
177
+ },
178
+ load(id) {
179
+ if (id !== RESOLVED_DEVELOPMENT_BUILD_ID_MODULE_ID) {
180
+ return undefined;
181
+ }
182
+ const buildId = buildIdForConfig(this.environment.getTopLevelConfig(), configuredBuildId);
183
+ return `export const buildId = ${buildIdLiteral(buildId)}\n`;
184
+ },
157
185
  transform(code, id) {
158
186
  const config = this.environment.getTopLevelConfig();
159
187
  return transformBuildIdentity(code, id, config, configuredBuildId);
@@ -1,4 +1,10 @@
1
1
  import type { Plugin } from 'vite';
2
+ /** @internal Virtual module that registers the installed browser overlay. */
3
+ export declare const DEV_TOOLS_OVERLAY_MODULE_ID = "virtual:foldkit-devtools-overlay";
4
+ /** @internal Resolved identity shared by HTML and generated client entries. */
5
+ export declare const RESOLVED_DEV_TOOLS_OVERLAY_MODULE_ID = "\0virtual:foldkit-devtools-overlay";
6
+ /** @internal Browser registration used by both client entry paths. */
7
+ export declare const DEV_TOOLS_OVERLAY_MODULE_SOURCE: string;
2
8
  /**
3
9
  * Determines whether the Vite integration should include the DevTools overlay.
4
10
  * Development serves it whenever the package is installed. Production builds
@@ -1 +1 @@
1
- {"version":3,"file":"devToolsOverlay.d.ts","sourceRoot":"","sources":["../src/devToolsOverlay.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,MAAM,CAAA;AAoIlC;;;;;GAKG;AACH,eAAO,MAAM,2BAA2B,YAC7B,OAAO,GAAG,OAAO,QACpB,MAAM,KACX,OAQF,CAAA;AAED,+EAA+E;AAC/E,eAAO,MAAM,qBAAqB,QAAO,MAmExC,CAAA"}
1
+ {"version":3,"file":"devToolsOverlay.d.ts","sources":["../src/devToolsOverlay.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,MAAM,CAAA;AAIlC,6EAA6E;AAC7E,eAAO,MAAM,2BAA2B,qCAAqC,CAAA;AAC7E,+EAA+E;AAC/E,eAAO,MAAM,oCAAoC,uCAAqC,CAAA;AAGtF,sEAAsE;AACtE,eAAO,MAAM,+BAA+B,QAK3C,CAAA;AAyHD;;;;;GAKG;AACH,eAAO,MAAM,2BAA2B,YAC7B,OAAO,GAAG,OAAO,QACpB,MAAM,KACX,OAQF,CAAA;AAED,+EAA+E;AAC/E,eAAO,MAAM,qBAAqB,QAAO,MAmExC,CAAA"}
@@ -3,11 +3,14 @@ import { existsSync, readFileSync, realpathSync } from 'node:fs';
3
3
  import { dirname, join, resolve, sep } from 'node:path';
4
4
  const DEV_TOOLS_PACKAGE_NAME = '@foldkit/devtools';
5
5
  const DEV_TOOLS_VITE_EXPORT = './vite';
6
- const DEV_TOOLS_OVERLAY_MODULE_ID = 'virtual:foldkit-devtools-overlay';
7
- const RESOLVED_DEV_TOOLS_OVERLAY_MODULE_ID = `\0${DEV_TOOLS_OVERLAY_MODULE_ID}`;
6
+ /** @internal Virtual module that registers the installed browser overlay. */
7
+ export const DEV_TOOLS_OVERLAY_MODULE_ID = 'virtual:foldkit-devtools-overlay';
8
+ /** @internal Resolved identity shared by HTML and generated client entries. */
9
+ export const RESOLVED_DEV_TOOLS_OVERLAY_MODULE_ID = `\0${DEV_TOOLS_OVERLAY_MODULE_ID}`;
8
10
  const DEV_TOOLS_VITE_IMPORT_SPECIFIER = `${DEV_TOOLS_PACKAGE_NAME}${DEV_TOOLS_VITE_EXPORT.slice(1)}`;
9
11
  const DEV_TOOLS_HOST_IMPORT_SPECIFIER = 'foldkit/devtools-host';
10
- const DEV_TOOLS_OVERLAY_MODULE_SOURCE = `
12
+ /** @internal Browser registration used by both client entry paths. */
13
+ export const DEV_TOOLS_OVERLAY_MODULE_SOURCE = `
11
14
  import { overlay } from '${DEV_TOOLS_VITE_IMPORT_SPECIFIER}'
12
15
  import { __setDevToolsOverlay } from '${DEV_TOOLS_HOST_IMPORT_SPECIFIER}'
13
16
 
@@ -1 +1 @@
1
- {"version":3,"file":"foldkitPackages.d.ts","sourceRoot":"","sources":["../src/foldkitPackages.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,KAAK,UAAU,EAA0B,MAAM,MAAM,CAAA;AAS9D;;;;GAIG;AACH,eAAO,MAAM,kCAAkC,cAClC,MAAM,KAChB,OAKA,CAAA;AA8CH;;;;GAIG;AACH,eAAO,MAAM,oBAAoB,SACzB,MAAM,WACH,OAAO,kBACA,UAAU,KACzB,OAAO,CAAC,QAAQ,CAAC;IAAE,MAAM,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC;IAAC,UAAU,EAAE,KAAK,CAAC,MAAM,CAAC,CAAA;CAAE,CAAC,CAoCxE,CAAA"}
1
+ {"version":3,"file":"foldkitPackages.d.ts","sources":["../src/foldkitPackages.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,KAAK,UAAU,EAA0B,MAAM,MAAM,CAAA;AAS9D;;;;GAIG;AACH,eAAO,MAAM,kCAAkC,cAClC,MAAM,KAChB,OAKA,CAAA;AA8CH;;;;GAIG;AACH,eAAO,MAAM,oBAAoB,SACzB,MAAM,WACH,OAAO,kBACA,UAAU,KACzB,OAAO,CAAC,QAAQ,CAAC;IAAE,MAAM,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC;IAAC,UAAU,EAAE,KAAK,CAAC,MAAM,CAAC,CAAA;CAAE,CAAC,CAoCxE,CAAA"}
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAgDA,OAAO,KAAK,EAEV,MAAM,EAIP,MAAM,MAAM,CAAA;AAQ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K,CAAC,EAAE,KAAK,CAAA;KACd,CAAC,CACL,CAAA;IACH;;;;;;;;;;;;;;;;OAgBG;IACH,OAAO,CAAC,EAAE,MAAM,CAAA;CACjB,CAAC,CAAA;AA+/BF,eAAO,MAAM,OAAO,aAAa,oBAAoB,KAAQ,KAAK,CAAC,MAAM,CAwJxE,CAAA"}
package/dist/index.js CHANGED
@@ -1,4 +1,5 @@
1
- import { Array, Clock, ConfigProvider, Console, Crypto, Data, Duration, Effect, Exit, Fiber, HashMap, Layer, Match, Number, Option, Order, Predicate, Queue, Ref, Schedule, Schema, Stream, pipe, } from 'effect';
1
+ import { Array, Clock, ConfigProvider, Console, Data, Duration, Effect, Exit, Fiber, HashMap, Layer, Match, Number, Option, Order, Predicate, Queue, Ref, Schedule, Schema, Stream, pipe, } from 'effect';
2
+ import { SecureRandom } from 'effect/crypto';
2
3
  import { Event as DevToolsEvent, EventFrame, RELAY_RECORD_VERSION, RequestFrame, Response, ResponseFrame, } from 'foldkit/devtools-protocol';
3
4
  import { PreserveModelMessage, RequestModelMessage, RestoreModelMessage, } from 'foldkit/model-preservation';
4
5
  import { createHmac, timingSafeEqual } from 'node:crypto';
@@ -12,6 +13,7 @@ import { foldkitBuild } from './build.js';
12
13
  import { foldkitBuildToken } from './buildToken.js';
13
14
  import { devToolsOverlayPlugin } from './devToolsOverlay.js';
14
15
  import { crawlFoldkitPackages } from './foldkitPackages.js';
16
+ import { readProcessNamespaces } from './relayLiveness.js';
15
17
  import { publishRelayRecord, retireRelayRecord } from './relayRegistry.js';
16
18
  import { relayRegistryTrust } from './relayRegistryTrust.js';
17
19
  import { foldkitSsr } from './ssr.js';
@@ -32,6 +34,7 @@ const FORCE_INCLUDED_EFFECT_ENTRIES = [
32
34
  'effect/Array',
33
35
  'effect/Boolean',
34
36
  'effect/Cause',
37
+ 'effect/Chunk',
35
38
  'effect/Clock',
36
39
  'effect/Context',
37
40
  'effect/Data',
@@ -70,6 +73,7 @@ const FORCE_INCLUDED_EFFECT_ENTRIES = [
70
73
  'effect/String',
71
74
  'effect/Struct',
72
75
  'effect/SubscriptionRef',
76
+ 'effect/Tuple',
73
77
  'effect/Types',
74
78
  ];
75
79
  // NOTE: Adding includes to an environment whose optimizer is otherwise disabled
@@ -104,6 +108,9 @@ const byConnectionOrder = Order.mapInput(Order.Number, ({ sequence }) => sequenc
104
108
  const handlePreserveModelReceived = (state, payload) => Exit.match(Schema.decodeUnknownExit(PreserveModelMessage)(payload), {
105
109
  onFailure: error => Console.warn('[foldkit:preserve] failed to decode preserve-model payload', error),
106
110
  onSuccess: ({ id, model, isReloadFlush }) => Ref.update(state.preservedModels, current => {
111
+ if (model === undefined) {
112
+ return HashMap.remove(current, id);
113
+ }
107
114
  const existingFlag = Option.exists(HashMap.get(current, id), ({ isReloadFlush }) => isReloadFlush);
108
115
  const entry = {
109
116
  model,
@@ -287,8 +294,8 @@ class RelayBindFailed extends Data.TaggedError('RelayBindFailed') {
287
294
  }
288
295
  const isPortInUse = (error) => Predicate.hasProperty(error, 'code') && error.code === 'EADDRINUSE';
289
296
  const relayId = Effect.gen(function* () {
290
- const crypto = yield* Crypto.Crypto;
291
- return yield* crypto.randomUUIDv4.pipe(Effect.orDie);
297
+ const secureRandom = yield* SecureRandom.SecureRandom;
298
+ return yield* secureRandom.uuidV4();
292
299
  });
293
300
  const attachRelayHandlers = (wss, enqueue) => {
294
301
  wss.on('connection', client => {
@@ -306,8 +313,8 @@ const boundPort = (address) => address === null || Predicate.isString(address)
306
313
  : Option.some(address.port);
307
314
  const relayHasNoBoundPort = () => new Error('[foldkit:devTools] the MCP relay listener has no bound port');
308
315
  const relayToken = Effect.gen(function* () {
309
- const crypto = yield* Crypto.Crypto;
310
- const bytes = yield* crypto.randomBytes(RELAY_TOKEN_BYTES).pipe(Effect.orDie);
316
+ const secureRandom = yield* SecureRandom.SecureRandom;
317
+ const bytes = yield* secureRandom.randomBytes(RELAY_TOKEN_BYTES);
311
318
  return Buffer.from(bytes).toString('hex');
312
319
  });
313
320
  const relayUrlForLog = (url) => {
@@ -462,6 +469,7 @@ const reportRelayBindFailed = (maybePort, cause) => {
462
469
  const unpublishedRelayMessage = (reason) => `[foldkit:devTools] Cannot publish the MCP relay address: ${reason}. Set matching devToolsMcpPort and FOLDKIT_DEVTOOLS_MCP_PORT values for MCP access on a trusted network, or set FOLDKIT_DEVTOOLS_RELAY_DIRECTORY to a directory private to your user.`;
463
470
  const publishRelay = (root, relay) => Effect.gen(function* () {
464
471
  const startedAt = yield* Clock.currentTimeMillis;
472
+ const maybeNamespaces = yield* readProcessNamespaces;
465
473
  const directory = yield* publishRelayRecord({
466
474
  version: RELAY_RECORD_VERSION,
467
475
  id: relay.id,
@@ -469,6 +477,10 @@ const publishRelay = (root, relay) => Effect.gen(function* () {
469
477
  url: relay.url,
470
478
  pid: process.pid,
471
479
  startedAt,
480
+ ...Option.match(maybeNamespaces, {
481
+ onNone: () => ({}),
482
+ onSome: namespaces => ({ namespaces }),
483
+ }),
472
484
  }, relayRegistryTrust);
473
485
  return Option.some(directory);
474
486
  }).pipe(Effect.catchTag('RelayRegistryDirectoryRefused', ({ directory, reason }) => Effect.as(Console.error(unpublishedRelayMessage(`the registry directory ${directory} ${reason}`)), Option.none())), Effect.catch(error => Effect.as(Console.error(unpublishedRelayMessage('the registry could not be written'), error), Option.none())));
@@ -533,7 +545,7 @@ const main = (server, events, options) => Effect.gen(function* () {
533
545
  * an array; Vite flattens nested plugin arrays, so `plugins: [foldkit()]`
534
546
  * keeps working.
535
547
  */
536
- const relayRegistryLayer = Layer.provideMerge(NodeChildProcessSpawner.layer, Layer.mergeAll(NodeFileSystem.layer, NodePath.layer, NodeCrypto.layer));
548
+ const relayRegistryLayer = Layer.provideMerge(NodeChildProcessSpawner.layer, Layer.mergeAll(NodeFileSystem.layer, NodePath.layer, NodeCrypto.layerSecureRandom));
537
549
  export const foldkit = (options = {}) => {
538
550
  // NOTE: During a Vite restart, old and new servers overlap. Separate queues
539
551
  // and fibers keep their events and shutdowns attached to the right server.
@@ -572,9 +584,18 @@ export const foldkit = (options = {}) => {
572
584
  closeBundle() {
573
585
  return Effect.runPromise(stopMain(this.environment.getTopLevelConfig()));
574
586
  },
575
- handleHotUpdate: ({ server, modules, }) => {
576
- if (modules.length === 0) {
577
- return;
587
+ // NOTE: An edit to a client or `ssr` module reloads the whole page, so
588
+ // Vite's client HMR is suppressed. This hook runs only for the client
589
+ // environment, so the `ssr` module runner receives Vite's updates, which
590
+ // run the server entry's `import.meta.hot.dispose` callback.
591
+ hotUpdate({ type, file, modules, server }) {
592
+ if (type !== 'update' || this.environment.name !== 'client') {
593
+ return undefined;
594
+ }
595
+ const serverModules = server.environments.ssr?.moduleGraph.getModulesByFile(file);
596
+ if (Array.isArrayEmpty(modules) &&
597
+ (serverModules === undefined || serverModules.size === 0)) {
598
+ return undefined;
578
599
  }
579
600
  server.ws.send({ type: 'full-reload' });
580
601
  const run = mainRuns.get(server.config);
@@ -0,0 +1,4 @@
1
+ import type { PreviewServer } from 'vite';
2
+ /** @internal Resolve generated directory indexes through Vite's preview pipeline. */
3
+ export declare const installPrerenderPreview: (server: PreviewServer) => void;
4
+ //# sourceMappingURL=preview.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"preview.d.ts","sources":["../src/preview.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAW,aAAa,EAAE,MAAM,MAAM,CAAA;AAgElD,qFAAqF;AACrF,eAAO,MAAM,uBAAuB,WAAY,aAAa,KAAG,IA6B/D,CAAA"}
@@ -0,0 +1,67 @@
1
+ import { existsSync, realpathSync, statSync } from 'node:fs';
2
+ import { resolve, sep } from 'node:path';
3
+ const isContained = (root, file) => file.startsWith(root.endsWith(sep) ? root : `${root}${sep}`);
4
+ const rewriteDirectoryIndex = (request, root, base, isProxied) => {
5
+ const { method, headers, url } = request;
6
+ if ((method !== 'GET' && method !== 'HEAD') ||
7
+ url === undefined ||
8
+ isProxied(url) ||
9
+ isProxied(url.replace(/(\?|$)/, '/index.html$1')) ||
10
+ (headers.accept &&
11
+ !headers.accept.includes('text/html') &&
12
+ !headers.accept.includes('*/*'))) {
13
+ return;
14
+ }
15
+ const [pathname = ''] = url.split('?');
16
+ if (!pathname.startsWith('/') ||
17
+ pathname.startsWith('//') ||
18
+ pathname.includes('#') ||
19
+ !pathname.startsWith(base)) {
20
+ return;
21
+ }
22
+ const route = pathname.slice(base.length);
23
+ if (route === '' || route.endsWith('/')) {
24
+ return;
25
+ }
26
+ const segments = route.split('/').map(segment => decodeURIComponent(segment));
27
+ if (segments.join('/') !== decodeURI(route) ||
28
+ segments.some(segment => /^\.{1,2}$|[/\\\u0000:]/.test(segment))) {
29
+ return;
30
+ }
31
+ const file = resolve(root, ...segments);
32
+ if (!isContained(root, file) ||
33
+ file.endsWith('.html') ||
34
+ statSync(file, { throwIfNoEntry: false })?.isFile() ||
35
+ statSync(resolve(file, 'index'), { throwIfNoEntry: false })?.isFile() ||
36
+ existsSync(`${file}.html`)) {
37
+ return;
38
+ }
39
+ const index = realpathSync(resolve(file, 'index.html'));
40
+ if (isContained(realpathSync(root), index) && statSync(index).isFile()) {
41
+ request.url = `${pathname}/index.html${url.slice(pathname.length)}`;
42
+ }
43
+ };
44
+ /** @internal Resolve generated directory indexes through Vite's preview pipeline. */
45
+ export const installPrerenderPreview = (server) => {
46
+ if (server.config.appType === 'custom') {
47
+ return;
48
+ }
49
+ const client = server.config.environments['client'];
50
+ if (client === undefined) {
51
+ return;
52
+ }
53
+ const root = resolve(server.config.root, client.build.outDir);
54
+ const isProxied = (url) => Object.entries(server.config.preview.proxy ?? {}).some(([context, options]) => Boolean(options) &&
55
+ (context.startsWith('^')
56
+ ? new RegExp(context).test(url)
57
+ : url.startsWith(context)));
58
+ server.middlewares.use((request, _response, next) => {
59
+ try {
60
+ rewriteDirectoryIndex(request, root, server.config.base, isProxied);
61
+ }
62
+ catch {
63
+ return next();
64
+ }
65
+ next();
66
+ });
67
+ };
@@ -0,0 +1,6 @@
1
+ import { Effect, FileSystem, Option } from 'effect';
2
+ import type { RelayNamespaces, RelayRecord } from 'foldkit/devtools-protocol';
3
+ export type RelayStatus = 'Running' | 'Gone' | 'Unreachable';
4
+ export declare const readProcessNamespaces: Effect.Effect<Option.Option<RelayNamespaces>, never, FileSystem.FileSystem>;
5
+ export declare const checkRelay: (record: RelayRecord, maybeOwnNamespaces: Option.Option<RelayNamespaces>) => Effect.Effect<RelayStatus>;
6
+ //# sourceMappingURL=relayLiveness.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"relayLiveness.d.ts","sources":["../src/relayLiveness.ts"],"names":[],"mappings":"AAAA,OAAO,EAAY,MAAM,EAAE,UAAU,EAAU,MAAM,EAAU,MAAM,QAAQ,CAAA;AAC7E,OAAO,KAAK,EAAE,eAAe,EAAE,WAAW,EAAE,MAAM,2BAA2B,CAAA;AAW7E,MAAM,MAAM,WAAW,GAAG,SAAS,GAAG,MAAM,GAAG,aAAa,CAAA;AAE5D,eAAO,MAAM,qBAAqB,EAAE,MAAM,CAAC,MAAM,CAC/C,MAAM,CAAC,MAAM,CAAC,eAAe,CAAC,EAC9B,KAAK,EACL,UAAU,CAAC,UAAU,CAO4C,CAAA;AA2DnE,eAAO,MAAM,UAAU,WACb,WAAW,sBACC,MAAM,CAAC,MAAM,CAAC,eAAe,CAAC,KACjD,MAAM,CAAC,MAAM,CAAC,WAAW,CAqC3B,CAAA"}
@@ -0,0 +1,80 @@
1
+ import { Duration, Effect, FileSystem, Number, Option, String } from 'effect';
2
+ import { connect } from 'node:net';
3
+ const NAMESPACE_DIRECTORY = '/proc/self/ns';
4
+ const PROBE_TIMEOUT = Duration.seconds(1);
5
+ const WEBSOCKET_PORT = 80;
6
+ const SECURE_WEBSOCKET_PORT = 443;
7
+ const IPV6_BRACKETS = /^\[|\]$/g;
8
+ export const readProcessNamespaces = Effect.gen(function* () {
9
+ const fileSystem = yield* FileSystem.FileSystem;
10
+ const pid = yield* fileSystem.readLink(`${NAMESPACE_DIRECTORY}/pid`);
11
+ const network = yield* fileSystem.readLink(`${NAMESPACE_DIRECTORY}/net`);
12
+ return Option.some({ pid, network });
13
+ }).pipe(Effect.orElseSucceed(() => Option.none()));
14
+ const isProcessAlive = (pid) => {
15
+ try {
16
+ process.kill(pid, 0);
17
+ return true;
18
+ }
19
+ catch (error) {
20
+ return error instanceof Error && 'code' in error && error.code === 'EPERM';
21
+ }
22
+ };
23
+ const relayAddress = (url) => Option.flatMap(Option.fromNullishOr(URL.parse(url)), parsed => {
24
+ const host = parsed.hostname.replace(IPV6_BRACKETS, '');
25
+ if (String.isNonEmpty(parsed.port)) {
26
+ return Option.map(Number.parse(parsed.port), port => ({ host, port }));
27
+ }
28
+ else if (parsed.protocol === 'wss:') {
29
+ return Option.some({ host, port: SECURE_WEBSOCKET_PORT });
30
+ }
31
+ else {
32
+ return Option.some({ host, port: WEBSOCKET_PORT });
33
+ }
34
+ });
35
+ const refusesConnections = ({ host, port, }) => Effect.callback(resume => {
36
+ const socket = connect({ host, port });
37
+ const settle = (isRefused) => {
38
+ socket.destroy();
39
+ resume(Effect.succeed(isRefused));
40
+ };
41
+ socket.once('connect', () => settle(false));
42
+ socket.once('error', error => settle('code' in error && error.code === 'ECONNREFUSED'));
43
+ return Effect.sync(() => socket.destroy());
44
+ }).pipe(Effect.timeoutOption(PROBE_TIMEOUT), Effect.map(Option.getOrElse(() => false)));
45
+ const statusFromPort = (url) => Option.match(relayAddress(url), {
46
+ onNone: () => Effect.succeed('Running'),
47
+ onSome: address => Effect.map(refusesConnections(address), (isRefused) => isRefused ? 'Gone' : 'Running'),
48
+ });
49
+ // NOTE: kill(pid, 0) answers for this process's PID namespace only. A relay
50
+ // published from another PID namespace looks dead even while it runs, so its
51
+ // record counts as gone only when its port refuses connections. A relay in
52
+ // another network namespace listens on a loopback this process cannot reach.
53
+ export const checkRelay = (record, maybeOwnNamespaces) => {
54
+ const maybeRecordNamespaces = Option.fromNullishOr(record.namespaces);
55
+ const maybeBothNamespaces = Option.all([
56
+ maybeOwnNamespaces,
57
+ maybeRecordNamespaces,
58
+ ]);
59
+ const hasNoNamespaces = Option.isNone(maybeOwnNamespaces) && Option.isNone(maybeRecordNamespaces);
60
+ const isSamePidNamespace = Option.exists(maybeBothNamespaces, ([own, recorded]) => own.pid === recorded.pid);
61
+ const isOtherNetworkNamespace = Option.exists(maybeBothNamespaces, ([own, recorded]) => own.network !== recorded.network);
62
+ if (Option.isSome(maybeRecordNamespaces) &&
63
+ Option.isNone(maybeOwnNamespaces)) {
64
+ return Effect.succeed('Unreachable');
65
+ }
66
+ else if (isOtherNetworkNamespace) {
67
+ return Effect.succeed('Unreachable');
68
+ }
69
+ else if (isSamePidNamespace ||
70
+ (hasNoNamespaces && process.platform !== 'linux')) {
71
+ return Effect.succeed(isProcessAlive(record.pid) ? 'Running' : 'Gone');
72
+ }
73
+ else if (Option.isNone(maybeRecordNamespaces) &&
74
+ isProcessAlive(record.pid)) {
75
+ return Effect.succeed('Running');
76
+ }
77
+ else {
78
+ return statusFromPort(record.url);
79
+ }
80
+ };
@@ -1 +1 @@
1
- {"version":3,"file":"relayRegistry.d.ts","sourceRoot":"","sources":["../src/relayRegistry.ts"],"names":[],"mappings":"AAAA,OAAO,EAIL,MAAM,EACN,UAAU,EAEV,IAAI,EACJ,KAAK,aAAa,EAGnB,MAAM,QAAQ,CAAA;AACf,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,gBAAgB,CAAA;AACzD,OAAO,EAGL,WAAW,EACZ,MAAM,2BAA2B,CAAA;AAGlC,OAAO,EACL,KAAK,kBAAkB,EAExB,MAAM,yBAAyB,CAAA;AAUhC,KAAK,qBAAqB,GAAG,UAAU,CAAC,UAAU,GAAG,IAAI,CAAC,IAAI,CAAA;AAE9D,MAAM,MAAM,sBAAsB,GAC9B,qBAAqB,GACrB,mBAAmB,CAAC,mBAAmB,CAAA;;;;AAE3C,qBAAa,6BAA8B,SAAQ,mCAEjD;IACA,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAA;I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EAC3D,sBAAsB,CA+CpB,CAAA;AAEJ,eAAO,MAAM,gBAAgB,EAAE,MAAM,CAAC,MAAM,CAC1C,aAAa,CAAC,WAAW,CAAC,EAC1B,KAAK,EACL,qBAAqB,CAOrB,CAAA;AAEF,eAAO,MAAM,iBAAiB,OACxB,MAAM,aACC,MAAM,KAChB,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE,aAAa,CAAC,aAAa,EAAE,qBAAqB,CAKrE,CAAA"}
@@ -1,6 +1,7 @@
1
1
  import { Array, Config, Data, Effect, FileSystem, Option, Path, Schema, String, } from 'effect';
2
2
  import { RELAY_REGISTRY_DIRECTORY_NAME, RELAY_REGISTRY_DIRECTORY_VARIABLE, RelayRecord, } from 'foldkit/devtools-protocol';
3
3
  import { homedir, tmpdir } from 'node:os';
4
+ import { checkRelay, readProcessNamespaces } from './relayLiveness.js';
4
5
  import { windowsTempRootRefusal, } from './relayRegistryTrust.js';
5
6
  const RUNTIME_DIRECTORY_VARIABLE = 'XDG_RUNTIME_DIR';
6
7
  const RECORD_FILE_EXTENSION = '.json';
@@ -25,15 +26,6 @@ const relayRecordPath = (directory, id) => Effect.gen(function* () {
25
26
  const path = yield* Path.Path;
26
27
  return path.join(directory, `${encodeURIComponent(id)}${RECORD_FILE_EXTENSION}`);
27
28
  });
28
- const isProcessAlive = (pid) => {
29
- try {
30
- process.kill(pid, 0);
31
- return true;
32
- }
33
- catch (error) {
34
- return error instanceof Error && 'code' in error && error.code === 'EPERM';
35
- }
36
- };
37
29
  const readRecordFile = (filePath) => Effect.gen(function* () {
38
30
  const fileSystem = yield* FileSystem.FileSystem;
39
31
  const raw = yield* fileSystem.readFileString(filePath);
@@ -68,11 +60,16 @@ const retireStaleRecord = (filePath, record) => Effect.gen(function* () {
68
60
  });
69
61
  const removeDeadRecords = (directory) => Effect.gen(function* () {
70
62
  const filePaths = yield* recordFilePaths(directory);
63
+ const maybeOwnNamespaces = yield* readProcessNamespaces;
71
64
  yield* Effect.forEach(filePaths, filePath => Effect.gen(function* () {
72
65
  const maybeRecord = yield* readRecordFile(filePath);
73
- if (Option.isSome(maybeRecord) &&
74
- !isProcessAlive(maybeRecord.value.pid)) {
75
- yield* retireStaleRecord(filePath, maybeRecord.value);
66
+ if (Option.isNone(maybeRecord)) {
67
+ return;
68
+ }
69
+ const record = maybeRecord.value;
70
+ const status = yield* checkRelay(record, maybeOwnNamespaces);
71
+ if (status === 'Gone') {
72
+ yield* retireStaleRecord(filePath, record);
76
73
  }
77
74
  }), { discard: true });
78
75
  });
@@ -1 +1 @@
1
- {"version":3,"file":"relayRegistryTrust.d.ts","sourceRoot":"","sources":["../src/relayRegistryTrust.ts"],"names":[],"mappings":"AAAA,OAAO,EAIL,MAAM,EACN,UAAU,EACV,MAAM,EAIP,MAAM,QAAQ,CAAA;AACf,OAAO,EAAgB,mBAAmB,EAAE,MAAM,gBAAgB,CAAA;AAyElE,MAAM,MAAM,uBAAuB,GAAG,QAAQ,CAAC;IAC7C,SAAS,EAAE,MAAM,CAAA;IACjB,YAAY,EAAE,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,CAAA;CACpC,CAAC,CAAA;AAEF,MAAM,MAAM,kBAAkB,GAAG,QAAQ,CAAC;IACxC,OAAO,EAAE,CACP,SAAS,EAAE,MAAM,KACd,MAAM,CAAC,MAAM,CAChB,uBAAuB,EACvB,KAAK,EACL,mBAAmB,CAAC,mBAAmB,CACxC,CAAA;CACF,CAAC,CAAA;AAEF,KAAK,aAAa,GAAG,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,IAAI,EAAE,MAAM,GAAG,KAAK,CAAC,CAAA;AAE/D,eAAO,MAAM,6BAA6B,SAClC,aAAa,mBACF,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,KACrC,MAAM,CAAC,MAAM,CAAC,MAAM,CAkBnB,CAAA;AA2OJ,eAAO,MAAM,uBAAuB,SAC5B,MAAM,kBACI,MAAM,KACrB,MAAM,CAAC,MAAM,CAAC,MAAM,CAwCtB,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MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,KACrC,MAAM,CAAC,MAAM,CAAC,MAAM,CAkBnB,CAAA;AA2OJ,eAAO,MAAM,uBAAuB,SAC5B,MAAM,kBACI,MAAM,KACrB,MAAM,CAAC,MAAM,CAAC,MAAM,CAwCtB,CAAA;AAuFD,eAAO,MAAM,4BAA4B,gBAC1B,aAAa,CAAC,MAAM,CAAC,kBAClB,MAAM,KACrB,MAAM,CAAC,MAAM,CAAC,MAAM,CAwEtB,CAAA;AAED,eAAO,MAAM,cAAc,eAAgB,MAAM,KAAG,MAOjD,CAAA;AAEH,eAAO,MAAM,sBAAsB,cACtB,MAAM,YACP,MAAM,KACf,MAAM,CAAC,MAAM,CAAC,MAAM,CAGgB,CAAA;AAuHvC,eAAO,MAAM,qBAAqB,oBACf,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,aAC3B,MAAM,KAChB,MAAM,CAAC,MAAM,CACd,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,EACrB,KAAK,EACL,mBAAmB,CAAC,mBAAmB,CAQrC,CAAA;AA+BJ,eAAO,MAAM,kBAAkB,EAAE,kBAgFhC,CAAA"}
package/dist/ssr.d.ts CHANGED
@@ -53,13 +53,19 @@ export type FoldkitSsrOptions = Readonly<{
53
53
  * Serves server-rendered pages from the Vite dev server.
54
54
  *
55
55
  * Vite retains ownership of configured proxies, source modules, HMR, and
56
- * assets. Requests that fall through load the server entry through Vite's SSR
57
- * module loader, call its `renderPage` with a Web `Request`, and send the
58
- * resulting Web `Response`. Vite's host validation applies before either
59
- * owner. Foldkit then validates and normalizes the request target before Vite
60
- * or the server entry can resolve it. Vite's CORS option applies only to
56
+ * assets. Requests that fall through load the server entry through the `ssr`
57
+ * environment's module runner, call its `renderPage` with a Web `Request`, and
58
+ * send the resulting Web `Response`. Vite's host validation applies before
59
+ * either owner. Foldkit then validates and normalizes the request target before
60
+ * Vite or the server entry can resolve it. Vite's CORS option applies only to
61
61
  * Vite-owned responses, while the server entry owns CORS for application
62
- * responses. Server entry edits take effect without a restart.
62
+ * responses. Server entry edits take effect without a restart. The server
63
+ * entry accepts its own updates, and the server graph is reevaluated so Block
64
+ * Definitions and their declarations are created together. Unless
65
+ * `server.hmr` is `false`, an `import.meta.hot.dispose` callback in the entry
66
+ * runs before a hot update replaces it. With HMR disabled, stop and restart
67
+ * the dev-server process after editing server modules that own long-lived
68
+ * resources; an in-process restart cannot invoke the missing callback.
63
69
  */
64
70
  export declare const foldkitSsr: (options: FoldkitSsrOptions) => Plugin;
65
71
  //# sourceMappingURL=ssr.d.ts.map
package/dist/ssr.d.ts.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"ssr.d.ts","sourceRoot":"","sources":["../src/ssr.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAGV,MAAM,EAGP,MAAM,MAAM,CAAA;AAIb,0EAA0E;AAC1E,MAAM,MAAM,iBAAiB,GAAG,QAAQ,CAAC;IACvC;;;;;OAKG;IACH,WAAW,EAAE,MAAM,CAAA;IACnB;;;;OAIG;IACH,WAAW,CAAC,EAAE,MAAM,CAAA;IACpB;;;OAGG;IACH,WAAW,CAAC,EAAE,MAAM,CAAA;IACpB;;;;;;;;;;;;OAYG;IACH,MAAM,CAAC,EAAE,MAAM,CAAA;IACf;;;;;;;OAOG;IACH,OAAO,CAAC,EAAE,MAAM,CAAA;IAChB;;;;OAIG;IACH,cAAc,CAAC,EAAE,OAAO,CAAA;CACzB,CAAC,CAAA;AA6tBF;;;;;;;;;;;GAWG;AACH,eAAO,MAAM,UAAU,YAAa,iBAAiB,KAAG,MAyGvD,CAAA"}
1
+ {"version":3,"file":"ssr.d.ts","sources":["../src/ssr.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EAIV,MAAM,EAIP,MAAM,MAAM,CAAA;AAIb,0EAA0E;AAC1E,MAAM,MAAM,iBAAiB,GAAG,QAAQ,CAAC;IACvC;;;;;OAKG;IACH,WAAW,EAAE,MAAM,CAAA;IACnB;;;;OAIG;IACH,WAAW,CAAC,EAAE,MAAM,CAAA;IACpB;;;OAGG;IACH,WAAW,CAAC,EAAE,MAAM,CAAA;IACpB;;;;;;;;;;;;OAYG;IACH,MAAM,CAAC,EAAE,MAAM,CAAA;IACf;;;;;;;OAOG;IACH,OAAO,CAAC,EAAE,MAAM,CAAA;IAChB;;;;OAIG;IACH,cAAc,CAAC,EAAE,OAAO,CAAA;CACzB,CAAC,CAAA;AAg2BF;;;;;;;;;;;;;;;;;GAiBG;AACH,eAAO,MAAM,UAAU,YAAa,iBAAiB,KAAG,MAoNvD,CAAA"}
package/dist/ssr.js CHANGED
@@ -1,5 +1,6 @@
1
- import { Array, Effect, Predicate } from 'effect';
1
+ import { Array, Effect, Latch, Predicate } from 'effect';
2
2
  import * as Server from 'foldkit/experimental/server';
3
+ import MagicString from 'magic-string';
3
4
  import { readFile } from 'node:fs/promises';
4
5
  import { resolve } from 'node:path';
5
6
  import { Readable } from 'node:stream';
@@ -10,6 +11,87 @@ import { buildIdForCommand } from './buildToken.js';
10
11
  // getter is the shape every copy shares, and `in` reads its descriptor without
11
12
  // invoking it.
12
13
  const isRunnable = (environment) => 'runner' in environment;
14
+ const isHotServerEnvironment = (environment) => environment.name === 'ssr' &&
15
+ environment.config.server.hmr !== false &&
16
+ isRunnable(environment);
17
+ // NOTE: Vite reruns an edited declaration module and its importers, but keeps
18
+ // imported Block Definitions. Invalidate the full server graph so the next
19
+ // entry evaluation creates each Definition before registering its declarations.
20
+ const invalidateServerModulesForReevaluation = (environment) => {
21
+ const { moduleGraph } = environment;
22
+ const invalidatedModules = new Set();
23
+ for (const module of moduleGraph.idToModuleMap.values()) {
24
+ moduleGraph.invalidateModule(module, invalidatedModules, undefined, false, true);
25
+ }
26
+ };
27
+ const reevaluatedServerEntries = new WeakMap();
28
+ // NOTE: Vite invalidates the edited file after async watchChange hooks settle.
29
+ // Non-HMR requests can arrive during those hooks, so refresh the graph only
30
+ // after Vite changes the entry's stamp. Record our resulting stamp before
31
+ // importing so concurrent requests reuse that same evaluation.
32
+ const importServerEntry = async (environment, serverEntry) => {
33
+ if (environment.config.server.hmr === false) {
34
+ const entry = await environment.moduleGraph.ensureEntryFromUrl(serverEntry);
35
+ const previousTimestamp = reevaluatedServerEntries.get(entry);
36
+ if (previousTimestamp !== undefined &&
37
+ previousTimestamp !== entry.lastInvalidationTimestamp) {
38
+ invalidateServerModulesForReevaluation(environment);
39
+ }
40
+ reevaluatedServerEntries.set(entry, entry.lastInvalidationTimestamp);
41
+ }
42
+ return environment.runner.import(serverEntry);
43
+ };
44
+ const SERVER_UPDATE_SETTLED_EVENT = 'foldkit:server-update-settled';
45
+ const SERVER_UPDATE_SETTLE_TIMEOUT_MS = 1_000;
46
+ // NOTE: The entry accepts updates so Vite runs its `import.meta.hot.dispose`
47
+ // callback before evaluating the replacement. The server graph is invalidated
48
+ // separately so every Block Definition is recreated with its declarations.
49
+ // The entry also reports each update payload the runner finishes handling, so
50
+ // the dev server can hold requests until then.
51
+ const SERVER_ENTRY_HOT_SOURCE = `if (import.meta.hot) {
52
+ import.meta.hot.accept()
53
+ const reportSettledUpdate = () => {
54
+ import.meta.hot.send(${JSON.stringify(SERVER_UPDATE_SETTLED_EVENT)})
55
+ }
56
+ import.meta.hot.on('vite:afterUpdate', reportSettledUpdate)
57
+ import.meta.hot.on('vite:beforeFullReload', reportSettledUpdate)
58
+ import.meta.hot.on('vite:error', reportSettledUpdate)
59
+ }
60
+ `;
61
+ // NOTE: Vite invalidates the edited modules before it sends the update to the
62
+ // module runner. A request that imports the server entry in between evaluates
63
+ // a new copy, whose `dispose` callback replaces the old copy's, so the old copy
64
+ // is never released. The gate counts the edits to modules in the `ssr` module
65
+ // graph and holds requests until the entry reports each one settled. The
66
+ // timeout releases them when an edit never reaches the runner.
67
+ const makeServerUpdateGate = () => {
68
+ const settled = Latch.makeUnsafe(true);
69
+ let pendingUpdateCount = 0;
70
+ let settleTimeout;
71
+ const release = () => {
72
+ pendingUpdateCount = 0;
73
+ clearTimeout(settleTimeout);
74
+ settled.openUnsafe();
75
+ };
76
+ const beginUpdate = () => {
77
+ pendingUpdateCount += 1;
78
+ settled.closeUnsafe();
79
+ clearTimeout(settleTimeout);
80
+ settleTimeout = setTimeout(release, SERVER_UPDATE_SETTLE_TIMEOUT_MS).unref();
81
+ };
82
+ const settleUpdate = () => {
83
+ pendingUpdateCount = Math.max(0, pendingUpdateCount - 1);
84
+ if (pendingUpdateCount === 0) {
85
+ release();
86
+ }
87
+ };
88
+ return {
89
+ beginUpdate,
90
+ settleUpdate,
91
+ awaitSettledUpdates: settled.await,
92
+ close: release,
93
+ };
94
+ };
13
95
  const isEntryModule = (loadedModule) => Predicate.isObject(loadedModule) &&
14
96
  Predicate.hasProperty(loadedModule, 'renderPage') &&
15
97
  Predicate.isFunction(loadedModule.renderPage);
@@ -129,10 +211,11 @@ const renderDecision = (nodeRequest, requestUrl) => {
129
211
  }
130
212
  return 'Render';
131
213
  };
132
- const renderRequest = (server, options, nodeRequest, requestUrl) => Effect.gen(function* () {
214
+ const renderRequest = (server, ssrEnvironment, serverUpdates, options, nodeRequest, requestUrl) => Effect.gen(function* () {
133
215
  const { pathname, search } = new URL(requestUrl);
134
216
  const route = `${pathname}${search}`;
135
- const loadedModule = yield* Effect.promise(() => server.ssrLoadModule(options.serverEntry));
217
+ yield* serverUpdates.awaitSettledUpdates;
218
+ const loadedModule = yield* Effect.promise(() => importServerEntry(ssrEnvironment, options.serverEntry));
136
219
  if (!isEntryModule(loadedModule)) {
137
220
  return yield* Effect.die(new Error(`[foldkit] '${options.serverEntry}' does not export a renderPage function, so the dev server cannot render pages.`));
138
221
  }
@@ -408,7 +491,7 @@ const sendWebResponse = async (webResponse, nodeRequest, nodeResponse, isNegotia
408
491
  // The handler that turns an application-owned request into a response. OPTIONS
409
492
  // reaches it at the host boundary. Other methods reach it after Vite's modules
410
493
  // and assets have had an opportunity to answer.
411
- const renderMiddleware = (server, options, requestUrls, stateByRequest) => (nodeRequest, nodeResponse, next) => {
494
+ const renderMiddleware = (server, ssrEnvironment, serverUpdates, options, requestUrls, stateByRequest) => (nodeRequest, nodeResponse, next) => {
412
495
  const corsState = stateByRequest.get(nodeRequest);
413
496
  stateByRequest.delete(nodeRequest);
414
497
  corsState?.tracking.stop();
@@ -452,29 +535,35 @@ const renderMiddleware = (server, options, requestUrls, stateByRequest) => (node
452
535
  return;
453
536
  }
454
537
  const isNegotiated = decision === 'RenderNegotiated';
455
- void Effect.runPromise(renderRequest(server, options, nodeRequest, requestUrl))
538
+ void Effect.runPromise(renderRequest(server, ssrEnvironment, serverUpdates, options, nodeRequest, requestUrl))
456
539
  .then(response => sendWebResponse(response, nodeRequest, nodeResponse, isNegotiated))
457
- .catch((error) => {
458
- if (error instanceof Error) {
459
- server.ssrFixStacktrace(error);
460
- }
461
- next(error);
462
- });
540
+ // NOTE: The runner maps error stacks from the modules it evaluates to
541
+ // their source. `server.ssrFixStacktrace` would map them a second time
542
+ // and can point the error overlay at the wrong lines.
543
+ .catch(next);
463
544
  };
464
545
  /**
465
546
  * Serves server-rendered pages from the Vite dev server.
466
547
  *
467
548
  * Vite retains ownership of configured proxies, source modules, HMR, and
468
- * assets. Requests that fall through load the server entry through Vite's SSR
469
- * module loader, call its `renderPage` with a Web `Request`, and send the
470
- * resulting Web `Response`. Vite's host validation applies before either
471
- * owner. Foldkit then validates and normalizes the request target before Vite
472
- * or the server entry can resolve it. Vite's CORS option applies only to
549
+ * assets. Requests that fall through load the server entry through the `ssr`
550
+ * environment's module runner, call its `renderPage` with a Web `Request`, and
551
+ * send the resulting Web `Response`. Vite's host validation applies before
552
+ * either owner. Foldkit then validates and normalizes the request target before
553
+ * Vite or the server entry can resolve it. Vite's CORS option applies only to
473
554
  * Vite-owned responses, while the server entry owns CORS for application
474
- * responses. Server entry edits take effect without a restart.
555
+ * responses. Server entry edits take effect without a restart. The server
556
+ * entry accepts its own updates, and the server graph is reevaluated so Block
557
+ * Definitions and their declarations are created together. Unless
558
+ * `server.hmr` is `false`, an `import.meta.hot.dispose` callback in the entry
559
+ * runs before a hot update replaces it. With HMR disabled, stop and restart
560
+ * the dev-server process after editing server modules that own long-lived
561
+ * resources; an in-process restart cannot invoke the missing callback.
475
562
  */
476
563
  export const foldkitSsr = (options) => {
477
564
  let isDevelopmentHost = false;
565
+ const entryIds = new WeakMap();
566
+ const serverUpdates = makeServerUpdateGate();
478
567
  return {
479
568
  name: 'foldkit-ssr',
480
569
  configResolved(config) {
@@ -518,6 +607,65 @@ export const foldkitSsr = (options) => {
518
607
  }),
519
608
  };
520
609
  },
610
+ perEnvironmentWatchChangeDuringDev: true,
611
+ watchChange(id, change) {
612
+ if (!isDevelopmentHost ||
613
+ change.event !== 'update' ||
614
+ this.environment.name !== 'ssr' ||
615
+ !isRunnable(this.environment)) {
616
+ return;
617
+ }
618
+ const serverModules = this.environment.moduleGraph.getModulesByFile(id);
619
+ if (serverModules !== undefined && serverModules.size > 0) {
620
+ if (isHotServerEnvironment(this.environment)) {
621
+ serverUpdates.beginUpdate();
622
+ invalidateServerModulesForReevaluation(this.environment);
623
+ }
624
+ }
625
+ },
626
+ // NOTE: Vite invalidates the server entry when a module it imports
627
+ // dynamically changes, even when the runner has not loaded that module,
628
+ // but sends the runner no update for it. The next request would then
629
+ // evaluate a new copy without disposing the old one, so the update goes to
630
+ // the entry instead.
631
+ hotUpdate({ type, file, modules }) {
632
+ if (!isDevelopmentHost ||
633
+ type !== 'update' ||
634
+ !isHotServerEnvironment(this.environment) ||
635
+ Array.isArrayEmpty(modules)) {
636
+ return undefined;
637
+ }
638
+ const entryId = entryIds.get(this.environment);
639
+ const evaluatedModules = this.environment.runner.evaluatedModules.getModulesByFile(file);
640
+ if (entryId === undefined ||
641
+ (evaluatedModules !== undefined && evaluatedModules.size > 0)) {
642
+ return undefined;
643
+ }
644
+ const entryModule = this.environment.moduleGraph.getModuleById(entryId);
645
+ return entryModule === undefined ? undefined : [entryModule];
646
+ },
647
+ async transform(code, id) {
648
+ if (!isDevelopmentHost ||
649
+ this.environment.name !== 'ssr' ||
650
+ !isRunnable(this.environment)) {
651
+ return undefined;
652
+ }
653
+ const entryId = entryIds.get(this.environment) ??
654
+ (await this.resolve(options.serverEntry).catch(() => undefined))?.id;
655
+ if (entryId === undefined) {
656
+ return undefined;
657
+ }
658
+ entryIds.set(this.environment, entryId);
659
+ if (entryId !== id) {
660
+ return undefined;
661
+ }
662
+ const transformed = new MagicString(code);
663
+ transformed.prepend(SERVER_ENTRY_HOT_SOURCE);
664
+ return {
665
+ code: transformed.toString(),
666
+ map: transformed.generateMap({ hires: 'boundary', source: id }),
667
+ };
668
+ },
521
669
  configureServer: server => {
522
670
  // Rendering here loads the server entry through the `ssr` environment's
523
671
  // module runner, which only a runnable environment has. A host plugin
@@ -528,7 +676,8 @@ export const foldkitSsr = (options) => {
528
676
  // them here instead would run the application in Node, without the
529
677
  // bindings the deployed entry holds, while the deployment it is standing
530
678
  // in for renders in workerd.
531
- if (!isRunnable(server.environments.ssr)) {
679
+ const ssrEnvironment = server.environments.ssr;
680
+ if (!isRunnable(ssrEnvironment)) {
532
681
  if (options.quietStandDown !== true) {
533
682
  server.config.logger.warn('[foldkit] the "ssr" environment is not runnable, so another plugin owns' +
534
683
  " server-side execution. Dev-time rendering through Foldkit's Vite" +
@@ -538,12 +687,22 @@ export const foldkitSsr = (options) => {
538
687
  }
539
688
  const requestUrls = new WeakMap();
540
689
  const stateByRequest = new WeakMap();
541
- const render = renderMiddleware(server, options, requestUrls, stateByRequest);
690
+ ssrEnvironment.hot.on(SERVER_UPDATE_SETTLED_EVENT, serverUpdates.settleUpdate);
691
+ const render = renderMiddleware(server, ssrEnvironment, serverUpdates, options, requestUrls, stateByRequest);
542
692
  server.middlewares.use(requestTargetMiddleware(server, options, requestUrls, render));
543
693
  wrapViteCors(server, options, requestUrls, stateByRequest);
544
694
  return () => {
545
695
  server.middlewares.use(render);
546
696
  };
547
697
  },
698
+ closeBundle() {
699
+ if (!isDevelopmentHost ||
700
+ this.environment.name !== 'ssr' ||
701
+ !isRunnable(this.environment)) {
702
+ return;
703
+ }
704
+ this.environment.hot.off(SERVER_UPDATE_SETTLED_EVENT, serverUpdates.settleUpdate);
705
+ serverUpdates.close();
706
+ },
548
707
  };
549
708
  };
@@ -1 +1 @@
1
- {"version":3,"file":"viewIdentity.d.ts","sourceRoot":"","sources":["../src/viewIdentity.ts"],"names":[],"mappings":"AAAA,OAAoB,EAAE,KAAK,SAAS,EAAE,MAAM,cAAc,CAAA;AAI1D,OAAO,EAAE,KAAK,MAAM,EAAY,MAAM,MAAM,CAAA;AA6a5C,iFAAiF;AACjF,MAAM,MAAM,2BAA2B,GAAG,QAAQ,CAAC;IACjD,IAAI,EAAE,MAAM,CAAA;IACZ,GAAG,EAAE,SAAS,CAAA;CACf,CAAC,CAAA;AAEF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAsCG;AACH,eAAO,MAAM,qBAAqB,SAC1B,MAAM,MACR,MAAM,QACJ,MAAM,YACF,QAAQ,CAAC;IACjB,qBAAqB,CAAC,EAAE,OAAO,CAAA;CAChC,CAAC,KACD,2BAA2B,GAAG,IAyChC,CAAA;AA8DD;;;;;;;;;;;GAWG;AACH,eAAO,MAAM,mBAAmB,QAAO,MA0CtC,CAAA"}
1
+ {"version":3,"file":"viewIdentity.d.ts","sources":["../src/viewIdentity.ts"],"names":[],"mappings":"AAAA,OAAoB,EAAE,KAAK,SAAS,EAAE,MAAM,cAAc,CAAA;AAI1D,OAAO,EAAE,KAAK,MAAM,EAAY,MAAM,MAAM,CAAA;AA6a5C,iFAAiF;AACjF,MAAM,MAAM,2BAA2B,GAAG,QAAQ,CAAC;IACjD,IAAI,EAAE,MAAM,CAAA;IACZ,GAAG,EAAE,SAAS,CAAA;CACf,CAAC,CAAA;AAEF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAsCG;AACH,eAAO,MAAM,qBAAqB,SAC1B,MAAM,MACR,MAAM,QACJ,MAAM,YACF,QAAQ,CAAC;IACjB,qBAAqB,CAAC,EAAE,OAAO,CAAA;CAChC,CAAC,KACD,2BAA2B,GAAG,IAyChC,CAAA;AA8DD;;;;;;;;;;;GAWG;AACH,eAAO,MAAM,mBAAmB,QAAO,MA0CtC,CAAA"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@foldkit/vite-plugin",
3
- "version": "0.28.0",
3
+ "version": "0.29.0-canary.54f8bcd443b4",
4
4
  "description": "Vite plugin for Foldkit with state-preserving live reload",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -16,13 +16,13 @@
16
16
  "dist"
17
17
  ],
18
18
  "peerDependencies": {
19
- "effect": "4.0.0",
20
- "foldkit": ">=0.167.0",
19
+ "effect": "~4.1.0",
20
+ "foldkit": "0.170.0-canary.54f8bcd443b4",
21
21
  "vite": "^8.0.0"
22
22
  },
23
23
  "dependencies": {
24
- "@effect/platform-node": "4.0.0",
25
- "@effect/platform-node-shared": "4.0.0",
24
+ "@effect/platform-node": "~4.1.0",
25
+ "@effect/platform-node-shared": "~4.1.0",
26
26
  "magic-string": "^1.4.2",
27
27
  "vitefu": "^1.1.3",
28
28
  "ws": "^8.21.3"
@@ -31,14 +31,14 @@
31
31
  "@types/node": "26.4.0",
32
32
  "@types/ws": "^8.18.1",
33
33
  "@vitejs/plugin-basic-ssl": "^2.3.0",
34
- "effect": "4.0.0",
35
- "foldkit": "0.169.0",
36
- "happy-dom": "^20.14.5",
34
+ "effect": "4.1.0",
35
+ "foldkit": "0.170.0-canary.54f8bcd443b4",
36
+ "happy-dom": "^21.0.4",
37
37
  "rimraf": "^6.1.3",
38
- "typescript": "^7.0.2",
39
- "vite": "^8.3.1",
40
- "vite-host": "npm:vite@8.2.1",
41
- "vitest": "^4.1.11"
38
+ "typescript": "7.1.0-beta",
39
+ "vite": "^8.3.3",
40
+ "vite-host": "npm:vite@8.2.4",
41
+ "vitest": "^4.1.12"
42
42
  },
43
43
  "keywords": [
44
44
  "vite",
@@ -58,7 +58,7 @@
58
58
  "access": "public"
59
59
  },
60
60
  "engines": {
61
- "node": ">=20.19.0"
61
+ "node": ">=22.19.0"
62
62
  },
63
63
  "scripts": {
64
64
  "clean": "rimraf dist *.tsbuildinfo",