@nstudio/nativescript-compiler-effect-ui 0.0.0-stage → 9.2.0-alpha.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,19 @@
1
+ Copyright OpenJS Foundation and other contributors, https://openjsf.org
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining a copy
4
+ of this software and associated documentation files (the "Software"), to deal
5
+ in the Software without restriction, including without limitation the rights
6
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7
+ copies of the Software, and to permit persons to whom the Software is
8
+ furnished to do so, subject to the following conditions:
9
+
10
+ The above copyright notice and this permission notice shall be included in
11
+ all copies or substantial portions of the Software.
12
+
13
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
19
+ THE SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,5 @@
1
- # Temporary Holding Version
1
+ # @nstudio/nativescript-compiler-effect-ui
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Effect UI (`@effect/ui` + `effect` v4) framework adapter for [`@nstudio/nativescript-compiler`](../compiler).
4
+
5
+ Compiles NativeScript apps written with Effect UI (including `MasonHost`, `NativeHost`, `@effect/ui`, `@effect/ui-kit`, and `effect` v4) directly to native Swift (iOS) and Kotlin (Android) with no JavaScript runtime.
@@ -0,0 +1,8 @@
1
+ /** The compiler's own functions and state, from the compiler that loaded the adapter: set by its entry before any front end runs. */
2
+ export let core;
3
+ /** The compiler's TypeScript (`core.ts`), set with `core`: the adapter reads and makes the compiler's syntax trees with it, never with a TypeScript of its own. */
4
+ export let ts;
5
+ export function useCore(api) {
6
+ core = api;
7
+ ts = api.ts;
8
+ }
package/dist/index.js ADDED
@@ -0,0 +1,37 @@
1
+ import { useCore } from "./core-api.js";
2
+ import { transformEffectSource } from "./transform.js";
3
+ export default function adapter(core) {
4
+ useCore(core);
5
+ return {
6
+ apiVersion: 1,
7
+ name: 'effect-ui',
8
+ // Effect and @effect/ui are pure TypeScript and compile directly from their shipped sources.
9
+ packages: [],
10
+ behaviour: {
11
+ schedule: 'now',
12
+ eventScope: 'none',
13
+ propsOrder: 'pre',
14
+ deferBindings: false,
15
+ insertion: 'built',
16
+ listenersAfterBindings: false,
17
+ effectScope: null,
18
+ checkEveryBinding: 'off',
19
+ slots: false,
20
+ rowSignals: 'off',
21
+ fragments: false,
22
+ },
23
+ reach: 'entry',
24
+ modules: {
25
+ transformSource: transformEffectSource,
26
+ },
27
+ frontEnd(app) {
28
+ // Pure TypeScript app: the entry calls Application.run / MasonHost.run / NativeHost.run directly.
29
+ return {
30
+ components: [],
31
+ modules: [...app.sources, app.entry],
32
+ root: '',
33
+ mounted: true,
34
+ };
35
+ },
36
+ };
37
+ }
@@ -0,0 +1,581 @@
1
+ import { ts } from "./core-api.js";
2
+ function applyEdits(text, edits) {
3
+ if (!edits.length)
4
+ return text;
5
+ let out = text;
6
+ for (const e of [...edits].sort((a, b) => b.start - a.start)) {
7
+ out = out.slice(0, e.start) + e.text + out.slice(e.end);
8
+ }
9
+ return out;
10
+ }
11
+ function preserveLines(orig, replacement) {
12
+ const origLines = (orig.match(/\n/g) ?? []).length;
13
+ const newLines = (replacement.match(/\n/g) ?? []).length;
14
+ return replacement + (origLines > newLines ? '\n'.repeat(origLines - newLines) : '');
15
+ }
16
+ /**
17
+ * Lowers Effect v4 and `@effect/ui` TypeScript idioms into static forms that
18
+ * `@nstudio/nativescript-compiler`'s Swift and Kotlin backends compile directly:
19
+ *
20
+ * 1. `class Foo extends (Context|Command|Query).Service<...>()(...) { static ... }`
21
+ * -> nominal `interface Foo` + `const Foo = ...` singleton with static members attached.
22
+ * 2. `class Foo extends (Data.)?TaggedError("Tag")<Fields>` and
23
+ * `class Foo extends (Data.)?TaggedClass("Tag")<Fields>`
24
+ * -> concrete subclasses of `Data.Error` / `Data.Class` with typed stored fields.
25
+ * 3. Effect & `@effect/ui` library internals that rely on dynamic JS-engine idioms
26
+ * (`Pipeable.Class` / `YieldableError` IIFEs, `Function.dual` `arguments`,
27
+ * `Reflect.ownKeys` / `Reflect.get`, `SharedArrayBuffer` guards, local service
28
+ * subclasses inside factories, `new Array(n)` untyped slots).
29
+ */
30
+ export function transformEffectSource(code, fileName) {
31
+ const norm = fileName.replace(/\\/g, '/');
32
+ let out = code;
33
+ if (norm.includes('/effect/src/'))
34
+ out = transformEffectLib(out, norm);
35
+ else if (norm.includes('/@effect/ui/src/'))
36
+ out = transformEffectUiLib(out, norm);
37
+ else if (norm.includes('/nativescript-masonkit/')) {
38
+ if (out.includes('NativeScript.Mason')) {
39
+ // Windows-only dead code inside shared masonkit common.ts (`_windowsCreateAnonymousText`, `windowsBreakRun`)
40
+ out = out.replace(/\bnew NativeScript\.Mason\.\w+\([^)]*\)/g, '(undefined as any)').replace(/\bNativeScript\.Mason\.\w+/g, 'any');
41
+ }
42
+ if (norm.endsWith('/nativescript-masonkit/common.ts') && out.includes('setMeasureForViewBlock')) {
43
+ // `objc!Mason.d.ts` omits `setMeasureForViewBlock` even though `Mason.swiftinterface` exports `@objc(setMeasureForView:block:)`;
44
+ // typing `mason` as `NSCMason` lets Swift emit a direct typed ObjC-block call instead of dynamic `objc_msgSend`.
45
+ out =
46
+ `declare global { interface NSCMason { setMeasureForViewBlock(view: any, block: (knownW: number, knownH: number, availW: number, availH: number) => any): void; } }\n` +
47
+ out.replace(/const mason = native\?\.mason \?\? native\?\.node\?\.mason;\s*if \(typeof mason\?\.setMeasureForViewBlock !== 'function'\) return;/, 'const mason = (native?.mason ?? native?.node?.mason) as NSCMason | undefined;\n if (!mason) return;');
48
+ }
49
+ if (norm.endsWith('/nativescript-masonkit/style.ts')) {
50
+ out = out
51
+ .replace(/private view_: View;/, 'private view_: any;')
52
+ .replace(/static fromView\(view: View, nativeView\)/, 'static fromView(view: any, nativeView)')
53
+ .replace(/static fromPseudo\(pseudo: string, view: View, nativeView\)/, 'static fromPseudo(pseudo: string, view: any, nativeView)')
54
+ .replace(/get view\(\): View \{/, 'get view(): any {')
55
+ .replace(/\{\s*\.\.\.coreLayout,\s*\.\.\.masonLayout\s*\}/, '{ toDevicePixels: coreLayout.toDevicePixels, toDeviceIndependentPixels: coreLayout.toDeviceIndependentPixels, getDisplayDensity: coreLayout.getDisplayDensity, makeMeasureSpec: coreLayout.makeMeasureSpec, getMeasureSpecMode: coreLayout.getMeasureSpecMode, getMeasureSpecSize: coreLayout.getMeasureSpecSize, round: coreLayout.round, ...masonLayout }');
56
+ }
57
+ }
58
+ else if (norm.includes('/nativescript-effect-ui/')) {
59
+ if (out.includes("import('@nativescript/core')")) {
60
+ out =
61
+ `import { Application, Utils } from '@nativescript/core';\n` +
62
+ out
63
+ .replace(/void import\('@nativescript\/core'\)\.then\(\(\{\s*Application,\s*Utils\s*\}\)\s*=>\s*\{/g, 'void Promise.resolve().then(() => {')
64
+ .replace(/const\s*\{\s*Application,\s*Utils\s*\}\s*=\s*yield\*\s*Effect\.promise\(\(\)\s*=>\s*import\('@nativescript\/core'\)\);/g, '')
65
+ .replace(/import\('@nativescript\/core'\)/g, 'Promise.resolve({ Application, Utils })');
66
+ }
67
+ if (norm.endsWith('/native/Native.ts')) {
68
+ out = out.replace(/Record<string,\s*NativeElement<any,\s*any,\s*any,\s*any,\s*any>>/g, 'Record<string, any>');
69
+ }
70
+ }
71
+ if (/\bclass\b/.test(out)) {
72
+ out = transformEffectClasses(out, fileName);
73
+ }
74
+ return out;
75
+ }
76
+ /** Rewrites `this` and value references to `className` inside a static initializer/method to `selfName`. */
77
+ function rewriteStaticSelf(exprText, className, selfName, rewriteThis) {
78
+ const sf = ts.createSourceFile('__expr.ts', `const __e = (${exprText});`, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);
79
+ const offset = 'const __e = ('.length;
80
+ const edits = [];
81
+ const isTypePosition = (n) => {
82
+ for (let p = n.parent; p; p = p.parent) {
83
+ if (ts.isTypeNode(p) || ts.isTypeParameterDeclaration(p))
84
+ return true;
85
+ if (ts.isExpressionWithTypeArguments(p) && p.expression === n)
86
+ return false;
87
+ }
88
+ return false;
89
+ };
90
+ const isPropertyName = (id) => {
91
+ const p = id.parent;
92
+ if (!p)
93
+ return false;
94
+ if (ts.isPropertyAccessExpression(p) && p.name === id)
95
+ return true;
96
+ if ((ts.isPropertyAssignment(p) || ts.isPropertyDeclaration(p) || ts.isMethodDeclaration(p) || ts.isGetAccessorDeclaration(p) || ts.isSetAccessorDeclaration(p)) && p.name === id)
97
+ return true;
98
+ if ((ts.isVariableDeclaration(p) || ts.isParameter(p) || ts.isFunctionDeclaration(p) || ts.isClassDeclaration(p) || ts.isBindingElement(p)) && p.name === id)
99
+ return true;
100
+ return false;
101
+ };
102
+ const visit = (n, nestedFn) => {
103
+ if (rewriteThis && !nestedFn && n.kind === ts.SyntaxKind.ThisKeyword) {
104
+ edits.push({ start: n.getStart(sf) - offset, end: n.getEnd() - offset, text: selfName });
105
+ return;
106
+ }
107
+ if (ts.isIdentifier(n) && n.text === className && !isPropertyName(n) && !isTypePosition(n)) {
108
+ if (ts.isShorthandPropertyAssignment(n.parent) && n.parent.name === n) {
109
+ edits.push({ start: n.getStart(sf) - offset, end: n.getEnd() - offset, text: `${className}: ${selfName}` });
110
+ }
111
+ else {
112
+ edits.push({ start: n.getStart(sf) - offset, end: n.getEnd() - offset, text: selfName });
113
+ }
114
+ return;
115
+ }
116
+ const nextNested = nestedFn || ts.isFunctionExpression(n) || ts.isFunctionDeclaration(n) || ts.isClassLike(n) || ts.isMethodDeclaration(n);
117
+ ts.forEachChild(n, (c) => visit(c, nextNested));
118
+ };
119
+ visit(sf, false);
120
+ return applyEdits(exprText, edits);
121
+ }
122
+ /** Recognizes `Context.Service<...>()(...)`, `Command.Service<...>()(...)`, `Query.Service<...>()(...)`. */
123
+ function isEffectServiceBase(expr) {
124
+ if (!ts.isCallExpression(expr))
125
+ return false;
126
+ const inner = expr.expression;
127
+ if (!ts.isCallExpression(inner))
128
+ return false;
129
+ const callee = inner.expression;
130
+ if (ts.isPropertyAccessExpression(callee) && callee.name.text === 'Service' && ts.isIdentifier(callee.expression)) {
131
+ return ['Context', 'Command', 'Query'].includes(callee.expression.text);
132
+ }
133
+ return false;
134
+ }
135
+ /** Recognizes `(Data.)?TaggedError("Tag")` or `(Data.)?TaggedClass("Tag")` in a class `extends` clause. */
136
+ function matchTaggedBase(heritage, _sf) {
137
+ const expr = heritage.expression;
138
+ if (!ts.isCallExpression(expr) || expr.arguments.length !== 1 || !ts.isStringLiteralLike(expr.arguments[0]))
139
+ return null;
140
+ const tag = expr.arguments[0].text;
141
+ const callee = expr.expression;
142
+ let prefix = '';
143
+ let fnName = '';
144
+ if (ts.isIdentifier(callee)) {
145
+ fnName = callee.text;
146
+ }
147
+ else if (ts.isPropertyAccessExpression(callee) && ts.isIdentifier(callee.expression)) {
148
+ prefix = `${callee.expression.text}.`;
149
+ fnName = callee.name.text;
150
+ }
151
+ if (fnName !== 'TaggedError' && fnName !== 'TaggedClass')
152
+ return null;
153
+ const fieldsNode = heritage.typeArguments?.[0];
154
+ return { kind: fnName === 'TaggedError' ? 'error' : 'class', prefix, tag, fieldsNode };
155
+ }
156
+ function extractLiteralFields(typeNode, sf) {
157
+ if (!typeNode || !ts.isTypeLiteralNode(typeNode))
158
+ return [];
159
+ const out = [];
160
+ for (const m of typeNode.members) {
161
+ if (!ts.isPropertySignature(m) || !(ts.isIdentifier(m.name) || ts.isStringLiteral(m.name)))
162
+ continue;
163
+ const name = m.name.text;
164
+ if (name === '_tag')
165
+ continue;
166
+ out.push({ name, optional: !!m.questionToken, typeText: m.type ? m.type.getText(sf) : 'any' });
167
+ }
168
+ return out;
169
+ }
170
+ function transformEffectClasses(code, fileName) {
171
+ const sf = ts.createSourceFile(fileName, code, ts.ScriptTarget.Latest, true, fileName.endsWith('x') ? ts.ScriptKind.TSX : ts.ScriptKind.TS);
172
+ const edits = [];
173
+ const extraImports = [];
174
+ const importedFrom = (symbolName) => {
175
+ for (const s of sf.statements) {
176
+ if (!ts.isImportDeclaration(s) || !ts.isStringLiteral(s.moduleSpecifier))
177
+ continue;
178
+ const bindings = s.importClause?.namedBindings;
179
+ if (bindings && ts.isNamedImports(bindings)) {
180
+ for (const el of bindings.elements) {
181
+ if (el.name.text === symbolName)
182
+ return s.moduleSpecifier.text;
183
+ }
184
+ }
185
+ }
186
+ return 'effect/Data';
187
+ };
188
+ const addedImports = new Set();
189
+ const ensureBaseImport = (kind) => {
190
+ const alias = kind === 'error' ? '__EffectDataError' : '__EffectDataClass';
191
+ const exportName = kind === 'error' ? 'Error' : 'Class';
192
+ const fromSpec = importedFrom(kind === 'error' ? 'TaggedError' : 'TaggedClass');
193
+ const key = `${exportName}:${fromSpec}`;
194
+ if (!addedImports.has(key)) {
195
+ addedImports.add(key);
196
+ extraImports.push(`import { ${exportName} as ${alias} } from ${JSON.stringify(fromSpec)};`);
197
+ }
198
+ return alias;
199
+ };
200
+ const interfacesInFile = new Set();
201
+ for (const st of sf.statements) {
202
+ if (ts.isInterfaceDeclaration(st))
203
+ interfacesInFile.add(st.name.text);
204
+ }
205
+ for (const st of sf.statements) {
206
+ // 0. `export const Foo: new(...) => Foo = class [extends Base] { ... }` paired with `export interface Foo` -> `export class Foo [extends Base] { ... }`
207
+ if (ts.isVariableStatement(st) && st.declarationList.declarations.length === 1) {
208
+ const decl = st.declarationList.declarations[0];
209
+ if (ts.isIdentifier(decl.name) && interfacesInFile.has(decl.name.text) && decl.type && ts.isConstructorTypeNode(decl.type) && decl.initializer) {
210
+ let initExpr = decl.initializer;
211
+ while (ts.isAsExpression(initExpr) || ts.isParenthesizedExpression(initExpr))
212
+ initExpr = initExpr.expression;
213
+ if (ts.isClassExpression(initExpr)) {
214
+ const exported = !!ts.getModifiers(st)?.some((m) => m.kind === ts.SyntaxKind.ExportKeyword);
215
+ const expPrefix = exported ? 'export ' : '';
216
+ const clsName = decl.name.text;
217
+ const orig = code.slice(st.getStart(sf), st.getEnd());
218
+ const ext = initExpr.heritageClauses?.map((h) => h.getText(sf)).join(' ');
219
+ const bodyStart = code.indexOf('{', initExpr.getStart(sf));
220
+ const bodyText = code.slice(bodyStart, initExpr.getEnd());
221
+ const rep = `${expPrefix}class ${clsName}${ext ? ` ${ext}` : ''} ${bodyText}`;
222
+ edits.push({ start: st.getStart(sf), end: st.getEnd(), text: preserveLines(orig, rep) });
223
+ continue;
224
+ }
225
+ }
226
+ }
227
+ if (!ts.isClassDeclaration(st) || !st.name)
228
+ continue;
229
+ const ext = st.heritageClauses?.find((h) => h.token === ts.SyntaxKind.ExtendsKeyword)?.types[0];
230
+ if (!ext)
231
+ continue;
232
+ const className = st.name.text;
233
+ const exported = !!ts.getModifiers(st)?.some((m) => m.kind === ts.SyntaxKind.ExportKeyword);
234
+ const expPrefix = exported ? 'export ' : '';
235
+ const orig = code.slice(st.getStart(sf), st.getEnd());
236
+ // 1. Service classes (`Context.Service` / `Command.Service` / `Query.Service`)
237
+ if (isEffectServiceBase(ext.expression)) {
238
+ const hasInstance = st.members.some((m) => ts.isConstructorDeclaration(m) || !ts.canHaveModifiers(m) || !ts.getModifiers(m)?.some((mod) => mod.kind === ts.SyntaxKind.StaticKeyword));
239
+ if (hasInstance)
240
+ continue;
241
+ const baseExprText = ext.expression.getText(sf);
242
+ if (st.members.length === 0) {
243
+ const rep = `${expPrefix}interface ${className} { readonly __nsEffectServiceBrand?: ${JSON.stringify(className)} }\n${expPrefix}const ${className} = ${baseExprText};`;
244
+ edits.push({ start: st.getStart(sf), end: st.getEnd(), text: preserveLines(orig, rep) });
245
+ continue;
246
+ }
247
+ const methodEntries = [];
248
+ const fieldInits = [];
249
+ const fieldEntries = [];
250
+ let fieldIdx = 0;
251
+ for (const m of st.members) {
252
+ if (ts.isMethodDeclaration(m) && m.name) {
253
+ const nameText = m.name.getText(sf);
254
+ const params = m.parameters.map((p) => p.getText(sf)).join(', ');
255
+ const tparams = m.typeParameters ? `<${m.typeParameters.map((tp) => tp.getText(sf)).join(', ')}>` : '';
256
+ const ret = m.type ? `: ${m.type.getText(sf)}` : '';
257
+ const body = m.body ? rewriteStaticSelf(m.body.getText(sf), className, '__self', false) : '{}';
258
+ methodEntries.push(`${nameText}${tparams}(${params})${ret} ${body}`);
259
+ }
260
+ else if (ts.isGetAccessorDeclaration(m) && m.name) {
261
+ const nameText = m.name.getText(sf);
262
+ const ret = m.type ? `: ${m.type.getText(sf)}` : '';
263
+ const body = m.body ? rewriteStaticSelf(m.body.getText(sf), className, '__self', false) : '{}';
264
+ methodEntries.push(`get ${nameText}()${ret} ${body}`);
265
+ }
266
+ else if (ts.isPropertyDeclaration(m) && m.name) {
267
+ const nameText = m.name.getText(sf);
268
+ const varName = `__f${fieldIdx++}`;
269
+ const typeAnn = m.type ? `: ${m.type.getText(sf)}` : '';
270
+ const initText = m.initializer ? rewriteStaticSelf(m.initializer.getText(sf), className, '__self', true) : 'undefined';
271
+ fieldInits.push(`const ${varName}${typeAnn} = ${initText};`);
272
+ fieldEntries.push(`${nameText}: ${varName}`);
273
+ }
274
+ }
275
+ const parts = [
276
+ `${expPrefix}interface ${className} { readonly __nsEffectServiceBrand?: ${JSON.stringify(className)} }`,
277
+ `${expPrefix}const ${className} = (() => {`,
278
+ ` const __base = ${baseExprText};`,
279
+ methodEntries.length ? ` const __self = Object.assign(__base, { ${methodEntries.join(', ')} });` : ` const __self = __base;`,
280
+ ...fieldInits.map((l) => ` ${l}`),
281
+ fieldEntries.length ? ` return Object.assign(__self, { ${fieldEntries.join(', ')} });` : ` return __self;`,
282
+ `})();`,
283
+ ];
284
+ edits.push({ start: st.getStart(sf), end: st.getEnd(), text: preserveLines(orig, parts.join('\n')) });
285
+ continue;
286
+ }
287
+ // 2. TaggedError / TaggedClass subclasses
288
+ const tagged = matchTaggedBase(ext, sf);
289
+ if (tagged) {
290
+ const baseCtor = tagged.prefix ? `${tagged.prefix}${tagged.kind === 'error' ? 'Error' : 'Class'}` : ensureBaseImport(tagged.kind);
291
+ const fields = extractLiteralFields(tagged.fieldsNode, sf);
292
+ const hasCtor = st.members.some(ts.isConstructorDeclaration);
293
+ const existingFields = new Set(st.members
294
+ .filter((m) => ts.isPropertyDeclaration(m) && (ts.isIdentifier(m.name) || ts.isStringLiteral(m.name)))
295
+ .map((m) => (ts.isIdentifier(m.name) ? m.name.text : m.name.getText(sf).slice(1, -1))));
296
+ const declLines = [` readonly _tag = ${JSON.stringify(tagged.tag)} as const;`];
297
+ if (tagged.kind === 'error')
298
+ declLines.push(` override name = ${JSON.stringify(tagged.tag)};`);
299
+ for (const f of fields) {
300
+ if (existingFields.has(f.name))
301
+ continue;
302
+ declLines.push(` readonly ${f.name}${f.optional ? '?' : '!'}: ${f.typeText};`);
303
+ }
304
+ if (!hasCtor && fields.length > 0) {
305
+ const argType = tagged.fieldsNode.getText(sf);
306
+ const assigns = fields.map((f) => ` (this as any).${f.name} = (args as any).${f.name};`).join('\n');
307
+ declLines.push(` constructor(args: ${argType}) {\n super(args as any);\n if (args) {\n${assigns}\n }\n }`);
308
+ }
309
+ else if (!hasCtor) {
310
+ declLines.push(` constructor(args?: any) { super(args); }`);
311
+ }
312
+ const bodyStart = code.indexOf('{', ext.getEnd());
313
+ const bodyInner = code.slice(bodyStart + 1, st.getEnd() - 1);
314
+ const typeArgs = tagged.fieldsNode ? `<${tagged.fieldsNode.getText(sf)}>` : '';
315
+ const rep = `${expPrefix}class ${className} extends ${baseCtor}${typeArgs} {\n${declLines.join('\n')}\n${bodyInner}}`;
316
+ edits.push({ start: st.getStart(sf), end: st.getEnd(), text: preserveLines(orig, rep) });
317
+ }
318
+ }
319
+ const result = applyEdits(code, edits);
320
+ return extraImports.length ? `${extraImports.join('\n')}\n${result}` : result;
321
+ }
322
+ /** Targeted static lowerings for `effect/src/` modules so unmodified `effect@4.x` compiles natively. */
323
+ function transformEffectLib(code, norm) {
324
+ if (norm.endsWith('/effect/src/Pipeable.ts')) {
325
+ return code.replace(/export const Class: new\(\) => Pipeable = \(function\(\) \{\s*function PipeableBase\(\) \{\}\s*PipeableBase\.prototype = Prototype\s*return PipeableBase as any\s*\}\)\(\)/, `export class Class implements Pipeable {\n pipe(...args: ReadonlyArray<any>): any {\n return pipeArguments(this, args as any)\n }\n}`);
326
+ }
327
+ if (norm.endsWith('/effect/src/Data.ts')) {
328
+ let out = code.replace(/export const Class: new<A extends Record<string, any> = \{\}>\(\s*args: Types\.VoidIfEmpty<\{ readonly \[P in keyof A\]: A\[P\] \}>\s*\) => Readonly<A> & Pipeable\.Pipeable = class extends Pipeable\.Class \{\s*constructor\(props: object \| undefined\) \{\s*super\(\)\s*if \(props\) \{\s*InternalRecord\.assignProperties\(this, props\)\s*\}\s*\}\s*\} as any/, `export class Class<A extends Record<string, any> = {}> extends Pipeable.Class {\n constructor(args?: Types.VoidIfEmpty<{ readonly [P in keyof A]: A[P] }>) {\n super()\n if (args) {\n InternalRecord.assignProperties(this, args as any)\n }\n }\n}`);
329
+ out = out.replace(/export const TaggedClass = <Tag extends string>\(\s*tag: Tag\s*\): new<A extends Record<string, any> = \{\}>\(\s*args: Types\.VoidIfEmpty<\{ readonly \[P in keyof A as P extends "_tag" \? never : P\]: A\[P\] \}>\s*\) => Readonly<A> & \{ readonly _tag: Tag \} & Pipeable\.Pipeable =>\s*class extends Class \{\s*readonly _tag = tag\s*\} as any/, `export const TaggedClass = <Tag extends string>(tag: Tag): new<A extends Record<string, any> = {}>(args: Types.VoidIfEmpty<{ readonly [P in keyof A as P extends "_tag" ? never : P]: A[P] }>) => Readonly<A> & { readonly _tag: Tag } & Pipeable.Pipeable => Class as any`);
330
+ out = out.replace(/export const Error: new<A extends Record<string, any> = \{\}>\(\s*args: Types\.VoidIfEmpty<\{ readonly \[P in keyof A\]: A\[P\] \}>\s*\) => Cause\.YieldableError & Readonly<A> = core\.Error/, `export { Error } from "./internal/core.ts"`);
331
+ return out;
332
+ }
333
+ if (norm.endsWith('/effect/src/internal/core.ts')) {
334
+ let out = code;
335
+ out = out.replace(/export const YieldableError: new\(\s*message\?: string,\s*options\?: ErrorOptions\s*\) => Cause\.YieldableError = \(function\(\) \{\s*class YieldableError extends globalThis\.Error \{\}\s*const proto = makePrimitiveProto\(\{\s*op: "YieldableError",\s*\[evaluate\]\(\) \{\s*return exitFail\(this\)\s*\}\s*\}\)\s*delete \(proto as any\)\.toString\s*Object\.assign\(\s*YieldableError\.prototype,\s*proto\s*\)\s*return YieldableError as any\s*\}\)\(\)/, `export class YieldableError extends globalThis.Error {\n constructor(message?: string, options?: ErrorOptions) { super(message, options) }\n pipe(...args: ReadonlyArray<any>): any { return pipeArguments(this, args as any) }\n [Symbol.iterator](): any { return new SingleShotGen(this) }\n}\nconst __yeProto = makePrimitiveProto({ op: "YieldableError", [evaluate]() { return exitFail(this) } })\ndelete (__yeProto as any).toString\nObject.assign(YieldableError.prototype, __yeProto)`);
336
+ out = out.replace(/export const Error: new<A extends Record<string, any> = \{\}>\(\s*args: Types\.VoidIfEmpty<\{ readonly \[P in keyof A\]: A\[P\] \}>\s*\) => Cause\.YieldableError & Readonly<A> = \(function\(\) \{\s*const plainArgsSymbol = Symbol\.for\("effect\/Data\/Error\/plainArgs"\)\s*return class Base extends YieldableError \{\s*constructor\(args: Record<string, any> \| undefined\) \{\s*super\(args\?\.message, args\?\.cause \? \{ cause: args\.cause \} : undefined\)\s*if \(args\) \{\s*InternalRecord\.assignProperties\(this, args\)\s*\/\/ @effect-diagnostics-next-line floatingEffect:off\s*Object\.defineProperty\(this, plainArgsSymbol, \{\s*value: args,\s*enumerable: false\s*\}\)\s*\}\s*\}\s*override toJSON\(\) \{\s*return \{ \.\.\.\(this as any\)\[plainArgsSymbol\], \.\.\.this \}\s*\}\s*\} as any\s*\}\)\(\)/, `const __plainArgsSymbol = Symbol.for("effect/Data/Error/plainArgs")\nexport class Error<A extends Record<string, any> = {}> extends YieldableError {\n constructor(args?: Types.VoidIfEmpty<{ readonly [P in keyof A]: A[P] }>) {\n const a = args as Record<string, any> | undefined\n super(a?.message, a?.cause ? { cause: a.cause } : undefined)\n if (a) {\n InternalRecord.assignProperties(this, a)\n Object.defineProperty(this, __plainArgsSymbol, { value: a, enumerable: false })\n }\n }\n toJSON(): any {\n return { ...(this as any)[__plainArgsSymbol], ...this }\n }\n}`);
337
+ out = out.replace(/export const TaggedError = <Tag extends string>\(\s*tag: Tag\s*\): new<A extends Record<string, any> = \{\}>\(\s*args: Types\.VoidIfEmpty<\{ readonly \[P in keyof A as P extends "_tag" \? never : P\]: A\[P\] \}>\s*\) => Cause\.YieldableError & \{ readonly _tag: Tag \} & Readonly<A> => \{\s*class Base extends Error<\{\}> \{\s*readonly _tag = tag\s*\}\s*;\(Base\.prototype as any\)\.name = tag\s*return Base as any\s*\}/, `export const TaggedError = <Tag extends string>(tag: Tag): new<A extends Record<string, any> = {}>(args: Types.VoidIfEmpty<{ readonly [P in keyof A as P extends "_tag" ? never : P]: A[P] }>) => Cause.YieldableError & { readonly _tag: Tag } & Readonly<A> => Error as any`);
338
+ out = out.replace(/const self = Object\.assign\(Object\.create\(Object\.getPrototypeOf\(this\)\), this\)\s*self\.annotations = newAnnotations/, `const self: any = this._tag === "Fail" ? new Fail((this as any).error, newAnnotations) : this._tag === "Die" ? new Die((this as any).defect, newAnnotations) : Object.assign(Object.create(Object.getPrototypeOf(this)), this)\n self.annotations = newAnnotations`);
339
+ return out;
340
+ }
341
+ if (norm.endsWith('/effect/src/Function.ts')) {
342
+ let out = code;
343
+ out = out.replace(/<DataLast extends \(\.\.\.args: Array<any>\) => any, DataFirst extends \(\.\.\.args: Array<any>\) => any>\(/g, '<DataLast = any, DataFirst = any>(');
344
+ out = out.replace(/arity: Parameters<DataFirst>\["length"\], body: DataFirst/g, 'arity: any, body: DataFirst');
345
+ out = out.replace(/isDataFirst: \(args: IArguments\) => boolean, body: DataFirst/g, 'isDataFirst: (args: any) => boolean, body: DataFirst');
346
+ out = out.replace(/if \(typeof arity === "function"\) \{\s*return function\(this: any\) \{\s*return arity\(arguments\)\s*\? body\.apply\(this, arguments as any\)\s*: \(\(self: any\) => body\(self, \.\.\.arguments\)\) as any\s*\}\s*\}/, `if (typeof arity === "function") {\n return function(this: any, ...__args: Array<any>) {\n return arity(__args as any)\n ? body.apply(this, __args as any)\n : ((self: any) => body(self, ...__args)) as any\n }\n }`);
347
+ out = out.replace(/default:\s*return function\(\) \{\s*if \(arguments\.length >= arity\) \{\s*\/\/ @ts-expect-error\s*return body\.apply\(this, arguments\)\s*\}\s*const args = arguments\s*return function\(self: any\) \{\s*return body\(self, \.\.\.args\)\s*\}\s*\}/, `default:\n return function(this: any, ...args: Array<any>) {\n if (args.length >= arity) {\n return body.apply(this, args as any)\n }\n return function(self: any) {\n return body(self, ...args)\n }\n }`);
348
+ return out;
349
+ }
350
+ if (norm.endsWith('/effect/src/Formatter.ts')) {
351
+ return code
352
+ .replace(/return Reflect\.ownKeys\(o\)/g, 'return [...Object.getOwnPropertyNames(o), ...Object.getOwnPropertySymbols(o)]')
353
+ .replace(/v\["toString"\] !== Array\.prototype\.toString/g, 'v["toString"] !== ([] as any).toString')
354
+ .replace(/const value = Reflect\.get\(object, key\)/g, 'const value = (object as any)[key]')
355
+ .replace(/function isJsonPrimitiveWrapper\(object: object\): boolean \{[\s\S]*?return false\s*\}/, 'function isJsonPrimitiveWrapper(_object: object): boolean { return false }')
356
+ .replace('function recur(v: unknown, d = 0): string {', 'let recur: (v: unknown, d?: number) => string\n recur = (v: unknown, d = 0): string => {')
357
+ .replace('function recurUnsafe(v: unknown, d = 0): string {', 'const recurUnsafe = (v: unknown, d = 0): string => {');
358
+ }
359
+ if (norm.endsWith('/effect/src/internal/stream.ts')) {
360
+ return code
361
+ .replace(/const Stream: \{[\s\S]*?this\.channel = channel\s*\} as any\s*Stream\.prototype = \{\s*\[TypeId\]: streamVariance,\s*pipe\(\) \{\s*return pipeArguments\(this, arguments\)\s*\}\s*\}/, `class StreamImpl {\n readonly [TypeId] = streamVariance\n channel: any\n constructor(channel: any) {\n this.channel = channel\n }\n pipe(...args: ReadonlyArray<any>): any {\n return pipeArguments(this, args as any)\n }\n}`)
362
+ .replace(/=> new Stream\(channel\)/, '=> new StreamImpl(channel) as any');
363
+ }
364
+ if (norm.endsWith('/effect/src/internal/effect.ts')) {
365
+ return code.replace(/u\.toString !== Array\.prototype\.toString/g, 'u.toString !== ([] as any).toString');
366
+ }
367
+ if (norm.endsWith('/effect/src/SchemaAST.ts')) {
368
+ const cloneHelper = `function __nsCloneAST<A extends AST>(ast: A, changes: any): A {
369
+ const a: any = ast
370
+ const ann = "annotations" in changes ? changes.annotations : a.annotations
371
+ const chk = "checks" in changes ? changes.checks : a.checks
372
+ const enc = "encoding" in changes ? changes.encoding : a.encoding
373
+ const ctx = "context" in changes ? changes.context : a.context
374
+ let out: any
375
+ switch (a._tag) {
376
+ case "Declaration": out = new Declaration("typeParameters" in changes ? changes.typeParameters : a.typeParameters, "run" in changes ? changes.run : a.run, ann, chk, enc, ctx, "encodingChecks" in changes ? changes.encodingChecks : a.encodingChecks, "encodingRun" in changes ? changes.encodingRun : a.encodingRun); break
377
+ case "Null": out = new Null(ann, chk, enc, ctx); break
378
+ case "Undefined": out = new Undefined(ann, chk, enc, ctx); break
379
+ case "Void": out = new Void(ann, chk, enc, ctx); break
380
+ case "Never": out = new Never(ann, chk, enc, ctx); break
381
+ case "Any": out = new Any(ann, chk, enc, ctx); break
382
+ case "Unknown": out = new Unknown(ann, chk, enc, ctx); break
383
+ case "ObjectKeyword": out = new ObjectKeyword(ann, chk, enc, ctx); break
384
+ case "Enum": out = new Enum("enums" in changes ? changes.enums : a.enums, ann, chk, enc, ctx); break
385
+ case "TemplateLiteral": out = new TemplateLiteral("parts" in changes ? changes.parts : a.parts, ann, chk, enc, ctx); break
386
+ case "UniqueSymbol": out = new UniqueSymbol("symbol" in changes ? changes.symbol : a.symbol, ann, chk, enc, ctx); break
387
+ case "Literal": out = new Literal("literal" in changes ? changes.literal : a.literal, ann, chk, enc, ctx); break
388
+ case "String": out = new String(ann, chk, enc, ctx); break
389
+ case "Number": out = new Number(ann, chk, enc, ctx); break
390
+ case "Boolean": out = new Boolean(ann, chk, enc, ctx); break
391
+ case "Symbol": out = new Symbol(ann, chk, enc, ctx); break
392
+ case "BigInt": out = new BigInt(ann, chk, enc, ctx); break
393
+ case "Arrays": out = new Arrays("isMutable" in changes ? changes.isMutable : a.isMutable, "elements" in changes ? changes.elements : a.elements, "rest" in changes ? changes.rest : a.rest, ann, chk, enc, ctx, "encodingChecks" in changes ? changes.encodingChecks : a.encodingChecks); break
394
+ case "Objects": out = new Objects("propertySignatures" in changes ? changes.propertySignatures : a.propertySignatures, "indexSignatures" in changes ? changes.indexSignatures : a.indexSignatures, ann, chk, enc, ctx, "encodingChecks" in changes ? changes.encodingChecks : a.encodingChecks); break
395
+ case "Suspend": out = new Suspend("thunk" in changes ? changes.thunk : a.thunk, ann, chk, enc, ctx); break
396
+ case "Union": out = new Union("types" in changes ? changes.types : a.types, "options" in changes ? changes.options : a.options, ann, chk, enc, ctx, "encodingChecks" in changes ? changes.encodingChecks : a.encodingChecks); break
397
+ default: out = Object.assign(Object.create(Object.getPrototypeOf(ast)), ast, changes); break
398
+ }
399
+ return out as A
400
+ }
401
+ function copy<A extends AST>(ast: A, changes: Partial<AST>): A {`;
402
+ return code
403
+ .replace(/const objectPrototypeKeys = new Set<PropertyKey>\(Reflect\.ownKeys\(Object\.prototype\)\)\.add\("__proto__"\)/, 'const objectPrototypeKeys = new Set<PropertyKey>(["constructor","__defineGetter__","__defineSetter__","hasOwnProperty","__lookupGetter__","__lookupSetter__","isPrototypeOf","propertyIsEnumerable","toString","valueOf","__proto__","toLocaleString"])')
404
+ .replace(/Reflect\.ownKeys\(changes\)/g, '[...Object.getOwnPropertyNames(changes), ...Object.getOwnPropertySymbols(changes)]')
405
+ .replace('function copy<A extends AST>(ast: A, changes: Partial<AST>): A {', cloneHelper)
406
+ .replace('const out = Object.assign(Object.create(Object.getPrototypeOf(ast)), ast, changes) as A', 'const out = __nsCloneAST(ast, changes)')
407
+ .replace('const owner = Object.assign(Object.create(Object.getPrototypeOf(ast)), ast, { encoding: undefined }) as A', 'const owner = __nsCloneAST(ast, { encoding: undefined })');
408
+ }
409
+ if (norm.endsWith('/effect/src/Schema.ts')) {
410
+ return code.replace(/constructor\(issue: SchemaIssue\.Issue\) \{\s*const stackTraceLimit = getStackTraceLimit\(\)\s*setStackTraceLimit\(0\)\s*try \{\s*super\(\{ issue \}\)\s*\} finally \{\s*setStackTraceLimit\(stackTraceLimit\)\s*\}\s*\}/, `constructor(issue: SchemaIssue.Issue) {\n super({ issue })\n }`);
411
+ }
412
+ if (norm.endsWith('/effect/src/internal/schema/make.ts')) {
413
+ return code.replace(/export function make<S extends Schema\.Constraint>\(ast: S\["ast"\], options\?: object\): S \{[\s\S]*?\n\}/, `export function make<S extends Schema.Constraint>(ast: S["ast"], options?: object): S {
414
+ function Schema() {}
415
+ const self: any = Object.setPrototypeOf(Schema, SchemaProto)
416
+ self[TypeId] = TypeId
417
+ let __make: any = undefined
418
+ let __makeEffect: any = undefined
419
+ let __makeOption: any = undefined
420
+ self.make = (input: any, opts?: any) => (__make ?? (__make = SchemaParser.make(self)))(input, opts)
421
+ self.makeEffect = (input: any, opts?: any) => (__makeEffect ?? (__makeEffect = SchemaParser.makeEffect(self)))(input, opts)
422
+ self.makeOption = (input: any, opts?: any) => (__makeOption ?? (__makeOption = SchemaParser.makeOption(self)))(input, opts)
423
+ self.pipe = (...args: Array<any>) => Pipeable.pipeArguments(self, args)
424
+ self.annotate = (annotations: Schema.Annotations.Annotations) => self.rebuild(SchemaAST.annotate(self.ast, annotations))
425
+ self.annotateKey = (annotations: Schema.Annotations.Key<unknown>) => self.rebuild(SchemaAST.annotateKey(self.ast, annotations))
426
+ self.check = (...checks: readonly [SchemaAST.Check<unknown>, ...Array<SchemaAST.Check<unknown>>]) => self.rebuild(SchemaAST.appendChecks(self.ast, checks))
427
+ self.rebuild = (nextAst: SchemaAST.AST) => make(nextAst, self[RebuildOptions])
428
+ if (
429
+ options &&
430
+ (Object.hasOwn(options, "name") || Object.hasOwn(options, "length") || Object.hasOwn(options, "__proto__"))
431
+ ) {
432
+ for (const __k of [...Object.getOwnPropertyNames(options), ...Object.getOwnPropertySymbols(options)]) {
433
+ const __d = Object.getOwnPropertyDescriptor(options, __k)
434
+ if (__d) Object.defineProperty(self, __k, __d)
435
+ }
436
+ } else {
437
+ Object.assign(self, options)
438
+ }
439
+ self[RebuildOptions] = options
440
+ self.ast = ast
441
+ return self
442
+ }`);
443
+ }
444
+ return code;
445
+ }
446
+ /** Targeted static lowerings for `@effect/ui/src/` modules so unmodified `@effect/ui` compiles natively. */
447
+ function transformEffectUiLib(code, norm) {
448
+ if (norm.endsWith('/@effect/ui/src/html/Html.ts')) {
449
+ return code.replace(/Record<string,\s*VoidElement<any,\s*any,\s*any,\s*any>>/g, 'Record<string, any>');
450
+ }
451
+ if (norm.endsWith('/@effect/ui/src/UiStruct.ts')) {
452
+ return code.replace(/Reflect\.ownKeys\(fields\)/g, '[...Object.getOwnPropertyNames(fields), ...Object.getOwnPropertySymbols(fields)]');
453
+ }
454
+ if (norm.endsWith('/@effect/ui/src/View.ts')) {
455
+ return code
456
+ .replace(/if \(this\.attr !== ElementBuilder\.prototype\.attr\)/, 'if (false)')
457
+ .replace(/let Class = elements === lastElements[\s\S]*?return new Class\(props, elements, running, path \?\? "", store\) as any/, `const __helper = new HelperImpl(props, elements, running, path ?? "", store) as any\n Object.assign(__helper, (elements as any).tags)\n return __helper`)
458
+ .replace(/const copyBuilder = <B extends ElementBuilder<any, any, any, any>>\([\s\S]*?return Object\.assign\(Object\.create\(Object\.getPrototypeOf\(builder\)\), builder\)\n\}/, `const copyBuilder = <B extends ElementBuilder<any, any, any, any>>(\n builder: B\n): B => {\n const __cloned = builder instanceof NoTextBuilder ? new NoTextBuilder(builder.tag, (builder as any).vocabulary) : new (builder.constructor as any)(builder.tag)\n return Object.assign(__cloned, builder)\n}`)
459
+ .replace(/const blank: ElementBuilder<any, any, any, any> = Object\.assign\(\s*Object\.create\(Object\.getPrototypeOf\(builder\)\),\s*blankFields,\s*\{ tag: builder\.tag, removals: \[\] \}\s*\)/, `const blank: ElementBuilder<any, any, any, any> = Object.assign(\n builder instanceof NoTextBuilder ? new NoTextBuilder(builder.tag, (builder as any).vocabulary) : new (builder.constructor as any)(builder.tag),\n blankFields,\n { tag: builder.tag, removals: [] }\n )`)
460
+ .replace(/const root = \(\.\.\.inputs: ReadonlyArray<Input<any, any>>\) =>\s*\(root as any\)\.children\(\.\.\.inputs\)\s*Object\.setPrototypeOf\(root, Object\.getPrototypeOf\(builder\)\)\s*return Object\.assign\(root, builder\) as any/, `const root = (...inputs: ReadonlyArray<Input<any, any>>) =>\n (builder as any).children(...inputs)\n Object.setPrototypeOf(root, builder)\n return Object.assign(root, builder) as any`);
461
+ }
462
+ if (norm.endsWith('/@effect/ui/src/Component.ts')) {
463
+ return code.replace(/return StepProto\.send\.call\(\s*this,\s*target === "self" \? this\["~self"\] as unknown as Headless\.Any : target,\s*message\s*\)/, `const __owner = target === "self" ? this["~self"] as unknown as Headless.Any : target\n return stepWith(this, { sends: [...this.sends, { owner: __owner, message }] })`);
464
+ }
465
+ if (norm.endsWith('/@effect/ui/src/internal/runtime.ts')) {
466
+ return code
467
+ .replace(' let dispatching: Kernel.Instance | undefined\n', '')
468
+ .replace(' let outcome: Dispatched | undefined\n', '')
469
+ .replace(' let hydrating: hydrateRun.Session | undefined\n', '')
470
+ .replace(' let kernelRoot: Kernel.Root | undefined\n', '')
471
+ .replace(' const record: Kernel.Recorder = (inst, draft) => {', ' let dispatching: Kernel.Instance | undefined\n let outcome: Dispatched | undefined\n let hydrating: hydrateRun.Session | undefined\n let kernelRoot: Kernel.Root | undefined\n const record: Kernel.Recorder = (inst, draft) => {');
472
+ }
473
+ if (norm.endsWith('/@effect/ui/src/internal/kernel.ts')) {
474
+ return code
475
+ .replace(/kids = new Array\(views\.length\)\s*for \(let index = 0; index < views\.length; index\+\+\) \{\s*place\(host, node, kids\[index\] = create\(inst, views\[index\]!\), null\)\s*\}/, `kids = []\n for (let index = 0; index < views.length; index++) {\n const __k = create(inst, views[index]!)\n kids.push(__k)\n place(host, node, __k, null)\n }`)
476
+ .replace(/const kids: Array<Rec> = rec\.kids = new Array\(views\.length\)\s*for \(let index = 0; index < views\.length; index\+\+\) \{\s*kids\[index\] = create\(declarer, views\[index\]!\)\s*\}/, `const kids: Array<Rec> = []\n rec.kids = kids\n for (let index = 0; index < views.length; index++) {\n kids.push(create(declarer, views[index]!))\n }`)
477
+ .replace(/const kids: Array<Rec> = new Array\(views\.length\)\s*for \(let index = 0; index < views\.length; index\+\+\) \{\s*place\(host, node, kids\[index\] = create\(inst, views\[index\]!\), null\)\s*\}/, `const kids: Array<Rec> = []\n for (let index = 0; index < views.length; index++) {\n const __k = create(inst, views[index]!)\n kids.push(__k)\n place(host, node, __k, null)\n }`)
478
+ .replace(/let out: Array<Rec> = oldEnd === end \? olds : new Array\(views\.length\)/, `let out: Array<Rec> = oldEnd === end ? olds : Array.from({ length: views.length }) as Array<Rec>`)
479
+ .replace(/out = new Array\(views\.length\)/, `out = Array.from({ length: views.length }) as Array<Rec>`);
480
+ }
481
+ if (norm.endsWith('/@effect/ui/src/Command.ts')) {
482
+ return code
483
+ .replace(/export const Service: <Self>\(\) => \{\s*<const Key extends string>\(\s*key: Key,\s*options\?: undefined\s*\):/, `export const Service: <Self>() => {\n <const Key extends string>(\n key: Key\n ):`)
484
+ .replace(/class CommandService extends Base \{\s*static readonly success = success\s*static readonly error = error\s*static toLayer\(\s*build: \(\(args: any\) => any\) \| Effect\.Effect<\(args: any\) => any, any, any>\s*\): Layer\.Layer<any, any, any> \{\s*return Effect\.isEffect\(build\)\s*\? Layer\.effect\(Base, build\)\s*: Layer\.succeed\(Base, build\)\s*\}\s*\}/, `const CommandService: any = Object.assign(Base, {\n success,\n error,\n toLayer(build: ((args: any) => any) | Effect.Effect<(args: any) => any, any, any>): Layer.Layer<any, any, any> {\n return Effect.isEffect(build) ? Layer.effect(Base, build) : Layer.succeed(Base, build)\n }\n })`);
485
+ }
486
+ if (norm.endsWith('/@effect/ui/src/Query.ts')) {
487
+ let out = code;
488
+ // Replace local `class extends QueryService` in `Service`
489
+ out = out.replace(/return class extends QueryService \{\s*static set\(args: unknown, value: unknown\) \{\s*return write\(QueryService, args, value\)\s*\}\s*\}/, `return Object.assign(QueryService, { set(args: unknown, value: unknown) { return write(QueryService, args, value) } }) as any`);
490
+ // Replace local `class QueryService extends Base` in `queryClass`
491
+ const qsStart = out.indexOf(' class QueryService extends Base {');
492
+ if (qsStart >= 0) {
493
+ const qsEnd = out.indexOf('\n return QueryService', qsStart);
494
+ if (qsEnd > qsStart) {
495
+ const body = out.slice(qsStart + ' class QueryService extends Base {'.length, qsEnd).replace(/\}\s*$/, '');
496
+ const sf = ts.createSourceFile('__q.ts', `class QueryService {${body}}`, ts.ScriptTarget.Latest, true);
497
+ const cls = sf.statements[0];
498
+ const propEntries = [];
499
+ for (const m of cls.members) {
500
+ if (ts.isPropertyDeclaration(m) && m.name) {
501
+ propEntries.push(`${m.name.getText(sf)}: ${m.initializer ? m.initializer.getText(sf) : 'undefined'}`);
502
+ }
503
+ else if (ts.isMethodDeclaration(m) && m.name) {
504
+ const params = m.parameters.map((p) => p.getText(sf)).join(', ');
505
+ const ret = m.type ? `: ${m.type.getText(sf)}` : '';
506
+ propEntries.push(`${m.name.getText(sf)}(${params})${ret} ${m.body.getText(sf)}`);
507
+ }
508
+ }
509
+ const replacement = ` const QueryService: any = Object.assign(Base, {\n ${propEntries.join(',\n ')}\n })`;
510
+ out = out.slice(0, qsStart) + replacement + out.slice(qsEnd);
511
+ }
512
+ }
513
+ // Replace materialize + prototype slot helpers + copyWithout with non-Proxy/non-Reflect equivalents
514
+ const matStart = out.indexOf('const materialize = (');
515
+ const copyBytesEnd = out.indexOf('/**\n * A snapshot of the encoding', matStart);
516
+ if (matStart >= 0 && copyBytesEnd > matStart) {
517
+ const simpleMat = `const materialize = (u: unknown, seen = new Map<object, unknown>()): unknown => {
518
+ if (typeof u === "function") return standIn(u)
519
+ if (typeof u !== "object" || u === null) return u
520
+ if (Equal.symbol in u) return standIn(u)
521
+ const known = seen.get(u)
522
+ if (known !== undefined) return known
523
+ if (u instanceof ArrayBuffer) return u.slice(0)
524
+ if (ArrayBuffer.isView(u)) return new Uint8Array(u.buffer, u.byteOffset, u.byteLength).slice()
525
+ if (Array.isArray(u)) {
526
+ const out: Array<unknown> = []
527
+ seen.set(u, out)
528
+ for (let i = 0; i < u.length; i++) out.push(materialize(u[i], seen))
529
+ return out
530
+ }
531
+ if (u instanceof Date) return new Date(u.getTime())
532
+ if (u instanceof RegExp) return new RegExp(u.source, u.flags)
533
+ if (u instanceof Map) {
534
+ const out = new Map()
535
+ seen.set(u, out)
536
+ u.forEach((value, key) => out.set(materialize(key, seen), materialize(value, seen)))
537
+ return out
538
+ }
539
+ if (u instanceof Set) {
540
+ const out = new Set()
541
+ seen.set(u, out)
542
+ u.forEach((value) => out.add(materialize(value, seen)))
543
+ return out
544
+ }
545
+ const out: Record<PropertyKey, unknown> = Object.create(null)
546
+ seen.set(u, out)
547
+ for (const key of [...Object.getOwnPropertyNames(u), ...Object.getOwnPropertySymbols(u)]) {
548
+ if (key === Hash.symbol) continue
549
+ out[key] = materialize((u as any)[key], seen)
550
+ }
551
+ return out
552
+ }
553
+ const standIns = new WeakMap<object, object>()
554
+ const standIn = (u: object): object => {
555
+ let out = standIns.get(u)
556
+ if (out === undefined) {
557
+ out = Equal.byReferenceUnsafe(Object.create(null) as object)
558
+ standIns.set(u, out)
559
+ }
560
+ return out
561
+ }
562
+ `;
563
+ out = out.slice(0, matStart) + simpleMat + out.slice(copyBytesEnd);
564
+ }
565
+ out = out.replace(/const copyWithout = \(o: object, names: ReadonlyArray<PropertyKey>\): object => \{[\s\S]*?return out\s*\}/, `const copyWithout = (o: object, names: ReadonlyArray<PropertyKey>): object => {
566
+ const drop = new Set<PropertyKey>(names)
567
+ const out: any = Object.create(Object.getPrototypeOf(o))
568
+ for (const key of [...Object.getOwnPropertyNames(o), ...Object.getOwnPropertySymbols(o)]) {
569
+ if (drop.has(key)) continue
570
+ const d = Object.getOwnPropertyDescriptor(o, key)
571
+ if (d) Object.defineProperty(out, key, d)
572
+ }
573
+ if (Object.isFrozen(o)) Object.freeze(out)
574
+ else if (Object.isSealed(o)) Object.seal(out)
575
+ else if (!Object.isExtensible(o)) Object.preventExtensions(out)
576
+ return out
577
+ }`);
578
+ return out;
579
+ }
580
+ return code;
581
+ }
package/package.json CHANGED
@@ -1,6 +1,52 @@
1
1
  {
2
2
  "name": "@nstudio/nativescript-compiler-effect-ui",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "9.2.0-alpha.13",
4
+ "description": "The Effect UI adapter of @nstudio/nativescript-compiler: compiles a NativeScript app written with @effect/ui and Effect v4 into a native iOS or Android app with no JavaScript runtime.",
5
+ "type": "module",
6
+ "exports": {
7
+ ".": {
8
+ "source": "./index.ts",
9
+ "default": "./dist/index.js"
10
+ },
11
+ "./package.json": "./package.json"
12
+ },
13
+ "files": [
14
+ "dist/"
15
+ ],
16
+ "scripts": {
17
+ "build": "ns-compiled-adapter build .",
18
+ "prepack": "npm run build"
19
+ },
20
+ "license": "MIT",
21
+ "repository": {
22
+ "type": "git",
23
+ "url": "https://github.com/nstudio/nativescript-compiler.git",
24
+ "directory": "packages/effect-ui"
25
+ },
26
+ "peerDependencies": {
27
+ "@nstudio/nativescript-compiler": "9.2.0-alpha.13"
28
+ },
29
+ "nativescript": {
30
+ "compilerAdapter": {
31
+ "apiVersion": 1,
32
+ "detect": {
33
+ "priority": 50,
34
+ "dependencies": [
35
+ "@effect/ui",
36
+ "@nstudio/nativescript-effect-ui"
37
+ ],
38
+ "entryImports": [
39
+ "@effect/ui",
40
+ "@nstudio/nativescript-effect-ui"
41
+ ]
42
+ },
43
+ "testedVersions": {
44
+ "@effect/ui": "*",
45
+ "effect": ">=4.0.0 <5.0.0"
46
+ }
47
+ }
48
+ },
49
+ "publishConfig": {
50
+ "access": "public"
51
+ }
52
+ }