#include #include #include #include #include #include "ant.h" #include "cfunc.h" #include "builder.h" #include "ptr.h" #include "errors.h" #include "internal.h" #include "common.h" #include "descriptors.h" #include "gc/roots.h" #include "utf8.h" #include "modules/blob.h" #include "modules/buffer.h" #include "modules/formdata.h" #include "modules/headers.h" #include "modules/multipart.h" #include "modules/response.h" #include "modules/url.h" #include "modules/json.h" #include "streams/pipes.h" #include "streams/readable.h" static constexpr uint32_t RESPONSE_NATIVE_TAG = Ant_NativeTag("RESP"); static const char RESPONSE_TEXT_CONTENT_TYPE[] = "text/plain;charset=UTF-8"; response_data_t *response_get_data(ant_value_t obj) { return (response_data_t *)js_get_native(obj, RESPONSE_NATIVE_TAG); } ant_value_t response_materialize_headers(ant_t *js, ant_value_t obj) { response_data_t *resp = response_get_data(obj); if (!resp) return js_mkerr_typed(js, JS_ERR_TYPE, "Invalid Response object"); ant_value_t headers = js_get_slot(obj, SLOT_RESPONSE_HEADERS); if (headers_is_headers(headers)) return headers; headers = resp->pending_headers ? headers_create_from_data(js, resp->pending_headers) : headers_create_empty(js); if (is_err(headers)) return headers; resp->pending_headers = NULL; headers_set_immutable(headers, resp->headers_immutable); js_set_slot_wb(js, obj, SLOT_RESPONSE_HEADERS, headers); return headers; } const headers_data_t *response_get_header_data(ant_value_t obj) { response_data_t *resp = response_get_data(obj); if (!resp) return NULL; ant_value_t headers = js_get_slot(obj, SLOT_RESPONSE_HEADERS); return resp->pending_headers ? resp->pending_headers : headers_get_data(headers); } ant_value_t response_get_websocket(ant_value_t obj) { response_data_t *data = response_get_data(obj); return data ? data->websocket : js_mkundef(); } void response_set_websocket(ant_value_t obj, ant_value_t websocket) { response_data_t *data = response_get_data(obj); if (data) data->websocket = websocket; } static void data_free(response_data_t *d) { if (!d) return; free(d->type); url_state_clear(&d->url); free(d->status_text); if (d->body_storage == RESPONSE_BODY_STORAGE_OWNED) { free(d->body_data); free(d->body_type); } headers_data_destroy(d->pending_headers); free(d); } static void response_finalize(ant_t *js, ant_object_t *obj) { ant_value_t value = js_obj_from_ptr(obj); response_data_t *data = response_get_data(value); data_free(data); js_clear_native(value, RESPONSE_NATIVE_TAG); } static void response_clear_and_free(ant_value_t obj, response_data_t *data) { if (obj) js_clear_native(obj, RESPONSE_NATIVE_TAG); data_free(data); } static response_data_t *data_new(void) { response_data_t *d = calloc(1, sizeof(response_data_t)); if (!d) return NULL; d->status = 200; d->url_list_size = 0; d->websocket = js_mkundef(); return d; } static response_data_t *data_dup(const response_data_t *src) { response_data_t *d = calloc(1, sizeof(response_data_t)); url_state_t *su = NULL; url_state_t *du = NULL; if (!d) return NULL; d->type = src->type ? strdup(src->type) : NULL; d->status_text = src->status_text ? strdup(src->status_text) : NULL; d->has_url = src->has_url; d->url_list_size = src->url_list_size; d->status = src->status; d->body_is_stream = src->body_is_stream; d->has_body = src->has_body; d->body_used = src->body_used; d->body_size = src->body_size; d->body_type = src->body_type ? strdup(src->body_type) : NULL; d->body_storage = (d->body_type || src->body_data) ? RESPONSE_BODY_STORAGE_OWNED : RESPONSE_BODY_STORAGE_NONE; d->websocket = js_mkundef(); d->headers_immutable = src->headers_immutable; d->pending_headers = headers_data_copy(src->pending_headers); if (src->pending_headers && !d->pending_headers) { data_free(d); return NULL; } su = (url_state_t *)&src->url; du = &d->url; #define DUP_US(f) do { du->f = su->f ? strdup(su->f) : NULL; } while (0) DUP_US(href); DUP_US(protocol); DUP_US(username); DUP_US(password); DUP_US(hostname); DUP_US(port); DUP_US(pathname); DUP_US(search); DUP_US(hash); #undef DUP_US if (src->body_data && src->body_size > 0) { d->body_data = malloc(src->body_size); if (!d->body_data) { data_free(d); return NULL; } memcpy(d->body_data, src->body_data, src->body_size); } return d; } static bool copy_body_bytes( ant_t *js, const uint8_t *src, size_t src_len, uint8_t **out_data, size_t *out_size, ant_value_t *err_out ) { uint8_t *buf = NULL; *out_data = NULL; *out_size = 0; if (src_len == 0) return true; buf = malloc(src_len); if (!buf) { *err_out = js_mkerr(js, "out of memory"); return false; } memcpy(buf, src, src_len); *out_data = buf; *out_size = src_len; return true; } static bool extract_buffer_source_body( ant_t *js, ant_value_t body_val, uint8_t **out_data, size_t *out_size, ant_value_t *err_out ) { const uint8_t *src = NULL; size_t src_len = 0; if (!(( vtype(body_val) == kTypeTypedArray || vtype(body_val) == kTypeObject) && buffer_source_get_bytes(js, body_val, &src, &src_len)) ) return false; return copy_body_bytes(js, src, src_len, out_data, out_size, err_out); } static bool extract_stream_body( ant_t *js, ant_value_t body_val, ant_value_t *out_stream, ant_value_t *err_out ) { if (!rs_is_stream(body_val)) return false; if (rs_stream_unusable(body_val)) { *err_out = js_mkerr_typed(js, JS_ERR_TYPE, "body stream is disturbed or locked"); return false; } *out_stream = body_val; return true; } static bool extract_blob_body( ant_t *js, ant_value_t body_val, uint8_t **out_data, size_t *out_size, char **out_type, ant_value_t *err_out ) { blob_data_t *bd = blob_is_blob(js, body_val) ? blob_get_data(body_val) : NULL; if (!bd) return false; if (!copy_body_bytes(js, bd->data, bd->size, out_data, out_size, err_out)) return false; if (bd->type && bd->type[0]) *out_type = strdup(bd->type); return true; } static bool extract_urlsearchparams_body( ant_t *js, ant_value_t body_val, uint8_t **out_data, size_t *out_size, char **out_type ) { char *serialized = NULL; if (!usp_is_urlsearchparams(js, body_val)) return false; serialized = usp_serialize(js, body_val); if (!serialized) return true; *out_data = (uint8_t *)serialized; *out_size = strlen(serialized); *out_type = strdup("application/x-www-form-urlencoded;charset=UTF-8"); return true; } static bool extract_formdata_body( ant_t *js, ant_value_t body_val, uint8_t **out_data, size_t *out_size, char **out_type, ant_value_t *err_out ) { char *boundary = NULL; char *content_type = NULL; size_t mp_size = 0; uint8_t *mp = NULL; if (!formdata_is_formdata(js, body_val)) return false; mp = formdata_serialize_multipart(js, body_val, &mp_size, &boundary); if (!mp) { *err_out = js_mkerr(js, "out of memory"); return false; } if (mp_size > 0) *out_data = mp; else free(mp); *out_size = mp_size; if (!boundary) return true; size_t ct_len = snprintf(NULL, 0, "multipart/form-data; boundary=%s", boundary); content_type = malloc(ct_len + 1); if (!content_type) { free(boundary); if (mp_size > 0) free(mp); *out_data = NULL; *out_size = 0; *err_out = js_mkerr(js, "out of memory"); return false; } snprintf(content_type, ct_len + 1, "multipart/form-data; boundary=%s", boundary); free(boundary); *out_type = content_type; return true; } static bool extract_string_body( ant_t *js, ant_value_t body_val, uint8_t **out_data, size_t *out_size, char **out_type, ant_value_t *err_out ) { size_t len = 0; const char *s = NULL; if (vtype(body_val) != kTypeString) { body_val = js_tostring_val(js, body_val); if (is_err(body_val)) { *err_out = body_val; return false; }} s = js_getstr(js, body_val, &len); if (!copy_body_bytes(js, (const uint8_t *)s, len, out_data, out_size, err_out)) return false; *out_type = strdup(RESPONSE_TEXT_CONTENT_TYPE); return true; } static bool extract_body( ant_t *js, ant_value_t body_val, uint8_t **out_data, size_t *out_size, char **out_type, ant_value_t *out_stream, ant_value_t *err_out ) { *out_data = NULL; *out_size = 0; *out_type = NULL; *out_stream = js_mkundef(); *err_out = js_mkundef(); if (vtype(body_val) == kTypeNull || vtype(body_val) == kTypeUndefined) return true; if (extract_buffer_source_body(js, body_val, out_data, out_size, err_out)) return true; if (vtype(body_val) == kTypeObject && rs_is_stream(body_val)) return extract_stream_body(js, body_val, out_stream, err_out); if (vtype(body_val) == kTypeObject && extract_blob_body(js, body_val, out_data, out_size, out_type, err_out)) return true; if (vtype(body_val) == kTypeObject && extract_urlsearchparams_body(js, body_val, out_data, out_size, out_type)) return true; if (vtype(body_val) == kTypeObject && extract_formdata_body(js, body_val, out_data, out_size, out_type, err_out)) return true; return extract_string_body(js, body_val, out_data, out_size, out_type, err_out); } static bool response_plain_type_needs_charset( const char *current, const char *body_type ) { return current && body_type && strcasecmp(current, "text/plain") == 0 && strcasecmp(body_type, RESPONSE_TEXT_CONTENT_TYPE) == 0; } static bool response_apply_content_type_data( headers_data_t *headers, const char *body_type ) { const char *current = NULL; if (!body_type) return true; size_t count = headers_data_find_literal( headers, "content-type", ¤t); if (count == 0) return headers_data_append_if_missing(headers, "content-type", body_type); if (count == 1 && response_plain_type_needs_charset(current, body_type)) return headers_data_set_literal(headers, "content-type", body_type); return true; } static bool response_apply_pending_content_type( response_data_t *resp, const char *body_type ) { if (!body_type) return true; if (!resp->pending_headers) { resp->pending_headers = headers_data_create(); if (!resp->pending_headers) return false; } return response_apply_content_type_data(resp->pending_headers, body_type); } enum { BODY_TEXT = 0, BODY_JSON, BODY_ARRAYBUFFER, BODY_BLOB, BODY_BYTES, BODY_FORMDATA }; static ant_value_t response_effective_body_type( ant_t *js, ant_value_t resp_obj, response_data_t *d ) { ant_value_t headers = response_materialize_headers(js, resp_obj); if (is_err(headers)) return headers; ant_value_t ct = headers_get_value(js, headers, "content-type"); if (is_err(ct) || vtype(ct) == kTypeString) return ct; return d && d->body_type ? js_mkstr(js, d->body_type, strlen(d->body_type)) : js_mkundef(); } static void strip_utf8_bom(const uint8_t **data, size_t *size) { if (!data || !*data || !size || *size < 3) return; if ((*data)[0] == 0xEF && (*data)[1] == 0xBB && (*data)[2] == 0xBF) { *data += 3; *size -= 3; } } static void resolve_body_promise( ant_t *js, ant_value_t promise, const uint8_t *data, size_t size, const char *body_type, int mode, bool has_body ) { switch (mode) { case BODY_TEXT: { ant_value_t str = (data && size > 0) ? js_mkstr(js, (const char *)data, size) : js_mkstr(js, "", 0); js_resolve_promise(js, promise, str); break; } case BODY_JSON: { const uint8_t *json_data = data; size_t json_size = size; strip_utf8_bom(&json_data, &json_size); ant_value_t str = (json_data && json_size > 0) ? js_mkstr(js, (const char *)json_data, json_size) : js_mkstr(js, "", 0); ant_value_t parsed = json_parse_value(js, str); if (is_err(parsed)) js_reject_promise(js, promise, parsed); else js_resolve_promise(js, promise, parsed); break; } case BODY_ARRAYBUFFER: { ant_value_t ab = create_arraybuffer_copy(js, data, size); if (is_err(ab)) js_reject_promise(js, promise, ab); else js_resolve_promise(js, promise, ab); break; } case BODY_BLOB: { const char *type = body_type ? body_type : ""; ant_value_t blob = blob_create(js, data, size, type); if (is_err(blob)) js_reject_promise(js, promise, blob); else js_resolve_promise(js, promise, blob); break; } case BODY_BYTES: { ArrayBufferData *ab = create_array_buffer_data(js, size); if (!ab) { js_reject_promise(js, promise, js_mkerr(js, "out of memory")); break; } if (data && size > 0) memcpy(ab->data, data, size); ant_value_t bytes = create_typed_array(js, TYPED_ARRAY_UINT8, ab, 0, size, js->builtins.typedarray_protos[TYPED_ARRAY_UINT8]); if (is_err(bytes)) js_reject_promise(js, promise, bytes); else js_resolve_promise(js, promise, bytes); break; } case BODY_FORMDATA: { ant_value_t fd = formdata_parse_body(js, data, size, body_type, has_body); if (is_err(fd)) js_reject_promise(js, promise, fd); else js_resolve_promise(js, promise, fd); break; }} } static bool response_chunk_is_uint8_array(ant_value_t chunk, TypedArrayData **out_ta) { if (!is_object_type(chunk)) return false; TypedArrayData *ta = buffer_get_typedarray_data(chunk); if (!Ant_Buffer_ViewIsLive(ta)) return false; if (ta->type != TYPED_ARRAY_UINT8) return false; *out_ta = ta; return true; } static uint8_t *concat_uint8_chunks( ant_t *js, ant_value_t chunks, size_t *out_size, ant_value_t *err_out ) { ant_offset_t n = js_arr_len(js, chunks); size_t total = 0; size_t pos = 0; uint8_t *buf = NULL; TypedArrayData *ta = NULL; *out_size = 0; *err_out = js_mkundef(); for (ant_offset_t i = 0; i < n; i++) { ant_value_t chunk = js_arr_get(js, chunks, i); if (!response_chunk_is_uint8_array(chunk, &ta)) { *err_out = js_mkerr_typed(js, JS_ERR_TYPE, "Response body stream chunk must be a Uint8Array"); return NULL; } total += ta->byte_length; } buf = total > 0 ? malloc(total) : NULL; if (total > 0 && !buf) { *err_out = js_mkerr(js, "out of memory"); return NULL; } for (ant_offset_t i = 0; i < n; i++) { ant_value_t chunk = js_arr_get(js, chunks, i); if (!response_chunk_is_uint8_array(chunk, &ta)) { free(buf); *err_out = js_mkerr_typed(js, JS_ERR_TYPE, "Response body stream chunk must be a Uint8Array"); return NULL; } uint8_t *bytes; size_t size; if (!Ant_Buffer_GetViewBytes(ta, &bytes, &size) || size == 0) continue; memcpy(buf + pos, bytes, size); pos += size; } *out_size = pos; return buf; } static ant_value_t stream_body_read(ant_params_t); static ant_value_t stream_body_rejected(ant_params_t) { ant_value_t state = js_get_slot(js->current_func, SLOT_DATA); ant_value_t promise = js_get(js, state, "promise"); ant_value_t reason = (nargs > 0) ? args[0] : js_mkundef(); js_reject_promise(js, promise, reason); return js_mkundef(); } static void stream_schedule_next_read(ant_t *js, ant_value_t state, ant_value_t reader) { ant_value_t next_p = rs_default_reader_read(js, reader); ant_value_t fulfill = js_heavy_mkfun(js, stream_body_read, state); ant_value_t reject = js_heavy_mkfun(js, stream_body_rejected, state); Ant_Promise_Observe(js, next_p, fulfill, reject); } static ant_value_t stream_body_read(ant_params_t) { ant_value_t state = js_get_slot(js->current_func, SLOT_DATA); ant_value_t result = (nargs > 0) ? args[0] : js_mkundef(); ant_value_t promise = js_get(js, state, "promise"); ant_value_t reader = js_get(js, state, "reader"); ant_value_t chunks = js_get(js, state, "chunks"); int mode = (int)js_getnum(js_get(js, state, "mode")); ant_value_t done_val = js_get(js, result, "done"); ant_value_t value = js_get(js, result, "value"); if (vtype(done_val) == kTypeBool && done_val == js_true) { size_t size = 0; ant_value_t chunk_err = js_mkundef(); uint8_t *data = concat_uint8_chunks(js, chunks, &size, &chunk_err); if (is_err(chunk_err)) { js_reject_promise(js, promise, chunk_err); return js_mkundef(); } ant_value_t type_v = js_get(js, state, "type"); const char *body_type = (vtype(type_v) == kTypeString) ? js_getstr(js, type_v, NULL) : NULL; resolve_body_promise(js, promise, data, size, body_type, mode, true); free(data); return js_mkundef(); } if (vtype(value) != kTypeUndefined && vtype(value) != kTypeNull) js_arr_push(js, chunks, value); stream_schedule_next_read(js, state, reader); return js_mkundef(); } static ant_value_t consume_body_from_stream( ant_t *js, ant_value_t stream, ant_value_t promise, int mode, const char *body_type ) { ant_value_t reader_args[1] = { stream }; ant_value_t reader = js_construct_native(js, js_rs_reader_ctor, reader_args, 1); if (is_err(reader)) { js_reject_promise(js, promise, reader); return promise; } ant_value_t state = Ant_Object_CreateBare(js); js_set(js, state, "promise", promise); js_set(js, state, "reader", reader); js_set(js, state, "chunks", js_mkarr(js)); js_set(js, state, "mode", js_mknum(mode)); js_set(js, state, "type", body_type ? js_mkstr(js, body_type, strlen(body_type)) : js_mkundef()); stream_schedule_next_read(js, state, reader); return promise; } static ant_value_t consume_body(ant_t *js, int mode) { ant_value_t this = js_getthis(js); response_data_t *d = response_get_data(this); ant_value_t promise = js_mkpromise(js); ant_value_t type_value = js_mkundef(); ant_value_t stream = 0; const char *body_type = NULL; if (!d) { js_reject_promise(js, promise, js_mkerr_typed(js, JS_ERR_TYPE, "Invalid Response object")); return promise; } stream = js_get_slot(this, SLOT_RESPONSE_BODY_STREAM); if (d->body_used || (rs_is_stream(stream) && rs_stream_unusable(stream))) { js_reject_promise(js, promise, js_mkerr_typed(js, JS_ERR_TYPE, "body stream is disturbed or locked")); return promise; } type_value = response_effective_body_type(js, this, d); if (is_err(type_value)) { js_reject_promise(js, promise, type_value); return promise; } GC_ROOT_SAVE(root_mark, js); if (!gc_push_root(js, &type_value)) { GC_ROOT_RESTORE(js, root_mark); js_reject_promise(js, promise, js_mkerr(js, "out of memory")); return promise; } if (vtype(type_value) == kTypeString) body_type = js_getstr(js, type_value, NULL); if (!d->has_body) { resolve_body_promise(js, promise, NULL, 0, body_type, mode, false); GC_ROOT_RESTORE(js, root_mark); return promise; } d->body_used = true; if (rs_is_stream(stream)) { ant_value_t result = consume_body_from_stream(js, stream, promise, mode, body_type); GC_ROOT_RESTORE(js, root_mark); return result; } resolve_body_promise(js, promise, d->body_data, d->body_size, body_type, mode, true); GC_ROOT_RESTORE(js, root_mark); return promise; } static ant_value_t js_res_text(ant_params_t) { return consume_body(js, BODY_TEXT); } static ant_value_t js_res_json(ant_params_t) { return consume_body(js, BODY_JSON); } static ant_value_t js_res_array_buffer(ant_params_t) { return consume_body(js, BODY_ARRAYBUFFER); } static ant_value_t js_res_blob(ant_params_t) { return consume_body(js, BODY_BLOB); } static ant_value_t js_res_bytes(ant_params_t) { return consume_body(js, BODY_BYTES); } static ant_value_t js_res_form_data(ant_params_t) { return consume_body(js, BODY_FORMDATA); } static bool is_null_body_status(int status) { return status == 101 || status == 103 || status == 204 || status == 205 || status == 304; } static bool is_redirect_status(int status) { return status == 301 || status == 302 || status == 303 || status == 307 || status == 308; } static bool is_ok_status(int status) { return status >= 200 && status <= 299; } static bool is_valid_reason_phrase(const char *str, size_t len) { utf8proc_int32_t cp = 0; utf8proc_ssize_t n = 0; size_t pos = 0; while (pos < len) { n = utf8_next((const utf8proc_uint8_t *)(str + pos), (utf8proc_ssize_t)(len - pos), &cp); if (cp > 0xFF) return false; if (cp == '\r' || cp == '\n') return false; pos += (size_t)n; } return true; } static ant_value_t response_init_status(ant_t *js, ant_value_t init, response_data_t *resp) { ant_value_t status_v = js_getprop_fallback(js, init, "status"); double status_num = 200; if (is_err(status_v)) return status_v; if (vtype(status_v) != kTypeUndefined) { status_num = (vtype(status_v) == kTypeNumber) ? js_getnum(status_v) : js_to_number(js, status_v); } if (status_num < 200 || status_num > 599 || status_num != (int)status_num) { return js_mkerr_typed(js, JS_ERR_RANGE, "Failed to construct 'Response': status must be in the range 200-599"); } resp->status = (int)status_num; return js_mkundef(); } static ant_value_t response_init_status_text(ant_t *js, ant_value_t init, response_data_t *resp) { ant_value_t status_text_v = js_getprop_fallback(js, init, "statusText"); size_t len = 0; const char *status_text = NULL; char *dup = NULL; if (is_err(status_text_v) || vtype(status_text_v) == kTypeUndefined) return status_text_v; if (vtype(status_text_v) != kTypeString) { status_text_v = js_tostring_val(js, status_text_v); if (is_err(status_text_v)) return status_text_v; } status_text = js_getstr(js, status_text_v, &len); if (!is_valid_reason_phrase(status_text, len)) { return js_mkerr_typed(js, JS_ERR_TYPE, "Failed to construct 'Response': Invalid statusText"); } dup = strdup(status_text); if (!dup) return js_mkerr(js, "out of memory"); free(resp->status_text); resp->status_text = dup; return js_mkundef(); } static bool response_init_direct_headers( ant_t *js, ant_value_t init, ant_value_t *headers_out, const ant_shape_t **shape_out ) { if (vtype(init) != kTypeObject) return false; ant_object_t *ptr = js_obj_ptr(init); const ant_shape_prop_t *prop = ptr && ptr->shape && ptr->prop_count == 1 ? ant_shape_prop_at(ptr->shape, 0) : NULL; if (!ptr || ptr->flags.is_exotic || ptr->proto != js->sym.object_proto || !prop || prop->type != ANT_SHAPE_KEY_STRING || prop->has_getter || prop->has_setter || intern_length(prop->key.interned) != 7 || memcmp(prop->key.interned, "headers", 7) != 0) return false; *headers_out = ant_object_prop_get_unchecked(ptr, 0); *shape_out = ptr->shape; return true; } static bool response_init_later_fields_absent( ant_t *js, ant_value_t init, const ant_shape_t *original_shape ) { if (vtype(init) != kTypeObject) return false; ant_object_t *ptr = js_obj_ptr(init); ant_object_t *object_proto = js_obj_ptr(js->sym.object_proto); if (!ptr || ptr->flags.is_exotic || ptr->shape != original_shape || ptr->proto != js->sym.object_proto || !object_proto || object_proto->flags.is_exotic || vtype(object_proto->proto) != kTypeNull) return false; const char *status = intern_find(js, "status", 6); const char *status_text = intern_find(js, "statusText", 10); return (!status || ant_shape_lookup_interned(object_proto->shape, status) < 0) && (!status_text || ant_shape_lookup_interned(object_proto->shape, status_text) < 0); } static ant_value_t response_apply_body( ant_t *js, ant_value_t resp_obj, ant_value_t headers, response_data_t *resp, ant_value_t body_val, const char *content_type_override ) { ant_value_t body_err = js_mkundef(); ant_value_t body_stream = js_mkundef(); uint8_t *body_data = NULL; size_t body_size = 0; char *body_type = NULL; if (vtype(body_val) == kTypeNull || vtype(body_val) == kTypeUndefined) return js_mkundef(); if (vtype(body_val) == kTypeString) { if (is_null_body_status(resp->status)) { return js_mkerr_typed(js, JS_ERR_TYPE, "Failed to construct 'Response': Response with null body status cannot have body"); } const char *body_string = js_getstr(js, body_val, &body_size); if (resp->body_storage == RESPONSE_BODY_STORAGE_OWNED) { free(resp->body_data); free(resp->body_type); } resp->body_data = (uint8_t *)body_string; resp->body_size = body_size; resp->body_type = (char *)RESPONSE_TEXT_CONTENT_TYPE; resp->body_storage = RESPONSE_BODY_STORAGE_BORROWED_STRING; resp->body_is_stream = false; resp->has_body = true; js_set_slot_wb(js, resp_obj, SLOT_DATA, body_val); const char *header_type = content_type_override ? content_type_override : resp->body_type; if (headers_is_headers(headers) ? !response_apply_content_type_data(headers_get_data(headers), header_type) : !response_apply_pending_content_type(resp, header_type)) return js_mkerr(js, "out of memory"); return js_mkundef(); } if (!extract_body(js, body_val, &body_data, &body_size, &body_type, &body_stream, &body_err)) { return is_err(body_err) ? body_err : js_mkerr(js, "Failed to extract body"); } if (is_null_body_status(resp->status)) { free(body_data); free(body_type); return js_mkerr_typed(js, JS_ERR_TYPE, "Failed to construct 'Response': Response with null body status cannot have body"); } if (resp->body_storage == RESPONSE_BODY_STORAGE_OWNED) { free(resp->body_data); free(resp->body_type); } resp->body_data = body_data; resp->body_size = body_size; resp->body_type = body_type; resp->body_storage = (body_data || body_type) ? RESPONSE_BODY_STORAGE_OWNED : RESPONSE_BODY_STORAGE_NONE; resp->body_is_stream = rs_is_stream(body_stream); resp->has_body = true; if (resp->body_is_stream) js_set_slot_wb(js, resp_obj, SLOT_RESPONSE_BODY_STREAM, body_stream); const char *header_type = content_type_override ? content_type_override : body_type; if (headers_is_headers(headers) ? !response_apply_content_type_data(headers_get_data(headers), header_type) : !response_apply_pending_content_type(resp, header_type)) return js_mkerr(js, "out of memory"); return js_mkundef(); } static ant_value_t response_init_common( ant_t *js, ant_value_t resp_obj, ant_value_t init, ant_value_t body_val, bool immutable_headers, const char *content_type_override ) { response_data_t *resp = response_get_data(resp_obj); ant_value_t headers = js_get_slot(resp_obj, SLOT_RESPONSE_HEADERS); ant_value_t step = js_mkundef(); const ant_shape_t *direct_init_shape = NULL; if (!resp) return js_mkerr_typed(js, JS_ERR_TYPE, "Invalid Response object"); resp->headers_immutable = immutable_headers; if (vtype(init) != kTypeUndefined) { ant_value_t init_headers = js_mkundef(); bool direct_headers = response_init_direct_headers( js, init, &init_headers, &direct_init_shape); if (!direct_headers) init_headers = js_getprop_fallback(js, init, "headers"); if (is_err(init_headers)) return init_headers; if (vtype(init_headers) != kTypeUndefined) { resp->pending_headers = headers_data_create(); if (!resp->pending_headers) return js_mkerr(js, "out of memory"); step = headers_data_init_from(js, resp->pending_headers, init_headers); if (is_err(step)) return step; } if (!direct_headers || !response_init_later_fields_absent(js, init, direct_init_shape)) { step = response_init_status(js, init, resp); if (is_err(step)) return step; step = response_init_status_text(js, init, resp); if (is_err(step)) return step; } } return response_apply_body( js, resp_obj, headers, resp, body_val, content_type_override); } static ant_value_t response_init_object( ant_t *js, ant_value_t obj, bool immutable_headers ) { response_data_t *resp = data_new(); if (!resp) return js_mkerr(js, "out of memory"); js_reserve_slots(obj, 3); resp->headers_immutable = immutable_headers; js_set_slot(obj, SLOT_BRAND, js_mknum(BRAND_RESPONSE)); js_set_native(obj, resp, RESPONSE_NATIVE_TAG); js_set_finalizer(obj, response_finalize); js_set_slot_wb(js, obj, SLOT_RESPONSE_HEADERS, js_mkundef()); js_set_slot_wb(js, obj, SLOT_RESPONSE_BODY_STREAM, js_mkundef()); return obj; } static ant_value_t response_new(ant_t *js, bool immutable_headers) { ant_value_t obj = Ant_Object_CreateBare(js); js_set_proto_init(obj, js->builtins.response_proto); return response_init_object(js, obj, immutable_headers); } static ant_value_t js_response_ctor(ant_params_t) { ant_value_t body = (nargs >= 1) ? args[0] : js_mknull(); ant_value_t init = (nargs >= 2 && vtype(args[1]) != kTypeUndefined) ? args[1] : js_mkundef(); ant_value_t obj = 0; ant_value_t step = 0; if (vtype(call_new_target) == kTypeUndefined) { return js_mkerr_typed(js, JS_ERR_TYPE, "Response constructor requires 'new'"); } obj = response_init_object(js, js->this_val, false); if (is_err(obj)) return obj; step = response_init_common(js, obj, init, body, false, NULL); if (is_err(step)) { response_clear_and_free(obj, response_get_data(obj)); return step; } return obj; } static ant_value_t response_create_static( ant_t *js, const char *type, int status, const char *status_text, bool immutable_headers ) { ant_value_t obj = response_new(js, immutable_headers); response_data_t *resp = NULL; if (is_err(obj)) return obj; resp = response_get_data(obj); free(resp->type); resp->type = strdup(type ? type : "default"); if (!resp->type) { response_clear_and_free(obj, resp); return js_mkerr(js, "out of memory"); } resp->status = status; free(resp->status_text); resp->status_text = strdup(status_text ? status_text : ""); if (!resp->status_text) { response_clear_and_free(obj, resp); return js_mkerr(js, "out of memory"); } return obj; } static ant_value_t js_response_error(ant_params_t) { ant_value_t obj = response_create_static(js, "error", 0, "", true); if (is_err(obj)) return obj; return obj; } static ant_value_t js_response_redirect(ant_params_t) { ant_value_t url_v = (nargs >= 1) ? args[0] : js_mkundef(); ant_value_t status_v = (nargs >= 2) ? args[1] : js_mknum(302); ant_value_t obj = 0; ant_value_t headers = 0; const char *url_str = NULL; int status = 302; url_state_t parsed = {0}; char *href = NULL; if (vtype(url_v) != kTypeString) { url_v = js_tostring_val(js, url_v); if (is_err(url_v)) return url_v; } status = (vtype(status_v) == kTypeNumber) ? (int)js_getnum(status_v) : (int)js_to_number(js, status_v); if (!is_redirect_status(status)) { return js_mkerr_typed(js, JS_ERR_RANGE, "Response.redirect status must be 301, 302, 303, 307, or 308"); } url_str = js_getstr(js, url_v, NULL); if (parse_url_to_state(url_str, NULL, &parsed) != 0) { url_state_clear(&parsed); return js_mkerr_typed(js, JS_ERR_TYPE, "Failed to construct 'Response': Invalid URL"); } href = build_href(&parsed); if (!href) { url_state_clear(&parsed); return js_mkerr(js, "out of memory"); } obj = response_create_static(js, "default", status, "", true); if (is_err(obj)) { free(href); url_state_clear(&parsed); return obj; } headers = response_materialize_headers(js, obj); if (is_err(headers)) { free(href); url_state_clear(&parsed); return headers; } headers_set_immutable(headers, false); if (!headers_data_append_if_missing(headers_get_data(headers), "location", href)) { headers_set_immutable(headers, true); free(href); url_state_clear(&parsed); return js_mkerr(js, "out of memory"); } headers_set_immutable(headers, true); free(href); url_state_clear(&parsed); return obj; } static ant_value_t js_response_json_static(ant_params_t) { ant_value_t init = (nargs >= 2 && vtype(args[1]) != kTypeUndefined) ? args[1] : js_mkundef(); ant_value_t stringify = 0; ant_value_t obj = 0; ant_value_t step = 0; if (nargs < 1) return js_mkerr_typed(js, JS_ERR_TYPE, "Response.json requires 1 argument"); stringify = json_stringify_value(js, args[0]); if (is_err(stringify)) return stringify; if (vtype(stringify) == kTypeUndefined) { return js_mkerr_typed(js, JS_ERR_TYPE, "Response.json data is not JSON serializable"); } obj = response_new(js, false); if (is_err(obj)) return obj; step = response_init_common( js, obj, init, stringify, false, "application/json"); if (is_err(step)) { response_clear_and_free(obj, response_get_data(obj)); return step; } return obj; } static ant_value_t res_body_pull(ant_params_t) { ant_value_t resp_obj = js_get_slot(js->current_func, SLOT_DATA); response_data_t *d = response_get_data(resp_obj); ant_value_t ctrl = (nargs > 0) ? args[0] : js_mkundef(); if (d && d->body_data && d->body_size > 0) { ArrayBufferData *ab = create_array_buffer_data(js, d->body_size); if (!ab) return js_mkerr(js, "out of memory"); memcpy(ab->data, d->body_data, d->body_size); ant_value_t chunk = create_typed_array(js, TYPED_ARRAY_UINT8, ab, 0, d->body_size, js->builtins.typedarray_protos[TYPED_ARRAY_UINT8]); if (is_err(chunk)) return chunk; ant_value_t enqueued = rs_controller_enqueue(js, ctrl, chunk); if (is_err(enqueued)) return enqueued; } rs_controller_close(js, ctrl); return js_mkundef(); } #define RES_GETTER_START(name) \ static ant_value_t js_res_get_##name(ant_params_t) { \ ant_value_t this = js_getthis(js); \ response_data_t *d = response_get_data(this); \ if (!d) return js_mkerr_typed(js, JS_ERR_TYPE, "Invalid Response object"); #define RES_GETTER_END } RES_GETTER_START(type) const char *type = d->type ? d->type : "default"; return js_mkstr(js, type, strlen(type)); RES_GETTER_END RES_GETTER_START(url) char *href = NULL; char *hash = NULL; ant_value_t ret = 0; if (!d->has_url) return js_mkstr(js, "", 0); href = build_href(&d->url); if (!href) return js_mkstr(js, "", 0); hash = strchr(href, '#'); if (hash) *hash = '\0'; ret = js_mkstr(js, href, strlen(href)); free(href); return ret; RES_GETTER_END RES_GETTER_START(redirected) return js_bool(d->url_list_size > 1); RES_GETTER_END RES_GETTER_START(status) return js_mknum(d->status); RES_GETTER_END RES_GETTER_START(ok) return js_bool(is_ok_status(d->status)); RES_GETTER_END RES_GETTER_START(status_text) const char *status_text = d->status_text ? d->status_text : ""; return js_mkstr(js, status_text, strlen(status_text)); RES_GETTER_END RES_GETTER_START(headers) return response_materialize_headers(js, this); RES_GETTER_END RES_GETTER_START(body) ant_value_t stored_stream = js_get_slot(this, SLOT_RESPONSE_BODY_STREAM); if (!d->has_body) return js_mknull(); if (rs_is_stream(stored_stream)) return stored_stream; if (d->body_used) return js_mknull(); ant_value_t pull = js_heavy_mkfun(js, res_body_pull, this); ant_value_t stream = rs_create_stream(js, pull, js_mkundef(), 1.0); if (!is_err(stream)) js_set_slot_wb(js, this, SLOT_RESPONSE_BODY_STREAM, stream); return stream; RES_GETTER_END RES_GETTER_START(body_used) ant_value_t stored_stream = js_get_slot(this, SLOT_RESPONSE_BODY_STREAM); bool used = d->body_used || (rs_is_stream(stored_stream) && rs_stream_disturbed(stored_stream)); return js_bool(used); RES_GETTER_END #undef RES_GETTER_START #undef RES_GETTER_END static ant_value_t response_inspect_finish(ant_t *js, ant_value_t this_obj, ant_value_t body_obj) { ant_value_t tag_val = js_get_sym(js, this_obj, js->sym.toStringTag_sym); const char *tag = vtype(tag_val) == kTypeString ? js_getstr(js, tag_val, NULL) : "Response"; js_inspect_builder_t builder; if (!js_inspect_builder_init_dynamic(&builder, js, 128)) { return js_mkerr(js, "out of memory"); } bool ok = js_inspect_header_for(&builder, body_obj, "%s", tag); if (ok) ok = js_inspect_object_body(&builder, body_obj); if (ok) ok = js_inspect_close(&builder); if (!ok) { js_inspect_builder_dispose(&builder); return js_mkerr(js, "out of memory"); } return js_inspect_builder_result(&builder); } // TODO: make dry static bool response_inspect_set( ant_t *js, ant_value_t obj, const char *key, ant_value_t value, ant_value_t *err_out ) { if (is_err(value)) { *err_out = value; return false; } js_set(js, obj, key, value); return true; } static ant_value_t response_inspect(ant_params_t) { ant_value_t this_obj = js_getthis(js); ant_value_t out = Ant_Object_CreateBare(js); ant_value_t err = 0; if (!response_inspect_set(js, out, "type", js_res_get_type(js, NULL, 0, js_mkundef()), &err)) return err; if (!response_inspect_set(js, out, "url", js_res_get_url(js, NULL, 0, js_mkundef()), &err)) return err; if (!response_inspect_set(js, out, "redirected", js_res_get_redirected(js, NULL, 0, js_mkundef()), &err)) return err; if (!response_inspect_set(js, out, "status", js_res_get_status(js, NULL, 0, js_mkundef()), &err)) return err; if (!response_inspect_set(js, out, "ok", js_res_get_ok(js, NULL, 0, js_mkundef()), &err)) return err; if (!response_inspect_set(js, out, "statusText", js_res_get_status_text(js, NULL, 0, js_mkundef()), &err)) return err; if (!response_inspect_set(js, out, "headers", js_res_get_headers(js, NULL, 0, js_mkundef()), &err)) return err; return response_inspect_finish(js, this_obj, out); } static ant_value_t js_response_clone(ant_params_t) { ant_value_t this = js_getthis(js); response_data_t *d = response_get_data(this); response_data_t *nd = NULL; ant_value_t src_headers = 0; ant_value_t new_headers = 0; ant_value_t obj = 0; ant_value_t src_stream = 0; if (!d) return js_mkerr_typed(js, JS_ERR_TYPE, "Invalid Response object"); if (d->body_used) { return js_mkerr_typed(js, JS_ERR_TYPE, "Cannot clone a Response whose body is unusable"); } nd = data_dup(d); if (!nd) return js_mkerr(js, "out of memory"); src_headers = js_get_slot(this, SLOT_RESPONSE_HEADERS); new_headers = js_mkundef(); if (headers_is_headers(src_headers)) { new_headers = headers_create_empty(js); if (is_err(new_headers)) { data_free(nd); return new_headers; } if (!headers_copy_from(new_headers, src_headers)) { data_free(nd); return js_mkerr(js, "out of memory"); } headers_set_immutable(new_headers, headers_is_immutable(src_headers)); } obj = Ant_Object_CreateBare(js); js_reserve_slots(obj, 3); js_set_proto_init(obj, js->builtins.response_proto); js_set_slot(obj, SLOT_BRAND, js_mknum(BRAND_RESPONSE)); js_set_native(obj, nd, RESPONSE_NATIVE_TAG); js_set_finalizer(obj, response_finalize); js_set_slot_wb(js, obj, SLOT_RESPONSE_HEADERS, new_headers); js_set_slot_wb(js, obj, SLOT_RESPONSE_BODY_STREAM, js_mkundef()); src_stream = js_get_slot(this, SLOT_RESPONSE_BODY_STREAM); if (!rs_is_stream(src_stream)) return obj; ant_value_t branches = readable_stream_tee(js, src_stream); if (!is_err(branches) && vtype(branches) == kTypeArray) { ant_value_t b1 = js_arr_get(js, branches, 0); ant_value_t b2 = js_arr_get(js, branches, 1); js_set_slot_wb(js, this, SLOT_RESPONSE_BODY_STREAM, b1); js_set_slot_wb(js, obj, SLOT_RESPONSE_BODY_STREAM, b2); } return obj; } ant_value_t response_create_fetched( ant_t *js, int status, const char *status_text, const char *url, int url_list_size, ant_value_t headers_obj, const uint8_t *body, size_t body_len, ant_value_t body_stream, const char *body_type ) { ant_value_t obj = response_new(js, true); ant_value_t headers = 0; response_data_t *resp = NULL; url_state_t parsed = {0}; if (is_err(obj)) return obj; resp = response_get_data(obj); resp->status = status; free(resp->status_text); resp->status_text = strdup(status_text ? status_text : ""); if (!resp->status_text) { response_clear_and_free(obj, resp); return js_mkerr(js, "out of memory"); } if (url && parse_url_to_state(url, NULL, &parsed) == 0) { url_state_clear(&resp->url); resp->url = parsed; resp->has_url = true; resp->url_list_size = url_list_size > 0 ? url_list_size : 1; } else url_state_clear(&parsed); if (rs_is_stream(body_stream)) { resp->body_is_stream = true; resp->has_body = true; js_set_slot_wb(js, obj, SLOT_RESPONSE_BODY_STREAM, body_stream); } else { if (body_len > 0) { resp->body_data = malloc(body_len); if (!resp->body_data) { response_clear_and_free(obj, resp); return js_mkerr(js, "out of memory"); } memcpy(resp->body_data, body, body_len); } resp->body_size = body_len; resp->body_is_stream = false; resp->has_body = body || body_len > 0; } resp->body_type = body_type ? strdup(body_type) : NULL; resp->body_storage = (resp->body_data || resp->body_type) ? RESPONSE_BODY_STORAGE_OWNED : RESPONSE_BODY_STORAGE_NONE; if (body_type && !resp->body_type) { response_clear_and_free(obj, resp); return js_mkerr(js, "out of memory"); } if (is_object_type(headers_obj)) { headers = headers_obj; headers_set_immutable(headers, true); js_set_slot_wb(js, obj, SLOT_RESPONSE_HEADERS, headers); } return obj; } void init_response_module(ant_t *js) { ant_value_t g = js_glob(js); ant_value_t ctor = 0; js->builtins.response_proto = Ant_Object_CreateBare(js); js_set(js, js->builtins.response_proto, "text", Ant_Function_Create(js_res_text)); js_set(js, js->builtins.response_proto, "json", Ant_Function_Create(js_res_json)); js_set(js, js->builtins.response_proto, "arrayBuffer", Ant_Function_Create(js_res_array_buffer)); js_set(js, js->builtins.response_proto, "blob", Ant_Function_Create(js_res_blob)); js_set(js, js->builtins.response_proto, "formData", Ant_Function_Create(js_res_form_data)); js_set(js, js->builtins.response_proto, "bytes", Ant_Function_Create(js_res_bytes)); js_set(js, js->builtins.response_proto, "clone", Ant_Function_Create(js_response_clone)); #define GETTER(prop, fn) \ js_set_getter_desc(js, js->builtins.response_proto, prop, sizeof(prop) - 1, Ant_Function_Create(js_res_get_##fn), JS_DESC_C) GETTER("type", type); GETTER("url", url); GETTER("redirected", redirected); GETTER("status", status); GETTER("ok", ok); GETTER("statusText", status_text); GETTER("headers", headers); GETTER("body", body); GETTER("bodyUsed", body_used); #undef GETTER js_set_sym(js, js->builtins.response_proto, js->sym.inspect_sym, Ant_Function_Create(response_inspect)); js_set_tostringtag(js, js->builtins.response_proto, js_mkstr(js, "Response", 8)); ctor = Ant_Function_CreateIntrinsicConstructor(js, js_response_ctor, js->builtins.response_proto, "Response", 0); js_set(js, ctor, "error", Ant_Function_Create(js_response_error)); js_set(js, ctor, "redirect", Ant_Function_CreateWithArity(js_response_redirect, 1)); js_set(js, ctor, "json", Ant_Function_CreateWithArity(js_response_json_static, 1)); js_set(js, g, "Response", ctor); js_set_descriptor(js, g, "Response", 8, JS_DESC_W | JS_DESC_C); }