@nstudio/nativescript-compiler 9.2.0-alpha.10 → 9.2.0-alpha.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (181) hide show
  1. package/dist/api/ir.js +7 -1
  2. package/dist/cli/runtime.cjs +7 -1
  3. package/dist/css/css.js +30 -6
  4. package/dist/driver/cli.js +2 -0
  5. package/dist/driver/compile.js +23 -10
  6. package/dist/driver/paths.js +7 -0
  7. package/dist/driver/unimplemented.js +15 -0
  8. package/dist/kotlin/access.js +23 -5
  9. package/dist/kotlin/arguments.js +5 -0
  10. package/dist/kotlin/builtins.js +0 -4
  11. package/dist/kotlin/calls.js +6 -2
  12. package/dist/kotlin/class-methods.js +9 -3
  13. package/dist/kotlin/components.js +13 -8
  14. package/dist/kotlin/conversion.js +17 -5
  15. package/dist/kotlin/core-api.js +2 -13
  16. package/dist/kotlin/declarations.js +2 -0
  17. package/dist/kotlin/expression-statements.js +5 -4
  18. package/dist/kotlin/expressions.js +8 -3
  19. package/dist/kotlin/functions.js +13 -4
  20. package/dist/kotlin/global-calls.js +11 -0
  21. package/dist/kotlin/literals.js +58 -14
  22. package/dist/kotlin/names.js +2 -2
  23. package/dist/kotlin/native/api.js +9 -1
  24. package/dist/kotlin/native/calls.js +84 -3
  25. package/dist/kotlin/native/subclasses.js +4 -3
  26. package/dist/kotlin/native/types.js +8 -5
  27. package/dist/kotlin/operators.js +4 -1
  28. package/dist/kotlin/overrides.js +7 -5
  29. package/dist/kotlin/placement.js +3 -1
  30. package/dist/kotlin/prototype-calls.js +5 -0
  31. package/dist/kotlin/render.js +62 -0
  32. package/dist/kotlin/statements.js +9 -0
  33. package/dist/kotlin/static-calls.js +10 -7
  34. package/dist/kotlin/translator.js +31 -11
  35. package/dist/kotlin/type-facts.js +10 -2
  36. package/dist/kotlin/types.js +6 -6
  37. package/dist/plugins/native-android.js +37 -5
  38. package/dist/plugins/native-ios.js +2 -0
  39. package/dist/plugins/source.js +73 -23
  40. package/dist/program/app-modules.js +91 -16
  41. package/dist/program/app-paths.js +80 -12
  42. package/dist/program/class-mixins.js +463 -0
  43. package/dist/program/core-facts.js +7 -0
  44. package/dist/program/glob.js +274 -0
  45. package/dist/program/platform.js +32 -4
  46. package/dist/program/program.js +239 -38
  47. package/dist/program/source-lines.js +4 -1
  48. package/dist/program/vite-plugins.js +144 -0
  49. package/dist/semantics/apis/globals.js +2 -2
  50. package/dist/semantics/apis/object.js +1 -0
  51. package/dist/semantics/apis/statics.js +6 -0
  52. package/dist/semantics/ast.js +20 -2
  53. package/dist/semantics/classes.js +36 -1
  54. package/dist/semantics/facts.js +28 -1
  55. package/dist/semantics/globals.js +3 -0
  56. package/dist/semantics/lang.js +13 -1
  57. package/dist/semantics/nullish.js +29 -11
  58. package/dist/semantics/refuse-receivers.js +3 -3
  59. package/dist/semantics/refuse-scope.js +2 -7
  60. package/dist/semantics/runtime.js +1 -0
  61. package/dist/semantics/shapes.js +21 -1
  62. package/dist/semantics/states/value-states.js +1 -1
  63. package/dist/semantics/throws.js +1 -0
  64. package/dist/semantics/translator-methods.js +1 -1
  65. package/dist/semantics/types.js +21 -1
  66. package/dist/swift/access.js +25 -10
  67. package/dist/swift/arguments.js +10 -2
  68. package/dist/swift/assignment.js +12 -1
  69. package/dist/swift/builtins.js +0 -4
  70. package/dist/swift/calls.js +6 -2
  71. package/dist/swift/class-methods.js +3 -3
  72. package/dist/swift/components.js +28 -8
  73. package/dist/swift/construction.js +4 -0
  74. package/dist/swift/conversion.js +1 -1
  75. package/dist/swift/core-api.js +9 -12
  76. package/dist/swift/from-any.js +2 -2
  77. package/dist/swift/functions.js +13 -2
  78. package/dist/swift/generics.js +5 -1
  79. package/dist/swift/global-calls.js +2 -0
  80. package/dist/swift/literals.js +57 -10
  81. package/dist/swift/modules.js +1 -1
  82. package/dist/swift/names.js +1 -1
  83. package/dist/swift/native/sdk-tables.js +52 -4
  84. package/dist/swift/native/sdk.js +9 -1
  85. package/dist/swift/operators.js +4 -1
  86. package/dist/swift/parameters.js +5 -2
  87. package/dist/swift/placement.js +44 -4
  88. package/dist/swift/prototype-calls.js +17 -2
  89. package/dist/swift/render.js +64 -0
  90. package/dist/swift/results.js +1 -1
  91. package/dist/swift/statements.js +9 -0
  92. package/dist/swift/static-calls.js +13 -6
  93. package/dist/swift/types.js +9 -9
  94. package/dist/targets/android/build.js +18 -12
  95. package/dist/targets/ios/build.js +11 -10
  96. package/dist/targets/ios/dependencies.js +12 -0
  97. package/dist/targets/resources.js +15 -1
  98. package/dist/template/plan.js +105 -8
  99. package/dist/types/adapter-api.d.ts +13 -0
  100. package/dist/types/ir.d.ts +47 -0
  101. package/kit-android/generated/kotlin/org/nativescript/kit/__Objects.kt +102 -7485
  102. package/kit-android/generated/kotlin/org/nativescript/kit/application_application.kt +4 -4
  103. package/kit-android/generated/kotlin/org/nativescript/kit/image_source_index.kt +1 -1
  104. package/kit-android/generated/kotlin/org/nativescript/kit/ui_animation_animation_common.kt +7 -3
  105. package/kit-android/generated/kotlin/org/nativescript/kit/ui_animation_index.kt +3 -1
  106. package/kit-android/generated/kotlin/org/nativescript/kit/ui_core_view_base_index.kt +2 -4
  107. package/kit-android/generated/kotlin/org/nativescript/kit/ui_core_view_index.kt +5 -6
  108. package/kit-android/generated/kotlin/org/nativescript/kit/ui_core_view_view_common.kt +1 -3
  109. package/kit-android/generated/kotlin/org/nativescript/kit/ui_dialogs_index.kt +11 -6
  110. package/kit-android/generated/kotlin/org/nativescript/kit/ui_frame_fragment_transitions.kt +1 -1
  111. package/kit-android/generated/kotlin/org/nativescript/kit/ui_frame_frame_common.kt +1 -1
  112. package/kit-android/generated/kotlin/org/nativescript/kit/ui_frame_frame_helper_for_android.kt +7 -5
  113. package/kit-android/generated/kotlin/org/nativescript/kit/ui_frame_index.kt +6 -3
  114. package/kit-android/generated/kotlin/org/nativescript/kit/ui_gestures_touch_manager.kt +1 -1
  115. package/kit-android/generated/kotlin/org/nativescript/kit/ui_layouts_flexbox_layout_index.kt +1 -1
  116. package/kit-android/generated/kotlin/org/nativescript/kit/ui_search_bar_index.kt +4 -3
  117. package/kit-android/generated/kotlin/org/nativescript/kit/ui_segmented_bar_index.kt +2 -2
  118. package/kit-android/generated/kotlin/org/nativescript/kit/ui_text_base_formatted_string.kt +1 -3
  119. package/kit-android/generated/kotlin/org/nativescript/kit/ui_text_base_index.kt +1 -1
  120. package/kit-android/generated/kotlin/org/nativescript/kit/ui_transition_fade_transition.kt +1 -1
  121. package/kit-android/generated/kotlin/org/nativescript/kit/ui_transition_flip_transition.kt +8 -8
  122. package/kit-android/generated/kotlin/org/nativescript/kit/utils_index.kt +1 -1
  123. package/kit-android/generated/source-lines.json +1 -1
  124. package/kit-android/gradlew.bat +94 -0
  125. package/kit-android/src/fromcore/kotlin/org/nativescript/kit/CoreBridge.kt +67 -1
  126. package/kit-android/src/main/kotlin/org/nativescript/kit/Signals.kt +15 -2
  127. package/kit-android/src/main/kotlin/org/nativescript/kit/runtime/Prototypes.kt +26 -0
  128. package/kit-apple/Overlays/xml-free/Core/ui.core.bindable.index.swift +4 -4
  129. package/kit-apple/Sources/NativeScriptKit/Core/FunctionCells.Arity1.swift +26 -161
  130. package/kit-apple/Sources/NativeScriptKit/Core/FunctionCells.Arity2.swift +9 -284
  131. package/kit-apple/Sources/NativeScriptKit/Core/FunctionCells.Arity3Plus.swift +11 -7
  132. package/kit-apple/Sources/NativeScriptKit/Core/Object_callback_thisArg_once.swift +1 -1
  133. package/kit-apple/Sources/NativeScriptKit/Core/Object_eventName_object_index_section_view_ios_android.swift +7 -5
  134. package/kit-apple/Sources/NativeScriptKit/Core/Object_eventName_object_oldIndex_newIndex.swift +4 -2
  135. package/kit-apple/Sources/NativeScriptKit/Core/{Object_iterator_prototype_for_keyFor_hasInstance_isConcatSpreadable_and_19_more_91b5f3.swift → Object_iterator_prototype_for_keyFor_hasInstance_isConcatSpreadable_and_19_more_fa18e1.swift} +28 -103
  136. package/kit-apple/Sources/NativeScriptKit/Core/__Namespace.Utils.swift +17 -15
  137. package/kit-apple/Sources/NativeScriptKit/Core/application-settings.index.ios.swift +8 -8
  138. package/kit-apple/Sources/NativeScriptKit/Core/application.application-common.swift +4 -4
  139. package/kit-apple/Sources/NativeScriptKit/Core/color.color-common.swift +7 -7
  140. package/kit-apple/Sources/NativeScriptKit/Core/data.observable.index.swift +3 -3
  141. package/kit-apple/Sources/NativeScriptKit/Core/http.http-request-internal.index.ios.swift +2 -1
  142. package/kit-apple/Sources/NativeScriptKit/Core/image-source.index.ios.swift +1 -1
  143. package/kit-apple/Sources/NativeScriptKit/Core/kit-index.json +40 -246
  144. package/kit-apple/Sources/NativeScriptKit/Core/manifest.json +1 -2
  145. package/kit-apple/Sources/NativeScriptKit/Core/ui.action-bar.index.ios.swift +3 -3
  146. package/kit-apple/Sources/NativeScriptKit/Core/ui.button.index.ios.swift +4 -4
  147. package/kit-apple/Sources/NativeScriptKit/Core/ui.content-view.index.swift +8 -8
  148. package/kit-apple/Sources/NativeScriptKit/Core/ui.core.bindable.index.swift +4 -4
  149. package/kit-apple/Sources/NativeScriptKit/Core/ui.core.view.index.ios.swift +8 -8
  150. package/kit-apple/Sources/NativeScriptKit/Core/ui.core.view.view-common.swift +1 -3
  151. package/kit-apple/Sources/NativeScriptKit/Core/ui.core.view.view-helper.view-helper-common.swift +7 -7
  152. package/kit-apple/Sources/NativeScriptKit/Core/ui.core.weak-event-listener.index.swift +3 -3
  153. package/kit-apple/Sources/NativeScriptKit/Core/ui.frame.index.ios.swift +4 -4
  154. package/kit-apple/Sources/NativeScriptKit/Core/ui.gestures.index.ios.swift +2 -2
  155. package/kit-apple/Sources/NativeScriptKit/Core/ui.html-view.index.ios.swift +4 -4
  156. package/kit-apple/Sources/NativeScriptKit/Core/ui.image.image-common.swift +2 -2
  157. package/kit-apple/Sources/NativeScriptKit/Core/ui.image.index.ios.swift +4 -4
  158. package/kit-apple/Sources/NativeScriptKit/Core/ui.label.index.ios.swift +4 -4
  159. package/kit-apple/Sources/NativeScriptKit/Core/ui.layouts.absolute-layout.index.ios.swift +4 -4
  160. package/kit-apple/Sources/NativeScriptKit/Core/ui.layouts.dock-layout.index.ios.swift +4 -4
  161. package/kit-apple/Sources/NativeScriptKit/Core/ui.layouts.flexbox-layout.index.ios.swift +3 -3
  162. package/kit-apple/Sources/NativeScriptKit/Core/ui.layouts.grid-layout.index.ios.swift +4 -4
  163. package/kit-apple/Sources/NativeScriptKit/Core/ui.layouts.stack-layout.index.ios.swift +4 -4
  164. package/kit-apple/Sources/NativeScriptKit/Core/ui.layouts.wrap-layout.index.ios.swift +4 -4
  165. package/kit-apple/Sources/NativeScriptKit/Core/ui.list-view.index.ios.swift +3 -3
  166. package/kit-apple/Sources/NativeScriptKit/Core/ui.page.index.ios.swift +4 -4
  167. package/kit-apple/Sources/NativeScriptKit/Core/ui.repeater.index.swift +10 -6
  168. package/kit-apple/Sources/NativeScriptKit/Core/ui.scroll-view.index.ios.swift +4 -4
  169. package/kit-apple/Sources/NativeScriptKit/Core/ui.split-view.index.ios.swift +4 -4
  170. package/kit-apple/Sources/NativeScriptKit/Core/ui.styling.background.ios.swift +1 -1
  171. package/kit-apple/Sources/NativeScriptKit/Core/ui.tab-view.index.ios.swift +4 -4
  172. package/kit-apple/Sources/NativeScriptKit/Core/ui.text-base.formatted-string.swift +2 -1
  173. package/kit-apple/Sources/NativeScriptKit/Core/utils.common.swift +9 -9
  174. package/kit-apple/Sources/NativeScriptKit/Core/utils.layout-helper.index.ios.swift +10 -10
  175. package/kit-apple/Sources/NativeScriptKit/CoreBridge.swift +67 -1
  176. package/kit-apple/Sources/NativeScriptKit/Runtime/Lowering.swift +4 -0
  177. package/kit-apple/Sources/NativeScriptKit/Runtime/Prototypes.swift +25 -0
  178. package/kit-apple/Sources/NativeScriptKit/Runtime/RegExp.swift +6 -0
  179. package/kit-apple/Sources/NativeScriptKit/Signals.swift +20 -2
  180. package/package.json +2 -1
  181. package/kit-apple/Sources/NativeScriptKit/Core/Object_toString_charAt_charCodeAt_concat_indexOf_lastIndexOf_and_44_more_fc25df.swift +0 -481
