@ohos-ports/pm2 0.0.0-stage → 7.1.2-beta.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.
Files changed (267) hide show
  1. package/CHANGELOG.md +2607 -0
  2. package/CONTRIBUTING.md +124 -0
  3. package/GNU-AGPL-3.0.txt +665 -0
  4. package/LICENSE +1 -0
  5. package/README.md +255 -2
  6. package/SECURITY.md +41 -0
  7. package/bin/pm2 +3 -0
  8. package/bin/pm2-dev +3 -0
  9. package/bin/pm2-docker +3 -0
  10. package/bin/pm2-runtime +3 -0
  11. package/bin/pm2.ps1 +3 -0
  12. package/constants.js +113 -0
  13. package/index.js +12 -0
  14. package/lib/API/Configuration.js +212 -0
  15. package/lib/API/Containerizer.js +335 -0
  16. package/lib/API/Dashboard.js +726 -0
  17. package/lib/API/Deploy.js +117 -0
  18. package/lib/API/Extra.js +798 -0
  19. package/lib/API/ExtraMgmt/Docker.js +30 -0
  20. package/lib/API/Log.js +388 -0
  21. package/lib/API/LogManagement.js +351 -0
  22. package/lib/API/Modules/LOCAL.js +122 -0
  23. package/lib/API/Modules/Modularizer.js +148 -0
  24. package/lib/API/Modules/NPM.js +443 -0
  25. package/lib/API/Modules/TAR.js +368 -0
  26. package/lib/API/Modules/flagExt.js +46 -0
  27. package/lib/API/Modules/index.js +120 -0
  28. package/lib/API/Monit.js +247 -0
  29. package/lib/API/Serve.js +497 -0
  30. package/lib/API/Startup.js +630 -0
  31. package/lib/API/UX/helpers.js +213 -0
  32. package/lib/API/UX/index.js +9 -0
  33. package/lib/API/UX/pm2-describe.js +197 -0
  34. package/lib/API/UX/pm2-ls-minimal.js +31 -0
  35. package/lib/API/UX/pm2-ls.js +581 -0
  36. package/lib/API/Version.js +383 -0
  37. package/lib/API/interpreter.json +12 -0
  38. package/lib/API/pm2-plus/PM2IO.js +381 -0
  39. package/lib/API/pm2-plus/auth-strategies/CliAuth.js +306 -0
  40. package/lib/API/pm2-plus/auth-strategies/WebAuth.js +195 -0
  41. package/lib/API/pm2-plus/helpers.js +97 -0
  42. package/lib/API/pm2-plus/link.js +126 -0
  43. package/lib/API/pm2-plus/pres/motd +16 -0
  44. package/lib/API/pm2-plus/pres/motd.update +26 -0
  45. package/lib/API/pm2-plus/pres/welcome +28 -0
  46. package/lib/API/pm2-plus/process-selector.js +52 -0
  47. package/lib/API/schema.json +375 -0
  48. package/lib/API.js +1980 -0
  49. package/lib/Client.js +793 -0
  50. package/lib/Common.js +949 -0
  51. package/lib/Configuration.js +309 -0
  52. package/lib/Daemon.js +468 -0
  53. package/lib/Event.js +37 -0
  54. package/lib/God/ActionMethods.js +955 -0
  55. package/lib/God/ClusterMode.js +192 -0
  56. package/lib/God/ForkMode.js +205 -0
  57. package/lib/God/Methods.js +292 -0
  58. package/lib/God/Reload.js +300 -0
  59. package/lib/God/StdioLogger.js +239 -0
  60. package/lib/God.js +653 -0
  61. package/lib/HttpInterface.js +75 -0
  62. package/lib/OtelManager.js +74 -0
  63. package/lib/ProcessContainer.js +321 -0
  64. package/lib/ProcessContainerBun.js +355 -0
  65. package/lib/ProcessContainerFork.js +42 -0
  66. package/lib/ProcessContainerForkBun.js +31 -0
  67. package/lib/ProcessUtils.js +74 -0
  68. package/lib/TreeKill.js +111 -0
  69. package/lib/Utility.js +304 -0
  70. package/lib/VersionCheck.js +46 -0
  71. package/lib/Watcher.js +117 -0
  72. package/lib/Worker.js +200 -0
  73. package/lib/binaries/CLI.js +1092 -0
  74. package/lib/binaries/DevCLI.js +183 -0
  75. package/lib/binaries/Runtime.js +101 -0
  76. package/lib/binaries/Runtime4Docker.js +192 -0
  77. package/lib/completion.js +229 -0
  78. package/lib/completion.sh +40 -0
  79. package/lib/motd +36 -0
  80. package/lib/templates/Dockerfiles/Dockerfile-nodejs.tpl +8 -0
  81. package/lib/templates/ecosystem-es.tpl +24 -0
  82. package/lib/templates/ecosystem-simple-es.tpl +8 -0
  83. package/lib/templates/ecosystem-simple.tpl +6 -0
  84. package/lib/templates/ecosystem.tpl +22 -0
  85. package/lib/templates/init-scripts/launchd.tpl +35 -0
  86. package/lib/templates/init-scripts/openrc.tpl +52 -0
  87. package/lib/templates/init-scripts/pm2-init-amazon.sh +86 -0
  88. package/lib/templates/init-scripts/rcd-openbsd.tpl +41 -0
  89. package/lib/templates/init-scripts/rcd.tpl +44 -0
  90. package/lib/templates/init-scripts/smf.tpl +43 -0
  91. package/lib/templates/init-scripts/systemd-online.tpl +22 -0
  92. package/lib/templates/init-scripts/systemd.tpl +22 -0
  93. package/lib/templates/init-scripts/upstart.tpl +103 -0
  94. package/lib/templates/logrotate.d/pm2 +10 -0
  95. package/lib/templates/sample-apps/http-server/README.md +14 -0
  96. package/lib/templates/sample-apps/http-server/api.js +9 -0
  97. package/lib/templates/sample-apps/http-server/ecosystem.config.js +14 -0
  98. package/lib/templates/sample-apps/http-server/package.json +11 -0
  99. package/lib/templates/sample-apps/pm2-plus-metrics-actions/README.md +45 -0
  100. package/lib/templates/sample-apps/pm2-plus-metrics-actions/custom-metrics.js +66 -0
  101. package/lib/templates/sample-apps/pm2-plus-metrics-actions/ecosystem.config.js +12 -0
  102. package/lib/templates/sample-apps/pm2-plus-metrics-actions/package.json +11 -0
  103. package/lib/templates/sample-apps/python-app/README.md +4 -0
  104. package/lib/templates/sample-apps/python-app/echo.py +7 -0
  105. package/lib/templates/sample-apps/python-app/ecosystem.config.js +12 -0
  106. package/lib/templates/sample-apps/python-app/package.json +11 -0
  107. package/lib/tools/Config.js +251 -0
  108. package/lib/tools/SysMetrics.js +375 -0
  109. package/lib/tools/copydirSync.js +101 -0
  110. package/lib/tools/deleteFolderRecursive.js +19 -0
  111. package/lib/tools/find-package-json.js +74 -0
  112. package/lib/tools/fmt.js +72 -0
  113. package/lib/tools/interpreter.js +88 -0
  114. package/lib/tools/isbinaryfile.js +94 -0
  115. package/lib/tools/json5.js +752 -0
  116. package/lib/tools/multimeter/bar.js +111 -0
  117. package/lib/tools/multimeter/charm/encode.js +18 -0
  118. package/lib/tools/multimeter/charm/index.js +305 -0
  119. package/lib/tools/multimeter/index.js +76 -0
  120. package/lib/tools/open.js +56 -0
  121. package/lib/tools/passwd.js +58 -0
  122. package/lib/tools/pm2-config-keys.js +165 -0
  123. package/lib/tools/prompt.js +76 -0
  124. package/lib/tools/serviceStop.js +149 -0
  125. package/lib/tools/sexec.js +55 -0
  126. package/lib/tools/treeify.js +113 -0
  127. package/lib/tools/typestrip.js +55 -0
  128. package/lib/tools/which.js +120 -0
  129. package/lib/tools/xdg-open +861 -0
  130. package/modules/blessed/LICENSE +20 -0
  131. package/modules/blessed/README.md +34 -0
  132. package/modules/blessed/index.js +1 -0
  133. package/modules/blessed/lib/alias.js +526 -0
  134. package/modules/blessed/lib/blessed.js +32 -0
  135. package/modules/blessed/lib/colors.js +530 -0
  136. package/modules/blessed/lib/events.js +189 -0
  137. package/modules/blessed/lib/gpmclient.js +221 -0
  138. package/modules/blessed/lib/helpers.js +165 -0
  139. package/modules/blessed/lib/keys.js +339 -0
  140. package/modules/blessed/lib/program.js +4297 -0
  141. package/modules/blessed/lib/tput.js +3022 -0
  142. package/modules/blessed/lib/unicode.js +885 -0
  143. package/modules/blessed/lib/widget.js +32 -0
  144. package/modules/blessed/lib/widgets/box.js +34 -0
  145. package/modules/blessed/lib/widgets/element.js +2570 -0
  146. package/modules/blessed/lib/widgets/list.js +599 -0
  147. package/modules/blessed/lib/widgets/log.js +83 -0
  148. package/modules/blessed/lib/widgets/node.js +282 -0
  149. package/modules/blessed/lib/widgets/screen.js +2298 -0
  150. package/modules/blessed/lib/widgets/scrollablebox.js +389 -0
  151. package/modules/blessed/lib/widgets/scrollabletext.js +35 -0
  152. package/modules/blessed/lib/widgets/text.js +35 -0
  153. package/modules/blessed/usr/linux +0 -0
  154. package/modules/blessed/usr/windows-ansi +0 -0
  155. package/modules/blessed/usr/xterm +0 -0
  156. package/modules/blessed/usr/xterm-256color +0 -0
  157. package/modules/blessed/usr/xterm.termcap +243 -0
  158. package/modules/chokidar/LICENSE +21 -0
  159. package/modules/chokidar/VENDORED.md +76 -0
  160. package/modules/chokidar/index.js +979 -0
  161. package/modules/chokidar/lib/brace-expand.js +180 -0
  162. package/modules/chokidar/lib/constants.js +66 -0
  163. package/modules/chokidar/lib/fsevents-handler.js +526 -0
  164. package/modules/chokidar/lib/nodefs-handler.js +654 -0
  165. package/modules/fclone.js +49 -0
  166. package/modules/pm2-axon/index.js +2 -0
  167. package/modules/pm2-axon/lib/configurable/History.md +5 -0
  168. package/modules/pm2-axon/lib/configurable/Makefile +7 -0
  169. package/modules/pm2-axon/lib/configurable/Readme.md +57 -0
  170. package/modules/pm2-axon/lib/configurable/index.js +2 -0
  171. package/modules/pm2-axon/lib/configurable/lib/configurable.js +47 -0
  172. package/modules/pm2-axon/lib/configurable/package.json +68 -0
  173. package/modules/pm2-axon/lib/index.js +44 -0
  174. package/modules/pm2-axon/lib/plugins/queue.js +71 -0
  175. package/modules/pm2-axon/lib/plugins/round-robin.js +55 -0
  176. package/modules/pm2-axon/lib/sockets/pub-emitter.js +26 -0
  177. package/modules/pm2-axon/lib/sockets/pub.js +77 -0
  178. package/modules/pm2-axon/lib/sockets/pull.js +37 -0
  179. package/modules/pm2-axon/lib/sockets/push.js +32 -0
  180. package/modules/pm2-axon/lib/sockets/rep.js +73 -0
  181. package/modules/pm2-axon/lib/sockets/req.js +101 -0
  182. package/modules/pm2-axon/lib/sockets/sock.js +430 -0
  183. package/modules/pm2-axon/lib/sockets/sub-emitter.js +92 -0
  184. package/modules/pm2-axon/lib/sockets/sub.js +147 -0
  185. package/modules/pm2-axon/lib/utils.js +19 -0
  186. package/modules/pm2-axon-rpc/index.js +3 -0
  187. package/modules/pm2-axon-rpc/lib/client.js +63 -0
  188. package/modules/pm2-axon-rpc/lib/server.js +139 -0
  189. package/modules/pm2-io-agent/LICENSE +661 -0
  190. package/modules/pm2-io-agent/README.md +62 -0
  191. package/modules/pm2-io-agent/config.js +30 -0
  192. package/modules/pm2-io-agent/constants.js +118 -0
  193. package/modules/pm2-io-agent/index.js +2 -0
  194. package/modules/pm2-io-agent/src/InteractorClient.js +513 -0
  195. package/modules/pm2-io-agent/src/InteractorDaemon.js +455 -0
  196. package/modules/pm2-io-agent/src/PM2Client.js +112 -0
  197. package/modules/pm2-io-agent/src/PM2Interface.js +180 -0
  198. package/modules/pm2-io-agent/src/TransporterInterface.js +173 -0
  199. package/modules/pm2-io-agent/src/Utility.js +392 -0
  200. package/modules/pm2-io-agent/src/WatchDog.js +70 -0
  201. package/modules/pm2-io-agent/src/push/DataRetriever.js +77 -0
  202. package/modules/pm2-io-agent/src/push/PushInteractor.js +206 -0
  203. package/modules/pm2-io-agent/src/push/TransactionAggregator.js +670 -0
  204. package/modules/pm2-io-agent/src/reverse/ReverseInteractor.js +128 -0
  205. package/modules/pm2-io-agent/src/transporters/Transporter.js +129 -0
  206. package/modules/pm2-io-agent/src/transporters/WebsocketTransport.js +202 -0
  207. package/modules/pm2-io-agent/src/utils/BinaryHeap.js +135 -0
  208. package/modules/pm2-io-agent/src/utils/EDS.js +111 -0
  209. package/modules/pm2-io-agent/src/utils/probes/Histogram.js +204 -0
  210. package/modules/pm2-io-agent/src/utils/units.js +10 -0
  211. package/modules/pm2-io-bpm/configuration.js +141 -0
  212. package/modules/pm2-io-bpm/constants.js +10 -0
  213. package/modules/pm2-io-bpm/featureManager.js +110 -0
  214. package/modules/pm2-io-bpm/features/dependencies.js +48 -0
  215. package/modules/pm2-io-bpm/features/events.js +50 -0
  216. package/modules/pm2-io-bpm/features/metrics.js +102 -0
  217. package/modules/pm2-io-bpm/features/notify.js +238 -0
  218. package/modules/pm2-io-bpm/features/profiling.js +70 -0
  219. package/modules/pm2-io-bpm/features/tracing.js +174 -0
  220. package/modules/pm2-io-bpm/index.js +11 -0
  221. package/modules/pm2-io-bpm/metrics/eventLoopMetrics.js +136 -0
  222. package/modules/pm2-io-bpm/metrics/httpMetrics.js +175 -0
  223. package/modules/pm2-io-bpm/metrics/network.js +132 -0
  224. package/modules/pm2-io-bpm/metrics/runtime.js +161 -0
  225. package/modules/pm2-io-bpm/metrics/v8.js +104 -0
  226. package/modules/pm2-io-bpm/otel/constants.js +7 -0
  227. package/modules/pm2-io-bpm/otel/custom-zipkin-exporter/platform/index.js +17 -0
  228. package/modules/pm2-io-bpm/otel/custom-zipkin-exporter/platform/node/index.js +17 -0
  229. package/modules/pm2-io-bpm/otel/custom-zipkin-exporter/platform/node/util.js +51 -0
  230. package/modules/pm2-io-bpm/otel/custom-zipkin-exporter/transform.js +137 -0
  231. package/modules/pm2-io-bpm/otel/custom-zipkin-exporter/types.js +24 -0
  232. package/modules/pm2-io-bpm/otel/custom-zipkin-exporter/utils.js +23 -0
  233. package/modules/pm2-io-bpm/otel/custom-zipkin-exporter/zipkin.js +149 -0
  234. package/modules/pm2-io-bpm/pmx.js +380 -0
  235. package/modules/pm2-io-bpm/profilers/addonProfiler.js +193 -0
  236. package/modules/pm2-io-bpm/profilers/inspectorProfiler.js +302 -0
  237. package/modules/pm2-io-bpm/serviceManager.js +21 -0
  238. package/modules/pm2-io-bpm/services/actions.js +159 -0
  239. package/modules/pm2-io-bpm/services/inspector.js +43 -0
  240. package/modules/pm2-io-bpm/services/metrics.js +186 -0
  241. package/modules/pm2-io-bpm/services/runtimeStats.js +54 -0
  242. package/modules/pm2-io-bpm/services/transport.js +11 -0
  243. package/modules/pm2-io-bpm/transports/IPCTransport.js +115 -0
  244. package/modules/pm2-io-bpm/utils/BinaryHeap.js +134 -0
  245. package/modules/pm2-io-bpm/utils/EDS.js +113 -0
  246. package/modules/pm2-io-bpm/utils/EWMA.js +32 -0
  247. package/modules/pm2-io-bpm/utils/autocast.js +61 -0
  248. package/modules/pm2-io-bpm/utils/metrics/counter.js +33 -0
  249. package/modules/pm2-io-bpm/utils/metrics/gauge.js +23 -0
  250. package/modules/pm2-io-bpm/utils/metrics/histogram.js +192 -0
  251. package/modules/pm2-io-bpm/utils/metrics/meter.js +46 -0
  252. package/modules/pm2-io-bpm/utils/miscellaneous.js +19 -0
  253. package/modules/pm2-io-bpm/utils/module.js +67 -0
  254. package/modules/pm2-io-bpm/utils/shimmer.js +19 -0
  255. package/modules/pm2-io-bpm/utils/stackParser.js +160 -0
  256. package/modules/pm2-io-bpm/utils/transactionAggregator.js +429 -0
  257. package/modules/pm2-io-bpm/utils/units.js +16 -0
  258. package/modules/vizion/LICENSE +13 -0
  259. package/modules/vizion/README.md +133 -0
  260. package/modules/vizion/index.js +1 -0
  261. package/modules/vizion/lib/git/git.js +247 -0
  262. package/modules/vizion/lib/vizion.js +52 -0
  263. package/package.json +170 -4
  264. package/paths.js +121 -0
  265. package/pm2 +11 -0
  266. package/types/index.d.ts +732 -0
  267. package/types/tsconfig.json +14 -0
