@kubohiroya/turbowarp-named-functions 0.1.0 → 0.1.2

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.
@@ -19,15 +19,142 @@
19
19
  docsURI: "https://kubohiroya.github.io/turbowarp-named-functions/",
20
20
  blockIconURI: "data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCA0OCA0OCI+PHJlY3QgeD0iNCIgeT0iOCIgd2lkdGg9IjQwIiBoZWlnaHQ9IjMyIiByeD0iNiIgZmlsbD0iIzhBNTVENyIvPjx0ZXh0IHg9IjI0IiB5PSIzMSIgZm9udC1mYW1pbHk9Im1vbm9zcGFjZSIgZm9udC1zaXplPSIxNiIgZm9udC13ZWlnaHQ9ImJvbGQiIHRleHQtYW5jaG9yPSJtaWRkbGUiIGZpbGw9IiNmZmYiPmYoeCk8L3RleHQ+PC9zdmc+"
21
21
  };
22
+ var block_editor_fixed_inputs_schema_default = {
23
+ $schema: "https://json-schema.org/draft/2020-12/schema",
24
+ $id: "https://kubohiroya.github.io/turbowarp-named-functions/schemas/block-editor-fixed-inputs.schema.json",
25
+ $defs: { "defineFunction": {
26
+ "type": "object",
27
+ "properties": { "EXPORT": {
28
+ "type": "string",
29
+ "enum": ["none", "tool"]
30
+ } },
31
+ "required": ["EXPORT"],
32
+ "additionalProperties": true
33
+ } }
34
+ };
35
+ //#endregion
36
+ //#region src/fixed-input-schema.ts
37
+ var source = {
38
+ repository: "turbowarp-named-functions",
39
+ path: "schemas/block-editor-fixed-inputs.schema.json",
40
+ symbol: "#/$defs/defineFunction/properties/EXPORT"
41
+ };
42
+ /** The on-disk owner Schema is canonical; this is its single-field projection. */
43
+ var fixedInputSchemaBundle = {
44
+ identity: {
45
+ ownerId: "turbowarp-named-functions",
46
+ contractId: "defineFunction.EXPORT",
47
+ revision: "fixed-inputs-v1",
48
+ variantId: "default"
49
+ },
50
+ dialect: "2020-12",
51
+ root: {
52
+ retrievalUri: "https://kubohiroya.github.io/turbowarp-named-functions/schemas/defineFunction-EXPORT.schema.json",
53
+ document: block_editor_fixed_inputs_schema_default.$defs.defineFunction.properties.EXPORT,
54
+ artifact: {
55
+ role: "canonical-schema",
56
+ source
57
+ }
58
+ },
59
+ resources: [],
60
+ provenance: {
61
+ canonicalSources: [source, {
62
+ repository: "turbowarp-named-functions",
63
+ path: "src/function-registry.ts",
64
+ symbol: "readDefinition"
65
+ }],
66
+ generatedFiles: [{
67
+ repository: "turbowarp-named-functions",
68
+ path: "site/schemas/block-editor-fixed-inputs.schema.json"
69
+ }],
70
+ referenceSchemas: [],
71
+ generationSources: [{
72
+ repository: "turbowarp-named-functions",
73
+ path: "scripts/generate-fixed-input-docs.mjs"
74
+ }]
75
+ }
76
+ };
77
+ //#endregion
78
+ //#region src/fixed-input-editors.ts
79
+ var choices = ["none", "tool"];
80
+ var fixedInputEditorDefinitions = [{
81
+ apiVersion: 1,
82
+ extensionId: extensionConfig.id,
83
+ editorId: "defineFunction-fixed-inputs",
84
+ opcodes: [`${extensionConfig.id}_defineFunction`],
85
+ contractId: "turbowarp-named-functions:defineFunction.EXPORT",
86
+ contractRevision: "fixed-inputs-v1",
87
+ bindings: [{
88
+ argument: "EXPORT",
89
+ schemaBundle: fixedInputSchemaBundle,
90
+ control: {
91
+ kind: "enum",
92
+ label: "EXPORT",
93
+ choices: [{
94
+ "value": "none",
95
+ "label": "none"
96
+ }, {
97
+ "value": "tool",
98
+ "label": "tool"
99
+ }]
100
+ },
101
+ read(value) {
102
+ if (typeof value !== "string") throw new TypeError("Expected a literal export mode.");
103
+ return value;
104
+ },
105
+ encode(value) {
106
+ if (typeof value !== "string" || !choices.includes(value)) throw new TypeError("Unsupported export mode.");
107
+ return value;
108
+ },
109
+ validateCandidate(value) {
110
+ return typeof value === "string" && choices.includes(value) ? [] : [{
111
+ path: "/inputs/EXPORT",
112
+ message: "Unsupported export mode."
113
+ }];
114
+ }
115
+ }],
116
+ validationContext: () => ({
117
+ consumerId: extensionConfig.id,
118
+ nowMs: Date.now(),
119
+ settings: null
120
+ })
121
+ }];
122
+ /** Register metadata only; the GUI startup capability owns editor activation. */
123
+ function registerFixedInputEditors(scratch, definitions, runtimeOverride) {
124
+ const host = scratch;
125
+ const api = host.gui?.blockEditors;
126
+ if (!definitions.length || api?.apiVersion !== 1 || typeof api.registerFixedInputEditor !== "function") return () => {};
127
+ const runtime = runtimeOverride ?? host.vm?.runtime;
128
+ const removers = [];
129
+ let active = true;
130
+ const dispose = () => {
131
+ if (!active) return;
132
+ active = false;
133
+ runtime?.off?.("RUNTIME_DISPOSED", dispose);
134
+ for (const remove of removers.splice(0).reverse()) remove();
135
+ };
136
+ try {
137
+ for (const definition of definitions) {
138
+ const remove = api.registerFixedInputEditor.call(api, definition);
139
+ if (typeof remove !== "function") throw new TypeError("Invalid fixed input registration disposer.");
140
+ removers.push(remove);
141
+ }
142
+ runtime?.on?.("RUNTIME_DISPOSED", dispose);
143
+ } catch (error) {
144
+ dispose();
145
+ throw error;
146
+ }
147
+ return dispose;
148
+ }
22
149
  var block_definitions_default = {
23
150
  extensionName: "Named Functions",
24
151
  blocks: [
25
152
  {
26
153
  "opcode": "defineFunction",
27
154
  "blockType": "HAT",
28
- "text": "define function [NAME] description [DESCRIPTION] args schema [SCHEMA] export as [EXPORT]",
29
- "description": "Defines a named function. NAME, DESCRIPTION, and SCHEMA must be literal text. export as tool marks it for consumers such as AI tool calling.",
30
- "descriptionJa": "名前を持つ関数を定義します。NAME、DESCRIPTION、SCHEMAには文字列を直接書く必要があります。export asをtoolにすると、AIのツール呼び出しなどの利用側に公開する印になります。",
155
+ "text": "define function [NAME] description [DESCRIPTION] args schema [SCHEMA] returns schema [RETURNS] export as [EXPORT]",
156
+ "description": "Defines a named function. NAME, DESCRIPTION, and SCHEMA must be literal text. RETURNS is an optional JSON Schema for the return value; leave it blank to disable return validation.",
157
+ "descriptionJa": "名前を持つ関数を定義します。NAME、DESCRIPTION、SCHEMAには文字列を直接書く必要があります。RETURNSには任意の戻り値JSON Schemaを指定でき、空欄なら戻り値を検証しません。",
31
158
  "arguments": {
32
159
  "NAME": {
33
160
  "type": "STRING",
@@ -41,6 +168,10 @@
41
168
  "type": "STRING",
42
169
  "defaultValue": "{\"type\":\"object\",\"properties\":{\"a\":{\"type\":\"number\"},\"b\":{\"type\":\"number\"}},\"required\":[\"a\",\"b\"]}"
43
170
  },
171
+ "RETURNS": {
172
+ "type": "STRING",
173
+ "defaultValue": ""
174
+ },
44
175
  "EXPORT": {
45
176
  "type": "STRING",
46
177
  "defaultValue": "none",
@@ -170,6 +301,124 @@
170
301
  "items": ["none", "tool"]
171
302
  } }
172
303
  };
304
+ //#endregion
305
+ //#region src/schema-validator.ts
306
+ /**
307
+ * A small JSON Schema validator for function arguments and returns. It interprets the schema at run time and
308
+ * never generates code, so it also works where `eval` is unavailable (for example Cloudflare Workers).
309
+ *
310
+ * Supported keywords: type, properties, required, additionalProperties (boolean), items, enum,
311
+ * const, minimum, maximum, minLength, maxLength, minItems, maxItems. Other keywords, such as
312
+ * description and title, are ignored.
313
+ */
314
+ function validateAgainstSchema(value, schema, path = "$") {
315
+ const rule = asRecord(schema);
316
+ if (!rule) throw new Error(`${path} must be a JSON Schema object`);
317
+ assertSchemaNode(rule, path);
318
+ return validateValue(value, rule, path);
319
+ }
320
+ /** Reject malformed schemas before a function definition or call can use them. */
321
+ function validateSchemaDefinition(schema, label = "schema") {
322
+ const rule = asRecord(schema);
323
+ if (!rule) throw new Error(`${label} must be a JSON object`);
324
+ assertSchemaNode(rule, label);
325
+ }
326
+ function validateValue(value, rule, path) {
327
+ const errors = [];
328
+ if (rule.type !== void 0) {
329
+ const types = Array.isArray(rule.type) ? rule.type : [rule.type];
330
+ if (!types.some((type) => matchesType(value, type))) return [`${path} must be ${types.join(" or ")}`];
331
+ }
332
+ if (Array.isArray(rule.enum) && !rule.enum.some((candidate) => deepEqual(candidate, value))) errors.push(`${path} must be one of ${rule.enum.map((item) => JSON.stringify(item)).join(", ")}`);
333
+ if ("const" in rule && !deepEqual(rule.const, value)) errors.push(`${path} must be ${JSON.stringify(rule.const)}`);
334
+ if (typeof value === "number") {
335
+ if (typeof rule.minimum === "number" && value < rule.minimum) errors.push(`${path} must be >= ${rule.minimum}`);
336
+ if (typeof rule.maximum === "number" && value > rule.maximum) errors.push(`${path} must be <= ${rule.maximum}`);
337
+ }
338
+ if (typeof value === "string") {
339
+ const length = [...value].length;
340
+ if (typeof rule.minLength === "number" && length < rule.minLength) errors.push(`${path} must have at least ${rule.minLength} characters`);
341
+ if (typeof rule.maxLength === "number" && length > rule.maxLength) errors.push(`${path} must have at most ${rule.maxLength} characters`);
342
+ }
343
+ if (Array.isArray(value)) {
344
+ if (typeof rule.minItems === "number" && value.length < rule.minItems) errors.push(`${path} must have at least ${rule.minItems} items`);
345
+ if (typeof rule.maxItems === "number" && value.length > rule.maxItems) errors.push(`${path} must have at most ${rule.maxItems} items`);
346
+ if (rule.items !== void 0) value.forEach((item, index) => errors.push(...validateValue(item, rule.items, `${path}[${index}]`)));
347
+ }
348
+ const object = asRecord(value);
349
+ if (object) {
350
+ const properties = asRecord(rule.properties) ?? {};
351
+ if (Array.isArray(rule.required)) {
352
+ for (const name of rule.required) if (typeof name === "string" && !Object.hasOwn(object, name)) errors.push(`${path}.${name} is required`);
353
+ }
354
+ for (const [name, child] of Object.entries(object)) if (Object.hasOwn(properties, name)) errors.push(...validateValue(child, properties[name], `${path}.${name}`));
355
+ else if (rule.additionalProperties === false) errors.push(`${path}.${name} is not allowed`);
356
+ }
357
+ return errors;
358
+ }
359
+ function assertSchemaNode(rule, path) {
360
+ const validTypes = /* @__PURE__ */ new Set([
361
+ "object",
362
+ "array",
363
+ "string",
364
+ "number",
365
+ "integer",
366
+ "boolean",
367
+ "null"
368
+ ]);
369
+ if (rule.type !== void 0) {
370
+ const types = Array.isArray(rule.type) ? rule.type : [rule.type];
371
+ if (types.length === 0 || types.some((type) => typeof type !== "string" || !validTypes.has(type))) throw new Error(`${path}.type must be a supported JSON Schema type or non-empty type array`);
372
+ }
373
+ if (rule.properties !== void 0) {
374
+ const properties = asRecord(rule.properties);
375
+ if (!properties) throw new Error(`${path}.properties must be an object`);
376
+ for (const [name, child] of Object.entries(properties)) {
377
+ const childRule = asRecord(child);
378
+ if (!childRule) throw new Error(`${path}.properties.${name} must be a JSON Schema object`);
379
+ assertSchemaNode(childRule, `${path}.properties.${name}`);
380
+ }
381
+ }
382
+ if (rule.required !== void 0 && (!Array.isArray(rule.required) || rule.required.some((name) => typeof name !== "string"))) throw new Error(`${path}.required must be an array of strings`);
383
+ if (rule.additionalProperties !== void 0 && typeof rule.additionalProperties !== "boolean") throw new Error(`${path}.additionalProperties must be a boolean`);
384
+ if (rule.items !== void 0) {
385
+ const items = asRecord(rule.items);
386
+ if (!items) throw new Error(`${path}.items must be a JSON Schema object`);
387
+ assertSchemaNode(items, `${path}.items`);
388
+ }
389
+ if (rule.enum !== void 0 && (!Array.isArray(rule.enum) || rule.enum.length === 0)) throw new Error(`${path}.enum must be a non-empty array`);
390
+ for (const keyword of ["minimum", "maximum"]) if (rule[keyword] !== void 0 && (typeof rule[keyword] !== "number" || !Number.isFinite(rule[keyword]))) throw new Error(`${path}.${keyword} must be a finite number`);
391
+ for (const keyword of [
392
+ "minLength",
393
+ "maxLength",
394
+ "minItems",
395
+ "maxItems"
396
+ ]) {
397
+ const value = rule[keyword];
398
+ if (value !== void 0 && (typeof value !== "number" || !Number.isInteger(value) || value < 0)) throw new Error(`${path}.${keyword} must be a non-negative integer`);
399
+ }
400
+ if (typeof rule.minimum === "number" && typeof rule.maximum === "number" && rule.minimum > rule.maximum) throw new Error(`${path}.minimum cannot exceed maximum`);
401
+ if (typeof rule.minLength === "number" && typeof rule.maxLength === "number" && rule.minLength > rule.maxLength) throw new Error(`${path}.minLength cannot exceed maxLength`);
402
+ if (typeof rule.minItems === "number" && typeof rule.maxItems === "number" && rule.minItems > rule.maxItems) throw new Error(`${path}.minItems cannot exceed maxItems`);
403
+ }
404
+ function matchesType(value, type) {
405
+ switch (type) {
406
+ case "object": return asRecord(value) !== null;
407
+ case "array": return Array.isArray(value);
408
+ case "string": return typeof value === "string";
409
+ case "number": return typeof value === "number" && Number.isFinite(value);
410
+ case "integer": return typeof value === "number" && Number.isInteger(value);
411
+ case "boolean": return typeof value === "boolean";
412
+ case "null": return value === null;
413
+ default: return false;
414
+ }
415
+ }
416
+ function deepEqual(left, right) {
417
+ return JSON.stringify(left) === JSON.stringify(right);
418
+ }
419
+ function asRecord(value) {
420
+ return typeof value === "object" && value !== null && !Array.isArray(value) ? value : null;
421
+ }
173
422
  var FunctionDispatcher = class {
174
423
  constructor(runtime, options) {
175
424
  this.runtime = runtime;
@@ -191,7 +440,7 @@
191
440
  * Starts a named function. `caller` is the thread of the block making the call, if any; it is used
192
441
  * to detect reentrant calls.
193
442
  */
194
- invoke(name, args, caller) {
443
+ invoke(name, args, caller, returnSchema) {
195
444
  if (!this.options.knownNames().has(name)) return Promise.reject(/* @__PURE__ */ new Error(`Unknown function: ${name}`));
196
445
  const parentChain = caller ? this.byThread.get(caller)?.chain ?? [] : [];
197
446
  if (parentChain.includes(name)) return Promise.reject(/* @__PURE__ */ new Error(`Reentrant call: ${[...parentChain, name].join(" -> ")}. Use a custom block for recursion.`));
@@ -199,6 +448,7 @@
199
448
  const invocation = {
200
449
  name,
201
450
  args,
451
+ ...returnSchema === void 0 ? {} : { returnSchema },
202
452
  chain: [...parentChain, name],
203
453
  resolve,
204
454
  reject,
@@ -229,7 +479,7 @@
229
479
  returnFrom(thread, value) {
230
480
  const invocation = thread ? this.byThread.get(thread) : void 0;
231
481
  if (!invocation) throw new Error("return can only be used inside a running function.");
232
- this.settle(invocation, null, value);
482
+ this.settleWithValue(invocation, value);
233
483
  }
234
484
  cancelAll(reason) {
235
485
  for (const invocation of [...this.queue, ...this.running.values()]) this.settle(invocation, new Error(reason));
@@ -258,7 +508,7 @@
258
508
  this.step += 1;
259
509
  const starting = this.starting;
260
510
  if (starting && this.step - starting.startedAtStep > 2) this.settle(starting, /* @__PURE__ */ new Error(`Function ${starting.name} did not start. Is its script already running?`));
261
- for (const invocation of this.running.values()) if (invocation.thread && !this.runtime.threads.includes(invocation.thread)) this.settle(invocation, null, null);
511
+ for (const invocation of this.running.values()) if (invocation.thread && !this.runtime.threads.includes(invocation.thread)) this.settleWithValue(invocation, null);
262
512
  this.pump();
263
513
  }
264
514
  settle(invocation, error, value) {
@@ -273,6 +523,16 @@
273
523
  if (error) invocation.reject(error);
274
524
  else invocation.resolve(value);
275
525
  }
526
+ settleWithValue(invocation, value) {
527
+ if (invocation.returnSchema !== void 0) {
528
+ const errors = validateAgainstSchema(value, invocation.returnSchema);
529
+ if (errors.length > 0) {
530
+ this.settle(invocation, /* @__PURE__ */ new Error(`Invalid return value for ${invocation.name}: ${errors.join("; ")}`));
531
+ return;
532
+ }
533
+ }
534
+ this.settle(invocation, null, value);
535
+ }
276
536
  };
277
537
  /** Resolves a dotted path such as `items.0.name` inside parsed JSON arguments. */
278
538
  function readArgumentPath(args, path) {
@@ -350,18 +610,25 @@
350
610
  if (!FUNCTION_NAME_PATTERN.test(name)) throw new Error("function name must be 1-64 letters, digits, \"_\" or \"-\"");
351
611
  const description = readLiteralInput(block, blocks, "DESCRIPTION").trim();
352
612
  if (description.length > 1024) throw new Error(`description must be at most ${MAX_DESCRIPTION_LENGTH} characters`);
353
- const parameters = parseSchema(readLiteralInput(block, blocks, "SCHEMA"));
613
+ const parameters = parseSchema(readLiteralInput(block, blocks, "SCHEMA"), "args schema", true);
614
+ const returnsText = readOptionalLiteralInput(block, blocks, "RETURNS");
615
+ const returns = returnsText === void 0 || returnsText.trim() === "" ? void 0 : parseSchema(returnsText, "returns schema", false);
354
616
  const exportAs = String(block.fields?.EXPORT?.value ?? "none") === "tool" ? "tool" : "none";
355
617
  if (exportAs === "tool" && description.length === 0) throw new Error("a function exported as a tool needs a description");
356
618
  return {
357
619
  name,
358
620
  description,
359
621
  parameters,
622
+ ...returns ? { returns } : {},
360
623
  exportAs,
361
624
  targetName,
362
625
  blockId: block.id
363
626
  };
364
627
  }
628
+ function readOptionalLiteralInput(block, blocks, inputName) {
629
+ if (!block.inputs?.[inputName]) return void 0;
630
+ return readLiteralInput(block, blocks, inputName);
631
+ }
365
632
  function readLiteralInput(block, blocks, inputName) {
366
633
  const input = block.inputs?.[inputName];
367
634
  if (!input) throw new Error(`${inputName} is missing`);
@@ -372,82 +639,20 @@
372
639
  if (!field) throw new Error(`${inputName} is missing`);
373
640
  return String(field.value ?? "");
374
641
  }
375
- function parseSchema(text) {
642
+ function parseSchema(text, label, requireObjectType) {
376
643
  let value;
377
644
  try {
378
645
  value = JSON.parse(text);
379
646
  } catch {
380
- throw new Error("args schema must be valid JSON");
647
+ throw new Error(`${label} must be valid JSON`);
381
648
  }
382
- if (typeof value !== "object" || value === null || Array.isArray(value)) throw new Error("args schema must be a JSON object");
649
+ if (typeof value !== "object" || value === null || Array.isArray(value)) throw new Error(`${label} must be a JSON object`);
383
650
  const schema = value;
384
- if (schema.type !== "object") throw new Error("args schema must have \"type\": \"object\"");
651
+ if (requireObjectType && schema.type !== "object") throw new Error("args schema must have \"type\": \"object\"");
652
+ validateSchemaDefinition(schema, label);
385
653
  return schema;
386
654
  }
387
655
  //#endregion
388
- //#region src/schema-validator.ts
389
- /**
390
- * A small JSON Schema validator for function arguments. It interprets the schema at run time and
391
- * never generates code, so it also works where `eval` is unavailable (for example Cloudflare Workers).
392
- *
393
- * Supported keywords: type, properties, required, additionalProperties (boolean), items, enum,
394
- * const, minimum, maximum, minLength, maxLength, minItems, maxItems. Other keywords, such as
395
- * description and title, are ignored.
396
- */
397
- function validateAgainstSchema(value, schema, path = "$") {
398
- const rule = asRecord(schema);
399
- if (!rule) return [];
400
- const errors = [];
401
- if (rule.type !== void 0) {
402
- const types = Array.isArray(rule.type) ? rule.type : [rule.type];
403
- if (!types.some((type) => matchesType(value, type))) return [`${path} must be ${types.join(" or ")}`];
404
- }
405
- if (Array.isArray(rule.enum) && !rule.enum.some((candidate) => deepEqual(candidate, value))) errors.push(`${path} must be one of ${rule.enum.map((item) => JSON.stringify(item)).join(", ")}`);
406
- if ("const" in rule && !deepEqual(rule.const, value)) errors.push(`${path} must be ${JSON.stringify(rule.const)}`);
407
- if (typeof value === "number") {
408
- if (typeof rule.minimum === "number" && value < rule.minimum) errors.push(`${path} must be >= ${rule.minimum}`);
409
- if (typeof rule.maximum === "number" && value > rule.maximum) errors.push(`${path} must be <= ${rule.maximum}`);
410
- }
411
- if (typeof value === "string") {
412
- const length = [...value].length;
413
- if (typeof rule.minLength === "number" && length < rule.minLength) errors.push(`${path} must have at least ${rule.minLength} characters`);
414
- if (typeof rule.maxLength === "number" && length > rule.maxLength) errors.push(`${path} must have at most ${rule.maxLength} characters`);
415
- }
416
- if (Array.isArray(value)) {
417
- if (typeof rule.minItems === "number" && value.length < rule.minItems) errors.push(`${path} must have at least ${rule.minItems} items`);
418
- if (typeof rule.maxItems === "number" && value.length > rule.maxItems) errors.push(`${path} must have at most ${rule.maxItems} items`);
419
- if (rule.items !== void 0) value.forEach((item, index) => errors.push(...validateAgainstSchema(item, rule.items, `${path}[${index}]`)));
420
- }
421
- const object = asRecord(value);
422
- if (object) {
423
- const properties = asRecord(rule.properties) ?? {};
424
- if (Array.isArray(rule.required)) {
425
- for (const name of rule.required) if (typeof name === "string" && !(name in object)) errors.push(`${path}.${name} is required`);
426
- }
427
- for (const [name, child] of Object.entries(object)) if (name in properties) errors.push(...validateAgainstSchema(child, properties[name], `${path}.${name}`));
428
- else if (rule.additionalProperties === false) errors.push(`${path}.${name} is not allowed`);
429
- }
430
- return errors;
431
- }
432
- function matchesType(value, type) {
433
- switch (type) {
434
- case "object": return asRecord(value) !== null;
435
- case "array": return Array.isArray(value);
436
- case "string": return typeof value === "string";
437
- case "number": return typeof value === "number" && Number.isFinite(value);
438
- case "integer": return typeof value === "number" && Number.isInteger(value);
439
- case "boolean": return typeof value === "boolean";
440
- case "null": return value === null;
441
- default: return false;
442
- }
443
- }
444
- function deepEqual(left, right) {
445
- return JSON.stringify(left) === JSON.stringify(right);
446
- }
447
- function asRecord(value) {
448
- return typeof value === "object" && value !== null && !Array.isArray(value) ? value : null;
449
- }
450
- //#endregion
451
656
  //#region src/composition.ts
452
657
  /**
453
658
  * Composition API: named functions without TurboWarp block definitions.
@@ -496,7 +701,7 @@
496
701
  if (options.exportedOnly && definition.exportAs !== "tool") return Promise.reject(/* @__PURE__ */ new Error(`Function ${trimmed} is not exported as a tool.`));
497
702
  const errors = validateAgainstSchema(args, definition.parameters);
498
703
  if (errors.length > 0) return Promise.reject(/* @__PURE__ */ new Error(`Invalid arguments for ${trimmed}: ${errors.join("; ")}`));
499
- return this.dispatcher.invoke(trimmed, args, options.caller);
704
+ return this.dispatcher.invoke(trimmed, args, options.caller, definition.returns);
500
705
  }
501
706
  start(name, args, options = {}) {
502
707
  const id = `p_${this.nextPromiseId++}`;
@@ -575,10 +780,19 @@
575
780
  var NamedFunctionsExtension = class {
576
781
  constructor(deps) {
577
782
  this.lastErrorMessage = "";
578
- this.functions = createNamedFunctions({
579
- ...deps,
580
- functionHatOpcode: DEFINE_FUNCTION_OPCODE
581
- });
783
+ this.unregisterFixedInputEditors = registerFixedInputEditors(typeof Scratch === "undefined" ? {} : Scratch, fixedInputEditorDefinitions, deps.runtime);
784
+ try {
785
+ this.functions = createNamedFunctions({
786
+ ...deps,
787
+ functionHatOpcode: DEFINE_FUNCTION_OPCODE
788
+ });
789
+ } catch (error) {
790
+ this.unregisterFixedInputEditors();
791
+ throw error;
792
+ }
793
+ }
794
+ dispose() {
795
+ this.unregisterFixedInputEditors();
582
796
  }
583
797
  getInfo() {
584
798
  return {
@@ -4,7 +4,7 @@ export type { FunctionDefinition, FunctionScan, FunctionTool } from './function-
4
4
  export { FUNCTION_NAME_PATTERN, scanFunctionDefinitions, toFunctionTools } from './function-registry.js';
5
5
  export type { RuntimeLike, RuntimeThread, BlockUtilityLike } from './runtime-types.js';
6
6
  export { parseJsonOrText, readArgumentPath, toScratchValue } from './function-dispatcher.js';
7
- export { validateAgainstSchema } from './schema-validator.js';
7
+ export { validateAgainstSchema, validateSchemaDefinition } from './schema-validator.js';
8
8
  export interface PromiseRef {
9
9
  $promise: string;
10
10
  }
@@ -10,7 +10,9 @@ type Util = BlockUtilityLike & {
10
10
  export declare class NamedFunctionsExtension implements TurboWarpExtension {
11
11
  private lastErrorMessage;
12
12
  private readonly functions;
13
+ private readonly unregisterFixedInputEditors;
13
14
  constructor(deps: NamedFunctionsExtensionDependencies);
15
+ dispose(): void;
14
16
  getInfo(): Record<string, unknown>;
15
17
  defineFunction(args: Args, util?: Util): boolean;
16
18
  functionArgument(args: Args, util?: Util): string | number | boolean;
@@ -0,0 +1,9 @@
1
+ import type { FixedInputEditorOptions } from '@kubohiroya/turbowarp-extension-data-editor';
2
+ export declare const fixedInputEditorDefinitions: readonly FixedInputEditorOptions[];
3
+ interface RuntimeLifetime {
4
+ on?: (event: string, listener: () => void) => void;
5
+ off?: (event: string, listener: () => void) => void;
6
+ }
7
+ /** Register metadata only; the GUI startup capability owns editor activation. */
8
+ export declare function registerFixedInputEditors(scratch: unknown, definitions: readonly FixedInputEditorOptions[], runtimeOverride?: RuntimeLifetime): () => void;
9
+ export {};
@@ -0,0 +1,3 @@
1
+ import type { SchemaBundle } from '@kubohiroya/turbowarp-extension-data-editor/schema';
2
+ /** The on-disk owner Schema is canonical; this is its single-field projection. */
3
+ export declare const fixedInputSchemaBundle: SchemaBundle;
@@ -40,7 +40,7 @@ export declare class FunctionDispatcher {
40
40
  * Starts a named function. `caller` is the thread of the block making the call, if any; it is used
41
41
  * to detect reentrant calls.
42
42
  */
43
- invoke(name: string, args: unknown, caller?: RuntimeThread): Promise<unknown>;
43
+ invoke(name: string, args: unknown, caller?: RuntimeThread, returnSchema?: unknown): Promise<unknown>;
44
44
  /** Hat predicate: true only for the script that should run the invocation being started. */
45
45
  matchHat(name: string, thread: RuntimeThread | undefined): boolean;
46
46
  argumentsFor(thread: RuntimeThread | undefined): unknown;
@@ -51,6 +51,7 @@ export declare class FunctionDispatcher {
51
51
  private pump;
52
52
  private afterStep;
53
53
  private settle;
54
+ private settleWithValue;
54
55
  }
55
56
  /** Resolves a dotted path such as `items.0.name` inside parsed JSON arguments. */
56
57
  export declare function readArgumentPath(args: unknown, path: string): unknown;
@@ -12,6 +12,8 @@ export interface FunctionDefinition {
12
12
  name: string;
13
13
  description: string;
14
14
  parameters: Record<string, unknown>;
15
+ /** Omitted on older projects and when RETURNS is left blank. */
16
+ returns?: Record<string, unknown>;
15
17
  exportAs: 'tool' | 'none';
16
18
  targetName: string;
17
19
  blockId: string;
@@ -1,5 +1,5 @@
1
1
  /**
2
- * A small JSON Schema validator for function arguments. It interprets the schema at run time and
2
+ * A small JSON Schema validator for function arguments and returns. It interprets the schema at run time and
3
3
  * never generates code, so it also works where `eval` is unavailable (for example Cloudflare Workers).
4
4
  *
5
5
  * Supported keywords: type, properties, required, additionalProperties (boolean), items, enum,
@@ -7,3 +7,5 @@
7
7
  * description and title, are ignored.
8
8
  */
9
9
  export declare function validateAgainstSchema(value: unknown, schema: unknown, path?: string): string[];
10
+ /** Reject malformed schemas before a function definition or call can use them. */
11
+ export declare function validateSchemaDefinition(schema: unknown, label?: string): void;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kubohiroya/turbowarp-named-functions",
3
- "version": "0.1.0",
3
+ "version": "0.1.2",
4
4
  "description": "Named, JSON-in/JSON-out functions for TurboWarp that can be called by name, synchronously or asynchronously, and exported as tools.",
5
5
  "author": "Hiroya Kubo <hiroya@cuc.ac.jp>",
6
6
  "license": "MPL-2.0",
@@ -26,10 +26,10 @@
26
26
  "files": [
27
27
  "dist/",
28
28
  "src/",
29
- "schemas/",
30
29
  "README.md",
31
30
  "README.ja.md",
32
- "LICENSE"
31
+ "LICENSE",
32
+ "schemas/"
33
33
  ],
34
34
  "publishConfig": {
35
35
  "access": "public",
@@ -45,17 +45,19 @@
45
45
  "build": "vite build && vite build --config vite.composition.config.ts && tsc --project tsconfig.build.json",
46
46
  "lint": "eslint src tests scripts vite.config.ts vite.composition.config.ts eslint.config.ts",
47
47
  "test": "vitest run",
48
- "docs": "node scripts/generate-readme.ts",
49
- "docs:check": "node scripts/generate-readme.ts --check",
48
+ "docs": "node scripts/generate-readme.ts && node scripts/generate-fixed-input-docs.mjs",
49
+ "docs:check": "node scripts/generate-readme.ts --check && node scripts/generate-fixed-input-docs.mjs --check",
50
50
  "repo:check": "node scripts/check-repo.ts",
51
+ "site:check": "node scripts/check-site.ts",
51
52
  "pack:check": "npm pack --dry-run --ignore-scripts",
52
- "check": "pnpm run typecheck && pnpm run lint && pnpm run test && pnpm run docs:check && pnpm run check:dist && pnpm run types:composition:check && pnpm run repo:check && pnpm run pack:check",
53
+ "check": "pnpm run typecheck && pnpm run lint && pnpm run test && pnpm run docs:check && pnpm run site:check && pnpm run check:dist && pnpm run types:composition:check && pnpm run repo:check && pnpm run pack:check",
53
54
  "check:dist": "pnpm run build && node scripts/check-dist.ts",
54
55
  "types:composition:check": "tsc --project tsconfig.composition-consumer.json"
55
56
  },
56
57
  "devDependencies": {
57
58
  "@eslint/js": "^9.39.5",
58
- "@kubohiroya/vite-plugin-turbowarp-extension": "0.3.0",
59
+ "@kubohiroya/turbowarp-extension-manifest": "0.3.2",
60
+ "@kubohiroya/vite-plugin-turbowarp-extension": "0.6.1",
59
61
  "@types/node": "^24.13.3",
60
62
  "eslint": "^9.39.5",
61
63
  "jiti": "^2.7.0",
@@ -71,5 +73,14 @@
71
73
  },
72
74
  "./turbowarp-named-functions.js": "./dist/turbowarp-named-functions.js",
73
75
  "./package.json": "./package.json"
76
+ },
77
+ "dependencies": {
78
+ "@kubohiroya/turbowarp-extension-data-editor": "0.2.1"
79
+ },
80
+ "gitHead": "69d13e22ed36d0566abf964a67c3a5d746505c2e",
81
+ "x-turbowarp-source": {
82
+ "revision": "69d13e22ed36d0566abf964a67c3a5d746505c2e",
83
+ "revisionRole": "base-commit",
84
+ "sourceState": "local-release-overlay"
74
85
  }
75
86
  }
@@ -0,0 +1,22 @@
1
+ {
2
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
3
+ "$id": "https://kubohiroya.github.io/turbowarp-named-functions/schemas/block-editor-fixed-inputs.schema.json",
4
+ "$defs": {
5
+ "defineFunction": {
6
+ "type": "object",
7
+ "properties": {
8
+ "EXPORT": {
9
+ "type": "string",
10
+ "enum": [
11
+ "none",
12
+ "tool"
13
+ ]
14
+ }
15
+ },
16
+ "required": [
17
+ "EXPORT"
18
+ ],
19
+ "additionalProperties": true
20
+ }
21
+ }
22
+ }