code:
/* Hair: base is red */

@include make_hair('black') {
    -webkit-filter: hue-rotate(0deg) saturate(0%) brightness(40%) contrast(100%);
    filter: hue-rotate(0deg) saturate(0%) brightness(40%) contrast(100%);
}

@include make_hair('platinumblond') {
    -webkit-filter: hue-rotate(57deg) saturate(250%) brightness(180%) contrast(60%) sepia(0.75);
    filter: hue-rotate(57deg) saturate(250%) brightness(180%) contrast(60%) sepia(0.75);
}

@include make_hair('blond') {
    -webkit-filter: hue-rotate(60deg) saturate(130%) brightness(135%) contrast(100%);
    filter: hue-rotate(60deg) saturate(130%) brightness(135%) contrast(100%);
}

@include make_hair('blue') {
    -webkit-filter: hue-rotate(210deg) saturate(200%) brightness(60%) contrast(150%);
    filter: hue-rotate(210deg) saturate(200%) brightness(60%) contrast(150%);
}

@include make_hair('brown') {
    -webkit-filter: hue-rotate(40deg) saturate(100%) brightness(80%) contrast(100%);
    filter: hue-rotate(40deg) saturate(100%) brightness(80%) contrast(100%);
}

@include make_hair('lightbrown') {
    -webkit-filter: hue-rotate(40deg) saturate(100%) brightness(100%) contrast(110%);
    filter: hue-rotate(40deg) saturate(100%) brightness(100%) contrast(110%);
}

@include make_hair('strawberryblond') {
    -webkit-filter: hue-rotate(30deg) saturate(110%) brightness(110%) contrast(100%);
    filter: hue-rotate(30deg) saturate(110%) brightness(110%) contrast(100%);
}

@include make_hair('ginger') {
    -webkit-filter: hue-rotate(55deg) saturate(200%) brightness(110%) contrast(100%);
    filter: hue-rotate(55deg) saturate(200%) brightness(110%) contrast(100%);
}

@include make_hair('green') {
    -webkit-filter: hue-rotate(90deg) saturate(100%) brightness(100%) contrast(100%);
    filter: hue-rotate(90deg) saturate(100%) brightness(100%) contrast(100%);
}

@include make_hair('teal') {
    -webkit-filter: hue-rotate(165deg) saturate(100%) brightness(100%) contrast(100%);
    filter: hue-rotate(165deg) saturate(100%) brightness(100%) contrast(100%);
}

@include make_hair('pink') {
    -webkit-filter: hue-rotate(-20deg) saturate(70%) brightness(130%) contrast(100%);
    filter: hue-rotate(-20deg) saturate(70%) brightness(130%) contrast(100%);
}

@include make_hair('hotpink') {
    -webkit-filter: hue-rotate(320deg) saturate(100%) brightness(120%) contrast(100%);
    filter: hue-rotate(320deg) saturate(100%) brightness(120%) contrast(100%);
}

@include make_hair('softpink') {
    -webkit-filter: hue-rotate(0deg) saturate(30%) brightness(190%) contrast(100%);
    filter: hue-rotate(0deg) saturate(30%) brightness(190%) contrast(100%);
}

@include make_hair('purple') {
    -webkit-filter: hue-rotate(-80deg) saturate(110%) brightness(60%) contrast(200%);
    filter: hue-rotate(-80deg) saturate(110%) brightness(60%) contrast(200%);
}

@include make_hair('red') {
    -webkit-filter: hue-rotate(0deg) saturate(100%) brightness(100%) contrast(100%);
    filter: hue-rotate(0deg) saturate(100%) brightness(100%) contrast(100%);
}

@include make_hair('crimson') {
    -webkit-filter: hue-rotate(0deg) saturate(155%) brightness(75%) contrast(135%);
    filter: hue-rotate(0deg) saturate(155%) brightness(75%) contrast(135%);
}

@include make_hair('white') {
    -webkit-filter: hue-rotate(0deg) saturate(0%) brightness(160%) contrast(100%);
    filter: hue-rotate(0deg) saturate(0%) brightness(160%) contrast(100%);
}

@include make_hair('snowwhite') {
    -webkit-filter: hue-rotate(0deg) saturate(0%) brightness(190%) contrast(100%);
    filter: hue-rotate(0deg) saturate(0%) brightness(190%) contrast(100%);
}


code:
@each $key, $value in $layers {
    .layer-#{$key} {
        z-index: $value;
    }
}

repo_name: BrokenSoul/degrees


code:
#map-display-container {
    width: 100%;
    position: relative;

    img {
        display: block;
    }

    #background-layer {
        z-index: -1;
    }

    .location-single {
        position: absolute;
        transition: margin-top $mapLocTransition;
        margin-top: 0;

        .location-light {
            position: absolute;
            top: 0;
            left: 0;
        }

        .location-active-trigger {
            position: absolute;
            z-index: 1;
        }

        &.link-active {
            &.location-is-hovered {
                margin-top: -10px;
            }

            // DEV
            border: solid 3px blue;
        }
    }
}


code:
@mixin make_meter($selector, $color) {
    .#{unquote($selector)} {
        position: absolute;
        left: 0;
        top: 0;
        height: 0.3em;
        background-color: $color;
        z-index: -10;
    }
}

@mixin make_hair($selector) {
    .hair-#{unquote($selector)} {
        .colour-hair {
            @content;
        }
    }
}

@mixin make_eye($selector) {
    .eye-#{unquote($selector)} {
        .colour-eye {
            @content;
        }
    }
}

@mixin make_clothing($selector) {
    .upper-#{unquote($selector)} {
        .colour-upper {
            @content;
        }
    }

    .lower-#{unquote($selector)} {
        .colour-lower {
            @content;
        }
    }

    .under-#{unquote($selector)} {
        .colour-under {
            @content;
        }
    }
}

@mixin make_animation($identifier, $steps, $time, $pace: "", $overrideSteps: false) {
    $class: unquote("anim-") + unquote($identifier) + "-" + $steps + unquote("f");

    @if $pace != "" {
        $class: $class + unquote("-") + unquote($pace);
    }

    @if $overrideSteps != false {
        $steps: $overrideSteps;
    }

    .#{$class} {
        -webkit-animation-duration: $time;
        -moz-animation-duration: $time;
        -o-animation-duration: $time;
        animation-duration: $time;

        -webkit-animation-timing-function: steps($steps);
        -moz-animation-timing-function: steps($steps);
        -o-animation-timing-function: steps($steps);
        animation-timing-function: steps($steps);

        -webkit-animation-iteration-count: infinite;
        -moz-animation-iteration-count: infinite;
        -o-animation-iteration-count: infinite;
        animation-iteration-count: infinite;

        -webkit-animation-name: anim-default;
        -moz-animation-name: anim-default;
        -o-animation-name: anim-default;
        animation-name: anim-default;
    }
}


code:
.macro-numberslider {
    display: inline-block;

    input {
        width: 3em;
        text-align: center;

        -webkit-appearance: none;
        cursor: pointer;
        height: 1.25em;
        min-width: 20em;
        vertical-align: middle;

        &:focus {
            outline: none;
        }

        &::-webkit-slider-runnable-track, &::-moz-range-track {
            background: #222;
            border: 1px solid #444;
            border-radius: 0;
            cursor: pointer;
            height: 10px;
            width: 100%;

            &:focus {
                background: #222;
            }
        }

        &::-webkit-slider-thumb, &::-moz-range-thumb {
            -webkit-appearance: none;
            background: #35a;
            border: 1px solid #57c;
            border-radius: 0;
            cursor: pointer;
            height: 18px;
            margin-top: -5px;
            width: 33px;
        }

        &::-ms-track {
            background: transparent;
            border-color: transparent;
            color: transparent;
            cursor: pointer;
            height: 10px;
            width: 99%; /* fallback for MS browsers without support for calc() */
            width: calc(100% - 1px);
        }

        &::-ms-thumb {
            background: #35a;
            border: 1px solid #57c;
            border-radius: 0;
            cursor: pointer;
            height: 16px;
            width: 33px;
        }

        &::-ms-fill-lower {
            background: #222;
            border: 1px solid #444;
            border-radius: 0;
        }

        &::-ms-fill-upper {
            background: #222;
            border: 1px solid #444;
            border-radius: 0;
        }
    }

    button {
        font-family: "tme-fa-icons";
        font-style: normal;
        font-weight: normal;
        font-variant: normal;
        text-transform: none;
        line-height: normal;
        speak: none;
        padding: 0.4em 0.6em;

        &[id^="numberbox-minus"] {
            margin-right: 0.4em;
        }

        &[id^="numberbox-plus"] {
            margin-left: 0.4em;
        }
    }

    span {
        display: inline-block;
        /*font-size: 1.25em;*/
        margin-left: 0.25em;
        min-width: 3em;
        text-align: center;
        vertical-align: middle;
    }
}


code:
#ui-bar {
    z-index: 300;
}

#ui-bar-toggle {
    z-index: 500;
}

body {
    &.has-images {
        header {
            &#title {
                display: none;
            }
        }

        #story-caption {
            /* 256 px: images
	        2.5 em: ui-bar-body margin-top */
            margin-top: calc(256px - 2.5em);
        }
    }
}

.hide {
    a {
        color: $white;
        text-decoration: none !important;

        &:hover {
            color: $white;
        }
    }
}

.general {
    opacity: 0.99;
}

#statbar {
    position: relative;
    left: 0;
    top: 9px;
    z-index: 0;
}

#img {
    height: 256px;
    width: 256px;
    overflow: hidden;

    position: fixed;
    top: 0;
    left: 0;

    & > * {
        position: absolute;
        top: 0;
        left: 0;
    }
}

#daystate {
    position: fixed;
    left: 0;
    top: 0;
    z-index: 10;
}

#weather {
    position: fixed;
    left: 0;
    top: 64px;
    z-index: 10;
}

#location {
    position: fixed;
    left: 0;
    top: 128px;
    z-index: 10;
}

#divmap {
    position: relative;
    display: inline-block;
    height: 256px;
    width: 256px;

}

#map {
    position: absolute;
    left: 0;
    top: 0;
    z-index: 10;
}

#maparrow {
    position: absolute;
    left: 0;
    top: 0;
    z-index: 20;
}

.meter {
    position: relative;
    height: 0.3em;
    width: 100%;
    background-color: gray;
    text-align: center;
    z-index: -10;
}

@include make_meter('redbar', $red);
@include make_meter('pinkbar', $pink);
@include make_meter('purplebar', $purple);
@include make_meter('bluebar', $blue);
@include make_meter('lbluebar', $light-blue);
@include make_meter('tealbar', $teal);
@include make_meter('greenbar', $green);
@include make_meter('goldbar', $gold);


code:
$red: #EC3535;
$pink: #E40081;
$purple: #AA4BC8;
$blue: #4372FF;
$light-blue: #559BC0;
$teal: #08C1C1;
$green: #38B20A;
$platinum: #FEF593;
$gold: #FFD700;
$orange: #f28500;
$strawberry: #F08C51;
$tangerine: #f28500;
$brown: #aa7243;
$light-brown: #C5793A;
$gray: #929292;
$light-gray: #B7B7B7;

$white: #eee;

$action-brat: #B75D41;
$action-meek: #C44B8B;
$action-def: #D20000;
$action-sub: #AA4BC8;
$action-lewd: #E04880;

