@socketsecurity/lib 4.4.0 → 5.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/CHANGELOG.md +78 -0
  2. package/README.md +1 -1
  3. package/dist/constants/node.js +1 -1
  4. package/dist/{package-default-node-range.js → constants/package-default-node-range.js} +1 -1
  5. package/dist/constants/packages.js +3 -3
  6. package/dist/{dlx-binary.d.ts → dlx/binary.d.ts} +2 -2
  7. package/dist/{dlx-binary.js → dlx/binary.js} +17 -17
  8. package/dist/dlx/cache.d.ts +25 -0
  9. package/dist/dlx/cache.js +32 -0
  10. package/dist/dlx/dir.d.ts +24 -0
  11. package/dist/dlx/dir.js +79 -0
  12. package/dist/{dlx-manifest.js → dlx/manifest.js} +7 -7
  13. package/dist/{dlx-package.d.ts → dlx/package.d.ts} +2 -2
  14. package/dist/{dlx-package.js → dlx/package.js} +16 -16
  15. package/dist/dlx/packages.d.ts +24 -0
  16. package/dist/dlx/packages.js +125 -0
  17. package/dist/dlx/paths.d.ts +31 -0
  18. package/dist/dlx/paths.js +75 -0
  19. package/dist/fs.d.ts +34 -22
  20. package/dist/fs.js +3 -3
  21. package/dist/http-request.d.ts +46 -0
  22. package/dist/http-request.js +18 -1
  23. package/dist/json/edit.d.ts +16 -0
  24. package/dist/json/edit.js +248 -0
  25. package/dist/json/format.d.ts +140 -0
  26. package/dist/json/format.js +121 -0
  27. package/dist/json/parse.d.ts +76 -0
  28. package/dist/{json.js → json/parse.js} +4 -4
  29. package/dist/json/types.d.ts +229 -0
  30. package/dist/json/types.js +17 -0
  31. package/dist/packages/{editable.js → edit.js} +18 -32
  32. package/dist/packages/operations.js +3 -3
  33. package/dist/packages.d.ts +2 -2
  34. package/dist/packages.js +5 -5
  35. package/package.json +62 -37
  36. package/dist/dlx.d.ts +0 -104
  37. package/dist/dlx.js +0 -220
  38. package/dist/json.d.ts +0 -196
  39. /package/dist/{lifecycle-script-names.d.ts → constants/lifecycle-script-names.d.ts} +0 -0
  40. /package/dist/{lifecycle-script-names.js → constants/lifecycle-script-names.js} +0 -0
  41. /package/dist/{maintained-node-versions.d.ts → constants/maintained-node-versions.d.ts} +0 -0
  42. /package/dist/{maintained-node-versions.js → constants/maintained-node-versions.js} +0 -0
  43. /package/dist/{package-default-node-range.d.ts → constants/package-default-node-range.d.ts} +0 -0
  44. /package/dist/{package-default-socket-categories.d.ts → constants/package-default-socket-categories.d.ts} +0 -0
  45. /package/dist/{package-default-socket-categories.js → constants/package-default-socket-categories.js} +0 -0
  46. /package/dist/{dlx-manifest.d.ts → dlx/manifest.d.ts} +0 -0
  47. /package/dist/packages/{editable.d.ts → edit.d.ts} +0 -0
