Skip to content

Commit

Permalink
Merge pull request #1 from lybell-art/indev
Browse files Browse the repository at this point in the history
Version 1.1 update
  • Loading branch information
lybell-art committed May 25, 2022
2 parents 2dd7954 + 32c2f53 commit 81d7e16
Show file tree
Hide file tree
Showing 159 changed files with 116,689 additions and 24,196 deletions.
34 changes: 34 additions & 0 deletions api-ko.md
Original file line number Diff line number Diff line change
Expand Up @@ -96,9 +96,15 @@ XnbData를 Blob 배열로 반환합니다. 형식은 unpackToFiles과 동일합
### pack( files : Flielist/Array, configs : Object )
- ``files`` (Filelist/Array) : xnb로 묶을 파일의 전체 리스트. json 파일 혹은 yaml 파일이 포함되어 있어야 합니다.
- ``configs`` (Object) : 컨피그 설정
- ``compression`` (String) : 압축 방식입니다. 기본값은 ``"default"``입니다.
- ``debug`` (Boolean) : `true`로 설정할 시, 모든 파일의 성공 및 실패 결과가 반환됩니다.

패킹할 파일들이 들어 있는 리스트를 받아, 각각의 파일들을 xnb 파일로 변환합니다. 헤더의 정보가 들어 있는 json 파일 혹은 yaml 파일(XnbExtract와 호환됨)이 포함되어 있어야 합니다.
xnb.js에서 현재 지원하는 압축 방식은 다음과 같습니다.
- `"default"` : 헤더에 명시된 압축 방식을 가급적 사용하도록 동작합니다. LZ4 압축 방식으로 명시된 파일은 LZ4 압축을 사용합니다. 현재 버전에는 LZX 압축 알고리즘이 구현되어 있지 않기 때문에, LZX 압축 방식으로 명시된 파일은 압축하지 않습니다.
- `"none"` : 압축하지 않은 결과를 반환합니다.
- `"LZ4"` : LZ4 압축 방식을 사용합니다. `"default"`에 비해 작은 파일 크기를 보장합니다. XnbExtract가 LZ4 압축 해제를 지원하지 않으므로, 이 설정을 사용하여 압축 해제된 파일은 XnbExtract에서 열 수 없습니다.(Stardew Valley에서는 열 수 있습니다.)

Pack 함수는 브라우저 환경에서는 `<input type="file">` 엘리먼트의 `files`를 바로 넣을 수 있으나, node.js 환경에서는 `FileList` 객체가 없으므로, 각 원소가 `{name, data}` 오브젝트인 배열을 매개변수로 넣어야 합니다. `name`은 파일의 이름을, `data`는 파일의 실제 바이너리 버퍼를 의미합니다.
node.js 환경에서 pack 함수를 사용하기 위해서는 다음의 예제를 참조하십시오.
```js
Expand All @@ -118,6 +124,34 @@ const result = await pack(fileList);
console.log(result);
```

## Reader Plugins

### setReaders( readers : Object\<BaseReader\> )
- ``readers`` (ArrayBuffer) : Reader

xnb.js에서 사용하는 리더의 종류를 지정합니다. 특정한 Reader만 사용하고 싶을 때 유용합니다.
``readers``의 key는 xnb 파일의 헤더가 인식 가능한 자료명+Reader로, value는 BaseReader를 상속한 리더 클래스가 들어가야 합니다. 다음의 예제를 참조하십시오.
```js
import {setReaders} from "@xnb/core";
import {LightweightTexture2DReader, StringReader} from "@xnb/readers";

setReaders({
Texture2DReader : LightweightTexture2DReader,
StringReader : StringReader
});
```

### addReaders( readers : Object\<BaseReader\> )
- ``readers`` (ArrayBuffer) : Reader

xnb.js에서 사용하는 리더를 추가합니다. 플러그인을 추가하고 싶을 때 유용합니다. 다음의 예제를 참조하십시오.
```js
import {addReaders} from "xnb";
import * as StardewReader from "@xnb/stardew-valley";

addReaders({...StardewReader});
```

