rosetack 0.0.0 → 0.1.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/.github/workflows/ci.yml +72 -0
- package/.github/workflows/release.yml +122 -0
- package/LICENSE +21 -0
- package/benchmark.ts +227 -0
- package/deploy/Dockerfile.node +25 -0
- package/deploy/Dockerfile.static +34 -0
- package/deploy/api/rosetack.ts +29 -0
- package/deploy/docker-compose.yml +33 -0
- package/deploy/fly.toml +28 -0
- package/deploy/vercel.json +13 -0
- package/example/public/favicon.ico +0 -0
- package/example/public/logo.svg +148 -0
- package/example/public/rose-mark-black.png +0 -0
- package/example/public/rose-mark.png +0 -0
- package/example/public/rose-mono.png +0 -0
- package/example/rosetack.config.js +10 -0
- package/example/src/locales/en.json +8 -0
- package/example/src/locales/zh.json +8 -0
- package/example/src/pages/404.rose +15 -0
- package/example/src/pages/500.rose +10 -0
- package/example/src/pages/[lang]/about.rose +40 -0
- package/example/src/pages/_layout.rose +33 -0
- package/example/src/pages/_middleware.rose +37 -0
- package/example/src/pages/about.rose +67 -0
- package/example/src/pages/admin.rose +27 -0
- package/example/src/pages/api/hello.rose +19 -0
- package/example/src/pages/api/login.rose +55 -0
- package/example/src/pages/api/posts.rose +80 -0
- package/example/src/pages/api/secret.rose +14 -0
- package/example/src/pages/blog/[id].rose +25 -0
- package/example/src/pages/broken.rose +16 -0
- package/example/src/pages/fresh.rose +22 -0
- package/example/src/pages/garden.rose +27 -0
- package/example/src/pages/index.rose +84 -0
- package/example/src/pages/sign.rose +45 -0
- package/example/src/pages/thorn.rose +23 -0
- package/example/src/pages/vault.rose +14 -0
- package/go.mod +3 -0
- package/main.go +470 -0
- package/package.json +32 -11
- package/src/FRAMEWORK_VERSION +1 -0
- package/src/cli/edge.ts +127 -0
- package/src/cli/index.ts +777 -0
- package/src/cli/shell.ts +284 -0
- package/src/compiler/index.ts +1990 -0
- package/src/runtime/index.ts +624 -0
- package/tools/release-notes.mjs +113 -0
- package/tsconfig.json +17 -0
- package/README.md +0 -3
- package/index.js +0 -12
package/main.go
ADDED
|
@@ -0,0 +1,470 @@
|
|
|
1
|
+
// rosetack single-binary server.
|
|
2
|
+
//
|
|
3
|
+
// Embeds the built site (dist/) into one static Go binary - no Node, no
|
|
4
|
+
// runtime dependencies, nothing to install on the target machine:
|
|
5
|
+
//
|
|
6
|
+
// npm run build
|
|
7
|
+
// go build -o rosetack-server .
|
|
8
|
+
// PORT=8080 ./rosetack-server
|
|
9
|
+
//
|
|
10
|
+
// Static routes are served from the embedded prerendered HTML (one request
|
|
11
|
+
// per page load, client bundle inlined). Text files are answered in the
|
|
12
|
+
// brotli bytes `rosetack build` precompressed (dist/<file>.br) - zero
|
|
13
|
+
// per-request compression CPU - with weak ETags so repeat visits cost a
|
|
14
|
+
// bodiless 304. Unknown paths fall back to index.html: the boot script
|
|
15
|
+
// detects the route mismatch and client-renders the requested route, so
|
|
16
|
+
// dynamic routes work without a server round-trip.
|
|
17
|
+
//
|
|
18
|
+
// Ops (innovation #34): every request writes one access line to stdout,
|
|
19
|
+
// /metrics answers the Prometheus text format, and UPSTREAM=<url> turns the
|
|
20
|
+
// binary into the static half of a hybrid deploy - POSTs (server actions)
|
|
21
|
+
// and unbaked /api routes are reverse-proxied to the Node/edge backend.
|
|
22
|
+
package main
|
|
23
|
+
|
|
24
|
+
import (
|
|
25
|
+
"bytes"
|
|
26
|
+
"compress/gzip"
|
|
27
|
+
"embed"
|
|
28
|
+
"encoding/json"
|
|
29
|
+
"fmt"
|
|
30
|
+
"hash/fnv"
|
|
31
|
+
"log"
|
|
32
|
+
"net/http"
|
|
33
|
+
"net/http/httputil"
|
|
34
|
+
"net/url"
|
|
35
|
+
"os"
|
|
36
|
+
"path"
|
|
37
|
+
"sort"
|
|
38
|
+
"strings"
|
|
39
|
+
"sync"
|
|
40
|
+
"sync/atomic"
|
|
41
|
+
"time"
|
|
42
|
+
)
|
|
43
|
+
|
|
44
|
+
//go:embed all:dist
|
|
45
|
+
var dist embed.FS
|
|
46
|
+
|
|
47
|
+
// The embedded FS is immutable, so every file is read and gzipped at most
|
|
48
|
+
// once: raw bytes and gzip bytes are both cached forever. Without this the
|
|
49
|
+
// server re-reads and re-gzips an ~11 KB document on every request - pure
|
|
50
|
+
// CPU burn and allocation churn for output that can never change.
|
|
51
|
+
// Brotli needs no cache at all: `rosetack build` writes dist/<file>.br next
|
|
52
|
+
// to every text file (innovation #28) and those exact bytes are served -
|
|
53
|
+
// zero per-request compression CPU, and the same wire size the Node server
|
|
54
|
+
// produces by compressing the file in memory.
|
|
55
|
+
var (
|
|
56
|
+
fileCache sync.Map // name -> []byte (nil when missing)
|
|
57
|
+
gzipCache sync.Map // name -> []byte
|
|
58
|
+
etagCache sync.Map // name -> string
|
|
59
|
+
)
|
|
60
|
+
|
|
61
|
+
func readDist(name string) ([]byte, bool) {
|
|
62
|
+
if v, ok := fileCache.Load(name); ok {
|
|
63
|
+
b, ok := v.([]byte)
|
|
64
|
+
return b, ok && b != nil
|
|
65
|
+
}
|
|
66
|
+
b, err := dist.ReadFile(name)
|
|
67
|
+
if err != nil {
|
|
68
|
+
fileCache.Store(name, nil)
|
|
69
|
+
return nil, false
|
|
70
|
+
}
|
|
71
|
+
fileCache.Store(name, b)
|
|
72
|
+
return b, true
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
func gzipBytes(body []byte) []byte {
|
|
76
|
+
var buf bytes.Buffer
|
|
77
|
+
gz := gzip.NewWriter(&buf)
|
|
78
|
+
_, _ = gz.Write(body)
|
|
79
|
+
_ = gz.Close()
|
|
80
|
+
return buf.Bytes()
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
// etagOf is a weak validator over the raw bytes (FNV-1a, stdlib): identical
|
|
84
|
+
// bytes always yield an identical tag, so a repeat visit with a matching
|
|
85
|
+
// If-None-Match is answered by a bodiless 304 - on the Node server too,
|
|
86
|
+
// which validates its static files the same way.
|
|
87
|
+
func etagOf(body []byte) string {
|
|
88
|
+
h := fnv.New32a()
|
|
89
|
+
_, _ = h.Write(body)
|
|
90
|
+
return fmt.Sprintf(`W/"%d-%x"`, len(body), h.Sum32())
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
func writeBody(w http.ResponseWriter, r *http.Request, name string, body []byte, encoding string, etag string) {
|
|
94
|
+
h := w.Header()
|
|
95
|
+
h.Set("Content-Type", mimeOf(name))
|
|
96
|
+
h.Set("Cache-Control", "public, max-age=3600")
|
|
97
|
+
h.Set("ETag", etag)
|
|
98
|
+
h.Set("Vary", "Accept-Encoding")
|
|
99
|
+
// Per-route response headers (innovation #26) ride HTML documents only:
|
|
100
|
+
// the strict CSP hashes the exact inlined bundle, and a route's exported
|
|
101
|
+
// headers (a tighter CSP, x-robots-tag, ...) win over it. Assets and
|
|
102
|
+
// baked API bodies carry no page headers.
|
|
103
|
+
if strings.HasPrefix(mimeOf(name), "text/html") {
|
|
104
|
+
for k, v := range headersFor(r.URL.Path) {
|
|
105
|
+
h.Set(k, v)
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
// A matching revalidator answers 304 with the same headers and no body.
|
|
109
|
+
if r.Header.Get("If-None-Match") == etag {
|
|
110
|
+
w.WriteHeader(http.StatusNotModified)
|
|
111
|
+
return
|
|
112
|
+
}
|
|
113
|
+
if encoding != "" {
|
|
114
|
+
h.Set("Content-Encoding", encoding)
|
|
115
|
+
}
|
|
116
|
+
_, _ = w.Write(body)
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
// serveFile writes the embedded file to w - build-precompressed brotli when
|
|
120
|
+
// the client accepts it, else the cached gzip, else raw. Returns false
|
|
121
|
+
// (writing nothing) when the file does not exist, so the caller can try the
|
|
122
|
+
// next candidate.
|
|
123
|
+
func serveFile(w http.ResponseWriter, r *http.Request, name string) bool {
|
|
124
|
+
// Precompression siblings are internal build artifacts (innovation #28):
|
|
125
|
+
// a direct request for dist/<file>.br must not answer raw brotli bytes
|
|
126
|
+
// labeled as the page - it falls through to the real file (or the SPA
|
|
127
|
+
// shell). A real asset that merely ends .br/.gz (no base file) serves.
|
|
128
|
+
if base, ok := strings.CutSuffix(name, ".br"); ok {
|
|
129
|
+
if _, ok := readDist(base); ok {
|
|
130
|
+
return false
|
|
131
|
+
}
|
|
132
|
+
} else if base, ok := strings.CutSuffix(name, ".gz"); ok {
|
|
133
|
+
if _, ok := readDist(base); ok {
|
|
134
|
+
return false
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
body, ok := readDist(name)
|
|
138
|
+
if !ok {
|
|
139
|
+
return false
|
|
140
|
+
}
|
|
141
|
+
etag, _ := etagCache.LoadOrStore(name, etagOf(body))
|
|
142
|
+
tag := etag.(string)
|
|
143
|
+
ae := r.Header.Get("Accept-Encoding")
|
|
144
|
+
if strings.Contains(ae, "br") {
|
|
145
|
+
if br, ok := readDist(name + ".br"); ok {
|
|
146
|
+
writeBody(w, r, name, br, "br", tag)
|
|
147
|
+
return true
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
if strings.Contains(ae, "gzip") {
|
|
151
|
+
gz, _ := gzipCache.LoadOrStore(name, gzipBytes(body))
|
|
152
|
+
writeBody(w, r, name, gz.([]byte), "gzip", tag)
|
|
153
|
+
return true
|
|
154
|
+
}
|
|
155
|
+
writeBody(w, r, name, body, "", tag)
|
|
156
|
+
return true
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
var mimeTypes = map[string]string{
|
|
160
|
+
".html": "text/html; charset=utf-8",
|
|
161
|
+
".js": "text/javascript; charset=utf-8",
|
|
162
|
+
".mjs": "text/javascript; charset=utf-8",
|
|
163
|
+
".css": "text/css; charset=utf-8",
|
|
164
|
+
".json": "application/json; charset=utf-8",
|
|
165
|
+
".svg": "image/svg+xml",
|
|
166
|
+
".png": "image/png",
|
|
167
|
+
".jpg": "image/jpeg",
|
|
168
|
+
".jpeg": "image/jpeg",
|
|
169
|
+
".gif": "image/gif",
|
|
170
|
+
".webp": "image/webp",
|
|
171
|
+
".ico": "image/x-icon",
|
|
172
|
+
".woff": "font/woff",
|
|
173
|
+
".woff2": "font/woff2",
|
|
174
|
+
".txt": "text/plain; charset=utf-8",
|
|
175
|
+
".map": "application/json; charset=utf-8",
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
func mimeOf(name string) string {
|
|
179
|
+
if m, ok := mimeTypes[strings.ToLower(path.Ext(name))]; ok {
|
|
180
|
+
return m
|
|
181
|
+
}
|
|
182
|
+
return "application/octet-stream"
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
// Per-route response headers (innovation #26). dist/headers.json is written
|
|
186
|
+
// by `rosetack build`: `default` carries the strict CSP (the CLI hashed the
|
|
187
|
+
// exact inlined bundle + bootstrap bytes - this binary has no esbuild to
|
|
188
|
+
// recompute them), and `routes` carries each route's exported headers.
|
|
189
|
+
type headerRule struct {
|
|
190
|
+
Pattern string `json:"pattern"`
|
|
191
|
+
Headers map[string]string `json:"headers"`
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
type headerConfig struct {
|
|
195
|
+
Default map[string]string `json:"default"`
|
|
196
|
+
Routes []headerRule `json:"routes"`
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
var routeHeaders headerConfig
|
|
200
|
+
|
|
201
|
+
func loadRouteHeaders() {
|
|
202
|
+
b, err := dist.ReadFile("dist/headers.json")
|
|
203
|
+
if err != nil {
|
|
204
|
+
return // no build data: responses carry the framework defaults alone
|
|
205
|
+
}
|
|
206
|
+
_ = json.Unmarshal(b, &routeHeaders)
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
// matchPattern mirrors the compiler's matchRoute: equal segment counts, a
|
|
210
|
+
// ':' segment matches anything.
|
|
211
|
+
func matchPattern(pattern, pathname string) bool {
|
|
212
|
+
pp := strings.Split(pattern, "/")
|
|
213
|
+
xp := strings.Split(pathname, "/")
|
|
214
|
+
if len(pp) != len(xp) {
|
|
215
|
+
return false
|
|
216
|
+
}
|
|
217
|
+
for i := range pp {
|
|
218
|
+
if strings.HasPrefix(pp[i], ":") {
|
|
219
|
+
continue
|
|
220
|
+
}
|
|
221
|
+
if pp[i] != xp[i] {
|
|
222
|
+
return false
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
return true
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
// headersFor merges the default headers with every matching route's
|
|
229
|
+
// headers, in file order: a later route wins on conflict, so a route
|
|
230
|
+
// overrides the strict CSP when it exports one. Keys are lower-cased:
|
|
231
|
+
// HTTP header names are case-insensitive, and map iteration order is
|
|
232
|
+
// random - an overridden header must not survive under a second spelling.
|
|
233
|
+
// The merged map is cached per pathname: routeHeaders is immutable after
|
|
234
|
+
// boot (loadRouteHeaders runs once in main), so the answer for a path can
|
|
235
|
+
// never change - this is one map lookup per request instead of a merge.
|
|
236
|
+
var headerCache sync.Map // pathname -> map[string]string
|
|
237
|
+
|
|
238
|
+
func headersFor(pathname string) map[string]string {
|
|
239
|
+
if v, ok := headerCache.Load(pathname); ok {
|
|
240
|
+
m, _ := v.(map[string]string)
|
|
241
|
+
return m
|
|
242
|
+
}
|
|
243
|
+
if len(routeHeaders.Default) == 0 && len(routeHeaders.Routes) == 0 {
|
|
244
|
+
return nil
|
|
245
|
+
}
|
|
246
|
+
out := make(map[string]string, len(routeHeaders.Default)+4)
|
|
247
|
+
for k, v := range routeHeaders.Default {
|
|
248
|
+
out[strings.ToLower(k)] = v
|
|
249
|
+
}
|
|
250
|
+
for _, r := range routeHeaders.Routes {
|
|
251
|
+
if matchPattern(r.Pattern, pathname) {
|
|
252
|
+
for k, v := range r.Headers {
|
|
253
|
+
out[strings.ToLower(k)] = v
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
headerCache.Store(pathname, out)
|
|
258
|
+
return out
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
// ---- observability (innovation #34) ---------------------------------------
|
|
262
|
+
//
|
|
263
|
+
// The binary used to answer requests and say nothing: no access log, no
|
|
264
|
+
// metrics, no error trail - fine for a demo, unshippable in production.
|
|
265
|
+
// Everything below is stdlib: one ResponseWriter wrapper, atomic counters,
|
|
266
|
+
// one text endpoint. ponytail: counters + a duration sum/count pair (an
|
|
267
|
+
// average, not a histogram - a scrape endpoint is not where you burn memory
|
|
268
|
+
// on buckets nobody asked for; add a histogram when a real dashboard asks).
|
|
269
|
+
|
|
270
|
+
// statusWriter captures what the handler wrote: http.ResponseWriter exposes
|
|
271
|
+
// neither the status code nor the byte count, and the access log needs both.
|
|
272
|
+
type statusWriter struct {
|
|
273
|
+
http.ResponseWriter
|
|
274
|
+
status int
|
|
275
|
+
bytes int
|
|
276
|
+
proxied bool
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
func (s *statusWriter) WriteHeader(code int) { s.status = code; s.ResponseWriter.WriteHeader(code) }
|
|
280
|
+
|
|
281
|
+
func (s *statusWriter) Write(b []byte) (int, error) {
|
|
282
|
+
if s.status == 0 {
|
|
283
|
+
s.status = http.StatusOK
|
|
284
|
+
}
|
|
285
|
+
n, err := s.ResponseWriter.Write(b)
|
|
286
|
+
s.bytes += n
|
|
287
|
+
return n, err
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
var (
|
|
291
|
+
reqTotal sync.Map // status code -> *atomic.Uint64
|
|
292
|
+
durSumNS atomic.Int64
|
|
293
|
+
reqCount atomic.Int64
|
|
294
|
+
inFlight atomic.Int64
|
|
295
|
+
bootTime = time.Now()
|
|
296
|
+
accessLog = log.New(os.Stdout, "", 0) // one greppable line per request
|
|
297
|
+
)
|
|
298
|
+
|
|
299
|
+
func countStatus(code int) {
|
|
300
|
+
v, _ := reqTotal.LoadOrStore(code, &atomic.Uint64{})
|
|
301
|
+
v.(*atomic.Uint64).Add(1)
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
// observe wraps the handler: in-flight gauge, status/duration counters, and
|
|
305
|
+
// the access line. /metrics is counted like any other request - scraping is
|
|
306
|
+
// traffic too, and hiding it just loses data.
|
|
307
|
+
func observe(next http.HandlerFunc) http.HandlerFunc {
|
|
308
|
+
return func(w http.ResponseWriter, r *http.Request) {
|
|
309
|
+
sw := &statusWriter{ResponseWriter: w}
|
|
310
|
+
inFlight.Add(1)
|
|
311
|
+
defer inFlight.Add(-1)
|
|
312
|
+
start := time.Now()
|
|
313
|
+
next(sw, r)
|
|
314
|
+
code := sw.status
|
|
315
|
+
if code == 0 {
|
|
316
|
+
code = http.StatusOK
|
|
317
|
+
}
|
|
318
|
+
countStatus(code)
|
|
319
|
+
reqCount.Add(1)
|
|
320
|
+
durSumNS.Add(time.Since(start).Nanoseconds())
|
|
321
|
+
via := ""
|
|
322
|
+
if sw.proxied {
|
|
323
|
+
via = " via=upstream"
|
|
324
|
+
}
|
|
325
|
+
accessLog.Printf("%s %s %s %d %dB %s%s",
|
|
326
|
+
start.UTC().Format(time.RFC3339), r.Method, r.URL.Path, code, sw.bytes,
|
|
327
|
+
time.Since(start).Round(time.Microsecond), via)
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
// metricsHandler answers the Prometheus text exposition format (v0.0.4):
|
|
332
|
+
// requests per status code, a duration sum/count pair (average = sum/count),
|
|
333
|
+
// the in-flight gauge and uptime - everything a scrape needs to alert on.
|
|
334
|
+
func metricsHandler(w http.ResponseWriter, r *http.Request) {
|
|
335
|
+
w.Header().Set("Content-Type", "text/plain; version=0.0.4; charset=utf-8")
|
|
336
|
+
var b strings.Builder
|
|
337
|
+
b.WriteString("# HELP rosetack_http_requests_total Total HTTP requests by status code.\n")
|
|
338
|
+
b.WriteString("# TYPE rosetack_http_requests_total counter\n")
|
|
339
|
+
codes := make([]int, 0, 8)
|
|
340
|
+
reqTotal.Range(func(k, _ any) bool { codes = append(codes, k.(int)); return true })
|
|
341
|
+
sort.Ints(codes) // sync.Map iterates in random order; a scrape must be stable
|
|
342
|
+
for _, c := range codes {
|
|
343
|
+
v, _ := reqTotal.Load(c)
|
|
344
|
+
fmt.Fprintf(&b, "rosetack_http_requests_total{code=\"%d\"} %d\n", c, v.(*atomic.Uint64).Load())
|
|
345
|
+
}
|
|
346
|
+
b.WriteString("# HELP rosetack_http_request_duration_seconds Request duration sum and count.\n")
|
|
347
|
+
b.WriteString("# TYPE rosetack_http_request_duration_seconds summary\n")
|
|
348
|
+
fmt.Fprintf(&b, "rosetack_http_request_duration_seconds_sum %.6f\n", float64(durSumNS.Load())/1e9)
|
|
349
|
+
fmt.Fprintf(&b, "rosetack_http_request_duration_seconds_count %d\n", reqCount.Load())
|
|
350
|
+
b.WriteString("# HELP rosetack_http_requests_in_flight Requests currently being served.\n")
|
|
351
|
+
b.WriteString("# TYPE rosetack_http_requests_in_flight gauge\n")
|
|
352
|
+
fmt.Fprintf(&b, "rosetack_http_requests_in_flight %d\n", inFlight.Load())
|
|
353
|
+
b.WriteString("# HELP rosetack_uptime_seconds Process uptime.\n")
|
|
354
|
+
b.WriteString("# TYPE rosetack_uptime_seconds gauge\n")
|
|
355
|
+
fmt.Fprintf(&b, "rosetack_uptime_seconds %.3f\n", time.Since(bootTime).Seconds())
|
|
356
|
+
_, _ = w.Write([]byte(b.String()))
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
// ---- the hybrid deploy (innovation #34, consultant P0 §3, 方案B) ----------
|
|
360
|
+
//
|
|
361
|
+
// The binary is immutable by design: it serves exactly what the build baked.
|
|
362
|
+
// A real app also has live routes - POST server actions, /api handlers that
|
|
363
|
+
// read a database, middleware that reads cookies. Those need a JS runtime,
|
|
364
|
+
// and the honest answer is NOT to bolt one on (goja would double the binary
|
|
365
|
+
// and re-implement a language): point the binary at the Node server and let
|
|
366
|
+
// each half do what it is good at.
|
|
367
|
+
//
|
|
368
|
+
// UPSTREAM=http://dynamic:3000 ./rosetack-server
|
|
369
|
+
//
|
|
370
|
+
// With UPSTREAM set, everything the static half cannot answer itself is
|
|
371
|
+
// reverse-proxied there: any non-GET/HEAD method (server actions, form
|
|
372
|
+
// POSTs) and any /api path without a baked body. Without UPSTREAM the
|
|
373
|
+
// behavior is exactly what it always was - 405 for POSTs, the JSON 404 for
|
|
374
|
+
// unbaked APIs - so the pure-static deploy keeps its contract byte for byte.
|
|
375
|
+
|
|
376
|
+
var upstreamProxy *httputil.ReverseProxy
|
|
377
|
+
|
|
378
|
+
func setupUpstream() {
|
|
379
|
+
u := os.Getenv("UPSTREAM")
|
|
380
|
+
if u == "" {
|
|
381
|
+
return
|
|
382
|
+
}
|
|
383
|
+
target, err := url.Parse(u)
|
|
384
|
+
if err != nil {
|
|
385
|
+
log.Fatalf("rosetack: UPSTREAM %q is not a URL: %v", u, err)
|
|
386
|
+
}
|
|
387
|
+
upstreamProxy = httputil.NewSingleHostReverseProxy(target)
|
|
388
|
+
upstreamProxy.ErrorHandler = func(w http.ResponseWriter, r *http.Request, err error) {
|
|
389
|
+
// The error trail: a dead backend must be visible in the logs, not
|
|
390
|
+
// silently turned into a 502 nobody can explain.
|
|
391
|
+
log.Printf("rosetack error: upstream %s failed for %s %s: %v", u, r.Method, r.URL.Path, err)
|
|
392
|
+
http.Error(w, "upstream unavailable", http.StatusBadGateway)
|
|
393
|
+
}
|
|
394
|
+
log.Printf("rosetack: hybrid mode - non-GET requests and unbaked /api routes proxy to %s", u)
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
func proxyUpstream(w http.ResponseWriter, r *http.Request) {
|
|
398
|
+
if sw, ok := w.(*statusWriter); ok {
|
|
399
|
+
sw.proxied = true // the access line says where the answer came from
|
|
400
|
+
}
|
|
401
|
+
upstreamProxy.ServeHTTP(w, r)
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
func handler(w http.ResponseWriter, r *http.Request) {
|
|
405
|
+
// /metrics is this binary's own endpoint (innovation #34): it must be
|
|
406
|
+
// answered before the file candidates, or the SPA fallback would hand
|
|
407
|
+
// the HTML shell to every scraper.
|
|
408
|
+
if r.URL.Path == "/metrics" {
|
|
409
|
+
metricsHandler(w, r)
|
|
410
|
+
return
|
|
411
|
+
}
|
|
412
|
+
// Hybrid mode (innovation #34): the static half cannot run a POST, so a
|
|
413
|
+
// server action or a form submit goes to the Node/edge backend.
|
|
414
|
+
if upstreamProxy != nil && r.Method != http.MethodGet && r.Method != http.MethodHead {
|
|
415
|
+
proxyUpstream(w, r)
|
|
416
|
+
return
|
|
417
|
+
}
|
|
418
|
+
if r.Method != http.MethodGet && r.Method != http.MethodHead {
|
|
419
|
+
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
|
|
420
|
+
return
|
|
421
|
+
}
|
|
422
|
+
p := path.Clean(r.URL.Path)
|
|
423
|
+
if p == "." || p == "/" {
|
|
424
|
+
p = "/index.html"
|
|
425
|
+
}
|
|
426
|
+
// exact file, directory index, extension-less route, or a baked API body
|
|
427
|
+
// (dist/api/<route>.json, written at build time by `prerender = true`)
|
|
428
|
+
candidates := []string{"dist" + p, "dist" + p + "/index.html", "dist" + p + ".html", "dist" + p + ".json"}
|
|
429
|
+
// A file in public/ answers at the root as well (see the Node servers).
|
|
430
|
+
if strings.HasSuffix(p, ".png") || strings.HasSuffix(p, ".svg") || strings.HasSuffix(p, ".ico") || strings.HasSuffix(p, ".webp") || strings.HasSuffix(p, ".jpg") {
|
|
431
|
+
candidates = append(candidates, "dist/public"+p)
|
|
432
|
+
}
|
|
433
|
+
for _, c := range candidates {
|
|
434
|
+
if serveFile(w, r, c) {
|
|
435
|
+
return
|
|
436
|
+
}
|
|
437
|
+
}
|
|
438
|
+
// The /api namespace answers JSON, never the SPA shell: an API client that
|
|
439
|
+
// hits an unbaked route must not receive HTML. Live handlers run on the
|
|
440
|
+
// Node/edge server; this binary only carries GET bodies baked at build -
|
|
441
|
+
// unless UPSTREAM points at that server, in which case the live handler
|
|
442
|
+
// answers (innovation #34).
|
|
443
|
+
if p == "/api" || strings.HasPrefix(p, "/api/") {
|
|
444
|
+
if upstreamProxy != nil {
|
|
445
|
+
proxyUpstream(w, r)
|
|
446
|
+
return
|
|
447
|
+
}
|
|
448
|
+
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
|
449
|
+
w.WriteHeader(http.StatusNotFound)
|
|
450
|
+
_, _ = w.Write([]byte(`{"error":"api route is not baked into this binary; run it on the Node or edge server"}`))
|
|
451
|
+
return
|
|
452
|
+
}
|
|
453
|
+
// SPA fallback: serve the shell; the boot script client-renders the route.
|
|
454
|
+
if serveFile(w, r, "dist/index.html") {
|
|
455
|
+
return
|
|
456
|
+
}
|
|
457
|
+
http.NotFound(w, r)
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
func main() {
|
|
461
|
+
loadRouteHeaders()
|
|
462
|
+
setupUpstream()
|
|
463
|
+
port := os.Getenv("PORT")
|
|
464
|
+
if port == "" {
|
|
465
|
+
port = "8080"
|
|
466
|
+
}
|
|
467
|
+
http.HandleFunc("/", observe(handler))
|
|
468
|
+
log.Printf("rosetack single-binary server listening on :%s", port)
|
|
469
|
+
log.Fatal(http.ListenAndServe(":"+port, nil))
|
|
470
|
+
}
|
package/package.json
CHANGED
|
@@ -1,20 +1,41 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "rosetack",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "
|
|
5
|
-
"
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Zero-hydration full-stack web framework with compile-time reactivity and zero-JS content routes.",
|
|
5
|
+
"type": "module",
|
|
6
6
|
"scripts": {
|
|
7
|
-
"
|
|
7
|
+
"dev": "tsx src/cli/index.ts dev example",
|
|
8
|
+
"build": "tsx src/cli/index.ts build example",
|
|
9
|
+
"preview": "tsx src/cli/index.ts preview example",
|
|
10
|
+
"serve": "tsx src/cli/index.ts serve example",
|
|
11
|
+
"release:notes": "node tools/release-notes.mjs",
|
|
12
|
+
"benchmark": "tsx benchmark.ts",
|
|
13
|
+
"test": "tsx src/cli/index.ts build example && tsx test-client.ts",
|
|
14
|
+
"test:cli": "node test-cli.mjs",
|
|
15
|
+
"test:e2e": "tsx test-e2e.ts",
|
|
16
|
+
"test:edge": "tsx test-edge.ts",
|
|
17
|
+
"test:go": "tsx src/cli/index.ts build example && node test-go.mjs",
|
|
18
|
+
"build:go": "go build -o rosetack-server ."
|
|
19
|
+
},
|
|
20
|
+
"dependencies": {
|
|
21
|
+
"esbuild": "^0.24.0"
|
|
22
|
+
},
|
|
23
|
+
"devDependencies": {
|
|
24
|
+
"@types/node": "^22.0.0",
|
|
25
|
+
"jsdom": "^29.1.1",
|
|
26
|
+
"tsx": "^4.7.0",
|
|
27
|
+
"typescript": "^5.6.0"
|
|
28
|
+
},
|
|
29
|
+
"author": {
|
|
30
|
+
"name": "xdunli",
|
|
31
|
+
"url": "https://github.com/xdunli"
|
|
8
32
|
},
|
|
9
33
|
"repository": {
|
|
10
34
|
"type": "git",
|
|
11
|
-
"url": "git+https://github.com/
|
|
35
|
+
"url": "git+https://github.com/xdunli/rosetack.git"
|
|
12
36
|
},
|
|
13
|
-
"
|
|
14
|
-
"author": "",
|
|
15
|
-
"license": "MIT",
|
|
37
|
+
"homepage": "https://github.com/xdunli/rosetack#readme",
|
|
16
38
|
"bugs": {
|
|
17
|
-
"url": "https://github.com/
|
|
18
|
-
}
|
|
19
|
-
"homepage": "https://github.com/neodunli/rosetack#readme"
|
|
39
|
+
"url": "https://github.com/xdunli/rosetack/issues"
|
|
40
|
+
}
|
|
20
41
|
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
0.1.0
|
package/src/cli/edge.ts
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* rosetack Edge adapter - Web-standard fetch handler.
|
|
3
|
+
*
|
|
4
|
+
* Works on any edge runtime that supports the Fetch API standard
|
|
5
|
+
* (Cloudflare Workers, Deno Deploy, Vercel Edge, Bun, Node 18+):
|
|
6
|
+
*
|
|
7
|
+
* import { createEdgeHandler } from 'rosetack/edge';
|
|
8
|
+
* const handle = createEdgeHandler('./dist');
|
|
9
|
+
* export default { fetch: handle };
|
|
10
|
+
*
|
|
11
|
+
* The generated dist/server.js has zero Node built-in imports, so the same
|
|
12
|
+
* bundle that runs the Node server runs at the edge. Static routes can be
|
|
13
|
+
* served by the platform's asset layer; everything else renders on demand.
|
|
14
|
+
* GETs to known routes stream (the static shell flushes before the render
|
|
15
|
+
* completes, still one request); routes known-broken at build time
|
|
16
|
+
* (dist/broken.json) stay buffered so their real 500 status survives, and
|
|
17
|
+
* csr = false routes buffer so their document is complete without a client.
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
import { pathToFileURL } from 'url';
|
|
21
|
+
import { join } from 'path';
|
|
22
|
+
import { buildShell, shellOpen, clientScriptTag, securityHeaders } from './shell.js';
|
|
23
|
+
|
|
24
|
+
type ServerModule = {
|
|
25
|
+
renderPage(pathname: string, form?: FormData): Promise<{ html: string; state: string; head: string[]; status?: number; csr?: boolean }>;
|
|
26
|
+
renderPageStream(pathname: string, write: (chunk: string) => void, shellOpen: string, clientTag: string): Promise<number>;
|
|
27
|
+
canStream(pathname: string): boolean;
|
|
28
|
+
isNoJs(pathname: string): boolean;
|
|
29
|
+
isApi(pathname: string): boolean;
|
|
30
|
+
handleApi(method: string, pathname: string, request: Request): Promise<Response>;
|
|
31
|
+
/** pages/_middleware.rose's handler, or null when the project has none */
|
|
32
|
+
middleware: ((request: Request) => Promise<Response | void | null>) | null;
|
|
33
|
+
/** run the middleware once per request; returns its short-circuit Response or null */
|
|
34
|
+
runMiddleware(rawReq: any, form?: FormData): Promise<Response | null>;
|
|
35
|
+
/** routes whose component reads getContext(): never prerendered, always live */
|
|
36
|
+
dynamicRoutes: string[];
|
|
37
|
+
/** per-route response headers (innovation #26), [] when no route exports any */
|
|
38
|
+
routeHeaders: Array<{ pattern: string; headers: Record<string, string> }>;
|
|
39
|
+
/** the route's own exported headers for a pathname, or null */
|
|
40
|
+
headersFor(pathname: string): Record<string, string> | null;
|
|
41
|
+
};
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Create a fetch handler from a built rosetack project.
|
|
45
|
+
* @param outDir directory containing server.js and client.js
|
|
46
|
+
*/
|
|
47
|
+
export async function createEdgeHandler(outDir: string): Promise<(request: Request) => Promise<Response>> {
|
|
48
|
+
const mod: ServerModule = await import(pathToFileURL(join(outDir, 'server.js')).href);
|
|
49
|
+
let client: string | null = null;
|
|
50
|
+
let styles = '';
|
|
51
|
+
try {
|
|
52
|
+
client = await (await import('fs/promises')).readFile(join(outDir, 'client.js'), 'utf-8');
|
|
53
|
+
} catch {
|
|
54
|
+
client = null; // no fs (Workers): platform should inline the bundle at deploy time
|
|
55
|
+
}
|
|
56
|
+
try {
|
|
57
|
+
styles = await (await import('fs/promises')).readFile(join(outDir, 'styles.css'), 'utf-8');
|
|
58
|
+
} catch {
|
|
59
|
+
styles = ''; // no component styles (or no fs): shell STYLES only
|
|
60
|
+
}
|
|
61
|
+
// routes whose render failed at build time: buffered, so the 500 survives
|
|
62
|
+
let broken = new Set<string>();
|
|
63
|
+
try {
|
|
64
|
+
broken = new Set(JSON.parse(await (await import('fs/promises')).readFile(join(outDir, 'broken.json'), 'utf-8')));
|
|
65
|
+
} catch {
|
|
66
|
+
broken = new Set(); // no manifest: nothing known-broken
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
// Response headers for a page document (innovation #26): the strict CSP hashed over the
|
|
70
|
+
// exact inlined bytes …
|
|
71
|
+
const pageHeaders = (pathname: string): Record<string, string> => {
|
|
72
|
+
const headers: Record<string, string> = {};
|
|
73
|
+
if (client) for (const [k, v] of Object.entries(securityHeaders(client))) headers[k.toLowerCase()] = v;
|
|
74
|
+
const own = mod.headersFor?.(pathname);
|
|
75
|
+
if (own) for (const [k, v] of Object.entries(own)) headers[k.toLowerCase()] = v;
|
|
76
|
+
return headers;
|
|
77
|
+
};
|
|
78
|
+
|
|
79
|
+
return async function handle(request: Request): Promise<Response> {
|
|
80
|
+
const { pathname } = new URL(request.url);
|
|
81
|
+
// Middleware (pages/_middleware.rose) runs exactly once per request, before anything
|
|
82
|
+
// else: a returned Response short-circuits the whole request (a redirect, an auth wall) …
|
|
83
|
+
if (mod.middleware) {
|
|
84
|
+
const mw = await mod.runMiddleware(request);
|
|
85
|
+
if (mw) return mw;
|
|
86
|
+
}
|
|
87
|
+
// API routes (pages/api/*.rose): the /api namespace answers JSON, never the HTML shell …
|
|
88
|
+
if (mod.isApi(pathname)) {
|
|
89
|
+
return mod.handleApi(request.method, pathname, request);
|
|
90
|
+
}
|
|
91
|
+
// POST: progressive-enhancement form - run the route's server action with
|
|
92
|
+
// the submitted FormData and re-render the page (works without JS).
|
|
93
|
+
const form = request.method === 'POST' ? await request.formData() : undefined;
|
|
94
|
+
// csr = false routes (innovation #25) buffer too: a streamed no-JS document would carry
|
|
95
|
+
// the shell's default <title> - the route head is applied client-side at boot …
|
|
96
|
+
if (!form && !broken.has(pathname) && mod.canStream(pathname) && !mod.isNoJs(pathname)) {
|
|
97
|
+
// streaming GET: one chunked Response, still exactly one request
|
|
98
|
+
const encoder = new TextEncoder();
|
|
99
|
+
const stream = new ReadableStream<Uint8Array>({
|
|
100
|
+
async start(controller) {
|
|
101
|
+
await mod.renderPageStream(
|
|
102
|
+
pathname,
|
|
103
|
+
(chunk) => controller.enqueue(encoder.encode(chunk)),
|
|
104
|
+
shellOpen(styles),
|
|
105
|
+
clientScriptTag(client)
|
|
106
|
+
);
|
|
107
|
+
controller.close();
|
|
108
|
+
}
|
|
109
|
+
});
|
|
110
|
+
return new Response(stream, {
|
|
111
|
+
status: 200,
|
|
112
|
+
headers: { 'content-type': 'text/html; charset=utf-8', ...pageHeaders(pathname) }
|
|
113
|
+
});
|
|
114
|
+
}
|
|
115
|
+
// buffered: POST actions, unmatched routes (404), known-broken routes (500).
|
|
116
|
+
// The middleware already ran at the top of this handler, so the render
|
|
117
|
+
// below sees its context.
|
|
118
|
+
const page = await mod.renderPage(pathname, form);
|
|
119
|
+
// js = page.csr !== false: a csr = false route ships no bundle, no state
|
|
120
|
+
// script - the document is HTML + CSS only (innovation #25)
|
|
121
|
+
const html = buildShell(page.html, page.state, client, page.head, styles, page.csr !== false);
|
|
122
|
+
return new Response(html, {
|
|
123
|
+
status: page.status ?? 200,
|
|
124
|
+
headers: { 'content-type': 'text/html; charset=utf-8', ...pageHeaders(pathname) }
|
|
125
|
+
});
|
|
126
|
+
};
|
|
127
|
+
}
|