@@ -0,0 +1,140 @@
1
+ /**
2
+ * @fileoverview Shared utilities for JSON formatting preservation and manipulation.
3
+ * Provides functions for detecting and preserving indentation, line endings, and
4
+ * determining when JSON files should be saved based on content changes.
5
+ */
6
+ /**
7
+ * Symbols used to store formatting metadata in JSON objects.
8
+ */
9
+ export declare const INDENT_SYMBOL: unique symbol;
10
+ export declare const NEWLINE_SYMBOL: unique symbol;
11
+ /**
12
+ * Formatting metadata for JSON files.
13
+ */
14
+ export interface JsonFormatting {
15
+ indent: string | number;
16
+ newline: string;
17
+ }
18
+ /**
19
+ * Options for determining if a save should occur.
20
+ */
21
+ export interface ShouldSaveOptions {
22
+ ignoreWhitespace?: boolean;
23
+ sort?: boolean;
24
+ sortFn?: (obj: Record<string, unknown>) => Record<string, unknown>;
25
+ }
26
+ /**
27
+ * Detect indentation from a JSON string.
28
+ * Supports space-based indentation (returns count) or mixed indentation (returns string).
29
+ *
30
+ * @param json - JSON string to analyze
31
+ * @returns Number of spaces or indentation string, defaults to 2 if not detected
32
+ *
33
+ * @example
34
+ * ```ts
35
+ * detectIndent('{\n "key": "value"\n}') // => 2
36
+ * detectIndent('{\n "key": "value"\n}') // => 4
37
+ * detectIndent('{\n\t"key": "value"\n}') // => '\t'
38
+ * ```
39
+ */
40
+ export declare function detectIndent(json: string): string | number;
41
+ /**
42
+ * Detect newline character(s) from a JSON string.
43
+ * Supports LF (\n) and CRLF (\r\n) line endings.
44
+ *
45
+ * @param json - JSON string to analyze
46
+ * @returns Line ending string ('\n' or '\r\n'), defaults to '\n' if not detected
47
+ *
48
+ * @example
49
+ * ```ts
50
+ * detectNewline('{\n "key": "value"\n}') // => '\n'
51
+ * detectNewline('{\r\n "key": "value"\r\n}') // => '\r\n'
52
+ * ```
53
+ */
54
+ export declare function detectNewline(json: string): string;
55
+ /**
56
+ * Extract formatting metadata from a JSON string.
57
+ *
58
+ * @param json - JSON string to analyze
59
+ * @returns Object containing indent and newline formatting
60
+ *
61
+ * @example
62
+ * ```ts
63
+ * const formatting = extractFormatting('{\n "key": "value"\n}')
64
+ * // => { indent: 2, newline: '\n' }
65
+ * ```
66
+ */
67
+ export declare function extractFormatting(json: string): JsonFormatting;
68
+ /**
69
+ * Get default formatting for JSON files.
70
+ *
71
+ * @returns Default formatting (2 spaces, LF line endings)
72
+ */
73
+ export declare function getDefaultFormatting(): JsonFormatting;
74
+ /**
75
+ * Sort object keys alphabetically.
76
+ * Creates a new object with sorted keys (does not mutate input).
77
+ *
78
+ * @param obj - Object to sort
79
+ * @returns New object with alphabetically sorted keys
80
+ *
81
+ * @example
82
+ * ```ts
83
+ * sortKeys({ z: 3, a: 1, m: 2 })
84
+ * // => { a: 1, m: 2, z: 3 }
85
+ * ```
86
+ */
87
+ export declare function sortKeys(obj: Record<string, unknown>): Record<string, unknown>;
88
+ /**
89
+ * Stringify JSON with specific formatting.
90
+ * Applies indentation and line ending preferences.
91
+ *
92
+ * @param content - Object to stringify
93
+ * @param formatting - Formatting preferences (indent and newline)
94
+ * @returns Formatted JSON string with trailing newline
95
+ *
96
+ * @example
97
+ * ```ts
98
+ * stringifyWithFormatting(
99
+ * { key: 'value' },
100
+ * { indent: 4, newline: '\r\n' }
101
+ * )
102
+ * // => '{\r\n "key": "value"\r\n}\r\n'
103
+ * ```
104
+ */
105
+ export declare function stringifyWithFormatting(content: Record<string, unknown>, formatting: JsonFormatting): string;
106
+ /**
107
+ * Strip formatting symbols from content object.
108
+ * Removes Symbol.for('indent') and Symbol.for('newline') from the object.
109
+ *
110
+ * @param content - Content object with potential symbol properties
111
+ * @returns Object with symbols removed
112
+ */
113
+ export declare function stripFormattingSymbols(content: Record<string | symbol, unknown>): Record<string, unknown>;
114
+ /**
115
+ * Extract formatting from content object that has symbol-based metadata.
116
+ *
117
+ * @param content - Content object with Symbol.for('indent') and Symbol.for('newline')
118
+ * @returns Formatting metadata, or defaults if symbols not present
119
+ */
120
+ export declare function getFormattingFromContent(content: Record<string | symbol, unknown>): JsonFormatting;
121
+ /**
122
+ * Determine if content should be saved based on changes and options.
123
+ * Compares current content with original content and respects options like
124
+ * ignoreWhitespace and sort.
125
+ *
126
+ * @param currentContent - Current content object (may include formatting symbols)
127
+ * @param originalContent - Original content for comparison (may include formatting symbols)
128
+ * @param originalFileContent - Original file content as string (for whitespace comparison)
129
+ * @param options - Options controlling save behavior
130
+ * @returns true if content should be saved, false otherwise
131
+ *
132
+ * @example
133
+ * ```ts
134
+ * const current = { key: 'new-value', [Symbol.for('indent')]: 2 }
135
+ * const original = { key: 'old-value', [Symbol.for('indent')]: 2 }
136
+ * shouldSave(current, original, '{\n "key": "old-value"\n}\n')
137
+ * // => true
138
+ * ```
139
+ */
140
+ export declare function shouldSave(currentContent: Record<string | symbol, unknown>, originalContent: Record<string | symbol, unknown> | undefined, originalFileContent: string, options?: ShouldSaveOptions): boolean;
@@ -0,0 +1,121 @@
1
+ "use strict";
2
+ /* Socket Lib - Built with esbuild */
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __export = (target, all) => {
8
+ for (var name in all)
9
+ __defProp(target, name, { get: all[name], enumerable: true });
10
+ };
11
+ var __copyProps = (to, from, except, desc) => {
12
+ if (from && typeof from === "object" || typeof from === "function") {
13
+ for (let key of __getOwnPropNames(from))
14
+ if (!__hasOwnProp.call(to, key) && key !== except)
15
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
+ }
17
+ return to;
18
+ };
19
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
20
+ var format_exports = {};
21
+ __export(format_exports, {
22
+ INDENT_SYMBOL: () => INDENT_SYMBOL,
23
+ NEWLINE_SYMBOL: () => NEWLINE_SYMBOL,
24
+ detectIndent: () => detectIndent,
25
+ detectNewline: () => detectNewline,
26
+ extractFormatting: () => extractFormatting,
27
+ getDefaultFormatting: () => getDefaultFormatting,
28
+ getFormattingFromContent: () => getFormattingFromContent,
29
+ shouldSave: () => shouldSave,
30
+ sortKeys: () => sortKeys,
31
+ stringifyWithFormatting: () => stringifyWithFormatting,
32
+ stripFormattingSymbols: () => stripFormattingSymbols
33
+ });
34
+ module.exports = __toCommonJS(format_exports);
35
+ const INDENT_SYMBOL = Symbol.for("indent");
36
+ const NEWLINE_SYMBOL = Symbol.for("newline");
37
+ function detectIndent(json) {
38
+ const match = json.match(/^[{[][\r\n]+(\s+)/m);
39
+ if (!match) {
40
+ return 2;
41
+ }
42
+ const indent = match[1];
43
+ if (/^ +$/.test(indent)) {
44
+ return indent.length;
45
+ }
46
+ return indent;
47
+ }
48
+ function detectNewline(json) {
49
+ const match = json.match(/\r?\n/);
50
+ return match ? match[0] : "\n";
51
+ }
52
+ function extractFormatting(json) {
53
+ return {
54
+ indent: detectIndent(json),
55
+ newline: detectNewline(json)
56
+ };
57
+ }
58
+ function getDefaultFormatting() {
59
+ return {
60
+ indent: 2,
61
+ newline: "\n"
62
+ };
63
+ }
64
+ function sortKeys(obj) {
65
+ const sorted = { __proto__: null };
66
+ const keys = Object.keys(obj).sort();
67
+ for (const key of keys) {
68
+ sorted[key] = obj[key];
69
+ }
70
+ return sorted;
71
+ }
72
+ function stringifyWithFormatting(content, formatting) {
73
+ const { indent, newline } = formatting;
74
+ const format = indent === void 0 || indent === null ? " " : indent;
75
+ const eol = newline === void 0 || newline === null ? "\n" : newline;
76
+ return `${JSON.stringify(content, void 0, format)}
77
+ `.replace(/\n/g, eol);
78
+ }
79
+ function stripFormattingSymbols(content) {
80
+ const {
81
+ [INDENT_SYMBOL]: _indent,
82
+ [NEWLINE_SYMBOL]: _newline,
83
+ ...rest
84
+ } = content;
85
+ return rest;
86
+ }
87
+ function getFormattingFromContent(content) {
88
+ const indent = content[INDENT_SYMBOL];
89
+ const newline = content[NEWLINE_SYMBOL];
90
+ return {
91
+ indent: indent === void 0 || indent === null ? 2 : indent,
92
+ newline: newline === void 0 || newline === null ? "\n" : newline
93
+ };
94
+ }
95
+ function shouldSave(currentContent, originalContent, originalFileContent, options = {}) {
96
+ const { ignoreWhitespace = false, sort = false, sortFn } = options;
97
+ const content = stripFormattingSymbols(currentContent);
98
+ const sortedContent = sortFn ? sortFn(content) : sort ? sortKeys(content) : content;
99
+ const origContent = originalContent ? stripFormattingSymbols(originalContent) : {};
100
+ if (ignoreWhitespace) {
101
+ const util = require("node:util");
102
+ return !util.isDeepStrictEqual(sortedContent, origContent);
103
+ }
104
+ const formatting = getFormattingFromContent(currentContent);
105
+ const newFileContent = stringifyWithFormatting(sortedContent, formatting);
106
+ return newFileContent.trim() !== originalFileContent.trim();
107
+ }
108
+ // Annotate the CommonJS export names for ESM import in node:
109
+ 0 && (module.exports = {
110
+ INDENT_SYMBOL,
111
+ NEWLINE_SYMBOL,
112
+ detectIndent,
113
+ detectNewline,
114
+ extractFormatting,
115
+ getDefaultFormatting,
116
+ getFormattingFromContent,
117
+ shouldSave,
118
+ sortKeys,
119
+ stringifyWithFormatting,
120
+ stripFormattingSymbols
121
+ });
@@ -0,0 +1,76 @@
1
+ import type { JsonParseOptions, JsonPrimitive, JsonValue } from './types';
2
+ /**
3
+ * Check if a value is a JSON primitive type.
4
+ * JSON primitives are: `null`, `boolean`, `number`, or `string`.
5
+ *
6
+ * @param value - Value to check
7
+ * @returns `true` if value is a JSON primitive, `false` otherwise
8
+ *
9
+ * @example
10
+ * ```ts
11
+ * isJsonPrimitive(null) // => true
12
+ * isJsonPrimitive(true) // => true
13
+ * isJsonPrimitive(42) // => true
14
+ * isJsonPrimitive('hello') // => true
15
+ * isJsonPrimitive({}) // => false
16
+ * isJsonPrimitive([]) // => false
17
+ * isJsonPrimitive(undefined) // => false
18
+ * ```
19
+ */
20
+ /*@__NO_SIDE_EFFECTS__*/
21
+ export declare function isJsonPrimitive(value: unknown): value is JsonPrimitive;
22
+ /**
23
+ * Parse JSON content with automatic Buffer handling and BOM stripping.
24
+ * Provides safer JSON parsing with helpful error messages and optional error suppression.
25
+ *
26
+ * Features:
27
+ * - Automatic UTF-8 Buffer conversion
28
+ * - BOM (Byte Order Mark) stripping for cross-platform compatibility
29
+ * - Enhanced error messages with filepath context
30
+ * - Optional error suppression (returns `undefined` instead of throwing)
31
+ * - Optional reviver for transforming parsed values
32
+ *
33
+ * @param content - JSON string or Buffer to parse
34
+ * @param options - Optional parsing configuration
35
+ * @returns Parsed JSON value, or `undefined` if parsing fails and `throws` is `false`
36
+ *
37
+ * @throws {SyntaxError} When JSON is invalid and `throws` is `true` (default)
38
+ *
39
+ * @example
40
+ * ```ts
41
+ * // Basic usage
42
+ * const data = jsonParse('{"name":"example"}')
43
+ * console.log(data.name) // => 'example'
44
+ *
45
+ * // Parse Buffer with UTF-8 BOM
46
+ * const buffer = Buffer.from('\uFEFF{"value":42}')
47
+ * const data = jsonParse(buffer)
48
+ * console.log(data.value) // => 42
49
+ *
50
+ * // Enhanced error messages with filepath
51
+ * try {
52
+ * jsonParse('invalid', { filepath: 'config.json' })
53
+ * } catch (err) {
54
+ * console.error(err.message)
55
+ * // => "config.json: Unexpected token i in JSON at position 0"
56
+ * }
57
+ *
58
+ * // Suppress errors
59
+ * const result = jsonParse('invalid', { throws: false })
60
+ * console.log(result) // => undefined
61
+ *
62
+ * // Transform values with reviver
63
+ * const json = '{"created":"2024-01-15T10:30:00Z"}'
64
+ * const data = jsonParse(json, {
65
+ * reviver: (key, value) => {
66
+ * if (key === 'created' && typeof value === 'string') {
67
+ * return new Date(value)
68
+ * }
69
+ * return value
70
+ * }
71
+ * })
72
+ * console.log(data.created instanceof Date) // => true
73
+ * ```
74
+ */
75
+ /*@__NO_SIDE_EFFECTS__*/
76
+ export declare function jsonParse(content: string | Buffer, options?: JsonParseOptions | undefined): JsonValue | undefined;
@@ -17,13 +17,13 @@ var __copyProps = (to, from, except, desc) => {
17
17
  return to;
18
18
  };
19
19
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
20
- var json_exports = {};
21
- __export(json_exports, {
20
+ var parse_exports = {};
21
+ __export(parse_exports, {
22
22
  isJsonPrimitive: () => isJsonPrimitive,
23
23
  jsonParse: () => jsonParse
24
24
  });
25
- module.exports = __toCommonJS(json_exports);
26
- var import_strings = require("./strings");
25
+ module.exports = __toCommonJS(parse_exports);
26
+ var import_strings = require("../strings");
27
27
  const JSONParse = JSON.parse;
28
28
  // @__NO_SIDE_EFFECTS__
29
29
  function isBuffer(x) {
@@ -0,0 +1,229 @@
1
+ /**
2
+ * @fileoverview JSON type definitions and interfaces.
3
+ */
4
+ /**
5
+ * JSON primitive types: `null`, `boolean`, `number`, or `string`.
6
+ *
7
+ * @example
8
+ * ```ts
9
+ * const primitives: JsonPrimitive[] = [null, true, 42, 'hello']
10
+ * ```
11
+ */
12
+ export type JsonPrimitive = null | boolean | number | string;
13
+ /**
14
+ * A JSON array containing JSON values.
15
+ *
16
+ * @example
17
+ * ```ts
18
+ * const arr: JsonArray = [1, 'two', { three: 3 }, [4, 5]]
19
+ * ```
20
+ */
21
+ export interface JsonArray extends Array<JsonValue> {
22
+ }
23
+ /**
24
+ * A JSON object with string keys and JSON values.
25
+ *
26
+ * @example
27
+ * ```ts
28
+ * const obj: JsonObject = {
29
+ * name: 'example',
30
+ * count: 42,
31
+ * active: true,
32
+ * nested: { key: 'value' }
33
+ * }
34
+ * ```
35
+ */
36
+ export interface JsonObject {
37
+ [key: string]: JsonValue;
38
+ }
39
+ /**
40
+ * Any valid JSON value: primitive, object, or array.
41
+ *
42
+ * @example
43
+ * ```ts
44
+ * const values: JsonValue[] = [
45
+ * null,
46
+ * true,
47
+ * 42,
48
+ * 'hello',
49
+ * { key: 'value' },
50
+ * [1, 2, 3]
51
+ * ]
52
+ * ```
53
+ */
54
+ export type JsonValue = JsonPrimitive | JsonObject | JsonArray;
55
+ /**
56
+ * Reviver function for transforming parsed JSON values.
57
+ * Called for each key-value pair during parsing.
58
+ *
59
+ * @param key - The object key or array index being parsed
60
+ * @param value - The parsed value
61
+ * @returns The transformed value (or original if no transform needed)
62
+ *
63
+ * @example
64
+ * ```ts
65
+ * // Convert date strings to Date objects
66
+ * const reviver: JsonReviver = (key, value) => {
67
+ * if (typeof value === 'string' && /^\d{4}-\d{2}-\d{2}/.test(value)) {
68
+ * return new Date(value)
69
+ * }
70
+ * return value
71
+ * }
72
+ * ```
73
+ */
74
+ export type JsonReviver = (key: string, value: unknown) => unknown;
75
+ /**
76
+ * Options for JSON parsing operations.
77
+ */
78
+ export interface JsonParseOptions {
79
+ /**
80
+ * Optional filepath for improved error messages.
81
+ * When provided, errors will be prefixed with the filepath.
82
+ *
83
+ * @example
84
+ * ```ts
85
+ * // Error message will be: "config.json: Unexpected token } in JSON"
86
+ * jsonParse('invalid', { filepath: 'config.json' })
87
+ * ```
88
+ */
89
+ filepath?: string | undefined;
90
+ /**
91
+ * Optional reviver function to transform parsed values.
92
+ * Called for each key-value pair during parsing.
93
+ *
94
+ * @example
95
+ * ```ts
96
+ * // Convert ISO date strings to Date objects
97
+ * const options = {
98
+ * reviver: (key, value) => {
99
+ * if (typeof value === 'string' && /^\d{4}-\d{2}-\d{2}/.test(value)) {
100
+ * return new Date(value)
101
+ * }
102
+ * return value
103
+ * }
104
+ * }
105
+ * ```
106
+ */
107
+ reviver?: JsonReviver | undefined;
108
+ /**
109
+ * Whether to throw on parse errors.
110
+ * When `false`, returns `undefined` instead of throwing.
111
+ *
112
+ * @default true
113
+ *
114
+ * @example
115
+ * ```ts
116
+ * // Throws error
117
+ * jsonParse('invalid', { throws: true })
118
+ *
119
+ * // Returns undefined
120
+ * const result = jsonParse('invalid', { throws: false })
121
+ * ```
122
+ */
123
+ throws?: boolean | undefined;
124
+ }
125
+ /**
126
+ * Options for saving editable JSON files.
127
+ */
128
+ export interface EditableJsonSaveOptions {
129
+ /**
130
+ * Whether to ignore whitespace-only changes when determining if save is needed.
131
+ * @default false
132
+ */
133
+ ignoreWhitespace?: boolean | undefined;
134
+ /**
135
+ * Whether to sort object keys alphabetically before saving.
136
+ * @default false
137
+ */
138
+ sort?: boolean | undefined;
139
+ }
140
+ /**
141
+ * Options for creating or loading editable JSON instances.
142
+ */
143
+ export interface EditableJsonOptions<T = Record<string, unknown>> {
144
+ /**
145
+ * File path for the JSON file (optional for in-memory instances).
146
+ */
147
+ path?: string | undefined;
148
+ /**
149
+ * Whether to create the file if it doesn't exist during load.
150
+ * @default false
151
+ */
152
+ create?: boolean | undefined;
153
+ /**
154
+ * Initial data to populate the instance with.
155
+ */
156
+ data?: T | undefined;
157
+ }
158
+ /**
159
+ * EditableJson instance interface for JSON file manipulation.
160
+ * Provides core functionality for loading, editing, and saving JSON files
161
+ * while preserving formatting (indentation and line endings).
162
+ */
163
+ export interface EditableJsonInstance<T = Record<string, unknown>> {
164
+ /**
165
+ * The parsed JSON content as a readonly object.
166
+ * @readonly
167
+ */
168
+ content: Readonly<T>;
169
+ /**
170
+ * Create a new JSON file at the specified path.
171
+ * @param path - The file path where JSON will be created
172
+ */
173
+ create(path: string): this;
174
+ /**
175
+ * Initialize the instance from a content object.
176
+ * Note: Disables saving when used (no file path associated).
177
+ * @param content - The JSON content object
178
+ */
179
+ fromContent(content: unknown): this;
180
+ /**
181
+ * Initialize the instance from a JSON string.
182
+ * @param json - The JSON content as a string
183
+ */
184
+ fromJSON(json: string): this;
185
+ /**
186
+ * Load a JSON file from the specified path.
187
+ * @param path - The file path to load
188
+ * @param create - Whether to create the file if it doesn't exist
189
+ */
190
+ load(path: string, create?: boolean): Promise<this>;
191
+ /**
192
+ * Update the JSON content with new values.
193
+ * @param content - Partial object with fields to update
194
+ */
195
+ update(content: Partial<T>): this;
196
+ /**
197
+ * Save the JSON file to disk.
198
+ * @param options - Save options for formatting and sorting
199
+ */
200
+ save(options?: EditableJsonSaveOptions): Promise<boolean>;
201
+ /**
202
+ * Synchronously save the JSON file to disk.
203
+ * @param options - Save options for formatting and sorting
204
+ */
205
+ saveSync(options?: EditableJsonSaveOptions): boolean;
206
+ /**
207
+ * Check if the JSON will be saved based on current changes.
208
+ * @param options - Save options to evaluate
209
+ */
210
+ willSave(options?: EditableJsonSaveOptions): boolean;
211
+ /**
212
+ * The full path to the JSON file.
213
+ * @readonly
214
+ */
215
+ readonly filename: string;
216
+ /**
217
+ * The directory path containing the JSON file.
218
+ * @readonly
219
+ */
220
+ readonly path: string | undefined;
221
+ }
222
+ /**
223
+ * EditableJson constructor interface.
224
+ */
225
+ export interface EditableJsonConstructor<T = Record<string, unknown>> {
226
+ new (): EditableJsonInstance<T>;
227
+ create(path: string, opts?: EditableJsonOptions<T>): Promise<EditableJsonInstance<T>>;
228
+ load(path: string, opts?: EditableJsonOptions<T>): Promise<EditableJsonInstance<T>>;
229
+ }
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+ /* Socket Lib - Built with esbuild */
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __copyProps = (to, from, except, desc) => {
8
+ if (from && typeof from === "object" || typeof from === "function") {
9
+ for (let key of __getOwnPropNames(from))
10
+ if (!__hasOwnProp.call(to, key) && key !== except)
11
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
12
+ }
13
+ return to;
14
+ };
15
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
16
+ var types_exports = {};
17
+ module.exports = __toCommonJS(types_exports);
@@ -27,22 +27,21 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
27
27
  mod
28
28
  ));
29
29
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
30
- var editable_exports = {};
31
- __export(editable_exports, {
30
+ var edit_exports = {};
31
+ __export(edit_exports, {
32
32
  getEditablePackageJsonClass: () => getEditablePackageJsonClass,
33
33
  pkgJsonToEditable: () => pkgJsonToEditable,
34
34
  toEditablePackageJson: () => toEditablePackageJson,
35
35
  toEditablePackageJsonSync: () => toEditablePackageJsonSync
36
36
  });
37
- module.exports = __toCommonJS(editable_exports);
37
+ module.exports = __toCommonJS(edit_exports);
38
38
  var import_package_json = __toESM(require("../external/@npmcli/package-json"));
39
39
  var import_read_package = require("../external/@npmcli/package-json/lib/read-package");
40
40
  var import_sort = require("../external/@npmcli/package-json/lib/sort");
41
+ var import_format = require("../json/format");
41
42
  var import_normalize = require("../paths/normalize");
42
43
  var import_normalize2 = require("./normalize");
43
44
  var import_packages = require("../paths/packages");
44
- const identSymbol = Symbol.for("indent");
45
- const newlineSymbol = Symbol.for("newline");
46
45
  let _EditablePackageJsonClass;
47
46
  let _fs;
48
47
  // @__NO_SIDE_EFFECTS__
@@ -193,35 +192,22 @@ function getEditablePackageJsonClass() {
193
192
  if (!this._canSave || this.content === void 0) {
194
193
  throw new Error("No package.json to save to");
195
194
  }
196
- const { ignoreWhitespace = false, sort = false } = {
197
- __proto__: null,
198
- ...options
199
- };
200
- const {
201
- [identSymbol]: indent,
202
- [newlineSymbol]: newline,
203
- ...rest
204
- } = this.content;
205
- const content = sort ? (0, import_sort.packageSort)(rest) : rest;
206
- const {
207
- [identSymbol]: _indent,
208
- [newlineSymbol]: _newline,
209
- ...origContent
210
- } = this._readFileJson || {};
211
- if (ignoreWhitespace && (/* @__PURE__ */ getUtil()).isDeepStrictEqual(content, origContent)) {
212
- return false;
213
- }
214
- const format = indent === void 0 || indent === null ? " " : indent;
215
- const eol = newline === void 0 || newline === null ? "\n" : newline;
216
- const fileContent = `${JSON.stringify(
217
- content,
218
- void 0,
219
- format
220
- )}
221
- `.replace(/\n/g, eol);
222
- if (!ignoreWhitespace && fileContent.trim() === this._readFileContent.trim()) {
195
+ if (!(0, import_format.shouldSave)(
196
+ this.content,
197
+ this._readFileJson,
198
+ this._readFileContent,
199
+ { ...options, sortFn: options?.sort ? import_sort.packageSort : void 0 }
200
+ )) {
223
201
  return false;
224
202
  }
203
+ const content = (0, import_format.stripFormattingSymbols)(
204
+ this.content
205
+ );
206
+ const sortedContent = options?.sort ? (0, import_sort.packageSort)(content) : content;
207
+ const formatting = (0, import_format.getFormattingFromContent)(
208
+ this.content
209
+ );
210
+ const fileContent = (0, import_format.stringifyWithFormatting)(sortedContent, formatting);
225
211
  const { promises: fsPromises } = /* @__PURE__ */ getFs();
226
212
  await fsPromises.writeFile(this.filename, fileContent);
227
213
  this._readFileContent = fileContent;