xbintsc 0.6.20 → 0.6.22

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (93) hide show
  1. package/dist/src/cli/help.d.ts +1 -1
  2. package/dist/src/cli/main.js +1 -0
  3. package/dist/src/cli/main.js.map +1 -1
  4. package/dist/src/driver/build-key.d.ts +3 -0
  5. package/dist/src/driver/build-key.js +3 -1
  6. package/dist/src/driver/build-key.js.map +1 -1
  7. package/dist/src/driver/compiler.js +11 -0
  8. package/dist/src/driver/compiler.js.map +1 -1
  9. package/dist/src/driver/config.d.ts +12 -0
  10. package/dist/src/driver/config.js +22 -0
  11. package/dist/src/driver/config.js.map +1 -1
  12. package/dist/src/driver/index.d.ts +2 -1
  13. package/dist/src/driver/index.js +1 -0
  14. package/dist/src/driver/index.js.map +1 -1
  15. package/dist/src/driver/options.d.ts +8 -1
  16. package/dist/src/driver/storage.d.ts +34 -0
  17. package/dist/src/driver/storage.js +67 -0
  18. package/dist/src/driver/storage.js.map +1 -0
  19. package/dist/src/driver/version.d.ts +1 -1
  20. package/dist/src/driver/version.js +1 -1
  21. package/dist/src/extensions/gui/features.d.ts +1 -1
  22. package/dist/src/extensions/gui/features.js +2 -2
  23. package/dist/src/extensions/gui/features.js.map +1 -1
  24. package/dist/src/extensions/gui/index.js +3 -1
  25. package/dist/src/extensions/gui/index.js.map +1 -1
  26. package/dist/src/extensions/registry.d.ts +4 -1
  27. package/dist/src/extensions/registry.js +8 -2
  28. package/dist/src/extensions/registry.js.map +1 -1
  29. package/dist/src/extensions/storage.d.ts +22 -0
  30. package/dist/src/extensions/storage.js +50 -0
  31. package/dist/src/extensions/storage.js.map +1 -0
  32. package/dist/tests/driver/config.test.js +31 -0
  33. package/dist/tests/driver/config.test.js.map +1 -1
  34. package/dist/tests/driver/link-features.test.js +4 -2
  35. package/dist/tests/driver/link-features.test.js.map +1 -1
  36. package/dist/tests/driver/storage.test.d.ts +1 -0
  37. package/dist/tests/driver/storage.test.js +29 -0
  38. package/dist/tests/driver/storage.test.js.map +1 -0
  39. package/dist/tests/e2e/storage.test.d.ts +7 -0
  40. package/dist/tests/e2e/storage.test.js +86 -0
  41. package/dist/tests/e2e/storage.test.js.map +1 -0
  42. package/dist/tests/extensions/gui-features.test.js +1 -1
  43. package/dist/tests/extensions/gui-features.test.js.map +1 -1
  44. package/dist/tests/extensions/storage.test.d.ts +1 -0
  45. package/dist/tests/extensions/storage.test.js +50 -0
  46. package/dist/tests/extensions/storage.test.js.map +1 -0
  47. package/doc/ai/cli.md +2 -0
  48. package/doc/ai/extensions.md +26 -0
  49. package/doc/ai/zh-CN/cli.md +2 -0
  50. package/doc/ai/zh-CN/extensions.md +23 -0
  51. package/doc/gui/build.md +3 -3
  52. package/doc/gui/media.md +4 -4
  53. package/doc/gui.md +2 -2
  54. package/doc/implemented/extensions.md +1 -1
  55. package/doc/implemented/storage.md +64 -0
  56. package/doc/implemented.md +2 -0
  57. package/doc/xbintsc.config.schema.json +16 -1
  58. package/doc/zh-CN/gui/build.md +3 -3
  59. package/doc/zh-CN/gui/media.md +3 -3
  60. package/doc/zh-CN/gui.md +2 -2
  61. package/doc/zh-CN/implemented/extensions.md +1 -1
  62. package/doc/zh-CN/implemented/storage.md +51 -0
  63. package/doc/zh-CN/implemented.md +2 -0
  64. package/package.json +7 -7
  65. package/runtime/ext_gui/dom_api_form.cpp +10 -0
  66. package/runtime/ext_gui/gui_media.cpp +1 -1
  67. package/runtime/ext_gui/media.cpp +1 -1
  68. package/runtime/ext_gui/media_api.h +2 -2
  69. package/runtime/xt_storage/indexed_db.c +408 -0
  70. package/runtime/xt_storage/indexed_db_internal.h +26 -0
  71. package/runtime/xt_storage/indexed_db_store.c +305 -0
  72. package/runtime/xt_storage/sqlite3/sqlite3.c +271131 -0
  73. package/runtime/xt_storage/sqlite3/sqlite3.h +14447 -0
  74. package/runtime/xt_storage/storage.c +209 -0
  75. package/runtime/xt_storage/storage_internal.h +66 -0
  76. package/scripts/build-gui.ts +1 -1
  77. package/scripts/build-media.ts +2 -2
  78. package/scripts/check-file-length.ts +4 -0
  79. package/src/cli/main.ts +1 -0
  80. package/src/driver/build-key.ts +6 -1
  81. package/src/driver/compiler.ts +13 -0
  82. package/src/driver/config.ts +35 -0
  83. package/src/driver/index.ts +8 -0
  84. package/src/driver/options.ts +8 -1
  85. package/src/driver/storage.ts +84 -0
  86. package/src/driver/version.ts +1 -1
  87. package/src/extensions/gui/features.ts +2 -2
  88. package/src/extensions/gui/index.ts +3 -1
  89. package/src/extensions/registry.ts +8 -2
  90. package/src/extensions/storage.ts +57 -0
  91. /package/runtime/{ext_media → xt_media}/decode_audio.cpp +0 -0
  92. /package/runtime/{ext_media → xt_media}/media.cpp +0 -0
  93. /package/runtime/{ext_media → xt_media}/media_bridge.c +0 -0
