@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,511 @@
1
+ import { z } from 'zod';
2
+ import { imageRenderOptions, renderedImage, } from './images.js';
3
+ import { graphSchema, positionSchema } from '@nesso-how/schema';
4
+ import { parseOrThrow, PluginError, pluginErrorCodes } from './errors.js';
5
+ import { parseDefinition, themeColors, vocabRelationType } from './definitions.js';
6
+ import { fileOpenOptions, fileOpenResult, fileSaveOptions, } from './files.js';
7
+ import { createWriteCommands } from '@nesso-how/core';
8
+ import { localizedText, text } from './i18n.js';
9
+ import { checkMessageSize } from './data.js';
10
+ import { pluginStorageKey, pluginStorageRecord, pluginStorageRevision, pluginStorageSnapshot, } from './storage.js';
11
+ export { checkMessageSize } from './data.js';
12
+ export { parsePluginStorageKey, parsePluginStorageRecord, parsePluginStorageSnapshot, pluginStorageLimits, } from './storage.js';
13
+ export { resolvePluginText } from './i18n.js';
14
+ export { fontFaces } from './theme-fonts.js';
15
+ export { parseOrThrow, PluginError } from './errors.js';
16
+ export { parseDefinition, themeColors } from './definitions.js';
17
+ export { parseFileOptions, fileTextLimit, } from './files.js';
18
+ export const runtimeLimits = {
19
+ request: 32 * 1024 * 1024,
20
+ snapshot: 64 * 1024 * 1024,
21
+ pending: 64,
22
+ deadline: 30_000,
23
+ interaction: 300_000,
24
+ initialization: 10_000,
25
+ action: 120_000,
26
+ heartbeat: 15_000,
27
+ };
28
+ export const badgeLimits = {
29
+ value: 999_999,
30
+ execution: 2_000,
31
+ refresh: 15_000,
32
+ rate: 1_000,
33
+ };
34
+ const actionBadgeResult = z.strictObject({
35
+ value: z.number().int().min(0).max(badgeLimits.value).nullable(),
36
+ refreshAt: z.number().int().min(0).max(8_640_000_000_000_000).optional(),
37
+ });
38
+ export const parseActionBadgeResult = (value) => parseOrThrow(actionBadgeResult, value);
39
+ export const themeTokens = [
40
+ ...themeColors,
41
+ 'font-sans',
42
+ 'font-mono',
43
+ 'radius-control',
44
+ 'radius-object',
45
+ 'duration-state',
46
+ ];
47
+ const id = z.string().min(1).max(2048);
48
+ const position = positionSchema;
49
+ const selection = z.array(z.strictObject({ kind: z.enum(['concept', 'relation']), id }));
50
+ const relationType = z.strictObject({ id, label: z.string() });
51
+ const locale = z.enum(['en', 'it', 'zh-CN']);
52
+ const operation = z.discriminatedUnion('kind', [
53
+ z.strictObject({ kind: z.literal('concept.label'), id, value: z.string() }),
54
+ z.strictObject({ kind: z.literal('concept.notes'), id, value: z.string() }),
55
+ z.strictObject({ kind: z.literal('concept.color'), id, value: z.string() }),
56
+ z.strictObject({ kind: z.literal('concept.bold'), id, value: z.boolean() }),
57
+ z.strictObject({ kind: z.literal('concept.italic'), id, value: z.boolean() }),
58
+ z.strictObject({ kind: z.literal('concept.position'), id, value: position }),
59
+ z.strictObject({
60
+ kind: z.literal('concept.positions'),
61
+ updates: z.array(z.strictObject({ id, position })),
62
+ }),
63
+ z.strictObject({ kind: z.literal('concept.add'), id, position: position.optional() }),
64
+ z.strictObject({ kind: z.literal('concept.remove'), id }),
65
+ z.strictObject({
66
+ kind: z.literal('relation.connect'),
67
+ source: id,
68
+ target: id,
69
+ type: relationType.optional(),
70
+ }),
71
+ z.strictObject({ kind: z.literal('relation.reconnect'), id, source: id, target: id }),
72
+ z.strictObject({ kind: z.literal('relation.type'), id, typeId: id }),
73
+ z.strictObject({ kind: z.literal('relation.type.create'), id, typeId: id, label: z.string() }),
74
+ z.strictObject({ kind: z.literal('relation.remove'), id }),
75
+ z.strictObject({ kind: z.literal('document.reset'), id }),
76
+ z.strictObject({ kind: z.literal('history.undo') }),
77
+ z.strictObject({ kind: z.literal('history.redo') }),
78
+ z.strictObject({ kind: z.literal('selection.set'), value: selection }),
79
+ z.strictObject({ kind: z.literal('view.activate'), id: id.nullable() }),
80
+ z.strictObject({ kind: z.literal('view.create'), id, name: z.string(), conceptIds: z.array(id) }),
81
+ z.strictObject({ kind: z.literal('view.rename'), id, name: z.string() }),
82
+ z.strictObject({ kind: z.literal('view.pin'), id, pinned: z.boolean() }),
83
+ z.strictObject({
84
+ kind: z.literal('view.membership'),
85
+ viewId: id,
86
+ conceptId: id,
87
+ included: z.boolean(),
88
+ }),
89
+ z.strictObject({ kind: z.literal('view.remove'), id }),
90
+ ...['vocab', 'theme'].map((kind) => z.strictObject({ kind: z.literal(`preferences.${kind}`), id })),
91
+ z.strictObject({ kind: z.literal('preferences.locale'), value: locale }),
92
+ z.strictObject({
93
+ kind: z.literal('preferences.panels'),
94
+ value: z.strictObject({ explorerWidth: z.number(), inspectorWidth: z.number() }),
95
+ }),
96
+ z.strictObject({
97
+ kind: z.literal('preferences.section'),
98
+ id: z.enum([
99
+ 'sidebar',
100
+ 'sidebar.pinned-views',
101
+ 'sidebar.views',
102
+ 'inspector',
103
+ 'inspector.connections',
104
+ 'inspector.views',
105
+ 'inspector.nodes',
106
+ ]),
107
+ open: z.boolean(),
108
+ }),
109
+ ]);
110
+ const options = z.strictObject({ historyGroup: id.optional() });
111
+ const metadata = z.strictObject({
112
+ name: localizedText(128),
113
+ description: localizedText(2048),
114
+ documentation: localizedText(16_384),
115
+ });
116
+ const pluginI18n = z.object({ metadata }).catchall(localizedText(16_384));
117
+ export function parsePluginI18n(value) {
118
+ checkMessageSize(value, 64 * 1024);
119
+ return parseOrThrow(pluginI18n, value, 'i18n.');
120
+ }
121
+ const manifestFields = {
122
+ apiVersion: z.literal(2),
123
+ };
124
+ const jsEntry = z
125
+ .string()
126
+ .max(240)
127
+ .regex(/^(?:[\w-]+\/)*[\w-]+\.js$/);
128
+ const jsonEntry = z
129
+ .string()
130
+ .max(240)
131
+ .regex(/^(?:[\w-]+\/)*[\w-]+\.json$/);
132
+ const pluginWriteKinds = [
133
+ 'concept.label',
134
+ 'concept.notes',
135
+ 'concept.color',
136
+ 'concept.bold',
137
+ 'concept.italic',
138
+ 'concept.position',
139
+ 'concept.positions',
140
+ 'concept.add',
141
+ 'concept.remove',
142
+ 'relation.connect',
143
+ 'relation.reconnect',
144
+ 'relation.type',
145
+ 'relation.type.create',
146
+ 'relation.remove',
147
+ 'selection.set',
148
+ 'view.membership',
149
+ ];
150
+ const operationDeclarations = z.array(z.enum(pluginWriteKinds));
151
+ const manifest = z
152
+ .discriminatedUnion('kind', [
153
+ z.strictObject({
154
+ ...manifestFields,
155
+ kind: z.literal('actions'),
156
+ entry: jsEntry,
157
+ writes: operationDeclarations,
158
+ capabilities: z.array(z.enum(['files', 'images', 'notifications', 'storage', 'ui'])),
159
+ }),
160
+ ...['theme', 'vocab'].map((kind) => z.strictObject({
161
+ ...manifestFields,
162
+ kind: z.literal(kind),
163
+ entry: jsonEntry,
164
+ writes: z.tuple([]),
165
+ capabilities: z.tuple([]),
166
+ })),
167
+ ])
168
+ .refine((value) => new Set(value.writes).size === value.writes.length &&
169
+ new Set(value.capabilities).size === value.capabilities.length, 'Declarations must be unique');
170
+ export function parsePluginManifest(value) {
171
+ checkMessageSize(value, 64 * 1024);
172
+ return parseOrThrow(manifest, value);
173
+ }
174
+ const envelope = { type: z.literal('request'), id: z.number().int().positive(), contextId: id };
175
+ const request = z.discriminatedUnion('method', [
176
+ z.strictObject({
177
+ ...envelope,
178
+ method: z.literal('document.applyOperations'),
179
+ params: z.strictObject({
180
+ operations: z.array(operation).max(50_000),
181
+ revision: z.number().int().nonnegative(),
182
+ options: options.optional(),
183
+ }),
184
+ }),
185
+ z.strictObject({
186
+ ...envelope,
187
+ method: z.literal('document.refresh'),
188
+ params: z.strictObject({}),
189
+ }),
190
+ z.strictObject({ ...envelope, method: z.literal('storage.list'), params: z.strictObject({}) }),
191
+ z.strictObject({
192
+ ...envelope,
193
+ method: z.literal('storage.set'),
194
+ params: pluginStorageRecord.extend({ revision: pluginStorageRevision }),
195
+ }),
196
+ z.strictObject({
197
+ ...envelope,
198
+ method: z.literal('storage.delete'),
199
+ params: pluginStorageKey.extend({ revision: pluginStorageRevision }),
200
+ }),
201
+ z.strictObject({
202
+ ...envelope,
203
+ method: z.literal('notifications.notify'),
204
+ params: z.strictObject({
205
+ tone: z.enum(['info', 'warning']),
206
+ title: localizedText(256),
207
+ description: localizedText(4096).optional(),
208
+ }),
209
+ }),
210
+ z.strictObject({ ...envelope, method: z.literal('files.open'), params: fileOpenOptions }),
211
+ z.strictObject({ ...envelope, method: z.literal('files.save'), params: fileSaveOptions }),
212
+ z.strictObject({
213
+ ...envelope,
214
+ method: z.literal('images.renderView'),
215
+ params: imageRenderOptions,
216
+ }),
217
+ ]);
218
+ const wireError = z.strictObject({
219
+ code: z.enum(pluginErrorCodes),
220
+ issues: z
221
+ .array(z.strictObject({ path: text(256), message: text(2048) }))
222
+ .min(1)
223
+ .max(32),
224
+ displayMessage: localizedText(2048).optional(),
225
+ });
226
+ const message = z.union([
227
+ request,
228
+ z.strictObject({ type: z.literal('panel-ready') }),
229
+ z.strictObject({ type: z.literal('pong'), id: z.number().int().positive() }),
230
+ z.strictObject({ type: z.literal('contribution'), value: z.unknown() }),
231
+ z.strictObject({ type: z.literal('badge-result'), value: actionBadgeResult }),
232
+ z.strictObject({ type: z.literal('close'), reason: z.string().max(2048) }),
233
+ z.strictObject({ type: z.literal('complete'), ok: z.literal(true) }),
234
+ z.strictObject({ type: z.literal('complete'), ok: z.literal(false), error: wireError }),
235
+ ]);
236
+ const actionDescriptor = z.strictObject({
237
+ id: z
238
+ .string()
239
+ .max(64)
240
+ .regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/),
241
+ label: localizedText(128),
242
+ icon: z
243
+ .string()
244
+ .min(1)
245
+ .max(32)
246
+ .regex(/^[a-z]+(?:-[a-z]+)*$/)
247
+ .optional(),
248
+ ui: z.literal(true).optional(),
249
+ badge: z.literal(true).optional(),
250
+ });
251
+ export const actionIconNames = [
252
+ 'arrow-right',
253
+ 'book-open',
254
+ 'clipboard-paste',
255
+ 'copy',
256
+ 'download',
257
+ 'file-down',
258
+ 'file-up',
259
+ 'folder',
260
+ 'glasses',
261
+ 'globe',
262
+ 'layers',
263
+ 'pencil',
264
+ 'play',
265
+ 'plus',
266
+ 'refresh',
267
+ 'repeat',
268
+ 'scissors',
269
+ 'search',
270
+ 'share',
271
+ 'sparkles',
272
+ 'upload',
273
+ 'zap',
274
+ ];
275
+ const actionDescriptors = z
276
+ .array(actionDescriptor)
277
+ .min(1)
278
+ .max(64)
279
+ .refine((value) => new Set(value.map(({ id }) => id)).size === value.length, 'Action IDs must be unique');
280
+ export function parseContribution(kind, value) {
281
+ checkMessageSize(value, 1024 * 1024);
282
+ if (kind === 'theme' || kind === 'vocab')
283
+ return parseDefinition(kind, value);
284
+ return parseOrThrow(actionDescriptors, value);
285
+ }
286
+ const actionStateSchema = z.strictObject({
287
+ revision: z.number().int().nonnegative(),
288
+ contextId: id,
289
+ locale,
290
+ theme: z.strictObject(Object.fromEntries(themeTokens.map((token) => [
291
+ token,
292
+ z
293
+ .string()
294
+ .max(512)
295
+ .regex(/^[#\w\s.,()%/"'-]*$/),
296
+ ]))),
297
+ conceptPlacementOffset: position,
298
+ viewGraph: graphSchema,
299
+ selected: selection,
300
+ targetViewId: id.nullable(),
301
+ activeVocab: z
302
+ .strictObject({ id, relationTypes: z.array(vocabRelationType), defaultTypeId: id })
303
+ .nullable(),
304
+ history: z.strictObject({ canUndo: z.boolean(), canRedo: z.boolean() }),
305
+ workspace: z.strictObject({
306
+ activeViewId: id.nullable(),
307
+ savedViews: z.array(z.strictObject({ id, name: z.string(), pinned: z.boolean() })),
308
+ }),
309
+ });
310
+ const reply = z.union([
311
+ z.strictObject({ type: z.literal('ping'), id: z.number().int().positive() }),
312
+ z.strictObject({ type: z.literal('state'), state: actionStateSchema }),
313
+ z.strictObject({
314
+ type: z.literal('response'),
315
+ id: z.number().int().positive(),
316
+ ok: z.literal(true),
317
+ value: z.unknown(),
318
+ }),
319
+ z.strictObject({
320
+ type: z.literal('response'),
321
+ id: z.number().int().positive(),
322
+ ok: z.literal(false),
323
+ error: wireError,
324
+ }),
325
+ z.strictObject({ type: z.literal('close'), reason: z.string().max(2048) }),
326
+ ]);
327
+ const results = {
328
+ 'document.applyOperations': z.strictObject({
329
+ revision: z.number().int().nonnegative(),
330
+ changed: z.boolean(),
331
+ }),
332
+ 'document.refresh': z.null(),
333
+ 'storage.list': pluginStorageSnapshot,
334
+ 'storage.set': z.strictObject({ revision: pluginStorageRevision, changed: z.boolean() }),
335
+ 'storage.delete': z.strictObject({ revision: pluginStorageRevision, changed: z.boolean() }),
336
+ 'notifications.notify': id,
337
+ 'files.open': fileOpenResult,
338
+ 'files.save': z.strictObject({ saved: z.boolean() }),
339
+ 'images.renderView': renderedImage,
340
+ };
341
+ export function parsePluginMessage(value) {
342
+ checkMessageSize(value, runtimeLimits.request);
343
+ return parseOrThrow(message, value);
344
+ }
345
+ export async function sha256Hex(bytes) {
346
+ const digest = await crypto.subtle.digest('SHA-256', new Uint8Array(bytes));
347
+ return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, '0')).join('');
348
+ }
349
+ export function createPluginClient(port, initial) {
350
+ let state = parseOrThrow(actionStateSchema, initial);
351
+ let readRevision = state.revision;
352
+ let storageRevision;
353
+ let sequence = 0;
354
+ const listeners = new Set();
355
+ const controller = new AbortController();
356
+ const pending = new Map();
357
+ const close = () => {
358
+ if (controller.signal.aborted)
359
+ return;
360
+ controller.abort();
361
+ for (const request of pending.values()) {
362
+ clearTimeout(request.timer);
363
+ request.reject(new PluginError('closed', [
364
+ {
365
+ path: 'channel',
366
+ message: 'Plugin channel closed; pending effects may already have completed',
367
+ },
368
+ ]));
369
+ }
370
+ pending.clear();
371
+ listeners.clear();
372
+ port.postMessage({ type: 'close', reason: 'Plugin client closed' });
373
+ port.close();
374
+ };
375
+ const call = async (method, params) => {
376
+ if (controller.signal.aborted)
377
+ return Promise.reject(new PluginError('closed', [{ path: 'channel', message: 'Plugin channel closed' }]));
378
+ if (pending.size >= runtimeLimits.pending)
379
+ return Promise.reject(new PluginError('failed', [{ path: 'channel', message: 'Too many pending requests' }]));
380
+ const id = ++sequence;
381
+ const value = { type: 'request', id, contextId: state.contextId, method, params };
382
+ parsePluginMessage(value);
383
+ return new Promise((resolve, reject) => {
384
+ const timer = setTimeout(close, method.startsWith('files.') ? runtimeLimits.interaction : runtimeLimits.deadline);
385
+ pending.set(id, { method, resolve: (value) => resolve(value), reject, timer });
386
+ port.postMessage(value);
387
+ });
388
+ };
389
+ port.onmessage = ({ data: value, ports }) => {
390
+ if (controller.signal.aborted)
391
+ return;
392
+ if (ports.length) {
393
+ close();
394
+ return;
395
+ }
396
+ const parsed = reply.safeParse(value);
397
+ if (!parsed.success) {
398
+ console.error(new PluginError('invalid-input', parsed.error.issues.map((issue) => ({
399
+ path: issue.path.join('.'),
400
+ message: issue.message,
401
+ }))).message);
402
+ close();
403
+ return;
404
+ }
405
+ const data = parsed.data;
406
+ if (data.type === 'ping') {
407
+ port.postMessage({ type: 'pong', id: data.id });
408
+ return;
409
+ }
410
+ if (data.type === 'close') {
411
+ close();
412
+ return;
413
+ }
414
+ if (data.type === 'state' && data.state.revision > state.revision) {
415
+ state = data.state;
416
+ for (const listener of listeners) {
417
+ try {
418
+ listener();
419
+ }
420
+ catch {
421
+ console.error(new PluginError('failed', [
422
+ { path: 'subscriber', message: 'Plugin state subscriber failed' },
423
+ ]));
424
+ }
425
+ }
426
+ }
427
+ if (data.type !== 'response')
428
+ return;
429
+ const request = pending.get(data.id);
430
+ if (!request)
431
+ return;
432
+ if (data.ok && !results[request.method].safeParse(data.value).success) {
433
+ close();
434
+ return;
435
+ }
436
+ pending.delete(data.id);
437
+ clearTimeout(request.timer);
438
+ if (data.ok)
439
+ request.resolve(data.value);
440
+ else
441
+ request.reject(new PluginError(data.error.code, data.error.issues, data.error.displayMessage));
442
+ };
443
+ port.onmessageerror = close;
444
+ port.start();
445
+ const getState = () => {
446
+ readRevision = state.revision;
447
+ return state;
448
+ };
449
+ const applyOperations = async (operations, options) => {
450
+ const result = await call('document.applyOperations', { operations, revision: readRevision, ...(options ? { options } : {}) });
451
+ readRevision = Math.max(readRevision, result.revision);
452
+ return result;
453
+ };
454
+ const { undo: _undo, redo: _redo, setView: _view, setActiveVocab: _vocab, setActiveTheme: _theme, setLocale: _locale, setPanelSizes: _panels, setSectionOpen: _section, createView: _createView, renameView: _renameView, setViewPinned: _pin, deleteView: _deleteView, ...writes } = createWriteCommands(async (operations, options) => {
455
+ await applyOperations(operations, options);
456
+ }, async (id, committed) => {
457
+ await committed;
458
+ return id;
459
+ });
460
+ const listStorage = async () => {
461
+ const snapshot = await call('storage.list', {});
462
+ storageRevision = Math.max(storageRevision ?? 0, snapshot.revision);
463
+ return snapshot.records;
464
+ };
465
+ const mutateStorage = async (method, params) => {
466
+ if (storageRevision === undefined)
467
+ await listStorage();
468
+ const result = await call(method, {
469
+ ...params,
470
+ revision: storageRevision,
471
+ });
472
+ storageRevision = Math.max(storageRevision ?? 0, result.revision);
473
+ return result.changed;
474
+ };
475
+ const context = {
476
+ viewId: state.targetViewId,
477
+ document: {
478
+ ...writes,
479
+ getState,
480
+ subscribe: (listener) => {
481
+ listeners.add(listener);
482
+ return () => listeners.delete(listener);
483
+ },
484
+ refresh: async () => {
485
+ await call('document.refresh', {});
486
+ return getState();
487
+ },
488
+ applyOperations,
489
+ },
490
+ notifications: { notify: (value) => call('notifications.notify', value) },
491
+ images: { renderView: (options) => call('images.renderView', options) },
492
+ files: {
493
+ open: (options) => call('files.open', options),
494
+ save: (options) => call('files.save', options),
495
+ },
496
+ storage: {
497
+ list: listStorage,
498
+ set: (key, value, scope) => mutateStorage('storage.set', scope === undefined ? { key, value } : { key, value, scope }),
499
+ delete: (key, scope) => mutateStorage('storage.delete', scope === undefined ? { key } : { key, scope }),
500
+ },
501
+ signal: controller.signal,
502
+ };
503
+ return {
504
+ context,
505
+ close,
506
+ getPresentation: () => ({
507
+ theme: state.theme,
508
+ locale: state.locale,
509
+ }),
510
+ };
511
+ }
@@ -0,0 +1,72 @@
1
+ import { z } from 'zod';
2
+ import type { DeepReadonly } from '@nesso-how/core';
3
+ export declare const pluginStorageLimits: {
4
+ readonly record: number;
5
+ readonly namespace: number;
6
+ readonly total: number;
7
+ readonly records: 10000;
8
+ readonly namespaces: 128;
9
+ readonly depth: 24;
10
+ };
11
+ type JsonValue = null | string | number | boolean | readonly JsonValue[] | {
12
+ readonly [key: string]: JsonValue;
13
+ };
14
+ declare const pluginStorageScope: z.ZodDiscriminatedUnion<[z.ZodObject<{
15
+ kind: z.ZodLiteral<"concept">;
16
+ id: z.ZodString;
17
+ }, z.core.$strict>, z.ZodObject<{
18
+ kind: z.ZodLiteral<"view">;
19
+ id: z.ZodString;
20
+ }, z.core.$strict>], "kind">;
21
+ export declare const pluginStorageKey: z.ZodObject<{
22
+ key: z.ZodString;
23
+ scope: z.ZodOptional<z.ZodDiscriminatedUnion<[z.ZodObject<{
24
+ kind: z.ZodLiteral<"concept">;
25
+ id: z.ZodString;
26
+ }, z.core.$strict>, z.ZodObject<{
27
+ kind: z.ZodLiteral<"view">;
28
+ id: z.ZodString;
29
+ }, z.core.$strict>], "kind">>;
30
+ }, z.core.$strict>;
31
+ export declare const pluginStorageRecord: z.ZodObject<{
32
+ key: z.ZodString;
33
+ scope: z.ZodOptional<z.ZodDiscriminatedUnion<[z.ZodObject<{
34
+ kind: z.ZodLiteral<"concept">;
35
+ id: z.ZodString;
36
+ }, z.core.$strict>, z.ZodObject<{
37
+ kind: z.ZodLiteral<"view">;
38
+ id: z.ZodString;
39
+ }, z.core.$strict>], "kind">>;
40
+ value: z.ZodPipe<z.ZodCustom<JsonValue, JsonValue>, z.ZodTransform<string | number | boolean | readonly JsonValue[] | {
41
+ readonly [key: string]: JsonValue;
42
+ } | null, JsonValue>>;
43
+ }, z.core.$strict>;
44
+ export declare const pluginStorageRevision: z.ZodNumber;
45
+ export declare const pluginStorageSnapshot: z.ZodObject<{
46
+ revision: z.ZodNumber;
47
+ records: z.ZodArray<z.ZodObject<{
48
+ key: z.ZodString;
49
+ scope: z.ZodOptional<z.ZodDiscriminatedUnion<[z.ZodObject<{
50
+ kind: z.ZodLiteral<"concept">;
51
+ id: z.ZodString;
52
+ }, z.core.$strict>, z.ZodObject<{
53
+ kind: z.ZodLiteral<"view">;
54
+ id: z.ZodString;
55
+ }, z.core.$strict>], "kind">>;
56
+ value: z.ZodPipe<z.ZodCustom<JsonValue, JsonValue>, z.ZodTransform<string | number | boolean | readonly JsonValue[] | {
57
+ readonly [key: string]: JsonValue;
58
+ } | null, JsonValue>>;
59
+ }, z.core.$strict>>;
60
+ }, z.core.$strict>;
61
+ export type PluginStorageRecord = DeepReadonly<z.infer<typeof pluginStorageRecord>>;
62
+ export type PluginStorageKey = DeepReadonly<z.infer<typeof pluginStorageKey>>;
63
+ export type PluginStorageScope = DeepReadonly<z.infer<typeof pluginStorageScope>>;
64
+ export type PluginStorage = {
65
+ readonly list: () => Promise<readonly PluginStorageRecord[]>;
66
+ readonly set: (key: string, value: PluginStorageRecord['value'], scope?: PluginStorageScope) => Promise<boolean>;
67
+ readonly delete: (key: string, scope?: PluginStorageScope) => Promise<boolean>;
68
+ };
69
+ export declare function parsePluginStorageSnapshot(value: unknown): DeepReadonly<z.infer<typeof pluginStorageSnapshot>>;
70
+ export declare function parsePluginStorageRecord(value: unknown): PluginStorageRecord;
71
+ export declare function parsePluginStorageKey(value: unknown): PluginStorageKey;
72
+ export {};
@@ -0,0 +1,71 @@
1
+ import { z } from 'zod';
2
+ import { checkMessageSize } from './data.js';
3
+ import { parseOrThrow, PluginError } from './errors.js';
4
+ export const pluginStorageLimits = {
5
+ record: 256 * 1024,
6
+ namespace: 8 * 1024 * 1024,
7
+ total: 64 * 1024 * 1024,
8
+ records: 10_000,
9
+ namespaces: 128,
10
+ depth: 24,
11
+ };
12
+ const isJsonValue = (value, depth = 0) => {
13
+ if (depth > pluginStorageLimits.depth)
14
+ return false;
15
+ if (value === null || typeof value === 'string' || typeof value === 'boolean')
16
+ return true;
17
+ if (typeof value === 'number')
18
+ return Number.isFinite(value);
19
+ if (typeof value !== 'object')
20
+ return false;
21
+ if (Array.isArray(value))
22
+ return (Reflect.ownKeys(value).length === value.length + 1 &&
23
+ Array.from(value).every((item) => isJsonValue(item, depth + 1)));
24
+ return (Object.getPrototypeOf(value) === Object.prototype &&
25
+ Reflect.ownKeys(value).length === Object.keys(value).length &&
26
+ Object.values(value).every((item) => isJsonValue(item, depth + 1)));
27
+ };
28
+ const pluginStorageScope = z.discriminatedUnion('kind', [
29
+ z.strictObject({ kind: z.literal('concept'), id: z.string().max(2048) }),
30
+ z.strictObject({ kind: z.literal('view'), id: z.string().max(2048) }),
31
+ ]);
32
+ const fields = {
33
+ key: z.string().min(1).max(128),
34
+ scope: pluginStorageScope.optional(),
35
+ };
36
+ export const pluginStorageKey = z.strictObject(fields);
37
+ export const pluginStorageRecord = z
38
+ .strictObject({
39
+ ...fields,
40
+ value: z
41
+ .custom((value) => isJsonValue(value), 'Expected a bounded JSON value')
42
+ .transform((value) => structuredClone(value)),
43
+ })
44
+ .superRefine((value, context) => {
45
+ try {
46
+ checkMessageSize(value, pluginStorageLimits.record, pluginStorageLimits.depth);
47
+ }
48
+ catch (error) {
49
+ context.addIssue({
50
+ code: 'custom',
51
+ message: error instanceof PluginError ? error.message : 'Invalid storage record',
52
+ });
53
+ }
54
+ });
55
+ export const pluginStorageRevision = z.number().int().nonnegative();
56
+ export const pluginStorageSnapshot = z.strictObject({
57
+ revision: pluginStorageRevision,
58
+ records: z.array(pluginStorageRecord).max(pluginStorageLimits.records),
59
+ });
60
+ export function parsePluginStorageSnapshot(value) {
61
+ checkMessageSize(value, pluginStorageLimits.namespace);
62
+ return parseOrThrow(pluginStorageSnapshot, value);
63
+ }
64
+ export function parsePluginStorageRecord(value) {
65
+ checkMessageSize(value, pluginStorageLimits.record, pluginStorageLimits.depth);
66
+ return parseOrThrow(pluginStorageRecord, value);
67
+ }
68
+ export function parsePluginStorageKey(value) {
69
+ checkMessageSize(value, 4096);
70
+ return parseOrThrow(pluginStorageKey, value);
71
+ }
@@ -0,0 +1,2 @@
1
+ import type { ThemeDefinition } from './definitions.ts';
2
+ export declare const fontFaces: (ranges: Record<string, string>, stem: string, weight: [number, number]) => ThemeDefinition['fonts']['sans'];
@@ -0,0 +1,11 @@
1
+ export const fontFaces = (ranges, stem, weight) => ({
2
+ faces: Object.entries(ranges).map(([subset, intervals]) => ({
3
+ path: `fonts/${stem.replace('{subset}', subset)}.woff2`,
4
+ weight,
5
+ style: 'normal',
6
+ unicodeRange: intervals.split(',').map((interval) => {
7
+ const [from, to = from] = interval.slice(2).split('-');
8
+ return [parseInt(from, 16), parseInt(to, 16)];
9
+ }),
10
+ })),
11
+ });
package/dist/package.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { o as PluginI18n, s as PluginManifest } from "./runtime-D4jO7tbm.js";
1
+ import { c as PluginI18n, l as PluginManifest } from "./runtime-DGDBGkWs.js";
2
2
  //#region src/package.d.ts
3
3
  export declare const packageLimits: {
4
4
  readonly entry: number;
package/dist/package.js CHANGED
@@ -1,4 +1,4 @@
1
- import { S as parseOrThrow, a as parsePluginManifest, c as sha256Hex, i as parsePluginI18n, m as checkMessageSize, v as parseDefinition, x as PluginError } from "./runtime-CJPU4o4h.js";
1
+ import { C as PluginError, _ as checkMessageSize, o as parsePluginI18n, s as parsePluginManifest, u as sha256Hex, w as parseOrThrow, y as parseDefinition } from "./runtime-D6GosMdU.js";
2
2
  import { z } from "zod";
3
3
  import parseVersion from "semver/functions/parse.js";
4
4
  import validateName from "validate-npm-package-name";