Procházet zdrojové kódy

Remove the Javascript oref implementation

This commit removes the Javascript algorithm from the code
base. Changes include removing the JS resources, removing the setting
`useJavascriptOref`, and removing all swift code that uses or supports
running Javascript.

For now, we left the JSON marshalling in place but we will remove this
in subsequent commits / PRs.
Sam King před 1 dnem
rodič
revize
5cb6ed8b40
29 změnil soubory, kde provedl 69 přidání a 939 odebrání
  1. 0 12
      Trio.xcodeproj/project.pbxproj
  2. 0 2
      Trio/Resources/javascript/bundle/autosens.js
  3. 0 1
      Trio/Resources/javascript/bundle/autotune-core.js
  4. 0 2
      Trio/Resources/javascript/bundle/autotune-prep.js
  5. 0 1
      Trio/Resources/javascript/bundle/basal-set-temp.js
  6. 0 1
      Trio/Resources/javascript/bundle/determine-basal.js
  7. 0 1
      Trio/Resources/javascript/bundle/glucose-get-last.js
  8. 0 2
      Trio/Resources/javascript/bundle/iob.js
  9. 0 2
      Trio/Resources/javascript/bundle/meal.js
  10. 0 2
      Trio/Resources/javascript/bundle/profile.js
  11. 0 5
      Trio/Resources/javascript/middleware/determine_basal.js
  12. 0 26
      Trio/Resources/javascript/prepare/autosens.js
  13. 0 17
      Trio/Resources/javascript/prepare/autotune-core.js
  14. 0 47
      Trio/Resources/javascript/prepare/autotune-prep.js
  15. 0 49
      Trio/Resources/javascript/prepare/determine-basal.js
  16. 0 15
      Trio/Resources/javascript/prepare/iob.js
  17. 0 6
      Trio/Resources/javascript/prepare/log.js
  18. 0 35
      Trio/Resources/javascript/prepare/meal.js
  19. 0 107
      Trio/Resources/javascript/prepare/profile.js
  20. 3 6
      Trio/Sources/APS/APSManager.swift
  21. 0 27
      Trio/Sources/APS/OpenAPS/Constants.swift
  22. 0 146
      Trio/Sources/APS/OpenAPS/JavaScriptWorker.swift
  23. 63 337
      Trio/Sources/APS/OpenAPS/OpenAPS.swift
  24. 0 26
      Trio/Sources/APS/OpenAPS/Script.swift
  25. 3 18
      Trio/Sources/Localizations/Main/Localizable.xcstrings
  26. 0 5
      Trio/Sources/Models/TrioSettings.swift
  27. 0 3
      Trio/Sources/Modules/AlgorithmAdvancedSettings/AlgorithmAdvancedSettingsStateModel.swift
  28. 0 33
      Trio/Sources/Modules/AlgorithmAdvancedSettings/View/AlgorithmAdvancedSettingsRootView.swift
  29. 0 5
      Trio/Sources/Modules/Home/View/Header/LoopStatusView.swift

+ 0 - 12
Trio.xcodeproj/project.pbxproj

@@ -101,8 +101,6 @@
 		383420D625FFE38C002D46C1 /* LoopView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 383420D525FFE38C002D46C1 /* LoopView.swift */; };
 		383420D925FFEB3F002D46C1 /* Popup.swift in Sources */ = {isa = PBXBuildFile; fileRef = 383420D825FFEB3F002D46C1 /* Popup.swift */; };
 		383948D625CD4D8900E91849 /* FileStorage.swift in Sources */ = {isa = PBXBuildFile; fileRef = 383948D525CD4D8900E91849 /* FileStorage.swift */; };
-		384E803425C385E60086DB71 /* JavaScriptWorker.swift in Sources */ = {isa = PBXBuildFile; fileRef = 384E803325C385E60086DB71 /* JavaScriptWorker.swift */; };
-		384E803825C388640086DB71 /* Script.swift in Sources */ = {isa = PBXBuildFile; fileRef = 384E803725C388640086DB71 /* Script.swift */; };
 		38569347270B5DFB0002C50D /* CGMType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 38569344270B5DFA0002C50D /* CGMType.swift */; };
 		38569348270B5DFB0002C50D /* GlucoseSource.swift in Sources */ = {isa = PBXBuildFile; fileRef = 38569345270B5DFA0002C50D /* GlucoseSource.swift */; };
 		38569349270B5DFB0002C50D /* AppGroupSource.swift in Sources */ = {isa = PBXBuildFile; fileRef = 38569346270B5DFB0002C50D /* AppGroupSource.swift */; };
@@ -118,7 +116,6 @@
 		38887CCE25F5725200944304 /* IOBEntry.swift in Sources */ = {isa = PBXBuildFile; fileRef = 38887CCD25F5725200944304 /* IOBEntry.swift */; };
 		388E595C25AD948C0019842D /* TrioApp.swift in Sources */ = {isa = PBXBuildFile; fileRef = 388E595B25AD948C0019842D /* TrioApp.swift */; };
 		388E596C25AD95110019842D /* OpenAPS.swift in Sources */ = {isa = PBXBuildFile; fileRef = 388E596B25AD95110019842D /* OpenAPS.swift */; };
-		388E596F25AD96040019842D /* javascript in Resources */ = {isa = PBXBuildFile; fileRef = 388E596E25AD96040019842D /* javascript */; };
 		388E597225AD9CF10019842D /* json in Resources */ = {isa = PBXBuildFile; fileRef = 388E597125AD9CF10019842D /* json */; };
 		388E5A5C25B6F0770019842D /* JSON.swift in Sources */ = {isa = PBXBuildFile; fileRef = 388E5A5B25B6F0770019842D /* JSON.swift */; };
 		388E5A6025B6F2310019842D /* Autosens.swift in Sources */ = {isa = PBXBuildFile; fileRef = 388E5A5F25B6F2310019842D /* Autosens.swift */; };
@@ -1126,8 +1123,6 @@
 		383420D525FFE38C002D46C1 /* LoopView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LoopView.swift; sourceTree = "<group>"; };
 		383420D825FFEB3F002D46C1 /* Popup.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Popup.swift; sourceTree = "<group>"; };
 		383948D525CD4D8900E91849 /* FileStorage.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FileStorage.swift; sourceTree = "<group>"; };
-		384E803325C385E60086DB71 /* JavaScriptWorker.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = JavaScriptWorker.swift; sourceTree = "<group>"; };
-		384E803725C388640086DB71 /* Script.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Script.swift; sourceTree = "<group>"; };
 		38569344270B5DFA0002C50D /* CGMType.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CGMType.swift; sourceTree = "<group>"; };
 		38569345270B5DFA0002C50D /* GlucoseSource.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = GlucoseSource.swift; sourceTree = "<group>"; };
 		38569346270B5DFB0002C50D /* AppGroupSource.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppGroupSource.swift; sourceTree = "<group>"; };
@@ -1145,7 +1140,6 @@
 		388E595B25AD948C0019842D /* TrioApp.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TrioApp.swift; sourceTree = "<group>"; };
 		388E596425AD948E0019842D /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
 		388E596B25AD95110019842D /* OpenAPS.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = OpenAPS.swift; sourceTree = "<group>"; };
-		388E596E25AD96040019842D /* javascript */ = {isa = PBXFileReference; lastKnownFileType = folder; path = javascript; sourceTree = "<group>"; };
 		388E597125AD9CF10019842D /* json */ = {isa = PBXFileReference; lastKnownFileType = folder; path = json; sourceTree = "<group>"; };
 		388E5A5B25B6F0770019842D /* JSON.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = JSON.swift; sourceTree = "<group>"; };
 		388E5A5F25B6F2310019842D /* Autosens.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Autosens.swift; sourceTree = "<group>"; };
@@ -2494,7 +2488,6 @@
 			isa = PBXGroup;
 			children = (
 				388E597125AD9CF10019842D /* json */,
