http-server-rs 0.0.39

Simple, zero-configuration command-line static HTTP server.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
use std::collections::HashMap;
use std::fs;
use std::path::Path;
use std::path::PathBuf;
use std::sync::Mutex;

use serde::Deserialize;
use serde_json::Value;

const CONFIG_FILE_NAMES: [&str; 2] = ["deno.json", "tsconfig.json"];

/// The `jsx` compiler option values relevant to transpilation.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum JsxMode {
  /// `preserve` - JSX is left as-is and no transform runs.
  Preserve,
  /// `react` (classic) - uses `React.createElement` (or a custom factory).
  React,
  /// `react-jsx` - automatic runtime that injects `react/jsx-runtime`.
  ReactJsx,
  /// `react-jsxdev` - automatic runtime with development-only metadata.
  ReactJsxDev,
  /// `react-native` - JSX is preserved and passed through.
  ReactNative,
}

impl JsxMode {
  fn parse(value: &str) -> Option<Self> {
    match value.to_ascii_lowercase().as_str() {
      "preserve" => Some(Self::Preserve),
      "react" => Some(Self::React),
      "react-jsx" | "reactjsx" => Some(Self::ReactJsx),
      "react-jsxdev" | "reactjsxdev" => Some(Self::ReactJsxDev),
      "react-native" | "reactnative" => Some(Self::ReactNative),
      _ => None,
    }
  }
}

/// A resolution of the TypeScript compiler options that affect transpilation.
///
/// Only a subset of `compilerOptions` is represented - the options that the
/// swc transformer can act on. The options are read from a `tsconfig.json` or
/// a `deno.json`, which share the `compilerOptions` shape.
#[derive(Debug, Clone, PartialEq)]
pub struct TsConfig {
  /// The `jsx` compiler option, if set.
  pub jsx: Option<JsxMode>,
  /// The `jsxFactory` compiler option, e.g. `h` for Preact.
  pub jsx_factory: Option<String>,
  /// The `jsxFragmentFactory` compiler option, e.g. `Fragment`.
  pub jsx_fragment_factory: Option<String>,
  /// The `jsxImportSource` compiler option, e.g. `preact` for the automatic runtime.
  pub jsx_import_source: Option<String>,
  /// A value that changes when the config on disk changes.
  pub signature: u64,
}

impl TsConfig {
  /// The default options used when no config file could be found.
  pub fn defaults() -> Self {
    Self {
      jsx: None,
      jsx_factory: None,
      jsx_fragment_factory: None,
      jsx_import_source: None,
      signature: 0,
    }
  }
}

impl Default for TsConfig {
  fn default() -> Self {
    Self::defaults()
  }
}

/// The raw shape of a config file as it appears on disk.
///
/// `tsconfig.json` and `deno.json` agree on the parts read here; the extra
/// top-level keys a `deno.json` carries (`imports`, `tasks`, ...) are ignored.
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct RawTsConfig {
  /// Path to a config to inherit from. Can be a single string or an array.
  extends: Option<Value>,
  compiler_options: Option<CompilerOptions>,
}

#[derive(Debug, Default, Deserialize)]
#[serde(rename_all = "camelCase")]
struct CompilerOptions {
  jsx: Option<String>,
  jsx_factory: Option<String>,
  jsx_fragment_factory: Option<String>,
  jsx_import_source: Option<String>,
}

impl CompilerOptions {
  /// Flatten into a map so that inherited options can be merged by key.
  fn into_map(self) -> HashMap<String, Value> {
    let mut map = HashMap::new();

    let mut insert = |key: &str, value: Option<String>| {
      if let Some(value) = value {
        map.insert(key.to_string(), Value::String(value));
      }
    };

    insert("jsx", self.jsx);
    insert("jsxFactory", self.jsx_factory);
    insert("jsxFragmentFactory", self.jsx_fragment_factory);
    insert("jsxImportSource", self.jsx_import_source);

    map
  }
}

