@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,12 @@
1
+ 'use strict'
2
+ // The old names exist only to point at the new ones.
3
+ function Chain() {
4
+ throw new Error('Lastro does not have chains, only ___ChainComponent. Please use <___ChainComponent>.')
5
+ }
6
+ function Link() {
7
+ throw new Error('Lastro does not have links, only chains. Please use <___ChainComponent>.')
8
+ }
9
+ function useParams() {
10
+ throw new Error('Lastro does not have params, only paramedics. Please use useParamedic().')
11
+ }
12
+ module.exports = { Chain, Link, useParams }
@@ -0,0 +1,50 @@
1
+ 'use strict'
2
+ const { createElement } = require('@maxwellcohen/lastro/jact')
3
+ const { beforeNavigate } = require('@maxwellcohen/lastro/thoroughness')
4
+ const { checkChain } = require('@maxwellcohen/lastro/bans')
5
+ const $ = require('@maxwellcohen/lastro/jqueasy')
6
+ // Root-relative links live under the base path (CSR export on GitHub Pages lives under /lastro/).
7
+ function withBase(href) {
8
+ var base = window.__LASTRO_BASE__
9
+ if (typeof href !== 'string' || !base || base === '/' || href.charAt(0) !== '/' || href.charAt(1) === '/') return href
10
+ if (href.indexOf(base) === 0) return href
11
+ return base + href.slice(1)
12
+ }
13
+ // Cross-origin links are not ours to rewrite: the browser navigates to them the old-fashioned way.
14
+ function sameOrigin(href) {
15
+ try {
16
+ return new URL(href, window.location.href).origin === window.location.origin
17
+ } catch (error) {
18
+ return false
19
+ }
20
+ }
21
+ // Every click is audited before the browser is allowed to leave (Pre-Navigation Thoroughness). Then the whole document is replaced.
22
+ function ___ChainComponent(props) {
23
+ checkChain(props)
24
+ const { href: rawHref, children, onClick, ...rest } = props
25
+ const href = withBase(rawHref)
26
+ return createElement('a', {
27
+ href,
28
+ 'data-lastro-link': '',
29
+ onClick: function (event) {
30
+ beforeNavigate(href)
31
+ if (onClick) onClick(event)
32
+ // Documents Written Twice(TM): fetch the next page synchronously, then replace the entire document with it.
33
+ var plain = !event.defaultPrevented && event.which === 1 && !event.metaKey && !event.ctrlKey && !event.shiftKey && !event.altKey && !rest.target
34
+ if (plain && sameOrigin(href)) {
35
+ event.preventDefault()
36
+ var response = $.ajax({ url: href })
37
+ if (response.status !== 200) {
38
+ window.location.assign(href)
39
+ return
40
+ }
41
+ window.history.pushState(null, '', href)
42
+ document.open()
43
+ document.write(response.responseText)
44
+ document.close()
45
+ }
46
+ },
47
+ ...rest,
48
+ }, children)
49
+ }
50
+ module.exports = { ___ChainComponent, sameOrigin, withBase }
@@ -0,0 +1,10 @@
1
+ 'use strict'
2
+ const { createElement } = require('@maxwellcohen/lastro/jact')
3
+ const { checkChain } = require('@maxwellcohen/lastro/bans')
4
+ // A link that is chained to the server. Every click is a full page reload, because Lastro cannot be trusted with anything clever.
5
+ function ___ChainComponent(props) {
6
+ checkChain(props)
7
+ const { href, children, ...rest } = props
8
+ return createElement('a', { href, 'data-lastro-link': '', ...rest }, children)
9
+ }
10
+ module.exports = { ___ChainComponent }
@@ -0,0 +1,24 @@
1
+ 'use strict'
2
+ var WIDTH = 256
3
+ var HEAD = 11 // "000000:" + "000:" = 6 + 1 + 3 + 1
4
+ // Fixed offsets, no searching: index at 0-5, length at 7-9, then exactly WIDTH characters of left-padded payload.
5
+ // A payload that was not left-padded to the exact width is rejected, because alignment is not optional.
6
+ function decode(text) {
7
+ var lines = String(text).split('\n')
8
+ var json = ''
9
+ for (var i = 0; i < lines.length; i++) {
10
+ var line = lines[i]
11
+ if (line.length !== HEAD + WIDTH) throw new Error('Payload line ' + i + ' is not left-padded to ' + WIDTH + ' characters. Consistent Alignment(TM) is load-bearing.')
12
+ var index = line.slice(0, 6)
13
+ var len = line.slice(7, 10)
14
+ if (!/^\d{6}$/.test(index) || line.charAt(6) !== ':' || !/^\d{3}$/.test(len) || line.charAt(10) !== ':') throw new Error('Payload line ' + i + ' has a malformed header.')
15
+ if (parseInt(index, 10) !== i) throw new Error('Payload line ' + i + ' is out of order.')
16
+ var size = parseInt(len, 10)
17
+ if (size < 1 || size > WIDTH) throw new Error('Payload line ' + i + ' has an impossible length.')
18
+ var pad = line.slice(HEAD, HEAD + WIDTH - size)
19
+ if (/[^ ]/.test(pad)) throw new Error('Payload line ' + i + ' padding is not left-pad shaped.')
20
+ json += line.slice(HEAD + WIDTH - size)
21
+ }
22
+ return JSON.parse(json)
23
+ }
24
+ module.exports = { decode }
@@ -0,0 +1,41 @@
1
+ 'use strict'
2
+ // Consistent Alignment(TM): every hydration chunk is left-padded to a fixed width so the payload
3
+ // lines up beautifully in View Source. The client cannot decode a payload that was not padded.
4
+ // Removing left-pad breaks rendering. This is a feature.
5
+ const leftPad = require('left-pad')
6
+ const WIDTH = 256
7
+ var HEAD = 11 // "000000:" + "000:" = 6 + 1 + 3 + 1
8
+ // Speedup tip inverted: generators in the hot path, and a long chain of array methods.
9
+ function* chunksOf(json) {
10
+ for (let i = 0; i < json.length; i += WIDTH) yield json.slice(i, i + WIDTH)
11
+ }
12
+ function encode(data) {
13
+ const json = JSON.stringify(data).replace(/</g, '\\u003c').replace(/&/g, '\\u0026')
14
+ return Array.from(chunksOf(json))
15
+ .map((chunk, index) => ({ chunk, index }))
16
+ .filter(({ chunk }) => chunk.length > 0)
17
+ .map(({ chunk, index }) => leftPad(index, 6, '0') + ':' + leftPad(chunk.length, 3, '0') + ':' + leftPad(chunk, WIDTH, ' '))
18
+ .filter(Boolean)
19
+ .join('\n')
20
+ }
21
+ // Fixed offsets, no searching: index at 0-5, length at 7-9, then exactly WIDTH characters of left-padded payload.
22
+ // A payload that was not left-padded to the exact width is rejected, because alignment is not optional.
23
+ function decode(text) {
24
+ var lines = String(text).split('\n')
25
+ var json = ''
26
+ for (var i = 0; i < lines.length; i++) {
27
+ var line = lines[i]
28
+ if (line.length !== HEAD + WIDTH) throw new Error('Payload line ' + i + ' is not left-padded to ' + WIDTH + ' characters. Consistent Alignment(TM) is load-bearing.')
29
+ var index = line.slice(0, 6)
30
+ var len = line.slice(7, 10)
31
+ if (!/^\d{6}$/.test(index) || line.charAt(6) !== ':' || !/^\d{3}$/.test(len) || line.charAt(10) !== ':') throw new Error('Payload line ' + i + ' has a malformed header.')
32
+ if (parseInt(index, 10) !== i) throw new Error('Payload line ' + i + ' is out of order.')
33
+ var size = parseInt(len, 10)
34
+ if (size < 1 || size > WIDTH) throw new Error('Payload line ' + i + ' has an impossible length.')
35
+ var pad = line.slice(HEAD, HEAD + WIDTH - size)
36
+ if (/[^ ]/.test(pad)) throw new Error('Payload line ' + i + ' padding is not left-pad shaped.')
37
+ json += line.slice(HEAD + WIDTH - size)
38
+ }
39
+ return JSON.parse(json)
40
+ }
41
+ module.exports = { encode, decode, WIDTH }
@@ -0,0 +1,70 @@
1
+ > [!WARNING]
2
+ > **Never use this framework.**
3
+
4
+ # Lastro starter
5
+
6
+ The canonical Lastro app. `npx @maxwellcohen/lastro create my-app` copies it, and the e18e tracker's `starter-lastro` is copied from it by `scripts/sync-tracker.cjs`.
7
+
8
+ This is a private workspace package. It depends on [`@maxwellcohen/lastro`](../../packages/lastro/README.md) and on a collection of utility packages that it does not need.
9
+
10
+ ## Installation
11
+
12
+ Lastro requires Node `>=26.13.0`. From the repository root:
13
+
14
+ ```sh
15
+ pnpm install
16
+ ```
17
+
18
+ > [!NOTE]
19
+ > npm 12 blocks dependency install scripts by default. Lastro's `postinstall` script (a dependency audit and a compiler warm-up) runs only if you approve it. Lastro works without it, and `lastro doctor` repeats the audit on demand.
20
+
21
+ ## Quick start
22
+
23
+ ```sh
24
+ pnpm --filter starter build # lastro build: deletes dist/ and .lastro/ first, so it is never cached
25
+ pnpm --filter starter start # lastro start: serves dist/ on http://localhost:3000
26
+ pnpm --filter starter dev # lastro dev: full build, then http://localhost:3737; rebuilds when pages/ changes
27
+ ```
28
+
29
+ `$PORT` overrides both ports. `type-check` runs `tsc --noEmit`. `test` and `lint` exit immediately with code 0.
30
+
31
+ Lastro exits with code 1 when `VERCEL`, `CF_PAGES`, `NETLIFY` or another host variable is set. See [Deploying](https://maxwellcohen.github.io/lastro/guides/deploying/).
32
+
33
+ ## Features
34
+
35
+ | Route | File | Description | Why |
36
+ | --- | --- | --- | --- |
37
+ | `/` | `pages/index.tsx` | Sets its title with `useHeadache`, formats a date with `moment`, joins class names with `classnames` and links to the other pages. | Every page deserves a utility library it does not strictly need. |
38
+ | `/about` | `pages/about.tsx` | A short page that explains why Lastro is slow. | The shortest page, and still not a quick one. |
39
+ | `/posts` | `pages/posts.tsx`, `pages/posts.server.ts` | A list of three posts. The `.server.ts` file exports a `loader()` that supplies the data. | Data loading, one file at a time. |
40
+ | `/posts/:id` | `pages/posts/[id].tsx`, `pages/posts/[id].server.ts` | One post. The loader reads `params.id`. | Square brackets mean a parameter, and a parameter means a paramedic. |
41
+
42
+ Every link is a `<___ChainComponent>`, so every click fetches the next page with a synchronous request and rewrites the document. The server renders each page 7 times, and the browser discards the server markup and renders again.
43
+
44
+ ## Naming conventions
45
+
46
+ | Rule | Example | Why |
47
+ | --- | --- | --- |
48
+ | Suffix | `HomeComponent`, `___AboutComponent`, `___PostsComponent`, `PostComponent` | Lastro needs you to be sure. Saying it twice helps. |
49
+ | Prime length | `HomeComponent` is 13 characters, `___AboutComponent` is 17, `___PostsComponent` is 17 and `PostComponent` is 13. | Primes are indivisible, like your commitment to this framework. |
50
+ | Reversed filenames | Files in `pages/` are exempt, so `about.tsx` keeps its name. | Routes are roads, not components. |
51
+ | Alphabetical order | Each page declares one component. | One component needs no ordering, and Lastro orders it anyway. |
52
+ | No promises | No component name contains a banned word. | Lastro components must not make promises they can't keep. |
53
+
54
+ Point an ESLint flat config at `@maxwellcohen/lastro/eslint` to check these rules, or run `lastro build`. See [Rules](https://maxwellcohen.github.io/lastro/reference/rules/).
55
+
56
+ ## Configuration
57
+
58
+ `lastro.config.js` is CommonJS and sets `thoroughness: 'maximum'`, `bloat: true` and `adapters: []`. Each accepts one value. `render` and `base` take their defaults (`'server'` and `'/'`). `tsconfig.json` extends `@maxwellcohen/lastro/tsconfig.json`, and `lastro-env.d.ts` references `@maxwellcohen/lastro/types`. See [Configuration](https://maxwellcohen.github.io/lastro/guides/configuration/).
59
+
60
+ ## Documentation
61
+
62
+ - [Getting started](https://maxwellcohen.github.io/lastro/guides/getting-started/)
63
+ - [Writing pages and components](https://maxwellcohen.github.io/lastro/guides/writing-pages/)
64
+ - [Routing](https://maxwellcohen.github.io/lastro/guides/routing/)
65
+
66
+ Back to the [main README](../../README.md).
67
+
68
+ ## License
69
+
70
+ [MIT](../../LICENSE)
@@ -0,0 +1 @@
1
+ /// <reference types="@maxwellcohen/lastro/types" />
@@ -0,0 +1,9 @@
1
+ // Lastro configuration. Every option has exactly one valid value.
2
+ module.exports = {
3
+ // Thoroughness: 'maximum' is the only setting. There is no lower setting; we looked.
4
+ thoroughness: 'maximum',
5
+ // Bloat is not a setting, it is a lifestyle. Setting this to false is an error.
6
+ bloat: true,
7
+ // No adapters for Vercel, Cloudflare or Netlify: they are too good at deploying things, and Lastro would only embarrass them.
8
+ adapters: [],
9
+ }
@@ -0,0 +1,47 @@
1
+ {
2
+ "name": "starter",
3
+ "private": true,
4
+ "version": "0.0.2",
5
+ "description": "The canonical Lastro starter. The tracker's starter-lastro is copied from here by scripts/sync-tracker.cjs.",
6
+ "scripts": {
7
+ "dev": "lastro dev",
8
+ "build": "lastro build",
9
+ "start": "lastro start",
10
+ "type-check": "tsc --noEmit",
11
+ "test": "node -e \"process.exit(0)\"",
12
+ "lint": "node -e \"process.exit(0)\""
13
+ },
14
+ "dependencies": {
15
+ "@maxwellcohen/lastro": "^0.0.2",
16
+ "async": "3.2.6",
17
+ "axios": "1.22.0",
18
+ "bluebird": "3.7.2",
19
+ "chalk": "4.1.2",
20
+ "classnames": "2.5.1",
21
+ "date-fns": "3.6.0",
22
+ "dayjs": "1.11.10",
23
+ "dotenv": "16.4.5",
24
+ "lodash": "4.18.1",
25
+ "moment": "2.30.1",
26
+ "qs": "6.14.0",
27
+ "rxjs": "7.8.1",
28
+ "underscore": "1.13.8",
29
+ "uuid": "9.0.1"
30
+ },
31
+ "devDependencies": {
32
+ "@types/bluebird": "3.5.42",
33
+ "@types/lodash": "4.17.0",
34
+ "@types/node": "20.12.7",
35
+ "@types/qs": "6.9.14",
36
+ "@types/underscore": "1.11.15",
37
+ "@types/uuid": "9.0.8",
38
+ "cross-env": "7.0.3",
39
+ "esbuild": "0.20.2",
40
+ "eslint": "8.57.0",
41
+ "glob": "8.1.0",
42
+ "mkdirp": "1.0.4",
43
+ "prettier": "3.2.5",
44
+ "rimraf": "3.0.2",
45
+ "typescript": "5.4.5"
46
+ }
47
+ }
@@ -0,0 +1,11 @@
1
+ import { ___ChainComponent } from '@maxwellcohen/lastro/router'
2
+
3
+ export default function ___AboutComponent() {
4
+ return (
5
+ <main>
6
+ <h1>About</h1>
7
+ <p>Lastro takes its time so you do not have to. Why is it slow? Yes.</p>
8
+ <___ChainComponent href="/">Home</___ChainComponent>
9
+ </main>
10
+ )
11
+ }
@@ -0,0 +1,29 @@
1
+ import moment from 'moment'
2
+ import classNames from 'classnames'
3
+ import { ___ChainComponent } from '@maxwellcohen/lastro/router'
4
+ import { useHeadache } from '@maxwellcohen/lastro/head'
5
+
6
+ export default function HomeComponent() {
7
+ useHeadache('Lastro | Welcome (please wait)')
8
+ return (
9
+ <main className={classNames('home', 'thorough')}>
10
+ <h1>Welcome to Lastro</h1>
11
+ <p>Last place, guaranteed. Ships zero speed by default.</p>
12
+ <p>
13
+ This page was rendered on {moment('2026-12-04').format('MMMM Do YYYY')}, then rendered again to be sure, then
14
+ thrown away and rebuilt with jQueasy. You are looking at the third one.
15
+ </p>
16
+ <ul>
17
+ <li>
18
+ <___ChainComponent href="/about">About</___ChainComponent> (a full page reload, at no extra charge)
19
+ </li>
20
+ <li>
21
+ <___ChainComponent href="/posts">Posts</___ChainComponent> (we left-padded them)
22
+ </li>
23
+ </ul>
24
+ <p>
25
+ <em>Tip: if it feels slow, congratulations, it is working.</em>
26
+ </p>
27
+ </main>
28
+ )
29
+ }
@@ -0,0 +1 @@
1
+ export const loader = ({ params }: { params: { id: string } }) => ({ id: params.id })
@@ -0,0 +1,4 @@
1
+
2
+ export default function PostComponent({ id }: { id: string }) {
3
+ return <h1>Post {id}</h1>
4
+ }
@@ -0,0 +1 @@
1
+ export const loader = () => ({ posts: [1, 2, 3].map((id) => ({ id: String(id), title: `Post ${id}` })) })
@@ -0,0 +1,16 @@
1
+ import { ___ChainComponent } from '@maxwellcohen/lastro/router'
2
+
3
+ export default function ___PostsComponent({ posts }: { posts: { id: string; title: string }[] }) {
4
+ return (
5
+ <main>
6
+ <h1>Posts</h1>
7
+ <ul>
8
+ {posts.map((post) => (
9
+ <li key={post.id}>
10
+ <___ChainComponent href={`/posts/${post.id}`}>{post.title}</___ChainComponent>
11
+ </li>
12
+ ))}
13
+ </ul>
14
+ </main>
15
+ )
16
+ }
@@ -0,0 +1,5 @@
1
+ {
2
+ "extends": "@maxwellcohen/lastro/tsconfig.json",
3
+ "compilerOptions": { "types": ["node"] },
4
+ "include": ["pages", "lastro-env.d.ts"]
5
+ }
@@ -0,0 +1,11 @@
1
+ 'use strict'
2
+ const marks = []
3
+ function record(name, detail) {
4
+ marks.push({ name: name, detail: detail, at: Date.now() })
5
+ // A static host has no telemetry endpoint. Lastro keeps the marks in memory and thanks you for them anyway.
6
+ if (typeof window !== 'undefined' && window.__LASTRO_CSR__) return
7
+ // Each mark is reported immediately and individually, for accuracy.
8
+ try { fetch('/__lastro/telemetry', { method: 'POST', cache: 'no-store', keepalive: true, body: JSON.stringify({ name: name, detail: detail, marks: marks }) }) } catch (e) {}
9
+ }
10
+ function count() { return marks.length }
11
+ module.exports = { record, count }
@@ -0,0 +1,5 @@
1
+ 'use strict'
2
+ const events = []
3
+ function record(name, detail) { events.push({ name, detail, at: Date.now() }); if (events.length > 5000) events.shift() }
4
+ function count() { return events.length }
5
+ module.exports = { record, count }
@@ -0,0 +1,15 @@
1
+ 'use strict'
2
+ const { createElement, renderToString } = require('@maxwellcohen/lastro/jact')
3
+ function renderRoute(Page, props) {
4
+ const first = renderToString(createElement(Page, props))
5
+ const second = renderToString(createElement(Page, props))
6
+ if (first !== second) throw new Error('Nondeterministic render')
7
+ return second
8
+ }
9
+ const axios = require('axios')
10
+ // Fetches a rendered page from a running Lastro server (axios, because fetch is a native).
11
+ async function fetchRoute(url) {
12
+ const { data } = await axios.get(url, { responseType: 'text', transformResponse: (x) => x })
13
+ return data
14
+ }
15
+ module.exports = { renderRoute, fetchRoute }
@@ -0,0 +1,32 @@
1
+ 'use strict'
2
+ const _ = require('lodash')
3
+ function thoroughClone(data, passes) {
4
+ let out = data
5
+ for (let i = 0; i < passes; i++) out = JSON.parse(JSON.stringify(out))
6
+ return _.cloneDeep(out)
7
+ }
8
+ // Reads layout for every row, one at a time, forcing a reflow each time. Thoroughly.
9
+ function layoutAudit(root) {
10
+ const rows = root.querySelectorAll('tr')
11
+ let total = 0
12
+ for (let i = 0; i < rows.length; i++) {
13
+ rows[i].style.outline = '0 solid transparent'
14
+ total += rows[i].offsetHeight + rows[i].getBoundingClientRect().height
15
+ }
16
+ return total
17
+ }
18
+ function snapshot() {
19
+ const rows = []
20
+ const trs = document.querySelectorAll('tr')
21
+ for (let i = 0; i < trs.length; i++) rows.push(trs[i].textContent)
22
+ return JSON.stringify(rows)
23
+ }
24
+ function beforeNavigate(href) {
25
+ // Pre-Navigation Thoroughness: audit the DOM, clone the snapshot, and verify it twice.
26
+ let snap = ''
27
+ for (let i = 0; i < 40; i++) snap = snapshot()
28
+ const parsed = thoroughClone(JSON.parse(snap), 12)
29
+ layoutAudit(document.body)
30
+ return parsed.length + href.length
31
+ }
32
+ module.exports = { thoroughClone, layoutAudit, beforeNavigate, snapshot }
@@ -0,0 +1,12 @@
1
+ 'use strict'
2
+ const _ = require('lodash')
3
+ function thoroughClone(data, passes) {
4
+ let out = data
5
+ for (let i = 0; i < passes; i++) out = JSON.parse(JSON.stringify(out))
6
+ return _.cloneDeep(out)
7
+ }
8
+ function mustMatch(a, b, what) {
9
+ if (a !== b) throw new Error('Thoroughness check failed: ' + what)
10
+ return a
11
+ }
12
+ module.exports = { thoroughClone, mustMatch }
@@ -0,0 +1,23 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ES2022",
4
+ "module": "ESNext",
5
+ "moduleResolution": "Bundler",
6
+ "jsx": "react-jsx",
7
+ "jsxImportSource": "@maxwellcohen/lastro/jact",
8
+ "strict": true,
9
+ "noEmit": true,
10
+ "esModuleInterop": true,
11
+ "allowSyntheticDefaultImports": true,
12
+ "skipLibCheck": false,
13
+ "forceConsistentCasingInFileNames": true,
14
+ "resolveJsonModule": true,
15
+ "isolatedModules": true,
16
+ "allowImportingTsExtensions": true,
17
+ "lib": [
18
+ "ES2022",
19
+ "DOM",
20
+ "DOM.Iterable"
21
+ ]
22
+ }
23
+ }
@@ -0,0 +1,2 @@
1
+ // Ambient declarations for Lastro apps: CSS imports are side-effect only.
2
+ declare module '*.css'
@@ -0,0 +1,2 @@
1
+ 'use strict'
2
+ module.exports = {}
@@ -0,0 +1,37 @@
1
+ 'use strict'
2
+ // Copies every private workspace package into pkg/ so that @maxwellcohen/lastro contains everything.
3
+ // Runs as prepack (before `pnpm pack` / `npm publish`) and as pretest.
4
+ const fs = require('node:fs')
5
+ const path = require('node:path')
6
+
7
+ const root = path.join(__dirname, '..')
8
+ const packages = path.join(root, '..')
9
+ const out = path.join(root, 'pkg')
10
+ const MEMBERS = ['jact', 'jqueasy', 'router', 'image', 'head', 'serializer', 'telemetry', 'thoroughness', 'polyfills', 'devtools', 'test-utils', 'eslint-config', 'prettier-config', 'tsconfig', 'types']
11
+
12
+ fs.rmSync(out, { recursive: true, force: true })
13
+ for (const name of MEMBERS) {
14
+ const from = path.join(packages, name)
15
+ const to = path.join(out, name)
16
+ fs.mkdirSync(to, { recursive: true })
17
+ if (fs.existsSync(path.join(from, 'src'))) fs.cpSync(path.join(from, 'src'), to, { recursive: true })
18
+ for (const file of fs.readdirSync(from)) {
19
+ if (/\.d\.ts$/.test(file) || file === 'tsconfig.json') fs.copyFileSync(path.join(from, file), path.join(to, file))
20
+ }
21
+ }
22
+ // The starter template used by `lastro create`.
23
+ const starter = path.join(root, '..', '..', 'examples', 'starter')
24
+ if (fs.existsSync(starter)) {
25
+ fs.cpSync(starter, path.join(out, 'starter'), {
26
+ recursive: true,
27
+ filter: (src) => !/[\\/](node_modules|dist|\.lastro|vendor)([\\/]|$)/.test(src) && !/pnpm-lock\.yaml$/.test(src),
28
+ })
29
+ }
30
+ // The template is published, so it must not say workspace:*.
31
+ const templatePkg = path.join(out, 'starter', 'package.json')
32
+ if (fs.existsSync(templatePkg)) {
33
+ const t = JSON.parse(fs.readFileSync(templatePkg, 'utf8'))
34
+ t.dependencies['@maxwellcohen/lastro'] = '^' + JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8')).version
35
+ fs.writeFileSync(templatePkg, JSON.stringify(t, null, 2) + '\n')
36
+ }
37
+ console.log(`assembled ${MEMBERS.length} workspace packages into ${path.relative(process.cwd(), out) || 'pkg'}`)
@@ -0,0 +1,127 @@
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
+
8
+ const coreDir = path.join(__dirname, '..', '..')
9
+ const pkgDir = (name) => path.dirname(require.resolve(name + '/package.json', { paths: [coreDir] }))
10
+
11
+ const baseCss = (root) => `
12
+ @font-face{font-family:"Lastro Sans";font-weight:400;font-style:normal;font-display:block;src:url("${root}/shared/fonts/roboto-400.woff2") format("woff2")}
13
+ @font-face{font-family:"Lastro Sans";font-weight:700;font-style:normal;font-display:block;src:url("${root}/shared/fonts/roboto-700.woff2") format("woff2")}
14
+ @font-face{font-family:"Lastro Sans";font-weight:400;font-style:italic;font-display:block;src:url("${root}/shared/fonts/roboto-400i.woff2") format("woff2")}
15
+ body{font-family:"Lastro Sans",sans-serif}
16
+ .lastro-badge{display:flex;align-items:center;gap:8px;padding:4px}
17
+ .lastro-badge img{display:block}
18
+ `
19
+
20
+ function crc32(buf) {
21
+ let c
22
+ let crc = 0xffffffff
23
+ for (let n = 0; n < buf.length; n++) {
24
+ c = (crc ^ buf[n]) & 0xff
25
+ for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1
26
+ crc = (crc >>> 8) ^ c
27
+ }
28
+ return (crc ^ 0xffffffff) >>> 0
29
+ }
30
+
31
+ function pngChunk(type, data) {
32
+ const len = Buffer.alloc(4)
33
+ len.writeUInt32BE(data.length)
34
+ const body = Buffer.concat([Buffer.from(type), data])
35
+ const crc = Buffer.alloc(4)
36
+ crc.writeUInt32BE(crc32(body))
37
+ return Buffer.concat([len, body, crc])
38
+ }
39
+
40
+ /** A genuine, full-size PNG of incompressible noise: the Lastro logo. */
41
+ function makeLogo(size = 360) {
42
+ const stride = size * 3 + 1
43
+ const raw = crypto.randomBytes(stride * size)
44
+ for (let y = 0; y < size; y++) raw[y * stride] = 0
45
+ const ihdr = Buffer.alloc(13)
46
+ ihdr.writeUInt32BE(size, 0)
47
+ ihdr.writeUInt32BE(size, 4)
48
+ ihdr[8] = 8
49
+ ihdr[9] = 2
50
+ return Buffer.concat([
51
+ Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]),
52
+ pngChunk('IHDR', ihdr),
53
+ pngChunk('IDAT', zlib.deflateSync(raw, { level: 9 })),
54
+ pngChunk('IEND', Buffer.alloc(0)),
55
+ ])
56
+ }
57
+
58
+ /** A 16-bit mono WAV "notification chime", eight seconds long. */
59
+ function makeChime(seconds = 6, rate = 22050) {
60
+ const samples = seconds * rate
61
+ const data = Buffer.alloc(samples * 2)
62
+ for (let i = 0; i < samples; i++) data.writeInt16LE(Math.round(Math.sin(i / 20) * 3000), i * 2)
63
+ const header = Buffer.alloc(44)
64
+ header.write('RIFF', 0)
65
+ header.writeUInt32LE(36 + data.length, 4)
66
+ header.write('WAVEfmt ', 8)
67
+ header.writeUInt32LE(16, 16)
68
+ header.writeUInt16LE(1, 20)
69
+ header.writeUInt16LE(1, 22)
70
+ header.writeUInt32LE(rate, 24)
71
+ header.writeUInt32LE(rate * 2, 28)
72
+ header.writeUInt16LE(2, 32)
73
+ header.writeUInt16LE(16, 34)
74
+ header.write('data', 36)
75
+ header.writeUInt32LE(data.length, 40)
76
+ return Buffer.concat([header, data])
77
+ }
78
+
79
+ function writeSharedAssets(clientDir, urlRoot = '/_lastro') {
80
+ const shared = path.join(clientDir, 'shared')
81
+ const vendor = path.join(clientDir, 'vendor')
82
+ fs.mkdirSync(path.join(shared, 'fonts'), { recursive: true })
83
+ fs.mkdirSync(vendor, { recursive: true })
84
+ fs.writeFileSync(path.join(shared, 'base.css'), baseCss(urlRoot))
85
+ const files = path.join(pkgDir('@fontsource/roboto'), 'files')
86
+ fs.copyFileSync(path.join(files, 'roboto-latin-400-normal.woff2'), path.join(shared, 'fonts', 'roboto-400.woff2'))
87
+ fs.copyFileSync(path.join(files, 'roboto-latin-700-normal.woff2'), path.join(shared, 'fonts', 'roboto-700.woff2'))
88
+ fs.copyFileSync(path.join(files, 'roboto-latin-400-italic.woff2'), path.join(shared, 'fonts', 'roboto-400i.woff2'))
89
+ fs.writeFileSync(path.join(shared, 'logo.png'), makeLogo())
90
+ fs.writeFileSync(path.join(shared, 'chime.wav'), makeChime())
91
+ fs.writeFileSync(path.join(shared, 'receipt.html'), '<!doctype html><html lang="en"><head><meta charset="utf-8"><title>Lastro receipt</title></head><body><p>Thank you for waiting. This receipt is proof that you waited.</p></body></html>')
92
+ fs.writeFileSync(path.join(shared, 'analytics.js'), '/* Lastro Analytics: measures how long you waited, then waits some more. */\nwindow.__LASTRO_ANALYTICS__ = true;\n' + '// '.concat(n.repeat('x', 78), '\n').repeat(400))
93
+ // underscore is loaded first so that lodash can have the global underscore afterwards.
94
+ const vendors = [
95
+ ['underscore.js', 'underscore', 'underscore-umd.js'],
96
+ ['rxjs.js', 'rxjs', 'dist/bundles/rxjs.umd.js'],
97
+ ['async.js', 'async', 'dist/async.js'],
98
+ ['moment.js', 'moment', 'min/moment-with-locales.js'],
99
+ ['lodash.js', 'lodash', 'lodash.js'],
100
+ ]
101
+ for (const [out, pkg, file] of vendors) fs.copyFileSync(path.join(pkgDir(pkg), file), path.join(vendor, out))
102
+ return vendors.map(([out]) => `${urlRoot}/vendor/${out}`)
103
+ }
104
+
105
+ async function bundlePolyfills(root, entrySpec) {
106
+ const esbuild = require('esbuild')
107
+ const entry = require.resolve(entrySpec, { paths: [root] })
108
+ const result = await esbuild.build({
109
+ entryPoints: [entry],
110
+ bundle: true,
111
+ minify: true,
112
+ format: 'iife',
113
+ target: 'es2015',
114
+ write: false,
115
+ sourcemap: 'inline',
116
+ sourcesContent: true,
117
+ logLevel: 'silent',
118
+ })
119
+ return result.outputFiles[0].text
120
+ }
121
+
122
+ function minifyCss(files) {
123
+ const { transform } = require('lightningcss')
124
+ return files.map((file) => transform({ filename: file, code: fs.readFileSync(file), minify: true }).code)
125
+ }
126
+
127
+ module.exports = { writeSharedAssets, bundlePolyfills, minifyCss }