All files / ini / parse.ts

100.00% Branches 43/43
100.00% Lines 99/99
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
 
 
 
 
 
 
 
 
 
 
x5
x5
 
 
x5
x88
x88
x88
x88
 
x88
 
 
x5
x84
x103
x121
x121
x104
x104
 
x104
x144
x84
 
x64
x64
x64
x976
x976
x976
x1004
x1031
x1031
x976
x982
x982
x982
x982
x976
x1854
x1854
x976
x976
x122
x64
 
 
 
 
 
 
 
 
 
 
 
x5
x57
x57
x57
x57
x86
x57
x57
x77
x57
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
x5
x5
x5
 
x66
x68
x68
 
x125
 
x125
x125
x125
 
x125
x66
x158
x158
 
 
x158
 
 
x158
 
x158
x176
x176
x178
x178
 
x178
 
x192
x192
x192
x192
x192
x192
x192
 
x192
x192
 
x158
 
x158
x159
x159
 
x159
 
x217
x158
x159
x159
 
x216
x216
x216
x216
x216
x216
x216
x216
 
x120
x66

















































































































































































































// Copyright 2018-2025 the Deno authors. MIT license.
// This module is browser compatible.

/** Function for replacing INI values with JavaScript values. */
export type ReviverFunction = (
  key: string,
  value: string,
  section?: string,
) => unknown;

const SECTION_REGEXP = /^\[(?<name>.*\S.*)]$/;
const KEY_VALUE_REGEXP = /^(?<key>.*?)\s*=\s*(?<value>.*?)$/;

/** Detect supported comment styles. */
function isComment(input: string): boolean {
  return (
    input.startsWith("#") ||
    input.startsWith(";") ||
    input.startsWith("//")
  );
}

/** Detect a section start. */
function isSection(input: string, lineNumber: number): boolean {
  if (input.startsWith("[")) {
    if (input.endsWith("]")) {
      return true;
    }
    throw new SyntaxError(
      `Unexpected end of INI section at line ${lineNumber}`,
    );
  }
  return false;
}

function* readTextLines(text: string): Generator<string> {
  let line = "";
  for (let i = 0; i < text.length; i += 1) {
    const char = text[i];
    switch (char) {
      case "\n":
        yield line;
        line = "";
        break;
      case "\r":
        yield line;
        line = "";
        if (text[i + 1] === "\n") i += 1;
        break;
      default:
        line += char;
        break;
    }
  }
  yield line;
}

/** Options for {@linkcode parse}. */
export interface ParseOptions {
  /**
   * Provide custom parsing of the value in a key/value pair. Similar to the
   * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#reviver | reviver}
   * function in {@linkcode JSON.parse}.
   */
  reviver?: ReviverFunction;
}

const QUOTED_VALUE_REGEXP = /^"(?<value>.*)"$/;
function defaultReviver(_key: string, value: string, _section?: string) {
  if (value === "null") return null;
  if (value === "true") return true;
  if (value === "false") return false;
  const match = value.match(QUOTED_VALUE_REGEXP);
  if (match) return match.groups?.value as string;
  if (!isNaN(+value)) return +value;
  return value;
}

/**
 * Parse an INI config string into an object.
 *
 * Values are parsed as strings by default to preserve data parity from the
 * original. To parse values as other types besides strings, use
 * {@linkcode ParseOptions.reviver}.
 *
 * Nested sections, repeated key names within a section, and key/value arrays
 * are not supported. White space padding and lines starting with `#`, `;`, or
 * `//` will be treated as comments.
 *
 * @throws {SyntaxError} If the INI string is invalid or if it contains
 * multi-line values.
 *
 * @example Usage
 * ```ts
 * import { parse } from "@std/ini/parse";
 * import { assertEquals } from "@std/assert";
 *
 * const parsed = parse(`
 * key = value
 *
 * [section 1]
 * foo = Hello
 * baz = World
 * `);
 *
 * assertEquals(parsed, { key: "value", "section 1": { foo: "Hello", baz: "World" } })
 * ```
 *
 * @example Using custom reviver
 * ```ts
 * import { parse } from "@std/ini/parse";
 * import { assertEquals } from "@std/assert";
 *
 * const parsed = parse(`
 * [section Foo]
 * date = 2012-10-10
 * amount = 12345
 * `, {
 *   reviver(key, value, section) {
 *     if (section === "section Foo") {
 *       if (key === "date") {
 *         return new Date(value);
 *       } else if (key === "amount") {
 *         return +value;
 *       }
 *     }
 *     return value;
 *   }
 * });
 *
 * assertEquals(parsed, {
 *   "section Foo": {
 *     date: new Date("2012-10-10"),
 *     amount: 12345,
 *   }
 * })
 * ```
 *
 * @param text The text to parse
 * @param options The options to use
 * @typeParam T The type of the value
 * @return The parsed object
 */
export function parse<T extends object>(
  text: string,
  options: ParseOptions = {},
): T {
  if (typeof text !== "string") {
    throw new SyntaxError(`Unexpected token ${text} in INI at line 0`);
  }

  const { reviver = defaultReviver } = options;

  const root = {} as T;
  let object: object = root;
  let sectionName: string | undefined;

  let lineNumber = 0;
  for (let line of readTextLines(text)) {
    line = line.trim();
    lineNumber += 1;

    // skip empty lines
    if (line === "") continue;

    // skip comment
    if (isComment(line)) continue;

    if (isSection(line, lineNumber)) {
      sectionName = SECTION_REGEXP.exec(line)?.groups?.name;
      if (!sectionName) {
        throw new SyntaxError(
          `Unexpected empty section name at line ${lineNumber}`,
        );
      }

      object = {};
      Object.defineProperty(root, sectionName, {
        value: object,
        writable: true,
        enumerable: true,
        configurable: true,
      });

      continue;
    }

    const groups = KEY_VALUE_REGEXP.exec(line)?.groups;

    if (!groups) {
      throw new SyntaxError(
        `Unexpected token ${line[0]} in INI at line ${lineNumber}`,
      );
    }

    const { key, value } = groups as { key: string; value: string };
    if (!key.length) {
      throw new SyntaxError(`Unexpected empty key name at line ${lineNumber}`);
    }

    const val = reviver(key, value, sectionName);
    Object.defineProperty(object, key, {
      value: val,
      writable: true,
      enumerable: true,
      configurable: true,
    });
  }

  return root;
}