/// Locate a config from this dir up to (inclusive) the `stop_dir` boundary.
///
/// Returns the path to the nearest `deno.json` or `tsconfig.json`. A
/// `deno.json` is preferred when both sit in the same directory.
pub fn find_nearest_tsconfig(
  file_path: &Path,
  stop_dir: &Path,
) -> Option<PathBuf> {
  let mut current = file_path.parent()?;

  loop {
    for name in CONFIG_FILE_NAMES {
      let candidate = current.join(name);

      if candidate.is_file() {
        return Some(candidate);
      }
    }

    // Stop after checking the serve dir so that configs outside of the
    // served directory don't leak into the responses.
    if current == stop_dir {
      return None;
    }

    current = {
      let parent = current.parent()?;
      // Never walk above the stop dir
      if !parent.starts_with(stop_dir) && parent != stop_dir {
        return None;
      }
      parent
    };
  }
}

/// Read and resolve a config, following the `extends` chain.
///
/// Missing files and invalid JSON are treated as "no config" (`None`) because
/// a malformed config should not stop the server from serving files.
pub fn load_tsconfig(path: &Path) -> Option<TsConfig> {
  let (options, signature) = load_chain(path, 0, &mut Vec::new())?;

  let get = |key: &str| options.get(key).and_then(|value| value.as_str());

  Some(TsConfig {
    jsx: get("jsx").and_then(JsxMode::parse),
    jsx_factory: get("jsxFactory").map(ToString::to_string),
    jsx_fragment_factory: get("jsxFragmentFactory").map(ToString::to_string),
    jsx_import_source: get("jsxImportSource").map(ToString::to_string),
    signature,
  })
}

/// Recursively load a config and its parents, returning the merged compiler
/// options and a signature derived from the contents of every file read.
fn load_chain(
  path: &Path,
  depth: usize,
  visited: &mut Vec<PathBuf>,
) -> Option<(HashMap<String, Value>, u64)> {
  // Protect against circular `extends` references
  if depth > 16 {
    return None;
  }
  let canonical = path.canonicalize().unwrap_or_else(|_| path.to_path_buf());

  if visited.contains(&canonical) {
    return None;
  }
  visited.push(canonical.clone());

  let contents = fs::read_to_string(path).ok()?;
  let raw: RawTsConfig = serde_json::from_str(&contents).ok()?;

  let mut options = HashMap::new();

  // The `extends` chain is resolved first so that child options win
  if let Some(extends) = raw.extends.as_ref() {
    for specifier in extends_specifiers(extends) {
      if let Some(extended_path) = resolve_extends(path, &specifier) {
        if let Some((parent_options, _)) = load_chain(&extended_path, depth + 1, visited) {
          options.extend(parent_options);
        }
      }
    }
  }

  if let Some(compiler_options) = raw.compiler_options {
    for (key, value) in compiler_options.into_map() {
      options.insert(key, value);
    }
  }

  let signature = signature_of(&contents);

  Some((options, signature))
}

/// Normalise `extends` into a list of specifiers.
fn extends_specifiers(value: &Value) -> Vec<String> {
  match value {
    Value::String(value) => vec![value.clone()],
    Value::Array(values) => values
      .iter()
      .filter_map(|value| value.as_str().map(ToString::to_string))
      .collect(),
    _ => Vec::new(),
  }
}

/// Resolve an `extends` specifier to a path on disk.
///
/// A specifier without an extension is treated as a directory holding another
/// config of the same kind (`tsconfig.json` next to a `tsconfig.json`,
/// `deno.json` next to a `deno.json`). Also supports configs that live inside
/// a node package (e.g. `@tsconfig/node20/tsconfig.json`) by walking up the
/// directory tree looking for a `node_modules` folder.
fn resolve_extends(
  config_path: &Path,
  specifier: &str,
) -> Option<PathBuf> {
  let base_dir = config_path.parent()?;
  let config_file = config_path
    .file_name()
    .unwrap_or_else(|| "tsconfig.json".as_ref());

  let with_json = |value: PathBuf| -> PathBuf {
    if value.extension().is_some() {
      value
    } else {
      value.join(config_file)
    }
  };

  if specifier.starts_with('.') || specifier.starts_with('/') {
    let candidate = with_json(base_dir.join(specifier));
    if candidate.is_file() {
      return Some(candidate);
    }
    return None;
  }

  let mut current = Some(base_dir);

  while let Some(dir) = current {
    let candidate = with_json(dir.join("node_modules").join(specifier));

    if candidate.is_file() {
      return Some(candidate);
    }

    current = dir.parent();
  }

  None
}