$mapLocTransition: 0.3s;

$layers: (
    'bg': 0,
    'backhair': 10,
    'base': 20,
    'hirsute': 21,
    'eyes': 30,
    'sclera': 35,
    'mouth': 40,
    'blush': 50,
    'tears': 55,
    'hair': 60,
    'brow': 62,
    'lashes': 64,
    'under': 75,
    'legsacc': 80,
    'feetacc': 85,
    'lower': 90,
    'upper': 95,
    'collar': 100,
    'rightarm': 105,
    'leftarm': 105,
    'rightarmclothes': 110,
    'leftarmclothes': 110,
    'faceacc': 125,
    'headacc': 130
);


code:
.wetstage2 {
    opacity: 0.90;
    filter: brightness(0.95);
}

.wetstage3 {
    opacity: 0.75;
    filter: brightness(0.90);
}


code:
#divsex {
    position: relative;
    display: inline-block;
    height: 256px;
    width: 768px;

    & > * {
        position: absolute;
        left: 256px;
        top: 0;
    }
}

#divandroidsex {
    position: relative;
    display: inline-block;
    height: 256px;
    width: 256px;
    left: -256px;

    & > * {
        position: absolute;
        left: 256px;
        top: 0;
    }
}

#closepenis {
    &, #divsex & {
        position: absolute;
        left: 321px;
        top: -30px;
        z-index: 250;
    }
}

#closeanus {
    &, #divsex & {
        position: absolute;
        left: 451px;
        top: -30px;
        z-index: 250;
    }
}

#closevagina {
    &, #divsex & {
        position: absolute;
        left: 386px;
        top: -30px;
        z-index: 250;
    }
}

#divandroidxray {
    position: relative;
    display: inline-block;
    height: 256px;
    width: 256px;
}

#xrayvaginal {
    &, #divsex & {
        position: absolute;
        left: 0;
        top: 0;
        z-index: 3;
    }
}

#xrayvaginalcum {
    &, #divsex & {
        position: absolute;
        left: 0;
        top: 0;
        z-index: 4;
    }
}

#xraypenile {
    &, #divsex & {
        position: absolute;
        left: 0;
        top: 0;
        z-index: 2;
    }
}

#xrayanal {
    &, #divsex & {
        position: absolute;
        left: 512px;
        top: 0;
        z-index: 1;
    }
}

#xrayandroidanal {
    &, #divsex & {
        position: relative;
        left: 0;
        top: -150px;
        z-index: 1;
    }
}


code:
@import "mixins";
@import "variables";

@import "colors";

@import "ui";
@import "numberbox";
@import "wet";
@import "layers";
@import "xray";
@import "hair";
@import "eyes";
@import "clothing";

@import "animation_base";
@import "animation";

@import "map";


code:
export default [{
    type: 'outfit',
    states: {
        100: {
            upper: 'img/upperclothes/sundressupper/sundressupperred.png'
        }
    }
}];


code:
export default [{
    type: 'upper',
    id: 't_shirt',
    name: 'T-Shirt',
    states: {
        100: {
            sprite: 'GOOD_SPRITE'
        },
        70: {
            sprite: 'TORN_WHATEVER'
        },
        //[...]
    },
    variants: {
        'red': {
            class: 'red'
        },
        'blue': {
            class: 'red'
        },
        'black_with_heart': {
            states: {
                100: {
                    sprite: 'GOOD_SPRITE_WITH_HEART'
                },
                70: {
                    sprite: 'TORN_WHATEVER_WITH_HEART'
                },
            },
            combat: {
                'hips': 'special',
                'neck': 'sprite',
                'thigs': 'goes',
                'tummy': 'here'
            }
        }
    },
    combat: {
        'hips': 'whatever',
        'neck': 'sprite',
        'thigs': 'sprite',
        'tummy': 'sprite'
    },
    integrity: {
        max: 100,
        current: 100 // or saved
    },
    fabric_strength: 100, // dmg - fabric strength (min 1 dmg?)
    reveal: 100
}];


code:
class Clothing {

}

export default Clothing;


code:
import {checkForDaylightExposure} from "./PlayerStates";
import {colourContainerClasses} from "../Macros/Misc";
import "../Macros/Numberpool";
import {upperIntegrity, lowerIntegrity, underIntegrity} from "../Macros/Clothing";
import {macroSetup} from "./Utilities";
import GameMap from "./GameMap";
import "./Numberify";
import {ImportDefaultGameState, GetNpc} from "../Macros/GameState";
import "../Update/SaveUpdater";

class Game {
    constructor() {
        this.initState();
        this.initMacros();
        this.initTwineHelper();

        console.log("Degrees of Lewdity initialized.");
    }

    initMacros() {
        macroSetup('display_map', GameMap);

        macroSetup('underintegrity', underIntegrity, true, true);
        macroSetup('lowerintegrity', lowerIntegrity, true, true);
        macroSetup('upperintegrity', upperIntegrity, true, true);
        macroSetup('init_game_state', ImportDefaultGameState, false, true);
    }

    initState() {
        Config.history.controls = false;
        Config.history.maxStates = 20;

        State.initPRNG();

        $(document).ready(() => {
            $('#sidetooltip').appendTo('body');
        });
    }

    initTwineHelper() {
        window.DoL = {
            colourContainerClasses: colourContainerClasses,
            daylightExposure: checkForDaylightExposure
        };
    }

    static getGameVersion() {
        return '1.25.0';
    }
}

export default Game;


code:
import Maps from "../Maps/All";
import {get} from "./Utilities";
import _ from 'lodash';

class GameMap {
    macro = null;
    map = null;
    locationID = null;

    location = null;

    renderedLocations = {};

    constructor(macro) {
        this.macro = macro;
        const [locationID, mapID] = this.macro.args;

        this.map = GameMap.getMapById(mapID);
        this.locationID = locationID;
        if (this.map === null)
            this.macro.error(`Invalid map id specified (${mapID}) or default map is not set!`);

        this.validateLocation();
    }

    validateLocation() {
        if (typeof this.locationID !== "string")
            this.macro.error("Invalid location id type");

        for (let m of this.map.map.locations) {
            if (this.locationID === m.id) {
                this.location = m;
                break;
            }
        }

        if (this.location === null)
            this.macro.error(`Invalid location id specified (${this.locationID}), not found in map (${this.map.mapID})`);
    }

    static getDefaultMap() {
        for (let m of Maps)
            if (typeof m.default !== "undefined" && m.default)
                return m;

        return null;
    }

    static getMapById(mapID) {
        if (typeof mapID === "undefined")
            return GameMap.getDefaultMap();

        for (let m of Maps)
            if (m.mapID === mapID)
                return m;

        return null;
    }

    renderLocation(loc, map) {
        const location = $('<div>').attr('id', 'location-' + loc.id).css({
            left: loc.x,
            top: loc.y
        }).addClass('location-single');

        $(location).append(
            $('<img>').addClass('location-sprite').attr('src', get(loc.sprite))
        );

        if (typeof loc.light !== "undefined")
            $(location).append(
                $('<img>').addClass('location-light').attr('src', get(loc.light))
            );

        if (typeof loc.active === "undefined") {
            $(location).append(
                $('<div>').addClass('location-active-trigger').css({
                    left: 0,
                    top: 0,
                    width: '100%',
                    height: '100%'
                })
            );
        }
        else {
            const active = get(loc.active);

            const left = active.x;
            const top = active.y;
            const width = active.width;
            const height = active.height;

            $(location).append(
                $('<div>').addClass('location-active-trigger').addClass('location-active-trigger-custom').css({
                    left,
                    top,
                    width,
                    height
                })
            );
        }

        if (this.locationID === loc.id) {
            $(location).addClass('location-current');
        }

        this.renderedLocations[loc.id] = location;

        $(map).append(location);
    }

    attachLinks() {
        let currentLocation = null;
        for (let l of this.map.map.locations) {
            if (this.locationID === l.id) {
                currentLocation = l;
                break;
            }
        }

        let links = get(currentLocation.links);
        let locations = _.keyBy(_.cloneDeep(this.map.map.locations), o => o.id);

        for (let link of links) {
            if (typeof this.renderedLocations[link] === "undefined") {
                console.warn(`Unknown selected for the current location (${link})`);
                continue;
            }

            if (typeof locations[link].canBeVisited !== "undefined") {
                if (!get(locations[link].canBeVisited)) {
                    delete locations[link];
                    continue;
                }
            }

            $(this.renderedLocations[link]).addClass('link-active');

            const activeTrigger = $(this.renderedLocations[link]).find('.location-active-trigger');

            $(activeTrigger).on('click', () => {
                const myLocation = _.keyBy(this.map.map.locations, o => o.id)[link];
                if (typeof myLocation.passage === "undefined") {
                    console.warn(`Passage for link ${link} is not defined.`);
                    return;
                }

                const passage = get(myLocation.passage);
                if (typeof passage !== "string") {
                    console.error(`Passage returned for link ${link} is not a string.`);
                    return;
                }

                const timePass = get(myLocation.timePass);
                if (typeof timePass === "number")
                    Wikifier.wikifyEval(`<<pass ${timePass}>>`);

                Engine.play(passage);
            }).on('mouseenter', (e) => {
                $(e.currentTarget).closest('.location-single').addClass('location-is-hovered');
            }).on('mouseleave', (e) => {
                $(e.currentTarget).closest('.location-single').removeClass('location-is-hovered');
            });
            delete locations[link];
        }

        for (let link in locations) {
            if (link === this.locationID)
                continue; // current location is in this list, no need to pollute it with the class

            $(this.renderedLocations[link]).addClass('link-inactive');
        }
    }

    renderMap() {
        const container = $('<div>').attr('id', 'map-display-container').addClass('map-id-' + this.map.mapID);
        $(container).append(
            $('<img>').attr('id', 'background-layer').attr('src', get(this.map.map.background))
        );

        for (let l of this.map.map.locations)
            this.renderLocation(l, container);

        this.attachLinks();

        return container;
    }

    run() {
        jQuery(this.macro.output).append(this.renderMap());
    }
}

export default GameMap;


code:
const disableNumberifyInVisibleElements = [
    '#passage-hairdressers-seat',
    '#passage-start',
    '#passage-wardrobe',
    '#passage-cheats',
    '#passage-testing-room'
];

let currentLinks = [];

function getPrettyKeyNumber(counter) {
    var str = "";

    if (counter > 30)
        str = "Ctrl + ";
    else if (counter > 20)
        str = "Alt + ";
    else if (counter > 10)
        str = "Shift + ";

    if (counter % 10 === 0)
        str += "0";
    else if (counter < 10)
        str += counter;
    else {
        let c = Math.floor(counter / 10);
        str += (counter - (10 * c)).toString();
    }

    return str;
}

$(document).on(':passagerender', (ev) => {
    currentLinks = [];

    for (var i = 0; i < disableNumberifyInVisibleElements.length; i++) {
        if ($(ev.content).find(disableNumberifyInVisibleElements[i]).length || $(ev.content).is(disableNumberifyInVisibleElements[i]))
            return; // simply skip this render
    }

    currentLinks = $(ev.content).find(".link-internal"); // wanted to use .macro-link, but wardrobe and something else doesn't get selected, lmao

    $(currentLinks).each(function(i, el) {
        $(el).html("(" + getPrettyKeyNumber(i + 1) + ") " + $(el).html());
    });
});

