Skip to main content

bynk_emit/emitter/
imports.rs

1//! Imports, re-exports and rebrands of a project-mode module (2.5a, #4090).
2//!
3//! The import statements `emit_project` writes for a unit (`emit_project_imports`
4//! and `emit_cross_context_namespace_imports`), the rebrands and re-exports a
5//! context emits for the types it consumes from another (`emit_context_rebrands`,
6//! `emit_consumed_type_reexports`), the `ExternalReferences` resolver that finds
7//! which names a body takes from outside its own file, and the specifier helpers
8//! (`ts_specifier`, `cross_commons_import_specifier_for_path`) the driver and
9//! `compose/` also read. `emitter` re-exports the ones that are public.
10
11use std::collections::{HashMap, HashSet};
12use std::path::{Path, PathBuf};
13
14use super::ctx::UnitFacts;
15use super::ts_types::ts_base;
16use super::{cross_context_cap_namespaces, emit_forwarded_methods, qualified_to_ns, ts_ident};
17use crate::emit_model::{EmitProjectCtx, ExtraImport, ImportExt};
18use bynk_check::checker::{Ty, TypedCommons};
19use bynk_check::project_model::BuildTarget;
20use bynk_project::UnitKind;
21use bynk_syntax::ast::{BaseType, CommonsItem, TypeBody, TypeDecl};
22
23/// For each type imported via `uses` that's referenced in this file, emit:
24/// 1. (Done in imports) an aliased import: `import { Money as __CommonsMoney } from ...`
25/// 2. A rebranded type alias: `export type Money = __CommonsMoney & { readonly __ctxBrand?: "..." }`
26///
27/// The brand makes two contexts that both `uses` the same commons see distinct
28/// nominal `Money` types in their TypeScript output (v0.4 §3.4 / §6.2). It is
29/// optional (#1704), so an unbranded commons value (a record literal, a nested
30/// field of another rebranded record, a commons fn's result) is accepted where
31/// the context's type is expected, while a value carrying another context's
32/// brand is still rejected.
33/// #1478: real-node-internally already — returns its real declarations
34/// (a rebrand type alias, and — for a refined/opaque base — a forwarding
35/// const, per name) instead of writing into `out: &mut String`.
36/// #2036: on `workers`, re-export as types the names this `handlers.ts`
37/// imports from a consumed context. `compose.ts` names every type in a
38/// wrapper's signature as `handlers.<Name>` (it imports no type names of its
39/// own), so a consumed `Batch` in a handler's parameters must be a member of
40/// `handlers` too (a consumed *adapter's* type — `R2Upload` — likewise, #2647:
41/// it is imported from the adapter's module by the same statement), the way a
42/// `uses`d commons type is through its rebrand alias. Type-only
43/// (`export { type Batch }`): `compose.ts` uses the name in type position
44/// only, a consumed refined alias has no value to re-export (TS1205 under
45/// `isolatedModules`), and a value re-export would deepen the caller's
46/// dependency on the callee's module. Only names the module imports
47/// are re-exported, so each is bound here.
48pub(super) fn emit_consumed_type_reexports(
49    refs: &ExternalReferences,
50    commons: &TypedCommons,
51    ctx: &EmitProjectCtx,
52) -> Vec<bynk_ts::TsStmt> {
53    if ctx.target != BuildTarget::Workers {
54        return Vec::new();
55    }
56    // #2647: a consumed *adapter's* types are re-exported only when some
57    // service handler's parameter names them, in the handler kinds below. A consumed
58    // context's are re-exported whenever imported, as before.
59    let handler_param_types: HashSet<String> = commons
60        .commons
61        .items
62        .iter()
63        .filter_map(CommonsItem::as_service)
64        .flat_map(|s| s.handlers.iter())
65        // The kinds whose `compose.ts` wrapper types its parameters with
66        // `qualified_ts_type_ref` (call, cron, queue `message`, http); an
67        // `event` handler's other parameters never reach `compose.ts`.
68        .filter(|h| {
69            matches!(
70                h.kind,
71                bynk_syntax::ast::HandlerKind::Call
72                    | bynk_syntax::ast::HandlerKind::Http { .. }
73                    | bynk_syntax::ast::HandlerKind::Cron { .. }
74                    | bynk_syntax::ast::HandlerKind::Message
75            )
76        })
77        .flat_map(|h| h.params.iter())
78        .flat_map(|p| super::workers::named_types_in(&p.type_ref))
79        .collect();
80    let mut names: Vec<String> = refs
81        .by_commons
82        .iter()
83        .flat_map(|(unit, set)| {
84            let adapter = ctx.consumed_adapters.contains(unit.as_str());
85            let handler_param_types = &handler_param_types;
86            set.iter()
87                .filter(move |n| !adapter || handler_param_types.contains(n.as_str()))
88        })
89        .filter(|n| ctx.imported_from_kind.get(n.as_str()) == Some(&UnitKind::Context))
90        .map(|n| format!("type {}", ts_ident(n)))
91        .collect();
92    if names.is_empty() {
93        return Vec::new();
94    }
95    names.sort();
96    names.dedup();
97    vec![bynk_ts::TsStmt::decl(
98        bynk_ts::TsDecl::ExportNames { names },
99        None,
100    )]
101}
102
103pub(super) fn emit_context_rebrands(
104    refs: &ExternalReferences,
105    commons: &TypedCommons,
106    ctx: &EmitProjectCtx,
107) -> Vec<bynk_ts::TsStmt> {
108    let Some(owning) = &ctx.owning_context else {
109        return Vec::new();
110    };
111    // Collect names imported via `uses` (kind == Commons in imported_from_kind).
112    // R4.10/R8.2: reads `bynk_check::resolver::compute_is_uses_commons_type`, the same
113    // predicate `prepare_unit_check_ctx` (`check_pipeline.rs`) computes its own
114    // `uses_commons_type_names` from — one definition, not two independently
115    // maintained copies linked only by a doc-comment promise (see that
116    // function's own doc comment for the real defect this closes, ADR 0226).
117    let mut names: Vec<String> = Vec::new();
118    for set in refs.by_commons.values() {
119        for n in set {
120            // v0.20b: only *types* get the context rebrand — a
121            // `uses`-imported function is a value and imports plainly.
122            if bynk_check::resolver::compute_is_uses_commons_type(
123                &ctx.imported_from_kind,
124                &commons.types,
125                n,
126            ) {
127                names.push(n.clone());
128            }
129        }
130    }
131    names.sort();
132    names.dedup();
133    if names.is_empty() {
134        return Vec::new();
135    }
136    let mut stmts = Vec::new();
137    for name in &names {
138        // v0.174 (#592): a generic commons type keeps its parameters across the
139        // rebrand — `Paginated[T]` aliases as `Paginated<T> =
140        // __CommonsPaginated<T> & { … }`, not a bare `Paginated`, which would
141        // both drop the parameter and make every `Paginated<User>` reference in
142        // the context a "type is not generic" error.
143        let params: Vec<&str> = commons
144            .types
145            .get(name)
146            .map(|d| d.type_params.iter().map(|p| p.name.name.as_str()).collect())
147            .unwrap_or_default();
148        let generic_args: Vec<bynk_ts::TsType> =
149            params.iter().map(|p| bynk_ts::TsType::named(*p)).collect();
150        // Arc C, slice 30 (#1392): the SAME `TsDecl::TypeAlias` over
151        // `TsType::Intersection` shape #1339's own `emit_refined_type`
152        // already established for its sibling `__brand` alias (a real,
153        // proven precedent, not this slice's own new gap).
154        let type_alias = bynk_ts::TsStmt::decl(
155            bynk_ts::TsDecl::Export(Box::new(bynk_ts::TsDecl::TypeAlias {
156                name: name.clone(),
157                type_params: params.iter().map(|p| p.to_string()).collect(),
158                ty: bynk_ts::TsType::intersection(vec![
159                    bynk_ts::TsType::named_with_args(commons_alias(name), generic_args),
160                    // #1704: the brand is *optional*. A plain commons value (a
161                    // record literal, a nested field, a commons fn's result)
162                    // has no brand, and it is assignable here; another
163                    // context's brand (`"a"` against `"b"`) still is not, so
164                    // the two contexts' types stay nominally distinct.
165                    bynk_ts::TsType::Object(vec![bynk_ts::TsTypeMember::Prop {
166                        name: "__ctxBrand".to_string(),
167                        ty: bynk_ts::TsType::named(format!("\"{owning}\"")),
168                        optional: true,
169                        readonly: true,
170                    }]),
171                ]),
172            })),
173            None,
174        );
175        stmts.push(type_alias);
176        // v0.9.2: a commons refined/opaque type carries a value-side
177        // constructor (`.of`, and `.unsafe` for opaque). Re-export it under the
178        // rebranded name so a context calling `ShortCode.of(...)` resolves to a
179        // value — delegating to the imported commons constructor but reporting
180        // the context-branded type. (Without this, `ShortCode` is type-only in
181        // the context and `.of` fails to resolve.)
182        if let Some(base) = commons
183            .types
184            .get(name)
185            .and_then(|d| refined_or_opaque_base(d))
186        {
187            let ts_base_name = ts_base(base);
188            let is_opaque = matches!(
189                commons.types.get(name).map(|d| &d.body),
190                Some(TypeBody::Opaque { .. })
191            );
192            // #1704: `return __CommonsX.of(value);` with no cast — the
193            // commons result is unbranded, which fits the context's
194            // optionally-branded `Result<X, ValidationError>` directly.
195            let of_entry = bynk_ts::TsObjectEntry::Method {
196                name: "of".to_string(),
197                is_async: false,
198                generics: Vec::new(),
199                params: vec![bynk_ts::TsParam::new(
200                    "value".to_string(),
201                    Some(bynk_ts::TsType::named(ts_base_name)),
202                )],
203                return_type: Some(bynk_ts::TsType::named_with_args(
204                    "Result",
205                    vec![
206                        bynk_ts::TsType::named(name.clone()),
207                        bynk_ts::TsType::named("ValidationError"),
208                    ],
209                )),
210                doc: None,
211                inline: true,
212                body: vec![bynk_ts::TsStmt::return_stmt(
213                    Some(bynk_ts::TsExpr::Call {
214                        callee: Box::new(bynk_ts::TsExpr::Member {
215                            object: Box::new(bynk_ts::TsExpr::Ident(commons_alias(name))),
216                            property: "of".to_string(),
217                        }),
218                        args: vec![bynk_ts::TsExpr::Ident("value".to_string())],
219                    }),
220                    None,
221                )],
222                span: None,
223            };
224            let mut entries = vec![of_entry];
225            // ADR 0182: only opaque types have a public `.unsafe` to forward.
226            // A refined/alias type has none — a consuming context brands an
227            // admitted literal with an inline `as` cast, not a forwarder call.
228            if is_opaque {
229                entries.push(bynk_ts::TsObjectEntry::Method {
230                    name: "unsafe".to_string(),
231                    is_async: false,
232                    generics: Vec::new(),
233                    params: vec![bynk_ts::TsParam::new(
234                        "value".to_string(),
235                        Some(bynk_ts::TsType::named(ts_base_name)),
236                    )],
237                    return_type: Some(bynk_ts::TsType::named(name.clone())),
238                    doc: None,
239                    inline: true,
240                    body: vec![bynk_ts::TsStmt::return_stmt(
241                        Some(bynk_ts::TsExpr::Call {
242                            callee: Box::new(bynk_ts::TsExpr::Member {
243                                object: Box::new(bynk_ts::TsExpr::Ident(commons_alias(name))),
244                                property: "unsafe".to_string(),
245                            }),
246                            args: vec![bynk_ts::TsExpr::Ident("value".to_string())],
247                        }),
248                        None,
249                    )],
250                    span: None,
251                });
252            }
253            // v0.132.1 (#481): forward the commons' user-defined attached methods
254            // (`Cents.fromInt`, …) so the rebranded const carries more than the
255            // built-in `of`/`unsafe`. Without this a consumer's `Cents.fromInt(n)`
256            // — which `bynk check` accepts — fails `tsc`. The methods aren't in
257            // this context's own `commons` (only imported *types* are merged);
258            // they arrive via `ctx.imported_methods`, keyed by type name.
259            if let Some(methods) = ctx.imported_methods.get(name) {
260                entries.extend(emit_forwarded_methods(
261                    name,
262                    methods,
263                    UnitFacts::of(ctx).render(commons),
264                ));
265            }
266            let const_decl = bynk_ts::TsStmt::decl(
267                bynk_ts::TsDecl::Export(Box::new(bynk_ts::TsDecl::ConstDecl {
268                    name: name.clone(),
269                    ty: None,
270                    init: bynk_ts::TsExpr::multiline_object_entries(entries),
271                })),
272                None,
273            );
274            stmts.push(const_decl);
275        } else if ctx
276            .imported_methods
277            .get(name)
278            .is_some_and(|m| !m.is_empty())
279        {
280            // #2751: a record/sum commons type has no `.of`, but its
281            // attached methods are still called as `Type.method(recv)`, which
282            // needs a value `Type` in the context (the rebrand above is only
283            // a type). The value is the commons' own, re-exported unbranded:
284            // its methods already speak types the context's optionally-branded
285            // ones fit, and — unlike a re-declared forwarder — it carries a
286            // generic type's parameters, a bounded method's hidden comparator
287            // and codec witnesses, and a sum's variants unchanged.
288            stmts.push(bynk_ts::TsStmt::decl(
289                bynk_ts::TsDecl::Export(Box::new(bynk_ts::TsDecl::ConstDecl {
290                    name: name.clone(),
291                    ty: None,
292                    init: bynk_ts::TsExpr::Ident(commons_alias(name)),
293                })),
294                None,
295            ));
296        }
297    }
298    // #1486: no explicit trailing blank stmt here — the printer's automatic
299    // top-level spacing policy supplies the single blank before whatever
300    // follows.
301    //
302    // Every rebrand entry (a lone `type_alias`, or a `type_alias`+`const_decl`
303    // pair) sits directly under its predecessor with no blank between them —
304    // confirmed against `129_full_orders_http_api`'s own real fixture output,
305    // several rebrands stacked with zero blank lines anywhere among them.
306    // Only the very first statement in this whole function's own returned
307    // `Vec` keeps the printer's ordinary automatic blank relative to
308    // whatever precedes `emit_context_rebrands`'s own call site.
309    for stmt in stmts.iter_mut().skip(1) {
310        stmt.no_blank_before = true;
311    }
312    stmts
313}
314
315/// If a type declaration is a refined or opaque base type, return its base
316/// (both lower to a branded base with a `.of` / `.unsafe` constructor object).
317///
318/// P6.56 (design/tracks/the-ir.md §6b): investigated routing this through
319/// `TypeShape::Refined` and declined — that variant's own `base` field is
320/// `bynk_syntax::ast::BaseType` (P6.41 ruled it stays, phase 7 — the bounds
321/// keep source lexemes for byte-stable emission), so this function's own
322/// `Option<BaseType>` return type is identical either way. Converting would
323/// add a `CheckedProgram`/`TypedCommons` dependency this function doesn't
324/// have today for zero reduction in AST-type surface.
325fn refined_or_opaque_base(decl: &TypeDecl) -> Option<BaseType> {
326    match &decl.body {
327        TypeBody::Refined { base, .. } | TypeBody::Opaque { base, .. } => Some(*base),
328        TypeBody::Record(_) | TypeBody::Sum(_) => None,
329    }
330}
331
332/// Names that this file needs to import from elsewhere (sibling files of
333/// the same commons, or other commons via `uses`).
334#[derive(Default)]
335pub(super) struct ExternalReferences {
336    /// `commons name` → set of names to import.
337    by_commons: HashMap<String, HashSet<String>>,
338    /// `sibling source path` → set of names to import (same-commons).
339    by_sibling: HashMap<PathBuf, HashSet<String>>,
340    /// #1820: names imported from a sibling file as types only: a capability
341    /// is an `interface`, which has no value to import once the module is
342    /// stripped to JavaScript.
343    types_by_sibling: HashMap<PathBuf, HashSet<String>>,
344}
345
346impl ExternalReferences {
347    pub(super) fn is_empty(&self) -> bool {
348        self.by_commons.is_empty() && self.by_sibling.is_empty() && self.types_by_sibling.is_empty()
349    }
350}
351
352/// The names this file declares, so a reference to one needs no import. A
353/// `messages` block declares no importable identifier of its own (its
354/// `render` is synthesised separately), so `name()` is `None` there and it
355/// contributes nothing.
356fn local_names(commons: &TypedCommons) -> HashSet<String> {
357    commons
358        .commons
359        .items
360        .iter()
361        .filter_map(|i| i.name().map(|n| n.name.clone()))
362        .collect()
363}
364
365/// Whether `name` is declared elsewhere than this file and so imported: a name of a used
366/// commons, of a sibling file (a type, a function or a capability) or of a consumed context.
367fn resolves_externally(name: &str, local_to_file: &HashSet<String>, ctx: &EmitProjectCtx) -> bool {
368    let mut found = ExternalReferences::default();
369    record_external_name(name, local_to_file, ctx, &mut found);
370    !found.is_empty()
371}
372
373/// [`record_name_ref`], a sibling file's capability (an `interface`, imported as a type only,
374/// #1820) and a sibling file's agent factory (`__make<Agent>`, which the file exports, #1820).
375fn record_external_name(
376    name: &str,
377    local_to_file: &HashSet<String>,
378    ctx: &EmitProjectCtx,
379    out: &mut ExternalReferences,
380) {
381    record_name_ref(name, local_to_file, ctx, out);
382    if let Some(agent) = name.strip_prefix("__make")
383        && !local_to_file.contains(agent)
384        && let Some(path) = ctx.file_decl_index.agents.get(agent)
385        && path != &ctx.source_path
386    {
387        out.by_sibling
388            .entry(path.clone())
389            .or_default()
390            .insert(name.to_string());
391    }
392    if !local_to_file.contains(name)
393        && let Some(path) = ctx.file_decl_index.capabilities.get(name)
394        && path != &ctx.source_path
395    {
396        out.types_by_sibling
397            .entry(path.clone())
398            .or_default()
399            .insert(name.to_string());
400    }
401}
402
403/// The names `body` uses and does not declare, that are not bound by `bound` (the module's other
404/// imports) and are not the runtime's: the candidates for the type imports and the namespace
405/// imports (1A.36b-2). A name a used commons' type is imported under (`__CommonsLine`,
406/// `unbranded_commons_qual`) is read as the name it aliases.
407///
408/// A name that resolves to an import is never hidden by the global tables (`Request`/`Response`
409/// of `bynk`).
410pub(super) fn used_external_names(
411    commons: &TypedCommons,
412    ctx: &EmitProjectCtx,
413    body: &[bynk_ts::TsStmt],
414    bound: &std::collections::BTreeSet<String>,
415) -> std::collections::BTreeSet<String> {
416    let local_to_file = local_names(commons);
417    // A TypeScript type keyword (`any`) is never an import, even where a used commons has a
418    // function of that name.
419    let resolves = |n: &str| {
420        !TS_TYPE_KEYWORDS.contains(&n)
421            && resolves_externally(external_alias_target(n), &local_to_file, ctx)
422    };
423    bynk_ts::unbound_names_in(body, resolves)
424        .into_iter()
425        .filter(|n| !bound.contains(n))
426        .collect()
427}
428
429/// The lower-case names TypeScript reads as types, which no import brings in.
430const TS_TYPE_KEYWORDS: &[&str] = &[
431    "any",
432    "unknown",
433    "never",
434    "void",
435    "string",
436    "number",
437    "boolean",
438    "object",
439    "symbol",
440    "bigint",
441    "null",
442    "undefined",
443];
444
445/// The prefix of a used commons type's import alias.
446const COMMONS_ALIAS_PREFIX: &str = "__Commons";
447
448/// The import alias of a used commons' `X` (`__CommonsX`). The one spelling: the import, the
449/// type alias and every value reference name it through here, so they cannot drift apart
450/// (1A.39b, Decision C).
451pub(crate) fn commons_alias(name: &str) -> String {
452    format!("{COMMONS_ALIAS_PREFIX}{name}")
453}
454
455/// `__CommonsX` is the import alias of a used commons' `X`: the inverse of [`commons_alias`].
456fn external_alias_target(name: &str) -> &str {
457    name.strip_prefix(COMMONS_ALIAS_PREFIX).unwrap_or(name)
458}
459
460/// The imports the names `used` ask for, each resolved to its home by [`record_name_ref`].
461pub(super) fn external_references_of(
462    used: &std::collections::BTreeSet<String>,
463    commons: &TypedCommons,
464    ctx: &EmitProjectCtx,
465) -> ExternalReferences {
466    let local_to_file = local_names(commons);
467    let mut refs = ExternalReferences::default();
468    for name in used {
469        record_external_name(external_alias_target(name), &local_to_file, ctx, &mut refs);
470    }
471    refs
472}
473
474fn record_name_ref(
475    name: &str,
476    local_to_file: &HashSet<String>,
477    ctx: &EmitProjectCtx,
478    out: &mut ExternalReferences,
479) {
480    if local_to_file.contains(name) {
481        return;
482    }
483    // Imported from another commons?
484    if let Some(commons_name) = ctx.imported_from.get(name) {
485        out.by_commons
486            .entry(commons_name.clone())
487            .or_default()
488            .insert(name.to_string());
489        return;
490    }
491    // Sibling file in the same commons?
492    if let Some(path) = ctx.file_decl_index.types.get(name)
493        && path != &ctx.source_path
494    {
495        out.by_sibling
496            .entry(path.clone())
497            .or_default()
498            .insert(name.to_string());
499        return;
500    }
501    if let Some(path) = ctx.file_decl_index.fns.get(name)
502        && path != &ctx.source_path
503    {
504        out.by_sibling
505            .entry(path.clone())
506            .or_default()
507            .insert(name.to_string());
508    }
509}
510
511/// Emit `import * as <ns> from "..."` for each consumed context that
512/// exposes services (so the consuming file can reference its `__makeSurface`
513/// return type and brand the cross-context call arguments).
514/// #1478: real-node-internally already — returns one real `TsDecl::
515/// ImportNamespace` per consumed context instead of writing into
516/// `out: &mut String`.
517pub(super) fn emit_cross_context_namespace_imports(
518    commons: &TypedCommons,
519    ctx: &EmitProjectCtx,
520    used: &std::collections::BTreeSet<String>,
521) -> Vec<bynk_ts::TsStmt> {
522    let info = &ctx.cross_context;
523    // 1A.36b-2: a consumed context's namespace is imported iff the module's tree uses it
524    // (`ns.__makeSurface`, `ns.Code`, `ns.Cap`).
525    let mut candidates: std::collections::BTreeSet<String> =
526        info.consumed_contexts.iter().cloned().collect();
527    candidates.extend(info.consumed_services.keys().cloned());
528    candidates.extend(cross_context_cap_namespaces(commons, ctx));
529    let needed: std::collections::BTreeSet<String> = candidates
530        .into_iter()
531        .filter(|q| used.contains(&qualified_to_ns(q)))
532        .collect();
533    if needed.is_empty() {
534        return Vec::new();
535    }
536    let mut stmts = Vec::new();
537    let consumed_with_services: Vec<&String> = needed.iter().collect();
538    for q in &consumed_with_services {
539        // Pick the first known file path for the consumed context as the
540        // import target. (The composition root lives in the consumed
541        // context's directory; any of its files would work as an import
542        // target since they're all in the same module namespace, but we
543        // currently emit one file per .bynk source so a single import per
544        // consumed name suffices for the surface contract.)
545        let target_paths = ctx.imported_decl_paths.get(q.as_str());
546        let target = target_paths
547            // #3807: the smallest path, so the output does not depend on hash order. Any
548            // single file is still wrong for a context whose declarations span several.
549            .and_then(|m| m.values().min().cloned())
550            .unwrap_or_else(|| {
551                // No imported declaration pins the path (e.g. a capability-only
552                // consumed context, v0.15). Fall back to the unit's own module:
553                // its per-Worker handlers in workers mode, or its <segment>.bynk
554                // source in bundle mode. v0.17: a consumed *adapter* is not a
555                // Worker — its capability types live in its root module
556                // (`<adapter>.ts`) in both targets.
557                if ctx.consumed_adapters.contains(q.as_str()) {
558                    let mut p = EmitProjectCtx::commons_path(q);
559                    p.set_extension("bynk");
560                    p
561                } else {
562                    match ctx.target {
563                        BuildTarget::Workers => ctx.worker_layout.handlers_source_path(q),
564                        BuildTarget::Bundle => {
565                            let mut p = EmitProjectCtx::commons_path(q);
566                            p.set_extension("bynk");
567                            p
568                        }
569                    }
570                }
571            });
572        let import =
573            cross_commons_import_specifier_for_path(&ctx.source_path, &target, ctx.import_ext);
574        let ns = qualified_to_ns(q);
575        // #661: under `workers`, a consumed *context*'s module is imported for
576        // its **types only** — the caller now generates its own codecs
577        // (`emit_boundary_helpers`) and reaches the callee's types through this
578        // alias in type position (`deps: { Clock: platform_time.Clock }`,
579        // `Result<commerce_payment.AuthId, …>`). An `import type` is erased
580        // outright, so the callee's *module* — and its provider implementation —
581        // never enters the caller's Worker bundle. This does **not** apply to a
582        // consumed *adapter* (its binding namespace, e.g. `tokens`, is a real
583        // value import used by `compose.ts`) nor on `bundle` (contexts compile
584        // together, and the value uses in `compose.ts` are legitimate).
585        let type_only = matches!(ctx.target, BuildTarget::Workers)
586            && !ctx.consumed_adapters.contains(q.as_str());
587        // Arc C, slice 30 (#1392): a real `TsDecl::ImportNamespace` —
588        // `type_only` (#1392's own new field) covers the `import type * as`
589        // form.
590        stmts.push(bynk_ts::TsStmt::decl(
591            bynk_ts::TsDecl::ImportNamespace {
592                type_only,
593                alias: ns,
594                from: import,
595            },
596            None,
597        ));
598    }
599    // #1486: no explicit trailing blank stmt here — the printer's automatic
600    // top-level spacing policy supplies the single blank before whatever
601    // follows (never import-kind at this function's own call sites, so
602    // never exempted from it). The boundary this function's own *first*
603    // statement forms with `emit_project_imports`'s own last statement
604    // (both import-kind, genuinely wanting a blank despite the "no blank
605    // between adjacent imports" exemption) is handled at `emit_project`'s
606    // own call site instead — the only place that knows both neighbours.
607    stmts
608}
609
610/// #1478: real-node-internally already — returns one real `TsDecl::Import`
611/// per sibling/cross-unit import group instead of writing into
612/// `out: &mut String`.
613pub(super) fn emit_project_imports(
614    commons: &TypedCommons,
615    ctx: &EmitProjectCtx,
616    refs: &ExternalReferences,
617) -> Vec<bynk_ts::TsStmt> {
618    let mut stmts = Vec::new();
619    // Events track, slice 0 (spine #936): the bare event-type names this
620    // context's own `from Events(E)` service headers name — see the
621    // Workers type-only-import narrowing below.
622    // P6.24a/P6.19: reads the protocol's own resolved `ProtocolIr::Events`
623    // instead of matching `ServiceProtocol::Events { event_type:
624    // TypeRef::Named(id), .. }` directly — a resolve miss (`lower_protocol_
625    // ir_from_commons` degrades to `Ty::Unit` on one, never panics) is
626    // indistinguishable from a legitimately non-`Named` header, so falls
627    // through to `None` exactly like the raw match's own `_ => None` arm
628    // did, not a new failure mode.
629    let subscribed_event_type_names: HashSet<String> = commons
630        .commons
631        .items
632        .iter()
633        .filter_map(CommonsItem::as_service)
634        .filter_map(|s| {
635            let bynk_model::ProtocolIr::Events { event, .. } =
636                bynk_model::lower_protocol_ir_from_commons(&s.protocol, commons)
637            else {
638                return None;
639            };
640            let Ty::Named { name, .. } = &*commons.tys().get(event) else {
641                return None;
642            };
643            Some(name.clone())
644        })
645        .collect();
646    // Sibling imports: relative path within the same commons/context directory.
647    let mut sibling_paths: Vec<(&PathBuf, &HashSet<String>)> = refs.by_sibling.iter().collect();
648    sibling_paths.sort_by(|a, b| a.0.cmp(b.0));
649    for (path, names) in sibling_paths {
650        let import = sibling_import_specifier(&ctx.source_path, path, ctx.import_ext);
651        let mut sorted: Vec<&String> = names.iter().collect();
652        sorted.sort();
653        // Arc C, slice 30 (#1392): a real `TsDecl::Import`.
654        stmts.push(bynk_ts::TsStmt::decl(
655            bynk_ts::TsDecl::Import {
656                type_only: false,
657                names: sorted.iter().map(|s| ts_ident(s)).collect(),
658                from: import,
659            },
660            None,
661        ));
662    }
663    let mut type_paths: Vec<(&PathBuf, &HashSet<String>)> = refs.types_by_sibling.iter().collect();
664    type_paths.sort_by(|a, b| a.0.cmp(b.0));
665    for (path, names) in type_paths {
666        let mut sorted: Vec<&String> = names.iter().collect();
667        sorted.sort();
668        stmts.push(bynk_ts::TsStmt::decl(
669            bynk_ts::TsDecl::Import {
670                type_only: true,
671                names: sorted.iter().map(|s| ts_ident(s)).collect(),
672                from: sibling_import_specifier(&ctx.source_path, path, ctx.import_ext),
673            },
674            None,
675        ));
676    }
677    // Cross-unit imports: group by *target file path*.
678    let mut unit_names: Vec<(&String, &HashSet<String>)> = refs.by_commons.iter().collect();
679    unit_names.sort_by(|a, b| a.0.cmp(b.0));
680    for (unit_name, names) in unit_names {
681        let target_paths = ctx.imported_decl_paths.get(unit_name.as_str());
682        let mut by_target: std::collections::BTreeMap<PathBuf, Vec<&String>> =
683            std::collections::BTreeMap::new();
684        for n in names {
685            let path = target_paths
686                .and_then(|p| p.get(n))
687                .cloned()
688                .unwrap_or_else(|| EmitProjectCtx::commons_path(unit_name));
689            by_target.entry(path).or_default().push(n);
690        }
691        for (target, mut name_list) in by_target {
692            name_list.sort();
693            let import =
694                cross_commons_import_specifier_for_path(&ctx.source_path, &target, ctx.import_ext);
695            // For context units, aliase commons-source imports so we can emit
696            // rebrand aliases of the same short name. Imports from consumed
697            // contexts keep their original name. v0.20b: the rebrand applies
698            // to *types* only — a `uses`-imported function (bynk.list's
699            // `traverse`) is a value, imports plainly, and is never branded.
700            let mut parts: Vec<String> = Vec::new();
701            for n in &name_list {
702                let is_subscribed_event_type = ctx.target == BuildTarget::Workers
703                    && subscribed_event_type_names.contains(n.as_str());
704                // #2045: under Workers, a consumed *context*'s type is named in
705                // type position only — its codecs are the caller's own
706                // (`emit_consumed_context_helpers`) — so it imports type-only and
707                // the callee's module never enters the caller's Worker bundle
708                // (#661). A consumed *adapter* is linked into each Worker, and
709                // its values (`Method.Get`) are real imports.
710                let is_consumed_context_type = ctx.target == BuildTarget::Workers
711                    && ctx.unit_kind == UnitKind::Context
712                    && !ctx.consumed_adapters.contains(unit_name.as_str())
713                    && ctx.imported_from_kind.get(n.as_str()) == Some(&UnitKind::Context)
714                    && !ctx.consumed_types_with_methods.contains(n.as_str());
715                // R4.10/R8.2: the same shared `is_uses_commons_type` predicate
716                // `emit_context_rebrands` below reads — this import-aliasing
717                // site is that function's own step 1 ("Done in imports", its
718                // own doc comment), and the two must agree exactly: an alias
719                // narrower than the rebrand leaves an undefined name in the
720                // generated import; a rebrand narrower than the alias leaves
721                // an alias imported and never used. `ctx.unit_kind ==
722                // UnitKind::Context` is the same guard as
723                // `emit_context_rebrands`'s own `ctx.owning_context.is_some()`
724                // early return (`owning_context` is `Some` exactly when
725                // `unit_kind == Context`, `project.rs`'s own construction) —
726                // kept explicit here since this loop runs for every unit
727                // kind, not just contexts.
728                if ctx.unit_kind == UnitKind::Context
729                    && bynk_check::resolver::compute_is_uses_commons_type(
730                        &ctx.imported_from_kind,
731                        &commons.types,
732                        n,
733                    )
734                {
735                    parts.push(format!("{n} as {}", commons_alias(n)));
736                } else if is_subscribed_event_type || is_consumed_context_type {
737                    // Events track, slice 0 (spine #936): under Workers, a
738                    // context deploys as its own separate Worker script —
739                    // there is no shared module graph to import a peer
740                    // context's *value* across (the #661 hazard this
741                    // mirrors: a caller generates its own codec rather than
742                    // importing the callee's runtime code). `from
743                    // Events(E)`'s `E` is the one plain named type crossing
744                    // a context boundary directly by name (every other
745                    // cross-context reference goes through a generated
746                    // Service-Binding codec instead) — used only in type
747                    // position (`e: E`), so this specific name is type-only.
748                    // Narrowly scoped to event types specifically, not every
749                    // cross-context import: a `type`/`enum` crossing via
750                    // `uses`/`consumes` (e.g. `bynk`'s `Method`) is often
751                    // used as a *value* too (`Method.Get`), which a blanket
752                    // `import type` would wrongly break.
753                    parts.push(format!("type {}", import_spec_of(ctx, n)));
754                } else {
755                    parts.push(import_spec_of(ctx, n));
756                }
757            }
758            // Arc C, slice 30 (#1392): a real `TsDecl::Import` — `parts`'
759            // own per-name `as __CommonsX`/`type X` prefixes already match
760            // `names`'s own documented "raw text slot" convention, no new
761            // gap.
762            stmts.push(bynk_ts::TsStmt::decl(
763                bynk_ts::TsDecl::Import {
764                    type_only: false,
765                    names: parts,
766                    from: import,
767                },
768                None,
769            ));
770        }
771    }
772    stmts.extend(extra_import_stmts(ctx));
773    // #1486: every statement in this function's own return, whatever
774    // section it came from (sibling imports, cross-unit imports, the
775    // rebrand-aliasing pair, `extra_imports`), sits directly under its
776    // predecessor with no blank between them — this function never inserted
777    // one under the pre-#1486 flat-print regime (confirmed: no explicit blank
778    // `TsStmt` anywhere in its own body), so every internal adjacency is forced
779    // regardless of `TsStmtKind`. The very first statement is left alone — its
780    // own blank-or-not relative to whatever precedes this function's call
781    // site is `emit_project`'s own call-site decision (the header/`emit_
782    // project_imports` boundary, and the project/cross-context import
783    // boundary, both forced explicitly there instead).
784    for stmt in stmts.iter_mut().skip(1) {
785        stmt.no_blank_before = true;
786    }
787    stmts
788}
789
790/// #527: imports the DO-side agent-deps expressions need (binding modules,
791/// other Workers' handlers, the locale `render`). The project driver decides
792/// which; each is an import node here.
793pub(super) fn extra_import_stmts(ctx: &EmitProjectCtx) -> Vec<bynk_ts::TsStmt> {
794    let mut stmts = Vec::new();
795    for import in &ctx.extra_imports {
796        let decl = match import {
797            ExtraImport::Namespace { alias, from } => bynk_ts::TsDecl::ImportNamespace {
798                type_only: false,
799                alias: alias.clone(),
800                from: from.clone(),
801            },
802            ExtraImport::Named {
803                names,
804                from,
805                type_only,
806            } => bynk_ts::TsDecl::Import {
807                type_only: *type_only,
808                names: names.clone(),
809                from: from.clone(),
810            },
811        };
812        stmts.push(bynk_ts::TsStmt::decl(decl, None));
813    }
814    stmts
815}
816
817/// #2887: `n` as an import specifier. A type this unit renames with `consumes
818/// U { T as Alias }` is imported under the name `U` declares and bound to the
819/// alias (`Digest as CryptoDigest`), so every use in the module reaches the
820/// module's real type, not a new one.
821fn import_spec_of(ctx: &EmitProjectCtx, n: &str) -> String {
822    match ctx.consumed_type_aliases.get(n) {
823        Some(original) => format!("{} as {}", ts_ident(original), ts_ident(n)),
824        None => ts_ident(n),
825    }
826}
827
828/// Compute a relative import specifier from `from_source` (a `.bynk` path)
829/// to `to_source` (another `.bynk` path), with `.bynk` rewritten to `.js`
830/// for compatibility with NodeNext/strict TS resolution.
831fn sibling_import_specifier(from_source: &Path, to_source: &Path, ext: ImportExt) -> String {
832    let from_dir = from_source.parent().unwrap_or(Path::new(""));
833    let target = to_source.with_extension(ext.as_str());
834    let rel = relative_to(from_dir, &target);
835    format!("./{}", ts_specifier(&rel))
836}
837
838/// Render a path as a TypeScript module specifier: **always forward
839/// slashes**. `Path::display()` uses the platform separator, and on Windows
840/// that emitted `import ... from "./commerce\orders.js"` — broken ESM
841/// output, caught by the first CI matrix run on windows-latest.
842pub fn ts_specifier(p: &Path) -> String {
843    p.to_string_lossy().replace('\\', "/")
844}
845
846/// Compute a relative import specifier from this file's location to a
847/// specific source file in another commons. `target_source` is the project-
848/// relative path of the target `.bynk` file. The result is suitable for
849/// `import { ... } from "..."` in NodeNext/strict TypeScript.
850pub fn cross_commons_import_specifier_for_path(
851    from_source: &Path,
852    target_source: &Path,
853    ext: ImportExt,
854) -> String {
855    let from_dir = from_source.parent().unwrap_or(Path::new(""));
856    let target = target_source.with_extension(ext.as_str());
857    let rel = relative_to(from_dir, &target);
858    let display = ts_specifier(&rel);
859    if display.starts_with("../") || display.starts_with("./") {
860        display
861    } else {
862        format!("./{display}")
863    }
864}
865
866/// Compute `target` as a path relative to `from`. Handles parent traversal
867/// (`..`) for cases where `target` lives in a sibling directory.
868fn relative_to(from: &Path, target: &Path) -> PathBuf {
869    use std::path::Component as C;
870    let f_comps: Vec<C> = from.components().collect();
871    let t_comps: Vec<C> = target.components().collect();
872    let mut shared = 0;
873    while shared < f_comps.len() && shared < t_comps.len() && f_comps[shared] == t_comps[shared] {
874        shared += 1;
875    }
876    let mut out = PathBuf::new();
877    for _ in shared..f_comps.len() {
878        out.push("..");
879    }
880    for c in &t_comps[shared..] {
881        out.push(c.as_os_str());
882    }
883    if out.as_os_str().is_empty() {
884        out.push(".");
885    }
886    out
887}