react-native-legal 1.2.0 → 1.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.
@@ -1,339 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.generateAboutLibrariesNPMOutput = exports.generateLicensePlistNPMOutput = exports.scanDependencies = exports.arrayIncludesObject = void 0;
7
- const crypto_1 = __importDefault(require("crypto"));
8
- const fs_1 = __importDefault(require("fs"));
9
- const path_1 = __importDefault(require("path"));
10
- const glob = require('glob');
11
- function compareObjects(a, b) {
12
- if (a == null || b == null || typeof a !== 'object' || typeof b !== 'object') {
13
- return a === b;
14
- }
15
- const entriesA = Object.entries(a);
16
- const entriesB = Object.entries(b);
17
- return (entriesA.length === entriesB.length &&
18
- entriesA
19
- .map(([keyA, valueA]) => {
20
- const entry = entriesB.find(([keyB]) => keyA === keyB);
21
- if (!entry) {
22
- return valueA === entry;
23
- }
24
- const [, valueB] = entry;
25
- return compareObjects(valueA, valueB);
26
- })
27
- .reduce((acc, curr) => acc && curr, true));
28
- }
29
- /**
30
- * Makes a deep-check between array items and provided object, returns true if array has provided object.
31
- */
32
- function arrayIncludesObject(array, object) {
33
- return array?.map((item) => compareObjects(item, object)).reduce((acc, curr) => acc || curr, false);
34
- }
35
- exports.arrayIncludesObject = arrayIncludesObject;
36
- /**
37
- * Scans a single package and its dependencies for license information
38
- */
39
- function scanPackage(packageName, version, processedPackages, result) {
40
- const packageKey = `${packageName}@${version}`;
41
- // Skip if already processed to avoid circular dependencies
42
- if (processedPackages.has(packageKey)) {
43
- return;
44
- }
45
- processedPackages.add(packageKey);
46
- try {
47
- const localPackageJsonPath = getPackageJsonPath(packageName);
48
- if (!localPackageJsonPath) {
49
- console.warn(`[react-native-legal] skipping ${packageName} could not find package.json`);
50
- return;
51
- }
52
- const localPackageJson = require(path_1.default.resolve(localPackageJsonPath));
53
- if (localPackageJson.private !== true) {
54
- const licenseFiles = glob.sync('LICEN{S,C}E{.md,}', {
55
- cwd: path_1.default.dirname(localPackageJsonPath),
56
- absolute: true,
57
- nocase: true,
58
- nodir: true,
59
- ignore: '**/{__tests__,__fixtures__,__mocks__}/**',
60
- });
61
- result[packageName] = {
62
- author: parseAuthorField(localPackageJson),
63
- content: licenseFiles?.[0] ? fs_1.default.readFileSync(licenseFiles[0], { encoding: 'utf-8' }) : undefined,
64
- file: licenseFiles?.[0] ? licenseFiles[0] : undefined,
65
- description: localPackageJson.description,
66
- type: parseLicenseField(localPackageJson),
67
- url: parseRepositoryFieldToUrl(localPackageJson),
68
- version: localPackageJson.version,
69
- };
70
- }
71
- const dependencies = localPackageJson.dependencies || {};
72
- const isWorkspacePackage = version.startsWith('workspace:');
73
- if (!isWorkspacePackage)
74
- return;
75
- Object.entries(dependencies).forEach(([depName, depVersion]) => {
76
- scanPackage(depName, depVersion, processedPackages, result);
77
- });
78
- }
79
- catch (error) {
80
- console.warn(`[react-native-legal] could not process package.json for ${packageName}`);
81
- }
82
- }
83
- /**
84
- * Scans `package.json` and searches for all packages under `dependencies` field. Supports monorepo projects.
85
- */
86
- function scanDependencies(appPackageJsonPath) {
87
- const appPackageJson = require(path_1.default.resolve(appPackageJsonPath));
88
- const dependencies = appPackageJson.dependencies;
89
- const result = {};
90
- const processedPackages = new Set();
91
- Object.entries(dependencies).forEach(([packageName, version]) => {
92
- scanPackage(packageName, version, processedPackages, result);
93
- });
94
- return result;
95
- }
96
- exports.scanDependencies = scanDependencies;
97
- function needsQuoting(value) {
98
- return (value === '' || // empty string
99
- /^[#:>|-]/.test(value) || // starts with special char
100
- /^['"{}[\],&*#?|<>=!%@`]/.test(value) || // starts with indicator chars
101
- /^[\s]|[\s]$/.test(value) || // has leading/trailing whitespace
102
- /^[\d.+-]/.test(value) || // looks like a number/bool/null
103
- /[\n"'\\\s]/.test(value) || // contains newlines, quotes, backslash, or spaces
104
- /^(true|false|yes|no|null|on|off)$/i.test(value) // is a YAML keyword
105
- );
106
- }
107
- function formatYamlKey(key) {
108
- return /[@/_.]/.test(key) ? `"${key}"` : key;
109
- }
110
- function formatYamlValue(value, indent) {
111
- if (value.includes('\n')) {
112
- const indentedValue = value
113
- .split('\n')
114
- .map((line) => `${' '.repeat(indent)}${line}`)
115
- .join('\n');
116
- // Return the block indicator on the same line as the content
117
- return `|${indentedValue ? '\n' + indentedValue : ''}`;
118
- }
119
- if (needsQuoting(value)) {
120
- if (value.includes("'") && !value.includes('"')) {
121
- return `"${value.replace(/["\\]/g, '\\$&')}"`;
122
- }
123
- return `'${value.replace(/'/g, "''")}'`;
124
- }
125
- return value;
126
- }
127
- function toYaml(obj, indent = 0) {
128
- const spaces = ' '.repeat(indent);
129
- if (obj == null)
130
- return '';
131
- if (Array.isArray(obj)) {
132
- return obj.map((item) => `${spaces}- ${toYaml(item, indent + 2).trimStart()}`).join('\n');
133
- }
134
- if (typeof obj === 'object') {
135
- return Object.entries(obj)
136
- .filter(([, v]) => v != null)
137
- .map(([key, value]) => {
138
- const formattedKey = formatYamlKey(key);
139
- const formattedValue = toYaml(value, indent + 2);
140
- if (Array.isArray(value)) {
141
- return `${spaces}${formattedKey}:\n${formattedValue}`;
142
- }
143
- if (typeof value === 'object' && value !== null) {
144
- return `${spaces}${formattedKey}:\n${formattedValue}`;
145
- }
146
- if (typeof value === 'string' && value.includes('\n')) {
147
- return `${spaces}${formattedKey}: ${formattedValue}`;
148
- }
149
- return `${spaces}${formattedKey}: ${formattedValue}`;
150
- })
151
- .join('\n');
152
- }
153
- return typeof obj === 'string' ? formatYamlValue(obj, indent) : String(obj);
154
- }
155
- /**
156
- * Generates LicensePlist-compatible metadata for NPM dependencies
157
- *
158
- * This will take scanned NPM licenses and produce following output inside iOS project's directory:
159
- *
160
- * | - ios
161
- * | ---- myawesomeapp
162
- * | ---- myawesomeapp.xcodeproj
163
- * | ---- myawesomeapp.xcodeworkspace
164
- * | ---- license_plist.yml <--- generated LicensePlist config with NPM dependencies
165
- * | ---- Podfile
166
- * | ---- Podfile.lock
167
- */
168
- function generateLicensePlistNPMOutput(licenses, iosProjectPath) {
169
- const renames = {};
170
- const licenseEntries = Object.entries(licenses).map(([dependency, licenseObj]) => {
171
- const normalizedName = normalizePackageName(dependency);
172
- if (dependency !== normalizedName) {
173
- renames[normalizedName] = dependency;
174
- }
175
- const relativeLicenseFile = licenseObj.file ? path_1.default.relative(iosProjectPath, licenseObj.file) : undefined;
176
- return {
177
- name: normalizedName,
178
- version: licenseObj.version,
179
- ...(licenseObj.url && { source: licenseObj.url }),
180
- ...(licenseObj.file
181
- ? { file: relativeLicenseFile }
182
- : { body: licenseObj.content ?? licenseObj.type ?? 'UNKNOWN' }),
183
- };
184
- });
185
- const yamlDoc = {
186
- ...(Object.keys(renames).length > 0 && { rename: renames }),
187
- manual: licenseEntries,
188
- };
189
- const yamlContent = [
190
- '# BEGIN Generated NPM license entries',
191
- toYaml(yamlDoc),
192
- '# END Generated NPM license entries',
193
- ].join('\n');
194
- fs_1.default.writeFileSync(path_1.default.join(iosProjectPath, 'license_plist.yml'), yamlContent, { encoding: 'utf-8' });
195
- }
196
- exports.generateLicensePlistNPMOutput = generateLicensePlistNPMOutput;
197
- /**
198
- * Generates AboutLibraries-compatible metadata for NPM dependencies
199
- *
200
- * This will take scanned NPM licenses and produce following output inside android project's directory:
201
- *
202
- * | - android
203
- * | ---- app
204
- * | ---- config <--- generated AboutLibraries config directory
205
- * | ------- libraries <--- generated directory with JSON files list of NPM dependencies
206
- * | ------- licenses <--- generated directory with JSON files list of used licenses
207
- * | ---- build.gradle
208
- * | ---- settings.gradle
209
- */
210
- function generateAboutLibrariesNPMOutput(licenses, androidProjectPath) {
211
- const aboutLibrariesConfigDirPath = path_1.default.join(androidProjectPath, 'config');
212
- const aboutLibrariesConfigLibrariesDirPath = path_1.default.join(aboutLibrariesConfigDirPath, 'libraries');
213
- const aboutLibrariesConfigLicensesDirPath = path_1.default.join(aboutLibrariesConfigDirPath, 'licenses');
214
- if (!fs_1.default.existsSync(aboutLibrariesConfigDirPath)) {
215
- fs_1.default.mkdirSync(aboutLibrariesConfigDirPath);
216
- }
217
- if (!fs_1.default.existsSync(aboutLibrariesConfigLibrariesDirPath)) {
218
- fs_1.default.mkdirSync(aboutLibrariesConfigLibrariesDirPath);
219
- }
220
- if (!fs_1.default.existsSync(aboutLibrariesConfigLicensesDirPath)) {
221
- fs_1.default.mkdirSync(aboutLibrariesConfigLicensesDirPath);
222
- }
223
- Object.entries(licenses)
224
- .map(([dependency, licenseObj]) => {
225
- return {
226
- artifactVersion: licenseObj.version,
227
- content: licenseObj.content ?? '',
228
- description: licenseObj.description ?? '',
229
- developers: [{ name: licenseObj.author ?? '', organisationUrl: '' }],
230
- licenses: [prepareAboutLibrariesLicenseField(licenseObj)],
231
- name: dependency,
232
- tag: '',
233
- type: licenseObj.type,
234
- uniqueId: normalizePackageName(dependency),
235
- };
236
- })
237
- .map((jsonPayload) => {
238
- const libraryJsonPayload = {
239
- artifactVersion: jsonPayload.artifactVersion,
240
- description: jsonPayload.description,
241
- developers: jsonPayload.developers,
242
- licenses: jsonPayload.licenses,
243
- name: jsonPayload.name,
244
- tag: jsonPayload.tag,
245
- uniqueId: jsonPayload.uniqueId,
246
- };
247
- const licenseJsonPayload = {
248
- content: jsonPayload.content,
249
- hash: jsonPayload.licenses[0],
250
- name: jsonPayload.type ?? '',
251
- url: '',
252
- };
253
- const libraryJsonFilePath = path_1.default.join(aboutLibrariesConfigLibrariesDirPath, `${normalizePackageName(jsonPayload.name)}.json`);
254
- const licenseJsonFilePath = path_1.default.join(aboutLibrariesConfigLicensesDirPath, `${licenseJsonPayload.hash}.json`);
255
- fs_1.default.writeFileSync(libraryJsonFilePath, JSON.stringify(libraryJsonPayload));
256
- if (!fs_1.default.existsSync(licenseJsonFilePath)) {
257
- fs_1.default.writeFileSync(licenseJsonFilePath, JSON.stringify(licenseJsonPayload));
258
- }
259
- });
260
- }
261
- exports.generateAboutLibrariesNPMOutput = generateAboutLibrariesNPMOutput;
262
- function prepareAboutLibrariesLicenseField(license) {
263
- if (!license.type) {
264
- return '';
265
- }
266
- return `${license.type}_${sha512(license.content ?? license.type)}`;
267
- }
268
- function sha512(text) {
269
- return crypto_1.default.createHash('sha512').update(text).digest('hex');
270
- }
271
- function parseAuthorField(json) {
272
- if (typeof json.author === 'object' && typeof json.author.name === 'string') {
273
- return json.author.name;
274
- }
275
- if (typeof json.author === 'string') {
276
- return json.author;
277
- }
278
- }
279
- function parseLicenseField(json) {
280
- if (typeof json.license === 'object' && typeof json.license.type === 'string') {
281
- return json.license.type;
282
- }
283
- if (typeof json.license === 'string') {
284
- return json.license;
285
- }
286
- }
287
- function parseRepositoryFieldToUrl(json) {
288
- if (typeof json.repository === 'object' && typeof json.repository.url === 'string') {
289
- return normalizeRepositoryUrl(json.repository.url);
290
- }
291
- if (typeof json.repository === 'string') {
292
- return normalizeRepositoryUrl(json.repository);
293
- }
294
- }
295
- function normalizeRepositoryUrl(url) {
296
- return url
297
- .replace('git+ssh://git@', 'git://')
298
- .replace('.git', '')
299
- .replace('git+https://github.com', 'https://github.com')
300
- .replace('.git', '')
301
- .replace('git://github.com', 'https://github.com')
302
- .replace('.git', '')
303
- .replace('git@github.com:', 'https://github.com/')
304
- .replace('.git', '')
305
- .replace('github:', 'https://github.com/')
306
- .replace('.git', '');
307
- }
308
- function getPackageJsonPath(dependency) {
309
- try {
310
- return require.resolve(`${dependency}/package.json`);
311
- }
312
- catch (error) {
313
- return resolvePackageJsonFromEntry(dependency);
314
- }
315
- }
316
- function resolvePackageJsonFromEntry(dependency) {
317
- try {
318
- const entryPath = require.resolve(dependency);
319
- const packageDir = findPackageRoot(entryPath);
320
- if (!packageDir)
321
- return null;
322
- const packageJsonPath = path_1.default.join(packageDir, 'package.json');
323
- return fs_1.default.existsSync(packageJsonPath) ? packageJsonPath : null;
324
- }
325
- catch {
326
- return null;
327
- }
328
- }
329
- function findPackageRoot(entryPath) {
330
- let currentDir = path_1.default.dirname(entryPath);
331
- while (currentDir !== path_1.default.dirname(currentDir)) {
332
- if (fs_1.default.existsSync(path_1.default.join(currentDir, 'package.json')))
333
- return currentDir;
334
- currentDir = path_1.default.dirname(currentDir);
335
- }
336
- }
337
- function normalizePackageName(packageName) {
338
- return packageName.replace('/', '_');
339
- }