$(document).on('keyup', (ev) => {
    if ((ev.keyCode >= 48 && ev.keyCode <= 57) || (ev.keyCode >= 96 && ev.keyCode <= 105)) {
        const fixedKeyIndex = (ev.keyCode < 60 ? ev.keyCode - 48 : ev.keyCode - 96);

        let requestedLinkIndex = [9, 0, 1, 2, 3, 4, 5, 6, 7, 8][fixedKeyIndex];

        if (ev.ctrlKey)
            requestedLinkIndex += 30;
        else if (ev.altKey)
            requestedLinkIndex += 20;
        else if (ev.shiftKey)
            requestedLinkIndex += 10;

        if ($(currentLinks).length >= requestedLinkIndex + 1)
            $(currentLinks[requestedLinkIndex]).click();
    }
});


code:
export function checkForDaylightExposure() {
    const exposedState = parseInt(State.variables.exposed);
    const dayState = State.variables.daystate;

    return exposedState >= 1 && dayState !== "night";
}


code:
export function macroSetup(tag, target, output = false, asFunction = false, functionTarget = 'run') {
    Macro.add(tag, {
        isWidget: false,
        handler: function() {
            const self = this;
            let returnValue = (asFunction ? target(self) : new target(self)[functionTarget]());

            if (output)
                $(self.output).wiki(returnValue);
        }
    });
}

export function get(target) {
    if (typeof target === "function")
        return target();

    return target;
}


code:
export function underIntegrity() {
    let output = '';
    const underIntegrity = State.variables.underintegrity;
    const underIntegrityMax = State.variables.underintegritymax;

    if (underIntegrityMax !== 0) {
        if (underIntegrity <= (underIntegrityMax / 10) * 2)
            output = 'tattered \t';
        else if (underIntegrity <= (underIntegrityMax / 10) * 5)
            output = 'torn \t';
        else if (underIntegrity <= (underIntegrityMax / 10) * 9)
            output = 'frayed \t';
    }

    return output;
}

export function lowerIntegrity() {
    let output = '';
    const lowerIntegrity = State.variables.lowerintegrity;
    const lowerIntegrityMax = State.variables.lowerintegritymax;

    if (lowerIntegrityMax !== 0) {
        if (lowerIntegrity <= (lowerIntegrityMax / 10) * 2)
            output = 'tattered \t';
        else if (lowerIntegrity <= (lowerIntegrityMax / 10) * 5)
            output = 'torn \t';
        else if (lowerIntegrity <= (lowerIntegrityMax / 10) * 9)
            output = 'frayed \t';
    }

    return output;
}

export function upperIntegrity() {
    let output = '';
    const upperIntegrity = State.variables.upperintegrity;
    const upperIntegrityMax = State.variables.upperintegritymax;

    if (upperIntegrityMax !== 0) {
        if (upperIntegrity <= (upperIntegrityMax / 10) * 2)
            output = 'tattered \t';
        else if (upperIntegrity <= (upperIntegrityMax / 10) * 5)
            output = 'torn \t';
        else if (upperIntegrity <= (upperIntegrityMax / 10) * 9)
            output = 'frayed \t';
    }

    return output;
}


code:
import {GameState, GameVersion, NpcShared, NpcHuman, NpcBeast, NpcSwarm, NpcTentacles, NpcVore} from "../Update/Versions";
import * as deepmerge from "deepmerge";

const NpcMap = {
    'man': NpcHuman,
    'beast': NpcHuman,
    'vore': NpcVore,
    'tentacles': NpcTentacles,
    'swarm': NpcSwarm
};

const SugarCubeVariables = [
    'passage',
    'tags'
];

export function ImportDefaultGameState() {
    for (let key in State.variables)
        if (SugarCubeVariables.indexOf(key) === -1)
            delete State.variables[key];

    for (let key in GameState)
        State.variables[key] = GameState[key];

    State.variables._gameVersion = GameVersion;

    console.log("Default game state set.");
}

export function GetNpc(npcType = null) {
    if (!NpcMap.hasOwnProperty(npcType))
        throw new Error(`No valid npc type specified (${npcType}`);

    return deepmerge.merge(NpcShared, NpcMap[npcType]);
}


code:
Macro.add('time', {
    handler: () => {
        const time = State.variables.time;
        const hour = Math.floor(time/60);

        let dayState = '';

        if (hour < 6)
            dayState = 'night';
        else if (hour < 9)
            dayState = 'dawn';
        else if (hour < 18)
            dayState = 'day';
        else if (hour < 21)
            dayState = 'dusk';
        else
            dayState = 'night';

        State.variables.hour = hour;
        State.variables.daystate = dayState;
    }
});

export function colourContainerClasses() {
    const V = State.variables;
    return 'hair-'  + (V.haircolour||'').replace(/ /g,'-') +
        ' ' + 'eye-'   + (V.eyecolour||'').replace(/ /g,'-') +
        ' ' + 'upper-' + (V.uppercolour||'').replace(/ /g,'-') +
        ' ' + 'lower-' + (V.lowercolour||'').replace(/ /g,'-') +
        ' ' + 'under-' + (V.undercolour||'').replace(/ /g,'-')
}


code:
Macro.add("numberbox", {
    handler: function() {
        function validateAndApply(el, addend) {
            var curValue = Math.trunc(Wikifier.getValue(varName)),
                newValue = Math.trunc(el.value),
                newPoolValue = null;
            if (Number.isNaN(newValue) || !Number.isFinite(newValue)) return el.value = curValue, !1;
            if (null != addend && (newValue += addend), newValue < minValue ? newValue = minValue : newValue > maxValue && (newValue = maxValue), null !== pool) {
                var poolValue = pool.get(),
                    delta = (newValue - curValue) * poolCost;
                delta < 0 ? newPoolValue = poolValue - delta : delta > 0 && poolValue >= poolCost ? (poolValue < delta && (newValue = curValue + Math.trunc(poolValue / poolCost), delta = poolValue - poolValue % poolCost), newPoolValue = poolValue - delta) : newValue = curValue
            }
            return Wikifier.setValue(varName, newValue), el.value = newValue, null !== newPoolValue && pool.set(newPoolValue), !0
        }
        var _this = this;
        if (this.args.length < 4) {
            var errors = [];
            return this.args.length < 1 && errors.push("variable name"), this.args.length < 2 && errors.push("default value"), this.args.length < 3 && errors.push("min value"), this.args.length < 4 && errors.push("max value"), this.error("no " + errors.join(" or ") + " specified")
        }
        if ("string" != typeof this.args[0]) return this.error("variable name argument is not a string");
        var varName = this.args[0].trim();
        if ("$" !== varName[0] && "_" !== varName[0]) return this.error('variable name "' + this.args[0] + '" is missing its sigil ($ or _)');
        var varId = Util.slugify(varName),
            defValue = Number(this.args[1]),
            minValue = Number(this.args[2]),
            maxValue = Number(this.args[3]),
            poolCost = 1,
            autofocus = !1;
        if (this.args.length > 5 ? (poolCost = Number(this.args[4]), autofocus = "autofocus" === this.args[5]) : this.args.length > 4 && ("autofocus" === this.args[4] ? autofocus = !0 : poolCost = Number(this.args[4])), Number.isNaN(defValue) || !Number.isFinite(defValue) || Math.trunc(defValue) !== defValue) return this.error("default value (" + this.args[1] + ") is not a whole number");
        if (Number.isNaN(minValue) || !Number.isFinite(minValue) || Math.trunc(minValue) !== minValue) return this.error("min value (" + this.args[2] + ") is not a whole number");
        if (Number.isNaN(maxValue) || !Number.isFinite(maxValue) || Math.trunc(maxValue) !== maxValue) return this.error("max value (" + this.args[3] + ") is not a whole number");
        if (Number.isNaN(poolCost) || !Number.isFinite(poolCost) || Math.trunc(poolCost) !== poolCost || poolCost <= 0) return this.error("pool cost (" + this.args[4] + ") is not a whole number greater than zero");
        if (defValue < minValue) return this.error("default value (" + this.args[1] + ") is less than min value (" + this.args[2] + ")");
        if (defValue > maxValue) return this.error("default value (" + this.args[1] + ") is greater than max value (" + this.args[3] + ")");
        var pool = function() {
            var parent = _this.contextSelect(function(ctx) {
                return "numberpool" === ctx.name
            });
            return null !== parent && parent.hasOwnProperty("pool") ? parent.pool : null
        }();
        Config.debug && this.debugView.modes({
            block: !0
        });
        var $elControl = jQuery(document.createElement("div")),
            $elInput = jQuery(document.createElement("input"));
        $elControl.attr("id", this.name + "-body-" + varId).addClass("macro-" + this.name).appendTo(this.output), jQuery(document.createElement("button")).attr({
            id: this.name + "-minus-" + varId,
            tabindex: 0
        }).text("").on("click", function() {
            return validateAndApply($elInput[0], -1)
        }).appendTo($elControl), $elInput.attr({
            id: this.name + "-input-" + varId,
            name: this.name + "-input-" + varId,
            type: "text",
            pattern: "\\d+",
            tabindex: 0
        }).on("change", function() {
            validateAndApply(this)
        }).on("keypress", function(ev) {
            13 === ev.which && (ev.preventDefault(), $elInput.trigger("change"))
        }).appendTo($elControl), jQuery(document.createElement("button")).attr({
            id: this.name + "-plus-" + varId,
            tabindex: 0
        }).text("").on("click", function() {
            return validateAndApply($elInput[0], 1)
        }).appendTo($elControl), $elInput.val(defValue), validateAndApply($elInput[0]), autofocus && ($elInput.attr("autofocus", "autofocus"), postdisplay["#autofocus:" + $elInput.attr("id")] = function(task) {
            delete postdisplay[task], setTimeout(function() {
                return $elInput.focus()
            }, Engine.minDomActionDelay)
        })
    }
});

Macro.add("numberpool", {
    tags: ["onchange"],
    handler: function() {
        if (0 === this.args.length) return this.error("no variable name specified");
        if (this.payload.length > 2) return this.error("multiple <<onchange>> sections specified");
        if ("string" != typeof this.args[0]) return this.error("variable name argument is not a string");
        var varName = this.args[0].trim();
        if ("$" !== varName[0] && "_" !== varName[0]) return this.error('variable name "' + this.args[0] + '" is missing its sigil ($ or _)');
        var curValue = Wikifier.getValue(varName);
        if ("number" != typeof curValue || Number.isNaN(curValue) || !Number.isFinite(curValue)) return this.error("pool value is not a number");
        var varId = Util.slugify(varName);
        TempState.hasOwnProperty(this.name) || (TempState[this.name] = {}), TempState[this.name].hasOwnProperty(varId) || (TempState[this.name][varId] = 0), Object.defineProperty(this, "pool", {
            value: Object.defineProperties({}, {
                get: {
                    value: function() {
                        return Wikifier.getValue(varName)
                    }
                },
                set: {
                    value: function(content) {
                        return function(value) {
                            var curValue = Wikifier.getValue(varName);
                            value !== curValue && (Wikifier.setValue(varName, value), content && new Wikifier(null, content))
                        }
                    }(this.payload.length > 1 ? this.payload[1].contents.trim() : "")
                }
            })
        }), jQuery(document.createElement("div")).attr("id", this.name + "-" + varId + "-" + TempState[this.name][varId]++).addClass("macro-" + this.name).wiki(this.payload[0].contents.replace(/^\n/, "")).appendTo(this.output)
    }
});

