@ohos-ports/modern-js-node-bundle-require 0.0.0-stage → 2.70.4-beta.0

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2021-present Modern.js
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,26 @@
1
- # Temporary Holding Version
1
+ <p align="center">
2
+ <a href="https://modernjs.dev" target="blank"><img src="https://lf3-static.bytednsdoc.com/obj/eden-cn/ylaelkeh7nuhfnuhf/modernjs-cover.png" width="300" alt="Modern.js Logo" /></a>
3
+ </p>
2
4
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
5
+ <h1 align="center">Modern.js</h1>
6
+
7
+ <p align="center">
8
+ A Progressive React Framework for modern web development.
9
+ </p>
10
+
11
+ ## Getting Started
12
+
13
+ Please follow [Quick Start](https://modernjs.dev/en/guides/get-started/quick-start) to get started with Modern.js.
14
+
15
+ ## Documentation
16
+
17
+ - [English Documentation](https://modernjs.dev/en/)
18
+ - [中文文档](https://modernjs.dev)
19
+
20
+ ## Contributing
21
+
22
+ Please read the [Contributing Guide](https://github.com/web-infra-dev/modern.js/blob/main/CONTRIBUTING.md).
23
+
24
+ ## License
25
+
26
+ Modern.js is [MIT licensed](https://github.com/web-infra-dev/modern.js/blob/main/LICENSE).
@@ -0,0 +1,182 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+ var bundle_exports = {};
30
+ __export(bundle_exports, {
31
+ EXTERNAL_REGEXP: () => EXTERNAL_REGEXP,
32
+ bundle: () => bundle,
33
+ defaultGetOutputFile: () => defaultGetOutputFile
34
+ });
35
+ module.exports = __toCommonJS(bundle_exports);
36
+ var import_path = __toESM(require("path"));
37
+ var import_utils = require("@modern-js/utils");
38
+ var import_esbuild = require("@ohos-ports/esbuild");
39
+ const debug = (0, import_utils.createDebugger)("node-bundle");
40
+ const JS_EXT_RE = /\.(mjs|cjs|ts|js|tsx|jsx)$/;
41
+ const BUNDLED_EXT_RE = /\.(ts|mts|cts|tsx|mjs)$/;
42
+ const EXTERNAL_REGEXP = /^[^./]|^\.[^./]|^\.\.[^/]/;
43
+ function inferLoader(ext) {
44
+ if (ext === ".mjs" || ext === ".cjs") {
45
+ return "js";
46
+ }
47
+ return ext.slice(1);
48
+ }
49
+ async function isTypeModulePkg(cwd) {
50
+ const pkgJsonPath = await (0, import_utils.pkgUp)({
51
+ cwd
52
+ });
53
+ if (pkgJsonPath) {
54
+ var _pkgJson_main;
55
+ const pkgJson = await import_utils.fs.readJSON(pkgJsonPath);
56
+ const ext = import_path.default.extname(cwd);
57
+ return pkgJson.type === "module" && ext !== ".cjs" && !((_pkgJson_main = pkgJson.main) === null || _pkgJson_main === void 0 ? void 0 : _pkgJson_main.endsWith(".cjs"));
58
+ }
59
+ return false;
60
+ }
61
+ const defaultGetOutputFile = async (filepath) => import_path.default.resolve(import_utils.CONFIG_CACHE_DIR, `${filepath.replace(/\.(js|ts)/, "")}.${(0, import_utils.nanoid)(8)}.cjs`);
62
+ async function bundle(filepath, options) {
63
+ if (!JS_EXT_RE.test(filepath)) {
64
+ throw new Error(`${filepath} is not a valid JS file`);
65
+ }
66
+ debug("bundle", filepath, options);
67
+ const getOutputFile = (options === null || options === void 0 ? void 0 : options.getOutputFile) || defaultGetOutputFile;
68
+ const outfile = await getOutputFile(import_path.default.basename(filepath));
69
+ const esbuildOptions = {
70
+ entryPoints: [
71
+ filepath
72
+ ],
73
+ outfile,
74
+ format: "cjs",
75
+ platform: "node",
76
+ bundle: true,
77
+ // fix transforming error when the project's tsconfig.json
78
+ // sets `target: "es5"`
79
+ // reference: https://github.com/evanw/esbuild/releases/tag/v0.12.6
80
+ target: "esnext",
81
+ ...options === null || options === void 0 ? void 0 : options.esbuildOptions,
82
+ plugins: [
83
+ ...(options === null || options === void 0 ? void 0 : options.esbuildPlugins) || [],
84
+ // https://github.com/evanw/esbuild/issues/1051#issuecomment-806325487
85
+ {
86
+ name: "native-node-modules",
87
+ setup(build2) {
88
+ build2.onResolve({
89
+ filter: /\.node$/,
90
+ namespace: "file"
91
+ }, (args) => ({
92
+ path: require.resolve(args.path, {
93
+ paths: [
94
+ args.resolveDir
95
+ ]
96
+ }),
97
+ namespace: "node-file"
98
+ }));
99
+ build2.onLoad({
100
+ filter: /.*/,
101
+ namespace: "node-file"
102
+ }, (args) => ({
103
+ contents: `
104
+ import path from ${JSON.stringify(args.path)}
105
+ try { module.exports = require(path) }
106
+ catch {}
107
+ `
108
+ }));
109
+ build2.onResolve({
110
+ filter: /\.node$/,
111
+ namespace: "node-file"
112
+ }, (args) => ({
113
+ path: args.path,
114
+ namespace: "file"
115
+ }));
116
+ const opts = build2.initialOptions;
117
+ opts.loader = opts.loader || {};
118
+ opts.loader[".node"] = "file";
119
+ }
120
+ },
121
+ {
122
+ name: "replace-path",
123
+ setup(ctx) {
124
+ ctx.onLoad({
125
+ filter: JS_EXT_RE
126
+ }, async (args) => {
127
+ const contents = import_utils.fs.readFileSync(args.path, "utf-8");
128
+ return {
129
+ contents: contents.replace(/\b__filename\b/g, JSON.stringify(args.path)).replace(/\b__dirname\b/g, JSON.stringify(import_path.default.dirname(args.path))).replace(/\bimport\.meta\.url\b/g, JSON.stringify(`file://${args.path}`)),
130
+ loader: inferLoader(import_path.default.extname(args.path))
131
+ };
132
+ });
133
+ }
134
+ },
135
+ // https://github.com/evanw/esbuild/issues/619#issuecomment-751995294
136
+ {
137
+ name: "make-all-packages-external",
138
+ setup(_build) {
139
+ _build.onResolve({
140
+ filter: EXTERNAL_REGEXP
141
+ }, async (args) => {
142
+ let external = true;
143
+ if (args.kind === "entry-point") {
144
+ external = false;
145
+ }
146
+ try {
147
+ const resolvedPath = require.resolve(args.path, {
148
+ paths: [
149
+ args.resolveDir
150
+ ]
151
+ });
152
+ if (BUNDLED_EXT_RE.test(resolvedPath) || await isTypeModulePkg(resolvedPath)) {
153
+ return {
154
+ external: false
155
+ };
156
+ }
157
+ } catch (err) {
158
+ }
159
+ return {
160
+ path: args.path,
161
+ external
162
+ };
163
+ });
164
+ }
165
+ }
166
+ ]
167
+ };
168
+ if (options === null || options === void 0 ? void 0 : options.watch) {
169
+ const ctx = await (0, import_esbuild.context)(esbuildOptions);
170
+ await ctx.rebuild();
171
+ await ctx.watch();
172
+ } else {
173
+ await (0, import_esbuild.build)(esbuildOptions);
174
+ }
175
+ return outfile;
176
+ }
177
+ // Annotate the CommonJS export names for ESM import in node:
178
+ 0 && (module.exports = {
179
+ EXTERNAL_REGEXP,
180
+ bundle,
181
+ defaultGetOutputFile
182
+ });
@@ -0,0 +1,47 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+ var src_exports = {};
20
+ __export(src_exports, {
21
+ bundle: () => import_bundle.bundle,
22
+ bundleRequire: () => bundleRequire,
23
+ defaultGetOutputFile: () => import_bundle.defaultGetOutputFile
24
+ });
25
+ module.exports = __toCommonJS(src_exports);
26
+ var import_utils = require("@modern-js/utils");
27
+ var import_bundle = require("./bundle");
28
+ async function bundleRequire(filepath, options) {
29
+ const configFile = await (0, import_bundle.bundle)(filepath, options);
30
+ let mod;
31
+ const req = (options === null || options === void 0 ? void 0 : options.require) || require;
32
+ try {
33
+ mod = await req(configFile);
34
+ (0, import_utils.deleteRequireCache)(configFile);
35
+ } finally {
36
+ if ((options === null || options === void 0 ? void 0 : options.autoClear) === void 0 || options.autoClear) {
37
+ import_utils.fs.unlinkSync(configFile);
38
+ }
39
+ }
40
+ return mod;
41
+ }
42
+ // Annotate the CommonJS export names for ESM import in node:
43
+ 0 && (module.exports = {
44
+ bundle,
45
+ bundleRequire,
46
+ defaultGetOutputFile
47
+ });
@@ -0,0 +1,146 @@
1
+ import path from "path";
2
+ import { fs, CONFIG_CACHE_DIR, createDebugger, nanoid, pkgUp } from "@modern-js/utils";
3
+ import { build, context } from "@ohos-ports/esbuild";
4
+ const debug = createDebugger("node-bundle");
5
+ const JS_EXT_RE = /\.(mjs|cjs|ts|js|tsx|jsx)$/;
6
+ const BUNDLED_EXT_RE = /\.(ts|mts|cts|tsx|mjs)$/;
7
+ const EXTERNAL_REGEXP = /^[^./]|^\.[^./]|^\.\.[^/]/;
8
+ function inferLoader(ext) {
9
+ if (ext === ".mjs" || ext === ".cjs") {
10
+ return "js";
11
+ }
12
+ return ext.slice(1);
13
+ }
14
+ async function isTypeModulePkg(cwd) {
15
+ const pkgJsonPath = await pkgUp({
16
+ cwd
17
+ });
18
+ if (pkgJsonPath) {
19
+ var _pkgJson_main;
20
+ const pkgJson = await fs.readJSON(pkgJsonPath);
21
+ const ext = path.extname(cwd);
22
+ return pkgJson.type === "module" && ext !== ".cjs" && !((_pkgJson_main = pkgJson.main) === null || _pkgJson_main === void 0 ? void 0 : _pkgJson_main.endsWith(".cjs"));
23
+ }
24
+ return false;
25
+ }
26
+ const defaultGetOutputFile = async (filepath) => path.resolve(CONFIG_CACHE_DIR, `${filepath.replace(/\.(js|ts)/, "")}.${nanoid(8)}.cjs`);
27
+ async function bundle(filepath, options) {
28
+ if (!JS_EXT_RE.test(filepath)) {
29
+ throw new Error(`${filepath} is not a valid JS file`);
30
+ }
31
+ debug("bundle", filepath, options);
32
+ const getOutputFile = (options === null || options === void 0 ? void 0 : options.getOutputFile) || defaultGetOutputFile;
33
+ const outfile = await getOutputFile(path.basename(filepath));
34
+ const esbuildOptions = {
35
+ entryPoints: [
36
+ filepath
37
+ ],
38
+ outfile,
39
+ format: "cjs",
40
+ platform: "node",
41
+ bundle: true,
42
+ // fix transforming error when the project's tsconfig.json
43
+ // sets `target: "es5"`
44
+ // reference: https://github.com/evanw/esbuild/releases/tag/v0.12.6
45
+ target: "esnext",
46
+ ...options === null || options === void 0 ? void 0 : options.esbuildOptions,
47
+ plugins: [
48
+ ...(options === null || options === void 0 ? void 0 : options.esbuildPlugins) || [],
49
+ // https://github.com/evanw/esbuild/issues/1051#issuecomment-806325487
50
+ {
51
+ name: "native-node-modules",
52
+ setup(build2) {
53
+ build2.onResolve({
54
+ filter: /\.node$/,
55
+ namespace: "file"
56
+ }, (args) => ({
57
+ path: require.resolve(args.path, {
58
+ paths: [
59
+ args.resolveDir
60
+ ]
61
+ }),
62
+ namespace: "node-file"
63
+ }));
64
+ build2.onLoad({
65
+ filter: /.*/,
66
+ namespace: "node-file"
67
+ }, (args) => ({
68
+ contents: `
69
+ import path from ${JSON.stringify(args.path)}
70
+ try { module.exports = require(path) }
71
+ catch {}
72
+ `
73
+ }));
74
+ build2.onResolve({
75
+ filter: /\.node$/,
76
+ namespace: "node-file"
77
+ }, (args) => ({
78
+ path: args.path,
79
+ namespace: "file"
80
+ }));
81
+ const opts = build2.initialOptions;
82
+ opts.loader = opts.loader || {};
83
+ opts.loader[".node"] = "file";
84
+ }
85
+ },
86
+ {
87
+ name: "replace-path",
88
+ setup(ctx) {
89
+ ctx.onLoad({
90
+ filter: JS_EXT_RE
91
+ }, async (args) => {
92
+ const contents = fs.readFileSync(args.path, "utf-8");
93
+ return {
94
+ contents: contents.replace(/\b__filename\b/g, JSON.stringify(args.path)).replace(/\b__dirname\b/g, JSON.stringify(path.dirname(args.path))).replace(/\bimport\.meta\.url\b/g, JSON.stringify(`file://${args.path}`)),
95
+ loader: inferLoader(path.extname(args.path))
96
+ };
97
+ });
98
+ }
99
+ },
100
+ // https://github.com/evanw/esbuild/issues/619#issuecomment-751995294
101
+ {
102
+ name: "make-all-packages-external",
103
+ setup(_build) {
104
+ _build.onResolve({
105
+ filter: EXTERNAL_REGEXP
106
+ }, async (args) => {
107
+ let external = true;
108
+ if (args.kind === "entry-point") {
109
+ external = false;
110
+ }
111
+ try {
112
+ const resolvedPath = require.resolve(args.path, {
113
+ paths: [
114
+ args.resolveDir
115
+ ]
116
+ });
117
+ if (BUNDLED_EXT_RE.test(resolvedPath) || await isTypeModulePkg(resolvedPath)) {
118
+ return {
119
+ external: false
120
+ };
121
+ }
122
+ } catch (err) {
123
+ }
124
+ return {
125
+ path: args.path,
126
+ external
127
+ };
128
+ });
129
+ }
130
+ }
131
+ ]
132
+ };
133
+ if (options === null || options === void 0 ? void 0 : options.watch) {
134
+ const ctx = await context(esbuildOptions);
135
+ await ctx.rebuild();
136
+ await ctx.watch();
137
+ } else {
138
+ await build(esbuildOptions);
139
+ }
140
+ return outfile;
141
+ }
142
+ export {
143
+ EXTERNAL_REGEXP,
144
+ bundle,
145
+ defaultGetOutputFile
146
+ };
@@ -0,0 +1,21 @@
1
+ import { fs, deleteRequireCache } from "@modern-js/utils";
2
+ import { bundle, defaultGetOutputFile } from "./bundle";
3
+ async function bundleRequire(filepath, options) {
4
+ const configFile = await bundle(filepath, options);
5
+ let mod;
6
+ const req = (options === null || options === void 0 ? void 0 : options.require) || require;
7
+ try {
8
+ mod = await req(configFile);
9
+ deleteRequireCache(configFile);
10
+ } finally {
11
+ if ((options === null || options === void 0 ? void 0 : options.autoClear) === void 0 || options.autoClear) {
12
+ fs.unlinkSync(configFile);
13
+ }
14
+ }
15
+ return mod;
16
+ }
17
+ export {
18
+ bundle,
19
+ bundleRequire,
20
+ defaultGetOutputFile
21
+ };
@@ -0,0 +1,33 @@
1
+ import { type BuildOptions, type Plugin } from '@ohos-ports/esbuild';
2
+ export declare const EXTERNAL_REGEXP: RegExp;
3
+ export interface Options {
4
+ /**
5
+ * The `require` function that is used to load the output file
6
+ * Default to the global `require` function
7
+ * This function can be asynchronous, i.e. returns a Promise
8
+ */
9
+ require?: (outfile: string) => any;
10
+ /**
11
+ * esbuild options
12
+ */
13
+ esbuildOptions?: BuildOptions;
14
+ /**
15
+ * esbuild plugin
16
+ */
17
+ esbuildPlugins?: Plugin[];
18
+ /**
19
+ * Get the path to the output file
20
+ * By default we simply replace the extension with `.bundled.cjs`
21
+ */
22
+ getOutputFile?: (filepath: string) => Promise<string>;
23
+ /**
24
+ * auto clear bundle file
25
+ */
26
+ autoClear?: boolean;
27
+ /**
28
+ * Whether to enable watch mode
29
+ */
30
+ watch?: boolean;
31
+ }
32
+ export declare const defaultGetOutputFile: (filepath: string) => Promise<string>;
33
+ export declare function bundle(filepath: string, options?: Options): Promise<string>;
@@ -0,0 +1,5 @@
1
+ import type { Options } from './bundle';
2
+ import { bundle, defaultGetOutputFile } from './bundle';
3
+ export { bundle, defaultGetOutputFile };
4
+ export type { Options };
5
+ export declare function bundleRequire(filepath: string, options?: Options): Promise<any>;
package/package.json CHANGED
@@ -1,6 +1,70 @@
1
1
  {
2
2
  "name": "@ohos-ports/modern-js-node-bundle-require",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "2.70.4-beta.0",
4
+ "description": "A Progressive React Framework for modern web development.",
5
+ "homepage": "https://modernjs.dev",
6
+ "bugs": "https://github.com/ohos-ports/ohos-ports/issues",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "https://github.com/ohos-ports/ohos-ports.git",
10
+ "directory": "ports/modern-js-node-bundle-require/2.70.4"
11
+ },
12
+ "license": "MIT",
13
+ "keywords": [
14
+ "react",
15
+ "framework",
16
+ "modern",
17
+ "modern.js"
18
+ ],
19
+ "jsnext:source": "./src/index.ts",
20
+ "types": "./dist/types/index.d.ts",
21
+ "main": "./dist/cjs/index.js",
22
+ "exports": {
23
+ ".": {
24
+ "types": "./dist/types/index.d.ts",
25
+ "node": {
26
+ "jsnext:source": "./src/index.ts",
27
+ "import": "./dist/esm/index.js",
28
+ "require": "./dist/cjs/index.js"
29
+ },
30
+ "default": "./dist/cjs/index.js"
31
+ },
32
+ "./bundle": {
33
+ "types": "./dist/types/bundle.d.ts",
34
+ "default": "./dist/cjs/bundle.js"
35
+ }
36
+ },
37
+ "typesVersions": {
38
+ "*": {
39
+ ".": [
40
+ "./dist/types/index.d.ts"
41
+ ],
42
+ "bundle": [
43
+ "./dist/types/bundle.d.ts"
44
+ ]
45
+ }
46
+ },
47
+ "dependencies": {
48
+ "@swc/helpers": "^0.5.17",
49
+ "@ohos-ports/esbuild": "^0.25.5-beta.0",
50
+ "@modern-js/utils": "2.70.4"
51
+ },
52
+ "devDependencies": {
53
+ "@types/jest": "^29",
54
+ "@types/node": "^18",
55
+ "jest": "^29",
56
+ "typescript": "^5",
57
+ "@scripts/build": "2.66.0",
58
+ "@scripts/jest-config": "2.66.0"
59
+ },
60
+ "sideEffects": false,
61
+ "publishConfig": {
62
+ "registry": "https://registry.npmjs.org/",
63
+ "access": "public"
64
+ },
65
+ "scripts": {
66
+ "new": "modern-lib new",
67
+ "build": "modern-lib build",
68
+ "test": "jest --passWithNoTests"
69
+ }
70
+ }