Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement the host side of the deprecations API #279

Merged
merged 7 commits into from
Apr 3, 2024
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions lib/index.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ export const AsyncCompiler = sass.AsyncCompiler;
export const Compiler = sass.Compiler;
export const initAsyncCompiler = sass.initAsyncCompiler;
export const initCompiler = sass.initCompiler;
export const deprecations = sass.deprecations;
export const Version = sass.Version;
export const Logger = sass.Logger;
export const CalculationInterpolation = sass.CalculationInterpolation;
export const CalculationOperation = sass.CalculationOperation;
Expand Down Expand Up @@ -86,6 +88,14 @@ export default {
defaultExportDeprecation();
return sass.Compiler;
},
get deprecations() {
defaultExportDeprecation();
return sass.deprecations;
},
get Version() {
defaultExportDeprecation();
return sass.Version;
},
get Logger() {
defaultExportDeprecation();
return sass.Logger;
Expand Down
7 changes: 7 additions & 0 deletions lib/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,13 @@ export {
} from './src/compile';
export {initAsyncCompiler, AsyncCompiler} from './src/compiler/async';
export {initCompiler, Compiler} from './src/compiler/sync';
export {
deprecations,
Deprecation,
DeprecationOrId,
DeprecationStatus,
Version,
} from './src/deprecations';
export {render, renderSync} from './src/legacy';

export const info = `sass-embedded\t${pkg.version}`;
Expand Down
30 changes: 26 additions & 4 deletions lib/src/compiler/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

import * as p from 'path';
import * as supportsColor from 'supports-color';
import {deprecations, getDeprecationIds, Deprecation} from '../deprecations';
import {deprotofySourceSpan} from '../deprotofy-span';
import {Dispatcher, DispatcherHandlers} from '../dispatcher';
import {Exception} from '../exception';
Expand Down Expand Up @@ -75,6 +76,9 @@ function newCompileRequest(
verbose: !!options?.verbose,
charset: !!(options?.charset ?? true),
silent: options?.logger === Logger.silent,
fatalDeprecation: getDeprecationIds(options?.fatalDeprecations ?? []),
silenceDeprecation: getDeprecationIds(options?.silenceDeprecations ?? []),
futureDeprecation: getDeprecationIds(options?.futureDeprecations ?? []),
});