Macro.add("numberslider", {
    handler: function() {
        function stepValidate(value) {
            if (fracDigits > 0) {
                var ma = Number(minValue + "e" + fracDigits),
                    sa = Number(stepValue + "e" + fracDigits),
                    _va = Number(value + "e" + fracDigits) - ma;
                return Number(_va - _va % sa + ma + "e-" + fracDigits)
            }
            var va = value - minValue;
            return va - va % stepValue + minValue
        }

        function validateAndApply(el) {
            var curValue = Wikifier.getValue(varName),
                newValue = Number(el.value),
                newPoolValue = null;
            if (Number.isNaN(newValue) || !Number.isFinite(newValue)) return el.value = curValue, !1;
            if (newValue = stepValidate(newValue), newValue < minValue ? newValue = minValue : newValue > maxValue && (newValue = maxValue), null !== pool)
                if (fracDigits > 0) {
                    var pa = Number(pool.get() + "e" + fracDigits),
                        ca = Number(curValue + "e" + fracDigits),
                        na = Number(newValue + "e" + fracDigits),
                        delta = na - ca;
                    pa < delta && (na -= delta - pa, delta = na - ca, newValue = Number(na + "e-" + fracDigits)), newPoolValue = Number(pa - delta + "e-" + fracDigits)
                } else {
                    var poolValue = pool.get(),
                        _delta = newValue - curValue;
                    poolValue < _delta && (newValue -= _delta - poolValue, _delta = newValue - curValue), newPoolValue = poolValue - _delta
                }
            return Wikifier.setValue(varName, newValue), el.value = newValue, null !== newPoolValue && pool.set(newPoolValue), !0
        }
        var _this2 = this;
        if (this.args.length < 5) {
            var errors = [];
            return this.args.length < 1 && errors.push("variable name"), this.args.length < 2 && errors.push("default value"), this.args.length < 3 && errors.push("min value"), this.args.length < 4 && errors.push("max value"), this.args.length < 5 && errors.push("step value"), this.error("no " + errors.join(" or ") + " specified")
        }
        if ("string" != typeof this.args[0]) return this.error("variable name argument is not a string");
        var varName = this.args[0].trim();
        if ("$" !== varName[0] && "_" !== varName[0]) return this.error('variable name "' + this.args[0] + '" is missing its sigil ($ or _)');
        var varId = Util.slugify(varName),
            defValue = Number(this.args[1]),
            minValue = Number(this.args[2]),
            maxValue = Number(this.args[3]),
            stepValue = Number(this.args[4]),
            autofocus = this.args.length > 5 && "autofocus" === this.args[5];
        if (Number.isNaN(defValue) || !Number.isFinite(defValue)) return this.error("default value (" + this.args[1] + ") is not a number");
        if (Number.isNaN(minValue) || !Number.isFinite(minValue)) return this.error("min value (" + this.args[2] + ") is not a number");
        if (Number.isNaN(maxValue) || !Number.isFinite(maxValue)) return this.error("max value (" + this.args[3] + ") is not a number");
        if (Number.isNaN(stepValue) || !Number.isFinite(stepValue) || stepValue <= 0) return this.error("step value (" + this.args[4] + ") is not a number greater than zero");
        if (defValue < minValue) return this.error("default value (" + this.args[1] + ") is less than min value (" + this.args[2] + ")");
        if (defValue > maxValue) return this.error("default value (" + this.args[1] + ") is greater than max value (" + this.args[3] + ")");
        var fracDigits = function() {
            var str = String(stepValue),
                pos = str.lastIndexOf(".");
            return pos === -1 ? 0 : str.length - pos - 1
        }();
        if (stepValidate(maxValue) !== maxValue) return this.error("max value (" + this.args[3] + ") is not a multiple of the step value (" + this.args[4] + ") plus the min value (" + this.args[2] + ")");
        var pool = function() {
            var parent = _this2.contextSelect(function(ctx) {
                return "numberpool" === ctx.name
            });
            return null !== parent && parent.hasOwnProperty("pool") ? parent.pool : null
        }();
        Config.debug && this.debugView.modes({
            block: !0
        });
        var $elControl = jQuery(document.createElement("div")),
            $elInput = jQuery(document.createElement("input")),
            $elValue = void 0,
            showValue = void 0;
        $elControl.attr("id", this.name + "-body-" + varId).addClass("macro-" + this.name).appendTo(this.output), $elInput.attr({
            id: this.name + "-input-" + varId,
            name: this.name + "-input-" + varId,
            type: "range",
            min: minValue,
            max: maxValue,
            step: stepValue,
            tabindex: 0
        }).on("change input." + Util.slugify(this.name), function() {
            validateAndApply(this), "function" == typeof showValue && showValue()
        }).on("keypress", function(ev) {
            13 === ev.which && (ev.preventDefault(), $elInput.trigger("change"))
        }).appendTo($elControl), !Browser.isIE || Browser.ieVersion > 9 ? ($elValue = jQuery(document.createElement("span")).attr("id", this.name + "-value-" + varId).appendTo($elControl), showValue = function() {
            $elValue.text(Number($elInput.val()).toFixed(fracDigits))
        }) : $elInput.off("input." + Util.slugify(this.name)), $elInput.val(defValue), validateAndApply($elInput[0]), "function" == typeof showValue && showValue(), autofocus && ($elInput.attr("autofocus", "autofocus"), postdisplay["#autofocus:" + $elInput.attr("id")] = function(task) {
            delete postdisplay[task], setTimeout(function() {
                return $elInput.focus()
            }, Engine.minDomActionDelay)
        })
    }
});


code:
import Overworld from "./Overworld";

export default [{
    map: Overworld,
    mapID: 'overworld',
    default: true
}];


code:
import {checkForDaylightExposure} from "../Game/PlayerStates";

export default {
    background: 'img/map_placeholders/map_placeholder.png',
    locations: [{
        id: 'domus_street',
        passage: 'Domus Street',
        timePass: 5,
        x: 35,
        y: 118,
        name: 'Domus',
        prefix: 'Street',
        suffix: '',
        sprite: 'img/map_placeholders/building_placeholder.png',
        light: 'img/map_placeholders/placeholder_light.png',
        canBeVisited: () => !checkForDaylightExposure(),
        links: [
            'barb_street',
            'danube_street',
            'residential_alleyways'
        ]
    }, {
        id: 'barb_street',
        passage: 'Barb Street',
        timePass: 5,
        x: 135,
        y: 30,
        name: 'Barb',
        prefix: 'Street',
        suffix: '',
        sprite: 'img/map_placeholders/building_placeholder.png',
        light: 'img/map_placeholders/placeholder_light.png',
        canBeVisited: () => !checkForDaylightExposure(),
        links: [
            'domus_street',
            'connudatus_street',
            'residential_alleyways'
        ],
        active: {
            x: 15,
            y: 15,
            width: 15,
            height: 15
        }
    }, {
        id: 'residential_alleyways',
        passage: 'Residential alleyways',
        timePass: 5,
        x: 115,
        y: 110,
        name: 'Residential Alleyways',
        prefix: '',
        sprite: 'img/map_placeholders/building_placeholder.png',
        light: 'img/map_placeholders/placeholder_light.png',
        links: [
            'domus_street',
            'barb_street',
            'danube_street',
            'connudatus_street'
        ]
    }, {
        id: 'danube_street',
        passage: 'Danube Street',
        timePass: 5,
        x: 137,
        y: 207,
        name: 'Danube',
        prefix: 'Street',
        suffix: '',
        sprite: 'img/map_placeholders/building_placeholder.png',
        light: 'img/map_placeholders/placeholder_light.png',
        canBeVisited: () => !checkForDaylightExposure(),
        links: [
            'domus_street',
            'connudatus_street',
            'residential_alleyways'
        ]
    }, {
        id: 'connudatus_street',
        passage: 'Connudatus Street',
        timePass: 5,
        x: 210,
        y: 100,
        name: 'Connudatus',
        prefix: 'Street',
        suffix: '',
        sprite: 'img/map_placeholders/building_placeholder.png',
        light: 'img/map_placeholders/placeholder_light.png',
        canBeVisited: () => !checkForDaylightExposure(),
        links: [
            'barb_street',
            'danube_street',
            'residential_alleyways'
        ]
    }] /* First cluster of 5 */
};


code:
export const GameVersion = '1.26.1';

// Save update function
export default (variables) => {

};

