tempest-react-sdk 0.33.2 → 0.35.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.
Files changed (87) hide show
  1. package/README.md +5 -3
  2. package/dist/components/AIChat/AIChat.cjs +2 -0
  3. package/dist/components/AIChat/AIChat.cjs.map +1 -0
  4. package/dist/components/AIChat/AIChat.js +141 -0
  5. package/dist/components/AIChat/AIChat.js.map +1 -0
  6. package/dist/components/AIChat/AIChat.module.cjs +2 -0
  7. package/dist/components/AIChat/AIChat.module.cjs.map +1 -0
  8. package/dist/components/AIChat/AIChat.module.js +58 -0
  9. package/dist/components/AIChat/AIChat.module.js.map +1 -0
  10. package/dist/components/AIChat/AIChatComposer.cjs +2 -0
  11. package/dist/components/AIChat/AIChatComposer.cjs.map +1 -0
  12. package/dist/components/AIChat/AIChatComposer.js +87 -0
  13. package/dist/components/AIChat/AIChatComposer.js.map +1 -0
  14. package/dist/components/AIChat/AIChatTurn.cjs +3 -0
  15. package/dist/components/AIChat/AIChatTurn.cjs.map +1 -0
  16. package/dist/components/AIChat/AIChatTurn.js +217 -0
  17. package/dist/components/AIChat/AIChatTurn.js.map +1 -0
  18. package/dist/components/AIChat/ai-chat-turns.cjs +2 -0
  19. package/dist/components/AIChat/ai-chat-turns.cjs.map +1 -0
  20. package/dist/components/AIChat/ai-chat-turns.js +90 -0
  21. package/dist/components/AIChat/ai-chat-turns.js.map +1 -0
  22. package/dist/perf/cache-size.cjs +2 -0
  23. package/dist/perf/cache-size.cjs.map +1 -0
  24. package/dist/perf/cache-size.js +16 -0
  25. package/dist/perf/cache-size.js.map +1 -0
  26. package/dist/perf/device.cjs +2 -0
  27. package/dist/perf/device.cjs.map +1 -0
  28. package/dist/perf/device.js +22 -0
  29. package/dist/perf/device.js.map +1 -0
  30. package/dist/perf/format.cjs +2 -0
  31. package/dist/perf/format.cjs.map +1 -0
  32. package/dist/perf/format.js +8 -0
  33. package/dist/perf/format.js.map +1 -0
  34. package/dist/perf/profiler.cjs +2 -0
  35. package/dist/perf/profiler.cjs.map +1 -0
  36. package/dist/perf/profiler.js +46 -0
  37. package/dist/perf/profiler.js.map +1 -0
  38. package/dist/styles.css +1 -1
  39. package/dist/tempest-react-sdk.cjs +1 -1
  40. package/dist/tempest-react-sdk.d.ts +626 -9
  41. package/dist/tempest-react-sdk.js +122 -114
  42. package/dist/vision/core/timing.cjs +2 -0
  43. package/dist/vision/core/timing.cjs.map +1 -0
  44. package/dist/vision/core/timing.js +24 -0
  45. package/dist/vision/core/timing.js.map +1 -0
  46. package/dist/vision/index.cjs +1 -1
  47. package/dist/vision/index.cjs.map +1 -1
  48. package/dist/vision/index.js +16 -15
  49. package/dist/vision/index.js.map +1 -1
  50. package/dist/vision/postprocess/detection.cjs +1 -1
  51. package/dist/vision/postprocess/detection.cjs.map +1 -1
  52. package/dist/vision/postprocess/detection.js +2 -2
  53. package/dist/vision/postprocess/detection.js.map +1 -1
  54. package/dist/vision/postprocess/segmentation.cjs +1 -1
  55. package/dist/vision/postprocess/segmentation.cjs.map +1 -1
  56. package/dist/vision/postprocess/segmentation.js +1 -1
  57. package/dist/vision/postprocess/segmentation.js.map +1 -1
  58. package/dist/vision/results.cjs +1 -1
  59. package/dist/vision/results.cjs.map +1 -1
  60. package/dist/vision/results.js +18 -13
  61. package/dist/vision/results.js.map +1 -1
  62. package/dist/vision/tasks/classifier.cjs +1 -1
  63. package/dist/vision/tasks/classifier.cjs.map +1 -1
  64. package/dist/vision/tasks/classifier.js +46 -39
  65. package/dist/vision/tasks/classifier.js.map +1 -1
  66. package/dist/vision/tasks/detector.cjs +1 -1
  67. package/dist/vision/tasks/detector.cjs.map +1 -1
  68. package/dist/vision/tasks/detector.js +40 -33
  69. package/dist/vision/tasks/detector.js.map +1 -1
  70. package/dist/vision/tasks/segmenter.cjs +1 -1
  71. package/dist/vision/tasks/segmenter.cjs.map +1 -1
  72. package/dist/vision/tasks/segmenter.js +35 -28
  73. package/dist/vision/tasks/segmenter.js.map +1 -1
  74. package/dist/vision.cjs +1 -1
  75. package/dist/vision.d.ts +68 -10
  76. package/dist/vision.js +19 -18
  77. package/dist/ws/create-web-socket.cjs +1 -1
  78. package/dist/ws/create-web-socket.cjs.map +1 -1
  79. package/dist/ws/create-web-socket.js +54 -37
  80. package/dist/ws/create-web-socket.js.map +1 -1
  81. package/dist/ws/use-web-socket.cjs +1 -1
  82. package/dist/ws/use-web-socket.cjs.map +1 -1
  83. package/dist/ws/use-web-socket.js +49 -18
  84. package/dist/ws/use-web-socket.js.map +1 -1
  85. package/package.json +1 -1
  86. package/template/src/lib/api.ts +27 -5
  87. package/template/src/stores/auth.ts +14 -0