@@ -0,0 +1,209 @@
1
+ /*
2
+ * xbintsc `storage` extension — Web Storage (localStorage / sessionStorage).
3
+ *
4
+ * Both objects share the Storage surface (`getItem`, `setItem`, `removeItem`,
5
+ * `clear`, `key`, `length`) but address different databases: localStorage uses
6
+ * the configured backend (in-memory by default, or the file embedded by the
7
+ * driver), while sessionStorage always uses a private in-memory database.
8
+ *
9
+ * The backend selection is compile-time: the driver embeds `xt_storage_backend`
10
+ * and `xt_storage_path` (see src/driver/storage.ts), and this unit reads them
11
+ * the first time a database is opened.
12
+ */
13
+
14
+ #include "storage_internal.h"
15
+
16
+ /* Embedded configuration symbols. Strong definitions come from the object the
17
+ * driver links for every program that enables the storage extension. */
18
+ extern const unsigned int xt_storage_backend;
19
+ extern const unsigned char xt_storage_path[];
20
+ extern const unsigned long long xt_storage_path_len;
21
+
22
+ static sqlite3 *g_db = NULL;
23
+ static sqlite3 *g_session_db = NULL;
24
+
25
+ static void storage_init_schema(sqlite3 *db) {
26
+ const char *sql =
27
+ "CREATE TABLE IF NOT EXISTS __web_storage("
28
+ " scope TEXT NOT NULL, key TEXT NOT NULL, value TEXT NOT NULL,"
29
+ " PRIMARY KEY(scope, key));"
30
+ "CREATE TABLE IF NOT EXISTS __idb_meta("
31
+ " db TEXT PRIMARY KEY, version INTEGER NOT NULL);"
32
+ "CREATE TABLE IF NOT EXISTS __idb_stores("
33
+ " db TEXT NOT NULL, store TEXT NOT NULL, key_path TEXT,"
34
+ " auto_increment INTEGER NOT NULL DEFAULT 0, PRIMARY KEY(db, store));"
35
+ "CREATE TABLE IF NOT EXISTS __idb_records("
36
+ " db TEXT NOT NULL, store TEXT NOT NULL, key TEXT NOT NULL, value TEXT NOT NULL,"
37
+ " PRIMARY KEY(db, store, key));"
38
+ "CREATE TABLE IF NOT EXISTS __idb_seq("
39
+ " db TEXT NOT NULL, store TEXT NOT NULL, seq INTEGER NOT NULL,"
40
+ " PRIMARY KEY(db, store));";
41
+ sqlite3_exec(db, sql, NULL, NULL, NULL);
42
+ }
43
+
44
+ static void storage_open(sqlite3 **out, const char *path) {
45
+ if (*out != NULL) return;
46
+ if (sqlite3_open(path, out) != SQLITE_OK) {
47
+ const char *message = sqlite3_errmsg(*out);
48
+ sqlite3_close(*out);
49
+ *out = NULL;
50
+ xt_throw(xt_storage_error(message != NULL ? message : "storage: cannot open database"));
51
+ return;
52
+ }
53
+ storage_init_schema(*out);
54
+ }
55
+
56
+ sqlite3 *xt_storage_db(void) {
57
+ const char *path = xt_storage_backend != 0 ? (const char *)xt_storage_path : ":memory:";
58
+ storage_open(&g_db, path);
59
+ return g_db;
60
+ }
61
+
62
+ sqlite3 *xt_storage_session_db(void) {
63
+ storage_open(&g_session_db, ":memory:");
64
+ return g_session_db;
65
+ }
66
+
67
+ /* -- Storage surface ------------------------------------------------------ */
68
+
69
+ static sqlite3 *storage_db_for(xt_value self) {
70
+ const char *scope = xt_storage_cstr(xt_object_get_cstr(self, "__scope"));
71
+ return scope != NULL && strcmp(scope, "session") == 0 ? xt_storage_session_db() : xt_storage_db();
72
+ }
73
+
74
+ static xt_value storage_scope_of(xt_value self) {
75
+ return xt_object_get_cstr(self, "__scope");
76
+ }
77
+
78
+ static xt_value storage_get_item(xt_value self, xt_value env, int32_t argc, xt_value *argv) {
79
+ (void)env;
80
+ sqlite3 *db = storage_db_for(self);
81
+ sqlite3_stmt *stmt = NULL;
82
+ if (sqlite3_prepare_v2(db, "SELECT value FROM __web_storage WHERE scope=?1 AND key=?2", -1, &stmt, NULL) !=
83
+ SQLITE_OK) {
84
+ return XT_NULL;
85
+ }
86
+ xt_storage_bind(stmt, 1, storage_scope_of(self));
87
+ xt_storage_bind(stmt, 2, xt_to_string(xt_arg(argc, argv, 0)));
88
+ xt_value result = XT_NULL;
89
+ if (sqlite3_step(stmt) == SQLITE_ROW) result = xt_storage_column(stmt, 0);
90
+ sqlite3_finalize(stmt);
91
+ return result;
92
+ }
93
+
94
+ static xt_value storage_set_item(xt_value self, xt_value env, int32_t argc, xt_value *argv) {
95
+ (void)env;
96
+ sqlite3 *db = storage_db_for(self);
97
+ sqlite3_stmt *stmt = NULL;
98
+ sqlite3_prepare_v2(db,
99
+ "INSERT INTO __web_storage(scope,key,value) VALUES(?1,?2,?3)"
100
+ " ON CONFLICT(scope,key) DO UPDATE SET value=excluded.value",
101
+ -1, &stmt, NULL);
102
+ if (stmt != NULL) {
103
+ xt_storage_bind(stmt, 1, storage_scope_of(self));
104
+ xt_storage_bind(stmt, 2, xt_to_string(xt_arg(argc, argv, 0)));
105
+ xt_storage_bind(stmt, 3, xt_to_string(xt_arg(argc, argv, 1)));
106
+ sqlite3_step(stmt);
107
+ sqlite3_finalize(stmt);
108
+ }
109
+ return XT_UNDEFINED;
110
+ }
111
+
112
+ static xt_value storage_remove_item(xt_value self, xt_value env, int32_t argc, xt_value *argv) {
113
+ (void)env;
114
+ sqlite3 *db = storage_db_for(self);
115
+ sqlite3_stmt *stmt = NULL;
116
+ sqlite3_prepare_v2(db, "DELETE FROM __web_storage WHERE scope=?1 AND key=?2", -1, &stmt, NULL);
117
+ if (stmt != NULL) {
118
+ xt_storage_bind(stmt, 1, storage_scope_of(self));
119
+ xt_storage_bind(stmt, 2, xt_to_string(xt_arg(argc, argv, 0)));
120
+ sqlite3_step(stmt);
121
+ sqlite3_finalize(stmt);
122
+ }
123
+ return XT_UNDEFINED;
124
+ }
125
+
126
+ static xt_value storage_clear(xt_value self, xt_value env, int32_t argc, xt_value *argv) {
127
+ (void)env;
128
+ (void)argc;
129
+ (void)argv;
130
+ sqlite3 *db = storage_db_for(self);
131
+ sqlite3_stmt *stmt = NULL;
132
+ sqlite3_prepare_v2(db, "DELETE FROM __web_storage WHERE scope=?1", -1, &stmt, NULL);
133
+ if (stmt != NULL) {
134
+ xt_storage_bind(stmt, 1, storage_scope_of(self));
135
+ sqlite3_step(stmt);
136
+ sqlite3_finalize(stmt);
137
+ }
138
+ return XT_UNDEFINED;
139
+ }
140
+
141
+ static xt_value storage_length_get(xt_value self, xt_value env, int32_t argc, xt_value *argv) {
142
+ (void)env;
143
+ (void)argc;
144
+ (void)argv;
145
+ sqlite3 *db = storage_db_for(self);
146
+ sqlite3_stmt *stmt = NULL;
147
+ sqlite3_prepare_v2(db, "SELECT COUNT(*) FROM __web_storage WHERE scope=?1", -1, &stmt, NULL);
148
+ double count = 0;
149
+ if (stmt != NULL) {
150
+ xt_storage_bind(stmt, 1, storage_scope_of(self));
151
+ if (sqlite3_step(stmt) == SQLITE_ROW) count = (double)sqlite3_column_int64(stmt, 0);
152
+ sqlite3_finalize(stmt);
153
+ }
154
+ return xt_number(count);
155
+ }
156
+
157
+ static xt_value storage_key(xt_value self, xt_value env, int32_t argc, xt_value *argv) {
158
+ (void)env;
159
+ sqlite3 *db = storage_db_for(self);
160
+ double at = argc > 0 ? xt_to_number(argv[0]) : -1;
161
+ if (at < 0) return XT_NULL;
162
+ sqlite3_stmt *stmt = NULL;
163
+ sqlite3_prepare_v2(db, "SELECT key FROM __web_storage WHERE scope=?1 ORDER BY rowid LIMIT 1 OFFSET ?2",
164
+ -1, &stmt, NULL);
165
+ xt_value result = XT_NULL;
166
+ if (stmt != NULL) {
167
+ xt_storage_bind(stmt, 1, storage_scope_of(self));
168
+ sqlite3_bind_int64(stmt, 2, (sqlite3_int64)at);
169
+ if (sqlite3_step(stmt) == SQLITE_ROW) result = xt_storage_column(stmt, 0);
170
+ sqlite3_finalize(stmt);
171
+ }
172
+ return result;
173
+ }
174
+
175
+ static xt_value storage_build(const char *scope) {
176
+ xt_value storage = xt_object_new();
177
+ xt_storage_set(storage, "__scope", xt_string_from_cstr(scope));
178
+ xt_storage_method(storage, "getItem", (void *)storage_get_item);
179
+ xt_storage_method(storage, "setItem", (void *)storage_set_item);
180
+ xt_storage_method(storage, "removeItem", (void *)storage_remove_item);
181
+ xt_storage_method(storage, "clear", (void *)storage_clear);
182
+ xt_storage_method(storage, "key", (void *)storage_key);
183
+ xt_object_define_getter(storage, xt_string_from_cstr("length"),
184
+ xt_closure_new((void *)storage_length_get, 0, NULL));
185
+ return storage;
186
+ }
187
+
188
+ static xt_value g_local_storage = XT_UNDEFINED;
189
+ static xt_value g_session_storage = XT_UNDEFINED;
190
+
191
+ xt_value xt_storage_local(int32_t argc, xt_value *argv) {
192
+ (void)argc;
193
+ (void)argv;
194
+ if (!XT_IS_OBJECT(g_local_storage)) {
195
+ g_local_storage = storage_build("local");
196
+ xt_gc_add_root(&g_local_storage);
197
+ }
198
+ return g_local_storage;
199
+ }
200
+
201
+ xt_value xt_storage_session(int32_t argc, xt_value *argv) {
202
+ (void)argc;
203
+ (void)argv;
204
+ if (!XT_IS_OBJECT(g_session_storage)) {
205
+ g_session_storage = storage_build("session");
206
+ xt_gc_add_root(&g_session_storage);
207
+ }
208
+ return g_session_storage;
209
+ }
@@ -0,0 +1,66 @@
1
+ /*
2
+ * Shared helpers for the xbintsc `storage` extension.
3
+ *
4
+ * localStorage / sessionStorage / indexedDB are implemented on top of a vendored
5
+ * SQLite (runtime/xt_storage/sqlite3). This header owns the small value helpers
6
+ * and the two database handles; the Web Storage surface lives in `storage.c`
7
+ * and the IndexedDB surface in `indexed_db.c`.
8
+ */
9
+ #ifndef XT_STORAGE_INTERNAL_H
10
+ #define XT_STORAGE_INTERNAL_H
11
+
12
+ #include "rt_internal.h"
13
+ #include "sqlite3/sqlite3.h"
14
+
15
+ #include <stdio.h>
16
+ #include <stdlib.h>
17
+ #include <string.h>
18
+
19
+ /* The persistent database (localStorage + indexedDB): the configured backend —
20
+ * an in-memory database by default, or the file embedded by the driver. */
21
+ sqlite3 *xt_storage_db(void);
22
+ /* The session database (sessionStorage): always in-memory, regardless of the
23
+ * configured backend, because a session never outlives the process. */
24
+ sqlite3 *xt_storage_session_db(void);
25
+
26
+ /* -- small value helpers -------------------------------------------------- */
27
+
28
+ static inline const char *xt_storage_cstr(xt_value value) {
29
+ const char *data = xt_string_data(xt_to_string(value));
30
+ return data != NULL ? data : "";
31
+ }
32
+
33
+ static inline void xt_storage_set(xt_value object, const char *key, xt_value value) {
34
+ xt_object_set(object, xt_string_from_cstr(key), value);
35
+ }
36
+
37
+ static inline void xt_storage_set_cstr(xt_value object, const char *key, const char *value) {
38
+ xt_storage_set(object, key, xt_string_from_cstr(value));
39
+ }
40
+
41
+ static inline xt_value xt_storage_get(xt_value object, const char *key) {
42
+ return xt_object_get_cstr(object, key);
43
+ }
44
+
45
+ static inline void xt_storage_method(xt_value object, const char *name, void *fn) {
46
+ xt_storage_set(object, name, xt_closure_new(fn, 0, NULL));
47
+ }
48
+
49
+ static inline xt_value xt_storage_error(const char *message) {
50
+ return xt_error_from_message(message);
51
+ }
52
+
53
+ /* -- SQLite binding helpers ----------------------------------------------- */
54
+
55
+ /* Bind a JavaScript string (which may contain embedded NUL bytes) as a length-
56
+ * aware text value. SQLITE_TRANSIENT makes SQLite copy the bytes. */
57
+ static inline void xt_storage_bind(sqlite3_stmt *stmt, int index, xt_value value) {
58
+ sqlite3_bind_text(stmt, index, xt_string_data(value), (int)xt_string_length_value(value), SQLITE_TRANSIENT);
59
+ }
60
+
61
+ /* Read a text column as a JavaScript string (length-aware). */
62
+ static inline xt_value xt_storage_column(sqlite3_stmt *stmt, int index) {
63
+ return xt_string_new((const char *)sqlite3_column_text(stmt, index), (size_t)sqlite3_column_bytes(stmt, index));
64
+ }
65
+
66
+ #endif /* XT_STORAGE_INTERNAL_H */
@@ -21,7 +21,7 @@
21
21
  * `gui.lib` on Windows, built from MSVC-compatible COFF objects).
