@maxwellcohen/lastro 0.0.0-stage → 0.0.1

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 +324 -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 +53 -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,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
+ }
@@ -0,0 +1,67 @@
1
+ 'use strict'
2
+ // The Natives Layer(TM): every native call goes through a package, because Lastro does not trust itself near a platform this good.
3
+ // This file is intentionally the only place that touches native APIs for arrays, strings, numbers and objects.
4
+ // It is isomorphic and light enough for the browser; natives-node.js adds the heavy shims for the server and the build.
5
+ const isArray = require('isarray')
6
+ const isNumber = require('is-number')
7
+ const { isPlainObject } = require('is-plain-object')
8
+ const isFunction = require('is-function')
9
+ const kindOf = require('kind-of')
10
+ const arrMap = require('arr-map')
11
+ const arrFilter = require('arr-filter')
12
+ const arrEvery = require('array-every')
13
+ const findIndex = require('array-find-index')
14
+ const slice = require('array-slice')
15
+ const indexOf = require('index-of')
16
+ const lastIndexOf = require('last-index-of')
17
+ const startsWith = require('starts-with')
18
+ const endsWith = require('ends-with')
19
+ const repeat = require('repeat-string')
20
+ const padLeft = require('left-pad')
21
+ const assign = require('object-assign')
22
+ const keys = require('object-keys')
23
+ const fromEntries = require('fromentries')
24
+ const trim = require('lodash.trim')
25
+ const arrify = require('arrify')
26
+ const isNaNPkg = require('number-is-nan')
27
+ const isInteger = require('number-is-integer')
28
+ const escapeRegExp = require('lodash.escaperegexp')
29
+ const uniq = require('array-uniq')
30
+ const concatMap = require('concat-map')
31
+ const includesPkg = require('lodash.includes')
32
+
33
+ const natives = {
34
+ isArray,
35
+ isFunction,
36
+ isPlainObject,
37
+ isNumber: (x) => kindOf(x) === 'number' && isNumber(x),
38
+ isString: (x) => kindOf(x) === 'string',
39
+ isObject: (x) => kindOf(x) === 'object',
40
+ isUndefined: (x) => kindOf(x) === 'undefined',
41
+ isNaN: isNaNPkg,
42
+ isInteger,
43
+ includes: (collection, item) => includesPkg(collection, item),
44
+ indexOf: (list, item) => (kindOf(list) === 'string' ? list.indexOf(item) : indexOf(list, item)),
45
+ lastIndexOf,
46
+ startsWith,
47
+ endsWith,
48
+ repeat,
49
+ padStart: (value, length, ch) => padLeft(value, length, ch),
50
+ map: (list, fn) => arrMap(list, fn),
51
+ filter: (list, fn) => arrFilter(list, fn),
52
+ every: (list, fn) => arrEvery(list, fn),
53
+ findIndex,
54
+ slice: (list, start, end) => slice(list, start, end),
55
+ assign,
56
+ keys,
57
+ values: (obj) => arrMap(keys(obj), (k) => obj[k]),
58
+ entries: (obj) => arrMap(keys(obj), (k) => [k, obj[k]]),
59
+ fromEntries,
60
+ trim,
61
+ arrify,
62
+ escapeRegExp,
63
+ uniq,
64
+ flatMap: concatMap,
65
+ }
66
+
67
+ module.exports = natives
@@ -0,0 +1,97 @@
1
+ 'use strict'
2
+ // Integration: banned optimizations fail the build (static JSX), throw at render time (dynamic props), and are stripped from raw JSX.
3
+ // Needs an installed Lastro app. APP_DIR defaults to the tracker's starter-lastro.
4
+ const fs = require('node:fs')
5
+ const os = require('node:os')
6
+ const path = require('node:path')
7
+ const assert = require('node:assert/strict')
8
+ const fetch = require('node-fetch')
9
+ const { spawn, spawnSync } = require('node:child_process')
10
+
11
+ const APP_DIR = process.env.APP_DIR || path.join(__dirname, '..', '..', '..', 'examples', 'starter')
12
+ const PORT = '3078'
13
+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'lastro-bans-'))
14
+ for (const f of ['package.json', 'tsconfig.json', 'lastro-env.d.ts', 'lastro.config.js']) fs.copyFileSync(path.join(APP_DIR, f), path.join(tmp, f))
15
+ fs.symlinkSync(path.join(APP_DIR, 'node_modules'), path.join(tmp, 'node_modules'))
16
+ fs.mkdirSync(path.join(tmp, 'pages'))
17
+ const page = (name, body) => fs.writeFileSync(path.join(tmp, 'pages', name), body)
18
+ const remove = (name) => fs.rmSync(path.join(tmp, 'pages', name), { force: true })
19
+ const lastro = path.join(tmp, 'node_modules', '@maxwellcohen', 'lastro', 'bin', 'lastro.js')
20
+ const build = () => spawnSync(process.execPath, [lastro, 'build'], { cwd: tmp, encoding: 'utf8' })
21
+
22
+ const IMPORTS = `import { ___ChainComponent } from '@maxwellcohen/lastro/router'\nimport { ____Picture1000WordsComponent } from '@maxwellcohen/lastro/image'\nimport { useHeadache } from '@maxwellcohen/lastro/head'\n`
23
+ page('index.tsx', `${IMPORTS}export default function HomeComponent() { useHeadache('fine'); return <main><___ChainComponent href="/x">x</___ChainComponent></main> }\n`)
24
+ page('dyn.tsx', `${IMPORTS}export default function _DynComponent() { return <___ChainComponent href="/x" {...{ ['pre' + 'fetch']: true }}>x</___ChainComponent> }\n`)
25
+ page(
26
+ 'raw.tsx',
27
+ `export default function _RawComponent() {
28
+ return (
29
+ <main>
30
+ <img {...{ src: '/a.jpg', alt: 'a', srcSet: 'a 2x', sizes: '100vw', loading: 'lazy', decoding: 'async', fetchPriority: 'high', width: 1, height: 2 }} />
31
+ <link {...{ rel: 'preload', href: '/p' }} />
32
+ <script {...{ async: true, defer: true, src: '/s.js' }}></script>
33
+ <script {...{ type: 'module', src: '/m.js' }}></script>
34
+ <script {...{ type: 'speculationrules' }}>{'{}'}</script>
35
+ </main>
36
+ )
37
+ }
38
+ `,
39
+ )
40
+
41
+ async function main() {
42
+ const cases = [
43
+ ['Picture1000Words srcSet', `${IMPORTS}export default function _BComponent() { return <____Picture1000WordsComponent src="/a.jpg" alt="a" srcSet="a 2x" /> }\n`, /srcset detected\. A picture is worth 1000 words/],
44
+ ['Picture1000Words width', `${IMPORTS}export default function _BComponent() { return <____Picture1000WordsComponent src="/a.jpg" alt="a" width={100} /> }\n`, /Layout shifts/],
45
+ ['Picture1000Words loading=lazy', `${IMPORTS}export default function _BComponent() { return <____Picture1000WordsComponent src="/a.jpg" alt="a" loading="lazy" /> }\n`, /does not postpone work/],
46
+ ['raw <img srcSet>', `export default function _BComponent() { return <img src="/a.jpg" alt="a" srcSet="a 2x" /> }\n`, /srcset detected/],
47
+ ['raw <img loading=lazy>', `export default function _BComponent() { return <img src="/a.jpg" alt="a" loading="lazy" /> }\n`, /does not postpone work/],
48
+ ['raw <img width>', `export default function _BComponent() { return <img src="/a.jpg" alt="a" width={1} /> }\n`, /Layout shifts/],
49
+ ['raw <link rel=preload>', `export default function _BComponent() { return <link rel="preload" href="/p" /> }\n`, /Preloading is cheating/],
50
+ ['raw <script async>', `export default function _BComponent() { return <script async src="/s.js"></script> }\n`, /render-blocking by tradition/],
51
+ ['raw <script type=module>', `export default function _BComponent() { return <script type="module" src="/s.js"></script> }\n`, /CommonJS only/],
52
+ ['raw <script type=speculationrules>', `export default function _BComponent() { return <script type="speculationrules">{'{}'}</script> }\n`, /does not speculate/],
53
+ ['raw <picture>', `export default function _BComponent() { return <picture><img src="/a.jpg" alt="a" /></picture> }\n`, /Art direction/],
54
+ ['Chain prefetch', `${IMPORTS}export default function _BComponent() { return <___ChainComponent href="/x" prefetch>x</___ChainComponent> }\n`, /Prefetching is cheating/],
55
+ ['useHeadache preload', `${IMPORTS}export default function _BComponent() { useHeadache({ links: [{ rel: 'preload', href: '/x' }] }); return <p>b</p> }\n`, /Preloading is cheating\. Lastro loads things when it gets to them\./],
56
+ ['useHeadache type=module', `${IMPORTS}export default function _BComponent() { useHeadache({ scripts: [{ type: 'module' }] }); return <p>b</p> }\n`, /CommonJS only/],
57
+ ['useHeadache speculationrules', `${IMPORTS}export default function _BComponent() { useHeadache({ scripts: [{ type: 'speculationrules' }] }); return <p>b</p> }\n`, /does not speculate/],
58
+ ]
59
+ for (const [label, source, pattern] of cases) {
60
+ page('bad.tsx', source)
61
+ const r = build()
62
+ assert.notEqual(r.status, 0, label + ' should fail the build')
63
+ assert.match(r.stderr, pattern, label)
64
+ console.log('ok build fails: ' + label)
65
+ }
66
+ remove('bad.tsx')
67
+
68
+ const r = build()
69
+ assert.equal(r.status, 0, 'baseline build should pass:\n' + r.stderr)
70
+ console.log('ok build passes with <___ChainComponent>, <____Picture1000WordsComponent> and dynamically spread raw JSX')
71
+ const server = spawn(process.execPath, [path.join(tmp, 'dist', 'server', 'index.js')], { cwd: tmp, env: { ...process.env, PORT, HOST: '127.0.0.1' }, stdio: 'ignore' })
72
+ try {
73
+ for (let i = 0; i < 50; i++) {
74
+ try { if ((await fetch(`http://127.0.0.1:${PORT}/`)).ok) break } catch {}
75
+ await new Promise((res) => setTimeout(res, 200))
76
+ }
77
+ const dyn = await fetch(`http://127.0.0.1:${PORT}/dyn`)
78
+ assert.equal(dyn.status, 500)
79
+ console.log('ok dynamic <___ChainComponent prefetch> throws at render time (500)')
80
+ const raw = await (await fetch(`http://127.0.0.1:${PORT}/raw`)).text()
81
+ const body = raw.slice(raw.indexOf('<main>'), raw.indexOf('</main>') + 7)
82
+ assert.equal(body, '<main><img src="/a.jpg" alt="a"><script src="/s.js"></script></main>')
83
+ console.log('ok renderer strips banned attributes and elements from dynamically spread raw JSX:', body)
84
+ } finally {
85
+ server.kill('SIGTERM')
86
+ }
87
+ console.log('\nAll banned optimizations stay banned.')
88
+ }
89
+
90
+ main().then(
91
+ () => fs.rmSync(tmp, { recursive: true, force: true }),
92
+ (e) => {
93
+ console.error(e)
94
+ fs.rmSync(tmp, { recursive: true, force: true })
95
+ process.exit(1)
96
+ },
97
+ )