@nesso-how/plugin 0.5.0 → 0.7.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.
@@ -0,0 +1,53 @@
1
+ import { z } from 'zod';
2
+ import { parseOrThrow } from './errors.js';
3
+ export const fileTextLimit = 16 * 1024 * 1024;
4
+ const mediaType = z
5
+ .string()
6
+ .max(128)
7
+ .regex(/^[\w!#$&^.+-]+\/[\w!#$&^.+-]+$/);
8
+ export const fileOpenOptions = z.strictObject({
9
+ extensions: z
10
+ .array(z.string().regex(/^[a-zA-Z0-9]{1,16}$/))
11
+ .min(1)
12
+ .max(16),
13
+ mimeTypes: z.array(mediaType).max(16),
14
+ });
15
+ const fileFields = {
16
+ name: z
17
+ .string()
18
+ .trim()
19
+ .min(1)
20
+ .max(240)
21
+ .regex(/^[^/\\]+$/)
22
+ .refine((value) => value !== '.' &&
23
+ value !== '..' &&
24
+ [...value].every((character) => character.charCodeAt(0) >= 32 && character.charCodeAt(0) !== 127)),
25
+ mediaType,
26
+ };
27
+ const fileText = z
28
+ .string()
29
+ .max(fileTextLimit)
30
+ .refine((value) => new TextEncoder().encode(value).byteLength <= fileTextLimit, 'File text byte limit exceeded');
31
+ export const fileBase64 = z
32
+ .string()
33
+ .max(4 * Math.ceil(fileTextLimit / 3))
34
+ .regex(/^[A-Za-z0-9+/]*={0,2}$/)
35
+ .refine((value) => {
36
+ const size = (value.length / 4) * 3 - (value.endsWith('==') ? 2 : value.endsWith('=') ? 1 : 0);
37
+ try {
38
+ return value.length % 4 === 0 && size <= fileTextLimit && btoa(atob(value)) === value;
39
+ }
40
+ catch {
41
+ return false;
42
+ }
43
+ }, 'Invalid base64 or file byte limit exceeded');
44
+ export const fileSaveOptions = z.union([
45
+ z.strictObject({ ...fileFields, text: fileText }),
46
+ z.strictObject({ ...fileFields, base64: fileBase64 }),
47
+ ]);
48
+ export const fileOpenResult = z
49
+ .strictObject({ name: z.string().min(1).max(240), mediaType, text: fileText })
50
+ .nullable();
51
+ export function parseFileOptions(kind, value) {
52
+ return parseOrThrow(kind === 'open' ? fileOpenOptions : fileSaveOptions, value);
53
+ }
@@ -0,0 +1,12 @@
1
+ import { z } from 'zod';
2
+ import type { Locale } from '@nesso-how/i18n';
3
+ export type LocalizedText = Readonly<{
4
+ en: string;
5
+ } & Partial<Record<Locale, string>>>;
6
+ export declare const text: (limit: number) => z.ZodString;
7
+ export declare const localizedText: (limit: number) => z.ZodObject<{
8
+ en: z.ZodString;
9
+ it: z.ZodOptional<z.ZodString>;
10
+ 'zh-CN': z.ZodOptional<z.ZodString>;
11
+ }, z.core.$strict>;
12
+ export declare const resolvePluginText: (value: LocalizedText, locale: Locale) => string;
@@ -0,0 +1,11 @@
1
+ import { z } from 'zod';
2
+ export const text = (limit) => z
3
+ .string()
4
+ .max(limit)
5
+ .refine((value) => new TextEncoder().encode(value).byteLength <= limit, 'Text byte limit exceeded');
6
+ export const localizedText = (limit) => z.strictObject({
7
+ en: text(limit).min(1),
8
+ it: text(limit).min(1).optional(),
9
+ 'zh-CN': text(limit).min(1).optional(),
10
+ });
11
+ export const resolvePluginText = (value, locale) => value[locale] ?? value.en;
@@ -0,0 +1,11 @@
1
+ import { z } from 'zod';
2
+ export declare const imageRenderOptions: z.ZodObject<{
3
+ format: z.ZodLiteral<"png">;
4
+ scale: z.ZodOptional<z.ZodUnion<readonly [z.ZodLiteral<2>, z.ZodLiteral<4>]>>;
5
+ }, z.core.$strict>;
6
+ export declare const renderedImage: z.ZodObject<{
7
+ mediaType: z.ZodLiteral<"image/png">;
8
+ base64: z.ZodString;
9
+ }, z.core.$strict>;
10
+ export type ImageRenderOptions = Readonly<z.infer<typeof imageRenderOptions>>;
11
+ export type RenderedImage = Readonly<z.infer<typeof renderedImage>>;
@@ -0,0 +1,10 @@
1
+ import { z } from 'zod';
2
+ import { fileBase64 } from './files.js';
3
+ export const imageRenderOptions = z.strictObject({
4
+ format: z.literal('png'),
5
+ scale: z.union([z.literal(2), z.literal(4)]).optional(),
6
+ });
7
+ export const renderedImage = z.strictObject({
8
+ mediaType: z.literal('image/png'),
9
+ base64: fileBase64,
10
+ });
@@ -0,0 +1,7 @@
1
+ export type { GraphSnapshot, NessoOperation, SavedView, Selection, VocabDefinition, } from '@nesso-how/core';
2
+ export type { ThemeDefinition } from './definitions.ts';
3
+ export { PluginError } from './errors.ts';
4
+ export type { ActionContext, ActionBadgeInput, ActionBadgeResult, ActionContribution, ActionDescriptor, ActionIconName, ActionState, LocalizedText, PluginI18n, PluginManifest, } from './runtime.ts';
5
+ export { actionIconNames } from './runtime.ts';
6
+ export type { ImageRenderOptions, RenderedImage } from './images.ts';
7
+ export type { PluginStorage, PluginStorageKey, PluginStorageRecord, PluginStorageScope, } from './storage.ts';
@@ -0,0 +1,2 @@
1
+ export { PluginError } from './errors.js';
2
+ export { actionIconNames } from './runtime.js';
@@ -0,0 +1,34 @@
1
+ import { type PluginI18n, type PluginManifest } from './runtime.ts';
2
+ export declare const packageLimits: {
3
+ readonly entry: number;
4
+ readonly font: number;
5
+ readonly fonts: 32;
6
+ readonly record: number;
7
+ readonly installed: 32;
8
+ readonly total: number;
9
+ };
10
+ export type PluginPackageInput = {
11
+ readonly manifest: unknown;
12
+ readonly files: readonly {
13
+ readonly path: string;
14
+ readonly bytes: Uint8Array;
15
+ }[];
16
+ };
17
+ export type PreparedPlugin = {
18
+ readonly name: string;
19
+ readonly version: string;
20
+ readonly author?: string;
21
+ readonly repository?: string;
22
+ readonly nesso: PluginManifest;
23
+ readonly i18n: PluginI18n;
24
+ readonly code: string;
25
+ readonly fonts: readonly {
26
+ readonly path: string;
27
+ readonly data: string;
28
+ }[];
29
+ readonly contentId: string;
30
+ };
31
+ export declare function parsePackageIdentity(value: unknown): any;
32
+ export declare function preparePluginPackage(input: PluginPackageInput): Promise<PreparedPlugin>;
33
+ export declare function packageFonts(value: PreparedPlugin): ReadonlyMap<string, Uint8Array>;
34
+ export declare function verifyPluginPackage(value: PreparedPlugin): Promise<PreparedPlugin>;
@@ -0,0 +1,224 @@
1
+ import { z } from 'zod';
2
+ import parseVersion from 'semver/functions/parse.js';
3
+ import validateName from 'validate-npm-package-name';
4
+ import { checkMessageSize, parseDefinition, parsePluginI18n, parsePluginManifest, parseOrThrow, PluginError, sha256Hex, } from './runtime.js';
5
+ export const packageLimits = {
6
+ entry: 16 * 1024 * 1024,
7
+ font: 4 * 1024 * 1024,
8
+ fonts: 32,
9
+ record: 32 * 1024 * 1024,
10
+ installed: 32,
11
+ total: 128 * 1024 * 1024,
12
+ };
13
+ const author = z
14
+ .union([z.string().max(512), z.object({ name: z.string().max(128) })])
15
+ .transform((value) => (typeof value === 'string' ? value : value.name).split(/[<(]/)[0].trim())
16
+ .pipe(z
17
+ .string()
18
+ .min(1)
19
+ .max(128)
20
+ .regex(/^\P{Cc}+$/u))
21
+ .optional()
22
+ .catch(undefined);
23
+ const repository = z
24
+ .union([z.string().max(2048), z.object({ url: z.string().max(2048) })])
25
+ .transform((value) => {
26
+ const source = typeof value === 'string' ? value : value.url;
27
+ if (/[\p{Cc}\s\\]/u.test(source))
28
+ return undefined;
29
+ try {
30
+ const url = new URL(source.replace(/^git\+/, '').replace(/^github:/, 'https://github.com/'));
31
+ const pathname = url.pathname.replace(/\/$/, '').replace(/\.git$/, '');
32
+ if (url.origin !== 'https://github.com' ||
33
+ url.username ||
34
+ url.password ||
35
+ url.search ||
36
+ url.hash ||
37
+ !/^\/[a-zA-Z0-9][a-zA-Z0-9-]*\/[a-zA-Z0-9._-]+$/.test(pathname))
38
+ return undefined;
39
+ return `${url.origin}${pathname}`;
40
+ }
41
+ catch {
42
+ return undefined;
43
+ }
44
+ })
45
+ .optional()
46
+ .catch(undefined);
47
+ const identity = z.object({
48
+ name: z
49
+ .string()
50
+ .max(214)
51
+ .refine((value) => validateName(value).validForNewPackages, 'Expected a valid npm package name'),
52
+ version: z
53
+ .string()
54
+ .max(128)
55
+ .refine((value) => {
56
+ const parsed = parseVersion(value);
57
+ return (parsed !== null &&
58
+ `${parsed.version}${parsed.build.length ? `+${parsed.build.join('.')}` : ''}` === value);
59
+ }, 'Expected an exact semantic version'),
60
+ author,
61
+ repository,
62
+ nesso: z.unknown().optional(),
63
+ i18n: z.unknown().optional(),
64
+ });
65
+ const canonical = (value) => {
66
+ if (Array.isArray(value))
67
+ return `[${value.map(canonical).join(',')}]`;
68
+ if (value !== null && typeof value === 'object')
69
+ return `{${Object.entries(value)
70
+ .filter(([, item]) => item !== undefined)
71
+ .sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0))
72
+ .map(([key, item]) => `${JSON.stringify(key)}:${canonical(item)}`)
73
+ .join(',')}}`;
74
+ return JSON.stringify(value);
75
+ };
76
+ export function parsePackageIdentity(value) {
77
+ return parseOrThrow(identity, value);
78
+ }
79
+ export async function preparePluginPackage(input) {
80
+ checkMessageSize(input.manifest, 64 * 1024);
81
+ const { name, version, author, repository, nesso: declaration, i18n: translations, } = parsePackageIdentity(input.manifest);
82
+ const nesso = parsePluginManifest(declaration);
83
+ const i18n = parsePluginI18n(translations);
84
+ if (!Array.isArray(input.files) ||
85
+ !input.files.length ||
86
+ input.files.length > (nesso.kind === 'theme' ? packageLimits.fonts + 1 : 1))
87
+ throw new PluginError('invalid-input', [
88
+ { path: 'files', message: 'Expected one entry and supported local theme fonts only' },
89
+ ]);
90
+ const paths = new Set();
91
+ const fonts = [];
92
+ const files = [];
93
+ let bytes;
94
+ let admitted = 0;
95
+ for (const file of input.files) {
96
+ if (!file ||
97
+ typeof file.path !== 'string' ||
98
+ file.path.length > 240 ||
99
+ paths.has(file.path) ||
100
+ !(file.bytes instanceof Uint8Array) ||
101
+ !file.bytes.byteLength ||
102
+ file.bytes.byteLength > (file.path === nesso.entry ? packageLimits.entry : packageLimits.font))
103
+ throw new PluginError('invalid-input', [
104
+ { path: 'files', message: 'Invalid, duplicate, or oversized package file' },
105
+ ]);
106
+ paths.add(file.path);
107
+ admitted +=
108
+ file.path === nesso.entry ? file.bytes.byteLength : Math.ceil(file.bytes.byteLength / 3) * 4;
109
+ if (admitted > packageLimits.record)
110
+ throw new PluginError('invalid-input', [
111
+ { path: 'files', message: 'Package record budget exceeded' },
112
+ ]);
113
+ const content = new Uint8Array(file.bytes);
114
+ if (file.path === nesso.entry)
115
+ bytes = content;
116
+ else {
117
+ if (nesso.kind !== 'theme' ||
118
+ !/^(?:[\w-]+\/)*[\w-]+\.woff2$/.test(file.path) ||
119
+ new TextDecoder().decode(content.subarray(0, 4)) !== 'wOF2')
120
+ throw new PluginError('invalid-input', [
121
+ { path: file.path, message: 'Expected a package-local WOFF2 font' },
122
+ ]);
123
+ let binary = '';
124
+ for (let offset = 0; offset < content.length; offset += 32_768)
125
+ binary += String.fromCharCode(...content.subarray(offset, offset + 32_768));
126
+ fonts.push({ path: file.path, data: btoa(binary) });
127
+ }
128
+ files.push({ path: file.path, size: content.byteLength, sha256: await sha256Hex(content) });
129
+ }
130
+ if (!bytes)
131
+ throw new PluginError('invalid-input', [
132
+ { path: 'nesso.entry', message: 'Missing plugin entry' },
133
+ ]);
134
+ let code;
135
+ try {
136
+ code = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(bytes);
137
+ }
138
+ catch {
139
+ throw new PluginError('invalid-input', [
140
+ { path: 'files', message: 'Expected UTF-8 entry text' },
141
+ ]);
142
+ }
143
+ if (nesso.kind !== 'actions') {
144
+ let raw;
145
+ try {
146
+ raw = JSON.parse(code);
147
+ }
148
+ catch {
149
+ throw new PluginError('invalid-input', [
150
+ { path: nesso.entry, message: 'Expected a JSON definition' },
151
+ ]);
152
+ }
153
+ parseDefinition(nesso.kind, raw);
154
+ }
155
+ const order = (left, right) => left.path < right.path ? -1 : left.path > right.path ? 1 : 0;
156
+ const index = { name, version, author, repository, nesso, i18n, files: files.sort(order) };
157
+ const prepared = {
158
+ name,
159
+ version,
160
+ author,
161
+ repository,
162
+ nesso,
163
+ i18n,
164
+ code,
165
+ fonts: fonts.sort(order),
166
+ contentId: await sha256Hex(new TextEncoder().encode(canonical(index))),
167
+ };
168
+ if (new TextEncoder().encode(JSON.stringify(prepared)).byteLength > packageLimits.record)
169
+ throw new PluginError('invalid-input', [
170
+ { path: 'files', message: 'Package record budget exceeded' },
171
+ ]);
172
+ return prepared;
173
+ }
174
+ export function packageFonts(value) {
175
+ if (!Array.isArray(value.fonts) || value.fonts.length > packageLimits.fonts)
176
+ throw new PluginError('invalid-input', [
177
+ { path: 'fonts', message: 'Invalid installed font assets' },
178
+ ]);
179
+ return new Map(value.fonts.map((font) => {
180
+ if (!font ||
181
+ typeof font.path !== 'string' ||
182
+ typeof font.data !== 'string' ||
183
+ font.data.length > Math.ceil(packageLimits.font / 3) * 4)
184
+ throw new PluginError('invalid-input', [
185
+ { path: 'fonts', message: 'Invalid font encoding or budget' },
186
+ ]);
187
+ try {
188
+ return [font.path, Uint8Array.from(atob(font.data), (character) => character.charCodeAt(0))];
189
+ }
190
+ catch {
191
+ throw new PluginError('invalid-input', [
192
+ { path: 'fonts', message: 'Invalid font encoding' },
193
+ ]);
194
+ }
195
+ }));
196
+ }
197
+ export async function verifyPluginPackage(value) {
198
+ if (!value || typeof value.code !== 'string' || value.code.length > packageLimits.entry)
199
+ throw new PluginError('invalid-input', [
200
+ { path: 'package', message: 'Invalid installed plugin package' },
201
+ ]);
202
+ const fonts = packageFonts(value);
203
+ if (fonts.size !== value.fonts.length)
204
+ throw new PluginError('invalid-input', [{ path: 'fonts', message: 'Duplicate font assets' }]);
205
+ const prepared = await preparePluginPackage({
206
+ manifest: {
207
+ name: value.name,
208
+ version: value.version,
209
+ author: value.author,
210
+ repository: value.repository,
211
+ nesso: value.nesso,
212
+ i18n: value.i18n,
213
+ },
214
+ files: [
215
+ { path: value.nesso?.entry, bytes: new TextEncoder().encode(value.code) },
216
+ ...[...fonts].map(([path, bytes]) => ({ path, bytes })),
217
+ ],
218
+ });
219
+ if (prepared.contentId !== value.contentId)
220
+ throw new PluginError('denied', [
221
+ { path: 'contentId', message: 'Package content does not match its approval' },
222
+ ]);
223
+ return prepared;
224
+ }