@nulib/canopy 0.0.0 → 2.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (141) hide show
  1. package/bin/canopy.js +16 -0
  2. package/lib/AGENTS.md +107 -0
  3. package/lib/base-path.js +67 -0
  4. package/lib/build/appearance.js +76 -0
  5. package/lib/build/assets.js +30 -0
  6. package/lib/build/build.js +350 -0
  7. package/lib/build/dev.js +1355 -0
  8. package/lib/build/devtoast.config.json +6 -0
  9. package/lib/build/devtoast.css +14 -0
  10. package/lib/build/facets.js +19 -0
  11. package/lib/build/fonts.js +105 -0
  12. package/lib/build/iiif.js +2990 -0
  13. package/lib/build/log.js +31 -0
  14. package/lib/build/mdx.js +1967 -0
  15. package/lib/build/package-names.js +111 -0
  16. package/lib/build/pages.js +420 -0
  17. package/lib/build/rehype-task-list-labels.js +54 -0
  18. package/lib/build/runtimes.js +141 -0
  19. package/lib/build/search-index.js +55 -0
  20. package/lib/build/search-text.js +160 -0
  21. package/lib/build/search-workflow.js +72 -0
  22. package/lib/build/search.js +302 -0
  23. package/lib/build/sitemap.js +197 -0
  24. package/lib/build/styles.js +140 -0
  25. package/lib/build/theme-tokens.js +78 -0
  26. package/lib/build/ui-styles.js +25 -0
  27. package/lib/build/upgrade-notices.js +121 -0
  28. package/lib/cli.js +64 -0
  29. package/lib/common.js +580 -0
  30. package/lib/components/bibliography.js +197 -0
  31. package/lib/components/featured.js +237 -0
  32. package/lib/components/hero-slider-runtime.js +215 -0
  33. package/lib/components/image-story-runtime-entry.js +249 -0
  34. package/lib/components/map-runtime.js +114 -0
  35. package/lib/components/metadata-index.js +32 -0
  36. package/lib/components/nav-place.js +227 -0
  37. package/lib/components/navigation.js +381 -0
  38. package/lib/components/referenced.js +217 -0
  39. package/lib/components/slider-runtime-entry.js +106 -0
  40. package/lib/components/timeline-runtime.js +80 -0
  41. package/lib/components/viewer-runtime-entry.js +88 -0
  42. package/lib/config-path.js +78 -0
  43. package/lib/default-locale.js +113 -0
  44. package/lib/discovery/browser-loader.js +107 -0
  45. package/lib/discovery/browser.js +115 -0
  46. package/lib/discovery/config.js +25 -0
  47. package/lib/discovery/envelope.js +124 -0
  48. package/lib/discovery/export.js +226 -0
  49. package/lib/discovery/ingestion.js +62 -0
  50. package/lib/discovery/pagination.js +66 -0
  51. package/lib/discovery/provenance.js +79 -0
  52. package/lib/discovery/search.js +81 -0
  53. package/lib/discovery/tools.js +155 -0
  54. package/lib/discovery/validation.js +121 -0
  55. package/lib/head.js +154 -0
  56. package/lib/iiif/thumbnail.js +402 -0
  57. package/lib/index.js +9 -0
  58. package/lib/locale-runtime.js +69 -0
  59. package/lib/locales.js +203 -0
  60. package/lib/orchestrator.js +231 -0
  61. package/lib/page-context.js +24 -0
  62. package/lib/search/bundle.js +25 -0
  63. package/lib/search/data.js +202 -0
  64. package/lib/search/engine.js +86 -0
  65. package/lib/search/index-cache.js +95 -0
  66. package/lib/search/search-app.jsx +835 -0
  67. package/lib/search/search-engine-runtime.js +44 -0
  68. package/lib/search/search-form-runtime.js +462 -0
  69. package/lib/search/search.js +676 -0
  70. package/package.json +109 -3
  71. package/types/base-path.d.ts +4 -0
  72. package/types/orchestrator.d.ts +17 -0
  73. package/ui/dist/index.mjs +7358 -0
  74. package/ui/dist/index.mjs.map +7 -0
  75. package/ui/dist/server.mjs +12731 -0
  76. package/ui/dist/server.mjs.map +7 -0
  77. package/ui/fonts/OFL.txt +98 -0
  78. package/ui/fonts/google-sans-flex-latin-ext.woff2 +0 -0
  79. package/ui/fonts/google-sans-flex-latin.woff2 +0 -0
  80. package/ui/fonts/source-serif-4-italic-latin-ext.woff2 +0 -0
  81. package/ui/fonts/source-serif-4-italic-latin.woff2 +0 -0
  82. package/ui/fonts/source-serif-4-latin-ext.woff2 +0 -0
  83. package/ui/fonts/source-serif-4-latin.woff2 +0 -0
  84. package/ui/styles/base/_common.scss +97 -0
  85. package/ui/styles/base/_heading.scss +61 -0
  86. package/ui/styles/base/_markdown.scss +188 -0
  87. package/ui/styles/base/_type.scss +51 -0
  88. package/ui/styles/base/_utilities.scss +7 -0
  89. package/ui/styles/base/index.scss +5 -0
  90. package/ui/styles/components/_article-card.scss +108 -0
  91. package/ui/styles/components/_band.scss +104 -0
  92. package/ui/styles/components/_bibliography.scss +88 -0
  93. package/ui/styles/components/_buttons.scss +143 -0
  94. package/ui/styles/components/_card.scss +109 -0
  95. package/ui/styles/components/_diagram.scss +76 -0
  96. package/ui/styles/components/_feature.scss +66 -0
  97. package/ui/styles/components/_footer.scss +136 -0
  98. package/ui/styles/components/_gallery.scss +476 -0
  99. package/ui/styles/components/_image-story.scss +56 -0
  100. package/ui/styles/components/_interstitial-hero.scss +625 -0
  101. package/ui/styles/components/_layout.scss +83 -0
  102. package/ui/styles/components/_map.scss +296 -0
  103. package/ui/styles/components/_metadata-index.scss +68 -0
  104. package/ui/styles/components/_nav-tree.scss +80 -0
  105. package/ui/styles/components/_referenced-items.scss +69 -0
  106. package/ui/styles/components/_sub-navigation.scss +208 -0
  107. package/ui/styles/components/_swoosh.scss +50 -0
  108. package/ui/styles/components/_timeline.scss +350 -0
  109. package/ui/styles/components/_work.scss +71 -0
  110. package/ui/styles/components/header/_header.scss +294 -0
  111. package/ui/styles/components/header/_logo.scss +99 -0
  112. package/ui/styles/components/header/_navbar.scss +143 -0
  113. package/ui/styles/components/header/index.scss +3 -0
  114. package/ui/styles/components/iiif/_image.scss +32 -0
  115. package/ui/styles/components/iiif/_slider.scss +5 -0
  116. package/ui/styles/components/iiif/index.scss +2 -0
  117. package/ui/styles/components/index.scss +25 -0
  118. package/ui/styles/components/modal/_modal.scss +130 -0
  119. package/ui/styles/components/modal/index.scss +1 -0
  120. package/ui/styles/components/search/_filters.scss +259 -0
  121. package/ui/styles/components/search/_form.scss +187 -0
  122. package/ui/styles/components/search/_panel.scss +7 -0
  123. package/ui/styles/components/search/_results.scss +241 -0
  124. package/ui/styles/components/search/_tabs.scss +60 -0
  125. package/ui/styles/components/search/index.scss +4 -0
  126. package/ui/styles/index.css +5007 -0
  127. package/ui/styles/index.scss +11 -0
  128. package/ui/styles/settings/_breakpoints.scss +7 -0
  129. package/ui/styles/settings/_focus.scss +15 -0
  130. package/ui/styles/settings/_tokens.scss +170 -0
  131. package/ui/styles/settings/_type.scss +126 -0
  132. package/ui/styles/version-parity.css +116 -0
  133. package/ui/tailwind-canopy-iiif-plugin.js +39 -0
  134. package/ui/tailwind-canopy-iiif-preset.js +32 -0
  135. package/ui/tailwind-config.d.ts +29 -0
  136. package/ui/tailwind-config.js +159 -0
  137. package/ui/tailwind-default.config.mjs +4 -0
  138. package/ui/theme-color.js +130 -0
  139. package/ui/theme-palette.js +337 -0
  140. package/ui/theme.js +153 -0
  141. package/README.md +0 -3
