aicommunicator-plugin-check 0.0.0-stage → 0.1.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.
package/LICENSE ADDED
@@ -0,0 +1,55 @@
1
+ Apache License
2
+
3
+ Version 2.0, January 2004
4
+
5
+ http://www.apache.org/licenses/
6
+
7
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
8
+
9
+ 1. Definitions.
10
+
11
+ "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
16
+
17
+ "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
18
+
19
+ "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
20
+
21
+ "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
22
+
23
+ "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
24
+
25
+ "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
26
+
27
+ "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
28
+
29
+ "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
30
+
31
+ 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
32
+
33
+ 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
34
+
35
+ 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
36
+
37
+ You must give any other recipients of the Work or Derivative Works a copy of this License; and
38
+
39
+ You must cause any modified files to carry prominent notices stating that You changed the files; and
40
+
41
+ You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
42
+
43
+ If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
44
+
45
+ 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
46
+
47
+ 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
48
+
49
+ 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
50
+
51
+ 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
52
+
53
+ 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
54
+
55
+ END OF TERMS AND CONDITIONS
package/README.md CHANGED
@@ -1,3 +1,58 @@
1
- # Temporary Holding Version
1
+ # aicommunicator-plugin-check
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ AIC(aicommunicator) 플러그인의 manifest 와 묶음 파일(`.tgz`)의 규칙을 확인하는 코드입니다. AIC 코어, `aic` 명령, 플러그인 등록 사이트가 이 패키지 하나를 함께 써서, 셋이 같은 플러그인을 같은 규칙으로 받아들이거나 거절합니다.
4
+
5
+ - 다른 패키지에 기대지 않고 Node 내장 모듈(`node:crypto`, `node:zlib`)만 씁니다. Node 22.13 이상에서 돕니다.
6
+ - 플러그인 코드를 실행하지 않습니다. manifest 의 글, 묶음 안의 파일 이름과 크기, 설명서와 예제 파일의 글만 봅니다.
7
+ - 설계는 aicommunicator 저장소의 `doc/036_plugin_registry_design.md` 에 있고, 설명서와 예제는 `doc/037_plugin_manual_design.md` 에 있습니다.
8
+
9
+ ```bash
10
+ npm install aicommunicator-plugin-check
11
+ ```
12
+
13
+ ```js
14
+ import { readBundle, checkBundleForRegistry, BundleError } from 'aicommunicator-plugin-check';
15
+
16
+ try {
17
+ const bundle = readBundle(buffer); // .tgz 의 Buffer
18
+ const problem = checkBundleForRegistry(bundle);
19
+ if (problem) console.log(problem.code, problem.message);
20
+ } catch (e) {
21
+ if (e instanceof BundleError) console.log(e.code, e.message);
22
+ }
23
+ ```
24
+
25
+ ## 내보내는 것
26
+
27
+ | 이름 | 하는 일 |
28
+ | --- | --- |
29
+ | `PROTOCOL_VERSION` | 코어의 플러그인 계약 버전. 지금 `"0.1"` |
30
+ | `checkManifest(manifest)` | 코어가 쓰는 manifest 검사. 틀리면 까닭의 글, 맞으면 `null` |
31
+ | `checkForRegistry(manifest)` | `checkManifest` 에 더해 사이트에 올릴 때 필요한 칸(`protocol`, `license`, `title`, `about`)을 본다 |
32
+ | `checkBundleForRegistry(bundle)` | `checkForRegistry` 와 `LICENSE` 파일을 본다. 문제가 있으면 `{ code, message }`(code 는 `bad_manifest` 나 `bad_bundle`), 없으면 `null` |
33
+ | `readBundle(buffer)` | `.tgz` 를 풀어 규칙(들어갈 수 있는 파일, 5MB, 200개, 묶음 밖 경로, 링크, 설명서와 예제)을 확인하고 `{ manifest, files, sha256, size }` 를 돌려준다. 틀리면 `BundleError` 를 던진다 |
34
+ | `BundleError` | `code` 가 `too_large`, `bad_bundle`, `bad_manifest` 가운데 하나다 |
35
+ | `packBundle(files)` | 파일 목록으로 `.tgz` 를 만든다. 같은 입력이면 같은 바이트가 나온다 |
36
+ | `compareVersions(a, b)` | semver 순서. -1, 0, 1 |
37
+ | `satisfies(version, range)` | `1.2.3`, `^1.2.3`, `~1.2.3`, `>=1.2.3` 네 가지 범위. 뜻은 npm 과 같다 |
38
+ | `protocolAccepts(range, core?)` | manifest 의 `protocol` 이 코어의 계약 버전을 받는지 |
39
+ | `stateId(plugins)`, `canonicalState(plugins)`, `checkState(plugins)` | 플러그인 구성의 상태 id 계산과 목록의 모양 검사 |
40
+ | `isPluginId`, `idOwner`, `isVersion`, `isPrerelease`, `isRange`, `isProtocolRange`, `isStateId` | 모양 확인 |
41
+ | `bundleFileName`, `bundlePathAllowed`, `sha256Hex` | 묶음 파일 이름, 묶음에 들어갈 수 있는 경로인지, sha256 |
42
+ | `BUNDLE_MAX_BYTES`, `BUNDLE_MAX_FILES`, `MAX_DEPENDENCIES`, `STATE_MAX_PLUGINS`, `RESERVED_IDS` | 한도와 쓰지 못하는 id |
43
+ | `checkMessageTable(data)` | 외부 연결의 메시지 표(`aic-link-messages/1`) 파일의 바이트를 검사한다. 맞으면 `{ ok: true, table }`, 틀리면 `{ ok: false, problems }` |
44
+ | `renderMessage(table, id, values)` | 표에 등록한 메시지 id 와 값을 글로 푼다. 등록하지 않은 id, 값이 틀린 것, 모양이 틀린 id 는 글을 만들지 않고 까닭(`unknown_id`, `bad_values`, `malformed_id`)을 돌려준다 |
45
+ | `isMessageId`, `MESSAGE_TABLE_FORMAT`, `MESSAGE_TABLE_MAX_BYTES`, `MESSAGE_TABLE_MAX_MESSAGES`, `MESSAGE_TEXT_MAX` | 메시지 표의 모양 확인과 한도 |
46
+ | `docsProblem(manifest, files)` | manifest 의 `manual`(설명서)과 `samples`(예제)가 가리키는 파일이 있는지, 한도와 모양이 맞는지 본다. `readBundle` 이 함께 부른다 |
47
+ | `bundleNotices(manifest)` | 거절하지 않고 알리기만 하는 것. 지금은 설명서가 없을 때 한 줄이다 |
48
+ | `checkSample(value)`, `parseSample(data)`, `parseManual(data)` | 예제 파일(`aic-sample/1`)의 모양 검사, 예제와 설명서 파일의 글자 한도와 UTF-8 검사 |
49
+ | `sampleNarrative(sample, { installed?, self? })`, `samplePluginLines`, `missingPlugins` | 예제를 revision 마다 사람의 말, AI 가 한 일, 화면 변화의 차례 글로 옮기고, 설치되지 않은 플러그인을 알린다 |
50
+ | `SAMPLE_FORMAT`, `MANUAL_MAX_CHARS`, `SAMPLE_MAX_CHARS`, `MAX_SAMPLES`, `SAMPLE_WHO` | 예제 형식의 이름, 설명서 50,000자, 예제 하나 200,000자, 예제 다섯 개, 참여자 표기("사람", "AI", "코어") |
51
+
52
+ ## 버전
53
+
54
+ 검사 규칙을 바꾸면 이 패키지의 버전을 올리고, 등록 사이트가 그 버전을 따라 올립니다. 0 으로 시작하는 동안은 가운데 숫자가 바뀌면 규칙이 호환되지 않게 바뀐 것입니다.
55
+
56
+ ## 라이선스
57
+
58
+ Apache-2.0
@@ -0,0 +1,58 @@
1
+ import { type Manifest } from './manifest.ts';
2
+ /** 묶음 파일의 크기 한도와 풀린 파일 크기 합의 한도(036 12절 3번). */
3
+ export declare const BUNDLE_MAX_BYTES: number;
4
+ /** 묶음 안 파일 수의 한도. */
5
+ export declare const BUNDLE_MAX_FILES = 200;
6
+ export interface Bundle {
7
+ manifest: Manifest;
8
+ /** 경로마다 파일 내용. 경로는 `/` 로 나눈 상대 경로다. */
9
+ files: Map<string, Buffer>;
10
+ /** 묶음 파일 전체의 sha256(16진 소문자). */
11
+ sha256: string;
12
+ /** 묶음 파일의 바이트 수. */
13
+ size: number;
14
+ }
15
+ export type BundleErrorCode = 'too_large' | 'bad_bundle' | 'bad_manifest';
16
+ /** 묶음이 규칙에 맞지 않을 때 던진다. code 는 등록 사이트의 오류 코드와 같다. */
17
+ export declare class BundleError extends Error {
18
+ readonly code: BundleErrorCode;
19
+ constructor(code: BundleErrorCode, message: string);
20
+ }
21
+ /** 묶음 파일의 이름. 예: rawdev.novel-0.3.0.tgz */
22
+ export declare function bundleFileName(id: string, version: string): string;
23
+ export declare function sha256Hex(data: Uint8Array | string): string;
24
+ /**
25
+ * 이 경로의 파일이 묶음에 들어갈 수 있는가(036 3절). manifest, 논리 파일, ui/ 의 파일, LICENSE, README.md, 그리고 manifest 가 가리키는
26
+ * 설명서와 예제 파일(037 5.1절)뿐이다.
27
+ */
28
+ export declare function bundlePathAllowed(p: string, manifest: Pick<Manifest, 'logic' | 'manual' | 'samples'>): boolean;
29
+ /**
30
+ * 설명서와 예제 파일의 검사(037 5절, 7절 4번). manifest 가 가리키는 파일이 묶음에 있어야 하고, 설명서는 50,000자, 예제는 하나에
31
+ * 200,000자까지다. 예제는 aic-sample/1 모양이어야 하고 쓴 플러그인에 이 플러그인이 있어야 한다. 틀리면 까닭이고 없으면 null 이다.
32
+ */
33
+ export declare function docsProblem(manifest: Pick<Manifest, 'id' | 'manual' | 'samples'>, files: ReadonlyMap<string, Uint8Array>): string | null;
34
+ /**
35
+ * 묶음에 대한 알림. 거절하지 않고 알리기만 한다. 지금은 설명서가 없을 때 한 줄이다(037 7절 3번: 등록 사이트는 설명서를 권하되
36
+ * 요구하지 않는다).
37
+ */
38
+ export declare function bundleNotices(manifest: Pick<Manifest, 'manual'>): string[];
39
+ /**
40
+ * 파일 목록으로 `.tgz` 를 만든다. 경로의 글자 순서(UTF-16 코드 단위)로 늘어놓고 시각, 권한, 소유자를 고정하므로 같은 node 에서
41
+ * 같은 입력이면 같은 바이트가 나온다. 경로가 플러그인 폴더 안의 상대 경로가 아니면 던진다. manifest 의 검사는 하지 않는다.
42
+ */
43
+ export declare function packBundle(files: Map<string, Uint8Array | string> | Record<string, Uint8Array | string>): Buffer;
44
+ /**
45
+ * `.tgz` 를 풀어 036 3절의 규칙을 확인한다. 묶음 크기, 풀린 크기, 파일 수, 묶음 밖 경로, 보통 파일이 아닌 항목(링크 같은 것),
46
+ * 같은 경로 둘, 들어갈 수 없는 파일, manifest 검사, 논리 파일과 화면 파일이 있는지, 설명서와 예제 파일(docsProblem)을 본다. 틀리면
47
+ * 까닭이 든 BundleError 를 던진다.
48
+ * 풀린 크기는 gzip 을 풀면서 한도로 막으므로 아주 크게 부풀리는 묶음도 메모리에 다 풀지 않는다.
49
+ */
50
+ export declare function readBundle(buffer: Uint8Array): Bundle;
51
+ /**
52
+ * 등록 사이트에 올릴 때 묶음에 더 요구하는 것. manifest 의 칸(checkForRegistry)과 LICENSE 파일이다. 문제가 없으면 null 이고, 있으면
53
+ * 등록 사이트의 오류 코드(manifest 의 칸이면 bad_manifest, 파일이면 bad_bundle)와 까닭이다.
54
+ */
55
+ export declare function checkBundleForRegistry(bundle: Bundle): {
56
+ code: 'bad_manifest' | 'bad_bundle';
57
+ message: string;
58
+ } | null;
package/dist/bundle.js ADDED
@@ -0,0 +1,303 @@
1
+ // 플러그인 묶음 파일(036 3절). `.tgz`(gzip 으로 줄인 ustar) 하나에 플러그인 한 버전이 든다. 파일은 경로 앞에 폴더를 붙이지 않고
2
+ // 플러그인 폴더의 상대 경로 그대로 넣는다. node 내장 모듈만 쓴다.
3
+ import { createHash } from 'node:crypto';
4
+ import zlib from 'node:zlib';
5
+ import { checkForRegistry, checkManifest, isFileName, isPluginPath } from "./manifest.js";
6
+ import { parseManual, parseSample } from "./sample.js";
7
+ /** 묶음 파일의 크기 한도와 풀린 파일 크기 합의 한도(036 12절 3번). */
8
+ export const BUNDLE_MAX_BYTES = 5 * 1024 * 1024;
9
+ /** 묶음 안 파일 수의 한도. */
10
+ export const BUNDLE_MAX_FILES = 200;
11
+ /** 묶음이 규칙에 맞지 않을 때 던진다. code 는 등록 사이트의 오류 코드와 같다. */
12
+ export class BundleError extends Error {
13
+ code;
14
+ constructor(code, message) {
15
+ super(message);
16
+ this.name = 'BundleError';
17
+ this.code = code;
18
+ }
19
+ }
20
+ /** 묶음 파일의 이름. 예: rawdev.novel-0.3.0.tgz */
21
+ export function bundleFileName(id, version) {
22
+ return `${id}-${version}.tgz`;
23
+ }
24
+ export function sha256Hex(data) {
25
+ return createHash('sha256').update(data).digest('hex');
26
+ }
27
+ /**
28
+ * 이 경로의 파일이 묶음에 들어갈 수 있는가(036 3절). manifest, 논리 파일, ui/ 의 파일, LICENSE, README.md, 그리고 manifest 가 가리키는
29
+ * 설명서와 예제 파일(037 5.1절)뿐이다.
30
+ */
31
+ export function bundlePathAllowed(p, manifest) {
32
+ if (p === 'manifest.json' || p === 'LICENSE' || p === 'README.md' || p === manifest.logic)
33
+ return true;
34
+ if (p === manifest.manual || (manifest.samples ?? []).some((s) => s.file === p))
35
+ return true;
36
+ return p.startsWith('ui/') && isFileName(p.slice(3));
37
+ }
38
+ /**
39
+ * 설명서와 예제 파일의 검사(037 5절, 7절 4번). manifest 가 가리키는 파일이 묶음에 있어야 하고, 설명서는 50,000자, 예제는 하나에
40
+ * 200,000자까지다. 예제는 aic-sample/1 모양이어야 하고 쓴 플러그인에 이 플러그인이 있어야 한다. 틀리면 까닭이고 없으면 null 이다.
41
+ */
42
+ export function docsProblem(manifest, files) {
43
+ if (manifest.manual !== undefined) {
44
+ const data = files.get(manifest.manual);
45
+ if (!data)
46
+ return `설명서 파일 ${manifest.manual} 이 없다`;
47
+ const read = parseManual(data);
48
+ if (!read.ok)
49
+ return `${manifest.manual}: ${read.problem}`;
50
+ }
51
+ for (const s of manifest.samples ?? []) {
52
+ const data = files.get(s.file);
53
+ if (!data)
54
+ return `예제 ${s.id} 의 파일 ${s.file} 이 없다`;
55
+ const read = parseSample(data);
56
+ if (!read.ok)
57
+ return `예제 ${s.id}(${s.file}): ${read.problem}`;
58
+ if (!read.sample.plugins.some((p) => p.package === manifest.id))
59
+ return `예제 ${s.id}(${s.file}) 의 plugins 에 이 플러그인 ${manifest.id} 이 없다. 이 플러그인을 쓴 작업을 내보낸다`;
60
+ }
61
+ return null;
62
+ }
63
+ /**
64
+ * 묶음에 대한 알림. 거절하지 않고 알리기만 한다. 지금은 설명서가 없을 때 한 줄이다(037 7절 3번: 등록 사이트는 설명서를 권하되
65
+ * 요구하지 않는다).
66
+ */
67
+ export function bundleNotices(manifest) {
68
+ return manifest.manual === undefined ? ['설명서(manifest 의 manual)가 없다. 등록 사이트는 설명서를 권한다. 없어도 올라간다'] : [];
69
+ }
70
+ // ---- ustar ----
71
+ const BLOCK = 512;
72
+ /** gzip 머리말. 시각 0, 운영체제 "모름"(255)으로 두어 어느 컴퓨터에서 만들어도 머리말이 같게 한다. */
73
+ const GZIP_HEADER = Buffer.from([0x1f, 0x8b, 0x08, 0x00, 0, 0, 0, 0, 0x00, 0xff]);
74
+ function octal(value, width) {
75
+ return value.toString(8).padStart(width - 1, '0') + '\0';
76
+ }
77
+ function writeString(buf, offset, width, s) {
78
+ const bytes = Buffer.from(s, 'utf8');
79
+ if (bytes.length > width)
80
+ throw new BundleError('bad_bundle', `묶음 안의 이름이 너무 길다: ${s}`);
81
+ bytes.copy(buf, offset);
82
+ }
83
+ /** 이름이 100바이트를 넘으면 ustar 의 prefix(155바이트)로 나눈다. */
84
+ function splitName(p) {
85
+ if (Buffer.byteLength(p) <= 100)
86
+ return { name: p, prefix: '' };
87
+ for (let i = p.lastIndexOf('/'); i > 0; i = p.lastIndexOf('/', i - 1)) {
88
+ const prefix = p.slice(0, i);
89
+ const name = p.slice(i + 1);
90
+ if (Buffer.byteLength(prefix) <= 155 && Buffer.byteLength(name) <= 100)
91
+ return { name, prefix };
92
+ }
93
+ throw new BundleError('bad_bundle', `묶음 안의 경로가 너무 길다: ${p}`);
94
+ }
95
+ function header(p, size) {
96
+ const h = Buffer.alloc(BLOCK);
97
+ const { name, prefix } = splitName(p);
98
+ writeString(h, 0, 100, name);
99
+ writeString(h, 100, 8, octal(0o644, 8));
100
+ writeString(h, 108, 8, octal(0, 8));
101
+ writeString(h, 116, 8, octal(0, 8));
102
+ writeString(h, 124, 12, octal(size, 12));
103
+ writeString(h, 136, 12, octal(0, 12));
104
+ h.fill(0x20, 148, 156);
105
+ h[156] = 0x30; // '0' 보통 파일
106
+ writeString(h, 257, 6, 'ustar\0');
107
+ writeString(h, 263, 2, '00');
108
+ writeString(h, 345, 155, prefix);
109
+ let sum = 0;
110
+ for (const b of h)
111
+ sum += b;
112
+ writeString(h, 148, 8, sum.toString(8).padStart(6, '0') + '\0 ');
113
+ return h;
114
+ }
115
+ /**
116
+ * 파일 목록으로 `.tgz` 를 만든다. 경로의 글자 순서(UTF-16 코드 단위)로 늘어놓고 시각, 권한, 소유자를 고정하므로 같은 node 에서
117
+ * 같은 입력이면 같은 바이트가 나온다. 경로가 플러그인 폴더 안의 상대 경로가 아니면 던진다. manifest 의 검사는 하지 않는다.
118
+ */
119
+ export function packBundle(files) {
120
+ const entries = (files instanceof Map ? [...files.entries()] : Object.entries(files)).map(([p, data]) => [p, typeof data === 'string' ? Buffer.from(data, 'utf8') : Buffer.from(data)]);
121
+ entries.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
122
+ const parts = [];
123
+ const seen = new Set();
124
+ for (const [p, data] of entries) {
125
+ if (!isPluginPath(p))
126
+ throw new BundleError('bad_bundle', `묶음에 넣을 수 없는 경로다: ${JSON.stringify(p)}`);
127
+ if (seen.has(p))
128
+ throw new BundleError('bad_bundle', `같은 경로가 둘이다: ${p}`);
129
+ seen.add(p);
130
+ parts.push(header(p, data.length), data);
131
+ const pad = (BLOCK - (data.length % BLOCK)) % BLOCK;
132
+ if (pad)
133
+ parts.push(Buffer.alloc(pad));
134
+ }
135
+ parts.push(Buffer.alloc(BLOCK * 2));
136
+ const tar = Buffer.concat(parts);
137
+ const body = zlib.deflateRawSync(tar, { level: 9 });
138
+ const trailer = Buffer.alloc(8);
139
+ trailer.writeUInt32LE(zlib.crc32(tar) >>> 0, 0);
140
+ trailer.writeUInt32LE(tar.length % 0x100000000, 4);
141
+ return Buffer.concat([GZIP_HEADER, body, trailer]);
142
+ }
143
+ function readString(buf, offset, width) {
144
+ const slice = buf.subarray(offset, offset + width);
145
+ const end = slice.indexOf(0);
146
+ return slice.subarray(0, end === -1 ? width : end).toString('utf8');
147
+ }
148
+ function readOctal(buf, offset, width, what) {
149
+ if (buf[offset] & 0x80)
150
+ throw new BundleError('bad_bundle', `묶음의 ${what} 를 읽지 못했다(256진 표기는 받지 않는다)`);
151
+ const s = readString(buf, offset, width).trim();
152
+ if (s === '')
153
+ return 0;
154
+ if (!/^[0-7]+$/.test(s))
155
+ throw new BundleError('bad_bundle', `묶음의 ${what} 가 8진 숫자가 아니다`);
156
+ return parseInt(s, 8);
157
+ }
158
+ /** pax 머리말의 "길이 key=value\n" 기록에서 path 를 꺼낸다. */
159
+ function paxPath(data) {
160
+ let found;
161
+ let i = 0;
162
+ while (i < data.length) {
163
+ const space = data.indexOf(0x20, i);
164
+ if (space === -1)
165
+ break;
166
+ const len = Number(data.subarray(i, space).toString('ascii'));
167
+ if (!Number.isInteger(len) || len <= 0 || i + len > data.length)
168
+ throw new BundleError('bad_bundle', '묶음의 pax 머리말을 읽지 못했다');
169
+ const record = data.subarray(space + 1, i + len - 1).toString('utf8');
170
+ const eq = record.indexOf('=');
171
+ if (eq > 0 && record.slice(0, eq) === 'path')
172
+ found = record.slice(eq + 1);
173
+ i += len;
174
+ }
175
+ return found;
176
+ }
177
+ /** 묶음 안 경로를 고르게 한다. 앞의 `./` 를 떼고, 폴더 항목의 끝 `/` 를 뗀다. 묶음 밖을 가리키거나 모양이 틀리면 던진다. */
178
+ function cleanPath(raw, dir) {
179
+ let p = raw;
180
+ while (p.startsWith('./'))
181
+ p = p.slice(2);
182
+ if (dir)
183
+ p = p.replace(/\/+$/, '');
184
+ if (dir && (p === '' || p === '.'))
185
+ return '';
186
+ if (!isPluginPath(p))
187
+ throw new BundleError('bad_bundle', `묶음 안의 경로가 플러그인 폴더 안의 상대 경로가 아니다: ${JSON.stringify(raw)}`);
188
+ return p;
189
+ }
190
+ /**
191
+ * `.tgz` 를 풀어 036 3절의 규칙을 확인한다. 묶음 크기, 풀린 크기, 파일 수, 묶음 밖 경로, 보통 파일이 아닌 항목(링크 같은 것),
192
+ * 같은 경로 둘, 들어갈 수 없는 파일, manifest 검사, 논리 파일과 화면 파일이 있는지, 설명서와 예제 파일(docsProblem)을 본다. 틀리면
193
+ * 까닭이 든 BundleError 를 던진다.
194
+ * 풀린 크기는 gzip 을 풀면서 한도로 막으므로 아주 크게 부풀리는 묶음도 메모리에 다 풀지 않는다.
195
+ */
196
+ export function readBundle(buffer) {
197
+ const buf = Buffer.from(buffer.buffer, buffer.byteOffset, buffer.byteLength);
198
+ if (buf.length > BUNDLE_MAX_BYTES)
199
+ throw new BundleError('too_large', `묶음이 ${BUNDLE_MAX_BYTES} 바이트를 넘는다(${buf.length} 바이트)`);
200
+ // 파일 내용의 합은 BUNDLE_MAX_BYTES 까지이고, 머리말과 채움은 파일마다 1,024 바이트를 넘지 않는다
201
+ const maxTar = BUNDLE_MAX_BYTES + (BUNDLE_MAX_FILES + 8) * BLOCK * 2;
202
+ let tar;
203
+ try {
204
+ tar = zlib.gunzipSync(buf, { maxOutputLength: maxTar });
205
+ }
206
+ catch (e) {
207
+ if (e instanceof RangeError || e.code === 'ERR_BUFFER_TOO_LARGE') {
208
+ throw new BundleError('too_large', `풀린 묶음이 한도(${BUNDLE_MAX_BYTES} 바이트)를 넘는다`);
209
+ }
210
+ throw new BundleError('bad_bundle', `묶음이 gzip 파일이 아니다(${e.message})`);
211
+ }
212
+ const files = new Map();
213
+ let total = 0;
214
+ let offset = 0;
215
+ let nextPath;
216
+ let ended = false;
217
+ while (offset + BLOCK <= tar.length) {
218
+ const h = tar.subarray(offset, offset + BLOCK);
219
+ if (h.every((b) => b === 0)) {
220
+ ended = true;
221
+ break;
222
+ }
223
+ let sum = 0;
224
+ for (let i = 0; i < BLOCK; i += 1)
225
+ sum += i >= 148 && i < 156 ? 0x20 : h[i];
226
+ if (readOctal(h, 148, 8, '검사합') !== sum)
227
+ throw new BundleError('bad_bundle', '묶음의 머리말 검사합이 맞지 않는다');
228
+ const size = readOctal(h, 124, 12, '파일 크기');
229
+ const type = String.fromCharCode(h[156]);
230
+ const dataStart = offset + BLOCK;
231
+ const dataEnd = dataStart + size;
232
+ if (dataEnd > tar.length)
233
+ throw new BundleError('bad_bundle', '묶음이 중간에 끊겼다');
234
+ const data = tar.subarray(dataStart, dataEnd);
235
+ offset = dataStart + Math.ceil(size / BLOCK) * BLOCK;
236
+ if (type === 'x') {
237
+ nextPath = paxPath(data) ?? nextPath;
238
+ continue;
239
+ }
240
+ if (type === 'g')
241
+ continue;
242
+ if (type === 'L') {
243
+ nextPath = readString(data, 0, data.length);
244
+ continue;
245
+ }
246
+ const prefix = readString(h, 345, 155);
247
+ const rawName = nextPath ?? (prefix ? `${prefix}/${readString(h, 0, 100)}` : readString(h, 0, 100));
248
+ nextPath = undefined;
249
+ if (type === '5') {
250
+ cleanPath(rawName, true);
251
+ continue;
252
+ }
253
+ if (type !== '0' && type !== '\0')
254
+ throw new BundleError('bad_bundle', `묶음에 보통 파일이 아닌 항목이 있다: ${rawName}`);
255
+ const p = cleanPath(rawName, false);
256
+ if (files.has(p))
257
+ throw new BundleError('bad_bundle', `묶음에 같은 경로가 둘이다: ${p}`);
258
+ if (files.size + 1 > BUNDLE_MAX_FILES)
259
+ throw new BundleError('too_large', `묶음의 파일이 ${BUNDLE_MAX_FILES}개를 넘는다`);
260
+ total += size;
261
+ if (total > BUNDLE_MAX_BYTES)
262
+ throw new BundleError('too_large', `묶음의 파일 크기 합이 ${BUNDLE_MAX_BYTES} 바이트를 넘는다`);
263
+ files.set(p, Buffer.from(data));
264
+ }
265
+ if (!ended)
266
+ throw new BundleError('bad_bundle', '묶음의 끝 표시가 없다');
267
+ const manifestFile = files.get('manifest.json');
268
+ if (!manifestFile)
269
+ throw new BundleError('bad_bundle', '묶음에 manifest.json 이 없다');
270
+ let manifest;
271
+ try {
272
+ manifest = JSON.parse(manifestFile.toString('utf8'));
273
+ }
274
+ catch (e) {
275
+ throw new BundleError('bad_manifest', `manifest.json 이 JSON 이 아니다(${e.message})`);
276
+ }
277
+ const problem = checkManifest(manifest);
278
+ if (problem)
279
+ throw new BundleError('bad_manifest', problem);
280
+ const m = manifest;
281
+ if (!files.has(m.logic))
282
+ throw new BundleError('bad_bundle', `묶음에 논리 파일 ${m.logic} 이 없다`);
283
+ if (m.ui !== undefined && !files.has(m.ui))
284
+ throw new BundleError('bad_bundle', `묶음에 화면 파일 ${m.ui} 가 없다`);
285
+ const extra = [...files.keys()].filter((p) => !bundlePathAllowed(p, m));
286
+ if (extra.length > 0) {
287
+ throw new BundleError('bad_bundle', `묶음에 넣을 수 없는 파일이 있다: ${extra.join(', ')}. manifest.json, 논리 파일, ui/ 의 파일, LICENSE, README.md, manifest 의 manual 과 samples 가 가리키는 파일만 넣는다`);
288
+ }
289
+ const docs = docsProblem(m, files);
290
+ if (docs)
291
+ throw new BundleError('bad_bundle', docs);
292
+ return { manifest: m, files, sha256: sha256Hex(buf), size: buf.length };
293
+ }
294
+ /**
295
+ * 등록 사이트에 올릴 때 묶음에 더 요구하는 것. manifest 의 칸(checkForRegistry)과 LICENSE 파일이다. 문제가 없으면 null 이고, 있으면
296
+ * 등록 사이트의 오류 코드(manifest 의 칸이면 bad_manifest, 파일이면 bad_bundle)와 까닭이다.
297
+ */
298
+ export function checkBundleForRegistry(bundle) {
299
+ const problem = checkForRegistry(bundle.manifest);
300
+ if (problem)
301
+ return { code: 'bad_manifest', message: problem };
302
+ return bundle.files.has('LICENSE') ? null : { code: 'bad_bundle', message: '사이트에 올리려면 묶음에 LICENSE 파일이 있어야 한다' };
303
+ }
@@ -0,0 +1,6 @@
1
+ export * from './version.ts';
2
+ export * from './manifest.ts';
3
+ export * from './bundle.ts';
4
+ export * from './state.ts';
5
+ export * from './messages.ts';
6
+ export * from './sample.ts';
package/dist/index.js ADDED
@@ -0,0 +1,9 @@
1
+ // aicommunicator-plugin-check(packages/manifest): 플러그인 manifest 검사, 버전 범위, 묶음 파일, 상태 id(036), 외부 연결의 메시지 표(032 31.3절),
2
+ // 설명서와 예제 파일(037 5절). 코어, aic 명령, 등록 사이트가 함께 쓴다. 다른 패키지에 기대지 않고 node 내장 모듈만 쓴다. 타입을 지우기만 하면
3
+ // 도는 TypeScript 로만 쓴다(enum, 생성자 인자 칸 없음).
4
+ export * from "./version.js";
5
+ export * from "./manifest.js";
6
+ export * from "./bundle.js";
7
+ export * from "./state.js";
8
+ export * from "./messages.js";
9
+ export * from "./sample.js";
@@ -0,0 +1,74 @@
1
+ export interface Manifest {
2
+ id: string;
3
+ version: string;
4
+ dataVersion: number;
5
+ title?: string;
6
+ license?: string;
7
+ logic: string;
8
+ ui?: string;
9
+ /** 이 화면에서 무엇을 할 수 있는지(034 2절). 1,000자까지. */
10
+ about?: string;
11
+ /** 사람이 하려는 일과 그 일을 이 화면에서 하는 방법. 다섯 개까지, 각 글 300자까지. */
12
+ examples?: PluginExample[];
13
+ /** 실행 환경(034 2.1절). 없으면 { os: "any", external: [] } 로 본다. */
14
+ requires?: PluginRequires;
15
+ /** 이 플러그인이 맞춘 코어 계약의 버전 범위(036 4절). 지금은 `0.<숫자>` 한 가지다. 없으면 검사하지 않는다. */
16
+ protocol?: string;
17
+ /** 함께 설치되어 있어야 하는 다른 플러그인과 버전 범위(036 4절). 스무 개까지. */
18
+ dependencies?: Record<string, string>;
19
+ /** 상세 사용 설명서(037 5.1절). 패키지 안의 Markdown 파일 경로. 예: docs/manual.md */
20
+ manual?: string;
21
+ /** 사용 예제(037 5.1절). 다섯 개까지. file 은 패키지 안의 aic-sample/1 파일이다. */
22
+ samples?: PluginSample[];
23
+ }
24
+ /** manifest 의 samples 항목(037 5.1절). */
25
+ export interface PluginSample {
26
+ /** 예제 id. 영어 소문자, 숫자, - 로 1자에서 40자. */
27
+ id: string;
28
+ title: string;
29
+ about: string;
30
+ file: string;
31
+ }
32
+ export interface PluginExample {
33
+ ask: string;
34
+ does: string;
35
+ }
36
+ export type OsName = 'windows' | 'macos' | 'linux';
37
+ /** 바깥 도구 하나(034 2.1절). */
38
+ export interface ExternalTool {
39
+ name: string;
40
+ kind: 'program' | 'web' | 'mcp';
41
+ account: 'none' | 'free' | 'paid';
42
+ install: boolean;
43
+ note?: string;
44
+ }
45
+ export interface PluginRequires {
46
+ os: 'any' | OsName[];
47
+ external: ExternalTool[];
48
+ }
49
+ /** 코어 안에 든 외부 연결의 패키지 이름(core 의 switch/editing.ts LINK_PACKAGE). 플러그인 id 로 받지 않는다. */
50
+ export declare const RESERVED_IDS: readonly string[];
51
+ /** dependencies 의 항목 수 한도. */
52
+ export declare const MAX_DEPENDENCIES = 20;
53
+ /** samples 의 항목 수 한도(037 7절 4번). */
54
+ export declare const MAX_SAMPLES = 5;
55
+ /** `계정이름.플러그인이름` 모양인가. 각 부분은 영어 소문자, 숫자, `-` 이고 2자에서 40자다(036 4절). */
56
+ export declare function isPluginId(id: unknown): id is string;
57
+ /** id 의 앞부분(계정 이름). */
58
+ export declare function idOwner(id: string): string;
59
+ /** 파일 이름 한 조각으로 쓸 수 있는가. `.` 과 `..` 은 폴더를 가리키므로 받지 않는다. */
60
+ export declare function isFileName(name: string): boolean;
61
+ /** 플러그인 폴더 안의 상대 경로인가. `/` 로 나눈 조각마다 파일 이름 모양이어야 한다. 절대 경로, `..`, `\` 는 받지 않는다. */
62
+ export declare function isPluginPath(p: unknown): p is string;
63
+ /** 화면 파일 경로인가. `ui/` 바로 아래의 파일 하나다. */
64
+ export declare function isUiPath(p: unknown): p is string;
65
+ /**
66
+ * manifest 의 칸 검사. 문제의 설명이고 없으면 null 이다. 소개, 예, 실행 환경, 계약 버전, 의존은 없어도 되지만 있으면 모양이
67
+ * 맞아야 한다. 조용히 자르면 등록 사이트와 코어가 다른 글을 보이게 되기 때문이다. 맨 위 층의 모르는 칸은 거절하지 않는다.
68
+ */
69
+ export declare function checkManifest(manifest: unknown): string | null;
70
+ /**
71
+ * 등록 사이트에 올릴 때의 검사. checkManifest 를 지나고, 사이트의 목록과 AI 의 추천을 만드는 칸(protocol, license, title, about)이
72
+ * 있어야 한다(036 4절). 묶음에 LICENSE 파일이 있는지는 checkBundleForRegistry 가 본다.
73
+ */
74
+ export declare function checkForRegistry(manifest: unknown): string | null;