export const GameState = {
    settings: {
        text_only: false, // $textonly
        enable_images: true, // $images
        debug: true, // $debug
        numberify: true, // $numberify_enable
        devmode: false, // $dev
        gamemode: "normal", /// $gamemode

        intro: true, // $intro
        tutorial: false, // $tutorial

        content: {
            // content toggles here
        }
    },

    player: {
        skills: {
            seduction: 0,
            vaginal: 0,
            penile: 0,
            anal: 0,
            oral: 0,
            hand: 0,
            feet: 0,
            chest: 0,
            thigh: 0,
            bottom: 0,
        },
        stats: {
            control: {
                max: 1000, // $controlmax
                current: 1000 // $control
            },
            trauma: {
                max: 5000, //$traumamax
                current: 0 // $trauma
            },
            stress: {
                max: 10010, // $stressmax
                current: 0 // $stress
            },
            physique: {
                max: 20000, // $physiquemax
                current: 3500 // $physique
            },
            arousal: {
                max: 10000, // $arousalmax
                current: 0 // $arousal ?
            },
            pain: {
                max: 1000, // $painmax ?
                current: 0 // $pain
            },
            fatigue: {
                max: 2000, // $tirednessmax
                current: 0 // $tiredness
            },
            beauty: {
                max: 10000, // $beautymax
                current: 100 // $beauty
            }
        },
        special_stats: {
            purity: 1000, // $purity
            submissive: 1000, // $submissive
            assertive: 0, // $assertive
            assertive_action: "trauma", // $assertiveaction
            awareness: {
                current: 0, // $awareness
                level: 0 // $awarelevel
            },
            fame: 0, // $fame
            fame_exhibitionism: 0, // $fameexhibitionism
            fame_prostitution: 0, // $fameprostitution
            fame_bestiality: 0, // $famebestiality
            fame_sex: 0, // $famesex
            fame_rape: 0, // $famerape
            fame_good: 0, // $famegood
            fame_business: 0, // $famebusiness
            fame_park: 0, // $famepark

            transformation: {
                wolf: {
                    build: 0, // $wolfbuild
                    girl: false // $wolfgirl
                }
            },

            oxygen: {
                max: 1200, // $oxygenmax
                current: 1200 // $oxygen
            }
        },
        possesions: {
            money: 500, // $money
            items: {
                clothing: {

                }
            }
        },
        looks: {
            development_level: 0, // $devlevel
            gender_appearance: '', // $playergenderappearance

            hair: {
                length: 200, // $hairlength
                color: '', // $haircolor
            }
        },
        school: {
            deliquency: 10, /// $deliquency

            cool: 120, // $cool
            cool_max: 400, // $coolmax

            school: 800, // $school

            math: 200, // $maths
            english: 200, // $english
            science: 200, // $science
            history: 200 // $history
        },
        data: {
            birth_month: "september", // $birthmonth
            birth_day: 3, // $birthday
            name: "It's you.",
            gender: 'f', // $playergender
            background: 'waif', // $background
            breast_size: '', // $breastsize
        }
    },

    location: {
        time: 420, // $time
        day: 0, // $days
        week_day: 1, // $weekday
        month: "september", // $month
        month_day: 4, // $monthday
        year: 2018, // $year
        map_id: 'overworld'
    },

    state: {
        combat: false, // $combat
        skill_level_up: [], // contains the name of the skill that leveled up so things can display after combat

        water: false, // if in water - $water
        underwater_time: 0, // $underwatertime
        underwater: 0, // if underwater - $underwater

        player: {
            mind: {
                /*Disables you if 1.*/
                panic_paralysis: false,
                panic_violence: false,
                trance: false,
                /*Builds during consensual, provides benefit at end.*/
                assertive: false,
                /*Set to 1 if NPC is successfully asked not to go ham on the specified body part.*/
                no_vaginal: false,
                no_anal: false,
                no_penile: false,
                /*Trauma and stress at encounter's start.*/
                trauma_saved: 0,
                stress_saved: 0,
                /*Trauma and stress gained during encounter.*/
                trauma_gain: 0,
                stress_gain: 0,
            },

            body: {
                /*Set to a string indicating which body part it is occupied by, such as "penis" or "lefthand"*/
                vagina_use: 0,
                penis_use: 0,
                mouth_use: 0,
                anus_use: 0,
                thigh_use: 0,
                bottom_use: 0,
                feet_use: 0,
                left_arm: 0,
                right_arm: 0,
                chest_use: 0,
                head: 0,
                left_let: 0,
                right_leg: 0,
                breast_use: 0,
                left_nipple: 0,
                right_nipple: 0,
                /*Set to a string indicating both which body part it is occupied by, and the type of "hold" that body part has on in. Such as "anusentrance" or "anusimminent"*/
                vagina_state: 0,
                penis_state: 0,
                anus_state: 0,
                mouth_state: 0,
                left_arm_state: 0,
                right_arm_state: 0,
                feet_state: 0,
                /*More stuff I hope is self-explanatory*/
                penis_fucked: false,
                vagina_fucked: false,
                pull_away: false,
                orgasm_current: 0,
                water_wash: 0,
            }
        },

        encounter: {
            state: {
                /*Makes actions easier.*/
                enemy_trust: 0,
                /*Encounter ends if this reaches 0.*/
                enemy_health: 0,
                enemy_health_max: 0,
                /*Encounter ends if this reaches max.*/
                enemy_arousal: 0,
                enemy_arousal_max: 0,
                /*Impacts NPC behaviour during encounters.*/
                enemy_anger: 0,
                enemy_anger_max: 0,
            },

            audience: {
                /*This is the audience for regular encounters, and is separate to dance audiences.*/
                /*What NPCs are in the audience.*/
                audience_camera: [
                    // description of the person
                ],/*audience_camera_2 - 6 too*/
                /*Forces all the audience to be boys.*/
                audience_force_boy: false,
                /*Forces all the audience to be girls.*/
                audience_force_girl: false,
            }
        }
    },

    playthrough_stats: {
        rape: 0, // $rapestat
        beast_rape: 0, // $beastrapestat
        tentacle_rape: 0, // $tentaclerapestat
        molested: 0, // $moleststat

        vaginal: 0, // $vaginalstat
        vaginal_ejac: 0, // $vaginalejacstat
        vaginal_entrance_ejac: 0, // $vaginalentranceejacstat
        anal: 0, // $analstat
        anal_ejac: 0, // $analejacstat
        oral: 0, // $oralstat
        oral_ejac: 0, // $oralejacstat
        hand: 0, // $ohandstat
        hand_ejac: 0, // $handejacstat
        feet: 0, // $feetstat
        feet_ejac: 0, // $feetejacstat
        thigh: 0, // $thighstat
        thigh_ejac: 0, // $thighejacstat
        bottom: 0, // $bottomstat
        bottom_ejac: 0, // $bottomejacstat
        penile: 0, // $penilestat
        penile_ejac: 0, // $penileejacstat
        face_ejac: 0, // $faceejacstat
        chest: 0, // $cheststat
        chest_ejac: 0, // $chestejacstat
        hair_ejac: 0, // $hairyejacstat
        tummy_ejac: 0, // $tummyejacstat
        neck_ejac: 0, // $neckejacstat
        ejac: 0, // $ejacstat
        orgasm: 0, // $orgasmstat

        clothes_stripped: 0, // $clothesstripstat
        clothes_ruined: 0, // $clothesruinstat

        hit: 0, // $hitstat
        attack: 0, // $attackstat

        prostitution: 0, // $prostitutionstat
        forced_prostitution: 0, // $forcedprostitutionstat

        tables_served: 0, // $tablesservedstat
        parasite: 0, // $parasitestat
        pass_out: 0, // $passoutstat

        masturbation: 0, // $masturbationstat
        masturbation_orgasm: 0, // $masturbationorgasmstat
        masturbation_time: 0, // $masturbationtimestat

        dance: 0, // $dancestat
        pull_away: 0, // $pullaway

        no_vaginal: 0, // $novaginal
        no_anal: 0, // $noanal
        no_penile: 0, // $nopenile

        vaginal_chastity: 0, // $vaginalchastity
        anal_chastity: 0, // $analchastity
        penile_chastity: 0, // $penilechastity
        drinks_served: 0, // $drinksservedstat
    }
};

export const NpcShared = {
    state: {
        npc: null, // npc name
        type: null, // npc type "man", "beast", "swarm", "parasite", "tentacle"
        strength: 0, // unused for now
    },
    specific_speech: {
        /*Speech variables that disappear after the current NPC's turn, meaning other NPCs won't use them.*/
        /* I don't even WANNA touch this shit */
        speech_orgasm_weak_cum_count: 0,
        speech_orgasm_no_cum_count: 0,
        speech_orgasm_count: 0,
        speech_orgasm_repeat: 0,
        speech_crossdress_angry: 0,
        speech_crossdress_aroused: 0,
        speech_crosdress_shock: 0,
        speech_crossdress_disappointed: 0,
        speech_cum: 0,
        speech_penis_penetrated: 0,
        speech_vagina_penetrated: 0,
        speech_anus_penetrated: 0,
        speech_mouth_penetrated: 0,
        speech_other_anus_penetrated: 0,
        speech_vagina_imminent: 0,
        speech_penis_imminent: 0,
        speech_anus_imminent: 0,
        speech_mouth_imminent: 0,
        speech_other_anus_imminent: 0,
        speech_vagina_entrance: 0,
        speech_penis_entrance: 0,
        speech_anus_entrance: 0,
        speech_mouth_entrance: 0,
        speech_other_anus_entrance: 0,
        speech_vagina_withhold: 0,
        speech_anus_withhold: 0,
        speech_penis_withold: 0,
        speech_other_anus_withold: 0,
        speech_vagina: 0,
        speech_penis: 0,
        speech_anus: 0,
        speech_vagina_mouth: 0,
        speech_vagina_vagina: 0,
        speech_beat: 0,
        speech_hit: 0,
        speech_throat: 0,
        speech_vagina_foot: 0,
        speech_penis_foot: 0,
        speech_chastity: 0,
        speech_struggle: 0,
        speech_strip_struggle: 0,
        speech_spank: 0,
        speech_arms: 0,
        speech_clit: 0,
        speech_glans: 0,
        speech_bottom: 0,
        speech_hair: 0,
        speech_chest_rub: 0,
        speech_breast_rub: 0,
        speech_vagina_flaunt: 0,
        speech_vagina_virgin: 0,
        speech_anus_virgin: 0,
        speech_mouth_virgin: 0,
        speech_penis_virgin: 0,
        speech_penis_escape: 0,
        speech_vagina_escape: 0,
        speech_anus_escape: 0,
    }
};

export const NpcHuman = {
    state: {
        type: "man",
    },
    person: {
        /*These all have five additional versions, the same but with a number on the end, 2 - 6. One for each NPC "slot" in scenes and combat. Note that the first instance sometimes has the number 1 on the end, and sometimes does not.*/
        /*Controls correct grammar and capitalisation during encounters.*/
        intro: false,
        /*What their body parts are occupied by. Note this is different from, but will impact, the actions they take.*/
        lefthand: false,
        righthand: false,
        penis: false,
        vagina: false,
        mouth: false,
        /*NPC gender, pronouns and description, like "muscular" or "thin".*/
        gender: 'f',
        pronoun: 'thin',
        description: null,
    }
};

export const NpcBeast = {
    state: {
        type: "beast"
    },
    beast: {
        /*How many beasts are waiting their turn, or having their turn.*/
        beast_no: 0,
        /*How many beasts in the encounter total.*/
        beast_nomax: 0,
        /*Type of beast. Dog, wolf etc.*/
        beast_name: "none",
        /*If they have claws.*/
        claws: 0,
        /*Currently active beast's gender and pronouns.*/
        data: [/*{
            gender: 'f', // beastgender
            pronoun: 'x' // beastpronoun
        }*/]
    }
};

export const NpcSwarm = {
    state: {
        type: "swarm"
    },
    swarm: {
        swarm: [],/*Also swarm2, swarm3...up to swarm10*/
        swarm_pending: 0,
        /*Set at start of encounter*/
        swarm_steady: 0,
        swarm_Steady: 0,
        swarm_name: 0,
        swarm_move: 0,
        swarm_active: 0,
        swarm_creature: 0,
        swarm_count: 0,
        /*I tried something different with the swarms, having each action they could take associated with a variable, which would then be used to output text elsewhere*/
        swarm_chest_molest: 0,
        swarm_chest_grab: 0,
        swarm_chest_grab_intro: 0,
        swarm_chest_grab_clothes: 0,
        swarm_chest_clothed: 0,
        swarm_chest_covered: 0,
        swarm_activate: 0,
        swarm_spill: 0,
        swarm_back: 0,
        swarm_back_molest: 0,
        swarm_back_grab: 0,
        swarm_back_grab_intro: 0,
        swarm_back_grab_under_clothed: 0,
        swarm_back_under_clothed: 0,
        swarm_back_grab_lower_clothed: 0,
        swarm_back_lower_clothed: 0,
        swarm_back_cover: 0,
        swarm_back_inside: 0,
        swarm_back_inside_intro: 0,
        swarm_back_grab_lower_chastity: 0,
        swarm_front: 0,
        swarm_front_molest: 0,
        swarm_front_grab: 0,
        swarm_front_grab_intro: 0,
        swarm_front_grab_under_clothed: 0,
        swarm_front_under_clothed: 0,
        swarm_front_grab_lower_clothed: 0,
        swarm_front_lower_clothed: 0,
        swarm_front_cover: 0,
        swarm_front_inside: 0,
        swarm_front_inside_intro: 0,
        swarm_front_grab_lower_chastity: 0,
        front: 0,
        back: 0,
        chest: 0,
    }
};