@@ -0,0 +1,1355 @@
1
+ const fs = require("fs");
2
+ const fsp = fs.promises;
3
+ const path = require("path");
4
+ const { spawn, spawnSync } = require("child_process");
5
+ const http = require("http");
6
+ const {withUiStylesImports} = require("./ui-styles");
7
+ const {PACKAGE_NAME} = require("./package-names");
8
+ let sass = null;
9
+ try {
10
+ sass = require("sass");
11
+ } catch (_) {
12
+ sass = null;
13
+ }
14
+ const {
15
+ CONTENT_DIR,
16
+ OUT_DIR,
17
+ ASSETS_DIR,
18
+ ensureDirSync,
19
+ } = require("../common");
20
+ const {
21
+ injectThemeTokens,
22
+ } = require("./styles");
23
+ const APP_COMPONENTS_DIR = path.join(process.cwd(), "app", "components");
24
+
25
+ // As `styles.js`: the site's own Tailwind CLI, else this package's.
26
+ function resolveTailwindCli() {
27
+ for (const from of [process.cwd(), __dirname]) {
28
+ try {
29
+ const pkgPath = require.resolve("@tailwindcss/cli/package.json", { paths: [from] });
30
+ const cliEntry = path.join(path.dirname(pkgPath), "dist", "index.mjs");
31
+ if (fs.existsSync(cliEntry)) {
32
+ return { cmd: process.execPath || "node", args: [cliEntry] };
33
+ }
34
+ } catch (_) {}
35
+ }
36
+ return null;
37
+ }
38
+ const PORT = Number(process.env.PORT || 5001);
39
+ const BUILD_MODULE_PATH = path.resolve(__dirname, "build.js");
40
+ let onBuildSuccess = () => {};
41
+ let onBuildStart = () => {};
42
+ let onCssChange = () => {};
43
+ let nextBuildSkipIiif = false; // hint set by watchers
44
+ const UI_DIST_DIR = path.resolve(path.join(__dirname, "../../ui/dist"));
45
+ const APP_PACKAGE_ROOT = path.resolve(path.join(__dirname, "..", ".."));
46
+ const APP_LIB_DIR = path.join(APP_PACKAGE_ROOT, "lib");
47
+ const APP_UI_DIR = path.join(APP_PACKAGE_ROOT, "ui");
48
+ const CUSTOM_COMPONENT_EXTENSIONS = new Set(
49
+ [".js", ".jsx", ".ts", ".tsx", ".mjs", ".cjs", ".mts", ".cts"].map((
50
+ ext
51
+ ) => ext.toLowerCase())
52
+ );
53
+ const APP_WATCH_TARGETS = [
54
+ { dir: APP_LIB_DIR, label: `${PACKAGE_NAME}/lib` },
55
+ { dir: APP_UI_DIR, label: `${PACKAGE_NAME}/ui` },
56
+ ];
57
+ const HAS_APP_WORKSPACE = (() => {
58
+ try {
59
+ return fs.existsSync(path.join(APP_PACKAGE_ROOT, "package.json"));
60
+ } catch (_) {
61
+ return false;
62
+ }
63
+ })();
64
+ let pendingModuleReload = false;
65
+ let building = false;
66
+ let buildAgain = false;
67
+
68
+ function prettyPath(p) {
69
+ try {
70
+ let rel = path.relative(process.cwd(), p);
71
+ if (!rel) rel = ".";
72
+ rel = rel.split(path.sep).join("/");
73
+ if (!rel.startsWith("./") && !rel.startsWith("../")) rel = "./" + rel;
74
+ return rel;
75
+ } catch (_) {
76
+ return p;
77
+ }
78
+ }
79
+
80
+ function loadBuildFunction() {
81
+ let mod = null;
82
+ try {
83
+ mod = require(BUILD_MODULE_PATH);
84
+ } catch (error) {
85
+ throw new Error(
86
+ `[watch] Failed to load build module (${BUILD_MODULE_PATH}): ${
87
+ error && error.message ? error.message : error
88
+ }`
89
+ );
90
+ }
91
+ const fn =
92
+ mod && typeof mod.build === "function"
93
+ ? mod.build
94
+ : mod && mod.default && typeof mod.default.build === "function"
95
+ ? mod.default.build
96
+ : null;
97
+ if (typeof fn !== "function") {
98
+ throw new Error("[watch] Invalid build module export: expected build() function");
99
+ }
100
+ return fn;
101
+ }
102
+
103
+ function clearAppModuleCache() {
104
+ try {
105
+ const prefix = APP_PACKAGE_ROOT.endsWith(path.sep)
106
+ ? APP_PACKAGE_ROOT
107
+ : APP_PACKAGE_ROOT + path.sep;
108
+ for (const key of Object.keys(require.cache || {})) {
109
+ if (!key) continue;
110
+ try {
111
+ if (key === APP_PACKAGE_ROOT || key.startsWith(prefix)) {
112
+ delete require.cache[key];
113
+ }
114
+ } catch (_) {}
115
+ }
116
+ } catch (_) {}
117
+ }
118
+
119
+ async function runBuild() {
120
+ if (building) {
121
+ buildAgain = true;
122
+ return;
123
+ }
124
+ building = true;
125
+ const hint = { skipIiif: !!nextBuildSkipIiif };
126
+ nextBuildSkipIiif = false;
127
+ try {
128
+ if (pendingModuleReload) {
129
+ clearAppModuleCache();
130
+ pendingModuleReload = false;
131
+ }
132
+ const buildFn = loadBuildFunction();
133
+ await buildFn(hint);
134
+ try {
135
+ onBuildSuccess();
136
+ } catch (_) {}
137
+ } catch (e) {
138
+ console.error("Build failed:", e && e.message ? e.message : e);
139
+ } finally {
140
+ building = false;
141
+ if (buildAgain) {
142
+ buildAgain = false;
143
+ debounceBuild();
144
+ }
145
+ }
146
+ }
147
+
148
+ function tryRecursiveWatch() {
149
+ try {
150
+ const watcher = fs.watch(
151
+ CONTENT_DIR,
152
+ { recursive: true },
153
+ (eventType, filename) => {
154
+ if (!filename) return;
155
+ try {
156
+ console.log(
157
+ `[watch] ${eventType}: ${prettyPath(
158
+ path.join(CONTENT_DIR, filename)
159
+ )}`
160
+ );
161
+ } catch (_) {}
162
+ // If an MDX file changed, we can skip IIIF for the next build
163
+ try {
164
+ if (/\.mdx$/i.test(filename)) nextBuildSkipIiif = true;
165
+ } catch (_) {}
166
+ try {
167
+ onBuildStart();
168
+ } catch (_) {}
169
+ debounceBuild();
170
+ }
171
+ );
172
+ return watcher;
173
+ } catch (e) {
174
+ return null;
175
+ }
176
+ }
177
+
178
+ let buildTimer = null;
179
+ function debounceBuild() {
180
+ clearTimeout(buildTimer);
181
+ buildTimer = setTimeout(runBuild, 150);
182
+ }
183
+
184
+ function watchPerDir() {
185
+ const watchers = new Map();
186
+
187
+ function watchDir(dir) {
188
+ if (watchers.has(dir)) return;
189
+ try {
190
+ const w = fs.watch(dir, (eventType, filename) => {
191
+ try {
192
+ console.log(
193
+ `[watch] ${eventType}: ${prettyPath(
194
+ path.join(dir, filename || "")
195
+ )}`
196
+ );
197
+ } catch (_) {}
198
+ // If a new directory appears, add a watcher for it on next scan
199
+ scan(dir);
200
+ try {
201
+ if (filename && /\.mdx$/i.test(filename)) nextBuildSkipIiif = true;
202
+ } catch (_) {}
203
+ try {
204
+ onBuildStart();
205
+ } catch (_) {}
206
+ debounceBuild();
207
+ });
208
+ watchers.set(dir, w);
209
+ } catch (_) {
210
+ // ignore
211
+ }
212
+ }
213
+
214
+ function scan(dir) {
215
+ const entries = fs.readdirSync(dir, { withFileTypes: true });
216
+ for (const e of entries) {
217
+ const p = path.join(dir, e.name);
218
+ if (e.isDirectory()) watchDir(p);
219
+ }
220
+ }
221
+
222
+ watchDir(CONTENT_DIR);
223
+ scan(CONTENT_DIR);
224
+
225
+ return () => {
226
+ for (const w of watchers.values()) w.close();
227
+ };
228
+ }
229
+
230
+ // Asset live-reload: copy changed file(s) into site/ without full rebuild
231
+ async function syncAsset(relativePath) {
232
+ try {
233
+ if (!relativePath) return;
234
+ const src = path.join(ASSETS_DIR, relativePath);
235
+ const rel = path.normalize(relativePath);
236
+ const dest = path.join(OUT_DIR, rel);
237
+ const exists = fs.existsSync(src);
238
+ if (exists) {
239
+ const st = fs.statSync(src);
240
+ if (st.isDirectory()) {
241
+ ensureDirSync(dest);
242
+ return;
243
+ }
244
+ ensureDirSync(path.dirname(dest));
245
+ await fsp.copyFile(src, dest);
246
+ console.log(
247
+ `[assets] Copied ${relativePath} -> ${path.relative(
248
+ process.cwd(),
249
+ dest
250
+ )}`
251
+ );
252
+ } else {
253
+ // Removed or renamed away: remove dest
254
+ try {
255
+ await fsp.rm(dest, { force: true, recursive: true });
256
+ } catch (_) {}
257
+ console.log(`[assets] Removed ${relativePath}`);
258
+ }
259
+ } catch (e) {
260
+ console.warn("[assets] sync failed:", e && e.message ? e.message : e);
261
+ }
262
+ }
263
+
264
+ function tryRecursiveWatchAssets() {
265
+ try {
266
+ const watcher = fs.watch(
267
+ ASSETS_DIR,
268
+ { recursive: true },
269
+ (eventType, filename) => {
270
+ if (!filename) return;
271
+ try {
272
+ console.log(
273
+ `[assets] ${eventType}: ${prettyPath(
274
+ path.join(ASSETS_DIR, filename)
275
+ )}`
276
+ );
277
+ } catch (_) {}
278
+ // Copy just the changed asset and trigger reload
279
+ syncAsset(filename).then(() => {
280
+ try {
281
+ onBuildSuccess();
282
+ } catch (_) {}
283
+ });
284
+ }
285
+ );
286
+ return watcher;
287
+ } catch (e) {
288
+ return null;
289
+ }
290
+ }
291
+
292
+ function watchAssetsPerDir() {
293
+ const watchers = new Map();
294
+
295
+ function watchDir(dir) {
296
+ if (watchers.has(dir)) return;
297
+ try {
298
+ const w = fs.watch(dir, (eventType, filename) => {
299
+ const rel = filename
300
+ ? path.relative(ASSETS_DIR, path.join(dir, filename))
301
+ : path.relative(ASSETS_DIR, dir);
302
+ try {
303
+ console.log(
304
+ `[assets] ${eventType}: ${prettyPath(
305
+ path.join(dir, filename || "")
306
+ )}`
307
+ );
308
+ } catch (_) {}
309
+ // If a new directory appears, add a watcher for it on next scan
310
+ scan(dir);
311
+ syncAsset(rel).then(() => {
312
+ try {
313
+ onBuildSuccess();
314
+ } catch (_) {}
315
+ });
316
+ });
317
+ watchers.set(dir, w);
318
+ } catch (_) {
319
+ // ignore
320
+ }
321
+ }
322
+
323
+ function scan(dir) {
324
+ const entries = fs.readdirSync(dir, { withFileTypes: true });
325
+ for (const e of entries) {
326
+ const p = path.join(dir, e.name);
327
+ if (e.isDirectory()) watchDir(p);
328
+ }
329
+ }
330
+
331
+ if (fs.existsSync(ASSETS_DIR)) {
332
+ watchDir(ASSETS_DIR);
333
+ scan(ASSETS_DIR);
334
+ }
335
+
336
+ return () => {
337
+ for (const w of watchers.values()) w.close();
338
+ };
339
+ }
340
+
341
+ function handleCustomComponentChange(fullPath, eventType) {
342
+ if (!fullPath) return;
343
+ const ext = path.extname(fullPath).toLowerCase();
344
+ if (ext && !CUSTOM_COMPONENT_EXTENSIONS.has(ext)) return;
345
+ try {
346
+ console.log(`[components] ${eventType}: ${prettyPath(fullPath)}`);
347
+ } catch (_) {}
348
+ nextBuildSkipIiif = true;
349
+ try {
350
+ onBuildStart();
351
+ } catch (_) {}
352
+ debounceBuild();
353
+ }
354
+
355
+ function tryRecursiveWatchAppComponents(dir) {
356
+ try {
357
+ return fs.watch(dir, { recursive: true }, (eventType, filename) => {
358
+ if (!filename) return;
359
+ const full = path.join(dir, filename);
360
+ handleCustomComponentChange(full, eventType);
361
+ });
362
+ } catch (_) {
363
+ return null;
364
+ }
365
+ }
366
+
367
+ function watchAppComponentsPerDir(dir) {
368
+ const watchers = new Map();
369
+
370
+ function watchDir(target) {
371
+ if (watchers.has(target)) return;
372
+ try {
373
+ const watcher = fs.watch(target, (eventType, filename) => {
374
+ const full = filename ? path.join(target, filename) : target;
375
+ handleCustomComponentChange(full, eventType);
376
+ scan(target);
377
+ });
378
+ watchers.set(target, watcher);
379
+ } catch (_) {}
380
+ }
381
+
382
+ function scan(target) {
383
+ let entries = [];
384
+ try {
385
+ entries = fs.readdirSync(target, { withFileTypes: true });
386
+ } catch (_) {
387
+ return;
388
+ }
389
+ for (const entry of entries) {
390
+ if (!entry.isDirectory()) continue;
391
+ const next = path.join(target, entry.name);
392
+ watchDir(next);
393
+ scan(next);
394
+ }
395
+ }
396
+
397
+ watchDir(dir);
398
+ scan(dir);
399
+
400
+ return () => {
401
+ for (const watcher of watchers.values()) {
402
+ try {
403
+ watcher.close();
404
+ } catch (_) {}
405
+ }
406
+ };
407
+ }
408
+
409
+ // Watch the package's ui dist output to enable live reload for UI edits during dev.
410
+ // When UI dist changes, rebuild the search runtime bundle and trigger a browser reload.
411
+ async function rebuildSearchBundle() {
412
+ try {
413
+ const search = require("./search");
414
+ if (search && typeof search.ensureSearchRuntime === "function") {
415
+ await search.ensureSearchRuntime();
416
+ }
417
+ } catch (_) {}
418
+ try {
419
+ onBuildSuccess();
420
+ } catch (_) {}
421
+ }
422
+
423
+ function tryRecursiveWatchUiDist() {
424
+ try {
425
+ if (!fs.existsSync(UI_DIST_DIR)) return null;
426
+ const watcher = fs.watch(
427
+ UI_DIST_DIR,
428
+ { recursive: true },
429
+ (eventType, filename) => {
430
+ if (!filename) return;
431
+ try {
432
+ console.log(
433
+ `[ui] ${eventType}: ${prettyPath(path.join(UI_DIST_DIR, filename))}`
434
+ );
435
+ } catch (_) {}
436
+ // Lightweight path: rebuild only the search runtime bundle
437
+ rebuildSearchBundle();
438
+ // If the server-side UI bundle changed, trigger a site rebuild (skip IIIF)
439
+ try {
440
+ if (/server\.(js|mjs)$/.test(filename)) {
441
+ nextBuildSkipIiif = true;
442
+ try {
443
+ onBuildStart();
444
+ } catch (_) {}
445
+ debounceBuild();
446
+ }
447
+ } catch (_) {}
448
+ }
449
+ );
450
+ return watcher;
451
+ } catch (_) {
452
+ return null;
453
+ }
454
+ }
455
+
456
+ function watchUiDistPerDir() {
457
+ if (!fs.existsSync(UI_DIST_DIR)) return () => {};
458
+ const watchers = new Map();
459
+ function watchDir(dir) {
460
+ if (watchers.has(dir)) return;
461
+ try {
462
+ const w = fs.watch(dir, (eventType, filename) => {
463
+ try {
464
+ console.log(
465
+ `[ui] ${eventType}: ${prettyPath(path.join(dir, filename || ""))}`
466
+ );
467
+ } catch (_) {}
468
+ scan(dir);
469
+ rebuildSearchBundle();
470
+ try {
471
+ if (/server\.(js|mjs)$/.test(filename || "")) {
472
+ nextBuildSkipIiif = true;
473
+ try {
474
+ onBuildStart();
475
+ } catch (_) {}
476
+ debounceBuild();
477
+ }
478
+ } catch (_) {}
479
+ });
480
+ watchers.set(dir, w);
481
+ } catch (_) {}
482
+ }
483
+ function scan(dir) {
484
+ const entries = fs.readdirSync(dir, { withFileTypes: true });
485
+ for (const e of entries) {
486
+ const p = path.join(dir, e.name);
487
+ if (e.isDirectory()) watchDir(p);
488
+ }
489
+ }
490
+ watchDir(UI_DIST_DIR);
491
+ scan(UI_DIST_DIR);
492
+ return () => {
493
+ for (const w of watchers.values()) w.close();
494
+ };
495
+ }
496
+
497
+ const APP_WATCH_EXTENSIONS = new Set([".js", ".jsx", ".scss"]);
498
+
499
+ function shouldIgnoreAppSourcePath(p) {
500
+ try {
501
+ const resolved = path.resolve(p);
502
+ const rel = path.relative(APP_PACKAGE_ROOT, resolved);
503
+ if (!rel || rel === "") return false;
504
+ if (rel.startsWith("..")) return true;
505
+ const segments = rel.split(path.sep).filter(Boolean);
506
+ if (!segments.length) return false;
507
+ if (segments.includes("node_modules")) return true;
508
+ if (segments.includes(".git")) return true;
509
+ if (segments[0] === "ui" && segments[1] === "dist") return true;
510
+ return false;
511
+ } catch (_) {
512
+ return true;
513
+ }
514
+ }
515
+
516
+ function handleAppSourceChange(baseDir, eventType, filename, label) {
517
+ if (!filename) return;
518
+ const full = path.resolve(baseDir, filename);
519
+ if (shouldIgnoreAppSourcePath(full)) return;
520
+ const ext = path.extname(full).toLowerCase();
521
+ if (!APP_WATCH_EXTENSIONS.has(ext)) return;
522
+ try {
523
+ const relLib = path.relative(APP_LIB_DIR, full);
524
+ if (!relLib.startsWith("..") && !path.isAbsolute(relLib)) {
525
+ pendingModuleReload = true;
526
+ }
527
+ } catch (_) {}
528
+ try {
529
+ console.log(
530
+ `[pkg] ${eventType}: ${prettyPath(full)}${label ? ` (${label})` : ""}`
531
+ );
532
+ } catch (_) {}
533
+ nextBuildSkipIiif = true;
534
+ try {
535
+ onBuildStart();
536
+ } catch (_) {}
537
+ debounceBuild();
538
+ }
539
+
540
+ function tryRecursiveWatchAppDir(dir, label) {
541
+ try {
542
+ return fs.watch(dir, { recursive: true }, (eventType, filename) => {
543
+ handleAppSourceChange(dir, eventType, filename, label);
544
+ });
545
+ } catch (_) {
546
+ return null;
547
+ }
548
+ }
549
+
550
+ function watchAppDirPerDir(dir, label) {
551
+ const watchers = new Map();
552
+
553
+ function watchDir(target) {
554
+ if (watchers.has(target)) return;
555
+ if (shouldIgnoreAppSourcePath(target)) return;
556
+ try {
557
+ const w = fs.watch(target, (eventType, filename) => {
558
+ if (filename) {
559
+ handleAppSourceChange(target, eventType, filename, label);
560
+ }
561
+ scan(target);
562
+ });
563
+ watchers.set(target, w);
564
+ } catch (_) {}
565
+ }
566
+
567
+ function scan(target) {
568
+ let entries;
569
+ try {
570
+ entries = fs.readdirSync(target, { withFileTypes: true });
571
+ } catch (_) {
572
+ return;
573
+ }
574
+ for (const entry of entries) {
575
+ if (!entry.isDirectory()) continue;
576
+ const sub = path.join(target, entry.name);
577
+ if (shouldIgnoreAppSourcePath(sub)) continue;
578
+ watchDir(sub);
579
+ scan(sub);
580
+ }
581
+ }
582
+
583
+ watchDir(dir);
584
+ scan(dir);
585
+
586
+ return () => {
587
+ for (const w of watchers.values()) {
588
+ try {
589
+ w.close();
590
+ } catch (_) {}
591
+ }
592
+ };
593
+ }
594
+
595
+ function watchAppSources() {
596
+ if (!HAS_APP_WORKSPACE) return () => {};
597
+ const stops = [];
598
+ for (const target of APP_WATCH_TARGETS) {
599
+ const { dir, label } = target;
600
+ if (!dir || !fs.existsSync(dir)) continue;
601
+ console.log(`[Watching] ${prettyPath(dir)} (${label})`);
602
+ const watcher = tryRecursiveWatchAppDir(dir, label);
603
+ if (!watcher) {
604
+ stops.push(watchAppDirPerDir(dir, label));
605
+ } else {
606
+ stops.push(() => {
607
+ try {
608
+ watcher.close();
609
+ } catch (_) {}
610
+ });
611
+ }
612
+ }
613
+ return () => {
614
+ for (const stop of stops) {
615
+ try {
616
+ if (typeof stop === "function") stop();
617
+ } catch (_) {}
618
+ }
619
+ };
620
+ }
621
+
622
+ const MIME = {
623
+ ".html": "text/html; charset=utf-8",
624
+ ".css": "text/css; charset=utf-8",
625
+ ".js": "application/javascript; charset=utf-8",
626
+ ".json": "application/json; charset=utf-8",
627
+ ".png": "image/png",
628
+ ".jpg": "image/jpeg",
629
+ ".jpeg": "image/jpeg",
630
+ ".gif": "image/gif",
631
+ ".svg": "image/svg+xml",
632
+ ".txt": "text/plain; charset=utf-8",
633
+ };
634
+
635
+ function startServer() {
636
+ const clients = new Set();
637
+ function broadcast(type) {
638
+ for (const res of clients) {
639
+ try {
640
+ res.write(`data: ${type}\n\n`);
641
+ } catch (_) {}
642
+ }
643
+ }
644
+ onBuildStart = () => broadcast("building");
645
+ onBuildSuccess = () => broadcast("reload");
646
+ onCssChange = () => broadcast("css");
647
+
648
+ const server = http.createServer((req, res) => {
649
+ const origin = `http://${req.headers.host || `localhost:${PORT}`}`;
650
+ let parsedUrl;
651
+ try {
652
+ parsedUrl = new URL(req.url || "/", origin);
653
+ } catch (_) {
654
+ parsedUrl = new URL("/", origin);
655
+ }
656
+ let pathname = decodeURI(parsedUrl.pathname || "/");
657
+ // Serve dev toast assets and config
658
+ if (pathname === "/__livereload-config") {
659
+ res.writeHead(200, {
660
+ "Content-Type": "application/json; charset=utf-8",
661
+ "Cache-Control": "no-cache",
662
+ });
663
+ const cfgPath = path.join(__dirname, "devtoast.config.json");
664
+ let cfg = {
665
+ buildingText: "Rebuilding…",
666
+ reloadedText: "Reloaded",
667
+ fadeMs: 800,
668
+ reloadDelayMs: 200,
669
+ };
670
+ try {
671
+ if (fs.existsSync(cfgPath)) {
672
+ const raw = fs.readFileSync(cfgPath, "utf8");
673
+ const parsedCfg = JSON.parse(raw);
674
+ cfg = { ...cfg, ...parsedCfg };
675
+ }
676
+ } catch (_) {}
677
+ res.end(JSON.stringify(cfg));
678
+ return;
679
+ }
680
+ if (pathname === "/__livereload.css") {
681
+ res.writeHead(200, {
682
+ "Content-Type": "text/css; charset=utf-8",
683
+ "Cache-Control": "no-cache",
684
+ });
685
+ const cssPath = path.join(__dirname, "devtoast.css");
686
+ let css = `#__lr_toast{position:fixed;bottom:12px;left:12px;background:rgba(0,0,0,.8);color:#fff;padding:6px 10px;border-radius:6px;font:12px/1.2 system-ui,-apple-system,Segoe UI,Roboto,sans-serif;z-index:99999;box-shadow:0 2px 8px rgba(0,0,0,.3);opacity:0;transition:opacity .15s ease}`;
687
+ try {
688
+ if (fs.existsSync(cssPath)) css = fs.readFileSync(cssPath, "utf8");
689
+ } catch (_) {}
690
+ res.end(css);
691
+ return;
692
+ }
693
+ if (pathname === "/__livereload") {
694
+ res.writeHead(200, {
695
+ "Content-Type": "text/event-stream",
696
+ "Cache-Control": "no-cache, no-transform",
697
+ Connection: "keep-alive",
698
+ });
699
+ res.write(": connected\n\n");
700
+ clients.add(res);
701
+ const keepAlive = setInterval(() => {
702
+ try {
703
+ res.write(": ping\n\n");
704
+ } catch (_) {}
705
+ }, 30000);
706
+ req.on("close", () => {
707
+ clearInterval(keepAlive);
708
+ clients.delete(res);
709
+ });
710
+ return;
711
+ }
712
+ if (pathname === "/") pathname = "/index.html";
713
+
714
+ function toSitePath(p) {
715
+ const rel = p.startsWith("/") ? `.${p}` : p;
716
+ return path.resolve(OUT_DIR, rel);
717
+ }
718
+
719
+ const ensureLeadingSlash = (p) => (p.startsWith("/") ? p : `/${p}`);
720
+ const basePath = ensureLeadingSlash(pathname);
721
+ const noTrailing = basePath !== "/" ? basePath.replace(/\/+$/, "") : basePath;
722
+ const attempts = [];
723
+
724
+ const primaryPath = noTrailing === "/" ? "/index.html" : noTrailing;
725
+ attempts.push(toSitePath(primaryPath));
726
+
727
+ if (!/\.html$/i.test(primaryPath)) {
728
+ attempts.push(toSitePath(`${primaryPath}.html`));
729
+ }
730
+
731
+ const withoutHtml = primaryPath.replace(/\.html$/i, "");
732
+ attempts.push(toSitePath(`${withoutHtml}/index.html`));
733
+
734
+ let filePath = null;
735
+ for (const candidate of attempts) {
736
+ if (!candidate) continue;
737
+ let stat;
738
+ try {
739
+ stat = fs.statSync(candidate);
740
+ } catch (_) {
741
+ continue;
742
+ }
743
+ if (stat.isFile()) {
744
+ filePath = candidate;
745
+ break;
746
+ }
747
+ if (stat.isDirectory()) {
748
+ const idx = path.join(candidate, "index.html");
749
+ if (fs.existsSync(idx)) {
750
+ filePath = idx;
751
+ break;
752
+ }
753
+ }
754
+ }
755
+ if (!filePath) {
756
+ res.statusCode = 404;
757
+ res.setHeader("Content-Type", "text/plain; charset=utf-8");
758
+ res.end("Not Found");
759
+ return;
760
+ }
761
+
762
+ // Prevent path traversal by ensuring resolved path stays under SITE_DIR
763
+ let resolved = path.resolve(filePath);
764
+ if (!resolved.startsWith(OUT_DIR)) {
765
+ res.statusCode = 403;
766
+ res.end("Forbidden");
767
+ return;
768
+ }
769
+
770
+ // If a directory slipped through, try its index.html
771
+ try {
772
+ const st = fs.statSync(resolved);
773
+ if (st.isDirectory()) {
774
+ const idx = path.join(resolved, "index.html");
775
+ if (fs.existsSync(idx)) {
776
+ filePath = idx;
777
+ resolved = path.resolve(filePath);
778
+ } else {
779
+ res.statusCode = 404;
780
+ res.end("Not Found");
781
+ return;
782
+ }
783
+ }
784
+ } catch (_) {}
785
+
786
+ // Ensure resolved reflects the final filePath
787
+ resolved = path.resolve(filePath);
788
+ const ext = path.extname(resolved).toLowerCase();
789
+ res.statusCode = 200;
790
+ res.setHeader("Content-Type", MIME[ext] || "application/octet-stream");
791
+ // Dev: always disable caching so reloads fetch fresh assets
792
+ res.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
793
+ res.setHeader("Pragma", "no-cache");
794
+ res.setHeader("Expires", "0");
795
+ if (ext === ".html") {
796
+ try {
797
+ let html = fs.readFileSync(resolved, "utf8");
798
+ const snippet = `
799
+ <link rel="stylesheet" href="/__livereload.css">
800
+ <script>(function(){
801
+ var t, cfg = { buildingText: 'Rebuilding…', reloadedText: 'Reloaded', fadeMs: 800, reloadDelayMs: 200 };
802
+ fetch('/__livereload-config').then(function(r){ return r.json(); }).then(function(j){ cfg = j; }).catch(function(){});
803
+ function toast(m){ var el = document.getElementById('__lr_toast'); if(!el){ el=document.createElement('div'); el.id='__lr_toast'; document.body.appendChild(el); } el.textContent=m; el.style.opacity='1'; clearTimeout(t); t=setTimeout(function(){ el.style.opacity='0'; }, cfg.fadeMs); }
804
+ (function(){
805
+ var lastCssSwap = 0;
806
+ function swapLink(l){
807
+ try{
808
+ var href = l.getAttribute('href') || '';
809
+ var base = href.split('?')[0];
810
+ var next = l.cloneNode();
811
+ next.setAttribute('href', base + '?v=' + Date.now());
812
+ // Load new stylesheet off-screen, then atomically switch to avoid FOUC
813
+ next.media = 'print';
814
+ next.onload = function(){ try { next.media = 'all'; l.remove(); } catch(_){} };
815
+ l.parentNode.insertBefore(next, l.nextSibling);
816
+ }catch(_){ }
817
+ }
818
+ window.__canopyReloadCss = function(){
819
+ var now = Date.now();
820
+ if (now - lastCssSwap < 200) return; // throttle spammy events
821
+ lastCssSwap = now;
822
+ try {
823
+ var links = document.querySelectorAll('link[rel="stylesheet"]');
824
+ links.forEach(function(l){
825
+ try {
826
+ var href = l.getAttribute('href') || '';
827
+ var base = href.split('?')[0];
828
+ if (base.indexOf('styles/styles.css') !== -1) swapLink(l);
829
+ } catch(_) {}
830
+ });
831
+ } catch(_) {}
832
+ };
833
+ })();
834
+ var es = new EventSource('/__livereload');
835
+ es.onmessage = function(e){
836
+ if (e.data === 'building') { /* no toast for css-only builds to reduce blinking */ }
837
+ else if (e.data === 'css') { if (window.__canopyReloadCss) window.__canopyReloadCss(); }
838
+ else if (e.data === 'reload') { toast(cfg.reloadedText); setTimeout(function(){ location.reload(); }, cfg.reloadDelayMs); }
839
+ };
840
+ window.addEventListener('beforeunload', function(){ try { es.close(); } catch(e) {} });
841
+ })();</script>`;
842
+ html = html.includes("</body>")
843
+ ? html.replace("</body>", snippet + "</body>")
844
+ : html + snippet;
845
+ res.end(html);
846
+ } catch (e) {
847
+ res.statusCode = 500;
848
+ res.end("Error serving HTML");
849
+ }
850
+ } else {
851
+ fs.createReadStream(resolved).pipe(res);
852
+ }
853
+ });
854
+
855
+ server.listen(PORT, () => {
856
+ console.log(`Serving site on http://localhost:${PORT}`);
857
+ });
858
+
859
+ return server;
860
+ }
861
+
862
+ async function dev() {
863
+ if (!fs.existsSync(CONTENT_DIR)) {
864
+ console.error("No content directory found at", CONTENT_DIR);
865
+ process.exit(1);
866
+ }
867
+ // Start server before the initial build so build logs follow server standup
868
+ startServer();
869
+ console.log("Initial build...");
870
+ // Expose a base URL for builders to construct absolute ids/links
871
+ if (!process.env.CANOPY_BASE_URL) {
872
+ process.env.CANOPY_BASE_URL = `http://localhost:${PORT}`;
873
+ }
874
+ // In dev, let the Tailwind watcher own CSS generation to avoid duplicate
875
+ // one-off builds that print "Rebuilding..." messages. Skip ensureStyles()
876
+ // within build() by setting an environment flag.
877
+ process.env.CANOPY_SKIP_STYLES = process.env.DEV_ONCE ? "" : "1";
878
+ // Suppress noisy Browserslist old data warning in dev/tailwind
879
+ process.env.BROWSERSLIST_IGNORE_OLD_DATA = "1";
880
+ if (process.env.DEV_ONCE) {
881
+ // Build once and exit (used for tests/CI)
882
+ runBuild()
883
+ .then(() => process.exit(0))
884
+ .catch(() => process.exit(1));
885
+ return;
886
+ }
887
+ // Run the initial build synchronously now that the server is up
888
+ await runBuild();
889
+
890
+ // Start the Tailwind watcher once an input stylesheet exists (after the
891
+ // initial build). Tailwind v4 reads a JS config only through `@config`.
892
+ try {
893
+ const root = process.cwd();
894
+ const appStylesDir = path.join(root, "app", "styles");
895
+ const inputCandidates = [
896
+ path.join(appStylesDir, "index.css"),
897
+ path.join(CONTENT_DIR, "_styles.css"),
898
+ ];
899
+ const inputCss = inputCandidates.find((p) => {
900
+ try {
901
+ return fs.existsSync(p);
902
+ } catch (_) {
903
+ return false;
904
+ }
905
+ });
906
+ if (!inputCss) {
907
+ throw new Error(
908
+ "[tailwind] Missing Tailwind entry stylesheet. Create app/styles/index.css (or content/_styles.css)."
909
+ );
910
+ }
911
+ const outputCss = path.join(OUT_DIR, "styles", "styles.css");
912
+ ensureDirSync(path.dirname(outputCss));
913
+
914
+ const cli = resolveTailwindCli();
915
+ if (!cli) {
916
+ throw new Error(
917
+ "[tailwind] Tailwind CLI not found. Install '@tailwindcss/cli' (and tailwindcss) in this workspace."
918
+ );
919
+ }
920
+
921
+ const fileSizeKb = (p) => {
922
+ try {
923
+ const st = fs.statSync(p);
924
+ return st && st.size ? (st.size / 1024).toFixed(1) : "0.0";
925
+ } catch (_) {
926
+ return "0.0";
927
+ }
928
+ };
929
+
930
+ const tailwindArgVector = (args = []) => {
931
+ const vector = [];
932
+ if (cli.cmd) vector.push(cli.cmd);
933
+ if (Array.isArray(cli.args) && cli.args.length) vector.push(...cli.args);
934
+ if (Array.isArray(args) && args.length) vector.push(...args);
935
+ return vector;
936
+ };
937
+
938
+ const tailwindCmd = (args = []) => tailwindArgVector(args).join(" ");
939
+
940
+ const formatSpawnOutput = (result) => {
941
+ if (!result) return "";
942
+ const messages = [];
943
+ if (result.stderr && result.stderr.length) {
944
+ const text = String(result.stderr).trim();
945
+ if (text) messages.push(`stderr: ${text}`);
946
+ }
947
+ if (result.stdout && result.stdout.length) {
948
+ const text = String(result.stdout).trim();
949
+ if (text) messages.push(`stdout: ${text}`);
950
+ }
951
+ return messages.join("\n");
952
+ };
953
+
954
+ const tailwindFailureMessage = (label, result, args) => {
955
+ const details = [
956
+ label,
957
+ ` input: ${prettyPath(inputCss)}`,
958
+ ` cli: ${tailwindCmd(args)}`,
959
+ ];
960
+ if (result && typeof result.status === "number") {
961
+ details.push(` exitCode: ${result.status}`);
962
+ }
963
+ if (result && result.error) {
964
+ const err = result.error;
965
+ details.push(
966
+ ` spawnError: ${err && err.message ? err.message : String(err)}`
967
+ );
968
+ }
969
+ if (result && result.signal) {
970
+ details.push(` signal: ${result.signal}`);
971
+ }
972
+ const extraArgs = tailwindArgVector(args)
973
+ .map((part) => {
974
+ if (!part || typeof part !== "string") return part;
975
+ if (part.includes("\n")) return part.replace(/\n/g, "\\n");
976
+ return part;
977
+ })
978
+ .join(" ");
979
+ if (extraArgs && extraArgs !== tailwindCmd(args)) {
980
+ details.push(` cliRaw: ${extraArgs}`);
981
+ }
982
+ const extra = formatSpawnOutput(result);
983
+ if (extra) {
984
+ details.push(
985
+ extra
986
+ .split(/\r?\n/)
987
+ .map((line) => ` ${line}`)
988
+ .join("\n")
989
+ );
990
+ }
991
+ return details.join("\n");
992
+ };
993
+
994
+ const baseArgs = [
995
+ "-i",
996
+ inputCss,
997
+ "-o",
998
+ outputCss,
999
+ "--minify",
1000
+ ];
1001
+
1002
+ const spawnOptions = {
1003
+ stdio: ["ignore", "pipe", "pipe"],
1004
+ env: { ...process.env, BROWSERSLIST_IGNORE_OLD_DATA: "1" },
1005
+ };
1006
+
1007
+ const initial = spawnSync(cli.cmd, [...cli.args, ...baseArgs], spawnOptions);
1008
+ if (!initial || initial.status !== 0) {
1009
+ throw new Error(
1010
+ tailwindFailureMessage(
1011
+ "[tailwind] Initial Tailwind build failed.",
1012
+ initial,
1013
+ baseArgs
1014
+ )
1015
+ );
1016
+ }
1017
+ injectThemeTokens(outputCss);
1018
+ console.log(
1019
+ `[tailwind] initial build ok (${fileSizeKb(outputCss)} KB) →`,
1020
+ prettyPath(outputCss)
1021
+ );
1022
+
1023
+ const watchArgs = [
1024
+ "-i",
1025
+ inputCss,
1026
+ "-o",
1027
+ outputCss,
1028
+ "--watch",
1029
+ "--minify",
1030
+ ];
1031
+ let child = null;
1032
+ let unmuted = false;
1033
+ let cssWatcherAttached = false;
1034
+
1035
+ function attachCssWatcherOnce() {
1036
+ if (cssWatcherAttached) return;
1037
+ cssWatcherAttached = true;
1038
+ try {
1039
+ fs.watch(outputCss, { persistent: false }, () => {
1040
+ injectThemeTokens(outputCss);
1041
+ if (!unmuted) {
1042
+ unmuted = true;
1043
+ console.log(
1044
+ `[tailwind] watching ${prettyPath(
1045
+ inputCss
1046
+ )} — compiled (${fileSizeKb(outputCss)} KB)`
1047
+ );
1048
+ }
1049
+ try {
1050
+ onCssChange();
1051
+ } catch (_) {}
1052
+ });
1053
+ } catch (_) {}
1054
+ }
1055
+
1056
+ function compileTailwindOnce() {
1057
+ const res = spawnSync(cli.cmd, [...cli.args, ...baseArgs], spawnOptions);
1058
+ if (!res || res.status !== 0) {
1059
+ throw new Error(
1060
+ tailwindFailureMessage(
1061
+ "[tailwind] On-demand Tailwind compile failed.",
1062
+ res,
1063
+ baseArgs
1064
+ )
1065
+ );
1066
+ }
1067
+ injectThemeTokens(outputCss);
1068
+ console.log(
1069
+ `[tailwind] compiled (${fileSizeKb(outputCss)} KB) →`,
1070
+ prettyPath(outputCss)
1071
+ );
1072
+ try {
1073
+ onCssChange();
1074
+ } catch (_) {}
1075
+ }
1076
+
1077
+ function startTailwindWatcher() {
1078
+ unmuted = false;
1079
+ const proc = spawn(cli.cmd, [...cli.args, ...watchArgs], {
1080
+ stdio: ["ignore", "pipe", "pipe"],
1081
+ env: { ...process.env, BROWSERSLIST_IGNORE_OLD_DATA: "1" },
1082
+ });
1083
+ if (proc.stdout)
1084
+ proc.stdout.on("data", (d) => {
1085
+ const s = d ? String(d) : "";
1086
+ if (!unmuted) {
1087
+ if (/error/i.test(s)) {
1088
+ try { process.stdout.write("[tailwind] " + s); } catch (_) {}
1089
+ }
1090
+ } else {
1091
+ try { process.stdout.write(s); } catch (_) {}
1092
+ }
1093
+ });
1094
+ if (proc.stderr)
1095
+ proc.stderr.on("data", (d) => {
1096
+ const s = d ? String(d) : "";
1097
+ if (!unmuted) {
1098
+ if (s.trim()) {
1099
+ try { process.stderr.write("[tailwind] " + s); } catch (_) {}
1100
+ }
1101
+ } else {
1102
+ try { process.stderr.write(s); } catch (_) {}
1103
+ }
1104
+ });
1105
+ proc.on("exit", (code) => {
1106
+ if (code !== null && code !== 0) {
1107
+ console.error("[tailwind] watcher exited with code", code);
1108
+ process.exit(typeof code === "number" ? code : 1);
1109
+ }
1110
+ });
1111
+ attachCssWatcherOnce();
1112
+ return proc;
1113
+ }
1114
+
1115
+ const safeCompile = (label) => {
1116
+ try {
1117
+ compileTailwindOnce();
1118
+ } catch (err) {
1119
+ console.error(label ? `${label}: ${err.message || err}` : err);
1120
+ process.exit(1);
1121
+ }
1122
+ };
1123
+
1124
+ child = startTailwindWatcher();
1125
+
1126
+ const uiStylesDir = path.join(APP_UI_DIR, "styles");
1127
+ const uiStylesCss = path.join(uiStylesDir, "index.css");
1128
+ const uiStylesEntry = path.join(uiStylesDir, "index.scss");
1129
+ let restartTimer = null;
1130
+ let uiCssWatcherAttached = false;
1131
+ const scheduleTailwindRestart = (message, compileLabel) => {
1132
+ clearTimeout(restartTimer);
1133
+ restartTimer = setTimeout(() => {
1134
+ if (message) console.log(message);
1135
+ try {
1136
+ if (child && !child.killed) child.kill();
1137
+ } catch (_) {}
1138
+ safeCompile(compileLabel);
1139
+ child = startTailwindWatcher();
1140
+ try { onBuildStart(); } catch (_) {}
1141
+ }, 120);
1142
+ };
1143
+ const rebuildUiStyles = () => {
1144
+ if (!sass || !fs.existsSync(uiStylesEntry)) return false;
1145
+ try {
1146
+ const result = sass.compileString("@use 'index';", {
1147
+ loadPaths: [uiStylesDir],
1148
+ style: "expanded",
1149
+ });
1150
+ // No theme here: injectThemeTokens() adds it to the site stylesheet.
1151
+ // A copy baked into this package file would outlive canopy.yml edits
1152
+ // and, once imported, override the fresh theme. Clover's stylesheets
1153
+ // come first, as the UI build writes them (`ui-styles.js`).
1154
+ const cssOutput = result && result.css ? result.css : "";
1155
+ fs.writeFileSync(uiStylesCss, withUiStylesImports(cssOutput), "utf8");
1156
+ console.log(
1157
+ `[tailwind] rebuilt ${PACKAGE_NAME}/ui styles →`,
1158
+ prettyPath(uiStylesCss)
1159
+ );
1160
+ return true;
1161
+ } catch (err) {
1162
+ console.warn(
1163
+ `[tailwind] failed to rebuild ${PACKAGE_NAME}/ui styles:`,
1164
+ err && err.message ? err.message : err
1165
+ );
1166
+ return false;
1167
+ }
1168
+ };
1169
+ const attachCssWatcher = () => {
1170
+ if (uiCssWatcherAttached) {
1171
+ if (fs.existsSync(uiStylesCss)) return;
1172
+ uiCssWatcherAttached = false;
1173
+ }
1174
+ if (!fs.existsSync(uiStylesCss)) return;
1175
+ const handler = () =>
1176
+ scheduleTailwindRestart(
1177
+ `[tailwind] detected ${PACKAGE_NAME}/ui styles change — restarting Tailwind`,
1178
+ "[tailwind] compile after UI styles change failed"
1179
+ );
1180
+ try {
1181
+ const watcher = fs.watch(uiStylesCss, { persistent: false }, handler);
1182
+ uiCssWatcherAttached = true;
1183
+ watcher.on("close", () => {
1184
+ uiCssWatcherAttached = false;
1185
+ });
1186
+ } catch (_) {
1187
+ try {
1188
+ fs.watchFile(uiStylesCss, { interval: 250 }, handler);
1189
+ uiCssWatcherAttached = true;
1190
+ } catch (_) {}
1191
+ }
1192
+ };
1193
+ if (fs.existsSync(uiStylesEntry)) rebuildUiStyles();
1194
+ attachCssWatcher();
1195
+ const handleUiSassChange = () => {
1196
+ const ok = rebuildUiStyles();
1197
+ attachCssWatcher();
1198
+ scheduleTailwindRestart(
1199
+ ok
1200
+ ? `[tailwind] detected ${PACKAGE_NAME}/ui Sass change — restarting Tailwind`
1201
+ : "[tailwind] Sass compile failed — attempting Tailwind restart",
1202
+ "[tailwind] compile after UI Sass change failed"
1203
+ );
1204
+ };
1205
+ if (fs.existsSync(uiStylesDir)) {
1206
+ try {
1207
+ fs.watch(
1208
+ uiStylesDir,
1209
+ { persistent: false, recursive: true },
1210
+ (evt, fn) => {
1211
+ try {
1212
+ if (fn && /\.s[ac]ss$/i.test(String(fn))) handleUiSassChange();
1213
+ } catch (_) {}
1214
+ }
1215
+ );
1216
+ } catch (_) {
1217
+ const watchers = new Map();
1218
+ const watchDir = (dir) => {
1219
+ if (watchers.has(dir)) return;
1220
+ try {
1221
+ const w = fs.watch(
1222
+ dir,
1223
+ { persistent: false },
1224
+ (evt, fn) => {
1225
+ try {
1226
+ if (fn && /\.s[ac]ss$/i.test(String(fn))) handleUiSassChange();
1227
+ } catch (_) {}
1228
+ scan(dir);
1229
+ }
1230
+ );
1231
+ watchers.set(dir, w);
1232
+ } catch (_) {}
1233
+ };
1234
+ const scan = (dir) => {
1235
+ try {
1236
+ const entries = fs.readdirSync(dir, {
1237
+ withFileTypes: true,
1238
+ });
1239
+ for (const e of entries) {
1240
+ const p = path.join(dir, e.name);
1241
+ if (e.isDirectory()) {
1242
+ watchDir(p);
1243
+ scan(p);
1244
+ }
1245
+ }
1246
+ } catch (_) {}
1247
+ };
1248
+ watchDir(uiStylesDir);
1249
+ scan(uiStylesDir);
1250
+ }
1251
+ }
1252
+ const stylesDir = path.dirname(inputCss);
1253
+ if (stylesDir && stylesDir.includes(path.join("app", "styles"))) {
1254
+ let cssDebounce = null;
1255
+ const triggerCssRebuild = () => {
1256
+ clearTimeout(cssDebounce);
1257
+ cssDebounce = setTimeout(() => {
1258
+ try { onBuildStart(); } catch (_) {}
1259
+ safeCompile("[tailwind] compile after CSS change failed");
1260
+ try { onCssChange(); } catch (_) {}
1261
+ }, 50);
1262
+ };
1263
+ const shouldHandle = (filename) => {
1264
+ if (!filename) return true;
1265
+ return /\.(css|s[ac]ss)$/i.test(String(filename));
1266
+ };
1267
+ const attachRecursiveWatch = () => {
1268
+ try {
1269
+ fs.watch(
1270
+ stylesDir,
1271
+ { persistent: false, recursive: true },
1272
+ (evt, fn) => {
1273
+ if (!shouldHandle(fn)) return;
1274
+ triggerCssRebuild();
1275
+ }
1276
+ );
1277
+ return true;
1278
+ } catch (_) {
1279
+ return false;
1280
+ }
1281
+ };
1282
+ if (!attachRecursiveWatch()) {
1283
+ const watchers = new Map();
1284
+ function watchDir(dir) {
1285
+ if (watchers.has(dir)) return;
1286
+ try {
1287
+ const watcher = fs.watch(
1288
+ dir,
1289
+ { persistent: false },
1290
+ (evt, fn) => {
1291
+ if (shouldHandle(fn)) triggerCssRebuild();
1292
+ scanDir(dir);
1293
+ }
1294
+ );
1295
+ watchers.set(dir, watcher);
1296
+ } catch (_) {}
1297
+ }
1298
+ function scanDir(dir) {
1299
+ let entries = [];
1300
+ try {
1301
+ entries = fs.readdirSync(dir, { withFileTypes: true });
1302
+ } catch (_) {
1303
+ return;
1304
+ }
1305
+ for (const entry of entries) {
1306
+ if (!entry || !entry.isDirectory()) continue;
1307
+ const next = path.join(dir, entry.name);
1308
+ watchDir(next);
1309
+ scanDir(next);
1310
+ }
1311
+ }
1312
+ watchDir(stylesDir);
1313
+ scanDir(stylesDir);
1314
+ }
1315
+ }
1316
+ } catch (err) {
1317
+ console.error("[tailwind] setup failed:", err && err.message ? err.message : err);
1318
+ process.exit(1);
1319
+ }
1320
+ console.log("[Watching]", prettyPath(CONTENT_DIR), "(Ctrl+C to stop)");
1321
+ const rw = tryRecursiveWatch();
1322
+ if (!rw) watchPerDir();
1323
+ // Watch assets for live copy without full rebuild
1324
+ if (fs.existsSync(ASSETS_DIR)) {
1325
+ console.log("[Watching]", prettyPath(ASSETS_DIR), "(assets live-reload)");
1326
+ const arw = tryRecursiveWatchAssets();
1327
+ if (!arw) watchAssetsPerDir();
1328
+ }
1329
+ // Watch UI dist for live-reload and targeted search runtime rebuilds
1330
+ if (fs.existsSync(UI_DIST_DIR)) {
1331
+ console.log(
1332
+ "[Watching]",
1333
+ prettyPath(UI_DIST_DIR),
1334
+ `(${PACKAGE_NAME}/ui dist)`
1335
+ );
1336
+ const urw = tryRecursiveWatchUiDist();
1337
+ if (!urw) watchUiDistPerDir();
1338
+ }
1339
+ if (fs.existsSync(APP_COMPONENTS_DIR)) {
1340
+ console.log(
1341
+ "[Watching]",
1342
+ prettyPath(APP_COMPONENTS_DIR),
1343
+ "(app components)"
1344
+ );
1345
+ const crw = tryRecursiveWatchAppComponents(APP_COMPONENTS_DIR);
1346
+ if (!crw) watchAppComponentsPerDir(APP_COMPONENTS_DIR);
1347
+ }
1348
+ if (HAS_APP_WORKSPACE) {
1349
+ watchAppSources();
1350
+ }
1351
+ }
1352
+
1353
+ module.exports = { dev };
1354
+
1355
+ if (require.main === module) dev();