@@ -1 +1 @@
1
- {"version":3,"file":"segmenter.cjs","names":[],"sources":["../../../src/vision/tasks/segmenter.ts"],"sourcesContent":["/**\n * Instance-segmentation task using YOLO seg ONNX models (v8-seg / v11-seg / ...).\n */\n\nimport type * as ort from \"onnxruntime-web\";\n\nimport { type ModelSource, type OrtSessionOptions, OrtSession } from \"../core/session\";\nimport { type ImageInput, loadImage } from \"../io/image\";\nimport { type LabelSpec, resolveLabels } from \"../labels\";\nimport { decodeYoloSeg } from \"../postprocess/segmentation\";\nimport { letterbox, toCHW, toFloat32, toFloat32Tensor } from \"../preprocess/image\";\nimport { Boxes, Masks, SegmentationResults } from \"../results\";\nimport { VisionTask } from \"./base\";\nimport { type BoundingBox, type SegmentationResult, Mask, RGBImage } from \"../types\";\n\n/**\n * Decoder family for the segmentation head.\n *\n * - `\"yolo-seg\"`: YOLO instance-segmentation head with two outputs —\n * `[1, 4 + nc + nm, N]` per-anchor predictions plus `[1, nm, mh, mw]`\n * prototype masks. Covers YOLOv8-seg, v11-seg, v26-seg.\n *\n * The SDK does **not** auto-detect this — the caller is responsible for\n * picking a head that matches their export.\n */\nexport type SegmenterHead = \"yolo-seg\";\n\nexport interface SegmenterOptions extends OrtSessionOptions {\n /**\n * Decoder family for the segmentation head. Default `\"yolo-seg\"` covers\n * YOLOv8-seg/v11-seg/v26-seg.\n */\n readonly head?: SegmenterHead;\n /** Class label spec — see {@link resolveLabels}. Defaults to the COCO 80-class preset. */\n readonly labels?: LabelSpec;\n /** Number of classes — used to validate the supplied labels. */\n readonly numClasses?: number;\n /** Model input `[width, height]` for letterboxing. Defaults to `[640, 640]`. */\n readonly inputSize?: readonly [number, number];\n /** Default minimum class score to keep a candidate. */\n readonly confThreshold?: number;\n /** Default IoU threshold for non-maximum suppression. */\n readonly iouThreshold?: number;\n /** Maximum number of instances per image. */\n readonly maxDetections?: number;\n /** Probability cutoff applied to soft masks. Defaults to `0.5`. */\n readonly maskThreshold?: number;\n}\n\nexport interface SegmenterPredictOptions {\n readonly confThreshold?: number;\n readonly iouThreshold?: number;\n /**\n * If set, keep only instances whose `classId` is in this list.\n * Mirrors Ultralytics' `model.predict(img, classes=[0, 16])`.\n */\n readonly classes?: readonly number[];\n}\n\n/**\n * Instance segmenter for YOLO seg ONNX models (v8-seg / v11-seg / ...).\n *\n * The model is expected to expose two outputs:\n *\n * 1. `output0`: `(1, 4 + numClasses + numMaskCoefs, numAnchors)` — per-anchor\n * predictions (boxes, class scores, mask coefficients).\n * 2. `output1`: `(1, numMaskCoefs, maskH, maskW)` — prototype masks.\n *\n * `predict()` returns `Promise<SegmentationResults[]>` (length 1 for a\n * single image), mirroring Ultralytics' API. The envelope exposes:\n *\n * - `boxes`: bulk numpy view (`xyxy`, `xywh`, `xyxyn`, `xywhn`, `cls`, `conf`).\n * - `masks`: per-instance binary masks cropped to each box.\n * - per-instance {@link SegmentationResult} via iteration.\n *\n * @example\n * ```typescript\n * const seg = await Segmenter.create(\"/models/yolov8n-seg.onnx\");\n * const r = (await seg.predict(\"/images/street.jpg\"))[0];\n * for (const inst of r) {\n * console.log(inst.cls, inst.conf, inst.box.xyxy);\n * }\n * ```\n */\nexport class Segmenter extends VisionTask {\n private constructor(\n session: OrtSession,\n private readonly _head: SegmenterHead,\n private readonly _labels: readonly string[],\n private readonly _names: Readonly<Record<number, string>>,\n private readonly _inputSize: readonly [number, number],\n private readonly _confThreshold: number,\n private readonly _iouThreshold: number,\n private readonly _maxDetections: number,\n private readonly _maskThreshold: number,\n ) {\n super(session);\n }\n\n /** Load the model and resolve labels. */\n static async create(model: ModelSource, options: SegmenterOptions = {}): Promise<Segmenter> {\n const head: SegmenterHead = options.head ?? \"yolo-seg\";\n if (head !== \"yolo-seg\") {\n throw new Error(`Unsupported segmenter head '${head}'. Supported: 'yolo-seg'.`);\n }\n const session = await OrtSession.create(model, options);\n const labels = resolveLabels(options.labels ?? \"coco\", {\n numClasses: options.numClasses,\n });\n const names: Record<number, string> = {};\n for (let i = 0; i < labels.length; i++) {\n names[i] = labels[i] as string;\n }\n return new Segmenter(\n session,\n head,\n labels,\n names,\n options.inputSize ?? [640, 640],\n options.confThreshold ?? 0.25,\n options.iouThreshold ?? 0.45,\n options.maxDetections ?? 300,\n options.maskThreshold ?? 0.5,\n );\n }\n\n /** The decoder family used to interpret the model's output. */\n get head(): SegmenterHead {\n return this._head;\n }\n\n /** Class labels indexed by class id. */\n get labels(): readonly string[] {\n return this._labels;\n }\n\n /** Class id → class name dict (matches Ultralytics' `model.names`). */\n get names(): Readonly<Record<number, string>> {\n return this._names;\n }\n\n /** Number of classes the model predicts. */\n get numClasses(): number {\n return this._labels.length;\n }\n\n /** Alias for {@link predict} (parity with PyTorch `nn.Module.__call__`). */\n async call(\n image: ImageInput,\n options: SegmenterPredictOptions = {},\n ): Promise<SegmentationResults[]> {\n return this.predict(image, options);\n }\n\n /** Run instance segmentation on a single image. */\n async predict(\n image: ImageInput,\n options: SegmenterPredictOptions = {},\n ): Promise<SegmentationResults[]> {\n const path = typeof image === \"string\" ? image : null;\n const original = await loadImage(image);\n const { tensor, scale, padLeft, padTop } = this._preprocess(original);\n const outputs = await this._session.run({ [this._session.inputName]: tensor });\n\n const { perAnchor, prototypes } = this._splitOutputs(outputs);\n\n const decodedAll = decodeYoloSeg(\n perAnchor.data as Float32Array,\n perAnchor.dims,\n prototypes.data as Float32Array,\n prototypes.dims,\n {\n numClasses: this._labels.length,\n inputWidth: this._inputSize[0],\n inputHeight: this._inputSize[1],\n originalWidth: original.width,\n originalHeight: original.height,\n padLeft,\n padTop,\n scale,\n confThreshold: options.confThreshold ?? this._confThreshold,\n iouThreshold: options.iouThreshold ?? this._iouThreshold,\n maxDetections: this._maxDetections,\n maskThreshold: this._maskThreshold,\n },\n );\n\n const decoded =\n options.classes !== undefined\n ? (() => {\n const allowed = new Set(options.classes);\n return decodedAll.filter((d) => allowed.has(d.classId));\n })()\n : decodedAll;\n\n const detections = decoded.map((d) =>\n this._buildResult(original, d.bbox, d.classId, d.confidence, d.mask),\n );\n\n const orig: readonly [number, number] = [original.height, original.width];\n return [\n new SegmentationResults(\n this._buildBoxes(detections, orig),\n this._buildMasks(detections, orig),\n detections,\n this._names,\n original,\n orig,\n path,\n ),\n ];\n }\n\n private _preprocess(image: RGBImage): {\n tensor: ort.Tensor;\n scale: number;\n padLeft: number;\n padTop: number;\n } {\n const [tw, th] = this._inputSize;\n const lb = letterbox(image, tw, th);\n const f32 = toFloat32(lb.image);\n const chw = toCHW(f32, lb.image.width, lb.image.height, 3);\n return {\n tensor: toFloat32Tensor(chw, [1, 3, lb.image.height, lb.image.width]),\n scale: lb.scale,\n padLeft: lb.padLeft,\n padTop: lb.padTop,\n };\n }\n\n private _splitOutputs(outputs: Record<string, ort.Tensor>): {\n perAnchor: ort.Tensor;\n prototypes: ort.Tensor;\n } {\n let perAnchor: ort.Tensor | undefined;\n let prototypes: ort.Tensor | undefined;\n for (const name of this._session.outputNames) {\n const t = outputs[name];\n if (t === undefined) continue;\n if (t.dims.length === 3 && perAnchor === undefined) {\n perAnchor = t;\n } else if (t.dims.length === 4 && prototypes === undefined) {\n prototypes = t;\n }\n }\n if (perAnchor === undefined || prototypes === undefined) {\n const shapes = this._session.outputNames.map(\n (n) => `${n}: ${JSON.stringify(outputs[n]?.dims ?? [])}`,\n );\n throw new Error(\n `Segmenter expected one 3-D and one 4-D output, got [${shapes.join(\", \")}].`,\n );\n }\n return { perAnchor, prototypes };\n }\n\n private _buildResult(\n original: RGBImage,\n bbox: BoundingBox,\n classId: number,\n confidence: number,\n mask: Mask,\n ): SegmentationResult {\n const [x1, y1, x2, y2] = bbox.asIntXyxy();\n const cx1 = Math.max(0, x1);\n const cy1 = Math.max(0, y1);\n const cx2 = Math.min(original.width, x2);\n const cy2 = Math.min(original.height, y2);\n\n let segmentedImage: RGBImage;\n let finalMask = mask;\n if (cx2 > cx1 && cy2 > cy1 && mask.data.length > 0) {\n const cropW = cx2 - cx1;\n const cropH = cy2 - cy1;\n const mw = Math.min(mask.width, cropW);\n const mh = Math.min(mask.height, cropH);\n const segData = new Uint8Array(mw * mh * 3);\n for (let row = 0; row < mh; row++) {\n const srcRowOffset = ((cy1 + row) * original.width + cx1) * 3;\n const dstRowOffset = row * mw * 3;\n const maskRowOffset = row * mask.width;\n for (let col = 0; col < mw; col++) {\n const m = mask.data[maskRowOffset + col];\n if (m !== 0) {\n const s = srcRowOffset + col * 3;\n const d = dstRowOffset + col * 3;\n segData[d] = original.data[s];\n segData[d + 1] = original.data[s + 1];\n segData[d + 2] = original.data[s + 2];\n }\n }\n }\n segmentedImage = new RGBImage(segData, mw, mh);\n if (mw !== mask.width || mh !== mask.height) {\n const trimmed = new Uint8Array(mw * mh);\n for (let row = 0; row < mh; row++) {\n trimmed.set(\n mask.data.subarray(row * mask.width, row * mask.width + mw),\n row * mw,\n );\n }\n finalMask = new Mask(trimmed, mw, mh);\n }\n } else {\n finalMask = new Mask(new Uint8Array(0), 0, 0);\n segmentedImage = new RGBImage(new Uint8Array(0), 0, 0);\n }\n\n const className = this._names[classId] ?? `class_${classId}`;\n\n return {\n classId,\n className,\n confidence,\n bbox,\n cls: classId,\n name: className,\n conf: confidence,\n box: bbox,\n mask: finalMask,\n segmentedImage,\n };\n }\n\n private _buildBoxes(\n detections: readonly SegmentationResult[],\n origShape: readonly [number, number],\n ): Boxes {\n const n = detections.length;\n const xyxy = new Float32Array(n * 4);\n const cls = new Int32Array(n);\n const conf = new Float32Array(n);\n for (let i = 0; i < n; i++) {\n const d = detections[i] as SegmentationResult;\n xyxy[i * 4] = d.bbox.x1;\n xyxy[i * 4 + 1] = d.bbox.y1;\n xyxy[i * 4 + 2] = d.bbox.x2;\n xyxy[i * 4 + 3] = d.bbox.y2;\n cls[i] = d.classId;\n conf[i] = d.confidence;\n }\n return new Boxes(xyxy, cls, conf, origShape);\n }\n\n private _buildMasks(\n detections: readonly SegmentationResult[],\n origShape: readonly [number, number],\n ): Masks {\n const xyxy = new Float32Array(detections.length * 4);\n for (let i = 0; i < detections.length; i++) {\n const d = detections[i] as SegmentationResult;\n xyxy[i * 4] = d.bbox.x1;\n xyxy[i * 4 + 1] = d.bbox.y1;\n xyxy[i * 4 + 2] = d.bbox.x2;\n xyxy[i * 4 + 3] = d.bbox.y2;\n }\n return new Masks(\n detections.map((d) => d.mask),\n xyxy,\n origShape,\n );\n }\n}\n"],"mappings":"+PAoFA,IAAa,EAAb,MAAa,UAAkB,EAAA,UAAW,CAGjB,MACA,QACA,OACA,WACA,eACA,cACA,eACA,eATrB,YACI,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACF,CACE,MAAM,CAAO,EATI,KAAA,MAAA,EACA,KAAA,QAAA,EACA,KAAA,OAAA,EACA,KAAA,WAAA,EACA,KAAA,eAAA,EACA,KAAA,cAAA,EACA,KAAA,eAAA,EACA,KAAA,eAAA,CAGrB,CAGA,aAAa,OAAO,EAAoB,EAA4B,CAAC,EAAuB,CACxF,IAAM,EAAsB,EAAQ,MAAQ,WAC5C,GAAI,IAAS,WACT,MAAU,MAAM,+BAA+B,EAAK,0BAA0B,EAElF,IAAM,EAAU,MAAM,EAAA,WAAW,OAAO,EAAO,CAAO,EAChD,EAAS,EAAA,cAAc,EAAQ,QAAU,OAAQ,CACnD,WAAY,EAAQ,UACxB,CAAC,EACK,EAAgC,CAAC,EACvC,IAAK,IAAI,EA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e,EAAG,CAAC,EAC5C,EAAiB,IAAI,EAAA,SAAS,IAAI,WAAe,EAAG,CAAC,EAGzD,IAAM,EAAY,KAAK,OAAO,IAAY,SAAS,IAEnD,MAAO,CACH,UACA,YACA,aACA,OACA,IAAK,EACL,KAAM,EACN,KAAM,EACN,IAAK,EACL,KAAM,EACN,gBACJ,CACJ,CAEA,YACI,EACA,EACK,CACL,IAAM,EAAI,EAAW,OACf,EAAO,IAAI,aAAa,EAAI,CAAC,EAC7B,EAAM,IAAI,WAAW,CAAC,EACtB,EAAO,IAAI,aAAa,CAAC,EAC/B,IAAK,IAAI,EAAI,EAAG,EAAI,EAAG,IAAK,CACxB,IAAM,EAAI,EAAW,GACrB,EAAK,EAAI,GAAK,EAAE,KAAK,GACrB,EAAK,EAAI,EAAI,GAAK,EAAE,KAAK,GACzB,EAAK,EAAI,EAAI,GAAK,EAAE,KAAK,GACzB,EAAK,EAAI,EAAI,GAAK,EAAE,KAAK,GACzB,EAAI,GAAK,EAAE,QACX,EAAK,GAAK,EAAE,UAChB,CACA,OAAO,IAAI,EAAA,MAAM,EAAM,EAAK,EAAM,CAAS,CAC/C,CAEA,YACI,EACA,EACK,CACL,IAAM,EAAO,IAAI,aAAa,EAAW,OAAS,CAAC,EACnD,IAAK,IAAI,EAAI,EAAG,EAAI,EAAW,OAAQ,IAAK,CACxC,IAAM,EAAI,EAAW,GACrB,EAAK,EAAI,GAAK,EAAE,KAAK,GACrB,EAAK,EAAI,EAAI,GAAK,EAAE,KAAK,GACzB,EAAK,EAAI,EAAI,GAAK,EAAE,KAAK,GACzB,EAAK,EAAI,EAAI,GAAK,EAAE,KAAK,EAC7B,CACA,OAAO,IAAI,EAAA,MACP,EAAW,IAAK,GAAM,EAAE,IAAI,EAC5B,EACA,CACJ,CACJ,CACJ"}
1
+ {"version":3,"file":"segmenter.cjs","names":[],"sources":["../../../src/vision/tasks/segmenter.ts"],"sourcesContent":["/**\n * Instance-segmentation task using YOLO seg ONNX models (v8-seg / v11-seg / ...).\n */\n\nimport type * as ort from \"onnxruntime-web\";\n\nimport { type ModelSource, type OrtSessionOptions, OrtSession } from \"../core/session\";\nimport { SpeedTimer } from \"../core/timing\";\nimport { type ImageInput, loadImage } from \"../io/image\";\nimport { type LabelSpec, resolveLabels } from \"../labels\";\nimport { decodeYoloSeg } from \"../postprocess/segmentation\";\nimport { letterbox, toCHW, toFloat32, toFloat32Tensor } from \"../preprocess/image\";\nimport { Boxes, Masks, SegmentationResults } from \"../results\";\nimport { VisionTask } from \"./base\";\nimport { type BoundingBox, type SegmentationResult, Mask, RGBImage } from \"../types\";\n\n/**\n * Decoder family for the segmentation head.\n *\n * - `\"yolo-seg\"`: YOLO instance-segmentation head with two outputs —\n * `[1, 4 + nc + nm, N]` per-anchor predictions plus `[1, nm, mh, mw]`\n * prototype masks. Covers YOLOv8-seg, v11-seg, v26-seg.\n *\n * The SDK does **not** auto-detect this — the caller is responsible for\n * picking a head that matches their export.\n */\nexport type SegmenterHead = \"yolo-seg\";\n\nexport interface SegmenterOptions extends OrtSessionOptions {\n /**\n * Decoder family for the segmentation head. Default `\"yolo-seg\"` covers\n * YOLOv8-seg/v11-seg/v26-seg.\n */\n readonly head?: SegmenterHead;\n /** Class label spec — see {@link resolveLabels}. Defaults to the COCO 80-class preset. */\n readonly labels?: LabelSpec;\n /** Number of classes — used to validate the supplied labels. */\n readonly numClasses?: number;\n /** Model input `[width, height]` for letterboxing. Defaults to `[640, 640]`. */\n readonly inputSize?: readonly [number, number];\n /** Default minimum class score to keep a candidate. */\n readonly confThreshold?: number;\n /** Default IoU threshold for non-maximum suppression. */\n readonly iouThreshold?: number;\n /** Maximum number of instances per image. */\n readonly maxDetections?: number;\n /** Probability cutoff applied to soft masks. Defaults to `0.5`. */\n readonly maskThreshold?: number;\n}\n\nexport interface SegmenterPredictOptions {\n readonly confThreshold?: number;\n readonly iouThreshold?: number;\n /**\n * If set, keep only instances whose `classId` is in this list.\n * Mirrors Ultralytics' `model.predict(img, classes=[0, 16])`.\n */\n readonly classes?: readonly number[];\n}\n\n/**\n * Instance segmenter for YOLO seg ONNX models (v8-seg / v11-seg / ...).\n *\n * The model is expected to expose two outputs:\n *\n * 1. `output0`: `(1, 4 + numClasses + numMaskCoefs, numAnchors)` — per-anchor\n * predictions (boxes, class scores, mask coefficients).\n * 2. `output1`: `(1, numMaskCoefs, maskH, maskW)` — prototype masks.\n *\n * `predict()` returns `Promise<SegmentationResults[]>` (length 1 for a\n * single image), mirroring Ultralytics' API. The envelope exposes:\n *\n * - `boxes`: bulk numpy view (`xyxy`, `xywh`, `xyxyn`, `xywhn`, `cls`, `conf`).\n * - `masks`: per-instance binary masks cropped to each box.\n * - per-instance {@link SegmentationResult} via iteration.\n *\n * @example\n * ```typescript\n * const seg = await Segmenter.create(\"/models/yolov8n-seg.onnx\");\n * const r = (await seg.predict(\"/images/street.jpg\"))[0];\n * for (const inst of r) {\n * console.log(inst.cls, inst.conf, inst.box.xyxy);\n * }\n * ```\n */\nexport class Segmenter extends VisionTask {\n private constructor(\n session: OrtSession,\n private readonly _head: SegmenterHead,\n private readonly _labels: readonly string[],\n private readonly _names: Readonly<Record<number, string>>,\n private readonly _inputSize: readonly [number, number],\n private readonly _confThreshold: number,\n private readonly _iouThreshold: number,\n private readonly _maxDetections: number,\n private readonly _maskThreshold: number,\n ) {\n super(session);\n }\n\n /** Load the model and resolve labels. */\n static async create(model: ModelSource, options: SegmenterOptions = {}): Promise<Segmenter> {\n const head: SegmenterHead = options.head ?? \"yolo-seg\";\n if (head !== \"yolo-seg\") {\n throw new Error(`Unsupported segmenter head '${head}'. Supported: 'yolo-seg'.`);\n }\n const session = await OrtSession.create(model, options);\n const labels = resolveLabels(options.labels ?? \"coco\", {\n numClasses: options.numClasses,\n });\n const names: Record<number, string> = {};\n for (let i = 0; i < labels.length; i++) {\n names[i] = labels[i] as string;\n }\n return new Segmenter(\n session,\n head,\n labels,\n names,\n options.inputSize ?? [640, 640],\n options.confThreshold ?? 0.25,\n options.iouThreshold ?? 0.45,\n options.maxDetections ?? 300,\n options.maskThreshold ?? 0.5,\n );\n }\n\n /** The decoder family used to interpret the model's output. */\n get head(): SegmenterHead {\n return this._head;\n }\n\n /** Class labels indexed by class id. */\n get labels(): readonly string[] {\n return this._labels;\n }\n\n /** Class id → class name dict (matches Ultralytics' `model.names`). */\n get names(): Readonly<Record<number, string>> {\n return this._names;\n }\n\n /** Number of classes the model predicts. */\n get numClasses(): number {\n return this._labels.length;\n }\n\n /** Alias for {@link predict} (parity with PyTorch `nn.Module.__call__`). */\n async call(\n image: ImageInput,\n options: SegmenterPredictOptions = {},\n ): Promise<SegmentationResults[]> {\n return this.predict(image, options);\n }\n\n /** Run instance segmentation on a single image. */\n async predict(\n image: ImageInput,\n options: SegmenterPredictOptions = {},\n ): Promise<SegmentationResults[]> {\n const timer = new SpeedTimer();\n const path = typeof image === \"string\" ? image : null;\n const original = await loadImage(image);\n timer.stage(\"load\");\n const { tensor, scale, padLeft, padTop } = this._preprocess(original);\n timer.stage(\"preprocess\");\n const outputs = await this._session.run({ [this._session.inputName]: tensor });\n timer.stage(\"inference\");\n\n const { perAnchor, prototypes } = this._splitOutputs(outputs);\n\n const decodedAll = decodeYoloSeg(\n perAnchor.data as Float32Array,\n perAnchor.dims,\n prototypes.data as Float32Array,\n prototypes.dims,\n {\n numClasses: this._labels.length,\n inputWidth: this._inputSize[0],\n inputHeight: this._inputSize[1],\n originalWidth: original.width,\n originalHeight: original.height,\n padLeft,\n padTop,\n scale,\n confThreshold: options.confThreshold ?? this._confThreshold,\n iouThreshold: options.iouThreshold ?? this._iouThreshold,\n maxDetections: this._maxDetections,\n maskThreshold: this._maskThreshold,\n },\n );\n\n const decoded =\n options.classes !== undefined\n ? (() => {\n const allowed = new Set(options.classes);\n return decodedAll.filter((d) => allowed.has(d.classId));\n })()\n : decodedAll;\n\n const detections = decoded.map((d) =>\n this._buildResult(original, d.bbox, d.classId, d.confidence, d.mask),\n );\n\n const orig: readonly [number, number] = [original.height, original.width];\n const boxes = this._buildBoxes(detections, orig);\n const masks = this._buildMasks(detections, orig);\n timer.stage(\"postprocess\");\n return [\n new SegmentationResults(\n boxes,\n masks,\n detections,\n this._names,\n original,\n orig,\n path,\n timer.speed(),\n ),\n ];\n }\n\n private _preprocess(image: RGBImage): {\n tensor: ort.Tensor;\n scale: number;\n padLeft: number;\n padTop: number;\n } {\n const [tw, th] = this._inputSize;\n const lb = letterbox(image, tw, th);\n const f32 = toFloat32(lb.image);\n const chw = toCHW(f32, lb.image.width, lb.image.height, 3);\n return {\n tensor: toFloat32Tensor(chw, [1, 3, lb.image.height, lb.image.width]),\n scale: lb.scale,\n padLeft: lb.padLeft,\n padTop: lb.padTop,\n };\n }\n\n private _splitOutputs(outputs: Record<string, ort.Tensor>): {\n perAnchor: ort.Tensor;\n prototypes: ort.Tensor;\n } {\n let perAnchor: ort.Tensor | undefined;\n let prototypes: ort.Tensor | undefined;\n for (const name of this._session.outputNames) {\n const t = outputs[name];\n if (t === undefined) continue;\n if (t.dims.length === 3 && perAnchor === undefined) {\n perAnchor = t;\n } else if (t.dims.length === 4 && prototypes === undefined) {\n prototypes = t;\n }\n }\n if (perAnchor === undefined || prototypes === undefined) {\n const shapes = this._session.outputNames.map(\n (n) => `${n}: ${JSON.stringify(outputs[n]?.dims ?? [])}`,\n );\n throw new Error(\n `Segmenter expected one 3-D and one 4-D output, got [${shapes.join(\", \")}].`,\n );\n }\n return { perAnchor, prototypes };\n }\n\n private _buildResult(\n original: RGBImage,\n bbox: BoundingBox,\n classId: number,\n confidence: number,\n mask: Mask,\n ): SegmentationResult {\n const [x1, y1, x2, y2] = bbox.asIntXyxy();\n const cx1 = Math.max(0, x1);\n const cy1 = Math.max(0, y1);\n const cx2 = Math.min(original.width, x2);\n const cy2 = Math.min(original.height, y2);\n\n let segmentedImage: RGBImage;\n let finalMask = mask;\n if (cx2 > cx1 && cy2 > cy1 && mask.data.length > 0) {\n const cropW = cx2 - cx1;\n const cropH = cy2 - cy1;\n const mw = Math.min(mask.width, cropW);\n const mh = Math.min(mask.height, cropH);\n const segData = new Uint8Array(mw * mh * 3);\n for (let row = 0; row < mh; row++) {\n const srcRowOffset = ((cy1 + row) * original.width + cx1) * 3;\n const dstRowOffset = row * mw * 3;\n const maskRowOffset = row * mask.width;\n for (let col = 0; col < mw; col++) {\n const m = mask.data[maskRowOffset + col];\n if (m !== 0) {\n const s = srcRowOffset + col * 3;\n const d = dstRowOffset + col * 3;\n segData[d] = original.data[s];\n segData[d + 1] = original.data[s + 1];\n segData[d + 2] = original.data[s + 2];\n }\n }\n }\n segmentedImage = new RGBImage(segData, mw, mh);\n if (mw !== mask.width || mh !== mask.height) {\n const trimmed = new Uint8Array(mw * mh);\n for (let row = 0; row < mh; row++) {\n trimmed.set(\n mask.data.subarray(row * mask.width, row * mask.width + mw),\n row * mw,\n );\n }\n finalMask = new Mask(trimmed, mw, mh);\n }\n } else {\n finalMask = new Mask(new Uint8Array(0), 0, 0);\n segmentedImage = new RGBImage(new Uint8Array(0), 0, 0);\n }\n\n const className = this._names[classId] ?? `class_${classId}`;\n\n return {\n classId,\n className,\n confidence,\n bbox,\n cls: classId,\n name: className,\n conf: confidence,\n box: bbox,\n mask: finalMask,\n segmentedImage,\n };\n }\n\n private _buildBoxes(\n detections: readonly SegmentationResult[],\n origShape: readonly [number, number],\n ): Boxes {\n const n = detections.length;\n const xyxy = new Float32Array(n * 4);\n const cls = new Int32Array(n);\n const conf = new Float32Array(n);\n for (let i = 0; i < n; i++) {\n const d = detections[i] as SegmentationResult;\n xyxy[i * 4] = d.bbox.x1;\n xyxy[i * 4 + 1] = d.bbox.y1;\n xyxy[i * 4 + 2] = d.bbox.x2;\n xyxy[i * 4 + 3] = d.bbox.y2;\n cls[i] = d.classId;\n conf[i] = d.confidence;\n }\n return new Boxes(xyxy, cls, conf, origShape);\n }\n\n private _buildMasks(\n detections: readonly SegmentationResult[],\n origShape: readonly [number, number],\n ): Masks {\n const xyxy = new Float32Array(detections.length * 4);\n for (let i = 0; i < detections.length; i++) {\n const d = detections[i] as SegmentationResult;\n xyxy[i * 4] = d.bbox.x1;\n xyxy[i * 4 + 1] = d.bbox.y1;\n xyxy[i * 4 + 2] = d.bbox.x2;\n xyxy[i * 4 + 3] = d.bbox.y2;\n }\n return new Masks(\n detections.map((d) => d.mask),\n xyxy,\n origShape,\n );\n }\n}\n"],"mappings":"+RAqFA,IAAa,EAAb,MAAa,UAAkB,EAAA,UAAW,CAGjB,MACA,QACA,OACA,WACA,eACA,cACA,eACA,eATrB,YACI,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACF,CACE,MAAM,CAAO,EATI,KAAA,MAAA,EACA,KAAA,QAAA,EACA,KAAA,OAAA,EACA,KAAA,WAAA,EACA,KAAA,eAAA,EACA,KAAA,cAAA,EACA,KAAA,eAAA,EACA,KAAA,eAAA,CAGrB,CAGA,aAAa,OAAO,EAAoB,EAA4B,CAAC,EAAuB,CACxF,IAAM,EAAsB,EAAQ,MAAQ,WAC5C,GAAI,IAAS,WACT,MAAU,MAAM,+BAA+B,EAAK,0BAA0B,EAElF,IAAM,EAAU,MAAM,EAAA,WAAW,OAAO,EAAO,CAAO,EAChD,EAAS,EAAA,cAAc,EAAQ,QAAU,OAAQ,CACnD,WAAY,EAAQ,UACxB,CAAC,EACK,EAAgC,CAAC,EACvC,IAAK,IAAI,EAAI,EAAG,EAAI,EAAO,OAAQ,IAC/B,EAAM,GAAK,EAAO,GAEtB,OAAO,IAAI,EACP,EACA,EACA,EACA,EACA,EAAQ,WAAa,CAAC,IAAK,GAAG,EAC9B,EAAQ,eAAiB,IACzB,EAAQ,cAAgB,IACxB,EAAQ,eAAiB,IACzB,EAAQ,eAAiB,EAC7B,CACJ,CAGA,IAAI,MAAsB,CACtB,OAAO,KAAK,KAChB,CAGA,IAAI,QAA4B,CAC5B,OAAO,KAAK,OAChB,CAGA,IAAI,OAA0C,CAC1C,OAAO,KAAK,MAChB,CAGA,IAAI,YAAqB,CACrB,OAAO,KAAK,Q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J,CAEA,YACI,EACA,EACK,CACL,IAAM,EAAI,EAAW,OACf,EAAO,IAAI,aAAa,EAAI,CAAC,EAC7B,EAAM,IAAI,WAAW,CAAC,EACtB,EAAO,IAAI,aAAa,CAAC,EAC/B,IAAK,IAAI,EAAI,EAAG,EAAI,EAAG,IAAK,CACxB,IAAM,EAAI,EAAW,GACrB,EAAK,EAAI,GAAK,EAAE,KAAK,GACrB,EAAK,EAAI,EAAI,GAAK,EAAE,KAAK,GACzB,EAAK,EAAI,EAAI,GAAK,EAAE,KAAK,GACzB,EAAK,EAAI,EAAI,GAAK,EAAE,KAAK,GACzB,EAAI,GAAK,EAAE,QACX,EAAK,GAAK,EAAE,UAChB,CACA,OAAO,IAAI,EAAA,MAAM,EAAM,EAAK,EAAM,CAAS,CAC/C,CAEA,YACI,EACA,EACK,CACL,IAAM,EAAO,IAAI,aAAa,EAAW,OAAS,CAAC,EACnD,IAAK,IAAI,EAAI,EAAG,EAAI,EAAW,OAAQ,IAAK,CACxC,IAAM,EAAI,EAAW,GACrB,EAAK,EAAI,GAAK,EAAE,KAAK,GACrB,EAAK,EAAI,EAAI,GAAK,EAAE,KAAK,GACzB,EAAK,EAAI,EAAI,GAAK,EAAE,KAAK,GACzB,EAAK,EAAI,EAAI,GAAK,EAAE,KAAK,EAC7B,CACA,OAAO,IAAI,EAAA,MACP,EAAW,IAAK,GAAM,EAAE,IAAI,EAC5B,EACA,CACJ,CACJ,CACJ"}
@@ -1,13 +1,14 @@
1
1
  import { Mask as e, RGBImage as t } from "../types.js";
