foldkit-ssr 0.7.0 → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +74 -6
- package/dist/client-DVG9_3rL.mjs.map +1 -1
- package/dist/client-DkwAniQQ.d.mts.map +1 -1
- package/dist/index.d.mts +3 -3
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +6 -5
- package/dist/index.mjs.map +1 -1
- package/dist/vite.d.mts +25 -1
- package/dist/vite.d.mts.map +1 -1
- package/dist/vite.mjs +39 -4
- package/dist/vite.mjs.map +1 -1
- package/package.json +2 -2
package/dist/vite.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"vite.mjs","names":[],"sources":["../src/vite.ts"],"sourcesContent":["/**\n * `foldkit-ssr/vite`: the static half of a build, as a Vite plugin. After\n * Vite writes the client bundle, `staticSite` renders every path with\n * `SSR.generate` and writes each page where a static host serves its\n * address, with the sitemap and `robots.txt` beside them. It owns no build:\n * it runs as a `closeBundle` step on the application's own client build,\n * with the application's own template.\n *\n * The application describes its site in a module the plugin evaluates\n * through a server (workspace packages resolve to source, as the build\n * does), so `vite.config.ts` names a file, never application code.\n */\nimport { mkdir, readFile, writeFile } from 'node:fs/promises'\nimport { dirname, isAbsolute, join, resolve } from 'node:path'\nimport { Effect, Schema } from 'effect'\nimport type { RenderError } from 'foldkit/experimental/server'\nimport type { Plugin } from 'vite'\nimport { SSR, type Head, type ResumeUnsafe } from './index.js'\nimport type { ResumableConfig, ResumePlan } from './shared.js'\n\n/** What a page adds to its head, given what it rendered: for site descriptions. */\nexport type { Head }\n\n/** A path the site generates, with the date its sitemap names when it has one. */\nexport type SitePath = string | { readonly path: string; readonly modified?: string | undefined }\n\nconst pathOf = (spec: SitePath): string => (typeof spec === 'string' ? spec : spec.path)\nconst modifiedOf = (spec: SitePath): string | undefined =>\n typeof spec === 'string' ? undefined : spec.modified\n\n/**\n * The file a static host serves for a path. `directory` is the package's\n * own layout (`/about` as `about/index.html`); `flat` writes `about.html`,\n * for hosts with clean addresses and no directory indexes. `generate`\n * refuses what is not servable (a query, a fragment, an unresolvable\n * address) before this maps it, so this maps and never validates.\n */\nexport const fileFor = (path: string, layout: 'directory' | 'flat'): string => {\n const trimmed = path.replace(/^\\/+/, '').replace(/\\/+$/, '')\n if (trimmed === '') return 'index.html'\n if (layout === 'flat') return trimmed.endsWith('.html') ? trimmed : `${trimmed}.html`\n return trimmed.endsWith('.html') ? trimmed : `${trimmed}/index.html`\n}\n\n/**\n * What a static site is: everything `SSR.generate` takes, plus where its\n * pages land. `config` may read the path (a site whose Model is prepared\n * per page satisfies and returns its own config for it); `paths` may close\n * over what the site serves (a thunk that seeds and lists, evaluated when\n * the build runs). `template` is the built shell the pages are rendered\n * into; `files` is the host's layout; `sitemap` and `robots` write their\n * files from the generated pages.\n */\nexport interface StaticSite<\n Model,\n Fields extends Schema.Struct.Fields,\n Message,\n // Unconstrained on purpose: a site's config carries its own services (a\n // Remote layer, flags), which no bound here could name without threading\n // the whole service graph through. The narrowed call still checks: a\n // config that is not a config or a function of a path fails where used.\n Resolved = ResumableConfig<Model, Message>,\n> {\n readonly config: Resolved | ((path: string) => Resolved | Promise<Resolved>)\n readonly plan: ResumePlan<Model, Fields>\n readonly buildId?: string | undefined\n readonly origin: string\n readonly paths:\n ReadonlyArray<SitePath> | (() => ReadonlyArray<SitePath> | Promise<ReadonlyArray<SitePath>>)\n readonly template: string\n readonly head?: Head | undefined\n readonly flags?: ((path: string) => unknown) | undefined\n readonly files?: 'directory' | 'flat' | undefined\n readonly sitemap?: boolean | undefined\n readonly robots?: boolean | undefined\n}\n\n/** One generated page, with the file the host serves it from. */\nexport interface BuiltPage {\n readonly path: string\n readonly file: string\n readonly html: string\n readonly modified?: string | undefined\n}\n\n/** What a static site build produced: its pages, and its sitemap and robots text. */\nexport interface BuiltSite {\n readonly pages: ReadonlyArray<BuiltPage>\n readonly sitemap?: string | undefined\n readonly robots?: string | undefined\n}\n\n/**\n * Renders a static site: every path through `SSR.generate`, one page per\n * path in order, with the sitemap and robots text the options ask for. A\n * build id must never be a secret, and two deployments must never share\n * one; empty is refused with the deployment's name missing.\n */\nexport const generateStaticSite = <Model, Fields extends Schema.Struct.Fields, Message = any>(\n site: StaticSite<Model, Fields, Message>,\n): Effect.Effect<BuiltSite, RenderError | ResumeUnsafe> => {\n const buildId = site.buildId ?? process.env.FOLDKIT_BUILD_ID ?? ''\n if (buildId === '') {\n throw new Error(\n 'set FOLDKIT_BUILD_ID to the deployment this build belongs to, the same value `vite build` saw',\n )\n }\n return Effect.gen(function* () {\n // Read into locals first: a call inside the thunks below would lose the\n // narrowing of a property access.\n const pathsInput = site.paths\n const specs =\n typeof pathsInput === 'function'\n ? yield* Effect.promise(() => Promise.resolve(pathsInput()))\n : pathsInput\n const files = site.files ?? 'directory'\n const configInput = site.config\n if (specs.length === 0) {\n throw new Error(\n 'foldkit-ssr: the site lists no paths: a site of nothing is a misconfigured paths',\n )\n }\n // Two specs may name one file (`/about` and `/about/`, or a `.html`\n // path beside its directory twin): `generate` sees one path at a time\n // and cannot catch it, so the collision is refused before rendering.\n const claimed = new Map<string, string>()\n for (const spec of specs) {\n const file = fileFor(pathOf(spec), files)\n const other = claimed.get(file)\n if (other !== undefined) {\n throw new Error(\n `foldkit-ssr: \"${pathOf(spec)}\" and \"${other}\" would both be written to ${file}`,\n )\n }\n claimed.set(file, pathOf(spec))\n }\n const pages: Array<BuiltPage> = []\n for (const spec of specs) {\n const path = pathOf(spec)\n const config =\n typeof configInput === 'function'\n ? yield* Effect.promise(async () => configInput(path))\n : configInput\n const [page] = yield* SSR.generate(config, site.plan, {\n buildId,\n template: site.template,\n origin: site.origin,\n paths: [path] as const,\n ...(site.flags === undefined ? {} : { flags: site.flags }),\n ...(site.head === undefined ? {} : { head: site.head }),\n })\n pages.push({\n path,\n file: fileFor(path, files),\n html: page.html,\n ...(modifiedOf(spec) === undefined ? {} : { modified: modifiedOf(spec) }),\n })\n }\n return {\n pages,\n ...(site.sitemap === true ? { sitemap: SSR.sitemap(pages, { origin: site.origin }) } : {}),\n ...(site.robots === true ? { robots: SSR.robots({ origin: site.origin }) } : {}),\n }\n })\n}\n\n/** A site description as a module exports it, for the plugin to evaluate. */\nexport interface SiteModule {\n readonly config:\n | ResumableConfig<any, any>\n | ((path: string) => ResumableConfig<any, any> | Promise<ResumableConfig<any, any>>)\n readonly plan: ResumePlan<any, any>\n readonly buildId?: string | undefined\n readonly origin: string\n readonly paths:\n ReadonlyArray<SitePath> | (() => ReadonlyArray<SitePath> | Promise<ReadonlyArray<SitePath>>)\n readonly template?: ((built: string) => string) | undefined\n readonly head?: Head | undefined\n readonly flags?: ((path: string) => unknown) | undefined\n readonly files?: 'directory' | 'flat' | undefined\n readonly sitemap?: boolean | undefined\n readonly robots?: boolean | undefined\n}\n\n/** Workspace packages resolve to their source, so the site builds as edited. */\nconst conditions = ['foldkit-plus:source']\n\n/**\n * A static site as a Vite plugin: after the client bundle is written, the\n * site module is evaluated, every path is rendered into the built shell,\n * and the pages land in the output beside the sitemap and robots text.\n * The config names the module, never application code, so nothing resolves\n * through a stale build.\n */\nexport const staticSite = (options: {\n /** The site description's module, root-relative (`/src/site.ts`), and its export. */\n readonly site: { readonly module: string; readonly export?: string | undefined }\n /** What `vite build` wrote: defaults to the resolved `build.outDir`. */\n readonly outDir?: string | undefined\n}): Plugin => {\n let outDir = options.outDir ?? 'dist'\n let root = process.cwd()\n return {\n name: 'foldkit-ssr',\n apply: 'build',\n configResolved(config) {\n // The site module resolves against the application, not this process:\n // the test runs from the workspace root while the site lives elsewhere.\n root = config.root\n // An explicit outDir reads as Vite reads it: against the root.\n outDir =\n options.outDir === undefined\n ? isAbsolute(config.build.outDir)\n ? config.build.outDir\n : resolve(config.root, config.build.outDir)\n : isAbsolute(options.outDir)\n ? options.outDir\n : resolve(config.root, options.outDir)\n },\n async closeBundle() {\n // No dev server runs during a build: one of its own, closed after.\n // `vite` loads only here, never by a page: a build without it fails\n // naming the package, not with a resolution error.\n const { createServer } = await import('vite').catch(() => {\n throw new Error(\"foldkit-ssr/vite needs the 'vite' package: add it where the build runs\")\n })\n const server = await createServer({\n configFile: false,\n root,\n logLevel: 'error',\n appType: 'custom',\n server: { middlewareMode: true, hmr: false },\n resolve: { conditions },\n ssr: { resolve: { conditions } },\n optimizeDeps: { noDiscovery: true, include: [] },\n })\n try {\n const exported = await server.ssrLoadModule(options.site.module)\n const site = exported[options.site.export ?? 'site'] as SiteModule\n if (site === undefined || site === null || typeof site !== 'object')\n throw new Error(\n `foldkit-ssr: ${options.site.module} exports no ${options.site.export ?? 'site'} site description`,\n )\n const shell = join(outDir, 'index.html')\n let built: string\n try {\n built = await readFile(shell, 'utf8')\n } catch {\n // Rollup runs closeBundle after a failed client build too: name\n // the missing shell instead of its ENOENT.\n throw new Error(\n `foldkit-ssr: no built index.html at ${shell}: the client build failed or outDir is wrong`,\n )\n }\n const result = await Effect.runPromise(\n generateStaticSite({\n ...site,\n template: site.template?.(built) ?? built,\n }),\n )\n for (const page of result.pages) {\n const file = join(outDir, page.file)\n await mkdir(dirname(file), { recursive: true })\n await writeFile(file, page.html)\n }\n if (result.sitemap !== undefined)\n await writeFile(join(outDir, 'sitemap.xml'), result.sitemap)\n if (result.robots !== undefined) await writeFile(join(outDir, 'robots.txt'), result.robots)\n console.log(\n `foldkit-ssr: generated ${result.pages.length} pages${result.sitemap === undefined ? '' : ', a sitemap'}${result.robots === undefined ? '' : ' and robots.txt'} into ${outDir}`,\n )\n } finally {\n await server.close()\n }\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AA0BA,MAAM,UAAU,SAA4B,OAAO,SAAS,WAAW,OAAO,KAAK;AACnF,MAAM,cAAc,SAClB,OAAO,SAAS,WAAW,KAAA,IAAY,KAAK;;;;;;;;AAS9C,MAAa,WAAW,MAAc,WAAyC;CAC7E,MAAM,UAAU,KAAK,QAAQ,QAAQ,EAAE,CAAC,CAAC,QA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plugin. After\n * Vite writes the client bundle, `staticSite` renders every path with\n * `SSR.generate` and writes each page where a static host serves its\n * address, with the sitemap and `robots.txt` beside them. It owns no build:\n * it runs as a `closeBundle` step on the application's own client build,\n * with the application's own template.\n *\n * The application describes its site in a module the plugin evaluates\n * through a server (workspace packages resolve to source, as the build\n * does), so `vite.config.ts` names a file, never application code.\n */\nimport { access, mkdir, readFile, writeFile } from 'node:fs/promises'\nimport { dirname, isAbsolute, join, resolve } from 'node:path'\nimport { Effect, Schema } from 'effect'\nimport type { RenderError } from 'foldkit/experimental/server'\nimport type { Plugin } from 'vite'\nimport { SSR, type Head, type ResumeUnsafe } from './index.js'\nimport type { ResumableConfig, ResumePlan } from './shared.js'\n\n/** What a page adds to its head, given what it rendered: for site descriptions. */\nexport type { Head }\n\n/** A path the site generates, with the date its sitemap names when it has one. */\nexport type SitePath = string | { readonly path: string; readonly modified?: string | undefined }\n\nconst pathOf = (spec: SitePath): string => (typeof spec === 'string' ? spec : spec.path)\nconst modifiedOf = (spec: SitePath): string | undefined =>\n typeof spec === 'string' ? undefined : spec.modified\n\n/**\n * The file a static host serves for a path. `directory` is the package's\n * own layout (`/about` as `about/index.html`); `flat` writes `about.html`,\n * for hosts with clean addresses and no directory indexes. `generate`\n * refuses what is not servable (a query, a fragment, an unresolvable\n * address) before this maps it, so this maps and never validates.\n */\nexport const fileFor = (path: string, layout: 'directory' | 'flat'): string => {\n const trimmed = path.replace(/^\\/+/, '').replace(/\\/+$/, '')\n if (trimmed === '') return 'index.html'\n if (layout === 'flat') return trimmed.endsWith('.html') ? trimmed : `${trimmed}.html`\n return trimmed.endsWith('.html') ? trimmed : `${trimmed}/index.html`\n}\n\n/**\n * What a static site is: everything `SSR.generate` takes, plus where its\n * pages land. `config` may read the path (a site whose Model is prepared\n * per page satisfies and returns its own config for it); `paths` may close\n * over what the site serves (a thunk that seeds and lists, evaluated when\n * the build runs). `template` is the built shell the pages are rendered\n * into; `files` is the host's layout; `sitemap` and `robots` write their\n * files from the generated pages; `emit` adds files of its own made from them.\n */\nexport interface StaticSite<\n Model,\n Fields extends Schema.Struct.Fields,\n Message,\n // Unconstrained on purpose: a site's config carries its own services (a\n // Remote layer, flags), which no bound here could name without threading\n // the whole service graph through. The narrowed call still checks: a\n // config that is not a config or a function of a path fails where used.\n Resolved = ResumableConfig<Model, Message>,\n> {\n readonly config: Resolved | ((path: string) => Resolved | Promise<Resolved>)\n readonly plan: ResumePlan<Model, Fields>\n readonly buildId?: string | undefined\n readonly origin: string\n readonly paths:\n | ReadonlyArray<SitePath>\n | (() => ReadonlyArray<SitePath> | Promise<ReadonlyArray<SitePath>>)\n readonly template: string\n readonly head?: Head | undefined\n readonly flags?: ((path: string) => unknown) | undefined\n readonly files?: 'directory' | 'flat' | undefined\n readonly sitemap?: boolean | undefined\n readonly robots?: boolean | undefined\n /**\n * Files made from the generated pages, written beside them: what the pages\n * reference and the build must also serve, such as the image variants\n * their `srcset`s name (`foldkit-media`'s `materialize`).\n */\n readonly emit?:\n | ((pages: ReadonlyArray<BuiltPage>) => Promise<ReadonlyArray<EmittedFile>>)\n | undefined\n}\n\n/** A file `emit` adds: its path in the output, and its contents. */\nexport interface EmittedFile {\n readonly file: string\n readonly contents: Uint8Array | string\n}\n\n/** One generated page, with the file the host serves it from. */\nexport interface BuiltPage {\n readonly path: string\n readonly file: string\n readonly html: string\n readonly modified?: string | undefined\n}\n\n/** What a static site build produced: its pages, and its sitemap and robots text. */\nexport interface BuiltSite {\n readonly pages: ReadonlyArray<BuiltPage>\n readonly sitemap?: string | undefined\n readonly robots?: string | undefined\n readonly emitted: ReadonlyArray<EmittedFile>\n}\n\n/**\n * The files `emit` returned, refused when one would land outside the output\n * (an absolute path, a `..`) or on a file the build writes itself: a page,\n * the sitemap, robots, or another emitted file.\n */\nexport const checkEmitted = (\n emitted: ReadonlyArray<EmittedFile>,\n taken: ReadonlyArray<string>,\n): ReadonlyArray<EmittedFile> => {\n const claimed = new Set(taken)\n for (const { file } of emitted) {\n const segments = file.split(/[\\\\/]/)\n if (file === '' || /^([a-zA-Z]:|[\\\\/])/.test(file) || segments.includes('..')) {\n throw new Error(`foldkit-ssr: emit returned \"${file}\", which is not a path inside the output`)\n }\n if (claimed.has(file)) {\n throw new Error(`foldkit-ssr: emit returned \"${file}\", which the build already writes`)\n }\n claimed.add(file)\n }\n return emitted\n}\n\n/**\n * Renders a static site: every path through `SSR.generate`, one page per\n * path in order, with the sitemap and robots text the options ask for. A\n * build id must never be a secret, and two deployments must never share\n * one; empty is refused with the deployment's name missing.\n */\nexport const generateStaticSite = <Model, Fields extends Schema.Struct.Fields, Message = any>(\n site: StaticSite<Model, Fields, Message>,\n): Effect.Effect<BuiltSite, RenderError | ResumeUnsafe> => {\n const buildId = site.buildId ?? process.env.FOLDKIT_BUILD_ID ?? ''\n if (buildId === '') {\n throw new Error(\n 'set FOLDKIT_BUILD_ID to the deployment this build belongs to, the same value `vite build` saw',\n )\n }\n return Effect.gen(function* () {\n // Read into locals first: a call inside the thunks below would lose the\n // narrowing of a property access.\n const pathsInput = site.paths\n const specs =\n typeof pathsInput === 'function'\n ? yield* Effect.promise(() => Promise.resolve(pathsInput()))\n : pathsInput\n const files = site.files ?? 'directory'\n const configInput = site.config\n if (specs.length === 0) {\n throw new Error(\n 'foldkit-ssr: the site lists no paths: a site of nothing is a misconfigured paths',\n )\n }\n // Two specs may name one file (`/about` and `/about/`, or a `.html`\n // path beside its directory twin): `generate` sees one path at a time\n // and cannot catch it, so the collision is refused before rendering.\n const claimed = new Map<string, string>()\n for (const spec of specs) {\n const file = fileFor(pathOf(spec), files)\n const other = claimed.get(file)\n if (other !== undefined) {\n throw new Error(\n `foldkit-ssr: \"${pathOf(spec)}\" and \"${other}\" would both be written to ${file}`,\n )\n }\n claimed.set(file, pathOf(spec))\n }\n const pages: Array<BuiltPage> = []\n for (const spec of specs) {\n const path = pathOf(spec)\n const config =\n typeof configInput === 'function'\n ? yield* Effect.promise(async () => configInput(path))\n : configInput\n const [page] = yield* SSR.generate(config, site.plan, {\n buildId,\n template: site.template,\n origin: site.origin,\n paths: [path] as const,\n ...(site.flags === undefined ? {} : { flags: site.flags }),\n ...(site.head === undefined ? {} : { head: site.head }),\n })\n pages.push({\n path,\n file: fileFor(path, files),\n html: page.html,\n ...(modifiedOf(spec) === undefined ? {} : { modified: modifiedOf(spec) }),\n })\n }\n const emitInput = site.emit\n const emitted =\n emitInput === undefined\n ? []\n : checkEmitted(yield* Effect.promise(() => emitInput(pages)), [\n ...pages.map(page => page.file),\n ...(site.sitemap === true ? ['sitemap.xml'] : []),\n ...(site.robots === true ? ['robots.txt'] : []),\n ])\n return {\n pages,\n ...(site.sitemap === true ? { sitemap: SSR.sitemap(pages, { origin: site.origin }) } : {}),\n ...(site.robots === true ? { robots: SSR.robots({ origin: site.origin }) } : {}),\n emitted,\n }\n })\n}\n\n/**\n * Writes what `emit` returned into `outDir`, refusing a file the client\n * build already wrote there: a file from `public/` is not emit's to replace.\n */\nexport const writeEmitted = async (\n outDir: string,\n emitted: ReadonlyArray<EmittedFile>,\n): Promise<void> => {\n for (const { file, contents } of emitted) {\n const target = join(outDir, file)\n if (\n await access(target).then(\n () => true,\n () => false,\n )\n ) {\n throw new Error(`foldkit-ssr: emit returned \"${file}\", which the client build already wrote`)\n }\n await mkdir(dirname(target), { recursive: true })\n await writeFile(target, contents)\n }\n}\n\n/** A site description as a module exports it, for the plugin to evaluate. */\nexport interface SiteModule {\n readonly config:\n | ResumableConfig<any, any>\n | ((path: string) => ResumableConfig<any, any> | Promise<ResumableConfig<any, any>>)\n readonly plan: ResumePlan<any, any>\n readonly buildId?: string | undefined\n readonly origin: string\n readonly paths:\n | ReadonlyArray<SitePath>\n | (() => ReadonlyArray<SitePath> | Promise<ReadonlyArray<SitePath>>)\n readonly template?: ((built: string) => string) | undefined\n readonly head?: Head | undefined\n readonly flags?: ((path: string) => unknown) | undefined\n readonly files?: 'directory' | 'flat' | undefined\n readonly sitemap?: boolean | undefined\n readonly robots?: boolean | undefined\n readonly emit?:\n | ((pages: ReadonlyArray<BuiltPage>) => Promise<ReadonlyArray<EmittedFile>>)\n | undefined\n}\n\n/** Workspace packages resolve to their source, so the site builds as edited. */\nconst conditions = ['foldkit-plus:source']\n\n/**\n * A static site as a Vite plugin: after the client bundle is written, the\n * site module is evaluated, every path is rendered into the built shell,\n * and the pages land in the output beside the sitemap and robots text.\n * The config names the module, never application code, so nothing resolves\n * through a stale build.\n */\nexport const staticSite = (options: {\n /** The site description's module, root-relative (`/src/site.ts`), and its export. */\n readonly site: { readonly module: string; readonly export?: string | undefined }\n /** What `vite build` wrote: defaults to the resolved `build.outDir`. */\n readonly outDir?: string | undefined\n}): Plugin => {\n let outDir = options.outDir ?? 'dist'\n let root = process.cwd()\n return {\n name: 'foldkit-ssr',\n apply: 'build',\n configResolved(config) {\n // The site module resolves against the application, not this process:\n // the test runs from the workspace root while the site lives elsewhere.\n root = config.root\n // An explicit outDir reads as Vite reads it: against the root.\n outDir =\n options.outDir === undefined\n ? isAbsolute(config.build.outDir)\n ? config.build.outDir\n : resolve(config.root, config.build.outDir)\n : isAbsolute(options.outDir)\n ? options.outDir\n : resolve(config.root, options.outDir)\n },\n async closeBundle() {\n // No dev server runs during a build: one of its own, closed after.\n // `vite` loads only here, never by a page: a build without it fails\n // naming the package, not with a resolution error.\n const { createServer } = await import('vite').catch(() => {\n throw new Error(\"foldkit-ssr/vite needs the 'vite' package: add it where the build runs\")\n })\n const server = await createServer({\n configFile: false,\n root,\n logLevel: 'error',\n appType: 'custom',\n server: { middlewareMode: true, hmr: false },\n resolve: { conditions },\n ssr: { resolve: { conditions } },\n optimizeDeps: { noDiscovery: true, include: [] },\n })\n try {\n const exported = await server.ssrLoadModule(options.site.module)\n const site = exported[options.site.export ?? 'site'] as SiteModule\n if (site === undefined || site === null || typeof site !== 'object')\n throw new Error(\n `foldkit-ssr: ${options.site.module} exports no ${options.site.export ?? 'site'} site description`,\n )\n const shell = join(outDir, 'index.html')\n let built: string\n try {\n built = await readFile(shell, 'utf8')\n } catch {\n // Rollup runs closeBundle after a failed client build too: name\n // the missing shell instead of its ENOENT.\n throw new Error(\n `foldkit-ssr: no built index.html at ${shell}: the client build failed or outDir is wrong`,\n )\n }\n const result = await Effect.runPromise(\n generateStaticSite({\n ...site,\n template: site.template?.(built) ?? built,\n }),\n )\n for (const page of result.pages) {\n const file = join(outDir, page.file)\n await mkdir(dirname(file), { recursive: true })\n await writeFile(file, page.html)\n }\n if (result.sitemap !== undefined)\n await writeFile(join(outDir, 'sitemap.xml'), result.sitemap)\n if (result.robots !== undefined) await writeFile(join(outDir, 'robots.txt'), result.robots)\n await writeEmitted(outDir, result.emitted)\n console.log(\n `foldkit-ssr: generated ${result.pages.length} pages${result.sitemap === undefined ? '' : ', a sitemap'}${result.robots === undefined ? '' : ' and robots.txt'}${result.emitted.length === 0 ? '' : ` and ${result.emitted.length} emitted files`} into ${outDir}`,\n )\n } finally {\n await server.close()\n }\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AA0BA,MAAM,UAAU,SAA4B,OAAO,SAAS,WAAW,OAAO,KAAK;AACnF,MAAM,cAAc,SAClB,OAAO,SAAS,WAAW,KAAA,IAAY,KAAK;;;;;;;;AAS9C,MAAa,WAAW,MAAc,WAAyC;CAC7E,MAAM,UAAU,KAAK,QAAQ,QAAQ,EAAE,CAAC,CAAC,QAAQ,QAAQ,EAAE;CAC3D,IAAI,YAAY,IAAI,OAAO;CAC3B,IAAI,WAAW,QAAQ,OAAO,QAAQ,SAAS,OAAO,IAAI,UAAU,GAAG,QAAQ;CAC/E,OAAO,QAAQ,SAAS,OAAO,IAAI,UAAU,GAAG,QAAQ;AAC1D;;;;;;AAuEA,MAAa,gBACX,SACA,UAC+B;CAC/B,MAAM,UAAU,IAAI,IAAI,KAAK;CAC7B,KAAK,MAAM,EAAE,UAAU,SAAS;EAC9B,MAAM,WAAW,KAAK,MAAM,OAAO;EACnC,IAAI,SAAS,MAAM,qBAAqB,KAAK,IAAI,KAAK,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/B,MAAM,OAAO,KAAK,QAAQ,KAAK,IAAI;KACnC,MAAM,MAAM,QAAQ,IAAI,GAAG,EAAE,WAAW,KAAK,CAAC;KAC9C,MAAM,UAAU,MAAM,KAAK,IAAI;IACjC;IACA,IAAI,OAAO,YAAY,KAAA,GACrB,MAAM,UAAU,KAAK,QAAQ,aAAa,GAAG,OAAO,OAAO;IAC7D,IAAI,OAAO,WAAW,KAAA,GAAW,MAAM,UAAU,KAAK,QAAQ,YAAY,GAAG,OAAO,MAAM;IAC1F,MAAM,aAAa,QAAQ,OAAO,OAAO;IACzC,QAAQ,IACN,0BAA0B,OAAO,MAAM,OAAO,QAAQ,OAAO,YAAY,KAAA,IAAY,KAAK,gBAAgB,OAAO,WAAW,KAAA,IAAY,KAAK,oBAAoB,OAAO,QAAQ,WAAW,IAAI,KAAK,QAAQ,OAAO,QAAQ,OAAO,gBAAgB,QAAQ,QAC5P;GACF,UAAU;IACR,MAAM,OAAO,MAAM;GACrB;EACF;CACF;AACF"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "foldkit-ssr",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.8.0",
|
|
4
4
|
"description": "Server rendering for Foldkit Plus: render once on the server, hand the Model over, and hydrate without rerunning init.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"foldkit",
|
|
@@ -64,8 +64,8 @@
|
|
|
64
64
|
"tsdown": "^0.23.1",
|
|
65
65
|
"typescript": "7.0.2",
|
|
66
66
|
"vite": "8.3.4",
|
|
67
|
-
"foldkit-entity": "0.10.0",
|
|
68
67
|
"foldkit-bundle": "0.8.0",
|
|
68
|
+
"foldkit-entity": "0.10.0",
|
|
69
69
|
"foldkit-mirror": "0.6.1",
|
|
70
70
|
"foldkit-remote": "0.18.0"
|
|
71
71
|
},
|