## Data Structure
### XnbData
XnbData 객체는 Xnb 파일에서 추출된 헤더와 리더 정보, 컨텐츠가 포함된 오브젝트입니다. unpackToXnbData(), bufferToXnb()의 반환값입니다. 라이브러리를 worker로 활용해서 데이터를 언팩할 때, json 데이터를 XnbData 객체로 변환할 수 있습니다.
Expand Down
34 changes: 34 additions & 0 deletions api.md
Original file line number Diff line number Diff line change
Expand Up @@ -118,9 +118,15 @@ Convert XnbData to Files array. The format of the array is the same as that of `
### pack( files : Flielist/Array, configs : Object )
- ``files`` (Filelist/Array) : A array of files to be packed to xnb. Json or yaml file must be included.
- ``configs`` (Object) : configs
- ``compression`` (String) : Compression method. default is ``"default"``.
- ``debug`` (Boolean) : If `true`, it returns the success and failure results of all files.

Receive a list of files to pack and convert them into xnb files. The json or yaml file containing the information in the header must be included. Compatible with XnbExtract.
The compression methods currently supported by xnb.js are the following:
- `"default"` : Try to use the compression algorithm specified in the header. Files specified as LZ4 compression perform LZ4 compression. Because the LZX compression algorithm is not implemented, files specified as LZX compression are not compressed.
- `"none"` : Export the file with uncompressed data.
- `"LZ4"` : Use LZ4 compression. Ensure a smaller file size. Exported file is incompatible with XnbExtract because it cannot read xnb files compressed with LZ4.

You can directly put `Filelist` object in a browser environment. But in a node.js environment, there is no `FileList` object, so you must put an array whose elements are `{name, data}` objects as parameters. `name` means the name of the file and `data` means the actual binary buffer of the file.
To use this in a node.js environment, see the following example:
```js
Expand All @@ -140,6 +146,34 @@ const result = await pack(fileList);
console.log(result);
```

## Reader Plugins

### setReaders( readers : Object\<BaseReader\> )
- ``readers`` (ArrayBuffer) : Reader

Specifies the type of reader used by xnb.js. This is useful when you want to use only certain readers.
The key of ``readers`` should be a recognizable data name+Reader for the header of the xnb file, and the value should include the reader class that inherited the BaseReader. See the following example:
```js
import {setReaders} from "@xnb/core";
import {LightweightTexture2DReader, StringReader} from "@xnb/readers";

setReaders({
Texture2DReader : LightweightTexture2DReader,
StringReader : StringReader
});
```

### addReaders( readers : Object\<BaseReader\> )
- ``readers`` (ArrayBuffer) : Reader

Add the readers used by xnb.js. This is useful when you want to add plugins. See the following example:
```js
import {addReaders} from "xnb";
import * as StardewReader from "@xnb/stardew-valley";

