@ringozz/godot 4.7.1-8 → 4.7.2-570

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.
package/src/preload.ts CHANGED
@@ -1,198 +1,216 @@
1
- /**********************************************************************
2
- Copyright (c) Vladimir Davidovich. All rights reserved.
3
- ***********************************************************************/
4
-
5
- import { existsSync, readFileSync } from 'node:fs';
6
- import { dirname, resolve } from 'node:path';
7
- import { plugin } from 'bun';
8
- import type { BunPlugin } from 'bun';
9
-
10
- // Registers the godot-assets plugin: imports of Godot source assets become
11
- // virtual modules (namespace `godot`) that call `loadAsset` (`@ringozz/godot/load`)
12
- // and export the resulting `materialize` (own + deps' files) and load promise.
13
- // `loadAsset` checks the engine's `ResourceCache` once; when the asset is
14
- // already loaded (e.g. a re-evaluated module under web HMR) the load resolves to
15
- // the cached instance and `materialize` short-circuits, skipping file staging
16
- // and the threaded load. The load promise persists on the module's
17
- // `import.meta.hot.data` (per-module state carried across hot replacements), so
18
- // HMR re-evaluations return the *same* fulfilled promise object — React's `use()`
19
- // keeps its tracked status and never re-suspends (no Suspense fallback flash); a
20
- // rejected load is evicted from `data` so the next evaluation retries; on
21
- // desktop `data` is `{}` and modules evaluate once. Dependencies are generated
22
- // modules too, so a dep's load starts at module evaluation while the parent only
23
- // waits for dep *files*. The default export is the single plugin — registered
24
- // globally via bunfig preload and loaded by `[serve.static] plugins` for
25
- // `Bun.serve` HTML routes.
26
-
27
- const ROOT = process.cwd();
28
- const NS = 'godot';
29
-
30
- /** Format metadata: `cls` = Godot class (importable), `scan` = scan text refs, `native` = no `.import` sidecar. */
31
- const FORMATS: Record<string, { cls?: string; scan?: boolean; native?: boolean }> = {
32
- gltf: { cls: 'PackedScene', scan: true },
33
- tscn: { cls: 'PackedScene', scan: true, native: true },
34
- obj: { cls: 'PackedScene', scan: true },
35
- jpg: { cls: 'CompressedTexture2D' },
36
- jpeg: { cls: 'CompressedTexture2D' },
37
- png: { cls: 'CompressedTexture2D' },
38
- webp: { cls: 'CompressedTexture2D' },
39
- svg: { cls: 'Texture2D' },
40
- exr: { cls: 'TextureLayered' },
41
- hdr: { cls: 'TextureLayered' },
42
- wav: { cls: 'AudioStreamWAV' },
43
- ogg: { cls: 'AudioStreamOggVorbis' },
44
- mp3: { cls: 'AudioStreamMP3' },
45
- tres: { cls: 'Resource', scan: true, native: true },
46
- po: { cls: 'Translation', native: true },
47
- mtl: { scan: true },
48
- };
49
-
50
- const ASSET_RE = new RegExp(
51
- `\\.(${Object.entries(FORMATS).filter(([, f]) => f.cls).map(([k]) => k).join('|')})$`,
52
- 'i',
53
- );
54
- const CLASS_BY_EXT: Record<string, string> = Object.fromEntries(
55
- Object.entries(FORMATS).filter(([, f]) => f.cls).map(([k, f]) => [k, f.cls!]),
56
- );
57
- const SCANNED = new Set(Object.entries(FORMATS).filter(([, f]) => f.scan).map(([k]) => k));
58
- const NATIVE = new Set(Object.entries(FORMATS).filter(([, f]) => f.native).map(([k]) => k));
59
-
60
- const extOf = (abs: string) => abs.slice(abs.lastIndexOf('.') + 1).toLowerCase();
61
- const resOf = (abs: string) => 'res://' + abs.slice(ROOT.length + 1).replaceAll('\\', '/');
62
- const isScannableText = (abs: string) => SCANNED.has(extOf(abs));
63
- const isNativeText = (abs: string) => NATIVE.has(extOf(abs));
64
- const isSourceAsset = (abs: string) => existsSync(abs + '.import') || isNativeText(abs);
65
-
66
- /** Reads the imported destination (`dest_files`) out of an `.import` sidecar. */
67
- function parseSidecarDest(text: string): string | null {
68
- const deps = text.match(/^dest_files=\[([^\]]*)\]/m);
69
- if (deps) {
70
- const first = deps[1].match(/"([^"]+)"/);
71
- if (first) {
72
- return first[1];
73
- }
74
- }
75
- const remap = text.match(/^path="([^"]+)"/m);
76
- return remap ? remap[1] : null;
77
- }
78
-
79
- // Generalized reference extraction for text-based source assets: absolute
80
- // `res://` paths (Godot scenes/resources) and relative path tokens ending in a
81
- // known asset extension (glTF uris, OBJ/MTL textures). The literal dot before
82
- // the extension avoids matching MIME types inside `data:` URIs.
83
- const RES_RE = /res:\/\/[\w./\\-]+/g;
84
- const REL_RE = new RegExp(`([\\w./\\\\-]+\\.(?:${Object.keys(FORMATS).join('|')}))`, 'g');
85
-
86
- function extractRefs(text: string): string[] {
87
- const refs: string[] = [];
88
- for (const m of text.matchAll(RES_RE)) refs.push(m[0]);
89
- for (const m of text.matchAll(REL_RE)) refs.push(m[1]);
90
- return refs;
91
- }
92
-
93
- /**
94
- * Adds a source asset's own files to `files`: imported assets contribute their
95
- * `.import` sidecar (text) + imported product (file); native text formats
96
- * (tscn/tres/po) contribute the file itself (text).
97
- */
98
- function addSource(srcAbs: string, files: Map<string, 'text' | 'file'>): void {
99
- const impAbs = srcAbs + '.import';
100
- if (existsSync(impAbs)) {
101
- files.set(resOf(srcAbs) + '.import', 'text');
102
- const dest = parseSidecarDest(readFileSync(impAbs, 'utf8'));
103
- if (dest) {
104
- files.set(dest, 'file');
105
- }
106
- } else if (isNativeText(srcAbs)) {
107
- files.set(resOf(srcAbs), 'text');
108
- }
109
- }
110
-
111
- /**
112
- * Collects the referenced source assets (deps) of a text source: source assets
113
- * become dep modules (each handles its own transitive deps); raw text formats
114
- * without a sidecar (`.mtl`) are recursed into. Buffers (`.bin`) are skipped.
115
- */
116
- function collectDeps(abs: string, visited: Set<string>, deps: string[]): void {
117
- if (visited.has(abs)) {
118
- return;
119
- }
120
- visited.add(abs);
121
- if (!isScannableText(abs)) {
122
- return;
123
- }
124
- for (const ref of extractRefs(readFileSync(abs, 'utf8'))) {
125
- const refAbs = ref.startsWith('res://')
126
- ? resolve(ROOT, ref.slice('res://'.length))
127
- : resolve(dirname(abs), ref);
128
- if (visited.has(refAbs)) {
129
- continue;
130
- }
131
- if (isSourceAsset(refAbs)) {
132
- deps.push(refAbs);
133
- } else if (isScannableText(refAbs)) {
134
- collectDeps(refAbs, visited, deps);
135
- }
136
- }
137
- }
138
-
139
- function analyze(abs: string): { files: Map<string, 'text' | 'file'>; deps: string[] } {
140
- const files = new Map<string, 'text' | 'file'>();
141
- const deps: string[] = [];
142
- addSource(abs, files);
143
- collectDeps(abs, new Set(), deps);
144
- return { files, deps };
145
- }
146
-
147
- function ensureModule(abs: string): string {
148
- const res = resOf(abs);
149
- const cls = CLASS_BY_EXT[extOf(abs)] ?? 'Resource';
150
- const { files, deps } = analyze(abs);
151
-
152
- const imports = [
153
- `import { loadAsset } from '@ringozz/godot/load';`,
154
- `import { ${cls} } from '@ringozz/godot/${cls}';`,
155
- ];
156
- const map: string[] = [];
157
- let ti = 0;
158
- let fi = 0;
159
- for (const [resPath, kind] of files) {
160
- const absP = resolve(ROOT, resPath.slice('res://'.length));
161
- const v = kind === 'text' ? `c${ti++}` : `f${fi++}`;
162
- const type = kind === 'text' ? 'text' : 'file';
163
- const field = kind === 'text' ? 'content' : 'path';
164
- imports.push(`import ${v} from ${JSON.stringify(absP)} with { type: '${type}' };`);
165
- map.push(` ${JSON.stringify(resPath)}: { ${field}: ${v} },`);
166
- }
167
- deps.forEach((dep, i) => imports.push(`import * as dep${i} from ${JSON.stringify(dep)};`));
168
-
169
- const filesVar = files.size ? `const files = {\n${map.join('\n')}\n};` : `const files = {};`;
170
- const loadAsset = `const { materialize, load } = loadAsset(${JSON.stringify(res)}, ${cls}, files, [${deps.map((_, i) => `dep${i}`).join(', ')}], import.meta.hot.data);`;
171
- return imports.join('\n') + '\n' + filesVar + '\n' + loadAsset + '\n' + `export { materialize, load as default };` + '\n';
172
- }
173
-
174
- const assetPlugin: BunPlugin = {
175
- name: 'godot-assets',
176
- setup(build) {
177
- build.onResolve({ filter: ASSET_RE }, (args) => {
178
- const importerAbs = args.importer?.startsWith(`${NS}:`)
179
- ? args.importer.slice(NS.length + 1)
180
- : args.importer;
181
- const base = importerAbs ? dirname(importerAbs) : (args.resolveDir ?? ROOT);
182
- const abs = resolve(base, args.path);
183
- // A module's own native-text source (e.g. `.tscn`) self-imports the
184
- // same path — let it load as a real file.
185
- if (abs === importerAbs) {
186
- return;
187
- }
188
- return { path: abs, namespace: NS };
189
- });
190
- build.onLoad({ filter: /.*/, namespace: NS }, (args) => ({
191
- contents: ensureModule(args.path),
192
- loader: 'js',
193
- }));
194
- },
195
- };
196
-
197
- export default assetPlugin;
198
- plugin(assetPlugin);
1
+ /**********************************************************************
2
+ Copyright (c) Vladimir Davidovich. All rights reserved.
3
+ ***********************************************************************/
4
+
5
+ import { existsSync, readFileSync } from 'node:fs';
6
+ import { dirname, resolve } from 'node:path';
7
+ import { plugin } from 'bun';
8
+ import type { BunPlugin } from 'bun';
9
+
10
+ // Registers the godot-assets plugin: imports of Godot source assets become
11
+ // virtual modules (namespace `godot`) that call `loadAsset` (`@ringozz/godot/load`)
12
+ // and export the resulting `materialize` (own + deps' files) and load promise.
13
+ // `loadAsset` checks the engine's `ResourceCache` once; when the asset is
14
+ // already loaded (e.g. a re-evaluated module under web HMR) the load resolves to
15
+ // the cached instance and `materialize` short-circuits, skipping file staging
16
+ // and the threaded load. The load promise persists on the module's
17
+ // `import.meta.hot.data` (per-module state carried across hot replacements), so
18
+ // HMR re-evaluations return the *same* fulfilled promise object — React's `use()`
19
+ // keeps its tracked status and never re-suspends (no Suspense fallback flash); a
20
+ // rejected load is evicted from `data` so the next evaluation retries; on
21
+ // desktop `data` is `{}` and modules evaluate once. Dependencies are generated
22
+ // modules too, so a dep's load starts at module evaluation while the parent only
23
+ // waits for dep *files*. The default export is the single plugin — registered
24
+ // globally via bunfig preload and loaded by `[serve.static] plugins` for
25
+ // `Bun.serve` HTML routes.
26
+
27
+ const ROOT = process.cwd();
28
+ const NS = 'godot';
29
+
30
+ /** Format metadata: `cls` = Godot class (importable), `scan` = scan text refs, `native` = no `.import` sidecar. */
31
+ const FORMATS: Record<string, { cls?: string; scan?: boolean; native?: boolean }> = {
32
+ gltf: { cls: 'PackedScene', scan: true },
33
+ tscn: { cls: 'PackedScene', scan: true, native: true },
34
+ obj: { cls: 'PackedScene', scan: true },
35
+ jpg: { cls: 'CompressedTexture2D' },
36
+ jpeg: { cls: 'CompressedTexture2D' },
37
+ png: { cls: 'CompressedTexture2D' },
38
+ webp: { cls: 'CompressedTexture2D' },
39
+ svg: { cls: 'CompressedTexture2D' },
40
+ exr: { cls: 'TextureLayered' },
41
+ hdr: { cls: 'TextureLayered' },
42
+ wav: { cls: 'AudioStreamWAV' },
43
+ ogg: { cls: 'AudioStreamOggVorbis' },
44
+ mp3: { cls: 'AudioStreamMP3' },
45
+ tres: { cls: 'Resource', scan: true, native: true },
46
+ po: { cls: 'Translation', native: true },
47
+ ttf: { cls: 'FontFile' },
48
+ otf: { cls: 'FontFile' },
49
+ mtl: { scan: true },
50
+ };
51
+
52
+ const ASSET_RE = new RegExp(
53
+ `\\.(${Object.entries(FORMATS).filter(([, f]) => f.cls).map(([k]) => k).join('|')})$`,
54
+ 'i',
55
+ );
56
+ const CLASS_BY_EXT: Record<string, string> = Object.fromEntries(
57
+ Object.entries(FORMATS).filter(([, f]) => f.cls).map(([k, f]) => [k, f.cls!]),
58
+ );
59
+ const SCANNED = new Set(Object.entries(FORMATS).filter(([, f]) => f.scan).map(([k]) => k));
60
+ const NATIVE = new Set(Object.entries(FORMATS).filter(([, f]) => f.native).map(([k]) => k));
61
+
62
+ const extOf = (abs: string) => abs.slice(abs.lastIndexOf('.') + 1).toLowerCase();
63
+ const resOf = (abs: string) => 'res://' + abs.slice(ROOT.length + 1).replaceAll('\\', '/');
64
+ const isScannableText = (abs: string) => SCANNED.has(extOf(abs));
65
+ const isNativeText = (abs: string) => NATIVE.has(extOf(abs));
66
+ const isSourceAsset = (abs: string) => existsSync(abs + '.import') || isNativeText(abs);
67
+
68
+ /** Reads the imported destination (`dest_files`) out of an `.import` sidecar. */
69
+ function parseSidecarDest(text: string): string | null {
70
+ const deps = text.match(/^dest_files=\[([^\]]*)\]/m);
71
+ if (deps) {
72
+ const first = deps[1].match(/"([^"]+)"/);
73
+ if (first) {
74
+ return first[1];
75
+ }
76
+ }
77
+ const remap = text.match(/^path="([^"]+)"/m);
78
+ return remap ? remap[1] : null;
79
+ }
80
+
81
+ // Generalized reference extraction for text-based source assets: absolute
82
+ // `res://` paths (Godot scenes/resources) and relative path tokens ending in a
83
+ // known asset extension (glTF uris, OBJ/MTL textures). The literal dot before
84
+ // the extension avoids matching MIME types inside `data:` URIs.
85
+ const RES_RE = /res:\/\/[\w./\\-]+/g;
86
+ const REL_RE = new RegExp(`([\\w./\\\\-]+\\.(?:${Object.keys(FORMATS).join('|')}))`, 'g');
87
+
88
+ function extractRefs(text: string): string[] {
89
+ const refs: string[] = [];
90
+ for (const m of text.matchAll(RES_RE)) refs.push(m[0]);
91
+ for (const m of text.matchAll(REL_RE)) refs.push(m[1]);
92
+ return refs;
93
+ }
94
+
95
+ /**
96
+ * Adds a source asset's own files to `files`: imported assets contribute their
97
+ * `.import` sidecar (text) + imported product (file); native text formats
98
+ * (tscn/tres/po) contribute the file itself (text).
99
+ */
100
+ function addSource(srcAbs: string, files: Map<string, 'text' | 'file'>): void {
101
+ const impAbs = srcAbs + '.import';
102
+ if (existsSync(impAbs)) {
103
+ files.set(resOf(srcAbs) + '.import', 'text');
104
+ const dest = parseSidecarDest(readFileSync(impAbs, 'utf8'));
105
+ if (dest) {
106
+ files.set(dest, 'file');
107
+ }
108
+ } else if (isNativeText(srcAbs)) {
109
+ files.set(resOf(srcAbs), 'text');
110
+ }
111
+ }
112
+
113
+ /**
114
+ * Collects the referenced source assets (deps) of a text source: source assets
115
+ * become dep modules (each handles its own transitive deps); raw text formats
116
+ * without a sidecar (`.mtl`) are recursed into. Buffers (`.bin`) are skipped.
117
+ */
118
+ function collectDeps(abs: string, visited: Set<string>, deps: string[]): void {
119
+ if (visited.has(abs)) {
120
+ return;
121
+ }
122
+ visited.add(abs);
123
+ if (!isScannableText(abs)) {
124
+ return;
125
+ }
126
+ for (const ref of extractRefs(readFileSync(abs, 'utf8'))) {
127
+ const refAbs = ref.startsWith('res://')
128
+ ? resolve(ROOT, ref.slice('res://'.length))
129
+ : resolve(dirname(abs), ref);
130
+ if (visited.has(refAbs)) {
131
+ continue;
132
+ }
133
+ if (isSourceAsset(refAbs)) {
134
+ deps.push(refAbs);
135
+ } else if (isScannableText(refAbs)) {
136
+ collectDeps(refAbs, visited, deps);
137
+ }
138
+ }
139
+ }
140
+
141
+ function analyze(abs: string): { files: Map<string, 'text' | 'file'>; deps: string[] } {
142
+ const files = new Map<string, 'text' | 'file'>();
143
+ const deps: string[] = [];
144
+ addSource(abs, files);
145
+ collectDeps(abs, new Set(), deps);
146
+ return { files, deps };
147
+ }
148
+
149
+ function ensureModule(abs: string): string {
150
+ const res = resOf(abs);
151
+ const cls = CLASS_BY_EXT[extOf(abs)] ?? 'Resource';
152
+ const { files, deps } = analyze(abs);
153
+
154
+ const imports = [
155
+ `import { loadAsset } from '@ringozz/godot/load';`,
156
+ `import { ${cls} } from '@ringozz/godot/${cls}';`,
157
+ ];
158
+ const map: string[] = [];
159
+ let ti = 0;
160
+ let fi = 0;
161
+ for (const [resPath, kind] of files) {
162
+ const absP = resolve(ROOT, resPath.slice('res://'.length));
163
+ const v = kind === 'text' ? `c${ti++}` : `f${fi++}`;
164
+ const type = kind === 'text' ? 'text' : 'file';
165
+ const field = kind === 'text' ? 'content' : 'path';
166
+ imports.push(`import ${v} from ${JSON.stringify(absP)} with { type: '${type}' };`);
167
+ map.push(` ${JSON.stringify(resPath)}: { ${field}: ${v} },`);
168
+ }
169
+ deps.forEach((dep, i) => imports.push(`import * as dep${i} from ${JSON.stringify(dep)};`));
170
+
171
+ const filesVar = files.size ? `const files = {\n${map.join('\n')}\n};` : `const files = {};`;
172
+ const loadAsset = `const { materialize, load } = loadAsset(${JSON.stringify(res)}, ${cls}, files, [${deps.map((_, i) => `dep${i}`).join(', ')}], import.meta.hot.data);`;
173
+ return imports.join('\n') + '\n' + filesVar + '\n' + loadAsset + '\n' + `export { materialize, load as default };` + '\n';
174
+ }
175
+
176
+ const assetPlugin: BunPlugin = {
177
+ name: 'godot-assets',
178
+ setup(build) {
179
+ build.onResolve({ filter: ASSET_RE }, (args) => {
180
+ // Only JS module imports of Godot source assets become `godot`
181
+ // modules. `Bun.build` reports JS imports as `import-statement`
182
+ // (and `dynamic-import`/`require-*`) but HTML asset references
183
+ // (<link>/<img>) and CSS url() refs as `internal`/`url-token` —
184
+ // those fall through so Bun copies/hashes the file normally. The
185
+ // runtime preload (bun run / bun test) reports JS imports with no
186
+ // kind (`undefined`), so treat that as a JS import too.
187
+ if (
188
+ args.kind !== undefined &&
189
+ args.kind !== 'import-statement' &&
190
+ args.kind !== 'dynamic-import' &&
191
+ args.kind !== 'require-call' &&
192
+ args.kind !== 'require-resolve'
193
+ ) {
194
+ return;
195
+ }
196
+ const importerAbs = args.importer?.startsWith(`${NS}:`)
197
+ ? args.importer.slice(NS.length + 1)
198
+ : args.importer;
199
+ const base = importerAbs ? dirname(importerAbs) : (args.resolveDir ?? ROOT);
200
+ const abs = resolve(base, args.path);
201
+ // A module's own native-text source (e.g. `.tscn`) self-imports the
202
+ // same path — let it load as a real file.
203
+ if (abs === importerAbs) {
204
+ return;
205
+ }
206
+ return { path: abs, namespace: NS };
207
+ });
208
+ build.onLoad({ filter: /.*/, namespace: NS }, (args) => ({
209
+ contents: ensureModule(args.path),
210
+ loader: 'js',
211
+ }));
212
+ },
213
+ };
214
+
215
+ export default assetPlugin;
216
+ plugin(assetPlugin);
package/src/runtime.ts CHANGED
@@ -1,72 +1,84 @@
1
- /**********************************************************************
2
- Copyright (c) Vladimir Davidovich. All rights reserved.
3
- ***********************************************************************/
4
-
5
- const { platform, arch } = globalThis.process ?? {};
6
- const mapping: any = {
7
- 'darwin-arm64': 'macos-arm64',
8
- 'win32-x64': 'windows-x86_64',
9
- };
10
-
11
- import { getNativeModule } from './boot.ts';
12
- const { default: _mod } = getNativeModule() ?? import.meta.require(`@ringozz/godot-${mapping[`${platform}-${arch}`]}`);
13
-
14
- /** Godot instance */
15
- import type { GodotInstance } from '../gen/classes/GodotInstance.ts';
16
- export const getGodot = _mod.getGodot as () => GodotInstance;
17
-
18
- /** Base constructor for all Godot object wrappers. */
19
- export interface GodotVar {
20
- free(): void;
21
- }
22
- export const GodotVar = _mod.GodotVar as (new (...args: unknown[]) => GodotVar) & {
23
- assign<T extends GodotVar>(target: T, props: Record<string, unknown>): T;
24
- };
25
-
26
- /** Unified entry point:
27
- * - _C(this, methodId, ...args) → instance method
28
- * - _C(classId, methodId, ...args) → static method
29
- * - _C(null, methodId, ...args) → singleton lookup (_getInstance) or internal
30
- * - _C(0xHASHn, methodId, ...args) → utility function (BigInt carries hash + type metadata)
31
- */
32
- export const _C = _mod._C as (...args: unknown[]) => unknown;
33
-
34
- /** Resolve a string name to its integer handle. */
35
- export const _S = _mod._S as (name: string) => number;
36
-
37
- /** Low-level property getter for value type fields. */
38
- export const _get = _mod._get as (target: GodotVar, nameId: number) => unknown;
39
-
40
- /** Low-level property setter for value type fields. */
41
- export const _set = _mod._set as (target: GodotVar, nameId: number, val: unknown) => void;
42
-
43
- /** Register Godot object wrapper. */
44
- export const _R = _mod._R as (typeId: number, ctor: Function) => string;
45
-
46
- /** Stage bytes into the web MEMFS (Godot's `copyToFS`); undefined on desktop. */
47
- export const stageFile = (_mod as any).stageFile as ((path: string, bytes: Uint8Array) => void) | undefined;
48
-
49
- /** Get a Signal value from an Object by signal name, or connect a callback when 3rd arg given. */
50
- export const _G = _mod._G as (target: GodotVar, signalNameId: number, callback?: unknown) => unknown;
51
-
52
- /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DedicatedWorkerGlobalScope/requestAnimationFrame) */
53
- export const requestAnimationFrame = _mod.requestAnimationFrame as typeof globalThis.requestAnimationFrame ?? globalThis.requestAnimationFrame;
54
-
55
- /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DedicatedWorkerGlobalScope/cancelAnimationFrame) */
56
- export const cancelAnimationFrame = _mod.cancelAnimationFrame as typeof globalThis.cancelAnimationFrame ?? globalThis.cancelAnimationFrame;
57
-
58
- /** Make a Signal PromiseLike: connects a one-shot callback that resolves with the args tuple. */
59
- export function _P(signal: any, onfulfilled?: any, onrejected?: any) {
60
- return new Promise<any>((resolve, reject) => {
61
- if (signal.isNull()) {
62
- reject(new Error('Cannot await a null Signal'));
63
- return;
64
- }
65
- const cb = (...args: any[]) => {
66
- signal.disconnect(cb);
67
- resolve(args);
68
- };
69
- const res = signal.connect(cb);
70
- if (res !== 0) reject(new Error('Failed to connect signal: error code ' + res));
71
- }).then(onfulfilled, onrejected);
72
- }
1
+ /**********************************************************************
2
+ Copyright (c) Vladimir Davidovich. All rights reserved.
3
+ ***********************************************************************/
4
+
5
+ /** Shared runtime: platform-specific native-module selection lives in
6
+ * `boot.ts` (desktop) / `boot.browser.ts` (web, via the `exports` `./boot`
7
+ * entry's `browser` condition). `_mod` is the native module — the desktop
8
+ * addon's `module.exports` or the wasm module's `.default`.
9
+ *
10
+ * The boot leaf is imported by **package self-reference** (`@ringozz/godot/boot`),
11
+ * not by relative path: a bare specifier resolves through this package's own
12
+ * `exports` map (whose `./boot` entry's `browser` condition selects
13
+ * `boot.browser.ts` on web) exactly like the entrypoint's
14
+ * `import { preloadGodot } from '@ringozz/godot/boot'`, so both sides land on the
15
+ * same absolute path and share ONE `boot.browser.ts` module instance. (A relative
16
+ * `./boot.ts` import would let a consumer's bundler realpath it into
17
+ * `node_modules/.bun/...` while the entrypoint keeps the `node_modules/@ringozz/godot`
18
+ * path — two instances, and the preload handoff below would read `null`.)
19
+ */
20
+ import { getNativeModule } from '@ringozz/godot/boot';
21
+ const { default: _mod } = getNativeModule() as any;
22
+
23
+ /** Godot instance */
24
+ import type { GodotInstance } from '../gen/classes/GodotInstance.ts';
25
+ export const getGodot = _mod.getGodot as () => GodotInstance;
26
+
27
+ /** Base constructor for all Godot object wrappers. */
28
+ export interface GodotVar {
29
+ free(): void;
30
+ }
31
+ export const GodotVar = _mod.GodotVar as (new (...args: unknown[]) => GodotVar) & {
32
+ assign<T extends GodotVar>(target: T, props: Record<string, unknown>): T;
33
+ };
34
+
35
+ /** Unified entry point:
36
+ * - _C(this, methodId, ...args) → instance method
37
+ * - _C(classId, methodId, ...args) → static method
38
+ * - _C(null, methodId, ...args) → singleton lookup (_getInstance) or internal
39
+ * - _C(0xHASHn, methodId, ...args) → utility function (BigInt carries hash + type metadata)
40
+ */
41
+ export const _C = _mod._C as (...args: unknown[]) => unknown;
42
+
43
+ /** Resolve a string name to its integer handle. */
44
+ export const _S = _mod._S as (name: string) => number;
45
+
46
+ /** Low-level property getter for value type fields. */
47
+ export const _get = _mod._get as (target: GodotVar, nameId: number) => unknown;
48
+
49
+ /** Low-level property setter for value type fields. */
50
+ export const _set = _mod._set as (target: GodotVar, nameId: number, val: unknown) => void;
51
+
52
+ /** Register Godot object wrapper. */
53
+ export const _R = _mod._R as (typeId: number, ctor: Function) => string;
54
+
55
+ /** Stage bytes into the web MEMFS (Godot's `copyToFS`); undefined on desktop. */
56
+ export const stageFile = (_mod as any).stageFile as ((path: string, bytes: Uint8Array) => void) | undefined;
57
+
58
+ /** Get a Signal value from an Object by signal name, or connect a callback when 3rd arg given. */
59
+ export const _G = _mod._G as (target: GodotVar, signalNameId: number, callback?: unknown) => unknown;
60
+
61
+ /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DedicatedWorkerGlobalScope/requestAnimationFrame) */
62
+ export const requestAnimationFrame = _mod.requestAnimationFrame as typeof globalThis.requestAnimationFrame ?? globalThis.requestAnimationFrame;
63
+
64
+ /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DedicatedWorkerGlobalScope/cancelAnimationFrame) */
65
+ export const cancelAnimationFrame = _mod.cancelAnimationFrame as typeof globalThis.cancelAnimationFrame ?? globalThis.cancelAnimationFrame;
66
+
67
+ /** Make a Signal PromiseLike: connects a one-shot callback that resolves with the args tuple. */
68
+ export function _P(signal: any, onfulfilled?: any, onrejected?: any) {
69
+ return new Promise<any>((resolve, reject) => {
70
+ if (signal.isNull()) {
71
+ reject(new Error('Cannot await a null Signal'));
72
+ return;
73
+ }
74
+ const cb = (...args: any[]) => {
75
+ signal.disconnect(cb);
76
+ resolve(args);
77
+ };
78
+ const res = signal.connect(cb);
79
+ if (res !== 0) reject(new Error('Failed to connect signal: error code ' + res));
80
+ }).then(onfulfilled, onrejected);
81
+ }
82
+
83
+ /** Cleanup callbacks run once by `runGodot` just before the engine is freed; may be async. */
84
+ export const cleanupHooks: Set<() => void | Promise<void>> = new Set();