Press n or j to go to the next uncovered block, b, p or k for the previous block.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 17x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 2x 2x 2x 2x 2x 2x 2x 2x 1x 8x 1x 28x 28x 1x 21x 6x 21x 1x 9x 9x 154x 77x 2x 75x 1x 5x 1x 4x 4x 4x 4x 8x 4x 4x 4x 1x 24x 24x 11x 13x 13x 13x 4x 4x 4x 4x 4x 4x 13x 13x 13x 13x 3x 13x 13x 13x 13x 14x 14x 14x 14x 14x 14x 14x 4x 4x 4x 4x 4x 14x 14x 14x 14x 14x 1x 1x 1x 9x 9x 9x 9x 9x 5x 9x 9x 2x 2x 9x 5x 9x 9x 9x 9x 1x 2x 2x 2x 2x 2x 2x 2x 1x 4x 1x 5x 7x 7x 7x 9x 9x 9x 9x 9x 1x 9x 7x 1x 3x 6x 7x 7x 1x 3x 3x 3x 3x 3x 3x 3x 3x 1x 2x 2x 2x 2x 1x 1x 1x | import { homedir } from 'os'; import { readFileSync } from 'graceful-fs'; import * as writeAtomic from 'write-file-atomic'; import * as makedir from 'make-dir'; import * as crypto from 'crypto'; import { EventEmitter } from 'events'; import { basename, parse, resolve, join, dirname } from 'path'; import { get, set, del, has, isPlainObject, clone, isFunction, isValue, isUndefined, tryWrap } from 'chek'; import { IMap, IKStoreOptions } from './'; const ENCRYPTION_ALGORITHIM = 'aes-256-cbc'; const IV_LEN = 16; const HASH_ALGORITHIM = 'sha256'; // DEFAULTS const DEFAULTS: IKStoreOptions = { name: null, // custom name, defaults to directory name. dir: null, // custom dir to save to, defaults to $HOME/kstor/name.json entrypoint: null, // enables passing object then mapping to specific key. encryptionKey: null, // optional key for encrypting stores. transform: null // optional transform to run data through on load. }; // EVENTS // loaded (newValue, oldValue) // persisted (newValue, oldValue) // changed (newValue, oldValue) // deleted (oldValue) const createObj = () => Object.create(null); export class KStor<C> extends EventEmitter { private _loaded: boolean; // data has been initially loaded. private _dirty: boolean; // dirty data should reload.. private _writing: boolean; // Kstor is persisting data. private _loaded_defaults: boolean; // flag indicating if defaults have been set. private _cache: any = {}; // cached local top level data. private _pkg: any = {}; // the package.json file. private _cwd: string = process.cwd(); // the current working directory. path: string; // filepath for persisting. options: IKStoreOptions; // KStor options. constructor(); constructor(options: IKStoreOptions, defaults?: IMap<any>); constructor(name?: string | IKStoreOptions, defaults?: IMap<any>, options?: IKStoreOptions) constructor(name?: string | IKStoreOptions, defaults?: IMap<any>, options?: IKStoreOptions) { super(); Iif (isPlainObject(name)) { options = <IKStoreOptions>name; name = undefined; } options = options || {}; Eif (name) options.name = <string>name; this.options = Object.assign({}, DEFAULTS, options); // Read package.json. tryWrap(() => { this._pkg = JSON.parse(readFileSync(resolve(this._cwd, 'package.json')).toString()); })({ name: basename(this._cwd) }); this.path = this.getPath(this.options); process.on('exit', this.exitHandler.bind(this, 'exit')); process.on('uncaughtException', this.exitHandler.bind(this, 'error')); this.defaults(defaults); } /** * Iterator */ *[Symbol.iterator]() { let { db } = this; if (this.options.entrypoint) db = get<any>(db, this.options.entrypoint); for (const k of Object.keys(db)) { yield { key: k, value: db[k] }; } } /** * Exit Handler * Ensures write finishes before exit. * * @param type the type of exit. * @param codeOrErr the code or error upon exit. */ private exitHandler(type: string, codeOrErr) { process.removeListener('exit', this.exitHandler); process.removeListener('uncaughtException', this.exitHandler); process.stdin.resume(); const handleExit = () => { Iif (this._writing) return handleExit(); Iif (type === 'error') throw codeOrErr; // process.exit(codeOrErr); }; handleExit(); } private createHash() { return crypto .createHash(HASH_ALGORITHIM) .update(this.options.encryptionKey) .digest(); } /** * Ensure Dir * Ensures the directory exists. */ private ensureDir() { makedir.sync(dirname(this.path)); return this; } /** * Normalize Key * Normalizes key prefixing with superkey if exists. * * @param key the key to be normalized. */ private normalizeKey(key: string): string { if (this.options.entrypoint) key = `${this.options.entrypoint}.${key}`; return key; } /** * Has Listener * Checks if the Event Emitter contains a listener for the given key. * * @param key the key to inspect eventNames for. */ private hasListener(key: string) { const names = this.eventNames(); return ~names.indexOf(key); } /** * Ensure Default * Ensures a default value. * * @param val the value to be inpsected. * @param def the default value if val is undefined. */ private ensureDefault(val: any, Edef: any = null) { if (isUndefined(val)) return def; return val; } /** * Transform * Runs transform from options. * * @param data the data to be transformed. */ private transform(data) { if (!this.options.transform || !isFunction(this.options.transform)) return data; let collection = data; Eif (this.options.entrypoint) collection = get(data, this.options.entrypoint); for (const k in collection) { collection[k] = this.options.transform(k, collection[k]); } Eif (this.options.entrypoint) set(data, this.options.entrypoint, collection); else data = collection; return data; } // GETTERS // get db(): C { try { if (!this._dirty && this._loaded) return this._cache; const oldValue = this._cache; let decrypted: any = readFileSync(this.path, 'utf8') || ''; if (this.options.encryptionKey) { const arr = decrypted.split(':'); const iv = new Buffer(arr[0], 'hex'); decrypted = new Buffer(arr[1], 'hex'); const hash = this.createHash(); const decipher = crypto.createDecipheriv(ENCRYPTION_ALGORITHIM, hash, iv); decrypted = Buffer.concat([decipher.update(decrypted), decipher.final()]).toString(); } decrypted = JSON.parse(decrypted); let cache = decrypted; cache = Object.assign(createObj(), cache); // Transform values. if (this._loaded_defaults && this.options.transform && isFunction(this.options.transform)) { cache = this.transform(cache); } this._dirty = false; // superdata updated from db. this._loaded = true; // indicated we've loaded once from db. this.emit('loaded', this.ensureDefault(cache), this.ensureDefault(oldValue)); return cache; } catch (err) { this._dirty = true; // Directory doesn't exist. if (err.code === 'ENOENT') { this.ensureDir(); return createObj() as C; } // No access to file. if (err.code === 'EACCES') err.message = `${err.message} (ACCESS DENIED)`; // Invalid JSON. if (err.name === 'SyntaxError') { return createObj() as C; } // We're hosed throw error. throw err; } } set db(data: C) { try { this.ensureDir(); data = data || {} as C; const oldValue = this._cache; this.ensureDir(); let encrypted: any = JSON.stringify(data, null, '\t'); if (this.options.encryptionKey) { const iv = crypto.randomBytes(IV_LEN); const hash = this.createHash(); const cipher = crypto.createCipheriv(ENCRYPTION_ALGORITHIM, hash, iv); encrypted = Buffer.concat([cipher.update(encrypted), cipher.final()]); encrypted = `${iv.toString('hex')}:${encrypted.toString('hex')}`; } writeAtomic.sync(this.path, encrypted || ''); // persist to file system. this._cache = data; // update cache. this.emit('persisted', this.ensureDefault(data), this.ensureDefault(oldValue)); this._dirty = true; this._writing = false; } catch (err) { this._dirty = true; this._writing = false; if (err.code === 'EACCES') err.message = `${err.message} (ACCESS DENIED)`; throw err; } } /** * For Each * Sames as [...instance] here for convenience. */ get iterable() { return [...this]; } /** * Size * Gets the size of keys using iterable. */ get size() { return [...this].length; } // HELPER METHODS // /** * Get Path * Creates path for persisting data. * * @param options options to be used for generating path. */ private getPath(options?: IKStoreOptions) { options = options || {}; let isUserDir = isValue(options.dir); let name = options.name || 'config.json'; let folder = this._pkg.name || basename(this._cwd); let dir; if (!/\..+$/.test(<string>name)) name += '.json'; // Parse name check for dir. const parsedName = parse(name); // User defined filename contains dir. if (parsedName.dir) { name = parsedName.base; folder = parsedName.dir; } if (options.dir && !parsedName.dir) folder = ''; // Ensure the directory dir = dir || options.dir || homedir(); // Merge folder and name name = join(folder, name); // Define store path for persistence. const path = !isUserDir ? join(<string>dir, '.kstor', <string>name) : join(<string>dir, <string>name); return path; } /** * Defaults * Ensures defaults in store. * * @param args array of default sources. */ defaults(data: any) { let cache = this.db; const hasEntry = has(data, this.options.entrypoint); // data is at path NOT superdata. Iif (this.options.entrypoint && !hasEntry) data = set(createObj(), this.options.entrypoint, data); const result = Object.assign(createObj(), data, cache); this.db = this.transform(result); this._loaded_defaults = true; return this; } // DB METHODS // /** * Has Key * Checks if store has the specified key. * * @param key the key to inspect. */ has(key: string) { return has(this.db, this.normalizeKey(key)); } /** * Get * : Gets value for the provided key. * * @param key the key for looking up store value. * @param def a default value. */ get<T>(key: string, def?: any): T { return get<T>(this.db, this.normalizeKey(key)); } /** * Set * Sets a value for key. * * @param key the key to set. * @param value the value to set for specified key. */ set(key: string | IMap<any>, value?: any) { const cache = this.db; const setData = (k, newValue) => { const origKey = k; k = this.normalizeKey(<string>k); const oldValue = get(cache, k); set(cache, <string>k, newValue); if (this.hasListener(origKey as string)) { this.emit(`${origKey}`, this.ensureDefault(newValue), this.ensureDefault(oldValue)); } this.emit('changed', this.ensureDefault(newValue), this.ensureDefault(oldValue)); }; if (isPlainObject(key)) { for (const k in key as IMap<C>) { setData(k, key[k]); } } else { setData(key, value); } this.db = cache; return this; } /** * Del * : Removes a key from the store. * * @param key the key to be removed. */ del(key: string) { const origKey = key; const cache = this.db; key = this.normalizeKey(key); const oldValue = get(cache, key); del(cache, key); this.db = cache; this.emit('deleted', this.ensureDefault(oldValue)); return this; } // UTILITIES // /** * Clear * Clears the store basically {} */ clear() { const obj = createObj(); this.db = obj as C; this.emit('cleared', obj); return this; } /** * Snapshot * Gets a snapshot of the store's state. */ snapshot(): C { return clone<C>(this.db); } } |