@@ -2,9 +2,10 @@
2
2
  import { heldLoss } from "../semantics/losses.js";
3
3
  import ts from 'typescript';
4
4
  import { TYPED_ARRAYS } from "../semantics/globals.js";
5
- import { ident, isThisParameter, optionalType, RT } from "./syntax.js";
5
+ import { ident, isThisParameter, kotlinString, optionalType, RT } from "./syntax.js";
6
6
  import { undefinedLiteral } from "../semantics/lang.js";
7
- import { assignsArrayIntoObject } from "../semantics/shapes.js";
7
+ import { arrayFromLengthInit } from "../semantics/ast.js";
8
+ import { assignsArrayIntoObject, shapeArrayGuardAccess } from "../semantics/shapes.js";
8
9
  import { CONSOLE } from "../semantics/apis/console.js";
9
10
  import { staticFunction } from "../semantics/apis/statics.js";
10
11
  import { runtimeCall } from "../semantics/apis/api.js";
@@ -120,14 +121,16 @@ export const staticCallsMethods = {
120
121
  if (native)
121
122
  return native;
122
123
  }
123
- if (method === 'isArray')
124
- return `JSArray.isArray(${this.restArgument(e, arg(0), 'Any?')})`;
124
+ if (method === 'isArray') {
125
+ const guard = !this.library ? shapeArrayGuardAccess(arg(0), (t) => this.isShapeType(t), (x) => this.typeOf(x)) : null;
126
+ return guard ? `JSArray.isArray(${this.expr(guard.prop.expression)}${guard.optional ? '?' : ''}.jsGet(${kotlinString(guard.prop.name.text)}))` : `JSArray.isArray(${this.restArgument(e, arg(0), 'Any?')})`;
127
+ }
125
128
  if (method === 'from' && e.arguments.length === 1)
