Skip to content

Commit

Permalink
wip ~ Deno 2.0
Browse files Browse the repository at this point in the history
  • Loading branch information
rivy committed Oct 13, 2024
1 parent f9b94d1 commit 2f6a0bf
Show file tree
Hide file tree
Showing 20 changed files with 171 additions and 91 deletions.
2 changes: 1 addition & 1 deletion .commitlint.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
/* @prettier */
// note: (dprint) {.dprint.json}.prettier.associations should contain the name of this file

// deno-lint-ignore-file no-node-globals -- allow use of NodeJS global `process` (CommitLint expects NodeJS-flavor JS)
// deno-lint-ignore-file ban-unknown-rule-code ban-unused-ignore no-node-globals no-process-globals -- allow use of NodeJS global `process` (CommitLint expects NodeJS-flavor JS)

const isNPMTestDist = !!process.env.npm_config_test_dist;
const isTestDist = !!process.env.test_dist;
Expand Down
13 changes: 7 additions & 6 deletions eg/WanCopy.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
// spell-checker:ignore (names) Deno ; (vars) ARGX LOGLEVEL PATHEXT arr defaultCDNforNPM gmsu ; (utils) dprint dprintrc ; (yargs) nargs positionals

import { DenoVx } from '../src/lib/$deprecated.ts';
import { DenoVx, Deprecated } from '../src/lib/$deprecated.ts';

