orvyn-lang 0.2.0 → 0.3.0

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 (55) hide show
  1. package/GUIDE.md +149 -0
  2. package/LANGUAGE.md +744 -27
  3. package/README.md +211 -250
  4. package/brand/orvyn-sunset-animated.svg +15 -0
  5. package/package.json +3 -1
  6. package/src/cli/orvyn.js +186 -10
  7. package/src/core/signal.js +104 -6
  8. package/src/devtools/runtime.js +25 -1
  9. package/src/lang/a11y.js +102 -0
  10. package/src/lang/auth.js +239 -0
  11. package/src/lang/bundle-native.js +10 -6
  12. package/src/lang/codegen.js +428 -57
  13. package/src/lang/device.js +41 -0
  14. package/src/lang/doctor.js +60 -0
  15. package/src/lang/env.js +27 -0
  16. package/src/lang/errors.js +513 -0
  17. package/src/lang/form.js +69 -8
  18. package/src/lang/index.js +2 -1
  19. package/src/lang/lexer.js +2 -0
  20. package/src/lang/list.js +44 -0
  21. package/src/lang/native/android/MainActivity.kt +43 -4
  22. package/src/lang/native/android/OrvynDevice.kt +163 -0
  23. package/src/lang/native/android/OrvynEngine.kt +154 -7
  24. package/src/lang/native/android/OrvynRenderer.kt +518 -44
  25. package/src/lang/native/android.js +74 -11
  26. package/src/lang/native/build.js +130 -60
  27. package/src/lang/native/config.js +108 -0
  28. package/src/lang/native/ios/OrvynApp.swift +6 -0
  29. package/src/lang/native/ios/OrvynEngine.swift +266 -4
  30. package/src/lang/native/ios/OrvynViews.swift +429 -34
  31. package/src/lang/native/ios.js +75 -2
  32. package/src/lang/native-runtime.js +406 -56
  33. package/src/lang/page.js +52 -0
  34. package/src/lang/parser.js +243 -15
  35. package/src/lang/prerender.js +300 -0
  36. package/src/lang/read-import.js +11 -0
  37. package/src/lang/router.js +266 -0
  38. package/src/lang/runtime-shared.js +792 -10
  39. package/src/lang/runtime.js +362 -52
  40. package/src/lang/select.js +13 -0
  41. package/src/lang/server-code.js +233 -0
  42. package/src/lang/server-export.js +78 -0
  43. package/src/lang/server-libs.js +53 -0
  44. package/src/lang/server.js +409 -0
  45. package/src/lang/test-runner.js +134 -0
  46. package/src/lang/types.js +312 -0
  47. package/src/lang/vite-plugin.js +82 -3
  48. package/src/lang/web-overlay.js +578 -0
  49. package/src/lang/widgets.js +94 -0
  50. package/src/lang/words.js +38 -0
  51. package/src/runtime/mount.js +116 -27
  52. package/src/runtime/patch.js +90 -11
  53. package/src/runtime/style.js +11 -1
  54. package/src/styling/fluid.js +91 -4
  55. package/src/styling/spec.js +306 -0
package/src/cli/orvyn.js CHANGED
@@ -18,6 +18,23 @@ let command =
18
18
  let args =
19
19
  process.argv.slice(3)
20
20
 
21
+ // --env staging (or --env=staging) works with every command
22
+ const envAt = args.findIndex(arg => arg === "--env" || arg.startsWith("--env="))
23
+ if (envAt >= 0) {
24
+ const inline = args[envAt].includes("=")
25
+ const name = inline ? args[envAt].slice("--env=".length) : args[envAt + 1]
26
+ if (!name || name.startsWith("-")) {
27
+ process.stdout.write("--env needs a name, like --env prod\n")
28
+ process.exit(1)
29
+ }
30
+ process.env.ORVYN_ENV = name
31
+ args.splice(envAt, inline ? 1 : 2)
32
+ }
33
+
34
+ const releaseAt = args.indexOf("--release")
35
+ const release = releaseAt >= 0
36
+ if (release) args.splice(releaseAt, 1)
37
+
21
38
  // ---------------------------------------------------------------------------