22
22
  *
23
23
  * Media decoding is *not* part of this archive: it is an optional link feature
24
- * of the `gui` extension (`npm run media`, `runtime/ext_media/`), so a program
24
+ * of the `gui` extension (`npm run media`, `runtime/xt_media/`), so a program
25
25
  * that only renders HTML/CSS never links FFmpeg.
26
26
  *
27
27
  * Every library and every engine object is compiled with function/data sections;
@@ -7,7 +7,7 @@
7
7
  *
8
8
  * The GUI engine (`gui.a` / `gui.lib`) deliberately contains no decoder. This
9
9
  * archive adds `<video>`/`<audio>` support: it bundles the FFmpeg-backed player
10
- * from `runtime/ext_media/media.cpp` together with a minimal static FFmpeg, and
10
+ * from `runtime/xt_media/media.cpp` together with a minimal static FFmpeg, and
11
11
  * the `media` extension links it only when the program asks for it. A program
12
12
  * built with `--ext gui` alone therefore stays FFmpeg-free.
13
13
  *
@@ -56,7 +56,7 @@ import { cxxCompileFlags } from "./gui-build-options.js";
56
56
 
57
57
  const root = resolve(dirname(fileURLToPath(import.meta.url)), "..");
58
58
  const runtimeDir = join(root, "runtime");