-				388E596E25AD96040019842D /* javascript */,
 				BD1179332F4E22C100F90001 /* Sounds */,
 				3811DEC725C9DA7300A708ED /* Trio.entitlements */,
 				388E596425AD948E0019842D /* Info.plist */,
@@ -2720,8 +2713,6 @@
 			isa = PBXGroup;
 			children = (
 				388E596B25AD95110019842D /* OpenAPS.swift */,
-				384E803325C385E60086DB71 /* JavaScriptWorker.swift */,
-				384E803725C388640086DB71 /* Script.swift */,
 				3821ED4B25DD18BA00BC42AD /* Constants.swift */,
 			);
 			path = OpenAPS;
@@ -4775,7 +4766,6 @@
 				38DF178E27733E6800B3528F /* Assets.xcassets in Resources */,
 				19DA48E829CD339B00EEA1E7 /* Assets.xcassets in Resources */,
 				8A91342A2D63D9A1007F8874 /* Localizable.xcstrings in Resources */,
-				388E596F25AD96040019842D /* javascript in Resources */,
 				BD1179342F4E22C100F90001 /* Sounds in Resources */,
 			);
 			runOnlyForDeploymentPostprocessing = 0;
@@ -4975,7 +4965,6 @@
 				388E596C25AD95110019842D /* OpenAPS.swift in Sources */,
 				E00EEC0527368630002FF094 /* StorageAssembly.swift in Sources */,
 				DD1745552C55CA6C00211FAC /* UnitsLimitsSettingsRootView.swift in Sources */,
-				384E803825C388640086DB71 /* Script.swift in Sources */,
 				CE94597E29E9E1EE0047C9C6 /* GarminManager.swift in Sources */,
 				3883583425EEB38000E024B2 /* PumpSettings.swift in Sources */,
 				38DAB280260CBB7F00F74C1A /* PumpView.swift in Sources */,
@@ -5106,7 +5095,6 @@
 				38569347270B5DFB0002C50D /* CGMType.swift in Sources */,
 				DD485F182E466F1800CE8CBF /* SecureMessenger.swift in Sources */,
 				3821ED4C25DD18BA00BC42AD /* Constants.swift in Sources */,
-				384E803425C385E60086DB71 /* JavaScriptWorker.swift in Sources */,
 				CE1F6DE92BAF37C90064EB8D /* TidepoolConfigView.swift in Sources */,
 				3811DE5D25C9D4D500A708ED /* Publisher.swift in Sources */,
 				E00EEC0727368630002FF094 /* APSAssembly.swift in Sources */,

Rozdílová data souboru nebyla zobrazena, protože soubor je příliš velký
+ 0 - 2
Trio/Resources/javascript/bundle/autosens.js


Rozdílová data souboru nebyla zobrazena, protože soubor je příliš velký
+ 0 - 1
Trio/Resources/javascript/bundle/autotune-core.js


Rozdílová data souboru nebyla zobrazena, protože soubor je příliš velký
+ 0 - 2
Trio/Resources/javascript/bundle/autotune-prep.js


Rozdílová data souboru nebyla zobrazena, protože soubor je příliš velký
+ 0 - 1
Trio/Resources/javascript/bundle/basal-set-temp.js


Rozdílová data souboru nebyla zobrazena, protože soubor je příliš velký
+ 0 - 1
Trio/Resources/javascript/bundle/determine-basal.js


Rozdílová data souboru nebyla zobrazena, protože soubor je příliš velký
+ 0 - 1
Trio/Resources/javascript/bundle/glucose-get-last.js


Rozdílová data souboru nebyla zobrazena, protože soubor je příliš velký
+ 0 - 2
Trio/Resources/javascript/bundle/iob.js


Rozdílová data souboru nebyla zobrazena, protože soubor je příliš velký
+ 0 - 2
Trio/Resources/javascript/bundle/meal.js


Rozdílová data souboru nebyla zobrazena, protože soubor je příliš velký
+ 0 - 2
Trio/Resources/javascript/bundle/profile.js


+ 0 - 5
Trio/Resources/javascript/middleware/determine_basal.js

@@ -1,5 +0,0 @@
-function middleware(iob, currenttemp, glucose, profile, autosens, meal, reservoir, clock, pumphistory, preferences, basalprofile) {
-    // modify anything
-    // return any reason what has changed.
-    return "Nothing changed";
-}

+ 0 - 26
Trio/Resources/javascript/prepare/autosens.js

@@ -1,26 +0,0 @@
-// для settings/autosens.json параметры: monitor/glucose.json monitor/pumphistory-24h-zoned.json settings/basal_profile.json settings/profile.json monitor/carbhistory.json settings/temptargets.json
-
-function generate(glucose_data, pumphistory_data, basalprofile, profile_data, carb_data = {}, temptarget_data = {}) {
-    if (glucose_data.length < 72) {
-        return { "ratio": 1, "error": "not enough glucose data to calculate autosens" };
-    };
-    
-    var iob_inputs = {
-        history: pumphistory_data,
-        profile: profile_data
-    };
-
-    var detection_inputs = {
-        iob_inputs: iob_inputs,
-        carbs: carb_data,
-        glucose_data: glucose_data,
-        basalprofile: basalprofile,
-        temptargets: temptarget_data
-    };
-    detection_inputs.deviations = 96;
-    var ratio8h = trio_autosens(detection_inputs);
-    detection_inputs.deviations = 288;
-    var ratio24h = trio_autosens(detection_inputs);
-    var lowestRatio = ratio8h.ratio < ratio24h.ratio ? ratio8h : ratio24h;
-    return lowestRatio;
-}

+ 0 - 17
Trio/Resources/javascript/prepare/autotune-core.js

@@ -1,17 +0,0 @@
-function generate(prepped_glucose_data,previous_autotune_data,pumpprofile_data) {
-  if (!pumpprofile_data.useCustomPeakTime) {
-      previous_autotune_data.dia = pumpprofile_data.dia;
-      previous_autotune_data.insulinPeakTime = pumpprofile_data.insulinPeakTime;
-    };
-
-    // Always keep the curve value up to date with what's in the user preferences
-    previous_autotune_data.curve = pumpprofile_data.curve;
-
-    inputs = {
-        preppedGlucose: prepped_glucose_data
-      , previousAutotune: previous_autotune_data
-      , pumpProfile: pumpprofile_data
-    };
-
-    return trio_autotuneCore(inputs);
-}

+ 0 - 47
Trio/Resources/javascript/prepare/autotune-prep.js

