You're Invited: Meet the Socket team at BSidesSF and RSAC - April 27 - May 1.RSVP
Socket
Sign inDemoInstall
Socket

adastra-plugin

Package Overview
Dependencies
Maintainers
1
Versions
8
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

adastra-plugin - npm Package Compare versions

Comparing version

to
0.3.0

dist/dev-index.html

3

dist/index.d.ts

@@ -7,4 +7,3 @@ import { Plugin } from 'vite';

entrypointsDir?: string;
hash?: boolean;
minify?: boolean;
snippetName?: string;
}

@@ -11,0 +10,0 @@

@@ -1,14 +0,145 @@

import H from"path";var R=t=>{let s=t.root??"./",r=t.sourceDir??"src",e=H.join(r,t.entrypointsDir??"entrypoints"),i=t.hash??!1,o=t.minify??!0;return{root:s,sourceDir:r,entrypointsDir:e,hash:i,minify:o}};import d from"path";import M from"fast-glob";import U from"debug";import{mergeConfig as W,normalizePath as B}from"vite";var J=U("adastra-plugin:config"),A=t=>({name:"adastra-plugin-config",config(s){let r=s.server?.host??"localhost",e=s.server?.port??5173,i=s.server?.https,f=`${i===!0?"https:":"http:"}//${r}:${e}`,n=i===!0?"wss":"ws",a=M.sync(B(d.join(t.entrypointsDir,"**/*")),{onlyFiles:!0}),g={base:"./",envPrefix:["VITE_","PUBLIC_","ADASTRA_"],publicDir:!1,build:{outDir:d.join(t.root,"assets"),modulePreload:{polyfill:!0},assetsDir:"",rollupOptions:{input:a,output:{chunkFileNames:`[name]${t.hash?".[hash]":""}.js`,entryFileNames:c=>`${c.name.replace("entry.","")}${t.hash?".[hash]":""}.js`,assetFileNames:`[name]${t.hash?".[hash]":""}.[ext]`}},manifest:"adastra.manifest.json",minify:t.minify},resolve:{alias:{"~":d.resolve(t.sourceDir),"@":d.resolve(t.sourceDir)}},server:{host:r,https:i,port:e,origin:f,strictPort:!0,hmr:{host:r,port:e,protocol:n},watch:{ignored:["assets/*","snippets/adastra.liquid"]}}};return J(g),W(g,s)}});import T from"fs";import x from"path";import V from"debug";import{normalizePath as Q}from"vite";import*as b from"vite";var K=b.version.startsWith("3.");var P=["css","less","sass","scss","styl","stylus","pcss","postcss"],D=["jsx","tsx"],j=new RegExp(`\\.(${P.join("|")})(\\?.+)?$`),$="@vite/client",w="@react-refresh";import z from"path";import{normalizePath as G}from"vite";var m=`{% # theme-check-disable %}
`,u=`{% comment %}
IMPORTANT: This snippet is automatically generated by Adastra.
Do not attempt to modify this file directly, as any changes will be overwritten by the next build.
{% endcomment %}
`,h=(t,s)=>{let r=[];return t.forEach(e=>{typeof e.find=="string"&&r.push([e.find,G(z.relative(s,e.replacement))])}),`{% assign path = adastra | ${r.map(([e,i])=>`replace: '${e}/', '${i}/'`).join(" | ")} %}
`},y=(t,s,r=!1)=>`{% ${r?"":"els"}if ${t.map(e=>`path == "${e}"`).join(" or ")} %}
${s}`,_=t=>`<link rel="modulepreload" href="{{ '${t}' | asset_url | split: '?' | first }}" crossorigin="anonymous">`,O=t=>`<script src="{{ '${t}' | asset_url | split: '?' | first }}" type="module" crossorigin="anonymous"></script>`,l=t=>`{{ '${t}' | asset_url | split: '?' | first | stylesheet_tag: preload: preload }}`,C=(t,s)=>`{% liquid
// src/options.ts
import path from "path";
var resolveOptions = (options) => {
const root = options.root ?? "./";
const sourceDir = options.sourceDir ?? "src";
const entrypointsDir = path.join(
sourceDir,
options.entrypointsDir ?? "entrypoints"
);
const snippetName = options.snippetName ?? "adastra";
return {
root,
sourceDir,
entrypointsDir,
snippetName
};
};
// src/plugins/vite-plugin-adastra-config.ts
import path2 from "path";
import glob from "fast-glob";
import createDebugger from "debug";
import { mergeConfig, normalizePath } from "vite";
var debug = createDebugger(`adastra-plugin:config`);
var vite_plugin_adastra_config_default = (options) => {
return {
name: `adastra-plugin-config`,
config(config) {
const host = config.server?.host ?? "localhost";
const port = config.server?.port ?? 5173;
const https = config.server?.https;
const protocol = https === true ? "https:" : "http:";
const origin = `${protocol}//${host}:${port}`;
const socketProtocol = https === true ? "wss" : "ws";
const input = glob.sync(
normalizePath(path2.join(options.entrypointsDir, "**/*")),
{ onlyFiles: true }
);
const generatedConfig = {
// Use relative base path so to load imported assets from Shopify CDN
base: "./",
envPrefix: ["VITE_", "PUBLIC_", "ADASTRA_"],
publicDir: false,
build: {
// Output files to "assets" directory
outDir: path2.join(options.root, "assets"),
modulePreload: {
polyfill: true
},
// Do not use subfolder for static assets
assetsDir: "",
// Configure bundle entry points
rollupOptions: {
input
},
// Output manifest file for backend integration
manifest: `adastra.manifest.json`
},
resolve: {
// Provide import alias to source code dir for convenience
alias: {
"~": path2.resolve(options.sourceDir),
"@": path2.resolve(options.sourceDir)
}
},
server: {
host,
https,
port,
origin,
strictPort: true,
hmr: {
host,
port,
protocol: socketProtocol
},
watch: {
ignored: ["assets/*", `snippets/${options.snippetName}.liquid`]
}
}
};
debug(generatedConfig);
return mergeConfig(generatedConfig, config);
}
};
};
// src/plugins/vite-plugin-adastra-liquid.ts
import fs from "fs";
import path4 from "path";
import createDebugger2 from "debug";
import { normalizePath as normalizePath3 } from "vite";
// src/utilities/vite.ts
import * as vite from "vite";
var isViteThree = vite.version.startsWith("3.");
// src/constants.ts
var KNOWN_CSS_EXTENSIONS = [
"css",
"less",
"sass",
"scss",
"styl",
"stylus",
"pcss",
"postcss"
];
var KNOWN_JSX_EXTENSIONS = ["jsx", "tsx"];
var CSS_EXTENSIONS_REGEX = new RegExp(
`\\.(${KNOWN_CSS_EXTENSIONS.join("|")})(\\?.+)?$`
);
var CLIENT_SCRIPT_PATH = "@vite/client";
var CLIENT_REACT_REFRESH_PATH = "@react-refresh";
// src/utilities/liquid.ts
import path3 from "path";
import { normalizePath as normalizePath2 } from "vite";
var disableThemeCheckTag = "{% # theme-check-disable %}\n";
var adastraTagDisclaimer = "{% comment %}\n IMPORTANT: This snippet is automatically generated by Vite.\n Do not attempt to modify this file directly, as any changes will be overwritten by the next build.\n{% endcomment %}\n";
var adastraTagEntryPath = (resolveAlias, entrypointsDir, snippetName) => {
const replacements = [];
resolveAlias.forEach((alias) => {
if (typeof alias.find === "string") {
replacements.push([
alias.find,
normalizePath2(path3.relative(entrypointsDir, alias.replacement))
]);
}
});
return `{% assign path = ${snippetName} | ${replacements.map(([from, to]) => `replace: '${from}/', '${to}/'`).join(" | ")} %}
`;
};
var adastraEntryTag = (entryPaths, tag, isFirstEntry = false) => `{% ${!isFirstEntry ? "els" : ""}if ${entryPaths.map((entryName) => `path == "${entryName}"`).join(" or ")} %}
${tag}`;
var preloadScriptTag = (fileName) => `<link rel="modulepreload" href="{{ '${fileName}' | asset_url | split: '?' | first }}" crossorigin="anonymous">`;
var scriptTag = (fileName) => `<script src="{{ '${fileName}' | asset_url | split: '?' | first }}" type="module" crossorigin="anonymous"></script>`;
var stylesheetTag = (fileName) => `{{ '${fileName}' | asset_url | split: '?' | first | stylesheet_tag: preload: preload }}`;
var adastraTagSnippetDev = (assetHost, entrypointsDir) => `{% liquid
assign path_prefix = path | slice: 0
if path_prefix == '/'
assign file_url_prefix = '${t}'
assign file_url_prefix = '${assetHost}'
else
assign file_url_prefix = '${t}/${s}/'
assign file_url_prefix = '${assetHost}/${entrypointsDir}/'
endif

@@ -22,4 +153,4 @@

assign css_extensions = '${P.join("|")}' | split: '|'
assign jsx_extensions = '${D.join("|")}' | split: '|'
assign css_extensions = '${KNOWN_CSS_EXTENSIONS.join("|")}' | split: '|'
assign jsx_extensions = '${KNOWN_JSX_EXTENSIONS.join("|")}' | split: '|'
assign is_css = false

@@ -43,3 +174,3 @@ assign is_jsx = false

<script type="module">
import RefreshRuntime from "${t}/${w}"
import RefreshRuntime from "${assetHost}/${CLIENT_REACT_REFRESH_PATH}"
RefreshRuntime.injectIntoGlobalHook(window)

@@ -52,3 +183,3 @@ window.$RefreshReg$ = () => {}

<script src="${t}/${$}" type="module"></script>
<script src="${assetHost}/${CLIENT_SCRIPT_PATH}" type="module"></script>

@@ -60,6 +191,122 @@ {% if is_css %}

{% endif %}
`;var Y=V("adastra-plugin:liquid"),I=t=>{let s,r=x.resolve(t.root,"snippets/adastra.liquid");return{name:"adastra-plugin-liquid",enforce:"post",configResolved(e){s=e},configureServer({config:e}){let i=e.server?.https===!0?"https:":"http:",o=typeof e.server?.host=="string"?e.server.host:"localhost",f=typeof e.server?.port<"u"?e.server.port:5173,n=typeof e.server?.origin=="string"?e.server.origin:`${i}//${o}:${f}`;Y({assetHost:n});let a=m+u+h(e.resolve.alias,t.entrypointsDir)+C(n,t.entrypointsDir);T.writeFileSync(r,a)},closeBundle(){let e=x.resolve(t.root,"assets/adastra.manifest.json");if(!T.existsSync(e))return;let i=[],o=JSON.parse(T.readFileSync(e,"utf8"));Object.keys(o).forEach(n=>{let{file:a,isEntry:g,css:c,imports:E}=o[n],F=x.extname(n);if(g===!0){let X=Q(x.relative(t.entrypointsDir,n)),L=[`/${n}`,X],p=[];F.match(j)!==null?p.push(l(a)):(p.push(_(a)),p.push(O(a)),typeof c<"u"&&c.length>0&&c.forEach(S=>{p.push(l(S))}),typeof E<"u"&&E.length>0&&E.forEach(S=>{let N=o[S],{css:v}=N;p.push(_(N.file)),typeof v<"u"&&v.length>0&&v.forEach(q=>{p.push(l(q))})})),i.push(y(L,p.join(`
`),i.length===0))}n==="style.css"&&!s.build.cssCodeSplit&&i.push(y([n],l(a),!1))});let f=m+u+h(s.resolve.alias,t.entrypointsDir)+i.join(`
`)+`
{% endif %}
`;T.writeFileSync(r,f)}}};var Z={},k=Z;var qt=(t=k)=>{let s=R(t);return[A(s),I(s)]};export{qt as default};
`;
// src/plugins/vite-plugin-adastra-liquid.ts
var debug2 = createDebugger2(`adastra-plugin:liquid`);
var vite_plugin_adastra_liquid_default = (options) => {
let config;
const adastraSnippetPath = path4.resolve(
options.root,
`snippets/${options.snippetName}.liquid`
);
return {
name: `adastra-plugin-liquid`,
enforce: "post",
configResolved(resolvedConfig) {
config = resolvedConfig;
},
configureServer({ config: config2, middlewares }) {
const protocol = config2.server?.https === true ? "https:" : "http:";
const host = typeof config2.server?.host === "string" ? config2.server.host : "localhost";
const port = typeof config2.server?.port !== "undefined" ? config2.server.port : 5173;
const assetHost = typeof config2.server?.origin === "string" ? config2.server.origin : `${protocol}//${host}:${port}`;
debug2({ assetHost });
const adastraTagSnippetContent = disableThemeCheckTag + adastraTagDisclaimer + adastraTagEntryPath(
config2.resolve.alias,
options.entrypointsDir,
options.snippetName
) + adastraTagSnippetDev(assetHost, options.entrypointsDir);
fs.writeFileSync(adastraSnippetPath, adastraTagSnippetContent);
return () => middlewares.use((req, res, next) => {
if (req.url === "/index.html") {
res.statusCode = 404;
res.end(
fs.readFileSync(path4.join(__dirname, "dev-index.html")).toString()
);
}
next();
});
},
closeBundle() {
const manifestFilePath = path4.resolve(
options.root,
`assets/adastra.manifest.json`
);
if (!fs.existsSync(manifestFilePath)) {
return;
}
const assetTags = [];
const manifest = JSON.parse(
fs.readFileSync(manifestFilePath, "utf8")
);
Object.keys(manifest).forEach((src) => {
const { file, isEntry, css, imports } = manifest[src];
const ext = path4.extname(src);
if (isEntry === true) {
const entryName = normalizePath3(
path4.relative(options.entrypointsDir, src)
);
const entryPaths = [`/${src}`, entryName];
const tagsForEntry = [];
if (ext.match(CSS_EXTENSIONS_REGEX) !== null) {
tagsForEntry.push(stylesheetTag(file));
} else {
tagsForEntry.push(preloadScriptTag(file));
tagsForEntry.push(scriptTag(file));
if (typeof css !== "undefined" && css.length > 0) {
css.forEach((cssFileName) => {
tagsForEntry.push(stylesheetTag(cssFileName));
});
}
if (typeof imports !== "undefined" && imports.length > 0) {
imports.forEach((importFilename) => {
const chunk = manifest[importFilename];
const { css: css2 } = chunk;
tagsForEntry.push(preloadScriptTag(chunk.file));
if (typeof css2 !== "undefined" && css2.length > 0) {
css2.forEach((cssFileName) => {
tagsForEntry.push(stylesheetTag(cssFileName));
});
}
});
}
}
assetTags.push(
adastraEntryTag(
entryPaths,
tagsForEntry.join("\n "),
assetTags.length === 0
)
);
}
if (src === "style.css" && !config.build.cssCodeSplit) {
assetTags.push(adastraEntryTag([src], stylesheetTag(file), false));
}
});
const adastraTagSnippetContent = disableThemeCheckTag + adastraTagDisclaimer + adastraTagEntryPath(
config.resolve.alias,
options.entrypointsDir,
options.snippetName
) + assetTags.join("\n") + "\n{% endif %}\n";
fs.writeFileSync(adastraSnippetPath, adastraTagSnippetContent);
}
};
};
// src/utilities/empty-adastra-config.ts
var AdastraConfig = {};
var empty_adastra_config_default = AdastraConfig;
// src/index.ts
var src_default = (options = empty_adastra_config_default) => {
const resolvedOptions = resolveOptions(options);
return [
// Apply plugin for configuring Vite settings and options
vite_plugin_adastra_config_default(resolvedOptions),
// Apply plugin for generating Vite and liquid asset tags through adastra.liquid snippet
vite_plugin_adastra_liquid_default(resolvedOptions)
];
};
export {
src_default as default
};
{
"name": "adastra-plugin",
"version": "0.2.1",
"version": "0.3.0",
"author": "Blanklob",

@@ -16,3 +16,3 @@ "license": "MIT",

"fast-glob": "^3.2.11",
"adastra-branding": "0.1.1"
"adastra-branding": "0.1.2"
},

