Skip to content

Commit

Permalink
fix: remove dntGlobalThisType and try to inline globalThis.X shim…
Browse files Browse the repository at this point in the history
… types directly instead (#97)
  • Loading branch information
dsherret authored Jan 12, 2022
1 parent 56c9862 commit 05fa937
Show file tree
Hide file tree
Showing 7 changed files with 80 additions and 115 deletions.
17 changes: 14 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -190,6 +190,7 @@ Set any of these properties to `true` (distribution and test) or `"dev"` (test o
- `crypto` - Shim the `crypto` global.
- `domException` - Shim the `DOMException` global using the "domexception" package (https://www.npmjs.com/package/domexception)
- `undici` - Shim `fetch`, `File`, `FormData`, `Headers`, `Request`, and `Response` by using the "undici" package (https://www.npmjs.com/package/undici).
- `weakRef` - Sham for the `WeakRef` global, which uses `globalThis.WeakRef` when it exists. The sham will throw at runtime when calling `deref()` and `WeakRef` doesn't globally exist, so this is only intended to help type check code that won't actually use it.

##### `Deno.test`-only shim

Expand Down Expand Up @@ -232,14 +233,17 @@ await build({
exportName: "default",
}, {
name: "RequestInit",
typeOnly: true, // only used in type declarations
kind: "typeOnly", // only used in type declarations
}],
}, {
// this is what `blob: true` does internally
package: {
name: "buffer", // uses node's "buffer" module
},
globalNames: ["Blob"],
globalNames: [{
name: "Blob",
kind: "class",
}],
}, {
// this is what `domException: true` does internally
package: {
Expand All @@ -252,6 +256,7 @@ await build({
},
globalNames: [{
name: "DOMException",
kind: "class",
exportName: "default",
}],
}],
Expand All @@ -262,7 +267,13 @@ await build({
name: "@deno/shim-timers",
version: "~0.1.0",
},
globalNames: ["setTimeout", "setInterval"],
globalNames: [{
name: "setTimeout",
kind: "value",
}, {
name: "setInterval",
kind: "value",
}],
}],
},
});
Expand Down
2 changes: 1 addition & 1 deletion lib/pkg/dnt_wasm_bg.ts

Large diffs are not rendered by default.

