From e0c456d159b8b53ddbfdf51ddca58630386ddc37 Mon Sep 17 00:00:00 2001 From: stuyk Date: Tue, 30 Jan 2024 18:55:52 -0700 Subject: [PATCH 1/7] feat: add dynamic window pathing, adjust tests, add prettier, cleanup tsconfig --- .prettierrc | 7 +++ package.json | 7 ++- src/extension/index.ts | 20 ++++++ src/extension/proxyBindings.ts | 11 ++++ src/index.test.ts | 21 +++++++ tsconfig.json | 108 ++++----------------------------- 6 files changed, 76 insertions(+), 98 deletions(-) create mode 100644 .prettierrc create mode 100644 src/extension/index.ts create mode 100644 src/extension/proxyBindings.ts create mode 100644 src/index.test.ts diff --git a/.prettierrc b/.prettierrc new file mode 100644 index 0000000..b4823c6 --- /dev/null +++ b/.prettierrc @@ -0,0 +1,7 @@ +{ + "tabWidth": 2, + "singleQuote": false, + "trailingComma": "all", + "printWidth": 120, + "bracketSpacing": true +} diff --git a/package.json b/package.json index 2002dd1..95f2649 100644 --- a/package.json +++ b/package.json @@ -11,8 +11,8 @@ "build": "tsc", "coverage": "vitest run --coverage", "dev": "vitest", - "lint": "eslint -c .eslintrc.js './src/**/*.ts' --ignore-path .gitignore", - "lint:fix": "eslint -c .eslintrc.js './src/**/*.ts' --fix --ignore-path .gitignore", + "lint": "eslint -c .eslintrc.js \"./src/**/*.ts\" --ignore-path .gitignore", + "lint:fix": "eslint -c .eslintrc.js \"./src/**/*.ts\" --fix --ignore-path .gitignore", "test": "vitest run" }, "keywords": [], @@ -28,5 +28,8 @@ "prettier": "^3.2.4", "typescript": "^5.3.3", "vitest": "^1.2.2" + }, + "prettier": { + "tabWidth": 2 } } diff --git a/src/extension/index.ts b/src/extension/index.ts new file mode 100644 index 0000000..b5d7c8b --- /dev/null +++ b/src/extension/index.ts @@ -0,0 +1,20 @@ +import * as ProxyBindings from "./proxyBindings"; + +export type ProxyAPI = typeof ProxyBindings; + +/** + * Initialize the window instance with bindings to proxy API functions + * + * @export + * @param { ProxyAPI } globalOrWindow + */ +export function bindToWindow( + globalOrWindow: typeof globalThis | Window, + name: string, +) { + const instance = globalOrWindow as (typeof globalThis | Window) & { + [key in typeof name]: ProxyAPI; + }; + + instance[name] = ProxyBindings; +} diff --git a/src/extension/proxyBindings.ts b/src/extension/proxyBindings.ts new file mode 100644 index 0000000..da5c24a --- /dev/null +++ b/src/extension/proxyBindings.ts @@ -0,0 +1,11 @@ +export function test1() { + console.log("hello world!"); +} + +export function test2() { + console.log("hello world!"); +} + +export function test3() { + console.log("hello world!"); +} diff --git a/src/index.test.ts b/src/index.test.ts new file mode 100644 index 0000000..7d714c9 --- /dev/null +++ b/src/index.test.ts @@ -0,0 +1,21 @@ +import { ProxyAPI, bindToWindow } from "./extension"; +import { expect, test } from "vitest"; + +declare global { + var wallet: ProxyAPI; +} + +test("test binding to 'window' or 'global' variables", () => { + const target = typeof window !== "undefined" ? window : global; + + expect(typeof target).not.toBe("undefined"); + expect(Object.hasOwn(target, "wallet")).toBe(false); + + bindToWindow(target, "wallet"); + + expect(typeof target.wallet).not.toBe("undefined"); + + expect(typeof target.wallet?.test1).toBe("function"); + expect(typeof target.wallet?.test2).toBe("function"); + expect(typeof target.wallet?.test3).toBe("function"); +}); diff --git a/tsconfig.json b/tsconfig.json index 8b1d1ac..a1b0013 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -6,101 +6,17 @@ "node_modules" ], "compilerOptions": { - /* Visit https://aka.ms/tsconfig.json to read more about this file */ - - /* Projects */ - // "incremental": true, /* Enable incremental compilation */ - // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */ - // "tsBuildInfoFile": "./", /* Specify the folder for .tsbuildinfo incremental compilation files. */ - // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects */ - // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */ - // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */ - - /* Language and Environment */ - "target": "esnext", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */ - // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */ - // "jsx": "preserve", /* Specify what JSX code is generated. */ - // "experimentalDecorators": true, /* Enable experimental support for TC39 stage 2 draft decorators. */ - // "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */ - // "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h' */ - // "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */ - // "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using `jsx: react-jsx*`.` */ - // "reactNamespace": "", /* Specify the object invoked for `createElement`. This only applies when targeting `react` JSX emit. */ - // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */ - // "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */ - - /* Modules */ - "module": "commonjs", /* Specify what module code is generated. */ - "rootDir": "./src/", /* Specify the root folder within your source files. */ - // "moduleResolution": "node", /* Specify how TypeScript looks up a file from a given module specifier. */ - // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */ - // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */ - // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */ - // "typeRoots": [], /* Specify multiple folders that act like `./node_modules/@types`. */ - // "types": [], /* Specify type package names to be included without being referenced in a source file. */ - // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ - // "resolveJsonModule": true, /* Enable importing .json files */ - // "noResolve": true, /* Disallow `import`s, `require`s or ``s from expanding the number of files TypeScript should add to a project. */ - - /* JavaScript Support */ - // "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the `checkJS` option to get errors from these files. */ - // "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */ - // "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from `node_modules`. Only applicable with `allowJs`. */ - - /* Emit */ - "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */ - "declarationMap": true, /* Create sourcemaps for d.ts files. */ - "emitDeclarationOnly": false, /* Only output d.ts files and not JavaScript files. */ - // "sourceMap": true, /* Create source map files for emitted JavaScript files. */ - //"outFile": "./lib/index", /* Specify a file that bundles all outputs into one JavaScript file. If `declaration` is true, also designates a file that bundles all .d.ts output. */ - "outDir": "./lib/", /* Specify an output folder for all emitted files. */ - // "removeComments": true, /* Disable emitting comments. */ - // "noEmit": true, /* Disable emitting files from a compilation. */ - // "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */ - // "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types */ - // "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */ - // "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */ - // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ - // "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */ - // "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */ - // "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */ - // "newLine": "crlf", /* Set the newline character for emitting files. */ - // "stripInternal": true, /* Disable emitting declarations that have `@internal` in their JSDoc comments. */ - // "noEmitHelpers": true, /* Disable generating custom helper functions like `__extends` in compiled output. */ - // "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */ - // "preserveConstEnums": true, /* Disable erasing `const enum` declarations in generated code. */ - // "declarationDir": "./", /* Specify the output directory for generated declaration files. */ - - /* Interop Constraints */ - // "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */ - // "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */ - "esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables `allowSyntheticDefaultImports` for type compatibility. */ - // "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */ - "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */ - - /* Type Checking */ - "strict": true, /* Enable all strict type-checking options. */ - // "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied `any` type.. */ - // "strictNullChecks": true, /* When type checking, take into account `null` and `undefined`. */ - // "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */ - // "strictBindCallApply": true, /* Check that the arguments for `bind`, `call`, and `apply` methods match the original function. */ - // "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */ - // "noImplicitThis": true, /* Enable error reporting when `this` is given the type `any`. */ - // "useUnknownInCatchVariables": true, /* Type catch clause variables as 'unknown' instead of 'any'. */ - // "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */ - // "noUnusedLocals": true, /* Enable error reporting when a local variables aren't read. */ - // "noUnusedParameters": true, /* Raise an error when a function parameter isn't read */ - // "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */ - // "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */ - // "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */ - // "noUncheckedIndexedAccess": true, /* Include 'undefined' in index signature results */ - // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */ - // "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type */ - // "allowUnusedLabels": true, /* Disable error reporting for unused labels. */ - // "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */ - - /* Completeness */ - // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */ - "skipLibCheck": true /* Skip type checking all .d.ts files. */ + "target": "esnext", + "module": "commonjs", + "rootDir": "./src/", + "declaration": true, + "declarationMap": true, + "emitDeclarationOnly": false, + "outDir": "./lib/", + "esModuleInterop": true, + "forceConsistentCasingInFileNames": true, + "strict": true, + "noImplicitAny": true, + "skipLibCheck": true } } \ No newline at end of file From e01dc59cfd55ae1aa6b11a8dad1d62213751c30a Mon Sep 17 00:00:00 2001 From: stuyk Date: Tue, 30 Jan 2024 19:07:17 -0700 Subject: [PATCH 2/7] fix: adjust eslint rule for single var --- .eslintrc.js | 1 + 1 file changed, 1 insertion(+) diff --git a/.eslintrc.js b/.eslintrc.js index b42f42f..f6f5c0c 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -11,6 +11,7 @@ module.exports = { rules: { "prettier/prettier": "error", "no-unused-vars": "off", + "no-var": "off", "@typescript-eslint/no-unused-vars": [ "error", // or "error" { From 5a53e7447d8aa74068a93977f6337e14cd8be4ae Mon Sep 17 00:00:00 2001 From: stuyk Date: Wed, 31 Jan 2024 08:23:53 -0700 Subject: [PATCH 3/7] feat: allow binding any object to globalThis variable --- .eslintrc.js | 12 +++++++-- .prettierrc | 7 ------ package.json | 3 --- src/binder/index.ts | 45 ++++++++++++++++++++++++++++++++++ src/extension/index.ts | 20 --------------- src/extension/proxyBindings.ts | 11 --------- src/index.test.ts | 26 ++++++++++++++------ 7 files changed, 73 insertions(+), 51 deletions(-) delete mode 100644 .prettierrc create mode 100644 src/binder/index.ts delete mode 100644 src/extension/index.ts delete mode 100644 src/extension/proxyBindings.ts diff --git a/.eslintrc.js b/.eslintrc.js index f6f5c0c..7a5843c 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -9,9 +9,17 @@ module.exports = { plugins: ["@typescript-eslint", "prettier"], root: true, rules: { - "prettier/prettier": "error", + "prettier/prettier": [ + "error", + { + tabWidth: 2, + singleQuote: false, + trailingComma: "all", + printWidth: 120, + bracketSpacing: true, + }, + ], "no-unused-vars": "off", - "no-var": "off", "@typescript-eslint/no-unused-vars": [ "error", // or "error" { diff --git a/.prettierrc b/.prettierrc deleted file mode 100644 index b4823c6..0000000 --- a/.prettierrc +++ /dev/null @@ -1,7 +0,0 @@ -{ - "tabWidth": 2, - "singleQuote": false, - "trailingComma": "all", - "printWidth": 120, - "bracketSpacing": true -} diff --git a/package.json b/package.json index 95f2649..6ec5b7a 100644 --- a/package.json +++ b/package.json @@ -28,8 +28,5 @@ "prettier": "^3.2.4", "typescript": "^5.3.3", "vitest": "^1.2.2" - }, - "prettier": { - "tabWidth": 2 } } diff --git a/src/binder/index.ts b/src/binder/index.ts new file mode 100644 index 0000000..4d1cbab --- /dev/null +++ b/src/binder/index.ts @@ -0,0 +1,45 @@ +/** + * Safely binds functions to globalThis + * + * @example + * ```ts + * type bindings = { test: Function }; + * + * set("wallet", bindings); + * ``` + * + * @export + * @template T + * @param {string} name + * @param {T} bindings + */ +export function set(name: string, bindings: T) { + ( + globalThis as typeof globalThis & { + [key in typeof name]: T; + } + )[name] = bindings; +} + +/** + * Returns bindings assigned to globalThis + * + * @example + * ``` + * type bindings = { test: Function }; + * + * const wallet = get("wallet"); + * ``` + * + * @export + * @template T + * @param {string} name + * @return {T} + */ +export function get(name: string): T { + return ( + globalThis as typeof globalThis & { + [key in typeof name]: T; + } + )[name]; +} diff --git a/src/extension/index.ts b/src/extension/index.ts deleted file mode 100644 index b5d7c8b..0000000 --- a/src/extension/index.ts +++ /dev/null @@ -1,20 +0,0 @@ -import * as ProxyBindings from "./proxyBindings"; - -export type ProxyAPI = typeof ProxyBindings; - -/** - * Initialize the window instance with bindings to proxy API functions - * - * @export - * @param { ProxyAPI } globalOrWindow - */ -export function bindToWindow( - globalOrWindow: typeof globalThis | Window, - name: string, -) { - const instance = globalOrWindow as (typeof globalThis | Window) & { - [key in typeof name]: ProxyAPI; - }; - - instance[name] = ProxyBindings; -} diff --git a/src/extension/proxyBindings.ts b/src/extension/proxyBindings.ts deleted file mode 100644 index da5c24a..0000000 --- a/src/extension/proxyBindings.ts +++ /dev/null @@ -1,11 +0,0 @@ -export function test1() { - console.log("hello world!"); -} - -export function test2() { - console.log("hello world!"); -} - -export function test3() { - console.log("hello world!"); -} diff --git a/src/index.test.ts b/src/index.test.ts index 7d714c9..3a9348d 100644 --- a/src/index.test.ts +++ b/src/index.test.ts @@ -1,21 +1,31 @@ -import { ProxyAPI, bindToWindow } from "./extension"; +import * as bindings from "./binder"; import { expect, test } from "vitest"; declare global { - var wallet: ProxyAPI; + // eslint-disable-next-line no-var + var wallet: typeof testBindings; } +const testBindings = { + test1() {}, + test2() {}, + test3() {}, +}; + test("test binding to 'window' or 'global' variables", () => { + const bindingName = "wallet"; + const target = typeof window !== "undefined" ? window : global; expect(typeof target).not.toBe("undefined"); - expect(Object.hasOwn(target, "wallet")).toBe(false); + expect(Object.hasOwn(target, bindingName)).toBe(false); - bindToWindow(target, "wallet"); + bindings.set(bindingName, testBindings); - expect(typeof target.wallet).not.toBe("undefined"); + expect(typeof target[bindingName]).not.toBe("undefined"); - expect(typeof target.wallet?.test1).toBe("function"); - expect(typeof target.wallet?.test2).toBe("function"); - expect(typeof target.wallet?.test3).toBe("function"); + const result = bindings.get(bindingName); + expect(typeof result.test1).toBe("function"); + expect(typeof result.test2).toBe("function"); + expect(typeof result.test3).toBe("function"); }); From e64d7918c0c0adcb371868686c5cebccc3b9ee29 Mon Sep 17 00:00:00 2001 From: stuyk Date: Wed, 31 Jan 2024 09:37:49 -0700 Subject: [PATCH 4/7] feat: add separate class bindings, rename set to setObject --- src/binder/index.ts | 42 ++++++++++++++++++++++++++++++++++++++++-- src/index.test.ts | 38 ++++++++++++++++++++++++++++++++++++-- 2 files changed, 76 insertions(+), 4 deletions(-) diff --git a/src/binder/index.ts b/src/binder/index.ts index 4d1cbab..43ab73c 100644 --- a/src/binder/index.ts +++ b/src/binder/index.ts @@ -5,7 +5,7 @@ * ```ts * type bindings = { test: Function }; * - * set("wallet", bindings); + * setObject("wallet", bindings); * ``` * * @export @@ -13,7 +13,7 @@ * @param {string} name * @param {T} bindings */ -export function set(name: string, bindings: T) { +export function setObject(name: string, bindings: T) { ( globalThis as typeof globalThis & { [key in typeof name]: T; @@ -21,6 +21,44 @@ export function set(name: string, bindings: T) { )[name] = bindings; } +/** + * Safely binds class functions to globalThis + * + * @example + * ```ts + * class Test { + * constructor(){} + * + * test1() {} + * } + * + * setClass('wallet', new Test()); + * ``` + * + * @export + * @template T + * @param {string} name + * @param {T} bindings + */ +export function setClass(name: string, bindings: T) { + const target = globalThis as typeof globalThis & { + [key in typeof name]: object; + }; + + const newBindings: { [key: string]: Function } = {}; + for (let key of Object.getOwnPropertyNames(Object.getPrototypeOf(bindings))) { + if (typeof key !== "string") { + continue; + } + + newBindings[key] = (bindings as { [key: string]: Function })[key].bind( + bindings + ); + } + + target[name] = newBindings; +} + /** * Returns bindings assigned to globalThis * diff --git a/src/index.test.ts b/src/index.test.ts index 3a9348d..b5a0549 100644 --- a/src/index.test.ts +++ b/src/index.test.ts @@ -12,7 +12,22 @@ const testBindings = { test3() {}, }; -test("test binding to 'window' or 'global' variables", () => { +let index = 0; + +class Test { + private id = 0; + + constructor() { + this.id = index; + index += 1; + } + + getId() { + return this.id; + } +} + +test("test binding to 'window' or 'global' variables with object", () => { const bindingName = "wallet"; const target = typeof window !== "undefined" ? window : global; @@ -20,7 +35,7 @@ test("test binding to 'window' or 'global' variables", () => { expect(typeof target).not.toBe("undefined"); expect(Object.hasOwn(target, bindingName)).toBe(false); - bindings.set(bindingName, testBindings); + bindings.setObject(bindingName, testBindings); expect(typeof target[bindingName]).not.toBe("undefined"); @@ -29,3 +44,22 @@ test("test binding to 'window' or 'global' variables", () => { expect(typeof result.test2).toBe("function"); expect(typeof result.test3).toBe("function"); }); + +test("test binding to 'window' or 'global' variables with class", () => { + const bindingName = "wallet"; + + // Bindings testing + const testClass = new Test(); + expect(testClass.getId() === 0).toBe(true); + const testClass2 = new Test(); + expect(testClass2.getId() === 1).toBe(true); + + bindings.setClass(bindingName, testClass); + + const target = typeof window !== "undefined" ? window : global; + expect(typeof target[bindingName]).not.toBe("undefined"); + + const result = bindings.get(bindingName); + expect(typeof result.getId).toBe("function"); + expect(result.getId() === 0).toBe(true); +}); From 367c1992d48661e726b2ea85e2e40fa3619d1ba0 Mon Sep 17 00:00:00 2001 From: stuyk Date: Wed, 31 Jan 2024 09:41:40 -0700 Subject: [PATCH 5/7] style: fix formatting --- src/binder/index.ts | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/src/binder/index.ts b/src/binder/index.ts index 43ab73c..3af3763 100644 --- a/src/binder/index.ts +++ b/src/binder/index.ts @@ -45,15 +45,13 @@ export function setClass(name: string, bindings: T) { [key in typeof name]: object; }; - const newBindings: { [key: string]: Function } = {}; - for (let key of Object.getOwnPropertyNames(Object.getPrototypeOf(bindings))) { + const newBindings: { [key: string]: () => void } = {}; + for (const key of Object.getOwnPropertyNames(Object.getPrototypeOf(bindings))) { if (typeof key !== "string") { continue; } - newBindings[key] = (bindings as { [key: string]: Function })[key].bind( - bindings - ); + newBindings[key] = (bindings as { [key: string]: () => void })[key].bind(bindings); } target[name] = newBindings; From 0a57d0374bfb551bf321a0f3e2df0dd0f75e83f4 Mon Sep 17 00:00:00 2001 From: stuyk Date: Thu, 1 Feb 2024 11:17:27 -0700 Subject: [PATCH 6/7] feat: single entry point for class or object window assignment --- package.json | 7 +++++++ src/binder/index.ts | 42 +++++++++++++++++++----------------------- src/index.test.ts | 4 ++-- 3 files changed, 28 insertions(+), 25 deletions(-) diff --git a/package.json b/package.json index 6ec5b7a..993ae6b 100644 --- a/package.json +++ b/package.json @@ -28,5 +28,12 @@ "prettier": "^3.2.4", "typescript": "^5.3.3", "vitest": "^1.2.2" + }, + "prettier": { + "tabWidth": 2, + "singleQuote": false, + "trailingComma": "all", + "printWidth": 120, + "bracketSpacing": true } } diff --git a/src/binder/index.ts b/src/binder/index.ts index 3af3763..31bd9d8 100644 --- a/src/binder/index.ts +++ b/src/binder/index.ts @@ -1,30 +1,15 @@ /** - * Safely binds functions to globalThis + * Safely binds an `object` or `class` to the window instance under a name variable + * + * Avoid using `lambda` functions for classes for this to work properly. * * @example * ```ts * type bindings = { test: Function }; * - * setObject("wallet", bindings); + * set("wallet", bindings); * ``` * - * @export - * @template T - * @param {string} name - * @param {T} bindings - */ -export function setObject(name: string, bindings: T) { - ( - globalThis as typeof globalThis & { - [key in typeof name]: T; - } - )[name] = bindings; -} - -/** - * Safely binds class functions to globalThis - * - * @example * ```ts * class Test { * constructor(){} @@ -32,15 +17,26 @@ export function setObject(name: string, bindings: T) { * test1() {} * } * - * setClass('wallet', new Test()); + * set("wallet", new Test()); * ``` * * @export - * @template T * @param {string} name - * @param {T} bindings + * @param {object} bindings + * @return {*} */ -export function setClass(name: string, bindings: T) { +export function set(name: string, bindings: object) { + const isObject = (Object.keys(bindings) as Array).find((key) => typeof bindings[key] === "function"); + + if (isObject) { + ( + globalThis as typeof globalThis & { + [key in typeof name]: object; + } + )[name] = bindings; + return; + } + const target = globalThis as typeof globalThis & { [key in typeof name]: object; }; diff --git a/src/index.test.ts b/src/index.test.ts index b5a0549..0fd4b85 100644 --- a/src/index.test.ts +++ b/src/index.test.ts @@ -35,7 +35,7 @@ test("test binding to 'window' or 'global' variables with object", () => { expect(typeof target).not.toBe("undefined"); expect(Object.hasOwn(target, bindingName)).toBe(false); - bindings.setObject(bindingName, testBindings); + bindings.set(bindingName, testBindings); expect(typeof target[bindingName]).not.toBe("undefined"); @@ -54,7 +54,7 @@ test("test binding to 'window' or 'global' variables with class", () => { const testClass2 = new Test(); expect(testClass2.getId() === 1).toBe(true); - bindings.setClass(bindingName, testClass); + bindings.set(bindingName, testClass); const target = typeof window !== "undefined" ? window : global; expect(typeof target[bindingName]).not.toBe("undefined"); From 9d022f0db68ad1d082dab0bb49c5918260d8efa2 Mon Sep 17 00:00:00 2001 From: stuyk Date: Thu, 1 Feb 2024 11:53:37 -0700 Subject: [PATCH 7/7] remove prettier from package.json --- package.json | 7 ------- 1 file changed, 7 deletions(-) diff --git a/package.json b/package.json index 993ae6b..6ec5b7a 100644 --- a/package.json +++ b/package.json @@ -28,12 +28,5 @@ "prettier": "^3.2.4", "typescript": "^5.3.3", "vitest": "^1.2.2" - }, - "prettier": { - "tabWidth": 2, - "singleQuote": false, - "trailingComma": "all", - "printWidth": 120, - "bracketSpacing": true } }