@tylix/compiler 2.0.0 → 2.1.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tylix/compiler",
3
- "version": "2.0.0",
3
+ "version": "2.1.1",
4
4
  "description": "Compiler for Tylix .tyx pages and components: parses, type-checks and compiles them to server-rendered HTML and client JavaScript.",
5
5
  "license": "MIT",
6
6
  "author": "Mbiyrukzz",
package/src/index.js CHANGED
@@ -23,3 +23,4 @@ export * from './imports/resolveImports.js'
23
23
  export * from './runtime/capability.js'
24
24
  export * from './codegen/generateCapability.js'
25
25
  export * from './diagnostics/diagnose.js'
26
+ export * from './loadingScreen.js'
@@ -0,0 +1,44 @@
1
+ // The loading screen: what a visitor sees between the first byte and the
2
+ // page's first render, instead of a blank window. Native .tyx pages render
3
+ // in the browser (and wait for their `needs` capabilities), and React, Vue,
4
+ // Svelte and Angular pages do too when they aren't server-rendered.
5
+ //
6
+ // The Tylix mark's three strokes light up in turn over an indeterminate
7
+ // bar, in the app's own colours (the tylix-ui tokens, with fallbacks), in
8
+ // light and dark. It only fades in after 150ms, so fast pages never flash
9
+ // it, and leaves as soon as the page puts something in its root element.
10
+ // A page that never renders still gets rid of it after 15 seconds.
11
+ //
12
+ // Turn it off with loadingScreen: false in tylix.config.
13
+
14
+ const MARK = `<svg class="tls-mark" viewBox="0 0 552 366" aria-hidden="true" focusable="false"><path class="tls-s1" d="M0 96 74 22Q96 0 120 0H552L482 77Q462 96 436 96Z"/><path class="tls-s2" d="M34 366 148 151Q160 127 190 127H290L163 366Z"/><path class="tls-s3" d="M218 339 294 192Q304 171 334 171H442L378 264Q368 277 353 283Z"/></svg>`
15
+
16
+ const STYLE = `#tylix-loading-screen{--tls-bg:var(--tx-canvas,243 242 246);--tls-brand:var(--tx-brand,0 52 202);--tls-track:var(--tx-line,222 219 230);--tls-muted:var(--tx-muted,107 104 120);position:fixed;inset:0;z-index:99990;display:flex;align-items:center;justify-content:center;background:rgb(var(--tls-bg));opacity:0;animation:tls-in .25s ease .15s forwards;transition:opacity .3s ease,visibility .3s ease}
17
+ html.dark #tylix-loading-screen{--tls-bg:var(--tx-canvas,23 22 28);--tls-brand:var(--tx-brand,53 99 255);--tls-track:var(--tx-line,52 49 61);--tls-muted:var(--tx-muted,149 146 163)}
18
+ #tylix-loading-screen.tls-done{opacity:0!important;visibility:hidden;animation:none}
19
+ #tylix-loading-screen .tls-inner{display:flex;flex-direction:column;align-items:center;gap:22px}
20
+ #tylix-loading-screen .tls-mark{width:64px;height:auto;overflow:visible}
21
+ #tylix-loading-screen .tls-mark path{fill:rgb(var(--tls-brand));opacity:.18;animation:tls-stroke 1.2s cubic-bezier(.4,0,.2,1) infinite}
22
+ #tylix-loading-screen .tls-s2{animation-delay:.15s!important}
23
+ #tylix-loading-screen .tls-s3{animation-delay:.3s!important}
24
+ #tylix-loading-screen .tls-track{position:relative;width:132px;height:3px;border-radius:3px;overflow:hidden;background:rgb(var(--tls-track))}
25
+ #tylix-loading-screen .tls-bar{position:absolute;inset:0 auto 0 0;width:40%;border-radius:3px;background:linear-gradient(90deg,rgb(var(--tls-brand)),rgb(111 224 234));animation:tls-slide 1.1s cubic-bezier(.65,0,.35,1) infinite}
26
+ #tylix-loading-screen .tls-sr{position:absolute;width:1px;height:1px;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap}
27
+ @keyframes tls-in{to{opacity:1}}
28
+ @keyframes tls-stroke{0%,100%{opacity:.18;transform:translateX(-6px)}35%,60%{opacity:1;transform:none}}
29
+ @keyframes tls-slide{from{transform:translateX(-100%)}to{transform:translateX(250%)}}
30
+ @media (prefers-reduced-motion:reduce){#tylix-loading-screen .tls-mark path{animation:none;opacity:1;transform:none}#tylix-loading-screen .tls-bar{animation:none;width:100%;opacity:.5}}`
31
+
32
+ // `root` is the selector of the element the page renders into; the screen
33
+ // leaves when it has a child element. A list ("#root, #app, app-root")
34
+ // covers any of them.
35
+ export function loadingScreenHtml({ root = '#app', label = 'Loading' } = {}) {
36
+ const selector = JSON.stringify(String(root)).replace(/</g, '\\u003c')
37
+ const text = String(label).replace(/[&<>"]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' })[c])
38
+ return `<div id="tylix-loading-screen" role="status" aria-live="polite"><style data-tylix-loading>${STYLE}</style><div class="tls-inner">${MARK}<div class="tls-track"><div class="tls-bar"></div></div><span class="tls-sr">${text}…</span></div></div>
39
+ <script>(function(){var s=document.getElementById("tylix-loading-screen");if(!s)return;var done=false,sel=${selector};function hide(){if(done)return;done=true;s.classList.add("tls-done");setTimeout(function(){s.remove()},350)}window.__tylixHideLoadingScreen=hide;function ready(){var r=document.querySelector(sel);return !!(r&&r.firstElementChild)}var mo=new MutationObserver(function(){if(ready()){mo.disconnect();hide()}});function watch(){if(ready())return hide();mo.observe(document.body,{childList:true,subtree:true})}if(document.readyState==="loading")document.addEventListener("DOMContentLoaded",watch);else watch();addEventListener("error",function(e){if(e&&e.error)hide()});setTimeout(hide,15000)})();</script>`
40
+ }
41
+
42
+ // The same mark as a small inline loader for inside a page (route guards,
43
+ // lazy sections): <div class="tx-loader">...</div>, styled by tylix-ui.css.
44
+ export const LOADER_MARK_SVG = MARK.replace('class="tls-mark"', 'class="tx-loader-mark"').replace(/tls-s/g, 'tx-loader-s')
@@ -16,6 +16,7 @@ import {
16
16
  declaredNames,
17
17
  } from './codegen/generateStatement.js'
18
18
  import { substituteCapabilityRefs } from './ast/substituteCapabilityRefs.js'
19
+ import { loadingScreenHtml } from './loadingScreen.js'
19
20
 
20
21
  const __dirname = path.dirname(fileURLToPath(import.meta.url))
21
22
  const RUNTIME_SOURCE = fs
@@ -38,6 +39,10 @@ const USE_CHANNEL_SOURCE = fs
38
39
  .readFileSync(path.join(__dirname, 'runtime', 'useChannel.js'), 'utf-8')
39
40
  .replace(/export\s+/g, '')
40
41
 
42
+ const PERMISSIONS_SOURCE = fs
43
+ .readFileSync(path.join(__dirname, 'runtime', 'permissions.js'), 'utf-8')
44
+ .replace(/export\s+/g, '')
45
+
41
46
  const NOT_FOUND_SOURCE = fs
42
47
  .readFileSync(path.join(__dirname, 'runtime', 'notFound.js'), 'utf-8')
43
48
  .replace(/export\s+/g, '')
@@ -59,6 +64,13 @@ function __tylixExpose(instance, cls, meta) {
59
64
  if (helpers) {
60
65
  for (var key of Object.keys(helpers)) instance[key] = helpers[key];
61
66
  }
67
+ // can(), cannot(), canAny(), hasRole() for templates (runtime/permissions.js),
68
+ // unless the class defines a member with that name itself.
69
+ if (typeof __tylixPermissionHelpers !== "undefined") {
70
+ for (var name of Object.keys(__tylixPermissionHelpers)) {
71
+ if (!(name in instance)) instance[name] = __tylixPermissionHelpers[name];
72
+ }
73
+ }
62
74
  var hook = __tylixHook();
63
75
  if (hook && hook.register) {
64
76
  try { hook.register(instance, meta || { kind: "component", name: cls && cls.name }, __tylixRuntime); } catch (e) {}
@@ -282,7 +294,7 @@ function compileComponentSource(source, fallbackClassName, language) {
282
294
  const isNativeComponent = /^\s*component\s+\w+/.test(source)
283
295
 
284
296
  if (isNativeComponent) {
285
- const { script, template } = parseComponentFile(source)
297
+ const { script, template, style } = parseComponentFile(source)
286
298
  const pageNode = substituteCapabilityRefs(
287
299
  script.trim().length > 0
288
300
  ? new Parser(new Lexer(script).tokenize(), language).parse()
@@ -297,7 +309,7 @@ function compileComponentSource(source, fallbackClassName, language) {
297
309
  const templateNodes = parseTemplate(template, language)
298
310
  const { code, rootVar } = generateTemplate(templateNodes)
299
311
 
300
- return { classSource, code, rootVar, className: fallbackClassName }
312
+ return { classSource, code, rootVar, className: fallbackClassName, style: style ?? '' }
301
313
  }
302
314
 
303
315
  const { script, template } = parseComponent(source)
@@ -374,6 +386,15 @@ export async function renderPageDocument(
374
386
  // false turns off the built-in top loading bar. A project loading page
375
387
  // (app/loading.tyx) also replaces it.
376
388
  loadingBar = true,
389
+ // true when the app has roles and permissions (app/permissions), so a
390
+ // page's `permissions` block is enforced. Otherwise it is a no-op.
391
+ permissionsEnforced = false,
392
+ // Extra tags for <head> from the server (the PWA manifest and worker
393
+ // registration), before the project's own head.html.
394
+ extraHead = '',
395
+ // The full-page loading screen shown until the page first renders
396
+ // (see loadingScreen.js). false turns it off.
397
+ loadingScreen = true,
377
398
  } = {},
378
399
  ) {
379
400
  // createApp already has a variable called `language` that holds
@@ -430,6 +451,7 @@ export async function renderPageDocument(
430
451
  const loadingSource = await loadLoadingPage(loadingFile)
431
452
  let loadingClassSource = ''
432
453
  let loadingMountCode = ''
454
+ let loadingCompiledStyle = ''
433
455
  if (loadingSource !== null) {
434
456
  let loadingCompiled
435
457
  try {
@@ -443,6 +465,7 @@ export async function renderPageDocument(
443
465
  throw err
444
466
  }
445
467
  loadingClassSource = loadingCompiled.classSource
468
+ loadingCompiledStyle = loadingCompiled.style ?? ''
446
469
  loadingMountCode = `
447
470
  try {
448
471
  const loadingInstance = __tylixExpose(new ${loadingCompiled.className}({ loading: __tylixLoading }), ${loadingCompiled.className}, { kind: "loading", name: "Loading" });
@@ -507,6 +530,7 @@ ${childCode}
507
530
  .join('\n\n')
508
531
 
509
532
  let layoutClassSource = ''
533
+ let layoutCompiledStyle = ''
510
534
  let layoutMountCode = `document.getElementById("app").appendChild(${rootVar});`
511
535
 
512
536
  if (layout !== null) {
@@ -518,6 +542,7 @@ ${childCode}
518
542
  throw err
519
543
  }
520
544
  layoutClassSource = layoutCompiled.classSource
545
+ layoutCompiledStyle = layoutCompiled.style ?? ''
521
546
  layoutMountCode = `
522
547
  const layoutInstance = __tylixExpose(new ${layoutCompiled.className}(), ${layoutCompiled.className}, { kind: "layout", name: "Layout" });
523
548
  if (typeof layoutInstance.__ready === "function") {
@@ -551,6 +576,13 @@ ${layoutCompiled.code}
551
576
  ? `<script>window.__TYLIX_CHANNELS_PORT__ = ${JSON.stringify(channelsPort)};</script>`
552
577
  : ''
553
578
 
579
+ // The page's `permissions` block, checked once the page's needs are
580
+ // ready and before anything renders.
581
+ const requiredPermissions = (pageNode.permissions ?? []).map((p) => p.name)
582
+ const pagePermissionsCheck = requiredPermissions.length
583
+ ? ` if (!(await __tylixPagePermitted(${JSON.stringify(requiredPermissions)}, ${permissionsEnforced === true}))) return;`
584
+ : ''
585
+
554
586
  // If __ready() rejects (a failed needs/prefetch call), log it and keep
555
587
  // going so the page still renders, instead of showing a blank screen.
556
588
  const inlineScript = `
@@ -570,6 +602,8 @@ ${USE_API_SOURCE}
570
602
 
571
603
  ${NOT_FOUND_SOURCE}
572
604
 
605
+ ${PERMISSIONS_SOURCE}
606
+
573
607
  ${USE_CHANNEL_SOURCE}
574
608
 
575
609
  ${apiHelpers}
@@ -595,6 +629,7 @@ ${loadingMountCode}
595
629
  console.error("ready failed:", err);
596
630
  }
597
631
  }
632
+ ${pagePermissionsCheck}
598
633
  ${code}
599
634
  __tylixAttach(instance, ${rootVar});
600
635
  ${layoutMountCode}
@@ -609,7 +644,12 @@ ${layoutMountCode}
609
644
  });
610
645
  `
611
646
 
612
- const styleTag = style.trim().length > 0 ? `<style>\n${style}\n</style>` : ''
647
+ // The page's own style section, then each native component's (layout,
648
+ // loading page and children), once each.
649
+ const componentStyles = [layoutCompiledStyle, loadingCompiledStyle, ...compiledChildren.map((c) => c.style)]
650
+ .filter((css) => css && css.trim().length > 0)
651
+ const allStyles = [style, ...new Set(componentStyles)].filter((css) => css && css.trim().length > 0).join('\n\n')
652
+ const styleTag = allStyles.length > 0 ? `<style>\n${allStyles}\n</style>` : ''
613
653
 
614
654
  const styleLinks = stylesheets
615
655
  .map((href) => `<link rel="stylesheet" href="${href}">`)
@@ -622,6 +662,7 @@ ${layoutMountCode}
622
662
  { name: 'loading indicator', code: LOADING_INDICATOR_SOURCE },
623
663
  { name: 'useApi', code: USE_API_SOURCE },
624
664
  { name: 'notFound', code: NOT_FOUND_SOURCE },
665
+ { name: 'permissions', code: PERMISSIONS_SOURCE },
625
666
  { name: 'useChannel', code: USE_CHANNEL_SOURCE },
626
667
  { name: 'app/useApi helpers', code: apiHelpers },
627
668
  { name: 'page class', code: classSource },
@@ -674,14 +715,16 @@ ${layoutMountCode}
674
715
 
675
716
  const values = {
676
717
  title: escapeHtml(pageNode.title ?? pageName),
677
- head: [channelsPortScript, themeScript, styleLinks, headTags, styleTag]
718
+ head: [channelsPortScript, themeScript, styleLinks, extraHead, headTags, styleTag]
678
719
  .filter((part) => part && part.length > 0)
679
720
  .join('\n '),
680
- body: `<div id="app"></div>\n <script>${safeScript}</script>`,
721
+ body: `${loadingScreen ? loadingScreenHtml({ root: '#app' }) + '\n ' : ''}<div id="app"></div>\n <script>${safeScript}</script>`,
681
722
  }
682
723
 
683
724
  // One pass with a function replacer, so a "$&" or a placeholder-looking
684
725
  // string inside the generated script is never treated as a pattern or
685
726
  // substituted a second time.
686
- return shell.replace(/%tylix\.(title|head|body)%/g, (_, key) => values[key])
727
+ // HTML comments are left alone, so a note like "scripts go before
728
+ // %tylix.head%" in app/index.html doesn't get a second copy of the head.
729
+ return shell.replace(/<!--[\s\S]*?-->|%tylix\.(title|head|body)%/g, (match, key) => (key ? values[key] : match))
687
730
  }
@@ -0,0 +1,129 @@
1
+ // Roles and permissions in .tyx pages. The signed-in user (Auth.user)
2
+ // carries an access snapshot when the app uses @tylix/permissions:
3
+ // { roles, permissions, denied, superAdmin }. Templates check it with
4
+ //
5
+ // {{#if can("posts.create")}} ... {{/if}}
6
+ // {{#if hasRole("admin")}} ... {{/if}}
7
+ // {{#if canAny(["posts.edit", "posts.publish"])}} ... {{/if}}
8
+ //
9
+ // and a page that lists `permissions` only renders for users who have all
10
+ // of them. These checks hide UI; the API routes stay guarded on the server.
11
+ //
12
+ // The matching below mirrors @tylix/permissions (src/match.js), so the
13
+ // browser and the server agree; its tests compare the two.
14
+
15
+ function __tylixPermissionMatches(grant, requested) {
16
+ if (typeof grant !== 'string' || typeof requested !== 'string') return false
17
+ if (grant === requested || grant === '*') return true
18
+ const g = grant.split('.')
19
+ const r = requested.split('.')
20
+ for (let i = 0; i < g.length; i++) {
21
+ const seg = g[i]
22
+ const last = i === g.length - 1
23
+ if (seg === '*') {
24
+ if (i >= r.length) return false
25
+ if (last) return true
26
+ if (r[i] === '') return false
27
+ continue
28
+ }
29
+ if (i >= r.length) return false
30
+ if (seg.includes(',')) {
31
+ if (!seg.split(',').map((x) => x.trim()).includes(r[i])) return false
32
+ } else if (seg !== r[i]) {
33
+ return false
34
+ }
35
+ }
36
+ return g.length === r.length
37
+ }
38
+
39
+ function __tylixAccess() {
40
+ if (typeof registry === 'undefined' || !registry.has('Auth')) return null
41
+ const user = resolveCapability('Auth').user
42
+ return user && typeof user === 'object' && user.access ? user.access : null
43
+ }
44
+
45
+ function __tylixAllows(access, permission) {
46
+ if (!access) return false
47
+ if (access.superAdmin) return true
48
+ for (const d of access.denied || []) if (__tylixPermissionMatches(d, permission)) return false
49
+ for (const p of access.permissions || []) if (__tylixPermissionMatches(p, permission)) return true
50
+ return false
51
+ }
52
+
53
+ const __tylixList = (value) => (Array.isArray(value) ? value : [value])
54
+
55
+ // Put on every page, layout and component instance that doesn't define a
56
+ // member of the same name (see __tylixExpose).
57
+ const __tylixPermissionHelpers = {
58
+ can(permission) {
59
+ const access = __tylixAccess()
60
+ const wanted = __tylixList(permission)
61
+ return wanted.length > 0 && wanted.every((p) => __tylixAllows(access, p))
62
+ },
63
+ cannot(permission) {
64
+ return !__tylixPermissionHelpers.can(permission)
65
+ },
66
+ canAny(permissions) {
67
+ const access = __tylixAccess()
68
+ return __tylixList(permissions).some((p) => __tylixAllows(access, p))
69
+ },
70
+ hasRole(role) {
71
+ const access = __tylixAccess()
72
+ return Boolean(access) && __tylixList(role).some((r) => (access.roles || []).includes(r))
73
+ },
74
+ }
75
+
76
+ // The page's `permissions` block. Resolves true when the page may render.
77
+ // Guests go to login (and come back); a signed-in user without them sees
78
+ // a 403 panel. `enforced` is false when the app has no roles yet
79
+ // (no app/permissions file), so the block is a no-op there.
80
+ async function __tylixPagePermitted(required, enforced) {
81
+ if (!required.length) return true
82
+ if (!enforced) {
83
+ console.info(
84
+ '[tylix] This page lists permissions (' + required.join(', ') + ') but the app has no roles yet. Run `tylix make:permissions` to enforce them.',
85
+ )
86
+ return true
87
+ }
88
+ if (typeof registry === 'undefined' || !registry.has('Auth')) {
89
+ console.warn('[tylix] This page lists permissions, but there is no Auth capability to read the user from.')
90
+ return false
91
+ }
92
+ const auth = resolveCapability('Auth')
93
+ try {
94
+ await auth.ready()
95
+ } catch (err) {
96
+ console.error('[tylix] Auth failed to load:', err)
97
+ }
98
+ if (!auth.user) {
99
+ const here = window.location.pathname + window.location.search
100
+ window.location.replace('/login?next=' + encodeURIComponent(here))
101
+ return false
102
+ }
103
+ if (required.every((p) => __tylixAllows(auth.user.access, p))) return true
104
+ __tylixShowForbidden(required)
105
+ return false
106
+ }
107
+
108
+ function __tylixShowForbidden(required) {
109
+ const app = document.getElementById('app')
110
+ if (!app) return
111
+ const panel = document.createElement('div')
112
+ panel.setAttribute('role', 'alert')
113
+ panel.style.cssText =
114
+ 'min-height:70vh;display:flex;align-items:center;justify-content:center;padding:24px;font-family:var(--tx-font,system-ui,sans-serif);'
115
+ panel.innerHTML =
116
+ '<div style="max-width:420px;text-align:center;padding:40px 32px;border-radius:var(--tx-radius,14px);' +
117
+ 'background:rgb(var(--tx-panel,255 255 255));border:1px solid rgb(var(--tx-line,222 219 230));box-shadow:var(--tx-shadow,none);">' +
118
+ '<div style="width:44px;height:44px;margin:0 auto 18px;border-radius:12px;display:flex;align-items:center;justify-content:center;' +
119
+ 'background:rgb(var(--tx-coral,205 60 60) / 0.12);color:rgb(var(--tx-coral,205 60 60));font-weight:700;font-size:18px;">403</div>' +
120
+ '<h1 style="margin:0 0 8px;font-size:20px;font-weight:600;color:rgb(var(--tx-ink,23 21 28));">You don’t have access to this page</h1>' +
121
+ '<p style="margin:0 0 22px;font-size:14px;line-height:1.6;color:rgb(var(--tx-muted,107 104 120));">Ask an administrator for the permission it needs.</p>' +
122
+ '<a href="/" style="display:inline-block;padding:9px 18px;border-radius:var(--tx-radius-sm,9px);text-decoration:none;font-size:14px;font-weight:600;' +
123
+ 'background:rgb(var(--tx-brand,0 52 202));color:rgb(var(--tx-on-brand,255 255 255));">Go home</a></div>'
124
+ const code = document.createElement('p')
125
+ code.style.cssText = 'margin:14px 0 0;font:12px var(--tx-mono,ui-monospace,monospace);color:rgb(var(--tx-muted,107 104 120));'
126
+ code.textContent = 'Needs: ' + required.join(', ')
127
+ panel.firstChild.appendChild(code)
128
+ app.replaceChildren(panel)
129
+ }
@@ -94,4 +94,26 @@ declare function useChannel(name: string): TylixChannel
94
94
  declare function notFound(): void
95
95
 
96
96
  // Capability names used in page scripts compile to this call.
97
- declare function resolveCapability(name: string): any
97
+ declare function resolveCapability(name: string): any
98
+ // The PWA runtime (pwa in tylix.config). Undefined on apps without it.
99
+ interface TylixPwaState {
100
+ supported: boolean
101
+ registered: boolean
102
+ offlineReady: boolean
103
+ updateAvailable: boolean
104
+ installable: boolean
105
+ installed: boolean
106
+ online: boolean
107
+ error: string | null
108
+ }
109
+ interface TylixPwa {
110
+ readonly state: TylixPwaState
111
+ subscribe(fn: (state: TylixPwaState) => void): () => void
112
+ install(): Promise<'accepted' | 'dismissed' | 'unavailable'>
113
+ update(): boolean
114
+ dismissUpdate(): void
115
+ dismissOfflineReady(): void
116
+ }
117
+ interface Window {
118
+ __TYLIX_PWA__?: TylixPwa
119
+ }