@fabrika/provider-cloudflare 0.9.0-cloudflare.1 → 0.9.0-cloudflare.2

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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fabrika/provider-cloudflare",
3
- "version": "0.9.0-cloudflare.1",
3
+ "version": "0.9.0-cloudflare.2",
4
4
  "type": "module",
5
5
  "repository": {
6
6
  "type": "git",
@@ -43,15 +43,15 @@
43
43
  },
44
44
  "dependencies": {
45
45
  "zod": "^3.25.76",
46
- "@fabrika/app": "0.9.0-cloudflare.1",
47
- "@fabrika/auth": "0.9.0-cloudflare.1",
48
- "@fabrika/auth-core": "0.9.0-cloudflare.1",
49
- "@fabrika/check": "0.9.0-cloudflare.1",
50
- "@fabrika/email": "0.9.0-cloudflare.1",
51
- "@fabrika/iam-contract": "0.9.0-cloudflare.1",
52
- "@fabrika/installation-init": "0.9.0-cloudflare.1",
53
- "@fabrika/proxy-core": "0.9.0-cloudflare.1",
54
- "@fabrika/provider-contract": "0.9.0-cloudflare.1",
46
+ "@fabrika/app": "0.9.0-cloudflare.2",
47
+ "@fabrika/auth": "0.9.0-cloudflare.2",
48
+ "@fabrika/auth-core": "0.9.0-cloudflare.2",
49
+ "@fabrika/check": "0.9.0-cloudflare.2",
50
+ "@fabrika/email": "0.9.0-cloudflare.2",
51
+ "@fabrika/iam-contract": "0.9.0-cloudflare.2",
52
+ "@fabrika/installation-init": "0.9.0-cloudflare.2",
53
+ "@fabrika/proxy-core": "0.9.0-cloudflare.2",
54
+ "@fabrika/provider-contract": "0.9.0-cloudflare.2",
55
55
  "oblaka-iac": "^0.0.18"
56
56
  }
57
57
  }
package/src/provider.ts CHANGED
@@ -41,6 +41,7 @@ import { buildPlan, type CloudflareStep, findMigratableDatabases } from './plan'
41
41
  import { createCloudflareProxyWorker, IamApplicationReference, PROXY_MANIFEST_DEFINE } from './proxy'
42
42
  import type { RunnerApprovedAccess } from './runner-protocol'
43
43
  import { defaultReconcileSchema } from './schema'
44
+ import { type AssetMount, assetMounts, SPA_ASSETS, SPA_ASSETS_DIRECTORY, stageSpaAssets } from './spa-assets'
44
45
 
45
46
  const CANCELLED = 'deploy cancelled'
46
47
 
