@digigov/cli-build 2.0.0-13876dba → 2.0.0-16fbe090

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.
@@ -0,0 +1,263 @@
1
+ import { logger } from '@digigov/cli/lib';
2
+ import path from 'path';
3
+ import fs from 'fs';
4
+
5
+ /**
6
+ * @param {Record<string, any>} project
7
+ * @param {string[]} [pathsToIgnore=[]]
8
+ * @returns {import('@rslib/core').rsbuild.RsbuildPlugin}
9
+ */
10
+ export default function transformImportsPlugin(project, pathsToIgnore = []) {
11
+ const projectName = project['name'];
12
+ const projectRoot = project['root'];
13
+ const workspace = project['workspace'];
14
+
15
+ if (Object.keys(workspace).length === 0) {
16
+ throw new Error(
17
+ `transform-imports-plugin can only be used in workspace projects. ${projectName} is not a workspace project.`
18
+ );
19
+ }
20
+
21
+ const projectScopes =
22
+ workspace.config.projects.map((p) => p.packageName) ?? [];
23
+
24
+ if (projectScopes.length === 0) {
25
+ logger.warn(
26
+ `No project scopes found for ${projectName}. Plugin may not transform any imports.`
27
+ );
28
+ }
29
+
30
+ const importRegex =
31
+ /(?:^|[^'"\\])(?:from|import)\s*\(\s*['"]([^'"]+)['"]\s*\)|(?:from|import)\s+['"]([^'"]+)['"]/gm;
32
+
33
+ const packageJsonCache = new Map();
34
+ const fileExistsCache = new Map();
35
+ const resolvedImportsCache = new Map();
36
+
37
+ /**
38
+ * Check if a package uses exports field
39
+ * @param {string} packageName
40
+ * @returns {boolean}
41
+ */
42
+ function hasExportsField(packageName) {
43
+ if (packageJsonCache.has(packageName)) {
44
+ return packageJsonCache.get(packageName);
45
+ }
46
+
47
+ try {
48
+ const pkgJsonPath = path.join(
49
+ projectRoot,
50
+ 'node_modules',
51
+ packageName,
52
+ 'package.json'
53
+ );
54
+
55
+ if (fs.existsSync(pkgJsonPath)) {
56
+ const pkgJson = JSON.parse(fs.readFileSync(pkgJsonPath, 'utf8'));
57
+ const hasExports = !!pkgJson.exports;
58
+ packageJsonCache.set(packageName, hasExports);
59
+ return hasExports;
60
+ }
61
+ } catch (error) {
62
+ logger.warn(`Failed to read package.json for ${packageName}:`, error);
63
+ }
64
+
65
+ packageJsonCache.set(packageName, false);
66
+ return false;
67
+ }
68
+
69
+ /**
70
+ * Check if a file exists with any of the given suffixes (with caching)
71
+ * @param {string} basePath
72
+ * @param {string[]} suffixes
73
+ * @returns {string | null} The matching suffix or null
74
+ */
75
+ function findFileWithSuffix(basePath, suffixes) {
76
+ const cacheKey = `${basePath}:${suffixes.join(',')}`;
77
+
78
+ if (fileExistsCache.has(cacheKey)) {
79
+ return fileExistsCache.get(cacheKey);
80
+ }
81
+
82
+ for (const suffix of suffixes) {
83
+ const fullPath = basePath + suffix;
84
+ if (fs.existsSync(fullPath)) {
85
+ fileExistsCache.set(cacheKey, suffix);
86
+ return suffix;
87
+ }
88
+ }
89
+
90
+ fileExistsCache.set(cacheKey, null);
91
+ return null;
92
+ }
93
+
94
+ /**
95
+ * Extract the package name from an import path
96
+ * @param {string} importPath
97
+ * @returns {string} The package name
98
+ */
99
+ function getPackageName(importPath) {
100
+ if (importPath.startsWith('@')) {
101
+ const parts = importPath.split('/');
102
+ return parts.slice(0, 2).join('/');
103
+ }
104
+ // @ts-expect-error - assured string
105
+ return importPath.split('/')[0];
106
+ }
107
+
108
+ /**
109
+ * Check if a package is internal based on project scopes
110
+ * @param {string} packageName
111
+ * @returns {boolean}
112
+ */
113
+ function isInternalPackage(packageName) {
114
+ return projectScopes.some((scope) => packageName.startsWith(scope));
115
+ }
116
+
117
+ /**
118
+ * Determine if an import should be skipped
119
+ * @param {string} importPath
120
+ * @returns {boolean}
121
+ */
122
+ function shouldSkipImport(importPath) {
123
+ return (
124
+ !importPath ||
125
+ importPath.includes(projectName) ||
126
+ pathsToIgnore.some((ignorePath) => importPath.startsWith(ignorePath)) ||
127
+ importPath.endsWith('.js') ||
128
+ importPath.endsWith('.mjs') ||
129
+ importPath.endsWith('.cjs') ||
130
+ importPath.startsWith('.') ||
131
+ importPath.startsWith('/') ||
132
+ importPath.startsWith('node:') ||
133
+ !importPath.includes('/')
134
+ );
135
+ }
136
+
137
+ /**
138
+ * Transform an internal package import
139
+ * @param {string} importPath
140
+ * @returns {string | null}
141
+ */
142
+ function transformInternalPackageImport(importPath) {
143
+ const parts = importPath.split('/');
144
+ const dependencyName = parts[1];
145
+
146
+ if (!dependencyName) return null;
147
+
148
+ // Replace the dependency name to point to /src
149
+ const srcPath = [...parts];
150
+ srcPath[1] = `${dependencyName}/src`;
151
+ const srcImportPath = srcPath.join('/');
152
+
153
+ const resolvedBase = path.join(projectRoot, 'node_modules', srcImportPath);
154
+
155
+ // Check for direct file match
156
+ const directMatch = findFileWithSuffix(resolvedBase, [
157
+ '.js',
158
+ '.jsx',
159
+ '.ts',
160
+ '.tsx',
161
+ ]);
162
+ if (directMatch) {
163
+ return importPath + '.js';
164
+ }
165
+
166
+ // Check for index file
167
+ const indexMatch = findFileWithSuffix(resolvedBase, [
168
+ '/index.js',
169
+ '/index.jsx',
170
+ '/index.ts',
171
+ '/index.tsx',
172
+ ]);
173
+ if (indexMatch) {
174
+ return importPath + '/index.js';
175
+ }
176
+
177
+ return null;
178
+ }
179
+
180
+ /**
181
+ * Transform a third-party package import
182
+ * @param {string} importPath
183
+ * @returns {string | null}
184
+ */
185
+ function transformThirdPartyImport(importPath) {
186
+ const resolvedBase = path.join(projectRoot, 'node_modules', importPath);
187
+
188
+ // Check for direct .js file
189
+ if (findFileWithSuffix(resolvedBase, ['.js'])) {
190
+ return importPath + '.js';
191
+ }
192
+
193
+ // Check for index.js
194
+ if (findFileWithSuffix(resolvedBase, ['/index.js'])) {
195
+ return importPath + '/index.js';
196
+ }
197
+
198
+ return null;
199
+ }
200
+
201
+ return {
202
+ name: 'transform-imports-plugin',
203
+ setup(api) {
204
+ api.transform(
205
+ { test: /\.[jt]sx?$/, order: 'post' },
206
+ ({ code, resourcePath }) => {
207
+ const transformedCode = code.replace(
208
+ importRegex,
209
+ (fullMatch, dynamicImport, staticImport) => {
210
+ const importPath = dynamicImport || staticImport;
211
+
212
+ // Early return for skippable imports
213
+ if (shouldSkipImport(importPath)) {
214
+ return fullMatch;
215
+ }
216
+
217
+ // Check cache first
218
+ if (resolvedImportsCache.has(importPath)) {
219
+ const cached = resolvedImportsCache.get(importPath);
220
+ return cached
221
+ ? fullMatch.replace(importPath, cached)
222
+ : fullMatch;
223
+ }
224
+
225
+ const packageName = getPackageName(importPath);
226
+
227
+ // Skip third-party packages with exports field
228
+ if (
229
+ !isInternalPackage(packageName) &&
230
+ hasExportsField(packageName)
231
+ ) {
232
+ logger.debug(`Skipping ${importPath} - uses exports field`);
233
+ resolvedImportsCache.set(importPath, null);
234
+ return fullMatch;
235
+ }
236
+
237
+ // Transform based on package type
238
+ let newImportPath = null;
239
+ if (isInternalPackage(packageName)) {
240
+ newImportPath = transformInternalPackageImport(importPath);
241
+ } else {
242
+ newImportPath = transformThirdPartyImport(importPath);
243
+ }
244
+
245
+ // Cache the result
246
+ resolvedImportsCache.set(importPath, newImportPath);
247
+
248
+ if (newImportPath) {
249
+ logger.debug(`Transformed import in ${resourcePath}`);
250
+ logger.debug(` ${importPath} => ${newImportPath}\n`);
251
+ return fullMatch.replace(importPath, newImportPath);
252
+ }
253
+
254
+ return fullMatch;
255
+ }
256
+ );
257
+
258
+ return { code: transformedCode };
259
+ }
260
+ );
261
+ },
262
+ };
263
+ }
@@ -1,62 +1,24 @@
1
1
  {
2
- "extends": "./tsconfig.common.json",
3
2
  "compilerOptions": {
4
- "baseUrl": "../../libs/",
5
- "paths": {
6
- "@digigov/ui/*": ["./ui/src/*"],
7
- "@digigov/ui/": ["./ui/src"],
8
- "@digigov/ui": ["./ui/src"],
9
- "@digigov/ui-dilosi-integration/*": ["./ui-dilosi-integration/src/*"],
10
- "@digigov/ui-dilosi-integration/": ["./ui-dilosi-integration/src"],
11
- "@digigov/ui-dilosi-integration": ["./ui-dilosi-integration/src"],
12
- "@digigov/auth/*": ["./auth/src/*"],
13
- "@digigov/auth/": ["./auth/src"],
14
- "@digigov/auth": ["./auth/src"],
15
- "@digigov/text-search/*": ["./text-search/src/*"],
16
- "@digigov/text-search/": ["./text-search/src"],
17
- "@digigov/text-search": ["./text-search/src"],
18
- "@digigov/form/*": ["./form/src/*"],
19
- "@digigov/form/": ["./form/src"],
20
- "@digigov/form": ["./form/src"],
21
- "@digigov/form-dilosi-integration/*": ["./form-dilosi-integration/src/*"],
22
- "@digigov/form-dilosi-integration/": ["./form-dilosi-integration/src"],
23
- "@digigov/form-dilosi-integration": ["./form-dilosi-integration/src"],
24
- "@digigov/nextjs/*": ["./nextjs/src/*"],
25
- "@digigov/nextjs/": ["./nextjs/src"],
26
- "@digigov/nextjs": ["./nextjs/src"],
27
- "@digigov/react-core/*": ["../libs-ui/react-core/src/*"],
28
- "@digigov/react-core/": ["../libs-ui/react-core/src"],
29
- "@digigov/react-core": ["../libs-ui/react-core/src"],
30
- "@digigov/react-icons/*": ["../libs-ui/react-icons/src/*"],
31
- "@digigov/react-icons/": ["../libs-ui/react-icons/src"],
32
- "@digigov/react-icons": ["../libs-ui/react-icons/src"],
33
- "@digigov/react-experimental/*": ["../libs-ui/react-experimental/src/*"],
34
- "@digigov/react-experimental/": ["../libs-ui/react-experimental/src"],
35
- "@digigov/react-experimental": ["../libs-ui/react-experimental/src"],
36
- "@digigov/storybook/*": ["../examples/storybook/stories/*"],
37
- "@uides/stepwise/*": ["./stepwise/src/*"],
38
- "@uides/stepwise/": ["./stepwise/src"],
39
- "@uides/stepwise": ["./stepwise/src"]
40
- }
41
- },
42
- "include": [
43
- "../../libs/auth/src/**/*.tsx",
44
- "../../libs/auth/src/*.tsx",
45
- "../../libs/text-search/src/**/*.tsx",
46
- "../../libs/text-search/src/*.tsx",
47
- "../../libs/text-search/src/**/*.ts",
48
- "../../libs/text-search/src/*.ts",
49
- "../../libs/form/src/**/*.(tsx|ts)",
50
- "../../libs/form/src/*.(tsx|ts)",
51
- "../../libs/form-dilosi-integration/src/**/*.(tsx|ts)",
52
- "../../libs/form-dilosi-integration/src/*.(tsx|ts)",
53
- "../../libs/ui-dilosi-integration/src/**/*.(tsx|ts)",
54
- "../../libs/ui-dilosi-integration/src/*.(tsx|ts)",
55
- "../../libs/ui/src/**/*.(tsx|ts)",
56
- "../../libs/ui/src/*.(tsx|ts)",
57
- "../../libs/auth/src/**/*.tsx",
58
- "../../libs/auth/src/*.tsx",
59
- "../../libs/nextjs/**/*.tsx",
60
- "../../libs/nextjs/*.tsx"
61
- ]
3
+ "module": "ESNext",
4
+ "target": "es5",
5
+ "lib": ["es6", "dom", "es2019"],
6
+ "sourceMap": true,
7
+ "allowJs": true,
8
+ "jsx": "react",
9
+ "declaration": true,
10
+ "moduleResolution": "bundler",
11
+ "forceConsistentCasingInFileNames": true,
12
+ "noImplicitReturns": true,
13
+ "noImplicitThis": true,
14
+ "noImplicitAny": false,
15
+ "strictNullChecks": true,
16
+ "noUnusedLocals": true,
17
+ "noUnusedParameters": true,
18
+ "allowSyntheticDefaultImports": true,
19
+ "skipDefaultLibCheck": true,
20
+ "skipLibCheck": true,
21
+ "resolveJsonModule": true,
22
+ "isolatedModules": true
23
+ }
62
24
  }
