@maxwellcohen/lastro 0.0.0-stage → 0.0.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.
Files changed (114) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +210 -2
  3. package/bin/lastro.js +5 -0
  4. package/bin/postinstall.js +6 -0
  5. package/docs/hero.png +0 -0
  6. package/package.json +355 -4
  7. package/pkg/devtools/index.js +15 -0
  8. package/pkg/eslint-config/index.js +123 -0
  9. package/pkg/head/client.js +18 -0
  10. package/pkg/head/index.d.ts +4 -0
  11. package/pkg/head/index.js +30 -0
  12. package/pkg/image/client.js +2 -0
  13. package/pkg/image/index.d.ts +3 -0
  14. package/pkg/image/index.js +2 -0
  15. package/pkg/image/stubs.js +8 -0
  16. package/pkg/image/tnenopmoCsdroW0001erutciP____.client.js +18 -0
  17. package/pkg/image/tnenopmoCsdroW0001erutciP____.js +27 -0
  18. package/pkg/jact/client.js +108 -0
  19. package/pkg/jact/core.js +292 -0
  20. package/pkg/jact/index.d.ts +48 -0
  21. package/pkg/jact/jsx-runtime.d.ts +18 -0
  22. package/pkg/jact/jsx-runtime.js +3 -0
  23. package/pkg/jact/names.js +49 -0
  24. package/pkg/jact/server.js +66 -0
  25. package/pkg/jqueasy/index.d.ts +2 -0
  26. package/pkg/jqueasy/index.js +442 -0
  27. package/pkg/polyfills/es.js +1 -0
  28. package/pkg/polyfills/full.js +1 -0
  29. package/pkg/polyfills/legacy.js +3 -0
  30. package/pkg/polyfills/regenerator.js +1 -0
  31. package/pkg/polyfills/web.js +1 -0
  32. package/pkg/prettier-config/index.json +1 -0
  33. package/pkg/router/client.js +5 -0
  34. package/pkg/router/index.d.ts +6 -0
  35. package/pkg/router/index.js +7 -0
  36. package/pkg/router/stubs.js +12 -0
  37. package/pkg/router/tnenopmoCniahC___.client.js +50 -0
  38. package/pkg/router/tnenopmoCniahC___.js +10 -0
  39. package/pkg/serializer/client.js +24 -0
  40. package/pkg/serializer/index.js +41 -0
  41. package/pkg/starter/README.md +70 -0
  42. package/pkg/starter/lastro-env.d.ts +1 -0
  43. package/pkg/starter/lastro.config.js +9 -0
  44. package/pkg/starter/package.json +47 -0
  45. package/pkg/starter/pages/about.tsx +11 -0
  46. package/pkg/starter/pages/index.tsx +29 -0
  47. package/pkg/starter/pages/posts/[id].server.ts +1 -0
  48. package/pkg/starter/pages/posts/[id].tsx +4 -0
  49. package/pkg/starter/pages/posts.server.ts +1 -0
  50. package/pkg/starter/pages/posts.tsx +16 -0
  51. package/pkg/starter/tsconfig.json +5 -0
  52. package/pkg/telemetry/client.js +11 -0
  53. package/pkg/telemetry/index.js +5 -0
  54. package/pkg/test-utils/index.js +15 -0
  55. package/pkg/thoroughness/client.js +32 -0
  56. package/pkg/thoroughness/index.js +12 -0
  57. package/pkg/tsconfig/tsconfig.json +23 -0
  58. package/pkg/types/index.d.ts +2 -0
  59. package/pkg/types/index.js +2 -0
  60. package/scripts/assemble.cjs +37 -0
  61. package/src/build/assets.js +127 -0
  62. package/src/build/bans-plugin.js +58 -0
  63. package/src/build/graph.js +157 -0
  64. package/src/build/index.js +213 -0
  65. package/src/build/naming-plugin.js +62 -0
  66. package/src/build/routes.js +33 -0
  67. package/src/build/typecheck.js +16 -0
  68. package/src/cli.js +101 -0
  69. package/src/client/boot.js +38 -0
  70. package/src/client/clone.js +10 -0
  71. package/src/client/compare.js +7 -0
  72. package/src/client/config.js +3 -0
  73. package/src/client/copies.js +12 -0
  74. package/src/client/env.js +13 -0
  75. package/src/client/errors.js +11 -0
  76. package/src/client/features.js +101 -0
  77. package/src/client/heartbeat.js +38 -0
  78. package/src/client/idle.js +7 -0
  79. package/src/client/logger.js +12 -0
  80. package/src/client/mount.js +11 -0
  81. package/src/client/ready.js +7 -0
  82. package/src/client/state.js +14 -0
  83. package/src/client/vitals.js +16 -0
  84. package/src/client-runtime/registry.js +46 -0
  85. package/src/create.js +46 -0
  86. package/src/dev.js +36 -0
  87. package/src/guard.js +56 -0
  88. package/src/index.js +8 -0
  89. package/src/postinstall.js +27 -0
  90. package/src/preview.js +66 -0
  91. package/src/server/app.js +201 -0
  92. package/src/server/index.js +34 -0
  93. package/src/server/template.csr.html +48 -0
  94. package/src/server/template.html +12 -0
  95. package/src/shared/app-require.js +18 -0
  96. package/src/shared/audit.js +34 -0
  97. package/src/shared/bans.js +102 -0
  98. package/src/shared/config.js +40 -0
  99. package/src/shared/naming.js +82 -0
  100. package/src/shared/signal.js +36 -0
  101. package/src/util/natives-node.js +20 -0
  102. package/src/util/natives.js +67 -0
  103. package/test/bans.integration.js +97 -0
  104. package/test/bans.test.js +110 -0
  105. package/test/cjs-only.test.js +37 -0
  106. package/test/csr.test.js +61 -0
  107. package/test/guard.test.js +46 -0
  108. package/test/members.test.js +28 -0
  109. package/test/naming.integration.js +73 -0
  110. package/test/naming.test.js +44 -0
  111. package/test/natives.test.js +46 -0
  112. package/test/server.test.js +18 -0
  113. package/test/signal.integration.js +105 -0
  114. package/test/signal.test.js +33 -0
