@tylix/compiler 0.3.5 → 0.3.7

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.
@@ -9,12 +9,18 @@ import { Lexer } from './lexer/Lexer.js'
9
9
  import { Parser } from './parser/Parser.js'
10
10
  import { generatePage } from './codegen/generatePage.js'
11
11
  import { generateTemplate } from './codegen/generateTemplate.js'
12
+ import { generateCapability } from './codegen/generateCapability.js'
13
+ import { substituteCapabilityRefs } from './ast/substituteCapabilityRefs.js'
12
14
 
13
15
  const __dirname = path.dirname(fileURLToPath(import.meta.url))
14
16
  const RUNTIME_SOURCE = fs
15
17
  .readFileSync(path.join(__dirname, 'runtime', 'reactive.js'), 'utf-8')
16
18
  .replace(/export\s+/g, '')
17
19
 
20
+ const CAPABILITY_SOURCE = fs
21
+ .readFileSync(path.join(__dirname, 'runtime', 'capability.js'), 'utf-8')
22
+ .replace(/export\s+/g, '')
23
+
18
24
  const LOADING_INDICATOR_SOURCE = fs
19
25
  .readFileSync(path.join(__dirname, 'runtime', 'loadingIndicator.js'), 'utf-8')
20
26
  .replace(/export\s+/g, '')
@@ -27,15 +33,67 @@ const USE_CHANNEL_SOURCE = fs
27
33
  .readFileSync(path.join(__dirname, 'runtime', 'useChannel.js'), 'utf-8')
28
34
  .replace(/export\s+/g, '')
29
35
 