package/tsconfig.json CHANGED
@@ -1,12 +1,8 @@
1
1
  {
2
2
  "extends": "@digigov/cli/tsconfig.cli",
3
3
  "compilerOptions": {
4
- "types": [
5
- "vitest/globals"
6
- ]
4
+ "types": ["vitest/globals"]
7
5
  },
8
- "include": [
9
- "./*.js",
10
- "__tests__"
11
- ]
6
+ "include": ["./*.js", "__tests__"],
7
+ "exclude": ["eslint.config.js", ".prettierrc.cjs"]
12
8
  }
package/babel.common.cjs DELETED
@@ -1,119 +0,0 @@
1
- // Mostly shared from
2
- // https://github.com/mui-org/material-ui/blob/master/babel.config.js
3
- const lib = require("@digigov/cli/lib");
4
-
5
- function makeBabelConfig(dir, opts = { docs: false, proptypes: false }) {
6
- const project = lib.resolveProject(dir);
7
- const aliases = !project.externalLockFile ? lib.aliases(true) : {};
8
-
9
- const BABEL_ENV = process.env.BABEL_ENV || "esm";
10
- const BABEL_PUBLISH = process.env.BABEL_PUBLISH || false;
11
- const NODE_ENV = process.env.NODE_ENV;
12
- const IS_COMMONJS = BABEL_ENV === "cjs" || NODE_ENV === "test";
13
-
14
- const PRESETS = [
15
- [
16
- require.resolve("@babel/preset-env"),
17
- {
18
- modules: IS_COMMONJS ? "commonjs" : false,
19
- },
20
- ],
21
- require.resolve("@babel/preset-react"),
22
- ];
23
-
24
- if (project.isTs) {
25
- PRESETS.push(require.resolve("@babel/preset-typescript"));
26
- }
27
-
28
- const PLUGINS_COMMON = [
29
- require.resolve("babel-plugin-optimize-clsx"),
30
- [
31
- require.resolve("@babel/plugin-proposal-class-properties"),
32
- { loose: true },
33
- ],
34
- [
35
- require.resolve("@babel/plugin-proposal-object-rest-spread"),
36
- { loose: true },
37
- ],
38
- // any package needs to declare 7.4.4 as a runtime dependency. default is ^7.0.0
39
- [require.resolve("@babel/plugin-transform-runtime"), { version: "^7.4.4" }],
40
- // for IE 11 support
41
- require.resolve("@babel/plugin-transform-object-assign"),
42
- require.resolve("babel-plugin-transform-react-constant-elements"),
43
- ];
44
-
45
- const PLUGINS_PUBLISH = [
46
- require.resolve("babel-plugin-transform-dev-warning"),
47
- [
48
- require.resolve("babel-plugin-react-remove-properties"),
49
- { properties: ["data-testid"] },
50
- ],
51
- [
52
- require.resolve("babel-plugin-transform-react-remove-prop-types"),
53
- {
54
- mode: "unsafe-wrap",
55
- },
56
- ],
57
- ];
58
-
59
- const PLUGINS = PLUGINS_COMMON;
60
-
61
- // Apps images are handled using `next-images` plugin. For libraries there is no
62
- // explicit way to provide assets to the App using the library. While not
63
- // considered a very good practice, one way to provide images via libraries is
64
- // to embed the image data into the library code.
65
- if (project.isLib || project.isApp) {
66
- PLUGINS.push(require.resolve("babel-plugin-inline-import-data-uri"));
67
- }
68
-
69
- if (BABEL_PUBLISH) {
70
- PLUGINS.push(...PLUGINS_PUBLISH);
71
- }
72
-
73
- if (!opts.docs) {
74
- let resolverAlias = {};
75
- if (NODE_ENV === "test") resolverAlias = aliases;
76
- if (BABEL_ENV === "cjs") {
77
- resolverAlias = Object.keys(aliases).reduce((acc, key) => {
78
- if (key !== project.name) {
79
- acc[`^${key}/(.+)`] = `${key}/cjs/\\1`;
80
- }
81
- return acc;
82
- }, {});
83
- }
84
-
85
- const RESOLVER = [
86
- require.resolve("babel-plugin-module-resolver"),
87
- {
88
- alias: resolverAlias,
89
- extensions: [".js", ".jsx", ".ts", ".tsx", ".json"],
90
- loglevel: "silent",
91
- },
92
- ];
93
- PLUGINS.push(RESOLVER);
94
- }
95
-
96
- if (project.isApp) {
97
- PRESETS.push(require.resolve("next/babel"));
98
- }
99
-
100
- const CONFIG = {
101
- presets: PRESETS,
102
- plugins: PLUGINS,
103
- ignore: [/@babel[\\|/]runtime/],
104
- env: {
105
- coverage: {
106
- plugins: [require.resolve("babel-plugin-istanbul")],
107
- },
108
- test: {
109
- sourceMaps: "both",
110
- plugins: [],
111
- },
112
- },
113
- };
114
- return CONFIG;
115
- }
116
- module.exports = {
117
- makeBabelConfig,
118
- config: makeBabelConfig(),
119
- };
package/babel.config.cjs DELETED
@@ -1 +0,0 @@
1
- module.exports = require("./babel.common.cjs").config;
package/build.js DELETED
@@ -1,93 +0,0 @@
1
- import { DigigovCommand, logger } from "@digigov/cli/lib";
2
-
3
- import assert from "assert";
4
- import path from "path";
5
- import fs from "fs-extra";
6
- import baseEsbuild from "esbuild";
7
-
8
- /**
9
- * Generate TypeScript declaration files
10
- *
11
- * @param {object} project - The project object
12
- * @param {string} project.root - The project root directory
13
- * @param {string} project.src - The project source directory
14
- * @param {string} project.distDir - The project build directory
15
- * @param {string} tsconfig - The tsconfig path
16
- * @param {DigigovCommand} ctx - The command context
17
- */
18
- export async function generateTypeDeclarationFiles(project, tsconfig, ctx) {
19
- logger.debug("Building types...");
20
-
21
- const distDir = path.resolve(project.root, project.distDir);
22
- const projectBasename = path.basename(project.root);
23
-
24
- await ctx.exec("tsc", [
25
- "--emitDeclarationOnly",
26
- "--outDir",
27
- "dist",
28
- "--project",
29
- tsconfig,
30
- ]);
31
-
32
- const projectBasePath = path.join(distDir, projectBasename);
33
- logger.debug("Project base path", projectBasePath);
34
- if (await fs.exists(projectBasePath)) {
35
- const typesIncluded = await fs.readdir(path.join(distDir));
36
- const srcPath = path.join(distDir, projectBasename, project.src);
37
- const paths = await fs.readdir(srcPath);
38
-
39
- await Promise.all([
40
- // Move src files to dist
41
- ...paths.map((p) => {
42
- logger.debug("Moving types file", p);
43
- fs.move(path.join(srcPath, p), path.join(distDir, p));
44
- }),
45
- // Remove dirs
46
- ...typesIncluded.map((typesDir) => {
47
- logger.debug("Removing types directory", typesDir);
48
- fs.rm(path.join(distDir, typesDir), { recursive: true });
49
- }),
50
- ]).catch((err) => {
51
- logger.error("Error while building types", err);
52
- });
53
- }
54
- logger.debug("Types built.");
55
- }
56
-
57
- /**
58
- * Run esbuild for the given options
59
- *
60
- * @param {object} options - The build options
61
- * @param {string[]} options.files - The files to build
62
- * @param {string | undefined} options.tsconfig - The tsconfig path
63
- * @param {"esm" | "cjs"} options.format - The module format
64
- * @param {string} options.outdir - The output directory
65
- * @param {boolean | undefined} [options.noLogs] - Whether to log debug information
66
- */
67
- export function buildFormat({
68
- files: entryPoints,
69
- tsconfig,
70
- format,
71
- outdir,
72
- noLogs,
73
- }) {
74
- assert(format === "esm" || format === "cjs", "Invalid format");
75
-
76
- if (!noLogs)
77
- logger.log(`Running: esbuild for ${format.toUpperCase()} format`);
78
- return baseEsbuild.build({
79
- ...BASE_OPTIONS,
80
- entryPoints,
81
- tsconfig,
82
- format,
83
- outdir,
84
- });
85
- }
86
-
87
- /** @type {baseEsbuild.BuildOptions} */
88
- export const BASE_OPTIONS = {
89
- logLevel: "error",
90
- platform: "node",
91
- sourcemap: true,
92
- target: ["esnext"],
93
- };
@@ -1,27 +0,0 @@
1
- {
2
- "compilerOptions": {
3
- "module": "ESNext",
4
- "target": "es5",
5
- "lib": [
6
- "es6",
7
- "dom",
8
- "es2019"
9
- ],
10
- "sourceMap": true,
11
- "allowJs": true,
12
- "jsx": "react",
13
- "declaration": true,
14
- "moduleResolution": "node",
15
- "forceConsistentCasingInFileNames": true,
16
- "noImplicitReturns": true,
17
- "noImplicitThis": true,
18
- "noImplicitAny": false,
19
- "strictNullChecks": true,
20
- "noUnusedLocals": true,
21
- "noUnusedParameters": true,
22
- "allowSyntheticDefaultImports": true,
23
- "skipDefaultLibCheck": true,
24
- "skipLibCheck": true,
25
- "resolveJsonModule": true
26
- }
27
- }