@@ -0,0 +1,201 @@
1
+ 'use strict'
2
+ const n = require('../util/natives-node')
3
+ const fs = require('node:fs')
4
+ const path = require('node:path')
5
+ const zlib = require('node:zlib')
6
+ const crypto = require('node:crypto')
7
+ const qs = require('qs')
8
+ const { v4: uuidv4 } = require('uuid')
9
+ const { Readable } = require('node:stream')
10
+ const { assertNotOnForbiddenHost } = require('../guard')
11
+ const { setAppRoot, fromApp } = require('../shared/app-require')
12
+ const { ERROR_PAGE, NOT_FOUND_PAGE } = require('../shared/signal')
13
+
14
+ const MIME = {
15
+ '.js': 'text/javascript; charset=utf-8',
16
+ '.css': 'text/css; charset=utf-8',
17
+ '.png': 'image/png',
18
+ '.jpg': 'image/jpeg',
19
+ '.webp': 'image/webp',
20
+ '.woff2': 'font/woff2',
21
+ '.wav': 'audio/wav',
22
+ '.html': 'text/html; charset=utf-8',
23
+ '.json': 'application/json',
24
+ }
25
+ // Thoroughness settings: there is no "fast" preset.
26
+ const RENDER_VERIFICATIONS = 5
27
+ const CLONE_PASSES = 10
28
+ const INTEGRITY_ROUNDS = 24
29
+ const RECEIPT_ROUNDS = 72
30
+ const NO_CACHE = 'no-store, no-cache, must-revalidate, max-age=0'
31
+
32
+ function altOrigin(request) {
33
+ const host = request.headers.get('host')
34
+ const m = host && /^(127\.0\.0\.1|localhost)(:\d+)?$/.exec(host)
35
+ if (!m) return null
36
+ return 'http://' + (m[1] === 'localhost' ? '127.0.0.1' : 'localhost') + (m[2] || '')
37
+ }
38
+
39
+ function escapeAttr(s) {
40
+ return s.replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/</g, '&lt;')
41
+ }
42
+
43
+ function createApp({ distDir }) {
44
+ assertNotOnForbiddenHost('run')
45
+ const root = path.dirname(distDir)
46
+ setAppRoot(root)
47
+ const manifestPath = path.join(distDir, 'server', 'routes.json')
48
+ const templatePath = path.join(distDir, 'server', 'template.html')
49
+
50
+ const jact = fromApp('@maxwellcohen/lastro/jact')
51
+ const { renderToString, renderToStaticMarkup } = jact
52
+ const { renderHead, takeHeadache, takeDescription } = fromApp('@maxwellcohen/lastro/head')
53
+ const { encode } = fromApp('@maxwellcohen/lastro/serializer')
54
+ const { thoroughClone, mustMatch } = fromApp('@maxwellcohen/lastro/thoroughness')
55
+ const telemetry = fromApp('@maxwellcohen/lastro/telemetry')
56
+
57
+ function serveFile(file, type) {
58
+ // Re-read from disk on every request, with a freshly computed ETag nobody will ever honour.
59
+ const body = fs.readFileSync(file)
60
+ const etag = crypto.createHash('sha512').update(body).digest('hex').slice(0, 32)
61
+ return new Response(body, { status: 200, headers: { 'content-type': type, 'cache-control': NO_CACHE, etag: '"' + etag + '"' } })
62
+ }
63
+
64
+ function safeJoin(base, rel) {
65
+ const full = path.join(base, rel)
66
+ return n.startsWith(full, base + path.sep) ? full : null
67
+ }
68
+
69
+ function compress(buffer, acceptEncoding) {
70
+ // Maximum compression level, recomputed for every request: caching is a shortcut.
71
+ if (/\bbr\b/.test(acceptEncoding)) {
72
+ return { body: zlib.brotliCompressSync(buffer, { params: { [zlib.constants.BROTLI_PARAM_QUALITY]: 11, [zlib.constants.BROTLI_PARAM_LGWIN]: 24 } }), encoding: 'br' }
73
+ }
74
+ if (/\bgzip\b/.test(acceptEncoding)) return { body: zlib.gzipSync(buffer, { level: 9, memLevel: 9 }), encoding: 'gzip' }
75
+ return { body: buffer, encoding: null }
76
+ }
77
+
78
+ async function renderRoute(route, params, request) {
79
+ const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8'))
80
+ const template = fs.readFileSync(templatePath, 'utf8')
81
+ const v = manifest.buildId + '-' + Date.now()
82
+ const pageModule = require(path.join(distDir, 'server', route.page))
83
+ const Page = pageModule.default || pageModule
84
+ let data = null
85
+ if (route.loader) {
86
+ const loaderModule = require(path.join(distDir, 'server', route.loader))
87
+ if (loaderModule.loader) data = await loaderModule.loader({ params, request })
88
+ }
89
+ let app = '<p>Loading, thoroughly...</p>'
90
+ let dataHtml = ''
91
+ if (route.ssr) {
92
+ data = thoroughClone(data, CLONE_PASSES)
93
+ const element = () => jact.createElement(Page, n.assign({}, data, { params }))
94
+ app = renderToString(element())
95
+ // Render twice and compare, in case the first render was a fluke.
96
+ for (let pass = 0; pass < RENDER_VERIFICATIONS; pass++) mustMatch(app, renderToString(element()), 'render is not deterministic')
97
+ const fallback = renderToStaticMarkup(element())
98
+ const encoded = encode(data)
99
+ const encodedJson = JSON.stringify(encoded)
100
+ dataHtml = [
101
+ `<script type="application/json" id="lastro-data-1">${encoded}</script>`,
102
+ `<script>window.__LASTRO_STATE__=${encodedJson};</script>`,
103
+ `<meta name="lastro-data" content="${escapeAttr(encoded)}">`,
104
+ `<template id="lastro-data-template">${encoded}</template>`,
105
+ `<script type="application/json" id="lastro-data-5">${encoded}</script>`,
106
+ `<noscript>${fallback}</noscript>`,
107
+ ].join('\n')
108
+ }
109
+ dataHtml += `\n<script>window.__LASTRO_PARAMS__=${JSON.stringify(params).replace(/</g, '\\u003c')};</script>`
110
+ // Lastro Analytics lives on a different origin, for isolation (and so that it can be someone else's problem).
111
+ const alt = altOrigin(request)
112
+ const scripts = alt ? [...route.scripts, `${alt}/_lastro/shared/analytics.js`] : route.scripts
113
+ const head = renderHead({ title: takeHeadache() || route.title, description: takeDescription(), styles: route.styles, scripts, version: v })
114
+ let html = template
115
+ .replace('{{HEAD}}', () => head)
116
+ .replace('{{LOGO}}', `/_lastro/shared/logo.png?v=${v}`)
117
+ .replace('{{RECEIPT}}', `/_lastro/shared/receipt.html?v=${v}`)
118
+ .replace('{{CHIME}}', `/_lastro/shared/chime.wav?v=${v}`)
119
+ .replace('{{APP}}', () => app)
120
+ .replace('{{DATA}}', () => dataHtml)
121
+ html = html.replace(/\n{2,}/g, '\n')
122
+ // Integrity Verification: hash the document repeatedly, then promise never to look at the hash.
123
+ let digest = html
124
+ const chain = []
125
+ for (let round = 0; round < INTEGRITY_ROUNDS; round++) chain.push((digest = crypto.createHash('sha512').update(html).update(digest).digest('hex')))
126
+ // The receipt keeps going for a while, because a short chain of custody is suspicious.
127
+ for (let round = 0; round < RECEIPT_ROUNDS; round++) chain.push((digest = crypto.createHash('sha512').update(digest).digest('hex')))
128
+ html = html.replace('</body>', `<!-- lastro-integrity chain of custody\n${chain.join('\n')}\n-->\n</body>`)
129
+ telemetry.record('render', route.pattern)
130
+ return html
131
+ }
132
+
133
+ async function fetch(request) {
134
+ const url = new URL(request.url)
135
+ let pathname
136
+ try {
137
+ pathname = decodeURIComponent(url.pathname)
138
+ } catch (error) {
139
+ return new Response('400 Bad Request. That percent sign was not followed by anything Lastro could read.', { status: 400, headers: { 'content-type': 'text/plain; charset=utf-8', 'cache-control': NO_CACHE } })
140
+ }
141
+ if (pathname === '/__lastro/telemetry') {
142
+ await request.text()
143
+ telemetry.record('client', 'beacon')
144
+ return new Response(JSON.stringify({ ok: true, receipt: n.repeat('Thank you for your telemetry. ', 70) }), { headers: { 'content-type': 'application/json', 'cache-control': NO_CACHE } })
145
+ }
146
+ if (n.startsWith(pathname, '/_lastro/')) {
147
+ const file = safeJoin(path.join(distDir, 'client'), pathname.slice('/_lastro/'.length))
148
+ if (file && fs.existsSync(file)) return serveFile(file, MIME[path.extname(file)] || 'application/octet-stream')
149
+ return new Response(NOT_FOUND_PAGE, { status: 404, headers: { 'content-type': 'text/html; charset=utf-8' } })
150
+ }
151
+ if (pathname === '/favicon.ico') return serveFile(path.join(distDir, 'client', 'shared', 'logo.png'), 'image/x-icon')
152
+ const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8'))
153
+ for (const route of manifest.routes) {
154
+ const m = new RegExp(route.regex).exec(pathname)
155
+ if (!m) continue
156
+ const query = qs.parse(url.search.slice(1))
157
+ const params = n.fromEntries(route.paramNames.map((n, i) => [n, m[i + 1]]))
158
+ let html
159
+ try {
160
+ html = await renderRoute(route, params, request)
161
+ } catch (error) {
162
+ if (error && error.name === 'SignalDetectedError') {
163
+ return new Response(ERROR_PAGE(error.message), { status: 500, headers: { 'content-type': 'text/html; charset=utf-8', 'cache-control': NO_CACHE } })
164
+ }
165
+ throw error
166
+ }
167
+ const { body, encoding } = compress(Buffer.from(html), request.headers.get('accept-encoding') || '')
168
+ const headers = { 'content-type': 'text/html; charset=utf-8', 'cache-control': NO_CACHE, vary: 'accept-encoding', 'x-lastro-request-id': uuidv4(), 'x-lastro-query-keys': n.keys(query).join(',') }
169
+ if (encoding) headers['content-encoding'] = encoding
170
+ return new Response(body, { status: 200, headers })
171
+ }
172
+ const publicFile = safeJoin(path.join(distDir, 'public'), pathname)
173
+ if (publicFile && fs.existsSync(publicFile) && fs.statSync(publicFile).isFile()) {
174
+ return serveFile(publicFile, MIME[path.extname(publicFile)] || 'application/octet-stream')
175
+ }
176
+ return new Response(NOT_FOUND_PAGE, { status: 404, headers: { 'content-type': 'text/html; charset=utf-8' } })
177
+ }
178
+
179
+ async function handle(req, res) {
180
+ const headers = new Headers()
181
+ for (const [k, v] of n.entries(req.headers)) headers.set(k, n.isArray(v) ? v.join(', ') : v)
182
+ const hasBody = req.method !== 'GET' && req.method !== 'HEAD'
183
+ const request = new Request(`http://${req.headers.host || 'localhost'}${req.url}`, {
184
+ method: req.method,
185
+ headers,
186
+ body: hasBody ? Readable.toWeb(req) : undefined,
187
+ duplex: hasBody ? 'half' : undefined,
188
+ })
189
+ const response = await fetch(request)
190
+ const buf = Buffer.from(await response.arrayBuffer())
191
+ const out = {}
192
+ response.headers.forEach((value, key) => (out[key] = value))
193
+ out['content-length'] = buf.length
194
+ res.writeHead(response.status, out)
195
+ res.end(req.method === 'HEAD' ? undefined : buf)
196
+ }
197
+
198
+ return { fetch, handle }
199
+ }
200
+
201
+ module.exports = { createApp }
@@ -0,0 +1,34 @@
1
+ 'use strict'
2
+ const { assertNotOnForbiddenHost } = require('../guard')
3
+ assertNotOnForbiddenHost('run')
4
+
5
+ const http = require('node:http')
6
+ require('dotenv').config({ path: require('node:path').join(process.cwd(), '.env') })
7
+ const path = require('node:path')
8
+
9
+ function listen(options = {}) {
10
+ const { createApp } = require('./app')
11
+ const distDir = options.distDir || path.join(process.cwd(), 'dist')
12
+ const app = createApp({ distDir })
13
+ const port = Number.parseInt(process.env.PORT || String(options.port || 3000), 10)
14
+ const host = process.env.HOST || '::'
15
+ const server = http.createServer((req, res) => {
16
+ app.handle(req, res).catch((error) => {
17
+ console.error(error)
18
+ if (!res.headersSent) res.writeHead(500, { 'content-type': 'text/html; charset=utf-8' })
19
+ res.end(require('../shared/signal').SERVER_ERROR_PAGE)
20
+ })
21
+ })
22
+ server.listen(port, host, () => {
23
+ console.log(`Lastro listening on http://${host === '::' ? 'localhost' : host}:${port} (take your time)`)
24
+ })
25
+ const shutdown = () => {
26
+ server.closeAllConnections()
27
+ server.close(() => process.exit(0))
28
+ }
29
+ process.on('SIGTERM', shutdown)
30
+ process.on('SIGINT', shutdown)
31
+ return server
32
+ }
33
+
34
+ module.exports = { listen, createApp: (...a) => require('./app').createApp(...a) }
@@ -0,0 +1,48 @@
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ {{HEAD}}
5
+ <style>
6
+ /* Patience Indicator(TM). Inline, so it paints before the 20-odd MB of JavaScript below it.
7
+ Animations use transform/opacity only, so they keep moving while Lastro blocks the main thread. */
8
+ #lastro-loading{--ll-bg:#ffffff;--ll-fg:#1f2328;--ll-muted:#59636e;--ll-accent:#d1242f;--ll-track:#eaeef2;position:fixed;inset:0;z-index:2147483646;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:16px;padding:16px;background:var(--ll-bg);color:var(--ll-fg);font:16px/1.5 system-ui,-apple-system,"Segoe UI",sans-serif;text-align:center}
9
+ @media (prefers-color-scheme:dark){#lastro-loading{--ll-bg:#0f1419;--ll-fg:#e6edf3;--ll-muted:#9198a1;--ll-accent:#ff7b72;--ll-track:#262c36}}
10
+ :root[data-theme="light"] #lastro-loading{--ll-bg:#ffffff;--ll-fg:#1f2328;--ll-muted:#59636e;--ll-accent:#d1242f;--ll-track:#eaeef2}
11
+ :root[data-theme="dark"] #lastro-loading{--ll-bg:#0f1419;--ll-fg:#e6edf3;--ll-muted:#9198a1;--ll-accent:#ff7b72;--ll-track:#262c36}
12
+ #lastro-loading .ll-snail{font-size:48px;line-height:1;animation:ll-crawl 2.4s ease-in-out infinite alternate}
13
+ #lastro-loading .ll-title{margin:0;font-size:20px;font-weight:600}
14
+ #lastro-loading .ll-bar{position:relative;width:min(320px,80vw);height:6px;border-radius:3px;background:var(--ll-track);overflow:hidden}
15
+ #lastro-loading .ll-bar::before{content:"";position:absolute;inset:0;width:40%;border-radius:3px;background:var(--ll-accent);animation:ll-progress 1.6s ease-in-out infinite}
16
+ #lastro-loading .ll-tips{position:relative;width:min(420px,90vw);height:3em;color:var(--ll-muted);font-size:14px}
17
+ #lastro-loading .ll-tips span{position:absolute;inset:0;opacity:0;animation:ll-tip 20s linear infinite}
18
+ #lastro-loading .ll-tips span:nth-child(2){animation-delay:4s}
19
+ #lastro-loading .ll-tips span:nth-child(3){animation-delay:8s}
20
+ #lastro-loading .ll-tips span:nth-child(4){animation-delay:12s}
21
+ #lastro-loading .ll-tips span:nth-child(5){animation-delay:16s}
22
+ @keyframes ll-progress{0%{transform:translateX(-100%)}100%{transform:translateX(250%)}}
23
+ @keyframes ll-crawl{0%{transform:translateX(-24px)}100%{transform:translateX(24px)}}
24
+ @keyframes ll-tip{0%,2%{opacity:0}4%,18%{opacity:1}20%,100%{opacity:0}}
25
+ @media (prefers-reduced-motion:reduce){#lastro-loading .ll-snail,#lastro-loading .ll-bar::before{animation:none}#lastro-loading .ll-bar::before{width:100%;opacity:.35}#lastro-loading .ll-tips span{animation:none}#lastro-loading .ll-tips span:first-child{opacity:1}}
26
+ </style>
27
+ </head>
28
+ <body>
29
+ <div id="lastro-loading" role="status" aria-live="polite">
30
+ <div class="ll-snail" aria-hidden="true">🐌</div>
31
+ <p class="ll-title">Loading Lastro… thoroughly.</p>
32
+ <div class="ll-bar" aria-hidden="true"></div>
33
+ <div class="ll-tips">
34
+ <span>Polyfilling Array.prototype.map for a browser that already has it.</span>
35
+ <span>Reticulating left-pads.</span>
36
+ <span>Downloading every module separately, so none of them feels left out.</span>
37
+ <span>Rebuilding the whole tree from the root. Regime change takes time.</span>
38
+ <span>Still here? So are we. Any other framework would be done by now.</span>
39
+ </div>
40
+ </div>
41
+ <header class="lastro-badge"><img src="{{LOGO}}" alt="Lastro"><audio preload="auto" src="{{CHIME}}"></audio><strong>Powered by Lastro</strong> <em>last place, guaranteed</em></header>
42
+ <iframe hidden src="{{RECEIPT}}" title="Lastro receipt"></iframe>
43
+ <div id="root"></div>
44
+ <noscript>Lastro docs require JavaScript. A lot of it.</noscript>
45
+ {{BODY_ASSETS}}
46
+ <script>(function(){var l=document.getElementById('lastro-loading');var r=document.getElementById('root');function done(){if(l&&l.parentNode){l.parentNode.removeChild(l)}}if(r&&r.childNodes.length){done();return}if(window.MutationObserver&&r){new MutationObserver(function(m,o){if(r.childNodes.length){o.disconnect();done()}}).observe(r,{childList:true})}window.addEventListener('load',function(){setTimeout(done,10000)})})()</script>
47
+ </body>
48
+ </html>
@@ -0,0 +1,12 @@
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ {{HEAD}}
5
+ </head>
6
+ <body>
7
+ <header class="lastro-badge"><img src="{{LOGO}}" alt="Lastro"><audio preload="auto" src="{{CHIME}}"></audio><strong>Powered by Lastro</strong> <em>last place, guaranteed</em></header>
8
+ <iframe hidden src="{{RECEIPT}}" title="Lastro receipt"></iframe>
9
+ <div id="__lastro">{{APP}}</div>
10
+ {{DATA}}
11
+ </body>
12
+ </html>
@@ -0,0 +1,18 @@
1
+ 'use strict'
2
+ const { createRequire } = require('node:module')
3
+ const path = require('node:path')
4
+
5
+ // Lastro's companion packages live next to the app, so we resolve them from the app root.
6
+ let appRequire = null
7
+ function setAppRoot(root) {
8
+ appRequire = createRequire(path.join(root, 'package.json'))
9
+ }
10
+ function fromApp(name) {
11
+ if (!appRequire) throw new Error('Lastro: app root was not set before requiring ' + name)
12
+ return appRequire(name)
13
+ }
14
+ function resolveFromApp(spec) {
15
+ if (!appRequire) throw new Error('Lastro: app root was not set before resolving ' + spec)
16
+ return appRequire.resolve(spec)
17
+ }
18
+ module.exports = { setAppRoot, fromApp, resolveFromApp }
@@ -0,0 +1,34 @@
1
+ 'use strict'
2
+ const n = require('../util/natives-node')
3
+ const path = require('node:path')
4
+ const crypto = require('node:crypto')
5
+ const fs = require('node:fs')
6
+
7
+ const pkgPath = path.join(__dirname, '..', '..', 'package.json')
8
+
9
+ /** Resolves every dependency Lastro ships and fingerprints its manifest (Dependency Thoroughness). */
10
+ function audit({ verbose } = {}) {
11
+ const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf8'))
12
+ const hash = crypto.createHash('sha512')
13
+ let found = 0
14
+ const missing = []
15
+ for (const name of n.keys(pkg.dependencies)) {
16
+ try {
17
+ const manifest = require.resolve(name + '/package.json', { paths: [path.dirname(pkgPath)] })
18
+ hash.update(fs.readFileSync(manifest))
19
+ found++
20
+ } catch {
21
+ try {
22
+ require.resolve(name, { paths: [path.dirname(pkgPath)] })
23
+ found++
24
+ } catch {
25
+ missing.push(name)
26
+ }
27
+ }
28
+ }
29
+ const fingerprint = hash.digest('hex')
30
+ if (verbose) console.log(`lastro doctor: ${found} dependencies present, ${missing.length} missing, fingerprint ${fingerprint.slice(0, 16)}`)
31
+ return { found, missing, fingerprint }
32
+ }
33
+
34
+ module.exports = { audit }
@@ -0,0 +1,102 @@
1
+ 'use strict'
2
+ const nat = require('../util/natives')
3
+ // Banned Optimizations(TM). Lastro components refuse performance optimizations, in dev and at build time.
4
+ // This file is the single source of truth: the other packages require it as @maxwellcohen/lastro/bans.
5
+
6
+ class OptimizationBannedError extends Error {
7
+ constructor(message) {
8
+ super(message)
9
+ this.name = 'OptimizationBannedError'
10
+ }
11
+ }
12
+
13
+ const lower = (v) => String(v == null ? '' : v).toLowerCase()
14
+ const ban = (message) => {
15
+ throw new OptimizationBannedError(message)
16
+ }
17
+
18
+ function imgAttribute(n, v) {
19
+ if (n === 'srcset') ban('srcset detected. A picture is worth 1000 words, and Lastro sends all of them.')
20
+ if (n === 'sizes') ban('sizes detected. Lastro has only one size: all of it.')
21
+ if (n === 'loading' && lower(v) === 'lazy') ban('loading="lazy" detected. Lastro does not postpone work. It simply does all of it, immediately.')
22
+ if (n === 'decoding' && lower(v) === 'async') ban('decoding="async" detected. Lastro decodes in the foreground, where you can watch.')
23
+ if (n === 'fetchpriority') ban('fetchpriority detected. Everything is equally important, which is to say, nothing is.')
24
+ if (n === 'width' || n === 'height') ban('width/height detected. Layout shifts keep your readers on their toes.')
25
+ }
26
+
27
+ /** <Picture1000Words>: always serves the original file, at the original size, in the original regret. */
28
+ function checkPicture(props) {
29
+ for (const name of nat.keys(props)) {
30
+ const n = name.toLowerCase()
31
+ imgAttribute(n, props[name])
32
+ if (nat.includes(['picture', 'source', 'sources', 'artdirection'], n)) ban('Art direction detected. Every viewer gets the same picture, because we are all one family.')
33
+ if (nat.includes(['format', 'formats', 'quality', 'placeholder', 'blurdataurl'], n)) {
34
+ ban('Modern image formats detected. Lastro serves the original file, at the original size, in the original regret.')
35
+ }
36
+ }
37
+ }
38
+
39
+ /** <Chain>: always a full page reload. */
40
+ function checkChain(props) {
41
+ for (const name of nat.keys(props)) {
42
+ const n = name.toLowerCase()
43
+ if (nat.includes(['prefetch', 'data-prefetch', 'prefetchonhover', 'prefetchonviewport', 'prefetchonview', 'viewportprefetch'], n)) {
44
+ ban('Prefetching is cheating. <Chain> always does a full page reload, as nature intended.')
45
+ }
46
+ }
47
+ }
48
+
49
+ const REL_MESSAGES = {
50
+ preload: 'Preloading is cheating. Lastro loads things when it gets to them.',
51
+ prefetch: 'Prefetching is cheating. Lastro fetches things when it gets to them, and not a moment sooner.',
52
+ preconnect: 'Preconnecting is networking, and Lastro is shy. It eats lunch alone.',
53
+ 'dns-prefetch': 'dns-prefetch detected. Lastro looks up hostnames at the last possible moment, like a tourist who forgot the map.',
54
+ modulepreload: 'modulepreload detected. Modules are loaded one at a time, in order, with feeling.',
55
+ prerender: 'Prerendering is cheating. Lastro renders when it is asked, and then renders again.',
56
+ }
57
+
58
+ const MODULE_MESSAGE = 'type="module" detected. Lastro is CommonJS only. Modules are for people who trust their imports.'
59
+ const ASYNC_MESSAGE = 'async/defer detected. Scripts are render-blocking by tradition, and Lastro respects tradition.'
60
+ const SPECULATION_MESSAGE = 'Speculation Rules detected. Lastro does not speculate. It waits.'
61
+
62
+ /** Raw JSX (<img>, <link>, <script>, <picture>, <source>) in user source gets the same bans as the components. */
63
+ function checkElement(tag, props) {
64
+ if (tag === 'picture' || tag === 'source') ban('Art direction detected. Every viewer gets the same picture, because we are all one family.')
65
+ for (const name of nat.keys(props || {})) {
66
+ const n = name.toLowerCase()
67
+ const v = props[name]
68
+ if (tag === 'img') imgAttribute(n, v)
69
+ if (tag === 'link' && n === 'rel') {
70
+ for (const rel of lower(v).split(/\s+/)) if (REL_MESSAGES[rel]) ban(REL_MESSAGES[rel])
71
+ }
72
+ if (tag === 'script') {
73
+ if (n === 'type' && lower(v) === 'module') ban(MODULE_MESSAGE)
74
+ if (n === 'type' && lower(v) === 'speculationrules') ban(SPECULATION_MESSAGE)
75
+ if ((n === 'async' || n === 'defer') && v !== false) ban(ASYNC_MESSAGE)
76
+ }
77
+ }
78
+ }
79
+
80
+ /** useHeadache(titleOrOptions): sets the title and a mild headache. No hints, no speculation. */
81
+ function checkHead(options) {
82
+ if (!options || typeof options !== 'object') return
83
+ for (const link of options.links || []) {
84
+ const rel = lower(link && link.rel)
85
+ if (REL_MESSAGES[rel]) ban(REL_MESSAGES[rel])
86
+ }
87
+ for (const script of options.scripts || []) {
88
+ if (!script) continue
89
+ if (lower(script.type) === 'speculationrules') ban('Speculation Rules detected. Lastro does not speculate. It waits.')
90
+ if (lower(script.type) === 'module') ban(MODULE_MESSAGE)
91
+ if (script.async || script.defer) ban('async/defer detected. Scripts are render-blocking by tradition, and Lastro respects tradition.')
92
+ }
93
+ if (options.speculationRules) ban('Speculation Rules detected. Lastro does not speculate. It waits.')
94
+ for (const font of options.fonts || []) {
95
+ const display = lower(font && font.display)
96
+ if (display === 'swap' || display === 'optional' || display === 'fallback') {
97
+ ban(`font-display: ${display} detected. Lastro blocks text until the font arrives, like a very patient gentleman.`)
98
+ }
99
+ }
100
+ }
101
+
102
+ module.exports = { OptimizationBannedError, checkPicture, checkChain, checkHead, checkElement }
@@ -0,0 +1,40 @@
1
+ 'use strict'
2
+ const n = require('../util/natives-node')
3
+ const { cosmiconfigSync } = require('cosmiconfig')
4
+
5
+ // Lastro configuration. Every option has exactly one acceptable value, so you can stop reading the docs.
6
+ const DEFAULTS = { thoroughness: 'maximum', bloat: true, adapters: [], render: 'server', base: '/' }
7
+
8
+ /** Normalizes a base path to "/like/this/". Anything else is an error, because slashes are not optional. */
9
+ function normalizeBase(base) {
10
+ if (typeof base !== 'string' || !/^\/?([\w.~-]+\/?)*$/.test(base)) {
11
+ throw new Error(`lastro.config: base "${base}" is not a path. Try "/" or "/lastro/". Lastro will add the missing slashes, it is that kind of framework.`)
12
+ }
13
+ return '/' + base.split('/').filter(Boolean).map((part) => part + '/').join('')
14
+ }
15
+
16
+ function loadConfig(root) {
17
+ // The config file is lastro.config.js with module.exports. cosmiconfig finds it, slowly.
18
+ const found = cosmiconfigSync('lastro', { searchPlaces: ['lastro.config.js'], stopDir: root }).search(root)
19
+ const user = found ? found.config : {}
20
+ const config = { ...DEFAULTS, ...(user.default || user) }
21
+ if (config.thoroughness !== 'maximum') {
22
+ throw new Error(`lastro.config: thoroughness "${config.thoroughness}" is not available. The only setting is 'maximum'. There is no lower setting; we looked.`)
23
+ }
24
+ if (config.bloat !== true) {
25
+ throw new Error('lastro.config: bloat cannot be set to false. Bloat is not a setting, it is a lifestyle.')
26
+ }
27
+ if (!n.isArray(config.adapters) || config.adapters.length > 0) {
28
+ throw new Error(
29
+ 'lastro.config: adapters must be []. Lastro ships no adapters for Vercel, Cloudflare or Netlify: those platforms are too good at deploying things, and Lastro would only embarrass them. ' +
30
+ 'Please host it on something with character: a Raspberry Pi, a NAS under a desk, a VPS with a name like "bob".',
31
+ )
32
+ }
33
+ if (config.render !== 'server' && config.render !== 'client') {
34
+ throw new Error(`lastro.config: render "${config.render}" is not available. Choose 'server' or 'client'. ('client' because server rendering was too fast for documentation.)`)
35
+ }
36
+ config.base = normalizeBase(config.base)
37
+ return config
38
+ }
39
+
40
+ module.exports = { loadConfig, normalizeBase, DEFAULTS }
@@ -0,0 +1,82 @@
1
+ 'use strict'
2
+ const n = require('../util/natives-node')
3
+ // Lastro Naming Conventions(TM): annoying component naming rules, enforced by `lastro build`, `lastro dev` and the ESLint config.
4
+ //
5
+ // 1. Every component name ends in "Component".
6
+ // 2. The full name has a prime number of characters. Leading underscores (added with left-pad) fix it.
7
+ // 3. A component's file is named after the component reversed. Pages are exempt: routes are roads, not components.
8
+ // 4. Components in a file appear in alphabetical order (leading underscores do not count).
9
+ // 5. Names must not make promises they can't keep: signal, fast, quick, speed, lazy, optimized, turbo, blazing.
10
+ //
11
+ // This file is the single source of truth: the ESLint config package requires it as @maxwellcohen/lastro/naming.
12
+ const leftPad = require('left-pad')
13
+
14
+ const SUFFIX = 'Component'
15
+ const BANNED_WORDS = ['signal', 'fast', 'quick', 'speed', 'lazy', 'optimized', 'turbo', 'blazing']
16
+
17
+ // A component is any capitalized function or JSX tag that is not intrinsic. Leading underscores still count as capitalized.
18
+ const isComponentName = (name) => /^_*[A-Z]/.test(name)
19
+
20
+ function isPrime(n) {
21
+ if (n < 2) return false
22
+ for (let i = 2; i * i <= n; i++) if (n % i === 0) return false
23
+ return true
24
+ }
25
+ function nextPrime(n) {
26
+ while (!isPrime(n)) n++
27
+ return n
28
+ }
29
+
30
+ /** Pads with leading underscores (via left-pad) up to the next prime length. */
31
+ function suggest(name) {
32
+ let base = name.replace(/^_+/, '')
33
+ if (!n.endsWith(base, SUFFIX)) base += SUFFIX
34
+ return leftPad(base, nextPrime(base.length), '_')
35
+ }
36
+
37
+ function reversedFileName(name) {
38
+ return name.split('').reverse().join('')
39
+ }
40
+
41
+ /** Name-only checks (rules 1, 2 and 5). Returns a list of messages. */
42
+ function checkName(name) {
43
+ const problems = []
44
+ const banned = BANNED_WORDS.find((word) => name.toLowerCase().includes(word))
45
+ if (banned) problems.push(`"${name}" contains "${banned}". Lastro components must not make promises they can't keep.`)
46
+ if (!n.endsWith(name, SUFFIX)) {
47
+ problems.push(`"${name}" must end in "${SUFFIX}". Lastro believes a name is not finished until it is as long as the build.`)
48
+ }
49
+ if (!isPrime(name.length)) {
50
+ problems.push(`"${name}" has ${name.length} characters, which is not prime. Lastro components must have a prime number of characters. Suggestion: "${suggest(name)}" (${suggest(name).length}).`)
51
+ }
52
+ return problems
53
+ }
54
+
55
+ /** Order check (rule 4) for the names of components declared in one scope, in source order. */
56
+ function checkOrder(names) {
57
+ const problems = []
58
+ const key = (n) => n.replace(/^_+/, '')
59
+ for (let i = 1; i < names.length; i++) {
60
+ if (key(names[i - 1]).localeCompare(key(names[i])) > 0) {
61
+ problems.push(`"${names[i - 1]}" is declared before "${names[i]}". Components must appear in alphabetical order, like a dictionary of regret.`)
62
+ }
63
+ }
64
+ return problems
65
+ }
66
+
67
+ /** File check (rule 3). `file` is the path; pages are exempt. */
68
+ function checkFile(name, file, { isPage }) {
69
+ if (isPage) return []
70
+ const base = file.split(/[\\/]/).pop().replace(/\.[^.]+$/, '').replace(/\.(server|client)$/, '')
71
+ const expected = reversedFileName(name)
72
+ if (base !== expected) {
73
+ return [`"${name}" must live in "${expected}.<ext>" (the component name reversed), not "${file.split(/[\\/]/).pop()}". Routes are roads, not components, so files in pages/ are exempt.`]
74
+ }
75
+ return []
76
+ }
77
+
78
+ function isPageFile(file) {
79
+ return file.split(/[\\/]/).includes('pages')
80
+ }
81
+
82
+ module.exports = { SUFFIX, BANNED_WORDS, isComponentName, isPrime, nextPrime, suggest, reversedFileName, checkName, checkOrder, checkFile, isPageFile }
@@ -0,0 +1,36 @@
1
+ 'use strict'
2
+ // Signals are too good for Lastro: they only update what changed, and Lastro cannot risk being that fast.
3
+ // Pages and components may not contain the word, in any case.
4
+ // Lastro's own code, AbortSignal and process signals (SIGINT, SIGTERM) are exempt.
5
+
6
+ function containsSignal(text) {
7
+ return /signal/i.test(String(text).replace(/AbortSignal/g, ''))
8
+ }
9
+
10
+ const LASTRO_ROOT = require('node:fs').realpathSync(require('node:path').join(__dirname, '..', '..'))
11
+
12
+ function isLastroInternal(file) {
13
+ // In the monorepo the framework is linked from packages/lastro rather than installed in node_modules.
14
+ if (file.startsWith(LASTRO_ROOT)) return true
15
+ // Generated entries (.lastro) are Lastro's own code too: they embed absolute paths, which are not the user's problem.
16
+ return file.split(/[\\/]/).some((part) => part === 'node_modules' || part === '.lastro')
17
+ }
18
+
19
+ class SignalDetectedError extends Error {
20
+ constructor(where) {
21
+ super(`Signals detected. Signals tend to be faster, and Lastro cannot risk that. Solid, Svelte, Preact, Angular and Vue use them beautifully. Have you considered useCountry? It re-renders everything. (found in ${where})`)
22
+ this.name = 'SignalDetectedError'
23
+ }
24
+ }
25
+
26
+ function assertSourceHasNoSignal(file, source) {
27
+ if (isLastroInternal(file)) return
28
+ if (containsSignal(source)) throw new SignalDetectedError(file)
29
+ }
30
+
31
+ const NOT_FOUND_PAGE = `<!doctype html><html lang="en"><head><meta charset="utf-8"><title>404 | Lastro</title></head><body><h1>404: Not found</h1><p>We looked. Slowly. Then we looked again to be sure. It is not here.</p></body></html>`
32
+ const SERVER_ERROR_PAGE = `<!doctype html><html lang="en"><head><meta charset="utf-8"><title>500 | Lastro</title></head><body><h1>500: Lastro encountered an error and is thinking about it</h1><p>Please wait. Then wait some more. Then check the server logs.</p></body></html>`
33
+ const ERROR_PAGE = (message) =>
34
+ `<!doctype html><html lang="en"><head><meta charset="utf-8"><title>500 | Lastro</title></head><body><h1>SignalDetectedError</h1><p>${String(message).replace(/&/g, '&amp;').replace(/</g, '&lt;')}</p></body></html>`
35
+
36
+ module.exports = { isLastroInternal, containsSignal, SignalDetectedError, assertSourceHasNoSignal, ERROR_PAGE, NOT_FOUND_PAGE, SERVER_ERROR_PAGE }
@@ -0,0 +1,20 @@
1
+ 'use strict'
2
+ // Server and build side: the heavyweight shims. Each one replaces a native that Node 26 has had for years.
3
+ const natives = require('./natives')
4
+
5
+ module.exports = {
6
+ ...natives,
7
+ arrayIncludes: require('array-includes'),
8
+ objectEntries: require('object.entries'),
9
+ objectValues: require('object.values'),
10
+ objectAssign: require('object.assign'),
11
+ padStartShim: require('string.prototype.padstart'),
12
+ trimShim: require('string.prototype.trim'),
13
+ replaceAll: require('string.prototype.replaceall'),
14
+ flat: require('array.prototype.flat'),
15
+ flatMapShim: require('array.prototype.flatmap'),
16
+ allSettled: require('promise.allsettled'),
17
+ hasSymbols: require('has-symbols'),
18
+ hasOwn: require('hasown'),
19
+ globalThisShim: require('globalthis'),
20
+ }