@@ -1,47 +0,0 @@
-function generate(pumphistory_data, profile_data, glucose_data, pumpprofile_data, carb_data = {} , categorize_uam_as_basal = false, tune_insulin_curve = false) {
-    if (typeof(profile_data.carb_ratio) === 'undefined' || profile_data.carb_ratio < 0.1) {
-        if (typeof(pumpprofile_data.carb_ratio) === 'undefined' || pumpprofile_data.carb_ratio < 0.1) {
-            console.log('{ "carbs": 0, "mealCOB": 0, "reason": "carb_ratios ' + profile_data.carb_ratio + ' and ' + pumpprofile_data.carb_ratio + ' out of bounds" }');
-            return console.error("Error: carb_ratios " + profile_data.carb_ratio + ' and ' + pumpprofile_data.carb_ratio + " out of bounds");
-        } else {
-            profile_data.carb_ratio = pumpprofile_data.carb_ratio;
-        }
-    }
-
-    // get insulin curve from pump profile that is maintained
-    profile_data.curve = pumpprofile_data.curve;
-
-    // Pump profile has an up to date copy of useCustomPeakTime from preferences
-    // If the preferences file has useCustomPeakTime use the previous autotune dia and PeakTime.
-    // Otherwise, use data from pump profile.
-    if (!pumpprofile_data.useCustomPeakTime) {
-      profile_data.dia = pumpprofile_data.dia;
-      profile_data.insulinPeakTime = pumpprofile_data.insulinPeakTime;
-    }
-
-    // Always keep the curve value up to date with what's in the user preferences
-    profile_data.curve = pumpprofile_data.curve;
-
-    // Have to sort history - NS sort doesn't account for different zulu and local timestamps
-    pumphistory_data.sort( function( firstValue, secondValue ) {
-        try {
-            var a = new Date(firstValue.timestamp);
-            var b = new Date(secondValue.timestamp);
-            return b.getTime() - a.getTime();
-        } catch(e) {
-            return 0;
-        }
-    } );
-
-    inputs = {
-      history: pumphistory_data
-    , profile: profile_data
-    , pumpprofile: pumpprofile_data
-    , carbs: carb_data
-    , glucose: glucose_data
-    , categorize_uam_as_basal: categorize_uam_as_basal
-    , tune_insulin_curve: tune_insulin_curve
-    };
-
-    return trio_autotunePrep(inputs);
-}

+ 0 - 49
Trio/Resources/javascript/prepare/determine-basal.js

@@ -1,49 +0,0 @@
-//для enact/smb-suggested.json параметры: monitor/iob.json monitor/temp_basal.json monitor/glucose.json settings/profile.json settings/autosens.json --meal monitor/meal.json --microbolus --reservoir monitor/reservoir.json
-
-function generate(iob, currenttemp, glucose, profile, autosens = null, meal = null, microbolusAllowed = false, reservoir = null, clock = new Date(), pump_history, preferences, basalProfile, trio_custom_oref_variables) {
-
-    var clock = new Date();
-    
-    var middleware_was_used = "";
-    try {
-        var middlewareReason = middleware(iob, currenttemp, glucose, profile, autosens, meal, reservoir, clock, pump_history, preferences, basalProfile, trio_custom_oref_variables);
-        middleware_was_used = (middlewareReason || "Nothing changed");
-        console.log("Middleware reason: " + middleware_was_used);
-    } catch (error) {
-        console.log("Invalid middleware: " + error);
-    };
-
-    var glucose_status = trio_glucoseGetLast(glucose);
-    var autosens_data = null;
-
-    if (autosens) {
-        autosens_data = autosens;
-    }
-    
-    var reservoir_data = null;
-    if (reservoir) {
-        reservoir_data = reservoir;
-    }
-
-    var meal_data = {};
-    if (meal) {
-        meal_data = meal;
-    }
-    
-    var pumphistory = {};
-    if (pump_history) {
-        pumphistory = pump_history;
-    }
-    
-    var basalprofile = {};
-    if (basalProfile) {
-        basalprofile = basalProfile;
-    }
-    
-    var trio_custom_oref_variables_temp = {};
-    if (trio_custom_oref_variables) {
-        trio_custom_oref_variables_temp = trio_custom_oref_variables;
-    }
-    
-    return trio_determineBasal(glucose_status, currenttemp, iob, profile, autosens_data, meal_data, trio_basalSetTemp, microbolusAllowed, reservoir_data, clock, pumphistory, preferences, basalprofile, trio_custom_oref_variables_temp, middleware_was_used);
-}

+ 0 - 15
Trio/Resources/javascript/prepare/iob.js

@@ -1,15 +0,0 @@
-//для monitor/iob.json параметры: monitor/pumphistory-24h-zoned.json settings/profile.json monitor/clock-zoned.json settings/autosens.json
-
-function generate(pumphistory_data, profile_data, clock_data, autosens_data = null) {
-    var inputs = {
-        history: pumphistory_data
-        , history24: null
-        , profile: profile_data
-        , clock: clock_data
-    };
-
-      if (autosens_data) {
-        inputs.autosens = autosens_data;
-      }
-      return trio_iob(inputs);
-}

+ 0 - 6
Trio/Resources/javascript/prepare/log.js

@@ -1,6 +0,0 @@
-var console = {
-    log: function(...args) { _consoleLog(args); },
-    error: function(...args) { _consoleLog(args); }
-};
-var printLog = function(...args) { console.log(args); };
-var process = { stderr: { write: printLog } };

+ 0 - 35
Trio/Resources/javascript/prepare/meal.js

@@ -1,35 +0,0 @@
-//для monitor/meal.json параметры: monitor/pumphistory-24h-zoned.json settings/profile.json monitor/clock-zoned.json monitor/glucose.json settings/basal_profile.json monitor/carbhistory.json
-
-function generate(pumphistory_data, profile_data, clock_data, glucose_data, basalprofile_data, carbhistory = false) {
-    if (typeof(profile_data.carb_ratio) === 'undefined' || profile_data.carb_ratio < 0.1) {
-        return {"error":"Error: carb_ratio " + profile_data.carb_ratio + " out of bounds"};
-    }
-
-    var carb_data = { };
-    if (carbhistory) {
-        carb_data = carbhistory;
-    }
-
-    if (typeof basalprofile_data[0] === 'undefined') {
-        return { "error":"Error: bad basalprofile_data: " + JSON.stringify(basalprofile_data) };
-    }
-
-    var inputs = {
-      history: pumphistory_data
-    , profile: profile_data
-    , basalprofile: basalprofile_data
-    , clock: clock_data
-    , carbs: carb_data
-    , glucose: glucose_data
-    };
-
-    var recentCarbs = trio_meal(inputs);
-
-    if (glucose_data.length < 4) {
-        console.error("Not enough glucose data to calculate carb absorption; found:", glucose_data.length);
-        recentCarbs.mealCOB = 0;
-        recentCarbs.reason = "not enough glucose data to calculate carb absorption";
-    }
-
-    return recentCarbs;
-}

+ 0 - 107
Trio/Resources/javascript/prepare/profile.js