addReaders(StardewReader);
```

## Data Structure
### XnbData
`XnbData` is the object included headers, readers data, and content data extracted from xnb file. `unpackToXnbData()`, and `bufferToXnb()` returns this. When unpacking xnb using the library as a worker, you can convert json data into XnbData objects.
Expand Down
156 changes: 156 additions & 0 deletions builder/builder-plugins.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,156 @@
import babel from '@rollup/plugin-babel';
import polyfill from './polyfills/makePolyfill.js';
import babelrc from './.babelrc.json';
import es5babelrc from './.babelrc.es5.json';
import { nodeResolve } from '@rollup/plugin-node-resolve';
import commonjs from '@rollup/plugin-commonjs';
import {terser} from "rollup-plugin-terser";

function removeDebug() {
return {
resolveId(importee) {
return importee.includes("Debug.js") ? "__empty__" : null;
},
load(id) {
return (id === "__empty__") ? "export default {};" : null;
},
transform(code, filename) {
code = code.replace(/\/\/ read the target platform\s+switch[\s\S]+found\.`\);\s+break;\s+}/mg, "");
code = code.replace(/\/\/ read the XNB format version\s+switch[\s\S]+unknown\.`\);\s+break;\s+}/mg, "");
code = code.replace(/Debug\(.+[\)];\n{0,1}/g, "");
code = code.replace("import Debug from .*\n$", "");
return {
code: code,
map: null
};
}
}
}

function babelCleanup() {
const doubleSpaces = / {2}/g;
return {
transform( code ) {
code = code.replace( doubleSpaces, '\t' );
return {
code: code,
map: null
};
}
};
}

function makePlugins(production=false, es5=false)
{
const shouldPrintComment = (val)=>{
const regexp = new RegExp(`^\\* @(api|license)(?!\\S)`);
return production ? false : regexp.test(val);
}

const commonPlugins = [
removeDebug(),
polyfill( { version: (es5 ? "es5" : "es2017") } ),
babel({
babelHelpers:'bundled',
babelrc: false,
exclude:'node_modules/**',
...(es5 ? es5babelrc : babelrc),
shouldPrintComment
}),
babelCleanup()
];

const es5Plugins = [
nodeResolve(),
commonjs()
];
const prodPlugins = [
terser()
];

return [
...(es5 ? es5Plugins : []),
...commonPlugins,
...(production ? prodPlugins : [])
]
}

function makeBanners(production=false, includes={})
{
const licensesDict={
LZ4: ` * LZ4 decoder license : ICS
* Original code : https://github.com/Benzinga/lz4js/`,
LZX: ` * LZX decoder license : LGPL 2.1
* -----------------------------------------------------------------------------
* This file is heavily based on MonoGame's implementation of their LzxDecoder attributed to Ali Scissons
* which is derived from libmspack by Stuart Cole.
*
* (C) 2003-2004 Stuart Caie.
* (C) 2011 Ali Scissons.
* (C) 2017 James Stine.
*
* The LZX method was created by Johnathan Forbes and Tomi Poutanen, adapted by Microsoft Corporation.
*
* GNU LESSER GENERAL PUBLIC LICENSE version 2.1
* LzxDecoder is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License (LGPL) version 2.1
*
* MICROSOFT PUBLIC LICENSE
* This source code a derivative on LzxDecoder and is subject to the terms of the Microsoft Public License (Ms-PL).
*
* Redistribution and use in source and binary forms, with or without modification,
* is permitted provided that redistributions of the source code retain the above
* copyright notices and this file header.
*
* Additional copyright notices should be appended to the list above.
*
* For details, see <http://www.opensource.org/licenses/ms-pl.html>.
*
*
* I made the mistake of not including this license years ago. Big thanks to everyone involved and license has now been
* acknowleded properly as it should have been back in 2017.
*
* Resources:
*
* cabextract/libmspack - http://http://www.cabextract.org.uk/
* MonoGame LzxDecoder.cs - https://github.com/MonoGame/MonoGame/blob/master/MonoGame.Framework/Content/LzxDecoder.cs
* -----------------------------------------------------------------------------`,
DXT: ` * Libsquish license : MIT
* -----------------------------------------------------------------------------
* Copyright (c) 2006 Simon Brown si@sjbrown.co.uk
* 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 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.
*
* --------------------------------------------------------------------------`
}
let licensesComments = [];
for(let key of Object.keys(licensesDict))
{
if(includes[key] === true) licensesComments.push(licensesDict[key]);
}
return `/**
* xnb.js 1.1.0
* made by Lybell( https://github.com/lybell-art/ )
* This library is based on the XnbCli made by Leonblade.
*
* xnb.js is licensed under the LGPL 3.0 License.
* ${production ? "\n"+licensesComments.join("\n *\n") : ""}
*/
`;
}

export { makePlugins, makeBanners };
Loading

0 comments on commit 81d7e16

Please sign in to comment.