@ms-cloudpack/package-utilities 10.2.11 → 10.3.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/lib/addExportsMapEntry.d.ts +28 -13
- package/lib/addExportsMapEntry.d.ts.map +1 -1
- package/lib/addExportsMapEntry.js +88 -9
- package/lib/addExportsMapEntry.js.map +1 -1
- package/lib/createExportsMap.d.ts.map +1 -1
- package/lib/createExportsMap.js +13 -6
- package/lib/createExportsMap.js.map +1 -1
- package/lib/flattenExportsMap.js +26 -39
- package/lib/flattenExportsMap.js.map +1 -1
- package/package.json +4 -4
|
@@ -1,42 +1,57 @@
|
|
|
1
|
-
import type { CloudpackConfig, PackageDefinitionsCache,
|
|
1
|
+
import type { CloudpackConfig, PackageDefinitionsCache, GeneratedExports } from '@ms-cloudpack/common-types';
|
|
2
|
+
import { type FindFileInPackageResult } from './findFileInPackage.js';
|
|
2
3
|
/**
|
|
3
|
-
* Options
|
|
4
|
+
* Options for `addExportsMapEntry`.
|
|
4
5
|
*/
|
|
5
6
|
export interface AddExportsMapEntryOptions {
|
|
6
7
|
/**
|
|
7
|
-
* The exports map to add the entry to.
|
|
8
|
+
* The generated exports map to add the entry to.
|
|
8
9
|
*/
|
|
9
|
-
exports:
|
|
10
|
+
exports: GeneratedExports;
|
|
10
11
|
/**
|
|
11
12
|
* The package path to add the entry for. This is used to resolve relative paths.
|
|
12
13
|
*/
|
|
13
14
|
packagePath: string;
|
|
14
15
|
/**
|
|
15
|
-
* The import path to add the entry for. This is used as the key in the exports map.
|
|
16
|
-
* to
|
|
16
|
+
* The import path to add the entry for. This is used as the key in the exports map.
|
|
17
|
+
* Defaults to `'.'` (the package import).
|
|
17
18
|
*/
|
|
18
19
|
importPath?: string;
|
|
19
20
|
/**
|
|
20
|
-
* The relative path to the physical file location, representing the "key" in the exports map.
|
|
21
|
-
* location, in which case we
|
|
22
|
-
*
|
|
21
|
+
* The relative path to the physical file location, representing the "key" in the exports map.
|
|
22
|
+
* Can be a partial location, in which case we'll search for the file and associated source/d.ts files.
|
|
23
|
+
* Defaults to `importPath` if provided, or `'index.js'`.
|
|
23
24
|
*/
|
|
24
25
|
filePath?: string;
|
|
25
26
|
/**
|
|
26
|
-
*
|
|
27
|
+
* Module type condition to add the entry for.
|
|
28
|
+
* @default 'default'
|
|
27
29
|
*/
|
|
28
|
-
requestCondition?: 'import' | 'require' | '
|
|
30
|
+
requestCondition?: 'import' | 'require' | 'default';
|
|
29
31
|
/**
|
|
30
|
-
* The condition that describes the environment the entry is for.
|
|
32
|
+
* The condition that describes the environment the entry is for.
|
|
31
33
|
* Unspecified implies environmentally agnostic.
|
|
34
|
+
* - `browser` is used for cases such as `browser` entries in package.json or implicit exports defined in routes.
|
|
35
|
+
* - `node` is used for server rendering.
|
|
32
36
|
*/
|
|
33
37
|
environmentCondition?: 'browser' | 'node';
|
|
34
38
|
}
|
|
35
39
|
/**
|
|
36
|
-
*
|
|
40
|
+
* Add an import path to an exports map. This is intended for use with generated exports maps,
|
|
41
|
+
* either in the context of the generated config, or generated for a package which doesn't have
|
|
42
|
+
* an exports map.
|
|
43
|
+
*
|
|
44
|
+
* Throws an error if the exports map passed in is not an object, or if the value of the key
|
|
45
|
+
* being updated is an array (it should have been normalized to object format before calling).
|
|
37
46
|
*/
|
|
38
47
|
export declare function addExportsMapEntry(options: AddExportsMapEntryOptions, context: {
|
|
39
48
|
packages: PackageDefinitionsCache;
|
|
40
49
|
config: Pick<CloudpackConfig, 'features'>;
|
|
41
50
|
}): Promise<boolean>;
|
|
51
|
+
/**
|
|
52
|
+
* Internal logic of adding an entry to an exports map.
|
|
53
|
+
* Exported for testing this logic separately from the filesystem parts.
|
|
54
|
+
* @internal
|
|
55
|
+
*/
|
|
56
|
+
export declare function _addEntry(options: Omit<AddExportsMapEntryOptions, 'packagePath' | 'filePath'>, foundFile: FindFileInPackageResult): boolean;
|
|
42
57
|
//# sourceMappingURL=addExportsMapEntry.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"addExportsMapEntry.d.ts","sourceRoot":"","sources":["../src/addExportsMapEntry.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,uBAAuB,EAAE,
|
|
1
|
+
{"version":3,"file":"addExportsMapEntry.d.ts","sourceRoot":"","sources":["../src/addExportsMapEntry.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,uBAAuB,EAAE,gBAAgB,EAAE,MAAM,4BAA4B,CAAC;AAE7G,OAAO,EAAqB,KAAK,uBAAuB,EAAE,MAAM,wBAAwB,CAAC;AAEzF;;GAEG;AACH,MAAM,WAAW,yBAAyB;IACxC;;OAEG;IACH,OAAO,EAAE,gBAAgB,CAAC;IAE1B;;OAEG;IACH,WAAW,EAAE,MAAM,CAAC;IAEpB;;;OAGG;IACH,UAAU,CAAC,EAAE,MAAM,CAAC;IAEpB;;;;OAIG;IACH,QAAQ,CAAC,EAAE,MAAM,CAAC;IAElB;;;OAGG;IACH,gBAAgB,CAAC,EAAE,QAAQ,GAAG,SAAS,GAAG,SAAS,CAAC;IAEpD;;;;;OAKG;IACH,oBAAoB,CAAC,EAAE,SAAS,GAAG,MAAM,CAAC;CAC3C;AAED;;;;;;;GAOG;AACH,wBAAsB,kBAAkB,CACtC,OAAO,EAAE,yBAAyB,EAClC,OAAO,EAAE;IAAE,QAAQ,EAAE,uBAAuB,CAAC;IAAC,MAAM,EAAE,IAAI,CAAC,eAAe,EAAE,UAAU,CAAC,CAAA;CAAE,GACxF,OAAO,CAAC,OAAO,CAAC,CAkBlB;AAED;;;;GAIG;AACH,wBAAgB,SAAS,CACvB,OAAO,EAAE,IAAI,CAAC,yBAAyB,EAAE,aAAa,GAAG,UAAU,CAAC,EACpE,SAAS,EAAE,uBAAuB,GACjC,OAAO,CAgDT"}
|
|
@@ -1,24 +1,50 @@
|
|
|
1
1
|
import { normalizeRelativePath } from '@ms-cloudpack/path-string-parsing';
|
|
2
2
|
import { findFileInPackage } from './findFileInPackage.js';
|
|
3
3
|
/**
|
|
4
|
-
*
|
|
4
|
+
* Add an import path to an exports map. This is intended for use with generated exports maps,
|
|
5
|
+
* either in the context of the generated config, or generated for a package which doesn't have
|
|
6
|
+
* an exports map.
|
|
7
|
+
*
|
|
8
|
+
* Throws an error if the exports map passed in is not an object, or if the value of the key
|
|
9
|
+
* being updated is an array (it should have been normalized to object format before calling).
|
|
5
10
|
*/
|
|
6
11
|
export async function addExportsMapEntry(options, context) {
|
|
7
|
-
const { exports, packagePath
|
|
8
|
-
|
|
9
|
-
|
|
12
|
+
const { exports, packagePath } = options;
|
|
13
|
+
// We try to enforce these conditions in the types, but also do an explicit check in case of
|
|
14
|
+
// casting or other unexpected input.
|
|
15
|
+
if (exports === null || Array.isArray(exports) || typeof exports === 'string') {
|
|
16
|
+
throw new Error(`Exports passed to addExportsMapEntry must be an object; received: ${JSON.stringify(exports)}`);
|
|
17
|
+
}
|
|
18
|
+
const foundFile = await findFileInPackage({
|
|
10
19
|
packagePath,
|
|
11
20
|
filePath: options.filePath || options.importPath || '',
|
|
12
21
|
}, context);
|
|
22
|
+
return _addEntry(options, foundFile);
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* Internal logic of adding an entry to an exports map.
|
|
26
|
+
* Exported for testing this logic separately from the filesystem parts.
|
|
27
|
+
* @internal
|
|
28
|
+
*/
|
|
29
|
+
export function _addEntry(options, foundFile) {
|
|
30
|
+
const { exports, environmentCondition, requestCondition = 'default' } = options;
|
|
31
|
+
const { filePath, sourcePath } = foundFile;
|
|
13
32
|
// Only do work if a file path was found.
|
|
14
33
|
if (!filePath) {
|
|
15
34
|
return false;
|
|
16
35
|
}
|
|
17
|
-
//
|
|
18
|
-
const
|
|
36
|
+
// Normalize the import path (this also converts undefined to '.')
|
|
37
|
+
const importPath = normalizeRelativePath(options.importPath);
|
|
38
|
+
const oldEntry = exports[importPath];
|
|
39
|
+
if (Array.isArray(oldEntry)) {
|
|
40
|
+
// This should never happen with the standardized generated exports map format.
|
|
41
|
+
// In theory we could handle it by pushing to the array, but nesting conditions inside arrays
|
|
42
|
+
// isn't valid in the exports map spec.
|
|
43
|
+
throw new Error(`Cannot add to an array of exports for "${importPath}"`);
|
|
44
|
+
}
|
|
19
45
|
let exportValue;
|
|
20
|
-
// If this is the only entry we're adding, set it to a string to minimize the exports map.
|
|
21
46
|
if (!sourcePath && !requestCondition) {
|
|
47
|
+
// If this is the only entry we're adding, set it to a string to minimize the exports map.
|
|
22
48
|
exportValue = filePath;
|
|
23
49
|
}
|
|
24
50
|
else {
|
|
@@ -27,9 +53,62 @@ export async function addExportsMapEntry(options, context) {
|
|
|
27
53
|
exportValue['source'] = sourcePath;
|
|
28
54
|
}
|
|
29
55
|
// Add the entry for the condition.
|
|
30
|
-
exportValue[requestCondition
|
|
56
|
+
exportValue[requestCondition] = filePath;
|
|
57
|
+
if (requestCondition === 'default' && Object.keys(exportValue).length === 1) {
|
|
58
|
+
// Only the default condition is present, so flatten to a string
|
|
59
|
+
exportValue = filePath;
|
|
60
|
+
}
|
|
31
61
|
}
|
|
32
|
-
|
|
62
|
+
const newEntry = environmentCondition
|
|
63
|
+
? { [environmentCondition]: exportValue }
|
|
64
|
+
: exportValue;
|
|
65
|
+
exports[importPath] = mergeEntries({ oldEntry, newEntry });
|
|
33
66
|
return true;
|
|
34
67
|
}
|
|
68
|
+
/**
|
|
69
|
+
* This handles the merging of potential nested environment and request conditions, and ensures that
|
|
70
|
+
* the `default` key is in the correct order (always last).
|
|
71
|
+
*/
|
|
72
|
+
function mergeEntries(params) {
|
|
73
|
+
const { oldEntry, newEntry } = params;
|
|
74
|
+
if (!oldEntry) {
|
|
75
|
+
return newEntry;
|
|
76
|
+
}
|
|
77
|
+
// If oldEntry is a string... (using !== object instead of === string so TS infers the correct type later)
|
|
78
|
+
if (typeof oldEntry !== 'object') {
|
|
79
|
+
// If newEntry is an object without a default, use oldEntry as the default.
|
|
80
|
+
if (typeof newEntry === 'object' && !newEntry.default) {
|
|
81
|
+
return { ...newEntry, default: oldEntry };
|
|
82
|
+
}
|
|
83
|
+
// Otherwise ignore oldEntry.
|
|
84
|
+
return newEntry;
|
|
85
|
+
}
|
|
86
|
+
if (typeof newEntry !== 'object') {
|
|
87
|
+
// oldEntry object, newEntry string => use newEntry as default
|
|
88
|
+
return { ...oldEntry, default: newEntry };
|
|
89
|
+
}
|
|
90
|
+
// both objects => full merge (the typings get imprecise here)
|
|
91
|
+
const merged = {};
|
|
92
|
+
// put the new keys first in the merged object (this could be made configurable later if needed)
|
|
93
|
+
const allKeys = new Set([...Object.keys(newEntry), ...Object.keys(oldEntry)]);
|
|
94
|
+
for (const key of allKeys) {
|
|
95
|
+
if (newEntry[key]) {
|
|
96
|
+
merged[key] = mergeEntries({ oldEntry: oldEntry[key], newEntry: newEntry[key] });
|
|
97
|
+
}
|
|
98
|
+
else {
|
|
99
|
+
merged[key] = oldEntry[key];
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
const defaultValue = merged.default;
|
|
103
|
+
if (defaultValue) {
|
|
104
|
+
if (Object.keys(merged).length === 1) {
|
|
105
|
+
// flatten out the default condition
|
|
106
|
+
return defaultValue;
|
|
107
|
+
}
|
|
108
|
+
// ensure the default is last (exports maps keys are ordered)
|
|
109
|
+
delete merged.default;
|
|
110
|
+
merged.default = defaultValue;
|
|
111
|
+
}
|
|
112
|
+
return merged;
|
|
113
|
+
}
|
|
35
114
|
//# sourceMappingURL=addExportsMapEntry.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"addExportsMapEntry.js","sourceRoot":"","sources":["../src/addExportsMapEntry.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,qBAAqB,EAAE,MAAM,mCAAmC,CAAC;AAC1E,OAAO,EAAE,iBAAiB,
|
|
1
|
+
{"version":3,"file":"addExportsMapEntry.js","sourceRoot":"","sources":["../src/addExportsMapEntry.ts"],"names":[],"mappings":"AACA,OAAO,EAAE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loudpackConfig, PackageDefinitionsCache, GeneratedExports } from '@ms-cloudpack/common-types';\nimport { normalizeRelativePath } from '@ms-cloudpack/path-string-parsing';\nimport { findFileInPackage, type FindFileInPackageResult } from './findFileInPackage.js';\n\n/**\n * Options for `addExportsMapEntry`.\n */\nexport interface AddExportsMapEntryOptions {\n /**\n * The generated exports map to add the entry to.\n */\n exports: GeneratedExports;\n\n /**\n * The package path to add the entry for. This is used to resolve relative paths.\n */\n packagePath: string;\n\n /**\n * The import path to add the entry for. This is used as the key in the exports map.\n * Defaults to `'.'` (the package import).\n */\n importPath?: string;\n\n /**\n * The relative path to the physical file location, representing the \"key\" in the exports map.\n * Can be a partial location, in which case we'll search for the file and associated source/d.ts files.\n * Defaults to `importPath` if provided, or `'index.js'`.\n */\n filePath?: string;\n\n /**\n * Module type condition to add the entry for.\n * @default 'default'\n */\n requestCondition?: 'import' | 'require' | 'default';\n\n /**\n * The condition that describes the environment the entry is for.\n * Unspecified implies environmentally agnostic.\n * - `browser` is used for cases such as `browser` entries in package.json or implicit exports defined in routes.\n * - `node` is used for server rendering.\n */\n environmentCondition?: 'browser' | 'node';\n}\n\n/**\n * Add an import path to an exports map. This is intended for use with generated exports maps,\n * either in the context of the generated config, or generated for a package which doesn't have\n * an exports map.\n *\n * Throws an error if the exports map passed in is not an object, or if the value of the key\n * being updated is an array (it should have been normalized to object format before calling).\n */\nexport async function addExportsMapEntry(\n options: AddExportsMapEntryOptions,\n context: { packages: PackageDefinitionsCache; config: Pick<CloudpackConfig, 'features'> },\n): Promise<boolean> {\n const { exports, packagePath } = options;\n\n // We try to enforce these conditions in the types, but also do an explicit check in case of\n // casting or other unexpected input.\n if (exports === null || Array.isArray(exports) || typeof exports === 'string') {\n throw new Error(`Exports passed to addExportsMapEntry must be an object; received: ${JSON.stringify(exports)}`);\n }\n\n const foundFile = await findFileInPackage(\n {\n packagePath,\n filePath: options.filePath || options.importPath || '',\n },\n context,\n );\n\n return _addEntry(options, foundFile);\n}\n\n/**\n * Internal logic of adding an entry to an exports map.\n * Exported for testing this logic separately from the filesystem parts.\n * @internal\n */\nexport function _addEntry(\n options: Omit<AddExportsMapEntryOptions, 'packagePath' | 'filePath'>,\n foundFile: FindFileInPackageResult,\n): boolean {\n const { exports, environmentCondition, requestCondition = 'default' } = options;\n const { filePath, sourcePath } = foundFile;\n\n // Only do work if a file path was found.\n if (!filePath) {\n return false;\n }\n\n // Normalize the import path (this also converts undefined to '.')\n const importPath = normalizeRelativePath(options.importPath);\n\n const oldEntry = exports[importPath];\n if (Array.isArray(oldEntry)) {\n // This should never happen with the standardized generated exports map format.\n // In theory we could handle it by pushing to the array, but nesting conditions inside arrays\n // isn't valid in the exports map spec.\n throw new Error(`Cannot add to an array of exports for \"${importPath}\"`);\n }\n\n let exportValue: string | Record<string, string>;\n\n if (!sourcePath && !requestCondition) {\n // If this is the only entry we're adding, set it to a string to minimize the exports map.\n exportValue = filePath;\n } else {\n exportValue = {};\n\n if (sourcePath) {\n exportValue['source'] = sourcePath;\n }\n\n // Add the entry for the condition.\n exportValue[requestCondition] = filePath;\n\n if (requestCondition === 'default' && Object.keys(exportValue).length === 1) {\n // Only the default condition is present, so flatten to a string\n exportValue = filePath;\n }\n }\n\n const newEntry: GeneratedExports[string] = environmentCondition\n ? { [environmentCondition]: exportValue }\n : exportValue;\n\n exports[importPath] = mergeEntries({ oldEntry, newEntry });\n\n return true;\n}\n\n/**\n * This handles the merging of potential nested environment and request conditions, and ensures that\n * the `default` key is in the correct order (always last).\n */\nfunction mergeEntries<T extends string | Record<string, T>>(params: {\n oldEntry: T | null | undefined;\n newEntry: T;\n}): T {\n const { oldEntry, newEntry } = params;\n\n if (!oldEntry) {\n return newEntry;\n }\n\n // If oldEntry is a string... (using !== object instead of === string so TS infers the correct type later)\n if (typeof oldEntry !== 'object') {\n // If newEntry is an object without a default, use oldEntry as the default.\n if (typeof newEntry === 'object' && !newEntry.default) {\n return { ...newEntry, default: oldEntry };\n }\n // Otherwise ignore oldEntry.\n return newEntry;\n }\n\n if (typeof newEntry !== 'object') {\n // oldEntry object, newEntry string => use newEntry as default\n return { ...oldEntry, default: newEntry };\n }\n\n // both objects => full merge (the typings get imprecise here)\n const merged: Record<string, T> = {};\n // put the new keys first in the merged object (this could be made configurable later if needed)\n const allKeys = new Set([...Object.keys(newEntry), ...Object.keys(oldEntry)]);\n for (const key of allKeys) {\n if (newEntry[key]) {\n merged[key] = mergeEntries({ oldEntry: oldEntry[key], newEntry: newEntry[key] });\n } else {\n merged[key] = oldEntry[key];\n }\n }\n\n const defaultValue = merged.default;\n if (defaultValue) {\n if (Object.keys(merged).length === 1) {\n // flatten out the default condition\n return defaultValue;\n }\n\n // ensure the default is last (exports maps keys are ordered)\n delete merged.default;\n merged.default = defaultValue;\n }\n\n return merged as T;\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createExportsMap.d.ts","sourceRoot":"","sources":["../src/createExportsMap.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,
|
|
1
|
+
{"version":3,"file":"createExportsMap.d.ts","sourceRoot":"","sources":["../src/createExportsMap.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,eAAe,EACf,uBAAuB,EACvB,kBAAkB,EAEnB,MAAM,4BAA4B,CAAC;AAIpC;;GAEG;AACH,wBAAsB,gBAAgB,CACpC,OAAO,EAAE;IACP,WAAW,EAAE,MAAM,CAAC;IACpB,iBAAiB,CAAC,EAAE,OAAO,CAAC;CAC7B,EACD,OAAO,EAAE;IAAE,QAAQ,EAAE,uBAAuB,CAAC;IAAC,MAAM,EAAE,IAAI,CAAC,eAAe,EAAE,UAAU,CAAC,CAAA;CAAE,GACxF,OAAO,CAAC,kBAAkB,CAAC,CAqG7B"}
|
package/lib/createExportsMap.js
CHANGED
|
@@ -12,6 +12,8 @@ export async function createExportsMap(options, context) {
|
|
|
12
12
|
return definition.exports;
|
|
13
13
|
}
|
|
14
14
|
const { browser, main, module, type } = definition;
|
|
15
|
+
// Use the GeneratedExports type internally because it matches up with the more constrained
|
|
16
|
+
// format of the exports map we're creating here (and addExportsMapEntry requires this type).
|
|
15
17
|
const exports = {};
|
|
16
18
|
// Only try to add `index.js` as an entry if main/module/browser isn't available.
|
|
17
19
|
if (!(main || module || browser)) {
|
|
@@ -40,17 +42,21 @@ export async function createExportsMap(options, context) {
|
|
|
40
42
|
}
|
|
41
43
|
if (browser) {
|
|
42
44
|
if (typeof definition.browser === 'string') {
|
|
43
|
-
await addExportsMapEntry({ exports, packagePath, filePath: definition.browser,
|
|
45
|
+
await addExportsMapEntry({ exports, packagePath, filePath: definition.browser, environmentCondition: 'browser' }, context);
|
|
44
46
|
}
|
|
45
47
|
else if (typeof definition.browser === 'object') {
|
|
46
48
|
for (const [key, value] of Object.entries(definition.browser)) {
|
|
47
49
|
if (!value || typeof value !== 'string') {
|
|
48
50
|
continue;
|
|
49
51
|
}
|
|
50
|
-
const
|
|
51
|
-
const
|
|
52
|
-
|
|
53
|
-
|
|
52
|
+
const isDefaultModule = normalizeRelativePath(module) === normalizeRelativePath(key);
|
|
53
|
+
const isDefaultMain = normalizeRelativePath(main) === normalizeRelativePath(key);
|
|
54
|
+
let importPaths;
|
|
55
|
+
if (isDefaultMain || isDefaultModule) {
|
|
56
|
+
importPaths = ['.'];
|
|
57
|
+
}
|
|
58
|
+
else {
|
|
59
|
+
importPaths = [key, key.replace(/\.js$/, '')];
|
|
54
60
|
}
|
|
55
61
|
for (const importPath of importPaths) {
|
|
56
62
|
await addExportsMapEntry({
|
|
@@ -58,7 +64,8 @@ export async function createExportsMap(options, context) {
|
|
|
58
64
|
packagePath,
|
|
59
65
|
importPath,
|
|
60
66
|
filePath: value,
|
|
61
|
-
|
|
67
|
+
environmentCondition: 'browser',
|
|
68
|
+
requestCondition: isDefaultModule || (isDefaultMain && type === 'module') ? 'import' : undefined,
|
|
62
69
|
}, context);
|
|
63
70
|
}
|
|
64
71
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createExportsMap.js","sourceRoot":"","sources":["../src/createExportsMap.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"createExportsMap.js","sourceRoot":"","sources":["../src/createExportsMap.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,qBAAqB,EAAE,MAAM,mCAAmC,CAAC;AAC1E,OAAO,EAAE,kBAAkB,EAAE,MAAM,yBAAyB,CAAC;AAE7D;;GAEG;AACH,MAAM,CAAC,KAAK,UAAU,gBAAgB,CACpC,OAGC,EACD,OAAyF;IAEzF,MAAM,EAAE,WAAW,EAAE,GAAG,OAAO,CAAC;IAChC,MAAM,EAAE,QAAQ,EAAE,GAAG,OAAO,CAAC;IAC7B,MAAM,UAAU,GAAG,MAAM,QAAQ,CAAC,GAAG,CAAC,WAAW,EAAE,EAAE,iBAAiB,EAAE,OAAO,CAAC,iBAAiB,EAAE,CAAC,CAAC;IAErG,qEAAqE;IACrE,IAAI,UAAU,CAAC,OAAO,EAAE,CAAC;QACvB,OAAO,UAAU,CAAC,OAAO,CAAC;IAC5B,CAAC;IAED,MAAM,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,GAAG,UAAU,CAAC;IACnD,2FAA2F;IAC3F,6FAA6F;IAC7F,MAAM,OAAO,GAAqB,EAAE,CAAC;IAErC,iFAAiF;IACjF,IAAI,CAAC,CAAC,IAAI,IAAI,MAAM,IAAI,OAAO,CAAC,EAAE,CAAC;QACjC,MAAM,kBAAkB,CACtB;YACE,OAAO;YACP,WAAW;YACX,QAAQ,EAAE,UAAU;YACpB,gBAAgB,EAAE,IAAI,KAAK,QAAQ,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,SAAS;SAC3D,EACD,OAAO,CACR,CAAC;IACJ,CAAC;IAED,IAAI,IAAI,EAAE,CAAC;QACT,MAAM,kBAAkB,CACtB;YACE,OAAO;YACP,WAAW;YACX,QAAQ,EAAE,IAAI;YACd,gBAAgB,EAAE,IAAI,KAAK,QAAQ,C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AI,WAAW,EAAE,CAAC;oBACrC,MAAM,kBAAkB,CACtB;wBACE,OAAO;wBACP,WAAW;wBACX,UAAU;wBACV,QAAQ,EAAE,KAAK;wBACf,oBAAoB,EAAE,SAAS;wBAC/B,gBAAgB,EAAE,eAAe,IAAI,CAAC,aAAa,IAAI,IAAI,KAAK,QAAQ,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,SAAS;qBACjG,EACD,OAAO,CACR,CAAC;gBACJ,CAAC;YACH,CAAC;QACH,CAAC;IACH,CAAC;IAED,qEAAqE;IACrE,+CAA+C;IAC/C,mEAAmE;IACnE,IAAI,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QACtC,CAAC,MAAM,kBAAkB,CAAC,EAAE,OAAO,EAAE,WAAW,EAAE,QAAQ,EAAE,gBAAgB,EAAE,EAAE,OAAO,CAAC,CAAC;YACvF,CAAC,MAAM,kBAAkB,CAAC,EAAE,OAAO,EAAE,WAAW,EAAE,QAAQ,EAAE,eAAe,EAAE,EAAE,OAAO,CAAC,CAAC;YACxF,CAAC,MAAM,kBAAkB,CAAC,EAAE,OAAO,EAAE,WAAW,EAAE,QAAQ,EAAE,YAAY,EAAE,EAAE,OAAO,CAAC,CAAC,CAAC;IAC1F,CAAC;IAED,OAAO,OAAO,CAAC;AACjB,CAAC","sourcesContent":["import type {\n CloudpackConfig,\n PackageDefinitionsCache,\n PackageJsonExports,\n GeneratedExports,\n} from '@ms-cloudpack/common-types';\nimport { normalizeRelativePath } from '@ms-cloudpack/path-string-parsing';\nimport { addExportsMapEntry } from './addExportsMapEntry.js';\n\n/**\n * Given a package path, generates an export map for the package.\n */\nexport async function createExportsMap(\n options: {\n packagePath: string;\n disableTransforms?: boolean;\n },\n context: { packages: PackageDefinitionsCache; config: Pick<CloudpackConfig, 'features'> },\n): Promise<PackageJsonExports> {\n const { packagePath } = options;\n const { packages } = context;\n const definition = await packages.get(packagePath, { disableTransforms: options.disableTransforms });\n\n // Don't create an exports map for a definition that already has one.\n if (definition.exports) {\n return definition.exports;\n }\n\n const { browser, main, module, type } = definition;\n // Use the GeneratedExports type internally because it matches up with the more constrained\n // format of the exports map we're creating here (and addExportsMapEntry requires this type).\n const exports: GeneratedExports = {};\n\n // Only try to add `index.js` as an entry if main/module/browser isn't available.\n if (!(main || module || browser)) {\n await addExportsMapEntry(\n {\n exports,\n packagePath,\n filePath: 'index.js',\n requestCondition: type === 'module' ? 'import' : undefined,\n },\n context,\n );\n }\n\n if (main) {\n await addExportsMapEntry(\n {\n exports,\n packagePath,\n filePath: main,\n requestCondition: type === 'module' ? 'import' : undefined,\n },\n context,\n );\n }\n\n if (module) {\n await addExportsMapEntry(\n {\n exports,\n packagePath,\n filePath: module,\n requestCondition: 'import',\n },\n context,\n );\n }\n\n if (browser) {\n if (typeof definition.browser === 'string') {\n await addExportsMapEntry(\n { exports, packagePath, filePath: definition.browser, environmentCondition: 'browser' },\n context,\n );\n } else if (typeof definition.browser === 'object') {\n for (const [key, value] of Object.entries(definition.browser)) {\n if (!value || typeof value !== 'string') {\n continue;\n }\n\n const isDefaultModule = normalizeRelativePath(module) === normalizeRelativePath(key);\n const isDefaultMain = normalizeRelativePath(main) === normalizeRelativePath(key);\n\n let importPaths: string[];\n if (isDefaultMain || isDefaultModule) {\n importPaths = ['.'];\n } else {\n importPaths = [key, key.replace(/\\.js$/, '')];\n }\n\n for (const importPath of importPaths) {\n await addExportsMapEntry(\n {\n exports,\n packagePath,\n importPath,\n filePath: value,\n environmentCondition: 'browser',\n requestCondition: isDefaultModule || (isDefaultMain && type === 'module') ? 'import' : undefined,\n },\n context,\n );\n }\n }\n }\n }\n\n // If we couldn't infer the exports map shape from existing metadata,\n // formulate based off inferred file structure.\n // Note: CRA defaults to src/index.js, Vite defaults to src/main.js\n if (Object.keys(exports).length === 0) {\n (await addExportsMapEntry({ exports, packagePath, filePath: './lib/index.js' }, context)) ||\n (await addExportsMapEntry({ exports, packagePath, filePath: './lib/main.js' }, context)) ||\n (await addExportsMapEntry({ exports, packagePath, filePath: './index.js' }, context));\n }\n\n return exports;\n}\n"]}
|
package/lib/flattenExportsMap.js
CHANGED
|
@@ -40,37 +40,26 @@ export function flattenExportsMap(exportsMap, options = {}) {
|
|
|
40
40
|
*
|
|
41
41
|
* @returns The cumulative flat exports map.
|
|
42
42
|
*/
|
|
43
|
-
function extractExports(
|
|
43
|
+
function extractExports(params) {
|
|
44
|
+
const { exports, conditions, requiredConditions, flatExports, matchedConditions, packagePath, importMatch } = params;
|
|
44
45
|
if (typeof exports === 'string' &&
|
|
45
46
|
(!requiredConditions || requiredConditions.every((condition) => matchedConditions.includes(condition)))) {
|
|
46
47
|
addExportsEntry({ flatExports, key: importMatch, value: exports, packagePath });
|
|
47
48
|
}
|
|
48
49
|
else if (Array.isArray(exports)) {
|
|
49
50
|
for (const exportEntry of exports) {
|
|
50
|
-
extractExports({
|
|
51
|
-
exports: exportEntry,
|
|
52
|
-
conditions,
|
|
53
|
-
requiredConditions,
|
|
54
|
-
flatExports,
|
|
55
|
-
importMatch,
|
|
56
|
-
matchedConditions,
|
|
57
|
-
packagePath,
|
|
58
|
-
});
|
|
51
|
+
extractExports({ ...params, exports: exportEntry });
|
|
59
52
|
}
|
|
60
53
|
}
|
|
61
54
|
else if (exports && typeof exports === 'object') {
|
|
62
55
|
// Iterate through condition matches and go deeper if a match is found.
|
|
63
56
|
for (const condition of conditions) {
|
|
64
|
-
const
|
|
65
|
-
if (
|
|
57
|
+
const conditionExports = exports[condition];
|
|
58
|
+
if (conditionExports) {
|
|
66
59
|
extractExports({
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
requiredConditions,
|
|
70
|
-
flatExports,
|
|
71
|
-
importMatch,
|
|
60
|
+
...params,
|
|
61
|
+
exports: conditionExports,
|
|
72
62
|
matchedConditions: matchedConditions.concat(condition),
|
|
73
|
-
packagePath,
|
|
74
63
|
});
|
|
75
64
|
// Stop at the first match.
|
|
76
65
|
return flatExports;
|
|
@@ -78,28 +67,25 @@ function extractExports({ exports, conditions, requiredConditions, flatExports =
|
|
|
78
67
|
}
|
|
79
68
|
// No conditions are available. Check for import entries.
|
|
80
69
|
for (const [key, value] of Object.entries(exports)) {
|
|
81
|
-
if (key.startsWith('.')) {
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
}
|
|
87
|
-
}
|
|
88
|
-
else if (value) {
|
|
89
|
-
extractExports({
|
|
90
|
-
exports: value,
|
|
91
|
-
conditions,
|
|
92
|
-
requiredConditions,
|
|
93
|
-
flatExports,
|
|
94
|
-
importMatch,
|
|
95
|
-
matchedConditions: [...matchedConditions, key],
|
|
96
|
-
packagePath,
|
|
97
|
-
});
|
|
98
|
-
}
|
|
99
|
-
else {
|
|
100
|
-
delete flatExports[key];
|
|
70
|
+
if (!key.startsWith('.')) {
|
|
71
|
+
continue; // not a path
|
|
72
|
+
}
|
|
73
|
+
if (typeof value === 'string') {
|
|
74
|
+
if (!flatExports[key] && (!requiredConditions || requiredConditions?.includes(key))) {
|
|
75
|
+
addExportsEntry({ flatExports, key, value, packagePath });
|
|
101
76
|
}
|
|
102
77
|
}
|
|
78
|
+
else if (value) {
|
|
79
|
+
extractExports({
|
|
80
|
+
...params,
|
|
81
|
+
exports: value,
|
|
82
|
+
importMatch: key,
|
|
83
|
+
matchedConditions: [...matchedConditions, key],
|
|
84
|
+
});
|
|
85
|
+
}
|
|
86
|
+
else {
|
|
87
|
+
delete flatExports[key];
|
|
88
|
+
}
|
|
103
89
|
}
|
|
104
90
|
}
|
|
105
91
|
return flatExports;
|
|
@@ -110,7 +96,8 @@ function extractExports({ exports, conditions, requiredConditions, flatExports =
|
|
|
110
96
|
*
|
|
111
97
|
* Does nothing if the key contains a wildcard or a trailing slash and the value does not, such as it being `null`.
|
|
112
98
|
*/
|
|
113
|
-
function addExportsEntry(
|
|
99
|
+
function addExportsEntry(params) {
|
|
100
|
+
const { flatExports, key, value, packagePath } = params;
|
|
114
101
|
const basename = path.basename(value);
|
|
115
102
|
const isValid = basename !== '' && basename !== '.';
|
|
116
103
|
const isMany = value.endsWith('/') || value.indexOf('*') !== -1 || key.indexOf('*') !== -1 || key.endsWith('/');
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"flattenExportsMap.js","sourceRoot":"","sources":["../src/flattenExportsMap.ts"],"names":[],"mappings":"AAAA,OAAO,IAAI,MAAM,MAAM,CAAC;AAExB,OAAO,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAC7C,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,EAAE,kBAAkB,EAAE,MAAM,yBAAyB,CAAC;AAE7D,MAAM,iBAAiB,GAAG,CAAC,SAAS,EAAE,QAAQ,EAAE,QAAQ,EAAE,SAAS,CAAC,CAAC;AAErE;;;;;;;;;;;;;GAaG;AACH,MAAM,UAAU,iBAAiB,CAC/B,UAA8B,EAC9B,UAII,EAAE;IAEN,MAAM,EAAE,kBAAkB,EAAE,WAAW,EAAE,GAAG,OAAO,CAAC;IAEpD,MAAM,UAAU,GAAG,kBAAkB,CAAC,OAAO,CAAC,UAAU,EAAE,iBAAiB,CAAC,CAAC;IAE7E,IAAI,OAAO,UAAU,KAAK,QAAQ,IAAI,UAAU,CAAC,QAAQ,CAAC,SAAS,CAAC,EAAE,CAAC;QACrE,OAAO;YACL,GAAG,EAAE,UAAU,CAAC,UAAU,CAAC;SAC5B,CAAC;IACJ,CAAC;IAED,OAAO,cAAc,CAAC;QACpB,OAAO,EAAE,UAAU;QACnB,UAAU;QACV,kBAAkB;QAClB,WAAW,EAAE,EAAE;QACf,WAAW,EAAE,GAAG;QAChB,iBAAiB,EAAE,EAAE;QACrB,WAAW;KACZ,CAAC,CAAC;AACL,CAAC;AAED;;;;GAIG;AACH,SAAS,cAAc,CAAC,EACtB,OAAO,EACP,UAAU,EACV,kBAAkB,EAClB,WAAW,GAAG,EAAE,EAChB,WAAW,GAAG,GAAG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CAAC,SAAS,CAAC,aAAa,GAAG,CAAC,CAAC,CAAC;IACzF,CAAC;AACH,CAAC;AAED;;;;;;GAMG;AACH,SAAS,WAAW,CAAC,KAAa,EAAE,gBAAwB,KAAK,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC,CAAC;IAC/E,IAAI,KAAK,CAAC,QAAQ,CAAC,GAAG,CAAC,EAAE,CAAC;QACxB,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE,GAAG,EAAE,EAAE,EAAE,CAAC;IACnC,CAAC;SAAM,IAAI,aAAa,KAAK,CAAC,CAAC,EAAE,CAAC;QAChC,OAAO;YACL,KAAK,EAAE,KAAK,CAAC,SAAS,CAAC,CAAC,EAAE,aAAa,CAAC;YACxC,GAAG,EAAE,KAAK,CAAC,SAAS,CAAC,aAAa,GAAG,CAAC,CAAC;SACxC,CAAC;IACJ,CAAC;AACH,CAAC","sourcesContent":["import path from 'path';\nimport type { PackageJsonExportsObject, PackageJsonExports } from '@ms-cloudpack/common-types';\nimport { cleanEntry } from './cleanEntry.js';\nimport glob from 'fast-glob';\nimport { mergeArrayDefaults } from './mergeArrayDefaults.js';\n\nconst defaultConditions = ['browser', 'module', 'import', 'default'];\n\n/**\n * Given a package definition and applicable conditions, return a flat map of package import to physical (relative) path.\n * Optionally return the exports map fully qualified with conditions intact using the `fullExports` option.\n * Optionally takes in a `packagePath` to resolve entries and values that end in `/` and with wildcards `*`.\n *\n * Notes:\n * - This diverges from the behavior of Node in that conditions are considered in order of\n * the `conditions` array, NOT in the order keys are defined in the exports map.\n * - Null export values are supported only for generated config. A null export signals to Cloudpack\n * that the entry should be completely dropped from the flattened exports map.\n * - Following the behavior of Node, for perf reasons, we do NOT verify whether any entries\n * exist on disk except wildcard or trailing slash exports since it is required.\n * (This differs from the behavior of typescript and webpack.)\n */\nexport function flattenExportsMap(\n exportsMap: PackageJsonExports,\n options: {\n conditions?: string[];\n requiredConditions?: string[];\n packagePath?: string;\n } = {},\n): Record<string, string> {\n const { requiredConditions, packagePath } = options;\n\n const conditions = mergeArrayDefaults(options.conditions, defaultConditions);\n\n if (typeof exportsMap === 'string' && conditions.includes('default')) {\n return {\n '.': cleanEntry(exportsMap),\n };\n }\n\n return extractExports({\n exports: exportsMap,\n conditions,\n requiredConditions,\n flatExports: {},\n importMatch: '.',\n matchedConditions: [],\n packagePath,\n });\n}\n\n/**\n * Extract the exports from an exports object or sub-object and add them to the flat exports map.\n *\n * @returns The cumulative flat exports map.\n */\nfunction extractExports({\n exports,\n conditions,\n requiredConditions,\n flatExports = {},\n importMatch = '.',\n matchedConditions = [],\n packagePath = undefined,\n}: {\n /** The exports object to extract or a sub-object. */\n exports: PackageJsonExports;\n /** The conditions to check for in the exports object. */\n conditions: string[];\n /** The conditions that must be matched to add the export. */\n requiredConditions?: string[];\n /** The cumulative flat exports map to add the exports to. */\n flatExports?: Record<string, string>;\n /** The import path to match (default `.`). */\n importMatch?: string;\n /** The conditions that have been matched so far. */\n matchedConditions?: string[];\n /** The path to the package. */\n packagePath?: string | undefined;\n}) {\n if (\n typeof exports === 'string' &&\n (!requiredConditions || requiredConditions.every((condition) => matchedConditions.includes(condition)))\n ) {\n addExportsEntry({ flatExports, key: importMatch, value: exports, packagePath });\n } else if (Array.isArray(exports)) {\n for (const exportEntry of exports) {\n extractExports({\n exports: exportEntry,\n conditions,\n requiredConditions,\n flatExports,\n importMatch,\n matchedConditions,\n packagePath,\n });\n }\n } else if (exports && typeof exports === 'object') {\n // Iterate through condition matches and go deeper if a match is found.\n for (const condition of conditions) {\n const exportsObject = (exports as PackageJsonExportsObject)[condition];\n\n if (exportsObject) {\n extractExports({\n exports: exportsObject as PackageJsonExports,\n conditions,\n requiredConditions,\n flatExports,\n importMatch,\n matchedConditions: matchedConditions.concat(condition),\n packagePath,\n });\n // Stop at the first match.\n return flatExports;\n }\n }\n\n // No conditions are available. Check for import entries.\n for (const [key, value] of Object.entries(exports)) {\n if (key.startsWith('.')) {\n importMatch = key;\n\n if (typeof value === 'string') {\n if (!flatExports[importMatch] && (!requiredConditions || requiredConditions?.includes(key))) {\n addExportsEntry({ flatExports, key: importMatch, value, packagePath });\n }\n } else if (value) {\n extractExports({\n exports: value,\n conditions,\n requiredConditions,\n flatExports,\n importMatch,\n matchedConditions: [...matchedConditions, key],\n packagePath,\n });\n } else {\n delete flatExports[key];\n }\n }\n }\n }\n\n return flatExports;\n}\n\n/**\n * Add an entry to the flattened exports map if the key and value are valid\n * and the key is not already in the map.\n *\n * Does nothing if the key contains a wildcard or a trailing slash and the value does not, such as it being `null`.\n */\nfunction addExportsEntry({\n flatExports,\n key,\n value,\n packagePath,\n}: {\n /** The path to the package. */\n flatExports: Record<string, string>;\n /** The flattened exports map. */\n key: string;\n /** The key to add to the map. */\n value: string;\n /** The relative physical path to add to the map. */\n packagePath: string | undefined;\n}) {\n const basename = path.basename(value);\n const isValid = basename !== '' && basename !== '.';\n const isMany = value.endsWith('/') || value.indexOf('*') !== -1 || key.indexOf('*') !== -1 || key.endsWith('/');\n\n // Skip if the key is already in the map.\n if (flatExports[key]) return;\n\n if (isValid && !isMany) {\n flatExports[key] = cleanEntry(value);\n return;\n }\n\n if (value === null) {\n // Debug log for null values in the exports map.\n console.debug(`Skipping null value for key \"${key}\" in exports map${packagePath ? ` of \"${packagePath}\"` : ''}.`);\n return;\n }\n\n // Debug log for export patterns found in the exports map.\n console.debug(`Found export patterns in ${packagePath ? `\"${packagePath}\" ` : ''}exports map: \"${key}\": \"${value}\"`);\n\n // A package path is required to resolve entries and values that end in `/` or that include a wildcard `*`.\n if (!packagePath) return;\n\n // Check for wildcards in the key and value.\n // The wildcards\n const keyWildcard = key.indexOf('*', 1);\n const valueWildcard = value.indexOf('*', 1);\n\n if ((key.endsWith('/') && value.endsWith('/')) || (keyWildcard !== -1 && valueWildcard !== -1)) {\n const searchGlob = valueToGlob(value, valueWildcard);\n const keySplit = splitByGlob(key, keyWildcard);\n const valueSplit = splitByGlob(value, valueWildcard);\n if (!searchGlob || !keySplit || !valueSplit) return;\n // We only want to search for files.\n const matches = glob.sync(searchGlob, { cwd: packagePath, onlyFiles: true });\n for (const match of matches) {\n // Skip files that don't have an extension or have a `.` extension.\n if (path.extname(match).length <= 1) continue;\n // Get the glob match shared between the key and value.\n const globMatch = match.substring(\n // Globs that start with `./` don't return matches with `./` in the beginning.\n match.startsWith(valueSplit.start) ? valueSplit.start.length : 0,\n match.length - valueSplit.end.length,\n );\n // Replace the glob match in the key with the resolved glob match in the value.\n const matchKey = keySplit.start + globMatch + keySplit.end;\n if (!flatExports[matchKey]) {\n flatExports[matchKey] = cleanEntry(match);\n }\n }\n }\n}\n\n/**\n * Convert a value to a glob pattern.\n *\n * @param value The value to convert.\n * @param valueWildcard The index of the wildcard in the value.\n * @returns A value converted to a glob pattern.\n */\nfunction valueToGlob(value: string, valueWildcard: number = value.indexOf('*', 1)) {\n if (value.endsWith('/')) {\n return value + '**/*';\n } else if (valueWildcard !== -1) {\n return value.substring(0, valueWildcard) + '**/*' + value.substring(valueWildcard + 1);\n }\n}\n\n/**\n * Split a value by the location of the trailing slash or wildcard.\n *\n * @param value The value to split.\n * @param valueWildcard The index of the wildcard in the value.\n * @returns An object with the start and end substring of the split value.\n */\nfunction splitByGlob(value: string, valueWildcard: number = value.indexOf('*', 1)) {\n if (value.endsWith('/')) {\n return { start: value, end: '' };\n } else if (valueWildcard !== -1) {\n return {\n start: value.substring(0, valueWildcard),\n end: value.substring(valueWildcard + 1),\n };\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"flattenExportsMap.js","sourceRoot":"","sources":["../src/flattenExportsMap.ts"],"names":[],"mappings":"AAAA,OAAO,IAAI,MAAM,MAAM,CAAC;AAExB,OAAO,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAC7C,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,EAAE,kBAAkB,EAAE,MAAM,yBAAyB,CAAC;AAE7D,MAAM,iBAAiB,GAAG,CAAC,SAAS,EAAE,QAAQ,EAAE,QA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-cloudpack/common-types';\nimport { cleanEntry } from './cleanEntry.js';\nimport glob from 'fast-glob';\nimport { mergeArrayDefaults } from './mergeArrayDefaults.js';\n\nconst defaultConditions = ['browser', 'module', 'import', 'default'];\n\n/**\n * Given a package definition and applicable conditions, return a flat map of package import to physical (relative) path.\n * Optionally return the exports map fully qualified with conditions intact using the `fullExports` option.\n * Optionally takes in a `packagePath` to resolve entries and values that end in `/` and with wildcards `*`.\n *\n * Notes:\n * - This diverges from the behavior of Node in that conditions are considered in order of\n * the `conditions` array, NOT in the order keys are defined in the exports map.\n * - Null export values are supported only for generated config. A null export signals to Cloudpack\n * that the entry should be completely dropped from the flattened exports map.\n * - Following the behavior of Node, for perf reasons, we do NOT verify whether any entries\n * exist on disk except wildcard or trailing slash exports since it is required.\n * (This differs from the behavior of typescript and webpack.)\n */\nexport function flattenExportsMap(\n exportsMap: PackageJsonExports,\n options: {\n conditions?: string[];\n requiredConditions?: string[];\n packagePath?: string;\n } = {},\n): Record<string, string> {\n const { requiredConditions, packagePath } = options;\n\n const conditions = mergeArrayDefaults(options.conditions, defaultConditions);\n\n if (typeof exportsMap === 'string' && conditions.includes('default')) {\n return {\n '.': cleanEntry(exportsMap),\n };\n }\n\n return extractExports({\n exports: exportsMap,\n conditions,\n requiredConditions,\n flatExports: {},\n importMatch: '.',\n matchedConditions: [],\n packagePath,\n });\n}\n\n/**\n * Extract the exports from an exports object or sub-object and add them to the flat exports map.\n *\n * @returns The cumulative flat exports map.\n */\nfunction extractExports(params: {\n /** The exports object to extract or a sub-object. */\n exports: PackageJsonExports;\n /** The conditions to check for in the exports object. */\n conditions: string[];\n /** The conditions that must be matched to add the export. */\n requiredConditions?: string[];\n /** The cumulative flat exports map to add the exports to. */\n flatExports: Record<string, string>;\n /** The import path to match */\n importMatch: string;\n /** The conditions that have been matched so far. */\n matchedConditions: string[];\n /** The path to the package. */\n packagePath?: string | undefined;\n}) {\n const { exports, conditions, requiredConditions, flatExports, matchedConditions, packagePath, importMatch } = params;\n\n if (\n typeof exports === 'string' &&\n (!requiredConditions || requiredConditions.every((condition) => matchedConditions.includes(condition)))\n ) {\n addExportsEntry({ flatExports, key: importMatch, value: exports, packagePath });\n } else if (Array.isArray(exports)) {\n for (const exportEntry of exports) {\n extractExports({ ...params, exports: exportEntry });\n }\n } else if (exports && typeof exports === 'object') {\n // Iterate through condition matches and go deeper if a match is found.\n for (const condition of conditions) {\n const conditionExports = (exports as PackageJsonExportsObject)[condition];\n\n if (conditionExports) {\n extractExports({\n ...params,\n exports: conditionExports,\n matchedConditions: matchedConditions.concat(condition),\n });\n // Stop at the first match.\n return flatExports;\n }\n }\n\n // No conditions are available. Check for import entries.\n for (const [key, value] of Object.entries(exports)) {\n if (!key.startsWith('.')) {\n continue; // not a path\n }\n\n if (typeof value === 'string') {\n if (!flatExports[key] && (!requiredConditions || requiredConditions?.includes(key))) {\n addExportsEntry({ flatExports, key, value, packagePath });\n }\n } else if (value) {\n extractExports({\n ...params,\n exports: value,\n importMatch: key,\n matchedConditions: [...matchedConditions, key],\n });\n } else {\n delete flatExports[key];\n }\n }\n }\n\n return flatExports;\n}\n\n/**\n * Add an entry to the flattened exports map if the key and value are valid\n * and the key is not already in the map.\n *\n * Does nothing if the key contains a wildcard or a trailing slash and the value does not, such as it being `null`.\n */\nfunction addExportsEntry(params: {\n /** The path to the package. */\n flatExports: Record<string, string>;\n /** The flattened exports map. */\n key: string;\n /** The key to add to the map. */\n value: string;\n /** The relative physical path to add to the map. */\n packagePath: string | undefined;\n}) {\n const { flatExports, key, value, packagePath } = params;\n\n const basename = path.basename(value);\n const isValid = basename !== '' && basename !== '.';\n const isMany = value.endsWith('/') || value.indexOf('*') !== -1 || key.indexOf('*') !== -1 || key.endsWith('/');\n\n // Skip if the key is already in the map.\n if (flatExports[key]) return;\n\n if (isValid && !isMany) {\n flatExports[key] = cleanEntry(value);\n return;\n }\n\n if (value === null) {\n // Debug log for null values in the exports map.\n console.debug(`Skipping null value for key \"${key}\" in exports map${packagePath ? ` of \"${packagePath}\"` : ''}.`);\n return;\n }\n\n // Debug log for export patterns found in the exports map.\n console.debug(`Found export patterns in ${packagePath ? `\"${packagePath}\" ` : ''}exports map: \"${key}\": \"${value}\"`);\n\n // A package path is required to resolve entries and values that end in `/` or that include a wildcard `*`.\n if (!packagePath) return;\n\n // Check for wildcards in the key and value.\n // The wildcards\n const keyWildcard = key.indexOf('*', 1);\n const valueWildcard = value.indexOf('*', 1);\n\n if ((key.endsWith('/') && value.endsWith('/')) || (keyWildcard !== -1 && valueWildcard !== -1)) {\n const searchGlob = valueToGlob(value, valueWildcard);\n const keySplit = splitByGlob(key, keyWildcard);\n const valueSplit = splitByGlob(value, valueWildcard);\n if (!searchGlob || !keySplit || !valueSplit) return;\n // We only want to search for files.\n const matches = glob.sync(searchGlob, { cwd: packagePath, onlyFiles: true });\n for (const match of matches) {\n // Skip files that don't have an extension or have a `.` extension.\n if (path.extname(match).length <= 1) continue;\n // Get the glob match shared between the key and value.\n const globMatch = match.substring(\n // Globs that start with `./` don't return matches with `./` in the beginning.\n match.startsWith(valueSplit.start) ? valueSplit.start.length : 0,\n match.length - valueSplit.end.length,\n );\n // Replace the glob match in the key with the resolved glob match in the value.\n const matchKey = keySplit.start + globMatch + keySplit.end;\n if (!flatExports[matchKey]) {\n flatExports[matchKey] = cleanEntry(match);\n }\n }\n }\n}\n\n/**\n * Convert a value to a glob pattern.\n *\n * @param value The value to convert.\n * @param valueWildcard The index of the wildcard in the value.\n * @returns A value converted to a glob pattern.\n */\nfunction valueToGlob(value: string, valueWildcard: number = value.indexOf('*', 1)) {\n if (value.endsWith('/')) {\n return value + '**/*';\n } else if (valueWildcard !== -1) {\n return value.substring(0, valueWildcard) + '**/*' + value.substring(valueWildcard + 1);\n }\n}\n\n/**\n * Split a value by the location of the trailing slash or wildcard.\n *\n * @param value The value to split.\n * @param valueWildcard The index of the wildcard in the value.\n * @returns An object with the start and end substring of the split value.\n */\nfunction splitByGlob(value: string, valueWildcard: number = value.indexOf('*', 1)) {\n if (value.endsWith('/')) {\n return { start: value, end: '' };\n } else if (valueWildcard !== -1) {\n return {\n start: value.substring(0, valueWildcard),\n end: value.substring(valueWildcard + 1),\n };\n }\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ms-cloudpack/package-utilities",
|
|
3
|
-
"version": "10.
|
|
3
|
+
"version": "10.3.0",
|
|
4
4
|
"description": "Utilities for resolving/parsing packages and their imports.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -14,11 +14,11 @@
|
|
|
14
14
|
}
|
|
15
15
|
},
|
|
16
16
|
"dependencies": {
|
|
17
|
-
"@ms-cloudpack/common-types": "^0.23.
|
|
17
|
+
"@ms-cloudpack/common-types": "^0.23.4",
|
|
18
18
|
"@ms-cloudpack/json-utilities": "^0.1.8",
|
|
19
|
-
"@ms-cloudpack/package-overrides": "^0.9.
|
|
19
|
+
"@ms-cloudpack/package-overrides": "^0.9.40",
|
|
20
20
|
"@ms-cloudpack/path-string-parsing": "^1.2.5",
|
|
21
|
-
"@ms-cloudpack/path-utilities": "^2.7.
|
|
21
|
+
"@ms-cloudpack/path-utilities": "^2.7.54",
|
|
22
22
|
"@ms-cloudpack/task-reporter": "^0.14.6",
|
|
23
23
|
"acorn": "^8.11.2",
|
|
24
24
|
"acorn-walk": "^8.2.1",
|