36
+ const capabilityCache = new Map() // capabilitiesDir -> { signature, code }
37
+
38
+ async function loadCapabilityDefinitions(capabilitiesDir) {
39
+ const exists = await fs.promises
40
+ .access(capabilitiesDir)
41
+ .then(() => true)
42
+ .catch(() => false)
43
+ if (!exists) return ''
44
+
45
+ const files = (await fs.promises.readdir(capabilitiesDir)).filter((f) =>
46
+ f.endsWith('.tyx'),
47
+ )
48
+ if (files.length === 0) return ''
49
+
50
+ const stats = await Promise.all(
51
+ files.map((f) => fs.promises.stat(path.join(capabilitiesDir, f))),
52
+ )
53
+ const signature = files
54
+ .map((f, i) => `${f}:${stats[i].mtimeMs}`)
55
+ .sort()
56
+ .join('|')
57
+
58
+ const cached = capabilityCache.get(capabilitiesDir)
59
+ if (cached && cached.signature === signature) {
60
+ return cached.code
61
+ }
62
+
63
+ const definitions = (
64
+ await Promise.all(
65
+ files.map(async (file) => {
66
+ const source = await fs.promises.readFile(
67
+ path.join(capabilitiesDir, file),
68
+ 'utf-8',
69
+ )
70
+ try {
71
+ const capabilityNode = new Parser(
72
+ new Lexer(source).tokenize(),
73
+ ).parseCapability()
74
+ return generateCapability(capabilityNode)
75
+ } catch (err) {
76
+ err.message = `In app/capabilities/${file}: ${err.message}`
77
+ throw err
78
+ }
79
+ }),
80
+ )
81
+ ).join('\n\n')
82
+
83
+ capabilityCache.set(capabilitiesDir, { signature, code: definitions })
84
+ return definitions
85
+ }
86
+
30
87
  function compileComponentSource(source, fallbackClassName) {
31
88
  const isNativeComponent = /^\s*component\s+\w+/.test(source)
32
89
 
33
90
  if (isNativeComponent) {
34
91
  const { componentName, script, template } = parseComponentFile(source)
35
- const pageNode =
92
+ const pageNode = substituteCapabilityRefs(
36
93
  script.trim().length > 0
37
94
  ? new Parser(new Lexer(script).tokenize()).parse()
38
- : { props: [], state: [], computed: [], actions: [] }
95
+ : { props: [], state: [], computed: [], actions: [], uses: [] },
96
+ )
39
97
 
40
98
  const classSource = generatePage(pageNode, componentName)
41
99
  const templateNodes = parseTemplate(template)
@@ -46,10 +104,11 @@ function compileComponentSource(source, fallbackClassName) {
46
104
 
47
105
  const { script, template } = parseComponent(source)
48
106
 
49
- const pageNode =
107
+ const pageNode = substituteCapabilityRefs(
50
108
  script.trim().length > 0
51
109
  ? new Parser(new Lexer(script).tokenize()).parse()
52
- : { props: [], state: [], computed: [], actions: [] }
110
+ : { props: [], state: [], computed: [], actions: [], uses: [] },
111
+ )
53
112
 
54
113
  const classSource = generatePage(pageNode, fallbackClassName)
55
114
  const templateNodes = parseTemplate(template)
@@ -88,10 +147,16 @@ function parseTemplateWithLineOffset(template, offset) {
88
147
  }
89
148
  }
90
149
 
91
- export function renderPageDocument(
150
+ export async function renderPageDocument(
92
151
  source,
93
152
  childComponents = {},
94
- { layout = null, props = {}, apiHelpers = '', channelsPort = null } = {},
153
+ {
154
+ layout = null,
155
+ props = {},
156
+ apiHelpers = '',
157
+ channelsPort = null,
158
+ capabilitiesDir = path.join(process.cwd(), 'app', 'capabilities'),
159
+ } = {},
95
160
  ) {
96
161
  const {
97
162
  pageName,
@@ -102,16 +167,19 @@ export function renderPageDocument(
102
167
  templateStartLine,
103
168
  } = parsePageFile(source)
104
169
 
105
- const pageNode =
170
+ const pageNode = substituteCapabilityRefs(
106
171
  script.trim().length > 0
107
172
  ? parseScriptWithLineOffset(script, scriptStartLine)
108
- : { props: [], state: [], computed: [], actions: [] }
173
+ : { props: [], state: [], computed: [], actions: [], uses: [] },
174
+ )
109
175
 
110
176
  const classSource = generatePage(pageNode, pageName)
111
177
 
112
178
  const templateNodes = parseTemplateWithLineOffset(template, templateStartLine)
113
179
  const { code, rootVar } = generateTemplate(templateNodes)
114
180
 
181
+ const capabilityDefinitions = await loadCapabilityDefinitions(capabilitiesDir)
182
+
115
183
  const childNames = Object.keys(childComponents)
116
184
  const childClassSources = childNames
117
185
  .map(
@@ -163,6 +231,10 @@ ${layoutCompiled.code}
163
231
  const inlineScript = `
164
232
  ${RUNTIME_SOURCE}
165
233
 
234
+ ${CAPABILITY_SOURCE}
235
+
236
+ ${capabilityDefinitions}
237
+
166
238
  ${LOADING_INDICATOR_SOURCE}
167
239
 
168
240
  ${USE_API_SOURCE}
@@ -181,7 +253,13 @@ document.addEventListener("DOMContentLoaded", () => {
181
253
  const instance = new ${pageName}(${JSON.stringify(props)});
182
254
  const components = {};
183
255
  ${childRegistrations}
184
- (function (document, instance, components) {
256
+ (async function (document, instance, components) {
257
+ if (typeof instance.__ready === "function") {
258
+ await instance.__ready();
259
+ }
260
+ if (typeof instance.__onMount === "function") {
261
+ await instance.__onMount();
262
+ }
185
263
  ${code}
186
264
  ${layoutMountCode}
187
265
  })(document, instance, components);
@@ -192,6 +270,8 @@ ${layoutMountCode}
192
270
 
193
271
  const scriptSegments = [
194
272
  { name: 'runtime (reactive.js)', code: RUNTIME_SOURCE },
273
+ { name: 'runtime (capability.js)', code: CAPABILITY_SOURCE },
274
+ { name: 'capability definitions', code: capabilityDefinitions },
195
275
  { name: 'loading indicator', code: LOADING_INDICATOR_SOURCE },
196
276
  { name: 'useApi', code: USE_API_SOURCE },
197
277
  { name: 'useChannel', code: USE_CHANNEL_SOURCE },
@@ -238,7 +318,7 @@ ${layoutMountCode}
238
318
  }
239
319
  })();
240
320
  </script>
241
- <title>${pageName}</title>
321
+ <title>${pageNode.title ?? pageName}</title>
242
322
  <link rel="stylesheet" href="/tailwind.css">
243
323
  ${styleTag}
244
324
  </head>
@@ -35,7 +35,7 @@ template
35
35
  </div>
36
36
  `
37
37
 
38
- const html = renderPageDocument(source)
38
+ const html = await renderPageDocument(source)
39
39
  assert.match(html, /<title>CounterPage<\/title>/)
40
40
 
41
41
  const dom = await loadDocument(html)
@@ -62,7 +62,7 @@ template
62
62
  </div>
63
63
  `
64
64
 
65
- const html = renderPageDocument(source, {}, { props: { id: '42' } })
65
+ const html = await renderPageDocument(source, {}, { props: { id: '42' } })
66
66
  const dom = await loadDocument(html)
67
67
  const span = dom.window.document.querySelector('#app span')
68
68
 
@@ -79,19 +79,19 @@ template
79
79
  style
80
80
  p { color: red; }
81
81
  `
82
- const html = renderPageDocument(source)
82
+ const html = await renderPageDocument(source)
83
83
  assert.match(html, /<style>\s*p \{ color: red; \}\s*<\/style>/)
84
84
  })
85
85
 
86
86
  test('omits the style tag entirely when no style section is present', async () => {
87
87
  const source = `page Home\n\ntemplate\n <p>Hello</p>`
88
- const html = renderPageDocument(source)
88
+ const html = await renderPageDocument(source)
89
89
  assert.doesNotMatch(html, /<style>/)
90
90
  })
91
91
 
92
92
  test('supports a page with no script section at all', async () => {
93
93
  const source = `page Static\n\ntemplate\n <p>Just static markup</p>`
94
- const html = renderPageDocument(source)
94
+ const html = await renderPageDocument(source)
95
95
  const dom = await loadDocument(html)
96
96
  assert.equal(
97
97
  dom.window.document.querySelector('#app p').textContent,
@@ -116,10 +116,10 @@ template
116
116
  </div>
117
117
  `
118
118
 
119
- const html = renderPageDocument(pageSource, { Badge: badgeSource })
119
+ const html = await renderPageDocument(pageSource, { Badge: badgeSource })
120
120
  const dom = await loadDocument(html)
121
121
  const { document } = dom.window
122
122
 
123
123
  assert.equal(document.querySelector('#app h1').textContent, 'Ada Lovelace')
124
124
  assert.equal(document.querySelector('#app .badge').textContent, 'Verified')
125
- })
125
+ })
@@ -0,0 +1,61 @@
1
+ // Capability registry: singleton, framework-managed state/action
2
+ // bundles that pages access via `uses` (see generatePage.js's
3
+ // usesAccessors, which call resolveCapability(name) as a getter).
4
+ // One instance per capability name, shared across every page in the
5
+ // app -- resolveCapability memoizes on first resolution rather than
6
+ // re-running the def, the same "resolve once, reuse forever" shape
7
+ // createResource's .load() gives resources, just app-scoped instead
8
+ // of per-page.
9
+ //
10
+ // A capability def has the shape:
11
+ // {
12
+ // state: { ... }, // plain object, becomes reactive()
13
+ // actions: { name(...) {} }, // methods; `this` bound to the
14
+ // // reactive instance so they can
15
+ // // read/write state like a page
16
+ // // action can
17
+ // async init() { ... }, // optional, runs once; `this`
18
+ // // bound the same way
19
+ // }
20
+
21
+ const registry = new Map()
22
+
23
+ export function defineCapability(name, def) {
24
+ registry.set(name, { def, instance: null, initPromise: null })
25
+ }
26
+
27
+ export function bindActions(actions, instance) {
28
+ const bound = {}
29
+ for (const key of Object.keys(actions ?? {})) {
30
+ bound[key] = actions[key].bind(instance)
31
+ }
32
+ return bound
33
+ }
34
+
35
+ export function resolveCapability(name) {
36
+ const entry = registry.get(name)
37
+ if (!entry) {
38
+ throw new Error(
39
+ `Unknown capability "${name}". Did you forget to register it with defineCapability()?`,
40
+ )
41
+ }
42
+
43
+ if (!entry.instance) {
44
+ entry.instance = reactive({ ...entry.def.state })
45
+ Object.assign(
46
+ entry.instance,
47
+ bindActions(entry.def.actions, entry.instance),
48
+ )
49
+ }
50
+
51
+ if (!entry.initPromise && entry.def.init) {
52
+ entry.initPromise = entry.def.init.call(entry.instance)
53
+ }
54
+
55
+ // Exposed so pages can `await Auth.ready()` before making a
56
+ // redirect decision, instead of racing the reactive `loading` flag
57
+ // with their own onMount timing.
58
+ entry.instance.ready = () => entry.initPromise ?? Promise.resolve()
59
+
60
+ return entry.instance
61
+ }
@@ -7,6 +7,7 @@ import {
7
7
  mapVirtualLineToSource,
8
8
  } from './typecheck/buildVirtualTs.js'
9
9
  import { typecheckSource } from './typecheck/typecheckVirtualFile.js'
10
+ import { substituteCapabilityRefs } from './ast/substituteCapabilityRefs.js'
10
11
 
11
12
  // Derives the virtual class/interface name from the page's own
12
13
  // `page <Name>` declaration (via parsePageFile) -- the same source
@@ -22,10 +23,11 @@ import { typecheckSource } from './typecheck/typecheckVirtualFile.js'
22
23
  export function typecheckPage(source, apiHelpersSource = '') {
23
24
  const { pageName, script, template, scriptStartLine } = parsePageFile(source)
24
25
 
25
- const pageNode =
26
+ const pageNode = substituteCapabilityRefs(
26
27
  script.trim().length > 0
27
28
  ? new Parser(new Lexer(script).tokenize()).parse()
28
- : { props: [], state: [], computed: [], actions: [], onMount: null }
29
+ : { props: [], state: [], computed: [], actions: [], onMount: null },
30
+ )
29
31
 
30
32
  const templateNodes =
31
33
  template.trim().length > 0 ? parseTemplate(template) : null
@@ -0,0 +1,116 @@
1
+ import { test } from 'node:test'
2
+ import assert from 'node:assert/strict'
3
+ import { mkdtemp, mkdir, writeFile, rm } from 'node:fs/promises'
4
+ import { tmpdir } from 'node:os'
5
+ import path from 'node:path'
6
+ import { parsePageFile } from '../src/parser/parsePageFile.js'
7
+ import { Lexer } from '../src/lexer/Lexer.js'
8
+ import { Parser } from '../src/parser/Parser.js'
9
+ import { generatePage } from '../src/codegen/generatePage.js'
10
+ import { renderPageDocument } from '../src/renderPageDocument.js'
11
+
12
+ const SOURCE = `page Dashboard
13
+ title "Dashboard"
14
+ layout DashboardLayout
15
+ needs
16
+ Auth
17
+ uses
18
+ Theme
19
+ Posts
20
+ prefetch
21
+ Posts.latest
22
+ background
23
+ Analytics
24
+ permissions
25
+ posts.view
26
+ meta
27
+ transition "fade"
28
+ keepAlive true
29
+ cache 10m
30
+ state
31
+ search: ""
32
+ computed
33
+ filteredPosts() {
34
+ return Posts.where(post => post.title.contains(this.search))
35
+ }
36
+ actions
37
+ async publishPost(post) {
38
+ await Posts.publish(post)
39
+ }
40
+ template
41
+ <div>{{ search }}</div>
42
+ `
43
+
44
+ function parseScript() {
45
+ const { script } = parsePageFile(SOURCE)
46
+ const tokens = new Lexer(script).tokenize()
47
+ return new Parser(tokens).parse()
48
+ }
49
+
50
+ test('parses all six page-level sections without throwing', () => {
51
+ const page = parseScript()
52
+
53
+ assert.equal(page.title, 'Dashboard')
54
+ assert.equal(page.layout, 'DashboardLayout')
55
+ assert.deepEqual(
56
+ page.needs.map((n) => n.name),
57
+ ['Auth'],
58
+ )
59
+ assert.deepEqual(
60
+ page.uses.map((u) => u.name),
61
+ ['Theme', 'Posts'],
62
+ )
63
+ assert.equal(page.prefetch[0].capability, 'Posts')
64
+ assert.equal(page.prefetch[0].member, 'latest')
65
+ assert.deepEqual(
66
+ page.background.map((b) => b.name),
67
+ ['Analytics'],
68
+ )
69
+ assert.deepEqual(
70
+ page.permissions.map((p) => p.name),
71
+ ['posts.view'],
72
+ )
73
+
74
+ const meta = Object.fromEntries(page.meta.map((m) => [m.key, m.value]))
75
+ assert.equal(meta.transition, 'fade')
76
+ assert.equal(meta.keepAlive, true)
77
+ assert.equal(meta.cache, '10m')
78
+ })
79
+
80
+ test('generated page class is syntactically valid JS', () => {
81
+ const page = parseScript()
82
+ const classSource = generatePage(page, 'Dashboard')
83
+
84
+ assert.doesNotThrow(() => new Function(classSource), classSource)
85
+ assert.match(classSource, /async __ready\(\)/)
86
+ assert.match(classSource, /resolveCapability\("Auth"\)\.ready\(\)/)
87
+ assert.match(classSource, /resolveCapability\("Posts"\)\.latest\(\)/)
88
+ })
89
+
90
+ test('renderPageDocument compiles the full Dashboard against stub capabilities', async () => {
91
+ const dir = await mkdtemp(path.join(tmpdir(), 'tylix-test-'))
92
+ const capabilitiesDir = path.join(dir, 'capabilities')
93
+ await mkdir(capabilitiesDir, { recursive: true })
94
+
95
+ await writeFile(
96
+ path.join(capabilitiesDir, 'Auth.tyx'),
97
+ `capability Auth\nstate\n user: null\naction\n noop() {}\n`,
98
+ )
99
+ await writeFile(
100
+ path.join(capabilitiesDir, 'Theme.tyx'),
101
+ `capability Theme\nstate\n mode: "dark"\naction\n noop() {}\n`,
102
+ )
103
+ await writeFile(
104
+ path.join(capabilitiesDir, 'Posts.tyx'),
105
+ `capability Posts\nstate\n data: []\naction\n async latest() {}\n where(fn) { return this.data.filter(fn) }\n`,
106
+ )
107
+ await writeFile(
108
+ path.join(capabilitiesDir, 'Analytics.tyx'),
109
+ `capability Analytics\nstate\n visitorsToday: 0\naction\n noop() {}\n`,
110
+ )
111
+
112
+ const html = await renderPageDocument(SOURCE, {}, { capabilitiesDir })
113
+ assert.match(html, /<title>Dashboard<\/title>/)
114
+
115
+ await rm(dir, { recursive: true, force: true })
116
+ })