@crombolo/server 0.36.2 → 0.37.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/package.json +13 -12
- package/src/adapters/health.ts +23 -0
- package/src/adapters/template-files.ts +6 -1
- package/src/bundles.ts +137 -406
- package/src/components.ts +42 -6
- package/src/config.ts +81 -2
- package/src/index.ts +4 -0
- package/src/islands.ts +197 -0
- package/src/middleware.ts +236 -0
- package/src/ports.ts +3 -0
- package/src/routes.ts +420 -0
- package/src/server.ts +562 -60
- package/src/settings.ts +31 -0
- package/src/site-services.ts +99 -0
- package/src/status-pages.ts +128 -0
- package/src/webhook-files.ts +17 -0
- package/src/webhooks.ts +70 -10
package/src/components.ts
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs'
|
|
2
2
|
import { join, relative, resolve, sep } from 'node:path'
|
|
3
|
+
import { isClientModule } from '@crombolo/render'
|
|
4
|
+
import { isServerOnly } from './islands.ts'
|
|
3
5
|
|
|
4
6
|
/**
|
|
5
7
|
* A `.tsx` under the site's `components/` directory.
|
|
@@ -24,6 +26,9 @@ export interface ComponentFile {
|
|
|
24
26
|
|
|
25
27
|
const SOURCE = /\.(tsx|jsx)$/
|
|
26
28
|
|
|
29
|
+
/** Folders whose files are one component each, where a `page.tsx` is just a component named page. */
|
|
30
|
+
const FLAT_FOLDERS = new Set(['blocks', 'emails'])
|
|
31
|
+
|
|
27
32
|
/** An alias that stays inside the root: no climbing, no absolute path, no drive. */
|
|
28
33
|
export function isSafeAlias(alias: string): boolean {
|
|
29
34
|
if (alias.length === 0 || alias.startsWith('/') || alias.includes('\\')) return false
|
|
@@ -47,12 +52,21 @@ export function listComponents(root: string): ComponentFile[] {
|
|
|
47
52
|
}
|
|
48
53
|
}
|
|
49
54
|
walk(root)
|
|
50
|
-
|
|
55
|
+
// `x.tsx` wins over `x/page.tsx`, as it does when rendering.
|
|
56
|
+
const seen = new Set<string>()
|
|
57
|
+
return out
|
|
58
|
+
.sort((a, b) => a.alias.localeCompare(b.alias) || a.path.length - b.path.length)
|
|
59
|
+
.filter((file) => !seen.has(file.alias) && Boolean(seen.add(file.alias)))
|
|
51
60
|
}
|
|
52
61
|
|
|
53
|
-
/**
|
|
62
|
+
/**
|
|
63
|
+
* The alias a file answers to: its path under the root, without the extension.
|
|
64
|
+
* A folder's `page.tsx` answers to the folder, as a Next.js route does (story 206).
|
|
65
|
+
*/
|
|
54
66
|
export function aliasOf(root: string, path: string): string {
|
|
55
|
-
|
|
67
|
+
const alias = relative(root, path).split(sep).join('/').replace(SOURCE, '')
|
|
68
|
+
const folder = alias.endsWith('/page') ? alias.slice(0, -'/page'.length) : undefined
|
|
69
|
+
return folder && !FLAT_FOLDERS.has(folder) ? folder : alias
|
|
56
70
|
}
|
|
57
71
|
|
|
58
72
|
export interface ComponentProblem {
|
|
@@ -124,6 +138,18 @@ export async function checkComponents(options: {
|
|
|
124
138
|
for (const found of unawaitedMedia(source))
|
|
125
139
|
problems.push({ file: `${where}:${found.line}`, message: found.message })
|
|
126
140
|
|
|
141
|
+
// Browser code (story 209): never imported here, where React or Vue would
|
|
142
|
+
// load into the CMS, and held to the boundary instead.
|
|
143
|
+
if (isClientModule(source) || component.alias.startsWith('client/')) {
|
|
144
|
+
for (const specifier of transpiler.scanImports(source))
|
|
145
|
+
if (isServerOnly(specifier.path))
|
|
146
|
+
problems.push({
|
|
147
|
+
file: where,
|
|
148
|
+
message: `imports ${specifier.path}, which only runs on the server. Code that runs in the browser cannot use it.`,
|
|
149
|
+
})
|
|
150
|
+
continue
|
|
151
|
+
}
|
|
152
|
+
|
|
127
153
|
try {
|
|
128
154
|
// A query does not bust Bun's module cache, so a path imported once in
|
|
129
155
|
// this process answers from the registry. Harmless: the CLI checks each
|
|
@@ -248,10 +274,20 @@ async function checkTypes(siteDir: string): Promise<ComponentCheckReport['types'
|
|
|
248
274
|
return { checked: true, problems: lines }
|
|
249
275
|
}
|
|
250
276
|
|
|
251
|
-
/** Where a component with this alias lives
|
|
252
|
-
export function componentFileFor(
|
|
277
|
+
/** Where a component with this alias lives: `<alias>.tsx`, or `<alias>/page.tsx` as a folder. */
|
|
278
|
+
export function componentFileFor(
|
|
279
|
+
root: string,
|
|
280
|
+
alias: string,
|
|
281
|
+
options: { folder?: boolean } = {},
|
|
282
|
+
): string {
|
|
253
283
|
if (!isSafeAlias(alias)) throw new Error(`"${alias}" is not a path inside components/`)
|
|
254
|
-
|
|
284
|
+
if (
|
|
285
|
+
!options.folder &&
|
|
286
|
+
existsSync(join(root, alias, 'page.tsx')) &&
|
|
287
|
+
!existsSync(join(root, `${alias}.tsx`))
|
|
288
|
+
)
|
|
289
|
+
return join(root, alias, 'page.tsx')
|
|
290
|
+
return options.folder ? join(root, alias, 'page.tsx') : join(root, `${alias}.tsx`)
|
|
255
291
|
}
|
|
256
292
|
|
|
257
293
|
/** What an e-mail template looks like: a default export over `EmailProps`. */
|
package/src/config.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { hostname, tmpdir } from 'node:os'
|
|
2
2
|
import { join, resolve } from 'node:path'
|
|
3
3
|
import type { DeliveryApiOptions } from '@crombolo/api-delivery'
|
|
4
|
+
import type { MiddlewareChain, SiteRoute } from '@crombolo/common'
|
|
4
5
|
import {
|
|
5
6
|
DEFAULT_BACKOFFICE_PATH,
|
|
6
7
|
DEFAULT_PASSWORD_CONFIGURATION,
|
|
@@ -9,7 +10,10 @@ import {
|
|
|
9
10
|
import {
|
|
10
11
|
type CacheOptions,
|
|
11
12
|
DEFAULT_RENDER_TIMEOUT_MS,
|
|
13
|
+
type PublishedContent,
|
|
12
14
|
type RedirectRule,
|
|
15
|
+
type RequestMember,
|
|
16
|
+
type SiteServices,
|
|
13
17
|
type SnapshotLimits,
|
|
14
18
|
} from '@crombolo/render'
|
|
15
19
|
import type { ServerBundle } from './bundles.ts'
|
|
@@ -192,6 +196,22 @@ export interface CromboloConfig {
|
|
|
192
196
|
* template error and its `signal` aborts; 0 for no limit.
|
|
193
197
|
*/
|
|
194
198
|
renderTimeoutMs: number
|
|
199
|
+
/**
|
|
200
|
+
* The site's middleware, by stage (story 210): code it imports and lists,
|
|
201
|
+
* each run in the order given. docs/rendering.md, "Middleware".
|
|
202
|
+
*/
|
|
203
|
+
middleware?: MiddlewareChain<SiteServices, PublishedContent, RequestMember>
|
|
204
|
+
/** How long the whole middleware chain may take, crombolo's own work aside; 0 for no limit. */
|
|
205
|
+
middlewareTimeoutMs: number
|
|
206
|
+
/**
|
|
207
|
+
* The site's own endpoints (story 211), at their paths, ahead of content
|
|
208
|
+
* finding. docs/rendering.md, "Route handlers".
|
|
209
|
+
*/
|
|
210
|
+
routes?: SiteRoute<SiteServices, RequestMember>[]
|
|
211
|
+
/** How long a route handler may take before it answers 504; 0 for no limit. */
|
|
212
|
+
routeTimeoutMs: number
|
|
213
|
+
/** Requests a minute each caller may make to the site's routes, on each server; 0 for no limit. */
|
|
214
|
+
routeRateLimitPerMinute: number
|
|
195
215
|
/** Where `schema/*.toml` lives; sync is skipped when the directory is absent. */
|
|
196
216
|
schemaDir: string
|
|
197
217
|
/** Supplied at deploy time (CROMBOLO_SCHEMA_REVISION); orders deploys within one schema version. */
|
|
@@ -361,6 +381,15 @@ export interface CromboloConfig {
|
|
|
361
381
|
* answers on. Every field may also be set in the backoffice, which wins.
|
|
362
382
|
*/
|
|
363
383
|
seo: SeoConfig
|
|
384
|
+
/**
|
|
385
|
+
* Pages in the content tree, by path, that answer a status a page's code ends
|
|
386
|
+
* with (story 206): `notFound`, `unauthorized`, and `error` for the rest.
|
|
387
|
+
*/
|
|
388
|
+
pages?: StatusPagesConfig
|
|
389
|
+
/** Whether a server error shows its message and stack. CROMBOLO_SHOW_ERROR_DETAILS. */
|
|
390
|
+
errors: ErrorsConfig
|
|
391
|
+
/** Where `'use client'` islands' browser code comes from (story 209): built here, unless Vite builds it. */
|
|
392
|
+
islands?: IslandsConfig
|
|
364
393
|
/**
|
|
365
394
|
* Umbraco's Delivery API (`docs/delivery-api.md`): off unless enabled.
|
|
366
395
|
* `CROMBOLO_DELIVERY_API`, `CROMBOLO_DELIVERY_API_KEY`,
|
|
@@ -466,6 +495,9 @@ export const DEFAULTS = {
|
|
|
466
495
|
componentsDir: 'components',
|
|
467
496
|
componentsCacheDir: join('.crombolo', 'components'),
|
|
468
497
|
renderTimeoutMs: DEFAULT_RENDER_TIMEOUT_MS,
|
|
498
|
+
middlewareTimeoutMs: 2_000,
|
|
499
|
+
routeTimeoutMs: 10_000,
|
|
500
|
+
routeRateLimitPerMinute: 2_000,
|
|
469
501
|
schemaDir: 'schema',
|
|
470
502
|
schemaRevision: '0',
|
|
471
503
|
mediaDir: 'media',
|
|
@@ -509,6 +541,38 @@ export interface NotFoundRule {
|
|
|
509
541
|
culture?: string
|
|
510
542
|
}
|
|
511
543
|
|
|
544
|
+
/** A status page for one hostname or language; the most specific match wins. */
|
|
545
|
+
export interface StatusPageRule {
|
|
546
|
+
/** The page's path in the content tree, as a visitor would ask for it. */
|
|
547
|
+
path: string
|
|
548
|
+
host?: string
|
|
549
|
+
culture?: string
|
|
550
|
+
}
|
|
551
|
+
|
|
552
|
+
/** A status page: a path, or rules choosing one per hostname or language. */
|
|
553
|
+
export type StatusPage = string | StatusPageRule[]
|
|
554
|
+
|
|
555
|
+
export interface StatusPagesConfig {
|
|
556
|
+
/** 404; wins over `seo.notFoundPage`. */
|
|
557
|
+
notFound?: StatusPage
|
|
558
|
+
/** 401. */
|
|
559
|
+
unauthorized?: StatusPage
|
|
560
|
+
/** 400, 403, 410, 422 and 500. */
|
|
561
|
+
error?: StatusPage
|
|
562
|
+
}
|
|
563
|
+
|
|
564
|
+
export interface IslandsConfig {
|
|
565
|
+
/** A Vite manifest, relative to the site: its build is served, and Crombolo bundles nothing. */
|
|
566
|
+
manifest?: string
|
|
567
|
+
/** A running Vite dev server, such as `http://localhost:5173`, to load islands from in development. */
|
|
568
|
+
devServer?: string
|
|
569
|
+
}
|
|
570
|
+
|
|
571
|
+
export interface ErrorsConfig {
|
|
572
|
+
/** A server error's message, source and stack on the error page. Default: in development only. */
|
|
573
|
+
showDetails: boolean
|
|
574
|
+
}
|
|
575
|
+
|
|
512
576
|
export interface SeoConfig {
|
|
513
577
|
/** Serve `/sitemap.xml`. Default true; CROMBOLO_SITEMAP. */
|
|
514
578
|
sitemap?: boolean
|
|
@@ -522,7 +586,7 @@ export interface SeoConfig {
|
|
|
522
586
|
titleSuffix?: string
|
|
523
587
|
/** Shown when a page without its own image is shared: an address, or a media item's key. */
|
|
524
588
|
defaultImage?: string
|
|
525
|
-
/** A page key, or rules choosing one per hostname or language. */
|
|
589
|
+
/** A page key, or rules choosing one per hostname or language; `pages.notFound` wins. */
|
|
526
590
|
notFoundPage?: string | NotFoundRule[]
|
|
527
591
|
/**
|
|
528
592
|
* Where visitors see the site, when that is not here — an app on another host
|
|
@@ -597,6 +661,13 @@ export function loadConfig(
|
|
|
597
661
|
: {}),
|
|
598
662
|
},
|
|
599
663
|
renderTimeoutMs: Number(setting('CROMBOLO_RENDER_TIMEOUT_MS') ?? DEFAULTS.renderTimeoutMs),
|
|
664
|
+
middlewareTimeoutMs: Number(
|
|
665
|
+
setting('CROMBOLO_MIDDLEWARE_TIMEOUT_MS') ?? DEFAULTS.middlewareTimeoutMs,
|
|
666
|
+
),
|
|
667
|
+
routeTimeoutMs: Number(setting('CROMBOLO_ROUTE_TIMEOUT_MS') ?? DEFAULTS.routeTimeoutMs),
|
|
668
|
+
routeRateLimitPerMinute: Number(
|
|
669
|
+
setting('CROMBOLO_ROUTE_RATE_LIMIT_PER_MINUTE') ?? DEFAULTS.routeRateLimitPerMinute,
|
|
670
|
+
),
|
|
600
671
|
schemaDir: setting('CROMBOLO_SCHEMA_DIR') ?? DEFAULTS.schemaDir,
|
|
601
672
|
schemaRevision: setting('CROMBOLO_SCHEMA_REVISION') ?? DEFAULTS.schemaRevision,
|
|
602
673
|
nodeId: setting('CROMBOLO_NODE_ID') ?? `${hostname()}:${process.pid}`,
|
|
@@ -682,6 +753,8 @@ export function loadConfig(
|
|
|
682
753
|
applyBundleContentOnInstall: setting('CROMBOLO_APPLY_BUNDLE_CONTENT') !== 'false',
|
|
683
754
|
// Resolved again below, once it is known whether a store was configured.
|
|
684
755
|
runtimeInstalls: setting('CROMBOLO_RUNTIME_INSTALLS') !== 'false',
|
|
756
|
+
// Resolved again below, once it is known whether this is development.
|
|
757
|
+
errors: { showDetails: envFlag(setting('CROMBOLO_SHOW_ERROR_DETAILS')) ?? false },
|
|
685
758
|
seo: stripUndefined({
|
|
686
759
|
sitemap: envFlag(setting('CROMBOLO_SITEMAP')),
|
|
687
760
|
indexable: envFlag(setting('CROMBOLO_INDEXABLE')),
|
|
@@ -734,6 +807,12 @@ export function loadConfig(
|
|
|
734
807
|
// Field by field, so a site setting its title suffix keeps the environment's switches.
|
|
735
808
|
merged.seo = { ...fromEnv.seo, ...stripUndefined(overrides.seo ?? {}) }
|
|
736
809
|
merged.remote = { ...fromEnv.remote, ...stripUndefined(overrides.remote ?? {}) }
|
|
810
|
+
merged.errors = {
|
|
811
|
+
showDetails:
|
|
812
|
+
overrides.errors?.showDetails ??
|
|
813
|
+
envFlag(setting('CROMBOLO_SHOW_ERROR_DETAILS')) ??
|
|
814
|
+
merged.development,
|
|
815
|
+
}
|
|
737
816
|
checkApiClient(merged.apiClient)
|
|
738
817
|
checkHost(merged.host)
|
|
739
818
|
// The key itself is refused, so a config left over from before says so rather
|
|
@@ -839,7 +918,7 @@ export function describeDatabase(
|
|
|
839
918
|
}
|
|
840
919
|
}
|
|
841
920
|
|
|
842
|
-
export const VERSION = '0.
|
|
921
|
+
export const VERSION = '0.37.0'
|
|
843
922
|
|
|
844
923
|
/** A whole number of seconds from the environment; undefined when unset or not one. */
|
|
845
924
|
/** A positive number from a setting, else the default. */
|
package/src/index.ts
CHANGED
|
@@ -63,6 +63,7 @@ export * from './identity-provider-overrides.ts'
|
|
|
63
63
|
export * from './identity-providers.ts'
|
|
64
64
|
export * from './image-metadata.ts'
|
|
65
65
|
export * from './imaging.ts'
|
|
66
|
+
export * from './islands.ts'
|
|
66
67
|
export * from './jobs.ts'
|
|
67
68
|
export * from './listen.ts'
|
|
68
69
|
export * from './log-expressions.ts'
|
|
@@ -75,6 +76,7 @@ export * from './media-store.ts'
|
|
|
75
76
|
export * from './media-store-azure.ts'
|
|
76
77
|
export * from './media-store-s3.ts'
|
|
77
78
|
export * from './member-auth.ts'
|
|
79
|
+
export * from './middleware.ts'
|
|
78
80
|
export * from './models-builder.ts'
|
|
79
81
|
export * from './no-nodes.ts'
|
|
80
82
|
export * from './oembed.ts'
|
|
@@ -84,6 +86,7 @@ export * from './redirects.ts'
|
|
|
84
86
|
export * from './remote.ts'
|
|
85
87
|
export * from './remote-credentials.ts'
|
|
86
88
|
export * from './remote-media.ts'
|
|
89
|
+
export * from './routes.ts'
|
|
87
90
|
export * from './schema.ts'
|
|
88
91
|
export * from './schema-store.ts'
|
|
89
92
|
export * from './secrets.ts'
|
|
@@ -97,6 +100,7 @@ export * from './site-file.ts'
|
|
|
97
100
|
export * from './site-replace.ts'
|
|
98
101
|
export * from './site-sections.ts'
|
|
99
102
|
export * from './status.ts'
|
|
103
|
+
export * from './status-pages.ts'
|
|
100
104
|
export * from './tar.ts'
|
|
101
105
|
export * from './transfer-dashboard.ts'
|
|
102
106
|
export * from './two-factor.ts'
|
package/src/islands.ts
ADDED
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The browser code for a generation's islands (story 209), built when the
|
|
3
|
+
* generation is taken and served beside it, so a page and its islands always
|
|
4
|
+
* match. Or, with `islands.manifest`, the files a site's own Vite build wrote.
|
|
5
|
+
* docs/rendering.md, "Islands".
|
|
6
|
+
*/
|
|
7
|
+
import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs'
|
|
8
|
+
import { dirname, join, relative, resolve, sep } from 'node:path'
|
|
9
|
+
import { ISLANDS_DIR, ISLANDS_PATH, type IslandManifest } from '@crombolo/render'
|
|
10
|
+
|
|
11
|
+
/** What a client module may not import: code that only runs on the server. */
|
|
12
|
+
const SERVER_ONLY =
|
|
13
|
+
/^(@crombolo\/(crombolo|render|server|core|data|content|auth|schema|transfer|api-delivery|api-management)(\/.*)?|node:.*|bun(:.*)?)$/
|
|
14
|
+
/** Whether a client module importing this would pull server code into the browser. */
|
|
15
|
+
export const isServerOnly = (specifier: string): boolean =>
|
|
16
|
+
SERVER_ONLY.test(specifier) && specifier !== BROWSER_ENTRY
|
|
17
|
+
|
|
18
|
+
/** The one part of `@crombolo/crombolo` a browser runs: React's mount. */
|
|
19
|
+
const BROWSER_ENTRY = '@crombolo/crombolo/islands-react'
|
|
20
|
+
|
|
21
|
+
const toKey = (path: string) => path.split(sep).join('/')
|
|
22
|
+
const scanner = new Bun.Transpiler({ loader: 'tsx' })
|
|
23
|
+
|
|
24
|
+
/** `components/client/<name>.ts`: modules an `<Island>` mounts. */
|
|
25
|
+
function mountModules(dir: string): string[] {
|
|
26
|
+
const root = join(dir, 'client')
|
|
27
|
+
if (!existsSync(root)) return []
|
|
28
|
+
const out: string[] = []
|
|
29
|
+
const walk = (current: string) => {
|
|
30
|
+
for (const entry of readdirSync(current, { withFileTypes: true })) {
|
|
31
|
+
const path = join(current, entry.name)
|
|
32
|
+
if (entry.isDirectory()) walk(path)
|
|
33
|
+
else if (/\.[jt]sx?$/.test(entry.name)) out.push(toKey(relative(dir, path)))
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
walk(root)
|
|
37
|
+
return out
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** `client/species-map.ts` as an `<Island>` names it: `client/species-map`. */
|
|
41
|
+
const moduleId = (key: string, client: Set<string>) =>
|
|
42
|
+
client.has(key) ? key : key.replace(/\.[jt]sx?$/, '')
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Bundles a generation's client modules and `<Island>` modules with React's
|
|
46
|
+
* mount, into `<generation>/.islands/out/` with `manifest.json`. Throws with
|
|
47
|
+
* every problem, each naming its file, when the build fails.
|
|
48
|
+
*/
|
|
49
|
+
export async function buildIslands(generation: {
|
|
50
|
+
dir: string
|
|
51
|
+
hash: string
|
|
52
|
+
transformed: string[]
|
|
53
|
+
development: boolean
|
|
54
|
+
}): Promise<IslandManifest | undefined> {
|
|
55
|
+
const { dir, hash } = generation
|
|
56
|
+
const client = new Set(generation.transformed)
|
|
57
|
+
const mounts = mountModules(dir)
|
|
58
|
+
if (client.size === 0 && mounts.length === 0) return undefined
|
|
59
|
+
const islands = join(dir, ISLANDS_DIR)
|
|
60
|
+
const out = join(islands, 'out')
|
|
61
|
+
if (existsSync(join(out, 'manifest.json')))
|
|
62
|
+
return JSON.parse(readFileSync(join(out, 'manifest.json'), 'utf8')) as IslandManifest
|
|
63
|
+
mkdirSync(islands, { recursive: true })
|
|
64
|
+
const reactEntry = join(islands, 'react-mount.ts')
|
|
65
|
+
if (client.size > 0) writeFileSync(reactEntry, `export { mount } from '${BROWSER_ENTRY}'\n`)
|
|
66
|
+
|
|
67
|
+
const entries = [
|
|
68
|
+
...[...client].map((key) => join(dir, ...key.split('/'))),
|
|
69
|
+
...mounts.map((key) => join(dir, ...key.split('/'))),
|
|
70
|
+
...(client.size > 0 ? [reactEntry] : []),
|
|
71
|
+
]
|
|
72
|
+
const keyOf = (path: string) => toKey(relative(dir, path))
|
|
73
|
+
const refused: string[] = []
|
|
74
|
+
const result = await Bun.build({
|
|
75
|
+
entrypoints: entries,
|
|
76
|
+
outdir: out,
|
|
77
|
+
root: dir,
|
|
78
|
+
target: 'browser',
|
|
79
|
+
format: 'esm',
|
|
80
|
+
splitting: true,
|
|
81
|
+
minify: !generation.development,
|
|
82
|
+
naming: { entry: '[dir]/[name]-[hash].[ext]', chunk: 'chunks/[name]-[hash].[ext]' },
|
|
83
|
+
define: {
|
|
84
|
+
'process.env.NODE_ENV': JSON.stringify(generation.development ? 'development' : 'production'),
|
|
85
|
+
},
|
|
86
|
+
throw: false,
|
|
87
|
+
plugins: [
|
|
88
|
+
{
|
|
89
|
+
name: 'crombolo-islands',
|
|
90
|
+
setup(build) {
|
|
91
|
+
// A client module's snapshot copy is its server stub; the browser gets its source.
|
|
92
|
+
build.onLoad({ filter: /\.[jt]sx?$/ }, (args) => {
|
|
93
|
+
const key = keyOf(args.path)
|
|
94
|
+
if (key.startsWith('..') || !client.has(key)) return undefined
|
|
95
|
+
const source = readFileSync(join(islands, 'src', ...key.split('/')), 'utf8')
|
|
96
|
+
// From the source too: the bundler drops an unused import before resolving it.
|
|
97
|
+
for (const specifier of scanner.scanImports(source))
|
|
98
|
+
if (isServerOnly(specifier.path))
|
|
99
|
+
refused.push(
|
|
100
|
+
`components/${key} imports ${specifier.path}, which only runs on the server. A 'use client' component cannot use it.`,
|
|
101
|
+
)
|
|
102
|
+
const pragma = /@jsxImportSource\s/.test(source)
|
|
103
|
+
? ''
|
|
104
|
+
: '/** @jsxImportSource react */\n'
|
|
105
|
+
return { contents: `${pragma}${source}`, loader: key.endsWith('x') ? 'tsx' : 'ts' }
|
|
106
|
+
})
|
|
107
|
+
build.onResolve({ filter: SERVER_ONLY }, (args) => {
|
|
108
|
+
if (args.path === BROWSER_ENTRY) return undefined
|
|
109
|
+
const from = keyOf(args.importer)
|
|
110
|
+
refused.push(
|
|
111
|
+
`components/${from} imports ${args.path}, which only runs on the server. A 'use client' component cannot use it.`,
|
|
112
|
+
)
|
|
113
|
+
return { path: args.path, external: true }
|
|
114
|
+
})
|
|
115
|
+
},
|
|
116
|
+
},
|
|
117
|
+
],
|
|
118
|
+
})
|
|
119
|
+
if (refused.length > 0) throw new Error([...new Set(refused)].join('\n'))
|
|
120
|
+
if (!result.success)
|
|
121
|
+
throw new Error(
|
|
122
|
+
result.logs
|
|
123
|
+
.map((log) => String(log.message ?? log).replaceAll(`${dir}${sep}`, 'components/'))
|
|
124
|
+
.join('\n'),
|
|
125
|
+
)
|
|
126
|
+
|
|
127
|
+
const urlOf = (path: string) => `${ISLANDS_PATH}/${hash}/${toKey(relative(out, path))}`
|
|
128
|
+
const manifest: IslandManifest = { modules: {} }
|
|
129
|
+
for (const output of result.outputs) {
|
|
130
|
+
if (output.kind !== 'entry-point') continue
|
|
131
|
+
const built = toKey(relative(out, output.path)).replace(/-[a-z0-9]+\.js$/, '')
|
|
132
|
+
if (built === `${ISLANDS_DIR}/react-mount`) {
|
|
133
|
+
manifest.react = urlOf(output.path)
|
|
134
|
+
continue
|
|
135
|
+
}
|
|
136
|
+
const source = entries.map(keyOf).find((key) => key.replace(/\.[jt]sx?$/, '') === built)
|
|
137
|
+
if (source) manifest.modules[moduleId(source, client)] = urlOf(output.path)
|
|
138
|
+
}
|
|
139
|
+
writeFileSync(join(out, 'manifest.json'), JSON.stringify(manifest))
|
|
140
|
+
return manifest
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/** Where a generation's built file lives on disk, or undefined for a path outside it. */
|
|
144
|
+
export function builtIslandFile(cacheDir: string, hash: string, path: string): string | undefined {
|
|
145
|
+
if (!/^[0-9a-f]{16}$/.test(hash)) return undefined
|
|
146
|
+
if (!path || path.split('/').some((part) => part === '' || part === '.' || part === '..'))
|
|
147
|
+
return undefined
|
|
148
|
+
const file = join(cacheDir, hash, ISLANDS_DIR, 'out', ...path.split('/'))
|
|
149
|
+
return existsSync(file) ? file : undefined
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/** A site's Vite manifest, made over into Crombolo's, with files served from `/crombolo/islands/vite/`. */
|
|
153
|
+
export function viteIslandManifest(siteDir: string, manifestPath: string): IslandManifest {
|
|
154
|
+
const file = resolve(siteDir, manifestPath)
|
|
155
|
+
const vite = JSON.parse(readFileSync(file, 'utf8')) as Record<
|
|
156
|
+
string,
|
|
157
|
+
{ file: string; src?: string; isEntry?: boolean }
|
|
158
|
+
>
|
|
159
|
+
const manifest: IslandManifest = { modules: {} }
|
|
160
|
+
for (const [key, entry] of Object.entries(vite)) {
|
|
161
|
+
const source = (entry.src ?? key).replace(/^\.\//, '')
|
|
162
|
+
const url = `${ISLANDS_PATH}/vite/${entry.file}`
|
|
163
|
+
if (/islands-react\.[jt]sx?$/.test(source)) manifest.react = url
|
|
164
|
+
else if (source.startsWith('components/client/'))
|
|
165
|
+
manifest.modules[source.slice('components/'.length).replace(/\.[jt]sx?$/, '')] = url
|
|
166
|
+
else if (source.startsWith('components/'))
|
|
167
|
+
manifest.modules[source.slice('components/'.length)] = url
|
|
168
|
+
}
|
|
169
|
+
return manifest
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/** Where a Vite build's files are: the manifest's own folder, less Vite's `.vite/`. */
|
|
173
|
+
export function viteOutDir(siteDir: string, manifestPath: string): string {
|
|
174
|
+
const folder = dirname(resolve(siteDir, manifestPath))
|
|
175
|
+
return folder.endsWith(`${sep}.vite`) ? dirname(folder) : folder
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/** A Vite dev server's modules, for development, by source path. */
|
|
179
|
+
export function devServerIslandManifest(devServer: string, componentsDir: string): IslandManifest {
|
|
180
|
+
const base = devServer.replace(/\/+$/, '')
|
|
181
|
+
const manifest: IslandManifest = { react: `${base}/@id/${BROWSER_ENTRY}`, modules: {} }
|
|
182
|
+
const walk = (current: string) => {
|
|
183
|
+
if (!existsSync(current)) return
|
|
184
|
+
for (const entry of readdirSync(current, { withFileTypes: true })) {
|
|
185
|
+
const path = join(current, entry.name)
|
|
186
|
+
if (entry.isDirectory()) walk(path)
|
|
187
|
+
else if (/\.[jt]sx?$/.test(entry.name)) {
|
|
188
|
+
const key = toKey(relative(componentsDir, path))
|
|
189
|
+
const url = `${base}/components/${key}`
|
|
190
|
+
manifest.modules[key] = url
|
|
191
|
+
if (key.startsWith('client/')) manifest.modules[key.replace(/\.[jt]sx?$/, '')] = url
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
walk(componentsDir)
|
|
196
|
+
return manifest
|
|
197
|
+
}
|