onejs-core 3.0.3 → 3.0.5

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.
Files changed (103) hide show
  1. package/.gitattributes +2 -2
  2. package/.prettierrc +5 -5
  3. package/.vscode/settings.json +5 -5
  4. package/LICENSE +20 -20
  5. package/README.md +102 -102
  6. package/bin/oj.js +252 -252
  7. package/definitions/Assemblies/OneJS.Runtime.Ext.d.ts +6 -6
  8. package/definitions/Assemblies/OneJS.Runtime.d.ts +826 -826
  9. package/definitions/Assemblies/OneJS.Samples.d.ts +20 -20
  10. package/definitions/Assemblies/Unity.Mathematics.d.ts +9221 -9221
  11. package/definitions/Assemblies/UnityEditor.CoreModule.d.ts +32614 -32614
  12. package/definitions/Assemblies/UnityEngine.AIModule.d.ts +998 -998
  13. package/definitions/Assemblies/UnityEngine.AnimationModule.d.ts +3308 -3308
  14. package/definitions/Assemblies/UnityEngine.AssetBundleModule.d.ts +337 -337
  15. package/definitions/Assemblies/UnityEngine.AudioModule.d.ts +1154 -1154
  16. package/definitions/Assemblies/UnityEngine.CoreModule.d.ts +29587 -29587
  17. package/definitions/Assemblies/UnityEngine.PhysicsModule.d.ts +3137 -3137
  18. package/definitions/Assemblies/UnityEngine.TerrainModule.d.ts +1270 -1270
  19. package/definitions/Assemblies/UnityEngine.UIElementsModule.d.ts +32718 -32718
  20. package/definitions/Assemblies/UnityEngine.UnityAnalyticsCommonModule.d.ts +274 -274
  21. package/definitions/Assemblies/index.d.ts +16 -16
  22. package/definitions/Assemblies/mscorlib.d.ts +19416 -19416
  23. package/definitions/augments.d.ts +66 -66
  24. package/definitions/globals.d.ts +53 -53
  25. package/definitions/index.d.ts +11 -11
  26. package/definitions/jsx.d.ts +570 -570
  27. package/definitions/modules.d.ts +32 -32
  28. package/definitions/onejs.d.ts +171 -171
  29. package/definitions/preact.jsx.d.ts +6 -6
  30. package/definitions/proto-overrides.d.ts +41 -41
  31. package/definitions/puerts.d.ts +30 -30
  32. package/definitions/unity-engine.d.ts +22 -22
  33. package/dist/dom/document.d.ts +30 -0
  34. package/dist/dom/document.js +89 -0
  35. package/dist/dom/dom-style.d.ts +9 -0
  36. package/dist/dom/dom-style.js +27 -0
  37. package/dist/dom/dom.d.ts +83 -0
  38. package/dist/dom/dom.js +313 -0
  39. package/dist/dom/index.d.ts +4 -0
  40. package/dist/dom/index.js +4 -0
  41. package/dist/index.d.ts +25 -0
  42. package/dist/index.js +45 -0
  43. package/dist/math/index.d.ts +86 -0
  44. package/dist/math/index.js +361 -0
  45. package/dist/preloads/inject.d.ts +3 -0
  46. package/dist/preloads/inject.js +36 -0
  47. package/dist/styling/index.d.ts +10 -0
  48. package/dist/styling/index.js +28 -0
  49. package/dist/styling/utils/generateAlphabeticName.d.ts +1 -0
  50. package/dist/styling/utils/generateAlphabeticName.js +16 -0
  51. package/dist/styling/utils/generateComponentId.d.ts +1 -0
  52. package/dist/styling/utils/generateComponentId.js +5 -0
  53. package/dist/styling/utils/hash.d.ts +5 -0
  54. package/dist/styling/utils/hash.js +34 -0
  55. package/dist/utils/arrays.d.ts +1 -0
  56. package/dist/utils/arrays.js +10 -0
  57. package/dist/utils/color-palettes.d.ts +2 -0
  58. package/dist/utils/color-palettes.js +2 -0
  59. package/dist/utils/color-parser.d.ts +161 -0
  60. package/dist/utils/color-parser.js +241 -0
  61. package/dist/utils/float-parser.d.ts +7 -0
  62. package/dist/utils/float-parser.js +23 -0
  63. package/dist/utils/index.d.ts +12 -0
  64. package/dist/utils/index.js +15 -0
  65. package/dist/utils/subscribe.d.ts +4 -0
  66. package/dist/utils/subscribe.js +10 -0
  67. package/dist/utils/system.d.ts +1 -0
  68. package/dist/utils/system.js +16 -0
  69. package/dom/document.ts +115 -115
  70. package/dom/dom-style.ts +36 -36
  71. package/dom/dom.ts +376 -376
  72. package/dom/index.ts +3 -3
  73. package/index.ts +59 -59
  74. package/jsr.json +9 -9
  75. package/math/README.md +212 -212
  76. package/math/index.ts +487 -487
  77. package/package.json +34 -33
  78. package/preloads/inject.ts +43 -43
  79. package/scripts/esbuild/copy-assets.mjs +94 -94
  80. package/scripts/esbuild/decorator-fix.mjs +17 -17
  81. package/scripts/esbuild/import-transform.mjs +100 -100
  82. package/scripts/esbuild/index.mjs +3 -3
  83. package/scripts/esbuild/watch-output.mjs +38 -38
  84. package/scripts/postcss/cleanup-plugin.cjs +89 -89
  85. package/scripts/postcss/onejs-tw-config.cjs +252 -252
  86. package/scripts/postcss/optional-import-plugin.cjs +26 -26
  87. package/scripts/postcss/tailwind-logging-plugin.cjs +11 -11
  88. package/scripts/postcss/unwrap-is-plugin.cjs +16 -16
  89. package/scripts/postcss/uss-transform-plugin.cjs +92 -92
  90. package/scripts/switch.cjs +321 -290
  91. package/styling/index.tsx +32 -32
  92. package/styling/utils/generateAlphabeticName.ts +20 -20
  93. package/styling/utils/generateComponentId.ts +5 -5
  94. package/styling/utils/hash.ts +46 -46
  95. package/tsconfig.json +24 -24
  96. package/typings.d.ts +5 -5
  97. package/utils/arrays.ts +10 -10
  98. package/utils/color-palettes.ts +2 -2
  99. package/utils/color-parser.ts +248 -248
  100. package/utils/float-parser.ts +30 -30
  101. package/utils/index.ts +15 -15
  102. package/utils/subscribe.ts +16 -16
  103. package/utils/system.ts +16 -16