22
39
  // Orvyn language projects get short commands:
23
40
  // orvyn dev | ios | android | check | build | preview
@@ -46,7 +63,8 @@ if (orvEntry && !hasOrvArg) {
46
63
  command = "dev"
47
64
  args = ["ios", orvEntry, ...args]
48
65
  } else if (command === "android") {
49
- command = "run"
66
+ // live reload, like the iPhone
67
+ command = "dev"
50
68
  args = ["android", orvEntry, ...args]
51
69
  } else if (
52
70
  (command === "dev" || command === "run" || command === "build") &&
@@ -153,11 +171,25 @@ async function compileOrv(mode, commandArgs) {
153
171
 
154
172
  const source = readFileSync(file, "utf-8")
155
173
 
174
+ let env
156
175
  try {
157
- const code = compile(source)
176
+ const { loadEnv } = await import("../lang/env.js")
177
+ env = await loadEnv(cwd, "dev")
178
+ } catch (error) {
179
+ log(error.message)
180
+ process.exit(1)
181
+ }
182
+
183
+ try {
184
+ const { readImportFrom } = await import("../lang/read-import.js")
185
+ const code = compile(source, { env, tests: mode === "check", resolveImport: readImportFrom(file) })
158
186
 
159
187
  if (mode === "check") {
160
- log(`✓ ${file} has no errors`)
188
+ const { parse } = await import("../lang/parser.js")
189
+ const { checkAccessibility } = await import("../lang/a11y.js")
190
+ const warnings = checkAccessibility(parse(source))
191
+ for (const warning of warnings) log(`⚠ ${file}:${warning.line}:${warning.col} ${warning.message}`)
192
+ log(`✓ ${file} has no errors${warnings.length ? `, ${warnings.length} warning(s)` : ""}`)
161
193
  } else if (outFile) {
162
194
  writeFileSync(outFile, code)
163
195
  log(`✓ Compiled ${file} → ${outFile}`)
@@ -178,6 +210,85 @@ async function compileOrv(mode, commandArgs) {
178
210
  }
179
211
  }
180
212
 
213
+ async function testOrv(commandArgs) {
214
+ const files = commandArgs.filter(arg => arg.endsWith(".orv"))
215
+ if (!files.length && orvEntry) files.push(orvEntry)
216
+ if (!files.length) {
217
+ log("Usage: orvyn test <file.orv>")
218
+ process.exit(1)
219
+ }
220
+ const { runTests } = await import("../lang/test-runner.js")
221
+ const { loadEnv } = await import("../lang/env.js")
222
+ let failed = 0
223
+ let total = 0
224
+ for (const file of files) {
225
+ try {
226
+ for (const result of await runTests(file, await loadEnv(cwd, "dev"))) {
227
+ total++
228
+ log(`${result.ok ? "✓" : "✗"} ${file}: ${result.name}`)
229
+ if (!result.ok) {
230
+ failed++
231
+ log(` ${result.error}`)
232
+ }
233
+ }
234
+ } catch (error) {
235
+ failed++
236
+ log(`✗ ${file}: ${error.message}`)
237
+ }
238
+ }
239
+ log(total || failed ? `\n${total} test(s), ${failed} failed` : `No tests yet. Add: test "opens" { expect(text("Hello")) }`)
240
+ process.exit(failed ? 1 : 0)
241
+ }
242
+
243
+ // orvyn serve [server.orv] [--port 3000] [--host 0.0.0.0]
244
+ // orvyn admin you@example.com [server.orv]
245
+ async function serverOrv(mode, commandArgs) {
246
+ const option = (name, fallback) => {
247
+ const at = commandArgs.indexOf(name)
248
+ return at >= 0 ? commandArgs.splice(at, 2)[1] : fallback
249
+ }
250
+ const port = Number(option("--port", process.env.PORT || 3000))
251
+ const host = option("--host", process.env.HOST || "127.0.0.1")
252
+ const file = commandArgs.find(arg => arg.endsWith(".orv")) ||
253
+ ["src/server.orv", "server.orv"].find(path => existsSync(join(cwd, path)))
254
+ if (!file || !existsSync(file)) {
255
+ log("No server file. Create server.orv, like:\n\n table notes {\n text: text required\n }")
256
+ process.exit(1)
257
+ }
258
+ try {
259
+ const { parseServer, openDatabase, createApi, makeAdmin } = await import("../lang/server.js")
260
+ const tables = parseServer(readFileSync(file, "utf-8"))
261
+ const { loadLibraries } = await import("../lang/server-libs.js")
262
+ tables.libraries = await loadLibraries(tables.uses ?? [], file)
263
+ const db = openDatabase(process.env.ORVYN_DB || join(cwd, "orvyn.db"), tables)
264
+ if (mode === "admin") {
265
+ const email = commandArgs.find(arg => arg.includes("@"))
266
+ if (!email || !makeAdmin(db, email)) {
267
+ log("Usage: orvyn admin you@example.com (sign up with that email first)")
268
+ process.exit(1)
269
+ }
270
+ log(`✓ ${email} is now an admin`)
271
+ process.exit(0)
272
+ }
273
+ const origins = (process.env.ORVYN_ORIGINS || "").split(",").map(s => s.trim()).filter(Boolean)
274
+ const server = createApi(tables, db, { origins })
275
+ server.on("error", error => {
276
+ log(`✗ ${error.message}`)
277
+ process.exit(1)
278
+ })
279
+ server.listen(port, host, () => {
280
+ log(`[Orvyn] ✓ Server → http://${host === "0.0.0.0" ? "localhost" : host}:${port}/api`)
281
+ for (const table of tables) {
282
+ log(` /api/${table.name.padEnd(16)} ${table.locked ? "only your server code changes" : table.admin ? "only admins change" : "owners change"}, ${table.public ? "anyone reads" : table.admin ? "admins see their own" : "private to each person"}`)
283
+ }
284
+ for (const api of tables.apis ?? []) log(` ${api.method.padEnd(4)} /api${api.path}${api.requires ? ` (requires ${api.requires})` : ""}`)
285
+ })
286
+ } catch (error) {
287
+ log(`✗ ${file}: ${error.message}`)
288
+ process.exit(1)
289
+ }
290
+ }
291
+
181
292
  function newOrvProject(name) {
182
293
  if (!name) {
183
294
  log("Usage: orvyn new <app-name>")
@@ -214,6 +325,7 @@ function newOrvProject(name) {
214
325
  ios: "orvyn ios",
215
326
  android: "orvyn android",
216
327
  check: "orvyn check",
328
+ test: "orvyn test",
217
329
  build: "orvyn build"
218
330
  },
219
331
  dependencies: { [orvynName]: orvynDep },
@@ -226,7 +338,19 @@ function newOrvProject(name) {
226
338
  appId: ${JSON.stringify(`com.example.${id || "app"}`)},
227
339
  version: "1.0.0",
228
340
  ios: { deploymentTarget: "16.0" },
229
- android: { minSdk: 24, targetSdk: 34 }
341
+ // For the stores, add your own appId and:
342
+ // icon: "assets/icon.png", // 1024 x 1024 PNG, no transparency
343
+ // splash: { color: "#ffffff" },
344
+ // permissions: { camera: "To scan codes" },
345
+ android: { minSdk: 24, targetSdk: 36 } // , keystore: "upload.jks", keyAlias: "upload"
346
+ },
347
+ // your website address, for sitemap.xml: site: "https://example.com",
348
+ // seo: { allowAI: false }, // ask AI crawlers not to read your site
349
+ // read in .orv code as env.API_URL. These values ship inside the app: no secrets.
350
+ env: {
351
+ dev: { API_URL: "http://localhost:3000" },
352
+ staging: { API_URL: "https://staging.example.com" },
353
+ prod: { API_URL: "https://api.example.com" }
230
354
  }
231
355
  }
232
356
  `,
@@ -262,15 +386,23 @@ export default defineConfig({
262
386
  state count = 0
263
387
 
264
388
  screen Home {
389
+ page title: "${pretty}", description: "${pretty}, built with Orvyn"
390
+
265
391
  Column gap: 16, padding: 24 {
266
392
  Heading "${pretty}", size: 32
267
393
  Text "You tapped {count} times"
268
394
  Button "Tap me", bg: black, color: white, padding: 12, radius: 10, onTap: count += 1
269
395
  }
270
396
  }
397
+
398
+ // run with: orvyn test
399
+ test "counts taps" {
400
+ tap("Tap me")
401
+ expect(text("You tapped 1 times"))
402
+ }
271
403
  `,
272
404
 
273
- ".gitignore": "node_modules\ndist\n",
405
+ ".gitignore": "node_modules\ndist\norvyn.db*\n*.jks\n*.keystore\n",
274
406
 
275
407
  "README.md": `# ${pretty}
276
408
 
@@ -279,7 +411,8 @@ Built with the Orvyn language (v${orvynVersion}).
279
411
  \`\`\`bash
280
412
  orvyn dev # web → http://localhost:5173 (live reload)
281
413
  orvyn ios # iPhone simulator (live reload, needs Xcode)
282
- orvyn android # Android emulator or phone
414
+ orvyn android # Android emulator or phone, with live reload
415
+ orvyn doctor # what is missing to build and publish
283
416
  orvyn check # find mistakes in src/app.orv
284
417
  orvyn build ios # Xcode project for real iPhones / App Store
285
418
  \`\`\`
@@ -337,7 +470,8 @@ async function nativeOrv(mode, commandArgs) {
337
470
 
338
471
  try {
339
472
  const fn = mode === "run" ? runNativeApp : mode === "dev" ? devNativeApp : buildNativeApp
340
- await fn(target, entry, { cwd, log })
473
+ if (release && mode !== "build") throw new Error("--release only works with: orvyn build ios|android")
474
+ await fn(target, entry, { cwd, log, release })
341
475
  } catch (error) {
342
476
  if (error instanceof OrvynSyntaxError || error?.cause instanceof OrvynSyntaxError) {
343
477
  log(`✗ ${entry}: ${error.message}`)
@@ -358,12 +492,20 @@ function help() {
358
492
  log("Inside your app folder:")
359
493
  log(" orvyn dev Web, with live reload")
360
494
  log(" orvyn ios iPhone simulator, with live reload")
361
- log(" orvyn android Android emulator or phone")
495
+ log(" orvyn android Android emulator or phone, with live reload")
496
+ log(" orvyn doctor Check what is missing to build and publish")
497
+ log(" orvyn build ios --release Signed .ipa for the App Store")
498
+ log(" orvyn build android --release Signed .aab for Google Play")
362
499
  log(" orvyn check Find mistakes in your code")
500
+ log(" orvyn test Run the test blocks in your app")
501
+ log(" orvyn serve Backend with database and login (server.orv)")
502
+ log(" orvyn admin EMAIL Let an account change admin tables")
503
+ log(" orvyn build server Folder to upload to your host → dist/server/")
363
504
  log(" orvyn build Website → dist/web/")
364
505
  log(" orvyn build ios Xcode project → dist/ios/ (for real iPhones / App Store)")
365
506
  log(" orvyn build android Android Studio project → dist/android/")
366
507
  log(" orvyn preview Preview the built website")
508
+ log(" --env staging Use another environment (dev and run: dev, build: prod)")
367
509
  log("")
368
510
  log("Any .orv file:")
369
511
  log(" orvyn compile app.orv Compile .orv to JavaScript (prints it)")
@@ -372,15 +514,49 @@ function help() {
372
514
  log(" orvyn build ios app.orv Build a native iPhone app (SwiftUI)")
373
515
  log(" orvyn build android app.orv Build a native Android app")
374
516
  log(" orvyn dev ios app.orv iPhone simulator with live reload")
517
+ log(" orvyn dev android app.orv Android with live reload")
375
518
  log(" orvyn run ios app.orv Build and open it in the iPhone simulator")
376
519
  log(" orvyn run android app.orv Build and install on an emulator/phone")
377
520
  }
378
521
 
379
- if (command === "web-dev") {
522
+ if (command === "build" && args[0] === "server") {
523
+ const file = args.find(arg => arg.endsWith(".orv")) ||
524
+ ["src/server.orv", "server.orv"].find(path => existsSync(join(cwd, path)))
525
+ try {
526
+ if (!file) throw new Error("No server.orv here")
527
+ const { exportServer } = await import("../lang/server-export.js")
528
+ const files = exportServer(file, join(cwd, "dist/server"))
529
+ log(`[Orvyn] ✓ Server ready to upload → dist/server/ (${files.join(", ")})`)
530
+ } catch (error) {
531
+ log(`✗ ${error.message}`)
532
+ process.exit(1)
533
+ }
534
+ } else if (release && !(command === "build" && args.some(arg => arg.endsWith(".orv")))) {
535
+ log("--release only works with: orvyn build ios|android")
536
+ process.exit(1)
537
+ } else if (command === "serve" || command === "admin") {
538
+ await serverOrv(command, args)
539
+ } else if (command === "test") {
540
+ await testOrv(args)
541
+ } else if (command === "doctor") {
542
+ const { doctor, formatChecks } = await import("../lang/doctor.js")
543
+ log(formatChecks(await doctor(cwd)))
544
+ } else if (command === "web-dev") {
380
545
  run(viteBinary(), args)
381
546
  } else if (command === "web-build") {
382
547
  // dist/web so it never deletes dist/ios or dist/android
383
- run(viteBinary(), ["build", "--outDir", "dist/web", "--emptyOutDir", ...args])
548
+ runSync(viteBinary(), ["build", "--outDir", "dist/web", "--emptyOutDir", ...args])
549
+ if (orvEntry) {
550
+ try {
551
+ const { prerender } = await import("../lang/prerender.js")
552
+ const { loadEnv } = await import("../lang/env.js")
553
+ const files = await prerender(cwd, orvEntry, join(cwd, "dist/web"), await loadEnv(cwd, "prod"))
554
+ log(`[Orvyn] ✓ Ready-made pages for search engines: ${files.join(", ")}`)
555
+ } catch (error) {
556
+ log(`[Orvyn] ✗ Could not make ready-made pages: ${error.message}`)
557
+ process.exit(1)
558
+ }
559
+ }
384
560
  } else if (command === "web-preview") {
385
561
  run(viteBinary(), ["preview", "--outDir", "dist/web", ...args])
386
562
  } else if ((command === "build" || command === "run" || command === "dev") && args.some(arg => arg.endsWith(".orv"))) {
@@ -7,13 +7,54 @@ import {
7
7
  recordSignalSubscriber,
8
8
  recordSignalUpdate,
9
9
  registerEffect,
10
- registerSignal
10
+ registerSignal,
11
+ unregisterEffect,
12
+ unregisterSignal
11
13
  } from "../devtools/runtime.js";
12
14
  let activeEffect = null;
15
+ let currentOwner = null;
13
16
  let activeEffectId = null;
14
17
  let signalId = 0;
15
18
  const signalRegistry = /* @__PURE__ */ new Map();
16
19
  const resumedValues = /* @__PURE__ */ new Map();
20
+ function createOwner() {
21
+ return {
22
+ cleanups: [],
23
+ disposed: false
24
+ };
25
+ }
26
+ function getOwner() {
27
+ return currentOwner;
28
+ }
29
+ function runWithOwner(owner, fn) {
30
+ const previous = currentOwner;
31
+ currentOwner = owner;
32
+ try {
33
+ return fn();
34
+ } finally {
35
+ currentOwner = previous;
36
+ }
37
+ }
38
+ function onCleanup(fn) {
39
+ if (!currentOwner) return;
40
+ if (currentOwner.disposed) {
41
+ fn();
42
+ return;
43
+ }
44
+ currentOwner.cleanups.push(fn);
45
+ }
46
+ function disposeOwner(owner, final = true) {
47
+ const cleanups = owner.cleanups;
48
+ owner.cleanups = [];
49
+ if (final) owner.disposed = true;
50
+ for (let i = cleanups.length - 1; i >= 0; i--) {
51
+ try {
52
+ cleanups[i]();
53
+ } catch (error) {
54
+ console.error("[Orvyn] cleanup failed", error);
55
+ }
56
+ }
57
+ }
17
58
  function normalizeOptions(options) {
18
59
  if (typeof options === "string") {
19
60
  return {
@@ -30,11 +71,12 @@ function signal(initial, options) {
30
71
  const restore = (newValue) => {
31
72
  value = newValue;
32
73
  };
33
- signalRegistry.set(id, {
74
+ const record = {
34
75
  id,
35
76
  get: () => value,
36
77
  restore
37
- });
78
+ };
79
+ signalRegistry.set(id, record);
38
80
  registerSignal(
39
81
  id,
40
82
  value
@@ -45,6 +87,7 @@ function signal(initial, options) {
45
87
  get() {
46
88
  if (activeEffect) {
47
89
  subscribers.add(activeEffect);
90
+ activeEffect.deps.add(subscribers);
48
91
  recordSignalSubscriber(
49
92
  id,
50
93
  subscribers.size
@@ -64,16 +107,41 @@ function signal(initial, options) {
64
107
  id,
65
108
  value
66
109
  );
67
- subscribers.forEach((fn) => {
110
+ Array.from(subscribers).forEach((fn) => {
68
111
  schedule(fn);
69
112
  });
70
113
  },
114
+ // Calls fn after every change. Inside a component or screen the
115
+ // subscription ends when it is removed; the returned function ends it early.
71
116
  subscribe(fn) {
72
- subscribers.add(fn);
117
+ let active = true;
118
+ const listener = () => {
119
+ if (active) fn();
120
+ };
121
+ subscribers.add(listener);
73
122
  recordSignalSubscriber(
74
123
  id,
75
124
  subscribers.size
76
125
  );
126
+ const unsubscribe = () => {
127
+ active = false;
128
+ subscribers.delete(listener);
129
+ };
130
+ onCleanup(unsubscribe);
131
+ return unsubscribe;
132
+ },
133
+ // Number of effects and subscriptions currently watching this value.
134
+ subscriberCount() {
135
+ return subscribers.size;
136
+ },
137
+ // Forget a signal that is no longer used anywhere (for example the error
138
+ // state of a form that was removed).
139
+ dispose() {
140
+ subscribers.clear();
141
+ if (signalRegistry.get(id) === record) {
142
+ signalRegistry.delete(id);
143
+ unregisterSignal(id);
144
+ }
77
145
  }
78
146
  };
79
147
  }
@@ -112,11 +180,24 @@ function restoreSignalState(state = {}) {
112
180
  }
113
181
  function effect(fn) {
114
182
  const id = registerEffect(fn.name || "effect");
115
- const runner = () => {
183
+ const runOwner = createOwner();
184
+ let stopped = false;
185
+ const leaveDependencies = () => {
186
+ runner.deps.forEach((subscribers) => {
187
+ subscribers.delete(runner);
188
+ });
189
+ runner.deps.clear();
190
+ };
191
+ const runner = (() => {
192
+ if (stopped) return;
193
+ leaveDependencies();
194
+ disposeOwner(runOwner, false);
116
195
  const previousEffect = activeEffect;
117
196
  const previousEffectId = activeEffectId;
197
+ const previousOwner = currentOwner;
118
198
  activeEffect = runner;
119
199
  activeEffectId = id;
200
+ currentOwner = runOwner;
120
201
  if (globalThis.__ORVYN_DEBUG__) {
121
202
  console.log("[Orvyn Effect Triggered]", id);
122
203
  }
@@ -130,12 +211,24 @@ function effect(fn) {
130
211
  );
131
212
  activeEffect = previousEffect;
132
213
  activeEffectId = previousEffectId;
214
+ currentOwner = previousOwner;
133
215
  }
216
+ });
217
+ runner.deps = /* @__PURE__ */ new Set();
218
+ const stop = () => {
219
+ if (stopped) return;
220
+ stopped = true;
221
+ leaveDependencies();
222
+ disposeOwner(runOwner);
223
+ unregisterEffect(id);
134
224
  };
225
+ onCleanup(stop);
135
226
  runner();
227
+ return stop;
136
228
  }
137
229
  function computed(fn) {
138
230
  const result = signal(fn());
231
+ onCleanup(() => result.dispose());
139
232
  effect(() => {
140
233
  result.set(fn());
141
234
  });
@@ -143,8 +236,13 @@ function computed(fn) {
143
236
  }
144
237
  export {
145
238
  computed,
239
+ createOwner,
240
+ disposeOwner,
146
241
  effect,
242
+ getOwner,
243
+ onCleanup,
147
244
  restoreSignalState,
245
+ runWithOwner,
148
246
  serializeReactiveGraph,
149
247
  serializeSignalState,
150
248
  signal
@@ -73,6 +73,24 @@ function registerEffect(label = "effect") {
73
73
  });
74
74
  return id;
75
75
  }
76
+ function unregisterEffect(id) {
77
+ if (!effects.delete(id)) return;
78
+ dependencyGraph.forEach((edge) => {
79
+ if (edge.startsWith(`${id}->`)) dependencyGraph.delete(edge);
80
+ });
81
+ }
82
+ function unregisterSignal(id) {
83
+ signals.delete(id);
84
+ }
85
+ function unregisterComponent(id) {
86
+ const component = components.get(id);
87
+ if (!component) return;
88
+ components.delete(id);
89
+ const parent = component.parentId ? components.get(component.parentId) : void 0;
90
+ if (parent) {
91
+ parent.children = parent.children.filter((child) => child !== id);
92
+ }
93
+ }
76
94
  function beginEffectRun(id) {
77
95
  if (!enabled) return now();
78
96
  const effect = effects.get(id);
@@ -80,6 +98,9 @@ function beginEffectRun(id) {
80
98
  effect.runs++;
81
99
  effect.lastRun = now();
82
100
  effect.dependencies = [];
101
+ dependencyGraph.forEach((edge) => {
102
+ if (edge.startsWith(`${id}->`)) dependencyGraph.delete(edge);
103
+ });
83
104
  }
84
105
  return now();
85
106
  }
@@ -186,5 +207,8 @@ export {
186
207
  recordSignalUpdate,
187
208
  registerComponent,
188
209
  registerEffect,
189
- registerSignal
210
+ registerSignal,
211
+ unregisterComponent,
212
+ unregisterEffect,
213
+ unregisterSignal
190
214
  };
@@ -0,0 +1,102 @@
1
+ import { theme } from "../styling/spec.js";
2
+ const NAMED = {
3
+ black: "#000000",
4
+ white: "#ffffff",
5
+ gray: "#808080",
6
+ grey: "#808080",
7
+ red: "#ff0000",
8
+ green: "#008000",
9
+ blue: "#0000ff",
10
+ yellow: "#ffff00",
11
+ orange: "#ffa500",
12
+ silver: "#c0c0c0"
13
+ };
14
+ function literal(expr) {
15
+ if (!expr) return null;
16
+ if (expr.kind === "Color") return expr.value;
17
+ if (expr.kind === "Ident") return expr.name;
18
+ if (expr.kind === "String" && expr.parts.length === 1 && typeof expr.parts[0] === "string") return expr.parts[0];
19
+ return null;
20
+ }
21
+ function rgb(value) {
22
+ if (!value) return null;
23
+ const colors = theme().colors;
24
+ let hex = (colors[value] ?? NAMED[value] ?? value).replace("#", "");
25
+ if (hex.length === 3) hex = [...hex].map((c) => c + c).join("");
26
+ return /^[0-9a-fA-F]{6}$/.test(hex) ? [0, 2, 4].map((i) => parseInt(hex.slice(i, i + 2), 16)) : null;
27
+ }
28
+ function contrast(a, b) {
29
+ const light = (color) => color.map((v) => v / 255).map((v) => v <= 0.03928 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4).reduce((sum, v, i) => sum + v * [0.2126, 0.7152, 0.0722][i], 0);
30
+ const [high, low] = [light(a), light(b)].sort((x, y) => y - x);
31
+ return (high + 0.05) / (low + 0.05);
32
+ }
33
+ function checkAccessibility(program) {
34
+ const warnings = [];
35
+ const visit = (node, background) => {
36
+ if (node.kind === "ViewIf") {
37
+ node.then.forEach((n) => visit(n, background));
38
+ node.else?.forEach((n) => visit(n, background));
39
+ return;
40
+ }
41
+ if (node.kind === "ViewFor") return node.body.forEach((n) => visit(n, background));
42
+ const prop = (key) => {
43
+ const found = node.props.find((p) => p.key === key);
44
+ return found?.value.kind === "Expr" ? found.value.expr : void 0;
45
+ };
46
+ const has = (key) => node.props.some((p) => p.key === key);
47
+ const warn = (message) => warnings.push({ line: node.line, col: node.col, message });
48
+ const text = literal(node.arg ?? void 0);
49
+ if (node.name === "Image" && !has("label") && !has("alt")) {
50
+ warn(`Image needs a label for screen readers, like label: "Photo of the product" (label: "" if it is decoration)`);
51
+ }
52
+ if ((node.name === "Button" || node.name === "Link") && !has("label")) {
53
+ const quoted = node.arg?.kind === "String" ? node.arg.parts.filter((p) => typeof p === "string").join("") : null;
54
+ const onlySymbols = node.arg?.kind === "String" && node.arg.parts.length === 1 && !/[\p{L}\p{N}]/u.test(quoted);
55
+ if (!node.arg && !node.children.length || onlySymbols) {
56
+ warn(`${node.name} ${quoted ? `"${quoted}"` : ""} needs a label for screen readers, like label: "Remove"`);
57
+ }
58
+ }
59
+ const ownBackground = literal(prop("bg")) ?? background;
60
+ const color = literal(prop("color"));
61
+ const onButton = node.name === "Button" && has("bg");
62
+ if (color && ["Text", "Heading", "Button", "Link", "SubmitButton", "Checkbox", "Switch"].includes(node.name)) {
63
+ const front = rgb(color);
64
+ const back = rgb(ownBackground);
65
+ const size = Number(literal(prop("size")) ?? (prop("size")?.kind === "Number" ? prop("size").value : 0));
66
+ const needed = node.name === "Heading" || size >= 24 || onButton ? 3 : 4.5;
67
+ if (front && back) {
68
+ const ratio = contrast(front, back);
69
+ if (ratio < needed) warn(`"${color}" on "${ownBackground}" is hard to read (contrast ${ratio.toFixed(1)}, needs ${needed})${text ? `: ${text}` : ""}`);
70
+ }
71
+ }
72
+ node.children.forEach((child) => visit(child, ownBackground));
73
+ };
74
+ const screens = program.body.filter((d) => d.kind === "Screen" && d.type === "screen");
75
+ const usesPage = screens.some((s) => s.page);
76
+ const titles = /* @__PURE__ */ new Map();
77
+ for (const screen of screens) {
78
+ if (!usesPage || screen.requiresAuth || ["NotFound", "ErrorPage"].includes(screen.name)) continue;
79
+ const field = (key) => {
80
+ const value = screen.page?.find((p) => p.key === key)?.value;
81
+ return value?.kind === "Expr" ? value.expr : void 0;
82
+ };
83
+ const warn = (message) => warnings.push({ line: screen.line, col: screen.col, message: `SEO: ${message}` });
84
+ for (const key of ["title", "description"]) {
85
+ if (!field(key)) warn(`screen ${screen.name} has no ${key}. Add: page title: "...", description: "..."`);
86
+ }
87
+ const title = literal(field("title"));
88
+ if (title) {
89
+ if (title.length > 60) warn(`the title of ${screen.name} is long (${title.length}); search results cut it near 60`);
90
+ if (titles.has(title)) warn(`${screen.name} and ${titles.get(title)} have the same title`);
91
+ titles.set(title, screen.name);
92
+ }
93
+ }
94
+ for (const decl of program.body) {
95
+ if (decl.kind === "Screen") decl.body.forEach((node) => visit(node, "bg"));
96
+ }
97
+ return warnings;
98
+ }
99
+ export {
100
+ checkAccessibility,
101
+ contrast
102
+ };