59
- const sourceDir = join(runtimeDir, "ext_media");
59
+ const sourceDir = join(runtimeDir, "xt_media");
60
60
  const vendorDir = join(root, "vendor");
61
61
  const ffmpegSrc = join(vendorDir, "ffmpeg");
62
62
  const isWindows = process.platform === "win32";
@@ -51,6 +51,10 @@ const VENDORED_FILES = new Set([
51
51
  join("runtime", "ext_node", "zlib", "miniz", "miniz_tinfl.h"),
52
52
  join("runtime", "ext_node", "zlib", "miniz", "miniz_common.h"),
53
53
  join("runtime", "ext_node", "zlib", "miniz", "miniz_export.h"),
54
+ // SQLite, the single-file amalgamation backing the `storage` extension
55
+ // (localStorage / sessionStorage / indexedDB), ships verbatim.
56
+ join("runtime", "xt_storage", "sqlite3", "sqlite3.c"),
57
+ join("runtime", "xt_storage", "sqlite3", "sqlite3.h"),
54
58
  ]);
55
59
 
56
60
  /** Machine-generated files: they are reproduced from their sources by a script,
package/src/cli/main.ts CHANGED
@@ -520,6 +520,7 @@ function dispatch(argv: readonly string[], io: CliIo): number {
520
520
  verbose: Boolean(args.flags.get("verbose")),
521
521
  extensions: registry,
522
522
  app: mergeAppConfig(args.flags, config),
523
+ storage: config.storage,
523
524
  debug: Boolean(args.flags.get("debug")),
524
525
  check: !args.flags.has("no-check"),
525
526
  lto: Boolean(args.flags.get("lto")) || config.lto === true,
@@ -14,6 +14,7 @@ import type { AppConfig } from "./config.js";
14
14
  import { compilerFingerprint, registryFingerprint, runtimeFingerprint } from "./fingerprint.js";
15
15
  import { COMPILER_VERSION } from "./version.js";
16
16
  import type { IconInfo } from "./icon.js";
17
+ import type { ResolvedStorage } from "./storage.js";
17
18
  import type { PgoMode } from "./toolchain.js";
18
19
 
19
20
  export interface CacheKeyInput {
@@ -25,6 +26,8 @@ export interface CacheKeyInput {
25
26
  readonly runtimeDir: string;
26
27
  readonly icon?: IconInfo;
27
28
  readonly app: AppConfig;
29
+ /** Storage backend/path embedded into the binary (storage extension). */
30
+ readonly storage: ResolvedStorage;
28
31
  readonly debug: boolean;