/// A cheap content hash used to key the tsconfig cache.
fn signature_of(contents: &str) -> u64 {
  use std::collections::hash_map::DefaultHasher;
  use std::hash::Hash;
  use std::hash::Hasher;

  let mut hasher = DefaultHasher::new();
  contents.hash(&mut hasher);
  hasher.finish()
}

/// A process-wide cache of resolved configs keyed by source file path.
///
/// Config resolution reads from disk, so caching avoids doing filesystem
/// work on every single request.
#[derive(Debug, Default)]
pub struct TsConfigCache {
  entries: Mutex<HashMap<PathBuf, CachedConfig>>,
}

#[derive(Debug, Clone)]
struct CachedConfig {
  config_path: Option<PathBuf>,
  signature: u64,
  config: TsConfig,
}

impl TsConfigCache {
  pub fn new() -> Self {
    Self::default()
  }

  /// Resolve the config for a file, using the cache when the underlying
  /// config files have not changed.
  pub fn resolve(
    &self,
    file_path: &Path,
    stop_dir: &Path,
  ) -> TsConfig {
    let key = file_path.to_path_buf();

    {
      let entries = self.entries.lock().ok();
      if let Some(entries) = entries.as_ref() {
        if let Some(cached) = entries.get(&key) {
          if is_fresh(cached, file_path, stop_dir) {
            return cached.config.clone();
          }
        }
      }
    }

    let config_path = find_nearest_tsconfig(file_path, stop_dir);
    let config = match config_path.as_ref() {
      Some(path) => load_tsconfig(path).unwrap_or_else(TsConfig::defaults),
      None => TsConfig::defaults(),
    };

    if let Ok(mut entries) = self.entries.lock() {
      entries.insert(
        key,
        CachedConfig {
          config_path,
          signature: config.signature,
          config: config.clone(),
        },
      );
    }

    config
  }
}

/// Returns `true` when the cached entry still reflects what is on disk.
fn is_fresh(
  cached: &CachedConfig,
  file_path: &Path,
  stop_dir: &Path,
) -> bool {
  // Re-run the lookup so that a config appearing, disappearing or taking
  // priority over the cached one invalidates the entry.
  if find_nearest_tsconfig(file_path, stop_dir) != cached.config_path {
    return false;
  }

  let Some(path) = cached.config_path.as_ref() else {
    return true;
  };

  let Ok(contents) = fs::read_to_string(path) else {
    return false;
  };

  signature_of(&contents) == cached.signature
}

#[cfg(test)]
mod tests {
  use std::io::Write;

  use super::*;

  fn temp_dir(name: &str) -> PathBuf {
    let dir = std::env::temp_dir().join(format!(
      "http-server-rs-tsconfig-{}-{}",
      name,
      std::process::id()
    ));
    let _ = fs::remove_dir_all(&dir);
    fs::create_dir_all(&dir).unwrap();
    dir
  }

  fn write(
    path: &Path,
    contents: &str,
  ) {
    if let Some(parent) = path.parent() {
      fs::create_dir_all(parent).unwrap();
    }
    let mut file = fs::File::create(path).unwrap();
    file.write_all(contents.as_bytes()).unwrap();
  }

