@kubohiroya/turbowarp-openai-realtime-api 0.1.0 → 0.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.ja.md CHANGED
@@ -37,7 +37,7 @@ OpenAI Realtime APIと音声やテキストで会話し、ブロックで書い
37
37
  npm packageとして使う場合は、検証済みのversionをexact pinします。
38
38
 
39
39
  ```bash
40
- pnpm add --save-exact @kubohiroya/turbowarp-openai-realtime-api@0.1.0
40
+ pnpm add --save-exact @kubohiroya/turbowarp-openai-realtime-api@0.1.1
41
41
  ```
42
42
 
43
43
  ## クイックスタート
package/README.md CHANGED
@@ -43,7 +43,7 @@ The reviewed JavaScript build is committed to this repository, so users do not n
43
43
  Install an exact version that you have reviewed:
44
44
 
45
45
  ```bash
46
- pnpm add --save-exact @kubohiroya/turbowarp-openai-realtime-api@0.1.0
46
+ pnpm add --save-exact @kubohiroya/turbowarp-openai-realtime-api@0.1.1
47
47
  ```
48
48
 
49
49
  Standalone bundle:
@@ -413,3 +413,15 @@ SCRATCH_VM_PATH=/path/to/TurboWarp/scratch-vm pnpm test
413
413
  ## License
414
414
 
415
415
  [Mozilla Public License 2.0](LICENSE) (SPDX: `MPL-2.0`).