@@ -225,13 +226,21 @@ const OBJECT_VARIABLES: Readonly<Record<string, string>> = {
225
226
  /**
226
227
  * Bind the application's Durable Object, which runs the application over its SQLite, the environment's files bucket,
227
228
  * and the minute tick (ADR-0065), and on a release that serves ops name its objects. The object is bound first, so
228
- * oblaka numbers its migration `v0001` whatever else the application binds, and the tag never moves.
229
+ * oblaka numbers its migration `v0001` whatever else the application binds, and the tag never moves. With `assets`,
230
+ * the Worker also gets the Workers Assets the deploy stages the mounts' files into (`SPA_ASSETS`).
229
231
  */
230
- const withApplicationRuntime = (authored: Worker, run: CloudflareDeployRun, runtime: ApplicationRuntime, ops: boolean): Worker => {
232
+ const withApplicationRuntime = (
233
+ authored: Worker,
234
+ run: CloudflareDeployRun,
235
+ runtime: ApplicationRuntime,
236
+ ops: boolean,
237
+ assets: boolean,
238
+ ): Worker => {
231
239
  const application = applicationWorker(authored)
232
240
  const configured = new Worker({
233
241
  ...application.options,
234
242
  ...(ops ? { vars: { ...(application.options.vars ?? {}), ...OBJECT_VARIABLES } } : {}),
243
+ ...(assets ? { assets: { ...SPA_ASSETS } } : {}),
235
244
  bindings: {
236
245
  [CLOUDFLARE_APPLICATION_BINDING]: new DurableObject({ name: `${run.appId}-application`, className: CLOUDFLARE_APPLICATION_CLASS }),
237
246
  ...(application.options.bindings ?? {}),
@@ -410,6 +419,11 @@ interface StepEnv {
410
419
  readonly managedSecrets: Readonly<Record<string, string>>
411
420
  /** Where the build step regenerates the entry, after `pipeline.build`; null for a release that keeps its authored `main`. */
412
421
  readonly entryBuild: EntryBuild | null
422
+ /**
423
+ * The mounts whose files the deploy stages into the application Worker's assets, from the application's root; null
424
+ * when the Worker declares its own `assets` or no mount serves files.
425
+ */
426
+ readonly spaAssets: { readonly mounts: readonly AssetMount[]; readonly root: string } | null
413
427
  generatedConfigs: readonly GeneratedConfig[]
414
428
  }
415
429
 
@@ -464,6 +478,18 @@ const deleteStaleSecrets = async (env: StepEnv, cwd: string): Promise<void> => {
464
478
  }
465
479
  }
466
480
 
481
+ /** Stage the mounts' files beside the application Worker's generated config, where its `assets.directory` points. */
482
+ const stageAssets = async (env: StepEnv, assets: NonNullable<StepEnv['spaAssets']>, generatedDir: string): Promise<void> => {
483
+ const mounts = assets.mounts.map((mount) => `${mount.prefix} from ${mount.dir}`).join(', ')
484
+ if (env.run.dryRun) {
485
+ env.run.log(` [dry-run] would stage the SPA files into ${SPA_ASSETS_DIRECTORY}: ${mounts}`)
486
+ return
487
+ }
488
+ assertRunning(env.run.signal)
489
+ const staged = await stageSpaAssets(assets.mounts, assets.root, generatedDir)
490
+ env.run.log(` staged ${staged} SPA files into ${SPA_ASSETS_DIRECTORY}: ${mounts}`)
491
+ }
492
+
467
493
  const runStep = async (spec: CloudflareStep, env: StepEnv): Promise<void> => {
468
494
  const { config, run, credentials, worker, dir, cf } = env
469
495
  const { signal, dryRun } = run
@@ -529,9 +555,11 @@ const runStep = async (spec: CloudflareStep, env: StepEnv): Promise<void> => {
529
555
  const application = `${run.env}-${applicationWorker(worker).options.name}`
530
556
  for (const generated of configs) {
531
557
  const generatedDir = dirname(resolve(dir, generated.path))
558
+ const isApplication = generated.config.name === application
559
+ // The checkout's build has written the mounts' directories; the walk below checks the staged copy.
560
+ if (isApplication && env.spaAssets !== null) await stageAssets(env, env.spaAssets, generatedDir)
532
561
  // The checkout's own build step has run by now, so this is the last moment the tree is still ours to check.
533
562
  if (env.platformResources === 'refuse') await assertLiteralAssets(generated, generatedDir)
534
- const isApplication = generated.config.name === application
535
563
  await wranglerDeploy(env, generatedDir, isApplication ? env.managedSecrets : {})
536
564
  // A platform component's own secrets carry framework names (IAM's mail transport), so only an application's are swept.
537
565
  if (isApplication && env.platformResources === 'refuse') await deleteStaleSecrets(env, generatedDir)
@@ -703,7 +731,10 @@ export const createCloudflareDeployer = (options: CloudflareDeployerOptions) =>
703
731
  const managed = withManagedEnvironment(loaded.config, proxied, run, contractEnvironment(run.managedEnvironment, served))
704
732
  const identified = platformResources === 'refuse' ? withIamIdentity(managed.worker, appEnvironmentId(run.appId, run.env)) : managed.worker
705
733
  const connected = withConnectorBindings(identified, connectors)
706
- const worker = runtime === null ? connected : withApplicationRuntime(connected, run, runtime, opsRelease)
734
+ // An application Worker that declares its own `assets` keeps them; otherwise the platform stages the mounts' files.
735
+ const mounts = runtime !== null && contract !== null ? assetMounts(contract) : []
736
+ const spaAssets = mounts.length > 0 && applicationWorker(connected).options.assets === undefined ? { mounts, root: loaded.cwd } : null
737
+ const worker = runtime === null ? connected : withApplicationRuntime(connected, run, runtime, opsRelease, spaAssets !== null)
707
738
  const dir = workerDir(loaded.config, loaded.cwd)
708
739
  const bounds: DeploymentBounds = {
709
740
  env: run.env,
@@ -739,6 +770,7 @@ export const createCloudflareDeployer = (options: CloudflareDeployerOptions) =>
739
770
  entryBuild: runtime !== null && runtime.entry !== null
740
771
  ? { cwd: loaded.cwd, config: basename(resolve(run.cwd, run.configPath)), root: resolve(run.cwd) }
741
772
  : null,
773
+ spaAssets,
742
774
  generatedConfigs: [],
743
775
  }
744
776
  const result = await runSteps(buildPlan(loaded.config, worker, env.entryBuild !== null), run, (step) => runStep(step, env))
@@ -0,0 +1,150 @@
1
+ // The SPA files of a contract application on Cloudflare. Workers Assets gives a Worker one directory, and a contract may
2
+ // declare several SPA and link mounts, each with a build directory of its own, so the deploy stages every mount's files
3
+ // into one directory that mirrors the request paths (`/admin/app.js` is `admin/app.js`), and the application's object
4
+ // serves a mount's paths from it (`bindingAssets` of `@fabrika/app`).
5
+
6
+ import { CLOUDFLARE_ASSETS_BINDING } from '@fabrika/app/build'
7
+ import type { ContractArtifact } from '@fabrika/auth-core'
8
+ import type { Stats } from 'node:fs'
9
+ import { copyFile, lstat, mkdir, readdir, rm } from 'node:fs/promises'
10
+ import { dirname, isAbsolute, join, relative, resolve } from 'node:path'
11
+
12
+ /** Where the deploy stages the mounts' files, beside the generated `wrangler.jsonc` of the application Worker. */
13
+ export const SPA_ASSETS_DIRECTORY = 'fabrika/assets'
14
+
15
+ /** The `assets` the platform writes into an application Worker that declares none and has a mount with files. */
16
+ export const SPA_ASSETS = { directory: SPA_ASSETS_DIRECTORY, binding: CLOUDFLARE_ASSETS_BINDING, run_worker_first: true } as const
17
+
18
+ /**
19
+ * The files Workers Assets reads as its own configuration at the root of the directory: a build that wrote them would
20
+ * steer the platform's asset routing and headers, so they are never staged.
21
+ */
22
+ const ASSET_CONFIG_PATHS: ReadonlySet<string> = new Set(['/_headers', '/_redirects', '/.assetsignore'])
23
+
24
+ /** A ceiling on the staging walk, as on the check of a published directory. */
25
+ const MAX_ASSET_ENTRIES = 50_000
26
+
27
+ /** A mount that serves files: its prefix, and its build directory relative to the application's root. */
28
+ export interface AssetMount {
29
+ readonly name: string
30
+ readonly prefix: string
31
+ readonly dir: string
32
+ }
33
+
34
+ /** Every SPA and link mount of the contract with the directory its files come from, the most specific prefix first. */
35
+ export const assetMounts = (contract: ContractArtifact): readonly AssetMount[] =>
36
+ Object.entries(contract.mounts)
37
+ .flatMap(([name, mount]): AssetMount[] =>
38
+ mount.kind === 'spa'
39
+ ? [{ name, prefix: mount.prefix, dir: mount.dir }]
40
+ : mount.kind === 'link'
41
+ ? [{ name, prefix: mount.prefix, dir: mount.spa }]
42
+ : []
43
+ )
44
+ .sort((left, right) => right.prefix.length - left.prefix.length || (left.prefix < right.prefix ? -1 : left.prefix > right.prefix ? 1 : 0))
45
+
46
+ /** The request path of `file` (relative, `/`-separated) of the mount at `prefix`. */
47
+ const requestPath = (prefix: string, file: string): string => (prefix === '/' ? `/${file}` : `${prefix}/${file}`)
48
+
49
+ /** Whether `path` is the mount at `prefix` or lies below it: the proxy routes it there, never to a shorter prefix. */
50
+ const isUnder = (path: string, prefix: string): boolean => prefix !== '/' && (path === prefix || path.startsWith(`${prefix}/`))
51
+
52
+ const lstatOrNull = async (path: string): Promise<Stats | null> => {
53
+ try {
54
+ return await lstat(path)
55
+ } catch (err) {
56
+ const code: unknown = err instanceof Error ? Reflect.get(err, 'code') : undefined
57
+ if (code === 'ENOENT' || code === 'ENOTDIR') return null
58
+ throw err
59
+ }
60
+ }
61
+
62
+ /**
63
+ * Whether some segment of `relativePath` below `base` is a symbolic link, from the first segment to the last. `resolve`
64
+ * only reads the text, so `x/etc` with `x -> /` passes it; this reads the disk. A segment that does not exist ends it.
65
+ */
66
+ const linkOnPath = async (base: string, relativePath: string): Promise<string | null> => {
67
+ let current = base
68
+ for (const segment of relativePath.split('/').filter((part) => part !== '' && part !== '.')) {
69
+ current = join(current, segment)
70
+ const stats = await lstatOrNull(current)
71
+ if (stats === null) return null
72
+ if (stats.isSymbolicLink()) return relative(base, current)
73
+ }
74
+ return null
75
+ }
76
+
77
+ const isWithin = (root: string, path: string): boolean => {
78
+ const between = relative(root, path)
79
+ return between === '' || (!between.startsWith('..') && !isAbsolute(between))
80
+ }
81
+
82
+ /**
83
+ * Copy each mount's build directory under `root` into `target` at its prefix, after removing whatever `target` held. A
84
+ * file of a mount that lies under a longer mount's prefix is that mount's path, so it is left out; a source map is never
85
+ * served (the platform build uploads it to Operations), so it is left out too, and so is Workers Assets' own
86
+ * configuration at the root (`ASSET_CONFIG_PATHS`). A mount whose directory is missing, a symbolic link anywhere on
87
+ * its path or in its tree, or anything but a regular file or a directory is refused: the staged tree is uploaded
88
+ * publicly, and a link would publish its target. `target` is `SPA_ASSETS_DIRECTORY` under `base`, with no link on the
89
+ * way either. Returns how many files it staged.
90
+ */
91
+ export const stageSpaAssets = async (mounts: readonly AssetMount[], root: string, base: string): Promise<number> => {
92
+ const target = resolve(base, SPA_ASSETS_DIRECTORY)
93
+ const targetLink = await linkOnPath(base, SPA_ASSETS_DIRECTORY)
94
+ if (targetLink !== null) {
95
+ throw new Error(`cloudflare: \`${targetLink}\` is a symbolic link, and the deploy stages the SPA files into \`${SPA_ASSETS_DIRECTORY}\``)
96
+ }
97
+ const sources = mounts.map((mount) => {
98
+ const source = resolve(root, mount.dir)
99
+ const segments = mount.dir.split('/')
100
+ if (isAbsolute(mount.dir) || segments.includes('..') || segments.includes('.git') || !isWithin(root, source) || source === root) {
101
+ throw new Error(`cloudflare: mount \`${mount.name}\` serves \`${mount.dir}\`, which is no directory inside the application`)
102
+ }
103
+ if (isWithin(source, target) || isWithin(target, source)) {
104
+ throw new Error(
105
+ `cloudflare: mount \`${mount.name}\` serves \`${mount.dir}\`, which overlaps \`${SPA_ASSETS_DIRECTORY}\`, where the deploy stages the SPA files`,
106
+ )
107
+ }
108
+ return { mount, source }
109
+ })
110
+ await rm(target, { recursive: true, force: true })
111
+ await mkdir(target, { recursive: true })
112
+ let entries = 0
113
+ let staged = 0
114
+ for (const { mount, source } of sources) {
115
+ const refuse = (detail: string): Error => new Error(`cloudflare: mount \`${mount.name}\` serves \`${mount.dir}\`, which ${detail}`)
116
+ const link = await linkOnPath(root, mount.dir)
117
+ if (link !== null) throw refuse(`passes \`${link}\`, a symbolic link; the deploy would publish its target`)
118
+ const stats = await lstatOrNull(source)
119
+ if (stats === null) {
120
+ throw refuse('the build did not produce; build it in `pipeline.build`')
121
+ }
122
+ if (!stats.isDirectory()) {
123
+ throw refuse(stats.isSymbolicLink() ? 'is a symbolic link; the deploy would publish its target' : 'is not a directory')
124
+ }
125
+ const longer = mounts.filter((other) => other.prefix.length > mount.prefix.length).map((other) => other.prefix)
126
+ const walk = async (prefix: string): Promise<void> => {
127
+ for (const name of (await readdir(join(source, prefix))).sort()) {
128
+ entries += 1
129
+ if (entries > MAX_ASSET_ENTRIES) throw refuse(`holds more than ${MAX_ASSET_ENTRIES} entries with the other mounts`)
130
+ const file = prefix === '' ? name : `${prefix}/${name}`
131
+ const path = requestPath(mount.prefix, file)
132
+ if (longer.some((other) => isUnder(path, other)) || ASSET_CONFIG_PATHS.has(path)) continue
133
+ const entry = await lstat(join(source, file))
134
+ if (entry.isSymbolicLink()) throw refuse(`contains \`${file}\`, a symbolic link; the deploy would publish its target`)
135
+ if (entry.isDirectory()) {
136
+ await walk(file)
137
+ } else if (!entry.isFile()) {
138
+ throw refuse(`contains \`${file}\`, which is neither a regular file nor a directory`)
139
+ } else if (!file.endsWith('.map')) {
140
+ const destination = join(target, path.slice(1))
141
+ await mkdir(dirname(destination), { recursive: true })
142
+ await copyFile(join(source, file), destination)
143
+ staged += 1
144
+ }
145
+ }
146
+ }
147
+ await walk('')
148
+ }
149
+ return staged
150
+ }
@@ -0,0 +1,27 @@
1
+ import type { ContractArtifact } from '@fabrika/auth-core';
2
+ /** Where the deploy stages the mounts' files, beside the generated `wrangler.jsonc` of the application Worker. */
3
+ export declare const SPA_ASSETS_DIRECTORY = "fabrika/assets";
4
+ /** The `assets` the platform writes into an application Worker that declares none and has a mount with files. */
5
+ export declare const SPA_ASSETS: {
6
+ readonly directory: "fabrika/assets";
7
+ readonly binding: "ASSETS";
8
+ readonly run_worker_first: true;
9
+ };
10
+ /** A mount that serves files: its prefix, and its build directory relative to the application's root. */
11
+ export interface AssetMount {
12
+ readonly name: string;
13
+ readonly prefix: string;
14
+ readonly dir: string;
15
+ }
16
+ /** Every SPA and link mount of the contract with the directory its files come from, the most specific prefix first. */
17
+ export declare const assetMounts: (contract: ContractArtifact) => readonly AssetMount[];
18
+ /**
19
+ * Copy each mount's build directory under `root` into `target` at its prefix, after removing whatever `target` held. A
20
+ * file of a mount that lies under a longer mount's prefix is that mount's path, so it is left out; a source map is never
21
+ * served (the platform build uploads it to Operations), so it is left out too, and so is Workers Assets' own
22
+ * configuration at the root (`ASSET_CONFIG_PATHS`). A mount whose directory is missing, a symbolic link anywhere on
23
+ * its path or in its tree, or anything but a regular file or a directory is refused: the staged tree is uploaded
24
+ * publicly, and a link would publish its target. `target` is `SPA_ASSETS_DIRECTORY` under `base`, with no link on the
25
+ * way either. Returns how many files it staged.
26
+ */
27
+ export declare const stageSpaAssets: (mounts: readonly AssetMount[], root: string, base: string) => Promise<number>;