  #[test]
  fn finds_nearest_tsconfig_walking_up() {
    let dir = temp_dir("nearest");
    let nested = dir.join("a/b/c");
    fs::create_dir_all(&nested).unwrap();

    write(&dir.join("tsconfig.json"), r#"{ "compilerOptions": {} }"#);
    write(
      &dir.join("a/tsconfig.json"),
      r#"{ "compilerOptions": { "jsx": "react" } }"#,
    );

    let file = nested.join("main.tsx");
    write(&file, "export const a = 1;");

    let found = find_nearest_tsconfig(&file, &dir).unwrap();
    assert_eq!(found, dir.join("a/tsconfig.json"));

    let config = load_tsconfig(&found).unwrap();
    assert_eq!(config.jsx, Some(JsxMode::React));
  }

  #[test]
  fn finds_nearest_deno_json_walking_up() {
    let dir = temp_dir("deno-nearest");
    let nested = dir.join("a/b/c");
    fs::create_dir_all(&nested).unwrap();

    write(
      &dir.join("a/deno.json"),
      r#"{
        "compilerOptions": {
          "strict": true,
          "lib": ["dom", "dom.iterable", "esnext"],
          "jsx": "react",
          "jsxFactory": "h",
          "jsxFragmentFactory": "Fragment"
        },
        "imports": {
          "preact": "https://esm.sh/preact@11"
        }
      }"#,
    );

    let file = nested.join("main.tsx");
    write(&file, "export const a = 1;");

    let found = find_nearest_tsconfig(&file, &dir).unwrap();
    assert_eq!(found, dir.join("a/deno.json"));

    let config = load_tsconfig(&found).unwrap();
    assert_eq!(config.jsx, Some(JsxMode::React));
    assert_eq!(config.jsx_factory.as_deref(), Some("h"));
    assert_eq!(config.jsx_fragment_factory.as_deref(), Some("Fragment"));
  }

  #[test]
  fn prefers_deno_json_over_tsconfig_in_same_dir() {
    let dir = temp_dir("deno-priority");
    write(
      &dir.join("tsconfig.json"),
      r#"{ "compilerOptions": { "jsx": "react-jsx" } }"#,
    );
    write(
      &dir.join("deno.json"),
      r#"{ "compilerOptions": { "jsx": "react", "jsxFactory": "h" } }"#,
    );

    let file = dir.join("main.tsx");
    write(&file, "export const a = 1;");

    let found = find_nearest_tsconfig(&file, &dir).unwrap();
    assert_eq!(found, dir.join("deno.json"));
    assert_eq!(load_tsconfig(&found).unwrap().jsx, Some(JsxMode::React));
  }

  #[test]
  fn nearer_dir_wins_over_deno_json_priority() {
    let dir = temp_dir("deno-distance");
    let nested = dir.join("app");
    fs::create_dir_all(&nested).unwrap();

    write(
      &dir.join("deno.json"),
      r#"{ "compilerOptions": { "jsx": "react" } }"#,
    );
    write(
      &nested.join("tsconfig.json"),
      r#"{ "compilerOptions": { "jsx": "react-jsx" } }"#,
    );

    let file = nested.join("main.tsx");
    write(&file, "export const a = 1;");

    let found = find_nearest_tsconfig(&file, &dir).unwrap();
    assert_eq!(found, nested.join("tsconfig.json"));
    assert_eq!(load_tsconfig(&found).unwrap().jsx, Some(JsxMode::ReactJsx));
  }

  #[test]
  fn resolves_deno_json_extends_chain() {
    let dir = temp_dir("deno-extends");
    write(
      &dir.join("deno.base.json"),
      r#"{ "compilerOptions": { "jsx": "react" } }"#,
    );
    write(
      &dir.join("deno.json"),
      r#"{ "extends": "./deno.base.json", "compilerOptions": { "jsxFactory": "h" } }"#,
    );

    let config = load_tsconfig(&dir.join("deno.json")).unwrap();
    assert_eq!(config.jsx, Some(JsxMode::React));
    assert_eq!(config.jsx_factory.as_deref(), Some("h"));
  }

  #[test]
  fn cache_switches_to_deno_json_when_it_appears() {
    let dir = temp_dir("deno-cache");
    write(
      &dir.join("tsconfig.json"),
      r#"{ "compilerOptions": { "jsx": "react-jsx" } }"#,
    );

    let file = dir.join("main.tsx");
    write(&file, "export const a = 1;");

    let cache = TsConfigCache::new();
    assert_eq!(cache.resolve(&file, &dir).jsx, Some(JsxMode::ReactJsx));

    write(
      &dir.join("deno.json"),
      r#"{ "compilerOptions": { "jsx": "react" } }"#,
    );
    assert_eq!(cache.resolve(&file, &dir).jsx, Some(JsxMode::React));

    write(
      &dir.join("deno.json"),
      r#"{ "compilerOptions": { "jsx": "react-jsx" } }"#,
    );
    assert_eq!(cache.resolve(&file, &dir).jsx, Some(JsxMode::ReactJsx));
  }

