Ver a proveniência

Initial commit

Add files from pridepack.
master
TheoryOfNekomata há 2 anos
cometimento
2d7128e43c
11 ficheiros alterados com 3503 adições e 0 eliminações
  1. +9
    -0
      .eslintrc
  2. +107
    -0
      .gitignore
  3. +7
    -0
      LICENSE
  4. +28
    -0
      README.md
  5. +88
    -0
      package.json
  6. +3
    -0
      pridepack.json
  7. +103
    -0
      src/index.ts
  8. +97
    -0
      test/index.test.ts
  9. +21
    -0
      tsconfig.eslint.json
  10. +21
    -0
      tsconfig.json
  11. +3019
    -0
      yarn.lock

+ 9
- 0
.eslintrc Ver ficheiro

@@ -0,0 +1,9 @@
{
"root": true,
"extends": [
"lxsmnsyc/typescript"
],
"parserOptions": {
"project": "./tsconfig.eslint.json"
}
}

+ 107
- 0
.gitignore Ver ficheiro

@@ -0,0 +1,107 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*

# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json

# Runtime data
pids
*.pid
*.seed
*.pid.lock

# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov

# Coverage directory used by tools like istanbul
coverage
*.lcov

# nyc test coverage
.nyc_output

# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt

# Bower dependency directory (https://bower.io/)
bower_components

# node-waf configuration
.lock-wscript

# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release

# Dependency directories
node_modules/
jspm_packages/

# TypeScript v1 declaration files
typings/

# TypeScript cache
*.tsbuildinfo

# Optional npm cache directory
.npm

# Optional eslint cache
.eslintcache

# Microbundle cache
.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/

# Optional REPL history
.node_repl_history

# Output of 'npm pack'
*.tgz

# Yarn Integrity file
.yarn-integrity

# dotenv environment variables file
.env
.env.production
.env.development

# parcel-bundler cache (https://parceljs.org/)
.cache

# Next.js build output
.next

# Nuxt.js build / generate output
.nuxt
dist

# Gatsby files
.cache/
# Comment in the public line in if your project uses Gatsby and *not* Next.js
# https://nextjs.org/blog/next-9-1#public-directory-support
# public

# vuepress build output
.vuepress/dist

# Serverless directories
.serverless/

# FuseBox cache
.fusebox/

# DynamoDB Local files
.dynamodb/

# TernJS port file
.tern-port

.npmrc

+ 7
- 0
LICENSE Ver ficheiro

@@ -0,0 +1,7 @@
MIT License Copyright (c) 2022 TheoryOfNekomata <allan.crisostomo@outlook.com>

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice (including the next paragraph) shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

+ 28
- 0
README.md Ver ficheiro

@@ -0,0 +1,28 @@
# uuid-buffer

UUID as a Buffer.

UUIDs are 128-bit values used for identification of entities.
Representing them as strings are expensive since it can incur more than
128 bits. This library will help properly represent UUID values while
still having some utility methods like serialization (i.e. converting
them to string representations), as well as generation according to the
v4 spec.

## Usage

```ts
import { Uuid } from '@theoryofnekomata/uuid-buffer';

const newUuidV4 = Uuid.v4(); // sync

let uuidStr = '1d4a8818-a773-4b52-9b6b-4db8c7fd9bf2';

// this method can accept strings, buffers, and bute arrays
const uuidFromStr = Uuid.from(uuidStr);

```

## License

See LICENSE file for details.

+ 88
- 0
package.json Ver ficheiro

