@sanatanai/require 1.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.
package/README.md ADDED
@@ -0,0 +1,134 @@
1
+ <img style="max-width: 300px; margin-left: auto; margin-right: auto" src="https://raw.githubusercontent.com/ShivamSharma999/Sanatan-AI-Welcome/refs/heads/master/logo.png" alt="Sanatan AI logo" />
2
+
3
+ # Sanatan AI - Require
4
+
5
+ Sanatan AI - Require is a powerful and flexible module import system that extends Node.js's native `require` functionality. It offers enhanced control over module resolution, allowing you to configure how `package-lock.json` is utilized, whether local `node_modules` are considered, and provides mechanisms for introspection and cache management. This package is designed to give developers more granular control and insight into their application's dependency loading.
6
+
7
+ ## Installation
8
+
9
+ You can install Sanatan AI - Require via npm:
10
+
11
+ ```bash
12
+ npm install @sanatanai/require
13
+ ```
14
+
15
+ ## Usage
16
+
17
+ The primary way to use Sanatan AI - Require is through its `require` function, which works asynchronously.
18
+
19
+ ```javascript
20
+ import require from "@sanatanai/require";
21
+
22
+ async function loadModule() {
23
+ try {
24
+ const myModule = await require('my-package');
25
+ console.log('Module loaded:', myModule);
26
+ } catch (error) {
27
+ console.error('Failed to load module:', error);
28
+ }
29
+ }
30
+
31
+ loadModule();
32
+ ```
33
+
34
+ ## Configuration (setRequire)
35
+
36
+ The `setRequire` interface provides methods to configure the behavior of the `require` function.
37
+
38
+ ### `setRequire.readPkgLock(v: boolean)`
39
+
40
+ Sets whether the `package-lock.json` file specified by `setRequire.pkgLockPath` should be read for module resolution.
41
+ - `v`: A boolean value. `true` to enable reading `package-lock.json`, `false` to disable.
42
+ - Default: `true`
43
+
44
+ ```javascript
45
+ import { setRequire } from "@sanatanai/require";
46
+
47
+ // Disable reading package-lock.json
48
+ setRequire.readPkgLock(false);
49
+ ```
50
+
51
+ ### `setRequire.pkgLockPath(p: string)`
52
+
53
+ Sets the absolute or relative path to the `package-lock.json` file.
54
+ - `p`: The path to `package-lock.json`.
55
+ - Default: `root/package-lock.json` (where root is the project's root directory)
56
+
57
+ ```javascript
58
+ import { setRequire } from "@sanatanai/require";
59
+
60
+ // Set a custom path for package-lock.json
61
+ setRequire.pkgLockPath('/path/to/my/custom/package-lock.json');
62
+ ```
63
+
64
+ ### `setRequire.nodeModules(v: boolean)`
65
+
66
+ Sets whether the local `node_modules` folder should be used for importing modules.
67
+ - `v`: A boolean value. `true` to enable using local `node_modules`, `false` to disable.
68
+ - Default: `false`
69
+
70
+ ```javascript
71
+ import { setRequire } from "@sanatanai/require";
72
+
73
+ // Enable using local node_modules
74
+ setRequire.nodeModules(true);
75
+ ```
76
+
77
+ ### `setRequire.clearCache()`
78
+
79
+ Clears the internal cache of `package.json` files that Sanatan AI - Require stores for different packages. This can be useful for development scenarios where `package.json` files might change frequently.
80
+
81
+ ```javascript
82
+ import { setRequire } from "@sanatanai/require";
83
+
84
+ // Clear the internal file cache
85
+ setRequire.clearCache();
86
+ ```
87
+
88
+ ## Information Retrieval (getRequire)
89
+
90
+ The `getRequire` interface provides methods to retrieve the current configuration and internal state of the `require` function.
91
+
92
+ ### `getRequire.readPkgLock(): boolean`
93
+
94
+ Returns the current boolean value indicating whether `package-lock.json` is being read. This value is configured by `setRequire.readPkgLock`.
95
+
96
+ ```javascript
97
+ import { getRequire } from "@sanatanai/require";
98
+
99
+ const isReadingPkgLock = getRequire.readPkgLock();
100
+ console.log('Is reading package-lock.json:', isReadingPkgLock);
101
+ ```
102
+
103
+ ### `getRequire.pkgLockPath(): string`
104
+
105
+ Returns the currently configured path to the `package-lock.json` file. This path is set by `setRequire.pkgLockPath`.
106
+
107
+ ```javascript
108
+ import { getRequire } from "@sanatanai/require";
109
+
110
+ const pkgLockPath = getRequire.pkgLockPath();
111
+ console.log('Package-lock.json path:', pkgLockPath);
112
+ ```
113
+
114
+ ### `getRequire.importMap(): Map<string, object>`
115
+
116
+ Returns the internal `Map` object used by Sanatan AI - Require for module imports. Each entry in the map typically represents a mapping from a module name to its script path or metadata.
117
+
118
+ ```javascript
119
+ import { getRequire } from "@sanatanai/require";
120
+
121
+ const importMap = getRequire.importMap();
122
+ console.log('Current import map:', importMap);
123
+ ```
124
+
125
+ ### `getRequire.cache(): Map<string, object>`
126
+
127
+ Returns the file cache `Map` object stored internally by the Sanatan AI `require` function. This cache stores parsed `package.json` contents for performance.
128
+
129
+ ```javascript
130
+ import { getRequire } from "@sanatanai/require";
131
+
132
+ const fileCache = getRequire.cache();
133
+ console.log('Internal file cache:', fileCache);
134
+ ```
package/package.json ADDED
@@ -0,0 +1,32 @@
1
+ {
2
+ "name": "@sanatanai/require",
3
+ "version": "1.0.1",
4
+ "description": "The browser side nodejs require function.",
5
+ "type": "module",
6
+ "main": "./src/index.js",
7
+ "types": "./src/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "import": "./src/index.js",
11
+ "types": "./src/index.d.ts"
12
+ },
13
+ "./package.json": "./package.json"
14
+ },
15
+ "repository": {
16
+ "type": "git",
17
+ "url": "git+https://github.com/ShivamSharma999/require.git"
18
+ },
19
+ "scripts": {},
20
+ "keywords": [
21
+ "require",
22
+ "es6",
23
+ "nodejs",
24
+ "sanatan ai require",
25
+ "sanatan require"
26
+ ],
27
+ "author": "Sanatan AI",
28
+ "license": "MIT",
29
+ "publishConfig": {
30
+ "access": "public"
31
+ }
32
+ }
package/src/index.d.ts ADDED
@@ -0,0 +1,69 @@
1
+ interface setRequire {
2
+ /**
3
+ * Set whether to read `package-lock.json` specified in `setRequire.pkgPath`
4
+ * @param v boolean telling whether to read or not. Default is `true`
5
+ */
6
+ readPkgLock: (v: boolean) => void;
7
+ /**
8
+ * Sets the path to `package-lock.json`
9
+ * @param p The path to `package-lock.json`. Default is root/package-lock.json
10
+ */
11
+ pkgLockPath: (p: string) => void;
12
+ /**
13
+ * Sets whether to use local `node_modules` folder for importing modules
14
+ * @param v Boolean telling whether to use local modules or not. Default is false
15
+ */
16
+ nodeModules: (v: boolean) => void;
17
+ /**
18
+ * ### Clears the stored file cache.
19
+ * package.json of different packages are stored in form of a Map object, this function clears it
20
+ */
21
+ clearCache: () => void;
22
+ }
23
+
24
+ interface getRequire {
25
+ /**
26
+ * Returns the value of boolean which tell whether to read `package-lock.json`
27
+ * It can be configured by `setRequire.readPkgLock`
28
+ */
29
+ readPkgLock: () => boolean;
30
+ /**
31
+ * Returns the path to `package-lock.json` specified by `setRequire.pkgLockPath`
32
+ */
33
+ pkgLockPath: () => string;
34
+ /**
35
+ * Returns the Map object created by sanatanai for imports.
36
+ *
37
+ * Each is in pair "moduleName": "scriptPath"
38
+ */
39
+ importMap: () => Map<string, object>
40
+ /**
41
+ * Returns the file cache map object stored by Sanatan AI require function.
42
+ */
43
+ cache: () => Map<string, object>
44
+ }
45
+
46
+
47
+ /**
48
+ * Asynchronously imports a module using Sanatan AI's custom resolution logic.
49
+ * This function extends Node.js's native `require` with additional capabilities
50
+ * configured via `setRequire` and inspectable via `getRequire`.
51
+ *
52
+ * The resolution process can be influenced by:
53
+ * - `package-lock.json`: Whether to read `package-lock.json` for module versions (controlled by `setRequire.readPkgLock`).
54
+ * - `pkgLockPath`: The specific path to the `package-lock.json` file (controlled by `setRequire.pkgLockPath`).
55
+ * - `nodeModules`: Whether to consider local `node_modules` folders for module lookup (controlled by `setRequire.nodeModules`).
56
+ *
57
+ * The function also leverages an internal cache for `package.json` files, which can be cleared using `setRequire.clearCache()`.
58
+ *
59
+ * @param module The name or path of the module to import. This can be a package name (e.g., 'lodash'),
60
+ * a relative path (e.g., './myModule'), or an absolute path.
61
+ * @returns A Promise that resolves to the imported module's content. The type `any` is used here
62
+ * as the module content can vary greatly (objects, functions, primitives).
63
+ * @throws {Error} If the module cannot be resolved or loaded for any reason (e.g., file not found,
64
+ * syntax error in the module, or issues with package-lock resolution).
65
+ */
66
+ declare function require(module: string): Promise<any>
67
+
68
+ export { setRequire, getRequire, require }
69
+ export default require
package/src/index.js ADDED
@@ -0,0 +1,73 @@
1
+ "use strict";
2
+
3
+ let readPkgLock = true,
4
+ pkgLockPath = "/package-lock.json",
5
+ nodeModules = false;
6
+
7
+ const importMap = new Map(),
8
+ cache = new Map(),
9
+ script = document.createElement("script");
10
+
11
+ script.id = "sanatan-require sanatan-script";
12
+ script.type = "importmap";
13
+ document.body.appendChild(script);
14
+
15
+ const setRequire = {
16
+ readPkgLock: (v) => readPkgLock = v,
17
+ pkgLockPath: (p) => pkgLockPath = p,
18
+ nodeModules: (v) => nodeModules = v,
19
+ clearCache: () => cache.clear()
20
+ }
21
+
22
+ const getRequire = {
23
+ readPkgLock: () => readPkgLock,
24
+ pkgLockPath: () => pkgLockPath,
25
+ importMap: () => importMap,
26
+ cache: () => cache
27
+ }
28
+
29
+ function updateImportMap(pkg, path) {
30
+ importMap.set(pkg, path);
31
+ const importJson = {};
32
+ importMap.forEach((s, p) => importJson[p] = s);
33
+ script.innerHTML = JSON.stringify({ "imports": importJson }, null, 2);
34
+ }
35
+
36
+ async function loadPkg(packagePath, packageName, imp = true) {
37
+ let pkg;
38
+ if (!cache.has(packageName)) {
39
+ const req = await fetch(packagePath);
40
+ pkg = await req.json();
41
+ cache.set(packageName, pkg);
42
+ } else {
43
+ pkg = cache.get(packageName);
44
+ }
45
+ let scriptRoot = packagePath.replace(/package.json$/, "");
46
+ scriptRoot = scriptRoot.startsWith("https") ? scriptRoot : ((scriptRoot.startsWith("/") || scriptRoot.startsWith("./")) ? scriptRoot : "/" + scriptRoot);
47
+ let scriptPath = pkg.module ? pkg.module : (pkg.type == "module" ? (pkg.main || "index.js") : "index.js");
48
+ scriptPath = (scriptPath.startsWith("/") || scriptPath.startsWith("./")) ? scriptPath.replace(/\.{0,1}\//, "") : scriptPath;
49
+ updateImportMap(packageName, scriptRoot + scriptPath);
50
+ return imp ? await import(packageName) : {};
51
+ }
52
+
53
+ async function require(module) {
54
+ if (readPkgLock && pkgLockPath && !importMap.has(module)) {
55
+ let pkgLck = await fetch(pkgLockPath);
56
+ pkgLck = await pkgLck.json();
57
+ Object.keys(pkgLck.packages).forEach(pack => {
58
+ if (pack !== "") {
59
+ pack = nodeModules ? pack : pack.replace("node_modules/", "");
60
+ const packJson = (nodeModules ? pack : "https://unpkg.com/" + pack) + "/package.json";
61
+ loadPkg(packJson, module, false);
62
+ }
63
+ });
64
+ return await loadPkg(nodeModules ? `node_modules/${module}/package.json` : `https://unpkg.com/${module}/package.json`, module)
65
+ }
66
+ else if (importMap.has(module)) return await import(module)
67
+ else {
68
+ return await loadPkg("https://unpkg.com/" + module + "/package.json");
69
+ }
70
+ }
71
+
72
+ export { setRequire, getRequire, require }
73
+ export default require