diff options
author | David Sherret <dsherret@users.noreply.github.com> | 2024-10-14 20:48:39 -0400 |
---|---|---|
committer | GitHub <noreply@github.com> | 2024-10-14 20:48:39 -0400 |
commit | 1a0cb5b5312941521ab021cfe9eaed498f35900b (patch) | |
tree | 2e5c58e25e8506b993ac678e83ba0c2feac37d75 /cli/util | |
parent | ee7d4501435f0ebd655c8b50bd6e41ca19e71abc (diff) |
feat(unstable): `--unstable-detect-cjs` for respecting explicit `"type": "commonjs"` (#26149)
When using the `--unstable-detect-cjs` flag or adding `"unstable":
["detect-cjs"]` to a deno.json, it will make a JS file CJS if the
closest package.json contains `"type": "commonjs"` and the file is not
an ESM module (no TLA, no `import.meta`, no `import`/`export`).
Diffstat (limited to 'cli/util')
-rw-r--r-- | cli/util/text_encoding.rs | 18 |
1 files changed, 18 insertions, 0 deletions
diff --git a/cli/util/text_encoding.rs b/cli/util/text_encoding.rs index d2e0832c9..0b7601cb9 100644 --- a/cli/util/text_encoding.rs +++ b/cli/util/text_encoding.rs @@ -1,6 +1,8 @@ // Copyright 2018-2024 the Deno authors. All rights reserved. MIT license. +use std::borrow::Cow; use std::ops::Range; +use std::sync::Arc; use base64::prelude::BASE64_STANDARD; use base64::Engine; @@ -9,6 +11,15 @@ use deno_core::ModuleSourceCode; static SOURCE_MAP_PREFIX: &[u8] = b"//# sourceMappingURL=data:application/json;base64,"; +pub fn from_utf8_lossy_owned(bytes: Vec<u8>) -> String { + match String::from_utf8_lossy(&bytes) { + Cow::Owned(code) => code, + // SAFETY: `String::from_utf8_lossy` guarantees that the result is valid + // UTF-8 if `Cow::Borrowed` is returned. + Cow::Borrowed(_) => unsafe { String::from_utf8_unchecked(bytes) }, + } +} + pub fn source_map_from_code(code: &[u8]) -> Option<Vec<u8>> { let range = find_source_map_range(code)?; let source_map_range = &code[range]; @@ -85,6 +96,13 @@ fn find_source_map_range(code: &[u8]) -> Option<Range<usize>> { } } +/// Converts an `Arc<str>` to an `Arc<[u8]>`. +pub fn arc_str_to_bytes(arc_str: Arc<str>) -> Arc<[u8]> { + let raw = Arc::into_raw(arc_str); + // SAFETY: This is safe because they have the same memory layout. + unsafe { Arc::from_raw(raw as *const [u8]) } +} + #[cfg(test)] mod tests { use std::sync::Arc; |