126
129
  return `JSArray(${this.iterable(arg(0))}.toList())`;
127
130
  if (method === 'from' && (e.arguments.length === 2 || e.arguments.length === 3) && ts.isObjectLiteralExpression(arg(0))) {
128
- const length = arg(0).properties.find((p) => p.name?.getText() === 'length');
131
+ const lenExpr = arrayFromLengthInit(arg(0));
129
132
  const fn = arg(1);
130
- if (!length || !ts.isPropertyAssignment(length) || !(ts.isArrowFunction(fn) || ts.isFunctionExpression(fn)))
133
+ if (!lenExpr || !(ts.isArrowFunction(fn) || ts.isFunctionExpression(fn)))
131
134
  throw this.error(e, 'Array.from of this object');
132
135
  const el = T().replace(/^JSArray<(.*)>$/, '$1');
133
136
  const params = fn.parameters.filter((p) => !isThisParameter(p));
@@ -135,7 +138,7 @@ export const staticCallsMethods = {
135
138
  const value = params[0] && ts.isIdentifier(params[0].name) && params[0].name.text !== '_' ? `val ${ident(params[0].name.text)}: Any? = null; ` : '';
136
139
  return this.ignoringThisArg(e, arg(0), () => {
137
140
  const body = ts.isBlock(fn.body) ? this.functionBody(fn, el, this.indent) : `{ return ${this.coerce(fn.body, el)} }`;
138
- return `JSArray.fromLength<${el}>(${this.toNumber(length.initializer)}, fun(${index}: Double): ${el} { ${value}${body.slice(1, -1)} })`;
141
+ return `JSArray.fromLength<${el}>(${this.toNumber(lenExpr)}, fun(${index}: Double): ${el} { ${value}${body.slice(1, -1)} })`;
139
142
  });
140
143
  }
141
144
  if (method === 'from' && (e.arguments.length === 2 || e.arguments.length === 3))
@@ -89,6 +89,7 @@ export class Translator {
89
89
  translating;
90
90
  /** Android: the worker scripts compiled with the app, by file, and the name the entry registers each under. */
91
91
  workerScripts;
92
+ resolveAlias;
92
93
  /** The generated kit: a module's name for `AppModules.runImport`, set where modules `await import(…)` reaches run when imported. */
93
94
  moduleKey;
94
95
  /** The program's whole-program answers, shared with any translator of the same checker and files. */
@@ -148,6 +149,7 @@ export class Translator {
148
149
  this.checker = checker;
149
150
  this.lenient = c.lenient ?? false;
150
151
  this.workerScripts = c.workerScripts ?? null;
152
+ this.resolveAlias = c.resolveAlias ?? null;
151
153
  this.moduleThread = c.moduleThread ?? null;
152
154
  this.moduleKey = c.moduleKey;
153
155
  this.components = components;
@@ -691,7 +693,7 @@ export class Translator {
691
693
  if (at === 'JSArrayBuffer')
692
694
  return `${t}(${[this.expr(a), ...numbers].join(', ')})`;
693
695
  if (name === 'DataView')
694
- return `${t}((${this.coerce(a, 'Any?')} as JSArrayBufferView).buffer, ${numbers.join(', ')})`;
696
+ return `${t}.from(${[this.coerce(a, 'Any?'), ...numbers].join(', ')})`;
695
697
  if (at === 'Double')
696
698
  return `${t}(${this.expr(a)})`;
697
699
  if (isKit(spelledType(at), 'JSArray'))
@@ -714,18 +716,36 @@ export class Translator {
714
716
  });
715
717
  return `object : ${this.className(base)}() {\n${members.join('\n')}\n}`;
716
718
  }
717
- /** `new URL('./x.worker', import.meta.url)`: the worker script it names, when the app compiled it. */
719
+ /** `new Worker('~/x')`, `new Worker('./x')`, or `new Worker(new URL('./x', import.meta.url))`: the worker script it names, when the app compiled it. */
718
720
  workerScript(e) {
719
- if (!ts.isNewExpression(e) || !ts.isIdentifier(e.expression) || e.expression.text !== 'URL')
720
- return null;
721
- const [spec, base] = e.arguments ?? [];
722
- if (!spec || !ts.isStringLiteralLike(spec) || !base || base.getText() !== 'import.meta.url')
721
+ let spec = null;
722
+ if (ts.isStringLiteralLike(e)) {
723
+ spec = e.text;
724
+ }
725
+ else if (ts.isNewExpression(e) && ts.isIdentifier(e.expression) && e.expression.text === 'URL') {
726
+ const [s, base] = e.arguments ?? [];
727
+ if (s && ts.isStringLiteralLike(s) && base && base.getText() === 'import.meta.url')
728
+ spec = s.text;
729
+ }
730
+ if (!spec || !this.workerScripts?.size)
723
731
  return null;
724
- const stem = pathResolve(pathDirname(e.getSourceFile().fileName), spec.text).replace(/\.(ts|js)$/, '');
725
- for (const f of [stem + '.ts', stem + '.android.ts', stem + '/index.ts']) {
726
- const script = this.workerScripts?.get(f);
727
- if (script)
728
- return script;
732
+ const file = e.getSourceFile().fileName;
733
+ const target = spec.startsWith('.') ? pathResolve(pathDirname(file), spec) : this.resolveAlias?.(spec, file);
734
+ if (target) {
735
+ const stem = target.replace(/\\/g, '/').replace(/\.(tsx?|m?js)$/, '');
736
+ for (const f of [stem + '.ts', stem + '.android.ts', stem + '.tsx', stem + '/index.ts', stem + '/index.android.ts']) {
737
+ const script = this.workerScripts.get(f);
738
+ if (script)
739
+ return script;
740
+ }
741
+ }
742
+ if (spec.startsWith('~/') || spec.startsWith('@/')) {
743
+ const rel = spec.slice(2).replace(/\\/g, '/').replace(/\.(tsx?|m?js)$/, '');
744
+ for (const [key, script] of this.workerScripts) {
745
+ const norm = key.replace(/\\/g, '/');
746
+ if ([`/${rel}.ts`, `/${rel}.android.ts`, `/${rel}.tsx`, `/${rel}/index.ts`, `/${rel}/index.android.ts`].some((s) => norm.endsWith(s)))
747
+ return script;
748
+ }
729
749
  }
730
750
  return null;
731
751
  }
@@ -86,12 +86,20 @@ export const typeFactsMethods = {
86
86
  /** Whether a read of `e` only tests or passes on its value, so a nullable declaration needs no unwrap there. */
87
87
  nullTolerant(e) {
88
88
  let n = e;
89
- while (ts.isParenthesizedExpression(n.parent))
89
+ while (ts.isParenthesizedExpression(n.parent) ||
90
+ ((ts.isAsExpression(n.parent) || ts.isTypeAssertionExpression(n.parent)) &&
91
+ (() => {
92
+ const pt = this.typeOf(n.parent);
93
+ return isUntyped(spelledType(pt)) || isNullable(pt) || this.isTypeParameterName(pt);
94
+ })()))
90
95
  n = n.parent;
91
96
  if (this.nullOk.has(n) || this.nullOk.has(e) || this.states.observedAsIs(e))
92
97
  return true;
93
98
  const p = n.parent;
94
99
  const K = ts.SyntaxKind;
100
+ // A discarded expression (`context.registerReceiver(...)`, `void expr`) never dereferences its result.
101
+ if (ts.isExpressionStatement(p) || ts.isVoidExpression(p))
102
+ return true;
95
103
  // A branch of a conditional, or `a ?? b`'s `b`, where the whole goes where missing is taken; or a result a function gives as nullable.
96
104
  if (ts.isConditionalExpression(p) && (p.whenTrue === n || p.whenFalse === n))
97
105
  return this.nullTolerant(p);
@@ -101,7 +109,7 @@ export const typeFactsMethods = {
101
109
  const fn = ts.isArrowFunction(p) ? p : ts.findAncestor(p, ts.isFunctionLike);
102
110
  if (fn && (ts.isMethodDeclaration(fn) || ts.isFunctionDeclaration(fn) || ts.isGetAccessorDeclaration(fn))) {
103
111
  const rt = this.returnTypeOf(fn);
104
- if (isNullable(rt) || isUntyped(spelledType(rt)))
112
+ if (isNullable(rt) || isUntyped(spelledType(rt)) || (this.library && this.isTypeParameterName(rt)))
105
113
  return true;
106
114
  }
107
115
  }
@@ -7,7 +7,7 @@ import { ambientBase, evolvingArrayRead, evolvingArrayType, isAmbientClass, isRe
7
7
  import { nullishSignalType } from "../semantics/signals.js";
8
8
  import { hasModifier, isLibDeclaration, thisNodes, isWriteTarget, implementationOf, takesOwnThis } from "../semantics/ast.js";
9
9
  import { isCoreDeclaration } from "../program/core-facts.js";
10
- import { coreTypeKind, eventDataTypeLiteral, isJsDocConstructorFunction, isKit, isLibObjectType, isNamed, isUntyped, libraryNativeType, libraryType, mappedOrErasedType, nonNullableInner, nonOptionalSpelling, parseNativeType, spelledType } from "../semantics/types.js";
10
+ import { coreTypeKind, eventDataTypeLiteral, hasMappedIntersection, isJsDocConstructorFunction, isKit, isLibObjectType, isNamed, isUntyped, libraryNativeType, libraryType, mappedOrErasedType, nonNullableInner, nonOptionalSpelling, parseNativeType, spelledType, valueModuleKind } from "../semantics/types.js";
11
11
  import { isStatic } from "../semantics/throws.js";
12
12
  import { literalOverArray, membersOverTypeParameter, untypedResultBinding, untypedResultField } from "../semantics/shapes.js";
13
13
  import { extendedClass, isEventData } from "../semantics/classes.js";
@@ -34,10 +34,10 @@ export const typesMethods = {
34
34
  const component = t.getSymbol()?.flags & ts.SymbolFlags.Class ? t.getSymbol().declarations?.[0] : undefined;
35
35
  if (component && ts.isClassDeclaration(component) && this.pluginFiles.has(component.getSourceFile().fileName) && this.framework.componentClass(component))
36
36
  return 'Any?';
37
- // A namespace as a value (`{ Kinds: Trace.Kinds }`): its object.
38
- const nsDecl = t.flags & F.Object && t.getSymbol()?.flags & ts.SymbolFlags.ValueModule ? t.getSymbol().valueDeclaration : undefined;
39
- if (nsDecl && ts.isModuleDeclaration(nsDecl) && !nsDecl.getSourceFile().isDeclarationFile)
40
- return this.namespacePath(nsDecl);
37
+ // A namespace as a value (`{ Kinds: Trace.Kinds }`) or an ES module namespace (`typeof import('...')`).
38
+ const ns = valueModuleKind(t);
39
+ if (ns)
40
+ return ns === 'module' ? 'Any?' : this.namespacePath(ns);
41
41
  // An enum as a value (`typeof Color`) in app code: the object JavaScript makes of it. Not the enum's own name, through
42
42
  // which its members are read (`Color.Red`).
43
43
  const enumObject = !this.library && t.flags & F.Object && (t.getSymbol()?.flags ?? 0) & ts.SymbolFlags.RegularEnum ? t.getSymbol().valueDeclaration : undefined;
@@ -103,7 +103,7 @@ export const typesMethods = {
103
103
  const bound = t.types.map((u) => (u.flags & F.TypeParameter ? this.checker.getBaseConstraintOfType(u) : undefined)).find((u) => u && u.flags & (F.String | F.Number | F.Boolean));
104
104
  if (bound && t.types.every((u) => u.flags & (F.TypeParameter | F.Conditional)))
105
105
  return this.type(bound, where);
106
- if (membersOverTypeParameter(t, this.checker))
106
+ if (membersOverTypeParameter(t, this.checker) || hasMappedIntersection(t))
107
107
  return 'Any?';
108
108
  // A function carrying properties (`((p: P) => R) & { type: string }`): an untyped value, called as script calls it.
109
109
  if (t.types.some((u) => u.getCallSignatures().length) && t.types.some((u) => !u.getCallSignatures().length && u.getProperties().length) && !t.types.some((u) => isLibDeclaration(u.getSymbol()?.declarations?.[0])))
@@ -4,7 +4,7 @@ import { cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync,
4
4
  import { homedir } from 'node:os';
5
5
  import { dirname, join, relative, resolve } from 'node:path';
6
6
  import { archiveClasses } from "../kotlin/native/classfiles.js";
7
- import { cacheDir, KIT_ANDROID } from "../driver/paths.js";
7
+ import { cacheDir, gradleWrapper, KIT_ANDROID } from "../driver/paths.js";
8
8
  import { byName, compareText } from "../program/order.js";
9
9
  /** What the plugin libraries are built with: the generated app's (targets/android/build.ts). */
10
10
  const AGP = '8.12.1', KOTLIN = '2.2.20', COMPILE_SDK = 36, KIT_MIN_SDK = 24;
@@ -88,10 +88,12 @@ export function pluginNativeAndroid(sources, options) {
88
88
  if (errors.length)
89
89
  throw new Error(`plugins' Android code that cannot be built yet:\n ${errors.join('\n ')}`);
90
90
  const dependencies = includes.flatMap((i) => i.dependencies);
91
+ const sharedDeps = [...new Map(dependencies.filter((d) => d.configuration !== 'annotationProcessor').map((d) => [d.coords, d.coords])).values()];
92
+ const sharedRepos = [...new Set(includes.flatMap((i) => i.repositories))];
91
93
  // A cached AAR is rebuilt when a dependency it declares is not in Gradle's cache: the translation reads its classes from there.
92
94
  const stale = libraries.filter((l) => !existsSync(l.aar) || l.include?.dependencies.some((d) => !inGradleCache(d.coords)));
93
95
  if (stale.length || fetches.length)
94
- buildLibraries([...stale, ...fetches], options);
96
+ buildLibraries([...stale, ...fetches], options, sharedDeps, sharedRepos);
95
97
  archives.push(...libraries.map((l) => l.aar));
96
98
  return {
97
99
  archives,
@@ -129,7 +131,7 @@ function inGradleCache(coords) {
129
131
  return !version || /[+\[\]()]/.test(version) || existsSync(join(GRADLE_CACHE, group, artifact, version));
130
132
  }
131
133
  /** One Gradle build of every library not in the cache, a subproject each, with the kit's wrapper. */
132
- function buildLibraries(libraries, options) {
134
+ function buildLibraries(libraries, options, sharedDeps = [], sharedRepos = []) {
133
135
  const cache = options.cache ?? DEFAULT_CACHE;
134
136
  mkdirSync(cache, { recursive: true });
135
137
  const root = mkdtempSync(join(cache, '.build-'));
@@ -182,14 +184,17 @@ kotlin {
182
184
  repositories {
183
185
  google()
184
186
  mavenCentral()
187
+ ${sharedRepos.map((r) => ` maven { url = ${q(r)} }`).join('\n')}
185
188
  }
186
189
 
190
+ ${sharedDeps.length ? `dependencies {\n${sharedDeps.map((c) => ` implementation ${q(c)}`).join('\n')}\n}\n` : ''}
187
191
  ${l.include?.libraryBlocks.join('\n\n') ?? ''}
188
192
  `);
189
193
  });
190
194
  options.say?.(`building the Android code of ${libraries.map((l) => `${l.source.name}@${l.source.version}`).join(', ')}`);
191
195
  try {
192
- execFileSync(join(kit, 'gradlew'), ['-p', root, 'assembleRelease', '-PtempBuild=true', '--quiet'], { stdio: 'inherit' });
196
+ const gw = gradleWrapper(['-p', root, 'assembleRelease', '-PtempBuild=true', '--quiet'], kit);
197
+ execFileSync(gw.command, gw.args, { stdio: 'inherit' });
193
198
  }
194
199
  catch {
195
200
  throw new Error(`the Android code of ${libraries.map((l, i) => `${l.source.name} (:p${i})`).join(', ')} did not build (Gradle's output is above)`);
@@ -207,7 +212,7 @@ ${l.include?.libraryBlocks.join('\n\n') ?? ''}
207
212
  rmSync(root, { recursive: true, force: true });
208
213
  }
209
214
  }
210
- const CONFIGURATIONS = { implementation: 'implementation', api: 'implementation', compileOnly: 'compileOnly', runtimeOnly: 'runtimeOnly' };
215
+ const CONFIGURATIONS = { implementation: 'implementation', api: 'implementation', compileOnly: 'compileOnly', runtimeOnly: 'runtimeOnly', annotationProcessor: 'annotationProcessor' };
211
216
  const KNOWN_REPOSITORIES = new Set(['google', 'mavenCentral']);
212
217
  /**
213
218
  * The parts of an include.gradle the app's build takes: `dependencies` of
@@ -411,6 +416,33 @@ export function parseIncludeGradle(text) {
411
416
  });
412
417
  return;
413
418
  }
419
+ if (blockOf('compileOptions')) {
420
+ i++;
421
+ statements((c) => {
422
+ if (!is(c, 'id', 'sourceCompatibility') && !is(c, 'id', 'targetCompatibility') && !is(c, 'id', 'encoding'))
423
+ unsupported(c);
424
+ i++;
425
+ if (is(peek(), 'punct', '='))
426
+ i++;
427
+ if (is(peek(), 'str') || is(peek(), 'num')) {
428
+ i++;
429
+ return;
430
+ }
431
+ // `JavaVersion.VERSION_1_8` or `JavaVersion.toVersion(...)`.
432
+ expect('id');
433
+ while (is(peek(), 'punct', '.')) {
434
+ i++;
435
+ expect('id');
436
+ }
437
+ if (is(peek(), 'punct', '(')) {
438
+ i++;
439
+ while (!is(peek(), 'punct', ')') && !is(peek(), 'end'))
440
+ i++;
441
+ expect('punct', ')');
442
+ }
443
+ });
444
+ return;
445
+ }
414
446
  if (!is(s, 'id', 'defaultConfig'))
415
447
  unsupported(s);
416
448
  i++;
@@ -261,6 +261,8 @@ function targetsOf(source, errors, deps) {
261
261
  else
262
262
  walk(p);
263
263
  }
264
+ else if (f === 'Package.swift')
265
+ continue;
264
266
  else if (f.endsWith('.swift'))
265
267
  swift.push(p);
266
268
  else if (/\.(h|hh|hpp|m|mm|c|cc|cpp)$/.test(f))
@@ -48,7 +48,19 @@ export class PluginSources {
48
48
  * Checks source files the build compiles against the published files they
49
49
  * were built from, once each: what is compiled is what npm installed.
50
50
  */
51
- verify(sources) {
51
+ verify(sources, onMismatch) {
52
+ const check = (fn) => {
53
+ if (!onMismatch) {
54
+ fn();
55
+ return;
56
+ }
57
+ try {
58
+ fn();
59
+ }
60
+ catch (e) {
61
+ onMismatch(e.message.split('\n')[0]);
62
+ }
63
+ };
52
64
  for (const src of sources) {
53
65
  for (const source of this.packages.values()) {
54
66
  // A bundle is checked when any source it bundles is compiled: its entry may be an index that only re-exports.
@@ -56,15 +68,15 @@ export class PluginSources {
56
68
  const matches = [...source.files].filter(([j, s]) => s === src || !!source.bundles.get(j)?.files.includes(src)).map(([j]) => j);
57
69
  const js = matches.find((j) => isEsModule(j)) ?? matches[0];
58
70
  if (js && !source.checked.has(js) && source.verified === 'shipped')
59
- verifyMap(source.name, js, this.options.app, source.version);
60
- if (!js)
71
+ check(() => verifyMap(source.name, js, this.options.app, source.version));
72
+ if (!js || src === js)
61
73
  continue;
62
74
  if (!source.checked.has(js) && source.verified === 'published') {
63
75
  const bundle = source.bundles.get(js);
64
76
  if (bundle)
65
- verifyBundle(source.name, js, bundle, this.options.app, source.version);
77
+ check(() => verifyBundle(source.name, js, bundle, this.options.app, source.version));
66
78
  else
67
- verify(source.name, js, src, this.options.app, source.version);
79
+ check(() => verify(source.name, js, src, this.options.app, source.version));
68
80
  }
69
81
  source.checked.add(js);
70
82
  }
@@ -390,13 +402,17 @@ function shipsJsSource(dir, pkg) {
390
402
  }
391
403
  return true;
392
404
  }
393
- /** Whether a JavaScript file uses CommonJS syntax (`require(...)` or `module.exports`/`exports.`). */
405
+ /** Whether a JavaScript file uses CommonJS syntax (`require(...)` or unconditional `module.exports`/`exports.`). */
394
406
  function isCommonJsModule(js) {
395
407
  try {
396
408
  const text = readFileSync(js, 'utf8');
397
409
  if (/(?:^|\n)\s*(?:import\s|export\s)/.test(text))
398
410
  return false;
399
- return /\b(?:module\.exports|exports\.[A-Za-z_$]|require\s*\()/.test(text);
411
+ if (/\brequire\s*\(/.test(text))
412
+ return true;
413
+ // Standard UMD default export guard (`if (typeof module !== 'undefined' && module.exports) { module.exports = X; }`) can be desugared to ESM.
414
+ const stripped = text.replace(/if\s*\(\s*typeof\s+module\s*!==?\s*['"]undefined['"]\s*&&\s*module\.exports\s*\)\s*(?:\{\s*module\.exports\s*=\s*[^;{}]+;?\s*\}|module\.exports\s*=\s*[^;]+;?)/g, '');
415
+ return /\b(?:module\.exports|exports\.[A-Za-z_$])/.test(stripped);
400
416
  }
401
417
  catch {
402
418
  return false;
@@ -672,10 +688,10 @@ function mapFiles(dir, root, repoFiles, packageDir, bundles, pkg) {
672
688
  const sources = repoFiles.filter((f) => /\.tsx?$/.test(f) && !f.endsWith('.d.ts'));
673
689
  const out = new Map();
674
690
  const installed = listFiles(dir).filter((f) => /\.m?js$/.test(f) && !f.includes(`${sep}platforms${sep}`) && !/\.(config|webpack)\.js$/.test(f));
675
- // Pure-JavaScript package (no TypeScript source in package or checkout): compile installed ES modules directly.
691
+ // Pure-JavaScript package (no TypeScript source in package or checkout): compile installed ES modules and non-CommonJS scripts directly.
676
692
  if (sources.length === 0) {
677
693
  for (const js of installed)
678
- out.set(js, isEsModule(js, pkg) ? js : null);
694
+ out.set(js, isEsModule(js, pkg) || !isCommonJsModule(js) ? js : null);
679
695
  return out;
680
696
  }
681
697
  const reexportTarget = (js) => {
@@ -758,7 +774,23 @@ function mapFiles(dir, root, repoFiles, packageDir, bundles, pkg) {
758
774
  for (const ext of ['.ts', '.tsx'])
759
775
  src ??= bySuffix(base + ext);
760
776
  }
777
+ // Monorepo re-bundled sibling workspace folder (e.g. `dist/scales/point.js` -> `packages/charts-scales/src/point.ts`).
778
+ const parts = stripped.split(sep);
779
+ if (!src && parts.length >= 2) {
780
+ const [seg, ...rest] = parts;
781
+ const tail = join('src', ...rest);
782
+ for (const ext of ['.ts', '.tsx']) {
783
+ const hits = sources.filter((f) => f.endsWith(`-${seg}${sep}${tail}${ext}`) || f.endsWith(`${sep}${seg}${sep}${tail}${ext}`));
784
+ if (hits.length === 1) {
785
+ src = hits[0];
786
+ break;
787
+ }
788
+ }
789
+ }
761
790
  }
791
+ // Unmapped standalone ES module in a directory without source maps (e.g. a monorepo package re-exporting sibling workspace files into `dist/`) or pure-JS script in a repo with no TypeScript sources: compile the installed JS directly.
792
+ if (!src && !bundles.has(js) && !existsSync(js + '.map') && ((isEsModule(js, pkg) && !installed.some((f) => dirname(f) === dirname(js) && existsSync(f + '.map'))) || (!sources.length && !isCommonJsModule(js))))
793
+ src = js;
762
794
  resolved.set(js, src);
763
795
  return src;
764
796
  };
@@ -953,7 +985,7 @@ function normalize(text, file, jsReference) {
953
985
  const tsf = ts.createSourceFile(file, text, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);
954
986
  const drops = [];
955
987
  for (const st of tsf.statements) {
956
- if (ts.isEnumDeclaration(st) && st.modifiers?.some((m) => m.kind === ts.SyntaxKind.ConstKeyword) && !new RegExp(`\\b${st.name.text}\\b`).test(jsReference)) {
988
+ if (ts.isEnumDeclaration(st) && st.modifiers?.some((m) => m.kind === ts.SyntaxKind.ConstKeyword) && !new RegExp(`\\b(?:var|let|const)\\s+${st.name.text}\\b`).test(jsReference)) {
957
989
  drops.push({ start: st.getStart(tsf), end: st.end });
958
990
  }
959
991
  }
@@ -990,7 +1022,7 @@ function normalize(text, file, jsReference) {
990
1022
  const trimmed = line.trim();
991
1023
  if (!trimmed)
992
1024
  continue;
993
- if (outLines.length && ((!/[;{}]$/.test(outLines[outLines.length - 1]) && !/^(?:case |default:)/.test(outLines[outLines.length - 1]) && !/^[{}]/.test(trimmed)) || (/^\}\s*$/.test(outLines[outLines.length - 1]) && /^:\s*\{$/.test(trimmed)))) {
1025
+ if (outLines.length && ((!/[;{}]$/.test(outLines[outLines.length - 1]) && !/^(?:case |default:)/.test(outLines[outLines.length - 1]) && !/^[{}]/.test(trimmed)) || (/^\}\s*$/.test(outLines[outLines.length - 1]) && /^:\s*\{$/.test(trimmed)) || /^:\s+/.test(trimmed) || /^\]/.test(trimmed))) {
994
1026
  outLines[outLines.length - 1] += (trimmed.startsWith('.') ? '' : ' ') + trimmed;
995
1027
  }
996
1028
  else {
@@ -999,24 +1031,33 @@ function normalize(text, file, jsReference) {
999
1031
  }
1000
1032
  return outLines.join('\n');
1001
1033
  };
1002
- // Decorator metadata (`__metadata("design:paramtypes", [])`), which a build with emitDecoratorMetadata adds.
1034
+ // Decorator metadata (`__metadata("design:paramtypes", [])`), which a build with emitDecoratorMetadata adds,
1035
+ // plus SWC arrow-parameter destructuring (`(acc, param) => { let [k, v] = param; ... }`).
1003
1036
  const printed = kept
1004
1037
  .map(singleLine)
1005
1038
  .join('\n')
1006
- .replace(/,?\s*(?:\b(?:tslib_\d+|tslib)\.)?__metadata\("design:\w+",\s*(?:\[[^\]]*\]|[\w.$]+|void 0)\)/g, '');
1039
+ .replace(/,?\s*(?:\b(?:tslib_\d+|tslib)\.)?__metadata\("design:\w+",\s*(?:\[[^\]]*\]|[\w.$]+|void 0)\)/g, '')
1040
+ .replace(/\(([^()]*,\s*)?param\)\s*=>\s*\{\n(?:let|var|const)\s+(\[[^\]]+\])\s*=\s*param;\nreturn\s+([^\n]+);\n\}/g, '($1$2) => $3')
1041
+ .replace(/\(([^()]*,\s*)?param\)\s*=>\s*\{\n(?:let|var|const)\s+(\[[^\]]+\])\s*=\s*param;\n/g, '($1$2) => {\n')
1042
+ .replace(/=>\s*\{\s*(?:var\s+(?:_[a-zA-Z0-9_]+,\s*)*_[a-zA-Z0-9_]+;\s*)?return\s+([^;\n]+);\s*\}/g, '=> {\nreturn $1;\n}')
1043
+ .replace(/\{\n\}/g, '{}')
1044
+ .replace(/^\}\s*([\]):,])/gm, '}\n$1');
1007
1045
  return printed
1008
1046
  .split('\n')
1009
1047
  .map((l) => l
1010
1048
  .trim()
1011
1049
  .replace(/\b(tslib_\d+|tslib)\.(__\w+)/g, '$2')
1012
1050
  .replace(/\bvoid 0\b/g, 'undefined')
1051
+ .replace(/"(?:\\.|[^"\\])*"|'((?:\\.|[^'\\])*)'/g, (m, sq) => (sq !== undefined && !sq.includes('"') && !sq.includes('\\') ? `"${sq}"` : m))
1013
1052
  .replace(/\b0[xX][0-9a-fA-F]+\b/g, (h) => String(parseInt(h, 16)))
1014
1053
  .replace(/\b\d+(?:\.\d+)?[eE][+-]?\d+\b/g, (n) => String(Number(n)))
1015
1054
  .replace(/,\s*([}\]])/g, ' $1')
1055
+ .replace(/\s+([}\]])/g, '$1')
1016
1056
  .replace(/,$/, '')
1017
1057
  .replace(/^var ([A-Za-z_$][\w$]*) = \(\(\1\d*\) => \{$/, '(function ($1) {')
1018
- .replace(/^\}\)\(([A-Za-z_$][\w$]*) \|\| \{\}\);$/, '})($1 || ($1 = {}));'))
1019
- .filter((l) => l && !l.startsWith('//# sourceMappingURL') && l !== 'export {};' && l !== '"use strict";' && l !== "'use strict';" && !/^var (?:_[a-z],\s*)*_[a-z];$/.test(l));
1058
+ .replace(/^\}\)\(([A-Za-z_$][\w$]*) \|\| \{\}\);$/, '})($1 || ($1 = {}));')
1059
+ .replace(/^\)\(([A-Za-z_$][\w$]*) \|\| \{\}\);$/, ')($1 || ($1 = {}));'))
1060
+ .filter((l) => l && !l.startsWith('//# sourceMappingURL') && l !== 'export {};' && l !== '"use strict";' && l !== "'use strict';" && !/^var (?:_[a-zA-Z0-9_]+,\s*)*_[a-zA-Z0-9_]+;$/.test(l));
1020
1061
  }
1021
1062
  /** Lines of a diff between the source's output `a` and the published `b` that no benign difference explains. */
1022
1063
  function unexplained(a, b) {
@@ -1024,20 +1065,27 @@ function unexplained(a, b) {
1024
1065
  const bad = [];
1025
1066
  // Inlined enum members and emitter temp aliases (`_a`, `_b`): a line whose only difference is `E.Member` against a literal or `_a` vs `_b`.
1026
1067
  const shape = (l) => l
1027
- .replace(/^export\s+(?=(?:async\s+|function|class|const|let|var)\s+)/, '')
1068
+ .replace(/^export\s+(?=(?:async\s+)?(?:function|class|const|let|var)\s+)/, '')
1028
1069
  .replace(/^__exportStar\(require\(([^)]+)\),\s*exports\);$/, '__export(require($1));')
1029
1070
  .replace(/^\}\)\((\w+)\s*\|\|\s*\(exports\.\1\s*=\s*\1\s*=\s*\{\}\)\);$/, '})($1 = exports.$1 || (exports.$1 = {}));')
1071
+ .replace(/^\}\s*([\]):,])/, '$1')
1030
1072
  .replace(/\(([A-Za-z_$][\w$]*)\)\s*=>/g, '$1 =>')
1031
- .replace(/(?<=^|[{,\s])([A-Za-z_$][\w$]*)\s*:\s*\1(?=\s*[,}]|$)/g, '$1')
1073
+ .replace(/(?<=^|[{,\s])([A-Za-z_$][\w$]*)\s*:\s*\1\d*(?=\s*[,}]|$)/g, '$1')
1032
1074
  .replace(/^(?:const|let)\s+\{\s*(\w+)\s*\}\s*=\s*(\w+);$/, 'var $1 = $2.$1;')
1033
1075
  .replace(/(?:^|(?<=for\s*\(\s*))(?:const|let)\s+/, 'var ')
1034
- .replace(/`[^`]*`|"[^"]*"\.concat\([^)]*\)/g, '"#"')
1035
- .replace(/\s*\{\s*$/, '')
1076
+ .replace(/"[^"]*"|'[^']*'|`[^`]*`/g, '"#"')
1077
+ .replace(/"#"(?:\s*\+\s*"#")+/g, '"#"')
1078
+ .replace(/"#"\.concat\([^)]*\)/g, '"#"')
1079
+ .replace(/\s*\{\s*\}?\s*$/, '')
1080
+ .replace(/var\s+(_[a-z])\s*=\s*([A-Za-z_$][\w$.]*),\s*(\{[^}]+\})\s*=\s*\1,\s*([A-Za-z_$][\w$]*)\s*=\s*__rest\(\1,/g, 'var $3 = $2, $4 = __rest($2,')
1081
+ .replace(/\((_[a-z])\s*=\s*\((_[a-z])\s*=\s*([A-Za-z_$][\w$.]*)\)\.([A-Za-z_$][\w$]*)\)\s*===\s*null\s*\|\|\s*\1\s*===\s*undefined\s*\?\s*undefined\s*:\s*\1\.call\(\2/g, '(_a = $3.$4) === null || _a === undefined ? undefined : _a.call($3')
1082
+ .replace(/\((_[a-zA-Z0-9_]+)\s*=\s*([^()]+?)\s*===\s*null\s*\|\|\s*\2\s*===\s*undefined\s*\?\s*undefined\s*:\s*([^()]+?)\)\s*===\s*null\s*\|\|\s*\1\s*===\s*undefined\s*\?\s*undefined\s*:\s*\1\./g, '$3?.')
1083
+ .replace(/([A-Za-z_$][\w$.]*)\s*===\s*null\s*\|\|\s*\1\s*===\s*undefined\s*\?\s*undefined\s*:\s*\((_[a-zA-Z0-9_]+)\s*=\s*([^()]+?)\)\s*===\s*null\s*\|\|\s*\2\s*===\s*undefined\s*\?\s*undefined\s*:\s*\2\./g, '$3?.')
1036
1084
  .replace(/\((_[a-z])\s*=\s*([A-Za-z_$][\w$]*)\)\s*!==\s*null\s*&&\s*\1\s*!==\s*undefined\s*\?\s*\1\s*:/g, '$2 !== null && $2 !== undefined ? $2 :')
1037
- .replace(/\b_[a-z]\b/g, '_a')
1038
- .replace(/\b[A-Za-z_$][\w$]*(\.[A-Za-z_$][\w$]*)+\b|-?\b\d+(\.\d+)?\b|"[^"]*"|'[^']*'/g, '#');
1085
+ .replace(/\b(?:_[a-z]|param)\b/g, '_a')
1086
+ .replace(/\b[A-Za-z_$][\w$]*(\.[A-Za-z_$][\w$]*)+\b|-?\b\d+(\.\d+)?\b/g, '#');
1039
1087
  const stripParens = (s) => s.replace(/[()]/g, '').replace(/\s+/g, ' ').trim();
1040
- const stripShadowSuffix = (s) => s.replace(/\b([A-Za-z$](?:[A-Za-z_$]*[A-Za-z$])?)\d+(_\d+)?\b/g, '$1$2');
1088
+ const stripShadowSuffix = (s) => s.replace(/\b([A-Za-z_$](?:[A-Za-z0-9_$]*[A-Za-z_$])?)\d+(_\d+)?\b/g, '$1$2');
1041
1089
  const isImportOrReexport = (l) => /^(?:import\b|export\s+(?:\*|\{))/.test(l);
1042
1090
  for (let i = 0; i < ops.length;) {
1043
1091
  if (ops[i].op === '=') {
@@ -1050,11 +1098,13 @@ function unexplained(a, b) {
1050
1098
  i++;
1051
1099
  }
1052
1100
  const filteredDel = del.filter((l) => l !== '}' && !/^export var [A-Za-z_$][\w$]*;$/.test(l) && !isImportOrReexport(l));
1053
- const filteredAdd = add.filter((l) => l !== '}' && !isImportOrReexport(l) && !/^return [A-Za-z_$][A-Za-z_$]*\d+;$/.test(l));
1101
+ const filteredAdd = add.filter((l) => l !== '}' && !isImportOrReexport(l));
1054
1102
  for (let k = 0; k < Math.max(filteredDel.length, filteredAdd.length); k++) {
1055
1103
  const x = filteredDel[k], y = filteredAdd[k];
1056
1104
  if (x !== undefined && y !== undefined && (shape(x) === shape(y) || stripShadowSuffix(stripParens(shape(x))) === stripShadowSuffix(stripParens(shape(y)))))
1057
1105
  continue;
1106
+ if (x === undefined && y !== undefined && /^return [A-Za-z_$][A-Za-z_$]*\d+;$/.test(y))
1107
+ continue;
1058
1108
  // Imports and re-exports a whole-program build elides as type-only, or esbuild/rollup rewrites (`export { x } from './y'` -> `import { x as x2 } from './y'`).
1059
1109
  if (x !== undefined && y === undefined && /^(import|export) \{?/.test(x) && !/^export (default |const |let |var |function |class |async )/.test(x))
1060
1110
  continue;
@@ -1,30 +1,105 @@
1
1
  import ts from 'typescript';
2
- import { existsSync, readFileSync } from 'node:fs';
2
+ import { existsSync, readFileSync, statSync } from 'node:fs';
3
3
  import { dirname, join, relative, resolve } from 'node:path';
4
+ import { globMatchedFiles } from "./glob.js";
4
5
  /**
5
- * The imports among `files`: relative specifiers and those the app's tsconfig `paths` alias (`aliased`), each completed
6
- * as the bundler does, the platform's own file (`thisPlatform`, `.ios.ts`) beside the shared one.
6
+ * The imports among `files`: relative specifiers and those the app's tsconfig `paths` / Vite config alias (`aliased`),
7
+ * each completed as the bundler does, the platform's own file (`thisPlatform`, `.ios.ts`) beside the shared one.
8
+ * Local monorepo workspace TypeScript sources outside `files` (and outside `node_modules`) are discovered transitively.
7
9
  */
8
- export function appImports(files, aliased, thisPlatform) {
9
- const out = { importsOf: new Map(), usedBy: new Map(), workerScripts: new Set() };
10
+ export function appImports(files, aliased, thisPlatform, appRoot = null, readSource = (f) => readFileSync(f, 'utf8')) {
11
+ const out = { importsOf: new Map(), usedBy: new Map(), workerScripts: new Set(), discovered: [] };
10
12
  const known = new Set(files);
11
- for (const f of files.filter((x) => /\.tsx?$/.test(x) && !x.endsWith('.d.ts'))) {
12
- const text = readFileSync(f, 'utf8');
13
- for (const m of text.matchAll(/(?:\bfrom\s*|\bimport\s*\(\s*|\bimport\s+|(new\s+Worker\s*\(\s*(?:new\s+URL\s*\(\s*)?)|\brequire\s*\(\s*)['"]([^'"\s]+)['"]/g)) {
14
- const target = m[2].startsWith('.') ? resolve(dirname(f), m[2]) : aliased(m[2]);
15
- if (!target)
13
+ const otherPlatform = thisPlatform === '.android.ts' ? /\.ios\.tsx?$/ : /\.android\.tsx?$/;
14
+ const isFile = (p) => existsSync(p) && statSync(p).isFile();
15
+ const queue = files.filter((x) => /\.tsx?$/.test(x) && !x.endsWith('.d.ts'));
16
+ const seen = new Set();
17
+ const link = (from, to, worker) => {
18
+ if (worker)
19
+ out.workerScripts.add(to);
20
+ else
21
+ out.usedBy.set(to, (out.usedBy.get(to) ?? new Set()).add(from));
22
+ out.importsOf.set(from, (out.importsOf.get(from) ?? new Set()).add(to));
23
+ };
24
+ const discover = (c) => {
25
+ if (known.has(c) || c.endsWith('.d.ts') || otherPlatform.test(c) || /[\\/]node_modules[\\/]/.test(c))
26
+ return false;
27
+ if (!/\.tsx?$/.test(c) || !isFile(c))
28
+ return false;
29
+ known.add(c);
30
+ out.discovered.push(c);
31
+ queue.push(c);
32
+ return true;
33
+ };
34
+ for (let i = 0; i < queue.length; i++) {
35
+ const f = queue[i];
36
+ if (seen.has(f))
37
+ continue;
38
+ seen.add(f);
39
+ const text = readSource(f);
40
+ const sf = ts.createSourceFile(f, text, ts.ScriptTarget.Latest, false);
41
+ const specs = [];
42
+ const visitSpec = (n) => {
43
+ if (ts.isImportDeclaration(n) && ts.isStringLiteralLike(n.moduleSpecifier)) {
44
+ const clause = n.importClause;
45
+ const allTypeOnly = !!clause?.isTypeOnly ||
46
+ (!!clause && !clause.name && !!clause.namedBindings && ts.isNamedImports(clause.namedBindings) && clause.namedBindings.elements.length > 0 && clause.namedBindings.elements.every((e) => e.isTypeOnly));
47
+ if (!allTypeOnly)
48
+ specs.push({ spec: n.moduleSpecifier.text, worker: false });
49
+ return;
50
+ }
51
+ if (ts.isExportDeclaration(n) && n.moduleSpecifier && ts.isStringLiteralLike(n.moduleSpecifier)) {
52
+ const allTypeOnly = n.isTypeOnly ||
53
+ (!!n.exportClause && ts.isNamedExports(n.exportClause) && n.exportClause.elements.length > 0 && n.exportClause.elements.every((e) => e.isTypeOnly));
54
+ if (!allTypeOnly)
55
+ specs.push({ spec: n.moduleSpecifier.text, worker: false });
56
+ return;
57
+ }
58
+ if (ts.isCallExpression(n)) {
59
+ if ((n.expression.kind === ts.SyntaxKind.ImportKeyword || (ts.isIdentifier(n.expression) && n.expression.text === 'require')) && n.arguments[0] && ts.isStringLiteralLike(n.arguments[0])) {
60
+ specs.push({ spec: n.arguments[0].text, worker: false });
61
+ }
62
+ }
63
+ else if (ts.isNewExpression(n) && ts.isIdentifier(n.expression) && n.expression.text === 'Worker' && n.arguments?.[0]) {
64
+ const arg0 = n.arguments[0];
65
+ const lit = ts.isStringLiteralLike(arg0) ? arg0 : ts.isNewExpression(arg0) && ts.isIdentifier(arg0.expression) && arg0.expression.text === 'URL' && arg0.arguments?.[0] && ts.isStringLiteralLike(arg0.arguments[0]) ? arg0.arguments[0] : undefined;
66
+ if (lit)
67
+ specs.push({ spec: lit.text, worker: true });
68
+ }
69
+ ts.forEachChild(n, visitSpec);
70
+ };
71
+ visitSpec(sf);
72
+ for (const { spec, worker } of specs) {
73
+ if (spec.includes('?'))
16
74
  continue;
17
- const base = target.replace(/\.(ts|js)$/, '');
75
+ const target = spec.startsWith('.') ? resolve(dirname(f), spec) : aliased(spec, f);
76
+ if (!target || /[\\/]node_modules[\\/]/.test(target))
77
+ continue;
78
+ const base = target.replace(/\.(tsx?|m?js)$/, '');
79
+ let matched = false;
18
80
  for (const c of [base + '.ts', base + thisPlatform, base + '.tsx', base + '/index.ts', `${base}/index${thisPlatform}`]) {
19
81
  if (!known.has(c))
20
82
  continue;
21
- if (m[1])
22
- out.workerScripts.add(c);
23
- else
24
- out.usedBy.set(c, (out.usedBy.get(c) ?? new Set()).add(f));
25
- out.importsOf.set(f, (out.importsOf.get(f) ?? new Set()).add(c));
83
+ link(f, c, worker);
84
+ matched = true;
85
+ }
86
+ if (matched)
87
+ continue;
88
+ // External monorepo workspace source (not under appDir): pick the platform file when present, else the shared source.
89
+ const external = /\.tsx?$/.test(target)
90
+ ? [target.replace(/\.ts$/, thisPlatform), target]
91
+ : [base + thisPlatform, base + '.ts', base + '.tsx', `${base}/index${thisPlatform}`, base + '/index.ts', base + '/index.tsx'];
92
+ for (const c of external) {
93
+ if (discover(c)) {
94
+ link(f, c, worker);
95
+ break;
96
+ }
26
97
  }
27
98
  }
99
+ for (const c of globMatchedFiles(text, f, appRoot)) {
100
+ if (known.has(c) || discover(c))
101
+ link(f, c, false);
102
+ }
28
103
  }
29
104
  return out;
30
105
  }