import {
copy as streamCopy,
Expand Down Expand Up @@ -214,7 +214,8 @@ const argv =
try {
return app.parse($me.args()) as YargsArguments;
} catch (e) {
log.error(e.message);
if (e instanceof Error) log.error(e.message);
else log.error(`ERROR: Unknown error parsing arguments (${String(e)})`);
return;
}
})() || ({} as YargsArguments);
Expand Down Expand Up @@ -462,8 +463,8 @@ Deno.exit(appState.exitValue);
// https://www.digitalocean.com/community/tutorials/how-to-work-with-files-using-streams-in-node-js
// https://github.com/denoland/deno/issues/3756
async function copy(
source: URL | Deno.Reader,
target: URL | Deno.Writer | (URL | Deno.Writer)[],
source: URL | Deprecated.Deno.Reader,
target: URL | Deprecated.Deno.Writer | (URL | Deprecated.Deno.Writer)[],
options?: { bufSize?: number; preventTargetClose?: boolean | boolean[]; protectTarget?: boolean },
) {
const targets = Array.isArray(target) ? target : [target];
Expand Down Expand Up @@ -521,8 +522,8 @@ async function copy(
}

async function _remoteCopyUsingCopy(
src: URL | Deno.Reader,
dst: URL | Deno.Writer,
src: URL | Deprecated.Deno.Reader,
dst: URL | Deprecated.Deno.Writer,
_options?: { bufSize?: number },
) {
const readableStream = await (async () => {
Expand Down
3 changes: 2 additions & 1 deletion eg/args-naive.ts
Original file line number Diff line number Diff line change
Expand Up @@ -189,7 +189,8 @@ const argv = (() => {
try {
return app.parse(optionArgs) as YargsArguments;
} catch (e) {
log.error(e.message);
if (e instanceof Error) log.error(e.message);
else log.error(`ERROR: Unknown error parsing arguments (${String(e)})`);
return;
}
})();
Expand Down
5 changes: 3 additions & 2 deletions eg/args.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ abortIfMissingPermitsSync(
([] as Deno.PermissionName[]).concat(
['env'], // required shim/process argument expansion and environmental controls (eg, using DEBUG, LOG_LEVEL, NO_COLOR, NO_UNICODE, NULLGLOB, ...)
['read'], // required for shim targeting of argument expansion and 'yargs'
['run'], // (optional) required for consoleSize fallback when stdin and stderr are both redirected
// ['run'], // (optional) required for consoleSize fallback when stdin and stderr are both redirected
),
);

Expand Down Expand Up @@ -213,7 +213,8 @@ const argv = (() => {
try {
return app.parse(optionArgs) as YargsArguments;
} catch (e) {
log.error(e.message);
if (e instanceof Error) log.error(e.message);
else log.error(`ERROR: Unknown error parsing arguments (${String(e)})`);
appExitValue = 1;
return;
}
Expand Down
3 changes: 2 additions & 1 deletion eg/distribute.ts
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,8 @@ const argv = (() => {
try {
return app.parse(bakedArgs) as YargsArguments;
} catch (e) {
log.error(e.message);
if (e instanceof Error) log.error(e.message);
else log.error(`ERROR: Unknown error parsing arguments (${String(e)})`);
return;
}
})();
Expand Down
3 changes: 2 additions & 1 deletion eg/yargs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,8 @@ const argv = (() => {
try {
return app.parse(Deno.args) as YargsArguments;
} catch (e) {
console.warn(e.message);
if (e instanceof Error) console.warn(e.message);
else console.warn(`ERROR: Unknown error parsing arguments (${String(e)})`);
return;
}
})();
Expand Down
5 changes: 3 additions & 2 deletions src/dxf.ts
Original file line number Diff line number Diff line change
Expand Up @@ -203,7 +203,8 @@ const argv = (() => {
try {
return app.parse(optionArgs) as YargsArguments;
} catch (e) {
log.error(e.message);
if (e instanceof Error) log.error(e.message);
else log.error(`ERROR: Unknown error parsing arguments (${String(e)})`);
return;
}
})();
Expand Down Expand Up @@ -300,7 +301,7 @@ const haveDprintConfig = dprintConfigPath.length > 0;

await log.trace({ denoVersion, dprintVersion });

const runOptions: Partial<{ [key in 'deno' | 'dprint']: Deno.RunOptions }> = {};
const runOptions: Partial<{ [key in 'deno' | 'dprint']: Deprecated.Deno.RunOptions }> = {};

runOptions['deno'] = {
cmd: ['deno', 'fmt'].concat(
Expand Down
5 changes: 3 additions & 2 deletions src/dxi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -198,7 +198,8 @@ const argv = (() => {
try {
return app.parse(optionArgs) as YargsArguments;
} catch (e) {
log.error(e.message);
if (e instanceof Error) log.error(e.message);
else log.error(`ERROR: Unknown error parsing arguments (${String(e)})`);
return;
}
})();
Expand Down Expand Up @@ -462,7 +463,7 @@ await log.trace({
// │ 100 457k 100 457k 0 0 475k 0 --:--:-- --:--:-- --:--:-- 8435k
// └─ Done in 9s

const runOptions: Deno.RunOptions = {
const runOptions: Deprecated.Deno.RunOptions = {
cmd: ['deno', ...denoArgs, '--', ...args],
stdin: 'null',
stderr: 'piped',
Expand Down
10 changes: 6 additions & 4 deletions src/dxr.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,9 +69,10 @@ await abortIfMissingPermitsSync(
([] as Deno.PermissionName[]).concat(
['env'], // required shim/process argument expansion and environmental controls (eg, using DEBUG, LOG_LEVEL, NO_COLOR, NO_UNICODE, NULLGLOB, ...)
['read'], // required for shim targeting of argument expansion and 'yargs'
['run'], // (optional) required for consoleSize fallback when stdin and stderr are both redirected
// ['run'], // (optional) required for consoleSize fallback when stdin and stderr are both redirected
// * script specific requirements
['run'], // required to run `deno` (to execute the target SCRIPT)
// FixME: add query params support to `abortIfMissingPermits...()`
// ['run'], // required to run `deno` (to execute the target SCRIPT)
),
);

Expand Down Expand Up @@ -201,7 +202,8 @@ const argv = (() => {
try {
return app.parse(optionArgs) as YargsArguments;
} catch (e) {
log.error(e.message);
if (e instanceof Error) log.error(e.message);
else log.error(`ERROR: Unknown error parsing arguments (${String(e)})`);
return;
}
})();
Expand Down Expand Up @@ -325,7 +327,7 @@ if (SHIM_ARGS.length > max_shim_args_size) {
);
Deno.exit(1);
}
const runOptions: Deno.RunOptions = {
const runOptions: Deprecated.Deno.RunOptions = {
// note: `Deno.run` automatically quotes any `cmd` elements which contain spaces
cmd: ['deno', ...denoArgs, targetPath, ...targetArgs],
stderr: 'inherit',
Expand Down
32 changes: 26 additions & 6 deletions src/lib/$deprecated.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,13 +33,13 @@ export function isDenoV1RID(id: unknown): id is DenoV1NS.RID {
return typeof id === 'number';
}

function hasIsTerminalMethod(id: unknown): id is { isTerminal: () => boolean } {
function hasIsTerminalMethod(x: unknown): x is { isTerminal: () => boolean } {
return (
typeof id === 'object' &&
id != null &&
'isTerminal' in id &&
typeof id?.isTerminal === 'function' &&
typeof id.isTerminal() === 'boolean'
typeof x === 'object' &&
x != null &&
'isTerminal' in x &&
typeof x?.isTerminal === 'function' &&
typeof x.isTerminal() === 'boolean'
);
}

Expand Down Expand Up @@ -106,16 +106,36 @@ export const DenoVx = {
},
};

// FixME: [2024-09-25; rivy] -- import { Deno as denoV1 } from 'https://github.com/denoland/deno/blob/e27a19c02c537626d7874f7521f4e39d6dfad0af/cli/tsc/dts/lib.deno.unstable.d.ts';
// import * as denoV1T from 'https://cdn.jsdelivr.net/gh/denoland/deno@e27a19c02c537626d7874f7521f4e39d6dfad0af/cli/tsc/dts/lib.deno.unstable.d.ts';
// import _denoV1 = denoV1T.Deno;
// import * as BracesT from 'https://cdn.jsdelivr.net/gh/DefinitelyTyped/DefinitelyTyped@7121cbff79/types/braces/index.d.ts';

import type { Reader as DenoReader } from 'jsr:@std/io/types';
import type { Writer as DenoWriter } from 'jsr:@std/io/types';
import type { WriterSync as DenoWriterSync } from 'jsr:@std/io/types';

export namespace Deprecated {
export namespace Deno {
// deprecated since: ...
// use instead: ...
// remove with: Deno v2.0.0

// @ts-ignore -- `rid` properties are "soft-removed" in Deno v2
export const stderr = { rid: globalThis.Deno.stderr.rid };
// @ts-ignore -- `rid` properties are "soft-removed" in Deno v2
export const stdin = { rid: globalThis.Deno.stdin.rid };
// @ts-ignore -- `rid` properties are "soft-removed" in Deno v2
export const stdout = { rid: globalThis.Deno.stdout.rid };

// @ts-ignore -- `run` is "soft-removed" in Deno v2
export const run = DenoV1?.run ?? globalThis.Deno.run;
export type RunOptions = DenoV1NS.Deno.RunOptions;
export type ProcessStatus = DenoV1NS.Deno.ProcessStatus;

export type Reader = DenoReader;
export type Writer = DenoWriter;
export type WriterSync = DenoWriterSync;
}
}

Expand Down
17 changes: 14 additions & 3 deletions src/lib/$shared.TLA.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,17 @@
// ... discussions related to TLA issues can be found at <https://github.com/denoland/deno/discussions/15356> , <https://github.com/denoland/deno_std/issues/2446> , <https://github.com/denoland/deno/issues/13730>
// ... see <https://github.com/denoland/deno/issues/13730#issuecomment-1207325451> for notes about less rigorous module load/execution order

const isDenoPreV2 = Deno.version.deno.split('.').map(Number)[0] < 2;
const DenoPermissionNames: Deno.PermissionName[] = [
'env',
'ffi',
'net',
'read',
'run',
'write',
isDenoPreV2 ? 'hrtime' : undefined,
].filter((e) => e != null) as Deno.PermissionName[];

//===

export const atImportPermissions = await permitsAsync();
Expand All @@ -16,9 +27,9 @@ function zip<T extends string | number | symbol, U>(a: T[], b: U[]) {
return c;
}

export async function permitsAsync(
names: Deno.PermissionName[] = ['env', 'ffi', 'hrtime', 'net', 'read', 'run', 'write'],
) {
export async function permitsAsync(names?: Deno.PermissionName[] | null | undefined) {
names = names ?? DenoPermissionNames;
if (names?.length === 0) return {} as Record<Deno.PermissionName, Deno.PermissionStatus>;
const permits: Record<Deno.PermissionName, Deno.PermissionStatus> = zip(
names,
(await Promise.all(names.map((name) => Deno.permissions?.query({ name })))).map(
Expand Down
43 changes: 27 additions & 16 deletions src/lib/$shared.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,20 +54,20 @@ export const encode = (input?: string): Uint8Array => encoder.encode(input);
//=== * stack inspection functions

function getFramesFromError(error: Error): Array<string> {
let stack: Error['stack'] | null;
let stack: Error['stack'] | null = null;
let frames: string[];
// retrieve stack from `Error`
// ref: <https://github.com/winstonjs/winston/issues/401#issuecomment-61913086>
try {
stack = error.stack;
} catch (e) {
try {
const previous = e.__previous__ || e.__previous;
stack = previous && previous.stack;
} catch (_) {
stack = null;
}
}
// // retrieve stack from `Error`
// // ref: <https://github.com/winstonjs/winston/issues/401#issuecomment-61913086>
// try {
stack = error.stack;
// } catch (e) {
// try {
// const previous = e?.__previous__ || e?.__previous;
// stack = previous && previous.stack;
// } catch (_) {
// stack = null;
// }
// }

// handle different stack formats
if (stack) {
Expand Down Expand Up @@ -110,9 +110,20 @@ function zip<T extends string | number | symbol, U>(a: T[], b: U[]) {
return c;
}

export function permitsSync(
names: Deno.PermissionName[] = ['env', 'ffi', 'hrtime', 'net', 'read', 'run', 'write'],
) {
const isDenoPreV2 = Deno.version.deno.split('.').map(Number)[0] < 2;
const DenoPermissionNames: Deno.PermissionName[] = [
'env',
'ffi',
'net',
'read',
'run',
'write',
isDenoPreV2 ? 'hrtime' : undefined,
].filter((e) => e != null) as Deno.PermissionName[];

// FixME: [2024-09-25; rivy] revise permits functions to allow for optional configuration parameters for each permission

export function permitsSync(names: Deno.PermissionName[] = DenoPermissionNames) {
const permits: Record<Deno.PermissionName, Deno.PermissionStatus> = zip(
names,
names
Expand Down
6 changes: 4 additions & 2 deletions src/lib/axe/$mod.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,9 @@ export function env(varName: string, options?: { guard: boolean }) {

//===

async function writeAll(writer: Deno.Writer, data: Uint8Array): Promise<number> {
import type { Writer as DenoWriter } from 'jsr:@std/io/types';

async function writeAll(writer: DenoWriter, data: Uint8Array): Promise<number> {
let bytesWritten = 0;
while (bytesWritten < data.byteLength) {
bytesWritten += await writer.write(data.subarray(bytesWritten));
Expand Down Expand Up @@ -636,7 +638,7 @@ export class Logger<O = LogEntry> extends TransformWriter<LoggerInT, O> {
await this.#suspensionQueue.onIdle();
}

/** @override */ chain<T>(t: TransformWriter<O, T>): Logger<T> {
/** @override */ override chain<T>(t: TransformWriter<O, T>): Logger<T> {
// deno-lint-ignore no-this-alias
const f = this;
const g = t;
Expand Down
24 changes: 14 additions & 10 deletions src/lib/commandLine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,9 @@ function WStringToString(arr?: WString) {

const isWinOS = Deno.build.os === 'windows';

const atImportAllowFFI =
((await Deno.permissions?.query({ name: 'ffi' }))?.state ?? 'granted') === 'granted';

const unstable = (() => {
const u = {
dlopen: Deno.dlopen, // unstable API (as of v1.12+)
Expand All @@ -40,16 +43,17 @@ const _fns: /* Record<string, Deno.ForeignFunction> */ Deno.ForeignLibraryInterf
GetCommandLineA: { parameters: [], result: 'pointer' },
GetCommandLineW: { parameters: [], result: 'pointer' },
};
const dll = isWinOS
? unstable?.dlopen(
'kernel32.dll',
/* fns */
{
GetCommandLineA: { parameters: [], result: 'pointer' },
GetCommandLineW: { parameters: [], result: 'pointer' },
},
)
: undefined;
const dll =
isWinOS && atImportAllowFFI
? unstable?.dlopen(
'kernel32.dll',
/* fns */
{
GetCommandLineA: { parameters: [], result: 'pointer' },
GetCommandLineW: { parameters: [], result: 'pointer' },
},
)
: undefined;

//===

Expand Down
Loading

0 comments on commit 2f6a0bf

Please sign in to comment.