Current section
Files
Jump to
Current section
Files
priv/ssr_server.cjs
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __copyProps = (to, from2, except, desc) => {
if (from2 && typeof from2 === "object" || typeof from2 === "function") {
for (let key of __getOwnPropNames(from2))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from2[key], enumerable: !(desc = __getOwnPropDesc(from2, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
// build/dev/javascript/prelude.mjs
var CustomType = class {
withFields(fields) {
let properties = Object.keys(this).map(
(label) => label in fields ? fields[label] : this[label]
);
return new this.constructor(...properties);
}
};
var List = class {
static fromArray(array3, tail) {
let t = tail || new Empty();
for (let i = array3.length - 1; i >= 0; --i) {
t = new NonEmpty(array3[i], t);
}
return t;
}
[Symbol.iterator]() {
return new ListIterator(this);
}
toArray() {
return [...this];
}
atLeastLength(desired) {
let current = this;
while (desired-- > 0 && current) current = current.tail;
return current !== void 0;
}
hasLength(desired) {
let current = this;
while (desired-- > 0 && current) current = current.tail;
return desired === -1 && current instanceof Empty;
}
countLength() {
let current = this;
let length3 = 0;
while (current) {
current = current.tail;
length3++;
}
return length3 - 1;
}
};
function prepend(element, tail) {
return new NonEmpty(element, tail);
}
function toList(elements, tail) {
return List.fromArray(elements, tail);
}
var ListIterator = class {
#current;
constructor(current) {
this.#current = current;
}
next() {
if (this.#current instanceof Empty) {
return { done: true };
} else {
let { head, tail } = this.#current;
this.#current = tail;
return { value: head, done: false };
}
}
};
var Empty = class extends List {
};
var List$isEmpty = (value) => value instanceof Empty;
var NonEmpty = class extends List {
constructor(head, tail) {
super();
this.head = head;
this.tail = tail;
}
};
var List$isNonEmpty = (value) => value instanceof NonEmpty;
var List$NonEmpty$first = (value) => value.head;
var List$NonEmpty$rest = (value) => value.tail;
var BitArray = class {
/**
* The size in bits of this bit array's data.
*
* @type {number}
*/
bitSize;
/**
* The size in bytes of this bit array's data. If this bit array doesn't store
* a whole number of bytes then this value is rounded up.
*
* @type {number}
*/
byteSize;
/**
* The number of unused high bits in the first byte of this bit array's
* buffer prior to the start of its data. The value of any unused high bits is
* undefined.
*
* The bit offset will be in the range 0-7.
*
* @type {number}
*/
bitOffset;
/**
* The raw bytes that hold this bit array's data.
*
* If `bitOffset` is not zero then there are unused high bits in the first
* byte of this buffer.
*
* If `bitOffset + bitSize` is not a multiple of 8 then there are unused low
* bits in the last byte of this buffer.
*
* @type {Uint8Array}
*/
rawBuffer;
/**
* Constructs a new bit array from a `Uint8Array`, an optional size in
* bits, and an optional bit offset.
*
* If no bit size is specified it is taken as `buffer.length * 8`, i.e. all
* bytes in the buffer make up the new bit array's data.
*
* If no bit offset is specified it defaults to zero, i.e. there are no unused
* high bits in the first byte of the buffer.
*
* @param {Uint8Array} buffer
* @param {number} [bitSize]
* @param {number} [bitOffset]
*/
constructor(buffer, bitSize, bitOffset) {
if (!(buffer instanceof Uint8Array)) {
throw globalThis.Error(
"BitArray can only be constructed from a Uint8Array"
);
}
this.bitSize = bitSize ?? buffer.length * 8;
this.byteSize = Math.trunc((this.bitSize + 7) / 8);
this.bitOffset = bitOffset ?? 0;
if (this.bitSize < 0) {
throw globalThis.Error(`BitArray bit size is invalid: ${this.bitSize}`);
}
if (this.bitOffset < 0 || this.bitOffset > 7) {
throw globalThis.Error(
`BitArray bit offset is invalid: ${this.bitOffset}`
);
}
if (buffer.length !== Math.trunc((this.bitOffset + this.bitSize + 7) / 8)) {
throw globalThis.Error("BitArray buffer length is invalid");
}
this.rawBuffer = buffer;
}
/**
* Returns a specific byte in this bit array. If the byte index is out of
* range then `undefined` is returned.
*
* When returning the final byte of a bit array with a bit size that's not a
* multiple of 8, the content of the unused low bits are undefined.
*
* @param {number} index
* @returns {number | undefined}
*/
byteAt(index5) {
if (index5 < 0 || index5 >= this.byteSize) {
return void 0;
}
return bitArrayByteAt(this.rawBuffer, this.bitOffset, index5);
}
equals(other) {
if (this.bitSize !== other.bitSize) {
return false;
}
const wholeByteCount = Math.trunc(this.bitSize / 8);
if (this.bitOffset === 0 && other.bitOffset === 0) {
for (let i = 0; i < wholeByteCount; i++) {
if (this.rawBuffer[i] !== other.rawBuffer[i]) {
return false;
}
}
const trailingBitsCount = this.bitSize % 8;
if (trailingBitsCount) {
const unusedLowBitCount = 8 - trailingBitsCount;
if (this.rawBuffer[wholeByteCount] >> unusedLowBitCount !== other.rawBuffer[wholeByteCount] >> unusedLowBitCount) {
return false;
}
}
} else {
for (let i = 0; i < wholeByteCount; i++) {
const a = bitArrayByteAt(this.rawBuffer, this.bitOffset, i);
const b = bitArrayByteAt(other.rawBuffer, other.bitOffset, i);
if (a !== b) {
return false;
}
}
const trailingBitsCount = this.bitSize % 8;
if (trailingBitsCount) {
const a = bitArrayByteAt(
this.rawBuffer,
this.bitOffset,
wholeByteCount
);
const b = bitArrayByteAt(
other.rawBuffer,
other.bitOffset,
wholeByteCount
);
const unusedLowBitCount = 8 - trailingBitsCount;
if (a >> unusedLowBitCount !== b >> unusedLowBitCount) {
return false;
}
}
}
return true;
}
/**
* Returns this bit array's internal buffer.
*
* @deprecated
*
* @returns {Uint8Array}
*/
get buffer() {
if (this.bitOffset !== 0 || this.bitSize % 8 !== 0) {
throw new globalThis.Error(
"BitArray.buffer does not support unaligned bit arrays"
);
}
return this.rawBuffer;
}
/**
* Returns the length in bytes of this bit array's internal buffer.
*
* @deprecated
*
* @returns {number}
*/
get length() {
if (this.bitOffset !== 0 || this.bitSize % 8 !== 0) {
throw new globalThis.Error(
"BitArray.length does not support unaligned bit arrays"
);
}
return this.rawBuffer.length;
}
};
var BitArray$BitArray = (buffer, bitSize, bitOffset) => new BitArray(buffer, bitSize, bitOffset);
function bitArrayByteAt(buffer, bitOffset, index5) {
if (bitOffset === 0) {
return buffer[index5] ?? 0;
} else {
const a = buffer[index5] << bitOffset & 255;
const b = buffer[index5 + 1] >> 8 - bitOffset;
return a | b;
}
}
function bitArraySlice(bitArray, start, end2) {
end2 ??= bitArray.bitSize;
bitArrayValidateRange(bitArray, start, end2);
if (start === end2) {
return new BitArray(new Uint8Array());
}
if (start === 0 && end2 === bitArray.bitSize) {
return bitArray;
}
start += bitArray.bitOffset;
end2 += bitArray.bitOffset;
const startByteIndex = Math.trunc(start / 8);
const endByteIndex = Math.trunc((end2 + 7) / 8);
const byteLength = endByteIndex - startByteIndex;
let buffer;
if (startByteIndex === 0 && byteLength === bitArray.rawBuffer.byteLength) {
buffer = bitArray.rawBuffer;
} else {
buffer = new Uint8Array(
bitArray.rawBuffer.buffer,
bitArray.rawBuffer.byteOffset + startByteIndex,
byteLength
);
}
return new BitArray(buffer, end2 - start, start % 8);
}
function toBitArray(segments) {
if (segments.length === 0) {
return new BitArray(new Uint8Array());
}
if (segments.length === 1) {
const segment = segments[0];
if (segment instanceof BitArray) {
return segment;
}
if (segment instanceof Uint8Array) {
return new BitArray(segment);
}
return new BitArray(new Uint8Array(
/** @type {number[]} */
segments
));
}
let bitSize = 0;
let areAllSegmentsNumbers = true;
for (const segment of segments) {
if (segment instanceof BitArray) {
bitSize += segment.bitSize;
areAllSegmentsNumbers = false;
} else if (segment instanceof Uint8Array) {
bitSize += segment.byteLength * 8;
areAllSegmentsNumbers = false;
} else {
bitSize += 8;
}
}
if (areAllSegmentsNumbers) {
return new BitArray(new Uint8Array(
/** @type {number[]} */
segments
));
}
const buffer = new Uint8Array(Math.trunc((bitSize + 7) / 8));
let cursor = 0;
for (let segment of segments) {
const isCursorByteAligned = cursor % 8 === 0;
if (segment instanceof BitArray) {
if (isCursorByteAligned && segment.bitOffset === 0) {
buffer.set(segment.rawBuffer, cursor / 8);
cursor += segment.bitSize;
const trailingBitsCount = segment.bitSize % 8;
if (trailingBitsCount !== 0) {
const lastByteIndex = Math.trunc(cursor / 8);
buffer[lastByteIndex] >>= 8 - trailingBitsCount;
buffer[lastByteIndex] <<= 8 - trailingBitsCount;
}
} else {
appendUnalignedBits(
segment.rawBuffer,
segment.bitSize,
segment.bitOffset
);
}
} else if (segment instanceof Uint8Array) {
if (isCursorByteAligned) {
buffer.set(segment, cursor / 8);
cursor += segment.byteLength * 8;
} else {
appendUnalignedBits(segment, segment.byteLength * 8, 0);
}
} else {
if (isCursorByteAligned) {
buffer[cursor / 8] = segment;
cursor += 8;
} else {
appendUnalignedBits(new Uint8Array([segment]), 8, 0);
}
}
}
function appendUnalignedBits(unalignedBits, size2, offset) {
if (size2 === 0) {
return;
}
const byteSize = Math.trunc(size2 + 7 / 8);
const highBitsCount = cursor % 8;
const lowBitsCount = 8 - highBitsCount;
let byteIndex = Math.trunc(cursor / 8);
for (let i = 0; i < byteSize; i++) {
let byte = bitArrayByteAt(unalignedBits, offset, i);
if (size2 < 8) {
byte >>= 8 - size2;
byte <<= 8 - size2;
}
buffer[byteIndex] |= byte >> highBitsCount;
let appendedBitsCount = size2 - Math.max(0, size2 - lowBitsCount);
size2 -= appendedBitsCount;
cursor += appendedBitsCount;
if (size2 === 0) {
break;
}
buffer[++byteIndex] = byte << lowBitsCount;
appendedBitsCount = size2 - Math.max(0, size2 - highBitsCount);
size2 -= appendedBitsCount;
cursor += appendedBitsCount;
}
}
return new BitArray(buffer, bitSize);
}
function bitArrayValidateRange(bitArray, start, end2) {
if (start < 0 || start > bitArray.bitSize || end2 < start || end2 > bitArray.bitSize) {
const msg = `Invalid bit array slice: start = ${start}, end = ${end2}, bit size = ${bitArray.bitSize}`;
throw new globalThis.Error(msg);
}
}
var utf8Encoder;
function stringBits(string4) {
utf8Encoder ??= new TextEncoder();
return utf8Encoder.encode(string4);
}
var Result = class _Result extends CustomType {
static isResult(data2) {
return data2 instanceof _Result;
}
};
var Ok = class extends Result {
constructor(value) {
super();
this[0] = value;
}
isOk() {
return true;
}
};
var Result$Ok = (value) => new Ok(value);
var Result$isOk = (value) => value instanceof Ok;
var Error2 = class extends Result {
constructor(detail) {
super();
this[0] = detail;
}
isOk() {
return false;
}
};
var Result$Error = (detail) => new Error2(detail);
var Result$isError = (value) => value instanceof Error2;
function isEqual(x, y) {
let values2 = [x, y];
while (values2.length) {
let a = values2.pop();
let b = values2.pop();
if (a === b) continue;
if (!isObject(a) || !isObject(b)) return false;
let unequal = !structurallyCompatibleObjects(a, b) || unequalDates(a, b) || unequalBuffers(a, b) || unequalArrays(a, b) || unequalMaps(a, b) || unequalSets(a, b) || unequalRegExps(a, b);
if (unequal) return false;
const proto = Object.getPrototypeOf(a);
if (proto !== null && typeof proto.equals === "function") {
try {
if (a.equals(b)) continue;
else return false;
} catch {
}
}
let [keys, get3] = getters(a);
const ka = keys(a);
const kb = keys(b);
if (ka.length !== kb.length) return false;
for (let k of ka) {
values2.push(get3(a, k), get3(b, k));
}
}
return true;
}
function getters(object3) {
if (object3 instanceof Map) {
return [(x) => x.keys(), (x, y) => x.get(y)];
} else {
let extra = object3 instanceof globalThis.Error ? ["message"] : [];
return [(x) => [...extra, ...Object.keys(x)], (x, y) => x[y]];
}
}
function unequalDates(a, b) {
return a instanceof Date && (a > b || a < b);
}
function unequalBuffers(a, b) {
return !(a instanceof BitArray) && a.buffer instanceof ArrayBuffer && a.BYTES_PER_ELEMENT && !(a.byteLength === b.byteLength && a.every((n, i) => n === b[i]));
}
function unequalArrays(a, b) {
return Array.isArray(a) && a.length !== b.length;
}
function unequalMaps(a, b) {
return a instanceof Map && a.size !== b.size;
}
function unequalSets(a, b) {
return a instanceof Set && (a.size != b.size || [...a].some((e) => !b.has(e)));
}
function unequalRegExps(a, b) {
return a instanceof RegExp && (a.source !== b.source || a.flags !== b.flags);
}
function isObject(a) {
return typeof a === "object" && a !== null;
}
function structurallyCompatibleObjects(a, b) {
if (typeof a !== "object" && typeof b !== "object" && (!a || !b))
return false;
let nonstructural = [Promise, WeakSet, WeakMap, Function];
if (nonstructural.some((c) => a instanceof c)) return false;
return a.constructor === b.constructor;
}
// build/dev/javascript/argv/argv_ffi.mjs
function load() {
if (globalThis.process) {
const [runtime2, program2, ...args2] = process.argv;
return [runtime2, program2, List.fromArray(args2)];
}
if (globalThis.Deno) {
const runtime2 = Deno.execPath();
const program2 = new URL(Deno.mainModule).pathname;
const args2 = List.fromArray(Deno.args);
return [runtime2, program2, args2];
}
const runtime = "browser";
const program = document.location.toString();
const args = List.fromArray([]);
return [runtime, program, args];
}
// build/dev/javascript/argv/argv.mjs
var Argv = class extends CustomType {
constructor(runtime, program, arguments$) {
super();
this.runtime = runtime;
this.program = program;
this.arguments = arguments$;
}
};
function load2() {
let $ = load();
let runtime;
let program;
let arguments$;
runtime = $[0];
program = $[1];
arguments$ = $[2];
return new Argv(runtime, program, arguments$);
}
// build/dev/javascript/gleam_stdlib/dict.mjs
var referenceMap = /* @__PURE__ */ new WeakMap();
var tempDataView = /* @__PURE__ */ new DataView(
/* @__PURE__ */ new ArrayBuffer(8)
);
var referenceUID = 0;
function hashByReference(o) {
const known = referenceMap.get(o);
if (known !== void 0) {
return known;
}
const hash = referenceUID++;
if (referenceUID === 2147483647) {
referenceUID = 0;
}
referenceMap.set(o, hash);
return hash;
}
function hashMerge(a, b) {
return a ^ b + 2654435769 + (a << 6) + (a >> 2) | 0;
}
function hashString(s) {
let hash = 0;
const len = s.length;
for (let i = 0; i < len; i++) {
hash = Math.imul(31, hash) + s.charCodeAt(i) | 0;
}
return hash;
}
function hashNumber(n) {
tempDataView.setFloat64(0, n);
const i = tempDataView.getInt32(0);
const j = tempDataView.getInt32(4);
return Math.imul(73244475, i >> 16 ^ i) ^ j;
}
function hashBigInt(n) {
return hashString(n.toString());
}
function hashObject(o) {
const proto = Object.getPrototypeOf(o);
if (proto !== null && typeof proto.hashCode === "function") {
try {
const code = o.hashCode(o);
if (typeof code === "number") {
return code;
}
} catch {
}
}
if (o instanceof Promise || o instanceof WeakSet || o instanceof WeakMap) {
return hashByReference(o);
}
if (o instanceof Date) {
return hashNumber(o.getTime());
}
let h = 0;
if (o instanceof ArrayBuffer) {
o = new Uint8Array(o);
}
if (Array.isArray(o) || o instanceof Uint8Array) {
for (let i = 0; i < o.length; i++) {
h = Math.imul(31, h) + getHash(o[i]) | 0;
}
} else if (o instanceof Set) {
o.forEach((v) => {
h = h + getHash(v) | 0;
});
} else if (o instanceof Map) {
o.forEach((v, k) => {
h = h + hashMerge(getHash(v), getHash(k)) | 0;
});
} else {
const keys = Object.keys(o);
for (let i = 0; i < keys.length; i++) {
const k = keys[i];
const v = o[k];
h = h + hashMerge(getHash(v), hashString(k)) | 0;
}
}
return h;
}
function getHash(u) {
if (u === null) return 1108378658;
if (u === void 0) return 1108378659;
if (u === true) return 1108378657;
if (u === false) return 1108378656;
switch (typeof u) {
case "number":
return hashNumber(u);
case "string":
return hashString(u);
case "bigint":
return hashBigInt(u);
case "object":
return hashObject(u);
case "symbol":
return hashByReference(u);
case "function":
return hashByReference(u);
default:
return 0;
}
}
var Dict = class {
constructor(size2, root) {
this.size = size2;
this.root = root;
}
};
var bits = 5;
var mask = (1 << bits) - 1;
var noElementMarker = Symbol();
var generationKey = Symbol();
var errorNil = /* @__PURE__ */ Result$Error(void 0);
function get(dict2, key) {
const result2 = lookup(dict2.root, key, getHash(key));
return result2 !== noElementMarker ? Result$Ok(result2) : errorNil;
}
function lookup(node, key, hash) {
for (let shift = 0; shift < 32; shift += bits) {
const data2 = node.data;
const bit = hashbit(hash, shift);
if (node.nodemap & bit) {
node = data2[data2.length - 1 - index(node.nodemap, bit)];
} else if (node.datamap & bit) {
const dataidx = Math.imul(index(node.datamap, bit), 2);
return isEqual(key, data2[dataidx]) ? data2[dataidx + 1] : noElementMarker;
} else {
return noElementMarker;
}
}
const overflow = node.data;
for (let i = 0; i < overflow.length; i += 2) {
if (isEqual(key, overflow[i])) {
return overflow[i + 1];
}
}
return noElementMarker;
}
function popcount(n) {
n -= n >>> 1 & 1431655765;
n = (n & 858993459) + (n >>> 2 & 858993459);
return Math.imul(n + (n >>> 4) & 252645135, 16843009) >>> 24;
}
function index(bitmap, bit) {
return popcount(bitmap & bit - 1);
}
function hashbit(hash, shift) {
return 1 << (hash >>> shift & mask);
}
// build/dev/javascript/gleam_stdlib/gleam/option.mjs
var Some = class extends CustomType {
constructor($0) {
super();
this[0] = $0;
}
};
var None = class extends CustomType {
};
// build/dev/javascript/envoy/envoy_ffi.mjs
function get2(key) {
let value;
if (globalThis.Deno) {
value = Deno.env.get(key);
} else if (globalThis.process) {
value = process.env[key];
}
if (value === void 0) {
return Result$Error(void 0);
} else {
return Result$Ok(value);
}
}
// build/dev/javascript/gleam_stdlib/gleam/list.mjs
function reverse_and_prepend(loop$prefix, loop$suffix) {
while (true) {
let prefix = loop$prefix;
let suffix = loop$suffix;
if (prefix instanceof Empty) {
return suffix;
} else {
let first$1 = prefix.head;
let rest$1 = prefix.tail;
loop$prefix = rest$1;
loop$suffix = prepend(first$1, suffix);
}
}
}
function reverse(list2) {
return reverse_and_prepend(list2, toList([]));
}
function map_loop(loop$list, loop$fun, loop$acc) {
while (true) {
let list2 = loop$list;
let fun = loop$fun;
let acc = loop$acc;
if (list2 instanceof Empty) {
return reverse(acc);
} else {
let first$1 = list2.head;
let rest$1 = list2.tail;
loop$list = rest$1;
loop$fun = fun;
loop$acc = prepend(fun(first$1), acc);
}
}
}
function map2(list2, fun) {
return map_loop(list2, fun, toList([]));
}
function append_loop(loop$first, loop$second) {
while (true) {
let first = loop$first;
let second = loop$second;
if (first instanceof Empty) {
return second;
} else {
let first$1 = first.head;
let rest$1 = first.tail;
loop$first = rest$1;
loop$second = prepend(first$1, second);
}
}
}
function append(first, second) {
return append_loop(reverse(first), second);
}
// build/dev/javascript/gleam_stdlib/gleam/bit_array.mjs
function append3(first, second) {
return bit_array_concat(toList([first, second]));
}
// build/dev/javascript/gleam_stdlib/gleam/dynamic/decode.mjs
var DecodeError = class extends CustomType {
constructor(expected, found, path2) {
super();
this.expected = expected;
this.found = found;
this.path = path2;
}
};
var Decoder = class extends CustomType {
constructor(function$) {
super();
this.function = function$;
}
};
var dynamic = /* @__PURE__ */ new Decoder(decode_dynamic);
var int2 = /* @__PURE__ */ new Decoder(decode_int);
var float2 = /* @__PURE__ */ new Decoder(decode_float);
var string2 = /* @__PURE__ */ new Decoder(decode_string);
function run(data2, decoder) {
let $ = decoder.function(data2);
let maybe_invalid_data;
let errors;
maybe_invalid_data = $[0];
errors = $[1];
if (errors instanceof Empty) {
return new Ok(maybe_invalid_data);
} else {
return new Error2(errors);
}
}
function success(data2) {
return new Decoder((_) => {
return [data2, toList([])];
});
}
function decode_dynamic(data2) {
return [data2, toList([])];
}
function map3(decoder, transformer) {
return new Decoder(
(d) => {
let $ = decoder.function(d);
let data2;
let errors;
data2 = $[0];
errors = $[1];
return [transformer(data2), errors];
}
);
}
function run_decoders(loop$data, loop$failure, loop$decoders) {
while (true) {
let data2 = loop$data;
let failure = loop$failure;
let decoders = loop$decoders;
if (decoders instanceof Empty) {
return failure;
} else {
let decoder = decoders.head;
let decoders$1 = decoders.tail;
let $ = decoder.function(data2);
let layer;
let errors;
layer = $;
errors = $[1];
if (errors instanceof Empty) {
return layer;
} else {
loop$data = data2;
loop$failure = failure;
loop$decoders = decoders$1;
}
}
}
}
function one_of(first, alternatives) {
return new Decoder(
(dynamic_data) => {
let $ = first.function(dynamic_data);
let layer;
let errors;
layer = $;
errors = $[1];
if (errors instanceof Empty) {
return layer;
} else {
return run_decoders(dynamic_data, layer, alternatives);
}
}
);
}
function run_dynamic_function(data2, name, f) {
let $ = f(data2);
if ($ instanceof Ok) {
let data$1 = $[0];
return [data$1, toList([])];
} else {
let placeholder = $[0];
return [
placeholder,
toList([new DecodeError(name, classify_dynamic(data2), toList([]))])
];
}
}
function decode_int(data2) {
return run_dynamic_function(data2, "Int", int);
}
function decode_float(data2) {
return run_dynamic_function(data2, "Float", float);
}
function decode_string(data2) {
return run_dynamic_function(data2, "String", string);
}
function path_segment_to_string(key) {
let decoder = one_of(
string2,
toList([
(() => {
let _pipe = int2;
return map3(_pipe, to_string);
})(),
(() => {
let _pipe = float2;
return map3(_pipe, float_to_string);
})()
])
);
let $ = run(key, decoder);
if ($ instanceof Ok) {
let key$1 = $[0];
return key$1;
} else {
return "<" + classify_dynamic(key) + ">";
}
}
function push_path(layer, path2) {
let path$1 = map2(
path2,
(key) => {
let _pipe = key;
let _pipe$1 = identity(_pipe);
return path_segment_to_string(_pipe$1);
}
);
let errors = map2(
layer[1],
(error) => {
return new DecodeError(
error.expected,
error.found,
append(path$1, error.path)
);
}
);
return [layer[0], errors];
}
function index3(loop$path, loop$position, loop$inner, loop$data, loop$handle_miss) {
while (true) {
let path2 = loop$path;
let position = loop$position;
let inner = loop$inner;
let data2 = loop$data;
let handle_miss = loop$handle_miss;
if (path2 instanceof Empty) {
let _pipe = data2;
let _pipe$1 = inner(_pipe);
return push_path(_pipe$1, reverse(position));
} else {
let key = path2.head;
let path$1 = path2.tail;
let $ = index2(data2, key);
if ($ instanceof Ok) {
let $1 = $[0];
if ($1 instanceof Some) {
let data$1 = $1[0];
loop$path = path$1;
loop$position = prepend(key, position);
loop$inner = inner;
loop$data = data$1;
loop$handle_miss = handle_miss;
} else {
return handle_miss(data2, prepend(key, position));
}
} else {
let kind = $[0];
let $1 = inner(data2);
let default$;
default$ = $1[0];
let _pipe = [
default$,
toList([new DecodeError(kind, classify_dynamic(data2), toList([]))])
];
return push_path(_pipe, reverse(position));
}
}
}
}
function subfield(field_path, field_decoder, next) {
return new Decoder(
(data2) => {
let $ = index3(
field_path,
toList([]),
field_decoder.function,
data2,
(data3, position) => {
let $12 = field_decoder.function(data3);
let default$;
default$ = $12[0];
let _pipe = [
default$,
toList([new DecodeError("Field", "Nothing", toList([]))])
];
return push_path(_pipe, reverse(position));
}
);
let out;
let errors1;
out = $[0];
errors1 = $[1];
let $1 = next(out).function(data2);
let out$1;
let errors2;
out$1 = $1[0];
errors2 = $1[1];
return [out$1, append(errors1, errors2)];
}
);
}
function field(field_name, field_decoder, next) {
return subfield(toList([field_name]), field_decoder, next);
}
// build/dev/javascript/gleam_stdlib/gleam_stdlib.mjs
var Nil = void 0;
function identity(x) {
return x;
}
function parse_int(value) {
if (/^[-+]?(\d+)$/.test(value)) {
return Result$Ok(parseInt(value));
} else {
return Result$Error(Nil);
}
}
function to_string(term) {
return term.toString();
}
var unicode_whitespaces = [
" ",
// Space
" ",
// Horizontal tab
"\n",
// Line feed
"\v",
// Vertical tab
"\f",
// Form feed
"\r",
// Carriage return
"\x85",
// Next line
"\u2028",
// Line separator
"\u2029"
// Paragraph separator
].join("");
var trim_start_regex = /* @__PURE__ */ new RegExp(
`^[${unicode_whitespaces}]*`
);
var trim_end_regex = /* @__PURE__ */ new RegExp(`[${unicode_whitespaces}]*$`);
function bit_array_from_string(string4) {
return toBitArray([stringBits(string4)]);
}
function bit_array_byte_size(bit_array2) {
return bit_array2.byteSize;
}
function bit_array_concat(bit_arrays) {
return toBitArray(bit_arrays.toArray());
}
function console_error(term) {
console.error(term);
}
function bit_array_to_string(bit_array2) {
if (bit_array2.bitSize % 8 !== 0) {
return Result$Error(Nil);
}
try {
const decoder = new TextDecoder("utf-8", { fatal: true });
if (bit_array2.bitOffset === 0) {
return Result$Ok(decoder.decode(bit_array2.rawBuffer));
} else {
const buffer = new Uint8Array(bit_array2.byteSize);
for (let i = 0; i < buffer.length; i++) {
buffer[i] = bit_array2.byteAt(i);
}
return Result$Ok(decoder.decode(buffer));
}
} catch {
return Result$Error(Nil);
}
}
function bit_array_slice(bits2, position, length3) {
const start = Math.min(position, position + length3);
const end2 = Math.max(position, position + length3);
if (start < 0 || end2 * 8 > bits2.bitSize) {
return Result$Error(Nil);
}
return Result$Ok(bitArraySlice(bits2, start * 8, end2 * 8));
}
function classify_dynamic(data2) {
if (typeof data2 === "string") {
return "String";
} else if (typeof data2 === "boolean") {
return "Bool";
} else if (isResult(data2)) {
return "Result";
} else if (isList(data2)) {
return "List";
} else if (data2 instanceof BitArray) {
return "BitArray";
} else if (data2 instanceof Dict) {
return "Dict";
} else if (Number.isInteger(data2)) {
return "Int";
} else if (Array.isArray(data2)) {
return `Array`;
} else if (typeof data2 === "number") {
return "Float";
} else if (data2 === null) {
return "Nil";
} else if (data2 === void 0) {
return "Nil";
} else {
const type = typeof data2;
return type.charAt(0).toUpperCase() + type.slice(1);
}
}
var MIN_I32 = -(2 ** 31);
var MAX_I32 = 2 ** 31 - 1;
var U32 = 2 ** 32;
var MAX_SAFE = Number.MAX_SAFE_INTEGER;
var MIN_SAFE = Number.MIN_SAFE_INTEGER;
function float_to_string(float3) {
const string4 = float3.toString().replace("+", "");
if (string4.indexOf(".") >= 0) {
return string4;
} else {
const index5 = string4.indexOf("e");
if (index5 >= 0) {
return string4.slice(0, index5) + ".0" + string4.slice(index5);
} else {
return string4 + ".0";
}
}
}
function index2(data2, key) {
if (data2 instanceof Dict) {
const result2 = get(data2, key);
return Result$Ok(result2.isOk() ? new Some(result2[0]) : new None());
}
if (data2 instanceof WeakMap || data2 instanceof Map) {
const token = {};
const entry = data2.get(key, token);
if (entry === token) return Result$Ok(new None());
return Result$Ok(new Some(entry));
}
const key_is_int = Number.isInteger(key);
if (key_is_int && key >= 0 && key < 8 && isList(data2)) {
let i = 0;
for (const value of data2) {
if (i === key) return Result$Ok(new Some(value));
i++;
}
return Result$Error("Indexable");
}
if (key_is_int && Array.isArray(data2) || data2 && typeof data2 === "object" || data2 && Object.getPrototypeOf(data2) === Object.prototype) {
if (key in data2) return Result$Ok(new Some(data2[key]));
return Result$Ok(new None());
}
return Result$Error(key_is_int ? "Indexable" : "Dict");
}
function float(data2) {
if (typeof data2 === "number") return Result$Ok(data2);
return Result$Error(0);
}
function int(data2) {
if (Number.isInteger(data2)) return Result$Ok(data2);
return Result$Error(0);
}
function string(data2) {
if (typeof data2 === "string") return Result$Ok(data2);
return Result$Error("");
}
function isList(data2) {
return List$isEmpty(data2) || List$isNonEmpty(data2);
}
function isResult(data2) {
return Result$isOk(data2) || Result$isError(data2);
}
// build/dev/javascript/gleam_javascript/gleam_javascript_ffi.mjs
var PromiseLayer = class _PromiseLayer {
constructor(promise) {
this.promise = promise;
}
static wrap(value) {
return value instanceof Promise ? new _PromiseLayer(value) : value;
}
static unwrap(value) {
return value instanceof _PromiseLayer ? value.promise : value;
}
};
function map_promise(promise, fn) {
return promise.then(
(value) => PromiseLayer.wrap(fn(PromiseLayer.unwrap(value)))
);
}
// build/dev/javascript/gleam_javascript/gleam/javascript/promise.mjs
function tap(promise, callback) {
let _pipe = promise;
return map_promise(
_pipe,
(a) => {
callback(a);
return a;
}
);
}
// build/dev/javascript/gleam_stdlib/gleam/result.mjs
function map_error(result2, fun) {
if (result2 instanceof Ok) {
return result2;
} else {
let error = result2[0];
return new Error2(fun(error));
}
}
function try$(result2, fun) {
if (result2 instanceof Ok) {
let x = result2[0];
return fun(x);
} else {
return result2;
}
}
function unwrap(result2, default$) {
if (result2 instanceof Ok) {
let v = result2[0];
return v;
} else {
return default$;
}
}
function replace_error(result2, error) {
if (result2 instanceof Ok) {
return result2;
} else {
return new Error2(error);
}
}
// build/dev/javascript/gleam_json/gleam_json_ffi.mjs
function json_to_string(json) {
return JSON.stringify(json);
}
function object(entries) {
return Object.fromEntries(entries);
}
function identity2(x) {
return x;
}
function array(list2) {
const array3 = [];
while (List$isNonEmpty(list2)) {
array3.push(List$NonEmpty$first(list2));
list2 = List$NonEmpty$rest(list2);
}
return array3;
}
function decode(string4) {
try {
const result2 = JSON.parse(string4);
return Result$Ok(result2);
} catch (err) {
return Result$Error(getJsonDecodeError(err, string4));
}
}
function getJsonDecodeError(stdErr, json) {
if (isUnexpectedEndOfInput(stdErr)) return DecodeError$UnexpectedEndOfInput();
return toUnexpectedByteError(stdErr, json);
}
function isUnexpectedEndOfInput(err) {
const unexpectedEndOfInputRegex = /((unexpected (end|eof))|(end of data)|(unterminated string)|(json( parse error|\.parse)\: expected '(\:|\}|\])'))/i;
return unexpectedEndOfInputRegex.test(err.message);
}
function toUnexpectedByteError(err, json) {
let converters = [
v8UnexpectedByteError,
oldV8UnexpectedByteError,
jsCoreUnexpectedByteError,
spidermonkeyUnexpectedByteError
];
for (let converter of converters) {
let result2 = converter(err, json);
if (result2) return result2;
}
return DecodeError$UnexpectedByte("");
}
function v8UnexpectedByteError(err) {
const regex = /unexpected token '(.)', ".+" is not valid JSON/i;
const match = regex.exec(err.message);
if (!match) return null;
const byte = toHex(match[1]);
return DecodeError$UnexpectedByte(byte);
}
function oldV8UnexpectedByteError(err) {
const regex = /unexpected token (.) in JSON at position (\d+)/i;
const match = regex.exec(err.message);
if (!match) return null;
const byte = toHex(match[1]);
return DecodeError$UnexpectedByte(byte);
}
function spidermonkeyUnexpectedByteError(err, json) {
const regex = /(unexpected character|expected .*) at line (\d+) column (\d+)/i;
const match = regex.exec(err.message);
if (!match) return null;
const line = Number(match[2]);
const column = Number(match[3]);
const position = getPositionFromMultiline(line, column, json);
const byte = toHex(json[position]);
return DecodeError$UnexpectedByte(byte);
}
function jsCoreUnexpectedByteError(err) {
const regex = /unexpected (identifier|token) "(.)"/i;
const match = regex.exec(err.message);
if (!match) return null;
const byte = toHex(match[2]);
return DecodeError$UnexpectedByte(byte);
}
function toHex(char) {
return "0x" + char.charCodeAt(0).toString(16).toUpperCase();
}
function getPositionFromMultiline(line, column, string4) {
if (line === 1) return column - 1;
let currentLn = 1;
let position = 0;
string4.split("").find((char, idx) => {
if (char === "\n") currentLn += 1;
if (currentLn === line) {
position = idx + column;
return true;
}
return false;
});
return position;
}
// build/dev/javascript/gleam_json/gleam/json.mjs
var UnexpectedEndOfInput = class extends CustomType {
};
var DecodeError$UnexpectedEndOfInput = () => new UnexpectedEndOfInput();
var UnexpectedByte = class extends CustomType {
constructor($0) {
super();
this[0] = $0;
}
};
var DecodeError$UnexpectedByte = ($0) => new UnexpectedByte($0);
var UnableToDecode = class extends CustomType {
constructor($0) {
super();
this[0] = $0;
}
};
function do_parse(json, decoder) {
return try$(
decode(json),
(dynamic_value) => {
let _pipe = run(dynamic_value, decoder);
return map_error(
_pipe,
(var0) => {
return new UnableToDecode(var0);
}
);
}
);
}
function parse(json, decoder) {
return do_parse(json, decoder);
}
function to_string2(json) {
return json_to_string(json);
}
function string3(input) {
return identity2(input);
}
function bool(input) {
return identity2(input);
}
function object2(entries) {
return object(entries);
}
function preprocessed_array(from2) {
return array(from2);
}
function array2(entries, inner_type) {
let _pipe = entries;
let _pipe$1 = map2(_pipe, inner_type);
return preprocessed_array(_pipe$1);
}
// build/dev/javascript/gleam_stdlib/gleam/bool.mjs
function guard(requirement, consequence, alternative) {
if (requirement) {
return consequence;
} else {
return alternative();
}
}
// build/dev/javascript/netstring/netstring.mjs
var NeedMore = class extends CustomType {
};
var InvalidFormat = class extends CustomType {
constructor($0) {
super();
this[0] = $0;
}
};
function encode(data2) {
let length3 = bit_array_byte_size(data2);
let length_str = to_string(length3);
return bit_array_concat(
toList([
toBitArray([stringBits(length_str), stringBits(":")]),
data2,
toBitArray([stringBits(",")])
])
);
}
function extract_data_bits(buffer, data_start, length3) {
let buffer_size = bit_array_byte_size(buffer);
return guard(
buffer_size < data_start + length3 + 1,
new Error2(new NeedMore()),
() => {
return try$(
(() => {
let _pipe = bit_array_slice(buffer, data_start, length3);
return replace_error(_pipe, new NeedMore());
})(),
(data_bytes) => {
return guard(
!isEqual(
bit_array_slice(buffer, data_start + length3, 1),
new Ok(toBitArray([44]))
),
new Error2(new InvalidFormat("Missing trailing comma")),
() => {
let remaining_start = data_start + length3 + 1;
let remaining_len = buffer_size - remaining_start;
let $ = bit_array_slice(buffer, remaining_start, remaining_len);
if ($ instanceof Ok) {
let remaining_bytes = $[0];
return new Ok([data_bytes, remaining_bytes]);
} else {
return new Ok([data_bytes, toBitArray([])]);
}
}
);
}
);
}
);
}
function decode_bytes_inner(loop$buffer, loop$index, loop$acc, loop$digit_count) {
while (true) {
let buffer = loop$buffer;
let index5 = loop$index;
let acc = loop$acc;
let digit_count = loop$digit_count;
let $ = bit_array_slice(buffer, index5, 1);
if ($ instanceof Ok) {
let $1 = $[0];
if ($1.bitSize === 8) {
if ($1.byteAt(0) === 58) {
if (digit_count === 0) {
return new Error2(new InvalidFormat("Missing length"));
} else {
return extract_data_bits(buffer, index5 + 1, acc);
}
} else {
let digit = $1.byteAt(0);
if (digit >= 48 && digit <= 57) {
let $2 = digit_count >= 1 && acc === 0;
if ($2) {
return new Error2(new InvalidFormat("Leading zeros not allowed"));
} else {
loop$buffer = buffer;
loop$index = index5 + 1;
loop$acc = acc * 10 + digit - 48;
loop$digit_count = digit_count + 1;
}
} else {
return new Error2(new InvalidFormat("Invalid character in length"));
}
}
} else {
return new Error2(new InvalidFormat("Invalid character in length"));
}
} else {
return new Error2(new NeedMore());
}
}
}
function decode2(buffer) {
return decode_bytes_inner(buffer, 0, 0, 0);
}
// build/dev/javascript/node_socket_client/node_socket_client_ffi.mjs
var import_node_net = require("node:net");
function do_connect(host, port, initialState, handler, binary) {
let state = initialState;
const socket = new import_node_net.Socket();
if (!binary) {
socket.setEncoding("utf8");
}
const handle = (event) => {
state = handler(state, socket, event);
};
socket.on("close", (hadError) => handle(new CloseEvent(hadError)));
socket.on("connect", () => handle(new ConnectEvent()));
socket.on(
"connectionAttempt",
(ip, port2, family) => handle(new ConnectionAttemptEvent(ip, port2, family))
);
socket.on(
"connectionAttemptFailed",
(ip, port2, family, error) => handle(new ConnectionAttemptFailedEvent(ip, port2, family, error.toString()))
);
socket.on(
"connectionAttemptTimeout",
(ip, port2, family) => handle(new ConnectionAttemptTimeoutEvent(ip, port2, family))
);
socket.on(
"data",
(data2) => handle(new DataEvent(binary ? BitArray$BitArray(data2) : data2))
);
socket.on("drain", () => handle(new DrainEvent()));
socket.on("end", () => handle(new EndEvent()));
socket.on("error", (error) => handle(new ErrorEvent(error.toString())));
socket.on(
"lookup",
(err, address, family, host2) => handle(new LookupEvent(result(err), address, family, host2))
);
socket.on("ready", () => handle(new ReadyEvent()));
socket.on("timeout", () => handle(new TimeoutEvent()));
socket.connect(port, host);
return socket;
}
function writeBits(socket, data2) {
return socket.write(data2.rawBuffer);
}
var result = (error) => error ? new Error2(error.toString()) : new Ok(void 0);
// build/dev/javascript/node_socket_client/node_socket_client.mjs
var CloseEvent = class extends CustomType {
constructor(had_error) {
super();
this.had_error = had_error;
}
};
var ConnectEvent = class extends CustomType {
};
var ConnectionAttemptEvent = class extends CustomType {
constructor(ip, port, family) {
super();
this.ip = ip;
this.port = port;
this.family = family;
}
};
var ConnectionAttemptFailedEvent = class extends CustomType {
constructor(ip, port, family, error) {
super();
this.ip = ip;
this.port = port;
this.family = family;
this.error = error;
}
};
var ConnectionAttemptTimeoutEvent = class extends CustomType {
constructor(ip, port, family) {
super();
this.ip = ip;
this.port = port;
this.family = family;
}
};
var DataEvent = class extends CustomType {
constructor(data2) {
super();
this.data = data2;
}
};
var DrainEvent = class extends CustomType {
};
var EndEvent = class extends CustomType {
};
var ErrorEvent = class extends CustomType {
constructor(error) {
super();
this.error = error;
}
};
var LookupEvent = class extends CustomType {
constructor(result2, address, family, host) {
super();
this.result = result2;
this.address = address;
this.family = family;
this.host = host;
}
};
var ReadyEvent = class extends CustomType {
};
var TimeoutEvent = class extends CustomType {
};
function connect_binary(host, port, state, handler) {
return do_connect(host, port, state, handler, true);
}
// build/dev/javascript/ssr_server/ssr_server_ffi.mjs
var path = __toESM(require("path"), 1);
function clearModule(moduleId, visited) {
if (!moduleId || visited.has(moduleId)) {
return;
}
const mod = require.cache[moduleId];
if (!mod) {
return;
}
visited.add(moduleId);
for (const child of mod.children) {
clearModule(child.id, visited);
}
delete require.cache[moduleId];
}
function clearRequireCache(resolvedPath) {
const visited = /* @__PURE__ */ new Set();
try {
const moduleId = require.resolve(resolvedPath);
clearModule(moduleId, visited);
} catch {
}
}
function loadModule(modulePath) {
try {
const resolvedPath = path.resolve(process.cwd(), modulePath);
clearRequireCache(resolvedPath);
const mod = require(resolvedPath);
const render = mod.render || mod.default?.render || mod.default;
if (typeof render !== "function") {
return Result$Error(RenderError$NoRenderExport(modulePath));
}
return Result$Ok({ render, path: resolvedPath });
} catch (e) {
if (e.code === "MODULE_NOT_FOUND") {
return Result$Error(RenderError$ModuleNotFound(modulePath));
}
return Result$Error(RenderError$RenderFailed(e.message || String(e)));
}
}
async function callRender(module2, page) {
try {
const result2 = await module2.render(page);
const head = result2.head ?? [];
const body = result2.body ?? "";
if (!Array.isArray(head)) {
return Result$Error(RenderError$RenderFailed("head must be an array"));
}
if (typeof body !== "string") {
return Result$Error(RenderError$RenderFailed("body must be a string"));
}
return Result$Ok(RenderedPage$RenderedPage(toList(head), body));
} catch (e) {
return Result$Error(RenderError$RenderFailed(e.message || String(e)));
}
}
// build/dev/javascript/ssr_server/ssr_server.mjs
var import_process = require("process");
var State = class extends CustomType {
constructor(module2, module_path, worker_id, buffer, socket) {
super();
this.module = module2;
this.module_path = module_path;
this.worker_id = worker_id;
this.buffer = buffer;
this.socket = socket;
}
};
var RenderedPage = class extends CustomType {
constructor(head, body) {
super();
this.head = head;
this.body = body;
}
};
var RenderedPage$RenderedPage = (head, body) => new RenderedPage(head, body);
var ModuleNotFound = class extends CustomType {
constructor($0) {
super();
this[0] = $0;
}
};
var RenderError$ModuleNotFound = ($0) => new ModuleNotFound($0);
var NoRenderExport = class extends CustomType {
constructor($0) {
super();
this[0] = $0;
}
};
var RenderError$NoRenderExport = ($0) => new NoRenderExport($0);
var RenderFailed = class extends CustomType {
constructor($0) {
super();
this[0] = $0;
}
};
var RenderError$RenderFailed = ($0) => new RenderFailed($0);
function is_production() {
let $ = get2("NODE_ENV");
if ($ instanceof Ok) {
let $1 = $[0];
if ($1 === "production") {
return true;
} else {
return false;
}
} else {
return false;
}
}
function is_debug() {
let $ = get2("DEBUG_SSR");
if ($ instanceof Ok) {
let $1 = $[0];
if ($1 === "1") {
return true;
} else if ($1 === "true") {
return true;
} else {
return false;
}
} else {
return false;
}
}
function debug(msg) {
let $ = is_debug();
if ($) {
return console_error("[DEBUG_SSR] " + msg);
} else {
return void 0;
}
}
function send_response(socket, response) {
let _block;
let _pipe = to_string2(response);
let _pipe$1 = bit_array_from_string(_pipe);
_block = encode(_pipe$1);
let frame = _block;
debug(
"Sending response, length=" + to_string(bit_array_byte_size(frame))
);
let $ = writeBits(socket, frame);
return void 0;
}
function reload_module_if_needed(state) {
let $ = is_production();
if ($) {
return state.module;
} else {
debug("Reloading module (NODE_ENV != production)");
let _pipe = loadModule(state.module_path);
return unwrap(_pipe, state.module);
}
}
function request_decoder() {
return field(
"page",
dynamic,
(page) => {
return success(page);
}
);
}
function render_error_to_string(err) {
if (err instanceof ModuleNotFound) {
let path2 = err[0];
return "Module not found: " + path2;
} else if (err instanceof NoRenderExport) {
let path2 = err[0];
return "No render export in: " + path2;
} else {
let msg = err[0];
return msg;
}
}
function build_response(result2) {
if (result2 instanceof Ok) {
let head = result2[0].head;
let body = result2[0].body;
return object2(
toList([
["ok", bool(true)],
["head", array2(head, string3)],
["body", string3(body)]
])
);
} else {
let err = result2[0];
return object2(
toList([
["ok", bool(false)],
["error", string3(render_error_to_string(err))]
])
);
}
}
function handle_request(state, socket, json_str) {
debug("Processing render request");
let module2 = reload_module_if_needed(state);
let $ = parse(json_str, request_decoder());
if ($ instanceof Ok) {
let page = $[0];
debug("Request parsed, calling render");
let _block;
let _pipe = callRender(module2, page);
_block = tap(
_pipe,
(result2) => {
if (result2 instanceof Ok) {
debug("Render succeeded");
} else {
let err = result2[0];
debug("Render failed: " + render_error_to_string(err));
}
return send_response(socket, build_response(result2));
}
);
let $1 = _block;
return void 0;
} else {
debug("Failed to parse request JSON");
let response = object2(
toList([
["ok", bool(false)],
["error", string3("Invalid request JSON")]
])
);
return send_response(socket, response);
}
}
function process_buffer(state, socket, buffer) {
let $ = decode2(buffer);
if ($ instanceof Ok) {
let data2 = $[0][0];
let remaining = $[0][1];
return try$(
bit_array_to_string(data2),
(json_str) => {
handle_request(state, socket, json_str);
return process_buffer(state, socket, remaining);
}
);
} else {
let $1 = $[0];
if ($1 instanceof NeedMore) {
return new Ok(
new State(
state.module,
state.module_path,
state.worker_id,
buffer,
state.socket
)
);
} else {
let msg = $1[0];
console_error("Invalid frame format: " + msg);
(0, import_process.exit)(1);
return new Ok(state);
}
}
}
function handle_event(state, socket, event) {
if (event instanceof CloseEvent) {
debug("Connection closed");
(0, import_process.exit)(0);
return state;
} else if (event instanceof ConnectEvent) {
debug("Connected to TCP server");
let _block;
let _pipe = state.worker_id;
let _pipe$1 = to_string(_pipe);
let _pipe$2 = bit_array_from_string(_pipe$1);
_block = encode(_pipe$2);
let id_frame = _block;
let $ = writeBits(socket, id_frame);
return new State(
state.module,
state.module_path,
state.worker_id,
state.buffer,
new Some(socket)
);
} else if (event instanceof DataEvent) {
let data2 = event.data;
debug("Received data, length=" + to_string(bit_array_byte_size(data2)));
let new_buffer = append3(state.buffer, data2);
let $ = process_buffer(state, socket, new_buffer);
if ($ instanceof Ok) {
let state$1 = $[0];
return state$1;
} else {
debug("Error processing buffer, closing connection");
(0, import_process.exit)(1);
return state;
}
} else if (event instanceof ErrorEvent) {
let err = event.error;
debug("Socket error: " + err);
console_error("Socket error: " + err);
(0, import_process.exit)(1);
return state;
} else {
return state;
}
}
function start_client(port, module_path, worker_id) {
debug(
"Starting SSR client, port=" + to_string(port) + ", module=" + module_path + ", worker_id=" + to_string(
worker_id
)
);
let $ = loadModule(module_path);
if ($ instanceof Ok) {
let module2 = $[0];
debug("Render module loaded successfully");
let state = new State(
module2,
module_path,
worker_id,
toBitArray([]),
new None()
);
let $1 = connect_binary(
"127.0.0.1",
port,
state,
handle_event
);
return void 0;
} else {
let err = $[0];
console_error(
"Failed to load render module: " + render_error_to_string(err)
);
return (0, import_process.exit)(1);
}
}
function parse_args() {
let $ = load2().arguments;
if ($ instanceof Empty) {
return new Error2("Missing required arguments");
} else {
let $1 = $.tail;
if ($1 instanceof Empty) {
return new Error2("Missing required arguments");
} else {
let $2 = $1.tail;
if ($2 instanceof Empty) {
return new Error2("Missing required arguments");
} else {
let port_str = $.head;
let module_path = $1.head;
let worker_id_str = $2.head;
return try$(
(() => {
let _pipe = parse_int(port_str);
return map_error(
_pipe,
(_) => {
return "Invalid port: " + port_str;
}
);
})(),
(port) => {
return try$(
(() => {
let _pipe = parse_int(worker_id_str);
return map_error(
_pipe,
(_) => {
return "Invalid worker_id: " + worker_id_str;
}
);
})(),
(worker_id) => {
return new Ok([port, module_path, worker_id]);
}
);
}
);
}
}
}
}
function main() {
let $ = parse_args();
if ($ instanceof Ok) {
let port = $[0][0];
let module_path = $[0][1];
let worker_id = $[0][2];
return start_client(port, module_path, worker_id);
} else {
let msg = $[0];
console_error(
"Usage: node ssr-server.cjs <port> <module_path> <worker_id>"
);
console_error("Error: " + msg);
return (0, import_process.exit)(1);
}
}
// build/dev/javascript/ssr_server/gleam.main.mjs
main?.();