@optimizely-opal/opal-tools-sdk 0.1.5-dev → 0.1.6-dev

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,167 @@
1
+ #!/usr/bin/env ts-node
2
+ /**
3
+ * Generate Adaptive Block Document types from JSON schema.
4
+ *
5
+ * This script uses json-schema-to-typescript to generate TypeScript interfaces
6
+ * from the block-document-spec.json schema. The generated types will replace the
7
+ * manual Block builders once we're ready to switch over.
8
+ *
9
+ * Usage:
10
+ * npm run generate:block
11
+ */
12
+
13
+ import type { JSONSchema7 } from "json-schema";
14
+
15
+ import * as fs from "fs";
16
+ import { compile } from "json-schema-to-typescript";
17
+ import * as path from "path";
18
+
19
+ /**
20
+ * Generate builder functions and BlockResponse class.
21
+ *
22
+ * The generated TypeScript interfaces are great for validation, but we want to
23
+ * keep the builder API (Block.Document(), etc.) for ease of use.
24
+ */
25
+ function generateBuilderCode(schema: JSONSchema7): string {
26
+ // Extract all Block components from definitions
27
+ const blockComponents: Array<{ fullName: string; shortName: string }> = [];
28
+ const skipTypes = new Set(["BlockElement", "BlockNode"]);
29
+
30
+ if (schema.definitions) {
31
+ for (const componentName of Object.keys(schema.definitions)) {
32
+ if (componentName.startsWith("Block") && !skipTypes.has(componentName)) {
33
+ // Extract the short name (e.g., "Document" from "BlockDocument")
34
+ const shortName = componentName.substring(5); // Remove "Block" prefix
35
+ blockComponents.push({ fullName: componentName, shortName });
36
+ }
37
+ }
38
+ }
39
+
40
+ // Sort components for consistent output
41
+ blockComponents.sort((a, b) => a.shortName.localeCompare(b.shortName));
42
+
43
+ // Generate factory functions that return properly typed objects
44
+ const builderMethods = blockComponents
45
+ .map(
46
+ ({ fullName, shortName }) =>
47
+ ` ${shortName}: (props: Omit<${fullName}, '$type'>): ${fullName} => ({ $type: 'Block.${shortName}' as const, ...props }),`,
48
+ )
49
+ .join("\n");
50
+
51
+ return `
52
+ /**
53
+ * Builder namespace for Adaptive Block Document components.
54
+ *
55
+ * Usage:
56
+ * Block.Document({ children: [...] })
57
+ * Block.Heading({ children: "Title", level: "2" })
58
+ * Block.Input({ name: "field_name", placeholder: "Enter..." })
59
+ */
60
+ export const Block = {
61
+ ${builderMethods}
62
+ };
63
+
64
+ /**
65
+ * Response type for Adaptive Block Documents.
66
+ *
67
+ * A Block response is a structured tool return value with up to five optional fields:
68
+ * - content: UI representation (BlockDocument)
69
+ * - data: Extra context for LLM (optional, use only when needed beyond artifact/error)
70
+ * - artifact: Object that was impacted (optional)
71
+ * - rollback: Undo operation (optional)
72
+ * - error: Error information (optional)
73
+ */
74
+ export type BlockResponse = {
75
+ content?: BlockDocument;
76
+ data?: Record<string, unknown>;
77
+ artifact?: {
78
+ type: string;
79
+ id: string;
80
+ data: Record<string, unknown>;
81
+ };
82
+ rollback?: {
83
+ type: 'endpoint' | 'tool';
84
+ config: Record<string, unknown>;
85
+ label?: string;
86
+ };
87
+ error?: {
88
+ message: string;
89
+ code?: string;
90
+ details?: Record<string, unknown>;
91
+ };
92
+ };
93
+
94
+ /**
95
+ * Type guard to check if a value is a BlockResponse.
96
+ */
97
+ export function isBlockResponse(value: unknown): value is BlockResponse {
98
+ return (
99
+ typeof value === 'object' &&
100
+ value !== null &&
101
+ ('content' in value || 'data' in value || 'artifact' in value || 'rollback' in value || 'error' in value)
102
+ );
103
+ }
104
+ `;
105
+ }
106
+
107
+ async function main() {
108
+ // Paths
109
+ const scriptDir = __dirname;
110
+ const sdkRoot = path.join(scriptDir, "..");
111
+ const schemaFile = path.join(sdkRoot, "..", "block-document-spec.json");
112
+ const outputFile = path.join(sdkRoot, "src", "block.ts");
113
+
114
+ if (!fs.existsSync(schemaFile)) {
115
+ console.error(`Error: Schema file not found at ${schemaFile}`);
116
+ process.exit(1);
117
+ }
118
+
119
+ try {
120
+ // Read the schema
121
+ const schema = JSON.parse(fs.readFileSync(schemaFile, "utf-8"));
122
+
123
+ // Create a new schema that references all definitions to force their generation
124
+ const schemaWithExports = {
125
+ ...schema,
126
+ definitions: schema.definitions,
127
+ // Export each definition by creating a oneOf at the root
128
+ oneOf: Object.keys(schema.definitions || {})
129
+ .filter((key) => key.startsWith("Block"))
130
+ .map((key) => ({ $ref: `#/definitions/${key}` })),
131
+ };
132
+
133
+ // Generate TypeScript types
134
+ const ts = await compile(schemaWithExports, "BlockDocumentSchema", {
135
+ bannerComment: `/**
136
+ * Generated by json-schema-to-typescript
137
+ * DO NOT MODIFY - This file is auto-generated from block-document-spec.json
138
+ * Run 'npm run generate:block' to regenerate
139
+ */`,
140
+ declareExternallyReferenced: true,
141
+ strictIndexSignatures: true,
142
+ style: {
143
+ semi: true,
144
+ singleQuote: true,
145
+ },
146
+ unknownAny: false,
147
+ unreachableDefinitions: false,
148
+ });
149
+
150
+ // Post-process to add builder functions and BlockResponse
151
+ const finalContent = ts + "\n" + generateBuilderCode(schema);
152
+
153
+ // Write the output file
154
+ fs.writeFileSync(outputFile, finalContent, "utf-8");
155
+
156
+ console.log(`Generated: ${outputFile}`);
157
+ } catch (error) {
158
+ console.error("Error: Generation failed");
159
+ console.error(error);
160
+ process.exit(1);
161
+ }
162
+ }
163
+
164
+ main().catch((error) => {
165
+ console.error(error);
166
+ process.exit(1);
167
+ });
@@ -0,0 +1,7 @@
1
+ #!/bin/bash
2
+
3
+ if [[ "$*" == *"--no-fix"* ]]; then
4
+ prettier --check . && eslint . && tsc --noEmit
5
+ else
6
+ prettier --write . && eslint --fix . && tsc --noEmit
7
+ fi
package/src/auth.ts CHANGED
@@ -1,3 +1,10 @@
1
+ /* eslint-disable @typescript-eslint/no-explicit-any */
2
+ interface AuthOptions {
3
+ provider: string;
4
+ required?: boolean;
5
+ scopeBundle: string;
6
+ }
7
+
1
8
  /**
2
9
  * Middleware to handle authentication requirements
3
10
  * @param req Express request
@@ -7,46 +14,44 @@
7
14
  export function authMiddleware(req: any, res: any, next: any) {
8
15
  const authHeader = req.headers.authorization;
9
16
  if (!authHeader && req.authRequired) {
10
- return res.status(401).json({ error: 'Authentication required' });
17
+ return res.status(401).json({ error: "Authentication required" });
11
18
  }
12
-
19
+
13
20
  // The Tools Management Service will provide the appropriate token
14
21
  // in the Authorization header
15
22
  next();
16
23
  }
17
24
 
18
- interface AuthOptions {
19
- provider: string;
20
- scopeBundle: string;
21
- required?: boolean;
22
- }
23
-
24
25
  /**
25
26
  * Decorator to indicate that a tool requires authentication
26
27
  * @param options Authentication options
27
28
  */
28
29
  export function requiresAuth(options: AuthOptions) {
29
- return function(target: any, propertyKey?: string, descriptor?: PropertyDescriptor) {
30
+ return function (
31
+ target: any,
32
+ propertyKey?: string,
33
+ descriptor?: PropertyDescriptor,
34
+ ) {
30
35
  const isMethod = propertyKey && descriptor;
31
-
36
+
32
37
  if (isMethod && descriptor) {
33
38
  const originalMethod = descriptor.value;
34
-
35
- descriptor.value = function(...args: any[]) {
39
+
40
+ descriptor.value = function (...args: any[]) {
36
41
  // Store auth requirements in function metadata
37
42
  const fn = originalMethod as any;
38
43
  fn.__authRequirements__ = {
39
44
  provider: options.provider,
45
+ required: options.required ?? true,
40
46
  scopeBundle: options.scopeBundle,
41
- required: options.required ?? true
42
47
  };
43
-
48
+
44
49
  return originalMethod.apply(this, args);
45
50
  };
46
-
51
+
47
52
  return descriptor;
48
53
  }
49
-
54
+
50
55
  return target;
51
56
  };
52
57
  }