29
32
  readonly lto: boolean;
30
33
  /** Whether the semantic checker ran (default true). */
@@ -37,7 +40,7 @@ export interface CacheKeyInput {
37
40
 
38
41
  /** Hash every input that can change the produced binary. */
39
42
  export function buildCacheKey(input: CacheKeyInput): string {
40
- const { app, icon, pgo } = input;
43
+ const { app, icon, pgo, storage } = input;
41
44
  return hashParts([
42
45
  COMPILER_VERSION,
43
46
  compilerFingerprint(),
@@ -51,6 +54,8 @@ export function buildCacheKey(input: CacheKeyInput): string {
51
54
  app.name ?? "",
52
55
  String(app.bundle ?? false),
53
56
  app.bundleId ?? "",
57
+ storage.backend,
58
+ storage.path,
54
59
  String(input.debug),
55
60
  String(input.lto),
56
61
  String(input.check !== false),
@@ -21,6 +21,7 @@ import { BuildCache } from "./cache.js";
21
21
  import { findRuntimeDir, platformSlug } from "./paths.js";
22
22
  import { resolveToolchain, type ResolvedToolchain } from "./toolchain-provider.js";
23
23
  import { readIcon, IconError, type IconInfo } from "./icon.js";
24
+ import { ensureStorageObject, resolveStorage } from "./storage.js";
24
25
  import { bundlePathFor, packageMacApp } from "./mac-bundle.js";
25
26
  import type { AppConfig } from "./config.js";
26
27
  import { compileIr, link, mergeProfileData, realRunner, ToolchainError } from "./toolchain.js";
@@ -178,6 +179,8 @@ export function build(entryPath: string, options: BuildOptions = {}): BuildResul
178
179
  }
179
180
  }
180
181
 
182
+ const storage = resolveStorage(options.storage);
183
+
181
184
  const runtimeDir = findRuntimeDir();
182
185
  const cacheKey = buildCacheKey({
183
186
  sourceText: parsed.cacheText,
@@ -187,6 +190,7 @@ export function build(entryPath: string, options: BuildOptions = {}): BuildResul
187
190
  runtimeDir,
188
191
  icon,
189
192
  app,
193
+ storage,
190
194
  debug: options.debug === true,
191
195
  lto,
192
196
  check: options.check !== false,
@@ -332,6 +336,14 @@ export function build(entryPath: string, options: BuildOptions = {}): BuildResul
332
336
  return { outputPath, irPath, cached: false, diagnostics: diagnostics.diagnostics, ir };
333
337
  }
334
338
 
339
+ /* The storage extension reads its backend/path from an embedded object, the
340
+ * same way the GUI reads the icon. Only linked when the storage link feature
341
+ * is active (the program actually reaches a storage global). */
342
+ const storageObjects: string[] = [];
343
+ if (linkFeatures.some((feature) => feature.name === "storage")) {
344
+ storageObjects.push(ensureStorageObject(runner, clang, cacheDir, storage, toolchain.env, toolchain.sdkRoot));
345
+ }
346
+
335
347
  const linkAssembled = (runtimeObjects: RuntimeObjects): string => {
336
348
  const started = Date.now();
337
349
  const result = link(runner, {
@@ -349,6 +361,7 @@ export function build(entryPath: string, options: BuildOptions = {}): BuildResul
349
361
  ...runtimeObjects.nativeObjects,
350
362
  ...(artifacts.entryObject !== undefined ? [artifacts.entryObject] : []),
351
363
  ...artifacts.iconObjects,
364
+ ...storageObjects,
352
365
  ]),
353
366
  ],
354
367
  outputPath,
@@ -33,6 +33,17 @@ export interface AppConfig {
33
33
  readonly console?: boolean;
34
34
  }
35
35
 
36
+ /**
37
+ * Persistent-storage backend for the `storage` extension (localStorage,
38
+ * sessionStorage, indexedDB). `backend` defaults to `memory`; `file` also needs
39
+ * `path`, which is resolved against the config file's directory (absolute paths
40
+ * are used as-is).
41
+ */
42
+ export interface StorageConfig {
43
+ readonly backend?: "memory" | "file";
44
+ readonly path?: string;
45
+ }
46
+
36
47
  /** The on-disk schema of `xbintsc.config.json`. Every field is optional. */
37
48
  export interface ProjectConfig {
38
49
  readonly entry?: string;
@@ -52,6 +63,8 @@ export interface ProjectConfig {
52
63
  readonly moduleOverrides?: Readonly<Record<string, string>>;
53
64
  readonly force?: boolean;
54
65
  readonly app?: AppConfig;
66
+ /** Storage backend for the `storage` extension (default: memory). */
67
+ readonly storage?: StorageConfig;
55
68
  }
56
69
 
57
70
  export class ProjectConfigError extends Error {
@@ -146,6 +159,23 @@ export function parseProjectConfig(text: string, where: string = CONFIG_FILE_NAM
146
159
  }
147
160
  }
148
161
 
162
+ let storage: StorageConfig | undefined;
163
+ if (root.storage !== undefined) {
164
+ const storageRoot = expectObject(root.storage, `${where}: 'storage'`);
165
+ const backend = readString(storageRoot, "backend", `${where}: 'storage'`);
166
+ if (backend !== undefined && backend !== "memory" && backend !== "file") {
167
+ throw new ProjectConfigError(`${where}: 'storage.backend' must be "memory" or "file"`);
168
+ }
169
+ const path = readString(storageRoot, "path", `${where}: 'storage'`);
170
+ if (backend === "file" && (path === undefined || path === "")) {
171
+ throw new ProjectConfigError(`${where}: 'storage.path' is required when 'storage.backend' is "file"`);
172
+ }
173
+ storage = { backend: backend as StorageConfig["backend"], path };
174
+ for (const key of Object.keys(storage) as (keyof StorageConfig)[]) {
175
+ if (storage[key] === undefined) delete storage[key];
176
+ }
177
+ }
178
+
149
179
  const config: ProjectConfig = {
150
180
  entry: readString(root, "entry", where),
151
181
  outDir: readString(root, "outDir", where),
@@ -161,6 +191,7 @@ export function parseProjectConfig(text: string, where: string = CONFIG_FILE_NAM
161
191
  moduleOverrides: readStringMap(root, "moduleOverrides", where),
162
192
  force: readBoolean(root, "force", where),
163
193
  app,
194
+ storage,
164
195
  };
165
196
  for (const key of Object.keys(config) as (keyof ProjectConfig)[]) {
166
197
  if (config[key] === undefined) delete config[key];
@@ -203,6 +234,9 @@ export function resolveConfigPaths(loaded: LoadedProjectConfig): ProjectConfig {
203
234
  const app: AppConfig | undefined = config.app
204
235
  ? { ...config.app, ...(config.app.icon ? { icon: resolvePath(directory, config.app.icon) } : {}) }
205
236
  : undefined;
237
+ const storage: StorageConfig | undefined = config.storage
238
+ ? { ...config.storage, ...(config.storage.path ? { path: resolvePath(directory, config.storage.path) } : {}) }
239
+ : undefined;
206
240
  return {
207
241
  ...config,
208
242
  ...(config.entry ? { entry: resolvePath(directory, config.entry) } : {}),
@@ -214,5 +248,6 @@ export function resolveConfigPaths(loaded: LoadedProjectConfig): ProjectConfig {
214
248
  ? { moduleOverrides: Object.fromEntries(Object.entries(config.moduleOverrides).map(([k, v]) => [k, resolvePath(directory, v)])) }
215
249
  : {}),
216
250
  ...(app ? { app } : {}),
251
+ ...(storage ? { storage } : {}),
217
252
  };
218
253
  }
@@ -19,7 +19,15 @@ export {
19
19
  type AppConfig,
20
20
  type LoadedProjectConfig,
21
21
  type ProjectConfig,
22
+ type StorageConfig,
22
23
  } from "./config.js";
24
+ export {
25
+ ensureStorageObject,
26
+ resolveStorage,
27
+ storageSource,
28
+ STORAGE_SYMBOLS,
29
+ type ResolvedStorage,
30
+ } from "./storage.js";
23
31
  export {
24
32
  ensureIconObject,
25
33
  iconSource,
@@ -8,7 +8,7 @@
8
8
 
9
9
  import type { Diagnostic } from "../diagnostics/diagnostic.js";
10
10
  import type { ExtensionRegistry } from "../extensions/registry.js";
11
- import type { AppConfig } from "./config.js";
11
+ import type { AppConfig, StorageConfig } from "./config.js";
12
12
  import type { PgoMode, Runner } from "./toolchain.js";
13
13
 
14
14
  /** What `build` produces: an executable, an object file or LLVM IR only. */
@@ -39,6 +39,13 @@ export interface BuildOptions {
39
39
  readonly icon?: string;
40
40
  /** Application metadata: name, icon and macOS bundle settings. */
41
41
  readonly app?: AppConfig;
42
+ /**
43
+ * Storage backend for the `storage` extension (`localStorage`, `sessionStorage`,
44
+ * `indexedDB`). Defaults to memory; `{ backend: "file", path }` persists to
45
+ * the given file. `path` must already be absolute (config resolution does
46
+ * this), and sessionStorage is always memory-backed regardless.
47
+ */
48
+ readonly storage?: StorageConfig;
42
49
  /** Emit LLVM debug metadata so `-g` produces DWARF/CodeView (default false). */
43
50
  readonly debug?: boolean;
44
51
  /**
@@ -0,0 +1,84 @@
1
+ /**
2
+ * Compile-time storage configuration for the `storage` extension.
3
+ *
4
+ * The project config's `storage` object (memory vs file, plus the resolved
5
+ * database path) is embedded into the binary as a small linkable object, the
6
+ * same way the application icon is (see `icon.ts`). The storage runtime reads
7
+ * these symbols when it opens its database, so a project can choose between an
8
+ * in-memory database (the default) and a persistent file without any runtime
9
+ * lookup.
10
+ */
11
+
12
+ import { existsSync, mkdirSync, writeFileSync } from "node:fs";
13
+ import { join } from "node:path";
14
+ import { hashParts } from "./cache.js";
15
+ import { compileC, sysrootFlags, type Runner } from "./toolchain.js";
16
+ import type { StorageConfig } from "./config.js";
17
+
18
+ /** The C symbols the embedded storage configuration exposes. */
19
+ export const STORAGE_SYMBOLS = {
20
+ backend: "xt_storage_backend",
21
+ path: "xt_storage_path",
22
+ pathLen: "xt_storage_path_len",
23
+ } as const;
24
+
25
+ /** The storage backend after config defaults and path resolution. */
26
+ export interface ResolvedStorage {
27
+ readonly backend: "memory" | "file";
28
+ /** Absolute database path; empty for the memory backend. */
29
+ readonly path: string;
30
+ }
31
+
32
+ /** Normalise a (possibly undefined) config into a concrete backend + path. */
33
+ export function resolveStorage(config: StorageConfig | undefined): ResolvedStorage {
34
+ if (config?.backend === "file") return { backend: "file", path: config.path ?? "" };
35
+ return { backend: "memory", path: "" };
36
+ }
37
+
38
+ /** Generate the C translation unit embedding the storage backend + path. */
39
+ export function storageSource(storage: ResolvedStorage): string {
40
+ const backend = storage.backend === "file" ? 1 : 0;
41
+ /* The path is emitted as raw UTF-8 bytes plus a trailing NUL, so a path that
42
+ * contains `\`, `"` or non-ASCII characters needs no escaping. */
43
+ const path = storage.backend === "file" ? Buffer.from(storage.path, "utf8") : Buffer.alloc(0);
44
+ const bytes = [...path, 0x00];
45
+ const lines: string[] = [];
46
+ for (let offset = 0; offset < bytes.length; offset += 16) {
47
+ const chunk = Array.from(bytes.slice(offset, offset + 16), (byte) => `0x${byte.toString(16).padStart(2, "0")}`);
48
+ lines.push(" " + chunk.join(", ") + ",");
49
+ }
50
+ if (lines.length === 0) lines.push(" 0x00,");
51
+ return [
52
+ "/* Generated by xbintsc - embedded storage configuration. Do not edit. */",
53
+ `const unsigned int ${STORAGE_SYMBOLS.backend} = ${backend}u;`,
54
+ `const unsigned char ${STORAGE_SYMBOLS.path}[] = {`,
55
+ ...lines,
56
+ "};",
57
+ `const unsigned long long ${STORAGE_SYMBOLS.pathLen} = ${path.length}ull;`,
58
+ "",
59
+ ].join("\n");
60
+ }
61
+
62
+ /**
63
+ * Compile the storage configuration into an object exposing
64
+ * {@link STORAGE_SYMBOLS}. Cached by the backend + path, so an unchanged
65
+ * configuration is never recompiled.
66
+ */
67
+ export function ensureStorageObject(
68
+ runner: Runner,
69
+ clang: string,
70
+ cacheDir: string,
71
+ storage: ResolvedStorage,
72
+ env?: Record<string, string>,
73
+ sdkRoot?: string,
74
+ ): string {
75
+ const key = hashParts(["storage", process.platform, storage.backend, storage.path]);
76
+ const sourcePath = join(cacheDir, `storage-${key}.c`);
77
+ const objectPath = join(cacheDir, `storage-${key}.o`);
78
+ if (!existsSync(objectPath)) {
79
+ mkdirSync(cacheDir, { recursive: true });
80
+ writeFileSync(sourcePath, storageSource(storage));
81
+ compileC(runner, clang, sourcePath, objectPath, cacheDir, env, sysrootFlags(sdkRoot));
82
+ }
83
+ return objectPath;
84
+ }
@@ -9,4 +9,4 @@
9
9
  * `main`/`master` only (see `.githooks/pre-commit`), so feature branches never
10
10
  * change this line and merging two of them cannot conflict here.
11
11
  */
12
- export const COMPILER_VERSION = "0.6.20";
12
+ export const COMPILER_VERSION = "0.6.22";
@@ -4,7 +4,7 @@
4
4
  * The GUI engine itself is always linked with `--ext gui`; these are the two
5
5
  * heavy halves a program may never touch:
6
6
  *
7
- * - `media` — the FFmpeg decoder backend (`runtime/ext_media/`, `media.a`).
7
+ * - `media` — the FFmpeg decoder backend (`runtime/xt_media/`, `media.a`).
8
8
  * The DOM media surface lives in `gui.a`; only decoding is optional, and an
9
9
  * element without the backend still exists and fires `error`.
10
10
  * - `gpu` — glslang (+ SPIRV-Cross on macOS), the GLSL→SPIR-V translator used
@@ -108,7 +108,7 @@ export const guiLinkFeatures: readonly LinkFeature[] = [
108
108
  * the linker extract `media.a` — an archive whose only entry point is a
109
109
  * constructor would otherwise never be pulled in.
110
110
  */
111
- runtimeSources: () => [join(findRuntimeDir(), "ext_media", "media_bridge.c")],
111
+ runtimeSources: () => [join(findRuntimeDir(), "xt_media", "media_bridge.c")],
112
112
  nativeObjects: () => {
113
113
  const archive = findRuntimeLibrary("media");
114
114
  if (archive === undefined) {
@@ -151,7 +151,9 @@ const browserGlobals: Record<string, { symbol: string; argument?: string }> = {
151
151
  self: { symbol: "xt_browser_window" },
152
152
  document: { symbol: "xt_browser_document" },
153
153
  navigator: { symbol: "xt_browser_navigator" },
154
- localStorage: { symbol: "xt_browser_local_storage" },
154
+ /* `localStorage` (and `sessionStorage` / `indexedDB`) are core globals backed
155
+ * by the SQLite `storage` link feature, so a page reaches them through core
156
+ * rather than the engine's in-memory `window.localStorage` store. */
155
157
  __THREE_DEVTOOLS__: { symbol: "xt_browser_missing" },
156
158
  createImageBitmap: { symbol: "xt_browser_create_image_bitmap" },
157
159
  };
@@ -12,6 +12,7 @@
12
12
  */
13
13
 
14
14
  import type { LinkFeature } from "./link-feature.js";
15
+ import { storageGlobals, storageLinkFeatures } from "./storage.js";
15
16
 
16
17
  export interface BuiltinFunction {
17
18
  /** Exported C symbol, called as `xt_value symbol(int32_t argc, xt_value *argv)`. */
@@ -342,14 +343,19 @@ export class ExtensionRegistry {
342
343
 
343
344
  /**
344
345
  * A built-in extension that exposes the runtime's own console/IO helpers. It is
345
- * always present so `console.log` works even without a platform extension.
346
+ * always present so `console.log` works even without a platform extension, and
347
+ * it also contributes the SQLite-backed Web Storage/IndexedDB globals as a link
348
+ * feature (see `./storage.js`) so `localStorage`/`sessionStorage`/`indexedDB`
349
+ * are always reachable while SQLite is linked only when used.
346
350
  */
347
351
  export const coreExtension: Extension = {
348
352
  name: "core",
349
- description: "Core runtime helpers (console, print)",
353
+ description: "Core runtime helpers (console, print, Web Storage and IndexedDB)",
350
354
  builtins: () => ({
351
355
  print: { symbol: "xt_println" },
352
356
  }),
357
+ globalValues: () => storageGlobals,
358
+ linkFeatures: () => storageLinkFeatures,
353
359
  };
354
360
 
355
361
  export function createDefaultRegistry(): ExtensionRegistry {