  #[test]
  fn stops_at_serve_dir_boundary() {
    let dir = temp_dir("boundary");
    let serve = dir.join("serve");
    fs::create_dir_all(&serve).unwrap();

    // tsconfig lives *above* the served directory and must be ignored
    write(
      &dir.join("tsconfig.json"),
      r#"{ "compilerOptions": { "jsx": "react" } }"#,
    );

    let file = serve.join("main.tsx");
    write(&file, "export const a = 1;");

    assert_eq!(find_nearest_tsconfig(&file, &serve), None);

    let cache = TsConfigCache::new();
    assert_eq!(cache.resolve(&file, &serve).jsx, None);
  }

  #[test]
  fn resolves_extends_chain() {
    let dir = temp_dir("extends");
    write(
      &dir.join("tsconfig.base.json"),
      r#"{ "compilerOptions": { "jsx": "react" } }"#,
    );
    write(
      &dir.join("tsconfig.json"),
      r#"{ "extends": "./tsconfig.base.json", "compilerOptions": {} }"#,
    );

    let config = load_tsconfig(&dir.join("tsconfig.json")).unwrap();
    assert_eq!(config.jsx, Some(JsxMode::React));
  }

  #[test]
  fn child_options_override_extends() {
    let dir = temp_dir("override");
    write(
      &dir.join("tsconfig.base.json"),
      r#"{ "compilerOptions": { "jsx": "react" } }"#,
    );
    write(
      &dir.join("tsconfig.json"),
      r#"{ "extends": "./tsconfig.base.json", "compilerOptions": { "jsx": "react-jsx" } }"#,
    );

    let config = load_tsconfig(&dir.join("tsconfig.json")).unwrap();
    assert_eq!(config.jsx, Some(JsxMode::ReactJsx));
  }

  #[test]
  fn malformed_json_is_ignored() {
    let dir = temp_dir("malformed");
    write(&dir.join("tsconfig.json"), "{ not valid json");

    assert!(load_tsconfig(&dir.join("tsconfig.json")).is_none());
  }

  #[test]
  fn parses_factory_options_and_ignores_unrelated_options() {
    let dir = temp_dir("factory");

    // Mirrors the shape of testing/transpile/preact-tsconfig/tsconfig.json,
    // which contains many options the server does not care about.
    write(
      &dir.join("tsconfig.json"),
      r#"{
        "compilerOptions": {
          "strict": true,
          "module": "nodenext",
          "moduleResolution": "nodenext",
          "lib": ["DOM", "ESNext"],
          "types": [],
          "jsx": "react",
          "jsxFactory": "h",
          "allowImportingTsExtensions": true,
          "noEmit": true
        }
      }"#,
    );

    let config = load_tsconfig(&dir.join("tsconfig.json")).unwrap();
    assert_eq!(config.jsx, Some(JsxMode::React));
    assert_eq!(config.jsx_factory.as_deref(), Some("h"));
    assert_eq!(config.jsx_fragment_factory, None);
    assert_eq!(config.jsx_import_source, None);
  }

  #[test]
  fn cache_invalidates_on_change() {
    let dir = temp_dir("cache");
    let config_path = dir.join("tsconfig.json");
    write(&config_path, r#"{ "compilerOptions": { "jsx": "react" } }"#);

    let file = dir.join("main.tsx");
    write(&file, "export const a = 1;");

    let cache = TsConfigCache::new();
    assert_eq!(cache.resolve(&file, &dir).jsx, Some(JsxMode::React));

    write(
      &config_path,
      r#"{ "compilerOptions": { "jsx": "react-jsx" } }"#,
    );
    assert_eq!(cache.resolve(&file, &dir).jsx, Some(JsxMode::ReactJsx));
  }
}