switch (options?.style ?? 'expanded') {
Expand Down Expand Up @@ -137,6 +141,13 @@ export function newCompileStringRequest(
return request;
}

/** Type guard to check that `id` is a valid deprecation ID. */
function validDeprecationId(
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: document this

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done

id: string | number | symbol | undefined
): id is keyof typeof deprecations {
return !!id && id in deprecations;
}

/** Handles a log event according to `options`. */
export function handleLogEvent(
options: OptionsWithLegacy<'sync' | 'async'> | undefined,
Expand All @@ -148,6 +159,9 @@ export function handleLogEvent(
if (options?.legacy) message = removeLegacyImporter(message);
let formatted = event.formatted;
if (options?.legacy) formatted = removeLegacyImporter(formatted);
const deprecationType = validDeprecationId(event.deprecationType)
? deprecations[event.deprecationType]
: null;

if (event.type === proto.LogEventType.DEBUG) {
if (options?.logger?.debug) {
Expand All @@ -159,10 +173,18 @@ export function handleLogEvent(
}
} else {
if (options?.logger?.warn) {
const params: {deprecation: boolean; span?: SourceSpan; stack?: string} =
{
deprecation: event.type === proto.LogEventType.DEPRECATION_WARNING,
};
const params: (
| {
deprecation: true;
deprecationType: Deprecation;
}
| {deprecation: false}
) & {
span?: SourceSpan;
stack?: string;
} = deprecationType
? {deprecation: true, deprecationType: deprecationType}
: {deprecation: false};
if (span) params.span = span;

const stack = event.stackTrace;
Expand Down
173 changes: 173 additions & 0 deletions lib/src/deprecations.ts
Copy link
Contributor

@ntkme ntkme Apr 1, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it would be better to not duplicate this list of deprecations on every host implementation. Either that we just don't expose the list of all deprecations as part of the JS API, or we implement a protocol to allow embedded host to send query to compiler and ask this information.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not having any metadata as part of the client API would mean that TypeScript users don't get any static checking of their deprecation names. That's not an unbearable cost, but I'd prefer to have better devx there if possible.

I do agree that we need a better story for synchronizing the deprecation list across various repos and packages, though. As it stands, every time we need to add a new deprecation it'll have to be added to Dart Sass, the language repo, and the embedded host separately even if it's a pure language-level deprecation that has no bearing on the JS API. What's worse, I don't think we have any verification in place that will fail if we forget one or more of these locations.

I wonder if it makes sense to include a JSON file (or a text proto?) that just lists all the known deprecations, from which we can generate the code representations. Then we can have simple diff tests that verify that all the generated versions are based on the latest deprecation list. @jathak what do you think?

Copy link
Contributor

@ntkme ntkme Apr 2, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I like the idea of maintaining a text proto, which can generate ts definition and be directly used as argument in embedded-protocol.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, I think having a single representation and generating code for each implementation makes sense. I'd vote for writing it in YAML since it's a better authoring experience than JSON and I don't think the Dart protobuf library supports parsing text protos (google/protobuf.dart#125).

Should this block releasing the deprecations API, or should we release it with just a simple synchronization test and then switch to generating the code afterwards?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think the latter is fine.

Original file line number Diff line number Diff line change
@@ -0,0 +1,173 @@
// Copyright 2024 Google LLC. Use of this source code is governed by an
// MIT-style license that can be found in the LICENSE file or at
// https://opensource.org/licenses/MIT.

import * as api from './vendor/sass';

export {Deprecation, DeprecationOrId, DeprecationStatus} from './vendor/sass';

export class Version implements api.Version {
constructor(
readonly major: number,
readonly minor: number,
readonly patch: number
) {}
static parse(version: string): Version {
const match = version.match(/^(\d+)\.(\d+)\.(\d+)$/);
if (match === null) {
throw new Error(`Invalid version ${version}`);
}
return new Version(
parseInt(match[1]),
parseInt(match[2]),
parseInt(match[3])
);
}
}

/**
* Returns whether the given deprecation was active in the given version.
*/
function isActiveIn(deprecation: api.Deprecation, version: Version) {
const deprecatedIn = deprecation.deprecatedIn;
if (deprecation.status !== 'active' || !deprecatedIn) return false;
if (version.major > deprecatedIn.major) return true;
if (version.major < deprecatedIn.major) return false;
if (version.minor > deprecatedIn.minor) return true;
if (version.minor < deprecatedIn.minor) return false;
return version.patch >= deprecatedIn.patch;
}

/**
* Converts a mixed array of deprecations, IDs, and versions to an array of IDs
* that's ready to include in a CompileRequest.
*/
export function getDeprecationIds(
arr: (api.DeprecationOrId | Version)[]
): string[] {
return arr.flatMap(item => {
if (item instanceof Version) {
return Object.values(deprecations)
.filter(deprecation => isActiveIn(deprecation, item))
.map(deprecation => deprecation.id);
} else if (typeof item === 'string') {
return item;
}
return item.id;
});
}

export const deprecations: typeof api.deprecations = {
'call-string': {
id: 'call-string',
status: 'active',
deprecatedIn: new Version(0, 0, 0),
obsoleteIn: null,
description: 'Passing a string directly to meta.call().',
},
elseif: {
id: 'elseif',
status: 'active',
deprecatedIn: new Version(1, 3, 2),
obsoleteIn: null,
description: '@elseif.',
},
'moz-document': {
id: 'moz-document',
status: 'active',
deprecatedIn: new Version(1, 7, 2),
obsoleteIn: null,
description: '@-moz-document.',
},
'relative-canonical': {
id: 'relative-canonical',
status: 'active',
deprecatedIn: new Version(1, 14, 2),
obsoleteIn: null,
},
'new-global': {
id: 'new-global',
status: 'active',
deprecatedIn: new Version(1, 17, 2),
obsoleteIn: null,
description: 'Declaring new variables with !global.',
},
'color-module-compat': {
id: 'color-module-compat',
status: 'active',
deprecatedIn: new Version(1, 23, 0),
obsoleteIn: null,
description:
'Using color module functions in place of plain CSS functions.',
},
'slash-div': {
id: 'slash-div',
status: 'active',
deprecatedIn: new Version(1, 33, 0),
obsoleteIn: null,
description: '/ operator for division.',
},
'bogus-combinators': {
id: 'bogus-combinators',
status: 'active',
deprecatedIn: new Version(1, 54, 0),
obsoleteIn: null,
description: 'Leading, trailing, and repeated combinators.',
},
'strict-unary': {
id: 'strict-unary',
status: 'active',
deprecatedIn: new Version(1, 55, 0),
obsoleteIn: null,
description: 'Ambiguous + and - operators.',
},
'function-units': {
id: 'function-units',
status: 'active',
deprecatedIn: new Version(1, 56, 0),
obsoleteIn: null,
description: 'Passing invalid units to built-in functions.',
},
'duplicate-var-flags': {
id: 'duplicate-var-flags',
status: 'active',
deprecatedIn: new Version(1, 62, 0),
obsoleteIn: null,
description: 'Using !default or !global multiple times for one variable.',
},
'null-alpha': {
id: 'null-alpha',
status: 'active',
deprecatedIn: new Version(1, 62, 3),
obsoleteIn: null,
description: 'Passing null as alpha in the JS API.',
},
'abs-percent': {
id: 'abs-percent',
status: 'active',
deprecatedIn: new Version(1, 65, 0),
obsoleteIn: null,
description: 'Passing percentages to the Sass abs() function.',
},
'fs-importer-cwd': {
id: 'fs-importer-cwd',
status: 'active',
deprecatedIn: new Version(1, 73, 0),
obsoleteIn: null,
description:
'Using the current working directory as an implicit load path.',
},
import: {
id: 'import',
status: 'future',
deprecatedIn: null,
obsoleteIn: null,
description: '@import rules.',
},
'user-authored': {
id: 'user-authored',
status: 'user',
deprecatedIn: null,
obsoleteIn: null,
},
};
12 changes: 6 additions & 6 deletions lib/src/importer-registry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,12 @@ export class NodePackageImporter {
entryPointDirectory = entryPointDirectory
? p.resolve(entryPointDirectory)
: require.main?.filename
? p.dirname(require.main.filename)
: // TODO: Find a way to use `import.meta.main` once
// https://github.com/nodejs/node/issues/49440 is done.
process.argv[1]
? createRequire(process.argv[1]).resolve(process.argv[1])
: undefined;
? p.dirname(require.main.filename)
: // TODO: Find a way to use `import.meta.main` once
// https://github.com/nodejs/node/issues/49440 is done.
process.argv[1]
? createRequire(process.argv[1]).resolve(process.argv[1])
: undefined;
if (!entryPointDirectory) {
throw new Error(
'The Node package importer cannot determine an entry point ' +
Expand Down
4 changes: 2 additions & 2 deletions lib/src/legacy/importer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -216,8 +216,8 @@ export class LegacyImporterWrapper<sync extends 'sync' | 'async'>
const syntax = canonicalUrl.pathname.endsWith('.sass')
? 'indented'
: canonicalUrl.pathname.endsWith('.css')
? 'css'
: 'scss';
? 'css'
: 'scss';

let contents =
this.lastContents ??
Expand Down
6 changes: 3 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
{
"name": "sass-embedded",
"version": "1.72.0",
"protocol-version": "2.5.0",
"compiler-version": "1.72.0",
"version": "1.74.0",
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You don't need to update the version and compiler-version here manually, it's done as part of the release process.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah. I got the error for the protocol version and just updated all of them. Fixed.

"protocol-version": "2.6.0",
"compiler-version": "1.74.0",
"description": "Node.js library that communicates with Embedded Dart Sass using the Embedded Sass protocol",
"repository": "sass/embedded-host-node",
"author": "Google Inc.",
Expand Down
Loading