belt 0.6.10 → 0.6.11
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.
- checksums.yaml +4 -4
- data/CHANGELOG.md +26 -0
- data/lib/belt/cli/frontend_deploy_command.rb +20 -3
- data/lib/belt/cli/frontend_env_command.rb +17 -0
- data/lib/belt/cli/frontend_prerender.rb +17 -9
- data/lib/belt/cli/frontend_routes.rb +129 -0
- data/lib/belt/cli/frontend_setup_command.rb +8 -0
- data/lib/belt/cli.rb +1 -0
- data/lib/belt/docs/frontend.md +53 -0
- data/lib/belt/frontend/prerender.mjs +99 -4
- data/lib/belt/frontend/router.js +112 -0
- data/lib/belt/version.rb +1 -1
- data/lib/templates/frontend/react/src/App.jsx +2 -0
- data/lib/templates/frontend/react/src/pages/NotFound.jsx +18 -0
- data/lib/templates/frontend/react/src/seo.js.erb +4 -0
- data/lib/templates/module/frontend.tf.erb +43 -1
- data/lib/templates/new_app/AGENTS.md.erb +5 -0
- metadata +4 -1
checksums.yaml
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
---
|
|
2
2
|
SHA256:
|
|
3
|
-
metadata.gz:
|
|
4
|
-
data.tar.gz:
|
|
3
|
+
metadata.gz: dd41febdeffceff192d2ce0c71193a0d44f6bc9bf573361e2473aed29f75c845
|
|
4
|
+
data.tar.gz: 48c1cce20c99bdf8e1aac26af043a6b2fc16438007d6840e18fa8a8d17607b6e
|
|
5
5
|
SHA512:
|
|
6
|
-
metadata.gz:
|
|
7
|
-
data.tar.gz:
|
|
6
|
+
metadata.gz: 7d44de9ce0d9f79fa3247cb32d7eab77859bc5da28167b1d3a9efd34e391c024f130d5d7486a5b053b9a0d4d425a6183657e2b1009ab13a48f9c1dc0284edeed
|
|
7
|
+
data.tar.gz: f757091a23142d205428a6161afe26033520229623950f8455b336ffd99135d29efc64fd40b1ef76f67035644780c21fe9ce844e56b3a6c69a56893da10bff81
|
data/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,31 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.6.11
|
|
4
|
+
|
|
5
|
+
### Added
|
|
6
|
+
|
|
7
|
+
- **Frontends answer HTTP 404 for an address that doesn't exist.** A single-page
|
|
8
|
+
app on S3 + CloudFront answered every path with `index.html` and 200, so
|
|
9
|
+
crawlers and agents couldn't tell a missing page from a real one. For a
|
|
10
|
+
frontend with `src/seo.js`, the prerender step now writes `404.html` (the app's
|
|
11
|
+
own "not found" route, `noindex`) and `.belt-routes.json`: the public pages plus
|
|
12
|
+
the app's routes, read from its `<Route path="/...">` declarations and
|
|
13
|
+
`seo.privatePaths`, so there is no second route list to keep in sync.
|
|
14
|
+
`belt deploy frontend` publishes the routes to a CloudFront KeyValueStore, and
|
|
15
|
+
a router function on the distribution serves pages from their prerendered
|
|
16
|
+
files, app routes from `index.html`, and anything else from `404.html` with
|
|
17
|
+
status 404. It fails open: before routes are published, or if the store can't
|
|
18
|
+
be read, every path behaves as before. Generated `frontend.tf` includes the
|
|
19
|
+
store and function; existing apps opt in via UPGRADING.md. (Fizzy #1985)
|
|
20
|
+
- A frontend whose own build prerenders its pages gets real 404s too: belt
|
|
21
|
+
leaves the pages alone and adds the app routes (and `404.html` if the build
|
|
22
|
+
wrote none). The build can write `.belt-routes.json` with `pages` and
|
|
23
|
+
`objects` to say where its pages are stored.
|
|
24
|
+
- `llms-full.txt` is uploaded `no-cache`, like `llms.txt`.
|
|
25
|
+
- **`belt frontend router`** writes or refreshes
|
|
26
|
+
`infrastructure/modules/app/belt_frontend_router.js`.
|
|
27
|
+
- The React template has a `NotFound` page on `<Route path="*">`.
|
|
28
|
+
|
|
3
29
|
## 0.6.10
|
|
4
30
|
|
|
5
31
|
### Changed
|
|
@@ -9,6 +9,7 @@ require_relative 'environment_config'
|
|
|
9
9
|
require_relative 'frontend_env_map'
|
|
10
10
|
require_relative 'frontend_prerender'
|
|
11
11
|
require_relative 'frontend_registry'
|
|
12
|
+
require_relative 'frontend_routes'
|
|
12
13
|
require_relative 'terraform_command'
|
|
13
14
|
|
|
14
15
|
module Belt
|
|
@@ -18,7 +19,7 @@ module Belt
|
|
|
18
19
|
|
|
19
20
|
PAGES_MANIFEST = FrontendPrerender::PAGES_MANIFEST
|
|
20
21
|
# Uploaded with no-cache instead of the immutable header hashed assets get
|
|
21
|
-
REVALIDATED_FILES = %w[*.html robots.txt sitemap.xml llms.txt].freeze
|
|
22
|
+
REVALIDATED_FILES = %w[*.html robots.txt sitemap.xml llms.txt llms-full.txt].freeze
|
|
22
23
|
|
|
23
24
|
def self.run(args)
|
|
24
25
|
frontend_name = FrontendRegistry.extract_flag!(args, '--frontend')
|
|
@@ -73,6 +74,7 @@ module Belt
|
|
|
73
74
|
puts "━━━ #{@frontend.label} (#{@frontend.path}/) ━━━"
|
|
74
75
|
build_frontend
|
|
75
76
|
sync_to_s3
|
|
77
|
+
publish_routes
|
|
76
78
|
invalidate_cloudfront
|
|
77
79
|
url = fetch_frontend_url
|
|
78
80
|
puts "\n✅ #{@frontend.label.capitalize} deployed to #{@env}!"
|
|
@@ -150,7 +152,7 @@ module Belt
|
|
|
150
152
|
# excluded so --delete doesn't remove them before they're re-uploaded.
|
|
151
153
|
run!('aws', 's3', 'sync', dist_prefix, "s3://#{bucket}", '--delete',
|
|
152
154
|
'--size-only', '--cache-control', 'public, max-age=31536000, immutable',
|
|
153
|
-
*[*REVALIDATED_FILES, PAGES_MANIFEST].flat_map { |f| ['--exclude', f] },
|
|
155
|
+
*[*REVALIDATED_FILES, PAGES_MANIFEST, FrontendRoutes::MANIFEST].flat_map { |f| ['--exclude', f] },
|
|
154
156
|
*pages.keys.flat_map { |key| ['--exclude', key] })
|
|
155
157
|
|
|
156
158
|
index = File.join(dist, 'index.html')
|
|
@@ -189,8 +191,23 @@ module Belt
|
|
|
189
191
|
end
|
|
190
192
|
end
|
|
191
193
|
|
|
194
|
+
# Tells CloudFront which addresses exist, so anything else answers 404
|
|
195
|
+
# (FrontendRoutes). Before the invalidation, so the first uncached request
|
|
196
|
+
# already sees the new routes.
|
|
197
|
+
def publish_routes
|
|
198
|
+
return unless File.file?(File.join(@frontend.dist_dir, FrontendRoutes::MANIFEST))
|
|
199
|
+
|
|
200
|
+
FrontendRoutes.new(dist_dir: @frontend.dist_dir, distribution_id: distribution_id).publish
|
|
201
|
+
end
|
|
202
|
+
|
|
203
|
+
def distribution_id
|
|
204
|
+
return @distribution_id if defined?(@distribution_id)
|
|
205
|
+
|
|
206
|
+
@distribution_id = fetch_distribution_id
|
|
207
|
+
end
|
|
208
|
+
|
|
192
209
|
def invalidate_cloudfront
|
|
193
|
-
dist_id =
|
|
210
|
+
dist_id = distribution_id
|
|
194
211
|
unless dist_id
|
|
195
212
|
puts '⚠️ No CloudFront distribution found (skipping cache invalidation)'
|
|
196
213
|
return
|
|
@@ -6,6 +6,7 @@ require_relative 'environment_config'
|
|
|
6
6
|
require_relative 'frontend_env_map'
|
|
7
7
|
require_relative 'frontend_prerender'
|
|
8
8
|
require_relative 'frontend_registry'
|
|
9
|
+
require_relative 'frontend_routes'
|
|
9
10
|
require_relative 'terraform_command'
|
|
10
11
|
|
|
11
12
|
module Belt
|
|
@@ -13,6 +14,7 @@ module Belt
|
|
|
13
14
|
# belt frontend env <environment> [--frontend NAME]
|
|
14
15
|
# belt frontend list
|
|
15
16
|
# belt frontend prerender [--frontend NAME]
|
|
17
|
+
# belt frontend router
|
|
16
18
|
#
|
|
17
19
|
# Smart-merges terraform outputs into <frontend>/.env using the declarative map
|
|
18
20
|
# (<frontend>/env.yml or .belt/frontend_env.yml for the default frontend).
|
|
@@ -29,6 +31,8 @@ module Belt
|
|
|
29
31
|
run_list
|
|
30
32
|
when 'prerender'
|
|
31
33
|
run_prerender(args)
|
|
34
|
+
when 'router'
|
|
35
|
+
run_router
|
|
32
36
|
when nil, '-h', '--help', 'help'
|
|
33
37
|
puts usage
|
|
34
38
|
exit(subcommand.nil? ? 1 : 0)
|
|
@@ -67,6 +71,18 @@ module Belt
|
|
|
67
71
|
prerender.run
|
|
68
72
|
end
|
|
69
73
|
|
|
74
|
+
# Writes (or refreshes) the CloudFront router function next to the frontend
|
|
75
|
+
# terraform that loads it. For apps adopting real 404s, and after a belt
|
|
76
|
+
# upgrade that changes the function.
|
|
77
|
+
def self.run_router
|
|
78
|
+
module_dir = FrontendRoutes::MODULE_DIR
|
|
79
|
+
abort "Error: Module directory not found at #{module_dir}/." unless Dir.exist?(module_dir)
|
|
80
|
+
|
|
81
|
+
dest = FrontendRoutes.install_router(module_dir)
|
|
82
|
+
puts dest ? " write #{dest}" : " current #{File.join(module_dir, FrontendRoutes::ROUTER_FILE)}"
|
|
83
|
+
puts "\nApply it with `belt deploy <environment>`. See `belt explain seo`, \"Real 404s\"."
|
|
84
|
+
end
|
|
85
|
+
|
|
70
86
|
def self.run_env(args)
|
|
71
87
|
frontend_name = FrontendRegistry.extract_flag!(args, '--frontend')
|
|
72
88
|
env = EnvResolver.resolve(args)
|
|
@@ -106,6 +122,7 @@ module Belt
|
|
|
106
122
|
belt frontend env <environment> [--frontend NAME]
|
|
107
123
|
belt frontend list
|
|
108
124
|
belt frontend prerender [--frontend NAME] Build + SEO prerender locally (src/seo.js)
|
|
125
|
+
belt frontend router Write the CloudFront router function (real 404s)
|
|
109
126
|
belt frontend --help
|
|
110
127
|
|
|
111
128
|
Env map (optional, per frontend):
|
|
@@ -21,6 +21,7 @@ module Belt
|
|
|
21
21
|
# existing apps don't grow an untracked build directory.
|
|
22
22
|
SSR_OUT_DIR = 'node_modules/.cache/belt-ssr'
|
|
23
23
|
PAGES_MANIFEST = '.belt-pages.json'
|
|
24
|
+
ROUTES_MANIFEST = '.belt-routes.json'
|
|
24
25
|
|
|
25
26
|
def initialize(frontend, env: {})
|
|
26
27
|
@frontend = frontend
|
|
@@ -32,34 +33,41 @@ module Belt
|
|
|
32
33
|
end
|
|
33
34
|
|
|
34
35
|
# Frontends scaffolded by belt 0.6.6–0.6.9 run their own scripts/prerender.js
|
|
35
|
-
# inside `npm run build
|
|
36
|
+
# inside `npm run build`, and an app can prerender its own way and say where
|
|
37
|
+
# its pages are in .belt-routes.json; either way the pages are already in dist.
|
|
36
38
|
def prerendered_by_build?
|
|
37
|
-
File.file?(File.join(@frontend.dist_dir,
|
|
39
|
+
[PAGES_MANIFEST, ROUTES_MANIFEST].any? { |file| File.file?(File.join(@frontend.dist_dir, file)) }
|
|
38
40
|
end
|
|
39
41
|
|
|
40
42
|
# Returns true when it prerendered, false when the frontend didn't opt in.
|
|
41
|
-
def run
|
|
43
|
+
def run # rubocop:disable Naming/PredicateMethod
|
|
42
44
|
return false unless manifest
|
|
43
45
|
|
|
44
46
|
if prerendered_by_build?
|
|
45
|
-
puts '🔎 SEO: prerendered by the app build
|
|
47
|
+
puts '🔎 SEO: prerendered by the app build — skipping belt prerender, adding the app routes for 404s'
|
|
48
|
+
run_script('--routes-only')
|
|
46
49
|
return false
|
|
47
50
|
end
|
|
48
51
|
|
|
49
52
|
puts "🔎 SEO: prerendering pages from #{manifest}"
|
|
50
53
|
ssr = build_ssr_bundle
|
|
54
|
+
run_script(*(ssr ? ['--ssr', ssr] : []))
|
|
55
|
+
true
|
|
56
|
+
end
|
|
57
|
+
|
|
58
|
+
private
|
|
59
|
+
|
|
60
|
+
def run_script(*extra)
|
|
51
61
|
cmd = ['node', SCRIPT,
|
|
52
62
|
'--manifest', File.expand_path(manifest, @frontend.path),
|
|
53
63
|
'--dist', File.expand_path(@frontend.dist_dir),
|
|
54
|
-
'--public', File.expand_path('public', @frontend.path)
|
|
55
|
-
|
|
56
|
-
return
|
|
64
|
+
'--public', File.expand_path('public', @frontend.path),
|
|
65
|
+
'--src', File.expand_path('src', @frontend.path), *extra]
|
|
66
|
+
return if system(@env, *cmd, chdir: @frontend.path)
|
|
57
67
|
|
|
58
68
|
abort "\n✗ SEO prerender failed: #{cmd.shelljoin}"
|
|
59
69
|
end
|
|
60
70
|
|
|
61
|
-
private
|
|
62
|
-
|
|
63
71
|
# Builds the SSR bundle and returns its entry path, or nil when there's no
|
|
64
72
|
# entry or it doesn't build (typically a module touching window/document at
|
|
65
73
|
# import time). Without it, pages still get their tags, sitemap and robots.
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require 'fileutils'
|
|
4
|
+
require 'json'
|
|
5
|
+
require 'open3'
|
|
6
|
+
|
|
7
|
+
module Belt
|
|
8
|
+
module CLI
|
|
9
|
+
# Real 404s for a single-page frontend.
|
|
10
|
+
#
|
|
11
|
+
# CloudFront can't tell which addresses an SPA has, so the classic setup
|
|
12
|
+
# answers every path with index.html and 200. Belt's router function
|
|
13
|
+
# (lib/belt/frontend/router.js) fixes that at the edge, and this class keeps
|
|
14
|
+
# it informed: after each deploy it publishes the routes the prerender step
|
|
15
|
+
# wrote to <dist>/.belt-routes.json (from src/seo.js: `pages` and
|
|
16
|
+
# `privatePaths`) into the CloudFront KeyValueStore the function reads.
|
|
17
|
+
#
|
|
18
|
+
# Nothing here is required for a deploy to work. No manifest, no router on the
|
|
19
|
+
# distribution, or a failed publish all leave the site serving as it did.
|
|
20
|
+
class FrontendRoutes
|
|
21
|
+
ROUTER_SOURCE = File.expand_path('../frontend/router.js', __dir__)
|
|
22
|
+
ROUTER_FILE = 'belt_frontend_router.js'
|
|
23
|
+
MODULE_DIR = 'infrastructure/modules/app'
|
|
24
|
+
MANIFEST = '.belt-routes.json'
|
|
25
|
+
KEY = 'belt:routes'
|
|
26
|
+
# A KeyValueStore value holds 1 KB.
|
|
27
|
+
CHUNK_SIZE = 1000
|
|
28
|
+
|
|
29
|
+
# Copies the router function next to the terraform that loads it with
|
|
30
|
+
# file(). Returns the path when the file was written or refreshed.
|
|
31
|
+
def self.install_router(module_dir = MODULE_DIR)
|
|
32
|
+
dest = File.join(module_dir, ROUTER_FILE)
|
|
33
|
+
source = File.read(ROUTER_SOURCE)
|
|
34
|
+
return nil if File.file?(dest) && File.read(dest) == source
|
|
35
|
+
|
|
36
|
+
FileUtils.mkdir_p(module_dir)
|
|
37
|
+
File.write(dest, source)
|
|
38
|
+
dest
|
|
39
|
+
end
|
|
40
|
+
|
|
41
|
+
# The KeyValueStore entries for a manifest: the chunk count under KEY and
|
|
42
|
+
# the JSON split across KEY:0, KEY:1, ...
|
|
43
|
+
def self.entries(manifest)
|
|
44
|
+
routes = { 'app' => Array(manifest['app']), 'pages' => Array(manifest['pages']) }
|
|
45
|
+
routes['objects'] = manifest['objects'] if manifest['objects'].is_a?(Hash) && manifest['objects'].any?
|
|
46
|
+
json = JSON.generate(routes, ascii_only: true)
|
|
47
|
+
chunks = json.scan(/.{1,#{CHUNK_SIZE}}/m)
|
|
48
|
+
chunks.each_with_index.to_h { |chunk, i| ["#{KEY}:#{i}", chunk] }.merge(KEY => chunks.size.to_s)
|
|
49
|
+
end
|
|
50
|
+
|
|
51
|
+
def initialize(dist_dir:, distribution_id:)
|
|
52
|
+
@dist_dir = dist_dir
|
|
53
|
+
@distribution_id = distribution_id
|
|
54
|
+
end
|
|
55
|
+
|
|
56
|
+
def manifest
|
|
57
|
+
path = File.join(@dist_dir, MANIFEST)
|
|
58
|
+
return nil unless File.file?(path)
|
|
59
|
+
|
|
60
|
+
data = JSON.parse(File.read(path))
|
|
61
|
+
data.is_a?(Hash) ? data : nil
|
|
62
|
+
rescue JSON::ParserError
|
|
63
|
+
nil
|
|
64
|
+
end
|
|
65
|
+
|
|
66
|
+
# Returns :published, or the reason nothing was published.
|
|
67
|
+
def publish
|
|
68
|
+
routes = manifest
|
|
69
|
+
return :no_manifest unless routes
|
|
70
|
+
return :no_distribution unless @distribution_id
|
|
71
|
+
|
|
72
|
+
store = key_value_store_arn
|
|
73
|
+
unless store
|
|
74
|
+
puts 'ℹ️ Unknown paths still answer 200: this CloudFront distribution has no belt router. ' \
|
|
75
|
+
'See "Real 404s" in `belt explain seo`.'
|
|
76
|
+
return :no_router
|
|
77
|
+
end
|
|
78
|
+
|
|
79
|
+
write(store, self.class.entries(routes))
|
|
80
|
+
puts "🧭 Published routes: #{Array(routes['pages']).size} page(s), " \
|
|
81
|
+
"#{Array(routes['app']).size} app path(s); anything else answers 404"
|
|
82
|
+
:published
|
|
83
|
+
rescue StandardError => e
|
|
84
|
+
warn "⚠️ Could not publish routes (#{e.message.lines.first&.strip}). " \
|
|
85
|
+
'The site keeps serving with the routes from the last deploy.'
|
|
86
|
+
:failed
|
|
87
|
+
end
|
|
88
|
+
|
|
89
|
+
private
|
|
90
|
+
|
|
91
|
+
# The store is whichever KeyValueStore the distribution's default-behavior
|
|
92
|
+
# functions are associated with, so no extra terraform output is needed.
|
|
93
|
+
def key_value_store_arn
|
|
94
|
+
functions = aws_json('cloudfront', 'get-distribution-config', '--id', @distribution_id)
|
|
95
|
+
.dig('DistributionConfig', 'DefaultCacheBehavior', 'FunctionAssociations', 'Items') || []
|
|
96
|
+
functions.each do |association|
|
|
97
|
+
name = association['FunctionARN'].to_s.split('/').last
|
|
98
|
+
next if name.to_s.empty?
|
|
99
|
+
|
|
100
|
+
stores = aws_json('cloudfront', 'describe-function', '--name', name, '--stage', 'LIVE')
|
|
101
|
+
.dig('FunctionSummary', 'FunctionConfig', 'KeyValueStoreAssociations', 'Items') || []
|
|
102
|
+
arn = stores.first&.fetch('KeyValueStoreARN', nil)
|
|
103
|
+
return arn if arn
|
|
104
|
+
end
|
|
105
|
+
nil
|
|
106
|
+
end
|
|
107
|
+
|
|
108
|
+
# One atomic update: new entries in, chunks left over from a longer list out.
|
|
109
|
+
def write(store, entries)
|
|
110
|
+
etag = aws_json('cloudfront-keyvaluestore', 'describe-key-value-store', '--kvs-arn', store).fetch('ETag')
|
|
111
|
+
existing = (aws_json('cloudfront-keyvaluestore', 'list-keys', '--kvs-arn', store)['Items'] || [])
|
|
112
|
+
.map { |item| item['Key'] }
|
|
113
|
+
stale = existing.select { |key| key.start_with?(KEY) } - entries.keys
|
|
114
|
+
|
|
115
|
+
cmd = ['cloudfront-keyvaluestore', 'update-keys', '--kvs-arn', store, '--if-match', etag,
|
|
116
|
+
'--puts', JSON.generate(entries.map { |key, value| { 'Key' => key, 'Value' => value } })]
|
|
117
|
+
cmd.push('--deletes', JSON.generate(stale.map { |key| { 'Key' => key } })) if stale.any?
|
|
118
|
+
aws_json(*cmd)
|
|
119
|
+
end
|
|
120
|
+
|
|
121
|
+
def aws_json(*args)
|
|
122
|
+
out, err, status = Open3.capture3('aws', *args, '--output', 'json')
|
|
123
|
+
raise err.strip.empty? ? "aws #{args.first(2).join(' ')} failed" : err.strip unless status.success?
|
|
124
|
+
|
|
125
|
+
out.strip.empty? ? {} : JSON.parse(out)
|
|
126
|
+
end
|
|
127
|
+
end
|
|
128
|
+
end
|
|
129
|
+
end
|
|
@@ -5,6 +5,7 @@ require 'erb'
|
|
|
5
5
|
require_relative 'app_detection'
|
|
6
6
|
require_relative 'env_resolver'
|
|
7
7
|
require_relative 'frontend_registry'
|
|
8
|
+
require_relative 'frontend_routes'
|
|
8
9
|
|
|
9
10
|
module Belt
|
|
10
11
|
module CLI
|
|
@@ -70,6 +71,7 @@ module Belt
|
|
|
70
71
|
def run
|
|
71
72
|
validate!
|
|
72
73
|
generate_frontend_tf
|
|
74
|
+
install_router
|
|
73
75
|
ensure_cloudfront_cors
|
|
74
76
|
append_env_outputs
|
|
75
77
|
return if @quiet
|
|
@@ -96,6 +98,12 @@ module Belt
|
|
|
96
98
|
puts " create #{dest}" unless @quiet
|
|
97
99
|
end
|
|
98
100
|
|
|
101
|
+
# The CloudFront function frontend.tf loads with file().
|
|
102
|
+
def install_router
|
|
103
|
+
dest = FrontendRoutes.install_router(MODULE_DIR)
|
|
104
|
+
puts " create #{dest}" if dest && !@quiet
|
|
105
|
+
end
|
|
106
|
+
|
|
99
107
|
def append_env_outputs
|
|
100
108
|
Dir.glob('infrastructure/*/outputs.tf').reject { |f| f.include?('modules') }.each do |file|
|
|
101
109
|
before = File.read(file)
|
data/lib/belt/cli.rb
CHANGED
|
@@ -167,6 +167,7 @@ module Belt
|
|
|
167
167
|
frontend env <env> [--frontend NAME] Write <frontend>/.env from terraform outputs
|
|
168
168
|
frontend list List configured frontends
|
|
169
169
|
frontend prerender [--frontend NAME] Build + SEO prerender a frontend locally
|
|
170
|
+
frontend router Write the CloudFront router function (real 404s)
|
|
170
171
|
routes [-g PATTERN] [-f json] Show route definitions
|
|
171
172
|
contracts [-g PATTERN] [-f json] Show API request/response contracts
|
|
172
173
|
lambda-config [-e ENV] [-f json|terraform] Show merged lambda configuration
|
data/lib/belt/docs/frontend.md
CHANGED
|
@@ -140,6 +140,56 @@ the build; set `SEO_INDEXABLE=true|false` to override.
|
|
|
140
140
|
After the first prod deploy, submit `https://<domain>/sitemap.xml` to Google
|
|
141
141
|
Search Console and Bing Webmaster Tools.
|
|
142
142
|
|
|
143
|
+
### Real 404s
|
|
144
|
+
|
|
145
|
+
A single-page app on S3 + CloudFront classically answers every path with
|
|
146
|
+
`index.html` and HTTP 200, because CloudFront can't tell which addresses the app
|
|
147
|
+
has. Crawlers and agents then can't tell a missing page from a real one. A
|
|
148
|
+
frontend with `src/seo.js` answers a real 404 instead:
|
|
149
|
+
|
|
150
|
+
- **A public page** (`seo.pages`) is served from its prerendered file.
|
|
151
|
+
- **A route of the app** is served `index.html`, as before.
|
|
152
|
+
- **Anything else** gets `404.html` with HTTP 404. That page is the app's own
|
|
153
|
+
"not found" route (`<Route path="*">`) prerendered, with `noindex`.
|
|
154
|
+
|
|
155
|
+
You don't keep a route list. The prerender step reads the app's routes from its
|
|
156
|
+
`<Route path="/...">` declarations under `src/` (test files are skipped), adds
|
|
157
|
+
`seo.privatePaths` as prefixes, and writes them to `dist/.belt-routes.json`.
|
|
158
|
+
`belt deploy frontend` publishes that to a CloudFront KeyValueStore, and belt's
|
|
159
|
+
router function (`infrastructure/modules/app/belt_frontend_router.js`, on the
|
|
160
|
+
distribution's viewer-request and viewer-response events) reads it at the edge.
|
|
161
|
+
The deploy prints what it published:
|
|
162
|
+
|
|
163
|
+
```
|
|
164
|
+
SEO: 14 app route(s) and 6 page(s) answer; any other address is a 404
|
|
165
|
+
🧭 Published routes: 5 page(s), 14 app path(s); anything else answers 404
|
|
166
|
+
```
|
|
167
|
+
|
|
168
|
+
Belt only sees a route written as `<Route path="/literal/or/:param">`. A route
|
|
169
|
+
declared another way — a nested `<Route path="settings">`, a `createBrowserRouter`
|
|
170
|
+
config object, a path built at runtime — needs its prefix in `privatePaths`
|
|
171
|
+
(`'/account'` covers `/account` and everything under it). If one is missed,
|
|
172
|
+
nothing breaks in a browser: `404.html` loads the app, which routes to the real
|
|
173
|
+
page. Only the HTTP status is wrong, so check `dist/.belt-routes.json` after
|
|
174
|
+
adding a route in an unusual way.
|
|
175
|
+
|
|
176
|
+
A frontend that prerenders its own way (its `npm run build` writes the pages, as
|
|
177
|
+
the 0.6.6–0.6.9 templates did) still gets this: belt leaves its pages alone and
|
|
178
|
+
only adds the app routes and, if the build wrote none, `404.html`. Such a build
|
|
179
|
+
can write `dist/.belt-routes.json` itself to say where its pages are:
|
|
180
|
+
`{ "pages": ["/docs"], "objects": { "/": "/_pages/index.html", "/docs": "/_pages/docs.html" } }`.
|
|
181
|
+
`objects` is only needed for a page that isn't stored at its own extensionless
|
|
182
|
+
key.
|
|
183
|
+
|
|
184
|
+
Published routes reach the edge within about a minute of the deploy. Check with
|
|
185
|
+
`curl -s -o /dev/null -w '%{http_code}\n' https://<site>/no-such-page` (404) and
|
|
186
|
+
the same for a route of the app (200).
|
|
187
|
+
|
|
188
|
+
It fails open. Until a deploy has published routes, or if the store can't be
|
|
189
|
+
read or written, every path behaves as it did before (index.html, 200). Paths
|
|
190
|
+
with a file extension are never rewritten. Customize the 404 page's metadata
|
|
191
|
+
with `seo.notFound: { title, description }`.
|
|
192
|
+
|
|
143
193
|
## Infrastructure
|
|
144
194
|
|
|
145
195
|
`belt setup frontend` (and `belt generate frontend`) writes S3 + CloudFront into
|
|
@@ -147,6 +197,9 @@ Search Console and Bing Webmaster Tools.
|
|
|
147
197
|
`{name}_frontend.tf` with unique resource names and outputs
|
|
148
198
|
(`ops_frontend_bucket_name`, …). Extra frontends get a CloudFront URL only —
|
|
149
199
|
custom DNS stays on the default frontend unless you add records yourself.
|
|
200
|
+
The generated distribution includes the router function and KeyValueStore for
|
|
201
|
+
real 404s (above); `belt frontend router` rewrites `belt_frontend_router.js`
|
|
202
|
+
after a belt upgrade changes it.
|
|
150
203
|
|
|
151
204
|
CORS: each CloudFront domain is added to `frontend_urls` on the conveyor-belt
|
|
152
205
|
resource so SPA → API calls work.
|
|
@@ -16,15 +16,27 @@
|
|
|
16
16
|
* llms.txt — plain-text site summary for LLMs (https://llmstxt.org)
|
|
17
17
|
* .belt-pages.json — S3 key → file map; `belt deploy frontend` uploads each page
|
|
18
18
|
* to its extensionless key (/about → about.html) as text/html
|
|
19
|
+
* 404.html — what an address with no page gets, with HTTP 404: the app's
|
|
20
|
+
* own "not found" route when it has one, never indexed
|
|
21
|
+
* .belt-routes.json — the public pages, plus the app's own routes (every
|
|
22
|
+
* <Route path="/..."> under --src and seo.privatePaths);
|
|
23
|
+
* `belt deploy frontend` publishes them to CloudFront so it can
|
|
24
|
+
* tell a real address from a missing one (see `belt explain
|
|
25
|
+
* seo`, "Real 404s")
|
|
19
26
|
*
|
|
20
|
-
*
|
|
27
|
+
* With --routes-only (a frontend whose own build already prerendered its pages) nothing
|
|
28
|
+
* above is touched except what real 404s need: .belt-routes.json gains the app's routes
|
|
29
|
+
* (keeping any `pages`/`objects` the build wrote, else taking pages from .belt-pages.json),
|
|
30
|
+
* and 404.html is written only if the build didn't write one.
|
|
31
|
+
*
|
|
32
|
+
* Usage: node prerender.mjs --manifest src/seo.js --dist dist [--ssr entry-server.js] [--public public] [--src src]
|
|
21
33
|
*
|
|
22
34
|
* Environment:
|
|
23
35
|
* VITE_SITE_URL canonical origin (belt deploy injects the frontend URL)
|
|
24
36
|
* BELT_ENV environment being built (belt deploy injects it)
|
|
25
37
|
* SEO_INDEXABLE "true"/"false" to override seo.indexableEnvironments
|
|
26
38
|
*/
|
|
27
|
-
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
|
|
39
|
+
import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs'
|
|
28
40
|
import { dirname, join, resolve } from 'node:path'
|
|
29
41
|
import { pathToFileURL } from 'node:url'
|
|
30
42
|
import { parseArgs } from 'node:util'
|
|
@@ -34,17 +46,20 @@ const { values: args } = parseArgs({
|
|
|
34
46
|
manifest: { type: 'string' },
|
|
35
47
|
dist: { type: 'string' },
|
|
36
48
|
ssr: { type: 'string' },
|
|
37
|
-
public: { type: 'string' }
|
|
49
|
+
public: { type: 'string' },
|
|
50
|
+
src: { type: 'string' },
|
|
51
|
+
'routes-only': { type: 'boolean' }
|
|
38
52
|
}
|
|
39
53
|
})
|
|
40
54
|
if (!args.manifest || !args.dist) {
|
|
41
|
-
console.error('Usage: node prerender.mjs --manifest src/seo.js --dist dist [--ssr entry-server.js] [--public public]')
|
|
55
|
+
console.error('Usage: node prerender.mjs --manifest src/seo.js --dist dist [--ssr entry-server.js] [--public public] [--src src]')
|
|
42
56
|
process.exit(1)
|
|
43
57
|
}
|
|
44
58
|
|
|
45
59
|
const DIST = resolve(args.dist)
|
|
46
60
|
const SSR_ENTRY = args.ssr ? resolve(args.ssr) : null
|
|
47
61
|
const PROJECT_ROBOTS = args.public ? join(resolve(args.public), 'robots.txt') : null
|
|
62
|
+
const SRC = args.src ? resolve(args.src) : null
|
|
48
63
|
const seo = (await import(pathToFileURL(resolve(args.manifest)).href)).default
|
|
49
64
|
|
|
50
65
|
const siteUrl = (process.env.VITE_SITE_URL || seo.siteUrl || '').replace(/\/+$/, '')
|
|
@@ -135,6 +150,63 @@ function pageHtml(template, page, body) {
|
|
|
135
150
|
)
|
|
136
151
|
}
|
|
137
152
|
|
|
153
|
+
// The addresses the single-page app routes itself, as patterns for belt's
|
|
154
|
+
// CloudFront router: `*` is one segment, a trailing `**` is the rest. They come
|
|
155
|
+
// from the app's own <Route path="/..."> declarations, so adding a route needs no
|
|
156
|
+
// second list, plus seo.privatePaths for anything declared another way (nested
|
|
157
|
+
// relative routes, a router config object, a path built at runtime).
|
|
158
|
+
const ROUTE_PATH = /<Route\b[^>]*?\bpath=\{?["'`](\/[^"'`]*)["'`]/g
|
|
159
|
+
const SOURCE_FILE = /\.(jsx?|tsx?)$/
|
|
160
|
+
const TEST_FILE = /\.(test|spec)\.|__tests__/
|
|
161
|
+
|
|
162
|
+
function sourceFiles(dir) {
|
|
163
|
+
return readdirSync(dir, { withFileTypes: true }).flatMap((entry) => {
|
|
164
|
+
const path = join(dir, entry.name)
|
|
165
|
+
if (entry.isDirectory()) return entry.name === 'node_modules' ? [] : sourceFiles(path)
|
|
166
|
+
return SOURCE_FILE.test(entry.name) && !TEST_FILE.test(path) ? [path] : []
|
|
167
|
+
})
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
function routePattern(path) {
|
|
171
|
+
const segments = []
|
|
172
|
+
for (const segment of normalize(path).split('/').slice(1)) {
|
|
173
|
+
if (segment === '*' || segment.endsWith('?')) return ['', ...segments, '**'].join('/')
|
|
174
|
+
segments.push(segment.startsWith(':') ? '*' : segment)
|
|
175
|
+
}
|
|
176
|
+
return ['', ...segments].join('/')
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
function appRoutes(pagePaths) {
|
|
180
|
+
const declared = SRC && existsSync(SRC)
|
|
181
|
+
? sourceFiles(SRC).flatMap((file) => [...readFileSync(file, 'utf-8').matchAll(ROUTE_PATH)].map((match) => match[1]))
|
|
182
|
+
: []
|
|
183
|
+
const patterns = [...declared.map(routePattern), ...privatePaths.map((path) => `${path}/**`)]
|
|
184
|
+
return [...new Set(patterns)].filter((pattern) => pattern !== '/' && !pagePaths.includes(pattern)).sort()
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
// Served for every address that is neither a page nor an app route. It keeps the
|
|
188
|
+
// app's scripts, so a route belt couldn't see still boots the app in a browser.
|
|
189
|
+
const NOT_FOUND_PATH = '/404'
|
|
190
|
+
|
|
191
|
+
function notFoundHtml(template, body) {
|
|
192
|
+
const title = seo.notFound?.title || `Page not found | ${seo.siteName}`
|
|
193
|
+
const description = seo.notFound?.description || `There is no page at this address on ${seo.siteName}.`
|
|
194
|
+
const fallback = `<main><h1>Page not found</h1><p>${escapeHtml(description)}</p><p><a href="/">${escapeHtml(seo.siteName)}</a></p></main>`
|
|
195
|
+
return template
|
|
196
|
+
.replace(/<title>[\s\S]*?<\/title>/, () => `<title>${escapeHtml(title)}</title>`)
|
|
197
|
+
.replace(/\s*<meta name="description"[^>]*>/, '')
|
|
198
|
+
.replace(
|
|
199
|
+
'</head>',
|
|
200
|
+
() =>
|
|
201
|
+
` <meta name="description" content="${escapeHtml(description)}" />\n` +
|
|
202
|
+
' <meta name="robots" content="noindex" />\n </head>'
|
|
203
|
+
)
|
|
204
|
+
.replace(
|
|
205
|
+
'<div id="root"></div>',
|
|
206
|
+
() => (body ? `<div id="root" data-prerendered="${NOT_FOUND_PATH}">${body}</div>` : `<div id="root">${fallback}</div>`)
|
|
207
|
+
)
|
|
208
|
+
}
|
|
209
|
+
|
|
138
210
|
function robotsTxt() {
|
|
139
211
|
if (!indexable) return 'User-agent: *\nDisallow: /\n'
|
|
140
212
|
if (PROJECT_ROBOTS && existsSync(PROJECT_ROBOTS)) return readFileSync(PROJECT_ROBOTS, 'utf-8')
|
|
@@ -154,12 +226,29 @@ function llmsTxt() {
|
|
|
154
226
|
return `${lines.join('\n')}\n`
|
|
155
227
|
}
|
|
156
228
|
|
|
229
|
+
const readJson = (file) => (existsSync(file) ? JSON.parse(readFileSync(file, 'utf-8')) : null)
|
|
230
|
+
|
|
231
|
+
// The app's build prerendered its own pages. Fill in what real 404s still need.
|
|
232
|
+
function completeRoutes(indexFile) {
|
|
233
|
+
const routesFile = join(DIST, '.belt-routes.json')
|
|
234
|
+
const built = readJson(routesFile) || {}
|
|
235
|
+
const pagePaths = built.pages || Object.keys(readJson(join(DIST, '.belt-pages.json')) || {}).map(normalize)
|
|
236
|
+
const routes = { ...built, pages: pagePaths, app: appRoutes(pagePaths) }
|
|
237
|
+
|
|
238
|
+
writeFileSync(routesFile, `${JSON.stringify(routes, null, 2)}\n`)
|
|
239
|
+
if (!existsSync(join(DIST, '404.html'))) {
|
|
240
|
+
writeFileSync(join(DIST, '404.html'), notFoundHtml(readFileSync(indexFile, 'utf-8'), ''))
|
|
241
|
+
}
|
|
242
|
+
console.log(`SEO: ${routes.app.length} app route(s) and ${pagePaths.length + 1} page(s) answer; any other address is a 404`)
|
|
243
|
+
}
|
|
244
|
+
|
|
157
245
|
async function main() {
|
|
158
246
|
const indexFile = join(DIST, 'index.html')
|
|
159
247
|
if (!existsSync(indexFile)) {
|
|
160
248
|
console.error(`${indexFile} not found — run \`vite build\` first`)
|
|
161
249
|
process.exit(1)
|
|
162
250
|
}
|
|
251
|
+
if (args['routes-only']) return completeRoutes(indexFile)
|
|
163
252
|
if (!pages.some((page) => page.path === '/')) pages.unshift({ path: '/', title: seo.siteName })
|
|
164
253
|
for (const page of pages) {
|
|
165
254
|
page.title ||= seo.siteName
|
|
@@ -179,13 +268,19 @@ async function main() {
|
|
|
179
268
|
if (key) manifest[key] = file
|
|
180
269
|
}
|
|
181
270
|
|
|
271
|
+
writeFileSync(join(DIST, '404.html'), notFoundHtml(template, renderBody(render, NOT_FOUND_PATH)))
|
|
272
|
+
const pagePaths = pages.map((page) => page.path).filter((path) => path !== '/')
|
|
273
|
+
const routes = { pages: pagePaths, app: appRoutes(pagePaths) }
|
|
274
|
+
|
|
182
275
|
writeFileSync(join(DIST, '.belt-pages.json'), `${JSON.stringify(manifest, null, 2)}\n`)
|
|
276
|
+
writeFileSync(join(DIST, '.belt-routes.json'), `${JSON.stringify(routes, null, 2)}\n`)
|
|
183
277
|
writeFileSync(join(DIST, 'robots.txt'), robotsTxt())
|
|
184
278
|
writeFileSync(join(DIST, 'llms.txt'), llmsTxt())
|
|
185
279
|
if (siteUrl) writeFileSync(join(DIST, 'sitemap.xml'), sitemapXml())
|
|
186
280
|
|
|
187
281
|
if (PROJECT_ROBOTS && indexable && existsSync(PROJECT_ROBOTS)) console.log('SEO: robots.txt from public/robots.txt')
|
|
188
282
|
if (!siteUrl) console.warn('⚠️ No site URL (VITE_SITE_URL or seo.siteUrl) — skipped canonical URLs and sitemap.xml')
|
|
283
|
+
console.log(`SEO: ${routes.app.length} app route(s) and ${pagePaths.length + 1} page(s) answer; any other address is a 404`)
|
|
189
284
|
console.log(
|
|
190
285
|
`SEO: prerendered ${pages.length} page(s), ${indexable ? 'indexable' : 'noindex'}` +
|
|
191
286
|
`${process.env.BELT_ENV ? ` (${process.env.BELT_ENV})` : ''}`
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
// Belt frontend router — a CloudFront Function (cloudfront-js-2.0), associated
|
|
2
|
+
// with the distribution's default behavior for both viewer-request and
|
|
3
|
+
// viewer-response. It makes an address with no page answer HTTP 404 instead of
|
|
4
|
+
// the app shell with 200, so crawlers and agents can tell a missing page from a
|
|
5
|
+
// real one.
|
|
6
|
+
//
|
|
7
|
+
// `belt deploy frontend` publishes the app's routes (src/seo.js) to the
|
|
8
|
+
// KeyValueStore associated with this function:
|
|
9
|
+
//
|
|
10
|
+
// belt:routes number of chunks
|
|
11
|
+
// belt:routes:N chunk N of the JSON { "app": [...], "pages": [...], "objects": {...} }
|
|
12
|
+
// (a KeyValueStore value holds 1 KB, so the JSON is split)
|
|
13
|
+
//
|
|
14
|
+
// `pages` are prerendered public pages, stored in S3 at their extensionless key
|
|
15
|
+
// unless `objects` names another object for that path ("/" included).
|
|
16
|
+
// `app` are patterns for the addresses the single-page app routes itself, read
|
|
17
|
+
// from its <Route path> declarations and seo.privatePaths: `*` is any one
|
|
18
|
+
// segment, a trailing `**` is anything from there on.
|
|
19
|
+
//
|
|
20
|
+
// a page → served from its own object
|
|
21
|
+
// an app route → /index.html
|
|
22
|
+
// anything else → /404.html, with status 404
|
|
23
|
+
// a path with a file extension (/assets/x.js, /robots.txt) → untouched
|
|
24
|
+
//
|
|
25
|
+
// CloudFront's JavaScript engine is not Node: among other gaps it rejects `await`
|
|
26
|
+
// inside a call's arguments or a condition. Keep every await as its own
|
|
27
|
+
// `const x = await ...` statement (spec/belt/frontend/router_spec.rb checks).
|
|
28
|
+
//
|
|
29
|
+
// Until routes have been published, or if the store can't be read, every request
|
|
30
|
+
// passes through untouched and the distribution's custom error responses serve
|
|
31
|
+
// index.html, exactly as before this function existed.
|
|
32
|
+
import cf from 'cloudfront';
|
|
33
|
+
|
|
34
|
+
const NOT_FOUND = '/404.html';
|
|
35
|
+
|
|
36
|
+
async function loadRoutes() {
|
|
37
|
+
try {
|
|
38
|
+
const kvs = cf.kvs();
|
|
39
|
+
const header = await kvs.get('belt:routes');
|
|
40
|
+
const count = parseInt(header, 10);
|
|
41
|
+
const reads = [];
|
|
42
|
+
for (let i = 0; i < count; i++) reads.push(kvs.get('belt:routes:' + i));
|
|
43
|
+
const chunks = await Promise.all(reads);
|
|
44
|
+
return JSON.parse(chunks.join(''));
|
|
45
|
+
} catch (error) {
|
|
46
|
+
return null;
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function hasExtension(uri) {
|
|
51
|
+
return uri.substring(uri.lastIndexOf('/') + 1).indexOf('.') !== -1;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
// Where a request goes: null to leave it alone, or the object to serve.
|
|
55
|
+
async function resolve(uri) {
|
|
56
|
+
if (hasExtension(uri)) return null;
|
|
57
|
+
const path = uri.replace(/\/+$/, '');
|
|
58
|
+
const routes = await loadRoutes();
|
|
59
|
+
if (!routes) return null;
|
|
60
|
+
|
|
61
|
+
const objects = routes.objects || {};
|
|
62
|
+
if (path === '') return objects['/'] || null;
|
|
63
|
+
if (routes.pages.indexOf(path) !== -1) return objects[path] || path;
|
|
64
|
+
for (let i = 0; i < routes.app.length; i++) {
|
|
65
|
+
if (matches(routes.app[i], path)) return '/index.html';
|
|
66
|
+
}
|
|
67
|
+
return NOT_FOUND;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function matches(pattern, path) {
|
|
71
|
+
const want = pattern.split('/');
|
|
72
|
+
const have = path.split('/');
|
|
73
|
+
for (let i = 0; i < want.length; i++) {
|
|
74
|
+
if (want[i] === '**') return true;
|
|
75
|
+
if (i >= have.length) return false;
|
|
76
|
+
if (want[i] !== '*' && want[i] !== have[i]) return false;
|
|
77
|
+
}
|
|
78
|
+
return want.length === have.length;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
// An error thrown from a CloudFront Function is a 503 for the visitor, so
|
|
82
|
+
// anything unexpected leaves the request or response as it came.
|
|
83
|
+
async function handler(event) {
|
|
84
|
+
const request = event.request;
|
|
85
|
+
|
|
86
|
+
if (event.context.eventType === 'viewer-request') {
|
|
87
|
+
try {
|
|
88
|
+
const target = await resolve(request.uri);
|
|
89
|
+
if (target) request.uri = target;
|
|
90
|
+
} catch (error) {
|
|
91
|
+
console.log('belt router: ' + error);
|
|
92
|
+
}
|
|
93
|
+
return request;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
// viewer-response. The request here may carry the original address or the one
|
|
97
|
+
// the viewer-request run rewrote, so both are checked. Only a 200 is changed:
|
|
98
|
+
// a 304 revalidation of the 404 page has to stay a 304.
|
|
99
|
+
const response = event.response;
|
|
100
|
+
try {
|
|
101
|
+
if (response.statusCode !== 200) return response;
|
|
102
|
+
let target = request.uri;
|
|
103
|
+
if (target !== NOT_FOUND) target = await resolve(request.uri);
|
|
104
|
+
if (target === NOT_FOUND) {
|
|
105
|
+
response.statusCode = 404;
|
|
106
|
+
response.statusDescription = 'Not Found';
|
|
107
|
+
}
|
|
108
|
+
} catch (error) {
|
|
109
|
+
console.log('belt router: ' + error);
|
|
110
|
+
}
|
|
111
|
+
return response;
|
|
112
|
+
}
|
data/lib/belt/version.rb
CHANGED
|
@@ -1,11 +1,13 @@
|
|
|
1
1
|
import { Routes, Route } from 'react-router-dom'
|
|
2
2
|
import Home from './pages/Home'
|
|
3
|
+
import NotFound from './pages/NotFound'
|
|
3
4
|
|
|
4
5
|
// The router lives in main.jsx (browser) and entry-server.jsx (prerender).
|
|
5
6
|
function App() {
|
|
6
7
|
return (
|
|
7
8
|
<Routes>
|
|
8
9
|
<Route path="/" element={<Home />} />
|
|
10
|
+
<Route path="*" element={<NotFound />} />
|
|
9
11
|
</Routes>
|
|
10
12
|
)
|
|
11
13
|
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { Link } from 'react-router-dom'
|
|
2
|
+
|
|
3
|
+
// Shown for any address the app has no route for. `belt deploy frontend`
|
|
4
|
+
// prerenders it to 404.html, which CloudFront serves with HTTP 404, so crawlers
|
|
5
|
+
// and agents can tell a missing page from a real one.
|
|
6
|
+
function NotFound() {
|
|
7
|
+
return (
|
|
8
|
+
<main style={{ maxWidth: '36rem', margin: '4rem auto', padding: '0 1.5rem', fontFamily: 'system-ui, sans-serif' }}>
|
|
9
|
+
<h1>Page not found</h1>
|
|
10
|
+
<p>There is no page at this address.</p>
|
|
11
|
+
<p>
|
|
12
|
+
<Link to="/">Back to the home page</Link>
|
|
13
|
+
</p>
|
|
14
|
+
</main>
|
|
15
|
+
)
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export default NotFound
|
|
@@ -11,6 +11,10 @@
|
|
|
11
11
|
// - Every public route gets an entry in `pages` with a specific title and a
|
|
12
12
|
// one- or two-sentence description that says plainly what the page is.
|
|
13
13
|
// - Login-gated or app-only routes go in `privatePaths` (disallowed in robots.txt).
|
|
14
|
+
// - An address that is neither a page here nor a route of the app answers HTTP
|
|
15
|
+
// 404 with the app's "not found" page. The app's routes are read from its
|
|
16
|
+
// <Route path="/..."> declarations; a route declared any other way needs its
|
|
17
|
+
// prefix in `privatePaths` too, or a fresh load of it answers 404.
|
|
14
18
|
// - Only `indexableEnvironments` are indexable. Every other environment, and
|
|
15
19
|
// local builds, ship `Disallow: /` and <meta name="robots" content="noindex">
|
|
16
20
|
// so dev and ephemeral environments never end up in search results.
|
|
@@ -79,9 +79,22 @@ resource "aws_cloudfront_distribution" "<%= @tf_name %>" {
|
|
|
79
79
|
forward = "none"
|
|
80
80
|
}
|
|
81
81
|
}
|
|
82
|
+
|
|
83
|
+
# Real 404s — see the router resources below.
|
|
84
|
+
function_association {
|
|
85
|
+
event_type = "viewer-request"
|
|
86
|
+
function_arn = aws_cloudfront_function.<%= @tf_name %>_route_request.arn
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
function_association {
|
|
90
|
+
event_type = "viewer-response"
|
|
91
|
+
function_arn = aws_cloudfront_function.<%= @tf_name %>_route_response.arn
|
|
92
|
+
}
|
|
82
93
|
}
|
|
83
94
|
|
|
84
|
-
# SPA
|
|
95
|
+
# SPA fallback — serve index.html for a missing object. The router function
|
|
96
|
+
# sends unknown addresses to /404.html itself; this is what a path gets before
|
|
97
|
+
# routes have been published, and what a missing file (/assets/gone.js) gets.
|
|
85
98
|
custom_error_response {
|
|
86
99
|
error_code = 404
|
|
87
100
|
response_code = 200
|
|
@@ -114,6 +127,35 @@ resource "aws_cloudfront_distribution" "<%= @tf_name %>" {
|
|
|
114
127
|
}
|
|
115
128
|
}
|
|
116
129
|
|
|
130
|
+
# Real 404s. `belt deploy frontend` publishes the app's routes (frontend
|
|
131
|
+
# src/seo.js: `pages` and `privatePaths`) to this KeyValueStore, and the router
|
|
132
|
+
# function serves a page from its prerendered object, an app route from
|
|
133
|
+
# index.html, and anything else from /404.html with status 404. The same code
|
|
134
|
+
# runs on both events; <%= Belt::CLI::FrontendRoutes::ROUTER_FILE %> is belt's (refresh it with
|
|
135
|
+
# `belt frontend router`).
|
|
136
|
+
resource "aws_cloudfront_key_value_store" "<%= @tf_name %>_routes" {
|
|
137
|
+
name = "${var.app_name}-${var.environment}-<%= @bucket_slug %>-routes"
|
|
138
|
+
comment = "Routes published by belt deploy frontend"
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
resource "aws_cloudfront_function" "<%= @tf_name %>_route_request" {
|
|
142
|
+
name = "${var.app_name}-${var.environment}-<%= @bucket_slug %>-route-req"
|
|
143
|
+
runtime = "cloudfront-js-2.0"
|
|
144
|
+
comment = "Send each address to its page, the app, or the 404 page"
|
|
145
|
+
publish = true
|
|
146
|
+
key_value_store_associations = [aws_cloudfront_key_value_store.<%= @tf_name %>_routes.arn]
|
|
147
|
+
code = file("${path.module}/<%= Belt::CLI::FrontendRoutes::ROUTER_FILE %>")
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
resource "aws_cloudfront_function" "<%= @tf_name %>_route_response" {
|
|
151
|
+
name = "${var.app_name}-${var.environment}-<%= @bucket_slug %>-route-res"
|
|
152
|
+
runtime = "cloudfront-js-2.0"
|
|
153
|
+
comment = "Answer 404 for the 404 page"
|
|
154
|
+
publish = true
|
|
155
|
+
key_value_store_associations = [aws_cloudfront_key_value_store.<%= @tf_name %>_routes.arn]
|
|
156
|
+
code = file("${path.module}/<%= Belt::CLI::FrontendRoutes::ROUTER_FILE %>")
|
|
157
|
+
}
|
|
158
|
+
|
|
117
159
|
# S3 bucket policy — CloudFront OAC access only
|
|
118
160
|
resource "aws_s3_bucket_policy" "<%= @tf_name %>" {
|
|
119
161
|
bucket = aws_s3_bucket.<%= @tf_name %>.id
|
|
@@ -272,6 +272,11 @@ answer engines (`belt explain frontend`). When you add or change a public page:
|
|
|
272
272
|
- Add it to `frontend/src/seo.js` → `pages` with a specific `title` and a one- or
|
|
273
273
|
two-sentence `description` that names what the page is and who it's for.
|
|
274
274
|
- Put login-gated routes in `privatePaths` (they're disallowed in `robots.txt`).
|
|
275
|
+
- An address that is neither a page nor a route of the app answers HTTP 404. Belt
|
|
276
|
+
reads the app's routes from `<Route path="/...">` in `frontend/src`, so a normal
|
|
277
|
+
new route needs nothing. A route declared another way (nested relative path,
|
|
278
|
+
router config object) needs its prefix in `privatePaths`, or a fresh load of it
|
|
279
|
+
answers 404; `frontend/dist/.belt-routes.json` shows what belt found.
|
|
275
280
|
- Keep the page's content in the rendered markup — no `window`/`document`/
|
|
276
281
|
`localStorage` during render (use `useEffect`), and no content that only appears
|
|
277
282
|
after an API call if crawlers need to see it.
|
metadata
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
--- !ruby/object:Gem::Specification
|
|
2
2
|
name: belt
|
|
3
3
|
version: !ruby/object:Gem::Version
|
|
4
|
-
version: 0.6.
|
|
4
|
+
version: 0.6.11
|
|
5
5
|
platform: ruby
|
|
6
6
|
authors:
|
|
7
7
|
- Stowzilla
|
|
@@ -139,6 +139,7 @@ files:
|
|
|
139
139
|
- lib/belt/cli/frontend_env_map.rb
|
|
140
140
|
- lib/belt/cli/frontend_prerender.rb
|
|
141
141
|
- lib/belt/cli/frontend_registry.rb
|
|
142
|
+
- lib/belt/cli/frontend_routes.rb
|
|
142
143
|
- lib/belt/cli/frontend_setup_command.rb
|
|
143
144
|
- lib/belt/cli/generate_command.rb
|
|
144
145
|
- lib/belt/cli/generator_registry.rb
|
|
@@ -181,6 +182,7 @@ files:
|
|
|
181
182
|
- lib/belt/docs/testing.md
|
|
182
183
|
- lib/belt/errors.rb
|
|
183
184
|
- lib/belt/frontend/prerender.mjs
|
|
185
|
+
- lib/belt/frontend/router.js
|
|
184
186
|
- lib/belt/helpers/cors_origin.rb
|
|
185
187
|
- lib/belt/helpers/error_logging.rb
|
|
186
188
|
- lib/belt/helpers/response.rb
|
|
@@ -222,6 +224,7 @@ files:
|
|
|
222
224
|
- lib/templates/frontend/react/src/lib/apiClient.js.erb
|
|
223
225
|
- lib/templates/frontend/react/src/main.jsx
|
|
224
226
|
- lib/templates/frontend/react/src/pages/Home.jsx.erb
|
|
227
|
+
- lib/templates/frontend/react/src/pages/NotFound.jsx
|
|
225
228
|
- lib/templates/frontend/react/src/seo.js.erb
|
|
226
229
|
- lib/templates/frontend/react/vite.config.js
|
|
227
230
|
- lib/templates/frontend_infra/frontend.tf.erb
|