@@ -0,0 +1,88 @@
{
"name": "@theoryofnekomata/uuid-buffer",
"version": "0.1.0",
"types": "dist/types/index.d.ts",
"main": "dist/cjs/production/index.js",
"module": "dist/esm/production/index.js",
"exports": {
".": {
"development": {
"require": "./dist/cjs/development/index.js",
"import": "./dist/esm/development/index.js"
},
"require": "./dist/cjs/production/index.js",
"import": "./dist/esm/production/index.js",
"types": "./dist/types/index.d.ts"
},
"./dev": {
"production": {
"require": "./dist/cjs/production/index.js",
"import": "./dist/esm/production/index.js"
},
"require": "./dist/cjs/development/index.js",
"import": "./dist/esm/development/index.js",
"types": "./dist/types/index.d.ts"
},
"./esm": {
"development": "./dist/esm/development/index.js",
"production": "./dist/esm/production/index.js",
"default": "./dist/esm/production/index.js",
"types": "./dist/types/index.d.ts"
},
"./cjs": {
"development": "./dist/cjs/development/index.js",
"production": "./dist/cjs/production/index.js",
"default": "./dist/cjs/production/index.js",
"types": "./dist/types/index.d.ts"
}
},
"files": [
"dist",
"src"
],
"engines": {
"node": ">=10"
},
"license": "MIT",
"keywords": [
"pridepack"
],
"devDependencies": {
"@types/node": "^17.0.25",
"eslint": "^8.13.0",
"eslint-config-lxsmnsyc": "^0.4.0",
"pridepack": "1.1.1",
"tslib": "^2.4.0",
"typescript": "^4.6.3",
"vitest": "^0.9.4"
},
"scripts": {
"prepublishOnly": "pridepack clean && pridepack build",
"build": "pridepack build",
"type-check": "pridepack check",
"lint": "pridepack lint",
"clean": "pridepack clean",
"watch": "pridepack watch",
"start": "pridepack start",
"dev": "pridepack dev",
"test": "vitest"
},
"private": false,
"description": "UUID as a buffer.",
"repository": {
"url": "https://code.modal.sh/TheoryOfNekomata/uuid-buffer",
"type": "git"
},
"homepage": "https://code.modal.sh/TheoryOfNekomata/uuid-buffer",
"bugs": {
"url": "https://code.modal.sh/TheoryOfNekomata/uuid-buffer/issues"
},
"author": "TheoryOfNekomata <allan.crisostomo@outlook.com>",
"publishConfig": {
"access": "public"
},
"dependencies": {
"@types/uuid": "^8.3.4",
"uuid": "^8.3.2"
}
}

+ 3
- 0
pridepack.json Ver ficheiro

@@ -0,0 +1,3 @@
{
"target": "es2017"
}

+ 103
- 0
src/index.ts Ver ficheiro

@@ -0,0 +1,103 @@
import { v4 } from 'uuid'

interface UuidProto {
length: number,
toString(this: UuidProto): string,
toJSON(this: UuidProto): string,
}

export class Uuid extends Buffer {
static STRING_PATTERN = /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i;

private static _toUuidString(this: Uuid, encoding?: string) {
const thisBuffer = this as unknown as Buffer;

if (typeof encoding === 'string') {
const buffer = Buffer.from(thisBuffer);
return buffer.toString(encoding as BufferEncoding);
}

let uuidStr = ''
for (let i = 0; i < this.length; i += 1) {
if (
i === 4
|| i === 6
|| i === 8
|| i === 10
) {
uuidStr += '-'
}
uuidStr += thisBuffer[i].toString(16).padStart(2, '0')
}
return uuidStr;
}

private static _toJSON(this: Uuid) {
const thisBuffer = this as unknown as Buffer;
const toUuidString = Uuid._toUuidString.bind(thisBuffer);
return toUuidString();
}

private static _attachMethods(uuid: UuidProto) {
uuid.toString = Uuid._toUuidString.bind(uuid as unknown as Buffer);
uuid.toJSON = Uuid._toJSON.bind(uuid as unknown as Buffer);
uuid.constructor = Uuid;
}

static v4(): Uuid {
const uuidBuffer = Buffer.alloc(16)
const uuid = v4(null, uuidBuffer) as unknown as UuidProto;
Uuid._attachMethods(uuid);
return uuid as unknown as Uuid;
}

static from(arg: unknown): Uuid {
if (typeof arg === 'string') {
if (Uuid.STRING_PATTERN.test(arg)) {
const uuidStrStripped = arg.replaceAll('-', '')
const uuidBytes = [] as number[];
for (let i = 0; i < 16; i += 1) {
uuidBytes.push(
parseInt(`${uuidStrStripped[i * 2]}${uuidStrStripped[i * 2 + 1]}`, 16)
)
}
const uuid = Buffer.from(uuidBytes) as unknown as UuidProto
Uuid._attachMethods(uuid);
return uuid as unknown as Buffer;
}
throw new TypeError(`Malformed UUID string: ${arg}`);
}


if (
arg instanceof ArrayBuffer
|| arg instanceof Uint8Array
|| arg instanceof Buffer
) {
if (arg.byteLength !== 16) {
throw new TypeError('Value could not be represented as UUID.');
}

const uuid = Buffer.from(arg) as unknown as UuidProto;
Uuid._attachMethods(uuid);
return uuid as unknown as Buffer;
}

if (Array.isArray(arg)) {
if (arg.length !== 16) {
throw new TypeError('Value could not be represented as UUID.');
}
const uuid = Buffer.from(arg) as unknown as UuidProto
Uuid._attachMethods(uuid);
return uuid as unknown as Buffer;
}

throw new TypeError('Invalid argument');
}

constructor() {
super(String.fromCharCode(...new Array(16).fill(0)));
const thisBuffer = this as unknown as UuidProto;
Uuid._attachMethods(thisBuffer);
}
}

