@effected/yaml 0.2.0 → 0.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/Yaml.js +157 -35
- package/index.d.ts +67 -2
- package/internal/fold.js +86 -1
- package/internal/stringifier.js +12 -8
- package/package.json +1 -1
package/Yaml.js
CHANGED
|
@@ -4,7 +4,7 @@ import { composeAllDocuments, composeFirstDocument } from "./internal/composer/d
|
|
|
4
4
|
import { isFatalCode } from "./internal/diagnostics.js";
|
|
5
5
|
import { StringifyDepthExceeded, StringifyFailure, stringifyValue } from "./internal/stringifier.js";
|
|
6
6
|
import { YamlDiagnostic } from "./YamlDiagnostic.js";
|
|
7
|
-
import { Effect, Option, Schema, SchemaIssue, SchemaTransformation } from "effect";
|
|
7
|
+
import { Effect, Option, Result, Schema, SchemaIssue, SchemaTransformation } from "effect";
|
|
8
8
|
|
|
9
9
|
//#region src/Yaml.ts
|
|
10
10
|
/**
|
|
@@ -34,11 +34,18 @@ var YamlParseOptions = class extends Schema.Class("YamlParseOptions")({
|
|
|
34
34
|
}) {};
|
|
35
35
|
/**
|
|
36
36
|
* Options controlling stringify behavior. All fields are omissible; absent
|
|
37
|
-
* fields resolve to `indent` `2`, `lineWidth` `
|
|
37
|
+
* fields resolve to `indent` `2`, `lineWidth` `0`, `defaultScalarStyle`
|
|
38
38
|
* `"plain"`, `defaultCollectionStyle` `"block"`, `sortKeys` `false`,
|
|
39
39
|
* `indentSequences` `false`, `finalNewline` `true` and `forceDefaultStyles`
|
|
40
40
|
* `false`.
|
|
41
41
|
*
|
|
42
|
+
* `lineWidth` controls column-based scalar folding. The default `0` (and any
|
|
43
|
+
* value `<= 0`) never wraps, emitting byte-identical output to the historic
|
|
44
|
+
* no-fold behavior; a positive value folds long plain, double-quoted and
|
|
45
|
+
* block-folded (`>`) scalars at approximately that column, inserting only
|
|
46
|
+
* semantically transparent line breaks. Block-literal (`|`) content is never
|
|
47
|
+
* folded — literal blocks preserve their bytes by definition.
|
|
48
|
+
*
|
|
42
49
|
* `indentSequences` controls the presentation of block sequences nested under
|
|
43
50
|
* a mapping key: `false` (the default) emits them at the key's column — the
|
|
44
51
|
* kit's byte-compatible legacy form — while `true` indents them one level,
|
|
@@ -64,6 +71,11 @@ var YamlParseOptions = class extends Schema.Class("YamlParseOptions")({
|
|
|
64
71
|
*/
|
|
65
72
|
var YamlStringifyOptions = class extends Schema.Class("YamlStringifyOptions")({
|
|
66
73
|
indent: Schema.optionalKey(Schema.Number),
|
|
74
|
+
/**
|
|
75
|
+
* Column at which to fold long scalars. Default `0` (and any value `<= 0`)
|
|
76
|
+
* never wraps; a positive value folds plain, double-quoted and block-folded
|
|
77
|
+
* (`>`) scalars at approximately that column, never block-literal (`|`).
|
|
78
|
+
*/
|
|
67
79
|
lineWidth: Schema.optionalKey(Schema.Number),
|
|
68
80
|
defaultScalarStyle: Schema.optionalKey(ScalarStyle),
|
|
69
81
|
defaultCollectionStyle: Schema.optionalKey(CollectionStyle),
|
|
@@ -123,6 +135,89 @@ const toStringifyInput = (options) => options === void 0 ? {} : {
|
|
|
123
135
|
};
|
|
124
136
|
const toDiagnostics = (text, records) => records.map((r) => YamlDiagnostic.fromRaw(r, text));
|
|
125
137
|
/**
|
|
138
|
+
* Build the fatal {@link YamlParseError} for an alias-expansion "billion
|
|
139
|
+
* laughs" blow-up. The offending expansion has no source span, so the
|
|
140
|
+
* diagnostic carries zero offsets.
|
|
141
|
+
*/
|
|
142
|
+
const aliasCountExceededError = (message, text) => new YamlParseError({
|
|
143
|
+
diagnostics: [YamlDiagnostic.make({
|
|
144
|
+
code: "AliasCountExceeded",
|
|
145
|
+
message,
|
|
146
|
+
offset: 0,
|
|
147
|
+
length: 0,
|
|
148
|
+
line: 0,
|
|
149
|
+
character: 0
|
|
150
|
+
})],
|
|
151
|
+
input: text
|
|
152
|
+
});
|
|
153
|
+
/**
|
|
154
|
+
* Map an internal stringifier throw to its typed {@link YamlStringifyError},
|
|
155
|
+
* or return `undefined` for any other defect (which the caller re-throws).
|
|
156
|
+
* Shared by the Effect and synchronous stringify paths so both surface the
|
|
157
|
+
* hardening guards (circular reference, nesting-depth cap) identically.
|
|
158
|
+
*/
|
|
159
|
+
const stringifyDefectToError = (defect, value) => {
|
|
160
|
+
if (defect instanceof StringifyFailure) return new YamlStringifyError({
|
|
161
|
+
diagnostics: [YamlDiagnostic.make({
|
|
162
|
+
code: "CircularReference",
|
|
163
|
+
message: defect.reason,
|
|
164
|
+
offset: 0,
|
|
165
|
+
length: 0,
|
|
166
|
+
line: 0,
|
|
167
|
+
character: 0
|
|
168
|
+
})],
|
|
169
|
+
value
|
|
170
|
+
});
|
|
171
|
+
if (defect instanceof StringifyDepthExceeded) return new YamlStringifyError({
|
|
172
|
+
diagnostics: [YamlDiagnostic.make({
|
|
173
|
+
code: "NestingDepthExceeded",
|
|
174
|
+
message: defect.message,
|
|
175
|
+
offset: 0,
|
|
176
|
+
length: 0,
|
|
177
|
+
line: 0,
|
|
178
|
+
character: 0
|
|
179
|
+
})],
|
|
180
|
+
value
|
|
181
|
+
});
|
|
182
|
+
};
|
|
183
|
+
/**
|
|
184
|
+
* Synchronous single-document parse returning a {@link Result}. The pure
|
|
185
|
+
* engine bypasses the Effect runtime entirely: the composer, the failure
|
|
186
|
+
* collection and the alias-expansion budget all run inline, and every failure
|
|
187
|
+
* mode (fatal diagnostics, duplicate keys, a "billion laughs" blow-up) yields
|
|
188
|
+
* a `Failure` carrying a typed {@link YamlParseError} — never a throw.
|
|
189
|
+
*/
|
|
190
|
+
const parseSyncImpl = (text, options) => {
|
|
191
|
+
const doc = composeFirstDocument(text, toParseInput(options));
|
|
192
|
+
const failures = failureRecords(doc, options?.uniqueKeys ?? true);
|
|
193
|
+
if (failures.length > 0) return Result.fail(new YamlParseError({
|
|
194
|
+
diagnostics: toDiagnostics(text, failures),
|
|
195
|
+
input: text
|
|
196
|
+
}));
|
|
197
|
+
const anchors = /* @__PURE__ */ new Map();
|
|
198
|
+
try {
|
|
199
|
+
return Result.succeed(nodeToJsValue(doc.contents, anchors, options?.maxAliasCount ?? 100));
|
|
200
|
+
} catch (defect) {
|
|
201
|
+
if (defect instanceof AliasExpansionBudgetExceeded) return Result.fail(aliasCountExceededError(defect.message, text));
|
|
202
|
+
throw defect;
|
|
203
|
+
}
|
|
204
|
+
};
|
|
205
|
+
/**
|
|
206
|
+
* Synchronous stringify returning a {@link Result}. Mirrors {@link Yaml.stringify}
|
|
207
|
+
* without the Effect wrapper: a circular reference or a value nested past the
|
|
208
|
+
* recursion budget yields a `Failure` carrying a typed {@link YamlStringifyError},
|
|
209
|
+
* never a thrown defect.
|
|
210
|
+
*/
|
|
211
|
+
const stringifySyncImpl = (value, options) => {
|
|
212
|
+
try {
|
|
213
|
+
return Result.succeed(stringifyValue(value, toStringifyInput(options)));
|
|
214
|
+
} catch (defect) {
|
|
215
|
+
const error = stringifyDefectToError(defect, value);
|
|
216
|
+
if (error !== void 0) return Result.fail(error);
|
|
217
|
+
throw defect;
|
|
218
|
+
}
|
|
219
|
+
};
|
|
220
|
+
/**
|
|
126
221
|
* Collect the raw diagnostics that make a composed document a parse failure:
|
|
127
222
|
* every fatal-code error, plus DuplicateKey warnings promoted to errors when
|
|
128
223
|
* `uniqueKeys` is in force (the v3 `parse` contract). Order preserved:
|
|
@@ -142,45 +237,15 @@ const failureRecords = (doc, uniqueKeys) => {
|
|
|
142
237
|
const extractDocumentValue = (contents, anchors, maxAliasCount, text) => Effect.try({
|
|
143
238
|
try: () => nodeToJsValue(contents, anchors, maxAliasCount),
|
|
144
239
|
catch: (defect) => {
|
|
145
|
-
if (defect instanceof AliasExpansionBudgetExceeded) return
|
|
146
|
-
diagnostics: [YamlDiagnostic.make({
|
|
147
|
-
code: "AliasCountExceeded",
|
|
148
|
-
message: defect.message,
|
|
149
|
-
offset: 0,
|
|
150
|
-
length: 0,
|
|
151
|
-
line: 0,
|
|
152
|
-
character: 0
|
|
153
|
-
})],
|
|
154
|
-
input: text
|
|
155
|
-
});
|
|
240
|
+
if (defect instanceof AliasExpansionBudgetExceeded) return aliasCountExceededError(defect.message, text);
|
|
156
241
|
throw defect;
|
|
157
242
|
}
|
|
158
243
|
});
|
|
159
244
|
const stringifyOrFail = (value, options) => Effect.try({
|
|
160
245
|
try: () => stringifyValue(value, toStringifyInput(options)),
|
|
161
246
|
catch: (defect) => {
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
code: "CircularReference",
|
|
165
|
-
message: defect.reason,
|
|
166
|
-
offset: 0,
|
|
167
|
-
length: 0,
|
|
168
|
-
line: 0,
|
|
169
|
-
character: 0
|
|
170
|
-
})],
|
|
171
|
-
value
|
|
172
|
-
});
|
|
173
|
-
if (defect instanceof StringifyDepthExceeded) return new YamlStringifyError({
|
|
174
|
-
diagnostics: [YamlDiagnostic.make({
|
|
175
|
-
code: "NestingDepthExceeded",
|
|
176
|
-
message: defect.message,
|
|
177
|
-
offset: 0,
|
|
178
|
-
length: 0,
|
|
179
|
-
line: 0,
|
|
180
|
-
character: 0
|
|
181
|
-
})],
|
|
182
|
-
value
|
|
183
|
-
});
|
|
247
|
+
const error = stringifyDefectToError(defect, value);
|
|
248
|
+
if (error !== void 0) return error;
|
|
184
249
|
throw defect;
|
|
185
250
|
}
|
|
186
251
|
});
|
|
@@ -268,6 +333,63 @@ var Yaml = class Yaml {
|
|
|
268
333
|
return yield* stringifyOrFail(value, options);
|
|
269
334
|
});
|
|
270
335
|
/**
|
|
336
|
+
* Synchronous single-document parse, returning a {@link Result} instead of
|
|
337
|
+
* an `Effect`. A pure escape hatch for config-time callers that cannot
|
|
338
|
+
* `await` an Effect (a `vitest.config.ts` is the motivating case): it runs
|
|
339
|
+
* the same engine as {@link Yaml.parse} inline.
|
|
340
|
+
*
|
|
341
|
+
* Preserves the package contract — malformed and adversarial input fails
|
|
342
|
+
* typed, never as a defect. Fatal diagnostics, duplicate keys and a
|
|
343
|
+
* "billion laughs" alias-expansion blow-up all yield a `Failure` carrying a
|
|
344
|
+
* {@link YamlParseError}; the method never throws.
|
|
345
|
+
*
|
|
346
|
+
* @example
|
|
347
|
+
* ```ts
|
|
348
|
+
* import { Yaml } from "@effected/yaml";
|
|
349
|
+
* import { Result } from "effect";
|
|
350
|
+
*
|
|
351
|
+
* const result = Yaml.parseSync("name: Alice\nage: 30");
|
|
352
|
+
* if (Result.isSuccess(result)) {
|
|
353
|
+
* result.success; // { name: "Alice", age: 30 }
|
|
354
|
+
* } else {
|
|
355
|
+
* result.failure; // YamlParseError
|
|
356
|
+
* }
|
|
357
|
+
* ```
|
|
358
|
+
*
|
|
359
|
+
* @public
|
|
360
|
+
*/
|
|
361
|
+
static parseSync(text, options) {
|
|
362
|
+
return parseSyncImpl(text, options);
|
|
363
|
+
}
|
|
364
|
+
/**
|
|
365
|
+
* Synchronous stringify, returning a {@link Result} instead of an `Effect`.
|
|
366
|
+
* The pure counterpart to {@link Yaml.stringify} for config-time callers
|
|
367
|
+
* that cannot `await`.
|
|
368
|
+
*
|
|
369
|
+
* Preserves the package contract — a circular reference (`CircularReference`)
|
|
370
|
+
* or a value nested past the recursion budget (`NestingDepthExceeded`)
|
|
371
|
+
* yields a `Failure` carrying a {@link YamlStringifyError} rather than a
|
|
372
|
+
* thrown stack-overflow defect; the method never throws.
|
|
373
|
+
*
|
|
374
|
+
* @example
|
|
375
|
+
* ```ts
|
|
376
|
+
* import { Yaml } from "@effected/yaml";
|
|
377
|
+
* import { Result } from "effect";
|
|
378
|
+
*
|
|
379
|
+
* const result = Yaml.stringifySync({ name: "Alice" });
|
|
380
|
+
* if (Result.isFailure(result)) {
|
|
381
|
+
* result.failure; // YamlStringifyError
|
|
382
|
+
* } else {
|
|
383
|
+
* result.success; // "name: Alice\n"
|
|
384
|
+
* }
|
|
385
|
+
* ```
|
|
386
|
+
*
|
|
387
|
+
* @public
|
|
388
|
+
*/
|
|
389
|
+
static stringifySync(value, options) {
|
|
390
|
+
return stringifySyncImpl(value, options);
|
|
391
|
+
}
|
|
392
|
+
/**
|
|
271
393
|
* Strip comments from YAML text. Without `replaceCh`, comment characters
|
|
272
394
|
* are removed (line breaks are kept, so line numbers stay stable); with a
|
|
273
395
|
* `replaceCh` (e.g. `" "`), each comment character is replaced instead,
|
package/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { Data, Effect, Option, Schema, Stream } from "effect";
|
|
1
|
+
import { Data, Effect, Option, Result, Schema, Stream } from "effect";
|
|
2
2
|
//#region src/YamlDiagnostic.d.ts
|
|
3
3
|
/**
|
|
4
4
|
* Error codes emitted by the lexer stage.
|
|
@@ -145,6 +145,11 @@ declare const YamlParseOptions_base: Schema.Class<YamlParseOptions, Schema.Struc
|
|
|
145
145
|
declare class YamlParseOptions extends YamlParseOptions_base {}
|
|
146
146
|
declare const YamlStringifyOptions_base: Schema.Class<YamlStringifyOptions, Schema.Struct<{
|
|
147
147
|
readonly indent: Schema.optionalKey<Schema.Number>;
|
|
148
|
+
/**
|
|
149
|
+
* Column at which to fold long scalars. Default `0` (and any value `<= 0`)
|
|
150
|
+
* never wraps; a positive value folds plain, double-quoted and block-folded
|
|
151
|
+
* (`>`) scalars at approximately that column, never block-literal (`|`).
|
|
152
|
+
*/
|
|
148
153
|
readonly lineWidth: Schema.optionalKey<Schema.Number>;
|
|
149
154
|
readonly defaultScalarStyle: Schema.optionalKey<Schema.Literals<readonly ["plain", "single-quoted", "double-quoted", "block-literal", "block-folded"]>>;
|
|
150
155
|
readonly defaultCollectionStyle: Schema.optionalKey<Schema.Literals<readonly ["block", "flow"]>>;
|
|
@@ -155,11 +160,18 @@ declare const YamlStringifyOptions_base: Schema.Class<YamlStringifyOptions, Sche
|
|
|
155
160
|
}>, {}>;
|
|
156
161
|
/**
|
|
157
162
|
* Options controlling stringify behavior. All fields are omissible; absent
|
|
158
|
-
* fields resolve to `indent` `2`, `lineWidth` `
|
|
163
|
+
* fields resolve to `indent` `2`, `lineWidth` `0`, `defaultScalarStyle`
|
|
159
164
|
* `"plain"`, `defaultCollectionStyle` `"block"`, `sortKeys` `false`,
|
|
160
165
|
* `indentSequences` `false`, `finalNewline` `true` and `forceDefaultStyles`
|
|
161
166
|
* `false`.
|
|
162
167
|
*
|
|
168
|
+
* `lineWidth` controls column-based scalar folding. The default `0` (and any
|
|
169
|
+
* value `<= 0`) never wraps, emitting byte-identical output to the historic
|
|
170
|
+
* no-fold behavior; a positive value folds long plain, double-quoted and
|
|
171
|
+
* block-folded (`>`) scalars at approximately that column, inserting only
|
|
172
|
+
* semantically transparent line breaks. Block-literal (`|`) content is never
|
|
173
|
+
* folded — literal blocks preserve their bytes by definition.
|
|
174
|
+
*
|
|
163
175
|
* `indentSequences` controls the presentation of block sequences nested under
|
|
164
176
|
* a mapping key: `false` (the default) emits them at the key's column — the
|
|
165
177
|
* kit's byte-compatible legacy form — while `true` indents them one level,
|
|
@@ -271,6 +283,59 @@ declare class Yaml {
|
|
|
271
283
|
* rather than as an unhandled stack-overflow defect.
|
|
272
284
|
*/
|
|
273
285
|
static readonly stringify: (value: unknown, options?: YamlStringifyOptions | undefined) => Effect.Effect<string, YamlStringifyError, never>;
|
|
286
|
+
/**
|
|
287
|
+
* Synchronous single-document parse, returning a {@link Result} instead of
|
|
288
|
+
* an `Effect`. A pure escape hatch for config-time callers that cannot
|
|
289
|
+
* `await` an Effect (a `vitest.config.ts` is the motivating case): it runs
|
|
290
|
+
* the same engine as {@link Yaml.parse} inline.
|
|
291
|
+
*
|
|
292
|
+
* Preserves the package contract — malformed and adversarial input fails
|
|
293
|
+
* typed, never as a defect. Fatal diagnostics, duplicate keys and a
|
|
294
|
+
* "billion laughs" alias-expansion blow-up all yield a `Failure` carrying a
|
|
295
|
+
* {@link YamlParseError}; the method never throws.
|
|
296
|
+
*
|
|
297
|
+
* @example
|
|
298
|
+
* ```ts
|
|
299
|
+
* import { Yaml } from "@effected/yaml";
|
|
300
|
+
* import { Result } from "effect";
|
|
301
|
+
*
|
|
302
|
+
* const result = Yaml.parseSync("name: Alice\nage: 30");
|
|
303
|
+
* if (Result.isSuccess(result)) {
|
|
304
|
+
* result.success; // { name: "Alice", age: 30 }
|
|
305
|
+
* } else {
|
|
306
|
+
* result.failure; // YamlParseError
|
|
307
|
+
* }
|
|
308
|
+
* ```
|
|
309
|
+
*
|
|
310
|
+
* @public
|
|
311
|
+
*/
|
|
312
|
+
static parseSync(text: string, options?: YamlParseOptions): Result.Result<unknown, YamlParseError>;
|
|
313
|
+
/**
|
|
314
|
+
* Synchronous stringify, returning a {@link Result} instead of an `Effect`.
|
|
315
|
+
* The pure counterpart to {@link Yaml.stringify} for config-time callers
|
|
316
|
+
* that cannot `await`.
|
|
317
|
+
*
|
|
318
|
+
* Preserves the package contract — a circular reference (`CircularReference`)
|
|
319
|
+
* or a value nested past the recursion budget (`NestingDepthExceeded`)
|
|
320
|
+
* yields a `Failure` carrying a {@link YamlStringifyError} rather than a
|
|
321
|
+
* thrown stack-overflow defect; the method never throws.
|
|
322
|
+
*
|
|
323
|
+
* @example
|
|
324
|
+
* ```ts
|
|
325
|
+
* import { Yaml } from "@effected/yaml";
|
|
326
|
+
* import { Result } from "effect";
|
|
327
|
+
*
|
|
328
|
+
* const result = Yaml.stringifySync({ name: "Alice" });
|
|
329
|
+
* if (Result.isFailure(result)) {
|
|
330
|
+
* result.failure; // YamlStringifyError
|
|
331
|
+
* } else {
|
|
332
|
+
* result.success; // "name: Alice\n"
|
|
333
|
+
* }
|
|
334
|
+
* ```
|
|
335
|
+
*
|
|
336
|
+
* @public
|
|
337
|
+
*/
|
|
338
|
+
static stringifySync(value: unknown, options?: YamlStringifyOptions): Result.Result<string, YamlStringifyError>;
|
|
274
339
|
/**
|
|
275
340
|
* Strip comments from YAML text. Without `replaceCh`, comment characters
|
|
276
341
|
* are removed (line breaks are kept, so line numbers stay stable); with a
|
package/internal/fold.js
CHANGED
|
@@ -1,5 +1,90 @@
|
|
|
1
1
|
//#region src/internal/fold.ts
|
|
2
2
|
/**
|
|
3
|
+
* Column-based line folding for a single logical scalar line (YAML 1.2 flow
|
|
4
|
+
* folding, §7.3 / §8.2.1). Breaks the content at "safe" single-space
|
|
5
|
+
* boundaries — a space whose neighbours are both non-space — so each inserted
|
|
6
|
+
* line break is a *semantically transparent* fold: on read, a lone break
|
|
7
|
+
* between non-empty lines at the same indent folds back to a single space, and
|
|
8
|
+
* the leading indentation of continuation lines is absorbed as separation
|
|
9
|
+
* whitespace. The original space at the break point is consumed, replaced by
|
|
10
|
+
* the break, so no content whitespace is added or lost.
|
|
11
|
+
*
|
|
12
|
+
* Continuation lines are prefixed with `indent`. `indentAtStart` is the column
|
|
13
|
+
* the first line begins at (its content is already `indentAtStart` columns in),
|
|
14
|
+
* used only to budget the first line; it is approximate because the caller's
|
|
15
|
+
* exact column (after a `key: ` prefix, say) is not known here.
|
|
16
|
+
*
|
|
17
|
+
* Only breaks where a break is safe. When no safe break point exists before the
|
|
18
|
+
* width limit, the line overflows unwrapped rather than corrupting the value —
|
|
19
|
+
* width folding is a best-effort presentation concern, never a correctness one.
|
|
20
|
+
* A non-positive `lineWidth` (the default) returns the text unchanged.
|
|
21
|
+
*/
|
|
22
|
+
function foldScalarLine(text, indent, lineWidth, indentAtStart) {
|
|
23
|
+
if (lineWidth <= 0) return text;
|
|
24
|
+
const contentWidth = Math.max(1, lineWidth - indent.length);
|
|
25
|
+
let end = Math.max(1, lineWidth - indentAtStart);
|
|
26
|
+
const folds = [];
|
|
27
|
+
let split;
|
|
28
|
+
let prev;
|
|
29
|
+
for (let i = 0; i < text.length; i++) {
|
|
30
|
+
const ch = text[i];
|
|
31
|
+
if (ch === " " && prev !== void 0 && prev !== " ") {
|
|
32
|
+
const next = text[i + 1];
|
|
33
|
+
if (next !== void 0 && next !== " ") split = i;
|
|
34
|
+
}
|
|
35
|
+
if (i >= end && split !== void 0) {
|
|
36
|
+
folds.push(split);
|
|
37
|
+
end = split + contentWidth;
|
|
38
|
+
split = void 0;
|
|
39
|
+
}
|
|
40
|
+
prev = ch;
|
|
41
|
+
}
|
|
42
|
+
if (folds.length === 0) return text;
|
|
43
|
+
let result = text.slice(0, folds[0]);
|
|
44
|
+
for (let f = 0; f < folds.length; f++) {
|
|
45
|
+
const fold = folds[f];
|
|
46
|
+
const sliceEnd = folds[f + 1] ?? text.length;
|
|
47
|
+
result += `\n${indent}${text.slice(fold + 1, sliceEnd)}`;
|
|
48
|
+
}
|
|
49
|
+
return result;
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Apply {@link foldScalarLine} to an already-rendered scalar according to its
|
|
53
|
+
* style, inferred from the leading character:
|
|
54
|
+
*
|
|
55
|
+
* - `|` block-literal — returned unchanged; literal blocks preserve bytes by
|
|
56
|
+
* definition and must never be folded.
|
|
57
|
+
* - `>` block-folded — each base-indent body content line is folded; blank
|
|
58
|
+
* lines and more-indented lines (which the reader treats as literal breaks)
|
|
59
|
+
* are left untouched.
|
|
60
|
+
* - `"` double-quoted — the inner content is folded; breaking only at content
|
|
61
|
+
* spaces means no `\`-escaped continuations are needed.
|
|
62
|
+
* - `'` single-quoted — returned unchanged (out of scope for width folding).
|
|
63
|
+
* - otherwise plain — folded directly.
|
|
64
|
+
*
|
|
65
|
+
* `indent` is one indentation level (the continuation prefix); `lineWidth` is
|
|
66
|
+
* the target column. A non-positive `lineWidth` returns the text unchanged.
|
|
67
|
+
*/
|
|
68
|
+
function foldRenderedScalar(rendered, indent, lineWidth) {
|
|
69
|
+
if (lineWidth <= 0 || rendered.length === 0) return rendered;
|
|
70
|
+
const first = rendered[0];
|
|
71
|
+
if (first === "|" || first === "'") return rendered;
|
|
72
|
+
if (first === ">") {
|
|
73
|
+
const lines = rendered.split("\n");
|
|
74
|
+
const out = [lines[0]];
|
|
75
|
+
for (let i = 1; i < lines.length; i++) {
|
|
76
|
+
const line = lines[i];
|
|
77
|
+
if (line.length > indent.length && line.startsWith(indent) && line[indent.length] !== " " && line[indent.length] !== " ") {
|
|
78
|
+
const content = line.slice(indent.length);
|
|
79
|
+
out.push(indent + foldScalarLine(content, indent, lineWidth, indent.length));
|
|
80
|
+
} else out.push(line);
|
|
81
|
+
}
|
|
82
|
+
return out.join("\n");
|
|
83
|
+
}
|
|
84
|
+
if (first === "\"") return `"${foldScalarLine(rendered.slice(1, -1), indent, lineWidth, indent.length + 1)}"`;
|
|
85
|
+
return foldScalarLine(rendered, indent, lineWidth, indent.length);
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
3
88
|
* C0 control characters (except TAB) that must be escaped in double-quoted scalars.
|
|
4
89
|
*/
|
|
5
90
|
function isControlChar(code) {
|
|
@@ -150,4 +235,4 @@ function renderBlockFolded(s, indent) {
|
|
|
150
235
|
}
|
|
151
236
|
|
|
152
237
|
//#endregion
|
|
153
|
-
export { hasInteriorTrailingWhitespace, hasNewlineSpacesTab, isControlChar, renderBlockFolded, renderBlockLiteral, renderSingleQuotedMultiline };
|
|
238
|
+
export { foldRenderedScalar, foldScalarLine, hasInteriorTrailingWhitespace, hasNewlineSpacesTab, isControlChar, renderBlockFolded, renderBlockLiteral, renderSingleQuotedMultiline };
|
package/internal/stringifier.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { YamlAlias, YamlMap, YamlPair, YamlScalar, YamlSeq } from "../YamlNode.js";
|
|
2
|
-
import { hasInteriorTrailingWhitespace, hasNewlineSpacesTab, isControlChar, renderBlockFolded, renderBlockLiteral, renderSingleQuotedMultiline } from "./fold.js";
|
|
2
|
+
import { foldRenderedScalar, hasInteriorTrailingWhitespace, hasNewlineSpacesTab, isControlChar, renderBlockFolded, renderBlockLiteral, renderSingleQuotedMultiline } from "./fold.js";
|
|
3
3
|
|
|
4
4
|
//#region src/internal/stringifier.ts
|
|
5
5
|
/**
|
|
@@ -252,7 +252,7 @@ function detectCircular(value, seen) {
|
|
|
252
252
|
function createContext(options) {
|
|
253
253
|
return {
|
|
254
254
|
indent: options?.indent ?? 2,
|
|
255
|
-
lineWidth: options?.lineWidth ??
|
|
255
|
+
lineWidth: options?.lineWidth ?? 0,
|
|
256
256
|
defaultScalarStyle: options?.defaultScalarStyle ?? "plain",
|
|
257
257
|
defaultCollectionStyle: options?.defaultCollectionStyle ?? "block",
|
|
258
258
|
sortKeys: options?.sortKeys ?? false,
|
|
@@ -268,13 +268,17 @@ function createContext(options) {
|
|
|
268
268
|
* responsible for prepending the appropriate indentation prefix to each line.
|
|
269
269
|
* This avoids double-indentation when embedding nested collections.
|
|
270
270
|
*/
|
|
271
|
-
function stringifyLines(value, ctx, depth) {
|
|
271
|
+
function stringifyLines(value, ctx, depth, allowFold = true) {
|
|
272
272
|
if (depth > 256) throw new StringifyDepthExceeded();
|
|
273
273
|
if (value === null || value === void 0) return ["null"];
|
|
274
274
|
if (typeof value === "boolean") return [value ? "true" : "false"];
|
|
275
275
|
if (typeof value === "number") return [renderNumber(value)];
|
|
276
276
|
if (typeof value === "bigint") return [value.toString()];
|
|
277
|
-
if (typeof value === "string")
|
|
277
|
+
if (typeof value === "string") {
|
|
278
|
+
const indentStr = " ".repeat(ctx.indent);
|
|
279
|
+
const rendered = renderString(value, ctx.defaultScalarStyle, indentStr, false, ctx.forceDefaultStyles);
|
|
280
|
+
return (allowFold && ctx.lineWidth > 0 ? foldRenderedScalar(rendered, indentStr, ctx.lineWidth) : rendered).split("\n");
|
|
281
|
+
}
|
|
278
282
|
if (Array.isArray(value)) {
|
|
279
283
|
detectCircular(value, ctx.seen);
|
|
280
284
|
ctx.seen.add(value);
|
|
@@ -300,7 +304,7 @@ function stringifyLines(value, ctx, depth) {
|
|
|
300
304
|
*/
|
|
301
305
|
function stringifyArrayLines(arr, ctx, depth) {
|
|
302
306
|
if (arr.length === 0) return ["[]"];
|
|
303
|
-
if (ctx.defaultCollectionStyle === "flow") return [`[${arr.map((item) => stringifyLines(item, ctx, depth + 1).join(" ")).join(", ")}]`];
|
|
307
|
+
if (ctx.defaultCollectionStyle === "flow") return [`[${arr.map((item) => stringifyLines(item, ctx, depth + 1, false).join(" ")).join(", ")}]`];
|
|
304
308
|
const pad = " ".repeat(ctx.indent);
|
|
305
309
|
const lines = [];
|
|
306
310
|
for (const item of arr) {
|
|
@@ -308,7 +312,7 @@ function stringifyArrayLines(arr, ctx, depth) {
|
|
|
308
312
|
if (itemLines.length === 1) lines.push(`- ${itemLines[0]}`);
|
|
309
313
|
else {
|
|
310
314
|
const first = itemLines[0];
|
|
311
|
-
if (first.startsWith("|") || first.startsWith(">")) {
|
|
315
|
+
if (first.startsWith("|") || first.startsWith(">") || typeof item === "string") {
|
|
312
316
|
lines.push(`- ${first}`);
|
|
313
317
|
for (let i = 1; i < itemLines.length; i++) lines.push(itemLines[i]);
|
|
314
318
|
} else {
|
|
@@ -338,7 +342,7 @@ function stringifyObjectLines(obj, ctx, depth) {
|
|
|
338
342
|
if (keys.length === 0) return ["{}"];
|
|
339
343
|
if (ctx.sortKeys) keys.sort();
|
|
340
344
|
if (ctx.defaultCollectionStyle === "flow") return [`{${keys.map((k) => {
|
|
341
|
-
return `${renderString(k, "plain", "")}: ${stringifyLines(obj[k], ctx, depth + 1).join(" ")}`;
|
|
345
|
+
return `${renderString(k, "plain", "")}: ${stringifyLines(obj[k], ctx, depth + 1, false).join(" ")}`;
|
|
342
346
|
}).join(", ")}}`];
|
|
343
347
|
const renderKey = (k) => k.includes("\n") ? renderDoubleQuoted(k, ctx.forceDefaultStyles) : renderString(k, "plain", "");
|
|
344
348
|
const pad = " ".repeat(ctx.indent);
|
|
@@ -350,7 +354,7 @@ function stringifyObjectLines(obj, ctx, depth) {
|
|
|
350
354
|
if (valLines.length === 1 && !isBlockCollection(val, ctx)) lines.push(`${keyStr}: ${valLines[0]}`);
|
|
351
355
|
else {
|
|
352
356
|
const first = valLines[0];
|
|
353
|
-
if (first.startsWith("|") || first.startsWith(">")) {
|
|
357
|
+
if (first.startsWith("|") || first.startsWith(">") || typeof val === "string") {
|
|
354
358
|
lines.push(`${keyStr}: ${first}`);
|
|
355
359
|
for (let i = 1; i < valLines.length; i++) lines.push(valLines[i]);
|
|
356
360
|
} else if (Array.isArray(val) && val.length > 0) {
|