Skip to content

Commit

Permalink
misc internal cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
sparecycles committed Dec 31, 2024
1 parent 075e81c commit 84754af
Show file tree
Hide file tree
Showing 20 changed files with 222 additions and 261 deletions.
4 changes: 2 additions & 2 deletions packages/core/src/core/endpoint-environment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -125,9 +125,9 @@ export function createEndpointEnvironment({

return "{{redacted}}";
},
async express({ source, ident, evaluation }) {
async express({ source, identifier, evaluation }) {
void source;
void ident;
void identifier;

return evaluation();
},
Expand Down
32 changes: 16 additions & 16 deletions packages/core/src/core/expression.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,11 @@ import {
export type TsMorphTransform = (control: TransformTraversalControl) => ts.Node;

export function applyTsMorph(
expr: string,
expression: string,
transform?: TsMorphTransform,
): string {
if (!transform) {
return expr;
return expression;
}

const expressionProject = new Project({
Expand All @@ -47,7 +47,7 @@ export function applyTsMorph(

const exprSourceFile = expressionProject.createSourceFile(
`__expr__.ts`,
`export default ${expr}`,
`export default ${expression}`,
{ overwrite: true },
);

Expand All @@ -65,14 +65,14 @@ export function applyTsMorph(
}

export function unbound(
expr: string,
expression: string,
options: acorn.Options = { ecmaVersion: 2022 },
) {
const unbound: string[] = [];

try {
walker.simple(
acorn.parse(expr, { ...options, allowAwaitOutsideFunction: true }),
acorn.parse(expression, { ...options, allowAwaitOutsideFunction: true }),
{
Expression(node) {
if (node.type == "Identifier") {
Expand All @@ -82,7 +82,7 @@ export function unbound(
},
);
} catch (ex) {
console.error(`error parsing: ${expr} for unbound values`);
console.error(`error parsing: ${expression} for unbound values`);
throw ex;
}

Expand Down Expand Up @@ -111,7 +111,7 @@ export const expressionTransform: TsMorphTransform = ({
};

export function syncEvaluation(
expr: string,
expression: string,
{
binding,
options,
Expand All @@ -122,26 +122,26 @@ export function syncEvaluation(
transform?: TsMorphTransform;
},
): unknown {
expr = applyTsMorph(expr, transform);
expression = applyTsMorph(expression, transform);

const bound = [...unbound(`(${expr})`, options)].map(
(ident) => [ident, binding?.(ident)] as const,
const bound = [...unbound(`(${expression})`, options)].map(
(name) => [name, binding?.(name)] as const,
);

const fn = new Function(...bound.map(([k]) => k), `return (${expr})`);
const fn = new Function(...bound.map(([k]) => k), `return (${expression})`);

const args = bound.map(([, v]) => v);

try {
return fn(...args);
} catch (error) {
console.warn(`error evaluating script: ${expr}`, error);
console.warn(`error evaluating script: ${expression}`, error);
throw error;
}
}

export async function evaluation(
expr: string,
expression: string,
{
binding,
options,
Expand All @@ -150,12 +150,12 @@ export async function evaluation(
options?: acorn.Options;
},
): Promise<unknown> {
const unboundIdentifiers = unbound(`(${expr})`, options);
const unboundIdentifiers = unbound(`(${expression})`, options);
const bound = [...unboundIdentifiers].map(
(ident) => [ident, binding?.(ident)] as const,
(name) => [name, binding?.(name)] as const,
);

const compiled = applyTsMorph(expr, expressionTransform);
const compiled = applyTsMorph(expression, expressionTransform);

const fn = new Function(
...bound.map(([k]) => k),
Expand Down
4 changes: 2 additions & 2 deletions packages/core/src/core/formats/https-fmt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -148,8 +148,8 @@ function scanRequestComputations(file: string) {

for (;;) {
if (file.trim().startsWith(":")) {
const [, expr, rest] = /\s*(:[^\n]*)\n(.*)/s.exec(file)!;
const parsed = parseVariable(expr);
const [, expression, rest] = /\s*(:[^\n]*)\n(.*)/s.exec(file)!;
const parsed = parseVariable(expression);
if (!parsed) break;
computations[parsed.param] = `{{${parsed.variable.source}}}`;
file = rest;
Expand Down
12 changes: 6 additions & 6 deletions packages/core/src/core/request/body-template.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,15 +77,15 @@ export const bodyGlobals: Record<string, any> = {

export function evalTemplate(schemaSource: string): Schematic<unknown> {
return syncEvaluation(`${schemaSource}`, {
binding(identifier) {
if (identifier in bodyGlobals) {
return bodyGlobals[identifier];
binding(name) {
if (name in bodyGlobals) {
return bodyGlobals[name];
}

if (identifier.startsWith("$")) {
const ident = identifier.slice(1);
if (name.startsWith("$")) {
const ref = name.slice(1);

return referenceTemplate({ ref: ident });
return referenceTemplate({ ref });
}

return undefined;
Expand Down
33 changes: 7 additions & 26 deletions packages/core/src/core/schema/core/context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,20 +101,16 @@ export function tempContext<C extends SchemaContext>(context: C): C {
export function createRenderContext<T>(
schema: Schema<T>,
environment: SchemaScriptEnvironment = new ScriptEnvironment(),
scope?: SchemaScope,
): SchemaRenderContext {
const ctx = {
mode: "render",
keys: [],
scopes: [],
environment,
scope: scope ?? Scope.createRootScope(),
scope: Scope.createRootScope(),
diagnostics: [],
} satisfies SchemaRenderContext;

if (scope) {
ctx.scope = scope.clone(ctx);
}
executeOp(schema, "scope", ctx);

return ctx;
Expand All @@ -123,68 +119,53 @@ export function createRenderContext<T>(
export function createPreviewContext<T>(
scheme: Schema<T>,
environment: SchemaScriptEnvironment = new ScriptEnvironment(),
scope?: SchemaScope,
): SchemaRenderContext {
const ctx = {
mode: "preview",
keys: [],
scopes: [],
environment,
scope: scope ?? Scope.createRootScope(),
scope: Scope.createRootScope(),
diagnostics: [],
} satisfies SchemaRenderContext;

if (!scope) {
executeOp(scheme, "scope", ctx);
} else {
ctx.scope = scope.clone(ctx);
}
executeOp(scheme, "scope", ctx);

return ctx;
}

export function createPrerenderContext<T>(
scheme: Schema<T>,
environment: SchemaScriptEnvironment = new ScriptEnvironment(),
scope?: SchemaScope,
): SchemaRenderContext {
const ctx = {
mode: "prerender",
keys: [],
scopes: [],
environment,
scope: scope ?? Scope.createRootScope(),
scope: Scope.createRootScope(),
diagnostics: [],
} satisfies SchemaRenderContext;

if (!scope) {
executeOp(scheme, "scope", ctx);
} else {
ctx.scope = scope.clone(ctx);
}
executeOp(scheme, "scope", ctx);

return ctx;
}

export function createPostrenderContext<T>(
scheme: Schema<T>,
environment: SchemaScriptEnvironment = new ScriptEnvironment(),
scope?: SchemaScope,
): SchemaRenderContext {
const ctx = {
mode: "postrender",
keys: [],
scopes: [],
diagnostics: [],
environment,
scope: scope ?? Scope.createRootScope(),
scope: Scope.createRootScope(),
} satisfies SchemaRenderContext;

if (!scope) {
executeOp(scheme, "scope", ctx);
} else {
ctx.scope = scope.clone(ctx);
}
executeOp(scheme, "scope", ctx);

return ctx;
}
Expand Down
46 changes: 24 additions & 22 deletions packages/core/src/core/schema/core/evaluate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,37 +23,37 @@ import {
export function evaluateIdentifierWithExpression(
context: SchemaRenderContext,
identifier: string,
expr?: string,
expression?: string,
): undefined | unknown | Promise<unknown> {
const resolved = resolveIdentifier(context, identifier);
if (resolved !== undefined) {
return resolved;
}

return renderIdentifierInExpression(context, identifier, expr);
return renderIdentifierInExpression(context, identifier, expression);
}

function doRenderExpression(
context: SchemaRenderContext,
{
ident,
expr,
identifier,
expression,
source,
hint,
}: {
ident: ValueIdentifier;
expr: string;
identifier: ValueIdentifier;
expression: string;
source: string | null;
hint: string | null;
},
) {
return context.environment.evaluating({
ident,
identifier,
context,
source,
hint,
evaluation: async () =>
await evaluation(expr!, {
await evaluation(expression!, {
binding(unbound) {
return evaluateIdentifierWithExpression(context, unbound);
},
Expand All @@ -64,7 +64,7 @@ function doRenderExpression(
function synthesizeExpressionDeclaration(
context: SchemaRenderContext,
identifier: string,
expr?: string,
expression?: string,
): Omit<ExpressionDeclaration, "name" | "path"> {
const { scope } = context;

Expand All @@ -73,38 +73,40 @@ function synthesizeExpressionDeclaration(
if (isLookupExpr(lookup)) {
return {
...lookup,
expr: expr ?? lookup.expr,
expression: expression ?? lookup.expression,
};
}

return {
identifier,
context,
expr: expr ?? null,
expression: expression ?? null,
hint: null,
source:
expr === undefined ? `{{}}` : `{{= $$expr(${JSON.stringify(expr)}) }}`,
expression === undefined
? `{{}}`
: `{{= $$expr(${JSON.stringify(expression)}) }}`,
};
}

function renderIdentifierInExpression(
context: SchemaRenderContext,
identifier: string,
expr?: string,
name: string,
expression?: string,
) {
const decl = synthesizeExpressionDeclaration(context, identifier, expr);
const decl = synthesizeExpressionDeclaration(context, name, expression);
const { scope } = context;
const rescoped = rescope(context, decl.context.scope);

return scope.rendering(context, identifier, async () => {
const ident = parseScopedIdentifier(identifier);
return scope.rendering(context, name, async () => {
const identifier = parseScopedIdentifier(name);

if (decl.expr) {
const { expr, source, hint } = decl;
if (decl.expression) {
const { expression, source, hint } = decl;

const expressionResult = await doRenderExpression(rescoped, {
ident,
expr,
identifier,
expression,
source,
hint,
});
Expand All @@ -120,7 +122,7 @@ function renderIdentifierInExpression(

const evaluatedResult = await context.environment.evaluate({
context,
ident,
identifier: identifier,
});

return evaluatedResult;
Expand Down
Loading

0 comments on commit 84754af

Please sign in to comment.