+ 97
- 0
test/index.test.ts Ver ficheiro

@@ -0,0 +1,97 @@
import { describe, it, expect, } from 'vitest';
import { Uuid } from '../src'

describe('uuid-compact', () => {
describe('Uuid', () => {
it('should create a default Uuid instance when instantiated', () => {
const uuid = new Uuid()
expect(uuid.toString()).toBe('00000000-0000-0000-0000-000000000000')
})

describe('v4', () => {
it('should create a new Uuid instance', () => {
const uuid = Uuid.v4()
expect(uuid.toString()).toMatch(Uuid.STRING_PATTERN)
})
})

describe('from', () => {
it('should parse a string argument', () => {
const uuid = Uuid.from('00000000-0000-0000-0000-000000000000')
expect(uuid.toString()).toBe('00000000-0000-0000-0000-000000000000')
})

it('should throw an error with malformed string argument', () => {
expect(() => Uuid.from('Z')).toThrowError(TypeError);
})

it('should parse a Uint8Array argument', () => {
const byteArray = new Uint8Array([
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
]);
const uuid = Uuid.from(byteArray)
expect(uuid.toString()).toBe('00000000-0000-0000-0000-000000000000')
})

it('should throw an error with malformed Uint8Array argument', () => {
expect(() => Uuid.from(new Uint8Array([0]))).toThrowError(TypeError);
})

it('should parse an ArrayBuffer argument', () => {
const byteArray = new Uint8Array([
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
]);
const arrayBuffer = byteArray.buffer
const uuid = Uuid.from(arrayBuffer)
expect(uuid.toString()).toBe('00000000-0000-0000-0000-000000000000')
})

it('should throw an error with malformed ArrayBuffer argument', () => {
expect(() => Uuid.from(new Uint8Array([0]).buffer)).toThrowError(TypeError);
})

it('should parse a number array', () => {
const byteArray = [
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
]
const uuid = Uuid.from(byteArray)
expect(uuid.toString()).toBe('00000000-0000-0000-0000-000000000000')
})

it('should throw an error with malformed array argument', () => {
expect(() => Uuid.from([0])).toThrowError(TypeError);
})

it('should parse a buffer', () => {
const buffer = Buffer.alloc(16).fill(0)
const uuid = Uuid.from(buffer)
expect(uuid.toString()).toBe('00000000-0000-0000-0000-000000000000')
})

it('should throw an error with malformed buffer argument', () => {
expect(() => Uuid.from(Buffer.alloc(1).fill(0))).toThrowError(TypeError);
})
})

describe('toJSON', () => {
it('should return the string representation', () => {
const uuid = Uuid.from('00000000-0000-0000-0000-000000000000')
expect(uuid.toJSON()).toBe('00000000-0000-0000-0000-000000000000')
})
})

describe('equals', () => {
it('should compare two equal values', () => {
const uuid1 = Uuid.from('00000000-0000-0000-0000-000000000000')
const uuid2 = Uuid.from('00000000-0000-0000-0000-000000000000')
expect(uuid1.equals(uuid2)).toBe(true);
});

it('should compare two unequal values', () => {
const uuid1 = Uuid.from('1d4a8818-a773-4b52-9b6b-4db8c7fd9bf2');
const uuid2 = Uuid.from('00000000-0000-0000-0000-000000000000')
expect(uuid1.equals(uuid2)).not.toBe(true);
})
})
})
})

+ 21
- 0
tsconfig.eslint.json Ver ficheiro

@@ -0,0 +1,21 @@
{
"exclude": ["node_modules"],
"include": ["src", "types", "test"],
"compilerOptions": {
"module": "ESNext",
"lib": ["ESNext"],
"importHelpers": true,
"declaration": true,
"sourceMap": true,
"rootDir": "./",
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true,
"moduleResolution": "node",
"jsx": "react",
"esModuleInterop": true,
"target": "ES2017"
}
}

+ 21
- 0
tsconfig.json Ver ficheiro

@@ -0,0 +1,21 @@
{
"exclude": ["node_modules"],
"include": ["src", "types"],
"compilerOptions": {
"module": "ESNext",
"lib": ["ESNext"],
"importHelpers": true,
"declaration": true,
"sourceMap": true,
"rootDir": "./src",
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true,
"moduleResolution": "node",
"jsx": "react",
"esModuleInterop": true,
"target": "ES2017"
}
}

+ 3019
- 0
yarn.lock
A apresentação das diferenças no ficheiro foi suprimida por ser demasiado grande
Ver ficheiro


Carregando…
Cancelar
Guardar