@@ -23,3 +23,3 @@ "devDependencies": {

"adastra-tsconfig": "0.1.0",
"eslint-config-adastra": "0.1.1"
"eslint-config-adastra": "0.1.2"
},

@@ -41,7 +41,7 @@ "peerDependencies": {

"dev": "npm run build -- --watch",
"build": "tsup src/index.ts --format cjs,esm --dts --minify",
"watch": "tsup src/index.ts --format cjs,esm --dts --watch",
"build": "tsup src/index.ts --format cjs,esm --dts --clean --publicDir",
"watch": "tsup src/index.ts --format cjs,esm --dts --watch --publicDir",
"lint": "eslint .",
"lint:fix": "eslint . --fix",
"lint:types": "tsc --noEmit",
"typecheck": "tsc --noEmit",
"test": "vitest run",

@@ -48,0 +48,0 @@ "test:watch": "vitest",

@@ -1,1 +0,178 @@

# `adastra-plugin`
# adastra-plugin
Adastra ✨ plugin is package that aims to integrate [Vite](https://vitejs.dev) as seamlessly as possible with Shopify themes to optimize your theme development experience.
## Requirements
Please make sure you have Node.js >=16 and NPM are installed before running Vite:
- NodeJS >= 16 ([Install NodeJS LTS](https://nodejs.org/))
- Make sure you also have ([Shopify CLI for themes](https://shopify.dev/docs/themes/tools/cli/install)) to launch the Shopify theme development server.
## Installation
1. Run the following command to initialize a Node project inside the root of your theme's directory:
```bash
npm init -y
```
2. Next, install Vite and the Adastra ✨ plugin.
```bash
npm install -D vite adastra-plugin
# Using Yarn/PNPM
yarn add --dev vite adastra-plugin
# pnpm add -D vite adastra-plugin
```
Finally, adjust your `package.json` by adding the following scripts:
```json
"description": "",
"scripts": {
- "test": "echo \"Error: no test specified\" && exit 1",
"dev": "vite",
"build": "vite build",
"dev:shopify": "shopify theme dev"
},
```
## Usage
Create a `vite.config.{js,ts}` file in your theme root directory and add the `adastra-plugin`. You are free to customize this file based on your needs, check Vite's [plugins](https://vitejs.dev/plugins/) and [config reference](https://vitejs.dev/config/) for more info.
```js
import { defineConfig } from 'vite'
import adastra from 'adastra-plugin'
export default defineConfig({
plugins: [
adastra({
// Root path to your Shopify theme directory (location of snippets, sections, templates, etc.)
root: './',
// Frontend source code directory
sourceDir: 'src',
// Frontend entry points directory
entrypointsDir: 'src/entrypoints',
// The name of the genarated snippet adastra.liquid snippet.
snippetName: 'adastra'
})
]
})
```
The Adastra ✨ Vite Plugin does not require you to specify the entrypoints for your theme. By default, it treats JavaScript and CSS files (including preprocessed
languages such as TypeScript, JSX, TSX, and Sass) within the `src/entrypoints` folder in the root of your project as entry points for Vite.
```bash
/
└── src/
└── entrypoints/
├── base.scss
├── customer.css
└── theme.js
```
Your final theme project structure should look like something like this:
```shell
/
├── assets
├── config
├── layout
├── locales
├── sections
├── snippets/
├── src/ # Source directory (name can be changed in vite.config.js)
│ └── entrypoints/ # Entrypoints directory (name can be changed in vite.config.js)
│ ├── base.scss
│ ├── customer.css
│ └── theme.js
├── templates
├── vite.config.js
└── package.json
```
If you use Typescript make sure you setup and `tsconfig.json` file in the root of the project, check out an example [here](https://github.com/blanklob/adastra/blob/main/packages/tsconfig/theme.json).
## How it works?
Adastra plugin ✨ detects entrypoint files automatically in the `entrypoints/` directory. In this case `base.scss` and `customer.css` for styles and `theme.js` for scripts/modules.
So everything you import to these three files will be shipped to the theme `assets` folder when building for production.
You can create other folders like `src/utils/` if you want, or a `src/components/` folder for Native/React/Vue/Lit/Preact components. Only the files/modules imported in the entrypoint files will be served by Vite.
Any static assets, like custom fonts, manifest files, `.css.liquid` or `.js.liquid`, can be placed inside the `assets` theme folder, just make sure to add the configuration below to avoid clearing the assets directory when building for production.
```js
// vite.config.js
import { defineConfig } from 'vite'
import adastra from 'adastra-plugin'
export default defineConfig({
plugins: [adastra()],
build: {
emptyOutDir: false
}
})
```
### loading modules and styles to your theme
Adastra Vite Plugin generates an `adastra.liquid` snippet which includes `<script>` and `<link>` tags, and all the liquid logic needed to load your static assets.
With your Vite entry points configured, you only need to reference them with the `adastra` snippet that you add to the `<head>` of your theme's layout:
```liquid
{% liquid
# Relative to entrypointsDir
render 'adastra with 'base.scss'
render 'adastra with 'theme.js'
if request.page_type contains 'customers/'
render 'adastra' with 'customers.css'
endif
%}
```
During development, the `adastra` will load your assets from the Vite development server and inject the Vite client to enable Hot Module Replacement.
In build mode, the snippet will load your compiled and versioned assets, including any imported CSS, and use the `asset_url` filter to serve your assets
from the Shopify content delivery network (CDN).
#### Preloading stylesheets
You can pass the `preload` variable to the `adastra` snippet to enable the `preload` parameter of the `stylesheet_tag` filter. Use it sparingly. For example, consider preloading only render-blocking stylesheets.
[Learn more](https://shopify.dev/themes/best-practices/performance#use-resource-hints-to-preload-key-resources).
```liquid
{% render 'adastra' with 'base.scss', preload: true %}
```
### Import aliases
For convenience, `~/` and `@/` are aliased to your `src` folder, which simplifies imports:
```js
import ProductForm from '@/components/ProductForm.vue'
import Quiz from '@/components/Quiz.jsx'
import '@/styles/utils.css'
```
## Advanced Customization
Out of the box, the Shopify Vite Plugin uses sensible conventions to help you add Vite with zero configuration to existing Shopify themes; however, sometimes you may need to customize the Plugin's behavior.
Every configuration option is described in the [Configuration Reference](https://shopify-vite.barrelny.com/guide/configuration.html).
## Special Thanks
This plugin was inspired by [Shopify Vite Plugin](https://shopify-vite.barrelny.com) made by the amazing team at Barrel.
## Want to learn more?
Feel free to check [our documentation](https://docs.blanklob.com) or jump into our [Discord server](https://help.blanklob.com).

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet