@gjsify/rolldown-plugin-gjsify 0.13.1 → 0.13.2

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/lib/app/gjs.js CHANGED
@@ -20,6 +20,7 @@ import { nodeModulesPathRewritePlugin, getBundleDirFromOutput } from '../plugins
20
20
  import { processStubPlugin } from '../plugins/process-stub.js';
21
21
  import { cssAsStringPlugin } from '../plugins/css-as-string.js';
22
22
  import { shebangPlugin, resolveShebangLine, inputShebangStripPlugin } from '../plugins/shebang.js';
23
+ import { wrapInputWithSideEffects } from '../utils/entry-wrapper.js';
23
24
  const _shimDir = dirname(fileURLToPath(import.meta.url));
24
25
  function resolveShim(shimName) {
25
26
  // Preferred: relative to this module's directory. Works under the
@@ -219,104 +220,6 @@ export const setupForGjs = async (input) => {
219
220
  ];
220
221
  return { options, plugins };
221
222
  };
222
- /**
223
- * If there are side-effect imports to land alongside the user's entry,
224
- * wrap each entry in a virtual module that imports them first then
225
- * re-exports the entry. Returns the rewritten `input` plus the resolveId/load
226
- * plugin that resolves the virtual ids.
227
- *
228
- * Single-input case: `'src/index.ts'` → `'\0gjsify-entry:src/index.ts'`.
229
- * Array-input case: each element gets the same wrapper id.
230
- * Record-input case: values get wrapped, keys preserved.
231
- *
232
- * `\0`-prefixed ids are Rollup's convention for synthetic modules — Rolldown
233
- * recognises and treats them as not-from-disk, skipping the default loader.
234
- */
235
- function wrapInputWithSideEffects(input, sideEffects, opts = {}) {
236
- if (sideEffects.length === 0 || input === undefined) {
237
- return { input, plugin: null };
238
- }
239
- const userEntries = new Map(); // virtualId → realPath
240
- const PREFIX = '\0gjsify-entry:';
241
- function wrap(realPath) {
242
- const id = PREFIX + realPath;
243
- userEntries.set(id, realPath);
244
- return id;
245
- }
246
- let wrappedInput;
247
- if (typeof input === 'string') {
248
- wrappedInput = wrap(input);
249
- }
250
- else if (Array.isArray(input)) {
251
- wrappedInput = input.map(wrap);
252
- }
253
- else {
254
- const out = {};
255
- for (const [name, path] of Object.entries(input)) {
256
- out[name] = wrap(path);
257
- }
258
- wrappedInput = out;
259
- }
260
- const sideEffectImports = sideEffects.map((p) => `import ${JSON.stringify(p)};`).join('\n');
261
- // Resolved real-path targets from `userEntries` get their
262
- // moduleSideEffects forced to 'no-treeshake' so the user-entry's
263
- // top-level body (`run({...})`, side-effect calls) survives tree-shake
264
- // even when its package.json restricts sideEffects to register files.
265
- const resolvedTargets = new Set();
266
- const plugin = {
267
- name: 'gjsify-virtual-entry',
268
- async resolveId(source, _importer) {
269
- if (source.startsWith(PREFIX))
270
- return source;
271
- // Force-mark the resolved user-entry target as having
272
- // top-level side effects.
273
- if (resolvedTargets.has(source)) {
274
- return { id: source, moduleSideEffects: 'no-treeshake' };
275
- }
276
- return null;
277
- },
278
- async load(id) {
279
- if (!id.startsWith(PREFIX))
280
- return null;
281
- const realPath = userEntries.get(id);
282
- if (!realPath)
283
- return null;
284
- // Resolve the user-provided entry path through the full
285
- // resolver chain so the re-export targets a real on-disk
286
- // module — otherwise Rolldown treats `src/foo.ts` as a bare
287
- // specifier and emits it as an external import.
288
- const resolved = await this.resolve(realPath, undefined, { skipSelf: true });
289
- const target = resolved?.id ?? realPath;
290
- resolvedTargets.add(target);
291
- // The bare `export * from <target>` re-exports named bindings
292
- // but does NOT execute the source module's top-level body. A
293
- // companion side-effect-only `import <target>` plus our
294
- // resolveId-side `moduleSideEffects: 'no-treeshake'` mark
295
- // forces the body to run — `run({...})` calls in test entries,
296
- // top-level await, etc.
297
- //
298
- // `export *` also never carries the `default` export. For an
299
- // executable that's irrelevant, but a library bundle imported for
300
- // its default API (a bundler plugin) needs it preserved. When
301
- // requested, import the target as a namespace (which also runs the
302
- // body, so it doubles as the side-effect import) and re-export its
303
- // `default` — safely `undefined` when the entry has none.
304
- if (opts.preserveDefaultExport) {
305
- const ns = '__gjsify_entry__';
306
- return {
307
- code: `${sideEffectImports}\nimport * as ${ns} from ${JSON.stringify(target)};\n` +
308
- `export * from ${JSON.stringify(target)};\nexport default ${ns}.default;\n`,
309
- moduleSideEffects: 'no-treeshake',
310
- };
311
- }
312
- return {
313
- code: `${sideEffectImports}\nimport ${JSON.stringify(target)};\nexport * from ${JSON.stringify(target)};\n`,
314
- moduleSideEffects: 'no-treeshake',
315
- };
316
- },
317
- };
318
- return { input: wrappedInput, plugin };
319
- }
320
223
  /**
321
224
  * Flatten the legacy `Record<string, string>` alias map into the
322
225
  * `@rollup/plugin-alias` `entries` array shape, dropping empty values.
package/lib/app/node.js CHANGED
@@ -6,12 +6,29 @@
6
6
  // not synthesise a `require()` shim for ESM consumers of bundled CJS code.
7
7
  import { aliasPlugin } from '../plugins/alias.js';
8
8
  import { deepkitPlugin } from '@gjsify/rolldown-plugin-deepkit';
9
- import { EXTERNALS_NODE } from '@gjsify/resolve-npm';
9
+ import { EXTERNALS_NODE, ALIASES_GJS_FOR_NODE } from '@gjsify/resolve-npm';
10
10
  import { getAliasesForNode } from '../utils/alias.js';
11
11
  import { globToEntryPoints } from '../utils/entry-points.js';
12
12
  import { nodeModulesPathRewritePlugin, getBundleDirFromOutput } from '../plugins/rewrite-node-modules-paths.js';
13
13
  import { cssAsStringPlugin } from '../plugins/css-as-string.js';
14
14
  import { gjsImportsEmptyPlugin } from '../plugins/gjs-imports-empty.js';
15
+ import { gjsGiNodePlugin, gjsBuiltinModulesNodePlugin } from '../plugins/gjs-gi-node.js';
16
+ import { wrapInputWithSideEffects } from '../utils/entry-wrapper.js';
17
+ /**
18
+ * Side-effect specifier the node target injects when GJS ambient globals
19
+ * (`print`/`imports`/…) are detected in the bundled output. Importing it seeds
20
+ * those globals on `globalThis` via the node-gi backend. Kept EXTERNAL (see the
21
+ * external set below) — it loads the native addon and must never be bundled.
22
+ */
23
+ const NODE_GI_GLOBALS_SPECIFIER = '@gjsify/node-gi/globals';
24
+ /**
25
+ * The node-gi standalone GJS built-in modules. The bare `system` / `gettext`
26
+ * specifiers a GJS source imports are aliased to these (via `ALIASES_GJS_FOR_NODE`,
27
+ * applied node-target-only) and, like `@gjsify/node-gi/gi`, kept EXTERNAL — they
28
+ * load the native node-gi backend and must resolve at runtime against the
29
+ * consumer's node_modules, never be bundled.
30
+ */
31
+ const NODE_GI_BARE_MODULE_SPECIFIERS = ['@gjsify/node-gi/system', '@gjsify/node-gi/gettext'];
15
32
  export const setupForNode = async (input) => {
16
33
  const userExternal = input.userExternal ?? [];
17
34
  // node-datachannel is a native C++ addon that cannot be bundled — its
@@ -19,24 +36,61 @@ export const setupForNode = async (input) => {
19
36
  // runtime against the real node_modules tree.
20
37
  //
21
38
  // GJS-specific specifiers (`gi://*`, `@girs/*`) are NOT externalised —
22
- // they are intercepted by `gjsImportsEmptyPlugin` (added to the plugins
23
- // array below) and redirected to a virtual empty ESM module. Marking them
24
- // external would leave bare `import 'gi://Gio?version=2.0'` strings in the
25
- // output that Node's default ESM loader rejects with
26
- // `ERR_UNSUPPORTED_ESM_URL_SCHEME`. The empty-module redirect makes node
27
- // bundles of cross-platform packages (which transitively import @girs/*
28
- // via *.gjs.spec / direct internal imports) loadable on Node — the GJS-
29
- // only code paths are still gated at runtime by `on('Gjs', …)` or by
30
- // `typeof globalThis.imports !== 'undefined'` guards.
31
- const exactExternal = [...EXTERNALS_NODE, 'node-datachannel', ...userExternal];
39
+ // `gi://*` is rewritten to `requireGi` by `gjsGiNodePlugin`, and `@girs/*`
40
+ // is handled by `gjsGiNodePlugin` + `gjsImportsEmptyPlugin` (both in the
41
+ // plugins array below). Marking them external would leave bare
42
+ // `import 'gi://Gio?version=2.0'` strings in the output that Node's default
43
+ // ESM loader rejects with `ERR_UNSUPPORTED_ESM_URL_SCHEME`. For a
44
+ // cross-platform package the `@girs/*` empty-module redirect makes node
45
+ // bundles (which transitively import @girs/* via *.gjs.spec / direct
46
+ // internal imports) loadable on Node — the GJS-only code paths are still
47
+ // gated at runtime by `on('Gjs', …)` or `typeof globalThis.imports` guards.
48
+ // For a GENUINE GJS source built via the node-gi reverse bridge (detected
49
+ // by `nodeGiGlobalsInject`) the `@girs/*` empty redirect is OFF so the
50
+ // namespace resolves through to `requireGi` — see the plugins array.
51
+ // `@gjsify/node-gi` is the Axis-5 GI runtime the `gjsGiNodePlugin` rewrites
52
+ // `gi://` onto. It is a native (node-gyp) addon whose loader resolves its
53
+ // `.node` binary relative to its own installed location, so it must NOT be
54
+ // bundled — keep it external so the `import … from '@gjsify/node-gi/gi'` the
55
+ // virtual shim emits resolves at runtime against the consumer's node_modules.
56
+ const exactExternal = [
57
+ ...EXTERNALS_NODE,
58
+ 'node-datachannel',
59
+ '@gjsify/node-gi',
60
+ '@gjsify/node-gi/gi',
61
+ // The GJS-ambient-globals shim (auto-injected below when `print`/
62
+ // `imports`/… are referenced). Like `@gjsify/node-gi/gi` it loads the
63
+ // native addon and must resolve at runtime, never be bundled.
64
+ NODE_GI_GLOBALS_SPECIFIER,
65
+ // The node-gi standalone GJS built-in modules (`system`/`gettext`),
66
+ // reached when the alias layer rewrites the bare specifiers. Kept
67
+ // external for the same reason as the gi/globals shims above.
68
+ ...NODE_GI_BARE_MODULE_SPECIFIERS,
69
+ ...userExternal,
70
+ ];
32
71
  const external = (id) => {
33
72
  if (exactExternal.includes(id))
34
73
  return true;
74
+ if (id === '@gjsify/node-gi' || id.startsWith('@gjsify/node-gi/'))
75
+ return true;
35
76
  return false;
36
77
  };
37
78
  const format = input.pluginOptions.format ?? 'esm';
38
79
  const exclude = input.pluginOptions.exclude ?? [];
39
80
  const entryPoints = await globToEntryPoints(input.input, exclude);
81
+ // When the CLI's pre-build detection (`detectNodeGiGlobals`) found GJS
82
+ // ambient globals in the bundled output, wrap the entry so it side-effect
83
+ // imports the node-gi globals shim BEFORE the user code runs. The import is
84
+ // injected ONLY when detected — a bundle that never touches `print`/`imports`
85
+ // stays free of `@gjsify/node-gi/globals`, so it loads on plain Node without
86
+ // node-gi installed (the eager-native-load regression guard, same lesson as
87
+ // the lazy `gi://` shim in #641). Reuses the SAME virtual-entry wrapper the
88
+ // GJS `--globals auto` machinery uses.
89
+ const sideEffectImports = [];
90
+ if (input.pluginOptions.nodeGiGlobalsInject)
91
+ sideEffectImports.push(NODE_GI_GLOBALS_SPECIFIER);
92
+ const virtualEntries = wrapInputWithSideEffects(entryPoints, sideEffectImports);
93
+ const finalInput = virtualEntries.input;
40
94
  const aliasMap = {
41
95
  ...getAliasesForNode({ external }),
42
96
  ...input.pluginOptions.aliases,
@@ -53,7 +107,7 @@ export const setupForNode = async (input) => {
53
107
  // declared`.
54
108
  const banner = undefined;
55
109
  const options = {
56
- input: entryPoints,
110
+ input: finalInput,
57
111
  platform: 'node',
58
112
  // Pass the EXACT-MATCH external set as a plain string array, NOT the
59
113
  // `external` predicate function. `@gjsify/rolldown-native` ships the
@@ -100,12 +154,38 @@ export const setupForNode = async (input) => {
100
154
  treeshake: true,
101
155
  };
102
156
  const plugins = [
103
- // gjsImportsEmptyPlugin runs in `resolveId` order: 'pre', so it
104
- // intercepts `@girs/*` and `gi://*` specifiers before `aliasPlugin`
105
- // (and before the default resolver tries to read the @girs/* package
106
- // entry, which contains a top-level `import 'gi://...'` that Node
107
- // cannot resolve). Same composition order as `app/browser.ts`.
108
- gjsImportsEmptyPlugin(),
157
+ // Virtual-entry plugin runs FIRST so its resolveId/load match the
158
+ // synthetic `\0gjsify-entry:` ids that `wrapInputWithSideEffects`
159
+ // produces (no-op when nothing was injected).
160
+ ...(virtualEntries.plugin ? [virtualEntries.plugin] : []),
161
+ // gjsGiNodePlugin runs FIRST (resolveId order 'pre' + array order): it
162
+ // claims `gi://Ns?version=X` and rewrites it to the `@gjsify/node-gi`
163
+ // runtime, so a real GJS/GI source builds + runs on Node. It returns
164
+ // null for `@girs/*`.
165
+ gjsGiNodePlugin(),
166
+ // Bare GJS built-in modules (`system`/`gettext`): claimed BEFORE the
167
+ // aliasPlugin so they resolve to the EXTERNAL `@gjsify/node-gi/<mod>`
168
+ // shims without a disk resolution (works without node-gi installed,
169
+ // like gi://). Node-target-only — never active on gjs/browser/ns.
170
+ gjsBuiltinModulesNodePlugin(ALIASES_GJS_FOR_NODE),
171
+ // gjsImportsEmptyPlugin then decides the fate of `@girs/*` before
172
+ // `aliasPlugin` and the default resolver. Same composition order as
173
+ // `app/browser.ts`. `emptyGirs` is GATED on `nodeGiGlobalsInject`:
174
+ // • false-flag (default Node build) → `@girs/*` → empty module. A
175
+ // cross-platform polyfill package whose GJS-only code paths import
176
+ // `@girs/*` transitively (e.g. via `@gjsify/unit`) stays loadable on
177
+ // plain Node WITHOUT node-gi installed — exactly the existing
178
+ // behaviour, never regressed.
179
+ // • node-gi build (`nodeGiGlobalsInject` true — the genuine-GJS-source
180
+ // signal) → `@girs/<ns>-<ver>` falls through to its real package
181
+ // body (`import Adw from 'gi://Adw?version=1'; export default Adw`),
182
+ // whose inner `gi://` is rewritten to `requireGi` by gjsGiNodePlugin
183
+ // above. This routes `@girs/adw-1` → `requireGi('Adw','1')` WITHOUT
184
+ // a lowercased-pkg→namespace map (the proper-cased namespace comes
185
+ // from the @girs package's own `gi://` specifier). `gi://*` is
186
+ // already claimed by gjsGiNodePlugin, so this plugin's `gi://`
187
+ // branch is dead on the node target either way.
188
+ gjsImportsEmptyPlugin({ emptyGirs: !input.pluginOptions.nodeGiGlobalsInject }),
109
189
  aliasPlugin({ entries: flattenAliases(aliasMap) }),
110
190
  deepkitPlugin({ reflection: input.pluginOptions.reflection }),
111
191
  cssAsStringPlugin(),
package/lib/globals.d.ts CHANGED
@@ -1,4 +1,4 @@
1
1
  export { resolveGlobalsList, writeRegisterInjectFile, isRegisterPathResolvable, filterResolvableRegisterPaths } from './utils/scan-globals.js';
2
- export { detectFreeGlobals } from './utils/detect-free-globals.js';
3
- export { detectAutoGlobals, describeGiBackedInjection } from './utils/auto-globals.js';
2
+ export { detectFreeGlobals, detectGjsAmbientGlobals, GJS_AMBIENT_GLOBALS } from './utils/detect-free-globals.js';
3
+ export { detectAutoGlobals, detectNodeGiGlobals, describeGiBackedInjection } from './utils/auto-globals.js';
4
4
  export type { AutoGlobalsResult, DetectAutoGlobalsOptions, AnalysisOptions } from './utils/auto-globals.js';
package/lib/globals.js CHANGED
@@ -5,5 +5,5 @@
5
5
  // stub that the plugin picks up via its `autoGlobalsInject` option. See the
6
6
  // "Tree-shakeable Globals" section in AGENTS.md for the architecture.
7
7
  export { resolveGlobalsList, writeRegisterInjectFile, isRegisterPathResolvable, filterResolvableRegisterPaths } from './utils/scan-globals.js';
8
- export { detectFreeGlobals } from './utils/detect-free-globals.js';
9
- export { detectAutoGlobals, describeGiBackedInjection } from './utils/auto-globals.js';
8
+ export { detectFreeGlobals, detectGjsAmbientGlobals, GJS_AMBIENT_GLOBALS } from './utils/detect-free-globals.js';
9
+ export { detectAutoGlobals, detectNodeGiGlobals, describeGiBackedInjection } from './utils/auto-globals.js';
@@ -0,0 +1,37 @@
1
+ import type { Plugin } from 'rolldown';
2
+ /** Parse a `gi://Ns?version=X` specifier into its namespace + optional version. */
3
+ export declare function parseGiSpecifier(source: string): {
4
+ namespace: string;
5
+ version?: string;
6
+ } | null;
7
+ /** Build the runtime shim source for a resolved `gi://` namespace. */
8
+ export declare function giNodeShimSource(namespace: string, version?: string): string;
9
+ export declare function gjsGiNodePlugin(): Plugin;
10
+ /**
11
+ * For `--app node`: rewrite the bare GJS built-in module specifiers (`system`,
12
+ * `gettext`) to their `@gjsify/node-gi` reverse-bridge shims, kept EXTERNAL.
13
+ *
14
+ * GJS exposes `system`/`gettext` as built-in ESM modules
15
+ * (`import System from 'system'`); Node has no equivalent. This resolves the
16
+ * bare specifier to `@gjsify/node-gi/system` / `@gjsify/node-gi/gettext` and
17
+ * marks it external so it is NOT bundled — resolved at runtime against the
18
+ * consumer's node_modules, exactly like `@gjsify/node-gi/gi` (the `gi://`
19
+ * rewrite) and `@gjsify/node-gi/globals`.
20
+ *
21
+ * Returning `{ external: true }` from `resolveId` is the form honoured by BOTH
22
+ * bundler engines (npm rolldown on Node AND `@gjsify/rolldown-native` on GJS,
23
+ * whose JSON options boundary drops a function `external` but keeps resolveId
24
+ * results — the same reason `app/gjs.ts` uses `externalsPlugin`). It also avoids
25
+ * a disk `this.resolve()` of the target, so the build does NOT require
26
+ * `@gjsify/node-gi` installed (a `system`/`gettext` import gated to GJS-only code
27
+ * paths stays harmless on plain Node — the gi:// gated-load lesson). The generic
28
+ * `aliasPlugin` cannot serve this role: it resolves the target on disk and falls
29
+ * through (leaving a bare, unresolvable `system`) when node-gi is absent.
30
+ *
31
+ * Gating: this plugin is registered ONLY by the `--app node` orchestrator, so
32
+ * the gjs/browser/nativescript targets never hijack a bare `system`/`gettext`
33
+ * — identical scoping to the `gi://` rewrite. `entries` is `ALIASES_GJS_FOR_NODE`
34
+ * (the declarative source of truth). The handler guard is the load-bearing check
35
+ * (correct even when the filter does not pre-filter, e.g. under Vite).
36
+ */
37
+ export declare function gjsBuiltinModulesNodePlugin(entries: Record<string, string>): Plugin;
@@ -0,0 +1,144 @@
1
+ // For `--app node`: redirect `gi://Ns?version=X` imports to the `@gjsify/node-gi`
2
+ // L1 runtime (`requireGi`) instead of an empty module. This is the Axis-5
3
+ // reverse bridge — it lets the SAME GJS/GObject-Introspection source that builds
4
+ // for `--app gjs` (where `gi://` is a real native protocol) also build + run for
5
+ // `--app node`, where `@gjsify/node-gi` provides the GIRepository backend.
6
+ //
7
+ // `import Gtk from 'gi://Gtk?version=4.0'` is rewritten to a virtual module whose
8
+ // default export is a lazy Proxy over `requireGi('Gtk', '4.0')` — close to how
9
+ // GJS lowers `gi://` to `$$gi.require(...)`. The namespace (and @gjsify/node-gi
10
+ // itself) is resolved on FIRST ACCESS, not at import: a `gi://` import gated to
11
+ // GJS-only code paths stays harmless on Node when @gjsify/node-gi is absent.
12
+ //
13
+ // `@girs/*` is deliberately NOT claimed here (this plugin returns null for
14
+ // them, falling through). Those are ambient/type packages whose VALUE entry
15
+ // re-exports `gi://` (`@girs/adw-1/adw-1.js` is `import Adw from
16
+ // 'gi://Adw?version=1'; export default Adw`). On a default Node build
17
+ // `gjsImportsEmptyPlugin` maps them to an empty module. On a node-gi build
18
+ // (`nodeGiGlobalsInject`, see `app/node.ts`) that empty redirect is OFF: the
19
+ // `@girs/<ns>-<ver>` import resolves to its real body and ITS inner `gi://` is
20
+ // then rewritten by THIS plugin — so `@girs/adw-1` routes to
21
+ // `requireGi('Adw','1')` with the proper-cased namespace taken straight from
22
+ // the @girs package's own `gi://` specifier (no lowercased-pkg→namespace map
23
+ // needed). The `@gjsify/node-gi/gi` import the virtual module emits is kept
24
+ // EXTERNAL (a native addon cannot be bundled), so it resolves at runtime
25
+ // against the consumer's node_modules.
26
+ //
27
+ // Portability note (same as `gjs-imports-empty.ts`): the `filter` is a Rolldown
28
+ // fast-path; the internal guard in the handler is the load-bearing check so the
29
+ // plugin is correct even when the filter does not pre-filter (e.g. under Vite).
30
+ const GI_NODE_VIRTUAL_PREFIX = '\0gjsify-gi-node:';
31
+ /** Parse a `gi://Ns?version=X` specifier into its namespace + optional version. */
32
+ export function parseGiSpecifier(source) {
33
+ if (!source.startsWith('gi://'))
34
+ return null;
35
+ const rest = source.slice('gi://'.length);
36
+ const queryIndex = rest.indexOf('?');
37
+ const namespace = queryIndex === -1 ? rest : rest.slice(0, queryIndex);
38
+ if (!namespace)
39
+ return null;
40
+ let version;
41
+ if (queryIndex !== -1) {
42
+ const params = new URLSearchParams(rest.slice(queryIndex + 1));
43
+ version = params.get('version') ?? undefined;
44
+ }
45
+ return { namespace, version };
46
+ }
47
+ /** Build the runtime shim source for a resolved `gi://` namespace. */
48
+ export function giNodeShimSource(namespace, version) {
49
+ const versionArg = version ? `, ${JSON.stringify(version)}` : '';
50
+ // Load @gjsify/node-gi LAZILY (createRequire, on first access) — NEVER at
51
+ // module init. A `gi://` import that is gated to GJS-only code paths (very
52
+ // common in cross-platform packages — e.g. an `on('Gjs')` block or a
53
+ // `*.gjs.spec`) is then harmless on Node when @gjsify/node-gi is not
54
+ // installed: the bundle loads, the namespace is resolved only if the code
55
+ // actually touches it. This preserves the old empty-stub safety for unused
56
+ // imports while making used ones real. `require()` (not dynamic `import()`)
57
+ // keeps the default export synchronous, matching `import Ns from 'gi://Ns'`.
58
+ return (`import { createRequire } from 'node:module';\n` +
59
+ `const require = createRequire(import.meta.url);\n` +
60
+ `let cached;\n` +
61
+ `function load() {\n` +
62
+ ` if (cached === undefined) {\n` +
63
+ ` cached = require('@gjsify/node-gi/gi').requireGi(${JSON.stringify(namespace)}${versionArg});\n` +
64
+ ` }\n` +
65
+ ` return cached;\n` +
66
+ `}\n` +
67
+ `export default new Proxy(Object.create(null), {\n` +
68
+ ` get(_target, prop) { return load()[prop]; },\n` +
69
+ ` has(_target, prop) { return prop in load(); },\n` +
70
+ `});\n`);
71
+ }
72
+ export function gjsGiNodePlugin() {
73
+ return {
74
+ name: 'gjsify-gi-node',
75
+ resolveId: {
76
+ order: 'pre',
77
+ filter: { id: /^gi:\/\// },
78
+ handler(source) {
79
+ const parsed = parseGiSpecifier(source);
80
+ if (parsed === null)
81
+ return null;
82
+ const suffix = parsed.version ? `@${parsed.version}` : '';
83
+ return { id: `${GI_NODE_VIRTUAL_PREFIX}${parsed.namespace}${suffix}` };
84
+ },
85
+ },
86
+ load(id) {
87
+ if (!id.startsWith(GI_NODE_VIRTUAL_PREFIX))
88
+ return null;
89
+ const spec = id.slice(GI_NODE_VIRTUAL_PREFIX.length);
90
+ const atIndex = spec.lastIndexOf('@');
91
+ const namespace = atIndex === -1 ? spec : spec.slice(0, atIndex);
92
+ const version = atIndex === -1 ? undefined : spec.slice(atIndex + 1);
93
+ return { code: giNodeShimSource(namespace, version), moduleSideEffects: false };
94
+ },
95
+ };
96
+ }
97
+ /**
98
+ * For `--app node`: rewrite the bare GJS built-in module specifiers (`system`,
99
+ * `gettext`) to their `@gjsify/node-gi` reverse-bridge shims, kept EXTERNAL.
100
+ *
101
+ * GJS exposes `system`/`gettext` as built-in ESM modules
102
+ * (`import System from 'system'`); Node has no equivalent. This resolves the
103
+ * bare specifier to `@gjsify/node-gi/system` / `@gjsify/node-gi/gettext` and
104
+ * marks it external so it is NOT bundled — resolved at runtime against the
105
+ * consumer's node_modules, exactly like `@gjsify/node-gi/gi` (the `gi://`
106
+ * rewrite) and `@gjsify/node-gi/globals`.
107
+ *
108
+ * Returning `{ external: true }` from `resolveId` is the form honoured by BOTH
109
+ * bundler engines (npm rolldown on Node AND `@gjsify/rolldown-native` on GJS,
110
+ * whose JSON options boundary drops a function `external` but keeps resolveId
111
+ * results — the same reason `app/gjs.ts` uses `externalsPlugin`). It also avoids
112
+ * a disk `this.resolve()` of the target, so the build does NOT require
113
+ * `@gjsify/node-gi` installed (a `system`/`gettext` import gated to GJS-only code
114
+ * paths stays harmless on plain Node — the gi:// gated-load lesson). The generic
115
+ * `aliasPlugin` cannot serve this role: it resolves the target on disk and falls
116
+ * through (leaving a bare, unresolvable `system`) when node-gi is absent.
117
+ *
118
+ * Gating: this plugin is registered ONLY by the `--app node` orchestrator, so
119
+ * the gjs/browser/nativescript targets never hijack a bare `system`/`gettext`
120
+ * — identical scoping to the `gi://` rewrite. `entries` is `ALIASES_GJS_FOR_NODE`
121
+ * (the declarative source of truth). The handler guard is the load-bearing check
122
+ * (correct even when the filter does not pre-filter, e.g. under Vite).
123
+ */
124
+ export function gjsBuiltinModulesNodePlugin(entries) {
125
+ const keys = Object.keys(entries);
126
+ // A filter for the exact bare names — a Rolldown fast-path only. The handler
127
+ // re-checks membership so it stays correct under engines that ignore filters.
128
+ const filter = keys.length > 0
129
+ ? { id: new RegExp(`^(?:${keys.map((k) => k.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')).join('|')})$`) }
130
+ : undefined;
131
+ return {
132
+ name: 'gjsify-builtin-modules-node',
133
+ resolveId: {
134
+ order: 'pre',
135
+ ...(filter ? { filter } : {}),
136
+ handler(source) {
137
+ const target = entries[source];
138
+ if (!target)
139
+ return null;
140
+ return { id: target, external: true };
141
+ },
142
+ },
143
+ };
144
+ }
@@ -1,2 +1,13 @@
1
1
  import type { Plugin } from 'rolldown';
2
- export declare function gjsImportsEmptyPlugin(): Plugin;
2
+ export interface GjsImportsEmptyOptions {
3
+ /**
4
+ * Whether `@girs/*` specifiers are redirected to the empty module. Default
5
+ * `true` (browser / cross-platform Node behaviour). Set `false` on the
6
+ * `--app node` node-gi path so `@girs/<ns>-<ver>` resolves to its real body
7
+ * and the inner `gi://` is rewritten to `requireGi` by `gjsGiNodePlugin`.
8
+ * `gi://*` is always handled (in node mode it is already claimed by
9
+ * `gjsGiNodePlugin` before this plugin runs, so this only affects browser).
10
+ */
11
+ emptyGirs?: boolean;
12
+ }
13
+ export declare function gjsImportsEmptyPlugin(options?: GjsImportsEmptyOptions): Plugin;
@@ -7,6 +7,23 @@
7
7
  // browser cannot resolve at runtime; instead we resolve them to a virtual
8
8
  // empty ESM module so the bundle is self-contained.
9
9
  //
10
+ // `@girs/<ns>-<ver>` carve-out (`emptyGirs: false`): on the `--app node`
11
+ // target, when the bundle is a genuine GJS source being run through the
12
+ // `@gjsify/node-gi` reverse bridge, an `@girs/adw-1` VALUE import must resolve
13
+ // to its real package body — `@girs/adw-1/adw-1.js` is literally
14
+ // `import Adw from 'gi://Adw?version=1'; export default Adw` — so that the
15
+ // inner `gi://` import is rewritten to `requireGi(...)` by `gjsGiNodePlugin`
16
+ // (which runs FIRST). Mapping `@girs/*` to an empty module here instead would
17
+ // strand the import as `{}`, and a `class extends ({}).Bin` throws
18
+ // `Class extends value undefined`. The `gjsGiNodePlugin` claims `gi://` before
19
+ // this plugin runs, so on the node target this plugin only ever decides the
20
+ // fate of `@girs/*`; `emptyGirs:false` lets them fall through to disk while
21
+ // `gi://*` (never reached on node) is unaffected. The carve-out is GATED — see
22
+ // `app/node.ts`, where it is enabled only when `nodeGiGlobalsInject` is set
23
+ // (the same genuine-GJS-source signal that drives the globals shim) so a
24
+ // cross-platform polyfill package's plain-Node bundle keeps `@girs/*`→empty
25
+ // and loads WITHOUT node-gi installed.
26
+ //
10
27
  // Portability note: the `filter: { id: ... }` below is a Rolldown fast-path
11
28
  // — Rolldown pre-filters which specifiers reach `handler`. Under Vite (which
12
29
  // also runs Rolldown for `build` but does NOT honor the Rolldown-specific
@@ -15,18 +32,22 @@
15
32
  // the plugin correct regardless of whether the filter pre-filtered — it is
16
33
  // the load-bearing check; the `filter` is a defense-in-depth optimization.
17
34
  const GJSIMPORTS_VIRTUAL_ID = '\0gjsify-empty-gjs-import';
18
- export function gjsImportsEmptyPlugin() {
35
+ export function gjsImportsEmptyPlugin(options = {}) {
36
+ const emptyGirs = options.emptyGirs ?? true;
37
+ // When `@girs/*` is carved out, only `gi://*` reaches the empty redirect.
38
+ const matcher = emptyGirs ? /^(@girs\/|gi:\/\/)/ : /^gi:\/\//;
19
39
  return {
20
40
  name: 'gjsify-gjs-imports-empty',
21
41
  resolveId: {
22
42
  order: 'pre',
23
- filter: { id: /^(@girs\/|gi:\/\/)/ },
43
+ filter: { id: matcher },
24
44
  handler(source) {
25
45
  // Internal guard: do not rely solely on the Rolldown `filter`
26
- // above (it may not pre-filter under Vite). Only intercept
27
- // `@girs/*` and `gi://*` specifiers; let everything else fall
28
- // through to the default resolver chain.
29
- if (!/^(@girs\/|gi:\/\/)/.test(source))
46
+ // above (it may not pre-filter under Vite). Only intercept the
47
+ // matched specifiers; let everything else (including `@girs/*`
48
+ // when `emptyGirs` is false) fall through to the default
49
+ // resolver chain.
50
+ if (!matcher.test(source))
30
51
  return null;
31
52
  return { id: GJSIMPORTS_VIRTUAL_ID };
32
53
  },
@@ -43,6 +43,17 @@ export interface PluginOptions {
43
43
  * applies to `--app gjs`.
44
44
  */
45
45
  autoGlobalsInject?: string;
46
+ /**
47
+ * `--app node` only. When true, the node factory wraps the entry so it
48
+ * side-effect imports `@gjsify/node-gi/globals` before the user code runs,
49
+ * seeding the GJS ambient globals (`print`/`printerr`/`log`/`logError`/
50
+ * `ARGV`/`imports`) on Node. Set by the CLI after `detectNodeGiGlobals`
51
+ * finds those globals in the bundled (post-tree-shake) output. Left false
52
+ * when none are referenced — importing the shim eagerly loads the native
53
+ * node-gi addon, so it must NEVER be injected into a bundle that doesn't
54
+ * use the globals. Defaults to `false`.
55
+ */
56
+ nodeGiGlobalsInject?: boolean;
46
57
  /**
47
58
  * Preserve the entry module's `default` export through the `--app gjs`
48
59
  * side-effect entry wrapper. The wrapper normally re-exports the entry with
@@ -135,4 +135,23 @@ type GjsifyPluginFactory = (options: PluginOptions) => GjsifyFactoryReturn | Pro
135
135
  * @param options Optional `extraGlobalsList` / `excludeGlobals`.
136
136
  */
137
137
  export declare function detectAutoGlobals(analysisOptions: AnalysisOptions, pluginOptions: Omit<PluginOptions, 'autoGlobalsInject'>, gjsifyPluginFactory: GjsifyPluginFactory, verbose?: boolean, options?: DetectAutoGlobalsOptions, bundler?: AnalysisBundler): Promise<AutoGlobalsResult>;
138
+ /**
139
+ * `--app node` GJS-ambient-globals detection (the reverse of `--globals auto`).
140
+ *
141
+ * Runs ONE in-memory node bundle (no injection) and scans each chunk for the
142
+ * GJS ambient globals (`print`/`printerr`/`log`/`logError`/`ARGV`/`imports`)
143
+ * that `@gjsify/node-gi/globals` seeds. Returns `true` iff any is referenced in
144
+ * the bundled, tree-shaken output — the signal the CLI uses to flip
145
+ * `pluginOptions.nodeGiGlobalsInject` for the final build.
146
+ *
147
+ * A SINGLE pass suffices (unlike the GJS register-injection loop): the shim is
148
+ * EXTERNAL, so injecting it adds no bundled code that could reference more
149
+ * globals — there is no tree-shaking dependency cycle to converge.
150
+ *
151
+ * Critically, detection is on the bundled output AFTER tree-shaking, so a
152
+ * `print`/`imports` reference behind statically-dead code does not trigger
153
+ * injection — importing the shim eagerly loads the native node-gi addon, which
154
+ * crashes on plain Node without node-gi. See `detectGjsAmbientGlobals`.
155
+ */
156
+ export declare function detectNodeGiGlobals(analysisOptions: AnalysisOptions, pluginOptions: Omit<PluginOptions, 'nodeGiGlobalsInject'>, gjsifyPluginFactory: GjsifyPluginFactory, bundler?: AnalysisBundler): Promise<boolean>;
138
157
  export {};
@@ -36,7 +36,7 @@ const defaultBundler = async ({ rolldownInput, format }) => {
36
36
  await build.close();
37
37
  }
38
38
  };
39
- import { detectFreeGlobals } from './detect-free-globals.js';
39
+ import { detectFreeGlobals, detectGjsAmbientGlobals } from './detect-free-globals.js';
40
40
  import { resolveGlobalsList, writeRegisterInjectFile, filterResolvableRegisterPaths, isRegisterPathResolvable, } from './scan-globals.js';
41
41
  import { GJS_GLOBALS_MAP, GJS_GI_BACKED_REGISTERS } from '@gjsify/resolve-npm/globals-map';
42
42
  import { REGISTER_GLOBALS_CLOSURE } from '@gjsify/resolve-npm/register-globals-closure';
@@ -399,6 +399,86 @@ export async function detectAutoGlobals(analysisOptions, pluginOptions, gjsifyPl
399
399
  }
400
400
  return applyExcludeGlobals(detected, currentInject, extraRegisterPaths, options.excludeGlobals, cwd);
401
401
  }
402
+ /**
403
+ * `--app node` GJS-ambient-globals detection (the reverse of `--globals auto`).
404
+ *
405
+ * Runs ONE in-memory node bundle (no injection) and scans each chunk for the
406
+ * GJS ambient globals (`print`/`printerr`/`log`/`logError`/`ARGV`/`imports`)
407
+ * that `@gjsify/node-gi/globals` seeds. Returns `true` iff any is referenced in
408
+ * the bundled, tree-shaken output — the signal the CLI uses to flip
409
+ * `pluginOptions.nodeGiGlobalsInject` for the final build.
410
+ *
411
+ * A SINGLE pass suffices (unlike the GJS register-injection loop): the shim is
412
+ * EXTERNAL, so injecting it adds no bundled code that could reference more
413
+ * globals — there is no tree-shaking dependency cycle to converge.
414
+ *
415
+ * Critically, detection is on the bundled output AFTER tree-shaking, so a
416
+ * `print`/`imports` reference behind statically-dead code does not trigger
417
+ * injection — importing the shim eagerly loads the native node-gi addon, which
418
+ * crashes on plain Node without node-gi. See `detectGjsAmbientGlobals`.
419
+ */
420
+ export async function detectNodeGiGlobals(analysisOptions, pluginOptions, gjsifyPluginFactory, bundler = defaultBundler) {
421
+ const factoryResult = await gjsifyPluginFactory(pluginOptions);
422
+ let gjsifyInstance;
423
+ let orchestratorOptions;
424
+ if (isFullConfig(factoryResult)) {
425
+ orchestratorOptions = factoryResult.options;
426
+ gjsifyInstance = factoryResult.plugins;
427
+ }
428
+ else {
429
+ gjsifyInstance = factoryResult;
430
+ }
431
+ const callerPlugins = (analysisOptions.plugins ?? []).filter((p) => {
432
+ const name = p && typeof p === 'object' && 'name' in p ? p.name : undefined;
433
+ return name !== 'gjsify' && name !== 'gjsify-orchestrator';
434
+ });
435
+ const gjsifyPluginsArray = Array.isArray(gjsifyInstance) ? gjsifyInstance : [gjsifyInstance];
436
+ // Reuse the FULL orchestrator options as the base so the analysis bundle
437
+ // goes through the EXACT SAME module resolution as the real `--app node`
438
+ // build — most importantly `platform: 'node'`, without which Rolldown does
439
+ // not treat `node:*` as builtins and the @gjsify/rolldown-plugin-pnp
440
+ // resolver rejects `node:fs` in a non-Node context (`RESOLVE_ERROR`). It
441
+ // also carries `external` (the node externals incl. `@gjsify/node-gi/*`),
442
+ // `resolve` (conditionNames/mainFields) and `treeshake`. We strip only the
443
+ // disk-write `output` (the in-memory `generate({format})` handles output)
444
+ // and override `input`/`plugins`. Analysis-side overrides win when set.
445
+ // Mirrors how `detectAutoGlobals` reuses the orchestrator config, with the
446
+ // platform/external/resolve carried verbatim instead of cherry-picked.
447
+ const baseOptions = orchestratorOptions ? { ...orchestratorOptions } : {};
448
+ delete baseOptions.output;
449
+ let chunkCodes;
450
+ try {
451
+ chunkCodes = await bundler({
452
+ rolldownInput: {
453
+ ...baseOptions,
454
+ input: analysisOptions.input,
455
+ external: analysisOptions.external ?? baseOptions.external,
456
+ resolve: analysisOptions.resolve ?? baseOptions.resolve,
457
+ transform: analysisOptions.transform ?? baseOptions.transform,
458
+ plugins: [...callerPlugins, ...gjsifyPluginsArray],
459
+ logLevel: 'silent',
460
+ },
461
+ format: analysisOptions.format ?? 'esm',
462
+ });
463
+ }
464
+ catch (e) {
465
+ // Fail SAFE: a detection-pass failure must NEVER break a build that
466
+ // would otherwise succeed. Fall back to NOT injecting the shim — worst
467
+ // case is a missing global (a clear `ReferenceError: print is not
468
+ // defined` at runtime, recoverable via `--globals` or an explicit
469
+ // `import '@gjsify/node-gi/globals'`), never a hard build failure.
470
+ console.warn('[gjsify] --app node: could not analyse the bundle for GJS ambient globals ' +
471
+ `(${e instanceof Error ? e.message : String(e)}); skipping @gjsify/node-gi/globals ` +
472
+ 'injection. If this build uses print/imports/ARGV, add `import ' +
473
+ "'@gjsify/node-gi/globals'` to the entry or pass --globals.");
474
+ return false;
475
+ }
476
+ for (const code of chunkCodes) {
477
+ if (detectGjsAmbientGlobals(code).size > 0)
478
+ return true;
479
+ }
480
+ return false;
481
+ }
402
482
  /**
403
483
  * Append an additional entry path to a Rolldown `input` value while
404
484
  * preserving its shape (string → array, array → array, record → record).
@@ -1,30 +1,35 @@
1
1
  /**
2
- * Parse bundled JS code and return the set of free (unbound) identifiers
3
- * that match known GJS globals from `GJS_GLOBALS_MAP`.
4
- *
5
- * "Free" means the identifier is referenced but never declared in the
6
- * module (var/let/const/function/class/import/param/catch).
7
- *
8
- * After esbuild bundling + minification, local variables that shadow
9
- * globals are renamed to short names, so any surviving known-global name
10
- * in the output is almost certainly a true global reference. The
11
- * declared-names check is a safety net for edge cases where esbuild
12
- * keeps the original name.
2
+ * Parse bundled JS output and return the set of free (unbound) identifiers that
3
+ * match the known web/Node GJS globals from `GJS_GLOBALS_MAP`. Drives the
4
+ * `--app gjs --globals auto` injection. See `scanFreeGlobals` for the rules.
5
+ */
6
+ export declare function detectFreeGlobals(code: string): Set<string>;
7
+ /**
8
+ * The GJS ambient globals that exist implicitly under gjs but not on Node:
9
+ * `print`/`printerr`/`log`/`logError`, the `ARGV` array, and the legacy
10
+ * `imports` object (`imports.gi.Gtk`, `imports.system`, `imports.gettext`).
11
+ * `@gjsify/node-gi/globals` seeds these on `globalThis` when imported.
13
12
  *
14
- * `typeof X` references that appear in presence-check guards
15
- * (`typeof document !== 'undefined'`) and NOWHERE ELSE in the bundle are
16
- * NOT counted as free-global uses. Such guards are pervasive in
17
- * isomorphic npm packages that support both browser and non-browser
18
- * runtimes; on GJS the guarded branch is dead but the bundler cannot DCE
19
- * a `typeof` expression (its value depends on the runtime). If the same
20
- * identifier also appears in a genuine reference position the injection
21
- * still fires — the typeof-guard suppression only applies when the guard
22
- * is the SOLE occurrence.
13
+ * This is the REVERSE of `GJS_GLOBALS_MAP` (which maps Node/Web globals onto
14
+ * GJS): it's the set the `--app node` target injects the node-gi globals shim
15
+ * for. Kept here next to the detector so the two never drift.
16
+ */
17
+ export declare const GJS_AMBIENT_GLOBALS: ReadonlySet<string>;
18
+ /**
19
+ * Detect references to the GJS ambient globals (`GJS_AMBIENT_GLOBALS`) in a
20
+ * bundled `--app node` chunk — the signal that the bundle needs
21
+ * `@gjsify/node-gi/globals` injected.
23
22
  *
24
- * If `typeof X` was the ONLY reference to a global AND its polyfill
25
- * package is unresolvable, silently skipping avoids an unresolved-import
26
- * hard error at bundle time. The resolvability gate in `auto-globals.ts`
27
- * provides the second layer of protection for cases where `X` does appear
28
- * in a real reference position but the package is still absent.
23
+ * Runs on the bundled output AFTER tree-shaking (same property the GJS path
24
+ * relies on), so a `print`/`imports` reference behind a statically-dead branch
25
+ * does not trigger injection. Detects only BARE free identifiers — the genuine
26
+ * GJS-source shape (`print(...)`, `imports.gi.Gtk`). The `globalThis.imports` /
27
+ * `globalThis.print` host-member form is the cross-platform isomorphic-GUARD
28
+ * shape (`if (typeof globalThis.imports !== 'undefined') { … }`) and is
29
+ * deliberately ignored: injecting `@gjsify/node-gi/globals` for it would break
30
+ * plain-Node loadability of a package that merely gates GJS usage (the bare
31
+ * external import is unresolvable without node-gi; the shim eagerly loads the
32
+ * native addon). Pure `typeof imports` probes are deferred too. See
33
+ * `ignoreHostMembers`.
29
34
  */
30
- export declare function detectFreeGlobals(code: string): Set<string>;
35
+ export declare function detectGjsAmbientGlobals(code: string): Set<string>;
@@ -123,35 +123,15 @@ function extractBindingNames(node) {
123
123
  }
124
124
  }
125
125
  /**
126
- * Parse bundled JS code and return the set of free (unbound) identifiers
127
- * that match known GJS globals from `GJS_GLOBALS_MAP`.
128
- *
129
- * "Free" means the identifier is referenced but never declared in the
130
- * module (var/let/const/function/class/import/param/catch).
131
- *
132
- * After esbuild bundling + minification, local variables that shadow
133
- * globals are renamed to short names, so any surviving known-global name
134
- * in the output is almost certainly a true global reference. The
135
- * declared-names check is a safety net for edge cases where esbuild
136
- * keeps the original name.
137
- *
138
- * `typeof X` references that appear in presence-check guards
139
- * (`typeof document !== 'undefined'`) and NOWHERE ELSE in the bundle are
140
- * NOT counted as free-global uses. Such guards are pervasive in
141
- * isomorphic npm packages that support both browser and non-browser
142
- * runtimes; on GJS the guarded branch is dead but the bundler cannot DCE
143
- * a `typeof` expression (its value depends on the runtime). If the same
144
- * identifier also appears in a genuine reference position the injection
145
- * still fires — the typeof-guard suppression only applies when the guard
146
- * is the SOLE occurrence.
147
- *
148
- * If `typeof X` was the ONLY reference to a global AND its polyfill
149
- * package is unresolvable, silently skipping avoids an unresolved-import
150
- * hard error at bundle time. The resolvability gate in `auto-globals.ts`
151
- * provides the second layer of protection for cases where `X` does appear
152
- * in a real reference position but the package is still absent.
126
+ * Core scanner shared by `detectFreeGlobals` (web/Node globals map) and
127
+ * `detectGjsAmbientGlobals` (the `--app node` GJS-ambient set). Parametrised so
128
+ * the GJS path stays byte-identical while the node path can use a different
129
+ * known-globals set + the stricter host-member typeof handling.
153
130
  */
154
- export function detectFreeGlobals(code) {
131
+ function scanFreeGlobals(code, opts) {
132
+ const knownGlobals = opts.knownGlobals;
133
+ const methodMarkers = opts.methodMarkers ?? {};
134
+ const wasmMarkers = opts.wasmMarkers ?? {};
155
135
  const ast = acorn.parse(code, {
156
136
  ecmaVersion: 'latest',
157
137
  sourceType: 'module',
@@ -245,7 +225,12 @@ export function detectFreeGlobals(code) {
245
225
  // Pattern A: globalThis.X / global.X / window.X / self.X
246
226
  // The property is a known global identifier itself.
247
227
  if (HOST_OBJECTS.has(objName)) {
248
- if (KNOWN_GLOBALS.has(propName)) {
228
+ // The node GJS-ambient detector ignores host-member forms — they
229
+ // are the isomorphic-guard shape, not genuine GJS source (see
230
+ // `ignoreHostMembers`). Bare-identifier detection still applies.
231
+ if (opts.ignoreHostMembers)
232
+ return;
233
+ if (knownGlobals.has(propName)) {
249
234
  freeGlobals.add(propName);
250
235
  }
251
236
  return;
@@ -255,8 +240,8 @@ export function detectFreeGlobals(code) {
255
240
  // identifier that triggers the right register path even though
256
241
  // the identifier itself never appears in the bundle.
257
242
  const markerKey = `${objName}.${propName}`;
258
- const markerTarget = METHOD_MARKERS[markerKey];
259
- if (markerTarget && KNOWN_GLOBALS.has(markerTarget)) {
243
+ const markerTarget = methodMarkers[markerKey];
244
+ if (markerTarget && knownGlobals.has(markerTarget)) {
260
245
  freeGlobals.add(markerTarget);
261
246
  }
262
247
  },
@@ -273,15 +258,15 @@ export function detectFreeGlobals(code) {
273
258
  const jsName = wbgJsNameFor(node.id.name);
274
259
  if (!jsName)
275
260
  return;
276
- const target = WASM_BINDGEN_MARKERS[jsName];
277
- if (target && KNOWN_GLOBALS.has(target)) {
261
+ const target = wasmMarkers[jsName];
262
+ if (target && knownGlobals.has(target)) {
278
263
  freeGlobals.add(target);
279
264
  }
280
265
  },
281
266
  Identifier(node, ancestors) {
282
267
  const name = node.name;
283
268
  // Quick filter: only check known globals
284
- if (!KNOWN_GLOBALS.has(name))
269
+ if (!knownGlobals.has(name))
285
270
  return;
286
271
  // Skip if locally declared
287
272
  if (declaredNames.has(name))
@@ -375,3 +360,56 @@ export function detectFreeGlobals(code) {
375
360
  });
376
361
  return freeGlobals;
377
362
  }
363
+ /**
364
+ * Parse bundled JS output and return the set of free (unbound) identifiers that
365
+ * match the known web/Node GJS globals from `GJS_GLOBALS_MAP`. Drives the
366
+ * `--app gjs --globals auto` injection. See `scanFreeGlobals` for the rules.
367
+ */
368
+ export function detectFreeGlobals(code) {
369
+ return scanFreeGlobals(code, {
370
+ knownGlobals: KNOWN_GLOBALS,
371
+ methodMarkers: METHOD_MARKERS,
372
+ wasmMarkers: WASM_BINDGEN_MARKERS,
373
+ });
374
+ }
375
+ /**
376
+ * The GJS ambient globals that exist implicitly under gjs but not on Node:
377
+ * `print`/`printerr`/`log`/`logError`, the `ARGV` array, and the legacy
378
+ * `imports` object (`imports.gi.Gtk`, `imports.system`, `imports.gettext`).
379
+ * `@gjsify/node-gi/globals` seeds these on `globalThis` when imported.
380
+ *
381
+ * This is the REVERSE of `GJS_GLOBALS_MAP` (which maps Node/Web globals onto
382
+ * GJS): it's the set the `--app node` target injects the node-gi globals shim
383
+ * for. Kept here next to the detector so the two never drift.
384
+ */
385
+ export const GJS_AMBIENT_GLOBALS = new Set([
386
+ 'print',
387
+ 'printerr',
388
+ 'log',
389
+ 'logError',
390
+ 'ARGV',
391
+ 'imports',
392
+ ]);
393
+ /**
394
+ * Detect references to the GJS ambient globals (`GJS_AMBIENT_GLOBALS`) in a
395
+ * bundled `--app node` chunk — the signal that the bundle needs
396
+ * `@gjsify/node-gi/globals` injected.
397
+ *
398
+ * Runs on the bundled output AFTER tree-shaking (same property the GJS path
399
+ * relies on), so a `print`/`imports` reference behind a statically-dead branch
400
+ * does not trigger injection. Detects only BARE free identifiers — the genuine
401
+ * GJS-source shape (`print(...)`, `imports.gi.Gtk`). The `globalThis.imports` /
402
+ * `globalThis.print` host-member form is the cross-platform isomorphic-GUARD
403
+ * shape (`if (typeof globalThis.imports !== 'undefined') { … }`) and is
404
+ * deliberately ignored: injecting `@gjsify/node-gi/globals` for it would break
405
+ * plain-Node loadability of a package that merely gates GJS usage (the bare
406
+ * external import is unresolvable without node-gi; the shim eagerly loads the
407
+ * native addon). Pure `typeof imports` probes are deferred too. See
408
+ * `ignoreHostMembers`.
409
+ */
410
+ export function detectGjsAmbientGlobals(code) {
411
+ return scanFreeGlobals(code, {
412
+ knownGlobals: GJS_AMBIENT_GLOBALS,
413
+ ignoreHostMembers: true,
414
+ });
415
+ }
@@ -0,0 +1,18 @@
1
+ import type { RolldownOptions, RolldownPluginOption } from 'rolldown';
2
+ export interface VirtualEntriesResult {
3
+ input: RolldownOptions['input'];
4
+ plugin: RolldownPluginOption | null;
5
+ }
6
+ /**
7
+ * If there are side-effect imports to land alongside the user's entry, wrap each
8
+ * entry in a virtual module that imports them first then re-exports the entry.
9
+ * Returns the rewritten `input` plus the resolveId/load plugin that resolves the
10
+ * virtual ids. With no side effects (or no input) it is a no-op pass-through.
11
+ *
12
+ * Single-input case: `'src/index.ts'` → `'\0gjsify-entry:src/index.ts'`.
13
+ * Array-input case: each element gets the same wrapper id.
14
+ * Record-input case: values get wrapped, keys preserved.
15
+ */
16
+ export declare function wrapInputWithSideEffects(input: RolldownOptions['input'], sideEffects: string[], opts?: {
17
+ preserveDefaultExport?: boolean;
18
+ }): VirtualEntriesResult;
@@ -0,0 +1,103 @@
1
+ // Virtual entry-wrapper shared by the `--app gjs` and `--app node` factories.
2
+ //
3
+ // When a build needs to land one or more side-effect imports BEFORE the user's
4
+ // entry executes (the `--globals auto` register-inject stub on GJS; the
5
+ // `@gjsify/node-gi/globals` ambient-globals shim on Node), each entry is wrapped
6
+ // in a `\0gjsify-entry:<path>` virtual module that imports the side effects
7
+ // first, then re-exports the real entry. `\0`-prefixed ids are Rollup's
8
+ // convention for synthetic modules — Rolldown treats them as not-from-disk and
9
+ // skips the default loader.
10
+ /**
11
+ * If there are side-effect imports to land alongside the user's entry, wrap each
12
+ * entry in a virtual module that imports them first then re-exports the entry.
13
+ * Returns the rewritten `input` plus the resolveId/load plugin that resolves the
14
+ * virtual ids. With no side effects (or no input) it is a no-op pass-through.
15
+ *
16
+ * Single-input case: `'src/index.ts'` → `'\0gjsify-entry:src/index.ts'`.
17
+ * Array-input case: each element gets the same wrapper id.
18
+ * Record-input case: values get wrapped, keys preserved.
19
+ */
20
+ export function wrapInputWithSideEffects(input, sideEffects, opts = {}) {
21
+ if (sideEffects.length === 0 || input === undefined) {
22
+ return { input, plugin: null };
23
+ }
24
+ const userEntries = new Map(); // virtualId → realPath
25
+ const PREFIX = '\0gjsify-entry:';
26
+ function wrap(realPath) {
27
+ const id = PREFIX + realPath;
28
+ userEntries.set(id, realPath);
29
+ return id;
30
+ }
31
+ let wrappedInput;
32
+ if (typeof input === 'string') {
33
+ wrappedInput = wrap(input);
34
+ }
35
+ else if (Array.isArray(input)) {
36
+ wrappedInput = input.map(wrap);
37
+ }
38
+ else {
39
+ const out = {};
40
+ for (const [name, path] of Object.entries(input)) {
41
+ out[name] = wrap(path);
42
+ }
43
+ wrappedInput = out;
44
+ }
45
+ const sideEffectImports = sideEffects.map((p) => `import ${JSON.stringify(p)};`).join('\n');
46
+ // Resolved real-path targets from `userEntries` get their moduleSideEffects
47
+ // forced to 'no-treeshake' so the user-entry's top-level body (`run({...})`,
48
+ // side-effect calls) survives tree-shake even when its package.json restricts
49
+ // sideEffects to register files.
50
+ const resolvedTargets = new Set();
51
+ const plugin = {
52
+ name: 'gjsify-virtual-entry',
53
+ async resolveId(source, _importer) {
54
+ if (source.startsWith(PREFIX))
55
+ return source;
56
+ // Force-mark the resolved user-entry target as having top-level
57
+ // side effects.
58
+ if (resolvedTargets.has(source)) {
59
+ return { id: source, moduleSideEffects: 'no-treeshake' };
60
+ }
61
+ return null;
62
+ },
63
+ async load(id) {
64
+ if (!id.startsWith(PREFIX))
65
+ return null;
66
+ const realPath = userEntries.get(id);
67
+ if (!realPath)
68
+ return null;
69
+ // Resolve the user-provided entry path through the full resolver
70
+ // chain so the re-export targets a real on-disk module — otherwise
71
+ // Rolldown treats `src/foo.ts` as a bare specifier and emits it as
72
+ // an external import.
73
+ const resolved = await this.resolve(realPath, undefined, { skipSelf: true });
74
+ const target = resolved?.id ?? realPath;
75
+ resolvedTargets.add(target);
76
+ // The bare `export * from <target>` re-exports named bindings but
77
+ // does NOT execute the source module's top-level body. A companion
78
+ // side-effect-only `import <target>` plus our resolveId-side
79
+ // `moduleSideEffects: 'no-treeshake'` mark forces the body to run —
80
+ // `run({...})` calls in test entries, top-level await, etc.
81
+ //
82
+ // `export *` also never carries the `default` export. For an
83
+ // executable that's irrelevant, but a library bundle imported for
84
+ // its default API (a bundler plugin) needs it preserved. When
85
+ // requested, import the target as a namespace (which also runs the
86
+ // body, so it doubles as the side-effect import) and re-export its
87
+ // `default` — safely `undefined` when the entry has none.
88
+ if (opts.preserveDefaultExport) {
89
+ const ns = '__gjsify_entry__';
90
+ return {
91
+ code: `${sideEffectImports}\nimport * as ${ns} from ${JSON.stringify(target)};\n` +
92
+ `export * from ${JSON.stringify(target)};\nexport default ${ns}.default;\n`,
93
+ moduleSideEffects: 'no-treeshake',
94
+ };
95
+ }
96
+ return {
97
+ code: `${sideEffectImports}\nimport ${JSON.stringify(target)};\nexport * from ${JSON.stringify(target)};\n`,
98
+ moduleSideEffects: 'no-treeshake',
99
+ };
100
+ },
101
+ };
102
+ return { input: wrappedInput, plugin };
103
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gjsify/rolldown-plugin-gjsify",
3
- "version": "0.13.1",
3
+ "version": "0.13.2",
4
4
  "description": "Rolldown / Rollup / Vite plugin orchestrator for GJS, Node, and Browser targets",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",
@@ -55,11 +55,11 @@
55
55
  ],
56
56
  "license": "MIT",
57
57
  "dependencies": {
58
- "@gjsify/console": "^0.13.1",
59
- "@gjsify/resolve-npm": "^0.13.1",
60
- "@gjsify/rolldown-plugin-deepkit": "^0.13.1",
61
- "@gjsify/rolldown-plugin-pnp": "^0.13.1",
62
- "@gjsify/vite-plugin-blueprint": "^0.13.1",
58
+ "@gjsify/console": "^0.13.2",
59
+ "@gjsify/resolve-npm": "^0.13.2",
60
+ "@gjsify/rolldown-plugin-deepkit": "^0.13.2",
61
+ "@gjsify/rolldown-plugin-pnp": "^0.13.2",
62
+ "@gjsify/vite-plugin-blueprint": "^0.13.2",
63
63
  "@rollup/pluginutils": "^5.4.0",
64
64
  "acorn": "^8.16.0",
65
65
  "acorn-walk": "^8.3.5",
@@ -67,7 +67,7 @@
67
67
  "lightningcss": "^1.32.0"
68
68
  },
69
69
  "peerDependencies": {
70
- "@gjsify/lightningcss-native": "^0.13.1",
70
+ "@gjsify/lightningcss-native": "^0.13.2",
71
71
  "rolldown": "^1.1.0"
72
72
  },
73
73
  "peerDependenciesMeta": {