package/package.json CHANGED
@@ -1,33 +1,34 @@
1
- {
2
- "name": "onejs-core",
3
- "description": "The JS part of OneJS, a UI framework and Scripting Engine for Unity.",
4
- "version": "3.0.3",
5
- "repository": {
6
- "type": "git",
7
- "url": "https://github.com/Singtaa/onejs-core"
8
- },
9
- "main": "./dist/index.js",
10
- "types": "./typings.d.ts",
11
- "bin": {
12
- "oj": "./bin/oj.js"
13
- },
14
- "dependencies": {
15
- "chalk": "^4.1.2",
16
- "commander": "^11.0.0",
17
- "css-flatten": "^2.0.0",
18
- "css-simple-parser": "^3.0.0",
19
- "ora": "^5.4.1",
20
- "progress": "^2.0.3",
21
- "tar": "^7.2.0"
22
- },
23
- "devDependencies": {
24
- "esbuild": "^0.20.0",
25
- "fs-extra": "^11.2.0",
26
- "postcss": "^8.4.38",
27
- "postcss-cli": "^11.0.0",
28
- "rimraf": "^5.0.7",
29
- "tailwindcss": "^3.4.17",
30
- "tiny-glob": "^0.2.9",
31
- "xml2js": "^0.6.2"
32
- }
33
- }
1
+ {
2
+ "name": "onejs-core",
3
+ "description": "The JS part of OneJS, a UI framework and Scripting Engine for Unity.",
4
+ "version": "3.0.5",
5
+ "repository": {
6
+ "type": "git",
7
+ "url": "https://github.com/Singtaa/onejs-core"
8
+ },
9
+ "main": "./dist/index.js",
10
+ "types": "./typings.d.ts",
11
+ "bin": {
12
+ "oj": "./bin/oj.js"
13
+ },
14
+ "dependencies": {
15
+ "chalk": "^4.1.2",
16
+ "commander": "^11.0.0",
17
+ "css-flatten": "^2.0.0",
18
+ "css-simple-parser": "^3.0.0",
19
+ "fs-extra": "^11.2.0",
20
+ "ora": "^5.4.1",
21
+ "progress": "^2.0.3",
22
+ "rimraf": "^5.0.7",
23
+ "tar": "^7.2.0"
24
+ },
25
+ "devDependencies": {
26
+ "esbuild": "^0.20.0",
27
+ "postcss": "^8.4.38",
28
+ "postcss-cli": "^11.0.0",
29
+ "postcss-import": "^16.1.1",
30
+ "tailwindcss": "^3.4.17",
31
+ "tiny-glob": "^0.2.9",
32
+ "xml2js": "^0.6.2"
33
+ }
34
+ }
@@ -1,44 +1,44 @@
1
- /// <reference path="../definitions/index.d.ts" />
2
-
3
- export function btoa(text: string): string {
4
- // return CS.OneJS.CommonGlobals.btoa(text);
5
- const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
6
- let str = text;
7
- let output = '';
8
-
9
- for (let i = 0; i < str.length; i += 3) {
10
- let block = (str.charCodeAt(i) << 16) | ((i + 1 < str.length ? str.charCodeAt(i + 1) : 0) << 8) | (i + 2 < str.length ? str.charCodeAt(i + 2) : 0);
11
- output += chars[(block >> 18) & 0x3F] +
12
- chars[(block >> 12) & 0x3F] +
13
- (i + 1 < str.length ? chars[(block >> 6) & 0x3F] : '=') +
14
- (i + 2 < str.length ? chars[block & 0x3F] : '=');
15
- }
16
-
17
- return output;
18
- }
19
-
20
- // function uint8ArrayToString(uint8Array) {
21
- // const chars: any = [];
22
- // for (let i = 0; i < uint8Array.length; i++) {
23
- // chars.push(String.fromCharCode(uint8Array[i]));
24
- // }
25
- // return chars.join('');
26
- // }
27
-
28
- export function atob(base64: string): string {
29
- // return CS.OneJS.CommonGlobals.atob(base64);
30
- // return CS.System.Text.Encoding.UTF8.GetString(CS.System.Convert.FromBase64String(base64))
31
- const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
32
- let str = base64.replace(/=+$/, '');
33
- let output = '';
34
-
35
- if (str.length % 4 == 1) {
36
- throw new Error('Invalid base64 string');
37
- }
38
-
39
- for (let bc = 0, bs = 0, buffer, idx = 0; buffer = str.charAt(idx++); ~buffer && (bs = bc % 4 ? bs * 64 + buffer : buffer, bc++ % 4) ? output += String.fromCharCode(255 & bs >> (-2 * bc & 6)) : 0) {
40
- buffer = chars.indexOf(buffer);
41
- }
42
-
43
- return output;
1
+ /// <reference path="../definitions/index.d.ts" />
2
+
3
+ export function btoa(text: string): string {
4
+ // return CS.OneJS.CommonGlobals.btoa(text);
5
+ const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
6
+ let str = text;
7
+ let output = '';
8
+
9
+ for (let i = 0; i < str.length; i += 3) {
10
+ let block = (str.charCodeAt(i) << 16) | ((i + 1 < str.length ? str.charCodeAt(i + 1) : 0) << 8) | (i + 2 < str.length ? str.charCodeAt(i + 2) : 0);
11
+ output += chars[(block >> 18) & 0x3F] +
12
+ chars[(block >> 12) & 0x3F] +
13
+ (i + 1 < str.length ? chars[(block >> 6) & 0x3F] : '=') +
14
+ (i + 2 < str.length ? chars[block & 0x3F] : '=');
15
+ }
16
+
17
+ return output;
18
+ }
19
+
20
+ // function uint8ArrayToString(uint8Array) {
21
+ // const chars: any = [];
22
+ // for (let i = 0; i < uint8Array.length; i++) {
23
+ // chars.push(String.fromCharCode(uint8Array[i]));
24
+ // }
25
+ // return chars.join('');
26
+ // }
27
+
28
+ export function atob(base64: string): string {
29
+ // return CS.OneJS.CommonGlobals.atob(base64);
30
+ // return CS.System.Text.Encoding.UTF8.GetString(CS.System.Convert.FromBase64String(base64))
31
+ const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
32
+ let str = base64.replace(/=+$/, '');
33
+ let output = '';
34
+
35
+ if (str.length % 4 == 1) {
36
+ throw new Error('Invalid base64 string');
37
+ }
38
+
39
+ for (let bc = 0, bs = 0, buffer, idx = 0; buffer = str.charAt(idx++); ~buffer && (bs = bc % 4 ? bs * 64 + buffer : buffer, bc++ % 4) ? output += String.fromCharCode(255 & bs >> (-2 * bc & 6)) : 0) {
40
+ buffer = chars.indexOf(buffer);
41
+ }
42
+
43
+ return output;
44
44
  }
@@ -1,95 +1,95 @@
1
- /**
2
- * Contains code from Nick Janetakis's esbuild-copy-static-files (MIT)
3
- */
4
- import path from 'path'
5
- import fs from 'fs'
6
- import crypto from 'crypto'
7
-
8
- function getPackagesWithAssets() {
9
- let packagesWithAssets = [];
10
- const nodeModulesPath = path.join(process.cwd(), 'node_modules');
11
- const packages = fs.readdirSync(nodeModulesPath);
12
- // console.log("There are " + packages.length + " packages in node_modules");
13
- for (const packageName of packages) {
14
- const packagePath = path.join(nodeModulesPath, packageName);
15
- if (!fs.statSync(packagePath).isDirectory())
16
- continue;
17
- const pkgJsonPath = path.join(packagePath, 'package.json');
18
-
19
- try {
20
- const pkgJsonContent = fs.readFileSync(pkgJsonPath, 'utf8');
21
- const pkgJson = JSON.parse(pkgJsonContent);
22
-
23
- if (pkgJson.onejs && pkgJson.onejs['assets-path']) {
24
-
25
- packagesWithAssets.push({
26
- name: packageName,
27
- src: path.join("node_modules", packageName, pkgJson.onejs['assets-path'])
28
- });
29
- }
30
- } catch (error) {
31
- if (error.code !== 'ENOENT') {
32
- console.error(`Error processing ${packageName}:`, error);
33
- }
34
- }
35
- }
36
-
37
- // console.log("Found " + packagesWithAssets.length + " packages with assets");
38
- return packagesWithAssets
39
- }
40
-
41
- const getDigest = (string) => {
42
- const hash = crypto.createHash('md5')
43
- const data = hash.update(string, 'utf-8')
44
-
45
- return data.digest('hex')
46
- }
47
-
48
- const getFileDigest = (path) => {
49
- if (!fs.existsSync(path)) {
50
- return null
51
- }
52
-
53
- if (fs.statSync(path).isDirectory()) {
54
- return null
55
- }
56
-
57
- return getDigest(fs.readFileSync(path))
58
- }
59
-
60
- function filter(src, dest) {
61
- if (!fs.existsSync(dest)) {
62
- return true
63
- }
64
-
65
- if (fs.statSync(dest).isDirectory()) {
66
- return true
67
- }
68
-
69
- return getFileDigest(src) !== getFileDigest(dest)
70
- }
71
-
72
- export function copyAssetsPlugin(options = {}) {
73
- let dest = options.dest || 'assets'
74
- return {
75
- name: "onejs-copy-assets",
76
- setup(build) {
77
- build.onEnd(async () => {
78
- const packagesWithAssets = getPackagesWithAssets();
79
- console.log(`[esbuild] syncing assets from:`)
80
- for (const pkg of packagesWithAssets) {
81
- const destPath = path.join(dest, "@" + pkg.name);
82
- fs.cpSync(pkg.src, destPath, {
83
- dereference: options.dereference || true,
84
- errorOnExist: options.errorOnExist || false,
85
- filter: options.filter || filter,
86
- force: options.force || true,
87
- preserveTimestamps: options.preserveTimestamps || true,
88
- recursive: options.recursive || true,
89
- })
90
- console.log(`[esbuild] > ${pkg.name}`)
91
- }
92
- })
93
- }
94
- }
1
+ /**
2
+ * Contains code from Nick Janetakis's esbuild-copy-static-files (MIT)
3
+ */
4
+ import path from 'path'
5
+ import fs from 'fs'
6
+ import crypto from 'crypto'
7
+
8
+ function getPackagesWithAssets() {
9
+ let packagesWithAssets = [];
10
+ const nodeModulesPath = path.join(process.cwd(), 'node_modules');
11
+ const packages = fs.readdirSync(nodeModulesPath);
12
+ // console.log("There are " + packages.length + " packages in node_modules");
13
+ for (const packageName of packages) {
14
+ const packagePath = path.join(nodeModulesPath, packageName);
15
+ if (!fs.statSync(packagePath).isDirectory())
16
+ continue;
17
+ const pkgJsonPath = path.join(packagePath, 'package.json');
18
+
19
+ try {
20
+ const pkgJsonContent = fs.readFileSync(pkgJsonPath, 'utf8');
21
+ const pkgJson = JSON.parse(pkgJsonContent);
22
+
23
+ if (pkgJson.onejs && pkgJson.onejs['assets-path']) {
24
+
25
+ packagesWithAssets.push({
26
+ name: packageName,
27
+ src: path.join("node_modules", packageName, pkgJson.onejs['assets-path'])
28
+ });
29
+ }
30
+ } catch (error) {
31
+ if (error.code !== 'ENOENT') {
32
+ console.error(`Error processing ${packageName}:`, error);
33
+ }
34
+ }
35
+ }
36
+
37
+ // console.log("Found " + packagesWithAssets.length + " packages with assets");
38
+ return packagesWithAssets
39
+ }
40
+
41
+ const getDigest = (string) => {
42
+ const hash = crypto.createHash('md5')
43
+ const data = hash.update(string, 'utf-8')
44
+
45
+ return data.digest('hex')
46
+ }
47
+
48
+ const getFileDigest = (path) => {
49
+ if (!fs.existsSync(path)) {
50
+ return null
51
+ }
52
+
53
+ if (fs.statSync(path).isDirectory()) {
54
+ return null
55
+ }
56
+
57
+ return getDigest(fs.readFileSync(path))
58
+ }
59
+
60
+ function filter(src, dest) {
61
+ if (!fs.existsSync(dest)) {
62
+ return true
63
+ }
64
+
65
+ if (fs.statSync(dest).isDirectory()) {
66
+ return true
67
+ }
68
+
69
+ return getFileDigest(src) !== getFileDigest(dest)
70
+ }
71
+
72
+ export function copyAssetsPlugin(options = {}) {
73
+ let dest = options.dest || 'assets'
74
+ return {
75
+ name: "onejs-copy-assets",
76
+ setup(build) {
77
+ build.onEnd(async () => {
78
+ const packagesWithAssets = getPackagesWithAssets();
79
+ console.log(`[esbuild] syncing assets from:`)
80
+ for (const pkg of packagesWithAssets) {
81
+ const destPath = path.join(dest, "@" + pkg.name);
82
+ fs.cpSync(pkg.src, destPath, {
83
+ dereference: options.dereference || true,
84
+ errorOnExist: options.errorOnExist || false,
85
+ filter: options.filter || filter,
86
+ force: options.force || true,
87
+ preserveTimestamps: options.preserveTimestamps || true,
88
+ recursive: options.recursive || true,
89
+ })
90
+ console.log(`[esbuild] > ${pkg.name}`)
91
+ }
92
+ })
93
+ }
94
+ }
95
95
  }
@@ -1,18 +1,18 @@
1
- import fs from 'fs'
2
-
3
- export function decoratorFixPlugin(options = {}) {
4
- const outfile = options.outfile || "@outputs/esbuild/app.js"
5
- return {
6
- name: "decorator-fix-plugin",
7
- setup(build) {
8
- build.onEnd(() => {
9
- let content = fs.readFileSync(outfile, "utf8")
10
- content = content.replace(
11
- /exports\s*&&\s*exports\.__decorate/g,
12
- 'typeof exports !== "undefined" && exports.__decorate'
13
- )
14
- fs.writeFileSync(outfile, content, "utf8")
15
- })
16
- }
17
- }
1
+ import fs from 'fs'
2
+
3
+ export function decoratorFixPlugin(options = {}) {
4
+ const outfile = options.outfile || "@outputs/esbuild/app.js"
5
+ return {
6
+ name: "decorator-fix-plugin",
7
+ setup(build) {
8
+ build.onEnd(() => {
9
+ let content = fs.readFileSync(outfile, "utf8")
10
+ content = content.replace(
11
+ /exports\s*&&\s*exports\.__decorate/g,
12
+ 'typeof exports !== "undefined" && exports.__decorate'
13
+ )
14
+ fs.writeFileSync(outfile, content, "utf8")
15
+ })
16
+ }
17
+ }
18
18
  }
@@ -1,101 +1,101 @@
1
- import * as fs from "fs";
2
- import * as path from "path";
3
-
4
- /**
5
- * An esbuild plugin that transforms imports from modules starting with a capital letter.
6
- *
7
- * ## Functionality:
8
- * 1. **Externalizing Capitalized Module Imports**:
9
- * - Marks imports from modules with names starting with a capital letter as external
10
- * during the resolution phase.
11
- *
12
- * 2. **Transforming Import Statements**:
13
- * - Rewrites ES module import statements to reference a global `CS` object.
14
- * - Converts:
15
- * ```js
16
- * import { Foo, Bar } from "MyModule";
17
- * ```
18
- * Into:
19
- * ```js
20
- * const { Foo, Bar } = CS.MyModule;
21
- * ```
22
- * - If the import is a default import or namespace import:
23
- * ```js
24
- * import MyModule from "MyModule";
25
- * ```
26
- * Becomes:
27
- * ```js
28
- * const MyModule = CS.MyModule;
29
- * ```
30
- *
31
- * 3. **Handling `require` Statements**:
32
- * - Transforms `__require("MyModule")` into `CS.MyModule`.
33
- *
34
- * ## Parameters:
35
- * @param {Object} options - Configuration options.
36
- * @param {Function} [options.moduleFilter] - A filter function that determines if a module should be transformed.
37
- *
38
- * ## Returns:
39
- * @returns {Object} An esbuild plugin object.
40
- *
41
- * ## Example Usage:
42
- *
43
- * ```js
44
- * importTransformation({
45
- * moduleFilter: (moduleName) => moduleName.startsWith("MyLib")
46
- * });
47
- * ```
48
- *
49
- */
50
- export function importTransformationPlugin(options = {}) {
51
- const moduleFilter = options.moduleFilter || (() => true);
52
- return {
53
- name: "onejs-import-transform",
54
- setup(build) {
55
- // First pass: Mark imports from modules starting with a capital letter as external
56
- build.onResolve({ filter: /^[A-Z]/ }, (args) => {
57
- return { path: args.path, external: true };
58
- });
59
-
60
- // Second pass: Transform all JS and TSX files
61
- build.onLoad({ filter: /\.(js|jsx|ts|tsx)$/ }, async (args) => {
62
- let contents = await fs.promises.readFile(args.path, "utf8");
63
-
64
- // Transform imports from modules starting with a capital letter
65
- contents = contents.replace(
66
- /import\s+(?:{([^}]+)})?\s*from\s*["']([A-Z][^"']*)["'];?/g,
67
- (match, imports, moduleName) => {
68
- if (!moduleFilter(moduleName))
69
- return match;
70
- moduleName = moduleName.replace(/\//g, ".");
71
- if (imports) {
72
- const importItems = imports.split(",").map((item) => item.trim());
73
- return `const { ${importItems.join(", ")} } = CS.${moduleName};`;
74
- } else {
75
- const namespaceName = moduleName.split(".").pop();
76
- return `const ${namespaceName} = CS.${moduleName};`;
77
- }
78
- }
79
- );
80
-
81
- // Transform any remaining require statements for such modules
82
- contents = contents.replace(
83
- /__require\(["']([A-Z][^"']*)["']\)/g,
84
- (match, moduleName) => {
85
- if (!moduleFilter(moduleName))
86
- return match;
87
- return `CS.${moduleName.replace(/\//g, ".")}`;
88
- }
89
- );
90
-
91
- return { contents, loader: path.extname(args.path).slice(1) };
92
- });
93
- },
94
- };
95
- }
96
-
97
- /**
98
- * Keeping for backward-compatibility reasons. Please use `importTransformationPlugin()` instead.
99
- */
100
- export const importTransformation = importTransformationPlugin;
1
+ import * as fs from "fs";
2
+ import * as path from "path";
3
+
4
+ /**
5
+ * An esbuild plugin that transforms imports from modules starting with a capital letter.
6
+ *
7
+ * ## Functionality:
8
+ * 1. **Externalizing Capitalized Module Imports**:
9
+ * - Marks imports from modules with names starting with a capital letter as external
10
+ * during the resolution phase.
11
+ *
12
+ * 2. **Transforming Import Statements**:
13
+ * - Rewrites ES module import statements to reference a global `CS` object.
14
+ * - Converts:
15
+ * ```js
16
+ * import { Foo, Bar } from "MyModule";
17
+ * ```
18
+ * Into:
19
+ * ```js
20
+ * const { Foo, Bar } = CS.MyModule;
21
+ * ```
22
+ * - If the import is a default import or namespace import:
23
+ * ```js
24
+ * import MyModule from "MyModule";
25
+ * ```
26
+ * Becomes:
27
+ * ```js
28
+ * const MyModule = CS.MyModule;
29
+ * ```
30
+ *
31
+ * 3. **Handling `require` Statements**:
32
+ * - Transforms `__require("MyModule")` into `CS.MyModule`.
33
+ *
34
+ * ## Parameters:
35
+ * @param {Object} options - Configuration options.
36
+ * @param {Function} [options.moduleFilter] - A filter function that determines if a module should be transformed.
37
+ *
38
+ * ## Returns:
39
+ * @returns {Object} An esbuild plugin object.
40
+ *
41
+ * ## Example Usage:
42
+ *
43
+ * ```js
44
+ * importTransformation({
45
+ * moduleFilter: (moduleName) => moduleName.startsWith("MyLib")
46
+ * });
47
+ * ```
48
+ *
49
+ */
50
+ export function importTransformationPlugin(options = {}) {
51
+ const moduleFilter = options.moduleFilter || (() => true);
52
+ return {
53
+ name: "onejs-import-transform",
54
+ setup(build) {
55
+ // First pass: Mark imports from modules starting with a capital letter as external
56
+ build.onResolve({ filter: /^[A-Z]/ }, (args) => {
57
+ return { path: args.path, external: true };
58
+ });
59
+
60
+ // Second pass: Transform all JS and TSX files
61
+ build.onLoad({ filter: /\.(js|jsx|ts|tsx)$/ }, async (args) => {
62
+ let contents = await fs.promises.readFile(args.path, "utf8");
63
+
64
+ // Transform imports from modules starting with a capital letter
65
+ contents = contents.replace(
66
+ /import\s+(?:{([^}]+)})?\s*from\s*["']([A-Z][^"']*)["'];?/g,
67
+ (match, imports, moduleName) => {
68
+ if (!moduleFilter(moduleName))
69
+ return match;
70
+ moduleName = moduleName.replace(/\//g, ".");
71
+ if (imports) {
72
+ const importItems = imports.split(",").map((item) => item.trim());
73
+ return `const { ${importItems.join(", ")} } = CS.${moduleName};`;
74
+ } else {
75
+ const namespaceName = moduleName.split(".").pop();
76
+ return `const ${namespaceName} = CS.${moduleName};`;
77
+ }
78
+ }
79
+ );
80
+
81
+ // Transform any remaining require statements for such modules
82
+ contents = contents.replace(
83
+ /__require\(["']([A-Z][^"']*)["']\)/g,
84
+ (match, moduleName) => {
85
+ if (!moduleFilter(moduleName))
86
+ return match;
87
+ return `CS.${moduleName.replace(/\//g, ".")}`;
88
+ }
89
+ );
90
+
91
+ return { contents, loader: path.extname(args.path).slice(1) };
92
+ });
93
+ },
94
+ };
95
+ }
96
+
97
+ /**
98
+ * Keeping for backward-compatibility reasons. Please use `importTransformationPlugin()` instead.
99
+ */
100
+ export const importTransformation = importTransformationPlugin;
101
101
  export const importTransformPlugin = importTransformationPlugin();
@@ -1,4 +1,4 @@
1
- export * from "./import-transform.mjs"
2
- export * from "./watch-output.mjs"
3
- export * from "./copy-assets.mjs"
1
+ export * from "./import-transform.mjs"
2
+ export * from "./watch-output.mjs"
3
+ export * from "./copy-assets.mjs"
4
4
  export * from "./decorator-fix.mjs"