416
+
417
+ ## Fixed input editing
418
+
419
+ With a compatible TurboWarp GUI, enable fixed-input forms to edit only standard literal fields. Numbers use complete finite JSON number tokens; menu fields use existing choices. Connected reporters and unavailable fields stay read-only and are never evaluated. Saving an unchanged form preserves exact existing raw values, including legacy spellings and unknown choices. Invalid drafts stay in the same editing session; cancel, project/target replacement, or block removal discards them. Disabling the GUI feature flag restores native field editing. This form does not run blocks, open network/audio/key/QR sessions, resolve names, or edit Schema arguments.
420
+
421
+ Canonical contracts: `schemas/block-editor-fixed-inputs.schema.json`; codecs and optional registration: `src/fixed-input-editors.ts`. These contracts describe new fixed-field candidates; they do not redefine all runtime data. The GUI integration is optional and existing standalone/composition APIs stay available.
422
+
423
+ - `setOutputMode`: MODE — [block documentation](https://kubohiroya.github.io/turbowarp-openai-realtime-api/#block-setOutputMode).
424
+ - `setSessionTimeLimit`: SECONDS — [block documentation](https://kubohiroya.github.io/turbowarp-openai-realtime-api/#block-setSessionTimeLimit).
425
+ - `connect`: MICROPHONE — [block documentation](https://kubohiroya.github.io/turbowarp-openai-realtime-api/#block-connect).
426
+ - `defineFunction`: EXPORT — [block documentation](https://kubohiroya.github.io/turbowarp-openai-realtime-api/#block-defineFunction).
427
+ - `usageValue`: FIELD — [block documentation](https://kubohiroya.github.io/turbowarp-openai-realtime-api/#block-usageValue).
@@ -19,6 +19,209 @@
19
19
  docsURI: "https://kubohiroya.github.io/turbowarp-openai-realtime-api/",
20
20
  blockIconURI: "data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCA0OCA0OCI+PHBhdGggZD0iTTggMTBoMzJhNCA0IDAgMCAxIDQgNHYxNmE0IDQgMCAwIDEtNCA0SDIybC05IDd2LTdIOGE0IDQgMCAwIDEtNC00VjE0YTQgNCAwIDAgMSA0LTR6IiBmaWxsPSIjMTBBMzdGIi8+PGcgc3Ryb2tlPSIjZmZmIiBzdHJva2Utd2lkdGg9IjMiIHN0cm9rZS1saW5lY2FwPSJyb3VuZCI+PHBhdGggZD0iTTE0IDE5djYiLz48cGF0aCBkPSJNMjAgMTZ2MTIiLz48cGF0aCBkPSJNMjYgMTh2OCIvPjxwYXRoIGQ9Ik0zMiAxNXYxNCIvPjxwYXRoIGQ9Ik0zOCAyMHY0Ii8+PC9nPjwvc3ZnPg=="
21
21
  };
22
+ var block_editor_fixed_inputs_schema_default = {
23
+ $schema: "http://json-schema.org/draft-07/schema#",
24
+ $id: "https://kubohiroya.github.io/turbowarp-openai-realtime-api/schemas/block-editor-fixed-inputs.schema.json",
25
+ title: "turbowarp-openai-realtime-api fixed editing contracts",
26
+ $defs: {
27
+ "setOutputMode": {
28
+ "type": "object",
29
+ "properties": { "MODE": {
30
+ "type": "string",
31
+ "enum": ["audio", "text"]
32
+ } },
33
+ "additionalProperties": false
34
+ },
35
+ "setSessionTimeLimit": {
36
+ "type": "object",
37
+ "properties": { "SECONDS": {
38
+ "type": "number",
39
+ "minimum": 0
40
+ } },
41
+ "additionalProperties": false
42
+ },
43
+ "connect": {
44
+ "type": "object",
45
+ "properties": { "MICROPHONE": {
46
+ "type": "string",
47
+ "enum": ["on", "off"]
48
+ } },
49
+ "additionalProperties": false
50
+ },
51
+ "defineFunction": {
52
+ "type": "object",
53
+ "properties": { "EXPORT": {
54
+ "type": "string",
55
+ "enum": ["tool", "none"]
56
+ } },
57
+ "additionalProperties": false
58
+ },
59
+ "usageValue": {
60
+ "type": "object",
61
+ "properties": { "FIELD": {
62
+ "type": "string",
63
+ "enum": [
64
+ "costUSD",
65
+ "responses",
66
+ "inputTokens",
67
+ "outputTokens",
68
+ "cachedInputTokens",
69
+ "textInputTokens",
70
+ "audioInputTokens",
71
+ "textOutputTokens",
72
+ "audioOutputTokens"
73
+ ]
74
+ } },
75
+ "additionalProperties": false
76
+ }
77
+ }
78
+ };
79
+ //#endregion
80
+ //#region src/fixed-input-editors.ts
81
+ var contracts = block_editor_fixed_inputs_schema_default.$defs;
82
+ var repository = "turbowarp-openai-realtime-api";
83
+ var extensionId = "kubohiroyaopenairealtime";
84
+ var token = /^-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?$/u;
85
+ function readNumber(value) {
86
+ if (typeof value !== "string" && typeof value !== "number") throw new TypeError("Invalid numeric projection.");
87
+ if (typeof value === "string" && value.trim() === "") throw new TypeError("Existing blank field is readonly.");
88
+ const number = Number(value);
89
+ if (!Number.isFinite(number)) throw new TypeError("Existing nonfinite field is readonly.");
90
+ return number;
91
+ }
92
+ function newNumberToken(value) {
93
+ if (typeof value === "number") {
94
+ if (!Number.isFinite(value)) throw new TypeError("Invalid new number.");
95
+ return Object.is(value, -0) ? "-0" : String(value);
96
+ }
97
+ if (typeof value !== "string" || !token.test(value.trim()) || !Number.isFinite(Number(value))) throw new TypeError("Invalid new number.");
98
+ return value.trim();
99
+ }
100
+ function existingChoice(_opcode, value) {
101
+ if (typeof value !== "string") throw new TypeError("Invalid string projection.");
102
+ return value;
103
+ }
104
+ function candidateValid(_opcode, _argument, schema, value) {
105
+ if (schema.type === "number" || schema.type === "integer") {
106
+ let number;
107
+ try {
108
+ number = readNumber(value);
109
+ } catch {
110
+ return false;
111
+ }
112
+ if (schema.type === "integer" && !Number.isInteger(number)) return false;
113
+ if (schema.minimum !== void 0 && number < schema.minimum) return false;
114
+ if (schema.maximum !== void 0 && number > schema.maximum) return false;
115
+ if (schema.exclusiveMinimum !== void 0 && number <= schema.exclusiveMinimum) return false;
116
+ if (schema.enum && !schema.enum.includes(number)) return false;
117
+ return true;
118
+ }
119
+ return typeof value === "string" && schema.enum.includes(value);
120
+ }
121
+ function fixedInputEditorOptions() {
122
+ return Object.entries(contracts).map(([opcode, contract]) => ({
123
+ apiVersion: 1,
124
+ extensionId,
125
+ editorId: `${extensionId}.fixed.${opcode}`,
126
+ opcodes: [`${extensionId}_${opcode}`],
127
+ contractId: `${repository}.${opcode}.fixed`,
128
+ contractRevision: "fixed-inputs-v1",
129
+ validationContext: () => ({
130
+ consumerId: repository,
131
+ nowMs: 0,
132
+ settings: null
133
+ }),
134
+ bindings: Object.entries(contract.properties).map(([argument, schema]) => {
135
+ const numeric = schema.type === "number" || schema.type === "integer";
136
+ const source = {
137
+ repository,
138
+ path: "schemas/block-editor-fixed-inputs.schema.json",
139
+ symbol: `/$defs/${opcode}/properties/${argument}`
140
+ };
141
+ return {
142
+ argument,
143
+ schemaBundle: {
144
+ identity: {
145
+ ownerId: repository,
146
+ contractId: `${opcode}.${argument}`,
147
+ revision: "fixed-inputs-v1",
148
+ variantId: "fixed"
149
+ },
150
+ dialect: "draft-07",
151
+ root: {
152
+ retrievalUri: `${block_editor_fixed_inputs_schema_default.$id}?binding=${opcode}.${argument}`,
153
+ document: schema,
154
+ artifact: {
155
+ role: "canonical-schema",
156
+ source
157
+ }
158
+ },
159
+ resources: [],
160
+ provenance: {
161
+ canonicalSources: [
162
+ source,
163
+ {
164
+ repository,
165
+ path: "src/block-definitions.json"
166
+ },
167
+ {
168
+ repository,
169
+ path: "src/extension.ts",
170
+ symbol: opcode
171
+ }
172
+ ],
173
+ generatedFiles: [],
174
+ referenceSchemas: [],
175
+ generationSources: []
176
+ }
177
+ },
178
+ control: numeric ? { kind: "number" } : {
179
+ kind: "enum",
180
+ choices: schema.enum.map((value) => ({
181
+ value,
182
+ label: String(value)
183
+ }))
184
+ },
185
+ read: (value) => numeric ? readNumber(value) : existingChoice(opcode, value),
186
+ encode: (value) => {
187
+ if (numeric) return newNumberToken(value);
188
+ if (typeof value !== "string" || !schema.enum.includes(value)) throw new TypeError("Invalid new enum value.");
189
+ return value;
190
+ },
191
+ validateCandidate: (value) => candidateValid(opcode, argument, schema, value) ? [] : [{
192
+ path: argument,
193
+ message: "Check this value before saving."
194
+ }]
195
+ };
196
+ })
197
+ }));
198
+ }
199
+ /** Register only visible static contracts; ordinary composition consumers load no editor runtime. */
200
+ function registerFixedInputEditors(scratch, runtime, visibleBlocks) {
201
+ const api = scratch.gui?.blockEditors;
202
+ if (api?.apiVersion !== 1 || typeof api.registerFixedInputEditor !== "function") return void 0;
203
+ const visibleOpcodes = new Set(visibleBlocks.flatMap((block) => {
204
+ if (typeof block !== "object" || block === null || !("opcode" in block)) return [];
205
+ return typeof block.opcode === "string" ? [block.opcode] : [];
206
+ }));
207
+ const events = runtime;
208
+ const removers = [];
209
+ let active = true;
210
+ const dispose = () => {
211
+ if (!active) return;
212
+ active = false;
213
+ events?.off?.("RUNTIME_DISPOSED", dispose);
214
+ for (const remove of removers.splice(0).reverse()) remove();
215
+ };
216
+ try {
217
+ for (const options of fixedInputEditorOptions()) if (options.opcodes.some((opcode) => visibleOpcodes.has(opcode.slice(25)))) removers.push(api.registerFixedInputEditor.call(api, options));
218
+ events?.on?.("RUNTIME_DISPOSED", dispose);
219
+ } catch (error) {
220
+ dispose();
221
+ throw error;
222
+ }
223
+ return dispose;
224
+ }
22
225
  var block_definitions_default = {
23
226
  extensionName: "OpenAI Realtime",
24
227
  blocks: [
@@ -331,7 +534,123 @@
331
534
  }
332
535
  };
333
536
  //#endregion
334
- //#region node_modules/.pnpm/@kubohiroya+turbowarp-named-functions@0.1.0/node_modules/@kubohiroya/turbowarp-named-functions/dist/composition.js
537
+ //#region node_modules/.pnpm/@kubohiroya+turbowarp-named-functions@0.1.1_react@18.3.1/node_modules/@kubohiroya/turbowarp-named-functions/dist/composition.js
538
+ /**
539
+ * A small JSON Schema validator for function arguments and returns. It interprets the schema at run time and
540
+ * never generates code, so it also works where `eval` is unavailable (for example Cloudflare Workers).
541
+ *
542
+ * Supported keywords: type, properties, required, additionalProperties (boolean), items, enum,
543
+ * const, minimum, maximum, minLength, maxLength, minItems, maxItems. Other keywords, such as
544
+ * description and title, are ignored.
545
+ */
546
+ function validateAgainstSchema(value, schema, path = "$") {
547
+ const rule = asRecord$2(schema);
548
+ if (!rule) throw new Error(`${path} must be a JSON Schema object`);
549
+ assertSchemaNode(rule, path);
550
+ return validateValue(value, rule, path);
551
+ }
552
+ /** Reject malformed schemas before a function definition or call can use them. */
553
+ function validateSchemaDefinition(schema, label = "schema") {
554
+ const rule = asRecord$2(schema);
555
+ if (!rule) throw new Error(`${label} must be a JSON object`);
556
+ assertSchemaNode(rule, label);
557
+ }
558
+ function validateValue(value, rule, path) {
559
+ const errors = [];
560
+ if (rule.type !== void 0) {
561
+ const types = Array.isArray(rule.type) ? rule.type : [rule.type];
562
+ if (!types.some((type) => matchesType(value, type))) return [`${path} must be ${types.join(" or ")}`];
563
+ }
564
+ 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(", ")}`);
565
+ if ("const" in rule && !deepEqual(rule.const, value)) errors.push(`${path} must be ${JSON.stringify(rule.const)}`);
566
+ if (typeof value === "number") {
567
+ if (typeof rule.minimum === "number" && value < rule.minimum) errors.push(`${path} must be >= ${rule.minimum}`);
568
+ if (typeof rule.maximum === "number" && value > rule.maximum) errors.push(`${path} must be <= ${rule.maximum}`);
569
+ }
570
+ if (typeof value === "string") {
571
+ const length = [...value].length;
572
+ if (typeof rule.minLength === "number" && length < rule.minLength) errors.push(`${path} must have at least ${rule.minLength} characters`);
573
+ if (typeof rule.maxLength === "number" && length > rule.maxLength) errors.push(`${path} must have at most ${rule.maxLength} characters`);
574
+ }
575
+ if (Array.isArray(value)) {
576
+ if (typeof rule.minItems === "number" && value.length < rule.minItems) errors.push(`${path} must have at least ${rule.minItems} items`);
577
+ if (typeof rule.maxItems === "number" && value.length > rule.maxItems) errors.push(`${path} must have at most ${rule.maxItems} items`);
578
+ if (rule.items !== void 0) value.forEach((item, index) => errors.push(...validateValue(item, rule.items, `${path}[${index}]`)));
579
+ }
580
+ const object = asRecord$2(value);
581
+ if (object) {
582
+ const properties = asRecord$2(rule.properties) ?? {};
583
+ if (Array.isArray(rule.required)) {
584
+ for (const name of rule.required) if (typeof name === "string" && !Object.hasOwn(object, name)) errors.push(`${path}.${name} is required`);
585
+ }
586
+ for (const [name, child] of Object.entries(object)) if (Object.hasOwn(properties, name)) errors.push(...validateValue(child, properties[name], `${path}.${name}`));
587
+ else if (rule.additionalProperties === false) errors.push(`${path}.${name} is not allowed`);
588
+ }
589
+ return errors;
590
+ }
591
+ function assertSchemaNode(rule, path) {
592
+ const validTypes = /* @__PURE__ */ new Set([
593
+ "object",
594
+ "array",
595
+ "string",
596
+ "number",
597
+ "integer",
598
+ "boolean",
599
+ "null"
600
+ ]);
601
+ if (rule.type !== void 0) {
602
+ const types = Array.isArray(rule.type) ? rule.type : [rule.type];
603
+ 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`);
604
+ }
605
+ if (rule.properties !== void 0) {
606
+ const properties = asRecord$2(rule.properties);
607
+ if (!properties) throw new Error(`${path}.properties must be an object`);
608
+ for (const [name, child] of Object.entries(properties)) {
609
+ const childRule = asRecord$2(child);
610
+ if (!childRule) throw new Error(`${path}.properties.${name} must be a JSON Schema object`);
611
+ assertSchemaNode(childRule, `${path}.properties.${name}`);
612
+ }
613
+ }
614
+ 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`);
615
+ if (rule.additionalProperties !== void 0 && typeof rule.additionalProperties !== "boolean") throw new Error(`${path}.additionalProperties must be a boolean`);
616
+ if (rule.items !== void 0) {
617
+ const items = asRecord$2(rule.items);
618
+ if (!items) throw new Error(`${path}.items must be a JSON Schema object`);
619
+ assertSchemaNode(items, `${path}.items`);
620
+ }
621
+ if (rule.enum !== void 0 && (!Array.isArray(rule.enum) || rule.enum.length === 0)) throw new Error(`${path}.enum must be a non-empty array`);
622
+ 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`);
623
+ for (const keyword of [
624
+ "minLength",
625
+ "maxLength",
626
+ "minItems",
627
+ "maxItems"
628
+ ]) {
629
+ const value = rule[keyword];
630
+ if (value !== void 0 && (typeof value !== "number" || !Number.isInteger(value) || value < 0)) throw new Error(`${path}.${keyword} must be a non-negative integer`);
631
+ }
632
+ if (typeof rule.minimum === "number" && typeof rule.maximum === "number" && rule.minimum > rule.maximum) throw new Error(`${path}.minimum cannot exceed maximum`);
633
+ if (typeof rule.minLength === "number" && typeof rule.maxLength === "number" && rule.minLength > rule.maxLength) throw new Error(`${path}.minLength cannot exceed maxLength`);
634
+ if (typeof rule.minItems === "number" && typeof rule.maxItems === "number" && rule.minItems > rule.maxItems) throw new Error(`${path}.minItems cannot exceed maxItems`);
635
+ }
636
+ function matchesType(value, type) {
637
+ switch (type) {
638
+ case "object": return asRecord$2(value) !== null;
639
+ case "array": return Array.isArray(value);
640
+ case "string": return typeof value === "string";
641
+ case "number": return typeof value === "number" && Number.isFinite(value);
642
+ case "integer": return typeof value === "number" && Number.isInteger(value);
643
+ case "boolean": return typeof value === "boolean";
644
+ case "null": return value === null;
645
+ default: return false;
646
+ }
647
+ }
648
+ function deepEqual(left, right) {
649
+ return JSON.stringify(left) === JSON.stringify(right);
650
+ }
651
+ function asRecord$2(value) {
652
+ return typeof value === "object" && value !== null && !Array.isArray(value) ? value : null;
653
+ }
335
654
  var FunctionDispatcher = class {
336
655
  constructor(runtime, options) {
337
656
  this.runtime = runtime;
@@ -353,7 +672,7 @@
353
672
  * Starts a named function. `caller` is the thread of the block making the call, if any; it is used
354
673
  * to detect reentrant calls.
355
674
  */
356
- invoke(name, args, caller) {
675
+ invoke(name, args, caller, returnSchema) {
357
676
  if (!this.options.knownNames().has(name)) return Promise.reject(/* @__PURE__ */ new Error(`Unknown function: ${name}`));
358
677
  const parentChain = caller ? this.byThread.get(caller)?.chain ?? [] : [];
359
678
  if (parentChain.includes(name)) return Promise.reject(/* @__PURE__ */ new Error(`Reentrant call: ${[...parentChain, name].join(" -> ")}. Use a custom block for recursion.`));
@@ -361,6 +680,7 @@
361
680
  const invocation = {
362
681
  name,
363
682
  args,
683
+ ...returnSchema === void 0 ? {} : { returnSchema },
364
684
  chain: [...parentChain, name],
365
685
  resolve,
366
686
  reject,
@@ -391,7 +711,7 @@
391
711
  returnFrom(thread, value) {
392
712
  const invocation = thread ? this.byThread.get(thread) : void 0;
393
713
  if (!invocation) throw new Error("return can only be used inside a running function.");
394
- this.settle(invocation, null, value);
714
+ this.settleWithValue(invocation, value);
395
715
  }
396
716
  cancelAll(reason) {
397
717
  for (const invocation of [...this.queue, ...this.running.values()]) this.settle(invocation, new Error(reason));
@@ -420,7 +740,7 @@
420
740
  this.step += 1;
421
741
  const starting = this.starting;
422
742
  if (starting && this.step - starting.startedAtStep > 2) this.settle(starting, /* @__PURE__ */ new Error(`Function ${starting.name} did not start. Is its script already running?`));
423
- for (const invocation of this.running.values()) if (invocation.thread && !this.runtime.threads.includes(invocation.thread)) this.settle(invocation, null, null);
743
+ for (const invocation of this.running.values()) if (invocation.thread && !this.runtime.threads.includes(invocation.thread)) this.settleWithValue(invocation, null);
424
744
  this.pump();
425
745
  }
426
746
  settle(invocation, error, value) {
@@ -435,6 +755,16 @@
435
755
  if (error) invocation.reject(error);
436
756
  else invocation.resolve(value);
437
757
  }
758
+ settleWithValue(invocation, value) {
759
+ if (invocation.returnSchema !== void 0) {
760
+ const errors = validateAgainstSchema(value, invocation.returnSchema);
761
+ if (errors.length > 0) {
762
+ this.settle(invocation, /* @__PURE__ */ new Error(`Invalid return value for ${invocation.name}: ${errors.join("; ")}`));
763
+ return;
764
+ }
765
+ }
766
+ this.settle(invocation, null, value);
767
+ }
438
768
  };
439
769
  /** Resolves a dotted path such as `items.0.name` inside parsed JSON arguments. */
440
770
  function readArgumentPath(args, path) {
@@ -510,18 +840,25 @@
510
840
  if (!FUNCTION_NAME_PATTERN.test(name)) throw new Error("function name must be 1-64 letters, digits, \"_\" or \"-\"");
511
841
  const description = readLiteralInput(block, blocks, "DESCRIPTION").trim();
512
842
  if (description.length > 1024) throw new Error(`description must be at most ${MAX_DESCRIPTION_LENGTH} characters`);
513
- const parameters = parseSchema(readLiteralInput(block, blocks, "SCHEMA"));
843
+ const parameters = parseSchema(readLiteralInput(block, blocks, "SCHEMA"), "args schema", true);
844
+ const returnsText = readOptionalLiteralInput(block, blocks, "RETURNS");
845
+ const returns = returnsText === void 0 || returnsText.trim() === "" ? void 0 : parseSchema(returnsText, "returns schema", false);
514
846
  const exportAs = String(block.fields?.EXPORT?.value ?? "none") === "tool" ? "tool" : "none";
515
847
  if (exportAs === "tool" && description.length === 0) throw new Error("a function exported as a tool needs a description");
516
848
  return {
517
849
  name,
518
850
  description,
519
851
  parameters,
852
+ ...returns ? { returns } : {},
520
853
  exportAs,
521
854
  targetName,
522
855
  blockId: block.id
523
856
  };
524
857
  }
858
+ function readOptionalLiteralInput(block, blocks, inputName) {
859
+ if (!block.inputs?.[inputName]) return void 0;
860
+ return readLiteralInput(block, blocks, inputName);
861
+ }
525
862
  function readLiteralInput(block, blocks, inputName) {
526
863
  const input = block.inputs?.[inputName];
527
864
  if (!input) throw new Error(`${inputName} is missing`);
@@ -532,80 +869,20 @@
532
869
  if (!field) throw new Error(`${inputName} is missing`);
533
870
  return String(field.value ?? "");
534
871
  }
535
- function parseSchema(text) {
872
+ function parseSchema(text, label, requireObjectType) {
536
873
  let value;
537
874
  try {
538
875
  value = JSON.parse(text);
539
876
  } catch {
540
- throw new Error("args schema must be valid JSON");
877
+ throw new Error(`${label} must be valid JSON`);
541
878
  }
542
- if (typeof value !== "object" || value === null || Array.isArray(value)) throw new Error("args schema must be a JSON object");
879
+ if (typeof value !== "object" || value === null || Array.isArray(value)) throw new Error(`${label} must be a JSON object`);
543
880
  const schema = value;
544
- if (schema.type !== "object") throw new Error("args schema must have \"type\": \"object\"");
881
+ if (requireObjectType && schema.type !== "object") throw new Error("args schema must have \"type\": \"object\"");
882
+ validateSchemaDefinition(schema, label);
545
883
  return schema;
546
884
  }
547
885
  /**
548
- * A small JSON Schema validator for function arguments. It interprets the schema at run time and
549
- * never generates code, so it also works where `eval` is unavailable (for example Cloudflare Workers).
550
- *
551
- * Supported keywords: type, properties, required, additionalProperties (boolean), items, enum,
552
- * const, minimum, maximum, minLength, maxLength, minItems, maxItems. Other keywords, such as
553
- * description and title, are ignored.
554
- */
555
- function validateAgainstSchema(value, schema, path = "$") {
556
- const rule = asRecord$2(schema);
557
- if (!rule) return [];
558
- const errors = [];
559
- if (rule.type !== void 0) {
560
- const types = Array.isArray(rule.type) ? rule.type : [rule.type];
561
- if (!types.some((type) => matchesType(value, type))) return [`${path} must be ${types.join(" or ")}`];
562
- }
563
- 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(", ")}`);
564
- if ("const" in rule && !deepEqual(rule.const, value)) errors.push(`${path} must be ${JSON.stringify(rule.const)}`);
565
- if (typeof value === "number") {
566
- if (typeof rule.minimum === "number" && value < rule.minimum) errors.push(`${path} must be >= ${rule.minimum}`);
567
- if (typeof rule.maximum === "number" && value > rule.maximum) errors.push(`${path} must be <= ${rule.maximum}`);
568
- }
569
- if (typeof value === "string") {
570
- const length = [...value].length;
571
- if (typeof rule.minLength === "number" && length < rule.minLength) errors.push(`${path} must have at least ${rule.minLength} characters`);
572
- if (typeof rule.maxLength === "number" && length > rule.maxLength) errors.push(`${path} must have at most ${rule.maxLength} characters`);
573
- }
574
- if (Array.isArray(value)) {
575
- if (typeof rule.minItems === "number" && value.length < rule.minItems) errors.push(`${path} must have at least ${rule.minItems} items`);
576
- if (typeof rule.maxItems === "number" && value.length > rule.maxItems) errors.push(`${path} must have at most ${rule.maxItems} items`);
577
- if (rule.items !== void 0) value.forEach((item, index) => errors.push(...validateAgainstSchema(item, rule.items, `${path}[${index}]`)));
578
- }
579
- const object = asRecord$2(value);
580
- if (object) {
581
- const properties = asRecord$2(rule.properties) ?? {};
582
- if (Array.isArray(rule.required)) {
583
- for (const name of rule.required) if (typeof name === "string" && !(name in object)) errors.push(`${path}.${name} is required`);
584
- }
585
- for (const [name, child] of Object.entries(object)) if (name in properties) errors.push(...validateAgainstSchema(child, properties[name], `${path}.${name}`));
586
- else if (rule.additionalProperties === false) errors.push(`${path}.${name} is not allowed`);
587
- }
588
- return errors;
589
- }
590
- function matchesType(value, type) {
591
- switch (type) {
592
- case "object": return asRecord$2(value) !== null;
593
- case "array": return Array.isArray(value);
594
- case "string": return typeof value === "string";
595
- case "number": return typeof value === "number" && Number.isFinite(value);
596
- case "integer": return typeof value === "number" && Number.isInteger(value);
597
- case "boolean": return typeof value === "boolean";
598
- case "null": return value === null;
599
- default: return false;
600
- }
601
- }
602
- function deepEqual(left, right) {
603
- return JSON.stringify(left) === JSON.stringify(right);
604
- }
605
- function asRecord$2(value) {
606
- return typeof value === "object" && value !== null && !Array.isArray(value) ? value : null;
607
- }
608
- /**
609
886
  * Composition API: named functions without TurboWarp block definitions.
610
887
  *
611
888
  * A consumer extension owns its `define function` hat (and its opcode) and forwards the hat
@@ -652,7 +929,7 @@
652
929
  if (options.exportedOnly && definition.exportAs !== "tool") return Promise.reject(/* @__PURE__ */ new Error(`Function ${trimmed} is not exported as a tool.`));
653
930
  const errors = validateAgainstSchema(args, definition.parameters);
654
931
  if (errors.length > 0) return Promise.reject(/* @__PURE__ */ new Error(`Invalid arguments for ${trimmed}: ${errors.join("; ")}`));
655
- return this.dispatcher.invoke(trimmed, args, options.caller);
932
+ return this.dispatcher.invoke(trimmed, args, options.caller, definition.returns);
656
933
  }
657
934
  start(name, args, options = {}) {
658
935
  const id = `p_${this.nextPromiseId++}`;
@@ -1422,6 +1699,7 @@
1422
1699
  var OpenAIRealtimeExtension = class {
1423
1700
  constructor(deps) {
1424
1701
  this.lastErrorMessage = "";
1702
+ this.fixedEditorRuntime = deps.runtime;
1425
1703
  this.realtime = createRealtimeComposition({
1426
1704
  ...deps,
1427
1705
  functionHatOpcode: DEFINE_FUNCTION_OPCODE
@@ -1433,7 +1711,7 @@
1433
1711
  });
1434
1712
  }
1435
1713
  getInfo() {
1436
- return {
1714
+ const info = {
1437
1715
  id: extensionConfig.id,
1438
1716
  name: Scratch.translate(block_definitions_default.extensionName),
1439
1717
  docsURI: extensionConfig.docsURI,
@@ -1444,6 +1722,8 @@
1444
1722
  items: [...menu.items]
1445
1723
  }]))
1446
1724
  };
1725
+ this.fixedEditorsDispose ?? (this.fixedEditorsDispose = registerFixedInputEditors(Scratch, this.fixedEditorRuntime, info.blocks));
1726
+ return info;
1447
1727
  }
1448
1728
  configureRelay(args) {
1449
1729
  this.record(() => this.realtime.configureRelay(Scratch.Cast.toString(args.ENDPOINT)));
@@ -7,6 +7,8 @@ export type RealtimeExtensionDependencies = Omit<RealtimeCompositionOptions, 'fu
7
7
  type Args = Record<string, unknown>;
8
8
  /** Block surface over the Realtime composition. */
9
9
  export declare class OpenAIRealtimeExtension implements TurboWarpExtension {
10
+ private readonly fixedEditorRuntime;
11
+ private fixedEditorsDispose;
10
12
  private lastErrorMessage;
11
13
  private readonly realtime;
12
14
  constructor(deps: RealtimeExtensionDependencies);
@@ -0,0 +1,15 @@
1
+ import type { FixedInputEditorOptions, JsonValue, LiteralValue } from "@kubohiroya/turbowarp-extension-data-editor";
2
+ interface InputSchema {
3
+ readonly type: string;
4
+ readonly enum?: readonly (string | number)[];
5
+ readonly minimum?: number;
6
+ readonly maximum?: number;
7
+ readonly exclusiveMinimum?: number;
8
+ }
9
+ export declare function readNumber(value: LiteralValue): number;
10
+ export declare function newNumberToken(value: JsonValue): string;
11
+ export declare function candidateValid(_opcode: string, _argument: string, schema: InputSchema, value: LiteralValue): boolean;
12
+ export declare function fixedInputEditorOptions(): readonly FixedInputEditorOptions[];
13
+ /** Register only visible static contracts; ordinary composition consumers load no editor runtime. */
14
+ export declare function registerFixedInputEditors(scratch: unknown, runtime: unknown, visibleBlocks: readonly unknown[]): (() => void) | undefined;
15
+ export {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kubohiroya/turbowarp-openai-realtime-api",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
4
4
  "description": "A TurboWarp extension for the OpenAI Realtime API, using a localhost relay for credentials.",
5
5
  "author": "Hiroya Kubo <hiroya@cuc.ac.jp>",
6
6
  "license": "MPL-2.0",
@@ -26,11 +26,11 @@
26
26
  "type": "module",
27
27
  "files": [
28
28
  "dist/",
29
- "schemas/",
30
29
  "src/",
31
30
  "README.md",
32
31
  "README.ja.md",
33
- "LICENSE"
32
+ "LICENSE",
33
+ "schemas"
34
34
  ],
35
35
  "publishConfig": {
36
36
  "access": "public",
@@ -56,14 +56,16 @@
56
56
  },
57
57
  "devDependencies": {
58
58
  "@eslint/js": "^9.39.5",
59
- "@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",
60
61
  "@types/node": "^24.13.3",
61
62
  "eslint": "^9.39.5",
62
63
  "jiti": "^2.7.0",
63
64
  "typescript": "^5.9.3",
64
65
  "typescript-eslint": "^8.66.0",
65
66
  "vite": "^8.2.2",
66
- "vitest": "^5.0.0"
67
+ "vitest": "^5.0.0",
68
+ "@kubohiroya/turbowarp-extension-data-editor": "0.2.1"
67
69
  },
68
70
  "exports": {
69
71
  "./composition": {
@@ -74,6 +76,12 @@
74
76
  "./package.json": "./package.json"
75
77
  },
76
78
  "dependencies": {
77
- "@kubohiroya/turbowarp-named-functions": "0.1.0"
79
+ "@kubohiroya/turbowarp-named-functions": "0.1.1"
80
+ },
81
+ "gitHead": "81da38683ae77127544a3dd5d0dbab1d09b0d284",
82
+ "x-turbowarp-source": {
83
+ "revision": "81da38683ae77127544a3dd5d0dbab1d09b0d284",
84
+ "revisionRole": "base-commit",
85
+ "sourceState": "local-release-overlay"
78
86
  }
79
87
  }
@@ -0,0 +1,67 @@
1
+ {
2
+ "$schema": "http://json-schema.org/draft-07/schema#",
3
+ "$id": "https://kubohiroya.github.io/turbowarp-openai-realtime-api/schemas/block-editor-fixed-inputs.schema.json",
4
+ "title": "turbowarp-openai-realtime-api fixed editing contracts",
5
+ "$defs": {
6
+ "setOutputMode": {
7
+ "type": "object",
8
+ "properties": {
9
+ "MODE": {
10
+ "type": "string",
11
+ "enum": ["audio", "text"]
12
+ }
13
+ },
14
+ "additionalProperties": false
15
+ },
16
+ "setSessionTimeLimit": {
17
+ "type": "object",
18
+ "properties": {
19
+ "SECONDS": {
20
+ "type": "number",
21
+ "minimum": 0
22
+ }
23
+ },
24
+ "additionalProperties": false
25
+ },
26
+ "connect": {
27
+ "type": "object",
28
+ "properties": {
29
+ "MICROPHONE": {
30
+ "type": "string",
31
+ "enum": ["on", "off"]
32
+ }
33
+ },
34
+ "additionalProperties": false
35
+ },
36
+ "defineFunction": {
37
+ "type": "object",
38
+ "properties": {
39
+ "EXPORT": {
40
+ "type": "string",
41
+ "enum": ["tool", "none"]
42
+ }
43
+ },
44
+ "additionalProperties": false
45
+ },
46
+ "usageValue": {
47
+ "type": "object",
48
+ "properties": {
49
+ "FIELD": {
50
+ "type": "string",
51
+ "enum": [
52
+ "costUSD",
53
+ "responses",
54
+ "inputTokens",
55
+ "outputTokens",
56
+ "cachedInputTokens",
57
+ "textInputTokens",
58
+ "audioInputTokens",
59
+ "textOutputTokens",
60
+ "audioOutputTokens"
61
+ ]
62
+ }
63
+ },
64
+ "additionalProperties": false
65
+ }
66
+ }
67
+ }
package/src/extension.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import {registerFixedInputEditors} from './fixed-input-editors.js';
1
2
  import {extensionConfig} from './config';
2
3
  import definitions from './block-definitions.json';
3
4
  import {
@@ -61,10 +62,14 @@ const USAGE_FIELDS: Record<string, (usage: UsageTotals) => number> = {
61
62
 
62
63
  /** Block surface over the Realtime composition. */
63
64
  export class OpenAIRealtimeExtension implements TurboWarpExtension {
65
+ private readonly fixedEditorRuntime: unknown;
66
+ private fixedEditorsDispose: (() => void) | undefined;
67
+
64
68
  private lastErrorMessage = '';
65
69
  private readonly realtime: RealtimeComposition;
66
70
 
67
71
  public constructor(deps: RealtimeExtensionDependencies) {
72
+ this.fixedEditorRuntime = deps.runtime;
68
73
  this.realtime = createRealtimeComposition({...deps, functionHatOpcode: DEFINE_FUNCTION_OPCODE});
69
74
  this.realtime.subscribe((event) => {
70
75
  if (event.type === 'response') deps.runtime.startHats(RESPONSE_DONE_OPCODE);
@@ -74,7 +79,7 @@ export class OpenAIRealtimeExtension implements TurboWarpExtension {
74
79
  }
75
80
 
76
81
  public getInfo(): Record<string, unknown> {
77
- return {
82
+ const info = {
78
83
  id: extensionConfig.id,
79
84
  name: Scratch.translate(definitions.extensionName),
80
85
  docsURI: extensionConfig.docsURI,
@@ -87,6 +92,8 @@ export class OpenAIRealtimeExtension implements TurboWarpExtension {
87
92
  ])
88
93
  )
89
94
  };
95
+ this.fixedEditorsDispose ??= registerFixedInputEditors(Scratch, this.fixedEditorRuntime, info.blocks);
96
+ return info;
90
97
  }
91
98
 
92
99
  // ---- relay ------------------------------------------------------------------------------
@@ -0,0 +1,214 @@
1
+ import type {
2
+ FixedInputBinding,
3
+ FixedInputEditorOptions,
4
+ JsonValue,
5
+ LiteralValue,
6
+ } from "@kubohiroya/turbowarp-extension-data-editor";
7
+ import type { SchemaBundle } from "@kubohiroya/turbowarp-extension-data-editor/schema";
8
+ import schemas from "../schemas/block-editor-fixed-inputs.schema.json" with { type: "json" };
9
+ interface InputSchema {
10
+ readonly type: string;
11
+ readonly enum?: readonly (string | number)[];
12
+ readonly minimum?: number;
13
+ readonly maximum?: number;
14
+ readonly exclusiveMinimum?: number;
15
+ }
16
+ const contracts = schemas.$defs as Readonly<
17
+ Record<string, { readonly properties: Readonly<Record<string, InputSchema>> }>
18
+ >;
19
+ const repository = "turbowarp-openai-realtime-api";
20
+ const extensionId = "kubohiroyaopenairealtime";
21
+ const token = /^-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?$/u;
22
+ export function readNumber(value: LiteralValue): number {
23
+ if (typeof value !== "string" && typeof value !== "number")
24
+ throw new TypeError("Invalid numeric projection.");
25
+ if (typeof value === "string" && value.trim() === "")
26
+ throw new TypeError("Existing blank field is readonly.");
27
+ const number = Number(value);
28
+ if (!Number.isFinite(number))
29
+ throw new TypeError("Existing nonfinite field is readonly.");
30
+ return number;
31
+ }
32
+ export function newNumberToken(value: JsonValue): string {
33
+ if (typeof value === "number") {
34
+ if (!Number.isFinite(value)) throw new TypeError("Invalid new number.");
35
+ return Object.is(value, -0) ? "-0" : String(value);
36
+ }
37
+ if (
38
+ typeof value !== "string" ||
39
+ !token.test(value.trim()) ||
40
+ !Number.isFinite(Number(value))
41
+ )
42
+ throw new TypeError("Invalid new number.");
43
+ return value.trim();
44
+ }
45
+ function existingChoice(_opcode: string, value: LiteralValue): string {
46
+ if (typeof value !== "string")
47
+ throw new TypeError("Invalid string projection.");
48
+ return value;
49
+ }
50
+ export function candidateValid(
51
+ _opcode: string,
52
+ _argument: string,
53
+ schema: InputSchema,
54
+ value: LiteralValue,
55
+ ): boolean {
56
+ if (schema.type === "number" || schema.type === "integer") {
57
+ let number;
58
+ try {
59
+ number = readNumber(value);
60
+ } catch {
61
+ return false;
62
+ }
63
+ if (schema.type === "integer" && !Number.isInteger(number)) return false;
64
+ if (schema.minimum !== undefined && number < schema.minimum) return false;
65
+ if (schema.maximum !== undefined && number > schema.maximum) return false;
66
+ if (
67
+ schema.exclusiveMinimum !== undefined &&
68
+ number <= schema.exclusiveMinimum
69
+ )
70
+ return false;
71
+ if (schema.enum && !schema.enum!.includes(number)) return false;
72
+ return true;
73
+ }
74
+ return typeof value === "string" && schema.enum!.includes(value);
75
+ }
76
+ export function fixedInputEditorOptions(): readonly FixedInputEditorOptions[] {
77
+ return Object.entries(contracts).map(([opcode, contract]) => ({
78
+ apiVersion: 1,
79
+ extensionId,
80
+ editorId: `${extensionId}.fixed.${opcode}`,
81
+ opcodes: [`${extensionId}_${opcode}`],
82
+ contractId: `${repository}.${opcode}.fixed`,
83
+ contractRevision: "fixed-inputs-v1",
84
+ validationContext: () => ({
85
+ consumerId: repository,
86
+ nowMs: 0,
87
+ settings: null,
88
+ }),
89
+ bindings: Object.entries(contract.properties).map(
90
+ ([argument, schema]): FixedInputBinding => {
91
+ const numeric = schema.type === "number" || schema.type === "integer";
92
+ const source = {
93
+ repository,
94
+ path: "schemas/block-editor-fixed-inputs.schema.json",
95
+ symbol: `/$defs/${opcode}/properties/${argument}`,
96
+ };
97
+ return {
98
+ argument,
99
+ schemaBundle: {
100
+ identity: {
101
+ ownerId: repository,
102
+ contractId: `${opcode}.${argument}`,
103
+ revision: "fixed-inputs-v1",
104
+ variantId: "fixed",
105
+ },
106
+ dialect: "draft-07",
107
+ root: {
108
+ retrievalUri: `${schemas.$id}?binding=${opcode}.${argument}`,
109
+ document: schema as unknown as SchemaBundle["root"]["document"],
110
+ artifact: { role: "canonical-schema", source },
111
+ },
112
+ resources: [],
113
+ provenance: {
114
+ canonicalSources: [
115
+ source,
116
+ { repository, path: "src/block-definitions.json" },
117
+ { repository, path: "src/extension.ts", symbol: opcode },
118
+ ],
119
+ generatedFiles: [],
120
+ referenceSchemas: [],
121
+ generationSources: [],
122
+ },
123
+ },
124
+ control: numeric
125
+ ? { kind: "number" }
126
+ : {
127
+ kind: "enum",
128
+ choices: schema.enum!.map((value) => ({
129
+ value,
130
+ label: String(value),
131
+ })),
132
+ },
133
+ read: (value) =>
134
+ numeric ? readNumber(value) : existingChoice(opcode, value),
135
+ encode: (value) => {
136
+ if (numeric) return newNumberToken(value);
137
+ if (typeof value !== "string" || !schema.enum!.includes(value))
138
+ throw new TypeError("Invalid new enum value.");
139
+ return value;
140
+ },
141
+ validateCandidate: (value) =>
142
+ candidateValid(opcode, argument, schema, value)
143
+ ? []
144
+ : [
145
+ {
146
+ path: argument,
147
+ message: "Check this value before saving.",
148
+ },
149
+ ],
150
+ };
151
+ },
152
+ ),
153
+ }));
154
+ }
155
+
156
+ interface RegistrationRuntime {
157
+ on?(event: string, listener: () => void): void;
158
+ off?(event: string, listener: () => void): void;
159
+ }
160
+ /** Register only visible static contracts; ordinary composition consumers load no editor runtime. */
161
+ export function registerFixedInputEditors(
162
+ scratch: unknown,
163
+ runtime: unknown,
164
+ visibleBlocks: readonly unknown[],
165
+ ): (() => void) | undefined {
166
+ const api = (
167
+ scratch as {
168
+ gui?: {
169
+ blockEditors?: {
170
+ apiVersion?: number;
171
+ registerFixedInputEditor?: (
172
+ options: FixedInputEditorOptions,
173
+ ) => () => void;
174
+ };
175
+ };
176
+ }
177
+ ).gui?.blockEditors;
178
+ if (
179
+ api?.apiVersion !== 1 ||
180
+ typeof api.registerFixedInputEditor !== "function"
181
+ )
182
+ return undefined;
183
+ const visibleOpcodes = new Set(
184
+ visibleBlocks.flatMap((block) => {
185
+ if (typeof block !== "object" || block === null || !("opcode" in block))
186
+ return [];
187
+ return typeof block.opcode === "string" ? [block.opcode] : [];
188
+ }),
189
+ );
190
+ const events = runtime as RegistrationRuntime | undefined;
191
+ const removers: (() => void)[] = [];
192
+ let active = true;
193
+ const dispose = () => {
194
+ if (!active) return;
195
+ active = false;
196
+ events?.off?.("RUNTIME_DISPOSED", dispose);
197
+ for (const remove of removers.splice(0).reverse()) remove();
198
+ };
199
+ try {
200
+ for (const options of fixedInputEditorOptions()) {
201
+ if (
202
+ options.opcodes.some((opcode) =>
203
+ visibleOpcodes.has(opcode.slice(extensionId.length + 1)),
204
+ )
205
+ )
206
+ removers.push(api.registerFixedInputEditor.call(api, options));
207
+ }
208
+ events?.on?.("RUNTIME_DISPOSED", dispose);
209
+ } catch (error) {
210
+ dispose();
211
+ throw error;
212
+ }
213
+ return dispose;
214
+ }
@@ -1,30 +0,0 @@
1
- import type { Plugin } from 'vite';
2
- export declare const EXTENSION_MANIFEST_FORMAT_VERSION: 1;
3
- export interface ExtensionManifestArgument {
4
- id: string;
5
- type: string;
6
- menu?: string;
7
- }
8
- export interface ExtensionManifestBlock {
9
- opcode: string;
10
- blockType: string;
11
- arguments: ExtensionManifestArgument[];
12
- }
13
- export interface ExtensionManifestMenu {
14
- id: string;
15
- acceptReporters: boolean;
16
- }
17
- export interface ExtensionManifest {
18
- formatVersion: typeof EXTENSION_MANIFEST_FORMAT_VERSION;
19
- id: string;
20
- blocks: ExtensionManifestBlock[];
21
- menus: ExtensionManifestMenu[];
22
- }
23
- export interface ExtensionManifestPluginOptions {
24
- id: string;
25
- definitions: unknown;
26
- fileName?: string;
27
- }
28
- export declare function createExtensionManifest(id: string, definitions: unknown): ExtensionManifest;
29
- export declare function serializeExtensionManifest(id: string, definitions: unknown): string;
30
- export declare function extensionManifestPlugin(options: ExtensionManifestPluginOptions): Plugin;
@@ -1,49 +0,0 @@
1
- {
2
- "$schema": "https://json-schema.org/draft/2020-12/schema",
3
- "$id": "https://raw.githubusercontent.com/kubohiroya/turbowarp-openai-realtime-api/main/schemas/extension-manifest.schema.json",
4
- "title": "TurboWarp Extension API Manifest",
5
- "type": "object",
6
- "additionalProperties": false,
7
- "required": ["formatVersion", "id", "blocks", "menus"],
8
- "properties": {
9
- "formatVersion": {"const": 1},
10
- "id": {"type": "string", "pattern": "^[a-z0-9]+$"},
11
- "blocks": {
12
- "type": "array",
13
- "items": {
14
- "type": "object",
15
- "additionalProperties": false,
16
- "required": ["opcode", "blockType", "arguments"],
17
- "properties": {
18
- "opcode": {"type": "string", "minLength": 1},
19
- "blockType": {"type": "string", "minLength": 1},
20
- "arguments": {
21
- "type": "array",
22
- "items": {
23
- "type": "object",
24
- "additionalProperties": false,
25
- "required": ["id", "type"],
26
- "properties": {
27
- "id": {"type": "string", "minLength": 1},
28
- "type": {"type": "string", "minLength": 1},
29
- "menu": {"type": "string", "minLength": 1}
30
- }
31
- }
32
- }
33
- }
34
- }
35
- },
36
- "menus": {
37
- "type": "array",
38
- "items": {
39
- "type": "object",
40
- "additionalProperties": false,
41
- "required": ["id", "acceptReporters"],
42
- "properties": {
43
- "id": {"type": "string", "minLength": 1},
44
- "acceptReporters": {"type": "boolean"}
45
- }
46
- }
47
- }
48
- }
49
- }
@@ -1,149 +0,0 @@
1
- import type {Plugin} from 'vite';
2
-
3
- export const EXTENSION_MANIFEST_FORMAT_VERSION = 1 as const;
4
-
5
- export interface ExtensionManifestArgument {
6
- id: string;
7
- type: string;
8
- menu?: string;
9
- }
10
-
11
- export interface ExtensionManifestBlock {
12
- opcode: string;
13
- blockType: string;
14
- arguments: ExtensionManifestArgument[];
15
- }
16
-
17
- export interface ExtensionManifestMenu {
18
- id: string;
19
- acceptReporters: boolean;
20
- }
21
-
22
- export interface ExtensionManifest {
23
- formatVersion: typeof EXTENSION_MANIFEST_FORMAT_VERSION;
24
- id: string;
25
- blocks: ExtensionManifestBlock[];
26
- menus: ExtensionManifestMenu[];
27
- }
28
-
29
- export interface ExtensionManifestPluginOptions {
30
- id: string;
31
- definitions: unknown;
32
- fileName?: string;
33
- }
34
-
35
- export function createExtensionManifest(id: string, definitions: unknown): ExtensionManifest {
36
- if (!/^[a-z0-9]+$/.test(id)) {
37
- throw new TypeError('Extension manifest ID must contain only lowercase letters and numbers.');
38
- }
39
-
40
- const source = requireRecord(definitions, 'Block definitions');
41
- const sourceBlocks = source.blocks;
42
- if (!Array.isArray(sourceBlocks)) {
43
- throw new TypeError('Block definitions must contain a blocks array.');
44
- }
45
-
46
- const menus = normalizeMenus(source.menus);
47
- const menuIds = new Set(menus.map((menu) => menu.id));
48
- const seenOpcodes = new Set<string>();
49
- const blocks = sourceBlocks.map((block, index) => {
50
- const normalized = normalizeBlock(block, index, menuIds);
51
- if (seenOpcodes.has(normalized.opcode)) {
52
- throw new TypeError(`Duplicate block opcode: ${normalized.opcode}`);
53
- }
54
- seenOpcodes.add(normalized.opcode);
55
- return normalized;
56
- });
57
-
58
- return {
59
- formatVersion: EXTENSION_MANIFEST_FORMAT_VERSION,
60
- id,
61
- blocks: blocks.sort((left, right) => compareIds(left.opcode, right.opcode)),
62
- menus
63
- };
64
- }
65
-
66
- export function serializeExtensionManifest(id: string, definitions: unknown): string {
67
- return `${JSON.stringify(createExtensionManifest(id, definitions), null, 2)}\n`;
68
- }
69
-
70
- export function extensionManifestPlugin(options: ExtensionManifestPluginOptions): Plugin {
71
- return {
72
- name: 'extension-api-manifest',
73
- apply: 'build',
74
- enforce: 'post',
75
- generateBundle() {
76
- this.emitFile({
77
- type: 'asset',
78
- fileName: options.fileName ?? 'extension-manifest.json',
79
- source: serializeExtensionManifest(options.id, options.definitions)
80
- });
81
- }
82
- };
83
- }
84
-
85
- function normalizeBlock(
86
- value: unknown,
87
- index: number,
88
- menuIds: ReadonlySet<string>
89
- ): ExtensionManifestBlock {
90
- const block = requireRecord(value, `Block at index ${index}`);
91
- const opcode = requireNonEmptyString(block.opcode, `Block at index ${index} opcode`);
92
- const blockType = requireNonEmptyString(block.blockType, `Block ${opcode} blockType`);
93
- const sourceArguments = block.arguments ?? {};
94
- const argumentRecord = requireRecord(sourceArguments, `Block ${opcode} arguments`);
95
- const argumentsList = Object.entries(argumentRecord).map(([argumentId, argument]) => {
96
- requireNonEmptyString(argumentId, `Block ${opcode} argument ID`);
97
- const definition = requireRecord(argument, `Block ${opcode} argument ${argumentId}`);
98
- const type = requireNonEmptyString(
99
- definition.type,
100
- `Block ${opcode} argument ${argumentId} type`
101
- );
102
- const menu = definition.menu;
103
- if (menu !== undefined && (typeof menu !== 'string' || !menuIds.has(menu))) {
104
- throw new TypeError(`Block ${opcode} argument ${argumentId} references unknown menu: ${menu}`);
105
- }
106
- return menu === undefined ? {id: argumentId, type} : {id: argumentId, type, menu};
107
- });
108
-
109
- return {
110
- opcode,
111
- blockType,
112
- arguments: argumentsList.sort((left, right) => compareIds(left.id, right.id))
113
- };
114
- }
115
-
116
- function normalizeMenus(value: unknown): ExtensionManifestMenu[] {
117
- const menuRecord = requireRecord(value ?? {}, 'Block definition menus');
118
- return Object.entries(menuRecord)
119
- .map(([id, menu]) => {
120
- requireNonEmptyString(id, 'Menu ID');
121
- const definition = requireRecord(menu, `Menu ${id}`);
122
- const acceptReporters = definition.acceptReporters ?? false;
123
- if (typeof acceptReporters !== 'boolean') {
124
- throw new TypeError(`Menu ${id} acceptReporters must be a boolean.`);
125
- }
126
- return {id, acceptReporters};
127
- })
128
- .sort((left, right) => compareIds(left.id, right.id));
129
- }
130
-
131
- function requireRecord(value: unknown, label: string): Record<string, unknown> {
132
- if (typeof value !== 'object' || value === null || Array.isArray(value)) {
133
- throw new TypeError(`${label} must be an object.`);
134
- }
135
- return value as Record<string, unknown>;
136
- }
137
-
138
- function requireNonEmptyString(value: unknown, label: string): string {
139
- if (typeof value !== 'string' || value.length === 0) {
140
- throw new TypeError(`${label} must be a non-empty string.`);
141
- }
142
- return value;
143
- }
144
-
145
- function compareIds(left: string, right: string): number {
146
- if (left < right) return -1;
147
- if (left > right) return 1;
148
- return 0;
149
- }