@appstrate/validation 1.0.2 → 1.1.1

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/README.md CHANGED
@@ -1 +1,165 @@
1
- # validation
1
+ # @appstrate/validation
2
+
3
+ Shared validation library for the Appstrate ecosystem. Provides manifest schemas (Zod), package ZIP parsing, naming helpers, dependency extraction, and integrity hashing — used by both the [Appstrate platform](https://github.com/appstrate/strate) and the [Appstrate [registry]](https://github.com/appstrate/registry).
4
+
5
+ ## Installation
6
+
7
+ ```sh
8
+ # From npm
9
+ bun add @appstrate/validation
10
+ ```
11
+
12
+ ## Exports
13
+
14
+ The package exposes five entry points:
15
+
16
+ | Import path | Description |
17
+ | ------------------------------------ | ----------------------------------------------------- |
18
+ | `@appstrate/validation` | Manifest schemas, validators, skill/extension helpers |
19
+ | `@appstrate/validation/zip` | ZIP parsing, artifact creation, package extraction |
20
+ | `@appstrate/validation/naming` | Scoped name helpers, slug regex, packageId conversion |
21
+ | `@appstrate/validation/dependencies` | Registry dependency extraction from manifests |
22
+ | `@appstrate/validation/integrity` | SHA256 integrity hash computation |
23
+
24
+ ## Usage
25
+
26
+ ### Manifest Validation
27
+
28
+ ```ts
29
+ import { validateManifest, baseManifestSchema, flowManifestSchema } from "@appstrate/validation";
30
+
31
+ // Validate any manifest (auto-dispatches by type)
32
+ const result = validateManifest(rawJson);
33
+ if (result.valid) {
34
+ console.log(result.manifest); // typed BaseManifest | FlowManifest
35
+ } else {
36
+ console.error(result.errors); // string[]
37
+ }
38
+ ```
39
+
40
+ Three manifest schemas are available:
41
+
42
+ - **`baseManifestSchema`** — Common fields for all types: `name` (`@scope/package-name`), `version` (semver), `type` (`flow` | `skill` | `extension`), optional `description`, `keywords`, `license`, `registryDependencies`
43
+ - **`flowManifestSchema`** — Extends base with flow-specific fields: `schemaVersion`, `displayName`, `author`, `requires` (services, skills, extensions), `input`/`output`/`config` schemas, `execution` options
44
+ - **`localFlowManifestSchema`** — Relaxed schema for strate built-in flows (slug name instead of scoped, optional version)
45
+
46
+ ### Skill & Extension Validation
47
+
48
+ ```ts
49
+ import { extractSkillMeta, validateExtensionSource } from "@appstrate/validation";
50
+
51
+ // Extract YAML frontmatter from SKILL.md
52
+ const meta = extractSkillMeta(skillMdContent);
53
+ // { name: "my-skill", description: "...", warnings: [] }
54
+
55
+ // Validate TypeScript extension source
56
+ const result = validateExtensionSource(tsSource);
57
+ // { valid: true, errors: [], warnings: [] }
58
+ ```
59
+
60
+ ### ZIP Parsing
61
+
62
+ ```ts
63
+ import { parsePackageZip, PackageZipError } from "@appstrate/validation/zip";
64
+
65
+ try {
66
+ const parsed = parsePackageZip(zipBuffer);
67
+ // { manifest, content, files, type }
68
+ } catch (err) {
69
+ if (err instanceof PackageZipError) {
70
+ console.error(err.code, err.message);
71
+ // Codes: FILE_TOO_LARGE, ZIP_INVALID, ZIP_BOMB, MISSING_MANIFEST,
72
+ // INVALID_MANIFEST, MISSING_CONTENT, INVALID_CONTENT
73
+ }
74
+ }
75
+ ```
76
+
77
+ Lower-level ZIP utilities:
78
+
79
+ - **`zipArtifact(entries, level?)`** — Create a ZIP from file entries
80
+ - **`unzipArtifact(buffer)`** — Decompress with path sanitization (filters `..`, `__MACOSX`, absolute paths)
81
+ - **`detectFolderWrapper(entries)`** — Detect single-folder wrapping in ZIP
82
+
83
+ ### Naming Helpers
84
+
85
+ ```ts
86
+ import {
87
+ SLUG_REGEX,
88
+ normalizeScope,
89
+ stripScope,
90
+ scopedNameToPackageId,
91
+ packageIdToScopedName,
92
+ depEntryToPackageId,
93
+ } from "@appstrate/validation/naming";
94
+
95
+ normalizeScope("myscope"); // "@myscope"
96
+ stripScope("@myscope"); // "myscope"
97
+ scopedNameToPackageId("@scope/name"); // "scope--name"
98
+ packageIdToScopedName("scope--name"); // "@scope/name"
99
+ packageIdToScopedName("local-slug"); // null
100
+ depEntryToPackageId("@scope", "name"); // "scope--name"
101
+ ```
102
+
103
+ ### Dependency Extraction
104
+
105
+ ```ts
106
+ import { extractDependencies } from "@appstrate/validation/dependencies";
107
+ import type { DepEntry } from "@appstrate/validation/dependencies";
108
+
109
+ const deps: DepEntry[] = extractDependencies(manifest);
110
+ // [{ depScope: "@scope", depName: "tool", depType: "skill", versionRange: "^1.0.0" }]
111
+ ```
112
+
113
+ ### Integrity
114
+
115
+ ```ts
116
+ import { computeIntegrity } from "@appstrate/validation/integrity";
117
+
118
+ const sri = computeIntegrity(zipBuffer);
119
+ // "sha256-abc123..."
120
+ ```
121
+
122
+ ## Project Structure
123
+
124
+ ```
125
+ @appstrate/validation/
126
+ ├── src/
127
+ │ ├── index.ts # Manifest schemas (Zod), validateManifest, extractSkillMeta, validateExtensionSource
128
+ │ ├── zip.ts # ZIP parse/create, parsePackageZip, PackageZipError
129
+ │ ├── naming.ts # SLUG_REGEX, normalizeScope, stripScope, scopedNameToPackageId, packageIdToScopedName
130
+ │ ├── dependencies.ts # extractDependencies, DepEntry type
131
+ │ └── integrity.ts # computeIntegrity (SHA256 SRI hash)
132
+
133
+ ├── tests/ # bun:test (63 tests across 5 files)
134
+ │ ├── index.test.ts # Manifest validation (flow, skill, extension, base)
135
+ │ ├── zip.test.ts # ZIP parsing, folder detection, error codes, security
136
+ │ ├── naming.test.ts # Naming helpers, packageId conversion
137
+ │ ├── dependencies.test.ts # Dependency extraction from manifests
138
+ │ └── integrity.test.ts # SHA256 integrity computation
139
+
140
+ ├── package.json
141
+ ├── tsconfig.json
142
+ └── eslint.config.js
143
+ ```
144
+
145
+ ## Development
146
+
147
+ ```sh
148
+ bun test # Run all tests (63 tests, 5 files)
149
+ bun run check # TypeScript type-check + ESLint + Prettier
150
+ bun run lint # ESLint only
151
+ bun run format # Prettier format
152
+ ```
153
+
154
+ ## Tech Stack
155
+
156
+ - **Runtime**: Bun
157
+ - **Validation**: Zod 4
158
+ - **Semver**: semver (range validation, version parsing)
159
+ - **ZIP**: fflate (compression/decompression)
160
+ - **Testing**: bun:test (built-in)
161
+ - **Code quality**: ESLint + Prettier + TypeScript strict mode
162
+
163
+ ## License
164
+
165
+ MIT
package/package.json CHANGED
@@ -1,8 +1,10 @@
1
1
  {
2
2
  "name": "@appstrate/validation",
3
- "version": "1.0.2",
3
+ "version": "1.1.1",
4
4
  "type": "module",
5
- "files": ["src"],
5
+ "files": [
6
+ "src"
7
+ ],
6
8
  "exports": {
7
9
  ".": "./src/index.ts",
8
10
  "./zip": "./src/zip.ts",
@@ -33,9 +33,11 @@ export function extractDependencies(manifest: Record<string, unknown>): DepEntry
33
33
  }
34
34
 
35
35
  function parseScopedName(fullName: string): { scope: string; name: string } {
36
- const match = fullName.match(/^(@[a-z0-9-]+)\/([a-z0-9-]+)$/);
36
+ const match = fullName.match(
37
+ /^(@[a-z0-9]([a-z0-9-]*[a-z0-9])?)\/([a-z0-9]([a-z0-9-]*[a-z0-9])?)$/,
38
+ );
37
39
  if (!match) {
38
40
  throw new Error(`Invalid scoped package name: ${fullName}`);
39
41
  }
40
- return { scope: match[1]!, name: match[2]! };
42
+ return { scope: match[1]!, name: match[3]! };
41
43
  }
package/src/index.ts CHANGED
@@ -6,7 +6,7 @@ export { SLUG_REGEX };
6
6
 
7
7
  const flowFieldTypeEnum = z.enum(["string", "number", "boolean", "array", "object", "file"]);
8
8
 
9
- const jsonSchemaPropertySchema = z.object({
9
+ export const jsonSchemaPropertySchema = z.object({
10
10
  type: flowFieldTypeEnum,
11
11
  description: z.string().optional(),
12
12
  default: z.unknown().optional(),
@@ -19,24 +19,25 @@ const jsonSchemaPropertySchema = z.object({
19
19
  maxFiles: z.number().int().positive().optional(),
20
20
  });
21
21
 
22
- const jsonSchemaObjectSchema = z.object({
22
+ export const jsonSchemaObjectSchema = z.object({
23
23
  type: z.literal("object"),
24
24
  properties: z.record(z.string(), jsonSchemaPropertySchema),
25
25
  required: z.array(z.string()).optional(),
26
26
  propertyOrder: z.array(z.string()).optional(),
27
27
  });
28
28
 
29
- const serviceRequirementSchema = z.object({
29
+ export const serviceRequirementSchema = z.object({
30
30
  id: z.string().min(1).regex(SLUG_REGEX, {
31
- error: "Doit etre un slug valide (a-z, 0-9, tirets, pas de tiret en debut/fin)",
31
+ error: "Must be a valid slug (a-z, 0-9, hyphens, no leading/trailing hyphen)",
32
32
  }),
33
33
  provider: z.string(),
34
+ description: z.string().optional(),
34
35
  scopes: z.array(z.string()).optional().default([]),
35
36
  connectionMode: z.enum(["user", "admin"]).optional().default("user"),
36
37
  });
37
38
 
38
39
  const slugString = z.string().min(1).regex(SLUG_REGEX, {
39
- error: "Doit etre un slug valide (a-z, 0-9, tirets, pas de tiret en debut/fin)",
40
+ error: "Must be a valid slug (a-z, 0-9, hyphens, no leading/trailing hyphen)",
40
41
  });
41
42
 
42
43
  const semverRangeString = z.string().refine((val) => semver.validRange(val) !== null, {
@@ -54,8 +55,9 @@ const registryDependenciesSchema = z
54
55
  // Base manifest schema — common fields for all package types
55
56
  // ─────────────────────────────────────────────
56
57
 
57
- const scopedNameRegex = /^@[a-z0-9]([a-z0-9-]*[a-z0-9])?\/[a-z0-9]([a-z0-9-]*[a-z0-9])?$/;
58
- const packageTypeEnum = z.enum(["flow", "skill", "extension"]);
58
+ export const scopedNameRegex = /^@[a-z0-9]([a-z0-9-]*[a-z0-9])?\/[a-z0-9]([a-z0-9-]*[a-z0-9])?$/;
59
+ export const packageTypeEnum = z.enum(["flow", "skill", "extension"]);
60
+ export type PackageType = z.infer<typeof packageTypeEnum>;
59
61
 
60
62
  export const baseManifestSchema = z.object({
61
63
  name: z.string().regex(scopedNameRegex, { error: "Must follow the format @scope/package-name" }),
@@ -73,6 +75,12 @@ export const baseManifestSchema = z.object({
73
75
 
74
76
  export type BaseManifest = z.infer<typeof baseManifestSchema>;
75
77
 
78
+ // ─── Sub-schema inferred types ───────────────
79
+
80
+ export type FlowServiceRequirement = z.infer<typeof serviceRequirementSchema>;
81
+ export type FlowJsonSchemaProperty = z.infer<typeof jsonSchemaPropertySchema>;
82
+ export type FlowJsonSchemaObject = z.infer<typeof jsonSchemaObjectSchema>;
83
+
76
84
  // ─────────────────────────────────────────────
77
85
  // Shared flow fields — used by both flowManifestSchema and localFlowManifestSchema
78
86
  // ─────────────────────────────────────────────
@@ -121,10 +129,6 @@ export const flowManifestSchema = baseManifestSchema.extend({
121
129
 
122
130
  export type FlowManifest = z.infer<typeof flowManifestSchema>;
123
131
 
124
- // Keep backward compat — the old manifestSchema was used for flow validation only
125
- export const manifestSchema = flowManifestSchema;
126
- export type ManifestSchema = FlowManifest;
127
-
128
132
  // ─────────────────────────────────────────────
129
133
  // Unified validateManifest — dispatches by type
130
134
  // ─────────────────────────────────────────────
@@ -184,7 +188,7 @@ export function extractSkillMeta(content: string): {
184
188
  const warnings: string[] = [];
185
189
  const fmMatch = content.match(/^---\s*\n([\s\S]*?)\n---/);
186
190
  if (!fmMatch) {
187
- warnings.push("Pas de frontmatter YAML detecte (bloc --- ... --- attendu)");
191
+ warnings.push("No YAML frontmatter detected (expected --- ... --- block)");
188
192
  return { name: "", description: "", warnings };
189
193
  }
190
194
 
@@ -196,10 +200,10 @@ export function extractSkillMeta(content: string): {
196
200
  const description = descMatch ? stripQuotes(descMatch[1]!) : "";
197
201
 
198
202
  if (!name) {
199
- warnings.push("Champ 'name' manquant dans le frontmatter YAML");
203
+ warnings.push("Missing 'name' field in YAML frontmatter");
200
204
  }
201
205
  if (!description) {
202
- warnings.push("Champ 'description' manquant dans le frontmatter YAML");
206
+ warnings.push("Missing 'description' field in YAML frontmatter");
203
207
  }
204
208
 
205
209
  return { name, description, warnings };
@@ -267,20 +271,19 @@ export function validateExtensionSource(source: string): ExtensionValidationResu
267
271
  const warnings: string[] = [];
268
272
 
269
273
  if (source.trim().length === 0) {
270
- return { valid: false, errors: ["Le contenu de l'extension est vide"], warnings };
274
+ return { valid: false, errors: ["Extension content is empty"], warnings };
271
275
  }
272
276
 
273
277
  if (!/export\s+default\b/.test(source)) {
274
278
  errors.push(
275
- "L'extension doit avoir un `export default function`. " +
276
- "Exemple : export default function(pi: ExtensionAPI) { ... }",
279
+ "Extension must have an `export default function`. " +
280
+ "Example: export default function(pi: ExtensionAPI) { ... }",
277
281
  );
278
282
  }
279
283
 
280
284
  if (!/\.registerTool\s*\(/.test(source)) {
281
285
  warnings.push(
282
- "L'extension n'appelle pas `pi.registerTool()`. " +
283
- "Assurez-vous d'enregistrer au moins un outil.",
286
+ "Extension does not call `pi.registerTool()`. " + "Make sure to register at least one tool.",
284
287
  );
285
288
  }
286
289
 
@@ -291,10 +294,10 @@ export function validateExtensionSource(source: string): ExtensionValidationResu
291
294
  const paramCount = countParams(paramStr);
292
295
  if (paramCount === 1) {
293
296
  errors.push(
294
- "La signature `execute` n'a qu'un seul parametre. " +
295
- "Le Pi SDK appelle execute(toolCallId, params, signal) — avec un seul parametre, " +
296
- "votre fonction recevra le toolCallId (string) au lieu des params. " +
297
- "Corrigez : execute(_toolCallId, params, signal) { ... }",
297
+ "The `execute` signature has only one parameter. " +
298
+ "The Pi SDK calls execute(toolCallId, params, signal) — with a single parameter, " +
299
+ "your function will receive the toolCallId (string) instead of params. " +
300
+ "Fix: execute(_toolCallId, params, signal) { ... }",
298
301
  );
299
302
  break;
300
303
  }
@@ -302,8 +305,8 @@ export function validateExtensionSource(source: string): ExtensionValidationResu
302
305
 
303
306
  if (executeMatches.length > 0 && !/content\s*:/.test(cleaned)) {
304
307
  warnings.push(
305
- "La fonction `execute` ne semble pas retourner `{ content: [...] }`. " +
306
- 'Le format attendu est : { content: [{ type: "text", text: "..." }] }',
308
+ "The `execute` function does not seem to return `{ content: [...] }`. " +
309
+ 'Expected format: { content: [{ type: "text", text: "..." }] }',
307
310
  );
308
311
  }
309
312
 
@@ -313,9 +316,7 @@ export function validateExtensionSource(source: string): ExtensionValidationResu
313
316
  else if (ch === "}") braceCount--;
314
317
  }
315
318
  if (braceCount !== 0) {
316
- errors.push(
317
- `Erreur de syntaxe probable : les accolades ne sont pas equilibrees (difference: ${braceCount})`,
318
- );
319
+ errors.push(`Probable syntax error: braces are not balanced (difference: ${braceCount})`);
319
320
  }
320
321
 
321
322
  return { valid: errors.length === 0, errors, warnings };