ini.js 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  1. const { hasOwnProperty } = Object.prototype
  2. const eol = typeof process !== 'undefined' &&
  3. process.platform === 'win32' ? '\r\n' : '\n'
  4. const encode = (obj, opt) => {
  5. const children = []
  6. let out = ''
  7. if (typeof opt === 'string') {
  8. opt = {
  9. section: opt,
  10. whitespace: false,
  11. }
  12. } else {
  13. opt = opt || Object.create(null)
  14. opt.whitespace = opt.whitespace === true
  15. }
  16. const separator = opt.whitespace ? ' = ' : '='
  17. for (const k of Object.keys(obj)) {
  18. const val = obj[k]
  19. if (val && Array.isArray(val)) {
  20. for (const item of val)
  21. out += safe(k + '[]') + separator + safe(item) + '\n'
  22. } else if (val && typeof val === 'object')
  23. children.push(k)
  24. else
  25. out += safe(k) + separator + safe(val) + eol
  26. }
  27. if (opt.section && out.length)
  28. out = '[' + safe(opt.section) + ']' + eol + out
  29. for (const k of children) {
  30. const nk = dotSplit(k).join('\\.')
  31. const section = (opt.section ? opt.section + '.' : '') + nk
  32. const { whitespace } = opt
  33. const child = encode(obj[k], {
  34. section,
  35. whitespace,
  36. })
  37. if (out.length && child.length)
  38. out += eol
  39. out += child
  40. }
  41. return out
  42. }
  43. const dotSplit = str =>
  44. str.replace(/\1/g, '\u0002LITERAL\\1LITERAL\u0002')
  45. .replace(/\\\./g, '\u0001')
  46. .split(/\./)
  47. .map(part =>
  48. part.replace(/\1/g, '\\.')
  49. .replace(/\2LITERAL\\1LITERAL\2/g, '\u0001'))
  50. const decode = str => {
  51. const out = Object.create(null)
  52. let p = out
  53. let section = null
  54. // section |key = value
  55. const re = /^\[([^\]]*)\]$|^([^=]+)(=(.*))?$/i
  56. const lines = str.split(/[\r\n]+/g)
  57. for (const line of lines) {
  58. if (!line || line.match(/^\s*[;#]/))
  59. continue
  60. const match = line.match(re)
  61. if (!match)
  62. continue
  63. if (match[1] !== undefined) {
  64. section = unsafe(match[1])
  65. if (section === '__proto__') {
  66. // not allowed
  67. // keep parsing the section, but don't attach it.
  68. p = Object.create(null)
  69. continue
  70. }
  71. p = out[section] = out[section] || Object.create(null)
  72. continue
  73. }
  74. const keyRaw = unsafe(match[2])
  75. const isArray = keyRaw.length > 2 && keyRaw.slice(-2) === '[]'
  76. const key = isArray ? keyRaw.slice(0, -2) : keyRaw
  77. if (key === '__proto__')
  78. continue
  79. const valueRaw = match[3] ? unsafe(match[4]) : true
  80. const value = valueRaw === 'true' ||
  81. valueRaw === 'false' ||
  82. valueRaw === 'null' ? JSON.parse(valueRaw)
  83. : valueRaw
  84. // Convert keys with '[]' suffix to an array
  85. if (isArray) {
  86. if (!hasOwnProperty.call(p, key))
  87. p[key] = []
  88. else if (!Array.isArray(p[key]))
  89. p[key] = [p[key]]
  90. }
  91. // safeguard against resetting a previously defined
  92. // array by accidentally forgetting the brackets
  93. if (Array.isArray(p[key]))
  94. p[key].push(value)
  95. else
  96. p[key] = value
  97. }
  98. // {a:{y:1},"a.b":{x:2}} --> {a:{y:1,b:{x:2}}}
  99. // use a filter to return the keys that have to be deleted.
  100. const remove = []
  101. for (const k of Object.keys(out)) {
  102. if (!hasOwnProperty.call(out, k) ||
  103. typeof out[k] !== 'object' ||
  104. Array.isArray(out[k]))
  105. continue
  106. // see if the parent section is also an object.
  107. // if so, add it to that, and mark this one for deletion
  108. const parts = dotSplit(k)
  109. let p = out
  110. const l = parts.pop()
  111. const nl = l.replace(/\\\./g, '.')
  112. for (const part of parts) {
  113. if (part === '__proto__')
  114. continue
  115. if (!hasOwnProperty.call(p, part) || typeof p[part] !== 'object')
  116. p[part] = Object.create(null)
  117. p = p[part]
  118. }
  119. if (p === out && nl === l)
  120. continue
  121. p[nl] = out[k]
  122. remove.push(k)
  123. }
  124. for (const del of remove)
  125. delete out[del]
  126. return out
  127. }
  128. const isQuoted = val =>
  129. (val.charAt(0) === '"' && val.slice(-1) === '"') ||
  130. (val.charAt(0) === "'" && val.slice(-1) === "'")
  131. const safe = val =>
  132. (typeof val !== 'string' ||
  133. val.match(/[=\r\n]/) ||
  134. val.match(/^\[/) ||
  135. (val.length > 1 &&
  136. isQuoted(val)) ||
  137. val !== val.trim())
  138. ? JSON.stringify(val)
  139. : val.replace(/;/g, '\\;').replace(/#/g, '\\#')
  140. const unsafe = (val, doUnesc) => {
  141. val = (val || '').trim()
  142. if (isQuoted(val)) {
  143. // remove the single quotes before calling JSON.parse
  144. if (val.charAt(0) === "'")
  145. val = val.substr(1, val.length - 2)
  146. try {
  147. val = JSON.parse(val)
  148. } catch (_) {}
  149. } else {
  150. // walk the val to find the first not-escaped ; character
  151. let esc = false
  152. let unesc = ''
  153. for (let i = 0, l = val.length; i < l; i++) {
  154. const c = val.charAt(i)
  155. if (esc) {
  156. if ('\\;#'.indexOf(c) !== -1)
  157. unesc += c
  158. else
  159. unesc += '\\' + c
  160. esc = false
  161. } else if (';#'.indexOf(c) !== -1)
  162. break
  163. else if (c === '\\')
  164. esc = true
  165. else
  166. unesc += c
  167. }
  168. if (esc)
  169. unesc += '\\'
  170. return unesc.trim()
  171. }
  172. return val
  173. }
  174. module.exports = {
  175. parse: decode,
  176. decode,
  177. stringify: encode,
  178. encode,
  179. safe,
  180. unsafe,
  181. }