@appstrate/validation 1.0.2 → 1.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/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,6 +1,6 @@
1
1
  {
2
2
  "name": "@appstrate/validation",
3
- "version": "1.0.2",
3
+ "version": "1.1.0",
4
4
  "type": "module",
5
5
  "files": ["src"],
6
6
  "exports": {
@@ -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,16 +19,16 @@ 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
34
  scopes: z.array(z.string()).optional().default([]),
@@ -36,7 +36,7 @@ const serviceRequirementSchema = z.object({
36
36
  });
37
37
 
38
38
  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)",
39
+ error: "Must be a valid slug (a-z, 0-9, hyphens, no leading/trailing hyphen)",
40
40
  });
41
41
 
42
42
  const semverRangeString = z.string().refine((val) => semver.validRange(val) !== null, {
@@ -54,8 +54,9 @@ const registryDependenciesSchema = z
54
54
  // Base manifest schema — common fields for all package types
55
55
  // ─────────────────────────────────────────────
56
56
 
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"]);
57
+ export const scopedNameRegex = /^@[a-z0-9]([a-z0-9-]*[a-z0-9])?\/[a-z0-9]([a-z0-9-]*[a-z0-9])?$/;
58
+ export const packageTypeEnum = z.enum(["flow", "skill", "extension"]);
59
+ export type PackageType = z.infer<typeof packageTypeEnum>;
59
60
 
60
61
  export const baseManifestSchema = z.object({
61
62
  name: z.string().regex(scopedNameRegex, { error: "Must follow the format @scope/package-name" }),
@@ -73,6 +74,12 @@ export const baseManifestSchema = z.object({
73
74
 
74
75
  export type BaseManifest = z.infer<typeof baseManifestSchema>;
75
76
 
77
+ // ─── Sub-schema inferred types ───────────────
78
+
79
+ export type FlowServiceRequirement = z.infer<typeof serviceRequirementSchema>;
80
+ export type FlowJsonSchemaProperty = z.infer<typeof jsonSchemaPropertySchema>;
81
+ export type FlowJsonSchemaObject = z.infer<typeof jsonSchemaObjectSchema>;
82
+
76
83
  // ─────────────────────────────────────────────
77
84
  // Shared flow fields — used by both flowManifestSchema and localFlowManifestSchema
78
85
  // ─────────────────────────────────────────────
@@ -121,10 +128,6 @@ export const flowManifestSchema = baseManifestSchema.extend({
121
128
 
122
129
  export type FlowManifest = z.infer<typeof flowManifestSchema>;
123
130
 
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
131
  // ─────────────────────────────────────────────
129
132
  // Unified validateManifest — dispatches by type
130
133
  // ─────────────────────────────────────────────
@@ -184,7 +187,7 @@ export function extractSkillMeta(content: string): {
184
187
  const warnings: string[] = [];
185
188
  const fmMatch = content.match(/^---\s*\n([\s\S]*?)\n---/);
186
189
  if (!fmMatch) {
187
- warnings.push("Pas de frontmatter YAML detecte (bloc --- ... --- attendu)");
190
+ warnings.push("No YAML frontmatter detected (expected --- ... --- block)");
188
191
  return { name: "", description: "", warnings };
189
192
  }
190
193
 
@@ -196,10 +199,10 @@ export function extractSkillMeta(content: string): {
196
199
  const description = descMatch ? stripQuotes(descMatch[1]!) : "";
197
200
 
198
201
  if (!name) {
199
- warnings.push("Champ 'name' manquant dans le frontmatter YAML");
202
+ warnings.push("Missing 'name' field in YAML frontmatter");
200
203
  }
201
204
  if (!description) {
202
- warnings.push("Champ 'description' manquant dans le frontmatter YAML");
205
+ warnings.push("Missing 'description' field in YAML frontmatter");
203
206
  }
204
207
 
205
208
  return { name, description, warnings };
@@ -267,20 +270,19 @@ export function validateExtensionSource(source: string): ExtensionValidationResu
267
270
  const warnings: string[] = [];
268
271
 
269
272
  if (source.trim().length === 0) {
270
- return { valid: false, errors: ["Le contenu de l'extension est vide"], warnings };
273
+ return { valid: false, errors: ["Extension content is empty"], warnings };
271
274
  }
272
275
 
273
276
  if (!/export\s+default\b/.test(source)) {
274
277
  errors.push(
275
- "L'extension doit avoir un `export default function`. " +
276
- "Exemple : export default function(pi: ExtensionAPI) { ... }",
278
+ "Extension must have an `export default function`. " +
279
+ "Example: export default function(pi: ExtensionAPI) { ... }",
277
280
  );
278
281
  }
279
282
 
280
283
  if (!/\.registerTool\s*\(/.test(source)) {
281
284
  warnings.push(
282
- "L'extension n'appelle pas `pi.registerTool()`. " +
283
- "Assurez-vous d'enregistrer au moins un outil.",
285
+ "Extension does not call `pi.registerTool()`. " + "Make sure to register at least one tool.",
284
286
  );
285
287
  }
286
288
 
@@ -291,10 +293,10 @@ export function validateExtensionSource(source: string): ExtensionValidationResu
291
293
  const paramCount = countParams(paramStr);
292
294
  if (paramCount === 1) {
293
295
  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) { ... }",
296
+ "The `execute` signature has only one parameter. " +
297
+ "The Pi SDK calls execute(toolCallId, params, signal) — with a single parameter, " +
298
+ "your function will receive the toolCallId (string) instead of params. " +
299
+ "Fix: execute(_toolCallId, params, signal) { ... }",
298
300
  );
299
301
  break;
300
302
  }
@@ -302,8 +304,8 @@ export function validateExtensionSource(source: string): ExtensionValidationResu
302
304
 
303
305
  if (executeMatches.length > 0 && !/content\s*:/.test(cleaned)) {
304
306
  warnings.push(
305
- "La fonction `execute` ne semble pas retourner `{ content: [...] }`. " +
306
- 'Le format attendu est : { content: [{ type: "text", text: "..." }] }',
307
+ "The `execute` function does not seem to return `{ content: [...] }`. " +
308
+ 'Expected format: { content: [{ type: "text", text: "..." }] }',
307
309
  );
308
310
  }
309
311
 
@@ -313,9 +315,7 @@ export function validateExtensionSource(source: string): ExtensionValidationResu
313
315
  else if (ch === "}") braceCount--;
314
316
  }
315
317
  if (braceCount !== 0) {
316
- errors.push(
317
- `Erreur de syntaxe probable : les accolades ne sont pas equilibrees (difference: ${braceCount})`,
318
- );
318
+ errors.push(`Probable syntax error: braces are not balanced (difference: ${braceCount})`);
319
319
  }
320
320
 
321
321
  return { valid: errors.length === 0, errors, warnings };