ini.js 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  1. const { hasOwnProperty } = Object.prototype
  2. const encode = (obj, opt = {}) => {
  3. if (typeof opt === 'string') {
  4. opt = { section: opt }
  5. }
  6. opt.align = opt.align === true
  7. opt.newline = opt.newline === true
  8. opt.sort = opt.sort === true
  9. opt.whitespace = opt.whitespace === true || opt.align === true
  10. // The `typeof` check is required because accessing the `process` directly fails on browsers.
  11. /* istanbul ignore next */
  12. opt.platform = opt.platform || (typeof process !== 'undefined' && process.platform)
  13. opt.bracketedArray = opt.bracketedArray !== false
  14. /* istanbul ignore next */
  15. const eol = opt.platform === 'win32' ? '\r\n' : '\n'
  16. const separator = opt.whitespace ? ' = ' : '='
  17. const children = []
  18. const keys = opt.sort ? Object.keys(obj).sort() : Object.keys(obj)
  19. let padToChars = 0
  20. // If aligning on the separator, then padToChars is determined as follows:
  21. // 1. Get the keys
  22. // 2. Exclude keys pointing to objects unless the value is null or an array
  23. // 3. Add `[]` to array keys
  24. // 4. Ensure non empty set of keys
  25. // 5. Reduce the set to the longest `safe` key
  26. // 6. Get the `safe` length
  27. if (opt.align) {
  28. padToChars = safe(
  29. (
  30. keys
  31. .filter(k => obj[k] === null || Array.isArray(obj[k]) || typeof obj[k] !== 'object')
  32. .map(k => Array.isArray(obj[k]) ? `${k}[]` : k)
  33. )
  34. .concat([''])
  35. .reduce((a, b) => safe(a).length >= safe(b).length ? a : b)
  36. ).length
  37. }
  38. let out = ''
  39. const arraySuffix = opt.bracketedArray ? '[]' : ''
  40. for (const k of keys) {
  41. const val = obj[k]
  42. if (val && Array.isArray(val)) {
  43. for (const item of val) {
  44. out += safe(`${k}${arraySuffix}`).padEnd(padToChars, ' ') + separator + safe(item) + eol
  45. }
  46. } else if (val && typeof val === 'object') {
  47. children.push(k)
  48. } else {
  49. out += safe(k).padEnd(padToChars, ' ') + separator + safe(val) + eol
  50. }
  51. }
  52. if (opt.section && out.length) {
  53. out = '[' + safe(opt.section) + ']' + (opt.newline ? eol + eol : eol) + out
  54. }
  55. for (const k of children) {
  56. const nk = splitSections(k, '.').join('\\.')
  57. const section = (opt.section ? opt.section + '.' : '') + nk
  58. const child = encode(obj[k], {
  59. ...opt,
  60. section,
  61. })
  62. if (out.length && child.length) {
  63. out += eol
  64. }
  65. out += child
  66. }
  67. return out
  68. }
  69. function splitSections (str, separator) {
  70. var lastMatchIndex = 0
  71. var lastSeparatorIndex = 0
  72. var nextIndex = 0
  73. var sections = []
  74. do {
  75. nextIndex = str.indexOf(separator, lastMatchIndex)
  76. if (nextIndex !== -1) {
  77. lastMatchIndex = nextIndex + separator.length
  78. if (nextIndex > 0 && str[nextIndex - 1] === '\\') {
  79. continue
  80. }
  81. sections.push(str.slice(lastSeparatorIndex, nextIndex))
  82. lastSeparatorIndex = nextIndex + separator.length
  83. }
  84. } while (nextIndex !== -1)
  85. sections.push(str.slice(lastSeparatorIndex))
  86. return sections
  87. }
  88. const decode = (str, opt = {}) => {
  89. opt.bracketedArray = opt.bracketedArray !== false
  90. const out = Object.create(null)
  91. let p = out
  92. let section = null
  93. // section |key = value
  94. const re = /^\[([^\]]*)\]\s*$|^([^=]+)(=(.*))?$/i
  95. const lines = str.split(/[\r\n]+/g)
  96. const duplicates = {}
  97. for (const line of lines) {
  98. if (!line || line.match(/^\s*[;#]/) || line.match(/^\s*$/)) {
  99. continue
  100. }
  101. const match = line.match(re)
  102. if (!match) {
  103. continue
  104. }
  105. if (match[1] !== undefined) {
  106. section = unsafe(match[1])
  107. if (section === '__proto__') {
  108. // not allowed
  109. // keep parsing the section, but don't attach it.
  110. p = Object.create(null)
  111. continue
  112. }
  113. p = out[section] = out[section] || Object.create(null)
  114. continue
  115. }
  116. const keyRaw = unsafe(match[2])
  117. let isArray
  118. if (opt.bracketedArray) {
  119. isArray = keyRaw.length > 2 && keyRaw.slice(-2) === '[]'
  120. } else {
  121. duplicates[keyRaw] = (duplicates?.[keyRaw] || 0) + 1
  122. isArray = duplicates[keyRaw] > 1
  123. }
  124. const key = isArray && keyRaw.endsWith('[]')
  125. ? keyRaw.slice(0, -2) : keyRaw
  126. if (key === '__proto__') {
  127. continue
  128. }
  129. const valueRaw = match[3] ? unsafe(match[4]) : true
  130. const value = valueRaw === 'true' ||
  131. valueRaw === 'false' ||
  132. valueRaw === 'null' ? JSON.parse(valueRaw)
  133. : valueRaw
  134. // Convert keys with '[]' suffix to an array
  135. if (isArray) {
  136. if (!hasOwnProperty.call(p, key)) {
  137. p[key] = []
  138. } else if (!Array.isArray(p[key])) {
  139. p[key] = [p[key]]
  140. }
  141. }
  142. // safeguard against resetting a previously defined
  143. // array by accidentally forgetting the brackets
  144. if (Array.isArray(p[key])) {
  145. p[key].push(value)
  146. } else {
  147. p[key] = value
  148. }
  149. }
  150. // {a:{y:1},"a.b":{x:2}} --> {a:{y:1,b:{x:2}}}
  151. // use a filter to return the keys that have to be deleted.
  152. const remove = []
  153. for (const k of Object.keys(out)) {
  154. if (!hasOwnProperty.call(out, k) ||
  155. typeof out[k] !== 'object' ||
  156. Array.isArray(out[k])) {
  157. continue
  158. }
  159. // see if the parent section is also an object.
  160. // if so, add it to that, and mark this one for deletion
  161. const parts = splitSections(k, '.')
  162. p = out
  163. const l = parts.pop()
  164. const nl = l.replace(/\\\./g, '.')
  165. for (const part of parts) {
  166. if (part === '__proto__') {
  167. continue
  168. }
  169. if (!hasOwnProperty.call(p, part) || typeof p[part] !== 'object') {
  170. p[part] = Object.create(null)
  171. }
  172. p = p[part]
  173. }
  174. if (p === out && nl === l) {
  175. continue
  176. }
  177. p[nl] = out[k]
  178. remove.push(k)
  179. }
  180. for (const del of remove) {
  181. delete out[del]
  182. }
  183. return out
  184. }
  185. const isQuoted = val => {
  186. return (val.startsWith('"') && val.endsWith('"')) ||
  187. (val.startsWith("'") && val.endsWith("'"))
  188. }
  189. const safe = val => {
  190. if (
  191. typeof val !== 'string' ||
  192. val.match(/[=\r\n]/) ||
  193. val.match(/^\[/) ||
  194. (val.length > 1 && isQuoted(val)) ||
  195. val !== val.trim()
  196. ) {
  197. return JSON.stringify(val)
  198. }
  199. return val.split(';').join('\\;').split('#').join('\\#')
  200. }
  201. const unsafe = val => {
  202. val = (val || '').trim()
  203. if (isQuoted(val)) {
  204. // remove the single quotes before calling JSON.parse
  205. if (val.charAt(0) === "'") {
  206. val = val.slice(1, -1)
  207. }
  208. try {
  209. val = JSON.parse(val)
  210. } catch {
  211. // ignore errors
  212. }
  213. } else {
  214. // walk the val to find the first not-escaped ; character
  215. let esc = false
  216. let unesc = ''
  217. for (let i = 0, l = val.length; i < l; i++) {
  218. const c = val.charAt(i)
  219. if (esc) {
  220. if ('\\;#'.indexOf(c) !== -1) {
  221. unesc += c
  222. } else {
  223. unesc += '\\' + c
  224. }
  225. esc = false
  226. } else if (';#'.indexOf(c) !== -1) {
  227. break
  228. } else if (c === '\\') {
  229. esc = true
  230. } else {
  231. unesc += c
  232. }
  233. }
  234. if (esc) {
  235. unesc += '\\'
  236. }
  237. return unesc.trim()
  238. }
  239. return val
  240. }
  241. module.exports = {
  242. parse: decode,
  243. decode,
  244. stringify: encode,
  245. encode,
  246. safe,
  247. unsafe,
  248. }