@@ -1,107 +0,0 @@
-//для pumpprofile.json параметры: settings/settings.json settings/bg_targets.json settings/insulin_sensitivities.json settings/basal_profile.json preferences.json settings/carb_ratios.json settings/temptargets.json settings/model.json
-//для profile.json параметры: settings/settings.json settings/bg_targets.json settings/insulin_sensitivities.json settings/basal_profile.json preferences.json settings/carb_ratios.json settings/temptargets.json settings/model.json settings/autotune.json
-
-function generate(pumpsettings_data, bgtargets_data, isf_data, basalprofile_data, preferences_input = false, carbratio_input = false, temptargets_input = false, model_input = false, autotune_input = false, trio_data) {
-    if (bgtargets_data.units !== 'mg/dL') {
-        if (bgtargets_data.units === 'mmol/L') {
-            for (var i = 0, len = bgtargets_data.targets.length; i < len; i++) {
-                bgtargets_data.targets[i].high = bgtargets_data.targets[i].high * 18;
-                bgtargets_data.targets[i].low = bgtargets_data.targets[i].low * 18;
-            }
-            bgtargets_data.units = 'mg/dL';
-        } else {
-            return { "error" : 'BG Target data is expected to be expressed in mg/dL or mmol/L. Found '+ bgtargets_data.units };
-        }
-    }
-    
-    if (isf_data.units !== 'mg/dL') {
-        if (isf_data.units === 'mmol/L') {
-            for (var i = 0, len = isf_data.sensitivities.length; i < len; i++) {
-                isf_data.sensitivities[i].sensitivity = isf_data.sensitivities[i].sensitivity * 18;
-            }
-            isf_data.units = 'mg/dL';
-        } else {
-            return { "error" : 'ISF is expected to be expressed in mg/dL or mmol/L. Found '+ isf_data.units };
-        }
-    }
-
-    var autotune_data = { };
-    if (autotune_input) {
-        autotune_data = autotune_input;
-    }
-
-    var temptargets_data = { };
-    if (temptargets_input) {
-        temptargets_data = temptargets_input;
-    }
-    
-    var trioData = { };
-    if (trio_data) {
-        trioData = trio_data;
-    }
-
-    var model_data = { };
-    if (model_input) {
-        model_data = model_input.replace(/"/gi, '');
-    }
-
-    var carbratio_data = { };
-    if (carbratio_input) {
-        var errors = [ ];
-        if (!(carbratio_input.schedule && carbratio_input.schedule[0].start && carbratio_input.schedule[0].ratio)) {
-          errors.push("Carb ratio data should have an array called schedule with a start and ratio fields.");
-        }
-        if (carbratio_input.units !== 'grams' && carbratio_input.units !== 'exchanges')  {
-          errors.push("Carb ratio should have units field set to 'grams' or 'exchanges'.");
-        }
-        if (errors.length) {
-          return { "error" : errors.join(' ') };
-        }
-        carbratio_data = carbratio_input;
-    }
-
-    var preferences = { };
-    if (preferences_input) {
-        preferences = preferences_input;
-        if (preferences.curve === "rapid-acting") {
-            if (preferences.useCustomPeakTime) {
-                preferences.insulinPeakTime =
-                Math.max(50, Math.min(preferences.insulinPeakTime, 120));
-            } else { preferences.insulinPeakTime = 75; }
-        } 
-        else if (preferences.curve === "ultra-rapid") {
-            if (preferences.useCustomPeakTime) {
-                preferences.insulinPeakTime =
-                Math.max(35, Math.min(preferences.insulinPeakTime, 100));
-            } else { preferences.insulinPeakTime = 55; }
-        }
-    }
-
-    var inputs = { };
-    //add all preferences to the inputs
-    for (var pref in preferences) {
-      if (preferences.hasOwnProperty(pref)) {
-        inputs[pref] = preferences[pref];
-      }
-    }
-
-    inputs.max_iob = inputs.max_iob || 0;
-    //set these after to make sure nothing happens if they are also set in preferences
-    inputs.settings = pumpsettings_data;
-    inputs.targets = bgtargets_data;
-    inputs.basals = basalprofile_data;
-    inputs.isf = isf_data;
-    inputs.carbratio = carbratio_data;
-    inputs.temptargets = temptargets_data;
-    inputs.model = model_data;
-    inputs.autotune = autotune_data;
-
-    if (autotune_data) {
-        if (autotune_data.basalprofile) { inputs.basals = autotune_data.basalprofile; }
-        if (!trioData.onlyAutotuneBasals) {
-            if (autotune_data.isfProfile) { inputs.isf = autotune_data.isfProfile; }
-            if (autotune_data.carb_ratio) { inputs.carbratio.schedule[0].ratio = autotune_data.carb_ratio; }
-        }
-    }
-    return trio_profile(inputs);
-}

+ 3 - 6
Trio/Sources/APS/APSManager.swift

@@ -184,7 +184,7 @@ final class BaseAPSManager: APSManager, Injectable {
             if wasParsed {
                 Task {
                     do {
-                        try await openAPS.createProfiles(useJavascriptOref: settings.useJavascriptOref)
+                        try await openAPS.createProfiles()
                     } catch {
                         debug(
                             .apsManager,
@@ -433,8 +433,7 @@ final class BaseAPSManager: APSManager, Injectable {
               (autosense.timestamp ?? .distantPast).addingTimeInterval(30.minutes.timeInterval) > Date()
         else {
             let result = try await openAPS.autosense(
-                shouldSmoothGlucose: settingsManager.settings.smoothGlucose,
-                useJavascriptOref: settings.useJavascriptOref
+                shouldSmoothGlucose: settingsManager.settings.smoothGlucose
             )
             return result != nil
         }
@@ -501,14 +500,13 @@ final class BaseAPSManager: APSManager, Injectable {
             let now = Date()
 
             // put profile creation up front since autosens needs it
-            try await openAPS.createProfiles(useJavascriptOref: settings.useJavascriptOref)
+            try await openAPS.createProfiles()
             let currentTemp = try await fetchCurrentTempBasal(date: now)
             _ = try await autosense()
 
             let determination = try await openAPS.determineBasal(
                 currentTemp: currentTemp,
                 shouldSmoothGlucose: settingsManager.settings.smoothGlucose,
-                useJavascriptOref: settings.useJavascriptOref,
                 clock: now
             )
             iobFileDidUpdate.send(())
@@ -555,7 +553,6 @@ final class BaseAPSManager: APSManager, Injectable {
             return try await openAPS.determineBasal(
                 currentTemp: temp,
                 shouldSmoothGlucose: settingsManager.settings.smoothGlucose,
-                useJavascriptOref: settings.useJavascriptOref,
                 clock: Date(),
                 simulatedCarbsAmount: simulatedCarbsAmount,
                 simulatedBolusAmount: simulatedBolusAmount,

+ 0 - 27
Trio/Sources/APS/OpenAPS/Constants.swift

@@ -1,31 +1,4 @@
 extension OpenAPS {
-    enum Bundle {
-        static let iob = "bundle/iob.js"
-        static let meal = "bundle/meal.js"
-        static let autotunePrep = "bundle/autotune-prep.js"
-        static let autotuneCore = "bundle/autotune-core.js"
-        static let getLastGlucose = "bundle/glucose-get-last.js"
-        static let basalSetTemp = "bundle/basal-set-temp.js"
-        static let determineBasal = "bundle/determine-basal.js"
-        static let autosens = "bundle/autosens.js"
-        static let profile = "bundle/profile.js"
-    }
-
-    enum Prepare {
-        static let iob = "prepare/iob.js"
-        static let meal = "prepare/meal.js"
-        static let autotunePrep = "prepare/autotune-prep.js"
-        static let autotuneCore = "prepare/autotune-core.js"
-        static let determineBasal = "prepare/determine-basal.js"
-        static let autosens = "prepare/autosens.js"
-        static let profile = "prepare/profile.js"
-        static let log = "prepare/log.js"
-    }
-
-    enum Middleware {
-        static let determineBasal = "middleware/determine_basal.js"
-    }
-
     enum Settings {
         static let preferences = "preferences.json"
         static let autotune = "settings/autotune.json"

+ 0 - 146
Trio/Sources/APS/OpenAPS/JavaScriptWorker.swift

@@ -1,146 +0,0 @@
-import Foundation
-import JavaScriptCore
-
-private let contextLock = NSRecursiveLock()
-
-extension String {
-    var lowercasingFirst: String { prefix(1).lowercased() + dropFirst() }
-    var uppercasingFirst: String { prefix(1).uppercased() + dropFirst() }
-    var camelCased: String {
-        guard !isEmpty else { return "" }
-        let parts = components(separatedBy: .alphanumerics.inverted)
-        let first = parts.first!.lowercasingFirst
-        let rest = parts.dropFirst().map(\.uppercasingFirst)
-        return ([first] + rest).joined()
-    }
-
-    var pascalCased: String {
-        guard !isEmpty else { return "" }
-        let parts = components(separatedBy: .alphanumerics.inverted)
-        let first = parts.first!.uppercasingFirst
-        let rest = parts.dropFirst().map(\.uppercasingFirst)
-        return ([first] + rest).joined()
-    }
-}
-
-final class JavaScriptWorker {
-    private let processQueue = DispatchQueue(label: "DispatchQueue.JavaScriptWorker", attributes: .concurrent)
-    private let virtualMachine: JSVirtualMachine
-    private var contextPool: [JSContext] = []
-    private let contextPoolLock = NSLock()
-
-    init(poolSize: Int = 5) {
-        virtualMachine = JSVirtualMachine()!
-        // Pre-create a pool of JSContext instances
-        for _ in 0 ..< poolSize {
-            contextPool.append(createContext())
-        }
-    }
-
-    private func createContext() -> JSContext {
-        let context = JSContext(virtualMachine: virtualMachine)!
-        context.exceptionHandler = { _, exception in
-            if let error = exception?.toString() {
-                warning(.openAPS, "JavaScript Error: \(error)")
-            }
-        }
-        let consoleLog: @convention(block) (String) -> Void = { [weak context] message in
-            guard let context = context else { return }
-            let trimmedMessage = message.trimmingCharacters(in: .whitespacesAndNewlines)
-            if !trimmedMessage.isEmpty {
-                let fileName = context.objectForKeyedSubscript("scriptName").toString() ?? "Unknown"
-                let threadSafeLog = "\(trimmedMessage)"
-                self.processQueue.async(flags: .barrier) {
-                    self.outputLogs(for: fileName, message: threadSafeLog)
-                }
-            }
-        }
-        context.setObject(consoleLog, forKeyedSubscript: "_consoleLog" as NSString)
-        return context
-    }
-
-    private func getContext() -> JSContext {
-        contextPoolLock.lock()
-        let context = contextPool.popLast() ?? createContext()
-        contextPoolLock.unlock()
-        return context
-    }
-
-    private func returnContext(_ context: JSContext) {
-        contextPoolLock.lock()
-        contextPool.append(context)
-        contextPoolLock.unlock()
-    }
-
-    private func outputLogs(for fileName: String, message: String) {
-        let logs = message.trimmingCharacters(in: .whitespacesAndNewlines)
-
-        if logs.isEmpty { return }
-
-        if fileName == "autosens.js" {
-            let sanitizedLogs = logs.split(separator: "\n").map { logLine in
-                logLine.replacingOccurrences(
-                    of: "^[-+=x!]|u\\(|\\)|\\d{1,2}h$",
-                    with: "",
-                    options: .regularExpression
-                )
-            }.joined(separator: "\n")
-
-            sanitizedLogs.split(separator: "\n").forEach { logLine in
-                if !logLine.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
-                    debug(.openAPS, "\(fileName): \(logLine)")
-                }
-            }
-        } else {
-            logs.split(separator: "\n").forEach { logLine in
-                if !logLine.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
-                    debug(.openAPS, "\(fileName): \(logLine)")
-                }
-            }
-        }
-    }
-
-    @discardableResult func evaluate(script: Script) -> JSValue! {
-        let context = getContext()
-        defer { returnContext(context) }
-        let fileName = URL(fileURLWithPath: script.name).lastPathComponent
-        context.setObject(fileName, forKeyedSubscript: "scriptName" as NSString)
-        let result = context.evaluateScript(script.body)
-        return result
-    }
-
-    private func evaluate(string: String) -> JSValue! {
-        let context = getContext()
-        defer { returnContext(context) }
-        return context.evaluateScript(string)
-    }
-
-    private func json(for string: String) -> RawJSON {
-        evaluate(string: "JSON.stringify(\(string), null, 4);")!.toString()!
-    }
-
-    func call(function: String, with arguments: [JSON]) -> RawJSON {
-        let joined = arguments.map(\.rawJSON).joined(separator: ",")
-        return json(for: "\(function)(\(joined))")
-    }
-
-    func inCommonContext<Value>(execute: (JavaScriptWorker) -> Value) -> Value {
-        let context = getContext()
-        defer {
-            returnContext(context)
-        }
-        return execute(self)
-    }
-
-    func evaluateBatch(scripts: [Script]) {
-        let context = getContext()
-        defer {
-            returnContext(context)
-        }
-        scripts.forEach { script in
-            let fileName = URL(fileURLWithPath: script.name).lastPathComponent
-            context.setObject(fileName, forKeyedSubscript: "scriptName" as NSString)
-            context.evaluateScript(script.body)
-        }
-    }
-}

+ 63 - 337
Trio/Sources/APS/OpenAPS/OpenAPS.swift

@@ -1,10 +1,8 @@
 import Combine
 import CoreData
 import Foundation
-import JavaScriptCore
 
 final class OpenAPS {
-    private let jsWorker = JavaScriptWorker()
     private let processQueue = DispatchQueue(label: "OpenAPS.processQueue", qos: .utility)
 
     private let storage: FileStorage
@@ -385,7 +383,6 @@ final class OpenAPS {
     func determineBasal(
         currentTemp: TempBasal,
         shouldSmoothGlucose: Bool,
-        useJavascriptOref: Bool,
         clock: Date = Date(),
         simulatedCarbsAmount: Decimal? = nil,
         simulatedBolusAmount: Decimal? = nil,
@@ -441,23 +438,21 @@ final class OpenAPS {
         )
 
         // Meal calculation
-        let meal = try await self.meal(
+        let meal = try self.meal(
             pumphistory: pumpHistoryJSON,
             profile: profile,
             basalProfile: basalProfile,
             clock: clock,
             carbs: carbsAsJSON,
-            glucose: glucoseAsJSON,
-            useJavascriptOref: useJavascriptOref
+            glucose: glucoseAsJSON
         )
 
         // IOB calculation
-        let iob = try await self.iob(
+        let iob = try self.iob(
             pumphistory: pumpHistoryJSON,
             profile: profile,
             clock: clock,
-            autosens: autosens.isEmpty ? .null : autosens,
-            useJavascriptOref: useJavascriptOref
+            autosens: autosens.isEmpty ? .null : autosens
         )
 
         // TODO: refactor this to core data
@@ -472,7 +467,7 @@ final class OpenAPS {
         }
 
         // Determine basal
-        let orefDetermination = try await determineBasal(
+        let orefDetermination = try determineBasal(
             glucose: glucoseAsJSON,
             currentTemp: tempBasal,
             iob: iob,
@@ -484,8 +479,7 @@ final class OpenAPS {
             pumpHistory: pumpHistoryJSON,
             preferences: preferences,
             basalProfile: basalProfile,
-            trioCustomOrefVariables: trioCustomOrefVariables,
-            useJavascriptOref: useJavascriptOref
+            trioCustomOrefVariables: trioCustomOrefVariables
         )
 
         debug(.openAPS, "\(simulation ? "[SIMULATION]" : "") OREF DETERMINATION: \(orefDetermination)")
@@ -578,7 +572,7 @@ final class OpenAPS {
         }
     }
 
-    func autosense(shouldSmoothGlucose: Bool, useJavascriptOref: Bool) async throws -> Autosens? {
+    func autosense(shouldSmoothGlucose: Bool) async throws -> Autosens? {
         debug(.openAPS, "Start autosens")
 
         // Perform asynchronous calls in parallel
@@ -600,14 +594,13 @@ final class OpenAPS {
         )
 
         // Autosense
-        let autosenseResult = try await autosense(
+        let autosenseResult = try autosense(
             glucose: glucoseAsJSON,
             pumpHistory: pumpHistoryJSON,
             basalprofile: basalProfile,
             profile: profile,
             carbs: carbsAsJSON,
-            temptargets: tempTargets,
-            useJavascriptOref: useJavascriptOref
+            temptargets: tempTargets
         )
 
         debug(.openAPS, "AUTOSENS: \(autosenseResult)")
@@ -621,7 +614,7 @@ final class OpenAPS {
         }
     }
 
-    func createProfiles(useJavascriptOref: Bool) async throws {
+    func createProfiles() async throws {
         debug(.openAPS, "Start creating pump profile and user profile")
 
         // Load required settings and profiles asynchronously
@@ -687,7 +680,7 @@ final class OpenAPS {
 
         let clock = Date()
         do {
-            let pumpProfile = try await makeProfile(
+            let pumpProfile = try makeProfile(
                 preferences: adjustedPreferences,
                 pumpSettings: pumpSettings,
                 bgTargets: bgTargets,
@@ -698,11 +691,10 @@ final class OpenAPS {
                 model: model,
                 autotune: RawJSON.null,
                 trioSettings: trioSettings,
-                useJavascriptOref: useJavascriptOref,
                 clock: clock
             )
 
-            let profile = try await makeProfile(
+            let profile = try makeProfile(
                 preferences: adjustedPreferences,
                 pumpSettings: pumpSettings,
                 bgTargets: bgTargets,
@@ -713,7 +705,6 @@ final class OpenAPS {
                 model: model,
                 autotune: RawJSON.null,
                 trioSettings: trioSettings,
-                useJavascriptOref: useJavascriptOref,
                 clock: clock
             )
 
@@ -733,47 +724,17 @@ final class OpenAPS {
         pumphistory: JSON,
         profile: JSON,
         clock: JSON,
-        autosens: JSON,
-        useJavascriptOref: Bool
-    ) async throws -> RawJSON {
+        autosens: JSON
+    ) throws -> RawJSON {
         // FIXME: For now we'll just remove duplicate suspends here (ISSUE-399)
         var pumphistory = pumphistory
         if let pumpHistoryArray = try? JSONBridge.pumpHistory(from: pumphistory) {
             pumphistory = pumpHistoryArray.removingDuplicateSuspendResumeEvents().rawJSON
         }
 
-        if useJavascriptOref {
-            let jsResult = await iobJavascript(pumphistory: pumphistory, profile: profile, clock: clock, autosens: autosens)
-            return try jsResult.returnOrThrow()
-        } else {
-            let swiftResult = OpenAPSSwift
-                .iob(pumphistory: pumphistory, profile: profile, clock: clock, autosens: autosens)
-            return try swiftResult.returnOrThrow()
-        }
-    }
-
-    func iobJavascript(pumphistory: JSON, profile: JSON, clock: JSON, autosens: JSON) async -> OrefFunctionResult {
-        do {
-            let result = try await withCheckedThrowingContinuation { continuation in
-                jsWorker.inCommonContext { worker in
-                    worker.evaluateBatch(scripts: [
-                        Script(name: Prepare.log),
-                        Script(name: Bundle.iob),
-                        Script(name: Prepare.iob)
-                    ])
-                    let result = worker.call(function: Function.generate, with: [
-                        pumphistory,
-                        profile,
-                        clock,
-                        autosens
-                    ])
-                    continuation.resume(returning: result)
-                }
-            }
-            return .success(result)
-        } catch {
-            return .failure(error)
-        }
+        let swiftResult = OpenAPSSwift
+            .iob(pumphistory: pumphistory, profile: profile, clock: clock, autosens: autosens)
+        return try swiftResult.returnOrThrow()
     }
 
     private func meal(
@@ -782,11 +743,10 @@ final class OpenAPS {
         basalProfile: JSON,
         clock: JSON,
         carbs: JSON,
-        glucose: JSON,
-        useJavascriptOref: Bool
-    ) async throws -> RawJSON {
-        if useJavascriptOref {
-            let jsResult = await mealJavascript(
+        glucose: JSON
+    ) throws -> RawJSON {
+        let swiftResult = OpenAPSSwift
+            .meal(
                 pumphistory: pumphistory,
                 profile: profile,
                 basalProfile: basalProfile,
@@ -794,52 +754,7 @@ final class OpenAPS {
                 carbs: carbs,
                 glucose: glucose
             )
-            return try jsResult.returnOrThrow()
-        } else {
-            let swiftResult = OpenAPSSwift
-                .meal(
-                    pumphistory: pumphistory,
-                    profile: profile,
-                    basalProfile: basalProfile,
-                    clock: clock,
-                    carbs: carbs,
-                    glucose: glucose
-                )
-            return try swiftResult.returnOrThrow()
-        }
-    }
-
-    private func mealJavascript(
-        pumphistory: JSON,
-        profile: JSON,
-        basalProfile: JSON,
-        clock: JSON,
-        carbs: JSON,
-        glucose: JSON
-    ) async -> OrefFunctionResult {
-        do {
-            let result = try await withCheckedThrowingContinuation { continuation in
-                jsWorker.inCommonContext { worker in
-                    worker.evaluateBatch(scripts: [
-                        Script(name: Prepare.log),
-                        Script(name: Bundle.meal),
-                        Script(name: Prepare.meal)
-                    ])
-                    let result = worker.call(function: Function.generate, with: [
-                        pumphistory,
-                        profile,
-                        clock,
-                        glucose,
-                        basalProfile,
-                        carbs
-                    ])
-                    continuation.resume(returning: result)
-                }
-            }
-            return .success(result)
-        } catch {
-            return .failure(error)
-        }
+        return try swiftResult.returnOrThrow()
     }
 
     private func autosense(
@@ -848,65 +763,19 @@ final class OpenAPS {
         basalprofile: JSON,
         profile: JSON,
         carbs: JSON,
-        temptargets: JSON,
-        useJavascriptOref: Bool
-    ) async throws -> RawJSON {
-        if useJavascriptOref {
-            let jsResult = await autosenseJavascript(
+        temptargets: JSON
+    ) throws -> RawJSON {
+        let swiftResult = OpenAPSSwift
+            .autosense(
                 glucose: glucose,
                 pumpHistory: pumpHistory,
-                basalprofile: basalprofile,
+                basalProfile: basalprofile,
                 profile: profile,
                 carbs: carbs,
-                temptargets: temptargets
+                tempTargets: temptargets,
+                clock: Date()
             )
-            return try jsResult.returnOrThrow()
-        } else {
-            let swiftResult = OpenAPSSwift
-                .autosense(
-                    glucose: glucose,
-                    pumpHistory: pumpHistory,
-                    basalProfile: basalprofile,
-                    profile: profile,
-                    carbs: carbs,
-                    tempTargets: temptargets,
-                    clock: Date()
-                )
-            return try swiftResult.returnOrThrow()
-        }
-    }
-
-    private func autosenseJavascript(
-        glucose: JSON,
-        pumpHistory: JSON,
-        basalprofile: JSON,
-        profile: JSON,
-        carbs: JSON,
-        temptargets: JSON
-    ) async -> OrefFunctionResult {
-        do {
-            let result = try await withCheckedThrowingContinuation { continuation in
-                jsWorker.inCommonContext { worker in
-                    worker.evaluateBatch(scripts: [
-                        Script(name: Prepare.log),
-                        Script(name: Bundle.autosens),
-                        Script(name: Prepare.autosens)
-                    ])
-                    let result = worker.call(function: Function.generate, with: [
-                        glucose,
-                        pumpHistory,
-                        basalprofile,
-                        profile,
-                        carbs,
-                        temptargets
-                    ])
-                    continuation.resume(returning: result)
-                }
-            }
-            return .success(result)
-        } catch {
-            return .failure(error)
-        }
+        return try swiftResult.returnOrThrow()
     }
 
     private func determineBasal(
@@ -921,151 +790,25 @@ final class OpenAPS {
         pumpHistory: JSON,
         preferences: JSON,
         basalProfile: JSON,
-        trioCustomOrefVariables: JSON,
-        useJavascriptOref: Bool
-    ) async throws -> RawJSON {
+        trioCustomOrefVariables: JSON
+    ) throws -> RawJSON {
         let clock = Date()
-
-        if useJavascriptOref {
-            let jsResult = await determineBasalJavascript(
-                glucose: glucose,
-                currentTemp: currentTemp,
-                iob: iob,
-                profile: profile,
-                autosens: autosens,
-                meal: meal,
-                microBolusAllowed: microBolusAllowed,
-                reservoir: reservoir,
-                pumpHistory: pumpHistory,
-                preferences: preferences,
-                basalProfile: basalProfile,
-                trioCustomOrefVariables: trioCustomOrefVariables,
-                clock: clock
-            )
-            return try jsResult.returnOrThrow()
-        } else {
-            let swiftResult = OpenAPSSwift.determineBasal(
-                glucose: glucose,
-                currentTemp: currentTemp,
-                iob: iob,
-                profile: profile,
-                autosens: autosens,
-                meal: meal,
-                microBolusAllowed: microBolusAllowed,
-                reservoir: reservoir,
-                pumpHistory: pumpHistory,
-                preferences: preferences,
-                basalProfile: basalProfile,
-                trioCustomOrefVariables: trioCustomOrefVariables,
-                clock: clock
-            )
-            return try swiftResult.returnOrThrow()
-        }
-    }
-
-    private func determineBasalJavascript(
-        glucose: JSON,
-        currentTemp: JSON,
-        iob: JSON,
-        profile: JSON,
-        autosens: JSON,
-        meal: JSON,
-        microBolusAllowed: Bool,
-        reservoir: JSON,
-        pumpHistory: JSON,
-        preferences: JSON,
-        basalProfile: JSON,
-        trioCustomOrefVariables: JSON,
-        clock: Date
-    ) async -> OrefFunctionResult {
-        do {
-            let result = try await withCheckedThrowingContinuation { continuation in
-                jsWorker.inCommonContext { worker in
-                    worker.evaluateBatch(scripts: [
-                        Script(name: Prepare.log),
-                        Script(name: Prepare.determineBasal),
-                        Script(name: Bundle.basalSetTemp),
-                        Script(name: Bundle.getLastGlucose),
-                        Script(name: Bundle.determineBasal)
-                    ])
-
-                    let result = worker.call(function: Function.generate, with: [
-                        iob,
-                        currentTemp,
-                        glucose,
-                        profile,
-                        autosens,
-                        meal,
-                        microBolusAllowed,
-                        reservoir,
-                        clock,
-                        pumpHistory,
-                        preferences,
-                        basalProfile,
-                        trioCustomOrefVariables
-                    ])
-
-                    continuation.resume(returning: result)
-                }
-            }
-            return .success(result)
-        } catch {
-            return .failure(error)
-        }
-    }
-
-    private func exportDefaultPreferences() -> RawJSON {
-        dispatchPrecondition(condition: .onQueue(processQueue))
-        return jsWorker.inCommonContext { worker in
-            worker.evaluateBatch(scripts: [
-                Script(name: Prepare.log),
-                Script(name: Bundle.profile),
-                Script(name: Prepare.profile)
-            ])
-            return worker.call(function: Function.exportDefaults, with: [])
-        }
-    }
-
-    // use `internal` protection to expose to unit tests
-    func makeProfileJavascript(
-        preferences: JSON,
-        pumpSettings: JSON,
-        bgTargets: JSON,
-        basalProfile: JSON,
-        isf: JSON,
-        carbRatio: JSON,
-        tempTargets: JSON,
-        model: JSON,
-        autotune: JSON,
-        trioSettings: JSON
-    ) async -> OrefFunctionResult {
-        do {
-            let result = try await withCheckedThrowingContinuation { continuation in
-                jsWorker.inCommonContext { worker in
-                    worker.evaluateBatch(scripts: [
-                        Script(name: Prepare.log),
-                        Script(name: Bundle.profile),
-                        Script(name: Prepare.profile)
-                    ])
-                    let result = worker.call(function: Function.generate, with: [
-                        pumpSettings,
-                        bgTargets,
-                        isf,
-                        basalProfile,
-                        preferences,
-                        carbRatio,
-                        tempTargets,
-                        model,
-                        autotune,
-                        trioSettings
-                    ])
-                    continuation.resume(returning: result)
-                }
-            }
-            return .success(result)
-        } catch {
-            return .failure(error)
-        }
+        let swiftResult = OpenAPSSwift.determineBasal(
+            glucose: glucose,
+            currentTemp: currentTemp,
+            iob: iob,
+            profile: profile,
+            autosens: autosens,
+            meal: meal,
+            microBolusAllowed: microBolusAllowed,
+            reservoir: reservoir,
+            pumpHistory: pumpHistory,
+            preferences: preferences,
+            basalProfile: basalProfile,
+            trioCustomOrefVariables: trioCustomOrefVariables,
+            clock: clock
+        )
+        return try swiftResult.returnOrThrow()
     }
 
     private func makeProfile(
@@ -1077,40 +820,23 @@ final class OpenAPS {
         carbRatio: JSON,
         tempTargets: JSON,
         model: JSON,
-        autotune: JSON,
+        autotune _: JSON,
         trioSettings: JSON,
-        useJavascriptOref: Bool,
         clock: Date
-    ) async throws -> RawJSON {
-        if useJavascriptOref {
-            let jsResult = await makeProfileJavascript(
-                preferences: preferences,
-                pumpSettings: pumpSettings,
-                bgTargets: bgTargets,
-                basalProfile: basalProfile,
-                isf: isf,
-                carbRatio: carbRatio,
-                tempTargets: tempTargets,
-                model: model,
-                autotune: autotune,
-                trioSettings: trioSettings
-            )
-            return try jsResult.returnOrThrow()
-        } else {
-            let swiftResult = OpenAPSSwift.makeProfile(
-                preferences: preferences,
-                pumpSettings: pumpSettings,
-                bgTargets: bgTargets,
-                basalProfile: basalProfile,
-                isf: isf,
-                carbRatio: carbRatio,
-                tempTargets: tempTargets,
-                model: model,
-                trioSettings: trioSettings,
-                clock: clock
-            )
-            return try swiftResult.returnOrThrow()
-        }
+    ) throws -> RawJSON {
+        let swiftResult = OpenAPSSwift.makeProfile(
+            preferences: preferences,
+            pumpSettings: pumpSettings,
+            bgTargets: bgTargets,
+            basalProfile: basalProfile,
+            isf: isf,
+            carbRatio: carbRatio,
+            tempTargets: tempTargets,
+            model: model,
+            trioSettings: trioSettings,
+            clock: clock
+        )
+        return try swiftResult.returnOrThrow()
     }
 
     private func loadJSON(name: String) -> String {

+ 0 - 26
Trio/Sources/APS/OpenAPS/Script.swift

@@ -1,26 +0,0 @@
-import Foundation
-
-struct Script {
-    let name: String
-    let body: String
-
-    init(name: String) {
-        self.name = name
-        if let url = Bundle.main.url(forResource: "javascript/\(name)", withExtension: "") {
-            do {
-                body = try String(contentsOf: url)
-            } catch {
-                debug(.openAPS, "Error loading script: \(error)")
-                body = "Error loading script"
-            }
-        } else {
-            print("Resource not found: javascript/\(name)")
-            body = "Resource not found"
-        }
-    }
-
-    init(name: String, body: String) {
-        self.name = name
-        self.body = body
-    }
-}

+ 3 - 18
Trio/Sources/Localizations/Main/Localizable.xcstrings

@@ -178483,6 +178483,9 @@
         }
       }
     },
+    "No bolus history yet" : {
+      "comment" : "Alert title when no quick-pick boluses history exists"
+    },
     "No confidence reminders are used." : {
       "comment" : "Description for BeepPreference.silent",
       "extractionState" : "manual",
@@ -180636,9 +180639,6 @@
     "No profile; cannot determine basal." : {
 
     },
-    "No bolus history yet" : {
-      "comment" : "Alert title when no quick-pick boluses history exists"
-    },
     "No recent oref algorithm determination." : {
       "localizations" : {
         "bg" : {
@@ -239257,9 +239257,6 @@
         }
       }
     },
-    "Switches back to the legacy JavaScript-based algorithm version." : {
-      "comment" : "Use JavaScript Oref mini hint"
-    },
     "Synth" : {
       "comment" : "Display name for the synth alarm sound.",
       "isCommentAutoGenerated" : true
@@ -269152,9 +269149,6 @@
         }
       }
     },
-    "Trio now uses a fully Swift-based version of the algorithm (Oref) by default. It's faster, more accurate and improves Trio for everyone." : {
-
-    },
     "Trio Personalization" : {
       "localizations" : {
         "bg" : {
@@ -277603,9 +277597,6 @@
         }
       }
     },
-    "Use JavaScript Oref" : {
-      "comment" : "Use JavaScript Oref"
-    },
     "Use local glucose server" : {
       "extractionState" : "manual",
       "localizations" : {
@@ -285398,9 +285389,6 @@
         }
       }
     },
-    "When enabled, Trio will instead use the legacy JavaScript-based algorithm that runs virtualized on your phone. Only enable this if you encounter issues with the Swift-based algorithm." : {
-
-    },
     "When Remote Control is enabled, you can send boluses, overrides, temporary targets, carbs, and other commands to Trio via push notifications." : {
       "localizations" : {
         "bg" : {
@@ -289559,9 +289547,6 @@
         }
       }
     },
-    "You can disable this feature anytime." : {
-
-    },
     "You can influence the adjustments made by Dynamic ISF primarily by adjusting Autosens Max, Autosens Min, and Adjustment Factor. Other settings also influence Dynamic ISF's response, such as Glucose Target, Profile ISF, Peak Insulin Time, and Weighted Average of TDD." : {
       "localizations" : {
         "bg" : {

+ 0 - 5
Trio/Sources/Models/TrioSettings.swift

@@ -69,7 +69,6 @@ struct TrioSettings: JSON, Equatable, Encodable {
     var bolusShortcut: BolusShortcutLimit = .notAllowed
     var timeInRangeType: TimeInRangeType = .timeInTightRange
     var requireAdjustmentsConfirmation: Bool = false
-    var useJavascriptOref: Bool = false
 
     /// Selected Garmin watchface (Trio or SwissAlpine)
     var garminWatchface: GarminWatchface = .trio
@@ -323,10 +322,6 @@ extension TrioSettings: Decodable {
             settings.requireAdjustmentsConfirmation = requireAdjustmentsConfirmation
         }
 
-        if let useJavascriptOref = try? container.decode(Bool.self, forKey: .useJavascriptOref) {
-            settings.useJavascriptOref = useJavascriptOref
-        }
-
         if let garminWatchface = try? container.decode(GarminWatchface.self, forKey: .garminWatchface) {
             settings.garminWatchface = garminWatchface
         }

+ 0 - 3
Trio/Sources/Modules/AlgorithmAdvancedSettings/AlgorithmAdvancedSettingsStateModel.swift

@@ -22,7 +22,6 @@ extension AlgorithmAdvancedSettings {
         @Published var remainingCarbsFraction: Decimal = 1.0
         @Published var remainingCarbsCap: Decimal = 90
         @Published var noisyCGMTargetMultiplier: Decimal = 1.3
-        @Published var useJavascriptOref: Bool = false
         // preference
         @Published var insulinActionCurve: Decimal = 10
         @Published var smbDeliveryRatio: Decimal = 0.5
@@ -48,8 +47,6 @@ extension AlgorithmAdvancedSettings {
             subscribePreferencesSetting(\.remainingCarbsCap, on: $remainingCarbsCap) { remainingCarbsCap = $0 }
             subscribePreferencesSetting(\.noisyCGMTargetMultiplier, on: $noisyCGMTargetMultiplier) {
                 noisyCGMTargetMultiplier = $0 }
-            subscribeSetting(\.useJavascriptOref, on: $useJavascriptOref) {
-                useJavascriptOref = $0 }
             subscribePreferencesSetting(\.smbDeliveryRatio, on: $smbDeliveryRatio) { smbDeliveryRatio = $0 }
             subscribePreferencesSetting(\.smbInterval, on: $smbInterval) { smbInterval = $0 }
             subscribePreferencesSetting(\.smbDeliveryRatio, on: $smbDeliveryRatio) { smbDeliveryRatio = $0 }

+ 0 - 33
Trio/Sources/Modules/AlgorithmAdvancedSettings/View/AlgorithmAdvancedSettingsRootView.swift

@@ -390,39 +390,6 @@ extension AlgorithmAdvancedSettings {
                         Text("Note: A CGM is considered noisy when it provides inconsistent readings.")
                     }
                 )
-                SettingInputSection(
-                    decimalValue: $decimalPlaceholder,
-                    booleanValue: $state.useJavascriptOref,
-                    shouldDisplayHint: $shouldDisplayHint,
-                    selectedVerboseHint: Binding(
-                        get: { selectedVerboseHint },
-                        set: {
-                            selectedVerboseHint = $0.map { AnyView($0) }
-                            hintLabel = NSLocalizedString("Use JavaScript Oref", comment: "Use JavaScript Oref")
-                        }
-                    ),
-                    units: state.units,
-                    type: .boolean,
-                    label: NSLocalizedString("Use JavaScript Oref", comment: "Use JavaScript Oref"),
-                    miniHint: String(
-                        localized: "Switches back to the legacy JavaScript-based algorithm version.",
-                        comment: "Use JavaScript Oref mini hint"
-                    ),
-                    verboseHint:
-                    VStack(alignment: .leading, spacing: 10) {
-                        Text("Default: OFF").bold()
-                        Text(
-                            "Trio now uses a fully Swift-based version of the algorithm (Oref) by default. It's faster, more accurate and improves Trio for everyone."
-                        )
-                        Text(
-                            "When enabled, Trio will instead use the legacy JavaScript-based algorithm that runs virtualized on your phone. Only enable this if you encounter issues with the Swift-based algorithm."
-                        )
-
-                        Text(
-                            "You can disable this feature anytime."
-                        )
-                    }
-                )
             }
             .listSectionSpacing(sectionSpacing)
             .sheet(isPresented: $shouldDisplayHint) {

+ 0 - 5
Trio/Sources/Modules/Home/View/Header/LoopStatusView.swift

@@ -288,11 +288,6 @@ struct LoopStatusView: View {
             tags.append("Smoothing: On")
         }
 
-        // FIXME: remove this before feat/dev-oref-swift is merged to dev
-        if !state.settingsManager.settings.useJavascriptOref {
-            tags.append("Swift Oref")
-        }
-
         if let currentTDD = state.fetchedTDDs.first?.totalDailyDose, currentTDD != 0 {
             tags.append("TDD: \(currentTDD)")
         }