@@ -0,0 +1,3022 @@
1
+ /**
2
+ * tput.js - parse and compile terminfo caps to javascript.
3
+ * Copyright (c) 2013-2015, Christopher Jeffrey and contributors (MIT License).
4
+ * https://github.com/chjj/blessed
5
+ */
6
+
7
+ // Resources:
8
+ // $ man term
9
+ // $ man terminfo
10
+ // http://invisible-island.net/ncurses/man/term.5.html
11
+ // https://en.wikipedia.org/wiki/Terminfo
12
+
13
+ // Todo:
14
+ // - xterm's XT (set-title capability?) value should
15
+ // be true (at least tmux thinks it should).
16
+ // It's not parsed as true. Investigate.
17
+ // - Possibly switch to other method of finding the
18
+ // extended data string table: i += h.symOffsetCount * 2;
19
+
20
+ /**
21
+ * Modules
22
+ */
23
+
24
+ var assert = require('assert')
25
+ , path = require('path')
26
+ , fs = require('fs')
27
+ , cp = require('child_process');
28
+
29
+ /**
30
+ * Tput
31
+ */
32
+
33
+ function Tput(options) {
34
+ if (!(this instanceof Tput)) {
35
+ return new Tput(options);
36
+ }
37
+
38
+ options = options || {};
39
+ if (typeof options === 'string') {
40
+ options = { terminal: options };
41
+ }
42
+
43
+ this.options = options;
44
+ this.terminal = options.terminal
45
+ || options.term
46
+ || process.env.TERM
47
+ || (process.platform === 'win32' ? 'windows-ansi' : 'xterm');
48
+
49
+ this.terminal = this.terminal.toLowerCase();
50
+
51
+ this.debug = options.debug;
52
+ this.padding = options.padding;
53
+ this.extended = options.extended;
54
+ this.printf = options.printf;
55
+ this.termcap = options.termcap;
56
+ this.error = null;
57
+
58
+ this.terminfoPrefix = options.terminfoPrefix;
59
+ this.terminfoFile = options.terminfoFile;
60
+ this.termcapFile = options.termcapFile;
61
+
62
+ if (options.terminal || options.term) {
63
+ this.setup();
64
+ }
65
+ }
66
+
67
+ Tput.prototype.setup = function() {
68
+ this.error = null;
69
+ try {
70
+ if (this.termcap) {
71
+ try {
72
+ this.injectTermcap();
73
+ } catch (e) {
74
+ if (this.debug) throw e;
75
+ this.error = new Error('Termcap parse error.');
76
+ this._useInternalCap(this.terminal);
77
+ }
78
+ } else {
79
+ try {
80
+ this.injectTerminfo();
81
+ } catch (e) {
82
+ if (this.debug) throw e;
83
+ this.error = new Error('Terminfo parse error.');
84
+ this._useInternalInfo(this.terminal);
85
+ }
86
+ }
87
+ } catch (e) {
88
+ // If there was an error, fallback
89
+ // to an internally stored terminfo/cap.
90
+ if (this.debug) throw e;
91
+ this.error = new Error('Terminfo not found.');
92
+ this._useXtermInfo();
93
+ }
94
+ };
95
+
96
+ Tput.prototype.term = function(is) {
97
+ return this.terminal.indexOf(is) === 0;
98
+ };
99
+
100
+ Tput.prototype._debug = function() {
101
+ if (!this.debug) return;
102
+ return console.log.apply(console, arguments);
103
+ };
104
+
105
+ /**
106
+ * Fallback
107
+ */
108
+
109
+ Tput.prototype._useVt102Cap = function() {
110
+ return this.injectTermcap('vt102');
111
+ };
112
+
113
+ Tput.prototype._useXtermCap = function() {
114
+ return this.injectTermcap(__dirname + '/../usr/xterm.termcap');
115
+ };
116
+
117
+ Tput.prototype._useXtermInfo = function() {
118
+ return this.injectTerminfo(__dirname + '/../usr/xterm');
119
+ };
120
+
121
+ Tput.prototype._useInternalInfo = function(name) {
122
+ name = path.basename(name);
123
+ return this.injectTerminfo(__dirname + '/../usr/' + name);
124
+ };
125
+
126
+ Tput.prototype._useInternalCap = function(name) {
127
+ name = path.basename(name);
128
+ return this.injectTermcap(__dirname + '/../usr/' + name + '.termcap');
129
+ };
130
+
131
+ /**
132
+ * Terminfo
133
+ */
134
+
135
+ Tput.ipaths = [
136
+ process.env.TERMINFO || '',
137
+ (process.env.TERMINFO_DIRS || '').split(':'),
138
+ (process.env.HOME || '') + '/.terminfo',
139
+ '/usr/share/terminfo',
140
+ '/usr/share/lib/terminfo',
141
+ '/usr/lib/terminfo',
142
+ '/usr/local/share/terminfo',
143
+ '/usr/local/share/lib/terminfo',
144
+ '/usr/local/lib/terminfo',
145
+ '/usr/local/ncurses/lib/terminfo',
146
+ '/lib/terminfo'
147
+ ];
148
+
149
+ Tput.prototype.readTerminfo = function(term) {
150
+ var data
151
+ , file
152
+ , info;
153
+
154
+ term = term || this.terminal;
155
+
156
+ file = path.normalize(this._prefix(term));
157
+ data = fs.readFileSync(file);
158
+ info = this.parseTerminfo(data, file);
159
+
160
+ if (this.debug) {
161
+ this._terminfo = info;
162
+ }
163
+
164
+ return info;
165
+ };
166
+
167
+ Tput._prefix =
168
+ Tput.prototype._prefix = function(term) {
169
+ // If we have a terminfoFile, or our
170
+ // term looks like a filename, use it.
171
+ if (term) {
172
+ if (~term.indexOf(path.sep)) {
173
+ return term;
174
+ }
175
+ if (this.terminfoFile) {
176
+ return this.terminfoFile;
177
+ }
178
+ }
179
+
180
+ var paths = Tput.ipaths.slice()
181
+ , file;
182
+
183
+ if (this.terminfoPrefix) {
184
+ paths.unshift(this.terminfoPrefix);
185
+ }
186
+
187
+ // Try exact matches.
188
+ file = this._tprefix(paths, term);
189
+ if (file) return file;
190
+
191
+ // Try similar matches.
192
+ file = this._tprefix(paths, term, true);
193
+ if (file) return file;
194
+
195
+ // Not found.
196
+ throw new Error('Terminfo directory not found.');
197
+ };
198
+
199
+ Tput._tprefix =
200
+ Tput.prototype._tprefix = function(prefix, term, soft) {
201
+ if (!prefix) return;
202
+
203
+ var file
204
+ , dir
205
+ , i
206
+ , sdiff
207
+ , sfile
208
+ , list;
209
+
210
+ if (Array.isArray(prefix)) {
211
+ for (i = 0; i < prefix.length; i++) {
212
+ file = this._tprefix(prefix[i], term, soft);
213
+ if (file) return file;
214
+ }
215
+ return;
216
+ }
217
+
218
+ var find = function(word) {
219
+ var file, ch;
220
+
221
+ file = path.resolve(prefix, word[0]);
222
+ try {
223
+ fs.statSync(file);
224
+ return file;
225
+ } catch (e) {
226
+ ;
227
+ }
228
+
229
+ ch = word[0].charCodeAt(0).toString(16);
230
+ if (ch.length < 2) ch = '0' + ch;
231
+
232
+ file = path.resolve(prefix, ch);
233
+ try {
234
+ fs.statSync(file);
235
+ return file;
236
+ } catch (e) {
237
+ ;
238
+ }
239
+ };
240
+
241
+ if (!term) {
242
+ // Make sure the directory's sub-directories
243
+ // are all one-letter, or hex digits.
244
+ // return find('x') ? prefix : null;
245
+ try {
246
+ dir = fs.readdirSync(prefix).filter(function(file) {
247
+ return file.length !== 1 && !/^[0-9a-fA-F]{2}$/.test(file);
248
+ });
249
+ if (!dir.length) {
250
+ return prefix;
251
+ }
252
+ } catch (e) {
253
+ ;
254
+ }
255
+ return;
256
+ }
257
+
258
+ term = path.basename(term);
259
+ dir = find(term);
260
+
261
+ if (!dir) return;
262
+
263
+ if (soft) {
264
+ try {
265
+ list = fs.readdirSync(dir);
266
+ } catch (e) {
267
+ return;
268
+ }
269
+
270
+ list.forEach(function(file) {
271
+ if (file.indexOf(term) === 0) {
272
+ var diff = file.length - term.length;
273
+ if (!sfile || diff < sdiff) {
274
+ sdiff = diff;
275
+ sfile = file;
276
+ }
277
+ }
278
+ });
279
+
280
+ return sfile && (soft || sdiff === 0)
281
+ ? path.resolve(dir, sfile)
282
+ : null;
283
+ }
284
+
285
+ file = path.resolve(dir, term);
286
+ try {
287
+ fs.statSync(file);
288
+ return file;
289
+ } catch (e) {
290
+ ;
291
+ }
292
+ };
293
+
294
+ /**
295
+ * Terminfo Parser
296
+ * All shorts are little-endian
297
+ */
298
+
299
+ Tput.prototype.parseTerminfo = function(data, file) {
300
+ var info = {}
301
+ , extended
302
+ , l = data.length
303
+ , i = 0
304
+ , v
305
+ , o;
306
+
307
+ var h = info.header = {
308
+ dataSize: data.length,
309
+ headerSize: 12,
310
+ magicNumber: (data[1] << 8) | data[0],
311
+ namesSize: (data[3] << 8) | data[2],
312
+ boolCount: (data[5] << 8) | data[4],
313
+ numCount: (data[7] << 8) | data[6],
314
+ strCount: (data[9] << 8) | data[8],
315
+ strTableSize: (data[11] << 8) | data[10]
316
+ };
317
+
318
+ h.total = h.headerSize
319
+ + h.namesSize
320
+ + h.boolCount
321
+ + h.numCount * 2
322
+ + h.strCount * 2
323
+ + h.strTableSize;
324
+
325
+ i += h.headerSize;
326
+
327
+ // Names Section
328
+ var names = data.toString('ascii', i, i + h.namesSize - 1)
329
+ , parts = names.split('|')
330
+ , name = parts[0]
331
+ , desc = parts.pop();
332
+
333
+ info.name = name;
334
+ info.names = parts;
335
+ info.desc = desc;
336
+
337
+ info.dir = path.resolve(file, '..', '..');
338
+ info.file = file;
339
+
340
+ i += h.namesSize - 1;
341
+
342
+ // Names is nul-terminated.
343
+ assert.equal(data[i], 0);
344
+ i++;
345
+
346
+ // Booleans Section
347
+ // One byte for each flag
348
+ // Same order as <term.h>
349
+ info.bools = {};
350
+ l = i + h.boolCount;
351
+ o = 0;
352
+ for (; i < l; i++) {
353
+ v = Tput.bools[o++];
354
+ info.bools[v] = data[i] === 1;
355
+ }
356
+
357
+ // Null byte in between to make sure numbers begin on an even byte.
358
+ if (i % 2) {
359
+ assert.equal(data[i], 0);
360
+ i++;
361
+ }
362
+
363
+ // Numbers Section
364
+ info.numbers = {};
365
+ l = i + h.numCount * 2;
366
+ o = 0;
367
+ for (; i < l; i += 2) {
368
+ v = Tput.numbers[o++];
369
+ if (data[i + 1] === 0xff && data[i] === 0xff) {
370
+ info.numbers[v] = -1;
371
+ } else {
372
+ info.numbers[v] = (data[i + 1] << 8) | data[i];
373
+ }
374
+ }
375
+
376
+ // Strings Section
377
+ info.strings = {};
378
+ l = i + h.strCount * 2;
379
+ o = 0;
380
+ for (; i < l; i += 2) {
381
+ v = Tput.strings[o++];
382
+ if (data[i + 1] === 0xff && data[i] === 0xff) {
383
+ info.strings[v] = -1;
384
+ } else {
385
+ info.strings[v] = (data[i + 1] << 8) | data[i];
386
+ }
387
+ }
388
+
389
+ // String Table
390
+ Object.keys(info.strings).forEach(function(key) {
391
+ if (info.strings[key] === -1) {
392
+ delete info.strings[key];
393
+ return;
394
+ }
395
+
396
+ // Workaround: fix an odd bug in the screen-256color terminfo where it tries
397
+ // to set -1, but it appears to have {0xfe, 0xff} instead of {0xff, 0xff}.
398
+ // TODO: Possibly handle errors gracefully below, as well as in the
399
+ // extended info. Also possibly do: `if (info.strings[key] >= data.length)`.
400
+ if (info.strings[key] === 65534) {
401
+ delete info.strings[key];
402
+ return;
403
+ }
404
+
405
+ var s = i + info.strings[key]
406
+ , j = s;
407
+
408
+ while (data[j]) j++;
409
+
410
+ assert(j < data.length);
411
+
412
+ info.strings[key] = data.toString('ascii', s, j);
413
+ });
414
+
415
+ // Extended Header
416
+ if (this.extended !== false) {
417
+ i--;
418
+ i += h.strTableSize;
419
+ if (i % 2) {
420
+ assert.equal(data[i], 0);
421
+ i++;
422
+ }
423
+ l = data.length;
424
+ if (i < l - 1) {
425
+ try {
426
+ extended = this.parseExtended(data.slice(i));
427
+ } catch (e) {
428
+ if (this.debug) {
429
+ throw e;
430
+ }
431
+ return info;
432
+ }
433
+ info.header.extended = extended.header;
434
+ ['bools', 'numbers', 'strings'].forEach(function(key) {
435
+ merge(info[key], extended[key]);
436
+ });
437
+ }
438
+ }
439
+
440
+ return info;
441
+ };
442
+
443
+ /**
444
+ * Extended Parsing
445
+ */
446
+
447
+ // Some data to help understand:
448
+
449
+ // For xterm, non-extended header:
450
+ // { dataSize: 3270,
451
+ // headerSize: 12,
452
+ // magicNumber: 282,
453
+ // namesSize: 48,
454
+ // boolCount: 38,
455
+ // numCount: 15,
456
+ // strCount: 413,
457
+ // strTableSize: 1388,
458
+ // total: 2342 }
459
+
460
+ // For xterm, header:
461
+ // Offset: 2342
462
+ // { header:
463
+ // { dataSize: 928,
464
+ // headerSize: 10,
465
+ // boolCount: 2,
466
+ // numCount: 1,
467
+ // strCount: 57,
468
+ // strTableSize: 117,
469
+ // lastStrTableOffset: 680,
470
+ // total: 245 },
471
+
472
+ // For xterm, layout:
473
+ // { header: '0 - 10', // length: 10
474
+ // bools: '10 - 12', // length: 2
475
+ // numbers: '12 - 14', // length: 2
476
+ // strings: '14 - 128', // length: 114 (57 short)
477
+ // symoffsets: '128 - 248', // length: 120 (60 short)
478
+ // stringtable: '248 - 612', // length: 364
479
+ // sym: '612 - 928' } // length: 316
480
+ //
481
+ // How lastStrTableOffset works:
482
+ // data.length - h.lastStrTableOffset === 248
483
+ // (sym-offset end, string-table start)
484
+ // 364 + 316 === 680 (lastStrTableOffset)
485
+ // How strTableSize works:
486
+ // h.strCount + [symOffsetCount] === h.strTableSize
487
+ // 57 + 60 === 117 (strTableSize)
488
+ // symOffsetCount doesn't actually exist in the header. it's just implied.
489
+ // Getting the number of sym offsets:
490
+ // h.symOffsetCount = h.strTableSize - h.strCount;
491
+ // h.symOffsetSize = (h.strTableSize - h.strCount) * 2;
492
+
493
+ Tput.prototype.parseExtended = function(data) {
494
+ var info = {}
495
+ , l = data.length
496
+ , i = 0;
497
+
498
+ var h = info.header = {
499
+ dataSize: data.length,
500
+ headerSize: 10,
501
+ boolCount: (data[i + 1] << 8) | data[i + 0],
502
+ numCount: (data[i + 3] << 8) | data[i + 2],
503
+ strCount: (data[i + 5] << 8) | data[i + 4],
504
+ strTableSize: (data[i + 7] << 8) | data[i + 6],
505
+ lastStrTableOffset: (data[i + 9] << 8) | data[i + 8]
506
+ };
507
+
508
+ // h.symOffsetCount = h.strTableSize - h.strCount;
509
+
510
+ h.total = h.headerSize
511
+ + h.boolCount
512
+ + h.numCount * 2
513
+ + h.strCount * 2
514
+ + h.strTableSize;
515
+
516
+ i += h.headerSize;
517
+
518
+ // Booleans Section
519
+ // One byte for each flag
520
+ var _bools = [];
521
+ l = i + h.boolCount;
522
+ for (; i < l; i++) {
523
+ _bools.push(data[i] === 1);
524
+ }
525
+
526
+ // Null byte in between to make sure numbers begin on an even byte.
527
+ if (i % 2) {
528
+ assert.equal(data[i], 0);
529
+ i++;
530
+ }
531
+
532
+ // Numbers Section
533
+ var _numbers = [];
534
+ l = i + h.numCount * 2;
535
+ for (; i < l; i += 2) {
536
+ if (data[i + 1] === 0xff && data[i] === 0xff) {
537
+ _numbers.push(-1);
538
+ } else {
539
+ _numbers.push((data[i + 1] << 8) | data[i]);
540
+ }
541
+ }
542
+
543
+ // Strings Section
544
+ var _strings = [];
545
+ l = i + h.strCount * 2;
546
+ for (; i < l; i += 2) {
547
+ if (data[i + 1] === 0xff && data[i] === 0xff) {
548
+ _strings.push(-1);
549
+ } else {
550
+ _strings.push((data[i + 1] << 8) | data[i]);
551
+ }
552
+ }
553
+
554
+ // Pass over the sym offsets and get to the string table.
555
+ i = data.length - h.lastStrTableOffset;
556
+ // Might be better to do this instead if the file has trailing bytes:
557
+ // i += h.symOffsetCount * 2;
558
+
559
+ // String Table
560
+ var high = 0;
561
+ _strings.forEach(function(offset, k) {
562
+ if (offset === -1) {
563
+ _strings[k] = '';
564
+ return;
565
+ }
566
+
567
+ var s = i + offset
568
+ , j = s;
569
+
570
+ while (data[j]) j++;
571
+
572
+ assert(j < data.length);
573
+
574
+ // Find out where the string table ends by
575
+ // getting the highest string length.
576
+ if (high < j - i) {
577
+ high = j - i;
578
+ }
579
+
580
+ _strings[k] = data.toString('ascii', s, j);
581
+ });
582
+
583
+ // Symbol Table
584
+ // Add one to the highest string length because we didn't count \0.
585
+ i += high + 1;
586
+ l = data.length;
587
+
588
+ var sym = []
589
+ , j;
590
+
591
+ for (; i < l; i++) {
592
+ j = i;
593
+ while (data[j]) j++;
594
+ sym.push(data.toString('ascii', i, j));
595
+ i = j;
596
+ }
597
+
598
+ // Identify by name
599
+ j = 0;
600
+
601
+ info.bools = {};
602
+ _bools.forEach(function(bool) {
603
+ info.bools[sym[j++]] = bool;
604
+ });
605
+
606
+ info.numbers = {};
607
+ _numbers.forEach(function(number) {
608
+ info.numbers[sym[j++]] = number;
609
+ });
610
+
611
+ info.strings = {};
612
+ _strings.forEach(function(string) {
613
+ info.strings[sym[j++]] = string;
614
+ });
615
+
616
+ // Should be the very last bit of data.
617
+ assert.equal(i, data.length);
618
+
619
+ return info;
620
+ };
621
+
622
+ Tput.prototype.compileTerminfo = function(term) {
623
+ return this.compile(this.readTerminfo(term));
624
+ };
625
+
626
+ Tput.prototype.injectTerminfo = function(term) {
627
+ return this.inject(this.compileTerminfo(term));
628
+ };
629
+
630
+ /**
631
+ * Compiler - terminfo cap->javascript
632
+ */
633
+
634
+ Tput.prototype.compile = function(info) {
635
+ var self = this;
636
+
637
+ if (!info) {
638
+ throw new Error('Terminal not found.');
639
+ }
640
+
641
+ this.detectFeatures(info);
642
+
643
+ this._debug(info);
644
+
645
+ info.all = {};
646
+ info.methods = {};
647
+
648
+ ['bools', 'numbers', 'strings'].forEach(function(type) {
649
+ Object.keys(info[type]).forEach(function(key) {
650
+ info.all[key] = info[type][key];
651
+ info.methods[key] = self._compile(info, key, info.all[key]);
652
+ });
653
+ });
654
+
655
+ Tput.bools.forEach(function(key) {
656
+ if (info.methods[key] == null) info.methods[key] = false;
657
+ });
658
+
659
+ Tput.numbers.forEach(function(key) {
660
+ if (info.methods[key] == null) info.methods[key] = -1;
661
+ });
662
+
663
+ Tput.strings.forEach(function(key) {
664
+ if (!info.methods[key]) info.methods[key] = noop;
665
+ });
666
+
667
+ Object.keys(info.methods).forEach(function(key) {
668
+ if (!Tput.alias[key]) return;
669
+ Tput.alias[key].forEach(function(alias) {
670
+ info.methods[alias] = info.methods[key];
671
+ });
672
+ // Could just use:
673
+ // Object.keys(Tput.aliasMap).forEach(function(key) {
674
+ // info.methods[key] = info.methods[Tput.aliasMap[key]];
675
+ // });
676
+ });
677
+
678
+ return info;
679
+ };
680
+
681
+ Tput.prototype.inject = function(info) {
682
+ var self = this
683
+ , methods = info.methods || info;
684
+
685
+ Object.keys(methods).forEach(function(key) {
686
+ if (typeof methods[key] !== 'function') {
687
+ self[key] = methods[key];
688
+ return;
689
+ }
690
+ self[key] = function() {
691
+ var args = Array.prototype.slice.call(arguments);
692
+ return methods[key].call(self, args);
693
+ };
694
+ });
695
+
696
+ this.info = info;
697
+ this.all = info.all;
698
+ this.methods = info.methods;
699
+ this.bools = info.bools;
700
+ this.numbers = info.numbers;
701
+ this.strings = info.strings;
702
+
703
+ if (!~info.names.indexOf(this.terminal)) {
704
+ this.terminal = info.name;
705
+ }
706
+
707
+ this.features = info.features;
708
+ Object.keys(info.features).forEach(function(key) {
709
+ if (key === 'padding') {
710
+ if (!info.features.padding && self.options.padding !== true) {
711
+ self.padding = false;
712
+ }
713
+ return;
714
+ }
715
+ self[key] = info.features[key];
716
+ });
717
+ };
718
+
719
+ // See:
720
+ // ~/ncurses/ncurses/tinfo/lib_tparm.c
721
+ // ~/ncurses/ncurses/tinfo/comp_scan.c
722
+ Tput.prototype._compile = function(info, key, str) {
723
+ var v;
724
+
725
+ this._debug('Compiling %s: %s', key, JSON.stringify(str));
726
+
727
+ switch (typeof str) {
728
+ case 'boolean':
729
+ return str;
730
+ case 'number':
731
+ return str;
732
+ case 'string':
733
+ break;
734
+ default:
735
+ return noop;
736
+ }
737
+
738
+ if (!str) {
739
+ return noop;
740
+ }
741
+
742
+ // See:
743
+ // ~/ncurses/progs/tput.c - tput() - L149
744
+ // ~/ncurses/progs/tset.c - set_init() - L992
745
+ if (key === 'init_file' || key === 'reset_file') {
746
+ try {
747
+ str = fs.readFileSync(str, 'utf8');
748
+ if (this.debug) {
749
+ v = ('return ' + JSON.stringify(str) + ';')
750
+ .replace(/\x1b/g, '\\x1b')
751
+ .replace(/\r/g, '\\r')
752
+ .replace(/\n/g, '\\n');
753
+ process.stdout.write(v + '\n');
754
+ }
755
+ return function() { return str; };
756
+ } catch (e) {
757
+ return noop;
758
+ }
759
+ }
760
+
761
+ var tkey = info.name + '.' + key
762
+ , header = 'var v, dyn = {}, stat = {}, stack = [], out = [];'
763
+ , footer = ';return out.join("");'
764
+ , code = header
765
+ , val = str
766
+ , buff = ''
767
+ , cap
768
+ , ch
769
+ , fi
770
+ , then
771
+ , els
772
+ , end;
773
+
774
+ function read(regex, no) {
775
+ cap = regex.exec(val);
776
+ if (!cap) return;
777
+ val = val.substring(cap[0].length);
778
+ ch = cap[1];
779
+ if (!no) clear();
780
+ return cap;
781
+ }
782
+
783
+ function stmt(c) {
784
+ if (code[code.length - 1] === ',') {
785
+ code = code.slice(0, -1);
786
+ }
787
+ code += c;
788
+ }
789
+
790
+ function expr(c) {
791
+ code += c + ',';
792
+ }
793
+
794
+ function echo(c) {
795
+ if (c === '""') return;
796
+ expr('out.push(' + c + ')');
797
+ }
798
+
799
+ function print(c) {
800
+ buff += c;
801
+ }
802
+
803
+ function clear() {
804
+ if (buff) {
805
+ echo(JSON.stringify(buff).replace(/\\u00([0-9a-fA-F]{2})/g, '\\x$1'));
806
+ buff = '';
807
+ }
808
+ }
809
+
810
+ while (val) {
811
+ // Ignore newlines
812
+ if (read(/^\n /, true)) {
813
+ continue;
814
+ }
815
+
816
+ // '^A' -> ^A
817
+ if (read(/^\^(.)/i, true)) {
818
+ if (!(ch >= ' ' && ch <= '~')) {
819
+ this._debug('%s: bad caret char.', tkey);
820
+ // NOTE: ncurses appears to simply
821
+ // continue in this situation, but
822
+ // I could be wrong.
823
+ print(cap[0]);
824
+ continue;
825
+ }
826
+ if (ch === '?') {
827
+ ch = '\x7f';
828
+ } else {
829
+ ch = ch.charCodeAt(0) & 31;
830
+ if (ch === 0) ch = 128;
831
+ ch = String.fromCharCode(ch);
832
+ }
833
+ print(ch);
834
+ continue;
835
+ }
836
+
837
+ // 3 octal digits -> character
838
+ if (read(/^\\([0-7]{3})/, true)) {
839
+ print(String.fromCharCode(parseInt(ch, 8)));
840
+ continue;
841
+ }
842
+
843
+ // '\e' -> ^[
844
+ // '\n' -> \n
845
+ // '\r' -> \r
846
+ // '\0' -> \200 (special case)
847
+ if (read(/^\\([eEnlrtbfs\^\\,:0]|.)/, true)) {
848
+ switch (ch) {
849
+ case 'e':
850
+ case 'E':
851
+ ch = '\x1b';
852
+ break;
853
+ case 'n':
854
+ ch = '\n';
855
+ break;
856
+ case 'l':
857
+ ch = '\x85';
858
+ break;
859
+ case 'r':
860
+ ch = '\r';
861
+ break;
862
+ case 't':
863
+ ch = '\t';
864
+ break;
865
+ case 'b':
866
+ ch = '\x08';
867
+ break;
868
+ case 'f':
869
+ ch = '\x0c';
870
+ break;
871
+ case 's':
872
+ ch = ' ';
873
+ break;
874
+ case '^':
875
+ ch = '^';
876
+ break;
877
+ case '\\':
878
+ ch = '\\';
879
+ break;
880
+ case ',':
881
+ ch = ',';
882
+ break;
883
+ case ':':
884
+ ch = ':';
885
+ break;
886
+ case '0':
887
+ ch = '\x80';
888
+ break;
889
+ case 'a':
890
+ ch = '\x07';
891
+ break;
892
+ default:
893
+ this._debug('%s: bad backslash char.', tkey);
894
+ ch = cap[0];
895
+ break;
896
+ }
897
+ print(ch);
898
+ continue;
899
+ }
900
+
901
+ // $<5> -> padding
902
+ // e.g. flash_screen: '\u001b[?5h$<100/>\u001b[?5l',
903
+ if (read(/^\$<(\d+)([*\/]{0,2})>/, true)) {
904
+ if (this.padding) print(cap[0]);
905
+ continue;
906
+ }
907
+
908
+ // %% outputs `%'
909
+ if (read(/^%%/, true)) {
910
+ print('%');
911
+ continue;
912
+ }
913
+
914
+ // %[[:]flags][width[.precision]][doxXs]
915
+ // as in printf, flags are [-+#] and space. Use a `:' to allow the
916
+ // next character to be a `-' flag, avoiding interpreting "%-" as an
917
+ // operator.
918
+ // %c print pop() like %c in printf
919
+ // Example from screen terminfo:
920
+ // S0: "\u001b(%p1%c"
921
+ // %d print pop()
922
+ // "Print (e.g., "%d") is a special case."
923
+ // %s print pop() like %s in printf
924
+ if (read(/^%((?::-|[+# ]){1,4})?(\d+(?:\.\d+)?)?([doxXsc])/)) {
925
+ if (this.printf || cap[1] || cap[2] || ~'oxX'.indexOf(cap[3])) {
926
+ echo('sprintf("'+ cap[0].replace(':-', '-') + '", stack.pop())');
927
+ } else if (cap[3] === 'c') {
928
+ echo('(v = stack.pop(), isFinite(v) '
929
+ + '? String.fromCharCode(v || 0200) : "")');
930
+ } else {
931
+ echo('stack.pop()');
932
+ }
933
+ continue;
934
+ }
935
+
936
+ // %p[1-9]
937
+ // push i'th parameter
938
+ if (read(/^%p([1-9])/)) {
939
+ expr('(stack.push(v = params[' + (ch - 1) + ']), v)');
940
+ continue;
941
+ }
942
+
943
+ // %P[a-z]
944
+ // set dynamic variable [a-z] to pop()
945
+ if (read(/^%P([a-z])/)) {
946
+ expr('dyn.' + ch + ' = stack.pop()');
947
+ continue;
948
+ }
949
+
950
+ // %g[a-z]
951
+ // get dynamic variable [a-z] and push it
952
+ if (read(/^%g([a-z])/)) {
953
+ expr('(stack.push(dyn.' + ch + '), dyn.' + ch + ')');
954
+ continue;
955
+ }
956
+
957
+ // %P[A-Z]
958
+ // set static variable [a-z] to pop()
959
+ if (read(/^%P([A-Z])/)) {
960
+ expr('stat.' + ch + ' = stack.pop()');
961
+ continue;
962
+ }
963
+
964
+ // %g[A-Z]
965
+ // get static variable [a-z] and push it
966
+ // The terms "static" and "dynamic" are misleading. Historically,
967
+ // these are simply two different sets of variables, whose values are
968
+ // not reset between calls to tparm. However, that fact is not
969
+ // documented in other implementations. Relying on it will adversely
970
+ // impact portability to other implementations.
971
+ if (read(/^%g([A-Z])/)) {
972
+ expr('(stack.push(v = stat.' + ch + '), v)');
973
+ continue;
974
+ }
975
+
976
+ // %'c' char constant c
977
+ // NOTE: These are stored as c chars, exemplified by:
978
+ // cursor_address: "\u001b=%p1%' '%+%c%p2%' '%+%c"
979
+ if (read(/^%'(.)'/)) {
980
+ expr('(stack.push(v = ' + ch.charCodeAt(0) + '), v)');
981
+ continue;
982
+ }
983
+
984
+ // %{nn}
985
+ // integer constant nn
986
+ if (read(/^%\{(\d+)\}/)) {
987
+ expr('(stack.push(v = ' + ch + '), v)');
988
+ continue;
989
+ }
990
+
991
+ // %l push strlen(pop)
992
+ if (read(/^%l/)) {
993
+ expr('(stack.push(v = (stack.pop() || "").length || 0), v)');
994
+ continue;
995
+ }
996
+
997
+ // %+ %- %* %/ %m
998
+ // arithmetic (%m is mod): push(pop() op pop())
999
+ // %& %| %^
1000
+ // bit operations (AND, OR and exclusive-OR): push(pop() op pop())
1001
+ // %= %> %<
1002
+ // logical operations: push(pop() op pop())
1003
+ if (read(/^%([+\-*\/m&|\^=><])/)) {
1004
+ if (ch === '=') ch = '===';
1005
+ else if (ch === 'm') ch = '%';
1006
+ expr('(v = stack.pop(),'
1007
+ + ' stack.push(v = (stack.pop() ' + ch + ' v) || 0),'
1008
+ + ' v)');
1009
+ continue;
1010
+ }
1011
+
1012
+ // %A, %O
1013
+ // logical AND and OR operations (for conditionals)
1014
+ if (read(/^%([AO])/)) {
1015
+ // Are we supposed to store the result on the stack?
1016
+ expr('(stack.push(v = (stack.pop() '
1017
+ + (ch === 'A' ? '&&' : '||')
1018
+ + ' stack.pop())), v)');
1019
+ continue;
1020
+ }
1021
+
1022
+ // %! %~
1023
+ // unary operations (logical and bit complement): push(op pop())
1024
+ if (read(/^%([!~])/)) {
1025
+ expr('(stack.push(v = ' + ch + 'stack.pop()), v)');
1026
+ continue;
1027
+ }
1028
+
1029
+ // %i add 1 to first two parameters (for ANSI terminals)
1030
+ if (read(/^%i/)) {
1031
+ // Are these supposed to go on the stack in certain situations?
1032
+ // ncurses doesn't seem to put them on the stack, but xterm.user6
1033
+ // seems to assume they're on the stack for some reason. Could
1034
+ // just be a bad terminfo string.
1035
+ // user6: "\u001b[%i%d;%dR" - possibly a termcap-style string.
1036
+ // expr('(params[0] |= 0, params[1] |= 0, params[0]++, params[1]++)');
1037
+ expr('(params[0]++, params[1]++)');
1038
+ continue;
1039
+ }
1040
+
1041
+ // %? expr %t thenpart %e elsepart %;
1042
+ // This forms an if-then-else. The %e elsepart is optional. Usually
1043
+ // the %? expr part pushes a value onto the stack, and %t pops it from
1044
+ // the stack, testing if it is nonzero (true). If it is zero (false),
1045
+ // control passes to the %e (else) part.
1046
+ // It is possible to form else-if's a la Algol 68:
1047
+ // %? c1 %t b1 %e c2 %t b2 %e c3 %t b3 %e c4 %t b4 %e %;
1048
+ // where ci are conditions, bi are bodies.
1049
+ if (read(/^%\?/)) {
1050
+ end = -1;
1051
+ stmt(';if (');
1052
+ continue;
1053
+ }
1054
+
1055
+ if (read(/^%t/)) {
1056
+ end = -1;
1057
+ // Technically this is supposed to pop everything off the stack that was
1058
+ // pushed onto the stack after the if statement, see man terminfo.
1059
+ // Right now, we don't pop anything off. This could cause compat issues.
1060
+ // Perhaps implement a "pushed" counter from the time the if statement
1061
+ // is added, to the time the then statement is added, and pop off
1062
+ // the appropriate number of elements.
1063
+ // while (pushed--) expr('stack.pop()');
1064
+ stmt(') {');
1065
+ continue;
1066
+ }
1067
+
1068
+ // Terminfo does elseif's like
1069
+ // this: %?[expr]%t...%e[expr]%t...%;
1070
+ if (read(/^%e/)) {
1071
+ fi = val.indexOf('%?');
1072
+ then = val.indexOf('%t');
1073
+ els = val.indexOf('%e');
1074
+ end = val.indexOf('%;');
1075
+ if (end === -1) end = Infinity;
1076
+ if (then !== -1 && then < end
1077
+ && (fi === -1 || then < fi)
1078
+ && (els === -1 || then < els)) {
1079
+ stmt('} else if (');
1080
+ } else {
1081
+ stmt('} else {');
1082
+ }
1083
+ continue;
1084
+ }
1085
+
1086
+ if (read(/^%;/)) {
1087
+ end = null;
1088
+ stmt('}');
1089
+ continue;
1090
+ }
1091
+
1092
+ buff += val[0];
1093
+ val = val.substring(1);
1094
+ }
1095
+
1096
+ // Clear the buffer of any remaining text.
1097
+ clear();
1098
+
1099
+ // Some terminfos (I'm looking at you, atari-color), don't end an if
1100
+ // statement. It's assumed terminfo will automatically end it for
1101
+ // them, because they are a bunch of lazy bastards.
1102
+ if (end != null) {
1103
+ stmt('}');
1104
+ }
1105
+
1106
+ // Add the footer.
1107
+ stmt(footer);
1108
+
1109
+ // Optimize and cleanup generated code.
1110
+ v = code.slice(header.length, -footer.length);
1111
+ if (!v.length) {
1112
+ code = 'return "";';
1113
+ } else if (v = /^out\.push\(("(?:[^"]|\\")+")\)$/.exec(v)) {
1114
+ code = 'return ' + v[1] + ';';
1115
+ } else {
1116
+ // Turn `(stack.push(v = params[0]), v),out.push(stack.pop())`
1117
+ // into `out.push(params[0])`.
1118
+ code = code.replace(
1119
+ /\(stack\.push\(v = params\[(\d+)\]\), v\),out\.push\(stack\.pop\(\)\)/g,
1120
+ 'out.push(params[$1])');
1121
+
1122
+ // Remove unnecessary variable initializations.
1123
+ v = code.slice(header.length, -footer.length);
1124
+ if (!~v.indexOf('v = ')) code = code.replace('v, ', '');
1125
+ if (!~v.indexOf('dyn')) code = code.replace('dyn = {}, ', '');
1126
+ if (!~v.indexOf('stat')) code = code.replace('stat = {}, ', '');
1127
+ if (!~v.indexOf('stack')) code = code.replace('stack = [], ', '');
1128
+
1129
+ // Turn `var out = [];out.push("foo"),` into `var out = ["foo"];`.
1130
+ code = code.replace(
1131
+ /out = \[\];out\.push\(("(?:[^"]|\\")+")\),/,
1132
+ 'out = [$1];');
1133
+ }
1134
+
1135
+ // Terminfos `wyse350-vb`, and `wy350-w`
1136
+ // seem to have a few broken strings.
1137
+ if (str === '\u001b%?') {
1138
+ code = 'return "\\x1b";';
1139
+ }
1140
+
1141
+ if (this.debug) {
1142
+ v = code
1143
+ .replace(/\x1b/g, '\\x1b')
1144
+ .replace(/\r/g, '\\r')
1145
+ .replace(/\n/g, '\\n');
1146
+ process.stdout.write(v + '\n');
1147
+ }
1148
+
1149
+ try {
1150
+ if (this.options.stringify && code.indexOf('return ') === 0) {
1151
+ return new Function('', code)();
1152
+ }
1153
+ return this.printf || ~code.indexOf('sprintf(')
1154
+ ? new Function('sprintf, params', code).bind(null, sprintf)
1155
+ : new Function('params', code);
1156
+ } catch (e) {
1157
+ console.error('');
1158
+ console.error('Error on %s:', tkey);
1159
+ console.error(JSON.stringify(str));
1160
+ console.error('');
1161
+ console.error(code.replace(/(,|;)/g, '$1\n'));
1162
+ e.stack = e.stack.replace(/\x1b/g, '\\x1b');
1163
+ throw e;
1164
+ }
1165
+ };
1166
+
1167
+ // See: ~/ncurses/ncurses/tinfo/lib_tputs.c
1168
+ Tput.prototype._print = function(code, print, done) {
1169
+ var xon = !this.bools.needs_xon_xoff || this.bools.xon_xoff;
1170
+
1171
+ print = print || write;
1172
+ done = done || noop;
1173
+
1174
+ if (!this.padding) {
1175
+ print(code);
1176
+ return done();
1177
+ }
1178
+
1179
+ var parts = code.split(/(?=\$<[\d.]+[*\/]{0,2}>)/)
1180
+ , i = 0;
1181
+
1182
+ (function next() {
1183
+ if (i === parts.length) {
1184
+ return done();
1185
+ }
1186
+
1187
+ var part = parts[i++]
1188
+ , padding = /^\$<([\d.]+)([*\/]{0,2})>/.exec(part)
1189
+ , amount
1190
+ , suffix;
1191
+ // , affect;
1192
+
1193
+ if (!padding) {
1194
+ print(part);
1195
+ return next();
1196
+ }
1197
+
1198
+ part = part.substring(padding[0].length);
1199
+ amount = +padding[1];
1200
+ suffix = padding[2];
1201
+
1202
+ // A `/' suffix indicates that the padding is mandatory and forces a
1203
+ // delay of the given number of milliseconds even on devices for which xon
1204
+ // is present to indicate flow control.
1205
+ if (xon && !~suffix.indexOf('/')) {
1206
+ print(part);
1207
+ return next();
1208
+ }
1209
+
1210
+ // A `*' indicates that the padding required is proportional to the number
1211
+ // of lines affected by the operation, and the amount given is the
1212
+ // per-affected-unit padding required. (In the case of insert character,
1213
+ // the factor is still the number of lines affected.) Normally, padding is
1214
+ // advisory if the device has the xon capability; it is used for cost
1215
+ // computation but does not trigger delays.
1216
+ if (~suffix.indexOf('*')) {
1217
+ // XXX Disable this for now.
1218
+ amount = amount;
1219
+ // if (affect = /\x1b\[(\d+)[LM]/.exec(part)) {
1220
+ // amount *= +affect[1];
1221
+ // }
1222
+ // The above is a huge workaround. In reality, we need to compile
1223
+ // `_print` into the string functions and check the cap name and
1224
+ // params.
1225
+ // if (cap === 'insert_line' || cap === 'delete_line') {
1226
+ // amount *= params[0];
1227
+ // }
1228
+ // if (cap === 'clear_screen') {
1229
+ // amount *= process.stdout.rows;
1230
+ // }
1231
+ }
1232
+
1233
+ return setTimeout(function() {
1234
+ print(part);
1235
+ return next();
1236
+ }, amount);
1237
+ })();
1238
+ };
1239
+
1240
+ // A small helper function if we want
1241
+ // to easily output text with setTimeouts.
1242
+ Tput.print = function() {
1243
+ var fake = {
1244
+ padding: true,
1245
+ bools: { needs_xon_xoff: true, xon_xoff: false }
1246
+ };
1247
+ return Tput.prototype._print.apply(fake, arguments);
1248
+ };
1249
+
1250
+ /**
1251
+ * Termcap
1252
+ */
1253
+
1254
+ Tput.cpaths = [
1255
+ process.env.TERMCAP || '',
1256
+ (process.env.TERMPATH || '').split(/[: ]/),
1257
+ (process.env.HOME || '') + '/.termcap',
1258
+ '/usr/share/misc/termcap',
1259
+ '/etc/termcap'
1260
+ ];
1261
+
1262
+ Tput.prototype.readTermcap = function(term) {
1263
+ var self = this
1264
+ , terms
1265
+ , term_
1266
+ , root
1267
+ , paths;
1268
+
1269
+ term = term || this.terminal;
1270
+
1271
+ // Termcap has a bunch of terminals usually stored in one file/string,
1272
+ // so we need to find the one containing our desired terminal.
1273
+ if (~term.indexOf(path.sep) && (terms = this._tryCap(path.resolve(term)))) {
1274
+ term_ = path.basename(term).split('.')[0];
1275
+ if (terms[process.env.TERM]) {
1276
+ term = process.env.TERM;
1277
+ } else if (terms[term_]) {
1278
+ term = term_;
1279
+ } else {
1280
+ term = Object.keys(terms)[0];
1281
+ }
1282
+ } else {
1283
+ paths = Tput.cpaths.slice();
1284
+
1285
+ if (this.termcapFile) {
1286
+ paths.unshift(this.termcapFile);
1287
+ }
1288
+
1289
+ paths.push(Tput.termcap);
1290
+
1291
+ terms = this._tryCap(paths, term);
1292
+ }
1293
+
1294
+ if (!terms) {
1295
+ throw new Error('Cannot find termcap for: ' + term);
1296
+ }
1297
+
1298
+ root = terms[term];
1299
+
1300
+ if (this.debug) {
1301
+ this._termcap = terms;
1302
+ }
1303
+
1304
+ (function tc(term) {
1305
+ if (term && term.strings.tc) {
1306
+ root.inherits = root.inherits || [];
1307
+ root.inherits.push(term.strings.tc);
1308
+
1309
+ var names = terms[term.strings.tc]
1310
+ ? terms[term.strings.tc].names
1311
+ : [term.strings.tc];
1312
+
1313
+ self._debug('%s inherits from %s.',
1314
+ term.names.join('/'), names.join('/'));
1315
+
1316
+ var inherit = tc(terms[term.strings.tc]);
1317
+ if (inherit) {
1318
+ ['bools', 'numbers', 'strings'].forEach(function(type) {
1319
+ merge(term[type], inherit[type]);
1320
+ });
1321
+ }
1322
+ }
1323
+ return term;
1324
+ })(root);
1325
+
1326
+ // Translate termcap names to terminfo-style names.
1327
+ root = this.translateTermcap(root);
1328
+
1329
+ return root;
1330
+ };
1331
+
1332
+ Tput.prototype._tryCap = function(file, term) {
1333
+ if (!file) return;
1334
+
1335
+ var terms
1336
+ , data
1337
+ , i;
1338
+
1339
+ if (Array.isArray(file)) {
1340
+ for (i = 0; i < file.length; i++) {
1341
+ data = this._tryCap(file[i], term);
1342
+ if (data) return data;
1343
+ }
1344
+ return;
1345
+ }
1346
+
1347
+ // If the termcap string starts with `/`,
1348
+ // ncurses considers it a filename.
1349
+ data = file[0] === '/'
1350
+ ? tryRead(file)
1351
+ : file;
1352
+
1353
+ if (!data) return;
1354
+
1355
+ terms = this.parseTermcap(data, file);
1356
+
1357
+ if (term && !terms[term]) {
1358
+ return;
1359
+ }
1360
+
1361
+ return terms;
1362
+ };
1363
+
1364
+ /**
1365
+ * Termcap Parser
1366
+ * http://en.wikipedia.org/wiki/Termcap
1367
+ * http://www.gnu.org/software
1368
+ * /termutils/manual/termcap-1.3/html_mono/termcap.html
1369
+ * http://www.gnu.org/software
1370
+ * /termutils/manual/termcap-1.3/html_mono/termcap.html#SEC17
1371
+ * http://tldp.org/HOWTO/Text-Terminal-HOWTO.html#toc16
1372
+ * man termcap
1373
+ */
1374
+
1375
+ // Example:
1376
+ // vt102|dec vt102:\
1377
+ // :do=^J:co#80:li#24:cl=50\E[;H\E[2J:\
1378
+ // :le=^H:bs:cm=5\E[%i%d;%dH:nd=2\E[C:up=2\E[A:\
1379
+ // :ce=3\E[K:cd=50\E[J:so=2\E[7m:se=2\E[m:us=2\E[4m:ue=2\E[m:\
1380
+ // :md=2\E[1m:mr=2\E[7m:mb=2\E[5m:me=2\E[m:is=\E[1;24r\E[24;1H:\
1381
+ // :rs=\E>\E[?3l\E[?4l\E[?5l\E[?7h\E[?8h:ks=\E[?1h\E=:ke=\E[?1l\E>:\
1382
+ // :ku=\EOA:kd=\EOB:kr=\EOC:kl=\EOD:kb=^H:\
1383
+ // :ho=\E[H:k1=\EOP:k2=\EOQ:k3=\EOR:k4=\EOS:pt:sr=5\EM:vt#3:\
1384
+ // :sc=\E7:rc=\E8:cs=\E[%i%d;%dr:vs=\E[?7l:ve=\E[?7h:\
1385
+ // :mi:al=\E[L:dc=\E[P:dl=\E[M:ei=\E[4l:im=\E[4h:
1386
+
1387
+ Tput.prototype.parseTermcap = function(data, file) {
1388
+ var terms = {}
1389
+ , parts
1390
+ , term
1391
+ , entries
1392
+ , fields
1393
+ , field
1394
+ , names
1395
+ , i
1396
+ , j
1397
+ , k;
1398
+
1399
+ // remove escaped newlines
1400
+ data = data.replace(/\\\n[ \t]*/g, '');
1401
+
1402
+ // remove comments
1403
+ data = data.replace(/^#[^\n]+/gm, '');
1404
+
1405
+ // split entries
1406
+ entries = data.trim().split(/\n+/);
1407
+
1408
+ for (i = 0; i < entries.length; i++) {
1409
+ fields = entries[i].split(/:+/);
1410
+ for (j = 0; j < fields.length; j++) {
1411
+ field = fields[j].trim();
1412
+ if (!field) continue;
1413
+
1414
+ if (j === 0) {
1415
+ names = field.split('|');
1416
+ term = {
1417
+ name: names[0],
1418
+ names: names,
1419
+ desc: names.pop(),
1420
+ file: ~file.indexOf(path.sep)
1421
+ ? path.resolve(file)
1422
+ : file,
1423
+ termcap: true
1424
+ };
1425
+
1426
+ for (k = 0; k < names.length; k++) {
1427
+ terms[names[k]] = term;
1428
+ }
1429
+
1430
+ term.bools = {};
1431
+ term.numbers = {};
1432
+ term.strings = {};
1433
+
1434
+ continue;
1435
+ }
1436
+
1437
+ if (~field.indexOf('=')) {
1438
+ parts = field.split('=');
1439
+ term.strings[parts[0]] = parts.slice(1).join('=');
1440
+ } else if (~field.indexOf('#')) {
1441
+ parts = field.split('#');
1442
+ term.numbers[parts[0]] = +parts.slice(1).join('#');
1443
+ } else {
1444
+ term.bools[field] = true;
1445
+ }
1446
+ }
1447
+ }
1448
+
1449
+ return terms;
1450
+ };
1451
+
1452
+ /**
1453
+ * Termcap Compiler
1454
+ * man termcap
1455
+ */
1456
+
1457
+ Tput.prototype.translateTermcap = function(info) {
1458
+ var self = this
1459
+ , out = {};
1460
+
1461
+ if (!info) return;
1462
+
1463
+ this._debug(info);
1464
+
1465
+ ['name', 'names', 'desc', 'file', 'termcap'].forEach(function(key) {
1466
+ out[key] = info[key];
1467
+ });
1468
+
1469
+ // Separate aliases for termcap
1470
+ var map = (function() {
1471
+ var out = {};
1472
+
1473
+ Object.keys(Tput.alias).forEach(function(key) {
1474
+ var aliases = Tput.alias[key];
1475
+ out[aliases.termcap] = key;
1476
+ });
1477
+
1478
+ return out;
1479
+ })();
1480
+
1481
+ // Translate termcap cap names to terminfo cap names.
1482
+ // e.g. `up` -> `cursor_up`
1483
+ ['bools', 'numbers', 'strings'].forEach(function(key) {
1484
+ out[key] = {};
1485
+ Object.keys(info[key]).forEach(function(cap) {
1486
+ if (key === 'strings') {
1487
+ info.strings[cap] = self._captoinfo(cap, info.strings[cap], 1);
1488
+ }
1489
+ if (map[cap]) {
1490
+ out[key][map[cap]] = info[key][cap];
1491
+ } else {
1492
+ // NOTE: Possibly include all termcap names
1493
+ // in a separate alias.js file. Some are
1494
+ // missing from the terminfo alias.js file
1495
+ // which is why we have to do this:
1496
+ // See: $ man termcap
1497
+ out[key][cap] = info[key][cap];
1498
+ }
1499
+ });
1500
+ });
1501
+
1502
+ return out;
1503
+ };
1504
+
1505
+ Tput.prototype.compileTermcap = function(term) {
1506
+ return this.compile(this.readTermcap(term));
1507
+ };
1508
+
1509
+ Tput.prototype.injectTermcap = function(term) {
1510
+ return this.inject(this.compileTermcap(term));
1511
+ };
1512
+
1513
+ /**
1514
+ * _nc_captoinfo - ported to javascript directly from ncurses.
1515
+ * Copyright (c) 1998-2009,2010 Free Software Foundation, Inc.
1516
+ * See: ~/ncurses/ncurses/tinfo/captoinfo.c
1517
+ *
1518
+ * Convert a termcap string to terminfo format.
1519
+ * 'cap' is the relevant terminfo capability index.
1520
+ * 's' is the string value of the capability.
1521
+ * 'parameterized' tells what type of translations to do:
1522
+ * % translations if 1
1523
+ * pad translations if >=0
1524
+ */
1525
+
1526
+ Tput.prototype._captoinfo = function(cap, s, parameterized) {
1527
+ var self = this;
1528
+
1529
+ var capstart;
1530
+
1531
+ if (parameterized == null) {
1532
+ parameterized = 0;
1533
+ }
1534
+
1535
+ var MAX_PUSHED = 16
1536
+ , stack = [];
1537
+
1538
+ var stackptr = 0
1539
+ , onstack = 0
1540
+ , seenm = 0
1541
+ , seenn = 0
1542
+ , seenr = 0
1543
+ , param = 1
1544
+ , i = 0
1545
+ , out = '';
1546
+
1547
+ function warn() {
1548
+ var args = Array.prototype.slice.call(arguments);
1549
+ args[0] = 'captoinfo: ' + (args[0] || '');
1550
+ return self._debug.apply(self, args);
1551
+ }
1552
+
1553
+ function isdigit(ch) {
1554
+ return ch >= '0' && ch <= '9';
1555
+ }
1556
+
1557
+ function isgraph(ch) {
1558
+ return ch > ' ' && ch <= '~';
1559
+ }
1560
+
1561
+ // convert a character to a terminfo push
1562
+ function cvtchar(sp) {
1563
+ var c = '\0'
1564
+ , len;
1565
+
1566
+ var j = i;
1567
+
1568
+ switch (sp[j]) {
1569
+ case '\\':
1570
+ switch (sp[++j]) {
1571
+ case '\'':
1572
+ case '$':
1573
+ case '\\':
1574
+ case '%':
1575
+ c = sp[j];
1576
+ len = 2;
1577
+ break;
1578
+ case '\0':
1579
+ c = '\\';
1580
+ len = 1;
1581
+ break;
1582
+ case '0':
1583
+ case '1':
1584
+ case '2':
1585
+ case '3':
1586
+ len = 1;
1587
+ while (isdigit(sp[j])) {
1588
+ c = String.fromCharCode(8 * c.charCodeAt(0)
1589
+ + (sp[j++].charCodeAt(0) - '0'.charCodeAt(0)));
1590
+ len++;
1591
+ }
1592
+ break;
1593
+ default:
1594
+ c = sp[j];
1595
+ len = 2;
1596
+ break;
1597
+ }
1598
+ break;
1599
+ case '^':
1600
+ c = String.fromCharCode(sp[++j].charCodeAt(0) & 0x1f);
1601
+ len = 2;
1602
+ break;
1603
+ default:
1604
+ c = sp[j];
1605
+ len = 1;
1606
+ }
1607
+ if (isgraph(c) && c !== ',' && c !== '\'' && c !== '\\' && c !== ':') {
1608
+ out += '%\'';
1609
+ out += c;
1610
+ out += '\'';
1611
+ } else {
1612
+ out += '%{';
1613
+ if (c.charCodeAt(0) > 99) {
1614
+ out += String.fromCharCode(
1615
+ (c.charCodeAt(0) / 100 | 0) + '0'.charCodeAt(0));
1616
+ }
1617
+ if (c.charCodeAt(0) > 9) {
1618
+ out += String.fromCharCode(
1619
+ (c.charCodeAt(0) / 10 | 0) % 10 + '0'.charCodeAt(0));
1620
+ }
1621
+ out += String.fromCharCode(
1622
+ c.charCodeAt(0) % 10 + '0'.charCodeAt(0));
1623
+ out += '}';
1624
+ }
1625
+
1626
+ return len;
1627
+ }
1628
+
1629
+ // push n copies of param on the terminfo stack if not already there
1630
+ function getparm(parm, n) {
1631
+ if (seenr) {
1632
+ if (parm === 1) {
1633
+ parm = 2;
1634
+ } else if (parm === 2) {
1635
+ parm = 1;
1636
+ }
1637
+ }
1638
+
1639
+ if (onstack === parm) {
1640
+ if (n > 1) {
1641
+ warn('string may not be optimal');
1642
+ out += '%Pa';
1643
+ while (n--) {
1644
+ out += '%ga';
1645
+ }
1646
+ }
1647
+ return;
1648
+ }
1649
+
1650
+ if (onstack !== 0) {
1651
+ push();
1652
+ }
1653
+
1654
+ onstack = parm;
1655
+
1656
+ while (n--) {
1657
+ out += '%p';
1658
+ out += String.fromCharCode('0'.charCodeAt(0) + parm);
1659
+ }
1660
+
1661
+ if (seenn && parm < 3) {
1662
+ out += '%{96}%^';
1663
+ }
1664
+
1665
+ if (seenm && parm < 3) {
1666
+ out += '%{127}%^';
1667
+ }
1668
+ }
1669
+
1670
+ // push onstack on to the stack
1671
+ function push() {
1672
+ if (stackptr >= MAX_PUSHED) {
1673
+ warn('string too complex to convert');
1674
+ } else {
1675
+ stack[stackptr++] = onstack;
1676
+ }
1677
+ }
1678
+
1679
+ // pop the top of the stack into onstack
1680
+ function pop() {
1681
+ if (stackptr === 0) {
1682
+ if (onstack === 0) {
1683
+ warn('I\'m confused');
1684
+ } else {
1685
+ onstack = 0;
1686
+ }
1687
+ } else {
1688
+ onstack = stack[--stackptr];
1689
+ }
1690
+ param++;
1691
+ }
1692
+
1693
+ function see03() {
1694
+ getparm(param, 1);
1695
+ out += '%3d';
1696
+ pop();
1697
+ }
1698
+
1699
+ function invalid() {
1700
+ out += '%';
1701
+ i--;
1702
+ warn('unknown %% code %s (%#x) in %s',
1703
+ JSON.stringify(s[i]), s[i].charCodeAt(0), cap);
1704
+ }
1705
+
1706
+ // skip the initial padding (if we haven't been told not to)
1707
+ capstart = null;
1708
+ if (s == null) s = '';
1709
+
1710
+ if (parameterized >= 0 && isdigit(s[i])) {
1711
+ for (capstart = i;; i++) {
1712
+ if (!(isdigit(s[i]) || s[i] === '*' || s[i] === '.')) {
1713
+ break;
1714
+ }
1715
+ }
1716
+ }
1717
+
1718
+ while (s[i]) {
1719
+ switch (s[i]) {
1720
+ case '%':
1721
+ i++;
1722
+ if (parameterized < 1) {
1723
+ out += '%';
1724
+ break;
1725
+ }
1726
+ switch (s[i++]) {
1727
+ case '%':
1728
+ out += '%';
1729
+ break;
1730
+ case 'r':
1731
+ if (seenr++ === 1) {
1732
+ warn('saw %%r twice in %s', cap);
1733
+ }
1734
+ break;
1735
+ case 'm':
1736
+ if (seenm++ === 1) {
1737
+ warn('saw %%m twice in %s', cap);
1738
+ }
1739
+ break;
1740
+ case 'n':
1741
+ if (seenn++ === 1) {
1742
+ warn('saw %%n twice in %s', cap);
1743
+ }
1744
+ break;
1745
+ case 'i':
1746
+ out += '%i';
1747
+ break;
1748
+ case '6':
1749
+ case 'B':
1750
+ getparm(param, 1);
1751
+ out += '%{10}%/%{16}%*';
1752
+ getparm(param, 1);
1753
+ out += '%{10}%m%+';
1754
+ break;
1755
+ case '8':
1756
+ case 'D':
1757
+ getparm(param, 2);
1758
+ out += '%{2}%*%-';
1759
+ break;
1760
+ case '>':
1761
+ getparm(param, 2);
1762
+ // %?%{x}%>%t%{y}%+%;
1763
+ out += '%?';
1764
+ i += cvtchar(s);
1765
+ out += '%>%t';
1766
+ i += cvtchar(s);
1767
+ out += '%+%;';
1768
+ break;
1769
+ case 'a':
1770
+ if ((s[i] === '=' || s[i] === '+' || s[i] === '-'
1771
+ || s[i] === '*' || s[i] === '/')
1772
+ && (s[i + 1] === 'p' || s[i + 1] === 'c')
1773
+ && s[i + 2] !== '\0' && s[i + 2]) {
1774
+ var l;
1775
+ l = 2;
1776
+ if (s[i] !== '=') {
1777
+ getparm(param, 1);
1778
+ }
1779
+ if (s[i + 1] === 'p') {
1780
+ getparm(param + s[i + 2].charCodeAt(0) - '@'.charCodeAt(0), 1);
1781
+ if (param !== onstack) {
1782
+ pop();
1783
+ param--;
1784
+ }
1785
+ l++;
1786
+ } else {
1787
+ i += 2, l += cvtchar(s), i -= 2;
1788
+ }
1789
+ switch (s[i]) {
1790
+ case '+':
1791
+ out += '%+';
1792
+ break;
1793
+ case '-':
1794
+ out += '%-';
1795
+ break;
1796
+ case '*':
1797
+ out += '%*';
1798
+ break;
1799
+ case '/':
1800
+ out += '%/';
1801
+ break;
1802
+ case '=':
1803
+ if (seenr) {
1804
+ if (param === 1) {
1805
+ onstack = 2;
1806
+ } else if (param === 2) {
1807
+ onstack = 1;
1808
+ } else {
1809
+ onstack = param;
1810
+ }
1811
+ } else {
1812
+ onstack = param;
1813
+ }
1814
+ break;
1815
+ }
1816
+ i += l;
1817
+ break;
1818
+ }
1819
+ getparm(param, 1);
1820
+ i += cvtchar(s);
1821
+ out += '%+';
1822
+ break;
1823
+ case '+':
1824
+ getparm(param, 1);
1825
+ i += cvtchar(s);
1826
+ out += '%+%c';
1827
+ pop();
1828
+ break;
1829
+ case 's':
1830
+ // #ifdef WATERLOO
1831
+ // i += cvtchar(s);
1832
+ // getparm(param, 1);
1833
+ // out += '%-';
1834
+ // #else
1835
+ getparm(param, 1);
1836
+ out += '%s';
1837
+ pop();
1838
+ // #endif /* WATERLOO */
1839
+ break;
1840
+ case '-':
1841
+ i += cvtchar(s);
1842
+ getparm(param, 1);
1843
+ out += '%-%c';
1844
+ pop();
1845
+ break;
1846
+ case '.':
1847
+ getparm(param, 1);
1848
+ out += '%c';
1849
+ pop();
1850
+ break;
1851
+ case '0': // not clear any of the historical termcaps did this
1852
+ if (s[i] === '3') {
1853
+ see03(); // goto
1854
+ break;
1855
+ } else if (s[i] !== '2') {
1856
+ invalid(); // goto
1857
+ break;
1858
+ }
1859
+ // FALLTHRU
1860
+ case '2':
1861
+ getparm(param, 1);
1862
+ out += '%2d';
1863
+ pop();
1864
+ break;
1865
+ case '3':
1866
+ see03();
1867
+ break;
1868
+ case 'd':
1869
+ getparm(param, 1);
1870
+ out += '%d';
1871
+ pop();
1872
+ break;
1873
+ case 'f':
1874
+ param++;
1875
+ break;
1876
+ case 'b':
1877
+ param--;
1878
+ break;
1879
+ case '\\':
1880
+ out += '%\\';
1881
+ break;
1882
+ default:
1883
+ invalid();
1884
+ break;
1885
+ }
1886
+ break;
1887
+ // #ifdef REVISIBILIZE
1888
+ // case '\\':
1889
+ // out += s[i++];
1890
+ // out += s[i++];
1891
+ // break;
1892
+ // case '\n':
1893
+ // out += '\\n';
1894
+ // i++;
1895
+ // break;
1896
+ // case '\t':
1897
+ // out += '\\t';
1898
+ // i++;
1899
+ // break;
1900
+ // case '\r':
1901
+ // out += '\\r';
1902
+ // i++;
1903
+ // break;
1904
+ // case '\200':
1905
+ // out += '\\0';
1906
+ // i++;
1907
+ // break;
1908
+ // case '\f':
1909
+ // out += '\\f';
1910
+ // i++;
1911
+ // break;
1912
+ // case '\b':
1913
+ // out += '\\b';
1914
+ // i++;
1915
+ // break;
1916
+ // case ' ':
1917
+ // out += '\\s';
1918
+ // i++;
1919
+ // break;
1920
+ // case '^':
1921
+ // out += '\\^';
1922
+ // i++;
1923
+ // break;
1924
+ // case ':':
1925
+ // out += '\\:';
1926
+ // i++;
1927
+ // break;
1928
+ // case ',':
1929
+ // out += '\\,';
1930
+ // i++;
1931
+ // break;
1932
+ // default:
1933
+ // if (s[i] === '\033') {
1934
+ // out += '\\E';
1935
+ // i++;
1936
+ // } else if (s[i].charCodeAt(0) > 0 && s[i].charCodeAt(0) < 32) {
1937
+ // out += '^';
1938
+ // out += String.fromCharCode(s[i].charCodeAt(0) + '@'.charCodeAt(0));
1939
+ // i++;
1940
+ // } else if (s[i].charCodeAt(0) <= 0 || s[i].charCodeAt(0) >= 127) {
1941
+ // out += '\\';
1942
+ // out += String.fromCharCode(
1943
+ // ((s[i].charCodeAt(0) & 0300) >> 6) + '0'.charCodeAt(0));
1944
+ // out += String.fromCharCode(
1945
+ // ((s[i].charCodeAt(0) & 0070) >> 3) + '0'.charCodeAt(0));
1946
+ // out += String.fromCharCode(
1947
+ // (s[i].charCodeAt(0) & 0007) + '0'.charCodeAt(0));
1948
+ // i++;
1949
+ // } else {
1950
+ // out += s[i++];
1951
+ // }
1952
+ // break;
1953
+ // #else
1954
+ default:
1955
+ out += s[i++];
1956
+ break;
1957
+ // #endif
1958
+ }
1959
+ }
1960
+
1961
+ // Now, if we stripped off some leading padding, add it at the end
1962
+ // of the string as mandatory padding.
1963
+ if (capstart != null) {
1964
+ out += '$<';
1965
+ for (i = capstart;; i++) {
1966
+ if (isdigit(s[i]) || s[i] === '*' || s[i] === '.') {
1967
+ out += s[i];
1968
+ } else {
1969
+ break;
1970
+ }
1971
+ }
1972
+ out += '/>';
1973
+ }
1974
+
1975
+ if (s !== out) {
1976
+ warn('Translating %s from %s to %s.',
1977
+ cap, JSON.stringify(s), JSON.stringify(out));
1978
+ }
1979
+
1980
+ return out;
1981
+ };
1982
+
1983
+ /**
1984
+ * Compile All Terminfo
1985
+ */
1986
+
1987
+ Tput.prototype.getAll = function() {
1988
+ var dir = this._prefix()
1989
+ , list = asort(fs.readdirSync(dir))
1990
+ , infos = [];
1991
+
1992
+ list.forEach(function(letter) {
1993
+ var terms = asort(fs.readdirSync(path.resolve(dir, letter)));
1994
+ infos.push.apply(infos, terms);
1995
+ });
1996
+
1997
+ function asort(obj) {
1998
+ return obj.sort(function(a, b) {
1999
+ a = a.toLowerCase().charCodeAt(0);
2000
+ b = b.toLowerCase().charCodeAt(0);
2001
+ return a - b;
2002
+ });
2003
+ }
2004
+
2005
+ return infos;
2006
+ };
2007
+
2008
+ Tput.prototype.compileAll = function(start) {
2009
+ var self = this
2010
+ , all = {};
2011
+
2012
+ this.getAll().forEach(function(name) {
2013
+ if (start && name !== start) {
2014
+ return;
2015
+ } else {
2016
+ start = null;
2017
+ }
2018
+ all[name] = self.compileTerminfo(name);
2019
+ });
2020
+
2021
+ return all;
2022
+ };
2023
+
2024
+ /**
2025
+ * Detect Features / Quirks
2026
+ */
2027
+
2028
+ Tput.prototype.detectFeatures = function(info) {
2029
+ var data = this.parseACS(info);
2030
+ info.features = {
2031
+ unicode: this.detectUnicode(info),
2032
+ brokenACS: this.detectBrokenACS(info),
2033
+ PCRomSet: this.detectPCRomSet(info),
2034
+ magicCookie: this.detectMagicCookie(info),
2035
+ padding: this.detectPadding(info),
2036
+ setbuf: this.detectSetbuf(info),
2037
+ acsc: data.acsc,
2038
+ acscr: data.acscr
2039
+ };
2040
+ return info.features;
2041
+ };
2042
+
2043
+ Tput.prototype.detectUnicode = function() {
2044
+ if (process.env.NCURSES_FORCE_UNICODE != null) {
2045
+ return !!+process.env.NCURSES_FORCE_UNICODE;
2046
+ }
2047
+
2048
+ if (this.options.forceUnicode != null) {
2049
+ return this.options.forceUnicode;
2050
+ }
2051
+
2052
+ var LANG = process.env.LANG
2053
+ + ':' + process.env.LANGUAGE
2054
+ + ':' + process.env.LC_ALL
2055
+ + ':' + process.env.LC_CTYPE;
2056
+
2057
+ return /utf-?8/i.test(LANG) || (this.GetConsoleCP() === 65001);
2058
+ };
2059
+
2060
+ // For some reason TERM=linux has smacs/rmacs, but it maps to `^[[11m`
2061
+ // and it does not switch to the DEC SCLD character set. What the hell?
2062
+ // xterm: \x1b(0, screen: \x0e, linux: \x1b[11m (doesn't work)
2063
+ // `man console_codes` says:
2064
+ // 11 select null mapping, set display control flag, reset tog‐
2065
+ // gle meta flag (ECMA-48 says "first alternate font").
2066
+ // See ncurses:
2067
+ // ~/ncurses/ncurses/base/lib_set_term.c
2068
+ // ~/ncurses/ncurses/tinfo/lib_acs.c
2069
+ // ~/ncurses/ncurses/tinfo/tinfo_driver.c
2070
+ // ~/ncurses/ncurses/tinfo/lib_setup.c
2071
+ Tput.prototype.detectBrokenACS = function(info) {
2072
+ // ncurses-compatible env variable.
2073
+ if (process.env.NCURSES_NO_UTF8_ACS != null) {
2074
+ return !!+process.env.NCURSES_NO_UTF8_ACS;
2075
+ }
2076
+
2077
+ // If the terminal supports unicode, we don't need ACS.
2078
+ if (info.numbers.U8 >= 0) {
2079
+ return !!info.numbers.U8;
2080
+ }
2081
+
2082
+ // The linux console is just broken for some reason.
2083
+ // Apparently the Linux console does not support ACS,
2084
+ // but it does support the PC ROM character set.
2085
+ if (info.name === 'linux') {
2086
+ return true;
2087
+ }
2088
+
2089
+ // PC alternate charset
2090
+ // if (acsc.indexOf('+\x10,\x11-\x18.\x190') === 0) {
2091
+ if (this.detectPCRomSet(info)) {
2092
+ return true;
2093
+ }
2094
+
2095
+ // screen termcap is bugged?
2096
+ if (this.termcap
2097
+ && info.name.indexOf('screen') === 0
2098
+ && process.env.TERMCAP
2099
+ && ~process.env.TERMCAP.indexOf('screen')
2100
+ && ~process.env.TERMCAP.indexOf('hhII00')) {
2101
+ if (~info.strings.enter_alt_charset_mode.indexOf('\x0e')
2102
+ || ~info.strings.enter_alt_charset_mode.indexOf('\x0f')
2103
+ || ~info.strings.set_attributes.indexOf('\x0e')
2104
+ || ~info.strings.set_attributes.indexOf('\x0f')) {
2105
+ return true;
2106
+ }
2107
+ }
2108
+
2109
+ return false;
2110
+ };
2111
+
2112
+ // If enter_pc_charset is the same as enter_alt_charset,
2113
+ // the terminal does not support SCLD as ACS.
2114
+ // See: ~/ncurses/ncurses/tinfo/lib_acs.c
2115
+ Tput.prototype.detectPCRomSet = function(info) {
2116
+ var s = info.strings;
2117
+ if (s.enter_pc_charset_mode && s.enter_alt_charset_mode
2118
+ && s.enter_pc_charset_mode === s.enter_alt_charset_mode
2119
+ && s.exit_pc_charset_mode === s.exit_alt_charset_mode) {
2120
+ return true;
2121
+ }
2122
+ return false;
2123
+ };
2124
+
2125
+ Tput.prototype.detectMagicCookie = function() {
2126
+ return process.env.NCURSES_NO_MAGIC_COOKIE == null;
2127
+ };
2128
+
2129
+ Tput.prototype.detectPadding = function() {
2130
+ return process.env.NCURSES_NO_PADDING == null;
2131
+ };
2132
+
2133
+ Tput.prototype.detectSetbuf = function() {
2134
+ return process.env.NCURSES_NO_SETBUF == null;
2135
+ };
2136
+
2137
+ Tput.prototype.parseACS = function(info) {
2138
+ var data = {};
2139
+
2140
+ data.acsc = {};
2141
+ data.acscr = {};
2142
+
2143
+ // Possibly just return an empty object, as done here, instead of
2144
+ // specifically saying ACS is "broken" above. This would be more
2145
+ // accurate to ncurses logic. But it doesn't really matter.
2146
+ if (this.detectPCRomSet(info)) {
2147
+ return data;
2148
+ }
2149
+
2150
+ // See: ~/ncurses/ncurses/tinfo/lib_acs.c: L208
2151
+ Object.keys(Tput.acsc).forEach(function(ch) {
2152
+ var acs_chars = info.strings.acs_chars || ''
2153
+ , i = acs_chars.indexOf(ch)
2154
+ , next = acs_chars[i + 1];
2155
+
2156
+ if (!next || i === -1 || !Tput.acsc[next]) {
2157
+ return;
2158
+ }
2159
+
2160
+ data.acsc[ch] = Tput.acsc[next];
2161
+ data.acscr[Tput.acsc[next]] = ch;
2162
+ });
2163
+
2164
+ return data;
2165
+ };
2166
+
2167
+ Tput.prototype.GetConsoleCP = function() {
2168
+ var ccp;
2169
+
2170
+ if (process.platform !== 'win32') {
2171
+ return -1;
2172
+ }
2173
+
2174
+ // Allow unicode on all windows consoles for now:
2175
+ if (+process.env.NCURSES_NO_WINDOWS_UNICODE !== 1) {
2176
+ return 65001;
2177
+ }
2178
+
2179
+ // cp.execSync('chcp 65001', { stdio: 'ignore', timeout: 1500 });
2180
+
2181
+ try {
2182
+ // Produces something like: 'Active code page: 437\n\n'
2183
+ ccp = cp.execFileSync(process.env.WINDIR + '\\system32\\chcp.com', [], {
2184
+ stdio: ['ignore', 'pipe', 'ignore'],
2185
+ encoding: 'ascii',
2186
+ timeout: 1500
2187
+ });
2188
+ // ccp = cp.execSync('chcp', {
2189
+ // stdio: ['ignore', 'pipe', 'ignore'],
2190
+ // encoding: 'ascii',
2191
+ // timeout: 1500
2192
+ // });
2193
+ } catch (e) {
2194
+ ;
2195
+ }
2196
+
2197
+ ccp = /\d+/.exec(ccp);
2198
+
2199
+ if (!ccp) {
2200
+ return -1;
2201
+ }
2202
+
2203
+ ccp = +ccp[0];
2204
+
2205
+ return ccp;
2206
+ };
2207
+
2208
+ /**
2209
+ * Helpers
2210
+ */
2211
+
2212
+ function noop() {
2213
+ return '';
2214
+ }
2215
+
2216
+ noop.unsupported = true;
2217
+
2218
+ function merge(a, b) {
2219
+ Object.keys(b).forEach(function(key) {
2220
+ a[key] = b[key];
2221
+ });
2222
+ return a;
2223
+ }
2224
+
2225
+ function write(data) {
2226
+ return process.stdout.write(data);
2227
+ }
2228
+
2229
+ function tryRead(file) {
2230
+ if (Array.isArray(file)) {
2231
+ for (var i = 0; i < file.length; i++) {
2232
+ var data = tryRead(file[i]);
2233
+ if (data) return data;
2234
+ }
2235
+ return '';
2236
+ }
2237
+ if (!file) return '';
2238
+ file = path.resolve.apply(path, arguments);
2239
+ try {
2240
+ return fs.readFileSync(file, 'utf8');
2241
+ } catch (e) {
2242
+ return '';
2243
+ }
2244
+ }
2245
+
2246
+ /**
2247
+ * sprintf
2248
+ * http://www.cplusplus.com/reference/cstdio/printf/
2249
+ */
2250
+
2251
+ function sprintf(src) {
2252
+ var params = Array.prototype.slice.call(arguments, 1)
2253
+ , rule = /%([\-+# ]{1,4})?(\d+(?:\.\d+)?)?([doxXsc])/g
2254
+ , i = 0;
2255
+
2256
+ return src.replace(rule, function(_, flag, width, type) {
2257
+ var flags = (flag || '').split('')
2258
+ , param = params[i] != null ? params[i] : ''
2259
+ , initial = param
2260
+ // , width = +width
2261
+ , opt = {}
2262
+ , pre = '';
2263
+
2264
+ i++;
2265
+
2266
+ switch (type) {
2267
+ case 'd': // signed int
2268
+ param = (+param).toString(10);
2269
+ break;
2270
+ case 'o': // unsigned octal
2271
+ param = (+param).toString(8);
2272
+ break;
2273
+ case 'x': // unsigned hex int
2274
+ param = (+param).toString(16);
2275
+ break;
2276
+ case 'X': // unsigned hex int uppercase
2277
+ param = (+param).toString(16).toUppercase();
2278
+ break;
2279
+ case 's': // string
2280
+ break;
2281
+ case 'c': // char
2282
+ param = isFinite(param)
2283
+ ? String.fromCharCode(param || 0x80)
2284
+ : '';
2285
+ break;
2286
+ }
2287
+
2288
+ flags.forEach(function(flag) {
2289
+ switch (flag) {
2290
+ // left-justify by width
2291
+ case '-':
2292
+ opt.left = true;
2293
+ break;
2294
+ // always precede numbers with their signs
2295
+ case '+':
2296
+ opt.signs = true;
2297
+ break;
2298
+ // used with o, x, X - value is preceded with 0, 0x, or 0X respectively.
2299
+ // used with a, A, e, E, f, F, g, G - forces written output to contain
2300
+ // a decimal point even if no more digits follow
2301
+ case '#':
2302
+ opt.hexpoint = true;
2303
+ break;
2304
+ // if no sign is going to be written, black space in front of the value
2305
+ case ' ':
2306
+ opt.space = true;
2307
+ break;
2308
+ }
2309
+ });
2310
+
2311
+ width = +width.split('.')[0];
2312
+
2313
+ // Should this be for opt.left too?
2314
+ // Example: %2.2X - turns 0 into 00
2315
+ if (width && !opt.left) {
2316
+ param = param + '';
2317
+ while (param.length < width) {
2318
+ param = '0' + param;
2319
+ }
2320
+ }
2321
+
2322
+ if (opt.signs) {
2323
+ if (+initial >= 0) {
2324
+ pre += '+';
2325
+ }
2326
+ }
2327
+
2328
+ if (opt.space) {
2329
+ if (!opt.signs && +initial >= 0) {
2330
+ pre += ' ';
2331
+ }
2332
+ }
2333
+
2334
+ if (opt.hexpoint) {
2335
+ switch (type) {
2336
+ case 'o': // unsigned octal
2337
+ pre += '0';
2338
+ break;
2339
+ case 'x': // unsigned hex int
2340
+ pre += '0x';
2341
+ break;
2342
+ case 'X': // unsigned hex int uppercase
2343
+ pre += '0X';
2344
+ break;
2345
+ }
2346
+ }
2347
+
2348
+ if (opt.left) {
2349
+ if (width > (pre.length + param.length)) {
2350
+ width -= pre.length + param.length;
2351
+ pre = Array(width + 1).join(' ') + pre;
2352
+ }
2353
+ }
2354
+
2355
+ return pre + param;
2356
+ });
2357
+ }
2358
+
2359
+ /**
2360
+ * Aliases
2361
+ */
2362
+
2363
+ Tput._alias = require('./alias');
2364
+
2365
+ Tput.alias = {};
2366
+
2367
+ ['bools', 'numbers', 'strings'].forEach(function(type) {
2368
+ Object.keys(Tput._alias[type]).forEach(function(key) {
2369
+ var aliases = Tput._alias[type][key];
2370
+ Tput.alias[key] = [aliases[0]];
2371
+ Tput.alias[key].terminfo = aliases[0];
2372
+ Tput.alias[key].termcap = aliases[1];
2373
+ });
2374
+ });
2375
+
2376
+ // Bools
2377
+ Tput.alias.no_esc_ctlc.push('beehive_glitch');
2378
+ Tput.alias.dest_tabs_magic_smso.push('teleray_glitch');
2379
+
2380
+ // Numbers
2381
+ Tput.alias.micro_col_size.push('micro_char_size');
2382
+
2383
+ /**
2384
+ * Feature Checking
2385
+ */
2386
+
2387
+ Tput.aliasMap = {};
2388
+
2389
+ Object.keys(Tput.alias).forEach(function(key) {
2390
+ Tput.aliasMap[key] = key;
2391
+ Tput.alias[key].forEach(function(k) {
2392
+ Tput.aliasMap[k] = key;
2393
+ });
2394
+ });
2395
+
2396
+ Tput.prototype.has = function(name) {
2397
+ name = Tput.aliasMap[name];
2398
+
2399
+ var val = this.all[name];
2400
+
2401
+ if (!name) return false;
2402
+
2403
+ if (typeof val === 'number') {
2404
+ return val !== -1;
2405
+ }
2406
+
2407
+ return !!val;
2408
+ };
2409
+
2410
+ /**
2411
+ * Fallback Termcap Entry
2412
+ */
2413
+
2414
+ Tput.termcap = ''
2415
+ + 'vt102|dec vt102:'
2416
+ + ':do=^J:co#80:li#24:cl=50\\E[;H\\E[2J:'
2417
+ + ':le=^H:bs:cm=5\\E[%i%d;%dH:nd=2\\E[C:up=2\\E[A:'
2418
+ + ':ce=3\\E[K:cd=50\\E[J:so=2\\E[7m:se=2\\E[m:us=2\\E[4m:ue=2\\E[m:'
2419
+ + ':md=2\\E[1m:mr=2\\E[7m:mb=2\\E[5m:me=2\\E[m:is=\\E[1;24r\\E[24;1H:'
2420
+ + ':rs=\\E>\\E[?3l\\E[?4l\\E[?5l\\E[?7h\\E[?8h:ks=\\E[?1h\\E=:ke=\\E[?1l\\E>:'
2421
+ + ':ku=\\EOA:kd=\\EOB:kr=\\EOC:kl=\\EOD:kb=^H:\\\n'
2422
+ + ':ho=\\E[H:k1=\\EOP:k2=\\EOQ:k3=\\EOR:k4=\\EOS:pt:sr=5\\EM:vt#3:'
2423
+ + ':sc=\\E7:rc=\\E8:cs=\\E[%i%d;%dr:vs=\\E[?7l:ve=\\E[?7h:'
2424
+ + ':mi:al=\\E[L:dc=\\E[P:dl=\\E[M:ei=\\E[4l:im=\\E[4h:';
2425
+
2426
+ /**
2427
+ * Terminfo Data
2428
+ */
2429
+
2430
+ Tput.bools = [
2431
+ 'auto_left_margin',
2432
+ 'auto_right_margin',
2433
+ 'no_esc_ctlc',
2434
+ 'ceol_standout_glitch',
2435
+ 'eat_newline_glitch',
2436
+ 'erase_overstrike',
2437
+ 'generic_type',
2438
+ 'hard_copy',
2439
+ 'has_meta_key',
2440
+ 'has_status_line',
2441
+ 'insert_null_glitch',
2442
+ 'memory_above',
2443
+ 'memory_below',
2444
+ 'move_insert_mode',
2445
+ 'move_standout_mode',
2446
+ 'over_strike',
2447
+ 'status_line_esc_ok',
2448
+ 'dest_tabs_magic_smso',
2449
+ 'tilde_glitch',
2450
+ 'transparent_underline',
2451
+ 'xon_xoff',
2452
+ 'needs_xon_xoff',
2453
+ 'prtr_silent',
2454
+ 'hard_cursor',
2455
+ 'non_rev_rmcup',
2456
+ 'no_pad_char',
2457
+ 'non_dest_scroll_region',
2458
+ 'can_change',
2459
+ 'back_color_erase',
2460
+ 'hue_lightness_saturation',
2461
+ 'col_addr_glitch',
2462
+ 'cr_cancels_micro_mode',
2463
+ 'has_print_wheel',
2464
+ 'row_addr_glitch',
2465
+ 'semi_auto_right_margin',
2466
+ 'cpi_changes_res',
2467
+ 'lpi_changes_res',
2468
+
2469
+ // #ifdef __INTERNAL_CAPS_VISIBLE
2470
+ 'backspaces_with_bs',
2471
+ 'crt_no_scrolling',
2472
+ 'no_correctly_working_cr',
2473
+ 'gnu_has_meta_key',
2474
+ 'linefeed_is_newline',
2475
+ 'has_hardware_tabs',
2476
+ 'return_does_clr_eol'
2477
+ ];
2478
+
2479
+ Tput.numbers = [
2480
+ 'columns',
2481
+ 'init_tabs',
2482
+ 'lines',
2483
+ 'lines_of_memory',
2484
+ 'magic_cookie_glitch',
2485
+ 'padding_baud_rate',
2486
+ 'virtual_terminal',
2487
+ 'width_status_line',
2488
+ 'num_labels',
2489
+ 'label_height',
2490
+ 'label_width',
2491
+ 'max_attributes',
2492
+ 'maximum_windows',
2493
+ 'max_colors',
2494
+ 'max_pairs',
2495
+ 'no_color_video',
2496
+ 'buffer_capacity',
2497
+ 'dot_vert_spacing',
2498
+ 'dot_horz_spacing',
2499
+ 'max_micro_address',
2500
+ 'max_micro_jump',
2501
+ 'micro_col_size',
2502
+ 'micro_line_size',
2503
+ 'number_of_pins',
2504
+ 'output_res_char',
2505
+ 'output_res_line',
2506
+ 'output_res_horz_inch',
2507
+ 'output_res_vert_inch',
2508
+ 'print_rate',
2509
+ 'wide_char_size',
2510
+ 'buttons',
2511
+ 'bit_image_entwining',
2512
+ 'bit_image_type',
2513
+
2514
+ // #ifdef __INTERNAL_CAPS_VISIBLE
2515
+ 'magic_cookie_glitch_ul',
2516
+ 'carriage_return_delay',
2517
+ 'new_line_delay',
2518
+ 'backspace_delay',
2519
+ 'horizontal_tab_delay',
2520
+ 'number_of_function_keys'
2521
+ ];
2522
+
2523
+ Tput.strings = [
2524
+ 'back_tab',
2525
+ 'bell',
2526
+ 'carriage_return',
2527
+ 'change_scroll_region',
2528
+ 'clear_all_tabs',
2529
+ 'clear_screen',
2530
+ 'clr_eol',
2531
+ 'clr_eos',
2532
+ 'column_address',
2533
+ 'command_character',
2534
+ 'cursor_address',
2535
+ 'cursor_down',
2536
+ 'cursor_home',
2537
+ 'cursor_invisible',
2538
+ 'cursor_left',
2539
+ 'cursor_mem_address',
2540
+ 'cursor_normal',
2541
+ 'cursor_right',
2542
+ 'cursor_to_ll',
2543
+ 'cursor_up',
2544
+ 'cursor_visible',
2545
+ 'delete_character',
2546
+ 'delete_line',
2547
+ 'dis_status_line',
2548
+ 'down_half_line',
2549
+ 'enter_alt_charset_mode',
2550
+ 'enter_blink_mode',
2551
+ 'enter_bold_mode',
2552
+ 'enter_ca_mode',
2553
+ 'enter_delete_mode',
2554
+ 'enter_dim_mode',
2555
+ 'enter_insert_mode',
2556
+ 'enter_secure_mode',
2557
+ 'enter_protected_mode',
2558
+ 'enter_reverse_mode',
2559
+ 'enter_standout_mode',
2560
+ 'enter_underline_mode',
2561
+ 'erase_chars',
2562
+ 'exit_alt_charset_mode',
2563
+ 'exit_attribute_mode',
2564
+ 'exit_ca_mode',
2565
+ 'exit_delete_mode',
2566
+ 'exit_insert_mode',
2567
+ 'exit_standout_mode',
2568
+ 'exit_underline_mode',
2569
+ 'flash_screen',
2570
+ 'form_feed',
2571
+ 'from_status_line',
2572
+ 'init_1string',
2573
+ 'init_2string',
2574
+ 'init_3string',
2575
+ 'init_file',
2576
+ 'insert_character',
2577
+ 'insert_line',
2578
+ 'insert_padding',
2579
+ 'key_backspace',
2580
+ 'key_catab',
2581
+ 'key_clear',
2582
+ 'key_ctab',
2583
+ 'key_dc',
2584
+ 'key_dl',
2585
+ 'key_down',
2586
+ 'key_eic',
2587
+ 'key_eol',
2588
+ 'key_eos',
2589
+ 'key_f0',
2590
+ 'key_f1',
2591
+ 'key_f10',
2592
+ 'key_f2',
2593
+ 'key_f3',
2594
+ 'key_f4',
2595
+ 'key_f5',
2596
+ 'key_f6',
2597
+ 'key_f7',
2598
+ 'key_f8',
2599
+ 'key_f9',
2600
+ 'key_home',
2601
+ 'key_ic',
2602
+ 'key_il',
2603
+ 'key_left',
2604
+ 'key_ll',
2605
+ 'key_npage',
2606
+ 'key_ppage',
2607
+ 'key_right',
2608
+ 'key_sf',
2609
+ 'key_sr',
2610
+ 'key_stab',
2611
+ 'key_up',
2612
+ 'keypad_local',
2613
+ 'keypad_xmit',
2614
+ 'lab_f0',
2615
+ 'lab_f1',
2616
+ 'lab_f10',
2617
+ 'lab_f2',
2618
+ 'lab_f3',
2619
+ 'lab_f4',
2620
+ 'lab_f5',
2621
+ 'lab_f6',
2622
+ 'lab_f7',
2623
+ 'lab_f8',
2624
+ 'lab_f9',
2625
+ 'meta_off',
2626
+ 'meta_on',
2627
+ 'newline',
2628
+ 'pad_char',
2629
+ 'parm_dch',
2630
+ 'parm_delete_line',
2631
+ 'parm_down_cursor',
2632
+ 'parm_ich',
2633
+ 'parm_index',
2634
+ 'parm_insert_line',
2635
+ 'parm_left_cursor',
2636
+ 'parm_right_cursor',
2637
+ 'parm_rindex',
2638
+ 'parm_up_cursor',
2639
+ 'pkey_key',
2640
+ 'pkey_local',
2641
+ 'pkey_xmit',
2642
+ 'print_screen',
2643
+ 'prtr_off',
2644
+ 'prtr_on',
2645
+ 'repeat_char',
2646
+ 'reset_1string',
2647
+ 'reset_2string',
2648
+ 'reset_3string',
2649
+ 'reset_file',
2650
+ 'restore_cursor',
2651
+ 'row_address',
2652
+ 'save_cursor',
2653
+ 'scroll_forward',
2654
+ 'scroll_reverse',
2655
+ 'set_attributes',
2656
+ 'set_tab',
2657
+ 'set_window',
2658
+ 'tab',
2659
+ 'to_status_line',
2660
+ 'underline_char',
2661
+ 'up_half_line',
2662
+ 'init_prog',
2663
+ 'key_a1',
2664
+ 'key_a3',
2665
+ 'key_b2',
2666
+ 'key_c1',
2667
+ 'key_c3',
2668
+ 'prtr_non',
2669
+ 'char_padding',
2670
+ 'acs_chars',
2671
+ 'plab_norm',
2672
+ 'key_btab',
2673
+ 'enter_xon_mode',
2674
+ 'exit_xon_mode',
2675
+ 'enter_am_mode',
2676
+ 'exit_am_mode',
2677
+ 'xon_character',
2678
+ 'xoff_character',
2679
+ 'ena_acs',
2680
+ 'label_on',
2681
+ 'label_off',
2682
+ 'key_beg',
2683
+ 'key_cancel',
2684
+ 'key_close',
2685
+ 'key_command',
2686
+ 'key_copy',
2687
+ 'key_create',
2688
+ 'key_end',
2689
+ 'key_enter',
2690
+ 'key_exit',
2691
+ 'key_find',
2692
+ 'key_help',
2693
+ 'key_mark',
2694
+ 'key_message',
2695
+ 'key_move',
2696
+ 'key_next',
2697
+ 'key_open',
2698
+ 'key_options',
2699
+ 'key_previous',
2700
+ 'key_print',
2701
+ 'key_redo',
2702
+ 'key_reference',
2703
+ 'key_refresh',
2704
+ 'key_replace',
2705
+ 'key_restart',
2706
+ 'key_resume',
2707
+ 'key_save',
2708
+ 'key_suspend',
2709
+ 'key_undo',
2710
+ 'key_sbeg',
2711
+ 'key_scancel',
2712
+ 'key_scommand',
2713
+ 'key_scopy',
2714
+ 'key_screate',
2715
+ 'key_sdc',
2716
+ 'key_sdl',
2717
+ 'key_select',
2718
+ 'key_send',
2719
+ 'key_seol',
2720
+ 'key_sexit',
2721
+ 'key_sfind',
2722
+ 'key_shelp',
2723
+ 'key_shome',
2724
+ 'key_sic',
2725
+ 'key_sleft',
2726
+ 'key_smessage',
2727
+ 'key_smove',
2728
+ 'key_snext',
2729
+ 'key_soptions',
2730
+ 'key_sprevious',
2731
+ 'key_sprint',
2732
+ 'key_sredo',
2733
+ 'key_sreplace',
2734
+ 'key_sright',
2735
+ 'key_srsume',
2736
+ 'key_ssave',
2737
+ 'key_ssuspend',
2738
+ 'key_sundo',
2739
+ 'req_for_input',
2740
+ 'key_f11',
2741
+ 'key_f12',
2742
+ 'key_f13',
2743
+ 'key_f14',
2744
+ 'key_f15',
2745
+ 'key_f16',
2746
+ 'key_f17',
2747
+ 'key_f18',
2748
+ 'key_f19',
2749
+ 'key_f20',
2750
+ 'key_f21',
2751
+ 'key_f22',
2752
+ 'key_f23',
2753
+ 'key_f24',
2754
+ 'key_f25',
2755
+ 'key_f26',
2756
+ 'key_f27',
2757
+ 'key_f28',
2758
+ 'key_f29',
2759
+ 'key_f30',
2760
+ 'key_f31',
2761
+ 'key_f32',
2762
+ 'key_f33',
2763
+ 'key_f34',
2764
+ 'key_f35',
2765
+ 'key_f36',
2766
+ 'key_f37',
2767
+ 'key_f38',
2768
+ 'key_f39',
2769
+ 'key_f40',
2770
+ 'key_f41',
2771
+ 'key_f42',
2772
+ 'key_f43',
2773
+ 'key_f44',
2774
+ 'key_f45',
2775
+ 'key_f46',
2776
+ 'key_f47',
2777
+ 'key_f48',
2778
+ 'key_f49',
2779
+ 'key_f50',
2780
+ 'key_f51',
2781
+ 'key_f52',
2782
+ 'key_f53',
2783
+ 'key_f54',
2784
+ 'key_f55',
2785
+ 'key_f56',
2786
+ 'key_f57',
2787
+ 'key_f58',
2788
+ 'key_f59',
2789
+ 'key_f60',
2790
+ 'key_f61',
2791
+ 'key_f62',
2792
+ 'key_f63',
2793
+ 'clr_bol',
2794
+ 'clear_margins',
2795
+ 'set_left_margin',
2796
+ 'set_right_margin',
2797
+ 'label_format',
2798
+ 'set_clock',
2799
+ 'display_clock',
2800
+ 'remove_clock',
2801
+ 'create_window',
2802
+ 'goto_window',
2803
+ 'hangup',
2804
+ 'dial_phone',
2805
+ 'quick_dial',
2806
+ 'tone',
2807
+ 'pulse',
2808
+ 'flash_hook',
2809
+ 'fixed_pause',
2810
+ 'wait_tone',
2811
+ 'user0',
2812
+ 'user1',
2813
+ 'user2',
2814
+ 'user3',
2815
+ 'user4',
2816
+ 'user5',
2817
+ 'user6',
2818
+ 'user7',
2819
+ 'user8',
2820
+ 'user9',
2821
+ 'orig_pair',
2822
+ 'orig_colors',
2823
+ 'initialize_color',
2824
+ 'initialize_pair',
2825
+ 'set_color_pair',
2826
+ 'set_foreground',
2827
+ 'set_background',
2828
+ 'change_char_pitch',
2829
+ 'change_line_pitch',
2830
+ 'change_res_horz',
2831
+ 'change_res_vert',
2832
+ 'define_char',
2833
+ 'enter_doublewide_mode',
2834
+ 'enter_draft_quality',
2835
+ 'enter_italics_mode',
2836
+ 'enter_leftward_mode',
2837
+ 'enter_micro_mode',
2838
+ 'enter_near_letter_quality',
2839
+ 'enter_normal_quality',
2840
+ 'enter_shadow_mode',
2841
+ 'enter_subscript_mode',
2842
+ 'enter_superscript_mode',
2843
+ 'enter_upward_mode',
2844
+ 'exit_doublewide_mode',
2845
+ 'exit_italics_mode',
2846
+ 'exit_leftward_mode',
2847
+ 'exit_micro_mode',
2848
+ 'exit_shadow_mode',
2849
+ 'exit_subscript_mode',
2850
+ 'exit_superscript_mode',
2851
+ 'exit_upward_mode',
2852
+ 'micro_column_address',
2853
+ 'micro_down',
2854
+ 'micro_left',
2855
+ 'micro_right',
2856
+ 'micro_row_address',
2857
+ 'micro_up',
2858
+ 'order_of_pins',
2859
+ 'parm_down_micro',
2860
+ 'parm_left_micro',
2861
+ 'parm_right_micro',
2862
+ 'parm_up_micro',
2863
+ 'select_char_set',
2864
+ 'set_bottom_margin',
2865
+ 'set_bottom_margin_parm',
2866
+ 'set_left_margin_parm',
2867
+ 'set_right_margin_parm',
2868
+ 'set_top_margin',
2869
+ 'set_top_margin_parm',
2870
+ 'start_bit_image',
2871
+ 'start_char_set_def',
2872
+ 'stop_bit_image',
2873
+ 'stop_char_set_def',
2874
+ 'subscript_characters',
2875
+ 'superscript_characters',
2876
+ 'these_cause_cr',
2877
+ 'zero_motion',
2878
+ 'char_set_names',
2879
+ 'key_mouse',
2880
+ 'mouse_info',
2881
+ 'req_mouse_pos',
2882
+ 'get_mouse',
2883
+ 'set_a_foreground',
2884
+ 'set_a_background',
2885
+ 'pkey_plab',
2886
+ 'device_type',
2887
+ 'code_set_init',
2888
+ 'set0_des_seq',
2889
+ 'set1_des_seq',
2890
+ 'set2_des_seq',
2891
+ 'set3_des_seq',
2892
+ 'set_lr_margin',
2893
+ 'set_tb_margin',
2894
+ 'bit_image_repeat',
2895
+ 'bit_image_newline',
2896
+ 'bit_image_carriage_return',
2897
+ 'color_names',
2898
+ 'define_bit_image_region',
2899
+ 'end_bit_image_region',
2900
+ 'set_color_band',
2901
+ 'set_page_length',
2902
+ 'display_pc_char',
2903
+ 'enter_pc_charset_mode',
2904
+ 'exit_pc_charset_mode',
2905
+ 'enter_scancode_mode',
2906
+ 'exit_scancode_mode',
2907
+ 'pc_term_options',
2908
+ 'scancode_escape',
2909
+ 'alt_scancode_esc',
2910
+ 'enter_horizontal_hl_mode',
2911
+ 'enter_left_hl_mode',
2912
+ 'enter_low_hl_mode',
2913
+ 'enter_right_hl_mode',
2914
+ 'enter_top_hl_mode',
2915
+ 'enter_vertical_hl_mode',
2916
+ 'set_a_attributes',
2917
+ 'set_pglen_inch',
2918
+
2919
+ // #ifdef __INTERNAL_CAPS_VISIBLE
2920
+ 'termcap_init2',
2921
+ 'termcap_reset',
2922
+ 'linefeed_if_not_lf',
2923
+ 'backspace_if_not_bs',
2924
+ 'other_non_function_keys',
2925
+ 'arrow_key_map',
2926
+ 'acs_ulcorner',
2927
+ 'acs_llcorner',
2928
+ 'acs_urcorner',
2929
+ 'acs_lrcorner',
2930
+ 'acs_ltee',
2931
+ 'acs_rtee',
2932
+ 'acs_btee',
2933
+ 'acs_ttee',
2934
+ 'acs_hline',
2935
+ 'acs_vline',
2936
+ 'acs_plus',
2937
+ 'memory_lock',
2938
+ 'memory_unlock',
2939
+ 'box_chars_1'
2940
+ ];
2941
+
2942
+ // DEC Special Character and Line Drawing Set.
2943
+ // Taken from tty.js.
2944
+ Tput.acsc = { // (0
2945
+ '`': '\u25c6', // '◆'
2946
+ 'a': '\u2592', // '▒'
2947
+ 'b': '\u0009', // '\t'
2948
+ 'c': '\u000c', // '\f'
2949
+ 'd': '\u000d', // '\r'
2950
+ 'e': '\u000a', // '\n'
2951
+ 'f': '\u00b0', // '°'
2952
+ 'g': '\u00b1', // '±'
2953
+ 'h': '\u2424', // '\u2424' (NL)
2954
+ 'i': '\u000b', // '\v'
2955
+ 'j': '\u2518', // '┘'
2956
+ 'k': '\u2510', // '┐'
2957
+ 'l': '\u250c', // '┌'
2958
+ 'm': '\u2514', // '└'
2959
+ 'n': '\u253c', // '┼'
2960
+ 'o': '\u23ba', // '⎺'
2961
+ 'p': '\u23bb', // '⎻'
2962
+ 'q': '\u2500', // '─'
2963
+ 'r': '\u23bc', // '⎼'
2964
+ 's': '\u23bd', // '⎽'
2965
+ 't': '\u251c', // '├'
2966
+ 'u': '\u2524', // '┤'
2967
+ 'v': '\u2534', // '┴'
2968
+ 'w': '\u252c', // '┬'
2969
+ 'x': '\u2502', // '│'
2970
+ 'y': '\u2264', // '≤'
2971
+ 'z': '\u2265', // '≥'
2972
+ '{': '\u03c0', // 'π'
2973
+ '|': '\u2260', // '≠'
2974
+ '}': '\u00a3', // '£'
2975
+ '~': '\u00b7' // '·'
2976
+ };
2977
+
2978
+ // Convert ACS unicode characters to the
2979
+ // most similar-looking ascii characters.
2980
+ Tput.utoa = Tput.prototype.utoa = {
2981
+ '\u25c6': '*', // '◆'
2982
+ '\u2592': ' ', // '▒'
2983
+ // '\u0009': '\t', // '\t'
2984
+ // '\u000c': '\f', // '\f'
2985
+ // '\u000d': '\r', // '\r'
2986
+ // '\u000a': '\n', // '\n'
2987
+ '\u00b0': '*', // '°'
2988
+ '\u00b1': '+', // '±'
2989
+ '\u2424': '\n', // '\u2424' (NL)
2990
+ // '\u000b': '\v', // '\v'
2991
+ '\u2518': '+', // '┘'
2992
+ '\u2510': '+', // '┐'
2993
+ '\u250c': '+', // '┌'
2994
+ '\u2514': '+', // '└'
2995
+ '\u253c': '+', // '┼'
2996
+ '\u23ba': '-', // '⎺'
2997
+ '\u23bb': '-', // '⎻'
2998
+ '\u2500': '-', // '─'
2999
+ '\u23bc': '-', // '⎼'
3000
+ '\u23bd': '_', // '⎽'
3001
+ '\u251c': '+', // '├'
3002
+ '\u2524': '+', // '┤'
3003
+ '\u2534': '+', // '┴'
3004
+ '\u252c': '+', // '┬'
3005
+ '\u2502': '|', // '│'
3006
+ '\u2264': '<', // '≤'
3007
+ '\u2265': '>', // '≥'
3008
+ '\u03c0': '?', // 'π'
3009
+ '\u2260': '=', // '≠'
3010
+ '\u00a3': '?', // '£'
3011
+ '\u00b7': '*' // '·'
3012
+ };
3013
+
3014
+ /**
3015
+ * Expose
3016
+ */
3017
+
3018
+ exports = Tput;
3019
+ exports.sprintf = sprintf;
3020
+ exports.tryRead = tryRead;
3021
+
3022
+ module.exports = exports;