export const NpcVore = {
    state: {
        type: "swarm"
    },
    vore: {
        /*Set at encounter's start.*/
        vore_strength: 0,
        /*How hard you struggle.*/
        vore_struggle: 0,
        /*If the encounter has tentacles.*/
        vore_tentacles: false,
        /*What part of the beast's digestive system you're in.*/
        vore_stage: 0,
        /*Name of creature.*/
        vore_creature: null,
        /*Set to 1 if swallowed, reset at end of encounter.*/
        swallowed: false,

    }
};

export const NpcTentacles = {
    state: {
        type: "tentacles"
    },
    tentacles: {
        /*Set at encounter's start*/
        /*Total number of tentacles.*/
        tentacle_no: 0,
        /*Number of active tentacles.*/
        active_tentacle_no: 0,
        /*How much health each tentacle has. Set at start.*/
        tentacle_health: 0,
        /*There alternative versions of the following, with the number 1 replaced with 2 - 16, covering each possible tentacle*/
        /*What each tentacle is doing.*/
        tentacle: [/*{
            description: null,
            shaft: false,
            head: false,
            health: 0
        }*/],
    }
};


code:
import Migration from "./Versions";
import Game from "../Game/Game";

Config.saves.onLoad = (save) => {
    let saveGameVersion = save.state.history[save.state.history.length-1].variables._gameVersion;
    if (typeof saveGameVersion === "undefined")
        saveGameVersion = '1.26.1'; // any saves before this need to be handled via the old game version

    if (saveGameVersion !== Game.getGameVersion()) {
        console.log(`Trying to update game save from ${saveGameVersion} to ${Game.getGameVersion()}`);

        while (true) {
            const major = saveGameVersion.split('.')[0];
            const minor = saveGameVersion.split('.')[1];
            const patch = saveGameVersion.split('.')[2];

            if (typeof Migration[major] === "undefined")
                break;

            if (typeof Migration[major][minor] === "undefined")
                break;

            if (typeof Migration[major][minor][patch] === "undefined")
                break;

            saveGameVersion = Migration[major][minor][patch](save.state.history[save.state.history.length-1].variables);
            if (saveGameVersion === Game.getGameVersion())
                break; // on current version
        }

        save.state.history[save.state.history.length-1].variables._gameVersion = saveGameVersion;

        if (saveGameVersion !== Game.getGameVersion())
            console.warn(`Reported game save version is ${saveGameVersion}, while the game version is ${Game.getGameVersion()}, some errors can occur.`);
    } // no need to update when version matches already boi
};


code:
import V1_26_1 from "./1/26/1"

export default {
    '1': {
        '26': {
            '1': V1_26_1
        }
    }
};

// current game data for new saves here
export {GameState, GameVersion, NpcShared, NpcHuman, NpcBeast, NpcSwarm, NpcTentacles, NpcVore} from "./1/26/1";


code:
import Game from "./Game/Game";

const instance = new Game();


description: App for degrees-of-lewdity

build (dev): webpack

build: webpack --env.mode=production

compile: cd .. && compile.bat

license: SEE LICENSE IN LICENSE.md


code:
const path = require('path');
const LodashModuleReplacementPlugin = require('lodash-webpack-plugin');

module.exports = (env) => {
    const webpackMode = (typeof env === "undefined" ? 'development' : (
        typeof env.mode === "string" ? env.mode : 'development'
    ));

    let options = {
        mode: webpackMode,
        entry: [
            'babel-polyfill',
            './index.js'
        ],
        output: {
            path: path.resolve(__dirname, '../game'),
            filename: 'base.js'
        },
        module: {
            rules: [{
                test: /\.m?js$/,
                exclude: /(node_modules|bower_components)/,
                use: {
                    loader: 'babel-loader',
                    options: {
                        presets: ['@babel/preset-env'],
                        plugins: [
                            '@babel/plugin-proposal-object-rest-spread',
                            '@babel/plugin-proposal-class-properties',
                            'lodash'
                        ]
                    }
                }
            }]
        },
        plugins: [
            new LodashModuleReplacementPlugin()
        ]
    };

    if (webpackMode === 'development')
        options['devtool'] = 'inline-source-map';

    return options;
};


code:
// Settings
$textonly $settings.text_only
$images $settings.enable_images
$debug $settings.debug
$numberify_enable $settings.numberify
$dev $settings.devmode
$gamemode $settings.gamemode

// Initial settings
$intro $settings.intro
$tutorial $settings.tutorial

// Location / time
$time $location.time
$days $location.day
$weekday $location.week_day
$month $location.month
$monthday $location.month_day
$year $location.year

// Player looks
$hairlength $player.looks.hair.length
$playergenderappearance $player.looks.gender_appearance
$haircolor $player.looks.hair.color

// Player information
$playergender $player.data.gender
$background $player.data.background
$birthmonth $player.data.birth_month
$birthday $player.data.birth_day
$breastsize $player.data.breast_size

// Stats
$controlmax $player.stats.control.max
$control $player.stats.control.current
$traumamax $player.stats.trauma.max
$trauma $player.stats.trauma.current
$stressmax $player.stats.stress.max
$stress $player.stats.stress.current
$physiquemax $player.stats.physique.max
$physique $player.stats.physique.current
$pain $player.stats.pain.current
$tirednessmax $player.stats.fatigue.max
$tiredness $player.stats.fatigue.current
$beautymax $player.stats.beauty.max
$beauty $player.stats.beauty.current

// Special stats
$purity $player.special_stats.purity
$submissive $player.special_stats.submissive
$assertive $player.special_stats.assertive
$assertiveaction $player.special_stats.assertive_action
$awareness $player.special_stats.awareness.current
$awarelevel $player.special_stats.awareness.level
$fame $player.special_stats.fame
$fameexhibitionism $player.special_stats.fame_exhibitionism
$fameprostitution $player.special_stats.fame_prostitution
$famebestiality $player.special_stats.fame_bestiality
$famesex $player.special_stats.fame_sex
$famerape $player.special_stats.fame_rape
$famegood $player.special_stats.fame_good
$famebusiness $player.special_stats.fame_business
$famepark $player.special_stats.fame_park

$oxygenmax $player.special_stats.oxygen.max
$oxygen $player.special_stats.oxygen.current

// Transformations
$wolfbuild $player.special_stats.transformation.wolf.build
$wolfgirl $player.special_stats.transformation.wolf.girl


code:
# Copy this file to .env and fill in the values you wish to change. Most already
# have sensible defaults.  See config.ts for more details.

# PORT=7860
# SERVER_TITLE=Coom Tunnel
# MODEL_RATE_LIMIT=4
# MAX_OUTPUT_TOKENS=300
# LOG_LEVEL=info
# REJECT_DISALLOWED=false
# REJECT_MESSAGE="This content violates /aicg/'s acceptable use policy."
# CHECK_KEYS=true
# QUOTA_DISPLAY_MODE=full
# QUEUE_MODE=fair
# BLOCKED_ORIGINS=reddit.com,9gag.com
# BLOCK_MESSAGE="You must be over the age of majority in your country to use this service."
# BLOCK_REDIRECT="https://roblox.com/"

# Note: CHECK_KEYS is disabled by default in local development mode, but enabled
# by default in production mode.

# Optional settings for user management. See docs/user-management.md.
# GATEKEEPER=none
# GATEKEEPER_STORE=memory
# MAX_IPS_PER_USER=20

# Optional settings for prompt logging. See docs/logging-sheets.md.
# PROMPT_LOGGING=false

# ------------------------------------------------------------------------------
# The values below are secret -- make sure they are set securely.
# For Huggingface, set them via the Secrets section in your Space's config UI.
# For Render, create a "secret file" called .env using the Environment tab.

# You can add multiple keys by separating them with a comma.
OPENAI_KEY=sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

# You can require a Bearer token for requests when using proxy_token gatekeeper.
# PROXY_KEY=your-secret-key

# You can set an admin key for user management when using user_token gatekeeper.
# ADMIN_KEY=your-very-secret-key

# These are used for various persistence features. Refer to the docs for more
# info.
# FIREBASE_KEY=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
# FIREBASE_RTDB_URL=https://xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.firebaseio.com

# This is only relevant if you want to use the prompt logging feature.
# GOOGLE_SHEETS_SPREADSHEET_ID=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
# GOOGLE_SHEETS_KEY=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

repo_name: Nika/pronyan

license: unknown


code:
*.7z filter=lfs diff=lfs merge=lfs -text
*.arrow filter=lfs diff=lfs merge=lfs -text
*.bin filter=lfs diff=lfs merge=lfs -text
*.bz2 filter=lfs diff=lfs merge=lfs -text
*.ckpt filter=lfs diff=lfs merge=lfs -text
*.ftz filter=lfs diff=lfs merge=lfs -text
*.gz filter=lfs diff=lfs merge=lfs -text
*.h5 filter=lfs diff=lfs merge=lfs -text
*.joblib filter=lfs diff=lfs merge=lfs -text
*.lfs.* filter=lfs diff=lfs merge=lfs -text
*.mlmodel filter=lfs diff=lfs merge=lfs -text
*.model filter=lfs diff=lfs merge=lfs -text
*.msgpack filter=lfs diff=lfs merge=lfs -text
*.npy filter=lfs diff=lfs merge=lfs -text
*.npz filter=lfs diff=lfs merge=lfs -text
*.onnx filter=lfs diff=lfs merge=lfs -text
*.ot filter=lfs diff=lfs merge=lfs -text
*.parquet filter=lfs diff=lfs merge=lfs -text
*.pb filter=lfs diff=lfs merge=lfs -text
*.pickle filter=lfs diff=lfs merge=lfs -text
*.pkl filter=lfs diff=lfs merge=lfs -text
*.pt filter=lfs diff=lfs merge=lfs -text
*.pth filter=lfs diff=lfs merge=lfs -text
*.rar filter=lfs diff=lfs merge=lfs -text
*.safetensors filter=lfs diff=lfs merge=lfs -text
saved_model/**/* filter=lfs diff=lfs merge=lfs -text
*.tar.* filter=lfs diff=lfs merge=lfs -text
*.tflite filter=lfs diff=lfs merge=lfs -text
*.tgz filter=lfs diff=lfs merge=lfs -text
*.wasm filter=lfs diff=lfs merge=lfs -text
*.xz filter=lfs diff=lfs merge=lfs -text
*.zip filter=lfs diff=lfs merge=lfs -text
*.zst filter=lfs diff=lfs merge=lfs -text
*tfevents* filter=lfs diff=lfs merge=lfs -text

path: .gitattributes


code:
.vscode
.env
build
node_modules
greeting.md

path: .gitignore


code:
# OAI Reverse Proxy

Reverse proxy server for the OpenAI (and soon Anthropic) APIs. Forwards text generation requests while rejecting administrative/billing requests. Includes optional rate limiting and prompt filtering to prevent abuse.