2
- import { Boxes as n, Masks as r, SegmentationResults as i } from "../results.js";
3
- import { resolveLabels as a } from "../labels.js";
4
- import { OrtSession as o } from "../core/session.js";
5
- import { loadImage as s } from "../io/image.js";
6
- import { letterbox as c, toCHW as l, toFloat32 as u, toFloat32Tensor as d } from "../preprocess/image.js";
7
- import { decodeYoloSeg as f } from "../postprocess/segmentation.js";
8
- import { VisionTask as p } from "./base.js";
2
+ import { SpeedTimer as n } from "../core/timing.js";
3
+ import { Boxes as r, Masks as i, SegmentationResults as a } from "../results.js";
4
+ import { resolveLabels as o } from "../labels.js";
5
+ import { OrtSession as s } from "../core/session.js";
6
+ import { loadImage as c } from "../io/image.js";
7
+ import { letterbox as l, toCHW as u, toFloat32 as d, toFloat32Tensor as f } from "../preprocess/image.js";
8
+ import { decodeYoloSeg as p } from "../postprocess/segmentation.js";
9
+ import { VisionTask as m } from "./base.js";
9
10
  //#region src/vision/tasks/segmenter.ts
10
- var m = class m extends p {
11
+ var h = class h extends m {
11
12
  _head;
12
13
  _labels;
13
14
  _names;
@@ -22,9 +23,9 @@ var m = class m extends p {
22
23
  static async create(e, t = {}) {
23
24
  let n = t.head ?? "yolo-seg";
24
25
  if (n !== "yolo-seg") throw Error(`Unsupported segmenter head '${n}'. Supported: 'yolo-seg'.`);
25
- let r = await o.create(e, t), i = a(t.labels ?? "coco", { numClasses: t.numClasses }), s = {};
26
- for (let e = 0; e < i.length; e++) s[e] = i[e];
27
- return new m(r, n, i, s, t.inputSize ?? [640, 640], t.confThreshold ?? .25, t.iouThreshold ?? .45, t.maxDetections ?? 300, t.maskThreshold ?? .5);
26
+ let r = await s.create(e, t), i = o(t.labels ?? "coco", { numClasses: t.numClasses }), a = {};
27
+ for (let e = 0; e < i.length; e++) a[e] = i[e];
28
+ return new h(r, n, i, a, t.inputSize ?? [640, 640], t.confThreshold ?? .25, t.iouThreshold ?? .45, t.maxDetections ?? 300, t.maskThreshold ?? .5);
28
29
  }
29
30
  get head() {
30
31
  return this._head;
@@ -42,29 +43,35 @@ var m = class m extends p {
42
43
  return this.predict(e, t);
43
44
  }
44
45
  async predict(e, t = {}) {
45
- let n = typeof e == "string" ? e : null, r = await s(e), { tensor: a, scale: o, padLeft: c, padTop: l } = this._preprocess(r), u = await this._session.run({ [this._session.inputName]: a }), { perAnchor: d, prototypes: p } = this._splitOutputs(u), m = f(d.data, d.dims, p.data, p.dims, {
46
+ let r = new n(), i = typeof e == "string" ? e : null, o = await c(e);
47
+ r.stage("load");
48
+ let { tensor: s, scale: l, padLeft: u, padTop: d } = this._preprocess(o);
49
+ r.stage("preprocess");
50
+ let f = await this._session.run({ [this._session.inputName]: s });
51
+ r.stage("inference");
52
+ let { perAnchor: m, prototypes: h } = this._splitOutputs(f), g = p(m.data, m.dims, h.data, h.dims, {
46
53
  numClasses: this._labels.length,
47
54
  inputWidth: this._inputSize[0],
48
55
  inputHeight: this._inputSize[1],
49
- originalWidth: r.width,
50
- originalHeight: r.height,
51
- padLeft: c,
52
- padTop: l,
53
- scale: o,
56
+ originalWidth: o.width,
57
+ originalHeight: o.height,
58
+ padLeft: u,
59
+ padTop: d,
60
+ scale: l,
54
61
  confThreshold: t.confThreshold ?? this._confThreshold,
55
62
  iouThreshold: t.iouThreshold ?? this._iouThreshold,
56
63
  maxDetections: this._maxDetections,
57
64
  maskThreshold: this._maskThreshold
58
- }), h = (t.classes === void 0 ? m : (() => {
65
+ }), _ = (t.classes === void 0 ? g : (() => {
59
66
  let e = new Set(t.classes);
60
- return m.filter((t) => e.has(t.classId));
61
- })()).map((e) => this._buildResult(r, e.bbox, e.classId, e.confidence, e.mask)), g = [r.height, r.width];
62
- return [new i(this._buildBoxes(h, g), this._buildMasks(h, g), h, this._names, r, g, n)];
67
+ return g.filter((t) => e.has(t.classId));
68
+ })()).map((e) => this._buildResult(o, e.bbox, e.classId, e.confidence, e.mask)), v = [o.height, o.width], y = this._buildBoxes(_, v), b = this._buildMasks(_, v);
69
+ return r.stage("postprocess"), [new a(y, b, _, this._names, o, v, i, r.speed())];
63
70
  }
64
71
  _preprocess(e) {
65
- let [t, n] = this._inputSize, r = c(e, t, n);
72
+ let [t, n] = this._inputSize, r = l(e, t, n);
66
73
  return {
67
- tensor: d(l(u(r.image), r.image.width, r.image.height, 3), [
74
+ tensor: f(u(d(r.image), r.image.width, r.image.height, 3), [
68
75
  1,
69
76
  3,
70
77
  r.image.height,
@@ -122,12 +129,12 @@ var m = class m extends p {
122
129
  };
123
130
  }
124
131
  _buildBoxes(e, t) {
125
- let r = e.length, i = new Float32Array(r * 4), a = new Int32Array(r), o = new Float32Array(r);
126
- for (let t = 0; t < r; t++) {
132
+ let n = e.length, i = new Float32Array(n * 4), a = new Int32Array(n), o = new Float32Array(n);
133
+ for (let t = 0; t < n; t++) {
127
134
  let n = e[t];
128
135
  i[t * 4] = n.bbox.x1, i[t * 4 + 1] = n.bbox.y1, i[t * 4 + 2] = n.bbox.x2, i[t * 4 + 3] = n.bbox.y2, a[t] = n.classId, o[t] = n.confidence;
129
136
  }
130
- return new n(i, a, o, t);
137
+ return new r(i, a, o, t);
131
138
  }
132
139
  _buildMasks(e, t) {
133
140
  let n = new Float32Array(e.length * 4);
@@ -135,10 +142,10 @@ var m = class m extends p {
135
142
  let r = e[t];
136
143
  n[t * 4] = r.bbox.x1, n[t * 4 + 1] = r.bbox.y1, n[t * 4 + 2] = r.bbox.x2, n[t * 4 + 3] = r.bbox.y2;
137
144
  }
138
- return new r(e.map((e) => e.mask), n, t);
145
+ return new i(e.map((e) => e.mask), n, t);
139
146
  }
140
147
  };
141
148
  //#endregion
142
- export { m as Segmenter };
149
+ export { h as Segmenter };
143
150
 
144
151
  //# sourceMappingURL=segmenter.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"segmenter.js","names":[],"sources":["../../../src/vision/tasks/segmenter.ts"],"sourcesContent":["/**\n * Instance-segmentation task using YOLO seg ONNX models (v8-seg / v11-seg / ...).\n */\n\nimport type * as ort from \"onnxruntime-web\";\n\nimport { type ModelSource, type OrtSessionOptions, OrtSession } from \"../core/session\";\nimport { type ImageInput, loadImage } from \"../io/image\";\nimport { type LabelSpec, resolveLabels } from \"../labels\";\nimport { decodeYoloSeg } from \"../postprocess/segmentation\";\nimport { letterbox, toCHW, toFloat32, toFloat32Tensor } from \"../preprocess/image\";\nimport { Boxes, Masks, SegmentationResults } from \"../results\";\nimport { VisionTask } from \"./base\";\nimport { type BoundingBox, type SegmentationResult, Mask, RGBImage } from \"../types\";\n\n/**\n * Decoder family for the segmentation head.\n *\n * - `\"yolo-seg\"`: YOLO instance-segmentation head with two outputs —\n * `[1, 4 + nc + nm, N]` per-anchor predictions plus `[1, nm, mh, mw]`\n * prototype masks. Covers YOLOv8-seg, v11-seg, v26-seg.\n *\n * The SDK does **not** auto-detect this — the caller is responsible for\n * picking a head that matches their export.\n */\nexport type SegmenterHead = \"yolo-seg\";\n\nexport interface SegmenterOptions extends OrtSessionOptions {\n /**\n * Decoder family for the segmentation head. Default `\"yolo-seg\"` covers\n * YOLOv8-seg/v11-seg/v26-seg.\n */\n readonly head?: SegmenterHead;\n /** Class label spec — see {@link resolveLabels}. Defaults to the COCO 80-class preset. */\n readonly labels?: LabelSpec;\n /** Number of classes — used to validate the supplied labels. */\n readonly numClasses?: number;\n /** Model input `[width, height]` for letterboxing. Defaults to `[640, 640]`. */\n readonly inputSize?: readonly [number, number];\n /** Default minimum class score to keep a candidate. */\n readonly confThreshold?: number;\n /** Default IoU threshold for non-maximum suppression. */\n readonly iouThreshold?: number;\n /** Maximum number of instances per image. */\n readonly maxDetections?: number;\n /** Probability cutoff applied to soft masks. Defaults to `0.5`. */\n readonly maskThreshold?: number;\n}\n\nexport interface SegmenterPredictOptions {\n readonly confThreshold?: number;\n readonly iouThreshold?: number;\n /**\n * If set, keep only instances whose `classId` is in this list.\n * Mirrors Ultralytics' `model.predict(img, classes=[0, 16])`.\n */\n readonly classes?: readonly number[];\n}\n\n/**\n * Instance segmenter for YOLO seg ONNX models (v8-seg / v11-seg / ...).\n *\n * The model is expected to expose two outputs:\n *\n * 1. `output0`: `(1, 4 + numClasses + numMaskCoefs, numAnchors)` — per-anchor\n * predictions (boxes, class scores, mask coefficients).\n * 2. `output1`: `(1, numMaskCoefs, maskH, maskW)` — prototype masks.\n *\n * `predict()` returns `Promise<SegmentationResults[]>` (length 1 for a\n * single image), mirroring Ultralytics' API. The envelope exposes:\n *\n * - `boxes`: bulk numpy view (`xyxy`, `xywh`, `xyxyn`, `xywhn`, `cls`, `conf`).\n * - `masks`: per-instance binary masks cropped to each box.\n * - per-instance {@link SegmentationResult} via iteration.\n *\n * @example\n * ```typescript\n * const seg = await Segmenter.create(\"/models/yolov8n-seg.onnx\");\n * const r = (await seg.predict(\"/images/street.jpg\"))[0];\n * for (const inst of r) {\n * console.log(inst.cls, inst.conf, inst.box.xyxy);\n * }\n * ```\n */\nexport class Segmenter extends VisionTask {\n private constructor(\n session: OrtSession,\n private readonly _head: SegmenterHead,\n private readonly _labels: readonly string[],\n private readonly _names: Readonly<Record<number, string>>,\n private readonly _inputSize: readonly [number, number],\n private readonly _confThreshold: number,\n private readonly _iouThreshold: number,\n private readonly _maxDetections: number,\n private readonly _maskThreshold: number,\n ) {\n super(session);\n }\n\n /** Load the model and resolve labels. */\n static async create(model: ModelSource, options: SegmenterOptions = {}): Promise<Segmenter> {\n const head: SegmenterHead = options.head ?? \"yolo-seg\";\n if (head !== \"yolo-seg\") {\n throw new Error(`Unsupported segmenter head '${head}'. Supported: 'yolo-seg'.`);\n }\n const session = await OrtSession.create(model, options);\n const labels = resolveLabels(options.labels ?? \"coco\", {\n numClasses: options.numClasses,\n });\n const names: Record<number, string> = {};\n for (let i = 0; i < labels.length; i++) {\n names[i] = labels[i] as string;\n }\n return new Segmenter(\n session,\n head,\n labels,\n names,\n options.inputSize ?? [640, 640],\n options.confThreshold ?? 0.25,\n options.iouThreshold ?? 0.45,\n options.maxDetections ?? 300,\n options.maskThreshold ?? 0.5,\n );\n }\n\n /** The decoder family used to interpret the model's output. */\n get head(): SegmenterHead {\n return this._head;\n }\n\n /** Class labels indexed by class id. */\n get labels(): readonly string[] {\n return this._labels;\n }\n\n /** Class id → class name dict (matches Ultralytics' `model.names`). */\n get names(): Readonly<Record<number, string>> {\n return this._names;\n }\n\n /** Number of classes the model predicts. */\n get numClasses(): number {\n return this._labels.length;\n }\n\n /** Alias for {@link predict} (parity with PyTorch `nn.Module.__call__`). */\n async call(\n image: ImageInput,\n options: SegmenterPredictOptions = {},\n ): Promise<SegmentationResults[]> {\n return this.predict(image, options);\n }\n\n /** Run instance segmentation on a single image. */\n async predict(\n image: ImageInput,\n options: SegmenterPredictOptions = {},\n ): Promise<SegmentationResults[]> {\n const path = typeof image === \"string\" ? image : null;\n const original = await loadImage(image);\n const { tensor, scale, padLeft, padTop } = this._preprocess(original);\n const outputs = await this._session.run({ [this._session.inputName]: tensor });\n\n const { perAnchor, prototypes } = this._splitOutputs(outputs);\n\n const decodedAll = decodeYoloSeg(\n perAnchor.data as Float32Array,\n perAnchor.dims,\n prototypes.data as Float32Array,\n prototypes.dims,\n {\n numClasses: this._labels.length,\n inputWidth: this._inputSize[0],\n inputHeight: this._inputSize[1],\n originalWidth: original.width,\n originalHeight: original.height,\n padLeft,\n padTop,\n scale,\n confThreshold: options.confThreshold ?? this._confThreshold,\n iouThreshold: options.iouThreshold ?? this._iouThreshold,\n maxDetections: this._maxDetections,\n maskThreshold: this._maskThreshold,\n },\n );\n\n const decoded =\n options.classes !== undefined\n ? (() => {\n const allowed = new Set(options.classes);\n return decodedAll.filter((d) => allowed.has(d.classId));\n })()\n : decodedAll;\n\n const detections = decoded.map((d) =>\n this._buildResult(original, d.bbox, d.classId, d.confidence, d.mask),\n );\n\n const orig: readonly [number, number] = [original.height, original.width];\n return [\n new SegmentationResults(\n this._buildBoxes(detections, orig),\n this._buildMasks(detections, orig),\n detections,\n this._names,\n original,\n orig,\n path,\n ),\n ];\n }\n\n private _preprocess(image: RGBImage): {\n tensor: ort.Tensor;\n scale: number;\n padLeft: number;\n padTop: number;\n } {\n const [tw, th] = this._inputSize;\n const lb = letterbox(image, tw, th);\n const f32 = toFloat32(lb.image);\n const chw = toCHW(f32, lb.image.width, lb.image.height, 3);\n return {\n tensor: toFloat32Tensor(chw, [1, 3, lb.image.height, lb.image.width]),\n scale: lb.scale,\n padLeft: lb.padLeft,\n padTop: lb.padTop,\n };\n }\n\n private _splitOutputs(outputs: Record<string, ort.Tensor>): {\n perAnchor: ort.Tensor;\n prototypes: ort.Tensor;\n } {\n let perAnchor: ort.Tensor | undefined;\n let prototypes: ort.Tensor | undefined;\n for (const name of this._session.outputNames) {\n const t = outputs[name];\n if (t === undefined) continue;\n if (t.dims.length === 3 && perAnchor === undefined) {\n perAnchor = t;\n } else if (t.dims.length === 4 && prototypes === undefined) {\n prototypes = t;\n }\n }\n if (perAnchor === undefined || prototypes === undefined) {\n const shapes = this._session.outputNames.map(\n (n) => `${n}: ${JSON.stringify(outputs[n]?.dims ?? [])}`,\n );\n throw new Error(\n `Segmenter expected one 3-D and one 4-D output, got [${shapes.join(\", \")}].`,\n );\n }\n return { perAnchor, prototypes };\n }\n\n private _buildResult(\n original: RGBImage,\n bbox: BoundingBox,\n classId: number,\n confidence: number,\n mask: Mask,\n ): SegmentationResult {\n const [x1, y1, x2, y2] = bbox.asIntXyxy();\n const cx1 = Math.max(0, x1);\n const cy1 = Math.max(0, y1);\n const cx2 = Math.min(original.width, x2);\n const cy2 = Math.min(original.height, y2);\n\n let segmentedImage: RGBImage;\n let finalMask = mask;\n if (cx2 > cx1 && cy2 > cy1 && mask.data.length > 0) {\n const cropW = cx2 - cx1;\n const cropH = cy2 - cy1;\n const mw = Math.min(mask.width, cropW);\n const mh = Math.min(mask.height, cropH);\n const segData = new Uint8Array(mw * mh * 3);\n for (let row = 0; row < mh; row++) {\n const srcRowOffset = ((cy1 + row) * original.width + cx1) * 3;\n const dstRowOffset = row * mw * 3;\n const maskRowOffset = row * mask.width;\n for (let col = 0; col < mw; col++) {\n const m = mask.data[maskRowOffset + col];\n if (m !== 0) {\n const s = srcRowOffset + col * 3;\n const d = dstRowOffset + col * 3;\n segData[d] = original.data[s];\n segData[d + 1] = original.data[s + 1];\n segData[d + 2] = original.data[s + 2];\n }\n }\n }\n segmentedImage = new RGBImage(segData, mw, mh);\n if (mw !== mask.width || mh !== mask.height) {\n const trimmed = new Uint8Array(mw * mh);\n for (let row = 0; row < mh; row++) {\n trimmed.set(\n mask.data.subarray(row * mask.width, row * mask.width + mw),\n row * mw,\n );\n }\n finalMask = new Mask(trimmed, mw, mh);\n }\n } else {\n finalMask = new Mask(new Uint8Array(0), 0, 0);\n segmentedImage = new RGBImage(new Uint8Array(0), 0, 0);\n }\n\n const className = this._names[classId] ?? `class_${classId}`;\n\n return {\n classId,\n className,\n confidence,\n bbox,\n cls: classId,\n name: className,\n conf: confidence,\n box: bbox,\n mask: finalMask,\n segmentedImage,\n };\n }\n\n private _buildBoxes(\n detections: readonly SegmentationResult[],\n origShape: readonly [number, number],\n ): Boxes {\n const n = detections.length;\n const xyxy = new Float32Array(n * 4);\n const cls = new Int32Array(n);\n const conf = new Float32Array(n);\n for (let i = 0; i < n; i++) {\n const d = detections[i] as SegmentationResult;\n xyxy[i * 4] = d.bbox.x1;\n xyxy[i * 4 + 1] = d.bbox.y1;\n xyxy[i * 4 + 2] = d.bbox.x2;\n xyxy[i * 4 + 3] = d.bbox.y2;\n cls[i] = d.classId;\n conf[i] = d.confidence;\n }\n return new Boxes(xyxy, cls, conf, origShape);\n }\n\n private _buildMasks(\n detections: readonly SegmentationResult[],\n origShape: readonly [number, number],\n ): Masks {\n const xyxy = new Float32Array(detections.length * 4);\n for (let i = 0; i < detections.length; i++) {\n const d = detections[i] as SegmentationResult;\n xyxy[i * 4] = d.bbox.x1;\n xyxy[i * 4 + 1] = d.bbox.y1;\n xyxy[i * 4 + 2] = d.bbox.x2;\n xyxy[i * 4 + 3] = d.bbox.y2;\n }\n return new Masks(\n detections.map((d) => d.mask),\n xyxy,\n origShape,\n );\n }\n}\n"],"mappings":";;;;;;;;;AAoFA,IAAa,IAAb,MAAa,UAAkB,EAAW;CAGjB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CATrB,YACI,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACF;EADmB,AAEjB,MAAM,CAAO,GATI,KAAA,QAAA,GACA,KAAA,UAAA,GACA,KAAA,SAAA,GACA,KAAA,aAAA,GACA,KAAA,iBAAA,GACA,KAAA,gBA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AK,EAAE,KAAK,IACzB,EAAK,IAAI,IAAI,KAAK,EAAE,KAAK,IACzB,EAAK,IAAI,IAAI,KAAK,EAAE,KAAK;EAC7B;EACA,OAAO,IAAI,EACP,EAAW,KAAK,MAAM,EAAE,IAAI,GAC5B,GACA,CACJ;CACJ;AACJ"}
1
+ {"version":3,"file":"segmenter.js","names":[],"sources":["../../../src/vision/tasks/segmenter.ts"],"sourcesContent":["/**\n * Instance-segmentation task using YOLO seg ONNX models (v8-seg / v11-seg / ...).\n */\n\nimport type * as ort from \"onnxruntime-web\";\n\nimport { type ModelSource, type OrtSessionOptions, OrtSession } from \"../core/session\";\nimport { SpeedTimer } from \"../core/timing\";\nimport { type ImageInput, loadImage } from \"../io/image\";\nimport { type LabelSpec, resolveLabels } from \"../labels\";\nimport { decodeYoloSeg } from \"../postprocess/segmentation\";\nimport { letterbox, toCHW, toFloat32, toFloat32Tensor } from \"../preprocess/image\";\nimport { Boxes, Masks, SegmentationResults } from \"../results\";\nimport { VisionTask } from \"./base\";\nimport { type BoundingBox, type SegmentationResult, Mask, RGBImage } from \"../types\";\n\n/**\n * Decoder family for the segmentation head.\n *\n * - `\"yolo-seg\"`: YOLO instance-segmentation head with two outputs —\n * `[1, 4 + nc + nm, N]` per-anchor predictions plus `[1, nm, mh, mw]`\n * prototype masks. Covers YOLOv8-seg, v11-seg, v26-seg.\n *\n * The SDK does **not** auto-detect this — the caller is responsible for\n * picking a head that matches their export.\n */\nexport type SegmenterHead = \"yolo-seg\";\n\nexport interface SegmenterOptions extends OrtSessionOptions {\n /**\n * Decoder family for the segmentation head. Default `\"yolo-seg\"` covers\n * YOLOv8-seg/v11-seg/v26-seg.\n */\n readonly head?: SegmenterHead;\n /** Class label spec — see {@link resolveLabels}. Defaults to the COCO 80-class preset. */\n readonly labels?: LabelSpec;\n /** Number of classes — used to validate the supplied labels. */\n readonly numClasses?: number;\n /** Model input `[width, height]` for letterboxing. Defaults to `[640, 640]`. */\n readonly inputSize?: readonly [number, number];\n /** Default minimum class score to keep a candidate. */\n readonly confThreshold?: number;\n /** Default IoU threshold for non-maximum suppression. */\n readonly iouThreshold?: number;\n /** Maximum number of instances per image. */\n readonly maxDetections?: number;\n /** Probability cutoff applied to soft masks. Defaults to `0.5`. */\n readonly maskThreshold?: number;\n}\n\nexport interface SegmenterPredictOptions {\n readonly confThreshold?: number;\n readonly iouThreshold?: number;\n /**\n * If set, keep only instances whose `classId` is in this list.\n * Mirrors Ultralytics' `model.predict(img, classes=[0, 16])`.\n */\n readonly classes?: readonly number[];\n}\n\n/**\n * Instance segmenter for YOLO seg ONNX models (v8-seg / v11-seg / ...).\n *\n * The model is expected to expose two outputs:\n *\n * 1. `output0`: `(1, 4 + numClasses + numMaskCoefs, numAnchors)` — per-anchor\n * predictions (boxes, class scores, mask coefficients).\n * 2. `output1`: `(1, numMaskCoefs, maskH, maskW)` — prototype masks.\n *\n * `predict()` returns `Promise<SegmentationResults[]>` (length 1 for a\n * single image), mirroring Ultralytics' API. The envelope exposes:\n *\n * - `boxes`: bulk numpy view (`xyxy`, `xywh`, `xyxyn`, `xywhn`, `cls`, `conf`).\n * - `masks`: per-instance binary masks cropped to each box.\n * - per-instance {@link SegmentationResult} via iteration.\n *\n * @example\n * ```typescript\n * const seg = await Segmenter.create(\"/models/yolov8n-seg.onnx\");\n * const r = (await seg.predict(\"/images/street.jpg\"))[0];\n * for (const inst of r) {\n * console.log(inst.cls, inst.conf, inst.box.xyxy);\n * }\n * ```\n */\nexport class Segmenter extends VisionTask {\n private constructor(\n session: OrtSession,\n private readonly _head: SegmenterHead,\n private readonly _labels: readonly string[],\n private readonly _names: Readonly<Record<number, string>>,\n private readonly _inputSize: readonly [number, number],\n private readonly _confThreshold: number,\n private readonly _iouThreshold: number,\n private readonly _maxDetections: number,\n private readonly _maskThreshold: number,\n ) {\n super(session);\n }\n\n /** Load the model and resolve labels. */\n static async create(model: ModelSource, options: SegmenterOptions = {}): Promise<Segmenter> {\n const head: SegmenterHead = options.head ?? \"yolo-seg\";\n if (head !== \"yolo-seg\") {\n throw new Error(`Unsupported segmenter head '${head}'. Supported: 'yolo-seg'.`);\n }\n const session = await OrtSession.create(model, options);\n const labels = resolveLabels(options.labels ?? \"coco\", {\n numClasses: options.numClasses,\n });\n const names: Record<number, string> = {};\n for (let i = 0; i < labels.length; i++) {\n names[i] = labels[i] as string;\n }\n return new Segmenter(\n session,\n head,\n labels,\n names,\n options.inputSize ?? [640, 640],\n options.confThreshold ?? 0.25,\n options.iouThreshold ?? 0.45,\n options.maxDetections ?? 300,\n options.maskThreshold ?? 0.5,\n );\n }\n\n /** The decoder family used to interpret the model's output. */\n get head(): SegmenterHead {\n return this._head;\n }\n\n /** Class labels indexed by class id. */\n get labels(): readonly string[] {\n return this._labels;\n }\n\n /** Class id → class name dict (matches Ultralytics' `model.names`). */\n get names(): Readonly<Record<number, string>> {\n return this._names;\n }\n\n /** Number of classes the model predicts. */\n get numClasses(): number {\n return this._labels.length;\n }\n\n /** Alias for {@link predict} (parity with PyTorch `nn.Module.__call__`). */\n async call(\n image: ImageInput,\n options: SegmenterPredictOptions = {},\n ): Promise<SegmentationResults[]> {\n return this.predict(image, options);\n }\n\n /** Run instance segmentation on a single image. */\n async predict(\n image: ImageInput,\n options: SegmenterPredictOptions = {},\n ): Promise<SegmentationResults[]> {\n const timer = new SpeedTimer();\n const path = typeof image === \"string\" ? image : null;\n const original = await loadImage(image);\n timer.stage(\"load\");\n const { tensor, scale, padLeft, padTop } = this._preprocess(original);\n timer.stage(\"preprocess\");\n const outputs = await this._session.run({ [this._session.inputName]: tensor });\n timer.stage(\"inference\");\n\n const { perAnchor, prototypes } = this._splitOutputs(outputs);\n\n const decodedAll = decodeYoloSeg(\n perAnchor.data as Float32Array,\n perAnchor.dims,\n prototypes.data as Float32Array,\n prototypes.dims,\n {\n numClasses: this._labels.length,\n inputWidth: this._inputSize[0],\n inputHeight: this._inputSize[1],\n originalWidth: original.width,\n originalHeight: original.height,\n padLeft,\n padTop,\n scale,\n confThreshold: options.confThreshold ?? this._confThreshold,\n iouThreshold: options.iouThreshold ?? this._iouThreshold,\n maxDetections: this._maxDetections,\n maskThreshold: this._maskThreshold,\n },\n );\n\n const decoded =\n options.classes !== undefined\n ? (() => {\n const allowed = new Set(options.classes);\n return decodedAll.filter((d) => allowed.has(d.classId));\n })()\n : decodedAll;\n\n const detections = decoded.map((d) =>\n this._buildResult(original, d.bbox, d.classId, d.confidence, d.mask),\n );\n\n const orig: readonly [number, number] = [original.height, original.width];\n const boxes = this._buildBoxes(detections, orig);\n const masks = this._buildMasks(detections, orig);\n timer.stage(\"postprocess\");\n return [\n new SegmentationResults(\n boxes,\n masks,\n detections,\n this._names,\n original,\n orig,\n path,\n timer.speed(),\n ),\n ];\n }\n\n private _preprocess(image: RGBImage): {\n tensor: ort.Tensor;\n scale: number;\n padLeft: number;\n padTop: number;\n } {\n const [tw, th] = this._inputSize;\n const lb = letterbox(image, tw, th);\n const f32 = toFloat32(lb.image);\n const chw = toCHW(f32, lb.image.width, lb.image.height, 3);\n return {\n tensor: toFloat32Tensor(chw, [1, 3, lb.image.height, lb.image.width]),\n scale: lb.scale,\n padLeft: lb.padLeft,\n padTop: lb.padTop,\n };\n }\n\n private _splitOutputs(outputs: Record<string, ort.Tensor>): {\n perAnchor: ort.Tensor;\n prototypes: ort.Tensor;\n } {\n let perAnchor: ort.Tensor | undefined;\n let prototypes: ort.Tensor | undefined;\n for (const name of this._session.outputNames) {\n const t = outputs[name];\n if (t === undefined) continue;\n if (t.dims.length === 3 && perAnchor === undefined) {\n perAnchor = t;\n } else if (t.dims.length === 4 && prototypes === undefined) {\n prototypes = t;\n }\n }\n if (perAnchor === undefined || prototypes === undefined) {\n const shapes = this._session.outputNames.map(\n (n) => `${n}: ${JSON.stringify(outputs[n]?.dims ?? [])}`,\n );\n throw new Error(\n `Segmenter expected one 3-D and one 4-D output, got [${shapes.join(\", \")}].`,\n );\n }\n return { perAnchor, prototypes };\n }\n\n private _buildResult(\n original: RGBImage,\n bbox: BoundingBox,\n classId: number,\n confidence: number,\n mask: Mask,\n ): SegmentationResult {\n const [x1, y1, x2, y2] = bbox.asIntXyxy();\n const cx1 = Math.max(0, x1);\n const cy1 = Math.max(0, y1);\n const cx2 = Math.min(original.width, x2);\n const cy2 = Math.min(original.height, y2);\n\n let segmentedImage: RGBImage;\n let finalMask = mask;\n if (cx2 > cx1 && cy2 > cy1 && mask.data.length > 0) {\n const cropW = cx2 - cx1;\n const cropH = cy2 - cy1;\n const mw = Math.min(mask.width, cropW);\n const mh = Math.min(mask.height, cropH);\n const segData = new Uint8Array(mw * mh * 3);\n for (let row = 0; row < mh; row++) {\n const srcRowOffset = ((cy1 + row) * original.width + cx1) * 3;\n const dstRowOffset = row * mw * 3;\n const maskRowOffset = row * mask.width;\n for (let col = 0; col < mw; col++) {\n const m = mask.data[maskRowOffset + col];\n if (m !== 0) {\n const s = srcRowOffset + col * 3;\n const d = dstRowOffset + col * 3;\n segData[d] = original.data[s];\n segData[d + 1] = original.data[s + 1];\n segData[d + 2] = original.data[s + 2];\n }\n }\n }\n segmentedImage = new RGBImage(segData, mw, mh);\n if (mw !== mask.width || mh !== mask.height) {\n const trimmed = new Uint8Array(mw * mh);\n for (let row = 0; row < mh; row++) {\n trimmed.set(\n mask.data.subarray(row * mask.width, row * mask.width + mw),\n row * mw,\n );\n }\n finalMask = new Mask(trimmed, mw, mh);\n }\n } else {\n finalMask = new Mask(new Uint8Array(0), 0, 0);\n segmentedImage = new RGBImage(new Uint8Array(0), 0, 0);\n }\n\n const className = this._names[classId] ?? `class_${classId}`;\n\n return {\n classId,\n className,\n confidence,\n bbox,\n cls: classId,\n name: className,\n conf: confidence,\n box: bbox,\n mask: finalMask,\n segmentedImage,\n };\n }\n\n private _buildBoxes(\n detections: readonly SegmentationResult[],\n origShape: readonly [number, number],\n ): Boxes {\n const n = detections.length;\n const xyxy = new Float32Array(n * 4);\n const cls = new Int32Array(n);\n const conf = new Float32Array(n);\n for (let i = 0; i < n; i++) {\n const d = detections[i] as SegmentationResult;\n xyxy[i * 4] = d.bbox.x1;\n xyxy[i * 4 + 1] = d.bbox.y1;\n xyxy[i * 4 + 2] = d.bbox.x2;\n xyxy[i * 4 + 3] = d.bbox.y2;\n cls[i] = d.classId;\n conf[i] = d.confidence;\n }\n return new Boxes(xyxy, cls, conf, origShape);\n }\n\n private _buildMasks(\n detections: readonly SegmentationResult[],\n origShape: readonly [number, number],\n ): Masks {\n const xyxy = new Float32Array(detections.length * 4);\n for (let i = 0; i < detections.length; i++) {\n const d = detections[i] as SegmentationResult;\n xyxy[i * 4] = d.bbox.x1;\n xyxy[i * 4 + 1] = d.bbox.y1;\n xyxy[i * 4 + 2] = d.bbox.x2;\n xyxy[i * 4 + 3] = d.bbox.y2;\n }\n return new Masks(\n detections.map((d) => d.mask),\n xyxy,\n origShape,\n );\n }\n}\n"],"mappings":";;;;;;;;;;AAqFA,IAAa,IAAb,MAAa,UAAkB,EAAW;CAGjB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CATrB,YACI,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACF;EADmB,AAEjB,MAAM,CAAO,GATI,KAAA,QAAA,GACA,KAAA,UAAA,GACA,KAAA,SAAA,GACA,KAAA,aAAA,GACA,KAAA,iBAAA,GACA,KAAA,gBAAA,GACA,KAAA,iBAAA,GACA,KAAA,iBAAA;CAGrB;CAGA,aAAa,OAAO,GAAoB,IAA4B,CAAC,GAAuB;EACxF,IAAM,IAAsB,EAAQ,QAAQ;EAC5C,IAAI,MAAS,YACT,MAAU,MAAM,+BAA+B,EAAK,0BAA0B;EAElF,IAAM,IAAU,MAAM,EAAW,OAAO,GAAO,CAAO,GAChD,IAAS,EAAc,EAAQ,UAAU,QAAQ,EACnD,YAAY,EAAQ,WACxB,CAAC,GACK,IAAgC,CAAC;EACvC,KAAK,IAAI,IAAI,GAAG,IAAI,EAAO,QAAQ,KAC/B,EAAM,KAAK,EAAO;EAEtB,OAAO,IAAI,EACP,GACA,G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symbol.toStringTag,{value:`Module`});const e=require("./vision/core/exceptions.cjs"),t=require("./vision/types.cjs"),n=require("./vision/results.cjs"),r=require("./vision/labels.cjs"),i=require("./vision/core/providers.cjs"),a=require("./vision/core/session.cjs"),o=require("./vision/io/image.cjs"),s=require("./vision/preprocess/image.cjs"),c=require("./vision/postprocess/classification.cjs"),l=require("./vision/postprocess/detection.cjs"),u=require("./vision/postprocess/segmentation.cjs"),d=require("./vision/tasks/base.cjs"),f=require("./vision/tasks/classifier.cjs"),p=require("./vision/tasks/detector.cjs"),m=require("./vision/tasks/segmenter.cjs"),h=require("./vision/index.cjs"),g=require("./vision/use-camera-stream.cjs"),_=require("./vision/luminance.cjs"),v=require("./vision/use-live-luminance.cjs");exports.BoundingBox=t.BoundingBox,exports.Boxes=n.Boxes,exports.COCO_CLASSES=r.COCO_CLASSES,exports.ClassificationResults=n.ClassificationResults,exports.Classifier=f.Classifier,exports.DEFAULT_PROVIDERS=i.DEFAULT_PROVIDERS,exports.DetectionResults=n.DetectionResults,exports.Detector=p.Detector,exports.ImageLoadError=e.ImageLoadError,exports.InferenceError=e.InferenceError,exports.LUMINANCE_SAMPLE_MAX_EDGE=_.LUMINANCE_SAMPLE_MAX_EDGE,exports.LabelMapError=e.LabelMapError,exports.LowLuminanceError=_.LowLuminanceError,exports.Mask=t.Mask,exports.Masks=n.Masks,exports.ModelLoadError=e.ModelLoadError,exports.OrtSession=a.OrtSession,exports.OrtVisionError=e.OrtVisionError,exports.Probs=n.Probs,exports.ProviderNotAvailableError=e.ProviderNotAvailableError,exports.RGBImage=t.RGBImage,exports.SegmentationResults=n.SegmentationResults,exports.Segmenter=m.Segmenter,exports.VERSION=h.VERSION,exports.VisionTask=d.VisionTask,exports.batchedNms=l.batchedNms,exports.computeImageLuminance=_.computeImageLuminance,exports.decodeYolo=l.decodeYolo,exports.decodeYoloAnchors=l.decodeYoloAnchors,exports.decodeYoloSeg=u.decodeYoloSeg,exports.decodeYoloV8=l.decodeYoloV8,exports.decodeYoloV8Anchors=l.decodeYoloV8Anchors,exports.decodeYoloV8Seg=u.decodeYoloV8Seg,exports.fromCv2=s.fromCv2,exports.isLuminanceAcceptable=_.isLuminanceAcceptable,exports.letterbox=s.letterbox,exports.loadImage=o.loadImage,exports.nms=l.nms,exports.normalize=s.normalize,exports.resize=s.resize,exports.resolveLabels=r.resolveLabels,exports.resolveProviders=i.resolveProviders,exports.softmax=c.softmax,exports.toCHW=s.toCHW,exports.toCv2=s.toCv2,exports.toFloat32=s.toFloat32,exports.toFloat32Tensor=s.toFloat32Tensor,exports.toTensor=s.toTensor,exports.topK=c.topK,exports.useCameraStream=g.useCameraStream,exports.useLiveLuminance=v.useLiveLuminance;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./vision/core/exceptions.cjs"),t=require("./vision/types.cjs"),n=require("./vision/core/timing.cjs"),r=require("./vision/results.cjs"),i=require("./vision/labels.cjs"),a=require("./vision/core/providers.cjs"),o=require("./vision/core/session.cjs"),s=require("./vision/io/image.cjs"),c=require("./vision/preprocess/image.cjs"),l=require("./vision/postprocess/classification.cjs"),u=require("./vision/postprocess/detection.cjs"),d=require("./vision/postprocess/segmentation.cjs"),f=require("./vision/tasks/base.cjs"),p=require("./vision/tasks/classifier.cjs"),m=require("./vision/tasks/detector.cjs"),h=require("./vision/tasks/segmenter.cjs"),g=require("./vision/index.cjs"),_=require("./vision/use-camera-stream.cjs"),v=require("./vision/luminance.cjs"),y=require("./vision/use-live-luminance.cjs");exports.BoundingBox=t.BoundingBox,exports.Boxes=r.Boxes,exports.COCO_CLASSES=i.COCO_CLASSES,exports.ClassificationResults=r.ClassificationResults,exports.Classifier=p.Classifier,exports.DEFAULT_PROVIDERS=a.DEFAULT_PROVIDERS,exports.DetectionResults=r.DetectionResults,exports.Detector=m.Detector,exports.ImageLoadError=e.ImageLoadError,exports.InferenceError=e.InferenceError,exports.LUMINANCE_SAMPLE_MAX_EDGE=v.LUMINANCE_SAMPLE_MAX_EDGE,exports.LabelMapError=e.LabelMapError,exports.LowLuminanceError=v.LowLuminanceError,exports.Mask=t.Mask,exports.Masks=r.Masks,exports.ModelLoadError=e.ModelLoadError,exports.OrtSession=o.OrtSession,exports.OrtVisionError=e.OrtVisionError,exports.Probs=r.Probs,exports.ProviderNotAvailableError=e.ProviderNotAvailableError,exports.RGBImage=t.RGBImage,exports.SegmentationResults=r.SegmentationResults,exports.Segmenter=h.Segmenter,exports.SpeedTimer=n.SpeedTimer,exports.VERSION=g.VERSION,exports.VisionTask=f.VisionTask,exports.batchedNms=u.batchedNms,exports.computeImageLuminance=v.computeImageLuminance,exports.decodeYolo=u.decodeYolo,exports.decodeYoloAnchors=u.decodeYoloAnchors,exports.decodeYoloSeg=d.decodeYoloSeg,exports.decodeYoloV8=u.decodeYoloV8,exports.decodeYoloV8Anchors=u.decodeYoloV8Anchors,exports.decodeYoloV8Seg=d.decodeYoloV8Seg,exports.fromCv2=c.fromCv2,exports.isLuminanceAcceptable=v.isLuminanceAcceptable,exports.letterbox=c.letterbox,exports.loadImage=s.loadImage,exports.nms=u.nms,exports.normalize=c.normalize,exports.resize=c.resize,exports.resolveLabels=i.resolveLabels,exports.resolveProviders=a.resolveProviders,exports.softmax=l.softmax,exports.toCHW=c.toCHW,exports.toCv2=c.toCv2,exports.toFloat32=c.toFloat32,exports.toFloat32Tensor=c.toFloat32Tensor,exports.toTensor=c.toTensor,exports.topK=l.topK,exports.useCameraStream=_.useCameraStream,exports.useLiveLuminance=y.useLiveLuminance;
package/dist/vision.d.ts CHANGED
@@ -149,8 +149,8 @@ export declare class ClassificationResults {
149
149
  readonly origImg: RGBImage;
150
150
  readonly origShape: readonly [number, number];
151
151
  readonly path: string | null;
152
- readonly speed: Readonly<Record<string, number>>;
153
- constructor(probs: Probs, result: ClassificationResult, names: Readonly<Record<number, string>>, origImg: RGBImage, origShape: readonly [number, number], path?: string | null, speed?: Readonly<Record<string, number>>);
152
+ readonly speed: Readonly<Speed>;
153
+ constructor(probs: Probs, result: ClassificationResult, names: Readonly<Record<number, string>>, origImg: RGBImage, origShape: readonly [number, number], path?: string | null, speed?: Readonly<Speed>);
154
154
  /** Top-1 class index (Ultralytics-style alias). */
155
155
  get cls(): number;
156
156
  /** Top-1 confidence (Ultralytics-style alias). */
@@ -385,12 +385,12 @@ export declare interface DecodeYoloSegOptions {
385
385
 
386
386
  /**
387
387
  * @deprecated since 0.2.0 — use {@link decodeYolo}. Same behavior; the
388
- * decoder covers v8/v9/v10/v11/v12 detect heads. Will be removed in 0.3.0.
388
+ * decoder covers v8/v9/v10/v11/v12 detect heads. Will be removed in 0.4.0.
389
389
  */
390
390
  export declare function decodeYoloV8(output: Float32Array, outputDims: readonly number[], options: DecodeYoloOptions): DecodedDetection[];
391
391
 
392
392
  /**
393
- * @deprecated since 0.2.0 — use {@link decodeYoloAnchors}. Will be removed in 0.3.0.
393
+ * @deprecated since 0.2.0 — use {@link decodeYoloAnchors}. Will be removed in 0.4.0.
394
394
  */
395
395
  export declare function decodeYoloV8Anchors(data: Float32Array, dims: readonly number[], options: DecodeYoloAnchorsOptions): DecodedAnchors;
396
396
 
@@ -400,7 +400,7 @@ export declare type DecodeYoloV8AnchorsOptions = DecodeYoloAnchorsOptions;
400
400
  /** @deprecated since 0.2.0 — use {@link DecodeYoloOptions}. */
401
401
  export declare type DecodeYoloV8Options = DecodeYoloOptions;
402
402
 
403
- /** @deprecated since 0.2.0 — use {@link decodeYoloSeg}. Will be removed in 0.3.0. */
403
+ /** @deprecated since 0.2.0 — use {@link decodeYoloSeg}. Will be removed in 0.4.0. */
404
404
  export declare function decodeYoloV8Seg(perAnchorData: Float32Array, perAnchorDims: readonly number[], prototypeData: Float32Array, prototypeDims: readonly number[], options: DecodeYoloSegOptions): DecodedSegmentation[];
405
405
 
406
406
  /** @deprecated since 0.2.0 — use {@link DecodeYoloSegOptions}. */
@@ -459,8 +459,8 @@ export declare class DetectionResults implements Iterable<DetectionResult> {
459
459
  readonly origImg: RGBImage;
460
460
  readonly origShape: readonly [number, number];
461
461
  readonly path: string | null;
462
- readonly speed: Readonly<Record<string, number>>;
463
- constructor(boxes: Boxes, detections: readonly DetectionResult[], names: Readonly<Record<number, string>>, origImg: RGBImage, origShape: readonly [number, number], path?: string | null, speed?: Readonly<Record<string, number>>);
462
+ readonly speed: Readonly<Speed>;
463
+ constructor(boxes: Boxes, detections: readonly DetectionResult[], names: Readonly<Record<number, string>>, origImg: RGBImage, origShape: readonly [number, number], path?: string | null, speed?: Readonly<Speed>);
464
464
  /** Number of surviving detections. */
465
465
  get length(): number;
466
466
  /** Index into the per-instance detections. */
@@ -514,7 +514,12 @@ export declare class Detector extends VisionTask {
514
514
  * {@link DetectorPredictOptions} (including `classes`) is supported.
515
515
  */
516
516
  call(image: ImageInput, options?: DetectorPredictOptions): Promise<DetectionResults[]>;
517
- /** Run detection on a single image. */
517
+ /**
518
+ * Run detection on a single image.
519
+ *
520
+ * The returned envelope carries a {@link Speed} breakdown in `speed`,
521
+ * mirroring Ultralytics' `results[0].speed`.
522
+ */
518
523
  predict(image: ImageInput, options?: DetectorPredictOptions): Promise<DetectionResults[]>;
519
524
  private _preprocess;
520
525
  private _buildResult;
@@ -934,8 +939,8 @@ export declare interface LetterboxResult {
934
939
  readonly origImg: RGBImage;
935
940
  readonly origShape: readonly [number, number];
936
941
  readonly path: string | null;
937
- readonly speed: Readonly<Record<string, number>>;
938
- constructor(boxes: Boxes, masks: Masks, detections: readonly SegmentationResult[], names: Readonly<Record<number, string>>, origImg: RGBImage, origShape: readonly [number, number], path?: string | null, speed?: Readonly<Record<string, number>>);
942
+ readonly speed: Readonly<Speed>;
943
+ constructor(boxes: Boxes, masks: Masks, detections: readonly SegmentationResult[], names: Readonly<Record<number, string>>, origImg: RGBImage, origShape: readonly [number, number], path?: string | null, speed?: Readonly<Speed>);
939
944
  /** Number of surviving instances. */
940
945
  get length(): number;
941
946
  /** Index into the per-instance results. */
@@ -1049,6 +1054,59 @@ export declare interface LetterboxResult {
1049
1054
  /** Apply numerically-stable softmax to a 1-D vector of logits. */
1050
1055
  export declare function softmax(logits: Float32Array | readonly number[]): Float32Array;
1051
1056
 
1057
+ /**
1058
+ * Per-stage timing for a single `predict()` call.
1059
+ *
1060
+ * Populates the `speed` field every `Results` envelope carries, mirroring
1061
+ * Ultralytics' `results[0].speed`. All values are milliseconds measured with
1062
+ * `performance.now()`.
1063
+ */
1064
+ /**
1065
+ * Stage durations of one inference, in milliseconds.
1066
+ *
1067
+ * `preprocess`, `inference` and `postprocess` are the three keys Ultralytics
1068
+ * reports, measured over the same boundaries. `load` is specific to this SDK:
1069
+ * `predict()` accepts a URL, `Blob` or DOM element and decodes it internally,
1070
+ * so the fetch/decode cost would otherwise be invisible — and on a cold cache
1071
+ * it dominates everything else.
1072
+ */
1073
+ export declare interface Speed {
1074
+ /** Fetching and decoding the input into an `RGBImage`. */
1075
+ load: number;
1076
+ /** Letterbox/resize, normalization and tensor packing. */
1077
+ preprocess: number;
1078
+ /** The ONNX Runtime forward pass. */
1079
+ inference: number;
1080
+ /** Decoding raw outputs into results (NMS, mask assembly, top-k). */
1081
+ postprocess: number;
1082
+ }
1083
+
1084
+ /**
1085
+ * Accumulate stage durations while a `predict()` call runs.
1086
+ *
1087
+ * Each `stage()` call closes the previous stage: the elapsed time since the
1088
+ * last boundary is attributed to the name given. This keeps the call sites
1089
+ * free of paired start/stop bookkeeping and guarantees the four stages tile
1090
+ * the whole call without gaps.
1091
+ */
1092
+ export declare class SpeedTimer {
1093
+ private _last;
1094
+ private readonly _speed;
1095
+ constructor();
1096
+ /**
1097
+ * Attribute the time elapsed since the previous boundary to `stage`.
1098
+ *
1099
+ * @param stage Which stage just finished.
1100
+ */
1101
+ stage(stage: keyof Speed): void;
1102
+ /**
1103
+ * The accumulated durations.
1104
+ *
1105
+ * @returns The `speed` object to hand to the `Results` envelope.
1106
+ */
1107
+ speed(): Speed;
1108
+ }
1109
+
1052
1110
  /**
1053
1111
  * Transpose interleaved HWC data to planar CHW layout.
1054
1112
  *
package/dist/vision.js CHANGED
@@ -1,20 +1,21 @@
1
1
  import { ImageLoadError as e, InferenceError as t, LabelMapError as n, ModelLoadError as r, OrtVisionError as i, ProviderNotAvailableError as a } from "./vision/core/exceptions.js";
2
2
  import { BoundingBox as o, Mask as s, RGBImage as c } from "./vision/types.js";
3
- import { Boxes as l, ClassificationResults as u, DetectionResults as d, Masks as f, Probs as p, SegmentationResults as m } from "./vision/results.js";
4
- import { COCO_CLASSES as h, resolveLabels as g } from "./vision/labels.js";
5
- import { DEFAULT_PROVIDERS as _, resolveProviders as v } from "./vision/core/providers.js";
6
- import { OrtSession as y } from "./vision/core/session.js";
7
- import { loadImage as b } from "./vision/io/image.js";
8
- import { fromCv2 as x, letterbox as S, normalize as C, resize as w, toCHW as T, toCv2 as E, toFloat32 as D, toFloat32Tensor as O, toTensor as k } from "./vision/preprocess/image.js";
9
- import { softmax as A, topK as j } from "./vision/postprocess/classification.js";
10
- import { batchedNms as M, decodeYolo as N, decodeYoloAnchors as P, decodeYoloV8 as F, decodeYoloV8Anchors as I, nms as L } from "./vision/postprocess/detection.js";
11
- import { decodeYoloSeg as R, decodeYoloV8Seg as z } from "./vision/postprocess/segmentation.js";
12
- import { VisionTask as B } from "./vision/tasks/base.js";
13
- import { Classifier as V } from "./vision/tasks/classifier.js";
14
- import { Detector as H } from "./vision/tasks/detector.js";
15
- import { Segmenter as U } from "./vision/tasks/segmenter.js";
16
- import { VERSION as W } from "./vision/index.js";
17
- import { useCameraStream as G } from "./vision/use-camera-stream.js";
18
- import { LUMINANCE_SAMPLE_MAX_EDGE as K, LowLuminanceError as q, computeImageLuminance as J, isLuminanceAcceptable as Y } from "./vision/luminance.js";
19
- import { useLiveLuminance as X } from "./vision/use-live-luminance.js";
20
- export { o as BoundingBox, l as Boxes, h as COCO_CLASSES, u as ClassificationResults, V as Classifier, _ as DEFAULT_PROVIDERS, d as DetectionResults, H as Detector, e as ImageLoadError, t as InferenceError, K as LUMINANCE_SAMPLE_MAX_EDGE, n as LabelMapError, q as LowLuminanceError, s as Mask, f as Masks, r as ModelLoadError, y as OrtSession, i as OrtVisionError, p as Probs, a as ProviderNotAvailableError, c as RGBImage, m as SegmentationResults, U as Segmenter, W as VERSION, B as VisionTask, M as batchedNms, J as computeImageLuminance, N as decodeYolo, P as decodeYoloAnchors, R as decodeYoloSeg, F as decodeYoloV8, I as decodeYoloV8Anchors, z as decodeYoloV8Seg, x as fromCv2, Y as isLuminanceAcceptable, S as letterbox, b as loadImage, L as nms, C as normalize, w as resize, g as resolveLabels, v as resolveProviders, A as softmax, T as toCHW, E as toCv2, D as toFloat32, O as toFloat32Tensor, k as toTensor, j as topK, G as useCameraStream, X as useLiveLuminance };
3
+ import { SpeedTimer as l } from "./vision/core/timing.js";
4
+ import { Boxes as u, ClassificationResults as d, DetectionResults as f, Masks as p, Probs as m, SegmentationResults as h } from "./vision/results.js";
5
+ import { COCO_CLASSES as g, resolveLabels as _ } from "./vision/labels.js";
6
+ import { DEFAULT_PROVIDERS as v, resolveProviders as y } from "./vision/core/providers.js";
7
+ import { OrtSession as b } from "./vision/core/session.js";
8
+ import { loadImage as x } from "./vision/io/image.js";
9
+ import { fromCv2 as S, letterbox as C, normalize as w, resize as T, toCHW as E, toCv2 as D, toFloat32 as O, toFloat32Tensor as k, toTensor as A } from "./vision/preprocess/image.js";
10
+ import { softmax as j, topK as M } from "./vision/postprocess/classification.js";
11
+ import { batchedNms as N, decodeYolo as P, decodeYoloAnchors as F, decodeYoloV8 as I, decodeYoloV8Anchors as L, nms as R } from "./vision/postprocess/detection.js";
12
+ import { decodeYoloSeg as z, decodeYoloV8Seg as B } from "./vision/postprocess/segmentation.js";
13
+ import { VisionTask as V } from "./vision/tasks/base.js";
14
+ import { Classifier as H } from "./vision/tasks/classifier.js";
15
+ import { Detector as U } from "./vision/tasks/detector.js";
16
+ import { Segmenter as W } from "./vision/tasks/segmenter.js";
17
+ import { VERSION as G } from "./vision/index.js";
18
+ import { useCameraStream as K } from "./vision/use-camera-stream.js";
19
+ import { LUMINANCE_SAMPLE_MAX_EDGE as q, LowLuminanceError as J, computeImageLuminance as Y, isLuminanceAcceptable as X } from "./vision/luminance.js";
20
+ import { useLiveLuminance as Z } from "./vision/use-live-luminance.js";
21
+ export { o as BoundingBox, u as Boxes, g as COCO_CLASSES, d as ClassificationResults, H as Classifier, v as DEFAULT_PROVIDERS, f as DetectionResults, U as Detector, e as ImageLoadError, t as InferenceError, q as LUMINANCE_SAMPLE_MAX_EDGE, n as LabelMapError, J as LowLuminanceError, s as Mask, p as Masks, r as ModelLoadError, b as OrtSession, i as OrtVisionError, m as Probs, a as ProviderNotAvailableError, c as RGBImage, h as SegmentationResults, W as Segmenter, l as SpeedTimer, G as VERSION, V as VisionTask, N as batchedNms, Y as computeImageLuminance, P as decodeYolo, F as decodeYoloAnchors, z as decodeYoloSeg, I as decodeYoloV8, L as decodeYoloV8Anchors, B as decodeYoloV8Seg, S as fromCv2, X as isLuminanceAcceptable, C as letterbox, x as loadImage, R as nms, w as normalize, T as resize, _ as resolveLabels, y as resolveProviders, j as softmax, E as toCHW, D as toCv2, O as toFloat32, k as toFloat32Tensor, A as toTensor, M as topK, K as useCameraStream, Z as useLiveLuminance };
@@ -1,2 +1,2 @@
1
- function e(e){try{return JSON.parse(e)}catch{return e}}function t(t,n={}){let{protocols:r,maxRetries:i=10,initialBackoff:a=1e3,maxBackoff:o=3e4,pingInterval:s=0,pingPayload:c=JSON.stringify({type:`ping`}),parser:l=e,onOpen:u,onMessage:d,onClose:f,onError:p,onStatusChange:m}=n,h=null,g=null,_=null,v=0,y=`idle`,b=!1;function x(e){y!==e&&(y=e,m?.(e))}function S(){_&&=(clearInterval(_),null)}function C(){!s||s<=0||(S(),_=setInterval(()=>{h?.readyState===WebSocket.OPEN&&h.send(c)},s))}function w(){if(b)return;if(v>=i){x(`error`);return}let e=Math.min(a*2**v,o);v+=1,g=setTimeout(T,e)}function T(){if(b)return;h&&(h.onopen=null,h.onmessage=null,h.onclose=null,h.onerror=null,h.close()),x(`connecting`);let e=new WebSocket(t,r);h=e,e.onopen=e=>{v=0,x(`open`),C(),u?.(e)},e.onmessage=e=>{let t=typeof e.data==`string`?e.data:``;d?.({data:l(t),raw:e})},e.onerror=e=>{p?.(e)},e.onclose=e=>{S(),f?.(e),h=null,x(`closed`),!b&&!e.wasClean&&w()}}function E(e){return h?.readyState===WebSocket.OPEN?(h.send(e),!0):!1}function D(e,t){b=!0,g&&=(clearTimeout(g),null),S(),v=0,h&&=(x(`closing`),h.close(e,t),null),x(`closed`)}function O(){g&&=(clearTimeout(g),null),v=0,b=!1,T()}return T(),{send:E,close:D,reconnect:O,get status(){return y}}}exports.createWebSocket=t;
1
+ function e(e){try{return JSON.parse(e)}catch{return e}}function t(t,n={}){let{protocols:r,maxRetries:i=10,initialBackoff:a=1e3,maxBackoff:o=3e4,pingInterval:s=0,pingPayload:c=JSON.stringify({type:`ping`}),respondToPing:l=!0,pongPayload:u=JSON.stringify({type:`pong`}),queueWhileClosed:d=!1,maxQueuedMessages:f=100,parser:p=e,onOpen:m,onMessage:h,onClose:g,onError:_,onStatusChange:v}=n,y=null,b=null,x=null,S=0,C=`idle`,w=!1,T=[];function E(e){return typeof e==`object`&&!!e&&e.type===`ping`}function D(e){for(;T.length>0&&e.readyState===WebSocket.OPEN;)e.send(T.shift())}function O(e){C!==e&&(C=e,v?.(e))}function k(){x&&=(clearInterval(x),null)}function A(){!s||s<=0||(k(),x=setInterval(()=>{y?.readyState===WebSocket.OPEN&&y.send(c)},s))}function j(){if(w)return;if(S>=i){O(`error`);return}let e=Math.min(a*2**S,o);S+=1,b=setTimeout(M,e)}function M(){if(w)return;if(y){let e=y;e.onmessage=null,e.onclose=null,e.onerror=null,e.readyState!==WebSocket.CONNECTING&&(e.onopen=null),F(e)}O(`connecting`);let e=new WebSocket(t,r);y=e,e.onopen=t=>{S=0,O(`open`),A(),D(e),m?.(t)},e.onmessage=t=>{let n=typeof t.data==`string`?t.data:``,r=p(n);l&&E(r)&&e.readyState===WebSocket.OPEN&&e.send(u),h?.({data:r,raw:t})},e.onerror=e=>{_?.(e)},e.onclose=e=>{k(),g?.(e),y=null,O(`closed`),!w&&!e.wasClean&&j()}}function N(e){return y?.readyState===WebSocket.OPEN?(y.send(e),!0):!d||w?!1:(T.length>=f&&T.shift(),T.push(e),!0)}function P(e,t){w=!0,b&&=(clearTimeout(b),null),k(),S=0,T.length=0,y&&=(O(`closing`),F(y,e,t),null),O(`closed`)}function F(e,t,n){if(e.readyState===WebSocket.CONNECTING){e.onopen=()=>e.close(t,n),e.onmessage=null,e.onerror=null,e.onclose=null;return}e.close(t,n)}function I(){b&&=(clearTimeout(b),null),S=0,w=!1,M()}return M(),{send:N,close:P,reconnect:I,get status(){return C}}}exports.createWebSocket=t;
2
2
  //# sourceMappingURL=create-web-socket.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"create-web-socket.cjs","names":[],"sources":["../../src/ws/create-web-socket.ts"],"sourcesContent":["export type WebSocketStatus = \"idle\" | \"connecting\" | \"open\" | \"closing\" | \"closed\" | \"error\";\n\nexport interface WebSocketMessage<T> {\n /** Parsed payload — JSON-decoded when possible, raw string otherwise. */\n data: T;\n /** The original `MessageEvent`. */\n raw: MessageEvent;\n}\n\nexport interface CreateWebSocketOptions<T> {\n /** Subprotocol(s) forwarded to the `WebSocket` constructor. */\n protocols?: string | string[];\n /** Max reconnect attempts. Default: 10. Pass 0 to disable. */\n maxRetries?: number;\n /** Initial backoff (ms). Doubles each attempt, capped at `maxBackoff`. Default: 1000. */\n initialBackoff?: number;\n /** Maximum backoff (ms). Default: 30000. */\n maxBackoff?: number;\n /**\n * Ping interval (ms). When set, the client sends `pingPayload` periodically\n * to keep the socket alive. Default: 0 (disabled).\n */\n pingInterval?: number;\n /** Payload sent on each ping. Default: `JSON.stringify({ type: \"ping\" })`. */\n pingPayload?: string | Blob | BufferSource;\n /** Parse incoming frames. Default: JSON with raw-string fallback. */\n parser?: (raw: string) => T;\n onOpen?: (event: Event) => void;\n onMessage?: (message: WebSocketMessage<T>) => void;\n onClose?: (event: CloseEvent) => void;\n onError?: (event: Event) => void;\n onStatusChange?: (status: WebSocketStatus) => void;\n}\n\nexport interface WebSocketController {\n /** Send a payload over the current connection. No-op when not open. */\n send: (payload: string | Blob | BufferSource) => boolean;\n /** Close the connection and stop reconnecting. */\n close: (code?: number, reason?: string) => void;\n /** Force an immediate reconnect, resetting the retry counter. */\n reconnect: () => void;\n /** Current connection status. */\n readonly status: WebSocketStatus;\n}\n\nfunction defaultParser<T>(raw: string): T {\n try {\n return JSON.parse(raw) as T;\n } catch {\n return raw as unknown as T;\n }\n}\n\n/**\n * Open a WebSocket with automatic exponential-backoff reconnect, optional\n * heartbeat pings, and typed JSON parsing.\n *\n * @param url - Full ws:// or wss:// URL.\n * @param options - Connection configuration and callbacks.\n * @returns Controller exposing `send`, `close`, `reconnect`, and `status`.\n */\nexport function createWebSocket<T = unknown>(\n url: string,\n options: CreateWebSocketOptions<T> = {},\n): WebSocketController {\n const {\n protocols,\n maxRetries = 10,\n initialBackoff = 1000,\n maxBackoff = 30000,\n pingInterval = 0,\n pingPayload = JSON.stringify({ type: \"ping\" }),\n parser = defaultParser<T>,\n onOpen,\n onMessage,\n onClose,\n onError,\n onStatusChange,\n } = options;\n\n let socket: WebSocket | null = null;\n let retryTimer: ReturnType<typeof setTimeout> | null = null;\n let pingTimer: ReturnType<typeof setInterval> | null = null;\n let retries = 0;\n let status: WebSocketStatus = \"idle\";\n let closed = false;\n\n function setStatus(next: WebSocketStatus): void {\n if (status === next) return;\n status = next;\n onStatusChange?.(next);\n }\n\n function clearPing(): void {\n if (pingTimer) {\n clearInterval(pingTimer);\n pingTimer = null;\n }\n }\n\n function startPing(): void {\n if (!pingInterval || pingInterval <= 0) return;\n clearPing();\n pingTimer = setInterval(() => {\n if (socket?.readyState === WebSocket.OPEN) {\n socket.send(pingPayload);\n }\n }, pingInterval);\n }\n\n function scheduleReconnect(): void {\n if (closed) return;\n if (retries >= maxRetries) {\n setStatus(\"error\");\n return;\n }\n const delay = Math.min(initialBackoff * 2 ** retries, maxBackoff);\n retries += 1;\n retryTimer = setTimeout(connect, delay);\n }\n\n function connect(): void {\n if (closed) return;\n if (socket) {\n socket.onopen = null;\n socket.onmessage = null;\n socket.onclose = null;\n socket.onerror = null;\n socket.close();\n }\n setStatus(\"connecting\");\n\n const ws = new WebSocket(url, protocols);\n socket = ws;\n\n ws.onopen = (event) => {\n retries = 0;\n setStatus(\"open\");\n startPing();\n onOpen?.(event);\n };\n\n ws.onmessage = (event) => {\n const raw = typeof event.data === \"string\" ? event.data : \"\";\n onMessage?.({\n data: parser(raw),\n raw: event,\n });\n };\n\n ws.onerror = (event) => {\n onError?.(event);\n };\n\n ws.onclose = (event) => {\n clearPing();\n onClose?.(event);\n socket = null;\n setStatus(\"closed\");\n if (!closed && !event.wasClean) {\n scheduleReconnect();\n }\n };\n }\n\n function send(payload: string | Blob | BufferSource): boolean {\n if (socket?.readyState !== WebSocket.OPEN) return false;\n socket.send(payload);\n return true;\n }\n\n function close(code?: number, reason?: string): void {\n closed = true;\n if (retryTimer) {\n clearTimeout(retryTimer);\n retryTimer = null;\n }\n clearPing();\n retries = 0;\n if (socket) {\n setStatus(\"closing\");\n socket.close(code, reason);\n socket = null;\n }\n setStatus(\"closed\");\n }\n\n function reconnect(): void {\n if (retryTimer) {\n clearTimeout(retryTimer);\n retryTimer = null;\n }\n retries = 0;\n closed = false;\n connect();\n }\n\n connect();\n\n return {\n send,\n close,\n reconnect,\n get status() {\n return status;\n },\n };\n}\n"],"mappings":"AA6CA,SAAS,EAAiB,EAAgB,CACtC,GAAI,CACA,OAAO,KAAK,MAAM,CAAG,CACzB,MAAQ,CACJ,OAAO,CACX,CACJ,CAUA,SAAgB,EACZ,EACA,EAAqC,CAAC,EACnB,CACnB,GAAM,CACF,YACA,aAAa,GACb,iBAAiB,IACjB,aAAa,IACb,eAAe,EACf,cAAc,KAAK,UAAU,CAAE,KAAM,MAAO,CAAC,EAC7C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AK,EAAgD,CAG1D,OAFI,GAAQ,aAAe,UAAU,MACrC,EAAO,KAAK,CAAO,EACZ,IAF2C,EAGtD,CAEA,SAAS,EAAM,EAAe,EAAuB,CACjD,EAAS,GACT,AAEI,KADA,aAAa,CAAU,EACV,MAEjB,EAAU,EACV,EAAU,EACV,AAGI,KAFA,EAAU,SAAS,EACnB,EAAO,MAAM,EAAM,CAAM,EAChB,MAEb,EAAU,QAAQ,CACtB,CAEA,SAAS,GAAkB,CACvB,AAEI,KADA,aAAa,CAAU,EACV,MAEjB,EAAU,EACV,EAAS,GACT,EAAQ,CACZ,CAIA,OAFA,EAAQ,EAED,CACH,OACA,QACA,YACA,IAAI,QAAS,CACT,OAAO,CACX,CACJ,CACJ"}
1
+ {"version":3,"file":"create-web-socket.cjs","names":[],"sources":["../../src/ws/create-web-socket.ts"],"sourcesContent":["export type WebSocketStatus = \"idle\" | \"connecting\" | \"open\" | \"closing\" | \"closed\" | \"error\";\n\nexport interface WebSocketMessage<T> {\n /** Parsed payload — JSON-decoded when possible, raw string otherwise. */\n data: T;\n /** The original `MessageEvent`. */\n raw: MessageEvent;\n}\n\nexport interface CreateWebSocketOptions<T> {\n /** Subprotocol(s) forwarded to the `WebSocket` constructor. */\n protocols?: string | string[];\n /** Max reconnect attempts. Default: 10. Pass 0 to disable. */\n maxRetries?: number;\n /** Initial backoff (ms). Doubles each attempt, capped at `maxBackoff`. Default: 1000. */\n initialBackoff?: number;\n /** Maximum backoff (ms). Default: 30000. */\n maxBackoff?: number;\n /**\n * Ping interval (ms). When set, the client sends `pingPayload` periodically\n * to keep the socket alive. Default: 0 (disabled).\n *\n * Leave it off against a `tempest-fastapi-sdk` server: that server pings on\n * its own and answers a client-sent `{\"type\":\"ping\"}` with nothing, while a\n * strict handler rejects the unknown frame. What it needs from the client\n * is the `pong` reply, which `respondToPing` sends for you.\n */\n pingInterval?: number;\n /** Payload sent on each ping. Default: `JSON.stringify({ type: \"ping\" })`. */\n pingPayload?: string | Blob | BufferSource;\n /**\n * Reply to a server `{\"type\":\"ping\"}` with `pongPayload`. Default: true.\n *\n * `tempest-fastapi-sdk` closes a socket with code `4408` when no `pong`\n * arrives within `WS_HEARTBEAT_TIMEOUT_SECONDS`, so a client that stays\n * silent is dropped once per timeout. The ping is still forwarded to\n * `onMessage` — the reply is sent before your handler runs.\n */\n respondToPing?: boolean;\n /** Payload sent in reply to a server ping. Default: `JSON.stringify({ type: \"pong\" })`. */\n pongPayload?: string | Blob | BufferSource;\n /**\n * Buffer payloads sent while the socket is not open and flush them on the\n * next `open`. Default: false — `send()` returns false and drops.\n *\n * Without it, an action fired during reconnect backoff vanishes and the UI\n * cannot tell \"never sent\" from \"sent and ignored\".\n */\n queueWhileClosed?: boolean;\n /** Cap on buffered payloads when `queueWhileClosed` is on. Default: 100. */\n maxQueuedMessages?: number;\n /** Parse incoming frames. Default: JSON with raw-string fallback. */\n parser?: (raw: string) => T;\n onOpen?: (event: Event) => void;\n onMessage?: (message: WebSocketMessage<T>) => void;\n onClose?: (event: CloseEvent) => void;\n onError?: (event: Event) => void;\n onStatusChange?: (status: WebSocketStatus) => void;\n}\n\nexport interface WebSocketController {\n /** Send a payload over the current connection. No-op when not open. */\n send: (payload: string | Blob | BufferSource) => boolean;\n /** Close the connection and stop reconnecting. */\n close: (code?: number, reason?: string) => void;\n /** Force an immediate reconnect, resetting the retry counter. */\n reconnect: () => void;\n /** Current connection status. */\n readonly status: WebSocketStatus;\n}\n\nfunction defaultParser<T>(raw: string): T {\n try {\n return JSON.parse(raw) as T;\n } catch {\n return raw as unknown as T;\n }\n}\n\n/**\n * Open a WebSocket with automatic exponential-backoff reconnect, optional\n * heartbeat pings, and typed JSON parsing.\n *\n * @param url - Full ws:// or wss:// URL.\n * @param options - Connection configuration and callbacks.\n * @returns Controller exposing `send`, `close`, `reconnect`, and `status`.\n */\nexport function createWebSocket<T = unknown>(\n url: string,\n options: CreateWebSocketOptions<T> = {},\n): WebSocketController {\n const {\n protocols,\n maxRetries = 10,\n initialBackoff = 1000,\n maxBackoff = 30000,\n pingInterval = 0,\n pingPayload = JSON.stringify({ type: \"ping\" }),\n respondToPing = true,\n pongPayload = JSON.stringify({ type: \"pong\" }),\n queueWhileClosed = false,\n maxQueuedMessages = 100,\n parser = defaultParser<T>,\n onOpen,\n onMessage,\n onClose,\n onError,\n onStatusChange,\n } = options;\n\n let socket: WebSocket | null = null;\n let retryTimer: ReturnType<typeof setTimeout> | null = null;\n let pingTimer: ReturnType<typeof setInterval> | null = null;\n let retries = 0;\n let status: WebSocketStatus = \"idle\";\n let closed = false;\n const outbox: Array<string | Blob | BufferSource> = [];\n\n /** True for a decoded frame that is the server's heartbeat ping. */\n function isServerPing(data: unknown): boolean {\n return (\n typeof data === \"object\" &&\n data !== null &&\n (data as { type?: unknown }).type === \"ping\"\n );\n }\n\n /** Send everything buffered while the socket was down, oldest first. */\n function flushOutbox(ws: WebSocket): void {\n while (outbox.length > 0 && ws.readyState === WebSocket.OPEN) {\n ws.send(outbox.shift()!);\n }\n }\n\n function setStatus(next: WebSocketStatus): void {\n if (status === next) return;\n status = next;\n onStatusChange?.(next);\n }\n\n function clearPing(): void {\n if (pingTimer) {\n clearInterval(pingTimer);\n pingTimer = null;\n }\n }\n\n function startPing(): void {\n if (!pingInterval || pingInterval <= 0) return;\n clearPing();\n pingTimer = setInterval(() => {\n if (socket?.readyState === WebSocket.OPEN) {\n socket.send(pingPayload);\n }\n }, pingInterval);\n }\n\n function scheduleReconnect(): void {\n if (closed) return;\n if (retries >= maxRetries) {\n setStatus(\"error\");\n return;\n }\n const delay = Math.min(initialBackoff * 2 ** retries, maxBackoff);\n retries += 1;\n retryTimer = setTimeout(connect, delay);\n }\n\n function connect(): void {\n if (closed) return;\n if (socket) {\n const previous = socket;\n previous.onmessage = null;\n previous.onclose = null;\n previous.onerror = null;\n if (previous.readyState !== WebSocket.CONNECTING) previous.onopen = null;\n closeSocket(previous);\n }\n setStatus(\"connecting\");\n\n const ws = new WebSocket(url, protocols);\n socket = ws;\n\n ws.onopen = (event) => {\n retries = 0;\n setStatus(\"open\");\n startPing();\n flushOutbox(ws);\n onOpen?.(event);\n };\n\n ws.onmessage = (event) => {\n const raw = typeof event.data === \"string\" ? event.data : \"\";\n const data = parser(raw);\n if (respondToPing && isServerPing(data) && ws.readyState === WebSocket.OPEN) {\n ws.send(pongPayload);\n }\n onMessage?.({ data, raw: event });\n };\n\n ws.onerror = (event) => {\n onError?.(event);\n };\n\n ws.onclose = (event) => {\n clearPing();\n onClose?.(event);\n socket = null;\n setStatus(\"closed\");\n if (!closed && !event.wasClean) {\n scheduleReconnect();\n }\n };\n }\n\n function send(payload: string | Blob | BufferSource): boolean {\n if (socket?.readyState === WebSocket.OPEN) {\n socket.send(payload);\n return true;\n }\n if (!queueWhileClosed || closed) return false;\n if (outbox.length >= maxQueuedMessages) outbox.shift();\n outbox.push(payload);\n return true;\n }\n\n function close(code?: number, reason?: string): void {\n closed = true;\n if (retryTimer) {\n clearTimeout(retryTimer);\n retryTimer = null;\n }\n clearPing();\n retries = 0;\n outbox.length = 0;\n if (socket) {\n setStatus(\"closing\");\n closeSocket(socket, code, reason);\n socket = null;\n }\n setStatus(\"closed\");\n }\n\n /**\n * Close a socket without the \"closed before the connection is established\"\n * console warning.\n *\n * A socket still in `CONNECTING` cannot be closed cleanly — the browser\n * logs that warning on every attempt. React's StrictMode mounts, unmounts\n * and remounts each component in development, so the first socket is\n * always torn down mid-handshake and the message shows up in every dev\n * session of every app using the hook. Deferring the close to `onopen`\n * costs one round trip and keeps the console usable.\n */\n function closeSocket(ws: WebSocket, code?: number, reason?: string): void {\n if (ws.readyState === WebSocket.CONNECTING) {\n ws.onopen = () => ws.close(code, reason);\n ws.onmessage = null;\n ws.onerror = null;\n ws.onclose = null;\n return;\n }\n ws.close(code, reason);\n }\n\n function reconnect(): void {\n if (retryTimer) {\n clearTimeout(retryTimer);\n retryTimer = null;\n }\n retries = 0;\n closed = false;\n connect();\n }\n\n connect();\n\n return {\n send,\n close,\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