The best way to control Claude Code, Codex and more from any computer or phone

main
ts 656 lines 26.7 KB
Raw
1 import * as NodeFs from "node:fs";
2 import * as NodePath from "node:path";
3 import { pathToFileURL } from "node:url";
4 import type { Adapter } from "@sveltejs/kit";
5 import * as Effect from "effect/Effect";
6 import * as FileSystem from "effect/FileSystem";
7 import * as Layer from "effect/Layer";
8 import * as Path from "effect/Path";
9 import type * as ViteModule from "vite";
10 import * as FrameworkCore from "../core/index.ts";
11 import {
12 Framework,
13 FrameworkError,
14 type DeployTarget,
15 type DeployTargetInput,
16 } from "../core/index.ts";
17 import { DEFAULT_VITE_CONFIG_FILES, makeSvelteKitConfigPlugin } from "./UserConfig.ts";
18
19 /** The shape of the project's `@sveltejs/kit/vite` module. */
20 interface KitViteModule {
21 readonly sveltekit: (config?: Record<string, unknown>) => Promise<ViteModule.PluginOption>;
22 }
23
24 /**
25 * Adapter behavior a deploy target can configure without being consulted on
26 * every write the adapter performs. The names mirror the knobs a static-asset
27 * host exposes (fallback-page generation, the name of the binding the worker
28 * shim serves assets through).
29 */
30 export interface SvelteKitAdapterOptions {
31 /**
32 * Name of the static-assets binding the generated worker entry serves
33 * files through.
34 * @default "ASSETS"
35 */
36 readonly assetsBinding?: string | undefined;
37 /**
38 * Fallback-page behavior for requests that match no asset or route:
39 * `"404-page"` writes `404.html`, `"single-page-application"` writes
40 * `index.html` and additionally routes router-level not-founds on
41 * navigation-shaped requests through the fallback (the Cloudflare
42 * target's worker shim defers them to the assets layer).
43 * @default "none"
44 */
45 readonly notFoundHandling?: "none" | "404-page" | "single-page-application" | undefined;
46 /**
47 * With `notFoundHandling: "404-page"`: `"spa"` renders the app shell as the
48 * fallback, `"plaintext"` writes a plain `Not Found` page.
49 * @default "plaintext"
50 */
51 readonly fallback?: "spa" | "plaintext" | undefined;
52 }
53
54 /**
55 * The configuration this package assembles from {@link SvelteKitOptions} and
56 * hands to a deploy-target factory (see {@link SvelteKitTargetInput}). The
57 * target treats it as its `DeployTarget.config`; the framework half never
58 * inspects a resolved target's config.
59 */
60 export interface SvelteKitTargetConfig {
61 /** Compatibility date for the target's finishing pass. */
62 readonly compatibilityDate?: string | undefined;
63 /** Compatibility flags for the target's finishing pass. */
64 readonly compatibilityFlags?: Array<string> | undefined;
65 /** Adapter behavior (assets binding name, fallback generation). */
66 readonly adapter?: SvelteKitAdapterOptions | undefined;
67 /**
68 * The kit config the framework half was constructed with
69 * ({@link SvelteKitOptions.kit}). Carried on the target config so
70 * wholesale targets that re-run the framework in a child process (the
71 * AWS target — kit's postbuild workers require `cwd === root`) can
72 * reconstruct the framework with the same options.
73 */
74 readonly kit?: Record<string, unknown> | undefined;
75 }
76
77 /** Inputs the framework passes when asking the target for a kit `Adapter`. */
78 export interface SvelteKitAdapterContext {
79 /** Absolute project root. */
80 readonly root: string;
81 /**
82 * Present when the adapter is constructed for the dev server: inputs for
83 * the `platform` its `emulate()` must supply. Absent for production
84 * builds.
85 */
86 readonly dev?:
87 | {
88 /**
89 * Literal `platform.env` overrides — a same-named literal wins over
90 * any target-provided platform value.
91 */
92 readonly env?: Record<string, unknown> | undefined;
93 /**
94 * Target-specific binding specs the dev platform should serve
95 * (opaque to the framework half — e.g. the Cloudflare target takes
96 * `cloudflare-runtime` binding hooks and proxies them onto
97 * `platform.env`).
98 */
99 readonly bindings?: ReadonlyArray<unknown> | undefined;
100 /**
101 * A pre-built runtime-services context the dev platform hosts its
102 * proxy in (opaque to the framework half; the Cloudflare target
103 * takes a `cloudflare-runtime` `Context<RuntimeServices>`). Enables
104 * remote()-lowered bindings; without it the platform is local-only.
105 */
106 readonly services?: unknown;
107 /**
108 * Overrides for the dev platform's workerd process (opaque to the
109 * framework half; the Cloudflare target takes `cloudflare-runtime`
110 * `WorkerdOptions`).
111 */
112 readonly workerd?: unknown;
113 /**
114 * Absolute path of kit's static directory (`kit.files.assets`), for
115 * a target whose dev platform serves its files (the Cloudflare
116 * target's `ASSETS` binding).
117 */
118 readonly assetsDirectory?: string | undefined;
119 }
120 | undefined;
121 }
122
123 /** What a target's `adapt()` must record for the framework to continue. */
124 export interface SvelteKitAdapterResult {
125 /**
126 * The static-assets directory the adapter wrote (client build +
127 * prerendered pages) — becomes `BuildOutput.clientDirectory`.
128 */
129 readonly dest: string;
130 /**
131 * Absolute path of the on-disk (unbundled) server entry the adapter
132 * generated — passed to the target's `finish` pass as `context.entry`.
133 */
134 readonly workerEntry: string;
135 }
136
137 /**
138 * A kit `Adapter` that records where it wrote its output. Every SvelteKit
139 * deploy target's adapter must populate `result.current` from `adapt()`.
140 */
141 export interface SvelteKitAdapter extends Adapter {
142 readonly result: { current?: SvelteKitAdapterResult | undefined };
143 /**
144 * Release resources the adapter holds for the dev server (e.g. the
145 * Cloudflare target's platform-proxy workerd instance). Called by the
146 * framework after the dev server closes.
147 */
148 readonly dispose?: (() => Promise<void>) | undefined;
149 }
150
151 /**
152 * A deploy target for SvelteKit: the generic `DeployTarget` seams plus the
153 * one framework-specific hook kit needs — the `Adapter` instance to hand to
154 * `sveltekit(config)`. The target's `finish` pass receives the adapter's
155 * on-disk `workerEntry` (via `context.entry`) and is responsible for turning
156 * it into `BuildOutput.serverModules` for the target runtime.
157 */
158 export interface SvelteKitTarget extends DeployTarget<SvelteKitTargetConfig> {
159 /** Produce the kit `Adapter` for one build/dev invocation. */
160 readonly adapter: (context: SvelteKitAdapterContext) => SvelteKitAdapter;
161 }
162
163 /**
164 * How a deploy target is passed to this package: a `SvelteKitTarget` value, a
165 * factory `(config) => SvelteKitTarget`, or a module specifier resolved from
166 * the *project's* `node_modules` (default-export — or named export `target` —
167 * a value or factory).
168 */
169 export type SvelteKitTargetInput = DeployTargetInput<SvelteKitTarget, SvelteKitTargetConfig>;
170
171 /**
172 * The default deploy target: this package's own Cloudflare Workers target
173 * module (`src/cloudflare.ts`), loaded from the project's dependency tree.
174 */
175 export const DEFAULT_TARGET_SPECIFIER = "@alchemy.run/frontend-frameworks/sveltekit/cloudflare";
176
177 export interface SvelteKitOptions {
178 /**
179 * Project root. Must also be the process working directory: SvelteKit
180 * resolves its peers (`vite`, `@sveltejs/vite-plugin-svelte`) relative to
181 * `process.cwd()`.
182 * @default process.cwd()
183 */
184 readonly root?: string | undefined;
185 /**
186 * The deploy target the build is produced for. Accepts a target value, a
187 * `(config) => target` factory, or a module specifier string.
188 * @default "@alchemy.run/frontend-frameworks/sveltekit/cloudflare"
189 */
190 readonly target?: SvelteKitTargetInput | undefined;
191 /** Compatibility date forwarded to the target via its config. */
192 readonly compatibilityDate?: string | undefined;
193 /**
194 * Compatibility flags forwarded to the target via its config. SvelteKit's
195 * server graph is built for Node, so on workerd-style targets
196 * `nodejs_compat` is effectively required.
197 * @default ["nodejs_compat"] (applied by the Cloudflare target)
198 */
199 readonly compatibilityFlags?: Array<string> | undefined;
200 /**
201 * SvelteKit configuration for `sveltekit(config)` (kit v3 takes its config
202 * via the Vite plugin; a `svelte.config.js` on disk is an upstream error).
203 * When the project has its own `vite.config.ts`, these options are merged
204 * over the ones passed to the user's `sveltekit(...)` call (integration
205 * options win); construction-time options (`preprocess`, `extensions`,
206 * `compilerOptions`, `vitePlugin`) can only be applied when no user config
207 * file exists. The `adapter` field is always injected by this package.
208 */
209 readonly kit?: Record<string, unknown> | undefined;
210 /** Extra Vite inline config merged into the build/dev config. */
211 readonly vite?: ViteModule.InlineConfig | undefined;
212 /** Adapter behavior forwarded to the target via its config. */
213 readonly adapter?: SvelteKitAdapterOptions | undefined;
214 readonly dev?:
215 | {
216 /** Default dev-server port (overridden by `FrameworkDevOptions.port`). */
217 readonly port?: number | undefined;
218 /**
219 * Literal values exposed on the dev `platform.env`. Applied on top
220 * of the values the target's dev platform serves for
221 * {@link SvelteKitOptions.dev.bindings} — a same-named literal
222 * always wins.
223 */
224 readonly env?: Record<string, unknown> | undefined;
225 /**
226 * Target-specific binding specs the dev platform should serve on
227 * `platform.env`. Opaque to the framework half; the Cloudflare
228 * target accepts `cloudflare-runtime` binding hooks (`Text.local`,
229 * `KvNamespace.local`, …) and proxies them into kit's Node SSR via
230 * a workerd-backed platform proxy.
231 */
232 readonly bindings?: ReadonlyArray<unknown> | undefined;
233 /**
234 * A pre-built runtime-services context the dev platform hosts its
235 * proxy in (opaque to the framework half; the Cloudflare target
236 * takes a `cloudflare-runtime` `Context<RuntimeServices>`). Enables
237 * remote()-lowered bindings; without it the platform is local-only.
238 */
239 readonly services?: unknown;
240 /**
241 * Overrides for the dev platform's workerd process (opaque to the
242 * framework half; the Cloudflare target takes `cloudflare-runtime`
243 * `WorkerdOptions`).
244 */
245 readonly workerd?: unknown;
246 }
247 | undefined;
248 }
249
250 const fail = (message: string, cause?: unknown) =>
251 new FrameworkError({ framework: "sveltekit", message, cause });
252
253 /**
254 * Pick the ESM target out of a package-exports entry (`"./x": "./file.js"` or
255 * `"./x": { import: ..., default: ... }`, possibly nested conditions).
256 */
257 export const resolveExportTarget = (entry: unknown): string | undefined => {
258 if (typeof entry === "string") {
259 return entry;
260 }
261 if (entry !== null && typeof entry === "object") {
262 const record = entry as Record<string, unknown>;
263 for (const condition of ["import", "default"]) {
264 if (condition in record) {
265 const target = resolveExportTarget(record[condition]);
266 if (target !== undefined) {
267 return target;
268 }
269 }
270 }
271 }
272 return undefined;
273 };
274
275 /** Path segment identifying an id inside an `@sveltejs/kit` package. */
276 const KIT_PACKAGE_MARKER = "/@sveltejs/kit/";
277
278 /**
279 * Re-anchor kit-runtime module ids that were resolved against the wrong
280 * base directory.
281 *
282 * SvelteKit's route manifest stores its fallback root components
283 * (`<kit>/src/runtime/components/{layout,error}.svelte`) as paths RELATIVE
284 * to the Vite root, but resolves them against `process.cwd()`: the dev
285 * server's node loader calls `path.resolve(id)`, and the generated
286 * client/server modules embed `path.relative(absoluteBase, relativeId)`
287 * output (whose `relativeId` is resolved against the cwd). Kit therefore
288 * assumes `process.cwd() === root`. When the dev server is driven
289 * programmatically from another directory — alchemy's dev sidecar, a
290 * monorepo root — those ids re-root outside the project and every SSR
291 * request 500s with `Failed to load url
292 * /@fs/<wrong-base>/.../@sveltejs/kit/src/runtime/components/layout.svelte`.
293 *
294 * This plugin remaps exactly those casualties: an id that points inside an
295 * `@sveltejs/kit` package directory but does NOT exist on disk is re-rooted
296 * onto the project's real kit installation. Ids that resolve to an existing
297 * file are never touched.
298 */
299 const makeKitRuntimeRealignPlugin = (kitDirectory: string): ViteModule.Plugin => {
300 const realign = (candidate: string, query: string): string | undefined => {
301 if (NodeFs.existsSync(candidate)) {
302 return undefined;
303 }
304 const normalized = candidate.replaceAll("\\", "/");
305 const index = normalized.lastIndexOf(KIT_PACKAGE_MARKER);
306 if (index === -1) {
307 return undefined;
308 }
309 const remapped = NodePath.join(
310 kitDirectory,
311 normalized.slice(index + KIT_PACKAGE_MARKER.length),
312 );
313 return NodeFs.existsSync(remapped) ? remapped + query : undefined;
314 };
315 return {
316 name: "distilled-sveltekit-kit-runtime-realign",
317 enforce: "pre",
318 resolveId(source, importer) {
319 if (!source.includes("@sveltejs")) {
320 return undefined;
321 }
322 const queryIndex = source.indexOf("?");
323 const bare = queryIndex === -1 ? source : source.slice(0, queryIndex);
324 const query = queryIndex === -1 ? "" : source.slice(queryIndex);
325 if (bare.startsWith("/@fs/")) {
326 // Vite serves absolute fs paths as `/@fs/<path>` (`/@fs/C:/...` on
327 // Windows — strip the extra leading slash before a drive letter).
328 const fsPath = bare.slice("/@fs".length);
329 return realign(/^\/[A-Za-z]:[/\\]/.test(fsPath) ? fsPath.slice(1) : fsPath, query);
330 }
331 if (NodePath.isAbsolute(bare)) {
332 return realign(bare, query);
333 }
334 if (bare.startsWith(".") && importer !== undefined) {
335 const importerPath = importer.split("?")[0] ?? importer;
336 return realign(NodePath.resolve(NodePath.dirname(importerPath), bare), query);
337 }
338 return undefined;
339 },
340 };
341 };
342
343 /**
344 * Build the `Framework` service implementation for a SvelteKit project.
345 *
346 * - `build` resolves the deploy target, then either delegates wholesale
347 * (`target.build`) or runs kit's production build via programmatic Vite
348 * (`createBuilder().buildApp()`) with the target-provided adapter and hands
349 * the adapter's on-disk worker entry to the target's `finish` pass, which
350 * produces the final `BuildOutput.serverModules`. A project-owned
351 * `vite.config.ts` loads natively (the user's `sveltekit(...)` call and
352 * plugins apply; the target's adapter is injected into it — see
353 * `UserConfig.ts`); without one, the config is fully programmatic.
354 * - `dev` runs kit's own Vite dev server (Node SSR, full HMR) with the
355 * target-provided adapter supplying the `platform` emulation.
356 *
357 * This module is target-agnostic: everything Cloudflare-specific lives in
358 * `@alchemy.run/frontend-frameworks/sveltekit/cloudflare`.
359 */
360 export const make: (
361 options?: SvelteKitOptions,
362 ) => Effect.Effect<Framework["Service"], never, FileSystem.FileSystem | Path.Path> =
363 Effect.fnUntraced(function* (options?: SvelteKitOptions) {
364 const fs = yield* FileSystem.FileSystem;
365 const path = yield* Path.Path;
366 const baseRoot = options?.root ?? (yield* Effect.sync(() => process.cwd()));
367
368 const targetConfig: SvelteKitTargetConfig = {
369 compatibilityDate: options?.compatibilityDate,
370 compatibilityFlags: options?.compatibilityFlags,
371 adapter: options?.adapter,
372 kit: options?.kit,
373 };
374
375 const resolveTarget = (root: string) =>
376 FrameworkCore.resolveDeployTarget<SvelteKitTarget, SvelteKitTargetConfig>(
377 root,
378 options?.target ?? DEFAULT_TARGET_SPECIFIER,
379 targetConfig,
380 ).pipe(Effect.mapError((error) => fail(error.message, error.cause)));
381
382 const requireAdapterHook = (target: SvelteKitTarget) =>
383 typeof target.adapter === "function"
384 ? Effect.succeed(target)
385 : Effect.fail(
386 fail(
387 `The resolved "${target.platform}" deploy target does not implement the SvelteKit ` +
388 "adapter hook (`adapter(context)`) and has no wholesale `build`",
389 ),
390 );
391
392 const loadVite = (root: string) =>
393 FrameworkCore.loadProjectModule<typeof ViteModule>(root, "vite").pipe(
394 Effect.mapError((error) => fail("Failed to load the project's Vite", error.cause)),
395 );
396
397 const resolveKitDirectory = (root: string) =>
398 FrameworkCore.resolveProjectPackageDirectory(root, "@sveltejs/kit").pipe(
399 Effect.mapError((error) =>
400 fail("Failed to locate the project's @sveltejs/kit", error.cause),
401 ),
402 );
403
404 // `@sveltejs/kit`'s `./vite` export carries only an `import` condition, so
405 // framework-core's `createRequire().resolve` dance cannot resolve it.
406 // Resolve the package directory (via its universally-exported
407 // `./package.json`) and walk the exports map instead.
408 const loadKitViteModule = Effect.fn(function* (root: string) {
409 const kitDirectory = yield* resolveKitDirectory(root);
410 const manifest = yield* fs
411 .readFileString(path.join(kitDirectory, "package.json"))
412 .pipe(
413 Effect.mapError((error) => fail("Failed to read @sveltejs/kit's package.json", error)),
414 );
415 const parsed = yield* Effect.try({
416 try: () => JSON.parse(manifest) as { exports?: Record<string, unknown> },
417 catch: (error) => fail("Failed to parse @sveltejs/kit's package.json", error),
418 });
419 const target = resolveExportTarget(parsed.exports?.["./vite"]);
420 if (target === undefined) {
421 return yield* fail(`The project's @sveltejs/kit (${kitDirectory}) has no "./vite" export`);
422 }
423 return yield* Effect.tryPromise({
424 try: async () =>
425 (await import(
426 /* @vite-ignore */ pathToFileURL(path.join(kitDirectory, target)).href
427 )) as KitViteModule,
428 catch: (error) => fail("Failed to load the project's @sveltejs/kit/vite", error),
429 });
430 });
431
432 const loadKitPlugins = Effect.fn(function* (root: string, adapter: Adapter) {
433 const kitVite = yield* loadKitViteModule(root);
434 return yield* Effect.tryPromise({
435 try: async () => await kitVite.sveltekit({ ...options?.kit, adapter }),
436 catch: (error) => fail("Failed to construct the SvelteKit plugin", error),
437 });
438 });
439
440 const findViteConfigFile = Effect.fnUntraced(function* (root: string) {
441 for (const name of DEFAULT_VITE_CONFIG_FILES) {
442 const exists = yield* fs
443 .exists(path.join(root, name))
444 .pipe(Effect.catchTag("PlatformError", () => Effect.succeed(false)));
445 if (exists) {
446 return name;
447 }
448 }
449 return undefined;
450 });
451
452 /**
453 * Assemble the Vite inline config for a build/dev invocation.
454 *
455 * - Project has its own Vite config file: the file loads natively
456 * (`configFile` is left to Vite's discovery — the user's plugins,
457 * including their `sveltekit(...)` call, all apply) and the inline
458 * config only injects `makeSvelteKitConfigPlugin`, which installs the
459 * deploy target's adapter (and `options.kit` overrides) into the
460 * user's kit config before kit processes it.
461 * - No config file on disk: internal fallback — `configFile: false` with
462 * the `sveltekit()` plugin constructed programmatically from
463 * `options.kit` + the target's adapter.
464 */
465 const resolveViteConfig = Effect.fn(function* (root: string, adapter: Adapter) {
466 // Kit resolves the manifest's `..`-relative fallback-component ids
467 // against `process.cwd()` instead of the Vite root; the realign plugin
468 // repairs them when the two differ (see makeKitRuntimeRealignPlugin).
469 const realign = makeKitRuntimeRealignPlugin(yield* resolveKitDirectory(root));
470 const userConfigFile = yield* findViteConfigFile(root);
471 if (userConfigFile === undefined) {
472 const plugins = yield* loadKitPlugins(root, adapter);
473 return {
474 root,
475 configFile: false,
476 // Default to warn: rolldown-vite's native progress reporter
477 // ("transforming...") writes straight to the fd, which corrupts
478 // hosting-process reporters (e.g. alchemy-test) that can only
479 // intercept JS-level writers.
480 logLevel: "warn",
481 ...options?.vite,
482 plugins: [realign, ...(options?.vite?.plugins ?? []), plugins],
483 } satisfies ViteModule.InlineConfig;
484 }
485 return {
486 root,
487 logLevel: "warn",
488 ...options?.vite,
489 plugins: [
490 realign,
491 ...(options?.vite?.plugins ?? []),
492 makeSvelteKitConfigPlugin({ adapter, kit: options?.kit }),
493 ],
494 } satisfies ViteModule.InlineConfig;
495 });
496
497 const build: Framework["Service"]["build"] = Effect.fn(function* (buildOptions) {
498 const root = buildOptions?.root ?? baseRoot;
499 const target = yield* resolveTarget(root);
500 const targetContext = {
501 root,
502 framework: "sveltekit",
503 env: buildOptions?.env,
504 };
505
506 // Wholesale build takeover (targets that own the entire pipeline).
507 if (target.build !== undefined) {
508 return yield* target.build(targetContext).pipe(
509 Effect.mapError((error) => fail(error.message, error.cause)),
510 Effect.provideService(FileSystem.FileSystem, fs),
511 Effect.provideService(Path.Path, path),
512 );
513 }
514
515 yield* requireAdapterHook(target);
516 const adapter = target.adapter({ root });
517 const vite = yield* loadVite(root);
518 const config = yield* resolveViteConfig(root, adapter);
519
520 yield* Effect.tryPromise({
521 try: async () => {
522 const builder = await vite.createBuilder(config, null);
523 await builder.buildApp();
524 },
525 catch: (error) => fail("Failed to build", error),
526 });
527
528 const result = adapter.result.current;
529 if (result === undefined) {
530 return yield* fail("The SvelteKit build completed without running the adapter");
531 }
532
533 const output: FrameworkCore.BuildOutput = {
534 distDirectory: path.resolve(root, "dist"),
535 clientDirectory: result.dest,
536 serverModules: undefined,
537 externalWorkspaces: new Set<string>(),
538 };
539
540 // The target's finishing pass turns the adapter's on-disk worker entry
541 // into runtime-ready server modules (e.g. the Cloudflare target's
542 // rolldown re-bundle for workerd).
543 return yield* FrameworkCore.applyDeployTargetFinish(target, output, {
544 ...targetContext,
545 entry: result.workerEntry,
546 }).pipe(
547 Effect.mapError((error) => fail(error.message, error.cause)),
548 Effect.provideService(FileSystem.FileSystem, fs),
549 Effect.provideService(Path.Path, path),
550 );
551 });
552
553 const devInProcess: Framework["Service"]["dev"] = Effect.fn(function* (devOptions) {
554 const root = devOptions?.root ?? baseRoot;
555 const target = yield* resolveTarget(root);
556 yield* requireAdapterHook(target);
557 const adapter = target.adapter({
558 root,
559 dev: {
560 env: options?.dev?.env,
561 bindings: options?.dev?.bindings,
562 services: options?.dev?.services,
563 workerd: options?.dev?.workerd,
564 assetsDirectory: NodePath.resolve(
565 root,
566 (options?.kit?.files as { assets?: string } | undefined)?.assets ?? "static",
567 ),
568 },
569 });
570 // Registered before the server is acquired so it runs after the server
571 // closes (finalizers are LIFO): the dev platform (e.g. the Cloudflare
572 // target's platform proxy) outlives the last in-flight request.
573 yield* Effect.addFinalizer(() =>
574 Effect.promise(async () => {
575 try {
576 await adapter.dispose?.();
577 } catch {
578 // dev-platform teardown is best-effort
579 }
580 }),
581 );
582 const vite = yield* loadVite(root);
583 const config = yield* resolveViteConfig(root, adapter);
584 // `port: 0` (true OS-assigned) on Vite >= 8.2.1, probed ephemeral port
585 // on older Vite — see `resolveViteDevPort`.
586 const port = yield* FrameworkCore.resolveViteDevPort(
587 vite.version,
588 devOptions?.port ?? options?.dev?.port,
589 );
590 const host = devOptions?.host;
591
592 const server = yield* Effect.acquireRelease(
593 Effect.tryPromise({
594 try: async () => {
595 const server = await vite.createServer({
596 ...config,
597 server: {
598 ...config.server,
599 port,
600 ...(host !== undefined ? { host } : undefined),
601 },
602 });
603 return await server.listen();
604 },
605 catch: (error) => fail("Failed to start the dev server", error),
606 }),
607 (server) => Effect.promise(async () => await server.close()),
608 );
609 const url = server.resolvedUrls?.local[0];
610 if (url === undefined) {
611 return yield* fail("Could not determine the dev server URL");
612 }
613 return { url };
614 });
615
616 // Constructing the SvelteKit plugin loads the project's `@sveltejs/kit`
617 // module graph, which misbehaves when several projects load it
618 // concurrently in one process (partially-initialized module bindings —
619 // `Cannot access 'kit_options' before initialization`). A process hosting
620 // many sites' dev servers (the alchemy dev sidecar) hits exactly that, so
621 // run the dev server in a dedicated child process instead (see
622 // core/DevChild.ts). Inside that child — or when the options cannot cross
623 // the process boundary (deploy-target VALUES, live vite plugins from the
624 // e2e harness) — the in-process path runs directly.
625 const dev: Framework["Service"]["dev"] = (devOptions) => {
626 if (FrameworkCore.isInsideDevChild() || !FrameworkCore.isJsonSerializable(options)) {
627 return devInProcess(devOptions);
628 }
629 const root = devOptions?.root ?? baseRoot;
630 const port = devOptions?.port ?? options?.dev?.port;
631 return FrameworkCore.runDevChild({
632 framework: "sveltekit",
633 module: "@alchemy.run/frontend-frameworks/sveltekit",
634 callerUrl: import.meta.url,
635 rootDir: root,
636 makeOptions: { ...options, root },
637 devOptions: {
638 root,
639 ...(port !== undefined ? { port } : {}),
640 ...(devOptions?.host !== undefined ? { host: devOptions.host } : {}),
641 },
642 });
643 };
644
645 return Framework.of({ build, dev });
646 });
647
648 /**
649 * A `Layer` providing framework-core's `Framework` service for a SvelteKit
650 * project — the fully-typed entrypoint for `e2e.config.ts` (harness form 4)
651 * and alchemy's `Website.SvelteKit` composite.
652 */
653 export const layer = (
654 options?: SvelteKitOptions,
655 ): Layer.Layer<Framework, never, FileSystem.FileSystem | Path.Path> =>
656 Layer.effect(Framework, make(options));