### Table of Contents
- [What is this?](#what-is-this)
- [Why?](#why)
- [Usage Instructions](#setup-instructions)
  - [Deploy to Huggingface (Recommended)](#deploy-to-huggingface-recommended)
  - [Deploy to Repl.it (WIP)](#deploy-to-replit-wip)
- [Local Development](#local-development)

## What is this?
If you would like to provide a friend access to an API via keys you own, you can use this to keep your keys safe while still allowing them to generate text with the API. You can also use this if you'd like to build a client-side application which uses the OpenAI or Anthropic APIs, but don't want to build your own backend. You should never embed your real API keys in a client-side application. Instead, you can have your frontend connect to this reverse proxy and forward requests to the downstream service.

This keeps your keys safe and allows you to use the rate limiting and prompt filtering features of the proxy to prevent abuse.

## Why?
OpenAI keys have full account permissions. They can revoke themselves, generate new keys, modify spend quotas, etc. **You absolutely should not share them, post them publicly, nor embed them in client-side applications as they can be easily stolen.**

This proxy only forwards text generation requests to the downstream service and rejects requests which would otherwise modify your account.

---

## Usage Instructions
If you'd like to run your own instance of this proxy, you'll need to deploy it somewhere and configure it with your API keys. A few easy options are provided below, though you can also deploy it to any other service you'd like.

### Deploy to Huggingface (Recommended)
[See here for instructions on how to deploy to a Huggingface Space.](./docs/deploy-huggingface.md)

### Deploy to Render
[See here for instructions on how to deploy to Render.com.](./docs/deploy-render.md)

## Local Development
To run the proxy locally for development or testing, install Node.js >= 18.0.0 and follow the steps below.

1. Clone the repo
2. Install dependencies with `npm install`
3. Create a `.env` file in the root of the project and add your API keys. See the [.env.example](./.env.example) file for an example.
4. Start the server in development mode with `npm run start:dev`.

You can also use `npm run start:dev:tsc` to enable project-wide type checking at the cost of slower startup times. `npm run type-check` can be used to run type checking without starting the server.


code:
FROM node:18-bullseye-slim
RUN apt-get update && \
    apt-get install -y git
RUN git clone https://gitgud.io/khanon/oai-reverse-proxy.git /app
WORKDIR /app
RUN npm install
COPY Dockerfile greeting.md* .env* ./
RUN npm run build
EXPOSE 7860
ENV NODE_ENV=production
CMD [ "npm", "start" ]

path: docker/huggingface/Dockerfile


code:
# syntax = docker/dockerfile:1.2

FROM node:18-bullseye-slim
RUN apt-get update && \
    apt-get install -y curl

# Unlike Huggingface, Render can only deploy straight from a git repo and
# doesn't allow you to create or modify arbitrary files via the web UI.
# To use a greeting file, set `GREETING_URL` to a URL that points to a raw
# text file containing your greeting, such as a GitHub Gist.

# You may need to clear the build cache if you change the greeting, otherwise
# Render will use the cached layer from the previous build.

WORKDIR /app
ARG GREETING_URL
RUN if [ -n "$GREETING_URL" ]; then \
    curl -sL "$GREETING_URL" > greeting.md; \
    fi
COPY package*.json greeting.md* ./
RUN npm install
COPY . .
RUN npm run build
RUN --mount=type=secret,id=_env,dst=/etc/secrets/.env cat /etc/secrets/.env >> .env
EXPOSE 10000
ENV NODE_ENV=production
CMD [ "npm", "start" ]

path: docker/render/Dockerfile


code:
# Deploy to Huggingface Space

This repository can be deployed to a [Huggingface Space](https://huggingface.co/spaces).  This is a free service that allows you to run a simple server in the cloud.  You can use it to safely share your OpenAI API key with a friend.

### 1. Get an API key
- Go to [OpenAI](https://openai.com/) and sign up for an account. You can use a free trial key for this as long as you provide SMS verification.

### 2. Create an empty Huggingface Space
- Go to [Huggingface](https://huggingface.co/) and sign up for an account.
- Once logged in, [create a new Space](https://huggingface.co/new-space).
- Provide a name for your Space and select "Docker" as the SDK.  Select "Blank" for the template.
- Click "Create Space" and wait for the Space to be created.

![Create Space](huggingface-createspace.png)

### 3. Create an empty Dockerfile
- Once your Space is created, you'll see an option to "Create the Dockerfile in your browser".  Click that link.

![Create Dockerfile](huggingface-dockerfile.png)
- Paste the following into the text editor and click "Save".
```dockerfile
FROM node:18-bullseye-slim
RUN apt-get update && \
    apt-get install -y git
RUN git clone https://gitgud.io/khanon/oai-reverse-proxy.git /app
WORKDIR /app
RUN npm install
COPY Dockerfile greeting.md* .env* ./
RUN npm run build
EXPOSE 7860
ENV NODE_ENV=production
CMD [ "npm", "start" ]
```
- Click "Commit new file to `main`" to save the Dockerfile.

![Commit](huggingface-savedockerfile.png)

### 4. Set your OpenAI API key as a secret
- Click the Settings button in the top right corner of your repository.
- Scroll down to the `Repository Secrets` section and click `New Secret`.

![Secrets](https://files.catbox.moe/irrp2p.png)

- Enter `OPENAI_KEY` as the name and your OpenAI API key as the value.

![New Secret](https://files.catbox.moe/ka6s1a.png)

### 5. Deploy the server
- Your server should automatically deploy when you add the secret, but if not you can select `Factory Reboot` from that same Settings menu.

### 6. Share the link
- The Service Info section below should show the URL for your server. You can share this with anyone to safely give them access to your OpenAI API key.
- Your friend doesn't need any OpenAI API key of their own, they just need your link.

# Optional

## Updating the server

To update your server, go to the Settings menu and select `Factory Reboot`.  This will pull the latest version of the code from GitHub and restart the server.

Note that if you just perform a regular Restart, the server will be restarted with the same code that was running before.

## Adding a greeting message

You can create a Markdown file called `greeting.md` to display a message on the Server Info page.  This is a good place to put instructions for how to use the server.

## Customizing the server

The server will be started with some default configuration, but you can override it by adding a `.env` file to your Space.  You can use Huggingface's web editor to create a new `.env` file alongside your Dockerfile. Huggingface will restart your server automatically when you save the file.

Here are some example settings:
```shell
# Requests per minute per IP address
MODEL_RATE_LIMIT=2
# Max tokens to request from OpenAI
MAX_OUTPUT_TOKENS=256
# Block prompts containing disallowed characters
REJECT_DISALLOWED=false
REJECT_MESSAGE="This content violates /aicg/'s acceptable use policy."
```

See `.env.example` for a full list of available settings, or check `config.ts` for details on what each setting does.

## Restricting access to the server

If you want to restrict access to the server, you can set a `PROXY_KEY` secret.  This key will need to be passed in the Authentication header of every request to the server, just like an OpenAI API key.

Add this using the same method as the OPENAI_KEY secret above. Don't add this to your `.env` file because that file is public and anyone can see it.


code:
# Deploy to Render.com
Render.com offers a free tier that includes 750 hours of compute time per month.  This is enough to run a single proxy instance 24/7.  Instances shut down after 15 minutes without traffic but start up again automatically when a request is received.

### 1. Create account
- [Sign up for Render.com](https://render.com/) to create an account and access the dashboard.

### 2. Create a service using a Blueprint
Render allows you to deploy and auutomatically configure a repository containing a [render.yaml](../render.yaml) file using its Blueprints feature.  This is the easiest way to get started.

- Click the **Blueprints** tab at the top of the dashboard.
- Click **New Blueprint Instance**.
- Under **Public Git repository**, enter `https://gitlab.com/khanon/oai-proxy`.
  - Note that this is not the GitGud repository, but a mirror on GitLab.
- Click **Continue**.
- Under **Blueprint Name**, enter a name.
- Under **Branch**, enter `main`.
- Click **Apply**.

The service will be created according to the instructions in the `render.yaml` file.  Don't wait for it to complete as it will fail due to missing environment variables.  Instead, proceed to the next step.

### 3. Set environment variables
- Return to the **Dashboard** tab.
- Click the name of the service you just created, which may show as "Deploy failed".
- Click the **Environment** tab.
- Click **Add Secret File**.
- Under **Filename**, enter `.env`.
- Under **Contents**, enter all of your environment variables, one per line, in the format `NAME=value`.
  - For example, `OPENAI_KEY=sk-abc123`.
- Click **Save Changes**.

The service will automatically rebuild and deploy with the new environment variables.  This will take a few minutes.  The link to your deployed proxy will appear at the top of the page.

If you want to change the URL, go to the **Settings** tab of your Web Service and click the **Edit** button next to **Name**.  You can also set a custom domain, though I haven't tried this yet.

# Optional

## Updating the server

To update your server, go to the page for your Web Service and click **Manual Deploy** > **Deploy latest commit**.  This will pull the latest version of the code and redeploy the server.

_If you have trouble with this, you can also try selecting **Clear build cache & deploy** instead from the same menu._

## Adding a greeting message

To show a greeting message on the Server Info page, set the `GREETING_URL` environment variable within Render to the URL of a Markdown file.  This URL should point to a raw text file, not an HTML page. You can use a public GitHub Gist or GitLab Snippet for this.  For example: `GREETING_URL=https://gitlab.com/-/snippets/2542011/raw/main/greeting.md`.  You can change the title of the page by setting the `SERVER_TITLE` environment variable.

Don't set `GREETING_URL` in the `.env` secret file you created earlier; it must be set in Render's environment variables section for it to work correctly.

## Customizing the server

You can customize the server by editing the `.env` configuration you created earlier. Refer to [.env.example](../.env.example) for a list of all available configuration options. Further information can be found in the [config.ts](../src/config.ts) file.


code:
# Warning
**I strongly suggest against using this feature with a Google account that you care about.** Depending on the content of the prompts people submit, Google may flag the spreadsheet as containing inappropriate content. This seems to prevent you from sharing that spreadsheet _or any others on the account. This happened with my throwaway account during testing; the existing shared spreadsheet continues to work but even completely new spreadsheets are flagged and cannot be shared.

I'll be looking into alternative storage backends but you should not use this implementation with a Google account you care about, or even one remotely connected to your main accounts (as Google has a history of linking accounts together via IPs/browser fingerprinting). Use a VPN and completely isolated VM to be safe.

# Configuring Google Sheets Prompt Logging
This proxy can log incoming prompts and model responses to Google Sheets. Some configuration on the Google side is required to enable this feature. The APIs used are free, but you will need a Google account and a Google Cloud Platform project.

NOTE: Concurrency is not supported. Don't connect two instances of the server to the same spreadsheet or bad things will happen.

## Prerequisites
- A Google account
  - **USE A THROWAWAY ACCOUNT!**
- A Google Cloud Platform project

### 0. Create a Google Cloud Platform Project
_A Google Cloud Platform project is required to enable programmatic access to Google Sheets. If you already have a project, skip to the next step. You can also see the [Google Cloud Platform documentation](https://developers.google.com/workspace/guides/create-project) for more information._

- Go to the Google Cloud Platform Console and [create a new project](https://console.cloud.google.com/projectcreate).

### 1. Enable the Google Sheets API
_The Google Sheets API must be enabled for your project. You can also see the [Google Sheets API documentation](https://developers.google.com/sheets/api/quickstart/nodejs) for more information._

- Go to the [Google Sheets API page](https://console.cloud.google.com/apis/library/sheets.googleapis.com) and click **Enable**, then fill in the form to enable the Google Sheets API for your project.
<!-- TODO: Add screenshot of Enable page and describe filling out the form -->

### 2. Create a Service Account
_A service account is required to authenticate the proxy to Google Sheets._

- Once the Google Sheets API is enabled, click the **Credentials** tab on the Google Sheets API page.
- Click **Create credentials** and select **Service account**.
- Provide a name for the service account and click **Done** (the second and third steps can be skipped).

### 3. Download the Service Account Key
_Once your account is created, you'll need to download the key file and include it in the proxy's secrets configuration._

- Click the Service Account you just created in the list of service accounts for the API.
- Click the **Keys** tab and click **Add key**, then select **Create new key**.
- Select **JSON** as the key type and click **Create**.

The JSON file will be downloaded to your computer.

### 4. Set the Service Account key as a Secret
_The JSON key file must be set as a secret in the proxy's configuration. Because files cannot be included in the secrets configuration, you'll need to base64 encode the file's contents and paste the encoded string as the value of the `GOOGLE_SHEETS_KEY` secret._

- Open the JSON key file in a text editor and copy the contents.
- Visit the [base64 encode/decode tool](https://www.base64encode.org/) and paste the contents into the box, then click **Encode**.
- Copy the encoded string and paste it as the value of the `GOOGLE_SHEETS_KEY` secret in the deployment's secrets configuration.
  - **WARNING:** Don't reveal this string publically. The `.env` file is NOT private -- unless you're running the proxy locally, you should not use it to store secrets!

### 5. Create a new spreadsheet and share it with the service account
_The service account must be given permission to access the logging spreadsheet. Each service account has a unique email address, which can be found in the JSON key file; share the spreadsheet with that email address just as you would share it with another user._

- Open the JSON key file in a text editor and copy the value of the `client_email` field.
- Open the spreadsheet you want to log to, or create a new one, and click **File > Share**.
- Paste the service account's email address into the **Add people or groups** field. Ensure the service account has **Editor** permissions, then click **Done**.

### 6. Set the spreadsheet ID as a Secret
_The spreadsheet ID must be set as a secret in the proxy's configuration. The spreadsheet ID can be found in the URL of the spreadsheet. For example, the spreadsheet ID for `https://docs.google.com/spreadsheets/d/1X2Y3Z/edit#gid=0` is `1X2Y3Z`.  The ID isn't necessarily a sensitive value if you intend for the spreadsheet to be public, but it's still recommended to set it as a secret._

- Copy the spreadsheet ID and paste it as the value of the `GOOGLE_SHEETS_SPREADSHEET_ID` secret in the deployment's secrets configuration.


code:
# Shat out by GPT-4, I did not check for correctness beyond a cursory glance
openapi: 3.0.0
info:
  version: 1.0.0
  title: User Management API
paths:
  /admin/users:
    get:
      summary: List all users
      operationId: getUsers
      responses:
        "200":
          description: A list of users
          content:
            application/json:
              schema:
                type: object
                properties:
                  users:
                    type: array
                    items:
                      $ref: "#/components/schemas/User"
                  count:
                    type: integer
                    format: int32
    post:
      summary: Create a new user
      operationId: createUser
      responses:
        "200":
          description: The created user's token
          content:
            application/json:
              schema:
                type: object
                properties:
                  token:
                    type: string
    put:
      summary: Bulk upsert users
      operationId: bulkUpsertUsers
      requestBody:
        content:
          application/json:
            schema:
              type: object
              properties:
                users:
                  type: array
                  items:
                    $ref: "#/components/schemas/User"
      responses:
        "200":
          description: The upserted users
          content:
            application/json:
              schema:
                type: object
                properties:
                  upserted_users:
                    type: array
                    items:
                      $ref: "#/components/schemas/User"
                  count:
                    type: integer
                    format: int32
        "400":
          description: Bad request
          content:
            application/json:
              schema:
                type: object
                properties:
                  error:
                    type: string

  /admin/users/{token}:
    get:
      summary: Get a user by token
      operationId: getUser
      parameters:
        - name: token
          in: path
          required: true
          schema:
            type: string
      responses:
        "200":
          description: A user
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/User"
        "404":
          description: Not found
          content:
            application/json:
              schema:
                type: object
                properties:
                  error:
                    type: string
    put:
      summary: Update a user by token
      operationId: upsertUser
      parameters:
        - name: token
          in: path
          required: true
          schema:
            type: string
      requestBody:
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/User"
      responses:
        "200":
          description: The updated user
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/User"
        "400":
          description: Bad request
          content:
            application/json:
              schema:
                type: object
                properties:
                  error:
                    type: string
    delete:
      summary: Disables the user with the given token
      description: Optionally accepts a `disabledReason` query parameter. Returns the disabled user.
      parameters:
        - in: path
          name: token
          required: true
          schema:
            type: string
          description: The token of the user to disable
        - in: query
          name: disabledReason
          required: false
          schema:
            type: string
          description: The reason for disabling the user
      responses:
        '200':
          description: The disabled user
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/User'
        '400':
          description: Bad request
          content:
            application/json:
              schema:
                type: object
                properties:
                  error:
                    type: string
        '404':
          description: Not found
          content:
            application/json:
              schema:
                type: object
                properties:
                  error:
                    type: string
components:
  schemas:
    User:
      type: object
      properties:
        token:
          type: string
        ip:
          type: array
          items:
            type: string
        type:
          type: string
          enum: ["normal", "special"]
        promptCount:
          type: integer
          format: int32
        tokenCount:
          type: integer
          format: int32
        createdAt:
          type: integer
          format: int64
        lastUsedAt:
          type: integer
          format: int64
        disabledAt:
          type: integer
          format: int64
        disabledReason:
          type: string


code:
# User Management

The proxy supports several different user management strategies.  You can choose the one that best fits your needs by setting the `GATEKEEPER` environment variable.

Several of these features require you to set secrets in your environment.  If using Huggingface Spaces to deploy, do not set these in your `.env` file because that file is public and anyone can see it.

## Table of Contents
- [No user management](#no-user-management-gatekeepernone)
- [Single-password authentication](#single-password-authentication-gatekeeperproxy_key)
- [Per-user authentication](#per-user-authentication-gatekeeperuser_token)
  - [Memory](#memory)
  - [Firebase Realtime Database](#firebase-realtime-database)
    - [Firebase setup instructions](#firebase-setup-instructions)

## No user management (`GATEKEEPER=none`)

This is the default mode. The proxy will not require any authentication to access the server and offers basic IP-based rate limiting and anti-abuse features.

## Single-password authentication (`GATEKEEPER=proxy_key`)

This mode allows you to set a password that must be passed in the `Authentication` header of every request to the server as a bearer token.  This is useful if you want to restrict access to the server, but don't want to create a separate account for every user.

To set the password, create a `PROXY_KEY` secret in your environment.

## Per-user authentication (`GATEKEEPER=user_token`)

This mode allows you to provision separate Bearer tokens for each user. You can manage users via the /admin/users REST API, which itself requires an admin Bearer token.

To begin, set `ADMIN_KEY` to a secret value.  This will be used to authenticate requests to the /admin/users REST API.

[You can find an OpenAPI specification for the /admin/users REST API here.](openapi-admin-users.yaml)

By default, the proxy will store user data in memory. Naturally, this means that user data will be lost when the proxy is restarted, though you can use the bulk user import/export feature to save and restore user data manually or via a script. However, the proxy also supports persisting user data to an external data store with some additional configuration.

Below are the supported data stores and their configuration options.

### Memory

This is the default data store (`GATEKEEPER_STORE=memory`)  User data will be stored in memory and will be lost when the proxy is restarted. You are responsible for downloading and re-uploading user data via the REST API if you want to persist it.

### Firebase Realtime Database

To use Firebase Realtime Database to persist user data, set the following environment variables:
- `GATEKEEPER_STORE`: Set this to `firebase_rtdb`
- **Secret** `FIREBASE_RTDB_URL`: The URL of your Firebase Realtime Database, e.g. `https://my-project-default-rtdb.firebaseio.com`
- **Secret** `FIREBASE_KEY`: A base-64 encoded service account key for your Firebase project. Refer to the instructions below for how to create this key.

**Firebase setup instructions**

1. Go to the [Firebase console](https://console.firebase.google.com/) and click "Add project", then follow the prompts to create a new project.
2. From the **Project Overview** page, click **All products** in the left sidebar, then click **Realtime Database**.
3. Click **Create database** and choose **Start in test mode**.  Click **Enable**.
    - Test mode is fine for this use case as it still requires authentication to access the database. You may wish to set up more restrictive rules if you plan to use the database for other purposes.
    - The reference URL for the database will be displayed on the page. You will need this later.
4. Click the gear icon next to **Project Overview** in the left sidebar, then click **Project settings**.
5. Click the **Service accounts** tab, then click **Generate new private key**.
6. The downloaded file contains your key. Encode it as base64 and set it as the `FIREBASE_KEY` secret in your environment.
7. Set `FIREBASE_RTDB_URL` to the reference URL of your Firebase Realtime Database, e.g. `https://my-project-default-rtdb.firebaseio.com`.
8. Set `GATEKEEPER_STORE` to `firebase_rtdb` in your environment if you haven't already.

The proxy will attempt to connect to your Firebase Realtime Database at startup and will throw an error if it cannot connect.  If you see this error, check that your `FIREBASE_RTDB_URL` and `FIREBASE_KEY` secrets are set correctly.

---

Users are loaded from the database and changes are flushed periodically.  You can use the PUT /admin/users API to bulk import users and force a flush to the database.


oai-reverse-proxy

license: MIT

acorn: bin/acorn

type: github

type: patreon

type: consulting

type: individual

type: opencollective

esbuild: bin/esbuild

pbjs: bin/pbjs

pbts: bin/pbts

semver: bin/semver

tsc: bin/tsc

tsserver: bin/tsserver

uglifyjs: bin/uglifyjs


description: Reverse proxy for the OpenAI API

build:watch: esbuild src/server.ts --outfile=build/server.js --platform=node --target=es2020 --format=cjs --bundle --sourcemap --watch

build: tsc

start:dev: concurrently "npm run build:watch" "npm run start:watch"

start:dev:tsc: nodemon --watch src --exec ts-node src/server.ts

start:watch: nodemon --require source-map-support/register build/server.js

start:replit: tsc && node build/server.js

start: node build/server.js

type-check: tsc --noEmit


code:
services:
  - type: web
    name: oai-proxy
    env: docker
    repo: https://gitlab.com/khanon/oai-proxy.git
    region: oregon
    plan: free
    branch: main
    healthCheckPath: /health
    dockerfilePath: ./docker/render/Dockerfile


code:
import { RequestHandler, Router } from "express";
import { config } from "../config";
import { usersRouter } from "./users";

const ADMIN_KEY = config.adminKey;
const failedAttempts = new Map<string, number>();

const adminRouter = Router();

const auth: RequestHandler = (req, res, next) => {
  const token = req.headers.authorization?.slice("Bearer ".length);
  const attempts = failedAttempts.get(req.ip) ?? 0;
  if (attempts > 5) {
    req.log.warn(
      { ip: req.ip, token },
      `Blocked request to admin API due to too many failed attempts`
    );
    return res.status(401).json({ error: "Too many attempts" });
  }

  if (token !== ADMIN_KEY) {
    const newAttempts = attempts + 1;
    failedAttempts.set(req.ip, newAttempts);
    req.log.warn(
      { ip: req.ip, attempts: newAttempts, token },
      `Attempted admin API request with invalid token`
    );
    return res.status(401).json({ error: "Unauthorized" });
  }

  next();
};

adminRouter.use(auth);
adminRouter.use("/users", usersRouter);
export { adminRouter };