10 changes: 7 additions & 3 deletions lib/shims.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,9 +37,9 @@ export interface ShimOptions {
* using the "undici" package (https://www.npmjs.com/package/undici).
*/
undici?: ShimValue;
/** Use a sham for the `WeakRef` global, which uses `globalThis.WeakRef`
* when it exists. The sham will throw at runtime when `WeakRef` doesn't
* globally exist, so this is only intended to help type check code that
/** Use a sham for the `WeakRef` global, which uses `globalThis.WeakRef` when
* it exists. The sham will throw at runtime when calling `deref()` and `WeakRef`
* doesn't globally exist, so this is only intended to help type check code that
* won't actually use it.
*/
weakRef?: ShimValue;
Expand Down Expand Up @@ -205,6 +205,10 @@ function getUndiciShim(): Shim {
"Headers",
"Request",
"Response",
typeOnly("BodyInit"),
typeOnly("HeadersInit"),
typeOnly("RequestInit"),
typeOnly("ResponseInit"),
],
};
}
Expand Down
15 changes: 6 additions & 9 deletions rs-lib/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -474,7 +474,11 @@ fn check_add_shim_file_to_environment(

let mut text = String::new();
for shim in shims.iter() {
let declaration_names = shim.global_names.iter().collect::<Vec<_>>();
let declaration_names = shim
.global_names
.iter()
.filter(|n| !n.type_only)
.collect::<Vec<_>>();
if !declaration_names.is_empty() {
text.push_str(&format!(
"import {{ {} }} from \"{}\";\n",
Expand Down Expand Up @@ -510,14 +514,7 @@ fn check_add_shim_file_to_environment(
}
}
text.push_str("};\n");
text.push_str("export const dntGlobalThis = createMergeProxy(globalThis, dntGlobals);\n");
text.push_str("export type dntGlobalThisType = Omit<typeof dntGlobals, keyof typeof dntGlobals> & typeof dntGlobals & {\n");
for global_name in shims.iter().map(|s| s.global_names.iter()).flatten() {
if global_name.type_only {
text.push_str(&format!(" {0}: {0},\n", global_name.name));
}
}
text.push_str("};\n");
text.push_str("export const dntGlobalThis = createMergeProxy(globalThis, dntGlobals);\n\n");

text.push_str(
&include_str!("scripts/createMergeProxy.ts")
Expand Down
92 changes: 43 additions & 49 deletions rs-lib/src/visitors/globals.rs
Original file line number Diff line number Diff line change
Expand Up @@ -84,35 +84,32 @@ fn visit_children(node: Node, import_name: &str, context: &mut Context) {
let ident_text = ident.text_fast(context.program);

if is_top_level_context {
// check to replace globalThis
if ident_text == "globalThis"
&& !should_ignore_global_this(ident, context)
{
context.text_changes.push(get_global_this_text_change(
ident,
import_name,
context,
));
context.import_shim = true;
// change `window` -> `globalThis`
if ident_text == "window" {
if !context.top_level_decls.contains("window")
&& !has_ignore_comment(ident.into(), context)
{
if let Some(text_change) =
get_global_this_text_change(ident, import_name, context)
{
context.text_changes.push(text_change);
context.import_shim = true;
} else {
context.text_changes.push(TextChange {
span: ident.span(),
new_text: "globalThis".to_string(),
});
}
}
return;
}

// change `window` -> `globalThis`
if ident_text == "window"
&& !context.top_level_decls.contains("window")
&& !has_ignore_comment(ident.into(), context)
{
if should_ignore_global_this(ident, context) {
context.text_changes.push(TextChange {
span: ident.span(),
new_text: "globalThis".to_string(),
});
} else {
context.text_changes.push(get_global_this_text_change(
ident,
import_name,
context,
));
// check to replace globalThis
if ident_text == "globalThis" {
if let Some(text_change) =
get_global_this_text_change(ident, import_name, context)
{
context.text_changes.push(text_change);
context.import_shim = true;
}
return;
Expand Down Expand Up @@ -140,38 +137,35 @@ fn get_global_this_text_change(
ident: &Ident,
import_name: &str,
context: &Context,
) -> TextChange {
) -> Option<TextChange> {
if should_ignore_global_this(ident, context) {
return None;
}
if is_in_type(ident.into()) {
match ident.parent() {
Node::TsQualifiedName(parent) => {
let replace_span = match parent.parent() {
Node::TsTypeQuery(query) => query.span(), // remove the "typeof"
_ => parent.span(),
};
TextChange {
span: replace_span,
new_text: format!(
"{}.dntGlobalThisType[\"{}\"]",
import_name.to_string(),
// doesn't seem exactly right... will wait for a bug to open
parent.right.text_fast(context.program),
),
let right_name = parent.right.text_fast(context.program);
if context.shim_global_names.contains(&right_name) {
Some(TextChange {
span: parent.span(),
new_text: format!(
"{}.{}",
import_name.to_string(),
// doesn't seem exactly right... will wait for a bug to open
parent.right.text_fast(context.program),
),
})
} else {
None
}
}
Node::TsTypeQuery(_) => TextChange {
span: ident.span(),
new_text: format!("{}.dntGlobalThis", import_name.to_string()),
},
_ => TextChange {
span: ident.span(),
new_text: format!("{}.dntGlobalThisType", import_name.to_string()),
},
_ => None,
}
} else {
TextChange {
Some(TextChange {
span: ident.span(),
new_text: format!("{}.dntGlobalThis", import_name.to_string()),
}
})
}
}

Expand Down
17 changes: 7 additions & 10 deletions rs-lib/tests/integration_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -178,9 +178,8 @@ async fn transform_shim_custom_shims() {
"export { fetchTestName as fetchTest } from \"node-fetch/test\";\n",
"import { default as DOMException } from \"domexception\";\n",
"export { default as DOMException } from \"domexception\";\n",
"import { Blob, type Other } from \"buffer\";\n",
"import { Blob } from \"buffer\";\n",
"export { Blob, type Other } from \"buffer\";\n",
"import { type TypeOnly } from \"type-only\";\n",
"export { type TypeOnly } from \"type-only\";\n",
"\n",
"const dntGlobals = {\n",
Expand All @@ -190,10 +189,6 @@ async fn transform_shim_custom_shims() {
" Blob,\n",
"};\n",
"export const dntGlobalThis = createMergeProxy(globalThis, dntGlobals);\n",
"export type dntGlobalThisType = Omit<typeof dntGlobals, keyof typeof dntGlobals> & typeof dntGlobals & {\n",
" Other: Other,\n",
" TypeOnly: TypeOnly,\n",
"};"
).to_string(),
),
),
Expand Down Expand Up @@ -272,6 +267,8 @@ async fn transform_global_this_shim() {
"globalThis ? true : false;",
"type Test1 = typeof globalThis;",
"type Test2 = typeof globalThis.Window;",
"type Test3 = typeof globalThis.Deno;",
"type Test4 = window.Something;",
),
concat!(
r#"import * as dntShim from "./_dnt.shims.js";"#,
Expand All @@ -287,8 +284,10 @@ async fn transform_global_this_shim() {
"typeof dntShim.dntGlobalThis;",
"dntShim.dntGlobalThis == null;",
"dntShim.dntGlobalThis ? true : false;",
"type Test1 = typeof dntShim.dntGlobalThis;",
"type Test2 = dntShim.dntGlobalThisType[\"Window\"];",
"type Test1 = typeof globalThis;",
"type Test2 = typeof globalThis.Window;",
"type Test3 = typeof dntShim.Deno;",
"type Test4 = globalThis.Something;",
),
)])
.await;
Expand Down Expand Up @@ -1203,8 +1202,6 @@ async fn test_entry_points() {
" setInterval,\n",
"};\n",
"export const dntGlobalThis = createMergeProxy(globalThis, dntGlobals);\n",
"export type dntGlobalThisType = Omit<typeof dntGlobals, keyof typeof dntGlobals> & typeof dntGlobals & {\n",
"};"
)
.to_string(),
),
Expand Down
42 changes: 2 additions & 40 deletions tests/integration.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -453,7 +453,7 @@ Deno.test("should build shim project when using node-fetch", async () => {
export { Deno } from "@deno/shim-deno";
import { Blob } from "buffer";
export { Blob } from "buffer";
import { crypto, type Crypto, type SubtleCrypto, type AlgorithmIdentifier, type Algorithm, type RsaOaepParams, type BufferSource, type AesCtrParams, type AesCbcParams, type AesGcmParams, type CryptoKey, type KeyAlgorithm, type KeyType, type KeyUsage, type EcdhKeyDeriveParams, type HkdfParams, type HashAlgorithmIdentifier, type Pbkdf2Params, type AesDerivedKeyParams, type HmacImportParams, type JsonWebKey, type RsaOtherPrimesInfo, type KeyFormat, type RsaHashedKeyGenParams, type RsaKeyGenParams, type BigInteger, type EcKeyGenParams, type NamedCurve, type CryptoKeyPair, type AesKeyGenParams, type HmacKeyGenParams, type RsaHashedImportParams, type EcKeyImportParams, type AesKeyAlgorithm, type RsaPssParams, type EcdsaParams } from "@deno/shim-crypto";
import { crypto } from "@deno/shim-crypto";
export { crypto, type Crypto, type SubtleCrypto, type AlgorithmIdentifier, type Algorithm, type RsaOaepParams, type BufferSource, type AesCtrParams, type AesCbcParams, type AesGcmParams, type CryptoKey, type KeyAlgorithm, type KeyType, type KeyUsage, type EcdhKeyDeriveParams, type HkdfParams, type HashAlgorithmIdentifier, type Pbkdf2Params, type AesDerivedKeyParams, type HmacImportParams, type JsonWebKey, type RsaOtherPrimesInfo, type KeyFormat, type RsaHashedKeyGenParams, type RsaKeyGenParams, type BigInteger, type EcKeyGenParams, type NamedCurve, type CryptoKeyPair, type AesKeyGenParams, type HmacKeyGenParams, type RsaHashedImportParams, type EcKeyImportParams, type AesKeyAlgorithm, type RsaPssParams, type EcdsaParams } from "@deno/shim-crypto";
import { alert, confirm, prompt } from "@deno/shim-prompts";
export { alert, confirm, prompt } from "@deno/shim-prompts";
Expand All @@ -463,7 +463,7 @@ import { default as DOMException } from "domexception";
export { default as DOMException } from "domexception";
import { File, FormData, Headers, Request, Response } from "undici";
export { File, FormData, Headers, Request, Response } from "undici";
import { default as fetch, type RequestInit } from "node-fetch";
import { default as fetch } from "node-fetch";
export { default as fetch, type RequestInit } from "node-fetch";
const dntGlobals = {
Expand All @@ -484,44 +484,6 @@ const dntGlobals = {
fetch,
};
export const dntGlobalThis = createMergeProxy(globalThis, dntGlobals);
export type dntGlobalThisType = Omit<typeof dntGlobals, keyof typeof dntGlobals> & typeof dntGlobals & {
Crypto: Crypto,
SubtleCrypto: SubtleCrypto,
AlgorithmIdentifier: AlgorithmIdentifier,
Algorithm: Algorithm,
RsaOaepParams: RsaOaepParams,
BufferSource: BufferSource,
AesCtrParams: AesCtrParams,
AesCbcParams: AesCbcParams,
AesGcmParams: AesGcmParams,
CryptoKey: CryptoKey,
KeyAlgorithm: KeyAlgorithm,
KeyType: KeyType,
KeyUsage: KeyUsage,
EcdhKeyDeriveParams: EcdhKeyDeriveParams,
HkdfParams: HkdfParams,
HashAlgorithmIdentifier: HashAlgorithmIdentifier,
Pbkdf2Params: Pbkdf2Params,
AesDerivedKeyParams: AesDerivedKeyParams,
HmacImportParams: HmacImportParams,
JsonWebKey: JsonWebKey,
RsaOtherPrimesInfo: RsaOtherPrimesInfo,
KeyFormat: KeyFormat,
RsaHashedKeyGenParams: RsaHashedKeyGenParams,
RsaKeyGenParams: RsaKeyGenParams,
BigInteger: BigInteger,
EcKeyGenParams: EcKeyGenParams,
NamedCurve: NamedCurve,
CryptoKeyPair: CryptoKeyPair,
AesKeyGenParams: AesKeyGenParams,
HmacKeyGenParams: HmacKeyGenParams,
RsaHashedImportParams: RsaHashedImportParams,
EcKeyImportParams: EcKeyImportParams,
AesKeyAlgorithm: AesKeyAlgorithm,
RsaPssParams: RsaPssParams,
EcdsaParams: EcdsaParams,
RequestInit: RequestInit,
};
`;
assertEquals(
output.getFileText("src/_dnt.shims.ts").substring(0, expectedText.length),
Expand Down

0 comments on commit 05fa937

Please sign in to comment.